ReportController.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. <?php
  2. namespace App\Http\Controllers\Admin;
  3. use App\Http\Controllers\Controller;
  4. use App\Models\Node;
  5. use App\Models\NodeDailyDataFlow;
  6. use App\Models\NodeHourlyDataFlow;
  7. use App\Models\Order;
  8. use App\Models\User;
  9. use Carbon\Carbon;
  10. use DB;
  11. use Illuminate\Contracts\View\View;
  12. use Illuminate\Http\Request;
  13. class ReportController extends Controller
  14. {
  15. public function accounting(): View
  16. {
  17. $completedOrders = Order::where('status', '>=', 2)->has('goods')->selectRaw('DATE(created_at) as date, sum(amount)/100 as total')->groupBy('date')->get();
  18. $ordersByDay = $completedOrders->filter(fn ($order) => $order->date >= now()->subMonthNoOverflow()->startOfMonth()->format('Y-m-d'))->pluck('total', 'date');
  19. $ordersByMonth = $completedOrders->filter(fn ($order) => $order->date >= now()->subYearNoOverflow()->startOfYear())->groupBy(fn ($order) => Carbon::parse($order->date)->format('Y-m'))->map(fn ($rows) => round($rows->sum('total'),
  20. 2))->toArray();
  21. $ordersByYear = $completedOrders->groupBy(fn ($order) => Carbon::parse($order->date)->format('Y'))->map(fn ($rows) => round($rows->sum('total'), 2))->toArray();
  22. $currentDays = date('j');
  23. $lastMonth = strtotime('first day of last month');
  24. $daysInLastMonth = date('t', $lastMonth);
  25. $months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
  26. $data = [
  27. 'days' => range(1, max($currentDays, $daysInLastMonth)),
  28. 'months' => array_map(static fn ($month) => Carbon::create(null, $month)->translatedFormat('F'), $months),
  29. 'currentMonth' => array_map(static fn ($i) => round($ordersByDay[date(sprintf('Y-m-%02u', $i))] ?? 0, 2), range(1, $currentDays)),
  30. 'lastMonth' => array_map(static fn ($i) => $ordersByDay[date(sprintf('Y-m-%02u', $i), $lastMonth)] ?? 0, range(1, $daysInLastMonth)),
  31. 'currentYear' => array_map(static fn ($i) => $ordersByMonth[date(sprintf('Y-%02u', $i))] ?? 0, range(1, date('m'))),
  32. 'lastYear' => array_map(static fn ($i) => $ordersByMonth[date(sprintf('Y-%02u', $i), strtotime('-1 years'))] ?? 0, $months),
  33. 'ordersByYear' => $ordersByYear,
  34. ];
  35. return view('admin.report.accounting', compact('data'));
  36. }
  37. public function userAnalysis(Request $request): View
  38. {
  39. $uid = $request->input('uid');
  40. $username = $request->input('username');
  41. if ($uid) {
  42. $user = User::find($uid);
  43. } elseif ($username) {
  44. $user = User::whereUsername($username)->first();
  45. }
  46. $data = null;
  47. if (isset($user)) {
  48. $currentTime = now();
  49. $currentDay = $currentTime->day;
  50. $currentHour = $currentTime->hour;
  51. // 用户当前小时在各线路消耗流量
  52. $currentHourFlow = $user->dataFlowLogs()->where('log_time', '>=', $currentTime->startOfHour()->timestamp)->with('node:id,name')->groupBy('node_id')->selectRaw('node_id, log_time, sum(u + d) as total')->get()->map(fn ($item) => [
  53. 'id' => $item->node_id,
  54. 'name' => $item->node->name,
  55. 'time' => $currentHour,
  56. 'total' => round($item->total / MiB, 2),
  57. ]);
  58. $hoursFlow = $user->hourlyDataFlows()->whereNotNull('node_id')->whereDate('created_at', $currentTime)->with('node:id,name')->selectRaw('node_id, HOUR(created_at) as hour, u + d as total')->get()->map(fn ($item
  59. ) => [
  60. 'id' => $item->node_id,
  61. 'name' => $item->node->name,
  62. 'time' => (int) $item->hour,
  63. 'total' => round($item->total / MiB, 2),
  64. ]); // 用户今天各小时在各线路消耗流量
  65. $daysFlow = $user->dailyDataFlows()->whereNotNull('node_id')->whereMonth('created_at', $currentTime)->with('node:id,name')->selectRaw('node_id, DAY(created_at) as day, u + d as total')->get()->map(fn ($item
  66. ) => [
  67. 'id' => $item->node_id,
  68. 'name' => $item->node->name,
  69. 'time' => (int) $item->day,
  70. 'total' => round($item->total / MiB, 2),
  71. ]);
  72. $currentDayFlow = collect($currentHourFlow)
  73. ->merge($hoursFlow)
  74. ->groupBy('id')
  75. ->map(fn ($items) => [
  76. 'id' => $items->first()['id'],
  77. 'name' => $items->first()['name'],
  78. 'time' => $currentDay,
  79. 'total' => round($items->sum('total'), 2),
  80. ])->values();
  81. $data = [
  82. 'hours' => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23],
  83. 'days' => range(1, $currentDay),
  84. 'nodes' => collect([$currentDayFlow, $daysFlow])->collapse()->pluck('name', 'id')->unique()->toArray(),
  85. 'hourlyFlows' => array_merge($hoursFlow->toArray(), $currentHourFlow->toArray()),
  86. 'dailyFlows' => array_merge($daysFlow->toArray(), $currentDayFlow->toArray()),
  87. ];
  88. }
  89. return view('admin.report.userDataAnalysis', compact('data'));
  90. }
  91. public function siteAnalysis(Request $request): View
  92. {
  93. $nodeId = $request->input('node_id');
  94. $nodes = Node::orderBy('name')->pluck('name', 'id');
  95. // Fetch flows
  96. $flows = NodeDailyDataFlow::whereNodeId($nodeId)->selectRaw('DATE(created_at) as date, sum(u + d) as total')->groupBy('date')->get()->keyBy('date');
  97. $dailyFlows = $flows->filter(fn ($flow) => $flow->date >= now()->subMonthNoOverflow()->startOfMonth()->toDateString())->pluck('total', 'date');
  98. $monthlyFlows = $flows->groupBy(fn ($flow) => Carbon::parse($flow->date)->format('Y-m'))->map(fn ($rows) => round($rows->sum('total') / GiB, 2));
  99. $yearlyFlows = $flows->groupBy(fn ($flow) => Carbon::parse($flow->date)->format('Y'))->map(fn ($rows) => round($rows->sum('total') / TiB, 2));
  100. $currentDays = (int) date('j');
  101. $lastDays = (int) date('t', strtotime('-1 months'));
  102. $todayFlow = NodeHourlyDataFlow::whereDate('created_at', today())->when($nodeId, fn ($query) => $query->whereNodeId($nodeId))->sum(DB::raw('u + d')) / GiB;
  103. $thirtyDaysAgo = now()->subDays(30);
  104. $trafficData = NodeDailyDataFlow::where('node_id', $nodeId)->where('created_at', '>=', $thirtyDaysAgo)->selectRaw('SUM(u + d) as total, COUNT(*) as dataCounts')->first();
  105. $total30Days = $trafficData->total ?? 0;
  106. $daysWithData = max($trafficData->dataCounts ?? 0, 1);
  107. $months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
  108. $data = [
  109. 'days' => range(1, max($currentDays, $lastDays)),
  110. 'months' => array_map(static fn ($month) => Carbon::create(null, $month)->translatedFormat('F'), $months),
  111. 'currentMonth' => array_map(static fn ($i) => ($dailyFlows[date(sprintf('Y-m-%02u', $i))] ?? 0) / GiB, range(1, $currentDays)),
  112. 'lastMonth' => array_map(static fn ($i) => ($dailyFlows[date(sprintf('Y-m-%02u', $i), strtotime('first day of last month'))] ?? 0) / GiB, range(1, $lastDays)),
  113. 'currentYear' => array_map(static fn ($i) => $monthlyFlows[date(sprintf('Y-%02u', $i))] ?? 0, range(1, date('m'))),
  114. 'lastYear' => array_map(static fn ($i) => $monthlyFlows[date(sprintf('Y-%02u', $i), strtotime('-1 years'))] ?? 0, $months),
  115. 'yearlyFlows' => $yearlyFlows->toArray(),
  116. 'avgDaily30d' => round(($total30Days / GiB) / $daysWithData, 2),
  117. ];
  118. if ($nodeId) {
  119. $totalAll30d = NodeDailyDataFlow::where('created_at', '>=', $thirtyDaysAgo)->whereNull('node_id')->sum(DB::raw('u + d'));
  120. $data['nodePct30d'] = round(($total30Days / max($totalAll30d, 1)) * 100, 2);
  121. }
  122. $data['currentMonth'][$currentDays - 1] = $todayFlow;
  123. $data['currentYear'][count($data['currentYear']) - 1] += $todayFlow;
  124. return view('admin.report.siteDataAnalysis', compact('data', 'nodes'));
  125. }
  126. }