utils.jsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  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(timestamp, dataExportDefaultTime = 'hour', showYear = false) {
  193. let date = new Date(timestamp * 1000);
  194. let year = date.getFullYear();
  195. let month = (date.getMonth() + 1).toString();
  196. let day = date.getDate().toString();
  197. let hour = date.getHours().toString();
  198. if (month.length === 1) {
  199. month = '0' + month;
  200. }
  201. if (day.length === 1) {
  202. day = '0' + day;
  203. }
  204. if (hour.length === 1) {
  205. hour = '0' + hour;
  206. }
  207. // 仅在跨年时显示年份
  208. let str = showYear ? year + '-' + month + '-' + day : month + '-' + day;
  209. if (dataExportDefaultTime === 'hour') {
  210. str += ' ' + hour + ':00';
  211. } else if (dataExportDefaultTime === 'week') {
  212. let nextWeek = new Date(timestamp * 1000 + 6 * 24 * 60 * 60 * 1000);
  213. let nextWeekYear = nextWeek.getFullYear();
  214. let nextMonth = (nextWeek.getMonth() + 1).toString();
  215. let nextDay = nextWeek.getDate().toString();
  216. if (nextMonth.length === 1) {
  217. nextMonth = '0' + nextMonth;
  218. }
  219. if (nextDay.length === 1) {
  220. nextDay = '0' + nextDay;
  221. }
  222. // 周视图结束日期也仅在跨年时显示年份
  223. let nextStr = showYear ? nextWeekYear + '-' + nextMonth + '-' + nextDay : nextMonth + '-' + nextDay;
  224. str += ' - ' + nextStr;
  225. }
  226. return str;
  227. }
  228. // 检查时间戳数组是否跨年
  229. export function isDataCrossYear(timestamps) {
  230. if (!timestamps || timestamps.length === 0) return false;
  231. const years = new Set(timestamps.map(ts => new Date(ts * 1000).getFullYear()));
  232. return years.size > 1;
  233. }
  234. export function downloadTextAsFile(text, filename) {
  235. let blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
  236. let url = URL.createObjectURL(blob);
  237. let a = document.createElement('a');
  238. a.href = url;
  239. a.download = filename;
  240. a.click();
  241. }
  242. export const verifyJSON = (str) => {
  243. try {
  244. JSON.parse(str);
  245. } catch (e) {
  246. return false;
  247. }
  248. return true;
  249. };
  250. export function verifyJSONPromise(value) {
  251. try {
  252. JSON.parse(value);
  253. return Promise.resolve();
  254. } catch (e) {
  255. return Promise.reject('不是合法的 JSON 字符串');
  256. }
  257. }
  258. export function shouldShowPrompt(id) {
  259. let prompt = localStorage.getItem(`prompt-${id}`);
  260. return !prompt;
  261. }
  262. export function setPromptShown(id) {
  263. localStorage.setItem(`prompt-${id}`, 'true');
  264. }
  265. /**
  266. * 比较两个对象的属性,找出有变化的属性,并返回包含变化属性信息的数组
  267. * @param {Object} oldObject - 旧对象
  268. * @param {Object} newObject - 新对象
  269. * @return {Array} 包含变化属性信息的数组,每个元素是一个对象,包含 key, oldValue 和 newValue
  270. */
  271. export function compareObjects(oldObject, newObject) {
  272. const changedProperties = [];
  273. // 比较两个对象的属性
  274. for (const key in oldObject) {
  275. if (oldObject.hasOwnProperty(key) && newObject.hasOwnProperty(key)) {
  276. if (oldObject[key] !== newObject[key]) {
  277. changedProperties.push({
  278. key: key,
  279. oldValue: oldObject[key],
  280. newValue: newObject[key],
  281. });
  282. }
  283. }
  284. }
  285. return changedProperties;
  286. }
  287. // playground message
  288. // 生成唯一ID
  289. let messageId = 4;
  290. export const generateMessageId = () => `${messageId++}`;
  291. // 提取消息中的文本内容
  292. export const getTextContent = (message) => {
  293. if (!message || !message.content) return '';
  294. if (Array.isArray(message.content)) {
  295. const textContent = message.content.find((item) => item.type === 'text');
  296. return textContent?.text || '';
  297. }
  298. return typeof message.content === 'string' ? message.content : '';
  299. };
  300. // 处理 think 标签
  301. export const processThinkTags = (content, reasoningContent = '') => {
  302. if (!content || !content.includes('<think>')) {
  303. return { content, reasoningContent };
  304. }
  305. const thoughts = [];
  306. const replyParts = [];
  307. let lastIndex = 0;
  308. let match;
  309. THINK_TAG_REGEX.lastIndex = 0;
  310. while ((match = THINK_TAG_REGEX.exec(content)) !== null) {
  311. replyParts.push(content.substring(lastIndex, match.index));
  312. thoughts.push(match[1]);
  313. lastIndex = match.index + match[0].length;
  314. }
  315. replyParts.push(content.substring(lastIndex));
  316. const processedContent = replyParts
  317. .join('')
  318. .replace(/<\/?think>/g, '')
  319. .trim();
  320. const thoughtsStr = thoughts.join('\n\n---\n\n');
  321. const processedReasoningContent =
  322. reasoningContent && thoughtsStr
  323. ? `${reasoningContent}\n\n---\n\n${thoughtsStr}`
  324. : reasoningContent || thoughtsStr;
  325. return {
  326. content: processedContent,
  327. reasoningContent: processedReasoningContent,
  328. };
  329. };
  330. // 处理未完成的 think 标签
  331. export const processIncompleteThinkTags = (content, reasoningContent = '') => {
  332. if (!content) return { content: '', reasoningContent };
  333. const lastOpenThinkIndex = content.lastIndexOf('<think>');
  334. if (lastOpenThinkIndex === -1) {
  335. return processThinkTags(content, reasoningContent);
  336. }
  337. const fragmentAfterLastOpen = content.substring(lastOpenThinkIndex);
  338. if (!fragmentAfterLastOpen.includes('</think>')) {
  339. const unclosedThought = fragmentAfterLastOpen
  340. .substring('<think>'.length)
  341. .trim();
  342. const cleanContent = content.substring(0, lastOpenThinkIndex);
  343. const processedReasoningContent = unclosedThought
  344. ? reasoningContent
  345. ? `${reasoningContent}\n\n---\n\n${unclosedThought}`
  346. : unclosedThought
  347. : reasoningContent;
  348. return processThinkTags(cleanContent, processedReasoningContent);
  349. }
  350. return processThinkTags(content, reasoningContent);
  351. };
  352. // 构建消息内容(包含图片)
  353. export const buildMessageContent = (
  354. textContent,
  355. imageUrls = [],
  356. imageEnabled = false,
  357. ) => {
  358. if (!textContent && (!imageUrls || imageUrls.length === 0)) {
  359. return '';
  360. }
  361. const validImageUrls = imageUrls.filter((url) => url && url.trim() !== '');
  362. if (imageEnabled && validImageUrls.length > 0) {
  363. return [
  364. { type: 'text', text: textContent || '' },
  365. ...validImageUrls.map((url) => ({
  366. type: 'image_url',
  367. image_url: { url: url.trim() },
  368. })),
  369. ];
  370. }
  371. return textContent || '';
  372. };
  373. // 创建新消息
  374. export const createMessage = (role, content, options = {}) => ({
  375. role,
  376. content,
  377. createAt: Date.now(),
  378. id: generateMessageId(),
  379. ...options,
  380. });
  381. // 创建加载中的助手消息
  382. export const createLoadingAssistantMessage = () =>
  383. createMessage(MESSAGE_ROLES.ASSISTANT, '', {
  384. reasoningContent: '',
  385. isReasoningExpanded: true,
  386. isThinkingComplete: false,
  387. hasAutoCollapsed: false,
  388. status: 'loading',
  389. });
  390. // 检查消息是否包含图片
  391. export const hasImageContent = (message) => {
  392. return (
  393. message &&
  394. Array.isArray(message.content) &&
  395. message.content.some((item) => item.type === 'image_url')
  396. );
  397. };
  398. // 格式化消息用于API请求
  399. export const formatMessageForAPI = (message) => {
  400. if (!message) return null;
  401. return {
  402. role: message.role,
  403. content: message.content,
  404. };
  405. };
  406. // 验证消息是否有效
  407. export const isValidMessage = (message) => {
  408. return message && message.role && (message.content || message.content === '');
  409. };
  410. // 获取最后一条用户消息
  411. export const getLastUserMessage = (messages) => {
  412. if (!Array.isArray(messages)) return null;
  413. for (let i = messages.length - 1; i >= 0; i--) {
  414. if (messages[i].role === MESSAGE_ROLES.USER) {
  415. return messages[i];
  416. }
  417. }
  418. return null;
  419. };
  420. // 获取最后一条助手消息
  421. export const getLastAssistantMessage = (messages) => {
  422. if (!Array.isArray(messages)) return null;
  423. for (let i = messages.length - 1; i >= 0; i--) {
  424. if (messages[i].role === MESSAGE_ROLES.ASSISTANT) {
  425. return messages[i];
  426. }
  427. }
  428. return null;
  429. };
  430. // 计算相对时间(几天前、几小时前等)
  431. export const getRelativeTime = (publishDate) => {
  432. if (!publishDate) return '';
  433. const now = new Date();
  434. const pubDate = new Date(publishDate);
  435. // 如果日期无效,返回原始字符串
  436. if (isNaN(pubDate.getTime())) return publishDate;
  437. const diffMs = now.getTime() - pubDate.getTime();
  438. const diffSeconds = Math.floor(diffMs / 1000);
  439. const diffMinutes = Math.floor(diffSeconds / 60);
  440. const diffHours = Math.floor(diffMinutes / 60);
  441. const diffDays = Math.floor(diffHours / 24);
  442. const diffWeeks = Math.floor(diffDays / 7);
  443. const diffMonths = Math.floor(diffDays / 30);
  444. const diffYears = Math.floor(diffDays / 365);
  445. // 如果是未来时间,显示具体日期
  446. if (diffMs < 0) {
  447. return formatDateString(pubDate);
  448. }
  449. // 根据时间差返回相应的描述
  450. if (diffSeconds < 60) {
  451. return '刚刚';
  452. } else if (diffMinutes < 60) {
  453. return `${diffMinutes} 分钟前`;
  454. } else if (diffHours < 24) {
  455. return `${diffHours} 小时前`;
  456. } else if (diffDays < 7) {
  457. return `${diffDays} 天前`;
  458. } else if (diffWeeks < 4) {
  459. return `${diffWeeks} 周前`;
  460. } else if (diffMonths < 12) {
  461. return `${diffMonths} 个月前`;
  462. } else if (diffYears < 2) {
  463. return '1 年前';
  464. } else {
  465. // 超过2年显示具体日期
  466. return formatDateString(pubDate);
  467. }
  468. };
  469. // 格式化日期字符串
  470. export const formatDateString = (date) => {
  471. const year = date.getFullYear();
  472. const month = String(date.getMonth() + 1).padStart(2, '0');
  473. const day = String(date.getDate()).padStart(2, '0');
  474. return `${year}-${month}-${day}`;
  475. };
  476. // 格式化日期时间字符串(包含时间)
  477. export const formatDateTimeString = (date) => {
  478. const year = date.getFullYear();
  479. const month = String(date.getMonth() + 1).padStart(2, '0');
  480. const day = String(date.getDate()).padStart(2, '0');
  481. const hours = String(date.getHours()).padStart(2, '0');
  482. const minutes = String(date.getMinutes()).padStart(2, '0');
  483. return `${year}-${month}-${day} ${hours}:${minutes}`;
  484. };
  485. function readTableCompactModes() {
  486. try {
  487. const json = localStorage.getItem(TABLE_COMPACT_MODES_KEY);
  488. return json ? JSON.parse(json) : {};
  489. } catch {
  490. return {};
  491. }
  492. }
  493. function writeTableCompactModes(modes) {
  494. try {
  495. localStorage.setItem(TABLE_COMPACT_MODES_KEY, JSON.stringify(modes));
  496. } catch {
  497. // ignore
  498. }
  499. }
  500. export function getTableCompactMode(tableKey = 'global') {
  501. const modes = readTableCompactModes();
  502. return !!modes[tableKey];
  503. }
  504. export function setTableCompactMode(compact, tableKey = 'global') {
  505. const modes = readTableCompactModes();
  506. modes[tableKey] = compact;
  507. writeTableCompactModes(modes);
  508. }
  509. // -------------------------------
  510. // Select 组件统一过滤逻辑
  511. // 使用方式: <Select filter={selectFilter} ... />
  512. // 统一的 Select 搜索过滤逻辑 -- 支持同时匹配 option.value 与 option.label
  513. export const selectFilter = (input, option) => {
  514. if (!input) return true;
  515. const keyword = input.trim().toLowerCase();
  516. const valueText = (option?.value ?? '').toString().toLowerCase();
  517. const labelText = (option?.label ?? '').toString().toLowerCase();
  518. return valueText.includes(keyword) || labelText.includes(keyword);
  519. };
  520. // -------------------------------
  521. // 模型定价计算工具函数
  522. export const calculateModelPrice = ({
  523. record,
  524. selectedGroup,
  525. groupRatio,
  526. tokenUnit,
  527. displayPrice,
  528. currency,
  529. precision = 4,
  530. }) => {
  531. // 1. 选择实际使用的分组
  532. let usedGroup = selectedGroup;
  533. let usedGroupRatio = groupRatio[selectedGroup];
  534. if (selectedGroup === 'all' || usedGroupRatio === undefined) {
  535. // 在模型可用分组中选择倍率最小的分组,若无则使用 1
  536. let minRatio = Number.POSITIVE_INFINITY;
  537. if (
  538. Array.isArray(record.enable_groups) &&
  539. record.enable_groups.length > 0
  540. ) {
  541. record.enable_groups.forEach((g) => {
  542. const r = groupRatio[g];
  543. if (r !== undefined && r < minRatio) {
  544. minRatio = r;
  545. usedGroup = g;
  546. usedGroupRatio = r;
  547. }
  548. });
  549. }
  550. // 如果找不到合适分组倍率,回退为 1
  551. if (usedGroupRatio === undefined) {
  552. usedGroupRatio = 1;
  553. }
  554. }
  555. // 2. 根据计费类型计算价格
  556. if (record.quota_type === 0) {
  557. // 按量计费
  558. const inputRatioPriceUSD = record.model_ratio * 2 * usedGroupRatio;
  559. const completionRatioPriceUSD =
  560. record.model_ratio * record.completion_ratio * 2 * usedGroupRatio;
  561. const unitDivisor = tokenUnit === 'K' ? 1000 : 1;
  562. const unitLabel = tokenUnit === 'K' ? 'K' : 'M';
  563. const rawDisplayInput = displayPrice(inputRatioPriceUSD);
  564. const rawDisplayCompletion = displayPrice(completionRatioPriceUSD);
  565. const numInput =
  566. parseFloat(rawDisplayInput.replace(/[^0-9.]/g, '')) / unitDivisor;
  567. const numCompletion =
  568. parseFloat(rawDisplayCompletion.replace(/[^0-9.]/g, '')) / unitDivisor;
  569. let symbol = '$';
  570. if (currency === 'CNY') {
  571. symbol = '¥';
  572. } else if (currency === 'CUSTOM') {
  573. try {
  574. const statusStr = localStorage.getItem('status');
  575. if (statusStr) {
  576. const s = JSON.parse(statusStr);
  577. symbol = s?.custom_currency_symbol || '¤';
  578. } else {
  579. symbol = '¤';
  580. }
  581. } catch (e) {
  582. symbol = '¤';
  583. }
  584. }
  585. return {
  586. inputPrice: `${symbol}${numInput.toFixed(precision)}`,
  587. completionPrice: `${symbol}${numCompletion.toFixed(precision)}`,
  588. unitLabel,
  589. isPerToken: true,
  590. usedGroup,
  591. usedGroupRatio,
  592. };
  593. }
  594. if (record.quota_type === 1) {
  595. // 按次计费
  596. const priceUSD = parseFloat(record.model_price) * usedGroupRatio;
  597. const displayVal = displayPrice(priceUSD);
  598. return {
  599. price: displayVal,
  600. isPerToken: false,
  601. usedGroup,
  602. usedGroupRatio,
  603. };
  604. }
  605. // 未知计费类型,返回占位信息
  606. return {
  607. price: '-',
  608. isPerToken: false,
  609. usedGroup,
  610. usedGroupRatio,
  611. };
  612. };
  613. // 格式化价格信息(用于卡片视图)
  614. export const formatPriceInfo = (priceData, t) => {
  615. if (priceData.isPerToken) {
  616. return (
  617. <>
  618. <span style={{ color: 'var(--semi-color-text-1)' }}>
  619. {t('输入')} {priceData.inputPrice}/{priceData.unitLabel}
  620. </span>
  621. <span style={{ color: 'var(--semi-color-text-1)' }}>
  622. {t('输出')} {priceData.completionPrice}/{priceData.unitLabel}
  623. </span>
  624. </>
  625. );
  626. }
  627. return (
  628. <>
  629. <span style={{ color: 'var(--semi-color-text-1)' }}>
  630. {t('模型价格')} {priceData.price}
  631. </span>
  632. </>
  633. );
  634. };
  635. // -------------------------------
  636. // CardPro 分页配置函数
  637. // 用于创建 CardPro 的 paginationArea 配置
  638. export const createCardProPagination = ({
  639. currentPage,
  640. pageSize,
  641. total,
  642. onPageChange,
  643. onPageSizeChange,
  644. isMobile = false,
  645. pageSizeOpts = [10, 20, 50, 100],
  646. showSizeChanger = true,
  647. t = (key) => key,
  648. }) => {
  649. if (!total || total <= 0) return null;
  650. const start = (currentPage - 1) * pageSize + 1;
  651. const end = Math.min(currentPage * pageSize, total);
  652. const totalText = `${t('显示第')} ${start} ${t('条 - 第')} ${end} ${t('条,共')} ${total} ${t('条')}`;
  653. return (
  654. <>
  655. {/* 桌面端左侧总数信息 */}
  656. {!isMobile && (
  657. <span
  658. className='text-sm select-none'
  659. style={{ color: 'var(--semi-color-text-2)' }}
  660. >
  661. {totalText}
  662. </span>
  663. )}
  664. {/* 右侧分页控件 */}
  665. <Pagination
  666. currentPage={currentPage}
  667. pageSize={pageSize}
  668. total={total}
  669. pageSizeOpts={pageSizeOpts}
  670. showSizeChanger={showSizeChanger}
  671. onPageSizeChange={onPageSizeChange}
  672. onPageChange={onPageChange}
  673. size={isMobile ? 'small' : 'default'}
  674. showQuickJumper={isMobile}
  675. showTotal
  676. />
  677. </>
  678. );
  679. };
  680. // 模型定价筛选条件默认值
  681. const DEFAULT_PRICING_FILTERS = {
  682. search: '',
  683. showWithRecharge: false,
  684. currency: 'USD',
  685. showRatio: false,
  686. viewMode: 'card',
  687. tokenUnit: 'M',
  688. filterGroup: 'all',
  689. filterQuotaType: 'all',
  690. filterEndpointType: 'all',
  691. filterVendor: 'all',
  692. filterTag: 'all',
  693. currentPage: 1,
  694. };
  695. // 重置模型定价筛选条件
  696. export const resetPricingFilters = ({
  697. handleChange,
  698. setShowWithRecharge,
  699. setCurrency,
  700. setShowRatio,
  701. setViewMode,
  702. setFilterGroup,
  703. setFilterQuotaType,
  704. setFilterEndpointType,
  705. setFilterVendor,
  706. setFilterTag,
  707. setCurrentPage,
  708. setTokenUnit,
  709. }) => {
  710. handleChange?.(DEFAULT_PRICING_FILTERS.search);
  711. setShowWithRecharge?.(DEFAULT_PRICING_FILTERS.showWithRecharge);
  712. setCurrency?.(DEFAULT_PRICING_FILTERS.currency);
  713. setShowRatio?.(DEFAULT_PRICING_FILTERS.showRatio);
  714. setViewMode?.(DEFAULT_PRICING_FILTERS.viewMode);
  715. setTokenUnit?.(DEFAULT_PRICING_FILTERS.tokenUnit);
  716. setFilterGroup?.(DEFAULT_PRICING_FILTERS.filterGroup);
  717. setFilterQuotaType?.(DEFAULT_PRICING_FILTERS.filterQuotaType);
  718. setFilterEndpointType?.(DEFAULT_PRICING_FILTERS.filterEndpointType);
  719. setFilterVendor?.(DEFAULT_PRICING_FILTERS.filterVendor);
  720. setFilterTag?.(DEFAULT_PRICING_FILTERS.filterTag);
  721. setCurrentPage?.(DEFAULT_PRICING_FILTERS.currentPage);
  722. };