StationTaskBatchService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. $stationTaskBatches_toCreate=$stationTaskBatches_toCreate->reverse();//这里的波次顺序是反的,不知为什么,所以反向一次就好了。其他解耦的地方都是正序,必须保持一致
  69. $this->insert($stationTaskBatches_toCreate->toArray());
  70. $stationTaskBatches_toCreate=$this->getAndAttachIds($stationTaskBatches_toCreate);
  71. $this->stationTaskService->registerSubTasks(
  72. $stationTasks_toAttach,
  73. $stationTaskBatches_toCreate->map(function($taskBatch){
  74. return [$taskBatch];
  75. })
  76. );
  77. $this->stationTaskService->registerStations(
  78. $stationTasks_toAttach,
  79. data_get($stationTaskBatches_toCreate,'*.station_id')
  80. );
  81. return $stationTaskBatches_toCreate;
  82. }
  83. function getAndAttachIds($stationTaskBatches): Collection
  84. {
  85. $md5=md5(is_array($stationTaskBatches)
  86. ?$md5=json_encode($stationTaskBatches):$stationTaskBatches->toJson());
  87. return Cache::remember(
  88. 'StationTaskBatch_'.$md5??md5(json_encode($stationTaskBatches->toArray()))
  89. ,config('cache.expirations.rarelyChange')
  90. ,function()use($stationTaskBatches){
  91. return StationTaskBatch::query()
  92. ->whereIn('status',data_get($stationTaskBatches,'*.status'))
  93. ->whereIn('batch_id',data_get($stationTaskBatches,'*.batch_id'))
  94. ->orderByDesc('id')
  95. ->limit(count($stationTaskBatches))
  96. ->get();
  97. });
  98. }
  99. function markManyExcepted(Collection $stationTaskBatches_failed)
  100. {
  101. foreach (
  102. $stationTaskBatches_failed
  103. as $stationTaskBatch) {
  104. if($stationTaskBatch['status']!='异常')
  105. $this->markExcepted($stationTaskBatch);
  106. }
  107. ($logAtFailings_andWait =
  108. function ($stationTaskBatches_failed) {
  109. if ($stationTaskBatches_failed->isEmpty()) return;
  110. throw new ErrorException('任务波次异常失败的');
  111. })($stationTaskBatches_failed);
  112. }
  113. /**
  114. * @param Collection|null $stationTaskBatches
  115. * @return Collection|\Tightenco\Collect\Support\Collection|null 返回执行失败的记录
  116. * @throws ErrorException
  117. */
  118. function runMany(?Collection $stationTaskBatches):?Collection
  119. {
  120. LogService::log(__METHOD__,'runMany','波次任务分配6.1:'.json_encode($stationTaskBatches));
  121. $stationTaskBatches_failed = null;
  122. ($execute =
  123. function (
  124. Collection $stationTaskBatches, &$stationTaskBatches_failed) {
  125. LogService::log(__METHOD__,'runMany','波次任务分配6.2:'.json_encode($stationTaskBatches));
  126. if ($stationTaskBatches->isEmpty()) return;
  127. LogService::log(__METHOD__,'runMany','波次任务分配6.3:'.json_encode($stationTaskBatches));
  128. $stationTaskBatches_failed = collect();
  129. LogService::log(__METHOD__,'runMany','波次任务分配6.4:'.json_encode($stationTaskBatches));
  130. foreach ($stationTaskBatches as $stationTaskBatch) {
  131. LogService::log(__METHOD__,'runMany','波次任务分配6.5:'.json_encode($stationTaskBatches));
  132. $failed = !$this->run($stationTaskBatch);
  133. LogService::log(__METHOD__,'runMany','波次任务分配6.6:'.json_encode($stationTaskBatches));
  134. if ($failed) $stationTaskBatches_failed->push($stationTaskBatch);
  135. }
  136. })($stationTaskBatches, $stationTaskBatches_failed);
  137. ($logAtFailings_andWait =
  138. function ($stationTaskBatches_failed) {
  139. LogService::log(__METHOD__,'runMany','波次任务分配6.7:'.json_encode($stationTaskBatches_failed));
  140. if ($stationTaskBatches_failed->isEmpty()) return;
  141. LogService::log(__METHOD__,'runMany','波次任务分配6.8:'.json_encode($stationTaskBatches_failed));
  142. $retry_after_sec = config('task.batchTask.retry_after_sec');
  143. LogService::log(__METHOD__, __FUNCTION__,
  144. '任务波次没有执行完的,' . $retry_after_sec . '秒后准备重试:' . $stationTaskBatches_failed->toJson()
  145. . '调用堆栈r:' . json_encode(array_slice(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), 0, 3))
  146. );
  147. LogService::log(__METHOD__,'runMany','波次任务分配6.9:'.json_encode($stationTaskBatches_failed));
  148. sleep($retry_after_sec);
  149. LogService::log(__METHOD__,'runMany','波次任务分配6.91:'.json_encode($stationTaskBatches_failed));
  150. })($stationTaskBatches_failed);
  151. LogService::log(__METHOD__,'runMany','波次任务分配6.92:'.json_encode($stationTaskBatches));
  152. $execute ($stationTaskBatches_failed, $stationTaskBatches_failed); //再次尝试
  153. LogService::log(__METHOD__,'runMany','波次任务分配6.93:'.json_encode($stationTaskBatches));
  154. $this->markManyExcepted ($stationTaskBatches_failed);
  155. LogService::log(__METHOD__,'runMany','波次任务分配6.94:'.json_encode($stationTaskBatches));
  156. return $stationTaskBatches_failed;
  157. }
  158. function run(StationTaskBatch $stationTaskBatch): bool
  159. {
  160. LogService::log(__METHOD__,'runMany','波次任务分配6.r1:'.json_encode($stationTaskBatch));
  161. $this->instant($this->foreignHaiRoboticsService,'ForeignHaiRoboticsService');
  162. $this->instant($this->stationService,'StationService');
  163. $stationTaskBatch->loadMissing(['station','stationTask.stationTaskMaterialBoxes']);
  164. LogService::log(__METHOD__,'runMany','波次任务分配6.r2:'.json_encode($stationTaskBatch));
  165. $toLocation = $this->stationService->getULineEntrance($stationTaskBatch['station'])['code'];
  166. LogService::log(__METHOD__,'runMany','波次任务分配6.r3:'.json_encode($stationTaskBatch));
  167. $groupPrefix = $stationTaskBatch['id'];
  168. $taskMaterialBoxes = $stationTaskBatch['stationTask']['stationTaskMaterialBoxes'] ??
  169. (function () use ($stationTaskBatch) {
  170. LogService::log(__METHOD__,'runMany','波次任务分配6.r4:'.json_encode($stationTaskBatch));
  171. throw new Exception('找不到料箱:' . json_encode($stationTaskBatch));
  172. })();
  173. try{
  174. LogService::log(__METHOD__,'runMany','波次任务分配6.r5:'.json_encode($stationTaskBatch));
  175. $isFetchedFromRobotics
  176. = $this->foreignHaiRoboticsService->
  177. fetchGroup($toLocation, $taskMaterialBoxes, $groupPrefix);
  178. LogService::log(__METHOD__,'runMany','波次任务分配6.r6:'.json_encode($stationTaskBatch));
  179. }catch(Exception $e){
  180. throw new ErrorException('$stationTaskBatch运行波次机器人任务失败,获取组失败: '.$stationTaskBatch->toJson() . $e->getMessage());
  181. }
  182. LogService::log(__METHOD__,'runMany','波次任务分配6.r7:'.json_encode($stationTaskBatch));
  183. ($markNewStatus
  184. =function()use($isFetchedFromRobotics,$stationTaskBatch){
  185. $isFetchedFromRobotics?
  186. $this->markProcessing($stationTaskBatch):
  187. $this->markExcepted($stationTaskBatch);
  188. LogService::log(__METHOD__,'runMany','波次任务分配6.r8:'.json_encode($stationTaskBatch));
  189. })();
  190. LogService::log(__METHOD__,'runMany','波次任务分配6.r9:'.json_encode($stationTaskBatch));
  191. return $isFetchedFromRobotics;
  192. }
  193. function markProcessing($stationTaskBatch_orCollection)
  194. {
  195. if (get_class($stationTaskBatch_orCollection)==StationTaskBatch::class){
  196. $stationTaskBatch_orCollection = collect([$stationTaskBatch_orCollection]);
  197. }
  198. $this->markProcessing_byIds(data_get($stationTaskBatch_orCollection, '*.id'));
  199. }
  200. function markProcessing_byIds($ids)
  201. {
  202. if(!$ids)$ids=[];
  203. if(!is_array($ids))$ids=[$ids];
  204. $hasProcessing=StationTaskBatch::query()
  205. ->whereNotIn('id', $ids)
  206. ->where(['status'=>'处理中'])
  207. ->where('created_at','>',Carbon::now()->subDay())
  208. ->get('id')->isNotEmpty();
  209. $status = '处理中';
  210. if($hasProcessing)
  211. $status = '处理队列';
  212. StationTaskBatch::query()
  213. ->whereIn('id', $ids)
  214. ->update(['status'=>$status]);
  215. }
  216. function markProcessed($stationTaskBatch_orCollection)
  217. {
  218. if (get_class($stationTaskBatch_orCollection)==StationTaskBatch::class){
  219. $stationTaskBatch_orCollection = collect([$stationTaskBatch_orCollection]);
  220. }
  221. $this->markProcessed_byIds(data_get($stationTaskBatch_orCollection, '*.id'));
  222. }
  223. function markProcessed_byIds($ids)
  224. {
  225. if(!$ids)$ids=[];
  226. if(!is_array($ids))$ids=[$ids];
  227. StationTaskBatch::query()
  228. ->whereIn('id', $ids)
  229. ->update(['status'=>'完成']);
  230. }
  231. // function markFinished($stationTaskBatches)
  232. // {
  233. // if (get_class($stationTaskBatches)==StationTaskBatch::class){
  234. // $stationTaskBatches = collect($stationTaskBatches);
  235. // }
  236. // StationTaskBatch::query()
  237. // ->whereIn('id', data_get($stationTaskBatches, '*.id'))
  238. // ->update(['status'=>'完成']);
  239. //
  240. // $this->stationTaskService
  241. // ->markProcessing_byId(
  242. // data_get($stationTaskBatches, '*.station_id')
  243. // );
  244. // }
  245. function markExcepted(StationTaskBatch $stationTaskBatch)
  246. {
  247. $stationTaskBatch['status'] = '异常';
  248. $stationTaskBatch ->update();
  249. }
  250. }