StationTaskMaterialBoxService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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()->orderByRaw("commodity_id,amount")//同商品多条 数量最小优先
  104. ->with('orderBin')->whereIn('order_id',$order_ids)->get();
  105. //$orderCommodities=$this->orderCommodityService->correctLocation_fromWMS($orderCommodities);
  106. if($orderCommodities->isEmpty())return $stationMaterialBoxes_toCreate;
  107. $stationType=$this->stationTypeService->getForMaterialBox_onBatchProcess();
  108. $stationTaskBatch=$this->stationTaskBatchService->get(['batch_id'=>$batch['id']])->first();
  109. $materialBoxIds_used=[];
  110. //$orderCommodities=$orderCommodities->sortBy('commodity_id');//按商品排序后,出货可以同商品挨在一起
  111. foreach ($orderCommodities as $orderCommodity){
  112. $station=$this->stationService->getStation_byType($stationType['name']);
  113. $materialBox=$this->materialBoxService->firstOrCreate(['code' => $orderCommodity['location']]);
  114. if(in_array($materialBox['id'],$materialBoxIds_used))continue;
  115. $stationMaterialBoxes_toCreate->push([
  116. 'station_id'=>$station['id'],
  117. 'material_box_id'=>$materialBox['id'],
  118. 'station_task_batch_id'=>$stationTaskBatch['id'],
  119. 'status'=>'待处理'
  120. ]);
  121. $materialBoxIds_used[]=$materialBox['id'];
  122. }
  123. return $this->insert($stationMaterialBoxes_toCreate->toArray(),true);
  124. }
  125. function get(array $kvPairs, $with=null){
  126. ksort($kvPairs);
  127. return Cache::remember('StationTaskMaterialBox'.md5(json_encode($kvPairs).json_encode([$with])), config('cache.expirations.fastChange'), function ()use($kvPairs,$with) {
  128. $query = StationTaskMaterialBox::query();
  129. if($with){
  130. $query->with($with);
  131. }
  132. foreach ($kvPairs as $column => $value){
  133. if (is_array($value))$query->whereIn($column,$value);
  134. else $query->where($column,$value);
  135. }
  136. return $query->get();
  137. });
  138. }
  139. function markHasPut(StationTaskMaterialBox $stationTaskMaterialBox){
  140. $this->instant($this->stationTaskBatchService,'StationTaskBatchService');
  141. $this->instant($this->stationTaskCommodityService,'StationTaskCommodityService');
  142. $this->instant($this->stationTaskService,'StationTaskService');
  143. $this->instant($this->stationService,'StationService');
  144. $this->instant($this->cacheShelfService,'CacheShelfService');
  145. $this->instant($this->storageService,'StorageService');
  146. try{
  147. LogService::log('海柔请求','markHasTaken1','');
  148. $taskType=$this->getServingTaskType($stationTaskMaterialBox);
  149. LogService::log('海柔请求','markHasTaken2',
  150. json_encode($taskType));
  151. switch ($taskType){
  152. case '分波次':
  153. $this->markProcessing($stationTaskMaterialBox);
  154. $this->stationTaskBatchService->markProcessing_byIds($stationTaskMaterialBox['station_task_batch_id']);
  155. $this->stationTaskCommodityService->markProcessing($stationTaskMaterialBox['stationTaskCommodities']);
  156. $this->stationTaskService->markProcessing_byIds(data_get($stationTaskMaterialBox['stationTaskCommodities'],'*.station_task_id'));
  157. /** @var StationTask $stationTask */
  158. $stationTask = $this->stationTaskService->getProcessing();
  159. $this->stationService->broadcastBinMonitor($stationTaskMaterialBox['station_id'], $stationTask);
  160. $stationTaskMaterialBox->materialBox['status']='在U型线';
  161. $stationTaskMaterialBox->materialBox->update();
  162. break;
  163. case '入立库':
  164. $this->cacheShelfService->putStationTaskMaterialBoxProcess($stationTaskMaterialBox);
  165. $stationTaskMaterialBox->materialBox['status']='在立库';
  166. $stationTaskMaterialBox->materialBox->update();
  167. $stationTaskMaterialBox->loadMissing("station"); //提前加载站,后续都需要站信息来处理
  168. $this->storageService->releaseOccupation($stationTaskMaterialBox); //释放库位占用
  169. $this->storageService->checkMark($stationTaskMaterialBox); //检查标记并做一些特殊处理
  170. break;
  171. case '入缓存架':
  172. $stationTaskMaterialBox->materialBox['status']='在缓存架';
  173. $stationTaskMaterialBox->materialBox->update();
  174. $this->storageService->putCacheShelf($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. // TODO 料箱处理
  197. function markHasTaken($stationTaskMaterialBox)
  198. {
  199. //TODO: 标记 料箱位置(需要其字段存在)$stationTaskMaterialBox['materialBox']['position']
  200. $this->instant($this->cacheShelfService,'CacheShelfService');
  201. // 料箱从缓存架上拿走
  202. if($stationTaskMaterialBox['station']['stationType']['name']=='缓存架'
  203. &&$stationTaskMaterialBox['type']=='取'){
  204. $stationTaskMaterialBox['status'] = '完成';
  205. $result = $this->cacheShelfService->lightOffTask($stationTaskMaterialBox['station']['code'],0);
  206. if($result['success'])
  207. $this->markProcessed($stationTaskMaterialBox);
  208. }
  209. }
  210. function processNextQueued(?StationTaskMaterialBox $stationTaskMaterialBox_lastProcessed){
  211. $station_id=$stationTaskMaterialBox_lastProcessed['station_id'];
  212. $stationTaskMaterialBox_next=StationTaskMaterialBox::query()
  213. ->where('station_id',$station_id)
  214. ->where('status','处理队列')
  215. ->orderBy('updated_at')
  216. ->first();
  217. if($stationTaskMaterialBox_next){
  218. $stationTaskMaterialBox_next->update(['status'=>'处理中']);
  219. }
  220. return $stationTaskMaterialBox_next;
  221. }
  222. function markProcessed(StationTaskMaterialBox $stationTaskMaterialBox){
  223. $stationTaskMaterialBox['status'] = '完成';
  224. $stationTaskMaterialBox->save();
  225. }
  226. function getNotProcessedSiblings($stationTaskMaterialBox){
  227. return StationTaskMaterialBox::query()
  228. ->whereNotIn('status',['完成'])
  229. ->where('station_task_id',$stationTaskMaterialBox['station_task_id'])
  230. ->get();
  231. }
  232. /**
  233. * 每波次仅将最老的作务标为“处理中”,其他置入队列;
  234. * 如某波次已经有“处理中“,则他部置入队列
  235. * @param $stationTaskMaterialBox_orBoxes ?? 单个或多个
  236. */
  237. function markProcessing($stationTaskMaterialBox_orBoxes)
  238. {
  239. $this->instant($this->stationTaskService,'StationTaskService');
  240. $stationTaskMaterialBoxes =
  241. (function()use($stationTaskMaterialBox_orBoxes){
  242. if (get_class($stationTaskMaterialBox_orBoxes)==StationTaskMaterialBox::class){
  243. return collect([$stationTaskMaterialBox_orBoxes]);
  244. }
  245. return collect($stationTaskMaterialBox_orBoxes);
  246. })();
  247. $stationTaskMaterialBoxes_grouped=
  248. ($按时间从前往后排出顺序=function ()use(&$stationTaskMaterialBoxes){
  249. return $stationTaskMaterialBoxes
  250. ->sortBy('id')
  251. ->groupBy('station_task_batch_id');
  252. })();
  253. $stationTaskMaterialBoxes_grouped->each(function(&$groupByBatch){
  254. ($将所有要标记的箱任务先放在队列里=function()use(&$groupByBatch){
  255. $groupByBatch->each(function (&$stationTaskMaterialBox){
  256. $stationTaskMaterialBox['status']='处理队列';
  257. });
  258. })();
  259. ($如果之前没有处理中则标记第一个为处理目标,准备持久化=function()use(&$groupByBatch){
  260. $stationId=$groupByBatch[0]['station_id'];
  261. $processing=$this->getProcessing_byStationId($stationId);
  262. if(!$processing){
  263. $groupByBatch[0]['status']='处理中';
  264. $groupByBatch[0]->update();
  265. }else{
  266. foreach ($groupByBatch as &$stationTaskMaterialBox){
  267. if($stationTaskMaterialBox['id']==$processing['id']){
  268. $stationTaskMaterialBox['status']='处理中';
  269. }
  270. }
  271. }
  272. })();
  273. });
  274. ($持久化处理队列的记录=function()use(&$stationTaskMaterialBoxes_grouped){
  275. $toArray = $stationTaskMaterialBoxes_grouped->collapse();
  276. $toArray=$toArray->where('status','处理队列');
  277. $ids_toUpdate = data_get($toArray, '*.id');
  278. if(count($ids_toUpdate))
  279. StationTaskMaterialBox::query()->whereIn('id',$ids_toUpdate)->update(['status'=>'处理队列']);
  280. })();
  281. // StationTaskMaterialBox::query()
  282. // ->whereIn('id', data_get($stationTaskMaterialBoxes, '*.id'))
  283. // ->update(['status'=>'处理中']);
  284. $this->stationTaskService
  285. ->markProcessing_byIds(
  286. data_get($stationTaskMaterialBoxes, '*.*.station_id')
  287. );
  288. }
  289. function getProcessing_byStationId($stationId)
  290. {
  291. //这里不能用缓存,因为更新会非常快
  292. return StationTaskMaterialBox::query()
  293. ->where('station_id',$stationId)
  294. ->where('status','处理中')
  295. ->where('created_at','>',Carbon::now()->subDay())
  296. ->first();
  297. }
  298. function excepted($stationTaskMaterialBoxes_orBox){
  299. if (get_class($stationTaskMaterialBoxes_orBox)==StationTaskMaterialBox::class){
  300. $stationTaskMaterialBoxes_orBox = collect([$stationTaskMaterialBoxes_orBox]);
  301. }
  302. StationTaskMaterialBox::query()->whereIn('id',data_get($stationTaskMaterialBoxes_orBox,'*.id'))
  303. ->update(['status'=>'异常']);
  304. switch (get_class($stationTaskMaterialBoxes_orBox)){
  305. case MaterialBox::class:
  306. case StationTaskMaterialBox::class:
  307. throw new ErrorException('料箱异常'.json_encode($stationTaskMaterialBoxes_orBox->toJson()));
  308. }
  309. }
  310. function getServingTaskType(StationTaskMaterialBox $stationTaskMaterialBox): string
  311. {
  312. $stationTaskMaterialBox->load('station.stationType');
  313. if($isBatching=(
  314. $stationTaskMaterialBox['station_task_batch_id'] &&
  315. $stationTaskMaterialBox['station']['stationType']['name'] == '料箱监视器')
  316. ){
  317. return '分波次';
  318. }
  319. if($isPuttingBack=(
  320. $stationTaskMaterialBox['station']['stationType']['name'] == '立库')
  321. ){
  322. return '入立库';
  323. }
  324. if($isCacheShelf=(
  325. $stationTaskMaterialBox['station']['stationType']['name'] == '缓存架')
  326. ){
  327. return '入缓存架';
  328. }
  329. // if($isStoring=false){
  330. // return '入库';
  331. // }
  332. throw new ErrorException('当前类型找不到');
  333. }
  334. }