Browse Source

Remove 'total' & 'traffic' in dataflow database table

BrettonYe 2 years ago
parent
commit
226e1dfdec

+ 24 - 31
app/Console/Commands/DailyNodeReport.php

@@ -2,11 +2,10 @@
 
 namespace App\Console\Commands;
 
-use App\Models\Node;
+use App\Models\NodeDailyDataFlow;
 use App\Models\User;
 use App\Notifications\NodeDailyReport;
 use Illuminate\Console\Command;
-use Illuminate\Database\Eloquent\Builder;
 use Log;
 use Notification;
 
@@ -21,35 +20,29 @@ class DailyNodeReport extends Command
         $jobTime = microtime(true);
 
         if (sysConfig('node_daily_notification')) {
-            $date = date('Y-m-d', strtotime('-1 days'));
-            $nodeList = Node::with('dailyDataFlows')->whereHas('dailyDataFlows', function (Builder $query) use ($date) {
-                $query->whereDate('created_at', $date);
-            })->get();
-            if ($nodeList->isNotEmpty()) {
-                $data = [];
-                $upload = 0;
-                $download = 0;
-                foreach ($nodeList as $node) {
-                    $log = $node->dailyDataFlows()->whereDate('created_at', $date)->first();
-                    $data[] = [
-                        'name' => $node->name,
-                        'upload' => formatBytes($log->u ?? 0),
-                        'download' => formatBytes($log->d ?? 0),
-                        'total' => $log->traffic ?? '',
-                    ];
-                    $upload += $log->u ?? 0;
-                    $download += $log->d ?? 0;
-                }
-                if ($data) {
-                    $data[] = [
-                        'name' => trans('notification.node.total'),
-                        'total' => formatBytes($upload + $download),
-                        'upload' => formatBytes($upload),
-                        'download' => formatBytes($download),
-                    ];
-
-                    Notification::send(User::role('Super Admin')->get(), new NodeDailyReport($data));
-                }
+            $nodeDailyLogs = NodeDailyDataFlow::with('node:id,name')->has('node')->orderBy('node_id')->whereDate('created_at', date('Y-m-d', strtotime('yesterday')))->get();
+
+            $data = [];
+            foreach ($nodeDailyLogs as $log) {
+                $data[] = [
+                    'name' => $log->node->name,
+                    'upload' => formatBytes($log->u),
+                    'download' => formatBytes($log->d),
+                    'total' => formatBytes($log->u + $log->d),
+                ];
+            }
+
+            if ($data) {
+                $u = $nodeDailyLogs->sum('u');
+                $d = $nodeDailyLogs->sum('d');
+                $data[] = [
+                    'name' => trans('notification.node.total'),
+                    'upload' => formatBytes($u),
+                    'download' => formatBytes($d),
+                    'total' => formatBytes($u + $d),
+                ];
+
+                Notification::send(User::role('Super Admin')->get(), new NodeDailyReport($data));
             }
         }
 

+ 4 - 4
app/Console/Commands/TaskAuto.php

@@ -81,13 +81,13 @@ class TaskAuto extends Command
                 $query->whereStatus(1); // 获取有订阅且未被封禁用户
             })
             ->whereHas('subscribeLogs', function (Builder $query) {
-                $query->where('request_time', '>=', date('Y-m-d H:i:s', strtotime('-1 day'))); //    ->distinct()->count('request_ip');
+                $query->whereDate('request_time', '>=', now()->subDay()); //    ->distinct()->count('request_ip');
             }, '>=', sysConfig('subscribe_ban_times'))
             ->chunk(config('tasks.chunk'), function ($users) {
                 $trafficBanTime = sysConfig('traffic_ban_time');
                 $ban_time = strtotime($trafficBanTime.' minutes');
                 $dirtyWorks = ['status' => 0, 'ban_time' => $ban_time, 'ban_desc' => 'Subscription link receive abnormal access and banned by the system'];
-                $banMsg = ['time' => $trafficBanTime, 'description' => __('[Auto Job] Blocked Subscription: Subscription with abnormal requests within 24 hours')];
+                $banMsg = ['time' => $trafficBanTime, 'description' => __('[Auto Task] Blocked Subscription: Subscription with abnormal requests within 24 hours')];
                 foreach ($users as $user) {
                     $user->subscribe->update($dirtyWorks);
                     $user->banedLogs()->create($banMsg); // 记录封禁日志
@@ -112,7 +112,7 @@ class TaskAuto extends Command
             ->chunk(config('tasks.chunk'), function ($users) {
                 foreach ($users as $user) {
                     $user->update(['enable' => 0]);
-                    $user->banedLogs()->create(['description' => __('[Auto Job] Blocked service: Run out of traffic')]); // 写入日志
+                    $user->banedLogs()->create(['description' => __('[Auto Task] Blocked service: Run out of traffic')]); // 写入日志
                 }
             });
 
@@ -127,7 +127,7 @@ class TaskAuto extends Command
                         // 多往前取5分钟,防止数据统计任务执行时间过长导致没有数据
                         if ($user->isTrafficWarning()) {
                             $user->update(['enable' => 0, 'ban_time' => $ban_time]);
-                            $user->banedLogs()->create(['time' => $trafficBanTime, 'description' => __('[Auto Job] Blocked service: Abnormal traffic within 1 hour')]); // 写入日志
+                            $user->banedLogs()->create(['time' => $trafficBanTime, 'description' => __('[Auto Task] Blocked service: Abnormal traffic within 1 hour')]); // 写入日志
                         }
                     }
                 });

+ 8 - 20
app/Console/Commands/TaskDaily.php

@@ -126,10 +126,10 @@ class TaskDaily extends Command
 
     private function userTrafficStatistics(): void
     {
-        $created_at = date('Y-m-d 23:59:59', strtotime('-1 days'));
+        $created_at = date('Y-m-d 23:59:59', strtotime('yesterday'));
         $end = strtotime($created_at);
         $start = $end - 86399;
-        // todo: laravel10 得改
+
         User::activeUser()->with('dataFlowLogs')->whereHas('dataFlowLogs', function (Builder $query) use ($start, $end) {
             $query->whereBetween('log_time', [$start, $end]);
         })->chunk(config('tasks.chunk'), function ($users) use ($start, $end, $created_at) {
@@ -141,16 +141,13 @@ class TaskDaily extends Command
                     ->get();
 
                 $data = $logs->each(function ($log) use ($created_at) {
-                    $log->total = $log->u + $log->d;
-                    $log->traffic = formatBytes($log->total);
                     $log->created_at = $created_at;
-                })->flatten()->toArray();
+                })->toArray();
 
                 $data[] = [ // 每日节点流量合计
+                    'node_id' => null,
                     'u' => $logs->sum('u'),
                     'd' => $logs->sum('d'),
-                    'total' => $logs->sum('total'),
-                    'traffic' => formatBytes($logs->sum('total')),
                     'created_at' => $created_at,
                 ];
 
@@ -161,25 +158,16 @@ class TaskDaily extends Command
 
     private function nodeTrafficStatistics(): void
     {
-        $created_at = date('Y-m-d 23:59:59', strtotime('-1 day'));
+        $created_at = date('Y-m-d 23:59:59', strtotime('yesterday'));
         $end = strtotime($created_at);
         $start = $end - 86399;
 
-        Node::orderBy('id')->with('userDataFlowLogs')->whereHas('userDataFlowLogs', function (Builder $query) use ($start, $end) {
+        Node::with('userDataFlowLogs')->whereHas('userDataFlowLogs', function (Builder $query) use ($start, $end) {
             $query->whereBetween('log_time', [$start, $end]);
         })->chunk(config('tasks.chunk'), function ($nodes) use ($start, $end, $created_at) {
             foreach ($nodes as $node) {
-                $traffic = $node->userDataFlowLogs()
-                    ->whereBetween('log_time', [$start, $end])
-                    ->selectRaw('sum(`u`) as u, sum(`d`) as d')->first();
-                $total = $traffic->u + $traffic->d;
-                $node->dailyDataFlows()->create([
-                    'u' => $traffic->u,
-                    'd' => $traffic->d,
-                    'total' => $total,
-                    'traffic' => formatBytes($total),
-                    'created_at' => $created_at,
-                ]);
+                $log = $node->userDataFlowLogs()->whereBetween('log_time', [$start, $end])->selectRaw('sum(`u`) as u, sum(`d`) as d')->first();
+                $node->dailyDataFlows()->create(['u' => $log->u, 'd' => $log->d, 'created_at' => $created_at]);
             }
         });
     }

+ 6 - 17
app/Console/Commands/TaskHourly.php

@@ -45,23 +45,21 @@ class TaskHourly extends Command
                     ->get();
 
                 $data = $logs->each(function ($log) use ($created_at) {
-                    $log->total = $log->u + $log->d;
-                    $log->traffic = formatBytes($log->total);
                     $log->created_at = $created_at;
-                })->flatten()->toArray();
+                })->toArray();
                 $overall = [ // 每小时节点流量合计
+                    'node_id' => null,
                     'u' => $logs->sum('u'),
                     'd' => $logs->sum('d'),
-                    'total' => $logs->sum('total'),
-                    'traffic' => formatBytes($logs->sum('total')),
                     'created_at' => $created_at,
                 ];
                 $data[] = $overall;
                 $user->hourlyDataFlows()->createMany($data);
+                $overall['total'] = $overall['u'] + $overall['d'];
 
                 // 用户流量异常警告
                 if ($data_anomaly_notification && $overall['total'] >= $traffic_ban_value) {
-                    Notification::send(User::find(1), new DataAnomaly($user->username, formatBytes($overall['u']), formatBytes($overall['d']), $overall['traffic']));
+                    Notification::send(User::find(1), new DataAnomaly($user->username, formatBytes($overall['u']), formatBytes($overall['d']), formatBytes($overall['total'])));
                 }
             }
         });
@@ -77,17 +75,8 @@ class TaskHourly extends Command
             $query->whereBetween('log_time', [$start, $end]);
         })->chunk(config('tasks.chunk'), function ($nodes) use ($start, $end, $created_at) {
             foreach ($nodes as $node) {
-                $traffic = $node->userDataFlowLogs()
-                    ->whereBetween('log_time', [$start, $end])
-                    ->selectRaw('sum(`u`) as u, sum(`d`) as d')->first();
-                $total = $traffic->u + $traffic->d;
-                $node->hourlyDataFlows()->create([
-                    'u' => $traffic->u,
-                    'd' => $traffic->d,
-                    'total' => $total,
-                    'traffic' => formatBytes($total),
-                    'created_at' => $created_at,
-                ]);
+                $traffic = $node->userDataFlowLogs()->whereBetween('log_time', [$start, $end])->selectRaw('sum(`u`) as u, sum(`d`) as d')->first();
+                $node->hourlyDataFlows()->create(['u' => $traffic->u, 'd' => $traffic->d, 'created_at' => $created_at]);
             }
         });
     }

+ 5 - 5
app/Helpers/DataChart.php

@@ -27,14 +27,14 @@ trait DataChart
 
         if ($is_node) {
             $currentFlow = UserDataFlowLog::whereNodeId($id);
-            $hourlyFlow = NodeHourlyDataFlow::whereNodeId($id)->whereDate('created_at', date('Y-m-d'))->selectRaw('(DATE_FORMAT(node_hourly_data_flow.created_at, "%k")) as date, total')->pluck('total', 'date');
-            $dailyFlow = NodeDailyDataFlow::whereNodeId($id)->whereMonth('created_at', date('n'))->selectRaw('(DATE_FORMAT(node_daily_data_flow.created_at, "%e")) as date, total')->pluck('total', 'date');
+            $hourlyFlow = NodeHourlyDataFlow::whereNodeId($id)->whereDate('created_at', date('Y-m-d'))->selectRaw('(DATE_FORMAT(node_hourly_data_flow.created_at, "%k")) as date, u + d as total')->pluck('total', 'date');
+            $dailyFlow = NodeDailyDataFlow::whereNodeId($id)->whereMonth('created_at', date('n'))->selectRaw('(DATE_FORMAT(node_daily_data_flow.created_at, "%e")) as date, u + d as total')->pluck('total', 'date');
         } else {
             $currentFlow = UserDataFlowLog::whereUserId($id);
-            $hourlyFlow = UserHourlyDataFlow::userHourly($id)->whereDate('created_at', date('Y-m-d'))->selectRaw('(DATE_FORMAT(user_hourly_data_flow.created_at, "%k")) as date, total')->pluck('total', 'date');
-            $dailyFlow = UserDailyDataFlow::userDaily($id)->whereMonth('created_at', date('n'))->selectRaw('(DATE_FORMAT(user_daily_data_flow.created_at, "%e")) as date, total')->pluck('total', 'date');
+            $hourlyFlow = UserHourlyDataFlow::userHourly($id)->whereDate('created_at', date('Y-m-d'))->selectRaw('(DATE_FORMAT(user_hourly_data_flow.created_at, "%k")) as date, u + d as total')->pluck('total', 'date');
+            $dailyFlow = UserDailyDataFlow::userDaily($id)->whereMonth('created_at', date('n'))->selectRaw('(DATE_FORMAT(user_daily_data_flow.created_at, "%e")) as date, u + d as total')->pluck('total', 'date');
         }
-        $currentFlow = $currentFlow->where('log_time', '>=', strtotime(date('Y-m-d H:0')))->sum(DB::raw('u + d'));
+        $currentFlow = $currentFlow->where('log_time', '>=', now()->startOfHour()->timestamp)->sum(DB::raw('u + d'));
 
         // 节点一天内的流量
         foreach ($hourlyFlow as $date => $dataFlow) {

+ 1 - 1
app/Http/Controllers/Admin/NodeAuthController.php

@@ -15,7 +15,7 @@ class NodeAuthController extends Controller
     // 节点授权列表
     public function index()
     {
-        return view('admin.node.auth', ['authorizations' => NodeAuth::with('node')->orderBy('node_id')->paginate()->appends(request('page'))]);
+        return view('admin.node.auth', ['authorizations' => NodeAuth::with('node:id,name,type,server,ip')->has('node')->orderBy('node_id')->paginate()->appends(request('page'))]);
     }
 
     // 添加节点授权

+ 3 - 4
app/Http/Controllers/Admin/NodeController.php

@@ -28,7 +28,7 @@ class NodeController extends Controller
     {
         $status = $request->input('status');
 
-        $query = Node::whereNull('relay_node_id')->with('onlineLogs', 'dailyDataFlows', 'heartbeats', 'childNodes');
+        $query = Node::whereNull('relay_node_id')->with(['onlineLogs', 'dailyDataFlows:node_id,u,d', 'heartbeats', 'childNodes']);
 
         if (isset($status)) {
             $query->whereStatus($status);
@@ -36,9 +36,8 @@ class NodeController extends Controller
 
         $nodeList = $query->orderByDesc('sort')->orderBy('id')->paginate(15)->appends($request->except('page'));
         foreach ($nodeList as $node) {
-            $online_log = $node->onlineLogs->where('log_time', '>=', strtotime('-5 minutes'))->sortBy('log_time')->first(); // 在线人数
-            $node->online_users = $online_log->online_user ?? 0;
-            $node->transfer = formatBytes($node->dailyDataFlows->sum('total')); // 已产生流量
+            $node->online_users = $node->onlineLogs->where('log_time', '>=', strtotime('-5 minutes'))->sortBy('log_time')->first()?->online_user; // 在线人数
+            $node->transfer = formatBytes($node->dailyDataFlows->sum('u') + $node->dailyDataFlows->sum('d')); // 已产生流量
             $node_info = $node->heartbeats->where('log_time', '>=', strtotime(config('tasks.recently_heartbeat')))->sortBy('log_time')->first(); // 近期负载
             $node->isOnline = $node_info !== null && ! empty($node_info->load);
             $node->load = $node_info->load ?? false;

+ 4 - 5
app/Http/Controllers/Admin/ReportController.php

@@ -71,7 +71,7 @@ class ReportController extends Controller
         if (isset($user)) {
             // 用户当前小时在各线路消耗流量
             $data['currentHourlyFlow'] = $user->dataFlowLogs()
-                ->where('log_time', '>=', strtotime(date('Y-m-d H:00')))
+                ->where('log_time', '>=', now()->startOfHour()->timestamp)
                 ->groupBy('node_id')
                 ->selectRaw('node_id, sum(u + d) as total')
                 ->get()->toArray();
@@ -79,8 +79,8 @@ class ReportController extends Controller
             // 用户今天各小时在各线路消耗流量
             $data['hours'] = range(0, 23);
             $data['hourlyFlow'] = $user->hourlyDataFlows()->whereNotNull('node_id')
-                ->where('created_at', '>=', date('Y-m-d H:i:s', strtotime('-1 days')))
-                ->selectRaw('node_id, (DATE_FORMAT(user_hourly_data_flow.created_at, "%k")) as date, total')
+                ->whereDate('created_at', now())
+                ->selectRaw('node_id, (DATE_FORMAT(user_hourly_data_flow.created_at, "%k")) as date, u + d as total')
                 ->get()->transform(function ($item) {
                     return [
                         'node_id' => $item->node_id,
@@ -93,8 +93,7 @@ class ReportController extends Controller
             $data['days'] = range(1, date('j'));
             $data['dailyFlow'] = $user->dailyDataFlows()->whereNotNull('node_id')
                 ->whereMonth('created_at', date('n'))
-                ->where('total', '>', 6000000)
-                ->selectRaw('node_id, (DATE_FORMAT(user_daily_data_flow.created_at, "%e")) as date, total')
+                ->selectRaw('node_id, (DATE_FORMAT(user_daily_data_flow.created_at, "%e")) as date, u + d as total')
                 ->get()->transform(function ($item) {
                     return [
                         'node_id' => $item->node_id,

+ 6 - 5
app/Http/Controllers/AdminController.php

@@ -9,6 +9,7 @@ use App\Models\Label;
 use App\Models\Level;
 use App\Models\Node;
 use App\Models\NodeDailyDataFlow;
+use App\Models\NodeHourlyDataFlow;
 use App\Models\Order;
 use App\Models\ReferralApply;
 use App\Models\ReferralLog;
@@ -28,9 +29,9 @@ class AdminController extends Controller
     public function index()
     {
         $past = strtotime('-'.sysConfig('expire_days').' days');
+        $dailyTrafficUsage = NodeHourlyDataFlow::whereDate('created_at', date('Y-m-d'))->sum(\DB::raw('u + d'));
 
         return view('admin.index', [
-            'expireDays' => sysConfig('expire_days'),
             'totalUserCount' => User::count(), // 总用户数
             'todayRegister' => User::whereDate('created_at', date('Y-m-d'))->count(), // 今日注册用户
             'enableUserCount' => User::whereEnable(1)->count(), // 有效用户数
@@ -42,10 +43,10 @@ class AdminController extends Controller
             'largeTrafficUserCount' => User::whereRaw('(u + d)/transfer_enable >= 0.9')->where('status', '<>', -1)->count(), // 流量使用超过90%的用户
             'flowAbnormalUserCount' => count((new UserHourlyDataFlow)->trafficAbnormal()), // 1小时内流量异常用户
             'nodeCount' => Node::count(),
-            'unnormalNodeCount' => Node::whereStatus(0)->count(),
-            'flowCount' => formatBytes(NodeDailyDataFlow::where('created_at', '>=', date('Y-m-d', strtotime('-30 days')))->sum('total')),
-            'todayFlowCount' => formatBytes(NodeDailyDataFlow::where('created_at', '>=', date('Y-m-d'))->sum('total')),
-            'totalFlowCount' => formatBytes(NodeDailyDataFlow::sum('total')),
+            'abnormalNodeCount' => Node::whereStatus(0)->count(),
+            'monthlyTrafficUsage' => formatBytes(NodeDailyDataFlow::whereMonth('created_at', date('n'))->sum(\DB::raw('u + d'))),
+            'dailyTrafficUsage' => $dailyTrafficUsage ? formatBytes($dailyTrafficUsage) : 0,
+            'totalTrafficUsage' => formatBytes(NodeDailyDataFlow::sum(\DB::raw('u + d'))),
             'totalCredit' => User::where('credit', '<>', 0)->sum('credit') / 100,
             'totalWaitRefAmount' => ReferralLog::whereIn('status', [0, 1])->sum('commission') / 100,
             'todayWaitRefAmount' => ReferralLog::whereIn('status', [0, 1])->whereDate('created_at', date('Y-m-d'))->sum('commission') / 100,

+ 1 - 1
app/Models/User.php

@@ -296,7 +296,7 @@ class User extends Authenticatable
 
     public function recentTrafficUsed()
     {
-        return UserHourlyDataFlow::userRecentUsed($this->id)->sum('total');
+        return UserHourlyDataFlow::userRecentUsed($this->id)->sum(\DB::raw('u + d'));
     }
 
     public function orders(): HasMany

+ 9 - 4
app/Models/UserDataModifyLog.php

@@ -2,6 +2,7 @@
 
 namespace App\Models;
 
+use Illuminate\Database\Eloquent\Casts\Attribute;
 use Illuminate\Database\Eloquent\Model;
 use Illuminate\Database\Eloquent\Relations\BelongsTo;
 
@@ -28,13 +29,17 @@ class UserDataModifyLog extends Model
         return $this->belongsTo(Order::class);
     }
 
-    public function getBeforeAttribute($value): string
+    public function before(): Attribute
     {
-        return $this->attributes['before'] = formatBytes($value);
+        return Attribute::make(
+            get: static fn (int $value) => formatBytes($value),
+        );
     }
 
-    public function getAfterAttribute($value): string
+    public function after(): Attribute
     {
-        return $this->attributes['after'] = formatBytes($value);
+        return Attribute::make(
+            get: static fn (int $value) => formatBytes($value),
+        );
     }
 }

+ 3 - 3
app/Models/UserHourlyDataFlow.php

@@ -42,11 +42,11 @@ class UserHourlyDataFlow extends Model
     public function trafficAbnormal(): array
     {
         $userTotalTrafficList = self::whereNodeId(null)
-            ->where('total', '>', MiB * 50)
+            ->where('d', '>', MiB * 10)
             ->where('created_at', '>=', date('Y-m-d H:i:s', time() - 3900))
             ->groupBy('user_id')
-            ->selectRaw('user_id, sum(total) as totalTraffic')->pluck('totalTraffic', 'user_id')
-            ->toArray(); // 只统计50M以上的记录,加快速度
+            ->selectRaw('user_id, sum(u + d) as total')->pluck('total', 'user_id')
+            ->toArray(); // 只统计10M以上的记录,加快速度
         foreach ($userTotalTrafficList as $user => $traffic) {
             if ($traffic > (int) sysConfig('traffic_ban_value') * GiB) {
                 $result[] = $user;

+ 0 - 6
database/migrations/2023_05_11_012354_update_failed_jobs.php

@@ -6,9 +6,6 @@ use Illuminate\Support\Facades\Schema;
 
 return new class extends Migration
 {
-    /**
-     * Run the migrations.
-     */
     public function up(): void
     {
         Schema::table('failed_jobs', static function (Blueprint $table) {
@@ -22,9 +19,6 @@ return new class extends Migration
         });
     }
 
-    /**
-     * Reverse the migrations.
-     */
     public function down(): void
     {
         Schema::table('failed_jobs', function (Blueprint $table) {

+ 0 - 6
database/migrations/2023_06_04_224713_update_paypal.php

@@ -9,9 +9,6 @@ return new class extends Migration
 
     private static array $newConfigs = ['paypal_client_id', 'paypal_client_secret'];
 
-    /**
-     * Run the migrations.
-     */
     public function up(): void
     {
         if (Config::exists()) {
@@ -24,9 +21,6 @@ return new class extends Migration
         }
     }
 
-    /**
-     * Reverse the migrations.
-     */
     public function down(): void
     {
         foreach (self::$newConfigs as $config) {

+ 74 - 0
database/migrations/2023_07_08_162803_clean_up_unnecessary_info.php

@@ -0,0 +1,74 @@
+<?php
+
+use App\Models\NodeDailyDataFlow;
+use App\Models\NodeHourlyDataFlow;
+use App\Models\UserDailyDataFlow;
+use App\Models\UserHourlyDataFlow;
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class extends Migration
+{
+    public function up(): void
+    {
+        DB::table('country')->where('code', '=', 'uk')->update(['code' => 'gb']);
+
+        Schema::table('node_daily_data_flow', function (Blueprint $table) {
+            $table->dropColumn(['total', 'traffic']);
+        });
+        Schema::table('node_hourly_data_flow', function (Blueprint $table) {
+            $table->dropColumn(['total', 'traffic']);
+        });
+        Schema::table('user_daily_data_flow', function (Blueprint $table) {
+            $table->dropColumn(['total', 'traffic']);
+        });
+        Schema::table('user_hourly_data_flow', function (Blueprint $table) {
+            $table->dropColumn(['total', 'traffic']);
+        });
+    }
+
+    public function down(): void
+    {
+        Schema::table('node_daily_data_flow', static function (Blueprint $table) {
+            $table->unsignedBigInteger('total')->default(0)->comment('总流量')->after('d');
+            $table->string('traffic')->nullable()->comment('总流量(带单位)')->after('total');
+        });
+        foreach (NodeDailyDataFlow::cursor() as $log) {
+            $log->total = $log->u + $log->d;
+            $log->traffic = formatBytes($log->total);
+            $log->save();
+        }
+
+        Schema::table('node_hourly_data_flow', static function (Blueprint $table) {
+            $table->unsignedBigInteger('total')->default(0)->comment('总流量')->after('d');
+            $table->string('traffic')->nullable()->comment('总流量(带单位)')->after('total');
+        });
+        foreach (NodeHourlyDataFlow::cursor() as $log) {
+            $log->total = $log->u + $log->d;
+            $log->traffic = formatBytes($log->total);
+            $log->save();
+        }
+
+        Schema::table('user_daily_data_flow', static function (Blueprint $table) {
+            $table->unsignedBigInteger('total')->default(0)->comment('总流量')->after('d');
+            $table->string('traffic')->nullable()->comment('总流量(带单位)')->after('total');
+        });
+        foreach (UserDailyDataFlow::cursor() as $log) {
+            $log->total = $log->u + $log->d;
+            $log->traffic = formatBytes($log->total);
+            $log->save();
+        }
+
+        Schema::table('user_hourly_data_flow', static function (Blueprint $table) {
+            $table->unsignedBigInteger('total')->default(0)->comment('总流量')->after('d');
+            $table->string('traffic')->nullable()->comment('总流量(带单位)')->after('total');
+        });
+
+        foreach (UserHourlyDataFlow::cursor() as $log) {
+            $log->total = $log->u + $log->d;
+            $log->traffic = formatBytes($log->total);
+            $log->save();
+        }
+    }
+};

File diff suppressed because it is too large
+ 2 - 2
public/assets/global/vendor/chart-js/chart.min.js


File diff suppressed because it is too large
+ 0 - 0
public/vendor/horizon/app.js


+ 1 - 1
public/vendor/horizon/mix-manifest.json

@@ -1,5 +1,5 @@
 {
-    "/app.js": "/app.js?id=c6d58c1ba0a1e0ad976bd661884a1582",
+    "/app.js": "/app.js?id=45904d8bd75c65ee5c136a52a5e8ead6",
     "/app-dark.css": "/app-dark.css?id=15c72df05e2b1147fa3e4b0670cfb435",
     "/app.css": "/app.css?id=4d6a1a7fe095eedc2cb2a4ce822ea8a5",
     "/img/favicon.png": "/img/favicon.png?id=1542bfe8a0010dcbee710da13cce367f",

+ 1 - 1
resources/rules/default.clash.yaml

@@ -10,7 +10,7 @@ log-level: info
 external-controller: 127.0.0.1:9090
 
 dns:
-  enable: true
+  enable: false
   listen: 0.0.0.0:53
   ipv6: true
 

+ 10 - 10
resources/views/admin/index.blade.php

@@ -56,7 +56,7 @@
                             <button type="button" class="btn btn-floating btn-sm btn-success">
                                 <i class="icon md-account"></i>
                             </button>
-                            <span class="ml-15 font-weight-400">{{ trans('admin.dashboard.active_days_users', ['days' => $expireDays]) }}</span>
+                            <span class="ml-15 font-weight-400">{{ trans('admin.dashboard.active_days_users', ['days' => sysConfig('expire_days')]) }}</span>
                             <div class="content-text text-center mb-0">
                                 <span class="font-size-40 font-weight-100">{{$activeUserCount}}</span>
                             </div>
@@ -69,7 +69,7 @@
                             <button type="button" class="btn btn-floating btn-sm btn-warning">
                                 <i class="icon md-account"></i>
                             </button>
-                            <span class="ml-15 font-weight-400">{{ trans('admin.dashboard.inactive_days_users', ['days' => $expireDays]) }}</span>
+                            <span class="ml-15 font-weight-400">{{ trans('admin.dashboard.inactive_days_users', ['days' => sysConfig('expire_days')]) }}</span>
                             <div class="content-text text-center mb-0">
                                 <span class="font-size-40 font-weight-100">{{$inactiveUserCount}}</span>
                             </div>
@@ -151,7 +151,7 @@
                             </button>
                             <span class="ml-15 font-weight-400">{{ trans('admin.dashboard.maintaining_nodes') }}</span>
                             <div class="content-text text-center mb-0">
-                                <span class="font-size-40 font-weight-100">{{$unnormalNodeCount}}</span>
+                                <span class="font-size-40 font-weight-100">{{$abnormalNodeCount}}</span>
                             </div>
                         </div>
                     </a>
@@ -164,25 +164,25 @@
                             <button type="button" class="btn btn-floating btn-sm btn-primary">
                                 <i class="icon md-time-countdown"></i>
                             </button>
-                            <span class="ml-15 font-weight-400">{{ trans('admin.dashboard.traffic_consumed') }}</span>
+                            <span class="ml-15 font-weight-400">{{ trans('admin.dashboard.days_traffic_consumed', ['days' => now()->diffInDays((new DateTime())->modify(config('tasks.clean.node_daily_logs')))]) }}</span>
                             <div class="content-text text-center mb-0">
-                                <span class="font-size-40 font-weight-100">{{$totalFlowCount}}</span>
+                                <span class="font-size-40 font-weight-100">{{ $totalTrafficUsage }}</span>
                             </div>
                         </div>
                     </a>
                 </div>
                 <div class="col-xl-3 col-md-6 info-panel">
-                    <a href="{{route('admin.log.traffic')}}" class="card card-shadow">
+                    <a href="{{ route('admin.log.traffic') }}" class="card card-shadow">
                         <div class="card-block bg-white">
                             <button type="button" class="btn btn-floating btn-sm btn-primary">
                                 <i class="icon md-time-countdown"></i>
                             </button>
-                            <span class="ml-15 font-weight-400">{{ trans('admin.dashboard.traffic_days_consumed', ['days' => 30]) }}</span>
+                            <span class="ml-15 font-weight-400">{{ trans('admin.dashboard.current_month_traffic_consumed') }}</span>
                             <div class="content-text text-center mb-0">
-                                <span class="font-size-40 font-weight-100">{{$flowCount}}</span>
-                                @if($todayFlowCount !== '0B')
+                                <span class="font-size-40 font-weight-100">{{ $monthlyTrafficUsage }}</span>
+                                @if( $dailyTrafficUsage !== 0 )
                                     <span class="badge badge-success badge-round up font-size-20 m-0" style="top:-20px">
-                                    <i class="icon wb-triangle-up" aria-hidden="true"></i> {{$todayFlowCount}}
+                                    <i class="icon wb-triangle-up" aria-hidden="true"></i> {{ $dailyTrafficUsage }}
                                 </span>
                                 @endif
                             </div>

+ 5 - 5
resources/views/admin/logs/userTraffic.blade.php

@@ -54,10 +54,10 @@
                                     @endif
                                 @endif
                             </td>
-                            <td> {{$log->before}} </td>
-                            <td> {{$log->after}} </td>
-                            <td> {{$log->description}} </td>
-                            <td> {{$log->created_at}} </td>
+                            <td> {{ $log->before }} </td>
+                            <td> {{ $log->after }} </td>
+                            <td> {{ $log->description }} </td>
+                            <td> {{ $log->created_at }} </td>
                         </tr>
                     @endforeach
                     </tbody>
@@ -70,7 +70,7 @@
                     </div>
                     <div class="col-sm-8">
                         <nav class="Page navigation float-right">
-                            {{$userTrafficLogs->links()}}
+                            {{ $userTrafficLogs->links() }}
                         </nav>
                     </div>
                 </div>

+ 54 - 22
resources/views/admin/report/userDataAnalysis.blade.php

@@ -70,26 +70,6 @@
             };
           }
 
-          const common_options = {
-            stack: 'node_id',
-            parsing: {
-              xAxisKey: 'date',
-              yAxisKey: 'total',
-            },
-            responsive: true,
-            plugins: {
-              legend: {
-                labels: {
-                  padding: 20,
-                  usePointStyle: true,
-                  pointStyle: 'circle',
-                  font: {size: 14},
-                },
-              },
-              tooltip: label_callbacks(' {{ trans_choice('common.days.attribute', 1) }}'),
-            },
-          };
-
           function area_a(label, data) {
             return {
               label: label,
@@ -110,7 +90,33 @@
               labels: @json($data['hours']),
               datasets: [area_a('{{ trans('admin.report.today') }}',@json($data['hourlyFlow']))],
             },
-            options: common_options,
+            options: {
+                // stack: 'node_id',
+                parsing: {
+                    xAxisKey: 'date',
+                    yAxisKey: 'total',
+                },
+                scales: {
+                    x: {
+                        stacked: true
+                    },
+                    y: {
+                        stacked: true
+                    }
+                },
+                responsive: true,
+                plugins: {
+                    legend: {
+                        labels: {
+                            padding: 20,
+                            usePointStyle: true,
+                            pointStyle: 'circle',
+                            font: {size: 14},
+                        },
+                    },
+                    tooltip: label_callbacks(' {{ trans_choice('common.hour', 2) }}'),
+                },
+            },
           });
 
           new Chart(document.getElementById('dailyBar'), {
@@ -119,7 +125,33 @@
               labels: @json($data['days']),
               datasets: [area_a('{{ trans('admin.report.current_month') }}',@json($data['dailyFlow']))],
             },
-            options: common_options,
+            options: {
+                // stack: 'node_id',
+                parsing: {
+                    xAxisKey: 'date',
+                    yAxisKey: 'total',
+                },
+                scales: {
+                    x: {
+                        stacked: true
+                    },
+                    y: {
+                        stacked: true
+                    }
+                },
+                responsive: true,
+                plugins: {
+                    legend: {
+                        labels: {
+                            padding: 20,
+                            usePointStyle: true,
+                            pointStyle: 'circle',
+                            font: {size: 14},
+                        },
+                    },
+                    tooltip: label_callbacks(' {{ trans_choice('common.days.attribute', 1) }}'),
+                },
+            },
           });
         </script>
     @endisset

Some files were not shown because too many files changed in this diff