SortingController.php 15 KB

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