Refactor client update handling to support nullable parameters for name and expiration
- Updated the `UpdateClientAsync` method in `IXuiPanelGateway` to accept nullable parameters for `name` and `expiresAt`, allowing for more flexible client management without unintended modifications. - Adjusted the `BlockUserCommandHandler`, `UnblockUserCommandHandler`, and other related command handlers to utilize the new nullable parameters, ensuring that client names remain unchanged during block/unblock operations and that expiration dates are managed correctly. - Enhanced the billing and configuration handling to reflect the new logic for managing client states based on expiration rather than enabling/disabling, improving reliability in client status management. - Updated tests to cover the new behavior and ensure proper functionality across the application.
This commit is contained in:
@@ -42,13 +42,17 @@ public sealed class BlockUserCommandHandler(
|
|||||||
|
|
||||||
if (inbound is not null && node is not null)
|
if (inbound is not null && node is not null)
|
||||||
{
|
{
|
||||||
|
// name: null — не трогаем текущее имя клиента в панели, это не переименование.
|
||||||
|
// expiresAt: null — блокировка админом отдельная ось от биллинга (см.
|
||||||
|
// IXuiPanelGateway.UpdateClientAsync), срок оплаты не трогаем.
|
||||||
var updateResult = await gateway.UpdateClientAsync(
|
var updateResult = await gateway.UpdateClientAsync(
|
||||||
node,
|
node,
|
||||||
inbound.RemoteInboundId,
|
inbound.RemoteInboundId,
|
||||||
config.ClientExternalId,
|
config.ClientExternalId,
|
||||||
config.Protocol,
|
config.Protocol,
|
||||||
config.Label ?? config.ClientEmail,
|
name: null,
|
||||||
enable: false,
|
enable: false,
|
||||||
|
expiresAt: null,
|
||||||
cancellationToken
|
cancellationToken
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -47,13 +47,17 @@ public sealed class UnblockUserCommandHandler(
|
|||||||
|
|
||||||
if (inbound is not null && node is not null)
|
if (inbound is not null && node is not null)
|
||||||
{
|
{
|
||||||
|
// name: null — не трогаем текущее имя клиента в панели, это не переименование.
|
||||||
|
// expiresAt: null — блокировка админом отдельная ось от биллинга (см.
|
||||||
|
// IXuiPanelGateway.UpdateClientAsync), срок оплаты не трогаем.
|
||||||
var updateResult = await gateway.UpdateClientAsync(
|
var updateResult = await gateway.UpdateClientAsync(
|
||||||
node,
|
node,
|
||||||
inbound.RemoteInboundId,
|
inbound.RemoteInboundId,
|
||||||
config.ClientExternalId,
|
config.ClientExternalId,
|
||||||
config.Protocol,
|
config.Protocol,
|
||||||
config.Label ?? config.ClientEmail,
|
name: null,
|
||||||
enable: true,
|
enable: true,
|
||||||
|
expiresAt: null,
|
||||||
cancellationToken
|
cancellationToken
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -47,13 +47,18 @@ internal static class BillingConfigResumer
|
|||||||
|
|
||||||
if (inbound is not null && node is not null)
|
if (inbound is not null && node is not null)
|
||||||
{
|
{
|
||||||
|
// Возвращаем через expiryTime = новый newPaidUntil, а не enable:true — тот же
|
||||||
|
// механизм приостановки, что и у BillingService (см. IXuiPanelGateway.UpdateClientAsync):
|
||||||
|
// переписываем просроченную дату на настоящую, панель/Xray сами перестают считать
|
||||||
|
// клиента истёкшим. name: null — не переименовываем клиента.
|
||||||
var updateResult = await gateway.UpdateClientAsync(
|
var updateResult = await gateway.UpdateClientAsync(
|
||||||
node,
|
node,
|
||||||
inbound.RemoteInboundId,
|
inbound.RemoteInboundId,
|
||||||
config.ClientExternalId,
|
config.ClientExternalId,
|
||||||
config.Protocol,
|
config.Protocol,
|
||||||
config.Label ?? config.ClientEmail,
|
name: null,
|
||||||
enable: true,
|
enable: null,
|
||||||
|
expiresAt: newPaidUntil,
|
||||||
cancellationToken
|
cancellationToken
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -36,6 +36,8 @@ public interface IXuiPanelGateway
|
|||||||
/// Возвращает ClientExternalId, присвоенный панелью (UUID для VLESS/VMess, пароль для Trojan/Shadowsocks).
|
/// Возвращает ClientExternalId, присвоенный панелью (UUID для VLESS/VMess, пароль для Trojan/Shadowsocks).
|
||||||
/// <paramref name="limitIp"/> — лимит одновременных IP клиента (квота роли, см. AppRole.MaxIpLimit);
|
/// <paramref name="limitIp"/> — лимит одновременных IP клиента (квота роли, см. AppRole.MaxIpLimit);
|
||||||
/// -1 (RoleQuota.Unlimited) означает без лимита — гейтвей сам переводит его в нативное значение 3x-ui.
|
/// -1 (RoleQuota.Unlimited) означает без лимита — гейтвей сам переводит его в нативное значение 3x-ui.
|
||||||
|
/// <paramref name="expiresAt"/> — дата, до которой клиент активен в самой панели (billing-роли —
|
||||||
|
/// AppUser.BillingPaidUntil на момент создания); <c>null</c> — без ограничения по сроку.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
Task<Result<string>> AddClientAsync(
|
Task<Result<string>> AddClientAsync(
|
||||||
Node node,
|
Node node,
|
||||||
@@ -44,6 +46,7 @@ public interface IXuiPanelGateway
|
|||||||
string clientEmail,
|
string clientEmail,
|
||||||
string clientName,
|
string clientName,
|
||||||
int limitIp,
|
int limitIp,
|
||||||
|
DateTimeOffset? expiresAt,
|
||||||
CancellationToken cancellationToken
|
CancellationToken cancellationToken
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -55,13 +58,35 @@ public interface IXuiPanelGateway
|
|||||||
CancellationToken cancellationToken
|
CancellationToken cancellationToken
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Все параметры, кроме обязательных идентификаторов, — "не трогать, если null" (см. ThreeXui.Net
|
||||||
|
/// UpdateClientRequest: "All fields optional — null means leave as is").
|
||||||
|
/// <para>
|
||||||
|
/// <paramref name="name"/> — НЕ отдельная косметическая метка: у клиента 3x-ui нет своего поля
|
||||||
|
/// remark/comment, поэтому ThreeXui.Net пишет её в то же поле <c>settings.clients[].email</c>,
|
||||||
|
/// которое AddClientAsync изначально заполняет стабильным ClientEmail. Передавайте <c>null</c>
|
||||||
|
/// для любого вызова, не являющегося намеренным переименованием — иначе затрёте панельный
|
||||||
|
/// identity-идентификатор клиента (и сломаете сопоставление по email в GetClientTrafficAsync).
|
||||||
|
/// Единственный легитимный вызывающий с непустым name — EditVpnConfigCommandHandler.
|
||||||
|
/// </para>
|
||||||
|
/// <para>
|
||||||
|
/// <paramref name="expiresAt"/> — используется для приостановки/возврата за неуплату
|
||||||
|
/// (BillingService/BillingConfigResumer): дата в прошлом делает клиента просроченным для самой
|
||||||
|
/// панели/Xray независимо от <paramref name="enable"/> (по факту тестирования — переключение
|
||||||
|
/// enable ненадёжно останавливает уже установленные соединения, а expiryTime — надёжно), дата в
|
||||||
|
/// будущем (новый AppUser.BillingPaidUntil) снимает приостановку. Блокировка/разблокировка
|
||||||
|
/// админом (BlockUserCommandHandler/UnblockUserCommandHandler) — отдельная ось, передаёт
|
||||||
|
/// <c>expiresAt: null</c> и управляет только <paramref name="enable"/>.
|
||||||
|
/// </para>
|
||||||
|
/// </summary>
|
||||||
Task<Result> UpdateClientAsync(
|
Task<Result> UpdateClientAsync(
|
||||||
Node node,
|
Node node,
|
||||||
string inboundRemoteId,
|
string inboundRemoteId,
|
||||||
string clientExternalId,
|
string clientExternalId,
|
||||||
VpnProtocol protocol,
|
VpnProtocol protocol,
|
||||||
string name,
|
string? name,
|
||||||
bool enable,
|
bool? enable,
|
||||||
|
DateTimeOffset? expiresAt,
|
||||||
CancellationToken cancellationToken
|
CancellationToken cancellationToken
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -73,6 +73,8 @@ public sealed class CreateVpnConfigCommandHandler(
|
|||||||
config.ClientEmail,
|
config.ClientEmail,
|
||||||
config.Label ?? config.ClientEmail,
|
config.Label ?? config.ClientEmail,
|
||||||
profile.MaxIpLimit,
|
profile.MaxIpLimit,
|
||||||
|
// BillingRequired-проверка выше гарантирует, что при BillingEnabled PaidUntil уже в будущем.
|
||||||
|
expiresAt: profile.BillingEnabled ? profile.BillingPaidUntil : null,
|
||||||
cancellationToken
|
cancellationToken
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -42,13 +42,17 @@ public sealed class EditVpnConfigCommandHandler(
|
|||||||
.FirstOrDefaultAsync(n => n.Id == inbound.NodeId, cancellationToken);
|
.FirstOrDefaultAsync(n => n.Id == inbound.NodeId, cancellationToken);
|
||||||
if (node is not null)
|
if (node is not null)
|
||||||
{
|
{
|
||||||
|
// enable/expiresAt: null — переименование не должно снимать приостановку/блокировку
|
||||||
|
// клиента (раньше здесь стояло enable:true и молча реактивировало погашенный за
|
||||||
|
// неуплату/блокировку конфиг просто оттого, что пользователь его переименовал).
|
||||||
var updateResult = await gateway.UpdateClientAsync(
|
var updateResult = await gateway.UpdateClientAsync(
|
||||||
node,
|
node,
|
||||||
inbound.RemoteInboundId,
|
inbound.RemoteInboundId,
|
||||||
config.ClientExternalId,
|
config.ClientExternalId,
|
||||||
config.Protocol,
|
config.Protocol,
|
||||||
command.Label,
|
command.Label,
|
||||||
enable: true,
|
enable: null,
|
||||||
|
expiresAt: null,
|
||||||
cancellationToken
|
cancellationToken
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -56,6 +56,9 @@ public sealed class RotateVpnConfigCommandHandler(
|
|||||||
newClientEmail,
|
newClientEmail,
|
||||||
config.Label ?? newClientEmail,
|
config.Label ?? newClientEmail,
|
||||||
profile.MaxIpLimit,
|
profile.MaxIpLimit,
|
||||||
|
// Переносим уже действующий срок (billing paidUntil) на нового клиента — ротация не должна
|
||||||
|
// ни продлевать, ни сбрасывать оплаченный период.
|
||||||
|
expiresAt: config.ExpiresAt,
|
||||||
cancellationToken
|
cancellationToken
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -139,13 +139,18 @@ public sealed class BillingService(
|
|||||||
|
|
||||||
if (inbound is not null && node is not null)
|
if (inbound is not null && node is not null)
|
||||||
{
|
{
|
||||||
|
// Приостанавливаем через expiryTime в прошлом, а не enable:false — переключение enable
|
||||||
|
// ненадёжно останавливает уже установленные соединения на стороне Xray/панели (см.
|
||||||
|
// IXuiPanelGateway.UpdateClientAsync), просроченный expiryTime — надёжно и независимо
|
||||||
|
// от enable. name: null — не переименовываем клиента.
|
||||||
var updateResult = await gateway.UpdateClientAsync(
|
var updateResult = await gateway.UpdateClientAsync(
|
||||||
node,
|
node,
|
||||||
inbound.RemoteInboundId,
|
inbound.RemoteInboundId,
|
||||||
config.ClientExternalId,
|
config.ClientExternalId,
|
||||||
config.Protocol,
|
config.Protocol,
|
||||||
config.Label ?? config.ClientEmail,
|
name: null,
|
||||||
enable: false,
|
enable: null,
|
||||||
|
expiresAt: DateTimeOffset.UtcNow.AddDays(-1),
|
||||||
cancellationToken
|
cancellationToken
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -92,6 +92,7 @@ internal sealed class XuiPanelGateway(
|
|||||||
string clientEmail,
|
string clientEmail,
|
||||||
string clientName,
|
string clientName,
|
||||||
int limitIp,
|
int limitIp,
|
||||||
|
DateTimeOffset? expiresAt,
|
||||||
CancellationToken cancellationToken
|
CancellationToken cancellationToken
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
@@ -105,7 +106,7 @@ internal sealed class XuiPanelGateway(
|
|||||||
clientEmail,
|
clientEmail,
|
||||||
ToRemoteProtocol(protocol),
|
ToRemoteProtocol(protocol),
|
||||||
limitIp == RoleQuota.Unlimited ? 0 : limitIp,
|
limitIp == RoleQuota.Unlimited ? 0 : limitIp,
|
||||||
null
|
expiresAt
|
||||||
);
|
);
|
||||||
var result = await client.AddClientAsync(inboundRemoteId, request, cancellationToken);
|
var result = await client.AddClientAsync(inboundRemoteId, request, cancellationToken);
|
||||||
return Result.Success(result.ExternalClientId);
|
return Result.Success(result.ExternalClientId);
|
||||||
@@ -150,16 +151,17 @@ internal sealed class XuiPanelGateway(
|
|||||||
string inboundRemoteId,
|
string inboundRemoteId,
|
||||||
string clientExternalId,
|
string clientExternalId,
|
||||||
VpnProtocol protocol,
|
VpnProtocol protocol,
|
||||||
string name,
|
string? name,
|
||||||
bool enable,
|
bool? enable,
|
||||||
|
DateTimeOffset? expiresAt,
|
||||||
CancellationToken cancellationToken
|
CancellationToken cancellationToken
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var client = GetClient(node);
|
var client = GetClient(node);
|
||||||
// deviceLimit: null — не трогаем то, что уже стоит на клиенте в панели (см. AddClientAsync).
|
// limitIp: null — не трогаем то, что уже стоит на клиенте в панели (см. AddClientAsync).
|
||||||
var request = new UpdateClientRequest(null, null, enable, name);
|
var request = new UpdateClientRequest(null, expiresAt, enable, name);
|
||||||
await client.UpdateClientAsync(
|
await client.UpdateClientAsync(
|
||||||
inboundRemoteId,
|
inboundRemoteId,
|
||||||
clientExternalId,
|
clientExternalId,
|
||||||
|
|||||||
+6
-2
@@ -167,7 +167,8 @@ public class ConfirmPaymentRequestCommandHandlerTests
|
|||||||
Arg.Any<string>(),
|
Arg.Any<string>(),
|
||||||
Arg.Any<VpnProtocol>(),
|
Arg.Any<VpnProtocol>(),
|
||||||
Arg.Any<string>(),
|
Arg.Any<string>(),
|
||||||
enable: true,
|
Arg.Any<bool?>(),
|
||||||
|
Arg.Any<DateTimeOffset?>(),
|
||||||
Arg.Any<CancellationToken>()
|
Arg.Any<CancellationToken>()
|
||||||
)
|
)
|
||||||
.Returns(Result.Success());
|
.Returns(Result.Success());
|
||||||
@@ -192,6 +193,8 @@ public class ConfirmPaymentRequestCommandHandlerTests
|
|||||||
Assert.NotNull(expiredConfig.ExpiresAt);
|
Assert.NotNull(expiredConfig.ExpiresAt);
|
||||||
Assert.NotNull(activeConfig.ExpiresAt);
|
Assert.NotNull(activeConfig.ExpiresAt);
|
||||||
Assert.Equal(expiredConfig.ExpiresAt, activeConfig.ExpiresAt);
|
Assert.Equal(expiredConfig.ExpiresAt, activeConfig.ExpiresAt);
|
||||||
|
// enable: null — возврат из приостановки теперь идёт через expiresAt (новый newPaidUntil),
|
||||||
|
// а не через переключение enable (см. IXuiPanelGateway.UpdateClientAsync).
|
||||||
await _gateway
|
await _gateway
|
||||||
.Received(1)
|
.Received(1)
|
||||||
.UpdateClientAsync(
|
.UpdateClientAsync(
|
||||||
@@ -200,7 +203,8 @@ public class ConfirmPaymentRequestCommandHandlerTests
|
|||||||
"ext-1",
|
"ext-1",
|
||||||
VpnProtocol.Vless,
|
VpnProtocol.Vless,
|
||||||
Arg.Any<string>(),
|
Arg.Any<string>(),
|
||||||
enable: true,
|
null,
|
||||||
|
Arg.Is<DateTimeOffset?>(d => d == expiredConfig.ExpiresAt),
|
||||||
Arg.Any<CancellationToken>()
|
Arg.Any<CancellationToken>()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-1
@@ -128,7 +128,8 @@ public class ApproveExtensionRequestCommandHandlerTests
|
|||||||
Arg.Any<string>(),
|
Arg.Any<string>(),
|
||||||
Arg.Any<VpnProtocol>(),
|
Arg.Any<VpnProtocol>(),
|
||||||
Arg.Any<string>(),
|
Arg.Any<string>(),
|
||||||
enable: true,
|
Arg.Any<bool?>(),
|
||||||
|
Arg.Any<DateTimeOffset?>(),
|
||||||
Arg.Any<CancellationToken>()
|
Arg.Any<CancellationToken>()
|
||||||
)
|
)
|
||||||
.Returns(Result.Success());
|
.Returns(Result.Success());
|
||||||
|
|||||||
+12
-5
@@ -54,7 +54,8 @@ public class BlockUserCommandHandlerTests
|
|||||||
Arg.Any<string>(),
|
Arg.Any<string>(),
|
||||||
Arg.Any<VpnProtocol>(),
|
Arg.Any<VpnProtocol>(),
|
||||||
Arg.Any<string>(),
|
Arg.Any<string>(),
|
||||||
Arg.Any<bool>(),
|
Arg.Any<bool?>(),
|
||||||
|
Arg.Any<DateTimeOffset?>(),
|
||||||
Arg.Any<CancellationToken>()
|
Arg.Any<CancellationToken>()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -91,7 +92,8 @@ public class BlockUserCommandHandlerTests
|
|||||||
Arg.Any<string>(),
|
Arg.Any<string>(),
|
||||||
Arg.Any<VpnProtocol>(),
|
Arg.Any<VpnProtocol>(),
|
||||||
Arg.Any<string>(),
|
Arg.Any<string>(),
|
||||||
Arg.Any<bool>(),
|
Arg.Any<bool?>(),
|
||||||
|
Arg.Any<DateTimeOffset?>(),
|
||||||
Arg.Any<CancellationToken>()
|
Arg.Any<CancellationToken>()
|
||||||
)
|
)
|
||||||
.Returns(Result.Success());
|
.Returns(Result.Success());
|
||||||
@@ -111,6 +113,8 @@ public class BlockUserCommandHandlerTests
|
|||||||
Assert.True(result.IsSuccess);
|
Assert.True(result.IsSuccess);
|
||||||
Assert.Equal(ConfigStatus.Disabled, config.Status);
|
Assert.Equal(ConfigStatus.Disabled, config.Status);
|
||||||
|
|
||||||
|
// name: null — блокировка не переименовывает клиента; expiresAt: null — блокировка не трогает
|
||||||
|
// срок оплаты (см. IXuiPanelGateway.UpdateClientAsync).
|
||||||
await _gateway
|
await _gateway
|
||||||
.Received(1)
|
.Received(1)
|
||||||
.UpdateClientAsync(
|
.UpdateClientAsync(
|
||||||
@@ -118,8 +122,9 @@ public class BlockUserCommandHandlerTests
|
|||||||
inbound.RemoteInboundId,
|
inbound.RemoteInboundId,
|
||||||
config.ClientExternalId,
|
config.ClientExternalId,
|
||||||
config.Protocol,
|
config.Protocol,
|
||||||
"my-config",
|
null,
|
||||||
enable: false,
|
enable: false,
|
||||||
|
expiresAt: null,
|
||||||
Arg.Any<CancellationToken>()
|
Arg.Any<CancellationToken>()
|
||||||
);
|
);
|
||||||
await _notifier
|
await _notifier
|
||||||
@@ -168,7 +173,8 @@ public class BlockUserCommandHandlerTests
|
|||||||
Arg.Any<string>(),
|
Arg.Any<string>(),
|
||||||
Arg.Any<VpnProtocol>(),
|
Arg.Any<VpnProtocol>(),
|
||||||
Arg.Any<string>(),
|
Arg.Any<string>(),
|
||||||
Arg.Any<bool>(),
|
Arg.Any<bool?>(),
|
||||||
|
Arg.Any<DateTimeOffset?>(),
|
||||||
Arg.Any<CancellationToken>()
|
Arg.Any<CancellationToken>()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -205,7 +211,8 @@ public class BlockUserCommandHandlerTests
|
|||||||
Arg.Any<string>(),
|
Arg.Any<string>(),
|
||||||
Arg.Any<VpnProtocol>(),
|
Arg.Any<VpnProtocol>(),
|
||||||
Arg.Any<string>(),
|
Arg.Any<string>(),
|
||||||
Arg.Any<bool>(),
|
Arg.Any<bool?>(),
|
||||||
|
Arg.Any<DateTimeOffset?>(),
|
||||||
Arg.Any<CancellationToken>()
|
Arg.Any<CancellationToken>()
|
||||||
)
|
)
|
||||||
.Returns(Result.Failure(Error.Failure("Xui.UpdateClientFailed", "Нода недоступна.")));
|
.Returns(Result.Failure(Error.Failure("Xui.UpdateClientFailed", "Нода недоступна.")));
|
||||||
|
|||||||
+5
-2
@@ -54,7 +54,8 @@ public class UnblockUserCommandHandlerTests
|
|||||||
Arg.Any<string>(),
|
Arg.Any<string>(),
|
||||||
Arg.Any<VpnProtocol>(),
|
Arg.Any<VpnProtocol>(),
|
||||||
Arg.Any<string>(),
|
Arg.Any<string>(),
|
||||||
Arg.Any<bool>(),
|
Arg.Any<bool?>(),
|
||||||
|
Arg.Any<DateTimeOffset?>(),
|
||||||
Arg.Any<CancellationToken>()
|
Arg.Any<CancellationToken>()
|
||||||
)
|
)
|
||||||
.Returns(Result.Success());
|
.Returns(Result.Success());
|
||||||
@@ -81,6 +82,7 @@ public class UnblockUserCommandHandlerTests
|
|||||||
config.Protocol,
|
config.Protocol,
|
||||||
Arg.Any<string>(),
|
Arg.Any<string>(),
|
||||||
true,
|
true,
|
||||||
|
null,
|
||||||
Arg.Any<CancellationToken>()
|
Arg.Any<CancellationToken>()
|
||||||
);
|
);
|
||||||
await _notifier
|
await _notifier
|
||||||
@@ -155,7 +157,8 @@ public class UnblockUserCommandHandlerTests
|
|||||||
Arg.Any<string>(),
|
Arg.Any<string>(),
|
||||||
Arg.Any<VpnProtocol>(),
|
Arg.Any<VpnProtocol>(),
|
||||||
Arg.Any<string>(),
|
Arg.Any<string>(),
|
||||||
Arg.Any<bool>(),
|
Arg.Any<bool?>(),
|
||||||
|
Arg.Any<DateTimeOffset?>(),
|
||||||
Arg.Any<CancellationToken>()
|
Arg.Any<CancellationToken>()
|
||||||
)
|
)
|
||||||
.Returns(Result.Failure(Error.Failure("Xui.UpdateClientFailed", "Нода недоступна.")));
|
.Returns(Result.Failure(Error.Failure("Xui.UpdateClientFailed", "Нода недоступна.")));
|
||||||
|
|||||||
+128
@@ -0,0 +1,128 @@
|
|||||||
|
using NSubstitute;
|
||||||
|
using PnvPanel.Application.Common.Interfaces;
|
||||||
|
using PnvPanel.Application.Common.Models;
|
||||||
|
using PnvPanel.Application.Configs;
|
||||||
|
using PnvPanel.Application.Configs.Create;
|
||||||
|
using PnvPanel.Application.Tests.TestSupport;
|
||||||
|
using PnvPanel.Domain.Inbounds;
|
||||||
|
using PnvPanel.Infrastructure.Persistence;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace PnvPanel.Application.Tests.Configs.Create;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Только ветки ДО ReserveQuotaSlotAsync (billing-guard) — дальше хендлер уходит в
|
||||||
|
/// pg_advisory_xact_lock, который InMemory-провайдер не поддерживает (см. CLAUDE.md/
|
||||||
|
/// ConfigQuotaTests в IntegrationTests для позитивного пути и гонок).
|
||||||
|
/// </summary>
|
||||||
|
public class CreateVpnConfigCommandHandlerTests
|
||||||
|
{
|
||||||
|
private readonly IIdentityService _identityService = Substitute.For<IIdentityService>();
|
||||||
|
private readonly IXuiPanelGateway _gateway = Substitute.For<IXuiPanelGateway>();
|
||||||
|
|
||||||
|
private static CurrentUserProfile Profile(
|
||||||
|
Guid userId,
|
||||||
|
Guid roleId,
|
||||||
|
bool billingEnabled,
|
||||||
|
DateTimeOffset? billingPaidUntil
|
||||||
|
) =>
|
||||||
|
new(
|
||||||
|
userId,
|
||||||
|
"alice",
|
||||||
|
roleId,
|
||||||
|
"premium",
|
||||||
|
IsActivated: true,
|
||||||
|
IsBlocked: false,
|
||||||
|
MaxConfigs: 5,
|
||||||
|
MaxIpLimit: 3,
|
||||||
|
SubscriptionToken: "sub-token",
|
||||||
|
BillingEnabled: billingEnabled,
|
||||||
|
BillingPaidUntil: billingPaidUntil,
|
||||||
|
BillingSuspended: false
|
||||||
|
);
|
||||||
|
|
||||||
|
private async Task<(Inbound inbound, Guid roleId)> SeedAllowedInboundAsync(AppDbContext dbContext)
|
||||||
|
{
|
||||||
|
var roleId = Guid.NewGuid();
|
||||||
|
var node = Domain.Nodes.Node.Register(
|
||||||
|
"node-1",
|
||||||
|
new Uri("https://node1.example.com"),
|
||||||
|
new Domain.Nodes.NodeCredentials("admin", "protected"),
|
||||||
|
null
|
||||||
|
);
|
||||||
|
var inbound = Inbound.FromRemote(node.Id, "1", VpnProtocol.Vless, "remark", 443);
|
||||||
|
inbound.Publish(null, [roleId]);
|
||||||
|
|
||||||
|
dbContext.Nodes.Add(node);
|
||||||
|
dbContext.Inbounds.Add(inbound);
|
||||||
|
await dbContext.SaveChangesAsync(CancellationToken.None);
|
||||||
|
|
||||||
|
return (inbound, roleId);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Handle_WhenBillingEnabledAndPaidUntilExpired_ReturnsBillingRequired()
|
||||||
|
{
|
||||||
|
using var dbContext = InMemoryDbContextFactory.Create();
|
||||||
|
var userId = Guid.NewGuid();
|
||||||
|
var (inbound, roleId) = await SeedAllowedInboundAsync(dbContext);
|
||||||
|
|
||||||
|
_identityService
|
||||||
|
.GetProfileAsync(userId, Arg.Any<CancellationToken>())
|
||||||
|
.Returns(Profile(userId, roleId, billingEnabled: true, billingPaidUntil: DateTimeOffset.UtcNow.AddDays(-1)));
|
||||||
|
|
||||||
|
var handler = new CreateVpnConfigCommandHandler(
|
||||||
|
dbContext,
|
||||||
|
_identityService,
|
||||||
|
_gateway,
|
||||||
|
FakeCurrentUser.Authenticated(userId)
|
||||||
|
);
|
||||||
|
|
||||||
|
var result = await handler.Handle(
|
||||||
|
new CreateVpnConfigCommand(inbound.Id, null),
|
||||||
|
CancellationToken.None
|
||||||
|
);
|
||||||
|
|
||||||
|
Assert.False(result.IsSuccess);
|
||||||
|
Assert.Equal(ConfigErrors.BillingRequired, result.Error);
|
||||||
|
await _gateway
|
||||||
|
.DidNotReceive()
|
||||||
|
.AddClientAsync(
|
||||||
|
Arg.Any<Domain.Nodes.Node>(),
|
||||||
|
Arg.Any<string>(),
|
||||||
|
Arg.Any<VpnProtocol>(),
|
||||||
|
Arg.Any<string>(),
|
||||||
|
Arg.Any<string>(),
|
||||||
|
Arg.Any<int>(),
|
||||||
|
Arg.Any<DateTimeOffset?>(),
|
||||||
|
Arg.Any<CancellationToken>()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Handle_WhenBillingEnabledAndPaidUntilNull_ReturnsBillingRequired()
|
||||||
|
{
|
||||||
|
using var dbContext = InMemoryDbContextFactory.Create();
|
||||||
|
var userId = Guid.NewGuid();
|
||||||
|
var (inbound, roleId) = await SeedAllowedInboundAsync(dbContext);
|
||||||
|
|
||||||
|
_identityService
|
||||||
|
.GetProfileAsync(userId, Arg.Any<CancellationToken>())
|
||||||
|
.Returns(Profile(userId, roleId, billingEnabled: true, billingPaidUntil: null));
|
||||||
|
|
||||||
|
var handler = new CreateVpnConfigCommandHandler(
|
||||||
|
dbContext,
|
||||||
|
_identityService,
|
||||||
|
_gateway,
|
||||||
|
FakeCurrentUser.Authenticated(userId)
|
||||||
|
);
|
||||||
|
|
||||||
|
var result = await handler.Handle(
|
||||||
|
new CreateVpnConfigCommand(inbound.Id, null),
|
||||||
|
CancellationToken.None
|
||||||
|
);
|
||||||
|
|
||||||
|
Assert.False(result.IsSuccess);
|
||||||
|
Assert.Equal(ConfigErrors.BillingRequired, result.Error);
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
@@ -65,6 +65,7 @@ public class RotateVpnConfigCommandHandlerTests
|
|||||||
Arg.Any<string>(),
|
Arg.Any<string>(),
|
||||||
Arg.Any<string>(),
|
Arg.Any<string>(),
|
||||||
Arg.Any<int>(),
|
Arg.Any<int>(),
|
||||||
|
Arg.Any<DateTimeOffset?>(),
|
||||||
Arg.Any<CancellationToken>()
|
Arg.Any<CancellationToken>()
|
||||||
)
|
)
|
||||||
.Returns(Result.Success("new-external-id"));
|
.Returns(Result.Success("new-external-id"));
|
||||||
@@ -209,6 +210,7 @@ public class RotateVpnConfigCommandHandlerTests
|
|||||||
Arg.Any<string>(),
|
Arg.Any<string>(),
|
||||||
Arg.Any<string>(),
|
Arg.Any<string>(),
|
||||||
Arg.Any<int>(),
|
Arg.Any<int>(),
|
||||||
|
Arg.Any<DateTimeOffset?>(),
|
||||||
Arg.Any<CancellationToken>()
|
Arg.Any<CancellationToken>()
|
||||||
)
|
)
|
||||||
.Returns(Result.Failure<string>(gatewayError));
|
.Returns(Result.Failure<string>(gatewayError));
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ public sealed class FakeXuiPanelGateway : IXuiPanelGateway
|
|||||||
string clientEmail,
|
string clientEmail,
|
||||||
string clientName,
|
string clientName,
|
||||||
int limitIp,
|
int limitIp,
|
||||||
|
DateTimeOffset? expiresAt,
|
||||||
CancellationToken cancellationToken
|
CancellationToken cancellationToken
|
||||||
) => Task.FromResult(Result.Success(Guid.NewGuid().ToString()));
|
) => Task.FromResult(Result.Success(Guid.NewGuid().ToString()));
|
||||||
|
|
||||||
@@ -54,8 +55,9 @@ public sealed class FakeXuiPanelGateway : IXuiPanelGateway
|
|||||||
string inboundRemoteId,
|
string inboundRemoteId,
|
||||||
string clientExternalId,
|
string clientExternalId,
|
||||||
VpnProtocol protocol,
|
VpnProtocol protocol,
|
||||||
string name,
|
string? name,
|
||||||
bool enable,
|
bool? enable,
|
||||||
|
DateTimeOffset? expiresAt,
|
||||||
CancellationToken cancellationToken
|
CancellationToken cancellationToken
|
||||||
) => Task.FromResult(Result.Success());
|
) => Task.FromResult(Result.Success());
|
||||||
|
|
||||||
|
|||||||
+26
-2
@@ -492,7 +492,7 @@ Singleton (как `PricingSettings`) — реквизиты для оплаты
|
|||||||
висит на подтверждении админом, а срок истёк» из требований: конфиги не гасятся, пока админ не
|
висит на подтверждении админом, а срок истёк» из требований: конфиги не гасятся, пока админ не
|
||||||
решит (не по вине пользователя, что админ не успел проверить оплату);
|
решит (не по вине пользователя, что админ не успел проверить оплату);
|
||||||
- `BillingPaidUntil` в прошлом (или `null`) и ещё не `BillingSuspended` → приостановить все `Active`
|
- `BillingPaidUntil` в прошлом (или `null`) и ещё не `BillingSuspended` → приостановить все `Active`
|
||||||
конфиги (`Suspend()` → `Expired`, гейтвей `UpdateClientAsync(enable:false)`, идемпотентно как в
|
конфиги (`Suspend()` → `Expired`, гейтвей `UpdateClientAsync(expiresAt: вчера)`, идемпотентно как в
|
||||||
`BlockUserCommandHandler`), `AppUser.BillingSuspended = true`, Telegram-уведомление пользователю,
|
`BlockUserCommandHandler`), `AppUser.BillingSuspended = true`, Telegram-уведомление пользователю,
|
||||||
`AuditLog` (`BillingSuspended`, источник `System`). На последующих тиках (уже suspended) — только
|
`AuditLog` (`BillingSuspended`, источник `System`). На последующих тиках (уже suspended) — только
|
||||||
идемпотентная досуспензия «зависших» `Active`-конфигов (самовосстановление после недоступности
|
идемпотентная досуспензия «зависших» `Active`-конфигов (самовосстановление после недоступности
|
||||||
@@ -500,9 +500,33 @@ Singleton (как `PricingSettings`) — реквизиты для оплаты
|
|||||||
- до истечения ≤ 3 дней и предупреждение для этого `PaidUntil` ещё не отправлено
|
- до истечения ≤ 3 дней и предупреждение для этого `PaidUntil` ещё не отправлено
|
||||||
(`BillingLastWarnedForPaidUntil != PaidUntil`) → Telegram-предупреждение, отметка отправки.
|
(`BillingLastWarnedForPaidUntil != PaidUntil`) → Telegram-предупреждение, отметка отправки.
|
||||||
|
|
||||||
|
#### Приостановка/возврат за неуплату — через expiresAt, не enable
|
||||||
|
|
||||||
|
Приостановка за неуплату (`BillingService`) и возврат (`BillingConfigResumer`) управляют панельным
|
||||||
|
клиентом через `IXuiPanelGateway.UpdateClientAsync(..., expiresAt: ..., enable: null, ...)`, а не через
|
||||||
|
`enable: false/true` — по факту эксплуатации переключение `enable` ненадёжно останавливает уже
|
||||||
|
установленные соединения на стороне Xray/панели, а просроченный `expiryTime` — надёжно, и не зависит
|
||||||
|
от `enable`. Конкретно:
|
||||||
|
- **Приостановка**: `expiresAt = UtcNow.AddDays(-1)` — гарантированно просроченная дата, `enable` не
|
||||||
|
трогаем (`null`, «оставить как есть» — см. ThreeXui.Net `UpdateClientRequest`).
|
||||||
|
- **Возврат**: `expiresAt = newPaidUntil` (реальный новый срок оплаты, не «снять ограничение» на
|
||||||
|
бесконечность) — так панель/Xray сама несёт актуальный срок: если `BillingService` вдруг пропустит
|
||||||
|
тик, панель всё равно перестанет пускать по истечении этой даты независимо от приложения.
|
||||||
|
- **Создание** (`CreateVpnConfigCommandHandler`) уже пушит `expiresAt = profile.BillingPaidUntil` при
|
||||||
|
`BillingEnabled` через `AddClientAsync` — свежий конфиг сразу несёт правильный срок, не «без
|
||||||
|
ограничения» до первого цикла `BillingService`.
|
||||||
|
- **Ротация** (`RotateVpnConfigCommandHandler`) переносит текущий `config.ExpiresAt` на нового клиента
|
||||||
|
— ротация не должна ни продлевать, ни сбрасывать оплаченный период.
|
||||||
|
- Блокировка/разблокировка админом (`Disable()`/`Enable()`) — отдельная ось, управляет только
|
||||||
|
`enable`, `expiresAt: null` (не трогает срок оплаты). Переименование (`EditVpnConfigCommandHandler`)
|
||||||
|
— `enable`/`expiresAt: null` (раньше по ошибке форсировало `enable:true`, тем самым молча снимая
|
||||||
|
приостановку/блокировку простым переименованием конфига — исправлено).
|
||||||
|
|
||||||
`CreateVpnConfigCommandHandler` дополнительно не даёт создать **новый** конфиг, если роль billing
|
`CreateVpnConfigCommandHandler` дополнительно не даёт создать **новый** конфиг, если роль billing
|
||||||
и оплата просрочена (`ConfigErrors.BillingRequired`) — иначе приостановку можно было бы обойти
|
и оплата просрочена (`ConfigErrors.BillingRequired`) — иначе приостановку можно было бы обойти
|
||||||
созданием свежего конфига.
|
созданием свежего конфига. Фронт (`dashboard.tsx`) зеркалит эту же проверку и скрывает кнопку создания
|
||||||
|
конфига заранее, а не только реагирует на 403 от сервера (см. `CreateConfigDialog.tsx` — safety-net на
|
||||||
|
случай гонки состояний).
|
||||||
|
|
||||||
`GET/POST /api/billing/*` — пользователь (статус, создание/отмена заявки, «я оплатил», отправка
|
`GET/POST /api/billing/*` — пользователь (статус, создание/отмена заявки, «я оплатил», отправка
|
||||||
реквизитов в свой Telegram). `GET/PUT/POST /api/admin/billing/*` — админ (настройки, список заявок,
|
реквизитов в свой Telegram). `GET/PUT/POST /api/admin/billing/*` — админ (настройки, список заявок,
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import { Plus } from 'lucide-react'
|
import { Plus } from 'lucide-react'
|
||||||
import { toast } from '@/shared/ui/toast-store'
|
import { toast } from '@/shared/ui/toast-store'
|
||||||
@@ -15,6 +16,7 @@ import { createConfig } from './api'
|
|||||||
export function CreateConfigDialog({ inbounds }: { inbounds: AvailableInboundDto[] }) {
|
export function CreateConfigDialog({ inbounds }: { inbounds: AvailableInboundDto[] }) {
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation()
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
|
const navigate = useNavigate()
|
||||||
const [open, setOpen] = useState(false)
|
const [open, setOpen] = useState(false)
|
||||||
const [inboundId, setInboundId] = useState('')
|
const [inboundId, setInboundId] = useState('')
|
||||||
const [label, setLabel] = useState('')
|
const [label, setLabel] = useState('')
|
||||||
@@ -29,6 +31,15 @@ export function CreateConfigDialog({ inbounds }: { inbounds: AvailableInboundDto
|
|||||||
setLabel('')
|
setLabel('')
|
||||||
},
|
},
|
||||||
onError: (error) => {
|
onError: (error) => {
|
||||||
|
// Safety-net: дашборд уже скрывает эту кнопку при истёкшей оплате (см. dashboard.tsx), но
|
||||||
|
// между открытием страницы и отправкой формы биллинг мог протухнуть — сервер всё равно
|
||||||
|
// проверяет (ConfigErrors.BillingRequired) и на всякий случай отправляем на оплату.
|
||||||
|
if (error instanceof HttpError && error.title === 'Configs.BillingRequired') {
|
||||||
|
toast.error(t('configs.billingRequiredNotice'))
|
||||||
|
setOpen(false)
|
||||||
|
void navigate({ to: '/billing' })
|
||||||
|
return
|
||||||
|
}
|
||||||
const message =
|
const message =
|
||||||
error instanceof HttpError && error.status === 409 ? t('configs.quotaExceeded') : t('auth.genericError')
|
error instanceof HttpError && error.status === 409 ? t('configs.quotaExceeded') : t('auth.genericError')
|
||||||
toast.error(message)
|
toast.error(message)
|
||||||
|
|||||||
@@ -30,6 +30,12 @@ function ConfigsList() {
|
|||||||
const inboundsQuery = useQuery({ queryKey: ['available-inbounds'], queryFn: listAvailableInbounds })
|
const inboundsQuery = useQuery({ queryKey: ['available-inbounds'], queryFn: listAvailableInbounds })
|
||||||
const billingStatusQuery = useQuery({ queryKey: ['my-billing-status'], queryFn: getMyBillingStatus })
|
const billingStatusQuery = useQuery({ queryKey: ['my-billing-status'], queryFn: getMyBillingStatus })
|
||||||
|
|
||||||
|
// Зеркалит серверную проверку в CreateVpnConfigCommandHandler (ConfigErrors.BillingRequired) —
|
||||||
|
// роль с биллингом и просроченной/неоплаченной подпиской не может создавать новые конфиги.
|
||||||
|
const billing = billingStatusQuery.data
|
||||||
|
const billingBlocksCreate =
|
||||||
|
!!billing?.billingEnabled && (billing.paidUntil == null || new Date(billing.paidUntil) < new Date())
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto flex w-full max-w-4xl flex-col gap-6 px-6 py-10">
|
<div className="mx-auto flex w-full max-w-4xl flex-col gap-6 px-6 py-10">
|
||||||
<div className="flex items-center justify-between gap-4">
|
<div className="flex items-center justify-between gap-4">
|
||||||
@@ -52,7 +58,14 @@ function ConfigsList() {
|
|||||||
</Link>
|
</Link>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{inboundsQuery.data?.length === 0 ? (
|
{billingBlocksCreate ? (
|
||||||
|
<div className="flex max-w-xs flex-col items-end gap-1 text-right text-sm">
|
||||||
|
<p className="text-muted-foreground">{t('configs.billingRequiredNotice')}</p>
|
||||||
|
<Link to="/billing" className="font-medium text-foreground underline underline-offset-2">
|
||||||
|
{t('configs.goToBilling')}
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
) : inboundsQuery.data?.length === 0 ? (
|
||||||
<p className="max-w-xs text-right text-sm text-muted-foreground">{t('configs.noInboundsNotice')}</p>
|
<p className="max-w-xs text-right text-sm text-muted-foreground">{t('configs.noInboundsNotice')}</p>
|
||||||
) : (
|
) : (
|
||||||
inboundsQuery.data && <CreateConfigDialog inbounds={inboundsQuery.data} />
|
inboundsQuery.data && <CreateConfigDialog inbounds={inboundsQuery.data} />
|
||||||
|
|||||||
@@ -78,6 +78,8 @@ const resources = {
|
|||||||
location: 'Локация',
|
location: 'Локация',
|
||||||
label: 'Метка (необязательно)',
|
label: 'Метка (необязательно)',
|
||||||
noInboundsNotice: 'Пока нет доступных локаций для создания конфига. Обратитесь к администратору — необходимо, чтобы он добавил сервер.',
|
noInboundsNotice: 'Пока нет доступных локаций для создания конфига. Обратитесь к администратору — необходимо, чтобы он добавил сервер.',
|
||||||
|
billingRequiredNotice: 'Оплата подписки истекла — создание новых конфигов недоступно, пока не продлите доступ.',
|
||||||
|
goToBilling: 'Перейти к оплате',
|
||||||
created: 'Конфиг создан.',
|
created: 'Конфиг создан.',
|
||||||
quotaExceeded: 'Достигнут лимит конфигов для вашей роли.',
|
quotaExceeded: 'Достигнут лимит конфигов для вашей роли.',
|
||||||
showLink: 'Ссылка / QR',
|
showLink: 'Ссылка / QR',
|
||||||
@@ -618,6 +620,8 @@ const resources = {
|
|||||||
location: 'Location',
|
location: 'Location',
|
||||||
label: 'Label (optional)',
|
label: 'Label (optional)',
|
||||||
noInboundsNotice: 'No locations are available for creating a config yet. Please contact the administrator — a server needs to be added.',
|
noInboundsNotice: 'No locations are available for creating a config yet. Please contact the administrator — a server needs to be added.',
|
||||||
|
billingRequiredNotice: 'Your subscription has expired — creating new configs is unavailable until you renew.',
|
||||||
|
goToBilling: 'Go to payment',
|
||||||
created: 'Config created.',
|
created: 'Config created.',
|
||||||
quotaExceeded: 'Config quota reached for your role.',
|
quotaExceeded: 'Config quota reached for your role.',
|
||||||
showLink: 'Link / QR',
|
showLink: 'Link / QR',
|
||||||
|
|||||||
Reference in New Issue
Block a user