StorageService.php 28 KB

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