StorageService.php 19 KB

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