9145ed5834
统一各中心表格的分页样式和切换行为,保留密钥筛选条件与兑换码搜索分页。
1127 lines
36 KiB
React
1127 lines
36 KiB
React
import { Toast, Pagination } from '@/components/ui';
|
||
import { toastConstants } from '../constants';
|
||
import React from 'react';
|
||
import i18next from 'i18next';
|
||
import {
|
||
THINK_TAG_REGEX,
|
||
MESSAGE_ROLES,
|
||
} from '../constants/playground.constants';
|
||
import { MOBILE_BREAKPOINT } from '../hooks/common/useIsMobile';
|
||
// 官方价折扣计算(纯函数):管理端与市场页共用
|
||
import { buildOfficialComparison, formatDiscountLabel } from './officialPrice';
|
||
import { clearUserData, getUserData, isSafePostLoginRedirect } from './data';
|
||
|
||
const HTMLToastContent = ({ htmlContent }) => {
|
||
return <div dangerouslySetInnerHTML={{ __html: htmlContent }} />;
|
||
};
|
||
export default HTMLToastContent;
|
||
export function isAdmin() {
|
||
let user = getUserData();
|
||
if (!user) return false;
|
||
return user.role >= 10;
|
||
}
|
||
|
||
export function isRoot() {
|
||
let user = getUserData();
|
||
if (!user) return false;
|
||
return user.role >= 100;
|
||
}
|
||
|
||
// 优先级:localStorage(/api/status 已落地)> window.__WL_BRAND__(index.html 内联脚本写入,
|
||
// 反映后端启动注入的系统配置)> 终极兜底 'Weelinking' / '/logo.svg'(完全未配置部署)。
|
||
// 关键场景:冷启动 + localStorage 还没被 /api/status 灌满的窗口期,
|
||
// 登录页、注册页、密码重置页、顶栏、聊天头像 5 处都通过本函数读品牌;
|
||
// 不接 window 这一层就会闪一下 'Weelinking' + 羽毛 logo,违背白牌。
|
||
// 字面串 'undefined' / 'null' 也视为空(来源:helpers/data.js 把 undefined 字段 setItem 时
|
||
// 会被 String() 转成字面串),否则 <img src="undefined"> 会变成破图。
|
||
const isBlankLS = (v) => !v || v === 'undefined' || v === 'null';
|
||
|
||
// localStorage 在 Safari 隐私模式 / 部分企业 IT 锁定下 getItem 会抛 SecurityError。
|
||
// 单独包一层防御,让调用方拿到 null 走后续 window/终极兜底,而不是直接掀掉组件。
|
||
function lsGet(key) {
|
||
try {
|
||
return localStorage.getItem(key);
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
export function getSystemName() {
|
||
let system_name = lsGet('system_name');
|
||
if (isBlankLS(system_name)) {
|
||
system_name =
|
||
(typeof window !== 'undefined' &&
|
||
window.__WL_BRAND__ &&
|
||
window.__WL_BRAND__.name) ||
|
||
'';
|
||
}
|
||
if (!system_name) return 'Weelinking';
|
||
return system_name;
|
||
}
|
||
|
||
export function getLogo() {
|
||
let logo = lsGet('logo');
|
||
if (isBlankLS(logo)) {
|
||
logo =
|
||
(typeof window !== 'undefined' &&
|
||
window.__WL_BRAND__ &&
|
||
window.__WL_BRAND__.logo) ||
|
||
'';
|
||
}
|
||
if (!logo) return '/logo.svg';
|
||
return logo;
|
||
}
|
||
|
||
export function getUserIdFromLocalStorage() {
|
||
let user = getUserData();
|
||
if (!user) return -1;
|
||
return user.id;
|
||
}
|
||
|
||
export { copyText as copy } from './clipboard';
|
||
|
||
// isMobile 函数已移除,请改用 useIsMobile Hook
|
||
|
||
let showErrorOptions = { autoClose: toastConstants.ERROR_TIMEOUT };
|
||
let showSuccessOptions = { autoClose: toastConstants.SUCCESS_TIMEOUT };
|
||
let showInfoOptions = { autoClose: toastConstants.INFO_TIMEOUT };
|
||
let showNoticeOptions = { autoClose: false };
|
||
|
||
const isMobileScreen = window.matchMedia(
|
||
`(max-width: ${MOBILE_BREAKPOINT - 1}px)`,
|
||
).matches;
|
||
if (isMobileScreen) {
|
||
showErrorOptions.position = 'top-center';
|
||
// showErrorOptions.transition = 'flip';
|
||
|
||
showSuccessOptions.position = 'top-center';
|
||
// showSuccessOptions.transition = 'flip';
|
||
|
||
showInfoOptions.position = 'top-center';
|
||
// showInfoOptions.transition = 'flip';
|
||
|
||
showNoticeOptions.position = 'top-center';
|
||
// showNoticeOptions.transition = 'flip';
|
||
}
|
||
|
||
let redirectingToLogin = false;
|
||
const reportedRequestErrors = new WeakSet();
|
||
|
||
export function redirectToExpiredLogin() {
|
||
if (redirectingToLogin) return;
|
||
redirectingToLogin = true;
|
||
clearUserData();
|
||
const { pathname, search, hash } = window.location;
|
||
const currentPath = `${pathname}${search}${hash}`;
|
||
const redirect = isSafePostLoginRedirect(currentPath)
|
||
? `&redirect=${encodeURIComponent(currentPath)}`
|
||
: '';
|
||
window.location.replace(`/org/login?expired=true${redirect}`);
|
||
}
|
||
|
||
export function showError(error, { redirectOnUnauthorized = true } = {}) {
|
||
if (
|
||
error?.code === 'ERR_CANCELED' ||
|
||
error === 'canceled' ||
|
||
(redirectingToLogin && error === 'Request failed with status code 401')
|
||
)
|
||
return;
|
||
|
||
if (error?.isAxiosError || error?.name === 'AxiosError') {
|
||
if (reportedRequestErrors.has(error)) return;
|
||
reportedRequestErrors.add(error);
|
||
|
||
const status = error.response?.status;
|
||
if (status === 401 && redirectOnUnauthorized) {
|
||
redirectToExpiredLogin();
|
||
return;
|
||
}
|
||
if (status === 405) {
|
||
Toast.info({
|
||
key: 'http-error:405',
|
||
content: i18next.t('本站仅作演示之用,无服务端!'),
|
||
});
|
||
return;
|
||
}
|
||
let content;
|
||
if (!error.response) {
|
||
content = i18next.t('错误:网络请求失败,请检查网络连接');
|
||
} else if (status === 429) {
|
||
content = i18next.t('错误:请求次数过多,请稍后再试!');
|
||
} else if (status === 500) {
|
||
content = i18next.t('错误:服务器内部错误,请联系管理员!');
|
||
} else {
|
||
content = i18next.t('错误:{{message}}', {
|
||
message: error.response.data?.message || error.message,
|
||
});
|
||
}
|
||
Toast.error({ key: `http-error:${content}`, content });
|
||
return;
|
||
}
|
||
console.error(error);
|
||
Toast.error(
|
||
i18next.t('错误:{{message}}', { message: error?.message || error }),
|
||
);
|
||
}
|
||
|
||
export function showWarning(message) {
|
||
Toast.warning(message);
|
||
}
|
||
|
||
export function showSuccess(message) {
|
||
Toast.success(message);
|
||
}
|
||
|
||
export function showInfo(message) {
|
||
Toast.info(message);
|
||
}
|
||
|
||
export function showNotice(message, isHTML = false) {
|
||
if (isHTML) {
|
||
Toast.info({
|
||
content: <HTMLToastContent htmlContent={message} />,
|
||
duration: 0,
|
||
});
|
||
} else {
|
||
Toast.info(message);
|
||
}
|
||
}
|
||
|
||
export function removeTrailingSlash(url) {
|
||
if (!url) return '';
|
||
if (url.endsWith('/')) {
|
||
return url.slice(0, -1);
|
||
} else {
|
||
return url;
|
||
}
|
||
}
|
||
|
||
export function getTodayStartTimestamp() {
|
||
var now = new Date();
|
||
now.setHours(0, 0, 0, 0);
|
||
return Math.floor(now.getTime() / 1000);
|
||
}
|
||
|
||
export function timestamp2string(timestamp) {
|
||
let date = new Date(timestamp * 1000);
|
||
let year = date.getFullYear().toString();
|
||
let month = (date.getMonth() + 1).toString();
|
||
let day = date.getDate().toString();
|
||
let hour = date.getHours().toString();
|
||
let minute = date.getMinutes().toString();
|
||
let second = date.getSeconds().toString();
|
||
if (month.length === 1) {
|
||
month = '0' + month;
|
||
}
|
||
if (day.length === 1) {
|
||
day = '0' + day;
|
||
}
|
||
if (hour.length === 1) {
|
||
hour = '0' + hour;
|
||
}
|
||
if (minute.length === 1) {
|
||
minute = '0' + minute;
|
||
}
|
||
if (second.length === 1) {
|
||
second = '0' + second;
|
||
}
|
||
return (
|
||
year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
|
||
);
|
||
}
|
||
|
||
export function timestamp2string1(timestamp, dataExportDefaultTime = 'hour') {
|
||
let date = new Date(timestamp * 1000);
|
||
// let year = date.getFullYear().toString();
|
||
let month = (date.getMonth() + 1).toString();
|
||
let day = date.getDate().toString();
|
||
let hour = date.getHours().toString();
|
||
if (day === '24') {
|
||
console.log('timestamp', timestamp);
|
||
}
|
||
if (month.length === 1) {
|
||
month = '0' + month;
|
||
}
|
||
if (day.length === 1) {
|
||
day = '0' + day;
|
||
}
|
||
if (hour.length === 1) {
|
||
hour = '0' + hour;
|
||
}
|
||
let str = month + '-' + day;
|
||
if (dataExportDefaultTime === 'hour') {
|
||
str += ' ' + hour + ':00';
|
||
} else if (dataExportDefaultTime === 'week') {
|
||
let nextWeek = new Date(timestamp * 1000 + 6 * 24 * 60 * 60 * 1000);
|
||
let nextMonth = (nextWeek.getMonth() + 1).toString();
|
||
let nextDay = nextWeek.getDate().toString();
|
||
if (nextMonth.length === 1) {
|
||
nextMonth = '0' + nextMonth;
|
||
}
|
||
if (nextDay.length === 1) {
|
||
nextDay = '0' + nextDay;
|
||
}
|
||
str += ' - ' + nextMonth + '-' + nextDay;
|
||
}
|
||
return str;
|
||
}
|
||
|
||
export function downloadTextAsFile(text, filename) {
|
||
let blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
|
||
let url = URL.createObjectURL(blob);
|
||
let a = document.createElement('a');
|
||
a.href = url;
|
||
a.download = filename;
|
||
a.click();
|
||
}
|
||
|
||
export const verifyJSON = (str) => {
|
||
try {
|
||
JSON.parse(str);
|
||
} catch (e) {
|
||
return false;
|
||
}
|
||
return true;
|
||
};
|
||
|
||
/**
|
||
* 比较两个对象的属性,找出有变化的属性,并返回包含变化属性信息的数组
|
||
* @param {Object} oldObject - 旧对象
|
||
* @param {Object} newObject - 新对象
|
||
* @return {Array} 包含变化属性信息的数组,每个元素是一个对象,包含 key, oldValue 和 newValue
|
||
*/
|
||
export function compareObjects(oldObject, newObject) {
|
||
const changedProperties = [];
|
||
|
||
// 比较两个对象的属性
|
||
for (const key in oldObject) {
|
||
if (oldObject.hasOwnProperty(key) && newObject.hasOwnProperty(key)) {
|
||
if (oldObject[key] !== newObject[key]) {
|
||
changedProperties.push({
|
||
key: key,
|
||
oldValue: oldObject[key],
|
||
newValue: newObject[key],
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
return changedProperties;
|
||
}
|
||
|
||
// playground message
|
||
|
||
// 生成唯一ID
|
||
let messageId = 4;
|
||
export const generateMessageId = () => `${messageId++}`;
|
||
|
||
// 提取消息中的文本内容
|
||
export const getTextContent = (message) => {
|
||
if (!message || !message.content) return '';
|
||
|
||
if (Array.isArray(message.content)) {
|
||
const textContent = message.content.find((item) => item.type === 'text');
|
||
return textContent?.text || '';
|
||
}
|
||
return typeof message.content === 'string' ? message.content : '';
|
||
};
|
||
|
||
// 处理 think 标签
|
||
export const processThinkTags = (content, reasoningContent = '') => {
|
||
if (!content || !content.includes('<think>')) {
|
||
return { content, reasoningContent };
|
||
}
|
||
|
||
const thoughts = [];
|
||
const replyParts = [];
|
||
let lastIndex = 0;
|
||
let match;
|
||
|
||
THINK_TAG_REGEX.lastIndex = 0;
|
||
while ((match = THINK_TAG_REGEX.exec(content)) !== null) {
|
||
replyParts.push(content.substring(lastIndex, match.index));
|
||
thoughts.push(match[1]);
|
||
lastIndex = match.index + match[0].length;
|
||
}
|
||
replyParts.push(content.substring(lastIndex));
|
||
|
||
const processedContent = replyParts
|
||
.join('')
|
||
.replace(/<\/?think>/g, '')
|
||
.trim();
|
||
const thoughtsStr = thoughts.join('\n\n---\n\n');
|
||
const processedReasoningContent =
|
||
reasoningContent && thoughtsStr
|
||
? `${reasoningContent}\n\n---\n\n${thoughtsStr}`
|
||
: reasoningContent || thoughtsStr;
|
||
|
||
return {
|
||
content: processedContent,
|
||
reasoningContent: processedReasoningContent,
|
||
};
|
||
};
|
||
|
||
// 处理未完成的 think 标签
|
||
export const processIncompleteThinkTags = (content, reasoningContent = '') => {
|
||
if (!content) return { content: '', reasoningContent };
|
||
|
||
const lastOpenThinkIndex = content.lastIndexOf('<think>');
|
||
if (lastOpenThinkIndex === -1) {
|
||
return processThinkTags(content, reasoningContent);
|
||
}
|
||
|
||
const fragmentAfterLastOpen = content.substring(lastOpenThinkIndex);
|
||
if (!fragmentAfterLastOpen.includes('</think>')) {
|
||
const unclosedThought = fragmentAfterLastOpen
|
||
.substring('<think>'.length)
|
||
.trim();
|
||
const cleanContent = content.substring(0, lastOpenThinkIndex);
|
||
const processedReasoningContent = unclosedThought
|
||
? reasoningContent
|
||
? `${reasoningContent}\n\n---\n\n${unclosedThought}`
|
||
: unclosedThought
|
||
: reasoningContent;
|
||
|
||
return processThinkTags(cleanContent, processedReasoningContent);
|
||
}
|
||
|
||
return processThinkTags(content, reasoningContent);
|
||
};
|
||
|
||
// 构建消息内容(包含图片)
|
||
export const buildMessageContent = (
|
||
textContent,
|
||
imageUrls = [],
|
||
imageEnabled = false,
|
||
uploadedFiles = [],
|
||
) => {
|
||
if (
|
||
!textContent &&
|
||
(!imageUrls || imageUrls.length === 0) &&
|
||
uploadedFiles.length === 0
|
||
) {
|
||
return '';
|
||
}
|
||
|
||
const validImageUrls = imageUrls.filter((url) => url && url.trim() !== '');
|
||
const hasMultiModal =
|
||
(imageEnabled && validImageUrls.length > 0) || uploadedFiles.length > 0;
|
||
|
||
if (hasMultiModal) {
|
||
// OpenAI / Claude 等多模态接口对 {type:'text', text:''} 的空文本 part 容错不一致,
|
||
// 部分会直接 400。仅在确有文本时才 push 文本 part;纯附件场景就是纯多媒体数组。
|
||
const parts = [];
|
||
const trimmedText = (textContent || '').trim();
|
||
if (trimmedText !== '') {
|
||
parts.push({ type: 'text', text: textContent });
|
||
}
|
||
|
||
if (imageEnabled && validImageUrls.length > 0) {
|
||
parts.push(
|
||
...validImageUrls.map((url) => ({
|
||
type: 'image_url',
|
||
image_url: { url: url.trim() },
|
||
})),
|
||
);
|
||
}
|
||
|
||
for (const file of uploadedFiles) {
|
||
if (file.type === 'image') {
|
||
parts.push({
|
||
type: 'image_url',
|
||
image_url: { url: file.url },
|
||
});
|
||
} else {
|
||
parts.push({
|
||
type: 'file',
|
||
file: {
|
||
filename: file.name,
|
||
file_name: file.name,
|
||
file_data: file.url,
|
||
},
|
||
});
|
||
}
|
||
}
|
||
|
||
return parts;
|
||
}
|
||
|
||
return textContent || '';
|
||
};
|
||
|
||
// 把毫秒时间戳格式化为"几分钟前"风格的相对时间,超过 7 天回落到日期。
|
||
// 用于消息时间戳:避免一连串绝对时间堆在长会话里挤眼,hover 时再看具体时刻就够了。
|
||
export const formatRelativeTime = (msTimestamp, t) => {
|
||
if (!msTimestamp) return '';
|
||
const now = Date.now();
|
||
const diff = now - msTimestamp;
|
||
if (diff < 0) return t('刚刚');
|
||
const sec = Math.floor(diff / 1000);
|
||
if (sec < 30) return t('刚刚');
|
||
if (sec < 60) return t('{{n}} 秒前', { n: sec });
|
||
const min = Math.floor(sec / 60);
|
||
if (min < 60) return t('{{n}} 分钟前', { n: min });
|
||
const hour = Math.floor(min / 60);
|
||
if (hour < 24) return t('{{n}} 小时前', { n: hour });
|
||
const day = Math.floor(hour / 24);
|
||
if (day < 7) return t('{{n}} 天前', { n: day });
|
||
// 超过一周直接显示绝对日期,避免"30天前"这种含糊
|
||
const d = new Date(msTimestamp);
|
||
const pad = (n) => ('0' + n).slice(-2);
|
||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
||
};
|
||
|
||
// 把字节数格式化为人类可读字符串:"1.2 MB", "456 KB", "789 B"
|
||
// decimals 默认 1 位小数,足够表达体验中心场景;0 字节直接返回 '0 B'
|
||
export const formatBytes = (bytes, decimals = 1) => {
|
||
const num = Number(bytes);
|
||
if (!Number.isFinite(num) || num <= 0) return '0 B';
|
||
const k = 1024;
|
||
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||
const i = Math.min(units.length - 1, Math.floor(Math.log(num) / Math.log(k)));
|
||
const value = num / Math.pow(k, i);
|
||
// 小于 1KB 时不带小数;KB 及以上保留指定位数
|
||
const fixed =
|
||
i === 0 ? Math.round(value).toString() : value.toFixed(decimals);
|
||
return `${parseFloat(fixed)} ${units[i]}`;
|
||
};
|
||
|
||
// 创建新消息
|
||
export const createMessage = (role, content, options = {}) => ({
|
||
role,
|
||
content,
|
||
createAt: Date.now(),
|
||
id: generateMessageId(),
|
||
...options,
|
||
});
|
||
|
||
// 创建加载中的助手消息。options 透传扩展字段,常用于:
|
||
// - inWebSearch: 用户开了联网搜索,加载态显示"正在联网搜索…"提示,与单纯 spinner 区分
|
||
// - processingAttachments: 本轮 user 消息附带 N 个文件 → 后端要先 inline base64
|
||
// 再发上游,期间客户端没有任何流,loading 显示"正在处理 N 个附件…"明确告诉用户
|
||
// 系统在做事,不要急着重发
|
||
export const createLoadingAssistantMessage = (options = {}) =>
|
||
createMessage(MESSAGE_ROLES.ASSISTANT, '', {
|
||
reasoningContent: '',
|
||
isReasoningExpanded: true,
|
||
isThinkingComplete: false,
|
||
hasAutoCollapsed: false,
|
||
status: 'loading',
|
||
...options,
|
||
});
|
||
|
||
// 格式化消息用于API请求
|
||
export const formatMessageForAPI = (message) => {
|
||
if (!message) return null;
|
||
|
||
return {
|
||
role: message.role,
|
||
content: message.content,
|
||
};
|
||
};
|
||
|
||
// 历史消息中的文件/图片附件,从「最后一条 user 消息」之外的所有消息里剥离,
|
||
// 避免每轮把同一份附件重复送给上游模型 — 既省 token,又规避 COS 私有桶预签名 URL 过期。
|
||
// 剥离后在文本里追加短占位符(如 [已发送附件: a.pdf, b.png]),让模型知道历史上有过附件,
|
||
// 避免它回复"你没给我文件"。本函数是纯函数,绝不修改入参,让上层 React.memo 安全工作。
|
||
export const stripHistoryAttachments = (messages) => {
|
||
if (!Array.isArray(messages) || messages.length === 0) return messages;
|
||
|
||
// 倒序找最后一条 user 消息下标 —— 这条要保留完整附件给本轮上游
|
||
let lastUserIdx = -1;
|
||
for (let i = messages.length - 1; i >= 0; i--) {
|
||
if (messages[i]?.role === MESSAGE_ROLES.USER) {
|
||
lastUserIdx = i;
|
||
break;
|
||
}
|
||
}
|
||
if (lastUserIdx < 0) return messages; // 没 user 消息(不太可能),不动
|
||
|
||
// 从 image_url 或 file part 里提取一个可读的展示名
|
||
// image_url 通常只是 URL(UUID 命名 + 长签名串),原始文件名拿不到,统一显示为"图片"
|
||
// 避免占位符里出现一长串无意义 UUID 浪费 token + 误导模型
|
||
const partDisplayName = (p) => {
|
||
if (p?.type === 'file') {
|
||
return p.file?.filename || p.file?.file_name || i18next.t('文件');
|
||
}
|
||
if (p?.type === 'image_url') {
|
||
return i18next.t('图片');
|
||
}
|
||
return '';
|
||
};
|
||
|
||
// 若附件超过 5 个,列前 5 个加「等 N 个」省略 — 防止占位符本身爆 token。
|
||
// 同名附件合并为 "name×N":image_url 全显示为"图片"会出现 "图片, 图片, 图片"
|
||
// 的丑陋重复 + 浪费 token;合并后变 "图片×3",更紧凑且让模型知道总张数。
|
||
const buildPlaceholder = (names) => {
|
||
if (names.length === 0) return '';
|
||
const counts = new Map();
|
||
const order = [];
|
||
for (const n of names) {
|
||
if (!counts.has(n)) order.push(n);
|
||
counts.set(n, (counts.get(n) || 0) + 1);
|
||
}
|
||
const grouped = order.map((n) =>
|
||
counts.get(n) > 1 ? `${n}×${counts.get(n)}` : n,
|
||
);
|
||
if (grouped.length <= 5) {
|
||
return `\n\n${i18next.t('[已发送附件: {{names}}]', {
|
||
names: grouped.join(', '),
|
||
})}`;
|
||
}
|
||
return `\n\n${i18next.t('[已发送附件: {{names}} 等 {{total}} 个]', {
|
||
names: grouped.slice(0, 5).join(', '),
|
||
total: names.length,
|
||
})}`;
|
||
};
|
||
|
||
// 白名单识别"要剥离的附件 part",其余 part(text / 未来可能的 audio / video 等)一律保留,
|
||
// 避免静默丢失未知类型 part —— 即使当前体验中心只用 text/file/image_url,也对得起函数语义。
|
||
const isAttachmentPart = (p) => p?.type === 'file' || p?.type === 'image_url';
|
||
|
||
let mutated = false;
|
||
const next = messages.map((m, idx) => {
|
||
if (idx === lastUserIdx) return m;
|
||
if (!m || !Array.isArray(m.content)) return m;
|
||
|
||
const attachmentNames = [];
|
||
const remaining = [];
|
||
for (const part of m.content) {
|
||
if (isAttachmentPart(part)) {
|
||
attachmentNames.push(partDisplayName(part));
|
||
} else {
|
||
remaining.push(part);
|
||
}
|
||
}
|
||
|
||
if (attachmentNames.length === 0) return m; // 这条没附件,不动
|
||
mutated = true;
|
||
|
||
const placeholder = buildPlaceholder(attachmentNames);
|
||
|
||
// 剩余全是 text part(最常见场景)→ 合并成 string,更广兼容性
|
||
const allText = remaining.every((p) => p?.type === 'text');
|
||
if (allText) {
|
||
const text = remaining
|
||
.map((p) => (typeof p?.text === 'string' ? p.text : ''))
|
||
.filter(Boolean)
|
||
.join('\n');
|
||
return { ...m, content: (text + placeholder).trim() };
|
||
}
|
||
|
||
// 还有非文本 part(理论可能,如 audio)→ 保持 array,把占位符塞进第一个 text part;
|
||
// 没有 text part 就在最前面 unshift 一个,保证模型一定能读到附件信息
|
||
const newContent = remaining.slice();
|
||
const firstTextIdx = newContent.findIndex((p) => p?.type === 'text');
|
||
if (firstTextIdx >= 0) {
|
||
newContent[firstTextIdx] = {
|
||
...newContent[firstTextIdx],
|
||
text: (newContent[firstTextIdx].text || '') + placeholder,
|
||
};
|
||
} else {
|
||
newContent.unshift({ type: 'text', text: placeholder.trim() });
|
||
}
|
||
return { ...m, content: newContent };
|
||
});
|
||
|
||
return mutated ? next : messages;
|
||
};
|
||
|
||
// 验证消息是否有效
|
||
export const isValidMessage = (message) => {
|
||
return message && message.role && (message.content || message.content === '');
|
||
};
|
||
|
||
// 计算相对时间(几天前、几小时前等)
|
||
export const getRelativeTime = (publishDate) => {
|
||
if (!publishDate) return '';
|
||
|
||
const now = new Date();
|
||
const pubDate = new Date(publishDate);
|
||
|
||
// 如果日期无效,返回原始字符串
|
||
if (isNaN(pubDate.getTime())) return publishDate;
|
||
|
||
const diffMs = now.getTime() - pubDate.getTime();
|
||
const diffSeconds = Math.floor(diffMs / 1000);
|
||
const diffMinutes = Math.floor(diffSeconds / 60);
|
||
const diffHours = Math.floor(diffMinutes / 60);
|
||
const diffDays = Math.floor(diffHours / 24);
|
||
const diffWeeks = Math.floor(diffDays / 7);
|
||
const diffMonths = Math.floor(diffDays / 30);
|
||
const diffYears = Math.floor(diffDays / 365);
|
||
|
||
// 如果是未来时间,显示具体日期
|
||
if (diffMs < 0) {
|
||
return formatDateString(pubDate);
|
||
}
|
||
|
||
// 根据时间差返回相应的描述
|
||
if (diffSeconds < 60) {
|
||
return i18next.t('刚刚');
|
||
} else if (diffMinutes < 60) {
|
||
return i18next.t('{{n}} 分钟前', { n: diffMinutes });
|
||
} else if (diffHours < 24) {
|
||
return i18next.t('{{n}} 小时前', { n: diffHours });
|
||
} else if (diffDays < 7) {
|
||
return i18next.t('{{n}} 天前', { n: diffDays });
|
||
} else if (diffWeeks < 4) {
|
||
return i18next.t('{{n}} 周前', { n: diffWeeks });
|
||
} else if (diffMonths < 12) {
|
||
return i18next.t('{{n}} 个月前', { n: diffMonths });
|
||
} else if (diffYears < 2) {
|
||
return i18next.t('{{n}} 年前', { n: 1 });
|
||
} else {
|
||
// 超过2年显示具体日期
|
||
return formatDateString(pubDate);
|
||
}
|
||
};
|
||
|
||
// 格式化日期字符串
|
||
export const formatDateString = (date) => {
|
||
const year = date.getFullYear();
|
||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||
const day = String(date.getDate()).padStart(2, '0');
|
||
return `${year}-${month}-${day}`;
|
||
};
|
||
|
||
// 格式化日期时间字符串(包含时间)
|
||
export const formatDateTimeString = (date) => {
|
||
const year = date.getFullYear();
|
||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||
const day = String(date.getDate()).padStart(2, '0');
|
||
const hours = String(date.getHours()).padStart(2, '0');
|
||
const minutes = String(date.getMinutes()).padStart(2, '0');
|
||
return `${year}-${month}-${day} ${hours}:${minutes}`;
|
||
};
|
||
|
||
export {
|
||
getTableCompactMode,
|
||
setTableCompactMode,
|
||
} from './tableCompactMode.js';
|
||
|
||
// -------------------------------
|
||
// Select 组件统一过滤逻辑
|
||
// 使用方式: <Select filter={selectFilter} ... />
|
||
// 统一的 Select 搜索过滤逻辑 -- 支持同时匹配 option.value 与 option.label
|
||
export const selectFilter = (input, option) => {
|
||
if (!input) return true;
|
||
|
||
const keyword = input.trim().toLowerCase();
|
||
const valueText = (option?.value ?? '').toString().toLowerCase();
|
||
const labelText = (option?.label ?? '').toString().toLowerCase();
|
||
const descriptionText = [option?.description, option?.fullLabel]
|
||
.filter(Boolean)
|
||
.join(' ')
|
||
.toLowerCase();
|
||
|
||
return (
|
||
valueText.includes(keyword) ||
|
||
labelText.includes(keyword) ||
|
||
descriptionText.includes(keyword)
|
||
);
|
||
};
|
||
|
||
export const getCurrencySymbol = () => '¥';
|
||
|
||
// -------------------------------
|
||
// 模型定价计算工具函数
|
||
const hasNumericPriceValue = (value) =>
|
||
value !== undefined &&
|
||
value !== null &&
|
||
value !== '' &&
|
||
Number.isFinite(Number(value));
|
||
|
||
export const calculateModelPrice = ({
|
||
record,
|
||
selectedGroup,
|
||
groupRatio,
|
||
groupModelDiscount = {},
|
||
tokenUnit,
|
||
displayPrice,
|
||
currency,
|
||
precision = 4,
|
||
}) => {
|
||
// 有效倍率 = 分组倍率(已含分组级等级折扣) × 该模型的等级折扣修正系数(四期,替换语义在后端换算好)。
|
||
// groupRatio[g] 未定义时必须返回 undefined 走下方最优分组搜索,不能变成 NaN。
|
||
const effRatio = (g) => {
|
||
const base = groupRatio[g];
|
||
if (base === undefined) return undefined;
|
||
return base * (groupModelDiscount?.[g]?.[record.model_name] ?? 1);
|
||
};
|
||
|
||
// 1. 选择实际使用的分组
|
||
let usedGroup = selectedGroup;
|
||
let usedGroupRatio = effRatio(selectedGroup);
|
||
|
||
if (selectedGroup === 'all' || usedGroupRatio === undefined) {
|
||
// 在模型可用分组中选择倍率最小的分组,若无则使用 1
|
||
// 注意按「有效倍率」比较:模型级折扣可能让基准倍率更高的分组实付更低。
|
||
let minRatio = Number.POSITIVE_INFINITY;
|
||
if (
|
||
Array.isArray(record.enable_groups) &&
|
||
record.enable_groups.length > 0
|
||
) {
|
||
record.enable_groups.forEach((g) => {
|
||
const r = effRatio(g);
|
||
if (r !== undefined && r < minRatio) {
|
||
minRatio = r;
|
||
usedGroup = g;
|
||
usedGroupRatio = r;
|
||
}
|
||
});
|
||
}
|
||
|
||
// 如果找不到合适分组倍率,回退为 1
|
||
if (usedGroupRatio === undefined) {
|
||
usedGroupRatio = 1;
|
||
}
|
||
}
|
||
|
||
// 有效倍率是「基准倍率 × 折扣修正系数」的浮点乘积(后端修正系数还可能是除法结果),
|
||
// 不收敛会展示出 0.7200000000000001 之类脏数字;4 位小数对展示精度足够。
|
||
usedGroupRatio = parseFloat(usedGroupRatio.toFixed(4));
|
||
|
||
// 2. 根据计费类型计算价格
|
||
if (record.quota_type === 0) {
|
||
// 按量计费
|
||
const inputRatioPriceUSD = record.model_ratio * 2 * usedGroupRatio;
|
||
const completionRatioPriceUSD =
|
||
record.model_ratio * record.completion_ratio * 2 * usedGroupRatio;
|
||
|
||
const unitDivisor = tokenUnit === 'K' ? 1000 : 1;
|
||
const unitLabel = tokenUnit === 'K' ? 'K' : 'M';
|
||
|
||
const symbol = getCurrencySymbol(currency || 'USD');
|
||
|
||
const formatUnitPrice = (usdPrice) => {
|
||
const rawDisplay = displayPrice(usdPrice);
|
||
const rawNumber = parseFloat(String(rawDisplay).replace(/[^0-9.]/g, ''));
|
||
const unitPrice =
|
||
(Number.isFinite(rawNumber) ? rawNumber : 0) / unitDivisor;
|
||
return `${symbol}${unitPrice.toFixed(precision)}`;
|
||
};
|
||
|
||
const extraPrices = [];
|
||
const addExtraPrice = (key, labelKey, ratio) => {
|
||
if (!hasNumericPriceValue(ratio)) return;
|
||
extraPrices.push({
|
||
key,
|
||
labelKey,
|
||
price: formatUnitPrice(inputRatioPriceUSD * Number(ratio)),
|
||
});
|
||
};
|
||
|
||
addExtraPrice('cache_read', '缓存读取', record.cache_ratio);
|
||
|
||
const hasCacheCreation5m = hasNumericPriceValue(
|
||
record.cache_creation_5m_ratio,
|
||
);
|
||
// 只有 1h 档(Claude:全部写入按 1h 计费)时不再重复展示通用缓存创建价
|
||
const onlyCacheCreation1h =
|
||
!hasCacheCreation5m &&
|
||
hasNumericPriceValue(record.cache_creation_1h_ratio);
|
||
const cacheCreationRatio = hasCacheCreation5m
|
||
? record.cache_creation_5m_ratio
|
||
: record.cache_creation_ratio;
|
||
if (!onlyCacheCreation1h) {
|
||
addExtraPrice(
|
||
hasCacheCreation5m ? 'cache_creation_5m' : 'cache_creation',
|
||
hasCacheCreation5m ? '缓存创建(5m)' : '缓存创建',
|
||
cacheCreationRatio,
|
||
);
|
||
}
|
||
addExtraPrice(
|
||
'cache_creation_1h',
|
||
'缓存创建(1h)',
|
||
record.cache_creation_1h_ratio,
|
||
);
|
||
|
||
// 官方价对比:官方价(¥/1M,1:1 兑美元口径)与 inputRatioPriceUSD 同量纲,
|
||
// 走同一 formatUnitPrice 管道保证币种/单位一致;折扣比在数值层算好,
|
||
// 仅当该方向实付低于官方时才给出删除线原价(加价场景静默)。
|
||
const comparison = buildOfficialComparison(
|
||
record,
|
||
record.official_price,
|
||
usedGroupRatio,
|
||
);
|
||
const official =
|
||
comparison && comparison.badgeDiscount
|
||
? {
|
||
inputPrice: comparison.discountInput
|
||
? formatUnitPrice(comparison.officialInput)
|
||
: null,
|
||
completionPrice: comparison.discountOutput
|
||
? formatUnitPrice(comparison.officialOutput)
|
||
: null,
|
||
}
|
||
: null;
|
||
|
||
return {
|
||
inputPrice: formatUnitPrice(inputRatioPriceUSD),
|
||
completionPrice: formatUnitPrice(completionRatioPriceUSD),
|
||
extraPrices,
|
||
unitLabel,
|
||
isPerToken: true,
|
||
usedGroup,
|
||
usedGroupRatio,
|
||
official,
|
||
discountBadge: comparison?.badgeDiscount ?? null,
|
||
};
|
||
}
|
||
|
||
if (record.quota_type === 1) {
|
||
// 按次计费
|
||
const priceUSD = parseFloat(record.model_price) * usedGroupRatio;
|
||
const displayVal = displayPrice(priceUSD);
|
||
|
||
const comparison = buildOfficialComparison(
|
||
record,
|
||
record.official_price,
|
||
usedGroupRatio,
|
||
);
|
||
const official =
|
||
comparison && comparison.discountPerCall
|
||
? { price: displayPrice(comparison.officialPerCall) }
|
||
: null;
|
||
|
||
return {
|
||
price: displayVal,
|
||
isPerToken: false,
|
||
usedGroup,
|
||
usedGroupRatio,
|
||
official,
|
||
discountBadge: comparison?.discountPerCall ?? null,
|
||
};
|
||
}
|
||
|
||
if (record.quota_type === 2) {
|
||
// 按秒分档计费:每个档位单价 × 分组倍率
|
||
const tiers = record.video_second_pricing?.tiers || [];
|
||
const videoTiers = tiers.map((tier) => ({
|
||
key: tier.key,
|
||
label: tier.label || tier.key,
|
||
price: displayPrice(parseFloat(tier.price_per_second) * usedGroupRatio),
|
||
}));
|
||
|
||
return {
|
||
isPerToken: false,
|
||
isPerSecond: true,
|
||
videoTiers,
|
||
tierParam: record.video_second_pricing?.tier_param,
|
||
usedGroup,
|
||
usedGroupRatio,
|
||
};
|
||
}
|
||
|
||
if (record.quota_type === 3) {
|
||
// 图片按分辨率分档计费:每个档位单价 × 当前生效分组倍率。
|
||
const tiers = record.image_resolution_pricing?.tiers || [];
|
||
const imageTiers = tiers.map((tier) => ({
|
||
key: tier.key,
|
||
label: tier.label || tier.key,
|
||
price: displayPrice(parseFloat(tier.price_per_image) * usedGroupRatio),
|
||
}));
|
||
|
||
return {
|
||
isPerToken: false,
|
||
isPerImageResolution: true,
|
||
imageTiers,
|
||
defaultTier: record.image_resolution_pricing?.default_tier,
|
||
resolutionRule: record.image_resolution_pricing?.resolution_rule,
|
||
usedGroup,
|
||
usedGroupRatio,
|
||
};
|
||
}
|
||
|
||
// 未知计费类型,返回占位信息
|
||
return {
|
||
price: '-',
|
||
isPerToken: false,
|
||
usedGroup,
|
||
usedGroupRatio,
|
||
};
|
||
};
|
||
|
||
// 官方价展示格式化(详情表参考行用):与 calculateModelPrice.formatUnitPrice
|
||
// 走同一 displayPrice 管道 + 单位换算,保证与实付价同币种同单位可直接对照。
|
||
export const formatOfficialPriceDisplay = ({
|
||
official,
|
||
tokenUnit,
|
||
displayPrice,
|
||
precision = 4,
|
||
}) => {
|
||
if (!official) return null;
|
||
const unitDivisor = tokenUnit === 'K' ? 1000 : 1;
|
||
const symbol = getCurrencySymbol();
|
||
const fmtUnit = (v) => {
|
||
const n = Number(v);
|
||
if (!Number.isFinite(n) || n <= 0) return null;
|
||
const rawDisplay = displayPrice(n);
|
||
const rawNumber = parseFloat(String(rawDisplay).replace(/[^0-9.]/g, ''));
|
||
return `${symbol}${((Number.isFinite(rawNumber) ? rawNumber : 0) / unitDivisor).toFixed(precision)}`;
|
||
};
|
||
const perCall = Number(official.per_call);
|
||
return {
|
||
input: fmtUnit(official.input),
|
||
output: fmtUnit(official.output),
|
||
perCall:
|
||
Number.isFinite(perCall) && perCall > 0 ? displayPrice(perCall) : null,
|
||
};
|
||
};
|
||
|
||
// 官方价删除线(配合实付价展示,仅折扣场景出现)
|
||
const renderOfficialStrike = (formattedPrice) => {
|
||
if (!formattedPrice) return null;
|
||
return (
|
||
// 只写 line-through:若叠加 no-underline,二者都设 text-decoration-line,
|
||
// Tailwind 生成序中 no-underline 靠后会反杀删除线(同特异性后者胜)
|
||
<del
|
||
className='mr-1 line-through'
|
||
style={{ color: 'var(--ui-color-text-3)', fontSize: '0.92em' }}
|
||
>
|
||
{formattedPrice}
|
||
</del>
|
||
);
|
||
};
|
||
|
||
// 折扣徽标文案:中文「2.5折」,其他语言「-75%」。无折扣返回空串。
|
||
export const getDiscountBadgeText = (priceData) => {
|
||
if (!priceData?.discountBadge) return '';
|
||
return formatDiscountLabel(priceData.discountBadge, i18next.language);
|
||
};
|
||
|
||
// 格式化价格信息(用于卡片视图)
|
||
export const formatPriceInfo = (priceData, t) => {
|
||
if (priceData.isPerSecond || priceData.isPerImageResolution) {
|
||
return (
|
||
<span style={{ color: 'var(--ui-color-text-1)' }}>{t('模型价格')}</span>
|
||
);
|
||
}
|
||
|
||
if (priceData.isPerToken) {
|
||
const extraPrices = Array.isArray(priceData.extraPrices)
|
||
? priceData.extraPrices
|
||
: [];
|
||
const official = priceData.official;
|
||
|
||
return (
|
||
<>
|
||
<span style={{ color: 'var(--ui-color-text-1)' }}>
|
||
{t('输入')} {renderOfficialStrike(official?.inputPrice)}
|
||
<span className={official?.inputPrice ? 'font-semibold' : ''}>
|
||
{priceData.inputPrice}
|
||
</span>
|
||
/{priceData.unitLabel}
|
||
</span>
|
||
<span style={{ color: 'var(--ui-color-text-1)' }}>
|
||
{t('输出')} {renderOfficialStrike(official?.completionPrice)}
|
||
<span className={official?.completionPrice ? 'font-semibold' : ''}>
|
||
{priceData.completionPrice}
|
||
</span>
|
||
/{priceData.unitLabel}
|
||
</span>
|
||
{extraPrices.map((item) => (
|
||
<span key={item.key} style={{ color: 'var(--ui-color-text-1)' }}>
|
||
{t(item.labelKey)} {item.price}/{priceData.unitLabel}
|
||
</span>
|
||
))}
|
||
</>
|
||
);
|
||
}
|
||
|
||
return (
|
||
<>
|
||
<span style={{ color: 'var(--ui-color-text-1)' }}>
|
||
{t('模型价格')} {renderOfficialStrike(priceData.official?.price)}
|
||
<span className={priceData.official?.price ? 'font-semibold' : ''}>
|
||
{priceData.price}
|
||
</span>
|
||
</span>
|
||
</>
|
||
);
|
||
};
|
||
|
||
// -------------------------------
|
||
// CardPro 分页配置函数
|
||
// 用于创建 CardPro 的 paginationArea 配置
|
||
export const createCardProPagination = ({
|
||
currentPage,
|
||
pageSize,
|
||
total,
|
||
onPageChange,
|
||
onPageSizeChange,
|
||
}) => {
|
||
return (
|
||
total > 0 && (
|
||
<Pagination
|
||
currentPage={currentPage}
|
||
pageSize={pageSize}
|
||
total={total}
|
||
onPageSizeChange={onPageSizeChange}
|
||
onPageChange={onPageChange}
|
||
/>
|
||
)
|
||
);
|
||
};
|
||
|
||
// 模型定价筛选条件默认值
|
||
const DEFAULT_PRICING_FILTERS = {
|
||
search: '',
|
||
showWithRecharge: false,
|
||
currency: 'USD',
|
||
viewMode: 'card',
|
||
tokenUnit: 'M',
|
||
filterGroup: 'all',
|
||
filterQuotaType: 'all',
|
||
filterEndpointType: 'all',
|
||
filterVendor: 'all',
|
||
filterTag: 'all',
|
||
currentPage: 1,
|
||
};
|
||
|
||
// 重置模型定价筛选条件
|
||
export const resetPricingFilters = ({
|
||
handleChange,
|
||
setShowWithRecharge,
|
||
setCurrency,
|
||
setViewMode,
|
||
setFilterGroup,
|
||
setFilterQuotaType,
|
||
setFilterEndpointType,
|
||
setFilterVendor,
|
||
setFilterTag,
|
||
setCurrentPage,
|
||
setTokenUnit,
|
||
}) => {
|
||
handleChange?.(DEFAULT_PRICING_FILTERS.search);
|
||
setShowWithRecharge?.(DEFAULT_PRICING_FILTERS.showWithRecharge);
|
||
setCurrency?.(DEFAULT_PRICING_FILTERS.currency);
|
||
setViewMode?.(DEFAULT_PRICING_FILTERS.viewMode);
|
||
setTokenUnit?.(DEFAULT_PRICING_FILTERS.tokenUnit);
|
||
setFilterGroup?.(DEFAULT_PRICING_FILTERS.filterGroup);
|
||
setFilterQuotaType?.(DEFAULT_PRICING_FILTERS.filterQuotaType);
|
||
setFilterEndpointType?.(DEFAULT_PRICING_FILTERS.filterEndpointType);
|
||
setFilterVendor?.(DEFAULT_PRICING_FILTERS.filterVendor);
|
||
setFilterTag?.(DEFAULT_PRICING_FILTERS.filterTag);
|
||
setCurrentPage?.(DEFAULT_PRICING_FILTERS.currentPage);
|
||
};
|
||
|
||
/**
|
||
* 当前设备是否没有 hover 能力(触屏)。
|
||
*
|
||
* Semi 的 Popover / Tooltip 默认 trigger='hover',在触屏上永远打不开。
|
||
* 控制台有若干「唯一入口就是这个 popover」的场景(日志详情、兑换码明文、
|
||
* 上游冲突 diff、渠道备注),必须在触屏切成 click 才够得到。
|
||
*
|
||
* 这里不做成 hook:调用方多是 ColumnDefs 这类纯函数,用不了 hook;
|
||
* 而设备的 hover 能力在会话期间不会变化,读一次即可。
|
||
*/
|
||
export const isTouchDevice = () => {
|
||
if (typeof window === 'undefined' || !window.matchMedia) return false;
|
||
return window.matchMedia('(hover: none)').matches;
|
||
};
|
||
|
||
/** Popover/Tooltip 的 trigger:触屏用 click,其余保持 hover。 */
|
||
export const hoverOrClickTrigger = () => (isTouchDevice() ? 'click' : 'hover');
|