StorageService.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. <?php
  2. namespace App\Services;
  3. use App\CommodityMaterialBoxModel;
  4. use App\Station;
  5. use App\StationTask;
  6. use App\StationTaskMaterialBox;
  7. use App\TaskTransaction;
  8. use App\Traits\ServiceAppAop;
  9. use App\Storage;
  10. use App\ValueStore;
  11. use Illuminate\Database\Eloquent\Model;
  12. use Illuminate\Support\Collection;
  13. use Illuminate\Support\Facades\Auth;
  14. use Illuminate\Support\Facades\DB;
  15. class StorageService
  16. {
  17. use ServiceAppAop;
  18. protected $modelClass=Storage::class;
  19. /**
  20. * 填充缓存架
  21. *
  22. * @param \Illuminate\Database\Eloquent\Collection $stations
  23. */
  24. public function paddingCacheShelf($stations)
  25. {
  26. $collection = new Collection();
  27. $stationCollection = new Collection();
  28. $blacklist = [];
  29. foreach ($stations as $station){
  30. $box = app("MaterialBoxService")->getAnEmptyBox($blacklist);
  31. if (!$box)continue;
  32. $task = StationTask::query()->create([
  33. 'status' => "待处理",
  34. 'station_id' => $station->id,
  35. ]);
  36. $collection->add(StationTaskMaterialBox::query()->create([
  37. 'station_id' => $station->id,
  38. 'material_box_id'=>$box->id,
  39. 'status'=>"待处理",
  40. 'type' => '取',
  41. 'station_task_id' => $task->id,
  42. ]));
  43. $stationCollection->add($station->code);
  44. $blacklist[] = $box->id;
  45. }
  46. app("ForeignHaiRoboticsService")->fetchGroup_multiLocation($stationCollection,$collection,'','立架出至缓存架');
  47. }
  48. /**
  49. * 缓存架放置记录
  50. *
  51. * @param StationTaskMaterialBox|\stdClass $stationTaskMaterialBox
  52. */
  53. public function putCacheShelf($stationTaskMaterialBox)
  54. {
  55. DB::beginTransaction();
  56. try{
  57. $storage = Storage::query()->where("material_box_id",$stationTaskMaterialBox->material_box_id)->lockForUpdate()->first();
  58. if ($storage)$storage->update(["station_id"=>$stationTaskMaterialBox->station_id,'status'=>0]);
  59. else Storage::query()->create([
  60. "station_id" => $stationTaskMaterialBox->station_id,
  61. "material_box_id" => $stationTaskMaterialBox->material_box_id,
  62. ]);
  63. DB::commit();
  64. }catch (\Exception $e){
  65. DB::rollBack();
  66. }
  67. }
  68. /**
  69. * 释放库位占用
  70. *
  71. * @param StationTaskMaterialBox|\stdClass $stationTaskMaterialBox
  72. */
  73. public function releaseOccupation($stationTaskMaterialBox)
  74. {
  75. if ($stationTaskMaterialBox->station->station_type_id != 5)return;
  76. $storage = Storage::query()->where("material_box_id",$stationTaskMaterialBox->material_box_id)->first();
  77. if (!$storage)return;
  78. $update = [];
  79. if ($storage->status == 1)$update["status"] = 0;
  80. if ($storage->station_id)$update["station_id"] = null;
  81. if ($update)$storage->update($update);
  82. }
  83. /**
  84. * 检查临时事务标记处理一些特殊情况
  85. *
  86. * @param StationTaskMaterialBox|\stdClass $stationTaskMaterialBox
  87. */
  88. public function checkMark($stationTaskMaterialBox)
  89. {
  90. $task = TaskTransaction::query()->where("material_box_id",$stationTaskMaterialBox->material_box_id)
  91. ->where("status",0)->first();
  92. if (!$task)return;
  93. //蓝灯闪烁
  94. if ($task->type == '入库' && $task->mark == 1)app("CacheShelfService")->stationLightUp($stationTaskMaterialBox->station->code,null,'2','2');
  95. }
  96. /**
  97. * 检查存储 根据事务表做处理
  98. *
  99. * @param Station|\stdClass $station
  100. *
  101. * @return bool
  102. *
  103. * @throws
  104. */
  105. public function checkStorage($station)
  106. {
  107. $task = TaskTransaction::query()->with("materialBox")->where("fm_station_id",$station->id)
  108. ->where("status",0)->first();
  109. if (!$task)return true;
  110. //建立入库任务,通知入库,完善库存
  111. if ($task->type == '入库' && $task->mark == 1){
  112. DB::beginTransaction();
  113. try{
  114. //get flux
  115. $asns = app("StorageService")->getFluxTask($task->doc_code,$task->bar_code,$task->amount);
  116. if (!$asns)return false;
  117. $ide = $task->materialBox->code;
  118. DB::connection("oracle")->beginTransaction();
  119. try{
  120. foreach ($asns as $asn)if (!$this->fluxPA($asn,$ide,(int)$asn->fmqty)){
  121. DB::connection("oracle")->rollBack();
  122. return false;
  123. };
  124. DB::connection("oracle")->commit();
  125. }catch(\Exception $e){
  126. DB::connection("oracle")->rollBack();
  127. return false;
  128. }
  129. $taskMaterialBox = $this->createWarehousingTask($station->id,$task->material_box_id);//建立入库任务
  130. if (!$this->enterWarehouse($station->id,$task->material_box_id,$task->commodity_id,$task->amount))throw new \Exception("库存异常"); //处理库存
  131. $task->update([
  132. "task_id" => $taskMaterialBox->id,
  133. "status" => 1,
  134. "user_id" => Auth::id(),
  135. ]);//标记事务完成
  136. $collection = new Collection([$taskMaterialBox]);
  137. app("ForeignHaiRoboticsService")->fetchGroup($station->code,$collection,'','缓存架入立架'); //呼叫机器人入库
  138. DB::commit();
  139. return true;
  140. }catch(\Exception $e){
  141. DB::rollBack();
  142. return false;
  143. }
  144. }
  145. return true;
  146. }
  147. /**
  148. * 建立入库任务
  149. *
  150. * @param $stationId
  151. * @param $boxId
  152. *
  153. * @return Model|\stdClass
  154. */
  155. public function createWarehousingTask($stationId,$boxId)
  156. {
  157. /** @var StationTask|\stdClass $task */
  158. $task = StationTask::query()->create([
  159. 'status' => "待处理",
  160. 'station_id' => $stationId,
  161. ]);
  162. return StationTaskMaterialBox::query()->create([
  163. 'station_id' => $stationId,
  164. 'material_box_id'=>$boxId,
  165. 'status'=>"待处理",
  166. 'type' => '放',
  167. 'station_task_id' => $task->id,
  168. ]);
  169. }
  170. /**
  171. * 库存入库
  172. *
  173. * @param integer $stationId
  174. * @param integer $boxId
  175. * @param integer $commodityId
  176. * @param integer $amount
  177. * @param integer $modelId
  178. *
  179. * @return bool
  180. */
  181. public function enterWarehouse($stationId, $boxId, $commodityId, $amount, $modelId = null)
  182. {
  183. DB::beginTransaction();
  184. try{
  185. $storage = Storage::query()->where("material_box_id",$boxId)->lockForUpdate()->first();
  186. $obj = [
  187. "station_id" => $stationId,
  188. "material_box_id" => $boxId,
  189. "commodity_id" => $commodityId,
  190. "amount" => $amount,
  191. "status" => 1,
  192. ];
  193. if ($storage){
  194. $obj["amount"] = DB::raw("amount+{$amount}");
  195. $storage->update($obj);
  196. $amount = (int)$storage->amount + (int)$amount;
  197. } else Storage::query()->create($obj);
  198. if ($commodityId && $modelId){
  199. //维护料箱最大上限 用于半箱补货
  200. $model = CommodityMaterialBoxModel::query()->select("maximum")->where("commodity_id",$commodityId)
  201. ->where("material_box_model_id",$modelId)->first();
  202. if (!$model)CommodityMaterialBoxModel::query()->create(["commodity_id"=>$commodityId,"material_box_model_id"=>$modelId,"maximum"=>$amount]);
  203. if ($model && $model->maximum < $amount)$model->update(["maximum"=>$amount]);
  204. }
  205. DB::commit();
  206. return true;
  207. }catch(\Exception $e){
  208. DB::rollBack();
  209. return false;
  210. }
  211. }
  212. /**
  213. * 获取FLUX上架任务列表
  214. *
  215. * @param string $asn
  216. * @param string $barCode
  217. * @param int $amount
  218. *
  219. * @return array|null
  220. */
  221. public function getFluxTask($asn,$barCode,$amount):?array
  222. {
  223. $sql = <<<sql
  224. SELECT * FROM DOC_ASN_DETAILS LEFT JOIN BAS_SKU ON DOC_ASN_DETAILS.CUSTOMERID = BAS_SKU.CUSTOMERID AND DOC_ASN_DETAILS.SKU = BAS_SKU.SKU
  225. LEFT JOIN TSK_TASKLISTS ON DOC_ASN_DETAILS.ASNNO = TSK_TASKLISTS.DOCNO AND DOC_ASN_DETAILS.ASNLINENO = TSK_TASKLISTS.DOCLINENO
  226. WHERE ASNNO = ? AND (ALTERNATE_SKU1 = ? OR ALTERNATE_SKU2 = ? OR ALTERNATE_SKU3 = ?) AND RECEIVEDQTY >= ?
  227. AND TASKPROCESS = '00' AND TASKTYPE = 'PA'
  228. sql;
  229. $asns = DB::connection("oracle")->select(DB::raw($sql),[$asn,$barCode,$barCode,$barCode,$amount]);
  230. if (!$asns)return null;
  231. $nums = [];
  232. foreach ($asns as $index=>$asn){
  233. if ((int)$asn->fmqty == $amount)return [$asn];
  234. $nums[] = (int)$asn->fmqty;
  235. }
  236. $result = $this->twoSum($nums,$amount);
  237. if ($result)return [$asns[$result[0]],$asns[$result[1]]];
  238. return null;
  239. }
  240. /**
  241. * 获取匹配数字
  242. *
  243. * @param Integer[] $nums
  244. * @param Integer $target
  245. * @return Integer[]|null
  246. */
  247. protected function twoSum($nums, $target) {
  248. $map=[];
  249. for($i=0;$i<count($nums);$i++){
  250. $complement=$target-$nums[$i];
  251. if(array_key_exists($complement,$map)){
  252. return [$map[$complement],$i];
  253. }
  254. $map[$nums[$i]]=$i;
  255. }
  256. return null;
  257. }
  258. /**
  259. * flux上架
  260. *
  261. * @param $asn
  262. * @param $ide
  263. * @param $amount
  264. * @return bool
  265. * @throws \Throwable
  266. */
  267. public function fluxPA($asn,$ide,$amount)
  268. {
  269. if (!$asn->taskid)return false;//ASN单无此入库信息,禁止上架
  270. $sql = <<<sql
  271. SELECT * FROM inv_lot_loc_id WHERE lotnum = ? AND traceid = ? AND customerid= ? and sku = ?
  272. sql;
  273. $inv = DB::connection("oracle")->select(DB::raw($sql),[$asn->fmlotnum,$asn->plantoid,$asn->customerid,$asn->sku]);
  274. if (count($inv)==0)return false;//余量与入库不符
  275. DB::connection("oracle")->transaction(function ()use($inv,$amount,$ide,$asn,&$who){
  276. $db = DB::connection("oracle");
  277. $qty = $amount;
  278. foreach ($inv as $in){
  279. if ($qty==0)break;
  280. if ($in->qty > $qty){
  281. $db->update(DB::raw("update inv_lot_loc_id set qty = qty-?,qtymvout = qty-? where lotnum = ? and locationid = ? and traceid = ?"),[
  282. $qty,$qty,$in->lotnum,$in->locationid,$in->traceid
  283. ]);//TODO 遗留问题:对应生成分配库位上架数量未被变更
  284. $in->qty = $in->qty-$qty;
  285. $qty = 0;
  286. }else{
  287. $db->delete(DB::raw("DELETE FROM inv_lot_loc_id WHERE lotnum = ? and locationid = ? and traceid = ?"),[
  288. $in->lotnum,$in->locationid,$in->traceid
  289. ]);
  290. $qty = $qty-$in->qty;
  291. }
  292. }
  293. $db->delete(DB::raw("DELETE FROM inv_lot_loc_id WHERE lotnum = ? AND traceid = ? AND traceid != '*' AND qty = 0"),[
  294. $inv[0]->lotnum,$inv[0]->traceid
  295. ]);
  296. $invHistory = $db->selectOne(DB::raw("SELECT * FROM inv_lot_loc_id WHERE lotnum = ? AND locationid = ? AND customerid = ? AND sku = ? AND traceid = '*' FOR UPDATE"),[
  297. $inv[0]->lotnum,$ide,$inv[0]->customerid,$inv[0]->sku
  298. ]);
  299. $who = 'WAS'.(Auth::user() ? '-'.Auth::user()["name"] : '');
  300. if ($invHistory)$db->update(DB::raw("UPDATE inv_lot_loc_id SET qty = qty+? WHERE lotnum = ? AND locationid = ? AND traceid = '*'"),[
  301. (int)$amount,$inv[0]->lotnum,$ide
  302. ]);
  303. else $db->insert(DB::raw("INSERT INTO inv_lot_loc_id VALUES(?,?,'*',?,?,?,0,0,0,0,0,0,TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),?,TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),?,0,0,0,0,0,'*',0,null)"),[
  304. $inv[0]->lotnum,$ide,$inv[0]->customerid,$inv[0]->sku,$amount,date("Y-m-d H:i:s"),$who,
  305. date("Y-m-d H:i:s"),$who
  306. ]);
  307. $sql = <<<sql
  308. INSERT INTO ACT_TRANSACTION_LOG VALUES(?,'PA',?,?,?,?,'ASN',?,?,?,?,?,?,?,?,TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),?,
  309. TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),?,0,0,0,0,TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),?,?,null,null,null,'*',?,?,?,?,?,?,?,
  310. ?,?,?,?,?,'N',null,?,?,?,?,?,?,?,null,null)
  311. sql;
  312. list($trid,$max) = $this->getTrNumber();
  313. $db->insert(DB::raw($sql),[
  314. $trid,$asn->customerid,$asn->sku,
  315. $asn->asnno,$asn->asnlineno,$inv[0]->lotnum,$asn->fmlocation,$asn->plantoid,$asn->packid,$asn->uom,$amount,$amount,'99',date("Y-m-d H:i:s"),$who,
  316. date("Y-m-d H:i:s"),$who,date("Y-m-d H:i:s"),$asn->customerid,$asn->sku,$ide,$who,$asn->packid,$asn->uom,$amount,$amount,$inv[0]->lotnum,
  317. '*','0','N','*',$asn->taskid_sequence,$asn->warehouseid,$asn->userdefine1,$asn->userdefine2,
  318. $asn->userdefine3,$asn->userdefine4,$asn->userdefine5,'O'
  319. ]);
  320. $this->setTrNumber($max);
  321. $sql = <<<sql
  322. update TSK_TASKLISTS set TASKPROCESS = '99',REASONCODE = 'OK',PLANTOLOCATION = ?,PLANLOGICALTOSEQUENCE = ?,
  323. CREATE_TRANSACTIONID = ?,OPENWHO = ?,OPENTIME = TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),
  324. CLOSEWHO = ?,CLOSETIME = ?,EDITTIME = ?,EDITWHO = ?
  325. where taskid = ? AND TASKID_SEQUENCE = ?
  326. sql;
  327. $db->update(DB::raw($sql),[
  328. $ide,$ide,$trid,$who,date("Y-m-d H:i:s"),$who,date("Y-m-d H:i:s"),date("Y-m-d H:i:s"),$who,$asn->taskid,$asn->taskid_sequence
  329. ]);
  330. });
  331. //成功后应去修改ASN状态及数量 暂时不知上架后ASN应为状态
  332. /* $sql = <<<sql
  333. UPDATE doc_asn_details SET linestatus = ?,edittime = TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),editwho = ? WHERE asnno = ? AND asnlineno = ?
  334. sql;*/
  335. //if ($asn->expectedqty>$asn->receivedqty && $asn->linestatus!='30')DB::connection("oracle")->update(DB::raw($sql),['30',date("Y-m-d H:i:s"),$who,$asn->asnno,$asn->asnlineno]);
  336. if ($asn->expectedqty==$asn->receivedqty && $asn->linestatus=='40'){
  337. //DB::connection("oracle")->update(DB::raw($sql),['40',date("Y-m-d H:i:s"),$who,$asn->asnno,$asn->asnlineno]);
  338. $check = DB::connection("oracle")->selectOne(DB::raw("SELECT 1 FROM DOC_ASN_DETAILS WHERE ASNNO = ? AND LINESTATUS != '40'"),[$asn->asnno]);
  339. if (!$check){
  340. $logs = DB::connection("oracle")->select(DB::raw("SELECT SUM(FMQTY) qty,TRANSACTIONTYPE FROM ACT_TRANSACTION_LOG WHERE DOCNO = ? AND TRANSACTIONTYPE IN ('PA','IN') GROUP BY TRANSACTIONTYPE"),[$asn->asnno]);
  341. $paQty = 0;
  342. $inQty = 0;
  343. foreach ($logs as $log){
  344. if ($log->transactiontype == 'IN')$inQty = $log->qty;
  345. else $paQty = $log->qty;
  346. }
  347. if ($paQty == $inQty){
  348. DB::connection("oracle")->update(DB::raw("UPDATE DOC_ASN_HEADER SET asnstatus = '99',edittime = TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),editwho = ? WHERE asnno = ?"),
  349. [date("Y-m-d H:i:s"),$who,$asn->asnno]);
  350. DB::connection("oracle")->update(DB::raw("UPDATE DOC_ASN_DETAILS SET linestatus = '99',edittime = TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),editwho = ? WHERE asnno = ?"),
  351. [date("Y-m-d H:i:s"),$who,$asn->asnno]);
  352. }
  353. }
  354. }
  355. return true;
  356. }
  357. /**
  358. * put cache rack box to warehousing(将缓存架料箱入库)
  359. *
  360. * @param string $fromLocation
  361. * @param integer $boxId
  362. *
  363. * @return int
  364. */
  365. public function putWareHousing(string $fromLocation, $boxId):?int
  366. {
  367. $station = Station::query()->select("id")
  368. ->where("station_type_id",5)->where("code",$fromLocation)->first();
  369. if (!$station)return null;
  370. if (StationTask::query()->select("id")->where("status","!=",'完成')->where("station_id",$station->id)->first())return null;
  371. /** @var StationTaskMaterialBox|\stdClass $stmb */
  372. $stmb = $this->createWarehousingTask($station->id,$boxId);
  373. return $stmb->id;
  374. }
  375. /**
  376. * 获取事务现号
  377. *
  378. * @return array
  379. */
  380. private function getTrNumber()
  381. {
  382. $val = ValueStore::query()->select("value")->where("name","flux_tr_number")->first();
  383. if (!$val)$val = ValueStore::query()->create(["name"=>"flux_tr_number","value"=>'0']);
  384. $max = $val->value+1;
  385. $number = sprintf("%09d", $max);
  386. return array('W'.$number,$max);
  387. }
  388. /**
  389. * 设置事务现号
  390. *
  391. * @param integer $max
  392. */
  393. private function setTrNumber($max)
  394. {
  395. ValueStore::query()->select("value")->where("name","flux_tr_number")->update(["value"=>(string)((int)$max+1)]);
  396. }
  397. /**
  398. * 入库
  399. *
  400. * @param integer $boxId
  401. * @param integer $amount
  402. * @param integer $commodityId
  403. *
  404. * @return bool
  405. */
  406. public function warehousing($boxId, $amount, $commodityId = null):bool
  407. {
  408. DB::beginTransaction();
  409. try{
  410. $storage = Storage::query()->where("material_box_id",$boxId)->lockForUpdate()->first();
  411. if (!$storage && !$commodityId)return false;
  412. if (!$storage){
  413. Storage::query()->create([
  414. "station_id" => null,
  415. "material_box_id" => $boxId,
  416. "commodity_id" => $commodityId,
  417. "amount" => $amount,
  418. ]);
  419. return true;
  420. }
  421. if ($commodityId && $storage->commodity_id && $storage->commodity_id!=$commodityId)return false;
  422. $obj = [
  423. "station_id" => null,
  424. "amount" => DB::raw("amount + {$amount}"),
  425. ];
  426. if (!$storage->commodity_id && $commodityId)$obj["commodity_id"] = $commodityId;
  427. $storage->update($obj);
  428. DB::commit();
  429. return true;
  430. }catch (\Exception $e){
  431. DB::rollBack();
  432. return false;
  433. }
  434. }
  435. /**
  436. * 出库
  437. *
  438. * @param integer $boxId
  439. * @param integer $amount
  440. * @param integer $commodityId
  441. *
  442. * @return bool
  443. */
  444. public function outWarehousing($boxId, $amount, $commodityId = null):bool
  445. {
  446. DB::beginTransaction();
  447. try{
  448. $storage = Storage::query()->where("material_box_id",$boxId)->lockForUpdate()->first();
  449. if (!$storage)return false;
  450. if ($commodityId && $storage->commodity_id && $storage->commodity_id!=$commodityId)return false;
  451. $obj = [
  452. "station_id" => null,
  453. "amount" => DB::raw("amount - {$amount}"),
  454. ];
  455. if (!$storage->commodity_id && $commodityId)$obj["commodity_id"] = $commodityId;
  456. $storage->update($obj);
  457. DB::commit();
  458. return true;
  459. }catch (\Exception $e){
  460. DB::rollBack();
  461. return false;
  462. }
  463. }
  464. }