StudentStatsWidget.php 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. $currentUser = auth()->user();
  13. $isTeacher = $currentUser?->isTeacher() ?? false;
  14. // 构建基础查询(带老师过滤)
  15. $baseQuery = DB::table('students');
  16. if ($isTeacher) {
  17. $teacherId = $currentUser?->teacher?->teacher_id;
  18. if ($teacherId) {
  19. $baseQuery->where('teacher_id', $teacherId);
  20. }
  21. }
  22. // 总学生数
  23. $totalStudents = (clone $baseQuery)->count();
  24. // 本月新增学生
  25. $newStudentsThisMonth = (clone $baseQuery)
  26. ->whereMonth('created_at', Carbon::now()->month)
  27. ->whereYear('created_at', Carbon::now()->year)
  28. ->count();
  29. // 有登录记录的学生数
  30. $activeStudents = (clone $baseQuery)
  31. ->join('users', 'students.student_id', '=', 'users.user_id')
  32. ->whereNotNull('users.last_login')
  33. ->count();
  34. // 本周登录的学生数
  35. $weeklyActiveStudents = (clone $baseQuery)
  36. ->join('users', 'students.student_id', '=', 'users.user_id')
  37. ->where('users.last_login', '>=', Carbon::now()->subWeek())
  38. ->count();
  39. // 按年级统计
  40. $gradeStats = (clone $baseQuery)
  41. ->select('grade', DB::raw('count(*) as count'))
  42. ->groupBy('grade')
  43. ->orderBy('count', 'desc')
  44. ->get();
  45. // 按班级统计
  46. $classStats = (clone $baseQuery)
  47. ->select('class_name', DB::raw('count(*) as count'))
  48. ->groupBy('class_name')
  49. ->orderBy('count', 'desc')
  50. ->limit(5)
  51. ->get();
  52. // 设置描述文本
  53. $description = $isTeacher ? '我的学生' : '全平台注册学生';
  54. return [
  55. Stat::make('总学生数', $totalStudents)
  56. ->description($description)
  57. ->descriptionIcon('heroicon-m-academic-cap')
  58. ->color('primary')
  59. ->chart([7, 15, 23, 38, 45, 52, $totalStudents]),
  60. Stat::make('本月新增', $newStudentsThisMonth)
  61. ->description('较上月 ' . ($newStudentsThisMonth > 0 ? '+' : '') . $newStudentsThisMonth)
  62. ->descriptionIcon('heroicon-m-arrow-trending-up')
  63. ->color($newStudentsThisMonth > 0 ? 'success' : 'gray'),
  64. Stat::make('活跃学生', $activeStudents)
  65. ->description('至少登录过一次')
  66. ->descriptionIcon('heroicon-m-user')
  67. ->color('info'),
  68. Stat::make('本周活跃', $weeklyActiveStudents)
  69. ->description('最近7天登录')
  70. ->descriptionIcon('heroicon-m-clock')
  71. ->color($weeklyActiveStudents > 0 ? 'success' : 'warning'),
  72. ];
  73. }
  74. protected function getColumns(): int
  75. {
  76. return 4;
  77. }
  78. }