ReportController.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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()->format('Y-m-d'))->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'))->format('Y-m-d'),
  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()
  67. ->whereNotNull('node_id')
  68. ->whereDate('created_at', $currentTime)
  69. ->with('node:id,name')
  70. ->selectRaw('node_id, HOUR(created_at) as hour, u + d as total')
  71. ->get();
  72. $currentHourFlow = $user->dataFlowLogs()
  73. ->where('log_time', '>=', $currentTime->startOfHour()->timestamp)
  74. ->with('node:id,name')
  75. ->groupBy('node_id')
  76. ->selectRaw('node_id, ? as hour, sum(u + d) as total', [$currentTime->hour])
  77. ->get();
  78. $todayData = $todayHoursFlow->concat($currentHourFlow)
  79. ->groupBy('node_id')
  80. ->map(function ($items) use ($mapFlow) {
  81. $hourlyData = $items->mapWithKeys(fn ($item) => [$item->hour => $mapFlow($item)]);
  82. $totalFlow = $items->sum('total');
  83. return [
  84. 'hourly' => $hourlyData,
  85. 'daily' => $mapFlow((object) [
  86. 'node_id' => $items->first()->node_id,
  87. 'node' => $items->first()->node,
  88. 'created_at' => Carbon::today(),
  89. 'total' => $totalFlow,
  90. ], 'date'),
  91. ];
  92. });
  93. }
  94. // 处理小时数据
  95. if ($hourlyDate->isToday() && $todayData) {
  96. $hourlyFlows = $todayData->flatMap(fn ($item) => $item['hourly'])->values();
  97. } else {
  98. $hourlyFlows = $user->hourlyDataFlows()
  99. ->whereNotNull('node_id')
  100. ->whereDate('created_at', $hourlyDate)
  101. ->with('node:id,name')
  102. ->selectRaw('node_id, HOUR(created_at) as hour, u + d as total')
  103. ->get()
  104. ->map(fn ($item) => $mapFlow($item));
  105. }
  106. // 处理每日数据
  107. $dailyFlows = $user->dailyDataFlows()
  108. ->whereNotNull('node_id')
  109. ->whereBetween('created_at', [$startDate, $endDate])
  110. ->with('node:id,name')
  111. ->selectRaw('node_id, DATE_FORMAT(created_at, "%m-%d") as date, u + d as total')
  112. ->get()
  113. ->map(fn ($item) => $mapFlow($item, 'date'));
  114. if ($endDate->isToday() && $todayData) {
  115. $dailyFlows = $dailyFlows->concat($todayData->map(fn ($item) => $item['daily']));
  116. }
  117. $data = array_merge($data, [
  118. 'hours' => range(0, 23),
  119. 'days' => collect(CarbonPeriod::create($startDate, $endDate))->map(fn ($date) => $date->format('m-d')),
  120. 'nodes' => $hourlyFlows->concat($dailyFlows)->pluck('name', 'id')->unique()->toArray(),
  121. 'hourlyFlows' => $hourlyFlows->toArray(),
  122. 'dailyFlows' => $dailyFlows->toArray(),
  123. 'hour_dates' => UserHourlyDataFlow::selectRaw('DISTINCT DATE(created_at) as date')
  124. ->orderByDesc('date')
  125. ->pluck('date')
  126. ->toArray(),
  127. ]);
  128. }
  129. return view('admin.report.userDataAnalysis', compact('data'));
  130. }
  131. public function nodeAnalysis(Request $request)
  132. {
  133. $currentTime = now();
  134. $currentDate = $currentTime->format('m-d');
  135. $currentHour = $currentTime->hour;
  136. $nodeId = $request->input('nodes');
  137. $startDate = $request->input('start') ?? $currentTime->format('Y-m-01');
  138. $endDate = $request->input('end') ?? $currentTime->format('Y-m-d');
  139. $hour_date = $request->input('hour_date') ?? $currentTime; // 默认是今天
  140. $nodes = Node::orderBy('name')->pluck('name', 'id'); // 用于前端节点显示
  141. $currentHourQuery = UserDataFlowLog::query();
  142. $hourlyQuery = NodeHourlyDataFlow::query();
  143. $dailyQuery = NodeDailyDataFlow::query();
  144. if ($nodeId) { // 节点过滤
  145. $currentHourQuery->whereIn('node_id', $nodeId);
  146. $hourlyQuery->whereIn('node_id', $nodeId);
  147. $dailyQuery->whereIn('node_id', $nodeId);
  148. }
  149. $data = [
  150. 'hours' => range(0, 23),
  151. 'start_date' => Carbon::parse(NodeDailyDataFlow::orderBy('created_at')->value('created_at'))->format('Y-m-d'), // 数据库里最早的日期
  152. ];
  153. $hoursFlow = $hourlyQuery->whereDate('created_at', $hour_date)->selectRaw('node_id, HOUR(created_at) as hour, u + d as total')->get()->map(fn ($item) => [
  154. 'id' => $item->node_id,
  155. 'name' => $nodes[$item->node_id],
  156. 'time' => (int) $item->hour,
  157. 'total' => round($item->total / GiB, 2),
  158. ])->toArray(); // 各线路小时消耗流量
  159. $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) => [
  160. 'id' => $item->node_id,
  161. 'name' => $nodes[$item->node_id],
  162. 'time' => $item->date,
  163. 'total' => round($item->total / GiB, 2),
  164. ])->toArray();
  165. if (Carbon::parse($hour_date)->isToday()) { // 如果日期是今天,本小时流量需要另外计算
  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' => round($item->total / GiB, 2),
  171. ])->toArray();
  172. $hoursFlow = array_merge($hoursFlow, $currentHourFlow);
  173. if (Carbon::parse($endDate)->isToday()) {
  174. $currentDayFlow = collect($hoursFlow)->groupBy('id')->map(fn ($items) => [
  175. 'id' => $items->first()['id'],
  176. 'name' => $items->first()['name'],
  177. 'time' => $currentDate,
  178. 'total' => round($items->sum('total'), 2),
  179. ])->values()->toArray();
  180. $daysFlow = array_merge($daysFlow, $currentDayFlow);
  181. }
  182. } elseif (Carbon::parse($endDate)->isToday()) { // 如果结束日期是今天,本日流量需要另外计算
  183. $todayHourlyQuery = NodeHourlyDataFlow::query();
  184. if ($nodeId) { // 节点过滤
  185. $todayHourlyQuery->whereIn('node_id', $nodeId);
  186. }
  187. $hoursFlowToday = $todayHourlyQuery->whereDate('created_at', $currentTime)->selectRaw('node_id, HOUR(created_at) as hour, u + d as total')->get()->map(fn ($item) => [
  188. 'id' => $item->node_id,
  189. 'name' => $nodes[$item->node_id],
  190. 'time' => (int) $item->hour,
  191. 'total' => $item->total / GiB,
  192. ])->toArray();
  193. $currentHourFlow = $currentHourQuery->where('log_time', '>=', $currentTime->startOfHour()->timestamp)->groupBy('node_id')->selectRaw('node_id, sum(u + d) as total')->get()->map(fn ($item) => [
  194. 'id' => $item->node_id,
  195. 'name' => $nodes[$item->node_id],
  196. 'time' => $currentHour,
  197. 'total' => $item->total / GiB,
  198. ])->toArray();
  199. $currentDayFlow = collect($currentHourFlow)->merge($hoursFlowToday)->groupBy('id')->map(fn ($items) => [
  200. 'id' => $items->first()['id'],
  201. 'name' => $items->first()['name'],
  202. 'time' => $currentDate,
  203. 'total' => round($items->sum('total'), 2),
  204. ])->values()->toArray();
  205. $daysFlow = array_merge($daysFlow, $currentDayFlow);
  206. }
  207. $data['hourlyFlows'] = $hoursFlow;
  208. $data['dailyFlows'] = $daysFlow;
  209. $data['nodes'] = collect($daysFlow)->pluck('name', 'id')->unique()->toArray();
  210. $hour_dates = NodeHourlyDataFlow::selectRaw('DISTINCT DATE_FORMAT(created_at, "%Y-%m-%d") as formatted_date')->orderByDesc('formatted_date')->pluck('formatted_date')->toArray();
  211. return view('admin.report.nodeDataAnalysis', compact('data', 'nodes', 'hour_dates'));
  212. }
  213. public function siteAnalysis(Request $request): View
  214. {
  215. $nodeId = $request->input('node_id');
  216. $nodes = Node::orderBy('name')->pluck('name', 'id');
  217. // Fetch flows
  218. $flows = NodeDailyDataFlow::whereNodeId($nodeId)->selectRaw('DATE(created_at) as date, sum(u + d) as total')->groupBy('date')->get()->keyBy('date');
  219. $dailyFlows = $flows->filter(fn ($flow) => $flow->date >= now()->subMonthNoOverflow()->startOfMonth()->toDateString())->pluck('total', 'date');
  220. $monthlyFlows = $flows->groupBy(fn ($flow) => Carbon::parse($flow->date)->format('Y-m'))->map(fn ($rows) => round($rows->sum('total') / GiB, 2));
  221. $yearlyFlows = $flows->groupBy(fn ($flow) => Carbon::parse($flow->date)->format('Y'))->map(fn ($rows) => round($rows->sum('total') / TiB, 2));
  222. $currentDays = (int) date('j');
  223. $lastDays = (int) date('t', strtotime('-1 months'));
  224. $todayFlow = NodeHourlyDataFlow::whereDate('created_at', today())->when($nodeId, fn ($query) => $query->whereNodeId($nodeId))->sum(DB::raw('u + d')) / GiB;
  225. $thirtyDaysAgo = now()->subDays(30);
  226. $trafficData = NodeDailyDataFlow::where('node_id', $nodeId)->where('created_at', '>=', $thirtyDaysAgo)->selectRaw('SUM(u + d) as total, COUNT(*) as dataCounts')->first();
  227. $total30Days = $trafficData->total ?? 0;
  228. $daysWithData = max($trafficData->dataCounts ?? 0, 1);
  229. $months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
  230. $data = [
  231. 'days' => range(1, max($currentDays, $lastDays)),
  232. 'months' => array_map(static fn ($month) => Carbon::create(null, $month)->translatedFormat('F'), $months),
  233. 'currentMonth' => array_map(static fn ($i) => ($dailyFlows[date(sprintf('Y-m-%02u', $i))] ?? 0) / GiB, range(1, $currentDays)),
  234. 'lastMonth' => array_map(static fn ($i) => ($dailyFlows[date(sprintf('Y-m-%02u', $i), strtotime('first day of last month'))] ?? 0) / GiB, range(1, $lastDays)),
  235. 'currentYear' => array_map(static fn ($i) => $monthlyFlows[date(sprintf('Y-%02u', $i))] ?? 0, range(1, date('m'))),
  236. 'lastYear' => array_map(static fn ($i) => $monthlyFlows[date(sprintf('Y-%02u', $i), strtotime('-1 years'))] ?? 0, $months),
  237. 'yearlyFlows' => $yearlyFlows->toArray(),
  238. 'avgDaily30d' => round(($total30Days / GiB) / $daysWithData, 2),
  239. ];
  240. if ($nodeId) {
  241. $totalAll30d = NodeDailyDataFlow::where('created_at', '>=', $thirtyDaysAgo)->whereNull('node_id')->sum(DB::raw('u + d'));
  242. $data['nodePct30d'] = round(($total30Days / max($totalAll30d, 1)) * 100, 2);
  243. }
  244. $data['currentMonth'][$currentDays - 1] = $todayFlow;
  245. $data['currentYear'][count($data['currentYear']) - 1] += $todayFlow;
  246. return view('admin.report.siteDataAnalysis', compact('data', 'nodes'));
  247. }
  248. }