From 0202e23fde2dc8326a898d31b7f4add218de7ea9 Mon Sep 17 00:00:00 2001 From: biss Date: Fri, 13 Nov 2026 19:46:02 +0800 Subject: [PATCH] Localize dormitory service errors --- .../Controllers/DormitoryHygieneController.cs | 187 ++++++++++++--- .../DormitoryServicesController.cs | 215 ++++++++++++++---- .../Localization/SharedResource.en-US.resx | 51 +++++ .../Localization/SharedResource.resx | 51 +++++ 4 files changed, 426 insertions(+), 78 deletions(-) diff --git a/src/Jiaowu.Api/Controllers/DormitoryHygieneController.cs b/src/Jiaowu.Api/Controllers/DormitoryHygieneController.cs index a3e5ab7..dae9448 100644 --- a/src/Jiaowu.Api/Controllers/DormitoryHygieneController.cs +++ b/src/Jiaowu.Api/Controllers/DormitoryHygieneController.cs @@ -6,17 +6,39 @@ using Jiaowu.Api.Infrastructure.Auth; using Jiaowu.Api.Infrastructure.Excel; using Jiaowu.Api.Infrastructure.Files; using Jiaowu.Api.Infrastructure.Persistence; +using Jiaowu.Api.Infrastructure.Localization; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Localization; namespace Jiaowu.Api.Controllers; [ApiController] [Authorize] [Route("api/dormitory-hygiene")] -public sealed class DormitoryHygieneController(AppDbContext db, ICurrentUserDataScope scope) : ControllerBase +public sealed class DormitoryHygieneController(AppDbContext db, ICurrentUserDataScope scope, + IStringLocalizer? localizer = null) : ControllerBase { + private static readonly IReadOnlyDictionary DormitoryHygieneErrorKeys = new Dictionary + { + ["批次名称不能为空且不能超过 150 个字符。"] = "DormitoryHygiene.Batch.NameRequired", + ["检查人员不能超过 100 个字符。"] = "DormitoryHygiene.Batch.InspectorMaxLength", + ["已发布的检查批次不能删除,可修改批次信息或成绩后重新发布。"] = "DormitoryHygiene.Batch.PublishedCannotDelete", + ["单次应提交 1 到 2000 条宿舍成绩。"] = "DormitoryHygiene.Scores.CountRange", + ["Excel 中没有可导入的宿舍成绩。"] = "DormitoryHygiene.Import.NoData", + ["没有宿舍成绩,不能发布。"] = "DormitoryHygiene.Batch.NoScoresToPublish", + ["请选择 1 到 500 个检查批次。"] = "DormitoryHygiene.Summary.BatchCountRange", + ["所选学期不存在。"] = "DormitoryHygiene.Term.NotFound", + ["只能选择目标学期日期范围内的已发布检查批次。"] = "DormitoryHygiene.Summary.PublishedBatchesInTermOnly", + ["该学期已有正在排队或计算中的汇总任务,请等待任务完成。"] = "DormitoryHygiene.Summary.AlreadyRunning", + ["当前账号未关联有效学生档案。"] = "DormitoryHygiene.StudentProfile.NotLinked", + ["本次提交中宿舍不能重复。"] = "DormitoryHygiene.Scores.DuplicateRoom", + ["存在不存在的宿舍,请刷新宿舍档案后重试。"] = "DormitoryHygiene.Scores.RoomNotFound", + ["每个卫生分项必须在 0 到 20 分之间。"] = "DormitoryHygiene.Scores.Range", + ["问题说明不能超过 1000 个字符,备注不能超过 500 个字符。"] = "DormitoryHygiene.Scores.TextLength", + }; + private const string Managers = SystemRoles.SuperAdmin + "," + SystemRoles.AcademicAdmin + "," + SystemRoles.DormitoryAdmin; private const string Viewers = Managers + "," + SystemRoles.CollegeAdmin + "," + SystemRoles.Counselor; private static readonly string[] ImportHeaders = @@ -44,12 +66,18 @@ public sealed class DormitoryHygieneController(AppDbContext db, ICurrentUserData .Skip((page - 1) * pageSize).Take(pageSize) .Select(x => new { - x.Id, BuildingName = x.DormitoryBuilding!.Name, x.RoomNumber, x.Floor, + 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, + 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, + 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 @@ -78,7 +106,13 @@ public sealed class DormitoryHygieneController(AppDbContext db, ICurrentUserData .Skip((page - 1) * pageSize).Take(pageSize) .Select(x => new { - x.Id, x.Name, x.InspectionDate, x.Inspector, x.Status, x.PublicationCount, x.PublishedAt, + 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)), ViolationCount = x.Scores.Count(s => s.IsViolation && rooms.Any(r => r.Id == s.DormitoryRoomId)), AverageScore = x.Scores.Where(s => rooms.Any(r => r.Id == s.DormitoryRoomId)) @@ -150,7 +184,8 @@ public sealed class DormitoryHygieneController(AppDbContext db, ICurrentUserData 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), + 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), ViolationCount = x.Count(v => v.score.IsViolation) @@ -171,11 +206,23 @@ public sealed class DormitoryHygieneController(AppDbContext db, ICurrentUserData .Skip((page - 1) * pageSize).Take(pageSize) .Select(x => new { - x.score.Id, x.score.DormitoryRoomId, x.room.DormitoryBuildingId, - BuildingName = x.room.DormitoryBuilding!.Name, x.room.RoomNumber, x.room.Floor, + 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.IsViolation, x.score.Issues, x.score.Notes + x.score.FloorScore, + x.score.BeddingScore, + x.score.BelongingsScore, + x.score.FacilitiesScore, + x.score.SafetyScore, + x.score.TotalScore, + x.score.Grade, + x.score.IsViolation, + x.score.Issues, + x.score.Notes }).ToListAsync(ct); return Ok(new { @@ -224,10 +271,19 @@ public sealed class DormitoryHygieneController(AppDbContext db, ICurrentUserData var data = await query.OrderBy(x => x.room.DormitoryBuilding!.Code).ThenBy(x => x.room.RoomNumber) .Select(x => new { - BuildingName = x.room.DormitoryBuilding!.Name, x.room.RoomNumber, x.room.Floor, - x.score.FloorScore, x.score.BeddingScore, x.score.BelongingsScore, - x.score.FacilitiesScore, x.score.SafetyScore, x.score.TotalScore, - x.score.Grade, x.score.IsViolation, x.score.Issues, x.score.Notes + BuildingName = x.room.DormitoryBuilding!.Name, + x.room.RoomNumber, + x.room.Floor, + x.score.FloorScore, + x.score.BeddingScore, + x.score.BelongingsScore, + x.score.FacilitiesScore, + x.score.SafetyScore, + x.score.TotalScore, + x.score.Grade, + x.score.IsViolation, + x.score.Issues, + x.score.Notes }).ToListAsync(ct); string[] headers = ["宿舍楼", "房间号", "楼层", .. ImportHeaders.Skip(2), "总分", "等级"]; var rows = data.Select(x => (IReadOnlyList) @@ -303,7 +359,10 @@ public sealed class DormitoryHygieneController(AppDbContext db, ICurrentUserData .OrderBy(x => x.InspectionDate).ThenBy(x => x.Name) .Select(x => new { - x.Id, x.Name, x.InspectionDate, x.Inspector, + x.Id, + x.Name, + x.InspectionDate, + x.Inspector, ScoreCount = x.Scores.Count, AverageScore = x.Scores.Select(s => (decimal?)s.TotalScore).Average(), ViolationCount = x.Scores.Count(s => s.IsViolation) @@ -325,9 +384,17 @@ public sealed class DormitoryHygieneController(AppDbContext db, ICurrentUserData .Skip((page - 1) * pageSize).Take(pageSize) .Select(x => new { - x.Id, x.AcademicTermId, TermName = x.AcademicTerm!.Name, x.Status, - x.SelectedBatchCount, x.StudentCount, x.StudentWithoutScoreCount, - x.StartedAt, x.CompletedAt, x.ErrorMessage, x.CreatedAt, + x.Id, + x.AcademicTermId, + TermName = x.AcademicTerm!.Name, + x.Status, + x.SelectedBatchCount, + x.StudentCount, + x.StudentWithoutScoreCount, + x.StartedAt, + x.CompletedAt, + x.ErrorMessage, + x.CreatedAt, CreatedBy = x.CreatedByUser!.DisplayName, BatchNames = x.SelectedBatches.OrderBy(b => b.DormitoryHygieneBatch!.InspectionDate) .Select(b => b.DormitoryHygieneBatch!.Name).ToList() @@ -344,12 +411,21 @@ public sealed class DormitoryHygieneController(AppDbContext db, ICurrentUserData .Where(x => x.Id == id) .Select(x => new { - x.Id, x.AcademicTermId, TermName = x.AcademicTerm!.Name, x.Status, - x.SelectedBatchCount, x.StudentCount, x.StudentWithoutScoreCount, - x.StartedAt, x.CompletedAt, x.ErrorMessage, x.CreatedAt, + x.Id, + x.AcademicTermId, + TermName = x.AcademicTerm!.Name, + x.Status, + x.SelectedBatchCount, + x.StudentCount, + x.StudentWithoutScoreCount, + x.StartedAt, + x.CompletedAt, + x.ErrorMessage, + x.CreatedAt, Batches = x.SelectedBatches.OrderBy(b => b.DormitoryHygieneBatch!.InspectionDate).Select(b => new { - b.DormitoryHygieneBatchId, b.DormitoryHygieneBatch!.Name, + b.DormitoryHygieneBatchId, + b.DormitoryHygieneBatch!.Name, b.DormitoryHygieneBatch.InspectionDate }).ToList() }).FirstOrDefaultAsync(ct); @@ -368,11 +444,16 @@ public sealed class DormitoryHygieneController(AppDbContext db, ICurrentUserData .Skip((page - 1) * pageSize).Take(pageSize) .Select(x => new { - x.StudentId, x.Student!.StudentNumber, x.Student.Name, + x.StudentId, + x.Student!.StudentNumber, + x.Student.Name, ClassName = x.Student.AdministrativeClass!.Name, MajorName = x.Student.AdministrativeClass.Major!.Name, - x.AverageScore, x.ExpectedBatchCount, x.IncludedScoreCount, - x.MissingScoreCount, x.ViolationCount + x.AverageScore, + x.ExpectedBatchCount, + x.IncludedScoreCount, + x.MissingScoreCount, + x.ViolationCount }).ToListAsync(ct); return Ok(new { Calculation = calculation, Results = new { Items = items, Page = page, PageSize = pageSize, Total = total } }); } @@ -464,21 +545,50 @@ public sealed class DormitoryHygieneController(AppDbContext db, ICurrentUserData .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.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.IsViolation, x.Issues, x.Notes + x.FloorScore, + x.BeddingScore, + x.BelongingsScore, + x.FacilitiesScore, + x.SafetyScore, + x.TotalScore, + x.Grade, + x.IsViolation, + 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)) }) + 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.IsViolation, x.Score.Issues, x.Score.Notes + 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.IsViolation, + x.Score.Issues, + x.Score.Notes }).ToList(); return Ok(new { Room = room, Scores = scores }); } @@ -547,8 +657,11 @@ public sealed class DormitoryHygieneController(AppDbContext db, ICurrentUserData return false; } 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 string LocalizeDormitoryHygieneMessage(string detail) => + DormitoryHygieneErrorKeys.TryGetValue(detail, out var key) ? SharedResourceText.Get(localizer, key) : detail; + + private ActionResult ConflictProblem(string detail) => Conflict(new ProblemDetails { Status = 409, Detail = LocalizeDormitoryHygieneMessage(detail) }); + private ActionResult ValidationProblem(string detail) => BadRequest(new ValidationProblemDetails { Detail = LocalizeDormitoryHygieneMessage(detail) }); private ActionResult ImportValidationProblem(IReadOnlyList errors) => BadRequest(new ValidationProblemDetails { Detail = string.Join(";", errors.Take(20)) + (errors.Count > 20 ? $";另有 {errors.Count - 20} 项错误" : string.Empty) }); diff --git a/src/Jiaowu.Api/Controllers/DormitoryServicesController.cs b/src/Jiaowu.Api/Controllers/DormitoryServicesController.cs index 932b951..a3e1750 100644 --- a/src/Jiaowu.Api/Controllers/DormitoryServicesController.cs +++ b/src/Jiaowu.Api/Controllers/DormitoryServicesController.cs @@ -7,17 +7,62 @@ using Jiaowu.Api.Infrastructure.Auth; using Jiaowu.Api.Infrastructure.Excel; using Jiaowu.Api.Infrastructure.Files; using Jiaowu.Api.Infrastructure.Persistence; +using Jiaowu.Api.Infrastructure.Localization; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Localization; namespace Jiaowu.Api.Controllers; [ApiController] [Authorize] [Route("api/dormitory-services")] -public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDataScope scope) : ControllerBase +public sealed class DormitoryServicesController( + AppDbContext db, + ICurrentUserDataScope scope, + IStringLocalizer? localizer = null) : ControllerBase { + private static readonly IReadOnlyDictionary DormitoryServicesErrorKeys = new Dictionary + { + ["Excel 中没有可导入的数据。"] = "DormitoryServices.Import.NoData", + ["楼栋编码已经存在。"] = "DormitoryServices.Building.CodeExists", + ["校区不存在。"] = "DormitoryServices.Campus.NotFound", + ["宿舍楼不存在。"] = "DormitoryServices.Building.NotFound", + ["该楼栋内已经存在此房间号。"] = "DormitoryServices.Room.NumberExists", + ["床位应为 1 到 20 个不重复、长度不超过 20 的编号。"] = "DormitoryServices.Bed.NumberCountRange", + ["不能删除已有学生入住的床位,请先办理调宿或退宿。"] = "DormitoryServices.Bed.OccupiedCannotDelete", + ["年级、专业或班级筛选项过多。"] = "DormitoryServices.Filters.TooMany", + ["请选择 1 到 2000 名待分配学生。"] = "DormitoryServices.Allocation.StudentCountRange", + ["单次应提交 1 到 2000 条分配结果。"] = "DormitoryServices.Allocation.ResultCountRange", + ["同一学生或床位不能在本次分配中重复。"] = "DormitoryServices.Allocation.DuplicateStudentOrBed", + ["存在无效的学生或床位。"] = "DormitoryServices.Allocation.InvalidStudentOrBed", + ["学生已经入住或床位已被占用,请刷新预览后重试。"] = "DormitoryServices.Allocation.OccupancyChanged", + ["同一宿舍不能同时分配不同性别的学生。"] = "DormitoryServices.Allocation.MixedGenderRoom", + ["分配结果包含性别不匹配的宿舍。"] = "DormitoryServices.Allocation.GenderMismatch", + ["自动分配任务尚未完成或已经提交。"] = "DormitoryServices.Allocation.JobNotReady", + ["该学生当前没有在住宿舍。"] = "DormitoryServices.Occupancy.NotHoused", + ["目标床位不存在、已停用或已被占用。"] = "DormitoryServices.Bed.Unavailable", + ["目标宿舍与学生性别不匹配。"] = "DormitoryServices.Room.GenderMismatch", + ["当前账号未关联有效学生档案。"] = "DormitoryServices.StudentProfile.NotLinked", + ["当前没有在住宿舍,不能提交调宿或退宿申请。"] = "DormitoryServices.Application.NoCurrentOccupancy", + ["申请类型无效。"] = "DormitoryServices.Application.TypeInvalid", + ["申请原因不能为空且不能超过 1000 个字符。"] = "DormitoryServices.Application.ReasonRequired", + ["你已有一条正在办理的住宿申请。"] = "DormitoryServices.Application.AlreadyPending", + ["申请当前状态不能进行辅导员审核。"] = "DormitoryServices.Application.NotAtCounselorReview", + ["申请尚未通过辅导员审核。"] = "DormitoryServices.Application.CounselorApprovalRequired", + ["学生住宿状态已变化,请核对后处理。"] = "DormitoryServices.Application.OccupancyChanged", + ["批准调宿申请时必须选择目标床位。"] = "DormitoryServices.Application.TargetBedRequired", + ["目标床位不可用。"] = "DormitoryServices.Application.TargetBedUnavailable", + ["当前状态不能撤回申请。"] = "DormitoryServices.Application.CannotWithdraw", + ["楼栋编码和名称不能为空且不能超过长度限制。"] = "DormitoryServices.Building.CodeNameLength", + ["楼层数必须在 1 到 100 之间。"] = "DormitoryServices.Building.FloorCountRange", + ["住宿性别规则无效。"] = "DormitoryServices.GenderPolicy.Invalid", + ["房间号不能为空且不能超过 30 个字符。"] = "DormitoryServices.Room.NumberLength", + ["楼层必须在 1 到 100 之间。"] = "DormitoryServices.Room.FloorRange", + ["床位数必须在 1 到 20 之间。"] = "DormitoryServices.Room.BedCountRange", + }; + private const int ProviderSafeIdBatchSize = 250; private const string Managers = SystemRoles.SuperAdmin + "," + SystemRoles.AcademicAdmin + "," + SystemRoles.DormitoryAdmin; private const string Viewers = Managers + "," + SystemRoles.CollegeAdmin + "," + SystemRoles.Counselor; @@ -35,7 +80,9 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat .OrderBy(building => building.Code) .Select(building => new { - building.Id, building.Code, building.Name, + 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), @@ -56,7 +103,9 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat { BuildingCount = buildingStats.Count, RoomCount = buildingStats.Sum(x => x.RoomCount), - BedCount = beds, OccupiedCount = occupied, VacantCount = beds - occupied, + 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, @@ -75,21 +124,37 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat .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, + 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, + 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, + 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, + 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 } @@ -258,8 +323,16 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat { 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 }); + 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; @@ -268,8 +341,15 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat { 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 }); + 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); @@ -285,7 +365,7 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat if (errors.Count > 0) { await transaction.RollbackAsync(ct); - return BadRequest(new ValidationProblemDetails { Title = "导入校验失败", Detail = string.Join("\n", errors.Take(50)) }); + return BadRequest(new ValidationProblemDetails { Title = SharedResourceText.Get(localizer, "DormitoryServices.Import.ValidationFailed"), 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 }); @@ -303,9 +383,13 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat 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) + 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); @@ -342,8 +426,12 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat return ConflictProblem("该楼栋内已经存在此房间号。"); var room = new DormitoryRoom { - DormitoryBuildingId = request.BuildingId, RoomNumber = roomNumber, Floor = request.Floor, - GenderPolicy = request.GenderPolicy, IsEnabled = request.IsEnabled, Notes = Normalize(request.Notes) + 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); @@ -413,10 +501,16 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat .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, + 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, + CollegeId = x.AdministrativeClass.Major.CollegeId, + CollegeName = x.AdministrativeClass.Major.College!.Name, Grade = x.AdministrativeClass.Grade }).ToListAsync(ct); return Ok(new { Items = items, Total = total, Page = page, PageSize = pageSize }); @@ -491,8 +585,12 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat result = JsonSerializer.Deserialize(batch.ResultPayload); return Ok(new { - JobId = batch.Id, batch.Status, batch.RequestedCount, batch.ErrorMessage, - Assignments = result?.Assignments ?? [], Unassigned = result?.Unassigned ?? [] + JobId = batch.Id, + batch.Status, + batch.RequestedCount, + batch.ErrorMessage, + Assignments = result?.Assignments ?? [], + Unassigned = result?.Unassigned ?? [] }); } @@ -581,10 +679,13 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat { batch = new DormitoryAllocationBatch { - Name = Normalize(request.Name) ?? $"宿舍分配 {DateTime.Now:yyyy-MM-dd HH:mm}", Mode = request.Mode, + 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 + RequestedCount = request.Assignments.Count, + AssignedCount = request.Assignments.Count, + CreatedByUserId = scope.Current.UserId, + CompletedAt = DateTime.UtcNow }; db.Add(batch); } @@ -593,9 +694,12 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat 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, + StudentId = item.StudentId, + ToBedId = item.BedId, + Action = DormitoryStayAction.CheckIn, EffectiveDate = request.CheckInDate, - Reason = Normalize(request.Reason) ?? "批量宿舍分配", DormitoryAllocationBatchId = batch.Id, + Reason = Normalize(request.Reason) ?? "批量宿舍分配", + DormitoryAllocationBatchId = batch.Id, OperatedByUserId = scope.Current.UserId }); } @@ -621,8 +725,12 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat occupancy.CheckInDate = request.TransferDate; db.Add(new DormitoryStayHistory { - StudentId = studentId, FromBedId = fromBedId, ToBedId = target.Id, - Action = DormitoryStayAction.Transfer, EffectiveDate = request.TransferDate, Reason = Normalize(request.Reason), + StudentId = studentId, + FromBedId = fromBedId, + ToBedId = target.Id, + Action = DormitoryStayAction.Transfer, + EffectiveDate = request.TransferDate, + Reason = Normalize(request.Reason), OperatedByUserId = scope.Current.UserId }); await db.SaveChangesAsync(ct); @@ -667,14 +775,24 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat var ordered = source.OrderByDescending(x => x.SubmittedAt).ThenByDescending(x => x.Id); var projection = ordered.Select(x => new { - x.Id, x.Type, x.Status, x.Reason, x.SubmittedAt, x.StudentId, - x.Student!.StudentNumber, StudentName = x.Student.Name, + 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 + x.CounselorComment, + x.CounselorReviewedAt, + x.FinalComment, + x.FinalReviewedAt, + x.TargetBedId }); if (!page.HasValue && !pageSize.HasValue) return Ok(await projection.ToListAsync(ct)); var normalizedPage = Math.Max(1, page ?? 1); @@ -695,10 +813,16 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat 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, + 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 + x.CounselorComment, + x.FinalComment, + x.FinalReviewedAt }).ToListAsync(ct); return Ok(items); } @@ -719,7 +843,9 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat return ConflictProblem("你已有一条正在办理的住宿申请。"); var application = new DormitoryApplication { - StudentId = studentId.Value, Type = request.Type, CurrentBedId = occupancy.DormitoryBedId, + 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 @@ -777,10 +903,14 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat application.Status = DormitoryApplicationStatus.Approved; db.Add(new DormitoryStayHistory { - StudentId = application.StudentId, FromBedId = fromBedId, ToBedId = toBedId, + 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 + Reason = application.Reason, + DormitoryApplicationId = application.Id, + OperatedByUserId = scope.Current.UserId }); await db.SaveChangesAsync(ct); return NoContent(); @@ -1018,8 +1148,11 @@ public sealed class DormitoryServicesController(AppDbContext db, ICurrentUserDat } 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 }); + private string LocalizeDormitoryServicesMessage(string detail) => + DormitoryServicesErrorKeys.TryGetValue(detail, out var key) ? SharedResourceText.Get(localizer, key) : detail; + + private ActionResult ConflictProblem(string detail) => Conflict(new ProblemDetails { Status = 409, Detail = LocalizeDormitoryServicesMessage(detail) }); + private ActionResult ValidationProblem(string detail) => BadRequest(new ValidationProblemDetails { Detail = LocalizeDormitoryServicesMessage(detail) }); } public sealed record DormitoryBuildingRequest(string Code, string Name, Guid? CampusId, int FloorCount, diff --git a/src/Jiaowu.Api/Resources/Infrastructure/Localization/SharedResource.en-US.resx b/src/Jiaowu.Api/Resources/Infrastructure/Localization/SharedResource.en-US.resx index f643d39..f0c82d2 100644 --- a/src/Jiaowu.Api/Resources/Infrastructure/Localization/SharedResource.en-US.resx +++ b/src/Jiaowu.Api/Resources/Infrastructure/Localization/SharedResource.en-US.resx @@ -485,4 +485,55 @@ You already have a booking for this project. Cancel the existing booking first. The teaching task is archived. Projects, sessions and bookings are read-only. Centrally scheduled experiments do not require student booking. + The Excel file contains no data to import. + A building with this code already exists. + The campus does not exist. + The dormitory building does not exist. + This room number already exists in the building. + Enter between 1 and 20 unique bed numbers, each no longer than 20 characters. + An occupied bed cannot be deleted. Transfer or check out the student first. + Too many year, major or class filters were selected. + Select between 1 and 2,000 students to assign. + Submit between 1 and 2,000 allocation results at a time. + A student or bed cannot appear more than once in the allocation. + The request contains an invalid student or bed. + A student is already housed or a bed is occupied. Refresh the preview and try again. + Students of different genders cannot be assigned to the same dormitory. + The allocation includes a dormitory that does not match the student gender. + The automatic allocation task is unfinished or has already been submitted. + The student is not currently housed in a dormitory. + The target bed does not exist, is disabled or is occupied. + The target dormitory does not match the student gender. + The current account is not linked to an active student record. + You are not currently housed in a dormitory and cannot request a transfer or checkout. + The application type is invalid. + Enter an application reason no longer than 1,000 characters. + You already have a dormitory application in progress. + This application is not awaiting counselor review. + The application has not passed counselor review. + The student housing status has changed. Verify it before proceeding. + Select a target bed to approve a transfer application. + The target bed is unavailable. + The application cannot be withdrawn in its current state. + Import validation failed + Enter a batch name no longer than 150 characters. + The inspector name cannot exceed 100 characters. + Published inspection batches cannot be deleted. Edit the batch or scores and publish again. + Submit between 1 and 2,000 dormitory scores at a time. + The Excel file contains no dormitory scores to import. + Scores are required before the batch can be published. + Select between 1 and 500 inspection batches. + The selected term does not exist. + Select published inspection batches within the target term date range. + A summary task for this term is queued or running. Wait for it to finish. + A dormitory cannot appear more than once in this submission. + Some dormitories do not exist. Refresh the dormitory records and try again. + Each hygiene score must be between 0 and 20. + The issue description cannot exceed 1,000 characters and notes cannot exceed 500. + Building code and name are required and must be within their length limits. + The number of floors must be between 1 and 100. + The dormitory gender policy is invalid. + The room number is required and must be no longer than 30 characters. + The floor must be between 1 and 100. + The number of beds must be between 1 and 20. diff --git a/src/Jiaowu.Api/Resources/Infrastructure/Localization/SharedResource.resx b/src/Jiaowu.Api/Resources/Infrastructure/Localization/SharedResource.resx index 3e10329..4251f37 100644 --- a/src/Jiaowu.Api/Resources/Infrastructure/Localization/SharedResource.resx +++ b/src/Jiaowu.Api/Resources/Infrastructure/Localization/SharedResource.resx @@ -485,4 +485,55 @@ 该实验项目已有预约,请先取消原预约。 教学任务已归档,实验项目、场次和预约仅可查看,不能再操作。 集中安排实验无需学生预约。 + DormitoryServices.Import.NoData + DormitoryServices.Building.CodeExists + DormitoryServices.Campus.NotFound + DormitoryServices.Building.NotFound + DormitoryServices.Room.NumberExists + DormitoryServices.Bed.NumberCountRange + DormitoryServices.Bed.OccupiedCannotDelete + DormitoryServices.Filters.TooMany + DormitoryServices.Allocation.StudentCountRange + DormitoryServices.Allocation.ResultCountRange + DormitoryServices.Allocation.DuplicateStudentOrBed + DormitoryServices.Allocation.InvalidStudentOrBed + DormitoryServices.Allocation.OccupancyChanged + DormitoryServices.Allocation.MixedGenderRoom + DormitoryServices.Allocation.GenderMismatch + DormitoryServices.Allocation.JobNotReady + DormitoryServices.Occupancy.NotHoused + DormitoryServices.Bed.Unavailable + DormitoryServices.Room.GenderMismatch + DormitoryServices.StudentProfile.NotLinked + DormitoryServices.Application.NoCurrentOccupancy + DormitoryServices.Application.TypeInvalid + DormitoryServices.Application.ReasonRequired + DormitoryServices.Application.AlreadyPending + DormitoryServices.Application.NotAtCounselorReview + DormitoryServices.Application.CounselorApprovalRequired + DormitoryServices.Application.OccupancyChanged + DormitoryServices.Application.TargetBedRequired + DormitoryServices.Application.TargetBedUnavailable + DormitoryServices.Application.CannotWithdraw + DormitoryServices.Import.ValidationFailed + DormitoryHygiene.Batch.NameRequired + DormitoryHygiene.Batch.InspectorMaxLength + DormitoryHygiene.Batch.PublishedCannotDelete + DormitoryHygiene.Scores.CountRange + DormitoryHygiene.Import.NoData + DormitoryHygiene.Batch.NoScoresToPublish + DormitoryHygiene.Summary.BatchCountRange + DormitoryHygiene.Term.NotFound + DormitoryHygiene.Summary.PublishedBatchesInTermOnly + DormitoryHygiene.Summary.AlreadyRunning + DormitoryHygiene.Scores.DuplicateRoom + DormitoryHygiene.Scores.RoomNotFound + DormitoryHygiene.Scores.Range + DormitoryHygiene.Scores.TextLength + DormitoryServices.Building.CodeNameLength + DormitoryServices.Building.FloorCountRange + DormitoryServices.GenderPolicy.Invalid + DormitoryServices.Room.NumberLength + DormitoryServices.Room.FloorRange + DormitoryServices.Room.BedCountRange