SortingController.php 15 KB

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