index_t = strtotime(date("Y-m-d H:i:s")); $logEtn->section = 3; //$this->logEtn = $logEtn; //$log = new LoggerFile(); $log = new LoggerDB(); $this->logger = new MappingHandlerModel($log); return true; } // запускается периодически через крон public function actionGetworks($company) { //$this->sectionList(); //exit; $this->company = $company; $GWparams = [ 'url' => 'http://' . Yii::$app->params['api']['domain'].'/Thingworx/Things/2050UserLibraryExp/Services/my_works', //'url' => 'http://devplatform.digitaldepot.ru:8085/Thingworx/Things/SMoPPIntegrationLibrary/Services/getUserWorks', 'param' => '', 'login' => 'ПройдаковИА', 'pass' => 'Ip15351112' ]; // список сотрудников онлайн $onlineUser = $this->getOnlineMobileUser($company); if( 0 == count($onlineUser)) { return 'Нет сотрудников онлайн'; } //$this->logger->setLog('ID пользователя => ' . (int)$_SESSION["id"]); //$this->logger->indx = time(); $this->logger->setLog( "\n=================== СТАРТ МЕППИНГА ==================================\n"); $this->logger->setLog( date("Y-m-d H:i:s") . "\n"); $mainModel = new MainModel(); // для каждого сотрудника онлайн запускаем проекты если они еще не запущены $setOnlineWorkers = []; $this->logger->setLog( "Колличество cотрудников онлайн :" . count($onlineUser) ."\n"); foreach($onlineUser as $user) { $this->logger->indx = $user->uuid; //echo get_class($this->logger); $buisy = $this->buisyEmployee($user); //var_dump($user->id,$user->name ); continue; if( $buisy || ('' == $user->uuid and null == $user->uuid )) { var_dump('Занят => '.$user->name,'
'.$user->id); //$this->logger->setLog( "\n Выпоняет задание. Работы не выдались. \n"); //continue; } $GWparams['param'] = $user->uuid; $responseMyWorks = $mainModel->curlRequest2($GWparams); $listWorks2 = json_decode($responseMyWorks,true);//var_dump($buisy,$user->id);continue; $listWorks2 = $this->prepareListWorks($listWorks2); $this->insertEippJob($listWorks2); //foreach ( $listIssetWorks3 as $work) { !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //echo '
';
                //var_dump($user->name);
                //var_dump($listWorks2);
                //echo '
'; foreach ( $listWorks2['data'] as $work) { foreach( $work['workers'] as $key => $uuid) { $this->attachWorkUser($work['id_work'],$uuid['id']); } $asusgJob2LaunchEntity = AsusgJob2Launch::find()->where(['asusg_job_uuid' => $work['id_work']])->andWhere(['like','employees_uuid',$user->uuid])->one(); if ( null != $asusgJob2LaunchEntity) { continue; } //$this->workDetail( $user->uuid, $work['id_work'] ); $mappingapiModel = new \app\models\MappingapiModel(); $this->datailWorkArray[$work['id_work']] = $mappingapiModel->workDetail($user->uuid,$work['id_work']); foreach( $this->datailWorkArray[$work['id_work']]['workers_uuid'] as $uuid) { $setOnlineWorkers[] = $uuid; } } //$this->logger->setLog( $mappingapiModel->prepareLogString."\n"); // !!!! //$this->logger->setLog( "Вот это сейчас должен получить работу :" . $user->id . "( ".$user->name." )\n"); } $setOnlineWorkers = array_unique($setOnlineWorkers); $onlineUserModificate = \app\models\entity\Accounts::find()->where(['in','uuid',$setOnlineWorkers])->andWhere(['company' =>$company])->all(); $this->logger->setLog( "Колличество cотрудников онлайн для них есть работа ( с напарниками ):" . count($setOnlineWorkers)."\n"); //var_dump($onlineUserModificate); foreach($onlineUserModificate as $user) { $this->logger->indx = $user->uuid; $this->user = $user; //var_dump($user->name,'
'); //continue; $this->logger->setLog( "\n Сотрудник =>".$user->name.". Его uuid = ".$user->uuid." \n" ); $buisy = $this->buisyEmployee($user); if( $buisy || ('' == $user->uuid and null == $user->uuid )) { //$this->logger->setLog("\n Выпоняет задание. Работы не выдались. \n" ); continue; } $this->issetLaunch = false; $GWparams['param'] = $user->uuid; ElasticLog::eipp($GWparams, 'my_works', 0); $listWorks2 = $mainModel->curlRequest2($GWparams); $unixTime = time(); LogEippResponse::addLog($unixTime.'gw'. $user->id ,$listWorks2,'Получение работ от ЕИПП'); ElasticLog::eipp($listWorks2, 'my_works', 0, false); $this->logger->setLog( "\nMY_WORK =====>\n" ); $this->logger->setLog("Параметры: \n user_id =>". $GWparams['param'] .".\n"); $this->logger->setLog( "Строка запроса : \n " . $GWparams['url'] .".\n"); $this->logger->setLog("Вот тут можно посмотреть что ЕИПП прислал по запросу http://dev.prmsys.net/api/mappinghandler/eippresponse?indx=".$unixTime."\n"); $this->logger->setLog("MY_WORK ======>\n\n"); $listWorks2 = json_decode($listWorks2,true); $listWorks2 = $this->prepareListWorks($listWorks2); /// НЕТ ДВУХ ПОЛЕЙ ["section_num"] ["section_DK"] //continue; //$this->logEtn->addlogText('','sdfsdfsdf'); $this->logger->setLog("Колличество работ из еипп: ". count($listWorks2['data'])." \n Cотрудник:" . $user->id . "( ". $user->name ." )\n"); echo "Колличество работ из еипп: ". count($listWorks2['data'])." \n Cотрудник:" . $user->id . "( ". $user->name ." )\n"; $listIsabsentWorks2 = $this->Getisabsentworksjp($listWorks2); // вновь утвержденный план 1 | вернет список работ кот нет ( в JobPlan ) $listIssetWorks3 = $this->Getissetworksjp($listWorks2); $this->logger->setLog('Колличество работ из еипп ( сверхциклвая ): '. count($listIsabsentWorks2)."\n"); $this->logger->setLog('Колличество работ из еипп ( цикловая ): '. count($listIssetWorks3)."\n"); $this->logger->setLog("\n СВЕРХЦИКЛОВЫЕ \n\n"); var_dump('Колличество работ из еипп ( цикловая ): '. count($listIssetWorks3)."\n"); var_dump('Колличество работ из еипп ( сверхциклвая ): '. count($listIsabsentWorks2)."\n"); $addJob2launch2 = $this->addJob2launch2($listIsabsentWorks2,$user); $this->logger->setLog("\n ЦИКЛОВЫЕ \n\n"); $addJob2launch3 = $this->addJob2launch3($listIssetWorks3,$user); if(!empty($this->listWorkForExtraArray)){ $this->logger->setLog("\n СВЕРХЦИКЛОВЫЕ (ДОП) \n\n"); $this->addJob2launch2($this->listWorkForExtraArray,$user); $this->listWorkForExtraArray = []; } if (!$this->issetLaunch) { continue; } $this->logger->setLog("Интеграция сверхцикловых работ прошла без падений!"); $this->logger->setLog("=====================================================\n\n"); //echo '
';
                //var_dump($user->id);
                ///var_dump($listWorks2);
                
                //echo '
'; } $this->fixPriority(1); $this->clearEmptyProjects(); return true;//$listWorks; } public function actionDojob() { Yii::$app->db->createCommand('update `accounts_internal` set `last_seen_mobile` = NOW() where id in (351,349,350)')->execute(); } public function actionDopro() { $JobPlanEntitty = AsusgJobplan::find()->where(['name' => 'Тормозное и пневматическое оборудование после ремонта испытать , отрегулировать согласно инструкции'])->one(); // 1204 1567 $jsusgJob2CommandEntity = AsusgJob2Command::find()->where(['asusg_job_id' => $JobPlanEntitty->id])->all(); foreach($jsusgJob2CommandEntity as $job) { echo '
';               
         var_dump('3 =>'. $job->id, $job->asusg_job_id);
        var_dump('3 =>'. $job->jobplantie->id);
        echo '
'; } exit; } public function actionMktest() { //if ( $this->datailWorkArray[$work['id_work']]['measurements'] ) { Yii::$app->params['countPriority'] = ((2*100)-1); var_dump(Yii::$app->params['countPriority']); $this->logger->setLog('приоритет '.((2*100)-1)); $paramsMeaserm = ['input_id' => 7078, 'assignees_arr' => 333, 'work' => 'c57839e6-49ed-4791-9353-925fc2d737b8','stage' =>0, 'parent_id' => 137340 ,'stage_type' => 'доремонтный','asusg_job_mapped_id' => 20456]; Yii::$app->params['api']['mesrmntParam'] = $paramsMeaserm; MappingapiModel::workMeasurements('c57839e6-49ed-4791-9353-925fc2d737b8','c57839e6-49ed-4791-9353-925fc2d737b8'); //} } public function actionProctest() { $procedureModel = new ProcedureModel(); $procedureModel->asusg_build_and_start_project_auto(27,210); } public function Getisabsentworksjp( $listWorks = null){ $result = []; if ( null == $listWorks) { return false; } foreach( $listWorks['data'] as $work) { $asusgJobPlan = AsusgJobPlan::find()->where(['name' => $work['work_name']])->one(); if ( null == $asusgJobPlan ){ $result[] = $work; } } return $result; } public function Getissetworksjp( $listWorks = null){ $result = []; if ( null == $listWorks) { return false; } foreach( $listWorks['data'] as $work) { $asusgJobPlan = AsusgJobPlan::find()->where(['name' => $work['work_name']])->one(); if ( null != $asusgJobPlan ){ $result[] = $work; } } return $result; } public function getOnlineMobileUser($company){ $result = []; $accountsEntity = \app\models\entity\Accounts::find()->where(['company' => $company])->all(); foreach ($accountsEntity as $account) { //var_dump($account->id,'
'); $last_seen_mobile = ( null != $account->last_seen_mobile )? new \DateTime($account->last_seen_mobile): $account->last_seen_mobile ; $online_mobile = $this->OnlineAccountCheck($this->TimeString($last_seen_mobile)); //var_dump(( !$online_mobile ),'
'); if ( !$online_mobile ){ continue; } $result[] = $account;//['id' => $account->id, 'uuid' => $account->uuid]; } return $result; } public function OnlineAccountCheck($last_seen) { $last_seen = date($last_seen); $time = (time()-strtotime($last_seen)); //var_dump($time,' <=', Yii::$app->params['onlineMobileTimeoutSeconds'],'
'); if ($time <= Yii::$app->params['onlineMobileTimeoutSeconds']) return true; return false; } public function TimeString($timeobj) { if ($timeobj != null) return $timeobj->format('d.m.Y H:i'); //return date('d.m.Y H:i', $timeobj); } public function getProjectType($repairName,$serieName) { $result = null; $repairtypesEntity = Repairtypes::findOne(['name' => $repairName]); $locomotiveSeriesEntity = LocomotiveSeries::findOne(['name' => $serieName]); $asusgProjectTypeEntity = AsusgProjectType::findOne(['repair_type' => $repairtypesEntity->id , 'loco_serie_id' => $locomotiveSeriesEntity->id]); if ( null != $asusgProjectTypeEntity->id ) { $result = $asusgProjectTypeEntity->id; } return $result; } public function addJob2launch2($listWorks,$user) { $this->logger->indx = $this->user->uuid; foreach ( $listWorks as $work) { $this->logger->header = $work['id_work']; Yii::$app->params['countPriority']= 1; $dwResult = $this->datailWorkArray[$work['id_work']]; $this->logger->setLog("Название работы:". $work['work_name']. ".\n UUID работы: " . $work['id_work'] . "\n\n"); $queueModel = new QueueModel(); $this->logger->setLog("\n 1. ДОБАВЛЕНИЕ В LAUNCH \n\n"); $asusgJob2LaunchEntity = AsusgJob2Launch::findOne(['asusg_job_uuid' => $work['id_work']]); $this->logger->setLog("\n AsusgJob2Launch = " . count($asusgJob2LaunchEntity). " id work = " . $work['id_work'] . "\n"); $this->addTypeWork($work['id_work'], 0); $let = mb_substr($work["section_lit"], -1); if( null != $let and !in_array($let,['А','Б','В']) ) { $let = 'А'; } //if( null == $tasktypesEntity->id ) { // var_dump(( null != $let), (!in_array($let,['А','Б','В']))); // exit; //} // ВАЖНО ПОНИМАТЬ !!!! // если проект для такой работы уже есть, его создавать нельзя // но можно прикреплять к нему задачи. Сотрудник который зашел первый получает и замеры и тмц и работы // тот кто зашел вторым получает только работы. //$mappingapiModel = new \app\models\MappingapiModel(); //$dwResult = $mappingapiModel->workDetail($user->uuid,$work['id_work']); //echo "
"; 
            //var_dump($user->id);
            //var_dump($work['work_name']);
            //var_dump($dwResult["hw_measurements_status"]);
            //var_dump($asusgJob2LaunchEntity->id);
            //echo "
"; //continue; $projtype = $this->getProjectType($work["repair_name"],$work["eq_serie"]); $switcher = $asusgJob2LaunchEntity; if ( null == $switcher) { $this->logger->setLog("\n switcher = null \n"); $resultArr = []; $asusgJob2LaunchEntity = new AsusgJob2Launch(); $asusgJob2LaunchEntity->asusg_jobplan_id = Yii::$app->params['supercycleplan']; $asusgJob2LaunchEntity->asusg_employee_id1 = $user->id; $asusgJob2LaunchEntity->asusg_job_uuid = $work['id_work']; $asusgJob2LaunchEntity->employees_uuid = $user->uuid; $asusgJob2LaunchEntity->section_uuid = $work["section_id"]; $asusgJob2LaunchEntity->asusg_project_id = 0; $asusgJob2LaunchEntity->job_order = 0; $asusgJob2LaunchEntity->time_limit = $dwResult['time_limit']; $asusgJob2LaunchEntity->outfit = $dwResult['outfit']; $asusgJob2LaunchEntity->name = $work['work_name']; $asusgJob2LaunchEntity->section_name = $work["section_lit"]; //$asusgJob2LaunchEntity->asusg_projecttype_id = 0; $asusgJob2LaunchEntity->asusg_projecttype_id = $projtype; if (!$asusgJob2LaunchEntity->save()) { $this->logger->setLog('в Job2launch не добавилась работа => "'. $work['work_name']. '" Добавление работ будет пропущено так как такая запись уже есть.'); continue; } $this->issetLaunch = true; //$this->logger->setLog($this->prepareLogString); //$this->prepareLogString = ''; $this->logger->setLog('в Job2launch была добавлена работа => "'. $work['work_name'].'"'); /// сначала генерю проект $projId = $this->generateProject($work); // работа еще нет нужно получить проект /// сначала генерю проетк } else { $this->logger->setLog("\n switcher != null \n"); $userUuidArr = explode(',', $asusgJob2LaunchEntity->employees_uuid); //var_dump("1"); if ( in_array( $user->uuid , $userUuidArr)) { // если сотрудник уже привязан к лаунчу $this->logger->setLog('сотрудник '.$user->name .' ('.$user->id.') уже привязан к лаунчу'. $asusgJob2LaunchEntity->id); continue; } else { $asusgJob2LaunchEntity->employees_uuid .= ','. $user->uuid; $asusgJob2LaunchEntity->save(); $this->logger->setLog('сотрудники ('.$asusgJob2LaunchEntity->employees_uuid.') привязаны к лаунчу'. $asusgJob2LaunchEntity->id); } //var_dump("2"); $projId = $this->getCreateProject($work); // работа уже есть нужно получить проект //continue; /* $this->prepareLogString .= "ВОТ ТУТ Я ХОТЕЛ ПОЛУЧИТЬ ИД ПРОЕКТА ЧЕРЕЗ ЗАДАЧУ( launch_id = ".$asusgJob2LaunchEntity->id.") => " . $asusgJob2LaunchEntity->tasks->id .", ВОТ ЧТО ПОЛУЧИЛ => " . $asusgJob2LaunchEntity->tasks->input_id ."!\n"; $projId = $asusgJob2LaunchEntity->tasks->input_id; */ $this->logger->setLog("ВОТ ТУТ Я ХОТЕЛ ПОЛУЧИТЬ ИД ПРОЕКТА ЧЕРЕЗ ЗАДАЧУ( launch_id = ".$asusgJob2LaunchEntity->id.") => " . $asusgJob2LaunchEntity->onetask->id .", ВОТ ЧТО ПОЛУЧИЛ => " . $asusgJob2LaunchEntity->onetask->input_id ."!\n"); //var_dump("3"); //$projId = $asusgJob2LaunchEntity->onetask->input_id; //if ( null == $projId ) { // $input_idTasks = Tasks::find()->where(['asusg_job_mapped_id' => $asusgJob2LaunchEntity->id])->andWhere(['IS NOT','input_id', null])->one(); // $this->prepareLogString .= "ВОТ ТАК ЧЕРЕЗ ЗАПРОС input_id => ".$input_idTasks->input_id."!\n"; // $projId = $input_idTasks->input_id; //} } $this->createProjects[] = $projId; /////////////// ДОБАВЛЕНИЕ ЗАДАЧИ $this->logger->setLog("\n 3. ДОБАВЛЕНИЕ ЗАДАЧИ \n\n"); $this->logger->setLog("\n Метка 1.1 \n"); $tasktypesEntity = Tasktypes::find()->where(['name' => 'Секция '.$let.', задача','company' => $this->company])->one(); $this->logger->setLog("\n Метка 1.2 (типи задачи ".$tasktypesEntity->id.")\n"); // $tasksEnt = Tasks::find()->where(['parent_id' => 0,'asusg_job_mapped_id' => $asusgJob2LaunchEntity->id,'assignees_arr' => $user->id])->one(); $this->statusMaintask = 0; $mainTaskId = $this->getIssetMainTask($work,$user); $isCloseMaintask = false; //var_dump('Задача = '.$mainTaskId); //var_dump($work["section_lit"] . "\n" . $work["outfit"] . ': ' . $work['work_name'] . "\n" . $dwResult['workers']); if ( $mainTaskId ) { // !!!!!!!!!! $this->logger->setLog("\n Задача для " . $work["section_lit"] . " уже есть ". $mainTaskId . "\n\n"); if( 5 == $this->statusMaintask ) { $isCloseMaintask = true; } //var_dump('Такая задача уже есть' . $mainTaskId); //continue; } else { $this->logger->setLog("\n Метка 1.3 \n"); //$this->logger->setLog($this->prepareLogString); //$this->prepareLogString = ''; $tasksEntity = new Tasks(); $tasksEntity->parent_id = 0; $tasksEntity->input_id = $projId; $tasksEntity->status = 2; $tasksEntity->type = $tasktypesEntity->id; $tasksEntity->assignees_arr = $this->user->id; $tasksEntity->preferred_assignee = $this->user->id; $tasksEntity->created = date("Y-m-d H:i;s"); $tasksEntity->asusg_job_mapped_id = $asusgJob2LaunchEntity->id; $tasksEntity->mapping_comment = $work["outfit"] . ': ' . $work['work_name']; $tasksEntity->text = $work["section_lit"] . "\n" . $work["outfit"] . ': ' . $work['work_name'] . "\n" . $dwResult['workers']; $this->logger->setLog("\n Метка 1.4 \n"); $this->logger->setLog(json_encode($tasksEntity->attributes)); $this->logger->setLog('валидация =>'.json_encode($tasksEntity->validate())); $this->logger->setLog(json_encode($tasksEntity-> getErrors())); if($tasksEntity->save()) { $mainTaskId = $tasksEntity->id; $this->logger->setLog('в Tasks была добавлена ЗАДАЧА => "'. $work['work_name'] . '" id => '.$tasksEntity->id); } else { $this->logger->setLog('в Tasks была НЕ добавлена ЗАДАЧА => "'. $work['work_name']); } } //var_dump('switcher = ' . $switcher->id,$user->id); echo '
'; $this->logger->setLog("\n Метка 3 \n"); //$countPriority = 1; if ( null == $switcher) { ///////////////// ДОБАВЛЕНИЕ ТМЦ //$mappingapiModel = new \app\models\MappingapiModel(); //var_dump($user->id-uuid,$work['id_work']); //$tmcString = $mappingapiModel->workDetail($user->uuid,$work['id_work']); $this->logger->setLog("\n ДОБАВЛЕНИЕ ТМЦ " . strlen($dwResult['tmcString']) . "\n"); if ( '' != $dwResult['tmcString']) { $tasksEntity3 = new Tasks(); $tasksEntity3->parent_id = $mainTaskId; $tasksEntity3->status = 2; $tasksEntity3->priority = Yii::$app->params['tmcPriority']; // $tasksEntity2->input_id = $job->asusgJob2Launch->asusg_project_id; $tasksEntity3->created = date("Y-m-d H:i;s"); $tasksEntity3->type = 2159; $tasksEntity3->assignees_arr = $this->user->id; $tasksEntity3->preferred_assignee = $this->user->id; $tasksEntity3->asusg_job_mapped_id = $asusgJob2LaunchEntity->id; $tasksEntity3->text = $dwResult['tmcString']; $tasksEntity3->mapping_comment = $dwResult['tmcString']; $tasksEntity3->input_id = $projId; if ( $tasksEntity3->save()) { //$query3 = "call asusg_add_checkpoints_to_task(" . $user->id . ",'" . $tasksEntity3->id . "')"; //$resProc = Yii::$app->db->createCommand($query3)->query(); $logResProc = 'false'; if ($resProc){ $logResProc = 'true'; } $this->logger->setLog('в Tasks была добавлена КОМАНДА => "'. $work['work_name'] . '" id => '.$tasksEntity3->id. ' процедура => ' . $logResProc . ' приоритет =>' . Yii::$app->params['countPriority']); } else { $this->logger->setLog('в Tasks была НЕ добавлена КОМАНДА => "'. $work['work_name'] . '" id => '.$tasksEntity3->id ); } Yii::$app->params['countPriority']++; } /////////////////// ///////////////// ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 0 $this->logger->setLog( "\n 4. ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 0 \n"); //if ( Yii::$app->params['api']['hw_msrmnt_stat'][ $dwResult["hw_measurements_status"] ]) { // выполнение hw_measurements_status = waiting if ( $this->datailWorkArray[$work['id_work']]['measurements'] == null) { $priority = $queueModel->insertExtraPlan($work,$asusgJob2LaunchEntity,$user->id); Yii::$app->params['countPriority'] = $priority; $paramsMeaserm = ['input_id' => $projId, 'assignees_arr' => $user->id, 'work' => $work,'stage' => 0, 'parent_id' => $mainTaskId , 'stage_type' => 'доремонтный','asusg_job_mapped_id' => $asusgJob2LaunchEntity->id ]; Yii::$app->params['api']['mesrmntParam'] = $paramsMeaserm; MappingapiModel::workMeasurements($work,$user->uuid); } /////////////////// } /////////////// НА РЕМОНТ $this->logger->setLog("\n 5. ДОБАВЛЕНИЕ НА РЕМОНТ \n"); $priority = $queueModel->insertExtraPlan($work,$asusgJob2LaunchEntity,$user->id); //$queueModel->execute($work,$user->uuid); $tasksEntity2 = new Tasks(); $tasksEntity2->parent_id = $mainTaskId; $tasksEntity2->status = 2; $tasksEntity2->priority = $priority; $tasksEntity2->created = date("Y-m-d H:i;s"); $tasksEntity2->type = Yii::$app->params['supercycletype']; $tasksEntity2->assignees_arr = $this->user->id; $tasksEntity2->preferred_assignee = $this->user->id; $tasksEntity2->asusg_job_mapped_id = $asusgJob2LaunchEntity->id; $tasksEntity2->text = $work["eq_serie"] . ' '.$work["section_lit"] . ', '. $work["outfit"] . ': ' . $work['work_name']; $tasksEntity2->input_id = $projId; $tasksEntity2->mapping_comment = $work["outfit"] . ': ' . $work['work_name']; if ( $tasksEntity2->save()) { if ( $isCloseMaintask ) { $updateTasks = Tasks::findOne($mainTaskId); $updateTasks->status = 2; $updateTasks->save(); } //Yii::$app->params['countPriority']++; /////////////////// //$query3 = "call asusg_add_checkpoints_to_task(" . $user->id . ",'" . $tasksEntity2->id . "')"; //$resProc = Yii::$app->db->createCommand($query3)->query(); /////////////////// $this->logger->setLog('в Tasks была добавлена КОМАНДА => "'. $work['work_name'] . '" id => '.$tasksEntity2->id . ' приоритет =>' . $priority . ', cтатус => ' . $tasksEntity2->status); } else { $this->logger->setLog('в Tasks была НЕ добавлена КОМАНДА => "'. $work['work_name'] . '" id => '.$tasksEntity2->id); } // $projId = $this->generateProject($work); //if ( null != $tasksEntity3) { // $tasksEntity3->input_id = $projId; // // if($tasksEntity3->save()){ // $this->logger->setLog('привязка КОМАНДЫ ТМЦ ( id = '.$tasksEntity3->id.') прошла успешно'); // } //} if ( null == $switcher) { ///////////////// ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 1 $this->logger->setLog("\n 6. ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 1 \n"); //if ( Yii::$app->params['api']['hw_msrmnt_stat'][ $dwResult["hw_measurements_status"] ]) { // выполнение hw_measurements_status = waiting if ( $this->datailWorkArray[$work['id_work']]['measurements'] ) { echo "сверхцикловые замеры 1";echo "
"; $paramsMeaserm['stage'] = 1; $paramsMeaserm['stage_type'] = 'контрольный'; $paramsMeaserm['asusg_job_mapped_id'] = $asusgJob2LaunchEntity->id; Yii::$app->params['api']['mesrmntParam'] = $paramsMeaserm; $priority = $queueModel->insertExtraPlan($work,$asusgJob2LaunchEntity,$user->id); Yii::$app->params['countPriority'] = $priority; MappingapiModel::workMeasurements($work,$user->uuid); } /////////////////// ///////////////// ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 2 $this->logger->setLog("\n 7. ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 2 \n"); //if ( Yii::$app->params['api']['hw_msrmnt_stat'][ $dwResult["hw_measurements_status"] ]) { // выполнение hw_measurements_status = waiting if ( $this->datailWorkArray[$work['id_work']]['measurements'] ) { echo "сверхцикловые замеры 2";echo "
"; $paramsMeaserm['stage'] = 2; $paramsMeaserm['stage_type'] = 'послеремонтный'; $paramsMeaserm['asusg_job_mapped_id'] = $asusgJob2LaunchEntity->id; Yii::$app->params['api']['mesrmntParam'] = $paramsMeaserm; $priority = $queueModel->insertExtraPlan($work,$asusgJob2LaunchEntity,$user->id); Yii::$app->params['countPriority'] = $priority; MappingapiModel::workMeasurements($work,$user->uuid); } /////////////////// } //( все правильно сначала 2 потом 1) //echo "
";        
            //var_dump($tasksEntity2->errors,$tasksEntity->errors);
            //echo "
"; //Yii::$app->params['countPriority'] = 1; } } public function addJob2launch3($listWorks,$user) { foreach ( $listWorks as $work) { $this->logger->indx = $user->uuid; $this->logger->header = $work['id_work']; Yii::$app->params['countPriority']= 1; $this->logger->setLog("\n 1. ДОБАВЛЕНИЕ В LAUNCH \n\n"); $asusgJob2LaunchEntity = AsusgJob2Launch::findOne(['asusg_job_uuid' => $work['id_work']]); $this->addTypeWork($work['id_work'], 1); $let = mb_substr($work["section_lit"], -1); // ВАЖНО ПОНИМАТЬ !!!! // если проект для такой работы уже есть, его создавать нельзя // но можно прикреплять к нему задачи. Сотрудник который зашел первый получает и замеры и тмц и работы // тот кто зашел вторым получает только работы. //$mappingapiModel = new \app\models\MappingapiModel(); //$dwResult = $mappingapiModel->workDetail($user->uuid,$work['id_work']); $dwResult = $this->datailWorkArray[$work['id_work']]; //echo "
"; 
            //var_dump($user->id);
            //var_dump($work['work_name']);
            //var_dump($dwResult["hw_measurements_status"]);
            //var_dump($dwResult);
            //var_dump($user->uuid);
            //echo "
"; //continue; $projtype = $this->getProjectType($work["repair_name"],$work["eq_serie"]); $JobPlanEntitty = AsusgJobplan::find()->where(['name' => $work["work_name"]])->one(); // 1204 1567 if ( null == $JobPlanEntitty->id ) { $this->logger->setLog(" ВНИМАНИЕ не нашел работу в AsusgJobplan ('name' => ".$work['work_name'].")\n\n"); } $jsusgJob2CommandEntity = AsusgJob2Command::find()->where(['asusg_job_id' => $JobPlanEntitty->id, 'asusg_projecttype_id' => $projtype ])->all(); if ( null == $jsusgJob2CommandEntity || 0 == count($jsusgJob2CommandEntity)){ $this->listWorkForExtraArray[] = $work; $this->logger->setLog(" ВНИМАНИЕ не нашел работу в asusgJob2Command ('name' => ".$work['work_name'].")\n\n"); continue; } $switcher = $asusgJob2LaunchEntity; if ( null == $switcher) { $resultArr = []; $asusgJob2LaunchEntity = new AsusgJob2Launch(); $asusgJob2LaunchEntity->asusg_jobplan_id = $JobPlanEntitty->id; $asusgJob2LaunchEntity->asusg_employee_id1 = $user->id; $asusgJob2LaunchEntity->asusg_job_uuid = $work['id_work']; $asusgJob2LaunchEntity->employees_uuid = $user->uuid; $asusgJob2LaunchEntity->section_uuid = $work["section_id"]; $asusgJob2LaunchEntity->asusg_project_id = 0; $asusgJob2LaunchEntity->job_order = 0; $asusgJob2LaunchEntity->asusg_projecttype_id = $projtype; $asusgJob2LaunchEntity->time_limit = $dwResult['time_limit']; $asusgJob2LaunchEntity->outfit = $dwResult['outfit']; $asusgJob2LaunchEntity->name = $work['work_name']; $asusgJob2LaunchEntity->section_name = $work["section_lit"]; if (!$asusgJob2LaunchEntity->save()) { $this->logger->setLog('в Job2launch не добавилась работа => "'. $work['work_name']. '" Добавление работ будет пропущено так как такая запись уже есть.'); continue; } $this->issetLaunch = true; //$this->logger->setLog($this->prepareLogString); //$this->prepareLogString = ''; $this->logger->setLog('в Job2launch была добавлена работа => "'. $work['work_name'].'"'); /// сначала генерю проект $projId = $this->generateProject($work); /// сначала генерю проект } else { $userUuidArr = explode(',', $asusgJob2LaunchEntity->employees_uuid); if ( in_array( $user->uuid , $userUuidArr)) { // если сотрудник уже привязан к лаунчу $this->logger->setLog('сотрудник '.$user->name .' ('.$user->id.') уже привязан к лаунчу'. $asusgJob2LaunchEntity->id); continue; } else { $asusgJob2LaunchEntity->employees_uuid .= ','. $user->uuid; $asusgJob2LaunchEntity->save(); $this->logger->setLog('сотрудники ('.$asusgJob2LaunchEntity->employees_uuid.') привязаны к лаунчу'. $asusgJob2LaunchEntity->id); } //continue; /* $this->prepareLogString .= "ВОТ ТУТ Я ХОТЕЛ ПОЛУЧИТЬ ИД ПРОЕКТА ЧЕРЕЗ ЗАДАЧУ => " . $asusgJob2LaunchEntity->tasks->id .", ВОТ ЧТО ПОЛУЧИЛ => " . $asusgJob2LaunchEntity->tasks->input_id ."!\n"; $projId = $asusgJob2LaunchEntity->tasks->input_id; */ $projId = $this->getCreateProject($work); // работа уже есть нужно получить проект //$this->prepareLogString .= "ВОТ ТУТ Я ХОТЕЛ ПОЛУЧИТЬ ИД ПРОЕКТА ЧЕРЕЗ ЗАДАЧУ => " . $asusgJob2LaunchEntity->onetask->id .", ВОТ ЧТО ПОЛУЧИЛ => " . $asusgJob2LaunchEntity->onetask->input_id ."!\n"; //$projId = $asusgJob2LaunchEntity->onetask->input_id; //if ( null == $projId ) { // $input_idTasks = Tasks::find()->where(['asusg_job_mapped_id' => $asusgJob2LaunchEntity->id])->andWhere(['IS NOT','input_id', null])->one(); // $this->prepareLogString .= "ВОТ ТАК ЧЕРЕЗ ЗАПРОС input_id => ".$input_idTasks->input_id."!\n"; // $projId = $input_idTasks->input_id; //} } /////////////// ДОБАВЛЕНИЕ ЗАДАЧИ $this->logger->setLog("\n 3. ДОБАВЛЕНИЕ ЗАДАЧИ \n\n"); $tasktypesEntity = Tasktypes::find()->where(['name' => 'Секция '.$let.', задача','company' => $this->company])->one(); $this->statusMaintask = 0; $mainTaskId = $this->getIssetMainTask($work,$user); $isCloseMaintask = false; if ( $mainTaskId ) { // !!!!!!!!!! //echo "Такая задача( цикловая ) уже есть"; $this->logger->setLog("\n Такая задача( цикловая ) уже есть \n\n"); if( 5 == $this->statusMaintask ) { $isCloseMaintask = true; } //$tasksEnt = Tasks::find()->where(['parent_id' => 0,'asusg_job_mapped_id' => $asusgJob2LaunchEntity->id,'assignees_arr' => $user->id])->one(); //if ( null != $tasksEnt) { //continue; } else { //$this->logger->setLog($this->prepareLogString); //$this->prepareLogString = ''; $tasksEntity = new Tasks(); $tasksEntity->parent_id = 0; $tasksEntity->status = 2; $tasksEntity->type = $tasktypesEntity->id; $tasksEntity->assignees_arr = $user->id; $tasksEntity->preferred_assignee = $user->id; $tasksEntity->created = date("Y-m-d H:i;s"); $tasksEntity->asusg_job_mapped_id = $asusgJob2LaunchEntity->id; $tasksEntity->mapping_comment = $work["outfit"] . ': ' . $work['work_name']; $tasksEntity->text = $work["section_lit"] . "\n" . $work["outfit"] . ': ' . $work['work_name'] . "\n" . $dwResult['workers']; $tasksEntity->input_id = $projId; if($tasksEntity->save()) { $mainTaskId = $tasksEntity->id; //$this->testIdpl3 = $tasksEntity->id; $this->logger->setLog('в Tasks была добавлена ЗАДАЧА => "'. $work['work_name'] . '" id => '.$tasksEntity->id); } else { $this->logger->setLog('в Tasks была НЕ добавлена ЗАДАЧА => "'. $work['work_name'] . '" id => '.$tasksEntity->id); continue; } //var_dump($tasksEntity->errors,$user->id); echo '
'; $this->logger->setLog(' колво записей => ' . count($jsusgJob2CommandEntity) . 'type => '. gettype($jsusgJob2CommandEntity)); } $arrJ = []; //$countPriority = 1; ///////////////// if ( null == $switcher) { $this->logger->setLog("switcher = null"); ///////////////// ДОБАВЛЕНИЕ ТМЦ $mappingapiModel = new \app\models\MappingapiModel(); //var_dump($user->id-uuid,$work['id_work']); $this->logger->setLog("сотрудник => " . $user->uuid . ", работа => " . $work['id_work']); //$tmcString = $mappingapiModel->workDetail($user->uuid,$work['id_work']); $this->logger->setLog("\n ДОБАВЛЕНИЕ ТМЦ " . strlen($dwResult['tmcString']) . "\n"); if ( '' != $dwResult['tmcString']) { $tasksEntity3 = new Tasks(); $tasksEntity3->parent_id = $tasksEntity->id; // + $tasksEntity3->status = 2; // + $tasksEntity3->priority = Yii::$app->params['tmcPriority']; // + // $tasksEntity2->input_id = $job->asusgJob2Launch->asusg_project_id; $tasksEntity3->created = date("Y-m-d H:i;s"); // + $tasksEntity3->type = 2159; // + $tasksEntity3->assignees_arr = $user->id; // + $tasksEntity3->preferred_assignee = $user->id; // + $tasksEntity3->asusg_job_mapped_id = $asusgJob2LaunchEntity->id; $tasksEntity3->text = $dwResult['tmcString']; // + $tasksEntity3->mapping_comment = $dwResult['tmcString']; // + $tasksEntity3->input_id = $projId; if ( $tasksEntity3->save()) { //var_dump('создана ТМЦ, задача =>' . $tasksEntity3->id); $arrJ[] = $tasksEntity3->id; $query3 = "call asusg_add_checkpoints_to_task(" . $user->id . ",'" . $tasksEntity3->id . "')"; $resProc = Yii::$app->db->createCommand($query3)->query(); $logResProc = 'false'; if ($resProc){ $logResProc = 'true'; } $this->logger->setLog('в Tasks была добавлена КОМАНДА => "'. $work['work_name'] . '" id => '.$tasksEntity3->id. ' процедура => ' . $logResProc); } else { //var_dump('не создана ТМЦ'); $this->logger->setLog('в Tasks была НЕ добавлена КОМАНДА => "'. $work['work_name'] . '" id => '.$tasksEntity3->id); } //Yii::$app->params['countPriority']++; } /////////////////// ///////////////// ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 0 $this->logger->setLog("\n 4. ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 0 \n"); //var_dump(Yii::$app->params['api']['hw_msrmnt_stat'][ $dwResult["hw_measurements_status"] ],$dwResult["hw_measurements_status"]); echo "\n"; //if ( Yii::$app->params['api']['hw_msrmnt_stat'][ $dwResult["hw_measurements_status"] ]) { // выполнение hw_measurements_status = waiting if ( $this->datailWorkArray[$work['id_work']]['measurements'] ) { //Yii::$app->params['countPriority'] = (($job->original_order*100)-1); Yii::$app->params['countPriority'] = (100-1); $this->logger->setLog('приоритет '.(100-1)); $paramsMeaserm = ['input_id' => $projId, 'assignees_arr' => $user->id, 'work' => $work,'stage' =>0, 'parent_id' => $tasksEntity->id ,'stage_type' => 'доремонтный','asusg_job_mapped_id' => $asusgJob2LaunchEntity->id]; Yii::$app->params['api']['mesrmntParam'] = $paramsMeaserm; MappingapiModel::workMeasurements($work,$user->uuid); } /////////////////// } /////////////// НА РЕМОНТ $this->logger->setLog("\n 5. ДОБАВЛЕНИЕ НА РЕМОНТ \n"); $countpr = 100; foreach($jsusgJob2CommandEntity as $job) { $job->job_uuid = $work['id_work']; $tasksEntity2 = new Tasks(); $tasksEntity2->parent_id = $mainTaskId; $tasksEntity2->status = 2; $tasksEntity2->priority = ($job->original_order*100);//Yii::$app->params['countPriority']; // $tasksEntity2->input_id = $job->asusgJob2Launch->asusg_project_id; $tasksEntity2->created = date("Y-m-d H:i;s"); $tasksEntity2->type = $job->smopp_cmd_id;//Yii::$app->params['supercycletype']; $tasksEntity2->assignees_arr = $user->id; $tasksEntity2->preferred_assignee = $user->id; $tasksEntity2->asusg_job_mapped_id = $job->jobplantieuuid->id; $tasksEntity2->text = $work["eq_serie"] . ' '.$work["section_lit"] . ', '. $work["outfit"] . ':' . $work['work_name'].'..'; $tasksEntity2->mapping_comment = $work["outfit"] . ': ' . $job->tasktypes->name; $tasksEntity2->input_id = $projId; if ( $tasksEntity2->save()) { if ( $isCloseMaintask ) { $taskEntity = Task::findOne($mainTaskId); $taskEntity->status = 2; $taskEntity->save(); $isCloseMaintask = false; } //$arrJ[] = $tasksEntity2->id; /////////////////// //$query3 = "call asusg_add_checkpoints_to_task(" . $user->id . ",'" . $tasksEntity2->id . "')"; //$resProc = Yii::$app->db->createCommand($query3)->query(); /////////////////// $this->logger->setLog('в Tasks была добавлена КОМАНДА => "'. $work['work_name'] . '" id => '.$tasksEntity2->id); } else { $this->logger->setLog('в Tasks была НЕ добавлена КОМАНДА => "'. $work['work_name'] . '" id => '.$tasksEntity2->id); } if ( ($job->original_order*100) > $countpr ) { $countpr = ($job->original_order*100); } } ///////////////////////////////////// // $projId = $this->generateProject3($work); //$tasksEntity->input_id = $tasksEntity->input_id ?? $projId; //if ($tasksEntity->save()) { // $this->logger->setLog('привязка ЗАДАЧИ ( id = '.$tasksEntity->id.') прошла успешно'); //} $tasksEntity = null; /* foreach($arrJ as $job_id) { $tasksEnt = Tasks::findOne($job_id); $tasksEnt->input_id = $tasksEnt->input_id ?? $projId; if($tasksEnt->save()){ $this->logger->setLog('привязка КОМАНДЫ ( id = '.$tasksEntity2->id.') прошла успешно'); } else { $this->logger->setLog('привязка КОМАНДЫ ( id = '.$tasksEntity2->id.') прошла не успешно'); } } */ if ( null != $tasksEntity3) { $tasksEntity3->input_id = $projId; //if($tasksEntity3->save()){ // $this->logger->setLog('привязка КОМАНДЫ ТМЦ ( id = '.$tasksEntity3->id.') прошла успешно'); //} } if ( null == $switcher) { ///////////////// ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 1 $this->logger->setLog("\n 6. ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 1 \n"); //if ( Yii::$app->params['api']['hw_msrmnt_stat'][ $dwResult["hw_measurements_status"] ]) { // выполнение hw_measurements_status = waiting if ( $this->datailWorkArray[$work['id_work']]['measurements'] ) { $paramsMeaserm['stage'] = 1; $paramsMeaserm['stage_type'] = 'контрольный'; $paramsMeaserm['asusg_job_mapped_id'] = $asusgJob2LaunchEntity->id; //Yii::$app->params['countPriority'] = (($job->original_order*100)+1); Yii::$app->params['countPriority'] = ($countpr+1); $this->logger->setLog('приоритет '.($countpr+1)); Yii::$app->params['api']['mesrmntParam'] = $paramsMeaserm; MappingapiModel::workMeasurements($work,$user->uuid); } /////////////////// ///////////////// ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 2 $this->logger->setLog("\n 7. ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 2 \n"); //if ( Yii::$app->params['api']['hw_msrmnt_stat'][ $dwResult["hw_measurements_status"] ]) { // выполнение hw_measurements_status = waiting if ( $this->datailWorkArray[$work['id_work']]['measurements'] ) { $paramsMeaserm['stage'] = 2; $paramsMeaserm['stage_type'] = 'послеремонтный'; $paramsMeaserm['asusg_job_mapped_id'] = $asusgJob2LaunchEntity->id; Yii::$app->params['countPriority'] = ($countpr+2); $this->logger->setLog('приоритет '.($countpr+2)); Yii::$app->params['api']['mesrmntParam'] = $paramsMeaserm; MappingapiModel::workMeasurements($work,$user->uuid); } /////////////////// } //echo "
";        
            //var_dump($job->asusgJob2Launch->asusg_project_id);
            //var_dump($tasksEntity2->errors,$tasksEntity->errors);
            //echo "
"; } } public function generateProject($work){ $this->logger->setLog("\n 2. ГЕНЕРАЦИЯ ПРОЕКТА \n"); $result = ''; $status = ''; $let = mb_substr($work["section_lit"], -1); $sectionsEntity = Sections::find()->select(['id', 'diagnostic_map']) //->where(['locomotive_series' => $work["eq_serie"],'section_number' => mb_substr($work['section_lit'],0,-1),'letter' => $let]) ->where(['locomotive_series' => $work["eq_serie"],'section_number' => mb_substr($work['section_lit'],0,-1),'section_subnumber' => $work["section_num"]]) ->one(); $this->logger->setLog("Параметры локомотива locomotive_series => " . $work["eq_serie"]. ", section_number => " . $work['section_lit'] . " ,letter => " .$let. " \n"); $diagnostic_map = $sectionsEntity->diagnostic_map; if ( null == $sectionsEntity->id) { $sectionsEntity2 = new Sections(); $sectionsEntity2->locomotive_series = $work["eq_serie"]; $sectionsEntity2->section_number = mb_substr($work['section_lit'],0,-1); $sectionsEntity2->section_subnumber = $work["section_num"]; $sectionsEntity2->diagnostic_map = $work["section_DK"]; $sectionsEntity2->uuid = $work["section_id"]; $sectionsEntity2->letter = $let; if ( $sectionsEntity2->save()) { $this->logger->setLog('в Sections была добавлена новая секция => '. $work["section_num"] . ' id => '.$sectionsEntity2->id); } else { //var_dump($sectionsEntity2->errors); $this->logger->setLog('в Sections при добавлении секции произошли ошибки => '. count($sectionsEntity2->errors) . ' шт.'); $sectionsEntity->diagnostic_map = $work['section_DK']; $sectionsEntity->save(); $this->logger->setLog('Пришлось просто обновить диагностическую карту секция=> '. $sectionsEntity . ', номер карты =>' . $work['section_DK']); } $diagnostic_map = $sectionsEntity->diagnostic_map; } else if( ( null == $sectionsEntity->diagnostic_map ) || ($sectionsEntity->diagnostic_map != $work['section_DK'])) { //else if( null == $sectionsEntity->diagnostic_map) { $sectionsEntity->diagnostic_map = $work['section_DK']; $sectionsEntity->save(); } $this->logger->setLog('Условие проверки1: ' . $sectionsEntity->diagnostic_map .'=='. $work['section_DK']); $this->logger->setLog('Условие проверки1: ' . $sectionsEntity2->diagnostic_map .'=='. $work['section_DK']); if ( $sectionsEntity->diagnostic_map == $work['section_DK'] ) { $projectRes = $this->getIssetProject($work); $result = ( isset($projectRes['id']) ) ? $projectRes['id'] : '' ; $status = ( isset($projectRes['status']) ) ? $projectRes['status'] : '' ; $this->logger->setLog('в Sections секция с такой диагностической картой => '. $work['section_DK'] . ' существует. Ид проекта '. $result); } if ( $sectionsEntity2->diagnostic_map == $work['section_DK'] ) { $projectRes = $this->getIssetProject($work); $result = ( isset($projectRes['id']) ) ? $projectRes['id'] : '' ; $status = ( isset($projectRes['status']) ) ? $projectRes['status'] : '' ; $this->logger->setLog('в Sections секция с такой диагностической картой => '. $work['section_DK'] . ' существует. Ид проекта '. $result); } $ProjectsL = ProjectsLocotech::findOne($result); $status = $ProjectsL->status; //if (!$result) { if ((!$result) || ( 5 == $status )) { $this->logger->setLog('Условие проверки2: '.(!$result) .' статус '. $status . json_encode($projectRes)); $result = $this->generateProject3($work); $this->logger->setLog('Такого проекта еще не было пришлось создать. Ид проекта => '. $result); } //var_dump($result); return $result; } public function generateProject3($work){ $result = ''; $projectsLocotech = new ProjectsLocotech(); $projectsLocotech->action = 197 ; $projectsLocotech->company = $this->company; $projectsLocotech->status = 2; $projectsLocotech->loco_type = $work["eq_serie"]; $projectsLocotech->loco_number = $work["eq_number"]; $projectsLocotech->depo ='' ; $projectsLocotech->depo_service = ''; $projectsLocotech->created = date('Y-m-d H:i:s'); $projectsLocotech->urgent = 0; $projectsLocotech->uuid = $work['work_name'].":".$work['repair_name'].",".$work["eq_serie"]; $projectsLocotech->save(); $result = $projectsLocotech->id; //$this->logger->setLog('Такого проекта еще не было пришлось создать. Ид проекта => '. $result); //var_dump($result); return $result; } private function getCreateProject($work) { $result = ''; $projectRes = $this->getIssetProject($work); $result = $projectRes['id']; $status = $projectRes['status']; //if ((!$result) || ( 5 == $status )) { // $result = $this->generateProject3($work); // $this->logger->setLog('Такого проекта еще не было пришлось создать. Ид проекта => '. $result); //} return $result; } private function getIssetProject($work) { $query = "select pl.id, pl.status from projects_locotech pl inner join tasks t on pl.id = t.input_id where pl.company = " . $this->company . " and pl.loco_type = '" . $work["eq_serie"] . "' and pl.loco_number = " . $work["eq_number"] . " and t.parent_id = 0 and pl.uuid like '%" . $work['repair_name']. ",%' order by pl.id desc limit 1"; $this->logger->setLog('Текст запроса ' . $query); $projectRes = Yii::$app->db->createCommand($query)->queryOne(); //$result = $projectId['id']; //$status = $projectId['satus']; return $projectRes; } private function getIssetMainTask($work,$user) { $result = null; $query = "select t.id as task_id, pl.status, t.status as maintask_status from projects_locotech pl inner join tasks t on pl.id = t.input_id left join tasks tc on tc.parent_id = t.id where pl.company = " . $this->company . " and pl.loco_type = '" . $work["eq_serie"] . "' and pl.loco_number = " . $work["eq_number"] . " and t.parent_id = 0 and pl.status <> 5 and tc.text like '%" . $work["section_lit"]. "%' and tc.assignees_arr = " . $user->id . " and pl.uuid like '%" . $work["repair_name"]. "%' order by pl.id desc limit 1"; //echo $query; $this->logger->setLog('Текст запроса ' . $query); $projectRes = Yii::$app->db->createCommand($query)->queryOne(); //echo $projectRes['task_id']; $this->logger->setLog('Текст ответа ' . json_encode($projectRes)); if ( is_array($projectRes) and !empty($projectRes)){ $result = $projectRes['task_id']; $this->statusMaintask = $projectRes['maintask_status']; } return $result; } private function getIssetMainTask_false($work,$user) { $result = null; $asusgJob2LaunchEntity = AsusgJob2Launch::find()->where(['asusg_job_uuid' => $work['id_work']])->andWhere(['like','employees_uuid', $user->uuid])->one(); $tasksEntity = Tasks::find()->where(['parent_id' => 0,'asusg_job_mapped_id' => $asusgJob2LaunchEntity->id, 'assignees_arr' => $user->id])->one(); $this->logger->setLog('Запрос на существовании задачи, ответ =>' . $tasksEntity->id); if ( $tasksEntity->id ){ $result = $tasksEntity->id; } return $result; } private function prepareListWorks($listWorks) { $result = []; $dataArr = []; if ( null == $listWorks || empty($listWorks)) { return []; } foreach ( $listWorks["rows"] as $rows) { $rows["result"] = json_decode($rows["result"],true); foreach ( $rows["result"]['data'] as $key => $data) { //echo '
';
                  //              var_dump($data);
                    //            echo '
'; $tempArray = []; $tempArray["eq_serie"] = explode(" ",$data["equip_sect_name"])[0]; $eq = explode(" ",$data["equip_sect_name"])[1]; $tempArray["eq_number"] = explode("/",$eq)[0]; //echo '
';
                //var_dump($tempArray["eq_number"]);
                //echo '
'; foreach ( $data["sections"] as $sections) { $tempArray["section_id"] = $sections["id_section"]; $tempArray["section_lit"] = $sections["section_name"]; //$this->getLocoInfoMore($sections["section_subnumber"]); $tempArray["section_num"] = $sections["section_subnumber"]; $tempArray["section_DK"] = $sections["section_dk"]; // echo '
';
//                                 var_dump($sections);
//                                 echo '
'; foreach ( $sections['works'] as $work) { $tempArray["id_work"] = $work["id_work"]; $tempArray["outfit"] = $work["outfit"]; $tempArray["work_name"] = $work["work_name"]; $tempArray["repair_name"] = $work["repair_type"]; $tempArray["work_status"] = $work["work_status"]; $tempArray["repeats"] = $work["repeats"]; //$extraSection = $this->getSectionInfo( $tempArray["section_id"], $tempArray["repair_name"]); //$tempArray["section_num"] = $extraSection['section_num']; //$tempArray['section_DK'] = $extraSection['section_DK']; foreach ( $work['workers'] as $worker) { $tempArray['workers'][] = $worker; //echo '
';
                                //var_dump($worker);
                                //echo '
'; } $dataArr[] = $tempArray; } } } $result['result'] = 'true'; $result['data'] = $dataArr; break; } return $result; } private function sectionList() { $result = []; //$params['place'] = 'a84d0a15-08ec-11e5-829d-00155d6cab05'; //$params['place'] = '95d7646d-e7ee-11e4-829d-00155d6cab05'; $params['place'] = 'a84d0a15-08ec-11e5-829d-00155d6cab05'; $params['date'] = '1581324560'; $locomotiveModel = new LocomotiveModel(); $result = $locomotiveModel->getSectionList($params); //$result = json_decode($result,true); //$this->sectionList = $result['array']; $this->sectionList = json_decode($result,true); return $result; } private function getSectionInfo( $id,$repair) { $result = []; if (empty($this->sectionList)) { $this->sectionList(); } foreach ($this->sectionList as $items) { //var_dump($section["Section"] .' == '. $id , $section['TypeOfRepair'] .' == '. $repair); echo '
'; foreach ( $items as $section) { if ( $section["Section"] == $id and $section['TypeOfRepair'] == $repair ) { $result['section_num'] = $section["NumberSection"]; $result['section_DK'] = $section['DiagnosticMapslocomotive']; return $result; } } } return $result; } private function buisyEmployee($user){ $tasksEntity = Tasks::find()->where(['assignees_arr' => $user->id])->andWhere(['<>','status',5])->all(); if ( 0 < count($tasksEntity)){ //var_dump('Return =>true'); return true; } //var_dump('Return =>false'); return false; } private function clearEmptyProjects() { if (empty($this->createProjects)) { return true; } $projectsArray = array_unique($this->createProjects); foreach ($projectsArray as $proj){ $tasksEntity = Tasks::find()->where(['input_id' => $proj])->all(); if ( 0 == count($tasksEntity)){ $projectsLocotech = ProjectsLocotech::findOne($proj); $projectsLocotech->delete(); } } return true; } // ЗАПИСЬ В ТАБЛИЦУ ОТВЕТА ОТ ЕИПП MYWORKS // params => $listWorks: array // // result => bolean private function insertEippJob($listWorks) { foreach( $listWorks['data'] as $work) { $myworkEntity = new Mywork(); $myworkEntity->id_work = $work['id_work']; $myworkEntity->section_DK = $work['section_DK']; $myworkEntity->eq_number = $work['eq_number']; $myworkEntity->repeats = $work['repeats']; $myworkEntity->outfit = $work['outfit']; $myworkEntity->work_name = $work['work_name']; $myworkEntity->section_id = $work['section_id']; $myworkEntity->section_num = $work['section_num']; $myworkEntity->section_lit = $work['section_lit']; $myworkEntity->repair_name = $work['repair_name']; $myworkEntity->eq_serie = $work['eq_serie']; $myworkEntity->save(); } } // ПОЛУЧЕНИ ДЕТАЛИЗАЦИИ ПО РАБОТЕ // params => $user_id: string // $work_id: string // // result => bolean public function workDetail($user_id, $work_id) { $myworkEntity = Mywork::findOne(['id_work' => $work_id,'detail' => 1]); if( $myworkEntity ){ return true; } $this->GWparams = [ 'url' => Yii::$app->params['api']['domain'] . $this->url . 'work_detail', 'param' => [ 'user_id' => $user_id, 'id_work' => $work_id ]]; //ElasticLog::eipp($this->GWparams, $work_id, $user_id); $response = $this->curlRequestUni($this->GWparams,'post'); $work = json_decode($response,true); //ElasticLog::eipp($response, $work_id, $user_id, false); $tmcList = $this->getTmcList($work); $myworkEntity = Mywork::findOne(['id_work' => $work_id]); $myworkEntity->hw_measurements_status = $tmcList['hw_measurements_status']; $myworkEntity->repeats = $tmcList['repeats']; $myworkEntity->time_limit = $tmcList['time_limit']; $myworkEntity->work_part_percent = $tmcList['work_part_percent']; $myworkEntity->time_remain = $tmcList['time_remain']; $myworkEntity->cam_list = json_encode($tmcList['cam_list']); $myworkEntity->equipement_name = $tmcList['equipement_name']; $myworkEntity->equipement_number = $tmcList['equipement_number']; $myworkEntity->work_status = $tmcList['work_status']; $myworkEntity->measurements = $tmcList['measurements']; $myworkEntity->tmsString = $tmcList['tmsString']; $myworkEntity->detail = 1; $myworkEntity->save(); return true; } // МЕППИНГ ОТВЕТА ПО ДЕТАЛИЗАЦИИ // params => $work: array // // result => array public function getTmcList($work) { $result = []; $tenpArray = []; $count = 1; foreach($work['rows'] as $tmc1) { foreach($tmc1 as $tmc2) { $tmc2 = json_decode($tmc2,true); foreach($tmc2['data'] as $key => $tmc3) { $result[$key] = $tmc3; foreach($tmc3 as $tmc4) { if ( '' != $tmc4["tmc_name"]) { $tenpArray[] = $tmc4["tmc_name"]; } } if ( 'workers' == $key) { $result['workers'] = []; foreach($tmc3 as $key => $tmc5) { $result['workers'][] = $tmc5['fio']; $result['workers_uuid'][] = $tmc5['id']; } } if ( 'measurements' == $key) { $result['measurements'] = $this->CheckmeasurementField($tmc3); } } } } $result['tmcString'] = ''; if ( !empty($tenpArray) ) { $result['tmcString'] = implode("\n * ", $tenpArray); $result['tmcString'] = "* " . $result['tmcString']; } $result['workers'] = 'Назначены: ' . implode(', ',$result['workers']); return $result; } // ПРОВЕРКА ПОЛЯ ЗАМЕРЫ, НА НЕОБХОДИМОСТЬ ИХ ЗАПРАШИВАТЬ // params => $msrm: string // // result => boolean private function CheckmeasurementField($msrm) { $msrmArr = explode('/', $msrm ); if ( (count($msrmArr) > 1) && ($msrmArr[0] == $msrmArr[1]) ) { return false; // если $msrm = 25/25/0 и (25==25) то можно не запрашивать замеры } return true; // если $msrm = 25/24/0 и (25!=24) то запрашивать замеры } // ЗАПИСЬ В ТАБЛИЦУ СВЯЗКА РАБОТА <==> ПОЛЬЗОВАТЕЛЬ // params => $user: string // $work: string // // result => bolean private function attachWorkUser($work,$user) { //var_dump($work,$user); $workworkerEntity = new Workworker(); $workworkerEntity->id_work = $work; $workworkerEntity->workers = $user; $workworkerEntity->save(); return true; } private function addTypeWork($workId, $workType) { $myworkEntity = Mywork::findOne(['id_work' => $workId]); $myworkEntity->type_work = $workType; $myworkEntity->save(); } private function fixPriority($k) { $tasksArray = []; $flag = 0; $pl = ProjectsLocotech::find()->where(['>','created', date('Y-m-d').' 00:00:00'])->andWhere(['<','created', date('Y-m-d').' 23:59:59'])->all(); $arrPL = []; foreach ($pl as $plEnt) { $arrPL[] = $plEnt->id; } $tE = Tasks::find()->andWhere(['IN', 'input_id',$arrPL]) ->groupBy(['assignees_arr']) ->all(); $arrT = []; foreach ($tE as $tEnt) { $arrT[] = $tEnt->assignees_arr; } $tt = Tasks::find()->where(['parent_id' => 0 ]) ->andWhere(['IN', 'input_id',$arrPL]) ->andWhere(['IN', 'assignees_arr',$arrT]) ->andWhere(['>','created', date('Y-m-d').' 00:00:00']) ->andWhere(['<','created', date('Y-m-d').' 23:59:59']) ->orderBy(['parent_id' => SORT_ASC])->all(); foreach ($tt as $t) { $mt = Tasks::find()->where(['parent_id' => $t->id ])->orderBy(['priority' => SORT_ASC])->all(); foreach ( $mt as $e) { if ( 0 != $prior['pr'] ) { if ( $prior['pr'] == $e->priority){ $tasksArray[$t->id][] = [['pr' =>$e->priority, 'id' => $e->id],$prior]; } } $prior['pr'] = $e->priority; $prior['id'] = $e->id; } } $i = 0; foreach( $tasksArray as &$task){ foreach( $task as &$t){ $mt = Tasks::findOne($t[1]['id']); $mt->scenario = Tasks::SCENARIO_UPDATE_PRIORITY; if ( 110 < $mt->priority) { $mt->priority = ($t[1]['pr'] + 5); $mt->save(); //var_dump($mt->validate(),$mt->errors); } if ( 89 > $mt->priority) { $mt->priority = ($t[1]['pr'] + 1); $mt->save(); } break; } $i++; } if ( empty($tasksArray) ) { return true; } else { $k++; if( 50 == $k ) { return true; } $this->fixPriority($k); } } } /* int(349) array(2) { ["dataShape"]=> array(1) { ["fieldDefinitions"]=> array(1) { ["result"]=> array(5) { ["name"]=> string(6) "result" ["description"]=> string(0) "" ["baseType"]=> string(4) "TEXT" ["ordinal"]=> int(0) ["aspects"]=> array(0) { } } } } ["rows"]=> array(1) { [0]=> array(1) { ["result"]=> string(1290) "{"result":"true", "data": [{"id_equipment":"95078df8-4487-46b9-9771-5c6b6e1f6b81", "equip_sect_name":"3ЭС5К 0362/3ЭС5К", // ["eq_serie"]/ ["eq_number"] "sections": [{"works": [{"id_work":"a7869ca0-0153-41f5-93c4-51393ccc574a", "repeats":1, "work_name":"Тормозное и пневматическое оборудование после ремонта испытать, // ["work_name"] отрегулировать согласно инструкции", "work_status":4, "workers": [{"id":"0f9ed850-e473-11e2-aaad-ac162db0b20c","fio":"Новосад Я. И."}, {"id":"0f9ed854-e473-11e2-aaad-ac162db0b20c","fio":"Ознобихин О. А."}], "measurements":"--/--/--"}], "section_name":"0362А", // ["section_lit"] "id_section":"6ddd13a5-986b-11e2-99b5-ac162db0b20c"}, // ["section_id"] {"works": [{"id_work":"a0a572e0-4d70-45d7-ac4a-9483933c70b9", "repeats":1, "work_name":"Тормозное и пневматическое оборудование после ремонта испытать, отрегулировать согласно инструкции", "work_status":4, "workers": [{"id":"0f9ed850-e473-11e2-aaad-ac162db0b20c","fio":"Новосад Я. И."}, {"id":"0f9ed854-e473-11e2-aaad-ac162db0b20c","fio":"Ознобихин О.А."}], "measurements":"--/--/--"}], "section_name":"0362В", "id_section":"6ddd13a6-986b-11e2-99b5-ac162db0b20c"}], "equip_percent":10730}]}" } } } $work["eq_serie"] . ' '.$work["section_lit"] . ', '. $work["outfit"] . ':' . $work['work_name'] repair_name - ? section_num - ? + outfit - ? section_DK - ? int(349) array(2) { ["result"]=> string(4) "true" ["data"]=> array(2) { [0]=> array(10) { ["id_work"]=> string(36) "a7869ca0-0153-41f5-93c4-51393ccc574a" + ["section_DK"]=> string(36) "6d4acb88-685e-11ea-80d6-005056011052" + ["eq_number"]=> string(4) "0362" + ["outfit"]=> float(1460789) + ["work_name"]=> string(187) "Тормозное и пневматическое оборудование после ремонта испытать , отрегулировать согласно инструкции" + ["section_id"]=> string(36) "6ddd13a5-986b-11e2-99b5-ac162db0b20c" + ["section_num"]=> string(8) "11381969" + ["section_lit"]=> string(6) "0362А" + ["repair_name"]=> string(6) "ТР-1" + ["eq_serie"]=> string(8) "3ЭС5К" + } [1]=> array(10) { ["id_work"]=> string(36) "a0a572e0-4d70-45d7-ac4a-9483933c70b9" ["section_DK"]=> string(36) "6d4acb89-685e-11ea-80d6-005056011052" ["eq_number"]=> string(4) "0362" ["outfit"]=> float(1460871) ["work_name"]=> string(187) "Тормозное и пневматическое оборудование после ремонта испытать , отрегулировать согласно инструкции" ["section_id"]=> string(36) "6ddd13a6-986b-11e2-99b5-ac162db0b20c" ["section_num"]=> string(8) "11381985" ["section_lit"]=> string(6) "0362В" ["repair_name"]=> string(6) "ТР-1" ["eq_serie"]=> string(8) "3ЭС5К" } } } */