StorageService.php 30 KB

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