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

学生端:满员后可加入/取消候补,展示候补顺位和当前候补人数。
自动递补:退课释放名额后,按候补时间顺序重新校验学籍、范围、学分及时间冲突;不合格者自动失效并继续下一位。
管理端:教学班显示候补人数,名单抽屉提供候补队列及移出操作。
状态通知:递补成功、资格失效、批次关闭、管理员移出均会通知学生。
并发安全:退课和递补放在 Serializable 事务中执行。
数据库:已补充 SQLite 开发迁移和 MySQL 正式迁移。
This commit is contained in:
2026-07-26 15:39:50 +08:00 Unverified
parent 65eed820a7
commit 56b13b3adb
12 changed files with 1203 additions and 79 deletions
@@ -153,12 +153,51 @@ public sealed class CourseSelectionsController(
[Authorize(Roles = RoundManagers)]
public async Task<ActionResult> CloseRound(Guid id, CancellationToken cancellationToken)
{
var round = await db.CourseSelectionRounds.FindAsync([id], cancellationToken);
if (round is null) return NotFound();
if (round.Status != CourseSelectionRoundStatus.Open)
return ConflictProblem("只有开放中的选课批次可以关闭。");
round.Status = CourseSelectionRoundStatus.Closed;
return await SaveAsync(id, false, 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.Status != CourseSelectionRoundStatus.Open)
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;
await db.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
return Ok(new { ExpiredWaitlistCount = waitlisted.Count });
},
cancellationToken,
IsolationLevel.Serializable);
}
[HttpGet("rounds/{roundId:guid}/offerings")]
@@ -193,6 +232,8 @@ public sealed class CourseSelectionsController(
x.Capacity,
EnrolledCount = x.Enrollments.Count(item =>
item.Status == CourseEnrollmentStatus.Enrolled),
WaitlistedCount = x.Enrollments.Count(item =>
item.Status == CourseEnrollmentStatus.Waitlisted),
x.IsOpenToAll,
x.Notes,
x.UpdatedAt
@@ -318,6 +359,36 @@ public sealed class CourseSelectionsController(
x.EnrolledAt
})
.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
{
offering.Id,
@@ -330,6 +401,13 @@ public sealed class CourseSelectionsController(
offering.Capacity,
EnrolledCount = students.Count,
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 =
CourseSelectionRules.SupportsProxyEnrollment(offering.CourseNature) &&
offering.RoundStatus != CourseSelectionRoundStatus.Draft &&
@@ -550,19 +628,28 @@ public sealed class CourseSelectionsController(
x.StudentId == student.Id);
if (enrollment is null)
{
db.CourseEnrollments.Add(new CourseEnrollment
enrollment = new CourseEnrollment
{
CourseSelectionOfferingId = id,
StudentId = student.Id,
EnrolledAt = now
});
};
db.CourseEnrollments.Add(enrollment);
}
else
{
enrollment.Status = CourseEnrollmentStatus.Enrolled;
enrollment.EnrolledAt = now;
enrollment.WaitlistedAt = null;
enrollment.WithdrawnAt = null;
}
await ExpireOtherWaitlistsForCourseAsync(
student.Id,
task.CourseId,
round.AcademicTermId,
enrollment.Id,
now,
cancellationToken);
}
await db.SaveChangesAsync(cancellationToken);
@@ -633,21 +720,30 @@ public sealed class CourseSelectionsController(
.FirstOrDefault(x => x.StudentId == student.Id);
if (enrollment is null)
{
db.CourseEnrollments.Add(new CourseEnrollment
enrollment = new CourseEnrollment
{
CourseSelectionOfferingId = offeringId,
StudentId = student.Id,
EnrollmentType = EnrollmentType.Retake,
EnrolledAt = now
});
};
db.CourseEnrollments.Add(enrollment);
}
else
{
enrollment.Status = CourseEnrollmentStatus.Enrolled;
enrollment.EnrolledAt = now;
enrollment.WaitlistedAt = null;
enrollment.WithdrawnAt = null;
enrollment.EnrollmentType = EnrollmentType.Retake;
}
await ExpireOtherWaitlistsForCourseAsync(
student.Id,
task.CourseId,
round.AcademicTermId,
enrollment.Id,
now,
cancellationToken);
enrolled++;
}
@@ -666,28 +762,93 @@ public sealed class CourseSelectionsController(
Guid enrollmentId,
CancellationToken cancellationToken)
{
var enrollment = await db.CourseEnrollments
.Include(x => x.CourseSelectionOffering)
.ThenInclude(x => x!.TeachingTask)
.ThenInclude(x => x!.Course)
.FirstOrDefaultAsync(
x =>
x.Id == enrollmentId &&
x.CourseSelectionOfferingId == offeringId,
cancellationToken);
if (enrollment is null) return NotFound();
var offering = enrollment.CourseSelectionOffering!;
if (!CourseSelectionRules.SupportsProxyEnrollment(
offering.TeachingTask!.Course!.Nature))
return ConflictProblem("管理员名单调整仅适用于公共必修课。");
if (offering.TeachingTask.Status != TeachingTaskStatus.Published)
return ConflictProblem("该教学班当前不可调整名单。");
if (enrollment.Status != CourseEnrollmentStatus.Enrolled)
return ConflictProblem("该学生已不在教学班名单中。");
return await db.ExecuteInRetriableTransactionAsync<ActionResult>(
async transaction =>
{
db.ChangeTracker.Clear();
var enrollment = await db.CourseEnrollments
.Include(x => x.CourseSelectionOffering)
.ThenInclude(x => x!.CourseSelectionRound)
.Include(x => x.CourseSelectionOffering)
.ThenInclude(x => x!.TeachingTask)
.ThenInclude(x => x!.Course)
.FirstOrDefaultAsync(
x =>
x.Id == enrollmentId &&
x.CourseSelectionOfferingId == offeringId,
cancellationToken);
if (enrollment is null) return NotFound();
var offering = enrollment.CourseSelectionOffering!;
if (!CourseSelectionRules.SupportsProxyEnrollment(
offering.TeachingTask!.Course!.Nature))
return ConflictProblem("管理员名单调整仅适用于公共必修课。");
if (offering.TeachingTask.Status != TeachingTaskStatus.Published)
return ConflictProblem("该教学班当前不可调整名单。");
if (enrollment.Status != CourseEnrollmentStatus.Enrolled)
return ConflictProblem("该学生已不在教学班名单中。");
enrollment.Status = CourseEnrollmentStatus.Withdrawn;
enrollment.WithdrawnAt = DateTime.UtcNow;
return await SaveAsync(enrollmentId, false, cancellationToken);
enrollment.Status = CourseEnrollmentStatus.Withdrawn;
enrollment.WithdrawnAt = DateTime.UtcNow;
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")]
@@ -724,6 +885,8 @@ public sealed class CourseSelectionsController(
x.Capacity,
x.Enrollments.Count(item =>
item.Status == CourseEnrollmentStatus.Enrolled),
x.Enrollments.Count(item =>
item.Status == CourseEnrollmentStatus.Waitlisted),
x.IsOpenToAll,
x.Enrollments
.Where(item => item.StudentId == student.Id)
@@ -732,6 +895,8 @@ public sealed class CourseSelectionsController(
x.TeachingTask.SchedulingMode == TeachingTaskSchedulingMode.Flexible,
db.CourseEnrollments.Any(e =>
e.StudentId == student.Id &&
(e.Status == CourseEnrollmentStatus.Enrolled ||
e.Status == CourseEnrollmentStatus.Withdrawn) &&
e.CourseSelectionOffering!.TeachingTask!.CourseId ==
x.TeachingTask.CourseId &&
e.CourseSelectionOffering.CourseSelectionRound!.AcademicTermId !=
@@ -751,9 +916,48 @@ public sealed class CourseSelectionsController(
entry.EndWeek,
entry.WeekPattern,
entry.Classroom == null ? "不占用教室" : entry.Classroom.Name))
.ToList()))
.ToList(),
null))
.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
{
Round = new
@@ -816,9 +1020,11 @@ public sealed class CourseSelectionsController(
x.Status,
x.EnrollmentType,
x.EnrolledAt,
x.WaitlistedAt,
x.WithdrawnAt,
CanWithdraw =
x.Status == CourseEnrollmentStatus.Enrolled &&
(x.Status == CourseEnrollmentStatus.Enrolled ||
x.Status == CourseEnrollmentStatus.Waitlisted) &&
x.CourseSelectionOffering.CourseSelectionRound.Status ==
CourseSelectionRoundStatus.Open &&
DateTime.UtcNow <=
@@ -866,6 +1072,8 @@ public sealed class CourseSelectionsController(
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,
@@ -884,9 +1092,9 @@ public sealed class CourseSelectionsController(
x.CourseSelectionOfferingId == offering.Id &&
x.Status == CourseEnrollmentStatus.Enrolled,
cancellationToken);
var effectiveCapacity = isRetake
? CourseSelectionRules.RetakeCapacity(offering.Capacity)
: offering.Capacity;
var effectiveCapacity = CourseSelectionRules.EffectiveCapacity(
offering.Capacity,
isRetake);
if (enrolledCount >= effectiveCapacity)
return ConflictProblem("该教学班名额已满。");
@@ -967,9 +1175,17 @@ public sealed class CourseSelectionsController(
{
existing.Status = CourseEnrollmentStatus.Enrolled;
existing.EnrolledAt = now;
existing.WaitlistedAt = null;
existing.WithdrawnAt = null;
existing.EnrollmentType = isRetake ? EnrollmentType.Retake : EnrollmentType.Normal;
}
await ExpireOtherWaitlistsForCourseAsync(
student.Id,
task.CourseId,
round.AcademicTermId,
existing.Id,
now,
cancellationToken);
await db.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
return Created(string.Empty, new { existing.Id, IsRetake = isRetake });
@@ -978,28 +1194,168 @@ public sealed class CourseSelectionsController(
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}")]
[Authorize(Roles = SystemRoles.Student)]
public async Task<ActionResult> Withdraw(Guid id, CancellationToken cancellationToken)
{
var student = await CurrentStudentAsync(cancellationToken);
if (student is null) return ProfileNotFound();
var enrollment = await db.CourseEnrollments
.Include(x => x.CourseSelectionOffering)
.ThenInclude(x => x!.CourseSelectionRound)
.FirstOrDefaultAsync(
x => x.Id == id && x.StudentId == student.Id,
cancellationToken);
if (enrollment is null) return NotFound();
if (enrollment.Status != CourseEnrollmentStatus.Enrolled)
return ConflictProblem("该课程已经退选。");
if (!CourseSelectionRules.CanWithdraw(
enrollment.CourseSelectionOffering!.CourseSelectionRound!,
DateTime.UtcNow))
return ConflictProblem("当前批次已停止退课。");
enrollment.Status = CourseEnrollmentStatus.Withdrawn;
enrollment.WithdrawnAt = DateTime.UtcNow;
return await SaveAsync(id, false, cancellationToken);
return await db.ExecuteInRetriableTransactionAsync<ActionResult>(
async transaction =>
{
db.ChangeTracker.Clear();
var student = await CurrentStudentAsync(cancellationToken);
if (student is null) return ProfileNotFound();
var enrollment = await db.CourseEnrollments
.Include(x => x.CourseSelectionOffering)
.ThenInclude(x => x!.CourseSelectionRound)
.Include(x => x.CourseSelectionOffering)
.ThenInclude(x => x!.TeachingTask)
.ThenInclude(x => x!.Course)
.FirstOrDefaultAsync(
x => x.Id == id && x.StudentId == student.Id,
cancellationToken);
if (enrollment is null) return NotFound();
var wasEnrolled = enrollment.Status == CourseEnrollmentStatus.Enrolled;
var wasWaitlisted =
enrollment.Status == CourseEnrollmentStatus.Waitlisted;
if (!wasEnrolled && !wasWaitlisted)
return ConflictProblem("该课程已经退选或候补已经结束。");
if (!CourseSelectionRules.CanWithdraw(
enrollment.CourseSelectionOffering!.CourseSelectionRound!,
DateTime.UtcNow))
return ConflictProblem("当前批次已停止退课和候补调整。");
enrollment.Status = wasWaitlisted
? CourseEnrollmentStatus.Cancelled
: CourseEnrollmentStatus.Withdrawn;
enrollment.WithdrawnAt = DateTime.UtcNow;
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")]
@@ -1178,6 +1534,214 @@ public sealed class CourseSelectionsController(
.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(
Guid id,
bool created,
@@ -1207,6 +1771,8 @@ public sealed class CourseSelectionsController(
private static string? Normalize(string? value) =>
string.IsNullOrWhiteSpace(value) ? null : value.Trim();
private sealed record EnrollmentEligibility(bool IsRetake, string? Error);
}
public sealed record CourseSelectionRoundRequest(
@@ -1242,11 +1808,13 @@ public sealed record StudentOfferingDto(
IEnumerable<string> TeacherNames,
int Capacity,
int EnrolledCount,
int WaitlistedCount,
bool IsOpenToAll,
CourseEnrollmentStatus? EnrollmentStatus,
bool IsFlexible,
bool IsRetake,
IEnumerable<StudentScheduleDto> Schedules);
IEnumerable<StudentScheduleDto> Schedules,
int? WaitlistPosition);
public sealed record StudentScheduleDto(
int DayOfWeek,
@@ -38,6 +38,7 @@ public sealed class CourseEnrollment : EntityBase
public CourseEnrollmentStatus Status { get; set; } = CourseEnrollmentStatus.Enrolled;
public EnrollmentType EnrollmentType { get; set; } = EnrollmentType.Normal;
public DateTime EnrolledAt { get; set; } = DateTime.UtcNow;
public DateTime? WaitlistedAt { get; set; }
public DateTime? WithdrawnAt { get; set; }
}
@@ -51,7 +52,10 @@ public enum CourseSelectionRoundStatus
public enum CourseEnrollmentStatus
{
Enrolled = 1,
Withdrawn = 2
Withdrawn = 2,
Waitlisted = 3,
Cancelled = 4,
Expired = 5
}
public enum EnrollmentType
@@ -14,6 +14,10 @@ public static class CourseSelectionRules
round.Status == CourseSelectionRoundStatus.Open &&
nowUtc <= round.WithdrawalEndsAt;
public static bool CanPromoteWaitlist(CourseSelectionRound round, DateTime nowUtc) =>
round.Status == CourseSelectionRoundStatus.Open &&
nowUtc <= round.WithdrawalEndsAt;
public static bool SupportsProxyEnrollment(CourseNature nature) =>
nature == CourseNature.GeneralRequired;
@@ -68,4 +72,7 @@ public static class CourseSelectionRules
/// <summary>Retake expanded capacity: ceiling(original * 1.15).</summary>
public static int RetakeCapacity(int originalCapacity) =>
(int)Math.Ceiling(originalCapacity * 1.15);
public static int EffectiveCapacity(int originalCapacity, bool isRetake) =>
isRetake ? RetakeCapacity(originalCapacity) : originalCapacity;
}
@@ -500,6 +500,12 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
entity.HasIndex(x => new { x.CourseSelectionOfferingId, x.StudentId })
.IsUnique();
entity.HasIndex(x => new { x.StudentId, x.Status });
entity.HasIndex(x => new
{
x.CourseSelectionOfferingId,
x.Status,
x.WaitlistedAt
});
entity.HasOne(x => x.CourseSelectionOffering)
.WithMany(x => x.Enrollments)
.HasForeignKey(x => x.CourseSelectionOfferingId)
@@ -48,6 +48,8 @@ public sealed class DevelopmentSqliteMigrator(
"20260725_25_academic_warnings";
private const string AcademicTermArchivingMigration =
"20260726_27_academic_term_archiving";
private const string CourseSelectionWaitlistMigration =
"20260726_28_course_selection_waitlist";
public async Task MigrateAsync(CancellationToken cancellationToken = default)
{
@@ -344,6 +346,19 @@ public sealed class DevelopmentSqliteMigrator(
AcademicTermArchivingMigration,
academicTermArchivingExists ? [] : AcademicTermArchivingStatements,
cancellationToken);
var courseSelectionWaitlistExists = await db.Database
.SqlQueryRaw<int>(
"""
SELECT COUNT(*) AS "Value"
FROM pragma_table_info('CourseEnrollments')
WHERE name = 'WaitlistedAt'
""")
.AnyAsync(value => value > 0, cancellationToken);
await ApplyMigrationAsync(
CourseSelectionWaitlistMigration,
courseSelectionWaitlistExists ? [] : CourseSelectionWaitlistStatements,
cancellationToken);
}
private async Task ApplyMigrationAsync(
@@ -1589,6 +1604,18 @@ public sealed class DevelopmentSqliteMigrator(
"""
];
private static readonly string[] CourseSelectionWaitlistStatements =
[
"""
ALTER TABLE "CourseEnrollments"
ADD COLUMN "WaitlistedAt" TEXT NULL;
""",
"""
CREATE INDEX IF NOT EXISTS "IX_CourseEnrollments_CourseSelectionOfferingId_Status_WaitlistedAt"
ON "CourseEnrollments" ("CourseSelectionOfferingId", "Status", "WaitlistedAt");
"""
];
private static readonly string[] CourseAdjustmentsStatements =
[
"""
@@ -0,0 +1,37 @@
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql;
[DbContext(typeof(AppDbContext))]
[Migration("20260726170000_CourseSelectionWaitlist")]
public partial class CourseSelectionWaitlist : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTime>(
name: "WaitlistedAt",
table: "CourseEnrollments",
type: "datetime(6)",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_CourseEnrollments_CourseSelectionOfferingId_Status_WaitlistedAt",
table: "CourseEnrollments",
columns: new[] { "CourseSelectionOfferingId", "Status", "WaitlistedAt" });
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_CourseEnrollments_CourseSelectionOfferingId_Status_WaitlistedAt",
table: "CourseEnrollments");
migrationBuilder.DropColumn(
name: "WaitlistedAt",
table: "CourseEnrollments");
}
}
@@ -732,6 +732,9 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.Property<DateTime?>("WaitlistedAt")
.HasColumnType("datetime(6)");
b.Property<DateTime?>("WithdrawnAt")
.HasColumnType("datetime(6)");
@@ -740,6 +743,8 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.HasIndex("CourseSelectionOfferingId", "StudentId")
.IsUnique();
b.HasIndex("CourseSelectionOfferingId", "Status", "WaitlistedAt");
b.HasIndex("StudentId", "Status");
b.ToTable("CourseEnrollments");