useUsageLogsData.jsx 29 KB

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