ClientsPage.tsx 56 KB

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