StorageService.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  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 * 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. $asns = DB::connection("oracle")->select(DB::raw($sql),[$asn,$barCode,$barCode,$barCode,$amount]);
  240. if (!$asns)return [];
  241. $nums = [];
  242. $sum = 0;
  243. $maxIndex = null;
  244. foreach ($asns as $i => $asn){
  245. if ((int)$asn->fmqty == $amount)return [$asn];
  246. $nums[] = (int)$asn->fmqty;
  247. $sum += (int)$asn->fmqty;
  248. if ((int)$asn->fmqty>$amount)$maxIndex = $i;
  249. }
  250. if ($sum<$amount)return []; //上架数大于入库数
  251. $result = $this->getMatch($nums,$amount);
  252. if (!$result)return $this->splitTask($asns,$maxIndex,$amount);
  253. $arr = [];
  254. foreach ($result as $index)$arr[] = $asns[$index];
  255. return $arr;
  256. }
  257. /**
  258. * 拆分任务
  259. * @param array $asns
  260. * @param int|null $maxIndex
  261. * @param int $amount
  262. *
  263. * @return array
  264. */
  265. private function splitTask($asns,$maxIndex,$amount):array
  266. {
  267. $result = [];
  268. if ($maxIndex===null){
  269. foreach ($asns as $asn){
  270. if ($amount>(int)$asn->fmqty){
  271. $result[] = $asn;
  272. $amount-=(int)$asn->fmqty;
  273. }else $splitTarget = $asn;
  274. }
  275. }else $splitTarget = $asns[$maxIndex];
  276. $result[] = $this->copyTask($splitTarget,$amount);
  277. return $result;
  278. }
  279. /**
  280. * @param \stdClass $task
  281. * @param int $amount
  282. *
  283. * @return \stdClass
  284. *
  285. * @throws
  286. */
  287. private function copyTask($task,$amount)
  288. {
  289. DB::connection("oracle")->beginTransaction();
  290. try {
  291. $columns = '';
  292. $values = '';
  293. $seq = 0;
  294. foreach ($task as $key=>$val){
  295. if (Str::upper($key)=='TASKID_SEQUENCE') {
  296. $taskMax = DB::connection("oracle")->selectOne(DB::raw("select MAX(TASKID_SEQUENCE) maxseq from TSK_TASKLISTS where taskid = ?"),[$task->taskid]);
  297. $val = $taskMax->maxseq + 1;
  298. $seq = $val;
  299. }
  300. if (Str::upper($key)=='FMQTY' || Str::upper($key)=='FMQTY_EACH')$val = $amount;
  301. if (Str::upper($key)=='FMID')$val = "WAS".$val;
  302. $columns .= "'".$key."',";
  303. $values .= "'".$val."',";
  304. }
  305. $columns = mb_substr($columns,0,-1);
  306. $values = mb_substr($values,0,-1);
  307. $sql = <<<sql
  308. INSERT INTO TSK_TASKLISTS({$columns}) VALUES({$values})
  309. sql;
  310. DB::connection("oracle")->insert(DB::raw($sql));
  311. DB::connection("oracle")->update(DB::raw("UPDATE TSK_TASKLISTS SET FMQTY = FMQTY-?,FMQTY_EACH = FMQTY_EACH-? WHERE TASKID = ? AND TASKID_SEQUENCE = ?"),[
  312. $amount,$amount,$task->taskid,$task->taskid_sequence
  313. ]);
  314. $invs = DB::connection("oracle")->select(DB::raw("SELECT * FROM INV_LOT_LOC_ID WHERE LOTNUM = ? AND LOCATIONID IN (?,?) AND TRACEID = ?"),[
  315. $task->fmlotnum,$task->fmlocation,$task->plantolocation,$task->fmid
  316. ]);
  317. foreach ($invs as $inv){
  318. $columns = '';
  319. $values = '';
  320. if ($inv->locationid==$task->fmlocation){
  321. DB::connection("oracle")->update(DB::raw("UPDATE inv_lot_loc_id SET qty = qty-? WHERE lotnum = ? AND locationid = ? AND traceid = ?"),[
  322. $amount,$inv->lotnum,$inv->locationid,$inv->traceid
  323. ]);
  324. foreach ($inv as $key=>$val){
  325. if (Str::upper($key)=='TRACEID') $val = "WAS".$task->fmid;
  326. if (Str::upper($key)=='QTY') $val = $amount;
  327. $columns .= "'".$key."',";
  328. $values .= "'".$val."',";
  329. }
  330. $columns = mb_substr($columns,0,-1);
  331. $values = mb_substr($values,0,-1);
  332. DB::connection("oracle")->insert(DB::raw("INSERT INTO inv_lot_loc_id({$columns}) VALUES({$values})"));
  333. }
  334. if ($inv->locationid==$task->plantolocation){
  335. DB::connection("oracle")->update(DB::raw("UPDATE inv_lot_loc_id SET QTYPA = QTYPA-? WHERE lotnum = ? AND locationid = ? AND traceid = ?"),[
  336. $amount,$inv->lotnum,$inv->locationid,$inv->traceid
  337. ]);
  338. foreach ($inv as $key=>$val){
  339. if (Str::upper($key)=='TRACEID') $val = "WAS".$task->fmid;
  340. if (Str::upper($key)=='QTYPA') $val = $amount;
  341. $columns .= "'".$key."',";
  342. $values .= "'".$val."',";
  343. }
  344. $columns = mb_substr($columns,0,-1);
  345. $values = mb_substr($values,0,-1);
  346. DB::connection("oracle")->insert(DB::raw("INSERT INTO inv_lot_loc_id({$columns}) VALUES({$values})"));
  347. }
  348. }
  349. DB::connection("oracle")->commit();
  350. }catch(\Exception $e) {
  351. DB::connection("oracle")->rollBack();
  352. throw new \Exception("拆分任务失败:".$e->getMessage());
  353. }
  354. return DB::connection("oracle")->selectOne(DB::raw("SELECT * FROM TSK_TASKLISTS WHERE TASKID = ? AND TASKID_SEQUENCE = ?"),[$task->taskid,$seq]);
  355. }
  356. /**
  357. * 获取匹配数字
  358. *
  359. * @param Integer[] $nums
  360. * @param Integer $target
  361. * @return Integer[]|null
  362. */
  363. protected function getMatch(array $nums,int $target) :?array
  364. {
  365. $map=[];
  366. foreach ($nums as $index=>$val){
  367. $complement=$target-$val;
  368. if(array_key_exists($complement,$map))return [$map[$complement],$index];
  369. if ($val==$target)return [$index];
  370. $map[$val]=$index;
  371. if ($val<$target){
  372. $temp = $nums;
  373. unset($temp[$index]);
  374. $arr = $this->getMatch($temp,$target-$val);
  375. if ($arr) {
  376. $arr[] = $index;
  377. return $arr;
  378. }
  379. }
  380. }
  381. return null;
  382. }
  383. /**
  384. * 将任务在flux上架
  385. *
  386. * @param $asn
  387. * @param $ide
  388. * @param $amount
  389. * @return bool
  390. * @throws \Throwable
  391. */
  392. public function fluxPA($asn,$ide,$amount)
  393. {
  394. if (!$asn->taskid)return false;//ASN单无此入库信息,禁止上架
  395. $sql = <<<sql
  396. SELECT * FROM inv_lot_loc_id WHERE lotnum = ? AND traceid = ? AND customerid= ? and sku = ? and qty = {$amount}
  397. sql;
  398. $inv = DB::connection("oracle")->selectOne(DB::raw($sql),[$asn->fmlotnum,$asn->plantoid,$asn->customerid,$asn->sku]);
  399. if (!$inv)return false;//余量与入库不符
  400. DB::connection("oracle")->transaction(function ()use($inv,$amount,$ide,$asn,&$who){
  401. $db = DB::connection("oracle");
  402. $db->delete(DB::raw("DELETE FROM inv_lot_loc_id WHERE lotnum = ? AND traceid = ? AND traceid != '*' AND qty = 0"),[
  403. $inv->lotnum,$inv->traceid
  404. ]);
  405. $invHistory = $db->selectOne(DB::raw("SELECT * FROM inv_lot_loc_id WHERE lotnum = ? AND locationid = ? AND customerid = ? AND sku = ? AND traceid = '*' FOR UPDATE"),[
  406. $inv->lotnum,$ide,$inv->customerid,$inv->sku
  407. ]);
  408. $who = 'WAS'.(Auth::user() ? '-'.Auth::user()["name"] : '');
  409. if ($invHistory)$db->update(DB::raw("UPDATE inv_lot_loc_id SET qty = qty+? WHERE lotnum = ? AND locationid = ? AND traceid = '*'"),[
  410. (int)$amount,$inv->lotnum,$ide
  411. ]);
  412. 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)"),[
  413. $inv->lotnum,$ide,$inv->customerid,$inv->sku,$amount,date("Y-m-d H:i:s"),$who,
  414. date("Y-m-d H:i:s"),$who
  415. ]);
  416. $sql = <<<sql
  417. INSERT INTO ACT_TRANSACTION_LOG VALUES(?,'PA',?,?,?,?,'ASN',?,?,?,?,?,?,?,?,TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),?,
  418. TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),?,0,0,0,0,TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),?,?,null,null,null,'*',?,?,?,?,?,?,?,
  419. ?,?,?,?,?,'N',null,?,?,?,?,?,?,?,null,null)
  420. sql;
  421. list($trid,$max) = $this->getTrNumber();
  422. $db->insert(DB::raw($sql),[
  423. $trid,$asn->customerid,$asn->sku,
  424. $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,
  425. 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,
  426. '*','0','N','*',$asn->taskid_sequence,$asn->warehouseid,$asn->userdefine1,$asn->userdefine2,
  427. $asn->userdefine3,$asn->userdefine4,$asn->userdefine5,'O'
  428. ]);
  429. $this->setTrNumber($max);
  430. $sql = <<<sql
  431. update TSK_TASKLISTS set TASKPROCESS = '99',REASONCODE = 'OK',PLANTOLOCATION = ?,PLANLOGICALTOSEQUENCE = ?,FMID = '*'
  432. COMPLETED_TRANSACTIONID = ?,OPENWHO = ?,OPENTIME = TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),
  433. CLOSEWHO = ?,CLOSETIME = ?,EDITTIME = ?,EDITWHO = ?
  434. where taskid = ? AND TASKID_SEQUENCE = ?
  435. sql;
  436. $db->update(DB::raw($sql),[
  437. $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
  438. ]);
  439. });
  440. //成功后应去修改ASN状态及数量 暂时不知上架后ASN应为状态
  441. /* $sql = <<<sql
  442. UPDATE doc_asn_details SET linestatus = ?,edittime = TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),editwho = ? WHERE asnno = ? AND asnlineno = ?
  443. sql;*/
  444. //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]);
  445. if ($asn->expectedqty==$asn->receivedqty && $asn->linestatus=='40'){
  446. //DB::connection("oracle")->update(DB::raw($sql),['40',date("Y-m-d H:i:s"),$who,$asn->asnno,$asn->asnlineno]);
  447. $check = DB::connection("oracle")->selectOne(DB::raw("SELECT 1 FROM DOC_ASN_DETAILS WHERE ASNNO = ? AND LINESTATUS != '40'"),[$asn->asnno]);
  448. if (!$check){
  449. $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]);
  450. $paQty = 0;
  451. $inQty = 0;
  452. foreach ($logs as $log){
  453. if ($log->transactiontype == 'IN')$inQty = $log->qty;
  454. else $paQty = $log->qty;
  455. }
  456. if ($paQty == $inQty){
  457. 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 = ?"),
  458. [date("Y-m-d H:i:s"),$who,$asn->asnno]);
  459. 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 = ?"),
  460. [date("Y-m-d H:i:s"),$who,$asn->asnno]);
  461. }
  462. }
  463. }
  464. return true;
  465. }
  466. /**
  467. * put cache rack box to warehousing(将缓存架料箱入库)
  468. *
  469. * @param string $fromLocation
  470. * @param integer $boxId
  471. *
  472. * @return int
  473. */
  474. public function putWareHousing(string $fromLocation, $boxId):?int
  475. {
  476. $station = Station::query()->select("id")
  477. ->where("station_type_id",5)->where("code",$fromLocation)->first();
  478. if (!$station)return null;
  479. if (StationTask::query()->select("id")->where("status","!=",'完成')->where("station_id",$station->id)->first())return null;
  480. /** @var StationTaskMaterialBox|\stdClass $stmb */
  481. $stmb = $this->createWarehousingTask($station->id,$boxId);
  482. return $stmb->id;
  483. }
  484. /**
  485. * 获取事务现号
  486. *
  487. * @return array
  488. */
  489. private function getTrNumber()
  490. {
  491. $val = ValueStore::query()->select("value")->where("name","flux_tr_number")->first();
  492. if (!$val)$val = ValueStore::query()->create(["name"=>"flux_tr_number","value"=>'0']);
  493. $max = $val->value+1;
  494. $number = sprintf("%09d", $max);
  495. return array('W'.$number,$max);
  496. }
  497. /**
  498. * 设置事务现号
  499. *
  500. * @param integer $max
  501. */
  502. private function setTrNumber($max)
  503. {
  504. ValueStore::query()->select("value")->where("name","flux_tr_number")->update(["value"=>(string)((int)$max+1)]);
  505. }
  506. /**
  507. * 入库
  508. *
  509. * @param integer $boxId
  510. * @param integer $amount
  511. * @param integer $commodityId
  512. *
  513. * @return bool
  514. */
  515. public function warehousing($boxId, $amount, $commodityId = null):bool
  516. {
  517. DB::beginTransaction();
  518. try{
  519. $storage = Storage::query()->where("material_box_id",$boxId)->lockForUpdate()->first();
  520. if (!$storage && !$commodityId)return false;
  521. if (!$storage){
  522. Storage::query()->create([
  523. "station_id" => null,
  524. "material_box_id" => $boxId,
  525. "commodity_id" => $commodityId,
  526. "amount" => $amount,
  527. ]);
  528. return true;
  529. }
  530. if ($commodityId && $storage->commodity_id && $storage->commodity_id!=$commodityId)return false;
  531. $obj = [
  532. "station_id" => null,
  533. "amount" => DB::raw("amount + {$amount}"),
  534. ];
  535. if (!$storage->commodity_id && $commodityId)$obj["commodity_id"] = $commodityId;
  536. $storage->update($obj);
  537. DB::commit();
  538. return true;
  539. }catch (\Exception $e){
  540. DB::rollBack();
  541. return false;
  542. }
  543. }
  544. /**
  545. * 出库
  546. *
  547. * @param integer $boxId
  548. * @param integer $amount
  549. * @param integer $commodityId
  550. *
  551. * @return bool
  552. */
  553. public function outWarehousing($boxId, $amount, $commodityId = null):bool
  554. {
  555. DB::beginTransaction();
  556. try{
  557. $storage = Storage::query()->where("material_box_id",$boxId)->lockForUpdate()->first();
  558. if (!$storage)return false;
  559. if ($commodityId && $storage->commodity_id && $storage->commodity_id!=$commodityId)return false;
  560. $obj = [
  561. "station_id" => null,
  562. "amount" => DB::raw("amount - {$amount}"),
  563. ];
  564. if (!$storage->commodity_id && $commodityId)$obj["commodity_id"] = $commodityId;
  565. $storage->update($obj);
  566. DB::commit();
  567. return true;
  568. }catch (\Exception $e){
  569. DB::rollBack();
  570. return false;
  571. }
  572. }
  573. /**
  574. * 清除任务
  575. *
  576. * @param array $stationCodes
  577. *
  578. */
  579. public function clearTask(array $stationCodes)
  580. {
  581. //清除海柔信息,标记料箱为出库
  582. DB::connection("mysql_haiRobotics")->table("ks_bin")->whereIn("ks_bin_space_code",$stationCodes)
  583. ->where("status",1)->update([
  584. "ks_bin_space_code" => null,"ks_bin_space_id"=>null,"orig_ks_bin_space_code"=>null,"orig_ks_bin_space_id"=>null,
  585. "status"=>4,
  586. ]);
  587. //WAS任务清除
  588. $station = Station::query()->select("id")->whereIn("code",$stationCodes);
  589. $task = StationTask::query()->select("id")->where("status","!=",'完成')->whereIn("station_id",$station);
  590. StationTaskMaterialBox::query()->where("status","!=",'完成')->whereIn("station_task_id",$task)->update([
  591. "status" => "完成"
  592. ]);
  593. StationTask::query()->where("status","!=",'完成')->whereIn("station_id",$station)->update([
  594. "status" => "完成"
  595. ]);
  596. Storage::query()->whereIn("station_id",$station)->update([
  597. "status" => 1,
  598. "station_id" => null,
  599. ]);
  600. }
  601. /**
  602. * 获取半箱库位库存信息
  603. *
  604. * @param CommodityMaterialBoxModel|\stdClass $model
  605. * @param StoreItem|\stdClass $item
  606. * @param string|null $asn
  607. *
  608. * @return ?Storage
  609. */
  610. public function getHalfBoxLocation(CommodityMaterialBoxModel $model,StoreItem $item,?string $asn = null,array $blacklist = []):?Storage
  611. {
  612. if (!$asn){
  613. $item->loadMissing("store");
  614. $asn = $item->store->asn_code;
  615. }
  616. $stationCodes = '';//拼接库位编码
  617. $map = [];//库位与库存映射
  618. //查询填充
  619. $query = Storage::query()->with("station")->whereHas("materialBox",function (Builder $query)use($model){
  620. $query->where("material_box_model_id",$model->material_box_model_id);
  621. })->where("commodity_id",$model->commodity_id)->where("amount","<",$model->maximum)
  622. ->where("status",0)->where(DB::raw("{$model->maximum}-amount"),">",0);
  623. if ($blacklist)$query->whereHas("materialBox",function (Builder $query)use($blacklist){
  624. $query->whereNotIn("id",$blacklist);
  625. });
  626. $query->get()->each(function ($storage)use(&$stationCodes,&$map){
  627. $stationCodes .= "'".$storage->station->code."',";
  628. $map[$storage->station->code] = $storage;
  629. });
  630. //不存在跳出
  631. if (!$stationCodes)return null;
  632. $stationCodes = mb_substr($stationCodes,0,-1);
  633. //查询对应asn detail
  634. $detail = DB::connection("oracle")->selectOne(DB::raw("SELECT * FROM DOC_ASN_DETAILS WHERE ASNNO = ? AND ASNLINENO = ?"),[
  635. $asn,$item->asn_line_code
  636. ]);
  637. if(!$detail)return null;
  638. $detail = get_object_vars($detail);
  639. //查询对应批次属性
  640. $lot = DB::connection("oracle")->selectOne(DB::raw("SELECT * FROM BAS_LOTID WHERE LOTID = (SELECT LOTID FROM BAS_SKU WHERE CUSTOMERID = ? AND SKU = ?)"),[
  641. $detail["customerid"],$detail["sku"]
  642. ]);
  643. if(!$lot)return null;
  644. //通过符合条件的批次号来查询 库存
  645. $lot = get_object_vars($lot);
  646. $sql = <<<sql
  647. SELECT * FROM INV_LOT_LOC_ID WHERE LOTNUM IN
  648. (SELECT LOTNUM FROM INV_LOT_ATT WHERE INV_LOT_ATT.CUSTOMERID = ? AND SKU = ?
  649. sql;
  650. //拼接可以合并的批次属性要求
  651. for ($i=1;$i<=8;$i++){
  652. if ($lot["lotkey0{$i}"]=='Y'){
  653. $val = $detail["lotatt0{$i}"] ? "'{$detail["lotatt0{$i}"]}'" : null;
  654. $sql .= " AND LOTATT0{$i} = $val";
  655. }
  656. }
  657. $sql .= ") AND LOCATIONID IN ({$stationCodes}) AND TRACEID = '*' AND {$model->maximum}-QTY > 0 ORDER BY {$model->maximum}-QTY";
  658. $res = DB::connection("oracle")->selectOne(DB::raw($sql),[
  659. $detail["customerid"],$detail["sku"]
  660. ]);
  661. return $res ? $map[$res->locationid] : null;
  662. }
  663. }