utils.jsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  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 { Toast, Pagination } from '@douyinfe/semi-ui';
  16. import { toastConstants } from '../constants';
  17. import React from 'react';
  18. import { toast } from 'react-toastify';
  19. import {
  20. THINK_TAG_REGEX,
  21. MESSAGE_ROLES,
  22. } from '../constants/playground.constants';
  23. import { TABLE_COMPACT_MODES_KEY } from '../constants';
  24. import { MOBILE_BREAKPOINT } from '../hooks/common/useIsMobile';
  25. const HTMLToastContent = ({ htmlContent }) => {
  26. return <div dangerouslySetInnerHTML={{ __html: htmlContent }} />;
  27. };
  28. export default HTMLToastContent;
  29. export function isAdmin() {
  30. let user = localStorage.getItem('user');
  31. if (!user) return false;
  32. user = JSON.parse(user);
  33. return user.role >= 10;
  34. }
  35. export function isRoot() {
  36. let user = localStorage.getItem('user');
  37. if (!user) return false;
  38. user = JSON.parse(user);
  39. return user.role >= 100;
  40. }
  41. export function getSystemName() {
  42. let system_name = localStorage.getItem('system_name');
  43. if (!system_name) return 'New API';
  44. return system_name;
  45. }
  46. export function getLogo() {
  47. let logo = localStorage.getItem('logo');
  48. if (!logo) return '/logo.png';
  49. return logo;
  50. }
  51. export function getUserIdFromLocalStorage() {
  52. let user = localStorage.getItem('user');
  53. if (!user) return -1;
  54. user = JSON.parse(user);
  55. return user.id;
  56. }
  57. export function getFooterHTML() {
  58. return localStorage.getItem('footer_html');
  59. }
  60. export async function copy(text) {
  61. let okay = true;
  62. try {
  63. await navigator.clipboard.writeText(text);
  64. } catch (e) {
  65. try {
  66. // 构建 textarea 执行复制命令,保留多行文本格式
  67. const textarea = window.document.createElement('textarea');
  68. textarea.value = text;
  69. textarea.setAttribute('readonly', '');
  70. textarea.style.position = 'fixed';
  71. textarea.style.left = '-9999px';
  72. textarea.style.top = '-9999px';
  73. window.document.body.appendChild(textarea);
  74. textarea.select();
  75. window.document.execCommand('copy');
  76. window.document.body.removeChild(textarea);
  77. } catch (e) {
  78. okay = false;
  79. console.error(e);
  80. }
  81. }
  82. return okay;
  83. }
  84. // isMobile 函数已移除,请改用 useIsMobile Hook
  85. let showErrorOptions = { autoClose: toastConstants.ERROR_TIMEOUT };
  86. let showWarningOptions = { autoClose: toastConstants.WARNING_TIMEOUT };
  87. let showSuccessOptions = { autoClose: toastConstants.SUCCESS_TIMEOUT };
  88. let showInfoOptions = { autoClose: toastConstants.INFO_TIMEOUT };
  89. let showNoticeOptions = { autoClose: false };
  90. const isMobileScreen = window.matchMedia(
  91. `(max-width: ${MOBILE_BREAKPOINT - 1}px)`,
  92. ).matches;
  93. if (isMobileScreen) {
  94. showErrorOptions.position = 'top-center';
  95. // showErrorOptions.transition = 'flip';
  96. showSuccessOptions.position = 'top-center';
  97. // showSuccessOptions.transition = 'flip';
  98. showInfoOptions.position = 'top-center';
  99. // showInfoOptions.transition = 'flip';
  100. showNoticeOptions.position = 'top-center';
  101. // showNoticeOptions.transition = 'flip';
  102. }
  103. export function showError(error) {
  104. console.error(error);
  105. if (error.message) {
  106. if (error.name === 'AxiosError') {
  107. switch (error.response.status) {
  108. case 401:
  109. // 清除用户状态
  110. localStorage.removeItem('user');
  111. // toast.error('错误:未登录或登录已过期,请重新登录!', showErrorOptions);
  112. window.location.href = '/login?expired=true';
  113. break;
  114. case 429:
  115. Toast.error('错误:请求次数过多,请稍后再试!');
  116. break;
  117. case 500:
  118. Toast.error('错误:服务器内部错误,请联系管理员!');
  119. break;
  120. case 405:
  121. Toast.info('本站仅作演示之用,无服务端!');
  122. break;
  123. default:
  124. Toast.error('错误:' + error.message);
  125. }
  126. return;
  127. }
  128. Toast.error('错误:' + error.message);
  129. } else {
  130. Toast.error('错误:' + error);
  131. }
  132. }
  133. export function showWarning(message) {
  134. Toast.warning(message);
  135. }
  136. export function showSuccess(message) {
  137. Toast.success(message);
  138. }
  139. export function showInfo(message) {
  140. Toast.info(message);
  141. }
  142. export function showNotice(message, isHTML = false) {
  143. if (isHTML) {
  144. toast(<HTMLToastContent htmlContent={message} />, showNoticeOptions);
  145. } else {
  146. Toast.info(message);
  147. }
  148. }
  149. export function openPage(url) {
  150. window.open(url);
  151. }
  152. export function removeTrailingSlash(url) {
  153. if (!url) return '';
  154. if (url.endsWith('/')) {
  155. return url.slice(0, -1);
  156. } else {
  157. return url;
  158. }
  159. }
  160. export function getTodayStartTimestamp() {
  161. var now = new Date();
  162. now.setHours(0, 0, 0, 0);
  163. return Math.floor(now.getTime() / 1000);
  164. }
  165. export function timestamp2string(timestamp) {
  166. let date = new Date(timestamp * 1000);
  167. let year = date.getFullYear().toString();
  168. let month = (date.getMonth() + 1).toString();
  169. let day = date.getDate().toString();
  170. let hour = date.getHours().toString();
  171. let minute = date.getMinutes().toString();
  172. let second = date.getSeconds().toString();
  173. if (month.length === 1) {
  174. month = '0' + month;
  175. }
  176. if (day.length === 1) {
  177. day = '0' + day;
  178. }
  179. if (hour.length === 1) {
  180. hour = '0' + hour;
  181. }
  182. if (minute.length === 1) {
  183. minute = '0' + minute;
  184. }
  185. if (second.length === 1) {
  186. second = '0' + second;
  187. }
  188. return (
  189. year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
  190. );
  191. }
  192. export function timestamp2string1(
  193. timestamp,
  194. dataExportDefaultTime = 'hour',
  195. showYear = false,
  196. ) {
  197. let date = new Date(timestamp * 1000);
  198. let year = date.getFullYear();
  199. let month = (date.getMonth() + 1).toString();
  200. let day = date.getDate().toString();
  201. let hour = date.getHours().toString();
  202. if (month.length === 1) {
  203. month = '0' + month;
  204. }
  205. if (day.length === 1) {
  206. day = '0' + day;
  207. }
  208. if (hour.length === 1) {
  209. hour = '0' + hour;
  210. }
  211. // 仅在跨年时显示年份
  212. let str = showYear ? year + '-' + month + '-' + day : month + '-' + day;
  213. if (dataExportDefaultTime === 'hour') {
  214. str += ' ' + hour + ':00';
  215. } else if (dataExportDefaultTime === 'week') {
  216. let nextWeek = new Date(timestamp * 1000 + 6 * 24 * 60 * 60 * 1000);
  217. let nextWeekYear = nextWeek.getFullYear();
  218. let nextMonth = (nextWeek.getMonth() + 1).toString();
  219. let nextDay = nextWeek.getDate().toString();
  220. if (nextMonth.length === 1) {
  221. nextMonth = '0' + nextMonth;
  222. }
  223. if (nextDay.length === 1) {
  224. nextDay = '0' + nextDay;
  225. }
  226. // 周视图结束日期也仅在跨年时显示年份
  227. let nextStr = showYear
  228. ? nextWeekYear + '-' + nextMonth + '-' + nextDay
  229. : nextMonth + '-' + nextDay;
  230. str += ' - ' + nextStr;
  231. }
  232. return str;
  233. }
  234. // 检查时间戳数组是否跨年
  235. export function isDataCrossYear(timestamps) {
  236. if (!timestamps || timestamps.length === 0) return false;
  237. const years = new Set(
  238. timestamps.map((ts) => new Date(ts * 1000).getFullYear()),
  239. );
  240. return years.size > 1;
  241. }
  242. export function downloadTextAsFile(text, filename) {
  243. let blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
  244. let url = URL.createObjectURL(blob);
  245. let a = document.createElement('a');
  246. a.href = url;
  247. a.download = filename;
  248. a.click();
  249. }
  250. export const verifyJSON = (str) => {
  251. try {
  252. JSON.parse(str);
  253. } catch (e) {
  254. return false;
  255. }
  256. return true;
  257. };
  258. export function verifyJSONPromise(value) {
  259. try {
  260. JSON.parse(value);
  261. return Promise.resolve();
  262. } catch (e) {
  263. return Promise.reject('不是合法的 JSON 字符串');
  264. }
  265. }
  266. export function shouldShowPrompt(id) {
  267. let prompt = localStorage.getItem(`prompt-${id}`);
  268. return !prompt;
  269. }
  270. export function setPromptShown(id) {
  271. localStorage.setItem(`prompt-${id}`, 'true');
  272. }
  273. /**
  274. * 比较两个对象的属性,找出有变化的属性,并返回包含变化属性信息的数组
  275. * @param {Object} oldObject - 旧对象
  276. * @param {Object} newObject - 新对象
  277. * @return {Array} 包含变化属性信息的数组,每个元素是一个对象,包含 key, oldValue 和 newValue
  278. */
  279. export function compareObjects(oldObject, newObject) {
  280. const changedProperties = [];
  281. // 比较两个对象的属性
  282. for (const key in oldObject) {
  283. if (oldObject.hasOwnProperty(key) && newObject.hasOwnProperty(key)) {
  284. if (oldObject[key] !== newObject[key]) {
  285. changedProperties.push({
  286. key: key,
  287. oldValue: oldObject[key],
  288. newValue: newObject[key],
  289. });
  290. }
  291. }
  292. }
  293. return changedProperties;
  294. }
  295. // playground message
  296. // 生成唯一ID
  297. let messageId = 4;
  298. export const generateMessageId = () => `${messageId++}`;
  299. // 提取消息中的文本内容
  300. export const getTextContent = (message) => {
  301. if (!message || !message.content) return '';
  302. if (Array.isArray(message.content)) {
  303. const textContent = message.content.find((item) => item.type === 'text');
  304. return textContent?.text || '';
  305. }
  306. return typeof message.content === 'string' ? message.content : '';
  307. };
  308. // 处理 think 标签
  309. export const processThinkTags = (content, reasoningContent = '') => {
  310. if (!content || !content.includes('<think>')) {
  311. return { content, reasoningContent };
  312. }
  313. const thoughts = [];
  314. const replyParts = [];
  315. let lastIndex = 0;
  316. let match;
  317. THINK_TAG_REGEX.lastIndex = 0;
  318. while ((match = THINK_TAG_REGEX.exec(content)) !== null) {
  319. replyParts.push(content.substring(lastIndex, match.index));
  320. thoughts.push(match[1]);
  321. lastIndex = match.index + match[0].length;
  322. }
  323. replyParts.push(content.substring(lastIndex));
  324. const processedContent = replyParts
  325. .join('')
  326. .replace(/<\/?think>/g, '')
  327. .trim();
  328. const thoughtsStr = thoughts.join('\n\n---\n\n');
  329. const processedReasoningContent =
  330. reasoningContent && thoughtsStr
  331. ? `${reasoningContent}\n\n---\n\n${thoughtsStr}`
  332. : reasoningContent || thoughtsStr;
  333. return {
  334. content: processedContent,
  335. reasoningContent: processedReasoningContent,
  336. };
  337. };
  338. // 处理未完成的 think 标签
  339. export const processIncompleteThinkTags = (content, reasoningContent = '') => {
  340. if (!content) return { content: '', reasoningContent };
  341. const lastOpenThinkIndex = content.lastIndexOf('<think>');
  342. if (lastOpenThinkIndex === -1) {
  343. return processThinkTags(content, reasoningContent);
  344. }
  345. const fragmentAfterLastOpen = content.substring(lastOpenThinkIndex);
  346. if (!fragmentAfterLastOpen.includes('</think>')) {
  347. const unclosedThought = fragmentAfterLastOpen
  348. .substring('<think>'.length)
  349. .trim();
  350. const cleanContent = content.substring(0, lastOpenThinkIndex);
  351. const processedReasoningContent = unclosedThought
  352. ? reasoningContent
  353. ? `${reasoningContent}\n\n---\n\n${unclosedThought}`
  354. : unclosedThought
  355. : reasoningContent;
  356. return processThinkTags(cleanContent, processedReasoningContent);
  357. }
  358. return processThinkTags(content, reasoningContent);
  359. };
  360. // 构建消息内容(包含图片)
  361. export const buildMessageContent = (
  362. textContent,
  363. imageUrls = [],
  364. imageEnabled = false,
  365. ) => {
  366. if (!textContent && (!imageUrls || imageUrls.length === 0)) {
  367. return '';
  368. }
  369. const validImageUrls = imageUrls.filter((url) => url && url.trim() !== '');
  370. if (imageEnabled && validImageUrls.length > 0) {
  371. return [
  372. { type: 'text', text: textContent || '' },
  373. ...validImageUrls.map((url) => ({
  374. type: 'image_url',
  375. image_url: { url: url.trim() },
  376. })),
  377. ];
  378. }
  379. return textContent || '';
  380. };
  381. // 创建新消息
  382. export const createMessage = (role, content, options = {}) => ({
  383. role,
  384. content,
  385. createAt: Date.now(),
  386. id: generateMessageId(),
  387. ...options,
  388. });
  389. // 创建加载中的助手消息
  390. export const createLoadingAssistantMessage = () =>
  391. createMessage(MESSAGE_ROLES.ASSISTANT, '', {
  392. reasoningContent: '',
  393. isReasoningExpanded: true,
  394. isThinkingComplete: false,
  395. hasAutoCollapsed: false,
  396. status: 'loading',
  397. });
  398. // 检查消息是否包含图片
  399. export const hasImageContent = (message) => {
  400. return (
  401. message &&
  402. Array.isArray(message.content) &&
  403. message.content.some((item) => item.type === 'image_url')
  404. );
  405. };
  406. // 格式化消息用于API请求
  407. export const formatMessageForAPI = (message) => {
  408. if (!message) return null;
  409. return {
  410. role: message.role,
  411. content: message.content,
  412. };
  413. };
  414. // 验证消息是否有效
  415. export const isValidMessage = (message) => {
  416. return message && message.role && (message.content || message.content === '');
  417. };
  418. // 获取最后一条用户消息
  419. export const getLastUserMessage = (messages) => {
  420. if (!Array.isArray(messages)) return null;
  421. for (let i = messages.length - 1; i >= 0; i--) {
  422. if (messages[i].role === MESSAGE_ROLES.USER) {
  423. return messages[i];
  424. }
  425. }
  426. return null;
  427. };
  428. // 获取最后一条助手消息
  429. export const getLastAssistantMessage = (messages) => {
  430. if (!Array.isArray(messages)) return null;
  431. for (let i = messages.length - 1; i >= 0; i--) {
  432. if (messages[i].role === MESSAGE_ROLES.ASSISTANT) {
  433. return messages[i];
  434. }
  435. }
  436. return null;
  437. };
  438. // 计算相对时间(几天前、几小时前等)
  439. export const getRelativeTime = (publishDate) => {
  440. if (!publishDate) return '';
  441. const now = new Date();
  442. const pubDate = new Date(publishDate);
  443. // 如果日期无效,返回原始字符串
  444. if (isNaN(pubDate.getTime())) return publishDate;
  445. const diffMs = now.getTime() - pubDate.getTime();
  446. const diffSeconds = Math.floor(diffMs / 1000);
  447. const diffMinutes = Math.floor(diffSeconds / 60);
  448. const diffHours = Math.floor(diffMinutes / 60);
  449. const diffDays = Math.floor(diffHours / 24);
  450. const diffWeeks = Math.floor(diffDays / 7);
  451. const diffMonths = Math.floor(diffDays / 30);
  452. const diffYears = Math.floor(diffDays / 365);
  453. // 如果是未来时间,显示具体日期
  454. if (diffMs < 0) {
  455. return formatDateString(pubDate);
  456. }
  457. // 根据时间差返回相应的描述
  458. if (diffSeconds < 60) {
  459. return '刚刚';
  460. } else if (diffMinutes < 60) {
  461. return `${diffMinutes} 分钟前`;
  462. } else if (diffHours < 24) {
  463. return `${diffHours} 小时前`;
  464. } else if (diffDays < 7) {
  465. return `${diffDays} 天前`;
  466. } else if (diffWeeks < 4) {
  467. return `${diffWeeks} 周前`;
  468. } else if (diffMonths < 12) {
  469. return `${diffMonths} 个月前`;
  470. } else if (diffYears < 2) {
  471. return '1 年前';
  472. } else {
  473. // 超过2年显示具体日期
  474. return formatDateString(pubDate);
  475. }
  476. };
  477. // 格式化日期字符串
  478. export const formatDateString = (date) => {
  479. const year = date.getFullYear();
  480. const month = String(date.getMonth() + 1).padStart(2, '0');
  481. const day = String(date.getDate()).padStart(2, '0');
  482. return `${year}-${month}-${day}`;
  483. };
  484. // 格式化日期时间字符串(包含时间)
  485. export const formatDateTimeString = (date) => {
  486. const year = date.getFullYear();
  487. const month = String(date.getMonth() + 1).padStart(2, '0');
  488. const day = String(date.getDate()).padStart(2, '0');
  489. const hours = String(date.getHours()).padStart(2, '0');
  490. const minutes = String(date.getMinutes()).padStart(2, '0');
  491. return `${year}-${month}-${day} ${hours}:${minutes}`;
  492. };
  493. function readTableCompactModes() {
  494. try {
  495. const json = localStorage.getItem(TABLE_COMPACT_MODES_KEY);
  496. return json ? JSON.parse(json) : {};
  497. } catch {
  498. return {};
  499. }
  500. }
  501. function writeTableCompactModes(modes) {
  502. try {
  503. localStorage.setItem(TABLE_COMPACT_MODES_KEY, JSON.stringify(modes));
  504. } catch {
  505. // ignore
  506. }
  507. }
  508. export function getTableCompactMode(tableKey = 'global') {
  509. const modes = readTableCompactModes();
  510. return !!modes[tableKey];
  511. }
  512. export function setTableCompactMode(compact, tableKey = 'global') {
  513. const modes = readTableCompactModes();
  514. modes[tableKey] = compact;
  515. writeTableCompactModes(modes);
  516. }
  517. // -------------------------------
  518. // Select 组件统一过滤逻辑
  519. // 使用方式: <Select filter={selectFilter} ... />
  520. // 统一的 Select 搜索过滤逻辑 -- 支持同时匹配 option.value 与 option.label
  521. export const selectFilter = (input, option) => {
  522. if (!input) return true;
  523. const keyword = input.trim().toLowerCase();
  524. const valueText = (option?.value ?? '').toString().toLowerCase();
  525. const labelText = (option?.label ?? '').toString().toLowerCase();
  526. return valueText.includes(keyword) || labelText.includes(keyword);
  527. };
  528. // -------------------------------
  529. // 模型定价计算工具函数
  530. export const calculateModelPrice = ({
  531. record,
  532. selectedGroup,
  533. groupRatio,
  534. tokenUnit,
  535. displayPrice,
  536. currency,
  537. precision = 4,
  538. }) => {
  539. // 1. 选择实际使用的分组
  540. let usedGroup = selectedGroup;
  541. let usedGroupRatio = groupRatio[selectedGroup];
  542. if (selectedGroup === 'all' || usedGroupRatio === undefined) {
  543. // 在模型可用分组中选择倍率最小的分组,若无则使用 1
  544. let minRatio = Number.POSITIVE_INFINITY;
  545. if (
  546. Array.isArray(record.enable_groups) &&
  547. record.enable_groups.length > 0
  548. ) {
  549. record.enable_groups.forEach((g) => {
  550. const r = groupRatio[g];
  551. if (r !== undefined && r < minRatio) {
  552. minRatio = r;
  553. usedGroup = g;
  554. usedGroupRatio = r;
  555. }
  556. });
  557. }
  558. // 如果找不到合适分组倍率,回退为 1
  559. if (usedGroupRatio === undefined) {
  560. usedGroupRatio = 1;
  561. }
  562. }
  563. // 2. 根据计费类型计算价格
  564. if (record.quota_type === 0) {
  565. // 按量计费
  566. const inputRatioPriceUSD = record.model_ratio * 2 * usedGroupRatio;
  567. const completionRatioPriceUSD =
  568. record.model_ratio * record.completion_ratio * 2 * usedGroupRatio;
  569. const unitDivisor = tokenUnit === 'K' ? 1000 : 1;
  570. const unitLabel = tokenUnit === 'K' ? 'K' : 'M';
  571. const rawDisplayInput = displayPrice(inputRatioPriceUSD);
  572. const rawDisplayCompletion = displayPrice(completionRatioPriceUSD);
  573. const numInput =
  574. parseFloat(rawDisplayInput.replace(/[^0-9.]/g, '')) / unitDivisor;
  575. const numCompletion =
  576. parseFloat(rawDisplayCompletion.replace(/[^0-9.]/g, '')) / unitDivisor;
  577. let symbol = '$';
  578. if (currency === 'CNY') {
  579. symbol = '¥';
  580. } else if (currency === 'CUSTOM') {
  581. try {
  582. const statusStr = localStorage.getItem('status');
  583. if (statusStr) {
  584. const s = JSON.parse(statusStr);
  585. symbol = s?.custom_currency_symbol || '¤';
  586. } else {
  587. symbol = '¤';
  588. }
  589. } catch (e) {
  590. symbol = '¤';
  591. }
  592. }
  593. return {
  594. inputPrice: `${symbol}${numInput.toFixed(precision)}`,
  595. completionPrice: `${symbol}${numCompletion.toFixed(precision)}`,
  596. unitLabel,
  597. isPerToken: true,
  598. usedGroup,
  599. usedGroupRatio,
  600. };
  601. }
  602. if (record.quota_type === 1) {
  603. // 按次计费
  604. const priceUSD = parseFloat(record.model_price) * usedGroupRatio;
  605. const displayVal = displayPrice(priceUSD);
  606. return {
  607. price: displayVal,
  608. isPerToken: false,
  609. usedGroup,
  610. usedGroupRatio,
  611. };
  612. }
  613. // 未知计费类型,返回占位信息
  614. return {
  615. price: '-',
  616. isPerToken: false,
  617. usedGroup,
  618. usedGroupRatio,
  619. };
  620. };
  621. // 格式化价格信息(用于卡片视图)
  622. export const formatPriceInfo = (priceData, t) => {
  623. if (priceData.isPerToken) {
  624. return (
  625. <>
  626. <span style={{ color: 'var(--semi-color-text-1)' }}>
  627. {t('输入')} {priceData.inputPrice}/{priceData.unitLabel}
  628. </span>
  629. <span style={{ color: 'var(--semi-color-text-1)' }}>
  630. {t('输出')} {priceData.completionPrice}/{priceData.unitLabel}
  631. </span>
  632. </>
  633. );
  634. }
  635. return (
  636. <>
  637. <span style={{ color: 'var(--semi-color-text-1)' }}>
  638. {t('模型价格')} {priceData.price}
  639. </span>
  640. </>
  641. );
  642. };
  643. // -------------------------------
  644. // CardPro 分页配置函数
  645. // 用于创建 CardPro 的 paginationArea 配置
  646. export const createCardProPagination = ({
  647. currentPage,
  648. pageSize,
  649. total,
  650. onPageChange,
  651. onPageSizeChange,
  652. isMobile = false,
  653. pageSizeOpts = [10, 20, 50, 100],
  654. showSizeChanger = true,
  655. t = (key) => key,
  656. }) => {
  657. if (!total || total <= 0) return null;
  658. const start = (currentPage - 1) * pageSize + 1;
  659. const end = Math.min(currentPage * pageSize, total);
  660. const totalText = `${t('显示第')} ${start} ${t('条 - 第')} ${end} ${t('条,共')} ${total} ${t('条')}`;
  661. return (
  662. <>
  663. {/* 桌面端左侧总数信息 */}
  664. {!isMobile && (
  665. <span
  666. className='text-sm select-none'
  667. style={{ color: 'var(--semi-color-text-2)' }}
  668. >
  669. {totalText}
  670. </span>
  671. )}
  672. {/* 右侧分页控件 */}
  673. <Pagination
  674. currentPage={currentPage}
  675. pageSize={pageSize}
  676. total={total}
  677. pageSizeOpts={pageSizeOpts}
  678. showSizeChanger={showSizeChanger}
  679. onPageSizeChange={onPageSizeChange}
  680. onPageChange={onPageChange}
  681. size={isMobile ? 'small' : 'default'}
  682. showQuickJumper={isMobile}
  683. showTotal
  684. />
  685. </>
  686. );
  687. };
  688. // 模型定价筛选条件默认值
  689. const DEFAULT_PRICING_FILTERS = {
  690. search: '',
  691. showWithRecharge: false,
  692. currency: 'USD',
  693. showRatio: false,
  694. viewMode: 'card',
  695. tokenUnit: 'M',
  696. filterGroup: 'all',
  697. filterQuotaType: 'all',
  698. filterEndpointType: 'all',
  699. filterVendor: 'all',
  700. filterTag: 'all',
  701. currentPage: 1,
  702. };
  703. // 重置模型定价筛选条件
  704. export const resetPricingFilters = ({
  705. handleChange,
  706. setShowWithRecharge,
  707. setCurrency,
  708. setShowRatio,
  709. setViewMode,
  710. setFilterGroup,
  711. setFilterQuotaType,
  712. setFilterEndpointType,
  713. setFilterVendor,
  714. setFilterTag,
  715. setCurrentPage,
  716. setTokenUnit,
  717. }) => {
  718. handleChange?.(DEFAULT_PRICING_FILTERS.search);
  719. setShowWithRecharge?.(DEFAULT_PRICING_FILTERS.showWithRecharge);
  720. setCurrency?.(DEFAULT_PRICING_FILTERS.currency);
  721. setShowRatio?.(DEFAULT_PRICING_FILTERS.showRatio);
  722. setViewMode?.(DEFAULT_PRICING_FILTERS.viewMode);
  723. setTokenUnit?.(DEFAULT_PRICING_FILTERS.tokenUnit);
  724. setFilterGroup?.(DEFAULT_PRICING_FILTERS.filterGroup);
  725. setFilterQuotaType?.(DEFAULT_PRICING_FILTERS.filterQuotaType);
  726. setFilterEndpointType?.(DEFAULT_PRICING_FILTERS.filterEndpointType);
  727. setFilterVendor?.(DEFAULT_PRICING_FILTERS.filterVendor);
  728. setFilterTag?.(DEFAULT_PRICING_FILTERS.filterTag);
  729. setCurrentPage?.(DEFAULT_PRICING_FILTERS.currentPage);
  730. };