ClientsPage.tsx 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630
  1. import { lazy, useCallback, useEffect, useMemo, useState } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import {
  4. Badge,
  5. Button,
  6. Card,
  7. Checkbox,
  8. Col,
  9. ConfigProvider,
  10. Dropdown,
  11. Input,
  12. Layout,
  13. Modal,
  14. Pagination,
  15. Popover,
  16. Result,
  17. Row,
  18. Select,
  19. Space,
  20. Spin,
  21. Statistic,
  22. Switch,
  23. Table,
  24. Tag,
  25. Tooltip,
  26. message,
  27. } from 'antd';
  28. import type { ColumnsType, TableProps } from 'antd/es/table';
  29. import {
  30. CheckCircleOutlined,
  31. ClockCircleOutlined,
  32. DeleteOutlined,
  33. DisconnectOutlined,
  34. DownloadOutlined,
  35. EditOutlined,
  36. FilterOutlined,
  37. InfoCircleOutlined,
  38. LinkOutlined,
  39. MoreOutlined,
  40. PlusOutlined,
  41. QrcodeOutlined,
  42. RestOutlined,
  43. RetweetOutlined,
  44. SearchOutlined,
  45. SortAscendingOutlined,
  46. StopOutlined,
  47. TagsOutlined,
  48. TeamOutlined,
  49. UploadOutlined,
  50. UsergroupAddOutlined,
  51. UsergroupDeleteOutlined,
  52. } from '@ant-design/icons';
  53. import { activateOnKey } from '@/utils/a11y';
  54. import { useTheme } from '@/hooks/useTheme';
  55. import { formatInboundLabel } from '@/lib/inbounds/label';
  56. import { useMediaQuery } from '@/hooks/useMediaQuery';
  57. import { useWebSocket } from '@/hooks/useWebSocket';
  58. import { useClients } from '@/hooks/useClients';
  59. import { useNodesQuery } from '@/api/queries/useNodesQuery';
  60. import { useDatepicker } from '@/hooks/useDatepicker';
  61. import type { ClientRecord, InboundOption, ExternalLink, ExternalLinkInput } from '@/hooks/useClients';
  62. import ClientTrafficCell from '@/components/clients/ClientTrafficCell';
  63. import ClientSpeedTag, { isActiveSpeed } from '@/components/clients/ClientSpeedTag';
  64. import AppSidebar from '@/layouts/AppSidebar';
  65. import { IntlUtil, SizeFormatter } from '@/utils';
  66. import { setMessageInstance } from '@/utils/messageBus';
  67. import { LazyMount } from '@/components/utility';
  68. const ClientFormModal = lazy(() => import('./ClientFormModal'));
  69. const ClientInfoModal = lazy(() => import('./ClientInfoModal'));
  70. const ClientQrModal = lazy(() => import('./ClientQrModal'));
  71. const ClientBulkAddModal = lazy(() => import('./ClientBulkAddModal'));
  72. const ClientBulkAdjustModal = lazy(() => import('./ClientBulkAdjustModal'));
  73. const FilterDrawer = lazy(() => import('./FilterDrawer'));
  74. const SubLinksModal = lazy(() => import('./SubLinksModal'));
  75. const BulkAddToGroupModal = lazy(() => import('./BulkAddToGroupModal'));
  76. const BulkAttachInboundsModal = lazy(() => import('./BulkAttachInboundsModal'));
  77. const BulkDetachInboundsModal = lazy(() => import('./BulkDetachInboundsModal'));
  78. const TextModal = lazy(() => import('@/components/feedback/TextModal'));
  79. const PromptModal = lazy(() => import('@/components/feedback/PromptModal'));
  80. import { emptyFilters, activeFilterCount } from './filters';
  81. import type { ClientFilters } from './filters';
  82. import './ClientsPage.css';
  83. const FILTER_STATE_KEY = 'clientsFilterState';
  84. const DISABLED_PAGE_SIZE = 200;
  85. function UngroupIcon() {
  86. return (
  87. <span
  88. style={{
  89. position: 'relative',
  90. display: 'inline-flex',
  91. alignItems: 'center',
  92. justifyContent: 'center',
  93. width: '1em',
  94. height: '1em',
  95. }}
  96. >
  97. <TagsOutlined />
  98. <span
  99. aria-hidden="true"
  100. style={{
  101. position: 'absolute',
  102. inset: 0,
  103. display: 'flex',
  104. alignItems: 'center',
  105. justifyContent: 'center',
  106. pointerEvents: 'none',
  107. }}
  108. >
  109. <span
  110. style={{
  111. display: 'block',
  112. width: '125%',
  113. height: '1.5px',
  114. background: 'currentColor',
  115. transform: 'rotate(-45deg)',
  116. borderRadius: '1px',
  117. }}
  118. />
  119. </span>
  120. </span>
  121. );
  122. }
  123. type Bucket = 'active' | 'deactive' | 'depleted' | 'expiring';
  124. interface PersistedFilterState {
  125. searchKey: string;
  126. filters: ClientFilters;
  127. sort: string;
  128. }
  129. const INBOUND_PROTOCOL_COLORS: Record<string, string> = {
  130. vless: 'blue',
  131. vmess: 'geekblue',
  132. trojan: 'volcano',
  133. shadowsocks: 'magenta',
  134. hysteria: 'cyan',
  135. hysteria2: 'green',
  136. wireguard: 'gold',
  137. http: 'purple',
  138. mixed: 'lime',
  139. tunnel: 'orange',
  140. };
  141. const INBOUND_CHIP_LIMIT = 1;
  142. function readFilterState(): PersistedFilterState {
  143. try {
  144. const raw = JSON.parse(localStorage.getItem(FILTER_STATE_KEY) || '{}');
  145. const fromRaw = (raw.filters ?? {}) as Partial<ClientFilters>;
  146. return {
  147. searchKey: typeof raw.searchKey === 'string' ? raw.searchKey : '',
  148. filters: {
  149. ...emptyFilters(),
  150. ...fromRaw,
  151. buckets: Array.isArray(fromRaw.buckets) ? fromRaw.buckets : [],
  152. protocols: Array.isArray(fromRaw.protocols) ? fromRaw.protocols : [],
  153. inboundIds: Array.isArray(fromRaw.inboundIds) ? fromRaw.inboundIds : [],
  154. nodeIds: Array.isArray(fromRaw.nodeIds) ? fromRaw.nodeIds : [],
  155. groups: Array.isArray(fromRaw.groups) ? fromRaw.groups : [],
  156. },
  157. sort: typeof raw.sort === 'string' ? raw.sort : '',
  158. };
  159. } catch {
  160. return { searchKey: '', filters: emptyFilters(), sort: '' };
  161. }
  162. }
  163. function gbToBytes(gb: number | undefined): number {
  164. if (!gb || gb <= 0) return 0;
  165. return Math.round(gb * 1024 * 1024 * 1024);
  166. }
  167. const SORT_OPTIONS: { value: string; column: string; order: 'ascend' | 'descend'; labelKey: string }[] = [
  168. { value: 'createdAt:ascend', column: 'createdAt', order: 'ascend', labelKey: 'pages.clients.sortOldest' },
  169. { value: 'createdAt:descend', column: 'createdAt', order: 'descend', labelKey: 'pages.clients.sortNewest' },
  170. { value: 'updatedAt:descend', column: 'updatedAt', order: 'descend', labelKey: 'pages.clients.sortRecentlyUpdated' },
  171. { value: 'lastOnline:descend', column: 'lastOnline', order: 'descend', labelKey: 'pages.clients.sortRecentlyOnline' },
  172. { value: 'email:ascend', column: 'email', order: 'ascend', labelKey: 'pages.clients.sortEmailAZ' },
  173. { value: 'email:descend', column: 'email', order: 'descend', labelKey: 'pages.clients.sortEmailZA' },
  174. { value: 'traffic:descend', column: 'traffic', order: 'descend', labelKey: 'pages.clients.sortMostTraffic' },
  175. { value: 'remaining:descend', column: 'remaining', order: 'descend', labelKey: 'pages.clients.sortHighestRemaining' },
  176. { value: 'expiryTime:ascend', column: 'expiryTime', order: 'ascend', labelKey: 'pages.clients.sortExpiringSoonest' },
  177. ];
  178. const DEFAULT_SORT = SORT_OPTIONS[0];
  179. function sortValueFor(column: string | null, order: 'ascend' | 'descend' | null): string {
  180. if (!column || !order) return DEFAULT_SORT.value;
  181. return `${column}:${order}`;
  182. }
  183. export default function ClientsPage() {
  184. const { t } = useTranslation();
  185. const { isDark, isUltra, antdThemeConfig } = useTheme();
  186. const { datepicker } = useDatepicker();
  187. const { isMobile } = useMediaQuery();
  188. const [modal, modalContextHolder] = Modal.useModal();
  189. const [messageApi, messageContextHolder] = message.useMessage();
  190. useEffect(() => { setMessageInstance(messageApi); }, [messageApi]);
  191. const {
  192. clients, total, filtered,
  193. summary: serverSummary,
  194. allGroups,
  195. setQuery,
  196. inbounds, onlines, loading, transitioning, fetched, fetchError, subSettings,
  197. tgBotEnable, expireDiff, trafficDiff, pageSize,
  198. create, update, remove, bulkDelete, bulkAdjust, bulkEnable, bulkDisable, bulkAddToGroup, bulkRemoveFromGroup, attach, setExternalLinks, bulkAttach, detach, bulkDetach,
  199. resetTraffic, resetAllTraffics, delDepleted, delOrphans, exportClients, importClients, setEnable,
  200. clientSpeed,
  201. applyTrafficEvent, applyClientStatsEvent,
  202. refresh,
  203. hydrate,
  204. } = useClients();
  205. useWebSocket({
  206. traffic: applyTrafficEvent,
  207. client_stats: applyClientStatsEvent,
  208. });
  209. // Node list for the Nodes filter; the section only renders when the panel
  210. // actually manages nodes (#4997).
  211. const { nodes } = useNodesQuery();
  212. const [togglingEmail, setTogglingEmail] = useState<string | null>(null);
  213. const [formOpen, setFormOpen] = useState(false);
  214. const [formMode, setFormMode] = useState<'add' | 'edit'>('add');
  215. const [editingClient, setEditingClient] = useState<ClientRecord | null>(null);
  216. const [editingAttachedIds, setEditingAttachedIds] = useState<number[]>([]);
  217. const [editingExternalLinks, setEditingExternalLinks] = useState<ExternalLink[]>([]);
  218. const [infoOpen, setInfoOpen] = useState(false);
  219. const [infoClient, setInfoClient] = useState<ClientRecord | null>(null);
  220. const [qrOpen, setQrOpen] = useState(false);
  221. const [qrClient, setQrClient] = useState<ClientRecord | null>(null);
  222. const [bulkAddOpen, setBulkAddOpen] = useState(false);
  223. const [bulkAdjustOpen, setBulkAdjustOpen] = useState(false);
  224. const [subLinksOpen, setSubLinksOpen] = useState(false);
  225. const [bulkGroupOpen, setBulkGroupOpen] = useState(false);
  226. const [bulkAttachOpen, setBulkAttachOpen] = useState(false);
  227. const [bulkDetachOpen, setBulkDetachOpen] = useState(false);
  228. const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  229. const [textOpen, setTextOpen] = useState(false);
  230. const [textTitle, setTextTitle] = useState('');
  231. const [textContent, setTextContent] = useState('');
  232. const [textFileName, setTextFileName] = useState('');
  233. const [promptOpen, setPromptOpen] = useState(false);
  234. const [promptTitle, setPromptTitle] = useState('');
  235. const [promptOkText, setPromptOkText] = useState('');
  236. const [promptInitial, setPromptInitial] = useState('');
  237. const [promptLoading, setPromptLoading] = useState(false);
  238. const [promptHandler, setPromptHandler] = useState<((value: string) => Promise<boolean | void> | boolean | void) | null>(null);
  239. const initial = readFilterState();
  240. const [searchKey, setSearchKey] = useState(initial.searchKey);
  241. const [filters, setFilters] = useState<ClientFilters>(initial.filters);
  242. const [filterDrawerOpen, setFilterDrawerOpen] = useState(false);
  243. const initialSort = SORT_OPTIONS.find((o) => o.value === initial.sort) ?? DEFAULT_SORT;
  244. const [sortColumn, setSortColumn] = useState<string | null>(initialSort.column);
  245. const [sortOrder, setSortOrder] = useState<'ascend' | 'descend' | null>(initialSort.order);
  246. const [currentPage, setCurrentPage] = useState(1);
  247. const [tablePageSize, setTablePageSize] = useState(25);
  248. // debouncedSearch lags behind the input so we don't spam the server on every
  249. // keystroke; the search box still feels instant locally.
  250. const [debouncedSearch, setDebouncedSearch] = useState(searchKey);
  251. useEffect(() => {
  252. localStorage.setItem(FILTER_STATE_KEY, JSON.stringify({ searchKey, filters, sort: sortValueFor(sortColumn, sortOrder) }));
  253. }, [searchKey, filters, sortColumn, sortOrder]);
  254. useEffect(() => {
  255. const handle = window.setTimeout(() => setDebouncedSearch(searchKey), 300);
  256. return () => window.clearTimeout(handle);
  257. }, [searchKey]);
  258. useEffect(() => {
  259. // Reset to page 1 whenever a filter or sort changes — otherwise an empty
  260. // result set on a high page number leaves the user staring at "no clients".
  261. setCurrentPage(1);
  262. }, [debouncedSearch, filters, sortColumn, sortOrder]);
  263. // The node filter maps onto inbound ids client-side (#4997): the paging API
  264. // already accepts an inbound CSV, so nodes never have to reach the backend.
  265. // Sentinel 0 = "local panel" (inbounds without a nodeId).
  266. const effectiveInboundCsv = useMemo(() => {
  267. if (!filters.nodeIds.length) return filters.inboundIds.join(',');
  268. const nodeSet = new Set(filters.nodeIds);
  269. const nodeInboundIds = inbounds
  270. .filter((ib) => nodeSet.has(ib.nodeId ?? 0))
  271. .map((ib) => ib.id);
  272. const pool = filters.inboundIds.length
  273. ? nodeInboundIds.filter((id) => filters.inboundIds.includes(id))
  274. : nodeInboundIds;
  275. // Nothing matches the selected nodes: send an impossible id so the filter
  276. // yields an honest empty result instead of being silently ignored.
  277. return pool.length ? pool.join(',') : '-1';
  278. }, [filters.nodeIds, filters.inboundIds, inbounds]);
  279. useEffect(() => {
  280. setQuery({
  281. page: currentPage,
  282. pageSize: tablePageSize,
  283. search: debouncedSearch,
  284. filter: filters.buckets.join(','),
  285. protocol: filters.protocols.join(','),
  286. inbound: effectiveInboundCsv,
  287. expiryFrom: filters.expiryFrom,
  288. expiryTo: filters.expiryTo,
  289. usageFrom: gbToBytes(filters.usageFromGB),
  290. usageTo: gbToBytes(filters.usageToGB),
  291. autoRenew: filters.autoRenew || undefined,
  292. hasTgId: filters.hasTgId || undefined,
  293. hasComment: filters.hasComment || undefined,
  294. group: filters.groups.join(',') || undefined,
  295. sort: sortColumn || undefined,
  296. order: sortOrder || undefined,
  297. });
  298. }, [setQuery, currentPage, tablePageSize, debouncedSearch, filters, effectiveInboundCsv, sortColumn, sortOrder]);
  299. const activeCount = activeFilterCount(filters);
  300. useEffect(() => {
  301. setTablePageSize(pageSize > 0 ? pageSize : DISABLED_PAGE_SIZE);
  302. }, [pageSize]);
  303. const onlineSet = useMemo(() => new Set(onlines || []), [onlines]);
  304. const inboundsById = useMemo(() => {
  305. const out: Record<number, InboundOption> = {};
  306. for (const ib of inbounds) out[ib.id] = ib;
  307. return out;
  308. }, [inbounds]);
  309. const protocolOptions = useMemo(() => {
  310. const values = new Set<string>((inbounds || []).map((i) => i.protocol).filter((x): x is string => !!x));
  311. return [...values].sort();
  312. }, [inbounds]);
  313. const groupOptions = useMemo(() => {
  314. const values = new Set<string>(allGroups);
  315. for (const g of filters.groups) values.add(g);
  316. return [...values].sort((a, b) => a.localeCompare(b));
  317. }, [allGroups, filters.groups]);
  318. const isOnline = useCallback((email: string) => !!email && onlineSet.has(email), [onlineSet]);
  319. function inboundLabel(id: number) {
  320. const ib = inboundsById[id];
  321. return formatInboundLabel(ib?.tag, ib?.remark);
  322. }
  323. const clientBucket = useCallback((row: ClientRecord | null | undefined): Bucket | null => {
  324. if (!row) return null;
  325. const traffic = row.traffic || {};
  326. const used = (traffic.up || 0) + (traffic.down || 0);
  327. const total = row.totalGB || 0;
  328. const now = Date.now();
  329. const expired = (row.expiryTime ?? 0) > 0 && (row.expiryTime ?? 0) <= now;
  330. const exhausted = total > 0 && used >= total;
  331. if (expired || exhausted) return 'depleted';
  332. if (!row.enable) return 'deactive';
  333. const nearExpiry = (row.expiryTime ?? 0) > 0 && (row.expiryTime ?? 0) - now < (expireDiff || 0);
  334. const nearLimit = total > 0 && total - used < (trafficDiff || 0);
  335. if (nearExpiry || nearLimit) return 'expiring';
  336. return 'active';
  337. }, [expireDiff, trafficDiff]);
  338. function bucketBadgeStatus(bucket: Bucket | null): 'success' | 'warning' | 'error' | 'default' {
  339. switch (bucket) {
  340. case 'depleted': return 'error';
  341. case 'expiring': return 'warning';
  342. case 'active': return 'success';
  343. default: return 'default';
  344. }
  345. }
  346. // The list page renders rows the server already sorted, filtered, and
  347. // paginated. Local filtering is gone — keep the variable name so the rest
  348. // of the file (table dataSource, mobile cards, select-all) doesn't need
  349. // a rename.
  350. const filteredClients = clients;
  351. // Server-computed counts that stay stable as the user paginates/filters.
  352. const summary = serverSummary;
  353. // Sort is server-side now; the page already arrives in the requested
  354. // order, so we just hand it through.
  355. const sortedClients = filteredClients;
  356. function remainingLabel(row: ClientRecord) {
  357. const total = row.totalGB || 0;
  358. if (total <= 0) return '∞';
  359. const used = (row.traffic?.up || 0) + (row.traffic?.down || 0);
  360. const r = total - used;
  361. return r > 0 ? SizeFormatter.sizeFormat(r) : '0';
  362. }
  363. function remainingColor(row: ClientRecord): string {
  364. const total = row.totalGB || 0;
  365. if (total <= 0) return 'purple';
  366. const used = (row.traffic?.up || 0) + (row.traffic?.down || 0);
  367. const ratio = used / total;
  368. if (ratio >= 1) return 'red';
  369. if (ratio >= 0.85) return 'orange';
  370. return 'green';
  371. }
  372. function expiryLabel(row: ClientRecord) {
  373. if (!row.expiryTime) return '∞';
  374. if (row.expiryTime < 0) {
  375. const days = Math.round(row.expiryTime / -86400000);
  376. return `${t('pages.clients.delayedStart')}: ${days}d`;
  377. }
  378. return IntlUtil.formatDate(row.expiryTime, datepicker);
  379. }
  380. function expiryRelative(row: ClientRecord) {
  381. if (!row.expiryTime) return '';
  382. if (row.expiryTime < 0) {
  383. const days = Math.round(row.expiryTime / -86400000);
  384. return `${days}d`;
  385. }
  386. return IntlUtil.formatRelativeTime(row.expiryTime);
  387. }
  388. function expiryColor(row: ClientRecord): string {
  389. if (!row.expiryTime) return 'purple';
  390. if (row.expiryTime < 0) return 'blue';
  391. const now = Date.now();
  392. if (row.expiryTime <= now) return 'red';
  393. if (row.expiryTime - now < 86400 * 1000 * 3) return 'orange';
  394. return 'green';
  395. }
  396. async function onToggleEnable(row: ClientRecord, next: boolean) {
  397. setTogglingEmail(row.email);
  398. try {
  399. const msg = await setEnable(row, next);
  400. if (!msg?.success) {
  401. messageApi.error(msg?.msg || t('somethingWentWrong'));
  402. }
  403. } finally {
  404. setTogglingEmail(null);
  405. }
  406. }
  407. function onAdd() {
  408. setFormMode('add');
  409. setEditingClient(null);
  410. setEditingAttachedIds([]);
  411. setEditingExternalLinks([]);
  412. setFormOpen(true);
  413. }
  414. async function onEdit(row: ClientRecord) {
  415. setFormMode('edit');
  416. // Paged list omits per-client secrets to keep the row payload tiny;
  417. // edit needs them, so fetch the full record first.
  418. const full = await hydrate(row.email);
  419. const merged: ClientRecord = full ? { ...row, ...full.client } : { ...row };
  420. setEditingClient(merged);
  421. const ids = full?.inboundIds ?? (Array.isArray(row.inboundIds) ? row.inboundIds : []);
  422. setEditingAttachedIds([...ids]);
  423. setEditingExternalLinks(Array.isArray(full?.externalLinks) ? [...full.externalLinks] : []);
  424. setFormOpen(true);
  425. }
  426. function onDelete(row: ClientRecord) {
  427. modal.confirm({
  428. title: t('pages.clients.deleteConfirmTitle', { email: row.email }),
  429. content: t('pages.clients.deleteConfirmContent'),
  430. okText: t('delete'),
  431. okType: 'danger',
  432. cancelText: t('cancel'),
  433. onOk: async () => {
  434. const msg = await remove(row.email);
  435. if (msg?.success) messageApi.success(t('pages.clients.toasts.deleted'));
  436. },
  437. });
  438. }
  439. function onResetTraffic(row: ClientRecord) {
  440. if (!row?.email) {
  441. messageApi.warning(t('pages.clients.resetNotPossible'));
  442. return;
  443. }
  444. modal.confirm({
  445. title: `${t('pages.inbounds.resetTraffic')} — ${row.email}`,
  446. content: t('pages.inbounds.resetTrafficContent'),
  447. okText: t('reset'),
  448. cancelText: t('cancel'),
  449. onOk: async () => {
  450. const msg = await resetTraffic(row);
  451. if (msg?.success) messageApi.success(t('pages.clients.toasts.trafficReset'));
  452. },
  453. });
  454. }
  455. async function onShowInfo(row: ClientRecord) {
  456. const full = await hydrate(row.email);
  457. setInfoClient(full ? { ...row, ...full.client, inboundIds: full.inboundIds } : row);
  458. setInfoOpen(true);
  459. }
  460. async function onShowQr(row: ClientRecord) {
  461. const full = await hydrate(row.email);
  462. setQrClient(full ? { ...row, ...full.client, inboundIds: full.inboundIds } : row);
  463. setQrOpen(true);
  464. }
  465. const openText = useCallback((opts: { title: string; content: string; fileName?: string }) => {
  466. setTextTitle(opts.title);
  467. setTextContent(opts.content);
  468. setTextFileName(opts.fileName || '');
  469. setTextOpen(true);
  470. }, []);
  471. const openPrompt = useCallback((opts: {
  472. title: string;
  473. okText?: string;
  474. value?: string;
  475. confirm: (value: string) => Promise<boolean | void> | boolean | void;
  476. }) => {
  477. setPromptTitle(opts.title);
  478. setPromptOkText(opts.okText || t('confirm'));
  479. setPromptInitial(opts.value || '');
  480. setPromptHandler(() => opts.confirm);
  481. setPromptOpen(true);
  482. }, [t]);
  483. const onPromptConfirm = useCallback(async (value: string) => {
  484. if (!promptHandler) {
  485. setPromptOpen(false);
  486. return;
  487. }
  488. setPromptLoading(true);
  489. try {
  490. const ok = await promptHandler(value);
  491. if (ok !== false) setPromptOpen(false);
  492. } finally {
  493. setPromptLoading(false);
  494. }
  495. }, [promptHandler]);
  496. function onResetAllTraffics() {
  497. modal.confirm({
  498. title: t('pages.clients.resetAllTrafficsTitle'),
  499. content: t('pages.clients.resetAllTrafficsContent'),
  500. okText: t('reset'),
  501. okType: 'danger',
  502. cancelText: t('cancel'),
  503. onOk: async () => {
  504. const msg = await resetAllTraffics();
  505. if (msg?.success) messageApi.success(t('pages.clients.toasts.allTrafficsReset'));
  506. },
  507. });
  508. }
  509. function onDelDepleted() {
  510. modal.confirm({
  511. title: t('pages.clients.delDepletedConfirmTitle'),
  512. content: t('pages.clients.delDepletedConfirmContent'),
  513. okText: t('delete'),
  514. okType: 'danger',
  515. cancelText: t('cancel'),
  516. onOk: async () => {
  517. const msg = await delDepleted();
  518. if (msg?.success) {
  519. const deleted = msg.obj?.deleted ?? 0;
  520. messageApi.success(t('pages.clients.toasts.delDepleted', { count: deleted }));
  521. }
  522. },
  523. });
  524. }
  525. function onDeleteOrphans() {
  526. modal.confirm({
  527. title: t('pages.clients.delOrphansConfirmTitle'),
  528. content: t('pages.clients.delOrphansConfirmContent'),
  529. okText: t('delete'),
  530. okType: 'danger',
  531. cancelText: t('cancel'),
  532. onOk: async () => {
  533. const msg = await delOrphans();
  534. if (msg?.success) {
  535. const deleted = msg.obj?.deleted ?? 0;
  536. messageApi.success(t('pages.clients.toasts.delOrphans', { count: deleted }));
  537. }
  538. },
  539. });
  540. }
  541. async function onExportClients() {
  542. const items = await exportClients();
  543. if (!items) return;
  544. openText({
  545. title: t('pages.clients.exportClients'),
  546. content: JSON.stringify(items, null, 2),
  547. fileName: 'clients-export.json',
  548. });
  549. }
  550. function onImportClients() {
  551. openPrompt({
  552. title: t('pages.clients.importClients'),
  553. okText: t('pages.clients.import'),
  554. value: '',
  555. confirm: async (value) => {
  556. const msg = await importClients(value);
  557. if (!msg?.success) return false;
  558. const created = msg.obj?.created ?? 0;
  559. const skipped = msg.obj?.skipped ?? [];
  560. if (skipped.length === 0) {
  561. messageApi.success(t('pages.clients.toasts.imported', { count: created }));
  562. } else {
  563. const firstError = skipped[0]?.reason ?? '';
  564. messageApi.warning(firstError
  565. ? `${t('pages.clients.toasts.importedMixed', { ok: created, failed: skipped.length })} — ${firstError}`
  566. : t('pages.clients.toasts.importedMixed', { ok: created, failed: skipped.length }));
  567. }
  568. return true;
  569. },
  570. });
  571. }
  572. function onBulkUngroup() {
  573. const emails = [...selectedRowKeys];
  574. if (emails.length === 0) return;
  575. modal.confirm({
  576. title: t('pages.clients.ungroupConfirmTitle', { count: emails.length }),
  577. content: t('pages.clients.ungroupConfirmContent'),
  578. okText: t('confirm'),
  579. okType: 'danger',
  580. cancelText: t('cancel'),
  581. onOk: async () => {
  582. const msg = await bulkRemoveFromGroup(emails);
  583. if (msg?.success) {
  584. setSelectedRowKeys([]);
  585. const affected = (msg.obj as { affected?: number } | undefined)?.affected ?? emails.length;
  586. messageApi.success(t('pages.clients.ungroupSuccessToast', { count: affected }));
  587. }
  588. },
  589. });
  590. }
  591. function onBulkSetEnable(enable: boolean) {
  592. const emails = [...selectedRowKeys];
  593. if (emails.length === 0) return;
  594. modal.confirm({
  595. title: t(enable ? 'pages.clients.bulkEnableConfirmTitle' : 'pages.clients.bulkDisableConfirmTitle', { count: emails.length }),
  596. content: t(enable ? 'pages.clients.bulkEnableConfirmContent' : 'pages.clients.bulkDisableConfirmContent'),
  597. okText: t('confirm'),
  598. okType: enable ? 'primary' : 'danger',
  599. cancelText: t('cancel'),
  600. onOk: async () => {
  601. const msg = enable ? await bulkEnable(emails) : await bulkDisable(emails);
  602. setSelectedRowKeys([]);
  603. const changed = msg?.obj?.changed ?? 0;
  604. const skipped = msg?.obj?.skipped ?? [];
  605. const failed = skipped.length;
  606. const firstError = skipped[0]?.reason ?? msg?.msg ?? '';
  607. const okKey = enable ? 'pages.clients.toasts.bulkEnabled' : 'pages.clients.toasts.bulkDisabled';
  608. const mixedKey = enable ? 'pages.clients.toasts.bulkEnabledMixed' : 'pages.clients.toasts.bulkDisabledMixed';
  609. if (failed === 0 && msg?.success) {
  610. messageApi.success(t(okKey, { count: changed }));
  611. } else {
  612. messageApi.warning(firstError
  613. ? `${t(mixedKey, { ok: changed, failed })} — ${firstError}`
  614. : t(mixedKey, { ok: changed, failed }));
  615. }
  616. },
  617. });
  618. }
  619. function onBulkDelete() {
  620. const emails = [...selectedRowKeys];
  621. if (emails.length === 0) return;
  622. modal.confirm({
  623. title: t('pages.clients.bulkDeleteConfirmTitle', { count: emails.length }),
  624. content: t('pages.clients.bulkDeleteConfirmContent'),
  625. okText: t('delete'),
  626. okType: 'danger',
  627. cancelText: t('cancel'),
  628. onOk: async () => {
  629. const msg = await bulkDelete(emails);
  630. setSelectedRowKeys([]);
  631. const ok = msg?.obj?.deleted ?? 0;
  632. const skipped = msg?.obj?.skipped ?? [];
  633. const failed = skipped.length;
  634. const firstError = skipped[0]?.reason ?? msg?.msg ?? '';
  635. if (failed === 0 && msg?.success) {
  636. messageApi.success(t('pages.clients.toasts.bulkDeleted', { count: ok }));
  637. } else {
  638. messageApi.warning(firstError
  639. ? `${t('pages.clients.toasts.bulkDeletedMixed', { ok, failed })} — ${firstError}`
  640. : t('pages.clients.toasts.bulkDeletedMixed', { ok, failed }));
  641. }
  642. },
  643. });
  644. }
  645. const onSave = useCallback(async (
  646. payload: Record<string, unknown> | { client: Record<string, unknown>; inboundIds: number[] },
  647. meta:
  648. | { isEdit: false; email: string; externalLinks: ExternalLinkInput[] }
  649. | { isEdit: true; email: string; attach: number[]; detach: number[]; externalLinks: ExternalLinkInput[] },
  650. ) => {
  651. if (!meta.isEdit) {
  652. const createMsg = await create(payload);
  653. if (!createMsg?.success) return createMsg;
  654. if (meta.email && meta.externalLinks.length > 0) {
  655. const r = await setExternalLinks(meta.email, meta.externalLinks);
  656. if (!r?.success) return r;
  657. }
  658. return createMsg;
  659. }
  660. const updateMsg = await update(meta.email, payload);
  661. if (!updateMsg?.success) return updateMsg;
  662. const rawEmail = (payload as { email?: unknown }).email;
  663. const emailKey = typeof rawEmail === 'string' && rawEmail.trim() ? rawEmail.trim() : meta.email;
  664. if (Array.isArray(meta.attach) && meta.attach.length > 0) {
  665. const r = await attach(emailKey, meta.attach);
  666. if (!r?.success) return r;
  667. }
  668. if (Array.isArray(meta.detach) && meta.detach.length > 0) {
  669. const r = await detach(emailKey, meta.detach);
  670. if (!r?.success) return r;
  671. }
  672. // Always replace the client's external links (an empty set clears them).
  673. const r = await setExternalLinks(emailKey, meta.externalLinks);
  674. if (!r?.success) return r;
  675. return updateMsg;
  676. }, [create, update, attach, detach, setExternalLinks]);
  677. const pageClass = useMemo(() => {
  678. const classes = ['clients-page'];
  679. if (isDark) classes.push('is-dark');
  680. if (isUltra) classes.push('is-ultra');
  681. return classes.join(' ');
  682. }, [isDark, isUltra]);
  683. const onTableChange: NonNullable<TableProps<ClientRecord>['onChange']> = (pag) => {
  684. if (pag?.current) setCurrentPage(pag.current);
  685. if (pag?.pageSize) setTablePageSize(pag.pageSize);
  686. };
  687. const columns = useMemo<ColumnsType<ClientRecord>>(() => [
  688. {
  689. title: t('pages.clients.actions'),
  690. key: 'actions',
  691. width: 200,
  692. render: (_v, record) => (
  693. <Space size={4}>
  694. <Tooltip title={t('pages.clients.qrCode')}>
  695. <Button size="small" type="text" style={{ fontSize: 16 }} icon={<QrcodeOutlined />} aria-label={t('pages.clients.qrCode')} onClick={() => onShowQr(record)} />
  696. </Tooltip>
  697. <Tooltip title={t('pages.clients.clientInfo')}>
  698. <Button size="small" type="text" style={{ fontSize: 16 }} icon={<InfoCircleOutlined />} aria-label={t('pages.clients.clientInfo')} onClick={() => onShowInfo(record)} />
  699. </Tooltip>
  700. <Tooltip title={t('pages.inbounds.resetTraffic')}>
  701. <Button size="small" type="text" style={{ fontSize: 16 }} icon={<RetweetOutlined />} aria-label={t('pages.inbounds.resetTraffic')} onClick={() => onResetTraffic(record)} />
  702. </Tooltip>
  703. <Tooltip title={t('edit')}>
  704. <Button size="small" type="text" style={{ fontSize: 16 }} icon={<EditOutlined />} aria-label={t('edit')} onClick={() => onEdit(record)} />
  705. </Tooltip>
  706. <Tooltip title={t('delete')}>
  707. <Button size="small" type="text" danger style={{ fontSize: 16 }} icon={<DeleteOutlined />} aria-label={t('delete')} onClick={() => onDelete(record)} />
  708. </Tooltip>
  709. </Space>
  710. ),
  711. },
  712. {
  713. title: t('pages.clients.enabled'),
  714. key: 'enable',
  715. width: 80,
  716. render: (_v, record) => (
  717. <Switch
  718. checked={!!record.enable}
  719. size="small"
  720. loading={togglingEmail === record.email}
  721. onChange={(next) => onToggleEnable(record, next)}
  722. />
  723. ),
  724. },
  725. {
  726. title: t('pages.clients.online'),
  727. key: 'online',
  728. width: 90,
  729. render: (_v, record) => {
  730. const bucket = clientBucket(record);
  731. const lastOnline = record.traffic?.lastOnline ?? 0;
  732. const lastOnlineTitle = `${t('lastOnline')}: ${lastOnline > 0 ? IntlUtil.formatDate(lastOnline, datepicker) : '-'}`;
  733. if (bucket === 'depleted') return (
  734. <Tooltip title={lastOnlineTitle}>
  735. <Tag color="red">{t('depleted')}</Tag>
  736. </Tooltip>
  737. );
  738. if (record.enable && isOnline(record.email)) return (
  739. <Tag color="green" className="dot-tag"><span className="online-dot" />{t('pages.clients.online')}</Tag>
  740. );
  741. if (!record.enable) return <Tag>{t('disabled')}</Tag>;
  742. if (bucket === 'expiring') return <Tag color="orange">{t('depletingSoon')}</Tag>;
  743. return (
  744. <Tooltip title={lastOnlineTitle}>
  745. <Tag>{t('pages.clients.offline')}</Tag>
  746. </Tooltip>
  747. );
  748. },
  749. },
  750. {
  751. title: t('pages.clients.client'),
  752. key: 'email',
  753. width: 220,
  754. render: (_v, record) => (
  755. <div className="email-cell">
  756. <span className="email">{record.email}</span>
  757. {record.subId && <span className="sub" title={record.subId}>{record.subId}</span>}
  758. {record.comment && <span className="sub" title={record.comment}>{record.comment}</span>}
  759. </div>
  760. ),
  761. },
  762. {
  763. title: t('pages.clients.group'),
  764. key: 'group',
  765. width: 130,
  766. hidden: allGroups.length === 0,
  767. render: (_v, record) => {
  768. if (!record.group) return <span style={{ color: 'rgba(0,0,0,0.45)' }}>—</span>;
  769. const isActive = filters.groups.includes(record.group);
  770. return (
  771. <Tag
  772. color="geekblue"
  773. style={{ margin: 0, cursor: 'pointer', opacity: isActive ? 0.6 : 1 }}
  774. onClick={(e) => {
  775. e.stopPropagation();
  776. if (!isActive) {
  777. setFilters({ ...filters, groups: [...filters.groups, record.group!] });
  778. }
  779. }}
  780. >
  781. {record.group}
  782. </Tag>
  783. );
  784. },
  785. },
  786. {
  787. title: t('pages.clients.attachedInbounds'),
  788. key: 'inboundIds',
  789. width: 170,
  790. render: (_v, record) => {
  791. const ids = record.inboundIds || [];
  792. if (ids.length === 0) return <span style={{ color: 'rgba(0,0,0,0.45)' }}>—</span>;
  793. const visible = ids.slice(0, INBOUND_CHIP_LIMIT);
  794. const overflow = ids.slice(INBOUND_CHIP_LIMIT);
  795. const chip = (id: number, compact: boolean) => {
  796. const ib = inboundsById[id];
  797. const proto = (ib?.protocol || '').toLowerCase();
  798. const color = INBOUND_PROTOCOL_COLORS[proto] ?? 'default';
  799. const compactLabel = formatInboundLabel(ib?.tag, ib?.remark);
  800. return (
  801. <Tooltip key={id} title={inboundLabel(id)}>
  802. <Tag color={color} style={{ margin: 2 }}>
  803. {compact ? compactLabel : inboundLabel(id)}
  804. </Tag>
  805. </Tooltip>
  806. );
  807. };
  808. return (
  809. <>
  810. {visible.map((id) => chip(id, true))}
  811. {overflow.length > 0 && (
  812. <Popover
  813. trigger="click"
  814. placement="bottomRight"
  815. content={
  816. <div style={{ display: 'flex', flexDirection: 'column', gap: 4, maxWidth: 280, maxHeight: 280, overflowY: 'auto' }}>
  817. {overflow.map((id) => chip(id, false))}
  818. </div>
  819. }
  820. >
  821. <Tag color="default" style={{ margin: 2, cursor: 'pointer' }}>
  822. +{overflow.length}
  823. </Tag>
  824. </Popover>
  825. )}
  826. </>
  827. );
  828. },
  829. },
  830. {
  831. title: t('pages.clients.traffic'),
  832. key: 'traffic',
  833. width: 300,
  834. render: (_v, record) => (
  835. <ClientTrafficCell
  836. up={record.traffic?.up}
  837. down={record.traffic?.down}
  838. total={record.totalGB}
  839. enabled={record.enable}
  840. trafficDiff={trafficDiff}
  841. />
  842. ),
  843. },
  844. {
  845. title: t('pages.clients.speed'),
  846. key: 'speed',
  847. width: 110,
  848. align: 'center',
  849. render: (_v, record) => {
  850. const speed = clientSpeed[record.email];
  851. if (!isActiveSpeed(speed)) return <Tag color="default">—</Tag>;
  852. return <ClientSpeedTag speed={speed} />;
  853. },
  854. },
  855. {
  856. title: t('pages.clients.remaining'),
  857. key: 'remaining',
  858. width: 130,
  859. render: (_v, record) => <Tag color={remainingColor(record)}>{remainingLabel(record)}</Tag>,
  860. },
  861. {
  862. title: t('pages.clients.duration'),
  863. key: 'expiryTime',
  864. width: 130,
  865. render: (_v, record) => (
  866. <Tooltip title={expiryLabel(record)}>
  867. <Tag color={expiryColor(record)}>{record.expiryTime ? expiryRelative(record) : '∞'}</Tag>
  868. </Tooltip>
  869. ),
  870. },
  871. // eslint-disable-next-line react-hooks/exhaustive-deps
  872. ], [t, togglingEmail, clientBucket, isOnline, inboundsById, filters, allGroups, datepicker, trafficDiff, clientSpeed]);
  873. const tablePagination = {
  874. current: currentPage,
  875. pageSize: tablePageSize,
  876. total: filtered,
  877. showSizeChanger: filtered > 10,
  878. pageSizeOptions: ['10', '25', '50', '100', '200'],
  879. hideOnSinglePage: filtered <= tablePageSize,
  880. showTotal: (n: number) => `${n}`,
  881. };
  882. const rowSelection = {
  883. selectedRowKeys,
  884. onChange: (keys: React.Key[]) => setSelectedRowKeys(keys as string[]),
  885. };
  886. function toggleSelect(email: string, checked: boolean) {
  887. setSelectedRowKeys((prev) => {
  888. const next = new Set(prev);
  889. if (checked) next.add(email); else next.delete(email);
  890. return Array.from(next);
  891. });
  892. }
  893. function selectAll(checked: boolean) {
  894. setSelectedRowKeys(checked ? filteredClients.map((c) => c.email) : []);
  895. }
  896. const allSelected = filteredClients.length > 0 && selectedRowKeys.length === filteredClients.length;
  897. const someSelected = selectedRowKeys.length > 0 && selectedRowKeys.length < filteredClients.length;
  898. function clearOneFilter<K extends keyof ClientFilters>(key: K) {
  899. if (key === 'expiryFrom' || key === 'expiryTo') {
  900. setFilters({ ...filters, expiryFrom: undefined, expiryTo: undefined });
  901. return;
  902. }
  903. if (key === 'usageFromGB' || key === 'usageToGB') {
  904. setFilters({ ...filters, usageFromGB: undefined, usageToGB: undefined });
  905. return;
  906. }
  907. setFilters({ ...filters, [key]: emptyFilters()[key] });
  908. }
  909. return (
  910. <ConfigProvider theme={antdThemeConfig}>
  911. {messageContextHolder}
  912. {modalContextHolder}
  913. <Layout className={pageClass}>
  914. <AppSidebar />
  915. <Layout className="content-shell">
  916. <Layout.Content id="content-layout" className="content-area">
  917. <Spin spinning={!fetched} delay={200} description={t('loading')} size="large">
  918. {!fetched ? (
  919. <div className="loading-spacer" />
  920. ) : fetchError ? (
  921. <Result
  922. status="error"
  923. title={t('somethingWentWrong')}
  924. subTitle={fetchError}
  925. extra={<Button type="primary" loading={loading} onClick={refresh}>{t('refresh')}</Button>}
  926. />
  927. ) : (
  928. <Row gutter={[isMobile ? 8 : 16, isMobile ? 8 : 12]}>
  929. <Col span={24}>
  930. <Card size="small" hoverable className="summary-card">
  931. <Row gutter={[16, 12]}>
  932. <Col xs={12} sm={8} md={4}>
  933. <Statistic title={t('clients')} value={String(summary.total)} prefix={<TeamOutlined />} />
  934. </Col>
  935. <Col xs={12} sm={8} md={4}>
  936. <Popover
  937. title={t('online')}
  938. open={summary.online.length ? undefined : false}
  939. content={<div className="client-email-list">{summary.online.map((e) => <div key={e}>{e}</div>)}</div>}
  940. >
  941. <Statistic title={t('online')} value={String(summary.online.length)} prefix={<span className="dot dot-blue" />} />
  942. </Popover>
  943. </Col>
  944. <Col xs={12} sm={8} md={4}>
  945. <Popover
  946. title={t('depleted')}
  947. open={summary.depleted.length ? undefined : false}
  948. content={<div className="client-email-list">{summary.depleted.map((e) => <div key={e}>{e}</div>)}</div>}
  949. >
  950. <Statistic title={t('depleted')} value={String(summary.depleted.length)} prefix={<span className="dot dot-red" />} />
  951. </Popover>
  952. </Col>
  953. <Col xs={12} sm={8} md={4}>
  954. <Popover
  955. title={t('depletingSoon')}
  956. open={summary.expiring.length ? undefined : false}
  957. content={<div className="client-email-list">{summary.expiring.map((e) => <div key={e}>{e}</div>)}</div>}
  958. >
  959. <Statistic title={t('depletingSoon')} value={String(summary.expiring.length)} prefix={<span className="dot dot-orange" />} />
  960. </Popover>
  961. </Col>
  962. <Col xs={12} sm={8} md={4}>
  963. <Popover
  964. title={t('disabled')}
  965. open={summary.deactive.length ? undefined : false}
  966. content={<div className="client-email-list">{summary.deactive.map((e) => <div key={e}>{e}</div>)}</div>}
  967. >
  968. <Statistic title={t('disabled')} value={String(summary.deactive.length)} prefix={<span className="dot dot-gray" />} />
  969. </Popover>
  970. </Col>
  971. <Col xs={12} sm={8} md={4}>
  972. <Statistic title={t('subscription.active')} value={String(summary.active)} prefix={<span className="dot dot-green" />} />
  973. </Col>
  974. </Row>
  975. </Card>
  976. </Col>
  977. <Col span={24}>
  978. <Card
  979. size="small"
  980. hoverable
  981. title={
  982. <div className="card-toolbar">
  983. {selectedRowKeys.length === 0 ? (
  984. <Button type="primary" icon={<PlusOutlined />} onClick={onAdd} aria-label={t('pages.clients.addClients')}>
  985. {!isMobile && t('pages.clients.addClients')}
  986. </Button>
  987. ) : (
  988. <Tag
  989. color="blue"
  990. closable
  991. onClose={() => setSelectedRowKeys([])}
  992. style={{ marginInlineEnd: 0, padding: '4px 8px', fontSize: 13 }}
  993. >
  994. {t('pages.clients.selectedCount', { count: selectedRowKeys.length })}
  995. </Tag>
  996. )}
  997. <Dropdown
  998. trigger={['click']}
  999. placement="bottomRight"
  1000. menu={{
  1001. items: selectedRowKeys.length > 0
  1002. ? [
  1003. {
  1004. key: 'attach',
  1005. icon: <UsergroupAddOutlined />,
  1006. label: t('pages.clients.attach'),
  1007. onClick: () => setBulkAttachOpen(true),
  1008. },
  1009. {
  1010. key: 'detach',
  1011. icon: <UsergroupDeleteOutlined />,
  1012. label: t('pages.clients.detach'),
  1013. danger: true,
  1014. onClick: () => setBulkDetachOpen(true),
  1015. },
  1016. {
  1017. key: 'addToGroup',
  1018. icon: <TagsOutlined />,
  1019. label: t('pages.clients.addToGroup'),
  1020. onClick: () => setBulkGroupOpen(true),
  1021. },
  1022. {
  1023. key: 'ungroup',
  1024. icon: <UngroupIcon />,
  1025. label: t('pages.clients.ungroup'),
  1026. danger: true,
  1027. onClick: onBulkUngroup,
  1028. },
  1029. { type: 'divider' as const },
  1030. {
  1031. key: 'enable',
  1032. icon: <CheckCircleOutlined />,
  1033. label: t('pages.clients.enable'),
  1034. onClick: () => onBulkSetEnable(true),
  1035. },
  1036. {
  1037. key: 'disable',
  1038. icon: <StopOutlined />,
  1039. label: t('pages.clients.disable'),
  1040. danger: true,
  1041. onClick: () => onBulkSetEnable(false),
  1042. },
  1043. {
  1044. key: 'adjust',
  1045. icon: <ClockCircleOutlined />,
  1046. label: t('pages.clients.adjust'),
  1047. onClick: () => setBulkAdjustOpen(true),
  1048. },
  1049. {
  1050. key: 'subLinks',
  1051. icon: <LinkOutlined />,
  1052. label: t('pages.clients.subLinks'),
  1053. onClick: () => setSubLinksOpen(true),
  1054. },
  1055. ]
  1056. : [
  1057. {
  1058. key: 'bulk',
  1059. icon: <UsergroupAddOutlined />,
  1060. label: t('pages.clients.bulk'),
  1061. onClick: () => setBulkAddOpen(true),
  1062. },
  1063. {
  1064. key: 'export',
  1065. icon: <DownloadOutlined />,
  1066. label: t('pages.clients.exportClients'),
  1067. onClick: onExportClients,
  1068. },
  1069. {
  1070. key: 'import',
  1071. icon: <UploadOutlined />,
  1072. label: t('pages.clients.importClients'),
  1073. onClick: onImportClients,
  1074. },
  1075. {
  1076. key: 'resetAll',
  1077. icon: <RetweetOutlined />,
  1078. label: t('pages.clients.resetAllTraffics'),
  1079. onClick: onResetAllTraffics,
  1080. },
  1081. { type: 'divider' as const },
  1082. {
  1083. key: 'delDepleted',
  1084. icon: <RestOutlined />,
  1085. label: t('pages.clients.delDepleted'),
  1086. danger: true,
  1087. onClick: onDelDepleted,
  1088. },
  1089. {
  1090. key: 'delOrphans',
  1091. icon: <DisconnectOutlined />,
  1092. label: t('pages.clients.delOrphans'),
  1093. danger: true,
  1094. onClick: onDeleteOrphans,
  1095. },
  1096. ],
  1097. }}
  1098. >
  1099. <Button icon={<MoreOutlined />} aria-label={t('more')}>
  1100. {!isMobile && t('more')}
  1101. </Button>
  1102. </Dropdown>
  1103. {selectedRowKeys.length > 0 && (
  1104. <Button
  1105. danger
  1106. icon={<DeleteOutlined />}
  1107. onClick={onBulkDelete}
  1108. style={{ marginInlineStart: 'auto' }}
  1109. aria-label={t('delete')}
  1110. >
  1111. {!isMobile && t('delete')}
  1112. </Button>
  1113. )}
  1114. </div>
  1115. }
  1116. >
  1117. <div className={isMobile ? 'filter-bar mobile' : 'filter-bar'}>
  1118. <Input
  1119. value={searchKey}
  1120. onChange={(e) => setSearchKey(e.target.value)}
  1121. placeholder={t('pages.clients.searchPlaceholder')}
  1122. allowClear
  1123. prefix={<SearchOutlined />}
  1124. size={isMobile ? 'small' : 'middle'}
  1125. style={{ maxWidth: 320 }}
  1126. aria-label={t('search')}
  1127. />
  1128. <Badge count={activeCount} size="small" offset={[-4, 4]}>
  1129. <Button
  1130. icon={<FilterOutlined />}
  1131. size={isMobile ? 'small' : 'middle'}
  1132. onClick={() => setFilterDrawerOpen(true)}
  1133. type={activeCount > 0 ? 'primary' : 'default'}
  1134. aria-label={t('filter')}
  1135. >
  1136. {!isMobile && t('filter')}
  1137. </Button>
  1138. </Badge>
  1139. <Select
  1140. value={sortValueFor(sortColumn, sortOrder)}
  1141. aria-label={t('sort')}
  1142. size={isMobile ? 'small' : 'middle'}
  1143. suffix={<SortAscendingOutlined />}
  1144. style={{ minWidth: isMobile ? 130 : 200 }}
  1145. onChange={(value) => {
  1146. const opt = SORT_OPTIONS.find((o) => o.value === value);
  1147. setSortColumn(opt?.column ?? null);
  1148. setSortOrder(opt?.order ?? null);
  1149. }}
  1150. options={SORT_OPTIONS.map((o) => ({ value: o.value, label: t(o.labelKey) }))}
  1151. />
  1152. {activeCount > 0 && (
  1153. <Button
  1154. size={isMobile ? 'small' : 'middle'}
  1155. onClick={() => setFilters(emptyFilters())}
  1156. >
  1157. {t('pages.clients.clearAllFilters')}
  1158. </Button>
  1159. )}
  1160. {(activeCount > 0 || debouncedSearch.trim().length > 0) && (
  1161. <span className="filter-count">
  1162. {t('pages.clients.showingCount', { shown: filtered, total })}
  1163. </span>
  1164. )}
  1165. </div>
  1166. {activeCount > 0 && (
  1167. <div className="filter-chips">
  1168. {filters.buckets.map((b) => (
  1169. <Tag
  1170. key={`b-${b}`}
  1171. closable
  1172. onClose={() => setFilters({ ...filters, buckets: filters.buckets.filter((x) => x !== b) })}
  1173. >
  1174. {bucketChipLabel(b, t)}
  1175. </Tag>
  1176. ))}
  1177. {filters.protocols.map((p) => (
  1178. <Tag
  1179. key={`p-${p}`}
  1180. closable
  1181. color="blue"
  1182. onClose={() => setFilters({ ...filters, protocols: filters.protocols.filter((x) => x !== p) })}
  1183. >
  1184. {p}
  1185. </Tag>
  1186. ))}
  1187. {filters.inboundIds.map((id) => (
  1188. <Tag
  1189. key={`i-${id}`}
  1190. closable
  1191. color="cyan"
  1192. onClose={() => setFilters({ ...filters, inboundIds: filters.inboundIds.filter((x) => x !== id) })}
  1193. >
  1194. {inboundLabel(id)}
  1195. </Tag>
  1196. ))}
  1197. {filters.groups.map((g) => (
  1198. <Tag
  1199. key={`g-${g}`}
  1200. closable
  1201. color="geekblue"
  1202. onClose={() => setFilters({ ...filters, groups: filters.groups.filter((x) => x !== g) })}
  1203. >
  1204. {t('pages.clients.group')}: {g}
  1205. </Tag>
  1206. ))}
  1207. {(filters.expiryFrom || filters.expiryTo) && (
  1208. <Tag closable color="purple" onClose={() => clearOneFilter('expiryFrom')}>
  1209. {t('pages.clients.expiryTime')}: {filters.expiryFrom ? IntlUtil.formatDate(filters.expiryFrom, datepicker) : '…'}
  1210. {' → '}
  1211. {filters.expiryTo ? IntlUtil.formatDate(filters.expiryTo, datepicker) : '…'}
  1212. </Tag>
  1213. )}
  1214. {(filters.usageFromGB || filters.usageToGB) && (
  1215. <Tag closable color="orange" onClose={() => clearOneFilter('usageFromGB')}>
  1216. {t('pages.clients.traffic')}: {filters.usageFromGB ?? 0}{filters.usageToGB ? `–${filters.usageToGB}` : '+'} GB
  1217. </Tag>
  1218. )}
  1219. {filters.autoRenew && (
  1220. <Tag closable color="gold" onClose={() => clearOneFilter('autoRenew')}>
  1221. {t('pages.clients.renew')}: {filters.autoRenew === 'on' ? t('enabled') : t('disabled')}
  1222. </Tag>
  1223. )}
  1224. {filters.hasTgId && (
  1225. <Tag closable onClose={() => clearOneFilter('hasTgId')}>
  1226. {t('pages.clients.telegramId')}: {filters.hasTgId === 'yes' ? t('pages.clients.has') : t('pages.clients.hasNot')}
  1227. </Tag>
  1228. )}
  1229. {filters.hasComment && (
  1230. <Tag closable onClose={() => clearOneFilter('hasComment')}>
  1231. {t('pages.clients.comment')}: {filters.hasComment === 'yes' ? t('pages.clients.has') : t('pages.clients.hasNot')}
  1232. </Tag>
  1233. )}
  1234. </div>
  1235. )}
  1236. {!isMobile ? (
  1237. <Table<ClientRecord>
  1238. columns={columns}
  1239. dataSource={sortedClients}
  1240. loading={transitioning}
  1241. rowKey="email"
  1242. rowSelection={rowSelection}
  1243. pagination={tablePagination}
  1244. size="small"
  1245. scroll={{ x: 1200 }}
  1246. onChange={onTableChange}
  1247. locale={{
  1248. emptyText: (
  1249. <div className="clients-empty">
  1250. <TeamOutlined style={{ fontSize: 32, marginBottom: 8 }} />
  1251. <div>{t('noData')}</div>
  1252. </div>
  1253. ),
  1254. }}
  1255. />
  1256. ) : (
  1257. <Spin spinning={transitioning}>
  1258. <div className="client-cards">
  1259. {filteredClients.length > 0 && (
  1260. <div className="card-bulk-bar">
  1261. <Checkbox
  1262. checked={allSelected}
  1263. indeterminate={someSelected}
  1264. onChange={(e) => selectAll(e.target.checked)}
  1265. >
  1266. {t('pages.clients.selectAll')}
  1267. </Checkbox>
  1268. {selectedRowKeys.length > 0 && (
  1269. <span className="bulk-count">{selectedRowKeys.length}</span>
  1270. )}
  1271. </div>
  1272. )}
  1273. {filteredClients.length === 0 && (
  1274. <div className="card-empty">
  1275. <TeamOutlined style={{ fontSize: 28, opacity: 0.5 }} />
  1276. <div>{t('noData')}</div>
  1277. </div>
  1278. )}
  1279. {filteredClients.length > 0 && (
  1280. <div className="card-pagination">
  1281. <Pagination
  1282. current={currentPage}
  1283. pageSize={tablePageSize}
  1284. total={filtered}
  1285. showSizeChanger={filtered > 10}
  1286. pageSizeOptions={['10', '25', '50', '100', '200']}
  1287. hideOnSinglePage={filtered <= tablePageSize}
  1288. size="small"
  1289. showTotal={(n) => `${n}`}
  1290. onChange={(p, s) => {
  1291. setCurrentPage(p);
  1292. if (s && s !== tablePageSize) setTablePageSize(s);
  1293. }}
  1294. />
  1295. </div>
  1296. )}
  1297. {filteredClients.map((row) => {
  1298. const bucket = clientBucket(row);
  1299. return (
  1300. <div key={row.email} className={`client-card${selectedRowKeys.includes(row.email) ? ' is-selected' : ''}`}>
  1301. <div className="card-head">
  1302. <Checkbox
  1303. checked={selectedRowKeys.includes(row.email)}
  1304. onChange={(e) => toggleSelect(row.email, e.target.checked)}
  1305. />
  1306. {row.enable && bucket !== 'depleted' && isOnline(row.email)
  1307. ? <span className="online-dot" style={{ marginInlineEnd: 0 }} />
  1308. : <Badge status={bucketBadgeStatus(bucket)} />}
  1309. <span className="tag-name">{row.email}</span>
  1310. {bucket === 'depleted' && <Tag color="red" className="status-tag">{t('depleted')}</Tag>}
  1311. {bucket === 'expiring' && <Tag color="orange" className="status-tag">{t('depletingSoon')}</Tag>}
  1312. <div className="card-actions">
  1313. <Tooltip title={t('pages.clients.clientInfo')}>
  1314. <InfoCircleOutlined
  1315. className="row-action-trigger"
  1316. role="button"
  1317. tabIndex={0}
  1318. aria-label={t('pages.clients.clientInfo')}
  1319. onClick={() => onShowInfo(row)}
  1320. onKeyDown={activateOnKey(() => onShowInfo(row))}
  1321. />
  1322. </Tooltip>
  1323. <Switch
  1324. checked={!!row.enable}
  1325. size="small"
  1326. loading={togglingEmail === row.email}
  1327. onChange={(next) => onToggleEnable(row, next)}
  1328. />
  1329. <Dropdown
  1330. trigger={['click']}
  1331. placement="bottomRight"
  1332. menu={{
  1333. items: [
  1334. {
  1335. key: 'qr',
  1336. label: <><QrcodeOutlined /> {t('pages.clients.qrCode')}</>,
  1337. onClick: () => onShowQr(row),
  1338. },
  1339. {
  1340. key: 'reset',
  1341. label: <><RetweetOutlined /> {t('pages.inbounds.resetTraffic')}</>,
  1342. onClick: () => onResetTraffic(row),
  1343. },
  1344. {
  1345. key: 'edit',
  1346. label: <><EditOutlined /> {t('edit')}</>,
  1347. onClick: () => onEdit(row),
  1348. },
  1349. {
  1350. key: 'delete',
  1351. danger: true,
  1352. label: <><DeleteOutlined /> {t('delete')}</>,
  1353. onClick: () => onDelete(row),
  1354. },
  1355. ],
  1356. }}
  1357. >
  1358. <Button type="text" size="small" className="row-action-trigger" icon={<MoreOutlined />} aria-label={t('more')} />
  1359. </Dropdown>
  1360. </div>
  1361. </div>
  1362. <ClientTrafficCell
  1363. compact
  1364. up={row.traffic?.up}
  1365. down={row.traffic?.down}
  1366. total={row.totalGB}
  1367. enabled={row.enable}
  1368. trafficDiff={trafficDiff}
  1369. />
  1370. {(() => {
  1371. const speed = clientSpeed[row.email];
  1372. if (!isActiveSpeed(speed)) return null;
  1373. return (
  1374. <div className="client-card-speed">
  1375. <ClientSpeedTag speed={speed} />
  1376. </div>
  1377. );
  1378. })()}
  1379. </div>
  1380. );
  1381. })}
  1382. </div>
  1383. </Spin>
  1384. )}
  1385. </Card>
  1386. </Col>
  1387. </Row>
  1388. )}
  1389. </Spin>
  1390. </Layout.Content>
  1391. </Layout>
  1392. <LazyMount when={formOpen}>
  1393. <ClientFormModal
  1394. open={formOpen}
  1395. mode={formMode}
  1396. client={editingClient}
  1397. attachedIds={editingAttachedIds}
  1398. attachedExternalLinks={editingExternalLinks}
  1399. inbounds={inbounds}
  1400. tgBotEnable={tgBotEnable}
  1401. groups={allGroups}
  1402. save={onSave}
  1403. resetTraffic={resetTraffic}
  1404. onOpenChange={setFormOpen}
  1405. />
  1406. </LazyMount>
  1407. <LazyMount when={infoOpen}>
  1408. <ClientInfoModal
  1409. open={infoOpen}
  1410. client={infoClient}
  1411. inboundsById={inboundsById}
  1412. isOnline={infoClient ? isOnline(infoClient.email) : false}
  1413. subSettings={subSettings}
  1414. onOpenChange={setInfoOpen}
  1415. />
  1416. </LazyMount>
  1417. <LazyMount when={qrOpen}>
  1418. <ClientQrModal
  1419. open={qrOpen}
  1420. client={qrClient}
  1421. inboundsById={inboundsById}
  1422. subSettings={subSettings}
  1423. onOpenChange={setQrOpen}
  1424. />
  1425. </LazyMount>
  1426. <LazyMount when={bulkAddOpen}>
  1427. <ClientBulkAddModal
  1428. open={bulkAddOpen}
  1429. inbounds={inbounds}
  1430. groups={allGroups}
  1431. onOpenChange={setBulkAddOpen}
  1432. onSaved={() => setBulkAddOpen(false)}
  1433. />
  1434. </LazyMount>
  1435. <LazyMount when={bulkAdjustOpen}>
  1436. <ClientBulkAdjustModal
  1437. open={bulkAdjustOpen}
  1438. count={selectedRowKeys.length}
  1439. onOpenChange={setBulkAdjustOpen}
  1440. onSubmit={async (addDays, addBytes, flow) => {
  1441. const msg = await bulkAdjust([...selectedRowKeys], addDays, addBytes, flow);
  1442. if (msg?.success) {
  1443. setSelectedRowKeys([]);
  1444. return msg.obj ?? { adjusted: 0 };
  1445. }
  1446. return null;
  1447. }}
  1448. />
  1449. </LazyMount>
  1450. <LazyMount when={subLinksOpen}>
  1451. <SubLinksModal
  1452. open={subLinksOpen}
  1453. emails={selectedRowKeys}
  1454. clients={clients}
  1455. subSettings={subSettings}
  1456. onOpenChange={setSubLinksOpen}
  1457. />
  1458. </LazyMount>
  1459. <LazyMount when={bulkGroupOpen}>
  1460. <BulkAddToGroupModal
  1461. open={bulkGroupOpen}
  1462. count={selectedRowKeys.length}
  1463. groups={allGroups}
  1464. onOpenChange={setBulkGroupOpen}
  1465. onSubmit={async (group) => {
  1466. const msg = await bulkAddToGroup([...selectedRowKeys], group);
  1467. if (msg?.success) {
  1468. setSelectedRowKeys([]);
  1469. return (msg.obj as { affected?: number } | undefined) ?? { affected: 0 };
  1470. }
  1471. return null;
  1472. }}
  1473. />
  1474. </LazyMount>
  1475. <LazyMount when={bulkAttachOpen}>
  1476. <BulkAttachInboundsModal
  1477. open={bulkAttachOpen}
  1478. count={selectedRowKeys.length}
  1479. inbounds={inbounds}
  1480. onOpenChange={setBulkAttachOpen}
  1481. onSubmit={async (inboundIds) => {
  1482. const msg = await bulkAttach([...selectedRowKeys], inboundIds);
  1483. if (msg?.success) {
  1484. setSelectedRowKeys([]);
  1485. return msg.obj ?? { attached: [], skipped: [], errors: [] };
  1486. }
  1487. return null;
  1488. }}
  1489. />
  1490. </LazyMount>
  1491. <LazyMount when={bulkDetachOpen}>
  1492. <BulkDetachInboundsModal
  1493. open={bulkDetachOpen}
  1494. count={selectedRowKeys.length}
  1495. inbounds={inbounds}
  1496. onOpenChange={setBulkDetachOpen}
  1497. onSubmit={async (inboundIds) => {
  1498. const msg = await bulkDetach([...selectedRowKeys], inboundIds);
  1499. if (msg?.success) {
  1500. setSelectedRowKeys([]);
  1501. return msg.obj ?? { detached: [], skipped: [], errors: [] };
  1502. }
  1503. return null;
  1504. }}
  1505. />
  1506. </LazyMount>
  1507. <LazyMount when={filterDrawerOpen}>
  1508. <FilterDrawer
  1509. open={filterDrawerOpen}
  1510. onOpenChange={setFilterDrawerOpen}
  1511. filters={filters}
  1512. onChange={setFilters}
  1513. inbounds={inbounds}
  1514. protocols={protocolOptions}
  1515. groups={groupOptions}
  1516. nodes={nodes}
  1517. />
  1518. </LazyMount>
  1519. <LazyMount when={textOpen}>
  1520. <TextModal
  1521. open={textOpen}
  1522. onClose={() => setTextOpen(false)}
  1523. title={textTitle}
  1524. content={textContent}
  1525. fileName={textFileName}
  1526. json
  1527. />
  1528. </LazyMount>
  1529. <LazyMount when={promptOpen}>
  1530. <PromptModal
  1531. open={promptOpen}
  1532. onClose={() => setPromptOpen(false)}
  1533. title={promptTitle}
  1534. okText={promptOkText}
  1535. initialValue={promptInitial}
  1536. loading={promptLoading}
  1537. json
  1538. onConfirm={onPromptConfirm}
  1539. />
  1540. </LazyMount>
  1541. </Layout>
  1542. </ConfigProvider>
  1543. );
  1544. }
  1545. function bucketChipLabel(b: string, t: (k: string) => string): string {
  1546. switch (b) {
  1547. case 'active': return t('subscription.active');
  1548. case 'expiring': return t('depletingSoon');
  1549. case 'depleted': return t('depleted');
  1550. case 'deactive': return t('disabled');
  1551. case 'online': return t('online');
  1552. default: return b;
  1553. }
  1554. }