diff --git a/src/Jiaowu.Api/Controllers/ApprovalsController.cs b/src/Jiaowu.Api/Controllers/ApprovalsController.cs index 802dbc7..dfda080 100644 --- a/src/Jiaowu.Api/Controllers/ApprovalsController.cs +++ b/src/Jiaowu.Api/Controllers/ApprovalsController.cs @@ -12,6 +12,7 @@ using Jiaowu.Api.Infrastructure.Persistence; using Jiaowu.Api.Infrastructure.Localization; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Localization; @@ -868,13 +869,13 @@ public sealed class ApprovalsController( [HttpPost("exemptions/{id:guid}/approve")] [Authorize(Roles = Managers)] - public async Task ApproveExemption(Guid id, CancellationToken ct) + public async Task ApproveExemption(Guid id, CancellationToken ct, [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] ReviewBody? body = null) { var ex = await Scoped(x => x.Id == id).AsTracking().Include(x => x.TeachingTask).ThenInclude(x => x!.Course).FirstOrDefaultAsync(ct); if (ex is null) return NotFound(); if (!CanReviewSnapshot(ex.ReviewerRoleSnapshot)) return Forbid(); if (ex.Status != ApprovalStatus.Submitted) return ConflictProblem("申请已处理,不能重复审核。"); - ex.Status = ApprovalStatus.Approved; ex.ReviewedAt = DateTime.UtcNow; ex.ReviewedByUserId = scope.Current.UserId; + ex.Status = ApprovalStatus.Approved; ex.ReviewedAt = DateTime.UtcNow; ex.ReviewedByUserId = scope.Current.UserId; ex.ReviewComment = body?.Comment?.Trim(); var eligibility = await db.ExamEligibilityDecisions.FirstOrDefaultAsync(x => x.TeachingTaskId == ex.TeachingTaskId && x.StudentId == ex.StudentId && x.Cancelled, ct); if (eligibility is not null) { eligibility.PreviousExamStatus = GradeExamStatus.Exempt; eligibility.PreviousGradeResult = null; } // Auto-apply: mark grade record as exempt @@ -957,13 +958,13 @@ public sealed class ApprovalsController( [HttpPost("deferred/{id:guid}/approve")] [Authorize(Roles = Managers)] - public async Task ApproveDeferred(Guid id, CancellationToken ct) + public async Task ApproveDeferred(Guid id, CancellationToken ct, [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] ReviewBody? body = null) { var d = await Scoped(x => x.Id == id).AsTracking().Include(x => x.TeachingTask).ThenInclude(x => x!.Course).FirstOrDefaultAsync(ct); if (d is null) return NotFound(); if (!CanReviewSnapshot(d.ReviewerRoleSnapshot)) return Forbid(); if (d.Status != ApprovalStatus.Submitted) return ConflictProblem("申请已处理,不能重复审核。"); - d.Status = ApprovalStatus.Approved; d.ReviewedAt = DateTime.UtcNow; d.ReviewedByUserId = scope.Current.UserId; + d.Status = ApprovalStatus.Approved; d.ReviewedAt = DateTime.UtcNow; d.ReviewedByUserId = scope.Current.UserId; d.ReviewComment = body?.Comment?.Trim(); var eligibility = await db.ExamEligibilityDecisions.FirstOrDefaultAsync(x => x.TeachingTaskId == d.TeachingTaskId && x.StudentId == d.StudentId && x.Cancelled, ct); if (eligibility is not null) eligibility.PreviousExamStatus = GradeExamStatus.Deferred; // Auto-apply: set grade record to deferred @@ -1332,13 +1333,13 @@ public sealed class ApprovalsController( [HttpPost("substitutions/{id:guid}/approve")] [Authorize(Roles = Managers)] - public async Task ApproveSubstitution(Guid id, CancellationToken ct) + public async Task ApproveSubstitution(Guid id, CancellationToken ct, [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] ReviewBody? body = null) { var cs = await Scoped(x => x.Id == id).AsTracking().Include(x => x.Student).Include(x => x.OriginalCourse).Include(x => x.SubstituteCourse).FirstOrDefaultAsync(ct); if (cs is null) return NotFound(); if (!CanReviewSnapshot(cs.ReviewerRoleSnapshot)) return Forbid(); if (cs.Status != ApprovalStatus.Submitted) return ConflictProblem("申请已处理,不能重复审核。"); - cs.Status = ApprovalStatus.Approved; cs.ReviewedAt = DateTime.UtcNow; cs.ReviewedByUserId = scope.Current.UserId; + cs.Status = ApprovalStatus.Approved; cs.ReviewedAt = DateTime.UtcNow; cs.ReviewedByUserId = scope.Current.UserId; cs.ReviewComment = body?.Comment?.Trim(); // Do not fabricate or edit a grade record. Formal curriculum and // graduation calculations resolve this approved rule from source data. await db.SaveChangesAsync(ct); diff --git a/src/Jiaowu.Api/Controllers/StudentLeavesController.cs b/src/Jiaowu.Api/Controllers/StudentLeavesController.cs index 96b30d1..2c4d4f3 100644 --- a/src/Jiaowu.Api/Controllers/StudentLeavesController.cs +++ b/src/Jiaowu.Api/Controllers/StudentLeavesController.cs @@ -2,6 +2,8 @@ using System.ComponentModel.DataAnnotations; using Jiaowu.Api.Domain.Academic; using Jiaowu.Api.Domain.Identity; using Jiaowu.Api.Infrastructure.Auth; +using Jiaowu.Api.Infrastructure.Approvals; +using Jiaowu.Api.Infrastructure.Branding; using Jiaowu.Api.Infrastructure.Persistence; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; @@ -12,10 +14,35 @@ namespace Jiaowu.Api.Controllers; [ApiController] [Authorize] [Route("api/student-leaves")] -public sealed class StudentLeavesController(AppDbContext db, ICurrentUserDataScope scope) : ControllerBase +public sealed class StudentLeavesController(AppDbContext db, ICurrentUserDataScope scope, BrandingOptions? branding = null) : ControllerBase { private const string Managers = SystemRoles.SuperAdmin + "," + SystemRoles.AcademicAdmin + "," + SystemRoles.CollegeAdmin; + [HttpGet("{id:guid}/form.docx")] + public async Task DownloadForm(Guid id, CancellationToken ct) + { + var current = scope.Current; + var manager = current.IsInRole(SystemRoles.SuperAdmin) || current.IsInRole(SystemRoles.AcademicAdmin) || current.IsInRole(SystemRoles.CollegeAdmin); + var item = await db.StudentLeaves.AsNoTracking().Where(x => x.Id == id && + (x.Student!.UserId == current.UserId || (manager && + (current.Scope == DataScope.All || (current.RestrictedCollegeId != null && x.Student.AdministrativeClass!.Major!.CollegeId == current.RestrictedCollegeId))))) + .Select(x => new { x.Student!.Name, x.Student.StudentNumber, ClassName = x.Student.AdministrativeClass!.Name, + x.Type, x.StartAt, x.EndAt, x.Reason, x.Status, x.CreatedAt, x.ReviewedAt, x.ReviewComment, x.ReviewedByUserId }).FirstOrDefaultAsync(ct); + if (item is null) return NotFound(); + var reviewer = item.ReviewedByUserId is null ? null : await db.Users.AsNoTracking() + .Where(x => x.Id == item.ReviewedByUserId).Select(x => x.DisplayName).FirstOrDefaultAsync(ct); + var fields = new List<(string, string)> { + ("申请编号", id.ToString()), ("姓名", item.Name), ("学号", item.StudentNumber), ("行政班", item.ClassName), + ("请假类型", item.Type switch { StudentLeaveType.Sick => "病假", StudentLeaveType.Personal => "事假", StudentLeaveType.Official => "公假", StudentLeaveType.Bereavement => "丧假", _ => "其他" }), + ("开始时间(UTC)", item.StartAt.ToString("yyyy-MM-dd HH:mm")), ("结束时间(UTC)", item.EndAt.ToString("yyyy-MM-dd HH:mm")), + ("请假事由", item.Reason), ("申请时间(UTC)", item.CreatedAt.ToString("yyyy-MM-dd HH:mm")), + ("审核结果", item.Status switch { StudentLeaveStatus.Approved => "通过", StudentLeaveStatus.Rejected => "驳回", StudentLeaveStatus.Withdrawn => "已撤回", _ => "待审核" }), + ("审核意见", item.ReviewComment ?? ""), ("审核人", reviewer ?? ""), ("审核时间(UTC)", item.ReviewedAt?.ToString("yyyy-MM-dd HH:mm") ?? "") + }; + return File(ApprovalFormWordGenerator.Generate(branding?.InstitutionName ?? "", "学生请假申请表", fields, DateTimeOffset.UtcNow), + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "学生请假申请表.docx"); + } + [HttpGet("mine")] [Authorize(Roles = SystemRoles.Student)] public async Task Mine(CancellationToken ct) => Ok(await db.StudentLeaves.AsNoTracking() diff --git a/tests/Jiaowu.Api.Tests/ApprovalsControllerTests.cs b/tests/Jiaowu.Api.Tests/ApprovalsControllerTests.cs index febbbf2..ec0a95d 100644 --- a/tests/Jiaowu.Api.Tests/ApprovalsControllerTests.cs +++ b/tests/Jiaowu.Api.Tests/ApprovalsControllerTests.cs @@ -19,6 +19,49 @@ namespace Jiaowu.Api.Tests; public sealed class ApprovalsControllerTests { + [Fact] + public async Task Student_leave_word_form_includes_review_and_respects_access_scope() + { + await using var fixture = await ApprovalFixture.CreateAsync(); + var leave = new StudentLeave { StudentId = fixture.Student.Id, Type = StudentLeaveType.Sick, + StartAt = DateTime.UtcNow, EndAt = DateTime.UtcNow.AddDays(1), Reason = "需要休息", + Status = StudentLeaveStatus.Approved, ReviewComment = "同意请假", ReviewedAt = DateTime.UtcNow }; + fixture.Db.StudentLeaves.Add(leave); + await fixture.Db.SaveChangesAsync(); + var student = new StudentLeavesController(fixture.Db, new StudentDataScope(fixture.Student.UserId!.Value), new BrandingOptions { InstitutionName = "示例大学" }); + var file = Assert.IsType(await student.DownloadForm(leave.Id, CancellationToken.None)); + using var word = DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Open(new MemoryStream(file.FileContents), false); + Assert.Contains("需要休息", word.MainDocumentPart!.Document!.Body!.InnerText); + Assert.Contains("同意请假", word.MainDocumentPart.Document.Body.InnerText); + var outsider = new StudentLeavesController(fixture.Db, new StudentDataScope(Guid.NewGuid())); + Assert.IsType(await outsider.DownloadForm(leave.Id, CancellationToken.None)); + var manager = new StudentLeavesController(fixture.Db, new ManagerDataScope()); + Assert.IsType(await manager.DownloadForm(leave.Id, CancellationToken.None)); + var otherCollege = new StudentLeavesController(fixture.Db, new CollegeDataScope(Guid.NewGuid())); + Assert.IsType(await otherCollege.DownloadForm(leave.Id, CancellationToken.None)); + } + + [Fact] + public async Task Course_approvals_save_optional_approval_comments_for_word_forms() + { + await using var fixture = await ApprovalFixture.CreateAsync(); + var exemption = new CourseExemption { StudentId = fixture.Student.Id, TeachingTaskId = fixture.CurrentTask.Id, Reason = "免修" }; + var deferred = new DeferredExam { StudentId = fixture.Student.Id, TeachingTaskId = fixture.CurrentTask.Id, Reason = "缓考" }; + var substitution = new CourseSubstitution { StudentId = fixture.Student.Id, OriginalCourseId = fixture.CurrentCourse.Id, SubstituteCourseId = fixture.SubstituteCourse.Id, Reason = "替代" }; + fixture.Db.AddRange(exemption, deferred, substitution); + await fixture.Db.SaveChangesAsync(); + var manager = new ApprovalsController(fixture.Db, new ManagerDataScope(), brandingOptions: new BrandingOptions { InstitutionName = "示例大学" }); + Assert.IsType(await manager.ApproveExemption(exemption.Id, CancellationToken.None, new ReviewBody(" 同意免修 "))); + Assert.IsType(await manager.ApproveDeferred(deferred.Id, CancellationToken.None, new ReviewBody("同意缓考"))); + Assert.IsType(await manager.ApproveSubstitution(substitution.Id, CancellationToken.None, new ReviewBody("同意替代"))); + foreach (var (type, id, expected) in new[] { ("CourseExemption", exemption.Id, "同意免修"), ("DeferredExam", deferred.Id, "同意缓考"), ("CourseSubstitution", substitution.Id, "同意替代") }) + { + var file = Assert.IsType(await manager.DownloadApprovalForm(type, id, CancellationToken.None)); + using var word = DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Open(new MemoryStream(file.FileContents), false); + Assert.Contains(expected, word.MainDocumentPart!.Document!.Body!.InnerText); + } + } + [Fact] public void Word_form_footer_converts_download_time_to_beijing_time() { diff --git a/web/src/components/StudentLeavePanel.vue b/web/src/components/StudentLeavePanel.vue index d85b998..752ddc9 100644 --- a/web/src/components/StudentLeavePanel.vue +++ b/web/src/components/StudentLeavePanel.vue @@ -3,6 +3,7 @@ import { computed, onMounted, reactive, ref } from 'vue' import { useI18n } from 'vue-i18n' import { ElMessage, ElMessageBox } from 'element-plus' import http, { apiErrorMessage } from '../api/http' +import { downloadApiFile } from '../api/excel' const props = defineProps<{ student: boolean; manager: boolean }>() const { locale } = useI18n() @@ -39,6 +40,10 @@ async function downloadAttachment(file: { id: string; fileName: string }) { setTimeout(() => URL.revokeObjectURL(url), 1000) } catch (e) { ElMessage.error(apiErrorMessage(e)) } } +async function downloadForm(row: any) { + try { await downloadApiFile(`/student-leaves/${row.id}/form.docx`, 'student-leave.docx') } + catch (e) { ElMessage.error(apiErrorMessage(e)) } +} const formatTime = (value: string) => new Date(value.endsWith('Z') ? value : value + 'Z').toLocaleString() async function load() { try { rows.value = (await http.get(props.student ? '/student-leaves/mine' : '/student-leaves/pending')).data } @@ -101,6 +106,7 @@ onMounted(async () => { diff --git a/web/src/views/ApprovalCenterView.vue b/web/src/views/ApprovalCenterView.vue index 0674ee0..6735218 100644 --- a/web/src/views/ApprovalCenterView.vue +++ b/web/src/views/ApprovalCenterView.vue @@ -128,6 +128,9 @@ const substituteKeyword = ref(""); const rejectDialog = ref(false); const rejectItem = ref(null); const rejectComment = ref(""); +const approveDialog = ref(false); +const approveTarget = ref(null); +const approveComment = ref(""); const reviewInProgress = ref(false); const workflowDialog = ref(false); const workflowSettings = ref<{ type: string; reviewerRole: string }[]>([]); @@ -456,10 +459,22 @@ async function submitForm() { } async function approveItem(item: any) { + if (reviewInProgress.value) return; + if (["CourseExemption", "DeferredExam", "CourseSubstitution"].includes(item.type)) { + approveTarget.value = item; + approveComment.value = ""; + approveDialog.value = true; + return; + } + await approveWithComment(item, ""); +} + +async function approveWithComment(item: any, comment: string) { if (reviewInProgress.value) return; reviewInProgress.value = true; try { - if (await submitReview(item, true, "")) { + if (await submitReview(item, true, comment)) { + approveDialog.value = false; ElMessage.success(t("approvalBatch.approved")); if (targetApprovalId.value) await router.replace({ path: "/approvals", query: { tab: "pending" } }); @@ -641,7 +656,7 @@ async function submitReview(item: any, approved: boolean, comment: string) { : "reject"; await http.post( `${ep}/${item.id}/${action}`, - approved ? undefined : { comment }, + approved && !["CourseExemption", "DeferredExam", "CourseSubstitution"].includes(item.type) ? undefined : { comment }, ); } return true; @@ -1681,6 +1696,14 @@ onMounted(async () => { + + + +