123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686 |
- <?php
- namespace app\models;
- use Yii;
- use yii\base\Model;
- use app\models\entity\ProjectsLocotech;
- use app\models\entity\Tasks;
- use app\models\entity\Tasktypes;
- use app\models\entity\Accounts;
- use app\models\CheckPointTypeModel;
- use app\models\CheckPointModel;
- use app\models\entity\Jobtypes;
- use app\models\entity\Commands;
- /**
- * This is the model class for table "s_regions".
- *
- * The followings are the available columns in table 's_regions':
- * @property integer $rg_id
- * @property string $rg_name
- */
- class TasksModel extends MainModel
- {
-
- public $createTasks;
- public $createTasksMessage;
- public $createType = [];
-
- public function GetTaskStatus($taskid)
- {
- $task = $this->GrabTask( $taskid );
- $parent = intval($task->parent_id);
- if ($parent > 0)
- return intval($task->status);
- else
- {
- $tasks = $this->GrabSubTasks( $taskid );
- $assigned = 0;
- $accepted = 0;
- $hold = 0;
- $done = 0;
- $lentasks = sizeof($tasks);
- foreach ($tasks as $task)
- {
- $status = intval( $task->status );
- switch ($status) {
- case 2:
- $assigned++;
- break;
- case 3:
- $accepted++;
- break;
- case 4:
- $hold++;
- break;
- case 5:
- $done++;
- break;
- }
- }
- if ($done == $lentasks && $lentasks > 0)
- {
- return 5;
- }
- elseif ($accepted > 0)
- {
- return 2;
- }
- elseif ($assigned > 0)
- return 2;
- else
- return 1;
- }
- }
-
- // работает
-
- public function GetTasksForProject($projectid, $status=0, $inactiveproject=0, $subs = 0)
- {
- global $link;
- // $taskstring = $this->GetTasksFromProjectString($projectid);
- $projectsLocotechEntity = ProjectsLocotech::findOne($projectid);
- $taskstring = $projectsLocotechEntity->tasks;
- if ( $inactiveproject != 0 ) {
- $countTaskEntity = Tasks::find()->where(['and',['id' => $taskstring],['or','status=2','status=3']])->count();
-
- if ( $countTaskEntity ) {
- $count = intval($countTaskEntity);
- if ( $count > 0 ) {
- echo "Found started tasks!";
- return;
- }
- }
- }
-
- if ( $subs > 0 ) {
- $tasksarr = explode(",", $taskstring);
-
- foreach ($tasksarr as $task_id)
- {
- $parent = $this->GrabTask($task_id);
- if ( $parent->status == $status ) {
- return $this->GrabSubTasks($task_id);
- }
- }
- }
- if ($status != 0) {
- $tasksEntity = Tasks::find()->where(['and', ['id' =>$taskstring],['status' => $status]])->all();
- } else {
- if( !empty($taskstring)) {
- $tasksEntity = Tasks::find()->where(['in', 'id', $taskstring ])->all();
- }
- }
-
- $ret = array();
- if ( !empty($tasksEntity) ) {
- foreach( $tasksEntity as $task){
- $tempArray = [];
- foreach($task as $item){
- $tempArray[] = $item;
- }
- array_push($ret, $tempArray);
- }
- }
- return $ret;
- }
-
-
- public function GetTasksFromProjectString($projectid)
- {
- $projectsLocotechEntity = ProjectsLocotech::findOne($projectid);
- $ret = array();
- if ($projectsLocotechEntity)
- {
- $ret = $projectsLocotechEntity->tasks;
- }
- return $ret;
- }
-
- public function GrabTask($task_id)
- {
- $tasksEntity = Tasks::findOne($task_id);
- if ( $tasksEntity ) {
- //$result = sizeof($tasksEntity);
- return $tasksEntity;
- }
- return null;
- }
-
- public function GrabSubTasks($parent_id)
- {
- $subtasks = array();
- $tasksEntity = Tasks::find()->where(['parent_id' => $parent_id])->all();
- foreach ( $tasksEntity as $task) {
- array_push($subtasks, $task);
- }
- return $subtasks;
- }
-
- // работает
-
- public function GrabTasktypes( $chooseSubtasks = "all" )
- {
- $companyId = Yii::$app->params['api']['companyId'];
- $tasktypesEntity = new Tasktypes();
-
- if ($chooseSubtasks == "subs") {
-
- $result = $tasktypesEntity::find()->where(['and','company' => $companyId,'main_task' => 0])->orderBy(['id' => DESC])->all();
- } else if ( $chooseSubtasks == "tasks" ) {
-
- $result = $tasktypesEntity::find()->where(['and','company' => $companyId,'main_task' => 1])->orderBy(['id' => DESC])->all();
- } else {
-
- $result = $tasktypesEntity::find()->where(['company' => $companyId])->orderBy(['id' => 'DESC'])->all();
-
- }
- if ( 0 == count($result) ) {
- return [];
- }
- return $result;
- }
-
-
- public function CreateTasks($tasktypesarr, $input_id=0)
- {
- global $link;
- // echo "CreateTasks $input_id";
- // print_r($tasktypesarr);
- // $query = mysqli_query($link, "select * from input_tables where id=".$input_id);
- // if ($res = mysqli_fetch_array($query)) {
- //
- // }
- $maintasks = array();
- foreach ($tasktypesarr as $tasktype_data)
- {
- if ($tasktype_data->main_task == '1')
- {
- $tasktype = $tasktype_data->id;
- // $tasktype_data = array_values($tasktypesarr)[0];//!!!! только первый эелмент берется
- // echo "subtasks ".$tasktype_data['subtasks']." tasktype ".$tasktype;
- $subtaskarr = explode(",", $tasktype_data->subtasks);
- // echo $action_data['name'] . "! Входная таблица " . $assign_id;
- $result = mysqli_query($link, "INSERT INTO tasks (type, status, priority, created, input_id) VALUES ($tasktype, 1, 0, NOW(), $input_id)"); //создание глобальной задачи
- if (mysqli_affected_rows($link) >0 )
- {
- $parent_id = mysqli_insert_id($link);
- array_push($maintasks, $parent_id);
- // $query1 = mysqli_query($link, "select MAX(id) from tasks");
- // if ($res1 = mysqli_fetch_row($query1)) {
- // $parent_id = $res1[0];
- //// echo "created parent_id ".$parent_id;
- // }
- $priority = 1;
- foreach ($subtaskarr as $sub) {
- $str = "insert into tasks (type, parent_id, priority, status, created, input_id) values ($sub, $parent_id, $priority, 1, NOW(), $input_id)";
- //echo "$str<br>";
- $sub_id = mysqli_insert_id($link);
- //создаем парентов
- $types = \CheckPointTypes\CheckPointType::GetCheckPointTypesByTask($sub);
- if (sizeof($types) > 0) {
- $q = mysqli_query($link, "select MAX(id) from tasks");
- if ($res = mysqli_fetch_row($q))
- {
- $myid = $res[0];
- foreach ($types as $typeID) {
- echo "create type " . $typeID['cp_type_id'];
- //var_dump($typeID['cp_type_id']);die();
- $cpt = \CheckPointTypes\CheckPointType::CreateFromID($typeID['cp_type_id']);
- if ($cpt != null)
- $cp = \CheckPoints\CheckPoint::CreateFromType($cpt, null, $myid+1);
- }
- }
- }
- mysqli_query($link, $str); //создание подзадач
- $priority++;
- }
- }
- }
- }
- if (sizeof($maintasks) > 0) {
- echo " <span style='color: green'>Задачи созданы для проекта $input_id!</span>";
- $taskstring = implode(",",$maintasks);
- AddTasksToProject($taskstring, $input_id);
- }
- else
- echo '<span style="color: red;"> Нет ни одной основной задачи!</span><br>';
- }
-
-
- // работает
-
- public function CreateTasksExtra($tasktypesarr, $input_id=0)
- {
- $checkpointModel = new CheckPointTypeModel();
- $tasksEntitySelect = new Tasks();
- $maintasks = array();
- foreach ( $tasktypesarr as $tasktype_data ) {
- if ( $tasktype_data->main_task == '1') {
- $tasktype = $tasktype_data->id;
- $subtaskarr = explode(",", $tasktype_data->subtasks);
-
- $testksEntity = new Tasks();
- $testksEntity->type = $tasktype;
- $testksEntity->status = 1;
- $testksEntity->priority = 0;
- $testksEntity->created = date("Y-m-d H:i:s");
- $testksEntity->input_id = $input_id;
- if ( $testksEntity->save() ) {
- $parent_id = $testksEntity->id;
- array_push($maintasks, $parent_id);
- $priority = 1;
- foreach ( $subtaskarr as $sub ) {
-
- if ( null == $sub ) {
- continue;
- }
-
- $testksEntitySub = new Tasks();
-
- $testksEntitySub->type = $sub;
- $testksEntitySub->parent_id = $parent_id;
- $testksEntitySub->priority = $priority;
- $testksEntitySub->status = 1;
- $testksEntitySub->created = date("Y-m-d H:i:s");
- $testksEntitySub->input_id = $input_id;
- $testksEntitySub->save();
- $sub_id = $testksEntitySub->id;
-
- $types = $checkpointModel::GetCheckPointTypesByTask($sub);
-
- if (count($types) > 0) {
- $id = Tasks::find()->max('id');
- $tasksEntity = Tasks::findOne($id);
- if ( $tasksEntity ) {
- $myid = $tasksEntity->id;
- foreach ($types as $typeID) {
- $this->message['createType'][] = $typeID->cp_type_id;
- $cpt = $checkpointModel->CreateFromID($typeID->cp_type_id);
- if ($cpt != null){
- $cp = CheckPointModel::CreateFromType($cpt, null, $myid+1);
- }
- }
- }
- }
- $priority++;
- }
- }
- }
- }
- if (sizeof($maintasks) > 0) {
- //echo " <span style='color: green'>Задачи созданы для проекта $input_id!</span>";
- $this->createTasks = $input_id;
- $taskstring = implode(",",$maintasks);
- $this->AddTasksToProject($taskstring, $input_id);
- } else {
- //echo '<span style="color: red;"> Нет ни одной основной задачи!</span><br>';
- $this->message['createTasksMessage'] = 'Нет ни одной основной задачи!';
- }
- }
- // работает
-
- public function AddTasksToProject($taskstring, $input_id)
- {
- $projectsLocotechEntity = ProjectsLocotech::findOne($input_id);
- $projectsLocotechEntity->tasks = $taskstring;
- $projectsLocotechEntity->update();
- }
-
-
- public function TasksAssign($task_id, $execute, $project_id = 0)
- {
- //1 ищем акки без тасков
- //2 определяем должности акков
- //3 определяем доступные задачи по должностям
- //2 берем активные (невыданные) задачи
- //2 выдаем подходящим аккам их подзадачи
- //tofix: удаление подзадач глобалов похоже не происходит на каком-то этапе
- //tofix: выдавать подзадачи с глобалами
- //tofix: подзадачи согласно проекту, а не все подряд подходящие сотруднику
- //global $link, $companyID;
- $accountModel = new AccountModel();
-
- $companyID = Yii::$app->params['api']['companyId'];
- $freeaccounts = array();
- $accountnames = array();
- //get free accs (without active tasks)
- $accountsEntity = Accounts::find()->where(['active_task_ids' => ''])->all();
- //$str = "select * from accounts where active_task_ids = ''";
- //$query1 = mysqli_query($link, $str);
- $online_counter = 0;
-
- foreach ($accountsEntity as $account) {
- $last_seen_mobile = $account->last_seen_mobile;
-
- $online_mobile = $accountModel->OnlineAccountCheck($last_seen_mobile);
-
-
- if (!$online_mobile)
- continue;
- else
- $online_counter++;
- //var_dump($account->id);
- $jobtypes = [];
- foreach ($account->accountsJobtypes as $value) {
- $jobtypes[] = $value->jobtype_id;
- }
-
- //$jobtypes = explode(",",$account->jobtypes);
- $acc_id = $account->id;
- $accountnames[$acc_id] = $account->name;
- $freeaccounts[$acc_id] = $jobtypes;
-
- }
- if ($online_counter == 0)
- {
- $this->message['TasksAssign'] = 'Задачи не выданы в работу! Нет подходящих исполнителей онлайн';
- //echo "<h3><span style='color:red'>Задачи не выданы в работу! Нет подходящих исполнителей онлайн</span></h3>";
- }
- $assigned_tasks = array();
- $accsused = array();
- if ($task_id =='' || !isset($task_id))
- {
- if ($project_id == 0) {
- $opentasks = $this->GrabOpenTasks('subtasks'); //array of mysql res, tasks status=1
- } else {
- $opentasks = $this->GetTasksForProject($project_id, 1, 1, 1);
- }
- } else {
- //$opentasks = GrabTasksFromGlobal($task_id);
- $opentasks = Tasks::find()->where(['and', 'parent_id = '. $task_id , 'status = 1'])->all();
- }
- // echo 'opentasks len '.sizeof($opentasks);
- // echo 'opentasks '.implode(",",$opentasks);
- // echo 'subtasks '.sizeof(array_values($subtasks));
- // print_r($opentasks);
- //echo '<br>';
- $assigned_accs = array();
- //account array with available jobtype list
- //$i=0;
- foreach ($freeaccounts as $acc_id => $jobtypes)
- {
- $parent_id = 0;
- $assigned_accs[$acc_id] = array();
- if (!in_array($acc_id, $accsused))
- {
- // echo '<br><b>free account: acc_id ' . $acc_id.'</b>';
- $jobtasks = array();
- $jobtypes = array_filter($jobtypes);
- // if($i == 6){print_r($jobtypes); die();}
- //$i++;
-
- foreach ($jobtypes as $job_type) {
- $jobtasks = array_merge($jobtasks, $this->GrabJobTaskTypes($job_type));
- }
-
- //echo '<br>jobtasks ' . implode(",", $jobtasks).'<br>';
- foreach ($opentasks as $opentask)
- {
- $taskid = $opentask->id;
- $exists = array_key_exists($taskid, $assigned_tasks);
- //echo ' key exists '.$taskid.' '.($exists == true).'<br>';
-
- if (!$exists) {
- // echo '!exists';
- if ( in_array( $opentask->type, $jobtasks ) ) {
- // echo ' job available task type '.$opentask['type'].' ';
- $pid = intval($opentask->parent_id);
- if ($pid != $parent_id && in_array($acc_id, $accsused)) {//parent change = stop for this acc
- //echo "cont1";
- continue;
- }
- else
- $parent_id = $pid;
- $parent = $this->GrabTask($parent_id);
- $parenttype = $parent['type'];
- $tasktype = intval($opentask->type);
- // echo "tt $tasktype";
- $tgrab = Tasktypes::findOne($parenttype);//GrabTasktype($parenttype);
- //$tsize = sizeof($tgrab);
- if ($tsize == null)
- $this->DeleteTasksByType($parenttype);
- //фикс блуждающих подзадач без парента и тасктипа парента
- if (($parent_id > 0 && $this->GrabTask($parent_id) == null) || $tsize == 0)
- {
- //echo "skip2 id $parent_id<br>";
- continue;
- }
-
- $res = $this->Assign($accsused, $assigned_tasks, $assigned_accs, $acc_id, $taskid, $execute);
-
- }
- }
- }
- if ($execute)
- {
- $parent_updated = false;
-
- foreach ($assigned_accs as $acc)
- {
-
- if (sizeof($assigned_accs[$acc_id]) == 0)
- continue;
- $tasks = implode(',', $acc);
- foreach ($acc as $tsk) {
- if (in_array($tsk, $assigned_accs[$acc_id])) {
-
- $tasksEntity = Tasks::findOne($tsk);
- $tasksEntity->status = 2;
- $tasksEntity->assignees_arr = $acc_id;
- $tasksEntity->update(); //создание подзадач
- ElasticLog::command((int)$task_id, 'Назначение');
- }
- }
- if ($parent_id != 0) {
- $tasks = $parent_id.','.$tasks;
- }
- $accountsEntity = Accounts::findOne($tsk);
- $accountsEntity->active_task_ids = $tasks;
- $accountsEntity->update(); //создание подзадач
-
- if ($parent_id != 0 && !$parent_updated) {
- $parent_updated = true;
-
- $tasksEntity = Tasks::findOne($parent_id);
- $tasksEntity->status = 2;
- $tasksEntity->update();
-
- $proj = getProjectByTask($parent_id);
-
- $projectsLocotechEntity = ProjectsLocotech::findOne($proj->id);
- $projectsLocotechEntity->status = 2;
- $projectsLocotechEntity->update();
- }
- }
- }
- }
- }
- //echo 'Assigned_tasks len '.sizeof($assigned_tasks).' opentasks len '.sizeof($opentasks);
- //echo "Задачи назначены ".sizeof($accsused)." сотрудникам: ";
- // foreach ($accsused as $acc)
- // {
- // echo $accountnames[$acc].", ";
- // }
- return $accsused;
- }
-
- public function GrabOpenTasks($flag = 'all') {
-
- if ($flag == 'subtasks') {
- $tasksEntity = Tasks::find()->where(['and','status = 1', 'parent_id > 0' ]);
- } else {
- $tasksEntity = Tasks::find()->where(['and','status = 1', 'parent_id = 0' ]);
- }
- $alltasks = array();
- foreach ($tasksEntity as $task) {
- $id = $task->id;
- $parent_id = $task->parent_id;
-
- if ($flag == 'subtasks' && GrabTask($parent_id) == null)
- {
- echo "parent_id skip $parent_id<br>";
- continue;
- }
- array_push($alltasks, $task);
- if ($flag == 'all') { //subtasks in main select
- $subs = $this->GrabSubTasks($id);
- $alltasks = array_merge($alltasks, $subs);
- }
- }
- return $alltasks;
- }
-
-
- public function GrabJobTaskTypes($job_id)
- {
- $jobtypesEntity = Jobtypes::findOne($job_id);
- $subtaskarr = array();
- /*
- foreach ( $jobtypesEntity->tasktype as $task ) {
-
- $subtaskarr[] = $task->id;
- }
- */
- foreach ( $jobtypesEntity->jobtypesTasktypes as $task ) {
-
- $subtaskarr[] = $task->tasktype_id;
- }
-
- return array_filter($subtaskarr);
- }
-
-
- public function DeleteTasksByType($task_type, $full=true)
- {
-
- $tasksEntity = Tasks::find()->where(['type' => $task_type])->all();
-
- foreach ( $tasksEntity as $task ) {
- $this->DeleteTask($task->id);
- }
- }
-
- public function DeleteTask($task_id, $full = true)
- {
- if ( $full ) {
- $tasksEntity = Tasks::find()->where(['parent_id' => $task_id])->all();
- foreach ($tasksEntity as $sub) {
- $this->DeleteTask($sub->id, false);
- }
- }
-
- $accid = Tasks::findOne($task_id);//GetAccountFromTask($task_id);
- $this->ClearTasksFromAccount($accid->assignees_arr);
-
- $tasksEntity = Tasks::findOne($task_id);
- $tasksEntity->delete();
- }
-
- public function ClearTasksFromAccount($acc_id, $debugtext = true)
- {
- $accountsEntity = Accounts::findOne($acc_id);
- if ( $accountsEntity ) {
- $mytasks = explode(',',$accountsEntity->active_task_ids);
- }
- $tasksacc = $this->GrabTasksForAccount($acc_id);
- if ( sizeof($tasksacc) > 0 && $debugtext ) {
- //echo "<span style='color:red'><b> Задачи аккаунта $acc_id очищены!</b></span>";
- $commandsEntity = new Commands();
- $commandsEntity->account_id = $acc_id;
- $commandsEntity->cmd = "21";
- $commandsEntity->created = date('Y-m-d H:i:s');
- $commandsEntity->save();
- }
- foreach ( $tasksacc as $mtask ) {
- $tasksEntity = Tasks::findOne($mtask->id);
- $tasksEntity->status = 1;
- $tasksEntity->control_map_checked = 0;
- $tasksEntity->accepted_time = null;
- $tasksEntity->confirm_data = '';
- $tasksEntity->finished_time = null;
- $tasksEntity->assignees_arr = '';
- $tasksEntity->update();
- }
- if ( null != $acc_id ) {
- $accountEntity = Accounts::findOne($acc_id);
- $accountEntity->active_task_ids = '';
- $accountEntity->update();
- }
- }
-
-
-
- public function GrabTasksForAccount($acc_id, $status=0)
- {
- if ( $status != 0 ) {
- $tasksEntity = Tasks::find()->where(['assignees_arr' => $acc_id])
- ->andWhere(['status' => $status])
- ->andWhere(['<' , 'status', '5'])
- ->all();
- } else {
- $tasksEntity = Tasks::find()->where(['assignees_arr' => $acc_id])
- ->andWhere(['<' , 'status', '5'])
- ->all();
- }
- return $tasksEntity;
- }
-
- public function Assign(&$accsused, &$assigned_tasks, &$assigned_accs, $acc_id, $taskid, $execute=false)
- {
-
- if ( !in_array($acc_id, $accsused) ) {
- array_push($accsused, $acc_id);
- }
- $assigned_tasks[$taskid] = $acc_id;
-
- array_push($assigned_accs[$acc_id],$taskid);
- return false;
- }
-
- public function getProjectByTask($taskId)
- {
- $tasksEntity = Tasks::findOne($taskId);
- if ( $tasksEntity ) {
- return ProjectsLocotech::findOne($tasksEntity->input_id);
- }
- return null;
- }
-
- }
|