CacheShelfTaskJob.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. <?php
  2. namespace App\Jobs;
  3. use App\Components\ErrorPush;
  4. use App\Services\ForeignHaiRoboticsService;
  5. use App\Services\LogService;
  6. use App\Station;
  7. use App\StationTaskMaterialBox;
  8. use App\TaskTransaction;
  9. use Illuminate\Bus\Queueable;
  10. use Illuminate\Contracts\Queue\ShouldQueue;
  11. use Illuminate\Database\Eloquent\Builder;
  12. use Illuminate\Foundation\Bus\Dispatchable;
  13. use Illuminate\Queue\InteractsWithQueue;
  14. use Illuminate\Support\Collection;
  15. use Illuminate\Support\Facades\Cache;
  16. use Illuminate\Support\Facades\DB;
  17. use Illuminate\Support\Facades\Log;
  18. class CacheShelfTaskJob implements ShouldQueue
  19. {
  20. use Dispatchable, InteractsWithQueue, Queueable, ErrorPush;
  21. protected $key;
  22. protected $count;
  23. /**
  24. * Create a new job instance.
  25. *
  26. * @return void
  27. */
  28. public function __construct(string $key,int $count)
  29. {
  30. $this->count = $count;
  31. $this->key = $key;
  32. }
  33. /**
  34. * Execute the job.
  35. *
  36. * @return void
  37. * @throws
  38. */
  39. public function handle()
  40. {
  41. /** @var ForeignHaiRoboticsService $service */
  42. $service = app("ForeignHaiRoboticsService");
  43. switch ($this->key){
  44. case "CACHE_SHELF_AVAILABLE"://缓存架释放呼叫
  45. //等待一定时间来合并同类请求至此
  46. $available = Cache::get($this->key,0);
  47. Log::debug("队列事务1",["当前数量:{$this->count}","缓存数量:$available"]);
  48. if ($this->count!==$available)return;
  49. Cache::forget($this->key); //无论是否开始分发 都清除本次缓存架的计数器
  50. //获取可用缓存架
  51. $stations = app("StationService")->getCacheShelf(true);
  52. Log::debug("队列事务2",["可用缓存架:{$stations->count()}"]);
  53. if ($stations->count()==0)break;
  54. LogService::log("海柔任务","队列事务分发",$stations->toJson());
  55. //检查事务 尝试分发任务 改变下方序列来控制分发顺序 逐级分发 一次成功就终止
  56. if ($this->dispatchOutTask($stations,$service))break; //首先尝试向出库事务分发 分发成功跳出
  57. if ($this->dispatchInTask($stations,$service))break; //尝试向入库事务分发
  58. break;
  59. default://入库呼叫
  60. if (!Cache::has($this->key))return;
  61. /** @var Collection $task */
  62. list($task,$location) = Cache::get($this->key);
  63. if ($this->count!==$task->count())return;
  64. $dataToPost = $service->makeJson_move_multi($task, '缓存架入立架', $location);
  65. $controlSuccess = $service->controlHaiRobot($dataToPost,$task,'缓存架入立架');
  66. $tIds = [];
  67. $task->each(function ($t)use(&$tIds){$tIds[] = $t->id;});
  68. StationTaskMaterialBox::query()->whereIn("id",$tIds)
  69. ->where("status","待处理")->update(['status' => $controlSuccess ? '处理中' : '异常']);
  70. Cache::forget($this->key);
  71. //if ($controlSuccess)$this->materialBoxMappingCacheShelf($task,$location);
  72. }
  73. }
  74. /**
  75. * 料箱映射缓存架,因为建立的入立架任务源库位是立库,无法获取真实源库位,所以在此拿到映射库位
  76. * 在料箱被取走时通过任务料箱号获取对应库位,来标记该缓存架库位可以被执行任务了 StationTaskMaterialBoxService:markHasTaken
  77. * 出库会启用库位占用逻辑 入库分为:人工入库与系统自动入库 人工控制入库由人工自己辨识库位可用度,而系统入库只能通过此映射来拿到可用库位信息
  78. *
  79. * @param Collection $task
  80. * @param Collection $location
  81. *
  82. * @return void
  83. */
  84. public function materialBoxMappingCacheShelf(Collection $task,Collection $location)
  85. {
  86. $map = Cache::get("CACHE_SHELF_MAPPING",function (){return [];});
  87. foreach ($task as $key=>$obj)$map[$obj->material_box_id] = $location[$key];
  88. Cache::forever("CACHE_SHELF_MAPPING",$map);
  89. }
  90. /**
  91. * 分发出库任务
  92. *
  93. * @param $stations
  94. * @param $service
  95. * @return bool
  96. */
  97. private function dispatchOutTask(&$stations,$service):bool
  98. {
  99. DB::beginTransaction();
  100. try {
  101. $tasks = TaskTransaction::query()->selectRaw("task_id,GROUP_CONCAT(id) AS ids,id")->with("task")
  102. ->where("type","出库")->whereHas("task",function ($query){
  103. $query->where("status","待处理");
  104. })->where("status",3)->lockForUpdate()
  105. ->where("mark",2)->groupBy("task_id")->get(); //检索等待的队列事务来获取对应任务
  106. Log::debug("队列事务3",["队列出库任务:{$tasks->count()}"]);
  107. if ($tasks->count()==0)return false;
  108. if ($this->dispatchTask($tasks,$stations,$service,function ($obj,$stationId,$time,&$updateTransaction){
  109. if ($obj->ids!=$obj->id){
  110. $ids = explode(",",$obj->ids);
  111. foreach ($ids as $id)$updateTransaction[] = ["id"=>$id,"to_station_id"=>$stationId,"status"=>0,"updated_at"=>$time];
  112. }else $updateTransaction[] = ["id"=>$obj->id,"to_station_id"=>$stationId,"status"=>0,"updated_at"=>$time];
  113. },function ($service,$toLocation,$task,$prefix){
  114. return $service->fetchGroup_multiLocation($toLocation,$task,$prefix,'立架出至缓存架',20,false);
  115. },"to_station_id")){DB::commit();return $stations->count()==0;} //缓存架用完 跳出,否则接着分发
  116. DB::rollBack();
  117. }catch (\Exception $e){
  118. DB::rollBack();
  119. $this->push(__METHOD__."->".__LINE__,"出库队列执行错误",$e->getMessage()." | 当前任务数:".$this->count." | 缓存信息:".(isset($available) ? json_encode($available) : ''));
  120. }
  121. return false;
  122. }
  123. /**
  124. * 分发入库任务
  125. *
  126. * @param $stations
  127. * @param $service
  128. * @return bool
  129. */
  130. private function dispatchInTask(&$stations,$service):bool
  131. {
  132. DB::beginTransaction();
  133. try {
  134. $tasks = TaskTransaction::query()->with("task")
  135. ->where("type","入库")->whereHas("task",function ($query){
  136. $query->where("status","待处理");
  137. })->where("status",3)->lockForUpdate()
  138. ->where("mark",1)->get(); //检索等待的队列事务来获取对应任务
  139. Log::debug("队列事务3",["队列入库任务:{$tasks->count()}"]);
  140. if ($tasks->count()==0)return false;
  141. if ($this->dispatchTask($tasks,$stations,$service,function ($obj,$stationId,$time,&$updateTransaction){
  142. $updateTransaction[] = ["id"=>$obj->id,"fm_station_id"=>$stationId,"status"=>0,"updated_at"=>$time];
  143. },function ($service,$toLocation,$task,$prefix){
  144. return $service->fetchGroup_multiLocation($toLocation,$task,'','立架出至缓存架',20,false);
  145. },"fm_station_id")){
  146. DB::commit();return $stations->count()==0; //缓存架用完 跳出,否则接着分发
  147. }
  148. DB::rollBack();
  149. }catch (\Exception $e){
  150. DB::rollBack();
  151. $this->push(__METHOD__."->".__LINE__,"入库队列执行错误",$e->getMessage()." | 当前任务数:".$this->count." | 缓存信息:".(isset($available) ? json_encode($available) : ''));
  152. }
  153. return false;
  154. }
  155. private function dispatchTask(\Illuminate\Database\Eloquent\Collection $tasks,&$stations, $service,
  156. \Closure $update, \Closure $execute, string $stationName):bool
  157. {
  158. $locations = $stations;
  159. if ($tasks->count()>$locations->count())$tasks = $tasks->slice(0,$locations->count());//事务过多切割部分处理
  160. if ($tasks->count()<$locations->count()){
  161. $stations = $stations->slice($tasks->count());
  162. $stations = $stations->values($stations);
  163. }
  164. $toLocation = collect();
  165. $task = collect();
  166. $updateTask = [["id","station_id","updated_at"]];
  167. $updateTransaction = [["id",$stationName,"status","updated_at"]];
  168. $time = date("Y-m-d H:i:s");
  169. $map = [];
  170. foreach ($tasks as $index=>$obj){
  171. $toLocation->push($stations[$index]->code);
  172. $map[$stations[$index]->code] = $stations[$index]->id;
  173. $obj->task->station_id = $stations[$index]->id;
  174. $task->push($obj->task);
  175. $updateTask[] = ["id"=>$obj->task->id,"station_id"=>$stations[$index]->id,"updated_at"=>$time];
  176. $update($obj,$stations[$index]->id,$time,$updateTransaction);
  177. }
  178. app("BatchUpdateService")->batchUpdate("station_task_material_boxes",$updateTask);
  179. app("BatchUpdateService")->batchUpdate("task_transactions",$updateTransaction);
  180. if ($execute($service,$toLocation,$task,$tasks[0]->station_task_batch_id)){
  181. foreach ($toLocation as $value){
  182. app("CacheShelfService")->lightUp($value,'3','0',["title"=>"机器人取箱中,禁止操作"]);
  183. Cache::forever("CACHE_SHELF_OCCUPANCY_{$map[$value]}",true);
  184. }
  185. app("StationService")->locationOccupyMulti($toLocation->toArray());
  186. DB::commit();
  187. return true;
  188. }
  189. DB::rollBack();
  190. $this->push(__METHOD__."->".__LINE__,"缓存队列执行错误","库位信息:".json_encode($toLocation)." 任务信息:".json_encode($task));
  191. return false;
  192. }
  193. }