StationTaskMaterialBoxService.php 16 KB

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