Files
PnvPanel/backend/tests/PnvPanel.Application.Tests/Billing/MarkPaymentSent/MarkPaymentSentCommandHandlerTests.cs
T
Leonid Pershin fad03c2834
CI / Backend (build + test) (push) Failing after 1m23s
CI / Frontend (lint + typecheck + build) (push) Successful in 34s
Enhance user plan management and update related endpoints
- Added new configuration options for user plans in `.env.example`, including `Plans__MaxCustomConfigCount` and `Plans__MinCustomConfigCount`.
- Introduced `MapPlanEndpoints` in `Program.cs` to handle plan-related API routes.
- Implemented `SetUserPlan` endpoint in `RoleEndpoints` to allow admins to assign plans to users.
- Removed deprecated role request approval endpoints from `AdminSupportEndpoints`.
- Updated `ITelegramNotifier` and related classes to reflect changes in role request handling and payment notifications.
- Refactored role management commands to remove `MaxConfigs` and focus on `MaxIpLimit` and billing settings.
- Enhanced billing request handling to accommodate plan changes instead of role changes.
- Updated various interfaces and command handlers to support new plan management features.
2026-07-23 22:52:20 +03:00

179 lines
7.0 KiB
C#

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;
public class MarkPaymentSentCommandHandlerTests
{
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<MarkPaymentSentCommandHandler> _logger = Substitute.For<
ILogger<MarkPaymentSentCommandHandler>
>();
private MarkPaymentSentCommandHandler CreateHandler(IAppDbContext dbContext, Guid userId) =>
new(dbContext, _identityService, _gateway, _notifier, _telegramNotifier, FakeCurrentUser.Authenticated(userId, "alice"), _logger);
private static CurrentUserProfile Profile(Guid userId, DateTimeOffset? paidUntil) =>
new(
userId,
"alice",
Guid.NewGuid(),
"premium",
IsActivated: true,
IsBlocked: false,
ConfigQuota: 5,
PlanId: null,
MaxIpLimit: 3,
SubscriptionToken: "sub-token",
BillingEnabled: true,
BillingPaidUntil: paidUntil,
BillingSuspended: false
);
[Fact]
public async Task Handle_WhenAwaitingPayment_MovesToAwaitingConfirmationAndNotifiesAdmins()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var request = PaymentRequest.Create(userId, PaymentPeriod.Year, 6000);
dbContext.PaymentRequests.Add(request);
await dbContext.SaveChangesAsync(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);
await _telegramNotifier
.Received(1)
.NotifyAdminsPaymentRequestedAsync(
request.Id,
Arg.Any<string>(),
PaymentRequestKind.Subscription,
PaymentPeriod.Year,
6000,
Arg.Any<CancellationToken>()
);
}
[Fact]
public async Task Handle_WhenAlreadyAwaitingConfirmation_ReturnsNotAwaitingPayment()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var request = PaymentRequest.Create(userId, PaymentPeriod.Year, 6000);
request.MarkPaymentSent();
dbContext.PaymentRequests.Add(request);
await dbContext.SaveChangesAsync(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 всегда
// сбрасывается в "без срока" (см. BillingConfigResumer.NoExpiry), истечение — только локально.
await _gateway
.Received(1)
.UpdateClientAsync(
Arg.Any<Node>(),
inbound.RemoteInboundId,
"ext-1",
VpnProtocol.Vless,
Arg.Any<string>(),
true,
Arg.Is<DateTimeOffset?>(d => d == DateTimeOffset.UnixEpoch),
Arg.Any<CancellationToken>()
);
await _notifier.Received(1).NotifyBillingStatusChangedAsync(userId, 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>()
);
}
}