SortingController.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. <?php
  2. namespace App\Http\Controllers\api\thirdPart\haochuang;
  3. use App\Batch;
  4. use App\CommodityBarcode;
  5. use App\Exceptions\Exception;
  6. use App\Http\Controllers\Controller;
  7. use App\Jobs\SendPieceOwnerJob;
  8. use App\OracleDOCWaveDetails;
  9. use App\Order;
  10. use App\OrderBin;
  11. use App\OrderCommodity;
  12. use App\Services\LogService;
  13. use App\Services\OracleDOCOrderHeaderService;
  14. use App\Services\OrderCommodityService;
  15. use App\Services\OrderService;
  16. use App\Services\WaveService;
  17. use App\SortingStation;
  18. use App\User;
  19. use App\UserToken;
  20. use Illuminate\Http\Request;
  21. use Illuminate\Support\Facades\DB;
  22. use Illuminate\Support\Facades\Hash;
  23. use Illuminate\Support\Facades\Http;
  24. use Illuminate\Support\Facades\Validator;
  25. class SortingController extends Controller
  26. {
  27. function login(Request $request){
  28. $name = $request->input('name');
  29. $password = $request->input('password');
  30. $station_id = $request->input('station_id');
  31. $errors=$this->loginValidator($request->all())->errors();
  32. if(count($errors)>0){
  33. app('LogService')->log(__METHOD__, 'error' . __FUNCTION__, json_encode($request->all()).'|'.json_encode($errors));
  34. return response()->json(['result'=>'failure','fail_info'=>'error','errors'=>$errors])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
  35. }
  36. $user=User::query()->where('name',$name)->first();
  37. if(!$user||!Hash::check($password, $user['password'])){
  38. return ['result'=>'failure','fail_info'=>'认证错误'];
  39. }
  40. $station = SortingStation::findOrCreate($station_id);
  41. $station->login();
  42. return ['result'=>'success','token'=>$user->token(604800)];
  43. }
  44. protected function loginValidator(array $data)
  45. {
  46. return Validator::make($data, [
  47. 'name' => ['required', 'string', 'max:191'],
  48. 'password' => ['required', 'string', 'max:191'],
  49. 'station_id' => ['required', 'string', 'max:191'],
  50. ],[
  51. 'required' => ':attribute 不能为空',
  52. ],[
  53. 'name' => '用户名',
  54. 'password' => '密码',
  55. 'station_id' => '设备ID',
  56. ]);
  57. }
  58. function process(Request $request){
  59. return response()->json(['result'=>'failure','fail_info'=>"功能关闭,请联系技术部更新新版APP"])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
  60. $token = trim($request->input('token'));
  61. if(!UserToken::getUser($token)){
  62. return ['result'=>'unauthority','fail_info'=>'无效令牌或令牌过期'];
  63. }
  64. $station_id = $request->input('station_id');
  65. $batch_id = $request->input('batch_id');
  66. app('LogService')->log("浩创", "process", '分拨墙播种请求:'.json_encode($request->all()));
  67. // 二次分拣拆分波次
  68. $childIndex = null;
  69. $ownerId = null;// 货主ID
  70. $warehouseId = null;// 仓库ID
  71. $number = 0;// 总拣数量
  72. // 容器号获取波次
  73. if (strlen($batch_id) != 13 || substr($batch_id, 0, 1) != 'W') {
  74. // 请求JAVA端获取对应波次号
  75. $url = config('api.java-back.base').config('api.java.device.picking.getContainerOfWave');
  76. $get = Http::get($url, ["container" => $batch_id]);
  77. $result = $get->json();
  78. if ($result["code"] != 200) {
  79. return response()->json(['result'=>'failure','fail_info'=>$result["message"]])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
  80. }
  81. $request->offsetSet("batch_id",$result["data"]);
  82. } else {
  83. $arr = explode('-',$batch_id);
  84. if (count($arr)==2){
  85. $childIndex = (int)$arr[1];
  86. $request->offsetSet("batch_id",$arr[0]);
  87. }
  88. }
  89. $batch_id = $request->input('batch_id');
  90. $errors=$this->processValidator($request->all())->errors();
  91. if(count($errors)>0){
  92. app('LogService')->log(__METHOD__, 'error' . __FUNCTION__, json_encode($request->all()).'|'.json_encode($errors));
  93. return response()->json(['result'=>'failure','fail_info'=>'error','errors'=>$errors])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
  94. }
  95. // 同步orderCommodity
  96. $this->syncOrder($batch_id);
  97. /** @var Batch|\stdClass $batch */
  98. $batch=Batch::query()->where('code',$batch_id)->orderBy('id','desc')->first();
  99. if ($batch->wms_type && mb_strstr($batch->wms_type, "单品")) {
  100. return response()->json(['result'=>'failure','fail_info'=>'单品波次无需分拣'])
  101. ->setEncodingOptions(JSON_UNESCAPED_UNICODE);
  102. }
  103. $data=[
  104. 'result'=>'success',
  105. 'station_id'=>$station_id,
  106. 'batch_id'=>$batch_id,
  107. 'orders'=>[]
  108. ];
  109. if ($childIndex!==null && $batch->split_size){
  110. $start = (($childIndex-1)*$batch->split_size)+1;
  111. $end = $childIndex*$batch->split_size;
  112. $sql = <<<SQL
  113. SELECT ORDERNO FROM DOC_WAVE_DETAILS WHERE WAVENO = '{$batch_id}' AND SEQNO BETWEEN {$start} AND {$end};
  114. SQL;
  115. $waves = DB::connection("oracle")->select(DB::raw($sql));
  116. $codes = array_column($waves,'orderno');
  117. $orders = Order::query()->with(["bin","owner","orderCommodities.commodity.barcodes"])->whereIn("code",$codes)->get();
  118. }else $orders = $batch->orders()->with(["bin","owner","orderCommodities.commodity.barcodes"])->get();
  119. $ordersSorted=$orders->sortBy(function(Order $order){
  120. return $order->bin->number;
  121. });
  122. $ordersSorted->each(function(Order $order)use(&$data,$request,$childIndex,$batch,&$ownerId,&$warehouseId,&$number){
  123. if($order['status']=='取消')return;
  124. $owner = $order->owner;
  125. if ($ownerId == null && $owner != null) {
  126. $ownerId = $owner->id;
  127. }
  128. if ($warehouseId == null) {
  129. $warehouseId = $order['warehouse_id'];
  130. }
  131. $orderData=[
  132. 'order_id'=>$order['code'],
  133. 'owner'=>$owner->code,
  134. 'status'=>$order['status']=='未处理'?'available':$order['status'],
  135. 'created_at'=>$order['created_at']->toDateTimeString(),
  136. 'bin'=>(function()use($order,$childIndex,$batch){
  137. $bin=$order->bin->number??'';
  138. if(!$bin){
  139. $bin=OracleDOCWaveDetails::query()->where('orderno', 'SO201230003574')->get('seqno')->first()['seqno']??'';
  140. LogService::log(__METHOD__,__FUNCTION__,'bin缺失补查:'.$bin.'. order:'.$order->toJson());
  141. return $childIndex!==null ? $bin-(($childIndex-1)*$batch->split_size) : $bin;
  142. }
  143. return $childIndex!==null ? $bin-(($childIndex-1)*$batch->split_size) : $bin;
  144. })(),
  145. 'barcodes'=>[]
  146. ];
  147. $order->orderCommodities->each(function(OrderCommodity $orderCommodity)use(&$orderData,$request,&$number){
  148. $commodity=$orderCommodity->commodity;
  149. if(!$commodity){
  150. app('LogService')->log(__METHOD__, 'error' . __FUNCTION__, '播种位数据准备出错,找不到订单对应的Commodity id的对象'.$orderCommodity['commodity_id'].',是否表数据在波次生成后丢失?'.json_encode($request->all()));
  151. return;
  152. }
  153. $barcodeStr=$commodity->barcodes->map(function(CommodityBarcode $barcode){
  154. return $barcode['code'];
  155. })->filter(function($code){
  156. return $code&&(!preg_match('/[\x{4e00}-\x{9fa5}]/u',$code));
  157. })->join(',');
  158. $number += (int)$orderCommodity['amount'] ?? 0;
  159. $orderData['barcodes'][]=[
  160. 'id'=>$orderCommodity['id']??'',
  161. 'barcode_id'=>$barcodeStr??'',
  162. 'name'=>$commodity['name']??'',
  163. 'sku'=>$commodity['sku']??'',
  164. 'amount'=>$orderCommodity['amount']??'',
  165. 'location'=>$orderCommodity['location']??'',
  166. ];
  167. });
  168. $data['orders'][]=$orderData;
  169. });
  170. $sendToWms=(new \App\Http\Controllers\api\thirdPart\flux\SortingController())->informBinAssignment($batch);
  171. if(!$sendToWms){
  172. app('LogService')->log(__METHOD__, 'error' . __FUNCTION__, '播种位发送给WMS错误:'.json_encode($request->all()));
  173. return response()->json(['result'=>'failure','fail_info'=>'播种位发送给WMS错误,请联系管理员检查错误'])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
  174. }
  175. $station = SortingStation::findOrCreate($station_id);
  176. $station->setProcessingBatch($batch);
  177. $messageId = $batch_id.($childIndex == null ? '' : '#'.$childIndex);
  178. (new WaveService())->sendPiece("HC-ST-".$messageId, UserToken::getUser($token)->id ?? '0', $ownerId,
  179. $warehouseId, date("Y-m-d H:i:s"), $number);
  180. try{
  181. SendPieceOwnerJob::dispatch($batch_id,UserToken::getUser($token)->id ?? '0',$warehouseId,$ownerId,date("Y-m-d H:i:s"));
  182. // (new WaveService())->sendOwnerPiece($batch_id,UserToken::getUser($token)->id ?? '0',$warehouseId,$ownerId,date("Y-m-d H:i:s"));
  183. }catch (\Exception $e){
  184. app('LogService')->log("二次分拣货主计件", "上传失败", $batch_id.$warehouseId.$ownerId.date("Y-m-d H:i:s").$e->getMessage());
  185. }
  186. return $data;
  187. }
  188. protected function processValidator(array $data)
  189. {
  190. return Validator::make($data, [
  191. 'token' => ['required', 'string', 'max:191'],
  192. 'station_id' => ['required', 'string', 'max:191'],
  193. 'batch_id' => ['required', 'string', 'max:191','exists:batches,code'],
  194. ],[
  195. 'required' => ':attribute 不能为空',
  196. 'exists' => ':attribute 不存在',
  197. ],[
  198. 'station_id' => '设备ID',
  199. 'batch_id' => '波次号',
  200. ]);
  201. }
  202. function done(Request $request){
  203. $token = $request->input('token');
  204. $station_id = $request->input('station_id');
  205. $batch_id = $request->input('batch_id');
  206. app('LogService')->log(__METHOD__, __FUNCTION__.'_request', '浩创的完成请求:'.json_encode($request->all()));
  207. $errors=$this->doneValidator($request->all())->errors();
  208. $failInfo='';
  209. foreach ($errors as $error){$failInfo.=$error[0].'; ';}
  210. if(count($errors)>0){
  211. app('LogService')->log(__METHOD__, 'error' . __FUNCTION__, json_encode($request->all()).'|'.json_encode($errors));
  212. return response()->json(['result'=>'failure','fail_info'=>$failInfo,'errors'=>$errors])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
  213. }
  214. if(!UserToken::getUser($token)){
  215. return ['result'=>'unauthority','fail_info'=>'无效令牌或令牌过期'];
  216. }
  217. $batch=Batch::query()->where('code',$batch_id)->first();
  218. if($batch->status=='已处理'){
  219. app('LogService')->log(__METHOD__,'alert_'.__FUNCTION__,$batch['code'].'重复发送,波次已处理');
  220. return ['result'=>'failure','fail_info'=>$batch['code'].'重复发送,波次已处理'];
  221. }
  222. $sendToWms=(new \App\Http\Controllers\api\thirdPart\flux\SortingController())->informBatchFinished($batch);
  223. if(!$sendToWms){
  224. app('LogService')->log(__METHOD__, 'error' . __FUNCTION__, '发送给WMS错误:'.json_encode($request->all()));
  225. return response()->json(['result'=>'failure','fail_info'=>'发送给WMS错误,请联系管理员检查错误'])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
  226. }
  227. $batch->setProcessed();
  228. $station = SortingStation::query()->where('name',$station_id)->first();
  229. $station->clearProcessingBatch();
  230. return ['result'=>'success','batch_id'=>$batch_id];
  231. }
  232. protected function doneValidator(array $data)
  233. {
  234. return Validator::make($data, [
  235. 'token' => ['required', 'string', 'max:191'],
  236. 'station_id' => ['required', 'string', 'max:191','exists:sorting_stations,name'],
  237. 'batch_id' => ['required', 'string', 'max:191','exists:batches,code'],
  238. ],[
  239. 'required' => ':attribute 不能为空',
  240. 'exists' => ':attribute 不存在',
  241. ],[
  242. 'station_id' => '设备ID',
  243. 'batch_id' => '波次号',
  244. ]);
  245. }
  246. public function syncOrder($code)
  247. {
  248. $orderHeaders = app(OracleDOCOrderHeaderService::class)->getQuery()->where('DOC_Order_Header.WaveNo',$code)->get();
  249. app(OrderService::class)->syncOrderByWMSOrderHeaders($orderHeaders);
  250. app(OrderCommodityService::class)->syncOrderCommodity($orderHeaders);
  251. $this->syncOrderBin($code);
  252. }
  253. public function syncOrderBin($code)
  254. {
  255. $wave = DB::connection("oracle")->selectOne(DB::raw("select * from DOC_WAVE_HEADER where WAVENO = ?"),[$code]);
  256. if (!$wave) return;
  257. $owner = app("OwnerService")->codeGetOwner($wave->customerid);
  258. $obj = [
  259. "wms_status" => $this->wms_status($wave),
  260. "wms_type"=>$wave->descr,
  261. "created_at"=>date("Y-m-d H:i:s"),
  262. "wms_created_at"=>$wave->addtime,
  263. "updated_at"=>$wave->edittime,
  264. "owner_id"=>$owner->id,
  265. ];
  266. $batch = Batch::query()->where("code",$code)->first();
  267. if (!$batch){
  268. $obj["code"] = $code;
  269. $batch = Batch::query()->create($obj);
  270. }else{
  271. Batch::query()->where("code",$code)->update($obj);
  272. }
  273. $order_nos = array_column(DB::connection("oracle")->select(DB::raw("select orderno from DOC_WAVE_DETAILS where WAVENO = ?"),[$code]),"orderno");
  274. Order::query()->whereIn("code",$order_nos)->update(["batch_id"=>$batch->id]);
  275. Order::query()->with(["batch","bin"])->whereIn("code",$order_nos)->get()->each(function ($order){
  276. if (!$order->bin){
  277. $bin = DB::connection("oracle")->selectOne(DB::raw("select seqno from DOC_WAVE_DETAILS where waveno = ? and orderno = ?"),[$order->batch->code,$order->code]);
  278. if ($bin){
  279. OrderBin::query()->create([
  280. 'order_id' => $order->id,
  281. 'number' => $bin->seqno,
  282. ]);
  283. }
  284. }
  285. });
  286. }
  287. /**
  288. * @param $wave
  289. * @return string
  290. */
  291. private function wms_status($wave): string
  292. {
  293. switch ($wave->wavestatus) {
  294. case 00:
  295. $wms_status = '创建';
  296. break;
  297. case 40:
  298. $wms_status = '部分收货';
  299. break;
  300. case 90:
  301. $wms_status = '取消';
  302. break;
  303. case 99:
  304. $wms_status = '完成';
  305. break;
  306. case 62:
  307. $wms_status = '部分装箱';
  308. break;
  309. default:
  310. $wms_status = (string)$wave->wavestatus;
  311. }
  312. return $wms_status;
  313. }
  314. }