Compare commits

...
2 Commits
3 changed files with 52 additions and 22 deletions

No files matched your search

@@ -1295,12 +1295,18 @@ public sealed class AttendanceController(
var records = await db.AttendanceRecords.AsNoTracking()
.Where(x => x.AttendanceSheet!.TeachingTaskId == taskId && x.AttendanceSheet.Status == AttendanceSheetStatus.Submitted)
.Select(x => new { x.StudentId, x.Status, x.AttendanceSheet!.PeriodCount }).ToListAsync(ct);
var decisions = await db.ExamEligibilityDecisions.AsNoTracking().Where(x => x.TeachingTaskId == taskId).ToListAsync(ct);
var totals = records.GroupBy(x => x.StudentId).ToDictionary(group => group.Key, group => new
{
Absent = group.Where(x => x.Status == AttendanceStatus.Absent).Sum(x => x.PeriodCount),
Leave = group.Where(x => x.Status == AttendanceStatus.Leave).Sum(x => x.PeriodCount)
});
var decisions = await db.ExamEligibilityDecisions.AsNoTracking().Where(x => x.TeachingTaskId == taskId)
.ToDictionaryAsync(x => x.StudentId, ct);
return Ok(roster.Select(student => {
var rows = records.Where(x => x.StudentId == student.StudentId).ToList();
var absent = rows.Where(x => x.Status == AttendanceStatus.Absent).Sum(x => x.PeriodCount);
var leave = rows.Where(x => x.Status == AttendanceStatus.Leave).Sum(x => x.PeriodCount);
var decision = decisions.FirstOrDefault(x => x.StudentId == student.StudentId);
totals.TryGetValue(student.StudentId, out var total);
var absent = total?.Absent ?? 0;
var leave = total?.Leave ?? 0;
decisions.TryGetValue(student.StudentId, out var decision);
return new { student.StudentId, student.StudentNumber, student.Name, student.ClassName, AbsentPeriods = absent,
LeavePeriods = leave, TotalHours = task.TotalHours, EligibleForReview = absent > 3 || (task.TotalHours > 0 && leave * 3 > task.TotalHours * 2),
Cancelled = (bool?)decision?.Cancelled, decision?.Comment, decision?.ReviewedAt };
@@ -130,6 +130,15 @@ public sealed class AutomaticScheduleGenerator(AppDbContext db)
ScheduleOptimizationSettings settings)
{
private readonly Random random = new();
private readonly Dictionary<Guid, Classroom> classroomsById = classrooms.ToDictionary(room => room.Id);
private readonly Dictionary<Guid, bool> groundFloorByTask = tasks.ToDictionary(task => task.Id, RequiresGroundFloor);
private readonly Dictionary<Guid, int[]> preferredDaysByTask = constraints.ToDictionary(
pair => pair.Key, pair => ParsePreferredDays(pair.Value.PreferredDayOfWeeks));
private readonly Dictionary<int, List<ScheduleEntry>> baselineByDay = baselineEntries
.GroupBy(entry => entry.DayOfWeek)
.ToDictionary(group => group.Key, group => group.ToList());
private readonly int firstActivePeriod = activePeriods.Min();
private readonly int lastActivePeriod = activePeriods.Max();
public async Task<GeneticScheduleOptimizationResult> OptimizeAsync(
Func<int, int, CancellationToken, Task>? reportProgress,
@@ -201,15 +210,15 @@ public sealed class AutomaticScheduleGenerator(AppDbContext db)
ISet<Guid> invalidTaskIds)
{
var result = new List<ScheduleDemand>();
var scheduledHoursByTask = baselineEntries.GroupBy(entry => (entry.TeachingTaskId, entry.Kind))
.ToDictionary(group => group.Key, group => group.Sum(TeachingTaskHours.ScheduledHours));
foreach (var task in tasks)
{
constraints.TryGetValue(task.Id, out var constraint);
foreach (var kind in new[] { ScheduleEntryKind.Lecture, ScheduleEntryKind.Experiment })
{
var targetHours = TeachingTaskHours.TargetHours(task.Course!, kind);
var scheduledHours = baselineEntries
.Where(entry => entry.TeachingTaskId == task.Id && entry.Kind == kind)
.Sum(TeachingTaskHours.ScheduledHours);
var scheduledHours = scheduledHoursByTask.GetValueOrDefault((task.Id, kind));
var label = kind == ScheduleEntryKind.Experiment ? "实验课" : "理论课";
if (scheduledHours > targetHours)
{
@@ -242,13 +251,17 @@ public sealed class AutomaticScheduleGenerator(AppDbContext db)
private List<ScheduleEntry> BuildCandidates(ScheduleDemand demand)
{
var allowedDays = ParseAllowedDays(demand.Constraint?.AllowedDayOfWeeks);
var firstPeriod = demand.Constraint?.EarliestPeriod ?? activePeriods.Min();
var lastPeriod = demand.Constraint?.LatestPeriod ?? activePeriods.Max();
var firstPeriod = demand.Constraint?.EarliestPeriod ?? firstActivePeriod;
var lastPeriod = demand.Constraint?.LatestPeriod ?? lastActivePeriod;
var rooms = EligibleRooms(demand.Task, demand.Constraint, demand.Kind, classrooms);
if ((demand.Constraint?.RequiresClassroom ?? true) && rooms.Count == 0)
return [];
var candidates = new List<ScheduleEntry>();
var roomOptions = demand.Kind != ScheduleEntryKind.Experiment &&
demand.Constraint?.RequiresClassroom == false
? new Classroom?[] { null }
: rooms.Cast<Classroom?>().ToArray();
for (var startWeek = demand.Task.StartWeek;
startWeek + demand.OccurrenceCount - 1 <= demand.Task.EndWeek;
startWeek++)
@@ -257,14 +270,10 @@ public sealed class AutomaticScheduleGenerator(AppDbContext db)
{
if (Enumerable.Range(start, demand.PeriodCount).Any(period => !activePeriods.Contains(period)))
continue;
var roomOptions = demand.Kind != ScheduleEntryKind.Experiment &&
demand.Constraint?.RequiresClassroom == false
? new Classroom?[] { null }
: rooms.Cast<Classroom?>().ToArray();
foreach (var room in roomOptions)
{
var candidate = CreateEntry(demand, startWeek, day, start, room);
if (CanAdd(candidate, baselineEntries))
if (CanAdd(candidate, baselineByDay.GetValueOrDefault(day) ?? []))
candidates.Add(candidate);
}
}
@@ -346,8 +355,13 @@ public sealed class AutomaticScheduleGenerator(AppDbContext db)
IReadOnlyList<ScheduleEntry> candidates,
IReadOnlyList<ScheduleEntry> state)
{
var feasible = candidates.Where(candidate => CanAdd(candidate, state))
.OrderBy(candidate => CandidateScore(candidate, state))
// Both conflict detection and candidate scoring only depend on entries on the same day.
var stateByDay = state.GroupBy(entry => entry.DayOfWeek)
.ToDictionary(group => group.Key, group => group.ToList());
IReadOnlyList<ScheduleEntry> StateFor(ScheduleEntry candidate) =>
stateByDay.TryGetValue(candidate.DayOfWeek, out var entries) ? entries : [];
var feasible = candidates.Where(candidate => CanAdd(candidate, StateFor(candidate)))
.OrderBy(candidate => CandidateScore(candidate, StateFor(candidate)))
.ToList();
if (feasible.Count == 0) return null;
var sampleSize = Math.Clamp((int)Math.Ceiling(feasible.Count / 4d), 1, 8);
@@ -358,7 +372,7 @@ public sealed class AutomaticScheduleGenerator(AppDbContext db)
{
var task = candidate.TeachingTask!;
var room = candidate.ClassroomId is Guid classroomId
? classrooms.FirstOrDefault(item => item.Id == classroomId)
? classroomsById.GetValueOrDefault(classroomId)
: null;
var roomWaste = room is null ? 0 : Math.Max(0, room.Capacity - task.Capacity);
var sameTaskDay = state.Count(entry =>
@@ -371,11 +385,11 @@ public sealed class AutomaticScheduleGenerator(AppDbContext db)
? 100_000
: 0;
var accessibilityPenalty = room is not null &&
RequiresGroundFloor(task) && room.Floor > 1
groundFloorByTask.GetValueOrDefault(task.Id) && room.Floor > 1
? 100_000
: 0;
constraints.TryGetValue(candidate.TeachingTaskId, out var constraint);
var preferredDays = ParsePreferredDays(constraint?.PreferredDayOfWeeks);
var preferredDays = preferredDaysByTask.GetValueOrDefault(candidate.TeachingTaskId) ?? [];
var preferencePenalty =
(preferredDays.Length > 0 && !preferredDays.Contains(candidate.DayOfWeek)
? settings.CoursePreferenceWeight
@@ -395,8 +409,8 @@ public sealed class AutomaticScheduleGenerator(AppDbContext db)
candidate,
state,
settings,
activePeriods.Min(),
activePeriods.Max()) +
firstActivePeriod,
lastActivePeriod) +
preferencePenalty +
accessibilityPenalty +
experimentGeneralClassroomPenalty;
@@ -220,6 +220,16 @@ public sealed class AttendanceControllerTests
await db.SaveChangesAsync();
Assert.IsType<NoContentResult>(await controller.ReviewExamEligibility(task.Id, firstStudent.Id,
new ExamEligibilityReviewRequest(true, "考勤"), CancellationToken.None));
var eligibilityResult = Assert.IsType<OkObjectResult>(await controller.GetExamEligibility(task.Id, CancellationToken.None));
using (var eligibility = System.Text.Json.JsonDocument.Parse(System.Text.Json.JsonSerializer.Serialize(eligibilityResult.Value)))
{
var studentRows = eligibility.RootElement.EnumerateArray().ToDictionary(row => row.GetProperty("StudentId").GetGuid());
Assert.Equal(4, studentRows[firstStudent.Id].GetProperty("AbsentPeriods").GetInt32());
Assert.True(studentRows[firstStudent.Id].GetProperty("EligibleForReview").GetBoolean());
Assert.True(studentRows[firstStudent.Id].GetProperty("Cancelled").GetBoolean());
Assert.Equal(1, studentRows[secondStudent.Id].GetProperty("AbsentPeriods").GetInt32());
Assert.Equal(System.Text.Json.JsonValueKind.Null, studentRows[secondStudent.Id].GetProperty("Cancelled").ValueKind);
}
Assert.Equal(GradeExamStatus.Disqualified, gradeSheet.Records.Single().ExamStatus);
Assert.Null(gradeSheet.Records.Single().TotalScore);
Assert.True(await Jiaowu.Api.Infrastructure.Exams.ExamApprovalExclusions.TaskIdsForStudent(db, firstStudent.Id)