| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341 |
- <?php
- namespace App\Http\Controllers\api\thirdPart\haochuang;
- use App\Batch;
- use App\CommodityBarcode;
- use App\Exceptions\Exception;
- use App\Http\Controllers\Controller;
- use App\Jobs\SendPieceOwnerJob;
- use App\OracleDOCWaveDetails;
- use App\Order;
- use App\OrderBin;
- use App\OrderCommodity;
- use App\Services\LogService;
- use App\Services\OracleDOCOrderHeaderService;
- use App\Services\OrderCommodityService;
- use App\Services\OrderService;
- use App\Services\WaveService;
- use App\SortingStation;
- use App\User;
- use App\UserToken;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Hash;
- use Illuminate\Support\Facades\Http;
- use Illuminate\Support\Facades\Validator;
- class SortingController extends Controller
- {
- function login(Request $request){
- $name = $request->input('name');
- $password = $request->input('password');
- $station_id = $request->input('station_id');
- $errors=$this->loginValidator($request->all())->errors();
- if(count($errors)>0){
- app('LogService')->log(__METHOD__, 'error' . __FUNCTION__, json_encode($request->all()).'|'.json_encode($errors));
- return response()->json(['result'=>'failure','fail_info'=>'error','errors'=>$errors])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
- }
- $user=User::query()->where('name',$name)->first();
- if(!$user||!Hash::check($password, $user['password'])){
- return ['result'=>'failure','fail_info'=>'认证错误'];
- }
- $station = SortingStation::findOrCreate($station_id);
- $station->login();
- return ['result'=>'success','token'=>$user->token(604800)];
- }
- protected function loginValidator(array $data)
- {
- return Validator::make($data, [
- 'name' => ['required', 'string', 'max:191'],
- 'password' => ['required', 'string', 'max:191'],
- 'station_id' => ['required', 'string', 'max:191'],
- ],[
- 'required' => ':attribute 不能为空',
- ],[
- 'name' => '用户名',
- 'password' => '密码',
- 'station_id' => '设备ID',
- ]);
- }
- function process(Request $request){
- return response()->json(['result'=>'failure','fail_info'=>"功能关闭,请联系技术部更新新版APP"])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
- $token = trim($request->input('token'));
- if(!UserToken::getUser($token)){
- return ['result'=>'unauthority','fail_info'=>'无效令牌或令牌过期'];
- }
- $station_id = $request->input('station_id');
- $batch_id = $request->input('batch_id');
- app('LogService')->log("浩创", "process", '分拨墙播种请求:'.json_encode($request->all()));
- // 二次分拣拆分波次
- $childIndex = null;
- $ownerId = null;// 货主ID
- $warehouseId = null;// 仓库ID
- $number = 0;// 总拣数量
- // 容器号获取波次
- if (strlen($batch_id) != 13 || substr($batch_id, 0, 1) != 'W') {
- // 请求JAVA端获取对应波次号
- $url = config('api.java-back.base').config('api.java.device.picking.getContainerOfWave');
- $get = Http::get($url, ["container" => $batch_id]);
- $result = $get->json();
- if ($result["code"] != 200) {
- return response()->json(['result'=>'failure','fail_info'=>$result["message"]])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
- }
- $request->offsetSet("batch_id",$result["data"]);
- } else {
- $arr = explode('-',$batch_id);
- if (count($arr)==2){
- $childIndex = (int)$arr[1];
- $request->offsetSet("batch_id",$arr[0]);
- }
- }
- $batch_id = $request->input('batch_id');
- $errors=$this->processValidator($request->all())->errors();
- if(count($errors)>0){
- app('LogService')->log(__METHOD__, 'error' . __FUNCTION__, json_encode($request->all()).'|'.json_encode($errors));
- return response()->json(['result'=>'failure','fail_info'=>'error','errors'=>$errors])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
- }
- // 同步orderCommodity
- $this->syncOrder($batch_id);
- /** @var Batch|\stdClass $batch */
- $batch=Batch::query()->where('code',$batch_id)->orderBy('id','desc')->first();
- if ($batch->wms_type && mb_strstr($batch->wms_type, "单品")) {
- return response()->json(['result'=>'failure','fail_info'=>'单品波次无需分拣'])
- ->setEncodingOptions(JSON_UNESCAPED_UNICODE);
- }
- $data=[
- 'result'=>'success',
- 'station_id'=>$station_id,
- 'batch_id'=>$batch_id,
- 'orders'=>[]
- ];
- if ($childIndex!==null && $batch->split_size){
- $start = (($childIndex-1)*$batch->split_size)+1;
- $end = $childIndex*$batch->split_size;
- $sql = <<<SQL
- SELECT ORDERNO FROM DOC_WAVE_DETAILS WHERE WAVENO = '{$batch_id}' AND SEQNO BETWEEN {$start} AND {$end};
- SQL;
- $waves = DB::connection("oracle")->select(DB::raw($sql));
- $codes = array_column($waves,'orderno');
- $orders = Order::query()->with(["bin","owner","orderCommodities.commodity.barcodes"])->whereIn("code",$codes)->get();
- }else $orders = $batch->orders()->with(["bin","owner","orderCommodities.commodity.barcodes"])->get();
- $ordersSorted=$orders->sortBy(function(Order $order){
- return $order->bin->number;
- });
- $ordersSorted->each(function(Order $order)use(&$data,$request,$childIndex,$batch,&$ownerId,&$warehouseId,&$number){
- if($order['status']=='取消')return;
- $owner = $order->owner;
- if ($ownerId == null && $owner != null) {
- $ownerId = $owner->id;
- }
- if ($warehouseId == null) {
- $warehouseId = $order['warehouse_id'];
- }
- $orderData=[
- 'order_id'=>$order['code'],
- 'owner'=>$owner->code,
- 'status'=>$order['status']=='未处理'?'available':$order['status'],
- 'created_at'=>$order['created_at']->toDateTimeString(),
- 'bin'=>(function()use($order,$childIndex,$batch){
- $bin=$order->bin->number??'';
- if(!$bin){
- $bin=OracleDOCWaveDetails::query()->where('orderno', 'SO201230003574')->get('seqno')->first()['seqno']??'';
- LogService::log(__METHOD__,__FUNCTION__,'bin缺失补查:'.$bin.'. order:'.$order->toJson());
- return $childIndex!==null ? $bin-(($childIndex-1)*$batch->split_size) : $bin;
- }
- return $childIndex!==null ? $bin-(($childIndex-1)*$batch->split_size) : $bin;
- })(),
- 'barcodes'=>[]
- ];
- $order->orderCommodities->each(function(OrderCommodity $orderCommodity)use(&$orderData,$request,&$number){
- $commodity=$orderCommodity->commodity;
- if(!$commodity){
- app('LogService')->log(__METHOD__, 'error' . __FUNCTION__, '播种位数据准备出错,找不到订单对应的Commodity id的对象'.$orderCommodity['commodity_id'].',是否表数据在波次生成后丢失?'.json_encode($request->all()));
- return;
- }
- $barcodeStr=$commodity->barcodes->map(function(CommodityBarcode $barcode){
- return $barcode['code'];
- })->filter(function($code){
- return $code&&(!preg_match('/[\x{4e00}-\x{9fa5}]/u',$code));
- })->join(',');
- $number += (int)$orderCommodity['amount'] ?? 0;
- $orderData['barcodes'][]=[
- 'id'=>$orderCommodity['id']??'',
- 'barcode_id'=>$barcodeStr??'',
- 'name'=>$commodity['name']??'',
- 'sku'=>$commodity['sku']??'',
- 'amount'=>$orderCommodity['amount']??'',
- 'location'=>$orderCommodity['location']??'',
- ];
- });
- $data['orders'][]=$orderData;
- });
- $sendToWms=(new \App\Http\Controllers\api\thirdPart\flux\SortingController())->informBinAssignment($batch);
- if(!$sendToWms){
- app('LogService')->log(__METHOD__, 'error' . __FUNCTION__, '播种位发送给WMS错误:'.json_encode($request->all()));
- return response()->json(['result'=>'failure','fail_info'=>'播种位发送给WMS错误,请联系管理员检查错误'])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
- }
- $station = SortingStation::findOrCreate($station_id);
- $station->setProcessingBatch($batch);
- $messageId = $batch_id.($childIndex == null ? '' : '#'.$childIndex);
- (new WaveService())->sendPiece("HC-ST-".$messageId, UserToken::getUser($token)->id ?? '0', $ownerId,
- $warehouseId, date("Y-m-d H:i:s"), $number);
- try{
- SendPieceOwnerJob::dispatch($batch_id,UserToken::getUser($token)->id ?? '0',$warehouseId,$ownerId,date("Y-m-d H:i:s"));
- // (new WaveService())->sendOwnerPiece($batch_id,UserToken::getUser($token)->id ?? '0',$warehouseId,$ownerId,date("Y-m-d H:i:s"));
- }catch (\Exception $e){
- app('LogService')->log("二次分拣货主计件", "上传失败", $batch_id.$warehouseId.$ownerId.date("Y-m-d H:i:s").$e->getMessage());
- }
- return $data;
- }
- protected function processValidator(array $data)
- {
- return Validator::make($data, [
- 'token' => ['required', 'string', 'max:191'],
- 'station_id' => ['required', 'string', 'max:191'],
- 'batch_id' => ['required', 'string', 'max:191','exists:batches,code'],
- ],[
- 'required' => ':attribute 不能为空',
- 'exists' => ':attribute 不存在',
- ],[
- 'station_id' => '设备ID',
- 'batch_id' => '波次号',
- ]);
- }
- function done(Request $request){
- $token = $request->input('token');
- $station_id = $request->input('station_id');
- $batch_id = $request->input('batch_id');
- app('LogService')->log(__METHOD__, __FUNCTION__.'_request', '浩创的完成请求:'.json_encode($request->all()));
- $errors=$this->doneValidator($request->all())->errors();
- $failInfo='';
- foreach ($errors as $error){$failInfo.=$error[0].'; ';}
- if(count($errors)>0){
- app('LogService')->log(__METHOD__, 'error' . __FUNCTION__, json_encode($request->all()).'|'.json_encode($errors));
- return response()->json(['result'=>'failure','fail_info'=>$failInfo,'errors'=>$errors])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
- }
- if(!UserToken::getUser($token)){
- return ['result'=>'unauthority','fail_info'=>'无效令牌或令牌过期'];
- }
- $batch=Batch::query()->where('code',$batch_id)->first();
- if($batch->status=='已处理'){
- app('LogService')->log(__METHOD__,'alert_'.__FUNCTION__,$batch['code'].'重复发送,波次已处理');
- return ['result'=>'failure','fail_info'=>$batch['code'].'重复发送,波次已处理'];
- }
- $sendToWms=(new \App\Http\Controllers\api\thirdPart\flux\SortingController())->informBatchFinished($batch);
- if(!$sendToWms){
- app('LogService')->log(__METHOD__, 'error' . __FUNCTION__, '发送给WMS错误:'.json_encode($request->all()));
- return response()->json(['result'=>'failure','fail_info'=>'发送给WMS错误,请联系管理员检查错误'])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
- }
- $batch->setProcessed();
- $station = SortingStation::query()->where('name',$station_id)->first();
- $station->clearProcessingBatch();
- return ['result'=>'success','batch_id'=>$batch_id];
- }
- protected function doneValidator(array $data)
- {
- return Validator::make($data, [
- 'token' => ['required', 'string', 'max:191'],
- 'station_id' => ['required', 'string', 'max:191','exists:sorting_stations,name'],
- 'batch_id' => ['required', 'string', 'max:191','exists:batches,code'],
- ],[
- 'required' => ':attribute 不能为空',
- 'exists' => ':attribute 不存在',
- ],[
- 'station_id' => '设备ID',
- 'batch_id' => '波次号',
- ]);
- }
- public function syncOrder($code)
- {
- $orderHeaders = app(OracleDOCOrderHeaderService::class)->getQuery()->where('DOC_Order_Header.WaveNo',$code)->get();
- app(OrderService::class)->syncOrderByWMSOrderHeaders($orderHeaders);
- app(OrderCommodityService::class)->syncOrderCommodity($orderHeaders);
- $this->syncOrderBin($code);
- }
- public function syncOrderBin($code)
- {
- $wave = DB::connection("oracle")->selectOne(DB::raw("select * from DOC_WAVE_HEADER where WAVENO = ?"),[$code]);
- if (!$wave) return;
- $owner = app("OwnerService")->codeGetOwner($wave->customerid);
- $obj = [
- "wms_status" => $this->wms_status($wave),
- "wms_type"=>$wave->descr,
- "created_at"=>date("Y-m-d H:i:s"),
- "wms_created_at"=>$wave->addtime,
- "updated_at"=>$wave->edittime,
- "owner_id"=>$owner->id,
- ];
- $batch = Batch::query()->where("code",$code)->first();
- if (!$batch){
- $obj["code"] = $code;
- $batch = Batch::query()->create($obj);
- }else{
- Batch::query()->where("code",$code)->update($obj);
- }
- $order_nos = array_column(DB::connection("oracle")->select(DB::raw("select orderno from DOC_WAVE_DETAILS where WAVENO = ?"),[$code]),"orderno");
- Order::query()->whereIn("code",$order_nos)->update(["batch_id"=>$batch->id]);
- Order::query()->with(["batch","bin"])->whereIn("code",$order_nos)->get()->each(function ($order){
- if (!$order->bin){
- $bin = DB::connection("oracle")->selectOne(DB::raw("select seqno from DOC_WAVE_DETAILS where waveno = ? and orderno = ?"),[$order->batch->code,$order->code]);
- if ($bin){
- OrderBin::query()->create([
- 'order_id' => $order->id,
- 'number' => $bin->seqno,
- ]);
- }
- }
- });
- }
- /**
- * @param $wave
- * @return string
- */
- private function wms_status($wave): string
- {
- switch ($wave->wavestatus) {
- case 00:
- $wms_status = '创建';
- break;
- case 40:
- $wms_status = '部分收货';
- break;
- case 90:
- $wms_status = '取消';
- break;
- case 99:
- $wms_status = '完成';
- break;
- case 62:
- $wms_status = '部分装箱';
- break;
- default:
- $wms_status = (string)$wave->wavestatus;
- }
- return $wms_status;
- }
- }
|