Localize attendance and experiment grade errors

This commit is contained in:
biss committed 2026-11-13 19:37:23 +08:00
1 parent 4ddc050aa2
commit 1042b630f0
4 files changed
+216 -17

No files matched your search

@@ -10,10 +10,12 @@ 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 Jiaowu.Api.Infrastructure.Teaching;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
namespace Jiaowu.Api.Controllers;
@@ -22,8 +24,35 @@ namespace Jiaowu.Api.Controllers;
[Route("api/attendance")]
public sealed class AttendanceController(
AppDbContext db,
ICurrentUserDataScope currentUserDataScope) : ControllerBase
ICurrentUserDataScope currentUserDataScope,
IStringLocalizer<SharedResource>? localizer = null) : ControllerBase
{
private static readonly IReadOnlyDictionary<string, string> AttendanceErrorKeys = new Dictionary<string, string>
{
["教学任务已归档,不能新建考勤表。"] = "Attendance.Task.ArchivedCannotCreate",
["该教学班没有有效学生。"] = "Attendance.Class.NoActiveStudents",
["不支持该签到方式。"] = "Attendance.CheckIn.MethodUnsupported",
["签到时长应为 1 至 180 分钟。"] = "Attendance.CheckIn.DurationRange",
["请获取有效的签到位置。"] = "Attendance.CheckIn.LocationRequired",
["定位签到范围应为 20 至 1000 米。"] = "Attendance.CheckIn.RadiusRange",
["考勤表已提交,不能修改。"] = "Attendance.Sheet.SubmittedCannotEdit",
["考勤表已提交,不能导入。"] = "Attendance.Sheet.SubmittedCannotImport",
["考勤表已提交。"] = "Attendance.Sheet.AlreadySubmitted",
["考勤表已提交,签到活动已经结束。"] = "Attendance.Sheet.SubmittedCheckInEnded",
["普通点名没有在线签到活动。"] = "Attendance.Sheet.NoOnlineCheckIn",
["该考勤表不是扫码签到。"] = "Attendance.Sheet.NotQrCheckIn",
["签到尚未开始或已经结束。"] = "Attendance.CheckIn.NotOpen",
["当前账号未关联学生档案。"] = "Attendance.StudentProfile.NotLinked",
["缺少签到活动信息。"] = "Attendance.CheckIn.ActivityMissing",
["教学任务已归档,签到活动已停止。"] = "Attendance.Task.ArchivedCheckInStopped",
["教学任务已归档,不能提交考勤申诉。"] = "Attendance.Appeal.TaskArchived",
["已有申诉正在处理中。"] = "Attendance.Appeal.AlreadyPending",
["该考勤记录申诉已通过。"] = "Attendance.Appeal.AlreadyApproved",
["当前账号未关联任何班级。"] = "Attendance.Counselor.NoClassesLinked",
["您不是该班级的辅导员。"] = "Attendance.Counselor.NotAssignedToClass",
["该申诉不在待处理状态。"] = "Attendance.Appeal.NotPending",
};
private const string AttendanceRoles =
SystemRoles.SuperAdmin + "," +
SystemRoles.AcademicAdmin + "," +
@@ -1750,10 +1779,13 @@ public sealed class AttendanceController(
private ActionResult ConflictProblem(string detail) =>
Conflict(new ProblemDetails
{
Title = "无法完成考勤操作",
Detail = detail,
Title = SharedResourceText.Get(localizer, "Attendance.Errors.Title"),
Detail = LocalizeAttendanceMessage(detail),
Status = StatusCodes.Status409Conflict
});
private string LocalizeAttendanceMessage(string detail) =>
AttendanceErrorKeys.TryGetValue(detail, out var key) ? SharedResourceText.Get(localizer, key) : detail;
}
public sealed record AttendanceSheetRequest(
@@ -8,10 +8,12 @@ using Jiaowu.Api.Infrastructure.Excel;
using Jiaowu.Api.Infrastructure.Files;
using Jiaowu.Api.Infrastructure.Grades;
using Jiaowu.Api.Infrastructure.Persistence;
using Jiaowu.Api.Infrastructure.Localization;
using Jiaowu.Api.Infrastructure.Teaching;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
namespace Jiaowu.Api.Controllers;
@@ -20,8 +22,34 @@ namespace Jiaowu.Api.Controllers;
[Route("api/experiment-grades")]
public sealed class ExperimentGradesController(
AppDbContext db,
ICurrentUserDataScope currentUserDataScope) : ControllerBase
ICurrentUserDataScope currentUserDataScope,
IStringLocalizer<SharedResource>? localizer = null) : ControllerBase
{
private static readonly IReadOnlyDictionary<string, string> ExperimentGradesErrorKeys = new Dictionary<string, string>
{
["当前账号未关联有效学生档案。"] = "ExperimentGrades.StudentProfile.NotLinked",
["只有已发布或已关闭实验项目可以建立成绩单。"] = "ExperimentGrades.Sheet.ProjectMustBePublishedOrClosed",
["该实验项目已经建立成绩单。"] = "ExperimentGrades.Sheet.AlreadyExists",
["实验项目当前没有可评分学生。"] = "ExperimentGrades.Sheet.NoStudentsToGrade",
["当前状态不能修改实验评分方案。"] = "ExperimentGrades.Settings.CannotEditCurrentState",
["成绩单提交后不能继续修改。"] = "ExperimentGrades.Sheet.SubmittedCannotEdit",
["包含无效或重复的实验成绩记录。"] = "ExperimentGrades.Records.InvalidOrDuplicate",
["实验尝试次数应在 1—20 次之间。"] = "ExperimentGrades.Records.AttemptCountRange",
["包含无效、重复或超出 0—100 分的评分项。"] = "ExperimentGrades.Items.InvalidDuplicateOrOutOfRange",
["只有录入中或已退回实验成绩单可以导入成绩。"] = "ExperimentGrades.Import.DraftOrReturnedOnly",
["Excel 中没有可导入的实验成绩数据。"] = "ExperimentGrades.Import.NoData",
["成绩单提交后不能同步参与学生。"] = "ExperimentGrades.Participants.SubmittedCannotSync",
["只有草稿或已退回实验成绩单可以提交。"] = "ExperimentGrades.Sheet.DraftOrReturnedOnly",
["实验成绩单没有学生记录。"] = "ExperimentGrades.Sheet.NoStudentRecords",
["仍有学生未登记实验参与状态。"] = "ExperimentGrades.Participants.StatusRequired",
["仍有已完成或补做学生缺少必填评分项。"] = "ExperimentGrades.Items.RequiredMissing",
["只有待审核实验成绩单可以通过审核。"] = "ExperimentGrades.Review.PendingOnlyApprove",
["只有待审核实验成绩单可以退回。"] = "ExperimentGrades.Review.PendingOnlyReturn",
["退回时必须填写修改意见。"] = "ExperimentGrades.Review.CommentRequired",
["只有审核通过的实验成绩单可以发布。"] = "ExperimentGrades.Publish.ApprovedOnly",
["教学任务已归档,实验成绩仅可查看或导出,不能再操作。"] = "ExperimentGrades.Task.ArchivedReadOnly",
};
private const string Managers =
SystemRoles.SuperAdmin + "," +
SystemRoles.AcademicAdmin + "," +
@@ -1398,15 +1426,15 @@ public sealed class ExperimentGradesController(
private static string ParticipationLabel(
ExperimentParticipationStatus status) => status switch
{
ExperimentParticipationStatus.Pending => "待登记",
ExperimentParticipationStatus.Completed => "已完成",
ExperimentParticipationStatus.Absent => "缺席",
ExperimentParticipationStatus.Excused => "请假",
ExperimentParticipationStatus.Makeup => "补做",
ExperimentParticipationStatus.Exempt => "免做",
_ => "待登记"
};
{
ExperimentParticipationStatus.Pending => "待登记",
ExperimentParticipationStatus.Completed => "已完成",
ExperimentParticipationStatus.Absent => "缺席",
ExperimentParticipationStatus.Excused => "请假",
ExperimentParticipationStatus.Makeup => "补做",
ExperimentParticipationStatus.Exempt => "免做",
_ => "待登记"
};
private static string SheetStatusLabel(ExperimentGradeSheetStatus status) =>
status switch
@@ -1467,9 +1495,9 @@ public sealed class ExperimentGradesController(
private ActionResult ImportValidationProblem(IReadOnlyList<string> errors)
{
foreach (var error in errors.Take(50)) ModelState.AddModelError("file", error);
foreach (var error in errors.Take(50)) ModelState.AddModelError("file", LocalizeExperimentGradeImportError(error));
if (errors.Count > 50)
ModelState.AddModelError("file", $"另有 {errors.Count - 50} 条错误未显示。");
ModelState.AddModelError("file", SharedResourceText.Get(localizer, "ExperimentGrades.Import.MoreErrors", errors.Count - 50));
return ValidationProblem(ModelState);
}
@@ -1488,14 +1516,49 @@ public sealed class ExperimentGradesController(
private static string? Normalize(string? value) =>
string.IsNullOrWhiteSpace(value) ? null : value.Trim();
private string LocalizeExperimentGradeImportError(string error)
{
if (System.Globalization.CultureInfo.CurrentUICulture.TwoLetterISOLanguageName != "en")
return error;
var rowMatch = System.Text.RegularExpressions.Regex.Match(error, "^第 (?<row>\\d+) 行:(?<detail>.*)$");
if (!rowMatch.Success) return error;
var row = int.Parse(rowMatch.Groups["row"].Value, System.Globalization.CultureInfo.InvariantCulture);
var detail = rowMatch.Groups["detail"].Value;
if (detail == "学号不能为空。")
return SharedResourceText.Get(localizer, "ExperimentGrades.Import.Row.StudentNumberRequired", row);
var studentMatch = System.Text.RegularExpressions.Regex.Match(detail, "^学号“(?<number>.+)”不在本实验成绩单中。$");
if (studentMatch.Success)
return SharedResourceText.Get(localizer, "ExperimentGrades.Import.Row.StudentNotInSheet", row, studentMatch.Groups["number"].Value);
if (detail == "“参与状态”请填写待登记、已完成、缺席、请假、补做或免做。")
return SharedResourceText.Get(localizer, "ExperimentGrades.Import.Row.ParticipationStatusInvalid", row);
if (detail == "“安全违规”请填写是或否。")
return SharedResourceText.Get(localizer, "ExperimentGrades.Import.Row.SafetyViolationInvalid", row);
if (detail == "“实验次数”请填写 1—20 的整数。")
return SharedResourceText.Get(localizer, "ExperimentGrades.Import.Row.AttemptCountInvalid", row);
var numberMatch = System.Text.RegularExpressions.Regex.Match(detail, "^“(?<header>.+)”请填写 (?<min>\\d+)—(?<max>\\d+) 的数值或留空。$");
if (numberMatch.Success)
return SharedResourceText.Get(localizer, "ExperimentGrades.Import.Row.NumberInvalid", row, numberMatch.Groups["header"].Value,
int.Parse(numberMatch.Groups["min"].Value, System.Globalization.CultureInfo.InvariantCulture),
int.Parse(numberMatch.Groups["max"].Value, System.Globalization.CultureInfo.InvariantCulture));
return error;
}
private ActionResult ConflictProblem(string detail) =>
Conflict(new ProblemDetails
{
Title = "无法完成实验成绩操作",
Detail = detail,
Title = SharedResourceText.Get(localizer, "ExperimentGrades.Errors.Title"),
Detail = LocalizeExperimentGradeMessage(detail),
Status = StatusCodes.Status409Conflict
});
private ActionResult ValidationProblem(string detail) =>
base.ValidationProblem(detail: LocalizeExperimentGradeMessage(detail));
private string LocalizeExperimentGradeMessage(string detail) =>
ExperimentGradesErrorKeys.TryGetValue(detail, out var key) ? SharedResourceText.Get(localizer, key) : detail;
private sealed record ExperimentParticipantSeed(
Guid StudentId,
Guid? SessionId);
@@ -374,4 +374,56 @@
<data name="MakeupExams.Enrollment.ExistingMakeupExams" xml:space="preserve"><value>The following students already have another makeup exam at this time: {0}</value></data>
<data name="MakeupExams.Timetable.StartPeriodUnconfigured" xml:space="preserve"><value>Starting period {0} is not configured in the timetable.</value></data>
<data name="MakeupExams.Timetable.EndPeriodUnconfigured" xml:space="preserve"><value>Ending period {0} is not configured in the timetable.</value></data>
<data name="Attendance.Task.ArchivedCannotCreate" xml:space="preserve"><value>This teaching task is archived. Attendance sheets cannot be created.</value></data>
<data name="Attendance.Class.NoActiveStudents" xml:space="preserve"><value>This class has no active students.</value></data>
<data name="Attendance.CheckIn.MethodUnsupported" xml:space="preserve"><value>This check-in method is not supported.</value></data>
<data name="Attendance.CheckIn.DurationRange" xml:space="preserve"><value>The check-in duration must be between 1 and 180 minutes.</value></data>
<data name="Attendance.CheckIn.LocationRequired" xml:space="preserve"><value>Obtain a valid check-in location.</value></data>
<data name="Attendance.CheckIn.RadiusRange" xml:space="preserve"><value>The location check-in radius must be between 20 and 1,000 meters.</value></data>
<data name="Attendance.Sheet.SubmittedCannotEdit" xml:space="preserve"><value>Submitted attendance sheets cannot be edited.</value></data>
<data name="Attendance.Sheet.SubmittedCannotImport" xml:space="preserve"><value>Attendance cannot be imported into a submitted sheet.</value></data>
<data name="Attendance.Sheet.AlreadySubmitted" xml:space="preserve"><value>The attendance sheet has already been submitted.</value></data>
<data name="Attendance.Sheet.SubmittedCheckInEnded" xml:space="preserve"><value>The attendance sheet is submitted and its check-in activity has ended.</value></data>
<data name="Attendance.Sheet.NoOnlineCheckIn" xml:space="preserve"><value>Roll call does not have an online check-in activity.</value></data>
<data name="Attendance.Sheet.NotQrCheckIn" xml:space="preserve"><value>This attendance sheet does not use QR code check-in.</value></data>
<data name="Attendance.CheckIn.NotOpen" xml:space="preserve"><value>Check-in has not started or has already ended.</value></data>
<data name="Attendance.StudentProfile.NotLinked" xml:space="preserve"><value>The current account is not linked to a student record.</value></data>
<data name="Attendance.CheckIn.ActivityMissing" xml:space="preserve"><value>Check-in activity information is missing.</value></data>
<data name="Attendance.Task.ArchivedCheckInStopped" xml:space="preserve"><value>The teaching task is archived and its check-in activity has stopped.</value></data>
<data name="Attendance.Appeal.TaskArchived" xml:space="preserve"><value>An attendance appeal cannot be submitted for an archived teaching task.</value></data>
<data name="Attendance.Appeal.AlreadyPending" xml:space="preserve"><value>An appeal is already being processed.</value></data>
<data name="Attendance.Appeal.AlreadyApproved" xml:space="preserve"><value>The appeal for this attendance record has already been approved.</value></data>
<data name="Attendance.Counselor.NoClassesLinked" xml:space="preserve"><value>The current account is not linked to any classes.</value></data>
<data name="Attendance.Counselor.NotAssignedToClass" xml:space="preserve"><value>You are not the counselor for this class.</value></data>
<data name="Attendance.Appeal.NotPending" xml:space="preserve"><value>This appeal is not pending.</value></data>
<data name="Attendance.Errors.Title" xml:space="preserve"><value>Attendance operation could not be completed</value></data>
<data name="ExperimentGrades.StudentProfile.NotLinked" xml:space="preserve"><value>The current account is not linked to an active student record.</value></data>
<data name="ExperimentGrades.Sheet.ProjectMustBePublishedOrClosed" xml:space="preserve"><value>A grade sheet can only be created for a published or closed experiment project.</value></data>
<data name="ExperimentGrades.Sheet.AlreadyExists" xml:space="preserve"><value>A grade sheet already exists for this experiment project.</value></data>
<data name="ExperimentGrades.Sheet.NoStudentsToGrade" xml:space="preserve"><value>This experiment project has no students to grade.</value></data>
<data name="ExperimentGrades.Settings.CannotEditCurrentState" xml:space="preserve"><value>The grading settings cannot be changed in the current state.</value></data>
<data name="ExperimentGrades.Sheet.SubmittedCannotEdit" xml:space="preserve"><value>The grade sheet cannot be changed after submission.</value></data>
<data name="ExperimentGrades.Records.InvalidOrDuplicate" xml:space="preserve"><value>The request contains invalid or duplicate experiment grade records.</value></data>
<data name="ExperimentGrades.Records.AttemptCountRange" xml:space="preserve"><value>The number of experiment attempts must be between 1 and 20.</value></data>
<data name="ExperimentGrades.Items.InvalidDuplicateOrOutOfRange" xml:space="preserve"><value>The request contains invalid, duplicate or out-of-range grading items. Scores must be between 0 and 100.</value></data>
<data name="ExperimentGrades.Import.DraftOrReturnedOnly" xml:space="preserve"><value>Grades can only be imported into draft or returned experiment grade sheets.</value></data>
<data name="ExperimentGrades.Import.NoData" xml:space="preserve"><value>The Excel file contains no experiment grades to import.</value></data>
<data name="ExperimentGrades.Participants.SubmittedCannotSync" xml:space="preserve"><value>Participants cannot be synchronized after the grade sheet is submitted.</value></data>
<data name="ExperimentGrades.Sheet.DraftOrReturnedOnly" xml:space="preserve"><value>Only draft or returned experiment grade sheets can be submitted.</value></data>
<data name="ExperimentGrades.Sheet.NoStudentRecords" xml:space="preserve"><value>The experiment grade sheet has no student records.</value></data>
<data name="ExperimentGrades.Participants.StatusRequired" xml:space="preserve"><value>Record experiment participation for every student first.</value></data>
<data name="ExperimentGrades.Items.RequiredMissing" xml:space="preserve"><value>Some completed or makeup participants are missing required grading items.</value></data>
<data name="ExperimentGrades.Review.PendingOnlyApprove" xml:space="preserve"><value>Only experiment grade sheets awaiting review can be approved.</value></data>
<data name="ExperimentGrades.Review.PendingOnlyReturn" xml:space="preserve"><value>Only experiment grade sheets awaiting review can be returned.</value></data>
<data name="ExperimentGrades.Review.CommentRequired" xml:space="preserve"><value>Enter revision comments when returning the grade sheet.</value></data>
<data name="ExperimentGrades.Publish.ApprovedOnly" xml:space="preserve"><value>Only approved experiment grade sheets can be published.</value></data>
<data name="ExperimentGrades.Task.ArchivedReadOnly" xml:space="preserve"><value>The teaching task is archived. Experiment grades can only be viewed or exported.</value></data>
<data name="ExperimentGrades.Errors.Title" xml:space="preserve"><value>Experiment grade operation could not be completed</value></data>
<data name="ExperimentGrades.Import.Row.StudentNumberRequired" xml:space="preserve"><value>Row {0}: enter a student number.</value></data>
<data name="ExperimentGrades.Import.Row.StudentNotInSheet" xml:space="preserve"><value>Row {0}: student number “{1}” is not on this experiment grade sheet.</value></data>
<data name="ExperimentGrades.Import.Row.ParticipationStatusInvalid" xml:space="preserve"><value>Row {0}: use a supported Chinese value in “参与状态”: 待登记、已完成、缺席、请假、补做 or 免做.</value></data>
<data name="ExperimentGrades.Import.Row.SafetyViolationInvalid" xml:space="preserve"><value>Row {0}: enter 是 or 否 in the “安全违规” column.</value></data>
<data name="ExperimentGrades.Import.Row.AttemptCountInvalid" xml:space="preserve"><value>Row {0}: enter an integer from 1 to 20 in “实验次数”.</value></data>
<data name="ExperimentGrades.Import.Row.NumberInvalid" xml:space="preserve"><value>Row {0}: enter a number between {2:0} and {3:0}, or leave “{1}” blank.</value></data>
<data name="ExperimentGrades.Import.MoreErrors" xml:space="preserve"><value>{0} additional errors are not shown.</value></data>
</root>
Loaded 3 of 4 files, more files were not shown because too many files have changed in this diff. Show more