StorageController.php 20 KB

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