Enhance user plan management and update related endpoints
CI / Backend (build + test) (push) Failing after 1m23s
CI / Frontend (lint + typecheck + build) (push) Successful in 34s

- 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.
This commit is contained in:
Leonid Pershin
2026-07-23 22:52:20 +03:00
parent 2c5b730500
commit fad03c2834
152 changed files with 4060 additions and 2240 deletions
@@ -31,7 +31,8 @@ public class ConfirmPaymentRequestCommandHandlerTests
"premium",
IsActivated: true,
IsBlocked: false,
MaxConfigs: 5,
ConfigQuota: 5,
PlanId: null,
MaxIpLimit: 3,
SubscriptionToken: "sub-token",
BillingEnabled: true,
@@ -225,13 +226,13 @@ public class ConfirmPaymentRequestCommandHandlerTests
}
[Fact]
public async Task Handle_WhenRoleChangeTopUp_ConfirmsWithoutExtendingPaidUntil()
public async Task Handle_WhenPlanChangeTopUp_ConfirmsWithoutExtendingPaidUntil()
{
using var dbContext = InMemoryDbContextFactory.Create();
var adminId = Guid.NewGuid();
var userId = Guid.NewGuid();
var existingPaidUntil = DateTimeOffset.UtcNow.AddDays(20);
var request = PaymentRequest.CreateRoleChangeTopUp(userId, 1200);
var request = PaymentRequest.CreatePlanChangeTopUp(userId, 1200);
request.MarkPaymentSent();
dbContext.PaymentRequests.Add(request);
await dbContext.SaveChangesAsync(CancellationToken.None);
@@ -28,7 +28,8 @@ public class GrantBillingGiftCommandHandlerTests
"premium",
IsActivated: true,
IsBlocked: false,
MaxConfigs: 5,
ConfigQuota: 5,
PlanId: null,
MaxIpLimit: 3,
SubscriptionToken: "sub-token",
BillingEnabled: billingEnabled,
@@ -17,7 +17,7 @@ public class ListPaymentRequestsQueryHandlerTests
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var subscription = PaymentRequest.Create(userId, PaymentPeriod.Quarter, 1500);
var topUp = PaymentRequest.CreateRoleChangeTopUp(userId, 500);
var topUp = PaymentRequest.CreatePlanChangeTopUp(userId, 500);
dbContext.PaymentRequests.AddRange(subscription, topUp);
await dbContext.SaveChangesAsync(CancellationToken.None);
@@ -30,7 +30,7 @@ public class ListPaymentRequestsQueryHandlerTests
var result = await handler.Handle(
new ListPaymentRequestsQuery(
StatusFilter: null,
KindFilter: PaymentRequestKind.RoleChangeTopUp,
KindFilter: PaymentRequestKind.PlanChangeTopUp,
Search: null,
Page: 1,
PageSize: 20
@@ -42,7 +42,8 @@ public class RejectPaymentRequestCommandHandlerTests
"premium",
IsActivated: true,
IsBlocked: false,
MaxConfigs: 5,
ConfigQuota: 5,
PlanId: null,
MaxIpLimit: 3,
SubscriptionToken: "sub-token",
BillingEnabled: true,
@@ -72,8 +72,8 @@ public class FactoryResetCommandHandlerTests
.Returns(
new List<RoleDto>
{
new(adminRoleId, "admin", -1, -1, IsSystem: true, BillingEnabled: false),
new(customRoleId, "premium", 10, 5, IsSystem: false, BillingEnabled: false),
new(adminRoleId, "admin", -1, IsSystem: true, BillingEnabled: false),
new(customRoleId, "premium", 5, IsSystem: false, BillingEnabled: false),
}
);
_roleService
@@ -0,0 +1,129 @@
using PnvPanel.Application.Admin.Plans;
using PnvPanel.Application.Tests.TestSupport;
using PnvPanel.Domain.Plans;
using Xunit;
namespace PnvPanel.Application.Tests.Admin.Plans;
public class PlanCommandHandlerTests
{
[Fact]
public async Task Create_AddsPlan()
{
using var dbContext = InMemoryDbContextFactory.Create();
var handler = new CreatePlanCommandHandler(dbContext);
var result = await handler.Handle(
new CreatePlanCommand("Стандарт", 3, 0),
CancellationToken.None
);
await dbContext.SaveChangesAsync(CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Equal("Стандарт", result.Value.Name);
Assert.Equal(3, result.Value.ConfigCount);
Assert.True(result.Value.IsEnabled);
Assert.NotNull(await dbContext.Plans.FindAsync([result.Value.Id], CancellationToken.None));
}
[Fact]
public async Task Update_WhenNotFound_ReturnsNotFound()
{
using var dbContext = InMemoryDbContextFactory.Create();
var handler = new UpdatePlanCommandHandler(dbContext);
var result = await handler.Handle(
new UpdatePlanCommand(Guid.NewGuid(), "Плюс", 6, 1, true),
CancellationToken.None
);
Assert.False(result.IsSuccess);
Assert.Equal(PnvPanel.Application.Plans.PlanErrors.NotFound, result.Error);
}
[Fact]
public async Task Update_WhenFound_UpdatesFields()
{
using var dbContext = InMemoryDbContextFactory.Create();
var plan = Plan.Create("Стандарт", 3, 0);
dbContext.Plans.Add(plan);
await dbContext.SaveChangesAsync(CancellationToken.None);
var handler = new UpdatePlanCommandHandler(dbContext);
var result = await handler.Handle(
new UpdatePlanCommand(plan.Id, "Плюс", 6, 1, false),
CancellationToken.None
);
Assert.True(result.IsSuccess);
Assert.Equal("Плюс", result.Value.Name);
Assert.Equal(6, result.Value.ConfigCount);
Assert.False(result.Value.IsEnabled);
}
[Fact]
public async Task Delete_WhenNotFound_ReturnsNotFound()
{
using var dbContext = InMemoryDbContextFactory.Create();
var handler = new DeletePlanCommandHandler(dbContext);
var result = await handler.Handle(
new DeletePlanCommand(Guid.NewGuid()),
CancellationToken.None
);
Assert.False(result.IsSuccess);
Assert.Equal(PnvPanel.Application.Plans.PlanErrors.NotFound, result.Error);
}
[Fact]
public async Task Delete_WhenFound_RemovesPlan()
{
using var dbContext = InMemoryDbContextFactory.Create();
var plan = Plan.Create("Стандарт", 3, 0);
dbContext.Plans.Add(plan);
await dbContext.SaveChangesAsync(CancellationToken.None);
var handler = new DeletePlanCommandHandler(dbContext);
var result = await handler.Handle(new DeletePlanCommand(plan.Id), CancellationToken.None);
await dbContext.SaveChangesAsync(CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Null(await dbContext.Plans.FindAsync([plan.Id], CancellationToken.None));
}
[Fact]
public async Task ListAdmin_ReturnsAllPlansOrderedBySortOrder()
{
using var dbContext = InMemoryDbContextFactory.Create();
dbContext.Plans.AddRange(
Plan.Create("Про", 9, 2),
Plan.Create("Стандарт", 3, 0),
Plan.Create("Плюс", 6, 1)
);
await dbContext.SaveChangesAsync(CancellationToken.None);
var handler = new ListAdminPlansQueryHandler(dbContext);
var result = await handler.Handle(new ListAdminPlansQuery(), CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Equal(["Стандарт", "Плюс", "Про"], result.Value.Select(p => p.Name));
}
[Fact]
public async Task ListPublic_OnlyReturnsEnabledPlans()
{
using var dbContext = InMemoryDbContextFactory.Create();
var disabled = Plan.Create("Скрытый", 12, 3);
disabled.Update(disabled.Name, disabled.ConfigCount, disabled.SortOrder, isEnabled: false);
dbContext.Plans.AddRange(Plan.Create("Стандарт", 3, 0), disabled);
await dbContext.SaveChangesAsync(CancellationToken.None);
var handler = new PnvPanel.Application.Plans.ListPlansQueryHandler(dbContext);
var result = await handler.Handle(new PnvPanel.Application.Plans.ListPlansQuery(), CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Single(result.Value);
Assert.Equal("Стандарт", result.Value[0].Name);
}
}
@@ -31,7 +31,8 @@ public class ApproveExtensionRequestCommandHandlerTests
"premium",
IsActivated: true,
IsBlocked: false,
MaxConfigs: 5,
ConfigQuota: 5,
PlanId: null,
MaxIpLimit: 3,
SubscriptionToken: "sub-token",
BillingEnabled: true,
@@ -1,265 +0,0 @@
using NSubstitute;
using PnvPanel.Application.Admin.Roles;
using PnvPanel.Application.Admin.Support;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Common.Messaging;
using PnvPanel.Application.Common.Models;
using PnvPanel.Application.Support;
using PnvPanel.Application.Tests.TestSupport;
using PnvPanel.Domain.Billing;
using PnvPanel.Domain.Support;
using Xunit;
namespace PnvPanel.Application.Tests.Admin.Support;
public class ApproveRoleRequestCommandHandlerTests
{
private readonly IRoleService _roleService = Substitute.For<IRoleService>();
private readonly IIdentityService _identityService = Substitute.For<IIdentityService>();
private readonly IRealtimeNotifier _notifier = Substitute.For<IRealtimeNotifier>();
private readonly ITelegramNotifier _telegramNotifier = Substitute.For<ITelegramNotifier>();
private ApproveRoleRequestCommandHandler CreateHandler(IAppDbContext dbContext, ICurrentUser currentUser) =>
new(dbContext, _roleService, _identityService, _notifier, _telegramNotifier, currentUser);
private static CurrentUserProfile Profile(
Guid userId,
int maxConfigs,
DateTimeOffset? billingPaidUntil = null
) =>
new(
userId,
"alice",
Guid.NewGuid(),
"old-role",
IsActivated: true,
IsBlocked: false,
MaxConfigs: maxConfigs,
MaxIpLimit: 3,
SubscriptionToken: "sub-token",
BillingEnabled: billingPaidUntil != null,
BillingPaidUntil: billingPaidUntil,
BillingSuspended: false
);
[Fact]
public async Task Handle_ForNewRoleRequest_CreatesRoleAssignsAndResolves()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var ticket = SupportTicket.CreateRoleRequestForNewRole(userId, "premium", 10, 5);
dbContext.SupportTickets.Add(ticket);
await dbContext.SaveChangesAsync(CancellationToken.None);
var newRoleId = Guid.NewGuid();
_roleService
.CreateRoleAsync("premium", 10, 5, false, Arg.Any<CancellationToken>())
.Returns(Result.Success(new RoleDto(newRoleId, "premium", 10, 5, false, false)));
_roleService
.ChangeUserRoleAsync(userId, newRoleId, Arg.Any<CancellationToken>())
.Returns(Result.Success());
var currentUser = FakeCurrentUser.Authenticated(Guid.NewGuid(), "admin");
var handler = CreateHandler(dbContext, currentUser);
var result = await handler.Handle(
new ApproveRoleRequestCommand(ticket.Id),
CancellationToken.None
);
Assert.True(result.IsSuccess);
Assert.Equal(TicketStatus.Resolved, ticket.Status);
await _roleService
.Received(1)
.CreateRoleAsync("premium", 10, 5, false, Arg.Any<CancellationToken>());
await _roleService
.Received(1)
.ChangeUserRoleAsync(userId, newRoleId, Arg.Any<CancellationToken>());
await _telegramNotifier
.Received(1)
.NotifyUserAsync(
userId,
Arg.Any<string>(),
Arg.Any<string?>(),
Arg.Any<CancellationToken>()
);
}
[Fact]
public async Task Handle_ForExistingRoleRequest_SkipsRoleCreation()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var roleId = Guid.NewGuid();
var ticket = SupportTicket.CreateRoleRequestForExistingRole(userId, roleId);
dbContext.SupportTickets.Add(ticket);
await dbContext.SaveChangesAsync(CancellationToken.None);
_roleService
.ListRolesAsync(Arg.Any<CancellationToken>())
.Returns(new List<RoleDto> { new(roleId, "premium", 10, 5, false, false) });
_roleService
.ChangeUserRoleAsync(userId, roleId, Arg.Any<CancellationToken>())
.Returns(Result.Success());
var currentUser = FakeCurrentUser.Authenticated(Guid.NewGuid());
var handler = CreateHandler(dbContext, currentUser);
var result = await handler.Handle(
new ApproveRoleRequestCommand(ticket.Id),
CancellationToken.None
);
Assert.True(result.IsSuccess);
await _roleService
.DidNotReceive()
.CreateRoleAsync(
Arg.Any<string>(),
Arg.Any<int>(),
Arg.Any<int>(),
Arg.Any<bool>(),
Arg.Any<CancellationToken>()
);
}
[Fact]
public async Task Handle_WhenNotRoleRequestType_ReturnsError()
{
using var dbContext = InMemoryDbContextFactory.Create();
var ticket = SupportTicket.CreateBugReport(Guid.NewGuid());
dbContext.SupportTickets.Add(ticket);
await dbContext.SaveChangesAsync(CancellationToken.None);
var currentUser = FakeCurrentUser.Authenticated(Guid.NewGuid());
var handler = CreateHandler(dbContext, currentUser);
var result = await handler.Handle(
new ApproveRoleRequestCommand(ticket.Id),
CancellationToken.None
);
Assert.False(result.IsSuccess);
Assert.Equal(SupportErrors.NotRoleRequest, result.Error);
}
[Fact]
public async Task Handle_WhenTicketIsOwnedByAdmin_StillApproves()
{
// Одобрить свою же заявку можно — единственный реальный риск (снять admin с последнего
// администратора) ловит RoleService.ChangeUserRoleAsync, а не этот хендлер (см. соседний тест).
using var dbContext = InMemoryDbContextFactory.Create();
var adminId = Guid.NewGuid();
var roleId = Guid.NewGuid();
var ticket = SupportTicket.CreateRoleRequestForExistingRole(adminId, roleId);
dbContext.SupportTickets.Add(ticket);
await dbContext.SaveChangesAsync(CancellationToken.None);
_roleService
.ListRolesAsync(Arg.Any<CancellationToken>())
.Returns(new List<RoleDto> { new(roleId, "premium", 10, 5, false, false) });
_roleService
.ChangeUserRoleAsync(adminId, roleId, Arg.Any<CancellationToken>())
.Returns(Result.Success());
var currentUser = FakeCurrentUser.Authenticated(adminId, "admin");
var handler = CreateHandler(dbContext, currentUser);
var result = await handler.Handle(
new ApproveRoleRequestCommand(ticket.Id),
CancellationToken.None
);
Assert.True(result.IsSuccess);
Assert.Equal(TicketStatus.Resolved, ticket.Status);
}
[Fact]
public async Task Handle_WhenRoleServiceRefusesLastAdminDowngrade_PropagatesFailure()
{
using var dbContext = InMemoryDbContextFactory.Create();
var adminId = Guid.NewGuid();
var roleId = Guid.NewGuid();
var ticket = SupportTicket.CreateRoleRequestForExistingRole(adminId, roleId);
dbContext.SupportTickets.Add(ticket);
await dbContext.SaveChangesAsync(CancellationToken.None);
_roleService
.ListRolesAsync(Arg.Any<CancellationToken>())
.Returns(new List<RoleDto> { new(roleId, "premium", 10, 5, false, false) });
_roleService
.ChangeUserRoleAsync(adminId, roleId, Arg.Any<CancellationToken>())
.Returns(Result.Failure(RoleErrors.CannotRemoveLastAdmin));
var currentUser = FakeCurrentUser.Authenticated(adminId, "admin");
var handler = CreateHandler(dbContext, currentUser);
var result = await handler.Handle(
new ApproveRoleRequestCommand(ticket.Id),
CancellationToken.None
);
Assert.False(result.IsSuccess);
Assert.Equal(RoleErrors.CannotRemoveLastAdmin, result.Error);
// Тикет остаётся Open — можно повторить попытку после назначения второго админа.
Assert.Equal(TicketStatus.Open, ticket.Status);
}
[Fact]
public async Task Handle_WhenNewRoleMoreExpensiveWithActivePaidPeriod_CreatesRoleChangeTopUp()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var roleId = Guid.NewGuid();
var ticket = SupportTicket.CreateRoleRequestForExistingRole(userId, roleId);
dbContext.SupportTickets.Add(ticket);
var pricing = PnvPanel.Domain.Pricing.PricingSettings.CreateDefault();
pricing.Update(500, 450, 400);
dbContext.PricingSettings.Add(pricing);
await dbContext.SaveChangesAsync(CancellationToken.None);
_roleService
.ListRolesAsync(Arg.Any<CancellationToken>())
.Returns(new List<RoleDto> { new(roleId, "premium", MaxConfigs: 10, 5, false, BillingEnabled: true) });
_roleService.ChangeUserRoleAsync(userId, roleId, Arg.Any<CancellationToken>()).Returns(Result.Success());
_identityService
.GetProfileAsync(userId, Arg.Any<CancellationToken>())
.Returns(Profile(userId, maxConfigs: 3, billingPaidUntil: DateTimeOffset.UtcNow.AddDays(30)));
var handler = CreateHandler(dbContext, FakeCurrentUser.Authenticated(Guid.NewGuid(), "admin"));
var result = await handler.Handle(new ApproveRoleRequestCommand(ticket.Id), CancellationToken.None);
Assert.True(result.IsSuccess);
var topUp = Assert.Single(dbContext.PaymentRequests.Local);
Assert.Equal(PaymentRequestKind.RoleChangeTopUp, topUp.Kind);
Assert.Null(topUp.Period);
Assert.True(topUp.AmountSnapshot > 0);
}
[Fact]
public async Task Handle_WhenNoActivePaidPeriod_DoesNotCreateTopUp()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var roleId = Guid.NewGuid();
var ticket = SupportTicket.CreateRoleRequestForExistingRole(userId, roleId);
dbContext.SupportTickets.Add(ticket);
await dbContext.SaveChangesAsync(CancellationToken.None);
_roleService
.ListRolesAsync(Arg.Any<CancellationToken>())
.Returns(new List<RoleDto> { new(roleId, "premium", MaxConfigs: 10, 5, false, BillingEnabled: true) });
_roleService.ChangeUserRoleAsync(userId, roleId, Arg.Any<CancellationToken>()).Returns(Result.Success());
_identityService
.GetProfileAsync(userId, Arg.Any<CancellationToken>())
.Returns(Profile(userId, maxConfigs: 3, billingPaidUntil: null));
var handler = CreateHandler(dbContext, FakeCurrentUser.Authenticated(Guid.NewGuid(), "admin"));
var result = await handler.Handle(new ApproveRoleRequestCommand(ticket.Id), CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Empty(dbContext.PaymentRequests.Local);
}
}
@@ -1,67 +0,0 @@
using NSubstitute;
using PnvPanel.Application.Admin.Support;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Tests.TestSupport;
using PnvPanel.Domain.Support;
using Xunit;
namespace PnvPanel.Application.Tests.Admin.Support;
public class RejectRoleRequestCommandHandlerTests
{
private readonly IRealtimeNotifier _notifier = Substitute.For<IRealtimeNotifier>();
private readonly ITelegramNotifier _telegramNotifier = Substitute.For<ITelegramNotifier>();
[Fact]
public async Task Handle_RejectsRoleRequest_ClosesTicket()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var ticket = SupportTicket.CreateRoleRequestForExistingRole(userId, Guid.NewGuid());
dbContext.SupportTickets.Add(ticket);
await dbContext.SaveChangesAsync(CancellationToken.None);
var currentUser = FakeCurrentUser.Authenticated(Guid.NewGuid(), "admin");
var handler = new RejectRoleRequestCommandHandler(
dbContext,
_notifier,
_telegramNotifier,
currentUser
);
var result = await handler.Handle(
new RejectRoleRequestCommand(ticket.Id, "не подходит"),
CancellationToken.None
);
Assert.True(result.IsSuccess);
Assert.Equal(TicketStatus.Closed, ticket.Status);
}
[Fact]
public async Task Handle_WhenTicketIsOwnedByAdmin_StillRejects()
{
// Отклонить свою же заявку можно — Reject не меняет роль, риска нет.
using var dbContext = InMemoryDbContextFactory.Create();
var adminId = Guid.NewGuid();
var ticket = SupportTicket.CreateRoleRequestForExistingRole(adminId, Guid.NewGuid());
dbContext.SupportTickets.Add(ticket);
await dbContext.SaveChangesAsync(CancellationToken.None);
var currentUser = FakeCurrentUser.Authenticated(adminId, "admin");
var handler = new RejectRoleRequestCommandHandler(
dbContext,
_notifier,
_telegramNotifier,
currentUser
);
var result = await handler.Handle(
new RejectRoleRequestCommand(ticket.Id, null),
CancellationToken.None
);
Assert.True(result.IsSuccess);
Assert.Equal(TicketStatus.Closed, ticket.Status);
}
}
@@ -68,14 +68,13 @@ public class ResolveTicketCommandHandlerTests
}
[Fact]
public async Task Handle_WhenRoleRequest_ReturnsOnlyBugReportCanBeResolvedDirectly()
public async Task Handle_WhenExtensionRequest_ReturnsOnlyBugReportCanBeResolvedDirectly()
{
// Заявку на роль/продление можно решить только через Approve/Reject — Resolve обходил бы
// одобрение (роль/продление так и не назначились бы), см. CLAUDE.md.
// Заявку на продление можно решить только через Approve/Reject — Resolve обходил бы
// одобрение (дни так и не начислились бы), см. CLAUDE.md.
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var roleId = Guid.NewGuid();
var ticket = SupportTicket.CreateRoleRequestForExistingRole(userId, roleId);
var ticket = SupportTicket.CreateExtensionRequest(userId, 14);
dbContext.SupportTickets.Add(ticket);
await dbContext.SaveChangesAsync(CancellationToken.None);
@@ -0,0 +1,139 @@
using NSubstitute;
using PnvPanel.Application.Admin.Users;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Common.Models;
using PnvPanel.Application.Plans;
using PnvPanel.Application.Tests.TestSupport;
using PnvPanel.Domain.Plans;
using Xunit;
namespace PnvPanel.Application.Tests.Admin.Users;
public class AdminSetUserPlanCommandHandlerTests
{
private readonly IIdentityService _identityService = Substitute.For<IIdentityService>();
private static CurrentUserProfile Profile(Guid userId, string role, int configQuota) =>
new(
userId,
"alice",
Guid.NewGuid(),
role,
IsActivated: true,
IsBlocked: false,
ConfigQuota: configQuota,
PlanId: null,
MaxIpLimit: 2,
SubscriptionToken: "sub-token",
BillingEnabled: false,
BillingPaidUntil: null,
BillingSuspended: false
);
[Fact]
public async Task Handle_WhenUnlimitedForNonAdmin_ReturnsUnlimitedOnlyForAdmin()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
_identityService
.GetProfileAsync(userId, Arg.Any<CancellationToken>())
.Returns(Profile(userId, "user", 3));
var handler = new AdminSetUserPlanCommandHandler(
dbContext,
_identityService,
FakeCurrentUser.Authenticated(Guid.NewGuid())
);
var result = await handler.Handle(
new AdminSetUserPlanCommand(userId, null, RoleQuota.Unlimited),
CancellationToken.None
);
Assert.False(result.IsSuccess);
Assert.Equal(PlanErrors.UnlimitedOnlyForAdmin, result.Error);
await _identityService
.DidNotReceive()
.SetConfigQuotaAsync(Arg.Any<Guid>(), Arg.Any<int>(), Arg.Any<Guid?>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_WhenUnlimitedForAdmin_Succeeds()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
_identityService
.GetProfileAsync(userId, Arg.Any<CancellationToken>())
.Returns(Profile(userId, "admin", -1));
_identityService
.SetConfigQuotaAsync(userId, RoleQuota.Unlimited, null, Arg.Any<CancellationToken>())
.Returns(Result.Success());
var handler = new AdminSetUserPlanCommandHandler(
dbContext,
_identityService,
FakeCurrentUser.Authenticated(Guid.NewGuid())
);
var result = await handler.Handle(
new AdminSetUserPlanCommand(userId, null, RoleQuota.Unlimited),
CancellationToken.None
);
Assert.True(result.IsSuccess);
await _identityService
.Received(1)
.SetConfigQuotaAsync(userId, RoleQuota.Unlimited, null, Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_WithPlanId_UsesPlanConfigCount()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var plan = Plan.Create("Плюс", 6, 0);
dbContext.Plans.Add(plan);
await dbContext.SaveChangesAsync(CancellationToken.None);
_identityService
.SetConfigQuotaAsync(userId, 6, plan.Id, Arg.Any<CancellationToken>())
.Returns(Result.Success());
var handler = new AdminSetUserPlanCommandHandler(
dbContext,
_identityService,
FakeCurrentUser.Authenticated(Guid.NewGuid())
);
var result = await handler.Handle(
new AdminSetUserPlanCommand(userId, plan.Id, null),
CancellationToken.None
);
Assert.True(result.IsSuccess);
await _identityService
.Received(1)
.SetConfigQuotaAsync(userId, 6, plan.Id, Arg.Any<CancellationToken>());
Assert.Single(dbContext.AuditLogs.Local);
}
[Fact]
public async Task Handle_WhenPlanNotFound_ReturnsNotFound()
{
using var dbContext = InMemoryDbContextFactory.Create();
var handler = new AdminSetUserPlanCommandHandler(
dbContext,
_identityService,
FakeCurrentUser.Authenticated(Guid.NewGuid())
);
var result = await handler.Handle(
new AdminSetUserPlanCommand(Guid.NewGuid(), Guid.NewGuid(), null),
CancellationToken.None
);
Assert.False(result.IsSuccess);
Assert.Equal(PlanErrors.NotFound, result.Error);
}
}
@@ -56,13 +56,13 @@ public class ListUsersQueryHandlerTests
}
[Fact]
public async Task Handle_WhenPendingRequestIsRoleChangeTopUp_LeavesBillingPendingReviewFalse()
public async Task Handle_WhenPendingRequestIsPlanChangeTopUp_LeavesBillingPendingReviewFalse()
{
// RoleChangeTopUp — доплата за смену роли, не подписка; не должна показывать пользователя
// PlanChangeTopUp — доплата за смену тарифа, не подписка; не должна показывать пользователя
// как "оплата на проверке" в админке (см. CLAUDE.md про Kind).
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var request = PaymentRequest.CreateRoleChangeTopUp(userId, 500);
var request = PaymentRequest.CreatePlanChangeTopUp(userId, 500);
request.MarkPaymentSent();
dbContext.PaymentRequests.Add(request);
await dbContext.SaveChangesAsync(CancellationToken.None);
@@ -54,6 +54,7 @@ public class GetCurrentUserQueryHandlerTests
true,
false,
3,
null,
RoleQuota.Unlimited,
"sub-token",
false,
@@ -29,7 +29,8 @@ public class LoginCommandHandlerTests
"user",
IsActivated: true,
IsBlocked: false,
MaxConfigs: 3,
ConfigQuota: 3,
PlanId: null,
MaxIpLimit: RoleQuota.Unlimited,
SubscriptionToken: "sub-token",
BillingEnabled: false,
@@ -28,7 +28,8 @@ public class RefreshCommandHandlerTests
"user",
IsActivated: true,
IsBlocked: false,
MaxConfigs: 3,
ConfigQuota: 3,
PlanId: null,
MaxIpLimit: RoleQuota.Unlimited,
SubscriptionToken: "sub-token",
BillingEnabled: false,
@@ -112,7 +113,8 @@ public class RefreshCommandHandlerTests
"user",
IsActivated: true,
IsBlocked: true,
MaxConfigs: 3,
ConfigQuota: 3,
PlanId: null,
MaxIpLimit: RoleQuota.Unlimited,
SubscriptionToken: "sub-token",
BillingEnabled: false,
@@ -27,7 +27,8 @@ public class CreatePaymentRequestCommandHandlerTests
"premium",
IsActivated: true,
IsBlocked: false,
MaxConfigs: maxConfigs,
ConfigQuota: maxConfigs,
PlanId: null,
MaxIpLimit: 3,
SubscriptionToken: "sub-token",
BillingEnabled: billingEnabled,
@@ -24,7 +24,8 @@ public class GetMyBillingStatusQueryHandlerTests
"premium",
IsActivated: true,
IsBlocked: false,
MaxConfigs: 5,
ConfigQuota: 5,
PlanId: null,
MaxIpLimit: 3,
SubscriptionToken: "sub-token",
BillingEnabled: billingEnabled,
@@ -33,7 +33,8 @@ public class MarkPaymentSentCommandHandlerTests
"premium",
IsActivated: true,
IsBlocked: false,
MaxConfigs: 5,
ConfigQuota: 5,
PlanId: null,
MaxIpLimit: 3,
SubscriptionToken: "sub-token",
BillingEnabled: true,
@@ -26,7 +26,8 @@ public class RequireActivationBehaviorTests
"user",
IsActivated: isActivated,
IsBlocked: false,
MaxConfigs: 3,
ConfigQuota: 3,
PlanId: null,
MaxIpLimit: RoleQuota.Unlimited,
SubscriptionToken: "sub-token",
BillingEnabled: false,
@@ -33,7 +33,8 @@ public class CreateVpnConfigCommandHandlerTests
"premium",
IsActivated: true,
IsBlocked: false,
MaxConfigs: 5,
ConfigQuota: 5,
PlanId: null,
MaxIpLimit: 3,
SubscriptionToken: "sub-token",
BillingEnabled: billingEnabled,
@@ -46,6 +46,7 @@ public class GetMyConfigsQueryHandlerTests
true,
false,
5,
null,
RoleQuota.Unlimited,
"sub-token",
false,
@@ -65,7 +66,7 @@ public class GetMyConfigsQueryHandlerTests
Assert.True(result.IsSuccess);
Assert.Single(result.Value.Configs);
Assert.Equal(activeConfig.Id, result.Value.Configs[0].Id);
Assert.Equal(5, result.Value.MaxConfigs);
Assert.Equal(5, result.Value.ConfigQuota);
}
[Fact]
@@ -16,6 +16,7 @@ using PnvPanel.Domain.Inbounds;
using PnvPanel.Domain.Instructions;
using PnvPanel.Domain.News;
using PnvPanel.Domain.Nodes;
using PnvPanel.Domain.Plans;
using PnvPanel.Domain.Pricing;
using PnvPanel.Domain.Support;
using PnvPanel.Domain.Telegram;
@@ -48,6 +49,7 @@ public sealed class ThrowingSaveDbContext(AppDbContext inner) : IAppDbContext
public DbSet<PricingDiscountTier> PricingDiscountTiers => inner.PricingDiscountTiers;
public DbSet<BillingSettings> BillingSettings => inner.BillingSettings;
public DbSet<PaymentRequest> PaymentRequests => inner.PaymentRequests;
public DbSet<Plan> Plans => inner.Plans;
public DatabaseFacade Database => inner.Database;
public Task<int> SaveChangesAsync(CancellationToken cancellationToken) =>
@@ -68,6 +70,7 @@ public class RotateVpnConfigCommandHandlerTests
true,
false,
3,
null,
RoleQuota.Unlimited,
"sub-token",
false,
@@ -0,0 +1,298 @@
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using PnvPanel.Application.Auth;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Common.Models;
using PnvPanel.Application.Plans;
using PnvPanel.Application.Tests.TestSupport;
using PnvPanel.Domain.Billing;
using PnvPanel.Domain.Configs;
using PnvPanel.Domain.Inbounds;
using PnvPanel.Domain.Nodes;
using PnvPanel.Domain.Plans;
using PnvPanel.Domain.Pricing;
using Xunit;
namespace PnvPanel.Application.Tests.Plans;
public class ChangePlanCommandHandlerTests
{
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 static CurrentUserProfile Profile(
Guid userId,
int configQuota = 3,
bool billingEnabled = false,
DateTimeOffset? billingPaidUntil = null
) =>
new(
userId,
"alice",
Guid.NewGuid(),
"user",
IsActivated: true,
IsBlocked: false,
ConfigQuota: configQuota,
PlanId: null,
MaxIpLimit: 2,
SubscriptionToken: "sub-token",
BillingEnabled: billingEnabled,
BillingPaidUntil: billingPaidUntil,
BillingSuspended: false
);
private ChangePlanCommandHandler CreateHandler(IAppDbContext dbContext, Guid userId) =>
new(
dbContext,
_identityService,
_gateway,
_notifier,
_telegramNotifier,
FakeCurrentUser.Authenticated(userId),
NullLogger<ChangePlanCommandHandler>.Instance
);
[Fact]
public async Task Handle_WhenPlanNotFound_ReturnsNotFound()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
_identityService.GetProfileAsync(userId, Arg.Any<CancellationToken>()).Returns(Profile(userId));
var result = await CreateHandler(dbContext, userId)
.Handle(new ChangePlanCommand(Guid.NewGuid(), null, []), CancellationToken.None);
Assert.False(result.IsSuccess);
Assert.Equal(PlanErrors.NotFound, result.Error);
}
[Fact]
public async Task Handle_WhenPlanDisabled_ReturnsDisabled()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var plan = Plan.Create("Скрытый", 6, 0);
plan.Update(plan.Name, plan.ConfigCount, plan.SortOrder, isEnabled: false);
dbContext.Plans.Add(plan);
await dbContext.SaveChangesAsync(CancellationToken.None);
_identityService.GetProfileAsync(userId, Arg.Any<CancellationToken>()).Returns(Profile(userId));
var result = await CreateHandler(dbContext, userId)
.Handle(new ChangePlanCommand(plan.Id, null, []), CancellationToken.None);
Assert.False(result.IsSuccess);
Assert.Equal(PlanErrors.Disabled, result.Error);
}
[Fact]
public async Task Handle_WithCustomConfigCount_UpdatesQuotaImmediatelyWithoutBilling()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
_identityService
.GetProfileAsync(userId, Arg.Any<CancellationToken>())
.Returns(Profile(userId, configQuota: 3, billingEnabled: false));
_identityService
.SetConfigQuotaAsync(userId, 8, null, Arg.Any<CancellationToken>())
.Returns(Result.Success());
var result = await CreateHandler(dbContext, userId)
.Handle(new ChangePlanCommand(null, 8, []), CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Equal(8, result.Value.ConfigQuota);
Assert.Null(result.Value.PlanId);
Assert.Null(result.Value.TopUpAmount);
await _identityService.Received(1).SetConfigQuotaAsync(userId, 8, null, Arg.Any<CancellationToken>());
Assert.Empty(dbContext.PaymentRequests);
}
[Fact]
public async Task Handle_WhenUpgradingWithBillingAndActivePaidPeriod_CreatesTopUp()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var plan = Plan.Create("Плюс", 10, 0);
dbContext.Plans.Add(plan);
var pricing = PricingSettings.CreateDefault();
pricing.Update(200, 180, 160);
dbContext.PricingSettings.Add(pricing);
await dbContext.SaveChangesAsync(CancellationToken.None);
var paidUntil = DateTimeOffset.UtcNow.AddDays(30);
_identityService
.GetProfileAsync(userId, Arg.Any<CancellationToken>())
.Returns(Profile(userId, configQuota: 3, billingEnabled: true, billingPaidUntil: paidUntil));
_identityService
.SetConfigQuotaAsync(userId, 10, plan.Id, Arg.Any<CancellationToken>())
.Returns(Result.Success());
var result = await CreateHandler(dbContext, userId)
.Handle(new ChangePlanCommand(plan.Id, null, []), CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Equal(10, result.Value.ConfigQuota);
Assert.Equal(plan.Id, result.Value.PlanId);
Assert.NotNull(result.Value.TopUpAmount);
var topUp = Assert.Single(dbContext.PaymentRequests);
Assert.Equal(PaymentRequestKind.PlanChangeTopUp, topUp.Kind);
Assert.Equal(result.Value.TopUpAmount, topUp.AmountSnapshot);
}
[Fact]
public async Task Handle_WhenDowngradeWithoutEnoughConfigIdsToRevoke_ReturnsMustSelectConfigsToRevoke()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var inbound = Inbound.FromRemote(Guid.NewGuid(), "1", VpnProtocol.Vless, "remark", 443);
dbContext.Inbounds.Add(inbound);
dbContext.VpnConfigs.AddRange(
VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, "a"),
VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, "b"),
VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, "c")
);
await dbContext.SaveChangesAsync(CancellationToken.None);
_identityService
.GetProfileAsync(userId, Arg.Any<CancellationToken>())
.Returns(Profile(userId, configQuota: 3));
var result = await CreateHandler(dbContext, userId)
.Handle(new ChangePlanCommand(null, 1, []), CancellationToken.None);
Assert.False(result.IsSuccess);
Assert.Equal(PlanErrors.MustSelectConfigsToRevoke(2), result.Error);
}
[Fact]
public async Task Handle_WhenDowngradeWithOnlyExpiredConfigs_StillRequiresSelectingThem()
{
// Все конфиги приостановлены за неуплату (Expired) — ни одного Active. Если считать
// excess только по Active, форма подумает, что отзывать нечего, а BillingConfigResumer
// потом молча вернёт все три в Active при следующей оплате — мимо новой квоты.
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var inbound = Inbound.FromRemote(Guid.NewGuid(), "1", VpnProtocol.Vless, "remark", 443);
dbContext.Inbounds.Add(inbound);
var configs = new[]
{
VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, "a"),
VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, "b"),
VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, "c"),
};
foreach (var c in configs)
c.Suspend();
dbContext.VpnConfigs.AddRange(configs);
await dbContext.SaveChangesAsync(CancellationToken.None);
_identityService
.GetProfileAsync(userId, Arg.Any<CancellationToken>())
.Returns(Profile(userId, configQuota: 3, billingEnabled: true));
var result = await CreateHandler(dbContext, userId)
.Handle(new ChangePlanCommand(null, 1, []), CancellationToken.None);
Assert.False(result.IsSuccess);
Assert.Equal(PlanErrors.MustSelectConfigsToRevoke(2), result.Error);
}
[Fact]
public async Task Handle_WhenDowngradeSelectingExpiredConfig_RevokesIt()
{
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 toKeep = VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, "keep");
var toRevoke = VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, "revoke");
toRevoke.Suspend();
dbContext.Nodes.Add(node);
dbContext.Inbounds.Add(inbound);
dbContext.VpnConfigs.AddRange(toKeep, toRevoke);
await dbContext.SaveChangesAsync(CancellationToken.None);
_identityService
.GetProfileAsync(userId, Arg.Any<CancellationToken>())
.Returns(Profile(userId, configQuota: 3, billingEnabled: true));
_identityService
.SetConfigQuotaAsync(userId, 1, null, Arg.Any<CancellationToken>())
.Returns(Result.Success());
_gateway
.RemoveClientAsync(
Arg.Any<Node>(),
inbound.RemoteInboundId,
toRevoke.ClientExternalId,
toRevoke.Protocol,
Arg.Any<CancellationToken>()
)
.Returns(Result.Success());
var result = await CreateHandler(dbContext, userId)
.Handle(new ChangePlanCommand(null, 1, [toRevoke.Id]), CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Equal(ConfigStatus.Revoked, toRevoke.Status);
Assert.Equal(ConfigStatus.Active, toKeep.Status);
}
[Fact]
public async Task Handle_WhenDowngradeWithCorrectConfigIds_RevokesThemAndUpdatesQuota()
{
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 toKeep = VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, "keep");
var toRevoke = VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, "revoke");
dbContext.Nodes.Add(node);
dbContext.Inbounds.Add(inbound);
dbContext.VpnConfigs.AddRange(toKeep, toRevoke);
await dbContext.SaveChangesAsync(CancellationToken.None);
_identityService
.GetProfileAsync(userId, Arg.Any<CancellationToken>())
.Returns(Profile(userId, configQuota: 3));
_identityService
.SetConfigQuotaAsync(userId, 1, null, Arg.Any<CancellationToken>())
.Returns(Result.Success());
_gateway
.RemoveClientAsync(
Arg.Any<Node>(),
inbound.RemoteInboundId,
toRevoke.ClientExternalId,
toRevoke.Protocol,
Arg.Any<CancellationToken>()
)
.Returns(Result.Success());
var result = await CreateHandler(dbContext, userId)
.Handle(new ChangePlanCommand(null, 1, [toRevoke.Id]), CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Equal(ConfigStatus.Revoked, toRevoke.Status);
Assert.Equal(ConfigStatus.Active, toKeep.Status);
await _identityService.Received(1).SetConfigQuotaAsync(userId, 1, null, Arg.Any<CancellationToken>());
await _notifier
.Received(1)
.NotifyConfigStatusChangedAsync(
userId,
toRevoke.Id,
ConfigStatus.Revoked,
Arg.Any<CancellationToken>()
);
}
}
@@ -23,7 +23,8 @@ public class AddTicketCommentCommandHandlerTests
role,
IsActivated: true,
IsBlocked: false,
MaxConfigs: 3,
ConfigQuota: 3,
PlanId: null,
MaxIpLimit: RoleQuota.Unlimited,
SubscriptionToken: "token",
BillingEnabled: false,
@@ -23,7 +23,8 @@ public class CreateExtensionRequestTicketCommandHandlerTests
"premium",
IsActivated: true,
IsBlocked: false,
MaxConfigs: 5,
ConfigQuota: 5,
PlanId: null,
MaxIpLimit: 3,
SubscriptionToken: "sub-token",
BillingEnabled: billingEnabled,
@@ -1,133 +0,0 @@
using NSubstitute;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Support;
using PnvPanel.Application.Support.CreateRoleRequest;
using PnvPanel.Application.Tests.TestSupport;
using PnvPanel.Domain.Support;
using Xunit;
namespace PnvPanel.Application.Tests.Support;
public class CreateRoleRequestTicketCommandHandlerTests
{
private readonly IRoleService _roleService = Substitute.For<IRoleService>();
private readonly IRealtimeNotifier _notifier = Substitute.For<IRealtimeNotifier>();
private readonly ITelegramNotifier _telegramNotifier = Substitute.For<ITelegramNotifier>();
[Fact]
public async Task Handle_ForExistingRole_CreatesTicket()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var roleId = Guid.NewGuid();
var currentUser = FakeCurrentUser.Authenticated(userId, "alice");
_roleService
.ListRolesAsync(Arg.Any<CancellationToken>())
.Returns(new List<RoleDto> { new(roleId, "premium", 5, 2, false, false) });
var handler = new CreateRoleRequestTicketCommandHandler(
dbContext,
_roleService,
_notifier,
_telegramNotifier,
currentUser
);
var result = await handler.Handle(
new CreateRoleRequestTicketCommand(roleId, null, null, null, "нужно больше конфигов"),
CancellationToken.None
);
await dbContext.SaveChangesAsync(CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Equal(roleId, result.Value.RequestedRoleId);
Assert.Equal("premium", result.Value.RequestedRoleName);
await _telegramNotifier
.Received(1)
.NotifyAdminsRoleRequestCreatedAsync(
Arg.Any<Guid>(),
"alice",
"premium",
"нужно больше конфигов",
Arg.Any<CancellationToken>()
);
}
[Fact]
public async Task Handle_ForAdminRole_ReturnsForbidden()
{
using var dbContext = InMemoryDbContextFactory.Create();
var roleId = Guid.NewGuid();
var currentUser = FakeCurrentUser.Authenticated(Guid.NewGuid());
_roleService
.ListRolesAsync(Arg.Any<CancellationToken>())
.Returns(new List<RoleDto> { new(roleId, "admin", -1, -1, true, false) });
var handler = new CreateRoleRequestTicketCommandHandler(
dbContext,
_roleService,
_notifier,
_telegramNotifier,
currentUser
);
var result = await handler.Handle(
new CreateRoleRequestTicketCommand(roleId, null, null, null, "хочу быть админом"),
CancellationToken.None
);
Assert.False(result.IsSuccess);
Assert.Equal(SupportErrors.CannotRequestAdminRole, result.Error);
}
[Fact]
public async Task Handle_ForNewRole_SetsProposedFields()
{
using var dbContext = InMemoryDbContextFactory.Create();
var currentUser = FakeCurrentUser.Authenticated(Guid.NewGuid(), "bob");
var handler = new CreateRoleRequestTicketCommandHandler(
dbContext,
_roleService,
_notifier,
_telegramNotifier,
currentUser
);
var result = await handler.Handle(
new CreateRoleRequestTicketCommand(null, "custom", 10, 4, "нужна кастомная роль"),
CancellationToken.None
);
Assert.True(result.IsSuccess);
Assert.Equal("custom", result.Value.ProposedRoleName);
Assert.Equal(10, result.Value.ProposedMaxConfigs);
Assert.Equal(4, result.Value.ProposedMaxIpLimit);
}
[Fact]
public async Task Handle_WhenPendingRoleRequestExists_ReturnsConflict()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
dbContext.SupportTickets.Add(SupportTicket.CreateRoleRequestForNewRole(userId, "x", 1, 1));
await dbContext.SaveChangesAsync(CancellationToken.None);
var currentUser = FakeCurrentUser.Authenticated(userId);
var handler = new CreateRoleRequestTicketCommandHandler(
dbContext,
_roleService,
_notifier,
_telegramNotifier,
currentUser
);
var result = await handler.Handle(
new CreateRoleRequestTicketCommand(null, "y", 2, 2, "ещё заявка"),
CancellationToken.None
);
Assert.False(result.IsSuccess);
Assert.Equal(SupportErrors.RoleRequestAlreadyPending, result.Error);
}
}
@@ -1,97 +0,0 @@
using NSubstitute;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Support.ListSelectableRoles;
using PnvPanel.Application.Tests.TestSupport;
using Xunit;
namespace PnvPanel.Application.Tests.Support.ListSelectableRoles;
public class ListSelectableRolesQueryHandlerTests
{
private readonly IRoleService _roleService = Substitute.For<IRoleService>();
private readonly IIdentityService _identityService = Substitute.For<IIdentityService>();
private static CurrentUserProfile Profile(Guid userId, Guid roleId, string role) =>
new(
userId,
"user",
roleId,
role,
IsActivated: true,
IsBlocked: false,
MaxConfigs: 3,
MaxIpLimit: 1,
SubscriptionToken: "token",
BillingEnabled: false,
BillingPaidUntil: null,
BillingSuspended: false
);
[Fact]
public async Task Handle_ExcludesAdminAndCurrentUserRole()
{
var userId = Guid.NewGuid();
var currentRoleId = Guid.NewGuid();
var extendedRoleId = Guid.NewGuid();
var adminRoleId = Guid.NewGuid();
_roleService
.ListRolesAsync(Arg.Any<CancellationToken>())
.Returns(
new List<RoleDto>
{
new(adminRoleId, "admin", -1, -1, IsSystem: true, BillingEnabled: false),
new(currentRoleId, "user", 3, 1, IsSystem: true, BillingEnabled: false),
new(extendedRoleId, "extended", 10, 5, IsSystem: false, BillingEnabled: false),
}
);
_identityService
.GetProfileAsync(userId, Arg.Any<CancellationToken>())
.Returns(Profile(userId, currentRoleId, "user"));
var currentUser = FakeCurrentUser.Authenticated(userId, "alice");
var handler = new ListSelectableRolesQueryHandler(
_roleService,
_identityService,
currentUser
);
var result = await handler.Handle(new ListSelectableRolesQuery(), CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Equal(["extended"], result.Value.Select(r => r.Name));
}
[Fact]
public async Task Handle_WhenProfileMissing_StillExcludesAdmin()
{
var userId = Guid.NewGuid();
var userRoleId = Guid.NewGuid();
var adminRoleId = Guid.NewGuid();
_roleService
.ListRolesAsync(Arg.Any<CancellationToken>())
.Returns(
new List<RoleDto>
{
new(adminRoleId, "admin", -1, -1, IsSystem: true, BillingEnabled: false),
new(userRoleId, "user", 3, 1, IsSystem: true, BillingEnabled: false),
}
);
_identityService
.GetProfileAsync(userId, Arg.Any<CancellationToken>())
.Returns((CurrentUserProfile?)null);
var currentUser = FakeCurrentUser.Authenticated(userId, "alice");
var handler = new ListSelectableRolesQueryHandler(
_roleService,
_identityService,
currentUser
);
var result = await handler.Handle(new ListSelectableRolesQuery(), CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Equal(["user"], result.Value.Select(r => r.Name));
}
}
@@ -85,13 +85,13 @@ public class ReopenTicketCommandHandlerTests
}
[Fact]
public async Task Handle_WhenRoleRequestResolved_ReturnsOnlyBugReportCanBeReopened()
public async Task Handle_WhenExtensionRequestResolved_ReturnsOnlyBugReportCanBeReopened()
{
// approve/reject — единственный способ решить заявку на роль/продление (см. CLAUDE.md);
// Reopen для них запрещён даже если тикет каким-то образом оказался Resolved.
// approve/reject — единственный способ решить заявку на продление (см. CLAUDE.md);
// Reopen для неё запрещён даже если тикет каким-то образом оказался Resolved.
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var ticket = SupportTicket.CreateRoleRequestForExistingRole(userId, Guid.NewGuid());
var ticket = SupportTicket.CreateExtensionRequest(userId, 14);
ticket.Resolve();
dbContext.SupportTickets.Add(ticket);
await dbContext.SaveChangesAsync(CancellationToken.None);
@@ -97,6 +97,7 @@ public class GetLoginRequestStatusQueryHandlerTests
true,
false,
3,
null,
RoleQuota.Unlimited,
"sub-token",
false,
@@ -169,6 +170,7 @@ public class GetLoginRequestStatusQueryHandlerTests
true,
true,
3,
null,
RoleQuota.Unlimited,
"sub-token",
false,
@@ -4,17 +4,17 @@ using Xunit;
namespace PnvPanel.Domain.Tests.Billing;
public class RoleChangeTopUpTests
public class PlanChangeTopUpTests
{
private static readonly DateTimeOffset Now = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero);
[Fact]
public void Compute_WhenNewRoleCheaper_ReturnsNull()
public void Compute_WhenNewPlanCheaper_ReturnsNull()
{
var amount = RoleChangeTopUp.Compute(
var amount = PlanChangeTopUp.Compute(
pricePerConfigPerMonth: 200,
oldMaxConfigs: 10,
newMaxConfigs: 3,
oldConfigCount: 10,
newConfigCount: 3,
discountTiers: [],
paidUntil: Now.AddDays(30),
now: Now
@@ -26,10 +26,10 @@ public class RoleChangeTopUpTests
[Fact]
public void Compute_WhenPaidUntilAlreadyExpired_ReturnsNull()
{
var amount = RoleChangeTopUp.Compute(
var amount = PlanChangeTopUp.Compute(
pricePerConfigPerMonth: 200,
oldMaxConfigs: 3,
newMaxConfigs: 10,
oldConfigCount: 3,
newConfigCount: 10,
discountTiers: [],
paidUntil: Now.AddDays(-1),
now: Now
@@ -39,12 +39,12 @@ public class RoleChangeTopUpTests
}
[Fact]
public void Compute_WhenEitherRoleUnlimited_ReturnsNull()
public void Compute_WhenEitherCountUnlimited_ReturnsNull()
{
var amount = RoleChangeTopUp.Compute(
var amount = PlanChangeTopUp.Compute(
pricePerConfigPerMonth: 200,
oldMaxConfigs: 3,
newMaxConfigs: -1,
oldConfigCount: 3,
newConfigCount: -1,
discountTiers: [],
paidUntil: Now.AddDays(30),
now: Now
@@ -56,12 +56,12 @@ public class RoleChangeTopUpTests
[Fact]
public void Compute_WhenUpgrading_ReturnsProratedDifference()
{
// Старая роль: 200 * 3 = 600 ₽/мес. Новая: 200 * 10 = 2000 ₽/мес. Разница 1400 ₽/мес,
// Старый тариф: 200 * 3 = 600 ₽/мес. Новый: 200 * 10 = 2000 ₽/мес. Разница 1400 ₽/мес,
// за 30 дней (ровно месяц) — 1400 ₽.
var amount = RoleChangeTopUp.Compute(
var amount = PlanChangeTopUp.Compute(
pricePerConfigPerMonth: 200,
oldMaxConfigs: 3,
newMaxConfigs: 10,
oldConfigCount: 3,
newConfigCount: 10,
discountTiers: [],
paidUntil: Now.AddDays(30),
now: Now
@@ -74,10 +74,10 @@ public class RoleChangeTopUpTests
public void Compute_ProratesToRemainingDaysOnly()
{
// Та же разница 1400 ₽/мес, но остаётся только 15 из 30 дней — половина.
var amount = RoleChangeTopUp.Compute(
var amount = PlanChangeTopUp.Compute(
pricePerConfigPerMonth: 200,
oldMaxConfigs: 3,
newMaxConfigs: 10,
oldConfigCount: 3,
newConfigCount: 10,
discountTiers: [],
paidUntil: Now.AddDays(15),
now: Now
@@ -87,16 +87,16 @@ public class RoleChangeTopUpTests
}
[Fact]
public void Compute_AppliesDiscountTiersToBothRoles()
public void Compute_AppliesDiscountTiersToBothCounts()
{
var tiers = new[] { PricingDiscountTier.Create(Guid.NewGuid(), minConfigs: 10, discountPercent: 10) };
// Старая роль (3 конфига, без скидки): 200*3 = 600. Новая (10 конфигов, порог скидки достигнут):
// Старый тариф (3 конфига, без скидки): 200*3 = 600. Новый (10 конфигов, порог скидки достигнут):
// 200*10 = 2000, -10% = 1800. Разница 1200 ₽/мес, за 30 дней — 1200 ₽.
var amount = RoleChangeTopUp.Compute(
var amount = PlanChangeTopUp.Compute(
pricePerConfigPerMonth: 200,
oldMaxConfigs: 3,
newMaxConfigs: 10,
oldConfigCount: 3,
newConfigCount: 10,
discountTiers: tiers,
paidUntil: Now.AddDays(30),
now: Now
@@ -0,0 +1,31 @@
using PnvPanel.Domain.Plans;
using Xunit;
namespace PnvPanel.Domain.Tests.Plans;
public class PlanTests
{
[Fact]
public void Create_SetsFieldsAndEnablesByDefault()
{
var plan = Plan.Create("Стандарт", 3, 0);
Assert.Equal("Стандарт", plan.Name);
Assert.Equal(3, plan.ConfigCount);
Assert.Equal(0, plan.SortOrder);
Assert.True(plan.IsEnabled);
}
[Fact]
public void Update_ChangesFieldsIncludingIsEnabled()
{
var plan = Plan.Create("Стандарт", 3, 0);
plan.Update("Плюс", 6, 1, false);
Assert.Equal("Плюс", plan.Name);
Assert.Equal(6, plan.ConfigCount);
Assert.Equal(1, plan.SortOrder);
Assert.False(plan.IsEnabled);
}
}
@@ -16,33 +16,7 @@ public class SupportTicketTests
Assert.Equal(userId, ticket.UserId);
Assert.Equal(TicketType.BugReport, ticket.Type);
Assert.Equal(TicketStatus.Open, ticket.Status);
Assert.Null(ticket.RequestedRoleId);
Assert.Null(ticket.ProposedRoleName);
}
[Fact]
public void CreateRoleRequestForExistingRole_SetsRequestedRoleId()
{
var userId = Guid.NewGuid();
var roleId = Guid.NewGuid();
var ticket = SupportTicket.CreateRoleRequestForExistingRole(userId, roleId);
Assert.Equal(TicketType.RoleRequest, ticket.Type);
Assert.Equal(roleId, ticket.RequestedRoleId);
Assert.Null(ticket.ProposedRoleName);
}
[Fact]
public void CreateRoleRequestForNewRole_SetsProposedFields()
{
var ticket = SupportTicket.CreateRoleRequestForNewRole(Guid.NewGuid(), "premium", 5, 3);
Assert.Equal(TicketType.RoleRequest, ticket.Type);
Assert.Null(ticket.RequestedRoleId);
Assert.Equal("premium", ticket.ProposedRoleName);
Assert.Equal(5, ticket.ProposedMaxConfigs);
Assert.Equal(3, ticket.ProposedMaxIpLimit);
Assert.Null(ticket.RequestedDays);
}
[Fact]
@@ -56,8 +30,6 @@ public class SupportTicketTests
Assert.Equal(TicketType.ExtensionRequest, ticket.Type);
Assert.Equal(TicketStatus.Open, ticket.Status);
Assert.Equal(14, ticket.RequestedDays);
Assert.Null(ticket.RequestedRoleId);
Assert.Null(ticket.ProposedRoleName);
}
[Fact]
@@ -11,7 +11,7 @@ public class ConfigQuotaTests(PnvPanelWebApplicationFactory factory)
private const int Quota = 2;
private const int ConcurrentAttempts = 6;
private sealed record RoleResponse(Guid Id, string Name, int MaxConfigs, bool IsSystem);
private sealed record RoleResponse(Guid Id, string Name, bool IsSystem);
private sealed record NodeResponse(Guid Id, string Name);
@@ -33,7 +33,7 @@ public class ConfigQuotaTests(PnvPanelWebApplicationFactory factory)
DateTimeOffset CreatedAt
);
private sealed record MyConfigsResponse(List<object> Configs, int MaxConfigs);
private sealed record MyConfigsResponse(List<object> Configs, int ConfigQuota);
/// <summary>
/// Доказывает, что pg_advisory_xact_lock в CreateVpnConfigCommandHandler реально защищает
@@ -54,7 +54,7 @@ public class ConfigQuotaTests(PnvPanelWebApplicationFactory factory)
var updateRoleResponse = await adminClient.SendPutJsonAsync(
$"/api/admin/roles/{userRole.Id}",
new { maxConfigs = Quota, maxIpLimit = -1 }
new { maxIpLimit = -1, billingEnabled = false }
);
Assert.Equal(HttpStatusCode.OK, updateRoleResponse.StatusCode);
@@ -109,6 +109,13 @@ public class ConfigQuotaTests(PnvPanelWebApplicationFactory factory)
);
Assert.Equal(HttpStatusCode.NoContent, approveResponse.StatusCode);
// Квота конфигов больше не на роли — пользователь сам выбирает тариф (см. ChangePlanCommand).
var changePlanResponse = await userClient.PostJsonAsync(
"/api/plans/change",
new { customConfigCount = Quota, configIdsToRevoke = Array.Empty<Guid>() }
);
Assert.Equal(HttpStatusCode.OK, changePlanResponse.StatusCode);
var tasks = Enumerable
.Range(0, ConcurrentAttempts)
.Select(async i =>