StorageService.php 19 KB

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