useUsageLogsData.jsx 24 KB

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