StationTaskBatchService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. <?php
  2. namespace App\Services;
  3. use App\Exceptions\ErrorException;
  4. use App\StationTaskBatch;
  5. use Exception;
  6. use Illuminate\Support\Collection;
  7. use Illuminate\Support\Facades\Cache;
  8. use App\Traits\ServiceAppAop;
  9. class StationTaskBatchService
  10. {
  11. use ServiceAppAop;
  12. protected $modelClass=StationTaskBatch::class;
  13. /** @var StationService $stationService */
  14. private $stationService;
  15. /** @var StationTaskBatchTypeService $stationTaskBatchTypeService */
  16. private $stationTaskBatchTypeService;
  17. /** @var BatchService $batchService */
  18. private $batchService;
  19. /** @var StationTypeService $stationTypeService */
  20. private $stationTypeService;
  21. /** @var StationTaskService $stationTaskService */
  22. private $stationTaskService;
  23. /** @var ForeignHaiRoboticsService $foreignHaiRoboticsService */
  24. private $foreignHaiRoboticsService;
  25. public function __construct()
  26. {
  27. $this->stationService = null;
  28. $this->stationTypeService = null;
  29. $this->stationTaskBatchTypeService = null;
  30. $this->batchService = null;
  31. $this->stationTaskService = null;
  32. $this->foreignHaiRoboticsService = null;
  33. }
  34. /**
  35. * @param Collection $batches Batch[]
  36. * @param Collection $stationTasks_toAttach
  37. * @return Collection
  38. * @throws Exception
  39. */
  40. function createByBatches(Collection $batches, Collection $stationTasks_toAttach): Collection
  41. {
  42. $this->stationService = app('StationService');
  43. $this->stationTaskService = app('StationTaskService');
  44. $this->stationTypeService = app('StationTypeService');
  45. $this->stationTaskBatchTypeService = app('StationTaskBatchTypeService');
  46. $this->batchService = app('BatchService');
  47. $stationTaskBatches_toCreate = new Collection();
  48. $stationTaskBatchType = $this->stationTaskBatchTypeService->firstByWhere('name', 'U型线分捡');
  49. $id_stationTaskBatchType=$stationTaskBatchType['id']??'';
  50. $batches_handled = collect();
  51. foreach ($batches as $batch) {
  52. if ($batch['status'] != '已处理') {
  53. $stationType = $this->stationTypeService->getByBatch($batch);
  54. $station = $this->stationService->getStation_byType($stationType['name']);
  55. $stationTaskBatches_toCreate->push(
  56. new StationTaskBatch([
  57. 'batch_id' => $batch['id'],
  58. 'station_id' => $station['id'],
  59. 'station_task_batch_type_id' => $id_stationTaskBatchType,
  60. 'status' => '待处理'
  61. ])
  62. );
  63. $batches_handled->push($batch);
  64. }
  65. }
  66. $this->batchService->updateWhereIn('id', data_get($batches_handled, '*.id'), ['status' => '处理中']);
  67. $this->insert($stationTaskBatches_toCreate->toArray());
  68. $stationTaskBatches_toCreate=$this->getAndAttachIds($stationTaskBatches_toCreate);
  69. $this->stationTaskService->registerSubTasks(
  70. $stationTasks_toAttach,
  71. $stationTaskBatches_toCreate->map(function($taskBatch){
  72. return [$taskBatch];
  73. })
  74. );
  75. $this->stationTaskService->registerStations(
  76. $stationTasks_toAttach,
  77. data_get($stationTaskBatches_toCreate,'*.station_id')
  78. );
  79. return $stationTaskBatches_toCreate;
  80. }
  81. function getAndAttachIds($stationTaskBatches): Collection
  82. {
  83. $md5=md5(is_array($stationTaskBatches)
  84. ?$md5=json_encode($stationTaskBatches):$stationTaskBatches->toJson());
  85. return Cache::remember(
  86. 'StationTaskBatch_'.$md5??md5(json_encode($stationTaskBatches->toArray()))
  87. ,config('cache.expirations.rarelyChange')
  88. ,function()use($stationTaskBatches){
  89. return StationTaskBatch::query()
  90. ->whereIn('status',data_get($stationTaskBatches,'*.status'))
  91. ->whereIn('batch_id',data_get($stationTaskBatches,'*.batch_id'))
  92. ->orderByDesc('id')
  93. ->limit(count($stationTaskBatches))
  94. ->get();
  95. });
  96. }
  97. function markManyExcepted(Collection $stationTaskBatches_failed)
  98. {
  99. foreach (
  100. $stationTaskBatches_failed
  101. as $stationTaskBatch) {
  102. if($stationTaskBatch['status']!='异常')
  103. $this->markExcepted($stationTaskBatch);
  104. }
  105. ($logAtFailings_andWait =
  106. function ($stationTaskBatches_failed) {
  107. if ($stationTaskBatches_failed->isEmpty()) return;
  108. throw new ErrorException('任务波次异常失败的');
  109. })($stationTaskBatches_failed);
  110. }
  111. /**
  112. * @param Collection $stationTaskBatches
  113. * @return Collection|\Tightenco\Collect\Support\Collection|null 返回执行失败的记录
  114. */
  115. function runMany(Collection $stationTaskBatches):?Collection
  116. {
  117. LogService::log(__METHOD__,'runMany','波次任务分配6.1:'.json_encode($stationTaskBatches));
  118. $stationTaskBatches_failed = null;
  119. ($execute =
  120. function (
  121. Collection $stationTaskBatches, &$stationTaskBatches_failed) {
  122. LogService::log(__METHOD__,'runMany','波次任务分配6.2:'.json_encode($stationTaskBatches));
  123. if ($stationTaskBatches->isEmpty()) return;
  124. LogService::log(__METHOD__,'runMany','波次任务分配6.3:'.json_encode($stationTaskBatches));
  125. $stationTaskBatches_failed = collect();
  126. LogService::log(__METHOD__,'runMany','波次任务分配6.4:'.json_encode($stationTaskBatches));
  127. foreach ($stationTaskBatches as $stationTaskBatch) {
  128. LogService::log(__METHOD__,'runMany','波次任务分配6.5:'.json_encode($stationTaskBatches));
  129. $failed = !$this->run($stationTaskBatch);
  130. LogService::log(__METHOD__,'runMany','波次任务分配6.6:'.json_encode($stationTaskBatches));
  131. if ($failed) $stationTaskBatches_failed->push($stationTaskBatch);
  132. }
  133. })($stationTaskBatches, $stationTaskBatches_failed);
  134. ($logAtFailings_andWait =
  135. function ($stationTaskBatches_failed) {
  136. LogService::log(__METHOD__,'runMany','波次任务分配6.7:'.json_encode($stationTaskBatches_failed));
  137. if ($stationTaskBatches_failed->isEmpty()) return;
  138. LogService::log(__METHOD__,'runMany','波次任务分配6.8:'.json_encode($stationTaskBatches_failed));
  139. $retry_after_sec = config('task.batchTask.retry_after_sec');
  140. LogService::log(__METHOD__, __FUNCTION__,
  141. '任务波次没有执行完的,' . $retry_after_sec . '秒后准备重试:' . $stationTaskBatches_failed->toJson()
  142. . '调用堆栈r:' . json_encode(array_slice(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), 0, 3))
  143. );
  144. LogService::log(__METHOD__,'runMany','波次任务分配6.9:'.json_encode($stationTaskBatches_failed));
  145. sleep($retry_after_sec);
  146. LogService::log(__METHOD__,'runMany','波次任务分配6.91:'.json_encode($stationTaskBatches_failed));
  147. })($stationTaskBatches_failed);
  148. LogService::log(__METHOD__,'runMany','波次任务分配6.92:'.json_encode($stationTaskBatches));
  149. $execute ($stationTaskBatches_failed, $stationTaskBatches_failed); //再次尝试
  150. LogService::log(__METHOD__,'runMany','波次任务分配6.93:'.json_encode($stationTaskBatches));
  151. $this->markManyExcepted ($stationTaskBatches_failed);
  152. LogService::log(__METHOD__,'runMany','波次任务分配6.94:'.json_encode($stationTaskBatches));
  153. return $stationTaskBatches_failed;
  154. }
  155. function run(StationTaskBatch $stationTaskBatch): bool
  156. {
  157. LogService::log(__METHOD__,'runMany','波次任务分配6.r1:'.json_encode($stationTaskBatch));
  158. $this->instant($this->foreignHaiRoboticsService,'ForeignHaiRoboticsService');
  159. $this->instant($this->stationService,'StationService');
  160. $stationTaskBatch->loadMissing(['station','stationTask.stationTaskMaterialBoxes']);
  161. LogService::log(__METHOD__,'runMany','波次任务分配6.r2:'.json_encode($stationTaskBatch));
  162. $toLocation = $this->stationService->getULineEntrance($stationTaskBatch['station'])['code'];
  163. LogService::log(__METHOD__,'runMany','波次任务分配6.r3:'.json_encode($stationTaskBatch));
  164. $groupPrefix = $stationTaskBatch['id'];
  165. $taskMaterialBoxes = $stationTaskBatch['stationTask']['stationTaskMaterialBoxes'] ??
  166. (function () use ($stationTaskBatch) {
  167. LogService::log(__METHOD__,'runMany','波次任务分配6.r4:'.json_encode($stationTaskBatch));
  168. throw new Exception('找不到料箱:' . json_encode($stationTaskBatch));
  169. })();
  170. try{
  171. LogService::log(__METHOD__,'runMany','波次任务分配6.r5:'.json_encode($stationTaskBatch));
  172. $isFetchedFromRobotics
  173. = $this->foreignHaiRoboticsService->
  174. fetchGroup($toLocation, $taskMaterialBoxes, $groupPrefix);
  175. LogService::log(__METHOD__,'runMany','波次任务分配6.r6:'.json_encode($stationTaskBatch));
  176. }catch(Exception $e){
  177. throw new ErrorException('$stationTaskBatch运行波次机器人任务失败,获取组失败: '.$stationTaskBatch->toJson() . $e->getMessage());
  178. }
  179. LogService::log(__METHOD__,'runMany','波次任务分配6.r7:'.json_encode($stationTaskBatch));
  180. ($markNewStatus
  181. =function()use($isFetchedFromRobotics,$stationTaskBatch){
  182. $isFetchedFromRobotics?
  183. $this->markProcessing($stationTaskBatch):
  184. $this->markExcepted($stationTaskBatch);
  185. LogService::log(__METHOD__,'runMany','波次任务分配6.r8:'.json_encode($stationTaskBatch));
  186. })();
  187. LogService::log(__METHOD__,'runMany','波次任务分配6.r9:'.json_encode($stationTaskBatch));
  188. return $isFetchedFromRobotics;
  189. }
  190. function markProcessing($stationTaskBatch_orCollection)
  191. {
  192. if (get_class($stationTaskBatch_orCollection)==StationTaskBatch::class){
  193. $stationTaskBatch_orCollection = collect([$stationTaskBatch_orCollection]);
  194. }
  195. $this->markProcessing_byIds(data_get($stationTaskBatch_orCollection, '*.id'));
  196. }
  197. function markProcessing_byIds($ids)
  198. {
  199. if(!$ids)$ids=[];
  200. if(!is_array($ids))$ids=[$ids];
  201. StationTaskBatch::query()
  202. ->whereIn('id', $ids)
  203. ->update(['status'=>'处理中']);
  204. }
  205. function markProcessed($stationTaskBatch_orCollection)
  206. {
  207. if (get_class($stationTaskBatch_orCollection)==StationTaskBatch::class){
  208. $stationTaskBatch_orCollection = collect([$stationTaskBatch_orCollection]);
  209. }
  210. $this->markProcessed_byIds(data_get($stationTaskBatch_orCollection, '*.id'));
  211. }
  212. function markProcessed_byIds($ids)
  213. {
  214. if(!$ids)$ids=[];
  215. if(!is_array($ids))$ids=[$ids];
  216. StationTaskBatch::query()
  217. ->whereIn('id', $ids)
  218. ->update(['status'=>'完成']);
  219. }
  220. // function markFinished($stationTaskBatches)
  221. // {
  222. // if (get_class($stationTaskBatches)==StationTaskBatch::class){
  223. // $stationTaskBatches = collect($stationTaskBatches);
  224. // }
  225. // StationTaskBatch::query()
  226. // ->whereIn('id', data_get($stationTaskBatches, '*.id'))
  227. // ->update(['status'=>'完成']);
  228. //
  229. // $this->stationTaskService
  230. // ->markProcessing_byId(
  231. // data_get($stationTaskBatches, '*.station_id')
  232. // );
  233. // }
  234. function markExcepted(StationTaskBatch $stationTaskBatch)
  235. {
  236. $stationTaskBatch['status'] = '异常';
  237. $stationTaskBatch ->update();
  238. }
  239. }