宿舍服务

This commit is contained in:
biss committed 2026-10-19 21:51:19 +08:00
1 parent 1a714e30e4
commit 37c5d6eb93
23 files changed
+12478 -13

No files matched your search

@@ -146,7 +146,7 @@ public sealed class AcademicCalendarController(AppDbContext db, HolidayCnClient
return null;
}
private static readonly HashSet<string> KnownRoles = [SystemRoles.SuperAdmin, SystemRoles.AcademicAdmin, SystemRoles.CollegeAdmin, SystemRoles.Leader, SystemRoles.Counselor, SystemRoles.Teacher, SystemRoles.Student, SystemRoles.MaintenanceAdmin, SystemRoles.MaintenanceStaff, SystemRoles.PhysicalEducationAdmin];
private static readonly HashSet<string> KnownRoles = [SystemRoles.SuperAdmin, SystemRoles.AcademicAdmin, SystemRoles.CollegeAdmin, SystemRoles.Leader, SystemRoles.Counselor, SystemRoles.Teacher, SystemRoles.Student, SystemRoles.MaintenanceAdmin, SystemRoles.MaintenanceStaff, SystemRoles.PhysicalEducationAdmin, SystemRoles.DormitoryAdmin];
private static bool IsForRoles(string? audienceRoles, HashSet<string> roles) => string.IsNullOrWhiteSpace(audienceRoles) || audienceRoles.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Any(roles.Contains);
private static string? SerializeRoles(IReadOnlyCollection<string> roles) => roles.Count == 0 ? null : string.Join(',', roles.Distinct().Order());
private static object ToResponse(AcademicCalendarEvent item) => new { item.Id, item.AcademicTermId, AcademicTermName = item.AcademicTerm?.Name, item.Title, item.Kind, item.StartsOn, item.EndsOn, item.ReminderDays, AudienceRoles = string.IsNullOrWhiteSpace(item.AudienceRoles) ? Array.Empty<string>() : item.AudienceRoles.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries), item.Description, item.IsEnabled, item.Source, item.SourceYear, item.IsOffDay };
@@ -0,0 +1,309 @@
using System.Globalization;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Excel;
using Jiaowu.Api.Infrastructure.Files;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Jiaowu.Api.Controllers;
[ApiController]
[Authorize]
[Route("api/dormitory-hygiene")]
public sealed class DormitoryHygieneController(AppDbContext db, ICurrentUserDataScope scope) : ControllerBase
{
private const string Managers = SystemRoles.SuperAdmin + "," + SystemRoles.AcademicAdmin + "," + SystemRoles.DormitoryAdmin;
private const string Viewers = Managers + "," + SystemRoles.CollegeAdmin + "," + SystemRoles.Counselor;
private static readonly string[] ImportHeaders =
[
"宿舍楼", "房间号", "地面卫生", "床铺整洁", "物品摆放", "设施卫生", "安全规范", "问题说明", "备注"
];
[HttpGet("rooms")]
[Authorize(Roles = Viewers)]
public async Task<ActionResult> GetRooms(string? keyword = null, int page = 1, int pageSize = 30,
CancellationToken ct = default)
{
page = Math.Max(page, 1);
pageSize = Math.Clamp(pageSize, 10, 100);
var source = ApplyRoomScope(db.DormitoryRooms.AsNoTracking());
if (!string.IsNullOrWhiteSpace(keyword))
{
keyword = keyword.Trim();
source = source.Where(x => x.DormitoryBuilding!.Name.Contains(keyword) || x.RoomNumber.Contains(keyword) ||
x.Beds.Any(b => b.Occupancy != null &&
(b.Occupancy.Student!.StudentNumber.Contains(keyword) || b.Occupancy.Student.Name.Contains(keyword))));
}
var total = await source.CountAsync(ct);
var items = await source.OrderBy(x => x.DormitoryBuilding!.Code).ThenBy(x => x.RoomNumber)
.Skip((page - 1) * pageSize).Take(pageSize)
.Select(x => new
{
x.Id, BuildingName = x.DormitoryBuilding!.Name, x.RoomNumber, x.Floor,
Capacity = x.Beds.Count(b => b.IsEnabled),
OccupantCount = x.Beds.Count(b => b.Occupancy != null), x.Notes,
Occupants = x.Beds.Where(b => b.Occupancy != null).OrderBy(b => b.BedNumber).Select(b => new
{
b.Occupancy!.StudentId, b.Occupancy.Student!.StudentNumber, b.Occupancy.Student.Name,
BedNumber = b.BedNumber,
CollegeName = b.Occupancy.Student.AdministrativeClass!.Major!.College!.Name,
ClassName = b.Occupancy.Student.AdministrativeClass.Name
}).ToList()
}).ToListAsync(ct);
return Ok(new { Items = items, Page = page, PageSize = pageSize, Total = total });
}
[HttpGet("batches")]
[Authorize(Roles = Viewers)]
public async Task<ActionResult> GetBatches(string? keyword = null, DormitoryHygieneBatchStatus? status = null,
int page = 1, int pageSize = 20, CancellationToken ct = default)
{
page = Math.Max(page, 1);
pageSize = Math.Clamp(pageSize, 10, 100);
var rooms = ApplyRoomScope(db.DormitoryRooms.AsNoTracking());
var source = db.DormitoryHygieneBatches.AsNoTracking();
if (!string.IsNullOrWhiteSpace(keyword))
{
keyword = keyword.Trim();
source = source.Where(x => x.Name.Contains(keyword) || (x.Inspector != null && x.Inspector.Contains(keyword)));
}
if (status.HasValue) source = source.Where(x => x.Status == status.Value);
var total = await source.CountAsync(ct);
var items = await source.OrderByDescending(x => x.InspectionDate).ThenByDescending(x => x.Id)
.Skip((page - 1) * pageSize).Take(pageSize)
.Select(x => new
{
x.Id, x.Name, x.InspectionDate, x.Inspector, x.Status, x.PublicationCount, x.PublishedAt,
ScoreCount = x.Scores.Count(s => rooms.Any(r => r.Id == s.DormitoryRoomId)),
AverageScore = x.Scores.Where(s => rooms.Any(r => r.Id == s.DormitoryRoomId))
.Select(s => (decimal?)s.TotalScore).Average()
}).ToListAsync(ct);
return Ok(new { Items = items, Page = page, PageSize = pageSize, Total = total });
}
[HttpPost("batches")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> CreateBatch(CreateDormitoryHygieneBatchRequest request, CancellationToken ct)
{
var name = Normalize(request.Name);
if (name is null || name.Length > 150) return ValidationProblem("批次名称不能为空且不能超过 150 个字符。");
if (Normalize(request.Inspector)?.Length > 100) return ValidationProblem("检查人员不能超过 100 个字符。");
var batch = new DormitoryHygieneBatch { Name = name, InspectionDate = request.InspectionDate, Inspector = Normalize(request.Inspector) };
db.DormitoryHygieneBatches.Add(batch);
await db.SaveChangesAsync(ct);
return Ok(new { batch.Id });
}
[HttpGet("batches/{id:guid}/scores")]
[Authorize(Roles = Viewers)]
public async Task<ActionResult> GetScores(Guid id, string? keyword = null, DormitoryHygieneGrade? grade = null,
bool attentionOnly = false, int page = 1, int pageSize = 30, CancellationToken ct = default)
{
var batch = await db.DormitoryHygieneBatches.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id, ct);
if (batch is null) return NotFound();
page = Math.Max(page, 1);
pageSize = Math.Clamp(pageSize, 10, 100);
var rooms = ApplyRoomScope(db.DormitoryRooms.AsNoTracking());
var all = from score in db.DormitoryHygieneScores.AsNoTracking()
join room in rooms on score.DormitoryRoomId equals room.Id
where score.DormitoryHygieneBatchId == id
select new { score, room };
var summary = await all.GroupBy(_ => 1).Select(x => new
{
TotalCount = x.Count(), AverageScore = Math.Round(x.Average(v => v.score.TotalScore), 1),
ExcellentCount = x.Count(v => v.score.Grade == DormitoryHygieneGrade.Excellent),
UnqualifiedCount = x.Count(v => v.score.Grade == DormitoryHygieneGrade.Unqualified)
}).FirstOrDefaultAsync(ct);
var source = all;
if (!string.IsNullOrWhiteSpace(keyword))
{
keyword = keyword.Trim();
source = source.Where(x => x.room.DormitoryBuilding!.Name.Contains(keyword) || x.room.RoomNumber.Contains(keyword));
}
if (grade.HasValue) source = source.Where(x => x.score.Grade == grade.Value);
if (attentionOnly) source = source.Where(x => x.score.Grade == DormitoryHygieneGrade.Unqualified || x.score.Issues != null);
var total = await source.CountAsync(ct);
var items = await source.OrderBy(x => x.room.DormitoryBuilding!.Code).ThenBy(x => x.room.RoomNumber)
.Skip((page - 1) * pageSize).Take(pageSize)
.Select(x => new
{
x.score.Id, x.score.DormitoryRoomId, BuildingName = x.room.DormitoryBuilding!.Name, x.room.RoomNumber,
OccupantCount = x.room.Beds.Count(b => b.Occupancy != null),
x.score.FloorScore, x.score.BeddingScore, x.score.BelongingsScore, x.score.FacilitiesScore,
x.score.SafetyScore, x.score.TotalScore, x.score.Grade, x.score.Issues, x.score.Notes
}).ToListAsync(ct);
return Ok(new
{
Batch = new { batch.Id, batch.Name, batch.InspectionDate, batch.Inspector, batch.Status, batch.PublicationCount, batch.PublishedAt },
Summary = summary ?? new { TotalCount = 0, AverageScore = 0m, ExcellentCount = 0, UnqualifiedCount = 0 },
Scores = new { Items = items, Page = page, PageSize = pageSize, Total = total }
});
}
[HttpPut("batches/{id:guid}/scores")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> UpsertScores(Guid id, UpsertDormitoryHygieneScoresRequest request, CancellationToken ct)
{
var batch = await db.DormitoryHygieneBatches.FirstOrDefaultAsync(x => x.Id == id, ct);
if (batch is null) return NotFound();
if (request.Scores.Count == 0 || request.Scores.Count > 2000) return ValidationProblem("单次应提交 1 到 2000 条宿舍成绩。");
var error = await UpsertScoresAsync(batch, request.Scores, ct);
return error ?? Ok(new { updated = request.Scores.Count });
}
[HttpGet("batches/{id:guid}/template")]
[Authorize(Roles = Managers)]
public async Task<IActionResult> DownloadTemplate(Guid id, CancellationToken ct)
{
var batch = await db.DormitoryHygieneBatches.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id, ct);
if (batch is null) return NotFound();
var bytes = ExcelWorkbookHelper.Create("宿舍卫生成绩导入", ImportHeaders, [],
["每项满分 20 分,总分由系统自动计算。", "宿舍楼与房间号必须和宿舍档案完全一致。"]);
return File(bytes, ExcelWorkbookHelper.ContentType, DownloadFileName.Template("宿舍卫生成绩", ".xlsx", batch.Name));
}
[HttpPost("batches/{id:guid}/import")]
[Authorize(Roles = Managers)]
[RequestSizeLimit(10 * 1024 * 1024)]
public async Task<ActionResult> Import(Guid id, IFormFile file, CancellationToken ct)
{
var batch = await db.DormitoryHygieneBatches.FirstOrDefaultAsync(x => x.Id == id, ct);
if (batch is null) return NotFound();
IReadOnlyList<ExcelRow> rows;
try { rows = await ExcelWorkbookHelper.ReadAsync(file, ImportHeaders, ct); }
catch (InvalidDataException exception) { return ValidationProblem(exception.Message); }
if (rows.Count == 0) return ValidationProblem("Excel 中没有可导入的宿舍成绩。");
var errors = new List<string>();
var buildings = rows.Select(x => x["宿舍楼"].Trim()).Distinct().ToList();
var rooms = await db.DormitoryRooms.Include(x => x.DormitoryBuilding)
.Where(x => buildings.Contains(x.DormitoryBuilding!.Name)).ToListAsync(ct);
var roomMap = rooms.ToDictionary(x => $"{x.DormitoryBuilding!.Name}\n{x.RoomNumber}", StringComparer.OrdinalIgnoreCase);
var inputs = new List<DormitoryHygieneScoreRequest>();
foreach (var row in rows)
{
var key = $"{row["宿舍楼"].Trim()}\n{row["房间号"].Trim()}";
if (!roomMap.TryGetValue(key, out var room)) { errors.Add($"第 {row.RowNumber} 行:未找到对应宿舍档案。"); continue; }
inputs.Add(new DormitoryHygieneScoreRequest(room.Id,
ParseScore(row["地面卫生"], "地面卫生", row.RowNumber, errors),
ParseScore(row["床铺整洁"], "床铺整洁", row.RowNumber, errors),
ParseScore(row["物品摆放"], "物品摆放", row.RowNumber, errors),
ParseScore(row["设施卫生"], "设施卫生", row.RowNumber, errors),
ParseScore(row["安全规范"], "安全规范", row.RowNumber, errors),
Normalize(row["问题说明"]), Normalize(row["备注"])));
}
if (errors.Count > 0) return ImportValidationProblem(errors);
var error = await UpsertScoresAsync(batch, inputs, ct);
return error ?? Ok(new { imported = inputs.Count });
}
[HttpPost("batches/{id:guid}/publish")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> Publish(Guid id, CancellationToken ct)
{
var batch = await db.DormitoryHygieneBatches.Include(x => x.Scores).FirstOrDefaultAsync(x => x.Id == id, ct);
if (batch is null) return NotFound();
if (batch.Scores.Count == 0) return ConflictProblem("没有宿舍成绩,不能发布。");
batch.Status = DormitoryHygieneBatchStatus.Published;
batch.PublicationCount++;
batch.PublishedAt = DateTime.UtcNow;
await db.SaveChangesAsync(ct);
return Ok(new { batch.PublicationCount, batch.PublishedAt });
}
[HttpGet("mine")]
[Authorize(Roles = SystemRoles.Student)]
public async Task<ActionResult> Mine(CancellationToken ct)
{
var studentId = await db.Students.Where(x => x.UserId == scope.Current.UserId).Select(x => (Guid?)x.Id).FirstOrDefaultAsync(ct);
if (studentId is null) return ConflictProblem("当前账号未关联有效学生档案。");
var room = await db.DormitoryOccupancies.AsNoTracking().Where(x => x.StudentId == studentId)
.Select(x => new
{
DormitoryRoomId = x.DormitoryBed!.DormitoryRoomId,
BuildingName = x.DormitoryBed.DormitoryRoom!.DormitoryBuilding!.Name,
x.DormitoryBed.DormitoryRoom.RoomNumber,
x.DormitoryBed.BedNumber,
Capacity = x.DormitoryBed.DormitoryRoom.Beds.Count(b => b.IsEnabled),
OccupantCount = x.DormitoryBed.DormitoryRoom.Beds.Count(b => b.Occupancy != null)
}).FirstOrDefaultAsync(ct);
if (room is null) return Ok(new { Room = (object?)null, Scores = Array.Empty<object>() });
var scores = await db.DormitoryHygieneScores.AsNoTracking()
.Where(x => x.DormitoryRoomId == room.DormitoryRoomId && x.DormitoryHygieneBatch!.Status == DormitoryHygieneBatchStatus.Published)
.OrderByDescending(x => x.DormitoryHygieneBatch!.InspectionDate)
.Select(x => new
{
x.Id, x.DormitoryHygieneBatchId, BatchName = x.DormitoryHygieneBatch!.Name,
x.DormitoryHygieneBatch.InspectionDate, x.DormitoryHygieneBatch.Inspector,
x.FloorScore, x.BeddingScore, x.BelongingsScore, x.FacilitiesScore,
x.SafetyScore, x.TotalScore, x.Grade, x.Issues, x.Notes
}).ToListAsync(ct);
return Ok(new { Room = room, Scores = scores });
}
private async Task<ActionResult?> UpsertScoresAsync(DormitoryHygieneBatch batch,
IReadOnlyList<DormitoryHygieneScoreRequest> inputs, CancellationToken ct)
{
var roomIds = inputs.Select(x => x.DormitoryRoomId).ToList();
if (roomIds.Count != roomIds.Distinct().Count()) return ValidationProblem("本次提交中宿舍不能重复。");
if (await db.DormitoryRooms.CountAsync(x => roomIds.Contains(x.Id), ct) != roomIds.Count)
return ValidationProblem("存在不存在的宿舍,请刷新宿舍档案后重试。");
foreach (var input in inputs)
{
if (new[] { input.FloorScore, input.BeddingScore, input.BelongingsScore, input.FacilitiesScore, input.SafetyScore }.Any(x => x is < 0 or > 20))
return ValidationProblem("每个卫生分项必须在 0 到 20 分之间。");
if (Normalize(input.Issues)?.Length > 1000 || Normalize(input.Notes)?.Length > 500)
return ValidationProblem("问题说明不能超过 1000 个字符,备注不能超过 500 个字符。");
}
var existing = await db.DormitoryHygieneScores
.Where(x => x.DormitoryHygieneBatchId == batch.Id && roomIds.Contains(x.DormitoryRoomId))
.ToDictionaryAsync(x => x.DormitoryRoomId, ct);
foreach (var input in inputs)
{
if (!existing.TryGetValue(input.DormitoryRoomId, out var score))
{
score = new DormitoryHygieneScore { DormitoryHygieneBatchId = batch.Id, DormitoryRoomId = input.DormitoryRoomId };
db.DormitoryHygieneScores.Add(score);
}
score.FloorScore = input.FloorScore; score.BeddingScore = input.BeddingScore;
score.BelongingsScore = input.BelongingsScore; score.FacilitiesScore = input.FacilitiesScore;
score.SafetyScore = input.SafetyScore;
score.TotalScore = input.FloorScore + input.BeddingScore + input.BelongingsScore + input.FacilitiesScore + input.SafetyScore;
score.Grade = GradeFor(score.TotalScore); score.Issues = Normalize(input.Issues); score.Notes = Normalize(input.Notes);
}
await db.SaveChangesAsync(ct);
return null;
}
private IQueryable<DormitoryRoom> ApplyRoomScope(IQueryable<DormitoryRoom> source)
{
var current = scope.Current;
if (current.Scope == DataScope.All) return source;
if (current.Scope == DataScope.College)
return source.Where(x => x.Beds.Any(b => b.Occupancy != null && b.Occupancy.Student!.AdministrativeClass!.Major!.CollegeId == current.RestrictedCollegeId));
if (current.Scope == DataScope.Class)
return source.Where(x => x.Beds.Any(b => b.Occupancy != null && b.Occupancy.Student!.AdministrativeClass!.CounselorUserId == current.UserId));
return source.Where(x => x.Beds.Any(b => b.Occupancy != null && b.Occupancy.Student!.UserId == current.UserId));
}
private static DormitoryHygieneGrade GradeFor(decimal score) => score switch
{ >= 90 => DormitoryHygieneGrade.Excellent, >= 80 => DormitoryHygieneGrade.Good, >= 60 => DormitoryHygieneGrade.Qualified, _ => DormitoryHygieneGrade.Unqualified };
private static decimal ParseScore(string value, string field, int row, List<string> errors)
{
if (decimal.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out var score) && score is >= 0 and <= 20) return score;
errors.Add($"第 {row} 行:{field}必须填写 0 到 20 之间的数字。"); return 0;
}
private static string? Normalize(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
private ActionResult ConflictProblem(string detail) => Conflict(new ProblemDetails { Status = 409, Detail = detail });
private ActionResult ValidationProblem(string detail) => BadRequest(new ValidationProblemDetails { Detail = detail });
private ActionResult ImportValidationProblem(IReadOnlyList<string> errors) => BadRequest(new ValidationProblemDetails
{ Detail = string.Join(";", errors.Take(20)) + (errors.Count > 20 ? $";另有 {errors.Count - 20} 项错误" : string.Empty) });
}
public sealed record CreateDormitoryHygieneBatchRequest(string Name, DateOnly InspectionDate, string? Inspector);
public sealed record DormitoryHygieneScoreRequest(Guid DormitoryRoomId, decimal FloorScore, decimal BeddingScore,
decimal BelongingsScore, decimal FacilitiesScore, decimal SafetyScore, string? Issues, string? Notes);
public sealed record UpsertDormitoryHygieneScoresRequest(IReadOnlyList<DormitoryHygieneScoreRequest> Scores);
@@ -0,0 +1,567 @@
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Jiaowu.Api.Controllers;
[ApiController]
[Authorize]
[Route("api/dormitory-services")]
public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDataScope scope) : ControllerBase
{
private const string Managers = SystemRoles.SuperAdmin + "," + SystemRoles.AcademicAdmin + "," + SystemRoles.DormitoryAdmin;
private const string Viewers = Managers + "," + SystemRoles.CollegeAdmin + "," + SystemRoles.Counselor;
private const string CounselorReviewers = SystemRoles.SuperAdmin + "," + SystemRoles.AcademicAdmin + "," + SystemRoles.CollegeAdmin + "," + SystemRoles.Counselor;
[HttpGet("overview")]
[Authorize(Roles = Viewers)]
public async Task<ActionResult> GetOverview(CancellationToken ct)
{
var rooms = ApplyRoomScope(db.DormitoryRooms.AsNoTracking());
var buildingStats = await db.DormitoryBuildings.AsNoTracking()
.Where(building => rooms.Any(room => room.DormitoryBuildingId == building.Id) || scope.Current.Scope == DataScope.All)
.OrderBy(building => building.Code)
.Select(building => new
{
building.Id, building.Code, building.Name,
RoomCount = building.Rooms.Count(room => room.IsEnabled && (scope.Current.Scope == DataScope.All || rooms.Any(r => r.Id == room.Id))),
BedCount = building.Rooms.Where(room => room.IsEnabled && (scope.Current.Scope == DataScope.All || rooms.Any(r => r.Id == room.Id)))
.SelectMany(room => room.Beds).Count(bed => bed.IsEnabled),
OccupiedCount = building.Rooms.Where(room => room.IsEnabled && (scope.Current.Scope == DataScope.All || rooms.Any(r => r.Id == room.Id)))
.SelectMany(room => room.Beds).Count(bed => bed.IsEnabled && bed.Occupancy != null),
MaleCount = building.Rooms.SelectMany(room => room.Beds).Count(bed => bed.Occupancy != null && bed.Occupancy.Student!.Gender == Gender.Male),
FemaleCount = building.Rooms.SelectMany(room => room.Beds).Count(bed => bed.Occupancy != null && bed.Occupancy.Student!.Gender == Gender.Female)
}).ToListAsync(ct);
var beds = buildingStats.Sum(x => x.BedCount);
var occupied = buildingStats.Sum(x => x.OccupiedCount);
var pendingApplications = await ApplyApplicationScope(db.DormitoryApplications.AsNoTracking())
.CountAsync(x => x.Status == DormitoryApplicationStatus.Submitted || x.Status == DormitoryApplicationStatus.CounselorApproved, ct);
var unassignedStudents = scope.Current.Scope == DataScope.All
? await db.Students.AsNoTracking().CountAsync(student => student.Status == StudentStatus.Active &&
!db.DormitoryOccupancies.Any(occupancy => occupancy.StudentId == student.Id), ct)
: 0;
return Ok(new
{
BuildingCount = buildingStats.Count,
RoomCount = buildingStats.Sum(x => x.RoomCount),
BedCount = beds, OccupiedCount = occupied, VacantCount = beds - occupied,
OccupancyRate = beds == 0 ? 0 : Math.Round(occupied * 100m / beds, 1),
VacancyRate = beds == 0 ? 0 : Math.Round((beds - occupied) * 100m / beds, 1),
UnassignedStudentCount = unassignedStudents,
PendingApplicationCount = pendingApplications,
Buildings = buildingStats
});
}
[HttpGet("buildings")]
[Authorize(Roles = Viewers)]
public async Task<ActionResult> GetBuildings(CancellationToken ct)
{
var scopedRooms = ApplyRoomScope(db.DormitoryRooms.AsNoTracking());
var buildings = await db.DormitoryBuildings.AsNoTracking()
.Where(x => scope.Current.Scope == DataScope.All || scopedRooms.Any(room => room.DormitoryBuildingId == x.Id))
.OrderBy(x => x.Code)
.Select(x => new
{
x.Id, x.Code, x.Name, x.CampusId, CampusName = x.Campus != null ? x.Campus.Name : null,
x.FloorCount, x.GenderPolicy, x.IsEnabled, x.Notes,
Rooms = x.Rooms.Where(room => scope.Current.Scope == DataScope.All || scopedRooms.Any(r => r.Id == room.Id))
.OrderBy(room => room.Floor).ThenBy(room => room.RoomNumber).Select(room => new
{
room.Id, room.RoomNumber, room.Floor, room.GenderPolicy, room.IsEnabled, room.Notes,
Capacity = room.Beds.Count(bed => bed.IsEnabled),
OccupiedCount = room.Beds.Count(bed => bed.IsEnabled && bed.Occupancy != null),
Beds = room.Beds.OrderBy(bed => bed.BedNumber).Select(bed => new
{
bed.Id, bed.BedNumber, bed.IsEnabled,
Occupant = bed.Occupancy == null ? null : new
{
bed.Occupancy.StudentId, bed.Occupancy.Student!.StudentNumber,
bed.Occupancy.Student.Name, bed.Occupancy.CheckInDate,
MajorName = bed.Occupancy.Student.AdministrativeClass!.Major!.Name,
ClassName = bed.Occupancy.Student.AdministrativeClass.Name
}
}).ToList()
}).ToList()
}).ToListAsync(ct);
return Ok(buildings);
}
[HttpPost("buildings")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> CreateBuilding(DormitoryBuildingRequest request, CancellationToken ct)
{
var error = ValidateBuilding(request);
if (error is not null) return ValidationProblem(error);
var code = request.Code.Trim().ToUpperInvariant();
if (await db.DormitoryBuildings.AnyAsync(x => x.Code == code, ct)) return ConflictProblem("楼栋编码已经存在。");
if (request.CampusId.HasValue && !await db.Campuses.AnyAsync(x => x.Id == request.CampusId, ct)) return ValidationProblem("校区不存在。");
var building = new DormitoryBuilding
{
Code = code, Name = request.Name.Trim(), CampusId = request.CampusId,
FloorCount = request.FloorCount, GenderPolicy = request.GenderPolicy,
IsEnabled = request.IsEnabled, Notes = Normalize(request.Notes)
};
db.Add(building);
await db.SaveChangesAsync(ct);
return Ok(new { building.Id });
}
[HttpPut("buildings/{id:guid}")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> UpdateBuilding(Guid id, DormitoryBuildingRequest request, CancellationToken ct)
{
var building = await db.DormitoryBuildings.FirstOrDefaultAsync(x => x.Id == id, ct);
if (building is null) return NotFound();
var error = ValidateBuilding(request);
if (error is not null) return ValidationProblem(error);
var code = request.Code.Trim().ToUpperInvariant();
if (await db.DormitoryBuildings.AnyAsync(x => x.Id != id && x.Code == code, ct)) return ConflictProblem("楼栋编码已经存在。");
building.Code = code; building.Name = request.Name.Trim(); building.CampusId = request.CampusId;
building.FloorCount = request.FloorCount; building.GenderPolicy = request.GenderPolicy;
building.IsEnabled = request.IsEnabled; building.Notes = Normalize(request.Notes);
await db.SaveChangesAsync(ct);
return NoContent();
}
[HttpPost("rooms")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> CreateRoom(DormitoryRoomRequest request, CancellationToken ct)
{
var error = ValidateRoom(request);
if (error is not null) return ValidationProblem(error);
var building = await db.DormitoryBuildings.FirstOrDefaultAsync(x => x.Id == request.BuildingId, ct);
if (building is null) return ValidationProblem("宿舍楼不存在。");
var roomNumber = request.RoomNumber.Trim();
if (await db.DormitoryRooms.AnyAsync(x => x.DormitoryBuildingId == request.BuildingId && x.RoomNumber == roomNumber, ct))
return ConflictProblem("该楼栋内已经存在此房间号。");
var room = new DormitoryRoom
{
DormitoryBuildingId = request.BuildingId, RoomNumber = roomNumber, Floor = request.Floor,
GenderPolicy = request.GenderPolicy, IsEnabled = request.IsEnabled, Notes = Normalize(request.Notes)
};
for (var i = 1; i <= request.BedCount; i++) room.Beds.Add(new DormitoryBed { BedNumber = i.ToString() });
db.Add(room);
await db.SaveChangesAsync(ct);
return Ok(new { room.Id });
}
[HttpPut("rooms/{id:guid}")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> UpdateRoom(Guid id, DormitoryRoomRequest request, CancellationToken ct)
{
var room = await db.DormitoryRooms.FirstOrDefaultAsync(x => x.Id == id, ct);
if (room is null) return NotFound();
var error = ValidateRoom(request, requireBedCount: false);
if (error is not null) return ValidationProblem(error);
if (await db.DormitoryRooms.AnyAsync(x => x.Id != id && x.DormitoryBuildingId == request.BuildingId && x.RoomNumber == request.RoomNumber.Trim(), ct))
return ConflictProblem("该楼栋内已经存在此房间号。");
room.DormitoryBuildingId = request.BuildingId; room.RoomNumber = request.RoomNumber.Trim(); room.Floor = request.Floor;
room.GenderPolicy = request.GenderPolicy; room.IsEnabled = request.IsEnabled; room.Notes = Normalize(request.Notes);
await db.SaveChangesAsync(ct);
return NoContent();
}
[HttpPut("rooms/{id:guid}/beds")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> ReplaceBeds(Guid id, ReplaceDormitoryBedsRequest request, CancellationToken ct)
{
var room = await db.DormitoryRooms.Include(x => x.Beds).ThenInclude(x => x.Occupancy).FirstOrDefaultAsync(x => x.Id == id, ct);
if (room is null) return NotFound();
var numbers = request.BedNumbers.Select(x => x.Trim()).Where(x => x.Length > 0).ToList();
if (numbers.Count is < 1 or > 20 || numbers.Any(x => x.Length > 20) || numbers.Count != numbers.Distinct(StringComparer.OrdinalIgnoreCase).Count())
return ValidationProblem("床位应为 1 到 20 个不重复、长度不超过 20 的编号。");
var removingOccupied = room.Beds.Any(bed => bed.Occupancy != null && !numbers.Contains(bed.BedNumber, StringComparer.OrdinalIgnoreCase));
if (removingOccupied) return ConflictProblem("不能删除已有学生入住的床位,请先办理调宿或退宿。");
foreach (var bed in room.Beds.Where(b => !numbers.Contains(b.BedNumber, StringComparer.OrdinalIgnoreCase))) db.Remove(bed);
foreach (var number in numbers.Where(number => room.Beds.All(b => !string.Equals(b.BedNumber, number, StringComparison.OrdinalIgnoreCase))))
db.Add(new DormitoryBed { DormitoryRoomId = room.Id, BedNumber = number });
await db.SaveChangesAsync(ct);
return Ok(new { count = numbers.Count });
}
[HttpGet("unassigned-students")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> GetUnassignedStudents(Guid? collegeId = null, Guid? majorId = null,
Guid? classId = null, Gender? gender = null, string? keyword = null, int page = 1, int pageSize = 50,
CancellationToken ct = default)
{
page = Math.Max(1, page); pageSize = Math.Clamp(pageSize, 10, 200);
var source = db.Students.AsNoTracking().Where(x => x.Status == StudentStatus.Active &&
!db.DormitoryOccupancies.Any(occupancy => occupancy.StudentId == x.Id));
if (collegeId.HasValue) source = source.Where(x => x.AdministrativeClass!.Major!.CollegeId == collegeId);
if (majorId.HasValue) source = source.Where(x => x.AdministrativeClass!.MajorId == majorId);
if (classId.HasValue) source = source.Where(x => x.AdministrativeClassId == classId);
if (gender.HasValue) source = source.Where(x => x.Gender == gender);
if (!string.IsNullOrWhiteSpace(keyword)) { keyword = keyword.Trim(); source = source.Where(x => x.StudentNumber.Contains(keyword) || x.Name.Contains(keyword)); }
var total = await source.CountAsync(ct);
var items = await source.OrderBy(x => x.AdministrativeClass!.MajorId).ThenBy(x => x.AdministrativeClassId).ThenBy(x => x.StudentNumber)
.Skip((page - 1) * pageSize).Take(pageSize)
.Select(x => new
{
x.Id, x.StudentNumber, x.Name, x.Gender, x.AdministrativeClassId,
ClassName = x.AdministrativeClass!.Name, MajorId = x.AdministrativeClass.MajorId,
MajorName = x.AdministrativeClass.Major!.Name,
CollegeId = x.AdministrativeClass.Major.CollegeId, CollegeName = x.AdministrativeClass.Major.College!.Name
}).ToListAsync(ct);
return Ok(new { Items = items, Total = total, Page = page, PageSize = pageSize });
}
[HttpPost("allocations/preview")]
[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);
}
[HttpPost("allocations/commit")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> CommitAllocation(CommitDormitoryAllocationRequest request, CancellationToken ct)
{
if (request.Assignments.Count == 0 || request.Assignments.Count > 2000) return ValidationProblem("单次应提交 1 到 2000 条分配结果。");
if (request.Assignments.Select(x => x.StudentId).Distinct().Count() != request.Assignments.Count ||
request.Assignments.Select(x => x.BedId).Distinct().Count() != request.Assignments.Count)
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)
.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 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);
foreach (var item in roomGroup)
{
var student = students[item.StudentId];
var room = beds[item.BedId].DormitoryRoom!;
if (!GenderAllowed(student.Gender, room) || !GenderCompatible(student.Gender, existingGenders.Concat(incomingGenders)))
return ValidationProblem("分配结果包含性别不匹配的宿舍。");
}
}
var batch = new DormitoryAllocationBatch
{
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);
foreach (var item in request.Assignments)
{
db.Add(new DormitoryOccupancy { StudentId = item.StudentId, DormitoryBedId = item.BedId, CheckInDate = request.CheckInDate });
db.Add(new DormitoryStayHistory
{
StudentId = item.StudentId, ToBedId = item.BedId, Action = DormitoryStayAction.CheckIn,
Reason = Normalize(request.Reason) ?? "批量宿舍分配", DormitoryAllocationBatchId = batch.Id,
OperatedByUserId = scope.Current.UserId
});
}
await db.SaveChangesAsync(ct);
return Ok(new { batch.Id, batch.AssignedCount });
}
[HttpPost("occupancies/{studentId:guid}/transfer")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> Transfer(Guid studentId, DormitoryTransferRequest request, CancellationToken ct)
{
var occupancy = await db.DormitoryOccupancies.FirstOrDefaultAsync(x => x.StudentId == studentId, ct);
if (occupancy is null) return ConflictProblem("该学生当前没有在住宿舍。");
var target = await db.DormitoryBeds.Include(x => x.Occupancy).Include(x => x.DormitoryRoom)!.ThenInclude(x => x!.DormitoryBuilding)
.FirstOrDefaultAsync(x => x.Id == request.TargetBedId, ct);
var student = await db.Students.FirstAsync(x => x.Id == studentId, ct);
if (target is null || !target.IsEnabled || target.Occupancy != null) return ConflictProblem("目标床位不存在、已停用或已被占用。");
if (!GenderAllowed(student.Gender, target.DormitoryRoom!) ||
!GenderCompatible(student.Gender, await CurrentRoomGenders(target.DormitoryRoomId, ct, studentId)))
return ValidationProblem("目标宿舍与学生性别不匹配。");
var fromBedId = occupancy.DormitoryBedId;
occupancy.DormitoryBedId = target.Id;
occupancy.CheckInDate = request.TransferDate;
db.Add(new DormitoryStayHistory
{
StudentId = studentId, FromBedId = fromBedId, ToBedId = target.Id,
Action = DormitoryStayAction.Transfer, Reason = Normalize(request.Reason),
OperatedByUserId = scope.Current.UserId
});
await db.SaveChangesAsync(ct);
return NoContent();
}
[HttpGet("applications")]
[Authorize(Roles = Viewers)]
public async Task<ActionResult> GetApplications(DormitoryApplicationStatus? status = null,
DormitoryApplicationType? type = null, CancellationToken ct = default)
{
var source = ApplyApplicationScope(db.DormitoryApplications.AsNoTracking());
if (status.HasValue) source = source.Where(x => x.Status == status.Value);
if (type.HasValue) source = source.Where(x => x.Type == type.Value);
var items = await source.OrderByDescending(x => x.SubmittedAt).Take(500).Select(x => new
{
x.Id, x.Type, x.Status, x.Reason, x.SubmittedAt, x.StudentId,
x.Student!.StudentNumber, StudentName = x.Student.Name,
CollegeName = x.Student.AdministrativeClass!.Major!.College!.Name,
ClassName = x.Student.AdministrativeClass.Name,
Current = db.DormitoryBeds.Where(b => b.Id == x.CurrentBedId).Select(b => b.DormitoryRoom!.DormitoryBuilding!.Name + " " + b.DormitoryRoom.RoomNumber + "-" + b.BedNumber).FirstOrDefault(),
PreferredBuildingName = x.PreferredBuilding != null ? x.PreferredBuilding.Name : null,
PreferredRoomNumber = x.PreferredRoom != null ? x.PreferredRoom.RoomNumber : null,
x.CounselorComment, x.CounselorReviewedAt, x.FinalComment, x.FinalReviewedAt, x.TargetBedId
}).ToListAsync(ct);
return Ok(items);
}
[HttpGet("applications/mine")]
[Authorize(Roles = SystemRoles.Student)]
public async Task<ActionResult> GetMyApplications(CancellationToken ct)
{
var studentId = await CurrentStudentId(ct);
if (studentId is null) return ConflictProblem("当前账号未关联有效学生档案。");
var items = await db.DormitoryApplications.AsNoTracking().Where(x => x.StudentId == studentId)
.OrderByDescending(x => x.SubmittedAt).Select(x => new
{
x.Id, x.Type, x.Status, x.Reason, x.SubmittedAt,
PreferredBuildingName = x.PreferredBuilding != null ? x.PreferredBuilding.Name : null,
PreferredRoomNumber = x.PreferredRoom != null ? x.PreferredRoom.RoomNumber : null,
x.CounselorComment, x.FinalComment, x.FinalReviewedAt
}).ToListAsync(ct);
return Ok(items);
}
[HttpPost("applications")]
[Authorize(Roles = SystemRoles.Student)]
public async Task<ActionResult> CreateApplication(CreateDormitoryApplicationRequest request, CancellationToken ct)
{
var studentId = await CurrentStudentId(ct);
if (studentId is null) return ConflictProblem("当前账号未关联有效学生档案。");
var occupancy = await db.DormitoryOccupancies.AsNoTracking().FirstOrDefaultAsync(x => x.StudentId == studentId, ct);
if (occupancy is null) return ConflictProblem("当前没有在住宿舍,不能提交调宿或退宿申请。");
if (!Enum.IsDefined(request.Type)) return ValidationProblem("申请类型无效。");
var reason = Normalize(request.Reason);
if (reason is null || reason.Length > 1000) return ValidationProblem("申请原因不能为空且不能超过 1000 个字符。");
if (await db.DormitoryApplications.AnyAsync(x => x.StudentId == studentId &&
(x.Status == DormitoryApplicationStatus.Submitted || x.Status == DormitoryApplicationStatus.CounselorApproved), ct))
return ConflictProblem("你已有一条正在办理的住宿申请。");
var application = new DormitoryApplication
{
StudentId = studentId.Value, Type = request.Type, CurrentBedId = occupancy.DormitoryBedId,
PreferredBuildingId = request.Type == DormitoryApplicationType.Transfer ? request.PreferredBuildingId : null,
PreferredRoomId = request.Type == DormitoryApplicationType.Transfer ? request.PreferredRoomId : null,
Reason = reason
};
db.Add(application);
await db.SaveChangesAsync(ct);
return Ok(new { application.Id });
}
[HttpPost("applications/{id:guid}/counselor-review")]
[Authorize(Roles = CounselorReviewers)]
public async Task<ActionResult> CounselorReview(Guid id, DormitoryReviewRequest request, CancellationToken ct)
{
var application = await ApplyApplicationScope(db.DormitoryApplications).FirstOrDefaultAsync(x => x.Id == id, ct);
if (application is null) return NotFound();
if (application.Status != DormitoryApplicationStatus.Submitted) return ConflictProblem("申请当前状态不能进行辅导员审核。");
application.Status = request.Approved ? DormitoryApplicationStatus.CounselorApproved : DormitoryApplicationStatus.Rejected;
application.CounselorReviewedByUserId = scope.Current.UserId; application.CounselorReviewedAt = DateTime.UtcNow;
application.CounselorComment = Normalize(request.Comment);
await db.SaveChangesAsync(ct);
return NoContent();
}
[HttpPost("applications/{id:guid}/final-review")]
[Authorize(Roles = Managers)]
public async Task<ActionResult> FinalReview(Guid id, DormitoryFinalReviewRequest request, CancellationToken ct)
{
var application = await db.DormitoryApplications.Include(x => x.Student).FirstOrDefaultAsync(x => x.Id == id, ct);
if (application is null) return NotFound();
if (application.Status != DormitoryApplicationStatus.CounselorApproved) return ConflictProblem("申请尚未通过辅导员审核。");
application.FinalReviewedByUserId = scope.Current.UserId; application.FinalReviewedAt = DateTime.UtcNow;
application.FinalComment = Normalize(request.Comment);
if (!request.Approved)
{
application.Status = DormitoryApplicationStatus.Rejected;
await db.SaveChangesAsync(ct); return NoContent();
}
var occupancy = await db.DormitoryOccupancies.FirstOrDefaultAsync(x => x.StudentId == application.StudentId, ct);
if (occupancy is null) return ConflictProblem("学生住宿状态已变化,请核对后处理。");
var fromBedId = occupancy.DormitoryBedId;
Guid? toBedId = null;
if (application.Type == DormitoryApplicationType.Transfer)
{
if (!request.TargetBedId.HasValue) return ValidationProblem("批准调宿申请时必须选择目标床位。");
var target = await db.DormitoryBeds.Include(x => x.Occupancy).Include(x => x.DormitoryRoom)!.ThenInclude(x => x!.DormitoryBuilding)
.FirstOrDefaultAsync(x => x.Id == request.TargetBedId, ct);
if (target is null || target.Occupancy != null || !target.IsEnabled) return ConflictProblem("目标床位不可用。");
if (!GenderAllowed(application.Student!.Gender, target.DormitoryRoom!) ||
!GenderCompatible(application.Student.Gender, await CurrentRoomGenders(target.DormitoryRoomId, ct, application.StudentId)))
return ValidationProblem("目标宿舍与学生性别不匹配。");
occupancy.DormitoryBedId = target.Id; occupancy.CheckInDate = DateOnly.FromDateTime(DateTime.Today); toBedId = target.Id;
application.TargetBedId = target.Id;
}
else db.Remove(occupancy);
application.Status = DormitoryApplicationStatus.Approved;
db.Add(new DormitoryStayHistory
{
StudentId = application.StudentId, FromBedId = fromBedId, ToBedId = toBedId,
Action = application.Type == DormitoryApplicationType.Transfer ? DormitoryStayAction.Transfer : DormitoryStayAction.Checkout,
Reason = application.Reason, DormitoryApplicationId = application.Id, OperatedByUserId = scope.Current.UserId
});
await db.SaveChangesAsync(ct);
return NoContent();
}
[HttpPost("applications/{id:guid}/cancel")]
[Authorize(Roles = SystemRoles.Student)]
public async Task<ActionResult> CancelApplication(Guid id, CancellationToken ct)
{
var studentId = await CurrentStudentId(ct);
var application = await db.DormitoryApplications.FirstOrDefaultAsync(x => x.Id == id && x.StudentId == studentId, ct);
if (application is null) return NotFound();
if (application.Status != DormitoryApplicationStatus.Submitted) return ConflictProblem("当前状态不能撤回申请。");
application.Status = DormitoryApplicationStatus.Cancelled;
await db.SaveChangesAsync(ct);
return NoContent();
}
private async Task<AllocationPreviewResult> BuildAutomaticAssignments(Guid[] studentIds, IReadOnlyList<Guid> buildingIds, CancellationToken ct)
{
var students = await db.Students.Include(x => x.AdministrativeClass!).ThenInclude(x => x.Major)
.Where(x => studentIds.Contains(x.Id) && x.Status == StudentStatus.Active &&
!db.DormitoryOccupancies.Any(o => o.StudentId == x.Id)).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)
.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 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 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)))
.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()
})
.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();
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 = [];
occupants.Add(student);
}
return new(assignments, unassigned, null);
}
private static bool GenderAllowed(Gender gender, DormitoryRoom room)
{
var policy = room.GenderPolicy != DormitoryGenderPolicy.Any ? room.GenderPolicy : room.DormitoryBuilding!.GenderPolicy;
return policy == DormitoryGenderPolicy.Any ||
policy == DormitoryGenderPolicy.Male && gender == Gender.Male ||
policy == DormitoryGenderPolicy.Female && gender == Gender.Female;
}
private static bool RoomGenderCompatible(Gender gender, DormitoryRoom room, IReadOnlyList<Student>? virtualStudents)
{
if (!GenderAllowed(gender, room)) return false;
var genders = room.Beds.Where(x => x.Occupancy != null).Select(x => x.Occupancy!.Student!.Gender)
.Concat(virtualStudents?.Select(x => x.Gender) ?? []).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 &&
(!excludingStudentId.HasValue || x.StudentId != excludingStudentId.Value))
.Select(x => x.Student!.Gender).Where(x => x != Gender.Unknown).Distinct().ToListAsync(ct);
private static bool GenderCompatible(Gender gender, IEnumerable<Gender> roomGenders)
{
var genders = roomGenders.Where(x => x != Gender.Unknown).Distinct().ToList();
return gender == Gender.Unknown ? genders.Count == 0 : genders.Count == 0 || genders.All(x => x == gender);
}
private IQueryable<DormitoryRoom> ApplyRoomScope(IQueryable<DormitoryRoom> source)
{
var current = scope.Current;
if (current.Scope == DataScope.All) return source;
if (current.Scope == DataScope.College)
return source.Where(x => x.Beds.Any(b => b.Occupancy != null && b.Occupancy.Student!.AdministrativeClass!.Major!.CollegeId == current.RestrictedCollegeId));
if (current.Scope == DataScope.Class)
return source.Where(x => x.Beds.Any(b => b.Occupancy != null && b.Occupancy.Student!.AdministrativeClass!.CounselorUserId == current.UserId));
return source.Where(x => x.Beds.Any(b => b.Occupancy != null && b.Occupancy.Student!.UserId == current.UserId));
}
private IQueryable<DormitoryApplication> ApplyApplicationScope(IQueryable<DormitoryApplication> source)
{
var current = scope.Current;
if (current.Scope == DataScope.All) return source;
if (current.Scope == DataScope.College) return source.Where(x => x.Student!.AdministrativeClass!.Major!.CollegeId == current.RestrictedCollegeId);
if (current.Scope == DataScope.Class) return source.Where(x => x.Student!.AdministrativeClass!.CounselorUserId == current.UserId);
return source.Where(x => x.Student!.UserId == current.UserId);
}
private async Task<Guid?> CurrentStudentId(CancellationToken ct) => await db.Students.Where(x => x.UserId == scope.Current.UserId).Select(x => (Guid?)x.Id).FirstOrDefaultAsync(ct);
private static string? ValidateBuilding(DormitoryBuildingRequest request)
{
if (string.IsNullOrWhiteSpace(request.Code) || request.Code.Trim().Length > 30 || string.IsNullOrWhiteSpace(request.Name) || request.Name.Trim().Length > 100) return "楼栋编码和名称不能为空且不能超过长度限制。";
if (request.FloorCount is < 1 or > 100) return "楼层数必须在 1 到 100 之间。";
if (!Enum.IsDefined(request.GenderPolicy)) return "住宿性别规则无效。";
return Normalize(request.Notes)?.Length > 500 ? "备注不能超过 500 个字符。" : null;
}
private static string? ValidateRoom(DormitoryRoomRequest request, bool requireBedCount = true)
{
if (string.IsNullOrWhiteSpace(request.RoomNumber) || request.RoomNumber.Trim().Length > 30) return "房间号不能为空且不能超过 30 个字符。";
if (request.Floor is < 1 or > 100) return "楼层必须在 1 到 100 之间。";
if (requireBedCount && request.BedCount is < 1 or > 20) return "床位数必须在 1 到 20 之间。";
if (!Enum.IsDefined(request.GenderPolicy)) return "住宿性别规则无效。";
return Normalize(request.Notes)?.Length > 500 ? "备注不能超过 500 个字符。" : null;
}
private static string? Normalize(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
private ActionResult ConflictProblem(string detail) => Conflict(new ProblemDetails { Status = 409, Detail = detail });
private ActionResult ValidationProblem(string detail) => BadRequest(new ValidationProblemDetails { Detail = detail });
}
public sealed record DormitoryBuildingRequest(string Code, string Name, Guid? CampusId, int FloorCount,
DormitoryGenderPolicy GenderPolicy, bool IsEnabled, string? Notes);
public sealed record DormitoryRoomRequest(Guid BuildingId, string RoomNumber, int Floor, DormitoryGenderPolicy GenderPolicy,
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 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);
public sealed record DormitoryTransferRequest(Guid TargetBedId, DateOnly TransferDate, string? Reason);
public sealed record CreateDormitoryApplicationRequest(DormitoryApplicationType Type, Guid? PreferredBuildingId,
Guid? PreferredRoomId, string Reason);
public sealed record DormitoryReviewRequest(bool Approved, string? Comment);
public sealed record DormitoryFinalReviewRequest(bool Approved, Guid? TargetBedId, string? Comment);
Loaded 3 of 23 files, more files were not shown because too many files have changed in this diff. Show more