StorageService.php 28 KB

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