StorageService.php 29 KB

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