using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using PnvPanel.Application.Common.Interfaces; using PnvPanel.Application.Common.Messaging; using PnvPanel.Application.Common.Models; using PnvPanel.Domain.Audit; using PnvPanel.Domain.Configs; namespace PnvPanel.Application.Admin.Users; /// Блокировка гасит все активные конфиги в 3x-ui (см. architecture.md). public sealed class BlockUserCommandHandler( IAppDbContext dbContext, IIdentityService identityService, IXuiPanelGateway gateway, IRealtimeNotifier notifier, ITelegramNotifier telegramNotifier, ICurrentUser currentUser, ILogger logger ) : ICommandHandler { public async Task Handle(BlockUserCommand command, CancellationToken cancellationToken) { var blockResult = await identityService.BlockUserAsync(command.UserId, cancellationToken); if (!blockResult.IsSuccess) return blockResult; var configs = await dbContext .VpnConfigs.Where(c => c.UserId == command.UserId && c.Status == ConfigStatus.Active) .ToListAsync(cancellationToken); foreach (var config in configs) { var inbound = await dbContext .Inbounds.AsNoTracking() .FirstOrDefaultAsync(i => i.Id == config.InboundId, cancellationToken); var node = inbound is null ? null : await dbContext .Nodes.AsNoTracking() .FirstOrDefaultAsync(n => n.Id == inbound.NodeId, cancellationToken); if (inbound is not null && node is not null) { // name: null — не трогаем текущее имя клиента в панели, это не переименование. // expiresAt: null — блокировка админом отдельная ось от биллинга (см. // IXuiPanelGateway.UpdateClientAsync), срок оплаты не трогаем. var updateResult = await gateway.UpdateClientAsync( node, inbound.RemoteInboundId, config.ClientExternalId, config.Protocol, name: null, enable: false, expiresAt: null, cancellationToken ); if (!updateResult.IsSuccess) { // Нода недоступна/сбой панели — не помечаем Disabled локально, иначе БД разойдётся // с реальным состоянием клиента в 3x-ui (пользователь решит, что VPN погашен, а он жив). // Конфиг останется Active и будет подхвачен повторным BlockUserCommand (идемпотентен). logger.LogWarning( "Failed to disable client for config {ConfigId} on node {NodeId} while blocking user {UserId}: {Error}", config.Id, node.Id, command.UserId, updateResult.Error ); continue; } } config.Disable(); await notifier.NotifyConfigStatusChangedAsync( config.UserId, config.Id, config.Status, cancellationToken ); } dbContext.AuditLogs.Add( AuditLog.Create( currentUser.UserId, "UserBlocked", "User", command.UserId.ToString(), metadata: null, AuditSource.Web ) ); await telegramNotifier.NotifyUserAsync( command.UserId, "⛔ Ваш аккаунт заблокирован администратором.", null, cancellationToken ); return Result.Success(); } }