Sfoglia il codice sorgente

Merge branch 'master' into zengjun

ajun 4 anni fa
parent
commit
e506d47283

+ 38 - 21
app/Console/Commands/CreateWeightStatistic.php

@@ -2,7 +2,15 @@
 
 namespace App\Console\Commands;
 
+use App\Order;
+use App\OrderBin;
 use App\OrderPackageCountingRecord;
+use App\Services\BatchService;
+use App\Services\common\BatchUpdateService;
+use App\Services\DocWaveHeaderService;
+use App\Services\LogService;
+use App\ValueStore;
+use Carbon\Carbon;
 use Illuminate\Console\Command;
 use Illuminate\Support\Facades\Cache;
 use Illuminate\Support\Facades\DB;
@@ -17,28 +25,37 @@ class CreateWeightStatistic extends Command
     {
         $yesterday = date("Y-m-d",strtotime("-1 day"));
         $sql = <<<sql
-SELECT DATE_FORMAT(order_packages.created_at,'%Y-%m-%d') date,
+SELECT DATE_FORMAT(order_packages.created_at,'%Y-%m-%d') date,IFNULL(order_packages.measuring_machine_id, 0) measuring_machine_id,order_packages.owner_id
 SUM(CASE WHEN order_packages.weighed_at IS NOT NULL THEN 1 ELSE 0 END) AS count,
-COUNT(1) total FROM order_packages LEFT JOIN orders ON order_packages.order_id=orders.id WHERE orders.wms_status != '订单取消'
-AND order_packages.created_at BETWEEN '{$yesterday} 00:00:00' AND '{$yesterday} 23:59:59' GROUP BY date
+COUNT(1) total FROM order_packages LEFT JOIN orders ON order_packages.order_id=orders.id
+WHERE orders.wms_status != '订单取消'
+AND order_packages.created_at BETWEEN '{$yesterday} 00:00:00' AND '{$yesterday} 23:59:59' GROUP BY date,order_packages.measuring_machine_id,order_packages.owner_id
 sql;
-        $result = DB::selectOne(DB::raw($sql));
-        if (!$result)$obj = [
-            "targeted_at"    => $yesterday,
-            "un_weigh_count" => 0,
-            "total_count"    => 0
-        ]; else $obj = [
-            "targeted_at"    => $result->date,
-            "un_weigh_count" => $result->count,
-            "total_count"    => $result->total,
-        ];
-        /** @var \stdClass $model */
-        $model = OrderPackageCountingRecord::query()->create($obj);
-        Cache::put("weight.".$yesterday,[
-            "date"=>$yesterday,
-            "total"=>$model->total_count,
-            "count"=>$model->un_weigh_count,
-            "value"=>$model->total_count ? intval(($model->un_weigh_count/$model->total_count)*100) : 0
-        ]);
+        $result = DB::select(DB::raw($sql));
+        if (!$result) {
+            $obj = [
+                "targeted_at" => $yesterday,
+                "un_weigh_count" => 0,
+                "total_count" => 0,
+                "measuring_machine_id" => 0,
+                "owner_id" => 0
+            ];
+            $model = OrderPackageCountingRecord::query()->create($obj);
+            Cache::put("weight.".$yesterday, $obj);
+        }else{
+            $objs = [];
+            foreach ($result as $v){
+                $obj = [
+                    "targeted_at"    => $v->date,
+                    "un_weigh_count" => $v->count,
+                    "total_count"    => $v->total,
+                    "measuring_machine_id"    => $v->measuring_machine_id,
+                    "owner_id"    => $v->owner_id
+                ];
+                $model = OrderPackageCountingRecord::query()->create($obj);
+                array_push($objs, $obj);
+            }
+            Cache::put("weight.".$yesterday, $objs);
+        }
     }
 }

+ 57 - 39
app/Http/Controllers/ControlPanelController.php

@@ -7,6 +7,7 @@ use App\Filters\OrderPackageReceivedSyncRecordFilters;
 use App\OrderPackageCountingRecord;
 use App\OrderPackageReceivedSyncRecord;
 use App\Owner;
+use App\MeasuringMachine;
 use App\Services\CacheService;
 use App\Services\CheckActiveMenuService;
 use App\Services\LaborReportsCountingRecordService;
@@ -124,41 +125,49 @@ class ControlPanelController extends Controller
         //转化为Carbon
         $start = Carbon::parse(request("start"));
         $end   = Carbon::parse(request("end"));
+        $owner = request("owner_ids");
 
         //定义三个数组 空间换时间 避免结果集二次转换
         $title = []; //标题
         $data = []; //核心数据,二维数组
-        foreach (CarbonPeriod::create($start,$end) as $date){
-            /** @var $date Carbon */
-            $str = $date->format("Y-m-d");
-            $data = $this->getTargetData($str);
-            $title[] = $str;
-        }
-
         //大于31天转换为月份显示
         if ($end->diffInDays($start) > 31){
+            $time1 = strtotime($start);
+            $time2 = strtotime($end);
             $title = [];
-            $sign = []; //标记是否已被插入
-            $dataTemp = []; //临时存储
-
-            foreach ($data as $datum){
-                $month = substr($datum["date"],0,7);
-                if (!isset($sign[$month])){
-                    $dataTemp[] = ["date"=>$month,"total"=>$datum["total"],"count"=>$datum["count"],"value"=>$datum["value"]];
-                    $title[] = $month;
-                    $sign[$month] = count($dataTemp)-1;
-                }else{
-                    $dataTemp[$sign[$month]]["total"] += $datum["total"];
-                    $dataTemp[$sign[$month]]["count"] += $datum["count"];
-                    $dataTemp[$sign[$month]]["value"] = (string)($dataTemp[$sign[$month]]["total"] ? intval(($dataTemp[$sign[$month]]["count"]/$dataTemp[$sign[$month]]["total"])*100) : 0);
-                }
+            do{
+                $str = date('Y-m',$time1); // 取得递增月;
+                $data[] = $this->getTargetData($str, $owner);
+                $title[] = $str;
+            }while( ($time1 = strtotime('+1 month', $time1)) <= $time2);
+            $start = $title[0];
+        }else{
+            foreach (CarbonPeriod::create($start,$end) as $date){
+                /** @var $date Carbon */
+                $str = $date->format("Y-m-d");
+                $data[] = $this->getTargetData($str, $owner);
+                $title[] = $str;
             }
-            $data = $dataTemp;
+            $start = date('Y-m-d', strtotime($start));
         }
 
+        $machines = MeasuringMachine::query()->select('id')->get()->toArray();
+        array_unshift($machines, ['id' => 0]);
+        array_unshift($machines, ['id' => '未称重']);
+
+        //data数据处理
+        $real_data = [];
+        foreach ($machines as $v){
+            $temp = [$v['id'] === 0 ? 'ID_未知' : 'ID_'.$v['id']];
+            foreach ($data as $val){
+                array_push($temp, array_column($val, $v['id'])? array_sum( array_column($val, $v['id'])) : 0);
+            }
+            array_push($real_data,$temp);
+        }
         array_unshift($title, 'product');
-        array_unshift($data, $title);
-        $this->success(["title"=>date("Y-m-d",strtotime($start)),"data"=>$data]);
+        array_unshift($real_data, $title);
+
+        $this->success(["title"=> $start,"data"=>$real_data]);
     }
 
 
@@ -209,36 +218,45 @@ class ControlPanelController extends Controller
      * @param string $date
      * @return array|null
      */
-    private function getTargetData(string $date)
+    private function getTargetData(string $date, array $owner = [])
     {
-        $res = [];
-        if ($date == date("Y-m-d",1622908800)){
+        $res = [];$where='';$no_weight  = 0;
+        if ($owner) $where = " and order_packages.owner_id in (".implode(',',$owner).")";
+        if ($date == date("Y-m-d")){
             $sql = <<<sql
-SELECT DATE_FORMAT(order_packages.created_at,'%Y-%m-%d') date,IFNULL(mm.name,'未知') name ,
+SELECT DATE_FORMAT(order_packages.created_at,'%Y-%m-%d') date,IFNULL(order_packages.measuring_machine_id, 0) measuring_machine_id,
 SUM(CASE WHEN order_packages.weighed_at IS NOT NULL THEN 1 ELSE 0 END) AS count,
 COUNT(1) total FROM order_packages LEFT JOIN orders ON order_packages.order_id=orders.id
-LEFT JOIN measuring_machines AS mm ON mm.id = order_packages.measuring_machine_id
-WHERE orders.wms_status != '订单取消'
+WHERE orders.wms_status != '订单取消'  {$where}
 AND order_packages.created_at like '{$date}%' GROUP BY date,order_packages.measuring_machine_id
 sql;
             //todo 新写
             $info = DB::select(DB::raw($sql));
-            if (!$info) return  $res;
-            $no_weight  =  isset($info[0]->name)  && $info[0]->name == '未知' ? $info[0]->total - $info[0]->count : 0;
+            if (empty($info)) return  $res;
             foreach ($info as $v){
-                $res[] = [$v->name,$v->count];
+                $res[] = [$v->measuring_machine_id,(int)$v->count];
+                $no_weight += (int)($v->total_count - $v->un_weigh_count);
             }
             array_push($res, ['未称重',$no_weight]);
         }else{
-            $info = app(CacheService::class)->getOrExecute("weight.".$date,function ()use($date){
-                return OrderPackageCountingRecord::query()->where("targeted_at",$date)->get()->toArray();
+            $info = app(CacheService::class)->getOrExecute("weight.".$date.($owner?implode(',',$owner):''),function ()use($date,$owner){
+                return OrderPackageCountingRecord::query()
+                    ->where(function ($query)use($date, $owner){
+                        if($owner)return $query->whereIn('owner_id',$owner);
+                        if ( strlen($date) > 8 ) {
+                            return $query->where('targeted_at',$date);
+                        }else{
+                            return $query->where('targeted_at', 'like',$date.'%');
+                        }
+                    })
+                    ->get()->toArray();
             },config("cache.expirations.forever"));
-            if (array_key_exists('date',$info)) return  $res;
-            $no_weight  =  isset($info[0]->name)  && $info[0]->name == '未知' ? $info[0]->total - $info[0]->count : 0;
+            if (empty($info)) return  $res;
             foreach ($info as $v){
-                $res[] = [$v->name,$v->count];
+                $res[] = [$v['measuring_machine_id']=>(int)$v['un_weigh_count']];
+                $no_weight += (int)($v['total_count'] - $v['un_weigh_count']);
             }
-            array_push($res, ['未称重',$no_weight]);
+            array_push($res, ['未称重'=>$no_weight]);
         }
         return $res;
     }

+ 50 - 5
app/Http/Controllers/TestController.php

@@ -6,11 +6,14 @@ use App\Components\AsyncResponse;
 use App\Components\ErrorPush;
 use App\ErrorTemp;
 use App\Feature;
+use App\Jobs\OrderCreateWaybill;
 use App\MaterialBox;
 use App\MaterialBoxModel;
+use App\Order;
 use App\Owner;
 use App\OwnerFeeDetail;
 use App\OwnerPriceOperation;
+use App\OrderPackageCountingRecord;
 use App\RejectedBill;
 use App\Services\ForeignHaiRoboticsService;
 use App\Station;
@@ -21,6 +24,7 @@ use App\Unit;
 use App\Waybill;
 use Illuminate\Database\Eloquent\Collection;
 use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Cache;
 use Illuminate\Support\Facades\Auth;
 use Illuminate\Support\Facades\Cache;
 use Illuminate\Support\Facades\Cookie;
@@ -59,11 +63,52 @@ class TestController extends Controller
     private $key = "CACHE_SHELF_AVAILABLE";
     public function test()
     {
-        $a = new Collection(["a","b"]);
-        dd($a->filter(function ($b){
-            if ($b=="a")return true;
-            else return false;
-        }));
+        $w = Waybill::query()->first();
+        $w->loadCount(["waybillAuditLogs"]);
+        dd($w);
+    }
+
+    public function addRecord()
+    {
+        $yesterday = '2021-06-08';
+        $sql = <<<sql
+SELECT DATE_FORMAT(order_packages.created_at,'%Y-%m-%d') date,IFNULL(order_packages.measuring_machine_id,0) measuring_machine_id,order_packages.owner_id,
+SUM(CASE WHEN order_packages.weighed_at IS NOT NULL THEN 1 ELSE 0 END) AS count,
+COUNT(1) total FROM order_packages LEFT JOIN orders ON order_packages.order_id=orders.id
+WHERE orders.wms_status != '订单取消'
+AND order_packages.created_at BETWEEN '{$yesterday} 00:00:00' AND '{$yesterday} 23:59:59' GROUP BY date,order_packages.measuring_machine_id,order_packages.owner_id
+sql;
+        $result = DB::select(DB::raw($sql));
+        if (!$result) {
+            $obj = [
+                "targeted_at" => $yesterday,
+                "un_weigh_count" => 0,
+                "total_count" => 0,
+                "measuring_machine_id" => 0,
+                "owner_id" => 0
+            ];
+            $model = OrderPackageCountingRecord::query()->create($obj);
+            Cache::put("weight.".$yesterday, $obj);
+        }else{
+            $objs = [];
+            foreach ($result as $v){
+                $obj = [
+                    "targeted_at"    => $v->date,
+                    "un_weigh_count" => $v->count,
+                    "total_count"    => $v->total,
+                    "measuring_machine_id"    => $v->measuring_machine_id,
+                    "owner_id"    => $v->owner_id
+                ];
+                $model = OrderPackageCountingRecord::query()->create($obj);
+                array_push($objs, $obj);
+            }
+            Cache::put("weight.".$yesterday, $objs);
+        }
+    }
+
+    public function redis()
+    {
+        Cache::pull('weight.2021-06-06');
     }
 
 }

+ 58 - 55
app/Http/Controllers/WaybillController.php

@@ -118,69 +118,72 @@ class WaybillController extends Controller
     public function update(Request $request, $id,WaybillPriceModelService $waybillPriceModelService,
                            LogisticService $logisticService,WaybillPayoffService $waybillPayoffService)
     {
-        if(!Gate::allows('运输管理-运单-调度')){ return redirect(url('/'));  }
-        if (!$request->warehouse_weight && $request->warehouse_weight_unit_id){
-            $request->offsetUnset('warehouse_weight_unit_id');
-        }
-        if (!$request->warehouse_weight_other && $request->warehouse_weight_unit_id_other){
-            $request->offsetUnset('warehouse_weight_unit_id_other');
-        }
-        if (!$request->carrier_weight && $request->carrier_weight_unit_id){
-            $request->offsetUnset('carrier_weight_unit_id');
-        }
-        if (!$request->carrier_weight_other && $request->carrier_weight_unit_id_other){
-            $request->offsetUnset('carrier_weight_unit_id_other');
-        }
+        if(!Gate::allows('运输管理-运单-调度')){ return view("exception.authority");  }
+        if (!$request->warehouse_weight && $request->warehouse_weight_unit_id)$request->offsetUnset('warehouse_weight_unit_id');
+        if (!$request->warehouse_weight_other && $request->warehouse_weight_unit_id_other)$request->offsetUnset('warehouse_weight_unit_id_other');
+        if (!$request->carrier_weight && $request->carrier_weight_unit_id)$request->offsetUnset('carrier_weight_unit_id');
+        if (!$request->carrier_weight_other && $request->carrier_weight_unit_id_other)$request->offsetUnset('carrier_weight_unit_id_other');
         $this->validatorWaybillDispatch($request,$id)->validate();
         $waybillPayoffParam = [];
         $waybillPayoffParam['total_receivable']=0;
         /** @var WaybillService */
-        $waybill = app('waybillService')->update($request,$id);
-        if ($waybill->type=="直发车"){
-            if ($waybill->charge)$waybillPayoffParam['total_receivable'] = ($waybill->charge);
-            elseif ($waybill->collect_fee)$waybillPayoffParam['total_receivable'] = ($waybill->collect_fee);
-            $waybillPayoffParam['total_expense'] = ($waybill->fee)+($waybill->other_fee)-($waybill->collect_fee);
-        }else {
-            $waybillPriceModel_id=$request->input('waybillPriceModel');
-            if ($waybillPriceModel_id){
-                $carrier_weight=$request->input('carrier_weight');
-                $waybillPriceModel=$waybillPriceModelService->find($waybillPriceModel_id);
-                $logistic=$logisticService->find($waybill->logistic_id);
-                if ($carrier_weight<$waybillPriceModel->initial_weight){
-                    $fee=(($waybillPriceModel->unit_price)*($waybillPriceModel->initial_weight))+$logistic->delivery_fee;
-                }else{
-                    $fee=(($waybillPriceModel->unit_price)*$carrier_weight)+$logistic->delivery_fee;
+        $waybill = app('waybillService')->find($id);
+        $oldBill = $waybill->carrier_bill;
+        DB::beginTransaction();
+        try {
+            $waybill = app('waybillService')->update($waybill, $request->input());
+            if ($waybill->type=="直发车"){
+                if ($waybill->charge)$waybillPayoffParam['total_receivable'] = ($waybill->charge);
+                elseif ($waybill->collect_fee)$waybillPayoffParam['total_receivable'] = ($waybill->collect_fee);
+                $waybillPayoffParam['total_expense'] = ($waybill->fee)+($waybill->other_fee)-($waybill->collect_fee);
+            }else {
+                $waybillPriceModel_id=$request->input('waybillPriceModel');
+                if ($waybillPriceModel_id){
+                    $carrier_weight=$request->input('carrier_weight');
+                    $waybillPriceModel=$waybillPriceModelService->find($waybillPriceModel_id);
+                    $logistic=$logisticService->find($waybill->logistic_id);
+                    if ($carrier_weight<$waybillPriceModel->initial_weight){
+                        $fee=(($waybillPriceModel->unit_price)*($waybillPriceModel->initial_weight))+$logistic->delivery_fee;
+                    }else{
+                        $fee=(($waybillPriceModel->unit_price)*$carrier_weight)+$logistic->delivery_fee;
+                    }
+                    if ($waybillPriceModel->base_fee&&$fee<$waybillPriceModel->base_fee){
+                        $fee=$waybillPriceModel->base_fee;
+                    }
+                    $waybill->fee=$fee;
+                    $waybill->waybill_price_model_id=$waybillPriceModel_id;
                 }
-                if ($waybillPriceModel->base_fee&&$fee<$waybillPriceModel->base_fee){
-                    $fee=$waybillPriceModel->base_fee;
+                $waybill->save();
+                if ($waybill->charge)$waybillPayoffParam['total_receivable'] = ($waybill->charge);
+                elseif($waybill->collect_fee) {
+                    $waybillPayoffParam['total_receivable'] = $waybill->collect_fee;
                 }
-                $waybill->fee=$fee;
-                $waybill->waybill_price_model_id=$waybillPriceModel_id;
+                $waybillPayoffParam['total_expense'] = ($waybill->pick_up_fee)+($waybill->other_fee)+($waybill->fee);
             }
-            $waybill->save();
-            if ($waybill->charge)$waybillPayoffParam['total_receivable'] = ($waybill->charge);
-            elseif($waybill->collect_fee) {
-                $waybillPayoffParam['total_receivable'] = $waybill->collect_fee;
+            if ($waybillPayoffParam['total_receivable'] > 0){
+                $waybillPayoffParam['waybill_id'] = $id;
+                $waybillPayoffParam['gross_margin'] = $waybillPayoffParam['total_receivable'] - $waybillPayoffParam['total_expense'];
+                $waybillPayoffParam['gross_profit_rate'] = $waybillPayoffParam['gross_margin']/$waybillPayoffParam['total_receivable'];
+                $waybillPayoffService->updateOrCreate($waybillPayoffParam);
             }
-            $waybillPayoffParam['total_expense'] = ($waybill->pick_up_fee)+($waybill->other_fee)+($waybill->fee);
-        }
-        if ($waybillPayoffParam['total_receivable'] > 0){
-            $waybillPayoffParam['waybill_id'] = $id;
-            $waybillPayoffParam['gross_margin'] = $waybillPayoffParam['total_receivable'] - $waybillPayoffParam['total_expense'];
-            $waybillPayoffParam['gross_profit_rate'] = $waybillPayoffParam['gross_margin']/$waybillPayoffParam['total_receivable'];
-            $waybillPayoffService->updateOrCreate($waybillPayoffParam);
-        }
-        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
-        WaybillAuditLog::query()->create([
-            'waybill_id'=>$id,
-            'audit_stage'=>'发起调度',
-            'user_id'=>Auth::id(),
-        ]);
-        //todo 若是德邦物流 请求API创建快递单号
-        $logistic_ids = Logistic::query()->where('name','like', '德邦%')->where('type','=','物流')->pluck('id')->toArray();
-        if (in_array($request['logistic_id'], $logistic_ids)){
-            $res = app('DbOpenService')->getDbOrderNo(['id' => $id]);
-            $msg =  $res['msg']? "【申请德邦物流单号:".$res['msg']."】"  :'';
+            $stage = "发起调度";
+            if ($waybill->type=='德邦物流' && !$oldBill){
+                $bill = app('DbOpenService')->getDbOrderNo($waybill);
+                if (!$bill){DB::rollBack();return "获取德邦单号失败,德邦服务异常";}
+                $waybill->update(["carrier_bill"=>$bill]);
+                $msg =  "【申请德邦物流单号:".$bill."】";
+                if (!app("WaybillService")->notifyFlux($waybill))$msg .= ",通知FLUX失败";
+                $stage = '发起德邦调度';
+            }
+            WaybillAuditLog::query()->create([
+                'waybill_id'    =>  $id,
+                'audit_stage'   =>  $stage,
+                'user_id'       =>  Auth::id(),
+            ]);
+            DB::commit();
+        }catch (\Exception $e){
+            DB::rollBack();
+            return "调度失败".$e->getMessage();
         }
         return redirect('transport/waybill/index')->with('successTip','运单“'.$waybill->waybill_number.'”调度成功 '. ($msg??''));
     }

+ 1 - 1
app/Http/Controllers/api/thirdPart/flux/WaybillController.php

@@ -126,7 +126,7 @@ class WaybillController extends Controller
             $waybill->update();
             if (!$waybill->order_id && $waybill->wms_bill_number)dispatch(new HandleExceptionWaybill($waybill))->delay(now()->addMinutes(15));
             //回传FLUX
-            $this->accomplishToWMS($waybill);
+            if ($prefix != 'BSDB') $this->accomplishToWMS($waybill);
         }
         return response()->json(['response'=>['return'=>['returnFlag'=>'1','returnCode'=>'0000','returnDesc'=>'正确接收','resultInfo'=>'']]])
             ->setEncodingOptions(JSON_UNESCAPED_UNICODE);

+ 38 - 0
app/Jobs/OrderCreateWaybill.php

@@ -0,0 +1,38 @@
+<?php
+
+namespace App\Jobs;
+
+use App\Order;
+use Illuminate\Bus\Queueable;
+use Illuminate\Contracts\Queue\ShouldQueue;
+use Illuminate\Foundation\Bus\Dispatchable;
+use Illuminate\Queue\InteractsWithQueue;
+
+class OrderCreateWaybill implements ShouldQueue
+{
+    use Dispatchable, InteractsWithQueue, Queueable;
+
+    private $arr;
+    /**
+     * Create a new job instance.
+     *
+     * @return void
+     */
+    public function __construct(array $arr)
+    {
+        $this->arr = $arr;
+    }
+
+    /**
+     * Execute the job.
+     *
+     * @return void
+     */
+    public function handle()
+    {
+        if (!$this->arr)return;
+        $codes = array_column($this->arr,"code");
+        $orders = Order::query()->with("logistic")->where("code",$codes)->get();
+        foreach ($orders as $order) app("WaybillService")->createDbBill($order);
+    }
+}

+ 1 - 1
app/OrderPackageCountingRecord.php

@@ -11,7 +11,7 @@ class OrderPackageCountingRecord extends Model
     use ModelLogChanging;
 
     protected $fillable=[
-        "targeted_at","un_weigh_count","total_count"
+        "targeted_at","un_weigh_count","total_count","measuring_machine_id","owner_id"
     ];
     public $timestamps=false;
 

+ 2 - 0
app/Providers/AppServiceProvider.php

@@ -107,6 +107,7 @@ use App\Services\UserOwnerGroupService;
 use App\Services\UserService;
 use App\Services\WarehouseService;
 use App\Services\WaybillFinancialService;
+use App\Services\WaybillService;
 use App\Services\WeighExceptedService;
 use App\Services\OrderFreezeService;
 use App\Services\RegionService;
@@ -378,6 +379,7 @@ class AppServiceProvider extends ServiceProvider
         app()->singleton('WarehouseService', WarehouseService::class);
         app()->singleton('WaybillFinancialService', WaybillFinancialService::class);
         app()->singleton('WeighExceptedService', WeighExceptedService::class);
+        app()->singleton('WaybillService', WaybillService::class);
     }
 
     private function registerObserver()

+ 103 - 132
app/Services/DbOpenService.php

@@ -2,155 +2,45 @@
 
 namespace App\Services;
 
-use App\Log;
-use App\OracleDOCOrderHeader;
-use App\OrderLogistic;
+use App\Components\ErrorPush;
 use App\Traits\ServiceAppAop;
-use App\Waybill;
-use Illuminate\Support\Carbon;
-use Illuminate\Support\Facades\DB;
+use Illuminate\Database\Eloquent\Model;
 
 
 class DbOpenService
 {
-    use ServiceAppAop;
+    use ServiceAppAop, ErrorPush;
 
     protected $modelClass = DbOpenService::class;
 
     /**
      * 创建德邦订单,生成快递单号
-     * @param array $params
+     * @param Model|\stdClass $waybill
+     *
+     * @return string|null
+     * @throws \Throwable
      */
-    public function getDbOrderNo(array $params = []):array
+    public function getDbOrderNo($waybill):?string
     {
-        //获取系统无快递单号订单信息
-        $order_info = Waybill::query()
-            ->with(['owner:id,name,phone_number', 'order', 'order.shop:id,name',
-                'order.warehouse:id,province_id,city_id,county_id,address',
-                'order.warehouse.province:id,name', 'order.warehouse.city:id,name',
-                'order.warehouse.county:id,name', 'deliveryType:id,name'])
-            ->where('id', '=', $params['id'])
-            ->first();
-        //请求德邦API 生成新订单
-        $model = new OrderLogistic();
+        $waybill->loadCount(["waybillAuditLogs"=>function($query){
+            $query->where("audit_stage","发起德邦调度");
+        }]);
+        if ($waybill->waybill_audit_logs_count>0)return null;
         $header = [
             'Content-Type' => 'application/x-www-form-urlencoded;charset=utf-8',
             "Accept" => "application/json"
         ];
-        if ($order_info) {
-            if (empty($order_info->order) || empty($order_info->owner) || empty($order_info->order->shop)) return ['code' => 0, 'msg' => '订单关联信息错误,请核实'];
-            $res = $model->isExist($order_info->order->id);
-            if (!$res || $res->status == 0 ?? 0) {
-                $data = [
-                    'logisticID' => config('api_logistic.DB.prod.sign') . date("YmdHis") . mt_rand(1000, 9999) . $order_info->order->id,
-                    'custOrderNo' => $order_info->order->client_code ?? '',
-                    // 'mailNo' => '',  // 不传会创建新的 运单号
-                    'needTraceInfo' => config('api_logistic.DB.prod.needTraceInfo'),
-                    'companyCode' => config('api_logistic.DB.prod.company_code'),
-                    'orderType' => $order_info->order_type,
-                    'transportType' => $order_info->transport_type,
-                    'customerCode' => config('api_logistic.DB.prod.customer_Code'),
-                    'sender' => [
-                        'companyName' => $order_info->order->shop->name ?? '',
-                        'businessNetworkNo' => '',
-                        'name' => $order_info->owner->name ?? '',
-                        'mobile' => $order_info->owner->phone_number ?? '',
-                        'phone' => $order_info->owner->phone_number ?? '',
-                        'province' => $order_info->order->warehouse->province->name ?? '',
-                        'city' => $order_info->order->warehouse->city->name ?? '',
-                        'country' => $order_info->order->warehouse->county->name ?? '',
-                        'town' => '',
-                        'address' => $order_info->order->warehouse->address ?? '',
-                    ],
-                    'receiver' => [
-                        'toNetworkNo' => '',
-                        'name' => $order_info->order->consignee_name ?? '',
-                        'phone' => $order_info->order->consignee_phone ?? '',
-                        'mobile' => $order_info->order->consignee_phone ?? '',
-                        'province' => $order_info->order->province ?? '',
-                        'city' => $order_info->order->city ?? "",
-                        'county' => $order_info->order->district ?? '',
-                        'town' => '',
-                        'address' => $order_info->order->address ?? '',
-                        'companyName' => ''
-                    ],
-                    'packageInfo' => [
-                        'cargoName' => $order_info->cargo_name ?? '',
-                        'totalNumber' => $order_info->total_number ?? '',
-                        'totalWeight' => $order_info->total_weight ?? '',
-                        'totalVolume' => '',
-                        'packageService' => $order_info->package_service ?? '',
-                        'deliveryType' => $order_info->deliveryType->name ?? '',
-                    ],
-                    'gmtCommit' => date('Y-m-d H:i:s'),
-                    'payType' => $order_info->pay_type,
-                    'addServices' => [
-                        'insuranceValue' => '',
-                        'codType' => '',
-                        'reciveLoanAccount' => '',
-                        'accountName' => '',
-                        'codValue' => '',
-                        'backSignBill' => $order_info->back_sign_bill
-                    ],
-                    'smsNotify' => config('api_logistic.DB.prod.smsNotify'),
-                    'sendStartTime' => date("Y-m-d H:i:s"),
-                    'sendEndTime' => $order_info->deliver_at ?? date("Y-m-d H:i:s", strtotime('+1 day')),
-                    'originalWaybillNumber' => $order_info->wms_bill_number ?? '',
-                    'remark' => $order_info->dispatch_remark ?? '',
-                    'isOut' => 'N',
-                    'passwordSigning' => config('api_logistic.DB.prod.passwordSigning'),
-                    'isdispatched' => '',
-                    'ispresaleorder' => '',
-                    'isCenterDelivery' => '',
-                    'orderExtendFields' => [
-                        'value' => '',
-                        'key' => ''
-                    ]
-                ];
-                $param = json_encode($data,1);
-                $dd["params"] = $param;
-                $dd["timestamp"] = (integer)getMillisecond();
-                $dd["digest"] = base64_encode(md5($param . config('api_logistic.DB.prod.app_key') . $dd['timestamp']));
-                $dd["companyCode"] = config('api_logistic.DB.prod.company_code');
-                $return = httpPost(config('api_logistic.DB.prod.uri')['create_order'], $dd, $header);
-                unset($data);
-                $id = $params['id'];
-                $order_no = $order_info->wms_bill_number;
-                if (array_key_exists('result', $return)) {
-                    //请求成功  快递单号 $return['mailNo']   请求编号 $return['uniquerRequestNumber']
-                    //返回日志记录
-                    $mail_no = $return['mailNo']??'';
-                    $add_data = [
-                        'order_id' => $order_info->order->id,
-                        'status' => $return['result'] == 'true' ? 1 : 0,
-                        'code' => $mail_no ?? '',
-                        'uniquer_request_number' => $return['uniquerRequestNumber'],
-                        'reason' => $return['reason'] ?? '',
-                        'created_at' => date('Y-m-d H:i:s')
-                    ];
-                    $roe = OrderLogistic::query()->insertGetId($add_data);
-                    if ($roe && $return['result'] == 'true') {
-                        DB::connection('mysql')->transaction(function () use ($id, $order_no, $mail_no) {
-                            $update_data = [
-                                'type' => '德邦物流',
-                                'waybill_number' => $mail_no,
-                                'updated_at' => date('Y-m-d H:i:s')
-                            ];
-                            Waybill::query()->where('id', '=', $id)->update($update_data);
-                            DB::connection('oracle')->transaction(function () use ($order_no, $mail_no) {
-                                OracleDOCOrderHeader::query()->where('orderno', $order_no)->update(['edittime' => Carbon::now(), 'soreference5' => $mail_no]);
-                            });
-                            LogService::log(__METHOD__, "申请快递单号回传WMS", ['orderno' => $order_no, 'soreference5' => $mail_no, 'edittime' => date('Y-m-d H:i:s')]);
-                        });
-                        return ['code' => 1, 'msg' => '申请德邦物流单号成功'];
-                    }
-                }
-                LogService::log(__METHOD__, "申请快递单号回传WMS", ['orderno' => $order_no, 'content'=> $return]);
-                return ['code' => 0, 'msg' => $return['reason']];
-            }
-            elseif($res->status == 1 ?? 0 ) return ['code' => 1, 'msg'=> '德邦快递单号已存在'];
+        $body = $this->formatWaybillData($waybill);
+
+        try {
+            $response = httpPost(config('api_logistic.DB.prod.uri')['create_order'], $body, $header);
+            if (!$response["result"])return null;
+            return $response['mailNo'] ?? '';
+            //OracleDOCOrderHeader::query()->where('orderno', $order_no)->update(['edittime' => Carbon::now(), 'soreference5' => $mail_no]);
+        }catch (\Exception $e){
+            $this->push(__METHOD__."->".__LINE__,"德邦接口请求失败",$e->getMessage() . ' | '.json_encode($response ?? ''));
+            return null;
         }
-        return ['code' => 0, 'msg' => '订单信息错误,请核实'];
     }
 
     /**
@@ -179,4 +69,85 @@ class DbOpenService
         }
         return ['code' => 0, 'msg' => '暂无物流信息'];
     }
+
+    /**
+     * @param Model|\stdClass $waybill
+     */
+    private function formatWaybillData($waybill):array
+    {
+        $waybill->loadMissing([
+            "order.shop","owner","order.warehouse.province","order.warehouse.city","order.warehouse.county","deliveryType"
+        ]);
+        $date = date('Y-m-d H:i:s');
+        $data =  [
+            'logisticID'    =>      config('api_logistic.DB.prod.sign').date("YmdHis").mt_rand(1000, 9999).$waybill->order->id,
+            'custOrderNo'   =>      $waybill->order->client_code ?? '',
+            'needTraceInfo' =>      config('api_logistic.DB.prod.needTraceInfo'),
+            'companyCode'   =>      config('api_logistic.DB.prod.company_code'),
+            'orderType'     =>      $waybill->order_type,
+            'transportType' =>      $waybill->transport_type,
+            'customerCode'  =>      config('api_logistic.DB.prod.customer_Code'),
+            'sender'        =>      [
+                'companyName'       => $waybill->order->shop->name ?? '',
+                'businessNetworkNo' => '',
+                'name'              => $waybill->owner->name ?? '',
+                'mobile'            => $waybill->owner->phone_number ?? '',
+                'phone'             => $waybill->owner->phone_number ?? '',
+                'province'          => $waybill->order->warehouse->province->name ?? '',
+                'city'              => $waybill->order->warehouse->city->name ?? '',
+                'country'           => $waybill->order->warehouse->county->name ?? '',
+                'town'              => '',
+                'address'           => $waybill->order->warehouse->address ?? '',
+            ],
+            'receiver' => [
+                'toNetworkNo'       => '',
+                'name'              => $waybill->order->consignee_name ?? '',
+                'phone'             => $waybill->order->consignee_phone ?? '',
+                'mobile'            => $waybill->order->consignee_phone ?? '',
+                'province'          => $waybill->order->province ?? '',
+                'city'              => $waybill->order->city ?? "",
+                'county'            => $waybill->order->district ?? '',
+                'town'              => '',
+                'address'           => $waybill->order->address ?? '',
+                'companyName'       => ''
+            ],
+            'packageInfo' => [
+                'cargoName'         => $waybill->cargo_name ?? '',
+                'totalNumber'       => $waybill->total_number ?? '',
+                'totalWeight'       => $waybill->total_weight ?? '',
+                'totalVolume'       => '',
+                'packageService'    => $waybill->package_service ?? '',
+                'deliveryType'      => $waybill->deliveryType->name ?? '',
+            ],
+            'gmtCommit'     =>  $date,
+            'payType'       =>  $waybill->pay_type,
+            'addServices'   =>  [
+                'insuranceValue'    => '',
+                'codType'           => '',
+                'reciveLoanAccount' => '',
+                'accountName'       => '',
+                'codValue'          => '',
+                'backSignBill'      => $waybill->back_sign_bill
+            ],
+            'smsNotify'     => config('api_logistic.DB.prod.smsNotify'),
+            'sendStartTime' => $date,
+            'sendEndTime'   => $waybill->deliver_at ?? date("Y-m-d H:i:s", strtotime('+1 day')),
+            'originalWaybillNumber' => $waybill->wms_bill_number ?? '',
+            'remark'        => $waybill->dispatch_remark ?? '',
+            'isOut'         => 'N',
+            'passwordSigning' => config('api_logistic.DB.prod.passwordSigning'),
+            'isdispatched'  => '',
+            'ispresaleorder'=> '',
+            'isCenterDelivery' => '',
+            'orderExtendFields' => [
+                'value'     => '',
+                'key'       => ''
+            ]
+        ];
+        $param = json_encode($data,1);
+        $timestamp = (integer)getMillisecond();
+        return ["params"=>$param,"timestamp"=>$timestamp,
+            "digest"=>base64_encode(md5($param.config('api_logistic.DB.prod.app_key').$timestamp)),
+            "companyCode" => config('api_logistic.DB.prod.company_code')];
+    }
 }

+ 2 - 0
app/Services/OrderService.php

@@ -5,6 +5,7 @@ namespace App\Services;
 use App\Commodity;
 use App\Feature;
 use App\Jobs\OrderCreateInstantBill;
+use App\Jobs\OrderCreateWaybill;
 use App\Jobs\OrderFreeze;
 use App\Logistic;
 use App\OracleActAllocationDetails;
@@ -712,6 +713,7 @@ class OrderService
                 $arr = $inner_params->toArray();
                 $this->insert($arr,false,false,false);
                 dispatch(new OrderFreeze($arr));
+                //dispatch(new OrderCreateWaybill($arr));
             });
         }
         unset($created_params);

+ 67 - 7
app/Services/WaybillService.php

@@ -2,6 +2,8 @@
 
 namespace App\Services;
 
+use App\Http\Controllers\api\thirdPart\flux\WaybillController;
+use App\Order;
 use App\OwnerFeeDetail;
 use App\Services\common\BatchUpdateService;
 use App\Services\common\QueryService;
@@ -10,6 +12,7 @@ use App\Waybill;
 use App\WaybillAuditLog;
 use Carbon\Carbon;
 use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Database\Eloquent\Model;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Auth;
 use Illuminate\Support\Facades\DB;
@@ -204,15 +207,20 @@ class WaybillService
         return Waybill::query()->find($id);
     }
 
-    public function update(Request $request,$id)
+    /**
+     * 修改物流单
+     *
+     * @param Waybill|\stdClass $waybill
+     * @param array $param
+     * @param $id
+     * @return Model
+     */
+    public function update(Waybill $waybill,array $param)
     {
-        $waybill = $this->find($id);
         //替换换行符
-        if ($request->dispatch_remark) {
-            $request->offsetSet('dispatch_remark', str_replace(["\n","\r"], ' ', $request->dispatch_remark));
-        }
-        if (!$request->destination) $request->offsetSet('destination', $waybill->destination);
-        $waybill->fill($request->input());
+        if ($param["dispatch_remark"] ?? false)$param["dispatch_remark"] = str_replace(["\n","\r"], ' ', $param["dispatch_remark"]);
+        if (!$param["destination"]) $param["destination"] = $waybill->destination;
+        $waybill->fill($param);
         $waybill->update();
         return $waybill;
     }
@@ -277,4 +285,56 @@ class WaybillService
         else OwnerFeeDetail::query()->create($obj);
         return true;
     }
+
+    /**
+     * 生成德邦单据
+     *
+     * @param Order|\stdClass $order
+     *
+     * @return void
+     */
+    public function createDbBill(Order $order)
+    {
+        $order->loadMissing("logistic");
+        if (!$order->logistic || substr($order->logistic->code,0,2) != 'DB')return;
+        if (Waybill::query()->selectRaw("1")->where("wms_bill_number",$order->code)->first())return;
+        $waybill = Waybill::query()->create([
+            'type'=>            "德邦物流",
+            'waybill_number'=>  Uuid::uuid1(),
+            'owner_id'=>        $order->owner_id,
+            'wms_bill_number'=> $order->code,
+            'destination'=>     $order->address,
+            'recipient'=>       $order->consignee_name,
+            'recipient_mobile'=>$order->consignee_phone,
+            'source_bill'=>     $order->client_code,
+            'is_to_pay'=>       strstr($order->logistic->code,'DF')===false ? 0 : 1,
+            'destination_city_id'=>$order->city ? app(RegionService::class)->getCity($order->city) : null,
+            'order_id'=>        $order->id,
+        ]);
+        $waybill->update([
+            "waybill_number" => 'BSDB'.date ("ymd").str_pad($waybill->id>99999?$waybill->id%99999:$waybill->id,4,"0",STR_PAD_LEFT),
+        ]);
+        WaybillAuditLog::query()->create([
+            'waybill_id'=>$waybill->id,
+            'audit_stage'=>'创建',
+            'user_id'=>Auth::id() ?? 0,
+        ]);
+    }
+
+    /**
+     * 通知FLUX新单号
+     *
+     * @param Model|\stdClass $waybill
+     *
+     * @return bool
+     */
+    public function notifyFlux($waybill):bool
+    {
+        /** @var Waybill|\stdClass $w */
+        $w = new Waybill();
+        $w->wms_bill_number = $waybill->wms_bill_number;
+        $w->waybill_number  = $waybill->carrier_bill;
+        $controller = new WaybillController();
+        return $controller->accomplishToWMS($w);
+    }
 }

+ 38 - 0
database/migrations/2021_08_03_154931_change_order_package_counting_records_table.php

@@ -0,0 +1,38 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+class ChangeOrderPackageCountingRecordsTable extends Migration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::table('order_package_counting_records', function (Blueprint $table) {
+            $table->dropColumn('name');
+            $table->bigInteger('measuring_machine_id')->nullable()->comment('外联 设备号');
+            $table->bigInteger('owner_id')->nullable()->comment('外联 货主ID');
+            $table->dropPrimary('targeted_at');
+            $table->index('targeted_at','index_date');
+            $table->unique(['targeted_at','measuring_machine_id','owner_id'],'index_data_id');
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('order_package_counting_records', function (Blueprint $table) {
+            $table->dropColumn('measuring_machine_id');
+            $table->dropColumn('owner_id');
+        });
+    }
+}

+ 31 - 6
resources/views/control/panel.blade.php

@@ -967,7 +967,26 @@
                     let params = {start:this.searchOption.weightDate[0],end:this.searchOption.weightDate[1],owner_ids:this.selectWeightOwners};
                     window.tempTip.postBasicRequest(url,params,res=>{
                         this.cardPool.weight.hideLoading();
-                        this.cardPool.weight.setOption(this._setWeightData(res.title,res.data));
+                        let myechart = this.cardPool.weight, option = this._setWeightData(res.title,res.data);
+                        myechart.on('updateAxisPointer', function (event) {
+                            var xAxisInfo = event.axesInfo[0];
+                            if (xAxisInfo) {
+                                var dimension = xAxisInfo.value + 1;
+                                myechart.setOption({
+                                    series: {
+                                        id: 'pie',
+                                        label: {
+                                            formatter: '{b}: {@[' + dimension + ']} ({d}%)'
+                                        },
+                                        encode: {
+                                            value: dimension,
+                                            tooltip: dimension
+                                        }
+                                    }
+                                });
+                            }
+                        });
+                        myechart.setOption(option);
                     });
                 },
                 loadOrderPackageReceivedSyncRecordInfo(){
@@ -1022,11 +1041,16 @@
                     this.loadExceptionTypeInfo();
                 },
                 _setWeightData(title, data){
-                    let temp = [];
-                    for (let i=1;i<data.length; i++){
+                    let temp = [],len = data.length -1;
+                    for (let i=0; i < len; i++){
                         temp.push({type: 'line', smooth: true, seriesLayoutBy: 'row', emphasis: {focus: 'series'}});
                     }
-                    temp.push({type: 'pie', id: 'pie', radius: '30%', center: ['50%', '25%'], emphasis: {focus: 'data'},
+                    temp.push({
+                        type: 'pie',
+                        id: 'pie',
+                        radius: '30%',
+                        center: ['50%', '25%'],
+                        emphasis: {focus: 'data'},
                         label: {
                             formatter: '{b}: {@'+title+'} ({d}%)'
                         },
@@ -1035,8 +1059,9 @@
                             value: title,
                             tooltip: title
                         }
-                    })
-                    return {
+                    });
+                    console.log(temp)
+                   return {
                         legend: {},
                         tooltip: {
                             trigger: 'axis',