Enhance billing request handling to support immediate config suspension and protection
CI / Backend (build + test) (push) Successful in 1m21s
CI / Frontend (lint + typecheck + build) (push) Successful in 33s

- Updated the `RejectPaymentRequestCommandHandler` to immediately suspend user configs if a payment request is rejected and no other pending subscription requests exist.
- Introduced `SuspendIfStillUnpaidAsync` method to handle the logic for suspending configs based on the user's billing status.
- Enhanced the `MarkPaymentSentCommandHandler` to protect configs during the payment confirmation process, ensuring users remain active while awaiting admin approval.
- Refactored `BillingConfigResumer` to include methods for protecting and suspending configs, improving the overall billing management flow.
- Updated tests to cover new behaviors and ensure proper functionality in various scenarios related to payment requests and config management.
This commit is contained in:
Leonid Pershin
2026-07-19 19:25:33 +03:00
parent 979eddf72e
commit b32756d5bc
8 changed files with 617 additions and 200 deletions
@@ -193,8 +193,9 @@ public class ConfirmPaymentRequestCommandHandlerTests
Assert.NotNull(expiredConfig.ExpiresAt);
Assert.NotNull(activeConfig.ExpiresAt);
Assert.Equal(expiredConfig.ExpiresAt, activeConfig.ExpiresAt);
// enable: null — возврат из приостановки теперь идёт через expiresAt (новый newPaidUntil),
// а не через переключение enable (см. IXuiPanelGateway.UpdateClientAsync).
// enable:true И expiresAt=новый newPaidUntil вместе (см. IXuiPanelGateway.UpdateClientAsync) —
// и для ранее Expired конфига (ext-1), и для уже Active (ext-2): пользователь мог доплатить
// заранее, панель должна узнать новый срок сразу, а не только когда конфиг реально просрочится.
await _gateway
.Received(1)
.UpdateClientAsync(
@@ -203,10 +204,22 @@ public class ConfirmPaymentRequestCommandHandlerTests
"ext-1",
VpnProtocol.Vless,
Arg.Any<string>(),
null,
true,
Arg.Is<DateTimeOffset?>(d => d == expiredConfig.ExpiresAt),
Arg.Any<CancellationToken>()
);
await _gateway
.Received(1)
.UpdateClientAsync(
Arg.Any<Node>(),
inbound.RemoteInboundId,
"ext-2",
VpnProtocol.Vless,
Arg.Any<string>(),
true,
Arg.Is<DateTimeOffset?>(d => d == activeConfig.ExpiresAt),
Arg.Any<CancellationToken>()
);
}
[Fact]
@@ -1,16 +1,54 @@
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()
@@ -23,16 +61,8 @@ public class RejectPaymentRequestCommandHandlerTests
dbContext.PaymentRequests.Add(request);
await dbContext.SaveChangesAsync(CancellationToken.None);
var handler = new RejectPaymentRequestCommandHandler(
dbContext,
_telegramNotifier,
FakeCurrentUser.Authenticated(adminId, "admin")
);
var result = await handler.Handle(
new RejectPaymentRequestCommand(request.Id, "Платёж не найден"),
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);
@@ -52,18 +82,120 @@ public class RejectPaymentRequestCommandHandlerTests
{
using var dbContext = InMemoryDbContextFactory.Create();
var handler = new RejectPaymentRequestCommandHandler(
dbContext,
_telegramNotifier,
FakeCurrentUser.Authenticated(Guid.NewGuid(), "admin")
);
var result = await handler.Handle(
new RejectPaymentRequestCommand(Guid.NewGuid(), null),
CancellationToken.None
);
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);
await _gateway
.Received(1)
.UpdateClientAsync(
Arg.Any<Node>(),
inbound.RemoteInboundId,
"ext-1",
VpnProtocol.Vless,
Arg.Any<string>(),
false,
Arg.Any<DateTimeOffset?>(),
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>()
);
}
}
@@ -1,9 +1,13 @@
using Microsoft.Extensions.Logging;
using NSubstitute;
using PnvPanel.Application.Billing;
using PnvPanel.Application.Billing.MarkPaymentSent;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Common.Models;
using PnvPanel.Application.Tests.TestSupport;
using PnvPanel.Domain.Billing;
using PnvPanel.Domain.Inbounds;
using PnvPanel.Domain.Nodes;
using Xunit;
namespace PnvPanel.Application.Tests.Billing.MarkPaymentSent;
@@ -11,7 +15,30 @@ namespace PnvPanel.Application.Tests.Billing.MarkPaymentSent;
public class MarkPaymentSentCommandHandlerTests
{
private readonly IIdentityService _identityService = Substitute.For<IIdentityService>();
private readonly IXuiPanelGateway _gateway = Substitute.For<IXuiPanelGateway>();
private readonly ITelegramNotifier _telegramNotifier = Substitute.For<ITelegramNotifier>();
private readonly ILogger<MarkPaymentSentCommandHandler> _logger = Substitute.For<
ILogger<MarkPaymentSentCommandHandler>
>();
private MarkPaymentSentCommandHandler CreateHandler(IAppDbContext dbContext, Guid userId) =>
new(dbContext, _identityService, _gateway, _telegramNotifier, FakeCurrentUser.Authenticated(userId, "alice"), _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_WhenAwaitingPayment_MovesToAwaitingConfirmationAndNotifiesAdmins()
@@ -22,17 +49,8 @@ public class MarkPaymentSentCommandHandlerTests
dbContext.PaymentRequests.Add(request);
await dbContext.SaveChangesAsync(CancellationToken.None);
var handler = new MarkPaymentSentCommandHandler(
dbContext,
_identityService,
_telegramNotifier,
FakeCurrentUser.Authenticated(userId, "alice")
);
var result = await handler.Handle(
new MarkPaymentSentCommand(request.Id),
CancellationToken.None
);
var result = await CreateHandler(dbContext, userId)
.Handle(new MarkPaymentSentCommand(request.Id), CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Equal(PaymentRequestStatus.AwaitingConfirmation, request.Status);
@@ -58,19 +76,99 @@ public class MarkPaymentSentCommandHandlerTests
dbContext.PaymentRequests.Add(request);
await dbContext.SaveChangesAsync(CancellationToken.None);
var handler = new MarkPaymentSentCommandHandler(
dbContext,
_identityService,
_telegramNotifier,
FakeCurrentUser.Authenticated(userId)
);
var result = await handler.Handle(
new MarkPaymentSentCommand(request.Id),
CancellationToken.None
);
var result = await CreateHandler(dbContext, userId)
.Handle(new MarkPaymentSentCommand(request.Id), CancellationToken.None);
Assert.False(result.IsSuccess);
Assert.Equal(BillingErrors.RequestNotAwaitingPayment, result.Error);
}
[Fact]
public async Task Handle_WhenPaidUntilAlreadyExpired_ProtectsConfigsOnPanel()
{
using var dbContext = InMemoryDbContextFactory.Create();
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 = Domain.Configs.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);
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, userId)
.Handle(new MarkPaymentSentCommand(request.Id), CancellationToken.None);
Assert.True(result.IsSuccess);
// enable:true + expiresAt в будущем — держим клиента рабочим на панели, пока заявка на проверке.
await _gateway
.Received(1)
.UpdateClientAsync(
Arg.Any<Node>(),
inbound.RemoteInboundId,
"ext-1",
VpnProtocol.Vless,
Arg.Any<string>(),
true,
Arg.Is<DateTimeOffset?>(d => d > DateTimeOffset.UtcNow),
Arg.Any<CancellationToken>()
);
}
[Fact]
public async Task Handle_WhenPaidUntilStillInFuture_DoesNotTouchGateway()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var request = PaymentRequest.Create(userId, PaymentPeriod.Quarter, 1500);
dbContext.PaymentRequests.Add(request);
await dbContext.SaveChangesAsync(CancellationToken.None);
_identityService
.GetProfileAsync(userId, Arg.Any<CancellationToken>())
.Returns(Profile(userId, paidUntil: DateTimeOffset.UtcNow.AddDays(10)));
var result = await CreateHandler(dbContext, userId)
.Handle(new MarkPaymentSentCommand(request.Id), CancellationToken.None);
Assert.True(result.IsSuccess);
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>()
);
}
}