StorageService.php 27 KB

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