StationTaskMaterialBoxService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. <?php
  2. namespace App\Services;
  3. use App\Batch;
  4. use App\Events\BroadcastToStation;
  5. use App\Exceptions\ErrorException;
  6. use App\Exceptions\Exception;
  7. use App\Jobs\CacheShelfTaskJob;
  8. use App\MaterialBox;
  9. use App\OrderCommodity;
  10. use App\StationCacheShelfGrid;
  11. use App\StationTask;
  12. use App\StationTaskBatch;
  13. use App\StationTaskMaterialBox;
  14. use Carbon\Carbon;
  15. use Illuminate\Support\Collection;
  16. use Illuminate\Support\Facades\Cache;
  17. use App\Traits\ServiceAppAop;
  18. use Illuminate\Support\Facades\DB;
  19. class StationTaskMaterialBoxService
  20. {
  21. use ServiceAppAop;
  22. protected $modelClass=StationTaskMaterialBox::class;
  23. /** @var StationService $stationService */
  24. private $stationService;
  25. /** @var StationTypeService $stationTypeService */
  26. private $stationTypeService;
  27. /** @var StationTaskService $stationTaskService */
  28. private $stationTaskService;
  29. /** @var StationTaskBatchService $stationTaskBatchService */
  30. private $stationTaskBatchService;
  31. /** @var StationTaskCommodityService $stationTaskCommodityService */
  32. private $stationTaskCommodityService;
  33. /** @var OrderCommodityService $orderCommodityService */
  34. private $orderCommodityService;
  35. /** @var MaterialBoxService $materialBoxService */
  36. private $materialBoxService;
  37. /** @var CacheShelfService $cacheShelfService */
  38. private $cacheShelfService;
  39. /** @var StorageService $storageService */
  40. private $storageService;
  41. public function __construct(){
  42. $this->stationService=null;
  43. $this->stationTypeService=null;
  44. $this->stationTaskService=null;
  45. $this->materialBoxService=null;
  46. $this->stationTaskBatchService=null;
  47. $this->stationTaskCommodityService=null;
  48. }
  49. function create($kvPairs)
  50. {
  51. return StationTaskMaterialBox::query()->create($kvPairs);
  52. }
  53. function createByStationAndMaterialBox($station, $materialBox)
  54. {
  55. return StationTaskMaterialBox::query()->create([
  56. 'station_id' => $station['id'],
  57. 'material_box_id' => $materialBox['id'],
  58. 'status' => '待处理'
  59. ]);
  60. }
  61. function getOccupied_byBatches(?Collection $batches): ?Collection
  62. {
  63. return StationTaskMaterialBox::query()
  64. ->where('status','<>','完成')
  65. ->where('created_at','>',Carbon::now()->subHours(2))
  66. ->whereHas('materialBox',function ($query)use($batches){
  67. $locations=OrderCommodity::query()
  68. ->whereHas('order',function ($queryO)use($batches){
  69. $queryO->whereIn('batch_id',data_get($batches,'*.id')??[]);
  70. })->get('location');
  71. $query->whereIn('code',data_get($locations,'*.location')??[]);
  72. })
  73. ->get();
  74. }
  75. function createByBatches(Collection $batches,Collection $stationTasks_toAttach): Collection
  76. {
  77. $this->instant($this->stationTaskService,'StationTaskService');
  78. LogService::log(__METHOD__,'assignTasks','波次任务分配4.c1:'.json_encode($batches));
  79. $stationTaskMaterialBoxes_byBatch = (function () use ($batches) {
  80. $stationTaskMaterialBoxes_listByBatch = new Collection();
  81. foreach ($batches as $batch) {
  82. $stationTaskMaterialBoxes_listByBatch->push(
  83. $this->createByBatch($batch)
  84. );
  85. }
  86. return $stationTaskMaterialBoxes_listByBatch;
  87. })();
  88. LogService::log(__METHOD__,'assignTasks','波次任务分配4.c2:'.json_encode($batches));
  89. $this->stationTaskService
  90. ->registerSubTasks(
  91. $stationTasks_toAttach,
  92. $stationTaskMaterialBoxes_byBatch);
  93. return collect(data_get($stationTaskMaterialBoxes_byBatch,'*.*'));
  94. }
  95. function createByBatch(Batch $batch): ?Collection
  96. {
  97. $this->instant($this->materialBoxService,'MaterialBoxService');
  98. $this->instant($this->stationTypeService,'StationTypeService');
  99. $this->instant($this->stationService,'StationService');
  100. $this->instant($this->stationTaskBatchService,'StationTaskBatchService');
  101. $this->instant($this->orderCommodityService,'OrderCommodityService');
  102. $stationMaterialBoxes_toCreate=new Collection();
  103. $order_ids=data_get($batch['orders'],'*.id');
  104. $orderCommodities=OrderCommodity::query()->orderByRaw("commodity_id,amount desc")//同商品多条 数量最小优先
  105. ->with('orderBin')->whereIn('order_id',$order_ids)->get();
  106. //$orderCommodities=$this->orderCommodityService->correctLocation_fromWMS($orderCommodities);
  107. if($orderCommodities->isEmpty())return $stationMaterialBoxes_toCreate;
  108. $stationType=$this->stationTypeService->getForMaterialBox_onBatchProcess();
  109. $stationTaskBatch=$this->stationTaskBatchService->get(['batch_id'=>$batch['id']])->first();
  110. $materialBoxIds_used=[];
  111. //$orderCommodities=$orderCommodities->sortBy('commodity_id');//按商品排序后,出货可以同商品挨在一起
  112. foreach ($orderCommodities as $orderCommodity){
  113. $station=$this->stationService->getStation_byType($stationType['name']);
  114. $materialBox=$this->materialBoxService->firstOrCreate(['code' => $orderCommodity['location']]);
  115. if(in_array($materialBox['id'],$materialBoxIds_used))continue;
  116. $stationMaterialBoxes_toCreate->push([
  117. 'station_id'=>$station['id'],
  118. 'material_box_id'=>$materialBox['id'],
  119. 'station_task_batch_id'=>$stationTaskBatch['id'],
  120. 'status'=>'待处理'
  121. ]);
  122. $materialBoxIds_used[]=$materialBox['id'];
  123. }
  124. return $this->insert($stationMaterialBoxes_toCreate->toArray(),true);
  125. }
  126. function get(array $kvPairs, $with=null){
  127. ksort($kvPairs);
  128. return Cache::remember('StationTaskMaterialBox'.md5(json_encode($kvPairs).json_encode([$with])), config('cache.expirations.fastChange'), function ()use($kvPairs,$with) {
  129. $query = StationTaskMaterialBox::query();
  130. if($with){
  131. $query->with($with);
  132. }
  133. foreach ($kvPairs as $column => $value){
  134. if (is_array($value))$query->whereIn($column,$value);
  135. else $query->where($column,$value);
  136. }
  137. return $query->get();
  138. });
  139. }
  140. function markHasPut(StationTaskMaterialBox $stationTaskMaterialBox){
  141. $this->instant($this->stationTaskBatchService,'StationTaskBatchService');
  142. $this->instant($this->stationTaskCommodityService,'StationTaskCommodityService');
  143. $this->instant($this->stationTaskService,'StationTaskService');
  144. $this->instant($this->stationService,'StationService');
  145. $this->instant($this->cacheShelfService,'CacheShelfService');
  146. $this->instant($this->storageService,'StorageService');
  147. try{
  148. LogService::log('海柔请求','markHasTaken1','');
  149. $taskType=$this->getServingTaskType($stationTaskMaterialBox);
  150. LogService::log('海柔请求','markHasTaken2',
  151. json_encode($taskType));
  152. switch ($taskType){
  153. case '分波次':
  154. $this->markProcessing($stationTaskMaterialBox);
  155. $this->stationTaskBatchService->markProcessing_byIds($stationTaskMaterialBox['station_task_batch_id']);
  156. $this->stationTaskCommodityService->markProcessing($stationTaskMaterialBox['stationTaskCommodities']);
  157. $this->stationTaskService->markProcessing_byIds(data_get($stationTaskMaterialBox['stationTaskCommodities'],'*.station_task_id'));
  158. /** @var StationTask $stationTask */
  159. $stationTask = $this->stationTaskService->getProcessing();
  160. $this->stationService->broadcastBinMonitor($stationTaskMaterialBox['station_id'], $stationTask);
  161. $stationTaskMaterialBox->materialBox['status']='在U型线';
  162. $stationTaskMaterialBox->materialBox->update();
  163. break;
  164. case '入立库':
  165. $stationTaskMaterialBox->materialBox['status']='在立库';
  166. $stationTaskMaterialBox->materialBox->update();
  167. //$this->storageService->checkMark($stationTaskMaterialBox); //检查标记并做一些特殊处理
  168. break;
  169. case '入缓存架':
  170. $stationTaskMaterialBox->materialBox['status']='在缓存架';
  171. $stationTaskMaterialBox->materialBox->update();
  172. $stationTaskMaterialBox->loadMissing("station"); //提前加载站,后续都需要站信息来处理
  173. $this->storageService->putCacheShelf($stationTaskMaterialBox);
  174. $this->storageService->releaseOccupation($stationTaskMaterialBox); //释放库位占用
  175. break;
  176. default:;
  177. }
  178. $this->taskCompleted($stationTaskMaterialBox);
  179. }catch (\Exception $e){
  180. throw new ErrorException('放置料箱出错');
  181. }
  182. }
  183. private function taskCompleted($stationTaskMaterialBox)
  184. {
  185. $this->set($stationTaskMaterialBox,[
  186. 'id' => $stationTaskMaterialBox['station_id'],
  187. 'status' => '完成',
  188. ]);
  189. if (!$stationTaskMaterialBox->station_task_id)return;
  190. $task = StationTaskMaterialBox::query()->select(DB::raw(1))
  191. ->where("station_task_id",$stationTaskMaterialBox->station_task_id)
  192. ->where("status","!=","完成")->first();
  193. if (!$task)StationTask::query()->where("id",$stationTaskMaterialBox->station_task_id)
  194. ->update(["status"=>"完成"]);
  195. }
  196. /**
  197. * 取出料箱通知
  198. *
  199. * @param $stationTaskMaterialBox
  200. * @throws \Exception
  201. */
  202. function markHasTaken($stationTaskMaterialBox)
  203. {
  204. $this->instant($this->cacheShelfService,'CacheShelfService');
  205. //维护缓存架可用度
  206. $map = Cache::get("CACHE_SHELF_MAPPING",function (){return [];});
  207. if (isset($map[$stationTaskMaterialBox->material_box_id])){
  208. $available=Cache::get("CACHE_SHELF_AVAILABLE",function (){return [];});
  209. $available[$map[$stationTaskMaterialBox->material_box_id]] = true;
  210. Cache::forever("CACHE_SHELF_AVAILABLE",$available);
  211. CacheShelfTaskJob::dispatch("CACHE_SHELF_AVAILABLE",count($available))->delay(now()->addSeconds(config("haiRou.cacheShelf.outBinAwait")));
  212. unset($map[$stationTaskMaterialBox->material_box_id]);
  213. Cache::forever("CACHE_SHELF_MAPPING",$map);
  214. }
  215. }
  216. function processNextQueued(?StationTaskMaterialBox $stationTaskMaterialBox_lastProcessed){
  217. $station_id=$stationTaskMaterialBox_lastProcessed['station_id'];
  218. $stationTaskMaterialBox_next=StationTaskMaterialBox::query()
  219. ->where('station_id',$station_id)
  220. ->where('status','处理队列')
  221. ->orderBy('updated_at')
  222. ->first();
  223. if($stationTaskMaterialBox_next){
  224. $stationTaskMaterialBox_next->update(['status'=>'处理中']);
  225. }
  226. return $stationTaskMaterialBox_next;
  227. }
  228. function markProcessed(StationTaskMaterialBox $stationTaskMaterialBox){
  229. $stationTaskMaterialBox['status'] = '完成';
  230. $stationTaskMaterialBox->save();
  231. }
  232. function getNotProcessedSiblings($stationTaskMaterialBox){
  233. return StationTaskMaterialBox::query()
  234. ->whereNotIn('status',['完成'])
  235. ->where('station_task_id',$stationTaskMaterialBox['station_task_id'])
  236. ->get();
  237. }
  238. /**
  239. * 每波次仅将最老的作务标为“处理中”,其他置入队列;
  240. * 如某波次已经有“处理中“,则他部置入队列
  241. * @param $stationTaskMaterialBox_orBoxes ?? 单个或多个
  242. */
  243. function markProcessing($stationTaskMaterialBox_orBoxes)
  244. {
  245. $this->instant($this->stationTaskService,'StationTaskService');
  246. $stationTaskMaterialBoxes =
  247. (function()use($stationTaskMaterialBox_orBoxes){
  248. if (get_class($stationTaskMaterialBox_orBoxes)==StationTaskMaterialBox::class){
  249. return collect([$stationTaskMaterialBox_orBoxes]);
  250. }
  251. return collect($stationTaskMaterialBox_orBoxes);
  252. })();
  253. $stationTaskMaterialBoxes_grouped=
  254. ($按时间从前往后排出顺序=function ()use(&$stationTaskMaterialBoxes){
  255. return $stationTaskMaterialBoxes
  256. ->sortBy('id')
  257. ->groupBy('station_task_batch_id');
  258. })();
  259. $stationTaskMaterialBoxes_grouped->each(function(&$groupByBatch){
  260. ($将所有要标记的箱任务先放在队列里=function()use(&$groupByBatch){
  261. $groupByBatch->each(function (&$stationTaskMaterialBox){
  262. $stationTaskMaterialBox['status']='处理队列';
  263. });
  264. })();
  265. ($如果之前没有处理中则标记第一个为处理目标,准备持久化=function()use(&$groupByBatch){
  266. $stationId=$groupByBatch[0]['station_id'];
  267. $processing=$this->getProcessing_byStationId($stationId);
  268. if(!$processing){
  269. $groupByBatch[0]['status']='处理中';
  270. $groupByBatch[0]->update();
  271. }else{
  272. foreach ($groupByBatch as &$stationTaskMaterialBox){
  273. if($stationTaskMaterialBox['id']==$processing['id']){
  274. $stationTaskMaterialBox['status']='处理中';
  275. }
  276. }
  277. }
  278. })();
  279. });
  280. ($持久化处理队列的记录=function()use(&$stationTaskMaterialBoxes_grouped){
  281. $toArray = $stationTaskMaterialBoxes_grouped->collapse();
  282. $toArray=$toArray->where('status','处理队列');
  283. $ids_toUpdate = data_get($toArray, '*.id');
  284. if(count($ids_toUpdate))
  285. StationTaskMaterialBox::query()->whereIn('id',$ids_toUpdate)->update(['status'=>'处理队列']);
  286. })();
  287. // StationTaskMaterialBox::query()
  288. // ->whereIn('id', data_get($stationTaskMaterialBoxes, '*.id'))
  289. // ->update(['status'=>'处理中']);
  290. $this->stationTaskService
  291. ->markProcessing_byIds(
  292. data_get($stationTaskMaterialBoxes, '*.*.station_id')
  293. );
  294. }
  295. function getProcessing_byStationId($stationId)
  296. {
  297. //这里不能用缓存,因为更新会非常快
  298. return StationTaskMaterialBox::query()
  299. ->where('station_id',$stationId)
  300. ->where('status','处理中')
  301. ->where('created_at','>',Carbon::now()->subDay())
  302. ->first();
  303. }
  304. function excepted($stationTaskMaterialBoxes_orBox){
  305. if (get_class($stationTaskMaterialBoxes_orBox)==StationTaskMaterialBox::class){
  306. $stationTaskMaterialBoxes_orBox = collect([$stationTaskMaterialBoxes_orBox]);
  307. }
  308. StationTaskMaterialBox::query()->whereIn('id',data_get($stationTaskMaterialBoxes_orBox,'*.id'))
  309. ->update(['status'=>'异常']);
  310. switch (get_class($stationTaskMaterialBoxes_orBox)){
  311. case MaterialBox::class:
  312. case StationTaskMaterialBox::class:
  313. throw new ErrorException('料箱异常'.json_encode($stationTaskMaterialBoxes_orBox->toJson()));
  314. }
  315. }
  316. function getServingTaskType(StationTaskMaterialBox $stationTaskMaterialBox): string
  317. {
  318. $stationTaskMaterialBox->load('station.stationType');
  319. switch ($stationTaskMaterialBox['station']['stationType']['name']){
  320. case "立库":
  321. return '入立库';
  322. case "缓存架":
  323. return '入缓存架';
  324. case "料箱监视器":
  325. if ($stationTaskMaterialBox['station_task_batch_id'])return "分波次";
  326. default:
  327. throw new ErrorException('当前类型找不到');
  328. }
  329. }
  330. }