ReportController.php 14 KB

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