2845 lines
133 KiB
C#
2845 lines
133 KiB
C#
using System.ComponentModel.DataAnnotations;
|
||
using System.Data;
|
||
using System.Globalization;
|
||
using System.Text;
|
||
using Jiaowu.Api.Contracts;
|
||
using Jiaowu.Api.Domain.Academic;
|
||
using Jiaowu.Api.Domain.Identity;
|
||
using Jiaowu.Api.Infrastructure.Auth;
|
||
using Jiaowu.Api.Infrastructure.CourseSelection;
|
||
using Jiaowu.Api.Infrastructure.Excel;
|
||
using Jiaowu.Api.Infrastructure.Files;
|
||
using Jiaowu.Api.Infrastructure.Localization;
|
||
using Jiaowu.Api.Infrastructure.Graduation;
|
||
using Jiaowu.Api.Infrastructure.Persistence;
|
||
using Jiaowu.Api.Infrastructure.Teaching;
|
||
using Microsoft.AspNetCore.Authorization;
|
||
using Microsoft.AspNetCore.Mvc;
|
||
using Microsoft.EntityFrameworkCore;
|
||
using Microsoft.Extensions.Localization;
|
||
|
||
namespace Jiaowu.Api.Controllers;
|
||
|
||
[ApiController]
|
||
[Authorize]
|
||
[Route("api/course-selections")]
|
||
public sealed class CourseSelectionsController(
|
||
AppDbContext db,
|
||
ICurrentUserDataScope currentUserDataScope,
|
||
IStringLocalizer<SharedResource>? localizer = null) : ControllerBase
|
||
{
|
||
private const string RoundManagers =
|
||
SystemRoles.SuperAdmin + "," +
|
||
SystemRoles.AcademicAdmin;
|
||
|
||
private const string OfferingManagers =
|
||
SystemRoles.SuperAdmin + "," +
|
||
SystemRoles.AcademicAdmin + "," +
|
||
SystemRoles.CollegeAdmin;
|
||
|
||
private const string SelectionUsers =
|
||
OfferingManagers + "," +
|
||
SystemRoles.Student;
|
||
|
||
private const string RosterReaders =
|
||
OfferingManagers + "," +
|
||
SystemRoles.Teacher;
|
||
|
||
[HttpGet("enrollments")]
|
||
[Authorize(Roles = OfferingManagers)]
|
||
public async Task<ActionResult> GetEnrollments(
|
||
[FromQuery] CourseEnrollmentQuery query,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var source = ApplyEnrollmentFilters(ScopedEnrollments(), query);
|
||
var total = await source.CountAsync(cancellationToken);
|
||
var page = Math.Max(1, query.Page);
|
||
var pageSize = Math.Clamp(query.PageSize, 1, 100);
|
||
var items = await ProjectEnrollments(OrderEnrollments(source))
|
||
.Skip((page - 1) * pageSize)
|
||
.Take(pageSize)
|
||
.ToListAsync(cancellationToken);
|
||
return Ok(new PagedResult<object>(items.Cast<object>().ToList(), total, page, pageSize));
|
||
}
|
||
|
||
private static readonly string[] EnrollmentExportHeaders = [
|
||
"学期", "开课院系", "课程代码", "课程名称", "教学班", "学号", "姓名",
|
||
"专业", "行政班", "年级", "修读状态", "修读类型", "选入时间", "退选时间", "免修审批"];
|
||
private static readonly string[] StudentEnrollmentExportHeaders = ["学号", "姓名", "专业", "行政班", "年级", "修读课程", "在修学分"];
|
||
|
||
[HttpGet("enrollments/export-columns")]
|
||
[Authorize(Roles = OfferingManagers)]
|
||
public IActionResult EnrollmentExportColumns(bool student = false) => Ok(student ? StudentEnrollmentExportHeaders : EnrollmentExportHeaders);
|
||
|
||
[HttpGet("enrollments/export.xlsx")]
|
||
[Authorize(Roles = OfferingManagers)]
|
||
[ProducesResponseType<FileContentResult>(StatusCodes.Status200OK, ExcelWorkbookHelper.ContentType)]
|
||
public async Task<ActionResult> ExportEnrollments(
|
||
[FromQuery] CourseEnrollmentQuery query,
|
||
CancellationToken cancellationToken, string? columns = null, string? format = null)
|
||
{
|
||
var items = await ProjectEnrollments(OrderEnrollments(
|
||
ApplyEnrollmentFilters(ScopedEnrollments(), query)))
|
||
.ToListAsync(cancellationToken);
|
||
var rows = items.Select(x => (IReadOnlyList<object?>)[
|
||
x.TermName, x.CollegeName, x.CourseCode, x.CourseName, x.TaskNumber,
|
||
x.StudentNumber, x.StudentName, x.MajorName, x.ClassName, x.Grade,
|
||
x.Status.ToString(), x.EnrollmentType.ToString(), x.EnrolledAt,
|
||
x.WithdrawnAt, x.ExemptionStatus?.ToString() ?? "—"
|
||
]).ToList();
|
||
return TabularExport.Create(this, "修读课程名单", EnrollmentExportHeaders, rows, columns, format);
|
||
}
|
||
|
||
[HttpGet("enrollments/students")]
|
||
[Authorize(Roles = OfferingManagers)]
|
||
public async Task<ActionResult> GetStudentEnrollmentSummaries(
|
||
[FromQuery] CourseEnrollmentQuery query,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var source = ApplyEnrollmentFilters(ScopedEnrollments(), query);
|
||
var matchingStudentIds = source.Select(x => x.StudentId).Distinct();
|
||
var total = await matchingStudentIds.CountAsync(cancellationToken);
|
||
var page = Math.Max(1, query.Page);
|
||
var pageSize = Math.Clamp(query.PageSize, 1, 100);
|
||
var pageStudentQuery = db.Students.AsNoTracking()
|
||
.Where(x => matchingStudentIds.Contains(x.Id))
|
||
.OrderBy(x => x.StudentNumber)
|
||
.Skip((page - 1) * pageSize)
|
||
.Take(pageSize);
|
||
var pageStudents = await pageStudentQuery
|
||
.Select(x => new EnrollmentStudentIdentity(
|
||
x.Id, x.StudentNumber, x.Name, x.AdministrativeClass!.Major!.Name,
|
||
x.AdministrativeClass.Name, x.AdministrativeClass.Grade))
|
||
.ToListAsync(cancellationToken);
|
||
if (pageStudents.Count == 0)
|
||
{
|
||
return Ok(new PagedResult<StudentEnrollmentSummary>([], total, page, pageSize));
|
||
}
|
||
|
||
// MySql.EntityFrameworkCore 10 cannot type-map a parameterized Guid collection.
|
||
// Keep the paged IDs as a server-side subquery instead of materializing Guid[].
|
||
var pageStudentIds = pageStudentQuery.Select(x => x.Id);
|
||
var enrollments = await ProjectEnrollments(OrderEnrollments(source.Where(x =>
|
||
pageStudentIds.Contains(x.StudentId))))
|
||
.ToListAsync(cancellationToken);
|
||
var summaries = pageStudents.Select(student =>
|
||
{
|
||
var courses = enrollments.Where(x => x.StudentId == student.StudentId).ToList();
|
||
return new StudentEnrollmentSummary(
|
||
student.StudentId, student.StudentNumber, student.StudentName,
|
||
student.MajorName, student.ClassName, student.Grade, courses,
|
||
courses.Count, courses.Where(x => x.Status == CourseEnrollmentStatus.Enrolled)
|
||
.Sum(x => x.Credits));
|
||
}).ToList();
|
||
return Ok(new PagedResult<StudentEnrollmentSummary>(summaries, total, page, pageSize));
|
||
}
|
||
|
||
[HttpGet("enrollments/students/export.xlsx")]
|
||
[Authorize(Roles = OfferingManagers)]
|
||
[ProducesResponseType<FileContentResult>(StatusCodes.Status200OK, ExcelWorkbookHelper.ContentType)]
|
||
public async Task<ActionResult> ExportStudentEnrollmentSummaries(
|
||
[FromQuery] CourseEnrollmentQuery query,
|
||
CancellationToken cancellationToken, string? columns = null, string? format = null)
|
||
{
|
||
var items = await ProjectEnrollments(OrderEnrollments(
|
||
ApplyEnrollmentFilters(ScopedEnrollments(), query)))
|
||
.ToListAsync(cancellationToken);
|
||
var rows = items.GroupBy(x => new
|
||
{
|
||
x.StudentId,
|
||
x.StudentNumber,
|
||
x.StudentName,
|
||
x.MajorName,
|
||
x.ClassName,
|
||
x.Grade
|
||
})
|
||
.OrderBy(x => x.Key.StudentNumber)
|
||
.Select(group => (IReadOnlyList<object?>)[
|
||
group.Key.StudentNumber, group.Key.StudentName, group.Key.MajorName,
|
||
group.Key.ClassName, group.Key.Grade,
|
||
string.Join(";", group.Select(x =>
|
||
$"{x.TermName} {x.CourseCode} {x.CourseName}({x.Status})")),
|
||
group.Where(x => x.Status == CourseEnrollmentStatus.Enrolled)
|
||
.Sum(x => x.Credits)
|
||
]).ToList();
|
||
return TabularExport.Create(this, "学生修读汇总", StudentEnrollmentExportHeaders, rows, columns, format);
|
||
}
|
||
|
||
[HttpGet("rounds")]
|
||
[Authorize(Roles = SelectionUsers)]
|
||
public async Task<ActionResult> GetRounds(
|
||
Guid? academicTermId,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var source = db.CourseSelectionRounds.AsNoTracking().AsQueryable();
|
||
if (academicTermId.HasValue)
|
||
source = source.Where(x => x.AcademicTermId == academicTermId);
|
||
if (currentUserDataScope.Current.IsInRole(SystemRoles.Student))
|
||
{
|
||
var userId = currentUserDataScope.Current.UserId;
|
||
var studentGrade = await db.Students.AsNoTracking()
|
||
.Where(x => x.UserId == userId)
|
||
.Select(x => (int?)x.AdministrativeClass!.Grade)
|
||
.FirstOrDefaultAsync(cancellationToken);
|
||
source = source.Where(x => x.Status != CourseSelectionRoundStatus.Draft);
|
||
if (studentGrade.HasValue)
|
||
{
|
||
source = source.Where(x =>
|
||
!x.EligibleGrades.Any() ||
|
||
x.EligibleGrades.Any(item => item.Grade == studentGrade.Value));
|
||
}
|
||
else
|
||
{
|
||
source = source.Where(_ => false);
|
||
}
|
||
}
|
||
|
||
var now = DateTime.UtcNow;
|
||
return Ok(await source
|
||
.OrderByDescending(x => x.AcademicTerm!.StartDate)
|
||
.ThenByDescending(x => x.StartsAt)
|
||
.Select(x => new
|
||
{
|
||
x.Id,
|
||
x.Name,
|
||
x.AcademicTermId,
|
||
TermName = x.AcademicTerm!.Name,
|
||
TermIsCurrent = x.AcademicTerm.IsCurrent,
|
||
TermIsArchived = x.AcademicTerm.IsArchived,
|
||
x.StartsAt,
|
||
x.EndsAt,
|
||
x.WithdrawalEndsAt,
|
||
x.MaxCredits,
|
||
x.MaxCourseCount,
|
||
x.Scope,
|
||
EligibleGrades = x.EligibleGrades
|
||
.OrderBy(item => item.Grade)
|
||
.Select(item => item.Grade),
|
||
x.Status,
|
||
IsAvailableNow =
|
||
x.Status == CourseSelectionRoundStatus.Open &&
|
||
now >= x.StartsAt &&
|
||
now <= x.EndsAt,
|
||
OfferingCount = x.Offerings.Count,
|
||
x.Notes,
|
||
x.UpdatedAt
|
||
})
|
||
.ToListAsync(cancellationToken));
|
||
}
|
||
|
||
[HttpGet("configuration-options")]
|
||
[Authorize(Roles = RoundManagers)]
|
||
public async Task<ActionResult> GetConfigurationOptions(
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var grades = await db.AdministrativeClasses.AsNoTracking()
|
||
.Where(x => x.IsEnabled)
|
||
.Select(x => x.Grade)
|
||
.Distinct()
|
||
.OrderByDescending(x => x)
|
||
.ToListAsync(cancellationToken);
|
||
return Ok(new { Grades = grades });
|
||
}
|
||
|
||
[HttpPost("rounds")]
|
||
[Authorize(Roles = RoundManagers)]
|
||
public async Task<ActionResult> CreateRound(
|
||
CourseSelectionRoundRequest request,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var validation = await ValidateRoundAsync(request, cancellationToken);
|
||
if (validation is not null) return validation;
|
||
var round = new CourseSelectionRound
|
||
{
|
||
AcademicTermId = request.AcademicTermId,
|
||
Name = request.Name.Trim(),
|
||
StartsAt = request.StartsAt.ToUniversalTime(),
|
||
EndsAt = request.EndsAt.ToUniversalTime(),
|
||
WithdrawalEndsAt = request.WithdrawalEndsAt.ToUniversalTime(),
|
||
MaxCredits = request.MaxCredits,
|
||
MaxCourseCount = request.MaxCourseCount,
|
||
Scope = request.Scope,
|
||
EligibleGrades = NormalizeGrades(request.EligibleGrades)
|
||
.Select(grade => new CourseSelectionRoundGrade { Grade = grade })
|
||
.ToList(),
|
||
Notes = Normalize(request.Notes)
|
||
};
|
||
db.CourseSelectionRounds.Add(round);
|
||
return await SaveAsync(round.Id, true, cancellationToken);
|
||
}
|
||
|
||
[HttpPut("rounds/{id:guid}")]
|
||
[Authorize(Roles = RoundManagers)]
|
||
public async Task<ActionResult> UpdateRound(
|
||
Guid id,
|
||
CourseSelectionRoundRequest request,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var round = await db.CourseSelectionRounds
|
||
.Include(x => x.EligibleGrades)
|
||
.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
|
||
if (round is null) return NotFound();
|
||
if (round.Status != CourseSelectionRoundStatus.Draft)
|
||
return ConflictProblem("只有草稿选课批次可以修改。");
|
||
var validation = await ValidateRoundAsync(request, cancellationToken);
|
||
if (validation is not null) return validation;
|
||
round.AcademicTermId = request.AcademicTermId;
|
||
round.Name = request.Name.Trim();
|
||
round.StartsAt = request.StartsAt.ToUniversalTime();
|
||
round.EndsAt = request.EndsAt.ToUniversalTime();
|
||
round.WithdrawalEndsAt = request.WithdrawalEndsAt.ToUniversalTime();
|
||
round.MaxCredits = request.MaxCredits;
|
||
round.MaxCourseCount = request.MaxCourseCount;
|
||
round.Scope = request.Scope;
|
||
var requestedGrades = NormalizeGrades(request.EligibleGrades);
|
||
var requestedGradeSet = requestedGrades.ToHashSet();
|
||
db.CourseSelectionRoundGrades.RemoveRange(
|
||
round.EligibleGrades.Where(x => !requestedGradeSet.Contains(x.Grade)));
|
||
foreach (var grade in requestedGrades.Where(grade =>
|
||
round.EligibleGrades.All(x => x.Grade != grade)))
|
||
{
|
||
round.EligibleGrades.Add(new CourseSelectionRoundGrade
|
||
{
|
||
CourseSelectionRoundId = round.Id,
|
||
Grade = grade
|
||
});
|
||
}
|
||
round.Notes = Normalize(request.Notes);
|
||
return await SaveAsync(id, false, cancellationToken);
|
||
}
|
||
|
||
[HttpDelete("rounds/{id:guid}")]
|
||
[Authorize(Roles = RoundManagers)]
|
||
public async Task<ActionResult> DeleteRound(Guid id, CancellationToken cancellationToken)
|
||
{
|
||
var round = await db.CourseSelectionRounds.FindAsync([id], cancellationToken);
|
||
if (round is null) return NotFound();
|
||
if (round.Status != CourseSelectionRoundStatus.Draft)
|
||
return ConflictProblem("只有草稿选课批次可以删除。");
|
||
db.CourseSelectionRounds.Remove(round);
|
||
return await SaveAsync(id, false, cancellationToken);
|
||
}
|
||
|
||
[HttpPost("rounds/{id:guid}/open")]
|
||
[Authorize(Roles = RoundManagers)]
|
||
public async Task<ActionResult> OpenRound(Guid id, CancellationToken cancellationToken)
|
||
{
|
||
var round = await db.CourseSelectionRounds
|
||
.Include(x => x.Offerings)
|
||
.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
|
||
if (round is null) return NotFound();
|
||
if (round.Status != CourseSelectionRoundStatus.Draft)
|
||
return ConflictProblem("只有草稿选课批次可以开放。");
|
||
if (round.Offerings.Count == 0)
|
||
return ConflictProblem("至少配置一个可选教学班后才能开放。");
|
||
round.Status = CourseSelectionRoundStatus.Open;
|
||
return await SaveAsync(id, false, cancellationToken);
|
||
}
|
||
|
||
[HttpPost("rounds/{id:guid}/close")]
|
||
[Authorize(Roles = RoundManagers)]
|
||
public async Task<ActionResult> CloseRound(Guid id, CancellationToken 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 enrollments = 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)
|
||
.ToListAsync(cancellationToken);
|
||
var waitlisted = enrollments
|
||
.Where(x => x.Status == CourseEnrollmentStatus.Waitlisted)
|
||
.ToList();
|
||
var now = DateTime.UtcNow;
|
||
foreach (var enrollment in waitlisted)
|
||
{
|
||
enrollment.Status = CourseEnrollmentStatus.Expired;
|
||
enrollment.WithdrawnAt = now;
|
||
enrollment.WaitlistResolvedAt = now;
|
||
enrollment.WaitlistResolutionReason = "选课批次已关闭,候补队列未能递补。";
|
||
}
|
||
|
||
var participantGroups = enrollments
|
||
.Where(x => x.Student!.UserId.HasValue)
|
||
.GroupBy(x => new
|
||
{
|
||
x.StudentId,
|
||
UserId = x.Student!.UserId!.Value
|
||
})
|
||
.ToList();
|
||
foreach (var participant in participantGroups)
|
||
{
|
||
var selectedCourses = participant
|
||
.Where(x => x.Status == CourseEnrollmentStatus.Enrolled)
|
||
.Select(x => x.CourseSelectionOffering!.TeachingTask!.Course!.Name)
|
||
.Distinct()
|
||
.OrderBy(x => x)
|
||
.ToArray();
|
||
var unsuccessfulCourses = participant
|
||
.Where(x => x.Status == CourseEnrollmentStatus.Expired)
|
||
.Select(x => x.CourseSelectionOffering!.TeachingTask!.Course!.Name)
|
||
.Distinct()
|
||
.OrderBy(x => x)
|
||
.ToArray();
|
||
db.Notifications.Add(new Notification
|
||
{
|
||
UserId = participant.Key.UserId,
|
||
Title = $"{round.Name}结果",
|
||
Content = BuildRoundResultContent(
|
||
round.Name,
|
||
selectedCourses,
|
||
unsuccessfulCourses),
|
||
Category = NotificationCategory.CourseSelection,
|
||
LinkUrl = "/course-selections"
|
||
});
|
||
}
|
||
|
||
round.Status = CourseSelectionRoundStatus.Closed;
|
||
await db.SaveChangesAsync(cancellationToken);
|
||
await transaction.CommitAsync(cancellationToken);
|
||
return Ok(new
|
||
{
|
||
ExpiredWaitlistCount = waitlisted.Count,
|
||
NotifiedStudentCount = participantGroups.Count
|
||
});
|
||
},
|
||
cancellationToken,
|
||
IsolationLevel.Serializable);
|
||
}
|
||
|
||
[HttpGet("rounds/{roundId:guid}/offerings")]
|
||
[Authorize(Roles = OfferingManagers)]
|
||
public async Task<ActionResult> GetOfferings(
|
||
Guid roundId,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var source = ScopedOfferings()
|
||
.AsNoTracking()
|
||
.AsSplitQuery()
|
||
.Where(x => x.CourseSelectionRoundId == roundId);
|
||
return Ok(await source
|
||
.OrderBy(x => x.TeachingTask!.Course!.Code)
|
||
.ThenBy(x => x.TeachingTask!.TaskNumber)
|
||
.Select(x => new
|
||
{
|
||
x.Id,
|
||
x.CourseSelectionRoundId,
|
||
x.TeachingTaskId,
|
||
x.TeachingTask!.TaskNumber,
|
||
TaskName = x.TeachingTask.Name,
|
||
CourseCode = x.TeachingTask.Course!.Code,
|
||
CourseName = x.TeachingTask.Course.Name,
|
||
CourseNature = x.TeachingTask.Course.Nature,
|
||
CollegeName = x.TeachingTask.Course.College!.Name,
|
||
x.TeachingTask.Course.Credits,
|
||
TeacherNames = x.TeachingTask.Teachers
|
||
.OrderByDescending(item => item.IsPrimary)
|
||
.Select(item => item.Teacher!.Name),
|
||
ClassNames = x.TeachingTask.Classes
|
||
.Select(item => item.AdministrativeClass!.Name),
|
||
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
|
||
})
|
||
.ToListAsync(cancellationToken));
|
||
}
|
||
|
||
[HttpPost("rounds/{roundId:guid}/offerings")]
|
||
[Authorize(Roles = OfferingManagers)]
|
||
public async Task<ActionResult> CreateOffering(
|
||
Guid roundId,
|
||
CourseSelectionOfferingRequest request,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var round = await db.CourseSelectionRounds.FindAsync([roundId], cancellationToken);
|
||
if (round is null) return NotFound();
|
||
if (round.Status != CourseSelectionRoundStatus.Draft)
|
||
return ConflictProblem("选课批次开放后不能调整教学班。");
|
||
var task = await FindAccessibleTaskAsync(request.TeachingTaskId, cancellationToken);
|
||
var validation = ValidateOffering(round, task, request);
|
||
if (validation is not null) return validation;
|
||
var offering = new CourseSelectionOffering
|
||
{
|
||
CourseSelectionRoundId = roundId,
|
||
TeachingTaskId = request.TeachingTaskId,
|
||
Capacity = request.Capacity,
|
||
IsOpenToAll = request.IsOpenToAll,
|
||
Notes = Normalize(request.Notes)
|
||
};
|
||
db.CourseSelectionOfferings.Add(offering);
|
||
return await SaveAsync(offering.Id, true, cancellationToken);
|
||
}
|
||
|
||
[HttpPut("rounds/{roundId:guid}/offerings/{id:guid}")]
|
||
[Authorize(Roles = OfferingManagers)]
|
||
public async Task<ActionResult> UpdateOffering(
|
||
Guid roundId,
|
||
Guid id,
|
||
CourseSelectionOfferingRequest request,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var offering = await ScopedOfferings()
|
||
.Include(x => x.CourseSelectionRound)
|
||
.FirstOrDefaultAsync(
|
||
x => x.Id == id && x.CourseSelectionRoundId == roundId,
|
||
cancellationToken);
|
||
if (offering is null) return NotFound();
|
||
if (offering.CourseSelectionRound!.Status != CourseSelectionRoundStatus.Draft)
|
||
return ConflictProblem("选课批次开放后不能调整教学班。");
|
||
var task = await FindAccessibleTaskAsync(request.TeachingTaskId, cancellationToken);
|
||
var validation = ValidateOffering(offering.CourseSelectionRound, task, request);
|
||
if (validation is not null) return validation;
|
||
offering.TeachingTaskId = request.TeachingTaskId;
|
||
offering.Capacity = request.Capacity;
|
||
offering.IsOpenToAll = request.IsOpenToAll;
|
||
offering.Notes = Normalize(request.Notes);
|
||
return await SaveAsync(id, false, cancellationToken);
|
||
}
|
||
|
||
[HttpDelete("rounds/{roundId:guid}/offerings/{id:guid}")]
|
||
[Authorize(Roles = OfferingManagers)]
|
||
public async Task<ActionResult> DeleteOffering(
|
||
Guid roundId,
|
||
Guid id,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var offering = await ScopedOfferings()
|
||
.Include(x => x.CourseSelectionRound)
|
||
.FirstOrDefaultAsync(
|
||
x => x.Id == id && x.CourseSelectionRoundId == roundId,
|
||
cancellationToken);
|
||
if (offering is null) return NotFound();
|
||
if (offering.CourseSelectionRound!.Status != CourseSelectionRoundStatus.Draft)
|
||
return ConflictProblem("选课批次开放后不能调整教学班。");
|
||
db.CourseSelectionOfferings.Remove(offering);
|
||
return await SaveAsync(id, false, cancellationToken);
|
||
}
|
||
|
||
[HttpGet("offerings/{id:guid}/roster")]
|
||
[Authorize(Roles = RosterReaders)]
|
||
public async Task<ActionResult> GetRoster(
|
||
Guid id,
|
||
string? keyword = null,
|
||
int? grade = null,
|
||
Guid? majorId = null,
|
||
Guid? administrativeClassId = null,
|
||
int studentPage = 1,
|
||
int studentPageSize = 20,
|
||
int waitlistPage = 1,
|
||
int waitlistPageSize = 20,
|
||
CancellationToken cancellationToken = default)
|
||
{
|
||
studentPage = Math.Max(1, studentPage);
|
||
studentPageSize = Math.Clamp(studentPageSize, 10, 100);
|
||
waitlistPage = Math.Max(1, waitlistPage);
|
||
waitlistPageSize = Math.Clamp(waitlistPageSize, 10, 100);
|
||
var offering = await db.CourseSelectionOfferings.AsNoTracking()
|
||
.Where(x => x.Id == id)
|
||
.Select(x => new
|
||
{
|
||
x.Id,
|
||
x.TeachingTaskId,
|
||
x.TeachingTask!.TaskNumber,
|
||
TaskName = x.TeachingTask.Name,
|
||
CourseCode = x.TeachingTask.Course!.Code,
|
||
CourseName = x.TeachingTask.Course!.Name,
|
||
CourseNature = x.TeachingTask.Course.Nature,
|
||
CollegeId = x.TeachingTask.Course.CollegeId,
|
||
TeacherUserIds = x.TeachingTask.Teachers
|
||
.Select(item => item.Teacher!.UserId),
|
||
x.CourseSelectionRoundId,
|
||
RoundStatus = x.CourseSelectionRound!.Status,
|
||
x.Capacity
|
||
})
|
||
.FirstOrDefaultAsync(cancellationToken);
|
||
if (offering is null) return NotFound();
|
||
var scope = currentUserDataScope.Current;
|
||
var isAssignedTeacher =
|
||
scope.IsInRole(SystemRoles.Teacher) &&
|
||
offering.TeacherUserIds.Contains(scope.UserId);
|
||
if (!isAssignedTeacher && !scope.CanAccessCollege(offering.CollegeId))
|
||
return Forbid();
|
||
|
||
var enrolledSource = db.CourseEnrollments.AsNoTracking()
|
||
.Where(x =>
|
||
x.CourseSelectionOfferingId == id &&
|
||
x.Status == CourseEnrollmentStatus.Enrolled);
|
||
var waitlistSource = db.CourseEnrollments.AsNoTracking()
|
||
.Where(x =>
|
||
x.CourseSelectionOfferingId == id &&
|
||
x.Status == CourseEnrollmentStatus.Waitlisted);
|
||
var enrolledCount = await enrolledSource.CountAsync(cancellationToken);
|
||
var waitlistedCount = await waitlistSource.CountAsync(cancellationToken);
|
||
var rosterSource = db.CourseEnrollments.AsNoTracking().Where(x =>
|
||
x.CourseSelectionOfferingId == id &&
|
||
(x.Status == CourseEnrollmentStatus.Enrolled ||
|
||
x.Status == CourseEnrollmentStatus.Waitlisted));
|
||
var filterOptions = await rosterSource
|
||
.Select(x => new
|
||
{
|
||
Grade = x.Student!.AdministrativeClass!.Grade,
|
||
MajorId = x.Student.AdministrativeClass.MajorId,
|
||
MajorName = x.Student.AdministrativeClass.Major!.Name,
|
||
ClassId = x.Student.AdministrativeClassId,
|
||
ClassName = x.Student.AdministrativeClass.Name
|
||
})
|
||
.Distinct()
|
||
.ToListAsync(cancellationToken);
|
||
if (grade.HasValue)
|
||
{
|
||
enrolledSource = enrolledSource.Where(x => x.Student!.AdministrativeClass!.Grade == grade.Value);
|
||
waitlistSource = waitlistSource.Where(x => x.Student!.AdministrativeClass!.Grade == grade.Value);
|
||
}
|
||
if (majorId.HasValue)
|
||
{
|
||
enrolledSource = enrolledSource.Where(x => x.Student!.AdministrativeClass!.MajorId == majorId.Value);
|
||
waitlistSource = waitlistSource.Where(x => x.Student!.AdministrativeClass!.MajorId == majorId.Value);
|
||
}
|
||
if (administrativeClassId.HasValue)
|
||
{
|
||
enrolledSource = enrolledSource.Where(x => x.Student!.AdministrativeClassId == administrativeClassId.Value);
|
||
waitlistSource = waitlistSource.Where(x => x.Student!.AdministrativeClassId == administrativeClassId.Value);
|
||
}
|
||
if (!string.IsNullOrWhiteSpace(keyword))
|
||
{
|
||
keyword = keyword.Trim();
|
||
enrolledSource = enrolledSource.Where(x =>
|
||
x.Student!.StudentNumber.Contains(keyword) ||
|
||
x.Student.Name.Contains(keyword) ||
|
||
x.Student.AdministrativeClass!.Name.Contains(keyword));
|
||
waitlistSource = waitlistSource.Where(x =>
|
||
x.Student!.StudentNumber.Contains(keyword) ||
|
||
x.Student.Name.Contains(keyword) ||
|
||
x.Student.AdministrativeClass!.Name.Contains(keyword));
|
||
}
|
||
var enrolledTotal = await enrolledSource.CountAsync(cancellationToken);
|
||
var waitlistedTotal = await waitlistSource.CountAsync(cancellationToken);
|
||
var students = await enrolledSource
|
||
.OrderBy(x => x.Student!.StudentNumber)
|
||
.Skip((studentPage - 1) * studentPageSize)
|
||
.Take(studentPageSize)
|
||
.Select(x => new
|
||
{
|
||
x.Id,
|
||
x.StudentId,
|
||
x.Student!.StudentNumber,
|
||
x.Student.Name,
|
||
ClassName = x.Student.AdministrativeClass!.Name,
|
||
MajorName = x.Student.AdministrativeClass.Major!.Name,
|
||
Grade = x.Student.AdministrativeClass.Grade,
|
||
x.EnrolledAt
|
||
})
|
||
.ToListAsync(cancellationToken);
|
||
var waitlistedRows = await waitlistSource
|
||
.OrderBy(x => x.WaitlistedAt)
|
||
.ThenBy(x => x.CreatedAt)
|
||
.Skip((waitlistPage - 1) * waitlistPageSize)
|
||
.Take(waitlistPageSize)
|
||
.Select(x => new
|
||
{
|
||
x.Id,
|
||
x.StudentId,
|
||
x.Student!.StudentNumber,
|
||
x.Student.Name,
|
||
ClassName = x.Student.AdministrativeClass!.Name,
|
||
MajorName = x.Student.AdministrativeClass.Major!.Name,
|
||
Grade = x.Student.AdministrativeClass.Grade,
|
||
x.WaitlistedAt
|
||
})
|
||
.ToListAsync(cancellationToken);
|
||
var waitlist = waitlistedRows
|
||
.Select((item, index) => new
|
||
{
|
||
item.Id,
|
||
item.StudentId,
|
||
item.StudentNumber,
|
||
item.Name,
|
||
item.ClassName,
|
||
item.MajorName,
|
||
item.Grade,
|
||
item.WaitlistedAt,
|
||
Position = (waitlistPage - 1) * waitlistPageSize + index + 1
|
||
})
|
||
.ToList();
|
||
return Ok(new
|
||
{
|
||
offering.Id,
|
||
offering.TeachingTaskId,
|
||
offering.TaskNumber,
|
||
offering.TaskName,
|
||
offering.CourseCode,
|
||
offering.CourseName,
|
||
offering.CourseNature,
|
||
offering.Capacity,
|
||
EnrolledCount = enrolledCount,
|
||
Students = students,
|
||
StudentPage = studentPage,
|
||
StudentPageSize = studentPageSize,
|
||
StudentTotal = enrolledTotal,
|
||
WaitlistedCount = waitlistedCount,
|
||
Waitlist = waitlist,
|
||
WaitlistPage = waitlistPage,
|
||
WaitlistPageSize = waitlistPageSize,
|
||
WaitlistTotal = waitlistedTotal,
|
||
FilterOptions = new
|
||
{
|
||
Grades = filterOptions.Select(x => x.Grade).Distinct().OrderBy(x => x),
|
||
Majors = filterOptions.Select(x => new { x.MajorId, x.MajorName }).Distinct()
|
||
.OrderBy(x => x.MajorName),
|
||
Classes = filterOptions.Select(x => new { x.ClassId, x.ClassName, x.MajorId })
|
||
.Distinct().OrderBy(x => x.ClassName)
|
||
},
|
||
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 &&
|
||
(currentUserDataScope.Current.IsInRole(SystemRoles.SuperAdmin) ||
|
||
currentUserDataScope.Current.IsInRole(SystemRoles.AcademicAdmin))
|
||
});
|
||
}
|
||
|
||
[HttpGet("offerings/{id:guid}/eligible-students")]
|
||
[Authorize(Roles = OfferingManagers)]
|
||
public async Task<ActionResult> GetEligibleStudents(
|
||
Guid id,
|
||
string? keyword = null,
|
||
int page = 1,
|
||
int pageSize = 20,
|
||
bool forceMode = false,
|
||
CancellationToken cancellationToken = default)
|
||
{
|
||
page = Math.Max(1, page);
|
||
pageSize = Math.Clamp(pageSize, 10, 100);
|
||
var offering = await db.CourseSelectionOfferings.AsNoTracking()
|
||
.Where(x => x.Id == id)
|
||
.Select(x => new
|
||
{
|
||
x.Id,
|
||
x.IsOpenToAll,
|
||
CourseNature = x.TeachingTask!.Course!.Nature,
|
||
CollegeId = x.TeachingTask.Course.CollegeId,
|
||
RoundStatus = x.CourseSelectionRound!.Status,
|
||
EligibleGrades = x.CourseSelectionRound.EligibleGrades
|
||
.Select(item => item.Grade),
|
||
ClassIds = x.TeachingTask.Classes
|
||
.Select(item => item.AdministrativeClassId)
|
||
})
|
||
.FirstOrDefaultAsync(cancellationToken);
|
||
if (offering is null) return NotFound();
|
||
if (!currentUserDataScope.Current.CanAccessCollege(offering.CollegeId))
|
||
return Forbid();
|
||
if (!forceMode && !CourseSelectionRules.SupportsProxyEnrollment(offering.CourseNature))
|
||
return ConflictProblem("管理员代选仅适用于公共必修课。");
|
||
if (offering.RoundStatus == CourseSelectionRoundStatus.Draft)
|
||
return ConflictProblem("选课批次开放后才能办理。");
|
||
|
||
var source = db.Students.AsNoTracking()
|
||
.Where(x =>
|
||
x.Status == StudentStatus.Active &&
|
||
!db.CourseEnrollments.Any(enrollment =>
|
||
enrollment.CourseSelectionOfferingId == id &&
|
||
enrollment.StudentId == x.Id &&
|
||
enrollment.Status == CourseEnrollmentStatus.Enrolled));
|
||
if (!forceMode && offering.EligibleGrades.Any())
|
||
{
|
||
source = source.WhereIn(
|
||
offering.EligibleGrades,
|
||
x => x.AdministrativeClass!.Grade);
|
||
}
|
||
if (!forceMode && !offering.IsOpenToAll)
|
||
source = source.WhereIn(offering.ClassIds, x => x.AdministrativeClassId);
|
||
if (!string.IsNullOrWhiteSpace(keyword))
|
||
{
|
||
keyword = keyword.Trim();
|
||
source = source.Where(x =>
|
||
x.StudentNumber.Contains(keyword) ||
|
||
x.Name.Contains(keyword) ||
|
||
x.AdministrativeClass!.Name.Contains(keyword));
|
||
}
|
||
|
||
var total = await source.CountAsync(cancellationToken);
|
||
var items = await source
|
||
.OrderBy(x => x.StudentNumber)
|
||
.Skip((page - 1) * pageSize)
|
||
.Take(pageSize)
|
||
.Select(x => new
|
||
{
|
||
x.Id,
|
||
x.StudentNumber,
|
||
x.Name,
|
||
ClassName = x.AdministrativeClass!.Name,
|
||
Grade = x.AdministrativeClass.Grade,
|
||
MajorName = x.AdministrativeClass.Major!.Name,
|
||
CollegeName = x.AdministrativeClass.Major.College!.Name
|
||
})
|
||
.ToListAsync(cancellationToken);
|
||
return Ok(new { Items = items, Total = total, Page = page, PageSize = pageSize });
|
||
}
|
||
|
||
[HttpPost("offerings/{id:guid}/admin-enrollments")]
|
||
[Authorize(Roles = RoundManagers)]
|
||
public async Task<ActionResult> AdminEnroll(
|
||
Guid id,
|
||
AdminEnrollmentRequest request,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var studentIds = request.StudentIds.Distinct().ToArray();
|
||
if (studentIds.Length == 0)
|
||
return ValidationProblem("请至少选择一名学生。");
|
||
if (studentIds.Length > 100)
|
||
return ValidationProblem("单次最多可为 100 名学生代选。");
|
||
|
||
return await db.ExecuteInRetriableTransactionAsync<ActionResult>(
|
||
async transaction =>
|
||
{
|
||
db.ChangeTracker.Clear();
|
||
var offering = await db.CourseSelectionOfferings
|
||
.Include(x => x.CourseSelectionRound)
|
||
.ThenInclude(x => x!.EligibleGrades)
|
||
.Include(x => x.TeachingTask)
|
||
.ThenInclude(x => x!.Course)
|
||
.Include(x => x.TeachingTask)
|
||
.ThenInclude(x => x!.Classes)
|
||
.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
|
||
if (offering is null) return NotFound();
|
||
var round = offering.CourseSelectionRound!;
|
||
var task = offering.TeachingTask!;
|
||
if (!CourseSelectionRules.SupportsProxyEnrollment(task.Course!.Nature))
|
||
return ConflictProblem("管理员代选仅适用于公共必修课。");
|
||
if (round.Status == CourseSelectionRoundStatus.Draft)
|
||
return ConflictProblem("选课批次开放后才能办理管理员代选。");
|
||
if (task.Status != TeachingTaskStatus.Published)
|
||
return ConflictProblem("该教学班当前不可办理代选。");
|
||
|
||
var students = await db.Students
|
||
.Include(x => x.AdministrativeClass)
|
||
.WhereIn(studentIds, x => x.Id)
|
||
.OrderBy(x => x.StudentNumber)
|
||
.ToListAsync(cancellationToken);
|
||
if (students.Count != studentIds.Length)
|
||
return ValidationProblem("存在无效的学生档案。");
|
||
if (await TeachingTaskRosterQuery.BlockedStudentIdsForTask(db, task.Id)
|
||
.AnyAsync(studentId => studentIds.Contains(studentId), cancellationToken))
|
||
return ConflictProblem("部分学生已因学籍异动退出该教学班,不能重新选入。");
|
||
var inactive = students.FirstOrDefault(x => x.Status != StudentStatus.Active);
|
||
if (inactive is not null)
|
||
return ConflictProblem(SelectionMessage($"学生 {inactive.StudentNumber} {inactive.Name} 当前不是在籍状态。", $"Student {inactive.StudentNumber} {inactive.Name} is not currently active."));
|
||
var eligibleGrades = round.EligibleGrades
|
||
.Select(x => x.Grade)
|
||
.ToArray();
|
||
var wrongGrade = students.FirstOrDefault(student =>
|
||
!CourseSelectionRules.IsGradeEligible(
|
||
eligibleGrades,
|
||
student.AdministrativeClass!.Grade));
|
||
if (wrongGrade is not null)
|
||
{
|
||
return ConflictProblem(
|
||
SelectionMessage($"学生 {wrongGrade.StudentNumber} {wrongGrade.Name} 所在年级不属于本轮选课对象。", $"Student {wrongGrade.StudentNumber} {wrongGrade.Name} is not in an eligible year for this round."));
|
||
}
|
||
var outOfScope = students.FirstOrDefault(student =>
|
||
!offering.IsOpenToAll &&
|
||
!task.Classes.Any(item =>
|
||
item.AdministrativeClassId == student.AdministrativeClassId));
|
||
if (outOfScope is not null)
|
||
{
|
||
return ConflictProblem(
|
||
SelectionMessage($"学生 {outOfScope.StudentNumber} {outOfScope.Name} 不属于该教学班的选课对象。", $"Student {outOfScope.StudentNumber} {outOfScope.Name} is not eligible for this class."));
|
||
}
|
||
|
||
var existingEnrollments = await db.CourseEnrollments
|
||
.Where(x => x.CourseSelectionOfferingId == id)
|
||
.WhereIn(studentIds, x => x.StudentId)
|
||
.ToListAsync(cancellationToken);
|
||
var alreadyEnrolled = existingEnrollments.FirstOrDefault(x =>
|
||
x.Status == CourseEnrollmentStatus.Enrolled);
|
||
if (alreadyEnrolled is not null)
|
||
{
|
||
var student = students.First(x => x.Id == alreadyEnrolled.StudentId);
|
||
return ConflictProblem(
|
||
SelectionMessage($"学生 {student.StudentNumber} {student.Name} 已在该教学班名单中。", $"Student {student.StudentNumber} {student.Name} is already on this class roster."));
|
||
}
|
||
|
||
var enrolledCount = await db.CourseEnrollments.CountAsync(
|
||
x =>
|
||
x.CourseSelectionOfferingId == id &&
|
||
x.Status == CourseEnrollmentStatus.Enrolled,
|
||
cancellationToken);
|
||
if (enrolledCount + students.Count > offering.Capacity)
|
||
{
|
||
return ConflictProblem(
|
||
SelectionMessage($"教学班仅剩 {Math.Max(0, offering.Capacity - enrolledCount)} 个名额,无法完成本次代选。", $"Only {Math.Max(0, offering.Capacity - enrolledCount)} places remain; this enrollment cannot be completed."));
|
||
}
|
||
|
||
var duplicateStudentIds = await db.CourseEnrollments.AsNoTracking()
|
||
.Where(x =>
|
||
x.Status == CourseEnrollmentStatus.Enrolled &&
|
||
x.CourseSelectionOffering!.TeachingTask!.CourseId == task.CourseId &&
|
||
x.CourseSelectionOffering.CourseSelectionRound!.AcademicTermId ==
|
||
round.AcademicTermId)
|
||
.WhereIn(studentIds, x => x.StudentId)
|
||
.Select(x => x.StudentId)
|
||
.Distinct()
|
||
.ToListAsync(cancellationToken);
|
||
if (duplicateStudentIds.Count > 0)
|
||
{
|
||
var student = students.First(x => duplicateStudentIds.Contains(x.Id));
|
||
return ConflictProblem(
|
||
SelectionMessage($"学生 {student.StudentNumber} {student.Name} 本学期已选择相同课程。", $"Student {student.StudentNumber} {student.Name} has already selected this course in this term."));
|
||
}
|
||
|
||
var candidateEntries = await PublishedScheduleEntries(
|
||
round.AcademicTermId,
|
||
[task.Id],
|
||
cancellationToken);
|
||
if (CourseSelectionRules.RequiresPublishedSchedule(task.SchedulingMode) &&
|
||
candidateEntries.Count == 0)
|
||
return ConflictProblem("该教学班尚未发布课表,暂时不能办理代选。");
|
||
|
||
foreach (var student in students)
|
||
{
|
||
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 ConflictProblem(
|
||
SelectionMessage($"学生 {student.StudentNumber} {student.Name} 代选后将超过本轮 {round.MaxCredits:0.#} 学分上限。", $"Enrolling student {student.StudentNumber} {student.Name} would exceed the round limit of {round.MaxCredits:0.#} credits."));
|
||
}
|
||
var selectedCourseCount = await db.CourseEnrollments.CountAsync(
|
||
x =>
|
||
x.StudentId == student.Id &&
|
||
x.Status == CourseEnrollmentStatus.Enrolled &&
|
||
x.CourseSelectionOffering!.CourseSelectionRoundId == round.Id,
|
||
cancellationToken);
|
||
if (CourseSelectionRules.HasReachedCourseLimit(
|
||
round.MaxCourseCount,
|
||
selectedCourseCount))
|
||
{
|
||
return ConflictProblem(
|
||
SelectionMessage($"学生 {student.StudentNumber} {student.Name} 已达到本轮最多 {round.MaxCourseCount} 门课程限制。", $"Student {student.StudentNumber} {student.Name} has reached the round limit of {round.MaxCourseCount} courses."));
|
||
}
|
||
|
||
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))
|
||
{
|
||
return ConflictProblem(
|
||
SelectionMessage($"学生 {student.StudentNumber} {student.Name} 的已选课程与该教学班时间冲突。", $"Student {student.StudentNumber} {student.Name} has a scheduling conflict with this class."));
|
||
}
|
||
}
|
||
|
||
var now = DateTime.UtcNow;
|
||
foreach (var student in students)
|
||
{
|
||
var enrollment = existingEnrollments.FirstOrDefault(x =>
|
||
x.StudentId == student.Id);
|
||
if (enrollment is null)
|
||
{
|
||
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);
|
||
await transaction.CommitAsync(cancellationToken);
|
||
return Ok(new { EnrolledCount = students.Count });
|
||
},
|
||
cancellationToken,
|
||
IsolationLevel.Serializable);
|
||
}
|
||
|
||
[HttpPost("offerings/{offeringId:guid}/force-enroll")]
|
||
[Authorize(Roles = OfferingManagers)]
|
||
public async Task<ActionResult> ForceEnroll(
|
||
Guid offeringId,
|
||
ForceEnrollmentRequest request,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var studentIds = request.StudentIds.Distinct().ToArray();
|
||
if (studentIds.Length == 0)
|
||
return ValidationProblem("请至少选择一名学生。");
|
||
if (studentIds.Length > 100)
|
||
return ValidationProblem("单次最多可为 100 名学生强制选课。");
|
||
|
||
return await db.ExecuteInRetriableTransactionAsync<ActionResult>(
|
||
async transaction =>
|
||
{
|
||
db.ChangeTracker.Clear();
|
||
var offering = await db.CourseSelectionOfferings
|
||
.Include(x => x.CourseSelectionRound)
|
||
.Include(x => x.TeachingTask)
|
||
.ThenInclude(x => x!.Course)
|
||
.FirstOrDefaultAsync(x => x.Id == offeringId, cancellationToken);
|
||
if (offering is null) return NotFound();
|
||
var round = offering.CourseSelectionRound!;
|
||
var task = offering.TeachingTask!;
|
||
if (!currentUserDataScope.Current.CanAccessCollege(task.Course!.CollegeId))
|
||
return Forbid();
|
||
|
||
if (round.Status == CourseSelectionRoundStatus.Draft)
|
||
return ConflictProblem("选课批次开放后才能办理强制选课。");
|
||
if (task.Status != TeachingTaskStatus.Published)
|
||
return ConflictProblem("该教学班当前不可选。");
|
||
|
||
var students = await db.Students
|
||
.Include(x => x.AdministrativeClass)
|
||
.WhereIn(studentIds, x => x.Id)
|
||
.OrderBy(x => x.StudentNumber)
|
||
.ToListAsync(cancellationToken);
|
||
if (students.Count != studentIds.Length)
|
||
return ValidationProblem("存在无效的学生档案。");
|
||
if (students.Any(x => x.Status != StudentStatus.Active))
|
||
return ConflictProblem("只有在籍学生可以办理强制选课。");
|
||
if (await TeachingTaskRosterQuery.BlockedStudentIdsForTask(db, task.Id)
|
||
.AnyAsync(studentId => studentIds.Contains(studentId), cancellationToken))
|
||
return ConflictProblem("部分学生已因学籍异动退出该教学班,不能重新选入。");
|
||
|
||
var existingEnrollments = await db.CourseEnrollments
|
||
.Where(x => x.CourseSelectionOfferingId == offeringId)
|
||
.WhereIn(studentIds, x => x.StudentId)
|
||
.ToListAsync(cancellationToken);
|
||
var alreadyEnrolled = existingEnrollments
|
||
.FirstOrDefault(x => x.Status == CourseEnrollmentStatus.Enrolled);
|
||
if (alreadyEnrolled is not null)
|
||
{
|
||
var dup = students.First(x => x.Id == alreadyEnrolled.StudentId);
|
||
return ConflictProblem(
|
||
SelectionMessage($"学生 {dup.StudentNumber} {dup.Name} 已在该教学班名单中。", $"Student {dup.StudentNumber} {dup.Name} is already on this class roster."));
|
||
}
|
||
|
||
var now = DateTime.UtcNow;
|
||
var enrolled = 0;
|
||
foreach (var student in students)
|
||
{
|
||
var isRetake = await IsEligibleForRetakeAsync(
|
||
student.Id, task.CourseId, round.AcademicTermId, cancellationToken);
|
||
var enrollment = existingEnrollments
|
||
.FirstOrDefault(x => x.StudentId == student.Id);
|
||
if (enrollment is null)
|
||
{
|
||
enrollment = new CourseEnrollment
|
||
{
|
||
CourseSelectionOfferingId = offeringId,
|
||
StudentId = student.Id,
|
||
EnrollmentType = isRetake ? EnrollmentType.Retake : EnrollmentType.Normal,
|
||
EnrolledAt = now
|
||
};
|
||
db.CourseEnrollments.Add(enrollment);
|
||
}
|
||
else
|
||
{
|
||
enrollment.Status = CourseEnrollmentStatus.Enrolled;
|
||
enrollment.EnrolledAt = now;
|
||
enrollment.WaitlistedAt = null;
|
||
enrollment.WithdrawnAt = null;
|
||
enrollment.EnrollmentType = isRetake ? EnrollmentType.Retake : EnrollmentType.Normal;
|
||
}
|
||
await ExpireOtherWaitlistsForCourseAsync(
|
||
student.Id,
|
||
task.CourseId,
|
||
round.AcademicTermId,
|
||
enrollment.Id,
|
||
now,
|
||
cancellationToken);
|
||
enrolled++;
|
||
}
|
||
|
||
await db.SaveChangesAsync(cancellationToken);
|
||
await transaction.CommitAsync(cancellationToken);
|
||
return Ok(new { EnrolledCount = enrolled });
|
||
},
|
||
cancellationToken,
|
||
IsolationLevel.Serializable);
|
||
}
|
||
|
||
[HttpDelete("offerings/{offeringId:guid}/admin-enrollments/{enrollmentId:guid}")]
|
||
[Authorize(Roles = RoundManagers)]
|
||
public async Task<ActionResult> AdminWithdraw(
|
||
Guid offeringId,
|
||
Guid enrollmentId,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
return await db.ExecuteInRetriableTransactionAsync<ActionResult>(
|
||
async transaction =>
|
||
{
|
||
db.ChangeTracker.Clear();
|
||
var enrollment = await db.CourseEnrollments
|
||
.Include(x => x.CourseSelectionOffering)
|
||
.ThenInclude(x => x!.CourseSelectionRound)
|
||
.ThenInclude(x => x!.EligibleGrades)
|
||
.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;
|
||
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}”" +
|
||
"候补队列。",
|
||
Category = NotificationCategory.CourseSelection,
|
||
LinkUrl = "/course-selections"
|
||
});
|
||
}
|
||
await db.SaveChangesAsync(cancellationToken);
|
||
await transaction.CommitAsync(cancellationToken);
|
||
return NoContent();
|
||
},
|
||
cancellationToken,
|
||
IsolationLevel.Serializable);
|
||
}
|
||
|
||
[HttpGet("student/options")]
|
||
[Authorize(Roles = SystemRoles.Student)]
|
||
public async Task<ActionResult> GetStudentOptions(
|
||
Guid roundId,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var student = await CurrentStudentAsync(cancellationToken);
|
||
if (student is null) return ProfileNotFound();
|
||
var round = await db.CourseSelectionRounds.AsNoTracking()
|
||
.Include(x => x.EligibleGrades)
|
||
.FirstOrDefaultAsync(x => x.Id == roundId, cancellationToken);
|
||
if (round is null || round.Status == CourseSelectionRoundStatus.Draft)
|
||
return NotFound();
|
||
var eligibleGrades = round.EligibleGrades
|
||
.Select(x => x.Grade)
|
||
.ToArray();
|
||
if (!CourseSelectionRules.IsGradeEligible(
|
||
eligibleGrades,
|
||
student.AdministrativeClass!.Grade))
|
||
{
|
||
return Forbid();
|
||
}
|
||
var retakeCourseIds = await RetakeCourseIdsAsync(
|
||
student.Id,
|
||
round.AcademicTermId,
|
||
cancellationToken);
|
||
|
||
var offerings = await db.CourseSelectionOfferings.AsNoTracking()
|
||
.Where(x =>
|
||
x.CourseSelectionRoundId == roundId &&
|
||
x.TeachingTask!.Status == TeachingTaskStatus.Published &&
|
||
(x.IsOpenToAll ||
|
||
x.TeachingTask.Classes.Any(item =>
|
||
item.AdministrativeClassId == student.AdministrativeClassId) ||
|
||
x.Enrollments.Any(item =>
|
||
item.StudentId == student.Id &&
|
||
(item.Status == CourseEnrollmentStatus.Enrolled ||
|
||
item.Status == CourseEnrollmentStatus.Waitlisted))))
|
||
.OrderBy(x => x.TeachingTask!.Course!.Code)
|
||
.Select(x => new StudentOfferingDto(
|
||
x.Id,
|
||
x.TeachingTaskId,
|
||
x.TeachingTask!.TaskNumber,
|
||
x.TeachingTask.Course!.Code,
|
||
x.TeachingTask.Course.Name,
|
||
x.TeachingTask.Course.Credits,
|
||
x.TeachingTask.Teachers
|
||
.OrderByDescending(item => item.IsPrimary)
|
||
.Select(item => item.Teacher!.Name),
|
||
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)
|
||
.Select(item => (CourseEnrollmentStatus?)item.Status)
|
||
.FirstOrDefault(),
|
||
x.TeachingTask.SchedulingMode == TeachingTaskSchedulingMode.Flexible,
|
||
retakeCourseIds.Contains(x.TeachingTask.CourseId),
|
||
db.ScheduleEntries
|
||
.Where(entry =>
|
||
entry.TeachingTaskId == x.TeachingTaskId &&
|
||
entry.SchedulePlan!.AcademicTermId == round.AcademicTermId &&
|
||
entry.SchedulePlan.Status == SchedulePlanStatus.Published)
|
||
.OrderBy(entry => entry.DayOfWeek)
|
||
.ThenBy(entry => entry.StartPeriod)
|
||
.Select(entry => new StudentScheduleDto(
|
||
entry.DayOfWeek,
|
||
entry.StartPeriod,
|
||
entry.PeriodCount,
|
||
entry.StartWeek,
|
||
entry.EndWeek,
|
||
entry.WeekPattern,
|
||
entry.Classroom == null ? "不占用教室" : entry.Classroom.Name))
|
||
.ToList(),
|
||
null))
|
||
.ToListAsync(cancellationToken);
|
||
|
||
if (round.Scope == CourseSelectionScope.RetakeOnly)
|
||
{
|
||
offerings = offerings.Where(x =>
|
||
x.IsRetake ||
|
||
x.EnrollmentStatus == CourseEnrollmentStatus.Enrolled ||
|
||
x.EnrollmentStatus == CourseEnrollmentStatus.Waitlisted)
|
||
.ToList();
|
||
}
|
||
|
||
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
|
||
{
|
||
round.Id,
|
||
round.Name,
|
||
round.StartsAt,
|
||
round.EndsAt,
|
||
round.WithdrawalEndsAt,
|
||
round.MaxCredits,
|
||
round.MaxCourseCount,
|
||
round.Scope,
|
||
EligibleGrades = eligibleGrades,
|
||
round.Status,
|
||
IsAvailableNow = CourseSelectionRules.IsSelectionOpen(
|
||
round,
|
||
DateTime.UtcNow)
|
||
},
|
||
Student = new
|
||
{
|
||
student.Id,
|
||
student.StudentNumber,
|
||
student.Name,
|
||
ClassName = student.AdministrativeClass!.Name,
|
||
Grade = student.AdministrativeClass.Grade
|
||
},
|
||
Offerings = offerings
|
||
});
|
||
}
|
||
|
||
[HttpGet("student/enrollments")]
|
||
[Authorize(Roles = SystemRoles.Student)]
|
||
public async Task<ActionResult> GetStudentEnrollments(
|
||
Guid? academicTermId,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var student = await CurrentStudentAsync(cancellationToken);
|
||
if (student is null) return ProfileNotFound();
|
||
var source = db.CourseEnrollments.AsNoTracking()
|
||
.Where(x => x.StudentId == student.Id);
|
||
if (academicTermId.HasValue)
|
||
{
|
||
source = source.Where(x =>
|
||
x.CourseSelectionOffering!.CourseSelectionRound!.AcademicTermId ==
|
||
academicTermId);
|
||
}
|
||
return Ok(await source
|
||
.OrderByDescending(x => x.EnrolledAt)
|
||
.Select(x => new
|
||
{
|
||
x.Id,
|
||
x.CourseSelectionOfferingId,
|
||
RoundId = x.CourseSelectionOffering!.CourseSelectionRoundId,
|
||
RoundName = x.CourseSelectionOffering.CourseSelectionRound!.Name,
|
||
TermName = x.CourseSelectionOffering.CourseSelectionRound.AcademicTerm!.Name,
|
||
x.CourseSelectionOffering.TeachingTaskId,
|
||
TaskNumber = x.CourseSelectionOffering.TeachingTask!.TaskNumber,
|
||
CourseCode = x.CourseSelectionOffering.TeachingTask.Course!.Code,
|
||
CourseName = x.CourseSelectionOffering.TeachingTask.Course.Name,
|
||
x.CourseSelectionOffering.TeachingTask.Course.Credits,
|
||
TeacherNames = x.CourseSelectionOffering.TeachingTask.Teachers
|
||
.OrderByDescending(item => item.IsPrimary)
|
||
.Select(item => item.Teacher!.Name),
|
||
x.Status,
|
||
x.EnrollmentType,
|
||
x.EnrolledAt,
|
||
x.WaitlistedAt,
|
||
x.WaitlistResolvedAt,
|
||
x.WaitlistResolutionReason,
|
||
x.WithdrawnAt,
|
||
CanWithdraw =
|
||
(x.Status == CourseEnrollmentStatus.Enrolled ||
|
||
x.Status == CourseEnrollmentStatus.Waitlisted) &&
|
||
x.CourseSelectionOffering.CourseSelectionRound.Status ==
|
||
CourseSelectionRoundStatus.Open &&
|
||
DateTime.UtcNow <=
|
||
x.CourseSelectionOffering.CourseSelectionRound.WithdrawalEndsAt
|
||
})
|
||
.ToListAsync(cancellationToken));
|
||
}
|
||
|
||
[HttpPost("student/enrollments")]
|
||
[Authorize(Roles = SystemRoles.Student)]
|
||
public async Task<ActionResult> Enroll(
|
||
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();
|
||
if (student.Status != StudentStatus.Active)
|
||
return ConflictProblem("只有在籍学生可以选课。");
|
||
|
||
var offering = await db.CourseSelectionOfferings
|
||
.Include(x => x.CourseSelectionRound)
|
||
.ThenInclude(x => x!.EligibleGrades)
|
||
.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 task = offering.TeachingTask!;
|
||
if (await TeachingTaskRosterQuery.BlockedStudentIdsForTask(db, task.Id)
|
||
.ContainsAsync(student.Id, cancellationToken))
|
||
return ConflictProblem("该教学班已因学籍异动退出,请选择其他教学班。");
|
||
var now = DateTime.UtcNow;
|
||
if (!CourseSelectionRules.IsSelectionOpen(round, now))
|
||
return ConflictProblem("当前不在该选课批次的开放时间内。");
|
||
if (task.Status != TeachingTaskStatus.Published)
|
||
return ConflictProblem("该教学班当前不可选。");
|
||
if (!CourseSelectionRules.IsGradeEligible(
|
||
round.EligibleGrades.Select(x => x.Grade),
|
||
student.AdministrativeClass!.Grade))
|
||
{
|
||
return ConflictProblem("你所在的年级不属于本轮选课对象。");
|
||
}
|
||
if (!offering.IsOpenToAll &&
|
||
!task.Classes.Any(x =>
|
||
x.AdministrativeClassId == student.AdministrativeClassId))
|
||
return Forbid();
|
||
|
||
var isRetake = await IsEligibleForRetakeAsync(
|
||
student.Id,
|
||
task.CourseId,
|
||
round.AcademicTermId,
|
||
cancellationToken);
|
||
if (round.Scope == CourseSelectionScope.RetakeOnly && !isRetake)
|
||
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("你已经选择了该教学班。");
|
||
|
||
var enrolledCount = await db.CourseEnrollments.CountAsync(
|
||
x =>
|
||
x.CourseSelectionOfferingId == offering.Id &&
|
||
x.Status == CourseEnrollmentStatus.Enrolled,
|
||
cancellationToken);
|
||
var effectiveCapacity = CourseSelectionRules.EffectiveCapacity(
|
||
offering.Capacity,
|
||
isRetake);
|
||
if (enrolledCount >= effectiveCapacity)
|
||
return ConflictProblem("该教学班名额已满。");
|
||
|
||
// Normal enrollment: no duplicate course in same term
|
||
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 ConflictProblem("同一学期不能重复选择相同课程。");
|
||
}
|
||
|
||
// Credit limit check
|
||
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 ConflictProblem(
|
||
SelectionMessage($"选课后将达到 {selectedCredits + task.Course.Credits:0.#} 学分,超过本轮 {round.MaxCredits:0.#} 学分上限。", $"Enrollment would total {selectedCredits + task.Course.Credits:0.#} credits, exceeding the round limit of {round.MaxCredits:0.#}."));
|
||
}
|
||
var selectedCourseCount = await db.CourseEnrollments.CountAsync(
|
||
x =>
|
||
x.StudentId == student.Id &&
|
||
x.Status == CourseEnrollmentStatus.Enrolled &&
|
||
x.CourseSelectionOffering!.CourseSelectionRoundId == round.Id,
|
||
cancellationToken);
|
||
if (CourseSelectionRules.HasReachedCourseLimit(
|
||
round.MaxCourseCount,
|
||
selectedCourseCount))
|
||
{
|
||
return ConflictProblem(
|
||
SelectionMessage($"你已达到本轮最多 {round.MaxCourseCount} 门课程限制。", $"You have reached the limit of {round.MaxCourseCount} courses for this round."));
|
||
}
|
||
|
||
// Schedule conflict check
|
||
var candidateEntries = await PublishedScheduleEntries(
|
||
round.AcademicTermId, [task.Id], cancellationToken);
|
||
if (CourseSelectionRules.RequiresPublishedSchedule(task.SchedulingMode) &&
|
||
candidateEntries.Count == 0)
|
||
return ConflictProblem("该教学班尚未发布课表,暂时不能选课。");
|
||
|
||
var selectedTaskIds = await db.CourseEnrollments
|
||
.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 ConflictProblem("该教学班与已选课程的上课时间冲突。");
|
||
|
||
// Retake: allow ≤50% overlap
|
||
var overlap = CourseSelectionRules.CalculateScheduleOverlap(
|
||
candidateEntries, selectedEntries);
|
||
if (overlap > 50)
|
||
return ConflictProblem(
|
||
SelectionMessage($"重修课程时间冲突 {overlap:F0}%,超过 50% 上限,无法选课。", $"The retake overlaps by {overlap:F0}%, exceeding the 50% limit."));
|
||
}
|
||
|
||
if (existing is null)
|
||
{
|
||
existing = new CourseEnrollment
|
||
{
|
||
CourseSelectionOfferingId = offering.Id,
|
||
StudentId = student.Id,
|
||
EnrollmentType = isRetake ? EnrollmentType.Retake : EnrollmentType.Normal
|
||
};
|
||
db.CourseEnrollments.Add(existing);
|
||
}
|
||
else
|
||
{
|
||
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 });
|
||
},
|
||
cancellationToken,
|
||
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)
|
||
.ThenInclude(x => x!.EligibleGrades)
|
||
.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(SelectionMessage(eligibility.Error, eligibility.EnglishError ?? LocalizeSelectionError(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.WaitlistResolvedAt = null;
|
||
existing.WaitlistResolutionReason = null;
|
||
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)
|
||
{
|
||
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)
|
||
.ThenInclude(x => x!.EligibleGrades)
|
||
.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")]
|
||
[Authorize(Roles = SystemRoles.Teacher)]
|
||
public async Task<ActionResult> GetMyOfferings(
|
||
Guid? academicTermId,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var userId = currentUserDataScope.Current.UserId;
|
||
var offeringsQuery = db.CourseSelectionOfferings.AsNoTracking()
|
||
.Where(x =>
|
||
x.TeachingTask!.Teachers.Any(t =>
|
||
t.Teacher!.UserId == userId) &&
|
||
x.CourseSelectionRound!.Status != CourseSelectionRoundStatus.Draft);
|
||
if (academicTermId.HasValue)
|
||
offeringsQuery = offeringsQuery.Where(x =>
|
||
x.CourseSelectionRound!.AcademicTermId == academicTermId);
|
||
var offerings = await offeringsQuery
|
||
.OrderByDescending(x => x.CourseSelectionRound!.AcademicTerm!.StartDate)
|
||
.ThenBy(x => x.TeachingTask!.Course!.Code)
|
||
.Select(x => new
|
||
{
|
||
x.Id,
|
||
x.TeachingTaskId,
|
||
x.TeachingTask!.TaskNumber,
|
||
TaskName = x.TeachingTask.Name,
|
||
x.TeachingTask.AcademicTermId,
|
||
TermName = x.TeachingTask.AcademicTerm!.Name,
|
||
CourseCode = x.TeachingTask.Course!.Code,
|
||
CourseName = x.TeachingTask.Course.Name,
|
||
RoundName = x.CourseSelectionRound!.Name,
|
||
x.Capacity,
|
||
EnrolledCount = x.Enrollments.Count(e =>
|
||
e.Status == CourseEnrollmentStatus.Enrolled),
|
||
RoundStatus = x.CourseSelectionRound.Status
|
||
})
|
||
.ToListAsync(cancellationToken);
|
||
return Ok(offerings);
|
||
}
|
||
|
||
[HttpGet("my-moodle-courses")]
|
||
[Authorize(Roles = SystemRoles.Student)]
|
||
public async Task<ActionResult> GetMyMoodleCourses(Guid academicTermId, CancellationToken cancellationToken)
|
||
{
|
||
var student = await CurrentStudentAsync(cancellationToken);
|
||
if (student is null) return ProfileNotFound();
|
||
var taskIds = TeachingTaskRosterQuery.TaskIdsForStudent(db, student.Id);
|
||
var courses = await db.TeachingTasks.AsNoTracking()
|
||
.Where(x => x.AcademicTermId == academicTermId && x.Status == TeachingTaskStatus.Published &&
|
||
x.MoodleCourseUrl != null && taskIds.Contains(x.Id))
|
||
.OrderBy(x => x.Course!.Code).ThenBy(x => x.TaskNumber)
|
||
.Select(x => new { x.Id, x.TaskNumber, TaskName = x.Name, CourseName = x.Course!.Name, x.MoodleCourseUrl })
|
||
.ToListAsync(cancellationToken);
|
||
return Ok(courses);
|
||
}
|
||
|
||
[HttpGet("my-teaching-tasks")]
|
||
[Authorize(Roles = SystemRoles.Teacher + "," + SystemRoles.SuperAdmin)]
|
||
public async Task<ActionResult> GetMyTeachingTasks(
|
||
Guid? academicTermId,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var userId = currentUserDataScope.Current.UserId;
|
||
var isSuperAdmin = currentUserDataScope.Current.IsInRole(SystemRoles.SuperAdmin);
|
||
var source = db.TeachingTasks.AsNoTracking()
|
||
.Where(x =>
|
||
(x.Status == TeachingTaskStatus.Published ||
|
||
x.Status == TeachingTaskStatus.Closed) &&
|
||
(isSuperAdmin || x.Teachers.Any(item => item.Teacher!.UserId == userId)));
|
||
if (academicTermId.HasValue)
|
||
source = source.Where(x => x.AcademicTermId == academicTermId);
|
||
|
||
var interruptedPairs = TeachingTaskRosterQuery.InterruptedPairs(db);
|
||
return Ok(await source
|
||
.OrderByDescending(x => x.AcademicTerm!.StartDate)
|
||
.ThenBy(x => x.Course!.Code)
|
||
.ThenBy(x => x.TaskNumber)
|
||
.Select(x => new
|
||
{
|
||
x.Id,
|
||
x.TaskNumber,
|
||
TaskName = x.Name,
|
||
x.MoodleCourseUrl,
|
||
x.Status,
|
||
x.AcademicTermId,
|
||
TermName = x.AcademicTerm!.Name,
|
||
CourseCode = x.Course!.Code,
|
||
CourseName = x.Course.Name,
|
||
x.Capacity,
|
||
StudentCount = db.Students.Count(student =>
|
||
student.Status == StudentStatus.Active &&
|
||
!db.StudentStatusChangeCourseEffects.Any(effect => effect.StudentId == student.Id && effect.TeachingTaskId == x.Id) &&
|
||
!interruptedPairs.Any(pair => pair.StudentId == student.Id && pair.TeachingTaskId == x.Id) &&
|
||
(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)))
|
||
})
|
||
.ToListAsync(cancellationToken));
|
||
}
|
||
|
||
[HttpGet("teaching-tasks/{id:guid}/roster")]
|
||
[Authorize(Roles = SystemRoles.Teacher + "," + SystemRoles.SuperAdmin)]
|
||
public async Task<ActionResult> GetTeachingTaskRoster(
|
||
Guid id,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var task = await GetAssignedTeachingTaskAsync(id, cancellationToken);
|
||
if (task is null) return NotFound();
|
||
|
||
var students = await LoadTeachingTaskRosterAsync(id, cancellationToken);
|
||
return Ok(new
|
||
{
|
||
task.Id,
|
||
task.TaskNumber,
|
||
task.TaskName,
|
||
task.CourseCode,
|
||
task.CourseName,
|
||
task.Capacity,
|
||
StudentCount = students.Count,
|
||
Students = students
|
||
});
|
||
}
|
||
|
||
[HttpGet("teaching-tasks/{id:guid}/roster/export.xlsx")]
|
||
[Authorize(Roles = SystemRoles.Teacher + "," + SystemRoles.SuperAdmin)]
|
||
[ProducesResponseType<FileContentResult>(StatusCodes.Status200OK, ExcelWorkbookHelper.ContentType)]
|
||
public async Task<ActionResult> ExportTeachingTaskRoster(
|
||
Guid id,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var task = await GetAssignedTeachingTaskAsync(id, cancellationToken);
|
||
if (task is null) return NotFound();
|
||
|
||
var students = await LoadTeachingTaskRosterAsync(id, cancellationToken);
|
||
var bytes = ExcelWorkbookHelper.Create(
|
||
"教学班名单",
|
||
[
|
||
"学号", "姓名", "班级", "专业", "联系电话", "电子邮箱",
|
||
"微信", "紧急联系人", "与本人关系", "紧急联系电话",
|
||
"特殊标记", "特殊情况说明", "进入方式", "选课时间"
|
||
, "学期", "课程代码", "课程名称", "教学班编号", "教学班名称", "学院", "入学年份", "性别"
|
||
],
|
||
students.Select(student => new List<object?>
|
||
{
|
||
student.StudentNumber,
|
||
student.Name,
|
||
student.ClassName,
|
||
student.MajorName,
|
||
student.Phone,
|
||
student.Email,
|
||
student.WeChat,
|
||
student.EmergencyContactName,
|
||
student.EmergencyContactRelationship,
|
||
student.EmergencyContactPhone,
|
||
student.SpecialTags,
|
||
student.SpecialNeeds,
|
||
student.EnrolledAt.HasValue ? "选课" : "行政班关联",
|
||
student.EnrolledAt?.ToString("yyyy-MM-dd HH:mm") ?? "-",
|
||
task.TermName, task.CourseCode, task.CourseName, task.TaskNumber, task.TaskName,
|
||
student.CollegeName, student.EnrollmentYear, student.Gender switch { Gender.Male => "男", Gender.Female => "女", _ => "未知" }
|
||
}).ToList<IReadOnlyList<object?>>());
|
||
return File(
|
||
bytes,
|
||
ExcelWorkbookHelper.ContentType,
|
||
DownloadFileName.Export("教学班名单", ".xlsx", task.TaskNumber));
|
||
}
|
||
|
||
[HttpGet("teaching-tasks/{id:guid}/roster/moodle.csv")]
|
||
[Authorize(Roles = SystemRoles.Teacher + "," + SystemRoles.SuperAdmin)]
|
||
public async Task<ActionResult> ExportMoodleRoster(Guid id, [FromQuery] string courseShortName,
|
||
[FromQuery] string? groupName, [FromQuery] bool includeTeachers, [FromQuery] string? teacherRole, CancellationToken cancellationToken)
|
||
{
|
||
var task = await GetAssignedTeachingTaskAsync(id, cancellationToken);
|
||
if (task is null) return NotFound();
|
||
courseShortName = courseShortName?.Trim() ?? "";
|
||
groupName = groupName?.Trim();
|
||
teacherRole = teacherRole?.Trim();
|
||
if (courseShortName.Length == 0 || courseShortName.Length > 255 || groupName?.Length > 255 ||
|
||
(!string.IsNullOrEmpty(groupName) && long.TryParse(groupName, out _)) ||
|
||
(includeTeachers && (string.IsNullOrEmpty(teacherRole) || teacherRole.Length > 100 || long.TryParse(teacherRole, out _))))
|
||
return BadRequest(new ProblemDetails { Detail = "请填写有效的 Moodle 课程简称;分组名称和教师角色短名称不能为纯数字,导出教师时须填写角色短名称。", Status = 400 });
|
||
|
||
var students = await LoadTeachingTaskRosterAsync(id, cancellationToken);
|
||
var entries = students.Select(x => (Username: x.StudentNumber.Trim().ToLowerInvariant(), Role: "student")).ToList();
|
||
if (includeTeachers)
|
||
{
|
||
var teachers = await db.TeachingTasks.AsNoTracking().Where(x => x.Id == id)
|
||
.SelectMany(x => x.Teachers.Select(t => t.Teacher!.TeacherNumber)).ToListAsync(cancellationToken);
|
||
entries.AddRange(teachers.Select(x => (x.Trim().ToLowerInvariant(), teacherRole!)));
|
||
}
|
||
if (entries.Any(x => string.IsNullOrWhiteSpace(x.Username)) || entries.Select(x => x.Username).Distinct(StringComparer.Ordinal).Count() != entries.Count)
|
||
return BadRequest(new ProblemDetails { Detail = "人员编号为空或转为小写后重复,无法安全导出 Moodle 名单。", Status = 400 });
|
||
|
||
static string Csv(string value) => "\"" + value.Replace("\"", "\"\"") + "\"";
|
||
var csv = new StringBuilder("username,course1,role1,group1\r\n");
|
||
foreach (var entry in entries)
|
||
csv.AppendJoin(',', Csv(entry.Username), Csv(courseShortName), Csv(entry.Role), Csv(groupName ?? "")).Append("\r\n");
|
||
var content = Encoding.UTF8.GetPreamble().Concat(Encoding.UTF8.GetBytes(csv.ToString())).ToArray();
|
||
return File(content, "text/csv; charset=utf-8", DownloadFileName.Export("Moodle名单", ".csv", task.TaskNumber));
|
||
}
|
||
|
||
[HttpGet("offerings/{id:guid}/roster/export.xlsx")]
|
||
[Authorize(Roles = RosterReaders)]
|
||
[ProducesResponseType<FileContentResult>(StatusCodes.Status200OK, ExcelWorkbookHelper.ContentType)]
|
||
public async Task<ActionResult> ExportRoster(
|
||
Guid id,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var offering = await db.CourseSelectionOfferings.AsNoTracking()
|
||
.Where(x => x.Id == id)
|
||
.Select(x => new
|
||
{
|
||
x.Id,
|
||
x.TeachingTask!.TaskNumber,
|
||
CourseCode = x.TeachingTask.Course!.Code,
|
||
CourseName = x.TeachingTask.Course.Name,
|
||
RoundName = x.CourseSelectionRound!.Name,
|
||
CollegeId = x.TeachingTask.Course.CollegeId,
|
||
TeacherUserIds = x.TeachingTask.Teachers
|
||
.Select(item => item.Teacher!.UserId)
|
||
})
|
||
.FirstOrDefaultAsync(cancellationToken);
|
||
if (offering is null) return NotFound();
|
||
|
||
var scope = currentUserDataScope.Current;
|
||
var isAssignedTeacher =
|
||
scope.IsInRole(SystemRoles.Teacher) &&
|
||
offering.TeacherUserIds.Contains(scope.UserId);
|
||
if (!isAssignedTeacher && !scope.CanAccessCollege(offering.CollegeId))
|
||
return Forbid();
|
||
|
||
var students = await db.CourseEnrollments.AsNoTracking()
|
||
.Where(x =>
|
||
x.CourseSelectionOfferingId == id &&
|
||
x.Status == CourseEnrollmentStatus.Enrolled)
|
||
.OrderBy(x => x.Student!.StudentNumber)
|
||
.Select(x => new
|
||
{
|
||
x.Student!.StudentNumber,
|
||
x.Student.Name,
|
||
ClassName = x.Student.AdministrativeClass!.Name,
|
||
MajorName = x.Student.AdministrativeClass.Major!.Name,
|
||
x.EnrolledAt
|
||
})
|
||
.ToListAsync(cancellationToken);
|
||
|
||
var bytes = ExcelWorkbookHelper.Create(
|
||
"选课名单",
|
||
["学号", "姓名", "班级", "专业", "选课时间"],
|
||
students.Select(s => new List<object?>
|
||
{
|
||
s.StudentNumber, s.Name, s.ClassName, s.MajorName,
|
||
s.EnrolledAt.ToString("yyyy-MM-dd HH:mm")
|
||
}).ToList<IReadOnlyList<object?>>());
|
||
return File(bytes, ExcelWorkbookHelper.ContentType,
|
||
DownloadFileName.Export("选课名单", ".xlsx", offering.TaskNumber));
|
||
}
|
||
|
||
private IQueryable<CourseSelectionOffering> ScopedOfferings()
|
||
{
|
||
var source = db.CourseSelectionOfferings.AsQueryable();
|
||
var scope = currentUserDataScope.Current;
|
||
return scope.Scope == DataScope.All
|
||
? source
|
||
: source.Where(x =>
|
||
x.TeachingTask!.Course!.CollegeId == scope.RestrictedCollegeId);
|
||
}
|
||
|
||
private Task<TeacherTeachingTaskInfo?> GetAssignedTeachingTaskAsync(
|
||
Guid id,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var userId = currentUserDataScope.Current.UserId;
|
||
var isSuperAdmin = currentUserDataScope.Current.IsInRole(SystemRoles.SuperAdmin);
|
||
return db.TeachingTasks.AsNoTracking()
|
||
.Where(x =>
|
||
x.Id == id &&
|
||
(x.Status == TeachingTaskStatus.Published ||
|
||
x.Status == TeachingTaskStatus.Closed) &&
|
||
(isSuperAdmin || x.Teachers.Any(item => item.Teacher!.UserId == userId)))
|
||
.Select(x => new TeacherTeachingTaskInfo(
|
||
x.Id,
|
||
x.TaskNumber,
|
||
x.Name,
|
||
x.Course!.Code,
|
||
x.Course.Name,
|
||
x.Capacity,
|
||
x.AcademicTerm!.Name))
|
||
.FirstOrDefaultAsync(cancellationToken);
|
||
}
|
||
|
||
private Task<List<TeachingTaskRosterStudent>> LoadTeachingTaskRosterAsync(
|
||
Guid teachingTaskId,
|
||
CancellationToken cancellationToken) =>
|
||
TeachingTaskRosterQuery.ForTask(db, teachingTaskId)
|
||
.AsNoTracking()
|
||
.OrderBy(x => x.StudentNumber)
|
||
.Select(x => new TeachingTaskRosterStudent(
|
||
x.Id,
|
||
x.StudentNumber,
|
||
x.Name,
|
||
x.AdministrativeClass!.Name,
|
||
x.AdministrativeClass.Major!.Name,
|
||
x.Phone,
|
||
x.Email,
|
||
x.WeChat,
|
||
x.EmergencyContactName,
|
||
x.EmergencyContactRelationship,
|
||
x.EmergencyContactPhone,
|
||
x.SpecialTags,
|
||
x.SpecialNeeds,
|
||
db.CourseEnrollments
|
||
.Where(enrollment =>
|
||
enrollment.StudentId == x.Id &&
|
||
enrollment.Status == CourseEnrollmentStatus.Enrolled &&
|
||
enrollment.CourseSelectionOffering!.TeachingTaskId ==
|
||
teachingTaskId)
|
||
.OrderByDescending(enrollment => enrollment.EnrolledAt)
|
||
.Select(enrollment => (DateTime?)enrollment.EnrolledAt)
|
||
.FirstOrDefault(),
|
||
x.AdministrativeClass.Major!.College!.Name,
|
||
x.EnrollmentYear,
|
||
x.Gender))
|
||
.ToListAsync(cancellationToken);
|
||
|
||
private async Task<TeachingTask?> FindAccessibleTaskAsync(
|
||
Guid id,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var scope = currentUserDataScope.Current;
|
||
var source = db.TeachingTasks.AsNoTracking().AsQueryable();
|
||
if (scope.Scope != DataScope.All)
|
||
{
|
||
source = source.Where(x =>
|
||
x.Course!.CollegeId == scope.RestrictedCollegeId);
|
||
}
|
||
return await source
|
||
.Include(x => x.Course)
|
||
.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
|
||
}
|
||
|
||
private ActionResult? ValidateOffering(
|
||
CourseSelectionRound round,
|
||
TeachingTask? task,
|
||
CourseSelectionOfferingRequest request)
|
||
{
|
||
if (task is null) return ValidationProblem("所选教学班不存在或超出数据范围。");
|
||
if (task.AcademicTermId != round.AcademicTermId)
|
||
return ValidationProblem("教学班与选课批次必须属于同一学期。");
|
||
if (task.Status != TeachingTaskStatus.Published)
|
||
return ValidationProblem("只有已发布的教学班可以进入选课。");
|
||
if (request.Capacity > task.Capacity)
|
||
return ValidationProblem(SelectionMessage($"选课容量不能超过教学班容量 {task.Capacity}。", $"Enrollment capacity cannot exceed the class capacity of {task.Capacity}."));
|
||
return null;
|
||
}
|
||
|
||
private async Task<ActionResult?> ValidateRoundAsync(
|
||
CourseSelectionRoundRequest request,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var startsAt = request.StartsAt.ToUniversalTime();
|
||
var endsAt = request.EndsAt.ToUniversalTime();
|
||
var withdrawalEndsAt = request.WithdrawalEndsAt.ToUniversalTime();
|
||
if (startsAt >= endsAt)
|
||
return ValidationProblem("选课开始时间必须早于结束时间。");
|
||
if (withdrawalEndsAt < endsAt)
|
||
return ValidationProblem("退课截止时间不能早于选课结束时间。");
|
||
if (!Enum.IsDefined(request.Scope))
|
||
return ValidationProblem("选课批次类型无效。");
|
||
var eligibleGrades = NormalizeGrades(request.EligibleGrades);
|
||
if (eligibleGrades.Length > 20)
|
||
return ValidationProblem("单个选课批次最多配置 20 个适用年级。");
|
||
if (eligibleGrades.Any(grade => grade is < 2000 or > 2200))
|
||
return ValidationProblem("适用年级必须在 2000—2200 之间。");
|
||
if (!await db.AcademicTerms.AnyAsync(
|
||
x => x.Id == request.AcademicTermId && x.IsEnabled,
|
||
cancellationToken))
|
||
return ValidationProblem("所选学期不存在或已停用。");
|
||
return null;
|
||
}
|
||
|
||
private async Task<Student?> CurrentStudentAsync(
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var userId = currentUserDataScope.Current.UserId;
|
||
return await db.Students
|
||
.Include(x => x.AdministrativeClass)
|
||
.FirstOrDefaultAsync(x => x.UserId == userId, cancellationToken);
|
||
}
|
||
|
||
private async Task<List<ScheduleEntry>> PublishedScheduleEntries(
|
||
Guid academicTermId,
|
||
IReadOnlyCollection<Guid> taskIds,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
if (taskIds.Count == 0) return [];
|
||
return await db.ScheduleEntries.AsNoTracking()
|
||
.Where(x =>
|
||
x.SchedulePlan!.AcademicTermId == academicTermId &&
|
||
x.SchedulePlan.Status == SchedulePlanStatus.Published)
|
||
.WhereIn(taskIds, x => x.TeachingTaskId)
|
||
.ToListAsync(cancellationToken);
|
||
}
|
||
|
||
private async Task<HashSet<Guid>> RetakeCourseIdsAsync(
|
||
Guid studentId,
|
||
Guid targetAcademicTermId,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var attempts = await db.GradeRecords.AsNoTracking()
|
||
.Where(x =>
|
||
x.StudentId == studentId &&
|
||
(x.PublishedAt != null ||
|
||
x.GradeSheet!.Status == GradeSheetStatus.Published) &&
|
||
x.GradeSheet!.TeachingTask!.AcademicTermId != targetAcademicTermId)
|
||
.Select(x => new RetakeGradeAttempt(
|
||
x.GradeSheet!.TeachingTask!.CourseId,
|
||
x.TotalScore,
|
||
x.ExamStatus,
|
||
x.IsPassed))
|
||
.ToListAsync(cancellationToken);
|
||
|
||
var cancelledCourseIds = await db.ExamEligibilityDecisions.AsNoTracking()
|
||
.Where(x => x.StudentId == studentId && x.Cancelled && x.TeachingTask!.AcademicTermId != targetAcademicTermId)
|
||
.Select(x => x.TeachingTask!.CourseId).Distinct().ToListAsync(cancellationToken);
|
||
return attempts
|
||
.GroupBy(x => x.CourseId)
|
||
.Where(group =>
|
||
{
|
||
var evaluation = StudentCourseProgressRules.Evaluate(
|
||
group.Select(x => new StudentCourseAttemptSnapshot(
|
||
x.TotalScore,
|
||
x.ExamStatus,
|
||
x.Passed)),
|
||
false);
|
||
return (evaluation.HasFailedAttempt || cancelledCourseIds.Contains(group.Key)) && !evaluation.HasPassedAttempt;
|
||
})
|
||
.Select(group => group.Key)
|
||
.Concat(cancelledCourseIds.Where(id => attempts.All(x => x.CourseId != id)))
|
||
.ToHashSet();
|
||
}
|
||
|
||
private async Task<bool> IsEligibleForRetakeAsync(
|
||
Guid studentId,
|
||
Guid courseId,
|
||
Guid targetAcademicTermId,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
var attempts = await db.GradeRecords.AsNoTracking()
|
||
.Where(x =>
|
||
x.StudentId == studentId &&
|
||
(x.PublishedAt != null ||
|
||
x.GradeSheet!.Status == GradeSheetStatus.Published) &&
|
||
x.GradeSheet!.TeachingTask!.CourseId == courseId &&
|
||
x.GradeSheet.TeachingTask.AcademicTermId != targetAcademicTermId)
|
||
.Select(x => new StudentCourseAttemptSnapshot(
|
||
x.TotalScore,
|
||
x.ExamStatus,
|
||
x.IsPassed))
|
||
.ToListAsync(cancellationToken);
|
||
var evaluation = StudentCourseProgressRules.Evaluate(attempts, false);
|
||
var cancelled = await db.ExamEligibilityDecisions.AsNoTracking().AnyAsync(x =>
|
||
x.StudentId == studentId && x.Cancelled && x.TeachingTask!.CourseId == courseId &&
|
||
x.TeachingTask.AcademicTermId != targetAcademicTermId, cancellationToken);
|
||
return (evaluation.HasFailedAttempt || cancelled) && !evaluation.HasPassedAttempt;
|
||
}
|
||
|
||
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 (await TeachingTaskRosterQuery.BlockedStudentIdsForTask(db, task.Id)
|
||
.ContainsAsync(student.Id, cancellationToken))
|
||
return new(false, "该教学班已因学籍异动退出,请选择其他教学班。");
|
||
if (task.Status != TeachingTaskStatus.Published)
|
||
return new(false, "该教学班当前不可选。");
|
||
if (!CourseSelectionRules.IsGradeEligible(
|
||
round.EligibleGrades.Select(x => x.Grade),
|
||
student.AdministrativeClass!.Grade))
|
||
{
|
||
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 IsEligibleForRetakeAsync(
|
||
student.Id,
|
||
task.CourseId,
|
||
round.AcademicTermId,
|
||
cancellationToken);
|
||
if (round.Scope == CourseSelectionScope.RetakeOnly && !isRetake)
|
||
return new(false, "该批次仅限有未通过历史成绩的学生办理重修选课或候补。");
|
||
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.#} 学分上限。",
|
||
$"Receiving a place would total {selectedCredits + task.Course.Credits:0.#} credits, exceeding the round limit of {round.MaxCredits:0.#}.");
|
||
}
|
||
var selectedCourseCount = await db.CourseEnrollments.CountAsync(
|
||
x =>
|
||
x.StudentId == student.Id &&
|
||
x.Status == CourseEnrollmentStatus.Enrolled &&
|
||
x.CourseSelectionOffering!.CourseSelectionRoundId == round.Id,
|
||
cancellationToken);
|
||
if (CourseSelectionRules.HasReachedCourseLimit(
|
||
round.MaxCourseCount,
|
||
selectedCourseCount))
|
||
{
|
||
return new(
|
||
isRetake,
|
||
$"你已达到本轮最多 {round.MaxCourseCount} 门课程限制。",
|
||
$"You have reached the limit of {round.MaxCourseCount} courses for this round.");
|
||
}
|
||
|
||
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% 上限。",
|
||
$"The retake overlaps by {overlap:F0}%, exceeding the 50% limit.");
|
||
}
|
||
}
|
||
|
||
return new(isRetake, null);
|
||
}
|
||
|
||
internal 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;
|
||
candidate.WaitlistResolvedAt = now;
|
||
candidate.WaitlistResolutionReason = eligibility.Error;
|
||
if (candidate.Student!.UserId is Guid invalidUserId)
|
||
{
|
||
db.Notifications.Add(new Notification
|
||
{
|
||
UserId = invalidUserId,
|
||
Title = "课程候补已失效",
|
||
Content =
|
||
$"“{offering.TeachingTask!.Course!.Name}”候补未能递补:" +
|
||
eligibility.Error,
|
||
Category = NotificationCategory.CourseSelection,
|
||
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.WaitlistResolvedAt = now;
|
||
candidate.WaitlistResolutionReason = "名额释放,已按候补顺位自动递补。";
|
||
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}”已释放名额," +
|
||
"你已自动进入正式选课名单。",
|
||
Category = NotificationCategory.CourseSelection,
|
||
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;
|
||
waitlist.WaitlistResolvedAt = now;
|
||
waitlist.WaitlistResolutionReason = "已在同一课程的其他教学班递补成功。";
|
||
}
|
||
}
|
||
|
||
private async Task<ActionResult> SaveAsync(
|
||
Guid id,
|
||
bool created,
|
||
CancellationToken cancellationToken)
|
||
{
|
||
try
|
||
{
|
||
await db.SaveChangesAsync(cancellationToken);
|
||
return created ? Created(string.Empty, new { id }) : NoContent();
|
||
}
|
||
catch (DbUpdateException)
|
||
{
|
||
return ConflictProblem("记录重复、容量已变化,或关联数据已失效。");
|
||
}
|
||
}
|
||
|
||
private static string BuildRoundResultContent(
|
||
string roundName,
|
||
IReadOnlyCollection<string> selectedCourses,
|
||
IReadOnlyCollection<string> unsuccessfulCourses)
|
||
{
|
||
var parts = new List<string> { $"{roundName}已结束。" };
|
||
parts.Add(selectedCourses.Count == 0
|
||
? "本轮未选中课程。"
|
||
: $"最终选中 {selectedCourses.Count} 门:{FormatCourseNames(selectedCourses)}。");
|
||
if (unsuccessfulCourses.Count > 0)
|
||
{
|
||
parts.Add(
|
||
$"候补未成功 {unsuccessfulCourses.Count} 门:" +
|
||
$"{FormatCourseNames(unsuccessfulCourses)}。");
|
||
}
|
||
|
||
return string.Concat(parts);
|
||
}
|
||
|
||
private static string FormatCourseNames(IReadOnlyCollection<string> courses)
|
||
{
|
||
const int visibleCount = 8;
|
||
const int visibleNameLength = 40;
|
||
var names = courses.Take(visibleCount)
|
||
.Select(name => name.Length <= visibleNameLength
|
||
? $"《{name}》"
|
||
: $"《{name[..visibleNameLength]}…》");
|
||
var result = string.Join("、", names);
|
||
return courses.Count > visibleCount
|
||
? $"{result}等 {courses.Count} 门课程"
|
||
: result;
|
||
}
|
||
|
||
private IQueryable<CourseEnrollment> ScopedEnrollments()
|
||
{
|
||
var source = db.CourseEnrollments.AsNoTracking();
|
||
var scope = currentUserDataScope.Current;
|
||
return scope.Scope == DataScope.All
|
||
? source
|
||
: source.Where(x =>
|
||
x.CourseSelectionOffering!.TeachingTask!.Course!.CollegeId ==
|
||
scope.RestrictedCollegeId);
|
||
}
|
||
|
||
private IQueryable<CourseEnrollment> ApplyEnrollmentFilters(
|
||
IQueryable<CourseEnrollment> source,
|
||
CourseEnrollmentQuery query)
|
||
{
|
||
if (query.AcademicTermId.HasValue)
|
||
source = source.Where(x => x.CourseSelectionOffering!.CourseSelectionRound!
|
||
.AcademicTermId == query.AcademicTermId.Value);
|
||
if (query.CourseId.HasValue)
|
||
source = source.Where(x => x.CourseSelectionOffering!.TeachingTask!.CourseId ==
|
||
query.CourseId.Value);
|
||
if (query.CollegeId.HasValue)
|
||
source = source.Where(x => x.CourseSelectionOffering!.TeachingTask!.Course!.CollegeId ==
|
||
query.CollegeId.Value);
|
||
if (query.MajorId.HasValue)
|
||
source = source.Where(x => x.Student!.AdministrativeClass!.MajorId ==
|
||
query.MajorId.Value);
|
||
if (query.AdministrativeClassId.HasValue)
|
||
source = source.Where(x => x.Student!.AdministrativeClassId ==
|
||
query.AdministrativeClassId.Value);
|
||
if (query.Grade.HasValue)
|
||
source = source.Where(x => x.Student!.AdministrativeClass!.Grade == query.Grade.Value);
|
||
if (query.EnrollmentYear.HasValue)
|
||
source = source.Where(x => x.Student!.EnrollmentYear == query.EnrollmentYear.Value);
|
||
if (query.Status.HasValue)
|
||
source = source.Where(x => x.Status == query.Status.Value);
|
||
if (query.EnrollmentType.HasValue)
|
||
source = source.Where(x => x.EnrollmentType == query.EnrollmentType.Value);
|
||
if (query.ExemptionStatus.HasValue)
|
||
source = source.Where(x => db.CourseExemptions
|
||
.Where(exemption => exemption.StudentId == x.StudentId &&
|
||
exemption.TeachingTaskId == x.CourseSelectionOffering!.TeachingTaskId)
|
||
.OrderByDescending(exemption => exemption.CreatedAt)
|
||
.Select(exemption => (ApprovalStatus?)exemption.Status)
|
||
.FirstOrDefault() == query.ExemptionStatus.Value);
|
||
if (!string.IsNullOrWhiteSpace(query.Keyword))
|
||
{
|
||
var keyword = query.Keyword.Trim();
|
||
source = source.Where(x =>
|
||
x.Student!.StudentNumber.Contains(keyword) ||
|
||
x.Student.Name.Contains(keyword) ||
|
||
x.CourseSelectionOffering!.TeachingTask!.Course!.Code.Contains(keyword) ||
|
||
x.CourseSelectionOffering.TeachingTask.Course.Name.Contains(keyword) ||
|
||
x.CourseSelectionOffering.TeachingTask.TaskNumber.Contains(keyword));
|
||
}
|
||
return source;
|
||
}
|
||
|
||
private static IOrderedQueryable<CourseEnrollment> OrderEnrollments(
|
||
IQueryable<CourseEnrollment> source) => source
|
||
.OrderByDescending(x => x.CourseSelectionOffering!.CourseSelectionRound!
|
||
.AcademicTerm!.StartDate)
|
||
.ThenBy(x => x.CourseSelectionOffering!.TeachingTask!.Course!.Code)
|
||
.ThenBy(x => x.Student!.StudentNumber);
|
||
|
||
private IQueryable<CourseEnrollmentListItem> ProjectEnrollments(
|
||
IQueryable<CourseEnrollment> source) => source.Select(x => new CourseEnrollmentListItem(
|
||
x.Id,
|
||
x.StudentId,
|
||
x.CourseSelectionOfferingId,
|
||
x.CourseSelectionOffering!.CourseSelectionRound!.AcademicTerm!.Name,
|
||
x.CourseSelectionOffering.CourseSelectionRound.AcademicTerm.StartDate,
|
||
x.CourseSelectionOffering.TeachingTask!.Course!.College!.Name,
|
||
x.CourseSelectionOffering.TeachingTask.Course.Code,
|
||
x.CourseSelectionOffering.TeachingTask.Course.Name,
|
||
x.CourseSelectionOffering.TeachingTask.TaskNumber,
|
||
x.CourseSelectionOffering.TeachingTask.Course.Credits,
|
||
x.Student!.StudentNumber,
|
||
x.Student.Name,
|
||
x.Student.AdministrativeClass!.Major!.Name,
|
||
x.Student.AdministrativeClass.Name,
|
||
x.Student.AdministrativeClass.Grade,
|
||
x.Status,
|
||
x.EnrollmentType,
|
||
x.EnrolledAt,
|
||
x.WithdrawnAt,
|
||
db.CourseExemptions
|
||
.Where(exemption => exemption.StudentId == x.StudentId &&
|
||
exemption.TeachingTaskId == x.CourseSelectionOffering.TeachingTaskId)
|
||
.OrderByDescending(exemption => exemption.CreatedAt)
|
||
.Select(exemption => (ApprovalStatus?)exemption.Status)
|
||
.FirstOrDefault()));
|
||
|
||
private ActionResult ProfileNotFound() =>
|
||
ConflictProblem("当前账号未关联有效学生档案,请联系教务管理员。");
|
||
|
||
private static readonly IReadOnlyDictionary<string, string> ErrorResourceKeys = new Dictionary<string, string>
|
||
{
|
||
["只有草稿选课批次可以修改。"] = "CourseSelection.Errors.OnlyDraftEnrollmentRoundsCanBeEdited",
|
||
["只有草稿选课批次可以删除。"] = "CourseSelection.Errors.OnlyDraftEnrollmentRoundsCanBeDeleted",
|
||
["只有草稿选课批次可以开放。"] = "CourseSelection.Errors.OnlyDraftEnrollmentRoundsCanBeOpened",
|
||
["至少配置一个可选教学班后才能开放。"] = "CourseSelection.Errors.AddAtLeastOneTeachingClassBeforeOpeningEnrollment",
|
||
["只有开放中的选课批次可以关闭。"] = "CourseSelection.Errors.OnlyOpenEnrollmentRoundsCanBeClosed",
|
||
["选课批次开放后不能调整教学班。"] = "CourseSelection.Errors.TeachingClassesCannotBeChangedAfterTheEnrollmentRoundOpens",
|
||
["管理员代选仅适用于公共必修课。"] = "CourseSelection.Errors.AdministrativeEnrollmentIsOnlyAvailableForRequiredGeneralCourses",
|
||
["选课批次开放后才能办理。"] = "CourseSelection.Errors.ThisActionIsOnlyAvailableAfterEnrollmentOpens",
|
||
["请至少选择一名学生。"] = "CourseSelection.Errors.SelectAtLeastOneStudent",
|
||
["单次最多可为 100 名学生代选。"] = "CourseSelection.Errors.AtMost100StudentsCanBeEnrolledAtOnce",
|
||
["选课批次开放后才能办理管理员代选。"] = "CourseSelection.Errors.AdministrativeEnrollmentIsOnlyAvailableAfterTheRoundOpens",
|
||
["该教学班当前不可办理代选。"] = "CourseSelection.Errors.AdministrativeEnrollmentIsUnavailableForThisClass",
|
||
["存在无效的学生档案。"] = "CourseSelection.Errors.TheSelectionContainsInvalidStudentRecords",
|
||
["该教学班尚未发布课表,暂时不能办理代选。"] = "CourseSelection.Errors.TheClassTimetableIsNotPublishedAdministrativeEnrollmentIsUnavailable",
|
||
["单次最多可为 100 名学生强制选课。"] = "CourseSelection.Errors.AtMost100StudentsCanBeForceEnrolledAtOnce",
|
||
["选课批次开放后才能办理强制选课。"] = "CourseSelection.Errors.ForceEnrollmentIsOnlyAvailableAfterTheRoundOpens",
|
||
["该教学班当前不可选。"] = "CourseSelection.Errors.ThisTeachingClassIsCurrentlyUnavailableForEnrollment",
|
||
["管理员名单调整仅适用于公共必修课。"] = "CourseSelection.Errors.AdministrativeRosterChangesAreOnlyAvailableForRequiredGeneralCourses",
|
||
["该教学班当前不可调整名单。"] = "CourseSelection.Errors.TheRosterForThisClassCannotCurrentlyBeChanged",
|
||
["该学生已不在教学班名单中。"] = "CourseSelection.Errors.TheStudentIsNoLongerOnThisClassRoster",
|
||
["只有在籍学生可以选课。"] = "CourseSelection.Errors.OnlyActiveStudentsCanEnrollInCourses",
|
||
["只有在籍学生可以选课或候补。"] = "CourseSelection.Errors.OnlyActiveStudentsCanEnrollOrJoinAWaitlist",
|
||
["你不属于该教学班的选课对象。"] = "CourseSelection.Errors.YouAreNotEligibleToEnrollInThisClass",
|
||
["该批次仅限有未通过历史成绩的学生办理重修选课或候补。"] = "CourseSelection.Errors.OnlyStudentsRetakingAPreviouslyFailedCourseCanEnrollOrJoinAWaitlistInThisRound",
|
||
["该教学班尚未发布课表,暂时不能选课或候补。"] = "CourseSelection.Errors.TheClassTimetableIsNotPublishedEnrollmentAndWaitlistingAreUnavailable",
|
||
["当前不在该选课批次的开放时间内。"] = "CourseSelection.Errors.TheEnrollmentRoundIsNotCurrentlyOpen",
|
||
["你所在的年级不属于本轮选课对象。"] = "CourseSelection.Errors.YourYearIsNotEligibleForThisEnrollmentRound",
|
||
["该批次仅限有未通过历史成绩的学生办理重修选课。"] = "CourseSelection.Errors.ThisRoundIsLimitedToStudentsRetakingAPreviouslyFailedCourse",
|
||
["你已经选择了该教学班。"] = "CourseSelection.Errors.YouAreAlreadyEnrolledInThisClass",
|
||
["该教学班名额已满。"] = "CourseSelection.Errors.ThisTeachingClassIsFull",
|
||
["同一学期不能重复选择相同课程。"] = "CourseSelection.Errors.YouCannotSelectTheSameCourseTwiceInOneTerm",
|
||
["该教学班尚未发布课表,暂时不能选课。"] = "CourseSelection.Errors.TheClassTimetableIsNotPublishedEnrollmentIsUnavailable",
|
||
["该教学班与已选课程的上课时间冲突。"] = "CourseSelection.Errors.ThisClassConflictsWithACourseYouHaveAlreadySelected",
|
||
["你已经在该教学班的候补队列中。"] = "CourseSelection.Errors.YouAreAlreadyOnThisClassWaitlist",
|
||
["你已在本学期同一课程的其他教学班候补。"] = "CourseSelection.Errors.YouAreAlreadyWaitlistedForAnotherClassOfThisCourseInThisTerm",
|
||
["该教学班当前仍有名额,请直接选择课程。"] = "CourseSelection.Errors.ThisClassStillHasPlacesEnrollDirectly",
|
||
["该课程已经退选或候补已经结束。"] = "CourseSelection.Errors.TheCourseHasAlreadyBeenDroppedOrTheWaitlistHasEnded",
|
||
["当前批次已停止退课和候补调整。"] = "CourseSelection.Errors.ThisRoundNoLongerPermitsWithdrawalsOrWaitlistChanges",
|
||
["所选教学班不存在或超出数据范围。"] = "CourseSelection.Errors.TheSelectedTeachingClassDoesNotExistOrIsOutsideYourDataScope",
|
||
["教学班与选课批次必须属于同一学期。"] = "CourseSelection.Errors.TheTeachingClassAndEnrollmentRoundMustBelongToTheSameTerm",
|
||
["只有已发布的教学班可以进入选课。"] = "CourseSelection.Errors.OnlyPublishedTeachingClassesCanBeOfferedForEnrollment",
|
||
["选课开始时间必须早于结束时间。"] = "CourseSelection.Errors.EnrollmentMustStartBeforeItEnds",
|
||
["退课截止时间不能早于选课结束时间。"] = "CourseSelection.Errors.TheWithdrawalDeadlineCannotBeEarlierThanTheEnrollmentEndTime",
|
||
["选课批次类型无效。"] = "CourseSelection.Errors.TheEnrollmentRoundTypeIsInvalid",
|
||
["单个选课批次最多配置 20 个适用年级。"] = "CourseSelection.Errors.AnEnrollmentRoundCanSpecifyAtMost20EligibleYears",
|
||
["适用年级必须在 2000—2200 之间。"] = "CourseSelection.Errors.EligibleYearsMustBeBetween2000And2200",
|
||
["所选学期不存在或已停用。"] = "CourseSelection.Errors.TheSelectedTermDoesNotExistOrIsDisabled",
|
||
["记录重复、容量已变化,或关联数据已失效。"] = "CourseSelection.Errors.TheRecordIsDuplicatedCapacityHasChangedOrRelatedDataIsNoLongerValid",
|
||
["当前账号未关联有效学生档案,请联系教务管理员。"] = "CourseSelection.Errors.TheCurrentAccountIsNotLinkedToAnActiveStudentRecordContactAcademicAdministration",
|
||
};
|
||
|
||
private static string SelectionMessage(string chinese, string english) =>
|
||
CultureInfo.CurrentUICulture.TwoLetterISOLanguageName == "en" ? english : chinese;
|
||
|
||
private static string LocalizeSelectionError(string detail) =>
|
||
CultureInfo.CurrentUICulture.TwoLetterISOLanguageName == "en" && ErrorResourceKeys.TryGetValue(detail, out var key)
|
||
? SharedResourceText.Get(null, key)
|
||
: detail;
|
||
|
||
private string LocalizeSelectionErrorForRequest(string detail) =>
|
||
CultureInfo.CurrentUICulture.TwoLetterISOLanguageName == "en" && ErrorResourceKeys.TryGetValue(detail, out var key)
|
||
? SharedResourceText.Get(localizer, key)
|
||
: detail;
|
||
|
||
private ActionResult ValidationProblem(string detail) => base.ValidationProblem(detail: LocalizeSelectionErrorForRequest(detail));
|
||
|
||
private ActionResult ConflictProblem(string detail) =>
|
||
Conflict(new ProblemDetails
|
||
{
|
||
Title = SharedResourceText.Get(localizer, "CourseSelection.Errors.OperationFailedTitle"),
|
||
Detail = LocalizeSelectionErrorForRequest(detail),
|
||
Status = StatusCodes.Status409Conflict
|
||
});
|
||
|
||
private static string? Normalize(string? value) =>
|
||
string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||
|
||
private static int[] NormalizeGrades(IEnumerable<int>? values) =>
|
||
values?.Distinct().OrderBy(x => x).ToArray() ?? [];
|
||
|
||
private sealed record EnrollmentEligibility(bool IsRetake, string? Error, string? EnglishError = null);
|
||
|
||
private sealed record RetakeGradeAttempt(
|
||
Guid CourseId,
|
||
decimal? TotalScore,
|
||
GradeExamStatus ExamStatus,
|
||
bool? Passed);
|
||
|
||
private sealed record TeacherTeachingTaskInfo(
|
||
Guid Id,
|
||
string TaskNumber,
|
||
string TaskName,
|
||
string CourseCode,
|
||
string CourseName,
|
||
int Capacity,
|
||
string TermName);
|
||
|
||
private sealed record TeachingTaskRosterStudent(
|
||
Guid StudentId,
|
||
string StudentNumber,
|
||
string Name,
|
||
string ClassName,
|
||
string MajorName,
|
||
string? Phone,
|
||
string? Email,
|
||
string? WeChat,
|
||
string? EmergencyContactName,
|
||
string? EmergencyContactRelationship,
|
||
string? EmergencyContactPhone,
|
||
string? SpecialTags,
|
||
string? SpecialNeeds,
|
||
DateTime? EnrolledAt,
|
||
string CollegeName,
|
||
int EnrollmentYear,
|
||
Gender Gender);
|
||
}
|
||
|
||
public sealed record CourseSelectionRoundRequest(
|
||
Guid AcademicTermId,
|
||
[Required, MaxLength(120)] string Name,
|
||
DateTime StartsAt,
|
||
DateTime EndsAt,
|
||
DateTime WithdrawalEndsAt,
|
||
[Range(typeof(decimal), "0.5", "99")] decimal MaxCredits,
|
||
[Range(1, 100)] int? MaxCourseCount,
|
||
IReadOnlyCollection<int>? EligibleGrades,
|
||
[MaxLength(500)] string? Notes,
|
||
CourseSelectionScope Scope = CourseSelectionScope.All);
|
||
|
||
public sealed record CourseSelectionOfferingRequest(
|
||
Guid TeachingTaskId,
|
||
[Range(1, 10000)] int Capacity,
|
||
bool IsOpenToAll,
|
||
[MaxLength(500)] string? Notes);
|
||
|
||
public sealed record StudentEnrollmentRequest(Guid OfferingId);
|
||
|
||
public sealed record AdminEnrollmentRequest(
|
||
[MinLength(1)] IReadOnlyCollection<Guid> StudentIds);
|
||
|
||
public sealed record ForceEnrollmentRequest(
|
||
[MinLength(1)] IReadOnlyCollection<Guid> StudentIds);
|
||
|
||
public sealed record CourseEnrollmentQuery(
|
||
Guid? AcademicTermId,
|
||
Guid? CourseId,
|
||
Guid? CollegeId,
|
||
Guid? MajorId,
|
||
Guid? AdministrativeClassId,
|
||
int? Grade,
|
||
int? EnrollmentYear,
|
||
CourseEnrollmentStatus? Status,
|
||
EnrollmentType? EnrollmentType,
|
||
ApprovalStatus? ExemptionStatus,
|
||
string? Keyword,
|
||
int Page = 1,
|
||
int PageSize = 20);
|
||
|
||
public sealed record CourseEnrollmentListItem(
|
||
Guid Id,
|
||
Guid StudentId,
|
||
Guid CourseSelectionOfferingId,
|
||
string TermName,
|
||
DateOnly TermStartDate,
|
||
string CollegeName,
|
||
string CourseCode,
|
||
string CourseName,
|
||
string TaskNumber,
|
||
decimal Credits,
|
||
string StudentNumber,
|
||
string StudentName,
|
||
string MajorName,
|
||
string ClassName,
|
||
int Grade,
|
||
CourseEnrollmentStatus Status,
|
||
EnrollmentType EnrollmentType,
|
||
DateTime? EnrolledAt,
|
||
DateTime? WithdrawnAt,
|
||
ApprovalStatus? ExemptionStatus);
|
||
|
||
public sealed record EnrollmentStudentIdentity(
|
||
Guid StudentId,
|
||
string StudentNumber,
|
||
string StudentName,
|
||
string MajorName,
|
||
string ClassName,
|
||
int Grade);
|
||
|
||
public sealed record StudentEnrollmentSummary(
|
||
Guid StudentId,
|
||
string StudentNumber,
|
||
string StudentName,
|
||
string MajorName,
|
||
string ClassName,
|
||
int Grade,
|
||
IReadOnlyList<CourseEnrollmentListItem> Courses,
|
||
int CourseCount,
|
||
decimal ActiveCredits);
|
||
|
||
public sealed record StudentOfferingDto(
|
||
Guid Id,
|
||
Guid TeachingTaskId,
|
||
string TaskNumber,
|
||
string CourseCode,
|
||
string CourseName,
|
||
decimal Credits,
|
||
IEnumerable<string> TeacherNames,
|
||
int Capacity,
|
||
int EnrolledCount,
|
||
int WaitlistedCount,
|
||
bool IsOpenToAll,
|
||
CourseEnrollmentStatus? EnrollmentStatus,
|
||
bool IsFlexible,
|
||
bool IsRetake,
|
||
IEnumerable<StudentScheduleDto> Schedules,
|
||
int? WaitlistPosition);
|
||
|
||
public sealed record StudentScheduleDto(
|
||
int DayOfWeek,
|
||
int StartPeriod,
|
||
int PeriodCount,
|
||
int StartWeek,
|
||
int EndWeek,
|
||
WeekPattern WeekPattern,
|
||
string ClassroomName);
|