SortingController.php 14 KB

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