Преглед изворни кода

控制台修复 order_counting_records_init

ANG YU пре 4 година
родитељ
комит
d1d5cac414

+ 60 - 0
app/Console/Commands/OrderCountingRecordTask.php

@@ -0,0 +1,60 @@
+<?php
+
+namespace App\Console\Commands;
+
+use App\Services\LogService;
+use App\Services\NewOrderCountingRecordService;
+use Illuminate\Console\Command;
+
+class OrderCountingRecordTask extends Command
+{
+    /**
+     * @var NewOrderCountingRecordService $service
+     */
+    public $service;
+    /**
+     * The name and signature of the console command.
+     *
+     * @var string
+     */
+    protected $signature = 'orderCountingRecordTask';
+
+    /**
+     * The console command description.
+     *
+     * @var string
+     */
+    protected $description = 'Command description';
+
+    /**
+     * Create a new command instance.
+     *
+     * @return void
+     */
+    public function __construct()
+    {
+        parent::__construct();
+    }
+
+    /**
+     * Execute the console command.
+     *
+     * @throws \Exception
+     */
+    public function handle()
+    {
+        LogService::log(OrderCountingRecordTask::class, "订单量统计", '');
+        ini_set('memory_limit', '2226M');
+        $this->service = app('NewOrderCountingRecordService');
+        if (now()->toDateString() == now()->startOfMonth()->toDateString()) {//是否为月初
+            //统计上月的数据
+            $this->service->recordOrder(now()->subMonth()->startOfMonth()->toDateString(), now()->subMonth()->endOfMonth()->toDateString(), '月');
+        }
+        if (now()->toDateString() == now()->startOfYear()->toDateString()) {//是否为年初
+            //统计上年的数据
+            $this->service->recordOrder(now()->subYear()->startofYear()->toDateString(), now()->subYear()->endOfYear()->toDateString(), '年');
+        }
+        //统计前一天的数据
+        $this->service->recordOrder(now()->subDay()->toDateString(), now()->subDay()->toDateString(), '日');
+    }
+}

+ 1 - 0
app/Console/Kernel.php

@@ -81,6 +81,7 @@ class  Kernel extends ConsoleKernel
         $schedule->command('sync:carrier')->hourlyAt(1);
         $schedule->command('createProcurementTotalBill')->monthlyOn(1);
         $schedule->command('check:cacheRack')->everyMinute();
+        $schedule->command('orderCountingRecordTask')->dailyAt("1:00");
     }
 
     /**

+ 3 - 3
app/Http/Controllers/ControlPanelController.php

@@ -51,7 +51,7 @@ class ControlPanelController extends Controller
         $end = Carbon::parse($request->end)->gt(Carbon::now()) ? Carbon::now()->toDateString() : $request->end;
         $ownerIds=$request->owner_ids;
         if (!$ownerIds || in_array('all',$ownerIds)) $ownerIds = $this->getCountingOwnerIds(null);
-        $orderCountingRecords = $orderCountingRecordService->orderCountingRecords($start, $end, $request->unit, $ownerIds);
+        $orderCountingRecords = $orderCountingRecordService->getOrderCountingRecordsApi($start, $end, $request->unit, $ownerIds);
         return compact('orderCountingRecords');
     }
 
@@ -65,7 +65,7 @@ class ControlPanelController extends Controller
         $end = Carbon::parse($request->end)->gt(Carbon::now()) ? Carbon::now()->toDateString() : $request->end;
         $ownerIds=$request->input('owner_ids');
         if (!$ownerIds || in_array('all',$ownerIds)) $ownerIds = $this->getCountingOwnerIds(null);
-        $logisticsCountingRecords = $orderCountingRecordService->logisticsCountingRecords($start, $end, $ownerIds);
+        $logisticsCountingRecords = $orderCountingRecordService->getLogisticRecordsApi($start, $end, $ownerIds);
         return compact('logisticsCountingRecords');
     }
 
@@ -78,7 +78,7 @@ class ControlPanelController extends Controller
         $start = Carbon::parse($request->start)->gt(Carbon::now()) ? Carbon::now()->toDateString() : $request->start;
         $end = Carbon::parse($request->end)->gt(Carbon::now()) ? Carbon::now()->toDateString() : $request->end;
         $ownerIds = $this->getCountingOwnerIds(null);
-        $warehouseCountingRecords = $orderCountingRecordService->warehouseCountingRecords($start, $end, $ownerIds);
+        $warehouseCountingRecords = $orderCountingRecordService->getWareHouseRecordsApi($start, $end, $ownerIds);
         return compact('warehouseCountingRecords');
     }
 

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

@@ -1549,4 +1549,13 @@ TEXT;
             }
         }
     }
+
+    public function order_counting_records_init()
+    {
+        \App\OrderCountingRecord::query()->truncate();
+        $start = '2021-05-14';
+        $end = '2021-06-07';
+        $service = app('NewOrderCountingRecordService');
+        $service->recordByDay($start, $end, '日');
+    }
 }

+ 14 - 1
app/OrderCountingRecord.php

@@ -5,12 +5,25 @@ namespace App;
 use Illuminate\Database\Eloquent\Model;
 
 use App\Traits\ModelLogChanging;
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
 
 class OrderCountingRecord extends Model
 {
     use ModelLogChanging;
 
     //
-    protected $fillable = ['owner_id','shop_id' ,'warehouse_id' ,'logistic_id' ,'date_target' ,'counting_unit' ,'amount','year','month','week'];
+    protected $fillable = ['owner_id' ,'warehouse_id' ,'logistic_id' ,'date_target' ,'counting_unit' ,'amount','year','month'];
+
+    public  $timestamps = false;
+
+    public function logistic(): BelongsTo
+    {
+        return $this->belongsTo(Logistic::class);
+    }
+
+    public function warehouse(): BelongsTo
+    {
+        return $this->belongsTo(Warehouse::class);
+    }
 
 }

+ 2 - 0
app/Providers/AppServiceProvider.php

@@ -33,6 +33,7 @@ use App\Services\LogisticYTOService;
 use App\Services\LogisticZopService;
 use App\Services\LogService;
 use App\Services\MaterialBoxService;
+use App\Services\NewOrderCountingRecordService;
 use App\Services\OracleBasCustomerService;
 use App\Services\OracleBasSkuService;
 use App\Services\OracleDocAsnDetailService;
@@ -193,6 +194,7 @@ class AppServiceProvider extends ServiceProvider
     private function loadingService(){
         app()->singleton('AllInventoryService',AllInventoryService::class);
         app()->singleton('AuthorityService',AuthorityService::class);
+        app()->singleton('NewOrderCountingRecordService',NewOrderCountingRecordService::class);
         app()->singleton('BatchService',BatchService::class);
         app()->singleton('BatchUpdateService', BatchUpdateService::class);
         app()->singleton('CacheService',CacheService::class);

+ 239 - 17
app/Services/NewOrderCountingRecordService.php

@@ -9,6 +9,7 @@ use App\Order;
 use App\OrderCountingRecord;
 use App\Warehouse;
 use Carbon\Carbon;
+use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Support\Arr;
 use Illuminate\Support\Collection;
 use Illuminate\Support\Facades\Cache;
@@ -18,7 +19,9 @@ use App\Traits\ServiceAppAop;
 class NewOrderCountingRecordService
 {
     use ServiceAppAop;
-    protected $modelClass=NewOrderCountingRecord::class;
+
+    protected $modelClass = OrderCountingRecord::class;
+
     public function orderCountingRecordsFromCache($start, $end, $unit, $ownerIds)
     {
         $dataList = collect();
@@ -86,22 +89,22 @@ class NewOrderCountingRecordService
     {
         $key = 'warehouseCountingRecords_' . $start . '_' . $end . '_' . json_encode($ownerIds);
         return Cache::remember($key, config('cache.expirations.warehouseCountingRecords'), function () use ($start, $end, $ownerIds) {
-        $dataList = collect();
-        $resultOrders = $this->get($start, $end, '日', $ownerIds);
-        $resultOrders->groupBy('warehouse_id')->each(function ($item) use (&$dataList) {
-            $counter = $item->reduce(function ($sum, $item) {
-                return $sum + $item->amount;
-            }, 0);
-            $warehouse = Warehouse::query()->find($item[0]->warehouse_id);
+            $dataList = collect();
+            $resultOrders = $this->get($start, $end, '日', $ownerIds);
+            $resultOrders->groupBy('warehouse_id')->each(function ($item) use (&$dataList) {
+                $counter = $item->reduce(function ($sum, $item) {
+                    return $sum + $item->amount;
+                }, 0);
+                $warehouse = Warehouse::query()->find($item[0]->warehouse_id);
 
-            $dataList->push([
-                'value' => $counter,
-                'warehouse_id' => $item[0]->warehouse_id,
-                'name' => $warehouse ? $warehouse->name : '仓库为空',
-                'code' => $warehouse ? $warehouse->code : 'NULL',
-            ]);
-        });
-        return $dataList;
+                $dataList->push([
+                    'value' => $counter,
+                    'warehouse_id' => $item[0]->warehouse_id,
+                    'name' => $warehouse ? $warehouse->name : '仓库为空',
+                    'code' => $warehouse ? $warehouse->code : 'NULL',
+                ]);
+            });
+            return $dataList;
         });
     }
 
@@ -476,11 +479,230 @@ class NewOrderCountingRecordService
     {
         if ($this->isNotCurrentDate($dateStr, $unit)) {
             LogService::log('NewOrderCountingRecordService', '缓存设置为永久', $dateStr);
-            $ttl = config('cache.expirations.forever');//非当前日期的缓存为永久
+            $ttl = config('cache.expirations.orderCountingRecord');//非当前日期的缓存为永久
         } else {
             LogService::log('NewOrderCountingRecordService', '缓存设置为临时', $dateStr);
             $ttl = config('cache.expirations.orderCountingRecord');//当前日期缓存为1800s
         }
         return $ttl;
     }
+
+
+    //TODO 控制台重构
+
+    public function getWareHouseRecordsApi($start, $end, $ownerIds): array
+    {
+        $orderCountingRecords = OrderCountingRecord::query()
+            ->selectRaw("sum(amount) as value ,warehouse_id")
+            ->with('warehouse:id,name,code')
+            ->whereBetween('date_target', [$start, $end])
+            ->whereIn('owner_id', $ownerIds)
+            ->groupBy('warehouse_id')
+            ->get();
+        $result = [];
+        foreach ($orderCountingRecords as $orderCountingRecord) {
+            $result[] = [
+                'logistic_id' => $orderCountingRecord->warehouse_id,
+                'value' => $orderCountingRecord->value,
+                'name' => $orderCountingRecord->warehouse->name ?? '',
+                'code' => $orderCountingRecord->warehouse->code ?? '',
+            ];
+        }
+        return $result;
+    }
+
+    public function getLogisticRecordsApi($start, $end, $ownerIds): array
+    {
+        $orderCountingRecords = OrderCountingRecord::query()
+            ->selectRaw("sum(amount) as value ,logistic_id")
+            ->with('logistic:id,name')
+            ->whereBetween('date_target', [$start, $end])
+            ->whereIn('owner_id', $ownerIds)
+            ->groupBy('logistic_id')
+            ->get();
+        $result = [];
+        foreach ($orderCountingRecords as $orderCountingRecord) {
+            $result[] = [
+                'logistic_id' => $orderCountingRecord->logistic_id,
+                'value' => $orderCountingRecord->value,
+                'name' => $orderCountingRecord->logistic->name ?? '',
+            ];
+        }
+        return $result;
+    }
+
+    /**
+     * 查询订单量趋势
+     * @param $start string
+     * @param $end string
+     * @param $unit string
+     * @param $ownerIds array
+     * @return Builder[]|\Illuminate\Database\Eloquent\Collection
+     */
+    public function getOrderCountingRecordsApi(string $start, string $end, string $unit, array $ownerIds)
+    {
+        $orderCountingRecords = OrderCountingRecord::query()
+            ->selectRaw("sum(amount) as counter ,date_target")
+            ->whereBetween('date_target', [$start, $end])
+            ->where('counting_unit', $unit)
+            ->whereIn('owner_id', $ownerIds)
+            ->groupBy('date_target')
+            ->get()->toArray();
+        if (now()->toDateString() == $end) {//查询时间包含当天
+            switch ($unit) {
+                case '日':
+                    //查询当天统计
+                    $startDateTime = Carbon::parse($end)->startOfDay()->toDateTimeString();
+                    $endDateTime = Carbon::parse($end)->endOfDay()->toDateTimeString();
+                    break;
+                case '月':
+                    //查询当月统计
+                    $startDateTime = Carbon::parse($end)->startOfMonth()->startOfDay()->toDateTimeString();
+                    $endDateTime = Carbon::parse($end)->endOfMonth()->endOfDay()->toDateTimeString();
+                    break;
+                case '年':
+                    //查询当年统计
+                    $startDateTime = Carbon::parse($end)->startOfYear()->startOfDay()->toDateTimeString();
+                    $endDateTime = Carbon::parse($end)->endOfYear()->endOfDay()->toDateTimeString();
+                    break;
+            }
+            $order = Order::query()
+                ->selectRaw("count(1) as amounts ,DATE_FORMAT(created_at,'%Y-%m-%d') as date_target")
+                ->whereBetween('created_at', [$startDateTime, $endDateTime])
+                ->where('wms_status', '订单完成')
+                ->whereIn('owner_id', $ownerIds)
+                ->groupBy('date_target')
+                ->first();
+            $orderCountingRecords[] = [
+                "counter" => $order->amounts,
+                "date_target" => $order->date_target,
+            ];
+        }
+        return $orderCountingRecords;
+    }
+
+    /**
+     * 统计订单量 从$start 开始统计 默认截止到当前日期的前一天
+     * @param $start string
+     * @param null $end string
+     * @param $unit string
+     */
+    public function recordOrder(string $start, $end = null, string $unit = '日')
+    {
+        switch ($unit) {
+            case '日':
+                $this->recordByDay($start, $end, $unit);
+                break;
+            case'月':
+                $this->recordByMonth($start, $end, $unit);
+                break;
+            case'年':
+                $this->recordByYear($start, $end, $unit);
+                break;
+            default:
+        }
+    }
+
+    /**
+     * 清空统计缓存
+     */
+    public function clearCacheOrderRecord()
+    {
+
+    }
+
+    /**
+     * 日统计
+     * @param string $start
+     * @param $end
+     * @param string $unit
+     */
+    public function recordByDay(string $start, $end = null, string $unit = '日'): void
+    {
+        $startDateTime = Carbon::parse($start)->startOfDay()->toDateTimeString();
+        if (is_null($end)) {
+            $end = now()->subDay()->endOfDay();
+        }
+        $endDateTime = Carbon::parse($end)->endOfDay()->toDateTimeString();
+        $orders = Order::query()
+            ->selectRaw("owner_id,warehouse_id,logistic_id,count(1) as amounts ,DATE_FORMAT(created_at,'%Y-%m-%d') as date_target")
+            ->whereBetween('created_at', [$startDateTime, $endDateTime])
+            ->where('wms_status', '订单完成')
+            ->groupBy('owner_id', 'warehouse_id', 'logistic_id', 'date_target')
+            ->get();
+        $insertData = [];
+        foreach ($orders as $order) {
+            $insertData[] = [
+                'owner_id' => $order->owner_id,
+                'warehouse_id' => $order->warehouse_id,
+                'logistic_id' => $order->logistic_id,
+                'date_target' => $order->date_target,
+                'counting_unit' => $unit,
+                'amount' => $order->amounts,
+                'year' => Carbon::parse($order->date_target)->year,
+                'month' => Carbon::parse($order->date_target)->year . '-' . Carbon::parse($order->date_target)->month,
+            ];
+        }
+        $insertDataChunked = array_chunk($insertData, 2000);
+        foreach ($insertDataChunked as $items) {
+            OrderCountingRecord::query()->insertOrIgnore($items);
+        }
+    }
+
+
+    public function recordByMonth(string $start, $end = null, $unit = '月')
+    {
+        $startDate = Carbon::parse($start)->startOfMonth()->toDateString();
+        if (is_null($end)) {
+            $end = now()->subMonth()->endOfDay();
+        }
+        $endDate = Carbon::parse($end)->endOfDay()->toDateString();
+        $orderCountingRecords = OrderCountingRecord::query()
+            ->selectRaw("owner_id,warehouse_id,logistic_id,sum(amount) as amount_sum,month,year,date_target")
+            ->whereBetween('date_target', [$startDate, $endDate])
+            ->where('counting_unit', '日')
+            ->groupBy('owner_id', 'warehouse_id', 'logistic_id', 'month', 'date_target')
+            ->get();
+        $insertData = [];
+        foreach ($orderCountingRecords as $orderCountingRecord) {
+            $insertData[] = [
+                'owner_id' => $orderCountingRecord->owner_id,
+                'warehouse_id' => $orderCountingRecord->warehouse_id,
+                'logistic_id' => $orderCountingRecord->logistic_id,
+                'counting_unit' => $unit,
+                'date_target' => Carbon::parse($orderCountingRecord->date_target)->startOfMonth()->toDateString(),
+                'amount' => $orderCountingRecord->amount_sum,
+                'year' => $orderCountingRecord->year,
+                'month' => $orderCountingRecord->month,
+            ];
+        }
+        OrderCountingRecord::query()->insertOrIgnore($insertData);
+    }
+
+    public function recordByYear(string $start, $end = null, $unit = '年')
+    {
+        $startYear = Carbon::parse($start)->year;
+        if (is_null($end)) {
+            $end = now()->subYear()->toDateString();
+        }
+        $endYear = Carbon::parse($end)->year;
+        $orderCountingRecords = OrderCountingRecord::query()
+            ->selectRaw("owner_id,warehouse_id,logistic_id,sum(amount) as amount_sum,year,date_target")
+            ->whereBetween('year', [$startYear, $endYear])
+            ->groupBy('owner_id', 'warehouse_id', 'logistic_id', 'year')
+            ->get();
+        $insertData = [];
+        foreach ($orderCountingRecords as $orderCountingRecord) {
+            $insertData[] = [
+                'owner_id' => $orderCountingRecord->owner_id,
+                'warehouse_id' => $orderCountingRecord->warehouse_id,
+                'logistic_id' => $orderCountingRecord->logistic_id,
+                'counting_unit' => $unit,
+                'date_target' => Carbon::parse($orderCountingRecord->date_target)->startOfYear()->toDateString(),
+                'amount' => $orderCountingRecord->amount_sum,
+                'year' => $orderCountingRecord->year,
+            ];
+        }
+        OrderCountingRecord::query()->insertOrIgnore($insertData);
+    }
 }

+ 0 - 1
database/factories/OrderCountingRecordFactory.php

@@ -14,7 +14,6 @@ use Illuminate\Database\Eloquent\Factory;
 $factory->define(OrderCountingRecord::class, function (Faker $faker) {
     return [
         'owner_id' => $faker->numberBetween(0, 100),
-        'shop_id' => $faker->numberBetween(0, 100),
         'warehouse_id' => $faker->numberBetween(0, 100),
         'logistic_id' => $faker->numberBetween(0, 100),
         'date_target' => Carbon::now()->toDateString(),

+ 54 - 0
database/migrations/2021_06_05_103627_change_order_counting_records.php

@@ -0,0 +1,54 @@
+<?php
+
+use App\OrderCountingRecord;
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+class ChangeOrderCountingRecords extends Migration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::table('order_counting_records', function (Blueprint $table) {
+            OrderCountingRecord::query()->truncate();
+            $table->dropColumn('week');
+            $table->dropColumn('shop_id');
+            $table->dropColumn('created_at');
+            $table->dropColumn('updated_at');
+
+            $table->dropIndex('order_counting_records_owner_id_index');
+            $table->dropIndex('order_counting_records_warehouse_id_index');
+            $table->dropIndex('order_counting_records_logistic_id_index');
+            $table->dropIndex('order_counting_records_date_target_index');
+            $table->dropIndex('order_counting_records_counting_unit_index');
+            $table->unique(['owner_id', 'warehouse_id', 'logistic_id', 'date_target', 'counting_unit'],'order_counting_records_unique');
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('order_counting_records', function (Blueprint $table) {
+            $table->string('week');
+            $table->integer('shop_id');
+
+            $table->index('owner_id');
+            $table->index('shop_id');
+            $table->index('warehouse_id');
+            $table->index('logistic_id');
+            $table->index('date_target');
+            $table->index('counting_unit');
+
+            $table->dropIndex('order_counting_records_unique');
+        });
+    }
+}

+ 22 - 0
database/seeds/OrderSeed.php

@@ -0,0 +1,22 @@
+<?php
+
+use Illuminate\Database\Seeder;
+
+class OrderSeed extends Seeder
+{
+    /**
+     * Run the database seeds.
+     *
+     * @return void
+     */
+    public function run()
+    {
+        foreach (now()->subMonth()->daysUntil(now()) as $day) {
+            factory(\App\Order::class)->times(random_int(10,12))->create([
+                'created_at' => $day->toDateTimeString(),
+                'wms_status' => '订单完成',
+            ]);
+        }
+
+    }
+}

+ 48 - 0
tests/Services/NewOrderCountingRecordService/GetOrderCountingRecordsApiTest.php

@@ -0,0 +1,48 @@
+<?php
+
+namespace Tests\Services\NewOrderCountingRecordService;
+use App\Services\NewOrderCountingRecordService;
+use Tests\TestCase;
+use App\OrderCountingRecord;
+use App\Traits\TestMockSubServices;
+
+class GetOrderCountingRecordsApiTest extends TestCase
+{
+    use TestMockSubServices;
+    /** @var NewOrderCountingRecordService $service */
+    public $service;
+    private $data;
+
+    private $amount=1;
+    function setUp(): void
+    {
+        parent::setUp();
+        $this->service = app('NewOrderCountingRecordService');
+//        $this->data['newOrderCountingRecords']
+//            = factory(OrderCountingRecord::class, $this->amount)
+//            ->create();
+    }
+
+    public function testReturned()
+    {
+        $this->assertTrue(true);
+    }
+
+    function tearDown(): void
+    {
+        OrderCountingRecord::query()
+            ->whereIn('id',data_get($this->data['newOrderCountingRecords'],'*.id')??[])
+            ->delete();
+        parent::tearDown();
+    }
+
+    /**
+     * @test
+     */
+    public function get_test()
+    {
+        $ownerIds = \App\Owner::query()->pluck('id')->toArray();
+        $result  =  $this->service->getOrderCountingRecordsApi('2021-05-01', '2021-06-08', '日', $ownerIds);
+        $this->assertTrue(true);
+    }
+}

+ 59 - 0
tests/Services/NewOrderCountingRecordService/RecordByMonthTest.php

@@ -0,0 +1,59 @@
+<?php
+
+namespace Tests\Services\NewOrderCountingRecordService;
+
+use App\Services\NewOrderCountingRecordService;
+use Tests\TestCase;
+use App\OrderCountingRecord;
+use App\Traits\TestMockSubServices;
+
+class RecordByMonthTest extends TestCase
+{
+    use TestMockSubServices;
+
+    /** @var NewOrderCountingRecordService $service */
+    public $service;
+    private $data;
+    private $amount = 2;
+
+    function setUp(): void
+    {
+        parent::setUp();
+        $this->service = app('NewOrderCountingRecordService');
+//        $this->data['newOrderCountingRecords']
+//            = factory(OrderCountingRecord::class, $this->amount)
+//            ->create();
+    }
+
+    public function testReturned()
+    {
+        $this->assertTrue(true);
+    }
+
+    function tearDown(): void
+    {
+        OrderCountingRecord::query()
+            ->whereIn('id', data_get($this->data['newOrderCountingRecords'], '*.id') ?? [])
+            ->delete();
+        parent::tearDown();
+    }
+
+    /**
+     * @test
+     */
+    public function get_test()
+    {
+        $start = '2021-05-01';
+        $startDate = $start;
+        $endDate = \Carbon\Carbon::parse($start)->endOfMonth()->toDateString();
+        $this->service->recordByMonth($start);
+        $this->assertEquals(OrderCountingRecord::query()
+            ->whereBetween('date_target', [$startDate, $endDate])
+            ->where('counting_unit','日')
+            ->sum('amount'), OrderCountingRecord::query()
+                ->where('counting_unit','月')
+                ->where('month','2021-5')
+                ->sum('amount'));
+        $this->assertTrue(true);
+    }
+}

+ 73 - 0
tests/Services/NewOrderCountingRecordService/RecordByYearTest.php

@@ -0,0 +1,73 @@
+<?php
+
+namespace Tests\Services\NewOrderCountingRecordService;
+
+use App\Services\NewOrderCountingRecordService;
+use Carbon\Carbon;
+use Tests\TestCase;
+use App\OrderCountingRecord;
+use App\Traits\TestMockSubServices;
+
+class RecordByYearTest extends TestCase
+{
+    use TestMockSubServices;
+
+    /** @var NewOrderCountingRecordService $service */
+    public $service;
+    private $data;
+    private $amount = 1;
+
+    function setUp(): void
+    {
+        parent::setUp();
+        $this->service = app('NewOrderCountingRecordService');
+//        $this->data['newOrderCountingRecords']
+//            = factory(OrderCountingRecord::class, $this->amount)
+//            ->create();
+    }
+
+    public function testReturned()
+    {
+        $this->assertTrue(true);
+    }
+
+    function tearDown(): void
+    {
+        OrderCountingRecord::query()
+            ->whereIn('id', data_get($this->data['newOrderCountingRecords'], '*.id') ?? [])
+            ->delete();
+        parent::tearDown();
+    }
+
+    /**
+     * @test
+     */
+    public function get_test()
+    {
+        $startYear = Carbon::parse(now()->subYear())->year;
+        if (is_null(null)) {
+            $end = now()->subYear()->toDateString();
+        }
+
+        $endYear = Carbon::parse($end)->year;
+        $aa = OrderCountingRecord::query()
+            ->whereBetween('year', [$startYear, $endYear])
+            ->where('counting_unit', '月')
+            ->sum('amount');
+
+        $this->data['newOrderCountingRecords']
+            = factory(OrderCountingRecord::class, $this->amount)
+            ->create([
+                'date_target' => now()->subYear()->startOfMonth()->toDateString(),
+                'counting_unit' => '月',
+                'amount' => 10,
+                'year' => now()->subYear()->year,
+            ]);
+        $this->service->recordByYear('2020-01-01');
+        $bb = OrderCountingRecord::query()
+            ->whereBetween('year', [$startYear, $endYear])
+            ->where('counting_unit', '月')
+            ->sum('amount');
+        $this->assertEquals($aa+10, $bb);
+    }
+}

+ 62 - 0
tests/Services/NewOrderCountingRecordService/RecordOrderDayTest.php

@@ -0,0 +1,62 @@
+<?php
+
+namespace Tests\Services\NewOrderCountingRecordService;
+use App\Services\NewOrderCountingRecordService;
+use Carbon\Carbon;
+use Tests\TestCase;
+use App\OrderCountingRecord;
+use App\Traits\TestMockSubServices;
+
+class RecordOrderDayTest extends TestCase
+{
+    use TestMockSubServices;
+    /** @var NewOrderCountingRecordService $service */
+    public $service;
+    private $data;
+    private $amount=2;
+    function setUp(): void
+    {
+        parent::setUp();
+        $this->service = app('NewOrderCountingRecordService');
+//        $this->data['newOrderCountingRecords']
+//            = factory(OrderCountingRecord::class, $this->amount)
+//            ->create();
+    }
+
+    public function testReturned()
+    {
+        $this->assertTrue(true);
+    }
+
+    function tearDown(): void
+    {
+        OrderCountingRecord::query()
+            ->whereIn('id',data_get($this->data['newOrderCountingRecords'],'*.id')??[])
+            ->delete();
+        parent::tearDown();
+    }
+
+
+    /**
+     * @test
+     */
+    public function record_test()
+    {
+        $start = '2021-05-14';
+        $end = '2021-06-08';
+        $this->service->recordByDay($start, $end, '日');
+        $startDateTime = Carbon::parse($start)->startOfDay()->toDateTimeString();
+        $endDateTime = now()->subDay()->endOfDay()->toDateTimeString();
+
+        $orderCount = \App\Order::query()
+            ->whereBetween('created_at', [$startDateTime, $endDateTime])
+            ->where('wms_status', '订单完成')
+            ->count();
+        //TODO 只能使用Date!!!!
+        $sum = OrderCountingRecord::query()
+            ->whereBetween('date_target', [Carbon::parse($startDateTime)->toDateString(), Carbon::parse($endDateTime)->toDateString()])
+            ->sum('amount');
+        $this->assertEquals($sum,
+            $orderCount);
+    }
+}