StorageService.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  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\StoreItem;
  9. use App\TaskTransaction;
  10. use App\Traits\ServiceAppAop;
  11. use App\Storage;
  12. use App\ValueStore;
  13. use Illuminate\Database\Eloquent\Builder;
  14. use Illuminate\Database\Eloquent\Model;
  15. use Illuminate\Support\Collection;
  16. use Illuminate\Support\Facades\Auth;
  17. use Illuminate\Support\Facades\DB;
  18. use Illuminate\Support\Str;
  19. class StorageService
  20. {
  21. use ServiceAppAop;
  22. protected $modelClass=Storage::class;
  23. /**
  24. * 填充缓存架
  25. *
  26. * @param \Illuminate\Database\Eloquent\Collection $stations
  27. */
  28. public function paddingCacheShelf($stations)
  29. {
  30. $collection = new Collection();
  31. $stationCollection = new Collection();
  32. $blacklist = [];
  33. foreach ($stations as $station){
  34. $box = app("MaterialBoxService")->getAnEmptyBox($blacklist);
  35. if (!$box)continue;
  36. $task = StationTask::query()->create([
  37. 'status' => "待处理",
  38. 'station_id' => $station->id,
  39. ]);
  40. $collection->add(StationTaskMaterialBox::query()->create([
  41. 'station_id' => $station->id,
  42. 'material_box_id'=>$box->id,
  43. 'status'=>"待处理",
  44. 'type' => '取',
  45. 'station_task_id' => $task->id,
  46. ]));
  47. $stationCollection->add($station->code);
  48. $blacklist[] = $box->id;
  49. }
  50. app("ForeignHaiRoboticsService")->fetchGroup_multiLocation($stationCollection,$collection,'','立架出至缓存架');
  51. }
  52. /**
  53. * 缓存架放置记录
  54. *
  55. * @param StationTaskMaterialBox|\stdClass $stationTaskMaterialBox
  56. */
  57. public function putCacheShelf($stationTaskMaterialBox)
  58. {
  59. DB::beginTransaction();
  60. try{
  61. $storage = Storage::query()->where("material_box_id",$stationTaskMaterialBox->material_box_id)->lockForUpdate()->first();
  62. if ($storage)$storage->update(["station_id"=>$stationTaskMaterialBox->station_id,'status'=>0]);
  63. else Storage::query()->create([
  64. "station_id" => $stationTaskMaterialBox->station_id,
  65. "material_box_id" => $stationTaskMaterialBox->material_box_id,
  66. ]);
  67. $stationTaskMaterialBox->loadMissing("station");
  68. //清理原有任务
  69. app("StorageService")->clearTask([$stationTaskMaterialBox->station->code]);
  70. DB::commit();
  71. }catch (\Exception $e){
  72. DB::rollBack();
  73. }
  74. }
  75. /**
  76. * 释放库位占用
  77. *
  78. * @param StationTaskMaterialBox|\stdClass $stationTaskMaterialBox
  79. */
  80. public function releaseOccupation($stationTaskMaterialBox)
  81. {
  82. if ($stationTaskMaterialBox->station->station_type_id != 5)return;
  83. $storage = Storage::query()->where("material_box_id",$stationTaskMaterialBox->material_box_id)->first();
  84. if (!$storage)return;
  85. $update = [];
  86. if ($storage->status == 1)$update["status"] = 0;
  87. if ($storage->station_id)$update["station_id"] = null;
  88. if ($update)$storage->update($update);
  89. }
  90. /**
  91. * 检查临时事务标记处理一些特殊情况
  92. *
  93. * @param StationTaskMaterialBox|\stdClass $stationTaskMaterialBox
  94. */
  95. public function checkMark($stationTaskMaterialBox)
  96. {
  97. $task = TaskTransaction::query()->where("material_box_id",$stationTaskMaterialBox->material_box_id)
  98. ->where("status",0)->first();
  99. if (!$task)return;
  100. //蓝灯闪烁
  101. if ($task->type == '入库' && $task->mark == 1)app("CacheShelfService")->stationLightUp($stationTaskMaterialBox->station->code,null,'2','2');
  102. }
  103. /**
  104. * 检查存储 根据事务表做处理
  105. *
  106. * @param Station|\stdClass $station
  107. *
  108. * @return bool
  109. *
  110. * @throws
  111. */
  112. public function checkStorage(Station $station)
  113. {
  114. $task = TaskTransaction::query()->with("materialBox")->where("fm_station_id",$station->id)
  115. ->where("status",0)->first();
  116. if (!$task)return true;
  117. //建立入库任务,通知入库,完善库存
  118. if ($task->type == '入库' && $task->mark == 1){
  119. DB::beginTransaction();
  120. try{
  121. //get flux
  122. $asns = $this->getFluxTask($task->doc_code,$task->bar_code,$task->amount);
  123. if (!$asns)return false;
  124. $ide = $task->materialBox->code;
  125. DB::connection("oracle")->beginTransaction();
  126. try{
  127. foreach ($asns as $asn)if (!$this->fluxPA($asn,$ide,(int)$asn->fmqty)){
  128. DB::connection("oracle")->rollBack();
  129. return false;
  130. };
  131. }catch(\Exception $e){
  132. DB::connection("oracle")->rollBack();
  133. return false;
  134. }
  135. $taskMaterialBox = $this->createWarehousingTask($station->id,$task->material_box_id);//建立入库任务
  136. if (!$this->enterWarehouse($station->id,$task->material_box_id,$task->commodity_id,$task->amount))throw new \Exception("库存异常"); //处理库存
  137. $task->update([
  138. "task_id" => $taskMaterialBox->id,
  139. "status" => 1,
  140. "user_id" => Auth::id(),
  141. ]);//标记事务完成
  142. $collection = new Collection([$taskMaterialBox]);
  143. app("ForeignHaiRoboticsService")->fetchGroup($station->code,$collection,'','缓存架入立架'); //呼叫机器人入库
  144. DB::commit();
  145. DB::connection("oracle")->commit();
  146. return true;
  147. }catch(\Exception $e){
  148. DB::rollBack();
  149. DB::connection("oracle")->rollBack();
  150. return false;
  151. }
  152. }
  153. return true;
  154. }
  155. /**
  156. * 建立入库任务
  157. *
  158. * @param $stationId
  159. * @param $boxId
  160. *
  161. * @return StationTaskMaterialBox|\stdClass|Model
  162. */
  163. public function createWarehousingTask($stationId,$boxId)
  164. {
  165. /** @var StationTask|\stdClass $task */
  166. $task = StationTask::query()->create([
  167. 'status' => "待处理",
  168. 'station_id' => $stationId,
  169. ]);
  170. return StationTaskMaterialBox::query()->create([
  171. 'station_id' => $stationId,
  172. 'material_box_id'=>$boxId,
  173. 'status'=>"待处理",
  174. 'type' => '放',
  175. 'station_task_id' => $task->id,
  176. ]);
  177. }
  178. /**
  179. * 库存入库
  180. *
  181. * @param integer $stationId
  182. * @param integer $boxId
  183. * @param integer $commodityId
  184. * @param integer $amount
  185. * @param integer $modelId
  186. *
  187. * @return bool
  188. */
  189. public function enterWarehouse($stationId, $boxId, $commodityId, $amount, $modelId = null)
  190. {
  191. DB::beginTransaction();
  192. try{
  193. $storage = Storage::query()->where("material_box_id",$boxId)->lockForUpdate()->first();
  194. $obj = [
  195. "station_id" => $stationId,
  196. "material_box_id" => $boxId,
  197. "commodity_id" => $commodityId,
  198. "amount" => $amount,
  199. "status" => 1,
  200. ];
  201. if ($storage){
  202. $amountTemp = (int)$storage->amount + (int)$amount;
  203. $obj["amount"] = DB::raw("amount+{$amount}");
  204. $storage->update($obj);
  205. $amount = $amountTemp;
  206. } else Storage::query()->create($obj);
  207. if ($commodityId && $modelId){
  208. //维护料箱最大上限 用于半箱补货
  209. $model = CommodityMaterialBoxModel::query()->select("maximum")->where("commodity_id",$commodityId)
  210. ->where("material_box_model_id",$modelId)->first();
  211. if (!$model)CommodityMaterialBoxModel::query()->create(["commodity_id"=>$commodityId,"material_box_model_id"=>$modelId,"maximum"=>$amount]);
  212. if ($model && $model->maximum < $amount)$model->update(["maximum"=>$amount]);
  213. }
  214. DB::commit();
  215. LogService::log(__CLASS__,"库存增加",$storage->toJson()." | ".json_encode([$stationId, $boxId, $commodityId, $amount, $modelId]));
  216. return true;
  217. }catch(\Exception $e){
  218. DB::rollBack();
  219. return false;
  220. }
  221. }
  222. /**
  223. * 获取FLUX上架任务列表
  224. *
  225. * @param string $asn
  226. * @param string $barCode
  227. * @param int $amount
  228. *
  229. * @return array|null
  230. */
  231. public function getFluxTask(string $asn,string $barCode,int $amount):array
  232. {
  233. $sql = <<<sql
  234. SELECT TSK_TASKLISTS.* FROM DOC_ASN_DETAILS LEFT JOIN BAS_SKU ON DOC_ASN_DETAILS.CUSTOMERID = BAS_SKU.CUSTOMERID AND DOC_ASN_DETAILS.SKU = BAS_SKU.SKU
  235. LEFT JOIN TSK_TASKLISTS ON DOC_ASN_DETAILS.ASNNO = TSK_TASKLISTS.DOCNO AND DOC_ASN_DETAILS.ASNLINENO = TSK_TASKLISTS.DOCLINENO
  236. WHERE ASNNO = ? AND (ALTERNATE_SKU1 = ? OR ALTERNATE_SKU2 = ? OR ALTERNATE_SKU3 = ?) AND RECEIVEDQTY >= ?
  237. AND TASKPROCESS = '00' AND TASKTYPE = 'PA'
  238. sql;
  239. $tasks = DB::connection("oracle")->select(DB::raw($sql),[$asn,$barCode,$barCode,$barCode,$amount]);
  240. if (!$tasks)return [];
  241. $nums = [];
  242. $sum = 0;
  243. $maxIndex = null;
  244. foreach ($tasks as $i => $task){
  245. if ((int)$task->fmqty == $amount)return [$task];
  246. $nums[] = (int)$task->fmqty;
  247. $sum += (int)$task->fmqty;
  248. if ((int)$task->fmqty>$amount)$maxIndex = $i;
  249. }
  250. if ($sum<$amount)return []; //上架数大于入库数
  251. $result = $this->getMatch($nums,$amount);
  252. if (!$result)return $this->splitTask($tasks,$maxIndex,$amount);
  253. $arr = [];
  254. foreach ($result as $index)$arr[] = $tasks[$index];
  255. return $arr;
  256. }
  257. /**
  258. * 拆分任务
  259. * @param array $tasks
  260. * @param int|null $maxIndex
  261. * @param int $amount
  262. *
  263. * @return array
  264. */
  265. private function splitTask($tasks,$maxIndex,$amount):array
  266. {
  267. $result = [];
  268. if ($maxIndex===null){
  269. foreach ($tasks as $task){
  270. if ($amount>(int)$task->fmqty){
  271. $result[] = $task;
  272. $amount-=(int)$task->fmqty;
  273. }else $splitTarget = $task;
  274. }
  275. }else $splitTarget = $tasks[$maxIndex];
  276. $result[] = $this->copyTask($splitTarget,$amount);
  277. return $result;
  278. }
  279. /**
  280. * 值转换
  281. *
  282. * @param ?string $val
  283. *
  284. * @return ?string
  285. */
  286. private function valFormat($val):?string
  287. {
  288. if ($val!==null){
  289. $ret = date("Y-m-d H:i:s",strtotime($val))==$val;
  290. if ($ret)$val = "to_date('".$val."','yyyy-mm-dd hh24:mi:ss')";
  291. else $val = "'".$val."'";
  292. }else $val = "null";
  293. return $val;
  294. }
  295. /**
  296. * @param \stdClass $task
  297. * @param int $amount
  298. *
  299. * @return \stdClass
  300. *
  301. * @throws
  302. */
  303. private function copyTask($task,$amount)
  304. {
  305. DB::connection("oracle")->beginTransaction();
  306. try {
  307. $columns = '';
  308. $values = '';
  309. $seq = 0;
  310. foreach ($task as $key=>$val){
  311. if (Str::upper($key)=='TASKID_SEQUENCE') {
  312. $taskMax = DB::connection("oracle")->selectOne(DB::raw("select MAX(TASKID_SEQUENCE) maxseq from TSK_TASKLISTS where taskid = ?"),[$task->taskid]);
  313. $val = $taskMax->maxseq + 1;
  314. $seq = $val;
  315. }
  316. if (Str::upper($key)=='FMQTY' || Str::upper($key)=='FMQTY_EACH'
  317. || Str::upper($key)=='PLANTOQTY' || Str::upper($key)=='PLANTOQTY_EACH')$val = $amount;
  318. if (Str::upper($key)=='FMID')$val = "WAS".$val;
  319. $columns .= $key.",";
  320. $values .= $this->valFormat($val) .",";
  321. }
  322. $columns = mb_substr($columns,0,-1);
  323. $values = mb_substr($values,0,-1);
  324. $sql = <<<sql
  325. INSERT INTO TSK_TASKLISTS({$columns}) VALUES({$values})
  326. sql;
  327. DB::connection("oracle")->insert(DB::raw($sql));
  328. DB::connection("oracle")->update(DB::raw("UPDATE TSK_TASKLISTS SET FMQTY = FMQTY-?,FMQTY_EACH = FMQTY_EACH-?,PLANTOQTY=PLANTOQTY-?,PLANTOQTY_EACH=PLANTOQTY_EACH-? WHERE TASKID = ? AND TASKID_SEQUENCE = ?"),[
  329. $amount,$amount,$amount,$amount,$task->taskid,$task->taskid_sequence
  330. ]);
  331. $invs = DB::connection("oracle")->select(DB::raw("SELECT * FROM INV_LOT_LOC_ID WHERE LOTNUM = ? AND LOCATIONID IN (?,?) AND TRACEID = ?"),[
  332. $task->fmlotnum,$task->fmlocation,$task->plantolocation,$task->fmid
  333. ]);
  334. foreach ($invs as $inv){
  335. if ($inv->locationid==$task->fmlocation){
  336. $columns = '';
  337. $values = '';
  338. DB::connection("oracle")->update(DB::raw("UPDATE inv_lot_loc_id SET qty = qty-? WHERE lotnum = ? AND locationid = ? AND traceid = ?"),[
  339. $amount,$inv->lotnum,$inv->locationid,$inv->traceid
  340. ]);
  341. foreach ($inv as $key=>$val){
  342. if (Str::upper($key)=='TRACEID') $val = "WAS".$task->fmid;
  343. if (Str::upper($key)=='QTY') $val = $amount;
  344. $columns .= $key.",";
  345. $values .= $this->valFormat($val) .",";
  346. }
  347. $columns = mb_substr($columns,0,-1);
  348. $values = mb_substr($values,0,-1);
  349. DB::connection("oracle")->insert(DB::raw("INSERT INTO inv_lot_loc_id({$columns}) VALUES({$values})"));
  350. }
  351. if ($inv->locationid==$task->plantolocation){
  352. $columns = '';
  353. $values = '';
  354. DB::connection("oracle")->update(DB::raw("UPDATE inv_lot_loc_id SET QTYPA = QTYPA-? WHERE lotnum = ? AND locationid = ? AND traceid = ?"),[
  355. $amount,$inv->lotnum,$inv->locationid,$inv->traceid
  356. ]);
  357. foreach ($inv as $key=>$val){
  358. if (Str::upper($key)=='TRACEID') $val = "WAS".$task->fmid;
  359. if (Str::upper($key)=='QTYPA') $val = $amount;
  360. $columns .= $key.",";
  361. $values .= $this->valFormat($val) .",";
  362. }
  363. $columns = mb_substr($columns,0,-1);
  364. $values = mb_substr($values,0,-1);
  365. DB::connection("oracle")->insert(DB::raw("INSERT INTO inv_lot_loc_id({$columns}) VALUES({$values})"));
  366. }
  367. }
  368. DB::connection("oracle")->commit();
  369. }catch(\Exception $e) {
  370. DB::connection("oracle")->rollBack();
  371. throw new \Exception("拆分任务失败:".$e->getMessage());
  372. }
  373. return DB::connection("oracle")->selectOne(DB::raw("SELECT * FROM TSK_TASKLISTS WHERE TASKID = ? AND TASKID_SEQUENCE = ?"),[$task->taskid,$seq]);
  374. }
  375. /**
  376. * 获取匹配数字
  377. *
  378. * @param Integer[] $nums
  379. * @param Integer $target
  380. * @return Integer[]|null
  381. */
  382. protected function getMatch(array $nums,int $target) :?array
  383. {
  384. $map=[];
  385. foreach ($nums as $index=>$val){
  386. $complement=$target-$val;
  387. if(array_key_exists($complement,$map))return [$map[$complement],$index];
  388. if ($val==$target)return [$index];
  389. $map[$val]=$index;
  390. if ($val<$target){
  391. $temp = $nums;
  392. unset($temp[$index]);
  393. $arr = $this->getMatch($temp,$target-$val);
  394. if ($arr) {
  395. $arr[] = $index;
  396. return $arr;
  397. }
  398. }
  399. }
  400. return null;
  401. }
  402. /**
  403. * 将任务在flux上架
  404. *
  405. * @param $asn
  406. * @param $ide
  407. * @param $amount
  408. * @return bool
  409. * @throws \Throwable
  410. */
  411. public function fluxPA($asn,$ide,$amount)
  412. {
  413. if (!$asn->taskid)return false;//ASN单无此入库信息,禁止上架
  414. $sql = <<<sql
  415. SELECT * FROM inv_lot_loc_id WHERE lotnum = ? AND traceid = ? AND customerid= ? and sku = ? and qty = {$amount}
  416. sql;
  417. $inv = DB::connection("oracle")->selectOne(DB::raw($sql),[$asn->fmlotnum,$asn->plantoid,$asn->customerid,$asn->sku]);
  418. if (!$inv)return false;//余量与入库不符
  419. DB::connection("oracle")->transaction(function ()use($inv,$amount,$ide,$asn,&$who){
  420. $db = DB::connection("oracle");
  421. $db->delete(DB::raw("DELETE FROM inv_lot_loc_id WHERE lotnum = ? AND traceid = ? AND traceid != '*' AND qty = 0"),[
  422. $inv->lotnum,$inv->traceid
  423. ]);
  424. $invHistory = $db->selectOne(DB::raw("SELECT * FROM inv_lot_loc_id WHERE lotnum = ? AND locationid = ? AND customerid = ? AND sku = ? AND traceid = '*' FOR UPDATE"),[
  425. $inv->lotnum,$ide,$inv->customerid,$inv->sku
  426. ]);
  427. $who = 'WAS'.(Auth::user() ? '-'.Auth::user()["name"] : '');
  428. if ($invHistory)$db->update(DB::raw("UPDATE inv_lot_loc_id SET qty = qty+? WHERE lotnum = ? AND locationid = ? AND traceid = '*'"),[
  429. (int)$amount,$inv->lotnum,$ide
  430. ]);
  431. 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)"),[
  432. $inv->lotnum,$ide,$inv->customerid,$inv->sku,$amount,date("Y-m-d H:i:s"),$who,
  433. date("Y-m-d H:i:s"),$who
  434. ]);
  435. $sql = <<<sql
  436. INSERT INTO ACT_TRANSACTION_LOG VALUES(?,'PA',?,?,?,?,'ASN',?,?,?,?,?,?,?,?,TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),?,
  437. TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),?,0,0,0,0,TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),?,?,null,null,null,'*',?,?,?,?,?,?,?,
  438. ?,?,?,?,?,'N',null,?,?,?,?,?,?,?,null,null)
  439. sql;
  440. list($trid,$max) = $this->getTrNumber();
  441. $db->insert(DB::raw($sql),[
  442. $trid,$asn->customerid,$asn->sku,
  443. $asn->asnno,$asn->asnlineno,$inv->lotnum,$asn->fmlocation,$asn->plantoid,$asn->packid,$asn->uom,$amount,$amount,'99',date("Y-m-d H:i:s"),$who,
  444. 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->lotnum,
  445. '*','0','N','*',$asn->taskid_sequence,$asn->warehouseid,$asn->userdefine1,$asn->userdefine2,
  446. $asn->userdefine3,$asn->userdefine4,$asn->userdefine5,'O'
  447. ]);
  448. $this->setTrNumber($max);
  449. $sql = <<<sql
  450. update TSK_TASKLISTS set TASKPROCESS = '99',REASONCODE = 'OK',PLANTOLOCATION = ?,PLANLOGICALTOSEQUENCE = ?,FMID = '*'
  451. COMPLETED_TRANSACTIONID = ?,OPENWHO = ?,OPENTIME = TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),
  452. CLOSEWHO = ?,CLOSETIME = ?,EDITTIME = ?,EDITWHO = ?
  453. where taskid = ? AND TASKID_SEQUENCE = ?
  454. sql;
  455. $db->update(DB::raw($sql),[
  456. $ide,'0',$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
  457. ]);
  458. });
  459. if ($asn->expectedqty==$asn->receivedqty && $asn->linestatus=='40'){
  460. $check = DB::connection("oracle")->selectOne(DB::raw("SELECT 1 FROM DOC_ASN_DETAILS WHERE ASNNO = ? AND LINESTATUS != '40'"),[$asn->asnno]);
  461. if (!$check){
  462. $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]);
  463. $paQty = 0;
  464. $inQty = 0;
  465. foreach ($logs as $log){
  466. if ($log->transactiontype == 'IN')$inQty = $log->qty;
  467. else $paQty = $log->qty;
  468. }
  469. if ($paQty == $inQty){
  470. 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 = ?"),
  471. [date("Y-m-d H:i:s"),$who,$asn->asnno]);
  472. 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 = ?"),
  473. [date("Y-m-d H:i:s"),$who,$asn->asnno]);
  474. }
  475. }
  476. }
  477. return true;
  478. }
  479. /**
  480. * put cache rack box to warehousing(将缓存架料箱入库)
  481. *
  482. * @param string $fromLocation
  483. * @param integer $boxId
  484. *
  485. * @return int
  486. */
  487. public function putWareHousing(string $fromLocation, $boxId):?int
  488. {
  489. $station = Station::query()->select("id")
  490. ->where("station_type_id",5)->where("code",$fromLocation)->first();
  491. if (!$station)return null;
  492. if (StationTask::query()->select("id")->where("status","!=",'完成')->where("station_id",$station->id)->first())return null;
  493. /** @var StationTaskMaterialBox|\stdClass $stmb */
  494. $stmb = $this->createWarehousingTask($station->id,$boxId);
  495. return $stmb->id;
  496. }
  497. /**
  498. * 获取事务现号
  499. *
  500. * @return array
  501. */
  502. private function getTrNumber()
  503. {
  504. $val = ValueStore::query()->select("value")->where("name","flux_tr_number")->first();
  505. if (!$val)$val = ValueStore::query()->create(["name"=>"flux_tr_number","value"=>'0']);
  506. $max = $val->value+1;
  507. $number = sprintf("%09d", $max);
  508. return array('W'.$number,$max);
  509. }
  510. /**
  511. * 设置事务现号
  512. *
  513. * @param integer $max
  514. */
  515. private function setTrNumber($max)
  516. {
  517. ValueStore::query()->select("value")->where("name","flux_tr_number")->update(["value"=>(string)((int)$max+1)]);
  518. }
  519. /**
  520. * 入库
  521. *
  522. * @param integer $boxId
  523. * @param integer $amount
  524. * @param integer $commodityId
  525. *
  526. * @return bool
  527. */
  528. public function warehousing($boxId, $amount, $commodityId = null):bool
  529. {
  530. DB::beginTransaction();
  531. try{
  532. $storage = Storage::query()->where("material_box_id",$boxId)->lockForUpdate()->first();
  533. if (!$storage && !$commodityId)return false;
  534. if (!$storage){
  535. Storage::query()->create([
  536. "station_id" => null,
  537. "material_box_id" => $boxId,
  538. "commodity_id" => $commodityId,
  539. "amount" => $amount,
  540. ]);
  541. return true;
  542. }
  543. if ($commodityId && $storage->commodity_id && $storage->commodity_id!=$commodityId)return false;
  544. $obj = [
  545. "station_id" => null,
  546. "amount" => DB::raw("amount + {$amount}"),
  547. ];
  548. if (!$storage->commodity_id && $commodityId)$obj["commodity_id"] = $commodityId;
  549. $storage->update($obj);
  550. DB::commit();
  551. return true;
  552. }catch (\Exception $e){
  553. DB::rollBack();
  554. return false;
  555. }
  556. }
  557. /**
  558. * 出库
  559. *
  560. * @param integer $boxId
  561. * @param integer $amount
  562. * @param integer $commodityId
  563. *
  564. * @return bool
  565. */
  566. public function outWarehousing($boxId, $amount, $commodityId = null):bool
  567. {
  568. DB::beginTransaction();
  569. try{
  570. $storage = Storage::query()->where("material_box_id",$boxId)->lockForUpdate()->first();
  571. if (!$storage)return false;
  572. if ($commodityId && $storage->commodity_id && $storage->commodity_id!=$commodityId)return false;
  573. $obj = [
  574. "station_id" => null,
  575. "amount" => DB::raw("amount - {$amount}"),
  576. ];
  577. if (!$storage->commodity_id && $commodityId)$obj["commodity_id"] = $commodityId;
  578. $storage->update($obj);
  579. DB::commit();
  580. return true;
  581. }catch (\Exception $e){
  582. DB::rollBack();
  583. return false;
  584. }
  585. }
  586. /**
  587. * 清除任务
  588. *
  589. * @param array $stationCodes
  590. *
  591. */
  592. public function clearTask(array $stationCodes)
  593. {
  594. //清除海柔信息,标记料箱为出库
  595. DB::connection("mysql_haiRobotics")->table("ks_bin")->whereIn("ks_bin_space_code",$stationCodes)
  596. ->where("status",1)->update([
  597. "ks_bin_space_code" => null,"ks_bin_space_id"=>null,"orig_ks_bin_space_code"=>null,"orig_ks_bin_space_id"=>null,
  598. "status"=>4,
  599. ]);
  600. //WAS任务清除
  601. $station = Station::query()->select("id")->whereIn("code",$stationCodes);
  602. $task = StationTask::query()->select("id")->where("status","!=",'完成')->whereIn("station_id",$station);
  603. StationTaskMaterialBox::query()->where("status","!=",'完成')->whereIn("station_task_id",$task)->update([
  604. "status" => "完成"
  605. ]);
  606. StationTask::query()->where("status","!=",'完成')->whereIn("station_id",$station)->update([
  607. "status" => "完成"
  608. ]);
  609. Storage::query()->whereIn("station_id",$station)->update([
  610. "status" => 1,
  611. "station_id" => null,
  612. ]);
  613. }
  614. /**
  615. * 获取半箱库位库存信息
  616. *
  617. * @param CommodityMaterialBoxModel|\stdClass $model
  618. * @param StoreItem|\stdClass $item
  619. * @param string|null $asn
  620. *
  621. * @return ?Storage
  622. */
  623. public function getHalfBoxLocation(CommodityMaterialBoxModel $model,StoreItem $item,?string $asn = null,array $blacklist = []):?Storage
  624. {
  625. if (!$asn){
  626. $item->loadMissing("store");
  627. $asn = $item->store->asn_code;
  628. }
  629. $stationCodes = '';//拼接库位编码
  630. $map = [];//库位与库存映射
  631. //查询填充
  632. $query = Storage::query()->with("station")->whereHas("materialBox",function (Builder $query)use($model){
  633. $query->where("material_box_model_id",$model->material_box_model_id);
  634. })->where("commodity_id",$model->commodity_id)->where("amount","<",$model->maximum)
  635. ->where("status",0)->where(DB::raw("{$model->maximum}-amount"),">",0);
  636. if ($blacklist)$query->whereHas("materialBox",function (Builder $query)use($blacklist){
  637. $query->whereNotIn("id",$blacklist);
  638. });
  639. $query->get()->each(function ($storage)use(&$stationCodes,&$map){
  640. $stationCodes .= "'".$storage->station->code."',";
  641. $map[$storage->station->code] = $storage;
  642. });
  643. //不存在跳出
  644. if (!$stationCodes)return null;
  645. $stationCodes = mb_substr($stationCodes,0,-1);
  646. //查询对应asn detail
  647. $detail = DB::connection("oracle")->selectOne(DB::raw("SELECT * FROM DOC_ASN_DETAILS WHERE ASNNO = ? AND ASNLINENO = ?"),[
  648. $asn,$item->asn_line_code
  649. ]);
  650. if(!$detail)return null;
  651. $detail = get_object_vars($detail);
  652. //查询对应批次属性
  653. $lot = DB::connection("oracle")->selectOne(DB::raw("SELECT * FROM BAS_LOTID WHERE LOTID = (SELECT LOTID FROM BAS_SKU WHERE CUSTOMERID = ? AND SKU = ?)"),[
  654. $detail["customerid"],$detail["sku"]
  655. ]);
  656. if(!$lot)return null;
  657. //通过符合条件的批次号来查询 库存
  658. $lot = get_object_vars($lot);
  659. $sql = <<<sql
  660. SELECT * FROM INV_LOT_LOC_ID WHERE LOTNUM IN
  661. (SELECT LOTNUM FROM INV_LOT_ATT WHERE INV_LOT_ATT.CUSTOMERID = ? AND SKU = ?
  662. sql;
  663. //拼接可以合并的批次属性要求
  664. for ($i=1;$i<=8;$i++){
  665. if ($lot["lotkey0{$i}"]=='Y'){
  666. $val = $detail["lotatt0{$i}"] ? "'{$detail["lotatt0{$i}"]}'" : null;
  667. $sql .= " AND LOTATT0{$i} = $val";
  668. }
  669. }
  670. $sql .= ") AND LOCATIONID IN ({$stationCodes}) AND TRACEID = '*' AND {$model->maximum}-QTY > 0 ORDER BY {$model->maximum}-QTY";
  671. $res = DB::connection("oracle")->selectOne(DB::raw($sql),[
  672. $detail["customerid"],$detail["sku"]
  673. ]);
  674. return $res ? $map[$res->locationid] : null;
  675. }
  676. }