StorageService.php 24 KB

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