Initial import of weiyuan frontend

This commit is contained in:
qiubaishen
2026-10-15 16:33:46 +08:00
commit d8f3aee261
774 changed files with 374914 additions and 0 deletions
@@ -0,0 +1,635 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useState, useRef, useMemo } from 'react';
import {
Banner,
Button,
Col,
Form,
Row,
Spin,
Modal,
Select,
InputGroup,
Input,
} from '@douyinfe/semi-ui';
import { API, showError, showSuccess, showWarning } from '../../../helpers';
import { useTranslation } from 'react-i18next';
const API_MAPPING = {
DocsLink: 'general_setting.docs_link',
QuotaDisplayType: 'general_setting.quota_display_type',
CustomCurrencySymbol: 'general_setting.custom_currency_symbol',
CustomCurrencyExchangeRate: 'general_setting.custom_currency_exchange_rate',
};
const DEFAULT_INPUTS = {
TopUpLink: '',
DocsLink: '',
QuotaDisplayType: 'USD',
CustomCurrencySymbol: '¤',
CustomCurrencyExchangeRate: '',
QuotaPerUnit: '',
RetryTimes: '',
USDExchangeRate: '',
DisplayTokenStatEnabled: false,
DefaultCollapseSidebar: false,
DemoSiteEnabled: false,
SelfUseModeEnabled: false,
LanguageSwitchEnabled: true,
CosEnabled: false,
CosSecretId: '',
CosSecretKey: '',
CosBucket: '',
CosRegion: '',
CosBaseUrl: '',
CosPrivate: true,
CosPresignExpireSeconds: 86400,
GlobalPromptArchiveEnabled: false,
};
export default function GeneralSettings(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [showQuotaWarning, setShowQuotaWarning] = useState(false);
const [testingCos, setTestingCos] = useState(false);
const [inputs, setInputs] = useState(DEFAULT_INPUTS);
const refForm = useRef();
const [inputsRow, setInputsRow] = useState(inputs);
function handleFieldChange(fieldName) {
return (value) => {
setInputs((inputs) => ({ ...inputs, [fieldName]: value }));
};
}
function onSubmit() {
// 直接从Form API获取所有表单值,这是最可靠的方式
const formValues = refForm.current?.getValues?.();
if (!formValues) {
showError(t('获取表单数据失败'));
return;
}
// 合并表单值和inputs状态中的非表单字段。
// 注意:额度展示类型(QuotaDisplayType)与自定义汇率走的是裸 Select/Input
// (非 Form 字段),不会出现在 getValues() 里——漏合并会导致“改了保存不上、
// 刷新后弹回原值”的静默丢失。
const mergedValues = {
...formValues,
USDExchangeRate: inputs.USDExchangeRate,
QuotaPerUnit: inputs.QuotaPerUnit,
QuotaDisplayType: inputs.QuotaDisplayType,
CustomCurrencyExchangeRate: inputs.CustomCurrencyExchangeRate,
};
// 构建需要更新的数据
const updateArray = [];
for (const key in mergedValues) {
if (mergedValues.hasOwnProperty(key) && inputsRow.hasOwnProperty(key)) {
const currentValue = mergedValues[key];
const originalValue = inputsRow[key];
// 与后端脱敏规则对齐(controller/option.go 按后缀 Token/Secret/Key 判定):
// 用 includes 会误伤 CosSecretId(明文回读、非脱敏字段),导致每次保存
// 都把它当“用户新填的敏感值”重复提交。
const isSensitiveField =
key.endsWith('Token') ||
key.endsWith('Secret') ||
key.endsWith('Key');
// 如果值发生了变化,或者是敏感字段且用户填写了值,则添加到更新列表
if (
currentValue !== originalValue ||
(isSensitiveField && currentValue !== '')
) {
// 如果是映射字段,使用后端Key
const apiKey = API_MAPPING[key] || key;
updateArray.push({
key: apiKey,
oldValue: originalValue,
newValue: currentValue,
});
}
}
}
if (!updateArray.length) {
showWarning(t('你似乎并没有修改什么'));
return;
}
// 构建API请求
const requestQueue = updateArray.map((item) => {
let value = '';
if (typeof item.newValue === 'boolean') {
value = String(item.newValue);
} else {
value = item.newValue;
}
// 调试输出
console.log(`提交字段: ${item.key}, 值: ${value}`);
return API.put('/api/option/', {
key: item.key,
value,
});
});
setLoading(true);
Promise.all(requestQueue)
.then((res) => {
if (requestQueue.length === 1) {
if (res.includes(undefined)) return;
} else if (requestQueue.length > 1) {
if (res.includes(undefined))
return showError(t('部分保存失败,请重试'));
}
showSuccess(t('保存成功'));
// 刷新数据
props.refresh();
})
.catch(() => {
showError(t('保存失败,请重试'));
})
.finally(() => {
setLoading(false);
});
}
async function testCosConnection() {
setTestingCos(true);
try {
const res = await API.post('/api/option/test_cos');
if (res.data.success) {
showSuccess(res.data.message || 'COS连接测试成功');
} else {
showError(res.data.message || 'COS连接测试失败');
}
} catch (error) {
showError('COS连接测试失败: ' + (error.message || '未知错误'));
} finally {
setTestingCos(false);
}
}
// 计算展示在输入框中的“1 USD = X <currency>”中的 X
const combinedRate = useMemo(() => {
const type = inputs.QuotaDisplayType;
if (type === 'USD') return '1';
if (type === 'CNY') return String(inputs['USDExchangeRate'] || '');
if (type === 'TOKENS') return String(inputs['QuotaPerUnit'] || '');
if (type === 'CUSTOM')
return String(inputs.CustomCurrencyExchangeRate || '');
return '';
}, [inputs]);
const onCombinedRateChange = (val) => {
const type = inputs.QuotaDisplayType;
if (type === 'CNY') {
handleFieldChange('USDExchangeRate')(val);
} else if (type === 'TOKENS') {
handleFieldChange('QuotaPerUnit')(val);
} else if (type === 'CUSTOM') {
handleFieldChange('CustomCurrencyExchangeRate')(val);
}
};
useEffect(() => {
// 初始化所有inputs中定义的字段,确保不会丢失任何字段
const currentInputs = { ...DEFAULT_INPUTS };
// 反向映射:从API Key映射到前端Key
const reverseMap = {};
Object.keys(API_MAPPING).forEach((frontendKey) => {
reverseMap[API_MAPPING[frontendKey]] = frontendKey;
});
// 然后用props.options中的值覆盖,处理敏感字段
for (let key in props.options) {
// 检查是否是直接匹配的Key
if (Object.keys(currentInputs).includes(key)) {
let value = props.options[key];
// 将敏感字段的掩码值转换为空字符串,方便用户输入
if (value === '***ALREADY_SET***') {
value = '';
}
// 布尔字段后端存字符串 'true'/'false',需转回布尔:
// 否则字符串 'false' 为真值会让 Switch 恒显示开启(与实际保存状态不符)
if (typeof currentInputs[key] === 'boolean') {
value = value === true || value === 'true';
}
currentInputs[key] = value;
}
// 检查是否是需要映射的Key
else if (
reverseMap[key] &&
Object.keys(currentInputs).includes(reverseMap[key])
) {
let value = props.options[key];
if (value === '***ALREADY_SET***') {
value = '';
}
currentInputs[reverseMap[key]] = value;
}
}
// 若旧字段存在且新字段缺失,则做一次兜底映射
if (
props.options['general_setting.quota_display_type'] === undefined &&
props.options?.DisplayInCurrencyEnabled !== undefined
) {
currentInputs.QuotaDisplayType = props.options.DisplayInCurrencyEnabled
? 'USD'
: 'TOKENS';
}
// 回填自定义货币相关字段(如果后端已存在)- 这些已经在上面的循环中通过映射处理了,但为了保险起见(如果后端key不在props.options遍历中?)
// props.options 遍历应该覆盖了所有后端返回的key。所以不需要额外的逻辑,只要映射表正确。
setInputs(currentInputs);
setInputsRow(structuredClone(currentInputs));
refForm.current.setValues(currentInputs);
}, [props.options]);
return (
<>
<Spin spinning={loading}>
<Form
values={inputs}
getFormApi={(formAPI) => (refForm.current = formAPI)}
style={{ marginBottom: 15 }}
>
<Form.Section text={t('通用设置')}>
<Row gutter={16}>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Input
field={'TopUpLink'}
label={t('充值链接')}
initValue={''}
placeholder={t('例如发卡网站的购买链接')}
onChange={handleFieldChange('TopUpLink')}
showClear
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Input
field={'DocsLink'}
label={t('文档地址')}
initValue={''}
placeholder={t('例如 https://docs.newapi.pro')}
onChange={handleFieldChange('DocsLink')}
showClear
/>
</Col>
{/* 单位美元额度已合入汇率组合控件(TOKENS 模式下编辑),不再单独展示 */}
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Input
field={'RetryTimes'}
label={t('失败重试次数')}
initValue={''}
placeholder={t('失败重试次数')}
onChange={handleFieldChange('RetryTimes')}
showClear
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Slot label={t('站点额度展示类型及汇率')}>
<InputGroup style={{ width: '100%' }}>
<Input
prefix={'1 USD = '}
style={{ width: '50%' }}
value={combinedRate}
onChange={onCombinedRateChange}
disabled={inputs.QuotaDisplayType === 'USD'}
/>
<Select
style={{ width: '50%' }}
value={inputs.QuotaDisplayType}
onChange={handleFieldChange('QuotaDisplayType')}
>
<Select.Option value='USD'>USD (¥)</Select.Option>
<Select.Option value='CNY'>CNY (¥)</Select.Option>
<Select.Option value='TOKENS'>Tokens</Select.Option>
<Select.Option value='CUSTOM'>
{t('自定义货币')}
</Select.Option>
</Select>
</InputGroup>
</Form.Slot>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Input
field={'CustomCurrencySymbol'}
label={t('自定义货币符号')}
placeholder={t('例如 €, £, Rp, ₩, ₹...')}
onChange={handleFieldChange('CustomCurrencySymbol')}
showClear
disabled={inputs.QuotaDisplayType !== 'CUSTOM'}
/>
</Col>
</Row>
<Row gutter={16}>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'DisplayTokenStatEnabled'}
label={t('额度查询接口返回令牌额度而非用户额度')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={handleFieldChange('DisplayTokenStatEnabled')}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'DefaultCollapseSidebar'}
label={t('默认折叠侧边栏')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={handleFieldChange('DefaultCollapseSidebar')}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'DemoSiteEnabled'}
label={t('演示站点模式')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={handleFieldChange('DemoSiteEnabled')}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'SelfUseModeEnabled'}
label={t('自用模式')}
extraText={t('开启后不限制:必须设置模型倍率')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={handleFieldChange('SelfUseModeEnabled')}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'LanguageSwitchEnabled'}
label={t('顶栏语言切换按钮')}
extraText={t('开启后顶栏右上角显示中/英文切换按钮')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={handleFieldChange('LanguageSwitchEnabled')}
/>
</Col>
</Row>
<Row>
<Button size='default' onClick={onSubmit}>
{t('保存通用设置')}
</Button>
</Row>
</Form.Section>
<Form.Section text={t('腾讯云COS配置')}>
<Row gutter={16}>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'CosEnabled'}
label={t('启用腾讯云COS存储')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={handleFieldChange('CosEnabled')}
/>
</Col>
</Row>
<Row gutter={16}>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Input
field={'CosSecretId'}
label={t('SecretId')}
initValue={''}
placeholder={t('腾讯云API密钥SecretId')}
onChange={handleFieldChange('CosSecretId')}
showClear
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Input
field={'CosSecretKey'}
label={t('SecretKey')}
initValue={''}
placeholder={t('腾讯云API密钥SecretKey')}
onChange={handleFieldChange('CosSecretKey')}
showClear
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Input
field={'CosBucket'}
label={t('Bucket名称')}
initValue={''}
placeholder={t('例如: my-bucket-1250000000')}
onChange={handleFieldChange('CosBucket')}
showClear
/>
</Col>
</Row>
<Row gutter={16}>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Input
field={'CosRegion'}
label={t('地域')}
initValue={''}
placeholder={t('例如: ap-beijing, ap-shanghai')}
onChange={handleFieldChange('CosRegion')}
showClear
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Input
field={'CosBaseUrl'}
label={t('自定义域名(可选)')}
initValue={''}
placeholder={t('例如: https://cdn.example.com')}
onChange={handleFieldChange('CosBaseUrl')}
showClear
/>
</Col>
</Row>
<Row gutter={16}>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'CosPrivate'}
label={t('私有访问模式')}
extraText={t(
'开启后图片URL将包含预签名信息,关闭后需将Bucket设为公有读',
)}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={handleFieldChange('CosPrivate')}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
field={'CosPresignExpireSeconds'}
label={t('预签名URL过期时间(秒)')}
initValue={86400}
placeholder={t('默认86400秒(24小时)')}
min={60}
max={604800}
onChange={handleFieldChange('CosPresignExpireSeconds')}
disabled={!inputs.CosPrivate}
extraText={t(
'仅私有模式有效,范围: 60秒-7天。建议 86400(24h) 以上,过短会导致历史图片链接频繁失效',
)}
showClear
/>
</Col>
</Row>
<Row gutter={16}>
<Col span={24}>
<Banner
type='info'
description={
<div>
<p>
{t(
'配置腾讯云COS后,生成的图片将自动上传到对象存储,方便用户访问和管理。请确保填写正确的配置信息。',
)}
</p>
<p style={{ marginTop: '8px' }}>
<strong>{t('私有访问模式说明:')}</strong>
</p>
<ul style={{ marginLeft: '20px', marginTop: '4px' }}>
<li>
{t(
'开启私有访问: 图片URL会包含临时签名,可保护图片安全,但URL会在指定时间后过期',
)}
</li>
<li>
{t(
'关闭私有访问: 图片URL永久有效,但需要将COS Bucket权限设置为"公有读私有写"',
)}
</li>
<li>
{t(
'推荐设置: 开启私有访问 + 过期时间设为24小时(86400秒)以上',
)}
</li>
</ul>
</div>
}
bordered
fullMode={false}
closeIcon={null}
/>
</Col>
</Row>
<Row gutter={16}>
<Button
size='default'
onClick={onSubmit}
style={{ marginRight: 8 }}
>
{t('保存COS配置')}
</Button>
<Button
size='default'
type='tertiary'
onClick={testCosConnection}
loading={testingCos}
disabled={!inputs.CosEnabled}
>
{t('测试连接')}
</Button>
</Row>
</Form.Section>
<Form.Section text={t('提示词采集(实验性)')}>
<Row gutter={16}>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'GlobalPromptArchiveEnabled'}
label={t('记录平台用户输入提示词')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={handleFieldChange('GlobalPromptArchiveEnabled')}
/>
</Col>
</Row>
<Row gutter={16}>
<Col span={24}>
<Banner
type='warning'
description={
<div>
<p>
{t(
'实验性功能:开启后平台将异步记录所有用户对话中的「用户输入提示词」及其调用统计(接口调用次数、总花费)至平台数据库 prompt_traces 表,仅用于 token 运营与模型训练数据研究,不是用户数据备份/存档功能。',
)}
</p>
<p style={{ marginTop: '8px' }}>
{t(
'与企业自有库采集相互独立、互不影响(企业开关开启时其数据同时写入企业自己配置的数据库)。开启前请确认符合隐私合规要求。',
)}
</p>
</div>
}
bordered
fullMode={false}
closeIcon={null}
/>
</Col>
</Row>
<Row gutter={16}>
<Button size='default' onClick={onSubmit}>
{t('保存提示词采集设置')}
</Button>
</Row>
</Form.Section>
</Form>
</Spin>
<Modal
title={t('警告')}
visible={showQuotaWarning}
onOk={() => setShowQuotaWarning(false)}
onCancel={() => setShowQuotaWarning(false)}
closeOnEsc={true}
width={500}
>
<Banner
type='warning'
description={t(
'此设置用于系统内部计算,默认值500000是为了精确到6位小数点设计,不推荐修改。',
)}
bordered
fullMode={false}
closeIcon={null}
/>
</Modal>
</>
);
}