StationTaskMaterialBoxService.php 16 KB

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