LogsTable.js 36 KB

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