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