Enhance billing request handling to support immediate config suspension and protection
- Updated the `RejectPaymentRequestCommandHandler` to immediately suspend user configs if a payment request is rejected and no other pending subscription requests exist. - Introduced `SuspendIfStillUnpaidAsync` method to handle the logic for suspending configs based on the user's billing status. - Enhanced the `MarkPaymentSentCommandHandler` to protect configs during the payment confirmation process, ensuring users remain active while awaiting admin approval. - Refactored `BillingConfigResumer` to include methods for protecting and suspending configs, improving the overall billing management flow. - Updated tests to cover new behaviors and ensure proper functionality in various scenarios related to payment requests and config management.
This commit is contained in:
@@ -1,20 +1,26 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Domain.Billing;
|
||||
using PnvPanel.Domain.Configs;
|
||||
|
||||
namespace PnvPanel.Application.Billing;
|
||||
|
||||
/// <summary>
|
||||
/// Общая часть "продлить оплату" — возвращает в Active конфиги, приостановленные за неуплату
|
||||
/// (Expired), и синхронизирует ExpiresAt на все конфиги пользователя. Используется при подтверждении
|
||||
/// заявки на оплату, одобрении заявки на продление и выдаче гифт-дней админом — расчёт самого
|
||||
/// newPaidUntil (AddMonths для платежа, AddDays для продления/гифта) остаётся на вызывающей стороне,
|
||||
/// как и AppUser.BillingPaidUntil (см. IIdentityService.ExtendBillingPaidUntilAsync, зовётся отдельно
|
||||
/// до этого helper'а).
|
||||
/// Общая синхронизация панели 3x-ui со статусом оплаты: продление (ResumeConfigsAsync), временная
|
||||
/// защита на время рассмотрения заявки админом (ProtectPendingConfigsAsync) и приостановка за неуплату
|
||||
/// (SuspendConfigsAsync). Xray проверяет expiryTime клиента сам, независимо от нашего локального
|
||||
/// статуса — поэтому "просто не гасить, пока заявка на проверке" недостаточно: если реальный
|
||||
/// BillingPaidUntil уже в прошлом, панель заблокирует клиента сама, пока мы явно не подвинем
|
||||
/// expiryTime вперёд. По той же причине везде передаём enable И expiresAt вместе (см.
|
||||
/// IXuiPanelGateway.UpdateClientAsync) — по факту эксплуатации одного enable недостаточно.
|
||||
/// </summary>
|
||||
internal static class BillingConfigResumer
|
||||
public static class BillingConfigResumer
|
||||
{
|
||||
/// <summary>Подтверждённая оплата/продление/гифт — реальный новый срок. Пушится на панель для
|
||||
/// ЛЮБОГО статуса конфига, не только Expired: пользователь мог доплатить/продлить заранее, пока
|
||||
/// конфиг ещё Active — панель должна узнать новый срок сразу, а не только когда конфиг реально
|
||||
/// просрочится.</summary>
|
||||
public static async Task ResumeConfigsAsync(
|
||||
IAppDbContext dbContext,
|
||||
IXuiPanelGateway gateway,
|
||||
@@ -25,58 +31,24 @@ internal static class BillingConfigResumer
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
var configs = await dbContext
|
||||
.VpnConfigs.Where(c =>
|
||||
c.UserId == userId
|
||||
&& (c.Status == ConfigStatus.Active || c.Status == ConfigStatus.Expired)
|
||||
)
|
||||
.ToListAsync(cancellationToken);
|
||||
var configs = await ActiveOrExpiredConfigsAsync(dbContext, userId, cancellationToken);
|
||||
|
||||
foreach (var config in configs)
|
||||
{
|
||||
if (config.Status == ConfigStatus.Expired)
|
||||
var wasExpired = config.Status == ConfigStatus.Expired;
|
||||
var pushed = await PushExpiryAsync(
|
||||
dbContext,
|
||||
gateway,
|
||||
logger,
|
||||
config,
|
||||
enable: true,
|
||||
newPaidUntil,
|
||||
"extending billing",
|
||||
cancellationToken
|
||||
);
|
||||
|
||||
if (wasExpired && pushed)
|
||||
{
|
||||
var inbound = await dbContext
|
||||
.Inbounds.AsNoTracking()
|
||||
.FirstOrDefaultAsync(i => i.Id == config.InboundId, cancellationToken);
|
||||
var node = inbound is null
|
||||
? null
|
||||
: await dbContext
|
||||
.Nodes.AsNoTracking()
|
||||
.FirstOrDefaultAsync(n => n.Id == inbound.NodeId, cancellationToken);
|
||||
|
||||
if (inbound is not null && node is not null)
|
||||
{
|
||||
// Возвращаем через expiryTime = новый newPaidUntil, а не enable:true — тот же
|
||||
// механизм приостановки, что и у BillingService (см. IXuiPanelGateway.UpdateClientAsync):
|
||||
// переписываем просроченную дату на настоящую, панель/Xray сами перестают считать
|
||||
// клиента истёкшим. name: null — не переименовываем клиента.
|
||||
var updateResult = await gateway.UpdateClientAsync(
|
||||
node,
|
||||
inbound.RemoteInboundId,
|
||||
config.ClientExternalId,
|
||||
config.Protocol,
|
||||
name: null,
|
||||
enable: null,
|
||||
expiresAt: newPaidUntil,
|
||||
cancellationToken
|
||||
);
|
||||
|
||||
if (!updateResult.IsSuccess)
|
||||
{
|
||||
// Нода недоступна — не трогаем локальный статус, подхватится следующим
|
||||
// продлением/циклом BillingService (идемпотентно).
|
||||
logger.LogWarning(
|
||||
"Failed to enable client for config {ConfigId} on node {NodeId} while extending billing for user {UserId}: {Error}",
|
||||
config.Id,
|
||||
node.Id,
|
||||
userId,
|
||||
updateResult.Error
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
config.Resume();
|
||||
await notifier.NotifyConfigStatusChangedAsync(
|
||||
config.UserId,
|
||||
@@ -89,4 +61,148 @@ internal static class BillingConfigResumer
|
||||
config.SetBillingExpiry(newPaidUntil);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Заявка на оплату ждёт решения админа (AwaitingConfirmation) — держим клиента рабочим
|
||||
/// на панели на время рассмотрения (expiresAt = сейчас + BillingSettings.GraceDays), не трогая
|
||||
/// Status/ExpiresAt в БД — это временная мера до Confirm (ResumeConfigsAsync проставит настоящий
|
||||
/// срок) или Reject (SuspendConfigsAsync вернёт как было). Вызывается и сразу при отметке "я
|
||||
/// оплатил" (MarkPaymentSentCommandHandler), и на каждом тике BillingService, пока заявка висит —
|
||||
/// идемпотентно, каждый вызов просто продлевает грейс ещё на GraceDays от текущего момента.</summary>
|
||||
public static async Task ProtectPendingConfigsAsync(
|
||||
IAppDbContext dbContext,
|
||||
IXuiPanelGateway gateway,
|
||||
ILogger logger,
|
||||
Guid userId,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
var settings = await dbContext.BillingSettings.AsNoTracking().FirstOrDefaultAsync(cancellationToken);
|
||||
var graceUntil = DateTimeOffset.UtcNow.AddDays(settings?.GraceDays ?? BillingSettings.DefaultGraceDays);
|
||||
|
||||
var configs = await ActiveOrExpiredConfigsAsync(dbContext, userId, cancellationToken);
|
||||
|
||||
foreach (var config in configs)
|
||||
{
|
||||
await PushExpiryAsync(
|
||||
dbContext,
|
||||
gateway,
|
||||
logger,
|
||||
config,
|
||||
enable: true,
|
||||
graceUntil,
|
||||
"protecting pending payment for",
|
||||
cancellationToken
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Приостановка за неуплату — общая для фоновой джобы (BillingService) и немедленной
|
||||
/// реакции на отклонение заявки админом (RejectPaymentRequestCommandHandler), чтобы не ждать
|
||||
/// следующего часового тика. Проходит и по уже Expired конфигам — они могли быть временно
|
||||
/// "защищены" ProtectPendingConfigsAsync (enable/expiresAt на панели уехали вперёд, а статус в БД
|
||||
/// остался как был), и при отклонении заявки эту защиту нужно снять с панели тоже, а не только
|
||||
/// локально.</summary>
|
||||
public static async Task SuspendConfigsAsync(
|
||||
IAppDbContext dbContext,
|
||||
IXuiPanelGateway gateway,
|
||||
IRealtimeNotifier notifier,
|
||||
ILogger logger,
|
||||
Guid userId,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
var expiredAt = DateTimeOffset.UtcNow.AddDays(-1);
|
||||
var configs = await ActiveOrExpiredConfigsAsync(dbContext, userId, cancellationToken);
|
||||
|
||||
foreach (var config in configs)
|
||||
{
|
||||
var wasActive = config.Status == ConfigStatus.Active;
|
||||
var pushed = await PushExpiryAsync(
|
||||
dbContext,
|
||||
gateway,
|
||||
logger,
|
||||
config,
|
||||
enable: false,
|
||||
expiredAt,
|
||||
"suspending for non-payment",
|
||||
cancellationToken
|
||||
);
|
||||
|
||||
if (!wasActive || !pushed)
|
||||
continue;
|
||||
|
||||
config.Suspend();
|
||||
await notifier.NotifyConfigStatusChangedAsync(
|
||||
config.UserId,
|
||||
config.Id,
|
||||
config.Status,
|
||||
cancellationToken
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private static Task<List<VpnConfig>> ActiveOrExpiredConfigsAsync(
|
||||
IAppDbContext dbContext,
|
||||
Guid userId,
|
||||
CancellationToken cancellationToken
|
||||
) =>
|
||||
dbContext
|
||||
.VpnConfigs.Where(c =>
|
||||
c.UserId == userId
|
||||
&& (c.Status == ConfigStatus.Active || c.Status == ConfigStatus.Expired)
|
||||
)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
/// <summary>Возвращает false только если панель реально отвергла обновление (нода недоступна и
|
||||
/// т.п.) — вызывающий тогда пропускает смену локального статуса, чтобы не разойтись с панелью
|
||||
/// (подхватится следующим циклом/событием). Если у конфига нет инбаунда/ноды вовсе — на панели
|
||||
/// нечего обновлять, но локальный статус менять можно (как и раньше в BillingService/
|
||||
/// BillingConfigResumer).</summary>
|
||||
private static async Task<bool> PushExpiryAsync(
|
||||
IAppDbContext dbContext,
|
||||
IXuiPanelGateway gateway,
|
||||
ILogger logger,
|
||||
VpnConfig config,
|
||||
bool enable,
|
||||
DateTimeOffset expiresAt,
|
||||
string action,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
var inbound = await dbContext
|
||||
.Inbounds.AsNoTracking()
|
||||
.FirstOrDefaultAsync(i => i.Id == config.InboundId, cancellationToken);
|
||||
var node = inbound is null
|
||||
? null
|
||||
: await dbContext
|
||||
.Nodes.AsNoTracking()
|
||||
.FirstOrDefaultAsync(n => n.Id == inbound.NodeId, cancellationToken);
|
||||
|
||||
if (inbound is null || node is null)
|
||||
return true;
|
||||
|
||||
var result = await gateway.UpdateClientAsync(
|
||||
node,
|
||||
inbound.RemoteInboundId,
|
||||
config.ClientExternalId,
|
||||
config.Protocol,
|
||||
name: null,
|
||||
enable,
|
||||
expiresAt,
|
||||
cancellationToken
|
||||
);
|
||||
|
||||
if (result.IsSuccess)
|
||||
return true;
|
||||
|
||||
logger.LogWarning(
|
||||
"Failed to update client for config {ConfigId} on node {NodeId} while {Action} user {UserId}: {Error}",
|
||||
config.Id,
|
||||
node.Id,
|
||||
action,
|
||||
config.UserId,
|
||||
result.Error
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
+23
-1
@@ -1,4 +1,5 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using PnvPanel.Application.Auth;
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
@@ -10,8 +11,10 @@ namespace PnvPanel.Application.Billing.MarkPaymentSent;
|
||||
public sealed class MarkPaymentSentCommandHandler(
|
||||
IAppDbContext dbContext,
|
||||
IIdentityService identityService,
|
||||
IXuiPanelGateway gateway,
|
||||
ITelegramNotifier telegramNotifier,
|
||||
ICurrentUser currentUser
|
||||
ICurrentUser currentUser,
|
||||
ILogger<MarkPaymentSentCommandHandler> logger
|
||||
) : ICommandHandler<MarkPaymentSentCommand, Result>
|
||||
{
|
||||
public async Task<Result> Handle(MarkPaymentSentCommand command, CancellationToken cancellationToken)
|
||||
@@ -32,6 +35,25 @@ public sealed class MarkPaymentSentCommandHandler(
|
||||
request.MarkPaymentSent();
|
||||
|
||||
var profile = await identityService.GetProfileAsync(userId, cancellationToken);
|
||||
|
||||
// Оплаченный период уже мог истечь, пока пользователь собирался заплатить — не ждём часовой
|
||||
// тик BillingService, сразу держим клиента рабочим на панели на время рассмотрения заявки
|
||||
// (см. BillingConfigResumer.ProtectPendingConfigsAsync). Только для Subscription — доплата за
|
||||
// смену роли (RoleChangeTopUp) на приостановку не влияет.
|
||||
if (
|
||||
request.Kind == PaymentRequestKind.Subscription
|
||||
&& (profile?.BillingPaidUntil is null || profile.BillingPaidUntil < DateTimeOffset.UtcNow)
|
||||
)
|
||||
{
|
||||
await BillingConfigResumer.ProtectPendingConfigsAsync(
|
||||
dbContext,
|
||||
gateway,
|
||||
logger,
|
||||
userId,
|
||||
cancellationToken
|
||||
);
|
||||
}
|
||||
|
||||
await telegramNotifier.NotifyAdminsPaymentRequestedAsync(
|
||||
request.Id,
|
||||
profile?.UserName ?? userId.ToString(),
|
||||
|
||||
Reference in New Issue
Block a user