StationTaskBatchService.php 12 KB

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