SortingController.php 12 KB

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