MappinghandlermwnewController.php 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663
  1. <?php
  2. namespace app\controllers;
  3. use app\models\ElasticLog;
  4. use Yii;
  5. use app\models\Logs;
  6. use yii\web\Controller;
  7. use app\models\MainModel;
  8. use app\models\QueueModel;
  9. use app\models\ProcedureModel;
  10. use app\models\entity\Tasks;
  11. use app\models\logger\LoggerDB;
  12. use app\models\entity\Sections;
  13. use app\models\LocomotiveModel;
  14. use app\models\MappingapiModel;
  15. use app\models\entity\Tasktypes;
  16. use \app\models\LogEippResponse;
  17. use app\models\logger\LoggerFile;
  18. use app\models\entity\Repairtypes;
  19. use app\models\entity\AsusgJobPlan;
  20. use app\models\MappingHandlerModel;
  21. use app\models\entity\AsusgJob2Launch;
  22. use app\models\entity\AsusgProjectType;
  23. use app\models\entity\LocomotiveSeries;
  24. use app\models\entity\ProjectsLocotech;
  25. use app\models\entity\AsusgJob2Command;
  26. use app\models\Mywork;
  27. use app\models\Workworker;
  28. class MappinghandlermwnewController extends Controller
  29. {
  30. private $logger;
  31. private $company;
  32. private $sectionList;
  33. private $testIdpl2;
  34. private $testIdpl3;
  35. private $datailWorkArray = [];
  36. private $locoGetInfoArray = [];
  37. private $statusMaintask;
  38. private $logEtn;
  39. private $prepareLogString = '';
  40. private $issetLaunch = false;
  41. private $listWorkForExtraArray = []; // работы которые должны быть цикловыми но для них не нашлось команд в файлике xls
  42. private $createProjects = [];
  43. private $url = '/Thingworx/Things/2050UserLibraryExp/Services/';
  44. private $user;
  45. public function beforeAction($action)
  46. {
  47. parent::beforeAction($action);
  48. $logEtn = new Logs();
  49. $logEtn->index_t = strtotime(date("Y-m-d H:i:s"));
  50. $logEtn->section = 3;
  51. //$this->logEtn = $logEtn;
  52. //$log = new LoggerFile();
  53. $log = new LoggerDB();
  54. $this->logger = new MappingHandlerModel($log);
  55. return true;
  56. }
  57. // запускается периодически через крон
  58. public function actionGetworks($company)
  59. {
  60. //$this->sectionList();
  61. //exit;
  62. $this->company = $company;
  63. $GWparams = [
  64. 'url' => 'http://' . Yii::$app->params['api']['domain'].'/Thingworx/Things/2050UserLibraryExp/Services/my_works',
  65. //'url' => 'http://devplatform.digitaldepot.ru:8085/Thingworx/Things/SMoPPIntegrationLibrary/Services/getUserWorks',
  66. 'param' => '',
  67. 'login' => 'ПройдаковИА',
  68. 'pass' => 'Ip15351112'
  69. ];
  70. // список сотрудников онлайн
  71. $onlineUser = $this->getOnlineMobileUser($company);
  72. if( 0 == count($onlineUser)) {
  73. return 'Нет сотрудников онлайн';
  74. }
  75. //$this->logger->setLog('ID пользователя => ' . (int)$_SESSION["id"]);
  76. //$this->logger->indx = time();
  77. $this->logger->setLog( "\n=================== СТАРТ МЕППИНГА ==================================\n");
  78. $this->logger->setLog( date("Y-m-d H:i:s") . "\n");
  79. $mainModel = new MainModel();
  80. // для каждого сотрудника онлайн запускаем проекты если они еще не запущены
  81. $setOnlineWorkers = [];
  82. $this->logger->setLog( "Колличество cотрудников онлайн :" . count($onlineUser) ."\n");
  83. foreach($onlineUser as $user) {
  84. $this->logger->indx = $user->uuid;
  85. //echo get_class($this->logger);
  86. $buisy = $this->buisyEmployee($user);
  87. //var_dump($user->id,$user->name ); continue;
  88. if( $buisy || ('' == $user->uuid and null == $user->uuid )) {
  89. var_dump('Занят => '.$user->name,'<br>'.$user->id);
  90. //$this->logger->setLog( "\n Выпоняет задание. Работы не выдались. \n");
  91. //continue;
  92. }
  93. $GWparams['param'] = $user->uuid;
  94. $responseMyWorks = $mainModel->curlRequest2($GWparams);
  95. $listWorks2 = json_decode($responseMyWorks,true);//var_dump($buisy,$user->id);continue;
  96. $listWorks2 = $this->prepareListWorks($listWorks2);
  97. $this->insertEippJob($listWorks2);
  98. //foreach ( $listIssetWorks3 as $work) { !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  99. //echo '<pre>';
  100. //var_dump($user->name);
  101. //var_dump($listWorks2);
  102. //echo '</pre>';
  103. foreach ( $listWorks2['data'] as $work) {
  104. foreach( $work['workers'] as $key => $uuid) {
  105. $this->attachWorkUser($work['id_work'],$uuid['id']);
  106. }
  107. $asusgJob2LaunchEntity = AsusgJob2Launch::find()->where(['asusg_job_uuid' => $work['id_work']])->andWhere(['like','employees_uuid',$user->uuid])->one();
  108. if ( null != $asusgJob2LaunchEntity) {
  109. continue;
  110. }
  111. //$this->workDetail( $user->uuid, $work['id_work'] );
  112. $mappingapiModel = new \app\models\MappingapiModel();
  113. $this->datailWorkArray[$work['id_work']] = $mappingapiModel->workDetail($user->uuid,$work['id_work']);
  114. foreach( $this->datailWorkArray[$work['id_work']]['workers_uuid'] as $uuid) {
  115. $setOnlineWorkers[] = $uuid;
  116. }
  117. }
  118. //$this->logger->setLog( $mappingapiModel->prepareLogString."\n"); // !!!!
  119. //$this->logger->setLog( "Вот это сейчас должен получить работу :" . $user->id . "( ".$user->name." )\n");
  120. }
  121. $setOnlineWorkers = array_unique($setOnlineWorkers);
  122. $onlineUserModificate = \app\models\entity\Accounts::find()->where(['in','uuid',$setOnlineWorkers])->andWhere(['company' =>$company])->all();
  123. $this->logger->setLog( "Колличество cотрудников онлайн для них есть работа ( с напарниками ):" . count($setOnlineWorkers)."\n");
  124. //var_dump($onlineUserModificate);
  125. foreach($onlineUserModificate as $user) {
  126. $this->logger->indx = $user->uuid;
  127. $this->user = $user;
  128. //var_dump($user->name,'<br>');
  129. //continue;
  130. $this->logger->setLog( "\n Сотрудник =>".$user->name.". Его uuid = ".$user->uuid." \n" );
  131. $buisy = $this->buisyEmployee($user);
  132. if( $buisy || ('' == $user->uuid and null == $user->uuid )) {
  133. //$this->logger->setLog("\n Выпоняет задание. Работы не выдались. \n" );
  134. continue;
  135. }
  136. $this->issetLaunch = false;
  137. $GWparams['param'] = $user->uuid;
  138. ElasticLog::eipp($GWparams, 'my_works', 0);
  139. $listWorks2 = $mainModel->curlRequest2($GWparams);
  140. $unixTime = time();
  141. LogEippResponse::addLog($unixTime.'gw'. $user->id ,$listWorks2,'Получение работ от ЕИПП');
  142. ElasticLog::eipp($listWorks2, 'my_works', 0, false);
  143. $this->logger->setLog( "\nMY_WORK =====>\n" );
  144. $this->logger->setLog("Параметры: \n user_id =>". $GWparams['param'] .".\n");
  145. $this->logger->setLog( "Строка запроса : \n " . $GWparams['url'] .".\n");
  146. $this->logger->setLog("Вот тут можно посмотреть что ЕИПП прислал по запросу http://dev.prmsys.net/api/mappinghandler/eippresponse?indx=".$unixTime."\n");
  147. $this->logger->setLog("MY_WORK ======>\n\n");
  148. $listWorks2 = json_decode($listWorks2,true);
  149. $listWorks2 = $this->prepareListWorks($listWorks2);
  150. /// НЕТ ДВУХ ПОЛЕЙ ["section_num"] ["section_DK"]
  151. //continue;
  152. //$this->logEtn->addlogText('','sdfsdfsdf');
  153. $this->logger->setLog("Колличество работ из еипп: ". count($listWorks2['data'])." \n Cотрудник:" . $user->id . "( ". $user->name ." )\n");
  154. echo "Колличество работ из еипп: ". count($listWorks2['data'])." \n Cотрудник:" . $user->id . "( ". $user->name ." )\n";
  155. $listIsabsentWorks2 = $this->Getisabsentworksjp($listWorks2); // вновь утвержденный план 1 | вернет список работ кот нет ( в JobPlan )
  156. $listIssetWorks3 = $this->Getissetworksjp($listWorks2);
  157. $this->logger->setLog('Колличество работ из еипп ( сверхциклвая ): '. count($listIsabsentWorks2)."\n");
  158. $this->logger->setLog('Колличество работ из еипп ( цикловая ): '. count($listIssetWorks3)."\n");
  159. $this->logger->setLog("\n СВЕРХЦИКЛОВЫЕ \n\n");
  160. var_dump('Колличество работ из еипп ( цикловая ): '. count($listIssetWorks3)."\n");
  161. var_dump('Колличество работ из еипп ( сверхциклвая ): '. count($listIsabsentWorks2)."\n");
  162. $addJob2launch2 = $this->addJob2launch2($listIsabsentWorks2,$user);
  163. $this->logger->setLog("\n ЦИКЛОВЫЕ \n\n");
  164. $addJob2launch3 = $this->addJob2launch3($listIssetWorks3,$user);
  165. if(!empty($this->listWorkForExtraArray)){
  166. $this->logger->setLog("\n СВЕРХЦИКЛОВЫЕ (ДОП) \n\n");
  167. $this->addJob2launch2($this->listWorkForExtraArray,$user);
  168. $this->listWorkForExtraArray = [];
  169. }
  170. if (!$this->issetLaunch) {
  171. continue;
  172. }
  173. $this->logger->setLog("Интеграция сверхцикловых работ прошла без падений!");
  174. $this->logger->setLog("=====================================================\n\n");
  175. //echo '<pre>';
  176. //var_dump($user->id);
  177. ///var_dump($listWorks2);
  178. //echo '</pre>';
  179. }
  180. $this->fixPriority(1);
  181. $this->clearEmptyProjects();
  182. return true;//$listWorks;
  183. }
  184. public function actionDojob()
  185. {
  186. Yii::$app->db->createCommand('update `accounts_internal` set `last_seen_mobile` = NOW() where id in (351,349,350)')->execute();
  187. }
  188. public function actionDopro()
  189. {
  190. $JobPlanEntitty = AsusgJobplan::find()->where(['name' => 'Тормозное и пневматическое оборудование после ремонта испытать , отрегулировать согласно инструкции'])->one(); // 1204 1567
  191. $jsusgJob2CommandEntity = AsusgJob2Command::find()->where(['asusg_job_id' => $JobPlanEntitty->id])->all();
  192. foreach($jsusgJob2CommandEntity as $job) {
  193. echo '<pre>';
  194. var_dump('3 =>'. $job->id, $job->asusg_job_id);
  195. var_dump('3 =>'. $job->jobplantie->id);
  196. echo '</pre>';
  197. }
  198. exit;
  199. }
  200. public function actionMktest()
  201. {
  202. //if ( $this->datailWorkArray[$work['id_work']]['measurements'] ) {
  203. Yii::$app->params['countPriority'] = ((2*100)-1);
  204. var_dump(Yii::$app->params['countPriority']);
  205. $this->logger->setLog('приоритет '.((2*100)-1));
  206. $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];
  207. Yii::$app->params['api']['mesrmntParam'] = $paramsMeaserm;
  208. MappingapiModel::workMeasurements('c57839e6-49ed-4791-9353-925fc2d737b8','c57839e6-49ed-4791-9353-925fc2d737b8');
  209. //}
  210. }
  211. public function actionProctest()
  212. {
  213. $procedureModel = new ProcedureModel();
  214. $procedureModel->asusg_build_and_start_project_auto(27,210);
  215. }
  216. public function Getisabsentworksjp( $listWorks = null){
  217. $result = [];
  218. if ( null == $listWorks) {
  219. return false;
  220. }
  221. foreach( $listWorks['data'] as $work) {
  222. $asusgJobPlan = AsusgJobPlan::find()->where(['name' => $work['work_name']])->one();
  223. if ( null == $asusgJobPlan ){
  224. $result[] = $work;
  225. }
  226. }
  227. return $result;
  228. }
  229. public function Getissetworksjp( $listWorks = null){
  230. $result = [];
  231. if ( null == $listWorks) {
  232. return false;
  233. }
  234. foreach( $listWorks['data'] as $work) {
  235. $asusgJobPlan = AsusgJobPlan::find()->where(['name' => $work['work_name']])->one();
  236. if ( null != $asusgJobPlan ){
  237. $result[] = $work;
  238. }
  239. }
  240. return $result;
  241. }
  242. public function getOnlineMobileUser($company){
  243. $result = [];
  244. $accountsEntity = \app\models\entity\Accounts::find()->where(['company' => $company])->all();
  245. foreach ($accountsEntity as $account) {
  246. //var_dump($account->id,'<br>');
  247. $last_seen_mobile = ( null != $account->last_seen_mobile )? new \DateTime($account->last_seen_mobile): $account->last_seen_mobile ;
  248. $online_mobile = $this->OnlineAccountCheck($this->TimeString($last_seen_mobile));
  249. //var_dump(( !$online_mobile ),'<br>');
  250. if ( !$online_mobile ){
  251. continue;
  252. }
  253. $result[] = $account;//['id' => $account->id, 'uuid' => $account->uuid];
  254. }
  255. return $result;
  256. }
  257. public function OnlineAccountCheck($last_seen)
  258. {
  259. $last_seen = date($last_seen);
  260. $time = (time()-strtotime($last_seen));
  261. //var_dump($time,' <=', Yii::$app->params['onlineMobileTimeoutSeconds'],'<br>');
  262. if ($time <= Yii::$app->params['onlineMobileTimeoutSeconds'])
  263. return true;
  264. return false;
  265. }
  266. public function TimeString($timeobj)
  267. {
  268. if ($timeobj != null)
  269. return $timeobj->format('d.m.Y H:i');
  270. //return date('d.m.Y H:i', $timeobj);
  271. }
  272. public function getProjectType($repairName,$serieName)
  273. {
  274. $result = null;
  275. $repairtypesEntity = Repairtypes::findOne(['name' => $repairName]);
  276. $locomotiveSeriesEntity = LocomotiveSeries::findOne(['name' => $serieName]);
  277. $asusgProjectTypeEntity = AsusgProjectType::findOne(['repair_type' => $repairtypesEntity->id , 'loco_serie_id' => $locomotiveSeriesEntity->id]);
  278. if ( null != $asusgProjectTypeEntity->id ) {
  279. $result = $asusgProjectTypeEntity->id;
  280. }
  281. return $result;
  282. }
  283. public function addJob2launch2($listWorks,$user)
  284. {
  285. $this->logger->indx = $this->user->uuid;
  286. foreach ( $listWorks as $work) {
  287. $this->logger->header = $work['id_work'];
  288. Yii::$app->params['countPriority']= 1;
  289. $dwResult = $this->datailWorkArray[$work['id_work']];
  290. $this->logger->setLog("Название работы:". $work['work_name']. ".\n UUID работы: " . $work['id_work'] . "\n\n");
  291. $queueModel = new QueueModel();
  292. $this->logger->setLog("\n 1. ДОБАВЛЕНИЕ В LAUNCH \n\n");
  293. $asusgJob2LaunchEntity = AsusgJob2Launch::findOne(['asusg_job_uuid' => $work['id_work']]);
  294. $this->logger->setLog("\n AsusgJob2Launch = " . count($asusgJob2LaunchEntity). " id work = " . $work['id_work'] . "\n");
  295. $this->addTypeWork($work['id_work'], 0);
  296. $let = mb_substr($work["section_lit"], -1);
  297. if( null != $let
  298. and !in_array($let,['А','Б','В'])
  299. ) {
  300. $let = 'А';
  301. }
  302. //if( null == $tasktypesEntity->id ) {
  303. // var_dump(( null != $let), (!in_array($let,['А','Б','В'])));
  304. // exit;
  305. //}
  306. // ВАЖНО ПОНИМАТЬ !!!!
  307. // если проект для такой работы уже есть, его создавать нельзя
  308. // но можно прикреплять к нему задачи. Сотрудник который зашел первый получает и замеры и тмц и работы
  309. // тот кто зашел вторым получает только работы.
  310. //$mappingapiModel = new \app\models\MappingapiModel();
  311. //$dwResult = $mappingapiModel->workDetail($user->uuid,$work['id_work']);
  312. //echo "<pre>";
  313. //var_dump($user->id);
  314. //var_dump($work['work_name']);
  315. //var_dump($dwResult["hw_measurements_status"]);
  316. //var_dump($asusgJob2LaunchEntity->id);
  317. //echo "</pre>";
  318. //continue;
  319. $projtype = $this->getProjectType($work["repair_name"],$work["eq_serie"]);
  320. $switcher = $asusgJob2LaunchEntity;
  321. if ( null == $switcher) {
  322. $this->logger->setLog("\n switcher = null \n");
  323. $resultArr = [];
  324. $asusgJob2LaunchEntity = new AsusgJob2Launch();
  325. $asusgJob2LaunchEntity->asusg_jobplan_id = Yii::$app->params['supercycleplan'];
  326. $asusgJob2LaunchEntity->asusg_employee_id1 = $user->id;
  327. $asusgJob2LaunchEntity->asusg_job_uuid = $work['id_work'];
  328. $asusgJob2LaunchEntity->employees_uuid = $user->uuid;
  329. $asusgJob2LaunchEntity->section_uuid = $work["section_id"];
  330. $asusgJob2LaunchEntity->asusg_project_id = 0;
  331. $asusgJob2LaunchEntity->job_order = 0;
  332. $asusgJob2LaunchEntity->time_limit = $dwResult['time_limit'];
  333. $asusgJob2LaunchEntity->outfit = $dwResult['outfit'];
  334. $asusgJob2LaunchEntity->name = $work['work_name'];
  335. $asusgJob2LaunchEntity->section_name = $work["section_lit"];
  336. //$asusgJob2LaunchEntity->asusg_projecttype_id = 0;
  337. $asusgJob2LaunchEntity->asusg_projecttype_id = $projtype;
  338. if (!$asusgJob2LaunchEntity->save()) {
  339. $this->logger->setLog('в Job2launch не добавилась работа => "'. $work['work_name']. '" Добавление работ будет пропущено так как такая запись уже есть.');
  340. continue;
  341. }
  342. $this->issetLaunch = true;
  343. //$this->logger->setLog($this->prepareLogString);
  344. //$this->prepareLogString = '';
  345. $this->logger->setLog('в Job2launch была добавлена работа => "'. $work['work_name'].'"');
  346. /// сначала генерю проект
  347. $projId = $this->generateProject($work); // работа еще нет нужно получить проект
  348. /// сначала генерю проетк
  349. } else {
  350. $this->logger->setLog("\n switcher != null \n");
  351. $userUuidArr = explode(',', $asusgJob2LaunchEntity->employees_uuid);
  352. //var_dump("1");
  353. if ( in_array( $user->uuid , $userUuidArr)) { // если сотрудник уже привязан к лаунчу
  354. $this->logger->setLog('сотрудник '.$user->name .' ('.$user->id.') уже привязан к лаунчу'. $asusgJob2LaunchEntity->id);
  355. continue;
  356. } else {
  357. $asusgJob2LaunchEntity->employees_uuid .= ','. $user->uuid;
  358. $asusgJob2LaunchEntity->save();
  359. $this->logger->setLog('сотрудники ('.$asusgJob2LaunchEntity->employees_uuid.') привязаны к лаунчу'. $asusgJob2LaunchEntity->id);
  360. }
  361. //var_dump("2");
  362. $projId = $this->getCreateProject($work); // работа уже есть нужно получить проект
  363. //continue;
  364. /*
  365. $this->prepareLogString .= "ВОТ ТУТ Я ХОТЕЛ ПОЛУЧИТЬ ИД ПРОЕКТА ЧЕРЕЗ ЗАДАЧУ( launch_id = ".$asusgJob2LaunchEntity->id.") => " . $asusgJob2LaunchEntity->tasks->id .", ВОТ ЧТО ПОЛУЧИЛ => " . $asusgJob2LaunchEntity->tasks->input_id ."!\n";
  366. $projId = $asusgJob2LaunchEntity->tasks->input_id;
  367. */
  368. $this->logger->setLog("ВОТ ТУТ Я ХОТЕЛ ПОЛУЧИТЬ ИД ПРОЕКТА ЧЕРЕЗ ЗАДАЧУ( launch_id = ".$asusgJob2LaunchEntity->id.") => " . $asusgJob2LaunchEntity->onetask->id .", ВОТ ЧТО ПОЛУЧИЛ => " . $asusgJob2LaunchEntity->onetask->input_id ."!\n");
  369. //var_dump("3");
  370. //$projId = $asusgJob2LaunchEntity->onetask->input_id;
  371. //if ( null == $projId ) {
  372. // $input_idTasks = Tasks::find()->where(['asusg_job_mapped_id' => $asusgJob2LaunchEntity->id])->andWhere(['IS NOT','input_id', null])->one();
  373. // $this->prepareLogString .= "ВОТ ТАК ЧЕРЕЗ ЗАПРОС input_id => ".$input_idTasks->input_id."!\n";
  374. // $projId = $input_idTasks->input_id;
  375. //}
  376. }
  377. $this->createProjects[] = $projId;
  378. /////////////// ДОБАВЛЕНИЕ ЗАДАЧИ
  379. $this->logger->setLog("\n 3. ДОБАВЛЕНИЕ ЗАДАЧИ \n\n");
  380. $this->logger->setLog("\n Метка 1.1 \n");
  381. $tasktypesEntity = Tasktypes::find()->where(['name' => 'Секция '.$let.', задача','company' => $this->company])->one();
  382. $this->logger->setLog("\n Метка 1.2 (типи задачи ".$tasktypesEntity->id.")\n");
  383. // $tasksEnt = Tasks::find()->where(['parent_id' => 0,'asusg_job_mapped_id' => $asusgJob2LaunchEntity->id,'assignees_arr' => $user->id])->one();
  384. $this->statusMaintask = 0;
  385. $mainTaskId = $this->getIssetMainTask($work,$user);
  386. $isCloseMaintask = false;
  387. //var_dump('Задача = '.$mainTaskId);
  388. //var_dump($work["section_lit"] . "\n" . $work["outfit"] . ': ' . $work['work_name'] . "\n" . $dwResult['workers']);
  389. if ( $mainTaskId ) { // !!!!!!!!!!
  390. $this->logger->setLog("\n Задача для " . $work["section_lit"] . " уже есть ". $mainTaskId . "\n\n");
  391. if( 5 == $this->statusMaintask ) {
  392. $isCloseMaintask = true;
  393. }
  394. //var_dump('Такая задача уже есть' . $mainTaskId);
  395. //continue;
  396. } else {
  397. $this->logger->setLog("\n Метка 1.3 \n");
  398. //$this->logger->setLog($this->prepareLogString);
  399. //$this->prepareLogString = '';
  400. $tasksEntity = new Tasks();
  401. $tasksEntity->parent_id = 0;
  402. $tasksEntity->input_id = $projId;
  403. $tasksEntity->status = 2;
  404. $tasksEntity->type = $tasktypesEntity->id;
  405. $tasksEntity->assignees_arr = $this->user->id;
  406. $tasksEntity->preferred_assignee = $this->user->id;
  407. $tasksEntity->created = date("Y-m-d H:i;s");
  408. $tasksEntity->asusg_job_mapped_id = $asusgJob2LaunchEntity->id;
  409. $tasksEntity->mapping_comment = $work["outfit"] . ': ' . $work['work_name'];
  410. $tasksEntity->text = $work["section_lit"] . "\n" . $work["outfit"] . ': ' . $work['work_name'] . "\n" . $dwResult['workers'];
  411. $this->logger->setLog("\n Метка 1.4 \n");
  412. $this->logger->setLog(json_encode($tasksEntity->attributes));
  413. $this->logger->setLog('валидация =>'.json_encode($tasksEntity->validate()));
  414. $this->logger->setLog(json_encode($tasksEntity-> getErrors()));
  415. if($tasksEntity->save()) {
  416. $mainTaskId = $tasksEntity->id;
  417. $this->logger->setLog('в Tasks была добавлена ЗАДАЧА => "'. $work['work_name'] . '" id => '.$tasksEntity->id);
  418. } else {
  419. $this->logger->setLog('в Tasks была НЕ добавлена ЗАДАЧА => "'. $work['work_name']);
  420. }
  421. }
  422. //var_dump('switcher = ' . $switcher->id,$user->id); echo '<br>';
  423. $this->logger->setLog("\n Метка 3 \n");
  424. //$countPriority = 1;
  425. if ( null == $switcher) {
  426. ///////////////// ДОБАВЛЕНИЕ ТМЦ
  427. //$mappingapiModel = new \app\models\MappingapiModel();
  428. //var_dump($user->id-uuid,$work['id_work']);
  429. //$tmcString = $mappingapiModel->workDetail($user->uuid,$work['id_work']);
  430. $this->logger->setLog("\n ДОБАВЛЕНИЕ ТМЦ " . strlen($dwResult['tmcString']) . "\n");
  431. if ( '' != $dwResult['tmcString']) {
  432. $tasksEntity3 = new Tasks();
  433. $tasksEntity3->parent_id = $mainTaskId;
  434. $tasksEntity3->status = 2;
  435. $tasksEntity3->priority = Yii::$app->params['tmcPriority'];
  436. // $tasksEntity2->input_id = $job->asusgJob2Launch->asusg_project_id;
  437. $tasksEntity3->created = date("Y-m-d H:i;s");
  438. $tasksEntity3->type = 2159;
  439. $tasksEntity3->assignees_arr = $this->user->id;
  440. $tasksEntity3->preferred_assignee = $this->user->id;
  441. $tasksEntity3->asusg_job_mapped_id = $asusgJob2LaunchEntity->id;
  442. $tasksEntity3->text = $dwResult['tmcString'];
  443. $tasksEntity3->mapping_comment = $dwResult['tmcString'];
  444. $tasksEntity3->input_id = $projId;
  445. if ( $tasksEntity3->save()) {
  446. //$query3 = "call asusg_add_checkpoints_to_task(" . $user->id . ",'" . $tasksEntity3->id . "')";
  447. //$resProc = Yii::$app->db->createCommand($query3)->query();
  448. $logResProc = 'false';
  449. if ($resProc){
  450. $logResProc = 'true';
  451. }
  452. $this->logger->setLog('в Tasks была добавлена КОМАНДА => "'. $work['work_name'] . '" id => '.$tasksEntity3->id. ' процедура => ' . $logResProc . ' приоритет =>' . Yii::$app->params['countPriority']);
  453. } else {
  454. $this->logger->setLog('в Tasks была НЕ добавлена КОМАНДА => "'. $work['work_name'] . '" id => '.$tasksEntity3->id );
  455. }
  456. Yii::$app->params['countPriority']++;
  457. }
  458. ///////////////////
  459. ///////////////// ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 0
  460. $this->logger->setLog( "\n 4. ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 0 \n");
  461. //if ( Yii::$app->params['api']['hw_msrmnt_stat'][ $dwResult["hw_measurements_status"] ]) { // выполнение hw_measurements_status = waiting
  462. if ( $this->datailWorkArray[$work['id_work']]['measurements'] == null) {
  463. $priority = $queueModel->insertExtraPlan($work,$asusgJob2LaunchEntity,$user->id);
  464. Yii::$app->params['countPriority'] = $priority;
  465. $paramsMeaserm = ['input_id' => $projId, 'assignees_arr' => $user->id, 'work' => $work,'stage' => 0, 'parent_id' => $mainTaskId , 'stage_type' => 'доремонтный','asusg_job_mapped_id' => $asusgJob2LaunchEntity->id ];
  466. Yii::$app->params['api']['mesrmntParam'] = $paramsMeaserm;
  467. MappingapiModel::workMeasurements($work,$user->uuid);
  468. }
  469. ///////////////////
  470. }
  471. /////////////// НА РЕМОНТ
  472. $this->logger->setLog("\n 5. ДОБАВЛЕНИЕ НА РЕМОНТ \n");
  473. $priority = $queueModel->insertExtraPlan($work,$asusgJob2LaunchEntity,$user->id);
  474. //$queueModel->execute($work,$user->uuid);
  475. $tasksEntity2 = new Tasks();
  476. $tasksEntity2->parent_id = $mainTaskId;
  477. $tasksEntity2->status = 2;
  478. $tasksEntity2->priority = $priority;
  479. $tasksEntity2->created = date("Y-m-d H:i;s");
  480. $tasksEntity2->type = Yii::$app->params['supercycletype'];
  481. $tasksEntity2->assignees_arr = $this->user->id;
  482. $tasksEntity2->preferred_assignee = $this->user->id;
  483. $tasksEntity2->asusg_job_mapped_id = $asusgJob2LaunchEntity->id;
  484. $tasksEntity2->text = $work["eq_serie"] . ' '.$work["section_lit"] . ', '. $work["outfit"] . ': ' . $work['work_name'];
  485. $tasksEntity2->input_id = $projId;
  486. $tasksEntity2->mapping_comment = $work["outfit"] . ': ' . $work['work_name'];
  487. if ( $tasksEntity2->save()) {
  488. if ( $isCloseMaintask ) {
  489. $updateTasks = Tasks::findOne($mainTaskId);
  490. $updateTasks->status = 2;
  491. $updateTasks->save();
  492. }
  493. //Yii::$app->params['countPriority']++;
  494. ///////////////////
  495. //$query3 = "call asusg_add_checkpoints_to_task(" . $user->id . ",'" . $tasksEntity2->id . "')";
  496. //$resProc = Yii::$app->db->createCommand($query3)->query();
  497. ///////////////////
  498. $this->logger->setLog('в Tasks была добавлена КОМАНДА => "'. $work['work_name'] . '" id => '.$tasksEntity2->id . ' приоритет =>' . $priority . ', cтатус => ' . $tasksEntity2->status);
  499. } else {
  500. $this->logger->setLog('в Tasks была НЕ добавлена КОМАНДА => "'. $work['work_name'] . '" id => '.$tasksEntity2->id);
  501. }
  502. // $projId = $this->generateProject($work);
  503. //if ( null != $tasksEntity3) {
  504. // $tasksEntity3->input_id = $projId;
  505. //
  506. // if($tasksEntity3->save()){
  507. // $this->logger->setLog('привязка КОМАНДЫ ТМЦ ( id = '.$tasksEntity3->id.') прошла успешно');
  508. // }
  509. //}
  510. if ( null == $switcher) {
  511. ///////////////// ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 1
  512. $this->logger->setLog("\n 6. ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 1 \n");
  513. //if ( Yii::$app->params['api']['hw_msrmnt_stat'][ $dwResult["hw_measurements_status"] ]) { // выполнение hw_measurements_status = waiting
  514. if ( $this->datailWorkArray[$work['id_work']]['measurements'] ) { echo "сверхцикловые замеры 1";echo "<br>";
  515. $paramsMeaserm['stage'] = 1;
  516. $paramsMeaserm['stage_type'] = 'контрольный';
  517. $paramsMeaserm['asusg_job_mapped_id'] = $asusgJob2LaunchEntity->id;
  518. Yii::$app->params['api']['mesrmntParam'] = $paramsMeaserm;
  519. $priority = $queueModel->insertExtraPlan($work,$asusgJob2LaunchEntity,$user->id);
  520. Yii::$app->params['countPriority'] = $priority;
  521. MappingapiModel::workMeasurements($work,$user->uuid);
  522. }
  523. ///////////////////
  524. ///////////////// ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 2
  525. $this->logger->setLog("\n 7. ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 2 \n");
  526. //if ( Yii::$app->params['api']['hw_msrmnt_stat'][ $dwResult["hw_measurements_status"] ]) { // выполнение hw_measurements_status = waiting
  527. if ( $this->datailWorkArray[$work['id_work']]['measurements'] ) { echo "сверхцикловые замеры 2";echo "<br>";
  528. $paramsMeaserm['stage'] = 2;
  529. $paramsMeaserm['stage_type'] = 'послеремонтный';
  530. $paramsMeaserm['asusg_job_mapped_id'] = $asusgJob2LaunchEntity->id;
  531. Yii::$app->params['api']['mesrmntParam'] = $paramsMeaserm;
  532. $priority = $queueModel->insertExtraPlan($work,$asusgJob2LaunchEntity,$user->id);
  533. Yii::$app->params['countPriority'] = $priority;
  534. MappingapiModel::workMeasurements($work,$user->uuid);
  535. }
  536. ///////////////////
  537. }
  538. //( все правильно сначала 2 потом 1)
  539. //echo "<pre>";
  540. //var_dump($tasksEntity2->errors,$tasksEntity->errors);
  541. //echo "</pre>";
  542. //Yii::$app->params['countPriority'] = 1;
  543. }
  544. }
  545. public function addJob2launch3($listWorks,$user)
  546. {
  547. foreach ( $listWorks as $work) {
  548. $this->logger->indx = $user->uuid;
  549. $this->logger->header = $work['id_work'];
  550. Yii::$app->params['countPriority']= 1;
  551. $this->logger->setLog("\n 1. ДОБАВЛЕНИЕ В LAUNCH \n\n");
  552. $asusgJob2LaunchEntity = AsusgJob2Launch::findOne(['asusg_job_uuid' => $work['id_work']]);
  553. $this->addTypeWork($work['id_work'], 1);
  554. $let = mb_substr($work["section_lit"], -1);
  555. // ВАЖНО ПОНИМАТЬ !!!!
  556. // если проект для такой работы уже есть, его создавать нельзя
  557. // но можно прикреплять к нему задачи. Сотрудник который зашел первый получает и замеры и тмц и работы
  558. // тот кто зашел вторым получает только работы.
  559. //$mappingapiModel = new \app\models\MappingapiModel();
  560. //$dwResult = $mappingapiModel->workDetail($user->uuid,$work['id_work']);
  561. $dwResult = $this->datailWorkArray[$work['id_work']];
  562. //echo "<pre>";
  563. //var_dump($user->id);
  564. //var_dump($work['work_name']);
  565. //var_dump($dwResult["hw_measurements_status"]);
  566. //var_dump($dwResult);
  567. //var_dump($user->uuid);
  568. //echo "</pre>";
  569. //continue;
  570. $projtype = $this->getProjectType($work["repair_name"],$work["eq_serie"]);
  571. $JobPlanEntitty = AsusgJobplan::find()->where(['name' => $work["work_name"]])->one(); // 1204 1567
  572. if ( null == $JobPlanEntitty->id ) {
  573. $this->logger->setLog(" ВНИМАНИЕ не нашел работу в AsusgJobplan ('name' => ".$work['work_name'].")\n\n");
  574. }
  575. $jsusgJob2CommandEntity = AsusgJob2Command::find()->where(['asusg_job_id' => $JobPlanEntitty->id, 'asusg_projecttype_id' => $projtype ])->all();
  576. if ( null == $jsusgJob2CommandEntity || 0 == count($jsusgJob2CommandEntity)){
  577. $this->listWorkForExtraArray[] = $work;
  578. $this->logger->setLog(" ВНИМАНИЕ не нашел работу в asusgJob2Command ('name' => ".$work['work_name'].")\n\n");
  579. continue;
  580. }
  581. $switcher = $asusgJob2LaunchEntity;
  582. if ( null == $switcher) {
  583. $resultArr = [];
  584. $asusgJob2LaunchEntity = new AsusgJob2Launch();
  585. $asusgJob2LaunchEntity->asusg_jobplan_id = $JobPlanEntitty->id;
  586. $asusgJob2LaunchEntity->asusg_employee_id1 = $user->id;
  587. $asusgJob2LaunchEntity->asusg_job_uuid = $work['id_work'];
  588. $asusgJob2LaunchEntity->employees_uuid = $user->uuid;
  589. $asusgJob2LaunchEntity->section_uuid = $work["section_id"];
  590. $asusgJob2LaunchEntity->asusg_project_id = 0;
  591. $asusgJob2LaunchEntity->job_order = 0;
  592. $asusgJob2LaunchEntity->asusg_projecttype_id = $projtype;
  593. $asusgJob2LaunchEntity->time_limit = $dwResult['time_limit'];
  594. $asusgJob2LaunchEntity->outfit = $dwResult['outfit'];
  595. $asusgJob2LaunchEntity->name = $work['work_name'];
  596. $asusgJob2LaunchEntity->section_name = $work["section_lit"];
  597. if (!$asusgJob2LaunchEntity->save()) {
  598. $this->logger->setLog('в Job2launch не добавилась работа => "'. $work['work_name']. '" Добавление работ будет пропущено так как такая запись уже есть.');
  599. continue;
  600. }
  601. $this->issetLaunch = true;
  602. //$this->logger->setLog($this->prepareLogString);
  603. //$this->prepareLogString = '';
  604. $this->logger->setLog('в Job2launch была добавлена работа => "'. $work['work_name'].'"');
  605. /// сначала генерю проект
  606. $projId = $this->generateProject($work);
  607. /// сначала генерю проект
  608. } else {
  609. $userUuidArr = explode(',', $asusgJob2LaunchEntity->employees_uuid);
  610. if ( in_array( $user->uuid , $userUuidArr)) { // если сотрудник уже привязан к лаунчу
  611. $this->logger->setLog('сотрудник '.$user->name .' ('.$user->id.') уже привязан к лаунчу'. $asusgJob2LaunchEntity->id);
  612. continue;
  613. } else {
  614. $asusgJob2LaunchEntity->employees_uuid .= ','. $user->uuid;
  615. $asusgJob2LaunchEntity->save();
  616. $this->logger->setLog('сотрудники ('.$asusgJob2LaunchEntity->employees_uuid.') привязаны к лаунчу'. $asusgJob2LaunchEntity->id);
  617. }
  618. //continue;
  619. /*
  620. $this->prepareLogString .= "ВОТ ТУТ Я ХОТЕЛ ПОЛУЧИТЬ ИД ПРОЕКТА ЧЕРЕЗ ЗАДАЧУ => " . $asusgJob2LaunchEntity->tasks->id .", ВОТ ЧТО ПОЛУЧИЛ => " . $asusgJob2LaunchEntity->tasks->input_id ."!\n";
  621. $projId = $asusgJob2LaunchEntity->tasks->input_id;
  622. */
  623. $projId = $this->getCreateProject($work); // работа уже есть нужно получить проект
  624. //$this->prepareLogString .= "ВОТ ТУТ Я ХОТЕЛ ПОЛУЧИТЬ ИД ПРОЕКТА ЧЕРЕЗ ЗАДАЧУ => " . $asusgJob2LaunchEntity->onetask->id .", ВОТ ЧТО ПОЛУЧИЛ => " . $asusgJob2LaunchEntity->onetask->input_id ."!\n";
  625. //$projId = $asusgJob2LaunchEntity->onetask->input_id;
  626. //if ( null == $projId ) {
  627. // $input_idTasks = Tasks::find()->where(['asusg_job_mapped_id' => $asusgJob2LaunchEntity->id])->andWhere(['IS NOT','input_id', null])->one();
  628. // $this->prepareLogString .= "ВОТ ТАК ЧЕРЕЗ ЗАПРОС input_id => ".$input_idTasks->input_id."!\n";
  629. // $projId = $input_idTasks->input_id;
  630. //}
  631. }
  632. /////////////// ДОБАВЛЕНИЕ ЗАДАЧИ
  633. $this->logger->setLog("\n 3. ДОБАВЛЕНИЕ ЗАДАЧИ \n\n");
  634. $tasktypesEntity = Tasktypes::find()->where(['name' => 'Секция '.$let.', задача','company' => $this->company])->one();
  635. $this->statusMaintask = 0;
  636. $mainTaskId = $this->getIssetMainTask($work,$user);
  637. $isCloseMaintask = false;
  638. if ( $mainTaskId ) { // !!!!!!!!!!
  639. //echo "Такая задача( цикловая ) уже есть";
  640. $this->logger->setLog("\n Такая задача( цикловая ) уже есть \n\n");
  641. if( 5 == $this->statusMaintask ) {
  642. $isCloseMaintask = true;
  643. }
  644. //$tasksEnt = Tasks::find()->where(['parent_id' => 0,'asusg_job_mapped_id' => $asusgJob2LaunchEntity->id,'assignees_arr' => $user->id])->one();
  645. //if ( null != $tasksEnt) {
  646. //continue;
  647. } else {
  648. //$this->logger->setLog($this->prepareLogString);
  649. //$this->prepareLogString = '';
  650. $tasksEntity = new Tasks();
  651. $tasksEntity->parent_id = 0;
  652. $tasksEntity->status = 2;
  653. $tasksEntity->type = $tasktypesEntity->id;
  654. $tasksEntity->assignees_arr = $user->id;
  655. $tasksEntity->preferred_assignee = $user->id;
  656. $tasksEntity->created = date("Y-m-d H:i;s");
  657. $tasksEntity->asusg_job_mapped_id = $asusgJob2LaunchEntity->id;
  658. $tasksEntity->mapping_comment = $work["outfit"] . ': ' . $work['work_name'];
  659. $tasksEntity->text = $work["section_lit"] . "\n" . $work["outfit"] . ': ' . $work['work_name'] . "\n" . $dwResult['workers'];
  660. $tasksEntity->input_id = $projId;
  661. if($tasksEntity->save()) {
  662. $mainTaskId = $tasksEntity->id;
  663. //$this->testIdpl3 = $tasksEntity->id;
  664. $this->logger->setLog('в Tasks была добавлена ЗАДАЧА => "'. $work['work_name'] . '" id => '.$tasksEntity->id);
  665. } else {
  666. $this->logger->setLog('в Tasks была НЕ добавлена ЗАДАЧА => "'. $work['work_name'] . '" id => '.$tasksEntity->id);
  667. continue;
  668. }
  669. //var_dump($tasksEntity->errors,$user->id); echo '<br>';
  670. $this->logger->setLog(' колво записей => ' . count($jsusgJob2CommandEntity) . 'type => '. gettype($jsusgJob2CommandEntity));
  671. }
  672. $arrJ = [];
  673. //$countPriority = 1;
  674. /////////////////
  675. if ( null == $switcher) {
  676. $this->logger->setLog("switcher = null");
  677. ///////////////// ДОБАВЛЕНИЕ ТМЦ
  678. $mappingapiModel = new \app\models\MappingapiModel();
  679. //var_dump($user->id-uuid,$work['id_work']);
  680. $this->logger->setLog("сотрудник => " . $user->uuid . ", работа => " . $work['id_work']);
  681. //$tmcString = $mappingapiModel->workDetail($user->uuid,$work['id_work']);
  682. $this->logger->setLog("\n ДОБАВЛЕНИЕ ТМЦ " . strlen($dwResult['tmcString']) . "\n");
  683. if ( '' != $dwResult['tmcString']) {
  684. $tasksEntity3 = new Tasks();
  685. $tasksEntity3->parent_id = $tasksEntity->id; // +
  686. $tasksEntity3->status = 2; // +
  687. $tasksEntity3->priority = Yii::$app->params['tmcPriority']; // +
  688. // $tasksEntity2->input_id = $job->asusgJob2Launch->asusg_project_id;
  689. $tasksEntity3->created = date("Y-m-d H:i;s"); // +
  690. $tasksEntity3->type = 2159; // +
  691. $tasksEntity3->assignees_arr = $user->id; // +
  692. $tasksEntity3->preferred_assignee = $user->id; // +
  693. $tasksEntity3->asusg_job_mapped_id = $asusgJob2LaunchEntity->id;
  694. $tasksEntity3->text = $dwResult['tmcString']; // +
  695. $tasksEntity3->mapping_comment = $dwResult['tmcString']; // +
  696. $tasksEntity3->input_id = $projId;
  697. if ( $tasksEntity3->save()) {
  698. //var_dump('создана ТМЦ, задача =>' . $tasksEntity3->id);
  699. $arrJ[] = $tasksEntity3->id;
  700. $query3 = "call asusg_add_checkpoints_to_task(" . $user->id . ",'" . $tasksEntity3->id . "')";
  701. $resProc = Yii::$app->db->createCommand($query3)->query();
  702. $logResProc = 'false';
  703. if ($resProc){
  704. $logResProc = 'true';
  705. }
  706. $this->logger->setLog('в Tasks была добавлена КОМАНДА => "'. $work['work_name'] . '" id => '.$tasksEntity3->id. ' процедура => ' . $logResProc);
  707. } else {
  708. //var_dump('не создана ТМЦ');
  709. $this->logger->setLog('в Tasks была НЕ добавлена КОМАНДА => "'. $work['work_name'] . '" id => '.$tasksEntity3->id);
  710. }
  711. //Yii::$app->params['countPriority']++;
  712. }
  713. ///////////////////
  714. ///////////////// ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 0
  715. $this->logger->setLog("\n 4. ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 0 \n");
  716. //var_dump(Yii::$app->params['api']['hw_msrmnt_stat'][ $dwResult["hw_measurements_status"] ],$dwResult["hw_measurements_status"]); echo "\n";
  717. //if ( Yii::$app->params['api']['hw_msrmnt_stat'][ $dwResult["hw_measurements_status"] ]) { // выполнение hw_measurements_status = waiting
  718. if ( $this->datailWorkArray[$work['id_work']]['measurements'] ) {
  719. //Yii::$app->params['countPriority'] = (($job->original_order*100)-1);
  720. Yii::$app->params['countPriority'] = (100-1);
  721. $this->logger->setLog('приоритет '.(100-1));
  722. $paramsMeaserm = ['input_id' => $projId, 'assignees_arr' => $user->id, 'work' => $work,'stage' =>0, 'parent_id' => $tasksEntity->id ,'stage_type' => 'доремонтный','asusg_job_mapped_id' => $asusgJob2LaunchEntity->id];
  723. Yii::$app->params['api']['mesrmntParam'] = $paramsMeaserm;
  724. MappingapiModel::workMeasurements($work,$user->uuid);
  725. }
  726. ///////////////////
  727. }
  728. /////////////// НА РЕМОНТ
  729. $this->logger->setLog("\n 5. ДОБАВЛЕНИЕ НА РЕМОНТ \n");
  730. $countpr = 100;
  731. foreach($jsusgJob2CommandEntity as $job) {
  732. $job->job_uuid = $work['id_work'];
  733. $tasksEntity2 = new Tasks();
  734. $tasksEntity2->parent_id = $mainTaskId;
  735. $tasksEntity2->status = 2;
  736. $tasksEntity2->priority = ($job->original_order*100);//Yii::$app->params['countPriority'];
  737. // $tasksEntity2->input_id = $job->asusgJob2Launch->asusg_project_id;
  738. $tasksEntity2->created = date("Y-m-d H:i;s");
  739. $tasksEntity2->type = $job->smopp_cmd_id;//Yii::$app->params['supercycletype'];
  740. $tasksEntity2->assignees_arr = $user->id;
  741. $tasksEntity2->preferred_assignee = $user->id;
  742. $tasksEntity2->asusg_job_mapped_id = $job->jobplantieuuid->id;
  743. $tasksEntity2->text = $work["eq_serie"] . ' '.$work["section_lit"] . ', '. $work["outfit"] . ':' . $work['work_name'].'..';
  744. $tasksEntity2->mapping_comment = $work["outfit"] . ': ' . $job->tasktypes->name;
  745. $tasksEntity2->input_id = $projId;
  746. if ( $tasksEntity2->save()) {
  747. if ( $isCloseMaintask ) {
  748. $taskEntity = Task::findOne($mainTaskId);
  749. $taskEntity->status = 2;
  750. $taskEntity->save();
  751. $isCloseMaintask = false;
  752. }
  753. //$arrJ[] = $tasksEntity2->id;
  754. ///////////////////
  755. //$query3 = "call asusg_add_checkpoints_to_task(" . $user->id . ",'" . $tasksEntity2->id . "')";
  756. //$resProc = Yii::$app->db->createCommand($query3)->query();
  757. ///////////////////
  758. $this->logger->setLog('в Tasks была добавлена КОМАНДА => "'. $work['work_name'] . '" id => '.$tasksEntity2->id);
  759. } else {
  760. $this->logger->setLog('в Tasks была НЕ добавлена КОМАНДА => "'. $work['work_name'] . '" id => '.$tasksEntity2->id);
  761. }
  762. if ( ($job->original_order*100) > $countpr ) {
  763. $countpr = ($job->original_order*100);
  764. }
  765. }
  766. /////////////////////////////////////
  767. // $projId = $this->generateProject3($work);
  768. //$tasksEntity->input_id = $tasksEntity->input_id ?? $projId;
  769. //if ($tasksEntity->save()) {
  770. // $this->logger->setLog('привязка ЗАДАЧИ ( id = '.$tasksEntity->id.') прошла успешно');
  771. //}
  772. $tasksEntity = null;
  773. /*
  774. foreach($arrJ as $job_id) {
  775. $tasksEnt = Tasks::findOne($job_id);
  776. $tasksEnt->input_id = $tasksEnt->input_id ?? $projId;
  777. if($tasksEnt->save()){
  778. $this->logger->setLog('привязка КОМАНДЫ ( id = '.$tasksEntity2->id.') прошла успешно');
  779. } else {
  780. $this->logger->setLog('привязка КОМАНДЫ ( id = '.$tasksEntity2->id.') прошла не успешно');
  781. }
  782. }
  783. */
  784. if ( null != $tasksEntity3) {
  785. $tasksEntity3->input_id = $projId;
  786. //if($tasksEntity3->save()){
  787. // $this->logger->setLog('привязка КОМАНДЫ ТМЦ ( id = '.$tasksEntity3->id.') прошла успешно');
  788. //}
  789. }
  790. if ( null == $switcher) {
  791. ///////////////// ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 1
  792. $this->logger->setLog("\n 6. ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 1 \n");
  793. //if ( Yii::$app->params['api']['hw_msrmnt_stat'][ $dwResult["hw_measurements_status"] ]) { // выполнение hw_measurements_status = waiting
  794. if ( $this->datailWorkArray[$work['id_work']]['measurements'] ) {
  795. $paramsMeaserm['stage'] = 1;
  796. $paramsMeaserm['stage_type'] = 'контрольный';
  797. $paramsMeaserm['asusg_job_mapped_id'] = $asusgJob2LaunchEntity->id;
  798. //Yii::$app->params['countPriority'] = (($job->original_order*100)+1);
  799. Yii::$app->params['countPriority'] = ($countpr+1);
  800. $this->logger->setLog('приоритет '.($countpr+1));
  801. Yii::$app->params['api']['mesrmntParam'] = $paramsMeaserm;
  802. MappingapiModel::workMeasurements($work,$user->uuid);
  803. }
  804. ///////////////////
  805. ///////////////// ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 2
  806. $this->logger->setLog("\n 7. ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 2 \n");
  807. //if ( Yii::$app->params['api']['hw_msrmnt_stat'][ $dwResult["hw_measurements_status"] ]) { // выполнение hw_measurements_status = waiting
  808. if ( $this->datailWorkArray[$work['id_work']]['measurements'] ) {
  809. $paramsMeaserm['stage'] = 2;
  810. $paramsMeaserm['stage_type'] = 'послеремонтный';
  811. $paramsMeaserm['asusg_job_mapped_id'] = $asusgJob2LaunchEntity->id;
  812. Yii::$app->params['countPriority'] = ($countpr+2);
  813. $this->logger->setLog('приоритет '.($countpr+2));
  814. Yii::$app->params['api']['mesrmntParam'] = $paramsMeaserm;
  815. MappingapiModel::workMeasurements($work,$user->uuid);
  816. }
  817. ///////////////////
  818. }
  819. //echo "<pre>";
  820. //var_dump($job->asusgJob2Launch->asusg_project_id);
  821. //var_dump($tasksEntity2->errors,$tasksEntity->errors);
  822. //echo "</pre>";
  823. }
  824. }
  825. public function generateProject($work){
  826. $this->logger->setLog("\n 2. ГЕНЕРАЦИЯ ПРОЕКТА \n");
  827. $result = '';
  828. $status = '';
  829. $let = mb_substr($work["section_lit"], -1);
  830. $sectionsEntity = Sections::find()->select(['id', 'diagnostic_map'])
  831. //->where(['locomotive_series' => $work["eq_serie"],'section_number' => mb_substr($work['section_lit'],0,-1),'letter' => $let])
  832. ->where(['locomotive_series' => $work["eq_serie"],'section_number' => mb_substr($work['section_lit'],0,-1),'section_subnumber' => $work["section_num"]])
  833. ->one();
  834. $this->logger->setLog("Параметры локомотива locomotive_series => " . $work["eq_serie"]. ", section_number => " . $work['section_lit'] . " ,letter => " .$let. " \n");
  835. $diagnostic_map = $sectionsEntity->diagnostic_map;
  836. if ( null == $sectionsEntity->id) {
  837. $sectionsEntity2 = new Sections();
  838. $sectionsEntity2->locomotive_series = $work["eq_serie"];
  839. $sectionsEntity2->section_number = mb_substr($work['section_lit'],0,-1);
  840. $sectionsEntity2->section_subnumber = $work["section_num"];
  841. $sectionsEntity2->diagnostic_map = $work["section_DK"];
  842. $sectionsEntity2->uuid = $work["section_id"];
  843. $sectionsEntity2->letter = $let;
  844. if ( $sectionsEntity2->save()) {
  845. $this->logger->setLog('в Sections была добавлена новая секция => '. $work["section_num"] . ' id => '.$sectionsEntity2->id);
  846. } else {
  847. //var_dump($sectionsEntity2->errors);
  848. $this->logger->setLog('в Sections при добавлении секции произошли ошибки => '. count($sectionsEntity2->errors) . ' шт.');
  849. $sectionsEntity->diagnostic_map = $work['section_DK'];
  850. $sectionsEntity->save();
  851. $this->logger->setLog('Пришлось просто обновить диагностическую карту секция=> '. $sectionsEntity . ', номер карты =>' . $work['section_DK']);
  852. }
  853. $diagnostic_map = $sectionsEntity->diagnostic_map;
  854. }
  855. else if( ( null == $sectionsEntity->diagnostic_map ) || ($sectionsEntity->diagnostic_map != $work['section_DK'])) {
  856. //else if( null == $sectionsEntity->diagnostic_map) {
  857. $sectionsEntity->diagnostic_map = $work['section_DK'];
  858. $sectionsEntity->save();
  859. }
  860. $this->logger->setLog('Условие проверки1: ' . $sectionsEntity->diagnostic_map .'=='. $work['section_DK']);
  861. $this->logger->setLog('Условие проверки1: ' . $sectionsEntity2->diagnostic_map .'=='. $work['section_DK']);
  862. if ( $sectionsEntity->diagnostic_map == $work['section_DK'] ) {
  863. $projectRes = $this->getIssetProject($work);
  864. $result = ( isset($projectRes['id']) ) ? $projectRes['id'] : '' ;
  865. $status = ( isset($projectRes['status']) ) ? $projectRes['status'] : '' ;
  866. $this->logger->setLog('в Sections секция с такой диагностической картой => '. $work['section_DK'] . ' существует. Ид проекта '. $result);
  867. }
  868. if ( $sectionsEntity2->diagnostic_map == $work['section_DK'] ) {
  869. $projectRes = $this->getIssetProject($work);
  870. $result = ( isset($projectRes['id']) ) ? $projectRes['id'] : '' ;
  871. $status = ( isset($projectRes['status']) ) ? $projectRes['status'] : '' ;
  872. $this->logger->setLog('в Sections секция с такой диагностической картой => '. $work['section_DK'] . ' существует. Ид проекта '. $result);
  873. }
  874. $ProjectsL = ProjectsLocotech::findOne($result);
  875. $status = $ProjectsL->status;
  876. //if (!$result) {
  877. if ((!$result) || ( 5 == $status )) {
  878. $this->logger->setLog('Условие проверки2: '.(!$result) .' статус '. $status . json_encode($projectRes));
  879. $result = $this->generateProject3($work);
  880. $this->logger->setLog('Такого проекта еще не было пришлось создать. Ид проекта => '. $result);
  881. }
  882. //var_dump($result);
  883. return $result;
  884. }
  885. public function generateProject3($work){
  886. $result = '';
  887. $projectsLocotech = new ProjectsLocotech();
  888. $projectsLocotech->action = 197 ;
  889. $projectsLocotech->company = $this->company;
  890. $projectsLocotech->status = 2;
  891. $projectsLocotech->loco_type = $work["eq_serie"];
  892. $projectsLocotech->loco_number = $work["eq_number"];
  893. $projectsLocotech->depo ='' ;
  894. $projectsLocotech->depo_service = '';
  895. $projectsLocotech->created = date('Y-m-d H:i:s');
  896. $projectsLocotech->urgent = 0;
  897. $projectsLocotech->uuid = $work['work_name'].":".$work['repair_name'].",".$work["eq_serie"];
  898. $projectsLocotech->save();
  899. $result = $projectsLocotech->id;
  900. //$this->logger->setLog('Такого проекта еще не было пришлось создать. Ид проекта => '. $result);
  901. //var_dump($result);
  902. return $result;
  903. }
  904. private function getCreateProject($work) {
  905. $result = '';
  906. $projectRes = $this->getIssetProject($work);
  907. $result = $projectRes['id'];
  908. $status = $projectRes['status'];
  909. //if ((!$result) || ( 5 == $status )) {
  910. // $result = $this->generateProject3($work);
  911. // $this->logger->setLog('Такого проекта еще не было пришлось создать. Ид проекта => '. $result);
  912. //}
  913. return $result;
  914. }
  915. private function getIssetProject($work) {
  916. $query = "select pl.id, pl.status from projects_locotech pl
  917. inner join tasks t on pl.id = t.input_id
  918. where pl.company = " . $this->company . "
  919. and pl.loco_type = '" . $work["eq_serie"] . "'
  920. and pl.loco_number = " . $work["eq_number"] . "
  921. and t.parent_id = 0
  922. and pl.uuid like '%" . $work['repair_name']. ",%'
  923. order by pl.id desc
  924. limit 1";
  925. $this->logger->setLog('Текст запроса ' . $query);
  926. $projectRes = Yii::$app->db->createCommand($query)->queryOne();
  927. //$result = $projectId['id'];
  928. //$status = $projectId['satus'];
  929. return $projectRes;
  930. }
  931. private function getIssetMainTask($work,$user) {
  932. $result = null;
  933. $query = "select t.id as task_id, pl.status, t.status as maintask_status
  934. from projects_locotech pl
  935. inner join tasks t on pl.id = t.input_id
  936. left join tasks tc on tc.parent_id = t.id
  937. where pl.company = " . $this->company . "
  938. and pl.loco_type = '" . $work["eq_serie"] . "'
  939. and pl.loco_number = " . $work["eq_number"] . "
  940. and t.parent_id = 0
  941. and pl.status <> 5
  942. and tc.text like '%" . $work["section_lit"]. "%'
  943. and tc.assignees_arr = " . $user->id . "
  944. and pl.uuid like '%" . $work["repair_name"]. "%'
  945. order by pl.id desc
  946. limit 1";
  947. //echo $query;
  948. $this->logger->setLog('Текст запроса ' . $query);
  949. $projectRes = Yii::$app->db->createCommand($query)->queryOne();
  950. //echo $projectRes['task_id'];
  951. $this->logger->setLog('Текст ответа ' . json_encode($projectRes));
  952. if ( is_array($projectRes) and !empty($projectRes)){
  953. $result = $projectRes['task_id'];
  954. $this->statusMaintask = $projectRes['maintask_status'];
  955. }
  956. return $result;
  957. }
  958. private function getIssetMainTask_false($work,$user) {
  959. $result = null;
  960. $asusgJob2LaunchEntity = AsusgJob2Launch::find()->where(['asusg_job_uuid' => $work['id_work']])->andWhere(['like','employees_uuid', $user->uuid])->one();
  961. $tasksEntity = Tasks::find()->where(['parent_id' => 0,'asusg_job_mapped_id' => $asusgJob2LaunchEntity->id, 'assignees_arr' => $user->id])->one();
  962. $this->logger->setLog('Запрос на существовании задачи, ответ =>' . $tasksEntity->id);
  963. if ( $tasksEntity->id ){
  964. $result = $tasksEntity->id;
  965. }
  966. return $result;
  967. }
  968. private function prepareListWorks($listWorks) {
  969. $result = [];
  970. $dataArr = [];
  971. if ( null == $listWorks || empty($listWorks)) {
  972. return [];
  973. }
  974. foreach ( $listWorks["rows"] as $rows) {
  975. $rows["result"] = json_decode($rows["result"],true);
  976. foreach ( $rows["result"]['data'] as $key => $data) {
  977. //echo '<pre>';
  978. // var_dump($data);
  979. // echo '</pre>';
  980. $tempArray = [];
  981. $tempArray["eq_serie"] = explode(" ",$data["equip_sect_name"])[0];
  982. $eq = explode(" ",$data["equip_sect_name"])[1];
  983. $tempArray["eq_number"] = explode("/",$eq)[0];
  984. //echo '<pre>';
  985. //var_dump($tempArray["eq_number"]);
  986. //echo '</pre>';
  987. foreach ( $data["sections"] as $sections) {
  988. $tempArray["section_id"] = $sections["id_section"];
  989. $tempArray["section_lit"] = $sections["section_name"];
  990. //$this->getLocoInfoMore($sections["section_subnumber"]);
  991. $tempArray["section_num"] = $sections["section_subnumber"];
  992. $tempArray["section_DK"] = $sections["section_dk"];
  993. // echo '<pre>';
  994. // var_dump($sections);
  995. // echo '</pre>';
  996. foreach ( $sections['works'] as $work) {
  997. $tempArray["id_work"] = $work["id_work"];
  998. $tempArray["outfit"] = $work["outfit"];
  999. $tempArray["work_name"] = $work["work_name"];
  1000. $tempArray["repair_name"] = $work["repair_type"];
  1001. $tempArray["work_status"] = $work["work_status"];
  1002. $tempArray["repeats"] = $work["repeats"];
  1003. //$extraSection = $this->getSectionInfo( $tempArray["section_id"], $tempArray["repair_name"]);
  1004. //$tempArray["section_num"] = $extraSection['section_num'];
  1005. //$tempArray['section_DK'] = $extraSection['section_DK'];
  1006. foreach ( $work['workers'] as $worker) {
  1007. $tempArray['workers'][] = $worker;
  1008. //echo '<pre>';
  1009. //var_dump($worker);
  1010. //echo '</pre>';
  1011. }
  1012. $dataArr[] = $tempArray;
  1013. }
  1014. }
  1015. }
  1016. $result['result'] = 'true';
  1017. $result['data'] = $dataArr;
  1018. break;
  1019. }
  1020. return $result;
  1021. }
  1022. private function sectionList() {
  1023. $result = [];
  1024. //$params['place'] = 'a84d0a15-08ec-11e5-829d-00155d6cab05';
  1025. //$params['place'] = '95d7646d-e7ee-11e4-829d-00155d6cab05';
  1026. $params['place'] = 'a84d0a15-08ec-11e5-829d-00155d6cab05';
  1027. $params['date'] = '1581324560';
  1028. $locomotiveModel = new LocomotiveModel();
  1029. $result = $locomotiveModel->getSectionList($params);
  1030. //$result = json_decode($result,true);
  1031. //$this->sectionList = $result['array'];
  1032. $this->sectionList = json_decode($result,true);
  1033. return $result;
  1034. }
  1035. private function getSectionInfo( $id,$repair) {
  1036. $result = [];
  1037. if (empty($this->sectionList)) {
  1038. $this->sectionList();
  1039. }
  1040. foreach ($this->sectionList as $items) {
  1041. //var_dump($section["Section"] .' == '. $id , $section['TypeOfRepair'] .' == '. $repair); echo '<br>';
  1042. foreach ( $items as $section) {
  1043. if ( $section["Section"] == $id and $section['TypeOfRepair'] == $repair ) {
  1044. $result['section_num'] = $section["NumberSection"];
  1045. $result['section_DK'] = $section['DiagnosticMapslocomotive'];
  1046. return $result;
  1047. }
  1048. }
  1049. }
  1050. return $result;
  1051. }
  1052. private function buisyEmployee($user){
  1053. $tasksEntity = Tasks::find()->where(['assignees_arr' => $user->id])->andWhere(['<>','status',5])->all();
  1054. if ( 0 < count($tasksEntity)){
  1055. //var_dump('Return =>true');
  1056. return true;
  1057. }
  1058. //var_dump('Return =>false');
  1059. return false;
  1060. }
  1061. private function clearEmptyProjects() {
  1062. if (empty($this->createProjects)) {
  1063. return true;
  1064. }
  1065. $projectsArray = array_unique($this->createProjects);
  1066. foreach ($projectsArray as $proj){
  1067. $tasksEntity = Tasks::find()->where(['input_id' => $proj])->all();
  1068. if ( 0 == count($tasksEntity)){
  1069. $projectsLocotech = ProjectsLocotech::findOne($proj);
  1070. $projectsLocotech->delete();
  1071. }
  1072. }
  1073. return true;
  1074. }
  1075. // ЗАПИСЬ В ТАБЛИЦУ ОТВЕТА ОТ ЕИПП MYWORKS
  1076. // params => $listWorks: array
  1077. //
  1078. // result => bolean
  1079. private function insertEippJob($listWorks) {
  1080. foreach( $listWorks['data'] as $work) {
  1081. $myworkEntity = new Mywork();
  1082. $myworkEntity->id_work = $work['id_work'];
  1083. $myworkEntity->section_DK = $work['section_DK'];
  1084. $myworkEntity->eq_number = $work['eq_number'];
  1085. $myworkEntity->repeats = $work['repeats'];
  1086. $myworkEntity->outfit = $work['outfit'];
  1087. $myworkEntity->work_name = $work['work_name'];
  1088. $myworkEntity->section_id = $work['section_id'];
  1089. $myworkEntity->section_num = $work['section_num'];
  1090. $myworkEntity->section_lit = $work['section_lit'];
  1091. $myworkEntity->repair_name = $work['repair_name'];
  1092. $myworkEntity->eq_serie = $work['eq_serie'];
  1093. $myworkEntity->save();
  1094. }
  1095. }
  1096. // ПОЛУЧЕНИ ДЕТАЛИЗАЦИИ ПО РАБОТЕ
  1097. // params => $user_id: string
  1098. // $work_id: string
  1099. //
  1100. // result => bolean
  1101. public function workDetail($user_id, $work_id)
  1102. {
  1103. $myworkEntity = Mywork::findOne(['id_work' => $work_id,'detail' => 1]);
  1104. if( $myworkEntity ){
  1105. return true;
  1106. }
  1107. $this->GWparams = [
  1108. 'url' => Yii::$app->params['api']['domain'] . $this->url . 'work_detail',
  1109. 'param' => [
  1110. 'user_id' => $user_id,
  1111. 'id_work' => $work_id
  1112. ]];
  1113. //ElasticLog::eipp($this->GWparams, $work_id, $user_id);
  1114. $response = $this->curlRequestUni($this->GWparams,'post');
  1115. $work = json_decode($response,true);
  1116. //ElasticLog::eipp($response, $work_id, $user_id, false);
  1117. $tmcList = $this->getTmcList($work);
  1118. $myworkEntity = Mywork::findOne(['id_work' => $work_id]);
  1119. $myworkEntity->hw_measurements_status = $tmcList['hw_measurements_status'];
  1120. $myworkEntity->repeats = $tmcList['repeats'];
  1121. $myworkEntity->time_limit = $tmcList['time_limit'];
  1122. $myworkEntity->work_part_percent = $tmcList['work_part_percent'];
  1123. $myworkEntity->time_remain = $tmcList['time_remain'];
  1124. $myworkEntity->cam_list = json_encode($tmcList['cam_list']);
  1125. $myworkEntity->equipement_name = $tmcList['equipement_name'];
  1126. $myworkEntity->equipement_number = $tmcList['equipement_number'];
  1127. $myworkEntity->work_status = $tmcList['work_status'];
  1128. $myworkEntity->measurements = $tmcList['measurements'];
  1129. $myworkEntity->tmsString = $tmcList['tmsString'];
  1130. $myworkEntity->detail = 1;
  1131. $myworkEntity->save();
  1132. return true;
  1133. }
  1134. // МЕППИНГ ОТВЕТА ПО ДЕТАЛИЗАЦИИ
  1135. // params => $work: array
  1136. //
  1137. // result => array
  1138. public function getTmcList($work) {
  1139. $result = [];
  1140. $tenpArray = [];
  1141. $count = 1;
  1142. foreach($work['rows'] as $tmc1) {
  1143. foreach($tmc1 as $tmc2) {
  1144. $tmc2 = json_decode($tmc2,true);
  1145. foreach($tmc2['data'] as $key => $tmc3) {
  1146. $result[$key] = $tmc3;
  1147. foreach($tmc3 as $tmc4) {
  1148. if ( '' != $tmc4["tmc_name"]) {
  1149. $tenpArray[] = $tmc4["tmc_name"];
  1150. }
  1151. }
  1152. if ( 'workers' == $key) {
  1153. $result['workers'] = [];
  1154. foreach($tmc3 as $key => $tmc5) {
  1155. $result['workers'][] = $tmc5['fio'];
  1156. $result['workers_uuid'][] = $tmc5['id'];
  1157. }
  1158. }
  1159. if ( 'measurements' == $key) {
  1160. $result['measurements'] = $this->CheckmeasurementField($tmc3);
  1161. }
  1162. }
  1163. }
  1164. }
  1165. $result['tmcString'] = '';
  1166. if ( !empty($tenpArray) ) {
  1167. $result['tmcString'] = implode("\n * ", $tenpArray);
  1168. $result['tmcString'] = "* " . $result['tmcString'];
  1169. }
  1170. $result['workers'] = 'Назначены: ' . implode(', ',$result['workers']);
  1171. return $result;
  1172. }
  1173. // ПРОВЕРКА ПОЛЯ ЗАМЕРЫ, НА НЕОБХОДИМОСТЬ ИХ ЗАПРАШИВАТЬ
  1174. // params => $msrm: string
  1175. //
  1176. // result => boolean
  1177. private function CheckmeasurementField($msrm) {
  1178. $msrmArr = explode('/', $msrm );
  1179. if ( (count($msrmArr) > 1) && ($msrmArr[0] == $msrmArr[1]) ) {
  1180. return false; // если $msrm = 25/25/0 и (25==25) то можно не запрашивать замеры
  1181. }
  1182. return true; // если $msrm = 25/24/0 и (25!=24) то запрашивать замеры
  1183. }
  1184. // ЗАПИСЬ В ТАБЛИЦУ СВЯЗКА РАБОТА <==> ПОЛЬЗОВАТЕЛЬ
  1185. // params => $user: string
  1186. // $work: string
  1187. //
  1188. // result => bolean
  1189. private function attachWorkUser($work,$user) {
  1190. //var_dump($work,$user);
  1191. $workworkerEntity = new Workworker();
  1192. $workworkerEntity->id_work = $work;
  1193. $workworkerEntity->workers = $user;
  1194. $workworkerEntity->save();
  1195. return true;
  1196. }
  1197. private function addTypeWork($workId, $workType) {
  1198. $myworkEntity = Mywork::findOne(['id_work' => $workId]);
  1199. $myworkEntity->type_work = $workType;
  1200. $myworkEntity->save();
  1201. }
  1202. private function fixPriority($k) {
  1203. $tasksArray = [];
  1204. $flag = 0;
  1205. $pl = ProjectsLocotech::find()->where(['>','created', date('Y-m-d').' 00:00:00'])->andWhere(['<','created', date('Y-m-d').' 23:59:59'])->all();
  1206. $arrPL = [];
  1207. foreach ($pl as $plEnt) {
  1208. $arrPL[] = $plEnt->id;
  1209. }
  1210. $tE = Tasks::find()->andWhere(['IN', 'input_id',$arrPL])
  1211. ->groupBy(['assignees_arr'])
  1212. ->all();
  1213. $arrT = [];
  1214. foreach ($tE as $tEnt) {
  1215. $arrT[] = $tEnt->assignees_arr;
  1216. }
  1217. $tt = Tasks::find()->where(['parent_id' => 0 ])
  1218. ->andWhere(['IN', 'input_id',$arrPL])
  1219. ->andWhere(['IN', 'assignees_arr',$arrT])
  1220. ->andWhere(['>','created', date('Y-m-d').' 00:00:00'])
  1221. ->andWhere(['<','created', date('Y-m-d').' 23:59:59'])
  1222. ->orderBy(['parent_id' => SORT_ASC])->all();
  1223. foreach ($tt as $t) {
  1224. $mt = Tasks::find()->where(['parent_id' => $t->id ])->orderBy(['priority' => SORT_ASC])->all();
  1225. foreach ( $mt as $e) {
  1226. if ( 0 != $prior['pr'] ) {
  1227. if ( $prior['pr'] == $e->priority){
  1228. $tasksArray[$t->id][] = [['pr' =>$e->priority, 'id' => $e->id],$prior];
  1229. }
  1230. }
  1231. $prior['pr'] = $e->priority;
  1232. $prior['id'] = $e->id;
  1233. }
  1234. }
  1235. $i = 0;
  1236. foreach( $tasksArray as &$task){
  1237. foreach( $task as &$t){
  1238. $mt = Tasks::findOne($t[1]['id']);
  1239. $mt->scenario = Tasks::SCENARIO_UPDATE_PRIORITY;
  1240. if ( 110 < $mt->priority) {
  1241. $mt->priority = ($t[1]['pr'] + 5);
  1242. $mt->save();
  1243. //var_dump($mt->validate(),$mt->errors);
  1244. }
  1245. if ( 89 > $mt->priority) {
  1246. $mt->priority = ($t[1]['pr'] + 1);
  1247. $mt->save();
  1248. }
  1249. break;
  1250. }
  1251. $i++;
  1252. }
  1253. if ( empty($tasksArray) ) {
  1254. return true;
  1255. } else {
  1256. $k++;
  1257. if( 50 == $k ) {
  1258. return true;
  1259. }
  1260. $this->fixPriority($k);
  1261. }
  1262. }
  1263. }
  1264. /*
  1265. int(349)
  1266. array(2) {
  1267. ["dataShape"]=>
  1268. array(1) {
  1269. ["fieldDefinitions"]=>
  1270. array(1) {
  1271. ["result"]=>
  1272. array(5) {
  1273. ["name"]=>
  1274. string(6) "result"
  1275. ["description"]=>
  1276. string(0) ""
  1277. ["baseType"]=>
  1278. string(4) "TEXT"
  1279. ["ordinal"]=>
  1280. int(0)
  1281. ["aspects"]=>
  1282. array(0) {
  1283. }
  1284. }
  1285. }
  1286. }
  1287. ["rows"]=>
  1288. array(1) {
  1289. [0]=>
  1290. array(1) {
  1291. ["result"]=>
  1292. string(1290) "{"result":"true",
  1293. "data":
  1294. [{"id_equipment":"95078df8-4487-46b9-9771-5c6b6e1f6b81",
  1295. "equip_sect_name":"3ЭС5К 0362/3ЭС5К", // ["eq_serie"]/ ["eq_number"]
  1296. "sections":
  1297. [{"works":
  1298. [{"id_work":"a7869ca0-0153-41f5-93c4-51393ccc574a",
  1299. "repeats":1,
  1300. "work_name":"Тормозное и пневматическое оборудование после ремонта испытать, // ["work_name"]
  1301. отрегулировать согласно инструкции",
  1302. "work_status":4,
  1303. "workers":
  1304. [{"id":"0f9ed850-e473-11e2-aaad-ac162db0b20c","fio":"Новосад Я. И."},
  1305. {"id":"0f9ed854-e473-11e2-aaad-ac162db0b20c","fio":"Ознобихин О. А."}],
  1306. "measurements":"--/--/--"}],
  1307. "section_name":"0362А", // ["section_lit"]
  1308. "id_section":"6ddd13a5-986b-11e2-99b5-ac162db0b20c"}, // ["section_id"]
  1309. {"works":
  1310. [{"id_work":"a0a572e0-4d70-45d7-ac4a-9483933c70b9",
  1311. "repeats":1,
  1312. "work_name":"Тормозное и пневматическое оборудование после ремонта испытать,
  1313. отрегулировать согласно инструкции",
  1314. "work_status":4,
  1315. "workers":
  1316. [{"id":"0f9ed850-e473-11e2-aaad-ac162db0b20c","fio":"Новосад Я. И."},
  1317. {"id":"0f9ed854-e473-11e2-aaad-ac162db0b20c","fio":"Ознобихин О.А."}],
  1318. "measurements":"--/--/--"}],
  1319. "section_name":"0362В",
  1320. "id_section":"6ddd13a6-986b-11e2-99b5-ac162db0b20c"}],
  1321. "equip_percent":10730}]}"
  1322. }
  1323. }
  1324. }
  1325. $work["eq_serie"] . ' '.$work["section_lit"] . ', '. $work["outfit"] . ':' . $work['work_name']
  1326. repair_name - ?
  1327. section_num - ? +
  1328. outfit - ?
  1329. section_DK - ?
  1330. int(349)
  1331. array(2) {
  1332. ["result"]=>
  1333. string(4) "true"
  1334. ["data"]=>
  1335. array(2) {
  1336. [0]=>
  1337. array(10) {
  1338. ["id_work"]=>
  1339. string(36) "a7869ca0-0153-41f5-93c4-51393ccc574a" +
  1340. ["section_DK"]=>
  1341. string(36) "6d4acb88-685e-11ea-80d6-005056011052" +
  1342. ["eq_number"]=>
  1343. string(4) "0362" +
  1344. ["outfit"]=>
  1345. float(1460789) +
  1346. ["work_name"]=>
  1347. string(187) "Тормозное и пневматическое оборудование после ремонта испытать , отрегулировать согласно инструкции" +
  1348. ["section_id"]=>
  1349. string(36) "6ddd13a5-986b-11e2-99b5-ac162db0b20c" +
  1350. ["section_num"]=>
  1351. string(8) "11381969" +
  1352. ["section_lit"]=>
  1353. string(6) "0362А" +
  1354. ["repair_name"]=>
  1355. string(6) "ТР-1" +
  1356. ["eq_serie"]=>
  1357. string(8) "3ЭС5К" +
  1358. }
  1359. [1]=>
  1360. array(10) {
  1361. ["id_work"]=>
  1362. string(36) "a0a572e0-4d70-45d7-ac4a-9483933c70b9"
  1363. ["section_DK"]=>
  1364. string(36) "6d4acb89-685e-11ea-80d6-005056011052"
  1365. ["eq_number"]=>
  1366. string(4) "0362"
  1367. ["outfit"]=>
  1368. float(1460871)
  1369. ["work_name"]=>
  1370. string(187) "Тормозное и пневматическое оборудование после ремонта испытать , отрегулировать согласно инструкции"
  1371. ["section_id"]=>
  1372. string(36) "6ddd13a6-986b-11e2-99b5-ac162db0b20c"
  1373. ["section_num"]=>
  1374. string(8) "11381985"
  1375. ["section_lit"]=>
  1376. string(6) "0362В"
  1377. ["repair_name"]=>
  1378. string(6) "ТР-1"
  1379. ["eq_serie"]=>
  1380. string(8) "3ЭС5К"
  1381. }
  1382. }
  1383. }
  1384. */