Add admin maintenance endpoints and file deletion functionality
CI / Backend (build + test) (push) Successful in 1m21s
CI / Frontend (lint + typecheck + build) (push) Successful in 37s

- Introduced a new `/api/admin/maintenance` route for administrative maintenance tasks, requiring admin authorization.
- Implemented the `DeleteAsync` method in `IFileStorage` to allow for the deletion of files associated with closed support tickets.
- Updated API documentation to include details about the new maintenance operations and their effects on closed tickets.
- Enhanced frontend routing to include the new maintenance section in the admin panel, improving navigation for administrators.
- Added localization support for maintenance-related actions in both Russian and English.
This commit is contained in:
Leonid Pershin
2026-07-14 12:04:10 +03:00
parent 9a6540a266
commit 8dfeb05912
15 changed files with 329 additions and 3 deletions
@@ -0,0 +1,36 @@
using PnvPanel.Api.Common;
using PnvPanel.Application.Admin.Maintenance;
using PnvPanel.Application.Common.Messaging;
using PnvPanel.Infrastructure.Identity;
namespace PnvPanel.Api.Endpoints;
public static class AdminMaintenanceEndpoints
{
public static IEndpointRouteBuilder MapAdminMaintenanceEndpoints(this IEndpointRouteBuilder app)
{
var admin = app.MapGroup("/api/admin/maintenance")
.WithTags("Admin.Maintenance")
.RequireAuthorization(policy => policy.RequireRole(RoleNames.Admin));
admin
.MapDelete("/tickets/closed", DeleteClosedTickets)
.Produces<DeleteClosedTicketsResponseDto>();
return app;
}
private static async Task<IResult> DeleteClosedTickets(
ISender sender,
CancellationToken cancellationToken
)
{
var result = await sender.Send(new DeleteClosedTicketsCommand(), cancellationToken);
if (!result.IsSuccess)
return result.ToHttpResult();
return Results.Ok(new DeleteClosedTicketsResponseDto(result.Value));
}
}
public sealed record DeleteClosedTicketsResponseDto(int DeletedCount);
+1
View File
@@ -191,6 +191,7 @@ app.MapAdminAppEndpoints();
app.MapAdminNewsEndpoints();
app.MapSupportEndpoints();
app.MapAdminSupportEndpoints();
app.MapAdminMaintenanceEndpoints();
app.MapTelegramEndpoints();
app.MapHub<PanelHub>("/hubs/panel");
@@ -0,0 +1,8 @@
using PnvPanel.Application.Common.Messaging;
using PnvPanel.Application.Common.Models;
namespace PnvPanel.Application.Admin.Maintenance;
/// <summary>Удаляет все тикеты в статусе Closed вместе с их перепиской и вложениями (в т.ч. файлами
/// на диске). Value — число удалённых тикетов.</summary>
public sealed record DeleteClosedTicketsCommand : ICommand<Result<int>>;
@@ -0,0 +1,69 @@
using Microsoft.EntityFrameworkCore;
using PnvPanel.Application.Auth;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Common.Messaging;
using PnvPanel.Application.Common.Models;
using PnvPanel.Domain.Audit;
using PnvPanel.Domain.Support;
namespace PnvPanel.Application.Admin.Maintenance;
public sealed class DeleteClosedTicketsCommandHandler(
IAppDbContext dbContext,
IFileStorage fileStorage,
ICurrentUser currentUser
) : ICommandHandler<DeleteClosedTicketsCommand, Result<int>>
{
public async Task<Result<int>> Handle(
DeleteClosedTicketsCommand command,
CancellationToken cancellationToken
)
{
if (currentUser.UserId is not { } adminId)
return Result.Failure<int>(AuthErrors.Unauthorized);
var ticketIds = await dbContext
.SupportTickets.AsNoTracking()
.Where(t => t.Status == TicketStatus.Closed)
.Select(t => t.Id)
.ToListAsync(cancellationToken);
if (ticketIds.Count == 0)
return Result.Success(0);
// Тикет/комментарий/вложение — плоские сущности без FK-каскада (см. SupportTicket), поэтому
// порядок удаления важен: вложения (+ файлы на диске) -> комментарии -> тикеты.
var comments = await dbContext
.TicketComments.Where(c => ticketIds.Contains(c.TicketId))
.ToListAsync(cancellationToken);
var commentIds = comments.Select(c => c.Id).ToList();
var attachments = await dbContext
.TicketAttachments.Where(a => commentIds.Contains(a.CommentId))
.ToListAsync(cancellationToken);
foreach (var attachment in attachments)
await fileStorage.DeleteAsync(attachment.StoredFileName, cancellationToken);
dbContext.TicketAttachments.RemoveRange(attachments);
dbContext.TicketComments.RemoveRange(comments);
var tickets = await dbContext
.SupportTickets.Where(t => ticketIds.Contains(t.Id))
.ToListAsync(cancellationToken);
dbContext.SupportTickets.RemoveRange(tickets);
dbContext.AuditLogs.Add(
AuditLog.Create(
adminId,
"ClosedTicketsCleanedUp",
"SupportTicket",
"bulk",
metadata: $"count={ticketIds.Count}",
AuditSource.Web
)
);
return Result.Success(ticketIds.Count);
}
}
@@ -12,4 +12,7 @@ public interface IFileStorage
/// <summary>Null, если файла с таким именем нет на диске (например, удалён вручную).</summary>
Task<Stream?> OpenReadAsync(string storedFileName, CancellationToken cancellationToken);
/// <summary>Идемпотентно — отсутствие файла не ошибка (мог быть удалён вручную).</summary>
Task DeleteAsync(string storedFileName, CancellationToken cancellationToken);
}
@@ -31,4 +31,13 @@ internal sealed class DiskFileStorage(IOptions<FileStorageOptions> options) : IF
return Task.FromResult<Stream?>(File.OpenRead(path));
}
public Task DeleteAsync(string storedFileName, CancellationToken cancellationToken)
{
var path = Path.Combine(options.Value.RootPath, storedFileName);
if (File.Exists(path))
File.Delete(path);
return Task.CompletedTask;
}
}
@@ -0,0 +1,85 @@
using NSubstitute;
using PnvPanel.Application.Admin.Maintenance;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Tests.TestSupport;
using PnvPanel.Domain.Support;
using Xunit;
namespace PnvPanel.Application.Tests.Admin.Maintenance;
public class DeleteClosedTicketsCommandHandlerTests
{
private readonly IFileStorage _fileStorage = Substitute.For<IFileStorage>();
[Fact]
public async Task Handle_DeletesClosedTicketsWithCommentsAndAttachments_KeepsOthers()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var closedTicket = SupportTicket.CreateBugReport(userId);
closedTicket.Close();
var openTicket = SupportTicket.CreateBugReport(userId);
dbContext.SupportTickets.AddRange(closedTicket, openTicket);
var closedComment = TicketComment.Create(
closedTicket.Id,
userId,
"закрытый тикет, есть скриншот"
);
var openComment = TicketComment.Create(openTicket.Id, userId, "открытый тикет");
dbContext.TicketComments.AddRange(closedComment, openComment);
var attachment = TicketAttachment.Create(
closedComment.Id,
"screenshot.png",
"stored-name",
"image/png",
1024
);
dbContext.TicketAttachments.Add(attachment);
await dbContext.SaveChangesAsync(CancellationToken.None);
var currentUser = FakeCurrentUser.Authenticated(Guid.NewGuid(), "admin");
var handler = new DeleteClosedTicketsCommandHandler(dbContext, _fileStorage, currentUser);
var result = await handler.Handle(new DeleteClosedTicketsCommand(), CancellationToken.None);
// Хендлер не коммитит сам (в проде это делает UnitOfWorkBehavior после диспетчера) — коммитим явно.
await dbContext.SaveChangesAsync(CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Equal(1, result.Value);
Assert.False(dbContext.SupportTickets.Any(t => t.Id == closedTicket.Id));
Assert.False(dbContext.TicketComments.Any(c => c.Id == closedComment.Id));
Assert.False(dbContext.TicketAttachments.Any(a => a.Id == attachment.Id));
Assert.True(dbContext.SupportTickets.Any(t => t.Id == openTicket.Id));
Assert.True(dbContext.TicketComments.Any(c => c.Id == openComment.Id));
await _fileStorage.Received(1).DeleteAsync("stored-name", Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_WhenNoClosedTickets_ReturnsZeroAndDeletesNothing()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var openTicket = SupportTicket.CreateBugReport(userId);
dbContext.SupportTickets.Add(openTicket);
await dbContext.SaveChangesAsync(CancellationToken.None);
var currentUser = FakeCurrentUser.Authenticated(Guid.NewGuid(), "admin");
var handler = new DeleteClosedTicketsCommandHandler(dbContext, _fileStorage, currentUser);
var result = await handler.Handle(new DeleteClosedTicketsCommand(), CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Equal(0, result.Value);
Assert.True(dbContext.SupportTickets.Any(t => t.Id == openTicket.Id));
await _fileStorage
.DidNotReceive()
.DeleteAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
}
}