Implement billing functionality and enhance role management
CI / Backend (build + test) (push) Successful in 1m22s
CI / Frontend (lint + typecheck + build) (push) Successful in 33s

- Introduced billing capabilities, allowing users to request payments for subscription periods (3/6/12 months) with admin approval via Telegram.
- Updated role management to include a `BillingEnabled` property, preventing billing for admin roles.
- Enhanced the `CreateRoleCommand` and `UpdateRoleCommand` to accept billing parameters, ensuring proper handling during role creation and updates.
- Added new endpoints for billing management and integrated billing checks into VPN config creation to enforce payment requirements.
- Updated related services, models, and tests to support the new billing features, ensuring comprehensive coverage and functionality.
- Enhanced documentation to reflect the new billing processes and role management changes.
This commit is contained in:
Leonid Pershin
2026-07-19 01:38:16 +03:00
parent b980dc6cef
commit b2ae358250
106 changed files with 6018 additions and 66 deletions
@@ -0,0 +1,91 @@
using PnvPanel.Api.Common;
using PnvPanel.Application.Admin.Billing;
using PnvPanel.Application.Common.Messaging;
using PnvPanel.Application.Common.Models;
using PnvPanel.Domain.Billing;
using PnvPanel.Infrastructure.Identity;
namespace PnvPanel.Api.Endpoints;
public static class AdminBillingEndpoints
{
public static IEndpointRouteBuilder MapAdminBillingEndpoints(this IEndpointRouteBuilder app)
{
var admin = app.MapGroup("/api/admin/billing")
.WithTags("Admin.Billing")
.RequireAuthorization(policy => policy.RequireRole(RoleNames.Admin));
admin.MapGet("/settings", GetSettings).Produces<BillingSettingsDto>();
admin.MapPut("/settings", UpdateSettings).Produces<BillingSettingsDto>();
admin
.MapGet("/requests", ListRequests)
.Produces<PagedList<AdminPaymentRequestDto>>();
admin
.MapPost("/requests/{id:guid}/confirm", ConfirmRequest)
.Produces(StatusCodes.Status204NoContent);
admin
.MapPost("/requests/{id:guid}/reject", RejectRequest)
.Produces(StatusCodes.Status204NoContent);
return app;
}
private static async Task<IResult> GetSettings(ISender sender, CancellationToken cancellationToken)
{
var result = await sender.Send(new GetBillingSettingsQuery(), cancellationToken);
return result.ToHttpResult();
}
private static async Task<IResult> UpdateSettings(
UpdateBillingSettingsCommand command,
ISender sender,
CancellationToken cancellationToken
)
{
var result = await sender.Send(command, cancellationToken);
return result.ToHttpResult();
}
private static async Task<IResult> ListRequests(
[AsParameters] ListPaymentRequestsRequest request,
ISender sender,
CancellationToken cancellationToken
)
{
var query = new ListPaymentRequestsQuery(request.Status, request.Page, request.PageSize);
var result = await sender.Send(query, cancellationToken);
return result.ToHttpResult();
}
private static async Task<IResult> ConfirmRequest(
Guid id,
ISender sender,
CancellationToken cancellationToken
)
{
var result = await sender.Send(new ConfirmPaymentRequestCommand(id), cancellationToken);
return result.ToHttpResult();
}
private static async Task<IResult> RejectRequest(
Guid id,
RejectPaymentRequestBody body,
ISender sender,
CancellationToken cancellationToken
)
{
var result = await sender.Send(
new RejectPaymentRequestCommand(id, body.Reason),
cancellationToken
);
return result.ToHttpResult();
}
}
public sealed record ListPaymentRequestsRequest(
PaymentRequestStatus? Status,
int Page = 1,
int PageSize = 20
);
public sealed record RejectPaymentRequestBody(string? Reason);
@@ -0,0 +1,84 @@
using PnvPanel.Api.Common;
using PnvPanel.Application.Billing;
using PnvPanel.Application.Billing.CancelPaymentRequest;
using PnvPanel.Application.Billing.CreatePaymentRequest;
using PnvPanel.Application.Billing.GetMyBillingStatus;
using PnvPanel.Application.Billing.MarkPaymentSent;
using PnvPanel.Application.Billing.SendRequisitesToTelegram;
using PnvPanel.Application.Common.Messaging;
using PnvPanel.Domain.Billing;
namespace PnvPanel.Api.Endpoints;
public static class BillingEndpoints
{
public static IEndpointRouteBuilder MapBillingEndpoints(this IEndpointRouteBuilder app)
{
var group = app.MapGroup("/api/billing").WithTags("Billing").RequireAuthorization();
group.MapGet("/status", GetStatus).Produces<BillingStatusDto>();
group.MapPost("/requests", CreateRequest).Produces<PaymentRequestDto>();
group
.MapPost("/requests/{id:guid}/cancel", CancelRequest)
.Produces(StatusCodes.Status204NoContent);
group
.MapPost("/requests/{id:guid}/mark-paid", MarkPaid)
.Produces(StatusCodes.Status204NoContent);
group
.MapPost("/requests/{id:guid}/send-requisites", SendRequisites)
.Produces(StatusCodes.Status204NoContent);
return app;
}
private static async Task<IResult> GetStatus(ISender sender, CancellationToken cancellationToken)
{
var result = await sender.Send(new GetMyBillingStatusQuery(), cancellationToken);
return result.ToHttpResult();
}
private static async Task<IResult> CreateRequest(
CreatePaymentRequestBody body,
ISender sender,
CancellationToken cancellationToken
)
{
var result = await sender.Send(
new CreatePaymentRequestCommand(body.Period),
cancellationToken
);
return result.ToHttpResult();
}
private static async Task<IResult> CancelRequest(
Guid id,
ISender sender,
CancellationToken cancellationToken
)
{
var result = await sender.Send(new CancelPaymentRequestCommand(id), cancellationToken);
return result.ToHttpResult();
}
private static async Task<IResult> MarkPaid(
Guid id,
ISender sender,
CancellationToken cancellationToken
)
{
var result = await sender.Send(new MarkPaymentSentCommand(id), cancellationToken);
return result.ToHttpResult();
}
private static async Task<IResult> SendRequisites(
Guid id,
ISender sender,
CancellationToken cancellationToken
)
{
var result = await sender.Send(new SendRequisitesToTelegramCommand(id), cancellationToken);
return result.ToHttpResult();
}
}
public sealed record CreatePaymentRequestBody(PaymentPeriod Period);
@@ -53,7 +53,7 @@ public static class RoleEndpoints
)
{
var result = await sender.Send(
new UpdateRoleCommand(id, body.MaxConfigs, body.MaxIpLimit),
new UpdateRoleCommand(id, body.MaxConfigs, body.MaxIpLimit, body.BillingEnabled),
cancellationToken
);
return result.ToHttpResult();
@@ -84,6 +84,6 @@ public static class RoleEndpoints
}
}
public sealed record UpdateRoleBody(int MaxConfigs, int MaxIpLimit);
public sealed record UpdateRoleBody(int MaxConfigs, int MaxIpLimit, bool BillingEnabled);
public sealed record ChangeUserRoleBody(Guid RoleId);
+2
View File
@@ -192,6 +192,8 @@ app.MapAdminAppEndpoints();
app.MapAdminNewsEndpoints();
app.MapAdminInstructionEndpoints();
app.MapAdminPricingEndpoints();
app.MapBillingEndpoints();
app.MapAdminBillingEndpoints();
app.MapSupportEndpoints();
app.MapAdminSupportEndpoints();
app.MapAdminMaintenanceEndpoints();
@@ -1,5 +1,6 @@
using Microsoft.Extensions.Options;
using PnvPanel.Application.Admin.Activation;
using PnvPanel.Application.Admin.Billing;
using PnvPanel.Application.Admin.Support;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Common.Messaging;
@@ -442,6 +443,55 @@ public sealed class PnvBotUpdateHandler(
break;
}
case "pay":
{
if (!await TrySetAdminCurrentUserAsync(services, fromId, cancellationToken))
{
await botClient.AnswerCallbackQuery(
callback.Id,
"Недостаточно прав.",
cancellationToken: cancellationToken
);
return;
}
var result =
parts[1] == "approve"
? await sender.Send(
new ConfirmPaymentRequestCommand(requestId),
cancellationToken
)
: await sender.Send(
new RejectPaymentRequestCommand(requestId, Reason: null),
cancellationToken
);
await botClient.AnswerCallbackQuery(
callback.Id,
result.IsSuccess ? "Готово" : result.Error.Message,
cancellationToken: cancellationToken
);
if (callback.Message is not null)
{
var statusText = result.IsSuccess
? (
parts[1] == "approve"
? "✅ Оплата подтверждена."
: "❌ Оплата отклонена."
)
: $"⚠️ {result.Error.Message}";
var text = $"{Escape(callback.Message.Text ?? "")}\n\n{statusText}";
await botClient.EditMessageText(
chatId.Value,
callback.Message.Id,
text,
parseMode: ParseMode.Html,
cancellationToken: cancellationToken
);
}
break;
}
case "cfg":
{
if (!await TrySetCurrentUserAsync(services, fromId, cancellationToken))
@@ -1,5 +1,6 @@
using Microsoft.Extensions.Options;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Domain.Billing;
using PnvPanel.Domain.Support;
using PnvPanel.Infrastructure.Telegram;
using Telegram.Bot;
@@ -225,6 +226,56 @@ internal sealed class TelegramNotifier(
}
}
public async Task NotifyAdminsPaymentRequestedAsync(
Guid requestId,
string userName,
PaymentPeriod period,
int amount,
CancellationToken cancellationToken
)
{
if (string.IsNullOrWhiteSpace(options.Value.BotToken))
return;
var text =
$"💰 <b>{Escape(userName)}</b> заявляет об оплате за {PeriodLabel(period)} — {amount} ₽\nПроверьте поступление и подтвердите.";
var keyboard = new InlineKeyboardMarkup(
new[]
{
InlineKeyboardButton.WithCallbackData("✅ Подтвердить", $"pay:approve:{requestId}"),
InlineKeyboardButton.WithCallbackData("❌ Отклонить", $"pay:reject:{requestId}"),
}
);
foreach (var adminId in options.Value.ParseAdminTelegramUserIds())
{
try
{
await botClient.SendMessage(
adminId,
text,
parseMode: ParseMode.Html,
replyMarkup: keyboard,
cancellationToken: cancellationToken
);
}
catch
{
// Админ мог не запускать бота (нет чата с ботом) — пропускаем, не валим команду.
}
}
}
private static string PeriodLabel(PaymentPeriod period) =>
period switch
{
PaymentPeriod.Quarter => "3 месяца",
PaymentPeriod.HalfYear => "полгода",
PaymentPeriod.Year => "год",
_ => period.ToString(),
};
public async Task NotifyUserAsync(
Guid userId,
string message,