宿舍相关功能

This commit is contained in:
biss committed 2026-10-21 21:28:29 +08:00
1 parent 4b22145041
commit 36a06c73a7
25 files changed
+10435 -113

No files matched your search

@@ -1,5 +1,7 @@
using System.Text.Json;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Domain.System;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Excel;
using Jiaowu.Api.Infrastructure.Files;
@@ -371,9 +373,41 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat
[Authorize(Roles = Managers)]
public async Task<ActionResult> PreviewAllocation(DormitoryAllocationPreviewRequest request, CancellationToken ct)
{
if (request.StudentIds.Count == 0 || request.StudentIds.Count > 2000) return ValidationProblem("请选择 1 到 2000 名待分配学生。");
var result = await BuildAutomaticAssignments(request.StudentIds.Distinct().ToArray(), request.BuildingIds, ct);
return result.Error is null ? Ok(new { Assignments = result.Assignments, Unassigned = result.Unassigned }) : ValidationProblem(result.Error);
var studentIds = request.StudentIds?.Distinct().ToArray() ?? [];
var buildingIds = request.BuildingIds ?? [];
if (studentIds.Length == 0 || studentIds.Length > 2000) return ValidationProblem("请选择 1 到 2000 名待分配学生。");
var batch = new DormitoryAllocationBatch
{
Name = $"宿舍自动分配预览 {DateTime.Now:yyyy-MM-dd HH:mm}",
Mode = DormitoryAllocationMode.Automatic,
Status = DormitoryAllocationBatchStatus.Queued,
RequestedCount = studentIds.Length,
CreatedByUserId = scope.Current.UserId,
RequestPayload = JsonSerializer.Serialize(new DormitoryAllocationJobPayload(studentIds, buildingIds.ToArray()))
};
db.Add(batch);
db.BackgroundJobOutboxMessages.Add(BackgroundJobOutboxMessage.Create(
BackgroundJobKind.DormitoryAutomaticAllocation, batch.Id));
await db.SaveChangesAsync(ct);
return Accepted(new { JobId = batch.Id, batch.Status });
}
[HttpGet("allocations/jobs/{id:guid}")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> GetAllocationJob(Guid id, CancellationToken ct)
{
var batch = await db.DormitoryAllocationBatches.AsNoTracking()
.FirstOrDefaultAsync(x => x.Id == id && x.Mode == DormitoryAllocationMode.Automatic &&
x.CreatedByUserId == scope.Current.UserId, ct);
if (batch is null) return NotFound();
AllocationPreviewResult? result = null;
if (batch.Status == DormitoryAllocationBatchStatus.PreviewReady && !string.IsNullOrWhiteSpace(batch.ResultPayload))
result = JsonSerializer.Deserialize<AllocationPreviewResult>(batch.ResultPayload);
return Ok(new
{
JobId = batch.Id, batch.Status, batch.RequestedCount, batch.ErrorMessage,
Assignments = result?.Assignments ?? [], Unassigned = result?.Unassigned ?? []
});
}
[HttpPost("allocations/commit")]
@@ -386,18 +420,26 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat
return ValidationProblem("同一学生或床位不能在本次分配中重复。");
var studentIds = request.Assignments.Select(x => x.StudentId).ToArray();
var bedIds = request.Assignments.Select(x => x.BedId).ToArray();
var students = await db.Students.Include(x => x.AdministrativeClass).Where(x => studentIds.Contains(x.Id)).ToDictionaryAsync(x => x.Id, ct);
var beds = await db.DormitoryBeds.Include(x => x.Occupancy).Include(x => x.DormitoryRoom)!.ThenInclude(x => x!.DormitoryBuilding)
var students = await db.Students.AsNoTracking().Where(x => studentIds.Contains(x.Id)).ToDictionaryAsync(x => x.Id, ct);
var beds = await db.DormitoryBeds.AsNoTracking().Include(x => x.Occupancy).Include(x => x.DormitoryRoom)!.ThenInclude(x => x!.DormitoryBuilding)
.Where(x => bedIds.Contains(x.Id)).ToDictionaryAsync(x => x.Id, ct);
if (students.Count != studentIds.Length || beds.Count != bedIds.Length) return ValidationProblem("存在无效的学生或床位。");
if (await db.DormitoryOccupancies.AnyAsync(x => studentIds.Contains(x.StudentId), ct) || beds.Values.Any(x => x.Occupancy != null || !x.IsEnabled || !x.DormitoryRoom!.IsEnabled))
return ConflictProblem("学生已经入住或床位已被占用,请刷新预览后重试。");
foreach (var roomGroup in request.Assignments.GroupBy(item => beds[item.BedId].DormitoryRoomId))
var roomGroups = request.Assignments.GroupBy(item => beds[item.BedId].DormitoryRoomId).ToList();
var roomIds = roomGroups.Select(x => x.Key).ToArray();
var existingGenderRows = await db.DormitoryOccupancies.AsNoTracking()
.Where(x => roomIds.Contains(x.DormitoryBed!.DormitoryRoomId) && !studentIds.Contains(x.StudentId))
.Select(x => new { RoomId = x.DormitoryBed!.DormitoryRoomId, x.Student!.Gender })
.Where(x => x.Gender != Gender.Unknown).ToListAsync(ct);
var existingGendersByRoom = existingGenderRows.GroupBy(x => x.RoomId)
.ToDictionary(x => x.Key, x => x.Select(v => v.Gender).Distinct().ToList());
foreach (var roomGroup in roomGroups)
{
var incomingGenders = roomGroup.Select(item => students[item.StudentId].Gender)
.Where(gender => gender != Gender.Unknown).Distinct().ToList();
if (incomingGenders.Count > 1) return ValidationProblem("同一宿舍不能同时分配不同性别的学生。");
var existingGenders = await CurrentRoomGenders(roomGroup.Key, ct);
var existingGenders = existingGendersByRoom.GetValueOrDefault(roomGroup.Key) ?? [];
foreach (var item in roomGroup)
{
var student = students[item.StudentId];
@@ -406,13 +448,31 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat
return ValidationProblem("分配结果包含性别不匹配的宿舍。");
}
}
var batch = new DormitoryAllocationBatch
DormitoryAllocationBatch batch;
if (request.JobId.HasValue)
{
Name = Normalize(request.Name) ?? $"宿舍分配 {DateTime.Now:yyyy-MM-dd HH:mm}", Mode = request.Mode,
RequestedCount = request.Assignments.Count, AssignedCount = request.Assignments.Count,
CreatedByUserId = scope.Current.UserId
};
db.Add(batch);
var existingBatch = await db.DormitoryAllocationBatches.FirstOrDefaultAsync(x => x.Id == request.JobId &&
x.CreatedByUserId == scope.Current.UserId && x.Mode == DormitoryAllocationMode.Automatic, ct);
if (existingBatch is null) return NotFound();
batch = existingBatch;
if (batch.Status != DormitoryAllocationBatchStatus.PreviewReady)
return ConflictProblem("自动分配任务尚未完成或已经提交。");
batch.Name = Normalize(request.Name) ?? batch.Name;
batch.Status = DormitoryAllocationBatchStatus.Committed;
batch.AssignedCount = request.Assignments.Count;
batch.CompletedAt = DateTime.UtcNow;
}
else
{
batch = new DormitoryAllocationBatch
{
Name = Normalize(request.Name) ?? $"宿舍分配 {DateTime.Now:yyyy-MM-dd HH:mm}", Mode = request.Mode,
Status = DormitoryAllocationBatchStatus.Committed,
RequestedCount = request.Assignments.Count, AssignedCount = request.Assignments.Count,
CreatedByUserId = scope.Current.UserId, CompletedAt = DateTime.UtcNow
};
db.Add(batch);
}
foreach (var item in request.Assignments)
{
db.Add(new DormitoryOccupancy { StudentId = item.StudentId, DormitoryBedId = item.BedId, CheckInDate = request.CheckInDate });
@@ -589,49 +649,69 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat
return NoContent();
}
private async Task<AllocationPreviewResult> BuildAutomaticAssignments(Guid[] studentIds, IReadOnlyList<Guid> buildingIds, CancellationToken ct)
[NonAction]
public async Task<AllocationPreviewResult> BuildAutomaticAssignments(Guid[] studentIds, IReadOnlyList<Guid> buildingIds, CancellationToken ct)
{
var students = await db.Students.Include(x => x.AdministrativeClass!).ThenInclude(x => x.Major)
var students = await db.Students.AsNoTracking()
.Where(x => studentIds.Contains(x.Id) && x.Status == StudentStatus.Active &&
!db.DormitoryOccupancies.Any(o => o.StudentId == x.Id)).ToListAsync(ct);
!db.DormitoryOccupancies.Any(o => o.StudentId == x.Id))
.Select(x => new AllocationStudentData(x.Id, x.StudentNumber, x.Name, x.Gender,
x.AdministrativeClassId, x.AdministrativeClass!.Name, x.AdministrativeClass.MajorId,
x.AdministrativeClass.Major!.Name))
.ToListAsync(ct);
if (students.Count != studentIds.Length) return new([], [], "部分学生不存在、不是在籍状态或已经分配宿舍。");
var bedSource = db.DormitoryBeds.Include(x => x.Occupancy)
.Include(x => x.DormitoryRoom)!.ThenInclude(x => x!.DormitoryBuilding)
.Include(x => x.DormitoryRoom)!.ThenInclude(x => x!.Beds).ThenInclude(x => x.Occupancy)!.ThenInclude(x => x!.Student)!.ThenInclude(x => x!.AdministrativeClass)
var bedSource = db.DormitoryBeds.AsNoTracking()
.Where(x => x.IsEnabled && x.Occupancy == null && x.DormitoryRoom!.IsEnabled && x.DormitoryRoom.DormitoryBuilding!.IsEnabled);
if (buildingIds.Count > 0) bedSource = bedSource.Where(x => buildingIds.Contains(x.DormitoryRoom!.DormitoryBuildingId));
var beds = await bedSource.AsSplitQuery().ToListAsync(ct);
var beds = await bedSource
.OrderBy(x => x.DormitoryRoom!.DormitoryBuilding!.Code)
.ThenBy(x => x.DormitoryRoom!.RoomNumber).ThenBy(x => x.BedNumber)
.Select(x => new AllocationBedData(x.Id, x.DormitoryRoomId, x.BedNumber,
x.DormitoryRoom!.RoomNumber, x.DormitoryRoom.GenderPolicy,
x.DormitoryRoom.DormitoryBuilding!.Code, x.DormitoryRoom.DormitoryBuilding.Name,
x.DormitoryRoom.DormitoryBuilding.GenderPolicy))
.ToListAsync(ct);
var roomIds = beds.Select(x => x.RoomId).Distinct().ToArray();
List<AllocationOccupantData> occupantRows;
if (roomIds.Length == 0)
occupantRows = [];
else
occupantRows = await db.DormitoryOccupancies.AsNoTracking()
.Where(x => roomIds.Contains(x.DormitoryBed!.DormitoryRoomId))
.Select(x => new AllocationOccupantData(x.DormitoryBed!.DormitoryRoomId, x.Student!.Gender,
x.Student.AdministrativeClass!.MajorId, x.Student.AdministrativeClassId))
.ToListAsync(ct);
var currentOccupants = occupantRows.GroupBy(x => x.RoomId).ToDictionary(x => x.Key, x => x.ToList());
var assignments = new List<DormitoryAllocationSuggestion>();
var unassigned = new List<object>();
var virtualAssignments = new Dictionary<Guid, List<Student>>();
foreach (var student in students.OrderBy(x => x.Gender).ThenBy(x => x.AdministrativeClass!.MajorId).ThenBy(x => x.AdministrativeClassId).ThenBy(x => x.StudentNumber))
var reservedBeds = new HashSet<Guid>();
var virtualAssignments = new Dictionary<Guid, List<AllocationStudentData>>();
foreach (var student in students.OrderBy(x => x.Gender).ThenBy(x => x.MajorId).ThenBy(x => x.ClassId).ThenBy(x => x.StudentNumber))
{
var eligible = beds.Where(bed => !assignments.Any(x => x.BedId == bed.Id) && GenderAllowed(student.Gender, bed.DormitoryRoom!))
.Where(bed => RoomGenderCompatible(student.Gender, bed.DormitoryRoom!, virtualAssignments.GetValueOrDefault(bed.DormitoryRoomId)))
var eligible = beds.Where(bed => !reservedBeds.Contains(bed.BedId) && GenderAllowed(student.Gender, bed.RoomGenderPolicy, bed.BuildingGenderPolicy))
.Where(bed => RoomGenderCompatible(student.Gender,
currentOccupants.GetValueOrDefault(bed.RoomId)?.Select(x => x.Gender),
virtualAssignments.GetValueOrDefault(bed.RoomId)?.Select(x => x.Gender)))
.Select(bed => new
{
Bed = bed,
Occupants = bed.DormitoryRoom!.Beds.Where(x => x.Occupancy != null).Select(x => x.Occupancy!.Student!).Concat(virtualAssignments.GetValueOrDefault(bed.DormitoryRoomId) ?? []).ToList()
Occupants = (currentOccupants.GetValueOrDefault(bed.RoomId)?.Select(x => (x.MajorId, x.ClassId)) ?? [])
.Concat(virtualAssignments.GetValueOrDefault(bed.RoomId)?.Select(x => (x.MajorId, x.ClassId)) ?? []).ToList()
})
.Select(x => new
{
x.Bed,
Score = x.Occupants.Count(o => o.AdministrativeClass!.MajorId == student.AdministrativeClass!.MajorId) * 1000 +
x.Occupants.Count(o => o.AdministrativeClassId == student.AdministrativeClassId) * 100 +
x.Occupants.Count * 10
})
.OrderByDescending(x => x.Score).ThenBy(x => x.Bed.DormitoryRoom!.DormitoryBuilding!.Code)
.ThenBy(x => x.Bed.DormitoryRoom!.RoomNumber).ThenBy(x => x.Bed.BedNumber).FirstOrDefault();
.Select(x => new { x.Bed, Score = x.Occupants.Count(o => o.MajorId == student.MajorId) * 1000 +
x.Occupants.Count(o => o.ClassId == student.ClassId) * 100 + x.Occupants.Count * 10 })
.OrderByDescending(x => x.Score).ThenBy(x => x.Bed.BuildingCode)
.ThenBy(x => x.Bed.RoomNumber).ThenBy(x => x.Bed.BedNumber).FirstOrDefault();
if (eligible is null)
{
unassigned.Add(new { student.Id, student.StudentNumber, student.Name, Reason = "没有符合性别约束的空床位" });
continue;
}
var room = eligible.Bed.DormitoryRoom!;
assignments.Add(new DormitoryAllocationSuggestion(student.Id, student.StudentNumber, student.Name,
student.AdministrativeClass!.Major!.Name, student.AdministrativeClass.Name, eligible.Bed.Id,
room.DormitoryBuilding!.Name, room.RoomNumber, eligible.Bed.BedNumber, eligible.Score));
if (!virtualAssignments.TryGetValue(room.Id, out var occupants)) virtualAssignments[room.Id] = occupants = [];
student.MajorName, student.ClassName, eligible.Bed.BedId,
eligible.Bed.BuildingName, eligible.Bed.RoomNumber, eligible.Bed.BedNumber, eligible.Score));
reservedBeds.Add(eligible.Bed.BedId);
if (!virtualAssignments.TryGetValue(eligible.Bed.RoomId, out var occupants)) virtualAssignments[eligible.Bed.RoomId] = occupants = [];
occupants.Add(student);
}
return new(assignments, unassigned, null);
@@ -653,6 +733,21 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat
return gender == Gender.Unknown ? genders.Count == 0 : genders.Count == 0 || genders.All(x => x == gender);
}
private static bool GenderAllowed(Gender gender, DormitoryGenderPolicy roomPolicy, DormitoryGenderPolicy buildingPolicy)
{
var policy = roomPolicy != DormitoryGenderPolicy.Any ? roomPolicy : buildingPolicy;
return policy == DormitoryGenderPolicy.Any ||
policy == DormitoryGenderPolicy.Male && gender == Gender.Male ||
policy == DormitoryGenderPolicy.Female && gender == Gender.Female;
}
private static bool RoomGenderCompatible(Gender gender, IEnumerable<Gender>? currentGenders, IEnumerable<Gender>? virtualGenders)
{
var genders = (currentGenders ?? []).Concat(virtualGenders ?? [])
.Where(x => x != Gender.Unknown).Distinct().ToList();
return gender == Gender.Unknown ? genders.Count == 0 : genders.Count == 0 || genders.All(x => x == gender);
}
private async Task<List<Gender>> CurrentRoomGenders(Guid roomId, CancellationToken ct, Guid? excludingStudentId = null) =>
await db.DormitoryOccupancies.AsNoTracking()
.Where(x => x.DormitoryBed!.DormitoryRoomId == roomId &&
@@ -665,6 +760,13 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat
return gender == Gender.Unknown ? genders.Count == 0 : genders.Count == 0 || genders.All(x => x == gender);
}
private sealed record AllocationStudentData(Guid Id, string StudentNumber, string Name, Gender Gender,
Guid ClassId, string ClassName, Guid MajorId, string MajorName);
private sealed record AllocationBedData(Guid BedId, Guid RoomId, string BedNumber, string RoomNumber,
DormitoryGenderPolicy RoomGenderPolicy, string BuildingCode, string BuildingName,
DormitoryGenderPolicy BuildingGenderPolicy);
private sealed record AllocationOccupantData(Guid RoomId, Gender Gender, Guid MajorId, Guid ClassId);
private IQueryable<DormitoryRoom> ApplyRoomScope(IQueryable<DormitoryRoom> source)
{
var current = scope.Current;
@@ -731,12 +833,13 @@ public sealed record DormitoryRoomRequest(Guid BuildingId, string RoomNumber, in
int BedCount, bool IsEnabled, string? Notes);
public sealed record ReplaceDormitoryBedsRequest(IReadOnlyList<string> BedNumbers);
public sealed record DormitoryAllocationPreviewRequest(IReadOnlyList<Guid> StudentIds, IReadOnlyList<Guid> BuildingIds);
public sealed record DormitoryAllocationJobPayload(Guid[] StudentIds, Guid[] BuildingIds);
public sealed record DormitoryAllocationSuggestion(Guid StudentId, string StudentNumber, string StudentName,
string MajorName, string ClassName, Guid BedId, string BuildingName, string RoomNumber, string BedNumber, int MatchScore);
public sealed record AllocationPreviewResult(IReadOnlyList<DormitoryAllocationSuggestion> Assignments, IReadOnlyList<object> Unassigned, string? Error);
public sealed record DormitoryAllocationItem(Guid StudentId, Guid BedId);
public sealed record CommitDormitoryAllocationRequest(string? Name, DormitoryAllocationMode Mode, DateOnly CheckInDate,
string? Reason, IReadOnlyList<DormitoryAllocationItem> Assignments);
string? Reason, IReadOnlyList<DormitoryAllocationItem> Assignments, Guid? JobId = null);
public sealed record DormitoryTransferRequest(Guid TargetBedId, DateOnly TransferDate, string? Reason);
public sealed record CreateDormitoryApplicationRequest(DormitoryApplicationType Type, Guid? PreferredBuildingId,
Guid? PreferredRoomId, string Reason);
@@ -51,10 +51,15 @@ public sealed class DormitoryAllocationBatch : EntityBase
{
public required string Name { get; set; }
public DormitoryAllocationMode Mode { get; set; }
public DormitoryAllocationBatchStatus Status { get; set; } = DormitoryAllocationBatchStatus.Committed;
public int RequestedCount { get; set; }
public int AssignedCount { get; set; }
public Guid CreatedByUserId { get; set; }
public ApplicationUser? CreatedByUser { get; set; }
public string? RequestPayload { get; set; }
public string? ResultPayload { get; set; }
public string? ErrorMessage { get; set; }
public DateTime? CompletedAt { get; set; }
}
public sealed class DormitoryStayHistory : EntityBase
@@ -127,6 +132,7 @@ public sealed class DormitoryHygieneScore : EntityBase
public enum DormitoryGenderPolicy { Any = 0, Male = 1, Female = 2 }
public enum DormitoryAllocationMode { Manual = 1, Automatic = 2 }
public enum DormitoryAllocationBatchStatus { Queued = 1, Running = 2, PreviewReady = 3, Committed = 4, Failed = 5 }
public enum DormitoryStayAction { CheckIn = 1, Transfer = 2, Checkout = 3 }
public enum DormitoryApplicationType { Transfer = 1, Checkout = 2 }
public enum DormitoryApplicationStatus { Submitted = 1, CounselorApproved = 2, Approved = 3, Rejected = 4, Cancelled = 5 }
@@ -36,7 +36,8 @@ public enum BackgroundJobKind
ExamPublish = 6,
CourseGradeStatisticsRefresh = 7,
GraduationAuditCalculation = 8,
DegreeAwardCalculation = 9
DegreeAwardCalculation = 9,
DormitoryAutomaticAllocation = 10
}
public enum BackgroundJobOutboxState
Loaded 3 of 25 files, more files were not shown because too many files have changed in this diff. Show more