Implement billing status notification and enhance user management integration
- Added `NotifyBillingStatusChangedAsync` method to `IRealtimeNotifier` for notifying clients about changes in billing status. - Updated `BillingConfigResumer` to call the new notification method after modifying billing configurations, ensuring users receive real-time updates. - Enhanced `ListUsersQueryHandler` to include a `BillingPendingReview` property in `UserSummaryDto`, indicating if a user has a pending payment request awaiting confirmation. - Refactored various command handlers to utilize `AdvisoryLock` for managing concurrent requests, preventing race conditions in billing operations. - Updated tests to cover new notification behaviors and ensure proper functionality in billing status management.
This commit is contained in:
+68
-28
@@ -1,5 +1,6 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PnvPanel.Application.Auth;
|
||||
using PnvPanel.Application.Common.Concurrency;
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
@@ -10,6 +11,12 @@ using PnvPanel.Domain.Support;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Support;
|
||||
|
||||
/// <summary>
|
||||
/// Проверка статуса + создание/назначение роли + Resolve() + доплата (если роль подорожала) — под
|
||||
/// AdvisoryLock (по Id тикета): без неё одобрение с сайта, гонящееся с одобрением из Telegram по одной
|
||||
/// и той же заявке, могли бы оба пройти проверку "ещё не решена" и оба создать RoleChangeTopUp —
|
||||
/// двойной счёт за один апгрейд.
|
||||
/// </summary>
|
||||
public sealed class ApproveRoleRequestCommandHandler(
|
||||
IAppDbContext dbContext,
|
||||
IRoleService roleService,
|
||||
@@ -27,18 +34,56 @@ public sealed class ApproveRoleRequestCommandHandler(
|
||||
if (currentUser.UserId is not { } adminId)
|
||||
return Result.Failure(AuthErrors.Unauthorized);
|
||||
|
||||
var claimed = await AdvisoryLock.RunAsync(
|
||||
dbContext,
|
||||
command.TicketId,
|
||||
lockedCancellationToken => ApproveAsync(command.TicketId, adminId, lockedCancellationToken),
|
||||
cancellationToken
|
||||
);
|
||||
if (!claimed.IsSuccess)
|
||||
return Result.Failure(claimed.Error);
|
||||
|
||||
var (ticket, topUpAmount) = claimed.Value;
|
||||
|
||||
await notifier.NotifyTicketUpdatedAsync(ticket.Id, ticket.UserId, cancellationToken);
|
||||
await telegramNotifier.NotifyUserAsync(
|
||||
ticket.UserId,
|
||||
"✅ Ваша заявка на роль одобрена.",
|
||||
$"/support?ticket={ticket.Id}",
|
||||
cancellationToken
|
||||
);
|
||||
|
||||
if (topUpAmount is { } amount)
|
||||
{
|
||||
await telegramNotifier.NotifyUserAsync(
|
||||
ticket.UserId,
|
||||
$"💳 Новая роль дороже прежней — требуется доплата {amount} ₽ за оставшуюся часть оплаченного периода.",
|
||||
"/billing",
|
||||
cancellationToken
|
||||
);
|
||||
}
|
||||
|
||||
return Result.Success();
|
||||
}
|
||||
|
||||
private async Task<Result<(SupportTicket Ticket, int? TopUpAmount)>> ApproveAsync(
|
||||
Guid ticketId,
|
||||
Guid adminId,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
var ticket = await dbContext.SupportTickets.FirstOrDefaultAsync(
|
||||
t => t.Id == command.TicketId,
|
||||
t => t.Id == ticketId,
|
||||
cancellationToken
|
||||
);
|
||||
if (ticket is null)
|
||||
return Result.Failure(SupportErrors.NotFound);
|
||||
return Result.Failure<(SupportTicket, int?)>(SupportErrors.NotFound);
|
||||
|
||||
if (ticket.Type != TicketType.RoleRequest)
|
||||
return Result.Failure(SupportErrors.NotRoleRequest);
|
||||
return Result.Failure<(SupportTicket, int?)>(SupportErrors.NotRoleRequest);
|
||||
|
||||
if (ticket.Status != TicketStatus.Open)
|
||||
return Result.Failure(SupportErrors.NotOpen);
|
||||
return Result.Failure<(SupportTicket, int?)>(SupportErrors.NotOpen);
|
||||
|
||||
// Снимаем профиль ДО смены роли — нужен старый MaxConfigs/BillingPaidUntil для проратированной
|
||||
// доплаты за апгрейд (см. ниже), после ChangeUserRoleAsync эти данные уже недоступны.
|
||||
@@ -50,7 +95,7 @@ public sealed class ApproveRoleRequestCommandHandler(
|
||||
var roles = await roleService.ListRolesAsync(cancellationToken);
|
||||
var found = roles.FirstOrDefault(r => r.Id == existingRoleId);
|
||||
if (found is null)
|
||||
return Result.Failure(SupportErrors.NotFound);
|
||||
return Result.Failure<(SupportTicket, int?)>(SupportErrors.NotFound);
|
||||
|
||||
newRole = found;
|
||||
}
|
||||
@@ -64,7 +109,7 @@ public sealed class ApproveRoleRequestCommandHandler(
|
||||
cancellationToken
|
||||
);
|
||||
if (!createResult.IsSuccess)
|
||||
return Result.Failure(createResult.Error);
|
||||
return Result.Failure<(SupportTicket, int?)>(createResult.Error);
|
||||
|
||||
newRole = createResult.Value;
|
||||
}
|
||||
@@ -75,7 +120,7 @@ public sealed class ApproveRoleRequestCommandHandler(
|
||||
cancellationToken
|
||||
);
|
||||
if (!assignResult.IsSuccess)
|
||||
return assignResult;
|
||||
return Result.Failure<(SupportTicket, int?)>(assignResult.Error);
|
||||
|
||||
ticket.Resolve();
|
||||
|
||||
@@ -90,25 +135,26 @@ public sealed class ApproveRoleRequestCommandHandler(
|
||||
)
|
||||
);
|
||||
|
||||
await notifier.NotifyTicketUpdatedAsync(ticket.Id, ticket.UserId, cancellationToken);
|
||||
await telegramNotifier.NotifyUserAsync(
|
||||
ticket.UserId,
|
||||
"✅ Ваша заявка на роль одобрена.",
|
||||
$"/support?ticket={ticket.Id}",
|
||||
cancellationToken
|
||||
);
|
||||
|
||||
int? topUpAmount = null;
|
||||
if (newRole.BillingEnabled && oldProfile?.BillingPaidUntil is { } paidUntil)
|
||||
await CreateTopUpIfNeededAsync(ticket.UserId, oldProfile.MaxConfigs, newRole.MaxConfigs, paidUntil, cancellationToken);
|
||||
{
|
||||
topUpAmount = await CreateTopUpIfNeededAsync(
|
||||
ticket.UserId,
|
||||
oldProfile.MaxConfigs,
|
||||
newRole.MaxConfigs,
|
||||
paidUntil,
|
||||
cancellationToken
|
||||
);
|
||||
}
|
||||
|
||||
return Result.Success();
|
||||
return Result.Success((ticket, topUpAmount));
|
||||
}
|
||||
|
||||
/// <summary>Роль подорожала, а оплаченный период ещё активен — по-хорошему пользователь должен
|
||||
/// доплатить разницу, а не доиграть апгрейд бесплатно до конца уже оплаченного срока. Роль меняется
|
||||
/// сразу (см. выше); доплата решается отдельно через обычный флоу PaymentRequest — см.
|
||||
/// domain-model.md#rolechangetopup.</summary>
|
||||
private async Task CreateTopUpIfNeededAsync(
|
||||
/// domain-model.md#rolechangetopup. Только БД — уведомление шлёт вызывающий код после снятия лока.</summary>
|
||||
private async Task<int?> CreateTopUpIfNeededAsync(
|
||||
Guid userId,
|
||||
int oldMaxConfigs,
|
||||
int newMaxConfigs,
|
||||
@@ -118,7 +164,7 @@ public sealed class ApproveRoleRequestCommandHandler(
|
||||
{
|
||||
var pricing = await dbContext.PricingSettings.AsNoTracking().FirstOrDefaultAsync(cancellationToken);
|
||||
if (pricing?.PricePerConfigPerQuarter is not { } rate)
|
||||
return;
|
||||
return null;
|
||||
|
||||
var tiers = await dbContext
|
||||
.PricingDiscountTiers.AsNoTracking()
|
||||
@@ -134,15 +180,9 @@ public sealed class ApproveRoleRequestCommandHandler(
|
||||
DateTimeOffset.UtcNow
|
||||
);
|
||||
if (amount is not { } topUpAmount)
|
||||
return;
|
||||
return null;
|
||||
|
||||
dbContext.PaymentRequests.Add(PaymentRequest.CreateRoleChangeTopUp(userId, topUpAmount));
|
||||
|
||||
await telegramNotifier.NotifyUserAsync(
|
||||
userId,
|
||||
$"💳 Новая роль дороже прежней — требуется доплата {topUpAmount} ₽ за оставшуюся часть оплаченного периода.",
|
||||
"/billing",
|
||||
cancellationToken
|
||||
);
|
||||
return topUpAmount;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user