feat(clients,groups): client groups + sub-links export + dedicated groups page

Persistent client groups
- New ClientGroup model + client_groups table that holds empty
  (placeholder) groups so a user can define a label before any client
  references it. ListGroups merges these with the distinct group_name
  values already stored on clients and reports {name, clientCount}.
- ClientRecord gains group_name column; the model.Client wire shape
  gains a matching `group` JSON field that survives the
  inbound.settings → SyncInbound round-trip.
- Rename/Delete on a group mutates client_groups (rename row / delete
  row) AND propagates to all matching clients in ClientRecord and in
  every owning inbound's settings JSON, all in one transaction.

Bulk operations
- AssignGroup(emails, group) updates clients.group_name + patches each
  affected inbound's settings JSON in one read-modify-write per inbound.
  Empty group clears the label. Auto-creates the client_groups row when
  the user assigns to a brand-new name.
- BulkResetTraffic(emails) loops the existing single-reset path so the
  caller can zero traffic across a whole selection or a whole group.
- EmailsByGroup(name) returns just the email list (used by the groups
  page to fan a single bulk action over every member).

Endpoints (all under /panel/api/clients)
- GET  /groups                         — summaries with counts
- GET  /groups/:name/emails            — emails in a group
- POST /groups/create                  — empty placeholder group
- POST /groups/rename                  — rename (table + clients + JSON)
- POST /groups/delete                  — drop label everywhere (clients survive)
- POST /bulkAssignGroup                — assign N selected clients
- POST /bulkResetTraffic               — reset traffic on a list

Clients page UX
- New Group column (Actions → Client → Group → Inbounds → …) with a
  click-to-filter chip.
- FilterDrawer gains a multi-select Group filter whose options come
  from the new ClientPageResponse.groups field (sourced from ListGroups
  so empty/placeholder groups are pickable too).
- Single-client and bulk-add forms gain a Group AutoComplete pre-loaded
  with all known group names.
- New toolbar buttons when selection > 0: "Group ({n})" opens
  BulkAssignGroupModal, "Sub links ({n})" opens SubLinksModal.

Sub-links export modal (new SubLinksModal.tsx)
- Table of selected clients with their subscription URL (and JSON URL
  when subJsonEnable is on), per-row copy, Copy all, and Download as
  sub-links-<timestamp>.txt. Warns when subscription is disabled or
  none of the selected clients have a subId.

Dedicated Groups page (new pages/groups/GroupsPage.tsx)
- /groups route + sidebar entry (TagsOutlined icon) + page title key.
- Card-based layout matching Clients/Inbounds/Nodes — summary card with
  Total/Grouped/Empty stats, main card with Add Group button + table.
- Per-row More dropdown (icon-first column on the left): Sub links,
  Adjust (days+traffic), Reset traffic, Rename, Delete clients in
  group, Delete group (keep clients). Empty groups disable the
  client-targeted actions.
- Reuses SubLinksModal and ClientBulkAdjustModal — emails for the
  group are fetched on demand from GET /groups/:name/emails.

Other polish
- /groups + groups-page selectors added to page-shell.css and
  page-cards.css so the new page inherits the same background, padding,
  card borders, hover shadow, and summary-card padding.
- .card-toolbar gains a small vertical padding so the larger toolbar
  buttons (now default size, matching Inbounds) don't crowd the top of
  the card-head on Clients and Groups pages.
This commit is contained in:
MHSanaei
2026-05-27 17:30:55 +02:00
parent 7680e27d1d
commit 93eda06878
25 changed files with 2052 additions and 42 deletions
+50
View File
@@ -535,6 +535,56 @@ export const sections: readonly Section[] = [
body: '[\n {\n "client": {\n "email": "alice@example.com",\n "totalGB": 53687091200,\n "expiryTime": 0,\n "enable": true\n },\n "inboundIds": [7]\n },\n {\n "client": {\n "email": "bob@example.com",\n "totalGB": 53687091200,\n "expiryTime": 0,\n "enable": true\n },\n "inboundIds": [7, 9]\n }\n]',
response: '{\n "success": true,\n "obj": {\n "created": 2,\n "skipped": [\n { "email": "alice@example.com", "reason": "email already in use" }\n ]\n }\n}',
},
{
method: 'POST',
path: '/panel/api/clients/bulkAssignGroup',
summary: 'Assign the given group label to many clients in one call. Updates clients.group_name and patches the matching client entry inside every owning inbound\'s settings JSON in a single transaction. Pass an empty group to clear the label. If the group name does not yet exist (in client_groups or as a derived label), it is auto-created as a persistent group.',
body: '{\n "emails": ["alice", "bob"],\n "group": "customer-a"\n}',
response: '{\n "success": true,\n "obj": {\n "affected": 2\n }\n}',
},
{
method: 'POST',
path: '/panel/api/clients/bulkResetTraffic',
summary: 'Zero up/down counters for many clients in one call. Loops the single-reset path so each client is re-enabled across its attached inbounds and pushed to Xray/remote nodes. Returns the count of successfully reset clients.',
body: '{\n "emails": ["alice", "bob"]\n}',
response: '{\n "success": true,\n "obj": {\n "affected": 2\n }\n}',
},
{
method: 'GET',
path: '/panel/api/clients/groups',
summary: 'List all client groups with their member counts. Merges persisted groups (rows in client_groups, including empty placeholders) with the distinct group_name values currently set on clients. Sorted alphabetically (case-insensitive).',
response: '{\n "success": true,\n "obj": [\n { "name": "customer-a", "clientCount": 5 },\n { "name": "internal", "clientCount": 0 }\n ]\n}',
},
{
method: 'GET',
path: '/panel/api/clients/groups/:name/emails',
summary: 'Return just the email list of clients that currently belong to the given group. Useful for fanning a single bulk action over an entire group without round-tripping the full client list.',
params: [
{ name: 'name', in: 'path', type: 'string', desc: 'Group name (URL-encoded).' },
],
response: '{\n "success": true,\n "obj": ["alice", "bob", "carol"]\n}',
},
{
method: 'POST',
path: '/panel/api/clients/groups/create',
summary: 'Create a new empty (placeholder) group. The group becomes selectable in client forms and the filter drawer even before any client is assigned to it. Errors if a group with the same name already exists.',
body: '{\n "name": "customer-a"\n}',
response: '{\n "success": true,\n "obj": {\n "name": "customer-a"\n }\n}',
},
{
method: 'POST',
path: '/panel/api/clients/groups/rename',
summary: 'Rename a group. The new name is applied to the client_groups row AND propagated to every matching client (both clients.group_name and the client entry inside every owning inbound\'s settings JSON) in a single transaction. Returns the number of clients whose label was updated.',
body: '{\n "oldName": "customer-a",\n "newName": "tier-1"\n}',
response: '{\n "success": true,\n "obj": {\n "affected": 5\n }\n}',
},
{
method: 'POST',
path: '/panel/api/clients/groups/delete',
summary: 'Remove a group. Deletes the client_groups row and clears the group label from every matching client (both clients.group_name and the inbound settings JSON). The clients themselves are NOT deleted — use /bulkDel after filtering by group for that. Returns the count of clients whose label was cleared.',
body: '{\n "name": "customer-a"\n}',
response: '{\n "success": true,\n "obj": {\n "affected": 5\n }\n}',
},
{
method: 'POST',
path: '/panel/api/clients/resetTraffic/:email',
@@ -0,0 +1,83 @@
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { AutoComplete, Form, Modal, message } from 'antd';
interface BulkAssignGroupModalProps {
open: boolean;
count: number;
groups: string[];
onOpenChange: (open: boolean) => void;
onSubmit: (group: string) => Promise<{ affected?: number } | null>;
}
export default function BulkAssignGroupModal({
open,
count,
groups,
onOpenChange,
onSubmit,
}: BulkAssignGroupModalProps) {
const { t } = useTranslation();
const [messageApi, messageContextHolder] = message.useMessage();
const [value, setValue] = useState('');
const [submitting, setSubmitting] = useState(false);
useEffect(() => {
if (open) setValue('');
}, [open]);
async function submit() {
const next = value.trim();
setSubmitting(true);
try {
const result = await onSubmit(next);
if (result) {
const affected = result.affected ?? 0;
if (next === '') {
messageApi.success(t('pages.clients.assignGroupClearedToast', { count: affected }));
} else {
messageApi.success(t('pages.clients.assignGroupAssignedToast', { count: affected, group: next }));
}
onOpenChange(false);
}
} finally {
setSubmitting(false);
}
}
return (
<>
{messageContextHolder}
<Modal
open={open}
title={t('pages.clients.assignGroupTitle', { count })}
okText={t('save')}
cancelText={t('cancel')}
confirmLoading={submitting}
onCancel={() => onOpenChange(false)}
onOk={submit}
destroyOnHidden
>
<Form layout="vertical">
<Form.Item
label={t('pages.clients.group')}
tooltip={t('pages.clients.assignGroupTooltip')}
>
<AutoComplete
value={value}
placeholder={t('pages.clients.assignGroupPlaceholder')}
options={groups.map((g) => ({ value: g }))}
onChange={(v) => setValue(v ?? '')}
filterOption={(input, option) =>
String(option?.value ?? '').toLowerCase().includes((input || '').toLowerCase())
}
allowClear
style={{ width: '100%' }}
autoFocus
/>
</Form.Item>
</Form>
</Modal>
</>
);
}
@@ -1,6 +1,6 @@
import { useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Form, Input, InputNumber, Modal, Select, Space, Switch, message } from 'antd';
import { AutoComplete, Button, Form, Input, InputNumber, Modal, Select, Space, Switch, message } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
@@ -21,6 +21,7 @@ interface ClientBulkAddModalProps {
open: boolean;
inbounds: InboundOption[];
ipLimitEnable?: boolean;
groups?: string[];
onOpenChange: (open: boolean) => void;
onSaved?: () => void;
}
@@ -36,6 +37,7 @@ function emptyForm(): FormState {
emailPostfix: '',
quantity: 1,
subId: '',
group: '',
comment: '',
flow: '',
limitIp: 0,
@@ -50,6 +52,7 @@ export default function ClientBulkAddModal({
open,
inbounds,
ipLimitEnable = false,
groups = [],
onOpenChange,
onSaved,
}: ClientBulkAddModalProps) {
@@ -157,6 +160,7 @@ export default function ClientBulkAddModal({
expiryTime: form.expiryTime,
reset: Number(form.reset) || 0,
limitIp: Number(form.limitIp) || 0,
group: form.group,
comment: form.comment,
enable: true,
},
@@ -263,6 +267,20 @@ export default function ClientBulkAddModal({
</Space.Compact>
</Form.Item>
<Form.Item label={t('pages.clients.group')} tooltip={t('pages.clients.groupDesc')}>
<AutoComplete
value={form.group}
placeholder={t('pages.clients.groupPlaceholder')}
options={groups.map((g) => ({ value: g }))}
onChange={(v) => update('group', v ?? '')}
filterOption={(input, option) =>
String(option?.value ?? '').toLowerCase().includes((input || '').toLowerCase())
}
allowClear
style={{ width: '100%' }}
/>
</Form.Item>
<Form.Item label={t('comment')}>
<Input value={form.comment} onChange={(e) => update('comment', e.target.value)} />
</Form.Item>
@@ -1,6 +1,7 @@
import { useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
AutoComplete,
Button,
Col,
Form,
@@ -61,6 +62,7 @@ interface ClientFormModalProps {
attachedIds?: number[];
ipLimitEnable?: boolean;
tgBotEnable?: boolean;
groups?: string[];
save: (
payload: Record<string, unknown> | SaveCreatePayload,
meta: SaveMetaEdit | SaveMetaCreate,
@@ -83,6 +85,7 @@ interface FormState {
reset: number;
limitIp: number;
tgId: number;
group: string;
comment: string;
enable: boolean;
inboundIds: number[];
@@ -104,6 +107,7 @@ function emptyForm(): FormState {
reset: 0,
limitIp: 0,
tgId: 0,
group: '',
comment: '',
enable: true,
inboundIds: [],
@@ -128,6 +132,7 @@ export default function ClientFormModal({
attachedIds = [],
ipLimitEnable = false,
tgBotEnable = false,
groups = [],
save,
onOpenChange,
}: ClientFormModalProps) {
@@ -163,6 +168,7 @@ export default function ClientFormModal({
reset: Number(client.reset) || 0,
limitIp: client.limitIp || 0,
tgId: Number(client.tgId) || 0,
group: client.group || '',
comment: client.comment || '',
enable: !!client.enable,
inboundIds: Array.isArray(attachedIds) ? [...attachedIds] : [],
@@ -287,6 +293,7 @@ export default function ClientFormModal({
reset: form.reset,
limitIp: form.limitIp,
tgId: form.tgId,
group: form.group,
comment: form.comment,
enable: form.enable,
inboundIds: form.inboundIds,
@@ -507,6 +514,21 @@ export default function ClientFormModal({
<Input value={form.comment} onChange={(e) => update('comment', e.target.value)} />
</Form.Item>
</Col>
<Col xs={24} md={12}>
<Form.Item label={t('pages.clients.group')} tooltip={t('pages.clients.groupDesc')}>
<AutoComplete
value={form.group}
placeholder={t('pages.clients.groupPlaceholder')}
options={groups.map((g) => ({ value: g }))}
onChange={(v) => update('group', v ?? '')}
filterOption={(input, option) =>
String(option?.value ?? '').toLowerCase().includes((input || '').toLowerCase())
}
allowClear
style={{ width: '100%' }}
/>
</Form.Item>
</Col>
</Row>
<Form.Item label={t('pages.clients.attachedInbounds')} required={!isEdit}>
@@ -74,6 +74,7 @@
align-items: center;
gap: 8px;
flex-wrap: wrap;
padding: 6px 0;
}
.email-cell {
+118 -14
View File
@@ -31,6 +31,7 @@ import {
EditOutlined,
FilterOutlined,
InfoCircleOutlined,
LinkOutlined,
MoreOutlined,
PlusOutlined,
QrcodeOutlined,
@@ -38,6 +39,7 @@ import {
RetweetOutlined,
SearchOutlined,
SortAscendingOutlined,
TagsOutlined,
TeamOutlined,
UsergroupAddOutlined,
} from '@ant-design/icons';
@@ -58,6 +60,8 @@ const ClientQrModal = lazy(() => import('./ClientQrModal'));
const ClientBulkAddModal = lazy(() => import('./ClientBulkAddModal'));
const ClientBulkAdjustModal = lazy(() => import('./ClientBulkAdjustModal'));
const FilterDrawer = lazy(() => import('./FilterDrawer'));
const SubLinksModal = lazy(() => import('./SubLinksModal'));
const BulkAssignGroupModal = lazy(() => import('./BulkAssignGroupModal'));
import { emptyFilters, activeFilterCount } from './filters';
import type { ClientFilters } from './filters';
import './ClientsPage.css';
@@ -97,6 +101,7 @@ function readFilterState(): PersistedFilterState {
buckets: Array.isArray(fromRaw.buckets) ? fromRaw.buckets : [],
protocols: Array.isArray(fromRaw.protocols) ? fromRaw.protocols : [],
inboundIds: Array.isArray(fromRaw.inboundIds) ? fromRaw.inboundIds : [],
groups: Array.isArray(fromRaw.groups) ? fromRaw.groups : [],
},
};
} catch {
@@ -140,10 +145,11 @@ export default function ClientsPage() {
const {
clients, filtered,
summary: serverSummary,
allGroups,
setQuery,
inbounds, onlines, loading, fetched, subSettings,
ipLimitEnable, tgBotEnable, expireDiff, trafficDiff, pageSize,
create, update, remove, bulkDelete, bulkAdjust, attach, detach,
create, update, remove, bulkDelete, bulkAdjust, bulkAssignGroup, attach, detach,
resetTraffic, resetAllTraffics, delDepleted, setEnable,
applyTrafficEvent, applyClientStatsEvent,
hydrate,
@@ -165,6 +171,8 @@ export default function ClientsPage() {
const [qrClient, setQrClient] = useState<ClientRecord | null>(null);
const [bulkAddOpen, setBulkAddOpen] = useState(false);
const [bulkAdjustOpen, setBulkAdjustOpen] = useState(false);
const [subLinksOpen, setSubLinksOpen] = useState(false);
const [bulkGroupOpen, setBulkGroupOpen] = useState(false);
const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
const initial = readFilterState();
@@ -210,6 +218,7 @@ export default function ClientsPage() {
autoRenew: filters.autoRenew || undefined,
hasTgId: filters.hasTgId || undefined,
hasComment: filters.hasComment || undefined,
group: filters.groups.join(',') || undefined,
sort: sortColumn || undefined,
order: sortOrder || undefined,
});
@@ -236,6 +245,12 @@ export default function ClientsPage() {
return [...values].sort();
}, [inbounds]);
const groupOptions = useMemo(() => {
const values = new Set<string>(allGroups);
for (const g of filters.groups) values.add(g);
return [...values].sort((a, b) => a.localeCompare(b));
}, [allGroups, filters.groups]);
const isOnline = useCallback((email: string) => !!email && onlineSet.has(email), [onlineSet]);
function inboundLabel(id: number) {
@@ -562,6 +577,29 @@ export default function ClientsPage() {
</div>
),
},
{
title: t('pages.clients.group'),
key: 'group',
width: 130,
render: (_v, record) => {
if (!record.group) return <span style={{ color: 'rgba(0,0,0,0.45)' }}></span>;
const isActive = filters.groups.includes(record.group);
return (
<Tag
color="geekblue"
style={{ margin: 0, cursor: 'pointer', opacity: isActive ? 0.6 : 1 }}
onClick={(e) => {
e.stopPropagation();
if (!isActive) {
setFilters({ ...filters, groups: [...filters.groups, record.group!] });
}
}}
>
{record.group}
</Tag>
);
},
},
{
title: t('pages.clients.attachedInbounds'),
key: 'inboundIds',
@@ -627,7 +665,7 @@ export default function ClientsPage() {
),
},
// eslint-disable-next-line react-hooks/exhaustive-deps
], [t, togglingEmail, clientBucket, isOnline, inboundsById]);
], [t, togglingEmail, clientBucket, isOnline, inboundsById, filters]);
const tablePagination = {
current: currentPage,
@@ -740,28 +778,56 @@ export default function ClientsPage() {
hoverable
title={
<div className="card-toolbar">
<Button type="primary" size="small" icon={<PlusOutlined />} onClick={onAdd}>
<Button type="primary" icon={<PlusOutlined />} onClick={onAdd}>
{!isMobile && t('pages.clients.addClients')}
</Button>
<Button size="small" icon={<UsergroupAddOutlined />} onClick={() => setBulkAddOpen(true)}>
{!isMobile && t('pages.clients.bulk')}
</Button>
{selectedRowKeys.length > 0 && (
<>
<Button size="small" icon={<ClockCircleOutlined />} onClick={() => setBulkAdjustOpen(true)}>
<Button icon={<ClockCircleOutlined />} onClick={() => setBulkAdjustOpen(true)}>
{t('pages.clients.adjustSelected', { count: selectedRowKeys.length })}
</Button>
<Button danger size="small" icon={<DeleteOutlined />} onClick={onBulkDelete}>
<Button icon={<TagsOutlined />} onClick={() => setBulkGroupOpen(true)}>
{t('pages.clients.assignGroupSelected', { count: selectedRowKeys.length })}
</Button>
<Button icon={<LinkOutlined />} onClick={() => setSubLinksOpen(true)}>
{t('pages.clients.subLinksSelected', { count: selectedRowKeys.length })}
</Button>
<Button danger icon={<DeleteOutlined />} onClick={onBulkDelete}>
{t('pages.clients.deleteSelected', { count: selectedRowKeys.length })}
</Button>
</>
)}
<Button size="small" icon={<RetweetOutlined />} onClick={onResetAllTraffics}>
{!isMobile && t('pages.clients.resetAllTraffics')}
</Button>
<Button size="small" danger icon={<RestOutlined />} onClick={onDelDepleted}>
{!isMobile && t('pages.clients.delDepleted')}
</Button>
<Dropdown
trigger={['click']}
placement="bottomRight"
menu={{
items: [
{
key: 'bulk',
icon: <UsergroupAddOutlined />,
label: t('pages.clients.bulk'),
onClick: () => setBulkAddOpen(true),
},
{
key: 'resetAll',
icon: <RetweetOutlined />,
label: t('pages.clients.resetAllTraffics'),
onClick: onResetAllTraffics,
},
{
key: 'delDepleted',
icon: <RestOutlined />,
label: t('pages.clients.delDepleted'),
danger: true,
onClick: onDelDepleted,
},
],
}}
>
<Button icon={<MoreOutlined />}>
{!isMobile && t('more')}
</Button>
</Dropdown>
</div>
}
>
@@ -838,6 +904,16 @@ export default function ClientsPage() {
{inboundLabel(id)}
</Tag>
))}
{filters.groups.map((g) => (
<Tag
key={`g-${g}`}
closable
color="geekblue"
onClose={() => setFilters({ ...filters, groups: filters.groups.filter((x) => x !== g) })}
>
{t('pages.clients.group')}: {g}
</Tag>
))}
{(filters.expiryFrom || filters.expiryTo) && (
<Tag closable color="purple" onClose={() => clearOneFilter('expiryFrom')}>
{t('pages.clients.expiryTime')}: {filters.expiryFrom ? IntlUtil.formatDate(filters.expiryFrom, datepicker) : '…'}
@@ -1008,6 +1084,7 @@ export default function ClientsPage() {
inbounds={inbounds}
ipLimitEnable={ipLimitEnable}
tgBotEnable={tgBotEnable}
groups={allGroups}
save={onSave}
onOpenChange={setFormOpen}
/>
@@ -1035,6 +1112,7 @@ export default function ClientsPage() {
open={bulkAddOpen}
inbounds={inbounds}
ipLimitEnable={ipLimitEnable}
groups={allGroups}
onOpenChange={setBulkAddOpen}
onSaved={() => setBulkAddOpen(false)}
/>
@@ -1054,6 +1132,31 @@ export default function ClientsPage() {
}}
/>
</LazyMount>
<LazyMount when={subLinksOpen}>
<SubLinksModal
open={subLinksOpen}
emails={selectedRowKeys}
clients={clients}
subSettings={subSettings}
onOpenChange={setSubLinksOpen}
/>
</LazyMount>
<LazyMount when={bulkGroupOpen}>
<BulkAssignGroupModal
open={bulkGroupOpen}
count={selectedRowKeys.length}
groups={allGroups}
onOpenChange={setBulkGroupOpen}
onSubmit={async (group) => {
const msg = await bulkAssignGroup([...selectedRowKeys], group);
if (msg?.success) {
setSelectedRowKeys([]);
return (msg.obj as { affected?: number } | undefined) ?? { affected: 0 };
}
return null;
}}
/>
</LazyMount>
<LazyMount when={filterDrawerOpen}>
<FilterDrawer
open={filterDrawerOpen}
@@ -1062,6 +1165,7 @@ export default function ClientsPage() {
onChange={setFilters}
inbounds={inbounds}
protocols={protocolOptions}
groups={groupOptions}
/>
</LazyMount>
</Layout>
@@ -27,6 +27,7 @@ interface FilterDrawerProps {
onChange: (next: ClientFilters) => void;
inbounds: InboundOption[];
protocols: string[];
groups: string[];
}
const BUCKET_KEYS = ['active', 'expiring', 'depleted', 'deactive', 'online'] as const;
@@ -38,6 +39,7 @@ export default function FilterDrawer({
onChange,
inbounds,
protocols,
groups,
}: FilterDrawerProps) {
const { t } = useTranslation();
@@ -60,6 +62,11 @@ export default function FilterDrawer({
[protocols],
);
const groupOptions = useMemo(
() => groups.map((g) => ({ value: g, label: g })),
[groups],
);
const dateRange: [Dayjs | null, Dayjs | null] = [
filters.expiryFrom ? dayjs(filters.expiryFrom) : null,
filters.expiryTo ? dayjs(filters.expiryTo) : null,
@@ -126,6 +133,21 @@ export default function FilterDrawer({
/>
</Form.Item>
<Form.Item label={t('pages.clients.group')}>
<Select
mode="multiple"
value={filters.groups}
onChange={(v) => patch('groups', v as string[])}
options={groupOptions}
placeholder={t('pages.clients.groupPlaceholder')}
maxTagCount="responsive"
allowClear
showSearch
optionFilterProp="label"
listHeight={220}
/>
</Form.Item>
<Form.Item label={t('pages.clients.expiryTime')}>
<DatePicker.RangePicker
value={dateRange}
@@ -0,0 +1,193 @@
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Alert, Button, Modal, Table, Tooltip, Typography, message } from 'antd';
import type { TableColumnType } from 'antd';
import { CopyOutlined, DownloadOutlined } from '@ant-design/icons';
import type { ClientRecord } from '@/hooks/useClients';
interface SubSettings {
enable: boolean;
subURI: string;
subJsonURI: string;
subJsonEnable: boolean;
}
interface SubLinksModalProps {
open: boolean;
emails: string[];
clients: ClientRecord[];
subSettings?: SubSettings;
onOpenChange: (open: boolean) => void;
}
interface Row {
key: string;
email: string;
subId: string;
link: string;
jsonLink: string;
}
export default function SubLinksModal({
open,
emails,
clients,
subSettings,
onOpenChange,
}: SubLinksModalProps) {
const { t } = useTranslation();
const [messageApi, messageContextHolder] = message.useMessage();
const enabled = !!subSettings?.enable && !!subSettings?.subURI;
const jsonEnabled = !!subSettings?.subJsonEnable && !!subSettings?.subJsonURI;
const rows = useMemo<Row[]>(() => {
if (!enabled) return [];
const byEmail = new Map(clients.map((c) => [c.email, c]));
const out: Row[] = [];
for (const email of emails) {
const c = byEmail.get(email);
if (!c?.subId) continue;
out.push({
key: email,
email,
subId: c.subId,
link: subSettings!.subURI + c.subId,
jsonLink: jsonEnabled ? subSettings!.subJsonURI + c.subId : '',
});
}
return out;
}, [emails, clients, enabled, jsonEnabled, subSettings]);
const allText = useMemo(
() => rows.map((r) => (jsonEnabled ? `${r.email}\t${r.link}\t${r.jsonLink}` : `${r.email}\t${r.link}`)).join('\n'),
[rows, jsonEnabled],
);
async function copy(text: string, label?: string) {
try {
await navigator.clipboard.writeText(text);
messageApi.success(label || t('copied'));
} catch {
messageApi.error(t('somethingWentWrong'));
}
}
function download() {
const blob = new Blob([allText], { type: 'text/plain;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
a.href = url;
a.download = `sub-links-${stamp}.txt`;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
}
const columns: TableColumnType<Row>[] = [
{
title: t('pages.clients.client'),
dataIndex: 'email',
key: 'email',
width: 180,
ellipsis: true,
},
{
title: t('pages.clients.subLinkColumn'),
dataIndex: 'link',
key: 'link',
ellipsis: true,
render: (link: string) => (
<Tooltip title={link} placement="topLeft">
<Typography.Text copyable={false} ellipsis>{link}</Typography.Text>
</Tooltip>
),
},
{
title: '',
key: 'actions',
width: 64,
render: (_v, row) => (
<Button size="small" type="text" icon={<CopyOutlined />} onClick={() => copy(row.link, t('copied'))} />
),
},
];
if (jsonEnabled) {
columns.splice(2, 0, {
title: t('pages.clients.subJsonLinkColumn'),
dataIndex: 'jsonLink',
key: 'jsonLink',
ellipsis: true,
render: (link: string) => (
<Tooltip title={link} placement="topLeft">
<Typography.Text copyable={false} ellipsis>{link}</Typography.Text>
</Tooltip>
),
});
}
return (
<>
{messageContextHolder}
<Modal
open={open}
title={t('pages.clients.subLinksTitle', { count: rows.length })}
width={780}
footer={
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<Button onClick={() => onOpenChange(false)}>{t('close')}</Button>
<div style={{ display: 'flex', gap: 8 }}>
<Button
icon={<CopyOutlined />}
disabled={rows.length === 0}
onClick={() => copy(allText, t('pages.clients.subLinksCopiedAll', { count: rows.length }))}
>
{t('pages.clients.subLinksCopyAll')}
</Button>
<Button
type="primary"
icon={<DownloadOutlined />}
disabled={rows.length === 0}
onClick={download}
>
{t('download')}
</Button>
</div>
</div>
}
onCancel={() => onOpenChange(false)}
>
{!enabled && (
<Alert
type="warning"
showIcon
message={t('pages.clients.subLinksDisabled')}
description={t('pages.clients.subLinksDisabledHint')}
style={{ marginBottom: 12 }}
/>
)}
{enabled && rows.length === 0 && (
<Alert
type="info"
showIcon
message={t('pages.clients.subLinksEmpty')}
style={{ marginBottom: 12 }}
/>
)}
{rows.length > 0 && (
<Table<Row>
dataSource={rows}
columns={columns}
size="small"
pagination={false}
scroll={{ y: 360 }}
/>
)}
</Modal>
</>
);
}
+3
View File
@@ -2,6 +2,7 @@ export interface ClientFilters {
buckets: string[];
protocols: string[];
inboundIds: number[];
groups: string[];
expiryFrom?: number;
expiryTo?: number;
usageFromGB?: number;
@@ -16,6 +17,7 @@ export function emptyFilters(): ClientFilters {
buckets: [],
protocols: [],
inboundIds: [],
groups: [],
autoRenew: '',
hasTgId: '',
hasComment: '',
@@ -27,6 +29,7 @@ export function activeFilterCount(f: ClientFilters): number {
if (f.buckets.length) n++;
if (f.protocols.length) n++;
if (f.inboundIds.length) n++;
if (f.groups.length) n++;
if (f.expiryFrom || f.expiryTo) n++;
if (f.usageFromGB || f.usageToGB) n++;
if (f.autoRenew) n++;
+528
View File
@@ -0,0 +1,528 @@
import { lazy, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
Button,
Card,
Col,
ConfigProvider,
Dropdown,
Form,
Input,
Layout,
Modal,
Row,
Space,
Spin,
Statistic,
Table,
Tag,
Tooltip,
message,
} from 'antd';
import type { MenuProps, TableColumnsType } from 'antd';
import {
ClockCircleOutlined,
DeleteOutlined,
EditOutlined,
LinkOutlined,
MoreOutlined,
PlusOutlined,
RetweetOutlined,
TagsOutlined,
TeamOutlined,
} from '@ant-design/icons';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useTheme } from '@/hooks/useTheme';
import { useMediaQuery } from '@/hooks/useMediaQuery';
import { usePageTitle } from '@/hooks/usePageTitle';
import { useClients } from '@/hooks/useClients';
import { HttpUtil } from '@/utils';
import { setMessageInstance } from '@/utils/messageBus';
import AppSidebar from '@/components/AppSidebar';
import LazyMount from '@/components/LazyMount';
import { keys } from '@/api/queryKeys';
import { GroupSummaryListSchema, type GroupSummary } from '@/schemas/client';
import { parseMsg } from '@/utils/zodValidate';
const SubLinksModal = lazy(() => import('../clients/SubLinksModal'));
const ClientBulkAdjustModal = lazy(() => import('../clients/ClientBulkAdjustModal'));
const JSON_HEADERS = { headers: { 'Content-Type': 'application/json' } } as const;
async function fetchGroups(): Promise<GroupSummary[]> {
const msg = await HttpUtil.get('/panel/api/clients/groups', undefined, { silent: true });
if (!msg?.success) throw new Error(msg?.msg || 'Failed to load groups');
const validated = parseMsg(msg, GroupSummaryListSchema, 'clients/groups');
return validated.obj ?? [];
}
async function fetchEmailsForGroup(name: string): Promise<string[]> {
const msg = await HttpUtil.get<string[]>(
`/panel/api/clients/groups/${encodeURIComponent(name)}/emails`,
undefined,
{ silent: true },
);
if (!msg?.success || !Array.isArray(msg.obj)) return [];
return msg.obj;
}
export default function GroupsPage() {
usePageTitle();
const { t } = useTranslation();
const { isDark, isUltra, antdThemeConfig } = useTheme();
const { isMobile } = useMediaQuery();
const [modal, modalContextHolder] = Modal.useModal();
const [messageApi, messageContextHolder] = message.useMessage();
useEffect(() => { setMessageInstance(messageApi); }, [messageApi]);
const queryClient = useQueryClient();
const { clients, subSettings, bulkAdjust, bulkDelete } = useClients();
const groupsQuery = useQuery({
queryKey: keys.clients.groups(),
queryFn: fetchGroups,
});
const groups = useMemo(() => groupsQuery.data ?? [], [groupsQuery.data]);
const loading = groupsQuery.isFetching;
const fetched = groupsQuery.data !== undefined;
const invalidate = useCallback(() => {
queryClient.invalidateQueries({ queryKey: keys.clients.root() });
}, [queryClient]);
const createMut = useMutation({
mutationFn: (body: { name: string }) =>
HttpUtil.post('/panel/api/clients/groups/create', body, JSON_HEADERS),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
});
const renameMut = useMutation({
mutationFn: (body: { oldName: string; newName: string }) =>
HttpUtil.post('/panel/api/clients/groups/rename', body, JSON_HEADERS),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
});
const deleteMut = useMutation({
mutationFn: (body: { name: string }) =>
HttpUtil.post('/panel/api/clients/groups/delete', body, JSON_HEADERS),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
});
const bulkResetMut = useMutation({
mutationFn: (body: { emails: string[] }) =>
HttpUtil.post('/panel/api/clients/bulkResetTraffic', body, JSON_HEADERS),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
});
const [createOpen, setCreateOpen] = useState(false);
const [createName, setCreateName] = useState('');
const [renameOpen, setRenameOpen] = useState(false);
const [renameTarget, setRenameTarget] = useState<GroupSummary | null>(null);
const [renameValue, setRenameValue] = useState('');
const [subLinksOpen, setSubLinksOpen] = useState(false);
const [adjustOpen, setAdjustOpen] = useState(false);
const [groupEmails, setGroupEmails] = useState<string[]>([]);
const [groupForAction, setGroupForAction] = useState<GroupSummary | null>(null);
const totalGroups = groups.length;
const totalClients = useMemo(
() => groups.reduce((acc, g) => acc + (g.clientCount || 0), 0),
[groups],
);
const emptyGroups = useMemo(
() => groups.filter((g) => (g.clientCount || 0) === 0).length,
[groups],
);
function openCreate() {
setCreateName('');
setCreateOpen(true);
}
async function confirmCreate() {
const name = createName.trim();
if (!name) return;
if (groups.some((g) => g.name.toLowerCase() === name.toLowerCase())) {
messageApi.error(t('pages.groups.renameCollision', { name }));
return;
}
const msg = await createMut.mutateAsync({ name });
if (msg?.success) {
messageApi.success(t('pages.groups.createSuccess', { name }));
setCreateOpen(false);
}
}
function openRename(g: GroupSummary) {
setRenameTarget(g);
setRenameValue(g.name);
setRenameOpen(true);
}
async function confirmRename() {
if (!renameTarget) return;
const next = renameValue.trim();
if (!next || next === renameTarget.name) {
setRenameOpen(false);
return;
}
if (groups.some((g) => g.name.toLowerCase() === next.toLowerCase() && g.name !== renameTarget.name)) {
messageApi.error(t('pages.groups.renameCollision', { name: next }));
return;
}
const msg = await renameMut.mutateAsync({ oldName: renameTarget.name, newName: next });
if (msg?.success) {
const affected = (msg.obj as { affected?: number } | undefined)?.affected ?? 0;
messageApi.success(t('pages.groups.renameSuccess', { count: affected }));
setRenameOpen(false);
}
}
function onDelete(g: GroupSummary) {
modal.confirm({
title: t('pages.groups.deleteConfirmTitle', { name: g.name }),
content: t('pages.groups.deleteConfirmContent', { count: g.clientCount }),
okText: t('delete'),
okType: 'danger',
cancelText: t('cancel'),
onOk: async () => {
const msg = await deleteMut.mutateAsync({ name: g.name });
if (msg?.success) {
const affected = (msg.obj as { affected?: number } | undefined)?.affected ?? 0;
messageApi.success(t('pages.groups.deleteSuccess', { count: affected }));
}
},
});
}
async function openSubLinksFor(g: GroupSummary) {
if (!g.clientCount) {
messageApi.info(t('pages.groups.emptyForAction'));
return;
}
const emails = await fetchEmailsForGroup(g.name);
if (emails.length === 0) {
messageApi.info(t('pages.groups.emptyForAction'));
return;
}
setGroupForAction(g);
setGroupEmails(emails);
setSubLinksOpen(true);
}
async function openAdjustFor(g: GroupSummary) {
if (!g.clientCount) {
messageApi.info(t('pages.groups.emptyForAction'));
return;
}
const emails = await fetchEmailsForGroup(g.name);
if (emails.length === 0) {
messageApi.info(t('pages.groups.emptyForAction'));
return;
}
setGroupForAction(g);
setGroupEmails(emails);
setAdjustOpen(true);
}
function onDeleteClients(g: GroupSummary) {
if (!g.clientCount) {
messageApi.info(t('pages.groups.emptyForAction'));
return;
}
modal.confirm({
title: t('pages.groups.deleteClientsConfirmTitle', { name: g.name }),
content: t('pages.groups.deleteClientsConfirmContent', { count: g.clientCount }),
okText: t('delete'),
okType: 'danger',
cancelText: t('cancel'),
onOk: async () => {
const emails = await fetchEmailsForGroup(g.name);
if (emails.length === 0) return;
const msg = await bulkDelete(emails);
if (msg?.success) {
const ok = msg.obj?.deleted ?? 0;
const skipped = msg.obj?.skipped ?? [];
const failed = skipped.length;
if (failed === 0) {
messageApi.success(t('pages.groups.deleteClientsSuccess', { count: ok }));
} else {
const firstError = skipped[0]?.reason ?? msg?.msg ?? '';
messageApi.warning(firstError
? `${t('pages.groups.deleteClientsMixed', { ok, failed })} — ${firstError}`
: t('pages.groups.deleteClientsMixed', { ok, failed }));
}
}
},
});
}
function onResetTraffic(g: GroupSummary) {
if (!g.clientCount) {
messageApi.info(t('pages.groups.emptyForAction'));
return;
}
modal.confirm({
title: t('pages.groups.resetConfirmTitle', { name: g.name }),
content: t('pages.groups.resetConfirmContent', { count: g.clientCount }),
okText: t('reset'),
okType: 'danger',
cancelText: t('cancel'),
onOk: async () => {
const emails = await fetchEmailsForGroup(g.name);
if (emails.length === 0) return;
const msg = await bulkResetMut.mutateAsync({ emails });
if (msg?.success) {
const affected = (msg.obj as { affected?: number } | undefined)?.affected ?? emails.length;
messageApi.success(t('pages.groups.resetSuccess', { count: affected }));
}
},
});
}
function rowActions(row: GroupSummary): MenuProps['items'] {
return [
{
key: 'subLinks',
icon: <LinkOutlined />,
label: t('pages.clients.subLinksSelected', { count: row.clientCount || 0 }),
disabled: !row.clientCount,
onClick: () => openSubLinksFor(row),
},
{
key: 'adjust',
icon: <ClockCircleOutlined />,
label: t('pages.clients.adjustSelected', { count: row.clientCount || 0 }),
disabled: !row.clientCount,
onClick: () => openAdjustFor(row),
},
{
key: 'reset',
icon: <RetweetOutlined />,
label: t('pages.groups.resetTraffic'),
disabled: !row.clientCount,
onClick: () => onResetTraffic(row),
},
{ type: 'divider' },
{
key: 'rename',
icon: <EditOutlined />,
label: t('pages.groups.rename'),
onClick: () => openRename(row),
},
{
key: 'deleteClients',
icon: <DeleteOutlined />,
label: t('pages.groups.deleteClients'),
danger: true,
disabled: !row.clientCount,
onClick: () => onDeleteClients(row),
},
{
key: 'delete',
icon: <DeleteOutlined />,
label: t('pages.groups.deleteGroupOnly'),
danger: true,
onClick: () => onDelete(row),
},
];
}
const columns: TableColumnsType<GroupSummary> = [
{
title: t('pages.clients.actions'),
key: 'actions',
width: 90,
render: (_v, row) => (
<Space size={4}>
<Dropdown trigger={['click']} menu={{ items: rowActions(row) }}>
<Button size="small" type="text" icon={<MoreOutlined />} />
</Dropdown>
<Tooltip title={t('pages.groups.rename')}>
<Button size="small" type="text" icon={<EditOutlined />} onClick={() => openRename(row)} />
</Tooltip>
</Space>
),
},
{
title: t('pages.groups.name'),
dataIndex: 'name',
key: 'name',
render: (name: string) => <Tag color="geekblue" style={{ margin: 0, fontSize: 13 }}>{name}</Tag>,
},
{
title: t('pages.groups.clientCount'),
dataIndex: 'clientCount',
key: 'clientCount',
width: 180,
render: (count: number) => <span>{count || 0}</span>,
},
];
const pageClass = useMemo(() => {
const classes = ['groups-page'];
if (isDark) classes.push('is-dark');
if (isUltra) classes.push('is-ultra');
return classes.join(' ');
}, [isDark, isUltra]);
return (
<ConfigProvider theme={antdThemeConfig}>
{messageContextHolder}
{modalContextHolder}
<Layout className={pageClass}>
<AppSidebar />
<Layout className="content-shell">
<Layout.Content id="content-layout" className="content-area">
<Spin spinning={!fetched} delay={200} description="Loading…" size="large">
{!fetched ? (
<div className="loading-spacer" />
) : (
<Row gutter={[isMobile ? 8 : 16, isMobile ? 8 : 12]}>
<Col span={24}>
<Card size="small" hoverable className="summary-card">
<Row gutter={[16, isMobile ? 16 : 12]}>
<Col xs={12} sm={8} md={6}>
<Statistic
title={t('pages.groups.totalGroups')}
value={String(totalGroups)}
prefix={<TagsOutlined />}
/>
</Col>
<Col xs={12} sm={8} md={6}>
<Statistic
title={t('pages.groups.totalGroupedClients')}
value={String(totalClients)}
prefix={<TeamOutlined />}
/>
</Col>
<Col xs={12} sm={8} md={6}>
<Statistic
title={t('pages.groups.emptyGroups')}
value={String(emptyGroups)}
/>
</Col>
</Row>
</Card>
</Col>
<Col span={24}>
<Card
size="small"
hoverable
title={
<div className="card-toolbar">
<Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
{!isMobile && t('pages.groups.addGroup')}
</Button>
</div>
}
>
<Table<GroupSummary>
dataSource={groups}
columns={columns}
rowKey="name"
size="small"
pagination={false}
loading={loading}
locale={{
emptyText: (
<div className="card-empty">
<TagsOutlined style={{ fontSize: 32, marginBottom: 8 }} />
<div>{t('noData')}</div>
</div>
),
}}
/>
</Card>
</Col>
</Row>
)}
</Spin>
</Layout.Content>
</Layout>
<Modal
open={createOpen}
title={t('pages.groups.addGroup')}
okText={t('create')}
cancelText={t('cancel')}
confirmLoading={createMut.isPending}
onCancel={() => setCreateOpen(false)}
onOk={confirmCreate}
destroyOnHidden
>
<Form layout="vertical">
<Form.Item label={t('pages.groups.name')}>
<Input
value={createName}
onChange={(e) => setCreateName(e.target.value)}
onPressEnter={confirmCreate}
placeholder={t('pages.clients.groupPlaceholder')}
autoFocus
/>
</Form.Item>
</Form>
</Modal>
<Modal
open={renameOpen}
title={renameTarget ? t('pages.groups.renameTitle', { name: renameTarget.name }) : ''}
okText={t('save')}
cancelText={t('cancel')}
confirmLoading={renameMut.isPending}
onCancel={() => setRenameOpen(false)}
onOk={confirmRename}
destroyOnHidden
>
<Form layout="vertical">
<Form.Item label={t('pages.groups.name')}>
<Input
value={renameValue}
onChange={(e) => setRenameValue(e.target.value)}
onPressEnter={confirmRename}
placeholder={t('pages.clients.groupPlaceholder')}
autoFocus
/>
</Form.Item>
</Form>
</Modal>
<LazyMount when={subLinksOpen}>
<SubLinksModal
open={subLinksOpen}
emails={groupEmails}
clients={clients}
subSettings={subSettings}
onOpenChange={setSubLinksOpen}
/>
</LazyMount>
<LazyMount when={adjustOpen}>
<ClientBulkAdjustModal
open={adjustOpen}
count={groupEmails.length}
onOpenChange={setAdjustOpen}
onSubmit={async (addDays, addBytes) => {
const msg = await bulkAdjust(groupEmails, addDays, addBytes);
if (msg?.success) {
const obj = msg.obj ?? { adjusted: 0 };
messageApi.success(
t('pages.groups.adjustSuccess', {
count: obj.adjusted ?? 0,
name: groupForAction?.name ?? '',
}),
);
return obj;
}
return null;
}}
/>
</LazyMount>
</Layout>
</ConfigProvider>
);
}