useUsageLogsData.jsx 26 KB

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