Files
Academic-Affairs-System/src/Jiaowu.Api/Controllers/StudentDisciplinesController.cs
T

208 lines
17 KiB
C#

using System.ComponentModel.DataAnnotations;
using System.Text.Json;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Attachments;
using Jiaowu.Api.Infrastructure.Excel;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Jiaowu.Api.Controllers;
[ApiController]
[Authorize(Roles = SystemRoles.Counselor + "," + SystemRoles.CollegeAdmin + "," + SystemRoles.AcademicAdmin + "," + SystemRoles.StudentAffairsAdmin + "," + SystemRoles.SuperAdmin)]
[Route("api/student-disciplines")]
public sealed class StudentDisciplinesController(AppDbContext db, ICurrentUserDataScope currentUserDataScope, IConfiguration configuration, IWebHostEnvironment environment, ILogger<StudentDisciplinesController> logger) : ControllerBase
{
private IQueryable<Student> Students()
{
var scope = currentUserDataScope.Current;
if (scope.IsInRole(SystemRoles.StudentAffairsAdmin)) return db.Students;
if (scope.IsInRole(SystemRoles.SuperAdmin) || scope.IsInRole(SystemRoles.AcademicAdmin))
return scope.Scope == DataScope.All ? db.Students : db.Students.Where(_ => false);
return scope.Scope switch
{
DataScope.College when scope.IsInRole(SystemRoles.CollegeAdmin) => db.Students.Where(x => x.AdministrativeClass!.Major!.CollegeId == scope.RestrictedCollegeId),
DataScope.Class when scope.IsInRole(SystemRoles.Counselor) => db.Students.Where(x => x.AdministrativeClass!.CounselorUserId == scope.UserId),
_ => db.Students.Where(_ => false)
};
}
private IQueryable<StudentDiscipline> Scoped() => db.StudentDisciplines.Where(x => Students().Any(s => s.Id == x.StudentId));
private IQueryable<StudentDiscipline> Filter(string? keyword, StudentDisciplineState? state, string? disciplineType, DateOnly? dateFrom, DateOnly? dateTo)
{
var query = Scoped().AsNoTracking();
if (!string.IsNullOrWhiteSpace(keyword)) { var term = keyword.Trim(); query = query.Where(x => x.Student!.Name.Contains(term) || x.Student.StudentNumber.Contains(term)); }
if (state.HasValue) query = query.Where(x => x.State == state);
if (!string.IsNullOrWhiteSpace(disciplineType)) { var type = disciplineType.Trim(); query = query.Where(x => x.DisciplineType.Contains(type)); }
if (dateFrom.HasValue) query = query.Where(x => x.DecisionDate >= dateFrom.Value);
if (dateTo.HasValue) query = query.Where(x => x.DecisionDate <= dateTo.Value);
return query;
}
[HttpGet("types")]
public async Task<IActionResult> Types(CancellationToken token) => Ok(await db.StudentDisciplineTypes.AsNoTracking().OrderBy(x => x.Name).Select(x => new { x.Id, x.Name, x.IsEnabled }).ToListAsync(token));
[HttpPut("types")]
[Authorize(Roles = SystemRoles.StudentAffairsAdmin + "," + SystemRoles.AcademicAdmin + "," + SystemRoles.SuperAdmin)]
public async Task<IActionResult> SetTypes([FromBody] string[] names, CancellationToken token)
{
if (names is null || names.Length > 100 || names.Any(x => string.IsNullOrWhiteSpace(x) || x.Trim().Length > 100)) return BadRequest("处分类型须为 1 至 100 字,最多 100 项。");
var normalized = names.Select(x => x.Trim()).ToArray();
if (normalized.Distinct(StringComparer.OrdinalIgnoreCase).Count() != normalized.Length) return BadRequest("处分类型不能重复。");
var existing = await db.StudentDisciplineTypes.ToListAsync(token);
foreach (var type in existing) type.IsEnabled = normalized.Contains(type.Name, StringComparer.OrdinalIgnoreCase);
foreach (var name in normalized.Where(name => !existing.Any(x => string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase)))) db.StudentDisciplineTypes.Add(new StudentDisciplineType { Name = name });
await db.SaveChangesAsync(token);
return NoContent();
}
[HttpGet("students")]
public async Task<IActionResult> SearchStudents(string? keyword, CancellationToken token)
{
keyword = keyword?.Trim();
if (string.IsNullOrEmpty(keyword) || keyword.Length < 2) return BadRequest("请输入至少两个字符。");
return Ok(await Students().AsNoTracking().Where(x => !x.IsArchived && (x.StudentNumber.Contains(keyword) || x.Name.Contains(keyword)))
.OrderBy(x => x.StudentNumber).Take(20).Select(x => new { x.Id, x.StudentNumber, x.Name, ClassName = x.AdministrativeClass!.Name }).ToListAsync(token));
}
[HttpGet]
public async Task<IActionResult> List(string? keyword, StudentDisciplineState? state, string? disciplineType, DateOnly? dateFrom, DateOnly? dateTo, int page = 1, int pageSize = 20, CancellationToken token = default)
{
if (page < 1 || pageSize is < 1 or > 100) return BadRequest();
var query = Filter(keyword, state, disciplineType, dateFrom, dateTo);
var total = await query.CountAsync(token);
var items = await query.OrderByDescending(x => x.CreatedAt).ThenByDescending(x => x.Id).Skip((page - 1) * pageSize).Take(pageSize)
.Select(x => new { x.Id, x.StudentId, x.Student!.StudentNumber, x.Student.Name, ClassName = x.Student.AdministrativeClass!.Name, x.DisciplineType, x.State, x.DecisionDate, x.EffectiveDate, x.CreatedAt }).ToListAsync(token);
return Ok(new { items, total, page, pageSize });
}
private static readonly string[] ExportHeaders = ["学号", "姓名", "班级", "处分类型", "状态", "决定日期", "生效日期", "文号", "决定机构"];
[HttpGet("export-columns")]
public IActionResult ExportColumns() => Ok(ExportHeaders);
[HttpGet("export")]
public async Task<IActionResult> Export(string? keyword, StudentDisciplineState? state, string? disciplineType, DateOnly? dateFrom, DateOnly? dateTo, CancellationToken token, string? columns = null, string? format = null)
{
var query = Filter(keyword, state, disciplineType, dateFrom, dateTo);
var items = await query.OrderByDescending(x => x.CreatedAt).ThenByDescending(x => x.Id).Take(10001).Select(x => new { x.Student!.StudentNumber, x.Student.Name, ClassName = x.Student.AdministrativeClass!.Name, x.DisciplineType, x.State, x.DecisionDate, x.EffectiveDate, x.DecisionNumber, x.DecisionAuthority }).ToListAsync(token);
if (items.Count > 10000) return BadRequest("结果超过 10000 条,请缩小查询范围。");
var rows = items.Select(x => (IReadOnlyList<object?>)new object?[] { x.StudentNumber, x.Name, x.ClassName, x.DisciplineType, StateLabel(x.State), x.DecisionDate.ToString("yyyy-MM-dd"), x.EffectiveDate.ToString("yyyy-MM-dd"), x.DecisionNumber, x.DecisionAuthority }).ToList();
if (columns is not null || format is not null) return TabularExport.Create(this, "处分记录", ExportHeaders, rows, columns, format);
return File(ExcelWorkbookHelper.Create("处分记录", ExportHeaders, rows), ExcelWorkbookHelper.ContentType, "处分记录.xlsx");
}
private static string StateLabel(StudentDisciplineState state) => state switch { StudentDisciplineState.Draft => "草稿", StudentDisciplineState.Submitted => "待院系审核", StudentDisciplineState.CollegeApproved => "待校级审核", StudentDisciplineState.Effective => "已批准", StudentDisciplineState.Rejected => "已驳回", StudentDisciplineState.Withdrawn => "已撤回", StudentDisciplineState.Lifted => "已解除", StudentDisciplineState.Revoked => "已撤销", _ => "未知" };
[HttpGet("{id:guid}")]
public async Task<IActionResult> Detail(Guid id, CancellationToken token)
{
var item = await Scoped().AsNoTracking().Where(x => x.Id == id).Select(x => new { x.Id, x.StudentId, x.Student!.StudentNumber, x.Student.Name, x.DisciplineType, x.Facts, x.Basis, x.DecisionNumber, x.DecisionAuthority, x.DecisionDate, x.EffectiveDate, x.State, x.CreatedByUserId, x.SubmittedAt, Events = x.Events.OrderBy(e => e.OccurredAt).Select(e => new { e.FromState, e.ToState, e.ActorUserId, e.OccurredAt, e.Comment, e.SnapshotJson }).ToList() }).SingleOrDefaultAsync(token);
return item is null ? NotFound() : Ok(item);
}
[HttpPost]
public async Task<IActionResult> Create(DisciplineInput input, CancellationToken token)
{
if (!await Students().AnyAsync(x => x.Id == input.StudentId && !x.IsArchived, token)) return NotFound();
if (!await db.StudentDisciplineTypes.AnyAsync(x => x.IsEnabled && x.Name == input.DisciplineType.Trim(), token)) return BadRequest("请选择已启用的处分类型。");
if (input.DecisionDate == default || input.EffectiveDate == default || input.EffectiveDate < input.DecisionDate) return BadRequest("请填写有效日期,生效日期不能早于决定日期。");
var item = new StudentDiscipline { StudentId = input.StudentId, DisciplineType = input.DisciplineType.Trim(), Facts = input.Facts.Trim(), Basis = input.Basis.Trim(), DecisionNumber = input.DecisionNumber.Trim(), DecisionAuthority = input.DecisionAuthority.Trim(), DecisionDate = input.DecisionDate, EffectiveDate = input.EffectiveDate, CreatedByUserId = currentUserDataScope.Current.UserId };
db.StudentDisciplines.Add(item);
await db.SaveChangesAsync(token);
return Ok(new { item.Id });
}
[HttpPost("{id:guid}/transition")]
public async Task<IActionResult> Transition(Guid id, TransitionInput input, CancellationToken token)
{
var item = await Scoped().SingleOrDefaultAsync(x => x.Id == id, token);
if (item is null) return NotFound();
var scope = currentUserDataScope.Current;
var school = scope.IsInRole(SystemRoles.StudentAffairsAdmin) || scope.IsInRole(SystemRoles.AcademicAdmin) || scope.IsInRole(SystemRoles.SuperAdmin);
var college = scope.IsInRole(SystemRoles.CollegeAdmin) || scope.IsInRole(SystemRoles.SuperAdmin);
var allowed = (item.State, input.State) switch
{
(StudentDisciplineState.Draft or StudentDisciplineState.Rejected or StudentDisciplineState.Withdrawn, StudentDisciplineState.Submitted) => item.CreatedByUserId == scope.UserId,
(StudentDisciplineState.Submitted, StudentDisciplineState.Withdrawn) => item.CreatedByUserId == scope.UserId,
(StudentDisciplineState.Submitted, StudentDisciplineState.CollegeApproved or StudentDisciplineState.Rejected) => college,
(StudentDisciplineState.CollegeApproved, StudentDisciplineState.Effective or StudentDisciplineState.Rejected) => school,
(StudentDisciplineState.Effective, StudentDisciplineState.Lifted or StudentDisciplineState.Revoked) => school,
_ => false
};
if (!allowed) return Conflict("当前状态或权限不允许此操作。");
if (input.State == StudentDisciplineState.Effective && item.EffectiveDate > DateOnly.FromDateTime(DateTime.Now)) return BadRequest("生效日期尚未到达,请在生效日期或之后审批通过。");
if (input.State is StudentDisciplineState.Rejected or StudentDisciplineState.Lifted or StudentDisciplineState.Revoked && string.IsNullOrWhiteSpace(input.Comment)) return BadRequest("请填写处理原因。");
var now = DateTime.UtcNow;
db.StudentDisciplineEvents.Add(new StudentDisciplineEvent { StudentDisciplineId = item.Id, FromState = item.State, ToState = input.State, ActorUserId = scope.UserId, OccurredAt = now, Comment = input.Comment?.Trim(), SnapshotJson = Snapshot(item) });
item.State = input.State;
if (input.State == StudentDisciplineState.Submitted) item.SubmittedAt = now;
try { await db.SaveChangesAsync(token); } catch (DbUpdateConcurrencyException) { return Conflict("记录已发生变化,请刷新后重试。"); }
return NoContent();
}
[HttpPut("{id:guid}")]
public async Task<IActionResult> Update(Guid id, DisciplineInput input, CancellationToken token)
{
var item = await Scoped().SingleOrDefaultAsync(x => x.Id == id, token);
if (item is null) return NotFound();
if (item.CreatedByUserId != currentUserDataScope.Current.UserId || item.State is not (StudentDisciplineState.Draft or StudentDisciplineState.Rejected or StudentDisciplineState.Withdrawn)) return Conflict("当前状态或权限不允许修改。");
if (item.StudentId != input.StudentId || input.DecisionDate == default || input.EffectiveDate == default || input.EffectiveDate < input.DecisionDate) return BadRequest("学生不能更改;请填写有效日期,生效日期不能早于决定日期。");
if (input.DisciplineType.Trim() != item.DisciplineType && !await db.StudentDisciplineTypes.AnyAsync(x => x.IsEnabled && x.Name == input.DisciplineType.Trim(), token)) return BadRequest("请选择已启用的处分类型。");
db.StudentDisciplineEvents.Add(new StudentDisciplineEvent { StudentDisciplineId = item.Id, FromState = item.State, ToState = item.State, ActorUserId = currentUserDataScope.Current.UserId, OccurredAt = DateTime.UtcNow, Comment = "修改前记录", SnapshotJson = Snapshot(item) });
item.DisciplineType = input.DisciplineType.Trim(); item.Facts = input.Facts.Trim(); item.Basis = input.Basis.Trim();
item.DecisionNumber = input.DecisionNumber.Trim(); item.DecisionAuthority = input.DecisionAuthority.Trim(); item.DecisionDate = input.DecisionDate; item.EffectiveDate = input.EffectiveDate;
try { await db.SaveChangesAsync(token); } catch (DbUpdateConcurrencyException) { return Conflict("记录已发生变化,请刷新后重试。"); }
return NoContent();
}
[HttpGet("{id:guid}/attachments")]
public async Task<IActionResult> Attachments(Guid id, CancellationToken token)
{
if (!await Scoped().AnyAsync(x => x.Id == id, token)) return NotFound();
return Ok(await db.ApprovalAttachments.AsNoTracking().Where(x => x.ApprovalType == "StudentDiscipline" && x.ApprovalId == id).Select(x => new { x.Id, x.FileName, x.Length }).ToListAsync(token));
}
[HttpPost("{id:guid}/attachments")]
[RequestSizeLimit(104857600)]
public async Task<IActionResult> Upload(Guid id, [FromForm] List<IFormFile> files, CancellationToken token)
{
var item = await Scoped().SingleOrDefaultAsync(x => x.Id == id, token);
if (item is null) return NotFound();
if (item.CreatedByUserId != currentUserDataScope.Current.UserId || item.State is not (StudentDisciplineState.Draft or StudentDisciplineState.Rejected or StudentDisciplineState.Withdrawn)) return Conflict("当前状态或权限不允许上传附件。");
if (files.Count == 0) return BadRequest("请选择附件。");
var count = await db.ApprovalAttachments.CountAsync(x => x.ApprovalType == "StudentDiscipline" && x.ApprovalId == id, token);
await using var prepared = new PreparedApprovalAttachments(configuration, environment, logger);
var error = await prepared.PrepareAsync(db, "StudentDiscipline", id, currentUserDataScope.Current.UserId, files, token, count);
if (error is not null) return BadRequest(error);
item.UpdatedAt = DateTime.UtcNow;
prepared.MarkSaveStarted();
try { await db.SaveChangesAsync(token); } catch (DbUpdateConcurrencyException) { return Conflict("记录已发生变化,请刷新后重试。"); }
prepared.MarkSaved();
return NoContent();
}
[HttpGet("{id:guid}/attachments/{attachmentId:guid}")]
public async Task<IActionResult> Download(Guid id, Guid attachmentId, CancellationToken token)
{
if (!await Scoped().AnyAsync(x => x.Id == id, token)) return NotFound();
var file = await db.ApprovalAttachments.AsNoTracking().SingleOrDefaultAsync(x => x.ApprovalType == "StudentDiscipline" && x.ApprovalId == id && x.Id == attachmentId, token);
if (file is null) return NotFound();
Response.ContentType = "application/octet-stream";
Response.Headers.ContentDisposition = new Microsoft.Net.Http.Headers.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, token);
return new EmptyResult();
}
private static string Snapshot(StudentDiscipline item) => JsonSerializer.Serialize(new { item.DisciplineType, item.Facts, item.Basis, item.DecisionNumber, item.DecisionAuthority, item.DecisionDate, item.EffectiveDate });
}
public sealed record DisciplineInput(Guid StudentId, [Required, StringLength(100, MinimumLength = 1)] string DisciplineType, [Required, StringLength(4000, MinimumLength = 1)] string Facts, [Required, StringLength(2000, MinimumLength = 1)] string Basis, [Required, StringLength(200, MinimumLength = 1)] string DecisionNumber, [Required, StringLength(200, MinimumLength = 1)] string DecisionAuthority, DateOnly DecisionDate, DateOnly EffectiveDate);
public sealed record TransitionInput(StudentDisciplineState State, [StringLength(1000)] string? Comment);