Inheritance: extends Illuminate\Database\Eloquent\Model
 public function index()
 {
     $data = Role::CheckRole()->get();
     $role = Role::GetOrderBy()->get();
     $permission = Permissions::GetOrderBy()->get();
     // dd('test');
     return view('admin.management.index', compact('data', 'permission', 'role'));
 }
Exemplo n.º 2
0
			<li class="submenu-li"><a href="<?php 
            echo Url::to(['/site/index', 'podr_issues' => 1]);
            ?>
">Задания моему подразделению</a> <?php 
            if (isset(Yii::$app->request->getQueryParams()['podr_issues']) && Yii::$app->request->getQueryParams()['podr_issues'] == 1) {
                ?>
<i class="pull-right glyphicon glyphicon-ok"></i><?php 
            }
            ?>
</li>
			<?php 
        }
    }
    ?>
			<?php 
    $permissions_podr_tasks_my = \app\models\Permissions::find()->where('(SUBJECT_TYPE = :subject_type and SUBJECT_ID = :user_id and DEL_TRACT_ID = :del_tract and PERM_LEVEL != :perm_level and ACTION_ID = :action) or
					(SUBJECT_TYPE = :subject_type_dolg and SUBJECT_ID = :dolg_id and DEL_TRACT_ID = :del_tract and PERM_LEVEL != :perm_level and ACTION_ID = :action)', ['action' => 23, 'subject_type_dolg' => 1, 'dolg_id' => \Yii::$app->session->get('user.user_iddolg'), 'subject_type' => 2, 'user_id' => \Yii::$app->user->id, 'del_tract' => 0, 'perm_level' => 0])->one();
    if ($permissions_podr_tasks_my) {
        if ($permissions_podr_tasks_my->PERM_LEVEL == 1 || $permissions_podr_tasks_my->PERM_LEVEL == 2) {
            ?>
			<li class="submenu-li"><a href="<?php 
            echo Url::to(['/site/index', 'tasks_my' => 1]);
            ?>
">Выданные мной</a> <?php 
            if (isset(Yii::$app->request->getQueryParams()['tasks_my']) && Yii::$app->request->getQueryParams()['tasks_my'] == 1) {
                ?>
<i class="pull-right glyphicon glyphicon-ok"></i><?php 
            }
            ?>
</li>
			<?php 
Exemplo n.º 3
0
 public function search($params)
 {
     $query = Tasks::find();
     //формируем провайдер
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     //задание сортировки по умолчанию
     $dataProvider->sort->attributes = ['TASKS.ID' => ['asc' => ['TASKS.ID' => SORT_ASC], 'desc' => ['TASKS.ID' => SORT_DESC]]];
     $dataProvider->sort->defaultOrder = ['TASKS.ID' => SORT_DESC];
     //overdue issues filter
     if (isset($params['overdue']) && $params['overdue'] == 1) {
         $tasks = \app\models\Tasks::find()->all();
         $list = [];
         foreach ($tasks as $task) {
             $id = $task->ID;
             $persons = \app\models\PersTasks::find()->where(['TASK_ID' => $id, 'DEL_TRACT_ID' => 0])->all();
             if ($persons) {
                 $states_array = [];
                 foreach ($persons as $person) {
                     $pers_tasks = \app\models\PersTasks::find()->where(['TASK_ID' => $id, 'TN' => $person->TN, 'DEL_TRACT_ID' => 0])->one();
                     $task_state = \app\models\TaskStates::find()->where(['IS_CURRENT' => 1, 'PERS_TASKS_ID' => $pers_tasks->ID, 'TASK_ID' => $id])->one();
                     if ($task_state) {
                         $states_array[] = $task_state->STATE_ID;
                     } else {
                         $list[] = $id;
                     }
                 }
                 if (!empty($states_array)) {
                     $min_state = min($states_array);
                     $state = \app\models\States::findOne($min_state);
                 }
             }
             if (isset($state)) {
                 if ($state->ID != 7 || $state->ID != 9) {
                     $list[] = $id;
                 }
             }
         }
         $list = array_unique($list);
         $query->andFilterWhere(['TASKS.ID' => $list]);
         $now = date("Y-m-d");
         $query->andFilterWhere(['<', 'TASKS.DEADLINE', new \yii\db\Expression("to_date('" . $now . "','{$this->dateFormat}')")]);
         $query->joinWith('perstasks');
         $query->andFilterWhere(['PERS_TASKS.TN' => \Yii::$app->user->id]);
     }
     //own issues filter
     if (isset($params['own_issues']) && $params['own_issues'] == 1) {
         $query->joinWith('perstasks');
         $query->andFilterWhere(['PERS_TASKS.TN' => \Yii::$app->user->id]);
     }
     if (isset($params['for_person']) && $params['for_person'] != '') {
         $query->joinWith('perstasks');
         $query->andFilterWhere(['PERS_TASKS.TN' => $params['for_person']]);
     }
     if (isset($params['for_podr']) && $params['for_podr'] != '') {
         $query->joinWith('podrtasks');
         $query->andFilterWhere(['PODR_TASKS.KODZIFR' => $params['for_podr']]);
     }
     //podr issues filter
     if (isset($params['podr_issues']) && $params['podr_issues'] == 1) {
         //check permission
         $permissions_podr_tasks_my = \app\models\Permissions::find()->where('(SUBJECT_TYPE = :subject_type and SUBJECT_ID = :user_id and DEL_TRACT_ID = :del_tract and PERM_LEVEL != :perm_level and ACTION_ID = :action) or
             (SUBJECT_TYPE = :subject_type_dolg and SUBJECT_ID = :id_dolg and DEL_TRACT_ID = :del_tract and PERM_LEVEL != :perm_level and ACTION_ID = :action)', ['subject_type_dolg' => 1, 'id_dolg' => \Yii::$app->session->get('user.user_iddolg'), 'action' => 21, 'subject_type' => 2, 'user_id' => \Yii::$app->user->id, 'del_tract' => 0, 'perm_level' => 0])->one();
         if ($permissions_podr_tasks_my) {
             if ($permissions_podr_tasks_my->PERM_LEVEL == 1 || $permissions_podr_tasks_my->PERM_LEVEL == 2) {
                 //get podr id of this user
                 $query_dao = new \yii\db\Query();
                 $query_dao->select('*')->from('STIGIT.V_F_PERS')->where('TN = \'' . \Yii::$app->user->id . '\'');
                 $command = $query_dao->createCommand();
                 $data = $command->queryOne();
                 //вот тут решить что означает выданные моему подразделению
                 $query->joinWith('podrtasks');
                 $query->andFilterWhere(['PODR_TASKS.KODZIFR' => trim($data['KODZIFR'])]);
             } else {
                 throw new \yii\web\ForbiddenHttpException('У Вас нет прав на "Выданные любым задания"');
             }
         } else {
             throw new \yii\web\ForbiddenHttpException('У Вас нет прав на "Выданные любым задания"');
         }
     }
     //tasks my filter
     if (isset($params['tasks_my']) && $params['tasks_my'] == 1) {
         //check permission
         $permissions_podr_tasks_my = \app\models\Permissions::find()->where('(SUBJECT_TYPE = :subject_type and SUBJECT_ID = :user_id and DEL_TRACT_ID = :del_tract and PERM_LEVEL != :perm_level and ACTION_ID = :action) or
         (SUBJECT_TYPE = :subject_type_dolg and SUBJECT_ID = :id_dolg and DEL_TRACT_ID = :del_tract and PERM_LEVEL != :perm_level and ACTION_ID = :action)', ['subject_type_dolg' => 1, 'id_dolg' => \Yii::$app->session->get('user.user_iddolg'), 'action' => 23, 'subject_type' => 2, 'user_id' => \Yii::$app->user->id, 'del_tract' => 0, 'perm_level' => 0])->one();
         if ($permissions_podr_tasks_my) {
             if ($permissions_podr_tasks_my->PERM_LEVEL == 1 || $permissions_podr_tasks_my->PERM_LEVEL == 2) {
                 //get all current user transactions
                 $transactions = \app\models\Transactions::find()->where(['TN' => \Yii::$app->user->id])->all();
                 if ($transactions) {
                     $transactions_array = [];
                     foreach ($transactions as $transaction) {
                         $transactions_array[] = $transaction->ID;
                     }
                     $query->andFilterWhere(['TRACT_ID' => $transactions_array]);
                 }
             } else {
                 throw new \yii\web\ForbiddenHttpException('У Вас нет прав на "Выданные лично задания"');
             }
         } else {
             throw new \yii\web\ForbiddenHttpException('У Вас нет прав на "Выданные лично задания"');
         }
     }
     if (!($this->load($params) && $this->validate())) {
         return $dataProvider;
     }
     //проверяем существует ли фильтр и добавляем его в запрос провайдера для каждого из полей фильтра
     if (!empty($this->states)) {
         $query->joinWith('taskstates');
         $query->andFilterWhere(['TASK_STATES.STATE_ID' => $this->states]);
     }
     if (!empty($this->podr_list)) {
         $podr_list = array_map('trim', explode(',', $this->podr_list));
         $query->joinWith('podrtasks');
         $query->andFilterWhere(['PODR_TASKS.KODZIFR' => $podr_list]);
     }
     if (!empty($this->agreed_podr_list)) {
         $agreed_podr_list = array_map('trim', explode(',', $this->agreed_podr_list));
         $query->joinWith('taskconfirms');
         $query->andFilterWhere(['TASK_CONFIRMS.KODZIFR' => $agreed_podr_list]);
     }
     if (!empty($this->persons_list)) {
         $persons_list = array_map('trim', explode(',', $this->persons_list));
         $query->joinWith('perstasks');
         $query->andFilterWhere(['PERS_TASKS.TN' => $persons_list]);
     }
     if (!empty($this->documentation)) {
         $query->joinWith('taskdocs');
         $query->andFilterWhere(['TASK_DOCS.DOC_CODE' => $this->documentation]);
     }
     if ($this->deadline_from != '' && $this->deadline_to != '') {
         $deadline_from = explode('-', $this->deadline_from);
         $deadline_from_formatted = $deadline_from[2] . '-' . $deadline_from[1] . '-' . $deadline_from[0];
         $deadline_to = explode('-', $this->deadline_to);
         $deadline_to_formatted = $deadline_to[2] . '-' . $deadline_to[1] . '-' . $deadline_to[0];
         $query->andFilterWhere(['>=', 'DEADLINE', new \yii\db\Expression("to_date('" . $deadline_from_formatted . "','{$this->dateFormat}')")])->andFilterWhere(['<=', 'DEADLINE', new \yii\db\Expression("to_date('" . $deadline_to_formatted . "','{$this->dateFormat}')")]);
     } else {
         if ($this->deadline_from != '' && $this->deadline_to == '') {
             $deadline_from = explode('-', $this->deadline_from);
             $deadline_from_formatted = $deadline_from[2] . '-' . $deadline_from[1] . '-' . $deadline_from[0];
             $query->andFilterWhere(['>=', 'DEADLINE', new \yii\db\Expression("to_date('" . $deadline_from_formatted . "','{$this->dateFormat}')")]);
         } else {
             if ($this->deadline_from == '' && $this->deadline_to != '') {
                 $deadline_to = explode('-', $this->deadline_to);
                 $deadline_to_formatted = $deadline_to[2] . '-' . $deadline_to[1] . '-' . $deadline_to[0];
                 $query->andFilterWhere(['<=', 'DEADLINE', new \yii\db\Expression("to_date('" . $deadline_to_formatted . "','{$this->dateFormat}')")]);
             }
         }
     }
     if ($this->task_type_date_3_from != '' && $this->task_type_date_3_to != '') {
         $query->joinWith('datetype3');
         $task_type_date_3_from = explode('-', $this->task_type_date_3_from);
         $task_type_date_3_from_formatted = $task_type_date_3_from[2] . '-' . $task_type_date_3_from[1] . '-' . $task_type_date_3_from[0];
         $task_type_date_3_to = explode('-', $this->task_type_date_3_to);
         $task_type_date_3_to_formatted = $task_type_date_3_to[2] . '-' . $task_type_date_3_to[1] . '-' . $task_type_date_3_to[0];
         $query->andFilterWhere(['>=', 'TASK_DATES.TASK_TYPE_DATE', new \yii\db\Expression("to_date('" . $task_type_date_3_from_formatted . "','{$this->dateFormat}')")])->andFilterWhere(['<=', 'TASK_DATES.TASK_TYPE_DATE', new \yii\db\Expression("to_date('" . $task_type_date_3_to_formatted . "','{$this->dateFormat}')")]);
     } else {
         if ($this->task_type_date_3_from != '' && $this->task_type_date_3_to == '') {
             $query->joinWith('datetype3');
             $task_type_date_3_from = explode('-', $this->task_type_date_3_from);
             $task_type_date_3_from_formatted = $task_type_date_3_from[2] . '-' . $task_type_date_3_from[1] . '-' . $task_type_date_3_from[0];
             $query->andFilterWhere(['>=', 'TASK_DATES.TASK_TYPE_DATE', new \yii\db\Expression("to_date('" . $task_type_date_3_from_formatted . "','{$this->dateFormat}')")]);
         } else {
             if ($this->task_type_date_3_from == '' && $this->task_type_date_3_to != '') {
                 $query->joinWith('datetype3');
                 $task_type_date_3_to = explode('-', $this->task_type_date_3_to);
                 $task_type_date_3_to_formatted = $task_type_date_3_to[2] . '-' . $task_type_date_3_to[1] . '-' . $task_type_date_3_to[0];
                 $query->andFilterWhere(['<=', 'TASK_DATES.TASK_TYPE_DATE', new \yii\db\Expression("to_date('" . $task_type_date_3_to_formatted . "','{$this->dateFormat}')")]);
             }
         }
     }
     if ($this->task_type_date_1_from != '' && $this->task_type_date_1_to != '') {
         $query->joinWith('datetype1');
         $task_type_date_1_from = explode('-', $this->task_type_date_1_from);
         $task_type_date_1_from_formatted = $task_type_date_1_from[2] . '-' . $task_type_date_1_from[1] . '-' . $task_type_date_1_from[0];
         $task_type_date_1_to = explode('-', $this->task_type_date_1_to);
         $task_type_date_1_to_formatted = $task_type_date_1_to[2] . '-' . $task_type_date_1_to[1] . '-' . $task_type_date_1_to[0];
         $query->andFilterWhere(['>=', 'TASK_DATES.TASK_TYPE_DATE', new \yii\db\Expression("to_date('" . $task_type_date_1_from_formatted . "','{$this->dateFormat}')")])->andFilterWhere(['<=', 'TASK_DATES.TASK_TYPE_DATE', new \yii\db\Expression("to_date('" . $task_type_date_1_to_formatted . "','{$this->dateFormat}')")]);
     } else {
         if ($this->task_type_date_1_from != '' && $this->task_type_date_1_to == '') {
             $query->joinWith('datetype1');
             $task_type_date_1_from = explode('-', $this->task_type_date_1_from);
             $task_type_date_1_from_formatted = $task_type_date_1_from[2] . '-' . $task_type_date_1_from[1] . '-' . $task_type_date_1_from[0];
             $query->andFilterWhere(['>=', 'TASK_DATES.TASK_TYPE_DATE', new \yii\db\Expression("to_date('" . $task_type_date_1_from_formatted . "','{$this->dateFormat}')")]);
         } else {
             if ($this->task_type_date_1_from == '' && $this->task_type_date_1_to != '') {
                 $query->joinWith('datetype1');
                 $task_type_date_1_to = explode('-', $this->task_type_date_1_to);
                 $task_type_date_1_to_formatted = $task_type_date_1_to[2] . '-' . $task_type_date_1_to[1] . '-' . $task_type_date_1_to[0];
                 $query->andFilterWhere(['<=', 'TASK_DATES.TASK_TYPE_DATE', new \yii\db\Expression("to_date('" . $task_type_date_1_to_formatted . "','{$this->dateFormat}')")]);
             }
         }
     }
     if ($this->task_type_date_4_from != '' && $this->task_type_date_4_to != '') {
         $query->joinWith('datetype4');
         $task_type_date_4_from = explode('-', $this->task_type_date_4_from);
         $task_type_date_4_from_formatted = $task_type_date_4_from[2] . '-' . $task_type_date_4_from[1] . '-' . $task_type_date_4_from[0];
         $task_type_date_4_to = explode('-', $this->task_type_date_4_to);
         $task_type_date_4_to_formatted = $task_type_date_4_to[2] . '-' . $task_type_date_4_to[1] . '-' . $task_type_date_4_to[0];
         $query->andFilterWhere(['>=', 'TASK_DATES.TASK_TYPE_DATE', new \yii\db\Expression("to_date('" . $task_type_date_4_from_formatted . "','{$this->dateFormat}')")])->andFilterWhere(['<=', 'TASK_DATES.TASK_TYPE_DATE', new \yii\db\Expression("to_date('" . $task_type_date_4_to_formatted . "','{$this->dateFormat}')")]);
     } else {
         if ($this->task_type_date_4_from != '' && $this->task_type_date_4_to == '') {
             $query->joinWith('datetype4');
             $task_type_date_4_from = explode('-', $this->task_type_date_4_from);
             $task_type_date_4_from_formatted = $task_type_date_4_from[2] . '-' . $task_type_date_4_from[1] . '-' . $task_type_date_4_from[0];
             $query->andFilterWhere(['>=', 'TASK_DATES.TASK_TYPE_DATE', new \yii\db\Expression("to_date('" . $task_type_date_4_from_formatted . "','{$this->dateFormat}')")]);
         } else {
             if ($this->task_type_date_4_from == '' && $this->task_type_date_4_to != '') {
                 $query->joinWith('datetype4');
                 $task_type_date_4_to = explode('-', $this->task_type_date_4_to);
                 $task_type_date_4_to_formatted = $task_type_date_4_to[2] . '-' . $task_type_date_4_to[1] . '-' . $task_type_date_4_to[0];
                 $query->andFilterWhere(['<=', 'TASK_DATES.TASK_TYPE_DATE', new \yii\db\Expression("to_date('" . $task_type_date_4_to_formatted . "','{$this->dateFormat}')")]);
             }
         }
     }
     if ($this->task_type_date_2_from != '' && $this->task_type_date_2_to != '') {
         $query->joinWith('datetype2');
         $task_type_date_2_from = explode('-', $this->task_type_date_2_from);
         $task_type_date_2_from_formatted = $task_type_date_2_from[2] . '-' . $task_type_date_2_from[1] . '-' . $task_type_date_2_from[0];
         $task_type_date_2_to = explode('-', $this->task_type_date_2_to);
         $task_type_date_2_to_formatted = $task_type_date_2_to[2] . '-' . $task_type_date_2_to[1] . '-' . $task_type_date_2_to[0];
         $query->andFilterWhere(['>=', 'TASK_DATES.TASK_TYPE_DATE', new \yii\db\Expression("to_date('" . $task_type_date_2_from_formatted . "','{$this->dateFormat}')")])->andFilterWhere(['<=', 'TASK_DATES.TASK_TYPE_DATE', new \yii\db\Expression("to_date('" . $task_type_date_2_to_formatted . "','{$this->dateFormat}')")]);
     } else {
         if ($this->task_type_date_2_from != '' && $this->task_type_date_2_to == '') {
             $query->joinWith('datetype2');
             $task_type_date_2_from = explode('-', $this->task_type_date_2_from);
             $task_type_date_2_from_formatted = $task_type_date_2_from[2] . '-' . $task_type_date_2_from[1] . '-' . $task_type_date_2_from[0];
             $query->andFilterWhere(['>=', 'TASK_DATES.TASK_TYPE_DATE', new \yii\db\Expression("to_date('" . $task_type_date_2_from_formatted . "','{$this->dateFormat}')")]);
         } else {
             if ($this->task_type_date_2_from == '' && $this->task_type_date_2_to != '') {
                 $query->joinWith('datetype2');
                 $task_type_date_2_to = explode('-', $this->task_type_date_2_to);
                 $task_type_date_2_to_formatted = $task_type_date_2_to[2] . '-' . $task_type_date_2_to[1] . '-' . $task_type_date_2_to[0];
                 $query->andFilterWhere(['<=', 'TASK_DATES.TASK_TYPE_DATE', new \yii\db\Expression("to_date('" . $task_type_date_2_to_formatted . "','{$this->dateFormat}')")]);
             }
         }
     }
     $query->andFilterWhere(['like', 'SOURCENUM', $this->SOURCENUM]);
     $query->andFilterWhere(['like', 'TASK_TEXT', $this->TASK_TEXT]);
     $query->andFilterWhere(['or like', 'PEOORDERNUM', $this->PEOORDERNUM]);
     $query->andFilterWhere(['or like', 'ORDERNUM', $this->ORDERNUM]);
     $query->andFilterWhere(['like', 'TASK_NUMBER', $this->TASK_NUMBER]);
     $query->andFilterWhere(['like', 'LOWER(DESIGNATION)', mb_strtolower($this->DESIGNATION, 'UTF-8')]);
     return $dataProvider;
 }
Exemplo n.º 4
0
 public function actionSetpermlevel()
 {
     if (Yii::$app->request->isAjax) {
         $permission_id = $_POST['permission_id'];
         $level = $_POST['level'];
         //$transactions = \app\models\Transactions::find()->where(['TN' => \Yii::$app->user->id ])->orderBy('ID DESC')->one();
         $permissions = \app\models\Permissions::findOne($permission_id);
         $permissions->PERM_LEVEL = $level;
         if ($permissions->save()) {
             Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
             return ['error' => 0];
         } else {
             //print_r($permissions->errors); die();
             Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
             return ['error' => 1];
         }
     }
 }
Exemplo n.º 5
0
									                var isset_children = 'true';
								                    for (var i = 0; i <= node_parent.children.length; i++) {
								                    	if($('#jstree-v_f_pers').jstree(true).get_node(node_parent.children[i]).text === node.text) {
								                    		isset_children = 'false';
								                    	} 
								                    }
								                    if(more && more.dnd && (operation === 'move_node' || operation === 'copy_node') && (node_parent.id === '#' || node_parent.parents.length != 1 || isset_children === 'false' )) {
													    return false;
													}
													return true;
									            },
									            "data" : [
										        	<?php 
foreach ($v_f_pers as $v_f_per) {
    echo '{"id" : "v_f_per_' . $v_f_per['tn'] . '", "icon" : "glyphicon glyphicon-user", "parent" : "#", "text" : "' . $v_f_per['fio'] . '", "li_attr" : { "data-panel" : "v_f_pers", "data-id" : "' . $v_f_per['tn'] . '" }},';
    $inner_list = \app\models\Permissions::find()->where(['SUBJECT_TYPE' => 2, 'SUBJECT_ID' => $v_f_per['tn'], 'DEL_TRACT_ID' => 0])->orderBy('PERM_TYPE')->all();
    if ($inner_list) {
        foreach ($inner_list as $li) {
            if ($li->PERM_TYPE == 1) {
                $result_li = \app\models\Actions::findOne($li->ACTION_ID);
                echo '{"id" : "' . $li->ID . '", "icon" : "glyphicon glyphicon-cog", "parent" : "v_f_per_' . $v_f_per['tn'] . '", "text" : "' . $result_li->ACTION_DESC . '", "li_attr" : { "data-id" : "' . $li->ID . '", "data-perm-level" : "' . $li->PERM_LEVEL . '", "class" : "inner-node-state"}},';
            } elseif ($li->PERM_TYPE == 2) {
                $result_li = \app\models\States::findOne($li->ACTION_ID);
                echo '{"id" : "' . $li->ID . '", "icon" : "glyphicon glyphicon-check", "parent" : "v_f_per_' . $v_f_per['tn'] . '", "text" : "' . $result_li->STATE_NAME . '", "li_attr" : { "data-id" : "' . $li->ID . '", "data-perm-level" : "' . $li->PERM_LEVEL . '", "class" : "inner-node-state"}},';
            }
        }
    }
}
?>
										        ],
									        },
Exemplo n.º 6
0
 public function actionExcel()
 {
     /*
         Проверка на доступ пользователя к странице
     */
     $permissions_report_task_search = \app\models\Permissions::find()->where('(SUBJECT_TYPE = :subject_type and SUBJECT_ID = :user_id and DEL_TRACT_ID = :del_tract and PERM_LEVEL != :perm_level and ACTION_ID = :action) or
                                     (SUBJECT_TYPE = :subject_type_dolg and SUBJECT_ID = :dolg_id and DEL_TRACT_ID = :del_tract and PERM_LEVEL != :perm_level and ACTION_ID = :action)', ['subject_type_dolg' => 1, 'dolg_id' => \Yii::$app->session->get('user.user_iddolg'), 'action' => 82, 'subject_type' => 2, 'user_id' => \Yii::$app->user->id, 'del_tract' => 0, 'perm_level' => 0])->one();
     if ($permissions_report_task_search) {
         /*
             Проверяем получены ли идентификаторы заданий для формирования отчета
         */
         if (Yii::$app->request->get('ids')) {
             $issues_ids = Yii::$app->request->get('ids');
             $issues_ids = explode(',', $issues_ids);
             /*
                 Делаем выборку необходимых заданий
             */
             $model = \app\models\Tasks::find()->where(['ID' => $issues_ids])->all();
             if ($model) {
                 // Создаем объект класса PHPExcel
                 $xls = new \PHPExcel();
                 // Устанавливаем индекс активного листа
                 $xls->setActiveSheetIndex(0);
                 // Получаем активный лист
                 $sheet = $xls->getActiveSheet();
                 // Подписываем лист
                 $sheet->setTitle('Отчет по отобранным заданиям');
                 $sheet->getStyle('A1')->getFont()->setBold(true);
                 // Вставляем текст в ячейку A1
                 $sheet->setCellValue("A1", 'Отчет по отобранным заданиям');
                 $sheet->getStyle('A1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
                 $sheet->getStyle('A1')->getFill()->getStartColor()->setRGB('EEEEEE');
                 // Объединяем ячейки
                 $sheet->mergeCells('A1:I1');
                 // Выравнивание текста
                 $sheet->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                 // Формируем шапку
                 $sheet->setCellValue("A2", 'Заказ ПЭО');
                 $sheet->setCellValue("B2", 'Номер заказа');
                 $sheet->setCellValue("C2", 'Проект/Тема');
                 $sheet->setCellValue("D2", 'Обозначение');
                 $sheet->setCellValue("E2", 'Наименование');
                 $sheet->setCellValue("F2", 'Срок выполнения');
                 $sheet->setCellValue("G2", 'Статус');
                 $sheet->setCellValue("H2", 'Ф.И.О. и Дата');
                 $sheet->setCellValue("I2", 'Форматов А4');
                 /* устанавливаем ширину колонок и стили*/
                 $sheet->getStyle('A2:I2')->getFont()->setBold(true);
                 $sheet->getColumnDimension('A')->setAutoSize(true);
                 $sheet->getColumnDimension('B')->setAutoSize(true);
                 $sheet->getColumnDimension('C')->setAutoSize(true);
                 $sheet->getColumnDimension('D')->setAutoSize(true);
                 $sheet->getColumnDimension('E')->setAutoSize(true);
                 $sheet->getColumnDimension('F')->setAutoSize(true);
                 $sheet->getColumnDimension('G')->setWidth(20);
                 $sheet->getColumnDimension('H')->setAutoSize(true);
                 $sheet->getColumnDimension('I')->setAutoSize(true);
                 $row_number = 3;
                 foreach ($model as $task) {
                     $sheet->setCellValue("A" . $row_number, $task->PEOORDERNUM);
                     $sheet->setCellValue("B" . $row_number, $task->ORDERNUM);
                     $sheet->setCellValue("C" . $row_number, '');
                     $sheet->setCellValue("D" . $row_number, $task->TASK_NUMBER);
                     $sheet->setCellValue("E" . $row_number, 'Задание');
                     $sheet->setCellValue("F" . $row_number, \Yii::$app->formatter->asDate($task->DEADLINE, 'php:d-m-Y'));
                     //вставляем информацию по статусам
                     $task_states = \app\models\TaskStates::find()->where(['TASK_ID' => $task->ID])->orderBy('STATE_ID ASC')->all();
                     if ($task_states) {
                         foreach ($task_states as $state) {
                             $state_date = $state->getStateDate();
                             $logo = new \PHPExcel_Worksheet_Drawing();
                             $logo->setPath(Yii::getAlias('@webroot') . '/images/items_status/' . $state->getStateColour() . '.png');
                             $logo->setCoordinates("G" . $row_number);
                             $logo->setOffsetX(5);
                             $logo->setOffsetY(2);
                             $logo->setResizeProportional(true);
                             $logo->setWidth(16);
                             $logo->setWorksheet($sheet);
                             $sheet->setCellValue("G" . $row_number, '        ' . $state->getStateName());
                             $pers_tasks = \app\models\PersTasks::findOne($state->PERS_TASKS_ID);
                             $query = new \yii\db\Query();
                             $query->select('*')->from('STIGIT.V_F_PERS')->where('TN = \'' . $pers_tasks->TN . '\'');
                             $command = $query->createCommand();
                             $data = $command->queryOne();
                             $sheet->setCellValue("H" . $row_number, $data['FIO'] . ' ' . $state_date);
                             $task_docs = \app\models\TaskDocs::find()->where(['PERS_TASKS_ID' => $state->PERS_TASKS_ID])->one();
                             if ($task_docs) {
                                 $quantity = $task_docs->FORMAT_QUANTITY;
                             } else {
                                 $quantity = 0;
                             }
                             $sheet->setCellValue("I" . $row_number, $quantity);
                             $row_number++;
                         }
                     }
                     $row_number++;
                 }
                 //стили для рамки таблицы
                 $styleArray = array('borders' => array('allborders' => array('style' => \PHPExcel_Style_Border::BORDER_THIN)));
                 $total_rows = $row_number - 1;
                 $sheet->getStyle('A1:I' . $total_rows)->applyFromArray($styleArray);
                 //параметры страницы для печати - альбомная
                 $xls->getActiveSheet()->getPageSetup()->setOrientation(\PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
                 $xls->getActiveSheet()->getPageSetup()->setPaperSize(\PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);
                 $xls->getActiveSheet()->getPageSetup()->setFitToPage(true);
                 $xls->getActiveSheet()->getPageSetup()->setFitToWidth(1);
                 $xls->getActiveSheet()->getPageSetup()->setFitToHeight(0);
                 // Выводим HTTP-заголовки
                 header("Expires: Mon, 1 Apr 1974 05:00:00 GMT");
                 header("Last-Modified: " . gmdate("D,d M YH:i:s") . " GMT");
                 header("Cache-Control: no-cache, must-revalidate");
                 header("Pragma: no-cache");
                 header("Content-type: application/vnd.ms-excel");
                 header("Content-Disposition: attachment; filename=report.xls");
                 //Выводим содержимое файла
                 $objWriter = new \PHPExcel_Writer_Excel5($xls);
                 $objWriter->save('php://output');
             } else {
                 /*
                     Вызываем эксепшн в случае, если были переданы не верные параметры заданий
                 */
                 throw new \yii\web\NotFoundHttpException('Что-то пошло не так. Пожалуйста, обратитесь к администратору системы.');
             }
         }
     } else {
         /*
             Вызываем эксепшн в случае, если доступ к формированию отчета запрещен
         */
         throw new \yii\web\ForbiddenHttpException('У Вас нет прав на редактирование "Формирование отчета"');
     }
 }
 public function _checkPermissions($action, $task_id)
 {
     switch ($action) {
         case 'open_issue_modal':
             //проверка прав на просмотр задания (в модальном окне)
             $permissions_for_open_issue_modal = \app\models\Permissions::find()->where('(SUBJECT_TYPE = :subject_type and SUBJECT_ID = :user_id and ACTION_ID = :action and DEL_TRACT_ID = :del_tract and PERM_LEVEL != :perm_level and PERM_TYPE = :perm_type)  or 
                                                                                     (SUBJECT_TYPE = :subject_type_dolg and SUBJECT_ID = :dolg_id and ACTION_ID = :action and DEL_TRACT_ID = :del_tract and PERM_LEVEL != :perm_level and PERM_TYPE = :perm_type)', ['subject_type_dolg' => 1, 'dolg_id' => \Yii::$app->session->get('user.user_iddolg'), 'perm_type' => 1, 'subject_type' => 2, 'user_id' => \Yii::$app->user->id, 'del_tract' => 0, 'perm_level' => 0, 'action' => 3])->one();
             if ($permissions_for_open_issue_modal) {
                 //в случае если есть доступ на просмотр данных о задании
                 $user_in_persons_or_podr_list = false;
                 //получаем массив подразделений задания
                 $podr_tasks = \app\models\PodrTasks::find()->where(['TASK_ID' => $task_id, 'DEL_TRACT_ID' => 0])->all();
                 if ($podr_tasks) {
                     // если существуют подразделения, то формируем их список
                     $podr_list_kodzifr_array = [];
                     foreach ($podr_tasks as $task) {
                         //обходим список подразделений
                         $query = new \yii\db\Query();
                         $query->select('*')->from('STIGIT.V_F_PODR')->where('KODZIFR = \'' . trim($task->KODZIFR) . '\'');
                         $command = $query->createCommand();
                         $data = $command->queryOne();
                         if (isset($data['KODZIFR'])) {
                             // проверяем на существование названия подразделения (на момент разработки не для всех были названия)
                             $podr_list_kodzifr_array[] = $data['KODZIFR'];
                         }
                     }
                 }
                 //проверяем входит ли данный пользователь в список исполнителей задания
                 //получаем список пользователей, кому назначено задание
                 $pers_tasks = \app\models\PersTasks::find()->where(['TASK_ID' => $task_id, 'DEL_TRACT_ID' => 0])->all();
                 if ($pers_tasks) {
                     // если существуют исполнители, то формируем их список
                     $persons_array = [];
                     foreach ($pers_tasks as $task) {
                         $query = new \yii\db\Query();
                         $query->select('*')->from('STIGIT.V_F_PERS')->where('TN = \'' . $task->TN . '\'');
                         $command = $query->createCommand();
                         $data = $command->queryOne();
                         $persons_array[] = $data['TN'];
                     }
                     //проверяем, входит ли пользователь в этот список
                     if (in_array(\Yii::$app->user->id, $persons_array)) {
                         //пользователь входит в список исполнителей
                         $user_in_persons_or_podr_list = true;
                     }
                 } else {
                     //в этом случае, задания назначено всем исполнителям из списка подразделений задания
                     $persons_array = [];
                     //обходим массив подразделений для проверки, входит ли в него текущий пользователь
                     $ids = join(',', $podr_list_kodzifr_array);
                     $query = new \yii\db\Query();
                     $query->select('*')->from('STIGIT.V_F_PERS')->where('TN = \'' . \Yii::$app->user->id . '\' and KODZIFR in (' . $ids . ')');
                     $command = $query->createCommand();
                     $data = $command->queryAll();
                     if (!empty($data)) {
                         // проверяем вхождение пользователя в список исполнителей подразделений задания
                         $user_in_persons_or_podr_list = true;
                         // текущий пользователь входит в подразделения, указанные в задании
                     }
                 }
                 //проверяем, является ли пользователь начальником подразделений, указанных в задании
                 //получаем список подчиненных подразделений
                 $user_boss_of = \Yii::$app->session->get('user.user_boss_of');
                 if (!empty($user_boss_of) && !$user_in_persons_or_podr_list) {
                     //проверяем, является ли пользователь начальником подразделений, указанных в задании
                     if (in_array($user_boss_of, $podr_list_kodzifr_array)) {
                         //пользователь является руководителем, но не входит в спиок исполнителей или указанных подразделений
                         //осуществляем проверку прав на 'podr_tasks_my_edit'
                         $permissions_for_open_issue_modal_for_boss = \app\models\Permissions::find()->where('(SUBJECT_TYPE = :subject_type and SUBJECT_ID = :user_id and ACTION_ID = :action and DEL_TRACT_ID = :del_tract and PERM_LEVEL != :perm_level and PERM_TYPE = :perm_type)  or 
                                                                                         (SUBJECT_TYPE = :subject_type_dolg and SUBJECT_ID = :dolg_id and ACTION_ID = :action and DEL_TRACT_ID = :del_tract and PERM_LEVEL != :perm_level and PERM_TYPE = :perm_type)', ['subject_type_dolg' => 1, 'dolg_id' => \Yii::$app->session->get('user.user_iddolg'), 'perm_type' => 1, 'subject_type' => 2, 'user_id' => \Yii::$app->user->id, 'del_tract' => 0, 'perm_level' => 0, 'action' => 101])->one();
                         if ($permissions_for_open_issue_modal_for_boss) {
                             //пользователю разрешен просмотр и редактирование заданий своего подразделения
                             $user_in_persons_or_podr_list = true;
                         }
                     }
                 }
                 if ($user_in_persons_or_podr_list) {
                     //пользователь имеет доступ к заданию, так как входит в список исполнителей выбранного задания, либо находится в составе подразделей задания,
                     //либо является руководителем подразделений, указанных в задании
                     return true;
                 }
             } else {
                 return false;
             }
             break;
         case 'open_issue_modal_in_current_status':
             //проверка прав на просмотр задания (в модальном окне) в текущем статусе задания
             //получаем текущий статус задания для данного пользователя
             $current_status = self::_getCurrentTaskStatusForCurrentUser($task_id);
             if ($current_status != 'empty_status' && $current_status != 'user_not_in_persons_list') {
                 //проверяем есть ли доступ у пользователя к заданию в текущем статусе
                 $permissions_for_open_issue_modal_in_current_status = \app\models\Permissions::find()->where('(SUBJECT_TYPE = :subject_type and SUBJECT_ID = :user_id and DEL_TRACT_ID = :del_tract and PERM_LEVEL != :perm_level and ACTION_ID = :action and PERM_TYPE = :perm_type) or
                                                                                         (SUBJECT_TYPE = :subject_type_dolg and SUBJECT_ID = :id_dolg and DEL_TRACT_ID = :del_tract and PERM_LEVEL != :perm_level and ACTION_ID = :action and PERM_TYPE = :perm_type)', ['subject_type_dolg' => 1, 'id_dolg' => \Yii::$app->session->get('user.user_iddolg'), 'perm_type' => 2, 'subject_type' => 2, 'user_id' => \Yii::$app->user->id, 'del_tract' => 0, 'perm_level' => 0, 'action' => $current_status])->one();
                 if ($permissions_for_open_issue_modal_in_current_status) {
                     //досутп на просмотр в текущем статусе разрешен
                     return 'true';
                 } else {
                     $state = \app\models\States::findOne($current_status);
                     return 'У Вас нет прав на "Форма свойств задания" в статусе "' . $state->STATE_NAME . '"';
                 }
             } elseif ($current_status == 'empty_status') {
                 //устанавливаем статус "Принято при первом открытии задания"
                 $pers_tasks = \app\models\PersTasks::find()->where(['TASK_ID' => $task_id, 'TN' => \Yii::$app->user->id, 'DEL_TRACT_ID' => 0])->one();
                 $transactions = \app\models\Transactions::find()->where(['TN' => \Yii::$app->user->id])->orderBy('ID DESC')->one();
                 //пишем первый статус в БД
                 $task_states = new \app\models\TaskStates();
                 $task_states->TASK_ID = $task_id;
                 $task_states->STATE_ID = 1;
                 $task_states->TRACT_ID = $transactions->ID;
                 $task_states->IS_CURRENT = 1;
                 if ($pers_tasks->ID) {
                     // устанавливаем pers_tasks id
                     $task_states->PERS_TASKS_ID = $pers_tasks->ID;
                 }
                 $task_states->save();
                 //разрешаем пользователю смотреть информацию по заданию
                 return 'true';
             } elseif ($current_status == 'user_not_in_persons_list') {
                 //пользователь не стоит в списке исполнителей задания
                 //проверяем, если он руководитель показываем информацию по заданию (остальные пользователи сбда не попадут из-за проверки выше)
                 return 'true_for_boss';
             }
             break;
         case 'update_issue':
             //проверяем, есть ли доступ на редактирование задания для исполнителей
             $permissions_for_update_issue = \app\models\Permissions::find()->where('(SUBJECT_TYPE = :subject_type and SUBJECT_ID = :user_id and ACTION_ID = :action and DEL_TRACT_ID = :del_tract and PERM_LEVEL = :perm_level and PERM_TYPE = :perm_type)  or 
                                                                                     (SUBJECT_TYPE = :subject_type_dolg and SUBJECT_ID = :dolg_id and ACTION_ID = :action and DEL_TRACT_ID = :del_tract and PERM_LEVEL = :perm_level and PERM_TYPE = :perm_type)', ['subject_type_dolg' => 1, 'dolg_id' => \Yii::$app->session->get('user.user_iddolg'), 'perm_type' => 1, 'subject_type' => 2, 'user_id' => \Yii::$app->user->id, 'del_tract' => 0, 'perm_level' => 2, 'action' => 3])->one();
             //проверка доступа на редактирование для руководителей
             $permissions_for_update_issue_boss = \app\models\Permissions::find()->where('(SUBJECT_TYPE = :subject_type and SUBJECT_ID = :user_id and ACTION_ID = :action and DEL_TRACT_ID = :del_tract and PERM_LEVEL = :perm_level and PERM_TYPE = :perm_type)  or 
                                                                                     (SUBJECT_TYPE = :subject_type_dolg and SUBJECT_ID = :dolg_id and ACTION_ID = :action and DEL_TRACT_ID = :del_tract and PERM_LEVEL = :perm_level and PERM_TYPE = :perm_type)', ['subject_type_dolg' => 1, 'dolg_id' => \Yii::$app->session->get('user.user_iddolg'), 'perm_type' => 1, 'subject_type' => 2, 'user_id' => \Yii::$app->user->id, 'del_tract' => 0, 'perm_level' => 2, 'action' => 101])->one();
             //проверяем кто редактирует задание
             $pers_tasks = \app\models\PersTasks::find()->where(['TASK_ID' => $task_id, 'DEL_TRACT_ID' => 0])->all();
             if ($pers_tasks) {
                 // если существуют исполнители, то формируем их список
                 $persons_array = [];
                 foreach ($pers_tasks as $task) {
                     $query = new \yii\db\Query();
                     $query->select('*')->from('STIGIT.V_F_PERS')->where('TN = \'' . $task->TN . '\'');
                     $command = $query->createCommand();
                     $data = $command->queryOne();
                     $persons_array[] = $data['TN'];
                 }
                 //проверяем, входит ли пользователь в этот список
                 if (in_array(\Yii::$app->user->id, $persons_array)) {
                     //пользователь входит в список исполнителей
                     $user_is_person = 1;
                 } else {
                     $user_is_person = 0;
                 }
             }
             if ($permissions_for_update_issue && $user_is_person == 1) {
                 return 'update_issue_for_person';
             } elseif ($permissions_for_update_issue_boss && $user_is_person == 0) {
                 return 'update_issue_for_boss';
             } else {
                 return false;
             }
             break;
     }
 }
 protected function getPermissions()
 {
     return Permissions::with('roles')->get();
 }
 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     /**
      * User Permissions
      */
     $createUser = new Permissions();
     $createUser->display_name = 'Create user';
     $createUser->name = 'user-create';
     $createUser->description = 'Permission to create user';
     $createUser->save();
     $updateUser = new Permissions();
     $updateUser->display_name = 'Update user';
     $updateUser->name = 'user-update';
     $updateUser->description = 'Permission to update user';
     $updateUser->save();
     $deleteUser = new Permissions();
     $deleteUser->display_name = 'Delete user';
     $deleteUser->name = 'user-delete';
     $deleteUser->description = 'Permission to update delete';
     $deleteUser->save();
     /**
      * Client Permissions
      */
     $createClient = new Permissions();
     $createClient->display_name = 'Create client';
     $createClient->name = 'client-create';
     $createClient->description = 'Permission to create client';
     $createClient->save();
     $updateClient = new Permissions();
     $updateClient->display_name = 'Update client';
     $updateClient->name = 'client-update';
     $updateClient->description = 'Permission to update client';
     $updateClient->save();
     $deleteClient = new Permissions();
     $deleteClient->display_name = 'Delete client';
     $deleteClient->name = 'client-delete';
     $deleteClient->description = 'Permission to delete client';
     $deleteClient->save();
     /**
      * Tasks Permissions
      */
     $createTask = new Permissions();
     $createTask->display_name = 'Create task';
     $createTask->name = 'task-create';
     $createTask->description = 'Permission to create task';
     $createTask->save();
     $updateTask = new Permissions();
     $updateTask->display_name = 'Update task';
     $updateTask->name = 'task-update';
     $updateTask->description = 'Permission to update task';
     $updateTask->save();
     /**
      * Leads Permissions
      */
     $createLead = new Permissions();
     $createLead->display_name = 'Create lead';
     $createLead->name = 'lead-create';
     $createLead->description = 'Permission to create lead';
     $createLead->save();
     $updateLead = new Permissions();
     $updateLead->display_name = 'Update lead';
     $updateLead->name = 'lead-update';
     $updateLead->description = 'Permission to update lead';
     $updateLead->save();
 }