Support attachments in student leave requests

This commit is contained in:
biss committed 2026-11-14 15:26:43 +08:00
1 parent 788436ac74
commit bdfbf49f40
13 files changed
+357 -8

No files matched your search

@@ -0,0 +1,44 @@
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Jiaowu.Api.Controllers;
[ApiController]
[Authorize(Roles = SystemRoles.SuperAdmin)]
[Route("api/approval-attachment-storage")]
public sealed class ApprovalAttachmentStorageController(AppDbContext db, IConfiguration configuration) : ControllerBase
{
internal static readonly Guid SettingId = Guid.Parse("3b0d4d71-835f-44c7-8af3-e4112913ba66");
[HttpGet]
public async Task<IActionResult> Get(CancellationToken ct)
{
var setting = await db.ApprovalAttachmentStorageSettings.AsNoTracking().SingleOrDefaultAsync(x => x.Id == SettingId, ct);
return Ok(new { Provider = setting?.Provider ?? "Local", S3Configured = IsS3Configured() });
}
[HttpPut]
public async Task<IActionResult> Put(StorageProviderRequest request, CancellationToken ct)
{
if (request.Provider is not ("Local" or "S3")) return BadRequest(new { message = "无效的存储方式。" });
if (request.Provider == "S3" && !IsS3Configured()) return BadRequest(new { message = "请先在服务器配置 S3 地址、区域、存储桶和访问凭据。" });
var setting = await db.ApprovalAttachmentStorageSettings.SingleOrDefaultAsync(x => x.Id == SettingId, ct);
if (setting is null)
{
setting = new ApprovalAttachmentStorageSetting { Id = SettingId, Provider = request.Provider };
db.ApprovalAttachmentStorageSettings.Add(setting);
}
else { setting.Provider = request.Provider; setting.UpdatedAt = DateTime.UtcNow; }
await db.SaveChangesAsync(ct);
return NoContent();
}
private bool IsS3Configured() => new[] { "Endpoint", "Region", "Bucket", "AccessKey", "SecretKey" }
.All(key => !string.IsNullOrWhiteSpace(configuration[$"Attachments:S3:{key}"]));
}
public sealed record StorageProviderRequest(string Provider);
@@ -0,0 +1,138 @@
using System.ComponentModel.DataAnnotations;
using System.Net.Mime;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
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/student-leave-attachments")]
public sealed class StudentLeaveAttachmentsController(
AppDbContext db, ICurrentUserDataScope scope, IConfiguration configuration, IWebHostEnvironment environment,
ILogger<StudentLeaveAttachmentsController> logger) : ControllerBase
{
private const string ApprovalType = "StudentLeave";
private readonly ApprovalAttachmentStorage storage = new(configuration, environment);
[HttpGet("policy")]
[Authorize(Roles = SystemRoles.Student)]
public async Task<IActionResult> Policy(CancellationToken ct)
{
var policy = await db.ApprovalAttachmentPolicies.AsNoTracking().SingleOrDefaultAsync(x => x.ApprovalType == ApprovalType, ct)
?? ApprovalAttachmentPoliciesController.Default(ApprovalType);
return Ok(new { policy.AllowedExtensions, policy.MaxFileBytes, policy.MaxFileCount });
}
// Persist the application and all attachment metadata together so reviewers cannot
// see a submitted application while its files are still being uploaded.
[HttpPost]
[Authorize(Roles = SystemRoles.Student)]
[RequestSizeLimit(105_000_000)]
[RequestFormLimits(MultipartBodyLengthLimit = 105_000_000)]
public async Task<IActionResult> Create([FromForm] CreateLeaveWithAttachments request, CancellationToken ct)
{
if (!Enum.IsDefined(request.Type) || request.StartAt == default || request.EndAt <= request.StartAt ||
string.IsNullOrWhiteSpace(request.Reason) || request.Reason.Trim().Length > 500)
return BadRequest(new { message = "请填写有效的请假类型、起止时间和事由。" });
var studentId = await db.Students.Where(x => x.UserId == scope.Current.UserId).Select(x => (Guid?)x.Id).FirstOrDefaultAsync(ct);
if (studentId is null) return Forbid();
var policy = await db.ApprovalAttachmentPolicies.AsNoTracking().SingleOrDefaultAsync(x => x.ApprovalType == ApprovalType, ct)
?? ApprovalAttachmentPoliciesController.Default(ApprovalType);
if (request.Files.Sum(x => x.Length) > 104_857_600)
return BadRequest(new { message = "单次申请的附件总大小不能超过 100 MiB。" });
for (var i = 0; i < request.Files.Count; i++)
{
var file = request.Files[i];
var error = ApprovalAttachmentValidation.Validate(policy, file.FileName, file.Length, i);
if (error != AttachmentValidationError.None)
return BadRequest(new { message = "附件不符合文件名、格式、大小或数量限制。", error = error.ToString() });
}
var provider = await db.ApprovalAttachmentStorageSettings.AsNoTracking()
.Where(x => x.Id == ApprovalAttachmentStorageController.SettingId).Select(x => x.Provider).SingleOrDefaultAsync(ct) ?? "Local";
var leave = new StudentLeave { StudentId = studentId.Value, Type = request.Type, StartAt = request.StartAt.UtcDateTime,
EndAt = request.EndAt.UtcDateTime, Reason = request.Reason.Trim() };
var writtenKeys = new List<string>();
var saving = false;
try
{
foreach (var file in request.Files)
{
var key = Guid.NewGuid().ToString("N");
await using var source = file.OpenReadStream();
try { await storage.PutAsync(provider, key, source, ct); }
catch (Exception ex)
{
logger.LogWarning(ex, "Attachment write did not complete for storage key {StorageKey}; check for an orphaned remote object.", key);
throw;
}
writtenKeys.Add(key);
db.ApprovalAttachments.Add(new ApprovalAttachment { ApprovalType = ApprovalType, ApprovalId = leave.Id,
UploadedByUserId = scope.Current.UserId, FileName = file.FileName, Length = file.Length,
StorageProvider = provider, StorageKey = key });
}
db.StudentLeaves.Add(leave);
saving = true;
await db.SaveChangesAsync(ct);
return Ok(new { leave.Id });
}
catch
{
if (saving)
logger.LogError("Attachment database save failed or its outcome is unknown for application {LeaveId}; retained storage keys {StorageKeys} for reconciliation.", leave.Id, string.Join(',', writtenKeys));
else foreach (var key in writtenKeys)
try { await storage.DeleteAsync(provider, key, CancellationToken.None); }
catch (Exception ex) { logger.LogError(ex, "Failed to remove orphaned attachment {StorageKey}.", key); }
throw;
}
}
[HttpGet("{leaveId:guid}")]
public async Task<IActionResult> List(Guid leaveId, CancellationToken ct)
{
if (!await CanRead(leaveId, ct)) return NotFound();
return Ok(await db.ApprovalAttachments.AsNoTracking().Where(x => x.ApprovalType == ApprovalType && x.ApprovalId == leaveId)
.OrderBy(x => x.CreatedAt).Select(x => new { x.Id, x.FileName, x.Length }).ToListAsync(ct));
}
[HttpGet("{leaveId:guid}/{attachmentId:guid}")]
public async Task<IActionResult> Download(Guid leaveId, Guid attachmentId, CancellationToken ct)
{
if (!await CanRead(leaveId, ct)) return NotFound();
var file = await db.ApprovalAttachments.AsNoTracking().SingleOrDefaultAsync(x =>
x.Id == attachmentId && x.ApprovalType == ApprovalType && x.ApprovalId == leaveId, 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 storage.CopyToAsync(file.StorageProvider, file.StorageKey, Response.Body, ct);
return new EmptyResult();
}
private Task<bool> CanRead(Guid leaveId, CancellationToken ct)
{
var current = scope.Current;
var manager = current.IsInRole(SystemRoles.SuperAdmin) || current.IsInRole(SystemRoles.AcademicAdmin) || current.IsInRole(SystemRoles.CollegeAdmin);
var all = manager && current.Scope == DataScope.All;
var collegeId = manager ? current.RestrictedCollegeId : Guid.Empty;
return db.StudentLeaves.AsNoTracking().AnyAsync(x => x.Id == leaveId &&
(x.Student!.UserId == current.UserId || all || manager && x.Student.AdministrativeClass!.Major!.CollegeId == collegeId), ct);
}
}
public sealed class CreateLeaveWithAttachments
{
public StudentLeaveType Type { get; init; }
public DateTimeOffset StartAt { get; init; }
public DateTimeOffset EndAt { get; init; }
[MaxLength(500)] public string Reason { get; init; } = "";
public List<IFormFile> Files { get; init; } = [];
}
@@ -7,8 +7,21 @@ namespace Jiaowu.Api.Infrastructure.Attachments;
// Configuration is supplied by the host; secrets must not be persisted in the database.
public sealed class ApprovalAttachmentStorage(IConfiguration configuration, IWebHostEnvironment environment)
{
private string LocalRoot => Path.GetFullPath(configuration["Attachments:LocalPath"] ??
Path.Combine(environment.ContentRootPath, "data", "attachments"), environment.ContentRootPath);
private string LocalRoot
{
get
{
var root = Path.GetFullPath(configuration["Attachments:LocalPath"] ??
Path.Combine(environment.ContentRootPath, "data", "attachments"), environment.ContentRootPath);
if (!string.IsNullOrEmpty(environment.WebRootPath))
{
var relative = Path.GetRelativePath(Path.GetFullPath(environment.WebRootPath), root);
if (relative == "." || relative != ".." && !relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal) && !Path.IsPathRooted(relative))
throw new InvalidOperationException("Attachment storage must not be inside the web root.");
}
return root;
}
}
private AmazonS3Client CreateS3Client()
{
Loaded 3 of 13 files, more files were not shown because too many files have changed in this diff. Show more