StorageService.php 30 KB

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