StorageController.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Commodity;
  4. use App\CommodityMaterialBoxModel;
  5. use App\Components\AsyncResponse;
  6. use App\MaterialBox;
  7. use App\MaterialBoxCommodity;
  8. use App\MaterialBoxModel;
  9. use App\Owner;
  10. use App\Services\LogService;
  11. use App\Station;
  12. use App\StationTask;
  13. use App\StationTaskMaterialBox;
  14. use App\StoreItem;
  15. use App\TaskTransaction;
  16. use Illuminate\Database\Eloquent\Builder;
  17. use Illuminate\Foundation\Auth\AuthenticatesUsers;
  18. use Illuminate\Support\Collection;
  19. use Illuminate\Support\Facades\Auth;
  20. use Illuminate\Support\Facades\DB;
  21. use Illuminate\Support\Facades\Gate;
  22. use Illuminate\Support\Facades\Validator;
  23. class StorageController extends Controller
  24. {
  25. use AsyncResponse;
  26. use AuthenticatesUsers;
  27. public function putShelf()
  28. {
  29. $this->error("停用缓存架上架,联系管理员开启");
  30. $this->gate("入库管理-入库-缓存架入库");
  31. $asn = \request("asn");
  32. $ide = \request("ide");
  33. $barCode = \request("barCode");
  34. $amount = (int)\request("amount");
  35. //check info
  36. if (!$asn || !$ide || !$barCode || !$amount)$this->error("信息不完整");
  37. $box = MaterialBox::query()->with("station")->where("code",$ide)->first();
  38. if (!$box)$this->error("WAS无此料箱");
  39. if (!$box->station)$this->error("WAS无此库位信息");
  40. if (!app("StationService")->isCacheShelfLocation($box->station))$this->error("非缓存架库位");
  41. $fromLocation = $box->station->code; //源库位
  42. $item = StoreItem::query()->whereHas("store",function (Builder $query){
  43. $query->where("asn_code",request("asn"));
  44. })->whereHas("commodity",function (Builder $query)use($barCode){
  45. $query->whereHas("barcodes",function (Builder $query)use($barCode){
  46. $query->where("code",$barCode);
  47. });
  48. })->first();
  49. if (!$item)$this->error("WAS无此ASN单信息");
  50. //get flux
  51. $tasks = app("StorageService")->getFluxTask($asn,$barCode,$amount);
  52. if (!$tasks)$this->error("该单无上架任务或不存在");
  53. //此处嵌套三层事务 以最高层级为准
  54. DB::beginTransaction(); //总体事务 回滚WAS错误操作
  55. try{
  56. //库存记录
  57. if (!app("StorageService")->enterWarehouse( $box->id, $item->commodity_id, $amount, $box->material_box_model_id))$this->error("库存异常");
  58. DB::connection("oracle")->transaction(function ()use($tasks,$ide){ //单体嵌套事务 回滚FLUX失败任务
  59. foreach ($tasks as $task)if (!app("StorageService")->fluxPA($task,$ide)){
  60. DB::connection("oracle")->rollBack();
  61. $this->error("FLUX上架失败");
  62. };
  63. });
  64. DB::commit();
  65. }catch (\Exception $e){
  66. DB::rollBack();
  67. $this->error($e->getMessage());
  68. }
  69. //亮灯
  70. app("CacheShelfService")->lightUp($fromLocation,'1','0',["detail01"=>$ide,"qty01"=>$amount]);
  71. $maximum = app("CommodityMaterialBoxModelService")->getMaximum($box->material_box_model_id,$item->commodity_id);
  72. $this->success(["model" => $box->material_box_model_id,"commodity" => $item->commodity_id, "maximum" => $maximum]);
  73. }
  74. public function setMaximum()
  75. {
  76. app("CommodityMaterialBoxModelService")->setMaximum(request("model"),request("commodity"),request("maximum"));
  77. $this->success();
  78. }
  79. /**
  80. * 检查最大限值并返回
  81. *
  82. */
  83. public function checkMaximum()
  84. {
  85. $item = app("StoreItemService")->getMaxAvailableDetail(request("asn"),request("barCode"));
  86. if (!$item)$this->error("无此单据记录");
  87. $models = CommodityMaterialBoxModel::query()->where("commodity_id",$item->commodity_id)->get();
  88. if ($models->count()==0)$this->success(["material_box_model_id"=>null]);
  89. $map = [];
  90. foreach ($models as $model)$map[$model->material_box_model_id] = $model;
  91. $this->getMaterBoxModel($item,$map);
  92. }
  93. /**
  94. * 检查ASN可上架总数
  95. */
  96. public function checkAsnAmount()
  97. {
  98. $sql = <<<sql
  99. SELECT sum(fmqty) amount FROM DOC_ASN_DETAILS LEFT JOIN BAS_SKU ON DOC_ASN_DETAILS.CUSTOMERID = BAS_SKU.CUSTOMERID AND DOC_ASN_DETAILS.SKU = BAS_SKU.SKU
  100. LEFT JOIN TSK_TASKLISTS ON DOC_ASN_DETAILS.ASNNO = TSK_TASKLISTS.DOCNO AND DOC_ASN_DETAILS.ASNLINENO = TSK_TASKLISTS.DOCLINENO
  101. WHERE ASNNO = ? AND (ALTERNATE_SKU1 = ? OR ALTERNATE_SKU2 = ? OR ALTERNATE_SKU3 = ?)
  102. AND TASKPROCESS = '00' AND TASKTYPE = 'PA'
  103. sql;
  104. $task = DB::connection("oracle")->selectOne(DB::raw($sql),[request("asn"),request("barCode"),request("barCode"),request("barCode")]);
  105. $this->success($task->amount ?? 0);
  106. }
  107. /**
  108. * 重置缓存架指定格口
  109. */
  110. public function resetCacheShelf()
  111. {
  112. $this->gate("入库管理-入库-缓存架入库");
  113. $boxes = request("boxes");
  114. //清理任务
  115. $data = '';
  116. //剔除准备执行任务但没有真正开始执行的待定库位
  117. $occupy = Station::query()->select("id")->whereIn("code",$boxes)->where("status",1)->get();
  118. foreach ($occupy as $item){
  119. unset($boxes[array_search($item->code,$boxes)]);
  120. $data .= '“'.$item->code.'”,';
  121. }
  122. if ($occupy->count()>0){
  123. $data .= "存在任务待处理,无法调取 ";
  124. $boxes = array_values($boxes);
  125. }
  126. //剔除存在任务的库位
  127. $tasks = StationTaskMaterialBox::query()->with("station:id,code")
  128. ->whereIn("station_id",Station::query()->select("id")->whereIn("code",$boxes))
  129. ->whereNotIn("status",["完成","取消"])->get();
  130. foreach ($tasks as $task){
  131. unset($boxes[array_search($task->station->code,$boxes)]);
  132. $data .= '“'.$task->station->code.'”,';
  133. };
  134. if ($tasks->count()>0){
  135. $data .= "任务排队中,无法调取";
  136. $boxes = array_values($boxes);
  137. }
  138. //重新调取料箱
  139. $result = app("ForeignHaiRoboticsService")->paddingCacheShelf(Station::query()->whereIn("code",$boxes)->get());
  140. if ($result===null)$this->error("任务下发错误,检查日志");
  141. if ($result===false)$this->error("已无可用料箱,部分库位填充失败");
  142. $this->success(["data"=>$data,"boxes"=>$boxes]);
  143. }
  144. /**
  145. * 取得料箱
  146. */
  147. public function acquireBox()
  148. {
  149. $this->gate("入库管理-入库-半箱补货入库");
  150. $boxId = request("material_box_id");
  151. $modelId = request("material_box_model_id");
  152. if (!$modelId)$this->error("商品未设定库存上限");
  153. //获取目标库位
  154. $station = app("StationService")->getMirrorMappingLocation(request("station"));
  155. if (!$station)$this->error("未知库位");
  156. $isAvailable = app("StationService")->isAvailable($station);
  157. if (!$isAvailable)$this->error("库存被占用或存在任务未处理");
  158. $amount = app("StorageService")->checkPutAmount(request("asn"),request("barCode"));
  159. if ($amount<request("amount"))$this->error("待上架数量不足,最大可上数量为{$amount}");
  160. //发起取箱任务
  161. $exe = function ($boxId)use($station){
  162. DB::beginTransaction();
  163. $collection = new Collection();
  164. $task = StationTask::query()->create([
  165. 'status' => "待处理",
  166. 'station_id' => $station->id,
  167. ]);
  168. $collection->add(StationTaskMaterialBox::query()->create([
  169. 'station_id' => $station->id,
  170. 'material_box_id'=>$boxId,
  171. 'status'=>"待处理",
  172. 'type' => '取',
  173. 'station_task_id' => $task->id,
  174. ]));
  175. if (!app("ForeignHaiRoboticsService")->fetchGroup($station->code,$collection,'','立架出至缓存架'))$this->error("呼叫机器人失败");
  176. //生成临时任务事务
  177. TaskTransaction::query()->create([
  178. "doc_code" => request("asn"),
  179. "bar_code" => request("barCode"),
  180. "fm_station_id" => $station->id,
  181. "material_box_id" => $boxId,
  182. "commodity_id" => request("commodity_id"),
  183. "amount" => request("amount"),
  184. "type" => "入库",
  185. "user_id" => Auth::id(),
  186. "mark" => 1
  187. ]);
  188. DB::commit();
  189. //亮灯
  190. app("CacheShelfService")->lightUp($station->code,'2','1');
  191. app("StationService")->locationOccupy($station->code);//占用库位
  192. };
  193. if ($boxId && app("MaterialBoxService")->checkUsableBox($boxId))$this->success($exe($boxId));
  194. $item = app("StoreItemService")->getMaxAvailableDetail(request("asn"),request("barCode"));
  195. if (!$item)$this->error("无此单据记录");
  196. $models = app("MaterialBoxModelService")->getModelSortedByOwner($item->store->owner_id);
  197. $models->load(["commodity"=>function($query)use($item){
  198. $query->where("commodity_id",$item->commodity_id);
  199. }]);
  200. //获取料箱
  201. if ($boxId){
  202. $blacklist = [$boxId];
  203. $boxId = null;
  204. //料箱存在且不可用
  205. /** @var \Illuminate\Database\Eloquent\Collection $models */
  206. foreach ($models as $model){
  207. if (!$model->commodity)continue;
  208. //料箱不可用寻找新料箱
  209. $result = app("StorageService")->getHalfBoxLocation($model->commodity,$item,request("asn"),$blacklist);
  210. while ($result){
  211. //料箱可用并且数量符合本次半箱数量 跳出
  212. if (app("MaterialBoxService")->checkUsableBox($result->material_box_id)
  213. && $model->maximum-$result->amount>=request("amount"))$this->success($exe($result->material_box_id));
  214. else $blacklist[] = $result->material_box_id;
  215. //否则黑名单此料箱继续查找 直至料箱为空
  216. $result = app("StorageService")->getHalfBoxLocation($model->commodity,$item,request("asn"),$blacklist);
  217. }
  218. }
  219. }
  220. //料箱不存在且该商品有过入库记录 拿取空箱
  221. if (!$modelId){
  222. $box = null;
  223. foreach ($models as $model){
  224. if (!$model->commodity)continue;
  225. $box = app("MaterialBoxService")->getAnEmptyBox($model);
  226. if($box)break;
  227. }
  228. }else $box = app("MaterialBoxService")->getAnEmptyBox(MaterialBoxModel::query()->find($modelId));
  229. if (!$box)$this->error("无可用料箱");
  230. $this->success($exe($box->id));
  231. }
  232. /**
  233. * 溢出校正
  234. */
  235. public function overflowRevision()
  236. {
  237. $this->gate("入库管理-入库-半箱补货入库");
  238. $station = request("station");
  239. $amount = request("amount");
  240. //获取目标库位
  241. $station = app("StationService")->getMirrorMappingLocation($station);
  242. if (!$station)$this->error("未知库位");
  243. $task = TaskTransaction::query()->with("materialBox")->where("fm_station_id",$station->id)->where("amount",">",$amount)
  244. ->where("type","入库")->where("mark",1)->where("status",0)->first();
  245. if (!$task)$this->error("无任务存在");
  246. $task->update(["amount" => DB::raw("amount - {$amount}")]);
  247. $storage = MaterialBoxCommodity::query()->where("material_box_id",$task->material_box_id)
  248. ->where("commodity_id",$task->commodity_id)->first();
  249. $maximum = (($storage->amount ?? 0)+$task->amount)-$amount;
  250. CommodityMaterialBoxModel::query()->where("material_box_model_id",$task->materialBox->material_box_model_id)
  251. ->where("commodity_id",$task->commodity_id)->update(["maximum"=>$maximum]);
  252. $this->success("校正成功");
  253. }
  254. public function syncStorage()
  255. {
  256. ini_set('max_execution_time', 0);
  257. $model = MaterialBoxModel::query()->create([
  258. "code" => "common"
  259. ]);
  260. $sql = <<<sql
  261. select * from INV_LOT_LOC_ID where traceid = '*' and locationid like 'IDE%'
  262. sql;
  263. DB::beginTransaction();
  264. foreach (DB::connection("oracle")->select(DB::raw($sql)) as $inv){
  265. $materialBox = MaterialBox::query()->firstOrCreate(["code"=>$inv->locationid],[
  266. "code" => $inv->locationid,
  267. "material_box_model_id"=>$model
  268. ]);
  269. $owner = Owner::query()->firstOrCreate([
  270. "code" => $inv->customerid
  271. ],[
  272. "code" => $inv->customerid,
  273. "name" => $inv->customerid,
  274. ]);
  275. $commodity = Commodity::query()->where("owner_id",$owner->id)->where("sku",$inv->sku)->first();
  276. $s = MaterialBoxCommodity::query()->where("material_box_id",$materialBox->id)
  277. ->where("commodity_id",$commodity->id)->first();
  278. if (!$s)MaterialBoxCommodity::query()->create([
  279. "material_box_id" => $materialBox->id,
  280. "commodity_id" => $commodity->id,
  281. "amount" => $inv->qty,
  282. ]);else $s->update(["amount" => $inv->qty]);
  283. }
  284. DB::commit();
  285. $this->success();
  286. }
  287. /**
  288. * 在安卓端的个体登录鉴权
  289. *
  290. */
  291. public function androidLogin()
  292. {
  293. $errors=Validator::make(request()->input(),[
  294. "name" => 'required|string',
  295. 'password' => 'required|string'])->errors();
  296. if($errors->count()>0){return ['success'=>false,'errors'=>$errors];}
  297. request()->offsetSet("remember",true);
  298. if (!$this->attemptLogin(request()))return ['success'=>false,'errors'=>['name'=>['登录信息验证失败']]];
  299. if (!Gate::allows("入库管理-入库-缓存架入库") && !Gate::allows("入库管理-入库-半箱补货入库"))return ['success'=>false,'errors'=>['name'=>['用户无权操作入库']]];
  300. return ['success'=>true,'url'=>url("store/inStorage/android.index")];
  301. }
  302. public function username(): string
  303. {
  304. return 'name';
  305. }
  306. /**
  307. * 库外箱绑定至库位
  308. */
  309. public function bindBox()
  310. {
  311. $location = request("location");
  312. $box = request("ide");
  313. if (!$location || !$box)$this->error("参数传递错误");
  314. $task = StationTaskMaterialBox::query()->select("id")->where(function ($query)use($location,$box){
  315. /** @var Builder $query */
  316. $query->whereHas("station",function ($query)use($location){
  317. /** @var Builder $query */
  318. $query->where("code",$location);
  319. })->orWhereHas("materialBox",function ($query)use($box){
  320. /** @var Builder $query */
  321. $query->where("code",$box);
  322. });
  323. })->whereNotIn("status",["完成","取消"])->first();
  324. if ($task)$this->error("库位或料箱存在任务待执行,无法放置料箱");
  325. $ks = DB::connection("mysql_haiRobotics")->table("ks_bin")->select(DB::raw("1"))
  326. ->where("ks_bin_code",$box)->where("status",4)->first();
  327. if (!$ks)$this->error("海柔料箱状态异常");
  328. DB::beginTransaction();
  329. try {
  330. $station = Station::query()->where("code",$location)->where("status",0)->first();
  331. $box = MaterialBox::query()->where("code",$box)->first();
  332. if (!$station || !$box)$this->error("库位或料箱未在WAS记录");
  333. $station->update(["material_box_id"=>$box->id]);
  334. DB::commit();
  335. $this->success();
  336. }catch (\Exception $e){
  337. DB::rollBack();
  338. $this->error($e->getMessage());
  339. }
  340. }
  341. public function bindModelIndex(){
  342. $models = MaterialBoxModel::query()->get();
  343. return view("store.inStorage.boxBindModel",compact("models"));
  344. }
  345. public function searchIde()
  346. {
  347. $ide = request("ide");
  348. $box = MaterialBox::query()->where("code",$ide)->first();
  349. if (!$box)$this->error("料箱不存在");
  350. $this->success($box->material_box_model_id);
  351. }
  352. public function boxBindModel()
  353. {
  354. $this->success(MaterialBox::query()->where("code",request("ide"))
  355. ->update(["material_box_model_id"=>request("material_box_model_id")]));
  356. }
  357. public function commodityBindModel()
  358. {
  359. $models = MaterialBoxModel::query()->get();
  360. return view("store.inStorage.commodityBindModel",compact("models"));
  361. }
  362. public function getModels()
  363. {
  364. $this->success(MaterialBoxModel::query()->select("id","code","description","maximum_kind")->get());
  365. }
  366. /**
  367. * 设定料箱最大
  368. */
  369. public function settingModelMaximum()
  370. {
  371. $insert = function ($commodityId){
  372. $in = [];
  373. $map = [];
  374. $ids = [];
  375. foreach (request("models") as $model){
  376. $insert[] = [
  377. "commodity_id" => $commodityId,
  378. "material_box_model_id" => $model["id"],
  379. "maximum" => $model["maximum"]
  380. ];
  381. $map[$model["id"]] = $model;
  382. $ids[] = $model["id"];
  383. }
  384. return array($in,$map,$ids);
  385. };
  386. if (request("commodityId")){
  387. list($in,$map,$ids) = $insert(request("commodityId"));
  388. if ($ids){
  389. $map = array_flip($ids);
  390. foreach (CommodityMaterialBoxModel::query()->whereIn("id",$ids)->lockForUpdate()->get() as $model){
  391. $index = $map[$model->id];
  392. if ($model->maximum != $in[$index]["maximum"])$model->update(["maximum"=>$in[$index]["maximum"]]);
  393. unset($in[$index]);
  394. }
  395. $in = array_values($in);
  396. }
  397. if ($in){
  398. LogService::log(__CLASS__,__METHOD__,json_encode($in));
  399. CommodityMaterialBoxModel::query()->insert($in);
  400. }
  401. $this->success();
  402. }
  403. $item = StoreItem::query()->whereHas("store",function (Builder $query){
  404. $query->where("asn_code",request("asn"));
  405. })->whereHas("commodity",function (Builder $query){
  406. $query->whereHas("barcodes",function (Builder $query){
  407. $query->where("code",request("barCode"));
  408. });
  409. })->first();
  410. if (!$item)$this->error("商品不存在");
  411. list($in,$map,$ids) = $insert($item->store->commodity_id);
  412. LogService::log(__CLASS__,__METHOD__,json_encode($in));
  413. CommodityMaterialBoxModel::query()->insert($in);
  414. $this->getMaterBoxModel($item,$map);
  415. }
  416. private function getMaterBoxModel($item,$map)
  417. {
  418. $models = app("MaterialBoxModelService")->getModelSortedByOwner($item->store->owner_id);
  419. foreach ($models as $model){
  420. if (!isset($map[$model->id]))continue;
  421. $result = app("StorageService")->getHalfBoxLocation($map[$model->id],$item,$item->store->asn_code);
  422. if (!$result)continue;
  423. $result->maximum = $model->maximum-$result->amount;
  424. $this->success($result);
  425. }
  426. $this->success(["need"=>$models[0]->maximum,"material_box_model_id"=>$models[0]->material_box_model_id,"commodity_id"=>$item->commodity_id]);
  427. }
  428. /**
  429. * 根据条码检索商品
  430. */
  431. public function searchBarCode()
  432. {
  433. $commodities = Commodity::query()->whereHas("barcodes",function (Builder $query){
  434. $query->where("code",request("barCode"));
  435. })->get();
  436. if (!$commodities->count())$this->error("库内无此商品信息");
  437. if ($commodities->count()>1)$commodities->load("owner");
  438. $this->success($commodities);
  439. }
  440. }