Localize dormitory service errors

This commit is contained in:
biss committed 2026-11-13 19:46:02 +08:00
1 parent c08d953f30
commit 0202e23fde
4 files changed
+426 -78

No files matched your search

@@ -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<SharedResource>? localizer = null) : ControllerBase
{
private static readonly IReadOnlyDictionary<string, string> DormitoryHygieneErrorKeys = new Dictionary<string, string>
{
["批次名称不能为空且不能超过 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<object?>)
@@ -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<string> errors) => BadRequest(new ValidationProblemDetails
{ Detail = string.Join(";", errors.Take(20)) + (errors.Count > 20 ? $";另有 {errors.Count - 20} 项错误" : string.Empty) });
@@ -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<SharedResource>? localizer = null) : ControllerBase
{
private static readonly IReadOnlyDictionary<string, string> DormitoryServicesErrorKeys = new Dictionary<string, string>
{
["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<AllocationPreviewResult>(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,
@@ -485,4 +485,55 @@
<data name="Experiments.Booking.ExistingBooking" xml:space="preserve"><value>You already have a booking for this project. Cancel the existing booking first.</value></data>
<data name="Experiments.Task.ArchivedReadOnly" xml:space="preserve"><value>The teaching task is archived. Projects, sessions and bookings are read-only.</value></data>
<data name="Experiments.Enrollment.CentralizedNoBooking" xml:space="preserve"><value>Centrally scheduled experiments do not require student booking.</value></data>
<data name="Excel 中没有可导入的数据。" xml:space="preserve"><value>The Excel file contains no data to import.</value></data>
<data name="楼栋编码已经存在。" xml:space="preserve"><value>A building with this code already exists.</value></data>
<data name="校区不存在。" xml:space="preserve"><value>The campus does not exist.</value></data>
<data name="宿舍楼不存在。" xml:space="preserve"><value>The dormitory building does not exist.</value></data>
<data name="该楼栋内已经存在此房间号。" xml:space="preserve"><value>This room number already exists in the building.</value></data>
<data name="床位应为 1 到 20 个不重复、长度不超过 20 的编号。" xml:space="preserve"><value>Enter between 1 and 20 unique bed numbers, each no longer than 20 characters.</value></data>
<data name="不能删除已有学生入住的床位,请先办理调宿或退宿。" xml:space="preserve"><value>An occupied bed cannot be deleted. Transfer or check out the student first.</value></data>
<data name="年级、专业或班级筛选项过多。" xml:space="preserve"><value>Too many year, major or class filters were selected.</value></data>
<data name="请选择 1 到 2000 名待分配学生。" xml:space="preserve"><value>Select between 1 and 2,000 students to assign.</value></data>
<data name="单次应提交 1 到 2000 条分配结果。" xml:space="preserve"><value>Submit between 1 and 2,000 allocation results at a time.</value></data>
<data name="同一学生或床位不能在本次分配中重复。" xml:space="preserve"><value>A student or bed cannot appear more than once in the allocation.</value></data>
<data name="存在无效的学生或床位。" xml:space="preserve"><value>The request contains an invalid student or bed.</value></data>
<data name="学生已经入住或床位已被占用,请刷新预览后重试。" xml:space="preserve"><value>A student is already housed or a bed is occupied. Refresh the preview and try again.</value></data>
<data name="同一宿舍不能同时分配不同性别的学生。" xml:space="preserve"><value>Students of different genders cannot be assigned to the same dormitory.</value></data>
<data name="分配结果包含性别不匹配的宿舍。" xml:space="preserve"><value>The allocation includes a dormitory that does not match the student gender.</value></data>
<data name="自动分配任务尚未完成或已经提交。" xml:space="preserve"><value>The automatic allocation task is unfinished or has already been submitted.</value></data>
<data name="该学生当前没有在住宿舍。" xml:space="preserve"><value>The student is not currently housed in a dormitory.</value></data>
<data name="目标床位不存在、已停用或已被占用。" xml:space="preserve"><value>The target bed does not exist, is disabled or is occupied.</value></data>
<data name="目标宿舍与学生性别不匹配。" xml:space="preserve"><value>The target dormitory does not match the student gender.</value></data>
<data name="当前账号未关联有效学生档案。" xml:space="preserve"><value>The current account is not linked to an active student record.</value></data>
<data name="当前没有在住宿舍,不能提交调宿或退宿申请。" xml:space="preserve"><value>You are not currently housed in a dormitory and cannot request a transfer or checkout.</value></data>
<data name="申请类型无效。" xml:space="preserve"><value>The application type is invalid.</value></data>
<data name="申请原因不能为空且不能超过 1000 个字符。" xml:space="preserve"><value>Enter an application reason no longer than 1,000 characters.</value></data>
<data name="你已有一条正在办理的住宿申请。" xml:space="preserve"><value>You already have a dormitory application in progress.</value></data>
<data name="申请当前状态不能进行辅导员审核。" xml:space="preserve"><value>This application is not awaiting counselor review.</value></data>
<data name="申请尚未通过辅导员审核。" xml:space="preserve"><value>The application has not passed counselor review.</value></data>
<data name="学生住宿状态已变化,请核对后处理。" xml:space="preserve"><value>The student housing status has changed. Verify it before proceeding.</value></data>
<data name="批准调宿申请时必须选择目标床位。" xml:space="preserve"><value>Select a target bed to approve a transfer application.</value></data>
<data name="目标床位不可用。" xml:space="preserve"><value>The target bed is unavailable.</value></data>
<data name="当前状态不能撤回申请。" xml:space="preserve"><value>The application cannot be withdrawn in its current state.</value></data>
<data name="导入校验失败" xml:space="preserve"><value>Import validation failed</value></data>
<data name="批次名称不能为空且不能超过 150 个字符。" xml:space="preserve"><value>Enter a batch name no longer than 150 characters.</value></data>
<data name="检查人员不能超过 100 个字符。" xml:space="preserve"><value>The inspector name cannot exceed 100 characters.</value></data>
<data name="已发布的检查批次不能删除,可修改批次信息或成绩后重新发布。" xml:space="preserve"><value>Published inspection batches cannot be deleted. Edit the batch or scores and publish again.</value></data>
<data name="单次应提交 1 到 2000 条宿舍成绩。" xml:space="preserve"><value>Submit between 1 and 2,000 dormitory scores at a time.</value></data>
<data name="Excel 中没有可导入的宿舍成绩。" xml:space="preserve"><value>The Excel file contains no dormitory scores to import.</value></data>
<data name="没有宿舍成绩,不能发布。" xml:space="preserve"><value>Scores are required before the batch can be published.</value></data>
<data name="请选择 1 到 500 个检查批次。" xml:space="preserve"><value>Select between 1 and 500 inspection batches.</value></data>
<data name="所选学期不存在。" xml:space="preserve"><value>The selected term does not exist.</value></data>
<data name="只能选择目标学期日期范围内的已发布检查批次。" xml:space="preserve"><value>Select published inspection batches within the target term date range.</value></data>
<data name="该学期已有正在排队或计算中的汇总任务,请等待任务完成。" xml:space="preserve"><value>A summary task for this term is queued or running. Wait for it to finish.</value></data>
<data name="本次提交中宿舍不能重复。" xml:space="preserve"><value>A dormitory cannot appear more than once in this submission.</value></data>
<data name="存在不存在的宿舍,请刷新宿舍档案后重试。" xml:space="preserve"><value>Some dormitories do not exist. Refresh the dormitory records and try again.</value></data>
<data name="每个卫生分项必须在 0 到 20 分之间。" xml:space="preserve"><value>Each hygiene score must be between 0 and 20.</value></data>
<data name="问题说明不能超过 1000 个字符,备注不能超过 500 个字符。" xml:space="preserve"><value>The issue description cannot exceed 1,000 characters and notes cannot exceed 500.</value></data>
<data name="DormitoryServices.Building.CodeNameLength" xml:space="preserve"><value>Building code and name are required and must be within their length limits.</value></data>
<data name="DormitoryServices.Building.FloorCountRange" xml:space="preserve"><value>The number of floors must be between 1 and 100.</value></data>
<data name="DormitoryServices.GenderPolicy.Invalid" xml:space="preserve"><value>The dormitory gender policy is invalid.</value></data>
<data name="DormitoryServices.Room.NumberLength" xml:space="preserve"><value>The room number is required and must be no longer than 30 characters.</value></data>
<data name="DormitoryServices.Room.FloorRange" xml:space="preserve"><value>The floor must be between 1 and 100.</value></data>
<data name="DormitoryServices.Room.BedCountRange" xml:space="preserve"><value>The number of beds must be between 1 and 20.</value></data>
</root>
Loaded 3 of 4 files, more files were not shown because too many files have changed in this diff. Show more