70 lines
3.0 KiB
C#
70 lines
3.0 KiB
C#
using System.ComponentModel.DataAnnotations;
|
|
using Jiaowu.Api.Domain.Identity;
|
|
using Jiaowu.Api.Infrastructure.Academic;
|
|
using Jiaowu.Api.Infrastructure.Auth;
|
|
using Jiaowu.Api.Infrastructure.Caching;
|
|
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 + "," + SystemRoles.AcademicAdmin + "," + SystemRoles.CollegeAdmin)]
|
|
[Route("api/archives/{kind}")]
|
|
public sealed class ArchivesController(AppDbContext db, ICurrentUserDataScope scope, IAppCache cache) : ControllerBase
|
|
{
|
|
[HttpPost("preview")]
|
|
public async Task<ActionResult> Preview(string kind, ArchiveBatchRequest request, CancellationToken ct)
|
|
{
|
|
var service = new ArchiveService(db, scope);
|
|
var results = new List<object>();
|
|
foreach (var id in request.Ids.Distinct())
|
|
{
|
|
var item = await service.InspectAsync(kind, id, !request.Archived, ct);
|
|
results.Add(item is null ? new { Id = id, Error = "记录不存在或无权操作。" } : (object)item.Value.Preview);
|
|
}
|
|
return Ok(results);
|
|
}
|
|
|
|
[HttpGet("{id:guid}/history")]
|
|
public async Task<ActionResult> History(string kind, Guid id, CancellationToken ct, int page = 1)
|
|
{
|
|
if (await new ArchiveService(db, scope).InspectAsync(kind, id, true, ct) is null) return NotFound();
|
|
return Ok(await db.ArchiveEvents.AsNoTracking().Where(x => x.Kind == kind && x.EntityId == id)
|
|
.OrderByDescending(x => x.CreatedAt).ThenByDescending(x => x.Id)
|
|
.Skip((Math.Clamp(page, 1, 100000) - 1) * 20).Take(20).ToListAsync(ct));
|
|
}
|
|
|
|
[HttpPost("apply")]
|
|
public async Task<ActionResult> Apply(string kind, ArchiveBatchRequest request, CancellationToken ct)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(request.Reason)) return BadRequest("请填写归档或恢复原因。");
|
|
var results = new List<object>();
|
|
foreach (var id in request.Ids.Distinct())
|
|
{
|
|
try
|
|
{
|
|
var result = await new ArchiveService(db, scope).ChangeAsync(kind, id, request.Archived, request.Reason, ct);
|
|
results.Add(result);
|
|
}
|
|
catch (Exception ex) when (ex is DbUpdateException or System.Data.Common.DbException)
|
|
{
|
|
results.Add(new ArchiveOperationResult(id, false, "记录已发生变化或保存失败,请刷新后重试。"));
|
|
}
|
|
finally { db.ChangeTracker.Clear(); }
|
|
}
|
|
await cache.RemoveByTagAsync(AppCacheTags.Timetables, ct);
|
|
await cache.RemoveByTagAsync(AppCacheTags.Analytics, ct);
|
|
await cache.RemoveByTagAsync(AppCacheTags.BaseData, ct);
|
|
return Ok(results);
|
|
}
|
|
}
|
|
|
|
public sealed record ArchiveBatchRequest(
|
|
[param: Required, MinLength(1), MaxLength(100)] Guid[] Ids,
|
|
bool Archived,
|
|
[param: MaxLength(500)] string? Reason = null);
|
|
|