Browse Source

历史计费处理方案

Zhouzhendong 4 năm trước cách đây
mục cha
commit
55507dfae3

+ 12 - 92
app/Http/Controllers/TestController.php

@@ -168,104 +168,24 @@ class TestController extends Controller
         }
     }
 
-    public function format(array $arr,$newRes):array
-    {
-        $result = [];
-        foreach ($arr as $index=>$item){
-            if (isset($result[$item["sku_name"]])){
-                if (array_search($item["self_uid"],$result[$item["sku_name"]])!==false){
-                    $result[$item["sku_name"]][] = $item["next_uid"];
-                }else $result[$index] = $index;
-            }else $result[$item["sku_name"]] = [$item["self_uid"],$item["next_uid"]];
-        }
-        $recursion = [];
-        foreach ($result as $item){
-            if (is_array($item))$newRes[] = $item;
-            else $recursion[$item] = $arr[$item];
-        }
-        if (count($recursion)>0)$newRes = $this->format($recursion,$newRes);
-        return $newRes;
-    }
-    public function socket(){
-        set_time_limit(0);
-        $ip = '127.0.0.1';
-        $port = 1935;
-        if(($sock = \socket_create(AF_INET,SOCK_STREAM,SOL_TCP)) < 0) {
-            echo "socket_create() 失败的原因是:".\socket_strerror($sock)."\n";
-        }
-        if(($ret = \socket_bind($sock,$ip,$port)) < 0) {
-            echo "socket_bind() 失败的原因是:".\socket_strerror($ret)."\n";
-        }
-        if(($ret = \socket_listen($sock,4)) < 0) {
-            echo "socket_listen() 失败的原因是:".\socket_strerror($ret)."\n";
-        }
-        $count = 0;
-        do {
-            if (($msgsock = \socket_accept($sock)) < 0) {
-                echo "socket_accept() failed: reason: " . \socket_strerror($msgsock) . "\n";
-                break;
-            } else {
-                $msg ="测试成功!\n";
-                \socket_write($msgsock, $msg, strlen($msg));
-                echo "测试成功了啊\n";
-                $buf = \socket_read($msgsock,8192);
-                $talkback = "收到的信息:$buf\n";
-                echo $talkback;
-                if(++$count >= 5){break;}
-            }
-            \socket_close($msgsock);
-        }while (true);
-        \socket_close($sock);
+    public function test1(\Closure $c,string $a){
+        dd($c($a));
     }
     public function test(Request $request)
     {
-        $waybill = Waybill::query()->orderByDesc("id")->first();
-        $s = new WaybillObserver();
-        $s->created($waybill);
-        dd(1);
-        /*        $waybill = Waybill::query()->where("type","德邦物流")
-            ->orderByDesc("id")->first();
-        Log::info("w",$waybill->toArray());*/
-        $waybill = json_decode('{"created_at":"2021-12-08 15:46:11","updated_at":"2021-12-08 15:46:11","type":"德邦物流","waybill_number":"BSDB2112084684","source_bill":"199270842873-SDO418677865878","owner_id":"8","wms_bill_number":"SO211208013919","origination":"松江九干仓","destination":"北京市 市辖区 朝阳区 骏豪中央公园广场A2 901","recipient":"刘慧姝","recipient_mobile":"13520176934,13520176934","charge":null,"collect_fee":null,"ordering_remark":null,"logistic_id":null,"carrier_bill":null,"origination_city_id":null,"destination_city_id":"264","warehouse_weight":null,"warehouse_weight_unit_id":null,"carrier_weight":null,"carrier_weight_unit_id":null,"carType_id":null,"fee":null,"pick_up_fee":null,"other_fee":null,"dispatch_remark":null,"waybill_price_model_id":null,"warehouse_weight_other":"0.00","warehouse_weight_unit_id_other":"1","carrier_weight_other":null,"carrier_weight_unit_id_other":null,"car_owner_info":null,"status":"未审核","mileage":null,"amount":null,"inquire_tel":null,"deleted_at":null,"amount_unit_id":null,"other_charge":null,"other_charge_remark":null,"deliver_at":null,"district_id":null,"order_id":"5449678","is_to_pay":"0","cargo_name":null,"total_number":"1","total_weight":null,"deliveryType_id":"3","merge_owner":null,"order_type":"2","transport_type":"JZQY_LONG","pay_type":"2","back_sign_bill":"2","package_service":"木箱","express_face_list":"0","station_no":null,"much_higher_delivery":null,"arrived_org_simple_name":null,"subjoin_fee":"0.000"}',true);
-        Waybill::query()->create($waybill);
-        dd(1);
-        return view('equipment.index');
-        //return response()->json(["info"=>["id"=>1,"name"=>2]]);
-        return response()->json(["info"=>["id"=>1,"name"=>2]]);
-        dd(time());
-        ini_set('max_execution_time',-1);
-        $worker = new Worker('tcp://0.0.0.0:9865');
-
-        $worker->onConnect = function ($conn) {
-            echo '新的连接来了';
+        dd(Order::class);
+        $c = "test";
+        $a = function ($b)use($c){
+            return $b.$c;
         };
-        $worker->onClose = function ($conn) {
-            echo '连接断开了';
-        };
-        $worker->onMessage = function ($conn, $message) {
-            $http_resonse = "HTTP/1.1 200 OK\r\n";
-            $http_resonse .= "Connection: keep-alive\r\n";
-            $http_resonse .= "Server: php socket server\r\n";
-            $http_resonse .= "Content-length: 11\r\n\r\n";
-            $http_resonse .= "hello world";
-            fwrite($conn, $http_resonse);
-        };
-
-        $worker->run();
-        return;
-        $service = new LogisticService();
-        foreach (ReceiveRecord::query()->where("logistic_id",0)->get() as $receive){
-            $name = $service->assertExpressCompany($receive->logistic_number);
-            if ($name){
-                $logistic = Logistic::query()->select("id","name")
-                    ->where("name","like","%{$name}%")->first();
-                $logisticId = $logistic ? $logistic->id : 0;
-            } else $logisticId = 0;
-            if ($logisticId!=0)$receive->update(["logistic_id"=>$logisticId]);
+        $this->test1($a,"a");
+        dd(2);
+        $w = Waybill::query()->get();
+        foreach ($w->chunk(50) as $a){
+            dd($a);
         }
-        dd(ReceiveRecord::query()->where("logistic_id",0)->count());
         $path = '';
-        $id = 115;
+        $id = 252;
 
         $file = fopen($path, "r");
         $user=array();

+ 62 - 0
app/Jobs/ExecutePostBillHandler.php

@@ -0,0 +1,62 @@
+<?php
+
+namespace App\Jobs;
+
+use App\Feature;
+use App\Order;
+use App\Store;
+use Illuminate\Bus\Queueable;
+use Illuminate\Contracts\Queue\ShouldQueue;
+use Illuminate\Database\Eloquent\Collection;
+use Illuminate\Foundation\Bus\Dispatchable;
+use Illuminate\Queue\InteractsWithQueue;
+
+class ExecutePostBillHandler implements ShouldQueue
+{
+    use Dispatchable, InteractsWithQueue, Queueable;
+
+    /**
+     * @var \Closure $closure
+     */
+    protected $closure;
+    /**
+     * @var Collection $collection
+     */
+    protected $collection;
+    /**
+     * @var string $modelClass
+     */
+    protected $modelClass;
+    /**
+     * Create a new job instance.
+     *
+     * @return void
+     */
+    public function __construct(\Closure $closure, Collection $collection, string $modelClass)
+    {
+        $this->closure = $closure;
+        $this->connection = $collection;
+        $this->modelClass = $modelClass;
+    }
+
+    /**
+     * Execute the job.
+     *
+     * @return void
+     */
+    public function handle()
+    {
+        $closure = $this->closure;
+        switch ($this->modelClass){
+            case Store::class:
+                foreach ($this->collection as $detail){
+                    $closure(Feature::MAPPING["store"],$detail->store,$detail);
+                }
+                break;
+            case Order::class:
+                foreach ($this->collection as $detail){
+                    $closure(Feature::MAPPING["order"],$detail->order,$detail);
+                }
+        }
+    }
+}

+ 2 - 2
app/Jobs/HandlePastBill.php

@@ -35,7 +35,7 @@ class HandlePastBill implements ShouldQueue
     public function handle(OwnerPriceOperationService $service)
     {
         ini_set('max_execution_time', 2500);
-        list($rule,$owner,$discountIndex,$pivot) = $this->arr;
-        $service->handlePastBill($rule,$owner,$discountIndex,$pivot);
+        list($rule,$owner,$discountIndex,$pivot,$month) = $this->arr;
+        $service->handlePastBill($rule,$owner,$discountIndex,$pivot,$month);
     }
 }

+ 1 - 1
app/Observers/WaybillObserver.php

@@ -64,7 +64,7 @@ class WaybillObserver
             $update["package_service"] = $waybill->package_service = '托膜';
         }
         if (!$waybill->deliveryType){
-            $update["deliveryType"] = $waybill->deliveryType = 3;
+            $update["deliveryType_id"] = $waybill->deliveryType_id = 3;
         }
         if (!$waybill->pay_type){
             $update["pay_type"] = $waybill->pay_type = Waybill::PAY_TYPE_DEFAULT;

+ 17 - 13
app/Services/OwnerPriceOperationService.php

@@ -4,12 +4,14 @@ namespace App\Services;
 
 use App\Components\ErrorPush;
 use App\Feature;
+use App\Jobs\ExecutePostBillHandler;
 use App\Jobs\HandlePastBill;
-use App\Owner;
+use App\Order;
 use App\OwnerFeeDetail;
 use App\OwnerPriceOperation;
 use App\OwnerPriceOperationItem;
 use App\Services\common\QueryService;
+use App\Store;
 use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Database\Eloquent\Collection;
 use Illuminate\Database\Eloquent\Model;
@@ -242,8 +244,9 @@ class OwnerPriceOperationService
      * @param Model|\stdClass $rule
      * @param integer $owner
      * @param bool|array $result
+     * @param string $month
      */
-    public function handleDiscount(Model $rule, int $owner, $result)
+    public function handleDiscount(Model $rule, int $owner, $result, string $month)
     {
         if (!$result)return;
         $sign = false;
@@ -258,15 +261,15 @@ class OwnerPriceOperationService
             $pivot = app(CacheService::class)->getOrExecute($key,function ()use($key,$targetValue,&$sign,$rule,$owner){
                 return DB::selectOne(DB::raw("SELECT * FROM owner_price_operation_owner WHERE owner_price_operation_id = ? AND owner_id = ? for update"),[$rule->id,$owner]);
             },1000);
-            if ($pivot && (!$pivot->discount_date || substr($pivot->discount_date,0,7)!=date("Y-m") || $pivot->target_value < $targetValue)){
+            if ($pivot && (!$pivot->discount_date || substr($pivot->discount_date,0,7)!=$month || $pivot->target_value < $targetValue)){
                 //未被标记过处理时间或处理时间不为本月,或上次处理值过期,处理历史即时账单
                 $sign = true;
             }
             if ($sign){
                 //先标记成功 这将在后续推进历史单处理流程,防止程序在此堵塞
                 DB::update(DB::raw("UPDATE owner_price_operation_owner SET discount_date = ?,target_value = ? WHERE  owner_price_operation_id = ? AND owner_id = ?"),
-                    [date("Y-m-d"),$targetValue,$rule->id,$owner]);
-                $pivot->discount_date = date("Y-m-d");
+                    [$month."-01",$targetValue,$rule->id,$owner]);
+                $pivot->discount_date = $month."-01";
                 $pivot->target_value = $targetValue;
                 Cache::put($key,$pivot,1000);
             }
@@ -276,7 +279,7 @@ class OwnerPriceOperationService
             $this->push(__METHOD__."->".__LINE__,"即时账单满减处理失败",$exception->getMessage()."  参数".json_encode(array($rule, $owner, $result)));
         }
         //进入历史单处理
-        if ($pivot && $sign)dispatch(new HandlePastBill(array($rule,$owner,$discountIndex,$pivot)));
+        if ($pivot && $sign)dispatch(new HandlePastBill(array($rule,$owner,$discountIndex,$pivot,$month)));
     }
 
     /** 参数顺序: 数量 匹配对象 列映射 货主ID 单位ID 类型 SKU .
@@ -344,7 +347,7 @@ class OwnerPriceOperationService
             if ($rule->strategy == '特征' && !app("FeatureService")->matchFeature($rule->feature,$columnMapping,$matchObject))continue;
             //获取满减信息并处理满减
             $result = $this->getDiscount($rule->discount_count,$total); //满减信息
-            $this->handleDiscount($rule,$ownerId,$result);
+            $this->handleDiscount($rule,$ownerId,$result,$month);
 
             $taxRate = app("OwnerService")->getTaxRateFee($rule, $ownerId);//获取税率
 
@@ -655,12 +658,12 @@ class OwnerPriceOperationService
      * @param int $owner
      * @param int $discountIndex
      * @param \stdClass|object $pivot
+     * @param string $month
      */
-    public function handlePastBill($rule, int $owner, int $discountIndex, $pivot)
+    public function handlePastBill($rule, int $owner, int $discountIndex, $pivot, $month)
     {
         DB::beginTransaction();
         try{
-            $month = date("Y-m");
             $day = date("t",strtotime($month));
             $query = OwnerFeeDetail::query()->where("owner_id",$owner)->whereBetween("worked_at",[$month."-01",$month."-".$day]);
             $units = app("UnitService")->getUnitMapping(["件","单","箱","m³","T","kg"],true); //获取单位映射集
@@ -694,12 +697,13 @@ class OwnerPriceOperationService
             };
             if ($rule->operation_type=='入库'){
                 foreach ($query->with(["store.storeItems.commodity","store.warehouse"])
-                             ->where("outer_table_name",'stores')->get() as $detail)
-                    $exe(Feature::MAPPING["store"],$detail->store,$detail);
+                             ->where("outer_table_name",'stores')->get()->chunk(50) as $coll){
+                    dispatch(new ExecutePostBillHandler($exe,$coll,Store::class));
+                }
             }else{
                 foreach ($query->with(["order.logistic","order.shop","order.packages.commodities.commodity","order.batch"])
-                             ->where("outer_table_name",'orders')->get() as $detail)
-                    $exe(Feature::MAPPING["order"],$detail->order,$detail);
+                             ->where("outer_table_name",'orders')->get()->chunk(50) as $coll)
+                    dispatch(new ExecutePostBillHandler($exe,$coll,Order::class));
             }
             DB::commit();
         }catch (\Exception $e){

+ 1 - 1
app/Services/weight/HengLiWeightService.php

@@ -39,7 +39,7 @@ class HengLiWeightService extends WeightService
 
     public function getWeightMessage($orderPackage, $e): array
     {
-        return ['success' => false, 'message' => $e->getMessage];
+        return ['success' => false, 'message' => $e->getMessage ?? ""];
     }
 
 }