SortingController.php 13 KB

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