diff --git a/src/Jiaowu.Api/Controllers/ApprovalsController.cs b/src/Jiaowu.Api/Controllers/ApprovalsController.cs index 7ed66b0..b16268a 100644 --- a/src/Jiaowu.Api/Controllers/ApprovalsController.cs +++ b/src/Jiaowu.Api/Controllers/ApprovalsController.cs @@ -167,11 +167,15 @@ public sealed class ApprovalsController( int pageSize = 20, CancellationToken ct = default, bool oldestFirst = false, - string? type = null) + string? type = null, + int? overdueHours = null) { if (page < 1 || pageSize is < 1 or > 100 || (long)page * pageSize > 100000) return ValidationProblem("page 必须大于 0,pageSize 必须在 1 到 100 之间,且分页窗口不能超过 100000 条。"); + if (overdueHours is < 1 or > 8760) + return ValidationProblem("等待时长必须在 1 到 8760 小时之间。"); + var cutoff = overdueHours.HasValue ? DateTime.UtcNow.AddHours(-overdueHours.Value) : (DateTime?)null; var take = checked(page * pageSize); var total = 0; var counts = new Dictionary(); @@ -193,67 +197,67 @@ public sealed class ApprovalsController( var substitutions = Scoped(x => x.Status == ApprovalStatus.Submitted && (super || x.ReviewerRoleSnapshot == null || x.ReviewerRoleSnapshot == "AnyManager" || (college && x.ReviewerRoleSnapshot == SystemRoles.CollegeAdmin) || (academic && x.ReviewerRoleSnapshot == SystemRoles.AcademicAdmin))); items.AddRange(await exemptions - .OrderByApprovalTime(x => x.SubmittedAt, oldestFirst).ThenBy(x => x.Id).Take(take) + .WhereApprovalBefore(x => x.SubmittedAt, cutoff).OrderByApprovalTime(x => x.SubmittedAt, oldestFirst).ThenBy(x => x.Id).Take(take) .Select(x => new ApprovalItem(x.Id, "CourseExemption", "免修", $"{x.Student!.Name} — 《{x.TeachingTask!.Course!.Name}》", x.Reason, x.SubmittedAt, x.TeachingTask.Course!.College!.Name)) .ToListAsync(ct)); - AddCount("CourseExemption", await exemptions.CountAsync(ct)); + AddCount("CourseExemption", await exemptions.WhereApprovalBefore(x => x.SubmittedAt, cutoff).CountAsync(ct)); items.AddRange(await deferred - .OrderByApprovalTime(x => x.SubmittedAt, oldestFirst).ThenBy(x => x.Id).Take(take) + .WhereApprovalBefore(x => x.SubmittedAt, cutoff).OrderByApprovalTime(x => x.SubmittedAt, oldestFirst).ThenBy(x => x.Id).Take(take) .Select(x => new ApprovalItem(x.Id, "DeferredExam", "缓考", $"{x.Student!.Name} — 《{x.TeachingTask!.Course!.Name}》", x.Reason, x.SubmittedAt, x.TeachingTask.Course!.College!.Name)) .ToListAsync(ct)); - AddCount("DeferredExam", await deferred.CountAsync(ct)); + AddCount("DeferredExam", await deferred.WhereApprovalBefore(x => x.SubmittedAt, cutoff).CountAsync(ct)); var canFinalReview = scope.Current.IsInRole(SystemRoles.SuperAdmin) || scope.Current.IsInRole(SystemRoles.AcademicAdmin); items.AddRange(await Scoped(x => x.Status == GradeModificationStatus.TeacherSubmitted || (canFinalReview && x.Status == GradeModificationStatus.CollegeApproved)) - .OrderByApprovalTime(x => x.SubmittedAt, oldestFirst).ThenBy(x => x.Id).Take(take) + .WhereApprovalBefore(x => x.SubmittedAt, cutoff).OrderByApprovalTime(x => x.SubmittedAt, oldestFirst).ThenBy(x => x.Id).Take(take) .Select(x => new ApprovalItem(x.Id, "GradeModification", "成绩修改", $"{x.GradeRecord!.Student!.Name} — 《{x.GradeRecord.GradeSheet!.TeachingTask!.Course!.Name}》", $"{x.CurrentScore} → {x.RequestedScore}:{x.Reason}", x.SubmittedAt, x.GradeRecord.GradeSheet.TeachingTask.Course!.College!.Name, x.Status == GradeModificationStatus.TeacherSubmitted ? "college" : "final")) .ToListAsync(ct)); - AddCount("GradeModification", await Scoped(x => x.Status == GradeModificationStatus.TeacherSubmitted || (canFinalReview && x.Status == GradeModificationStatus.CollegeApproved)).CountAsync(ct)); + AddCount("GradeModification", await Scoped(x => x.Status == GradeModificationStatus.TeacherSubmitted || (canFinalReview && x.Status == GradeModificationStatus.CollegeApproved)).WhereApprovalBefore(x => x.SubmittedAt, cutoff).CountAsync(ct)); items.AddRange(await substitutions - .OrderByApprovalTime(x => x.SubmittedAt, oldestFirst).ThenBy(x => x.Id).Take(take) + .WhereApprovalBefore(x => x.SubmittedAt, cutoff).OrderByApprovalTime(x => x.SubmittedAt, oldestFirst).ThenBy(x => x.Id).Take(take) .Select(x => new ApprovalItem(x.Id, "CourseSubstitution", "课程替代", $"{x.Student!.Name}:{x.SubstituteCourse!.Name} → {x.OriginalCourse!.Name}", x.Reason, x.SubmittedAt, x.Student.AdministrativeClass!.Major!.College!.Name)) .ToListAsync(ct)); - AddCount("CourseSubstitution", await substitutions.CountAsync(ct)); + AddCount("CourseSubstitution", await substitutions.WhereApprovalBefore(x => x.SubmittedAt, cutoff).CountAsync(ct)); var canCollegeReview = scope.Current.IsInRole(SystemRoles.CollegeAdmin); items.AddRange(await Scoped(x => (canCollegeReview && x.State == StudentStatusChangeState.CounselorApproved) || (canFinalReview && x.State == StudentStatusChangeState.CollegeApproved)) - .OrderByApprovalTime(x => x.SubmittedAt, oldestFirst).ThenBy(x => x.Id).Take(take) + .WhereApprovalBefore(x => x.SubmittedAt, cutoff).OrderByApprovalTime(x => x.SubmittedAt, oldestFirst).ThenBy(x => x.Id).Take(take) .Select(x => new ApprovalItem(x.Id, "StudentStatusChange", "学籍异动", $"{x.Student!.Name} — {SSCLabel(x.Type)}", x.Reason, x.SubmittedAt, x.Student.AdministrativeClass!.Major!.College!.Name, x.State == StudentStatusChangeState.CounselorApproved ? "college" : "final")) .ToListAsync(ct)); - AddCount("StudentStatusChange", await Scoped(x => (canCollegeReview && x.State == StudentStatusChangeState.CounselorApproved) || (canFinalReview && x.State == StudentStatusChangeState.CollegeApproved)).CountAsync(ct)); + AddCount("StudentStatusChange", await Scoped(x => (canCollegeReview && x.State == StudentStatusChangeState.CounselorApproved) || (canFinalReview && x.State == StudentStatusChangeState.CollegeApproved)).WhereApprovalBefore(x => x.SubmittedAt, cutoff).CountAsync(ct)); items.AddRange(await Scoped(x => x.Status == CourseAdjustmentStatus.Submitted) - .OrderByApprovalTime(x => x.SubmittedAt ?? x.CreatedAt, oldestFirst).ThenBy(x => x.Id).Take(take) + .WhereApprovalBefore(x => x.SubmittedAt ?? x.CreatedAt, cutoff).OrderByApprovalTime(x => x.SubmittedAt ?? x.CreatedAt, oldestFirst).ThenBy(x => x.Id).Take(take) .Select(x => new ApprovalItem(x.Id, "CourseAdjustment", CALabel(x.Type), $"《{x.TeachingTask!.Course!.Name}》", x.Reason, x.SubmittedAt ?? x.CreatedAt, x.TeachingTask.Course.College!.Name)) .ToListAsync(ct)); - AddCount("CourseAdjustment", await Scoped(x => x.Status == CourseAdjustmentStatus.Submitted).CountAsync(ct)); + AddCount("CourseAdjustment", await Scoped(x => x.Status == CourseAdjustmentStatus.Submitted).WhereApprovalBefore(x => x.SubmittedAt ?? x.CreatedAt, cutoff).CountAsync(ct)); items.AddRange(await Scoped(x => x.Status == GradeSheetStatus.Submitted) - .OrderByApprovalTime(x => x.SubmittedAt ?? x.CreatedAt, oldestFirst).ThenBy(x => x.Id).Take(take) + .WhereApprovalBefore(x => x.SubmittedAt ?? x.CreatedAt, cutoff).OrderByApprovalTime(x => x.SubmittedAt ?? x.CreatedAt, oldestFirst).ThenBy(x => x.Id).Take(take) .Select(x => new ApprovalItem(x.Id, "GradeSheet", "成绩审核", $"《{x.TeachingTask!.Course!.Name}》— {x.Records.Count}人", "教师已提交成绩", x.SubmittedAt ?? x.CreatedAt, x.TeachingTask.Course.College!.Name)) .ToListAsync(ct)); - AddCount("GradeSheet", await Scoped(x => x.Status == GradeSheetStatus.Submitted).CountAsync(ct)); + AddCount("GradeSheet", await Scoped(x => x.Status == GradeSheetStatus.Submitted).WhereApprovalBefore(x => x.SubmittedAt ?? x.CreatedAt, cutoff).CountAsync(ct)); var attendance = db.AttendanceRecords.AsNoTracking().Where(x => x.AppealStatus == AttendanceAppealStatus.Pending && x.AttendanceSheet!.TeachingTask!.Status == TeachingTaskStatus.Published); if (!canFinalReview) attendance = attendance.Where(x => x.AttendanceSheet!.TeachingTask!.Teachers.Any(t => t.Teacher!.UserId == current.UserId)); items.AddRange(await attendance - .OrderByApprovalTime(x => x.AppealSubmittedAt ?? x.AttendanceSheet!.CreatedAt, oldestFirst).ThenBy(x => x.StudentId).ThenBy(x => x.AttendanceSheetId).Take(take) + .WhereApprovalBefore(x => x.AppealSubmittedAt ?? x.AttendanceSheet!.CreatedAt, cutoff).OrderByApprovalTime(x => x.AppealSubmittedAt ?? x.AttendanceSheet!.CreatedAt, oldestFirst).ThenBy(x => x.StudentId).ThenBy(x => x.AttendanceSheetId).Take(take) .Select(x => new ApprovalItem(x.StudentId, "AttendanceAppeal", "考勤申诉", $"{x.Student!.Name} — 《{x.AttendanceSheet!.TeachingTask!.Course!.Name}》", x.AppealReason ?? "", x.AppealSubmittedAt ?? x.AttendanceSheet.CreatedAt, x.Student.AdministrativeClass!.Major!.College!.Name, null, x.AttendanceSheetId)) .ToListAsync(ct)); - AddCount("AttendanceAppeal", await attendance.CountAsync(ct)); + AddCount("AttendanceAppeal", await attendance.WhereApprovalBefore(x => x.AppealSubmittedAt ?? x.AttendanceSheet!.CreatedAt, cutoff).CountAsync(ct)); var applications = db.TeacherCourseApplications.AsNoTracking() .Where(x => x.Status == TeacherCourseApplicationStatus.Pending); if (scope.Current.RestrictedCollegeId is { } teacherCollegeId) applications = applications.Where(x => x.Teacher!.CollegeId == teacherCollegeId); - items.AddRange(await applications.OrderByApprovalTime(x => x.SubmittedAt, oldestFirst).ThenBy(x => x.Id).Take(take) + items.AddRange(await applications.WhereApprovalBefore(x => x.SubmittedAt, cutoff).OrderByApprovalTime(x => x.SubmittedAt, oldestFirst).ThenBy(x => x.Id).Take(take) .Select(x => new ApprovalItem(x.Id, "TeacherCourseApplication", "课程申报", $"{x.Teacher!.Name} — 《{x.Course!.Name}》", x.Statement ?? "", x.SubmittedAt, x.Teacher.College!.Name)).ToListAsync(ct)); - AddCount("TeacherCourseApplication", await applications.CountAsync(ct)); + AddCount("TeacherCourseApplication", await applications.WhereApprovalBefore(x => x.SubmittedAt, cutoff).CountAsync(ct)); // This workflow is restricted to the applicant's college even for users // who also hold a system-wide role. @@ -261,76 +265,76 @@ public sealed class ApprovalsController( { var reservations = db.ClassroomReservations.AsNoTracking().Where(x => x.Status == ClassroomReservationStatus.Submitted && x.ApplicantCollegeId == collegeId); - items.AddRange(await reservations.OrderByApprovalTime(x => x.CreatedAt, oldestFirst).ThenBy(x => x.Id).Take(take) + items.AddRange(await reservations.WhereApprovalBefore(x => x.CreatedAt, cutoff).OrderByApprovalTime(x => x.CreatedAt, oldestFirst).ThenBy(x => x.Id).Take(take) .Select(x => new ApprovalItem(x.Id, "ClassroomReservation", "教室借用", $"{x.ApplicantName} — {x.Classroom!.Name}", x.Purpose, x.CreatedAt, x.ApplicantCollege!.Name)).ToListAsync(ct)); - AddCount("ClassroomReservation", await reservations.CountAsync(ct)); + AddCount("ClassroomReservation", await reservations.WhereApprovalBefore(x => x.CreatedAt, cutoff).CountAsync(ct)); } var gradeBatches = Scoped(x => x.Status == GradeSheetStatus.Submitted); - items.AddRange(await gradeBatches.OrderByApprovalTime(x => x.SubmittedAt, oldestFirst).ThenBy(x => x.Id).Take(take) + items.AddRange(await gradeBatches.WhereApprovalBefore(x => x.SubmittedAt, cutoff).OrderByApprovalTime(x => x.SubmittedAt, oldestFirst).ThenBy(x => x.Id).Take(take) .Select(x => new ApprovalItem(x.Id, "GradeSubmissionBatch", "部分成绩审核", $"《{x.GradeSheet!.TeachingTask!.Course!.Name}》", "部分学生成绩待审核", x.SubmittedAt, x.GradeSheet.TeachingTask.Course.College!.Name)).ToListAsync(ct)); - AddCount("GradeSubmissionBatch", await gradeBatches.CountAsync(ct)); + AddCount("GradeSubmissionBatch", await gradeBatches.WhereApprovalBefore(x => x.SubmittedAt, cutoff).CountAsync(ct)); var experimentGrades = Scoped(x => x.Status == ExperimentGradeSheetStatus.Submitted && x.ExperimentProject!.TeachingTask!.Status == TeachingTaskStatus.Published); - items.AddRange(await experimentGrades.OrderByApprovalTime(x => x.SubmittedAt ?? x.CreatedAt, oldestFirst).ThenBy(x => x.Id).Take(take) + items.AddRange(await experimentGrades.WhereApprovalBefore(x => x.SubmittedAt ?? x.CreatedAt, cutoff).OrderByApprovalTime(x => x.SubmittedAt ?? x.CreatedAt, oldestFirst).ThenBy(x => x.Id).Take(take) .Select(x => new ApprovalItem(x.Id, "ExperimentGradeSheet", "实验成绩审核", x.ExperimentProject!.Name, "实验成绩待审核", x.SubmittedAt ?? x.CreatedAt, x.ExperimentProject.TeachingTask!.Course!.College!.Name)).ToListAsync(ct)); - AddCount("ExperimentGradeSheet", await experimentGrades.CountAsync(ct)); + AddCount("ExperimentGradeSheet", await experimentGrades.WhereApprovalBefore(x => x.SubmittedAt ?? x.CreatedAt, cutoff).CountAsync(ct)); var campusApplications = Scoped(x => x.Status == CampusRegistrationApplicationStatus.PendingReview); - items.AddRange(await campusApplications.OrderByApprovalTime(x => x.CreatedAt, oldestFirst).ThenBy(x => x.Id).Take(take) + items.AddRange(await campusApplications.WhereApprovalBefore(x => x.CreatedAt, cutoff).OrderByApprovalTime(x => x.CreatedAt, oldestFirst).ThenBy(x => x.Id).Take(take) .Select(x => new ApprovalItem(x.Id, "CampusRegistration", "校园报名审核", $"{x.Student!.Name} — {x.Project!.Name}", x.ApplicantNote ?? "", x.CreatedAt, x.Project.College != null ? x.Project.College.Name : "全校")).ToListAsync(ct)); - AddCount("CampusRegistration", await campusApplications.CountAsync(ct)); + AddCount("CampusRegistration", await campusApplications.WhereApprovalBefore(x => x.CreatedAt, cutoff).CountAsync(ct)); { var canDormFinal = canFinalReview || current.IsInRole(SystemRoles.DormitoryAdmin); var dormApplications = Scoped(x => x.Status == DormitoryApplicationStatus.Submitted || (canDormFinal && x.Status == DormitoryApplicationStatus.CounselorApproved)); - items.AddRange(await dormApplications.OrderByApprovalTime(x => x.SubmittedAt, oldestFirst).ThenBy(x => x.Id).Take(take) + items.AddRange(await dormApplications.WhereApprovalBefore(x => x.SubmittedAt, cutoff).OrderByApprovalTime(x => x.SubmittedAt, oldestFirst).ThenBy(x => x.Id).Take(take) .Select(x => new ApprovalItem(x.Id, "DormitoryApplication", "住宿申请", x.Student!.Name, x.Reason, x.SubmittedAt, x.Student.AdministrativeClass!.Major!.College!.Name, x.Status == DormitoryApplicationStatus.Submitted ? "counselor" : "dormitory")).ToListAsync(ct)); - AddCount("DormitoryApplication", await dormApplications.CountAsync(ct)); + AddCount("DormitoryApplication", await dormApplications.WhereApprovalBefore(x => x.SubmittedAt, cutoff).CountAsync(ct)); } var declarations = Scoped(x => x.Status == ComprehensiveAssessmentDeclarationStatus.CounselorApproved); - items.AddRange(await declarations.OrderByApprovalTime(x => x.SubmittedAt ?? x.CreatedAt, oldestFirst).ThenBy(x => x.Id).Take(take) + items.AddRange(await declarations.WhereApprovalBefore(x => x.SubmittedAt ?? x.CreatedAt, cutoff).OrderByApprovalTime(x => x.SubmittedAt ?? x.CreatedAt, oldestFirst).ThenBy(x => x.Id).Take(take) .Select(x => new ApprovalItem(x.Id, "AssessmentDeclaration", "综合测评材料复核", $"{x.Student!.Name} — {x.Title}", x.Category, x.SubmittedAt ?? x.CreatedAt, x.Student.AdministrativeClass!.Major!.College!.Name, "college")).ToListAsync(ct)); - AddCount("AssessmentDeclaration", await declarations.CountAsync(ct)); + AddCount("AssessmentDeclaration", await declarations.WhereApprovalBefore(x => x.SubmittedAt ?? x.CreatedAt, cutoff).CountAsync(ct)); var assessmentAppeals = Scoped(x => x.Status == ComprehensiveAssessmentAppealStatus.Submitted); - items.AddRange(await assessmentAppeals.OrderByApprovalTime(x => x.CreatedAt, oldestFirst).ThenBy(x => x.Id).Take(take) + items.AddRange(await assessmentAppeals.WhereApprovalBefore(x => x.CreatedAt, cutoff).OrderByApprovalTime(x => x.CreatedAt, oldestFirst).ThenBy(x => x.Id).Take(take) .Select(x => new ApprovalItem(x.Id, "AssessmentAppeal", "综合测评申诉", x.Student!.Name, x.Reason, x.CreatedAt, x.Student.AdministrativeClass!.Major!.College!.Name)).ToListAsync(ct)); - AddCount("AssessmentAppeal", await assessmentAppeals.CountAsync(ct)); + AddCount("AssessmentAppeal", await assessmentAppeals.WhereApprovalBefore(x => x.CreatedAt, cutoff).CountAsync(ct)); } if (current.IsInRole(SystemRoles.Counselor)) { var userId = current.UserId; var changes = db.StudentStatusChanges.AsNoTracking().Where(x => x.State == StudentStatusChangeState.Submitted && x.Student!.AdministrativeClass!.CounselorUserId == userId); - items.AddRange(await changes.OrderByApprovalTime(x => x.SubmittedAt, oldestFirst).ThenBy(x => x.Id).Take(take) + items.AddRange(await changes.WhereApprovalBefore(x => x.SubmittedAt, cutoff).OrderByApprovalTime(x => x.SubmittedAt, oldestFirst).ThenBy(x => x.Id).Take(take) .Select(x => new ApprovalItem(x.Id, "StudentStatusChange", "学籍异动", $"{x.Student!.Name} — {SSCLabel(x.Type)}", x.Reason, x.SubmittedAt, x.Student.AdministrativeClass!.Major!.College!.Name, "counselor")).ToListAsync(ct)); - AddCount("StudentStatusChange", await changes.CountAsync(ct)); + AddCount("StudentStatusChange", await changes.WhereApprovalBefore(x => x.SubmittedAt, cutoff).CountAsync(ct)); var declarations = db.ComprehensiveAssessmentDeclarations.AsNoTracking().Where(x => x.Status == ComprehensiveAssessmentDeclarationStatus.Submitted && x.Student!.AdministrativeClass!.CounselorUserId == userId); - items.AddRange(await declarations.OrderByApprovalTime(x => x.SubmittedAt ?? x.CreatedAt, oldestFirst).ThenBy(x => x.Id).Take(take) + items.AddRange(await declarations.WhereApprovalBefore(x => x.SubmittedAt ?? x.CreatedAt, cutoff).OrderByApprovalTime(x => x.SubmittedAt ?? x.CreatedAt, oldestFirst).ThenBy(x => x.Id).Take(take) .Select(x => new ApprovalItem(x.Id, "AssessmentDeclaration", "综合测评材料初审", $"{x.Student!.Name} — {x.Title}", x.Category, x.SubmittedAt ?? x.CreatedAt, x.Student.AdministrativeClass!.Major!.College!.Name, "counselor")).ToListAsync(ct)); - AddCount("AssessmentDeclaration", await declarations.CountAsync(ct)); + AddCount("AssessmentDeclaration", await declarations.WhereApprovalBefore(x => x.SubmittedAt ?? x.CreatedAt, cutoff).CountAsync(ct)); if (!isManager) { var dorm = db.DormitoryApplications.AsNoTracking().Where(x => x.Status == DormitoryApplicationStatus.Submitted && x.Student!.AdministrativeClass!.CounselorUserId == userId); - items.AddRange(await dorm.OrderByApprovalTime(x => x.SubmittedAt, oldestFirst).ThenBy(x => x.Id).Take(take) + items.AddRange(await dorm.WhereApprovalBefore(x => x.SubmittedAt, cutoff).OrderByApprovalTime(x => x.SubmittedAt, oldestFirst).ThenBy(x => x.Id).Take(take) .Select(x => new ApprovalItem(x.Id, "DormitoryApplication", "住宿申请", x.Student!.Name, x.Reason, x.SubmittedAt, x.Student.AdministrativeClass!.Major!.College!.Name, "counselor")).ToListAsync(ct)); - AddCount("DormitoryApplication", await dorm.CountAsync(ct)); + AddCount("DormitoryApplication", await dorm.WhereApprovalBefore(x => x.SubmittedAt, cutoff).CountAsync(ct)); } } @@ -338,9 +342,9 @@ public sealed class ApprovalsController( { var userId = current.UserId; var teacherAttendance = db.AttendanceRecords.AsNoTracking().Where(x => x.AppealStatus == AttendanceAppealStatus.Pending && x.AttendanceSheet!.TeachingTask!.Status == TeachingTaskStatus.Published && x.AttendanceSheet.TeachingTask.Teachers.Any(t => t.Teacher!.UserId == userId)); - items.AddRange(await teacherAttendance.OrderByApprovalTime(x => x.AppealSubmittedAt ?? x.AttendanceSheet!.CreatedAt, oldestFirst).ThenBy(x => x.StudentId).ThenBy(x => x.AttendanceSheetId).Take(take) + items.AddRange(await teacherAttendance.WhereApprovalBefore(x => x.AppealSubmittedAt ?? x.AttendanceSheet!.CreatedAt, cutoff).OrderByApprovalTime(x => x.AppealSubmittedAt ?? x.AttendanceSheet!.CreatedAt, oldestFirst).ThenBy(x => x.StudentId).ThenBy(x => x.AttendanceSheetId).Take(take) .Select(x => new ApprovalItem(x.StudentId, "AttendanceAppeal", "考勤申诉", $"{x.Student!.Name} — 《{x.AttendanceSheet!.TeachingTask!.Course!.Name}》", x.AppealReason ?? "", x.AppealSubmittedAt ?? x.AttendanceSheet.CreatedAt, x.Student.AdministrativeClass!.Major!.College!.Name, null, x.AttendanceSheetId)).ToListAsync(ct)); - AddCount("AttendanceAppeal", await teacherAttendance.CountAsync(ct)); + AddCount("AttendanceAppeal", await teacherAttendance.WhereApprovalBefore(x => x.AppealSubmittedAt ?? x.AttendanceSheet!.CreatedAt, cutoff).CountAsync(ct)); } if (current.IsInRole(SystemRoles.Teacher) || isManager) @@ -350,36 +354,36 @@ public sealed class ApprovalsController( gradeAppeals = gradeAppeals.Where(x => x.GradeRecord!.GradeSheet!.TeachingTask!.Teachers.Any(t => t.Teacher!.UserId == current.UserId)); else if (current.RestrictedCollegeId is { } gradeCollegeId) gradeAppeals = gradeAppeals.Where(x => x.GradeRecord!.GradeSheet!.TeachingTask!.Course!.CollegeId == gradeCollegeId); - items.AddRange(await gradeAppeals.OrderByApprovalTime(x => x.SubmittedAt, oldestFirst).ThenBy(x => x.Id).Take(take) + items.AddRange(await gradeAppeals.WhereApprovalBefore(x => x.SubmittedAt, cutoff).OrderByApprovalTime(x => x.SubmittedAt, oldestFirst).ThenBy(x => x.Id).Take(take) .Select(x => new ApprovalItem(x.Id, "GradeAppeal", "成绩异议", $"{x.Student!.Name} — 《{x.GradeRecord!.GradeSheet!.TeachingTask!.Course!.Name}》", x.Reason, x.SubmittedAt, x.GradeRecord.GradeSheet.TeachingTask.Course.College!.Name)).ToListAsync(ct)); - AddCount("GradeAppeal", await gradeAppeals.CountAsync(ct)); + AddCount("GradeAppeal", await gradeAppeals.WhereApprovalBefore(x => x.SubmittedAt, cutoff).CountAsync(ct)); } if (current.IsInRole(SystemRoles.DormitoryAdmin) && !isManager) { var dorm = Scoped(x => x.Status == DormitoryApplicationStatus.CounselorApproved); - items.AddRange(await dorm.OrderByApprovalTime(x => x.SubmittedAt, oldestFirst).ThenBy(x => x.Id).Take(take) + items.AddRange(await dorm.WhereApprovalBefore(x => x.SubmittedAt, cutoff).OrderByApprovalTime(x => x.SubmittedAt, oldestFirst).ThenBy(x => x.Id).Take(take) .Select(x => new ApprovalItem(x.Id, "DormitoryApplication", "住宿申请", x.Student!.Name, x.Reason, x.SubmittedAt, x.Student.AdministrativeClass!.Major!.College!.Name, "dormitory")).ToListAsync(ct)); - AddCount("DormitoryApplication", await dorm.CountAsync(ct)); + AddCount("DormitoryApplication", await dorm.WhereApprovalBefore(x => x.SubmittedAt, cutoff).CountAsync(ct)); } if (current.IsInRole(SystemRoles.StudentAffairsAdmin) && !isManager) { var declarations = Scoped(x => x.Status == ComprehensiveAssessmentDeclarationStatus.CounselorApproved); - items.AddRange(await declarations.OrderByApprovalTime(x => x.SubmittedAt ?? x.CreatedAt, oldestFirst).ThenBy(x => x.Id).Take(take) + items.AddRange(await declarations.WhereApprovalBefore(x => x.SubmittedAt ?? x.CreatedAt, cutoff).OrderByApprovalTime(x => x.SubmittedAt ?? x.CreatedAt, oldestFirst).ThenBy(x => x.Id).Take(take) .Select(x => new ApprovalItem(x.Id, "AssessmentDeclaration", "综合测评材料复核", $"{x.Student!.Name} — {x.Title}", x.Category, x.SubmittedAt ?? x.CreatedAt, x.Student.AdministrativeClass!.Major!.College!.Name, "college")).ToListAsync(ct)); - AddCount("AssessmentDeclaration", await declarations.CountAsync(ct)); + AddCount("AssessmentDeclaration", await declarations.WhereApprovalBefore(x => x.SubmittedAt ?? x.CreatedAt, cutoff).CountAsync(ct)); var appeals = Scoped(x => x.Status == ComprehensiveAssessmentAppealStatus.Submitted); - items.AddRange(await appeals.OrderByApprovalTime(x => x.CreatedAt, oldestFirst).ThenBy(x => x.Id).Take(take) + items.AddRange(await appeals.WhereApprovalBefore(x => x.CreatedAt, cutoff).OrderByApprovalTime(x => x.CreatedAt, oldestFirst).ThenBy(x => x.Id).Take(take) .Select(x => new ApprovalItem(x.Id, "AssessmentAppeal", "综合测评申诉", x.Student!.Name, x.Reason, x.CreatedAt, x.Student.AdministrativeClass!.Major!.College!.Name)).ToListAsync(ct)); - AddCount("AssessmentAppeal", await appeals.CountAsync(ct)); + AddCount("AssessmentAppeal", await appeals.WhereApprovalBefore(x => x.CreatedAt, cutoff).CountAsync(ct)); } if (isManager || current.IsInRole(SystemRoles.Leader)) { var plans = Scoped(x => x.Status == ImprovementPlanStatus.Completed); - items.AddRange(await plans.OrderByApprovalTime(x => x.UpdatedAt, oldestFirst).ThenBy(x => x.Id).Take(take) + items.AddRange(await plans.WhereApprovalBefore(x => x.UpdatedAt, cutoff).OrderByApprovalTime(x => x.UpdatedAt, oldestFirst).ThenBy(x => x.Id).Take(take) .Select(x => new ApprovalItem(x.Id, "TeachingImprovement", "教学改进复评", $"{x.Teacher.Name} — 《{x.TeachingTask.Course!.Name}》", x.ProblemSummary, x.UpdatedAt, x.TeachingTask.Course.College!.Name)).ToListAsync(ct)); - AddCount("TeachingImprovement", await plans.CountAsync(ct)); + AddCount("TeachingImprovement", await plans.WhereApprovalBefore(x => x.UpdatedAt, cutoff).CountAsync(ct)); } if (isManager || current.IsInRole(SystemRoles.Counselor)) @@ -397,9 +401,9 @@ public sealed class ApprovalsController( (isAcademic && x.GraduationClearanceItem.ResponsibleRole == SystemRoles.AcademicAdmin) || (isCollege && x.GraduationClearanceItem.ResponsibleRole == SystemRoles.CollegeAdmin && x.Student!.AdministrativeClass!.Major!.CollegeId == collegeId) || (isCounselor && x.GraduationClearanceItem.ResponsibleRole == SystemRoles.Counselor && x.Student!.AdministrativeClass!.CounselorUserId == userId))); - items.AddRange(await clearances.OrderByApprovalTime(x => x.CreatedAt, oldestFirst).ThenBy(x => x.Id).Take(take) + items.AddRange(await clearances.WhereApprovalBefore(x => x.CreatedAt, cutoff).OrderByApprovalTime(x => x.CreatedAt, oldestFirst).ThenBy(x => x.Id).Take(take) .Select(x => new ApprovalItem(x.Id, "GraduationClearance", "毕业离校办理", $"{x.Student!.Name} — {x.GraduationClearanceItem!.Name}", x.GraduationClearanceItem.ResponsibleUnit, x.CreatedAt, x.Student.AdministrativeClass!.Major!.College!.Name)).ToListAsync(ct)); - AddCount("GraduationClearance", await clearances.CountAsync(ct)); + AddCount("GraduationClearance", await clearances.WhereApprovalBefore(x => x.CreatedAt, cutoff).CountAsync(ct)); } var filtered = string.IsNullOrWhiteSpace(type) ? items : items.Where(x => x.Type == type); @@ -1133,6 +1137,16 @@ public sealed record ApprovalProgressResponse(string Type, Guid Id, IReadOnlyLis internal static class ApprovalOrderingExtensions { + public static IQueryable WhereApprovalBefore(this IQueryable source, + System.Linq.Expressions.Expression> selector, DateTime? cutoff) + { + if (!cutoff.HasValue) return source; + var effectiveCutoff = cutoff.Value; + System.Linq.Expressions.Expression> boundary = () => effectiveCutoff; + var body = System.Linq.Expressions.Expression.LessThanOrEqual(selector.Body, boundary.Body); + return source.Where(System.Linq.Expressions.Expression.Lambda>(body, selector.Parameters)); + } + public static IOrderedQueryable OrderByApprovalTime(this IQueryable source, System.Linq.Expressions.Expression> selector, bool oldestFirst) => oldestFirst ? source.OrderBy(selector) : source.OrderByDescending(selector); diff --git a/tests/Jiaowu.Api.Tests/ApprovalsControllerTests.cs b/tests/Jiaowu.Api.Tests/ApprovalsControllerTests.cs index 5bcde4a..14177f8 100644 --- a/tests/Jiaowu.Api.Tests/ApprovalsControllerTests.cs +++ b/tests/Jiaowu.Api.Tests/ApprovalsControllerTests.cs @@ -13,6 +13,39 @@ namespace Jiaowu.Api.Tests; public sealed class ApprovalsControllerTests { + [Fact] + public void Overdue_filter_translates_with_mysql_provider() + { + var options = new DbContextOptionsBuilder() + .UseMySQL("Server=localhost;Database=design;User=design;Password=unused") + .Options; + using var db = new AppDbContext(options); + var sql = db.GradeSheets.WhereApprovalBefore(x => x.SubmittedAt ?? x.CreatedAt, DateTime.UtcNow).ToQueryString(); + Assert.Contains("COALESCE", sql, StringComparison.OrdinalIgnoreCase); + Assert.Contains("WHERE", sql, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task Overdue_filter_applies_before_counts_and_pagination() + { + await using var fixture = await ApprovalFixture.CreateAsync(); + fixture.Db.AddRange( + new CourseExemption { StudentId = fixture.Student.Id, TeachingTaskId = fixture.CurrentTask.Id, Reason = "已等待", SubmittedAt = DateTime.UtcNow.AddHours(-100) }, + new DeferredExam { StudentId = fixture.Student.Id, TeachingTaskId = fixture.CurrentTask.Id, Reason = "刚提交", SubmittedAt = DateTime.UtcNow.AddHours(-4) }, + new GradeSheet { TeachingTaskId = fixture.CurrentTask.Id, Status = GradeSheetStatus.Submitted, SubmittedAt = null, CreatedAt = DateTime.UtcNow.AddHours(-80) }); + await fixture.Db.SaveChangesAsync(); + var controller = new ApprovalsController(fixture.Db, new ManagerDataScope()); + var response = await controller.GetPending(1, 1, CancellationToken.None, oldestFirst: true, overdueHours: 72); + var result = Assert.IsType(Assert.IsType(response.Result).Value); + Assert.Equal(2, result.Total); + Assert.Equal("CourseExemption", Assert.Single(result.Items).Type); + Assert.Equal(1, result.Counts["CourseExemption"]); + Assert.Equal(1, result.Counts["GradeSheet"]); + Assert.False(result.Counts.ContainsKey("DeferredExam")); + var invalid = await controller.GetPending(1, 20, CancellationToken.None, overdueHours: 0); + Assert.IsType(invalid.Result); + } + [Fact] public async Task Student_status_cancellation_is_recorded_in_progress() { diff --git a/web/e2e/approval-center.spec.ts b/web/e2e/approval-center.spec.ts index 8a5bc33..9d37456 100644 --- a/web/e2e/approval-center.spec.ts +++ b/web/e2e/approval-center.spec.ts @@ -23,9 +23,14 @@ for (const scenario of cases) test(`${scenario.type} can be ${scenario.reject ? localStorage.setItem('jiaowu_session_expires_at', '2099-01-01T00:00:00Z') }, user) let reviewed = false + let overdueRequested = false await page.route(url => url.pathname.startsWith('/api/'), async route => { const url = new URL(route.request().url()) if (url.pathname === '/api/approvals/pending') { + if (url.searchParams.has('overdueHours')) { + expect(url.searchParams.get('overdueHours')).toBe('72') + overdueRequested = true + } const items = reviewed ? [] : [{ id: 'item-1', secondaryId: scenario.secondaryId, type: scenario.type, stage: scenario.stage, label: '申请', title: '学生 — 《课程》', desc: '申请事由', time: '2026-11-01T00:00:00Z', college: '学院' }] return route.fulfill({ json: { items, total: items.length, page: 1, pageSize: 20, counts: reviewed ? {} : { [scenario.type]: 1 } } }) } @@ -44,6 +49,11 @@ for (const scenario of cases) test(`${scenario.type} can be ${scenario.reject ? await page.goto('/approvals') const card = page.locator('.appr-card').filter({ hasText: '申请事由' }) await expect(card).toBeVisible() + if (scenario.type === 'AttendanceAppeal' && !scenario.reject) { + await page.locator('.approval-overdue-filter .el-switch').click() + await expect.poll(() => overdueRequested).toBe(true) + await expect(page.getByText('按每条事项显示的时间计算,阈值保存在当前浏览器。')).toBeVisible() + } if (scenario.progress) { await card.getByRole('button', { name: '办理进度' }).click() const dialog = page.getByRole('dialog') diff --git a/web/src/i18n/messages/en-US.ts b/web/src/i18n/messages/en-US.ts index 8c6b215..aef0378 100644 --- a/web/src/i18n/messages/en-US.ts +++ b/web/src/i18n/messages/en-US.ts @@ -1,4 +1,5 @@ export default { + approvalOverdue: { only: 'Waiting longer than', hours: 'hours', hint: 'Measured from the time shown on each item. The threshold is saved in this browser.' }, approvalProgress: { title: 'Progress', submitted: 'Submitted', approved: 'Approved', rejected: 'Rejected', cancelled: 'Withdrawn', counselorApproved: 'Counselor review approved', counselorRejected: 'Counselor review rejected', collegeApproved: 'College review approved', collegeRejected: 'College review rejected', finalApproved: 'Final review approved', finalRejected: 'Final review rejected', legacyReviewed: 'Most recent review', incomplete: 'Earlier review details are unavailable for this request.' }, approvalCenterAdjustment: 'Class adjustment', approvalCenterClearance: 'Graduation clearance', diff --git a/web/src/i18n/messages/zh-CN.ts b/web/src/i18n/messages/zh-CN.ts index fe77491..6841c6f 100644 --- a/web/src/i18n/messages/zh-CN.ts +++ b/web/src/i18n/messages/zh-CN.ts @@ -1,4 +1,5 @@ export default { + approvalOverdue: { only: '只看等待超过', hours: '小时', hint: '按每条事项显示的时间计算,阈值保存在当前浏览器。' }, approvalProgress: { title: '办理进度', submitted: '已提交', approved: '审核通过', rejected: '审核驳回', cancelled: '已撤回', counselorApproved: '辅导员审核通过', counselorRejected: '辅导员审核驳回', collegeApproved: '学院审核通过', collegeRejected: '学院审核驳回', finalApproved: '校级审核通过', finalRejected: '校级审核驳回', legacyReviewed: '最近一次审核', incomplete: '该申请较早的审核详情未留存。' }, approvalCenterAdjustment: '调停课', approvalCenterClearance: '毕业离校办理', diff --git a/web/src/views/ApprovalCenterView.vue b/web/src/views/ApprovalCenterView.vue index b49f9ed..78f6c14 100644 --- a/web/src/views/ApprovalCenterView.vue +++ b/web/src/views/ApprovalCenterView.vue @@ -69,6 +69,9 @@ const oldestPending = ref(null) const oldestFirst = ref(false) const selectedPendingType = ref('') const pendingCounts = ref>({}) +const storedOverdueHours = Number(localStorage.getItem('jiaowu_approval_overdue_hours')) +const overdueHours = ref(Number.isInteger(storedOverdueHours) && storedOverdueHours >= 1 && storedOverdueHours <= 8760 ? storedOverdueHours : 72) +const overdueOnly = ref(false) const targetApprovalType = computed(() => { const value = route.query.type return typeof value === 'string' ? value : undefined @@ -200,7 +203,9 @@ const selectedSubstitute = computed(() => const recordCount = computed(() => myExemptions.value.length + myDeferred.value.length + mySubstitutions.value.length) +let loadSequence = 0 async function load() { + const sequence = ++loadSequence loading.value = true try { if (isApprover.value) { @@ -208,13 +213,15 @@ async function load() { const { data } = await http.get( `/approvals/pending/${targetApprovalType.value}/${targetApprovalId.value}`, ) + if (sequence !== loadSequence) return pending.value = [data] pendingTotal.value = 1 pendingCounts.value = {} } else { const { data } = await http.get('/approvals/pending', { - params: { page: pendingPage.value, pageSize: pendingPageSize, oldestFirst: oldestFirst.value, type: selectedPendingType.value || undefined }, + params: { page: pendingPage.value, pageSize: pendingPageSize, oldestFirst: oldestFirst.value, type: selectedPendingType.value || undefined, overdueHours: overdueOnly.value ? overdueHours.value : undefined }, }) + if (sequence !== loadSequence) return pending.value = data.items pendingTotal.value = data.total pendingCounts.value = data.counts ?? {} @@ -233,17 +240,22 @@ async function load() { http.get('/approvals/deferred/mine'), http.get('/approvals/substitutions/mine'), ]) + if (sequence !== loadSequence) return enrolledCourses.value = courses.data myGrades.value = grades.data myExemptions.value = ex.data myDeferred.value = df.data mySubstitutions.value = substitutions.data } - if (isTeacher.value) gradeRecords.value = (await http.get('/approvals/grade-records')).data + if (isTeacher.value) { + const { data } = await http.get('/approvals/grade-records') + if (sequence !== loadSequence) return + gradeRecords.value = data + } } catch (e) { - ElMessage.error(apiErrorMessage(e)) + if (sequence === loadSequence) ElMessage.error(apiErrorMessage(e)) } finally { - loading.value = false + if (sequence === loadSequence) loading.value = false } } @@ -459,6 +471,13 @@ function selectPendingType(type: string) { void load() } +function updateOverdueHours(value: number | undefined) { + if (!value || !Number.isInteger(value) || value < 1 || value > 8760) return + overdueHours.value = value + localStorage.setItem('jiaowu_approval_overdue_hours', String(value)) + if (overdueOnly.value) { pendingPage.value = 1; void load() } +} + function approvalStageLabel(stage: string) { if (stage === 'counselor') return t('approvalCenterCounselorStage') if (stage === 'dormitory') return t('approvalCenterDormitoryStage') @@ -609,7 +628,13 @@ onMounted(async () => {
{{ t('approvalCenterExtra.pendingTotal', { count: pendingTotal }) }} {{ t('approvalCenterExtra.oldest', { title: oldestPending.title, time: new Date(oldestPending.time).toLocaleString(getDisplayLocale()) }) }} - + +
+ + + {{ t('approvalOverdue.hours') }} +
+ {{ t('approvalOverdue.hint') }}
{{ t('approvalCenterAllTypes') }} {{ approvalCountLabel(String(type)) }} · {{ count }} @@ -924,6 +949,7 @@ onMounted(async () => { .approval-monitor { display: flex; flex-wrap: wrap; align-items: center; gap: 12px 20px; padding: 12px 16px; color: #475467; background: #f3f6fb; border-radius: 10px; font-size: 13px; } .approval-monitor .el-switch { margin-left: auto; } .approval-monitor-counts { display: flex; flex-basis: 100%; flex-wrap: wrap; gap: 6px; } +.approval-overdue-filter { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; } .approval-progress { display: grid; gap: 18px; padding-left: 24px; } .approval-progress li { padding-left: 4px; } .approval-progress time { display: block; margin-top: 4px; color: #667085; font-size: 12px; }