From 16cbd188fb6ca74645ac85bc63042ba22e74bfec Mon Sep 17 00:00:00 2001 From: biss Date: Tue, 20 Oct 2026 18:21:34 +0800 Subject: [PATCH] =?UTF-8?q?=E8=BE=85=E5=AF=BC=E5=91=98=E6=9D=83=E9=99=90?= =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/AttendanceController.cs | 78 +++-- .../Controllers/BaseDataController.cs | 26 +- .../Controllers/BaseDataExcelController.cs | 6 + .../Controllers/GradesController.cs | 113 ++++--- .../GraduationClearanceController.cs | 11 +- .../Controllers/NotificationsController.cs | 35 +- .../StudentStatusChangesController.cs | 17 +- src/Jiaowu.Api/Controllers/UsersController.cs | 251 +++++++++++++- .../Controllers/WarningsController.cs | 19 +- .../CounselorDataScopeTests.cs | 306 ++++++++++++++++++ web/src/views/CourseGradeStatisticsView.vue | 22 +- web/src/views/UsersView.vue | 154 ++++++++- 12 files changed, 940 insertions(+), 98 deletions(-) create mode 100644 tests/Jiaowu.Api.Tests/CounselorDataScopeTests.cs diff --git a/src/Jiaowu.Api/Controllers/AttendanceController.cs b/src/Jiaowu.Api/Controllers/AttendanceController.cs index 676dec1..7f98634 100644 --- a/src/Jiaowu.Api/Controllers/AttendanceController.cs +++ b/src/Jiaowu.Api/Controllers/AttendanceController.cs @@ -43,6 +43,9 @@ public sealed class AttendanceController( { page = Math.Max(1, page); pageSize = Math.Clamp(pageSize, 10, 50); + var scope = currentUserDataScope.Current; + var counselorOnly = scope.Scope == DataScope.Class && + scope.IsInRole(SystemRoles.Counselor); var tasks = AccessibleTasks().AsNoTracking() .Where(x => x.Status == TeachingTaskStatus.Published || x.Status == TeachingTaskStatus.Closed); @@ -82,14 +85,16 @@ public sealed class AttendanceController( CourseCode = x.Course!.Code, CourseName = x.Course!.Name, StudentCount = db.Students.Count(student => - (student.Status == StudentStatus.Active && + (!counselorOnly || + student.AdministrativeClass!.CounselorUserId == scope.UserId) && + ((student.Status == StudentStatus.Active && x.Classes.Any(assignment => assignment.AdministrativeClassId == student.AdministrativeClassId)) || db.CourseEnrollments.Any(enrollment => enrollment.StudentId == student.Id && enrollment.Status == CourseEnrollmentStatus.Enrolled && - enrollment.CourseSelectionOffering!.TeachingTaskId == x.Id)), + enrollment.CourseSelectionOffering!.TeachingTaskId == x.Id))), SheetCount = db.AttendanceSheets.Count(sheet => sheet.TeachingTaskId == x.Id) }) @@ -110,6 +115,9 @@ public sealed class AttendanceController( { page = Math.Max(1, page); pageSize = Math.Clamp(pageSize, 10, 50); + var scope = currentUserDataScope.Current; + var counselorOnly = scope.Scope == DataScope.Class && + scope.IsInRole(SystemRoles.Counselor); var task = await AccessibleTasks().AsNoTracking() .FirstOrDefaultAsync(x => x.Id == teachingTaskId, cancellationToken); if (task is null) return NotFound(); @@ -143,13 +151,26 @@ public sealed class AttendanceController( x.CheckInEndsAt, x.Notes, x.SubmittedAt, - CheckedInCount = x.Records.Count(r => r.CheckInAt != null), - PresentCount = x.Records.Count(r => r.Status == AttendanceStatus.Present), - AbsentCount = x.Records.Count(r => r.Status == AttendanceStatus.Absent), - LateCount = x.Records.Count(r => r.Status == AttendanceStatus.Late), - LeaveCount = x.Records.Count(r => r.Status == AttendanceStatus.Leave), - ExcusedCount = x.Records.Count(r => r.Status == AttendanceStatus.Excused), - TotalCount = x.Records.Count + CheckedInCount = x.Records.Count(r => + (!counselorOnly || r.Student!.AdministrativeClass!.CounselorUserId == scope.UserId) && + r.CheckInAt != null), + PresentCount = x.Records.Count(r => + (!counselorOnly || r.Student!.AdministrativeClass!.CounselorUserId == scope.UserId) && + r.Status == AttendanceStatus.Present), + AbsentCount = x.Records.Count(r => + (!counselorOnly || r.Student!.AdministrativeClass!.CounselorUserId == scope.UserId) && + r.Status == AttendanceStatus.Absent), + LateCount = x.Records.Count(r => + (!counselorOnly || r.Student!.AdministrativeClass!.CounselorUserId == scope.UserId) && + r.Status == AttendanceStatus.Late), + LeaveCount = x.Records.Count(r => + (!counselorOnly || r.Student!.AdministrativeClass!.CounselorUserId == scope.UserId) && + r.Status == AttendanceStatus.Leave), + ExcusedCount = x.Records.Count(r => + (!counselorOnly || r.Student!.AdministrativeClass!.CounselorUserId == scope.UserId) && + r.Status == AttendanceStatus.Excused), + TotalCount = x.Records.Count(r => + !counselorOnly || r.Student!.AdministrativeClass!.CounselorUserId == scope.UserId) }) .ToListAsync(cancellationToken); return Ok(new PagedResult(sheets, total, page, pageSize)); @@ -164,6 +185,8 @@ public sealed class AttendanceController( var task = await AccessibleTasks().AsNoTracking() .FirstOrDefaultAsync(x => x.Id == request.TeachingTaskId, cancellationToken); if (task is null) return NotFound(); + if (!await CanManageTaskAsync(request.TeachingTaskId, cancellationToken)) + return Forbid(); if (!IsTaskOperable(task)) return ConflictProblem("教学任务已归档,不能新建考勤表。"); @@ -245,6 +268,9 @@ public sealed class AttendanceController( [Authorize(Roles = AttendanceRoles)] public async Task GetSheet(Guid id, CancellationToken cancellationToken) { + var scope = currentUserDataScope.Current; + var counselorOnly = scope.Scope == DataScope.Class && + scope.IsInRole(SystemRoles.Counselor); var sheet = await db.AttendanceSheets.AsNoTracking() .Where(x => x.Id == id) .Select(x => new @@ -268,6 +294,8 @@ public sealed class AttendanceController( CourseCode = x.TeachingTask.Course!.Code, CourseName = x.TeachingTask.Course.Name, Records = x.Records + .Where(r => !counselorOnly || + r.Student!.AdministrativeClass!.CounselorUserId == scope.UserId) .OrderBy(r => r.Student!.StudentNumber) .Select(r => new { @@ -529,6 +557,9 @@ public sealed class AttendanceController( [Authorize(Roles = AttendanceRoles)] public async Task Export(Guid id, CancellationToken cancellationToken) { + var scope = currentUserDataScope.Current; + var counselorOnly = scope.Scope == DataScope.Class && + scope.IsInRole(SystemRoles.Counselor); var sheetData = await db.AttendanceSheets.AsNoTracking() .Where(x => x.Id == id) .Select(x => new @@ -539,6 +570,8 @@ public sealed class AttendanceController( TaskNumber = x.TeachingTask!.TaskNumber, CourseName = x.TeachingTask.Course!.Name, Records = x.Records + .Where(r => !counselorOnly || + r.Student!.AdministrativeClass!.CounselorUserId == scope.UserId) .OrderBy(r => r.Student!.StudentNumber) .Select(r => new { @@ -1203,11 +1236,13 @@ public sealed class AttendanceController( return source.Where(x => x.Course!.CollegeId == scope.RestrictedCollegeId); if (scope.IsInRole(SystemRoles.Counselor)) { - var collegeIds = db.AdministrativeClasses - .Where(c => c.CounselorUserId == scope.UserId) - .Select(c => c.Major!.CollegeId) - .Distinct(); - return source.Where(x => collegeIds.Contains(x.Course!.CollegeId)); + return source.Where(task => + task.Classes.Any(item => + item.AdministrativeClass!.CounselorUserId == scope.UserId) || + db.CourseEnrollments.Any(enrollment => + enrollment.CourseSelectionOffering!.TeachingTaskId == task.Id && + enrollment.Status == CourseEnrollmentStatus.Enrolled && + enrollment.Student!.AdministrativeClass!.CounselorUserId == scope.UserId)); } if (scope.IsInRole(SystemRoles.Teacher)) return source.Where(x => @@ -1399,9 +1434,14 @@ public sealed class AttendanceController( .FirstOrDefaultAsync(cancellationToken); if (course is null) return null; - var enrolledStudents = await TeachingTaskRosterQuery - .ForTask(db, teachingTaskId) - .AsNoTracking() + var scope = currentUserDataScope.Current; + var counselorOnly = scope.Scope == DataScope.Class && + scope.IsInRole(SystemRoles.Counselor); + var roster = TeachingTaskRosterQuery.ForTask(db, teachingTaskId).AsNoTracking(); + if (counselorOnly) + roster = roster.Where(x => + x.AdministrativeClass!.CounselorUserId == scope.UserId); + var enrolledStudents = await roster .Select(x => new AttendanceStatisticsStudentIdentity( x.Id, x.StudentNumber, @@ -1424,7 +1464,9 @@ public sealed class AttendanceController( var records = await db.AttendanceRecords.AsNoTracking() .Where(x => x.AttendanceSheet!.TeachingTaskId == teachingTaskId && - x.AttendanceSheet.Status == AttendanceSheetStatus.Submitted) + x.AttendanceSheet.Status == AttendanceSheetStatus.Submitted && + (!counselorOnly || + x.Student!.AdministrativeClass!.CounselorUserId == scope.UserId)) .Select(x => new AttendanceStatisticsRecord( x.AttendanceSheetId, x.StudentId, diff --git a/src/Jiaowu.Api/Controllers/BaseDataController.cs b/src/Jiaowu.Api/Controllers/BaseDataController.cs index 53937d8..9c9c998 100644 --- a/src/Jiaowu.Api/Controllers/BaseDataController.cs +++ b/src/Jiaowu.Api/Controllers/BaseDataController.cs @@ -272,7 +272,7 @@ public sealed class BaseDataController(AppDbContext db, IAppCache cache, .Take(pageSize.Value) .Select(x => new AdministrativeClassListItem( x.Id, x.Code, x.Name, x.MajorId, x.Major!.Name, - x.Major.College!.Name, x.Grade, x.CounselorUserId, + x.Major.CollegeId, x.Major.College!.Name, x.Grade, x.CounselorUserId, x.CounselorName, x.IsEnabled, x.SortOrder)) .ToListAsync(cancellationToken); return Ok(new PagedResult( @@ -289,6 +289,7 @@ public sealed class BaseDataController(AppDbContext db, IAppCache cache, x.Name, x.MajorId, x.Major!.Name, + x.Major.CollegeId, x.Major.College!.Name, x.Grade, x.CounselorUserId, @@ -336,6 +337,9 @@ public sealed class BaseDataController(AppDbContext db, IAppCache cache, cancellationToken); if (request.CounselorUserId.HasValue && counselorName is null) return ValidationProblem("所选辅导员账号不存在、已停用或没有辅导员角色。"); + if (!await CounselorBelongsToMajorCollegeAsync( + request.CounselorUserId, request.MajorId, cancellationToken)) + return ValidationProblem("辅导员所属学院与行政班所属学院不一致。"); var entity = new AdministrativeClass { @@ -365,6 +369,9 @@ public sealed class BaseDataController(AppDbContext db, IAppCache cache, cancellationToken); if (request.CounselorUserId.HasValue && counselorName is null) return ValidationProblem("所选辅导员账号不存在、已停用或没有辅导员角色。"); + if (!await CounselorBelongsToMajorCollegeAsync( + request.CounselorUserId, request.MajorId, cancellationToken)) + return ValidationProblem("辅导员所属学院与行政班所属学院不一致。"); ApplyCatalog(entity, request); entity.MajorId = request.MajorId; entity.Grade = request.Grade; @@ -771,6 +778,22 @@ public sealed class BaseDataController(AppDbContext db, IAppCache cache, .FirstOrDefaultAsync(cancellationToken); } + private async Task CounselorBelongsToMajorCollegeAsync( + Guid? userId, + Guid majorId, + CancellationToken cancellationToken) + { + if (!userId.HasValue) return true; + var counselorCollegeId = await db.Users.AsNoTracking() + .Where(x => x.Id == userId.Value) + .Select(x => x.CollegeId) + .FirstOrDefaultAsync(cancellationToken); + if (!counselorCollegeId.HasValue) return true; + return await db.Majors.AsNoTracking().AnyAsync( + x => x.Id == majorId && x.CollegeId == counselorCollegeId.Value, + cancellationToken); + } + private static void ApplyCatalog(CatalogEntity entity, CatalogRequest request) { entity.Code = request.Code.Trim(); @@ -866,6 +889,7 @@ public sealed record AdministrativeClassListItem( string Name, Guid MajorId, string MajorName, + Guid CollegeId, string CollegeName, int Grade, Guid? CounselorUserId, diff --git a/src/Jiaowu.Api/Controllers/BaseDataExcelController.cs b/src/Jiaowu.Api/Controllers/BaseDataExcelController.cs index dbf82d9..40f07aa 100644 --- a/src/Jiaowu.Api/Controllers/BaseDataExcelController.cs +++ b/src/Jiaowu.Api/Controllers/BaseDataExcelController.cs @@ -337,6 +337,12 @@ public sealed class BaseDataExcelController(AppDbContext db, IAppCache cache) : if (counselorNumber is not null && !counselors.TryGetValue(counselorNumber, out counselor)) errors.Add($"第 {row.RowNumber} 行:辅导员工号“{counselorNumber}”不存在或已停用。"); + if (counselor?.CollegeId is { } counselorCollegeId && + counselorCollegeId != major.CollegeId) + { + errors.Add($"第 {row.RowNumber} 行:辅导员所属学院与行政班所属学院不一致。"); + continue; + } var entity = existing.GetValueOrDefault(code); if (entity is null) { diff --git a/src/Jiaowu.Api/Controllers/GradesController.cs b/src/Jiaowu.Api/Controllers/GradesController.cs index c741183..cd4bdd6 100644 --- a/src/Jiaowu.Api/Controllers/GradesController.cs +++ b/src/Jiaowu.Api/Controllers/GradesController.cs @@ -61,6 +61,9 @@ public sealed class GradesController( { page = Math.Max(1, page); pageSize = Math.Clamp(pageSize, 10, 50); + var currentScope = currentUserDataScope.Current; + var counselorOnly = currentScope.Scope == DataScope.Class && + currentScope.IsInRole(SystemRoles.Counselor); var source = AccessibleTasks().AsNoTracking() .Where(x => x.Status == TeachingTaskStatus.Published || @@ -144,14 +147,20 @@ public sealed class GradesController( item.SourceType, item.SourceSnapshotAt }), - StudentCount = sheet.Records.Count, + StudentCount = sheet.Records.Count(record => + !counselorOnly || + record.Student!.AdministrativeClass!.CounselorUserId == currentScope.UserId), CompletedCount = sheet.Records.Count(record => - record.IsPassed != null || - record.TotalScore != null || - record.ExamStatus != GradeExamStatus.Normal), + (!counselorOnly || + record.Student!.AdministrativeClass!.CounselorUserId == currentScope.UserId) && + (record.IsPassed != null || + record.TotalScore != null || + record.ExamStatus != GradeExamStatus.Normal)), PassedCount = sheet.Records.Count(record => - record.IsPassed == true || - record.IsPassed == null && record.TotalScore >= 60), + (!counselorOnly || + record.Student!.AdministrativeClass!.CounselorUserId == currentScope.UserId) && + (record.IsPassed == true || + record.IsPassed == null && record.TotalScore >= 60)), sheet.SubmittedAt, sheet.ReviewedAt, sheet.PublishedAt, @@ -284,6 +293,13 @@ public sealed class GradesController( var recordsSource = db.GradeRecords.AsNoTracking() .Where(record => record.GradeSheetId == id); + var currentScope = currentUserDataScope.Current; + if (currentScope.Scope == DataScope.Class && + currentScope.IsInRole(SystemRoles.Counselor)) + { + recordsSource = recordsSource.Where(record => + record.Student!.AdministrativeClass!.CounselorUserId == currentScope.UserId); + } if (studentKeyword is not null) recordsSource = recordsSource.Where(record => record.Student!.StudentNumber.Contains(studentKeyword) || @@ -327,7 +343,7 @@ public sealed class GradesController( .SingleAsync(x => x.Id == sheet.TeachingTaskId, cancellationToken); // Determine if current user is from the course's college - var scope = currentUserDataScope.Current; + var scope = currentScope; var isCourseCollegeReviewer = IsReviewer() && (scope.Scope == DataScope.All || scope.RestrictedCollegeId == sheet.CourseCollegeId); @@ -1230,7 +1246,44 @@ public sealed class GradesController( Guid? classId = null; Guid? majorId = null; Guid? collegeId = null; - if (scope.IsInRole(SystemRoles.Student)) + var visibleClasses = new List<(Guid Id, string Name)>(); + if (scope.Scope == DataScope.College) + { + collegeId = scope.RestrictedCollegeId; + if (collegeId == Guid.Empty || !scope.CanAccessCollege( + await db.Courses.Where(x => x.Id == sheet.CourseId) + .Select(x => x.CollegeId).FirstAsync(cancellationToken))) + return Forbid(); + } + else if (scope.Scope == DataScope.Class && scope.IsInRole(SystemRoles.Counselor)) + { + var allowedClassIds = await db.AdministrativeClasses.AsNoTracking() + .Where(x => x.CounselorUserId == scope.UserId) + .Select(x => x.Id) + .ToListAsync(cancellationToken); + if (allowedClassIds.Count == 0) return Forbid(); + var visibleClassRows = await db.GradeRecords.AsNoTracking() + .Where(x => x.GradeSheetId == id && + allowedClassIds.Contains(x.Student!.AdministrativeClassId)) + .Select(x => new + { + Id = x.Student!.AdministrativeClassId, + x.Student.AdministrativeClass!.Name + }) + .Distinct() + .OrderBy(x => x.Name) + .ToListAsync(cancellationToken); + if (visibleClassRows.Count == 0) return Forbid(); + visibleClasses.AddRange(visibleClassRows.Select(x => (x.Id, x.Name))); + // A counselor sees their classes plus the matching major/college + // benchmarks, never an unrelated class-level statistic. + classId = visibleClassRows.First().Id; + majorId = await db.AdministrativeClasses.Where(x => x.Id == classId) + .Select(x => x.MajorId).FirstAsync(cancellationToken); + collegeId = await db.Majors.Where(x => x.Id == majorId) + .Select(x => x.CollegeId).FirstAsync(cancellationToken); + } + else if (scope.IsInRole(SystemRoles.Student)) { if (sheet.Status != GradeSheetStatus.Published) return NotFound(); @@ -1239,38 +1292,17 @@ public sealed class GradesController( .Select(x => new { x.Student!.AdministrativeClassId, + ClassName = x.Student.AdministrativeClass!.Name, MajorId = x.Student.AdministrativeClass!.MajorId, CollegeId = x.Student.AdministrativeClass.Major!.CollegeId }) .FirstOrDefaultAsync(cancellationToken); if (student is null) return Forbid(); classId = student.AdministrativeClassId; + visibleClasses.Add((student.AdministrativeClassId, student.ClassName)); majorId = student.MajorId; collegeId = student.CollegeId; } - else if (scope.Scope == DataScope.College) - { - collegeId = scope.RestrictedCollegeId; - if (collegeId == Guid.Empty || !scope.CanAccessCollege( - await db.Courses.Where(x => x.Id == sheet.CourseId) - .Select(x => x.CollegeId).FirstAsync(cancellationToken))) - return Forbid(); - } - else if (scope.IsInRole(SystemRoles.Counselor)) - { - var allowedClassIds = await db.AdministrativeClasses.AsNoTracking() - .Where(x => x.CounselorUserId == scope.UserId) - .Select(x => x.Id) - .ToListAsync(cancellationToken); - if (allowedClassIds.Count == 0) return Forbid(); - // A counselor sees their classes plus the matching major/college - // benchmarks, never an unrelated class-level statistic. - classId = allowedClassIds.First(); - majorId = await db.AdministrativeClasses.Where(x => x.Id == classId) - .Select(x => x.MajorId).FirstAsync(cancellationToken); - collegeId = await db.Majors.Where(x => x.Id == majorId) - .Select(x => x.CollegeId).FirstAsync(cancellationToken); - } var cacheKey = AppCacheKeys.CourseGradeStatistics(id); var statistics = await (cache ?? NoOpAppCache.Instance).GetOrCreateAsync(cacheKey, async token => @@ -1313,6 +1345,12 @@ public sealed class GradesController( sheet.CourseName, sheet.CourseCode, sheet.TermName, IsRefreshing = !statistics.Any(), Class = classId.HasValue ? Find(CourseGradeStatisticScope.AdministrativeClass, classId) : null, + Classes = visibleClasses.Select(item => new + { + ClassId = item.Id, + ClassName = item.Name, + Statistics = Find(CourseGradeStatisticScope.AdministrativeClass, item.Id) + }).Where(item => item.Statistics is not null).ToArray(), Major = majorId.HasValue ? Find(CourseGradeStatisticScope.Major, majorId) : null, College = collegeId.HasValue ? Find(CourseGradeStatisticScope.College, collegeId) : null, University = scope.Scope == DataScope.All || scope.IsInRole(SystemRoles.Student) @@ -1329,12 +1367,13 @@ public sealed class GradesController( return source.Where(x => x.Course!.CollegeId == scope.RestrictedCollegeId); if (scope.IsInRole(SystemRoles.Counselor)) { - // Counselor sees grades for courses in their managed classes' college - var collegeIds = db.AdministrativeClasses - .Where(c => c.CounselorUserId == scope.UserId) - .Select(c => c.Major!.CollegeId) - .Distinct(); - return source.Where(x => collegeIds.Contains(x.Course!.CollegeId)); + return source.Where(task => + task.Classes.Any(item => + item.AdministrativeClass!.CounselorUserId == scope.UserId) || + db.CourseEnrollments.Any(enrollment => + enrollment.CourseSelectionOffering!.TeachingTaskId == task.Id && + enrollment.Status == CourseEnrollmentStatus.Enrolled && + enrollment.Student!.AdministrativeClass!.CounselorUserId == scope.UserId)); } if (scope.IsInRole(SystemRoles.Teacher)) return source.Where(x => diff --git a/src/Jiaowu.Api/Controllers/GraduationClearanceController.cs b/src/Jiaowu.Api/Controllers/GraduationClearanceController.cs index 869a7d0..2f93e7a 100644 --- a/src/Jiaowu.Api/Controllers/GraduationClearanceController.cs +++ b/src/Jiaowu.Api/Controllers/GraduationClearanceController.cs @@ -360,13 +360,14 @@ public sealed class GraduationClearanceController( { var scope = currentUserDataScope.Current; var source = db.GraduationClearanceRecords.AsQueryable(); - if (scope.IsInRole(SystemRoles.Counselor)) + if (scope.Scope == DataScope.All) return source; + if (scope.Scope == DataScope.College) + return source.Where(x => + x.Student!.AdministrativeClass!.Major!.CollegeId == scope.RestrictedCollegeId); + if (scope.Scope == DataScope.Class) return source.Where(x => x.Student!.AdministrativeClass!.CounselorUserId == scope.UserId); - if (scope.IsInRole(SystemRoles.CollegeAdmin)) - return source.Where(x => - x.Student!.AdministrativeClass!.Major!.CollegeId == scope.CollegeId); - return source; + return source.Where(_ => false); } private bool CanManage(GraduationClearanceRecord record) diff --git a/src/Jiaowu.Api/Controllers/NotificationsController.cs b/src/Jiaowu.Api/Controllers/NotificationsController.cs index b089c21..8cf47a3 100644 --- a/src/Jiaowu.Api/Controllers/NotificationsController.cs +++ b/src/Jiaowu.Api/Controllers/NotificationsController.cs @@ -158,8 +158,12 @@ public sealed class NotificationsController( return Ok(await BuildAdministratorComposerAsync( scope, collegeId.Value, - MessageAudienceType.College, - $"{college}全院成员", + scope.Scope == DataScope.Class + ? MessageAudienceType.Custom + : MessageAudienceType.College, + scope.Scope == DataScope.Class + ? "所带行政班成员" + : $"{college}全院成员", cancellationToken)); } @@ -382,7 +386,9 @@ public sealed class NotificationsController( scope, collegeId.Value, request, - $"{collegeName}全院成员", + scope.Scope == DataScope.Class + ? "所带行政班成员" + : $"{collegeName}全院成员", cancellationToken); if (result.Error is not null) return result.Error; audienceType = result.AudienceType; @@ -625,6 +631,8 @@ public sealed class NotificationsController( string audienceName, CancellationToken cancellationToken) { + var counselorOnly = scope.Scope == DataScope.Class && + scope.IsInRole(SystemRoles.Counselor); var colleges = await db.Colleges.AsNoTracking() .Where(x => !fixedCollegeId.HasValue || x.Id == fixedCollegeId.Value) .OrderBy(x => x.Code) @@ -633,6 +641,7 @@ public sealed class NotificationsController( var administrativeClasses = await db.AdministrativeClasses.AsNoTracking() .Where(x => x.IsEnabled && + (!counselorOnly || x.CounselorUserId == scope.UserId) && (!fixedCollegeId.HasValue || x.Major!.CollegeId == fixedCollegeId.Value)) .OrderByDescending(x => x.Grade) @@ -649,6 +658,13 @@ public sealed class NotificationsController( var teachingTasks = await db.TeachingTasks.AsNoTracking() .Where(x => x.Status != TeachingTaskStatus.Draft && + (!counselorOnly || + x.Classes.Any(item => + item.AdministrativeClass!.CounselorUserId == scope.UserId) || + db.CourseEnrollments.Any(enrollment => + enrollment.CourseSelectionOffering!.TeachingTaskId == x.Id && + enrollment.Status == CourseEnrollmentStatus.Enrolled && + enrollment.Student!.AdministrativeClass!.CounselorUserId == scope.UserId)) && (!fixedCollegeId.HasValue || x.Course!.CollegeId == fixedCollegeId.Value)) .OrderByDescending(x => x.AcademicTerm!.IsCurrent) @@ -687,6 +703,15 @@ public sealed class NotificationsController( var source = db.Users.AsNoTracking() .Where(x => x.IsEnabled && x.Id != scope.UserId); if (IsSchoolAdministrator(scope)) return source; + if (scope.Scope == DataScope.Class && scope.IsInRole(SystemRoles.Counselor)) + { + return source.Where(user => + db.Students.Any(student => + student.UserId == user.Id && + student.AdministrativeClass!.CounselorUserId == scope.UserId && + (!fixedCollegeId.HasValue || + student.AdministrativeClass.Major!.CollegeId == fixedCollegeId.Value))); + } if (!fixedCollegeId.HasValue) return source.Where(_ => false); var collegeId = fixedCollegeId.Value; return source.Where(user => @@ -781,7 +806,9 @@ public sealed class NotificationsController( if (request.RecipientMode == MessageRecipientMode.Scope) { return new RecipientResolution( - fixedCollegeId.HasValue + scope.Scope == DataScope.Class && scope.IsInRole(SystemRoles.Counselor) + ? MessageAudienceType.Custom + : fixedCollegeId.HasValue ? MessageAudienceType.College : MessageAudienceType.School, defaultAudienceName, diff --git a/src/Jiaowu.Api/Controllers/StudentStatusChangesController.cs b/src/Jiaowu.Api/Controllers/StudentStatusChangesController.cs index d2ecfa3..f718cb3 100644 --- a/src/Jiaowu.Api/Controllers/StudentStatusChangesController.cs +++ b/src/Jiaowu.Api/Controllers/StudentStatusChangesController.cs @@ -202,17 +202,16 @@ public sealed class StudentStatusChangesController( { var scope = currentUserDataScope.Current; var source = db.StudentStatusChanges.AsQueryable(); - if (scope.IsInRole(SystemRoles.Student)) - return source.Where(x => x.Student!.UserId == scope.UserId); - if (scope.IsInRole(SystemRoles.Counselor)) + if (scope.Scope == DataScope.All) return source; + if (scope.Scope == DataScope.College) + return source.Where(x => + x.Student!.AdministrativeClass!.Major!.CollegeId == scope.RestrictedCollegeId); + if (scope.Scope == DataScope.Class) return source.Where(x => x.Student!.AdministrativeClass!.CounselorUserId == scope.UserId); - if (scope.IsInRole(SystemRoles.CollegeAdmin)) - return source.Where(x => - x.Student!.AdministrativeClass!.Major!.CollegeId == scope.CollegeId); - if (scope.IsInRole(SystemRoles.AcademicAdmin) || - scope.IsInRole(SystemRoles.SuperAdmin)) return source; - return source.Where(_ => false); + return scope.IsInRole(SystemRoles.Student) + ? source.Where(x => x.Student!.UserId == scope.UserId) + : source.Where(_ => false); } private static bool CanReviewCurrentStage( diff --git a/src/Jiaowu.Api/Controllers/UsersController.cs b/src/Jiaowu.Api/Controllers/UsersController.cs index fd54cc8..73a509c 100644 --- a/src/Jiaowu.Api/Controllers/UsersController.cs +++ b/src/Jiaowu.Api/Controllers/UsersController.cs @@ -3,6 +3,7 @@ using System.Security.Claims; using Jiaowu.Api.Contracts; using Jiaowu.Api.Domain.Academic; using Jiaowu.Api.Domain.Identity; +using Jiaowu.Api.Infrastructure.Caching; using Jiaowu.Api.Infrastructure.Persistence; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; @@ -18,7 +19,8 @@ namespace Jiaowu.Api.Controllers; public sealed class UsersController( AppDbContext db, UserManager userManager, - RoleManager roleManager) : ControllerBase + RoleManager roleManager, + IAppCache cache) : ControllerBase { [HttpGet] public async Task>> GetUsers( @@ -105,6 +107,9 @@ public sealed class UsersController( .Select(x => x.RoleName) .OrderBy(x => x) .ToArray()); + var counselorClassesByUser = await LoadCounselorClassesByUserAsync( + userIds, + cancellationToken); var items = users.Select(user => new UserListItem( user.Id, @@ -115,7 +120,10 @@ public sealed class UsersController( user.IsEnabled, user.LastLoginAt, user.CreatedAt, - rolesByUser.GetValueOrDefault(user.Id, Array.Empty()))) + rolesByUser.GetValueOrDefault(user.Id, Array.Empty()), + counselorClassesByUser.GetValueOrDefault( + user.Id, + Array.Empty()))) .ToArray(); return Ok(new PagedResult(items, total, page, pageSize)); } @@ -176,7 +184,8 @@ public sealed class UsersController( reader.IsDBNull(4) ? null : reader.GetGuid(4), Convert.ToBoolean(reader.GetValue(5)), reader.IsDBNull(6) ? null : reader.GetDateTime(6), - reader.GetDateTime(7), Array.Empty())); + reader.GetDateTime(7), Array.Empty(), + Array.Empty())); } } @@ -197,9 +206,15 @@ public sealed class UsersController( roles.Add(roleReader.GetString(1)); } } + var counselorClassesByUser = await LoadCounselorClassesByUserAsync( + users.Select(x => x.Id).ToArray(), + cancellationToken); var items = users.Select(user => user with { - Roles = rolesByUser.GetValueOrDefault(user.Id, []).OrderBy(x => x).ToArray() + Roles = rolesByUser.GetValueOrDefault(user.Id, []).OrderBy(x => x).ToArray(), + CounselorClasses = counselorClassesByUser.GetValueOrDefault( + user.Id, + Array.Empty()) }).ToArray(); return new PagedResult(items, total, page, pageSize); } @@ -228,6 +243,73 @@ public sealed class UsersController( .Select(x => new { x.Name, x.Description, x.DataScope }) .ToListAsync(cancellationToken)); + [HttpGet("counselor-class-options")] + public async Task>> GetCounselorClassOptions( + Guid collegeId, + string? keyword = null, + int page = 1, + int pageSize = 50, + CancellationToken cancellationToken = default) + { + if (page < 1 || pageSize is < 1 or > 100) + return ValidationProblem("页码必须大于 0,且每页条数应在 1 至 100 之间。"); + + var source = db.AdministrativeClasses.AsNoTracking() + .Where(x => x.IsEnabled && x.Major!.CollegeId == collegeId); + if (!string.IsNullOrWhiteSpace(keyword)) + { + keyword = keyword.Trim(); + source = source.Where(x => + x.Code.Contains(keyword) || + x.Name.Contains(keyword) || + x.Major!.Name.Contains(keyword)); + } + + var total = await source.CountAsync(cancellationToken); + var items = await source + .OrderByDescending(x => x.Grade) + .ThenBy(x => x.Code) + .Skip((page - 1) * pageSize) + .Take(pageSize) + .Select(x => new CounselorClassOption( + x.Id, + x.Code, + x.Name, + x.Grade, + x.Major!.Name, + x.Major.CollegeId, + x.Major.College!.Name, + x.CounselorUserId, + x.CounselorName)) + .ToListAsync(cancellationToken); + return Ok(new PagedResult(items, total, page, pageSize)); + } + + [HttpGet("{id:guid}/counselor-classes")] + public async Task GetCounselorClasses( + Guid id, + CancellationToken cancellationToken) + { + if (!await db.Users.AsNoTracking().AnyAsync(x => x.Id == id, cancellationToken)) + return NotFound(); + + return Ok(await db.AdministrativeClasses.AsNoTracking() + .Where(x => x.CounselorUserId == id) + .OrderByDescending(x => x.Grade) + .ThenBy(x => x.Code) + .Select(x => new + { + x.Id, + x.Code, + x.Name, + x.Grade, + CollegeId = x.Major!.CollegeId, + CollegeName = x.Major.College!.Name, + MajorName = x.Major.Name + }) + .ToListAsync(cancellationToken)); + } + [HttpPost] public async Task Create( CreateUserRequest request, @@ -237,6 +319,13 @@ public sealed class UsersController( var invalidRoles = ValidateRoles(roles); if (invalidRoles is not null) return invalidRoles; var staffNumber = Normalize(request.StaffNumber); + var counselorClasses = await ResolveCounselorClassesAsync( + roles, + request.CollegeId, + request.CounselorClassIds, + null, + cancellationToken); + if (counselorClasses.Error is not null) return counselorClasses.Error; return await db.ExecuteInRetriableTransactionAsync( async transaction => { @@ -265,8 +354,15 @@ public sealed class UsersController( profiles.Teacher.UserId = user.Id; if (profiles.Student is not null) profiles.Student.UserId = user.Id; + ApplyCounselorAssignments( + user, + roles, + request.CounselorClassIds, + counselorClasses.Classes, + []); await db.SaveChangesAsync(cancellationToken); await transaction.CommitAsync(cancellationToken); + await cache.RemoveByTagAsync(AppCacheTags.BaseData, cancellationToken); return CreatedAtAction( nameof(GetUsers), new { id = user.Id }, @@ -299,6 +395,13 @@ public sealed class UsersController( var invalidRoles = ValidateRoles(roles); if (invalidRoles is not null) return invalidRoles; var staffNumber = Normalize(request.StaffNumber); + var counselorClasses = await ResolveCounselorClassesAsync( + roles, + request.CollegeId, + request.CounselorClassIds, + id, + cancellationToken); + if (counselorClasses.Error is not null) return counselorClasses.Error; return await db.ExecuteInRetriableTransactionAsync( async transaction => { @@ -344,6 +447,9 @@ public sealed class UsersController( var linkedStudents = await db.Students .Where(x => x.UserId == id) .ToListAsync(); + var linkedClasses = await db.AdministrativeClasses + .Where(x => x.CounselorUserId == id) + .ToListAsync(cancellationToken); if (!roles.Contains( SystemRoles.Teacher, StringComparer.OrdinalIgnoreCase)) @@ -358,8 +464,15 @@ public sealed class UsersController( profiles.Teacher.UserId = id; if (profiles.Student is not null) profiles.Student.UserId = id; + ApplyCounselorAssignments( + user, + roles, + request.CounselorClassIds, + counselorClasses.Classes, + linkedClasses); await db.SaveChangesAsync(cancellationToken); await transaction.CommitAsync(cancellationToken); + await cache.RemoveByTagAsync(AppCacheTags.BaseData, cancellationToken); return NoContent(); }, cancellationToken); @@ -416,6 +529,116 @@ public sealed class UsersController( return (teacher, student, null); } + private async Task>> + LoadCounselorClassesByUserAsync( + IReadOnlyCollection userIds, + CancellationToken cancellationToken) + { + if (userIds.Count == 0) + return new Dictionary>(); + + var rows = await db.AdministrativeClasses.AsNoTracking() + .Where(x => x.CounselorUserId.HasValue && + userIds.Contains(x.CounselorUserId.Value)) + .OrderByDescending(x => x.Grade) + .ThenBy(x => x.Code) + .Select(x => new + { + UserId = x.CounselorUserId!.Value, + Item = new CounselorClassSummary(x.Id, x.Code, x.Name, x.Grade) + }) + .ToListAsync(cancellationToken); + return rows + .GroupBy(x => x.UserId) + .ToDictionary( + group => group.Key, + group => (IReadOnlyCollection)group + .Select(x => x.Item) + .ToArray()); + } + + private async Task<(List Classes, ActionResult? Error)> + ResolveCounselorClassesAsync( + IReadOnlyCollection roles, + Guid? collegeId, + IReadOnlyCollection? requestedClassIds, + Guid? currentUserId, + CancellationToken cancellationToken) + { + var hasCounselorRole = roles.Contains( + SystemRoles.Counselor, + StringComparer.OrdinalIgnoreCase); + if (requestedClassIds is null && (!hasCounselorRole || !currentUserId.HasValue)) + return ([], null); + + var classIds = requestedClassIds is null + ? await db.AdministrativeClasses.AsNoTracking() + .Where(x => x.CounselorUserId == currentUserId) + .Select(x => x.Id) + .ToArrayAsync(cancellationToken) + : requestedClassIds.Distinct().ToArray(); + if (!hasCounselorRole && classIds.Length > 0) + return ([], ValidationProblem("只有辅导员角色可以绑定所带行政班。")); + if (classIds.Length == 0) return ([], null); + + var classes = await db.AdministrativeClasses + .Include(x => x.Major) + .Where(x => classIds.Contains(x.Id)) + .ToListAsync(cancellationToken); + if (classes.Count != classIds.Length) + return ([], ValidationProblem("所选行政班中包含不存在的记录。")); + if (collegeId.HasValue && classes.Any(x => x.Major!.CollegeId != collegeId.Value)) + return ([], ValidationProblem("辅导员只能绑定所属学院的行政班。")); + + var occupied = classes + .Where(x => x.CounselorUserId.HasValue && + x.CounselorUserId != currentUserId) + .Select(x => x.Name) + .OrderBy(x => x) + .ToArray(); + if (occupied.Length > 0) + return ([], ConflictProblem( + $"以下行政班已绑定其他辅导员:{string.Join("、", occupied)}。请先在行政班管理中完成交接。")); + + return (classes, null); + } + + private static void ApplyCounselorAssignments( + ApplicationUser user, + IReadOnlyCollection roles, + IReadOnlyCollection? requestedClassIds, + IReadOnlyCollection requestedClasses, + IReadOnlyCollection currentlyLinkedClasses) + { + var hasCounselorRole = roles.Contains( + SystemRoles.Counselor, + StringComparer.OrdinalIgnoreCase); + if (!hasCounselorRole) + { + foreach (var administrativeClass in currentlyLinkedClasses) + { + administrativeClass.CounselorUserId = null; + administrativeClass.CounselorName = null; + } + return; + } + + // A null value keeps existing assignments for backwards-compatible API clients. + if (requestedClassIds is null) return; + var selectedIds = requestedClassIds.ToHashSet(); + foreach (var administrativeClass in currentlyLinkedClasses + .Where(x => !selectedIds.Contains(x.Id))) + { + administrativeClass.CounselorUserId = null; + administrativeClass.CounselorName = null; + } + foreach (var administrativeClass in requestedClasses) + { + administrativeClass.CounselorUserId = user.Id; + administrativeClass.CounselorName = user.DisplayName; + } + } + private ActionResult IdentityValidationProblem(IdentityResult result) { foreach (var error in result.Errors) @@ -441,7 +664,8 @@ public sealed record CreateUserRequest( [Required, MinLength(8), MaxLength(100)] string Password, [MaxLength(30)] string? StaffNumber, Guid? CollegeId, - [MinLength(1)] string[] Roles); + [MinLength(1)] string[] Roles, + Guid[]? CounselorClassIds = null); public sealed record SetUserStatusRequest(bool IsEnabled); public sealed record UserListItem( @@ -453,8 +677,21 @@ public sealed record UserListItem( bool IsEnabled, DateTime? LastLoginAt, DateTime CreatedAt, - IReadOnlyCollection Roles); + IReadOnlyCollection Roles, + IReadOnlyCollection CounselorClasses); +public sealed record CounselorClassSummary(Guid Id, string Code, string Name, int Grade); +public sealed record CounselorClassOption( + Guid Id, + string Code, + string Name, + int Grade, + string MajorName, + Guid CollegeId, + string CollegeName, + Guid? CounselorUserId, + string? CounselorName); public sealed record SetRolesRequest( [MaxLength(30)] string? StaffNumber, Guid? CollegeId, - [MinLength(1)] string[] Roles); + [MinLength(1)] string[] Roles, + Guid[]? CounselorClassIds = null); diff --git a/src/Jiaowu.Api/Controllers/WarningsController.cs b/src/Jiaowu.Api/Controllers/WarningsController.cs index c317ffe..635f562 100644 --- a/src/Jiaowu.Api/Controllers/WarningsController.cs +++ b/src/Jiaowu.Api/Controllers/WarningsController.cs @@ -151,13 +151,20 @@ public sealed class WarningsController(AppDbContext db, ICurrentUserDataScope sc return BadRequest("预警记录游标无效。"); var q = db.WarningRecords.AsNoTracking().AsQueryable(); - if (scope.Current.Scope == DataScope.College || scope.Current.IsInRole(SystemRoles.Counselor)) + if (scope.Current.Scope == DataScope.College) { - var classIds = await db.AdministrativeClasses.Where(c => c.CounselorUserId == scope.Current.UserId).Select(c => c.Id).ToListAsync(ct); - if (classIds.Count > 0) - q = q.WhereIn(classIds, x => x.Student!.AdministrativeClassId); - else if (scope.Current.RestrictedCollegeId.HasValue) - q = q.Where(x => x.Student!.AdministrativeClass!.Major!.CollegeId == scope.Current.RestrictedCollegeId); + q = q.Where(x => + x.Student!.AdministrativeClass!.Major!.CollegeId == + scope.Current.RestrictedCollegeId); + } + else if (scope.Current.Scope == DataScope.Class) + { + q = q.Where(x => + x.Student!.AdministrativeClass!.CounselorUserId == scope.Current.UserId); + } + else if (scope.Current.Scope != DataScope.All) + { + q = q.Where(_ => false); } if (academicTermId.HasValue) q = q.Where(x => x.AcademicTermId == academicTermId); if (type.HasValue) q = q.Where(x => x.Type == type); diff --git a/tests/Jiaowu.Api.Tests/CounselorDataScopeTests.cs b/tests/Jiaowu.Api.Tests/CounselorDataScopeTests.cs new file mode 100644 index 0000000..097d843 --- /dev/null +++ b/tests/Jiaowu.Api.Tests/CounselorDataScopeTests.cs @@ -0,0 +1,306 @@ +using System.Text.Json; +using Jiaowu.Api.Contracts; +using Jiaowu.Api.Controllers; +using Jiaowu.Api.Domain.Academic; +using Jiaowu.Api.Domain.Identity; +using Jiaowu.Api.Infrastructure.Auth; +using Jiaowu.Api.Infrastructure.Persistence; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; + +namespace Jiaowu.Api.Tests; + +public sealed class CounselorDataScopeTests +{ + [Fact] + public async Task Counselor_message_scope_contains_only_managed_class_students() + { + await using var fixture = await CounselorFixture.CreateAsync(); + var controller = new NotificationsController(fixture.Db, fixture.Scope); + + var result = await controller.Send( + new SendMessageRequest("班级通知", "仅发送给所带行政班。"), + CancellationToken.None); + + Assert.IsType(result); + var notification = Assert.Single(await fixture.Db.Notifications.ToListAsync()); + Assert.Equal(fixture.ManagedStudentUser.Id, notification.UserId); + Assert.Equal(MessageAudienceType.Custom, + (await fixture.Db.MessageDispatches.SingleAsync()).AudienceType); + } + + [Fact] + public async Task Counselor_attendance_access_excludes_unmanaged_tasks_and_students() + { + await using var fixture = await CounselorFixture.CreateAsync(); + var controller = new AttendanceController(fixture.Db, fixture.Scope); + + var tasksResult = Assert.IsType(await controller.GetMyTasks( + fixture.Term.Id, null, 1, 20, CancellationToken.None)); + var tasks = Assert.IsType>(tasksResult.Value); + Assert.Equal(1, tasks.Total); + + var inaccessible = await controller.GetSheets( + fixture.UnmanagedTask.Id, null, null, null, 1, 20, CancellationToken.None); + Assert.IsType(inaccessible); + + var sheetResult = Assert.IsType(await controller.GetSheet( + fixture.AttendanceSheet.Id, CancellationToken.None)); + var json = JsonSerializer.Serialize(sheetResult.Value); + Assert.Contains(fixture.ManagedStudent.StudentNumber, json); + Assert.DoesNotContain(fixture.UnmanagedStudent.StudentNumber, json); + + var createResult = await controller.CreateSheet( + new AttendanceSheetRequest( + fixture.ManagedTask.Id, + "越权创建", + DateTime.UtcNow, + null, + AttendanceCheckInMethod.Manual, + null, + null, + null, + null), + CancellationToken.None); + Assert.IsType(createResult); + } + + [Fact] + public async Task Counselor_grade_access_excludes_unmanaged_tasks_and_students() + { + await using var fixture = await CounselorFixture.CreateAsync(); + var controller = new GradesController(fixture.Db, fixture.Scope); + + var sheetsResult = Assert.IsType(await controller.GetSheets( + fixture.Term.Id, null, page: 1, pageSize: 20, + cancellationToken: CancellationToken.None)); + var sheets = Assert.IsType>(sheetsResult.Value); + Assert.Equal(1, sheets.Total); + + var sheetResult = Assert.IsType(await controller.GetSheet( + fixture.GradeSheet.Id, cancellationToken: CancellationToken.None)); + var json = JsonSerializer.Serialize(sheetResult.Value); + Assert.Contains(fixture.ManagedStudent.StudentNumber, json); + Assert.DoesNotContain(fixture.UnmanagedStudent.StudentNumber, json); + } + + [Fact] + public async Task Counselor_course_statistics_contains_every_managed_class_in_sheet() + { + await using var fixture = await CounselorFixture.CreateAsync(); + var classes = await fixture.Db.AdministrativeClasses + .OrderBy(x => x.Code) + .ToListAsync(); + foreach (var administrativeClass in classes) + { + administrativeClass.CounselorUserId = fixture.Scope.Current.UserId; + administrativeClass.CounselorName = fixture.Scope.Current.DisplayName; + } + + fixture.Db.CourseGradeStatistics.AddRange(classes.Select((administrativeClass, index) => + new CourseGradeStatistic + { + CourseId = fixture.ManagedTask.CourseId, + AcademicTermId = fixture.Term.Id, + Scope = CourseGradeStatisticScope.AdministrativeClass, + ScopeEntityId = administrativeClass.Id, + StudentCount = 1, + PassedCount = index == 0 ? 1 : 0, + Below60Count = index == 0 ? 0 : 1, + From90To100Count = index == 0 ? 1 : 0, + HighestScore = index == 0 ? 90 : 50, + AverageScore = index == 0 ? 90 : 50, + LowestScore = index == 0 ? 90 : 50, + PassRate = index == 0 ? 100 : 0, + CalculatedAt = DateTime.UtcNow + })); + await fixture.Db.SaveChangesAsync(); + + var controller = new GradesController(fixture.Db, fixture.Scope); + var result = Assert.IsType(await controller.GetCourseStatistics( + fixture.GradeSheet.Id, CancellationToken.None)); + using var document = JsonDocument.Parse(JsonSerializer.Serialize(result.Value)); + var visibleClasses = document.RootElement.GetProperty("Classes"); + + Assert.Equal(2, visibleClasses.GetArrayLength()); + Assert.Contains(visibleClasses.EnumerateArray(), item => + item.GetProperty("ClassName").GetString() == "所带班级"); + Assert.Contains(visibleClasses.EnumerateArray(), item => + item.GetProperty("ClassName").GetString() == "其他班级"); + } + + private sealed class CounselorScope : ICurrentUserDataScope + { + public CounselorScope(Guid userId, Guid collegeId) + { + Current = new CurrentUserScope( + userId, + "测试辅导员", + collegeId, + DataScope.Class, + new HashSet([SystemRoles.Counselor])); + } + + public CurrentUserScope Current { get; } + } + + private sealed class CounselorFixture : IAsyncDisposable + { + private readonly SqliteConnection connection; + + private CounselorFixture( + SqliteConnection connection, + AppDbContext db, + ApplicationUser counselor, + ApplicationUser managedStudentUser, + Student managedStudent, + Student unmanagedStudent, + AcademicTerm term, + TeachingTask managedTask, + TeachingTask unmanagedTask, + AttendanceSheet attendanceSheet, + GradeSheet gradeSheet, + Guid collegeId) + { + this.connection = connection; + Db = db; + ManagedStudentUser = managedStudentUser; + ManagedStudent = managedStudent; + UnmanagedStudent = unmanagedStudent; + Term = term; + ManagedTask = managedTask; + UnmanagedTask = unmanagedTask; + AttendanceSheet = attendanceSheet; + GradeSheet = gradeSheet; + Scope = new CounselorScope(counselor.Id, collegeId); + } + + public AppDbContext Db { get; } + public ApplicationUser ManagedStudentUser { get; } + public Student ManagedStudent { get; } + public Student UnmanagedStudent { get; } + public AcademicTerm Term { get; } + public TeachingTask ManagedTask { get; } + public TeachingTask UnmanagedTask { get; } + public AttendanceSheet AttendanceSheet { get; } + public GradeSheet GradeSheet { get; } + public CounselorScope Scope { get; } + + public static async Task CreateAsync() + { + var connection = new SqliteConnection("Data Source=:memory:"); + await connection.OpenAsync(); + var db = new AppDbContext(new DbContextOptionsBuilder() + .UseSqlite(connection).Options); + await db.Database.EnsureCreatedAsync(); + + var college = new College { Code = "C01", Name = "测试学院" }; + var major = new Major + { + Code = "M01", Name = "测试专业", CollegeId = college.Id, + DegreeType = "本科", SchoolingYears = 4 + }; + var counselor = User("counselor", "辅导员", college.Id); + var managedStudentUser = User("student1", "所带学生", college.Id); + var unmanagedStudentUser = User("student2", "其他学生", college.Id); + var managedClass = new AdministrativeClass + { + Code = "CL01", Name = "所带班级", MajorId = major.Id, Grade = 2026, + CounselorUserId = counselor.Id, CounselorName = counselor.DisplayName + }; + var unmanagedClass = new AdministrativeClass + { + Code = "CL02", Name = "其他班级", MajorId = major.Id, Grade = 2026 + }; + var managedStudent = Student("20260001", "所带学生", managedClass.Id, + managedStudentUser.Id); + var unmanagedStudent = Student("20260002", "其他学生", unmanagedClass.Id, + unmanagedStudentUser.Id); + var term = new AcademicTerm + { + Code = "2026-A", Name = "2026 秋季", AcademicYear = "2026-2027", + Season = TermSeason.Autumn, StartDate = new DateOnly(2026, 9, 1), + EndDate = new DateOnly(2027, 1, 20), IsCurrent = true + }; + var course = new Course + { + Code = "COURSE-1", Name = "测试课程", CollegeId = college.Id, + Credits = 2, TotalHours = 32, LectureHours = 32, PracticeHours = 0, + Nature = CourseNature.MajorRequired, + AssessmentMethod = AssessmentMethod.Examination + }; + var managedTask = Task("TASK-1", "混合教学班", term.Id, course.Id); + managedTask.Classes.Add(new TeachingTaskClass + { TeachingTaskId = managedTask.Id, AdministrativeClassId = managedClass.Id }); + managedTask.Classes.Add(new TeachingTaskClass + { TeachingTaskId = managedTask.Id, AdministrativeClassId = unmanagedClass.Id }); + var unmanagedTask = Task("TASK-2", "无关教学班", term.Id, course.Id); + unmanagedTask.Classes.Add(new TeachingTaskClass + { TeachingTaskId = unmanagedTask.Id, AdministrativeClassId = unmanagedClass.Id }); + var attendanceSheet = new AttendanceSheet + { + TeachingTaskId = managedTask.Id, + Name = "第一周点名", + AttendanceDate = new DateTime(2026, 9, 1), + Status = AttendanceSheetStatus.Submitted, + Records = + [ + new AttendanceRecord { StudentId = managedStudent.Id, Status = AttendanceStatus.Present }, + new AttendanceRecord { StudentId = unmanagedStudent.Id, Status = AttendanceStatus.Absent } + ] + }; + var gradeSheet = new GradeSheet + { + TeachingTaskId = managedTask.Id, + Status = GradeSheetStatus.Published, + Records = + [ + new GradeRecord { StudentId = managedStudent.Id, TotalScore = 90, IsPassed = true }, + new GradeRecord { StudentId = unmanagedStudent.Id, TotalScore = 50, IsPassed = false } + ] + }; + + db.AddRange(college, term); + db.Users.AddRange(counselor, managedStudentUser, unmanagedStudentUser); + await db.SaveChangesAsync(); + db.AddRange(major, course); + await db.SaveChangesAsync(); + db.AddRange(managedClass, unmanagedClass); + await db.SaveChangesAsync(); + db.AddRange(managedStudent, unmanagedStudent, managedTask, unmanagedTask); + await db.SaveChangesAsync(); + db.AddRange(attendanceSheet, gradeSheet); + await db.SaveChangesAsync(); + db.ChangeTracker.Clear(); + + return new CounselorFixture(connection, db, counselor, managedStudentUser, + managedStudent, unmanagedStudent, term, managedTask, unmanagedTask, + attendanceSheet, gradeSheet, college.Id); + } + + private static ApplicationUser User(string name, string displayName, Guid collegeId) => new() + { + Id = Guid.NewGuid(), UserName = name, NormalizedUserName = name.ToUpperInvariant(), + DisplayName = displayName, CollegeId = collegeId, IsEnabled = true + }; + + private static Student Student(string number, string name, Guid classId, Guid userId) => new() + { + StudentNumber = number, Name = name, AdministrativeClassId = classId, + EnrollmentYear = 2026, EnrollmentDate = new DateOnly(2026, 9, 1), UserId = userId + }; + + private static TeachingTask Task(string number, string name, Guid termId, Guid courseId) => new() + { + TaskNumber = number, Name = name, AcademicTermId = termId, CourseId = courseId, + Capacity = 100, Status = TeachingTaskStatus.Published + }; + + public async ValueTask DisposeAsync() + { + await Db.DisposeAsync(); + await connection.DisposeAsync(); + } + } +} diff --git a/web/src/views/CourseGradeStatisticsView.vue b/web/src/views/CourseGradeStatisticsView.vue index 309cd0a..cd4798c 100644 --- a/web/src/views/CourseGradeStatisticsView.vue +++ b/web/src/views/CourseGradeStatisticsView.vue @@ -29,12 +29,22 @@ const comparisonChartElement = ref() let chart: echarts.ECharts | undefined let comparisonChart: echarts.ECharts | undefined -const rows = computed(() => [ - { key: 'class', label: '本班', caption: '同班同学', value: report.value?.class }, - { key: 'major', label: '本专业', caption: '专业学生', value: report.value?.major }, - { key: 'college', label: '本学院', caption: '学院学生', value: report.value?.college }, - { key: 'university', label: '本校', caption: '全校学生', value: report.value?.university }, -].filter(item => item.value)) +const rows = computed(() => { + const classRows = report.value?.classes?.length + ? report.value.classes.map((item: any) => ({ + key: `class-${item.classId}`, + label: item.className, + caption: '该行政班学生', + value: item.statistics, + })) + : [{ key: 'class', label: '本班', caption: '同班同学', value: report.value?.class }] + return [ + ...classRows, + { key: 'major', label: '本专业', caption: '专业学生', value: report.value?.major }, + { key: 'college', label: '本学院', caption: '学院学生', value: report.value?.college }, + { key: 'university', label: '本校', caption: '全校学生', value: report.value?.university }, + ].filter(item => item.value) +}) const selectedRow = computed(() => rows.value.find(item => item.key === activeScope.value) ?? rows.value[0]) const selectedDistribution = computed(() => selectedRow.value?.value.distribution ?? []) diff --git a/web/src/views/UsersView.vue b/web/src/views/UsersView.vue index edb65eb..877bfdb 100644 --- a/web/src/views/UsersView.vue +++ b/web/src/views/UsersView.vue @@ -9,13 +9,21 @@ import { downloadApiFile, importExcel } from '../api/excel' interface UserRow { id: string; userName: string; displayName: string; staffNumber?: string collegeId?: string; roles: string[]; isEnabled: boolean; lastLoginAt?: string + counselorClasses: Array<{ id: string; code: string; name: string; grade: number }> } type DataScope = 'Self' | 'Class' | 'College' | 'All' interface Role { name: string; description: string; dataScope: DataScope } +interface AdministrativeClassOption { + id: string; code: string; name: string; grade: number; majorName: string + collegeId?: string; collegeName: string; counselorUserId?: string; counselorName?: string +} const users = ref([]) const roles = ref([]) const colleges = ref([]) +const administrativeClasses = ref([]) +const selectedCounselorClasses = ref([]) +const classOptionsLoading = ref(false) const loading = ref(false) const importing = ref(false) const fileInput = ref() @@ -27,6 +35,7 @@ const passwordUser = ref(null) const editingRoles = ref([]) const editingStaffNumber = ref('') const editingCollegeId = ref() +const editingCounselorClassIds = ref([]) const keyword = ref('') const roleFilter = ref() const collegeFilter = ref() @@ -39,7 +48,10 @@ const passwordForm = reactive({ newPassword: '', confirmPassword: '' }) const form = reactive({ userName: '', displayName: '', password: '', staffNumber: '', collegeId: undefined as string | undefined, roles: [] as string[], + counselorClassIds: [] as string[], }) +const isCreatingCounselor = computed(() => form.roles.includes('Counselor')) +const isEditingCounselor = computed(() => editingRoles.value.includes('Counselor')) const scopePriority: Record = { Self: 0, Class: 1, @@ -138,16 +150,64 @@ async function handleImport(event: Event) { function openCreate() { Object.assign(form, { userName: '', displayName: '', password: '', staffNumber: '', - collegeId: undefined, roles: [], + collegeId: undefined, roles: [], counselorClassIds: [], }) dialogVisible.value = true } +async function fetchClassOptions(collegeId: string | undefined, keyword = '') { + if (!collegeId) return [] + const response = await http.get('/users/counselor-class-options', { + params: { collegeId, keyword: keyword.trim() || undefined, page: 1, pageSize: 100 }, + }) + return response.data.items as AdministrativeClassOption[] +} + +async function loadCreateClassOptions(keyword = '') { + classOptionsLoading.value = true + try { + administrativeClasses.value = await fetchClassOptions(form.collegeId, keyword) + } catch (error) { + ElMessage.error(apiErrorMessage(error)) + } finally { + classOptionsLoading.value = false + } +} + +async function loadEditClassOptions(keyword = '') { + classOptionsLoading.value = true + try { + const options = await fetchClassOptions(editingCollegeId.value, keyword) + administrativeClasses.value = [ + ...selectedCounselorClasses.value, + ...options.filter(item => !selectedCounselorClasses.value.some(selected => selected.id === item.id)), + ] + } catch (error) { + ElMessage.error(apiErrorMessage(error)) + } finally { + classOptionsLoading.value = false + } +} + +function changeCreateCollege() { + form.counselorClassIds = [] + administrativeClasses.value = [] + void loadCreateClassOptions() +} + +function changeEditCollege() { + editingCounselorClassIds.value = [] + selectedCounselorClasses.value = [] + administrativeClasses.value = [] + void loadEditClassOptions() +} + async function create() { try { await http.post('/users', form) ElMessage.success('账号已创建') dialogVisible.value = false + administrativeClasses.value = [] await load() } catch (error) { ElMessage.error(apiErrorMessage(error)) @@ -164,12 +224,33 @@ async function setStatus(row: any) { } } -function openRoleEditor(row: any) { +async function openRoleEditor(row: any) { editingUser.value = row editingRoles.value = [...row.roles] editingStaffNumber.value = row.staffNumber ?? '' editingCollegeId.value = row.collegeId + editingCounselorClassIds.value = [] + selectedCounselorClasses.value = [] + administrativeClasses.value = [] roleDialogVisible.value = true + try { + const [assignments, options] = await Promise.all([ + http.get(`/users/${row.id}/counselor-classes`), + fetchClassOptions(row.collegeId), + ]) + selectedCounselorClasses.value = assignments.data.map((item: AdministrativeClassOption) => ({ + ...item, + counselorUserId: row.id, + counselorName: row.displayName, + })) + editingCounselorClassIds.value = selectedCounselorClasses.value.map(item => item.id) + administrativeClasses.value = [ + ...selectedCounselorClasses.value, + ...options.filter(item => !selectedCounselorClasses.value.some(selected => selected.id === item.id)), + ] + } catch (error) { + ElMessage.error(apiErrorMessage(error)) + } } async function saveRoles() { @@ -179,9 +260,11 @@ async function saveRoles() { staffNumber: editingStaffNumber.value, collegeId: editingCollegeId.value, roles: editingRoles.value, + counselorClassIds: isEditingCounselor.value ? editingCounselorClassIds.value : [], }) ElMessage.success('角色与数据范围已更新') roleDialogVisible.value = false + administrativeClasses.value = [] await load() } catch (error) { ElMessage.error(apiErrorMessage(error)) @@ -280,6 +363,21 @@ onMounted(load) {{ role }} + + + @@ -322,7 +420,7 @@ onMounted(load) - + @@ -331,6 +429,29 @@ onMounted(load) + + + + + 学院仅表示组织归属,辅导员的数据权限严格来自这里选择的行政班。 +