StorageService.php 30 KB

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