diff --git a/src/Jiaowu.Api/Controllers/ApprovalsController.cs b/src/Jiaowu.Api/Controllers/ApprovalsController.cs index dfda080..caea948 100644 --- a/src/Jiaowu.Api/Controllers/ApprovalsController.cs +++ b/src/Jiaowu.Api/Controllers/ApprovalsController.cs @@ -88,10 +88,11 @@ public sealed class ApprovalsController( [HttpGet("forms/{type}/{id:guid}.docx")] public async Task DownloadApprovalForm(string type, Guid id, CancellationToken ct) { - if (type is not ("CourseExemption" or "DeferredExam" or "CourseSubstitution")) return NotFound(); + if (type is not ("CourseExemption" or "DeferredExam" or "CourseSubstitution" or "StudentStatusChange")) return NotFound(); // Use exactly the same access rules as the approval progress endpoint. var progress = await GetProgress(type, id, ct); - if (progress.Result is not OkObjectResult) return NotFound(); + if (progress.Result is not OkObjectResult { Value: ApprovalProgressResponse progressData }) return NotFound(); + if (type == "StudentStatusChange") return await DownloadStatusChangeForm(id, progressData, ct); var item = type switch { @@ -151,6 +152,49 @@ public sealed class ApprovalsController( string? SubstituteCourse, string Reason, DateTime SubmittedAt, DateTime? ReviewedAt, ApprovalStatus Status, string? Comment, Guid? ReviewerId, Guid? TeachingTaskId); + private async Task DownloadStatusChangeForm(Guid id, ApprovalProgressResponse progress, CancellationToken ct) + { + var item = await db.StudentStatusChanges.AsNoTracking().Where(x => x.Id == id) + .Select(x => new { x.Student!.Name, x.Student.StudentNumber, + OriginalClass = x.OriginalClass != null ? x.OriginalClass.Name : null, + TargetClass = x.TargetClass != null ? x.TargetClass.Name : null, + Term = x.AffectedTerm != null ? x.AffectedTerm.Name : null, + x.Type, x.State, x.Reason, x.SubmittedAt, x.ServiceStartDate, x.DischargeDate, + x.ReceivingCollegeReviewerId, x.ReceivingCollegeReviewedAt }).FirstOrDefaultAsync(ct); + if (item is null) return NotFound(); + var fields = new List<(string Label, string Value)> { + ("申请编号", id.ToString()), ("姓名", item.Name), ("学号", item.StudentNumber), + ("原行政班", item.OriginalClass ?? "未记录"), ("异动类型", SSCLabel(item.Type)), + ("目标行政班", item.TargetClass ?? ""), ("涉及学期", item.Term ?? ""), + ("申请理由", item.Reason), ("申请时间", item.SubmittedAt.ToString("yyyy-MM-dd HH:mm") + " UTC") + }; + if (item.ServiceStartDate is { } start) fields.Add(("入伍日期", start.ToString("yyyy-MM-dd"))); + if (item.DischargeDate is { } discharge) fields.Add(("退役日期", discharge.ToString("yyyy-MM-dd"))); + var events = await db.StudentStatusChangeEvents.AsNoTracking().Where(x => x.StudentStatusChangeId == id) + .Select(x => new { x.OccurredAt, x.ActorUserId }).ToListAsync(ct); + var actorIds = events.Select(x => x.ActorUserId).ToList(); + if (item.ReceivingCollegeReviewerId is { } receivingId) actorIds.Add(receivingId); + var actors = await db.Users.AsNoTracking().Where(x => actorIds.Contains(x.Id)) + .ToDictionaryAsync(x => x.Id, x => x.DisplayName, ct); + foreach (var step in progress.Steps.Where(x => x.Kind != "submitted")) + { + var label = step.Kind switch { + "counselorApproved" => "辅导员通过", "counselorRejected" => "辅导员驳回", + "collegeApproved" => "学院审核通过", "collegeRejected" => "学院审核驳回", + "receivingCollegeApproved" => "接收学院通过", "receivingCollegeRejected" => "接收学院驳回", + "finalApproved" => "最终审核通过", "finalRejected" => "最终审核驳回", + "cancelled" => "申请撤回", _ => "历史审核" + }; + var actorId = step.Kind.StartsWith("receivingCollege", StringComparison.Ordinal) && item.ReceivingCollegeReviewedAt == step.Time + ? item.ReceivingCollegeReviewerId : events.FirstOrDefault(x => x.OccurredAt == step.Time)?.ActorUserId; + var actor = actorId is { } aid && actors.TryGetValue(aid, out var name) ? name : ""; + fields.Add((label, $"{step.Comment ?? ""} {actor} {step.Time:yyyy-MM-dd HH:mm} UTC".Trim())); + } + if (progress.HistoryIncomplete) fields.Add(("记录说明", "历史审核记录不完整,表中仅列出系统已保存的记录。")); + return File(ApprovalFormWordGenerator.Generate(brandingOptions?.InstitutionName ?? "", "学籍异动申请表", fields, DateTimeOffset.UtcNow), + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "学籍异动申请表.docx"); + } + [HttpGet("progress/{type}/{id:guid}")] public async Task> GetProgress(string type, Guid id, CancellationToken ct) { diff --git a/src/Jiaowu.Api/Infrastructure/Approvals/ApprovalFormWordGenerator.cs b/src/Jiaowu.Api/Infrastructure/Approvals/ApprovalFormWordGenerator.cs index 47eb1ed..1f2daf2 100644 --- a/src/Jiaowu.Api/Infrastructure/Approvals/ApprovalFormWordGenerator.cs +++ b/src/Jiaowu.Api/Infrastructure/Approvals/ApprovalFormWordGenerator.cs @@ -6,6 +6,13 @@ namespace Jiaowu.Api.Infrastructure.Approvals; public static class ApprovalFormWordGenerator { + private static readonly HashSet CenteredValues = new(StringComparer.Ordinal) + { + "申请编号", "姓名", "学号", "行政班", "原行政班", "目标行政班", "异动类型", "涉及学期", + "课程", "课程编号", "学分", "学时", "授课教师", "教学班编号", "教学班名称", "开课学期", + "被替代课程", "替代课程", "请假类型", "审核结果", "审核人", "申请时间", "审核时间", + "开始时间(UTC)", "结束时间(UTC)", "申请时间(UTC)", "审核时间(UTC)", "入伍日期", "退役日期" + }; public static byte[] Generate(string institutionName, string title, IReadOnlyList<(string Label, string Value)> fields, DateTimeOffset downloadedAt) { using var stream = new MemoryStream(); @@ -47,10 +54,10 @@ public static class ApprovalFormWordGenerator if (i + 1 < fields.Count && pairs.Contains((label, fields[i + 1].Label))) { var next = fields[++i]; - table.Append(new TableRow(Cell(label, 1500), Cell(value, 3000), - Cell(next.Label, 1500), Cell(next.Value, 3000))); + table.Append(new TableRow(Cell(label, 1500, center: true), Cell(value, 3000, center: ShouldCenter(label, value)), + Cell(next.Label, 1500, center: true), Cell(next.Value, 3000, center: ShouldCenter(next.Label, next.Value)))); } - else table.Append(new TableRow(Cell(label, 1500), Cell(value, 7500, 3))); + else table.Append(new TableRow(Cell(label, 1500, center: true), Cell(value, 7500, 3, ShouldCenter(label, value)))); } body.Append(table); body.Append(new SectionProperties(new FooterReference { Type = HeaderFooterValues.Default, Id = main.GetIdOfPart(footer) }, @@ -61,10 +68,14 @@ public static class ApprovalFormWordGenerator return stream.ToArray(); } - private static TableCell Cell(string value, int width, int span = 1) => new( + private static bool ShouldCenter(string label, string value) => CenteredValues.Contains(label) + && value.Length <= 30 && !value.Contains('\n') && !value.Contains('\r'); + + private static TableCell Cell(string value, int width, int span = 1, bool center = false) => new( new TableCellProperties(new TableCellWidth { Width = width.ToString(), Type = TableWidthUnitValues.Dxa }, - new GridSpan { Val = span }), - new Paragraph(TextRun(value, "宋体", "28"))); + new GridSpan { Val = span }, new TableCellVerticalAlignment { Val = TableVerticalAlignmentValues.Center }), + new Paragraph(new ParagraphProperties(new Justification { Val = center ? JustificationValues.Center : JustificationValues.Left }), + TextRun(value, "宋体", "28"))); private static Run TextRun(string value, string chineseFont, string size) => new( new RunProperties(new RunFonts { Ascii = "Times New Roman", HighAnsi = "Times New Roman", diff --git a/tests/Jiaowu.Api.Tests/ApprovalsControllerTests.cs b/tests/Jiaowu.Api.Tests/ApprovalsControllerTests.cs index ec0a95d..caf53aa 100644 --- a/tests/Jiaowu.Api.Tests/ApprovalsControllerTests.cs +++ b/tests/Jiaowu.Api.Tests/ApprovalsControllerTests.cs @@ -19,6 +19,52 @@ namespace Jiaowu.Api.Tests; public sealed class ApprovalsControllerTests { + [Fact] + public void Approval_form_centers_labels_and_short_values_but_left_aligns_comments() + { + var bytes = Jiaowu.Api.Infrastructure.Approvals.ApprovalFormWordGenerator.Generate("示例大学", "学籍异动申请表", + [("姓名", "张同学"), ("学号", "20260001"), ("申请理由", "申请休学"), ("辅导员通过", "同意申请")], DateTimeOffset.UtcNow); + using var doc = DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Open(new MemoryStream(bytes), false); + var cells = doc.MainDocumentPart!.Document!.Body!.Descendants().ToList(); + DocumentFormat.OpenXml.Wordprocessing.JustificationValues? Alignment(int index) => cells[index].GetFirstChild()!.ParagraphProperties!.Justification!.Val!.Value; + Assert.Equal(DocumentFormat.OpenXml.Wordprocessing.JustificationValues.Center, Alignment(0)); + Assert.Equal(DocumentFormat.OpenXml.Wordprocessing.JustificationValues.Center, Alignment(1)); + Assert.Equal(DocumentFormat.OpenXml.Wordprocessing.JustificationValues.Center, Alignment(2)); + Assert.Equal(DocumentFormat.OpenXml.Wordprocessing.JustificationValues.Center, Alignment(4)); + Assert.Equal(DocumentFormat.OpenXml.Wordprocessing.JustificationValues.Left, Alignment(5)); + Assert.Equal(DocumentFormat.OpenXml.Wordprocessing.JustificationValues.Center, Alignment(6)); + Assert.Equal(DocumentFormat.OpenXml.Wordprocessing.JustificationValues.Left, Alignment(7)); + } + + [Fact] + public async Task Status_change_form_shows_saved_stages_and_denies_other_students() + { + await using var fixture = await ApprovalFixture.CreateAsync(); + var change = new StudentStatusChange { StudentId = fixture.Student.Id, Type = StudentStatusChangeType.Suspension, + OriginalStatus = StudentStatus.Active, TargetStatus = StudentStatus.Suspended, Reason = "申请休学", + State = StudentStatusChangeState.CollegeApproved }; + var first = new StudentStatusChangeEvent { StudentStatusChangeId = change.Id, FromState = StudentStatusChangeState.Submitted, + ToState = StudentStatusChangeState.CounselorApproved, ActorUserId = fixture.Student.UserId!.Value, OccurredAt = DateTime.UtcNow.AddMinutes(-2), Comment = "辅导员意见" }; + var second = new StudentStatusChangeEvent { StudentStatusChangeId = change.Id, FromState = StudentStatusChangeState.CounselorApproved, + ToState = StudentStatusChangeState.CollegeApproved, ActorUserId = fixture.Student.UserId.Value, OccurredAt = DateTime.UtcNow.AddMinutes(-1), Comment = "学院意见" }; + fixture.Db.AddRange(change, first, second); + await fixture.Db.SaveChangesAsync(); + var student = new ApprovalsController(fixture.Db, new StudentDataScope(fixture.Student.UserId.Value)); + var file = Assert.IsType(await student.DownloadApprovalForm("StudentStatusChange", change.Id, CancellationToken.None)); + using var word = DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Open(new MemoryStream(file.FileContents), false); + var text = word.MainDocumentPart!.Document!.Body!.InnerText; + Assert.Contains("辅导员意见", text); + Assert.Contains("学院意见", text); + Assert.Contains("测试学生", text); + var outsider = new ApprovalsController(fixture.Db, new StudentDataScope(Guid.NewGuid())); + Assert.IsType(await outsider.DownloadApprovalForm("StudentStatusChange", change.Id, CancellationToken.None)); + fixture.Db.StudentStatusChangeEvents.Remove(first); + await fixture.Db.SaveChangesAsync(); + var legacyFile = Assert.IsType(await student.DownloadApprovalForm("StudentStatusChange", change.Id, CancellationToken.None)); + using var legacy = DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Open(new MemoryStream(legacyFile.FileContents), false); + Assert.Contains("历史审核记录不完整", legacy.MainDocumentPart!.Document!.Body!.InnerText); + } + [Fact] public async Task Student_leave_word_form_includes_review_and_respects_access_scope() { diff --git a/web/src/views/ApprovalCenterView.vue b/web/src/views/ApprovalCenterView.vue index 6735218..237b20a 100644 --- a/web/src/views/ApprovalCenterView.vue +++ b/web/src/views/ApprovalCenterView.vue @@ -937,7 +937,7 @@ onMounted(async () => {