CacheShelfTaskJob.php 8.9 KB

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