fix testings User

parent 696a6110
<?php
namespace common\modules\testings\controllers;
use Yii;
use common\components\AdminController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\modules\testings\components\MarkBoxBehavior;
use common\modules\testings\models\User;
use common\modules\testings\models\SearchUser;
use common\modules\testings\models\SearchUserGroup;
class UserAdminController extends AdminController
{
public static function actionsTitles()
{
return array(
'View' => 'Просмотр пользователя',
'Create' => 'Создание пользователя',
'Update' => 'Редактирование пользователя',
'Delete' => 'Удаление пользователя',
'Manage' => 'Управление пользователями',
'Manage-group' => 'Управление группами',
'Update-mark' => 'Пометка пользователй',
'Reset-mark' => 'Сброс пометок',
);
}
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
'marked' => [
'class' => MarkBoxBehavior::className(),
'session_key' => 'user-admin',
]
];
}
public function actions()
{
return [
'update-mark' => [
'class' => \common\modules\testings\components\MarkBoxAction::className(),
]
];
}
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
public function actionCreate()
{
$model = new User;
Yii::$app->controller->page_title = 'Добавить пользователя';
Yii::$app->controller->breadcrumbs = [
['Список пользователей' => '/testings/user-admin/manage'],
'Добавить пользователя'
];
if ($model->load(Yii::$app->request->post()))
{
$model->manager_id = Yii::app()->user->id;
if($model->validate())
{
$model->login = $model->generateLogin();
$model->password = PasswordGenerator::generate(6);
$model->save();
return $this->redirect(['manage']);
}
}
$form = new \common\components\BaseForm('/common/modules/testings/forms/UserForm', $model);
return $this->render('create', [
'model' => $model,
'form' => $form->out
]);
}
public function actionUpdate($id)
{
Yii::$app->controller->page_title = 'Редактировать пользователя';
Yii::$app->controller->breadcrumbs = [
['Список пользователей' => '/testings/user-admin/manage'],
'Редактировать пользователя'
];
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()))
{
$model->manager_id = Yii::app()->user->id;
if($model->validate())
{
$model->save();
return $this->redirect(['manage']);
}
}
$form = new \common\components\BaseForm('/common/modules/testings/forms/AnswerForm', $model);
return $this->render('update', [
'model' => $model,
'form' => $form->out
]);
}
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['manage']);
}
public function actionManage()
{
$searchModel = new SearchUser();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
Yii::$app->controller->page_title = 'Список назначений тестов пользователям';
Yii::$app->controller->breadcrumbs = [
'Список назначений тестов пользователям',
];
return $this->render('manage', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
public function actionManageGroup()
{
$searchModel = new SearchUserGroup();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
Yii::$app->controller->page_title = 'Список групп';
Yii::$app->controller->breadcrumbs = [
'Список групп',
];
return $this->render('manage-group', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Finds the Faq model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Faq the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = User::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
<?php
namespace common\modules\testings\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\modules\testings\models\User;
use common\modules\testings\models\UserGroup;
use common\modules\testings\models\SendHistory;
use common\modules\testings\models\Test;
class SearchUser extends User
{
public $filter_group_id;
public $filter_history_status;
public function rules()
{
return [
[['id', 'sex', 'manager_id', 'is_auth', 'filter_group_id'], 'integer'],
[['id', 'sex', 'first_name', 'patronymic', 'last_name', 'company_name', 'email', 'manager_id', 'create_date', 'is_auth', 'filter_history_status', 'filter_group_id'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params, $order = null, $limit = null)
{
$query = User::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => ['pageSize' => self::PAGE_SIZE],
'sort'=>array(
'defaultOrder'=>'t.id DESC',
),
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
'sex' => $this->sex,
'manager_id' => $this->manager_id,
'is_auth' => $this->is_auth,
]);
$query->andFilterWhere(['like', 'first_name', $this->first_name])
->andFilterWhere(['like', 'patronymic', $this->patronymic])
->andFilterWhere(['like', 'last_name', $this->last_name])
->andFilterWhere(['like', 'company_name', $this->company_name])
->andFilterWhere(['like', 'email', $this->email])
->andFilterWhere(['like', 'tki', $this->tki])
->andFilterWhere(['like', 'create_date', $this->create_date]);
$with = ['passings.test'];
$query->groupBy([User::tableName() . '.id']);
if($this->filter_group_id || Yii::$app->request->get('group'))
{
$with[] = 'groupRelated.group';
if($this->filter_group_id)
{
$query->andFilterWhere([
UserGroup::tableName() . '.id' => $this->filter_group_id,
]);
}
if(Yii::$app->request->get('group'))
{
$query->andFilterWhere([
UserGroup::tableName() . '.id' => Yii::$app->request->get('group')
]);
}
}
if($this->filter_history_status)
{
$with[] = 'history';
$query->andFilterWhere([
SendHistory::tableName() . '.unisender_status' => $this->filter_history_status
]);
}
if (Yii::$app->request->get('session'))
{
$query->andFilterWhere([
Test::tableName() . '.session_id' => Yii::$app->request->get('session')
]);
}
$query->joinWith($with);
if(!empty($order))
$query->orderBy($order);
if(!empty($limit))
$query->limit($limit);
return $dataProvider;
}
}
<?php
namespace common\modules\testings\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\modules\testings\models\UserGroup;
class SearchUserGroup extends UserGroup
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id', 'session_id'], 'integer'],
[['id', 'name', 'created', 'session_id'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params, $order = null, $limit = null)
{
$query = UserGroup::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => ['pageSize' => self::PAGE_SIZE],
'sort'=>array(
'defaultOrder'=>'created DESC',
),
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
'name' => $this->name,
'created' => $this->created,
]);
if(Yii::$app->request->get('session'))
{
$query->andFilterWhere([
'session_id' => Yii::$app->request->get('session'),
]);
}
else
{
$query->andFilterWhere([
'session_id' => $this->session_id,
]);
}
if(!empty($order))
$query->orderBy($order);
if(!empty($limit))
$query->limit($limit);
return $dataProvider;
}
}
<?php
namespace common\modules\testings\models;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
use common\modules\testings\models\Passing;
use common\modules\testings\models\UserGroupAssign;
use common\modules\testings\models\SendHistory;
use common\modules\users\models\User as Manager;
class User extends \common\components\ActiveRecordModel
{
const PAGE_SIZE = 10;
const WOMAN = 0;
const MAN = 1;
public static $sex_list = [
self::WOMAN => 'Женский',
self::MAN => 'Мужской',
];
public static function tableName()
{
return 'testings_users';
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'create_date',
'updatedAtAttribute' => null,
'value' => new Expression('NOW()'),
],
];
}
public function name()
{
return 'Пользователи';
}
public function attributeLabels()
{
return [
'company_name' => 'Компания',
'is_auth' => 'sd',
'filter_group_id' => 'Группа',
'sex' => 'Пол',
'first_name' => 'Имя',
'patronymic' => 'Отчество',
'last_name' => 'Фамилия',
'company_name' => 'Наименование компании',
'city' => 'Город',
'login' => 'Логин',
'password' => 'Пароль',
'email' => 'Email',
'manager_id' => 'Ответственный менеджер',
'create_date' => 'Время создания',
];
}
public function rules()
{
return [
[['sex', 'first_name', 'last_name', 'company_name', 'email', 'manager_id'], 'required'],
[['sex', 'is_auth'], 'integer'],
[['first_name', 'patronymic', 'last_name'], 'string', 'max' => 50],
[['company_name'], 'string', 'max' => 250],
[['email'], 'string', 'max' => 150],
[['city'], 'string', 'max' => 100],
[['manager_id'], 'string', 'max' => 11],
];
}
public function getPassings()
{
return $this->hasMany(Passing::className(), ['user_id' => 'id']);
}
public function getManager()
{
return $this->hasOne(Manager::className(), ['id' => 'manager_id']);
}
public function getGroupRelated()
{
return $this->hasOne(UserGroupAssign::className(), ['user_id' => 'id'])->andWhere([
UserGroupAssign::tableName() . '.session_id' => Yii::$app->request->get('session')
]);
}
public function getHistory()
{
return $this->hasOne(SendHistory::className(), ['user_id' => 'id'])->andWhere([
SendHistory::tableName() . '.session_id' => Yii::$app->request->get('session')
]);
}
public function getFio()
{
return $this->last_name . ' ' . $this->first_name . ' ' . $this->patronymic;
}
public function generateLogin()
{
return 'testlogin' . $this->id;
}
public function assignedTestsForSession($session_id)
{
$cr = new CDbCriteria;
$cr->with = 'passings';
$cr->addCondition('passings.user_id = :user_id');
$cr->addCondition('session_id = :session_id');
$cr->params = array(
':user_id'=>$this->id,
':session_id'=>$session_id,
);
$cr->together = true;
$cr->group = 't.id';
return TestingTest::model()->findAll($cr);
}
public static function getCompaniesList()
{
return Yii::app()->db->createCommand('SELECT DISTINCT `company_name` FROM `testings_users`')->queryAll();
}
}
<?php
namespace common\modules\testings\models;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
class UserGroup extends \common\components\ActiveRecordModel
{
const PAGE_SIZE = 10;
/**
* @inheritdoc
*/
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'created',
'updatedAtAttribute' => null,
'value' => new Expression('NOW()'),
],
];
}
public static function tableName()
{
return 'testings_users_groups';
}
public function name()
{
return 'Группы пользователей';
}
public function attributeLabels()
{
return [
'name' => 'Название группы',
'created' => 'Дата импорта',
'session_id' => 'Сессия',
];
}
public function rules()
{
return [
[['name'], 'required'],
[['created', 'session_id'], 'safe'],
];
}
}
<?php
namespace common\modules\testings\models;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
class UserGroupAssign extends \common\components\ActiveRecordModel
{
const PAGE_SIZE = 10;
/**
* @inheritdoc
*/
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'created',
'updatedAtAttribute' => null,
'value' => new Expression('NOW()'),
],
];
}
public static function tableName()
{
return 'testings_users_groups_assign';
}
public function name()
{
return 'Связка пользователей и групп';
}
public function attributeLabels()
{
return [
'group_id' => 'Группа',
'user_id' => 'Пользователь',
'session_id' => 'Сессия',
];
}
public function rules()
{
return [
[['group_id', 'user_id', 'session_id'], 'required'],
];
}
public function getGroup()
{
return $this->hasOne(UserGroup::className(), ['id' => 'group_id']);
}
}
<?php
use yii\helpers\Html;
use \common\components\zii\AdminGrid;
/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */
?>
<?php echo AdminGrid::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
// ['class' => 'yii\grid\SerialColumn'],
'name',
[
'attribute' => 'created',
'value' => function($model)
{
return date("d.m.Y H:i:s", $model->created);
}
],
[
'header' => 'Список пользователей',
'value' => function($model) {
return Html::a('Список пользователей', [
"/testings/user-admin/manage",
"session" => \Yii::$app->request->get('session'),
"group" => $model->id,
]);
},
'format' => 'html',
],
],
]); ?>
\ No newline at end of file
<?php
use yii\helpers\Html;
use \common\components\zii\AdminGrid;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use common\modules\testings\models\User;
use common\modules\testings\models\UserGroup;
use common\modules\testings\models\SendHistory;
use common\modules\testings\models\Session;
use common\modules\testings\models\Passing;
/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */
$session = null;
if (\Yii::$app->request->get('session'))
{
$session = Session::findOne(\Yii::$app->request->get('session'));
}
?>
<p>
<?= Html::a('Добавить', ['create'], ['class' => 'btn btn-success']) ?>
<?php if($session) : ?>
<?= Html::a('Разослать уведомления всем', ['/testings/session-admin/send-message-to-all', 'id' => $session->id], ['class' => 'btn btn-info']) ?>
<?= Html::a('История отправки дубликатов', ['/testings/send-history-admin/manage', 'session' => $session->id], ['class' => 'btn btn-info']) ?>
<?= Html::a('Импорт пользователей из XLS', ['/testings/session-admin/import-passings', 'id' => $session->id], ['class' => 'btn btn-info']) ?>
<?php endif; ?>
</p>
<?php if (\Yii::$app->session->hasFlash('flash')) : ?>
<div class="message"><span>
<?php echo \Yii::$app->session->getFlash('flash'); ?>
</span></div>
<?php endif; ?>
<?php
$columns = [
[
'attribute' => 'sex',
'value' => function($model)
{
return User::$sex_list[$model->sex];
},
'filter' => User::$sex_list,
'visible' => !\Yii::$app->request->get('session'),
],
'last_name',
'first_name',
'patronymic',
'company_name',
[
'attribute' => 'filter_group_id',
'value' => function($model)
{
return $model->groupRelated->group->name;
},
'filter' => ArrayHelper::map(UserGroup::find()->where(['session_id' => \Yii::$app->request->get('session')])->all(), 'id', 'name')
],
[
'attribute' => 'email',
'value' => function($model)
{
return Html::a($model->email, "mailto:" . $model->email);
},
'format' => 'html',
],
[
'header' => 'Статус отправки',
'attribute' => 'filter_history_status',
'filter' => SendHistory::getStatusTitle(),
'format' => 'raw',
'value' => function($model)
{
if($model->history)
{
return SendHistory::getStatusTitle($model->history->unisender_status);
}
},
],
[
'header' => 'Время отправки',
'value' => function($model)
{
if($model->history)
{
return date('d.m.Y H:i:s', $model->history->sended);
}
},
],
[
'attribute' => 'manager_id',
'value' => function($model)
{
if($model->manager)
{
return Html::a($model->manager->name, ["/users/user-admin/view", "id" => $model->manager_id]);
}
else
{
return "Пользователь удалён";
}
},
'format' => 'html',
],
'tki'
];
$link = '';
if ($session)
{
$marked = \Yii::$app->controller->getMarked($session->id);
$qty = count($marked);
$style = ($qty) ? '' : 'display:none;';
$send = Html::a("Разослать выделенным ($qty)",
['testings/session-admin/send-message-to-marked', 'id' => $session->id],
['style' => $style, 'id' => 'sendMarkup']
);
$clear = Html::a("[сброс]",
['update-mark', 'session' => $session->id],
['style' => $style, 'id' => 'resetMarkup']
);
$link = $send . ' ' . $clear . '<br><br>';
echo $link;
array_unshift(
$columns,
[
'class' => 'common\modules\testings\components\MarkBoxColumn',
'updateUrl' => Url::to(['update-mark', 'session' => $session->id]),
]
);
foreach($session->tests as $test)
{
$columns = ArrayHelper::merge(
$columns,
[
[
'header' => $test->name,
'value' => function($model) use($test)
{
$passing = Passing::find()->where([
'test_id' => $test->id,
'user_id' => $model->id
])->one();
if($passing)
{
return Html::a("Да", ["/testings/passing-admin/change-status", "user"=>$model->id, "test" => $test->id], ["title" => "Изменить на НЕТ"]);
}
else
{
return Html::a("Нет", ["/testings/passing-admin/change-status", "user"=>$model->id, "test" => $test->id], ["title" => "Изменить на ДА"]);
}
},
'format' => 'html',
]
]
);
}
$buttons = [
[
'class' => \common\components\ColorActionColumn::className(),
'template' => '{send} {view} {update}',
'buttons' => [
'send' => function ($url, $model, $key) use($session)
{
return Html::a('<i class="fa fa-envelope fa-lg"></i>', Url::to(['testings/session-admin/send-message', 'id' => $session->id, 'user' => $model->id]), [
'title' => 'Уведомить о тестировании',
'data-toggle' => 'tooltip',
'data-pjax' => '0',
]);
},
]
]
];
$columns = ArrayHelper::merge($columns, $buttons);
}
echo AdminGrid::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => $columns,
]);
\ No newline at end of file
<?php
echo $form;
\ No newline at end of file
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use common\modules\testings\models\User;
/* @var $this yii\web\View */
/* @var $model common\modules\faq\models\Faq */
?>
<div class="faq-view">
<h1><?= Html::encode($model->fio) ?></h1>
<p>
<?= Html::a(Yii::t('content', 'Update'), ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
[
'attribute' => 'sex',
'value' => User::$sex_list[$model->sex],
'filter' => false
],
'first_name',
'patronymic',
'last_name',
'company_name',
'city',
'login',
'email:email',
[
'attribute' => 'manager_id',
'value' => ($model->manager)?$model->manager->name:"Пользователь удалён"
],
'tki',
'region',
'create_date',
],
]) ?>
</div>
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment