Advertisement
alpa_s

Untitled

Mar 5th, 2018
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 30.68 KB | None | 0 0
  1. <?php
  2.  
  3. namespace console\controllers;
  4.  
  5. use common\helpers\NoticeHelper;
  6. use common\helpers\StringHelper;
  7. use common\helpers\Translit;
  8. use common\models\job\Blacklist;
  9. use common\models\job\Job;
  10. use common\models\job\JobImportUpload;
  11. use common\models\job\Log;
  12. use common\modules\sites\models\SitesTasks;
  13. use common\modules\user\models\notify\UserNotification;
  14. use common\modules\user\models\User;
  15. use Yii;
  16. use yii\console\Controller;
  17. use yii\console\Exception as ConsoleException;
  18. use yii\data\Pagination;
  19. use yii\db\Query;
  20. use yii\helpers\Json;
  21. use yii\helpers\Url;
  22.  
  23. ini_set('error_reporting', E_ALL);
  24. ini_set('display_errors', 1);
  25. ini_set('display_startup_errors', 1);
  26.  
  27. class JobController extends Controller
  28. {
  29. public function beforeAction($action)
  30. {
  31. if (parent::beforeAction($action)) {
  32. echo "\r\n" . 'START' . "\r\n" . '...' . "\r\n";
  33. return true;
  34. } else
  35. return false;
  36. }
  37.  
  38. public function afterAction($action, $result)
  39. {
  40. echo "\r\n" . '...' . "\r\n" . 'END.' . "\r\n\r\n";
  41. return parent::afterAction($action, $result);
  42. }
  43.  
  44. /**
  45. * Импорт задач массово
  46. * /path/to/yii job/import-job-webmaster $limit
  47. */
  48. public function actionImportJobWebmaster($limit)
  49. {
  50. echo "Import task here. Limit xml file check: $limit\n";
  51.  
  52. $xmls = JobImportUpload::find()->where('status = :status', [':status' => 'upload'])->limit($limit)->all();
  53.  
  54. if (!empty($xmls)) {
  55. foreach ($xmls as $xmlFile) {
  56. $countSuccess = 0;
  57. $countError = 0;
  58. $errors = [];
  59.  
  60. $url = Yii::getAlias('@frontend/web') . JobImportUpload::PATH_UPLOAD_XML . $xmlFile->url;
  61. $xml = simplexml_load_file($url, 'SimpleXMLElement', LIBXML_NOCDATA);
  62.  
  63. $countTask = count($xml->task);
  64.  
  65. if ($countTask > 0) {
  66. $siteStructure = SitesTasks::findOne($xmlFile->st_id);
  67.  
  68. if ($siteStructure !== NULL) {
  69. $keyTask = 0;
  70. $sendNoticeNewJob = [];
  71.  
  72. foreach ($xml->task as $task) {
  73. $validated = true;
  74.  
  75. if (count($task->job)) {
  76. if (isset($task->structure->_source_text)) {
  77. $task->structure->_source_text = htmlspecialchars($task->structure->_source_text);
  78. }
  79. $job = new Job();
  80. $job->isCreateUpdate = true;
  81. $job->setAttributes((array)$task->job);
  82. $job->price_per = Yii::$app->params['job.price_per'];
  83. $job->site_task_id = $xmlFile->st_id;
  84. $job->creator_id = $xmlFile->user_id;
  85.  
  86. if (empty($job->skype)) {
  87. $job->skype = 'adcombo_job';
  88. }
  89.  
  90. $job->import_id = $xmlFile->id;
  91. $userCreator = User::findOne($job->creator_id);
  92. $job->balanceWebmaster = $userCreator->userMoneys->balance;
  93.  
  94. if ($job->validate()) {
  95. $job->structure = $siteStructure->structure;
  96. if (count($task->structure)) {
  97. $structureTask = (array)$task->structure;
  98.  
  99. $fieldsOrig = json_decode($job->structure, true);
  100. $fieldsJob = [];
  101.  
  102. if (isset($fieldsOrig['groupField']))
  103. $fieldsJob['groupField'] = $fieldsOrig['groupField'];
  104.  
  105. foreach ($fieldsOrig['formField'] as $keyGroup => $fields) {
  106. //Проверка на группы
  107. $keyGroupInput = explode('#', $keyGroup);
  108. $inGroup = 0;
  109. $countInGroup = 1;
  110.  
  111. if ($keyGroupInput[0] == 'group') {
  112. $inGroup = 1;
  113. $countInGroup = $fieldsOrig['groupField'][$keyGroupInput[1]]['minList'];
  114. $nameGroupTranslit = '_' . Translit::translate($fieldsOrig['groupField'][$keyGroupInput[1]]['nameGroup']);
  115.  
  116. $countInGroupXml = 0;
  117. if (isset($structureTask[$nameGroupTranslit]))
  118. $countInGroupXml = count($structureTask[$nameGroupTranslit]->item);
  119.  
  120. if ($countInGroupXml > $countInGroup) {
  121. $countInGroup = $countInGroupXml;
  122. $fieldsJob['groupField'][$keyGroupInput[1]]['minList'] = $countInGroupXml;
  123. }
  124.  
  125. if ($countInGroupXml > $fieldsJob['groupField'][$keyGroupInput[1]]['maxList'])
  126. $fieldsJob['groupField'][$keyGroupInput[1]]['maxList'] = $countInGroupXml;
  127. }
  128.  
  129. for ($i = 0; $i < $countInGroup; $i++) {
  130. foreach ($fields as $key => $field) {
  131. $nameFieldTranslit = '_' . Translit::translate($field['options']['nameField']);
  132.  
  133. if ($inGroup) {
  134. if (isset($structureTask[$nameGroupTranslit]->item[$i]->{$nameFieldTranslit}))
  135. $fieldsJob['formField'][$keyGroup][$key]['value'][$i] = (string)$structureTask[$nameGroupTranslit]->item[$i]->{$nameFieldTranslit};
  136. } else {
  137. if (isset($structureTask[$nameFieldTranslit]))
  138. $fieldsJob['formField'][$keyGroup][$key]['value'] = $structureTask[$nameFieldTranslit];
  139. }
  140. }
  141. }
  142. }
  143.  
  144. if (!isset($fieldsJob['formField'])) {
  145. $fieldsJob['formField'] = [];
  146. $validated = $validated && false;
  147. $errors['jobs'][$keyTask]['errors'][] = Yii::t('app', 'Incorrect fields in structure.');
  148. }
  149.  
  150. // Формируем новый массив(данные) с заполненными полями из оригинального и обработанного
  151. $result = [];
  152.  
  153. if (isset($fieldsOrig['formField'])) {
  154. if (count($fieldsJob['formField']) <> count($siteStructure->getOnlyPerfomerFieldStructure(1))) {
  155. $validated = $validated && false;
  156. $errors['jobs'][$keyTask]['errors'][] = Yii::t('app', 'The number of fields in the structure is different from the number of fields in the XML.');
  157. }
  158.  
  159. $result['formField'] = array_replace_recursive($fieldsOrig['formField'], $fieldsJob['formField']);
  160. }
  161.  
  162. if (isset($fieldsOrig['groupField'])) {
  163. $result['groupField'] = array_replace_recursive($fieldsOrig['groupField'], $fieldsJob['groupField']);
  164. }
  165.  
  166. $job->structure = json_encode($result);
  167. unset($result);
  168. }
  169.  
  170. $job->status = $xmlFile->job_status;
  171. $job->original_structure = $job->structure;
  172.  
  173. if ($job->status == Job::STATUS_ACTIVATED && $job->type == Job::TYPE_TYPICAL) {
  174.  
  175. $job->scenario = 'create';
  176.  
  177. if (!$job->validate()) {
  178. $job->scenario = 'empty';
  179. $job->status = Job::STATUS_DRAFT;
  180. }
  181. }
  182.  
  183. if ($validated && $job->save()) {
  184. if ($job->isActivated()) {
  185. $job->addInLastJobsCache();
  186. $sendNoticeNewJob[$job->orig_lang . '-' . $job->target_lang] = $job;
  187. }
  188.  
  189. if ($job->status == Job::STATUS_ACTIVATED && $job->type == Job::TYPE_TYPICAL) {
  190. $userCreator->userMoneys->balance = $userCreator->userMoneys->balance - $job->getTotalPrice();
  191. $userCreator->userMoneys->save();
  192. $userCreator->saveMoneyLog(['sum' => $job->getTotalPrice(), 'type' => 'minus', 'ual_id' => '6', 'comment' => 'job #' . $job->id]);
  193. $userCreator->reservedMoney($job->getTotalPrice());
  194. }
  195.  
  196. Log::create($job->creator_id, $job->id, Log::TYPE_CREATE_AWAY);
  197.  
  198. $countSuccess++;
  199. } else
  200. $countError++;
  201. } else
  202. $countError++;
  203.  
  204. if ($job->hasErrors())
  205. foreach ($job->errors as $modelErrors)
  206. foreach ($modelErrors as $error)
  207. $errors['jobs'][$keyTask]['errors'][] = $error;
  208.  
  209. unset($modelErrors, $error);
  210.  
  211. if (isset($errors['jobs'][$keyTask]))
  212. $errors['jobs'][$keyTask]['title'] = $job->title;
  213. } else
  214. $countError++;
  215.  
  216. $keyTask++;
  217. }
  218.  
  219. if (!empty($sendNoticeNewJob)) {
  220. foreach ($sendNoticeNewJob as $job)
  221. $job->addJobNoticeCache();
  222. //$job->sendNoticeNewJobToEmail();
  223. }
  224.  
  225. $xmlFile->status = 'success';
  226. } else {
  227. $xmlFile->status = 'error';
  228. $errors['total'][] = Yii::t('app', 'Your structure site not found');
  229. }
  230. } else {
  231. $xmlFile->status = 'error';
  232. $errors['total'][] = Yii::t('app', 'Wrong format file');
  233. }
  234.  
  235. $xmlFile->stats = Yii::t('app', 'Check {n} jobs', ['n' => $countTask]) . "\r\n";
  236. $xmlFile->stats .= Yii::t('app', 'Success {n} jobs', ['n' => $countSuccess]) . "\r\n";
  237. $xmlFile->stats .= Yii::t('app', 'Error {n} jobs', ['n' => $countError]) . "\r\n";
  238.  
  239. if (!empty($errors))
  240. $xmlFile->message = serialize($errors);
  241. else
  242. $xmlFile->message = null;
  243.  
  244. echo "#{$xmlFile->id} - {$xmlFile->stats}\n";
  245. echo "##------------------------------------------------##\n";
  246.  
  247. $xmlFile->save(false);
  248. }
  249. }
  250. }
  251.  
  252. /**
  253. * Снятие просроченных фрилансером задач
  254. */
  255. public function actionUnsetByDeadline()
  256. {
  257. $memory = memory_get_usage();
  258.  
  259. $date = date('Y-m-d H:i:s');
  260. $query = new Query;
  261. $jobs = $query->select('id, original_structure, creator_id, user_id')
  262. ->from(Job::tableName())
  263. ->where(['or',
  264. ['status' => Job::STATUS_TAKEN],
  265. ['status' => Job::STATUS_REWORK]])
  266. ->andWhere(['<', 'deadline_rework', $date])
  267. ->andWhere(['not', ['user_id' => null]])
  268. //SELECT `id`, `original_structure`, `creator_id`, `user_id` FROM `job` WHERE
  269. // `status` IN ('taken','rework') AND `deadline_rework` < '2017-03-09 10:48:20' AND `user_id` IS NOT NULL
  270. /*
  271. ->where(['and',
  272. ['status' => Job::STATUS_TAKEN],
  273. ['<', 'deadline', $date],
  274. ])
  275. ->orWhere(['and',
  276. ['status' => Job::STATUS_REWORK],
  277. ['<', 'deadline_rework', $date],
  278. ])
  279. ->andWhere(['not', ['user_id' => null]])*/
  280. ->all();
  281.  
  282. unset($query, $date);
  283.  
  284. if (!empty($jobs)) {
  285. $i = 1;
  286.  
  287. foreach ($jobs as $key => $job) {
  288. echo $i++ . " | id: {$job['id']} | ";
  289.  
  290. $transaction = Yii::$app->db->beginTransaction();
  291.  
  292. try {
  293. $jobObject = Job::findOne($job['id']);
  294. $jobObject->removeUser();
  295. unset($jobObject);
  296.  
  297. // Делаем запись, чтобы в дальнейшем пользователь не мог взять эту задачу
  298. Blacklist::create($job['id'], $job['user_id']);
  299.  
  300. // Записываем логи по задаче
  301. Log::create($job['user_id'], $job['id'], Log::TYPE_TAKE_AWAY);
  302.  
  303. $notifyTitle = Yii::t('app', 'Job time expired');
  304. $notifyBody = Yii::t('app', 'Job time expired - "{job}"', [
  305. 'job' => '{job:' . $job['id'] . '}',
  306. ]);
  307. // Создаем уведомление для вебмастера что c его задачи автоматом сняли пользователя
  308. UserNotification::create($job['creator_id'], $notifyTitle, $notifyBody);
  309. // Создаем уведомление для исполнителя что у него забрали задачу автоматом
  310. UserNotification::create($job['user_id'], $notifyTitle, $notifyBody);
  311.  
  312. echo 'success | ';
  313.  
  314. $transaction->commit();
  315. } catch (\Exception $e) {
  316. $transaction->rollBack();
  317. throw new ConsoleException($e->getMessage());
  318. }
  319.  
  320. unset($transaction, $jobs[$key], $job);
  321.  
  322. echo "\n";
  323. }
  324. } else
  325. echo "Jobs is empty...\n";
  326.  
  327. unset($jobs);
  328.  
  329. $memory = memory_get_usage() - $memory;
  330. echo "Total memory: {$memory}\n";
  331. }
  332.  
  333. /**
  334. * Автоматическое принятие задач при просрочки проверки
  335. */
  336. public function actionApproveByDeadline()
  337. {
  338. $memory = memory_get_usage();
  339.  
  340. $date = date('Y-m-d H:i:s');
  341. $query = Job::find()->where(['and',
  342. ['status' => Job::STATUS_VERIFIED],
  343. ['<', 'deadline_verified', $date],
  344. ]);
  345.  
  346. $count = $query->count('id');
  347.  
  348. if ($count > 0) {
  349. $pagination = new Pagination([
  350. 'totalCount' => $count,
  351. 'defaultPageSize' => 1000,
  352. ]);
  353.  
  354. unset($count);
  355.  
  356. $part = 0;
  357. $i = 1;
  358.  
  359. while ($part < $pagination->pageCount) {
  360. echo "Part - {$part}:\n";
  361.  
  362. $pagination->page = $part;
  363.  
  364. $jobs = $query->offset($pagination->offset)
  365. ->limit($pagination->limit)
  366. ->all();
  367.  
  368. foreach ($jobs as $key => $job) {
  369. echo $i++ . " | {$job['id']} | ";
  370.  
  371. if ($job->approve())
  372. echo 'approve | ';
  373. else
  374. echo 'error : ' . print_r($job->errors, true);
  375.  
  376. echo "\n";
  377.  
  378. unset($job, $jobs[$key]);
  379. }
  380.  
  381. $part++;
  382. }
  383. } else
  384. echo "Jobs is empty...\n";
  385.  
  386. $memory = memory_get_usage() - $memory;
  387. echo "Total memory: {$memory}\n";
  388. }
  389.  
  390. /**
  391. * Автоматическое принятие
  392. */
  393. public function actionAutoApprove()
  394. {
  395. $memory = memory_get_usage();
  396.  
  397. $query = Job::find()->where([
  398. 'status' => Job::STATUS_VERIFIED
  399. ]);
  400.  
  401. $count = $query->count('id');
  402.  
  403. if ($count > 0) {
  404. $pagination = new Pagination([
  405. 'totalCount' => $count,
  406. 'defaultPageSize' => 1000,
  407. ]);
  408.  
  409. unset($count);
  410.  
  411. $part = 0;
  412. $i = 1;
  413.  
  414. while ($part < $pagination->pageCount) {
  415. echo "Part - {$part}:\n";
  416.  
  417. $pagination->page = $part++;
  418.  
  419. $jobs = $query->offset($pagination->offset)
  420. ->limit($pagination->limit)
  421. ->all();
  422. /**
  423. * @var $job Job
  424. */
  425. foreach ($jobs as $key => $job) {
  426. echo $i++ . " | {$job['id']} | ";
  427. $verifyTime = strtotime($job->updated_at);
  428. $timeNow = strtotime(date("Y-m-d H:i:s"));
  429. $absTime = abs($timeNow - $verifyTime);
  430. if($absTime > 60 * 60 * 120 ||
  431. ($job->delivery_up == 1 && $absTime > 60 * 60 * 24) ||
  432. $job->creator->isAutoApprove()){
  433. if ($job->approve())
  434. echo 'approve | ';
  435. else
  436. echo 'error : ' . print_r($job->errors, true);
  437. } else
  438. echo 'not is auto approve | ';
  439.  
  440. echo "\n";
  441.  
  442. unset($job, $jobs[$key]);
  443. }
  444. }
  445. } else
  446. echo "Jobs is empty...\n";
  447.  
  448. $memory = memory_get_usage() - $memory;
  449. echo "Total memory: {$memory}\n";
  450. }
  451.  
  452. /**
  453. * Скачивание лэндинга
  454. */
  455. public function actionPrepareLanding($limit = 5)
  456. {
  457. $jobs = Job::find()
  458. ->where(['status' => Job::STATUS_PREPARE])
  459. ->limit((int)$limit)
  460. ->all();
  461.  
  462. if (!empty($jobs)) {
  463. $i = 1;
  464.  
  465. foreach ($jobs as $job) {
  466. echo $i++ . " | id: {$job->id} | ";
  467.  
  468. if ($job->isLandingType()) {
  469. $errorsSave = [];
  470.  
  471. foreach ($job->landings as $landing) {
  472. if (!$landing->download()) {
  473. $errors = implode("\r\n", $landing->errors);
  474. $errorsSave[] = "{$landing->url}: {$errors}";
  475. unset($errors);
  476. }
  477. }
  478.  
  479. if (empty($errorsSave)) {
  480. echo 'success | ';
  481. $structure = $job->structureArray;
  482.  
  483. foreach ($job->landings as $landing) {
  484. if (isset($structure['formField']["single#{$landing->id}"]["landing#{$landing->id}"]))
  485. $structure['formField']["single#{$landing->id}"]["landing#{$landing->id}"]['options']['download'] = Url::to(['/landing/download', 'id' => $landing->id, 'jobId' => $landing->job->id]);
  486.  
  487. if (isset($structure['formField']["group#{$landing->id}"]["landing#{$landing->id}"]))
  488. $structure['formField']["group#{$landing->id}"]["landing#{$landing->id}"]['options']['download'] = Url::to(['/landing/download', 'id' => $landing->id, 'jobId' => $landing->job->id]);
  489.  
  490. if (!empty($landing->data)) {
  491. if (isset($structure['formField']["single#{$landing->id}"]["landing#{$landing->id}"]))
  492. $structure['formField']["single#{$landing->id}"]["landing#{$landing->id}"]['data'] = $landing->data;
  493.  
  494. if (isset($structure['formField']["group#{$landing->id}"]["landing#{$landing->id}"]))
  495. $structure['formField']["group#{$landing->id}"]["landing#{$landing->id}"]['data'] = $landing->data;
  496. }
  497. }
  498.  
  499. $job->structure = $job->original_structure = Json::encode($structure);
  500.  
  501. if ($job->isDraftAfterPrepare()) {
  502. $job->draft_after_prepare = Job::DRAFT_AFTER_PREPARE_NO;
  503. $job->status = Job::STATUS_DRAFT;
  504. } else
  505. $job->status = Job::STATUS_ACTIVATED;
  506. } else {
  507. echo 'error | ';
  508. $job->landing_errors = implode("\r\n", $errorsSave);
  509. }
  510. } else {
  511. echo 'is not landing type | ';
  512. $job->landing_errors = Yii::t('app', 'Job is not landing type.');
  513. }
  514.  
  515. $job->save(false, ['status', 'updated_at', 'activated_at', 'structure', 'original_structure', 'landing_errors', 'draft_after_prepare']);
  516. echo "\n";
  517.  
  518. if ($job->isActivated()) {
  519. $job->addInLastJobsCache();
  520. $job->addJobNoticeCache();
  521. // $job->sendNoticeNewJobToEmail();
  522. }
  523. }
  524. } else
  525. echo "Jobs is empty...\n";
  526. }
  527.  
  528. /**
  529. * Сравнение с Google translate
  530. */
  531. public function actionCompareWithGoogle($limit = 5)
  532. {
  533. $jobs = Job::find()->with('origLanguage', 'targetLanguage')
  534. ->where([
  535. 'deleted' => Job::DELETED_FALSE,
  536. 'status' => Job::STATUS_VERIFIED,
  537.  
  538. ])
  539. ->andWhere(['google_translate' => null])
  540. ->orderBy('activated_at ASC, id ASC')
  541. ->limit($limit)
  542. ->all();
  543.  
  544. if (!empty($jobs)) {
  545. $i = 1;
  546. $shingler = new \common\components\Shingler([
  547. 'sizeShingle' => 3,
  548. ]);
  549.  
  550. foreach ($jobs as $job) {
  551. var_dump($job->google_translate);
  552. if ($job->isLandingType()){
  553. $job->google_translate = 101;
  554. $job->save(false, ['status', 'google_translate']);
  555. continue;
  556. }
  557.  
  558.  
  559. echo $i++ . " | id: {$job->id} | ";
  560.  
  561. // Текст вебмастера
  562. $origText = $job->textFromStructure(1);
  563. $origText = StringHelper::stripTags($origText);
  564. $origText = StringHelper::proposals($origText, 4);
  565.  
  566. // Текст фрилансера
  567. $targetText = $job->textFromStructure(0);
  568. $targetText = StringHelper::stripTags($targetText);
  569. $targetText = StringHelper::proposals($targetText, 4);
  570.  
  571. // Исходный язык
  572. $sourceLang = $job->origLanguage->code;
  573. $sourceLang = mb_substr($sourceLang, 0, 2);
  574.  
  575. // Целевой язык
  576. $targetLang = $job->targetLanguage->code;
  577. $targetLang = mb_substr($targetLang, 0, 2);
  578.  
  579. // Делаем запрос в гугл
  580. $url = 'https://www.googleapis.com/language/translate/v2?' . http_build_query([
  581. 'key' => 'AIzaSyA1JCMmlzy9UoSJnWuO_FcA8uiZ7hid4Sk',// 'AIzaSyAwG3GcY52AYe3id3fRtRLr7l-I_w1VjL8',
  582. 'q' => $origText,
  583. 'source' => $sourceLang,
  584. 'target' => $targetLang,
  585. ]);
  586. $ch = curl_init();
  587. curl_setopt($ch, CURLOPT_URL, $url);
  588. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  589. $data = curl_exec($ch);
  590. $info = curl_getinfo($ch);
  591. curl_close($ch);
  592.  
  593. if (preg_match('/^2/', $info['http_code'])) {
  594. try {
  595. /* Пример JSON с Google:
  596. {
  597. "data": {
  598. "translations": [
  599. {
  600. "translatedText": "привет мир"
  601. }
  602. ]
  603. }
  604. }*/
  605.  
  606. $data = Json::decode($data);
  607. } catch (\yii\base\InvalidParamException $e) {
  608. $data = false;
  609. }
  610.  
  611. if ($data !== false && is_array($data)) {
  612. if (!empty($data['data']['translations']) && is_array($data['data']['translations'])) {
  613. $googleText = '';
  614.  
  615. foreach ($data['data']['translations'] as $translation)
  616. $googleText .= implode(' ', $translation) . ' ';
  617.  
  618. $googleText = trim($googleText);
  619. $job->status = Job::STATUS_VERIFIED;
  620. $percentage = similar_text($targetText, $googleText, $percent);
  621. $job->google_translate = round($percent,2);//$shingler->compare($targetText, $googleText);
  622. if ($job->google_translate == 0) {
  623. $job->google_translate = 101;
  624. }
  625. $job->save(false, ['status', 'google_translate']);
  626.  
  627. echo "success | result: {$job->google_translate} | ";
  628. } else
  629. echo 'Not found translated text in JSON from Google | ';
  630. } else
  631. echo 'Error - JSON from google not valid | ';
  632. } else
  633. echo "Error - http code from Google {$info['http_code']} | ";
  634.  
  635. echo "\n";
  636. }
  637. } else
  638. echo "Jobs is empty...\n";
  639. }
  640.  
  641. public function actionDeallocateByDeadline()
  642. {
  643. $memory = memory_get_usage();
  644.  
  645. $date = date('Y-m-d H:i:s');
  646. $query = new Query;
  647. $jobs = $query->select('id, original_structure, creator_id, user_id')
  648. ->from(Job::tableName())
  649. ->where(['status' => Job::STATUS_REWORK])
  650. ->andWhere(['<', 'deadline_rework', $date])
  651. ->andWhere(['not', ['user_id' => null]])
  652. //SELECT `id`, `original_structure`, `creator_id`, `user_id` FROM `job` WHERE
  653. // `status` IN ('taken','rework') AND `deadline_rework` < '2017-03-09 10:48:20' AND `user_id` IS NOT NULL
  654. /*
  655. ->where(['and',
  656. ['status' => Job::STATUS_TAKEN],
  657. ['<', 'deadline', $date],
  658. ])
  659. ->orWhere(['and',
  660. ['status' => Job::STATUS_REWORK],
  661. ['<', 'deadline_rework', $date],
  662. ])
  663. ->andWhere(['not', ['user_id' => null]])*/
  664. ->all();
  665.  
  666. unset($query, $date);
  667.  
  668. if (!empty($jobs)) {
  669. $i = 1;
  670.  
  671. foreach ($jobs as $key => $job) {
  672. echo $i++ . " | id: {$job['id']} | ";
  673.  
  674. $transaction = Yii::$app->db->beginTransaction();
  675.  
  676. try {
  677. $jobObject = Job::findOne($job['id']);
  678. //$jobObject->setDeallocatedStatus();
  679. $jobObject->removeUser(Job::STATUS_DEALLOCATE);
  680. unset($jobObject);
  681.  
  682. // Делаем запись, чтобы в дальнейшем пользователь не мог взять эту задачу
  683. //Blacklist::create($job['id'], $job['user_id']);
  684.  
  685. // Записываем логи по задаче
  686. Log::create($job['user_id'], $job['id'], Log::TYPE_DEALLOCATE);
  687.  
  688. $notifyTitle = Yii::t('app', 'Job time expired');
  689. $notifyBody = Yii::t('app', 'Job time expired - "{job}"', [
  690. 'job' => '{job:' . $job['id'] . '}',
  691. ]);
  692. // Создаем уведомление для вебмастера что c его задачи автоматом сняли пользователя
  693. UserNotification::create($job['creator_id'], $notifyTitle, $notifyBody);
  694. // Создаем уведомление для исполнителя что у него забрали задачу автоматом
  695. UserNotification::create($job['user_id'], $notifyTitle, $notifyBody);
  696.  
  697. echo 'success | ';
  698.  
  699. $transaction->commit();
  700. } catch (\Exception $e) {
  701. $transaction->rollBack();
  702. throw new ConsoleException($e->getMessage());
  703. }
  704.  
  705. unset($transaction, $jobs[$key], $job);
  706.  
  707. echo "\n";
  708. }
  709. } else
  710. echo "Jobs is empty...\n";
  711.  
  712. unset($jobs);
  713.  
  714. $memory = memory_get_usage() - $memory;
  715. echo "Total memory: {$memory}\n";
  716. }
  717.  
  718. public function actionSendNotifications(){
  719. NoticeHelper::sendNoticeNewJobToEmail();
  720. }
  721. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement