useUsageLogsData.jsx 27 KB

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