SortingController.php 12 KB

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