StorageService.php 27 KB

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