From c08d953f30e04ba01b9851f490c15c17787c8f0e Mon Sep 17 00:00:00 2001 From: biss Date: Fri, 13 Nov 2026 19:41:10 +0800 Subject: [PATCH] Localize experiment project errors --- .../Controllers/ExperimentsController.cs | 121 +++++++++++++++--- .../Localization/SharedResource.en-US.resx | 59 +++++++++ .../Localization/SharedResource.resx | 59 +++++++++ 3 files changed, 222 insertions(+), 17 deletions(-) diff --git a/src/Jiaowu.Api/Controllers/ExperimentsController.cs b/src/Jiaowu.Api/Controllers/ExperimentsController.cs index 51ef955..1cf1f6d 100644 --- a/src/Jiaowu.Api/Controllers/ExperimentsController.cs +++ b/src/Jiaowu.Api/Controllers/ExperimentsController.cs @@ -8,11 +8,13 @@ using Jiaowu.Api.Domain.System; using Jiaowu.Api.Infrastructure.Auth; using Jiaowu.Api.Infrastructure.Experiments; using Jiaowu.Api.Infrastructure.Persistence; +using Jiaowu.Api.Infrastructure.Localization; using Jiaowu.Api.Infrastructure.Teaching; using Jiaowu.Api.Infrastructure.Timetables; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Localization; namespace Jiaowu.Api.Controllers; @@ -22,8 +24,62 @@ namespace Jiaowu.Api.Controllers; public sealed class ExperimentsController( AppDbContext db, ICurrentUserDataScope currentUserDataScope, - ClassroomReservationAvailabilityService classroomAvailability) : ControllerBase + ClassroomReservationAvailabilityService classroomAvailability, + IStringLocalizer? localizer = null) : ControllerBase { + private static readonly IReadOnlyDictionary ExperimentsErrorKeys = new Dictionary + { + ["当前账号未关联有效学生档案。"] = "Experiments.StudentProfile.NotLinked", + ["教学任务不存在、未发布或不在当前管理范围内。"] = "Experiments.Task.Unavailable", + ["该教学任务下已存在相同实验项目编码。"] = "Experiments.Project.DuplicateCode", + ["请至少选择一个教学任务。"] = "Experiments.Task.Required", + ["单次最多为 100 个教学任务创建实验项目。"] = "Experiments.Task.BatchLimit", + ["部分教学任务不存在、未发布或不在当前管理范围内。"] = "Experiments.Task.BatchUnavailable", + ["批量设置仅支持同一学期、同一课程的教学任务。"] = "Experiments.Task.SameTermAndCourseRequired", + ["自行安排一次可生成 1 至 100 个实验项目。"] = "Experiments.Project.GenerationCountRange", + ["本次最多生成 1000 个自行安排实验项目,请缩小教学任务或项目数量。"] = "Experiments.Project.TotalGenerationLimit", + ["项目编码前缀过长,无法追加顺序号。"] = "Experiments.Project.CodePrefixTooLong", + ["所选教学班中包含未排入实验室的已发布实验课,请先完成课表安排。"] = "Experiments.Project.LabClassesNeedScheduling", + ["存在旧版已发布实验项目,不能自动拆分为每周项目;请先关闭后重新设置。"] = "Experiments.Project.LegacyPublishedCannotSplit", + ["所选实验课中已存在相同实验项目编码和周次,不能重复生成。"] = "Experiments.Project.DuplicateCodeAndWeek", + ["自动生成顺序号时无需填写逐行项目名称。"] = "Experiments.Project.NamesNotAllowedWithSequence", + ["项目名称前缀过长,无法追加顺序号。"] = "Experiments.Project.NamePrefixTooLong", + ["每个实验项目名称均不能为空,且不能超过 120 个字符。"] = "Experiments.Project.NameLength", + ["只有草稿实验项目可以修改。"] = "Experiments.Project.DraftOnlyForEdit", + ["创建后不能更换实验项目所属教学任务。"] = "Experiments.Project.TaskCannotChange", + ["只有草稿实验项目可以删除。"] = "Experiments.Project.DraftOnlyForDelete", + ["只有已发布实验项目可以修正教学内容。"] = "Experiments.Project.PublishedOnlyForContentEdit", + ["请填写实验项目名称。"] = "Experiments.Project.NameRequired", + ["请选择 1 至 100 个实验项目。"] = "Experiments.Project.SelectionCountRange", + ["请为每个已选实验项目填写一个名称,每行一个且数量必须一致。"] = "Experiments.Project.NamePerSelectionRequired", + ["批量修改名称只能包含草稿实验项目。"] = "Experiments.Project.BulkRenameDraftOnly", + ["批量删除只能包含草稿实验项目。"] = "Experiments.Project.BulkDeleteDraftOnly", + ["只有草稿实验项目可以发布。"] = "Experiments.Project.DraftOnlyForPublish", + ["存在不在项目开放日期范围内的实验场次。"] = "Experiments.Project.SessionOutsideOpenWindow", + ["请先设置有效的开始选课和截至选课时间。"] = "Experiments.Project.EnrollmentWindowRequired", + ["请为每个有效实验场次至少指定一位指导老师。"] = "Experiments.Session.InstructorRequired", + ["只有已发布实验项目可以关闭。"] = "Experiments.Project.PublishedOnlyForClose", + ["已关闭实验项目不能再增加场次。"] = "Experiments.Project.ClosedCannotAddSessions", + ["集中安排的实验项目直接使用已发布课表中的实验课,不能在此重复排时派地点。"] = "Experiments.Project.CentralizedUsesTimetable", + ["请至少添加一条实验排课。"] = "Experiments.Session.AtLeastOneRequired", + ["单次最多安排 100 条实验场次。"] = "Experiments.Session.BatchLimit", + ["实验项目不能为空。"] = "Experiments.Session.ProjectRequired", + ["集中安排实验无需代选场次。"] = "Experiments.Enrollment.CentralizedNoProxyBooking", + ["集中安排实验无需学生预约。"] = "Experiments.Enrollment.CentralizedNoBooking", + ["只能为已发布的自行安排实验场次代选学生。"] = "Experiments.Enrollment.PublishedSelfScheduledOnly", + ["学生不存在或不在学。"] = "Experiments.Student.Unavailable", + ["该学生不在本实验项目的教学任务名单内。"] = "Experiments.Student.NotOnRoster", + ["该学生已预约本实验项目的其他场次。"] = "Experiments.Booking.OtherSessionExists", + ["该实验场次名额已满,请选择其他时间。"] = "Experiments.Session.Full", + ["请至少选择一名学生。"] = "Experiments.Student.Required", + ["单次最多可代选 100 名学生。"] = "Experiments.Student.ProxyEnrollmentLimit", + ["存在无效的学生档案。"] = "Experiments.Student.InvalidRecords", + ["当前不在该实验项目的选课时间范围内。"] = "Experiments.Booking.OutsideEnrollmentWindow", + ["该实验场次已经结束,不能预约。"] = "Experiments.Booking.SessionEnded", + ["该实验项目已有预约,请先取消原预约。"] = "Experiments.Booking.ExistingBooking", + ["教学任务已归档,实验项目、场次和预约仅可查看,不能再操作。"] = "Experiments.Task.ArchivedReadOnly", + }; + private const string Managers = SystemRoles.SuperAdmin + "," + SystemRoles.AcademicAdmin + "," + @@ -167,7 +223,8 @@ public sealed class ExperimentsController( BuildingName = x.Building!.Name, CampusName = x.Building.Campus!.Name, x.Capacity - ,x.TeachingVenueNature + , + x.TeachingVenueNature }) .ToListAsync(cancellationToken), Teachers = await AccessibleTeachingTasks().AsNoTracking() @@ -321,12 +378,15 @@ public sealed class ExperimentsController( ClassroomName = item.Classroom!.Name, BuildingName = item.Classroom.Building!.Name, CampusName = item.Classroom.Building.Campus!.Name - ,InstructorNames = item.Instructors + , + InstructorNames = item.Instructors .OrderBy(instructor => instructor.Teacher!.TeacherNumber) .Select(instructor => instructor.Teacher!.Name) - ,InstructorTeacherIds = item.Instructors + , + InstructorTeacherIds = item.Instructors .Select(instructor => instructor.TeacherId) - ,CanManage = scope.Scope != DataScope.Self || + , + CanManage = scope.Scope != DataScope.Self || item.Instructors.Any(instructor => instructor.Teacher!.UserId == scope.UserId) }) @@ -414,7 +474,8 @@ public sealed class ExperimentsController( ClassroomName = item.Classroom!.Name, BuildingName = item.Classroom.Building!.Name, CampusName = item.Classroom.Building.Campus!.Name - ,InstructorNames = item.Instructors + , + InstructorNames = item.Instructors .OrderBy(instructor => instructor.Teacher!.TeacherNumber) .Select(instructor => instructor.Teacher!.Name) }), @@ -521,7 +582,7 @@ public sealed class ExperimentsController( : 1; if (request.ArrangementMode == ExperimentArrangementMode.SelfScheduled && names is not null && names.Count != definitionCount) - return ValidationProblem($"已填写 {names.Count} 个项目名称,请将生成项目数设为相同数量。"); + return ValidationProblem(SharedResourceText.Get(localizer, "Experiments.Project.NameCountMismatch", names.Count)); if (request.ArrangementMode == ExperimentArrangementMode.SelfScheduled && taskIds.Count * definitionCount > 1000) return ValidationProblem("本次最多生成 1000 个自行安排实验项目,请缩小教学任务或项目数量。"); @@ -667,7 +728,7 @@ public sealed class ExperimentsController( ? definitionCount : projects.Count; if (names.Count != expectedNameCount) - return ValidationProblem($"已填写 {names.Count} 个项目名称,但本次将生成 {projects.Count} 个实验项目;请确保每行对应一个项目。"); + return ValidationProblem(SharedResourceText.Get(localizer, "Experiments.Project.NameCountMismatchWithGenerated", names.Count, projects.Count)); for (var index = 0; index < projects.Count; index++) projects[index].Name = names[request.ArrangementMode == ExperimentArrangementMode.SelfScheduled ? index % definitionCount @@ -1390,14 +1451,14 @@ public sealed class ExperimentsController( return ValidationProblem("存在无效的学生档案。"); var inactive = students.FirstOrDefault(x => x.Status != StudentStatus.Active); if (inactive is not null) - return ConflictProblem($"学生 {inactive.StudentNumber} {inactive.Name} 当前不是在籍状态。"); + return ConflictProblem(SharedResourceText.Get(localizer, "Experiments.Student.Inactive", inactive.StudentNumber, inactive.Name)); var roster = await TeachingTaskRosterQuery.LoadForTasksAsync( db, [session.ExperimentProject.TeachingTaskId], cancellationToken); var eligibleStudentIds = roster.Select(x => x.StudentId).ToHashSet(); var outOfRoster = students.FirstOrDefault(x => !eligibleStudentIds.Contains(x.Id)); if (outOfRoster is not null) - return ConflictProblem($"学生 {outOfRoster.StudentNumber} {outOfRoster.Name} 不在本实验项目的教学任务名单内。"); + return ConflictProblem(SharedResourceText.Get(localizer, "Experiments.Student.OutOfRoster", outOfRoster.StudentNumber, outOfRoster.Name)); var existingBookings = await db.ExperimentBookings .Where(x => x.ExperimentProjectId == session.ExperimentProjectId) @@ -1408,23 +1469,27 @@ public sealed class ExperimentsController( if (booked is not null) { var student = students.First(x => x.Id == booked.StudentId); - return ConflictProblem(booked.ExperimentSessionId == session.Id - ? $"学生 {student.StudentNumber} {student.Name} 已预约本实验场次。" - : $"学生 {student.StudentNumber} {student.Name} 已预约本实验项目的其他场次。"); + return ConflictProblem(SharedResourceText.Get( + localizer, + booked.ExperimentSessionId == session.Id + ? "Experiments.Student.AlreadyBookedThisSession" + : "Experiments.Student.AlreadyBookedOtherSession", + student.StudentNumber, + student.Name)); } foreach (var student in students) { var scheduleProblem = await StudentConflictAsync(student.Id, session, cancellationToken); if (scheduleProblem is not null) - return ConflictProblem($"学生 {student.StudentNumber} {student.Name}:{scheduleProblem}"); + return ConflictProblem(SharedResourceText.Get(localizer, "Experiments.Student.ScheduleConflict", student.StudentNumber, student.Name, LocalizeScheduleConflict(scheduleProblem))); } var reservedCount = await db.ExperimentBookings.CountAsync(x => x.ExperimentSessionId == session.Id && x.Status == ExperimentBookingStatus.Booked, cancellationToken); if (reservedCount + students.Count > session.Capacity) - return ConflictProblem($"该实验场次仅剩 {Math.Max(0, session.Capacity - reservedCount)} 个名额,无法完成本次代选。"); + return ConflictProblem(SharedResourceText.Get(localizer, "Experiments.Session.RemainingSeats", Math.Max(0, session.Capacity - reservedCount))); foreach (var student in students) { @@ -2055,10 +2120,32 @@ public sealed class ExperimentsController( private ActionResult ConflictProblem(string detail) => Conflict(new ProblemDetails { - Title = "无法完成操作", - Detail = detail, + Title = SharedResourceText.Get(localizer, "Experiments.Errors.Title"), + Detail = LocalizeExperimentMessage(detail), Status = StatusCodes.Status409Conflict }); + + private ActionResult ValidationProblem(string detail) => + base.ValidationProblem(detail: LocalizeExperimentMessage(detail)); + + private string LocalizeExperimentMessage(string detail) => + ExperimentsErrorKeys.TryGetValue(detail, out var key) ? SharedResourceText.Get(localizer, key) : detail; + + private string LocalizeScheduleConflict(string detail) + { + if (System.Globalization.CultureInfo.CurrentUICulture.TwoLetterISOLanguageName != "en") return detail; + var match = System.Text.RegularExpressions.Regex.Match(detail, "^“(?.+)”与“(?.+)”存在(?教室|教师|行政班)冲突。$"); + if (!match.Success) return detail; + var reason = match.Groups["reason"].Value switch + { + "教室" => SharedResourceText.Get(localizer, "Schedules.Conflict.Classroom"), + "教师" => SharedResourceText.Get(localizer, "Schedules.Conflict.Teacher"), + "行政班" => SharedResourceText.Get(localizer, "Schedules.Conflict.AdministrativeClass"), + _ => match.Groups["reason"].Value + }; + return SharedResourceText.Get(localizer, "Schedules.Job.Conflict", match.Groups["first"].Value, match.Groups["second"].Value, reason); + } + } public sealed record ExperimentProjectRequest( 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 b28648d..f643d39 100644 --- a/src/Jiaowu.Api/Resources/Infrastructure/Localization/SharedResource.en-US.resx +++ b/src/Jiaowu.Api/Resources/Infrastructure/Localization/SharedResource.en-US.resx @@ -426,4 +426,63 @@ Row {0}: enter an integer from 1 to 20 in “实验次数”. Row {0}: enter a number between {2:0} and {3:0}, or leave “{1}” blank. {0} additional errors are not shown. + You entered {0} project names. Set the generated project count to match. + You entered {0} project names for {1} generated projects. Enter one name per project. + The following teaching tasks already use experiment project code {0}: {1}. + Student {0} {1} is not currently active. + Student {0} {1} is not on the roster for this experiment project. + Student {0} {1} already has a booking for this experiment session. + Student {0} {1} already has a booking for another session in this project. + Student {0} {1}: {2} + Only {0} places remain in this experiment session, so the enrollment cannot be completed. + The operation could not be completed + The current account is not linked to an active student record. + The teaching task does not exist, is unpublished or is outside your management scope. + An experiment project with this code already exists for the teaching task. + Select at least one teaching task. + Create projects for no more than 100 teaching tasks at a time. + Some teaching tasks do not exist, are unpublished or are outside your management scope. + Bulk setup requires teaching tasks from the same term and course. + Generate between 1 and 100 self-scheduled experiment projects at a time. + Generate no more than 1,000 self-scheduled projects at a time. Reduce the number of teaching tasks or projects. + The project code prefix is too long to append a sequence number. + Some selected classes include published lab courses that are not scheduled in a lab. Schedule them first. + Legacy published projects cannot be split into weekly projects. Close them and configure the projects again. + A project with the same code and week already exists for a selected lab class. + Do not enter individual project names when sequence numbers are generated automatically. + The project name prefix is too long to append a sequence number. + Each experiment project name is required and must be no longer than 120 characters. + Only draft experiment projects can be edited. + The teaching task cannot be changed after the project is created. + Only draft experiment projects can be deleted. + Teaching content can only be corrected for published experiment projects. + Enter an experiment project name. + Select between 1 and 100 experiment projects. + Enter one project name per selected project, with one name on each line. + Only draft experiment projects can be renamed in bulk. + Only draft experiment projects can be deleted in bulk. + Only draft experiment projects can be published. + Some experiment sessions are outside the project enrollment dates. + Set valid enrollment opening and closing times first. + Assign at least one instructor to each valid experiment session. + Only published experiment projects can be closed. + Sessions cannot be added to a closed experiment project. + Centrally scheduled projects use lab classes from the published timetable. Do not schedule them again here. + Add at least one experiment session. + Schedule no more than 100 experiment sessions at a time. + Select an experiment project. + Centrally scheduled experiments do not require proxy booking. + Students can only be enrolled by an administrator in published self-scheduled sessions. + The student does not exist or is not active. + The student is not on the teaching task roster for this experiment. + The student already has a booking for another session in this project. + This experiment session is full. Select another time. + Select at least one student. + Enroll no more than 100 students at a time. + The request contains invalid student records. + The experiment project is not currently open for enrollment. + This experiment session has ended and cannot be booked. + 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. diff --git a/src/Jiaowu.Api/Resources/Infrastructure/Localization/SharedResource.resx b/src/Jiaowu.Api/Resources/Infrastructure/Localization/SharedResource.resx index 868b6dc..3e10329 100644 --- a/src/Jiaowu.Api/Resources/Infrastructure/Localization/SharedResource.resx +++ b/src/Jiaowu.Api/Resources/Infrastructure/Localization/SharedResource.resx @@ -426,4 +426,63 @@ 第 {0} 行:“实验次数”请填写 1—20 的整数。 第 {0} 行:“{1}”请填写 {2:0}—{3:0} 的数值或留空。 另有 {0} 条错误未显示。 + 已填写 {0} 个项目名称,请将生成项目数设为相同数量。 + 已填写 {0} 个项目名称,但本次将生成 {1} 个实验项目;请确保每行对应一个项目。 + 以下教学任务已存在实验项目编码 {0}:{1}。 + 学生 {0} {1} 当前不是在籍状态。 + 学生 {0} {1} 不在本实验项目的教学任务名单内。 + 学生 {0} {1} 已预约本实验场次。 + 学生 {0} {1} 已预约本实验项目的其他场次。 + 学生 {0} {1}:{2} + 该实验场次仅剩 {0} 个名额,无法完成本次代选。 + 无法完成操作 + 当前账号未关联有效学生档案。 + 教学任务不存在、未发布或不在当前管理范围内。 + 该教学任务下已存在相同实验项目编码。 + 请至少选择一个教学任务。 + 单次最多为 100 个教学任务创建实验项目。 + 部分教学任务不存在、未发布或不在当前管理范围内。 + 批量设置仅支持同一学期、同一课程的教学任务。 + 自行安排一次可生成 1 至 100 个实验项目。 + 本次最多生成 1000 个自行安排实验项目,请缩小教学任务或项目数量。 + 项目编码前缀过长,无法追加顺序号。 + 所选教学班中包含未排入实验室的已发布实验课,请先完成课表安排。 + 存在旧版已发布实验项目,不能自动拆分为每周项目;请先关闭后重新设置。 + 所选实验课中已存在相同实验项目编码和周次,不能重复生成。 + 自动生成顺序号时无需填写逐行项目名称。 + 项目名称前缀过长,无法追加顺序号。 + 每个实验项目名称均不能为空,且不能超过 120 个字符。 + 只有草稿实验项目可以修改。 + 创建后不能更换实验项目所属教学任务。 + 只有草稿实验项目可以删除。 + 只有已发布实验项目可以修正教学内容。 + 请填写实验项目名称。 + 请选择 1 至 100 个实验项目。 + 请为每个已选实验项目填写一个名称,每行一个且数量必须一致。 + 批量修改名称只能包含草稿实验项目。 + 批量删除只能包含草稿实验项目。 + 只有草稿实验项目可以发布。 + 存在不在项目开放日期范围内的实验场次。 + 请先设置有效的开始选课和截至选课时间。 + 请为每个有效实验场次至少指定一位指导老师。 + 只有已发布实验项目可以关闭。 + 已关闭实验项目不能再增加场次。 + 集中安排的实验项目直接使用已发布课表中的实验课,不能在此重复排时派地点。 + 请至少添加一条实验排课。 + 单次最多安排 100 条实验场次。 + 实验项目不能为空。 + 集中安排实验无需代选场次。 + 只能为已发布的自行安排实验场次代选学生。 + 学生不存在或不在学。 + 该学生不在本实验项目的教学任务名单内。 + 该学生已预约本实验项目的其他场次。 + 该实验场次名额已满,请选择其他时间。 + 请至少选择一名学生。 + 单次最多可代选 100 名学生。 + 存在无效的学生档案。 + 当前不在该实验项目的选课时间范围内。 + 该实验场次已经结束,不能预约。 + 该实验项目已有预约,请先取消原预约。 + 教学任务已归档,实验项目、场次和预约仅可查看,不能再操作。 + 集中安排实验无需学生预约。