已完成“考试安排与考场管理”模块:
考试计划草稿、场次配置与正式发布。 教学班、考试时间、考场、监考教师关联。 自动校验考场容量。 阻止考场、监考教师和学生考试时间冲突。 管理员查看考生名单。 教师查看个人监考安排。 学生查看已发布考试日程。 SQLite 增量升级和 MySQL 正式迁移。
This commit is contained in:
@@ -0,0 +1,307 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Jiaowu.Api.Domain.Academic;
|
||||
using Jiaowu.Api.Domain.Identity;
|
||||
using Jiaowu.Api.Infrastructure.Auth;
|
||||
using Jiaowu.Api.Infrastructure.Persistence;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Jiaowu.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
[Route("api/exams")]
|
||||
public sealed class ExamsController(
|
||||
AppDbContext db,
|
||||
ICurrentUserDataScope currentUserDataScope) : ControllerBase
|
||||
{
|
||||
private const string Managers =
|
||||
SystemRoles.SuperAdmin + "," + SystemRoles.AcademicAdmin;
|
||||
|
||||
[HttpGet("plans")]
|
||||
public async Task<ActionResult> GetPlans(
|
||||
Guid? academicTermId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var source = db.ExamPlans.AsNoTracking().AsQueryable();
|
||||
if (academicTermId.HasValue)
|
||||
source = source.Where(x => x.AcademicTermId == academicTermId);
|
||||
if (!IsManager())
|
||||
source = source.Where(x => x.Status == ExamPlanStatus.Published);
|
||||
return Ok(await source.OrderByDescending(x => x.AcademicTerm!.StartDate)
|
||||
.ThenByDescending(x => x.CreatedAt)
|
||||
.Select(x => new
|
||||
{
|
||||
x.Id, x.Name, x.AcademicTermId, TermName = x.AcademicTerm!.Name,
|
||||
x.Status, SessionCount = x.Sessions.Count, x.Notes, x.PublishedAt
|
||||
}).ToListAsync(cancellationToken));
|
||||
}
|
||||
|
||||
[HttpPost("plans")]
|
||||
[Authorize(Roles = Managers)]
|
||||
public async Task<ActionResult> CreatePlan(
|
||||
ExamPlanRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (!await db.AcademicTerms.AnyAsync(
|
||||
x => x.Id == request.AcademicTermId && x.IsEnabled,
|
||||
cancellationToken))
|
||||
return ValidationProblem("所选学期不存在或已停用。");
|
||||
var plan = new ExamPlan
|
||||
{
|
||||
AcademicTermId = request.AcademicTermId,
|
||||
Name = request.Name.Trim(),
|
||||
Notes = Normalize(request.Notes)
|
||||
};
|
||||
db.ExamPlans.Add(plan);
|
||||
return await SaveAsync(plan.Id, true, cancellationToken);
|
||||
}
|
||||
|
||||
[HttpGet("plans/{id:guid}")]
|
||||
public async Task<ActionResult> GetPlan(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
var manager = IsManager();
|
||||
var plan = await db.ExamPlans.AsNoTracking()
|
||||
.Where(x => x.Id == id && (manager || x.Status == ExamPlanStatus.Published))
|
||||
.Select(x => new
|
||||
{
|
||||
x.Id, x.Name, x.AcademicTermId, TermName = x.AcademicTerm!.Name,
|
||||
x.Status, x.Notes, x.PublishedAt,
|
||||
Sessions = x.Sessions.OrderBy(item => item.StartsAt).Select(item => new
|
||||
{
|
||||
item.Id, item.TeachingTaskId, item.TeachingTask!.TaskNumber,
|
||||
TaskName = item.TeachingTask.Name,
|
||||
CourseCode = item.TeachingTask.Course!.Code,
|
||||
CourseName = item.TeachingTask.Course.Name,
|
||||
item.ClassroomId, ClassroomName = item.Classroom!.Name,
|
||||
BuildingName = item.Classroom.Building!.Name,
|
||||
ClassroomCapacity = item.Classroom.Capacity,
|
||||
item.StartsAt, item.EndsAt, item.Notes,
|
||||
InvigilatorIds = item.Invigilators.Select(i => i.TeacherId),
|
||||
InvigilatorNames = item.Invigilators.Select(i => i.Teacher!.Name),
|
||||
StudentCount = db.CourseEnrollments.Count(e =>
|
||||
e.Status == CourseEnrollmentStatus.Enrolled &&
|
||||
e.CourseSelectionOffering!.TeachingTaskId == item.TeachingTaskId)
|
||||
})
|
||||
}).FirstOrDefaultAsync(cancellationToken);
|
||||
return plan is null ? NotFound() : Ok(plan);
|
||||
}
|
||||
|
||||
[HttpPost("plans/{planId:guid}/sessions")]
|
||||
[Authorize(Roles = Managers)]
|
||||
public async Task<ActionResult> CreateSession(
|
||||
Guid planId,
|
||||
ExamSessionRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var plan = await db.ExamPlans.FindAsync([planId], cancellationToken);
|
||||
if (plan is null) return NotFound();
|
||||
if (plan.Status != ExamPlanStatus.Draft)
|
||||
return ConflictProblem("已发布的考试计划不能调整场次。");
|
||||
var validation = await ValidateSessionAsync(plan, null, request, cancellationToken);
|
||||
if (validation is not null) return validation;
|
||||
var session = new ExamSession
|
||||
{
|
||||
ExamPlanId = planId,
|
||||
TeachingTaskId = request.TeachingTaskId,
|
||||
ClassroomId = request.ClassroomId,
|
||||
StartsAt = request.StartsAt.ToUniversalTime(),
|
||||
EndsAt = request.EndsAt.ToUniversalTime(),
|
||||
Notes = Normalize(request.Notes),
|
||||
Invigilators = request.InvigilatorIds.Distinct().Select(id =>
|
||||
new ExamSessionInvigilator { TeacherId = id }).ToList()
|
||||
};
|
||||
db.ExamSessions.Add(session);
|
||||
return await SaveAsync(session.Id, true, cancellationToken);
|
||||
}
|
||||
|
||||
[HttpDelete("plans/{planId:guid}/sessions/{id:guid}")]
|
||||
[Authorize(Roles = Managers)]
|
||||
public async Task<ActionResult> DeleteSession(
|
||||
Guid planId,
|
||||
Guid id,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var session = await db.ExamSessions.Include(x => x.ExamPlan)
|
||||
.FirstOrDefaultAsync(x => x.Id == id && x.ExamPlanId == planId, cancellationToken);
|
||||
if (session is null) return NotFound();
|
||||
if (session.ExamPlan!.Status != ExamPlanStatus.Draft)
|
||||
return ConflictProblem("已发布的考试计划不能调整场次。");
|
||||
db.ExamSessions.Remove(session);
|
||||
return await SaveAsync(id, false, cancellationToken);
|
||||
}
|
||||
|
||||
[HttpPost("plans/{id:guid}/publish")]
|
||||
[Authorize(Roles = Managers)]
|
||||
public async Task<ActionResult> Publish(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
var plan = await db.ExamPlans.Include(x => x.Sessions)
|
||||
.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
|
||||
if (plan is null) return NotFound();
|
||||
if (plan.Status != ExamPlanStatus.Draft)
|
||||
return ConflictProblem("只有草稿考试计划可以发布。");
|
||||
if (plan.Sessions.Count == 0)
|
||||
return ConflictProblem("至少安排一个考试场次后才能发布。");
|
||||
plan.Status = ExamPlanStatus.Published;
|
||||
plan.PublishedAt = DateTime.UtcNow;
|
||||
return await SaveAsync(id, false, cancellationToken);
|
||||
}
|
||||
|
||||
[HttpGet("sessions/{id:guid}/roster")]
|
||||
[Authorize(Roles = Managers)]
|
||||
public async Task<ActionResult> GetRoster(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
var session = await db.ExamSessions.AsNoTracking()
|
||||
.Where(x => x.Id == id)
|
||||
.Select(x => new
|
||||
{
|
||||
x.Id, x.TeachingTaskId, x.TeachingTask!.TaskNumber,
|
||||
CourseName = x.TeachingTask.Course!.Name,
|
||||
ClassroomName = x.Classroom!.Name, x.StartsAt,
|
||||
Students = db.CourseEnrollments
|
||||
.Where(e => e.Status == CourseEnrollmentStatus.Enrolled &&
|
||||
e.CourseSelectionOffering!.TeachingTaskId == x.TeachingTaskId)
|
||||
.OrderBy(e => e.Student!.StudentNumber)
|
||||
.Select(e => new
|
||||
{
|
||||
e.StudentId, e.Student!.StudentNumber, e.Student.Name,
|
||||
ClassName = e.Student.AdministrativeClass!.Name
|
||||
}).ToList()
|
||||
}).FirstOrDefaultAsync(cancellationToken);
|
||||
return session is null ? NotFound() : Ok(session);
|
||||
}
|
||||
|
||||
[HttpGet("my-schedule")]
|
||||
public async Task<ActionResult> GetMySchedule(CancellationToken cancellationToken)
|
||||
{
|
||||
var scope = currentUserDataScope.Current;
|
||||
if (scope.IsInRole(SystemRoles.Student))
|
||||
{
|
||||
var studentId = await db.Students.Where(x => x.UserId == scope.UserId)
|
||||
.Select(x => (Guid?)x.Id).FirstOrDefaultAsync(cancellationToken);
|
||||
if (!studentId.HasValue) return ConflictProblem("当前账号未关联学生档案。");
|
||||
return Ok(await db.ExamSessions.AsNoTracking()
|
||||
.Where(x => x.ExamPlan!.Status == ExamPlanStatus.Published &&
|
||||
db.CourseEnrollments.Any(e => e.StudentId == studentId &&
|
||||
e.Status == CourseEnrollmentStatus.Enrolled &&
|
||||
e.CourseSelectionOffering!.TeachingTaskId == x.TeachingTaskId))
|
||||
.OrderBy(x => x.StartsAt).Select(x => new
|
||||
{
|
||||
x.Id, PlanName = x.ExamPlan!.Name, x.StartsAt, x.EndsAt,
|
||||
x.TeachingTask!.TaskNumber, CourseCode = x.TeachingTask.Course!.Code,
|
||||
CourseName = x.TeachingTask.Course.Name,
|
||||
ClassroomName = x.Classroom!.Name,
|
||||
BuildingName = x.Classroom.Building!.Name,
|
||||
InvigilatorNames = x.Invigilators.Select(i => i.Teacher!.Name)
|
||||
})
|
||||
.ToListAsync(cancellationToken));
|
||||
}
|
||||
if (scope.IsInRole(SystemRoles.Teacher))
|
||||
{
|
||||
return Ok(await db.ExamSessions.AsNoTracking()
|
||||
.Where(x => x.ExamPlan!.Status == ExamPlanStatus.Published &&
|
||||
x.Invigilators.Any(i => i.Teacher!.UserId == scope.UserId))
|
||||
.OrderBy(x => x.StartsAt).Select(x => new
|
||||
{
|
||||
x.Id, PlanName = x.ExamPlan!.Name, x.StartsAt, x.EndsAt,
|
||||
x.TeachingTask!.TaskNumber, CourseCode = x.TeachingTask.Course!.Code,
|
||||
CourseName = x.TeachingTask.Course.Name,
|
||||
ClassroomName = x.Classroom!.Name,
|
||||
BuildingName = x.Classroom.Building!.Name,
|
||||
InvigilatorNames = x.Invigilators.Select(i => i.Teacher!.Name),
|
||||
StudentCount = db.CourseEnrollments.Count(e =>
|
||||
e.Status == CourseEnrollmentStatus.Enrolled &&
|
||||
e.CourseSelectionOffering!.TeachingTaskId == x.TeachingTaskId)
|
||||
})
|
||||
.ToListAsync(cancellationToken));
|
||||
}
|
||||
return Ok(Array.Empty<object>());
|
||||
}
|
||||
|
||||
private async Task<ActionResult?> ValidateSessionAsync(
|
||||
ExamPlan plan,
|
||||
Guid? currentId,
|
||||
ExamSessionRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var starts = request.StartsAt.ToUniversalTime();
|
||||
var ends = request.EndsAt.ToUniversalTime();
|
||||
if (starts >= ends) return ValidationProblem("考试开始时间必须早于结束时间。");
|
||||
var task = await db.TeachingTasks.AsNoTracking()
|
||||
.FirstOrDefaultAsync(x => x.Id == request.TeachingTaskId, cancellationToken);
|
||||
if (task is null || task.AcademicTermId != plan.AcademicTermId)
|
||||
return ValidationProblem("教学班与考试计划必须属于同一学期。");
|
||||
var room = await db.Classrooms.AsNoTracking()
|
||||
.FirstOrDefaultAsync(x => x.Id == request.ClassroomId && x.IsEnabled, cancellationToken);
|
||||
if (room is null) return ValidationProblem("所选考场不存在或已停用。");
|
||||
var studentCount = await db.CourseEnrollments.CountAsync(x =>
|
||||
x.Status == CourseEnrollmentStatus.Enrolled &&
|
||||
x.CourseSelectionOffering!.TeachingTaskId == task.Id, cancellationToken);
|
||||
if (studentCount > room.Capacity)
|
||||
return ConflictProblem($"考场容量不足:需容纳 {studentCount} 人,教室容量为 {room.Capacity}。");
|
||||
var teacherIds = request.InvigilatorIds.Distinct().ToArray();
|
||||
if (teacherIds.Length == 0) return ValidationProblem("至少安排一名监考教师。");
|
||||
if (await db.Teachers.CountAsync(x => teacherIds.Contains(x.Id) &&
|
||||
x.Status == TeacherStatus.Active, cancellationToken) != teacherIds.Length)
|
||||
return ValidationProblem("存在无效监考教师。");
|
||||
|
||||
var overlaps = db.ExamSessions.Where(x => x.ExamPlanId == plan.Id &&
|
||||
x.Id != currentId && x.StartsAt < ends && starts < x.EndsAt);
|
||||
if (await overlaps.AnyAsync(x => x.ClassroomId == room.Id, cancellationToken))
|
||||
return ConflictProblem("该时段考场已被占用。");
|
||||
if (await overlaps.AnyAsync(x =>
|
||||
x.Invigilators.Any(i => teacherIds.Contains(i.TeacherId)), cancellationToken))
|
||||
return ConflictProblem("监考教师在该时段已有考试任务。");
|
||||
var studentIds = db.CourseEnrollments.Where(x =>
|
||||
x.Status == CourseEnrollmentStatus.Enrolled &&
|
||||
x.CourseSelectionOffering!.TeachingTaskId == task.Id)
|
||||
.Select(x => x.StudentId);
|
||||
if (await overlaps.AnyAsync(other =>
|
||||
db.CourseEnrollments.Any(e =>
|
||||
studentIds.Contains(e.StudentId) &&
|
||||
e.Status == CourseEnrollmentStatus.Enrolled &&
|
||||
e.CourseSelectionOffering!.TeachingTaskId == other.TeachingTaskId),
|
||||
cancellationToken))
|
||||
return ConflictProblem("存在学生考试时间冲突。");
|
||||
return null;
|
||||
}
|
||||
|
||||
private bool IsManager() =>
|
||||
currentUserDataScope.Current.IsInRole(SystemRoles.SuperAdmin) ||
|
||||
currentUserDataScope.Current.IsInRole(SystemRoles.AcademicAdmin);
|
||||
|
||||
private async Task<ActionResult> SaveAsync(Guid id, bool created, CancellationToken token)
|
||||
{
|
||||
try
|
||||
{
|
||||
await db.SaveChangesAsync(token);
|
||||
return created ? Created(string.Empty, new { id }) : NoContent();
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
return ConflictProblem("考试场次重复,或关联数据已发生变化。");
|
||||
}
|
||||
}
|
||||
|
||||
private ActionResult ConflictProblem(string detail) => Conflict(new ProblemDetails
|
||||
{
|
||||
Title = "无法完成考务操作", Detail = detail,
|
||||
Status = StatusCodes.Status409Conflict
|
||||
});
|
||||
private static string? Normalize(string? value) =>
|
||||
string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
}
|
||||
|
||||
public sealed record ExamPlanRequest(
|
||||
Guid AcademicTermId,
|
||||
[Required, MaxLength(120)] string Name,
|
||||
[MaxLength(500)] string? Notes);
|
||||
|
||||
public sealed record ExamSessionRequest(
|
||||
Guid TeachingTaskId,
|
||||
Guid ClassroomId,
|
||||
DateTime StartsAt,
|
||||
DateTime EndsAt,
|
||||
IReadOnlyCollection<Guid> InvigilatorIds,
|
||||
[MaxLength(500)] string? Notes);
|
||||
Reference in New Issue
Block a user