using Jiaowu.Api.Domain.Academic; using Jiaowu.Api.Domain.Identity; using Jiaowu.Api.Infrastructure.Auth; using Jiaowu.Api.Infrastructure.Localization; using Jiaowu.Api.Infrastructure.Persistence; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Localization; namespace Jiaowu.Api.Controllers; [ApiController] [Authorize] [Route("api/dashboard")] public sealed class DashboardController( AppDbContext db, ICurrentUserDataScope currentUserDataScope, IStringLocalizer localizer) : ControllerBase { private string L(string key, params object[] arguments) => localizer[key, arguments].Value; [HttpGet] public async Task> Get( CancellationToken cancellationToken) { var scope = currentUserDataScope.Current; Guid? restrictedCollegeId = scope.Scope == DataScope.All ? null : scope.CollegeId ?? Guid.Empty; var collegeName = restrictedCollegeId.HasValue && restrictedCollegeId.Value != Guid.Empty ? await db.Colleges.AsNoTracking() .Where(x => x.Id == restrictedCollegeId.Value) .Select(x => x.Name) .FirstOrDefaultAsync(cancellationToken) : null; var currentTerm = await db.AcademicTerms .AsNoTracking() .Where(x => x.IsCurrent) .Select(x => new DashboardTerm( x.Id, x.Name, x.StartDate, x.EndDate)) .FirstOrDefaultAsync(cancellationToken); var currentTermId = currentTerm?.Id; var students = db.Students.AsNoTracking() .Where(x => !restrictedCollegeId.HasValue || x.AdministrativeClass!.Major!.CollegeId == restrictedCollegeId.Value); var teachers = db.Teachers.AsNoTracking() .Where(x => !restrictedCollegeId.HasValue || x.CollegeId == restrictedCollegeId.Value); var courses = db.Courses.AsNoTracking() .Where(x => !restrictedCollegeId.HasValue || x.CollegeId == restrictedCollegeId.Value); var teachingTasks = db.TeachingTasks.AsNoTracking() .Where(x => currentTermId.HasValue && x.AcademicTermId == currentTermId.Value && (!restrictedCollegeId.HasValue || x.Course!.CollegeId == restrictedCollegeId.Value)); var gradeSheets = db.GradeSheets.AsNoTracking() .Where(x => currentTermId.HasValue && x.TeachingTask!.AcademicTermId == currentTermId.Value && (!restrictedCollegeId.HasValue || x.TeachingTask.Course!.CollegeId == restrictedCollegeId.Value)); var enrollments = db.CourseEnrollments.AsNoTracking() .Where(x => currentTermId.HasValue && x.Status == CourseEnrollmentStatus.Enrolled && x.CourseSelectionOffering!.CourseSelectionRound! .AcademicTermId == currentTermId.Value && (!restrictedCollegeId.HasValue || x.CourseSelectionOffering.TeachingTask!.Course!.CollegeId == restrictedCollegeId.Value)); var taskCount = await teachingTasks.CountAsync(cancellationToken); var publishedTaskCount = await teachingTasks.CountAsync( x => x.Status == TeachingTaskStatus.Published, cancellationToken); var scheduledTaskCount = currentTermId.HasValue ? await db.ScheduleEntries.AsNoTracking() .Where(x => x.SchedulePlan!.AcademicTermId == currentTermId.Value && x.SchedulePlan.Status == SchedulePlanStatus.Published && (!restrictedCollegeId.HasValue || x.TeachingTask!.Course!.CollegeId == restrictedCollegeId.Value)) .Select(x => x.TeachingTaskId) .Distinct() .CountAsync(cancellationToken) : 0; var gradeSheetCount = await gradeSheets.CountAsync(cancellationToken); var publishedGradeSheetCount = await gradeSheets.CountAsync( x => x.Status == GradeSheetStatus.Published, cancellationToken); var counts = new DashboardCounts( await students.CountAsync( x => x.Status == StudentStatus.Active, cancellationToken), await teachers.CountAsync( x => x.Status == TeacherStatus.Active, cancellationToken), await courses.CountAsync( x => x.IsEnabled, cancellationToken), taskCount, publishedTaskCount, scheduledTaskCount, await enrollments.CountAsync(cancellationToken), gradeSheetCount, publishedGradeSheetCount, await gradeSheets.CountAsync( x => x.Status == GradeSheetStatus.Submitted, cancellationToken), currentTermId.HasValue ? await db.CourseSelectionRounds.AsNoTracking().CountAsync( x => x.AcademicTermId == currentTermId.Value && x.Status == CourseSelectionRoundStatus.Open, cancellationToken) : 0); var pending = await LoadPendingAsync( scope, restrictedCollegeId, cancellationToken); return Ok(new DashboardResponse( BuildAudience(scope, collegeName), currentTerm, counts, pending, await BuildGreetingAsync(scope, currentTermId, counts, pending, cancellationToken), DateTime.UtcNow)); } [HttpGet("greeting")] public async Task> GetGreeting( CancellationToken cancellationToken) { var currentTermId = await db.AcademicTerms.AsNoTracking() .Where(x => x.IsCurrent) .Select(x => (Guid?)x.Id) .FirstOrDefaultAsync(cancellationToken); return Ok(await BuildGreetingAsync( currentUserDataScope.Current, currentTermId, null, null, cancellationToken)); } private async Task BuildGreetingAsync( CurrentUserScope scope, Guid? currentTermId, DashboardCounts? counts, DashboardPending? pending, CancellationToken cancellationToken) { var greeting = GetTimeGreeting(); var greetingTitle = string.IsNullOrWhiteSpace(scope.DisplayName) ? greeting : L("Dashboard.Greeting.Title", scope.DisplayName, greeting); var isManager = scope.IsInRole(SystemRoles.SuperAdmin) || scope.IsInRole(SystemRoles.AcademicAdmin) || scope.IsInRole(SystemRoles.CollegeAdmin) || scope.IsInRole(SystemRoles.Leader) || scope.IsInRole(SystemRoles.Counselor); if (!isManager && scope.IsInRole(SystemRoles.Student)) { var studentId = await db.Students.AsNoTracking() .Where(x => x.UserId == scope.UserId) .Select(x => (Guid?)x.Id) .FirstOrDefaultAsync(cancellationToken); if (!studentId.HasValue) return new DashboardGreeting("Student", greetingTitle, L("Dashboard.Student.Unbound.Subtitle"), L("Dashboard.Student.Label"), L("Dashboard.Student.Unbound.Narrative"), []); var student = await db.Students.AsNoTracking() .Where(x => x.Id == studentId.Value) .Select(x => new { x.AdministrativeClassId }) .FirstAsync(cancellationToken); var currentTasks = db.TeachingTasks.AsNoTracking().Where(task => currentTermId.HasValue && task.AcademicTermId == currentTermId.Value && task.Status == TeachingTaskStatus.Published && (task.Classes.Any(item => item.AdministrativeClassId == student.AdministrativeClassId) || db.CourseEnrollments.Any(enrollment => enrollment.StudentId == studentId.Value && enrollment.Status == CourseEnrollmentStatus.Enrolled && enrollment.CourseSelectionOffering!.TeachingTaskId == task.Id))); var taskWorkload = await currentTasks.Select(task => new { task.Id, task.CourseId, Credits = task.Course!.Credits, IsClassAssigned = task.Classes.Any(item => item.AdministrativeClassId == student.AdministrativeClassId) }).ToListAsync(cancellationToken); var currentCourses = taskWorkload .GroupBy(x => x.CourseId) .Select(x => x.First()) .ToList(); var courseCount = currentCourses.Count; var courseCredits = currentCourses.Sum(x => x.Credits); var classAssignedCount = taskWorkload.Count(x => x.IsClassAssigned); var selfSelectedCount = taskWorkload.Count(x => !x.IsClassAssigned); var publishedGrades = db.GradeRecords.AsNoTracking().Where(x => x.StudentId == studentId.Value && (x.PublishedAt != null || x.GradeSheet!.Status == GradeSheetStatus.Published) && currentTermId.HasValue && x.GradeSheet!.TeachingTask!.AcademicTermId == currentTermId.Value); var gradeCount = await publishedGrades.CountAsync(cancellationToken); var average = await publishedGrades .Where(x => x.ExamStatus == GradeExamStatus.Normal && x.TotalScore.HasValue) .AverageAsync(x => (decimal?)x.TotalScore, cancellationToken); var failed = await publishedGrades.CountAsync(x => x.ExamStatus == GradeExamStatus.Normal && (x.IsPassed == false || x.IsPassed == null && x.TotalScore.HasValue && x.TotalScore < 60), cancellationToken); var subtitle = failed > 0 ? L("Dashboard.Student.Subtitle.Failed", failed) : courseCount > 0 ? L("Dashboard.Student.Subtitle.Active", courseCount, courseCredits) : L("Dashboard.Student.Subtitle.Empty"); var narrative = courseCount == 0 ? L("Dashboard.Student.Narrative.Empty") : failed > 0 ? L("Dashboard.Student.Narrative.Failed", courseCount, classAssignedCount, failed) : gradeCount > 0 ? L("Dashboard.Student.Narrative.Published", courseCount, gradeCount) : L("Dashboard.Student.Narrative.Pending", courseCount, classAssignedCount, selfSelectedCount); return new DashboardGreeting("Student", greetingTitle, subtitle, L("Dashboard.Student.Label"), narrative, [ new DashboardGreetingInsight(L("Dashboard.Student.Insight.Courses"), L("Dashboard.Unit.Courses", courseCount), L("Dashboard.Unit.Credits", courseCredits), "calm"), new DashboardGreetingInsight(L("Dashboard.Student.Insight.Published"), L("Dashboard.Unit.Courses", gradeCount), average.HasValue ? L("Dashboard.Student.Average", average.Value) : L("Dashboard.Student.AwaitingGrades"), "calm"), new DashboardGreetingInsight(L("Dashboard.Student.Insight.Attention"), L("Dashboard.Unit.Courses", failed), failed > 0 ? L("Dashboard.Student.Attention.Required") : L("Dashboard.Student.Attention.None"), failed > 0 ? "attention" : "positive") ]); } if (!isManager && scope.IsInRole(SystemRoles.Teacher)) { var teacherId = await db.Teachers.AsNoTracking() .Where(x => x.UserId == scope.UserId && x.Status == TeacherStatus.Active) .Select(x => (Guid?)x.Id) .FirstOrDefaultAsync(cancellationToken); if (!teacherId.HasValue) return new DashboardGreeting("Teacher", greetingTitle, L("Dashboard.Teacher.Unbound.Subtitle"), L("Dashboard.Teacher.Label"), L("Dashboard.Teacher.Unbound.Narrative"), []); var tasks = db.TeachingTasks.AsNoTracking().Where(x => currentTermId.HasValue && x.AcademicTermId == currentTermId.Value && x.Teachers.Any(t => t.TeacherId == teacherId.Value)); var teachingClasses = await tasks.CountAsync(cancellationToken); var estimatedHours = await tasks.SumAsync( x => (int?)(x.WeeklyHours * (x.EndWeek - x.StartWeek + 1)), cancellationToken) ?? 0; var gradeSheets = db.GradeSheets.AsNoTracking().Where(x => x.TeachingTask!.Teachers.Any(t => t.TeacherId == teacherId.Value) && currentTermId.HasValue && x.TeachingTask.AcademicTermId == currentTermId.Value); var pendingGrades = await gradeSheets.CountAsync(x => x.Status == GradeSheetStatus.Draft || x.Status == GradeSheetStatus.Returned, cancellationToken); var submittedGrades = await gradeSheets.CountAsync(x => x.Status == GradeSheetStatus.Submitted, cancellationToken); var subtitle = pendingGrades > 0 ? L("Dashboard.Teacher.Subtitle.Pending", pendingGrades) : teachingClasses > 0 ? L("Dashboard.Teacher.Subtitle.Active", teachingClasses, estimatedHours) : L("Dashboard.Teacher.Subtitle.Empty"); var narrative = pendingGrades > 0 ? L("Dashboard.Teacher.Narrative.Pending", teachingClasses, estimatedHours, pendingGrades) : L("Dashboard.Teacher.Narrative.Clear", teachingClasses, estimatedHours); return new DashboardGreeting("Teacher", greetingTitle, subtitle, L("Dashboard.Teacher.Label"), narrative, [ new DashboardGreetingInsight(L("Dashboard.Teacher.Insight.Classes"), L("Dashboard.Unit.Classes", teachingClasses), L("Dashboard.Unit.Hours", estimatedHours), "calm"), new DashboardGreetingInsight(L("Dashboard.Teacher.Insight.Pending"), L("Dashboard.Unit.Sheets", pendingGrades), pendingGrades > 0 ? L("Dashboard.Teacher.Pending.Required") : L("Dashboard.Teacher.Pending.None"), pendingGrades > 0 ? "attention" : "positive"), new DashboardGreetingInsight(L("Dashboard.Teacher.Insight.Review"), L("Dashboard.Unit.Sheets", submittedGrades), submittedGrades > 0 ? L("Dashboard.Teacher.Review.Pending") : L("Dashboard.Teacher.Review.None"), "calm") ]); } var actionable = pending is null ? 0 : pending.TeacherApplications + pending.GradeSheets + pending.CourseAdjustments + pending.StudentStatusChanges + pending.GradeModifications + pending.ClassroomReservations + pending.GeneralApprovals; var taskCount = counts?.TeachingTasks ?? 0; var scheduledCount = counts?.ScheduledTeachingTasks ?? 0; var subtitleForManager = actionable > 0 ? L("Dashboard.Manager.Subtitle.Pending", actionable) : taskCount > 0 ? L("Dashboard.Manager.Subtitle.Active", taskCount) : L("Dashboard.Manager.Subtitle.Empty"); var managerNarrative = actionable > 0 ? L("Dashboard.Manager.Narrative.Pending", taskCount, scheduledCount, actionable) : L("Dashboard.Manager.Narrative.Clear", taskCount, scheduledCount); return new DashboardGreeting("Manager", greetingTitle, subtitleForManager, L("Dashboard.Manager.Label"), managerNarrative, [ new DashboardGreetingInsight(L("Dashboard.Manager.Insight.Pending"), L("Dashboard.Unit.Items", actionable), actionable > 0 ? L("Dashboard.Manager.Pending.Required") : L("Dashboard.Manager.Pending.None"), actionable > 0 ? "attention" : "positive"), new DashboardGreetingInsight(L("Dashboard.Manager.Insight.Classes"), L("Dashboard.Unit.Classes", taskCount), L("Dashboard.Manager.Scale"), "calm"), new DashboardGreetingInsight(L("Dashboard.Manager.Insight.Scheduled"), L("Dashboard.Unit.Classes", scheduledCount), taskCount > 0 ? L("Dashboard.Manager.Coverage", Math.Round(scheduledCount * 100d / taskCount)) : L("Dashboard.Manager.AwaitingTasks"), "calm") ]); } private string GetTimeGreeting() { var hour = DateTime.UtcNow.AddHours(8).Hour; return hour < 11 ? L("Dashboard.Greeting.Morning") : hour < 14 ? L("Dashboard.Greeting.Noon") : hour < 18 ? L("Dashboard.Greeting.Afternoon") : L("Dashboard.Greeting.Evening"); } private async Task LoadPendingAsync( CurrentUserScope scope, Guid? restrictedCollegeId, CancellationToken cancellationToken) { var isSchoolManager = scope.IsInRole(SystemRoles.SuperAdmin) || scope.IsInRole(SystemRoles.AcademicAdmin); var isCollegeManager = !isSchoolManager && scope.IsInRole(SystemRoles.CollegeAdmin); if (!isSchoolManager && !isCollegeManager) return new DashboardPending(0, 0, 0, 0, 0, 0, 0); var teacherApplications = db.TeacherCourseApplications.AsNoTracking() .Where(x => x.Status == TeacherCourseApplicationStatus.Pending && (!restrictedCollegeId.HasValue || x.Teacher!.CollegeId == restrictedCollegeId.Value)); var gradeSheets = db.GradeSheets.AsNoTracking() .Where(x => x.Status == GradeSheetStatus.Submitted && (!restrictedCollegeId.HasValue || x.TeachingTask!.Course!.CollegeId == restrictedCollegeId.Value)); var courseAdjustments = db.CourseAdjustments.AsNoTracking() .Where(x => x.Status == CourseAdjustmentStatus.Submitted && (!restrictedCollegeId.HasValue || x.TeachingTask!.Course!.CollegeId == restrictedCollegeId.Value)); var studentStatusChanges = db.StudentStatusChanges.AsNoTracking() .Where(x => x.State == (isCollegeManager ? StudentStatusChangeState.CounselorApproved : StudentStatusChangeState.CollegeApproved) && (!restrictedCollegeId.HasValue || x.Student!.AdministrativeClass!.Major!.CollegeId == restrictedCollegeId.Value)); var gradeModifications = db.GradeModifications.AsNoTracking() .Where(x => x.Status == (isCollegeManager ? GradeModificationStatus.TeacherSubmitted : GradeModificationStatus.CollegeApproved) && (!restrictedCollegeId.HasValue || x.GradeRecord!.GradeSheet!.TeachingTask!.Course!.CollegeId == restrictedCollegeId.Value)); var generalApprovals = await db.CourseExemptions.AsNoTracking().CountAsync( x => x.Status == ApprovalStatus.Submitted && (!restrictedCollegeId.HasValue || x.TeachingTask!.Course!.CollegeId == restrictedCollegeId.Value), cancellationToken) + await db.DeferredExams.AsNoTracking().CountAsync( x => x.Status == ApprovalStatus.Submitted && (!restrictedCollegeId.HasValue || x.TeachingTask!.Course!.CollegeId == restrictedCollegeId.Value), cancellationToken) + await db.CourseSubstitutions.AsNoTracking().CountAsync( x => x.Status == ApprovalStatus.Submitted && (!restrictedCollegeId.HasValue || x.Student!.AdministrativeClass!.Major!.CollegeId == restrictedCollegeId.Value), cancellationToken) + await db.AttendanceRecords.AsNoTracking().CountAsync( x => x.AppealStatus == AttendanceAppealStatus.Pending && (!restrictedCollegeId.HasValue || x.Student!.AdministrativeClass!.Major!.CollegeId == restrictedCollegeId.Value), cancellationToken); var classroomReservations = isCollegeManager && restrictedCollegeId.HasValue ? await db.ClassroomReservations.AsNoTracking().CountAsync( x => x.Status == ClassroomReservationStatus.Submitted && x.ApplicantCollegeId == restrictedCollegeId.Value, cancellationToken) : 0; return new DashboardPending( await teacherApplications.CountAsync(cancellationToken), await gradeSheets.CountAsync(cancellationToken), await courseAdjustments.CountAsync(cancellationToken), await studentStatusChanges.CountAsync(cancellationToken), await gradeModifications.CountAsync(cancellationToken), classroomReservations, generalApprovals); } private DashboardAudience BuildAudience( CurrentUserScope scope, string? collegeName) { if (scope.IsInRole(SystemRoles.SuperAdmin)) return new DashboardAudience( "System", L("Dashboard.Audience.System.Title"), L("Dashboard.Audience.AllSchool"), L("Dashboard.Audience.System.Description")); if (scope.IsInRole(SystemRoles.AcademicAdmin)) return new DashboardAudience( "School", L("Dashboard.Audience.School.Title"), L("Dashboard.Audience.AllSchool"), L("Dashboard.Audience.School.Description")); if (scope.IsInRole(SystemRoles.CollegeAdmin)) return new DashboardAudience( "College", L("Dashboard.Audience.College.Title"), collegeName ?? L("Dashboard.Audience.ThisCollege"), L("Dashboard.Audience.College.Description")); if (scope.IsInRole(SystemRoles.Leader)) return new DashboardAudience( "Leadership", L("Dashboard.Audience.Leadership.Title"), L("Dashboard.Audience.AllSchool"), L("Dashboard.Audience.Leadership.Description")); if (scope.IsInRole(SystemRoles.Counselor)) return new DashboardAudience( "Counselor", L("Dashboard.Audience.Counselor.Title"), collegeName ?? L("Dashboard.Audience.ManagedClasses"), L("Dashboard.Audience.Counselor.Description")); return new DashboardAudience( "Teaching", L("Dashboard.Audience.Teaching.Title"), collegeName ?? L("Dashboard.Audience.PersonalTeaching"), L("Dashboard.Audience.Teaching.Description")); } } public sealed record DashboardResponse( DashboardAudience Audience, DashboardTerm? CurrentTerm, DashboardCounts Counts, DashboardPending Pending, DashboardGreeting Greeting, DateTime GeneratedAt); public sealed record DashboardGreeting( string Role, string Title, string Subtitle, string Label, string Narrative, IReadOnlyList Insights); public sealed record DashboardGreetingInsight( string Label, string Value, string Hint, string Tone); public sealed record DashboardAudience( string Level, string Title, string ScopeName, string Description); public sealed record DashboardTerm( Guid Id, string Name, DateOnly StartDate, DateOnly EndDate); public sealed record DashboardCounts( int Students, int Teachers, int Courses, int TeachingTasks, int PublishedTeachingTasks, int ScheduledTeachingTasks, int CourseEnrollments, int GradeSheets, int PublishedGradeSheets, int SubmittedGradeSheets, int OpenCourseSelectionRounds); public sealed record DashboardPending( int TeacherApplications, int GradeSheets, int CourseAdjustments, int StudentStatusChanges, int GradeModifications, int ClassroomReservations, int GeneralApprovals);