StorageService.php 29 KB

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