Files
PnvPanel/backend/tests/PnvPanel.Application.Tests/Admin/Billing/RejectPaymentRequestCommandHandlerTests.cs
T
Leonid Pershin 29291b5dec
CI / Backend (build + test) (push) Failing after 1m8s
CI / Frontend (lint + typecheck + build) (push) Successful in 34s
Refactor billing configuration management to centralize expiration handling
- Updated `BillingConfigResumer` to manage billing expiration entirely on the application side, using `enable` as the sole control mechanism for client access.
- Changed all relevant methods to pass `DateTimeOffset.UnixEpoch` for `expiresAt`, ensuring the panel does not enforce expiration independently of our application logic.
- Modified `IXuiPanelGateway` interface to reflect the new expiration handling approach, clarifying the role of `expiresAt` in client management.
- Adjusted command handlers for creating and rotating VPN configurations to set `expiresAt` to `null`, preventing unintended expiration enforcement by the panel.
- Enhanced documentation to explain the new billing expiration management strategy and its implications for client configurations.
2026-07-22 23:43:45 +03:00

206 lines
8.0 KiB
C#

using Microsoft.Extensions.Logging;
using NSubstitute;
using PnvPanel.Application.Admin.Billing;
using PnvPanel.Application.Billing;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Common.Models;
using PnvPanel.Application.Tests.TestSupport;
using PnvPanel.Domain.Billing;
using PnvPanel.Domain.Configs;
using PnvPanel.Domain.Inbounds;
using PnvPanel.Domain.Nodes;
using Xunit;
namespace PnvPanel.Application.Tests.Admin.Billing;
public class RejectPaymentRequestCommandHandlerTests
{
private readonly IIdentityService _identityService = Substitute.For<IIdentityService>();
private readonly IXuiPanelGateway _gateway = Substitute.For<IXuiPanelGateway>();
private readonly IRealtimeNotifier _notifier = Substitute.For<IRealtimeNotifier>();
private readonly ITelegramNotifier _telegramNotifier = Substitute.For<ITelegramNotifier>();
private readonly ILogger<RejectPaymentRequestCommandHandler> _logger = Substitute.For<
ILogger<RejectPaymentRequestCommandHandler>
>();
private RejectPaymentRequestCommandHandler CreateHandler(IAppDbContext dbContext, Guid adminId) =>
new(
dbContext,
_identityService,
_gateway,
_notifier,
_telegramNotifier,
FakeCurrentUser.Authenticated(adminId, "admin"),
_logger
);
private static CurrentUserProfile Profile(Guid userId, DateTimeOffset? paidUntil) =>
new(
userId,
"alice",
Guid.NewGuid(),
"premium",
IsActivated: true,
IsBlocked: false,
MaxConfigs: 5,
MaxIpLimit: 3,
SubscriptionToken: "sub-token",
BillingEnabled: true,
BillingPaidUntil: paidUntil,
BillingSuspended: false
);
[Fact]
public async Task Handle_WhenAwaitingConfirmation_RejectsAndNotifiesUser()
{
using var dbContext = InMemoryDbContextFactory.Create();
var adminId = Guid.NewGuid();
var userId = Guid.NewGuid();
var request = PaymentRequest.Create(userId, PaymentPeriod.Quarter, 1500);
request.MarkPaymentSent();
dbContext.PaymentRequests.Add(request);
await dbContext.SaveChangesAsync(CancellationToken.None);
var result = await CreateHandler(dbContext, adminId)
.Handle(new RejectPaymentRequestCommand(request.Id, "Платёж не найден"), CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Equal(PaymentRequestStatus.Rejected, request.Status);
Assert.Equal("Платёж не найден", request.RejectionReason);
await _telegramNotifier
.Received(1)
.NotifyUserAsync(
userId,
Arg.Is<string>(m => m.Contains("Платёж не найден")),
Arg.Any<string?>(),
Arg.Any<CancellationToken>()
);
}
[Fact]
public async Task Handle_WhenRequestNotFound_ReturnsRequestNotFound()
{
using var dbContext = InMemoryDbContextFactory.Create();
var result = await CreateHandler(dbContext, Guid.NewGuid())
.Handle(new RejectPaymentRequestCommand(Guid.NewGuid(), null), CancellationToken.None);
Assert.False(result.IsSuccess);
Assert.Equal(BillingErrors.RequestNotFound, result.Error);
}
[Fact]
public async Task Handle_WhenStillUnpaidAndNoOtherPendingRequest_SuspendsConfigsImmediately()
{
using var dbContext = InMemoryDbContextFactory.Create();
var adminId = Guid.NewGuid();
var userId = Guid.NewGuid();
var node = Node.Register(
"node-1",
new Uri("https://node1.example.com"),
new NodeCredentials("admin", "protected"),
null
);
var inbound = Inbound.FromRemote(node.Id, "1", VpnProtocol.Vless, "remark", 443);
var config = VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, null);
config.AssignRemoteClient("ext-1");
dbContext.Nodes.Add(node);
dbContext.Inbounds.Add(inbound);
dbContext.VpnConfigs.Add(config);
var request = PaymentRequest.Create(userId, PaymentPeriod.Quarter, 1500);
request.MarkPaymentSent();
dbContext.PaymentRequests.Add(request);
await dbContext.SaveChangesAsync(CancellationToken.None);
_identityService
.GetProfileAsync(userId, Arg.Any<CancellationToken>())
.Returns(Profile(userId, paidUntil: DateTimeOffset.UtcNow.AddDays(-1)));
_gateway
.UpdateClientAsync(
Arg.Any<Node>(),
Arg.Any<string>(),
Arg.Any<string>(),
Arg.Any<VpnProtocol>(),
Arg.Any<string>(),
Arg.Any<bool?>(),
Arg.Any<DateTimeOffset?>(),
Arg.Any<CancellationToken>()
)
.Returns(Result.Success());
var result = await CreateHandler(dbContext, adminId)
.Handle(new RejectPaymentRequestCommand(request.Id, null), CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Equal(ConfigStatus.Expired, config.Status);
// enable:false — истечение управляется полностью на нашей стороне, панельный expiresAt
// сбрасывается в "без срока" (см. BillingConfigResumer.NoExpiry), не реальную просроченную дату.
await _gateway
.Received(1)
.UpdateClientAsync(
Arg.Any<Node>(),
inbound.RemoteInboundId,
"ext-1",
VpnProtocol.Vless,
Arg.Any<string>(),
false,
Arg.Is<DateTimeOffset?>(d => d == DateTimeOffset.UnixEpoch),
Arg.Any<CancellationToken>()
);
// Фронт (/billing) должен узнать о смене статуса сразу, не дожидаясь опроса.
await _notifier.Received(1).NotifyBillingStatusChangedAsync(userId, Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_WhenAnotherSubscriptionRequestStillPending_DoesNotSuspend()
{
using var dbContext = InMemoryDbContextFactory.Create();
var adminId = Guid.NewGuid();
var userId = Guid.NewGuid();
var node = Node.Register(
"node-1",
new Uri("https://node1.example.com"),
new NodeCredentials("admin", "protected"),
null
);
var inbound = Inbound.FromRemote(node.Id, "1", VpnProtocol.Vless, "remark", 443);
var config = VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, null);
config.AssignRemoteClient("ext-1");
dbContext.Nodes.Add(node);
dbContext.Inbounds.Add(inbound);
dbContext.VpnConfigs.Add(config);
var request = PaymentRequest.Create(userId, PaymentPeriod.Quarter, 1500);
request.MarkPaymentSent();
var otherRequest = PaymentRequest.Create(userId, PaymentPeriod.Quarter, 1500);
otherRequest.MarkPaymentSent();
dbContext.PaymentRequests.AddRange(request, otherRequest);
await dbContext.SaveChangesAsync(CancellationToken.None);
_identityService
.GetProfileAsync(userId, Arg.Any<CancellationToken>())
.Returns(Profile(userId, paidUntil: DateTimeOffset.UtcNow.AddDays(-1)));
var result = await CreateHandler(dbContext, adminId)
.Handle(new RejectPaymentRequestCommand(request.Id, null), CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Equal(ConfigStatus.Active, config.Status);
await _gateway
.DidNotReceive()
.UpdateClientAsync(
Arg.Any<Node>(),
Arg.Any<string>(),
Arg.Any<string>(),
Arg.Any<VpnProtocol>(),
Arg.Any<string>(),
Arg.Any<bool?>(),
Arg.Any<DateTimeOffset?>(),
Arg.Any<CancellationToken>()
);
}
}