StorageService.php 31 KB

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