SortingController.php 14 KB

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