useUsageLogsData.jsx 24 KB

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