LogsTable.js 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462
  1. import React, { useEffect, useState } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import {
  4. API,
  5. copy,
  6. getTodayStartTimestamp,
  7. isAdmin,
  8. showError,
  9. showSuccess,
  10. timestamp2string,
  11. renderAudioModelPrice,
  12. renderClaudeLogContent,
  13. renderClaudeModelPrice,
  14. renderClaudeModelPriceSimple,
  15. renderGroup,
  16. renderLogContent,
  17. renderModelPrice,
  18. renderModelPriceSimple,
  19. renderNumber,
  20. renderQuota,
  21. stringToColor,
  22. getLogOther,
  23. renderModelTag,
  24. } from '../../helpers';
  25. import {
  26. Avatar,
  27. Button,
  28. Descriptions,
  29. Empty,
  30. Modal,
  31. Popover,
  32. Space,
  33. Spin,
  34. Table,
  35. Tag,
  36. Tooltip,
  37. Checkbox,
  38. Card,
  39. Typography,
  40. Divider,
  41. Form,
  42. } from '@douyinfe/semi-ui';
  43. import {
  44. IllustrationNoResult,
  45. IllustrationNoResultDark,
  46. } from '@douyinfe/semi-illustrations';
  47. import { ITEMS_PER_PAGE } from '../../constants';
  48. import Paragraph from '@douyinfe/semi-ui/lib/es/typography/paragraph';
  49. import { IconSetting, IconSearch, IconHelpCircle } from '@douyinfe/semi-icons';
  50. import { Route } from 'lucide-react';
  51. const { Text } = Typography;
  52. const colors = [
  53. 'amber',
  54. 'blue',
  55. 'cyan',
  56. 'green',
  57. 'grey',
  58. 'indigo',
  59. 'light-blue',
  60. 'lime',
  61. 'orange',
  62. 'pink',
  63. 'purple',
  64. 'red',
  65. 'teal',
  66. 'violet',
  67. 'yellow',
  68. ];
  69. const LogsTable = () => {
  70. const { t } = useTranslation();
  71. function renderType(type) {
  72. switch (type) {
  73. case 1:
  74. return (
  75. <Tag color='cyan' size='large' shape='circle'>
  76. {t('充值')}
  77. </Tag>
  78. );
  79. case 2:
  80. return (
  81. <Tag color='lime' size='large' shape='circle'>
  82. {t('消费')}
  83. </Tag>
  84. );
  85. case 3:
  86. return (
  87. <Tag color='orange' size='large' shape='circle'>
  88. {t('管理')}
  89. </Tag>
  90. );
  91. case 4:
  92. return (
  93. <Tag color='purple' size='large' shape='circle'>
  94. {t('系统')}
  95. </Tag>
  96. );
  97. case 5:
  98. return (
  99. <Tag color='red' size='large' shape='circle'>
  100. {t('错误')}
  101. </Tag>
  102. );
  103. default:
  104. return (
  105. <Tag color='grey' size='large' shape='circle'>
  106. {t('未知')}
  107. </Tag>
  108. );
  109. }
  110. }
  111. function renderIsStream(bool) {
  112. if (bool) {
  113. return (
  114. <Tag color='blue' size='large' shape='circle'>
  115. {t('流')}
  116. </Tag>
  117. );
  118. } else {
  119. return (
  120. <Tag color='purple' size='large' shape='circle'>
  121. {t('非流')}
  122. </Tag>
  123. );
  124. }
  125. }
  126. function renderUseTime(type) {
  127. const time = parseInt(type);
  128. if (time < 101) {
  129. return (
  130. <Tag color='green' size='large' shape='circle'>
  131. {' '}
  132. {time} s{' '}
  133. </Tag>
  134. );
  135. } else if (time < 300) {
  136. return (
  137. <Tag color='orange' size='large' shape='circle'>
  138. {' '}
  139. {time} s{' '}
  140. </Tag>
  141. );
  142. } else {
  143. return (
  144. <Tag color='red' size='large' shape='circle'>
  145. {' '}
  146. {time} s{' '}
  147. </Tag>
  148. );
  149. }
  150. }
  151. function renderFirstUseTime(type) {
  152. let time = parseFloat(type) / 1000.0;
  153. time = time.toFixed(1);
  154. if (time < 3) {
  155. return (
  156. <Tag color='green' size='large' shape='circle'>
  157. {' '}
  158. {time} s{' '}
  159. </Tag>
  160. );
  161. } else if (time < 10) {
  162. return (
  163. <Tag color='orange' size='large' shape='circle'>
  164. {' '}
  165. {time} s{' '}
  166. </Tag>
  167. );
  168. } else {
  169. return (
  170. <Tag color='red' size='large' shape='circle'>
  171. {' '}
  172. {time} s{' '}
  173. </Tag>
  174. );
  175. }
  176. }
  177. function renderModelName(record) {
  178. let other = getLogOther(record.other);
  179. let modelMapped =
  180. other?.is_model_mapped &&
  181. other?.upstream_model_name &&
  182. other?.upstream_model_name !== '';
  183. if (!modelMapped) {
  184. return renderModelTag(record.model_name, {
  185. onClick: (event) => {
  186. copyText(event, record.model_name).then((r) => {});
  187. },
  188. });
  189. } else {
  190. return (
  191. <>
  192. <Space vertical align={'start'}>
  193. <Popover
  194. content={
  195. <div style={{ padding: 10 }}>
  196. <Space vertical align={'start'}>
  197. <div className='flex items-center'>
  198. <Text strong style={{ marginRight: 8 }}>
  199. {t('请求并计费模型')}:
  200. </Text>
  201. {renderModelTag(record.model_name, {
  202. onClick: (event) => {
  203. copyText(event, record.model_name).then((r) => {});
  204. },
  205. })}
  206. </div>
  207. <div className='flex items-center'>
  208. <Text strong style={{ marginRight: 8 }}>
  209. {t('实际模型')}:
  210. </Text>
  211. {renderModelTag(other.upstream_model_name, {
  212. onClick: (event) => {
  213. copyText(event, other.upstream_model_name).then(
  214. (r) => {},
  215. );
  216. },
  217. })}
  218. </div>
  219. </Space>
  220. </div>
  221. }
  222. >
  223. {renderModelTag(record.model_name, {
  224. onClick: (event) => {
  225. copyText(event, record.model_name).then((r) => {});
  226. },
  227. suffixIcon: (
  228. <Route
  229. style={{ width: '0.9em', height: '0.9em', opacity: 0.75 }}
  230. />
  231. ),
  232. })}
  233. </Popover>
  234. </Space>
  235. </>
  236. );
  237. }
  238. }
  239. // Define column keys for selection
  240. const COLUMN_KEYS = {
  241. TIME: 'time',
  242. CHANNEL: 'channel',
  243. USERNAME: 'username',
  244. TOKEN: 'token',
  245. GROUP: 'group',
  246. TYPE: 'type',
  247. MODEL: 'model',
  248. USE_TIME: 'use_time',
  249. PROMPT: 'prompt',
  250. COMPLETION: 'completion',
  251. COST: 'cost',
  252. RETRY: 'retry',
  253. IP: 'ip',
  254. DETAILS: 'details',
  255. };
  256. // State for column visibility
  257. const [visibleColumns, setVisibleColumns] = useState({});
  258. const [showColumnSelector, setShowColumnSelector] = useState(false);
  259. // Load saved column preferences from localStorage
  260. useEffect(() => {
  261. const savedColumns = localStorage.getItem('logs-table-columns');
  262. if (savedColumns) {
  263. try {
  264. const parsed = JSON.parse(savedColumns);
  265. // Make sure all columns are accounted for
  266. const defaults = getDefaultColumnVisibility();
  267. const merged = { ...defaults, ...parsed };
  268. setVisibleColumns(merged);
  269. } catch (e) {
  270. console.error('Failed to parse saved column preferences', e);
  271. initDefaultColumns();
  272. }
  273. } else {
  274. initDefaultColumns();
  275. }
  276. }, []);
  277. // Get default column visibility based on user role
  278. const getDefaultColumnVisibility = () => {
  279. return {
  280. [COLUMN_KEYS.TIME]: true,
  281. [COLUMN_KEYS.CHANNEL]: isAdminUser,
  282. [COLUMN_KEYS.USERNAME]: isAdminUser,
  283. [COLUMN_KEYS.TOKEN]: true,
  284. [COLUMN_KEYS.GROUP]: true,
  285. [COLUMN_KEYS.TYPE]: true,
  286. [COLUMN_KEYS.MODEL]: true,
  287. [COLUMN_KEYS.USE_TIME]: true,
  288. [COLUMN_KEYS.PROMPT]: true,
  289. [COLUMN_KEYS.COMPLETION]: true,
  290. [COLUMN_KEYS.COST]: true,
  291. [COLUMN_KEYS.RETRY]: isAdminUser,
  292. [COLUMN_KEYS.IP]: true,
  293. [COLUMN_KEYS.DETAILS]: true,
  294. };
  295. };
  296. // Initialize default column visibility
  297. const initDefaultColumns = () => {
  298. const defaults = getDefaultColumnVisibility();
  299. setVisibleColumns(defaults);
  300. localStorage.setItem('logs-table-columns', JSON.stringify(defaults));
  301. };
  302. // Handle column visibility change
  303. const handleColumnVisibilityChange = (columnKey, checked) => {
  304. const updatedColumns = { ...visibleColumns, [columnKey]: checked };
  305. setVisibleColumns(updatedColumns);
  306. };
  307. // Handle "Select All" checkbox
  308. const handleSelectAll = (checked) => {
  309. const allKeys = Object.keys(COLUMN_KEYS).map((key) => COLUMN_KEYS[key]);
  310. const updatedColumns = {};
  311. allKeys.forEach((key) => {
  312. // For admin-only columns, only enable them if user is admin
  313. if (
  314. (key === COLUMN_KEYS.CHANNEL ||
  315. key === COLUMN_KEYS.USERNAME ||
  316. key === COLUMN_KEYS.RETRY) &&
  317. !isAdminUser
  318. ) {
  319. updatedColumns[key] = false;
  320. } else {
  321. updatedColumns[key] = checked;
  322. }
  323. });
  324. setVisibleColumns(updatedColumns);
  325. };
  326. // Define all columns
  327. const allColumns = [
  328. {
  329. key: COLUMN_KEYS.TIME,
  330. title: t('时间'),
  331. dataIndex: 'timestamp2string',
  332. },
  333. {
  334. key: COLUMN_KEYS.CHANNEL,
  335. title: t('渠道'),
  336. dataIndex: 'channel',
  337. className: isAdmin() ? 'tableShow' : 'tableHiddle',
  338. render: (text, record, index) => {
  339. return isAdminUser ? (
  340. record.type === 0 || record.type === 2 || record.type === 5 ? (
  341. <div>
  342. {
  343. <Tooltip content={record.channel_name || '[未知]'}>
  344. <Tag
  345. color={colors[parseInt(text) % colors.length]}
  346. size='large'
  347. shape='circle'
  348. >
  349. {' '}
  350. {text}{' '}
  351. </Tag>
  352. </Tooltip>
  353. }
  354. </div>
  355. ) : (
  356. <></>
  357. )
  358. ) : (
  359. <></>
  360. );
  361. },
  362. },
  363. {
  364. key: COLUMN_KEYS.USERNAME,
  365. title: t('用户'),
  366. dataIndex: 'username',
  367. className: isAdmin() ? 'tableShow' : 'tableHiddle',
  368. render: (text, record, index) => {
  369. return isAdminUser ? (
  370. <div>
  371. <Avatar
  372. size='small'
  373. color={stringToColor(text)}
  374. style={{ marginRight: 4 }}
  375. onClick={(event) => {
  376. event.stopPropagation();
  377. showUserInfo(record.user_id);
  378. }}
  379. >
  380. {typeof text === 'string' && text.slice(0, 1)}
  381. </Avatar>
  382. {text}
  383. </div>
  384. ) : (
  385. <></>
  386. );
  387. },
  388. },
  389. {
  390. key: COLUMN_KEYS.TOKEN,
  391. title: t('令牌'),
  392. dataIndex: 'token_name',
  393. render: (text, record, index) => {
  394. return record.type === 0 || record.type === 2 || record.type === 5 ? (
  395. <div>
  396. <Tag
  397. color='grey'
  398. size='large'
  399. shape='circle'
  400. onClick={(event) => {
  401. //cancel the row click event
  402. copyText(event, text);
  403. }}
  404. >
  405. {' '}
  406. {t(text)}{' '}
  407. </Tag>
  408. </div>
  409. ) : (
  410. <></>
  411. );
  412. },
  413. },
  414. {
  415. key: COLUMN_KEYS.GROUP,
  416. title: t('分组'),
  417. dataIndex: 'group',
  418. render: (text, record, index) => {
  419. if (record.type === 0 || record.type === 2 || record.type === 5) {
  420. if (record.group) {
  421. return <>{renderGroup(record.group)}</>;
  422. } else {
  423. let other = null;
  424. try {
  425. other = JSON.parse(record.other);
  426. } catch (e) {
  427. console.error(
  428. `Failed to parse record.other: "${record.other}".`,
  429. e,
  430. );
  431. }
  432. if (other === null) {
  433. return <></>;
  434. }
  435. if (other.group !== undefined) {
  436. return <>{renderGroup(other.group)}</>;
  437. } else {
  438. return <></>;
  439. }
  440. }
  441. } else {
  442. return <></>;
  443. }
  444. },
  445. },
  446. {
  447. key: COLUMN_KEYS.TYPE,
  448. title: t('类型'),
  449. dataIndex: 'type',
  450. render: (text, record, index) => {
  451. return <>{renderType(text)}</>;
  452. },
  453. },
  454. {
  455. key: COLUMN_KEYS.MODEL,
  456. title: t('模型'),
  457. dataIndex: 'model_name',
  458. render: (text, record, index) => {
  459. return record.type === 0 || record.type === 2 || record.type === 5 ? (
  460. <>{renderModelName(record)}</>
  461. ) : (
  462. <></>
  463. );
  464. },
  465. },
  466. {
  467. key: COLUMN_KEYS.USE_TIME,
  468. title: t('用时/首字'),
  469. dataIndex: 'use_time',
  470. render: (text, record, index) => {
  471. if (!(record.type === 2 || record.type === 5)) {
  472. return <></>;
  473. }
  474. if (record.is_stream) {
  475. let other = getLogOther(record.other);
  476. return (
  477. <>
  478. <Space>
  479. {renderUseTime(text)}
  480. {renderFirstUseTime(other?.frt)}
  481. {renderIsStream(record.is_stream)}
  482. </Space>
  483. </>
  484. );
  485. } else {
  486. return (
  487. <>
  488. <Space>
  489. {renderUseTime(text)}
  490. {renderIsStream(record.is_stream)}
  491. </Space>
  492. </>
  493. );
  494. }
  495. },
  496. },
  497. {
  498. key: COLUMN_KEYS.PROMPT,
  499. title: t('提示'),
  500. dataIndex: 'prompt_tokens',
  501. render: (text, record, index) => {
  502. return record.type === 0 || record.type === 2 || record.type === 5 ? (
  503. <>{<span> {text} </span>}</>
  504. ) : (
  505. <></>
  506. );
  507. },
  508. },
  509. {
  510. key: COLUMN_KEYS.COMPLETION,
  511. title: t('补全'),
  512. dataIndex: 'completion_tokens',
  513. render: (text, record, index) => {
  514. return parseInt(text) > 0 &&
  515. (record.type === 0 || record.type === 2 || record.type === 5) ? (
  516. <>{<span> {text} </span>}</>
  517. ) : (
  518. <></>
  519. );
  520. },
  521. },
  522. {
  523. key: COLUMN_KEYS.COST,
  524. title: t('花费'),
  525. dataIndex: 'quota',
  526. render: (text, record, index) => {
  527. return record.type === 0 || record.type === 2 || record.type === 5 ? (
  528. <>{renderQuota(text, 6)}</>
  529. ) : (
  530. <></>
  531. );
  532. },
  533. },
  534. {
  535. key: COLUMN_KEYS.IP,
  536. title: (
  537. <div className="flex items-center gap-1">
  538. {t('IP')}
  539. <Tooltip content={t('只有当用户设置开启IP记录时,才会进行请求和错误类型日志的IP记录')}>
  540. <IconHelpCircle className="text-gray-400 cursor-help" />
  541. </Tooltip>
  542. </div>
  543. ),
  544. dataIndex: 'ip',
  545. render: (text, record, index) => {
  546. return (record.type === 2 || record.type === 5) && text ? (
  547. <Tooltip content={text}>
  548. <Tag
  549. color='orange'
  550. size='large'
  551. shape='circle'
  552. onClick={(event) => {
  553. copyText(event, text);
  554. }}
  555. >
  556. {text}
  557. </Tag>
  558. </Tooltip>
  559. ) : (
  560. <></>
  561. );
  562. },
  563. },
  564. {
  565. key: COLUMN_KEYS.RETRY,
  566. title: t('重试'),
  567. dataIndex: 'retry',
  568. className: isAdmin() ? 'tableShow' : 'tableHiddle',
  569. render: (text, record, index) => {
  570. if (!(record.type === 2 || record.type === 5)) {
  571. return <></>;
  572. }
  573. let content = t('渠道') + `:${record.channel}`;
  574. if (record.other !== '') {
  575. let other = JSON.parse(record.other);
  576. if (other === null) {
  577. return <></>;
  578. }
  579. if (other.admin_info !== undefined) {
  580. if (
  581. other.admin_info.use_channel !== null &&
  582. other.admin_info.use_channel !== undefined &&
  583. other.admin_info.use_channel !== ''
  584. ) {
  585. // channel id array
  586. let useChannel = other.admin_info.use_channel;
  587. let useChannelStr = useChannel.join('->');
  588. content = t('渠道') + `:${useChannelStr}`;
  589. }
  590. }
  591. }
  592. return isAdminUser ? <div>{content}</div> : <></>;
  593. },
  594. },
  595. {
  596. key: COLUMN_KEYS.DETAILS,
  597. title: t('详情'),
  598. dataIndex: 'content',
  599. fixed: 'right',
  600. render: (text, record, index) => {
  601. let other = getLogOther(record.other);
  602. if (other == null || record.type !== 2) {
  603. return (
  604. <Paragraph
  605. ellipsis={{
  606. rows: 2,
  607. showTooltip: {
  608. type: 'popover',
  609. opts: { style: { width: 240 } },
  610. },
  611. }}
  612. style={{ maxWidth: 240 }}
  613. >
  614. {text}
  615. </Paragraph>
  616. );
  617. }
  618. let content = other?.claude
  619. ? renderClaudeModelPriceSimple(
  620. other.model_ratio,
  621. other.model_price,
  622. other.group_ratio,
  623. other?.user_group_ratio,
  624. other.cache_tokens || 0,
  625. other.cache_ratio || 1.0,
  626. other.cache_creation_tokens || 0,
  627. other.cache_creation_ratio || 1.0,
  628. )
  629. : renderModelPriceSimple(
  630. other.model_ratio,
  631. other.model_price,
  632. other.group_ratio,
  633. other?.user_group_ratio,
  634. other.cache_tokens || 0,
  635. other.cache_ratio || 1.0,
  636. );
  637. return (
  638. <Paragraph
  639. ellipsis={{
  640. rows: 2,
  641. }}
  642. style={{ maxWidth: 240 }}
  643. >
  644. {content}
  645. </Paragraph>
  646. );
  647. },
  648. },
  649. ];
  650. // Update table when column visibility changes
  651. useEffect(() => {
  652. if (Object.keys(visibleColumns).length > 0) {
  653. // Save to localStorage
  654. localStorage.setItem(
  655. 'logs-table-columns',
  656. JSON.stringify(visibleColumns),
  657. );
  658. }
  659. }, [visibleColumns]);
  660. // Filter columns based on visibility settings
  661. const getVisibleColumns = () => {
  662. return allColumns.filter((column) => visibleColumns[column.key]);
  663. };
  664. // Column selector modal
  665. const renderColumnSelector = () => {
  666. return (
  667. <Modal
  668. title={t('列设置')}
  669. visible={showColumnSelector}
  670. onCancel={() => setShowColumnSelector(false)}
  671. footer={
  672. <div className='flex justify-end'>
  673. <Button
  674. theme='light'
  675. onClick={() => initDefaultColumns()}
  676. className='!rounded-full'
  677. >
  678. {t('重置')}
  679. </Button>
  680. <Button
  681. theme='light'
  682. onClick={() => setShowColumnSelector(false)}
  683. className='!rounded-full'
  684. >
  685. {t('取消')}
  686. </Button>
  687. <Button
  688. type='primary'
  689. onClick={() => setShowColumnSelector(false)}
  690. className='!rounded-full'
  691. >
  692. {t('确定')}
  693. </Button>
  694. </div>
  695. }
  696. >
  697. <div style={{ marginBottom: 20 }}>
  698. <Checkbox
  699. checked={Object.values(visibleColumns).every((v) => v === true)}
  700. indeterminate={
  701. Object.values(visibleColumns).some((v) => v === true) &&
  702. !Object.values(visibleColumns).every((v) => v === true)
  703. }
  704. onChange={(e) => handleSelectAll(e.target.checked)}
  705. >
  706. {t('全选')}
  707. </Checkbox>
  708. </div>
  709. <div
  710. className='flex flex-wrap max-h-96 overflow-y-auto rounded-lg p-4'
  711. style={{ border: '1px solid var(--semi-color-border)' }}
  712. >
  713. {allColumns.map((column) => {
  714. // Skip admin-only columns for non-admin users
  715. if (
  716. !isAdminUser &&
  717. (column.key === COLUMN_KEYS.CHANNEL ||
  718. column.key === COLUMN_KEYS.USERNAME ||
  719. column.key === COLUMN_KEYS.RETRY)
  720. ) {
  721. return null;
  722. }
  723. return (
  724. <div key={column.key} className='w-1/2 mb-4 pr-2'>
  725. <Checkbox
  726. checked={!!visibleColumns[column.key]}
  727. onChange={(e) =>
  728. handleColumnVisibilityChange(column.key, e.target.checked)
  729. }
  730. >
  731. {column.title}
  732. </Checkbox>
  733. </div>
  734. );
  735. })}
  736. </div>
  737. </Modal>
  738. );
  739. };
  740. const [logs, setLogs] = useState([]);
  741. const [expandData, setExpandData] = useState({});
  742. const [showStat, setShowStat] = useState(false);
  743. const [loading, setLoading] = useState(false);
  744. const [loadingStat, setLoadingStat] = useState(false);
  745. const [activePage, setActivePage] = useState(1);
  746. const [logCount, setLogCount] = useState(ITEMS_PER_PAGE);
  747. const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
  748. const [logType, setLogType] = useState(0);
  749. const isAdminUser = isAdmin();
  750. let now = new Date();
  751. // Form 初始值
  752. const formInitValues = {
  753. username: '',
  754. token_name: '',
  755. model_name: '',
  756. channel: '',
  757. group: '',
  758. dateRange: [
  759. timestamp2string(getTodayStartTimestamp()),
  760. timestamp2string(now.getTime() / 1000 + 3600),
  761. ],
  762. logType: '0',
  763. };
  764. const [stat, setStat] = useState({
  765. quota: 0,
  766. token: 0,
  767. });
  768. // Form API 引用
  769. const [formApi, setFormApi] = useState(null);
  770. // 获取表单值的辅助函数,确保所有值都是字符串
  771. const getFormValues = () => {
  772. const formValues = formApi ? formApi.getValues() : {};
  773. // 处理时间范围
  774. let start_timestamp = timestamp2string(getTodayStartTimestamp());
  775. let end_timestamp = timestamp2string(now.getTime() / 1000 + 3600);
  776. if (
  777. formValues.dateRange &&
  778. Array.isArray(formValues.dateRange) &&
  779. formValues.dateRange.length === 2
  780. ) {
  781. start_timestamp = formValues.dateRange[0];
  782. end_timestamp = formValues.dateRange[1];
  783. }
  784. return {
  785. username: formValues.username || '',
  786. token_name: formValues.token_name || '',
  787. model_name: formValues.model_name || '',
  788. start_timestamp,
  789. end_timestamp,
  790. channel: formValues.channel || '',
  791. group: formValues.group || '',
  792. logType: formValues.logType ? parseInt(formValues.logType) : 0,
  793. };
  794. };
  795. const getLogSelfStat = async () => {
  796. const {
  797. token_name,
  798. model_name,
  799. start_timestamp,
  800. end_timestamp,
  801. group,
  802. logType: formLogType,
  803. } = getFormValues();
  804. const currentLogType = formLogType !== undefined ? formLogType : logType;
  805. let localStartTimestamp = Date.parse(start_timestamp) / 1000;
  806. let localEndTimestamp = Date.parse(end_timestamp) / 1000;
  807. let url = `/api/log/self/stat?type=${currentLogType}&token_name=${token_name}&model_name=${model_name}&start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}&group=${group}`;
  808. url = encodeURI(url);
  809. let res = await API.get(url);
  810. const { success, message, data } = res.data;
  811. if (success) {
  812. setStat(data);
  813. } else {
  814. showError(message);
  815. }
  816. };
  817. const getLogStat = async () => {
  818. const {
  819. username,
  820. token_name,
  821. model_name,
  822. start_timestamp,
  823. end_timestamp,
  824. channel,
  825. group,
  826. logType: formLogType,
  827. } = getFormValues();
  828. const currentLogType = formLogType !== undefined ? formLogType : logType;
  829. let localStartTimestamp = Date.parse(start_timestamp) / 1000;
  830. let localEndTimestamp = Date.parse(end_timestamp) / 1000;
  831. 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}`;
  832. url = encodeURI(url);
  833. let res = await API.get(url);
  834. const { success, message, data } = res.data;
  835. if (success) {
  836. setStat(data);
  837. } else {
  838. showError(message);
  839. }
  840. };
  841. const handleEyeClick = async () => {
  842. if (loadingStat) {
  843. return;
  844. }
  845. setLoadingStat(true);
  846. if (isAdminUser) {
  847. await getLogStat();
  848. } else {
  849. await getLogSelfStat();
  850. }
  851. setShowStat(true);
  852. setLoadingStat(false);
  853. };
  854. const showUserInfo = async (userId) => {
  855. if (!isAdminUser) {
  856. return;
  857. }
  858. const res = await API.get(`/api/user/${userId}`);
  859. const { success, message, data } = res.data;
  860. if (success) {
  861. Modal.info({
  862. title: t('用户信息'),
  863. content: (
  864. <div style={{ padding: 12 }}>
  865. <p>
  866. {t('用户名')}: {data.username}
  867. </p>
  868. <p>
  869. {t('余额')}: {renderQuota(data.quota)}
  870. </p>
  871. <p>
  872. {t('已用额度')}:{renderQuota(data.used_quota)}
  873. </p>
  874. <p>
  875. {t('请求次数')}:{renderNumber(data.request_count)}
  876. </p>
  877. </div>
  878. ),
  879. centered: true,
  880. });
  881. } else {
  882. showError(message);
  883. }
  884. };
  885. const setLogsFormat = (logs) => {
  886. let expandDatesLocal = {};
  887. for (let i = 0; i < logs.length; i++) {
  888. logs[i].timestamp2string = timestamp2string(logs[i].created_at);
  889. logs[i].key = logs[i].id;
  890. let other = getLogOther(logs[i].other);
  891. let expandDataLocal = [];
  892. if (isAdmin()) {
  893. // let content = '渠道:' + logs[i].channel;
  894. // if (other.admin_info !== undefined) {
  895. // if (
  896. // other.admin_info.use_channel !== null &&
  897. // other.admin_info.use_channel !== undefined &&
  898. // other.admin_info.use_channel !== ''
  899. // ) {
  900. // // channel id array
  901. // let useChannel = other.admin_info.use_channel;
  902. // let useChannelStr = useChannel.join('->');
  903. // content = `渠道:${useChannelStr}`;
  904. // }
  905. // }
  906. // expandDataLocal.push({
  907. // key: '渠道重试',
  908. // value: content,
  909. // })
  910. }
  911. if (isAdminUser && (logs[i].type === 0 || logs[i].type === 2)) {
  912. expandDataLocal.push({
  913. key: t('渠道信息'),
  914. value: `${logs[i].channel} - ${logs[i].channel_name || '[未知]'}`,
  915. });
  916. }
  917. if (other?.ws || other?.audio) {
  918. expandDataLocal.push({
  919. key: t('语音输入'),
  920. value: other.audio_input,
  921. });
  922. expandDataLocal.push({
  923. key: t('语音输出'),
  924. value: other.audio_output,
  925. });
  926. expandDataLocal.push({
  927. key: t('文字输入'),
  928. value: other.text_input,
  929. });
  930. expandDataLocal.push({
  931. key: t('文字输出'),
  932. value: other.text_output,
  933. });
  934. }
  935. if (other?.cache_tokens > 0) {
  936. expandDataLocal.push({
  937. key: t('缓存 Tokens'),
  938. value: other.cache_tokens,
  939. });
  940. }
  941. if (other?.cache_creation_tokens > 0) {
  942. expandDataLocal.push({
  943. key: t('缓存创建 Tokens'),
  944. value: other.cache_creation_tokens,
  945. });
  946. }
  947. if (logs[i].type === 2) {
  948. expandDataLocal.push({
  949. key: t('日志详情'),
  950. value: other?.claude
  951. ? renderClaudeLogContent(
  952. other?.model_ratio,
  953. other.completion_ratio,
  954. other.model_price,
  955. other.group_ratio,
  956. other?.user_group_ratio,
  957. other.cache_ratio || 1.0,
  958. other.cache_creation_ratio || 1.0,
  959. )
  960. : renderLogContent(
  961. other?.model_ratio,
  962. other.completion_ratio,
  963. other.model_price,
  964. other.group_ratio,
  965. other?.user_group_ratio,
  966. false,
  967. 1.0,
  968. other.web_search || false,
  969. other.web_search_call_count || 0,
  970. other.file_search || false,
  971. other.file_search_call_count || 0,
  972. ),
  973. });
  974. }
  975. if (logs[i].type === 2) {
  976. let modelMapped =
  977. other?.is_model_mapped &&
  978. other?.upstream_model_name &&
  979. other?.upstream_model_name !== '';
  980. if (modelMapped) {
  981. expandDataLocal.push({
  982. key: t('请求并计费模型'),
  983. value: logs[i].model_name,
  984. });
  985. expandDataLocal.push({
  986. key: t('实际模型'),
  987. value: other.upstream_model_name,
  988. });
  989. }
  990. let content = '';
  991. if (other?.ws || other?.audio) {
  992. content = renderAudioModelPrice(
  993. other?.text_input,
  994. other?.text_output,
  995. other?.model_ratio,
  996. other?.model_price,
  997. other?.completion_ratio,
  998. other?.audio_input,
  999. other?.audio_output,
  1000. other?.audio_ratio,
  1001. other?.audio_completion_ratio,
  1002. other?.group_ratio,
  1003. other?.user_group_ratio,
  1004. other?.cache_tokens || 0,
  1005. other?.cache_ratio || 1.0,
  1006. );
  1007. } else if (other?.claude) {
  1008. content = renderClaudeModelPrice(
  1009. logs[i].prompt_tokens,
  1010. logs[i].completion_tokens,
  1011. other.model_ratio,
  1012. other.model_price,
  1013. other.completion_ratio,
  1014. other.group_ratio,
  1015. other?.user_group_ratio,
  1016. other.cache_tokens || 0,
  1017. other.cache_ratio || 1.0,
  1018. other.cache_creation_tokens || 0,
  1019. other.cache_creation_ratio || 1.0,
  1020. );
  1021. } else {
  1022. content = renderModelPrice(
  1023. logs[i].prompt_tokens,
  1024. logs[i].completion_tokens,
  1025. other?.model_ratio,
  1026. other?.model_price,
  1027. other?.completion_ratio,
  1028. other?.group_ratio,
  1029. other?.user_group_ratio,
  1030. other?.cache_tokens || 0,
  1031. other?.cache_ratio || 1.0,
  1032. other?.image || false,
  1033. other?.image_ratio || 0,
  1034. other?.image_output || 0,
  1035. other?.web_search || false,
  1036. other?.web_search_call_count || 0,
  1037. other?.web_search_price || 0,
  1038. other?.file_search || false,
  1039. other?.file_search_call_count || 0,
  1040. other?.file_search_price || 0,
  1041. other?.audio_input_seperate_price || false,
  1042. other?.audio_input_token_count || 0,
  1043. other?.audio_input_price || 0,
  1044. );
  1045. }
  1046. expandDataLocal.push({
  1047. key: t('计费过程'),
  1048. value: content,
  1049. });
  1050. if (other?.reasoning_effort) {
  1051. expandDataLocal.push({
  1052. key: t('Reasoning Effort'),
  1053. value: other.reasoning_effort,
  1054. });
  1055. }
  1056. }
  1057. expandDatesLocal[logs[i].key] = expandDataLocal;
  1058. }
  1059. setExpandData(expandDatesLocal);
  1060. setLogs(logs);
  1061. };
  1062. const loadLogs = async (startIdx, pageSize, customLogType = null) => {
  1063. setLoading(true);
  1064. let url = '';
  1065. const {
  1066. username,
  1067. token_name,
  1068. model_name,
  1069. start_timestamp,
  1070. end_timestamp,
  1071. channel,
  1072. group,
  1073. logType: formLogType,
  1074. } = getFormValues();
  1075. // 使用传入的 logType 或者表单中的 logType 或者状态中的 logType
  1076. const currentLogType =
  1077. customLogType !== null
  1078. ? customLogType
  1079. : formLogType !== undefined
  1080. ? formLogType
  1081. : logType;
  1082. let localStartTimestamp = Date.parse(start_timestamp) / 1000;
  1083. let localEndTimestamp = Date.parse(end_timestamp) / 1000;
  1084. if (isAdminUser) {
  1085. 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}`;
  1086. } else {
  1087. 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}`;
  1088. }
  1089. url = encodeURI(url);
  1090. const res = await API.get(url);
  1091. const { success, message, data } = res.data;
  1092. if (success) {
  1093. const newPageData = data.items;
  1094. setActivePage(data.page);
  1095. setPageSize(data.page_size);
  1096. setLogCount(data.total);
  1097. setLogsFormat(newPageData);
  1098. } else {
  1099. showError(message);
  1100. }
  1101. setLoading(false);
  1102. };
  1103. const handlePageChange = (page) => {
  1104. setActivePage(page);
  1105. loadLogs(page, pageSize).then((r) => {}); // 不传入logType,让其从表单获取最新值
  1106. };
  1107. const handlePageSizeChange = async (size) => {
  1108. localStorage.setItem('page-size', size + '');
  1109. setPageSize(size);
  1110. setActivePage(1);
  1111. loadLogs(activePage, size)
  1112. .then()
  1113. .catch((reason) => {
  1114. showError(reason);
  1115. });
  1116. };
  1117. const refresh = async () => {
  1118. setActivePage(1);
  1119. handleEyeClick();
  1120. await loadLogs(1, pageSize); // 不传入logType,让其从表单获取最新值
  1121. };
  1122. const copyText = async (e, text) => {
  1123. e.stopPropagation();
  1124. if (await copy(text)) {
  1125. showSuccess('已复制:' + text);
  1126. } else {
  1127. Modal.error({ title: t('无法复制到剪贴板,请手动复制'), content: text });
  1128. }
  1129. };
  1130. useEffect(() => {
  1131. const localPageSize =
  1132. parseInt(localStorage.getItem('page-size')) || ITEMS_PER_PAGE;
  1133. setPageSize(localPageSize);
  1134. loadLogs(activePage, localPageSize)
  1135. .then()
  1136. .catch((reason) => {
  1137. showError(reason);
  1138. });
  1139. }, []);
  1140. // 当 formApi 可用时,初始化统计
  1141. useEffect(() => {
  1142. if (formApi) {
  1143. handleEyeClick();
  1144. }
  1145. }, [formApi]);
  1146. const expandRowRender = (record, index) => {
  1147. return <Descriptions data={expandData[record.key]} />;
  1148. };
  1149. // 检查是否有任何记录有展开内容
  1150. const hasExpandableRows = () => {
  1151. return logs.some(
  1152. (log) => expandData[log.key] && expandData[log.key].length > 0,
  1153. );
  1154. };
  1155. return (
  1156. <>
  1157. {renderColumnSelector()}
  1158. <Card
  1159. className='!rounded-2xl mb-4'
  1160. title={
  1161. <div className='flex flex-col w-full'>
  1162. <Spin spinning={loadingStat}>
  1163. <Space>
  1164. <Tag
  1165. color='blue'
  1166. size='large'
  1167. style={{
  1168. padding: 15,
  1169. borderRadius: '9999px',
  1170. fontWeight: 500,
  1171. boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)',
  1172. }}
  1173. >
  1174. {t('消耗额度')}: {renderQuota(stat.quota)}
  1175. </Tag>
  1176. <Tag
  1177. color='pink'
  1178. size='large'
  1179. style={{
  1180. padding: 15,
  1181. borderRadius: '9999px',
  1182. fontWeight: 500,
  1183. boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)',
  1184. }}
  1185. >
  1186. RPM: {stat.rpm}
  1187. </Tag>
  1188. <Tag
  1189. color='white'
  1190. size='large'
  1191. style={{
  1192. padding: 15,
  1193. border: 'none',
  1194. boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)',
  1195. borderRadius: '9999px',
  1196. fontWeight: 500,
  1197. }}
  1198. >
  1199. TPM: {stat.tpm}
  1200. </Tag>
  1201. </Space>
  1202. </Spin>
  1203. <Divider margin='12px' />
  1204. {/* 搜索表单区域 */}
  1205. <Form
  1206. initValues={formInitValues}
  1207. getFormApi={(api) => setFormApi(api)}
  1208. onSubmit={refresh}
  1209. allowEmpty={true}
  1210. autoComplete='off'
  1211. layout='vertical'
  1212. trigger='change'
  1213. stopValidateWithError={false}
  1214. >
  1215. <div className='flex flex-col gap-4'>
  1216. <div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4'>
  1217. {/* 时间选择器 */}
  1218. <div className='col-span-1 lg:col-span-2'>
  1219. <Form.DatePicker
  1220. field='dateRange'
  1221. className='w-full'
  1222. type='dateTimeRange'
  1223. placeholder={[t('开始时间'), t('结束时间')]}
  1224. showClear
  1225. pure
  1226. />
  1227. </div>
  1228. {/* 其他搜索字段 */}
  1229. <Form.Input
  1230. field='token_name'
  1231. prefix={<IconSearch />}
  1232. placeholder={t('令牌名称')}
  1233. className='!rounded-full'
  1234. showClear
  1235. pure
  1236. />
  1237. <Form.Input
  1238. field='model_name'
  1239. prefix={<IconSearch />}
  1240. placeholder={t('模型名称')}
  1241. className='!rounded-full'
  1242. showClear
  1243. pure
  1244. />
  1245. <Form.Input
  1246. field='group'
  1247. prefix={<IconSearch />}
  1248. placeholder={t('分组')}
  1249. className='!rounded-full'
  1250. showClear
  1251. pure
  1252. />
  1253. {isAdminUser && (
  1254. <>
  1255. <Form.Input
  1256. field='channel'
  1257. prefix={<IconSearch />}
  1258. placeholder={t('渠道 ID')}
  1259. className='!rounded-full'
  1260. showClear
  1261. pure
  1262. />
  1263. <Form.Input
  1264. field='username'
  1265. prefix={<IconSearch />}
  1266. placeholder={t('用户名称')}
  1267. className='!rounded-full'
  1268. showClear
  1269. pure
  1270. />
  1271. </>
  1272. )}
  1273. </div>
  1274. {/* 操作按钮区域 */}
  1275. <div className='flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3'>
  1276. {/* 日志类型选择器 */}
  1277. <div className='w-full sm:w-auto'>
  1278. <Form.Select
  1279. field='logType'
  1280. placeholder={t('日志类型')}
  1281. className='!rounded-full w-full sm:w-auto min-w-[120px]'
  1282. showClear
  1283. pure
  1284. onChange={() => {
  1285. // 延迟执行搜索,让表单值先更新
  1286. setTimeout(() => {
  1287. refresh();
  1288. }, 0);
  1289. }}
  1290. >
  1291. <Form.Select.Option value='0'>
  1292. {t('全部')}
  1293. </Form.Select.Option>
  1294. <Form.Select.Option value='1'>
  1295. {t('充值')}
  1296. </Form.Select.Option>
  1297. <Form.Select.Option value='2'>
  1298. {t('消费')}
  1299. </Form.Select.Option>
  1300. <Form.Select.Option value='3'>
  1301. {t('管理')}
  1302. </Form.Select.Option>
  1303. <Form.Select.Option value='4'>
  1304. {t('系统')}
  1305. </Form.Select.Option>
  1306. <Form.Select.Option value='5'>
  1307. {t('错误')}
  1308. </Form.Select.Option>
  1309. </Form.Select>
  1310. </div>
  1311. <div className='flex gap-2 w-full sm:w-auto justify-end'>
  1312. <Button
  1313. type='primary'
  1314. htmlType='submit'
  1315. loading={loading}
  1316. className='!rounded-full'
  1317. >
  1318. {t('查询')}
  1319. </Button>
  1320. <Button
  1321. theme='light'
  1322. onClick={() => {
  1323. if (formApi) {
  1324. formApi.reset();
  1325. setLogType(0);
  1326. // 重置后立即查询,使用setTimeout确保表单重置完成
  1327. setTimeout(() => {
  1328. refresh();
  1329. }, 100);
  1330. }
  1331. }}
  1332. className='!rounded-full'
  1333. >
  1334. {t('重置')}
  1335. </Button>
  1336. <Button
  1337. theme='light'
  1338. type='tertiary'
  1339. icon={<IconSetting />}
  1340. onClick={() => setShowColumnSelector(true)}
  1341. className='!rounded-full'
  1342. >
  1343. {t('列设置')}
  1344. </Button>
  1345. </div>
  1346. </div>
  1347. </div>
  1348. </Form>
  1349. </div>
  1350. }
  1351. shadows='always'
  1352. bordered={false}
  1353. >
  1354. <Table
  1355. columns={getVisibleColumns()}
  1356. {...(hasExpandableRows() && {
  1357. expandedRowRender: expandRowRender,
  1358. expandRowByClick: true,
  1359. rowExpandable: (record) =>
  1360. expandData[record.key] && expandData[record.key].length > 0,
  1361. })}
  1362. dataSource={logs}
  1363. rowKey='key'
  1364. loading={loading}
  1365. scroll={{ x: 'max-content' }}
  1366. className='rounded-xl overflow-hidden'
  1367. size='middle'
  1368. empty={
  1369. <Empty
  1370. image={
  1371. <IllustrationNoResult style={{ width: 150, height: 150 }} />
  1372. }
  1373. darkModeImage={
  1374. <IllustrationNoResultDark style={{ width: 150, height: 150 }} />
  1375. }
  1376. description={t('搜索无结果')}
  1377. style={{ padding: 30 }}
  1378. />
  1379. }
  1380. pagination={{
  1381. formatPageText: (page) =>
  1382. t('第 {{start}} - {{end}} 条,共 {{total}} 条', {
  1383. start: page.currentStart,
  1384. end: page.currentEnd,
  1385. total: logCount,
  1386. }),
  1387. currentPage: activePage,
  1388. pageSize: pageSize,
  1389. total: logCount,
  1390. pageSizeOptions: [10, 20, 50, 100],
  1391. showSizeChanger: true,
  1392. onPageSizeChange: (size) => {
  1393. handlePageSizeChange(size);
  1394. },
  1395. onPageChange: handlePageChange,
  1396. }}
  1397. />
  1398. </Card>
  1399. </>
  1400. );
  1401. };
  1402. export default LogsTable;