MainMappingModel.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. <?php
  2. namespace app\models;
  3. use Yii;
  4. use yii\base\Model;
  5. //use yii\web\Controller;
  6. //use app\models\MainModel;
  7. //use app\models\ProcedureModel;
  8. use app\models\entity\Tasks;
  9. use app\models\Logs;
  10. //use app\models\ProjectsModel;
  11. use app\models\entity\Accounts;
  12. //use app\models\entity\Sections;
  13. //use app\models\LocomotiveModel;
  14. //use app\models\entity\Tasktypes;
  15. use app\models\logger\LoggerFile;
  16. use app\models\entity\Checkpoints;
  17. //use app\models\entity\Repairtypes;
  18. //use app\models\entity\Projecttypes;
  19. //use app\models\entity\AsusgProject;
  20. use app\models\entity\AsusgJobPlan;
  21. use app\models\MappingHandlerModel;
  22. use app\models\entity\AsusgJob2Launch;
  23. use app\models\entity\AsusgMeasurements;
  24. //use app\models\entity\AsusgProjectType;
  25. //use app\models\entity\LocomotiveSeries;
  26. //use app\models\entity\ProjectsLocotech;
  27. //use app\models\entity\AsusgJob2Command;
  28. use app\models\procedure\AsusgAddMeasurementToTaskModel;
  29. use app\models\LogEippResponse;
  30. class MainMappingModel extends MainModel
  31. {
  32. const MAINTASK = 0;
  33. const TMC = 1;
  34. const TASK = 2;
  35. const MAPPINGTYPE = 197
  36. private static $_instance;
  37. private $url = 'http://devplatform.digitaldepot.ru:8085/Thingworx/Things/2050UserLibraryExp/Services/';
  38. private $GWparams = ['login' => 'ПройдаковИА','pass' => 'Ip15351112'];
  39. private $responseEippMeasurement = '';
  40. public $prepareLogString = '';
  41. public $company;
  42. private $launchObj;
  43. private $parent_id;
  44. private $projId;
  45. private $arrStage = [0 => 'ЗАДАЧИ', 1 => 'КОМАНДЫ ТМЦ', 2 => 'КОМАНДЫ'];
  46. private $create_task_id;
  47. function __construct($company) {
  48. $this->company = $company;
  49. }
  50. // ВОЗВРАЩАЕТ СПИСОК ПОЛЬЗОВАТЕЛЕЙ ОНЛАЙН + НАПАРНИКИ ПО РАБОТАМ
  51. // params => $onlineUser: array
  52. //
  53. // result => array
  54. public function onlineUserPlus($onlineUser)
  55. {
  56. $setOnlineWorkers = [];
  57. foreach($onlineUser as $user) {
  58. if( '' == $user->uuid and null == $user->uuid) {
  59. continue;
  60. }
  61. $this->GWparams['param'] = $user->uuid;
  62. $listWorks2 = json_decode($this->curlRequest2($this->GWparams),true);
  63. $listWorks2 = $this->prepareListWorks($listWorks2);
  64. foreach ( $listWorks2['data'] as $work) {
  65. $mappingapiModel = new \app\models\MappingapiModel();
  66. $this->datailWorkArray[$work['id_work']] = $mappingapiModel->workDetail( $user->uuid, $work['id_work'] );
  67. foreach( $this->datailWorkArray[$work['id_work']]['workers_uuid'] as $uuid) {
  68. $setOnlineWorkers[] = $uuid;
  69. }
  70. }
  71. }
  72. $setOnlineWorkers = array_unique($setOnlineWorkers);
  73. $onlineUserModificate = Accounts::find()->where(['in','uuid',$setOnlineWorkers])->andWhere(['company' => $this->company])->all();
  74. return $onlineUserModificate;
  75. }
  76. public function MappingStart($onlineUserPlus)
  77. {
  78. foreach($onlineUserPlus as $user) {
  79. $this->GWparams['param'] = $user->uuid;
  80. $listWorks2 = json_decode($this->curlRequest2($this->GWparams),true);
  81. $listWorks2 = $this->prepareListWorks($listWorks2);
  82. $listIsabsentWorks2 = $this->Getisabsentworksjp($listWorks2); // вновь утвержденный план 1 | вернет список работ кот нет ( в JobPlan )
  83. $listIssetWorks3 = $this->Getissetworksjp($listWorks2);
  84. $addJob2launch2 = $this->addJob2launch2($listIsabsentWorks2,$user);
  85. $addJob2launch3 = $this->addJob2launch3($listIssetWorks3,$user);
  86. //echo '<pre>';
  87. //var_dump($user->id,$listWorks2);
  88. //echo '</pre>';
  89. }
  90. return true;
  91. }
  92. // ВОЗВРАЩАЕТ СПИСОК РАБОТ СВЕРХЦИКЛОВЫХ
  93. // params => $listWorks: array
  94. //
  95. // result => array
  96. private function Getisabsentworksjp( $listWorks = null){
  97. $result = [];
  98. if ( null == $listWorks) {
  99. return false;
  100. }
  101. foreach( $listWorks['data'] as $work) {
  102. $asusgJobPlan = AsusgJobPlan::find()->where(['name' => $work['work_name']])->one();
  103. if ( null == $asusgJobPlan ){
  104. $result[] = $work;
  105. }
  106. }
  107. return $result;
  108. }
  109. // ВОЗВРАЩАЕТ СПИСОК РАБОТ ЦИКЛОВЫХ
  110. // params => $listWorks: array
  111. //
  112. // result => array
  113. private function Getissetworksjp( $listWorks = null){
  114. $result = [];
  115. if ( null == $listWorks) {
  116. return false;
  117. }
  118. foreach( $listWorks['data'] as $work) {
  119. $asusgJobPlan = AsusgJobPlan::find()->where(['name' => $work['work_name']])->one();
  120. if ( null != $asusgJobPlan ){
  121. $result[] = $work;
  122. }
  123. }
  124. return $result;
  125. }
  126. // ВОЗВРАЩАЕТ СПИСОК СОТРУДНИКОВ ОНЛАЙН
  127. // params => $listWorks: integer
  128. //
  129. // result => array
  130. public function getOnlineMobileUser(){
  131. $result = [];
  132. $accountsEntity = Accounts::find()->where(['company' => $this->company])->all();
  133. foreach ($accountsEntity as $account) {
  134. $last_seen_mobile = ( null != $account->last_seen_mobile )? new \DateTime($account->last_seen_mobile): $account->last_seen_mobile ;
  135. $online_mobile = $this->OnlineAccountCheck($this->TimeString($last_seen_mobile));
  136. if ( !$online_mobile ){
  137. continue;
  138. }
  139. $result[] = $account;
  140. }
  141. return $result;
  142. }
  143. public function OnlineAccountCheck($last_seen)
  144. {
  145. $last_seen = date($last_seen);
  146. $time = (time()-strtotime($last_seen));
  147. if ($time <= Yii::$app->params['onlineMobileTimeoutSeconds'])
  148. return true;
  149. return false;
  150. }
  151. public function TimeString($timeobj)
  152. {
  153. if ($timeobj != null)
  154. return $timeobj->format('d.m.Y H:i');
  155. }
  156. public function getProjectType($repairName,$serieName)
  157. {
  158. $result = null;
  159. $repairtypesEntity = Repairtypes::findOne(['name' => $repairName]);
  160. $locomotiveSeriesEntity = LocomotiveSeries::findOne(['name' => $serieName]);
  161. $asusgProjectTypeEntity = AsusgProjectType::findOne(['repair_type' => $repairtypesEntity->id , 'loco_serie_id' => $locomotiveSeriesEntity->id]);
  162. if ( null != $asusgProjectTypeEntity->id ) {
  163. $result = $asusgProjectTypeEntity->id;
  164. }
  165. return $result;
  166. }
  167. private function prepareListWorks($listWorks) {
  168. $result = [];
  169. $dataArr = [];
  170. if ( null == $listWorks || empty($listWorks)) {
  171. return [];
  172. }
  173. foreach ( $listWorks["rows"] as $rows) {
  174. $rows["result"] = json_decode($rows["result"],true);
  175. foreach ( $rows["result"]['data'] as $key => $data) {
  176. $tempArray = [];
  177. $tempArray["eq_serie"] = explode(" ",$data["equip_sect_name"])[0];
  178. $eq = explode(" ",$data["equip_sect_name"])[1];
  179. $tempArray["eq_number"] = explode("/",$eq)[0];
  180. foreach ( $data["sections"] as $sections) {
  181. $tempArray["section_id"] = $sections["id_section"];
  182. $tempArray["section_lit"] = $sections["section_name"];
  183. $tempArray["section_num"] = $sections["section_subnumber"];
  184. $tempArray["section_DK"] = $sections["section_dk"];
  185. foreach ( $sections['works'] as $work) {
  186. $tempArray["id_work"] = $work["id_work"];
  187. $tempArray["outfit"] = $work["outfit"];
  188. $tempArray["work_name"] = $work["work_name"];
  189. $tempArray["repair_name"] = $work["repair_type"];
  190. $tempArray["work_status"] = $work["work_status"];
  191. $tempArray["repeats"] = $work["repeats"];
  192. $dataArr[] = $tempArray;
  193. foreach ( $works['workers'] as $worker) {
  194. //echo '<pre>';
  195. //var_dump($worker);
  196. //echo '</pre>';
  197. }
  198. }
  199. }
  200. }
  201. $result['result'] = 'true';
  202. $result['data'] = $dataArr;
  203. break;
  204. }
  205. return $result;
  206. }
  207. private function AddAsusgJob2Launch( $work, $dwResult, $user, $projtype, $jobPlan = null )
  208. {
  209. $jp = Yii::$app->params['supercycleplan'];
  210. if (!$jobPlan){
  211. $jp = $jobPlan;
  212. }
  213. $asusgJob2LaunchEntity = new AsusgJob2Launch();
  214. $asusgJob2LaunchEntity->asusg_jobplan_id = $jp; // +
  215. $asusgJob2LaunchEntity->asusg_employee_id1 = $user->id; // +
  216. $asusgJob2LaunchEntity->asusg_job_uuid = $work['id_work']; // +
  217. $asusgJob2LaunchEntity->employees_uuid = $user->uuid; // +
  218. $asusgJob2LaunchEntity->section_uuid = $work["section_id"]; // +
  219. $asusgJob2LaunchEntity->asusg_project_id = 0; // +
  220. $asusgJob2LaunchEntity->job_order = 0; // +
  221. $asusgJob2LaunchEntity->time_limit = $dwResult['time_limit']; // +
  222. $asusgJob2LaunchEntity->outfit = $dwResult['outfit']; // +
  223. $asusgJob2LaunchEntity->name = $dwResult['work_name']; // +
  224. $asusgJob2LaunchEntity->section_name = $work["section_lit"]; // +
  225. $asusgJob2LaunchEntity->asusg_projecttype_id = $projtype;
  226. if ( $asusgJob2LaunchEntity->save() ) {
  227. $this->launchObj = $asusgJob2LaunchEntity;
  228. return true;
  229. } else {
  230. return false;
  231. }
  232. }
  233. // Добавление задачи
  234. // params => $works: array ( инфо о работе )
  235. // $tasktypesEntity: integer ( тип работы id-шник)
  236. // $user object ( инфо о пользователе )
  237. // $dwResult array ( инфо детализация о работе )
  238. // $stage: integer ( это команда на ТМЦ или 1 да /0 нет )
  239. // $parent_id: integer ( 0 == задача / 0 <> команда)
  240. //
  241. // result => array
  242. $tasksEntity2->asusg_job_mapped_id = $job->jobplantie->id;
  243. $tasksEntity2->text = $work["eq_serie"] . ' '.$work["section_lit"] . ', '. $work["outfit"] . ':' . $work['work_name'];
  244. $tasksEntity2->mapping_comment = $work["outfit"] . ': ' . $work['work_name'];
  245. private function addTasks($work, $tasktypesEntity, $launch_id = null, $stage = 0, $parent_id = 0 )
  246. {
  247. $result = false;
  248. $type = $tasktypesEntity;
  249. $tasksEntity = new Tasks();
  250. $tasksEntity->input_id = $this->projId;
  251. $tasksEntity->parent_id = $parent_id; // +
  252. $tasksEntity->status = 2; // +
  253. $tasksEntity->type = $type; // +
  254. $tasksEntity->assignees_arr = $work['user_info']->id; // +
  255. $tasksEntity->created = date("Y-m-d H:i;s"); // +
  256. $tasksEntity->asusg_job_mapped_id = ( is_object($this->launchObj) ) ? $this->launchObj->id : null ; // +
  257. $tasksEntity->priority = Yii::$app->params['countPriority'];
  258. $tasksEntity->text = $work["eq_serie"] . ' '.$work["section_lit"] . ', '. $work["outfit"] . ': ' . $work['work_name'];
  259. $tasksEntity->mapping_comment = $work["outfit"] . ': ' . $work['work_name'];
  260. if ( self::TMC == $stage) {
  261. $tasksEntity->text = $work['dwResult']['tmcString']; // +
  262. $tasksEntity->mapping_comment = $work['dwResult']['tmcString']; // +
  263. }
  264. if ( self::MAINTASK == $stage ) {
  265. $tasksEntity->priority = 0;
  266. $tasksEntity->mapping_comment = $work["outfit"] . ': ' . $work['work_name']; // +
  267. $tasksEntity->text = $work["section_lit"] . "\n" . $work["outfit"] . ': ' . $work['work_name'] . "\n" . $work['dwResult']['workers'];// +
  268. }
  269. if($tasksEntity->save()) {
  270. $this->create_task_id = $tasksEntity->id;
  271. if ( self::MAINTASK == $stage ) {
  272. $this->parent_id = $tasksEntity->id; // присвоение ид ЗАДАЧИ
  273. }
  274. $this->logger->setLog('привязка ' . $this->arrStage[$stage] . ' ( id = '.$tasksEntity->id.') прошла успешно.');
  275. $result = true;
  276. }
  277. Yii::$app->params['countPriority']++;
  278. return $result;
  279. }
  280. public function addJob2launch2($listWorks,$user)
  281. {
  282. foreach ( $listWorks as $work) {
  283. $dwResult = $this->datailWorkArray[$work['id_work']];
  284. $work['user_info'] = $user;
  285. $work['dwResult'] = $dwResult;
  286. $this->prepareLogString .= "Название работы:". $work['work_name']. ".\n UUID работы: " . $work['id_work'] . "\n\n";
  287. $this->prepareLogString .= "\n 1. ДОБАВЛЕНИЕ В LAUNCH \n\n";
  288. $asusgJob2LaunchEntity = AsusgJob2Launch::findOne(['asusg_job_uuid' => $work['id_work']]);
  289. $let = mb_substr($work["section_lit"], -1);
  290. // ВАЖНО ПОНИМАТЬ !!!!
  291. // если проект для такой работы уже есть, его создавать нельзя
  292. // но можно прикреплять к нему задачи. Сотрудник который зашел первый получает и замеры и тмц и работы
  293. // тот кто зашел вторым получает только работы.
  294. $projtype = $this->getProjectType($work["repair_name"],$work["eq_serie"]);
  295. $switcher = $asusgJob2LaunchEntity;
  296. if ( null == $switcher) {
  297. $AsusgJob2LaunchRes = $this->AddAsusgJob2Launch($work, $dwResult, $user, $projtype);
  298. if ( !$AsusgJob2LaunchRes ) {
  299. $this->logger->setLog('в Job2launch не добавилась работа => "'. $work['work_name']. '" Добавление работ будет пропущено так как такая запись уже есть.');
  300. continue;
  301. }
  302. $this->logger->setLog($this->prepareLogString);
  303. $this->prepareLogString = '';
  304. $this->logger->setLog('в Job2launch была добавлена работа => "'. $work['work_name'].'"');
  305. /// сначала генерю проект
  306. $this->projId = $this->generateProject($work);
  307. } else {
  308. $this->prepareLogString .= "ВОТ ТУТ Я ХОТЕЛ ПОЛУЧИТЬ ИД ПРОЕКТА ЧЕРЕЗ ЗАДАЧУ( launch_id = ".$asusgJob2LaunchEntity->id.") => " . $asusgJob2LaunchEntity->tasks->id .", ВОТ ЧТО ПОЛУЧИЛ => " . $this->launchObj->tasks->input_id ."!\n";
  309. $this->projId = $this->launchObj->tasks->input_id;
  310. }
  311. /////////////// ДОБАВЛЕНИЕ ЗАДАЧИ
  312. $this->prepareLogString .= "\n 3. ДОБАВЛЕНИЕ ЗАДАЧИ \n\n";
  313. $tasktypesEntity = Tasktypes::find()->where(['name' => 'Секция '.$let.', задача','company' => $this->company])->one();
  314. $tasksEnt = Tasks::find()->where(['parent_id' => 0,'asusg_job_mapped_id' => $asusgJob2LaunchEntity->id,'assignees_arr' => $user->id])->one();
  315. if ( null != $tasksEnt) {
  316. continue;
  317. }
  318. $this->logger->setLog($this->prepareLogString);
  319. $this->prepareLogString = '';
  320. $addTasksRes = $this->addTasks($work, $tasktypesEntity->id, $this->launchObj->id, 0, 0 );
  321. if( $addTasksRes ) {
  322. $this->testIdpl2 = $tasksEntity->id;
  323. $this->logger->setLog('в Tasks была добавлена ЗАДАЧА => "'. $work['work_name'] . '" id => '.$tasksEntity->id);
  324. } else {
  325. $this->logger->setLog('в Tasks была НЕ добавлена ЗАДАЧА => "'. $work['work_name'] . '" id => '.$tasksEntity->id);
  326. }
  327. if ( null == $switcher) {
  328. ///////////////// ДОБАВЛЕНИЕ ТМЦ
  329. $this->logger->setLog("\n ДОБАВЛЕНИЕ ТМЦ " . strlen($dwResult['tmcString']) . "\n");
  330. if ( '' != $dwResult['tmcString']) {
  331. $addTasksTMC = $this->addTasks($work, 2159, $this->launchObj->id, 1, $this->parent_id );
  332. if ( $addTasksTMC ) {
  333. $query3 = "call asusg_add_checkpoints_to_task(" . $user->id . ",'" . $tasksEntity3->id . "')";
  334. $resProc = Yii::$app->db->createCommand($query3)->query();
  335. $logResProc = 'false';
  336. if ($resProc){
  337. $logResProc = 'true';
  338. }
  339. $this->logger->setLog('в Tasks была добавлена КОМАНДА => "'. $work['work_name'] . '" id => '.$tasksEntity3->id. ' процедура => ' . $logResProc . ' приоритет =>' . Yii::$app->params['countPriority']);
  340. } else {
  341. $this->logger->setLog('в Tasks была НЕ добавлена КОМАНДА => "'. $work['work_name'] . '" id => '.$tasksEntity3->id );
  342. }
  343. }
  344. ///////////////// ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 0
  345. $this->logger->setLog( "\n 4. ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 0 \n");
  346. //if ( Yii::$app->params['api']['hw_msrmnt_stat'][ $dwResult["hw_measurements_status"] ]) { // выполнение hw_measurements_status = waiting
  347. $paramsMeaserm = ['input_id' => $projId, 'assignees_arr' => $user->id, 'work' => $work,'stage' => 0, 'parent_id' => $tasksEntity->id , 'stage_type' => 'доремонтный','asusg_job_mapped_id' => $asusgJob2LaunchEntity->id ];
  348. Yii::$app->params['api']['mesrmntParam'] = $paramsMeaserm;
  349. MappingapiModel::workMeasurements($work['id_work'],$user->uuid);
  350. //}
  351. }
  352. /////////////// НА РЕМОНТ
  353. $this->logger->setLog("\n 5. ДОБАВЛЕНИЕ НА РЕМОНТ \n");
  354. $addTasksJob = $this->addTasks($work, Yii::$app->params['supercycletype'], $this->launchObj->id, 2, $this->parent_id );
  355. if ( $addTasksJob ) {
  356. $this->logger->setLog('в Tasks была добавлена КОМАНДА => "'. $work['work_name'] . '" id => '.$tasksEntity2->id . ' приоритет =>' . Yii::$app->params['countPriority']);
  357. } else {
  358. $this->logger->setLog('в Tasks была НЕ добавлена КОМАНДА => "'. $work['work_name'] . '" id => '.$tasksEntity2->id);
  359. }
  360. if ( null == $switcher) {
  361. ///////////////// ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 1
  362. $this->logger->setLog("\n 6. ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 1 \n");
  363. //if ( Yii::$app->params['api']['hw_msrmnt_stat'][ $dwResult["hw_measurements_status"] ]) { // выполнение hw_measurements_status = waiting
  364. $paramsMeaserm['asusg_job_mapped_id' => $asusgJob2LaunchEntity->id, 'stage_type' => 'контрольный','stage' => 1];
  365. Yii::$app->params['api']['mesrmntParam'] = $paramsMeaserm;
  366. MappingapiModel::workMeasurements($work['id_work'],$user->uuid);
  367. //}
  368. ///////////////// ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 2
  369. $this->logger->setLog("\n 7. ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 2 \n");
  370. //if ( Yii::$app->params['api']['hw_msrmnt_stat'][ $dwResult["hw_measurements_status"] ]) { // выполнение hw_measurements_status = waiting
  371. $paramsMeaserm['asusg_job_mapped_id' => $asusgJob2LaunchEntity->id, 'stage_type' => 'послеремонтный', 'stage' => 2];
  372. Yii::$app->params['api']['mesrmntParam'] = $paramsMeaserm;
  373. MappingapiModel::workMeasurements($work['id_work'],$user->uuid);
  374. //}
  375. }
  376. Yii::$app->params['countPriority'] = 1;
  377. }
  378. }
  379. public function addJob2launch3($listWorks,$user)
  380. {
  381. foreach ( $listWorks as $work) {
  382. $dwResult = $this->datailWorkArray[$work['id_work']];
  383. $work['user_info'] = $user;
  384. $work['dwResult'] = $dwResult;
  385. $this->prepareLogString .= "\n 1. ДОБАВЛЕНИЕ В LAUNCH \n\n";
  386. $asusgJob2LaunchEntity = AsusgJob2Launch::findOne(['asusg_job_uuid' => $work['id_work']]);
  387. $let = mb_substr($work["section_lit"], -1);
  388. // ВАЖНО ПОНИМАТЬ !!!!
  389. // если проект для такой работы уже есть, его создавать нельзя
  390. // но можно прикреплять к нему задачи. Сотрудник который зашел первый получает и замеры и тмц и работы
  391. // тот кто зашел вторым получает только работы.
  392. $projtype = $this->getProjectType($work["repair_name"],$work["eq_serie"]);
  393. $JobPlanEntitty = AsusgJobplan::find()->where(['name' => $work["work_name"]])->one(); // 1204 1567
  394. if ( null == $JobPlanEntitty->id ) {
  395. $this->prepareLogString .= " ВНИМАНИЕ не нашел работу в AsusgJobplan ('name' => ".$work['work_name'].")\n\n";
  396. }
  397. $jsusgJob2CommandEntity = AsusgJob2Command::find()->where(['asusg_job_id' => $JobPlanEntitty->id, 'asusg_projecttype_id' => $projtype ])->all();
  398. $switcher = $asusgJob2LaunchEntity;
  399. if ( null == $switcher) {
  400. $AsusgJob2LaunchRes = $this->AddAsusgJob2Launch($work, $dwResult, $user, $projtype, $JobPlanEntitty->id); // ADD LAUNCH
  401. if (!$AsusgJob2LaunchRes) {
  402. $this->logger->setLog('в Job2launch не добавилась работа => "'. $work['work_name']. '" Добавление работ будет пропущено так как такая запись уже есть.');
  403. continue;
  404. }
  405. $this->issetLaunch = true;
  406. $this->logger->setLog($this->prepareLogString);
  407. $this->prepareLogString = '';
  408. $this->logger->setLog('в Job2launch была добавлена работа => "'. $work['work_name'].'"');
  409. /// сначала генерю проект
  410. $projId = $this->generateProject($work);
  411. } else {
  412. $this->prepareLogString .= "ВОТ ТУТ Я ХОТЕЛ ПОЛУЧИТЬ ИД ПРОЕКТА ЧЕРЕЗ ЗАДАЧУ => " . $asusgJob2LaunchEntity->tasks->id .", ВОТ ЧТО ПОЛУЧИЛ => " . $asusgJob2LaunchEntity->tasks->input_id ."!\n";
  413. $projId = $asusgJob2LaunchEntity->tasks->input_id;
  414. }
  415. /////////////// ДОБАВЛЕНИЕ ЗАДАЧИ
  416. $this->prepareLogString .= "\n 3. ДОБАВЛЕНИЕ ЗАДАЧИ \n\n";
  417. $tasktypesEntity = Tasktypes::find()->where(['name' => 'Секция '.$let.', задача','company' => $this->company])->one();
  418. $tasksEnt = Tasks::find()->where(['parent_id' => 0,'asusg_job_mapped_id' => $asusgJob2LaunchEntity->id,'assignees_arr' => $user->id])->one();
  419. if ( null != $tasksEnt) {
  420. continue;
  421. }
  422. $this->logger->setLog($this->prepareLogString);
  423. $this->prepareLogString = '';
  424. $addTasksRes = $this->addTasks($work, $tasktypesEntity->id, 0, 0 );
  425. if($addTasksRes) {
  426. $this->logger->setLog('в Tasks была добавлена ЗАДАЧА => "'. $work['work_name'] . '" id => '.$tasksEntity->id);
  427. } else {
  428. $this->logger->setLog('в Tasks была НЕ добавлена ЗАДАЧА => "'. $work['work_name'] . '" id => '.$tasksEntity->id);
  429. }
  430. $this->logger->setLog(' колво записей => ' . count($jsusgJob2CommandEntity) . 'type => '. gettype($jsusgJob2CommandEntity));
  431. $arrJ = [];
  432. if ( null == $switcher) {
  433. $this->logger->setLog("switcher = null");
  434. ///////////////// ДОБАВЛЕНИЕ ТМЦ
  435. $mappingapiModel = new \app\models\MappingapiModel();
  436. $this->logger->setLog("сотрудник => " . $user->uuid . ", работа => " . $work['id_work']);
  437. $tmcString = $mappingapiModel->workDetail($user->uuid,$work['id_work']);
  438. $this->logger->setLog("\n ДОБАВЛЕНИЕ ТМЦ " . strlen($dwResult['tmcString']) . "\n");
  439. if ( '' != $dwResult['tmcString']) {
  440. $addTasksTMC = $this->addTasks($work, 2159, 1, $this->parent_id );
  441. if ( $addTasksTMC ) {
  442. var_dump('создана ТМЦ, задача =>' . $this->create_task_id);
  443. $arrJ[] = $this->create_task_id;
  444. $query3 = "call asusg_add_checkpoints_to_task(" . $user->id . ",'" . $this->create_task_id . "')";
  445. $resProc = Yii::$app->db->createCommand($query3)->query();
  446. $logResProc = 'false';
  447. if ( $resProc ){
  448. $logResProc = 'true';
  449. }
  450. $this->logger->setLog('в Tasks была добавлена КОМАНДА => "'. $work['work_name'] . '" id => ' . $this->create_task_id. ' процедура => ' . $logResProc);
  451. } else {
  452. var_dump('не создана ТМЦ');
  453. $this->logger->setLog('в Tasks была НЕ добавлена КОМАНДА => "'. $work['work_name'] . '" id => ' . $this->create_task_id );
  454. }
  455. }
  456. ///////////////// ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 0
  457. $this->logger->setLog("\n 4. ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 0 \n");
  458. //if ( Yii::$app->params['api']['hw_msrmnt_stat'][ $dwResult["hw_measurements_status"] ]) { // выполнение hw_measurements_status = waiting
  459. $paramsMeaserm = ['input_id' => $projId, 'assignees_arr' => $user->id, 'work' => $work,'stage' =>0, 'parent_id' => $tasksEntity->id ,'stage_type' => 'доремонтный','asusg_job_mapped_id' => $asusgJob2LaunchEntity->id];
  460. Yii::$app->params['api']['mesrmntParam'] = $paramsMeaserm;
  461. MappingapiModel::workMeasurements($work['id_work'],$user->uuid);
  462. //}
  463. }
  464. /////////////// НА РЕМОНТ
  465. $this->logger->setLog("\n 5. ДОБАВЛЕНИЕ НА РЕМОНТ \n");
  466. foreach($jsusgJob2CommandEntity as $job) {
  467. $tasksEntity2 = new Tasks();
  468. $tasksEntity2->parent_id = $tasksEntity->id;
  469. $tasksEntity2->status = 2;
  470. $tasksEntity2->priority = Yii::$app->params['countPriority'];
  471. $tasksEntity2->input_id = $projId;
  472. $tasksEntity2->created = date("Y-m-d H:i;s");
  473. $tasksEntity2->type = $job->smopp_cmd_id;
  474. $tasksEntity2->assignees_arr = $user->id;
  475. $tasksEntity2->asusg_job_mapped_id = $job->jobplantie->id;
  476. $tasksEntity2->text = $work["eq_serie"] . ' '.$work["section_lit"] . ', '. $work["outfit"] . ':' . $work['work_name'];
  477. $tasksEntity2->mapping_comment = $work["outfit"] . ': ' . $work['work_name'];
  478. if ( $tasksEntity2->save()) {
  479. $arrJ[] = $this->create_task_id;
  480. $this->logger->setLog('в Tasks была добавлена КОМАНДА => "'. $work['work_name'] . '" id => '.$tasksEntity2->id);
  481. } else {
  482. $this->logger->setLog('в Tasks была НЕ добавлена КОМАНДА => "'. $work['work_name'] . '" id => '.$tasksEntity2->id);
  483. }
  484. Yii::$app->params['countPriority']++;
  485. }
  486. foreach($arrJ as $job_id) {
  487. $tasksEnt = Tasks::findOne($job_id);
  488. $tasksEnt->input_id = $tasksEnt->input_id ?? $projId;
  489. if($tasksEnt->save()){
  490. $this->logger->setLog('привязка КОМАНДЫ ( id = '.$tasksEntity2->id.') прошла успешно');
  491. } else {
  492. $this->logger->setLog('привязка КОМАНДЫ ( id = '.$tasksEntity2->id.') прошла не успешно');
  493. }
  494. }
  495. if ( null == $switcher) {
  496. ///////////////// ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 1
  497. $this->logger->setLog("\n 6. ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 1 \n");
  498. //if ( Yii::$app->params['api']['hw_msrmnt_stat'][ $dwResult["hw_measurements_status"] ]) { // выполнение hw_measurements_status = waiting
  499. $paramsMeaserm['asusg_job_mapped_id' => $asusgJob2LaunchEntity->id, 'stage_type' => 'контрольный', 'stage' => 1];
  500. Yii::$app->params['api']['mesrmntParam'] = $paramsMeaserm;
  501. MappingapiModel::workMeasurements($work['id_work'],$user->uuid);
  502. //}
  503. ///////////////// ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 2
  504. $this->logger->setLog("\n 7. ДОБАВЛЕНИЕ ЗАМЕРОВ ЭТАП 2 \n");
  505. //if ( Yii::$app->params['api']['hw_msrmnt_stat'][ $dwResult["hw_measurements_status"] ]) { // выполнение hw_measurements_status = waiting
  506. $paramsMeaserm['asusg_job_mapped_id' => $asusgJob2LaunchEntity->id, 'stage_type' => 'послеремонтный','stage' => 2];
  507. Yii::$app->params['api']['mesrmntParam'] = $paramsMeaserm;
  508. MappingapiModel::workMeasurements($work['id_work'],$user->uuid);
  509. //}
  510. }
  511. }
  512. }
  513. private function generateProject($work){
  514. $this->logger->setLog("\n 2. ГЕНЕРАЦИЯ ПРОЕКТА \n");
  515. $result = '';
  516. $let = mb_substr($work["section_lit"], -1);
  517. $sectionsEntity = Sections::find()->select(['id', 'diagnostic_map'])
  518. ->where(['locomotive_series' => $work["eq_serie"],'section_number' => mb_substr($work['section_lit'],0,-1),'letter' => $let])
  519. ->one();
  520. $this->logger->setLog("Параметры локомотива locomotive_series => " . $work["eq_serie"]. ", section_number => " . $work['section_lit'] . " ,letter => " .$let. " \n");
  521. $diagnostic_map = $sectionsEntity->diagnostic_map;
  522. if ( null == $sectionsEntity->id) {
  523. $sectionsEntity = addNewSection($work);
  524. }
  525. else if( null == $sectionsEntity->diagnostic_map ) {
  526. $sectionsEntity->diagnostic_map = $work['section_DK'];
  527. $sectionsEntity->save();
  528. }
  529. if ($sectionsEntity->diagnostic_map == $work['section_DK'] ) {
  530. $result = getProjectId($work);
  531. $this->logger->setLog('в Sections секция с такой диагностической картой => '. $work['section_DK'] . ' существует. Ид проекта '. $result);
  532. }
  533. if (!$result) {
  534. $result = addProjectLocotech($work);
  535. $this->logger->setLog('Такого проекта еще не было пришлось создать. Ид проекта => '. $result);
  536. }
  537. return $result;
  538. }
  539. private function prepareListWorks($listWorks) {
  540. $result = [];
  541. $dataArr = [];
  542. if ( null == $listWorks || empty($listWorks)) {
  543. return [];
  544. }
  545. foreach ( $listWorks["rows"] as $rows) {
  546. $rows["result"] = json_decode($rows["result"],true);
  547. foreach ( $rows["result"]['data'] as $key => $data) {
  548. $tempArray = [];
  549. $tempArray["eq_serie"] = explode(" ",$data["equip_sect_name"])[0];
  550. $eq = explode(" ",$data["equip_sect_name"])[1];
  551. $tempArray["eq_number"] = explode("/",$eq)[0];
  552. foreach ( $data["sections"] as $sections) {
  553. $tempArray["section_id"] = $sections["id_section"];
  554. $tempArray["section_lit"] = $sections["section_name"];
  555. $tempArray["section_num"] = $sections["section_subnumber"];
  556. $tempArray["section_DK"] = $sections["section_dk"];
  557. foreach ( $sections['works'] as $work) {
  558. $tempArray["id_work"] = $work["id_work"];
  559. $tempArray["outfit"] = $work["outfit"];
  560. $tempArray["work_name"] = $work["work_name"];
  561. $tempArray["repair_name"] = $work["repair_type"];
  562. $tempArray["work_status"] = $work["work_status"];
  563. $tempArray["repeats"] = $work["repeats"];
  564. $dataArr[] = $tempArray;
  565. }
  566. }
  567. }
  568. $result['result'] = 'true';
  569. $result['data'] = $dataArr;
  570. break;
  571. }
  572. return $result;
  573. }
  574. private function addNewSwction($work)
  575. {
  576. $let = mb_substr($work["section_lit"], -1);
  577. $sectionsEntity = new Sections();
  578. $sectionsEntity->locomotive_series = $work["eq_serie"];
  579. $sectionsEntity->section_number = mb_substr($work['section_lit'],0,-1);
  580. $sectionsEntity->section_subnumber = $work["section_num"];
  581. $sectionsEntity->diagnostic_map = $work["section_DK"];
  582. $sectionsEntity->uuid = $work["section_id"];
  583. $sectionsEntity->letter = $let;
  584. if ( $sectionsEntity->save()) {
  585. $this->logger->setLog('в Sections была добавлена новая секция => '. $work["section_num"] . ' id => '.$sectionsEntity->id);
  586. } else {
  587. $this->logger->setLog('в Sections при добавлении секции произошли ошибки => '. count($sectionsEntity->errors) . ' шт.');
  588. }
  589. return $sectionsEntity;
  590. }
  591. private function getProjectId($work)
  592. {
  593. $let = mb_substr($work["section_lit"], -1);
  594. $query = "select pl.id from projects_locotech pl
  595. inner join tasks t on pl.id = t.input_id
  596. left join tasktypes tt on t.type = tt.id
  597. where pl.company = " . $this->company . "
  598. and pl.loco_type = '" . $work["eq_serie"] . "'
  599. and pl.loco_number = " . $work["eq_number"] . "
  600. and t.parent_id = 0
  601. and tt.letter like '%" . $let . "%'
  602. and pl.uuid like '%" . $work['repair_name']. ",%'
  603. order by pl.id desc
  604. limit 1";
  605. $projectId = Yii::$app->db->createCommand($query)->queryOne();
  606. return $projectId['id'];
  607. }
  608. private function addProjectLocotech($work)
  609. {
  610. $projectsLocotech = new ProjectsLocotech();
  611. $projectsLocotech->action = self::MAPPINGTYPE;
  612. $projectsLocotech->company = $this->company;
  613. $projectsLocotech->status = 2;
  614. $projectsLocotech->loco_type = $work["eq_serie"];
  615. $projectsLocotech->loco_number = $work["eq_number"];
  616. $projectsLocotech->depo ='' ;
  617. $projectsLocotech->depo_service = '';
  618. $projectsLocotech->created = date('Y-m-d H:i:s');
  619. $projectsLocotech->urgent = 0;
  620. $projectsLocotech->uuid = $work['work_name'].":".$work['repair_name'].",".$work["eq_serie"];
  621. $projectsLocotech->save();
  622. return $projectsLocotech->id;
  623. }
  624. }