ReportController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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 App\Models\UserDataFlowLog;
  10. use Carbon\Carbon;
  11. use DB;
  12. use Illuminate\Contracts\View\View;
  13. use Illuminate\Http\Request;
  14. class ReportController extends Controller
  15. {
  16. public function accounting(): View
  17. {
  18. $completedOrders = Order::where('status', '>=', 2)->has('goods')->selectRaw('DATE(created_at) as date, sum(amount)/100 as total')->groupBy('date')->get();
  19. $ordersByDay = $completedOrders->filter(fn ($order) => $order->date >= now()->subMonthNoOverflow()->startOfMonth()->format('Y-m-d'))->pluck('total', 'date');
  20. $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'),
  21. 2))->toArray();
  22. $ordersByYear = $completedOrders->groupBy(fn ($order) => Carbon::parse($order->date)->format('Y'))->map(fn ($rows) => round($rows->sum('total'), 2))->toArray();
  23. $currentDays = date('j');
  24. $lastMonth = strtotime('first day of last month');
  25. $daysInLastMonth = date('t', $lastMonth);
  26. $months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
  27. $data = [
  28. 'days' => range(1, max($currentDays, $daysInLastMonth)),
  29. 'months' => array_map(static fn ($month) => Carbon::create(null, $month)->translatedFormat('F'), $months),
  30. 'currentMonth' => array_map(static fn ($i) => round($ordersByDay[date(sprintf('Y-m-%02u', $i))] ?? 0, 2), range(1, $currentDays)),
  31. 'lastMonth' => array_map(static fn ($i) => $ordersByDay[date(sprintf('Y-m-%02u', $i), $lastMonth)] ?? 0, range(1, $daysInLastMonth)),
  32. 'currentYear' => array_map(static fn ($i) => $ordersByMonth[date(sprintf('Y-%02u', $i))] ?? 0, range(1, date('m'))),
  33. 'lastYear' => array_map(static fn ($i) => $ordersByMonth[date(sprintf('Y-%02u', $i), strtotime('-1 years'))] ?? 0, $months),
  34. 'ordersByYear' => $ordersByYear,
  35. ];
  36. return view('admin.report.accounting', compact('data'));
  37. }
  38. public function userAnalysis(Request $request): View
  39. {
  40. $uid = $request->input('uid');
  41. $username = $request->input('username');
  42. if ($uid) {
  43. $user = User::find($uid);
  44. } elseif ($username) {
  45. $user = User::whereUsername($username)->first();
  46. }
  47. $data = null;
  48. if (isset($user)) {
  49. $currentTime = now();
  50. $currentDay = $currentTime->day;
  51. $currentHour = $currentTime->hour;
  52. // 用户当前小时在各线路消耗流量
  53. $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) => [
  54. 'id' => $item->node_id,
  55. 'name' => $item->node->name,
  56. 'time' => $currentHour,
  57. 'total' => round($item->total / MiB, 2),
  58. ]);
  59. $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) => [
  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. 'id' => $item->node_id,
  67. 'name' => $item->node->name,
  68. 'time' => (int) $item->day,
  69. 'total' => round($item->total / MiB, 2),
  70. ]);
  71. $currentDayFlow = collect($currentHourFlow)->merge($hoursFlow)->groupBy('id')->map(fn ($items) => [
  72. 'id' => $items->first()['id'],
  73. 'name' => $items->first()['name'],
  74. 'time' => $currentDay,
  75. 'total' => round($items->sum('total'), 2),
  76. ])->values();
  77. $data = [
  78. '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],
  79. 'days' => range(1, $currentDay),
  80. 'nodes' => collect([$currentDayFlow, $daysFlow])->collapse()->pluck('name', 'id')->unique()->toArray(),
  81. 'hourlyFlows' => array_merge($hoursFlow->toArray(), $currentHourFlow->toArray()),
  82. 'dailyFlows' => array_merge($daysFlow->toArray(), $currentDayFlow->toArray()),
  83. ];
  84. }
  85. return view('admin.report.userDataAnalysis', compact('data'));
  86. }
  87. public function nodeAnalysis(Request $request)
  88. {
  89. $currentTime = now();
  90. $currentDate = $currentTime->format('m-d');
  91. $currentHour = $currentTime->hour;
  92. $nodeId = $request->input('nodes');
  93. $startDate = $request->input('start') ?? $currentTime->format('Y-m-01');
  94. $endDate = $request->input('end') ?? $currentTime->format('Y-m-d');
  95. $hour_date = $request->input('hour_date') ?? $currentTime; // 默认是今天
  96. $nodes = Node::orderBy('name')->pluck('name', 'id'); // 用于前端节点显示
  97. $currentHourQuery = UserDataFlowLog::query();
  98. $hourlyQuery = NodeHourlyDataFlow::query();
  99. $dailyQuery = NodeDailyDataFlow::query();
  100. if ($nodeId) { // 节点过滤
  101. $currentHourQuery->whereIn('node_id', $nodeId);
  102. $hourlyQuery->whereIn('node_id', $nodeId);
  103. $dailyQuery->whereIn('node_id', $nodeId);
  104. }
  105. $data = [
  106. '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],
  107. 'start_date' => Carbon::parse(NodeDailyDataFlow::orderBy('created_at')->value('created_at'))->format('Y-m-d'), // 数据库里最早的日期
  108. ];
  109. $hoursFlow = $hourlyQuery->whereDate('created_at', $hour_date)->selectRaw('node_id, HOUR(created_at) as hour, u + d as total')->get()->map(fn ($item) => [
  110. 'id' => $item->node_id,
  111. 'name' => $nodes[$item->node_id],
  112. 'time' => (int) $item->hour,
  113. 'total' => round($item->total / GiB, 2),
  114. ])->toArray(); // 各线路小时消耗流量
  115. $daysFlow = $dailyQuery->whereNotNull('node_id')->whereDate('created_at', '>=', $startDate)->whereDate('created_at', '<=', $endDate)->selectRaw('node_id, DATE_FORMAT(created_at, "%m-%d") as date, u + d as total')->get()->map(fn ($item) => [
  116. 'id' => $item->node_id,
  117. 'name' => $nodes[$item->node_id],
  118. 'time' => $item->date,
  119. 'total' => round($item->total / GiB, 2),
  120. ])->toArray();
  121. if (Carbon::parse($hour_date)->isToday()) { // 如果日期是今天,本小时流量需要另外计算
  122. $currentHourFlow = $currentHourQuery->where('log_time', '>=', $currentTime->startOfHour()->timestamp)->groupBy('node_id')->selectRaw('node_id, sum(u + d) as total')->get()->map(fn ($item) => [
  123. 'id' => $item->node_id,
  124. 'name' => $nodes[$item->node_id],
  125. 'time' => $currentHour,
  126. 'total' => round($item->total / GiB, 2),
  127. ])->toArray();
  128. $hoursFlow = array_merge($hoursFlow, $currentHourFlow);
  129. if (Carbon::parse($endDate)->isToday()) {
  130. $currentDayFlow = collect($hoursFlow)->groupBy('id')->map(fn ($items) => [
  131. 'id' => $items->first()['id'],
  132. 'name' => $items->first()['name'],
  133. 'time' => $currentDate,
  134. 'total' => round($items->sum('total'), 2),
  135. ])->values()->toArray();
  136. $daysFlow = array_merge($daysFlow, $currentDayFlow);
  137. }
  138. } elseif (Carbon::parse($endDate)->isToday()) { // 如果结束日期是今天,本日流量需要另外计算
  139. $todayHourlyQuery = NodeHourlyDataFlow::query();
  140. if ($nodeId) { // 节点过滤
  141. $todayHourlyQuery->whereIn('node_id', $nodeId);
  142. }
  143. $hoursFlowToday = $todayHourlyQuery->whereDate('created_at', $currentTime)->selectRaw('node_id, HOUR(created_at) as hour, u + d as total')->get()->map(fn ($item) => [
  144. 'id' => $item->node_id,
  145. 'name' => $nodes[$item->node_id],
  146. 'time' => (int) $item->hour,
  147. 'total' => $item->total / GiB,
  148. ])->toArray();
  149. $currentHourFlow = $currentHourQuery->where('log_time', '>=', $currentTime->startOfHour()->timestamp)->groupBy('node_id')->selectRaw('node_id, sum(u + d) as total')->get()->map(fn ($item) => [
  150. 'id' => $item->node_id,
  151. 'name' => $nodes[$item->node_id],
  152. 'time' => $currentHour,
  153. 'total' => $item->total / GiB,
  154. ])->toArray();
  155. $currentDayFlow = collect($currentHourFlow)->merge($hoursFlowToday)->groupBy('id')->map(fn ($items) => [
  156. 'id' => $items->first()['id'],
  157. 'name' => $items->first()['name'],
  158. 'time' => $currentDate,
  159. 'total' => round($items->sum('total'), 2),
  160. ])->values()->toArray();
  161. $daysFlow = array_merge($daysFlow, $currentDayFlow);
  162. }
  163. $data['hourlyFlows'] = $hoursFlow;
  164. $data['dailyFlows'] = $daysFlow;
  165. $data['nodes'] = collect($daysFlow)->pluck('name', 'id')->unique()->toArray();
  166. $hour_dates = NodeHourlyDataFlow::selectRaw('DISTINCT DATE_FORMAT(created_at, "%Y-%m-%d") as formatted_date')->orderByDesc('formatted_date')->pluck('formatted_date')->toArray();
  167. return view('admin.report.nodeDataAnalysis', compact('data', 'nodes', 'hour_dates'));
  168. }
  169. public function siteAnalysis(Request $request): View
  170. {
  171. $nodeId = $request->input('node_id');
  172. $nodes = Node::orderBy('name')->pluck('name', 'id');
  173. // Fetch flows
  174. $flows = NodeDailyDataFlow::whereNodeId($nodeId)->selectRaw('DATE(created_at) as date, sum(u + d) as total')->groupBy('date')->get()->keyBy('date');
  175. $dailyFlows = $flows->filter(fn ($flow) => $flow->date >= now()->subMonthNoOverflow()->startOfMonth()->toDateString())->pluck('total', 'date');
  176. $monthlyFlows = $flows->groupBy(fn ($flow) => Carbon::parse($flow->date)->format('Y-m'))->map(fn ($rows) => round($rows->sum('total') / GiB, 2));
  177. $yearlyFlows = $flows->groupBy(fn ($flow) => Carbon::parse($flow->date)->format('Y'))->map(fn ($rows) => round($rows->sum('total') / TiB, 2));
  178. $currentDays = (int) date('j');
  179. $lastDays = (int) date('t', strtotime('-1 months'));
  180. $todayFlow = NodeHourlyDataFlow::whereDate('created_at', today())->when($nodeId, fn ($query) => $query->whereNodeId($nodeId))->sum(DB::raw('u + d')) / GiB;
  181. $thirtyDaysAgo = now()->subDays(30);
  182. $trafficData = NodeDailyDataFlow::where('node_id', $nodeId)->where('created_at', '>=', $thirtyDaysAgo)->selectRaw('SUM(u + d) as total, COUNT(*) as dataCounts')->first();
  183. $total30Days = $trafficData->total ?? 0;
  184. $daysWithData = max($trafficData->dataCounts ?? 0, 1);
  185. $months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
  186. $data = [
  187. 'days' => range(1, max($currentDays, $lastDays)),
  188. 'months' => array_map(static fn ($month) => Carbon::create(null, $month)->translatedFormat('F'), $months),
  189. 'currentMonth' => array_map(static fn ($i) => ($dailyFlows[date(sprintf('Y-m-%02u', $i))] ?? 0) / GiB, range(1, $currentDays)),
  190. 'lastMonth' => array_map(static fn ($i) => ($dailyFlows[date(sprintf('Y-m-%02u', $i), strtotime('first day of last month'))] ?? 0) / GiB, range(1, $lastDays)),
  191. 'currentYear' => array_map(static fn ($i) => $monthlyFlows[date(sprintf('Y-%02u', $i))] ?? 0, range(1, date('m'))),
  192. 'lastYear' => array_map(static fn ($i) => $monthlyFlows[date(sprintf('Y-%02u', $i), strtotime('-1 years'))] ?? 0, $months),
  193. 'yearlyFlows' => $yearlyFlows->toArray(),
  194. 'avgDaily30d' => round(($total30Days / GiB) / $daysWithData, 2),
  195. ];
  196. if ($nodeId) {
  197. $totalAll30d = NodeDailyDataFlow::where('created_at', '>=', $thirtyDaysAgo)->whereNull('node_id')->sum(DB::raw('u + d'));
  198. $data['nodePct30d'] = round(($total30Days / max($totalAll30d, 1)) * 100, 2);
  199. }
  200. $data['currentMonth'][$currentDays - 1] = $todayFlow;
  201. $data['currentYear'][count($data['currentYear']) - 1] += $todayFlow;
  202. return view('admin.report.siteDataAnalysis', compact('data', 'nodes'));
  203. }
  204. }