useUsageLogsData.jsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. /*
  2. Copyright (C) 2025 QuantumNous
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <https://www.gnu.org/licenses/>.
  13. For commercial licensing, please contact support@quantumnous.com
  14. */
  15. import { useState, useEffect } from 'react';
  16. import { useTranslation } from 'react-i18next';
  17. import { Modal } from '@douyinfe/semi-ui';
  18. import {
  19. API,
  20. getTodayStartTimestamp,
  21. isAdmin,
  22. showError,
  23. showSuccess,
  24. timestamp2string,
  25. renderQuota,
  26. renderNumber,
  27. getLogOther,
  28. copy,
  29. renderClaudeLogContent,
  30. renderLogContent,
  31. renderAudioModelPrice,
  32. renderClaudeModelPrice,
  33. renderModelPrice,
  34. } from '../../helpers';
  35. import { ITEMS_PER_PAGE } from '../../constants';
  36. import { useTableCompactMode } from '../common/useTableCompactMode';
  37. export const useLogsData = () => {
  38. const { t } = useTranslation();
  39. // Define column keys for selection
  40. const COLUMN_KEYS = {
  41. TIME: 'time',
  42. CHANNEL: 'channel',
  43. USERNAME: 'username',
  44. TOKEN: 'token',
  45. GROUP: 'group',
  46. TYPE: 'type',
  47. MODEL: 'model',
  48. USE_TIME: 'use_time',
  49. PROMPT: 'prompt',
  50. COMPLETION: 'completion',
  51. COST: 'cost',
  52. RETRY: 'retry',
  53. IP: 'ip',
  54. DETAILS: 'details',
  55. };
  56. // Basic state
  57. const [logs, setLogs] = useState([]);
  58. const [expandData, setExpandData] = useState({});
  59. const [showStat, setShowStat] = useState(false);
  60. const [loading, setLoading] = useState(false);
  61. const [loadingStat, setLoadingStat] = useState(false);
  62. const [activePage, setActivePage] = useState(1);
  63. const [logCount, setLogCount] = useState(0);
  64. const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
  65. const [logType, setLogType] = useState(0);
  66. // User and admin
  67. const isAdminUser = isAdmin();
  68. // Role-specific storage key to prevent different roles from overwriting each other
  69. const STORAGE_KEY = isAdminUser
  70. ? 'logs-table-columns-admin'
  71. : 'logs-table-columns-user';
  72. // Statistics state
  73. const [stat, setStat] = useState({
  74. quota: 0,
  75. token: 0,
  76. });
  77. // Form state
  78. const [formApi, setFormApi] = useState(null);
  79. let now = new Date();
  80. const formInitValues = {
  81. username: '',
  82. token_name: '',
  83. model_name: '',
  84. channel: '',
  85. group: '',
  86. request_id: '',
  87. dateRange: [
  88. timestamp2string(getTodayStartTimestamp()),
  89. timestamp2string(now.getTime() / 1000 + 3600),
  90. ],
  91. logType: '0',
  92. };
  93. // Column visibility state
  94. const [visibleColumns, setVisibleColumns] = useState({});
  95. const [showColumnSelector, setShowColumnSelector] = useState(false);
  96. // Compact mode
  97. const [compactMode, setCompactMode] = useTableCompactMode('logs');
  98. // User info modal state
  99. const [showUserInfo, setShowUserInfoModal] = useState(false);
  100. const [userInfoData, setUserInfoData] = useState(null);
  101. // Channel affinity usage cache stats modal state (admin only)
  102. const [
  103. showChannelAffinityUsageCacheModal,
  104. setShowChannelAffinityUsageCacheModal,
  105. ] = useState(false);
  106. const [channelAffinityUsageCacheTarget, setChannelAffinityUsageCacheTarget] =
  107. useState(null);
  108. // Load saved column preferences from localStorage
  109. useEffect(() => {
  110. const savedColumns = localStorage.getItem(STORAGE_KEY);
  111. if (savedColumns) {
  112. try {
  113. const parsed = JSON.parse(savedColumns);
  114. const defaults = getDefaultColumnVisibility();
  115. const merged = { ...defaults, ...parsed };
  116. // For non-admin users, force-hide admin-only columns (does not touch admin settings)
  117. if (!isAdminUser) {
  118. merged[COLUMN_KEYS.CHANNEL] = false;
  119. merged[COLUMN_KEYS.USERNAME] = false;
  120. merged[COLUMN_KEYS.RETRY] = false;
  121. }
  122. setVisibleColumns(merged);
  123. } catch (e) {
  124. console.error('Failed to parse saved column preferences', e);
  125. initDefaultColumns();
  126. }
  127. } else {
  128. initDefaultColumns();
  129. }
  130. }, []);
  131. // Get default column visibility based on user role
  132. const getDefaultColumnVisibility = () => {
  133. return {
  134. [COLUMN_KEYS.TIME]: true,
  135. [COLUMN_KEYS.CHANNEL]: isAdminUser,
  136. [COLUMN_KEYS.USERNAME]: isAdminUser,
  137. [COLUMN_KEYS.TOKEN]: true,
  138. [COLUMN_KEYS.GROUP]: true,
  139. [COLUMN_KEYS.TYPE]: true,
  140. [COLUMN_KEYS.MODEL]: true,
  141. [COLUMN_KEYS.USE_TIME]: true,
  142. [COLUMN_KEYS.PROMPT]: true,
  143. [COLUMN_KEYS.COMPLETION]: true,
  144. [COLUMN_KEYS.COST]: true,
  145. [COLUMN_KEYS.RETRY]: isAdminUser,
  146. [COLUMN_KEYS.IP]: true,
  147. [COLUMN_KEYS.DETAILS]: true,
  148. };
  149. };
  150. // Initialize default column visibility
  151. const initDefaultColumns = () => {
  152. const defaults = getDefaultColumnVisibility();
  153. setVisibleColumns(defaults);
  154. localStorage.setItem(STORAGE_KEY, JSON.stringify(defaults));
  155. };
  156. // Handle column visibility change
  157. const handleColumnVisibilityChange = (columnKey, checked) => {
  158. const updatedColumns = { ...visibleColumns, [columnKey]: checked };
  159. setVisibleColumns(updatedColumns);
  160. };
  161. // Handle "Select All" checkbox
  162. const handleSelectAll = (checked) => {
  163. const allKeys = Object.keys(COLUMN_KEYS).map((key) => COLUMN_KEYS[key]);
  164. const updatedColumns = {};
  165. allKeys.forEach((key) => {
  166. if (
  167. (key === COLUMN_KEYS.CHANNEL ||
  168. key === COLUMN_KEYS.USERNAME ||
  169. key === COLUMN_KEYS.RETRY) &&
  170. !isAdminUser
  171. ) {
  172. updatedColumns[key] = false;
  173. } else {
  174. updatedColumns[key] = checked;
  175. }
  176. });
  177. setVisibleColumns(updatedColumns);
  178. };
  179. // Persist column settings to the role-specific STORAGE_KEY
  180. useEffect(() => {
  181. if (Object.keys(visibleColumns).length > 0) {
  182. localStorage.setItem(STORAGE_KEY, JSON.stringify(visibleColumns));
  183. }
  184. }, [visibleColumns]);
  185. // 获取表单值的辅助函数,确保所有值都是字符串
  186. const getFormValues = () => {
  187. const formValues = formApi ? formApi.getValues() : {};
  188. let start_timestamp = timestamp2string(getTodayStartTimestamp());
  189. let end_timestamp = timestamp2string(now.getTime() / 1000 + 3600);
  190. if (
  191. formValues.dateRange &&
  192. Array.isArray(formValues.dateRange) &&
  193. formValues.dateRange.length === 2
  194. ) {
  195. start_timestamp = formValues.dateRange[0];
  196. end_timestamp = formValues.dateRange[1];
  197. }
  198. return {
  199. username: formValues.username || '',
  200. token_name: formValues.token_name || '',
  201. model_name: formValues.model_name || '',
  202. start_timestamp,
  203. end_timestamp,
  204. channel: formValues.channel || '',
  205. group: formValues.group || '',
  206. request_id: formValues.request_id || '',
  207. logType: formValues.logType ? parseInt(formValues.logType) : 0,
  208. };
  209. };
  210. // Statistics functions
  211. const getLogSelfStat = async () => {
  212. const {
  213. token_name,
  214. model_name,
  215. start_timestamp,
  216. end_timestamp,
  217. group,
  218. logType: formLogType,
  219. } = getFormValues();
  220. const currentLogType = formLogType !== undefined ? formLogType : logType;
  221. let localStartTimestamp = Date.parse(start_timestamp) / 1000;
  222. let localEndTimestamp = Date.parse(end_timestamp) / 1000;
  223. let url = `/api/log/self/stat?type=${currentLogType}&token_name=${token_name}&model_name=${model_name}&start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}&group=${group}`;
  224. url = encodeURI(url);
  225. let res = await API.get(url);
  226. const { success, message, data } = res.data;
  227. if (success) {
  228. setStat(data);
  229. } else {
  230. showError(message);
  231. }
  232. };
  233. const getLogStat = async () => {
  234. const {
  235. username,
  236. token_name,
  237. model_name,
  238. start_timestamp,
  239. end_timestamp,
  240. channel,
  241. group,
  242. logType: formLogType,
  243. } = getFormValues();
  244. const currentLogType = formLogType !== undefined ? formLogType : logType;
  245. let localStartTimestamp = Date.parse(start_timestamp) / 1000;
  246. let localEndTimestamp = Date.parse(end_timestamp) / 1000;
  247. let url = `/api/log/stat?type=${currentLogType}&username=${username}&token_name=${token_name}&model_name=${model_name}&start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}&channel=${channel}&group=${group}`;
  248. url = encodeURI(url);
  249. let res = await API.get(url);
  250. const { success, message, data } = res.data;
  251. if (success) {
  252. setStat(data);
  253. } else {
  254. showError(message);
  255. }
  256. };
  257. const handleEyeClick = async () => {
  258. if (loadingStat) {
  259. return;
  260. }
  261. setLoadingStat(true);
  262. if (isAdminUser) {
  263. await getLogStat();
  264. } else {
  265. await getLogSelfStat();
  266. }
  267. setShowStat(true);
  268. setLoadingStat(false);
  269. };
  270. // User info function
  271. const showUserInfoFunc = async (userId) => {
  272. if (!isAdminUser) {
  273. return;
  274. }
  275. const res = await API.get(`/api/user/${userId}`);
  276. const { success, message, data } = res.data;
  277. if (success) {
  278. setUserInfoData(data);
  279. setShowUserInfoModal(true);
  280. } else {
  281. showError(message);
  282. }
  283. };
  284. const openChannelAffinityUsageCacheModal = (affinity) => {
  285. const a = affinity || {};
  286. setChannelAffinityUsageCacheTarget({
  287. rule_name: a.rule_name || a.reason || '',
  288. using_group: a.using_group || '',
  289. key_hint: a.key_hint || '',
  290. key_fp: a.key_fp || '',
  291. });
  292. setShowChannelAffinityUsageCacheModal(true);
  293. };
  294. // Format logs data
  295. const setLogsFormat = (logs) => {
  296. const requestConversionDisplayValue = (conversionChain) => {
  297. const chain = Array.isArray(conversionChain)
  298. ? conversionChain.filter(Boolean)
  299. : [];
  300. if (chain.length <= 1) {
  301. return t('原生格式');
  302. }
  303. return `${chain.join(' -> ')}`;
  304. };
  305. let expandDatesLocal = {};
  306. for (let i = 0; i < logs.length; i++) {
  307. logs[i].timestamp2string = timestamp2string(logs[i].created_at);
  308. logs[i].key = logs[i].id;
  309. let other = getLogOther(logs[i].other);
  310. let expandDataLocal = [];
  311. if (isAdminUser && (logs[i].type === 0 || logs[i].type === 2)) {
  312. expandDataLocal.push({
  313. key: t('渠道信息'),
  314. value: `${logs[i].channel} - ${logs[i].channel_name || '[未知]'}`,
  315. });
  316. }
  317. if (logs[i].request_id) {
  318. expandDataLocal.push({
  319. key: t('Request ID'),
  320. value: logs[i].request_id,
  321. });
  322. }
  323. if (other?.ws || other?.audio) {
  324. expandDataLocal.push({
  325. key: t('语音输入'),
  326. value: other.audio_input,
  327. });
  328. expandDataLocal.push({
  329. key: t('语音输出'),
  330. value: other.audio_output,
  331. });
  332. expandDataLocal.push({
  333. key: t('文字输入'),
  334. value: other.text_input,
  335. });
  336. expandDataLocal.push({
  337. key: t('文字输出'),
  338. value: other.text_output,
  339. });
  340. }
  341. if (other?.cache_tokens > 0) {
  342. expandDataLocal.push({
  343. key: t('缓存 Tokens'),
  344. value: other.cache_tokens,
  345. });
  346. }
  347. if (other?.cache_creation_tokens > 0) {
  348. expandDataLocal.push({
  349. key: t('缓存创建 Tokens'),
  350. value: other.cache_creation_tokens,
  351. });
  352. }
  353. if (logs[i].type === 2) {
  354. expandDataLocal.push({
  355. key: t('日志详情'),
  356. value: other?.claude
  357. ? renderClaudeLogContent(
  358. other?.model_ratio,
  359. other.completion_ratio,
  360. other.model_price,
  361. other.group_ratio,
  362. other?.user_group_ratio,
  363. other.cache_ratio || 1.0,
  364. other.cache_creation_ratio || 1.0,
  365. other.cache_creation_tokens_5m || 0,
  366. other.cache_creation_ratio_5m ||
  367. other.cache_creation_ratio ||
  368. 1.0,
  369. other.cache_creation_tokens_1h || 0,
  370. other.cache_creation_ratio_1h ||
  371. other.cache_creation_ratio ||
  372. 1.0,
  373. )
  374. : renderLogContent(
  375. other?.model_ratio,
  376. other.completion_ratio,
  377. other.model_price,
  378. other.group_ratio,
  379. other?.user_group_ratio,
  380. other.cache_ratio || 1.0,
  381. false,
  382. 1.0,
  383. other.web_search || false,
  384. other.web_search_call_count || 0,
  385. other.file_search || false,
  386. other.file_search_call_count || 0,
  387. ),
  388. });
  389. if (logs[i]?.content) {
  390. expandDataLocal.push({
  391. key: t('其他详情'),
  392. value: logs[i].content,
  393. });
  394. }
  395. if (isAdminUser && other?.reject_reason) {
  396. expandDataLocal.push({
  397. key: t('拦截原因'),
  398. value: other.reject_reason,
  399. });
  400. }
  401. }
  402. if (logs[i].type === 2) {
  403. let modelMapped =
  404. other?.is_model_mapped &&
  405. other?.upstream_model_name &&
  406. other?.upstream_model_name !== '';
  407. if (modelMapped) {
  408. expandDataLocal.push({
  409. key: t('请求并计费模型'),
  410. value: logs[i].model_name,
  411. });
  412. expandDataLocal.push({
  413. key: t('实际模型'),
  414. value: other.upstream_model_name,
  415. });
  416. }
  417. const isViolationFeeLog =
  418. other?.violation_fee === true ||
  419. Boolean(other?.violation_fee_code) ||
  420. Boolean(other?.violation_fee_marker);
  421. let content = '';
  422. if (!isViolationFeeLog) {
  423. if (other?.ws || other?.audio) {
  424. content = renderAudioModelPrice(
  425. other?.text_input,
  426. other?.text_output,
  427. other?.model_ratio,
  428. other?.model_price,
  429. other?.completion_ratio,
  430. other?.audio_input,
  431. other?.audio_output,
  432. other?.audio_ratio,
  433. other?.audio_completion_ratio,
  434. other?.group_ratio,
  435. other?.user_group_ratio,
  436. other?.cache_tokens || 0,
  437. other?.cache_ratio || 1.0,
  438. );
  439. } else if (other?.claude) {
  440. content = renderClaudeModelPrice(
  441. logs[i].prompt_tokens,
  442. logs[i].completion_tokens,
  443. other.model_ratio,
  444. other.model_price,
  445. other.completion_ratio,
  446. other.group_ratio,
  447. other?.user_group_ratio,
  448. other.cache_tokens || 0,
  449. other.cache_ratio || 1.0,
  450. other.cache_creation_tokens || 0,
  451. other.cache_creation_ratio || 1.0,
  452. other.cache_creation_tokens_5m || 0,
  453. other.cache_creation_ratio_5m ||
  454. other.cache_creation_ratio ||
  455. 1.0,
  456. other.cache_creation_tokens_1h || 0,
  457. other.cache_creation_ratio_1h ||
  458. other.cache_creation_ratio ||
  459. 1.0,
  460. );
  461. } else {
  462. content = renderModelPrice(
  463. logs[i].prompt_tokens,
  464. logs[i].completion_tokens,
  465. other?.model_ratio,
  466. other?.model_price,
  467. other?.completion_ratio,
  468. other?.group_ratio,
  469. other?.user_group_ratio,
  470. other?.cache_tokens || 0,
  471. other?.cache_ratio || 1.0,
  472. other?.image || false,
  473. other?.image_ratio || 0,
  474. other?.image_output || 0,
  475. other?.web_search || false,
  476. other?.web_search_call_count || 0,
  477. other?.web_search_price || 0,
  478. other?.file_search || false,
  479. other?.file_search_call_count || 0,
  480. other?.file_search_price || 0,
  481. other?.audio_input_seperate_price || false,
  482. other?.audio_input_token_count || 0,
  483. other?.audio_input_price || 0,
  484. other?.image_generation_call || false,
  485. other?.image_generation_call_price || 0,
  486. );
  487. }
  488. expandDataLocal.push({
  489. key: t('计费过程'),
  490. value: content,
  491. });
  492. }
  493. if (other?.reasoning_effort) {
  494. expandDataLocal.push({
  495. key: t('Reasoning Effort'),
  496. value: other.reasoning_effort,
  497. });
  498. }
  499. }
  500. if (other?.request_path) {
  501. expandDataLocal.push({
  502. key: t('请求路径'),
  503. value: other.request_path,
  504. });
  505. }
  506. if (other?.billing_source === 'subscription') {
  507. const planId = other?.subscription_plan_id;
  508. const planTitle = other?.subscription_plan_title || '';
  509. const subscriptionId = other?.subscription_id;
  510. const unit = t('额度');
  511. const pre = other?.subscription_pre_consumed ?? 0;
  512. const postDelta = other?.subscription_post_delta ?? 0;
  513. const finalConsumed = other?.subscription_consumed ?? pre + postDelta;
  514. const remain = other?.subscription_remain;
  515. const total = other?.subscription_total;
  516. // Use multiple Description items to avoid an overlong single line.
  517. if (planId) {
  518. expandDataLocal.push({
  519. key: t('订阅套餐'),
  520. value: `#${planId} ${planTitle}`.trim(),
  521. });
  522. }
  523. if (subscriptionId) {
  524. expandDataLocal.push({
  525. key: t('订阅实例'),
  526. value: `#${subscriptionId}`,
  527. });
  528. }
  529. const settlementLines = [
  530. `${t('预扣')}:${pre} ${unit}`,
  531. `${t('结算差额')}:${postDelta > 0 ? '+' : ''}${postDelta} ${unit}`,
  532. `${t('最终抵扣')}:${finalConsumed} ${unit}`,
  533. ]
  534. .filter(Boolean)
  535. .join('\n');
  536. expandDataLocal.push({
  537. key: t('订阅结算'),
  538. value: (
  539. <div style={{ whiteSpace: 'pre-line' }}>{settlementLines}</div>
  540. ),
  541. });
  542. if (remain !== undefined && total !== undefined) {
  543. expandDataLocal.push({
  544. key: t('订阅剩余'),
  545. value: `${remain}/${total} ${unit}`,
  546. });
  547. }
  548. expandDataLocal.push({
  549. key: t('订阅说明'),
  550. value: t(
  551. 'token 会按倍率换算成“额度/次数”,请求结束后再做差额结算(补扣/返还)。',
  552. ),
  553. });
  554. }
  555. if (isAdminUser) {
  556. expandDataLocal.push({
  557. key: t('请求转换'),
  558. value: requestConversionDisplayValue(other?.request_conversion),
  559. });
  560. }
  561. if (isAdminUser) {
  562. let localCountMode = '';
  563. if (other?.admin_info?.local_count_tokens) {
  564. localCountMode = t('本地计费');
  565. } else {
  566. localCountMode = t('上游返回');
  567. }
  568. expandDataLocal.push({
  569. key: t('计费模式'),
  570. value: localCountMode,
  571. });
  572. }
  573. expandDatesLocal[logs[i].key] = expandDataLocal;
  574. }
  575. setExpandData(expandDatesLocal);
  576. setLogs(logs);
  577. };
  578. // Load logs function
  579. const loadLogs = async (startIdx, pageSize, customLogType = null) => {
  580. setLoading(true);
  581. let url = '';
  582. const {
  583. username,
  584. token_name,
  585. model_name,
  586. start_timestamp,
  587. end_timestamp,
  588. channel,
  589. group,
  590. request_id,
  591. logType: formLogType,
  592. } = getFormValues();
  593. const currentLogType =
  594. customLogType !== null
  595. ? customLogType
  596. : formLogType !== undefined
  597. ? formLogType
  598. : logType;
  599. let localStartTimestamp = Date.parse(start_timestamp) / 1000;
  600. let localEndTimestamp = Date.parse(end_timestamp) / 1000;
  601. if (isAdminUser) {
  602. url = `/api/log/?p=${startIdx}&page_size=${pageSize}&type=${currentLogType}&username=${username}&token_name=${token_name}&model_name=${model_name}&start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}&channel=${channel}&group=${group}&request_id=${request_id}`;
  603. } else {
  604. url = `/api/log/self/?p=${startIdx}&page_size=${pageSize}&type=${currentLogType}&token_name=${token_name}&model_name=${model_name}&start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}&group=${group}&request_id=${request_id}`;
  605. }
  606. url = encodeURI(url);
  607. const res = await API.get(url);
  608. const { success, message, data } = res.data;
  609. if (success) {
  610. const newPageData = data.items;
  611. setActivePage(data.page);
  612. setPageSize(data.page_size);
  613. setLogCount(data.total);
  614. setLogsFormat(newPageData);
  615. } else {
  616. showError(message);
  617. }
  618. setLoading(false);
  619. };
  620. // Page handlers
  621. const handlePageChange = (page) => {
  622. setActivePage(page);
  623. loadLogs(page, pageSize).then((r) => {});
  624. };
  625. const handlePageSizeChange = async (size) => {
  626. localStorage.setItem('page-size', size + '');
  627. setPageSize(size);
  628. setActivePage(1);
  629. loadLogs(activePage, size)
  630. .then()
  631. .catch((reason) => {
  632. showError(reason);
  633. });
  634. };
  635. // Refresh function
  636. const refresh = async () => {
  637. setActivePage(1);
  638. handleEyeClick();
  639. await loadLogs(1, pageSize);
  640. };
  641. // Copy text function
  642. const copyText = async (e, text) => {
  643. e.stopPropagation();
  644. if (await copy(text)) {
  645. showSuccess('已复制:' + text);
  646. } else {
  647. Modal.error({ title: t('无法复制到剪贴板,请手动复制'), content: text });
  648. }
  649. };
  650. // Initialize data
  651. useEffect(() => {
  652. const localPageSize =
  653. parseInt(localStorage.getItem('page-size')) || ITEMS_PER_PAGE;
  654. setPageSize(localPageSize);
  655. loadLogs(activePage, localPageSize)
  656. .then()
  657. .catch((reason) => {
  658. showError(reason);
  659. });
  660. }, []);
  661. // Initialize statistics when formApi is available
  662. useEffect(() => {
  663. if (formApi) {
  664. handleEyeClick();
  665. }
  666. }, [formApi]);
  667. // Check if any record has expandable content
  668. const hasExpandableRows = () => {
  669. return logs.some(
  670. (log) => expandData[log.key] && expandData[log.key].length > 0,
  671. );
  672. };
  673. return {
  674. // Basic state
  675. logs,
  676. expandData,
  677. showStat,
  678. loading,
  679. loadingStat,
  680. activePage,
  681. logCount,
  682. pageSize,
  683. logType,
  684. stat,
  685. isAdminUser,
  686. // Form state
  687. formApi,
  688. setFormApi,
  689. formInitValues,
  690. getFormValues,
  691. // Column visibility
  692. visibleColumns,
  693. showColumnSelector,
  694. setShowColumnSelector,
  695. handleColumnVisibilityChange,
  696. handleSelectAll,
  697. initDefaultColumns,
  698. COLUMN_KEYS,
  699. // Compact mode
  700. compactMode,
  701. setCompactMode,
  702. // User info modal
  703. showUserInfo,
  704. setShowUserInfoModal,
  705. userInfoData,
  706. showUserInfoFunc,
  707. // Channel affinity usage cache stats modal
  708. showChannelAffinityUsageCacheModal,
  709. setShowChannelAffinityUsageCacheModal,
  710. channelAffinityUsageCacheTarget,
  711. openChannelAffinityUsageCacheModal,
  712. // Functions
  713. loadLogs,
  714. handlePageChange,
  715. handlePageSizeChange,
  716. refresh,
  717. copyText,
  718. handleEyeClick,
  719. setLogsFormat,
  720. hasExpandableRows,
  721. setLogType,
  722. // Translation
  723. t,
  724. };
  725. };