From 312ed5ad5cb676da071775d68493494cf4db4114 Mon Sep 17 00:00:00 2001 From: biss Date: Fri, 13 Nov 2026 19:54:18 +0800 Subject: [PATCH] Localize student status and approval errors --- .../Controllers/ApprovalsController.cs | 753 +++++++++--------- .../StudentStatusChangesController.cs | 327 ++++++-- .../Localization/SharedResource.en-US.resx | 69 ++ .../Localization/SharedResource.resx | 69 ++ 4 files changed, 797 insertions(+), 421 deletions(-) diff --git a/src/Jiaowu.Api/Controllers/ApprovalsController.cs b/src/Jiaowu.Api/Controllers/ApprovalsController.cs index d128d03..706490c 100644 --- a/src/Jiaowu.Api/Controllers/ApprovalsController.cs +++ b/src/Jiaowu.Api/Controllers/ApprovalsController.cs @@ -6,9 +6,11 @@ using Jiaowu.Api.Domain.System; using Jiaowu.Api.Infrastructure.Auth; using Jiaowu.Api.Infrastructure.Grades; using Jiaowu.Api.Infrastructure.Persistence; +using Jiaowu.Api.Infrastructure.Localization; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Localization; namespace Jiaowu.Api.Controllers; @@ -18,8 +20,32 @@ namespace Jiaowu.Api.Controllers; public sealed class ApprovalsController( AppDbContext db, ICurrentUserDataScope scope, - StudentAcademicStatisticsService? studentAcademicStatistics = null) : ControllerBase + StudentAcademicStatisticsService? studentAcademicStatistics = null, + IStringLocalizer? localizer = null) : ControllerBase { + private static readonly IReadOnlyDictionary ApprovalsErrorKeys = new Dictionary + { + ["审批类型或审核角色无效。"] = "Approvals.Workflow.TypeOrRoleInvalid", + ["page 必须大于 0,pageSize 必须在 1 到 100 之间,且分页窗口不能超过 100000 条。"] = "Approvals.Pagination.Invalid", + ["等待时长必须在 1 到 8760 小时之间。"] = "Approvals.Settings.WaitDurationRange", + ["该课程不在您当前或已发布课表的修读课程中,请刷新课程列表后重试。"] = "Approvals.Course.NotInCurrentSchedule", + ["该课程已有免修申请在审核中。"] = "Approvals.Exemption.AlreadyPending", + ["申请已处理,不能重复审核。"] = "Approvals.Request.AlreadyProcessed", + ["该课程已有缓考申请在审核中。"] = "Approvals.DeferredExam.AlreadyPending", + ["只能修改已发布的成绩。"] = "Approvals.GradeModification.PublishedOnly", + ["百分制调整后成绩必须在 0 到 100 之间。"] = "Approvals.GradeModification.ScoreRange", + ["调整等级制或通过/不通过制成绩时必须填写有效的最终评价。"] = "Approvals.GradeModification.FinalResultRequired", + ["该成绩已有修改申请在审批中。"] = "Approvals.GradeModification.AlreadyPending", + ["状态不正确。"] = "Approvals.GradeModification.InvalidState", + ["需先通过学院审核。"] = "Approvals.GradeModification.CollegeApprovalRequired", + ["当前角色或阶段不能驳回该申请。"] = "Approvals.Request.RejectionNotAllowed", + ["被替代课程和替代课程不能相同。"] = "Approvals.Substitution.CoursesMustDiffer", + ["被替代课程必须是当前或已发布课表的修读课程,或已有未通过成绩的课程。"] = "Approvals.Substitution.OriginalCourseRequired", + ["替代课程必须具有已发布且及格的成绩。"] = "Approvals.Substitution.PassingPublishedGradeRequired", + ["该课程组合未配置适用的等价课程规则,暂不能申请替代。"] = "Approvals.Substitution.EquivalencyRuleMissing", + ["该课程已有替代申请在审核中。"] = "Approvals.Substitution.AlreadyPending", + }; + private const string Managers = SystemRoles.SuperAdmin + "," + SystemRoles.AcademicAdmin + "," + SystemRoles.CollegeAdmin; private const string Teachers = Managers + "," + SystemRoles.Teacher; private const string Students = Managers + "," + SystemRoles.Student; @@ -66,268 +92,268 @@ public sealed class ApprovalsController( switch (type) { case "CourseExemption": - { - var restrictedCollegeId = current.RestrictedCollegeId; - var allColleges = manager && current.Scope == DataScope.All; - var query = db.CourseExemptions.AsNoTracking().Where(x => x.Id == id && - (x.Student!.UserId == userId || (manager && (allColleges || x.TeachingTask!.Course!.CollegeId == restrictedCollegeId)))); - var item = await query.FirstOrDefaultAsync(ct); - if (item is null) return NotFound(); - AddSingleApprovalSteps(steps, item.SubmittedAt, item.ReviewedAt, item.Status, item.ReviewComment); - break; - } + { + var restrictedCollegeId = current.RestrictedCollegeId; + var allColleges = manager && current.Scope == DataScope.All; + var query = db.CourseExemptions.AsNoTracking().Where(x => x.Id == id && + (x.Student!.UserId == userId || (manager && (allColleges || x.TeachingTask!.Course!.CollegeId == restrictedCollegeId)))); + var item = await query.FirstOrDefaultAsync(ct); + if (item is null) return NotFound(); + AddSingleApprovalSteps(steps, item.SubmittedAt, item.ReviewedAt, item.Status, item.ReviewComment); + break; + } case "DeferredExam": - { - var restrictedCollegeId = current.RestrictedCollegeId; - var allColleges = manager && current.Scope == DataScope.All; - var query = db.DeferredExams.AsNoTracking().Where(x => x.Id == id && - (x.Student!.UserId == userId || (manager && (allColleges || x.TeachingTask!.Course!.CollegeId == restrictedCollegeId)))); - var item = await query.FirstOrDefaultAsync(ct); - if (item is null) return NotFound(); - AddSingleApprovalSteps(steps, item.SubmittedAt, item.ReviewedAt, item.Status, item.ReviewComment); - break; - } + { + var restrictedCollegeId = current.RestrictedCollegeId; + var allColleges = manager && current.Scope == DataScope.All; + var query = db.DeferredExams.AsNoTracking().Where(x => x.Id == id && + (x.Student!.UserId == userId || (manager && (allColleges || x.TeachingTask!.Course!.CollegeId == restrictedCollegeId)))); + var item = await query.FirstOrDefaultAsync(ct); + if (item is null) return NotFound(); + AddSingleApprovalSteps(steps, item.SubmittedAt, item.ReviewedAt, item.Status, item.ReviewComment); + break; + } case "CourseSubstitution": - { - var restrictedCollegeId = current.RestrictedCollegeId; - var allColleges = manager && current.Scope == DataScope.All; - var query = db.CourseSubstitutions.AsNoTracking().Where(x => x.Id == id && - (x.Student!.UserId == userId || (manager && (allColleges || x.Student.AdministrativeClass!.Major!.CollegeId == restrictedCollegeId)))); - var item = await query.FirstOrDefaultAsync(ct); - if (item is null) return NotFound(); - AddSingleApprovalSteps(steps, item.SubmittedAt, item.ReviewedAt, item.Status, item.ReviewComment); - break; - } + { + var restrictedCollegeId = current.RestrictedCollegeId; + var allColleges = manager && current.Scope == DataScope.All; + var query = db.CourseSubstitutions.AsNoTracking().Where(x => x.Id == id && + (x.Student!.UserId == userId || (manager && (allColleges || x.Student.AdministrativeClass!.Major!.CollegeId == restrictedCollegeId)))); + var item = await query.FirstOrDefaultAsync(ct); + if (item is null) return NotFound(); + AddSingleApprovalSteps(steps, item.SubmittedAt, item.ReviewedAt, item.Status, item.ReviewComment); + break; + } case "GradeModification": - { - var restrictedCollegeId = current.RestrictedCollegeId; - var allColleges = manager && current.Scope == DataScope.All; - var query = db.GradeModifications.AsNoTracking().Where(x => x.Id == id && - (x.ApplicantUserId == userId || (manager && (allColleges || x.GradeRecord!.GradeSheet!.TeachingTask!.Course!.CollegeId == restrictedCollegeId)))); - var item = await query.FirstOrDefaultAsync(ct); - if (item is null) return NotFound(); - steps.Add(new("submitted", item.SubmittedAt, item.Reason)); - if (item.CollegeReviewedAt is { } collegeTime) { - var rejected = item.Status == GradeModificationStatus.Rejected && item.FinalReviewedAt is null; - steps.Add(new(rejected ? "collegeRejected" : "collegeApproved", collegeTime, rejected ? item.ReviewComment : null)); + var restrictedCollegeId = current.RestrictedCollegeId; + var allColleges = manager && current.Scope == DataScope.All; + var query = db.GradeModifications.AsNoTracking().Where(x => x.Id == id && + (x.ApplicantUserId == userId || (manager && (allColleges || x.GradeRecord!.GradeSheet!.TeachingTask!.Course!.CollegeId == restrictedCollegeId)))); + var item = await query.FirstOrDefaultAsync(ct); + if (item is null) return NotFound(); + steps.Add(new("submitted", item.SubmittedAt, item.Reason)); + if (item.CollegeReviewedAt is { } collegeTime) + { + var rejected = item.Status == GradeModificationStatus.Rejected && item.FinalReviewedAt is null; + steps.Add(new(rejected ? "collegeRejected" : "collegeApproved", collegeTime, rejected ? item.ReviewComment : null)); + } + if (item.FinalReviewedAt is { } finalTime) + steps.Add(new(item.Status == GradeModificationStatus.Rejected ? "finalRejected" : "finalApproved", finalTime, item.ReviewComment)); + break; } - if (item.FinalReviewedAt is { } finalTime) - steps.Add(new(item.Status == GradeModificationStatus.Rejected ? "finalRejected" : "finalApproved", finalTime, item.ReviewComment)); - break; - } case "TeacherCourseApplication": - { - var query = db.TeacherCourseApplications.AsNoTracking().Where(x => x.Id == id); - if (manager) { - if (current.RestrictedCollegeId is { } collegeId) - query = query.Where(x => x.Teacher!.CollegeId == collegeId || x.Teacher.UserId == userId); + var query = db.TeacherCourseApplications.AsNoTracking().Where(x => x.Id == id); + if (manager) + { + if (current.RestrictedCollegeId is { } collegeId) + query = query.Where(x => x.Teacher!.CollegeId == collegeId || x.Teacher.UserId == userId); + } + else query = query.Where(x => x.Teacher!.UserId == userId); + var item = await query.FirstOrDefaultAsync(ct); + if (item is null) return NotFound(); + steps.Add(new("started", item.SubmittedAt, null)); + if (item.ReviewedAt is { } time && item.Status is TeacherCourseApplicationStatus.Approved or TeacherCourseApplicationStatus.Rejected) + steps.Add(new(item.Status == TeacherCourseApplicationStatus.Approved ? "approved" : "rejected", time, item.ReviewComment)); + if ((item.Status is TeacherCourseApplicationStatus.Approved or TeacherCourseApplicationStatus.Rejected) && item.ReviewedAt is null || + item.Status == TeacherCourseApplicationStatus.Withdrawn) + historyIncomplete = true; + break; } - else query = query.Where(x => x.Teacher!.UserId == userId); - var item = await query.FirstOrDefaultAsync(ct); - if (item is null) return NotFound(); - steps.Add(new("started", item.SubmittedAt, null)); - if (item.ReviewedAt is { } time && item.Status is TeacherCourseApplicationStatus.Approved or TeacherCourseApplicationStatus.Rejected) - steps.Add(new(item.Status == TeacherCourseApplicationStatus.Approved ? "approved" : "rejected", time, item.ReviewComment)); - if ((item.Status is TeacherCourseApplicationStatus.Approved or TeacherCourseApplicationStatus.Rejected) && item.ReviewedAt is null || - item.Status == TeacherCourseApplicationStatus.Withdrawn) - historyIncomplete = true; - break; - } case "ClassroomReservation": - { - var collegeId = current.CollegeId; - var canReview = current.IsInRole(SystemRoles.CollegeAdmin) && collegeId.HasValue; - var item = await db.ClassroomReservations.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id && - (x.ApplicantUserId == userId || (canReview && x.ApplicantCollegeId == collegeId)), ct); - if (item is null) return NotFound(); - steps.Add(new("submitted", item.CreatedAt, null)); - if (item.ReviewedAt is { } time && item.Status is ClassroomReservationStatus.Approved or ClassroomReservationStatus.Rejected or ClassroomReservationStatus.Cancelled) - steps.Add(new(item.Status == ClassroomReservationStatus.Rejected ? "rejected" : "approved", time, item.ReviewComment)); - if (item.CancelledAt is { } cancelledAt && item.Status == ClassroomReservationStatus.Cancelled) - steps.Add(new("cancelled", cancelledAt, null)); - if ((item.Status is ClassroomReservationStatus.Approved or ClassroomReservationStatus.Rejected) && item.ReviewedAt is null || - item.Status == ClassroomReservationStatus.Cancelled && item.CancelledAt is null) - historyIncomplete = true; - break; - } + { + var collegeId = current.CollegeId; + var canReview = current.IsInRole(SystemRoles.CollegeAdmin) && collegeId.HasValue; + var item = await db.ClassroomReservations.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id && + (x.ApplicantUserId == userId || (canReview && x.ApplicantCollegeId == collegeId)), ct); + if (item is null) return NotFound(); + steps.Add(new("submitted", item.CreatedAt, null)); + if (item.ReviewedAt is { } time && item.Status is ClassroomReservationStatus.Approved or ClassroomReservationStatus.Rejected or ClassroomReservationStatus.Cancelled) + steps.Add(new(item.Status == ClassroomReservationStatus.Rejected ? "rejected" : "approved", time, item.ReviewComment)); + if (item.CancelledAt is { } cancelledAt && item.Status == ClassroomReservationStatus.Cancelled) + steps.Add(new("cancelled", cancelledAt, null)); + if ((item.Status is ClassroomReservationStatus.Approved or ClassroomReservationStatus.Rejected) && item.ReviewedAt is null || + item.Status == ClassroomReservationStatus.Cancelled && item.CancelledAt is null) + historyIncomplete = true; + break; + } case "CourseAdjustment": - { - var restrictedCollegeId = current.RestrictedCollegeId; - var allColleges = manager && current.Scope == DataScope.All; - var query = db.CourseAdjustments.AsNoTracking().Where(x => x.Id == id && - (x.ApplicantUserId == userId || (manager && (allColleges || x.TeachingTask!.Course!.CollegeId == restrictedCollegeId)))); - var item = await query.FirstOrDefaultAsync(ct); - if (item is null) return NotFound(); - if (item.SubmittedAt is { } submittedAt) steps.Add(new("submitted", submittedAt, null)); - else if (item.Status == CourseAdjustmentStatus.Draft) steps.Add(new("created", item.CreatedAt, null)); - else historyIncomplete = true; - if (item.ReviewedAt is { } reviewedAt && item.Status is CourseAdjustmentStatus.Approved or CourseAdjustmentStatus.Rejected) - steps.Add(new(item.Status == CourseAdjustmentStatus.Approved ? "approved" : "rejected", reviewedAt, item.ReviewComment)); - else if (item.Status is CourseAdjustmentStatus.Approved or CourseAdjustmentStatus.Rejected) historyIncomplete = true; - break; - } + { + var restrictedCollegeId = current.RestrictedCollegeId; + var allColleges = manager && current.Scope == DataScope.All; + var query = db.CourseAdjustments.AsNoTracking().Where(x => x.Id == id && + (x.ApplicantUserId == userId || (manager && (allColleges || x.TeachingTask!.Course!.CollegeId == restrictedCollegeId)))); + var item = await query.FirstOrDefaultAsync(ct); + if (item is null) return NotFound(); + if (item.SubmittedAt is { } submittedAt) steps.Add(new("submitted", submittedAt, null)); + else if (item.Status == CourseAdjustmentStatus.Draft) steps.Add(new("created", item.CreatedAt, null)); + else historyIncomplete = true; + if (item.ReviewedAt is { } reviewedAt && item.Status is CourseAdjustmentStatus.Approved or CourseAdjustmentStatus.Rejected) + steps.Add(new(item.Status == CourseAdjustmentStatus.Approved ? "approved" : "rejected", reviewedAt, item.ReviewComment)); + else if (item.Status is CourseAdjustmentStatus.Approved or CourseAdjustmentStatus.Rejected) historyIncomplete = true; + break; + } case "DormitoryApplication": - { - var viewer = manager || current.IsInRole(SystemRoles.DormitoryAdmin) || current.IsInRole(SystemRoles.Counselor); - var query = db.DormitoryApplications.AsNoTracking().Where(x => x.Id == id); - if (!viewer) query = query.Where(x => x.Student!.UserId == userId); - else if (current.Scope == DataScope.College) - query = query.Where(x => x.Student!.UserId == userId || x.Student.AdministrativeClass!.Major!.CollegeId == current.RestrictedCollegeId); - else if (current.Scope == DataScope.Class) - query = query.Where(x => x.Student!.UserId == userId || x.Student.AdministrativeClass!.CounselorUserId == userId); - else if (current.Scope != DataScope.All) - query = query.Where(x => x.Student!.UserId == userId); - var item = await query.FirstOrDefaultAsync(ct); - if (item is null) return NotFound(); - steps.Add(new("submitted", item.SubmittedAt, null)); - if (item.CounselorReviewedAt is { } counselorAt) { - var rejected = item.Status == DormitoryApplicationStatus.Rejected && item.FinalReviewedAt is null; - steps.Add(new(rejected ? "counselorRejected" : "counselorApproved", counselorAt, item.CounselorComment)); - } - if (item.FinalReviewedAt is { } finalAt && item.Status is DormitoryApplicationStatus.Approved or DormitoryApplicationStatus.Rejected) - steps.Add(new(item.Status == DormitoryApplicationStatus.Approved ? "dormitoryApproved" : "dormitoryRejected", finalAt, item.FinalComment)); - if (item.Status == DormitoryApplicationStatus.Cancelled || - item.Status == DormitoryApplicationStatus.CounselorApproved && item.CounselorReviewedAt is null || - item.Status == DormitoryApplicationStatus.Approved && (item.CounselorReviewedAt is null || item.FinalReviewedAt is null) || - item.Status == DormitoryApplicationStatus.Rejected && item.CounselorReviewedAt is null) - historyIncomplete = true; - break; - } - case "GradeSheet": - { - var tasks = AccessibleGradeProgressTasks(); - var item = await db.GradeSheets.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id && - tasks.Any(task => task.Id == x.TeachingTaskId), ct); - if (item is null) return NotFound(); - historyIncomplete = AddGradeProgressSteps(steps, item.Status.ToString(), item.CreatedAt, - item.SubmittedAt, item.ReviewedAt, item.PublishedAt, item.ReviewComment); - break; - } - case "GradeSubmissionBatch": - { - var tasks = AccessibleGradeProgressTasks(); - var item = await db.GradeSubmissionBatches.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id && - tasks.Any(task => task.Id == x.GradeSheet!.TeachingTaskId), ct); - if (item is null) return NotFound(); - historyIncomplete = AddGradeProgressSteps(steps, item.Status.ToString(), item.CreatedAt, - item.SubmittedAt, item.ReviewedAt, item.PublishedAt, item.ReviewComment); - break; - } - case "ExperimentGradeSheet": - { - var projects = AccessibleExperimentProgressProjects(); - var item = await db.ExperimentGradeSheets.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id && - projects.Any(project => project.Id == x.ExperimentProjectId), ct); - if (item is null) return NotFound(); - historyIncomplete = AddGradeProgressSteps(steps, item.Status.ToString(), item.CreatedAt, - item.SubmittedAt, item.ReviewedAt, item.PublishedAt, item.ReviewComment); - break; - } - case "AssessmentDeclaration": - { - var viewer = manager || current.IsInRole(SystemRoles.StudentAffairsAdmin) || current.IsInRole(SystemRoles.Counselor); - var query = db.ComprehensiveAssessmentDeclarations.AsNoTracking().Where(x => x.Id == id); - if (!viewer) query = query.Where(x => x.Student!.UserId == userId); - else if (current.Scope == DataScope.College) - query = query.Where(x => x.Student!.UserId == userId || x.Student.AdministrativeClass!.Major!.CollegeId == current.RestrictedCollegeId); - else if (current.Scope == DataScope.Class) - query = query.Where(x => x.Student!.UserId == userId || x.Student.AdministrativeClass!.CounselorUserId == userId); - else if (current.Scope != DataScope.All) - query = query.Where(x => x.Student!.UserId == userId); - var item = await query.FirstOrDefaultAsync(ct); - if (item is null) return NotFound(); - if (item.SubmittedAt is { } submittedAt) steps.Add(new("submitted", submittedAt, null)); - else if (item.Status == ComprehensiveAssessmentDeclarationStatus.Draft) steps.Add(new("created", item.CreatedAt, null)); - else historyIncomplete = true; - if (item.CounselorReviewedAt is { } counselorAt && item.Status is ComprehensiveAssessmentDeclarationStatus.CounselorApproved or ComprehensiveAssessmentDeclarationStatus.Approved or ComprehensiveAssessmentDeclarationStatus.Rejected) - { - var rejected = item.Status == ComprehensiveAssessmentDeclarationStatus.Rejected && item.CollegeReviewedAt is null; - steps.Add(new(rejected ? "counselorRejected" : "counselorApproved", counselorAt, item.CounselorComment)); - } - if (item.CollegeReviewedAt is { } collegeAt && item.Status is ComprehensiveAssessmentDeclarationStatus.Approved or ComprehensiveAssessmentDeclarationStatus.Rejected) - steps.Add(new(item.Status == ComprehensiveAssessmentDeclarationStatus.Approved ? "collegeApproved" : "collegeRejected", collegeAt, item.CollegeComment)); - if (item.Status == ComprehensiveAssessmentDeclarationStatus.Withdrawn || - item.Status == ComprehensiveAssessmentDeclarationStatus.CounselorApproved && item.CounselorReviewedAt is null || - item.Status == ComprehensiveAssessmentDeclarationStatus.Approved && (item.CounselorReviewedAt is null || item.CollegeReviewedAt is null) || - item.Status == ComprehensiveAssessmentDeclarationStatus.Rejected && item.CounselorReviewedAt is null) - historyIncomplete = true; - break; - } - case "AssessmentAppeal": - { - var viewer = manager || current.IsInRole(SystemRoles.StudentAffairsAdmin) || current.IsInRole(SystemRoles.Counselor); - var query = db.ComprehensiveAssessmentAppeals.AsNoTracking().Where(x => x.Id == id); - if (!viewer) query = query.Where(x => x.Student!.UserId == userId); - else if (current.Scope == DataScope.College) - query = query.Where(x => x.Student!.UserId == userId || x.Student.AdministrativeClass!.Major!.CollegeId == current.RestrictedCollegeId); - else if (current.Scope == DataScope.Class) - query = query.Where(x => x.Student!.UserId == userId || x.Student.AdministrativeClass!.CounselorUserId == userId); - else if (current.Scope != DataScope.All) - query = query.Where(x => x.Student!.UserId == userId); - var item = await query.FirstOrDefaultAsync(ct); - if (item is null) return NotFound(); - steps.Add(new("submitted", item.CreatedAt, null)); - if (item.ReviewedAt is { } reviewedAt && item.Status is ComprehensiveAssessmentAppealStatus.Approved or ComprehensiveAssessmentAppealStatus.Rejected) - steps.Add(new(item.Status == ComprehensiveAssessmentAppealStatus.Approved ? "approved" : "rejected", reviewedAt, item.ReviewComment)); - else if (item.Status is ComprehensiveAssessmentAppealStatus.Approved or ComprehensiveAssessmentAppealStatus.Rejected) historyIncomplete = true; - break; - } - case "StudentStatusChange": - { - var query = db.StudentStatusChanges.AsNoTracking().Where(x => x.Id == id); - if (manager || current.IsInRole(SystemRoles.Counselor)) - { - if (current.Scope == DataScope.College) - query = query.Where(x => x.Student!.UserId == userId || (x.OriginalClass != null - ? x.OriginalClass.Major!.CollegeId == current.RestrictedCollegeId - : x.Student.AdministrativeClass!.Major!.CollegeId == current.RestrictedCollegeId) || - current.IsInRole(SystemRoles.CollegeAdmin) && x.Type == StudentStatusChangeType.MajorTransfer && x.TargetClass!.Major!.CollegeId == current.RestrictedCollegeId && - (x.State == StudentStatusChangeState.CollegeApproved || x.State == StudentStatusChangeState.Approved || x.State == StudentStatusChangeState.Rejected)); + var viewer = manager || current.IsInRole(SystemRoles.DormitoryAdmin) || current.IsInRole(SystemRoles.Counselor); + var query = db.DormitoryApplications.AsNoTracking().Where(x => x.Id == id); + if (!viewer) query = query.Where(x => x.Student!.UserId == userId); + else if (current.Scope == DataScope.College) + query = query.Where(x => x.Student!.UserId == userId || x.Student.AdministrativeClass!.Major!.CollegeId == current.RestrictedCollegeId); else if (current.Scope == DataScope.Class) - query = query.Where(x => x.Student!.UserId == userId || - (x.OriginalClass != null ? x.OriginalClass.CounselorUserId : x.Student.AdministrativeClass!.CounselorUserId) == userId || - x.State == StudentStatusChangeState.Approved && x.TargetClass != null && x.TargetClass.CounselorUserId == userId); + query = query.Where(x => x.Student!.UserId == userId || x.Student.AdministrativeClass!.CounselorUserId == userId); else if (current.Scope != DataScope.All) query = query.Where(x => x.Student!.UserId == userId); - } - else query = query.Where(x => x.Student!.UserId == userId); - var item = await query.FirstOrDefaultAsync(ct); - if (item is null) return NotFound(); - steps.Add(new("submitted", item.SubmittedAt, null)); - var events = await db.StudentStatusChangeEvents.AsNoTracking() - .Where(x => x.StudentStatusChangeId == id) - .OrderBy(x => x.FromState).ThenBy(x => x.OccurredAt).ThenBy(x => x.Id).ToListAsync(ct); - var expected = StudentStatusChangeState.Submitted; - foreach (var entry in events) - { - if (entry.FromState != expected) historyIncomplete = true; - if (entry.FromState == StudentStatusChangeState.CollegeApproved && item.ReceivingCollegeReviewedAt is { } receivingAt && entry.ToState == StudentStatusChangeState.Approved) - steps.Add(new("receivingCollegeApproved", receivingAt, item.ReceivingCollegeReviewComment)); - var kind = entry.ToState switch + var item = await query.FirstOrDefaultAsync(ct); + if (item is null) return NotFound(); + steps.Add(new("submitted", item.SubmittedAt, null)); + if (item.CounselorReviewedAt is { } counselorAt) { - StudentStatusChangeState.CounselorApproved => "counselorApproved", - StudentStatusChangeState.CollegeApproved => "collegeApproved", - StudentStatusChangeState.Approved => "finalApproved", - StudentStatusChangeState.Cancelled => "cancelled", - StudentStatusChangeState.Rejected when entry.FromState == StudentStatusChangeState.Submitted => "counselorRejected", - StudentStatusChangeState.Rejected when entry.FromState == StudentStatusChangeState.CounselorApproved => "collegeRejected", - StudentStatusChangeState.Rejected when entry.FromState == StudentStatusChangeState.CollegeApproved && item.ReceivingCollegeReviewerId == entry.ActorUserId && item.ReceivingCollegeReviewedAt == entry.OccurredAt => "receivingCollegeRejected", - StudentStatusChangeState.Rejected when entry.FromState == StudentStatusChangeState.CollegeApproved => "finalRejected", - _ => "legacyReviewed" - }; - steps.Add(new(kind, entry.OccurredAt, entry.Comment)); - expected = entry.ToState; + var rejected = item.Status == DormitoryApplicationStatus.Rejected && item.FinalReviewedAt is null; + steps.Add(new(rejected ? "counselorRejected" : "counselorApproved", counselorAt, item.CounselorComment)); + } + if (item.FinalReviewedAt is { } finalAt && item.Status is DormitoryApplicationStatus.Approved or DormitoryApplicationStatus.Rejected) + steps.Add(new(item.Status == DormitoryApplicationStatus.Approved ? "dormitoryApproved" : "dormitoryRejected", finalAt, item.FinalComment)); + if (item.Status == DormitoryApplicationStatus.Cancelled || + item.Status == DormitoryApplicationStatus.CounselorApproved && item.CounselorReviewedAt is null || + item.Status == DormitoryApplicationStatus.Approved && (item.CounselorReviewedAt is null || item.FinalReviewedAt is null) || + item.Status == DormitoryApplicationStatus.Rejected && item.CounselorReviewedAt is null) + historyIncomplete = true; + break; + } + case "GradeSheet": + { + var tasks = AccessibleGradeProgressTasks(); + var item = await db.GradeSheets.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id && + tasks.Any(task => task.Id == x.TeachingTaskId), ct); + if (item is null) return NotFound(); + historyIncomplete = AddGradeProgressSteps(steps, item.Status.ToString(), item.CreatedAt, + item.SubmittedAt, item.ReviewedAt, item.PublishedAt, item.ReviewComment); + break; + } + case "GradeSubmissionBatch": + { + var tasks = AccessibleGradeProgressTasks(); + var item = await db.GradeSubmissionBatches.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id && + tasks.Any(task => task.Id == x.GradeSheet!.TeachingTaskId), ct); + if (item is null) return NotFound(); + historyIncomplete = AddGradeProgressSteps(steps, item.Status.ToString(), item.CreatedAt, + item.SubmittedAt, item.ReviewedAt, item.PublishedAt, item.ReviewComment); + break; + } + case "ExperimentGradeSheet": + { + var projects = AccessibleExperimentProgressProjects(); + var item = await db.ExperimentGradeSheets.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id && + projects.Any(project => project.Id == x.ExperimentProjectId), ct); + if (item is null) return NotFound(); + historyIncomplete = AddGradeProgressSteps(steps, item.Status.ToString(), item.CreatedAt, + item.SubmittedAt, item.ReviewedAt, item.PublishedAt, item.ReviewComment); + break; + } + case "AssessmentDeclaration": + { + var viewer = manager || current.IsInRole(SystemRoles.StudentAffairsAdmin) || current.IsInRole(SystemRoles.Counselor); + var query = db.ComprehensiveAssessmentDeclarations.AsNoTracking().Where(x => x.Id == id); + if (!viewer) query = query.Where(x => x.Student!.UserId == userId); + else if (current.Scope == DataScope.College) + query = query.Where(x => x.Student!.UserId == userId || x.Student.AdministrativeClass!.Major!.CollegeId == current.RestrictedCollegeId); + else if (current.Scope == DataScope.Class) + query = query.Where(x => x.Student!.UserId == userId || x.Student.AdministrativeClass!.CounselorUserId == userId); + else if (current.Scope != DataScope.All) + query = query.Where(x => x.Student!.UserId == userId); + var item = await query.FirstOrDefaultAsync(ct); + if (item is null) return NotFound(); + if (item.SubmittedAt is { } submittedAt) steps.Add(new("submitted", submittedAt, null)); + else if (item.Status == ComprehensiveAssessmentDeclarationStatus.Draft) steps.Add(new("created", item.CreatedAt, null)); + else historyIncomplete = true; + if (item.CounselorReviewedAt is { } counselorAt && item.Status is ComprehensiveAssessmentDeclarationStatus.CounselorApproved or ComprehensiveAssessmentDeclarationStatus.Approved or ComprehensiveAssessmentDeclarationStatus.Rejected) + { + var rejected = item.Status == ComprehensiveAssessmentDeclarationStatus.Rejected && item.CollegeReviewedAt is null; + steps.Add(new(rejected ? "counselorRejected" : "counselorApproved", counselorAt, item.CounselorComment)); + } + if (item.CollegeReviewedAt is { } collegeAt && item.Status is ComprehensiveAssessmentDeclarationStatus.Approved or ComprehensiveAssessmentDeclarationStatus.Rejected) + steps.Add(new(item.Status == ComprehensiveAssessmentDeclarationStatus.Approved ? "collegeApproved" : "collegeRejected", collegeAt, item.CollegeComment)); + if (item.Status == ComprehensiveAssessmentDeclarationStatus.Withdrawn || + item.Status == ComprehensiveAssessmentDeclarationStatus.CounselorApproved && item.CounselorReviewedAt is null || + item.Status == ComprehensiveAssessmentDeclarationStatus.Approved && (item.CounselorReviewedAt is null || item.CollegeReviewedAt is null) || + item.Status == ComprehensiveAssessmentDeclarationStatus.Rejected && item.CounselorReviewedAt is null) + historyIncomplete = true; + break; + } + case "AssessmentAppeal": + { + var viewer = manager || current.IsInRole(SystemRoles.StudentAffairsAdmin) || current.IsInRole(SystemRoles.Counselor); + var query = db.ComprehensiveAssessmentAppeals.AsNoTracking().Where(x => x.Id == id); + if (!viewer) query = query.Where(x => x.Student!.UserId == userId); + else if (current.Scope == DataScope.College) + query = query.Where(x => x.Student!.UserId == userId || x.Student.AdministrativeClass!.Major!.CollegeId == current.RestrictedCollegeId); + else if (current.Scope == DataScope.Class) + query = query.Where(x => x.Student!.UserId == userId || x.Student.AdministrativeClass!.CounselorUserId == userId); + else if (current.Scope != DataScope.All) + query = query.Where(x => x.Student!.UserId == userId); + var item = await query.FirstOrDefaultAsync(ct); + if (item is null) return NotFound(); + steps.Add(new("submitted", item.CreatedAt, null)); + if (item.ReviewedAt is { } reviewedAt && item.Status is ComprehensiveAssessmentAppealStatus.Approved or ComprehensiveAssessmentAppealStatus.Rejected) + steps.Add(new(item.Status == ComprehensiveAssessmentAppealStatus.Approved ? "approved" : "rejected", reviewedAt, item.ReviewComment)); + else if (item.Status is ComprehensiveAssessmentAppealStatus.Approved or ComprehensiveAssessmentAppealStatus.Rejected) historyIncomplete = true; + break; + } + case "StudentStatusChange": + { + var query = db.StudentStatusChanges.AsNoTracking().Where(x => x.Id == id); + if (manager || current.IsInRole(SystemRoles.Counselor)) + { + if (current.Scope == DataScope.College) + query = query.Where(x => x.Student!.UserId == userId || (x.OriginalClass != null + ? x.OriginalClass.Major!.CollegeId == current.RestrictedCollegeId + : x.Student.AdministrativeClass!.Major!.CollegeId == current.RestrictedCollegeId) || + current.IsInRole(SystemRoles.CollegeAdmin) && x.Type == StudentStatusChangeType.MajorTransfer && x.TargetClass!.Major!.CollegeId == current.RestrictedCollegeId && + (x.State == StudentStatusChangeState.CollegeApproved || x.State == StudentStatusChangeState.Approved || x.State == StudentStatusChangeState.Rejected)); + else if (current.Scope == DataScope.Class) + query = query.Where(x => x.Student!.UserId == userId || + (x.OriginalClass != null ? x.OriginalClass.CounselorUserId : x.Student.AdministrativeClass!.CounselorUserId) == userId || + x.State == StudentStatusChangeState.Approved && x.TargetClass != null && x.TargetClass.CounselorUserId == userId); + else if (current.Scope != DataScope.All) + query = query.Where(x => x.Student!.UserId == userId); + } + else query = query.Where(x => x.Student!.UserId == userId); + var item = await query.FirstOrDefaultAsync(ct); + if (item is null) return NotFound(); + steps.Add(new("submitted", item.SubmittedAt, null)); + var events = await db.StudentStatusChangeEvents.AsNoTracking() + .Where(x => x.StudentStatusChangeId == id) + .OrderBy(x => x.FromState).ThenBy(x => x.OccurredAt).ThenBy(x => x.Id).ToListAsync(ct); + var expected = StudentStatusChangeState.Submitted; + foreach (var entry in events) + { + if (entry.FromState != expected) historyIncomplete = true; + if (entry.FromState == StudentStatusChangeState.CollegeApproved && item.ReceivingCollegeReviewedAt is { } receivingAt && entry.ToState == StudentStatusChangeState.Approved) + steps.Add(new("receivingCollegeApproved", receivingAt, item.ReceivingCollegeReviewComment)); + var kind = entry.ToState switch + { + StudentStatusChangeState.CounselorApproved => "counselorApproved", + StudentStatusChangeState.CollegeApproved => "collegeApproved", + StudentStatusChangeState.Approved => "finalApproved", + StudentStatusChangeState.Cancelled => "cancelled", + StudentStatusChangeState.Rejected when entry.FromState == StudentStatusChangeState.Submitted => "counselorRejected", + StudentStatusChangeState.Rejected when entry.FromState == StudentStatusChangeState.CounselorApproved => "collegeRejected", + StudentStatusChangeState.Rejected when entry.FromState == StudentStatusChangeState.CollegeApproved && item.ReceivingCollegeReviewerId == entry.ActorUserId && item.ReceivingCollegeReviewedAt == entry.OccurredAt => "receivingCollegeRejected", + StudentStatusChangeState.Rejected when entry.FromState == StudentStatusChangeState.CollegeApproved => "finalRejected", + _ => "legacyReviewed" + }; + steps.Add(new(kind, entry.OccurredAt, entry.Comment)); + expected = entry.ToState; + } + if (item.State == StudentStatusChangeState.CollegeApproved && item.ReceivingCollegeReviewedAt is { } receivingReviewAt) + steps.Add(new("receivingCollegeApproved", receivingReviewAt, item.ReceivingCollegeReviewComment)); + if (expected != item.State) historyIncomplete = true; + if (events.Count == 0 && item.ReviewedAt is { } lastReview && item.State != StudentStatusChangeState.Submitted) + steps.Add(new(item.State == StudentStatusChangeState.Cancelled ? "cancelled" : "legacyReviewed", lastReview, item.ReviewComment)); + break; } - if (item.State == StudentStatusChangeState.CollegeApproved && item.ReceivingCollegeReviewedAt is { } receivingReviewAt) - steps.Add(new("receivingCollegeApproved", receivingReviewAt, item.ReceivingCollegeReviewComment)); - if (expected != item.State) historyIncomplete = true; - if (events.Count == 0 && item.ReviewedAt is { } lastReview && item.State != StudentStatusChangeState.Submitted) - steps.Add(new(item.State == StudentStatusChangeState.Cancelled ? "cancelled" : "legacyReviewed", lastReview, item.ReviewComment)); - break; - } default: return NotFound(); } @@ -435,133 +461,133 @@ public sealed class ApprovalsController( var isManager = current.IsInRole(SystemRoles.SuperAdmin) || current.IsInRole(SystemRoles.AcademicAdmin) || current.IsInRole(SystemRoles.CollegeAdmin); if (isManager) { - var super = current.IsInRole(SystemRoles.SuperAdmin); - var college = current.IsInRole(SystemRoles.CollegeAdmin); - var academic = current.IsInRole(SystemRoles.AcademicAdmin); - var exemptions = Scoped(x => x.Status == ApprovalStatus.Submitted && (super || x.ReviewerRoleSnapshot == null || x.ReviewerRoleSnapshot == "AnyManager" || (college && x.ReviewerRoleSnapshot == SystemRoles.CollegeAdmin) || (academic && x.ReviewerRoleSnapshot == SystemRoles.AcademicAdmin))); - var deferred = Scoped(x => x.Status == ApprovalStatus.Submitted && (super || x.ReviewerRoleSnapshot == null || x.ReviewerRoleSnapshot == "AnyManager" || (college && x.ReviewerRoleSnapshot == SystemRoles.CollegeAdmin) || (academic && x.ReviewerRoleSnapshot == SystemRoles.AcademicAdmin))); - 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))); + var super = current.IsInRole(SystemRoles.SuperAdmin); + var college = current.IsInRole(SystemRoles.CollegeAdmin); + var academic = current.IsInRole(SystemRoles.AcademicAdmin); + var exemptions = Scoped(x => x.Status == ApprovalStatus.Submitted && (super || x.ReviewerRoleSnapshot == null || x.ReviewerRoleSnapshot == "AnyManager" || (college && x.ReviewerRoleSnapshot == SystemRoles.CollegeAdmin) || (academic && x.ReviewerRoleSnapshot == SystemRoles.AcademicAdmin))); + var deferred = Scoped(x => x.Status == ApprovalStatus.Submitted && (super || x.ReviewerRoleSnapshot == null || x.ReviewerRoleSnapshot == "AnyManager" || (college && x.ReviewerRoleSnapshot == SystemRoles.CollegeAdmin) || (academic && x.ReviewerRoleSnapshot == SystemRoles.AcademicAdmin))); + 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 - .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.WhereApprovalBefore(x => x.SubmittedAt, cutoff).CountAsync(ct)); + items.AddRange(await exemptions + .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.WhereApprovalBefore(x => x.SubmittedAt, cutoff).CountAsync(ct)); - items.AddRange(await deferred - .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.WhereApprovalBefore(x => x.SubmittedAt, cutoff).CountAsync(ct)); + items.AddRange(await deferred + .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.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)) - .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)).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)) + .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)).WhereApprovalBefore(x => x.SubmittedAt, cutoff).CountAsync(ct)); - items.AddRange(await substitutions - .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.WhereApprovalBefore(x => x.SubmittedAt, cutoff).CountAsync(ct)); + items.AddRange(await substitutions + .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.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)) - .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)).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)) + .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)).WhereApprovalBefore(x => x.SubmittedAt, cutoff).CountAsync(ct)); - items.AddRange(await Scoped(x => x.Status == CourseAdjustmentStatus.Submitted) - .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).WhereApprovalBefore(x => x.SubmittedAt ?? x.CreatedAt, cutoff).CountAsync(ct)); + items.AddRange(await Scoped(x => x.Status == CourseAdjustmentStatus.Submitted) + .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).WhereApprovalBefore(x => x.SubmittedAt ?? x.CreatedAt, cutoff).CountAsync(ct)); - items.AddRange(await Scoped(x => x.Status == GradeSheetStatus.Submitted) - .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).WhereApprovalBefore(x => x.SubmittedAt ?? x.CreatedAt, cutoff).CountAsync(ct)); + items.AddRange(await Scoped(x => x.Status == GradeSheetStatus.Submitted) + .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).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 - .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.WhereApprovalBefore(x => x.AppealSubmittedAt ?? x.AttendanceSheet!.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 + .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.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.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.WhereApprovalBefore(x => x.SubmittedAt, 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.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.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. - if (scope.Current.IsInRole(SystemRoles.CollegeAdmin) && scope.Current.CollegeId is { } collegeId) - { - var reservations = db.ClassroomReservations.AsNoTracking().Where(x => - x.Status == ClassroomReservationStatus.Submitted && x.ApplicantCollegeId == collegeId); - 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.WhereApprovalBefore(x => x.CreatedAt, cutoff).CountAsync(ct)); - } + // This workflow is restricted to the applicant's college even for users + // who also hold a system-wide role. + if (scope.Current.IsInRole(SystemRoles.CollegeAdmin) && scope.Current.CollegeId is { } collegeId) + { + var reservations = db.ClassroomReservations.AsNoTracking().Where(x => + x.Status == ClassroomReservationStatus.Submitted && x.ApplicantCollegeId == collegeId); + 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.WhereApprovalBefore(x => x.CreatedAt, cutoff).CountAsync(ct)); + } - var gradeBatches = Scoped(x => x.Status == GradeSheetStatus.Submitted); - 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.WhereApprovalBefore(x => x.SubmittedAt, cutoff).CountAsync(ct)); + var gradeBatches = Scoped(x => x.Status == GradeSheetStatus.Submitted); + 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.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.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.WhereApprovalBefore(x => x.SubmittedAt ?? x.CreatedAt, cutoff).CountAsync(ct)); + var experimentGrades = Scoped(x => x.Status == ExperimentGradeSheetStatus.Submitted && x.ExperimentProject!.TeachingTask!.Status == TeachingTaskStatus.Published); + 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.WhereApprovalBefore(x => x.SubmittedAt ?? x.CreatedAt, cutoff).CountAsync(ct)); - var campusApplications = Scoped(x => x.Status == CampusRegistrationApplicationStatus.PendingReview); - 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.WhereApprovalBefore(x => x.CreatedAt, cutoff).CountAsync(ct)); + var campusApplications = Scoped(x => x.Status == CampusRegistrationApplicationStatus.PendingReview); + 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.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.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.WhereApprovalBefore(x => x.SubmittedAt, 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.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.WhereApprovalBefore(x => x.SubmittedAt, cutoff).CountAsync(ct)); + } - var declarations = Scoped(x => x.Status == ComprehensiveAssessmentDeclarationStatus.CounselorApproved); - 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.WhereApprovalBefore(x => x.SubmittedAt ?? x.CreatedAt, cutoff).CountAsync(ct)); + var declarations = Scoped(x => x.Status == ComprehensiveAssessmentDeclarationStatus.CounselorApproved); + 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.WhereApprovalBefore(x => x.SubmittedAt ?? x.CreatedAt, cutoff).CountAsync(ct)); - var assessmentAppeals = Scoped(x => x.Status == ComprehensiveAssessmentAppealStatus.Submitted); - 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.WhereApprovalBefore(x => x.CreatedAt, cutoff).CountAsync(ct)); + var assessmentAppeals = Scoped(x => x.Status == ComprehensiveAssessmentAppealStatus.Submitted); + 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.WhereApprovalBefore(x => x.CreatedAt, cutoff).CountAsync(ct)); } if (current.IsInRole(SystemRoles.Counselor)) @@ -1372,7 +1398,18 @@ public sealed class ApprovalsController( private static string SSCLabel(StudentStatusChangeType t) => t switch { StudentStatusChangeType.Suspension => "休学", StudentStatusChangeType.Resumption => "复学", StudentStatusChangeType.Withdrawal => "退学", StudentStatusChangeType.Enlistment => "入伍保留学籍", StudentStatusChangeType.Demotion => "降级", StudentStatusChangeType.ClassTransfer => "转班", StudentStatusChangeType.MajorTransfer => "转专业", StudentStatusChangeType.DataCorrection => "档案纠错", _ => "异动" }; private static string CALabel(CourseAdjustmentType t) => t switch { CourseAdjustmentType.Reschedule => "调课", CourseAdjustmentType.Cancel => "停课", CourseAdjustmentType.Makeup => "补课", CourseAdjustmentType.Substitute => "代课", _ => "调停课" }; - private ActionResult ConflictProblem(string d) => Conflict(new ProblemDetails { Title = "无法完成", Detail = d, Status = 409 }); + private ActionResult ConflictProblem(string d) => Conflict(new ProblemDetails + { + Title = SharedResourceText.Get(localizer, "Approvals.Errors.Title"), + Detail = LocalizeApprovalMessage(d), + Status = 409 + }); + + private ActionResult ValidationProblem(string detail) => + base.ValidationProblem(detail: LocalizeApprovalMessage(detail)); + + private string LocalizeApprovalMessage(string detail) => + ApprovalsErrorKeys.TryGetValue(detail, out var key) ? SharedResourceText.Get(localizer, key) : detail; } public sealed record ApprovalItem(Guid Id, string Type, string Label, string Title, string Desc, DateTime Time, string College, string? Stage = null, Guid? SecondaryId = null); diff --git a/src/Jiaowu.Api/Controllers/StudentStatusChangesController.cs b/src/Jiaowu.Api/Controllers/StudentStatusChangesController.cs index 79d5717..5b3819e 100644 --- a/src/Jiaowu.Api/Controllers/StudentStatusChangesController.cs +++ b/src/Jiaowu.Api/Controllers/StudentStatusChangesController.cs @@ -5,9 +5,11 @@ using Jiaowu.Api.Domain.Academic; using Jiaowu.Api.Domain.Identity; using Jiaowu.Api.Infrastructure.Auth; using Jiaowu.Api.Infrastructure.Persistence; +using Jiaowu.Api.Infrastructure.Localization; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Localization; namespace Jiaowu.Api.Controllers; @@ -16,8 +18,61 @@ namespace Jiaowu.Api.Controllers; [Route("api/student-status-changes")] public sealed class StudentStatusChangesController( AppDbContext db, - ICurrentUserDataScope currentUserDataScope) : ControllerBase + ICurrentUserDataScope currentUserDataScope, + IStringLocalizer? localizer = null) : ControllerBase { + private static readonly IReadOnlyDictionary StudentStatusChangesErrorKeys = new Dictionary + { + ["页码必须大于 0,且每页条数应在 1 至 100 之间。"] = "StudentStatusChanges.Page.Range", + ["当前账号未关联学生档案。"] = "StudentStatusChanges.StudentProfile.NotLinked", + ["请输入至少两个字符的学号或姓名。"] = "StudentStatusChanges.Search.MinimumLength", + ["请填写不晚于今天的有效退役日期,备注不超过 500 字。"] = "StudentStatusChanges.Discharge.InvalidDate", + ["仅保留学籍期间可以登记退役信息。"] = "StudentStatusChanges.Discharge.RetainedStatusRequired", + ["缺少已批准的入伍日期,需先核实历史学籍记录。"] = "StudentStatusChanges.Discharge.EnlistmentDateMissing", + ["退役日期不能早于入伍日期。"] = "StudentStatusChanges.Discharge.DateBeforeEnlistment", + ["该申请缺少受影响学期,请重新提交申请。"] = "StudentStatusChanges.Application.TermMissing", + ["请填写 10 至 500 字的取消原因。"] = "StudentStatusChanges.Application.CancelReasonLength", + ["只有已生效且具有起始学期的异动可以处理预约。"] = "StudentStatusChanges.Booking.ChangeNotEffective", + ["预约已取消、已过期或不属于本次异动范围。"] = "StudentStatusChanges.Booking.Unavailable", + ["该预约已由本次异动处理过,不能重复取消。"] = "StudentStatusChanges.Booking.AlreadyProcessed", + ["学生档案已归档,不能发起新的学籍异动。"] = "StudentStatusChanges.Student.Archived", + ["当前学籍状态不能申请该类异动。"] = "StudentStatusChanges.Application.InvalidForCurrentStatus", + ["入伍保留学籍须填写不晚于今天的入伍日期。"] = "StudentStatusChanges.Enlistment.DateRequired", + ["在校生入伍日期不能早于入学日期;新生保留入学资格需另行办理。"] = "StudentStatusChanges.Enlistment.DateBeforeEnrollment", + ["退役复学须填写不晚于今天且不早于入伍日期的退役日期。"] = "StudentStatusChanges.Resumption.DischargeDateRequired", + ["复学申请的退役日期与最新登记不一致,请先更正退役登记。"] = "StudentStatusChanges.Resumption.DischargeDateMismatch", + ["申请必须选择有效的生效学期。"] = "StudentStatusChanges.Application.EffectiveTermRequired", + ["异动当前在批准后立即生效,不能选择尚未开始的学期。"] = "StudentStatusChanges.Application.FutureTermNotAllowed", + ["目标班级不符合异动类型要求。"] = "StudentStatusChanges.Application.TargetClassInvalid", + ["降级目标班级须属于本专业的较低年级。"] = "StudentStatusChanges.Application.DemotionTargetGrade", + ["已有一项学籍异动正在审核中。"] = "StudentStatusChanges.Application.AlreadyPending", + ["请填写至少 10 个字的纠错原因,并选择有效的学籍状态。"] = "StudentStatusChanges.Correction.ReasonAndStatusRequired", + ["学生档案已归档,不能直接纠错。"] = "StudentStatusChanges.Correction.ArchivedStudent", + ["学籍状态或班级已变化,请刷新后重新核对。"] = "StudentStatusChanges.Correction.RecordChanged", + ["纠错前后的状态和班级没有变化。"] = "StudentStatusChanges.Correction.NoChanges", + ["目标班级不存在或不可用。"] = "StudentStatusChanges.Correction.TargetClassUnavailable", + ["该学生或相关班级已有教学、考试或学籍异动记录,不能直接纠错;请按学籍异动流程处理并核对历史数据。"] = "StudentStatusChanges.Correction.HasRelatedRecords", + ["当前申请不在待转入学院审核阶段。"] = "StudentStatusChanges.Review.NotAtReceivingCollege", + ["转入学院驳回时必须填写审核意见。"] = "StudentStatusChanges.Review.ReceivingCollegeCommentRequired", + ["申请状态已发生变化,请刷新后重试。"] = "StudentStatusChanges.Application.StateChanged", + ["当前角色或审核阶段不允许执行该操作。"] = "StudentStatusChanges.Review.ActionNotAllowed", + ["学生学籍状态已发生变化,请重新核对申请。"] = "StudentStatusChanges.Review.StudentStatusChanged", + ["学生班级已发生变化,请重新核对申请。"] = "StudentStatusChanges.Review.StudentClassChanged", + ["退役日期登记已变化,请驳回申请并重新提交。"] = "StudentStatusChanges.Review.DischargeRecordChanged", + ["复学目标班级已不可用或不属于原专业。"] = "StudentStatusChanges.Resumption.TargetClassUnavailable", + ["复学申请缺少生效学期,请驳回后重新提交。"] = "StudentStatusChanges.Resumption.EffectiveTermMissing", + ["复学批准后立即生效,不能选择尚未开始的学期。"] = "StudentStatusChanges.Resumption.FutureTermNotAllowed", + ["缺少带起始学期的休学或入伍记录,无法安全调整复学班级,请先核实历史学籍。"] = "StudentStatusChanges.Resumption.HistoryMissing", + ["复学生效学期不能早于休学或入伍起始学期。"] = "StudentStatusChanges.Resumption.TermBeforeSuspension", + ["目标班级已不可用或不符合异动要求。"] = "StudentStatusChanges.Review.TargetClassUnavailable", + ["跨学院转专业须先经当前转入学院审核同意。"] = "StudentStatusChanges.Review.ReceivingCollegeApprovalRequired", + ["该申请缺少受影响学期,请驳回后重新提交。"] = "StudentStatusChanges.Review.TermMissing", + ["异动批准后立即生效,不能选择尚未开始的学期。"] = "StudentStatusChanges.Review.FutureTermNotAllowed", + ["存在未发布或异常考核成绩,请先处理成绩后再批准。请查看课程影响预览。"] = "StudentStatusChanges.Review.UnpublishedGrades", + ["存在未提交的成绩,请先核对课程影响并确认归档原成绩。"] = "StudentStatusChanges.Review.UnsubmittedGrades", + ["只有尚未进入审核的申请可以撤回。"] = "StudentStatusChanges.Application.WithdrawBeforeReviewOnly", + }; + [HttpGet] public async Task> Get( int page = 1, @@ -131,7 +186,9 @@ public sealed class StudentStatusChangesController( .Take(100) .Select(report => new { - report.StudentId, report.DischargeDate, report.ReportedAt, + report.StudentId, + report.DischargeDate, + report.ReportedAt, StudentNumber = db.Students.Where(student => student.Id == report.StudentId).Select(student => student.StudentNumber).FirstOrDefault(), StudentName = db.Students.Where(student => student.Id == report.StudentId).Select(student => student.Name).FirstOrDefault(), ClassName = db.Students.Where(student => student.Id == report.StudentId).Select(student => student.AdministrativeClass!.Name).FirstOrDefault() @@ -139,8 +196,13 @@ public sealed class StudentStatusChangesController( var today = DateOnly.FromDateTime(DateTime.UtcNow); return Ok(reports.Select(report => new { - report.StudentId, report.StudentNumber, report.StudentName, report.ClassName, report.DischargeDate, - report.ReportedAt, RetainedUntil = report.DischargeDate.AddYears(2), + report.StudentId, + report.StudentNumber, + report.StudentName, + report.ClassName, + report.DischargeDate, + report.ReportedAt, + RetainedUntil = report.DischargeDate.AddYears(2), DaysRemaining = report.DischargeDate.AddYears(2).DayNumber - today.DayNumber })); } @@ -189,12 +251,21 @@ public sealed class StudentStatusChangesController( .OrderByDescending(x => x.ReportedAt).ThenByDescending(x => x.Id) .Select(x => new { x.DischargeDate, x.ReportedAt }).FirstOrDefaultAsync(token); var retainedUntil = report?.DischargeDate.AddYears(2); - return new { student.Status, Types = types, HasPending = hasPending, - CurrentClassId = student.AdministrativeClassId, MajorId = student.AdministrativeClass!.MajorId, - CurrentGrade = student.AdministrativeClass.Grade, CollegeId = student.AdministrativeClass.Major!.CollegeId, - RequiresDischargeDate = enlistment is not null, DischargeDate = report?.DischargeDate, - DischargeReportedAt = report?.ReportedAt, RetainedUntil = retainedUntil, - RetentionDaysRemaining = retainedUntil?.DayNumber - DateOnly.FromDateTime(DateTime.UtcNow).DayNumber }; + return new + { + student.Status, + Types = types, + HasPending = hasPending, + CurrentClassId = student.AdministrativeClassId, + MajorId = student.AdministrativeClass!.MajorId, + CurrentGrade = student.AdministrativeClass.Grade, + CollegeId = student.AdministrativeClass.Major!.CollegeId, + RequiresDischargeDate = enlistment is not null, + DischargeDate = report?.DischargeDate, + DischargeReportedAt = report?.ReportedAt, + RetainedUntil = retainedUntil, + RetentionDaysRemaining = retainedUntil?.DayNumber - DateOnly.FromDateTime(DateTime.UtcNow).DayNumber + }; } [HttpGet("discharge-reports")] @@ -217,9 +288,16 @@ public sealed class StudentStatusChangesController( private async Task LoadDischargeReportsAsync(Guid studentId, CancellationToken token) => await db.StudentMilitaryDischargeReports.AsNoTracking().Where(x => x.StudentId == studentId) .OrderByDescending(x => x.ReportedAt).ThenByDescending(x => x.Id) - .Select(x => new { x.Id, x.DischargeDate, x.ReportedAt, x.ReportedByUserId, x.Notes, + .Select(x => new + { + x.Id, + x.DischargeDate, + x.ReportedAt, + x.ReportedByUserId, + x.Notes, ReportedByName = db.Users.Where(u => u.Id == x.ReportedByUserId).Select(u => u.DisplayName).FirstOrDefault(), - ServiceStartDate = x.EnlistmentChange!.ServiceStartDate }) + ServiceStartDate = x.EnlistmentChange!.ServiceStartDate + }) .ToListAsync(token); [HttpPost("discharge-reports")] @@ -254,9 +332,15 @@ public sealed class StudentStatusChangesController( return ConflictProblem("缺少已批准的入伍日期,需先核实历史学籍记录。"); if (request.DischargeDate < enlistment.ServiceStartDate) return ValidationProblem("退役日期不能早于入伍日期。"); - var report = new StudentMilitaryDischargeReport { StudentId = student.Id, EnlistmentChangeId = enlistment.Id, - DischargeDate = request.DischargeDate, ReportedByUserId = scope.UserId, ReportedAt = DateTime.UtcNow, - Notes = string.IsNullOrWhiteSpace(request.Notes) ? null : request.Notes.Trim() }; + var report = new StudentMilitaryDischargeReport + { + StudentId = student.Id, + EnlistmentChangeId = enlistment.Id, + DischargeDate = request.DischargeDate, + ReportedByUserId = scope.UserId, + ReportedAt = DateTime.UtcNow, + Notes = string.IsNullOrWhiteSpace(request.Notes) ? null : request.Notes.Trim() + }; db.StudentMilitaryDischargeReports.Add(report); await db.SaveChangesAsync(token); await transaction.CommitAsync(token); @@ -285,12 +369,29 @@ public sealed class StudentStatusChangesController( var archives = await db.StudentStatusChangeGradeArchives.AsNoTracking() .Where(x => x.StudentStatusChangeId == id) .OrderBy(x => x.ArchivedAt) - .Select(x => new { x.Id, x.TeachingTaskId, x.GradeSheetId, x.OriginalGradeRecordId, + .Select(x => new + { + x.Id, + x.TeachingTaskId, + x.GradeSheetId, + x.OriginalGradeRecordId, TaskName = db.TeachingTasks.Where(task => task.Id == x.TeachingTaskId).Select(task => task.Name).FirstOrDefault(), - x.ArchivedByUserId, x.ArchivedAt, x.SnapshotJson }) + x.ArchivedByUserId, + x.ArchivedAt, + x.SnapshotJson + }) .ToListAsync(token); - return Ok(archives.Select(x => new { x.Id, x.TeachingTaskId, x.TaskName, x.GradeSheetId, x.OriginalGradeRecordId, - x.ArchivedByUserId, x.ArchivedAt, Snapshot = JsonSerializer.Deserialize(x.SnapshotJson) })); + return Ok(archives.Select(x => new + { + x.Id, + x.TeachingTaskId, + x.TaskName, + x.GradeSheetId, + x.OriginalGradeRecordId, + x.ArchivedByUserId, + x.ArchivedAt, + Snapshot = JsonSerializer.Deserialize(x.SnapshotJson) + })); } [HttpGet("{id:guid}/experiment-effects")] @@ -300,13 +401,21 @@ public sealed class StudentStatusChangesController( return Ok(await db.StudentStatusChangeExperimentEffects.AsNoTracking() .Where(x => x.StudentStatusChangeId == id) .OrderBy(x => x.CancelledAt) - .Select(x => new { x.Id, x.ExperimentBookingId, x.ExperimentSessionId, x.CancelledAt, x.CancelledByUserId, x.Reason, + .Select(x => new + { + x.Id, + x.ExperimentBookingId, + x.ExperimentSessionId, + x.CancelledAt, + x.CancelledByUserId, + x.Reason, SessionDate = db.ExperimentSessions.Where(session => session.Id == x.ExperimentSessionId) .Select(session => (DateOnly?)session.SessionDate).FirstOrDefault(), ProjectName = db.ExperimentSessions.Where(session => session.Id == x.ExperimentSessionId) .Select(session => session.ExperimentProject!.Name).FirstOrDefault(), TaskName = db.ExperimentSessions.Where(session => session.Id == x.ExperimentSessionId) - .Select(session => session.ExperimentProject!.TeachingTask!.Name).FirstOrDefault() }) + .Select(session => session.ExperimentProject!.TeachingTask!.Name).FirstOrDefault() + }) .ToListAsync(token)); } @@ -320,9 +429,13 @@ public sealed class StudentStatusChangesController( var today = DateOnly.FromDateTime(DateTime.UtcNow.AddHours(8)); return Ok(await FollowUpBookings(change, today).AsNoTracking().Select(x => new { - BookingId = x.Id, x.ExperimentSessionId, SessionDate = x.ExperimentSession!.SessionDate, - x.ExperimentSession.StartPeriod, x.ExperimentSession.PeriodCount, - ProjectName = x.ExperimentProject!.Name, TaskName = x.ExperimentProject.TeachingTask!.Name + BookingId = x.Id, + x.ExperimentSessionId, + SessionDate = x.ExperimentSession!.SessionDate, + x.ExperimentSession.StartPeriod, + x.ExperimentSession.PeriodCount, + ProjectName = x.ExperimentProject!.Name, + TaskName = x.ExperimentProject.TeachingTask!.Name }).ToListAsync(token)); } @@ -356,8 +469,13 @@ public sealed class StudentStatusChangesController( x.ExperimentSessionId == booking.ExperimentSessionId && x.Status == ExperimentBookingStatus.Booked && x.Id != booking.Id, token); db.StudentStatusChangeExperimentEffects.Add(new StudentStatusChangeExperimentEffect { - StudentStatusChangeId = id, ExperimentBookingId = booking.Id, ExperimentSessionId = booking.ExperimentSessionId, - StudentId = booking.StudentId, CancelledAt = now, CancelledByUserId = scope.UserId, Reason = request.Reason.Trim() + StudentStatusChangeId = id, + ExperimentBookingId = booking.Id, + ExperimentSessionId = booking.ExperimentSessionId, + StudentId = booking.StudentId, + CancelledAt = now, + CancelledByUserId = scope.UserId, + Reason = request.Reason.Trim() }); await db.SaveChangesAsync(token); await transaction.CommitAsync(token); @@ -485,9 +603,13 @@ public sealed class StudentStatusChangesController( return ConflictProblem("已有一项学籍异动正在审核中。"); var change = new StudentStatusChange { - StudentId = student.Id, Type = request.Type, SubmittedByUserId = actorId, - OriginalStatus = student.Status, TargetStatus = target.Value, - Reason = request.Reason.Trim(), AffectedTermId = request.AffectedTermId, + StudentId = student.Id, + Type = request.Type, + SubmittedByUserId = actorId, + OriginalStatus = student.Status, + TargetStatus = target.Value, + Reason = request.Reason.Trim(), + AffectedTermId = request.AffectedTermId, OriginalClassId = student.AdministrativeClassId, TargetClassId = request.Type is StudentStatusChangeType.Resumption or StudentStatusChangeType.Demotion or StudentStatusChangeType.ClassTransfer or StudentStatusChangeType.MajorTransfer ? request.TargetClassId : null, ServiceStartDate = request.Type == StudentStatusChangeType.Enlistment ? request.ServiceStartDate : null, @@ -546,16 +668,29 @@ public sealed class StudentStatusChangesController( var now = DateTime.UtcNow; var change = new StudentStatusChange { - StudentId = studentId, Type = StudentStatusChangeType.DataCorrection, - OriginalStatus = student.Status, TargetStatus = request.TargetStatus, - OriginalClassId = student.AdministrativeClassId, TargetClassId = request.TargetClassId, - Reason = request.Reason.Trim(), SubmittedByUserId = scope.UserId, - State = StudentStatusChangeState.Approved, SubmittedAt = now, ReviewedAt = now, ApprovedAt = now + StudentId = studentId, + Type = StudentStatusChangeType.DataCorrection, + OriginalStatus = student.Status, + TargetStatus = request.TargetStatus, + OriginalClassId = student.AdministrativeClassId, + TargetClassId = request.TargetClassId, + Reason = request.Reason.Trim(), + SubmittedByUserId = scope.UserId, + State = StudentStatusChangeState.Approved, + SubmittedAt = now, + ReviewedAt = now, + ApprovedAt = now }; db.StudentStatusChanges.Add(change); - db.StudentStatusChangeEvents.Add(new StudentStatusChangeEvent { StudentStatusChangeId = change.Id, - FromState = StudentStatusChangeState.Submitted, ToState = StudentStatusChangeState.Approved, - ActorUserId = scope.UserId, OccurredAt = now, Comment = change.Reason }); + db.StudentStatusChangeEvents.Add(new StudentStatusChangeEvent + { + StudentStatusChangeId = change.Id, + FromState = StudentStatusChangeState.Submitted, + ToState = StudentStatusChangeState.Approved, + ActorUserId = scope.UserId, + OccurredAt = now, + Comment = change.Reason + }); student.Status = request.TargetStatus; student.AdministrativeClassId = request.TargetClassId; await db.SaveChangesAsync(token); @@ -610,9 +745,15 @@ public sealed class StudentStatusChangesController( change.State = StudentStatusChangeState.Rejected; change.ReviewedAt = now; change.ReviewComment = change.ReceivingCollegeReviewComment; - db.StudentStatusChangeEvents.Add(new StudentStatusChangeEvent { StudentStatusChangeId = change.Id, - FromState = StudentStatusChangeState.CollegeApproved, ToState = StudentStatusChangeState.Rejected, - ActorUserId = scope.UserId, OccurredAt = now, Comment = change.ReceivingCollegeReviewComment }); + db.StudentStatusChangeEvents.Add(new StudentStatusChangeEvent + { + StudentStatusChangeId = change.Id, + FromState = StudentStatusChangeState.CollegeApproved, + ToState = StudentStatusChangeState.Rejected, + ActorUserId = scope.UserId, + OccurredAt = now, + Comment = change.ReceivingCollegeReviewComment + }); } try { await db.SaveChangesAsync(token); } catch (DbUpdateConcurrencyException) { return ConflictProblem("申请状态已发生变化,请刷新后重试。"); } @@ -707,7 +848,9 @@ public sealed class StudentStatusChangesController( foreach (var taskId in missedTaskIds) db.StudentStatusChangeCourseEffects.Add(new StudentStatusChangeCourseEffect { - StudentStatusChangeId = change.Id, StudentId = change.StudentId, TeachingTaskId = taskId + StudentStatusChangeId = change.Id, + StudentId = change.StudentId, + TeachingTaskId = taskId }); } change.Student.AdministrativeClassId = targetClass.Id; @@ -752,18 +895,40 @@ public sealed class StudentStatusChangesController( { var snapshot = new { - grade.RegularScore, grade.FinalScore, grade.TotalScore, grade.GradePoint, - Result = grade.Result?.ToString(), grade.IsPassed, ExamStatus = grade.ExamStatus.ToString(), grade.Notes, - Sheet = new { grade.GradeSheet!.RegularWeight, grade.GradeSheet.FinalWeight, - EvaluationMethod = grade.GradeSheet.EvaluationMethod.ToString(), Status = grade.GradeSheet.Status.ToString() }, - Items = grade.ItemScores.Select(x => new { x.GradeItemId, Name = x.GradeItem!.Name, x.GradeItem.Weight, - x.GradeItem.SortOrder, SourceType = x.GradeItem.SourceType.ToString(), x.Score }).ToArray() + grade.RegularScore, + grade.FinalScore, + grade.TotalScore, + grade.GradePoint, + Result = grade.Result?.ToString(), + grade.IsPassed, + ExamStatus = grade.ExamStatus.ToString(), + grade.Notes, + Sheet = new + { + grade.GradeSheet!.RegularWeight, + grade.GradeSheet.FinalWeight, + EvaluationMethod = grade.GradeSheet.EvaluationMethod.ToString(), + Status = grade.GradeSheet.Status.ToString() + }, + Items = grade.ItemScores.Select(x => new + { + x.GradeItemId, + Name = x.GradeItem!.Name, + x.GradeItem.Weight, + x.GradeItem.SortOrder, + SourceType = x.GradeItem.SourceType.ToString(), + x.Score + }).ToArray() }; db.StudentStatusChangeGradeArchives.Add(new StudentStatusChangeGradeArchive { - StudentStatusChangeId = change.Id, StudentId = change.StudentId, - TeachingTaskId = grade.GradeSheet!.TeachingTaskId, GradeSheetId = grade.GradeSheetId, - OriginalGradeRecordId = grade.Id, ArchivedByUserId = scope.UserId, ArchivedAt = reviewedAt, + StudentStatusChangeId = change.Id, + StudentId = change.StudentId, + TeachingTaskId = grade.GradeSheet!.TeachingTaskId, + GradeSheetId = grade.GradeSheetId, + OriginalGradeRecordId = grade.Id, + ArchivedByUserId = scope.UserId, + ArchivedAt = reviewedAt, SnapshotJson = JsonSerializer.Serialize(snapshot, new JsonSerializerOptions(JsonSerializerDefaults.Web)) }); } @@ -774,7 +939,9 @@ public sealed class StudentStatusChangesController( foreach (var taskId in excludedTaskIds.Except(existingEffects)) db.StudentStatusChangeCourseEffects.Add(new StudentStatusChangeCourseEffect { - StudentStatusChangeId = change.Id, StudentId = change.StudentId, TeachingTaskId = taskId + StudentStatusChangeId = change.Id, + StudentId = change.StudentId, + TeachingTaskId = taskId }); var enrollments = await db.CourseEnrollments.Where(x => x.StudentId == change.StudentId && (x.Status == CourseEnrollmentStatus.Enrolled || x.Status == CourseEnrollmentStatus.Waitlisted) && @@ -815,9 +982,13 @@ public sealed class StudentStatusChangesController( { db.StudentStatusChangeExperimentEffects.Add(new StudentStatusChangeExperimentEffect { - StudentStatusChangeId = change.Id, ExperimentBookingId = booking.Id, - ExperimentSessionId = booking.ExperimentSessionId, StudentId = booking.StudentId, CancelledAt = reviewedAt, - CancelledByUserId = scope.UserId, Reason = "学籍异动终审自动取消" + StudentStatusChangeId = change.Id, + ExperimentBookingId = booking.Id, + ExperimentSessionId = booking.ExperimentSessionId, + StudentId = booking.StudentId, + CancelledAt = reviewedAt, + CancelledByUserId = scope.UserId, + Reason = "学籍异动终审自动取消" }); booking.Status = ExperimentBookingStatus.Cancelled; booking.CancelledAt = reviewedAt; @@ -847,8 +1018,12 @@ public sealed class StudentStatusChangesController( change.ReviewedAt = reviewedAt; db.StudentStatusChangeEvents.Add(new StudentStatusChangeEvent { - StudentStatusChangeId = change.Id, FromState = fromState, ToState = change.State, - ActorUserId = scope.UserId, OccurredAt = reviewedAt, Comment = change.ReviewComment + StudentStatusChangeId = change.Id, + FromState = fromState, + ToState = change.State, + ActorUserId = scope.UserId, + OccurredAt = reviewedAt, + Comment = change.ReviewComment }); try { await db.SaveChangesAsync(token); } catch (DbUpdateConcurrencyException) { return ConflictProblem("申请状态已发生变化,请刷新后重试。"); } @@ -887,14 +1062,29 @@ public sealed class StudentStatusChangesController( var ids = tasks.Select(x => x.Id).ToArray(); var grades = await db.GradeRecords.AsNoTracking() .Where(x => x.StudentId == studentId && ids.Contains(x.GradeSheet!.TeachingTaskId)) - .Select(x => new { x.Id, x.GradeSheet!.TeachingTaskId, x.PublishedAt, SheetStatus = x.GradeSheet.Status, - x.GradeSheet.RegularWeight, x.GradeSheet.FinalWeight, x.GradeSheet.EvaluationMethod, - x.ExamStatus, x.RegularScore, x.FinalScore, x.TotalScore, x.GradePoint, x.IsPassed, x.Result, x.Notes, + .Select(x => new + { + x.Id, + x.GradeSheet!.TeachingTaskId, + x.PublishedAt, + SheetStatus = x.GradeSheet.Status, + x.GradeSheet.RegularWeight, + x.GradeSheet.FinalWeight, + x.GradeSheet.EvaluationMethod, + x.ExamStatus, + x.RegularScore, + x.FinalScore, + x.TotalScore, + x.GradePoint, + x.IsPassed, + x.Result, + x.Notes, HasScores = x.ItemScores.Any(s => s.Score != null), HasSubmissions = x.ScoreSubmissions.Any() || x.SubmissionBatches.Any(), HasReferences = db.GradeModifications.Any(m => m.GradeRecordId == x.Id) || db.GradeAppeals.Any(a => a.GradeRecordId == x.Id) || - db.MakeupExamEnrollments.Any(e => e.SourceGradeRecordId == x.Id) }) + db.MakeupExamEnrollments.Any(e => e.SourceGradeRecordId == x.Id) + }) .ToListAsync(token); var gradeIds = grades.Select(x => x.Id).ToArray(); var itemScores = await db.GradeItemScores.AsNoTracking().Where(x => gradeIds.Contains(x.GradeRecordId)) @@ -948,8 +1138,11 @@ public sealed class StudentStatusChangesController( change.ReviewedAt = cancelledAt; db.StudentStatusChangeEvents.Add(new StudentStatusChangeEvent { - StudentStatusChangeId = change.Id, FromState = StudentStatusChangeState.Submitted, - ToState = StudentStatusChangeState.Cancelled, ActorUserId = userId, OccurredAt = cancelledAt + StudentStatusChangeId = change.Id, + FromState = StudentStatusChangeState.Submitted, + ToState = StudentStatusChangeState.Cancelled, + ActorUserId = userId, + OccurredAt = cancelledAt }); try { await db.SaveChangesAsync(token); } catch (DbUpdateConcurrencyException) { return ConflictProblem("申请状态已发生变化,请刷新后重试。"); } @@ -1019,9 +1212,17 @@ public sealed class StudentStatusChangesController( private ActionResult ConflictProblem(string detail) => Conflict(new ProblemDetails { - Title = "无法完成学籍异动操作", Detail = detail, + Title = SharedResourceText.Get(localizer, "StudentStatusChanges.Errors.Title"), + Detail = LocalizeStudentStatusChangeMessage(detail), Status = StatusCodes.Status409Conflict }); + + private ActionResult ValidationProblem(string detail) => + base.ValidationProblem(detail: LocalizeStudentStatusChangeMessage(detail)); + + private string LocalizeStudentStatusChangeMessage(string detail) => + StudentStatusChangesErrorKeys.TryGetValue(detail, out var key) ? SharedResourceText.Get(localizer, key) : detail; + } public sealed record StudentStatusChangePage( diff --git a/src/Jiaowu.Api/Resources/Infrastructure/Localization/SharedResource.en-US.resx b/src/Jiaowu.Api/Resources/Infrastructure/Localization/SharedResource.en-US.resx index d6c8b1e..4fe2afb 100644 --- a/src/Jiaowu.Api/Resources/Infrastructure/Localization/SharedResource.en-US.resx +++ b/src/Jiaowu.Api/Resources/Infrastructure/Localization/SharedResource.en-US.resx @@ -571,4 +571,73 @@ The number of applicants exceeds the current room capacity, so the reservation cannot be approved. The reservation date cannot be in the past. The reservation date is outside the selected term. + Page must be greater than 0 and page size must be between 1 and 100. + The current account is not linked to a student record. + Enter at least two characters of a student number or name. + Enter a valid discharge date no later than today. Notes must be 500 characters or fewer. + Discharge information can only be recorded while student status is retained. + There is no approved enlistment date. Verify the student history first. + The discharge date cannot be earlier than the enlistment date. + This application has no affected term. Submit it again. + Enter a cancellation reason between 10 and 500 characters. + Bookings can only be processed for an effective status change with a start term. + The booking is cancelled, expired or outside the scope of this status change. + This booking was already processed for this status change. + An archived student record cannot start a new status change. + This type of status change is not available for the current student status. + Enter an enlistment date no later than today to retain student status. + For an enrolled student, the enlistment date cannot be earlier than the enrollment date. New students must apply separately to retain admission eligibility. + Enter a discharge date no later than today and no earlier than the enlistment date. + The discharge date in this resumption request differs from the latest record. Correct the discharge record first. + Select a valid effective term. + This change takes effect upon approval. Select a term that has already started. + The target class does not meet the requirements for this change type. + The demotion target must be a lower year in the same major. + A student status change is already under review. + Enter a correction reason of at least 10 characters and select a valid student status. + An archived student record cannot be corrected directly. + The student status or class has changed. Refresh and review it again. + The status and class are unchanged by this correction. + The target class does not exist or is unavailable. + This student or class has teaching, exam or status change records, so it cannot be corrected directly. Use the status change process and verify the history. + This application is not awaiting review by the receiving college. + Enter a review comment when the receiving college rejects the application. + The application status has changed. Refresh and try again. + Your role or the current review stage does not allow this action. + The student status has changed. Review the application again. + The student class has changed. Review the application again. + The discharge record has changed. Reject the application and submit it again. + The resumption target class is unavailable or is not in the original major. + The resumption application has no effective term. Reject it and submit again. + Resumption takes effect upon approval. Select a term that has already started. + A suspension or enlistment record with a start term is missing. Verify the student history before changing the resumption class. + The resumption term cannot be earlier than the suspension or enlistment start term. + The target class is unavailable or does not meet the change requirements. + An inter-college major transfer requires approval from the receiving college first. + This application has no affected term. Reject it and submit it again. + The change takes effect upon approval. Select a term that has already started. + Some grades are unpublished or abnormal. Review the course impact and resolve them before approval. + Some grades have not been submitted. Review the course impact and confirm the original grades should be archived. + Only applications that have not entered review can be withdrawn. + Student status change could not be completed + The approval type or reviewer role is invalid. + Page must be greater than 0, pageSize must be between 1 and 100, and the pagination window cannot exceed 100,000 records. + The waiting threshold must be between 1 and 8,760 hours. + This course is not in your current or published timetable. Refresh the course list and try again. + An exemption request for this course is already under review. + This request has already been processed and cannot be reviewed again. + A deferred exam request for this course is already under review. + Only published grades can be modified. + An adjusted percentage score must be between 0 and 100. + Enter a valid final result when adjusting letter-grade or pass/fail grades. + A modification request for this grade is already under review. + The current status is invalid for this action. + College approval is required first. + Your role or the current stage does not allow this request to be rejected. + The original and substitute courses must be different. + The original course must be in your current or published timetable, or have a failing grade. + The substitute course must have a published passing grade. + No applicable course equivalency rule is configured for this pair, so substitution cannot be requested. + A substitution request for this course is already under review. + The approval request could not be completed diff --git a/src/Jiaowu.Api/Resources/Infrastructure/Localization/SharedResource.resx b/src/Jiaowu.Api/Resources/Infrastructure/Localization/SharedResource.resx index 2ea5266..8e25fba 100644 --- a/src/Jiaowu.Api/Resources/Infrastructure/Localization/SharedResource.resx +++ b/src/Jiaowu.Api/Resources/Infrastructure/Localization/SharedResource.resx @@ -571,4 +571,73 @@ 申请人数已超过教室当前容量,不能批准。 预约日期不能早于今天。 预约日期不在所选学期范围内。 + StudentStatusChanges.Page.Range + StudentStatusChanges.StudentProfile.NotLinked + StudentStatusChanges.Search.MinimumLength + StudentStatusChanges.Discharge.InvalidDate + StudentStatusChanges.Discharge.RetainedStatusRequired + StudentStatusChanges.Discharge.EnlistmentDateMissing + StudentStatusChanges.Discharge.DateBeforeEnlistment + StudentStatusChanges.Application.TermMissing + StudentStatusChanges.Application.CancelReasonLength + StudentStatusChanges.Booking.ChangeNotEffective + StudentStatusChanges.Booking.Unavailable + StudentStatusChanges.Booking.AlreadyProcessed + StudentStatusChanges.Student.Archived + StudentStatusChanges.Application.InvalidForCurrentStatus + StudentStatusChanges.Enlistment.DateRequired + StudentStatusChanges.Enlistment.DateBeforeEnrollment + StudentStatusChanges.Resumption.DischargeDateRequired + StudentStatusChanges.Resumption.DischargeDateMismatch + StudentStatusChanges.Application.EffectiveTermRequired + StudentStatusChanges.Application.FutureTermNotAllowed + StudentStatusChanges.Application.TargetClassInvalid + StudentStatusChanges.Application.DemotionTargetGrade + StudentStatusChanges.Application.AlreadyPending + StudentStatusChanges.Correction.ReasonAndStatusRequired + StudentStatusChanges.Correction.ArchivedStudent + StudentStatusChanges.Correction.RecordChanged + StudentStatusChanges.Correction.NoChanges + StudentStatusChanges.Correction.TargetClassUnavailable + StudentStatusChanges.Correction.HasRelatedRecords + StudentStatusChanges.Review.NotAtReceivingCollege + StudentStatusChanges.Review.ReceivingCollegeCommentRequired + StudentStatusChanges.Application.StateChanged + StudentStatusChanges.Review.ActionNotAllowed + StudentStatusChanges.Review.StudentStatusChanged + StudentStatusChanges.Review.StudentClassChanged + StudentStatusChanges.Review.DischargeRecordChanged + StudentStatusChanges.Resumption.TargetClassUnavailable + StudentStatusChanges.Resumption.EffectiveTermMissing + StudentStatusChanges.Resumption.FutureTermNotAllowed + StudentStatusChanges.Resumption.HistoryMissing + StudentStatusChanges.Resumption.TermBeforeSuspension + StudentStatusChanges.Review.TargetClassUnavailable + StudentStatusChanges.Review.ReceivingCollegeApprovalRequired + StudentStatusChanges.Review.TermMissing + StudentStatusChanges.Review.FutureTermNotAllowed + StudentStatusChanges.Review.UnpublishedGrades + StudentStatusChanges.Review.UnsubmittedGrades + StudentStatusChanges.Application.WithdrawBeforeReviewOnly + StudentStatusChanges.Errors.Title + Approvals.Workflow.TypeOrRoleInvalid + Approvals.Pagination.Invalid + Approvals.Settings.WaitDurationRange + Approvals.Course.NotInCurrentSchedule + Approvals.Exemption.AlreadyPending + Approvals.Request.AlreadyProcessed + Approvals.DeferredExam.AlreadyPending + Approvals.GradeModification.PublishedOnly + Approvals.GradeModification.ScoreRange + Approvals.GradeModification.FinalResultRequired + Approvals.GradeModification.AlreadyPending + Approvals.GradeModification.InvalidState + Approvals.GradeModification.CollegeApprovalRequired + Approvals.Request.RejectionNotAllowed + Approvals.Substitution.CoursesMustDiffer + Approvals.Substitution.OriginalCourseRequired + Approvals.Substitution.PassingPublishedGradeRequired + Approvals.Substitution.EquivalencyRuleMissing + Approvals.Substitution.AlreadyPending + Approvals.Errors.Title