Refactor client update handling to support nullable parameters for name and expiration
CI / Backend (build + test) (push) Successful in 1m18s
CI / Frontend (lint + typecheck + build) (push) Successful in 59s

- Updated the `UpdateClientAsync` method in `IXuiPanelGateway` to accept nullable parameters for `name` and `expiresAt`, allowing for more flexible client management without unintended modifications.
- Adjusted the `BlockUserCommandHandler`, `UnblockUserCommandHandler`, and other related command handlers to utilize the new nullable parameters, ensuring that client names remain unchanged during block/unblock operations and that expiration dates are managed correctly.
- Enhanced the billing and configuration handling to reflect the new logic for managing client states based on expiration rather than enabling/disabling, improving reliability in client status management.
- Updated tests to cover the new behavior and ensure proper functionality across the application.
This commit is contained in:
Leonid Pershin
2026-07-19 18:58:36 +03:00
parent 5ff5224935
commit 979eddf72e
20 changed files with 282 additions and 29 deletions
@@ -167,7 +167,8 @@ public class ConfirmPaymentRequestCommandHandlerTests
Arg.Any<string>(),
Arg.Any<VpnProtocol>(),
Arg.Any<string>(),
enable: true,
Arg.Any<bool?>(),
Arg.Any<DateTimeOffset?>(),
Arg.Any<CancellationToken>()
)
.Returns(Result.Success());
@@ -192,6 +193,8 @@ public class ConfirmPaymentRequestCommandHandlerTests
Assert.NotNull(expiredConfig.ExpiresAt);
Assert.NotNull(activeConfig.ExpiresAt);
Assert.Equal(expiredConfig.ExpiresAt, activeConfig.ExpiresAt);
// enable: null — возврат из приостановки теперь идёт через expiresAt (новый newPaidUntil),
// а не через переключение enable (см. IXuiPanelGateway.UpdateClientAsync).
await _gateway
.Received(1)
.UpdateClientAsync(
@@ -200,7 +203,8 @@ public class ConfirmPaymentRequestCommandHandlerTests
"ext-1",
VpnProtocol.Vless,
Arg.Any<string>(),
enable: true,
null,
Arg.Is<DateTimeOffset?>(d => d == expiredConfig.ExpiresAt),
Arg.Any<CancellationToken>()
);
}
@@ -128,7 +128,8 @@ public class ApproveExtensionRequestCommandHandlerTests
Arg.Any<string>(),
Arg.Any<VpnProtocol>(),
Arg.Any<string>(),
enable: true,
Arg.Any<bool?>(),
Arg.Any<DateTimeOffset?>(),
Arg.Any<CancellationToken>()
)
.Returns(Result.Success());
@@ -54,7 +54,8 @@ public class BlockUserCommandHandlerTests
Arg.Any<string>(),
Arg.Any<VpnProtocol>(),
Arg.Any<string>(),
Arg.Any<bool>(),
Arg.Any<bool?>(),
Arg.Any<DateTimeOffset?>(),
Arg.Any<CancellationToken>()
);
}
@@ -91,7 +92,8 @@ public class BlockUserCommandHandlerTests
Arg.Any<string>(),
Arg.Any<VpnProtocol>(),
Arg.Any<string>(),
Arg.Any<bool>(),
Arg.Any<bool?>(),
Arg.Any<DateTimeOffset?>(),
Arg.Any<CancellationToken>()
)
.Returns(Result.Success());
@@ -111,6 +113,8 @@ public class BlockUserCommandHandlerTests
Assert.True(result.IsSuccess);
Assert.Equal(ConfigStatus.Disabled, config.Status);
// name: null — блокировка не переименовывает клиента; expiresAt: null — блокировка не трогает
// срок оплаты (см. IXuiPanelGateway.UpdateClientAsync).
await _gateway
.Received(1)
.UpdateClientAsync(
@@ -118,8 +122,9 @@ public class BlockUserCommandHandlerTests
inbound.RemoteInboundId,
config.ClientExternalId,
config.Protocol,
"my-config",
null,
enable: false,
expiresAt: null,
Arg.Any<CancellationToken>()
);
await _notifier
@@ -168,7 +173,8 @@ public class BlockUserCommandHandlerTests
Arg.Any<string>(),
Arg.Any<VpnProtocol>(),
Arg.Any<string>(),
Arg.Any<bool>(),
Arg.Any<bool?>(),
Arg.Any<DateTimeOffset?>(),
Arg.Any<CancellationToken>()
);
}
@@ -205,7 +211,8 @@ public class BlockUserCommandHandlerTests
Arg.Any<string>(),
Arg.Any<VpnProtocol>(),
Arg.Any<string>(),
Arg.Any<bool>(),
Arg.Any<bool?>(),
Arg.Any<DateTimeOffset?>(),
Arg.Any<CancellationToken>()
)
.Returns(Result.Failure(Error.Failure("Xui.UpdateClientFailed", "Нода недоступна.")));
@@ -54,7 +54,8 @@ public class UnblockUserCommandHandlerTests
Arg.Any<string>(),
Arg.Any<VpnProtocol>(),
Arg.Any<string>(),
Arg.Any<bool>(),
Arg.Any<bool?>(),
Arg.Any<DateTimeOffset?>(),
Arg.Any<CancellationToken>()
)
.Returns(Result.Success());
@@ -81,6 +82,7 @@ public class UnblockUserCommandHandlerTests
config.Protocol,
Arg.Any<string>(),
true,
null,
Arg.Any<CancellationToken>()
);
await _notifier
@@ -155,7 +157,8 @@ public class UnblockUserCommandHandlerTests
Arg.Any<string>(),
Arg.Any<VpnProtocol>(),
Arg.Any<string>(),
Arg.Any<bool>(),
Arg.Any<bool?>(),
Arg.Any<DateTimeOffset?>(),
Arg.Any<CancellationToken>()
)
.Returns(Result.Failure(Error.Failure("Xui.UpdateClientFailed", "Нода недоступна.")));
@@ -0,0 +1,128 @@
using NSubstitute;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Common.Models;
using PnvPanel.Application.Configs;
using PnvPanel.Application.Configs.Create;
using PnvPanel.Application.Tests.TestSupport;
using PnvPanel.Domain.Inbounds;
using PnvPanel.Infrastructure.Persistence;
using Xunit;
namespace PnvPanel.Application.Tests.Configs.Create;
/// <summary>
/// Только ветки ДО ReserveQuotaSlotAsync (billing-guard) — дальше хендлер уходит в
/// pg_advisory_xact_lock, который InMemory-провайдер не поддерживает (см. CLAUDE.md/
/// ConfigQuotaTests в IntegrationTests для позитивного пути и гонок).
/// </summary>
public class CreateVpnConfigCommandHandlerTests
{
private readonly IIdentityService _identityService = Substitute.For<IIdentityService>();
private readonly IXuiPanelGateway _gateway = Substitute.For<IXuiPanelGateway>();
private static CurrentUserProfile Profile(
Guid userId,
Guid roleId,
bool billingEnabled,
DateTimeOffset? billingPaidUntil
) =>
new(
userId,
"alice",
roleId,
"premium",
IsActivated: true,
IsBlocked: false,
MaxConfigs: 5,
MaxIpLimit: 3,
SubscriptionToken: "sub-token",
BillingEnabled: billingEnabled,
BillingPaidUntil: billingPaidUntil,
BillingSuspended: false
);
private async Task<(Inbound inbound, Guid roleId)> SeedAllowedInboundAsync(AppDbContext dbContext)
{
var roleId = Guid.NewGuid();
var node = Domain.Nodes.Node.Register(
"node-1",
new Uri("https://node1.example.com"),
new Domain.Nodes.NodeCredentials("admin", "protected"),
null
);
var inbound = Inbound.FromRemote(node.Id, "1", VpnProtocol.Vless, "remark", 443);
inbound.Publish(null, [roleId]);
dbContext.Nodes.Add(node);
dbContext.Inbounds.Add(inbound);
await dbContext.SaveChangesAsync(CancellationToken.None);
return (inbound, roleId);
}
[Fact]
public async Task Handle_WhenBillingEnabledAndPaidUntilExpired_ReturnsBillingRequired()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var (inbound, roleId) = await SeedAllowedInboundAsync(dbContext);
_identityService
.GetProfileAsync(userId, Arg.Any<CancellationToken>())
.Returns(Profile(userId, roleId, billingEnabled: true, billingPaidUntil: DateTimeOffset.UtcNow.AddDays(-1)));
var handler = new CreateVpnConfigCommandHandler(
dbContext,
_identityService,
_gateway,
FakeCurrentUser.Authenticated(userId)
);
var result = await handler.Handle(
new CreateVpnConfigCommand(inbound.Id, null),
CancellationToken.None
);
Assert.False(result.IsSuccess);
Assert.Equal(ConfigErrors.BillingRequired, result.Error);
await _gateway
.DidNotReceive()
.AddClientAsync(
Arg.Any<Domain.Nodes.Node>(),
Arg.Any<string>(),
Arg.Any<VpnProtocol>(),
Arg.Any<string>(),
Arg.Any<string>(),
Arg.Any<int>(),
Arg.Any<DateTimeOffset?>(),
Arg.Any<CancellationToken>()
);
}
[Fact]
public async Task Handle_WhenBillingEnabledAndPaidUntilNull_ReturnsBillingRequired()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var (inbound, roleId) = await SeedAllowedInboundAsync(dbContext);
_identityService
.GetProfileAsync(userId, Arg.Any<CancellationToken>())
.Returns(Profile(userId, roleId, billingEnabled: true, billingPaidUntil: null));
var handler = new CreateVpnConfigCommandHandler(
dbContext,
_identityService,
_gateway,
FakeCurrentUser.Authenticated(userId)
);
var result = await handler.Handle(
new CreateVpnConfigCommand(inbound.Id, null),
CancellationToken.None
);
Assert.False(result.IsSuccess);
Assert.Equal(ConfigErrors.BillingRequired, result.Error);
}
}
@@ -65,6 +65,7 @@ public class RotateVpnConfigCommandHandlerTests
Arg.Any<string>(),
Arg.Any<string>(),
Arg.Any<int>(),
Arg.Any<DateTimeOffset?>(),
Arg.Any<CancellationToken>()
)
.Returns(Result.Success("new-external-id"));
@@ -209,6 +210,7 @@ public class RotateVpnConfigCommandHandlerTests
Arg.Any<string>(),
Arg.Any<string>(),
Arg.Any<int>(),
Arg.Any<DateTimeOffset?>(),
Arg.Any<CancellationToken>()
)
.Returns(Result.Failure<string>(gatewayError));