useUsageLogsData.jsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. /*
  2. Copyright (C) 2025 QuantumNous
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <https://www.gnu.org/licenses/>.
  13. For commercial licensing, please contact support@quantumnous.com
  14. */
  15. import { useState, useEffect } from 'react';
  16. import { useTranslation } from 'react-i18next';
  17. import { Modal } from '@douyinfe/semi-ui';
  18. import {
  19. API,
  20. getTodayStartTimestamp,
  21. isAdmin,
  22. showError,
  23. showSuccess,
  24. timestamp2string,
  25. renderQuota,
  26. renderNumber,
  27. getLogOther,
  28. copy,
  29. renderClaudeLogContent,
  30. renderLogContent,
  31. renderAudioModelPrice,
  32. renderClaudeModelPrice,
  33. renderModelPrice,
  34. } from '../../helpers';
  35. import { ITEMS_PER_PAGE } from '../../constants';
  36. import { useTableCompactMode } from '../common/useTableCompactMode';
  37. export const useLogsData = () => {
  38. const { t } = useTranslation();
  39. // Define column keys for selection
  40. const COLUMN_KEYS = {
  41. TIME: 'time',
  42. CHANNEL: 'channel',
  43. USERNAME: 'username',
  44. TOKEN: 'token',
  45. GROUP: 'group',
  46. TYPE: 'type',
  47. MODEL: 'model',
  48. USE_TIME: 'use_time',
  49. PROMPT: 'prompt',
  50. COMPLETION: 'completion',
  51. COST: 'cost',
  52. RETRY: 'retry',
  53. IP: 'ip',
  54. DETAILS: 'details',
  55. };
  56. // Basic state
  57. const [logs, setLogs] = useState([]);
  58. const [expandData, setExpandData] = useState({});
  59. const [showStat, setShowStat] = useState(false);
  60. const [loading, setLoading] = useState(false);
  61. const [loadingStat, setLoadingStat] = useState(false);
  62. const [activePage, setActivePage] = useState(1);
  63. const [logCount, setLogCount] = useState(0);
  64. const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
  65. const [logType, setLogType] = useState(0);
  66. // User and admin
  67. const isAdminUser = isAdmin();
  68. // Role-specific storage key to prevent different roles from overwriting each other
  69. const STORAGE_KEY = isAdminUser
  70. ? 'logs-table-columns-admin'
  71. : 'logs-table-columns-user';
  72. // Statistics state
  73. const [stat, setStat] = useState({
  74. quota: 0,
  75. token: 0,
  76. });
  77. // Form state
  78. const [formApi, setFormApi] = useState(null);
  79. let now = new Date();
  80. const formInitValues = {
  81. username: '',
  82. token_name: '',
  83. model_name: '',
  84. channel: '',
  85. group: '',
  86. dateRange: [
  87. timestamp2string(getTodayStartTimestamp()),
  88. timestamp2string(now.getTime() / 1000 + 3600),
  89. ],
  90. logType: '0',
  91. };
  92. // Column visibility state
  93. const [visibleColumns, setVisibleColumns] = useState({});
  94. const [showColumnSelector, setShowColumnSelector] = useState(false);
  95. // Compact mode
  96. const [compactMode, setCompactMode] = useTableCompactMode('logs');
  97. // User info modal state
  98. const [showUserInfo, setShowUserInfoModal] = useState(false);
  99. const [userInfoData, setUserInfoData] = useState(null);
  100. // Load saved column preferences from localStorage
  101. useEffect(() => {
  102. const savedColumns = localStorage.getItem(STORAGE_KEY);
  103. if (savedColumns) {
  104. try {
  105. const parsed = JSON.parse(savedColumns);
  106. const defaults = getDefaultColumnVisibility();
  107. const merged = { ...defaults, ...parsed };
  108. // For non-admin users, force-hide admin-only columns (does not touch admin settings)
  109. if (!isAdminUser) {
  110. merged[COLUMN_KEYS.CHANNEL] = false;
  111. merged[COLUMN_KEYS.USERNAME] = false;
  112. merged[COLUMN_KEYS.RETRY] = false;
  113. }
  114. setVisibleColumns(merged);
  115. } catch (e) {
  116. console.error('Failed to parse saved column preferences', e);
  117. initDefaultColumns();
  118. }
  119. } else {
  120. initDefaultColumns();
  121. }
  122. }, []);
  123. // Get default column visibility based on user role
  124. const getDefaultColumnVisibility = () => {
  125. return {
  126. [COLUMN_KEYS.TIME]: true,
  127. [COLUMN_KEYS.CHANNEL]: isAdminUser,
  128. [COLUMN_KEYS.USERNAME]: isAdminUser,
  129. [COLUMN_KEYS.TOKEN]: true,
  130. [COLUMN_KEYS.GROUP]: true,
  131. [COLUMN_KEYS.TYPE]: true,
  132. [COLUMN_KEYS.MODEL]: true,
  133. [COLUMN_KEYS.USE_TIME]: true,
  134. [COLUMN_KEYS.PROMPT]: true,
  135. [COLUMN_KEYS.COMPLETION]: true,
  136. [COLUMN_KEYS.COST]: true,
  137. [COLUMN_KEYS.RETRY]: isAdminUser,
  138. [COLUMN_KEYS.IP]: true,
  139. [COLUMN_KEYS.DETAILS]: true,
  140. };
  141. };
  142. // Initialize default column visibility
  143. const initDefaultColumns = () => {
  144. const defaults = getDefaultColumnVisibility();
  145. setVisibleColumns(defaults);
  146. localStorage.setItem(STORAGE_KEY, JSON.stringify(defaults));
  147. };
  148. // Handle column visibility change
  149. const handleColumnVisibilityChange = (columnKey, checked) => {
  150. const updatedColumns = { ...visibleColumns, [columnKey]: checked };
  151. setVisibleColumns(updatedColumns);
  152. };
  153. // Handle "Select All" checkbox
  154. const handleSelectAll = (checked) => {
  155. const allKeys = Object.keys(COLUMN_KEYS).map((key) => COLUMN_KEYS[key]);
  156. const updatedColumns = {};
  157. allKeys.forEach((key) => {
  158. if (
  159. (key === COLUMN_KEYS.CHANNEL ||
  160. key === COLUMN_KEYS.USERNAME ||
  161. key === COLUMN_KEYS.RETRY) &&
  162. !isAdminUser
  163. ) {
  164. updatedColumns[key] = false;
  165. } else {
  166. updatedColumns[key] = checked;
  167. }
  168. });
  169. setVisibleColumns(updatedColumns);
  170. };
  171. // Persist column settings to the role-specific STORAGE_KEY
  172. useEffect(() => {
  173. if (Object.keys(visibleColumns).length > 0) {
  174. localStorage.setItem(STORAGE_KEY, JSON.stringify(visibleColumns));
  175. }
  176. }, [visibleColumns]);
  177. // 获取表单值的辅助函数,确保所有值都是字符串
  178. const getFormValues = () => {
  179. const formValues = formApi ? formApi.getValues() : {};
  180. let start_timestamp = timestamp2string(getTodayStartTimestamp());
  181. let end_timestamp = timestamp2string(now.getTime() / 1000 + 3600);
  182. if (
  183. formValues.dateRange &&
  184. Array.isArray(formValues.dateRange) &&
  185. formValues.dateRange.length === 2
  186. ) {
  187. start_timestamp = formValues.dateRange[0];
  188. end_timestamp = formValues.dateRange[1];
  189. }
  190. return {
  191. username: formValues.username || '',
  192. token_name: formValues.token_name || '',
  193. model_name: formValues.model_name || '',
  194. start_timestamp,
  195. end_timestamp,
  196. channel: formValues.channel || '',
  197. group: formValues.group || '',
  198. logType: formValues.logType ? parseInt(formValues.logType) : 0,
  199. };
  200. };
  201. // Statistics functions
  202. const getLogSelfStat = async () => {
  203. const {
  204. token_name,
  205. model_name,
  206. start_timestamp,
  207. end_timestamp,
  208. group,
  209. logType: formLogType,
  210. } = getFormValues();
  211. const currentLogType = formLogType !== undefined ? formLogType : logType;
  212. let localStartTimestamp = Date.parse(start_timestamp) / 1000;
  213. let localEndTimestamp = Date.parse(end_timestamp) / 1000;
  214. let url = `/api/log/self/stat?type=${currentLogType}&token_name=${token_name}&model_name=${model_name}&start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}&group=${group}`;
  215. url = encodeURI(url);
  216. let res = await API.get(url);
  217. const { success, message, data } = res.data;
  218. if (success) {
  219. setStat(data);
  220. } else {
  221. showError(message);
  222. }
  223. };
  224. const getLogStat = async () => {
  225. const {
  226. username,
  227. token_name,
  228. model_name,
  229. start_timestamp,
  230. end_timestamp,
  231. channel,
  232. group,
  233. logType: formLogType,
  234. } = getFormValues();
  235. const currentLogType = formLogType !== undefined ? formLogType : logType;
  236. let localStartTimestamp = Date.parse(start_timestamp) / 1000;
  237. let localEndTimestamp = Date.parse(end_timestamp) / 1000;
  238. let url = `/api/log/stat?type=${currentLogType}&username=${username}&token_name=${token_name}&model_name=${model_name}&start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}&channel=${channel}&group=${group}`;
  239. url = encodeURI(url);
  240. let res = await API.get(url);
  241. const { success, message, data } = res.data;
  242. if (success) {
  243. setStat(data);
  244. } else {
  245. showError(message);
  246. }
  247. };
  248. const handleEyeClick = async () => {
  249. if (loadingStat) {
  250. return;
  251. }
  252. setLoadingStat(true);
  253. if (isAdminUser) {
  254. await getLogStat();
  255. } else {
  256. await getLogSelfStat();
  257. }
  258. setShowStat(true);
  259. setLoadingStat(false);
  260. };
  261. // User info function
  262. const showUserInfoFunc = async (userId) => {
  263. if (!isAdminUser) {
  264. return;
  265. }
  266. const res = await API.get(`/api/user/${userId}`);
  267. const { success, message, data } = res.data;
  268. if (success) {
  269. setUserInfoData(data);
  270. setShowUserInfoModal(true);
  271. } else {
  272. showError(message);
  273. }
  274. };
  275. // Format logs data
  276. const setLogsFormat = (logs) => {
  277. const requestConversionDisplayValue = (conversionChain) => {
  278. const chain = Array.isArray(conversionChain)
  279. ? conversionChain.filter(Boolean)
  280. : [];
  281. if (chain.length <= 1) {
  282. return t('原生格式');
  283. }
  284. return `${chain.join(' -> ')}`;
  285. };
  286. let expandDatesLocal = {};
  287. for (let i = 0; i < logs.length; i++) {
  288. logs[i].timestamp2string = timestamp2string(logs[i].created_at);
  289. logs[i].key = logs[i].id;
  290. let other = getLogOther(logs[i].other);
  291. let expandDataLocal = [];
  292. if (isAdminUser && (logs[i].type === 0 || logs[i].type === 2)) {
  293. expandDataLocal.push({
  294. key: t('渠道信息'),
  295. value: `${logs[i].channel} - ${logs[i].channel_name || '[未知]'}`,
  296. });
  297. }
  298. if (other?.ws || other?.audio) {
  299. expandDataLocal.push({
  300. key: t('语音输入'),
  301. value: other.audio_input,
  302. });
  303. expandDataLocal.push({
  304. key: t('语音输出'),
  305. value: other.audio_output,
  306. });
  307. expandDataLocal.push({
  308. key: t('文字输入'),
  309. value: other.text_input,
  310. });
  311. expandDataLocal.push({
  312. key: t('文字输出'),
  313. value: other.text_output,
  314. });
  315. }
  316. if (other?.cache_tokens > 0) {
  317. expandDataLocal.push({
  318. key: t('缓存 Tokens'),
  319. value: other.cache_tokens,
  320. });
  321. }
  322. if (other?.cache_creation_tokens > 0) {
  323. expandDataLocal.push({
  324. key: t('缓存创建 Tokens'),
  325. value: other.cache_creation_tokens,
  326. });
  327. }
  328. if (logs[i].type === 2) {
  329. expandDataLocal.push({
  330. key: t('日志详情'),
  331. value: other?.claude
  332. ? renderClaudeLogContent(
  333. other?.model_ratio,
  334. other.completion_ratio,
  335. other.model_price,
  336. other.group_ratio,
  337. other?.user_group_ratio,
  338. other.cache_ratio || 1.0,
  339. other.cache_creation_ratio || 1.0,
  340. other.cache_creation_tokens_5m || 0,
  341. other.cache_creation_ratio_5m || other.cache_creation_ratio || 1.0,
  342. other.cache_creation_tokens_1h || 0,
  343. other.cache_creation_ratio_1h || other.cache_creation_ratio || 1.0,
  344. )
  345. : renderLogContent(
  346. other?.model_ratio,
  347. other.completion_ratio,
  348. other.model_price,
  349. other.group_ratio,
  350. other?.user_group_ratio,
  351. other.cache_ratio || 1.0,
  352. false,
  353. 1.0,
  354. other.web_search || false,
  355. other.web_search_call_count || 0,
  356. other.file_search || false,
  357. other.file_search_call_count || 0,
  358. ),
  359. });
  360. if (logs[i]?.content) {
  361. expandDataLocal.push({
  362. key: t('其他详情'),
  363. value: logs[i].content,
  364. });
  365. }
  366. if (isAdminUser && other?.reject_reason) {
  367. expandDataLocal.push({
  368. key: t('拦截原因'),
  369. value: other.reject_reason,
  370. });
  371. }
  372. }
  373. if (logs[i].type === 2) {
  374. let modelMapped =
  375. other?.is_model_mapped &&
  376. other?.upstream_model_name &&
  377. other?.upstream_model_name !== '';
  378. if (modelMapped) {
  379. expandDataLocal.push({
  380. key: t('请求并计费模型'),
  381. value: logs[i].model_name,
  382. });
  383. expandDataLocal.push({
  384. key: t('实际模型'),
  385. value: other.upstream_model_name,
  386. });
  387. }
  388. const isViolationFeeLog =
  389. other?.violation_fee === true ||
  390. Boolean(other?.violation_fee_code) ||
  391. Boolean(other?.violation_fee_marker);
  392. let content = '';
  393. if (!isViolationFeeLog) {
  394. if (other?.ws || other?.audio) {
  395. content = renderAudioModelPrice(
  396. other?.text_input,
  397. other?.text_output,
  398. other?.model_ratio,
  399. other?.model_price,
  400. other?.completion_ratio,
  401. other?.audio_input,
  402. other?.audio_output,
  403. other?.audio_ratio,
  404. other?.audio_completion_ratio,
  405. other?.group_ratio,
  406. other?.user_group_ratio,
  407. other?.cache_tokens || 0,
  408. other?.cache_ratio || 1.0,
  409. );
  410. } else if (other?.claude) {
  411. content = renderClaudeModelPrice(
  412. logs[i].prompt_tokens,
  413. logs[i].completion_tokens,
  414. other.model_ratio,
  415. other.model_price,
  416. other.completion_ratio,
  417. other.group_ratio,
  418. other?.user_group_ratio,
  419. other.cache_tokens || 0,
  420. other.cache_ratio || 1.0,
  421. other.cache_creation_tokens || 0,
  422. other.cache_creation_ratio || 1.0,
  423. other.cache_creation_tokens_5m || 0,
  424. other.cache_creation_ratio_5m ||
  425. other.cache_creation_ratio ||
  426. 1.0,
  427. other.cache_creation_tokens_1h || 0,
  428. other.cache_creation_ratio_1h ||
  429. other.cache_creation_ratio ||
  430. 1.0,
  431. );
  432. } else {
  433. content = renderModelPrice(
  434. logs[i].prompt_tokens,
  435. logs[i].completion_tokens,
  436. other?.model_ratio,
  437. other?.model_price,
  438. other?.completion_ratio,
  439. other?.group_ratio,
  440. other?.user_group_ratio,
  441. other?.cache_tokens || 0,
  442. other?.cache_ratio || 1.0,
  443. other?.image || false,
  444. other?.image_ratio || 0,
  445. other?.image_output || 0,
  446. other?.web_search || false,
  447. other?.web_search_call_count || 0,
  448. other?.web_search_price || 0,
  449. other?.file_search || false,
  450. other?.file_search_call_count || 0,
  451. other?.file_search_price || 0,
  452. other?.audio_input_seperate_price || false,
  453. other?.audio_input_token_count || 0,
  454. other?.audio_input_price || 0,
  455. other?.image_generation_call || false,
  456. other?.image_generation_call_price || 0,
  457. );
  458. }
  459. expandDataLocal.push({
  460. key: t('计费过程'),
  461. value: content,
  462. });
  463. }
  464. if (other?.reasoning_effort) {
  465. expandDataLocal.push({
  466. key: t('Reasoning Effort'),
  467. value: other.reasoning_effort,
  468. });
  469. }
  470. }
  471. if (other?.request_path) {
  472. expandDataLocal.push({
  473. key: t('请求路径'),
  474. value: other.request_path,
  475. });
  476. }
  477. if (isAdminUser) {
  478. expandDataLocal.push({
  479. key: t('请求转换'),
  480. value: requestConversionDisplayValue(other?.request_conversion),
  481. });
  482. }
  483. if (isAdminUser) {
  484. let localCountMode = '';
  485. if (other?.admin_info?.local_count_tokens) {
  486. localCountMode = t('本地计费');
  487. } else {
  488. localCountMode = t('上游返回');
  489. }
  490. expandDataLocal.push({
  491. key: t('计费模式'),
  492. value: localCountMode,
  493. });
  494. }
  495. expandDatesLocal[logs[i].key] = expandDataLocal;
  496. }
  497. setExpandData(expandDatesLocal);
  498. setLogs(logs);
  499. };
  500. // Load logs function
  501. const loadLogs = async (startIdx, pageSize, customLogType = null) => {
  502. setLoading(true);
  503. let url = '';
  504. const {
  505. username,
  506. token_name,
  507. model_name,
  508. start_timestamp,
  509. end_timestamp,
  510. channel,
  511. group,
  512. logType: formLogType,
  513. } = getFormValues();
  514. const currentLogType =
  515. customLogType !== null
  516. ? customLogType
  517. : formLogType !== undefined
  518. ? formLogType
  519. : logType;
  520. let localStartTimestamp = Date.parse(start_timestamp) / 1000;
  521. let localEndTimestamp = Date.parse(end_timestamp) / 1000;
  522. if (isAdminUser) {
  523. 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}`;
  524. } else {
  525. 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}`;
  526. }
  527. url = encodeURI(url);
  528. const res = await API.get(url);
  529. const { success, message, data } = res.data;
  530. if (success) {
  531. const newPageData = data.items;
  532. setActivePage(data.page);
  533. setPageSize(data.page_size);
  534. setLogCount(data.total);
  535. setLogsFormat(newPageData);
  536. } else {
  537. showError(message);
  538. }
  539. setLoading(false);
  540. };
  541. // Page handlers
  542. const handlePageChange = (page) => {
  543. setActivePage(page);
  544. loadLogs(page, pageSize).then((r) => {});
  545. };
  546. const handlePageSizeChange = async (size) => {
  547. localStorage.setItem('page-size', size + '');
  548. setPageSize(size);
  549. setActivePage(1);
  550. loadLogs(activePage, size)
  551. .then()
  552. .catch((reason) => {
  553. showError(reason);
  554. });
  555. };
  556. // Refresh function
  557. const refresh = async () => {
  558. setActivePage(1);
  559. handleEyeClick();
  560. await loadLogs(1, pageSize);
  561. };
  562. // Copy text function
  563. const copyText = async (e, text) => {
  564. e.stopPropagation();
  565. if (await copy(text)) {
  566. showSuccess('已复制:' + text);
  567. } else {
  568. Modal.error({ title: t('无法复制到剪贴板,请手动复制'), content: text });
  569. }
  570. };
  571. // Initialize data
  572. useEffect(() => {
  573. const localPageSize =
  574. parseInt(localStorage.getItem('page-size')) || ITEMS_PER_PAGE;
  575. setPageSize(localPageSize);
  576. loadLogs(activePage, localPageSize)
  577. .then()
  578. .catch((reason) => {
  579. showError(reason);
  580. });
  581. }, []);
  582. // Initialize statistics when formApi is available
  583. useEffect(() => {
  584. if (formApi) {
  585. handleEyeClick();
  586. }
  587. }, [formApi]);
  588. // Check if any record has expandable content
  589. const hasExpandableRows = () => {
  590. return logs.some(
  591. (log) => expandData[log.key] && expandData[log.key].length > 0,
  592. );
  593. };
  594. return {
  595. // Basic state
  596. logs,
  597. expandData,
  598. showStat,
  599. loading,
  600. loadingStat,
  601. activePage,
  602. logCount,
  603. pageSize,
  604. logType,
  605. stat,
  606. isAdminUser,
  607. // Form state
  608. formApi,
  609. setFormApi,
  610. formInitValues,
  611. getFormValues,
  612. // Column visibility
  613. visibleColumns,
  614. showColumnSelector,
  615. setShowColumnSelector,
  616. handleColumnVisibilityChange,
  617. handleSelectAll,
  618. initDefaultColumns,
  619. COLUMN_KEYS,
  620. // Compact mode
  621. compactMode,
  622. setCompactMode,
  623. // User info modal
  624. showUserInfo,
  625. setShowUserInfoModal,
  626. userInfoData,
  627. showUserInfoFunc,
  628. // Functions
  629. loadLogs,
  630. handlePageChange,
  631. handlePageSizeChange,
  632. refresh,
  633. copyText,
  634. handleEyeClick,
  635. setLogsFormat,
  636. hasExpandableRows,
  637. setLogType,
  638. // Translation
  639. t,
  640. };
  641. };