Kaynağa Gözat

定时同步承运商

Zhouzhendong 5 yıl önce
ebeveyn
işleme
eca1ff31b2

+ 53 - 0
app/Console/Commands/SyncCarrier.php

@@ -0,0 +1,53 @@
+<?php
+
+namespace App\Console\Commands;
+
+use App\Logistic;
+use App\Services\common\BatchUpdateService;
+use Illuminate\Console\Command;
+use Illuminate\Support\Facades\DB;
+
+class SyncCarrier extends Command
+{
+    /**
+     * The name and signature of the console command.
+     *
+     * @var string
+     */
+    protected $signature = 'sync:carrier';
+
+    /**
+     * The console command description.
+     *
+     * @var string
+     */
+    protected $description = 'Sync carriers every hour';
+
+    /**
+     * Create a new command instance.
+     *
+     * @return void
+     */
+    public function __construct()
+    {
+        parent::__construct();
+    }
+
+    /**
+     * Execute the console command.
+     *
+     * @return void
+     */
+    public function handle()
+    {
+        $carriers = DB::connection("oracle")->select(DB::raw("SELECT CUSTOMERID,CUSTOMER_TYPE,DESCR_C,CASE DESCR_E WHEN 'WL' THEN '物流' ELSE '快递' END AS TYPE FROM BAS_CUSTOMER WHERE CUSTOMER_TYPE = 'CA'"));
+        $logistics = Logistic::query()->whereIn("code",array_column($carriers,"customerid"))->get();
+        $changes = diff($carriers,$logistics,"code",["code"=>"customerid","name"=>"descr_c","type"=>"type"]);
+        if ($changes['attached'])Logistic::query()->insert($changes['attached']);
+        if ($changes['updated']){
+            array_unshift($changes['updated'],["code","name","type"]);
+            app(BatchUpdateService::class)->batchUpdate("logistics",$changes['updated']);
+        }
+        if ($changes["detached"])Logistic::query()->whereIn("code",$changes["detached"])->delete();
+    }
+}

+ 3 - 0
app/Console/Kernel.php

@@ -10,6 +10,7 @@ use App\Console\Commands\InventoryDailyLoggingOwner;
 use App\Console\Commands\LogExpireDelete;
 use App\Console\Commands\MakeServiceCommand;
 use App\Console\Commands\SyncBatchTask;
+use App\Console\Commands\SyncCarrier;
 use App\Console\Commands\SyncLogCacheTask;
 use App\Console\Commands\SyncOrderPackageLogisticRouteTask;
 use App\Console\Commands\SyncUserVisitMenuLogsCacheTask;
@@ -46,6 +47,7 @@ class  Kernel extends ConsoleKernel
         WasSyncWmsAsnInformation::class,
         CreateWeightStatistic::class,
         BeforeCreateOwnerReport::class,
+        SyncCarrier::class,
     ];
 
     /**
@@ -72,6 +74,7 @@ class  Kernel extends ConsoleKernel
         $schedule->command('clear:cancelledOrder')->everyTenMinutes();
         $schedule->command('WasSyncWmsAsnInformation')->everyMinute();
         $schedule->command('create:weightStatistic')->dailyAt("00:30");
+        $schedule->command('sync:carrier')->hourlyAt(1);
     }
 
     /**

+ 47 - 0
app/Http/Controllers/TestController.php

@@ -125,6 +125,7 @@ use Carbon\CarbonPeriod;
 use ChangeColumnOrderIdToOrderIssues;
 use Doctrine\DBAL\Query\QueryBuilder;
 use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Database\Eloquent\Model;
 use Illuminate\Support\Facades\Auth;
 use Illuminate\Support\Facades\Cache;
 use Illuminate\Http\Request;
@@ -158,8 +159,54 @@ class TestController extends Controller
 
     public function test()
     {
+        $a = [[1,2,3]];
+        dd(array_unshift($a,["code","name","type"]),$a);
         return view("test");
     }
+    public function handle()
+    {
+        $carriers = DB::connection("oracle")->select(DB::raw("SELECT CUSTOMERID,CUSTOMER_TYPE,DESCR_C,CASE DESCR_E WHEN 'WL' THEN '物流' ELSE '快递' END AS TYPE FROM BAS_CUSTOMER WHERE CUSTOMER_TYPE = 'CA'"));
+        $logistics = Logistic::query()->whereIn("code",array_column($carriers,"customerid"))->get();
+        $changes = diff($carriers,$logistics,"code",["code"=>"customerid","name"=>"descr_c","type"=>"type"]);
+        dd($changes);
+    }
+
+    private function diff($array1,$array2,$identification,$mapping):array
+    {
+        $changes = [
+            'attached' => [], 'detached' => [], 'updated' => [],
+        ];
+        $map = [];
+        foreach ($array2 as $item){
+            if (is_array($item))$map[$item[$identification]] = $item;
+            else $map[$item->$identification] = json_decode($item,true);
+        }
+        foreach ($array1 as $item){
+            /** @var \stdClass|array|Model $item */
+            if (!is_array($item) && !is_subclass_of($item,Model::class))$item = (array)$item;
+            if (!isset($map[$item[$mapping[$identification]]])){
+                $obj = [];
+                foreach ($mapping as $column2=>$column1)$obj[$column2] = $item[$column1];
+                $changes['attached'][] = $obj;continue;
+            }
+            $sign = false;
+            $obj = [];
+            foreach ($mapping as $column2=>$column1){
+                $obj[$column2] = $item[$column1];
+                if ($map[$item[$mapping[$identification]]][$column2] != $item[$column1])$sign = true;
+            }
+            if ($sign)$changes['updated'][] = $obj;
+            unset($map[$item[$mapping[$identification]]]);
+        }
+        //返回列表跟返回KEY
+        /*foreach ($map as $item){
+            $obj = [];
+            foreach ($mapping as $column2=>$column1)$obj[$column2] = $item[$column2];
+            $changes['detached'][] = $obj;
+        }*/
+        if ($map)$changes['detached'][] = array_keys($map);
+        return $changes;
+    }
     public function assignBatch(){
         $batches = collect([
   [

+ 2 - 1
app/Logistic.php

@@ -10,11 +10,12 @@ use Illuminate\Database\Eloquent\Model;
  */use App\Traits\ModelTimeFormat;
 
 use App\Traits\ModelLogChanging;
+use Illuminate\Database\Eloquent\SoftDeletes;
 
 class Logistic extends Model
 {
     use ModelLogChanging;
-
+    use SoftDeletes;
     use ModelTimeFormat;
     protected $fillable = ['name','code',"type","mobile","remark","delivery_fee"];
 

+ 40 - 0
app/Utils/helpers.php

@@ -1,6 +1,7 @@
 <?php
 
 use Carbon\Carbon;
+use Illuminate\Database\Eloquent\Model;
 
 function formatExcelDate(int $timestamp)
 {
@@ -8,4 +9,43 @@ function formatExcelDate(int $timestamp)
     $today=new Carbon('1900-01-01');
     $day = $today->addDays($diff-2);
     return $day->toDateString();
+}
+
+function diff($array1,$array2,string $identification,array $mapping,bool $intactDetached = false):array
+{
+    $changes = [
+        'attached' => [], 'detached' => [], 'updated' => [],
+    ];
+    $map = [];
+    foreach ($array2 as $item){
+        if (is_array($item))$map[$item[$identification]] = $item;
+        else $map[$item->$identification] = json_decode($item,true);
+    }
+    foreach ($array1 as $item){
+        /** @var \stdClass|array|Model $item */
+        if (!is_array($item) && !is_subclass_of($item,Model::class))$item = (array)$item;
+        if (!isset($map[$item[$mapping[$identification]]])){
+            $obj = [];
+            foreach ($mapping as $column2=>$column1)$obj[$column2] = $item[$column1];
+            $changes['attached'][] = $obj;continue;
+        }
+        $sign = false;
+        $obj = [];
+        foreach ($mapping as $column2=>$column1){
+            $obj[$column2] = $item[$column1];
+            if ($map[$item[$mapping[$identification]]][$column2] != $item[$column1])$sign = true;
+        }
+        if ($sign)$changes['updated'][] = $obj;
+        unset($map[$item[$mapping[$identification]]]);
+    }
+    if ($map){
+        if ($intactDetached){
+            foreach ($map as $item){
+                $obj = [];
+                foreach ($mapping as $column2=>$column1)$obj[$column2] = $item[$column2];
+                $changes['detached'][] = $obj;
+            }
+        }else $changes['detached'][] = array_keys($map);
+    }
+    return $changes;
 }

+ 32 - 0
database/migrations/2021_03_25_150800_change_logistics_add_column_deleted_at.php

@@ -0,0 +1,32 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+class ChangeLogisticsAddColumnDeletedAt extends Migration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::table('logistics', function (Blueprint $table) {
+            $table->timestamp("deleted_at")->nullable();
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('logistics', function (Blueprint $table) {
+            $table->dropColumn("deleted_at");
+        });
+    }
+}