StationTaskBatchService.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. ->get();
  93. });
  94. }
  95. function markManyExcepted(Collection $stationTaskBatches_failed)
  96. {
  97. foreach (
  98. $stationTaskBatches_failed
  99. as $stationTaskBatch) {
  100. if($stationTaskBatch['status']!='异常')
  101. $this->markExcepted($stationTaskBatch);
  102. }
  103. ($logAtFailings_andWait =
  104. function ($stationTaskBatches_failed) {
  105. if ($stationTaskBatches_failed->isEmpty()) return;
  106. throw new ErrorException('任务波次异常失败的');
  107. })($stationTaskBatches_failed);
  108. }
  109. /**
  110. * @param Collection $stationTaskBatches
  111. * @return Collection|\Tightenco\Collect\Support\Collection|null 返回执行失败的记录
  112. */
  113. function runMany(Collection $stationTaskBatches):?Collection
  114. {
  115. $stationTaskBatches_failed = null;
  116. ($execute =
  117. function (
  118. Collection $stationTaskBatches, &$stationTaskBatches_failed) {
  119. if ($stationTaskBatches->isEmpty()) return;
  120. $stationTaskBatches_failed = collect();
  121. foreach ($stationTaskBatches as $stationTaskBatch) {
  122. $failed = !$this->run($stationTaskBatch);
  123. if ($failed) $stationTaskBatches_failed->push($stationTaskBatch);
  124. }
  125. })($stationTaskBatches, $stationTaskBatches_failed);
  126. ($logAtFailings_andWait =
  127. function ($stationTaskBatches_failed) {
  128. if ($stationTaskBatches_failed->isEmpty()) return;
  129. $retry_after_sec = config('task.batchTask.retry_after_sec');
  130. LogService::log(__METHOD__, __FUNCTION__,
  131. '任务波次没有执行完的,' . $retry_after_sec . '秒后准备重试:' . $stationTaskBatches_failed->toJson()
  132. . '调用堆栈:' . json_encode(array_slice(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), 0, 3))
  133. );
  134. sleep($retry_after_sec);
  135. })($stationTaskBatches_failed);
  136. $execute ($stationTaskBatches_failed, $stationTaskBatches_failed); //再次尝试
  137. $this->markManyExcepted ($stationTaskBatches_failed);
  138. return $stationTaskBatches_failed;
  139. }
  140. function run(StationTaskBatch $stationTaskBatch): bool
  141. {
  142. $this->instant($this->foreignHaiRoboticsService,'ForeignHaiRoboticsService');
  143. $this->instant($this->stationService,'StationService');
  144. $stationTaskBatch->loadMissing(['station','stationTask.stationTaskMaterialBoxes']);
  145. $toLocation = $this->stationService->getULineEntrance($stationTaskBatch['station'])['code'];
  146. $groupPrefix = $stationTaskBatch['id'];
  147. $taskMaterialBoxes = $stationTaskBatch['stationTask']['stationTaskMaterialBoxes'] ??
  148. (function () use ($stationTaskBatch) {
  149. throw new Exception('找不到料箱:' . json_encode($stationTaskBatch));
  150. })();
  151. try{
  152. $isFetchedFromRobotics
  153. = $this->foreignHaiRoboticsService->
  154. fetchGroup($toLocation, $taskMaterialBoxes, $groupPrefix);
  155. }catch(Exception $e){
  156. throw new ErrorException('$stationTaskBatch运行波次机器人任务失败,获取组失败: '.$stationTaskBatch->toJson() . $e->getMessage());
  157. }
  158. ($markNewStatus
  159. =function()use($isFetchedFromRobotics,$stationTaskBatch){
  160. $isFetchedFromRobotics?
  161. $this->markProcessing($stationTaskBatch):
  162. $this->markExcepted($stationTaskBatch);
  163. })();
  164. return $isFetchedFromRobotics;
  165. }
  166. function markProcessing($stationTaskBatch_orCollection)
  167. {
  168. if (get_class($stationTaskBatch_orCollection)==StationTaskBatch::class){
  169. $stationTaskBatch_orCollection = collect([$stationTaskBatch_orCollection]);
  170. }
  171. $this->markProcessing_byIds(data_get($stationTaskBatch_orCollection, '*.id'));
  172. }
  173. function markProcessing_byIds($ids)
  174. {
  175. if(!$ids)$ids=[];
  176. if(!is_array($ids))$ids=[$ids];
  177. StationTaskBatch::query()
  178. ->whereIn('id', $ids)
  179. ->update(['status'=>'处理中']);
  180. }
  181. // function markFinished($stationTaskBatches)
  182. // {
  183. // if (get_class($stationTaskBatches)==StationTaskBatch::class){
  184. // $stationTaskBatches = collect($stationTaskBatches);
  185. // }
  186. // StationTaskBatch::query()
  187. // ->whereIn('id', data_get($stationTaskBatches, '*.id'))
  188. // ->update(['status'=>'完成']);
  189. //
  190. // $this->stationTaskService
  191. // ->markProcessing_byId(
  192. // data_get($stationTaskBatches, '*.station_id')
  193. // );
  194. // }
  195. function markExcepted(StationTaskBatch $stationTaskBatch)
  196. {
  197. $stationTaskBatch['status'] = '异常';
  198. $stationTaskBatch ->update();
  199. }
  200. }