Implement billing functionality and enhance role management
- Introduced billing capabilities, allowing users to request payments for subscription periods (3/6/12 months) with admin approval via Telegram. - Updated role management to include a `BillingEnabled` property, preventing billing for admin roles. - Enhanced the `CreateRoleCommand` and `UpdateRoleCommand` to accept billing parameters, ensuring proper handling during role creation and updates. - Added new endpoints for billing management and integrated billing checks into VPN config creation to enforce payment requirements. - Updated related services, models, and tests to support the new billing features, ensuring comprehensive coverage and functionality. - Enhanced documentation to reflect the new billing processes and role management changes.
This commit is contained in:
+237
@@ -0,0 +1,237 @@
|
||||
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 ConfirmPaymentRequestCommandHandlerTests
|
||||
{
|
||||
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<ConfirmPaymentRequestCommandHandler> _logger = Substitute.For<
|
||||
ILogger<ConfirmPaymentRequestCommandHandler>
|
||||
>();
|
||||
|
||||
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: paidUntil is null
|
||||
);
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenNoPriorPayment_ExtendsFromNow()
|
||||
{
|
||||
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);
|
||||
|
||||
_identityService
|
||||
.GetProfileAsync(userId, Arg.Any<CancellationToken>())
|
||||
.Returns(Profile(userId, paidUntil: null));
|
||||
_identityService
|
||||
.ExtendBillingPaidUntilAsync(userId, Arg.Any<DateTimeOffset>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Success());
|
||||
|
||||
var handler = new ConfirmPaymentRequestCommandHandler(
|
||||
dbContext,
|
||||
_identityService,
|
||||
_gateway,
|
||||
_notifier,
|
||||
_telegramNotifier,
|
||||
FakeCurrentUser.Authenticated(adminId, "admin"),
|
||||
_logger
|
||||
);
|
||||
|
||||
var before = DateTimeOffset.UtcNow;
|
||||
var result = await handler.Handle(
|
||||
new ConfirmPaymentRequestCommand(request.Id),
|
||||
CancellationToken.None
|
||||
);
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(PaymentRequestStatus.Confirmed, request.Status);
|
||||
await _identityService
|
||||
.Received(1)
|
||||
.ExtendBillingPaidUntilAsync(
|
||||
userId,
|
||||
Arg.Is<DateTimeOffset>(d => d >= before.AddMonths(3).AddMinutes(-1)),
|
||||
Arg.Any<CancellationToken>()
|
||||
);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenPaidUntilInFuture_ExtendsFromExistingPaidUntil()
|
||||
{
|
||||
using var dbContext = InMemoryDbContextFactory.Create();
|
||||
var adminId = Guid.NewGuid();
|
||||
var userId = Guid.NewGuid();
|
||||
var existingPaidUntil = DateTimeOffset.UtcNow.AddDays(20);
|
||||
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: existingPaidUntil));
|
||||
_identityService
|
||||
.ExtendBillingPaidUntilAsync(userId, Arg.Any<DateTimeOffset>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Success());
|
||||
|
||||
var handler = new ConfirmPaymentRequestCommandHandler(
|
||||
dbContext,
|
||||
_identityService,
|
||||
_gateway,
|
||||
_notifier,
|
||||
_telegramNotifier,
|
||||
FakeCurrentUser.Authenticated(adminId, "admin"),
|
||||
_logger
|
||||
);
|
||||
|
||||
await handler.Handle(new ConfirmPaymentRequestCommand(request.Id), CancellationToken.None);
|
||||
|
||||
var expected = existingPaidUntil.AddMonths(3);
|
||||
await _identityService
|
||||
.Received(1)
|
||||
.ExtendBillingPaidUntilAsync(
|
||||
userId,
|
||||
Arg.Is<DateTimeOffset>(d => Math.Abs((d - expected).TotalSeconds) < 5),
|
||||
Arg.Any<CancellationToken>()
|
||||
);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_ResumesExpiredConfigsAndSyncsExpiry()
|
||||
{
|
||||
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 expiredConfig = VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, null);
|
||||
expiredConfig.AssignRemoteClient("ext-1");
|
||||
expiredConfig.Suspend();
|
||||
var activeConfig = VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, null);
|
||||
activeConfig.AssignRemoteClient("ext-2");
|
||||
|
||||
dbContext.Nodes.Add(node);
|
||||
dbContext.Inbounds.Add(inbound);
|
||||
dbContext.VpnConfigs.AddRange(expiredConfig, activeConfig);
|
||||
|
||||
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: null));
|
||||
_identityService
|
||||
.ExtendBillingPaidUntilAsync(userId, Arg.Any<DateTimeOffset>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Success());
|
||||
_gateway
|
||||
.UpdateClientAsync(
|
||||
Arg.Any<Node>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<VpnProtocol>(),
|
||||
Arg.Any<string>(),
|
||||
enable: true,
|
||||
Arg.Any<CancellationToken>()
|
||||
)
|
||||
.Returns(Result.Success());
|
||||
|
||||
var handler = new ConfirmPaymentRequestCommandHandler(
|
||||
dbContext,
|
||||
_identityService,
|
||||
_gateway,
|
||||
_notifier,
|
||||
_telegramNotifier,
|
||||
FakeCurrentUser.Authenticated(adminId, "admin"),
|
||||
_logger
|
||||
);
|
||||
|
||||
var result = await handler.Handle(
|
||||
new ConfirmPaymentRequestCommand(request.Id),
|
||||
CancellationToken.None
|
||||
);
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(ConfigStatus.Active, expiredConfig.Status);
|
||||
Assert.NotNull(expiredConfig.ExpiresAt);
|
||||
Assert.NotNull(activeConfig.ExpiresAt);
|
||||
Assert.Equal(expiredConfig.ExpiresAt, activeConfig.ExpiresAt);
|
||||
await _gateway
|
||||
.Received(1)
|
||||
.UpdateClientAsync(
|
||||
Arg.Any<Node>(),
|
||||
inbound.RemoteInboundId,
|
||||
"ext-1",
|
||||
VpnProtocol.Vless,
|
||||
Arg.Any<string>(),
|
||||
enable: true,
|
||||
Arg.Any<CancellationToken>()
|
||||
);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenRequestAlreadyDecided_ReturnsNotDecidable()
|
||||
{
|
||||
using var dbContext = InMemoryDbContextFactory.Create();
|
||||
var adminId = Guid.NewGuid();
|
||||
var userId = Guid.NewGuid();
|
||||
var request = PaymentRequest.Create(userId, PaymentPeriod.Quarter, 1500);
|
||||
request.Cancel();
|
||||
dbContext.PaymentRequests.Add(request);
|
||||
await dbContext.SaveChangesAsync(CancellationToken.None);
|
||||
|
||||
var handler = new ConfirmPaymentRequestCommandHandler(
|
||||
dbContext,
|
||||
_identityService,
|
||||
_gateway,
|
||||
_notifier,
|
||||
_telegramNotifier,
|
||||
FakeCurrentUser.Authenticated(adminId, "admin"),
|
||||
_logger
|
||||
);
|
||||
|
||||
var result = await handler.Handle(
|
||||
new ConfirmPaymentRequestCommand(request.Id),
|
||||
CancellationToken.None
|
||||
);
|
||||
|
||||
Assert.False(result.IsSuccess);
|
||||
Assert.Equal(BillingErrors.RequestNotDecidable, result.Error);
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
using NSubstitute;
|
||||
using PnvPanel.Application.Admin.Billing;
|
||||
using PnvPanel.Application.Billing;
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Tests.TestSupport;
|
||||
using PnvPanel.Domain.Billing;
|
||||
using Xunit;
|
||||
|
||||
namespace PnvPanel.Application.Tests.Admin.Billing;
|
||||
|
||||
public class RejectPaymentRequestCommandHandlerTests
|
||||
{
|
||||
private readonly ITelegramNotifier _telegramNotifier = Substitute.For<ITelegramNotifier>();
|
||||
|
||||
[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 handler = new RejectPaymentRequestCommandHandler(
|
||||
dbContext,
|
||||
_telegramNotifier,
|
||||
FakeCurrentUser.Authenticated(adminId, "admin")
|
||||
);
|
||||
|
||||
var result = await handler.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 handler = new RejectPaymentRequestCommandHandler(
|
||||
dbContext,
|
||||
_telegramNotifier,
|
||||
FakeCurrentUser.Authenticated(Guid.NewGuid(), "admin")
|
||||
);
|
||||
|
||||
var result = await handler.Handle(
|
||||
new RejectPaymentRequestCommand(Guid.NewGuid(), null),
|
||||
CancellationToken.None
|
||||
);
|
||||
|
||||
Assert.False(result.IsSuccess);
|
||||
Assert.Equal(BillingErrors.RequestNotFound, result.Error);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user