Add attachments to assessment and course applications

This commit is contained in:
biss committed 2026-11-14 15:37:11 +08:00
1 parent bdfbf49f40
commit d36c0ff7b8
17 files changed
+12906 -39

No files matched your search

@@ -16,11 +16,7 @@ public sealed class ApprovalAttachmentPoliciesController(AppDbContext db) : Cont
{
public static readonly string[] Types =
[
"CourseExemption", "DeferredExam", "CourseSubstitution", "GradeModification",
"StudentStatusChange", "StudentLeave", "TeacherCourseApplication", "ClassroomReservation",
"CourseAdjustment", "DormitoryApplication", "GradeSheet", "GradeSubmissionBatch",
"ExperimentGradeSheet", "AssessmentDeclaration", "AssessmentAppeal",
"CampusRegistration", "AttendanceAppeal"
"CourseExemption", "DeferredExam", "StudentLeave", "AssessmentDeclaration"
];
[HttpGet]
@@ -0,0 +1,58 @@
using System.Net.Mime;
using Jiaowu.Api.Infrastructure.Attachments;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Net.Http.Headers;
namespace Jiaowu.Api.Controllers;
[ApiController]
[Authorize]
[Route("api/approval-attachments")]
public sealed class ApprovalAttachmentsController(AppDbContext db, ICurrentUserDataScope scope,
IConfiguration configuration, IWebHostEnvironment environment) : ControllerBase
{
private static readonly string[] Types = ["CourseExemption", "DeferredExam", "AssessmentDeclaration"];
[HttpGet("policy/{type}")]
public async Task<IActionResult> Policy(string type, CancellationToken ct)
{
if (!Types.Contains(type, StringComparer.Ordinal)) return NotFound();
var policy = await db.ApprovalAttachmentPolicies.AsNoTracking().SingleOrDefaultAsync(x => x.ApprovalType == type, ct)
?? ApprovalAttachmentPoliciesController.Default(type);
return Ok(new { policy.AllowedExtensions, policy.MaxFileBytes, policy.MaxFileCount });
}
[HttpGet("{type}/{id:guid}")]
public async Task<IActionResult> List(string type, Guid id, CancellationToken ct)
{
if (!await CanRead(type, id, ct)) return NotFound();
return Ok(await db.ApprovalAttachments.AsNoTracking().Where(x => x.ApprovalType == type && x.ApprovalId == id)
.OrderBy(x => x.CreatedAt).Select(x => new { x.Id, x.FileName, x.Length }).ToListAsync(ct));
}
[HttpGet("{type}/{id:guid}/{attachmentId:guid}")]
public async Task<IActionResult> Download(string type, Guid id, Guid attachmentId, CancellationToken ct)
{
if (!await CanRead(type, id, ct)) return NotFound();
var file = await db.ApprovalAttachments.AsNoTracking().SingleOrDefaultAsync(x => x.ApprovalType == type && x.ApprovalId == id && x.Id == attachmentId, ct);
if (file is null) return NotFound();
Response.ContentType = MediaTypeNames.Application.Octet;
Response.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileNameStar = file.FileName }.ToString();
Response.Headers.XContentTypeOptions = "nosniff";
Response.ContentLength = file.Length;
await new ApprovalAttachmentStorage(configuration, environment).CopyToAsync(file.StorageProvider, file.StorageKey, Response.Body, ct);
return new EmptyResult();
}
private async Task<bool> CanRead(string type, Guid id, CancellationToken ct)
{
if (!Types.Contains(type, StringComparer.Ordinal)) return false;
// Reuse the approval progress endpoint's business-specific access checks.
var result = await new ApprovalsController(db, scope).GetProgress(type, id, ct);
return result.Result is OkObjectResult;
}
}
@@ -4,6 +4,7 @@ using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Domain.System;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Attachments;
using Jiaowu.Api.Infrastructure.Grades;
using Jiaowu.Api.Infrastructure.Persistence;
using Jiaowu.Api.Infrastructure.Localization;
@@ -751,8 +752,21 @@ public sealed class ApprovalsController(
[HttpPost("exemptions")]
[Authorize(Roles = SystemRoles.Student)]
public async Task<ActionResult> ApplyExemption(ExemptionRequest req, CancellationToken ct)
public Task<ActionResult> ApplyExemption(ExemptionRequest req, CancellationToken ct) => ApplyExemptionCore(req, null, null, ct);
[HttpPost("exemptions-with-attachments")]
[Authorize(Roles = SystemRoles.Student)]
[RequestSizeLimit(105_000_000)]
[RequestFormLimits(MultipartBodyLengthLimit = 105_000_000)]
public Task<ActionResult> ApplyExemptionWithAttachments([FromForm] CourseApplicationWithAttachments req,
[FromServices] IConfiguration configuration, [FromServices] IWebHostEnvironment environment,
[FromServices] ILogger<ApprovalsController> logger, CancellationToken ct) =>
ApplyExemptionCore(new ExemptionRequest(req.TeachingTaskId, req.Reason), req.Files,
new PreparedApprovalAttachments(configuration, environment, logger), ct);
private async Task<ActionResult> ApplyExemptionCore(ExemptionRequest req, IReadOnlyList<IFormFile>? files, PreparedApprovalAttachments? upload, CancellationToken ct)
{
await using var prepared = upload;
var studentId = await GetStudentIdAsync(ct);
if (studentId is null) return StudentNotFound();
if (!await IsStudentCourseAvailableForApplicationAsync(
@@ -761,8 +775,15 @@ public sealed class ApprovalsController(
if (await db.CourseExemptions.AnyAsync(x => x.StudentId == studentId && x.TeachingTaskId == req.TeachingTaskId && x.Status == ApprovalStatus.Submitted, ct))
return ConflictProblem("该课程已有免修申请在审核中。");
var ex = new CourseExemption { StudentId = studentId.Value, TeachingTaskId = req.TeachingTaskId, Reason = req.Reason.Trim(), ReviewerRoleSnapshot = await ReviewerRoleForNewRequest("CourseExemption", ct) };
if (prepared is not null && files is not null)
{
var error = await prepared.PrepareAsync(db, "CourseExemption", ex.Id, scope.Current.UserId, files, ct);
if (error is not null) return BadRequest(new { message = error });
}
db.CourseExemptions.Add(ex);
prepared?.MarkSaveStarted();
await db.SaveChangesAsync(ct);
prepared?.MarkSaved();
// Reload to get nav properties for notification
var info = await db.CourseExemptions.Where(x => x.Id == ex.Id)
.Select(x => new { StudentName = x.Student!.Name, CourseName = x.TeachingTask!.Course!.Name })
@@ -819,8 +840,21 @@ public sealed class ApprovalsController(
[HttpPost("deferred")]
[Authorize(Roles = SystemRoles.Student)]
public async Task<ActionResult> ApplyDeferred(ExemptionRequest req, CancellationToken ct)
public Task<ActionResult> ApplyDeferred(ExemptionRequest req, CancellationToken ct) => ApplyDeferredCore(req, null, null, ct);
[HttpPost("deferred-with-attachments")]
[Authorize(Roles = SystemRoles.Student)]
[RequestSizeLimit(105_000_000)]
[RequestFormLimits(MultipartBodyLengthLimit = 105_000_000)]
public Task<ActionResult> ApplyDeferredWithAttachments([FromForm] CourseApplicationWithAttachments req,
[FromServices] IConfiguration configuration, [FromServices] IWebHostEnvironment environment,
[FromServices] ILogger<ApprovalsController> logger, CancellationToken ct) =>
ApplyDeferredCore(new ExemptionRequest(req.TeachingTaskId, req.Reason), req.Files,
new PreparedApprovalAttachments(configuration, environment, logger), ct);
private async Task<ActionResult> ApplyDeferredCore(ExemptionRequest req, IReadOnlyList<IFormFile>? files, PreparedApprovalAttachments? upload, CancellationToken ct)
{
await using var prepared = upload;
var sid = await GetStudentIdAsync(ct);
if (sid is null) return StudentNotFound();
if (!await IsStudentCourseAvailableForApplicationAsync(
@@ -829,8 +863,15 @@ public sealed class ApprovalsController(
if (await db.DeferredExams.AnyAsync(x => x.StudentId == sid && x.TeachingTaskId == req.TeachingTaskId && x.Status == ApprovalStatus.Submitted, ct))
return ConflictProblem("该课程已有缓考申请在审核中。");
var d = new DeferredExam { StudentId = sid.Value, TeachingTaskId = req.TeachingTaskId, Reason = req.Reason.Trim(), ReviewerRoleSnapshot = await ReviewerRoleForNewRequest("DeferredExam", ct) };
if (prepared is not null && files is not null)
{
var error = await prepared.PrepareAsync(db, "DeferredExam", d.Id, scope.Current.UserId, files, ct);
if (error is not null) return BadRequest(new { message = error });
}
db.DeferredExams.Add(d);
prepared?.MarkSaveStarted();
await db.SaveChangesAsync(ct);
prepared?.MarkSaved();
var info = await db.DeferredExams.Where(x => x.Id == d.Id)
.Select(x => new { StudentName = x.Student!.Name, CourseName = x.TeachingTask!.Course!.Name })
.FirstAsync(ct);
@@ -1471,6 +1512,12 @@ public sealed record StudentCourseSubstitutionRecord(
string SubstituteCourseCode,
string SubstituteCourseName);
public sealed record ExemptionRequest(Guid TeachingTaskId, [Required, MaxLength(500)] string Reason);
public sealed class CourseApplicationWithAttachments
{
public Guid TeachingTaskId { get; init; }
[Required, MaxLength(500)] public string Reason { get; init; } = "";
public List<IFormFile> Files { get; init; } = [];
}
public sealed record GradeModRequest(
Guid GradeRecordId,
decimal? RequestedScore,
Loaded 3 of 17 files, more files were not shown because too many files have changed in this diff. Show more