Enhance admin maintenance functionality with new endpoints and response types
- Added new DELETE endpoints for managing audit logs and disabled apps in the admin maintenance section. - Updated existing endpoint for closed tickets to use a unified response type, `MaintenanceCleanupResponseDto`. - Enhanced API documentation to reflect the new operations and their expected request/response formats. - Improved frontend integration with new functions for deleting old audit logs and disabled apps, including user confirmation prompts. - Added localization support for new maintenance actions in both Russian and English.
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
using PnvPanel.Api.Common;
|
||||
using PnvPanel.Application.Admin.Maintenance;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
using PnvPanel.Infrastructure.Identity;
|
||||
|
||||
namespace PnvPanel.Api.Endpoints;
|
||||
@@ -15,7 +16,13 @@ public static class AdminMaintenanceEndpoints
|
||||
|
||||
admin
|
||||
.MapDelete("/tickets/closed", DeleteClosedTickets)
|
||||
.Produces<DeleteClosedTicketsResponseDto>();
|
||||
.Produces<MaintenanceCleanupResponseDto>();
|
||||
admin
|
||||
.MapDelete("/audit-logs", DeleteOldAuditLogs)
|
||||
.Produces<MaintenanceCleanupResponseDto>();
|
||||
admin
|
||||
.MapDelete("/apps/disabled", DeleteDisabledApps)
|
||||
.Produces<MaintenanceCleanupResponseDto>();
|
||||
|
||||
return app;
|
||||
}
|
||||
@@ -26,11 +33,35 @@ public static class AdminMaintenanceEndpoints
|
||||
)
|
||||
{
|
||||
var result = await sender.Send(new DeleteClosedTicketsCommand(), cancellationToken);
|
||||
if (!result.IsSuccess)
|
||||
return result.ToHttpResult();
|
||||
|
||||
return Results.Ok(new DeleteClosedTicketsResponseDto(result.Value));
|
||||
return ToResponse(result);
|
||||
}
|
||||
|
||||
private static async Task<IResult> DeleteOldAuditLogs(
|
||||
int olderThanDays,
|
||||
ISender sender,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
var result = await sender.Send(
|
||||
new DeleteOldAuditLogsCommand(olderThanDays),
|
||||
cancellationToken
|
||||
);
|
||||
return ToResponse(result);
|
||||
}
|
||||
|
||||
private static async Task<IResult> DeleteDisabledApps(
|
||||
ISender sender,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
var result = await sender.Send(new DeleteDisabledAppsCommand(), cancellationToken);
|
||||
return ToResponse(result);
|
||||
}
|
||||
|
||||
private static IResult ToResponse(Result<int> result) =>
|
||||
result.IsSuccess
|
||||
? Results.Ok(new MaintenanceCleanupResponseDto(result.Value))
|
||||
: result.ToHttpResult();
|
||||
}
|
||||
|
||||
public sealed record DeleteClosedTicketsResponseDto(int DeletedCount);
|
||||
public sealed record MaintenanceCleanupResponseDto(int DeletedCount);
|
||||
|
||||
+1
-1
@@ -59,7 +59,7 @@ public sealed class DeleteClosedTicketsCommandHandler(
|
||||
"ClosedTicketsCleanedUp",
|
||||
"SupportTicket",
|
||||
"bulk",
|
||||
metadata: $"count={ticketIds.Count}",
|
||||
metadata: $"{{\"count\":{ticketIds.Count}}}",
|
||||
AuditSource.Web
|
||||
)
|
||||
);
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Maintenance;
|
||||
|
||||
/// <summary>Удаляет все ClientApp с IsEnabled = false. Value — число удалённых записей.</summary>
|
||||
public sealed record DeleteDisabledAppsCommand : ICommand<Result<int>>;
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
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;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Maintenance;
|
||||
|
||||
public sealed class DeleteDisabledAppsCommandHandler(
|
||||
IAppDbContext dbContext,
|
||||
ICurrentUser currentUser
|
||||
) : ICommandHandler<DeleteDisabledAppsCommand, Result<int>>
|
||||
{
|
||||
public async Task<Result<int>> Handle(
|
||||
DeleteDisabledAppsCommand command,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
if (currentUser.UserId is not { } adminId)
|
||||
return Result.Failure<int>(AuthErrors.Unauthorized);
|
||||
|
||||
var apps = await dbContext
|
||||
.ClientApps.Where(a => !a.IsEnabled)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
if (apps.Count == 0)
|
||||
return Result.Success(0);
|
||||
|
||||
dbContext.ClientApps.RemoveRange(apps);
|
||||
|
||||
dbContext.AuditLogs.Add(
|
||||
AuditLog.Create(
|
||||
adminId,
|
||||
"DisabledAppsCleanedUp",
|
||||
"ClientApp",
|
||||
"bulk",
|
||||
metadata: $"{{\"count\":{apps.Count}}}",
|
||||
AuditSource.Web
|
||||
)
|
||||
);
|
||||
|
||||
return Result.Success(apps.Count);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Maintenance;
|
||||
|
||||
/// <summary>Удаляет записи AuditLog старше OlderThanDays дней. Value — число удалённых записей.</summary>
|
||||
public sealed record DeleteOldAuditLogsCommand(int OlderThanDays) : ICommand<Result<int>>;
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
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;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Maintenance;
|
||||
|
||||
public sealed class DeleteOldAuditLogsCommandHandler(
|
||||
IAppDbContext dbContext,
|
||||
ICurrentUser currentUser
|
||||
) : ICommandHandler<DeleteOldAuditLogsCommand, Result<int>>
|
||||
{
|
||||
public async Task<Result<int>> Handle(
|
||||
DeleteOldAuditLogsCommand command,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
if (currentUser.UserId is not { } adminId)
|
||||
return Result.Failure<int>(AuthErrors.Unauthorized);
|
||||
|
||||
var threshold = DateTimeOffset.UtcNow.AddDays(-command.OlderThanDays);
|
||||
|
||||
var logs = await dbContext
|
||||
.AuditLogs.Where(l => l.CreatedAt < threshold)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
if (logs.Count == 0)
|
||||
return Result.Success(0);
|
||||
|
||||
dbContext.AuditLogs.RemoveRange(logs);
|
||||
|
||||
// Новая запись создаётся уже после выборки старых — её CreatedAt = UtcNow не попадает
|
||||
// под тот же порог и не удаляется этой же операцией.
|
||||
dbContext.AuditLogs.Add(
|
||||
AuditLog.Create(
|
||||
adminId,
|
||||
"AuditLogsCleanedUp",
|
||||
"AuditLog",
|
||||
"bulk",
|
||||
metadata: $"{{\"count\":{logs.Count},\"olderThanDays\":{command.OlderThanDays}}}",
|
||||
AuditSource.Web
|
||||
)
|
||||
);
|
||||
|
||||
return Result.Success(logs.Count);
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Maintenance;
|
||||
|
||||
public sealed class DeleteOldAuditLogsCommandValidator
|
||||
: AbstractValidator<DeleteOldAuditLogsCommand>
|
||||
{
|
||||
public DeleteOldAuditLogsCommandValidator()
|
||||
{
|
||||
RuleFor(x => x.OlderThanDays).GreaterThanOrEqualTo(1).LessThanOrEqualTo(3650);
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
using PnvPanel.Application.Admin.Maintenance;
|
||||
using PnvPanel.Application.Tests.TestSupport;
|
||||
using PnvPanel.Domain.Apps;
|
||||
using Xunit;
|
||||
|
||||
namespace PnvPanel.Application.Tests.Admin.Maintenance;
|
||||
|
||||
public class DeleteDisabledAppsCommandHandlerTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Handle_DeletesDisabledApps_KeepsEnabled()
|
||||
{
|
||||
using var dbContext = InMemoryDbContextFactory.Create();
|
||||
|
||||
var disabledApp = ClientApp.Create(
|
||||
"Old Client",
|
||||
new Uri("https://example.com/old"),
|
||||
OsPlatform.Android,
|
||||
null,
|
||||
null,
|
||||
0
|
||||
);
|
||||
disabledApp.Update(
|
||||
disabledApp.Name,
|
||||
disabledApp.DownloadUrl,
|
||||
disabledApp.OperatingSystem,
|
||||
null,
|
||||
null,
|
||||
0,
|
||||
isEnabled: false
|
||||
);
|
||||
|
||||
var enabledApp = ClientApp.Create(
|
||||
"Active Client",
|
||||
new Uri("https://example.com/active"),
|
||||
OsPlatform.IOS,
|
||||
null,
|
||||
null,
|
||||
0
|
||||
);
|
||||
|
||||
dbContext.ClientApps.AddRange(disabledApp, enabledApp);
|
||||
await dbContext.SaveChangesAsync(CancellationToken.None);
|
||||
|
||||
var currentUser = FakeCurrentUser.Authenticated(Guid.NewGuid(), "admin");
|
||||
var handler = new DeleteDisabledAppsCommandHandler(dbContext, currentUser);
|
||||
|
||||
var result = await handler.Handle(new DeleteDisabledAppsCommand(), CancellationToken.None);
|
||||
// Хендлер не коммитит сам (в проде это делает UnitOfWorkBehavior после диспетчера) — коммитим явно.
|
||||
await dbContext.SaveChangesAsync(CancellationToken.None);
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(1, result.Value);
|
||||
Assert.False(dbContext.ClientApps.Any(a => a.Id == disabledApp.Id));
|
||||
Assert.True(dbContext.ClientApps.Any(a => a.Id == enabledApp.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenNoDisabledApps_ReturnsZero()
|
||||
{
|
||||
using var dbContext = InMemoryDbContextFactory.Create();
|
||||
var enabledApp = ClientApp.Create(
|
||||
"Active Client",
|
||||
new Uri("https://example.com/active"),
|
||||
OsPlatform.IOS,
|
||||
null,
|
||||
null,
|
||||
0
|
||||
);
|
||||
dbContext.ClientApps.Add(enabledApp);
|
||||
await dbContext.SaveChangesAsync(CancellationToken.None);
|
||||
|
||||
var currentUser = FakeCurrentUser.Authenticated(Guid.NewGuid(), "admin");
|
||||
var handler = new DeleteDisabledAppsCommandHandler(dbContext, currentUser);
|
||||
|
||||
var result = await handler.Handle(new DeleteDisabledAppsCommand(), CancellationToken.None);
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(0, result.Value);
|
||||
Assert.True(dbContext.ClientApps.Any(a => a.Id == enabledApp.Id));
|
||||
}
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
using PnvPanel.Application.Admin.Maintenance;
|
||||
using PnvPanel.Application.Tests.TestSupport;
|
||||
using PnvPanel.Domain.Audit;
|
||||
using Xunit;
|
||||
|
||||
namespace PnvPanel.Application.Tests.Admin.Maintenance;
|
||||
|
||||
public class DeleteOldAuditLogsCommandHandlerTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Handle_DeletesOldLogs_KeepsItsOwnCleanupEntry()
|
||||
{
|
||||
using var dbContext = InMemoryDbContextFactory.Create();
|
||||
var oldLog = AuditLog.Create(
|
||||
Guid.NewGuid(),
|
||||
"OldAction",
|
||||
"Test",
|
||||
"1",
|
||||
null,
|
||||
AuditSource.Web
|
||||
);
|
||||
dbContext.AuditLogs.Add(oldLog);
|
||||
await dbContext.SaveChangesAsync(CancellationToken.None);
|
||||
|
||||
// Гарантируем, что порог (UtcNow внутри хендлера) окажется позже CreatedAt старой записи.
|
||||
await Task.Delay(5, CancellationToken.None);
|
||||
|
||||
var currentUser = FakeCurrentUser.Authenticated(Guid.NewGuid(), "admin");
|
||||
var handler = new DeleteOldAuditLogsCommandHandler(dbContext, currentUser);
|
||||
|
||||
var result = await handler.Handle(
|
||||
new DeleteOldAuditLogsCommand(OlderThanDays: 0),
|
||||
CancellationToken.None
|
||||
);
|
||||
// Хендлер не коммитит сам (в проде это делает UnitOfWorkBehavior после диспетчера) — коммитим явно.
|
||||
await dbContext.SaveChangesAsync(CancellationToken.None);
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(1, result.Value);
|
||||
Assert.False(dbContext.AuditLogs.Any(l => l.Id == oldLog.Id));
|
||||
// Собственная запись об очистке создаётся уже после выборки порога и не попадает под удаление.
|
||||
Assert.True(dbContext.AuditLogs.Any(l => l.Action == "AuditLogsCleanedUp"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenNothingOlderThanThreshold_ReturnsZero()
|
||||
{
|
||||
using var dbContext = InMemoryDbContextFactory.Create();
|
||||
var recentLog = AuditLog.Create(
|
||||
Guid.NewGuid(),
|
||||
"RecentAction",
|
||||
"Test",
|
||||
"1",
|
||||
null,
|
||||
AuditSource.Web
|
||||
);
|
||||
dbContext.AuditLogs.Add(recentLog);
|
||||
await dbContext.SaveChangesAsync(CancellationToken.None);
|
||||
|
||||
var currentUser = FakeCurrentUser.Authenticated(Guid.NewGuid(), "admin");
|
||||
var handler = new DeleteOldAuditLogsCommandHandler(dbContext, currentUser);
|
||||
|
||||
var result = await handler.Handle(
|
||||
new DeleteOldAuditLogsCommand(OlderThanDays: 36500),
|
||||
CancellationToken.None
|
||||
);
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(0, result.Value);
|
||||
Assert.True(dbContext.AuditLogs.Any(l => l.Id == recentLog.Id));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user