StudentStatsWidget.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace App\Filament\Widgets;
  3. use Filament\Widgets\StatsOverviewWidget as BaseWidget;
  4. use Filament\Widgets\StatsOverviewWidget\Stat;
  5. use Illuminate\Support\Facades\DB;
  6. use Illuminate\Support\Carbon;
  7. class StudentStatsWidget extends BaseWidget
  8. {
  9. protected static ?int $sort = 1;
  10. protected function getStats(): array
  11. {
  12. // 总学生数
  13. $totalStudents = DB::table('students')->count();
  14. // 本月新增学生
  15. $newStudentsThisMonth = DB::table('students')
  16. ->whereMonth('created_at', Carbon::now()->month)
  17. ->whereYear('created_at', Carbon::now()->year)
  18. ->count();
  19. // 有登录记录的学生数
  20. $activeStudents = DB::table('students')
  21. ->join('users', 'students.student_id', '=', 'users.user_id')
  22. ->whereNotNull('users.last_login')
  23. ->count();
  24. // 本周登录的学生数
  25. $weeklyActiveStudents = DB::table('students')
  26. ->join('users', 'students.student_id', '=', 'users.user_id')
  27. ->where('users.last_login', '>=', Carbon::now()->subWeek())
  28. ->count();
  29. // 按年级统计
  30. $gradeStats = DB::table('students')
  31. ->select('grade', DB::raw('count(*) as count'))
  32. ->groupBy('grade')
  33. ->orderBy('count', 'desc')
  34. ->get();
  35. // 按班级统计
  36. $classStats = DB::table('students')
  37. ->select('class_name', DB::raw('count(*) as count'))
  38. ->groupBy('class_name')
  39. ->orderBy('count', 'desc')
  40. ->limit(5)
  41. ->get();
  42. return [
  43. Stat::make('总学生数', $totalStudents)
  44. ->description('全平台注册学生')
  45. ->descriptionIcon('heroicon-m-academic-cap')
  46. ->color('primary')
  47. ->chart([7, 15, 23, 38, 45, 52, $totalStudents]),
  48. Stat::make('本月新增', $newStudentsThisMonth)
  49. ->description('较上月 ' . ($newStudentsThisMonth > 0 ? '+' : '') . $newStudentsThisMonth)
  50. ->descriptionIcon('heroicon-m-arrow-trending-up')
  51. ->color($newStudentsThisMonth > 0 ? 'success' : 'gray'),
  52. Stat::make('活跃学生', $activeStudents)
  53. ->description('至少登录过一次')
  54. ->descriptionIcon('heroicon-m-user')
  55. ->color('info'),
  56. Stat::make('本周活跃', $weeklyActiveStudents)
  57. ->description('最近7天登录')
  58. ->descriptionIcon('heroicon-m-clock')
  59. ->color($weeklyActiveStudents > 0 ? 'success' : 'warning'),
  60. ];
  61. }
  62. protected function getColumns(): int
  63. {
  64. return 4;
  65. }
  66. }