Add admin configs endpoint and related UI components
- Introduced a new endpoint to list all admin configs, enhancing the admin interface for better management. - Updated API documentation to include the new `/configs` endpoint with pagination and search capabilities. - Added routing and UI elements for the configs section in the admin panel, improving navigation and accessibility. - Enhanced localization for the configs feature in both Russian and English, ensuring a user-friendly experience.
This commit is contained in:
@@ -1,9 +1,11 @@
|
||||
using PnvPanel.Api.Common;
|
||||
using PnvPanel.Application.Admin.Configs;
|
||||
using PnvPanel.Application.Admin.Users;
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
using PnvPanel.Application.Configs;
|
||||
using PnvPanel.Domain.Configs;
|
||||
using PnvPanel.Infrastructure.Identity;
|
||||
|
||||
namespace PnvPanel.Api.Endpoints;
|
||||
@@ -22,6 +24,7 @@ public static class AdminUserEndpoints
|
||||
admin.MapPost("/users/{id:guid}/reset-password", ResetPassword).Produces(StatusCodes.Status204NoContent);
|
||||
admin.MapDelete("/users/{id:guid}", DeleteUser).Produces(StatusCodes.Status204NoContent);
|
||||
admin.MapGet("/users/{id:guid}/configs", GetUserConfigs).Produces<IReadOnlyList<VpnConfigDto>>();
|
||||
admin.MapGet("/configs", ListAllConfigs).Produces<PagedList<AdminVpnConfigDto>>();
|
||||
admin.MapDelete("/configs/{id:guid}", ForceRevokeConfig).Produces(StatusCodes.Status204NoContent);
|
||||
|
||||
return app;
|
||||
@@ -65,6 +68,14 @@ public static class AdminUserEndpoints
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> ListAllConfigs(
|
||||
int page, int pageSize, string? search, ConfigStatus? status, ISender sender, CancellationToken cancellationToken)
|
||||
{
|
||||
var query = new ListAllConfigsQuery(page <= 0 ? 1 : page, pageSize <= 0 ? 20 : pageSize, search, status);
|
||||
var result = await sender.Send(query, cancellationToken);
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> ForceRevokeConfig(Guid id, ISender sender, CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await sender.Send(new ForceRevokeConfigCommand(id), cancellationToken);
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
using PnvPanel.Domain.Configs;
|
||||
using PnvPanel.Domain.Inbounds;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Configs;
|
||||
|
||||
/// <summary>Строка глобального списка конфигов для админа — в отличие от VpnConfigDto (self-service)
|
||||
/// содержит владельца и ноду, т.к. список не скоупится одним пользователем.</summary>
|
||||
public sealed record AdminVpnConfigDto(
|
||||
Guid Id, Guid UserId, string UserName, string? Label, string ClientEmail, VpnProtocol Protocol,
|
||||
string Location, string NodeName, long UsedUpBytes, long UsedDownBytes, DateTimeOffset? ExpiresAt,
|
||||
ConfigStatus Status, DateTimeOffset CreatedAt);
|
||||
@@ -0,0 +1,11 @@
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
using PnvPanel.Domain.Configs;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Configs;
|
||||
|
||||
/// <summary><paramref name="Search"/> матчится по ClientEmail/Label — это то, по чему админ сверяет
|
||||
/// конфиг с записью в 3x-ui, а не по владельцу (для поиска по пользователю есть /admin/users).</summary>
|
||||
public sealed record ListAllConfigsQuery(int Page, int PageSize, string? Search, ConfigStatus? Status)
|
||||
: IQuery<Result<PagedList<AdminVpnConfigDto>>>;
|
||||
@@ -0,0 +1,58 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Configs;
|
||||
|
||||
public sealed class ListAllConfigsQueryHandler(IAppDbContext dbContext, IIdentityService identityService)
|
||||
: IQueryHandler<ListAllConfigsQuery, Result<PagedList<AdminVpnConfigDto>>>
|
||||
{
|
||||
public async Task<Result<PagedList<AdminVpnConfigDto>>> Handle(ListAllConfigsQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
var page = query.Page <= 0 ? 1 : query.Page;
|
||||
var pageSize = query.PageSize is <= 0 or > 100 ? 20 : query.PageSize;
|
||||
|
||||
var configsQuery = dbContext.VpnConfigs.AsNoTracking();
|
||||
|
||||
if (query.Status is { } status)
|
||||
configsQuery = configsQuery.Where(c => c.Status == status);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(query.Search))
|
||||
{
|
||||
var search = query.Search.Trim();
|
||||
configsQuery = configsQuery.Where(c => c.ClientEmail.Contains(search) || (c.Label != null && c.Label.Contains(search)));
|
||||
}
|
||||
|
||||
var pageResult = await configsQuery
|
||||
.OrderByDescending(c => c.CreatedAt)
|
||||
.ToPagedListAsync(page, pageSize, cancellationToken);
|
||||
|
||||
var inboundIds = pageResult.Items.Select(c => c.InboundId).Distinct().ToList();
|
||||
var inbounds = (await dbContext.Inbounds.AsNoTracking()
|
||||
.Where(i => inboundIds.Contains(i.Id))
|
||||
.ToListAsync(cancellationToken))
|
||||
.ToDictionary(i => i.Id);
|
||||
|
||||
var nodeIds = inbounds.Values.Select(i => i.NodeId).Distinct().ToList();
|
||||
var nodes = (await dbContext.Nodes.AsNoTracking()
|
||||
.Where(n => nodeIds.Contains(n.Id))
|
||||
.ToListAsync(cancellationToken))
|
||||
.ToDictionary(n => n.Id);
|
||||
|
||||
var userNames = await identityService.GetUserNamesAsync(
|
||||
pageResult.Items.Select(c => c.UserId).Distinct().ToList(), cancellationToken);
|
||||
|
||||
var items = pageResult.Items.Select(c =>
|
||||
{
|
||||
var inbound = inbounds.GetValueOrDefault(c.InboundId);
|
||||
var node = inbound is null ? null : nodes.GetValueOrDefault(inbound.NodeId);
|
||||
return new AdminVpnConfigDto(
|
||||
c.Id, c.UserId, userNames.GetValueOrDefault(c.UserId, "?"), c.Label, c.ClientEmail, c.Protocol,
|
||||
inbound?.DisplayName ?? inbound?.Remark ?? "?", node?.Name ?? "?",
|
||||
c.UsedUpBytes, c.UsedDownBytes, c.ExpiresAt, c.Status, c.CreatedAt);
|
||||
}).ToList();
|
||||
|
||||
return Result.Success(new PagedList<AdminVpnConfigDto>(items, pageResult.Total, pageResult.Page, pageResult.PageSize));
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
using NSubstitute;
|
||||
using PnvPanel.Application.Admin.Configs;
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Tests.TestSupport;
|
||||
using PnvPanel.Domain.Configs;
|
||||
using PnvPanel.Domain.Inbounds;
|
||||
using PnvPanel.Domain.Nodes;
|
||||
using Xunit;
|
||||
|
||||
namespace PnvPanel.Application.Tests.Admin.Configs;
|
||||
|
||||
public class ListAllConfigsQueryHandlerTests
|
||||
{
|
||||
private readonly IIdentityService _identityService = Substitute.For<IIdentityService>();
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_ReturnsConfigsAcrossUsersWithOwnerNodeAndUserName()
|
||||
{
|
||||
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);
|
||||
inbound.Publish("Germany", [], null);
|
||||
var config = VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, "my-config");
|
||||
|
||||
dbContext.Nodes.Add(node);
|
||||
dbContext.Inbounds.Add(inbound);
|
||||
dbContext.VpnConfigs.Add(config);
|
||||
await dbContext.SaveChangesAsync(CancellationToken.None);
|
||||
|
||||
_identityService.GetUserNamesAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Dictionary<Guid, string> { [userId] = "alice" });
|
||||
|
||||
var handler = new ListAllConfigsQueryHandler(dbContext, _identityService);
|
||||
|
||||
var result = await handler.Handle(new ListAllConfigsQuery(1, 20, Search: null, Status: null), CancellationToken.None);
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
var item = Assert.Single(result.Value.Items);
|
||||
Assert.Equal(config.Id, item.Id);
|
||||
Assert.Equal(userId, item.UserId);
|
||||
Assert.Equal("alice", item.UserName);
|
||||
Assert.Equal("node-1", item.NodeName);
|
||||
Assert.Equal("Germany", item.Location);
|
||||
Assert.Equal(1, result.Value.Total);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_FiltersBySearchAcrossClientEmailAndLabel()
|
||||
{
|
||||
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 matching = VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, "phone-config");
|
||||
var other = VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, "laptop-config");
|
||||
|
||||
dbContext.Nodes.Add(node);
|
||||
dbContext.Inbounds.Add(inbound);
|
||||
dbContext.VpnConfigs.AddRange(matching, other);
|
||||
await dbContext.SaveChangesAsync(CancellationToken.None);
|
||||
|
||||
_identityService.GetUserNamesAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Dictionary<Guid, string> { [userId] = "alice" });
|
||||
|
||||
var handler = new ListAllConfigsQueryHandler(dbContext, _identityService);
|
||||
|
||||
var result = await handler.Handle(new ListAllConfigsQuery(1, 20, Search: "phone", Status: null), CancellationToken.None);
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
var item = Assert.Single(result.Value.Items);
|
||||
Assert.Equal(matching.Id, item.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_FiltersByStatus()
|
||||
{
|
||||
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 active = VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, "active-config");
|
||||
var revoked = VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, "revoked-config");
|
||||
revoked.Revoke();
|
||||
|
||||
dbContext.Nodes.Add(node);
|
||||
dbContext.Inbounds.Add(inbound);
|
||||
dbContext.VpnConfigs.AddRange(active, revoked);
|
||||
await dbContext.SaveChangesAsync(CancellationToken.None);
|
||||
|
||||
_identityService.GetUserNamesAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Dictionary<Guid, string> { [userId] = "alice" });
|
||||
|
||||
var handler = new ListAllConfigsQueryHandler(dbContext, _identityService);
|
||||
|
||||
var result = await handler.Handle(new ListAllConfigsQuery(1, 20, Search: null, Status: ConfigStatus.Revoked), CancellationToken.None);
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
var item = Assert.Single(result.Value.Items);
|
||||
Assert.Equal(revoked.Id, item.Id);
|
||||
}
|
||||
}
|
||||
@@ -170,10 +170,15 @@ approve/reject над `ActivationRequest`.
|
||||
| POST | `/api/admin/users/{id}/reset-password` | admin | `{ newPassword }` | `204 No Content` |
|
||||
| DELETE | `/api/admin/users/{id}` | admin | — | `204 No Content` (отзывает все конфиги пользователя в 3x-ui, затем удаляет учётку; себя удалить нельзя) |
|
||||
| GET | `/api/admin/users/{id}/configs` | admin | — | `VpnConfigDto[]` |
|
||||
| GET | `/api/admin/configs` | admin | query: `page, pageSize, search?, status?` | `PagedList<AdminVpnConfigDto>` |
|
||||
| DELETE | `/api/admin/configs/{id}` | admin | — | `204 No Content` (принудительный отзыв любого конфига) |
|
||||
| GET | `/api/admin/stats` | admin | — | `StatsDto` |
|
||||
| GET | `/api/admin/audit` | admin | query: `page, pageSize` | `PagedList<AuditLogDto>` |
|
||||
|
||||
`AdminVpnConfigDto` — глобальный список конфигов для админа (не скоупится одним пользователем, в
|
||||
отличие от `VpnConfigDto`): `{ id, userId, userName, label, clientEmail, protocol, location, nodeName,
|
||||
usedUpBytes, usedDownBytes, expiresAt, status, createdAt }`. `search` матчится по `clientEmail`/`label`.
|
||||
|
||||
**Блокировка/разблокировка — два отдельных эндпоинта без тела**, не один переключатель `isBlocked`.
|
||||
`StatsDto`: `{ totalUsers, activatedUsers, pendingActivationRequests, totalNodes, onlineNodes,
|
||||
totalConfigs, activeConfigs, totalUsedUpBytes, totalUsedDownBytes }` — считается на лету при запросе,
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { apiRequest } from '@/shared/api/client'
|
||||
import type { AdminVpnConfigDto, ConfigStatus, PagedList } from '@/shared/api/types'
|
||||
|
||||
export function listAllConfigs(page: number, pageSize: number, search: string | undefined, status: ConfigStatus | undefined) {
|
||||
const params = new URLSearchParams({ page: String(page), pageSize: String(pageSize) })
|
||||
if (search) params.set('search', search)
|
||||
if (status) params.set('status', status)
|
||||
return apiRequest<PagedList<AdminVpnConfigDto>>(`/admin/configs?${params.toString()}`)
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import { Route as AdminUsersRouteImport } from './routes/admin/users'
|
||||
import { Route as AdminRolesRouteImport } from './routes/admin/roles'
|
||||
import { Route as AdminNodesRouteImport } from './routes/admin/nodes'
|
||||
import { Route as AdminNewsRouteImport } from './routes/admin/news'
|
||||
import { Route as AdminConfigsRouteImport } from './routes/admin/configs'
|
||||
import { Route as AdminAuditRouteImport } from './routes/admin/audit'
|
||||
import { Route as AdminAppsRouteImport } from './routes/admin/apps'
|
||||
import { Route as AdminActivationRouteImport } from './routes/admin/activation'
|
||||
@@ -91,6 +92,11 @@ const AdminNewsRoute = AdminNewsRouteImport.update({
|
||||
path: '/news',
|
||||
getParentRoute: () => AdminRoute,
|
||||
} as any)
|
||||
const AdminConfigsRoute = AdminConfigsRouteImport.update({
|
||||
id: '/configs',
|
||||
path: '/configs',
|
||||
getParentRoute: () => AdminRoute,
|
||||
} as any)
|
||||
const AdminAuditRoute = AdminAuditRouteImport.update({
|
||||
id: '/audit',
|
||||
path: '/audit',
|
||||
@@ -119,6 +125,7 @@ export interface FileRoutesByFullPath {
|
||||
'/admin/activation': typeof AdminActivationRoute
|
||||
'/admin/apps': typeof AdminAppsRoute
|
||||
'/admin/audit': typeof AdminAuditRoute
|
||||
'/admin/configs': typeof AdminConfigsRoute
|
||||
'/admin/news': typeof AdminNewsRoute
|
||||
'/admin/nodes': typeof AdminNodesRoute
|
||||
'/admin/roles': typeof AdminRolesRoute
|
||||
@@ -136,6 +143,7 @@ export interface FileRoutesByTo {
|
||||
'/admin/activation': typeof AdminActivationRoute
|
||||
'/admin/apps': typeof AdminAppsRoute
|
||||
'/admin/audit': typeof AdminAuditRoute
|
||||
'/admin/configs': typeof AdminConfigsRoute
|
||||
'/admin/news': typeof AdminNewsRoute
|
||||
'/admin/nodes': typeof AdminNodesRoute
|
||||
'/admin/roles': typeof AdminRolesRoute
|
||||
@@ -155,6 +163,7 @@ export interface FileRoutesById {
|
||||
'/admin/activation': typeof AdminActivationRoute
|
||||
'/admin/apps': typeof AdminAppsRoute
|
||||
'/admin/audit': typeof AdminAuditRoute
|
||||
'/admin/configs': typeof AdminConfigsRoute
|
||||
'/admin/news': typeof AdminNewsRoute
|
||||
'/admin/nodes': typeof AdminNodesRoute
|
||||
'/admin/roles': typeof AdminRolesRoute
|
||||
@@ -175,6 +184,7 @@ export interface FileRouteTypes {
|
||||
| '/admin/activation'
|
||||
| '/admin/apps'
|
||||
| '/admin/audit'
|
||||
| '/admin/configs'
|
||||
| '/admin/news'
|
||||
| '/admin/nodes'
|
||||
| '/admin/roles'
|
||||
@@ -192,6 +202,7 @@ export interface FileRouteTypes {
|
||||
| '/admin/activation'
|
||||
| '/admin/apps'
|
||||
| '/admin/audit'
|
||||
| '/admin/configs'
|
||||
| '/admin/news'
|
||||
| '/admin/nodes'
|
||||
| '/admin/roles'
|
||||
@@ -210,6 +221,7 @@ export interface FileRouteTypes {
|
||||
| '/admin/activation'
|
||||
| '/admin/apps'
|
||||
| '/admin/audit'
|
||||
| '/admin/configs'
|
||||
| '/admin/news'
|
||||
| '/admin/nodes'
|
||||
| '/admin/roles'
|
||||
@@ -321,6 +333,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof AdminNewsRouteImport
|
||||
parentRoute: typeof AdminRoute
|
||||
}
|
||||
'/admin/configs': {
|
||||
id: '/admin/configs'
|
||||
path: '/configs'
|
||||
fullPath: '/admin/configs'
|
||||
preLoaderRoute: typeof AdminConfigsRouteImport
|
||||
parentRoute: typeof AdminRoute
|
||||
}
|
||||
'/admin/audit': {
|
||||
id: '/admin/audit'
|
||||
path: '/audit'
|
||||
@@ -349,6 +368,7 @@ interface AdminRouteChildren {
|
||||
AdminActivationRoute: typeof AdminActivationRoute
|
||||
AdminAppsRoute: typeof AdminAppsRoute
|
||||
AdminAuditRoute: typeof AdminAuditRoute
|
||||
AdminConfigsRoute: typeof AdminConfigsRoute
|
||||
AdminNewsRoute: typeof AdminNewsRoute
|
||||
AdminNodesRoute: typeof AdminNodesRoute
|
||||
AdminRolesRoute: typeof AdminRolesRoute
|
||||
@@ -360,6 +380,7 @@ const AdminRouteChildren: AdminRouteChildren = {
|
||||
AdminActivationRoute: AdminActivationRoute,
|
||||
AdminAppsRoute: AdminAppsRoute,
|
||||
AdminAuditRoute: AdminAuditRoute,
|
||||
AdminConfigsRoute: AdminConfigsRoute,
|
||||
AdminNewsRoute: AdminNewsRoute,
|
||||
AdminNodesRoute: AdminNodesRoute,
|
||||
AdminRolesRoute: AdminRolesRoute,
|
||||
|
||||
@@ -9,6 +9,7 @@ const TABS = [
|
||||
{ to: '/admin', key: 'overview' },
|
||||
{ to: '/admin/activation', key: 'activation' },
|
||||
{ to: '/admin/users', key: 'users' },
|
||||
{ to: '/admin/configs', key: 'configs' },
|
||||
{ to: '/admin/roles', key: 'roles' },
|
||||
{ to: '/admin/nodes', key: 'nodes' },
|
||||
{ to: '/admin/apps', key: 'apps' },
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
import { useState } from 'react'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Trash2 } from 'lucide-react'
|
||||
import { toast } from '@/shared/ui/toast-store'
|
||||
import { Input } from '@/shared/ui/input'
|
||||
import { Button } from '@/shared/ui/button'
|
||||
import { Badge } from '@/shared/ui/badge'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/shared/ui/select'
|
||||
import { formatBytes } from '@/shared/lib/format'
|
||||
import { listAllConfigs } from '@/features/admin/configs/api'
|
||||
import { forceRevokeConfig } from '@/features/admin/users/api'
|
||||
import type { ConfigStatus } from '@/shared/api/types'
|
||||
|
||||
export const Route = createFileRoute('/admin/configs')({ component: AdminConfigsPage })
|
||||
|
||||
const PAGE_SIZE = 20
|
||||
|
||||
const STATUS_VARIANT: Record<ConfigStatus, 'success' | 'warning' | 'destructive'> = {
|
||||
Active: 'success',
|
||||
Disabled: 'warning',
|
||||
Expired: 'destructive',
|
||||
LimitReached: 'destructive',
|
||||
Revoked: 'destructive',
|
||||
}
|
||||
|
||||
function AdminConfigsPage() {
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient()
|
||||
const [search, setSearch] = useState('')
|
||||
const [status, setStatus] = useState<ConfigStatus | 'all'>('all')
|
||||
const [page, setPage] = useState(1)
|
||||
|
||||
const statusFilter = status === 'all' ? undefined : status
|
||||
|
||||
const { data, isLoading, isError, refetch } = useQuery({
|
||||
queryKey: ['admin-configs', page, search, statusFilter],
|
||||
queryFn: () => listAllConfigs(page, PAGE_SIZE, search || undefined, statusFilter),
|
||||
})
|
||||
|
||||
const revokeMutation = useMutation({
|
||||
mutationFn: (configId: string) => forceRevokeConfig(configId),
|
||||
onSuccess: async () => {
|
||||
toast.success(t('configs.revoked'))
|
||||
await queryClient.invalidateQueries({ queryKey: ['admin-configs'] })
|
||||
},
|
||||
onError: () => toast.error(t('auth.genericError')),
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Input
|
||||
placeholder={t('admin.configs.searchPlaceholder')}
|
||||
value={search}
|
||||
onChange={(e) => {
|
||||
setSearch(e.target.value)
|
||||
setPage(1)
|
||||
}}
|
||||
className="max-w-sm"
|
||||
/>
|
||||
<Select
|
||||
value={status}
|
||||
onValueChange={(value) => {
|
||||
setStatus(value as ConfigStatus | 'all')
|
||||
setPage(1)
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-48">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">{t('admin.configs.allStatuses')}</SelectItem>
|
||||
{(['Active', 'Disabled', 'Expired', 'LimitReached', 'Revoked'] satisfies ConfigStatus[]).map((s) => (
|
||||
<SelectItem key={s} value={s}>
|
||||
{t(`configs.status.${s}`)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{isLoading && <p className="text-sm text-muted-foreground">…</p>}
|
||||
|
||||
{isError && (
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="text-sm text-muted-foreground">{t('auth.genericError')}</p>
|
||||
<Button variant="outline" size="sm" onClick={() => void refetch()}>
|
||||
{t('activation.retry')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{data && (
|
||||
<>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border text-muted-foreground">
|
||||
<th className="py-2 font-medium">{t('admin.configs.owner')}</th>
|
||||
<th className="py-2 font-medium">{t('admin.users.configs')}</th>
|
||||
<th className="py-2 font-medium">{t('admin.configs.protocol')}</th>
|
||||
<th className="py-2 font-medium">{t('admin.configs.node')}</th>
|
||||
<th className="py-2 font-medium">{t('admin.configs.traffic')}</th>
|
||||
<th className="py-2 font-medium">{t('admin.configs.statusLabel')}</th>
|
||||
<th className="py-2" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.items.map((config) => (
|
||||
<tr key={config.id} className="border-b border-border align-top">
|
||||
<td className="py-2">{config.userName}</td>
|
||||
<td className="py-2">
|
||||
<div>{config.label ?? config.clientEmail}</div>
|
||||
<div className="font-mono text-xs text-muted-foreground/60">{config.clientEmail}</div>
|
||||
</td>
|
||||
<td className="py-2">
|
||||
<Badge variant="outline">{config.protocol}</Badge>
|
||||
</td>
|
||||
<td className="py-2">
|
||||
{config.nodeName} · {config.location}
|
||||
</td>
|
||||
<td className="py-2 text-muted-foreground">
|
||||
↑ {formatBytes(config.usedUpBytes)} ↓ {formatBytes(config.usedDownBytes)}
|
||||
</td>
|
||||
<td className="py-2">
|
||||
<Badge variant={STATUS_VARIANT[config.status]}>{t(`configs.status.${config.status}`)}</Badge>
|
||||
</td>
|
||||
<td className="py-2 text-right">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={config.status === 'Revoked' || revokeMutation.isPending}
|
||||
onClick={() => {
|
||||
if (confirm(t('configs.confirmRevoke'))) revokeMutation.mutate(config.id)
|
||||
}}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{data.items.length === 0 && <p className="text-sm text-muted-foreground">{t('admin.configs.empty')}</p>}
|
||||
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="text-muted-foreground">{t('admin.configs.total', { count: data.total })}</span>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" size="sm" disabled={page <= 1} onClick={() => setPage((p) => p - 1)}>
|
||||
{t('admin.prev')}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" disabled={page * PAGE_SIZE >= data.total} onClick={() => setPage((p) => p + 1)}>
|
||||
{t('admin.next')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -59,6 +59,23 @@ export type VpnConfigDto = {
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
/** Строка админского списка «Все конфиги» — в отличие от VpnConfigDto содержит владельца и ноду. */
|
||||
export type AdminVpnConfigDto = {
|
||||
id: string
|
||||
userId: string
|
||||
userName: string
|
||||
label: string | null
|
||||
clientEmail: string
|
||||
protocol: VpnProtocol
|
||||
location: string
|
||||
nodeName: string
|
||||
usedUpBytes: number
|
||||
usedDownBytes: number
|
||||
expiresAt: string | null
|
||||
status: ConfigStatus
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export type AvailableInboundDto = {
|
||||
inboundId: string
|
||||
displayName: string
|
||||
|
||||
@@ -154,6 +154,7 @@ const resources = {
|
||||
overview: 'Обзор',
|
||||
activation: 'Запросы на активацию',
|
||||
users: 'Пользователи',
|
||||
configs: 'Все конфиги',
|
||||
roles: 'Роли',
|
||||
nodes: 'Ноды',
|
||||
apps: 'Приложения',
|
||||
@@ -187,6 +188,19 @@ const resources = {
|
||||
confirmDelete: 'Удалить пользователя? Все его конфиги будут отозваны в 3x-ui, действие необратимо.',
|
||||
deleted: 'Пользователь удалён.',
|
||||
},
|
||||
configs: {
|
||||
searchPlaceholder: 'Поиск по email в панели или метке',
|
||||
owner: 'Владелец',
|
||||
node: 'Нода',
|
||||
location: 'Локация',
|
||||
protocol: 'Протокол',
|
||||
traffic: 'Трафик',
|
||||
statusLabel: 'Статус',
|
||||
allStatuses: 'Все статусы',
|
||||
created: 'Создан',
|
||||
empty: 'Конфиги не найдены.',
|
||||
total: 'Всего: {{count}}',
|
||||
},
|
||||
activation: {
|
||||
empty: 'Нет ожидающих запросов на активацию.',
|
||||
approved: 'Пользователь активирован.',
|
||||
@@ -447,6 +461,7 @@ const resources = {
|
||||
overview: 'Overview',
|
||||
activation: 'Activation requests',
|
||||
users: 'Users',
|
||||
configs: 'All configs',
|
||||
roles: 'Roles',
|
||||
nodes: 'Nodes',
|
||||
apps: 'Apps',
|
||||
@@ -480,6 +495,19 @@ const resources = {
|
||||
confirmDelete: 'Delete this user? All their configs will be revoked in 3x-ui — this cannot be undone.',
|
||||
deleted: 'User deleted.',
|
||||
},
|
||||
configs: {
|
||||
searchPlaceholder: 'Search by panel email or label',
|
||||
owner: 'Owner',
|
||||
node: 'Node',
|
||||
location: 'Location',
|
||||
protocol: 'Protocol',
|
||||
traffic: 'Traffic',
|
||||
statusLabel: 'Status',
|
||||
allStatuses: 'All statuses',
|
||||
created: 'Created',
|
||||
empty: 'No configs found.',
|
||||
total: 'Total: {{count}}',
|
||||
},
|
||||
activation: {
|
||||
empty: 'No pending activation requests.',
|
||||
approved: 'User activated.',
|
||||
|
||||
Reference in New Issue
Block a user