已完成“选课候补与自动递补”完整流程。

学生端:满员后可加入/取消候补,展示候补顺位和当前候补人数。
自动递补:退课释放名额后,按候补时间顺序重新校验学籍、范围、学分及时间冲突;不合格者自动失效并继续下一位。
管理端:教学班显示候补人数,名单抽屉提供候补队列及移出操作。
状态通知:递补成功、资格失效、批次关闭、管理员移出均会通知学生。
并发安全:退课和递补放在 Serializable 事务中执行。
数据库:已补充 SQLite 开发迁移和 MySQL 正式迁移。
This commit is contained in:
biss committed 2026-07-26 15:39:50 +08:00
1 parent 65eed820a7
commit 56b13b3adb
12 files changed
+1166 -42

No files matched your search

+1 -1
View File
@@ -2,7 +2,7 @@
面向普通高校的教务管理系统。后端使用 ASP.NET Core 10、EF Core 10,前端使用 Vue 3、TypeScript 和 Element Plus。 面向普通高校的教务管理系统。后端使用 ASP.NET Core 10、EF Core 10,前端使用 Vue 3、TypeScript 和 Element Plus。
当前已实现系统登录与角色权限、基础数据、用户管理、教师档案、学生档案、课程库、培养方案、教学任务、排课课表、学生选课、成绩管理、考试考场、学籍异动、毕业审核、学位授予、毕业离校和首页统计。人员及课程列表支持组合筛选、服务端分页和完整增删改查;培养方案支持课程模块、专业年级版本、复制新版本、发布与旧版本归档,已发布版本可继续维护名称、学分说明和课程结构,适用专业、入学年级及版本号保持锁定;教学任务支持学期课程开设、多教师、合班、容量校验、发布与结课,公共课由校级教务负责、专业必修/专业选修/实践课下放课程所属学院管理,并支持教师按学期申报授课科目、学院审核授课资格、公共课按若干行政班合并教学班,以及在审核通过的教师池中随机均衡分配后批量生成草稿;排课支持学期作息维护、单双周与周次节次、课程可用时间、校区/教学楼/指定教室约束、不占用教室课程、教室容量、教师/行政班/教室冲突校验、自动生成、手工微调和版本化发布;选课支持批次时间窗、投放范围、容量与学分上限、重复课程与课表冲突校验、退课截止时间和实时教学班名单;成绩管理支持分项比例、批量录入、特殊考试状态、自动总评与绩点、教师提交、学院审核、校级发布和学生成绩单;考试管理支持考试计划、场次、考场容量、监考教师、考生名单以及考场/监考/学生时间冲突校验;学籍异动支持休学、复学、退学申请,辅导员、学院、学校三级顺序审核,学生撤回,以及最终审批后自动同步学籍状态;毕业审核按入学年级匹配已发布培养方案,以正式成绩计算总学分、必修通过和未解决不及格课程,支持学院范围查看、人工复核、校级锁定发布和学生结果查询;学位授予以已发布毕业资格为来源,按正式成绩加权平均绩点生成规则结论,支持学院人工复核、校级发布锁定和学生结果查询;毕业离校支持自定义事项与责任部门,按校级、学院、辅导员角色分工办理,强制数据范围校验,学生进度查询,以及必办事项全部完成后的批次锁定。 当前已实现系统登录与角色权限、基础数据、用户管理、教师档案、学生档案、课程库、培养方案、教学任务、排课课表、学生选课、成绩管理、考试考场、学籍异动、毕业审核、学位授予、毕业离校和首页统计。人员及课程列表支持组合筛选、服务端分页和完整增删改查;培养方案支持课程模块、专业年级版本、复制新版本、发布与旧版本归档,已发布版本可继续维护名称、学分说明和课程结构,适用专业、入学年级及版本号保持锁定;教学任务支持学期课程开设、多教师、合班、容量校验、发布与结课,公共课由校级教务负责、专业必修/专业选修/实践课下放课程所属学院管理,并支持教师按学期申报授课科目、学院审核授课资格、公共课按若干行政班合并教学班,以及在审核通过的教师池中随机均衡分配后批量生成草稿;排课支持学期作息维护、单双周与周次节次、课程可用时间、校区/教学楼/指定教室约束、不占用教室课程、教室容量、教师/行政班/教室冲突校验、自动生成、手工微调和版本化发布;选课支持批次时间窗、投放范围、容量与学分上限、重复课程与课表冲突校验、退课截止时间、满员候补、顺位查询、退课后资格复核与自动递补,以及正式名单和候补队列管理;成绩管理支持分项比例、批量录入、特殊考试状态、自动总评与绩点、教师提交、学院审核、校级发布和学生成绩单;考试管理支持考试计划、场次、考场容量、监考教师、考生名单以及考场/监考/学生时间冲突校验;学籍异动支持休学、复学、退学申请,辅导员、学院、学校三级顺序审核,学生撤回,以及最终审批后自动同步学籍状态;毕业审核按入学年级匹配已发布培养方案,以正式成绩计算总学分、必修通过和未解决不及格课程,支持学院范围查看、人工复核、校级锁定发布和学生结果查询;学位授予以已发布毕业资格为来源,按正式成绩加权平均绩点生成规则结论,支持学院人工复核、校级发布锁定和学生结果查询;毕业离校支持自定义事项与责任部门,按校级、学院、辅导员角色分工办理,强制数据范围校验,学生进度查询,以及必办事项全部完成后的批次锁定。
课程库支持下载标准模板后批量导入 `.xlsx`,按课程编码新增或更新,并在整批校验失败时不写入任何课程;授课资格既支持教师申报后审核,也支持学院在本院教师范围内直接分配;学生可在“我的培养方案”中查看本人适用的已发布方案,并按已完成、在读、重修中、未通过、待完成和未修读状态核对课程与学分进度。 课程库支持下载标准模板后批量导入 `.xlsx`,按课程编码新增或更新,并在整批校验失败时不写入任何课程;授课资格既支持教师申报后审核,也支持学院在本院教师范围内直接分配;学生可在“我的培养方案”中查看本人适用的已发布方案,并按已完成、在读、重修中、未通过、待完成和未修读状态核对课程与学分进度。
@@ -153,12 +153,51 @@ public sealed class CourseSelectionsController(
[Authorize(Roles = RoundManagers)] [Authorize(Roles = RoundManagers)]
public async Task<ActionResult> CloseRound(Guid id, CancellationToken cancellationToken) public async Task<ActionResult> CloseRound(Guid id, CancellationToken cancellationToken)
{ {
var round = await db.CourseSelectionRounds.FindAsync([id], cancellationToken); return await db.ExecuteInRetriableTransactionAsync<ActionResult>(
async transaction =>
{
db.ChangeTracker.Clear();
var round = await db.CourseSelectionRounds
.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
if (round is null) return NotFound(); if (round is null) return NotFound();
if (round.Status != CourseSelectionRoundStatus.Open) if (round.Status != CourseSelectionRoundStatus.Open)
return ConflictProblem("只有开放中的选课批次可以关闭。"); return ConflictProblem("只有开放中的选课批次可以关闭。");
var waitlisted = await db.CourseEnrollments
.Include(x => x.Student)
.Include(x => x.CourseSelectionOffering)
.ThenInclude(x => x!.TeachingTask)
.ThenInclude(x => x!.Course)
.Where(x =>
x.CourseSelectionOffering!.CourseSelectionRoundId == id &&
x.Status == CourseEnrollmentStatus.Waitlisted)
.ToListAsync(cancellationToken);
var now = DateTime.UtcNow;
foreach (var enrollment in waitlisted)
{
enrollment.Status = CourseEnrollmentStatus.Expired;
enrollment.WithdrawnAt = now;
if (enrollment.Student!.UserId is Guid userId)
{
db.Notifications.Add(new Notification
{
UserId = userId,
Title = "课程候补已结束",
Content =
$"“{enrollment.CourseSelectionOffering!.TeachingTask!.Course!.Name}”" +
"选课批次已关闭,本次候补未获得名额。",
LinkUrl = "/course-selections"
});
}
}
round.Status = CourseSelectionRoundStatus.Closed; round.Status = CourseSelectionRoundStatus.Closed;
return await SaveAsync(id, false, cancellationToken); await db.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
return Ok(new { ExpiredWaitlistCount = waitlisted.Count });
},
cancellationToken,
IsolationLevel.Serializable);
} }
[HttpGet("rounds/{roundId:guid}/offerings")] [HttpGet("rounds/{roundId:guid}/offerings")]
@@ -193,6 +232,8 @@ public sealed class CourseSelectionsController(
x.Capacity, x.Capacity,
EnrolledCount = x.Enrollments.Count(item => EnrolledCount = x.Enrollments.Count(item =>
item.Status == CourseEnrollmentStatus.Enrolled), item.Status == CourseEnrollmentStatus.Enrolled),
WaitlistedCount = x.Enrollments.Count(item =>
item.Status == CourseEnrollmentStatus.Waitlisted),
x.IsOpenToAll, x.IsOpenToAll,
x.Notes, x.Notes,
x.UpdatedAt x.UpdatedAt
@@ -318,6 +359,36 @@ public sealed class CourseSelectionsController(
x.EnrolledAt x.EnrolledAt
}) })
.ToListAsync(cancellationToken); .ToListAsync(cancellationToken);
var waitlistedRows = await db.CourseEnrollments.AsNoTracking()
.Where(x =>
x.CourseSelectionOfferingId == id &&
x.Status == CourseEnrollmentStatus.Waitlisted)
.OrderBy(x => x.WaitlistedAt)
.ThenBy(x => x.CreatedAt)
.Select(x => new
{
x.Id,
x.StudentId,
x.Student!.StudentNumber,
x.Student.Name,
ClassName = x.Student.AdministrativeClass!.Name,
MajorName = x.Student.AdministrativeClass.Major!.Name,
x.WaitlistedAt
})
.ToListAsync(cancellationToken);
var waitlist = waitlistedRows
.Select((item, index) => new
{
item.Id,
item.StudentId,
item.StudentNumber,
item.Name,
item.ClassName,
item.MajorName,
item.WaitlistedAt,
Position = index + 1
})
.ToList();
return Ok(new return Ok(new
{ {
offering.Id, offering.Id,
@@ -330,6 +401,13 @@ public sealed class CourseSelectionsController(
offering.Capacity, offering.Capacity,
EnrolledCount = students.Count, EnrolledCount = students.Count,
Students = students, Students = students,
WaitlistedCount = waitlist.Count,
Waitlist = waitlist,
CanManageWaitlist =
offering.RoundStatus == CourseSelectionRoundStatus.Open &&
(scope.IsInRole(SystemRoles.SuperAdmin) ||
scope.IsInRole(SystemRoles.AcademicAdmin) ||
scope.IsInRole(SystemRoles.CollegeAdmin)),
CanProxyEnroll = CanProxyEnroll =
CourseSelectionRules.SupportsProxyEnrollment(offering.CourseNature) && CourseSelectionRules.SupportsProxyEnrollment(offering.CourseNature) &&
offering.RoundStatus != CourseSelectionRoundStatus.Draft && offering.RoundStatus != CourseSelectionRoundStatus.Draft &&
@@ -550,19 +628,28 @@ public sealed class CourseSelectionsController(
x.StudentId == student.Id); x.StudentId == student.Id);
if (enrollment is null) if (enrollment is null)
{ {
db.CourseEnrollments.Add(new CourseEnrollment enrollment = new CourseEnrollment
{ {
CourseSelectionOfferingId = id, CourseSelectionOfferingId = id,
StudentId = student.Id, StudentId = student.Id,
EnrolledAt = now EnrolledAt = now
}); };
db.CourseEnrollments.Add(enrollment);
} }
else else
{ {
enrollment.Status = CourseEnrollmentStatus.Enrolled; enrollment.Status = CourseEnrollmentStatus.Enrolled;
enrollment.EnrolledAt = now; enrollment.EnrolledAt = now;
enrollment.WaitlistedAt = null;
enrollment.WithdrawnAt = null; enrollment.WithdrawnAt = null;
} }
await ExpireOtherWaitlistsForCourseAsync(
student.Id,
task.CourseId,
round.AcademicTermId,
enrollment.Id,
now,
cancellationToken);
} }
await db.SaveChangesAsync(cancellationToken); await db.SaveChangesAsync(cancellationToken);
@@ -633,21 +720,30 @@ public sealed class CourseSelectionsController(
.FirstOrDefault(x => x.StudentId == student.Id); .FirstOrDefault(x => x.StudentId == student.Id);
if (enrollment is null) if (enrollment is null)
{ {
db.CourseEnrollments.Add(new CourseEnrollment enrollment = new CourseEnrollment
{ {
CourseSelectionOfferingId = offeringId, CourseSelectionOfferingId = offeringId,
StudentId = student.Id, StudentId = student.Id,
EnrollmentType = EnrollmentType.Retake, EnrollmentType = EnrollmentType.Retake,
EnrolledAt = now EnrolledAt = now
}); };
db.CourseEnrollments.Add(enrollment);
} }
else else
{ {
enrollment.Status = CourseEnrollmentStatus.Enrolled; enrollment.Status = CourseEnrollmentStatus.Enrolled;
enrollment.EnrolledAt = now; enrollment.EnrolledAt = now;
enrollment.WaitlistedAt = null;
enrollment.WithdrawnAt = null; enrollment.WithdrawnAt = null;
enrollment.EnrollmentType = EnrollmentType.Retake; enrollment.EnrollmentType = EnrollmentType.Retake;
} }
await ExpireOtherWaitlistsForCourseAsync(
student.Id,
task.CourseId,
round.AcademicTermId,
enrollment.Id,
now,
cancellationToken);
enrolled++; enrolled++;
} }
@@ -666,7 +762,13 @@ public sealed class CourseSelectionsController(
Guid enrollmentId, Guid enrollmentId,
CancellationToken cancellationToken) CancellationToken cancellationToken)
{ {
return await db.ExecuteInRetriableTransactionAsync<ActionResult>(
async transaction =>
{
db.ChangeTracker.Clear();
var enrollment = await db.CourseEnrollments var enrollment = await db.CourseEnrollments
.Include(x => x.CourseSelectionOffering)
.ThenInclude(x => x!.CourseSelectionRound)
.Include(x => x.CourseSelectionOffering) .Include(x => x.CourseSelectionOffering)
.ThenInclude(x => x!.TeachingTask) .ThenInclude(x => x!.TeachingTask)
.ThenInclude(x => x!.Course) .ThenInclude(x => x!.Course)
@@ -687,7 +789,66 @@ public sealed class CourseSelectionsController(
enrollment.Status = CourseEnrollmentStatus.Withdrawn; enrollment.Status = CourseEnrollmentStatus.Withdrawn;
enrollment.WithdrawnAt = DateTime.UtcNow; enrollment.WithdrawnAt = DateTime.UtcNow;
return await SaveAsync(enrollmentId, false, cancellationToken); await db.SaveChangesAsync(cancellationToken);
var promoted = await PromoteNextWaitlistedAsync(
offering,
cancellationToken);
await db.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
return Ok(new { PromotedStudentId = promoted?.StudentId });
},
cancellationToken,
IsolationLevel.Serializable);
}
[HttpDelete("offerings/{offeringId:guid}/waitlist/{enrollmentId:guid}")]
[Authorize(Roles = OfferingManagers)]
public async Task<ActionResult> AdminCancelWaitlist(
Guid offeringId,
Guid enrollmentId,
CancellationToken cancellationToken)
{
return await db.ExecuteInRetriableTransactionAsync<ActionResult>(
async transaction =>
{
db.ChangeTracker.Clear();
if (!await ScopedOfferings().AnyAsync(
x => x.Id == offeringId,
cancellationToken))
return NotFound();
var enrollment = await db.CourseEnrollments
.Include(x => x.Student)
.Include(x => x.CourseSelectionOffering)
.ThenInclude(x => x!.TeachingTask)
.ThenInclude(x => x!.Course)
.FirstOrDefaultAsync(
x =>
x.Id == enrollmentId &&
x.CourseSelectionOfferingId == offeringId &&
x.Status == CourseEnrollmentStatus.Waitlisted,
cancellationToken);
if (enrollment is null) return NotFound();
enrollment.Status = CourseEnrollmentStatus.Cancelled;
enrollment.WithdrawnAt = DateTime.UtcNow;
if (enrollment.Student!.UserId is Guid userId)
{
db.Notifications.Add(new Notification
{
UserId = userId,
Title = "课程候补已取消",
Content =
$"管理员已将你移出“{enrollment.CourseSelectionOffering!.TeachingTask!.Course!.Name}”" +
"候补队列。",
LinkUrl = "/course-selections"
});
}
await db.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
return NoContent();
},
cancellationToken,
IsolationLevel.Serializable);
} }
[HttpGet("student/options")] [HttpGet("student/options")]
@@ -724,6 +885,8 @@ public sealed class CourseSelectionsController(
x.Capacity, x.Capacity,
x.Enrollments.Count(item => x.Enrollments.Count(item =>
item.Status == CourseEnrollmentStatus.Enrolled), item.Status == CourseEnrollmentStatus.Enrolled),
x.Enrollments.Count(item =>
item.Status == CourseEnrollmentStatus.Waitlisted),
x.IsOpenToAll, x.IsOpenToAll,
x.Enrollments x.Enrollments
.Where(item => item.StudentId == student.Id) .Where(item => item.StudentId == student.Id)
@@ -732,6 +895,8 @@ public sealed class CourseSelectionsController(
x.TeachingTask.SchedulingMode == TeachingTaskSchedulingMode.Flexible, x.TeachingTask.SchedulingMode == TeachingTaskSchedulingMode.Flexible,
db.CourseEnrollments.Any(e => db.CourseEnrollments.Any(e =>
e.StudentId == student.Id && e.StudentId == student.Id &&
(e.Status == CourseEnrollmentStatus.Enrolled ||
e.Status == CourseEnrollmentStatus.Withdrawn) &&
e.CourseSelectionOffering!.TeachingTask!.CourseId == e.CourseSelectionOffering!.TeachingTask!.CourseId ==
x.TeachingTask.CourseId && x.TeachingTask.CourseId &&
e.CourseSelectionOffering.CourseSelectionRound!.AcademicTermId != e.CourseSelectionOffering.CourseSelectionRound!.AcademicTermId !=
@@ -751,9 +916,48 @@ public sealed class CourseSelectionsController(
entry.EndWeek, entry.EndWeek,
entry.WeekPattern, entry.WeekPattern,
entry.Classroom == null ? "不占用教室" : entry.Classroom.Name)) entry.Classroom == null ? "不占用教室" : entry.Classroom.Name))
.ToList())) .ToList(),
null))
.ToListAsync(cancellationToken); .ToListAsync(cancellationToken);
var waitlistedOfferingIds = offerings
.Where(x => x.EnrollmentStatus == CourseEnrollmentStatus.Waitlisted)
.Select(x => x.Id)
.ToArray();
if (waitlistedOfferingIds.Length > 0)
{
var queueRows = await db.CourseEnrollments.AsNoTracking()
.Where(x => x.Status == CourseEnrollmentStatus.Waitlisted)
.WhereIn(waitlistedOfferingIds, x => x.CourseSelectionOfferingId)
.Select(x => new
{
x.CourseSelectionOfferingId,
x.StudentId,
x.WaitlistedAt,
x.CreatedAt
})
.ToListAsync(cancellationToken);
var positions = queueRows
.GroupBy(x => x.CourseSelectionOfferingId)
.SelectMany(group => group
.OrderBy(x => x.WaitlistedAt)
.ThenBy(x => x.CreatedAt)
.Select((item, index) => new
{
item.CourseSelectionOfferingId,
item.StudentId,
Position = index + 1
}))
.Where(x => x.StudentId == student.Id)
.ToDictionary(x => x.CourseSelectionOfferingId, x => x.Position);
offerings = offerings
.Select(x => x with
{
WaitlistPosition = positions.GetValueOrDefault(x.Id)
})
.ToList();
}
return Ok(new return Ok(new
{ {
Round = new Round = new
@@ -816,9 +1020,11 @@ public sealed class CourseSelectionsController(
x.Status, x.Status,
x.EnrollmentType, x.EnrollmentType,
x.EnrolledAt, x.EnrolledAt,
x.WaitlistedAt,
x.WithdrawnAt, x.WithdrawnAt,
CanWithdraw = CanWithdraw =
x.Status == CourseEnrollmentStatus.Enrolled && (x.Status == CourseEnrollmentStatus.Enrolled ||
x.Status == CourseEnrollmentStatus.Waitlisted) &&
x.CourseSelectionOffering.CourseSelectionRound.Status == x.CourseSelectionOffering.CourseSelectionRound.Status ==
CourseSelectionRoundStatus.Open && CourseSelectionRoundStatus.Open &&
DateTime.UtcNow <= DateTime.UtcNow <=
@@ -866,6 +1072,8 @@ public sealed class CourseSelectionsController(
var isRetake = await db.CourseEnrollments.AnyAsync( var isRetake = await db.CourseEnrollments.AnyAsync(
x => x =>
x.StudentId == student.Id && x.StudentId == student.Id &&
(x.Status == CourseEnrollmentStatus.Enrolled ||
x.Status == CourseEnrollmentStatus.Withdrawn) &&
x.CourseSelectionOffering!.TeachingTask!.CourseId == task.CourseId && x.CourseSelectionOffering!.TeachingTask!.CourseId == task.CourseId &&
x.CourseSelectionOffering.CourseSelectionRound!.AcademicTermId != x.CourseSelectionOffering.CourseSelectionRound!.AcademicTermId !=
round.AcademicTermId, round.AcademicTermId,
@@ -884,9 +1092,9 @@ public sealed class CourseSelectionsController(
x.CourseSelectionOfferingId == offering.Id && x.CourseSelectionOfferingId == offering.Id &&
x.Status == CourseEnrollmentStatus.Enrolled, x.Status == CourseEnrollmentStatus.Enrolled,
cancellationToken); cancellationToken);
var effectiveCapacity = isRetake var effectiveCapacity = CourseSelectionRules.EffectiveCapacity(
? CourseSelectionRules.RetakeCapacity(offering.Capacity) offering.Capacity,
: offering.Capacity; isRetake);
if (enrolledCount >= effectiveCapacity) if (enrolledCount >= effectiveCapacity)
return ConflictProblem("该教学班名额已满。"); return ConflictProblem("该教学班名额已满。");
@@ -967,9 +1175,17 @@ public sealed class CourseSelectionsController(
{ {
existing.Status = CourseEnrollmentStatus.Enrolled; existing.Status = CourseEnrollmentStatus.Enrolled;
existing.EnrolledAt = now; existing.EnrolledAt = now;
existing.WaitlistedAt = null;
existing.WithdrawnAt = null; existing.WithdrawnAt = null;
existing.EnrollmentType = isRetake ? EnrollmentType.Retake : EnrollmentType.Normal; existing.EnrollmentType = isRetake ? EnrollmentType.Retake : EnrollmentType.Normal;
} }
await ExpireOtherWaitlistsForCourseAsync(
student.Id,
task.CourseId,
round.AcademicTermId,
existing.Id,
now,
cancellationToken);
await db.SaveChangesAsync(cancellationToken); await db.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken); await transaction.CommitAsync(cancellationToken);
return Created(string.Empty, new { existing.Id, IsRetake = isRetake }); return Created(string.Empty, new { existing.Id, IsRetake = isRetake });
@@ -978,28 +1194,168 @@ public sealed class CourseSelectionsController(
IsolationLevel.Serializable); IsolationLevel.Serializable);
} }
[HttpPost("student/waitlist")]
[Authorize(Roles = SystemRoles.Student)]
public async Task<ActionResult> JoinWaitlist(
StudentEnrollmentRequest request,
CancellationToken cancellationToken)
{
return await db.ExecuteInRetriableTransactionAsync<ActionResult>(
async transaction =>
{
db.ChangeTracker.Clear();
var student = await CurrentStudentAsync(cancellationToken);
if (student is null) return ProfileNotFound();
var offering = await db.CourseSelectionOfferings
.Include(x => x.CourseSelectionRound)
.Include(x => x.TeachingTask)
.ThenInclude(x => x!.Course)
.Include(x => x.TeachingTask)
.ThenInclude(x => x!.Classes)
.FirstOrDefaultAsync(x => x.Id == request.OfferingId, cancellationToken);
if (offering is null) return NotFound();
var round = offering.CourseSelectionRound!;
var now = DateTime.UtcNow;
if (!CourseSelectionRules.IsSelectionOpen(round, now))
return ConflictProblem("当前不在该选课批次的开放时间内。");
var existing = await db.CourseEnrollments.FirstOrDefaultAsync(
x =>
x.CourseSelectionOfferingId == offering.Id &&
x.StudentId == student.Id,
cancellationToken);
if (existing?.Status == CourseEnrollmentStatus.Enrolled)
return ConflictProblem("你已经选择了该教学班。");
if (existing?.Status == CourseEnrollmentStatus.Waitlisted)
return ConflictProblem("你已经在该教学班的候补队列中。");
var eligibility = await EvaluateEnrollmentEligibilityAsync(
student,
offering,
cancellationToken);
if (eligibility.Error is not null)
return ConflictProblem(eligibility.Error);
var sameCourseWaitlistExists = await db.CourseEnrollments.AnyAsync(
x =>
x.StudentId == student.Id &&
x.Status == CourseEnrollmentStatus.Waitlisted &&
x.CourseSelectionOffering!.TeachingTask!.CourseId ==
offering.TeachingTask!.CourseId &&
x.CourseSelectionOffering.CourseSelectionRound!.AcademicTermId ==
round.AcademicTermId,
cancellationToken);
if (sameCourseWaitlistExists)
return ConflictProblem("你已在本学期同一课程的其他教学班候补。");
var enrolledCount = await db.CourseEnrollments.CountAsync(
x =>
x.CourseSelectionOfferingId == offering.Id &&
x.Status == CourseEnrollmentStatus.Enrolled,
cancellationToken);
var effectiveCapacity = CourseSelectionRules.EffectiveCapacity(
offering.Capacity,
eligibility.IsRetake);
if (enrolledCount < effectiveCapacity)
return ConflictProblem("该教学班当前仍有名额,请直接选择课程。");
if (existing is null)
{
existing = new CourseEnrollment
{
CourseSelectionOfferingId = offering.Id,
StudentId = student.Id,
Status = CourseEnrollmentStatus.Waitlisted,
EnrollmentType = eligibility.IsRetake
? EnrollmentType.Retake
: EnrollmentType.Normal,
WaitlistedAt = now
};
db.CourseEnrollments.Add(existing);
}
else
{
existing.Status = CourseEnrollmentStatus.Waitlisted;
existing.EnrollmentType = eligibility.IsRetake
? EnrollmentType.Retake
: EnrollmentType.Normal;
existing.WaitlistedAt = now;
existing.WithdrawnAt = null;
}
await db.SaveChangesAsync(cancellationToken);
var position = await db.CourseEnrollments.CountAsync(
x =>
x.CourseSelectionOfferingId == offering.Id &&
x.Status == CourseEnrollmentStatus.Waitlisted &&
x.WaitlistedAt <= now,
cancellationToken);
await transaction.CommitAsync(cancellationToken);
return Accepted(new
{
existing.Id,
Status = CourseEnrollmentStatus.Waitlisted,
Position = position,
IsRetake = eligibility.IsRetake
});
},
cancellationToken,
IsolationLevel.Serializable);
}
[HttpDelete("student/enrollments/{id:guid}")] [HttpDelete("student/enrollments/{id:guid}")]
[Authorize(Roles = SystemRoles.Student)] [Authorize(Roles = SystemRoles.Student)]
public async Task<ActionResult> Withdraw(Guid id, CancellationToken cancellationToken) public async Task<ActionResult> Withdraw(Guid id, CancellationToken cancellationToken)
{ {
return await db.ExecuteInRetriableTransactionAsync<ActionResult>(
async transaction =>
{
db.ChangeTracker.Clear();
var student = await CurrentStudentAsync(cancellationToken); var student = await CurrentStudentAsync(cancellationToken);
if (student is null) return ProfileNotFound(); if (student is null) return ProfileNotFound();
var enrollment = await db.CourseEnrollments var enrollment = await db.CourseEnrollments
.Include(x => x.CourseSelectionOffering) .Include(x => x.CourseSelectionOffering)
.ThenInclude(x => x!.CourseSelectionRound) .ThenInclude(x => x!.CourseSelectionRound)
.Include(x => x.CourseSelectionOffering)
.ThenInclude(x => x!.TeachingTask)
.ThenInclude(x => x!.Course)
.FirstOrDefaultAsync( .FirstOrDefaultAsync(
x => x.Id == id && x.StudentId == student.Id, x => x.Id == id && x.StudentId == student.Id,
cancellationToken); cancellationToken);
if (enrollment is null) return NotFound(); if (enrollment is null) return NotFound();
if (enrollment.Status != CourseEnrollmentStatus.Enrolled) var wasEnrolled = enrollment.Status == CourseEnrollmentStatus.Enrolled;
return ConflictProblem("该课程已经退选。"); var wasWaitlisted =
enrollment.Status == CourseEnrollmentStatus.Waitlisted;
if (!wasEnrolled && !wasWaitlisted)
return ConflictProblem("该课程已经退选或候补已经结束。");
if (!CourseSelectionRules.CanWithdraw( if (!CourseSelectionRules.CanWithdraw(
enrollment.CourseSelectionOffering!.CourseSelectionRound!, enrollment.CourseSelectionOffering!.CourseSelectionRound!,
DateTime.UtcNow)) DateTime.UtcNow))
return ConflictProblem("当前批次已停止退课。"); return ConflictProblem("当前批次已停止退课和候补调整。");
enrollment.Status = CourseEnrollmentStatus.Withdrawn;
enrollment.Status = wasWaitlisted
? CourseEnrollmentStatus.Cancelled
: CourseEnrollmentStatus.Withdrawn;
enrollment.WithdrawnAt = DateTime.UtcNow; enrollment.WithdrawnAt = DateTime.UtcNow;
return await SaveAsync(id, false, cancellationToken); await db.SaveChangesAsync(cancellationToken);
CourseEnrollment? promoted = null;
if (wasEnrolled)
{
promoted = await PromoteNextWaitlistedAsync(
enrollment.CourseSelectionOffering,
cancellationToken);
await db.SaveChangesAsync(cancellationToken);
}
await transaction.CommitAsync(cancellationToken);
return Ok(new
{
CancelledWaitlist = wasWaitlisted,
PromotedStudentId = promoted?.StudentId
});
},
cancellationToken,
IsolationLevel.Serializable);
} }
[HttpGet("my-offerings")] [HttpGet("my-offerings")]
@@ -1178,6 +1534,214 @@ public sealed class CourseSelectionsController(
.ToListAsync(cancellationToken); .ToListAsync(cancellationToken);
} }
private async Task<EnrollmentEligibility> EvaluateEnrollmentEligibilityAsync(
Student student,
CourseSelectionOffering offering,
CancellationToken cancellationToken)
{
var round = offering.CourseSelectionRound!;
var task = offering.TeachingTask!;
if (student.Status != StudentStatus.Active)
return new(false, "只有在籍学生可以选课或候补。");
if (task.Status != TeachingTaskStatus.Published)
return new(false, "该教学班当前不可选。");
if (!offering.IsOpenToAll &&
!await db.TeachingTaskClasses.AnyAsync(
x =>
x.TeachingTaskId == task.Id &&
x.AdministrativeClassId == student.AdministrativeClassId,
cancellationToken))
return new(false, "你不属于该教学班的选课对象。");
var isRetake = await db.CourseEnrollments.AnyAsync(
x =>
x.StudentId == student.Id &&
(x.Status == CourseEnrollmentStatus.Enrolled ||
x.Status == CourseEnrollmentStatus.Withdrawn) &&
x.CourseSelectionOffering!.TeachingTask!.CourseId == task.CourseId &&
x.CourseSelectionOffering.CourseSelectionRound!.AcademicTermId !=
round.AcademicTermId,
cancellationToken);
if (!isRetake)
{
var duplicateCourse = await db.CourseEnrollments.AnyAsync(
x =>
x.StudentId == student.Id &&
x.Status == CourseEnrollmentStatus.Enrolled &&
x.CourseSelectionOffering!.TeachingTask!.CourseId == task.CourseId &&
x.CourseSelectionOffering.CourseSelectionRound!.AcademicTermId ==
round.AcademicTermId,
cancellationToken);
if (duplicateCourse)
return new(false, "同一学期不能重复选择相同课程。");
}
var selectedCredits = await db.CourseEnrollments
.Where(x =>
x.StudentId == student.Id &&
x.Status == CourseEnrollmentStatus.Enrolled &&
x.CourseSelectionOffering!.CourseSelectionRoundId == round.Id)
.SumAsync(
x => (decimal?)x.CourseSelectionOffering!.TeachingTask!.Course!.Credits,
cancellationToken) ?? 0;
if (selectedCredits + task.Course!.Credits > round.MaxCredits)
{
return new(
isRetake,
$"获得名额后将达到 {selectedCredits + task.Course.Credits:0.#} 学分," +
$"超过本轮 {round.MaxCredits:0.#} 学分上限。");
}
var candidateEntries = await PublishedScheduleEntries(
round.AcademicTermId,
[task.Id],
cancellationToken);
if (CourseSelectionRules.RequiresPublishedSchedule(task.SchedulingMode) &&
candidateEntries.Count == 0)
return new(isRetake, "该教学班尚未发布课表,暂时不能选课或候补。");
var selectedTaskIds = await db.CourseEnrollments.AsNoTracking()
.Where(x =>
x.StudentId == student.Id &&
x.Status == CourseEnrollmentStatus.Enrolled &&
x.CourseSelectionOffering!.CourseSelectionRound!.AcademicTermId ==
round.AcademicTermId)
.Select(x => x.CourseSelectionOffering!.TeachingTaskId)
.Distinct()
.ToArrayAsync(cancellationToken);
var selectedEntries = await PublishedScheduleEntries(
round.AcademicTermId,
selectedTaskIds,
cancellationToken);
if (CourseSelectionRules.HasScheduleConflict(candidateEntries, selectedEntries))
{
if (!isRetake)
return new(false, "该教学班与已选课程的上课时间冲突。");
var overlap = CourseSelectionRules.CalculateScheduleOverlap(
candidateEntries,
selectedEntries);
if (overlap > 50)
{
return new(
true,
$"重修课程时间冲突 {overlap:F0}%,超过 50% 上限。");
}
}
return new(isRetake, null);
}
private async Task<CourseEnrollment?> PromoteNextWaitlistedAsync(
CourseSelectionOffering offering,
CancellationToken cancellationToken)
{
var round = offering.CourseSelectionRound!;
if (!CourseSelectionRules.CanPromoteWaitlist(round, DateTime.UtcNow))
return null;
var waitlist = await db.CourseEnrollments
.Include(x => x.Student)
.ThenInclude(x => x!.AdministrativeClass)
.Where(x =>
x.CourseSelectionOfferingId == offering.Id &&
x.Status == CourseEnrollmentStatus.Waitlisted)
.OrderBy(x => x.WaitlistedAt)
.ThenBy(x => x.CreatedAt)
.ToListAsync(cancellationToken);
if (waitlist.Count == 0) return null;
var enrolledCount = await db.CourseEnrollments.CountAsync(
x =>
x.CourseSelectionOfferingId == offering.Id &&
x.Status == CourseEnrollmentStatus.Enrolled,
cancellationToken);
var now = DateTime.UtcNow;
foreach (var candidate in waitlist)
{
var eligibility = await EvaluateEnrollmentEligibilityAsync(
candidate.Student!,
offering,
cancellationToken);
if (eligibility.Error is not null)
{
candidate.Status = CourseEnrollmentStatus.Expired;
candidate.WithdrawnAt = now;
if (candidate.Student!.UserId is Guid invalidUserId)
{
db.Notifications.Add(new Notification
{
UserId = invalidUserId,
Title = "课程候补已失效",
Content =
$"“{offering.TeachingTask!.Course!.Name}”候补未能递补:" +
eligibility.Error,
LinkUrl = "/course-selections"
});
}
continue;
}
var effectiveCapacity = CourseSelectionRules.EffectiveCapacity(
offering.Capacity,
eligibility.IsRetake);
if (enrolledCount >= effectiveCapacity)
continue;
candidate.Status = CourseEnrollmentStatus.Enrolled;
candidate.EnrollmentType = eligibility.IsRetake
? EnrollmentType.Retake
: EnrollmentType.Normal;
candidate.EnrolledAt = now;
candidate.WithdrawnAt = null;
await ExpireOtherWaitlistsForCourseAsync(
candidate.StudentId,
offering.TeachingTask!.CourseId,
round.AcademicTermId,
candidate.Id,
now,
cancellationToken);
if (candidate.Student!.UserId is Guid userId)
{
db.Notifications.Add(new Notification
{
UserId = userId,
Title = "课程候补递补成功",
Content =
$"“{offering.TeachingTask.Course!.Name}”已释放名额," +
"你已自动进入正式选课名单。",
LinkUrl = "/course-selections"
});
}
return candidate;
}
return null;
}
private async Task ExpireOtherWaitlistsForCourseAsync(
Guid studentId,
Guid courseId,
Guid academicTermId,
Guid retainedEnrollmentId,
DateTime now,
CancellationToken cancellationToken)
{
var otherWaitlists = await db.CourseEnrollments
.Where(x =>
x.Id != retainedEnrollmentId &&
x.StudentId == studentId &&
x.Status == CourseEnrollmentStatus.Waitlisted &&
x.CourseSelectionOffering!.TeachingTask!.CourseId == courseId &&
x.CourseSelectionOffering.CourseSelectionRound!.AcademicTermId ==
academicTermId)
.ToListAsync(cancellationToken);
foreach (var waitlist in otherWaitlists)
{
waitlist.Status = CourseEnrollmentStatus.Expired;
waitlist.WithdrawnAt = now;
}
}
private async Task<ActionResult> SaveAsync( private async Task<ActionResult> SaveAsync(
Guid id, Guid id,
bool created, bool created,
@@ -1207,6 +1771,8 @@ public sealed class CourseSelectionsController(
private static string? Normalize(string? value) => private static string? Normalize(string? value) =>
string.IsNullOrWhiteSpace(value) ? null : value.Trim(); string.IsNullOrWhiteSpace(value) ? null : value.Trim();
private sealed record EnrollmentEligibility(bool IsRetake, string? Error);
} }
public sealed record CourseSelectionRoundRequest( public sealed record CourseSelectionRoundRequest(
@@ -1242,11 +1808,13 @@ public sealed record StudentOfferingDto(
IEnumerable<string> TeacherNames, IEnumerable<string> TeacherNames,
int Capacity, int Capacity,
int EnrolledCount, int EnrolledCount,
int WaitlistedCount,
bool IsOpenToAll, bool IsOpenToAll,
CourseEnrollmentStatus? EnrollmentStatus, CourseEnrollmentStatus? EnrollmentStatus,
bool IsFlexible, bool IsFlexible,
bool IsRetake, bool IsRetake,
IEnumerable<StudentScheduleDto> Schedules); IEnumerable<StudentScheduleDto> Schedules,
int? WaitlistPosition);
public sealed record StudentScheduleDto( public sealed record StudentScheduleDto(
int DayOfWeek, int DayOfWeek,
@@ -38,6 +38,7 @@ public sealed class CourseEnrollment : EntityBase
public CourseEnrollmentStatus Status { get; set; } = CourseEnrollmentStatus.Enrolled; public CourseEnrollmentStatus Status { get; set; } = CourseEnrollmentStatus.Enrolled;
public EnrollmentType EnrollmentType { get; set; } = EnrollmentType.Normal; public EnrollmentType EnrollmentType { get; set; } = EnrollmentType.Normal;
public DateTime EnrolledAt { get; set; } = DateTime.UtcNow; public DateTime EnrolledAt { get; set; } = DateTime.UtcNow;
public DateTime? WaitlistedAt { get; set; }
public DateTime? WithdrawnAt { get; set; } public DateTime? WithdrawnAt { get; set; }
} }
@@ -51,7 +52,10 @@ public enum CourseSelectionRoundStatus
public enum CourseEnrollmentStatus public enum CourseEnrollmentStatus
{ {
Enrolled = 1, Enrolled = 1,
Withdrawn = 2 Withdrawn = 2,
Waitlisted = 3,
Cancelled = 4,
Expired = 5
} }
public enum EnrollmentType public enum EnrollmentType
Loaded 3 of 12 files, more files were not shown because too many files have changed in this diff. Show more