CacheShelfTaskJob.php 9.1 KB

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