宿舍模块优化
This commit is contained in:
1 parent
bd7c586c5a
commit
4360280aee
13 files changed
+10277
-23
No files matched your search
@@ -100,8 +100,9 @@ public sealed class DormitoryHygieneController(AppDbContext db, ICurrentUserData
|
||||
|
||||
[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)
|
||||
public async Task<ActionResult> GetScores(Guid id, string? keyword = null, Guid? buildingId = null, int? floor = 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();
|
||||
@@ -119,6 +120,8 @@ public sealed class DormitoryHygieneController(AppDbContext db, ICurrentUserData
|
||||
UnqualifiedCount = x.Count(v => v.score.Grade == DormitoryHygieneGrade.Unqualified)
|
||||
}).FirstOrDefaultAsync(ct);
|
||||
var source = all;
|
||||
if (buildingId.HasValue) source = source.Where(x => x.room.DormitoryBuildingId == buildingId.Value);
|
||||
if (floor.HasValue) source = source.Where(x => x.room.Floor == floor.Value);
|
||||
if (!string.IsNullOrWhiteSpace(keyword))
|
||||
{
|
||||
keyword = keyword.Trim();
|
||||
@@ -131,7 +134,8 @@ public sealed class DormitoryHygieneController(AppDbContext db, ICurrentUserData
|
||||
.Skip((page - 1) * pageSize).Take(pageSize)
|
||||
.Select(x => new
|
||||
{
|
||||
x.score.Id, x.score.DormitoryRoomId, BuildingName = x.room.DormitoryBuilding!.Name, x.room.RoomNumber,
|
||||
x.score.Id, x.score.DormitoryRoomId, x.room.DormitoryBuildingId,
|
||||
BuildingName = x.room.DormitoryBuilding!.Name, x.room.RoomNumber, x.room.Floor,
|
||||
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
|
||||
@@ -166,6 +170,32 @@ public sealed class DormitoryHygieneController(AppDbContext db, ICurrentUserData
|
||||
return File(bytes, ExcelWorkbookHelper.ContentType, DownloadFileName.Template("宿舍卫生成绩", ".xlsx", batch.Name));
|
||||
}
|
||||
|
||||
[HttpGet("batches/{id:guid}/export.xlsx")]
|
||||
[Authorize(Roles = Viewers)]
|
||||
public async Task<IActionResult> Export(Guid id, CancellationToken ct)
|
||||
{
|
||||
var batch = await db.DormitoryHygieneBatches.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id, ct);
|
||||
if (batch is null) return NotFound();
|
||||
var rooms = ApplyRoomScope(db.DormitoryRooms.AsNoTracking());
|
||||
var data = await (from score in db.DormitoryHygieneScores.AsNoTracking()
|
||||
join room in rooms on score.DormitoryRoomId equals room.Id
|
||||
where score.DormitoryHygieneBatchId == id
|
||||
orderby room.DormitoryBuilding!.Code, room.RoomNumber
|
||||
select new
|
||||
{
|
||||
BuildingName = room.DormitoryBuilding!.Name, room.RoomNumber, room.Floor,
|
||||
score.FloorScore, score.BeddingScore, score.BelongingsScore,
|
||||
score.FacilitiesScore, score.SafetyScore, score.TotalScore,
|
||||
score.Grade, score.Issues, score.Notes
|
||||
}).ToListAsync(ct);
|
||||
string[] headers = ["宿舍楼", "房间号", "楼层", .. ImportHeaders.Skip(2), "总分", "等级"];
|
||||
var rows = data.Select(x => (IReadOnlyList<object?>)
|
||||
[x.BuildingName, x.RoomNumber, x.Floor, x.FloorScore, x.BeddingScore, x.BelongingsScore,
|
||||
x.FacilitiesScore, x.SafetyScore, x.Issues, x.Notes, x.TotalScore, GradeName(x.Grade)]).ToList();
|
||||
var bytes = ExcelWorkbookHelper.Create("宿舍卫生成绩", headers, rows);
|
||||
return File(bytes, ExcelWorkbookHelper.ContentType, DownloadFileName.Export("宿舍卫生成绩", ".xlsx", batch.Name));
|
||||
}
|
||||
|
||||
[HttpPost("batches/{id:guid}/import")]
|
||||
[Authorize(Roles = Managers)]
|
||||
[RequestSizeLimit(10 * 1024 * 1024)]
|
||||
@@ -223,24 +253,62 @@ public sealed class DormitoryHygieneController(AppDbContext db, ICurrentUserData
|
||||
var room = await db.DormitoryOccupancies.AsNoTracking().Where(x => x.StudentId == studentId)
|
||||
.Select(x => new
|
||||
{
|
||||
DormitoryBedId = x.DormitoryBedId,
|
||||
DormitoryRoomId = x.DormitoryBed!.DormitoryRoomId,
|
||||
BuildingName = x.DormitoryBed.DormitoryRoom!.DormitoryBuilding!.Name,
|
||||
x.DormitoryBed.DormitoryRoom.RoomNumber,
|
||||
x.DormitoryBed.BedNumber,
|
||||
x.CheckInDate,
|
||||
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)
|
||||
var histories = await db.DormitoryStayHistories.AsNoTracking()
|
||||
.Include(x => x.ToBed)!.ThenInclude(x => x!.DormitoryRoom)!.ThenInclude(x => x!.DormitoryBuilding)
|
||||
.Where(x => x.StudentId == studentId)
|
||||
.OrderBy(x => x.EffectiveDate).ThenBy(x => x.OccurredAt).ToListAsync(ct);
|
||||
var stays = new List<StudentStayWindow>();
|
||||
StudentStayWindow? openStay = null;
|
||||
foreach (var history in histories)
|
||||
{
|
||||
var effectiveDate = history.EffectiveDate ?? DateOnly.FromDateTime(history.OccurredAt);
|
||||
if (openStay is not null)
|
||||
{
|
||||
openStay.EndDate = effectiveDate;
|
||||
openStay = null;
|
||||
}
|
||||
if (history.Action is DormitoryStayAction.CheckIn or DormitoryStayAction.Transfer && history.ToBed?.DormitoryRoom is not null)
|
||||
{
|
||||
openStay = new StudentStayWindow(history.ToBedId!.Value, history.ToBed.DormitoryRoomId,
|
||||
history.ToBed.DormitoryRoom.DormitoryBuilding!.Name, history.ToBed.DormitoryRoom.RoomNumber,
|
||||
history.ToBed.BedNumber, effectiveDate);
|
||||
stays.Add(openStay);
|
||||
}
|
||||
}
|
||||
if (room is not null && (openStay is null || openStay.BedId != room.DormitoryBedId))
|
||||
stays.Add(new StudentStayWindow(room.DormitoryBedId, room.DormitoryRoomId, room.BuildingName,
|
||||
room.RoomNumber, room.BedNumber, room.CheckInDate));
|
||||
if (stays.Count == 0) return Ok(new { Room = room, Scores = Array.Empty<object>() });
|
||||
var roomIds = stays.Select(x => x.RoomId).Distinct().ToArray();
|
||||
var scoreRows = await db.DormitoryHygieneScores.AsNoTracking()
|
||||
.Where(x => roomIds.Contains(x.DormitoryRoomId) && x.DormitoryHygieneBatch!.Status == DormitoryHygieneBatchStatus.Published)
|
||||
.Select(x => new
|
||||
{
|
||||
x.Id, x.DormitoryHygieneBatchId, BatchName = x.DormitoryHygieneBatch!.Name,
|
||||
x.DormitoryHygieneBatch.InspectionDate, x.DormitoryHygieneBatch.Inspector,
|
||||
x.DormitoryRoomId,
|
||||
x.FloorScore, x.BeddingScore, x.BelongingsScore, x.FacilitiesScore,
|
||||
x.SafetyScore, x.TotalScore, x.Grade, x.Issues, x.Notes
|
||||
}).ToListAsync(ct);
|
||||
var scores = scoreRows.Select(score => new { Score = score, Stay = stays.FirstOrDefault(stay => stay.RoomId == score.DormitoryRoomId &&
|
||||
score.InspectionDate >= stay.StartDate && (!stay.EndDate.HasValue || score.InspectionDate < stay.EndDate.Value)) })
|
||||
.Where(x => x.Stay is not null).OrderByDescending(x => x.Score.InspectionDate)
|
||||
.Select(x => new
|
||||
{
|
||||
x.Score.Id, x.Score.DormitoryHygieneBatchId, x.Score.BatchName, x.Score.InspectionDate, x.Score.Inspector,
|
||||
BuildingName = x.Stay!.BuildingName, x.Stay.RoomNumber, x.Stay.BedNumber,
|
||||
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
|
||||
}).ToList();
|
||||
return Ok(new { Room = room, Scores = scores });
|
||||
}
|
||||
|
||||
@@ -291,6 +359,8 @@ public sealed class DormitoryHygieneController(AppDbContext db, ICurrentUserData
|
||||
|
||||
private static DormitoryHygieneGrade GradeFor(decimal score) => score switch
|
||||
{ >= 90 => DormitoryHygieneGrade.Excellent, >= 80 => DormitoryHygieneGrade.Good, >= 60 => DormitoryHygieneGrade.Qualified, _ => DormitoryHygieneGrade.Unqualified };
|
||||
private static string GradeName(DormitoryHygieneGrade grade) => grade switch
|
||||
{ DormitoryHygieneGrade.Excellent => "优秀", DormitoryHygieneGrade.Good => "良好", DormitoryHygieneGrade.Qualified => "合格", _ => "不合格" };
|
||||
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;
|
||||
@@ -301,6 +371,18 @@ public sealed class DormitoryHygieneController(AppDbContext db, ICurrentUserData
|
||||
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) });
|
||||
|
||||
private sealed class StudentStayWindow(Guid bedId, Guid roomId, string buildingName, string roomNumber,
|
||||
string bedNumber, DateOnly startDate)
|
||||
{
|
||||
public Guid BedId { get; } = bedId;
|
||||
public Guid RoomId { get; } = roomId;
|
||||
public string BuildingName { get; } = buildingName;
|
||||
public string RoomNumber { get; } = roomNumber;
|
||||
public string BedNumber { get; } = bedNumber;
|
||||
public DateOnly StartDate { get; } = startDate;
|
||||
public DateOnly? EndDate { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record CreateDormitoryHygieneBatchRequest(string Name, DateOnly InspectionDate, string? Inspector);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
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;
|
||||
@@ -16,6 +18,8 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat
|
||||
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;
|
||||
private static readonly string[] ExcelHeaders = ["楼栋编码", "楼栋名称", "校区编码", "楼层数", "楼栋住宿性别", "楼栋状态",
|
||||
"房间号", "所在楼层", "房间住宿性别", "房间状态", "床位号", "床位状态", "入住学生学号", "入住日期", "备注"];
|
||||
|
||||
[HttpGet("overview")]
|
||||
[Authorize(Roles = Viewers)]
|
||||
@@ -91,6 +95,158 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat
|
||||
return Ok(buildings);
|
||||
}
|
||||
|
||||
[HttpGet("excel/template.xlsx")]
|
||||
[Authorize(Roles = Managers)]
|
||||
public IActionResult DownloadExcelTemplate()
|
||||
{
|
||||
var bytes = ExcelWorkbookHelper.Create("宿舍基础数据", ExcelHeaders, [],
|
||||
[
|
||||
"一行代表一个床位;同一楼栋、房间的信息请保持一致。楼栋编码、房间号和床位号共同定位床位。",
|
||||
"住宿性别填写“不限”“男生”或“女生”,状态填写“启用”或“停用”。",
|
||||
"入住学生学号和入住日期可留空;填写学号时会新增入住或将该学生调至目标床位。",
|
||||
"导入采用合并更新:文件中已有编码会更新,不存在则新增;未出现在文件中的楼栋、房间、床位和入住记录不会删除。",
|
||||
"整批数据先校验,任一行有误时均不会写入;单次最多 2000 行。"
|
||||
]);
|
||||
return File(bytes, ExcelWorkbookHelper.ContentType, DownloadFileName.Template("宿舍基础数据与入住关系", ".xlsx"));
|
||||
}
|
||||
|
||||
[HttpGet("excel/export.xlsx")]
|
||||
[Authorize(Roles = Managers)]
|
||||
public async Task<IActionResult> ExportExcel(CancellationToken ct)
|
||||
{
|
||||
var rows = await db.DormitoryBeds.AsNoTracking().OrderBy(x => x.DormitoryRoom!.DormitoryBuilding!.Code)
|
||||
.ThenBy(x => x.DormitoryRoom!.RoomNumber).ThenBy(x => x.BedNumber)
|
||||
.Select(x => new object?[]
|
||||
{
|
||||
x.DormitoryRoom!.DormitoryBuilding!.Code, x.DormitoryRoom.DormitoryBuilding.Name,
|
||||
x.DormitoryRoom.DormitoryBuilding.Campus != null ? x.DormitoryRoom.DormitoryBuilding.Campus.Code : null,
|
||||
x.DormitoryRoom.DormitoryBuilding.FloorCount, GenderPolicyName(x.DormitoryRoom.DormitoryBuilding.GenderPolicy),
|
||||
x.DormitoryRoom.DormitoryBuilding.IsEnabled ? "启用" : "停用", x.DormitoryRoom.RoomNumber,
|
||||
x.DormitoryRoom.Floor, GenderPolicyName(x.DormitoryRoom.GenderPolicy), x.DormitoryRoom.IsEnabled ? "启用" : "停用",
|
||||
x.BedNumber, x.IsEnabled ? "启用" : "停用", x.Occupancy != null ? x.Occupancy.Student!.StudentNumber : null,
|
||||
x.Occupancy != null ? x.Occupancy.CheckInDate : null, x.DormitoryRoom.Notes
|
||||
}).ToListAsync(ct);
|
||||
var bytes = ExcelWorkbookHelper.Create("宿舍基础数据", ExcelHeaders, rows);
|
||||
return File(bytes, ExcelWorkbookHelper.ContentType, DownloadFileName.Export("宿舍基础数据与入住关系", ".xlsx"));
|
||||
}
|
||||
|
||||
[HttpPost("excel/import.xlsx")]
|
||||
[Authorize(Roles = Managers)]
|
||||
[RequestSizeLimit(10 * 1024 * 1024)]
|
||||
public async Task<ActionResult> ImportExcel(IFormFile file, CancellationToken ct)
|
||||
{
|
||||
IReadOnlyList<ExcelRow> rows;
|
||||
try { rows = await ExcelWorkbookHelper.ReadAsync(file, ExcelHeaders, ct); }
|
||||
catch (InvalidDataException exception) { return ValidationProblem(exception.Message); }
|
||||
if (rows.Count == 0) return ValidationProblem("Excel 中没有可导入的数据。");
|
||||
|
||||
return await db.ExecuteInRetriableTransactionAsync<ActionResult>(async transaction =>
|
||||
{
|
||||
var errors = new List<string>();
|
||||
var campuses = await db.Campuses.AsNoTracking().ToDictionaryAsync(x => x.Code, StringComparer.OrdinalIgnoreCase, ct);
|
||||
var students = await db.Students.Include(x => x.AdministrativeClass).ToDictionaryAsync(x => x.StudentNumber, StringComparer.OrdinalIgnoreCase, ct);
|
||||
var buildings = await db.DormitoryBuildings.ToDictionaryAsync(x => x.Code, StringComparer.OrdinalIgnoreCase, ct);
|
||||
var rooms = await db.DormitoryRooms.Include(x => x.DormitoryBuilding).ToListAsync(ct);
|
||||
var beds = await db.DormitoryBeds.Include(x => x.Occupancy).ToListAsync(ct);
|
||||
var occupancies = await db.DormitoryOccupancies.ToDictionaryAsync(x => x.StudentId, ct);
|
||||
var seenBeds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var seenStudents = new HashSet<Guid>();
|
||||
var createdBuildings = 0; var createdRooms = 0; var createdBeds = 0; var assigned = 0; var updated = 0;
|
||||
|
||||
foreach (var row in rows)
|
||||
{
|
||||
var prefix = $"第 {row.RowNumber} 行:";
|
||||
var buildingCode = row["楼栋编码"].Trim().ToUpperInvariant();
|
||||
var buildingName = row["楼栋名称"].Trim();
|
||||
var roomNumber = row["房间号"].Trim();
|
||||
var bedNumber = row["床位号"].Trim();
|
||||
if (buildingCode.Length is 0 or > 30 || buildingName.Length is 0 or > 100 || roomNumber.Length is 0 or > 30 || bedNumber.Length is 0 or > 20)
|
||||
{ errors.Add(prefix + "楼栋编码、楼栋名称、房间号和床位号不能为空且不能超过长度限制。"); continue; }
|
||||
var key = $"{buildingCode}\u001f{roomNumber}\u001f{bedNumber}";
|
||||
if (!seenBeds.Add(key)) { errors.Add(prefix + "同一床位在文件中重复。"); continue; }
|
||||
if (!TryPositiveInt(row["楼层数"], 100, out var floorCount) || !TryPositiveInt(row["所在楼层"], 100, out var floor))
|
||||
{ errors.Add(prefix + "楼层数和所在楼层必须为 1 到 100 的整数。"); continue; }
|
||||
if (!TryGenderPolicy(row["楼栋住宿性别"], out var buildingGender) || !TryGenderPolicy(row["房间住宿性别"], out var roomGender))
|
||||
{ errors.Add(prefix + "住宿性别只能填写不限、男生或女生。"); continue; }
|
||||
if (!TryEnabled(row["楼栋状态"], out var buildingEnabled) || !TryEnabled(row["房间状态"], out var roomEnabled) || !TryEnabled(row["床位状态"], out var bedEnabled))
|
||||
{ errors.Add(prefix + "状态只能填写启用或停用。"); continue; }
|
||||
Guid? campusId = null;
|
||||
var campusCode = row["校区编码"];
|
||||
if (campusCode.Length > 0)
|
||||
{
|
||||
if (!campuses.TryGetValue(campusCode, out var campus)) { errors.Add(prefix + $"校区编码“{campusCode}”不存在。"); continue; }
|
||||
campusId = campus.Id;
|
||||
}
|
||||
if (!buildings.TryGetValue(buildingCode, out var building))
|
||||
{
|
||||
building = new DormitoryBuilding { Code = buildingCode, Name = buildingName, FloorCount = floorCount };
|
||||
db.Add(building); buildings[buildingCode] = building; createdBuildings++;
|
||||
}
|
||||
else updated++;
|
||||
building.Name = buildingName; building.CampusId = campusId; building.FloorCount = floorCount;
|
||||
building.GenderPolicy = buildingGender; building.IsEnabled = buildingEnabled;
|
||||
var room = rooms.FirstOrDefault(x => x.DormitoryBuildingId == building.Id && string.Equals(x.RoomNumber, roomNumber, StringComparison.OrdinalIgnoreCase));
|
||||
if (room is null)
|
||||
{
|
||||
room = new DormitoryRoom { DormitoryBuildingId = building.Id, RoomNumber = roomNumber, Floor = floor };
|
||||
db.Add(room); rooms.Add(room); createdRooms++;
|
||||
}
|
||||
room.DormitoryBuilding = building;
|
||||
room.Floor = floor; room.GenderPolicy = roomGender; room.IsEnabled = roomEnabled; room.Notes = Normalize(row["备注"]);
|
||||
var bed = beds.FirstOrDefault(x => x.DormitoryRoomId == room.Id && string.Equals(x.BedNumber, bedNumber, StringComparison.OrdinalIgnoreCase));
|
||||
if (bed is null)
|
||||
{
|
||||
bed = new DormitoryBed { DormitoryRoomId = room.Id, BedNumber = bedNumber };
|
||||
db.Add(bed); beds.Add(bed); createdBeds++;
|
||||
}
|
||||
bed.IsEnabled = bedEnabled;
|
||||
var studentNumber = row["入住学生学号"];
|
||||
if (studentNumber.Length == 0) continue;
|
||||
if (!students.TryGetValue(studentNumber, out var student)) { errors.Add(prefix + $"学号“{studentNumber}”不存在。"); continue; }
|
||||
if (!seenStudents.Add(student.Id)) { errors.Add(prefix + $"学生“{studentNumber}”在文件中重复分配。"); continue; }
|
||||
if (!bedEnabled || !roomEnabled || !buildingEnabled) { errors.Add(prefix + "不能向停用的楼栋、房间或床位分配学生。"); continue; }
|
||||
if (bed.Occupancy is not null && bed.Occupancy.StudentId != student.Id) { errors.Add(prefix + "目标床位已有其他学生入住。"); continue; }
|
||||
if (!GenderAllowed(student.Gender, room)) { errors.Add(prefix + "学生性别与楼栋或房间住宿规则不匹配。"); continue; }
|
||||
var checkInDate = DateOnly.FromDateTime(DateTime.Today);
|
||||
if (row["入住日期"].Length > 0 && !DateOnly.TryParse(row["入住日期"], out checkInDate)) { errors.Add(prefix + "入住日期格式无效,应为 yyyy-MM-dd。"); continue; }
|
||||
if (occupancies.TryGetValue(student.Id, out var occupancy))
|
||||
{
|
||||
if (occupancy.DormitoryBedId != bed.Id)
|
||||
{
|
||||
db.Add(new DormitoryStayHistory { StudentId = student.Id, FromBedId = occupancy.DormitoryBedId, ToBedId = bed.Id,
|
||||
Action = DormitoryStayAction.Transfer, EffectiveDate = checkInDate, Reason = "Excel 批量调宿", OperatedByUserId = scope.Current.UserId });
|
||||
occupancy.DormitoryBedId = bed.Id; assigned++;
|
||||
}
|
||||
occupancy.CheckInDate = checkInDate;
|
||||
}
|
||||
else
|
||||
{
|
||||
occupancy = new DormitoryOccupancy { StudentId = student.Id, DormitoryBedId = bed.Id, CheckInDate = checkInDate };
|
||||
db.Add(occupancy); occupancies[student.Id] = occupancy; bed.Occupancy = occupancy; assigned++;
|
||||
db.Add(new DormitoryStayHistory { StudentId = student.Id, ToBedId = bed.Id, Action = DormitoryStayAction.CheckIn,
|
||||
EffectiveDate = checkInDate, Reason = "Excel 批量分配", OperatedByUserId = scope.Current.UserId });
|
||||
}
|
||||
}
|
||||
var studentsById = students.Values.ToDictionary(x => x.Id);
|
||||
foreach (var roomGroup in occupancies.Values.GroupBy(x => beds.First(b => b.Id == x.DormitoryBedId).DormitoryRoomId))
|
||||
{
|
||||
var room = rooms.First(x => x.Id == roomGroup.Key);
|
||||
var residentStudents = roomGroup.Select(x => studentsById[x.StudentId]).ToList();
|
||||
if (residentStudents.Select(x => x.Gender).Distinct().Count() > 1)
|
||||
errors.Add($"{room.DormitoryBuilding!.Name} {room.RoomNumber}:导入后会出现不同性别学生混住。");
|
||||
if (residentStudents.Any(x => !GenderAllowed(x.Gender, room)))
|
||||
errors.Add($"{room.DormitoryBuilding!.Name} {room.RoomNumber}:现有或导入学生与住宿性别规则不匹配。");
|
||||
}
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
await transaction.RollbackAsync(ct);
|
||||
return BadRequest(new ValidationProblemDetails { Title = "导入校验失败", Detail = string.Join("\n", errors.Take(50)) });
|
||||
}
|
||||
await db.SaveChangesAsync(ct); await transaction.CommitAsync(ct);
|
||||
return Ok(new { CreatedBuildings = createdBuildings, CreatedRooms = createdRooms, CreatedBeds = createdBeds, Assigned = assigned, Updated = updated, Total = rows.Count });
|
||||
}, ct);
|
||||
}
|
||||
|
||||
[HttpPost("buildings")]
|
||||
[Authorize(Roles = Managers)]
|
||||
public async Task<ActionResult> CreateBuilding(DormitoryBuildingRequest request, CancellationToken ct)
|
||||
@@ -263,6 +419,7 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat
|
||||
db.Add(new DormitoryStayHistory
|
||||
{
|
||||
StudentId = item.StudentId, ToBedId = item.BedId, Action = DormitoryStayAction.CheckIn,
|
||||
EffectiveDate = request.CheckInDate,
|
||||
Reason = Normalize(request.Reason) ?? "批量宿舍分配", DormitoryAllocationBatchId = batch.Id,
|
||||
OperatedByUserId = scope.Current.UserId
|
||||
});
|
||||
@@ -290,7 +447,7 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat
|
||||
db.Add(new DormitoryStayHistory
|
||||
{
|
||||
StudentId = studentId, FromBedId = fromBedId, ToBedId = target.Id,
|
||||
Action = DormitoryStayAction.Transfer, Reason = Normalize(request.Reason),
|
||||
Action = DormitoryStayAction.Transfer, EffectiveDate = request.TransferDate, Reason = Normalize(request.Reason),
|
||||
OperatedByUserId = scope.Current.UserId
|
||||
});
|
||||
await db.SaveChangesAsync(ct);
|
||||
@@ -412,6 +569,7 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat
|
||||
{
|
||||
StudentId = application.StudentId, FromBedId = fromBedId, ToBedId = toBedId,
|
||||
Action = application.Type == DormitoryApplicationType.Transfer ? DormitoryStayAction.Transfer : DormitoryStayAction.Checkout,
|
||||
EffectiveDate = DateOnly.FromDateTime(DateTime.Today),
|
||||
Reason = application.Reason, DormitoryApplicationId = application.Id, OperatedByUserId = scope.Current.UserId
|
||||
});
|
||||
await db.SaveChangesAsync(ct);
|
||||
@@ -544,6 +702,25 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat
|
||||
return Normalize(request.Notes)?.Length > 500 ? "备注不能超过 500 个字符。" : null;
|
||||
}
|
||||
private static string? Normalize(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
private static string GenderPolicyName(DormitoryGenderPolicy value) => value switch
|
||||
{
|
||||
DormitoryGenderPolicy.Male => "男生",
|
||||
DormitoryGenderPolicy.Female => "女生",
|
||||
_ => "不限"
|
||||
};
|
||||
private static bool TryGenderPolicy(string value, out DormitoryGenderPolicy result)
|
||||
{
|
||||
result = value.Trim() switch { "" or "不限" => DormitoryGenderPolicy.Any, "男" or "男生" => DormitoryGenderPolicy.Male, "女" or "女生" => DormitoryGenderPolicy.Female, _ => (DormitoryGenderPolicy)(-1) };
|
||||
return Enum.IsDefined(result);
|
||||
}
|
||||
private static bool TryEnabled(string value, out bool result)
|
||||
{
|
||||
var normalized = value.Trim();
|
||||
result = normalized is "" or "启用" or "是" or "1" or "true" or "TRUE";
|
||||
return result || normalized is "停用" or "否" or "0" or "false" or "FALSE";
|
||||
}
|
||||
private static bool TryPositiveInt(string value, int maximum, out int result) =>
|
||||
int.TryParse(value, out result) && result >= 1 && result <= maximum;
|
||||
private ActionResult ConflictProblem(string detail) => Conflict(new ProblemDetails { Status = 409, Detail = detail });
|
||||
private ActionResult ValidationProblem(string detail) => BadRequest(new ValidationProblemDetails { Detail = detail });
|
||||
}
|
||||
|
||||
@@ -71,6 +71,7 @@ public sealed class DormitoryStayHistory : EntityBase
|
||||
public Guid? DormitoryAllocationBatchId { get; set; }
|
||||
public DormitoryAllocationBatch? DormitoryAllocationBatch { get; set; }
|
||||
public Guid OperatedByUserId { get; set; }
|
||||
public DateOnly? EffectiveDate { get; set; }
|
||||
public DateTime OccurredAt { get; set; } = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
|
||||
Loaded 3 of 13 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user