StationTaskBatchService.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. <?php
  2. namespace App\Services;
  3. use App\Exceptions\ErrorException;
  4. use App\StationTaskBatch;
  5. use App\StationTaskCommodity;
  6. use App\TaskTransaction;
  7. use Carbon\Carbon;
  8. use Exception;
  9. use Illuminate\Support\Collection;
  10. use Illuminate\Support\Facades\Cache;
  11. use App\Traits\ServiceAppAop;
  12. class StationTaskBatchService
  13. {
  14. use ServiceAppAop;
  15. protected $modelClass=StationTaskBatch::class;
  16. /** @var StationService $stationService */
  17. private $stationService;
  18. /** @var StationTaskBatchTypeService $stationTaskBatchTypeService */
  19. private $stationTaskBatchTypeService;
  20. /** @var BatchService $batchService */
  21. private $batchService;
  22. /** @var StationTypeService $stationTypeService */
  23. private $stationTypeService;
  24. /** @var StationTaskService $stationTaskService */
  25. private $stationTaskService;
  26. /** @var ForeignHaiRoboticsService $foreignHaiRoboticsService */
  27. private $foreignHaiRoboticsService;
  28. public function __construct()
  29. {
  30. $this->stationService = null;
  31. $this->stationTypeService = null;
  32. $this->stationTaskBatchTypeService = null;
  33. $this->batchService = null;
  34. $this->stationTaskService = null;
  35. $this->foreignHaiRoboticsService = null;
  36. }
  37. /**
  38. * @param Collection $batches Batch[]
  39. * @param Collection $stationTasks_toAttach
  40. * @return Collection
  41. * @throws Exception
  42. */
  43. function createByBatches(Collection $batches, Collection $stationTasks_toAttach): Collection
  44. {
  45. $this->stationService = app('StationService');
  46. $this->stationTaskService = app('StationTaskService');
  47. $this->stationTypeService = app('StationTypeService');
  48. $this->stationTaskBatchTypeService = app('StationTaskBatchTypeService');
  49. $this->batchService = app('BatchService');
  50. $stationTaskBatches_toCreate = new Collection();
  51. $stationTaskBatchType = $this->stationTaskBatchTypeService->firstByWhere('name', 'U型线分捡');
  52. $id_stationTaskBatchType=$stationTaskBatchType['id']??'';
  53. $batches_handled = collect();
  54. foreach ($batches as $batch) {
  55. if ($batch['status'] != '已处理') {
  56. $stationType = $this->stationTypeService->getByBatch($batch);
  57. $station = $this->stationService->getStation_byType($stationType['name']);
  58. $stationTaskBatches_toCreate->push(
  59. new StationTaskBatch([
  60. 'batch_id' => $batch['id'],
  61. 'station_id' => $station['id'],
  62. 'station_task_batch_type_id' => $id_stationTaskBatchType,
  63. 'status' => '待处理'
  64. ])
  65. );
  66. $batches_handled->push($batch);
  67. }
  68. }
  69. $this->batchService->updateWhereIn('id', data_get($batches_handled, '*.id'), ['status' => '处理中']);
  70. $stationTaskBatches_toCreate=$stationTaskBatches_toCreate->reverse();//这里的波次顺序是反的,不知为什么,所以反向一次就好了。其他解耦的地方都是正序,必须保持一致
  71. $this->insert($stationTaskBatches_toCreate->toArray());
  72. $stationTaskBatches_toCreate=$this->getAndAttachIds($stationTaskBatches_toCreate);
  73. $this->stationTaskService->registerSubTasks(
  74. $stationTasks_toAttach,
  75. $stationTaskBatches_toCreate->map(function($taskBatch){
  76. return [$taskBatch];
  77. })
  78. );
  79. $this->stationTaskService->registerStations(
  80. $stationTasks_toAttach,
  81. data_get($stationTaskBatches_toCreate,'*.station_id')
  82. );
  83. return $stationTaskBatches_toCreate;
  84. }
  85. function getAndAttachIds($stationTaskBatches): Collection
  86. {
  87. $md5=md5(is_array($stationTaskBatches)
  88. ?$md5=json_encode($stationTaskBatches):$stationTaskBatches->toJson());
  89. return Cache::remember(
  90. 'StationTaskBatch_'.$md5??md5(json_encode($stationTaskBatches->toArray()))
  91. ,config('cache.expirations.rarelyChange')
  92. ,function()use($stationTaskBatches){
  93. return StationTaskBatch::query()
  94. ->whereIn('status',data_get($stationTaskBatches,'*.status'))
  95. ->whereIn('batch_id',data_get($stationTaskBatches,'*.batch_id'))
  96. ->orderByDesc('id')
  97. ->limit(count($stationTaskBatches))
  98. ->get();
  99. });
  100. }
  101. function markManyExcepted(Collection $stationTaskBatches_failed)
  102. {
  103. foreach (
  104. $stationTaskBatches_failed
  105. as $stationTaskBatch) {
  106. if($stationTaskBatch['status']!='异常')
  107. $this->markExcepted($stationTaskBatch);
  108. }
  109. ($logAtFailings_andWait =
  110. function ($stationTaskBatches_failed) {
  111. if ($stationTaskBatches_failed->isEmpty()) return;
  112. throw new ErrorException('任务波次异常失败的');
  113. })($stationTaskBatches_failed);
  114. }
  115. /**
  116. * @param Collection|null $stationTaskBatches
  117. * @param string $locationType
  118. * @return Collection|\Tightenco\Collect\Support\Collection|null 返回执行失败的记录
  119. * @throws ErrorException
  120. */
  121. function runMany(?Collection $stationTaskBatches, $locationType = 'OUTBIN-U-SHAPE-LINE'):?Collection
  122. {
  123. LogService::log(__METHOD__,'runMany','波次任务分配6.1:'.json_encode($stationTaskBatches));
  124. $stationTaskBatches_failed = null;
  125. ($execute = function(Collection $stationTaskBatches, &$stationTaskBatches_failed)use($locationType){
  126. if ($stationTaskBatches->isEmpty()) return; //波次任务不存在 跳出
  127. $stationTaskBatches_failed = collect();
  128. foreach ($stationTaskBatches as $stationTaskBatch){
  129. $failed = !$this->run($stationTaskBatch, $locationType); //运行波次 获取执行结果
  130. if ($failed) $stationTaskBatches_failed->push($stationTaskBatch);//执行失败 记录失败波次
  131. }
  132. })($stationTaskBatches, $stationTaskBatches_failed);
  133. (function ($stationTaskBatches_failed) {
  134. if ($stationTaskBatches_failed->isEmpty()) return;
  135. $retry_after_sec = config('task.batchTask.retry_after_sec');
  136. LogService::log(__METHOD__, __FUNCTION__,
  137. '任务波次没有执行完的,' . $retry_after_sec . '秒后准备重试:' . $stationTaskBatches_failed->toJson()
  138. . '调用堆栈r:' . json_encode(array_slice(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), 0, 3))
  139. );
  140. sleep($retry_after_sec);
  141. })($stationTaskBatches_failed);
  142. $execute($stationTaskBatches_failed, $stationTaskBatches_failed); //再次尝试
  143. $this->markManyExcepted($stationTaskBatches_failed);
  144. return $stationTaskBatches_failed;
  145. }
  146. /**
  147. * 解析波次任务 任务下发海柔
  148. *
  149. * @param StationTaskBatch $stationTaskBatch
  150. * @param string $locationType
  151. * @return bool
  152. * @throws ErrorException
  153. */
  154. function run(StationTaskBatch $stationTaskBatch, $locationType): bool
  155. {
  156. $this->instant($this->foreignHaiRoboticsService,'ForeignHaiRoboticsService');
  157. $this->instant($this->stationService,'StationService');
  158. $stationTaskBatch->loadMissing(['station','stationTask.stationTaskMaterialBoxes']);
  159. LogService::log(__METHOD__,'runMany','波次任务分配6.r2:'.json_encode($stationTaskBatch));
  160. $groupPrefix = $stationTaskBatch['id'];//将波次任务ID当作组前缀
  161. $taskMaterialBoxes = $stationTaskBatch['stationTask']['stationTaskMaterialBoxes'] ??
  162. (function () use ($stationTaskBatch) {
  163. LogService::log(__METHOD__,'runMany','波次任务分配6.r4:'.json_encode($stationTaskBatch));
  164. throw new Exception('找不到料箱:' . json_encode($stationTaskBatch));
  165. })();//存在任务返回任务 否则抛出无料箱异常
  166. try{
  167. //获取放线入口
  168. switch ($locationType){
  169. case 'OUTBIN-U-SHAPE-LINE'://U型线
  170. $toLocation = $this->stationService->getULineEntrance($stationTaskBatch['station'])['code'];
  171. $isFetchedFromRobotics = $this->foreignHaiRoboticsService->
  172. fetchGroup($toLocation, $taskMaterialBoxes, $groupPrefix);//执行料箱任务
  173. break;
  174. case 'OUTBIN-CACHE-SHELF'://缓存架
  175. list($toLocation, $taskMaterialBoxes, $map) = $this->apportionLocation($taskMaterialBoxes);
  176. if ($toLocation->count()>0){
  177. $isFetchedFromRobotics = $this->foreignHaiRoboticsService->
  178. fetchGroup_multiLocation($toLocation, $taskMaterialBoxes, $groupPrefix, '立架出至缓存架',20);
  179. foreach ($toLocation as $value){
  180. app("CacheShelfService")->lightUp($value,'3','2');
  181. Cache::forever("CACHE_SHELF_OCCUPANCY_{$map[$value]}",true);
  182. }
  183. app("StationService")->locationOccupyMulti($toLocation->toArray());
  184. }else $isFetchedFromRobotics = true;
  185. break;
  186. default:
  187. $isFetchedFromRobotics = false;
  188. }
  189. LogService::log(__METHOD__,'runMany','波次任务分配6.r6:'.json_encode($stationTaskBatch));
  190. }catch(Exception $e){
  191. throw new ErrorException('$stationTaskBatch运行波次机器人任务失败,获取组失败: '.$stationTaskBatch->toJson() . $e->getMessage());
  192. }
  193. (function()use($isFetchedFromRobotics,$stationTaskBatch){
  194. $isFetchedFromRobotics?
  195. $this->markProcessing($stationTaskBatch)://执行成功标记已处理
  196. $this->markExcepted($stationTaskBatch);//执行失败标记失败
  197. })();
  198. return $isFetchedFromRobotics;//返回执行结果
  199. }
  200. function markProcessing($stationTaskBatch_orCollection)
  201. {
  202. if (get_class($stationTaskBatch_orCollection)==StationTaskBatch::class){
  203. $stationTaskBatch_orCollection = collect([$stationTaskBatch_orCollection]);
  204. }
  205. $taskIds = data_get($stationTaskBatch_orCollection, '*.id');
  206. $this->markProcessing_byIds($taskIds);
  207. //app("StorageService")->handleStorage($stationTaskBatch_orCollection);
  208. }
  209. function markProcessing_byIds($ids)
  210. {
  211. if(!$ids)$ids=[];
  212. if(!is_array($ids))$ids=[$ids];
  213. $hasProcessing=StationTaskBatch::query()
  214. ->whereNotIn('id', $ids)
  215. ->where(['status'=>'处理中'])
  216. ->where('created_at','>',Carbon::now()->subDay())
  217. ->get('id')->isNotEmpty();
  218. $status = '处理中';
  219. if($hasProcessing)
  220. $status = '处理队列';
  221. StationTaskBatch::query()
  222. ->whereIn('id', $ids)
  223. ->update(['status'=>$status]);
  224. }
  225. function markProcessed($stationTaskBatch_orCollection)
  226. {
  227. if (get_class($stationTaskBatch_orCollection)==StationTaskBatch::class){
  228. $stationTaskBatch_orCollection = collect([$stationTaskBatch_orCollection]);
  229. }
  230. $this->markProcessed_byIds(data_get($stationTaskBatch_orCollection, '*.id'));
  231. }
  232. function markProcessed_byIds($ids)
  233. {
  234. if(!$ids)$ids=[];
  235. if(!is_array($ids))$ids=[$ids];
  236. StationTaskBatch::query()
  237. ->whereIn('id', $ids)
  238. ->update(['status'=>'完成']);
  239. }
  240. function markExcepted(StationTaskBatch $stationTaskBatch)
  241. {
  242. $stationTaskBatch['status'] = '异常';
  243. $stationTaskBatch ->update();
  244. }
  245. /**
  246. * 为任务分配缓存架库位
  247. *
  248. * @param \Illuminate\Database\Eloquent\Collection $taskMaterialBoxes
  249. *
  250. * @return array
  251. */
  252. public function apportionLocation(Collection $taskMaterialBoxes):array
  253. {
  254. $taskMaterialBoxes->loadMissing(["stationTaskCommodities.order","stationTaskCommodities.commodity.barcodes"]);
  255. //获取可用的库位 加行锁
  256. $stations = app("StationService")->getCacheShelf(true);
  257. $location = [];
  258. $map = [];
  259. foreach ($stations as $station){
  260. $location[] = $station->code;
  261. $map[$station->code] = $station->id;
  262. }
  263. /** @var Collection $handleTask */
  264. $handleTask = $taskMaterialBoxes->splice(0,count($location));
  265. $toLocation = collect();
  266. $updateTask = [["id","station_id"]];
  267. $insertTransaction = [];
  268. $exeInsert = function ($task,$taskCommodity,$status)use(&$insertTransaction){
  269. $insertTransaction[] = [
  270. "doc_code" => $taskCommodity->order->code ?? "",
  271. "bar_code" => $taskCommodity->commodity->barcodes[0]->code ?? "",
  272. "to_station_id" => $task->station_id,
  273. "material_box_id" => $task->material_box_id,
  274. "task_id" => $task->id,
  275. "commodity_id" => $taskCommodity->commodity_id,
  276. "amount" => $taskCommodity->amount,
  277. "type" => "出库",
  278. "status" => $status,
  279. "mark" => 2,
  280. "bin_number"=>$taskCommodity->bin_number,
  281. ];
  282. };
  283. foreach ($handleTask as $index=>$task){
  284. $task->station_id = $map[$location[$index]];
  285. $toLocation->push($location[$index]);
  286. $handleTask->offsetSet($index,$task);
  287. $updateTask[] = ["id"=>$task->id,"station_id"=>$task->station_id];
  288. foreach ($task->stationTaskCommodities as $taskCommodity)$exeInsert($task,$taskCommodity,0);
  289. }
  290. if ($handleTask->count()>0)app("BatchUpdateService")->batchUpdate("station_task_material_boxes",$updateTask);
  291. foreach ($taskMaterialBoxes as $obj)foreach ($obj->stationTaskCommodities as $taskCommodity)$exeInsert($obj,$taskCommodity,3);
  292. TaskTransaction::query()->insert($insertTransaction);
  293. return array($toLocation, $handleTask, $map);
  294. }
  295. }