useUsageLogsData.jsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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. let expandDatesLocal = {};
  278. for (let i = 0; i < logs.length; i++) {
  279. logs[i].timestamp2string = timestamp2string(logs[i].created_at);
  280. logs[i].key = logs[i].id;
  281. let other = getLogOther(logs[i].other);
  282. let expandDataLocal = [];
  283. if (isAdminUser && (logs[i].type === 0 || logs[i].type === 2)) {
  284. expandDataLocal.push({
  285. key: t('渠道信息'),
  286. value: `${logs[i].channel} - ${logs[i].channel_name || '[未知]'}`,
  287. });
  288. }
  289. if (other?.ws || other?.audio) {
  290. expandDataLocal.push({
  291. key: t('语音输入'),
  292. value: other.audio_input,
  293. });
  294. expandDataLocal.push({
  295. key: t('语音输出'),
  296. value: other.audio_output,
  297. });
  298. expandDataLocal.push({
  299. key: t('文字输入'),
  300. value: other.text_input,
  301. });
  302. expandDataLocal.push({
  303. key: t('文字输出'),
  304. value: other.text_output,
  305. });
  306. }
  307. if (other?.cache_tokens > 0) {
  308. expandDataLocal.push({
  309. key: t('缓存 Tokens'),
  310. value: other.cache_tokens,
  311. });
  312. }
  313. if (other?.cache_creation_tokens > 0) {
  314. expandDataLocal.push({
  315. key: t('缓存创建 Tokens'),
  316. value: other.cache_creation_tokens,
  317. });
  318. }
  319. if (logs[i].type === 2) {
  320. expandDataLocal.push({
  321. key: t('日志详情'),
  322. value: other?.claude
  323. ? renderClaudeLogContent(
  324. other?.model_ratio,
  325. other.completion_ratio,
  326. other.model_price,
  327. other.group_ratio,
  328. other?.user_group_ratio,
  329. other.cache_ratio || 1.0,
  330. other.cache_creation_ratio || 1.0,
  331. )
  332. : renderLogContent(
  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. false,
  340. 1.0,
  341. other.web_search || false,
  342. other.web_search_call_count || 0,
  343. other.file_search || false,
  344. other.file_search_call_count || 0,
  345. ),
  346. });
  347. }
  348. if (logs[i].type === 2) {
  349. let modelMapped =
  350. other?.is_model_mapped &&
  351. other?.upstream_model_name &&
  352. other?.upstream_model_name !== '';
  353. if (modelMapped) {
  354. expandDataLocal.push({
  355. key: t('请求并计费模型'),
  356. value: logs[i].model_name,
  357. });
  358. expandDataLocal.push({
  359. key: t('实际模型'),
  360. value: other.upstream_model_name,
  361. });
  362. }
  363. let content = '';
  364. if (other?.ws || other?.audio) {
  365. content = renderAudioModelPrice(
  366. other?.text_input,
  367. other?.text_output,
  368. other?.model_ratio,
  369. other?.model_price,
  370. other?.completion_ratio,
  371. other?.audio_input,
  372. other?.audio_output,
  373. other?.audio_ratio,
  374. other?.audio_completion_ratio,
  375. other?.group_ratio,
  376. other?.user_group_ratio,
  377. other?.cache_tokens || 0,
  378. other?.cache_ratio || 1.0,
  379. );
  380. } else if (other?.claude) {
  381. content = renderClaudeModelPrice(
  382. logs[i].prompt_tokens,
  383. logs[i].completion_tokens,
  384. other.model_ratio,
  385. other.model_price,
  386. other.completion_ratio,
  387. other.group_ratio,
  388. other?.user_group_ratio,
  389. other.cache_tokens || 0,
  390. other.cache_ratio || 1.0,
  391. other.cache_creation_tokens || 0,
  392. other.cache_creation_ratio || 1.0,
  393. );
  394. } else {
  395. content = renderModelPrice(
  396. logs[i].prompt_tokens,
  397. logs[i].completion_tokens,
  398. other?.model_ratio,
  399. other?.model_price,
  400. other?.completion_ratio,
  401. other?.group_ratio,
  402. other?.user_group_ratio,
  403. other?.cache_tokens || 0,
  404. other?.cache_ratio || 1.0,
  405. other?.image || false,
  406. other?.image_ratio || 0,
  407. other?.image_output || 0,
  408. other?.web_search || false,
  409. other?.web_search_call_count || 0,
  410. other?.web_search_price || 0,
  411. other?.file_search || false,
  412. other?.file_search_call_count || 0,
  413. other?.file_search_price || 0,
  414. other?.audio_input_seperate_price || false,
  415. other?.audio_input_token_count || 0,
  416. other?.audio_input_price || 0,
  417. other?.image_generation_call || false,
  418. other?.image_generation_call_price || 0,
  419. );
  420. }
  421. expandDataLocal.push({
  422. key: t('计费过程'),
  423. value: content,
  424. });
  425. if (other?.reasoning_effort) {
  426. expandDataLocal.push({
  427. key: t('Reasoning Effort'),
  428. value: other.reasoning_effort,
  429. });
  430. }
  431. }
  432. expandDatesLocal[logs[i].key] = expandDataLocal;
  433. }
  434. setExpandData(expandDatesLocal);
  435. setLogs(logs);
  436. };
  437. // Load logs function
  438. const loadLogs = async (startIdx, pageSize, customLogType = null) => {
  439. setLoading(true);
  440. let url = '';
  441. const {
  442. username,
  443. token_name,
  444. model_name,
  445. start_timestamp,
  446. end_timestamp,
  447. channel,
  448. group,
  449. logType: formLogType,
  450. } = getFormValues();
  451. const currentLogType =
  452. customLogType !== null
  453. ? customLogType
  454. : formLogType !== undefined
  455. ? formLogType
  456. : logType;
  457. let localStartTimestamp = Date.parse(start_timestamp) / 1000;
  458. let localEndTimestamp = Date.parse(end_timestamp) / 1000;
  459. if (isAdminUser) {
  460. 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}`;
  461. } else {
  462. 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}`;
  463. }
  464. url = encodeURI(url);
  465. const res = await API.get(url);
  466. const { success, message, data } = res.data;
  467. if (success) {
  468. const newPageData = data.items;
  469. setActivePage(data.page);
  470. setPageSize(data.page_size);
  471. setLogCount(data.total);
  472. setLogsFormat(newPageData);
  473. } else {
  474. showError(message);
  475. }
  476. setLoading(false);
  477. };
  478. // Page handlers
  479. const handlePageChange = (page) => {
  480. setActivePage(page);
  481. loadLogs(page, pageSize).then((r) => {});
  482. };
  483. const handlePageSizeChange = async (size) => {
  484. localStorage.setItem('page-size', size + '');
  485. setPageSize(size);
  486. setActivePage(1);
  487. loadLogs(activePage, size)
  488. .then()
  489. .catch((reason) => {
  490. showError(reason);
  491. });
  492. };
  493. // Refresh function
  494. const refresh = async () => {
  495. setActivePage(1);
  496. handleEyeClick();
  497. await loadLogs(1, pageSize);
  498. };
  499. // Copy text function
  500. const copyText = async (e, text) => {
  501. e.stopPropagation();
  502. if (await copy(text)) {
  503. showSuccess('已复制:' + text);
  504. } else {
  505. Modal.error({ title: t('无法复制到剪贴板,请手动复制'), content: text });
  506. }
  507. };
  508. // Initialize data
  509. useEffect(() => {
  510. const localPageSize =
  511. parseInt(localStorage.getItem('page-size')) || ITEMS_PER_PAGE;
  512. setPageSize(localPageSize);
  513. loadLogs(activePage, localPageSize)
  514. .then()
  515. .catch((reason) => {
  516. showError(reason);
  517. });
  518. }, []);
  519. // Initialize statistics when formApi is available
  520. useEffect(() => {
  521. if (formApi) {
  522. handleEyeClick();
  523. }
  524. }, [formApi]);
  525. // Check if any record has expandable content
  526. const hasExpandableRows = () => {
  527. return logs.some(
  528. (log) => expandData[log.key] && expandData[log.key].length > 0,
  529. );
  530. };
  531. return {
  532. // Basic state
  533. logs,
  534. expandData,
  535. showStat,
  536. loading,
  537. loadingStat,
  538. activePage,
  539. logCount,
  540. pageSize,
  541. logType,
  542. stat,
  543. isAdminUser,
  544. // Form state
  545. formApi,
  546. setFormApi,
  547. formInitValues,
  548. getFormValues,
  549. // Column visibility
  550. visibleColumns,
  551. showColumnSelector,
  552. setShowColumnSelector,
  553. handleColumnVisibilityChange,
  554. handleSelectAll,
  555. initDefaultColumns,
  556. COLUMN_KEYS,
  557. // Compact mode
  558. compactMode,
  559. setCompactMode,
  560. // User info modal
  561. showUserInfo,
  562. setShowUserInfoModal,
  563. userInfoData,
  564. showUserInfoFunc,
  565. // Functions
  566. loadLogs,
  567. handlePageChange,
  568. handlePageSizeChange,
  569. refresh,
  570. copyText,
  571. handleEyeClick,
  572. setLogsFormat,
  573. hasExpandableRows,
  574. setLogType,
  575. // Translation
  576. t,
  577. };
  578. };