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
+327
View File
@@ -0,0 +1,327 @@
/*
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, { useState, useEffect } from 'react';
import {
Form,
Button,
Table,
Modal,
Space,
Card,
Typography,
Tag,
Popconfirm,
} from '@douyinfe/semi-ui';
import { IconPlus, IconEdit, IconDelete } from '@douyinfe/semi-icons';
import { useTranslation } from 'react-i18next';
import { API, showError, showSuccess } from '../../helpers';
const { Title } = Typography;
const AmountOptionsManager = ({
apiPath = '/api/user/payment/amount-options',
title = '充值档位管理',
}) => {
const { t } = useTranslation();
const [options, setOptions] = useState([]);
const [loading, setLoading] = useState(false);
const [editModal, setEditModal] = useState({ visible: false, data: null });
const [, setFormApi] = useState(null);
useEffect(() => {
loadOptions();
}, [apiPath]);
const loadOptions = async () => {
try {
setLoading(true);
const res = await API.get(apiPath);
if (res.data.success) {
setOptions(res.data.data || []);
} else {
showError(t('加载失败'));
}
} catch (error) {
showError(t('加载失败'));
} finally {
setLoading(false);
}
};
const columns = [
{ title: 'ID', dataIndex: 'id', width: 60 },
{
title: t('金额'),
dataIndex: 'amount',
render: (v) => `¥${v}`,
width: 100,
},
{
title: t('折扣'),
dataIndex: 'discount',
render: (v) =>
t('{{rate}}折', {
rate: (v * 10).toFixed(1),
percent: Math.round(100 - v * 100),
}),
width: 80,
},
{ title: t('标签'), dataIndex: 'label', width: 100 },
{
title: t('角标'),
dataIndex: 'badge',
render: (text, record) => {
if (!text) return '-';
return <Tag color={record.badge_color || 'blue'}>{text}</Tag>;
},
width: 100,
},
{
title: t('赠送额度'),
dataIndex: 'bonus',
render: (v) => (v > 0 ? v.toLocaleString() : '-'),
width: 120,
},
{
title: t('标记'),
render: (text, record) => (
<Space>
{record.is_recommend && <Tag color='blue'>{t('推荐')}</Tag>}
{record.is_hot && <Tag color='red'>{t('热门')}</Tag>}
{record.min_vip_level > 0 && (
<Tag color='purple'>VIP{record.min_vip_level}+</Tag>
)}
</Space>
),
width: 150,
},
{ title: t('排序'), dataIndex: 'sort', width: 70 },
{
title: t('操作'),
render: (text, record) => (
<Space>
<Button
size='small'
icon={<IconEdit />}
onClick={() => handleEdit(record)}
>
{t('编辑')}
</Button>
<Popconfirm
title={t('确定删除该档位吗?')}
onConfirm={() => handleDelete(record.id)}
>
<Button size='small' type='danger' icon={<IconDelete />}>
{t('删除')}
</Button>
</Popconfirm>
</Space>
),
width: 150,
},
];
const handleEdit = (record) => {
setEditModal({ visible: true, data: record });
};
const handleDelete = async (id) => {
const newOptions = options.filter((opt) => opt.id !== id);
await saveOptions(newOptions);
};
const handleAdd = () => {
setEditModal({
visible: true,
data: {
id: Math.max(...options.map((o) => o.id), 0) + 1,
amount: 10,
discount: 1.0,
label: '',
badge: '',
badge_color: '#1890ff',
is_recommend: false,
is_hot: false,
min_vip_level: 0,
bonus: 0,
sort: options.length + 1,
},
});
};
const handleSave = async (values) => {
try {
setLoading(true);
const newOptions =
editModal.data.id && options.find((o) => o.id === editModal.data.id)
? options.map((opt) =>
opt.id === editModal.data.id ? { ...opt, ...values } : opt,
)
: [...options, { ...values, id: editModal.data.id }];
await saveOptions(newOptions);
setEditModal({ visible: false, data: null });
} catch (error) {
showError(t('保存失败'));
} finally {
setLoading(false);
}
};
const saveOptions = async (newOptions) => {
try {
const res = await API.post(apiPath, {
amount_options: newOptions.sort((a, b) => a.sort - b.sort),
});
if (res.data.success) {
showSuccess(t('保存成功'));
loadOptions();
} else {
showError(res.data.message);
}
} catch (error) {
showError(t('保存失败'));
}
};
return (
<div style={{ padding: '20px' }}>
<Card>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 20,
}}
>
<Title heading={3}>{t(title)}</Title>
<Button type='primary' icon={<IconPlus />} onClick={handleAdd}>
{t('新增档位')}
</Button>
</div>
<Table
// 列宽合计远超窄屏视口;没有 scroll 时表格会压缩到 min-content 硬塞进去,
// 末尾的操作列落在视口外,且 iOS 上滚动条不可见、毫无可拖动提示
scroll={{ x: 'max-content' }}
columns={columns}
dataSource={options}
rowKey='id'
loading={loading}
pagination={false}
/>
</Card>
{/* 编辑/新增弹窗 */}
<Modal
title={
editModal.data?.id && options.find((o) => o.id === editModal.data.id)
? t('编辑档位')
: t('新增档位')
}
visible={editModal.visible}
onCancel={() => setEditModal({ visible: false, data: null })}
footer={null}
width={600}
>
<Form
initValues={editModal.data || {}}
onSubmit={handleSave}
getFormApi={(api) => setFormApi(api)}
>
<Form.InputNumber
field='amount'
label={t('充值金额(元)')}
rules={[{ required: true, message: t('请输入金额') }]}
min={1}
style={{ width: '100%' }}
/>
<Form.InputNumber
field='discount'
label={t('折扣率')}
rules={[{ required: true, message: t('请输入折扣率') }]}
step={0.01}
min={0.01}
max={1}
style={{ width: '100%' }}
extraText={t('1.0 = 无折扣,0.9 = 9折,0.01 = 1折')}
/>
<Form.Input
field='label'
label={t('显示标签')}
rules={[{ required: true, message: t('请输入标签') }]}
placeholder={t('如:10元')}
/>
<Form.Input
field='badge'
label={t('角标文字')}
placeholder={t('如:最划算(可选)')}
/>
<Form.Input
field='badge_color'
label={t('角标颜色')}
placeholder='#1890ff'
/>
<Form.InputNumber
field='bonus'
label={t('赠送额度')}
min={0}
style={{ width: '100%' }}
extraText={t('额外赠送的额度(0 = 不赠送)')}
/>
<Form.InputNumber
field='min_vip_level'
label={t('最低VIP等级')}
min={0}
style={{ width: '100%' }}
extraText={t('0 = 无限制')}
/>
<Form.Switch field='is_recommend' label={t('推荐标记')} />
<Form.Switch field='is_hot' label={t('热门标记')} />
<Form.InputNumber
field='sort'
label={t('排序')}
rules={[{ required: true, message: t('请输入排序') }]}
min={1}
style={{ width: '100%' }}
extraText={t('数字越小越靠前')}
/>
<div style={{ marginTop: 20, textAlign: 'right' }}>
<Button
htmlType='button'
style={{ marginRight: 8 }}
onClick={() => setEditModal({ visible: false, data: null })}
>
{t('取消')}
</Button>
<Button htmlType='submit' type='primary' loading={loading}>
{t('保存')}
</Button>
</div>
</Form>
</Modal>
</div>
);
};
export default AmountOptionsManager;
+507
View File
@@ -0,0 +1,507 @@
/*
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 } from 'react';
import {
Banner,
Button,
Form,
Space,
Spin,
RadioGroup,
Radio,
Table,
Modal,
Input,
Divider,
} from '@douyinfe/semi-ui';
import {
IconPlus,
IconEdit,
IconDelete,
IconSearch,
IconSaveStroked,
} from '@douyinfe/semi-icons';
import {
compareObjects,
API,
showError,
showSuccess,
showWarning,
verifyJSON,
} from '../../../helpers';
import { useTranslation } from 'react-i18next';
export default function SettingsChats(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [inputs, setInputs] = useState({
Chats: '[]',
});
const refForm = useRef();
const [inputsRow, setInputsRow] = useState(inputs);
const [editMode, setEditMode] = useState('visual');
const [chatConfigs, setChatConfigs] = useState([]);
const [modalVisible, setModalVisible] = useState(false);
const [editingConfig, setEditingConfig] = useState(null);
const [isEdit, setIsEdit] = useState(false);
const [searchText, setSearchText] = useState('');
const modalFormRef = useRef();
const jsonToConfigs = (jsonString) => {
try {
const configs = JSON.parse(jsonString);
return Array.isArray(configs)
? configs.map((config, index) => ({
id: index,
name: Object.keys(config)[0] || '',
url: Object.values(config)[0] || '',
}))
: [];
} catch (error) {
console.error('JSON parse error:', error);
return [];
}
};
const configsToJson = (configs) => {
const jsonArray = configs.map((config) => ({
[config.name]: config.url,
}));
return JSON.stringify(jsonArray, null, 2);
};
const syncJsonToConfigs = () => {
const configs = jsonToConfigs(inputs.Chats);
setChatConfigs(configs);
};
const syncConfigsToJson = (configs) => {
const jsonString = configsToJson(configs);
setInputs((prev) => ({
...prev,
Chats: jsonString,
}));
if (refForm.current && editMode === 'json') {
refForm.current.setValues({ Chats: jsonString });
}
};
async function onSubmit() {
try {
console.log('Starting validation...');
await refForm.current
.validate()
.then(() => {
console.log('Validation passed');
const updateArray = compareObjects(inputs, inputsRow);
if (!updateArray.length)
return showWarning(t('你似乎并没有修改什么'));
const requestQueue = updateArray.map((item) => {
let value = '';
if (typeof inputs[item.key] === 'boolean') {
value = String(inputs[item.key]);
} else {
value = inputs[item.key];
}
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);
});
})
.catch((error) => {
console.error('Validation failed:', error);
showError(t('请检查输入'));
});
} catch (error) {
showError(t('请检查输入'));
console.error(error);
}
}
useEffect(() => {
const currentInputs = {};
for (let key in props.options) {
if (Object.keys(inputs).includes(key)) {
if (key === 'Chats') {
const obj = JSON.parse(props.options[key]);
currentInputs[key] = JSON.stringify(obj, null, 2);
} else {
currentInputs[key] = props.options[key];
}
}
}
setInputs(currentInputs);
setInputsRow(structuredClone(currentInputs));
if (refForm.current) {
refForm.current.setValues(currentInputs);
}
// 同步到可视化配置
const configs = jsonToConfigs(currentInputs.Chats || '[]');
setChatConfigs(configs);
}, [props.options]);
useEffect(() => {
if (editMode === 'visual') {
syncJsonToConfigs();
}
}, [inputs.Chats, editMode]);
useEffect(() => {
if (refForm.current && editMode === 'json') {
refForm.current.setValues(inputs);
}
}, [editMode, inputs]);
const handleAddConfig = () => {
setEditingConfig({ name: '', url: '' });
setIsEdit(false);
setModalVisible(true);
setTimeout(() => {
if (modalFormRef.current) {
modalFormRef.current.setValues({ name: '', url: '' });
}
}, 100);
};
const handleEditConfig = (config) => {
setEditingConfig({ ...config });
setIsEdit(true);
setModalVisible(true);
setTimeout(() => {
if (modalFormRef.current) {
modalFormRef.current.setValues(config);
}
}, 100);
};
const handleDeleteConfig = (id) => {
const newConfigs = chatConfigs.filter((config) => config.id !== id);
setChatConfigs(newConfigs);
syncConfigsToJson(newConfigs);
showSuccess(t('删除成功'));
};
const handleModalOk = () => {
if (modalFormRef.current) {
modalFormRef.current
.validate()
.then((values) => {
// 检查名称是否重复
const isDuplicate = chatConfigs.some(
(config) =>
config.name === values.name &&
(!isEdit || config.id !== editingConfig.id),
);
if (isDuplicate) {
showError(t('聊天应用名称已存在,请使用其他名称'));
return;
}
if (isEdit) {
const newConfigs = chatConfigs.map((config) =>
config.id === editingConfig.id
? { ...editingConfig, name: values.name, url: values.url }
: config,
);
setChatConfigs(newConfigs);
syncConfigsToJson(newConfigs);
} else {
const maxId =
chatConfigs.length > 0
? Math.max(...chatConfigs.map((c) => c.id))
: -1;
const newConfig = {
id: maxId + 1,
name: values.name,
url: values.url,
};
const newConfigs = [...chatConfigs, newConfig];
setChatConfigs(newConfigs);
syncConfigsToJson(newConfigs);
}
setModalVisible(false);
setEditingConfig(null);
showSuccess(isEdit ? t('编辑成功') : t('添加成功'));
})
.catch((error) => {
console.error('Modal form validation error:', error);
});
}
};
const handleModalCancel = () => {
setModalVisible(false);
setEditingConfig(null);
};
const filteredConfigs = chatConfigs.filter(
(config) =>
!searchText ||
config.name.toLowerCase().includes(searchText.toLowerCase()),
);
const highlightKeywords = (text) => {
if (!text) return text;
const parts = text.split(/(\{address\}|\{key\})/g);
return parts.map((part, index) => {
if (part === '{address}') {
return (
<span key={index} style={{ color: '#0077cc', fontWeight: 600 }}>
{part}
</span>
);
} else if (part === '{key}') {
return (
<span key={index} style={{ color: '#ff6b35', fontWeight: 600 }}>
{part}
</span>
);
}
return part;
});
};
const columns = [
{
title: t('聊天应用名称'),
dataIndex: 'name',
key: 'name',
render: (text) => text || t('未命名'),
},
{
title: t('URL链接'),
dataIndex: 'url',
key: 'url',
render: (text) => (
<div style={{ maxWidth: 300, wordBreak: 'break-all' }}>
{highlightKeywords(text)}
</div>
),
},
{
title: t('操作'),
key: 'action',
render: (_, record) => (
<Space>
<Button
type='primary'
icon={<IconEdit />}
size='small'
onClick={() => handleEditConfig(record)}
>
{t('编辑')}
</Button>
<Button
type='danger'
icon={<IconDelete />}
size='small'
onClick={() => handleDeleteConfig(record.id)}
>
{t('删除')}
</Button>
</Space>
),
},
];
return (
<Spin spinning={loading}>
<Space vertical style={{ width: '100%' }}>
<Form.Section text={t('聊天设置')}>
<Banner
type='info'
description={t(
'链接中的{key}将自动替换为sk-xxxx,{address}将自动替换为系统设置的服务器地址,末尾不带/和/v1',
)}
/>
<Divider />
<div style={{ marginBottom: 16 }}>
<span style={{ marginRight: 16, fontWeight: 600 }}>
{t('编辑模式')}:
</span>
<RadioGroup
type='button'
value={editMode}
onChange={(e) => {
const newMode = e.target.value;
setEditMode(newMode);
// 确保模式切换时数据正确同步
setTimeout(() => {
if (newMode === 'json' && refForm.current) {
refForm.current.setValues(inputs);
}
}, 100);
}}
>
<Radio value='visual'>{t('可视化编辑')}</Radio>
<Radio value='json'>{t('JSON编辑')}</Radio>
</RadioGroup>
</div>
{editMode === 'visual' ? (
<div>
<Space style={{ marginBottom: 16 }}>
<Button
type='primary'
icon={<IconPlus />}
onClick={handleAddConfig}
>
{t('添加聊天配置')}
</Button>
<Button
type='primary'
theme='solid'
icon={<IconSaveStroked />}
onClick={onSubmit}
>
{t('保存聊天设置')}
</Button>
<Input
prefix={<IconSearch />}
placeholder={t('搜索聊天应用名称')}
value={searchText}
onChange={(value) => setSearchText(value)}
style={{ width: 250 }}
showClear
/>
</Space>
<Table
columns={columns}
dataSource={filteredConfigs}
rowKey='id'
pagination={{
pageSize: 10,
showSizeChanger: false,
showQuickJumper: true,
showTotal: (total, range) =>
t('共 {{total}} 项,当前显示 {{start}}-{{end}} 项', {
total,
start: range[0],
end: range[1],
}),
}}
/>
</div>
) : (
<Form
values={inputs}
getFormApi={(formAPI) => (refForm.current = formAPI)}
>
<Form.TextArea
label={t('聊天配置')}
extraText={''}
placeholder={t('为一个 JSON 文本')}
field={'Chats'}
autosize={{ minRows: 6, maxRows: 12 }}
trigger='blur'
stopValidateWithError
rules={[
{
validator: (rule, value) => {
return verifyJSON(value);
},
message: t('不是合法的 JSON 字符串'),
},
]}
onChange={(value) =>
setInputs({
...inputs,
Chats: value,
})
}
/>
</Form>
)}
</Form.Section>
{editMode === 'json' && (
<Space>
<Button
type='primary'
icon={<IconSaveStroked />}
onClick={onSubmit}
>
{t('保存聊天设置')}
</Button>
</Space>
)}
</Space>
<Modal
title={isEdit ? t('编辑聊天配置') : t('添加聊天配置')}
visible={modalVisible}
onOk={handleModalOk}
onCancel={handleModalCancel}
width={600}
>
<Form getFormApi={(api) => (modalFormRef.current = api)}>
<Form.Input
field='name'
label={t('聊天应用名称')}
placeholder={t('请输入聊天应用名称')}
rules={[
{ required: true, message: t('请输入聊天应用名称') },
{ min: 1, message: t('名称不能为空') },
]}
/>
<Form.Input
field='url'
label={t('URL链接')}
placeholder={t('请输入完整的URL链接')}
rules={[{ required: true, message: t('请输入URL链接') }]}
/>
<Banner
type='info'
description={t(
'提示:链接中的{key}将被替换为API密钥,{address}将被替换为服务器地址',
)}
style={{ marginTop: 16 }}
/>
</Form>
</Modal>
</Spin>
);
}
@@ -0,0 +1,513 @@
/*
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 } from 'react';
import {
Button,
Space,
Table,
Form,
Typography,
Empty,
Divider,
Avatar,
Modal,
Tag,
Switch,
} from '@douyinfe/semi-ui';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../../components/common/illustrations';
import { Plus, Edit, Trash2, Save, Settings } from 'lucide-react';
import { API, showError, showSuccess } from '../../../helpers';
import { useTranslation } from 'react-i18next';
const { Text } = Typography;
const SettingsAPIInfo = ({ options, refresh }) => {
const { t } = useTranslation();
const [apiInfoList, setApiInfoList] = useState([]);
const [showApiModal, setShowApiModal] = useState(false);
const [showDeleteModal, setShowDeleteModal] = useState(false);
const [deletingApi, setDeletingApi] = useState(null);
const [editingApi, setEditingApi] = useState(null);
const [modalLoading, setModalLoading] = useState(false);
const [loading, setLoading] = useState(false);
const [hasChanges, setHasChanges] = useState(false);
const [apiForm, setApiForm] = useState({
url: '',
description: '',
route: '',
color: 'blue',
});
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const [selectedRowKeys, setSelectedRowKeys] = useState([]);
// 面板启用状态 state
const [panelEnabled, setPanelEnabled] = useState(true);
const colorOptions = [
{ value: 'blue', label: 'blue' },
{ value: 'green', label: 'green' },
{ value: 'cyan', label: 'cyan' },
{ value: 'purple', label: 'purple' },
{ value: 'pink', label: 'pink' },
{ value: 'red', label: 'red' },
{ value: 'orange', label: 'orange' },
{ value: 'amber', label: 'amber' },
{ value: 'yellow', label: 'yellow' },
{ value: 'lime', label: 'lime' },
{ value: 'light-green', label: 'light-green' },
{ value: 'teal', label: 'teal' },
{ value: 'light-blue', label: 'light-blue' },
{ value: 'indigo', label: 'indigo' },
{ value: 'violet', label: 'violet' },
{ value: 'grey', label: 'grey' },
];
const updateOption = async (key, value) => {
const res = await API.put('/api/option/', {
key,
value,
});
const { success, message } = res.data;
if (success) {
showSuccess(t('API信息已更新'));
if (refresh) refresh();
} else {
showError(message);
}
};
const submitApiInfo = async () => {
try {
setLoading(true);
const apiInfoJson = JSON.stringify(apiInfoList);
await updateOption('console_setting.api_info', apiInfoJson);
setHasChanges(false);
} catch (error) {
console.error('API信息更新失败', error);
showError(t('API信息更新失败'));
} finally {
setLoading(false);
}
};
const handleAddApi = () => {
setEditingApi(null);
setApiForm({
url: '',
description: '',
route: '',
color: 'blue',
});
setShowApiModal(true);
};
const handleEditApi = (api) => {
setEditingApi(api);
setApiForm({
url: api.url,
description: api.description,
route: api.route,
color: api.color,
});
setShowApiModal(true);
};
const handleDeleteApi = (api) => {
setDeletingApi(api);
setShowDeleteModal(true);
};
const confirmDeleteApi = () => {
if (deletingApi) {
const newList = apiInfoList.filter((api) => api.id !== deletingApi.id);
setApiInfoList(newList);
setHasChanges(true);
showSuccess(t('API信息已删除,请及时点击“保存设置”进行保存'));
}
setShowDeleteModal(false);
setDeletingApi(null);
};
const handleSaveApi = async () => {
if (!apiForm.url || !apiForm.route || !apiForm.description) {
showError(t('请填写完整的API信息'));
return;
}
try {
setModalLoading(true);
let newList;
if (editingApi) {
newList = apiInfoList.map((api) =>
api.id === editingApi.id ? { ...api, ...apiForm } : api,
);
} else {
const newId = Math.max(...apiInfoList.map((api) => api.id), 0) + 1;
const newApi = {
id: newId,
...apiForm,
};
newList = [...apiInfoList, newApi];
}
setApiInfoList(newList);
setHasChanges(true);
setShowApiModal(false);
showSuccess(
editingApi
? 'API信息已更新,请及时点击“保存设置”进行保存'
: 'API信息已添加,请及时点击“保存设置”进行保存',
);
} catch (error) {
showError('操作失败: ' + error.message);
} finally {
setModalLoading(false);
}
};
const parseApiInfo = (apiInfoStr) => {
if (!apiInfoStr) {
setApiInfoList([]);
return;
}
try {
const parsed = JSON.parse(apiInfoStr);
setApiInfoList(Array.isArray(parsed) ? parsed : []);
} catch (error) {
console.error('解析API信息失败:', error);
setApiInfoList([]);
}
};
useEffect(() => {
const apiInfoStr = options['console_setting.api_info'] ?? options.ApiInfo;
if (apiInfoStr !== undefined) {
parseApiInfo(apiInfoStr);
}
}, [options['console_setting.api_info'], options.ApiInfo]);
useEffect(() => {
const enabledStr = options['console_setting.api_info_enabled'];
setPanelEnabled(
enabledStr === undefined
? true
: enabledStr === 'true' || enabledStr === true,
);
}, [options['console_setting.api_info_enabled']]);
const handleToggleEnabled = async (checked) => {
const newValue = checked ? 'true' : 'false';
try {
const res = await API.put('/api/option/', {
key: 'console_setting.api_info_enabled',
value: newValue,
});
if (res.data.success) {
setPanelEnabled(checked);
showSuccess(t('设置已保存'));
refresh?.();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
};
const columns = [
{
title: 'ID',
dataIndex: 'id',
},
{
title: t('API地址'),
dataIndex: 'url',
render: (text, record) => (
<Tag color={record.color} shape='circle' style={{ maxWidth: '280px' }}>
{text}
</Tag>
),
},
{
title: t('线路描述'),
dataIndex: 'route',
render: (text, record) => <Tag shape='circle'>{text}</Tag>,
},
{
title: t('说明'),
dataIndex: 'description',
ellipsis: true,
render: (text, record) => <Tag shape='circle'>{text || '-'}</Tag>,
},
{
title: t('颜色'),
dataIndex: 'color',
render: (color) => <Avatar size='extra-extra-small' color={color} />,
},
{
title: t('操作'),
fixed: 'right',
width: 150,
render: (_, record) => (
<Space>
<Button
icon={<Edit size={14} />}
theme='light'
type='tertiary'
size='small'
onClick={() => handleEditApi(record)}
>
{t('编辑')}
</Button>
<Button
icon={<Trash2 size={14} />}
type='danger'
theme='light'
size='small'
onClick={() => handleDeleteApi(record)}
>
{t('删除')}
</Button>
</Space>
),
},
];
const handleBatchDelete = () => {
if (selectedRowKeys.length === 0) {
showError(t('请先选择要删除的API信息'));
return;
}
const newList = apiInfoList.filter(
(api) => !selectedRowKeys.includes(api.id),
);
setApiInfoList(newList);
setSelectedRowKeys([]);
setHasChanges(true);
showSuccess(`已删除 ${selectedRowKeys.length} 个API信息,请及时点击“保存设置”进行保存`,
);
};
const renderHeader = () => (
<div className='flex flex-col w-full'>
<div className='mb-2'>
<div className='flex items-center text-blue-500'>
<Settings size={16} className='mr-2' />
<Text>
{t(
'API信息管理,可以配置多个API地址用于状态展示和负载均衡(最多50个)',
)}
</Text>
</div>
</div>
<Divider margin='12px' />
<div className='flex flex-col md:flex-row justify-between items-center gap-4 w-full'>
<div className='flex gap-2 w-full md:w-auto order-2 md:order-1'>
<Button
theme='light'
type='primary'
icon={<Plus size={14} />}
className='w-full md:w-auto'
onClick={handleAddApi}
>
{t('添加API')}
</Button>
<Button
icon={<Trash2 size={14} />}
type='danger'
theme='light'
onClick={handleBatchDelete}
disabled={selectedRowKeys.length === 0}
className='w-full md:w-auto'
>
{t('批量删除')}{' '}
{selectedRowKeys.length > 0 && `(${selectedRowKeys.length})`}
</Button>
<Button
icon={<Save size={14} />}
onClick={submitApiInfo}
loading={loading}
disabled={!hasChanges}
type='secondary'
className='w-full md:w-auto'
>
{t('保存设置')}
</Button>
</div>
{/* 启用开关 */}
<div className='order-1 md:order-2 flex items-center gap-2'>
<Switch checked={panelEnabled} onChange={handleToggleEnabled} />
<Text>{panelEnabled ? t('已启用') : t('已禁用')}</Text>
</div>
</div>
</div>
);
// 计算当前页显示的数据
const getCurrentPageData = () => {
const startIndex = (currentPage - 1) * pageSize;
const endIndex = startIndex + pageSize;
return apiInfoList.slice(startIndex, endIndex);
};
const rowSelection = {
selectedRowKeys,
onChange: (selectedRowKeys, selectedRows) => {
setSelectedRowKeys(selectedRowKeys);
},
onSelect: (record, selected, selectedRows) => {
console.log(`选择行: ${selected}`, record);
},
onSelectAll: (selected, selectedRows) => {
console.log(`全选: ${selected}`, selectedRows);
},
getCheckboxProps: (record) => ({
disabled: false,
name: record.id,
}),
};
return (
<>
<Form.Section text={renderHeader()}>
<Table
columns={columns}
dataSource={getCurrentPageData()}
rowSelection={rowSelection}
rowKey='id'
scroll={{ x: 'max-content' }}
pagination={{
currentPage: currentPage,
pageSize: pageSize,
total: apiInfoList.length,
showSizeChanger: true,
showQuickJumper: true,
pageSizeOptions: ['5', '10', '20', '50'],
onChange: (page, size) => {
setCurrentPage(page);
setPageSize(size);
},
onShowSizeChange: (current, size) => {
setCurrentPage(1);
setPageSize(size);
},
}}
size='middle'
loading={loading}
empty={
<Empty
image={
<IllustrationNoResult style={{ width: 150, height: 150 }} />
}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('暂无API信息')}
style={{ padding: 30 }}
/>
}
className='overflow-hidden'
/>
</Form.Section>
<Modal
title={editingApi ? t('编辑API') : t('添加API')}
visible={showApiModal}
onOk={handleSaveApi}
onCancel={() => setShowApiModal(false)}
okText={t('保存')}
cancelText={t('取消')}
confirmLoading={modalLoading}
>
<Form
layout='vertical'
initValues={apiForm}
key={editingApi ? editingApi.id : 'new'}
>
<Form.Input
field='url'
label={t('API地址')}
placeholder='https://api.example.com'
rules={[{ required: true, message: t('请输入API地址') }]}
onChange={(value) => setApiForm({ ...apiForm, url: value })}
/>
<Form.Input
field='route'
label={t('线路描述')}
placeholder={t('如:香港线路')}
rules={[{ required: true, message: t('请输入线路描述') }]}
onChange={(value) => setApiForm({ ...apiForm, route: value })}
/>
<Form.Input
field='description'
label={t('说明')}
placeholder={t('如:大带宽批量分析图片推荐')}
rules={[{ required: true, message: t('请输入说明') }]}
onChange={(value) => setApiForm({ ...apiForm, description: value })}
/>
<Form.Select
field='color'
label={t('标识颜色')}
optionList={colorOptions}
onChange={(value) => setApiForm({ ...apiForm, color: value })}
render={(option) => (
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<Avatar size='extra-extra-small' color={option.value} />
{option.label}
</div>
)}
/>
</Form>
</Modal>
<Modal
title={t('确认删除')}
visible={showDeleteModal}
onOk={confirmDeleteApi}
onCancel={() => {
setShowDeleteModal(false);
setDeletingApi(null);
}}
okText={t('确认删除')}
cancelText={t('取消')}
type='warning'
okButtonProps={{
type: 'danger',
theme: 'solid',
}}
>
<Text>{t('确定要删除此API信息吗?')}</Text>
</Modal>
</>
);
};
export default SettingsAPIInfo;
@@ -0,0 +1,633 @@
/*
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 } from 'react';
import {
Button,
Space,
Table,
Form,
Typography,
Empty,
Divider,
Modal,
Tag,
Switch,
TextArea,
Tooltip,
} from '@douyinfe/semi-ui';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../../components/common/illustrations';
import { Plus, Edit, Trash2, Save, Bell, Maximize2 } from 'lucide-react';
import {
API,
showError,
showSuccess,
getRelativeTime,
formatDateTimeString,
} from '../../../helpers';
import { useTranslation } from 'react-i18next';
const { Text } = Typography;
const SettingsAnnouncements = ({ options, refresh }) => {
const { t } = useTranslation();
const [announcementsList, setAnnouncementsList] = useState([]);
const [showAnnouncementModal, setShowAnnouncementModal] = useState(false);
const [showDeleteModal, setShowDeleteModal] = useState(false);
const [showContentModal, setShowContentModal] = useState(false);
const [deletingAnnouncement, setDeletingAnnouncement] = useState(null);
const [editingAnnouncement, setEditingAnnouncement] = useState(null);
const [modalLoading, setModalLoading] = useState(false);
const [loading, setLoading] = useState(false);
const [hasChanges, setHasChanges] = useState(false);
const [announcementForm, setAnnouncementForm] = useState({
content: '',
publishDate: new Date(),
type: 'default',
extra: '',
});
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const [selectedRowKeys, setSelectedRowKeys] = useState([]);
// 面板启用状态
const [panelEnabled, setPanelEnabled] = useState(true);
const formApiRef = useRef(null);
const typeOptions = [
{ value: 'default', label: t('默认') },
{ value: 'ongoing', label: t('进行中') },
{ value: 'success', label: t('成功') },
{ value: 'warning', label: t('警告') },
{ value: 'error', label: t('错误') },
];
const getTypeColor = (type) => {
const colorMap = {
default: 'grey',
ongoing: 'blue',
success: 'green',
warning: 'orange',
error: 'red',
};
return colorMap[type] || 'grey';
};
const columns = [
{
title: t('内容'),
dataIndex: 'content',
key: 'content',
render: (text) => (
<Tooltip content={text} position='topLeft' showArrow>
<div
style={{
maxWidth: '300px',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
{text}
</div>
</Tooltip>
),
},
{
title: t('发布时间'),
dataIndex: 'publishDate',
key: 'publishDate',
width: 180,
render: (publishDate) => (
<div>
<div style={{ fontWeight: 'bold' }}>
{getRelativeTime(publishDate)}
</div>
<div
style={{
fontSize: '12px',
color: 'var(--semi-color-text-2)',
marginTop: '2px',
}}
>
{publishDate ? formatDateTimeString(new Date(publishDate)) : '-'}
</div>
</div>
),
},
{
title: t('类型'),
dataIndex: 'type',
key: 'type',
width: 100,
render: (type) => (
<Tag color={getTypeColor(type)} shape='circle'>
{typeOptions.find((opt) => opt.value === type)?.label || type}
</Tag>
),
},
{
title: t('说明'),
dataIndex: 'extra',
key: 'extra',
render: (text) => (
<Tooltip content={text || '-'} showArrow>
<div
style={{
maxWidth: '200px',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
color: 'var(--semi-color-text-2)',
}}
>
{text || '-'}
</div>
</Tooltip>
),
},
{
title: t('操作'),
key: 'action',
fixed: 'right',
width: 150,
render: (text, record) => (
<Space>
<Button
icon={<Edit size={14} />}
theme='light'
type='tertiary'
size='small'
onClick={() => handleEditAnnouncement(record)}
>
{t('编辑')}
</Button>
<Button
icon={<Trash2 size={14} />}
type='danger'
theme='light'
size='small'
onClick={() => handleDeleteAnnouncement(record)}
>
{t('删除')}
</Button>
</Space>
),
},
];
const updateOption = async (key, value) => {
const res = await API.put('/api/option/', {
key,
value,
});
const { success, message } = res.data;
if (success) {
showSuccess(t('系统公告已更新'));
if (refresh) refresh();
} else {
showError(message);
}
};
const submitAnnouncements = async () => {
try {
setLoading(true);
const announcementsJson = JSON.stringify(announcementsList);
await updateOption('console_setting.announcements', announcementsJson);
setHasChanges(false);
} catch (error) {
console.error('系统公告更新失败', error);
showError(t('系统公告更新失败'));
} finally {
setLoading(false);
}
};
const handleAddAnnouncement = () => {
setEditingAnnouncement(null);
setAnnouncementForm({
content: '',
publishDate: new Date(),
type: 'default',
extra: '',
});
setShowAnnouncementModal(true);
};
const handleEditAnnouncement = (announcement) => {
setEditingAnnouncement(announcement);
setAnnouncementForm({
content: announcement.content,
publishDate: announcement.publishDate
? new Date(announcement.publishDate)
: new Date(),
type: announcement.type || 'default',
extra: announcement.extra || '',
});
setShowAnnouncementModal(true);
};
const handleDeleteAnnouncement = (announcement) => {
setDeletingAnnouncement(announcement);
setShowDeleteModal(true);
};
const confirmDeleteAnnouncement = () => {
if (deletingAnnouncement) {
const newList = announcementsList.filter(
(item) => item.id !== deletingAnnouncement.id,
);
setAnnouncementsList(newList);
setHasChanges(true);
showSuccess(t('公告已删除,请及时点击“保存设置”进行保存'));
}
setShowDeleteModal(false);
setDeletingAnnouncement(null);
};
const handleSaveAnnouncement = async () => {
if (!announcementForm.content || !announcementForm.publishDate) {
showError(t('请填写完整的公告信息'));
return;
}
try {
setModalLoading(true);
// 将publishDate转换为ISO字符串保存
const formData = {
...announcementForm,
publishDate: announcementForm.publishDate.toISOString(),
};
let newList;
if (editingAnnouncement) {
newList = announcementsList.map((item) =>
item.id === editingAnnouncement.id ? { ...item, ...formData } : item,
);
} else {
const newId =
Math.max(...announcementsList.map((item) => item.id), 0) + 1;
const newAnnouncement = {
id: newId,
...formData,
};
newList = [...announcementsList, newAnnouncement];
}
setAnnouncementsList(newList);
setHasChanges(true);
setShowAnnouncementModal(false);
showSuccess(
editingAnnouncement
? '公告已更新,请及时点击“保存设置”进行保存'
: '公告已添加,请及时点击“保存设置”进行保存',
);
} catch (error) {
showError('操作失败: ' + error.message);
} finally {
setModalLoading(false);
}
};
const parseAnnouncements = (announcementsStr) => {
if (!announcementsStr) {
setAnnouncementsList([]);
return;
}
try {
const parsed = JSON.parse(announcementsStr);
const list = Array.isArray(parsed) ? parsed : [];
// 确保每个项目都有id
const listWithIds = list.map((item, index) => ({
...item,
id: item.id || index + 1,
}));
setAnnouncementsList(listWithIds);
} catch (error) {
console.error('解析系统公告失败:', error);
setAnnouncementsList([]);
}
};
useEffect(() => {
const annStr =
options['console_setting.announcements'] ?? options.Announcements;
if (annStr !== undefined) {
parseAnnouncements(annStr);
}
}, [options['console_setting.announcements'], options.Announcements]);
useEffect(() => {
const enabledStr = options['console_setting.announcements_enabled'];
setPanelEnabled(
enabledStr === undefined
? true
: enabledStr === 'true' || enabledStr === true,
);
}, [options['console_setting.announcements_enabled']]);
const handleToggleEnabled = async (checked) => {
const newValue = checked ? 'true' : 'false';
try {
const res = await API.put('/api/option/', {
key: 'console_setting.announcements_enabled',
value: newValue,
});
if (res.data.success) {
setPanelEnabled(checked);
showSuccess(t('设置已保存'));
refresh?.();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
};
const handleBatchDelete = () => {
if (selectedRowKeys.length === 0) {
showError(t('请先选择要删除的系统公告'));
return;
}
const newList = announcementsList.filter(
(item) => !selectedRowKeys.includes(item.id),
);
setAnnouncementsList(newList);
setSelectedRowKeys([]);
setHasChanges(true);
showSuccess(`已删除 ${selectedRowKeys.length} 个系统公告,请及时点击“保存设置”进行保存`,
);
};
const renderHeader = () => (
<div className='flex flex-col w-full'>
<div className='mb-2'>
<div className='flex items-center text-blue-500'>
<Bell size={16} className='mr-2' />
<Text>
{t(
'系统公告管理,可以发布系统通知和重要消息(最多100个,前端显示最新20条)',
)}
</Text>
</div>
</div>
<Divider margin='12px' />
<div className='flex flex-col md:flex-row justify-between items-center gap-4 w-full'>
<div className='flex gap-2 w-full md:w-auto order-2 md:order-1'>
<Button
theme='light'
type='primary'
icon={<Plus size={14} />}
className='w-full md:w-auto'
onClick={handleAddAnnouncement}
>
{t('添加公告')}
</Button>
<Button
icon={<Trash2 size={14} />}
type='danger'
theme='light'
onClick={handleBatchDelete}
disabled={selectedRowKeys.length === 0}
className='w-full md:w-auto'
>
{t('批量删除')}{' '}
{selectedRowKeys.length > 0 && `(${selectedRowKeys.length})`}
</Button>
<Button
icon={<Save size={14} />}
onClick={submitAnnouncements}
loading={loading}
disabled={!hasChanges}
type='secondary'
className='w-full md:w-auto'
>
{t('保存设置')}
</Button>
</div>
{/* 启用开关 */}
<div className='order-1 md:order-2 flex items-center gap-2'>
<Switch checked={panelEnabled} onChange={handleToggleEnabled} />
<Text>{panelEnabled ? t('已启用') : t('已禁用')}</Text>
</div>
</div>
</div>
);
// 计算当前页显示的数据(按发布时间倒序排序,最新优先显示)
const getCurrentPageData = () => {
const sortedList = [...announcementsList].sort((a, b) => {
const dateA = new Date(a.publishDate).getTime();
const dateB = new Date(b.publishDate).getTime();
return dateB - dateA; // 倒序,最新的排在前面
});
const startIndex = (currentPage - 1) * pageSize;
const endIndex = startIndex + pageSize;
return sortedList.slice(startIndex, endIndex);
};
const rowSelection = {
selectedRowKeys,
onChange: (selectedRowKeys, selectedRows) => {
setSelectedRowKeys(selectedRowKeys);
},
onSelect: (record, selected, selectedRows) => {
console.log(`选择行: ${selected}`, record);
},
onSelectAll: (selected, selectedRows) => {
console.log(`全选: ${selected}`, selectedRows);
},
getCheckboxProps: (record) => ({
disabled: false,
name: record.id,
}),
};
return (
<>
<Form.Section text={renderHeader()}>
<Table
columns={columns}
dataSource={getCurrentPageData()}
rowSelection={rowSelection}
rowKey='id'
scroll={{ x: 'max-content' }}
pagination={{
currentPage: currentPage,
pageSize: pageSize,
total: announcementsList.length,
showSizeChanger: true,
showQuickJumper: true,
pageSizeOptions: ['5', '10', '20', '50'],
onChange: (page, size) => {
setCurrentPage(page);
setPageSize(size);
},
onShowSizeChange: (current, size) => {
setCurrentPage(1);
setPageSize(size);
},
}}
size='middle'
loading={loading}
empty={
<Empty
image={
<IllustrationNoResult style={{ width: 150, height: 150 }} />
}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('暂无系统公告')}
style={{ padding: 30 }}
/>
}
className='overflow-hidden'
/>
</Form.Section>
<Modal
title={editingAnnouncement ? t('编辑公告') : t('添加公告')}
visible={showAnnouncementModal}
onOk={handleSaveAnnouncement}
onCancel={() => setShowAnnouncementModal(false)}
okText={t('保存')}
cancelText={t('取消')}
confirmLoading={modalLoading}
>
<Form
layout='vertical'
initValues={announcementForm}
key={editingAnnouncement ? editingAnnouncement.id : 'new'}
getFormApi={(api) => (formApiRef.current = api)}
>
<Form.TextArea
field='content'
label={t('公告内容')}
placeholder={t('请输入公告内容(支持 Markdown/HTML)')}
maxCount={500}
rows={3}
rules={[{ required: true, message: t('请输入公告内容') }]}
onChange={(value) =>
setAnnouncementForm({ ...announcementForm, content: value })
}
/>
<Button
theme='light'
type='tertiary'
size='small'
icon={<Maximize2 size={14} />}
style={{ marginBottom: 16 }}
onClick={() => setShowContentModal(true)}
>
{t('放大编辑')}
</Button>
<Form.DatePicker
field='publishDate'
label={t('发布日期')}
type='dateTime'
rules={[{ required: true, message: t('请选择发布日期') }]}
onChange={(value) =>
setAnnouncementForm({ ...announcementForm, publishDate: value })
}
/>
<Form.Select
field='type'
label={t('公告类型')}
optionList={typeOptions}
onChange={(value) =>
setAnnouncementForm({ ...announcementForm, type: value })
}
/>
<Form.Input
field='extra'
label={t('说明信息')}
placeholder={t('可选,公告的补充说明')}
onChange={(value) =>
setAnnouncementForm({ ...announcementForm, extra: value })
}
/>
</Form>
</Modal>
<Modal
title={t('确认删除')}
visible={showDeleteModal}
onOk={confirmDeleteAnnouncement}
onCancel={() => {
setShowDeleteModal(false);
setDeletingAnnouncement(null);
}}
okText={t('确认删除')}
cancelText={t('取消')}
type='warning'
okButtonProps={{
type: 'danger',
theme: 'solid',
}}
>
<Text>{t('确定要删除此公告吗?')}</Text>
</Modal>
{/* 公告内容放大编辑 Modal */}
<Modal
title={t('编辑公告内容')}
visible={showContentModal}
onOk={() => {
// 将内容同步到表单
if (formApiRef.current) {
formApiRef.current.setValue('content', announcementForm.content);
}
setShowContentModal(false);
}}
onCancel={() => setShowContentModal(false)}
okText={t('确定')}
cancelText={t('取消')}
width={800}
>
<TextArea
value={announcementForm.content}
placeholder={t('请输入公告内容(支持 Markdown/HTML)')}
maxCount={500}
rows={15}
style={{ width: '100%' }}
onChange={(value) =>
setAnnouncementForm({ ...announcementForm, content: value })
}
/>
</Modal>
</>
);
};
export default SettingsAnnouncements;
@@ -0,0 +1,170 @@
/*
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 } from 'react';
import { Button, Col, Form, Row, Spin } from '@douyinfe/semi-ui';
import {
compareObjects,
API,
showError,
showSuccess,
showWarning,
} from '../../../helpers';
import { useTranslation } from 'react-i18next';
export default function DataDashboard(props) {
const { t } = useTranslation();
const optionsDataExportDefaultTime = [
{ key: 'hour', label: t('小时'), value: 'hour' },
{ key: 'day', label: t('天'), value: 'day' },
{ key: 'week', label: t('周'), value: 'week' },
];
const [loading, setLoading] = useState(false);
const [inputs, setInputs] = useState({
DataExportEnabled: false,
DataExportInterval: '',
DataExportDefaultTime: '',
});
const refForm = useRef();
const [inputsRow, setInputsRow] = useState(inputs);
function onSubmit() {
const updateArray = compareObjects(inputs, inputsRow);
if (!updateArray.length) return showWarning(t('你似乎并没有修改什么'));
const requestQueue = updateArray.map((item) => {
let value = '';
if (typeof inputs[item.key] === 'boolean') {
value = String(inputs[item.key]);
} else {
value = inputs[item.key];
}
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);
});
}
useEffect(() => {
const currentInputs = {};
for (let key in props.options) {
if (Object.keys(inputs).includes(key)) {
currentInputs[key] = props.options[key];
}
}
setInputs(currentInputs);
setInputsRow(structuredClone(currentInputs));
refForm.current.setValues(currentInputs);
localStorage.setItem(
'data_export_default_time',
String(inputs.DataExportDefaultTime),
);
}, [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.Switch
field={'DataExportEnabled'}
label={t('启用数据看板(实验性)')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={(value) => {
setInputs({
...inputs,
DataExportEnabled: value,
});
}}
/>
</Col>
</Row>
<Row>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
label={t('数据看板更新间隔')}
step={1}
min={1}
suffix={t('分钟')}
extraText={t('设置过短会影响数据库性能')}
placeholder={t('数据看板更新间隔')}
field={'DataExportInterval'}
onChange={(value) =>
setInputs({
...inputs,
DataExportInterval: String(value),
})
}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Select
label={t('数据看板默认时间粒度')}
optionList={optionsDataExportDefaultTime}
field={'DataExportDefaultTime'}
extraText={t('仅修改展示粒度,统计精确到小时')}
placeholder={t('数据看板默认时间粒度')}
style={{ width: 180 }}
onChange={(value) =>
setInputs({
...inputs,
DataExportDefaultTime: String(value),
})
}
/>
</Col>
</Row>
<Row>
<Button size='default' onClick={onSubmit}>
{t('保存数据看板设置')}
</Button>
</Row>
</Form.Section>
</Form>
</Spin>
</>
);
}
+489
View File
@@ -0,0 +1,489 @@
/*
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 } from 'react';
import {
Button,
Space,
Table,
Form,
Typography,
Empty,
Divider,
Modal,
Switch,
Tooltip,
} from '@douyinfe/semi-ui';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../../components/common/illustrations';
import { Plus, Edit, Trash2, Save, HelpCircle } from 'lucide-react';
import { API, showError, showSuccess } from '../../../helpers';
import { useTranslation } from 'react-i18next';
const { Text } = Typography;
const SettingsFAQ = ({ options, refresh }) => {
const { t } = useTranslation();
const [faqList, setFaqList] = useState([]);
const [showFaqModal, setShowFaqModal] = useState(false);
const [showDeleteModal, setShowDeleteModal] = useState(false);
const [deletingFaq, setDeletingFaq] = useState(null);
const [editingFaq, setEditingFaq] = useState(null);
const [modalLoading, setModalLoading] = useState(false);
const [loading, setLoading] = useState(false);
const [hasChanges, setHasChanges] = useState(false);
const [faqForm, setFaqForm] = useState({
question: '',
answer: '',
});
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const [selectedRowKeys, setSelectedRowKeys] = useState([]);
// 面板启用状态
const [panelEnabled, setPanelEnabled] = useState(true);
const columns = [
{
title: t('问题标题'),
dataIndex: 'question',
key: 'question',
render: (text) => (
<Tooltip content={text} showArrow>
<div
style={{
maxWidth: '300px',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
fontWeight: 'bold',
}}
>
{text}
</div>
</Tooltip>
),
},
{
title: t('回答内容'),
dataIndex: 'answer',
key: 'answer',
render: (text) => (
<Tooltip content={text} showArrow>
<div
style={{
maxWidth: '400px',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
color: 'var(--semi-color-text-1)',
}}
>
{text}
</div>
</Tooltip>
),
},
{
title: t('操作'),
key: 'action',
fixed: 'right',
width: 150,
render: (text, record) => (
<Space>
<Button
icon={<Edit size={14} />}
theme='light'
type='tertiary'
size='small'
onClick={() => handleEditFaq(record)}
>
{t('编辑')}
</Button>
<Button
icon={<Trash2 size={14} />}
type='danger'
theme='light'
size='small'
onClick={() => handleDeleteFaq(record)}
>
{t('删除')}
</Button>
</Space>
),
},
];
const updateOption = async (key, value) => {
const res = await API.put('/api/option/', {
key,
value,
});
const { success, message } = res.data;
if (success) {
showSuccess(t('常见问答已更新'));
if (refresh) refresh();
} else {
showError(message);
}
};
const submitFAQ = async () => {
try {
setLoading(true);
const faqJson = JSON.stringify(faqList);
await updateOption('console_setting.faq', faqJson);
setHasChanges(false);
} catch (error) {
console.error('常见问答更新失败', error);
showError(t('常见问答更新失败'));
} finally {
setLoading(false);
}
};
const handleAddFaq = () => {
setEditingFaq(null);
setFaqForm({
question: '',
answer: '',
});
setShowFaqModal(true);
};
const handleEditFaq = (faq) => {
setEditingFaq(faq);
setFaqForm({
question: faq.question,
answer: faq.answer,
});
setShowFaqModal(true);
};
const handleDeleteFaq = (faq) => {
setDeletingFaq(faq);
setShowDeleteModal(true);
};
const confirmDeleteFaq = () => {
if (deletingFaq) {
const newList = faqList.filter((item) => item.id !== deletingFaq.id);
setFaqList(newList);
setHasChanges(true);
showSuccess(t('问答已删除,请及时点击“保存设置”进行保存'));
}
setShowDeleteModal(false);
setDeletingFaq(null);
};
const handleSaveFaq = async () => {
if (!faqForm.question || !faqForm.answer) {
showError(t('请填写完整的问答信息'));
return;
}
try {
setModalLoading(true);
let newList;
if (editingFaq) {
newList = faqList.map((item) =>
item.id === editingFaq.id ? { ...item, ...faqForm } : item,
);
} else {
const newId = Math.max(...faqList.map((item) => item.id), 0) + 1;
const newFaq = {
id: newId,
...faqForm,
};
newList = [...faqList, newFaq];
}
setFaqList(newList);
setHasChanges(true);
setShowFaqModal(false);
showSuccess(
editingFaq
? '问答已更新,请及时点击“保存设置”进行保存'
: '问答已添加,请及时点击“保存设置”进行保存',
);
} catch (error) {
showError('操作失败: ' + error.message);
} finally {
setModalLoading(false);
}
};
const parseFAQ = (faqStr) => {
if (!faqStr) {
setFaqList([]);
return;
}
try {
const parsed = JSON.parse(faqStr);
const list = Array.isArray(parsed) ? parsed : [];
// 确保每个项目都有id
const listWithIds = list.map((item, index) => ({
...item,
id: item.id || index + 1,
}));
setFaqList(listWithIds);
} catch (error) {
console.error('解析常见问答失败:', error);
setFaqList([]);
}
};
useEffect(() => {
if (options['console_setting.faq'] !== undefined) {
parseFAQ(options['console_setting.faq']);
}
}, [options['console_setting.faq']]);
useEffect(() => {
const enabledStr = options['console_setting.faq_enabled'];
setPanelEnabled(
enabledStr === undefined
? true
: enabledStr === 'true' || enabledStr === true,
);
}, [options['console_setting.faq_enabled']]);
const handleToggleEnabled = async (checked) => {
const newValue = checked ? 'true' : 'false';
try {
const res = await API.put('/api/option/', {
key: 'console_setting.faq_enabled',
value: newValue,
});
if (res.data.success) {
setPanelEnabled(checked);
showSuccess(t('设置已保存'));
refresh?.();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
};
const handleBatchDelete = () => {
if (selectedRowKeys.length === 0) {
showError(t('请先选择要删除的常见问答'));
return;
}
const newList = faqList.filter(
(item) => !selectedRowKeys.includes(item.id),
);
setFaqList(newList);
setSelectedRowKeys([]);
setHasChanges(true);
showSuccess(`已删除 ${selectedRowKeys.length} 个常见问答,请及时点击“保存设置”进行保存`,
);
};
const renderHeader = () => (
<div className='flex flex-col w-full'>
<div className='mb-2'>
<div className='flex items-center text-blue-500'>
<HelpCircle size={16} className='mr-2' />
<Text>
{t(
'常见问答管理,为用户提供常见问题的答案(最多50个,前端显示最新20条)',
)}
</Text>
</div>
</div>
<Divider margin='12px' />
<div className='flex flex-col md:flex-row justify-between items-center gap-4 w-full'>
<div className='flex gap-2 w-full md:w-auto order-2 md:order-1'>
<Button
theme='light'
type='primary'
icon={<Plus size={14} />}
className='w-full md:w-auto'
onClick={handleAddFaq}
>
{t('添加问答')}
</Button>
<Button
icon={<Trash2 size={14} />}
type='danger'
theme='light'
onClick={handleBatchDelete}
disabled={selectedRowKeys.length === 0}
className='w-full md:w-auto'
>
{t('批量删除')}{' '}
{selectedRowKeys.length > 0 && `(${selectedRowKeys.length})`}
</Button>
<Button
icon={<Save size={14} />}
onClick={submitFAQ}
loading={loading}
disabled={!hasChanges}
type='secondary'
className='w-full md:w-auto'
>
{t('保存设置')}
</Button>
</div>
{/* 启用开关 */}
<div className='order-1 md:order-2 flex items-center gap-2'>
<Switch checked={panelEnabled} onChange={handleToggleEnabled} />
<Text>{panelEnabled ? t('已启用') : t('已禁用')}</Text>
</div>
</div>
</div>
);
// 计算当前页显示的数据
const getCurrentPageData = () => {
const startIndex = (currentPage - 1) * pageSize;
const endIndex = startIndex + pageSize;
return faqList.slice(startIndex, endIndex);
};
const rowSelection = {
selectedRowKeys,
onChange: (selectedRowKeys, selectedRows) => {
setSelectedRowKeys(selectedRowKeys);
},
onSelect: (record, selected, selectedRows) => {
console.log(`选择行: ${selected}`, record);
},
onSelectAll: (selected, selectedRows) => {
console.log(`全选: ${selected}`, selectedRows);
},
getCheckboxProps: (record) => ({
disabled: false,
name: record.id,
}),
};
return (
<>
<Form.Section text={renderHeader()}>
<Table
columns={columns}
dataSource={getCurrentPageData()}
rowSelection={rowSelection}
rowKey='id'
scroll={{ x: 'max-content' }}
pagination={{
currentPage: currentPage,
pageSize: pageSize,
total: faqList.length,
showSizeChanger: true,
showQuickJumper: true,
pageSizeOptions: ['5', '10', '20', '50'],
onChange: (page, size) => {
setCurrentPage(page);
setPageSize(size);
},
onShowSizeChange: (current, size) => {
setCurrentPage(1);
setPageSize(size);
},
}}
size='middle'
loading={loading}
empty={
<Empty
image={
<IllustrationNoResult style={{ width: 150, height: 150 }} />
}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('暂无常见问答')}
style={{ padding: 30 }}
/>
}
className='overflow-hidden'
/>
</Form.Section>
<Modal
title={editingFaq ? t('编辑问答') : t('添加问答')}
visible={showFaqModal}
onOk={handleSaveFaq}
onCancel={() => setShowFaqModal(false)}
okText={t('保存')}
cancelText={t('取消')}
confirmLoading={modalLoading}
width={800}
>
<Form
layout='vertical'
initValues={faqForm}
key={editingFaq ? editingFaq.id : 'new'}
>
<Form.Input
field='question'
label={t('问题标题')}
placeholder={t('请输入问题标题')}
maxLength={200}
rules={[{ required: true, message: t('请输入问题标题') }]}
onChange={(value) => setFaqForm({ ...faqForm, question: value })}
/>
<Form.TextArea
field='answer'
label={t('回答内容')}
placeholder={t('请输入回答内容(支持 Markdown/HTML)')}
maxCount={1000}
rows={6}
rules={[{ required: true, message: t('请输入回答内容') }]}
onChange={(value) => setFaqForm({ ...faqForm, answer: value })}
/>
</Form>
</Modal>
<Modal
title={t('确认删除')}
visible={showDeleteModal}
onOk={confirmDeleteFaq}
onCancel={() => {
setShowDeleteModal(false);
setDeletingFaq(null);
}}
okText={t('确认删除')}
cancelText={t('取消')}
type='warning'
okButtonProps={{
type: 'danger',
theme: 'solid',
}}
>
<Text>{t('确定要删除此问答吗?')}</Text>
</Modal>
</>
);
};
export default SettingsFAQ;
@@ -0,0 +1,521 @@
/*
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 } from 'react';
import {
Button,
Space,
Table,
Form,
Typography,
Empty,
Divider,
Modal,
Switch,
} from '@douyinfe/semi-ui';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../../components/common/illustrations';
import { Plus, Edit, Trash2, Save, Activity } from 'lucide-react';
import { API, showError, showSuccess } from '../../../helpers';
import { useTranslation } from 'react-i18next';
const { Text } = Typography;
const SettingsUptimeKuma = ({ options, refresh }) => {
const { t } = useTranslation();
const [uptimeGroupsList, setUptimeGroupsList] = useState([]);
const [showUptimeModal, setShowUptimeModal] = useState(false);
const [showDeleteModal, setShowDeleteModal] = useState(false);
const [deletingGroup, setDeletingGroup] = useState(null);
const [editingGroup, setEditingGroup] = useState(null);
const [modalLoading, setModalLoading] = useState(false);
const [loading, setLoading] = useState(false);
const [hasChanges, setHasChanges] = useState(false);
const [uptimeForm, setUptimeForm] = useState({
categoryName: '',
url: '',
slug: '',
});
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const [selectedRowKeys, setSelectedRowKeys] = useState([]);
const [panelEnabled, setPanelEnabled] = useState(true);
const columns = [
{
title: t('分类名称'),
dataIndex: 'categoryName',
key: 'categoryName',
render: (text) => (
<div
style={{
fontWeight: 'bold',
color: 'var(--semi-color-text-0)',
}}
>
{text}
</div>
),
},
{
title: t('Uptime Kuma地址'),
dataIndex: 'url',
key: 'url',
render: (text) => (
<div
style={{
maxWidth: '300px',
wordBreak: 'break-all',
fontFamily: 'monospace',
color: 'var(--semi-color-primary)',
}}
>
{text}
</div>
),
},
{
title: t('状态页面Slug'),
dataIndex: 'slug',
key: 'slug',
render: (text) => (
<div
style={{
fontFamily: 'monospace',
color: 'var(--semi-color-text-1)',
}}
>
{text}
</div>
),
},
{
title: t('操作'),
key: 'action',
fixed: 'right',
width: 150,
render: (text, record) => (
<Space>
<Button
icon={<Edit size={14} />}
theme='light'
type='tertiary'
size='small'
onClick={() => handleEditGroup(record)}
>
{t('编辑')}
</Button>
<Button
icon={<Trash2 size={14} />}
type='danger'
theme='light'
size='small'
onClick={() => handleDeleteGroup(record)}
>
{t('删除')}
</Button>
</Space>
),
},
];
const updateOption = async (key, value) => {
const res = await API.put('/api/option/', {
key,
value,
});
const { success, message } = res.data;
if (success) {
showSuccess(t('Uptime Kuma配置已更新'));
if (refresh) refresh();
} else {
showError(message);
}
};
const submitUptimeGroups = async () => {
try {
setLoading(true);
const groupsJson = JSON.stringify(uptimeGroupsList);
await updateOption('console_setting.uptime_kuma_groups', groupsJson);
setHasChanges(false);
} catch (error) {
console.error('Uptime Kuma配置更新失败', error);
showError(t('Uptime Kuma配置更新失败'));
} finally {
setLoading(false);
}
};
const handleAddGroup = () => {
setEditingGroup(null);
setUptimeForm({
categoryName: '',
url: '',
slug: '',
});
setShowUptimeModal(true);
};
const handleEditGroup = (group) => {
setEditingGroup(group);
setUptimeForm({
categoryName: group.categoryName,
url: group.url,
slug: group.slug,
});
setShowUptimeModal(true);
};
const handleDeleteGroup = (group) => {
setDeletingGroup(group);
setShowDeleteModal(true);
};
const confirmDeleteGroup = () => {
if (deletingGroup) {
const newList = uptimeGroupsList.filter(
(item) => item.id !== deletingGroup.id,
);
setUptimeGroupsList(newList);
setHasChanges(true);
showSuccess(t('分类已删除,请及时点击“保存设置”进行保存'));
}
setShowDeleteModal(false);
setDeletingGroup(null);
};
const handleSaveGroup = async () => {
if (!uptimeForm.categoryName || !uptimeForm.url || !uptimeForm.slug) {
showError(t('请填写完整的分类信息'));
return;
}
try {
new URL(uptimeForm.url);
} catch (error) {
showError(t('请输入有效的URL地址'));
return;
}
if (!/^[a-zA-Z0-9_-]+$/.test(uptimeForm.slug)) {
showError(t('Slug只能包含字母、数字、下划线和连字符'));
return;
}
try {
setModalLoading(true);
let newList;
if (editingGroup) {
newList = uptimeGroupsList.map((item) =>
item.id === editingGroup.id ? { ...item, ...uptimeForm } : item,
);
} else {
const newId =
Math.max(...uptimeGroupsList.map((item) => item.id), 0) + 1;
const newGroup = {
id: newId,
...uptimeForm,
};
newList = [...uptimeGroupsList, newGroup];
}
setUptimeGroupsList(newList);
setHasChanges(true);
setShowUptimeModal(false);
showSuccess(
editingGroup
? '分类已更新,请及时点击“保存设置”进行保存'
: '分类已添加,请及时点击“保存设置”进行保存',
);
} catch (error) {
showError('操作失败: ' + error.message);
} finally {
setModalLoading(false);
}
};
const parseUptimeGroups = (groupsStr) => {
if (!groupsStr) {
setUptimeGroupsList([]);
return;
}
try {
const parsed = JSON.parse(groupsStr);
const list = Array.isArray(parsed) ? parsed : [];
const listWithIds = list.map((item, index) => ({
...item,
id: item.id || index + 1,
}));
setUptimeGroupsList(listWithIds);
} catch (error) {
console.error('解析Uptime Kuma配置失败:', error);
setUptimeGroupsList([]);
}
};
useEffect(() => {
const groupsStr = options['console_setting.uptime_kuma_groups'];
if (groupsStr !== undefined) {
parseUptimeGroups(groupsStr);
}
}, [options['console_setting.uptime_kuma_groups']]);
useEffect(() => {
const enabledStr = options['console_setting.uptime_kuma_enabled'];
setPanelEnabled(
enabledStr === undefined
? true
: enabledStr === 'true' || enabledStr === true,
);
}, [options['console_setting.uptime_kuma_enabled']]);
const handleToggleEnabled = async (checked) => {
const newValue = checked ? 'true' : 'false';
try {
const res = await API.put('/api/option/', {
key: 'console_setting.uptime_kuma_enabled',
value: newValue,
});
if (res.data.success) {
setPanelEnabled(checked);
showSuccess(t('设置已保存'));
refresh?.();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
};
const handleBatchDelete = () => {
if (selectedRowKeys.length === 0) {
showError(t('请先选择要删除的分类'));
return;
}
const newList = uptimeGroupsList.filter(
(item) => !selectedRowKeys.includes(item.id),
);
setUptimeGroupsList(newList);
setSelectedRowKeys([]);
setHasChanges(true);
showSuccess(`已删除 ${selectedRowKeys.length} 个分类,请及时点击“保存设置”进行保存`,
);
};
const renderHeader = () => (
<div className='flex flex-col w-full'>
<div className='mb-2'>
<div className='flex items-center text-blue-500'>
<Activity size={16} className='mr-2' />
<Text>
{t(
'Uptime Kuma监控分类管理,可以配置多个监控分类用于服务状态展示(最多20个)',
)}
</Text>
</div>
</div>
<Divider margin='12px' />
<div className='flex flex-col md:flex-row justify-between items-center gap-4 w-full'>
<div className='flex gap-2 w-full md:w-auto order-2 md:order-1'>
<Button
theme='light'
type='primary'
icon={<Plus size={14} />}
className='w-full md:w-auto'
onClick={handleAddGroup}
>
{t('添加分类')}
</Button>
<Button
icon={<Trash2 size={14} />}
type='danger'
theme='light'
onClick={handleBatchDelete}
disabled={selectedRowKeys.length === 0}
className='w-full md:w-auto'
>
{t('批量删除')}{' '}
{selectedRowKeys.length > 0 && `(${selectedRowKeys.length})`}
</Button>
<Button
icon={<Save size={14} />}
onClick={submitUptimeGroups}
loading={loading}
disabled={!hasChanges}
type='secondary'
className='w-full md:w-auto'
>
{t('保存设置')}
</Button>
</div>
{/* 启用开关 */}
<div className='order-1 md:order-2 flex items-center gap-2'>
<Switch checked={panelEnabled} onChange={handleToggleEnabled} />
<Text>{panelEnabled ? t('已启用') : t('已禁用')}</Text>
</div>
</div>
</div>
);
const getCurrentPageData = () => {
const startIndex = (currentPage - 1) * pageSize;
const endIndex = startIndex + pageSize;
return uptimeGroupsList.slice(startIndex, endIndex);
};
const rowSelection = {
selectedRowKeys,
onChange: (selectedRowKeys, selectedRows) => {
setSelectedRowKeys(selectedRowKeys);
},
onSelect: (record, selected, selectedRows) => {
console.log(`选择行: ${selected}`, record);
},
onSelectAll: (selected, selectedRows) => {
console.log(`全选: ${selected}`, selectedRows);
},
getCheckboxProps: (record) => ({
disabled: false,
name: record.id,
}),
};
return (
<>
<Form.Section text={renderHeader()}>
<Table
columns={columns}
dataSource={getCurrentPageData()}
rowSelection={rowSelection}
rowKey='id'
scroll={{ x: 'max-content' }}
pagination={{
currentPage: currentPage,
pageSize: pageSize,
total: uptimeGroupsList.length,
showSizeChanger: true,
showQuickJumper: true,
pageSizeOptions: ['5', '10', '20', '50'],
onChange: (page, size) => {
setCurrentPage(page);
setPageSize(size);
},
onShowSizeChange: (current, size) => {
setCurrentPage(1);
setPageSize(size);
},
}}
size='middle'
loading={loading}
empty={
<Empty
image={
<IllustrationNoResult style={{ width: 150, height: 150 }} />
}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('暂无监控数据')}
style={{ padding: 30 }}
/>
}
className='overflow-hidden'
/>
</Form.Section>
<Modal
title={editingGroup ? t('编辑分类') : t('添加分类')}
visible={showUptimeModal}
onOk={handleSaveGroup}
onCancel={() => setShowUptimeModal(false)}
okText={t('保存')}
cancelText={t('取消')}
confirmLoading={modalLoading}
width={600}
>
<Form
layout='vertical'
initValues={uptimeForm}
key={editingGroup ? editingGroup.id : 'new'}
>
<Form.Input
field='categoryName'
label={t('分类名称')}
placeholder={t('请输入分类名称,如:OpenAI、Claude等')}
maxLength={50}
rules={[{ required: true, message: t('请输入分类名称') }]}
onChange={(value) =>
setUptimeForm({ ...uptimeForm, categoryName: value })
}
/>
<Form.Input
field='url'
label={t('Uptime Kuma地址')}
placeholder={t(
'请输入Uptime Kuma服务地址,如:https://status.example.com',
)}
maxLength={500}
rules={[{ required: true, message: t('请输入Uptime Kuma地址') }]}
onChange={(value) => setUptimeForm({ ...uptimeForm, url: value })}
/>
<Form.Input
field='slug'
label={t('状态页面Slug')}
placeholder={t('请输入状态页面的Slug,如:my-status')}
maxLength={100}
rules={[{ required: true, message: t('请输入状态页面Slug') }]}
onChange={(value) => setUptimeForm({ ...uptimeForm, slug: value })}
/>
</Form>
</Modal>
<Modal
title={t('确认删除')}
visible={showDeleteModal}
onOk={confirmDeleteGroup}
onCancel={() => {
setShowDeleteModal(false);
setDeletingGroup(null);
}}
okText={t('确认删除')}
cancelText={t('取消')}
type='warning'
okButtonProps={{
type: 'danger',
theme: 'solid',
}}
>
<Text>{t('确定要删除此分类吗?')}</Text>
</Modal>
</>
);
};
export default SettingsUptimeKuma;
@@ -0,0 +1,210 @@
/*
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 } from 'react';
import { Button, Col, Form, Row, Spin, Tag } from '@douyinfe/semi-ui';
import {
compareObjects,
API,
showError,
showSuccess,
showWarning,
} from '../../../helpers';
import { useTranslation } from 'react-i18next';
export default function SettingsDrawing(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [inputs, setInputs] = useState({
DrawingEnabled: false,
MjNotifyEnabled: false,
MjAccountFilterEnabled: false,
MjForwardUrlEnabled: false,
MjModeClearEnabled: false,
MjActionCheckSuccessEnabled: false,
});
const refForm = useRef();
const [inputsRow, setInputsRow] = useState(inputs);
function onSubmit() {
const updateArray = compareObjects(inputs, inputsRow);
if (!updateArray.length) return showWarning(t('你似乎并没有修改什么'));
const requestQueue = updateArray.map((item) => {
let value = '';
if (typeof inputs[item.key] === 'boolean') {
value = String(inputs[item.key]);
} else {
value = inputs[item.key];
}
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);
});
}
useEffect(() => {
const currentInputs = {};
for (let key in props.options) {
if (Object.keys(inputs).includes(key)) {
currentInputs[key] = props.options[key];
}
}
setInputs(currentInputs);
setInputsRow(structuredClone(currentInputs));
refForm.current.setValues(currentInputs);
localStorage.setItem('mj_notify_enabled', String(inputs.MjNotifyEnabled));
}, [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.Switch
field={'DrawingEnabled'}
label={t('启用绘图功能')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={(value) => {
setInputs({
...inputs,
DrawingEnabled: value,
});
}}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'MjNotifyEnabled'}
label={t('允许回调(会泄露服务器 IP 地址)')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={(value) =>
setInputs({
...inputs,
MjNotifyEnabled: value,
})
}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'MjAccountFilterEnabled'}
label={t('允许 AccountFilter 参数')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={(value) =>
setInputs({
...inputs,
MjAccountFilterEnabled: value,
})
}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'MjForwardUrlEnabled'}
label={t('开启之后将上游地址替换为服务器地址')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={(value) =>
setInputs({
...inputs,
MjForwardUrlEnabled: value,
})
}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'MjModeClearEnabled'}
label={
<>
{t('开启之后会清除用户提示词中的')} <Tag>--fast</Tag> 、
<Tag>--relax</Tag> {t('以及')} <Tag>--turbo</Tag>{' '}
{t('参数')}
</>
}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={(value) =>
setInputs({
...inputs,
MjModeClearEnabled: value,
})
}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'MjActionCheckSuccessEnabled'}
label={t('检测必须等待绘图成功才能进行放大等操作')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={(value) =>
setInputs({
...inputs,
MjActionCheckSuccessEnabled: value,
})
}
/>
</Col>
</Row>
<Row>
<Button size='default' onClick={onSubmit}>
{t('保存绘图设置')}
</Button>
</Row>
</Form.Section>
</Form>
</Spin>
</>
);
}
@@ -0,0 +1,272 @@
/*
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 } from 'react';
import { Button, Col, Form, Row, Spin } from '@douyinfe/semi-ui';
import {
compareObjects,
API,
showError,
showSuccess,
showWarning,
verifyJSON,
} from '../../../helpers';
import { useTranslation } from 'react-i18next';
import Text from '@douyinfe/semi-ui/lib/es/typography/text';
const CLAUDE_HEADER = {
'claude-3-7-sonnet-20250219-thinking': {
'anthropic-beta': [
'output-128k-2025-02-19',
'token-efficient-tools-2025-02-19',
],
},
};
const CLAUDE_DEFAULT_MAX_TOKENS = {
default: 8192,
'claude-3-haiku-20240307': 4096,
'claude-3-opus-20240229': 4096,
'claude-3-7-sonnet-20250219-thinking': 8192,
};
export default function SettingClaudeModel(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [inputs, setInputs] = useState({
'claude.model_headers_settings': '',
'claude.thinking_adapter_enabled': true,
'claude.default_max_tokens': '',
'claude.thinking_adapter_budget_tokens_percentage': 0.8,
'claude.cache_creation_5m_ratio': 1.25,
'claude.cache_creation_1h_ratio': 2,
});
const refForm = useRef();
const [inputsRow, setInputsRow] = useState(inputs);
function onSubmit() {
const updateArray = compareObjects(inputs, inputsRow);
if (!updateArray.length) return showWarning(t('你似乎并没有修改什么'));
const requestQueue = updateArray.map((item) => {
let value = String(inputs[item.key]);
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('部分保存失败,请重试'));
}
// 后端校验失败返回 200 + success:false(如倍率填了负数),不能误报保存成功
const failed = res.find((r) => !r?.data?.success);
if (failed) {
showError(failed?.data?.message || t('保存失败,请重试'));
props.refresh();
return;
}
showSuccess(t('保存成功'));
props.refresh();
})
.catch(() => {
showError(t('保存失败,请重试'));
})
.finally(() => {
setLoading(false);
});
}
useEffect(() => {
const currentInputs = {};
for (let key in props.options) {
if (Object.keys(inputs).includes(key)) {
currentInputs[key] = 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('Claude设置')}>
<Row>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.TextArea
label={t('Claude请求头覆盖')}
field={'claude.model_headers_settings'}
placeholder={
t('为一个 JSON 文本,例如:') +
'\n' +
JSON.stringify(CLAUDE_HEADER, null, 2)
}
extraText={
t('示例') + '\n' + JSON.stringify(CLAUDE_HEADER, null, 2)
}
autosize={{ minRows: 6, maxRows: 12 }}
trigger='blur'
stopValidateWithError
rules={[
{
validator: (rule, value) => verifyJSON(value),
message: t('不是合法的 JSON 字符串'),
},
]}
onChange={(value) =>
setInputs({
...inputs,
'claude.model_headers_settings': value,
})
}
/>
</Col>
</Row>
<Row>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.TextArea
label={t('缺省 MaxTokens')}
field={'claude.default_max_tokens'}
placeholder={
t('为一个 JSON 文本,例如:') +
'\n' +
JSON.stringify(CLAUDE_DEFAULT_MAX_TOKENS, null, 2)
}
extraText={
t('示例') +
'\n' +
JSON.stringify(CLAUDE_DEFAULT_MAX_TOKENS, null, 2)
}
autosize={{ minRows: 6, maxRows: 12 }}
trigger='blur'
stopValidateWithError
rules={[
{
validator: (rule, value) => verifyJSON(value),
message: t('不是合法的 JSON 字符串'),
},
]}
onChange={(value) =>
setInputs({ ...inputs, 'claude.default_max_tokens': value })
}
/>
</Col>
</Row>
<Row>
<Col span={16}>
<Form.Switch
label={t('启用Claude思考适配(-thinking后缀)')}
field={'claude.thinking_adapter_enabled'}
onChange={(value) =>
setInputs({
...inputs,
'claude.thinking_adapter_enabled': value,
})
}
/>
</Col>
</Row>
<Row>
<Col span={16}>
{/*//展示MaxTokens和BudgetTokens的计算公式, 并展示实际数字*/}
<Text>
{t(
'Claude思考适配 BudgetTokens = MaxTokens * BudgetTokens 百分比',
)}
</Text>
</Col>
</Row>
<Row>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
label={t('思考适配 BudgetTokens 百分比')}
field={'claude.thinking_adapter_budget_tokens_percentage'}
initValue={''}
extraText={t('0.1以上的小数')}
min={0.1}
onChange={(value) =>
setInputs({
...inputs,
'claude.thinking_adapter_budget_tokens_percentage': value,
})
}
/>
</Col>
</Row>
<Row gutter={16}>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
label={t('5分钟缓存创建倍率')}
field={'claude.cache_creation_5m_ratio'}
initValue={''}
extraText={t(
'仅作用于 Claude 模型,相对输入价格的倍率;未区分时长的缓存创建也按此倍率计费',
)}
min={0}
step={0.05}
onChange={(value) =>
setInputs({
...inputs,
'claude.cache_creation_5m_ratio': value,
})
}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
label={t('1小时缓存创建倍率')}
field={'claude.cache_creation_1h_ratio'}
initValue={''}
extraText={t('仅作用于 Claude 模型,相对输入价格的倍率')}
min={0}
step={0.05}
onChange={(value) =>
setInputs({
...inputs,
'claude.cache_creation_1h_ratio': value,
})
}
/>
</Col>
</Row>
<Row>
<Button size='default' onClick={onSubmit}>
{t('保存')}
</Button>
</Row>
</Form.Section>
</Form>
</Spin>
</>
);
}
@@ -0,0 +1,289 @@
/*
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 } from 'react';
import { Button, Col, Form, Row, Spin } from '@douyinfe/semi-ui';
import {
compareObjects,
API,
showError,
showSuccess,
showWarning,
verifyJSON,
} from '../../../helpers';
import { useTranslation } from 'react-i18next';
import Text from '@douyinfe/semi-ui/lib/es/typography/text';
const GEMINI_SETTING_EXAMPLE = {
default: 'OFF',
HARM_CATEGORY_CIVIC_INTEGRITY: 'BLOCK_NONE',
};
const GEMINI_VERSION_EXAMPLE = {
default: 'v1beta',
};
const DEFAULT_GEMINI_INPUTS = {
'gemini.safety_settings': '',
'gemini.version_settings': '',
'gemini.supported_imagine_models': '',
'gemini.thinking_adapter_enabled': false,
'gemini.thinking_adapter_budget_tokens_percentage': 0.6,
'gemini.function_call_thought_signature_enabled': true,
};
export default function SettingGeminiModel(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [inputs, setInputs] = useState(DEFAULT_GEMINI_INPUTS);
const refForm = useRef();
const [inputsRow, setInputsRow] = useState(DEFAULT_GEMINI_INPUTS);
async function onSubmit() {
await refForm.current
.validate()
.then(() => {
const updateArray = compareObjects(inputs, inputsRow);
if (!updateArray.length) return showWarning(t('你似乎并没有修改什么'));
const requestQueue = updateArray.map((item) => {
let value = String(inputs[item.key]);
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);
});
})
.catch((error) => {
console.error('Validation failed:', error);
showError(t('请检查输入'));
});
}
useEffect(() => {
const currentInputs = { ...DEFAULT_GEMINI_INPUTS };
for (let key in props.options) {
if (Object.prototype.hasOwnProperty.call(DEFAULT_GEMINI_INPUTS, key)) {
currentInputs[key] = 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('Gemini设置')}>
<Row>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.TextArea
label={t('Gemini安全设置')}
placeholder={
t('为一个 JSON 文本,例如:') +
'\n' +
JSON.stringify(GEMINI_SETTING_EXAMPLE, null, 2)
}
field={'gemini.safety_settings'}
extraText={t(
'default为默认设置,可单独设置每个分类的安全等级',
)}
autosize={{ minRows: 6, maxRows: 12 }}
trigger='blur'
stopValidateWithError
rules={[
{
validator: (rule, value) => verifyJSON(value),
message: t('不是合法的 JSON 字符串'),
},
]}
onChange={(value) =>
setInputs({ ...inputs, 'gemini.safety_settings': value })
}
/>
</Col>
</Row>
<Row>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.TextArea
label={t('Gemini版本设置')}
placeholder={
t('为一个 JSON 文本,例如:') +
'\n' +
JSON.stringify(GEMINI_VERSION_EXAMPLE, null, 2)
}
field={'gemini.version_settings'}
extraText={t('default为默认设置,可单独设置每个模型的版本')}
autosize={{ minRows: 6, maxRows: 12 }}
trigger='blur'
stopValidateWithError
rules={[
{
validator: (rule, value) => verifyJSON(value),
message: t('不是合法的 JSON 字符串'),
},
]}
onChange={(value) =>
setInputs({ ...inputs, 'gemini.version_settings': value })
}
/>
</Col>
</Row>
<Row>
<Col span={16}>
<Form.Switch
label={t('启用FunctionCall思维签名填充')}
field={'gemini.function_call_thought_signature_enabled'}
extraText={t(
'仅为使用OpenAI格式的Gemini/Vertex渠道填充thoughtSignature',
)}
onChange={(value) =>
setInputs({
...inputs,
'gemini.function_call_thought_signature_enabled': value,
})
}
/>
</Col>
</Row>
<Row>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.TextArea
field={'gemini.supported_imagine_models'}
label={t('支持的图像模型')}
placeholder={
t('例如:') +
'\n' +
JSON.stringify(
['gemini-2.0-flash-exp-image-generation'],
null,
2,
)
}
onChange={(value) =>
setInputs({
...inputs,
'gemini.supported_imagine_models': value,
})
}
trigger='blur'
stopValidateWithError
rules={[
{
validator: (rule, value) => verifyJSON(value),
message: t('不是合法的 JSON 字符串'),
},
]}
/>
</Col>
</Row>
</Form.Section>
<Form.Section text={t('Gemini思考适配设置')}>
<Row>
<Col span={16}>
<Text>
{t(
'和Claude不同,默认情况下Gemini的思考模型会自动决定要不要思考,就算不开启适配模型也可以正常使用,' +
'如果您需要计费,推荐设置无后缀模型价格按思考价格设置。' +
'支持使用 gemini-2.5-pro-preview-06-05-thinking-128 格式来精确传递思考预算。',
)}
</Text>
</Col>
</Row>
<Row>
<Col span={16}>
<Form.Switch
label={t('启用Gemini思考后缀适配')}
field={'gemini.thinking_adapter_enabled'}
extraText={t(
'适配 -thinking、-thinking-预算数字 和 -nothinking 后缀',
)}
onChange={(value) =>
setInputs({
...inputs,
'gemini.thinking_adapter_enabled': value,
})
}
/>
</Col>
</Row>
<Row>
<Col span={16}>
<Text>
{t(
'Gemini思考适配 BudgetTokens = MaxTokens * BudgetTokens 百分比',
)}
</Text>
</Col>
</Row>
<Row>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
label={t('思考预算占比')}
field={'gemini.thinking_adapter_budget_tokens_percentage'}
initValue={''}
extraText={t('0.002-1之间的小数')}
min={0.002}
max={1}
onChange={(value) =>
setInputs({
...inputs,
'gemini.thinking_adapter_budget_tokens_percentage': value,
})
}
/>
</Col>
</Row>
</Form.Section>
<Row>
<Button size='default' onClick={onSubmit}>
{t('保存')}
</Button>
</Row>
</Form>
</Spin>
</>
);
}
@@ -0,0 +1,343 @@
/*
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 } from 'react';
import { Button, Col, Form, Row, Spin, Banner } from '@douyinfe/semi-ui';
import {
compareObjects,
API,
showError,
showSuccess,
showWarning,
verifyJSON,
} from '../../../helpers';
import { useTranslation } from 'react-i18next';
const thinkingExample = JSON.stringify(
['moonshotai/kimi-k2-thinking', 'kimi-k2-thinking'],
null,
2,
);
const defaultGlobalSettingInputs = {
'global.pass_through_request_enabled': false,
'global.thinking_model_blacklist': '[]',
'general_setting.ping_interval_enabled': false,
'general_setting.ping_interval_seconds': 60,
'general_setting.force_responses_models': '',
'general_setting.force_responses_reasoning_summary_enabled': true,
'general_setting.hide_price_enabled': false,
'general_setting.market_curated_only': false,
};
const forceResponsesExample =
'gpt-5-codex\ngpt-5.5\ngpt-5.5-codex\no3-pro\no3-deep-research';
export default function SettingGlobalModel(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [inputs, setInputs] = useState(defaultGlobalSettingInputs);
const refForm = useRef();
const [inputsRow, setInputsRow] = useState(defaultGlobalSettingInputs);
const normalizeValueBeforeSave = (key, value) => {
if (key === 'global.thinking_model_blacklist') {
const text = typeof value === 'string' ? value.trim() : '';
return text === '' ? '[]' : value;
}
return value;
};
function onSubmit() {
const updateArray = compareObjects(inputs, inputsRow);
if (!updateArray.length) return showWarning(t('你似乎并没有修改什么'));
const requestQueue = updateArray.map((item) => {
const normalizedValue = normalizeValueBeforeSave(
item.key,
inputs[item.key],
);
let value = String(normalizedValue);
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);
});
}
useEffect(() => {
const currentInputs = {};
for (const key of Object.keys(defaultGlobalSettingInputs)) {
if (props.options[key] !== undefined) {
let value = props.options[key];
if (key === 'global.thinking_model_blacklist') {
try {
value =
value && String(value).trim() !== ''
? JSON.stringify(JSON.parse(value), null, 2)
: defaultGlobalSettingInputs[key];
} catch (error) {
value = defaultGlobalSettingInputs[key];
}
}
currentInputs[key] = value;
} else {
currentInputs[key] = defaultGlobalSettingInputs[key];
}
}
setInputs(currentInputs);
setInputsRow(structuredClone(currentInputs));
if (refForm.current) {
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>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
label={t('启用请求透传')}
field={'global.pass_through_request_enabled'}
onChange={(value) =>
setInputs({
...inputs,
'global.pass_through_request_enabled': value,
})
}
extraText={t(
'开启后,所有请求将直接透传给上游,不会进行任何处理(重定向和渠道适配也将失效),请谨慎开启',
)}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
label={t('隐藏模型价格')}
field={'general_setting.hide_price_enabled'}
onChange={(value) =>
setInputs({
...inputs,
'general_setting.hide_price_enabled': value,
})
}
extraText={t(
'开启后,定价页与模型详情弹窗将对普通用户和访客隐藏所有模型价格,管理员仍可见',
)}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
label={t('模型超市仅展示已建档模型')}
field={'general_setting.market_curated_only'}
onChange={(value) =>
setInputs({
...inputs,
'general_setting.market_curated_only': value,
})
}
extraText={t(
'开启后,模型超市仅对普通用户展示已在「模型管理」建档且启用的模型,新增渠道模型建档后才上架,管理员仍可见全部',
)}
/>
</Col>
</Row>
<Row>
<Col span={24}>
<Form.TextArea
label={t('禁用思考处理的模型列表')}
field={'global.thinking_model_blacklist'}
placeholder={t('例如:') + '\n' + thinkingExample}
rows={4}
rules={[
{
validator: (rule, value) => {
if (!value || value.trim() === '') return true;
return verifyJSON(value);
},
message: t('不是合法的 JSON 字符串'),
},
]}
extraText={t(
'列出的模型将不会自动添加或移除-thinking/-nothinking 后缀',
)}
onChange={(value) =>
setInputs({
...inputs,
'global.thinking_model_blacklist': value,
})
}
/>
</Col>
</Row>
<Row>
<Col span={24}>
<Banner
type='info'
description={
<div>
<p>
<strong>{t('强制 Responses 协议路由说明:')}</strong>
</p>
<ul style={{ marginLeft: 20, marginTop: 4 }}>
<li>
{t(
'配置后,外部 SDK / Cursor / Codex CLI / Cline 等以 /v1/chat/completions 请求这些模型时,后端会自动透明转换为 /v1/responses 调用上游',
)}
</li>
<li>
{t(
'响应会反向翻译回标准 Chat Completion 格式,客户端零感知',
)}
</li>
<li>
{t('体验中心选用这些模型也会自动走 Responses 协议')}
</li>
<li>
{t(
'匹配规则:模型名包含列表中的任一关键字即命中(与 OpenAIResponseOnlyModels 一致)',
)}
</li>
</ul>
</div>
}
bordered
fullMode={false}
closeIcon={null}
/>
</Col>
</Row>
<Row>
<Col span={24}>
<Form.TextArea
label={t('强制 Responses 协议的模型列表')}
field={'general_setting.force_responses_models'}
placeholder={t('例如:') + '\n' + forceResponsesExample}
rows={4}
extraText={t('多个模型用逗号或换行分隔。留空则该功能不生效')}
onChange={(value) =>
setInputs({
...inputs,
'general_setting.force_responses_models': value,
})
}
/>
</Col>
</Row>
<Row>
<Col span={24}>
<Form.Switch
label={t('转换时返回思考摘要')}
field={
'general_setting.force_responses_reasoning_summary_enabled'
}
onChange={(value) =>
setInputs({
...inputs,
'general_setting.force_responses_reasoning_summary_enabled':
value,
})
}
extraText={t(
'开启后,带推理参数的 Chat 请求转为 Responses 协议时会代为请求思考摘要,并以 reasoning_content 返回;推理力度始终透传,不受此开关影响。渠道不支持思考摘要时(如 OpenAI 组织未认证)会自动去掉摘要重试,并对该渠道暂停请求摘要 1 小时',
)}
/>
</Col>
</Row>
<Form.Section text={t('连接保活设置')}>
<Row style={{ marginTop: 10 }}>
<Col span={24}>
<Banner
type='warning'
description={t(
'警告:启用保活后,如果已经写入保活数据后渠道出错,系统无法重试,如果必须开启,推荐设置尽可能大的Ping间隔',
)}
/>
</Col>
</Row>
<Row>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
label={t('启用Ping间隔')}
field={'general_setting.ping_interval_enabled'}
onChange={(value) =>
setInputs({
...inputs,
'general_setting.ping_interval_enabled': value,
})
}
extraText={t('开启后,将定期发送ping数据保持连接活跃')}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
label={t('Ping间隔(秒)')}
field={'general_setting.ping_interval_seconds'}
onChange={(value) =>
setInputs({
...inputs,
'general_setting.ping_interval_seconds': value,
})
}
min={1}
disabled={!inputs['general_setting.ping_interval_enabled']}
/>
</Col>
</Row>
</Form.Section>
<Row>
<Button size='default' onClick={onSubmit}>
{t('保存')}
</Button>
</Row>
</Form.Section>
</Form>
</Spin>
</>
);
}
@@ -0,0 +1,569 @@
/*
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, useRef, useState } from 'react';
import {
Button,
Col,
Form,
Input,
InputNumber,
Modal,
Popconfirm,
Row,
Space,
Spin,
Switch,
Table,
Tag,
Typography,
} from '@douyinfe/semi-ui';
import { IconDelete, IconEdit, IconPlus } from '@douyinfe/semi-icons';
import { useTranslation } from 'react-i18next';
import { API, showError, showSuccess } from '../../../helpers';
const OPTION_KEY = 'image.image_resolution_pricing';
const MATCH_MODE_OPTIONS = [
{ value: 'exact', label: '精确匹配' },
{ value: 'prefix', label: '前缀匹配' },
];
const RESOLUTION_RULE_OPTIONS = [
{
value: 'manual',
label: '手工别名',
requiredTiers: [],
help: '仅按档位 key 和别名匹配;未命中时使用默认档位。',
},
{
value: 'gpt_image_2',
label: 'GPT Image 2',
requiredTiers: ['1k', '2k', '4k'],
help: '识别官方尺寸及合法自定义宽高,自定义尺寸按总像素向上取档。',
},
{
value: 'gemini',
label: 'Gemini',
requiredTiers: ['1k', '2k', '4k'],
help: '识别 imageSize、官方比例尺寸及自定义宽高。0.5K 按 1K 档计费。',
},
{
value: 'seedream_4_0',
label: 'Seedream 4.0',
requiredTiers: ['1k', '2k', '4k'],
help: '按 Seedream 4.0 官方 1K、2K、4K 尺寸和自定义宽高识别。',
},
{
value: 'seedream_4_5',
label: 'Seedream 4.5',
requiredTiers: ['2k', '4k'],
help: '按 Seedream 4.5 官方 2K、4K 尺寸和自定义宽高识别。',
},
{
value: 'seedream_5_0_pro',
label: 'Seedream 5.0 Pro',
requiredTiers: ['1k', '2k'],
help: '识别 1K、1.5K、2K,1.5K 按 1K 档计费。',
},
{
value: 'seedream_5_0_lite',
label: 'Seedream 5.0 Lite',
requiredTiers: ['2k', '3k', '4k'],
help: '按 Seedream 5.0 Lite 官方 2K、3K、4K 尺寸和自定义宽高识别。',
},
];
const emptyTier = () => ({
key: '',
label: '',
price_per_image: 0,
aliases: '',
});
const normalize = (value) =>
String(value || '')
.trim()
.toLowerCase()
.replaceAll(' ', '');
const parsePricing = (value) => {
try {
const parsed = JSON.parse(value || '[]');
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
};
const resolutionRuleOption = (value) =>
RESOLUTION_RULE_OPTIONS.find((option) => option.value === value) ||
RESOLUTION_RULE_OPTIONS[0];
export default function SettingImagePricing({ options, refresh }) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [configs, setConfigs] = useState([]);
const [modalVisible, setModalVisible] = useState(false);
const [editingIndex, setEditingIndex] = useState(-1);
const [resolutionRule, setResolutionRule] = useState('manual');
const [tierRows, setTierRows] = useState([emptyTier()]);
const formRef = useRef();
useEffect(() => {
setConfigs(parsePricing(options?.[OPTION_KEY]));
}, [options]);
const save = async (next) => {
setLoading(true);
try {
const response = await API.put('/api/option/', {
key: OPTION_KEY,
value: JSON.stringify(next),
});
if (!response.data.success) {
showError(response.data.message || t('保存失败'));
return false;
}
setConfigs(next);
showSuccess(t('保存成功'));
refresh();
return true;
} catch (error) {
showError(error?.response?.data?.message || t('保存失败,请重试'));
return false;
} finally {
setLoading(false);
}
};
const openAdd = () => {
setEditingIndex(-1);
setResolutionRule('manual');
setTierRows([emptyTier()]);
setModalVisible(true);
setTimeout(() => {
formRef.current?.setValues({
model_name: '',
match_mode: 'exact',
resolution_rule: 'manual',
default_tier: '',
enabled: true,
});
}, 0);
};
const openEdit = (record, index) => {
const nextResolutionRule = record.resolution_rule || 'manual';
setEditingIndex(index);
setResolutionRule(nextResolutionRule);
setTierRows(
(record.tiers || []).map((tier) => ({
key: tier.key || '',
label: tier.label || '',
price_per_image: tier.price_per_image || 0,
aliases: Array.isArray(tier.aliases) ? tier.aliases.join(',') : '',
})),
);
setModalVisible(true);
setTimeout(() => {
formRef.current?.setValues({
model_name: record.model_name || '',
match_mode: record.match_mode || 'exact',
resolution_rule: nextResolutionRule,
default_tier: record.default_tier || '',
enabled: record.enabled !== false,
});
}, 0);
};
const updateTier = (index, patch) => {
setTierRows((rows) =>
rows.map((row, rowIndex) =>
rowIndex === index ? { ...row, ...patch } : row,
),
);
};
const buildConfig = (values) => {
const modelName = String(values.model_name || '').trim();
if (
configs.some(
(config, index) =>
index !== editingIndex &&
normalize(config.model_name) === normalize(modelName),
)
) {
showError(t('该模型已配置图片分档计费'));
return null;
}
if (tierRows.length === 0 || tierRows.some((row) => !normalize(row.key))) {
showError(t('每个档位都必须填写档位 key'));
return null;
}
const tiers = tierRows.map((row) => ({
key: String(row.key).trim(),
label: String(row.label || row.key).trim(),
price_per_image: Number(row.price_per_image),
aliases: String(row.aliases || '')
.split(',')
.map((alias) => alias.trim())
.filter(Boolean),
}));
if (tiers.some((tier) => !(tier.price_per_image > 0))) {
showError(t('每个档位的每张单价必须大于 0'));
return null;
}
const seen = new Set();
for (const tier of tiers) {
for (const matchValue of [tier.key, ...tier.aliases]) {
const key = normalize(matchValue);
if (seen.has(key)) {
showError(t('同一模型内的档位 key 和别名不能重复'));
return null;
}
seen.add(key);
}
}
const selectedRule = values.resolution_rule || 'manual';
const missingTier = resolutionRuleOption(selectedRule).requiredTiers.find(
(requiredTier) =>
!tiers.some((tier) => normalize(tier.key) === requiredTier),
);
if (missingTier) {
showError(t('当前识别规则要求配置 {{tier}} 档位', { tier: missingTier }));
return null;
}
const defaultTier = String(values.default_tier || tiers[0].key).trim();
if (!tiers.some((tier) => normalize(tier.key) === normalize(defaultTier))) {
showError(t('默认档位必须填写一个已有的档位 key'));
return null;
}
return {
model_name: modelName,
match_mode: values.match_mode || 'exact',
resolution_rule: selectedRule,
enabled: values.enabled !== false,
default_tier: defaultTier,
tiers,
};
};
const submit = () => {
formRef.current
?.validate()
.then(async (values) => {
const config = buildConfig(values);
if (!config) return;
const next = [...configs];
if (editingIndex >= 0) {
next[editingIndex] = config;
} else {
next.push(config);
}
if (await save(next)) setModalVisible(false);
})
.catch(() => {});
};
const remove = async (index) => {
const next = configs.filter((_, configIndex) => configIndex !== index);
await save(next);
};
const toggle = async (index, enabled) => {
const next = configs.map((config, configIndex) =>
configIndex === index ? { ...config, enabled } : config,
);
await save(next);
};
const columns = [
{
title: t('模型名称'),
dataIndex: 'model_name',
key: 'model_name',
},
{
title: t('匹配方式'),
dataIndex: 'match_mode',
key: 'match_mode',
render: (matchMode) =>
t(matchMode === 'prefix' ? '前缀匹配' : '精确匹配'),
},
{
title: t('识别规则'),
dataIndex: 'resolution_rule',
key: 'resolution_rule',
render: (rule) => t(resolutionRuleOption(rule || 'manual').label),
},
{
title: t('默认档位'),
dataIndex: 'default_tier',
key: 'default_tier',
},
{
title: t('分辨率档位'),
dataIndex: 'tiers',
key: 'tiers',
render: (tiers) => (
<Space wrap>
{(tiers || []).map((tier) => (
<Tag key={tier.key} color='blue'>
{`${tier.label || tier.key}: $${tier.price_per_image}/张`}
</Tag>
))}
</Space>
),
},
{
title: t('启用'),
dataIndex: 'enabled',
key: 'enabled',
render: (enabled, _record, index) => (
<Switch
checked={enabled !== false}
onChange={(checked) => toggle(index, checked)}
aria-label={t('启用图片分档计费')}
/>
),
},
{
title: t('操作'),
key: 'action',
width: 110,
render: (_text, record, index) => (
<Space>
<Button
icon={<IconEdit />}
size='small'
theme='borderless'
aria-label={t('编辑')}
onClick={() => openEdit(record, index)}
/>
<Popconfirm
title={t('确定删除此图片定价配置吗?')}
onConfirm={() => remove(index)}
>
<Button
icon={<IconDelete />}
size='small'
type='danger'
theme='borderless'
aria-label={t('删除')}
/>
</Popconfirm>
</Space>
),
},
];
const currentRule = resolutionRuleOption(resolutionRule);
return (
<Spin spinning={loading}>
<Form>
<Form.Section text={t('图片分辨率分档计费')}>
<Typography.Text type='tertiary'>
{t(
'仅已启用且匹配的模型按分辨率档位计费,未配置模型继续使用现有固定价格或模型倍率。单价单位为美元/张,最终费用仍乘分组倍率。',
)}
</Typography.Text>
<div style={{ marginTop: 12, marginBottom: 12 }}>
<Button icon={<IconPlus />} onClick={openAdd}>
{t('添加图片计费模型')}
</Button>
</div>
<Table
columns={columns}
dataSource={configs}
rowKey={(record, index) => `${record.model_name}-${index}`}
pagination={false}
empty={t('暂无图片分档计费配置')}
/>
</Form.Section>
</Form>
<Modal
title={editingIndex >= 0 ? t('编辑图片定价') : t('添加图片定价')}
visible={modalVisible}
onOk={submit}
onCancel={() => setModalVisible(false)}
okText={t('保存')}
cancelText={t('取消')}
width={760}
confirmLoading={loading}
>
<Form
getFormApi={(formApi) => (formRef.current = formApi)}
initValues={{
model_name: '',
match_mode: 'exact',
resolution_rule: 'manual',
default_tier: '',
enabled: true,
}}
>
<Form.Input
field='model_name'
label={t('模型名称')}
placeholder={t('例如 gpt-image-2-count')}
rules={[{ required: true, message: t('请输入模型名称') }]}
extraText={t('填写平台对外暴露的模型名称。')}
/>
<Row gutter={12}>
<Col span={12}>
<Form.Select
field='match_mode'
label={t('模型匹配方式')}
extraText={t('精确匹配不会影响同名前缀的其他模型。')}
>
{MATCH_MODE_OPTIONS.map((option) => (
<Form.Select.Option key={option.value} value={option.value}>
{t(option.label)}
</Form.Select.Option>
))}
</Form.Select>
</Col>
<Col span={12}>
<Form.Select
field='resolution_rule'
label={t('分辨率识别规则')}
onChange={(value) => setResolutionRule(value)}
extraText={t(currentRule.help)}
>
{RESOLUTION_RULE_OPTIONS.map((option) => (
<Form.Select.Option key={option.value} value={option.value}>
{option.label}
</Form.Select.Option>
))}
</Form.Select>
</Col>
</Row>
<Form.Input
field='default_tier'
label={t('默认档位')}
placeholder={t('留空时使用第一个档位')}
extraText={t(
'请求未提供尺寸或传入 auto 时使用;自动规则下,非法的显式尺寸会直接返回 invalid_size。',
)}
/>
<Form.Switch field='enabled' label={t('启用')} />
</Form>
<div
style={{
marginTop: 8,
padding: '8px 12px',
borderRadius: 6,
background: 'var(--semi-color-fill-0)',
color: 'var(--semi-color-text-2)',
fontSize: 12,
lineHeight: 1.6,
}}
>
<div>
{currentRule.requiredTiers.length > 0
? t('当前规则必须配置档位:{{tiers}}', {
tiers: currentRule.requiredTiers.join('、'),
})
: t('手工规则可自定义档位 key,并通过别名匹配请求尺寸。')}
</div>
<div>
{t('别名始终优先于自动识别,可用于覆盖个别尺寸的计费档位。')}
</div>
<div>{t('自定义宽高按总像素向上取最近档位,避免低档计费。')}</div>
</div>
<div style={{ marginTop: 14 }}>
<Typography.Text strong>{t('档位列表')}</Typography.Text>
{tierRows.map((row, index) => (
<Row
key={index}
gutter={8}
type='flex'
align='middle'
style={{ marginTop: 8 }}
>
<Col span={5}>
<Input
value={row.key}
placeholder={t('档位 key')}
onChange={(value) => updateTier(index, { key: value })}
/>
</Col>
<Col span={5}>
<Input
value={row.label}
placeholder={t('显示名称')}
onChange={(value) => updateTier(index, { label: value })}
/>
</Col>
<Col span={5}>
<InputNumber
value={row.price_per_image}
placeholder={t('单价/张')}
prefix='$'
min={0}
step={0.01}
style={{ width: '100%' }}
onChange={(value) =>
updateTier(index, { price_per_image: value })
}
/>
</Col>
<Col span={7}>
<Input
value={row.aliases}
placeholder={t('别名,英文逗号分隔')}
onChange={(value) => updateTier(index, { aliases: value })}
/>
</Col>
<Col span={2}>
<Button
icon={<IconDelete />}
size='small'
type='danger'
theme='borderless'
disabled={tierRows.length === 1}
aria-label={t('删除档位')}
onClick={() =>
setTierRows((rows) =>
rows.filter((_, rowIndex) => rowIndex !== index),
)
}
/>
</Col>
</Row>
))}
<Button
icon={<IconPlus />}
size='small'
style={{ marginTop: 10 }}
onClick={() => setTierRows((rows) => [...rows, emptyTier()])}
>
{t('添加档位')}
</Button>
</div>
</Modal>
</Spin>
);
}
@@ -0,0 +1,500 @@
/*
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 } from 'react';
import {
Button,
Table,
Modal,
Form,
Space,
Typography,
Tabs,
TabPane,
Popconfirm,
Select,
Empty,
Spin,
} from '@douyinfe/semi-ui';
import { IconPlus } from '@douyinfe/semi-icons';
import { API, showError, showSuccess } from '../../../helpers';
import { useTranslation } from 'react-i18next';
const { Title, Text } = Typography;
const SettingModelCategory = () => {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [level1Categories, setLevel1Categories] = useState([]);
const [level2Categories, setLevel2Categories] = useState([]);
const [allLevel2Categories, setAllLevel2Categories] = useState([]);
// 模态框相关
const [modalVisible, setModalVisible] = useState(false);
const [editingCategory, setEditingCategory] = useState(null);
const [isLevel1Modal, setIsLevel1Modal] = useState(true);
// 二级分类选择的一级分类
const [selectedLevel1Id, setSelectedLevel1Id] = useState(null);
const loadCategories = async () => {
setLoading(true);
try {
const res = await API.get('/api/model_categories/flat');
const { success, data, message } = res.data;
if (success) {
const categoriesData = data || [];
// 分离一级和二级分类
const level1 = categoriesData.filter((cat) => cat.parent_id === 0);
const level2 = categoriesData.filter((cat) => cat.parent_id !== 0);
setLevel1Categories(level1);
setAllLevel2Categories(level2);
// 如果已选择一级分类,更新二级分类列表
if (selectedLevel1Id) {
const filteredLevel2 = level2.filter(
(cat) => cat.parent_id === selectedLevel1Id,
);
setLevel2Categories(filteredLevel2);
}
} else {
showError(message || t('加载分类失败'));
}
} catch (error) {
showError(t('加载分类失败: ') + error.message);
} finally {
setLoading(false);
}
};
useEffect(() => {
loadCategories();
}, []);
// 选择一级分类时更新二级分类列表
const handleLevel1Select = (value) => {
setSelectedLevel1Id(value);
const filteredLevel2 = allLevel2Categories.filter(
(cat) => cat.parent_id === value,
);
setLevel2Categories(filteredLevel2);
};
// 打开新建一级分类模态框
const handleAddLevel1 = () => {
setIsLevel1Modal(true);
setEditingCategory({
id: 0,
parent_id: 0,
category_name: '',
category_key: '',
description: '',
sort: 0,
status: 1,
});
setModalVisible(true);
};
// 打开编辑一级分类模态框
const handleEditLevel1 = (category) => {
setIsLevel1Modal(true);
setEditingCategory({ ...category });
setModalVisible(true);
};
// 打开新建二级分类模态框
const handleAddLevel2 = () => {
if (!selectedLevel1Id) {
showError(t('请先选择一级分类'));
return;
}
// 找到选中的一级分类名称
const selectedLevel1 = level1Categories.find(
(cat) => cat.id === selectedLevel1Id,
);
setIsLevel1Modal(false);
setEditingCategory({
id: 0,
parent_id: selectedLevel1Id,
parent_category_name: selectedLevel1?.category_name || '',
category_name: '',
category_key: '',
description: '',
sort: 0,
status: 1,
});
setModalVisible(true);
};
// 打开编辑二级分类模态框
const handleEditLevel2 = (category) => {
setIsLevel1Modal(false);
setEditingCategory({ ...category });
setModalVisible(true);
};
// 保存分类
const handleSave = async (values) => {
try {
let res;
if (editingCategory.id === 0) {
// 创建
res = await API.post('/api/model_categories/', values);
} else {
// 更新
res = await API.put('/api/model_categories/', {
...values,
id: editingCategory.id,
});
}
const { success, message } = res.data;
if (success) {
showSuccess(editingCategory.id === 0 ? t('创建成功') : t('保存成功'));
setModalVisible(false);
await loadCategories();
} else {
showError(
message || (editingCategory.id === 0 ? t('创建失败') : t('保存失败')),
);
}
} catch (error) {
showError(
(editingCategory.id === 0 ? t('创建失败: ') : t('保存失败: ')) +
error.message,
);
}
};
// 删除分类
const handleDelete = async (id) => {
try {
const res = await API.delete(`/api/model_categories/${id}`);
const { success, message } = res.data;
if (success) {
showSuccess(t('删除成功'));
await loadCategories();
} else {
showError(message || t('删除失败'));
}
} catch (error) {
showError(t('删除失败: ') + error.message);
}
};
// 重置分类
const handleReset = async () => {
try {
const res = await API.post('/api/model_categories/reset');
const { success, message } = res.data;
if (success) {
showSuccess(t('分类已重置为默认配置'));
await loadCategories();
} else {
showError(message || t('重置失败'));
}
} catch (error) {
showError(t('重置失败: ') + error.message);
}
};
// 一级分类表格列
const level1Columns = [
{
title: t('分类名称'),
dataIndex: 'category_name',
width: 150,
},
{
title: t('分类标识'),
dataIndex: 'category_key',
width: 150,
},
{
title: t('描述'),
dataIndex: 'description',
},
{
title: t('排序'),
dataIndex: 'sort',
width: 80,
},
{
title: t('操作'),
dataIndex: 'operate',
width: 150,
render: (text, record) => (
<Space>
<Button size='small' onClick={() => handleEditLevel1(record)}>
{t('修改')}
</Button>
<Popconfirm
title={t('确定要删除这个分类吗?')}
content={t('删除前请确保已删除其下的所有二级分类')}
onConfirm={() => handleDelete(record.id)}
okText={t('确定')}
cancelText={t('取消')}
>
<Button size='small' type='danger'>
{t('删除')}
</Button>
</Popconfirm>
</Space>
),
},
];
// 二级分类表格列
const level2Columns = [
{
title: t('分类名称'),
dataIndex: 'category_name',
width: 150,
},
{
title: t('分类标识'),
dataIndex: 'category_key',
width: 150,
},
{
title: t('描述'),
dataIndex: 'description',
},
{
title: t('排序'),
dataIndex: 'sort',
width: 80,
},
{
title: t('操作'),
dataIndex: 'operate',
width: 150,
render: (text, record) => (
<Space>
<Button size='small' onClick={() => handleEditLevel2(record)}>
{t('修改')}
</Button>
<Popconfirm
title={t('确定要删除这个分类吗?')}
content={t('此操作不可恢复')}
onConfirm={() => handleDelete(record.id)}
okText={t('确定')}
cancelText={t('取消')}
>
<Button size='small' type='danger'>
{t('删除')}
</Button>
</Popconfirm>
</Space>
),
},
];
return (
<Spin spinning={loading}>
<div>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 16,
}}
>
<div>
<Title heading={5}>{t('模型分类管理')}</Title>
<Text type='tertiary'>
{t('管理模型的一级分类和二级分类,用于模型标签化管理')}
</Text>
</div>
<Popconfirm
title={t('确定要重置分类吗?')}
content={t('这将删除所有自定义分类并恢复为默认配置')}
onConfirm={handleReset}
okText={t('确定')}
cancelText={t('取消')}
>
<Button type='tertiary'>{t('重置为默认分类')}</Button>
</Popconfirm>
</div>
<Tabs type='line'>
{/* 一级分类 */}
<TabPane tab={t('一级分类')} itemKey='level1'>
<div
style={{
display: 'flex',
justifyContent: 'flex-end',
marginBottom: 16,
}}
>
<Button
type='primary'
icon={<IconPlus />}
onClick={handleAddLevel1}
>
{t('新建')}
</Button>
</div>
<Table
// 列宽合计远超窄屏视口;没有 scroll 时表格会压缩到 min-content 硬塞进去,
// 末尾的操作列落在视口外,且 iOS 上滚动条不可见、毫无可拖动提示
scroll={{ x: 'max-content' }}
columns={level1Columns}
dataSource={level1Categories}
rowKey='id'
pagination={false}
empty={<Empty description={t('暂无数据')} />}
/>
</TabPane>
{/* 二级分类 */}
<TabPane tab={t('二级分类')} itemKey='level2'>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 16,
}}
>
<div style={{ flex: 1, maxWidth: 300 }}>
<Select
placeholder={t('选择一级分类')}
value={selectedLevel1Id}
onChange={handleLevel1Select}
style={{ width: '100%' }}
>
{level1Categories.map((cat) => (
<Select.Option key={cat.id} value={cat.id}>
{cat.category_name}
</Select.Option>
))}
</Select>
</div>
<Button
type='primary'
icon={<IconPlus />}
onClick={handleAddLevel2}
disabled={!selectedLevel1Id}
>
{t('新建二级分类')}
</Button>
</div>
{selectedLevel1Id ? (
<Table
// 列宽合计远超窄屏视口;没有 scroll 时表格会压缩到 min-content 硬塞进去,
// 末尾的操作列落在视口外,且 iOS 上滚动条不可见、毫无可拖动提示
scroll={{ x: 'max-content' }}
columns={level2Columns}
dataSource={level2Categories}
rowKey='id'
pagination={false}
empty={<Empty description={t('暂无数据')} />}
/>
) : (
<Empty description={t('请先选择一级分类')} />
)}
</TabPane>
</Tabs>
{/* 编辑/新建模态框 */}
<Modal
title={
editingCategory?.id === 0
? isLevel1Modal
? t('新建一级分类')
: t('新建二级分类')
: isLevel1Modal
? t('编辑一级分类')
: t('编辑二级分类')
}
visible={modalVisible}
onCancel={() => setModalVisible(false)}
footer={null}
width={600}
>
<Form
initValues={editingCategory}
onSubmit={(values) => handleSave(values)}
labelPosition='left'
labelWidth='120px'
>
{!isLevel1Modal && (
<Form.Input
field='parent_category_name'
label={t('一级分类')}
disabled
style={{ width: '100%' }}
/>
)}
<Form.Input
field='category_name'
label={t('分类名称')}
placeholder={
isLevel1Modal ? t('例如:文本模型') : t('例如:文本生成')
}
rules={[{ required: true, message: t('请输入分类名称') }]}
style={{ width: '100%' }}
/>
<Form.Input
field='category_key'
label={t('分类标识')}
placeholder={
isLevel1Modal ? t('例如:text') : t('例如:text_generation')
}
rules={[{ required: true, message: t('请输入分类标识') }]}
extraText={t('唯一标识,只能包含字母、数字和下划线')}
style={{ width: '100%' }}
/>
<Form.TextArea
field='description'
label={t('描述')}
placeholder={t('分类的详细描述')}
autosize={{ minRows: 2, maxRows: 4 }}
style={{ width: '100%' }}
/>
<Form.InputNumber
field='sort'
label={t('排序')}
placeholder={t('数字越小越靠前')}
style={{ width: '100%' }}
/>
<Form.Input field='parent_id' noLabel style={{ display: 'none' }} />
<div
style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}
>
<Button onClick={() => setModalVisible(false)}>
{t('取消')}
</Button>
<Button type='primary' htmlType='submit'>
{editingCategory?.id === 0 ? t('创建') : t('保存')}
</Button>
</div>
</Form>
</Modal>
</div>
</Spin>
);
};
export default SettingModelCategory;
@@ -0,0 +1,905 @@
/*
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 } from 'react';
import {
Button,
Col,
Form,
Row,
Spin,
Table,
Modal,
Tag,
Popconfirm,
Space,
Input,
InputNumber,
Switch,
Typography,
} from '@douyinfe/semi-ui';
import { IconPlus, IconDelete, IconEdit } from '@douyinfe/semi-icons';
import {
API,
showError,
showSuccess,
} from '../../../helpers';
import { useTranslation } from 'react-i18next';
// 视频相关的渠道类型
const VIDEO_CHANNEL_TYPES = [
{ value: 1, label: 'OpenAI', provider: 'openai' },
{ value: 17, label: '阿里通义', provider: 'ali' },
{ value: 35, label: 'MiniMax/Hailuo', provider: 'hailuo' },
{ value: 54, label: '豆包视频', provider: 'doubao' },
{ value: 55, label: 'Sora', provider: 'sora' },
];
// 提供商选项
const PROVIDER_OPTIONS = [
{ value: 'openai', label: 'OpenAI 兼容' },
{ value: 'ali', label: '阿里云' },
{ value: 'hailuo', label: 'Hailuo/MiniMax' },
{ value: 'doubao', label: '豆包' },
{ value: 'sora', label: 'Sora' },
];
const defaultVideoModelInputs = {
'video.custom_video_models': '[]',
'video.video_second_pricing': '[]',
'video.asset_library_user_limit': 50,
'video.real_portrait_enabled': false,
};
// 按秒分档:选档字段选项
const TIER_PARAM_OPTIONS = [
{ value: 'resolution', label: '分辨率 (resolution)' },
{ value: 'mode', label: '模式 (mode)' },
{ value: 'size', label: '尺寸 (size)' },
];
export default function SettingVideoModel(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [, setInputs] = useState(defaultVideoModelInputs);
const [models, setModels] = useState([]);
const [modalVisible, setModalVisible] = useState(false);
const [editingModel, setEditingModel] = useState(null);
const [editingIndex, setEditingIndex] = useState(-1);
const modalFormRef = useRef();
// 解析模型列表
const parseModels = (jsonStr) => {
try {
if (!jsonStr || jsonStr === '[]') return [];
return JSON.parse(jsonStr);
} catch (e) {
return [];
}
};
// 序列化模型列表
const serializeModels = (modelList) => {
return JSON.stringify(modelList);
};
// 保存到服务器
const saveToServer = async (modelList) => {
setLoading(true);
try {
const value = serializeModels(modelList);
const res = await API.put('/api/option/', {
key: 'video.custom_video_models',
value,
});
if (res.data.success) {
showSuccess(t('保存成功'));
props.refresh();
} else {
showError(res.data.message || t('保存失败'));
}
} catch (e) {
showError(t('保存失败,请重试'));
} finally {
setLoading(false);
}
};
// 添加模型
const handleAddModel = () => {
setEditingModel(null);
setEditingIndex(-1);
setModalVisible(true);
};
// 编辑模型
const handleEditModel = (record, index) => {
setEditingModel(record);
setEditingIndex(index);
setModalVisible(true);
};
// 删除模型
const handleDeleteModel = (index) => {
const newModels = [...models];
newModels.splice(index, 1);
setModels(newModels);
saveToServer(newModels);
};
// 切换启用状态
const handleToggleEnabled = (index) => {
const newModels = [...models];
newModels[index].enabled = !newModels[index].enabled;
setModels(newModels);
saveToServer(newModels);
};
// 提交模型表单
const handleModalOk = () => {
modalFormRef.current.validate().then((values) => {
const newModel = {
model_name: values.model_name,
provider: values.provider,
channel_type: values.channel_type,
supports_i2v: values.supports_i2v || false,
enabled: values.enabled !== false,
endpoint: values.endpoint || '',
};
const newModels = [...models];
if (editingIndex >= 0) {
newModels[editingIndex] = newModel;
} else {
newModels.push(newModel);
}
setModels(newModels);
saveToServer(newModels);
setModalVisible(false);
});
};
// 根据 provider 自动设置 channel_type
const handleProviderChange = (value) => {
const channelType = VIDEO_CHANNEL_TYPES.find((c) => c.provider === value);
if (channelType && modalFormRef.current) {
modalFormRef.current.setValue('channel_type', channelType.value);
}
};
// ===== 视频按秒分档定价 =====
const [pricingConfigs, setPricingConfigs] = useState([]);
const [pricingModalVisible, setPricingModalVisible] = useState(false);
const [editingPricingIndex, setEditingPricingIndex] = useState(-1);
const [tierRows, setTierRows] = useState([]);
const pricingFormRef = useRef();
const savePricingToServer = async (list) => {
setLoading(true);
try {
const res = await API.put('/api/option/', {
key: 'video.video_second_pricing',
value: JSON.stringify(list),
});
if (res.data.success) {
showSuccess(t('保存成功'));
props.refresh();
} else {
showError(res.data.message || t('保存失败'));
}
} catch (e) {
showError(t('保存失败,请重试'));
} finally {
setLoading(false);
}
};
const handleAddPricing = () => {
setEditingPricingIndex(-1);
setTierRows([{ key: '', label: '', price_per_second: 0, aliases: '' }]);
setPricingModalVisible(true);
};
const handleEditPricing = (record, index) => {
setEditingPricingIndex(index);
setTierRows(
(record.tiers || []).map((tier) => ({
key: tier.key || '',
label: tier.label || '',
price_per_second: tier.price_per_second || 0,
aliases: Array.isArray(tier.aliases) ? tier.aliases.join(',') : '',
})),
);
setPricingModalVisible(true);
// 表单初值通过 initValues 设置,这里延迟回填以确保 formApi 就绪
setTimeout(() => {
if (pricingFormRef.current) {
pricingFormRef.current.setValues({
model_name: record.model_name,
tier_param: record.tier_param || 'resolution',
default_tier: record.default_tier || '',
default_duration: record.default_duration || undefined,
enabled: record.enabled !== false,
});
}
}, 0);
};
const handleDeletePricing = (index) => {
const next = [...pricingConfigs];
next.splice(index, 1);
setPricingConfigs(next);
savePricingToServer(next);
};
const handleTogglePricingEnabled = (index) => {
const next = [...pricingConfigs];
next[index] = { ...next[index], enabled: !next[index].enabled };
setPricingConfigs(next);
savePricingToServer(next);
};
const updateTierRow = (idx, patch) => {
setTierRows((rows) =>
rows.map((r, i) => (i === idx ? { ...r, ...patch } : r)),
);
};
const addTierRow = () => {
setTierRows((rows) => [
...rows,
{ key: '', label: '', price_per_second: 0, aliases: '' },
]);
};
const removeTierRow = (idx) => {
setTierRows((rows) => rows.filter((_, i) => i !== idx));
};
const handlePricingModalOk = () => {
pricingFormRef.current.validate().then((values) => {
const tiers = tierRows
.filter((r) => r.key && r.key.trim() !== '')
.map((r) => ({
key: r.key.trim(),
label: r.label?.trim() || r.key.trim(),
price_per_second: Number(r.price_per_second) || 0,
aliases: (r.aliases || '')
.split(',')
.map((a) => a.trim())
.filter((a) => a !== ''),
}));
if (tiers.length === 0) {
showError(t('请至少配置一个档位'));
return;
}
// 单价必须为正,避免保存后该档位静默 0 扣费
if (tiers.some((tier) => !(tier.price_per_second > 0))) {
showError(t('每个档位的每秒单价必须大于 0'));
return;
}
// default_tier 留空时回退到首个档位,避免请求未带档位/档位不匹配时计费档位不确定
const defaultTier = (values.default_tier || '').trim() || tiers[0].key;
const newConfig = {
model_name: values.model_name,
tier_param: values.tier_param || 'resolution',
default_tier: defaultTier,
default_duration: Math.max(0, parseInt(values.default_duration, 10) || 0),
enabled: values.enabled !== false,
tiers,
};
const next = [...pricingConfigs];
if (editingPricingIndex >= 0) {
next[editingPricingIndex] = newConfig;
} else {
next.push(newConfig);
}
setPricingConfigs(next);
savePricingToServer(next);
setPricingModalVisible(false);
});
};
const pricingColumns = [
{ title: t('模型名称'), dataIndex: 'model_name', key: 'model_name' },
{
title: t('选档字段'),
dataIndex: 'tier_param',
key: 'tier_param',
render: (text) => {
const opt = TIER_PARAM_OPTIONS.find((o) => o.value === text);
return opt ? opt.label : text || 'resolution';
},
},
{
title: t('缺省时长'),
dataIndex: 'default_duration',
key: 'default_duration',
render: (v) => (v > 0 ? `${v}s` : t('全局缺省')),
},
{
title: t('档位'),
dataIndex: 'tiers',
key: 'tiers',
render: (tiers) => (
<Space wrap>
{(tiers || []).map((tier) => (
<Tag key={tier.key} color='blue'>
{(tier.label || tier.key) + ':$' + tier.price_per_second + '/s'}
</Tag>
))}
</Space>
),
},
{
title: t('状态'),
dataIndex: 'enabled',
key: 'enabled',
render: (value, record, index) => (
<Tag
color={value ? 'green' : 'red'}
style={{ cursor: 'pointer' }}
onClick={() => handleTogglePricingEnabled(index)}
>
{value ? t('启用') : t('禁用')}
</Tag>
),
},
{
title: t('操作'),
key: 'action',
render: (text, record, index) => (
<Space>
<Button
icon={<IconEdit />}
size='small'
onClick={() => handleEditPricing(record, index)}
/>
<Popconfirm
title={t('确定要删除此定价配置吗?')}
onConfirm={() => handleDeletePricing(index)}
>
<Button icon={<IconDelete />} size='small' type='danger' />
</Popconfirm>
</Space>
),
},
];
// 表格列定义
const columns = [
{
title: t('模型名称'),
dataIndex: 'model_name',
key: 'model_name',
},
{
title: t('提供商'),
dataIndex: 'provider',
key: 'provider',
render: (text) => {
const provider = PROVIDER_OPTIONS.find((p) => p.value === text);
return provider ? provider.label : text;
},
},
{
title: t('渠道类型'),
dataIndex: 'channel_type',
key: 'channel_type',
render: (text) => {
const channel = VIDEO_CHANNEL_TYPES.find((c) => c.value === text);
return channel ? channel.label : text;
},
},
{
title: t('自定义端点'),
dataIndex: 'endpoint',
key: 'endpoint',
render: (text) => text || <Tag color='grey'>{t('默认')}</Tag>,
},
{
title: t('支持图生视频'),
dataIndex: 'supports_i2v',
key: 'supports_i2v',
render: (value) =>
value ? (
<Tag color='green'>{t('是')}</Tag>
) : (
<Tag color='grey'>{t('否')}</Tag>
),
},
{
title: t('状态'),
dataIndex: 'enabled',
key: 'enabled',
render: (value, record, index) => (
<Tag
color={value ? 'green' : 'red'}
style={{ cursor: 'pointer' }}
onClick={() => handleToggleEnabled(index)}
>
{value ? t('启用') : t('禁用')}
</Tag>
),
},
{
title: t('操作'),
key: 'action',
render: (text, record, index) => (
<Space>
<Button
icon={<IconEdit />}
size='small'
onClick={() => handleEditModel(record, index)}
/>
<Popconfirm
title={t('确定要删除此模型吗?')}
onConfirm={() => handleDeleteModel(index)}
>
<Button icon={<IconDelete />} size='small' type='danger' />
</Popconfirm>
</Space>
),
},
];
useEffect(() => {
const currentInputs = {};
for (const key of Object.keys(defaultVideoModelInputs)) {
if (props.options[key] !== undefined) {
let value = props.options[key];
currentInputs[key] = value;
} else {
currentInputs[key] = defaultVideoModelInputs[key];
}
}
setInputs(currentInputs);
setModels(parseModels(currentInputs['video.custom_video_models']));
setPricingConfigs(parseModels(currentInputs['video.video_second_pricing']));
setAssetLimit(
parseInt(currentInputs['video.asset_library_user_limit'], 10) || 50,
);
setRealPortraitEnabled(
String(currentInputs['video.real_portrait_enabled']).toLowerCase() ===
'true',
);
}, [props.options]);
// ===== 素材库配额 =====
const [assetLimit, setAssetLimit] = useState(50);
const [realPortraitEnabled, setRealPortraitEnabled] = useState(false);
const saveAssetLimit = async () => {
if (!assetLimit || assetLimit <= 0) {
showError(t('配额必须为正整数'));
return;
}
setLoading(true);
try {
const res = await API.put('/api/option/', {
key: 'video.asset_library_user_limit',
value: String(assetLimit),
});
if (res.data.success) {
showSuccess(t('保存成功'));
props.refresh();
} else {
showError(res.data.message || t('保存失败'));
}
} catch (e) {
showError(t('保存失败,请重试'));
} finally {
setLoading(false);
}
};
const saveRealPortraitEnabled = async () => {
setLoading(true);
try {
const res = await API.put('/api/option/', {
key: 'video.real_portrait_enabled',
value: String(realPortraitEnabled),
});
if (res.data.success) {
showSuccess(t('保存成功'));
props.refresh();
} else {
showError(res.data.message || t('保存失败'));
}
} catch (e) {
showError(t('保存失败,请重试'));
} finally {
setLoading(false);
}
};
return (
<>
<Spin spinning={loading}>
<Form style={{ marginBottom: 15 }}>
<Form.Section text={t('自定义视频模型')}>
<Row style={{ marginBottom: 16 }}>
<Col span={24}>
<div
style={{ color: 'var(--semi-color-text-2)', marginBottom: 8 }}
>
{t(
'在此配置自定义视频生成模型,这些模型将与内置模型一起可用于视频生成功能。',
)}
</div>
</Col>
</Row>
<Row style={{ marginBottom: 16 }}>
<Col span={24}>
<Button icon={<IconPlus />} onClick={handleAddModel}>
{t('添加模型')}
</Button>
</Col>
</Row>
<Row>
<Col span={24}>
<Table
columns={columns}
dataSource={models}
rowKey={(record, index) => index}
pagination={false}
empty={t('暂无自定义视频模型')}
/>
</Col>
</Row>
<Row style={{ marginBottom: 8 }}>
<Col span={24}>
<div
style={{ color: 'var(--semi-color-text-2)', marginBottom: 8 }}
>
{t(
'真人人像需要 TokenPony 素材权限、公网 HTTPS 服务地址、稳定的 CRYPTO_SECRET 和私有 COS。',
)}
</div>
</Col>
</Row>
<Row style={{ marginBottom: 16 }}>
<Col span={24}>
<Space>
<Switch
checked={realPortraitEnabled}
onChange={setRealPortraitEnabled}
/>
<Button onClick={saveRealPortraitEnabled}>
{t('保存真人人像设置')}
</Button>
</Space>
</Col>
</Row>
</Form.Section>
<Form.Section text={t('视频按秒分档定价')}>
<Row style={{ marginBottom: 16 }}>
<Col span={24}>
<div
style={{ color: 'var(--semi-color-text-2)', marginBottom: 8 }}
>
{t(
'为视频模型配置「按秒分档」计费:每个档位设置每秒单价(官方原价),实际计费 = 单价 × 视频时长 × 分组倍率(分组折扣无需在此重复配置)。配置后该模型计费类型变为「按秒计费」。',
)}
</div>
</Col>
</Row>
<Row style={{ marginBottom: 16 }}>
<Col span={24}>
<Button icon={<IconPlus />} onClick={handleAddPricing}>
{t('添加定价配置')}
</Button>
</Col>
</Row>
<Row>
<Col span={24}>
<Table
columns={pricingColumns}
dataSource={pricingConfigs}
rowKey={(record, index) => index}
pagination={false}
empty={t('暂无按秒分档定价配置')}
/>
</Col>
</Row>
</Form.Section>
<Form.Section text={t('视频素材库')}>
<Row style={{ marginBottom: 8 }}>
<Col span={24}>
<div
style={{ color: 'var(--semi-color-text-2)', marginBottom: 8 }}
>
{t(
'每用户素材数量上限(审核中与已通过的素材计入,审核失败不计入)。保存后约 1 分钟内生效,无需重启。',
)}
</div>
</Col>
</Row>
<Row style={{ marginBottom: 16 }}>
<Col xs={24} sm={12} md={8}>
<InputNumber
value={assetLimit}
min={1}
max={10000}
onChange={(v) => setAssetLimit(v)}
style={{ width: 200, marginRight: 12 }}
/>
<Button onClick={saveAssetLimit}>{t('保存素材库配额')}</Button>
</Col>
</Row>
</Form.Section>
</Form>
</Spin>
<Modal
title={editingIndex >= 0 ? t('编辑模型') : t('添加模型')}
visible={modalVisible}
onOk={handleModalOk}
onCancel={() => setModalVisible(false)}
okText={t('确定')}
cancelText={t('取消')}
>
<Form
getFormApi={(formAPI) => (modalFormRef.current = formAPI)}
initValues={
editingModel || {
model_name: '',
provider: 'ali',
channel_type: 17,
supports_i2v: false,
enabled: true,
endpoint: '',
}
}
>
<Form.Input
field='model_name'
label={t('模型名称')}
placeholder={t('请输入模型名称,如 my-video-model')}
rules={[{ required: true, message: t('请输入模型名称') }]}
/>
<Form.Select
field='provider'
label={t('提供商')}
placeholder={t('请选择提供商')}
rules={[{ required: true, message: t('请选择提供商') }]}
onChange={handleProviderChange}
>
{PROVIDER_OPTIONS.map((option) => (
<Form.Select.Option key={option.value} value={option.value}>
{option.label}
</Form.Select.Option>
))}
</Form.Select>
<Form.Select
field='channel_type'
label={t('渠道类型')}
placeholder={t('请选择渠道类型')}
rules={[{ required: true, message: t('请选择渠道类型') }]}
extraText={t('渠道类型决定了使用哪种 API 协议与上游通信')}
>
{VIDEO_CHANNEL_TYPES.map((option) => (
<Form.Select.Option key={option.value} value={option.value}>
{option.label}
</Form.Select.Option>
))}
</Form.Select>
<Form.Input
field='endpoint'
label={t('自定义API端点')}
placeholder={t('如 /v1/chat/completions,留空则使用默认端点')}
extraText={t('自定义请求的API路径,默认为 /v1/videos/generations')}
/>
<Form.Switch
field='supports_i2v'
label={t('支持图生视频')}
extraText={t('是否支持以图片作为输入生成视频')}
/>
<Form.Switch
field='enabled'
label={t('启用')}
extraText={t('是否启用此模型')}
/>
</Form>
</Modal>
<Modal
title={
editingPricingIndex >= 0 ? t('编辑定价配置') : t('添加定价配置')
}
visible={pricingModalVisible}
onOk={handlePricingModalOk}
onCancel={() => setPricingModalVisible(false)}
okText={t('确定')}
cancelText={t('取消')}
width={640}
>
<Form
getFormApi={(formAPI) => (pricingFormRef.current = formAPI)}
initValues={{
model_name: '',
tier_param: 'resolution',
default_tier: '',
default_duration: undefined,
enabled: true,
}}
>
<Form.Input
field='model_name'
label={t('模型名称')}
placeholder={t('请输入模型名称,如 kling-v2-master')}
rules={[{ required: true, message: t('请输入模型名称') }]}
extraText={t('支持前缀匹配,例如填 kling 可匹配所有 kling 开头模型')}
/>
<Form.Select
field='tier_param'
label={t('选档字段')}
extraText={t('请求中用于选择档位的字段:分辨率/模式/尺寸')}
>
{TIER_PARAM_OPTIONS.map((option) => (
<Form.Select.Option key={option.value} value={option.value}>
{option.label}
</Form.Select.Option>
))}
</Form.Select>
<Form.Input
field='default_tier'
label={t('默认档位')}
placeholder={t('请求未带档位或不匹配时使用的档位 key')}
extraText={t(
'请填上游模型自身的默认档位,避免按错档计费(如 kling 默认 std、vidu 默认 1080p);留空则默认取第一个档位。',
)}
/>
<Form.InputNumber
field='default_duration'
label={t('缺省时长(秒)')}
min={0}
precision={0}
style={{ width: '100%' }}
placeholder={t('请求未带时长时使用,留空则按全局缺省 5 秒')}
extraText={t(
'应填该上游模型自身的默认时长(如 hailuo 默认 6 秒),避免省略时长时按 5 秒少扣。',
)}
/>
<Form.Switch field='enabled' label={t('启用')} />
</Form>
<div
style={{
marginTop: 8,
padding: '8px 12px',
borderRadius: 6,
background: 'var(--semi-color-fill-0)',
color: 'var(--semi-color-text-2)',
fontSize: 12,
lineHeight: 1.6,
}}
>
<Typography.Text strong style={{ fontSize: 12 }}>
{t('选档值来源说明')}
</Typography.Text>
<div style={{ marginTop: 4 }}>
{t(
'视频生成接口(/v1/video/generations)与任务接口会自动读取请求中的 resolution / mode / size 字段来选档。',
)}
</div>
<div>
{t(
'通过对话接口(/v1/chat/completions)调用时,自然语言无法可靠表达计费档位,需在请求体的 metadata 中显式传入,例如:',
)}
</div>
<pre
style={{
margin: '4px 0 0',
padding: '6px 8px',
borderRadius: 4,
background: 'var(--semi-color-fill-1)',
whiteSpace: 'pre-wrap',
fontSize: 12,
}}
>
{'"metadata": { "mode": "pro", "resolution": "1080P" }'}
</pre>
<div style={{ marginTop: 4 }}>
{t('未传入选档值时,将按上面配置的「默认档位」计费。')}
</div>
</div>
<div style={{ marginTop: 12 }}>
<Typography.Text strong>{t('档位列表')}</Typography.Text>
<div
style={{
color: 'var(--semi-color-text-2)',
fontSize: 12,
margin: '4px 0 8px',
}}
>
{t(
'key 为档位标识(需与请求字段值或别名匹配),label 用于展示(如 1080P/S),单价为每秒美元价。别名用英文逗号分隔。',
)}
</div>
{tierRows.map((row, idx) => (
<Row
key={idx}
gutter={8}
type='flex'
align='middle'
style={{ marginBottom: 8 }}
>
<Col span={5}>
<Input
placeholder={t('key 如 1080P')}
value={row.key}
onChange={(v) => updateTierRow(idx, { key: v })}
/>
</Col>
<Col span={5}>
<Input
placeholder={t('展示名 如 1080P/S')}
value={row.label}
onChange={(v) => updateTierRow(idx, { label: v })}
/>
</Col>
<Col span={5}>
<InputNumber
placeholder={t('单价/秒')}
prefix='$'
min={0}
step={0.01}
style={{ width: '100%' }}
value={row.price_per_second}
onChange={(v) =>
updateTierRow(idx, { price_per_second: v })
}
/>
</Col>
<Col span={7}>
<Input
placeholder={t('别名(逗号分隔) 如 std,standard')}
value={row.aliases}
onChange={(v) => updateTierRow(idx, { aliases: v })}
/>
</Col>
<Col span={2}>
<Button
icon={<IconDelete />}
size='small'
type='danger'
onClick={() => removeTierRow(idx)}
/>
</Col>
</Row>
))}
<Button icon={<IconPlus />} size='small' onClick={addTierRow}>
{t('添加档位')}
</Button>
</div>
</Modal>
</>
);
}
@@ -0,0 +1,126 @@
/*
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 } from 'react';
import { Banner, Button, Card, Checkbox, Form, Spin } from '@douyinfe/semi-ui';
import { API, isRoot, showError, showSuccess } from '../../../helpers';
import { useTranslation } from 'react-i18next';
import { DELEGATABLE_SETTING_TABS } from '../../../constants/settingTabs';
const OPTION_KEY = 'AdminDelegatedSettingTabs';
function parseTabs(raw) {
if (!raw) return [];
try {
const parsed = JSON.parse(raw);
return Array.isArray(parsed) ? parsed : [];
} catch (e) {
return [];
}
}
export default function SettingsAdminDelegation(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [selected, setSelected] = useState([]);
const [savedRaw, setSavedRaw] = useState('');
const refForm = useRef();
useEffect(() => {
const raw = props.options?.[OPTION_KEY] ?? '';
setSavedRaw(raw);
const tabs = parseTabs(raw);
setSelected(tabs);
refForm.current?.setValues({ [OPTION_KEY]: tabs });
}, [props.options]);
// 该配置项属于权限下放的「控制开关」,仅超级管理员可见可改(后端亦强制 root-only)。
if (!isRoot()) {
return null;
}
function onSubmit() {
const value = JSON.stringify(selected);
if (value === JSON.stringify(parseTabs(savedRaw))) {
showSuccess(t('保存成功'));
return;
}
setLoading(true);
API.put('/api/option/', { key: OPTION_KEY, value })
.then((res) => {
const { success, message } = res.data;
if (success) {
showSuccess(t('保存成功'));
props.refresh?.();
} else {
showError(message);
}
})
.catch(() => {
showError(t('保存失败,请重试'));
})
.finally(() => {
setLoading(false);
});
}
return (
<Card style={{ marginTop: '10px' }}>
<Spin spinning={loading}>
<Form
values={{ [OPTION_KEY]: selected }}
getFormApi={(formAPI) => (refForm.current = formAPI)}
style={{ marginBottom: 15 }}
>
<Form.Section text={t('普通管理员可见的系统设置页')}>
<Banner
type='warning'
description={t(
'勾选后,普通管理员(非超级管理员)将能够看到并编辑这些系统设置 Tab。请谨慎下放含密钥的页面(如系统设置、支付设置、数据安全)。未勾选的 Tab 仍仅超级管理员可见。',
)}
bordered
fullMode={false}
closeIcon={null}
style={{ marginBottom: 16 }}
/>
<Form.CheckboxGroup
field={OPTION_KEY}
noLabel
direction='horizontal'
onChange={(value) => setSelected(value)}
>
{DELEGATABLE_SETTING_TABS.map((tab) => (
<Checkbox key={tab.key} value={tab.key}>
{t(tab.labelKey)}
</Checkbox>
))}
</Form.CheckboxGroup>
<Button
size='default'
theme='solid'
onClick={onSubmit}
style={{ marginTop: 12 }}
>
{t('保存')}
</Button>
</Form.Section>
</Form>
</Spin>
</Card>
);
}
@@ -0,0 +1,325 @@
/*
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 } from 'react';
import { Button, Col, Form, Row, Spin } from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import {
compareObjects,
API,
showError,
showSuccess,
showWarning,
} from '../../../helpers';
import { FormQuotaInput } from '../../../components/common/ui/QuotaInput';
export default function SettingsCreditLimit(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [inputs, setInputs] = useState({
QuotaForNewUser: '',
PreConsumedQuota: '',
QuotaForInviter: '',
QuotaForInvitee: '',
'quota_setting.enable_free_model_pre_consume': true,
// 邀请消费返佣配置
InviteRebateEnabled: false,
InviteRebateRate: '0.1',
InviteRebateMinConsume: '0',
InviteRebateMaxPerInvitee: '0',
InviteRebateDurationDays: '0',
InviteRebateDescription: '',
});
const refForm = useRef();
const [inputsRow, setInputsRow] = useState(inputs);
function onSubmit() {
const updateArray = compareObjects(inputs, inputsRow);
if (!updateArray.length) return showWarning(t('你似乎并没有修改什么'));
const requestQueue = updateArray.map((item) => {
let value = '';
if (typeof inputs[item.key] === 'boolean') {
value = String(inputs[item.key]);
} else {
value = inputs[item.key];
}
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);
});
}
useEffect(() => {
// 定义所有需要的字段及其默认值
const defaultInputs = {
QuotaForNewUser: '',
PreConsumedQuota: '',
QuotaForInviter: '',
QuotaForInvitee: '',
'quota_setting.enable_free_model_pre_consume': true,
InviteRebateEnabled: false,
InviteRebateRate: '0.1',
InviteRebateMinConsume: '0',
InviteRebateMaxPerInvitee: '0',
InviteRebateDurationDays: '0',
// 缺这个 key 会让奖励说明“读不回也写不进”:currentInputs 按本表构建,
// 少了它 diff 永远检不出变更,保存被判“没有修改”。
InviteRebateDescription: '',
};
const currentInputs = {};
// 遍历所有定义的字段,优先使用后端返回的值,否则使用默认值
for (let key in defaultInputs) {
currentInputs[key] = props.options.hasOwnProperty(key)
? props.options[key]
: defaultInputs[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}>
<FormQuotaInput
label={t('新用户初始额度')}
field={'QuotaForNewUser'}
minQuota={0}
onChange={(value) =>
setInputs({
...inputs,
QuotaForNewUser: value === null ? '' : String(value),
})
}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<FormQuotaInput
label={t('请求预扣费额度')}
field={'PreConsumedQuota'}
minQuota={0}
extraText={t('请求结束后多退少补')}
onChange={(value) =>
setInputs({
...inputs,
PreConsumedQuota: value === null ? '' : String(value),
})
}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<FormQuotaInput
label={t('邀请新用户奖励额度')}
field={'QuotaForInviter'}
minQuota={0}
onChange={(value) =>
setInputs({
...inputs,
QuotaForInviter: value === null ? '' : String(value),
})
}
/>
</Col>
</Row>
<Row>
<Col xs={24} sm={12} md={8} lg={8} xl={6}>
<FormQuotaInput
label={t('新用户使用邀请码奖励额度')}
field={'QuotaForInvitee'}
minQuota={0}
onChange={(value) =>
setInputs({
...inputs,
QuotaForInvitee: value === null ? '' : String(value),
})
}
/>
</Col>
</Row>
<Row>
<Col>
<Form.Switch
label={t('对免费模型启用预消耗')}
field={'quota_setting.enable_free_model_pre_consume'}
extraText={t(
'开启后,对免费模型(倍率为0,或者价格为0)的模型也会预消耗额度',
)}
onChange={(value) =>
setInputs({
...inputs,
'quota_setting.enable_free_model_pre_consume': value,
})
}
/>
</Col>
</Row>
<Row>
<Button size='default' onClick={onSubmit}>
{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
label={t('启用邀请消费返佣')}
field={'InviteRebateEnabled'}
extraText={t(
'开启后,被邀请用户消费时,邀请人将按比例获得返佣',
)}
onChange={(value) =>
setInputs({
...inputs,
InviteRebateEnabled: value,
})
}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
label={t('返佣比例')}
field={'InviteRebateRate'}
step={0.01}
min={0}
max={1}
suffix={''}
extraText={t('0.1 表示 10%,最大值为 1')}
placeholder={'0.1'}
onChange={(value) =>
setInputs({
...inputs,
InviteRebateRate: String(value),
})
}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<FormQuotaInput
label={t('最小消费额度')}
field={'InviteRebateMinConsume'}
minQuota={0}
extraText={t('单次消费达到此额度才返佣,0表示无限制')}
onChange={(value) =>
setInputs({
...inputs,
InviteRebateMinConsume:
value === null ? '' : String(value),
})
}
/>
</Col>
</Row>
<Row gutter={16}>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<FormQuotaInput
label={t('单用户返佣上限')}
field={'InviteRebateMaxPerInvitee'}
minQuota={0}
extraText={t('每个被邀请人最多返佣额度,0表示无限制')}
onChange={(value) =>
setInputs({
...inputs,
InviteRebateMaxPerInvitee:
value === null ? '' : String(value),
})
}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
label={t('返佣有效期')}
field={'InviteRebateDurationDays'}
step={1}
min={0}
suffix={t('天')}
extraText={t('被邀请人注册后多少天内消费才返佣,0表示永久')}
placeholder={'0'}
onChange={(value) =>
setInputs({
...inputs,
InviteRebateDurationDays: String(value),
})
}
/>
</Col>
</Row>
<Row gutter={16}>
<Col span={24}>
<Form.TextArea
label={t('奖励说明')}
field={'InviteRebateDescription'}
rows={6}
placeholder={t(
'支持Markdown格式,例如:\n- 邀请好友注册并使用,好友消费后您将按比例获得返佣奖励\n- 返佣奖励会累积到您的邀请额度中',
)}
extraText={t(
'用户在邀请有奖页面看到的奖励说明,支持Markdown格式。留空则显示默认说明。',
)}
onChange={(value) =>
setInputs({
...inputs,
InviteRebateDescription: value,
})
}
/>
</Col>
</Row>
<Row>
<Button size='default' onClick={onSubmit}>
{t('保存返佣设置')}
</Button>
</Row>
</Form.Section>
</Form>
</Spin>
</>
);
}
@@ -0,0 +1,347 @@
/*
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 {
Button,
Form,
Row,
Col,
Spin,
Card,
Cascader,
Typography,
} from '@douyinfe/semi-ui';
import { API, showError, showSuccess } from '../../../helpers';
import { useTranslation } from 'react-i18next';
const { Text } = Typography;
export default function SettingsDashboardMonitor() {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const formApi = useRef();
const [config, setConfig] = useState({
refresh_interval: 60,
history_collect_interval: 5,
history_retention_days: 30,
enable_auto_refresh: true,
enable_history_persist: true,
description: '实时监控各分组服务可用性与性能指标',
excluded_channels: [],
});
// 分组-渠道树数据
const [groupChannelTree, setGroupChannelTree] = useState([]);
// 已选择的排除渠道(级联选择器格式)
const [selectedExcluded, setSelectedExcluded] = useState([]);
// 加载分组-渠道树
const loadGroupChannelTree = async () => {
try {
const res = await API.get('/api/monitor/group-channel-tree');
if (res.data.success) {
const treeData = res.data.data || [];
// 转换为 Cascader 格式
const cascaderData = treeData.map((group) => ({
label: group.group,
value: group.group,
children: group.channels.map((channel) => ({
label: channel.name,
value: channel.id,
})),
}));
setGroupChannelTree(cascaderData);
}
} catch (error) {
console.error('加载分组渠道树失败:', error);
}
};
// 将 "groupName:channelId" 格式转换为 Cascader 选中格式 [[groupName, channelId], ...]
// 使用 lastIndexOf 处理分组名包含冒号的情况
const convertExcludedToSelected = (excludedChannels) => {
if (!excludedChannels || !Array.isArray(excludedChannels)) {
return [];
}
return excludedChannels
.map((item) => {
const lastColonIndex = item.lastIndexOf(':');
if (lastColonIndex === -1) {
return null;
}
const groupName = item.substring(0, lastColonIndex);
const channelId = parseInt(item.substring(lastColonIndex + 1), 10);
return [groupName, channelId];
})
.filter(Boolean);
};
// 将 Cascader 选中格式转换为 "groupName:channelId" 格式
const convertSelectedToExcluded = (selected) => {
if (!selected || !Array.isArray(selected)) {
return [];
}
return selected.map(
([groupName, channelId]) => `${groupName}:${channelId}`,
);
};
const loadConfig = async () => {
setLoading(true);
try {
const res = await API.get('/api/monitor/config');
if (res.data.success) {
const newConfig = res.data.data;
setConfig(newConfig);
// 更新表单值
if (formApi.current) {
formApi.current.setValues(newConfig);
}
// 转换并设置已选择的排除渠道
const selected = convertExcludedToSelected(newConfig.excluded_channels);
setSelectedExcluded(selected);
} else {
showError(res.data.message || t('获取配置失败'));
}
} catch (error) {
showError(t('网络请求失败'));
} finally {
setLoading(false);
}
};
const saveConfig = async () => {
// 从表单获取最新值
const values = formApi.current.getValues();
// 验证配置合理性
if (values.refresh_interval < 10 || values.refresh_interval > 600) {
showError(t('刷新间隔必须在 10-600 秒之间'));
return;
}
if (
values.history_collect_interval < 1 ||
values.history_collect_interval > 60
) {
showError(t('历史数据采集间隔必须在 1-60 分钟之间'));
return;
}
if (
values.history_retention_days < 7 ||
values.history_retention_days > 365
) {
showError(t('历史数据保留天数必须在 7-365 天之间'));
return;
}
// 添加排除渠道配置
values.excluded_channels = convertSelectedToExcluded(selectedExcluded);
setLoading(true);
try {
const res = await API.put('/api/monitor/config', values);
if (res.data.success) {
showSuccess(t('保存成功,配置将在几秒后生效'));
loadConfig();
} else {
showError(res.data.message || t('保存失败'));
}
} catch (error) {
showError(t('网络请求失败'));
} finally {
setLoading(false);
}
};
useEffect(() => {
loadConfig();
loadGroupChannelTree();
}, []);
// 渲染已选择的排除渠道标签
const renderSelectedTags = useMemo(() => {
if (!selectedExcluded || selectedExcluded.length === 0) {
return <Text type='tertiary'>{t('未设置排除渠道')}</Text>;
}
return (
<div
style={{
display: 'flex',
flexWrap: 'wrap',
gap: '4px',
marginTop: '8px',
}}
>
{selectedExcluded.map(([groupName, channelId], index) => {
// 查找渠道名称
const group = groupChannelTree.find((g) => g.value === groupName);
const channel = group?.children?.find((c) => c.value === channelId);
const channelName = channel?.label || channelId;
return (
<span
key={index}
style={{
padding: '2px 8px',
background: 'var(--semi-color-fill-0)',
borderRadius: '4px',
fontSize: '12px',
}}
>
{groupName} / {channelName}
</span>
);
})}
</div>
);
}, [selectedExcluded, groupChannelTree, t]);
return (
<Spin spinning={loading}>
<Card
title={
<div className='flex items-center gap-2'>
<span>{t('服务大盘监控设置')}</span>
</div>
}
headerExtraContent={<Button onClick={loadConfig}>{t('刷新')}</Button>}
>
<Form getFormApi={(api) => (formApi.current = api)} initValues={config}>
<Form.Section text={t('页面显示设置')}>
<Row gutter={16}>
<Col xs={24}>
<Form.TextArea
field='description'
label={t('服务大盘描述文本')}
placeholder={t(
'请输入服务大盘页面的描述文本,支持 Markdown 格式',
)}
rows={3}
extraText={t(
'显示在服务大盘页面标题下方的描述信息,支持 Markdown 语法(如 **粗体**、*斜体*、[链接](url)、列表等)',
)}
/>
</Col>
</Row>
</Form.Section>
<Form.Section text={t('刷新设置')}>
<Row gutter={16}>
<Col xs={24} sm={12} md={8}>
<Form.Switch
field='enable_auto_refresh'
label={t('启用自动刷新')}
size='default'
checkedText='|'
uncheckedText='〇'
/>
</Col>
<Col xs={24} sm={12} md={8}>
<Form.InputNumber
field='refresh_interval'
label={t('前端刷新间隔')}
min={10}
max={600}
suffix={t('秒')}
extraText={t('服务大盘页面的数据刷新间隔')}
/>
</Col>
</Row>
</Form.Section>
<Form.Section text={t('历史数据设置')}>
<Row gutter={16}>
<Col xs={24} sm={12} md={8}>
<Form.Switch
field='enable_history_persist'
label={t('启用历史数据持久化')}
size='default'
checkedText='|'
uncheckedText='〇'
extraText={t('关闭后将停止采集历史数据')}
/>
</Col>
<Col xs={24} sm={12} md={8}>
<Form.InputNumber
field='history_collect_interval'
label={t('历史数据采集间隔')}
min={1}
max={60}
suffix={t('分钟')}
extraText={t('后端采集监控历史数据的间隔')}
/>
</Col>
<Col xs={24} sm={12} md={8}>
<Form.InputNumber
field='history_retention_days'
label={t('历史数据保留天数')}
min={7}
max={365}
suffix={t('天')}
extraText={t('超过此天数的历史数据将被自动清理')}
/>
</Col>
</Row>
</Form.Section>
<Form.Section text={t('监控排除设置')}>
<Row gutter={16}>
<Col xs={24}>
<div style={{ marginBottom: '8px' }}>
<Text strong>{t('排除监控的渠道')}</Text>
<Text type='tertiary' style={{ marginLeft: '8px' }}>
{t(
'选择需要从监控统计中排除的渠道,被排除的渠道不会影响监控数据的计算,也不会参与自动封禁检测',
)}
</Text>
</div>
<Cascader
treeData={groupChannelTree}
value={selectedExcluded}
onChange={(value) => setSelectedExcluded(value || [])}
placeholder={t('选择要排除的分组和渠道')}
multiple
filterTreeNode
searchPlaceholder={t('搜索分组或渠道')}
style={{ width: '100%' }}
displayProp='label'
leafOnly
showClear
maxTagCount={5}
dropdownStyle={{ maxHeight: '400px' }}
/>
{renderSelectedTags}
</Col>
</Row>
</Form.Section>
<div className='mt-4'>
<Button type='primary' onClick={saveConfig} loading={loading}>
{t('保存设置')}
</Button>
</div>
</Form>
</Card>
</Spin>
);
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,406 @@
/*
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 } from 'react';
import { Button, Col, Form, Row, Spin, Banner } from '@douyinfe/semi-ui';
import {
compareObjects,
API,
isRoot,
showError,
showSuccess,
showWarning,
} from '../../../helpers';
import { useTranslation } from 'react-i18next';
export default function SettingsFallback(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [inputs, setInputs] = useState({
// Phase 1
'fallback_setting.enabled': false,
'fallback_setting.max_depth': 3,
'fallback_setting.timeout_ms': 60000,
'fallback_setting.total_timeout_ms': 180000,
'fallback_setting.billing_mode': 'actual',
'fallback_setting.edit_permission': 'root_only',
// Phase 2
'fallback_setting.allow_cross_group': false,
'fallback_setting.cross_border_allowed': false,
'fallback_setting.bound_user_allowed': false,
// Phase 3
'fallback_setting.cooling_seconds': 30,
'fallback_setting.per_token_max_per_minute': 0,
'fallback_setting.rollout_percent': 100,
'fallback_setting.max_attempts_per_request': 10,
});
const refForm = useRef();
const [inputsRow, setInputsRow] = useState(inputs);
function onSubmit() {
const updateArray = compareObjects(inputs, inputsRow);
if (!updateArray.length) return showWarning(t('你似乎并没有修改什么'));
// 前端先校验总超时 ≥ 单跳超时(单跳超时为 0 表示关闭,不校验);
// 后端只校验各自范围,不校验两者关系
const timeoutMs = Number(inputs['fallback_setting.timeout_ms']);
const totalTimeoutMs = Number(inputs['fallback_setting.total_timeout_ms']);
if (timeoutMs > 0 && totalTimeoutMs < timeoutMs) {
return showError(t('整条链总超时应不小于单跳超时'));
}
const requestQueue = updateArray.map((item) =>
API.put('/api/option/', {
key: item.key,
value: String(inputs[item.key]),
}),
);
setLoading(true);
// 逐个检查业务结果:后端校验失败返回 HTTP 200 + success:false,
// 只看 Promise 是否 resolve 会把失败误报为保存成功
Promise.allSettled(requestQueue)
.then((results) => {
const failedMessages = [];
results.forEach((r) => {
if (r.status === 'fulfilled' && r.value?.data?.success) return;
const message =
r.status === 'fulfilled'
? r.value?.data?.message
: r.reason?.response?.data?.message || r.reason?.message;
failedMessages.push(message || t('保存失败,请重试'));
});
if (failedMessages.length === 0) {
showSuccess(t('保存成功'));
} else {
showError(
t('保存失败: ') + Array.from(new Set(failedMessages)).join(';'),
);
}
})
.finally(() => {
setLoading(false);
// 无论成败都回读,让页面与库中实际值保持一致
props.refresh();
});
}
useEffect(() => {
const currentInputs = {};
for (let key in props.options) {
if (Object.keys(inputs).includes(key)) {
currentInputs[key] = props.options[key];
}
}
// 合并已有 inputs 默认值,避免覆盖丢失
const merged = { ...inputs, ...currentInputs };
setInputs(merged);
setInputsRow(structuredClone(merged));
refForm.current?.setValues(merged);
}, [props.options]);
return (
<Spin spinning={loading}>
<Form
values={inputs}
getFormApi={(formAPI) => (refForm.current = formAPI)}
style={{ marginBottom: 15 }}
>
<Form.Section text={t('兜底渠道设置(Fallback Channels)')}>
<Banner
type='info'
description={t(
'当主渠道请求失败时,按各渠道配置的兜底链顺序自动切换;用户侧无感。详见技术方案文档。',
)}
closeIcon={null}
style={{ marginBottom: 12 }}
/>
<Row gutter={16}>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'fallback_setting.enabled'}
label={t('兜底渠道总开关')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={(value) =>
setInputs({ ...inputs, 'fallback_setting.enabled': value })
}
extraText={t('关闭后所有兜底逻辑跳过,行为与改造前一致')}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
field={'fallback_setting.max_depth'}
label={t('单次请求最大兜底链长(1-10)')}
min={1}
max={10}
precision={0}
onNumberChange={(value) =>
setInputs({ ...inputs, 'fallback_setting.max_depth': value })
}
style={{ width: '100%' }}
/>
</Col>
{/* 计费策略/编辑权限属于策略键,后端下放黑名单保持 root-only;
对非 root 隐藏,避免"能看不能存"(保存必 403)的断裂 */}
{isRoot() && (
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Select
field={'fallback_setting.billing_mode'}
label={t('兜底计费策略')}
optionList={[
{ value: 'actual', label: t('按实际渠道价(默认)') },
{
value: 'main_capped',
label: t('按主渠道价封顶(Phase 4 待实现)'),
disabled: true,
},
{
value: 'min',
label: t('取较低价(Phase 4 待实现)'),
disabled: true,
},
]}
onChange={(value) =>
setInputs({
...inputs,
'fallback_setting.billing_mode': value,
})
}
style={{ width: '100%' }}
extraText={t(
'Phase 1-3 仅实现 actual 策略;其他选项当前不生效',
)}
/>
</Col>
)}
</Row>
<Row gutter={16} style={{ marginTop: 12 }}>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
field={'fallback_setting.timeout_ms'}
label={t('单跳超时(毫秒)')}
min={0}
max={1800000}
precision={0}
onNumberChange={(value) =>
setInputs({ ...inputs, 'fallback_setting.timeout_ms': value })
}
style={{ width: '100%' }}
extraText={t(
'0 = 关闭单跳超时;超时覆盖整个流式响应,长输出模型请调大或设为 0;图像生成链路的单跳超时最低 300 秒',
)}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
field={'fallback_setting.total_timeout_ms'}
label={t('整条链总超时(毫秒)')}
min={5000}
max={1800000}
precision={0}
onNumberChange={(value) =>
setInputs({
...inputs,
'fallback_setting.total_timeout_ms': value,
})
}
style={{ width: '100%' }}
extraText={t('总超时后熔断返回 503;应不小于单跳超时')}
/>
</Col>
{isRoot() && (
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Select
field={'fallback_setting.edit_permission'}
label={t('兜底配置编辑权限')}
optionList={[
{ value: 'root_only', label: t('仅 Root 管理员(推荐)') },
{
value: 'scope_check',
label: t('按可见范围校验(待实现)'),
disabled: true,
},
]}
onChange={(value) =>
setInputs({
...inputs,
'fallback_setting.edit_permission': value,
})
}
style={{ width: '100%' }}
/>
</Col>
)}
</Row>
</Form.Section>
<Form.Section text={t('兜底渠道-合规与边界(Phase 2)')}>
<Row gutter={16}>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'fallback_setting.allow_cross_group'}
label={t('允许跨分组兜底')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={(value) =>
setInputs({
...inputs,
'fallback_setting.allow_cross_group': value,
})
}
extraText={t(
'关闭时仅允许同分组的渠道作为兜底;auto 分组按实际选中的分组判断;用户分组未知时自动跳过本限制',
)}
/>
</Col>
{/* 跨境兜底涉及数据出境合规,后端下放黑名单保持 root-only;
对非 root 隐藏,避免"能看不能存"(保存必失败)的断裂 */}
{isRoot() && (
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'fallback_setting.cross_border_allowed'}
label={t('允许跨境兜底')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={(value) =>
setInputs({
...inputs,
'fallback_setting.cross_border_allowed': value,
})
}
extraText={t(
'关闭时仅当源/目标都标记 Region 且不同时拦截;涉及数据出境合规',
)}
/>
</Col>
)}
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'fallback_setting.bound_user_allowed'}
label={t('绑定用户渠道允许兜底')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={(value) =>
setInputs({
...inputs,
'fallback_setting.bound_user_allowed': value,
})
}
extraText={t(
'关闭时,被绑定到任一渠道的用户的所有请求都不走兜底;开启后这些用户的请求也会走兜底链',
)}
/>
</Col>
</Row>
</Form.Section>
<Form.Section text={t('兜底渠道-保护与放量(Phase 3)')}>
<Row gutter={16}>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
field={'fallback_setting.cooling_seconds'}
label={t('失败渠道冷却秒数')}
min={0}
max={86400}
precision={0}
onNumberChange={(value) =>
setInputs({
...inputs,
'fallback_setting.cooling_seconds': value,
})
}
style={{ width: '100%' }}
extraText={t(
'兜底渠道刚失败后 N 秒内被跳过,同时作为重试耗尽标记的时长;0 = 禁用冷却与重试耗尽标记。需 Redis 启用',
)}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
field={'fallback_setting.per_token_max_per_minute'}
label={t('单 token 每分钟兜底触发上限')}
min={0}
max={100000}
precision={0}
onNumberChange={(value) =>
setInputs({
...inputs,
'fallback_setting.per_token_max_per_minute': value,
})
}
style={{ width: '100%' }}
extraText={t(
'0 = 不限。超过上限的请求不再触发兜底。需 Redis 启用',
)}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
field={'fallback_setting.rollout_percent'}
label={t('灰度放量百分比(0-100)')}
min={0}
max={100}
precision={0}
onNumberChange={(value) =>
setInputs({
...inputs,
'fallback_setting.rollout_percent': value,
})
}
style={{ width: '100%' }}
extraText={t(
'按用户 ID 哈希决定该用户是否启用兜底;100=全部启用,0=全部关闭',
)}
/>
</Col>
</Row>
<Row gutter={16} style={{ marginTop: 12 }}>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
field={'fallback_setting.max_attempts_per_request'}
label={t('单请求最大上游尝试次数(1-50)')}
min={1}
max={50}
precision={0}
onNumberChange={(value) =>
setInputs({
...inputs,
'fallback_setting.max_attempts_per_request': value,
})
}
style={{ width: '100%' }}
extraText={t(
'单个请求最多向上游发起的调用次数,包含同渠道重试和兜底切换,防止快速失败时调用次数失控;仅对配置了失败次数大于 1 的渠道生效',
)}
/>
</Col>
</Row>
</Form.Section>
<Row>
<Button size='default' onClick={onSubmit} style={{ marginTop: 8 }}>
{t('保存兜底渠道设置')}
</Button>
</Row>
</Form>
</Spin>
);
}
@@ -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>
</>
);
}
@@ -0,0 +1,727 @@
/*
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, useContext } from 'react';
import {
Button,
Card,
Col,
Form,
Row,
Select,
Switch,
Typography,
} from '@douyinfe/semi-ui';
import { API, showError, showSuccess } from '../../../helpers';
import { useTranslation } from 'react-i18next';
import { StatusContext } from '../../../context/Status';
import {
getVisibleGroupOptions,
normalizeGroups,
} from '../../../helpers/navigationVisibility';
const { Text } = Typography;
const authConfigModules = [
'experienceCenter',
'keyManagement',
'userCenter',
'pricing',
'skillMarket',
'docs',
];
const createDefaultHeaderNavModules = () => ({
home: { enabled: true, groups: [] },
experienceCenter: { enabled: true, requireAuth: false, groups: [] },
keyManagement: { enabled: true, requireAuth: false, groups: [] },
userCenter: { enabled: true, requireAuth: false, groups: [] },
console: { enabled: true, groups: [] },
pricing: { enabled: true, requireAuth: false, groups: [] },
skillMarket: { enabled: true, requireAuth: false, groups: [] },
docs: { enabled: true, requireAuth: false, groups: [] },
weyai: { enabled: true, groups: [] },
about: { enabled: true, groups: [] },
});
const normalizeNavModule = (value, key) => {
const base = authConfigModules.includes(key)
? { enabled: true, requireAuth: false, groups: [] }
: { enabled: true, groups: [] };
if (typeof value === 'boolean') {
return { ...base, enabled: value };
}
if (value && typeof value === 'object') {
return {
...base,
...value,
enabled: value.enabled !== false,
groups: normalizeGroups(value.groups),
};
}
return base;
};
const mergeHeaderNavModules = (savedModules) => {
const defaults = createDefaultHeaderNavModules();
const merged = {};
Object.keys(defaults).forEach((key) => {
merged[key] = normalizeNavModule(savedModules?.[key], key);
});
Object.keys(savedModules || {}).forEach((key) => {
if (!merged[key]) {
merged[key] = normalizeNavModule(savedModules[key], key);
}
});
return merged;
};
export default function SettingsHeaderNavModules(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [groupOptions, setGroupOptions] = useState([]);
const [statusState, statusDispatch] = useContext(StatusContext);
const [headerNavModules, setHeaderNavModules] = useState(
createDefaultHeaderNavModules(),
);
const getDefaultActionButtons = () => [
{ key: 'tutorial', title: t('新手教程'), enabled: true, groups: [] },
{ key: 'pricing', title: t('推广'), enabled: true, groups: [] },
// 只在用户有 WeyAi 访问权限且下载页已开放时才会出现,这里控制的是"允许出现"
{ key: 'weyaiDownload', title: t('下载 WeyAi'), enabled: true, groups: [] },
{ key: 'recharge', title: t('充值'), enabled: true, groups: [] },
];
const [actionButtons, setActionButtons] = useState(getDefaultActionButtons());
const getMergedGroupOptions = (selectedGroups) =>
getVisibleGroupOptions(groupOptions, selectedGroups);
function handleActionButtonChange(buttonKey) {
return (checked) => {
setActionButtons((prev) =>
prev.map((btn) =>
btn.key === buttonKey ? { ...btn, enabled: checked } : btn,
),
);
};
}
function handleActionButtonGroupsChange(buttonKey) {
return (groups) => {
setActionButtons((prev) =>
prev.map((btn) =>
btn.key === buttonKey
? { ...btn, groups: normalizeGroups(groups) }
: btn,
),
);
};
}
function handleHeaderNavModuleChange(moduleKey) {
return (checked) => {
setHeaderNavModules((prev) => ({
...prev,
[moduleKey]: {
...normalizeNavModule(prev[moduleKey], moduleKey),
enabled: checked,
},
}));
};
}
function handleModuleAuthChange(moduleKey) {
return (checked) => {
setHeaderNavModules((prev) => ({
...prev,
[moduleKey]: {
...normalizeNavModule(prev[moduleKey], moduleKey),
requireAuth: checked,
},
}));
};
}
function handleModuleGroupsChange(moduleKey) {
return (groups) => {
setHeaderNavModules((prev) => ({
...prev,
[moduleKey]: {
...normalizeNavModule(prev[moduleKey], moduleKey),
groups: normalizeGroups(groups),
},
}));
};
}
// 右侧工具区按钮(教程 / 推广 / 通知 / 主题等)显隐开关,写入 headerNavModules.rightActions
function handleRightActionChange(actionKey) {
return (checked) => {
setHeaderNavModules((prev) => ({
...prev,
rightActions: {
...(prev.rightActions || {}),
[actionKey]: checked,
},
}));
};
}
function resetHeaderNavModules() {
setHeaderNavModules(createDefaultHeaderNavModules());
setActionButtons(getDefaultActionButtons());
showSuccess(t('已重置为默认配置'));
}
async function onSubmit() {
setLoading(true);
try {
const actionButtonsValue = JSON.stringify(
actionButtons.map(({ key, enabled, groups }) => ({
key,
enabled,
groups: normalizeGroups(groups),
})),
);
const res = await API.put('/api/option/', {
key: 'HeaderNavModules',
value: JSON.stringify(headerNavModules),
});
const resActionButtons = await API.put('/api/option/', {
key: 'HeaderActionButtons',
value: actionButtonsValue,
});
const { success, message } = res.data;
const successActionButtons = resActionButtons.data.success;
if (success && successActionButtons) {
showSuccess(t('保存成功'));
statusDispatch({
type: 'set',
payload: {
...statusState.status,
HeaderNavModules: JSON.stringify(headerNavModules),
HeaderActionButtons: actionButtonsValue,
},
});
if (props.refresh) {
await props.refresh();
}
} else {
showError(message || resActionButtons.data.message);
}
} catch (error) {
showError(t('保存失败,请重试'));
} finally {
setLoading(false);
}
}
const loadAllGroups = async () => {
try {
const res = await API.get('/api/group/');
if (res.data.success) {
const groups = Array.isArray(res.data.data) ? res.data.data : [];
setGroupOptions(
groups.map((group) => ({ value: group, label: group })),
);
}
} catch {
setGroupOptions([]);
}
};
useEffect(() => {
loadAllGroups();
}, []);
useEffect(() => {
if (props.options && props.options.HeaderNavModules) {
try {
const modules = JSON.parse(props.options.HeaderNavModules);
setHeaderNavModules(mergeHeaderNavModules(modules));
} catch (error) {
setHeaderNavModules(createDefaultHeaderNavModules());
}
}
const defaultButtons = getDefaultActionButtons();
if (props.options && props.options.HeaderActionButtons) {
try {
const saved = JSON.parse(props.options.HeaderActionButtons);
const merged = defaultButtons.map((def) => {
const found = Array.isArray(saved)
? saved.find((button) => button.key === def.key)
: null;
return found
? {
...def,
enabled: found.enabled !== false,
groups: normalizeGroups(found.groups),
}
: def;
});
setActionButtons(merged);
} catch (error) {
setActionButtons(defaultButtons);
}
} else {
setActionButtons(defaultButtons);
}
}, [props.options, t]);
// home/about 在顶栏导航中无对应消费点(导航不渲染这两项链接),
// 属于死开关,不再在 UI 展示;保存结构仍保留 key 以兼容旧配置。
const moduleConfigs = [
{
key: 'experienceCenter',
title: t('体验中心'),
description: t('AI模型体验,快速测试模型能力'),
hasSubConfig: true,
},
{
key: 'keyManagement',
title: t('秘钥管理'),
description: t('API秘钥管理与配置'),
hasSubConfig: true,
},
{
key: 'userCenter',
title: t('用户中心'),
description: t('用户个人信息与设置'),
hasSubConfig: true,
},
{
key: 'console',
title: t('控制台'),
description: t('用户控制面板,管理账户'),
},
{
key: 'pricing',
title: t('模型广场'),
description: t('模型定价展示'),
hasSubConfig: true,
},
{
key: 'skillMarket',
title: t('技能超市'),
description: t('平台已发布技能目录,仅展示元数据'),
hasSubConfig: true,
},
{
key: 'docs',
title: t('文档'),
description: t('系统文档和帮助信息'),
hasSubConfig: true,
},
{
key: 'weyai',
title: t('WeyAi'),
description: t(
'WeyAi 网页端入口:未登录访客可见、点击后先登录;已登录用户在开放范围内才显示',
),
},
];
// 普通用户的「新手教程/推广/充值」按钮由下方「功能按钮」区
// (HeaderActionButtons)控制;rightActions 里的同名开关与
// orgCenter 快捷入口在普通用户链路无任何消费点(企业员工读的是
// HeaderNavModulesOrgUser),属于死开关,不再在 UI 展示。
const rightActionConfigs = [
{
key: 'notifications',
title: t('公告按钮'),
description: t('顶部右侧的系统公告与未读提醒入口'),
},
{
key: 'theme',
title: t('主题按钮'),
description: t('顶部右侧的浅色/深色主题切换'),
},
{
key: 'newYear',
title: t('新年按钮'),
description: t('元旦当天显示的新年彩蛋按钮'),
},
{
key: 'userSettings',
title: t('个人设置快捷入口'),
description: t('用户头像菜单中的个人设置入口'),
},
{
key: 'keyManagement',
title: t('秘钥管理快捷入口'),
description: t('用户头像菜单中的秘钥管理入口'),
},
];
return (
<Card>
<Form.Section
text={t('顶栏管理')}
extraText={t('控制顶栏模块显示状态和可见用户分组,全局生效')}
>
<Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
{moduleConfigs.map((module) => {
const moduleConfig = normalizeNavModule(
headerNavModules[module.key],
module.key,
);
return (
<Col key={module.key} xs={24} sm={12} md={6} lg={6} xl={6}>
<Card
style={{
borderRadius: '8px',
border: '1px solid var(--semi-color-border)',
transition: 'all 0.2s ease',
background: 'var(--semi-color-bg-1)',
minHeight: '80px',
}}
bodyStyle={{ padding: '16px' }}
hoverable
>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
height: '100%',
}}
>
<div style={{ flex: 1, textAlign: 'left' }}>
<div
style={{
fontWeight: '600',
fontSize: '14px',
color: 'var(--semi-color-text-0)',
marginBottom: '4px',
}}
>
{module.title}
</div>
<Text
type='secondary'
size='small'
style={{
fontSize: '12px',
color: 'var(--semi-color-text-2)',
lineHeight: '1.4',
display: 'block',
}}
>
{module.description}
</Text>
</div>
<div style={{ marginLeft: '16px' }}>
<Switch
checked={moduleConfig.enabled}
onChange={handleHeaderNavModuleChange(module.key)}
size='default'
/>
</div>
</div>
{moduleConfig.enabled && (
<div
style={{
borderTop: '1px solid var(--semi-color-border)',
marginTop: '12px',
paddingTop: '12px',
}}
>
{module.hasSubConfig && (
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '12px',
}}
>
<div style={{ flex: 1, textAlign: 'left' }}>
<div
style={{
fontWeight: '500',
fontSize: '12px',
color: 'var(--semi-color-text-1)',
marginBottom: '2px',
}}
>
{t('需要登录访问')}
</div>
<Text
type='secondary'
size='small'
style={{
fontSize: '11px',
color: 'var(--semi-color-text-2)',
lineHeight: '1.4',
display: 'block',
}}
>
{t('开启后未登录用户无法访问')}
</Text>
</div>
<div style={{ marginLeft: '16px' }}>
<Switch
checked={moduleConfig.requireAuth || false}
onChange={handleModuleAuthChange(module.key)}
size='default'
/>
</div>
</div>
)}
<Text
type='secondary'
size='small'
style={{ display: 'block', marginBottom: '6px' }}
>
{t('可见用户分组(留空表示全部分组)')}
</Text>
<Select
multiple
filter
showClear
maxTagCount={2}
placeholder={t('选择分组')}
style={{ width: '100%' }}
value={moduleConfig.groups || []}
optionList={getMergedGroupOptions(moduleConfig.groups)}
onChange={handleModuleGroupsChange(module.key)}
/>
</div>
)}
</Card>
</Col>
);
})}
</Row>
<div style={{ marginBottom: '16px' }}>
<div
style={{
fontWeight: '600',
fontSize: '14px',
color: 'var(--semi-color-text-0)',
marginBottom: '4px',
}}
>
{t('功能按钮')}
</div>
<Text
type='secondary'
size='small'
style={{
fontSize: '12px',
color: 'var(--semi-color-text-2)',
display: 'block',
}}
>
{t('控制顶栏右上角功能按钮的显示、隐藏与可见用户分组')}
</Text>
</div>
<Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
{actionButtons.map((button) => (
<Col key={button.key} xs={24} sm={12} md={6} lg={6} xl={6}>
<Card
style={{
borderRadius: '8px',
border: '1px solid var(--semi-color-border)',
transition: 'all 0.2s ease',
background: 'var(--semi-color-bg-1)',
minHeight: '80px',
}}
bodyStyle={{ padding: '16px' }}
hoverable
>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
height: '100%',
}}
>
<div style={{ flex: 1, textAlign: 'left' }}>
<div
style={{
fontWeight: '600',
fontSize: '14px',
color: 'var(--semi-color-text-0)',
}}
>
{button.title}
</div>
</div>
<div style={{ marginLeft: '16px' }}>
<Switch
checked={button.enabled}
onChange={handleActionButtonChange(button.key)}
size='default'
/>
</div>
</div>
{button.enabled && (
<div
style={{
borderTop: '1px solid var(--semi-color-border)',
marginTop: '12px',
paddingTop: '12px',
}}
>
<Text
type='secondary'
size='small'
style={{ display: 'block', marginBottom: '6px' }}
>
{t('可见用户分组(留空表示全部分组)')}
</Text>
<Select
multiple
filter
showClear
maxTagCount={2}
placeholder={t('选择分组')}
style={{ width: '100%' }}
value={button.groups || []}
optionList={getMergedGroupOptions(button.groups)}
onChange={handleActionButtonGroupsChange(button.key)}
/>
</div>
)}
</Card>
</Col>
))}
</Row>
<Form.Section
text={t('顶部右侧按钮')}
extraText={t('控制顶部导航栏右侧快捷按钮和头像菜单入口')}
>
<Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
{rightActionConfigs.map((action) => (
<Col key={action.key} xs={24} sm={12} md={8} lg={6} xl={6}>
<Card
style={{
borderRadius: '8px',
border: '1px solid var(--semi-color-border)',
transition: 'all 0.2s ease',
background: 'var(--semi-color-bg-1)',
minHeight: '80px',
}}
bodyStyle={{ padding: '16px' }}
hoverable
>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
height: '100%',
}}
>
<div style={{ flex: 1, textAlign: 'left' }}>
<div
style={{
fontWeight: '600',
fontSize: '14px',
color: 'var(--semi-color-text-0)',
marginBottom: '4px',
}}
>
{action.title}
</div>
<Text
type='secondary'
size='small'
style={{
fontSize: '12px',
color: 'var(--semi-color-text-2)',
lineHeight: '1.4',
display: 'block',
}}
>
{action.description}
</Text>
</div>
<div style={{ marginLeft: '16px' }}>
<Switch
checked={
headerNavModules.rightActions?.[action.key] !== false
}
onChange={handleRightActionChange(action.key)}
size='default'
/>
</div>
</div>
</Card>
</Col>
))}
</Row>
</Form.Section>
<div
style={{
display: 'flex',
gap: '12px',
justifyContent: 'flex-start',
alignItems: 'center',
paddingTop: '8px',
borderTop: '1px solid var(--semi-color-border)',
}}
>
<Button
size='default'
type='tertiary'
onClick={resetHeaderNavModules}
style={{
borderRadius: '6px',
fontWeight: '500',
}}
>
{t('重置为默认')}
</Button>
<Button
size='default'
type='primary'
onClick={onSubmit}
loading={loading}
style={{
borderRadius: '6px',
fontWeight: '500',
minWidth: '100px',
}}
>
{t('保存设置')}
</Button>
</div>
</Form.Section>
</Card>
);
}
@@ -0,0 +1,762 @@
/*
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
*/
// 运营设置 → 语言与地区:按访客 IP 国家自动选择界面语言的配置卡片。
// 整份配置存于单个 option key "LanguageSetting"(JSON),后端入库前整份校验;
// 这里的前端校验只为即时提示,口径与 setting/language_setting.Validate 一致。
import React, { useEffect, useMemo, useState } from 'react';
import {
Banner,
Button,
Checkbox,
Form,
Input,
Radio,
RadioGroup,
Select,
Spin,
Switch,
Typography,
} from '@douyinfe/semi-ui';
import { ArrowDown, ArrowUp, Plus, Trash2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { API, showError, showSuccess, showWarning } from '../../../helpers';
import { LANGUAGE_CATALOG, getLanguageEntry } from '../../../i18n/catalog';
import { normalizeLanguage } from '../../../i18n/language';
import {
STORAGE_KEYS,
announceBootUpdated,
storeBootResult,
} from '../../../i18n/bootstrap';
import { COUNTRY_CODES, getCountryName } from '../../../constants/countries';
const { Text } = Typography;
// 与后端 language_setting.Default() 一致;options 缺值或解析失败时兜底
const DEFAULT_SETTING = {
auto_detect_enabled: true,
default_language: 'zh',
enabled_languages: ['zh', 'zh-TW', 'en', 'ja', 'ko', 'vi', 'th'],
ip_before_browser: true,
rules: [
{ language: 'zh', countries: ['CN', 'SG'] },
{ language: 'zh-TW', countries: ['TW', 'HK', 'MO'] },
{ language: 'ja', countries: ['JP'] },
{ language: 'ko', countries: ['KR'] },
{ language: 'vi', countries: ['VN'] },
{ language: 'th', countries: ['TH'] },
],
trusted_country_header: '',
};
const HEADER_NAME_PATTERN = /^[A-Za-z0-9-]{1,64}$/;
const parseSetting = (raw) => {
// 不用 structuredClone:构建目标 es2015 无 polyfill,Safari ≤15.3 会让整个运营设置页崩溃
const fallback = JSON.parse(JSON.stringify(DEFAULT_SETTING));
if (!raw) return fallback;
try {
const parsed = JSON.parse(raw);
return {
...fallback,
...parsed,
enabled_languages: Array.isArray(parsed.enabled_languages)
? parsed.enabled_languages
: [],
rules: Array.isArray(parsed.rules)
? parsed.rules.map((rule) => ({
language: rule?.language || '',
countries: Array.isArray(rule?.countries) ? rule.countries : [],
}))
: [],
trusted_country_header: parsed.trusted_country_header || '',
};
} catch {
return fallback;
}
};
const endonymOf = (code) => getLanguageEntry(code)?.endonym || code;
const FieldLabel = ({ children, extra }) => (
<div className='mb-1.5'>
<Text strong>{children}</Text>
{extra && (
<Text type='tertiary' size='small' className='ml-2'>
{extra}
</Text>
)}
</div>
);
export default function SettingsLanguage(props) {
const { t, i18n } = useTranslation();
const uiLanguage = normalizeLanguage(i18n.language);
const [setting, setSetting] = useState(() =>
parseSetting(props.options?.LanguageSetting),
);
const [savedJSON, setSavedJSON] = useState('');
const [saving, setSaving] = useState(false);
const [testIp, setTestIp] = useState('');
const [testing, setTesting] = useState(false);
const [testResult, setTestResult] = useState(null);
const [geoip, setGeoip] = useState(null);
const [geoipLoadFailed, setGeoipLoadFailed] = useState(false);
const [updating, setUpdating] = useState(false);
useEffect(() => {
const next = parseSetting(props.options?.LanguageSetting);
setSetting(next);
setSavedJSON(JSON.stringify(next));
}, [props.options?.LanguageSetting]);
const loadGeoipStatus = async () => {
try {
const res = await API.get('/api/option/language/test', {
skipErrorHandler: true,
disableDuplicate: true,
});
if (res.data?.success) {
setGeoip(res.data.data.geoip);
setGeoipLoadFailed(false);
} else {
setGeoipLoadFailed(true);
}
} catch {
// 状态仅作展示:失败不弹提示,只在卡片上标明,避免与"库不可用"混淆
setGeoipLoadFailed(true);
}
};
useEffect(() => {
loadGeoipStatus();
}, []);
// 后端启动即把完整配置写入 OptionMap,正常情况下这里一定拿得到非空 JSON;为空说明 /api/option/
// 读取失败或该 key 被权限过滤。此时卡片展示的是默认配置,若允许保存会整份覆盖线上规则(R82 F3)
const optionLoaded = Boolean(props.options?.LanguageSetting);
const update = (patch) => setSetting((prev) => ({ ...prev, ...patch }));
const enabledEntries = setting.enabled_languages
.map(getLanguageEntry)
.filter(Boolean);
const disabledEntries = LANGUAGE_CATALOG.filter(
(entry) => !setting.enabled_languages.includes(entry.code),
);
const usedLanguages = new Set(setting.rules.map((rule) => rule.language));
const countryOptions = useMemo(
() =>
COUNTRY_CODES.map((code) => ({
value: code,
label: `${getCountryName(code, uiLanguage)} (${code})`,
})),
[uiLanguage],
);
const { messages, conflicts } = useMemo(() => {
const result = [];
const enabled = new Set(setting.enabled_languages);
if (enabled.size === 0) result.push(t('至少启用一种语言'));
if (!enabled.has(setting.default_language)) {
result.push(t('默认语言必须处于启用状态'));
}
const owner = new Map();
const conflictSet = new Set();
setting.rules.forEach((rule) => {
if (!enabled.has(rule.language)) {
result.push(
t('规则语言 {{name}} 未启用', { name: endonymOf(rule.language) }),
);
}
if (rule.countries.length === 0) {
result.push(
t('{{name}} 的规则至少选择一个国家/地区', {
name: endonymOf(rule.language),
}),
);
}
rule.countries.forEach((country) => {
if (owner.has(country) && owner.get(country) !== rule.language) {
conflictSet.add(country);
} else {
owner.set(country, rule.language);
}
});
});
conflictSet.forEach((country) =>
result.push(
t('{{country}} 同时出现在多条规则中', {
country: getCountryName(country, uiLanguage),
}),
),
);
const header = setting.trusted_country_header.trim();
if (header && !HEADER_NAME_PATTERN.test(header)) {
result.push(t('CDN 国家头名称只能包含字母、数字和连字符'));
}
return { messages: result, conflicts: conflictSet };
}, [setting, t, uiLanguage]);
const toggleLanguage = (code, checked) =>
update({
enabled_languages: checked
? [...setting.enabled_languages, code]
: setting.enabled_languages.filter((item) => item !== code),
});
const moveLanguage = (index, delta) => {
const list = [...setting.enabled_languages];
const target = index + delta;
if (target < 0 || target >= list.length) return;
[list[index], list[target]] = [list[target], list[index]];
update({ enabled_languages: list });
};
const updateRule = (index, patch) =>
update({
rules: setting.rules.map((rule, i) =>
i === index ? { ...rule, ...patch } : rule,
),
});
const nextRuleLanguage = enabledEntries.find(
(entry) => !usedLanguages.has(entry.code),
);
const addRule = () => {
if (!nextRuleLanguage) return;
update({
rules: [
...setting.rules,
{ language: nextRuleLanguage.code, countries: [] },
],
});
};
const removeRule = (index) =>
update({ rules: setting.rules.filter((_, i) => i !== index) });
// 保存后刷新本浏览器的判定缓存并通知顶栏:管理员自己立刻看到启用语言的变化
// (其他访客仍按缓存策略在后续访问生效)
const refreshOwnLanguageBoot = async () => {
try {
const res = await API.get('/api/i18n/locale', {
headers: {
'X-UI-Language-Choice':
localStorage.getItem(STORAGE_KEYS.userChoice) || '',
'X-UI-Languages': (navigator.languages || [navigator.language]).join(
',',
),
},
skipErrorHandler: true,
disableDuplicate: true,
});
if (res.data?.success) {
storeBootResult(res.data.data, { notify: announceBootUpdated });
}
} catch {
// 缓存刷新失败不影响保存结果,下次访问时启动流程会再刷新
}
};
const save = async () => {
if (!optionLoaded) {
showWarning(t('配置尚未加载,请刷新页面后再编辑,以免覆盖线上配置'));
return;
}
if (messages.length > 0) {
showWarning(messages[0]);
return;
}
if (JSON.stringify(setting) === savedJSON) {
showWarning(t('你似乎并没有修改什么'));
return;
}
setSaving(true);
try {
const res = await API.put(
'/api/option/',
{
key: 'LanguageSetting',
value: JSON.stringify({
...setting,
trusted_country_header: setting.trusted_country_header.trim(),
}),
},
{ skipErrorHandler: true },
);
if (res.data?.success) {
showSuccess(t('保存成功'));
props.refresh();
refreshOwnLanguageBoot();
} else {
showError(res.data?.message || t('保存失败,请重试'));
}
} catch {
showError(t('保存失败,请重试'));
} finally {
setSaving(false);
}
};
const runTest = async () => {
const ip = testIp.trim();
if (!ip) {
showWarning(t('请输入 IP 地址'));
return;
}
// 粗校验拦下明显非法的输入,给出本地化提示(精确校验仍以后端为准)
if (!/^[0-9a-fA-F.:]+$/.test(ip) || !/[.:]/.test(ip)) {
showWarning(t('请输入合法的 IP 地址'));
return;
}
// 先清空上一次结果,失败时不能让旧 IP 的结果显示在新 IP 下
setTestResult(null);
setTesting(true);
try {
const res = await API.get('/api/option/language/test', {
params: { ip },
skipErrorHandler: true,
disableDuplicate: true,
});
if (res.data?.success) {
setTestResult(res.data.data);
setGeoip(res.data.data.geoip);
} else {
setTestResult(null);
showError(res.data?.message || t('测试失败'));
}
} catch {
showError(t('测试失败'));
} finally {
setTesting(false);
}
};
const updateGeoip = async () => {
setUpdating(true);
try {
const res = await API.post('/api/option/language/geoip/update', null, {
skipErrorHandler: true,
});
if (res.data?.success) {
const { updated, geoip: status } = res.data.data;
setGeoip(status);
showSuccess(
updated
? t('IP 库已更新到 {{month}} 版', { month: status?.month })
: t('IP 库已是最新版本'),
);
} else {
showError(res.data?.message || t('IP 库更新失败'));
loadGeoipStatus();
}
} catch {
// 常见于反向代理读超时:后端下载与请求已解绑,可能仍在进行,拉一次状态看真实结果
showError(t('IP 库更新请求未返回结果,更新可能仍在进行,请稍后查看状态'));
loadGeoipStatus();
} finally {
setUpdating(false);
}
};
const sourceLabels = {
query: t('URL 参数'),
user: t('用户选择'),
ip: t('IP 国家'),
browser: t('浏览器语言'),
default: t('默认语言'),
};
// 只放限定词:会拼进"IP 库:{{source}} · {{month}} 版",完整译成"内置数据库"会与前半句同词复读;
// 下载来源也不能叫"自动更新",否则与同一行的开关状态重名(R83 M1/M2)
const geoipSourceLabels = {
embedded: t('内置'),
file: t('指定文件'),
downloaded: t('在线下载'),
};
return (
<Spin spinning={saving}>
<Form style={{ marginBottom: 15 }}>
<Form.Section text={t('语言与地区')}>
<Banner
type='info'
description={t(
'按访客 IP 所在国家/地区自动选择界面语言。判定顺序:URL 参数 > 用户手动选择 > IP 国家与浏览器语言 > 默认语言。保存后首次访问的访客立即生效;已访问过的访客会先沿用上次结果,第二次访问时生效。',
)}
bordered
fullMode={false}
closeIcon={null}
style={{ marginBottom: 16 }}
/>
{/* md 单列宽约 220px,装不下 vi/th/en/ja 的"IP 国家 / 浏览器语言"分段按钮(按钮型
RadioGroup 不换行);这两个词同时用在"最终语言:××(IP 国家)"句中,缩词会伤那句,
因此改断点而非改文案(R83 M7) */}
<div className='grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 mb-4'>
<div>
<FieldLabel>{t('自动识别语言')}</FieldLabel>
<Switch
checked={setting.auto_detect_enabled}
onChange={(checked) => update({ auto_detect_enabled: checked })}
/>
</div>
<div>
<FieldLabel>{t('默认语言')}</FieldLabel>
<Select
className='w-full'
value={setting.default_language}
optionList={enabledEntries.map((entry) => ({
value: entry.code,
label: entry.endonym,
}))}
onChange={(value) => update({ default_language: value })}
/>
</div>
<div>
<FieldLabel>{t('识别优先')}</FieldLabel>
<RadioGroup
type='button'
value={setting.ip_before_browser ? 'ip' : 'browser'}
disabled={!setting.auto_detect_enabled}
onChange={(e) =>
update({ ip_before_browser: e.target.value === 'ip' })
}
>
<Radio value='ip'>{t('IP 国家')}</Radio>
<Radio value='browser'>{t('浏览器语言')}</Radio>
</RadioGroup>
</div>
</div>
<FieldLabel extra={t('勾选的语言展示在顶栏,顺序即展示顺序')}>
{t('启用的语言')}
</FieldLabel>
<div className='flex flex-col gap-0.5 mb-4 max-w-md'>
{enabledEntries.map((entry, index) => {
const isDefault = entry.code === setting.default_language;
return (
<div
key={entry.code}
className='flex items-center justify-between gap-2 rounded-md px-2 py-1 hover:!bg-semi-color-fill-1'
>
<Checkbox
checked
disabled={isDefault}
onChange={(e) =>
toggleLanguage(entry.code, e.target.checked)
}
>
{entry.endonym}
{isDefault && (
<Text type='tertiary' size='small' className='ml-2'>
{t('默认')}
</Text>
)}
</Checkbox>
<div className='flex gap-1 shrink-0'>
<Button
size='small'
theme='borderless'
type='tertiary'
icon={<ArrowUp size={14} />}
aria-label={t('上移')}
disabled={index === 0}
onClick={() => moveLanguage(index, -1)}
/>
<Button
size='small'
theme='borderless'
type='tertiary'
icon={<ArrowDown size={14} />}
aria-label={t('下移')}
disabled={index === enabledEntries.length - 1}
onClick={() => moveLanguage(index, 1)}
/>
</div>
</div>
);
})}
{disabledEntries.map((entry) => (
<div key={entry.code} className='px-2 py-1'>
<Checkbox
checked={false}
onChange={(e) => toggleLanguage(entry.code, e.target.checked)}
>
<Text type='tertiary'>{entry.endonym}</Text>
</Checkbox>
</div>
))}
</div>
<div className='max-w-md'>
<FieldLabel>{t('CDN 国家头')}</FieldLabel>
<Input
value={setting.trusted_country_header}
placeholder='CF-IPCountry'
showClear
disabled={!setting.auto_detect_enabled}
onChange={(value) => update({ trusted_country_header: value })}
/>
<Text type='tertiary' size='small' className='block mt-1'>
{setting.auto_detect_enabled
? t(
'仅当站点前置 CDN 且会传递国家头时填写,留空表示只使用 IP 库',
)
: t('自动识别已关闭,CDN 国家头当前不生效')}
</Text>
</div>
</Form.Section>
<Form.Section text={t('国家/地区映射规则')}>
<Text type='tertiary' size='small' className='block mb-3'>
{t('未被任何规则覆盖的国家/地区,继续按浏览器语言或默认语言判定')}
</Text>
<div className='flex flex-col gap-3'>
{setting.rules.map((rule, index) => {
const languageOptions = LANGUAGE_CATALOG.filter(
(entry) =>
entry.code === rule.language ||
(setting.enabled_languages.includes(entry.code) &&
!usedLanguages.has(entry.code)),
).map((entry) => ({ value: entry.code, label: entry.endonym }));
const invalidCountries =
rule.countries.length === 0 ||
rule.countries.some((country) => conflicts.has(country));
return (
<div
key={index}
className='flex flex-col sm:flex-row gap-2 sm:items-start'
>
<Select
className='w-full sm:!w-40 shrink-0'
value={rule.language}
optionList={languageOptions}
validateStatus={
setting.enabled_languages.includes(rule.language)
? 'default'
: 'error'
}
onChange={(value) => updateRule(index, { language: value })}
/>
<Select
className='w-full flex-1 min-w-0'
multiple
filter
maxTagCount={8}
value={rule.countries}
optionList={countryOptions}
placeholder={t('选择国家/地区')}
validateStatus={invalidCountries ? 'error' : 'default'}
onChange={(value) =>
updateRule(index, { countries: value })
}
/>
<Button
type='danger'
theme='borderless'
icon={<Trash2 size={16} />}
aria-label={t('删除规则')}
onClick={() => removeRule(index)}
/>
</div>
);
})}
</div>
<Button
className='!mt-3'
icon={<Plus size={16} />}
disabled={!nextRuleLanguage}
onClick={addRule}
>
{t('添加规则')}
</Button>
</Form.Section>
{messages.length > 0 && (
<Banner
type='danger'
bordered
fullMode={false}
closeIcon={null}
style={{ marginBottom: 12 }}
description={
<ul className='list-disc pl-4 m-0'>
{messages.map((message) => (
<li key={message}>{message}</li>
))}
</ul>
}
/>
)}
{!optionLoaded && (
<Banner
type='warning'
bordered
fullMode={false}
closeIcon={null}
style={{ marginBottom: 12 }}
description={t(
'配置尚未加载,请刷新页面后再编辑,以免覆盖线上配置',
)}
/>
)}
<Button
size='default'
onClick={save}
loading={saving}
disabled={messages.length > 0 || !optionLoaded}
>
{t('保存语言与地区设置')}
</Button>
<Form.Section text={t('识别测试与 IP 库')} style={{ marginTop: 24 }}>
<div className='flex flex-col sm:flex-row gap-2 max-w-xl'>
<Input
value={testIp}
placeholder={t('输入 IP 地址,如 8.8.8.8')}
onChange={setTestIp}
onEnterPress={runTest}
/>
<Button onClick={runTest} loading={testing}>
{t('测试')}
</Button>
</div>
<Text type='tertiary' size='small' className='block mt-1'>
{t('测试基于已保存的配置,仅模拟 IP 识别')}
</Text>
{testResult && (
<div className='mt-3 flex flex-wrap gap-x-5 gap-y-1'>
<Text>
{t('国家/地区:{{value}}', {
value: testResult.country
? `${getCountryName(testResult.country, uiLanguage)} (${testResult.country})`
: t('未识别'),
})}
</Text>
<Text>
{t('命中规则:{{value}}', {
value: testResult.rule_language
? endonymOf(testResult.rule_language)
: t('未命中'),
})}
</Text>
<Text strong>
{t('最终语言:{{language}}({{source}})', {
language: endonymOf(testResult.language),
source: sourceLabels[testResult.source] || testResult.source,
})}
</Text>
{testResult.auto_detect_enabled === false && (
<Text type='warning' size='small' className='basis-full'>
{t(
'自动识别已关闭,访客不会按 IP 判定;以上为 IP 对应的规则',
)}
</Text>
)}
</div>
)}
<div className='mt-4 flex flex-wrap items-center gap-x-3 gap-y-2'>
<Text>
{geoip?.source
? t('IP 库:{{source}} · {{month}} 版', {
source: geoipSourceLabels[geoip.source] || geoip.source,
month: geoip.month,
})
: geoip
? t('IP 库:不可用')
: geoipLoadFailed
? t('IP 库:状态获取失败')
: t('IP 库:加载中…')}
</Text>
{geoip && (
<Text type='tertiary' size='small'>
{!geoip.auto_update
? t('自动更新已关闭')
: geoip.last_check_at
? t('自动更新已开启 · 上次检查 {{time}}', {
time: new Date(
geoip.last_check_at * 1000,
).toLocaleString(),
})
: t('自动更新已开启')}
</Text>
)}
<Button
size='small'
onClick={updateGeoip}
loading={updating}
disabled={Boolean(geoip) && !geoip.auto_update}
>
{t('立即更新')}
</Button>
{geoip && !geoip.auto_update && (
<Text type='tertiary' size='small'>
{geoip.source === 'file' || geoip.custom_path_error
? t('已通过 GEOIP_DB_PATH 指定 IP 库,不支持在线更新')
: t(
'自动更新已关闭(GEOIP_AUTO_UPDATE=false),在线更新不可用',
)}
</Text>
)}
</div>
{geoip?.custom_path_error && (
<Text type='danger' size='small' className='block mt-1'>
{t(
'GEOIP_DB_PATH 指定的 IP 库加载失败,当前使用内置库:{{error}}',
{
error: geoip.custom_path_error,
},
)}
</Text>
)}
<Text type='tertiary' size='small' className='block mt-1'>
{t(
'多节点部署时,立即更新只作用于处理本次请求的节点,其余节点会在每日自动检查时更新',
)}
</Text>
{geoip?.last_error && (
<Text type='danger' size='small' className='block mt-1'>
{t('上次更新失败:{{error}}', { error: geoip.last_error })}
</Text>
)}
{geoip?.persist_warning && (
<Text type='warning' size='small' className='block mt-1'>
{t('磁盘保存异常:{{message}}', {
message: geoip.persist_warning,
})}
</Text>
)}
<Text type='tertiary' size='small' className='block mt-3'>
{t('IP 数据来源:')}{' '}
<a
href='https://db-ip.com'
target='_blank'
rel='noopener noreferrer'
>
DB-IP.com
</a>
</Text>
</Form.Section>
</Form>
</Spin>
);
}
+262
View File
@@ -0,0 +1,262 @@
/*
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 } from 'react';
import {
Button,
Col,
Form,
Row,
Spin,
Typography,
Modal,
} from '@douyinfe/semi-ui';
import dayjs from 'dayjs';
import { useTranslation } from 'react-i18next';
import {
compareObjects,
API,
showError,
showSuccess,
showWarning,
} from '../../../helpers';
const { Text } = Typography;
export default function SettingsLog(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [loadingCleanHistoryLog, setLoadingCleanHistoryLog] = useState(false);
const [inputs, setInputs] = useState({
LogConsumeEnabled: false,
historyTimestamp: dayjs().subtract(1, 'month').toDate(),
});
const refForm = useRef();
const [inputsRow, setInputsRow] = useState(inputs);
function onSubmit() {
const updateArray = compareObjects(inputs, inputsRow).filter(
(item) => item.key !== 'historyTimestamp',
);
if (!updateArray.length) return showWarning(t('你似乎并没有修改什么'));
const requestQueue = updateArray.map((item) => {
let value = '';
if (typeof inputs[item.key] === 'boolean') {
value = String(inputs[item.key]);
} else {
value = inputs[item.key];
}
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 onCleanHistoryLog() {
if (!inputs.historyTimestamp) {
showError(t('请选择日志记录时间'));
return;
}
const now = dayjs();
const targetDate = dayjs(inputs.historyTimestamp);
const targetTime = targetDate.format('YYYY-MM-DD HH:mm:ss');
const currentTime = now.format('YYYY-MM-DD HH:mm:ss');
const daysDiff = now.diff(targetDate, 'day');
Modal.confirm({
title: t('确认清除历史日志'),
content: (
<div style={{ lineHeight: '1.8' }}>
<p>
<Text>{t('当前时间')}:</Text>
<Text strong style={{ color: 'var(--semi-color-success)' }}>
{currentTime}
</Text>
</p>
<p>
<Text>{t('选择时间')}:</Text>
<Text strong type='danger'>
{targetTime}
</Text>
{daysDiff > 0 && (
<Text type='tertiary'>
{' '}
({t('约')} {daysDiff} {t('天前')})
</Text>
)}
</p>
<div
style={{
background: '#fff7e6',
border: '1px solid #ffd591',
padding: '12px',
borderRadius: '4px',
marginTop: '12px',
color: '#333',
}}
>
<Text strong style={{ color: 'var(--semi-color-warning)' }}>
⚠️ {t('注意')}:
</Text>
<Text style={{ color: '#333' }}>{t('将删除')} </Text>
<Text strong style={{ color: 'var(--semi-color-danger)' }}>
{targetTime}
</Text>
{daysDiff > 0 && (
<Text style={{ color: '#8c8c8c' }}>
{' '}
({t('约')} {daysDiff} {t('天前')})
</Text>
)}
<Text style={{ color: '#333' }}> {t('之前的所有日志')}</Text>
</div>
<p style={{ marginTop: '12px' }}>
<Text type='danger'>
{t('此操作不可恢复,请仔细确认时间后再操作!')}
</Text>
</p>
</div>
),
okText: t('确认删除'),
cancelText: t('取消'),
okType: 'danger',
onOk: async () => {
try {
setLoadingCleanHistoryLog(true);
const res = await API.delete(
`/api/log/?target_timestamp=${Date.parse(inputs.historyTimestamp) / 1000}`,
);
const { success, message, data } = res.data;
if (success) {
showSuccess(`${data} ${t('条日志已清理!')}`);
return;
} else {
throw new Error(t('日志清理失败:') + message);
}
} catch (error) {
showError(error.message);
} finally {
setLoadingCleanHistoryLog(false);
}
},
});
}
useEffect(() => {
const currentInputs = {};
for (let key in props.options) {
if (Object.keys(inputs).includes(key)) {
currentInputs[key] = props.options[key];
}
}
currentInputs['historyTimestamp'] = inputs.historyTimestamp;
// Object.assign(inputs, ...) 原地修改 state 且返回同一引用,React 按引用
// 相等会跳过重渲染(当前靠下面的 setValues 补救才不出错);改为新对象。
setInputs({ ...inputs, ...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.Switch
field={'LogConsumeEnabled'}
label={t('启用额度消费日志记录')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={(value) => {
setInputs({
...inputs,
LogConsumeEnabled: value,
});
}}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Spin spinning={loadingCleanHistoryLog}>
<Form.DatePicker
label={t('清除历史日志')}
field={'historyTimestamp'}
type='dateTime'
inputReadOnly={true}
onChange={(value) => {
setInputs({
...inputs,
historyTimestamp: value,
});
}}
/>
<Text
type='tertiary'
size='small'
style={{ display: 'block', marginTop: 4, marginBottom: 8 }}
>
{t('将清除选定时间之前的所有日志')}
</Text>
<Button
size='default'
type='danger'
onClick={onCleanHistoryLog}
>
{t('清除历史日志')}
</Button>
</Spin>
</Col>
</Row>
<Row>
<Button size='default' onClick={onSubmit}>
{t('保存日志设置')}
</Button>
</Row>
</Form.Section>
</Form>
</Spin>
</>
);
}
@@ -0,0 +1,135 @@
/*
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 } from 'react';
import { Banner, Button, Col, Form, Row, Spin } from '@douyinfe/semi-ui';
import { API, showError, showSuccess, showWarning } from '../../../helpers';
import { useTranslation } from 'react-i18next';
export default function SettingsMarquee(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [inputs, setInputs] = useState({
MarqueeContent: '',
});
const refForm = useRef();
const [inputsRow, setInputsRow] = useState(inputs);
function handleFieldChange(fieldName) {
return (value) => {
setInputs((inputs) => ({ ...inputs, [fieldName]: value }));
};
}
function onSubmit() {
const updateArray = [];
for (const key in inputs) {
if (inputs.hasOwnProperty(key) && inputsRow.hasOwnProperty(key)) {
if (inputs[key] !== inputsRow[key]) {
updateArray.push({
key: key,
value: inputs[key],
});
}
}
}
if (!updateArray.length) {
showWarning(t('你似乎并没有修改什么'));
return;
}
const requestQueue = updateArray.map((item) => {
return API.put('/api/option/', {
key: item.key,
value: String(item.value),
});
});
setLoading(true);
Promise.all(requestQueue)
.then((res) => {
if (res.includes(undefined)) {
showError(t('部分保存失败,请重试'));
return;
}
showSuccess(t('保存成功'));
props.refresh();
})
.catch(() => {
showError(t('保存失败,请重试'));
})
.finally(() => {
setLoading(false);
});
}
useEffect(() => {
const currentInputs = { ...inputs };
for (let key in props.options) {
if (Object.keys(currentInputs).includes(key)) {
currentInputs[key] = 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('跑马灯公告设置')}>
<Banner
type='info'
description={t(
'跑马灯公告会在页面顶部(导航栏下方)以滚动文字的形式展示给所有用户。留空则不显示跑马灯。支持使用 | 分隔多条公告内容。',
)}
bordered
fullMode={false}
closeIcon={null}
style={{ marginBottom: 16 }}
/>
<Row gutter={16}>
<Col span={24}>
<Form.TextArea
field={'MarqueeContent'}
label={t('跑马灯公告内容')}
placeholder={t(
'请输入跑马灯公告内容,留空则不显示。多条公告请用 | 分隔,例如:欢迎使用本平台 | 新功能上线啦 | 限时优惠活动进行中',
)}
onChange={handleFieldChange('MarqueeContent')}
autosize={{ minRows: 2, maxRows: 6 }}
showClear
/>
</Col>
</Row>
<Row>
<Button size='default' onClick={onSubmit}>
{t('保存跑马灯设置')}
</Button>
</Row>
</Form.Section>
</Form>
</Spin>
);
}
@@ -0,0 +1,306 @@
/*
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 } from 'react';
import { Button, Col, Form, Row, Spin } from '@douyinfe/semi-ui';
import {
compareObjects,
API,
showError,
showSuccess,
showWarning,
} from '../../../helpers';
import { useTranslation } from 'react-i18next';
// InputNumber 清空时 onChange 会收到 ''/null,parseInt 得到 NaN:
// String(NaN) 会把字面量 "NaN" 落库(数字 NaN 经 JSON 序列化为 null,
// 后端存成 "<nil>"),且脏值永久留库。统一经此转换:非法输入回退空串——
// 传统 key 后端 Atoi('') 按 0 处理(与清空语义一致,不再留脏值);
// monitor_setting.* 命名空间 key 解析失败保留运行中旧值、重启后回默认。
const toIntString = (value) => {
const parsed = parseInt(value, 10);
return Number.isNaN(parsed) ? '' : String(parsed);
};
export default function SettingsMonitoring(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [inputs, setInputs] = useState({
ChannelDisableThreshold: '',
QuotaRemindThreshold: '',
AutomaticDisableChannelEnabled: false,
AutomaticEnableChannelEnabled: false,
ChannelServerErrorAutoDisableThreshold: '3',
AutomaticDisableKeywords: '',
'monitor_setting.auto_test_channel_enabled': false,
'monitor_setting.auto_test_channel_minutes': 10,
ChannelAffinityEnabled: false,
ChannelAffinityTTL: 300,
});
const refForm = useRef();
const [inputsRow, setInputsRow] = useState(inputs);
function onSubmit() {
const updateArray = compareObjects(inputs, inputsRow);
if (!updateArray.length) return showWarning(t('你似乎并没有修改什么'));
const requestQueue = updateArray.map((item) => {
let value = '';
if (typeof inputs[item.key] === 'boolean') {
value = String(inputs[item.key]);
} else {
value = inputs[item.key];
}
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);
});
}
useEffect(() => {
const currentInputs = {};
for (let key in props.options) {
if (Object.keys(inputs).includes(key)) {
currentInputs[key] = 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.Switch
field={'monitor_setting.auto_test_channel_enabled'}
label={t('定时测试所有通道')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={(value) =>
setInputs({
...inputs,
'monitor_setting.auto_test_channel_enabled': value,
})
}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
label={t('自动测试所有通道间隔时间')}
step={1}
min={1}
suffix={t('分钟')}
extraText={t('每隔多少分钟测试一次所有通道')}
placeholder={''}
field={'monitor_setting.auto_test_channel_minutes'}
onChange={(value) =>
setInputs({
...inputs,
'monitor_setting.auto_test_channel_minutes':
toIntString(value),
})
}
/>
</Col>
</Row>
<Row gutter={16}>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
label={t('测试所有渠道的最长响应时间')}
step={1}
min={0}
suffix={t('秒')}
extraText={t(
'当运行通道全部测试时,超过此时间将自动禁用通道',
)}
placeholder={''}
field={'ChannelDisableThreshold'}
onChange={(value) =>
setInputs({
...inputs,
ChannelDisableThreshold: String(value),
})
}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
label={t('额度提醒阈值')}
step={1}
min={0}
suffix={'Token'}
extraText={t('低于此额度时将发送邮件提醒用户')}
placeholder={''}
field={'QuotaRemindThreshold'}
onChange={(value) =>
setInputs({
...inputs,
QuotaRemindThreshold: String(value),
})
}
/>
</Col>
</Row>
<Row gutter={16}>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'AutomaticDisableChannelEnabled'}
label={t('失败时自动禁用通道')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={(value) => {
setInputs({
...inputs,
AutomaticDisableChannelEnabled: value,
});
}}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'AutomaticEnableChannelEnabled'}
label={t('成功时自动启用通道')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={(value) =>
setInputs({
...inputs,
AutomaticEnableChannelEnabled: value,
})
}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
label={t('5xx 错误自动禁用阈值')}
step={1}
min={0}
suffix={t('次')}
extraText={t(
'渠道连续返回 5xx 错误达到此次数时自动禁用,0 表示不启用',
)}
placeholder={'3'}
field={'ChannelServerErrorAutoDisableThreshold'}
onChange={(value) =>
setInputs({
...inputs,
ChannelServerErrorAutoDisableThreshold:
toIntString(value),
})
}
/>
</Col>
</Row>
<Row gutter={16}>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'ChannelAffinityEnabled'}
label={t('渠道会话亲和性')}
extraText={t(
'将同一用户的连续请求路由到同一渠道,提升上游 Prompt Cache 命中率(需启用 Redis)',
)}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={(value) =>
setInputs({
...inputs,
ChannelAffinityEnabled: value,
})
}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
label={t('亲和性缓存有效期')}
step={30}
min={30}
max={3600}
suffix={t('秒')}
extraText={t(
'用户在此时间内的请求将路由到同一渠道,默认 300 秒',
)}
placeholder={'300'}
field={'ChannelAffinityTTL'}
onChange={(value) =>
setInputs({
...inputs,
ChannelAffinityTTL: toIntString(value),
})
}
/>
</Col>
</Row>
<Row gutter={16}>
<Col xs={24} sm={16}>
<Form.TextArea
label={t('自动禁用关键词')}
placeholder={t('一行一个,不区分大小写')}
extraText={t(
'当上游通道返回错误中包含这些关键词时(不区分大小写),自动禁用通道',
)}
field={'AutomaticDisableKeywords'}
autosize={{ minRows: 6, maxRows: 12 }}
onChange={(value) =>
setInputs({ ...inputs, AutomaticDisableKeywords: value })
}
/>
</Col>
</Row>
<Row>
<Button size='default' onClick={onSubmit}>
{t('保存监控设置')}
</Button>
</Row>
</Form.Section>
</Form>
</Spin>
</>
);
}
@@ -0,0 +1,266 @@
/*
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, useContext } from 'react';
import {
Banner,
Button,
Card,
Col,
Form,
Row,
Switch,
Typography,
} from '@douyinfe/semi-ui';
import { API, showError, showSuccess } from '../../../helpers';
import { useTranslation } from 'react-i18next';
import { StatusContext } from '../../../context/Status';
import {
getOrgUserDefaultNavModules,
normalizeOrgUserNavModules,
isHeaderModuleEnabled,
} from '../../../constants/headerNavModules';
const { Text } = Typography;
const OPTION_KEY = 'HeaderNavModulesOrgUser';
// 中部一级导航模块
const moduleKeys = [
'home',
'experienceCenter',
'keyManagement',
'userCenter',
'console',
'pricing',
'skillMarket',
'docs',
'weyai',
'about',
];
// 右侧按钮 / 头像菜单入口
const rightActionKeys = [
'tutorial',
'promotion',
'recharge',
// 下面 rightActionConfigs 每多一项,这里必须同步登记,否则开关只显示不落库
'weyaiDownload',
'notifications',
'theme',
'newYear',
'userSettings',
'keyManagement',
'orgCenter',
];
export default function SettingsOrgUserNavModules(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [statusState, statusDispatch] = useContext(StatusContext);
const [modules, setModules] = useState({});
const [rightActions, setRightActions] = useState({});
// 仅展示对企业员工真实生效的开关:
// - home/about 在顶栏导航中无对应链接(全仓无 isHeaderModuleEnabled 消费点);
// - console 链接带 adminOnly 且 /console 不在企业员工路由放行清单,开了也进不去;
// - rightActions.orgCenter 全仓无读取点。
// 上述死开关从 UI 移除(保存结构仍保留 key,由预设默认值兜底),
// 避免"打开对应开关并保存"的承诺对这些项不成立。
const moduleConfigs = [
{ key: 'experienceCenter', title: t('体验中心') },
{ key: 'keyManagement', title: t('秘钥管理') },
{ key: 'userCenter', title: t('用户中心') },
{ key: 'pricing', title: t('模型广场') },
// 技能超市是企业员工基线里唯一默认开启的 C 端入口(方案决策点 3):
// 纯只读、不产生 C 端消费,且是员工理解「我有哪些技能可用」的唯一途径。
// 其路由已在 App.jsx 的 ORG_USER_NAV_PATHS 中放行,开关与可达性一致。
{ key: 'skillMarket', title: t('技能超市') },
{ key: 'docs', title: t('文档') },
{ key: 'weyai', title: t('WeyAi') },
];
const rightActionConfigs = [
{ key: 'tutorial', title: t('新手教程按钮') },
{ key: 'promotion', title: t('推广按钮') },
{ key: 'recharge', title: t('充值按钮') },
{ key: 'weyaiDownload', title: t('下载 WeyAi 按钮') },
{ key: 'notifications', title: t('公告按钮') },
{ key: 'theme', title: t('主题按钮') },
{ key: 'newYear', title: t('新年按钮') },
{ key: 'userSettings', title: t('个人设置快捷入口') },
{ key: 'keyManagement', title: t('秘钥管理快捷入口') },
];
// 以企业硬性默认预设为基线,叠加已保存配置 → 反映实际生效状态
useEffect(() => {
const eff = normalizeOrgUserNavModules(props.options?.[OPTION_KEY] || '');
const m = {};
moduleKeys.forEach((k) => (m[k] = isHeaderModuleEnabled(eff, k)));
setModules(m);
const r = {};
rightActionKeys.forEach((k) => (r[k] = eff.rightActions?.[k] !== false));
setRightActions(r);
}, [props.options]);
// 恢复企业默认(隐藏 C 端入口的预设)
const applyRecommended = () => {
const preset = getOrgUserDefaultNavModules();
const m = {};
moduleKeys.forEach((k) => (m[k] = isHeaderModuleEnabled(preset, k)));
setModules(m);
const r = {};
rightActionKeys.forEach((k) => (r[k] = preset.rightActions?.[k] !== false));
setRightActions(r);
showSuccess(t('已恢复企业默认配置,记得点击保存'));
};
const onSubmit = async () => {
setLoading(true);
try {
const out = {};
moduleKeys.forEach((k) => (out[k] = { enabled: !!modules[k] }));
out.rightActions = {};
rightActionKeys.forEach((k) => (out.rightActions[k] = !!rightActions[k]));
const value = JSON.stringify(out);
const res = await API.put('/api/option/', { key: OPTION_KEY, value });
if (res.data.success) {
showSuccess(t('保存成功'));
statusDispatch({
type: 'set',
payload: { ...statusState.status, [OPTION_KEY]: value },
});
if (props.refresh) await props.refresh();
} else {
showError(res.data.message);
}
} catch {
showError(t('保存失败,请重试'));
} finally {
setLoading(false);
}
};
const renderSwitchCard = (cfg, checked, onChange) => (
<Col key={cfg.key} xs={24} sm={12} md={8} lg={6} xl={6}>
<Card
style={{
borderRadius: '8px',
border: '1px solid var(--semi-color-border)',
background: 'var(--semi-color-bg-1)',
minHeight: '64px',
}}
bodyStyle={{ padding: '16px' }}
hoverable
>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<div
style={{
fontWeight: 600,
fontSize: '14px',
color: 'var(--semi-color-text-0)',
}}
>
{cfg.title}
</div>
<Switch checked={checked} onChange={onChange} />
</div>
</Card>
</Col>
);
return (
<Card>
<Form.Section
text={t('企业员工顶栏')}
extraText={t(
'控制「仅企业资源」员工账号登录后顶栏可见的入口;普通用户不受影响',
)}
>
<Banner
type='info'
closeIcon={null}
description={t(
'仅对 org_only(仅企业资源)模式的员工账号生效。已默认隐藏 C 端入口(秘钥/模型超市/用户中心/充值/推广等),开箱即生效;如需放开某项,打开对应开关并保存。',
)}
style={{ marginBottom: '16px' }}
/>
<div style={{ fontWeight: 600, marginBottom: '12px' }}>
{t('中部导航')}
</div>
<Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
{moduleConfigs.map((cfg) =>
renderSwitchCard(cfg, !!modules[cfg.key], (v) =>
setModules((prev) => ({ ...prev, [cfg.key]: v })),
),
)}
</Row>
<div style={{ fontWeight: 600, marginBottom: '12px' }}>
{t('右侧按钮 / 头像菜单')}
</div>
<Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
{rightActionConfigs.map((cfg) =>
renderSwitchCard(cfg, !!rightActions[cfg.key], (v) =>
setRightActions((prev) => ({ ...prev, [cfg.key]: v })),
),
)}
</Row>
<div
style={{
display: 'flex',
gap: '12px',
paddingTop: '8px',
borderTop: '1px solid var(--semi-color-border)',
}}
>
<Button type='tertiary' onClick={applyRecommended}>
{t('恢复企业默认')}
</Button>
<Button
type='primary'
onClick={onSubmit}
loading={loading}
style={{ minWidth: '100px' }}
>
{t('保存设置')}
</Button>
</div>
<Text
type='tertiary'
size='small'
style={{ display: 'block', marginTop: '8px' }}
>
{t(
'提示:本设置仅控制顶栏显隐;个人资源访问由企业「仅企业资源」模式在后端拦截。',
)}
</Text>
</Form.Section>
</Card>
);
}
@@ -0,0 +1,157 @@
/*
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 } from 'react';
import { Button, Col, Form, Row, Spin } from '@douyinfe/semi-ui';
import {
compareObjects,
API,
showError,
showSuccess,
showWarning,
} from '../../../helpers';
import { useTranslation } from 'react-i18next';
export default function SettingsSensitiveWords(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [inputs, setInputs] = useState({
CheckSensitiveEnabled: false,
CheckSensitiveOnPromptEnabled: false,
SensitiveWords: '',
});
const refForm = useRef();
const [inputsRow, setInputsRow] = useState(inputs);
function onSubmit() {
const updateArray = compareObjects(inputs, inputsRow);
if (!updateArray.length) return showWarning(t('你似乎并没有修改什么'));
const requestQueue = updateArray.map((item) => {
let value = '';
if (typeof inputs[item.key] === 'boolean') {
value = String(inputs[item.key]);
} else {
value = inputs[item.key];
}
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);
});
}
useEffect(() => {
const currentInputs = {};
for (let key in props.options) {
if (Object.keys(inputs).includes(key)) {
currentInputs[key] = 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.Switch
field={'CheckSensitiveEnabled'}
label={t('启用屏蔽词过滤功能')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={(value) => {
setInputs({
...inputs,
CheckSensitiveEnabled: value,
});
}}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'CheckSensitiveOnPromptEnabled'}
label={t('启用 Prompt 检查')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={(value) =>
setInputs({
...inputs,
CheckSensitiveOnPromptEnabled: value,
})
}
/>
</Col>
</Row>
<Row>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.TextArea
label={t('屏蔽词列表')}
extraText={t('一行一个屏蔽词,不需要符号分割')}
placeholder={t('一行一个屏蔽词,不需要符号分割')}
field={'SensitiveWords'}
onChange={(value) =>
setInputs({
...inputs,
SensitiveWords: value,
})
}
style={{ fontFamily: 'JetBrains Mono, Consolas' }}
autosize={{ minRows: 6, maxRows: 12 }}
/>
</Col>
</Row>
<Row>
<Button size='default' onClick={onSubmit}>
{t('保存屏蔽词过滤设置')}
</Button>
</Row>
</Form.Section>
</Form>
</Spin>
</>
);
}
@@ -0,0 +1,831 @@
/*
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, { useState, useEffect, useContext } from 'react';
import { useTranslation } from 'react-i18next';
import {
Card,
Form,
Button,
Switch,
Row,
Col,
Select,
Typography,
} from '@douyinfe/semi-ui';
import { API, showSuccess, showError } from '../../../helpers';
import { StatusContext } from '../../../context/Status';
import {
getVisibleGroupOptions,
normalizeGroups,
} from '../../../helpers/navigationVisibility';
import { getDefaultSidebarModulesAdmin } from '../../../constants/sidebarModules';
import {
CLOUD_BRAIN_UI_ENABLED,
isCloudBrainOrgModule,
} from '../../../config/cloudBrainUi';
const { Text } = Typography;
const normalizeModuleGroups = (moduleGroups) => {
if (!moduleGroups || typeof moduleGroups !== 'object') return {};
return Object.keys(moduleGroups).reduce((acc, key) => {
acc[key] = normalizeGroups(moduleGroups[key]);
return acc;
}, {});
};
const withVisibilityMeta = (section = {}) => ({
...section,
groups: normalizeGroups(section.groups),
moduleGroups: normalizeModuleGroups(section.moduleGroups),
});
// Keep the settings UI in sync with runtime sidebar defaults.
const createDefaultSidebarModules = () =>
Object.entries(getDefaultSidebarModulesAdmin()).reduce(
(acc, [sectionKey, section]) => {
acc[sectionKey] = withVisibilityMeta(section);
return acc;
},
{},
);
const mergeSidebarModules = (savedModules = {}) => {
const defaults = createDefaultSidebarModules();
const merged = {};
Object.keys(defaults).forEach((sectionKey) => {
const savedSection = savedModules[sectionKey] || {};
merged[sectionKey] = withVisibilityMeta({
...defaults[sectionKey],
...savedSection,
});
});
Object.keys(savedModules || {}).forEach((sectionKey) => {
if (!merged[sectionKey]) {
const savedSection = savedModules[sectionKey] || {};
merged[sectionKey] = withVisibilityMeta(savedSection);
}
});
const ucFromDb = savedModules.userCenter || {};
const needsUsageRecordMigration =
ucFromDb.usageRecord === undefined &&
ucFromDb.usageLog === false &&
ucFromDb.taskLog === false;
if (needsUsageRecordMigration) {
merged.userCenter.usageRecord = false;
}
delete merged.userCenter.usageLog;
delete merged.userCenter.taskLog;
// 迁移清理:技能相关开关曾被错误放在体验中心区域(无任何消费方),
// 现已移至企业中心(orgCenter.*,由 OrgSidebar 与 /org 路由守卫消费)。
delete merged.experienceCenter.mySkills;
delete merged.experienceCenter.skillMarket;
delete merged.experienceCenter.skillLibrary;
delete merged.experienceCenter.skillAssignments;
return merged;
};
export default function SettingsSidebarModulesAdmin(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [groupOptions, setGroupOptions] = useState([]);
const [statusState, statusDispatch] = useContext(StatusContext);
const [sidebarModulesAdmin, setSidebarModulesAdmin] = useState(
createDefaultSidebarModules(),
);
const getMergedGroupOptions = (selectedGroups) =>
getVisibleGroupOptions(groupOptions, selectedGroups);
function handleSectionChange(sectionKey) {
return (checked) => {
setSidebarModulesAdmin((prev) => ({
...prev,
[sectionKey]: {
...prev[sectionKey],
enabled: checked,
},
}));
};
}
function handleSectionGroupsChange(sectionKey) {
return (groups) => {
setSidebarModulesAdmin((prev) => ({
...prev,
[sectionKey]: {
...prev[sectionKey],
groups: normalizeGroups(groups),
},
}));
};
}
function handleModuleChange(sectionKey, moduleKey) {
return (checked) => {
setSidebarModulesAdmin((prev) => ({
...prev,
[sectionKey]: {
...prev[sectionKey],
[moduleKey]: checked,
},
}));
};
}
function handleModuleGroupsChange(sectionKey, moduleKey) {
return (groups) => {
setSidebarModulesAdmin((prev) => ({
...prev,
[sectionKey]: {
...prev[sectionKey],
moduleGroups: {
...(prev[sectionKey]?.moduleGroups || {}),
[moduleKey]: normalizeGroups(groups),
},
},
}));
};
}
function resetSidebarModules() {
setSidebarModulesAdmin(createDefaultSidebarModules());
showSuccess(t('已重置为默认配置'));
}
async function onSubmit() {
setLoading(true);
try {
const res = await API.put('/api/option/', {
key: 'SidebarModulesAdmin',
value: JSON.stringify(sidebarModulesAdmin),
});
const { success, message } = res.data;
if (success) {
showSuccess(t('保存成功'));
statusDispatch({
type: 'set',
payload: {
...statusState.status,
SidebarModulesAdmin: JSON.stringify(sidebarModulesAdmin),
},
});
if (props.refresh) {
await props.refresh();
}
} else {
showError(message);
}
} catch (error) {
showError(t('保存失败,请重试'));
} finally {
setLoading(false);
}
}
const loadAllGroups = async () => {
try {
const res = await API.get('/api/group/');
if (res.data.success) {
const groups = Array.isArray(res.data.data) ? res.data.data : [];
setGroupOptions(
groups.map((group) => ({ value: group, label: group })),
);
}
} catch {
setGroupOptions([]);
}
};
useEffect(() => {
loadAllGroups();
}, []);
useEffect(() => {
if (props.options && props.options.SidebarModulesAdmin) {
try {
const modules = JSON.parse(props.options.SidebarModulesAdmin);
setSidebarModulesAdmin(mergeSidebarModules(modules));
} catch (error) {
setSidebarModulesAdmin(createDefaultSidebarModules());
}
}
}, [props.options]);
const sectionConfigs = [
{
key: 'experienceCenter',
title: t('体验中心'),
description: t('AI模型体验功能'),
modules: [
{
key: 'cloudBrain',
title: t('云端大脑(Beta)'),
description: t('精选专家异步任务工作空间'),
},
{
key: 'imageGeneration',
title: t('图片生成'),
description: t('AI图片生成功能'),
},
{
key: 'videoGeneration',
title: t('视频生成'),
description: t('AI视频生成功能'),
},
],
},
{
key: 'userCenter',
title: t('用户中心'),
description: t('用户个人中心功能'),
modules: [
{
key: 'dashboard',
title: t('数据看板'),
description: t('用户数据统计'),
},
{
key: 'usageRecord',
title: t('使用记录'),
description: t('API使用记录和任务执行记录'),
},
{
key: 'serviceDashboard',
title: t('服务监控'),
description: t('服务可用性监控'),
},
{
key: 'topup',
title: t('在线充值'),
description: t('跳转到充值页面'),
},
{
key: 'invoice',
title: t('发票管理'),
description: t('发票抬头和开票记录'),
},
{
key: 'invite',
title: t('邀请好友'),
description: t('邀请好友获得奖励'),
},
{
key: 'settings',
title: t('个人设置'),
description: t('个人信息设置'),
},
],
},
{
key: 'chat',
title: t('聊天区域'),
description: t('操练场和聊天功能'),
modules: [
{
key: 'playground',
title: t('操练场'),
description: t('AI模型测试环境'),
},
{ key: 'chat', title: t('聊天'), description: t('聊天会话管理') },
],
},
{
key: 'console',
title: t('控制台区域'),
description: t('数据管理、日志和监控入口'),
modules: [
{ key: 'detail', title: t('数据看板'), description: t('系统数据统计') },
{ key: 'token', title: t('令牌管理'), description: t('API令牌管理') },
{ key: 'log', title: t('使用日志'), description: t('API使用记录') },
{
key: 'midjourney',
title: t('绘图日志'),
description: t('绘图任务记录'),
},
{ key: 'task', title: t('任务日志'), description: t('系统任务记录') },
{
key: 'monitor',
title: t('监控中心'),
description: t('运行状态和监控面板'),
},
],
},
{
key: 'personal',
title: t('个人中心区域'),
description: t('控制台内的用户个人功能'),
modules: [
{ key: 'topup', title: t('钱包管理'), description: t('余额充值管理') },
{
key: 'personal',
title: t('个人设置'),
description: t('个人信息设置'),
},
],
},
{
key: 'analytics',
title: t('运营看板页面'),
description: t('控制 /console/analytics 页面 Tab 入口'),
// 该区域的消费方(Analytics 页守卫)只判 enabled,不做分组过滤;
// 展示分组选择器会让管理员误以为限制生效(实际静默失效),故隐藏。
groupsSupported: false,
modules: [
{
key: 'operations',
title: t('运营看板'),
description: t('平台运营数据统计'),
},
{
key: 'quality',
title: t('调用质量'),
description: t('调用成功率、兜底与失败分析'),
},
{
key: 'risk',
title: t('风控看板'),
description: t('高频低消耗和自动封号'),
},
{
key: 'org',
title: t('个人/企业消耗'),
description: t('个人与企业消耗统计'),
},
{
key: 'audit',
title: t('体验中心上传审计'),
description: t('体验中心上传审核入口'),
},
],
},
{
key: 'orgCenter',
title: t('企业中心'),
description: t('企业控制台侧边栏功能'),
// 企业中心按企业成员身份/权限位控制可见性(OrgSidebar),不消费
// C 端用户分组;隐藏分组选择器避免"配置了却静默失效"的误导。
groupsSupported: false,
modules: [
{
key: 'knowledge',
title: t('企业知识(Beta)'),
description: t('企业知识库、文档摄取与专家引用管理'),
},
{
key: 'cloudBrain',
title: t('云端大脑(Beta)'),
description: t('企业精选专家与任务产物'),
},
{
key: 'connectors',
title: t('Connector 管理'),
description: t('企业 Connector 实例、凭据、授权与审计'),
},
{
key: 'myConnectors',
title: t('我的 AI 能力 · 业务系统授权'),
description: t('员工查看自己的 Connector 授权范围(合并页页签)'),
},
{
key: 'mySkills',
title: t('我的 AI 能力 · 我的技能'),
description: t('员工有效技能集(合并页页签)'),
},
{
key: 'skillMarket',
title: t('技能超市 · 为企业启用'),
description: t(
'允许企业管理员在技能超市自助把平台技能加入企业技能库;关闭后仅平台可代为启用',
),
},
{
key: 'skillLibrary',
title: t('技能中心 · 企业技能库'),
description: t('企业 Skill 版本与定制(合并页页签)'),
},
{
key: 'skillAssignments',
title: t('分发与锁定'),
description: t('Skill 范围策略与成员预览'),
},
{
key: 'experts',
title: t('企业专家工坊'),
description: t('企业专家版本、模型与交付路径'),
},
{
key: 'agentAudit',
title: t('Agent 任务审计'),
description: t('专家任务元数据与正文审计'),
},
{
key: 'workbench',
title: t('工作台'),
description: t('员工自助工作台'),
},
{
key: 'dashboard',
title: t('数据看板'),
description: t('企业概览与额度统计'),
},
{
key: 'quality',
title: t('调用质量'),
description: t('企业调用成功率与失败分析'),
},
{
key: 'effectiveness',
title: t('效能分析'),
description: t('覆盖、质量、效率、治理与 A/B 实验'),
},
{
key: 'privateSkills',
title: t('技能中心 · 企业自研 Skill'),
description: t('企业私有 Skill 编辑、审核与发布(合并页页签)'),
},
{
key: 'analytics',
title: t('用量分析'),
description: t('模型与成员用量趋势'),
},
{
key: 'members',
title: t('成员管理'),
description: t('企业成员管理'),
},
{
key: 'memberAccounts',
title: t('员工账号'),
description: t('集中管理员工登录账号'),
},
{
key: 'departments',
title: t('部门管理'),
description: t('组织架构与部门预算'),
},
{
key: 'projects',
title: t('项目管理'),
description: t('项目成员与项目预算'),
},
{
key: 'deptManage',
title: t('部门管理(负责人)'),
description: t('部门负责人的本部门管理入口'),
},
{
key: 'projectManage',
title: t('我的项目(项目经理)'),
description: t('项目经理的项目管理入口'),
},
{
key: 'budgets',
title: t('预算中心'),
description: t('部门/项目/成员额度上限'),
},
{
key: 'requests',
title: t('审批中心'),
description: t('提额申请与审批'),
},
{ key: 'tokens', title: t('令牌管理'), description: t('企业令牌管理') },
{ key: 'logs', title: t('消耗明细'), description: t('企业消耗记录') },
{ key: 'audit', title: t('审计日志'), description: t('企业操作审计') },
{
key: 'recharge',
title: t('企业充值'),
description: t('企业余额充值'),
},
{
key: 'settings',
title: t('企业设置'),
description: t('企业资料与配置'),
},
],
},
{
key: 'admin',
title: t('管理员区域'),
description: t('系统管理功能'),
modules: [
{
key: 'analytics',
title: t('运营看板'),
description: t('运营数据统计分析'),
},
{ key: 'channel', title: t('渠道管理'), description: t('API渠道配置') },
{ key: 'models', title: t('模型管理'), description: t('AI模型配置') },
{
key: 'redemption',
title: t('兑换码管理'),
description: t('兑换码生成管理'),
},
{ key: 'user', title: t('用户管理'), description: t('用户账户管理') },
{
key: 'subscription',
title: t('会员卡管理'),
description: t('会员订阅和卡片配置'),
},
{
key: 'admin-token',
title: t('秘钥管理'),
description: t('管理员秘钥管理'),
},
{
key: 'organizations',
title: t('企业管理'),
description: t('企业账户管理'),
},
{
key: 'skill-platform',
title: t('平台 Skill 中心'),
description: t('Skill 来源、扫描、审核与发布'),
},
{
key: 'expert-platform',
title: t('平台专家中心'),
description: t('平台专家模板与模型能力验证'),
},
{ key: 'order', title: t('订单管理'), description: t('订单记录管理') },
{
key: 'invoice',
title: t('发票管理'),
description: t('发票审核管理'),
},
{
key: 'setting',
title: t('系统设置'),
description: t('系统参数配置'),
},
],
},
];
const visibleSectionConfigs = CLOUD_BRAIN_UI_ENABLED
? sectionConfigs
: sectionConfigs.map((section) => ({
...section,
modules: section.modules.filter((module) => {
if (section.key === 'experienceCenter') {
return !isCloudBrainOrgModule(module.key);
}
if (section.key === 'orgCenter') {
return !isCloudBrainOrgModule(module.key);
}
if (section.key === 'admin') {
return (
module.key !== 'skill-platform' &&
module.key !== 'expert-platform'
);
}
return true;
}),
}));
return (
<Card>
<Form.Section
text={t('侧边栏管理(全局控制)')}
extraText={t(
'全局控制侧边栏区域、功能和可见用户分组,管理员隐藏的功能用户无法启用',
)}
>
{visibleSectionConfigs.map((section) => {
const sectionConfig = sidebarModulesAdmin[section.key] || {};
const sectionGroups = normalizeGroups(sectionConfig.groups);
return (
<div key={section.key} style={{ marginBottom: '32px' }}>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
gap: '16px',
marginBottom: '16px',
padding: '12px 16px',
backgroundColor: 'var(--semi-color-fill-0)',
borderRadius: '8px',
border: '1px solid var(--semi-color-border)',
}}
>
<div style={{ flex: 1, minWidth: 0 }}>
<div
style={{
fontWeight: '600',
fontSize: '16px',
color: 'var(--semi-color-text-0)',
marginBottom: '4px',
}}
>
{section.title}
</div>
<Text
type='secondary'
size='small'
style={{
fontSize: '12px',
color: 'var(--semi-color-text-2)',
lineHeight: '1.4',
}}
>
{section.description}
</Text>
{section.groupsSupported !== false && (
<div style={{ marginTop: '10px', maxWidth: 420 }}>
<Text
type='secondary'
size='small'
style={{ display: 'block', marginBottom: '6px' }}
>
{t('区域可见用户分组(留空表示全部分组)')}
</Text>
<Select
multiple
filter
showClear
maxTagCount={3}
placeholder={t('选择分组')}
style={{ width: '100%' }}
value={sectionGroups}
optionList={getMergedGroupOptions(sectionGroups)}
onChange={handleSectionGroupsChange(section.key)}
disabled={!sectionConfig.enabled}
/>
</div>
)}
</div>
<Switch
checked={sectionConfig.enabled}
onChange={handleSectionChange(section.key)}
size='default'
/>
</div>
<Row gutter={[16, 16]}>
{section.modules.map((module) => {
const moduleGroups = normalizeGroups(
sectionConfig.moduleGroups?.[module.key],
);
return (
<Col key={module.key} xs={24} sm={12} md={8} lg={6} xl={6}>
<Card
bodyStyle={{ padding: '16px' }}
hoverable
style={{
opacity: sectionConfig.enabled ? 1 : 0.5,
transition: 'opacity 0.2s',
}}
>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
height: '100%',
}}
>
<div style={{ flex: 1, textAlign: 'left' }}>
<div
style={{
fontWeight: '600',
fontSize: '14px',
color: 'var(--semi-color-text-0)',
marginBottom: '4px',
}}
>
{module.title}
</div>
<Text
type='secondary'
size='small'
style={{
fontSize: '12px',
color: 'var(--semi-color-text-2)',
lineHeight: '1.4',
display: 'block',
}}
>
{module.description}
</Text>
</div>
<div style={{ marginLeft: '16px' }}>
<Switch
checked={sectionConfig[module.key]}
onChange={handleModuleChange(
section.key,
module.key,
)}
size='default'
disabled={!sectionConfig.enabled}
/>
</div>
</div>
{section.groupsSupported !== false &&
sectionConfig.enabled &&
sectionConfig[module.key] && (
<div
style={{
borderTop: '1px solid var(--semi-color-border)',
marginTop: '12px',
paddingTop: '12px',
}}
>
<Text
type='secondary'
size='small'
style={{
display: 'block',
marginBottom: '6px',
}}
>
{t('功能可见用户分组(留空表示全部分组)')}
</Text>
<Select
multiple
filter
showClear
maxTagCount={2}
placeholder={t('选择分组')}
style={{ width: '100%' }}
value={moduleGroups}
optionList={getMergedGroupOptions(moduleGroups)}
onChange={handleModuleGroupsChange(
section.key,
module.key,
)}
/>
</div>
)}
</Card>
</Col>
);
})}
</Row>
</div>
);
})}
<div
style={{
display: 'flex',
gap: '12px',
justifyContent: 'flex-start',
alignItems: 'center',
paddingTop: '8px',
borderTop: '1px solid var(--semi-color-border)',
}}
>
<Button
size='default'
type='tertiary'
onClick={resetSidebarModules}
style={{
borderRadius: '6px',
fontWeight: '500',
}}
>
{t('重置为默认')}
</Button>
<Button
size='default'
type='primary'
onClick={onSubmit}
loading={loading}
style={{
borderRadius: '6px',
fontWeight: '500',
minWidth: '100px',
}}
>
{t('保存设置')}
</Button>
</div>
</Form.Section>
</Card>
);
}
@@ -0,0 +1,205 @@
/*
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, useRef, useState } from 'react';
import { Banner, Button, Col, Form, Row, Spin } from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import {
API,
compareObjects,
showError,
showSuccess,
showWarning,
} from '../../../helpers';
// InputNumber 清空时 onChange 会收到 ''/null,parseInt 得到 NaN,
// String(NaN) 会把字面量 "NaN" 永久落库(同 SettingsMonitoring 的既有教训)。
// 统一经此转换:非法输入回退空串,后端 Atoi('') 按 0 处理,再由 setting 层的
// GetXxx() 回退默认值。
const toIntString = (value) => {
const parsed = parseInt(value, 10);
return Number.isNaN(parsed) ? '' : String(parsed);
};
const DEFAULTS = {
SkillMarketRequireAuth: false,
SkillInjectEnabled: false,
SkillInjectMaxSkills: '5',
SkillInjectMaxRunes: '3000',
SkillInjectCacheTTLSeconds: '60',
};
export default function SettingsSkillInject(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [inputs, setInputs] = useState(DEFAULTS);
const [inputsRow, setInputsRow] = useState(DEFAULTS);
const refForm = useRef();
function onSubmit() {
const updateArray = compareObjects(inputs, inputsRow);
if (!updateArray.length) return showWarning(t('你似乎并没有修改什么'));
const requestQueue = updateArray.map((item) => {
const raw = inputs[item.key];
const value = typeof raw === 'boolean' ? String(raw) : String(raw);
return API.put('/api/option/', { key: item.key, value });
});
setLoading(true);
Promise.all(requestQueue)
.then((res) => {
if (res.includes(undefined)) {
return showError(t('部分保存失败,请重试'));
}
showSuccess(t('保存成功'));
props.refresh();
})
.catch(() => showError(t('保存失败,请重试')))
.finally(() => setLoading(false));
}
useEffect(() => {
const currentInputs = {};
for (const key in DEFAULTS) {
currentInputs[key] = Object.prototype.hasOwnProperty.call(
props.options,
key,
)
? props.options[key]
: DEFAULTS[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>
<Col span={24}>
<Form.Switch
field='SkillMarketRequireAuth'
label={t('技能超市要求登录')}
extraText={t(
'默认关闭,未登录访客可浏览技能元数据(不含任何约束正文)。开启后页面与目录接口同时要求登录——只改前端路由不足以防护,技能目录是平台资产的完整清单。',
)}
onChange={(value) =>
setInputs({ ...inputs, SkillMarketRequireAuth: value })
}
/>
</Col>
</Row>
<Row>
<Button size='default' onClick={onSubmit}>
{t('保存')}
</Button>
</Row>
</Form.Section>
<Form.Section text={t('技能注入(网关直连)')}>
<Banner
type='warning'
closeIcon={null}
description={t(
'这是双开关:这里打开后,还需要在具体密钥上单独开启「技能注入」才会生效。注入文本按正常 prompt token 计费,归属密钥所属方。前置注入会改变 system 前缀,依赖 prompt 缓存的高频调用方可能出现缓存失效、成本上升。',
)}
style={{ marginBottom: 12 }}
/>
<Row>
<Col span={24}>
<Form.Switch
field='SkillInjectEnabled'
label={t('启用技能注入总开关')}
extraText={t(
'关闭时注入链路在入口处直接早退,热路径零开销、行为与未上线该功能完全一致。',
)}
onChange={(value) =>
setInputs({ ...inputs, SkillInjectEnabled: value })
}
/>
</Col>
</Row>
<Row gutter={16}>
<Col xs={24} sm={12} md={8}>
<Form.InputNumber
field='SkillInjectMaxSkills'
label={t('单次最多注入技能数')}
min={1}
max={20}
extraText={t(
'默认 5,与云脑侧口径一致;两条路径取值不同会导致同一用户拿到的技能数不一样,无法向用户解释。',
)}
onChange={(value) =>
setInputs({
...inputs,
SkillInjectMaxSkills: toIntString(value),
})
}
/>
</Col>
<Col xs={24} sm={12} md={8}>
<Form.InputNumber
field='SkillInjectMaxRunes'
label={t('注入文本长度上限(字符)')}
min={200}
max={20000}
extraText={t(
'默认 3000。超出预算的技能会被整条丢弃而不是截断——半截约束比没有约束更容易让模型跑偏。',
)}
onChange={(value) =>
setInputs({
...inputs,
SkillInjectMaxRunes: toIntString(value),
})
}
/>
</Col>
<Col xs={24} sm={12} md={8}>
<Form.InputNumber
field='SkillInjectCacheTTLSeconds'
label={t('技能集缓存时长(秒)')}
min={5}
max={600}
extraText={t(
'默认 60。多节点部署下这是唯一的失效手段,也就是「改了技能最长多久对新请求生效」的产品承诺,调大请同步修改面向用户的提示文案。',
)}
onChange={(value) =>
setInputs({
...inputs,
SkillInjectCacheTTLSeconds: toIntString(value),
})
}
/>
</Col>
</Row>
<Row>
<Button size='default' onClick={onSubmit}>
{t('保存')}
</Button>
</Row>
</Form.Section>
</Form>
</Spin>
);
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,196 @@
/*
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 } from 'react';
import { Button, Form, Spin } from '@douyinfe/semi-ui';
import {
API,
removeTrailingSlash,
showError,
showSuccess,
} from '../../../helpers';
import { useTranslation } from 'react-i18next';
export default function SettingsGeneralPayment(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [inputs, setInputs] = useState({
ServerAddress: '',
ShowDefaultPayMethods: true,
HideWechatPay: false,
HideAlipayPay: false,
HidePayPal: false,
});
const formApiRef = useRef(null);
useEffect(() => {
if (props.options && formApiRef.current) {
const disabledPayMethods = Array.isArray(props.options.DisabledPayMethods)
? props.options.DisabledPayMethods
: [];
const currentInputs = {
ServerAddress: props.options.ServerAddress || '',
ShowDefaultPayMethods:
props.options.ShowDefaultPayMethods !== undefined
? props.options.ShowDefaultPayMethods
: true,
HideWechatPay: disabledPayMethods.includes('wxpay'),
HideAlipayPay: disabledPayMethods.includes('alipay'),
HidePayPal: disabledPayMethods.includes('paypal'),
};
setInputs(currentInputs);
formApiRef.current.setValues(currentInputs);
}
}, [props.options]);
const handleFormChange = (values) => {
setInputs(values);
};
const submitServerAddress = async () => {
setLoading(true);
try {
let ServerAddress = removeTrailingSlash(inputs.ServerAddress);
const res = await API.put('/api/option/', {
key: 'ServerAddress',
value: ServerAddress,
});
if (res.data.success) {
showSuccess(t('更新成功'));
props.refresh && props.refresh();
} else {
showError(res.data.message);
}
} catch (error) {
showError(t('更新失败'));
}
setLoading(false);
};
const submitShowDefaultPayMethods = async () => {
setLoading(true);
try {
const res = await API.put('/api/option/', {
key: 'payment_setting.show_default_pay_methods',
value: String(inputs.ShowDefaultPayMethods),
});
if (res.data.success) {
showSuccess(t('更新成功'));
props.refresh && props.refresh();
} else {
showError(res.data.message);
}
} catch (error) {
showError(t('更新失败'));
}
setLoading(false);
};
const submitDisabledPayMethods = async () => {
setLoading(true);
try {
// 保留 UI 未管理的其他类型(如 stripe),仅覆写当前表单管理的开关状态
const others = (
Array.isArray(props.options?.DisabledPayMethods)
? props.options.DisabledPayMethods
: []
).filter((m) => m !== 'wxpay' && m !== 'alipay' && m !== 'paypal');
const disabled = [...others];
if (inputs.HideWechatPay) disabled.push('wxpay');
if (inputs.HideAlipayPay) disabled.push('alipay');
if (inputs.HidePayPal) disabled.push('paypal');
const res = await API.put('/api/option/', {
key: 'payment_setting.disabled_pay_methods',
value: JSON.stringify(disabled),
});
if (res.data.success) {
showSuccess(t('更新成功'));
props.refresh && props.refresh();
} else {
showError(res.data.message);
}
} catch (error) {
showError(t('更新失败'));
}
setLoading(false);
};
return (
<Spin spinning={loading}>
<Form
initValues={inputs}
onValueChange={handleFormChange}
getFormApi={(api) => (formApiRef.current = api)}
>
<Form.Section text={t('通用设置')}>
<Form.Input
field='ServerAddress'
label={t('服务器地址')}
placeholder={'https://yourdomain.com'}
style={{ width: '100%' }}
extraText={t(
'该服务器地址将影响支付回调地址以及默认首页展示的地址,请确保正确配置',
)}
/>
<Button onClick={submitServerAddress}>{t('更新服务器地址')}</Button>
</Form.Section>
<Form.Section text={t('支付方式显示设置')}>
<Form.Switch
field='ShowDefaultPayMethods'
label={t('显示默认支付方式')}
extraText={t(
'启用后,即使未配置支付信息(支付地址、易支付ID、易支付密钥),也会在充值页面显示支付宝和微信的支付选项',
)}
/>
<Button onClick={submitShowDefaultPayMethods}>
{t('更新显示设置')}
</Button>
</Form.Section>
<Form.Section text={t('支付渠道开关')}>
<Form.Switch
field='HideWechatPay'
label={t('隐藏微信支付')}
extraText={t(
'开启后,充值页面将不再显示微信支付按钮,且拒绝微信支付下单(不影响已发起订单的回调入账)',
)}
/>
<Form.Switch
field='HideAlipayPay'
label={t('隐藏支付宝支付')}
extraText={t(
'开启后,充值页面将不再显示支付宝支付按钮,且拒绝支付宝下单(不影响已发起订单的回调入账)',
)}
/>
<Form.Switch
field='HidePayPal'
label={t('隐藏 PayPal 支付')}
extraText={t(
'开启后拒绝 PayPal 新订单,但仍处理已发起订单的回跳、Webhook 和主动对账',
)}
/>
<Button onClick={submitDisabledPayMethods}>
{t('更新支付渠道开关')}
</Button>
</Form.Section>
</Form>
</Spin>
);
}
@@ -0,0 +1,581 @@
/*
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 } from 'react';
import {
Button,
Card,
Switch,
InputNumber,
Input,
Table,
Modal,
Tag,
Typography,
Spin,
Space,
Select,
Popconfirm,
} from '@douyinfe/semi-ui';
import {
IconPlus,
IconDelete,
IconEdit,
IconRefresh,
} from '@douyinfe/semi-icons';
import { Crown, Sparkles, Zap } from 'lucide-react';
import { API, showError, showSuccess, renderQuota } from '../../../helpers';
import QuotaInput from '../../../components/common/ui/QuotaInput';
import { useTranslation } from 'react-i18next';
const { Text } = Typography;
const planTypeOptions = [
{ value: 'weekly', label: '周卡' },
{ value: 'monthly', label: '月卡' },
{ value: 'quarterly', label: '季卡' },
];
const tierOptions = [
{ value: 'lite', label: '轻度版' },
{ value: 'pro', label: '重度版' },
];
export default function SettingsMembership() {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [plans, setPlans] = useState([]);
const [setting, setSetting] = useState({
membership_enabled: false,
daily_grant_hour: 0,
membership_title: '会员订阅',
membership_description: '开通会员,每天自动到账额度,用完再扣账户余额',
expiry_notify_days: 3,
expiry_notify_enabled: true,
});
const [settingLoading, setSettingLoading] = useState(false);
// 编辑方案弹窗
const [editModalVisible, setEditModalVisible] = useState(false);
const [editingPlan, setEditingPlan] = useState(null);
const [editLoading, setEditLoading] = useState(false);
// 获取方案列表
const fetchPlans = async () => {
setLoading(true);
try {
const res = await API.get('/api/user/membership/manage/plans');
const { success, data } = res.data;
if (success) {
setPlans(data || []);
}
} catch (err) {
showError(t('获取会员方案失败'));
} finally {
setLoading(false);
}
};
// 获取配置
const fetchSetting = async () => {
try {
const res = await API.get('/api/user/membership/manage/setting');
const { success, data } = res.data;
if (success) {
setSetting(data);
}
} catch (err) {
console.error(err);
}
};
// 保存配置
const saveSetting = async () => {
setSettingLoading(true);
try {
const res = await API.put('/api/user/membership/manage/setting', setting);
const { success, message } = res.data;
if (success) {
showSuccess(t('配置已保存'));
} else {
showError(message);
}
} catch (err) {
showError(t('保存配置失败'));
} finally {
setSettingLoading(false);
}
};
// 保存方案
const savePlan = async (plan) => {
if (!plan?.daily_quota || plan.daily_quota <= 0) {
showError(t('请填写每日到账额度(金额需大于 0)'));
return;
}
setEditLoading(true);
try {
let res;
if (plan.id) {
res = await API.put('/api/user/membership/manage/plans', plan);
} else {
res = await API.post('/api/user/membership/manage/plans', plan);
}
const { success, message } = res.data;
if (success) {
showSuccess(plan.id ? '更新成功' : '创建成功');
setEditModalVisible(false);
setEditingPlan(null);
fetchPlans();
} else {
showError(message);
}
} catch (err) {
showError(t('保存失败'));
} finally {
setEditLoading(false);
}
};
// 删除方案
const deletePlan = async (id) => {
try {
const res = await API.delete(`/api/user/membership/manage/plans/${id}`);
const { success, message } = res.data;
if (success) {
showSuccess(t('删除成功'));
fetchPlans();
} else {
showError(message);
}
} catch (err) {
showError(t('删除失败'));
}
};
// 手动发放
const manualGrant = async () => {
try {
const res = await API.post('/api/user/membership/manage/grant');
const { success, message } = res.data;
if (success) {
showSuccess(message);
} else {
showError(message);
}
} catch (err) {
showError(t('发放失败'));
}
};
useEffect(() => {
fetchPlans();
fetchSetting();
}, []);
// 表格列定义
const columns = [
{
title: '方案名称',
dataIndex: 'name',
key: 'name',
render: (text, record) => (
<div className='flex items-center gap-2'>
<Zap size={16} className='text-blue-500' />
<Text strong>{text}</Text>
{record.badge && (
<Tag size='small' color='blue'>
{record.badge}
</Tag>
)}
</div>
),
},
{
title: '类型',
dataIndex: 'plan_type',
key: 'plan_type',
render: (v) => {
const map = { weekly: '周卡', monthly: '月卡', quarterly: '季卡' };
return <Tag>{map[v] || v}</Tag>;
},
},
{
title: '档位',
dataIndex: 'tier',
key: 'tier',
render: (v) => {
const map = { lite: '轻度', pro: '重度' };
const color = v === 'pro' ? 'red' : 'blue';
return <Tag color={color}>{map[v] || v}</Tag>;
},
},
{
title: '天数',
dataIndex: 'duration_days',
key: 'duration_days',
render: (v) => `${v} 天`,
},
{
title: '价格',
dataIndex: 'price',
key: 'price',
render: (v) => <Text strong>¥{v}</Text>,
},
{
title: '每日额度',
dataIndex: 'daily_quota',
key: 'daily_quota',
render: (v) => <Text type='success'>{renderQuota(v)}</Text>,
},
{
title: '状态',
dataIndex: 'is_enabled',
key: 'is_enabled',
render: (v) => (
<Tag color={v ? 'green' : 'grey'}>{v ? '启用' : '禁用'}</Tag>
),
},
{
title: '排序',
dataIndex: 'sort',
key: 'sort',
},
{
title: '操作',
key: 'action',
render: (_, record) => (
<Space>
<Button
icon={<IconEdit />}
size='small'
onClick={() => {
setEditingPlan({ ...record });
setEditModalVisible(true);
}}
/>
<Popconfirm
title={t('确定删除此方案?')}
onConfirm={() => deletePlan(record.id)}
>
<Button icon={<IconDelete />} size='small' type='danger' />
</Popconfirm>
</Space>
),
},
];
return (
<div className='space-y-6'>
{/* 功能配置 */}
<Card
title={
<div className='flex items-center gap-2'>
<Crown size={20} className='text-amber-500' />
<span>{t('会员功能配置')}</span>
</div>
}
>
<div className='space-y-4'>
<div className='flex items-center justify-between'>
<div>
<Text strong>{t('启用会员功能')}</Text>
<Text className='text-gray-400 block text-sm'>
{t('开启后用户可以在充值页面订阅会员')}
</Text>
</div>
<Switch
checked={setting.membership_enabled}
onChange={(v) =>
setSetting({ ...setting, membership_enabled: v })
}
/>
</div>
<div className='grid grid-cols-2 gap-4'>
<div>
<Text className='block mb-1 text-sm'>
{t('每日额度发放时间(0-23点)')}
</Text>
<InputNumber
value={setting.daily_grant_hour}
min={0}
max={23}
onChange={(v) =>
setSetting({ ...setting, daily_grant_hour: v })
}
style={{ width: '100%' }}
/>
</div>
<div>
<Text className='block mb-1 text-sm'>{t('到期提醒天数')}</Text>
<InputNumber
value={setting.expiry_notify_days}
min={1}
max={30}
onChange={(v) =>
setSetting({ ...setting, expiry_notify_days: v })
}
style={{ width: '100%' }}
/>
</div>
</div>
<div>
<Text className='block mb-1 text-sm'>{t('会员页面标题')}</Text>
<Input
value={setting.membership_title}
onChange={(v) => setSetting({ ...setting, membership_title: v })}
/>
</div>
<div>
<Text className='block mb-1 text-sm'>{t('会员页面描述')}</Text>
<Input
value={setting.membership_description}
onChange={(v) =>
setSetting({ ...setting, membership_description: v })
}
/>
</div>
<div className='flex items-center gap-2'>
<Button
theme='solid'
onClick={saveSetting}
loading={settingLoading}
>
{t('保存配置')}
</Button>
<Popconfirm
title={t('确认手动发放今日会员额度?')}
onConfirm={manualGrant}
>
<Button icon={<IconRefresh />}>{t('手动发放今日额度')}</Button>
</Popconfirm>
</div>
</div>
</Card>
{/* 方案管理 */}
<Card
title={
<div className='flex items-center justify-between w-full'>
<div className='flex items-center gap-2'>
<Sparkles size={20} className='text-brand' />
<span>{t('会员方案管理')}</span>
</div>
<Button
icon={<IconPlus />}
theme='solid'
size='small'
onClick={() => {
setEditingPlan({
name: '',
plan_type: 'monthly',
tier: 'lite',
duration_days: 30,
price: 59.9,
daily_quota: 500000,
description: '',
badge: '',
badge_color: '',
is_recommend: false,
is_enabled: true,
sort: 0,
});
setEditModalVisible(true);
}}
>
{t('新增方案')}
</Button>
</div>
}
>
{loading ? (
<Spin />
) : (
<Table
// 列宽合计远超窄屏视口;没有 scroll 时表格会压缩到 min-content 硬塞进去,
// 末尾的操作列落在视口外,且 iOS 上滚动条不可见、毫无可拖动提示
scroll={{ x: 'max-content' }}
columns={columns}
dataSource={plans}
rowKey='id'
pagination={false}
size='small'
/>
)}
</Card>
{/* 编辑方案弹窗 */}
<Modal
title={editingPlan?.id ? t('编辑方案') : t('新增方案')}
visible={editModalVisible}
onOk={() => savePlan(editingPlan)}
onCancel={() => {
setEditModalVisible(false);
setEditingPlan(null);
}}
confirmLoading={editLoading}
width={600}
centered
>
{editingPlan && (
<div className='space-y-4 py-2'>
<div className='grid grid-cols-2 gap-4'>
<div>
<Text className='block mb-1 text-sm'>{t('方案名称')}</Text>
<Input
value={editingPlan.name}
onChange={(v) => setEditingPlan({ ...editingPlan, name: v })}
placeholder={t('如:月卡·轻度')}
/>
</div>
<div>
<Text className='block mb-1 text-sm'>{t('方案类型')}</Text>
<Select
value={editingPlan.plan_type}
onChange={(v) =>
setEditingPlan({ ...editingPlan, plan_type: v })
}
optionList={planTypeOptions}
style={{ width: '100%' }}
/>
</div>
</div>
<div className='grid grid-cols-2 gap-4'>
<div>
<Text className='block mb-1 text-sm'>{t('档位')}</Text>
<Select
value={editingPlan.tier}
onChange={(v) => setEditingPlan({ ...editingPlan, tier: v })}
optionList={tierOptions}
style={{ width: '100%' }}
/>
</div>
<div>
<Text className='block mb-1 text-sm'>{t('有效天数')}</Text>
<InputNumber
value={editingPlan.duration_days}
min={1}
onChange={(v) =>
setEditingPlan({ ...editingPlan, duration_days: v })
}
style={{ width: '100%' }}
/>
</div>
</div>
<div className='grid grid-cols-2 gap-4'>
<div>
<Text className='block mb-1 text-sm'>{t('价格(元)')}</Text>
<InputNumber
value={editingPlan.price}
min={0.01}
precision={2}
onChange={(v) => setEditingPlan({ ...editingPlan, price: v })}
style={{ width: '100%' }}
/>
</div>
<div>
<Text className='block mb-1 text-sm'>{t('每日到账额度')}</Text>
<QuotaInput
value={editingPlan.daily_quota}
minQuota={1}
onChange={(v) =>
setEditingPlan({ ...editingPlan, daily_quota: v })
}
style={{ width: '100%' }}
/>
</div>
</div>
<div>
<Text className='block mb-1 text-sm'>{t('方案描述')}</Text>
<Input
value={editingPlan.description}
onChange={(v) =>
setEditingPlan({ ...editingPlan, description: v })
}
placeholder={t('方案简要描述')}
/>
</div>
<div className='grid grid-cols-2 gap-4'>
<div>
<Text className='block mb-1 text-sm'>{t('角标文字')}</Text>
<Input
value={editingPlan.badge}
onChange={(v) => setEditingPlan({ ...editingPlan, badge: v })}
placeholder={t('如:推荐、热门')}
/>
</div>
<div>
<Text className='block mb-1 text-sm'>{t('角标颜色')}</Text>
<Input
value={editingPlan.badge_color}
onChange={(v) =>
setEditingPlan({ ...editingPlan, badge_color: v })
}
placeholder='#1890ff'
/>
</div>
</div>
<div className='grid grid-cols-2 gap-4'>
<div>
<Text className='block mb-1 text-sm'>{t('排序权重')}</Text>
<InputNumber
value={editingPlan.sort}
min={0}
onChange={(v) => setEditingPlan({ ...editingPlan, sort: v })}
style={{ width: '100%' }}
/>
</div>
<div className='flex items-center gap-4 pt-6'>
<div className='flex items-center gap-2'>
<Switch
checked={editingPlan.is_enabled}
onChange={(v) =>
setEditingPlan({ ...editingPlan, is_enabled: v })
}
size='small'
/>
<Text className='text-sm'>{t('启用')}</Text>
</div>
<div className='flex items-center gap-2'>
<Switch
checked={editingPlan.is_recommend}
onChange={(v) =>
setEditingPlan({ ...editingPlan, is_recommend: v })
}
size='small'
/>
<Text className='text-sm'>{t('推荐')}</Text>
</div>
</div>
</div>
</div>
)}
</Modal>
</div>
);
}
@@ -0,0 +1,310 @@
/*
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 } from 'react';
import {
Banner,
Button,
Form,
Row,
Col,
Typography,
Spin,
} from '@douyinfe/semi-ui';
const { Text } = Typography;
import { API, showError, showSuccess, toBoolean } from '../../../helpers';
import { useTranslation } from 'react-i18next';
export default function SettingsNuonuoInvoice(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [inputs, setInputs] = useState({
NuonuoEnabled: false,
NuonuoAppKey: '',
NuonuoAppSecret: '',
NuonuoApiUrl: 'https://sdk.nuonuo.com/open/v1/services',
NuonuoCallbackUrl: '',
NuonuoTaxNum: '',
NuonuoSalerName: '',
NuonuoSalerAddress: '',
NuonuoSalerTel: '',
NuonuoSalerBank: '',
NuonuoClerk: '',
NuonuoExtensionNum: '',
NuonuoItemName: '信息技术服务*信息技术服务费',
NuonuoTaxRate: '0.06',
NuonuoMinAmount: 200,
NuonuoMonthlyLimit: 5,
});
const formApiRef = useRef(null);
useEffect(() => {
if (props.options && formApiRef.current) {
const currentInputs = {
NuonuoEnabled: toBoolean(props.options.NuonuoEnabled),
NuonuoAppKey: props.options.NuonuoAppKey || '',
NuonuoAppSecret: props.options.NuonuoAppSecret || '',
NuonuoApiUrl:
props.options.NuonuoApiUrl ||
'https://sdk.nuonuo.com/open/v1/services',
NuonuoCallbackUrl: props.options.NuonuoCallbackUrl || '',
NuonuoTaxNum: props.options.NuonuoTaxNum || '',
NuonuoSalerName: props.options.NuonuoSalerName || '',
NuonuoSalerAddress: props.options.NuonuoSalerAddress || '',
NuonuoSalerTel: props.options.NuonuoSalerTel || '',
NuonuoSalerBank: props.options.NuonuoSalerBank || '',
NuonuoClerk: props.options.NuonuoClerk || '',
NuonuoExtensionNum: props.options.NuonuoExtensionNum || '',
NuonuoItemName:
props.options.NuonuoItemName || '信息技术服务*信息技术服务费',
NuonuoTaxRate: props.options.NuonuoTaxRate || '0.06',
NuonuoMinAmount: parseFloat(props.options.NuonuoMinAmount) || 200,
NuonuoMonthlyLimit: parseInt(props.options.NuonuoMonthlyLimit) || 5,
};
setInputs(currentInputs);
formApiRef.current.setValues(currentInputs);
}
}, [props.options]);
const handleFormChange = (values) => {
setInputs(values);
};
// key 映射:前端字段名 → 后端 option key
const keyMap = {
NuonuoEnabled: 'nuonuo_setting.enabled',
NuonuoAppKey: 'nuonuo_setting.app_key',
NuonuoAppSecret: 'nuonuo_setting.app_secret',
NuonuoApiUrl: 'nuonuo_setting.api_url',
NuonuoCallbackUrl: 'nuonuo_setting.callback_url',
NuonuoTaxNum: 'nuonuo_setting.tax_num',
NuonuoSalerName: 'nuonuo_setting.saler_name',
NuonuoSalerAddress: 'nuonuo_setting.saler_address',
NuonuoSalerTel: 'nuonuo_setting.saler_tel',
NuonuoSalerBank: 'nuonuo_setting.saler_bank',
NuonuoClerk: 'nuonuo_setting.clerk',
NuonuoExtensionNum: 'nuonuo_setting.extension_num',
NuonuoItemName: 'nuonuo_setting.item_name',
NuonuoTaxRate: 'nuonuo_setting.tax_rate',
NuonuoMinAmount: 'nuonuo_setting.min_amount',
NuonuoMonthlyLimit: 'nuonuo_setting.monthly_limit',
};
const submitConfig = async () => {
setLoading(true);
try {
const options = Object.entries(keyMap).map(([frontKey, backKey]) => {
let value = inputs[frontKey];
if (typeof value === 'boolean') value = value ? 'true' : 'false';
else value = String(value ?? '');
return { key: backKey, value };
});
const results = await Promise.all(
options.map((opt) => API.put('/api/option/', opt)),
);
const errors = results.filter((res) => !res.data.success);
if (errors.length > 0) {
errors.forEach((res) => showError(res.data.message));
} else {
showSuccess(t('保存成功'));
props.refresh?.();
}
} catch (error) {
showError(t('保存失败'));
}
setLoading(false);
};
return (
<>
<Banner
type='info'
description={t(
'配置诺诺发票开放平台参数,启用后用户可在线申请开具电子发票。需先在诺诺开放平台(open.nuonuo.com)注册应用并获取 AppKey/AppSecret。',
)}
style={{ marginBottom: 16 }}
/>
<Spin spinning={loading}>
<Form
getFormApi={(api) => (formApiRef.current = api)}
onValueChange={handleFormChange}
labelPosition='left'
labelWidth='160px'
>
<Row gutter={16}>
<Col span={24}>
<Form.Switch field='NuonuoEnabled' label={t('启用发票功能')} />
</Col>
</Row>
<Text strong style={{ display: 'block', margin: '16px 0 8px' }}>
{t('API 凭证')}
</Text>
<Row gutter={16}>
<Col span={12}>
<Form.Input
field='NuonuoAppKey'
label='AppKey'
placeholder={t('诺诺应用 AppKey')}
/>
</Col>
<Col span={12}>
<Form.Input
field='NuonuoAppSecret'
label='AppSecret'
placeholder={t('诺诺应用 AppSecret')}
mode='password'
/>
</Col>
</Row>
<Row gutter={16}>
<Col span={12}>
<Form.Input
field='NuonuoApiUrl'
label={t('API 地址')}
placeholder='https://sdk.nuonuo.com/open/v1/services'
/>
</Col>
<Col span={12}>
<Form.Input
field='NuonuoCallbackUrl'
label={t('回调地址')}
placeholder={t('https://your-domain.com/api/nuonuo/callback')}
/>
</Col>
</Row>
<Text strong style={{ display: 'block', margin: '16px 0 8px' }}>
{t('销方信息')}
</Text>
<Row gutter={16}>
<Col span={12}>
<Form.Input
field='NuonuoTaxNum'
label={t('销方税号')}
placeholder={t('统一社会信用代码')}
/>
</Col>
<Col span={12}>
<Form.Input
field='NuonuoSalerName'
label={t('销方名称')}
placeholder={t('公司全称')}
/>
</Col>
</Row>
<Row gutter={16}>
<Col span={12}>
<Form.Input
field='NuonuoSalerAddress'
label={t('销方地址')}
placeholder={t('公司注册地址')}
/>
</Col>
<Col span={12}>
<Form.Input
field='NuonuoSalerTel'
label={t('销方电话')}
placeholder={t('公司电话')}
/>
</Col>
</Row>
<Row gutter={16}>
<Col span={24}>
<Form.Input
field='NuonuoSalerBank'
label={t('开户行及账号')}
placeholder={t('销方开户行及银行账号')}
/>
</Col>
</Row>
<Text strong style={{ display: 'block', margin: '16px 0 8px' }}>
{t('开票信息')}
</Text>
<Row gutter={16}>
<Col span={12}>
<Form.Input
field='NuonuoClerk'
label={t('开票员')}
placeholder={t('开票人姓名')}
/>
</Col>
<Col span={12}>
<Form.Input
field='NuonuoExtensionNum'
label={t('分机号')}
placeholder={t('全电发票分机号(非全电可留空)')}
/>
</Col>
</Row>
<Row gutter={16}>
<Col span={12}>
<Form.Input
field='NuonuoItemName'
label={t('商品名称')}
placeholder={t('信息技术服务*信息技术服务费')}
/>
</Col>
<Col span={12}>
<Form.Input
field='NuonuoTaxRate'
label={t('税率')}
placeholder={t('如 0.06 表示 6%')}
/>
</Col>
</Row>
<Text strong style={{ display: 'block', margin: '16px 0 8px' }}>
{t('业务规则')}
</Text>
<Row gutter={16}>
<Col span={12}>
<Form.InputNumber
field='NuonuoMinAmount'
label={t('最低开票金额(元)')}
min={0}
step={10}
/>
</Col>
<Col span={12}>
<Form.InputNumber
field='NuonuoMonthlyLimit'
label={t('每月申请上限(次)')}
min={1}
step={1}
/>
</Col>
</Row>
<Button
type='primary'
theme='solid'
onClick={submitConfig}
loading={loading}
style={{ marginTop: 16 }}
>
{t('保存诺诺发票配置')}
</Button>
</Form>
</Spin>
</>
);
}
@@ -0,0 +1,245 @@
/*
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, { useState } from 'react';
import {
Form,
Button,
Typography,
Space,
Divider,
} from '@douyinfe/semi-ui';
import { API, showError, showSuccess } from '../../../helpers';
import { useTranslation } from 'react-i18next';
const { Title, Text } = Typography;
const SettingsPaymentAlipay = ({ options, refresh }) => {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const onSubmit = async (values) => {
try {
setLoading(true);
// 保存支付宝配置
const configs = [
{ key: 'AlipayAppId', value: values.AlipayAppId || '' },
// 如果私钥/公钥未修改(仍然是空或占位符),则使用占位符让后端跳过更新
{
key: 'AlipayPrivateKey',
value:
values.AlipayPrivateKey && values.AlipayPrivateKey.trim() !== ''
? values.AlipayPrivateKey
: '***ALREADY_SET***',
},
{
key: 'AlipayPublicKey',
value:
values.AlipayPublicKey && values.AlipayPublicKey.trim() !== ''
? values.AlipayPublicKey
: '***ALREADY_SET***',
},
{
key: 'AlipayPCEnabled',
value: values.AlipayPCEnabled ? 'true' : 'false',
},
{
key: 'AlipayWAPEnabled',
value: values.AlipayWAPEnabled ? 'true' : 'false',
},
{
key: 'AlipayQREnabled',
value: values.AlipayQREnabled ? 'true' : 'false',
},
{
key: 'AlipayIsSandbox',
value: values.AlipayIsSandbox ? 'true' : 'false',
},
{ key: 'AlipayNotifyUrl', value: values.AlipayNotifyUrl || '' },
{ key: 'AlipayReturnUrl', value: values.AlipayReturnUrl || '' },
{ key: 'AlipaySubject', value: values.AlipaySubject || '平台充值' },
{
key: 'AlipayExpireMinutes',
value: String(values.AlipayExpireMinutes || 30),
},
];
for (const config of configs) {
const res = await API.put('/api/option/', config);
if (!res.data.success) {
throw new Error(`保存 ${config.key} 失败: ${res.data.message}`);
}
}
showSuccess(t('支付宝配置保存成功'));
if (refresh) refresh();
} catch (error) {
showError(error.message || t('保存失败'));
} finally {
setLoading(false);
}
};
return (
<>
<Title heading={5}>{t('支付宝配置')}</Title>
<Text type='tertiary'>
{t('配置支付宝电脑网站支付、手机网站支付和当面付扫码支付。请前往')}{' '}
<a
href='https://open.alipay.com'
target='_blank'
rel='noopener noreferrer'
>{t('支付宝开放平台')}</a>{' '}
{t('获取相关配置信息。')}
</Text>
<Divider margin='12px' />
<Form
labelPosition='left'
labelAlign='right'
labelWidth={180}
onSubmit={onSubmit}
initValues={{
AlipayAppId: options.AlipayAppId || '',
AlipayPrivateKey:
options.AlipayPrivateKey &&
options.AlipayPrivateKey !== '***ALREADY_SET***'
? options.AlipayPrivateKey
: '',
AlipayPublicKey:
options.AlipayPublicKey &&
options.AlipayPublicKey !== '***ALREADY_SET***'
? options.AlipayPublicKey
: '',
AlipayPCEnabled: options.AlipayPCEnabled || false,
AlipayWAPEnabled: options.AlipayWAPEnabled || false,
AlipayQREnabled: options.AlipayQREnabled || false,
AlipayIsSandbox: options.AlipayIsSandbox || false,
AlipayNotifyUrl: options.AlipayNotifyUrl || '',
AlipayReturnUrl: options.AlipayReturnUrl || '',
AlipaySubject: options.AlipaySubject || '平台充值',
AlipayExpireMinutes: options.AlipayExpireMinutes || 30,
}}
>
<Form.Input
field='AlipayAppId'
label={t('应用 ID (App ID)')}
placeholder={t('请输入支付宝应用 ID')}
rules={[{ required: true, message: t('请输入应用 ID') }]}
/>
<Form.TextArea
field='AlipayPrivateKey'
label={t('应用私钥')}
placeholder={
options.AlipayPrivateKey === '***ALREADY_SET***'
? t('已设置(留空不修改,填写新内容则更新)')
: t('请粘贴完整的 RSA2 私钥内容(包含 -----BEGIN PRIVATE KEY----- 等)')
}
rows={6}
extraText={
options.AlipayPrivateKey === '***ALREADY_SET***'
? t('✓ 已配置应用私钥(留空则保持不变)')
: t('应用私钥,用于生成签名')
}
/>
<Form.TextArea
field='AlipayPublicKey'
label={t('支付宝公钥')}
placeholder={
options.AlipayPublicKey === '***ALREADY_SET***'
? t('已设置(留空不修改,填写新内容则更新)')
: t('请粘贴支付宝公钥内容(包含 -----BEGIN PUBLIC KEY----- 等)')
}
rows={6}
extraText={
options.AlipayPublicKey === '***ALREADY_SET***'
? t('✓ 已配置支付宝公钥(留空则保持不变)')
: t('支付宝公钥(非应用公钥),用于验证签名')
}
/>
<Divider margin='12px' />
<Form.Switch
field='AlipayPCEnabled'
label={t('启用电脑网站支付')}
extraText={t('PC 端网页支付,跳转到支付宝页面')}
/>
<Form.Switch
field='AlipayWAPEnabled'
label={t('启用手机网站支付')}
extraText={t('手机浏览器唤起支付宝 APP 支付')}
/>
<Form.Switch
field='AlipayQREnabled'
label={t('启用当面付扫码支付')}
extraText={t('生成二维码,用户扫码支付')}
/>
<Form.Switch
field='AlipayIsSandbox'
label={t('沙箱模式')}
extraText={t('测试环境,使用支付宝沙箱进行调试')}
/>
<Divider margin='12px' />
<Form.Input
field='AlipayNotifyUrl'
label={t('异步通知 URL')}
placeholder={t('留空则使用默认地址')}
extraText={t('默认: {服务器地址}/api/alipay/notify')}
/>
<Form.Input
field='AlipayReturnUrl'
label={t('同步返回 URL')}
placeholder={t('留空则使用默认地址')}
extraText={t('默认: {服务器地址}/recharge')}
/>
<Form.Input
field='AlipaySubject'
label={t('商品标题')}
placeholder={t('平台充值')}
extraText={t('显示在支付宝支付界面的商品标题')}
/>
<Form.InputNumber
field='AlipayExpireMinutes'
label={t('订单过期时间(分钟)')}
min={1}
max={1440}
extraText={t('订单未支付的有效时间,默认 30 分钟')}
/>
<Space style={{ marginTop: 20 }}>
<Button type='primary' htmlType='submit' loading={loading}>{t('保存配置')}</Button>
</Space>
</Form>
</>
);
};
export default SettingsPaymentAlipay;
@@ -0,0 +1,332 @@
/*
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 } from 'react';
import { Button, Form, Row, Col, Typography, Spin } from '@douyinfe/semi-ui';
const { Text } = Typography;
import {
API,
removeTrailingSlash,
showError,
showSuccess,
verifyJSON,
} from '../../../helpers';
import { useTranslation } from 'react-i18next';
export default function SettingsPaymentGateway(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [inputs, setInputs] = useState({
PayAddress: '',
EpayId: '',
EpayKey: '',
Price: 7.3,
MinTopUp: 1,
TopupGroupRatio: '',
CustomCallbackAddress: '',
PayMethods: '',
AmountOptions: '',
AmountDiscount: '',
});
const [originInputs, setOriginInputs] = useState({});
const formApiRef = useRef(null);
useEffect(() => {
if (props.options && formApiRef.current) {
const currentInputs = {
PayAddress: props.options.PayAddress || '',
EpayId: props.options.EpayId || '',
EpayKey: props.options.EpayKey || '',
Price:
props.options.Price !== undefined
? parseFloat(props.options.Price)
: 7.3,
MinTopUp:
props.options.MinTopUp !== undefined
? parseFloat(props.options.MinTopUp)
: 1,
TopupGroupRatio: props.options.TopupGroupRatio || '',
CustomCallbackAddress: props.options.CustomCallbackAddress || '',
PayMethods: props.options.PayMethods || '',
AmountOptions: props.options.AmountOptions || '',
AmountDiscount: props.options.AmountDiscount || '',
};
// 美化 JSON 展示
try {
if (currentInputs.AmountOptions) {
currentInputs.AmountOptions = JSON.stringify(
JSON.parse(currentInputs.AmountOptions),
null,
2,
);
}
} catch {}
try {
if (currentInputs.AmountDiscount) {
currentInputs.AmountDiscount = JSON.stringify(
JSON.parse(currentInputs.AmountDiscount),
null,
2,
);
}
} catch {}
setInputs(currentInputs);
setOriginInputs({ ...currentInputs });
formApiRef.current.setValues(currentInputs);
}
}, [props.options]);
const handleFormChange = (values) => {
setInputs(values);
};
const submitPayAddress = async () => {
if (props.options.ServerAddress === '') {
showError(t('请先填写服务器地址'));
return;
}
if (originInputs['TopupGroupRatio'] !== inputs.TopupGroupRatio) {
if (!verifyJSON(inputs.TopupGroupRatio)) {
showError(t('充值分组倍率不是合法的 JSON 字符串'));
return;
}
}
if (originInputs['PayMethods'] !== inputs.PayMethods) {
if (!verifyJSON(inputs.PayMethods)) {
showError(t('充值方式设置不是合法的 JSON 字符串'));
return;
}
}
if (
originInputs['AmountOptions'] !== inputs.AmountOptions &&
inputs.AmountOptions.trim() !== ''
) {
if (!verifyJSON(inputs.AmountOptions)) {
showError(t('自定义充值数量选项不是合法的 JSON 数组'));
return;
}
}
if (
originInputs['AmountDiscount'] !== inputs.AmountDiscount &&
inputs.AmountDiscount.trim() !== ''
) {
if (!verifyJSON(inputs.AmountDiscount)) {
showError(t('充值金额折扣配置不是合法的 JSON 对象'));
return;
}
}
setLoading(true);
try {
const options = [
{ key: 'PayAddress', value: removeTrailingSlash(inputs.PayAddress) },
];
if (inputs.EpayId !== '') {
options.push({ key: 'EpayId', value: inputs.EpayId });
}
if (inputs.EpayKey !== undefined && inputs.EpayKey !== '') {
options.push({ key: 'EpayKey', value: inputs.EpayKey });
}
if (inputs.Price !== '') {
options.push({ key: 'Price', value: inputs.Price.toString() });
}
if (inputs.MinTopUp !== '') {
options.push({ key: 'MinTopUp', value: inputs.MinTopUp.toString() });
}
if (inputs.CustomCallbackAddress !== '') {
options.push({
key: 'CustomCallbackAddress',
value: inputs.CustomCallbackAddress,
});
}
if (originInputs['TopupGroupRatio'] !== inputs.TopupGroupRatio) {
options.push({ key: 'TopupGroupRatio', value: inputs.TopupGroupRatio });
}
if (originInputs['PayMethods'] !== inputs.PayMethods) {
options.push({ key: 'PayMethods', value: inputs.PayMethods });
}
if (originInputs['AmountOptions'] !== inputs.AmountOptions) {
options.push({
key: 'payment_setting.amount_options',
value: inputs.AmountOptions,
});
}
if (originInputs['AmountDiscount'] !== inputs.AmountDiscount) {
options.push({
key: 'payment_setting.amount_discount',
value: inputs.AmountDiscount,
});
}
// 发送请求
const requestQueue = options.map((opt) =>
API.put('/api/option/', {
key: opt.key,
value: opt.value,
}),
);
const results = await Promise.all(requestQueue);
// 检查所有请求是否成功
const errorResults = results.filter((res) => !res.data.success);
if (errorResults.length > 0) {
errorResults.forEach((res) => {
showError(res.data.message);
});
} else {
showSuccess(t('更新成功'));
// 更新本地存储的原始值
setOriginInputs({ ...inputs });
props.refresh && props.refresh();
}
} catch (error) {
showError(t('更新失败'));
}
setLoading(false);
};
return (
<Spin spinning={loading}>
<Form
initValues={inputs}
onValueChange={handleFormChange}
getFormApi={(api) => (formApiRef.current = api)}
>
<Form.Section text={t('支付设置')}>
<Text>
{t(
'(当前仅支持易支付接口,默认使用上方服务器地址作为回调地址!)',
)}
</Text>
<Row gutter={{ xs: 8, sm: 16, md: 24, lg: 24, xl: 24, xxl: 24 }}>
<Col xs={24} sm={24} md={8} lg={8} xl={8}>
<Form.Input
field='PayAddress'
label={t('支付地址')}
placeholder={t('例如:https://yourdomain.com')}
/>
</Col>
<Col xs={24} sm={24} md={8} lg={8} xl={8}>
<Form.Input
field='EpayId'
label={t('易支付商户ID')}
placeholder={t('例如:0001')}
/>
</Col>
<Col xs={24} sm={24} md={8} lg={8} xl={8}>
<Form.Input
field='EpayKey'
label={t('易支付商户密钥')}
placeholder={t('敏感信息不会发送到前端显示')}
type='password'
/>
</Col>
</Row>
<Row
gutter={{ xs: 8, sm: 16, md: 24, lg: 24, xl: 24, xxl: 24 }}
style={{ marginTop: 16 }}
>
<Col xs={24} sm={24} md={8} lg={8} xl={8}>
<Form.Input
field='CustomCallbackAddress'
label={t('回调地址')}
placeholder={t('例如:https://yourdomain.com')}
/>
</Col>
<Col xs={24} sm={24} md={8} lg={8} xl={8}>
<Form.InputNumber
field='Price'
precision={2}
label={t('充值价格(x元/美金)')}
placeholder={t('例如:7,就是7元/美金')}
/>
</Col>
<Col xs={24} sm={24} md={8} lg={8} xl={8}>
<Form.InputNumber
field='MinTopUp'
label={t('最低充值美元数量')}
placeholder={t('例如:2,就是最低充值2$')}
/>
</Col>
</Row>
<Form.TextArea
field='TopupGroupRatio'
label={t('充值分组倍率')}
placeholder={t('为一个 JSON 文本,键为组名称,值为倍率')}
autosize
/>
<Form.TextArea
field='PayMethods'
label={t('充值方式设置')}
placeholder={t('为一个 JSON 文本')}
autosize
/>
<Row
gutter={{ xs: 8, sm: 16, md: 24, lg: 24, xl: 24, xxl: 24 }}
style={{ marginTop: 16 }}
>
<Col span={24}>
<Form.TextArea
field='AmountOptions'
label={t('自定义充值数量选项')}
placeholder={t(
'为一个 JSON 数组,例如:[10, 20, 50, 100, 200, 500]',
)}
autosize
extraText={t(
'设置用户可选择的充值数量选项,例如:[10, 20, 50, 100, 200, 500]',
)}
/>
</Col>
</Row>
<Row
gutter={{ xs: 8, sm: 16, md: 24, lg: 24, xl: 24, xxl: 24 }}
style={{ marginTop: 16 }}
>
<Col span={24}>
<Form.TextArea
field='AmountDiscount'
label={t('充值金额折扣配置')}
placeholder={t(
'为一个 JSON 对象,例如:{"100": 0.95, "200": 0.9, "500": 0.85}',
)}
autosize
extraText={t(
'设置不同充值金额对应的折扣,键为充值金额,值为折扣率,例如:{"100": 0.95, "200": 0.9, "500": 0.85}',
)}
/>
</Col>
</Row>
<Button onClick={submitPayAddress}>{t('更新支付设置')}</Button>
</Form.Section>
</Form>
</Spin>
);
}
@@ -0,0 +1,422 @@
/*
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 } from 'react';
import {
Banner,
Button,
Form,
Row,
Col,
Typography,
Spin,
Table,
Modal,
Input,
InputNumber,
Select,
} from '@douyinfe/semi-ui';
const { Text } = Typography;
import { API, showError, showSuccess } from '../../../helpers';
import { useTranslation } from 'react-i18next';
import { Plus, Trash2 } from 'lucide-react';
export default function SettingsPaymentGatewayCreem(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [inputs, setInputs] = useState({
CreemApiKey: '',
CreemWebhookSecret: '',
CreemProducts: '[]',
CreemTestMode: false,
});
const [, setOriginInputs] = useState({});
const [products, setProducts] = useState([]);
const [showProductModal, setShowProductModal] = useState(false);
const [editingProduct, setEditingProduct] = useState(null);
const [productForm, setProductForm] = useState({
name: '',
productId: '',
price: 0,
quota: 0,
currency: 'USD',
});
const formApiRef = useRef(null);
useEffect(() => {
if (props.options && formApiRef.current) {
const currentInputs = {
CreemApiKey: props.options.CreemApiKey || '',
CreemWebhookSecret: props.options.CreemWebhookSecret || '',
CreemProducts: props.options.CreemProducts || '[]',
CreemTestMode: props.options.CreemTestMode === 'true',
};
setInputs(currentInputs);
setOriginInputs({ ...currentInputs });
formApiRef.current.setValues(currentInputs);
// Parse products
try {
const parsedProducts = JSON.parse(currentInputs.CreemProducts);
setProducts(parsedProducts);
} catch (e) {
setProducts([]);
}
}
}, [props.options]);
const handleFormChange = (values) => {
setInputs(values);
};
const submitCreemSetting = async () => {
setLoading(true);
try {
const options = [];
if (inputs.CreemApiKey && inputs.CreemApiKey !== '') {
options.push({ key: 'CreemApiKey', value: inputs.CreemApiKey });
}
if (inputs.CreemWebhookSecret && inputs.CreemWebhookSecret !== '') {
options.push({
key: 'CreemWebhookSecret',
value: inputs.CreemWebhookSecret,
});
}
// Save test mode setting
options.push({
key: 'CreemTestMode',
value: inputs.CreemTestMode ? 'true' : 'false',
});
// Save products as JSON string
options.push({ key: 'CreemProducts', value: JSON.stringify(products) });
// 发送请求
const requestQueue = options.map((opt) =>
API.put('/api/option/', {
key: opt.key,
value: opt.value,
}),
);
const results = await Promise.all(requestQueue);
// 检查所有请求是否成功
const errorResults = results.filter((res) => !res.data.success);
if (errorResults.length > 0) {
errorResults.forEach((res) => {
showError(res.data.message);
});
} else {
showSuccess(t('更新成功'));
// 更新本地存储的原始值
setOriginInputs({ ...inputs });
props.refresh?.();
}
} catch (error) {
showError(t('更新失败'));
}
setLoading(false);
};
const openProductModal = (product = null) => {
if (product) {
setEditingProduct(product);
setProductForm({ ...product });
} else {
setEditingProduct(null);
setProductForm({
name: '',
productId: '',
price: 0,
quota: 0,
currency: 'USD',
});
}
setShowProductModal(true);
};
const closeProductModal = () => {
setShowProductModal(false);
setEditingProduct(null);
setProductForm({
name: '',
productId: '',
price: 0,
quota: 0,
currency: 'USD',
});
};
const saveProduct = () => {
if (
!productForm.name ||
!productForm.productId ||
productForm.price <= 0 ||
productForm.quota <= 0 ||
!productForm.currency
) {
showError(t('请填写完整的产品信息'));
return;
}
let newProducts = [...products];
if (editingProduct) {
// 编辑现有产品
const index = newProducts.findIndex(
(p) => p.productId === editingProduct.productId,
);
if (index !== -1) {
newProducts[index] = { ...productForm };
}
} else {
// 添加新产品
if (newProducts.find((p) => p.productId === productForm.productId)) {
showError(t('产品ID已存在'));
return;
}
newProducts.push({ ...productForm });
}
setProducts(newProducts);
closeProductModal();
};
const deleteProduct = (productId) => {
const newProducts = products.filter((p) => p.productId !== productId);
setProducts(newProducts);
};
const columns = [
{
title: t('产品名称'),
dataIndex: 'name',
key: 'name',
},
{
title: t('产品ID'),
dataIndex: 'productId',
key: 'productId',
},
{
title: t('展示价格'),
dataIndex: 'price',
key: 'price',
render: (price, record) =>
`${record.currency === 'EUR' ? '€' : '¥'}${price}`,
},
{
title: t('充值额度'),
dataIndex: 'quota',
key: 'quota',
},
{
title: t('操作'),
key: 'action',
render: (_, record) => (
<div className='flex gap-2'>
<Button
type='tertiary'
size='small'
onClick={() => openProductModal(record)}
>
{t('编辑')}
</Button>
<Button
type='danger'
theme='borderless'
size='small'
icon={<Trash2 size={14} />}
onClick={() => deleteProduct(record.productId)}
/>
</div>
),
},
];
return (
<Spin spinning={loading}>
<Form
initValues={inputs}
onValueChange={handleFormChange}
getFormApi={(api) => (formApiRef.current = api)}
>
<Form.Section text={t('Creem 设置')}>
<Text>
{t('Creem 介绍')}
<a href='https://creem.io' target='_blank' rel='noreferrer'>
Creem Official Site
</a>
<br />
</Text>
<Banner type='info' description={t('Creem Setting Tips')} />
<Row gutter={{ xs: 8, sm: 16, md: 24, lg: 24, xl: 24, xxl: 24 }}>
<Col xs={24} sm={24} md={8} lg={8} xl={8}>
<Form.Input
field='CreemApiKey'
label={t('API 密钥')}
placeholder={t('Creem API 密钥,敏感信息不显示')}
type='password'
/>
</Col>
<Col xs={24} sm={24} md={8} lg={8} xl={8}>
<Form.Input
field='CreemWebhookSecret'
label={t('Webhook 密钥')}
placeholder={t(
'用于验证回调 new-api 的 webhook 请求的密钥,敏感信息不显示',
)}
type='password'
/>
</Col>
<Col xs={24} sm={24} md={8} lg={8} xl={8}>
<Form.Switch
field='CreemTestMode'
label={t('测试模式')}
extraText={t('启用后将使用 Creem Test Mode')}
/>
</Col>
</Row>
<div style={{ marginTop: 24 }}>
<div className='flex justify-between items-center mb-4'>
<Text strong>{t('产品配置')}</Text>
<Button
type='primary'
icon={<Plus size={16} />}
onClick={() => openProductModal()}
>
{t('添加产品')}
</Button>
</div>
<Table
columns={columns}
dataSource={products}
pagination={false}
empty={
<div className='text-center py-8'>
<Text type='tertiary'>{t('暂无产品配置')}</Text>
</div>
}
/>
</div>
<Button onClick={submitCreemSetting} style={{ marginTop: 16 }}>
{t('更新 Creem 设置')}
</Button>
</Form.Section>
</Form>
{/* 产品配置模态框 */}
<Modal
title={editingProduct ? t('编辑产品') : t('添加产品')}
visible={showProductModal}
onOk={saveProduct}
onCancel={closeProductModal}
maskClosable={false}
size='small'
centered
>
<div className='space-y-4'>
<div>
<Text strong className='block mb-2'>
{t('产品名称')}
</Text>
<Input
value={productForm.name}
onChange={(value) =>
setProductForm({ ...productForm, name: value })
}
placeholder={t('例如:基础套餐')}
size='large'
/>
</div>
<div>
<Text strong className='block mb-2'>
{t('产品ID')}
</Text>
<Input
value={productForm.productId}
onChange={(value) =>
setProductForm({ ...productForm, productId: value })
}
placeholder={t('例如:prod_6I8rBerHpPxyoiU9WK4kot')}
size='large'
disabled={!!editingProduct}
/>
</div>
<div>
<Text strong className='block mb-2'>
{t('货币')}
</Text>
<Select
value={productForm.currency}
onChange={(value) =>
setProductForm({ ...productForm, currency: value })
}
size='large'
className='w-full'
>
<Select.Option value='USD'>{t('USD (美元)')}</Select.Option>
<Select.Option value='EUR'>{t('EUR (欧元)')}</Select.Option>
</Select>
</div>
<div>
<Text strong className='block mb-2'>
{t('价格')} (
{productForm.currency === 'EUR' ? t('欧元') : t('美元')})
</Text>
<InputNumber
value={productForm.price}
onChange={(value) =>
setProductForm({ ...productForm, price: value })
}
placeholder={t('例如:4.99')}
min={0.01}
precision={2}
size='large'
className='w-full'
defaultValue={4.49}
/>
</div>
<div>
<Text strong className='block mb-2'>
{t('充值额度')}
</Text>
<InputNumber
value={productForm.quota}
onChange={(value) =>
setProductForm({ ...productForm, quota: value })
}
placeholder={t('例如:100000')}
min={1}
precision={0}
size='large'
className='w-full'
/>
</div>
</div>
</Modal>
</Spin>
);
}
@@ -0,0 +1,971 @@
/*
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, { useCallback, useEffect, useRef, useState } from 'react';
import {
Banner,
Button,
Checkbox,
Col,
Form,
Modal,
Row,
Spin,
Table,
TextArea,
Typography,
} from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import {
API,
isRoot,
removeTrailingSlash,
showError,
showSuccess,
} from '../../../helpers';
import { mergePayPalFeePolicyFormValues } from '../../../helpers/paypalPayment';
const { Text } = Typography;
const SECRET_PLACEHOLDER = '***ALREADY_SET***';
const PAYPAL_OPERATIONS_PAGE_SIZE = 20;
function normalizePayPalOperations(data) {
if (!data || typeof data !== 'object' || Array.isArray(data)) {
return null;
}
return {
...data,
pending_count: Number.isFinite(Number(data.pending_count))
? Number(data.pending_count)
: 0,
pending_page: Number.isFinite(Number(data.pending_page))
? Number(data.pending_page)
: 1,
pending_page_size: Number.isFinite(Number(data.pending_page_size))
? Number(data.pending_page_size)
: 20,
pending_orders: Array.isArray(data.pending_orders)
? data.pending_orders.filter(
(order) =>
order &&
typeof order === 'object' &&
typeof order.trade_no === 'string' &&
order.trade_no.trim() !== '',
)
: [],
config_history: Array.isArray(data.config_history)
? data.config_history
: [],
can_change_config: Boolean(data.can_change_config),
};
}
export default function SettingsPaymentGatewayPayPal(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [fxStatus, setFxStatus] = useState(null);
const [feePolicy, setFeePolicy] = useState(null);
const [feeAudits, setFeeAudits] = useState([]);
const [feeAuditPage, setFeeAuditPage] = useState(1);
const [feeAuditTotal, setFeeAuditTotal] = useState(0);
const [operations, setOperations] = useState(null);
const [operationsPage, setOperationsPage] = useState(1);
const [selectedOperationOrderKeys, setSelectedOperationOrderKeys] = useState(
[],
);
const [expireOrder, setExpireOrder] = useState(null);
const [expireReason, setExpireReason] = useState('');
const [forceExpire, setForceExpire] = useState(false);
const [forceExpireConfirmed, setForceExpireConfirmed] = useState(false);
const [batchExpire, setBatchExpire] = useState(null);
const [batchExpireReason, setBatchExpireReason] = useState('');
const [batchForceConfirmed, setBatchForceConfirmed] = useState(false);
const formApiRef = useRef(null);
const [inputs, setInputs] = useState({
PayPalClientID: '',
PayPalClientSecret: '',
PayPalWebhookID: '',
PayPalSandbox: true,
PayPalMinTopUp: 1,
PayPalFXMode: 'manual',
PayPalFXProvider: 'open_exchange_rates',
PayPalFXAPIKey: '',
PayPalFXAdjustmentBps: 0,
PayPalUserPaysFee: false,
PayPalFeeRatePercent: 0,
});
useEffect(() => {
const values = {
PayPalClientID: props.options?.PayPalClientID || '',
PayPalClientSecret: props.options?.PayPalClientSecret || '',
PayPalWebhookID: props.options?.PayPalWebhookID || '',
PayPalSandbox: props.options?.PayPalSandbox ?? true,
PayPalMinTopUp: Number(props.options?.PayPalMinTopUp) || 1,
PayPalFXMode: props.options?.PayPalFXMode || 'manual',
PayPalFXProvider:
props.options?.PayPalFXProvider || 'open_exchange_rates',
PayPalFXAPIKey: props.options?.PayPalFXAPIKey || '',
PayPalFXAdjustmentBps: Number(props.options?.PayPalFXAdjustmentBps) || 0,
};
setInputs((current) => {
const next = {
...values,
PayPalUserPaysFee: current.PayPalUserPaysFee,
PayPalFeeRatePercent: current.PayPalFeeRatePercent,
};
formApiRef.current?.setValues(next);
return next;
});
}, [props.options]);
const refreshFXStatus = useCallback(async () => {
try {
const response = await API.get('/api/option/paypal/fx/status');
if (response.data.success) setFxStatus(response.data.data);
} catch {
setFxStatus(null);
}
}, []);
useEffect(() => {
refreshFXStatus();
}, [refreshFXStatus]);
const refreshFeePolicy = useCallback(
async (page = 1, preserveDraft = false) => {
if (!isRoot()) return;
try {
const [policyResponse, auditResponse] = await Promise.all([
API.get('/api/option/paypal/fee-policy'),
API.get(
`/api/option/paypal/fee-policy/audits?p=${page}&page_size=20`,
),
]);
if (policyResponse.data.success) {
const policy = policyResponse.data.data;
setFeePolicy(policy);
if (!preserveDraft) {
setInputs((current) =>
mergePayPalFeePolicyFormValues(current, policy),
);
if (formApiRef.current) {
formApiRef.current.setValues(
mergePayPalFeePolicyFormValues(
formApiRef.current.getValues(),
policy,
),
);
}
}
}
if (auditResponse.data.success) {
const auditData = auditResponse.data.data;
setFeeAudits(auditData?.items || []);
setFeeAuditPage(page);
setFeeAuditTotal(Number(auditData?.total || 0));
}
} catch (error) {
showError(error?.response?.data?.message || t('获取手续费策略失败'));
}
},
[t],
);
useEffect(() => {
refreshFeePolicy(1);
}, [refreshFeePolicy]);
const refreshOperations = useCallback(
async (page = 1) => {
if (!isRoot()) return;
try {
const response = await API.get(
`/api/option/paypal/operations/preflight?p=${page}&page_size=${PAYPAL_OPERATIONS_PAGE_SIZE}`,
);
if (response?.data?.success) {
setOperations(normalizePayPalOperations(response.data.data));
setOperationsPage(page);
}
} catch (error) {
showError(
error?.response?.data?.message || t('获取 PayPal 订单预检信息失败'),
);
}
},
[t],
);
useEffect(() => {
refreshOperations(1);
}, [refreshOperations]);
const inspectOperationOrder = async (tradeNo) => {
setLoading(true);
try {
const response = await API.post(
`/api/option/paypal/operations/orders/${encodeURIComponent(tradeNo)}/inspect`,
);
if (!response.data.success)
throw new Error(response.data.message || t('查询失败'));
const data = response.data.data;
showSuccess(`${tradeNo}:PayPal 状态 ${data.remote_status}`);
setSelectedOperationOrderKeys((keys) =>
keys.filter((key) => key !== String(tradeNo)),
);
await refreshOperations(operationsPage);
} catch (error) {
showError(
error?.response?.data?.message || error?.message || t('查询失败'),
);
} finally {
setLoading(false);
}
};
const reconcileOperationOrder = async (tradeNo) => {
setLoading(true);
try {
const response = await API.post(
`/api/option/paypal/operations/orders/${encodeURIComponent(tradeNo)}/reconcile`,
);
if (!response.data.success)
throw new Error(response.data.message || t('对账失败'));
showSuccess(t('PayPal 订单已触发对账'));
setSelectedOperationOrderKeys((keys) =>
keys.filter((key) => key !== String(tradeNo)),
);
await refreshOperations(operationsPage);
} catch (error) {
showError(
error?.response?.data?.message || error?.message || t('对账失败'),
);
} finally {
setLoading(false);
}
};
const expireOperationOrder = async () => {
const reason =
typeof expireReason === 'string'
? expireReason.trim()
: String(expireReason ?? '').trim();
if (!expireOrder || reason.length < 6) {
showError(t('请填写至少 6 个字符的过期原因'));
return;
}
if (forceExpire && !forceExpireConfirmed) {
showError(t('请先确认强制过期风险'));
return;
}
setLoading(true);
try {
const response = await API.post(
`/api/option/paypal/operations/orders/${encodeURIComponent(expireOrder.trade_no)}/expire`,
{
confirm_trade_no: expireOrder.trade_no,
reason,
force: forceExpire,
},
);
if (!response.data.success)
throw new Error(response.data.message || t('过期失败'));
showSuccess(t('PayPal 订单已标记为过期'));
setExpireOrder(null);
setExpireReason('');
setForceExpire(false);
setForceExpireConfirmed(false);
setSelectedOperationOrderKeys((keys) =>
keys.filter((key) => key !== String(expireOrder.trade_no)),
);
await refreshOperations(operationsPage);
} catch (error) {
showError(
error?.response?.data?.message || error?.message || t('过期失败'),
);
} finally {
setLoading(false);
}
};
const runBatchOperation = async (operation) => {
if (selectedOperationOrderKeys.length === 0) {
showError(t('请先勾选 PayPal 订单'));
return;
}
setLoading(true);
try {
const response = await API.post(
'/api/option/paypal/operations/orders/batch',
{
trade_nos: selectedOperationOrderKeys,
operation,
},
);
if (!response?.data?.success) {
throw new Error(response?.data?.message || t('批量操作失败'));
}
const data = response.data.data || {};
const failedResults = (data.results || []).filter(
(item) => !item.success,
);
showSuccess(
`批量${operation === 'inspect' ? '查询' : '对账'}完成:成功 ${data.succeeded || 0} 笔,失败 ${data.failed || 0} 笔`,
);
if (failedResults.length > 0) {
showError(
failedResults
.slice(0, 3)
.map((item) => `${item.trade_no}:${item.message || t('操作失败')}`)
.join(';'),
);
}
setSelectedOperationOrderKeys([]);
await refreshOperations(operationsPage);
} catch (error) {
showError(
error?.response?.data?.message || error?.message || t('批量操作失败'),
);
} finally {
setLoading(false);
}
};
const openBatchExpire = (force) => {
if (selectedOperationOrderKeys.length === 0) {
showError(t('请先勾选 PayPal 订单'));
return;
}
setBatchExpire({ tradeNos: selectedOperationOrderKeys, force });
setBatchForceConfirmed(false);
setBatchExpireReason(
force
? '管理员确认远端状态无法核验,强制关闭所选 PayPal 订单'
: '确认所选 PayPal 订单均未完成支付',
);
};
const confirmBatchExpire = async () => {
const reason = batchExpireReason.trim();
if (!batchExpire || reason.length < 6) {
showError(t('请填写至少 6 个字符的过期原因'));
return;
}
if (batchExpire.force && !batchForceConfirmed) {
showError(t('请先确认强制过期风险'));
return;
}
setLoading(true);
try {
const response = await API.post(
'/api/option/paypal/operations/orders/batch',
{
trade_nos: batchExpire.tradeNos,
operation: 'expire',
reason,
force: batchExpire.force,
},
);
if (!response?.data?.success) {
throw new Error(response?.data?.message || t('批量过期失败'));
}
const data = response.data.data || {};
const failedResults = (data.results || []).filter(
(item) => !item.success,
);
showSuccess(
`批量${batchExpire.force ? '强制' : ''}过期完成:成功 ${data.succeeded || 0} 笔,失败 ${data.failed || 0} 笔`,
);
if (failedResults.length > 0) {
showError(
failedResults
.slice(0, 3)
.map((item) => `${item.trade_no}:${item.message || t('操作失败')}`)
.join(';'),
);
}
setBatchExpire(null);
setBatchExpireReason('');
setBatchForceConfirmed(false);
setSelectedOperationOrderKeys([]);
await refreshOperations(operationsPage);
} catch (error) {
showError(
error?.response?.data?.message || error?.message || t('批量过期失败'),
);
} finally {
setLoading(false);
}
};
const submit = async () => {
if (!props.options?.ServerAddress) {
showError(t('请先填写服务器地址'));
return;
}
const options = [
{ key: 'PayPalClientID', value: inputs.PayPalClientID?.trim() },
{ key: 'PayPalWebhookID', value: inputs.PayPalWebhookID?.trim() },
{ key: 'PayPalSandbox', value: String(inputs.PayPalSandbox) },
{ key: 'PayPalMinTopUp', value: String(inputs.PayPalMinTopUp || 1) },
{ key: 'PayPalFXMode', value: inputs.PayPalFXMode || 'manual' },
{
key: 'PayPalFXProvider',
value: inputs.PayPalFXProvider || 'open_exchange_rates',
},
{
key: 'PayPalFXAdjustmentBps',
value: String(inputs.PayPalFXAdjustmentBps || 0),
},
];
if (
inputs.PayPalClientSecret &&
inputs.PayPalClientSecret !== SECRET_PLACEHOLDER
) {
options.push({
key: 'PayPalClientSecret',
value: inputs.PayPalClientSecret,
});
}
if (inputs.PayPalFXAPIKey && inputs.PayPalFXAPIKey !== SECRET_PLACEHOLDER) {
options.push({ key: 'PayPalFXAPIKey', value: inputs.PayPalFXAPIKey });
}
setLoading(true);
try {
for (const option of options) {
const response = await API.put('/api/option/', option);
if (!response.data.success) {
throw new Error(response.data.message || t('更新失败'));
}
}
if (isRoot()) {
const rateBps = Math.round(
Number(inputs.PayPalFeeRatePercent || 0) * 100,
);
if (
rateBps < 0 ||
rateBps > 2000 ||
(inputs.PayPalUserPaysFee && rateBps < 1)
) {
throw new Error(t('手续费比例必须在有效范围内'));
}
const response = await API.put('/api/option/paypal/fee-policy', {
user_pays_fee: Boolean(inputs.PayPalUserPaysFee),
rate_bps: rateBps,
expected_version: feePolicy?.version,
});
if (!response.data.success) {
throw new Error(response.data.message || t('更新失败'));
}
}
showSuccess(t('更新成功'));
await props.refresh?.();
await refreshFXStatus();
await refreshFeePolicy(1);
} catch (error) {
if (error?.response?.status === 409) {
await refreshFeePolicy(feeAuditPage, true);
showError(t('手续费策略已被其他管理员更新,请重新确认'));
} else {
showError(
error?.response?.data?.message || error?.message || t('更新失败'),
);
}
} finally {
setLoading(false);
}
};
const webhookBase = props.options?.ServerAddress
? removeTrailingSlash(props.options.ServerAddress)
: t('网站地址');
const pendingOrders = Array.isArray(operations?.pending_orders)
? operations.pending_orders
: [];
const runFXAction = async (action) => {
setLoading(true);
try {
const response = await API.post(`/api/option/paypal/fx/${action}`);
if (!response.data.success) {
throw new Error(response.data.message || t('操作失败'));
}
showSuccess(
t(action === 'refresh' ? '汇率刷新成功' : '已确认手工兜底汇率'),
);
await refreshFXStatus();
} catch (error) {
showError(error?.message || t('操作失败'));
} finally {
setLoading(false);
}
};
return (
<Spin spinning={loading}>
<Form
initValues={inputs}
onValueChange={(values) => setInputs({ ...values })}
getFormApi={(api) => (formApiRef.current = api)}
>
<Form.Section text={t('PayPal 设置')}>
<Banner
type='info'
description={`${t('Webhook 地址')}:${webhookBase}/api/paypal/webhook`}
/>
{isRoot() && (
<>
<Row gutter={16} style={{ marginTop: 16 }}>
<Col xs={24} md={8}>
<Form.Switch
field='PayPalUserPaysFee'
label={t('用户承担支付服务费')}
checkedText='|'
uncheckedText='〇'
/>
</Col>
<Col xs={24} md={8}>
<Form.InputNumber
field='PayPalFeeRatePercent'
label={t('支付服务费比例(%)')}
min={inputs.PayPalUserPaysFee ? 0.01 : 0}
max={20}
precision={2}
disabled={!inputs.PayPalUserPaysFee}
/>
</Col>
<Col xs={24} md={8}>
<Text type='tertiary'>
{t('手续费策略版本')}:{feePolicy?.version || '-'}
<br />
{t('最后更新')}:
{feePolicy?.updated_at
? new Date(feePolicy.updated_at * 1000).toLocaleString()
: '-'}
<br />
{t('最后更新人')}:{feePolicy?.updated_by || '-'}
</Text>
</Col>
</Row>
<Banner
type='info'
description={t(
'默认由平台承担;启用后将按配置比例向用户展示并收取支付服务费',
)}
style={{ marginTop: 16 }}
/>
<Table
size='small'
pagination={{
currentPage: feeAuditPage,
pageSize: 20,
total: feeAuditTotal,
showTotal: true,
onPageChange: (page) => refreshFeePolicy(page, true),
}}
dataSource={feeAudits}
rowKey='id'
style={{ marginTop: 16 }}
columns={[
{
title: t('版本'),
dataIndex: 'policy_version',
width: 80,
},
{
title: t('承担方'),
dataIndex: 'new_user_pays_fee',
render: (value) => t(value ? '用户承担' : '平台承担'),
},
{
title: t('费率'),
dataIndex: 'new_rate_bps',
render: (value) => `${(Number(value) / 100).toFixed(2)}%`,
},
{
title: t('操作人'),
dataIndex: 'operator_id',
},
{
title: t('更新时间'),
dataIndex: 'created_at',
render: (value) =>
value ? new Date(value * 1000).toLocaleString() : '-',
},
]}
/>
<Banner
type={operations?.pending_count ? 'warning' : 'success'}
description={
operations
? `配置切换预检:${operations.pending_count || 0} 笔 PayPal pending 订单;${
operations.can_change_config
? '可以切换环境或应用配置'
: '请先隐藏新订单并完成历史订单排空'
}`
: '正在读取 PayPal 配置切换预检状态'
}
style={{ marginTop: 16 }}
/>
{pendingOrders.length > 0 && (
<div
className='flex flex-wrap items-center gap-2'
style={{ marginTop: 12 }}
>
<Text type='tertiary'>
已选 {selectedOperationOrderKeys.length} 笔
</Text>
<Button
size='small'
htmlType='button'
disabled={selectedOperationOrderKeys.length === 0}
onClick={() => runBatchOperation('inspect')}
>
批量查询远端状态
</Button>
<Button
size='small'
theme='solid'
htmlType='button'
disabled={selectedOperationOrderKeys.length === 0}
onClick={() => runBatchOperation('reconcile')}
>
批量触发对账
</Button>
<Button
size='small'
type='danger'
htmlType='button'
disabled={selectedOperationOrderKeys.length === 0}
onClick={() => openBatchExpire(false)}
>
批量确认过期
</Button>
<Button
size='small'
type='warning'
htmlType='button'
disabled={selectedOperationOrderKeys.length === 0}
onClick={() => openBatchExpire(true)}
>
批量强制过期
</Button>
</div>
)}
{pendingOrders.length > 0 && (
<Table
size='small'
rowKey='trade_no'
dataSource={pendingOrders}
rowSelection={{
selectedRowKeys: selectedOperationOrderKeys,
onChange: (keys) =>
setSelectedOperationOrderKeys(keys.map(String)),
}}
pagination={{
currentPage: operationsPage,
pageSize: PAYPAL_OPERATIONS_PAGE_SIZE,
total: Number(operations?.pending_count || 0),
showTotal: true,
onPageChange: (page) => {
setSelectedOperationOrderKeys([]);
refreshOperations(page);
},
}}
scroll={{ x: 900 }}
style={{ marginTop: 12 }}
columns={[
{ title: '本地订单号', dataIndex: 'trade_no' },
{ title: 'PayPal Order ID', dataIndex: 'third_trade_no' },
{ title: '环境', dataIndex: 'payment_environment' },
{
title: '创建时间',
dataIndex: 'create_time',
render: (value) =>
value ? new Date(value * 1000).toLocaleString() : '-',
},
{
title: '操作',
render: (_, row) => (
<div className='flex flex-wrap gap-2'>
<Button
size='small'
htmlType='button'
onClick={() => inspectOperationOrder(row.trade_no)}
>
查询远端状态
</Button>
<Button
size='small'
theme='solid'
htmlType='button'
onClick={() =>
reconcileOperationOrder(row.trade_no)
}
disabled={!row.third_trade_no}
>
触发对账
</Button>
<Button
size='small'
type='danger'
htmlType='button'
onClick={() => {
setExpireOrder(row);
setForceExpire(false);
setForceExpireConfirmed(false);
setExpireReason('确认该订单未完成 PayPal 支付');
}}
>
确认未付款并过期
</Button>
<Button
size='small'
type='warning'
htmlType='button'
onClick={() => {
setExpireOrder(row);
setForceExpire(true);
setForceExpireConfirmed(false);
setExpireReason(
'管理员确认远端状态无法核验,强制关闭该 PayPal 订单',
);
}}
>
强制过期
</Button>
</div>
),
},
]}
/>
)}
<Button
size='small'
type='tertiary'
htmlType='button'
onClick={() => refreshOperations(operationsPage)}
style={{ marginTop: 12 }}
>
刷新配置切换预检
</Button>
</>
)}
<Banner
type='warning'
description={t(
'订阅 CHECKOUT.ORDER.APPROVED、PAYMENT.CAPTURE.COMPLETED、PAYMENT.CAPTURE.PENDING、PAYMENT.CAPTURE.DECLINED、PAYMENT.CAPTURE.DENIED 和 CHECKOUT.PAYMENT-APPROVAL.REVERSED 事件',
)}
/>
<Row gutter={16}>
<Col xs={24} md={8}>
<Form.Input field='PayPalClientID' label='Client ID' />
</Col>
<Col xs={24} md={8}>
<Form.Input
field='PayPalClientSecret'
label='Client Secret'
type='password'
placeholder={t('敏感信息不会显示')}
/>
</Col>
<Col xs={24} md={8}>
<Form.Input field='PayPalWebhookID' label='Webhook ID' />
</Col>
</Row>
<Row gutter={16} style={{ marginTop: 16 }}>
<Col xs={24} md={8}>
<Form.Switch
field='PayPalSandbox'
label={t('Sandbox 测试环境')}
checkedText='|'
uncheckedText='〇'
/>
</Col>
<Col xs={24} md={8}>
<Form.InputNumber
field='PayPalMinTopUp'
label={t('最低充值单位')}
min={1}
precision={0}
/>
</Col>
<Col xs={24} md={8}>
<Text type='tertiary'>
{t('结算币种')}:USD
<br />
{t('换算汇率')}:USDExchangeRate ={' '}
{props.options?.USDExchangeRate || '-'}
</Text>
</Col>
</Row>
<Row gutter={16} style={{ marginTop: 16 }}>
<Col xs={24} md={8}>
<Form.Select
field='PayPalFXMode'
label={t('汇率模式')}
optionList={[
{ label: t('手工汇率'), value: 'manual' },
{ label: t('准实时汇率'), value: 'realtime' },
]}
/>
</Col>
<Col xs={24} md={8}>
<Form.Input
field='PayPalFXAPIKey'
label='Open Exchange Rates API Key'
type='password'
placeholder={t('敏感信息不会显示')}
/>
</Col>
<Col xs={24} md={8}>
<Form.InputNumber
field='PayPalFXAdjustmentBps'
label={t('汇率保护加点(基点)')}
min={0}
max={300}
precision={0}
/>
</Col>
</Row>
<Banner
type={fxStatus?.latest_valid ? 'success' : 'warning'}
description={
fxStatus?.latest_valid
? `${t('当前市场汇率')}:1 USD = ${fxStatus.latest_valid.market_rate} CNY`
: t('暂无可用的市场汇率快照')
}
style={{ marginTop: 16 }}
/>
<div className='flex flex-wrap gap-2' style={{ marginTop: 12 }}>
<Button onClick={submit} disabled={isRoot() && !feePolicy}>
{t('更新 PayPal 设置')}
</Button>
<Button type='tertiary' onClick={() => runFXAction('refresh')}>
{t('立即刷新汇率')}
</Button>
<Button type='warning' onClick={() => runFXAction('acknowledge')}>
{t('确认手工兜底汇率')}
</Button>
</div>
</Form.Section>
</Form>
<Modal
title={
forceExpire ? '确认强制过期 PayPal 订单' : '确认 PayPal 订单过期'
}
visible={Boolean(expireOrder)}
onCancel={() => setExpireOrder(null)}
onOk={expireOperationOrder}
okText='确认过期'
cancelText='取消'
>
{expireOrder && (
<div className='space-y-3'>
<Text>
订单:<strong>{expireOrder.trade_no}</strong>
</Text>
<Banner
type={forceExpire ? 'danger' : 'warning'}
description={
forceExpire
? '强制过期会绕过远端查询失败或仍可支付状态,可能导致 PayPal 后续付款无法入账。已确认完成支付的订单仍会被拒绝。'
: '系统会再次查询 PayPal 远端状态;如果已完成支付,将拒绝过期操作。请确认未付款后再提交。'
}
/>
{forceExpire && (
<Checkbox
checked={forceExpireConfirmed}
onChange={(event) =>
setForceExpireConfirmed(
Boolean(event?.target?.checked ?? event?.checked),
)
}
>
我确认已核对 PayPal 后台或业务记录,同意强制关闭该订单
</Checkbox>
)}
<TextArea
value={expireReason}
onChange={(value) =>
setExpireReason(
typeof value === 'string'
? value
: value?.target?.value || '',
)
}
rows={3}
placeholder='填写处置原因,至少 6 个字符'
/>
</div>
)}
</Modal>
<Modal
title={
batchExpire?.force
? '确认批量强制过期 PayPal 订单'
: '确认批量 PayPal 订单过期'
}
visible={Boolean(batchExpire)}
onCancel={() => setBatchExpire(null)}
onOk={confirmBatchExpire}
okText='确认批量过期'
cancelText='取消'
>
{batchExpire && (
<div className='space-y-3'>
<Text>已选择 {batchExpire.tradeNos.length} 笔 PayPal 订单。</Text>
<Banner
type={batchExpire.force ? 'danger' : 'warning'}
description={
batchExpire.force
? '批量强制过期会绕过远端查询失败或仍可支付状态;已确认完成支付的订单仍会逐笔拒绝。'
: '系统会逐笔查询 PayPal 远端状态,已完成或仍可支付的订单会逐笔失败并返回原因。'
}
/>
{batchExpire.force && (
<Checkbox
checked={batchForceConfirmed}
onChange={(event) =>
setBatchForceConfirmed(
Boolean(event?.target?.checked ?? event?.checked),
)
}
>
我确认已核对所选订单,同意批量强制关闭
</Checkbox>
)}
<TextArea
value={batchExpireReason}
onChange={(value) =>
setBatchExpireReason(
typeof value === 'string'
? value
: value?.target?.value || '',
)
}
rows={3}
placeholder='填写处置原因,至少 6 个字符'
/>
</div>
)}
</Modal>
</Spin>
);
}
@@ -0,0 +1,250 @@
/*
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 } from 'react';
import {
Banner,
Button,
Form,
Row,
Col,
Typography,
Spin,
} from '@douyinfe/semi-ui';
const { Text } = Typography;
import {
API,
removeTrailingSlash,
showError,
showSuccess,
} from '../../../helpers';
import { useTranslation } from 'react-i18next';
export default function SettingsPaymentGateway(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [inputs, setInputs] = useState({
StripeApiSecret: '',
StripeWebhookSecret: '',
StripePriceId: '',
StripeUnitPrice: 8.0,
StripeMinTopUp: 1,
StripePromotionCodesEnabled: false,
});
const [originInputs, setOriginInputs] = useState({});
const formApiRef = useRef(null);
useEffect(() => {
if (props.options && formApiRef.current) {
const currentInputs = {
StripeApiSecret: props.options.StripeApiSecret || '',
StripeWebhookSecret: props.options.StripeWebhookSecret || '',
StripePriceId: props.options.StripePriceId || '',
StripeUnitPrice:
props.options.StripeUnitPrice !== undefined
? parseFloat(props.options.StripeUnitPrice)
: 8.0,
StripeMinTopUp:
props.options.StripeMinTopUp !== undefined
? parseFloat(props.options.StripeMinTopUp)
: 1,
StripePromotionCodesEnabled:
props.options.StripePromotionCodesEnabled !== undefined
? props.options.StripePromotionCodesEnabled
: false,
};
setInputs(currentInputs);
setOriginInputs({ ...currentInputs });
formApiRef.current.setValues(currentInputs);
}
}, [props.options]);
const handleFormChange = (values) => {
setInputs(values);
};
const submitStripeSetting = async () => {
if (props.options.ServerAddress === '') {
showError(t('请先填写服务器地址'));
return;
}
setLoading(true);
try {
const options = [];
if (inputs.StripeApiSecret && inputs.StripeApiSecret !== '') {
options.push({ key: 'StripeApiSecret', value: inputs.StripeApiSecret });
}
if (inputs.StripeWebhookSecret && inputs.StripeWebhookSecret !== '') {
options.push({
key: 'StripeWebhookSecret',
value: inputs.StripeWebhookSecret,
});
}
if (inputs.StripePriceId !== '') {
options.push({ key: 'StripePriceId', value: inputs.StripePriceId });
}
if (
inputs.StripeUnitPrice !== undefined &&
inputs.StripeUnitPrice !== null
) {
options.push({
key: 'StripeUnitPrice',
value: inputs.StripeUnitPrice.toString(),
});
}
if (
inputs.StripeMinTopUp !== undefined &&
inputs.StripeMinTopUp !== null
) {
options.push({
key: 'StripeMinTopUp',
value: inputs.StripeMinTopUp.toString(),
});
}
if (
originInputs['StripePromotionCodesEnabled'] !==
inputs.StripePromotionCodesEnabled &&
inputs.StripePromotionCodesEnabled !== undefined
) {
options.push({
key: 'StripePromotionCodesEnabled',
value: inputs.StripePromotionCodesEnabled ? 'true' : 'false',
});
}
// 发送请求
const requestQueue = options.map((opt) =>
API.put('/api/option/', {
key: opt.key,
value: opt.value,
}),
);
const results = await Promise.all(requestQueue);
// 检查所有请求是否成功
const errorResults = results.filter((res) => !res.data.success);
if (errorResults.length > 0) {
errorResults.forEach((res) => {
showError(res.data.message);
});
} else {
showSuccess(t('更新成功'));
// 更新本地存储的原始值
setOriginInputs({ ...inputs });
props.refresh?.();
}
} catch (error) {
showError(t('更新失败'));
}
setLoading(false);
};
return (
<Spin spinning={loading}>
<Form
initValues={inputs}
onValueChange={handleFormChange}
getFormApi={(api) => (formApiRef.current = api)}
>
<Form.Section text={t('Stripe 设置')}>
<Text>
Stripe 密钥、Webhook 等设置请
<a
href='https://dashboard.stripe.com/developers'
target='_blank'
rel='noreferrer'
>{t('点击此处')}</a>{t('进行设置,最好先在')}<a
href='https://dashboard.stripe.com/test/developers'
target='_blank'
rel='noreferrer'
>{t('测试环境')}</a>{t('进行测试。')}<br />
</Text>
<Banner
type='info'
description={`Webhook 填:${props.options.ServerAddress ? removeTrailingSlash(props.options.ServerAddress) : t('网站地址')}/api/stripe/webhook`}
/>
<Banner
type='warning'
description={`需要包含事件:checkout.session.completed 和 checkout.session.expired`}
/>
<Row gutter={{ xs: 8, sm: 16, md: 24, lg: 24, xl: 24, xxl: 24 }}>
<Col xs={24} sm={24} md={8} lg={8} xl={8}>
<Form.Input
field='StripeApiSecret'
label={t('API 密钥')}
placeholder={t(
'sk_xxx 或 rk_xxx 的 Stripe 密钥,敏感信息不显示',
)}
type='password'
/>
</Col>
<Col xs={24} sm={24} md={8} lg={8} xl={8}>
<Form.Input
field='StripeWebhookSecret'
label={t('Webhook 签名密钥')}
placeholder={t('whsec_xxx 的 Webhook 签名密钥,敏感信息不显示')}
type='password'
/>
</Col>
<Col xs={24} sm={24} md={8} lg={8} xl={8}>
<Form.Input
field='StripePriceId'
label={t('商品价格 ID')}
placeholder={t('price_xxx 的商品价格 ID,新建产品后可获得')}
/>
</Col>
</Row>
<Row
gutter={{ xs: 8, sm: 16, md: 24, lg: 24, xl: 24, xxl: 24 }}
style={{ marginTop: 16 }}
>
<Col xs={24} sm={24} md={8} lg={8} xl={8}>
<Form.InputNumber
field='StripeUnitPrice'
precision={2}
label={t('充值价格(x元/美金)')}
placeholder={t('例如:7,就是7元/美金')}
/>
</Col>
<Col xs={24} sm={24} md={8} lg={8} xl={8}>
<Form.InputNumber
field='StripeMinTopUp'
label={t('最低充值美元数量')}
placeholder={t('例如:2,就是最低充值2$')}
/>
</Col>
<Col xs={24} sm={24} md={8} lg={8} xl={8}>
<Form.Switch
field='StripePromotionCodesEnabled'
size='default'
checkedText='|'
uncheckedText='〇'
label={t('允许在 Stripe 支付中输入促销码')}
/>
</Col>
</Row>
<Button onClick={submitStripeSetting}>{t('更新 Stripe 设置')}</Button>
</Form.Section>
</Form>
</Spin>
);
}
@@ -0,0 +1,352 @@
/*
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, { useState } from 'react';
import {
Form,
Button,
Typography,
Space,
Divider,
} from '@douyinfe/semi-ui';
import { API, showError, showSuccess } from '../../../helpers';
import { useTranslation } from 'react-i18next';
const { Title, Text } = Typography;
const SettingsPaymentWechat = ({ options, refresh }) => {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const onSubmit = async (values) => {
try {
setLoading(true);
// 保存微信支付配置
const configs = [
{ key: 'WechatMchId', value: values.WechatMchId || '' },
{ key: 'WechatAppId', value: values.WechatAppId || '' },
// 如果敏感字段未修改(仍然是空或占位符),则使用占位符让后端跳过更新
{
key: 'WechatAPIv3Key',
value:
values.WechatAPIv3Key && values.WechatAPIv3Key.trim() !== ''
? values.WechatAPIv3Key
: '***ALREADY_SET***',
},
{ key: 'WechatSerialNo', value: values.WechatSerialNo || '' },
{
key: 'WechatPrivateKey',
value:
values.WechatPrivateKey && values.WechatPrivateKey.trim() !== ''
? values.WechatPrivateKey
: '***ALREADY_SET***',
},
{
key: 'WechatNativeEnabled',
value: values.WechatNativeEnabled ? 'true' : 'false',
},
{
key: 'WechatH5Enabled',
value: values.WechatH5Enabled ? 'true' : 'false',
},
{ key: 'WechatNotifyUrl', value: values.WechatNotifyUrl || '' },
{
key: 'WechatDescription',
value: values.WechatDescription || '平台充值',
},
{
key: 'WechatExpireMinutes',
value: String(values.WechatExpireMinutes || 30),
},
// 公钥模式配置(2024年新商户)
{
key: 'WechatUsePublicKey',
value: values.WechatUsePublicKey ? 'true' : 'false',
},
{ key: 'WechatPublicKeyID', value: values.WechatPublicKeyID || '' },
{
key: 'WechatPublicKeyPEM',
value:
values.WechatPublicKeyPEM && values.WechatPublicKeyPEM.trim() !== ''
? values.WechatPublicKeyPEM
: '***ALREADY_SET***',
},
// 手动证书模式配置
{
key: 'WechatUseManualCert',
value: values.WechatUseManualCert ? 'true' : 'false',
},
{
key: 'WechatPlatformCertPath',
value: values.WechatPlatformCertPath || '',
},
{
key: 'WechatPlatformCertPEM',
value:
values.WechatPlatformCertPEM &&
values.WechatPlatformCertPEM.trim() !== ''
? values.WechatPlatformCertPEM
: '***ALREADY_SET***',
},
];
for (const config of configs) {
const res = await API.put('/api/option/', config);
if (!res.data.success) {
throw new Error(`保存 ${config.key} 失败: ${res.data.message}`);
}
}
showSuccess(t('微信支付配置保存成功'));
if (refresh) refresh();
} catch (error) {
showError(error.message || t('保存失败'));
} finally {
setLoading(false);
}
};
return (
<>
<Title heading={5}>{t('微信支付配置')}</Title>
<Text type='tertiary'>
配置微信支付 Native(扫码)和 H5 支付方式。请前往{' '}
<a
href='https://pay.weixin.qq.com'
target='_blank'
rel='noopener noreferrer'
>{t('微信支付商户平台')}</a>{' '}
获取相关配置信息。
</Text>
<Divider margin='12px' />
<Form
labelPosition='left'
labelAlign='right'
labelWidth={180}
onSubmit={onSubmit}
initValues={{
WechatMchId: options.WechatMchId || '',
WechatAppId: options.WechatAppId || '',
WechatAPIv3Key:
options.WechatAPIv3Key &&
options.WechatAPIv3Key !== '***ALREADY_SET***'
? options.WechatAPIv3Key
: '',
WechatSerialNo: options.WechatSerialNo || '',
WechatPrivateKey:
options.WechatPrivateKey &&
options.WechatPrivateKey !== '***ALREADY_SET***'
? options.WechatPrivateKey
: '',
WechatNativeEnabled: options.WechatNativeEnabled || false,
WechatH5Enabled: options.WechatH5Enabled || false,
WechatNotifyUrl: options.WechatNotifyUrl || '',
WechatDescription: options.WechatDescription || '平台充值',
WechatExpireMinutes: options.WechatExpireMinutes || 30,
// 公钥模式
WechatUsePublicKey: options.WechatUsePublicKey || false,
WechatPublicKeyID: options.WechatPublicKeyID || '',
WechatPublicKeyPEM:
options.WechatPublicKeyPEM &&
options.WechatPublicKeyPEM !== '***ALREADY_SET***'
? options.WechatPublicKeyPEM
: '',
// 手动证书模式
WechatUseManualCert: options.WechatUseManualCert || false,
WechatPlatformCertPath: options.WechatPlatformCertPath || '',
WechatPlatformCertPEM:
options.WechatPlatformCertPEM &&
options.WechatPlatformCertPEM !== '***ALREADY_SET***'
? options.WechatPlatformCertPEM
: '',
}}
>
<Form.Input
field='WechatMchId'
label={t('商户号 (Mch ID)')}
placeholder={t('请输入微信支付商户号')}
rules={[{ required: true, message: '请输入商户号' }]}
/>
<Form.Input
field='WechatAppId'
label={t('应用 ID (App ID)')}
placeholder={t('请输入微信应用 ID')}
rules={[{ required: true, message: '请输入应用 ID' }]}
/>
<Form.Input
field='WechatAPIv3Key'
label={t('APIv3 密钥')}
placeholder={
options.WechatAPIv3Key === '***ALREADY_SET***'
? '已设置(留空不修改,填写新内容则更新)'
: '请输入 APIv3 密钥'
}
mode='password'
extraText={
options.WechatAPIv3Key === '***ALREADY_SET***'
? '✓ 已配置 APIv3 密钥(留空则保持不变)'
: ''
}
/>
<Form.Input
field='WechatSerialNo'
label={t('证书序列号')}
placeholder={t('请输入证书序列号')}
rules={[{ required: true, message: '请输入证书序列号' }]}
/>
<Form.TextArea
field='WechatPrivateKey'
label={t('商户私钥')}
placeholder={
options.WechatPrivateKey === '***ALREADY_SET***'
? '已设置(留空不修改,填写新内容则更新)'
: '请粘贴完整的 PEM 格式私钥内容(包含 -----BEGIN PRIVATE KEY----- 等)'
}
rows={6}
extraText={
options.WechatPrivateKey === '***ALREADY_SET***'
? '✓ 已配置商户私钥(留空则保持不变)'
: '支持直接粘贴 PEM 格式内容或填写文件路径'
}
/>
<Divider margin='12px' />
<Title heading={6} style={{ marginTop: 16, marginBottom: 8 }}>{t('公钥模式(2024年新商户必选)')}</Title>
<Text type='tertiary' style={{ display: 'block', marginBottom: 12 }}>
2024年后注册的微信支付商户默认使用公钥模式。如果初始化失败提示"无可用的平台证书",
请从商户平台下载微信支付公钥并启用此模式。
</Text>
<Form.Switch
field='WechatUsePublicKey'
label={t('启用公钥模式')}
extraText='2024年新商户必须开启此选项'
/>
<Form.Input
field='WechatPublicKeyID'
label={t('微信支付公钥 ID')}
placeholder='PUB_KEY_ID_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
extraText='从商户平台【API安全】→【微信支付公钥】获取,格式如 PUB_KEY_ID_xxx'
/>
<Form.TextArea
field='WechatPublicKeyPEM'
label={t('微信支付公钥内容')}
placeholder={
options.WechatPublicKeyPEM === '***ALREADY_SET***'
? '已设置(留空不修改,填写新内容则更新)'
: '请粘贴完整的微信支付公钥 PEM 内容(包含 -----BEGIN PUBLIC KEY----- 等)'
}
rows={6}
extraText={
options.WechatPublicKeyPEM === '***ALREADY_SET***'
? '✓ 已配置微信支付公钥(留空则保持不变)'
: '从商户平台下载的公钥文件内容'
}
/>
<Divider margin='12px' />
<Title heading={6} style={{ marginTop: 16, marginBottom: 8 }}>{t('高级配置:手动平台证书模式(可选)')}</Title>
<Text type='tertiary' style={{ display: 'block', marginBottom: 12 }}>{t('默认情况下,SDK 会自动下载微信平台证书,无需手动配置。仅在离线环境或网络受限时启用此选项。')}</Text>
<Form.Switch
field='WechatUseManualCert'
label={t('启用手动证书模式')}
extraText='开启后需要手动配置平台证书,关闭则使用自动下载模式(推荐)'
/>
<Form.Input
field='WechatPlatformCertPath'
label={t('平台证书文件路径')}
placeholder='/data/certs/wechatpay_platform_cert.pem'
extraText='平台证书文件的绝对路径(与下方 PEM 内容二选一)'
/>
<Form.TextArea
field='WechatPlatformCertPEM'
label={t('平台证书 PEM 内容')}
placeholder={
options.WechatPlatformCertPEM === '***ALREADY_SET***'
? '已设置(留空不修改,填写新内容则更新)'
: '请粘贴完整的平台证书 PEM 内容(包含 -----BEGIN CERTIFICATE----- 等)'
}
rows={6}
extraText={
options.WechatPlatformCertPEM === '***ALREADY_SET***'
? '✓ 已配置平台证书(留空则保持不变)'
: '与上方文件路径二选一,优先使用文件路径'
}
/>
<Divider margin='12px' />
<Form.Switch
field='WechatNativeEnabled'
label={t('启用 Native 扫码支付')}
extraText='用户扫描二维码完成支付'
/>
<Form.Switch
field='WechatH5Enabled'
label={t('启用 H5 支付')}
extraText='在手机浏览器中唤起微信支付'
/>
<Divider margin='12px' />
<Form.Input
field='WechatNotifyUrl'
label={t('回调通知 URL')}
placeholder={t('留空则使用默认地址')}
extraText='默认: {服务器地址}/api/wechat/notify'
/>
<Form.Input
field='WechatDescription'
label={t('商品描述')}
placeholder={t('平台充值')}
extraText='显示在微信支付界面的商品描述'
/>
<Form.InputNumber
field='WechatExpireMinutes'
label={t('订单过期时间(分钟)')}
min={1}
max={1440}
extraText='订单未支付的有效时间,默认 30 分钟'
/>
<Space style={{ marginTop: 20 }}>
<Button type='primary' htmlType='submit' loading={loading}>{t('保存配置')}</Button>
</Space>
</Form>
</>
);
};
export default SettingsPaymentWechat;
@@ -0,0 +1,454 @@
/*
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 { useState, useEffect, useContext } from 'react';
import { useTranslation } from 'react-i18next';
import {
Card,
Button,
Switch,
Typography,
Row,
Col,
Avatar,
} from '@douyinfe/semi-ui';
import { API, showSuccess, showError } from '../../../helpers';
import { StatusContext } from '../../../context/Status';
import { useUserPermissions } from '../../../hooks/common/useUserPermissions';
import { useSidebar } from '../../../hooks/common/useSidebar';
import { Settings } from 'lucide-react';
const { Text } = Typography;
export default function SettingsSidebarModulesUser() {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [statusState] = useContext(StatusContext);
// 使用后端权限验证替代前端角色判断
const {
loading: permissionsLoading,
hasSidebarSettingsPermission,
isSidebarSectionAllowed,
isSidebarModuleAllowed,
} = useUserPermissions();
// 使用useSidebar钩子获取刷新方法
const { refreshUserConfig } = useSidebar();
// 根据用户权限生成默认配置
const generateDefaultConfig = () => {
const defaultConfig = {};
// 聊天区域 - 所有用户都可以访问
if (isSidebarSectionAllowed('chat')) {
defaultConfig.chat = {
enabled: true,
playground: isSidebarModuleAllowed('chat', 'playground'),
chat: isSidebarModuleAllowed('chat', 'chat'),
};
}
// 控制台区域 - 所有用户都可以访问
if (isSidebarSectionAllowed('console')) {
defaultConfig.console = {
enabled: true,
detail: isSidebarModuleAllowed('console', 'detail'),
token: isSidebarModuleAllowed('console', 'token'),
log: isSidebarModuleAllowed('console', 'log'),
midjourney: isSidebarModuleAllowed('console', 'midjourney'),
task: isSidebarModuleAllowed('console', 'task'),
monitor: isSidebarModuleAllowed('console', 'monitor'),
};
}
// 个人中心区域 - 所有用户都可以访问
if (isSidebarSectionAllowed('personal')) {
defaultConfig.personal = {
enabled: true,
topup: isSidebarModuleAllowed('personal', 'topup'),
personal: isSidebarModuleAllowed('personal', 'personal'),
};
}
// 管理员区域 - 只有管理员可以访问
if (isSidebarSectionAllowed('admin')) {
defaultConfig.admin = {
enabled: true,
analytics: isSidebarModuleAllowed('admin', 'analytics'),
channel: isSidebarModuleAllowed('admin', 'channel'),
models: isSidebarModuleAllowed('admin', 'models'),
redemption: isSidebarModuleAllowed('admin', 'redemption'),
user: isSidebarModuleAllowed('admin', 'user'),
subscription: isSidebarModuleAllowed('admin', 'subscription'),
'admin-token': isSidebarModuleAllowed('admin', 'admin-token'),
organizations: isSidebarModuleAllowed('admin', 'organizations'),
order: isSidebarModuleAllowed('admin', 'order'),
invoice: isSidebarModuleAllowed('admin', 'invoice'),
setting: isSidebarModuleAllowed('admin', 'setting'),
};
}
return defaultConfig;
};
// 用户个人左侧边栏模块设置
const [sidebarModulesUser, setSidebarModulesUser] = useState({});
// 管理员全局配置
const [adminConfig, setAdminConfig] = useState(null);
// 处理区域级别开关变更
function handleSectionChange(sectionKey) {
return (checked) => {
const newModules = {
...sidebarModulesUser,
[sectionKey]: {
...sidebarModulesUser[sectionKey],
enabled: checked,
},
};
setSidebarModulesUser(newModules);
console.log('用户边栏区域配置变更:', sectionKey, checked, newModules);
};
}
// 处理功能级别开关变更
function handleModuleChange(sectionKey, moduleKey) {
return (checked) => {
const newModules = {
...sidebarModulesUser,
[sectionKey]: {
...sidebarModulesUser[sectionKey],
[moduleKey]: checked,
},
};
setSidebarModulesUser(newModules);
console.log(
'用户边栏功能配置变更:',
sectionKey,
moduleKey,
checked,
newModules,
);
};
}
// 重置为默认配置(基于权限过滤)
function resetSidebarModules() {
const defaultConfig = generateDefaultConfig();
setSidebarModulesUser(defaultConfig);
showSuccess(t('已重置为默认配置'));
console.log('用户边栏配置重置为默认:', defaultConfig);
}
// 保存配置
async function onSubmit() {
setLoading(true);
try {
console.log('保存用户边栏配置:', sidebarModulesUser);
const res = await API.put('/api/user/self', {
sidebar_modules: JSON.stringify(sidebarModulesUser),
});
const { success, message } = res.data;
if (success) {
showSuccess(t('保存成功'));
console.log('用户边栏配置保存成功');
// 刷新useSidebar钩子中的用户配置,实现实时更新
await refreshUserConfig();
console.log('用户边栏配置已刷新,边栏将立即更新');
} else {
showError(message);
console.error('用户边栏配置保存失败:', message);
}
} catch (error) {
showError(t('保存失败,请重试'));
console.error('用户边栏配置保存异常:', error);
} finally {
setLoading(false);
}
}
// 统一的配置加载逻辑
useEffect(() => {
const loadConfigs = async () => {
try {
// 获取管理员全局配置
if (statusState?.status?.SidebarModulesAdmin) {
const adminConf = JSON.parse(statusState.status.SidebarModulesAdmin);
setAdminConfig(adminConf);
console.log('加载管理员边栏配置:', adminConf);
}
// 获取用户个人配置
const userRes = await API.get('/api/user/self');
if (userRes.data.success && userRes.data.data.sidebar_modules) {
let userConf;
// 检查sidebar_modules是字符串还是对象
if (typeof userRes.data.data.sidebar_modules === 'string') {
userConf = JSON.parse(userRes.data.data.sidebar_modules);
} else {
userConf = userRes.data.data.sidebar_modules;
}
console.log('从API加载的用户配置:', userConf);
// 确保用户配置也经过权限过滤
const filteredUserConf = {};
Object.keys(userConf).forEach((sectionKey) => {
if (isSidebarSectionAllowed(sectionKey)) {
filteredUserConf[sectionKey] = { ...userConf[sectionKey] };
// 过滤不允许的模块
Object.keys(userConf[sectionKey]).forEach((moduleKey) => {
if (
moduleKey !== 'enabled' &&
!isSidebarModuleAllowed(sectionKey, moduleKey)
) {
delete filteredUserConf[sectionKey][moduleKey];
}
});
}
});
setSidebarModulesUser(filteredUserConf);
console.log('权限过滤后的用户配置:', filteredUserConf);
} else {
// 如果用户没有配置,使用权限过滤后的默认配置
const defaultConfig = generateDefaultConfig();
setSidebarModulesUser(defaultConfig);
console.log('用户无配置,使用默认配置:', defaultConfig);
}
} catch (error) {
console.error('加载边栏配置失败:', error);
// 出错时也使用默认配置
const defaultConfig = generateDefaultConfig();
setSidebarModulesUser(defaultConfig);
}
};
// 只有权限加载完成且有边栏设置权限时才加载配置
if (!permissionsLoading && hasSidebarSettingsPermission()) {
loadConfigs();
}
}, [
statusState,
permissionsLoading,
hasSidebarSettingsPermission,
isSidebarSectionAllowed,
isSidebarModuleAllowed,
]);
// 检查功能是否被管理员允许
const isAllowedByAdmin = (sectionKey, moduleKey = null) => {
if (!adminConfig) return true;
if (moduleKey) {
return (
adminConfig[sectionKey]?.enabled && adminConfig[sectionKey]?.[moduleKey]
);
} else {
return adminConfig[sectionKey]?.enabled;
}
};
// 区域配置数据(根据后端权限过滤)
const sectionConfigs = [
{
key: 'chat',
title: t('聊天区域'),
description: t('操练场和聊天功能'),
modules: [
{
key: 'playground',
title: t('操练场'),
description: t('AI模型测试环境'),
},
{ key: 'chat', title: t('聊天'), description: t('聊天会话管理') },
],
},
{
key: 'console',
title: t('控制台区域'),
description: t('数据管理和日志查看'),
modules: [
{ key: 'detail', title: t('数据看板'), description: t('系统数据统计') },
{ key: 'token', title: t('令牌管理'), description: t('API令牌管理') },
{ key: 'log', title: t('使用日志'), description: t('API使用记录') },
{
key: 'midjourney',
title: t('绘图日志'),
description: t('绘图任务记录'),
},
{ key: 'task', title: t('任务日志'), description: t('系统任务记录') },
],
},
{
key: 'personal',
title: t('个人中心区域'),
description: t('用户个人功能'),
modules: [
{ key: 'topup', title: t('钱包管理'), description: t('余额充值管理') },
{
key: 'personal',
title: t('个人设置'),
description: t('个人信息设置'),
},
],
},
{
key: 'admin',
title: t('管理员区域'),
description: t('系统管理功能'),
modules: [
{ key: 'channel', title: t('渠道管理'), description: t('API渠道配置') },
{ key: 'models', title: t('模型管理'), description: t('AI模型配置') },
{
key: 'redemption',
title: t('兑换码管理'),
description: t('兑换码生成管理'),
},
{ key: 'user', title: t('用户管理'), description: t('用户账户管理') },
{
key: 'setting',
title: t('系统设置'),
description: t('系统参数配置'),
},
],
},
]
.filter((section) => {
// 使用后端权限验证替代前端角色判断
return isSidebarSectionAllowed(section.key);
})
.map((section) => ({
...section,
modules: section.modules.filter((module) =>
isSidebarModuleAllowed(section.key, module.key),
),
}))
.filter(
(section) =>
// 过滤掉没有可用模块的区域
section.modules.length > 0 && isAllowedByAdmin(section.key),
);
// 渲染守卫:所有 Hook 必须在 early return 之前调用,故权限判断下移到此处。
// 权限加载中,或无边栏设置权限时,不渲染此组件。
if (permissionsLoading || !hasSidebarSettingsPermission()) {
return null;
}
return (
<Card className='!rounded-2xl shadow-sm border-0'>
{/* 卡片头部 */}
<div className='flex items-center mb-4'>
<Avatar size='small' color='purple' className='mr-3 shadow-md'>
<Settings size={16} />
</Avatar>
<div>
<Typography.Text className='text-lg font-medium'>
{t('左侧边栏个人设置')}
</Typography.Text>
<div className='text-xs text-gray-600'>
{t('个性化设置左侧边栏的显示内容')}
</div>
</div>
</div>
<div className='mb-4'>
<Text type='secondary' className='text-sm text-gray-600'>
{t('您可以个性化设置侧边栏的要显示功能')}
</Text>
</div>
{sectionConfigs.map((section) => (
<div key={section.key} className='mb-6'>
{/* 区域标题和总开关 */}
<div className='flex justify-between items-center mb-4 p-4 bg-gray-50 rounded-xl border border-gray-200'>
<div>
<div className='font-semibold text-base text-gray-900 mb-1'>
{section.title}
</div>
<Text className='text-xs text-gray-600'>
{section.description}
</Text>
</div>
<Switch
checked={sidebarModulesUser[section.key]?.enabled}
onChange={handleSectionChange(section.key)}
size='default'
/>
</div>
{/* 功能模块网格 */}
<Row gutter={[12, 12]}>
{section.modules.map((module) => (
<Col key={module.key} xs={24} sm={12} md={8} lg={6} xl={6}>
<Card
className={`!rounded-xl border border-gray-200 hover:border-blue-300 transition-all duration-200 ${
sidebarModulesUser[section.key]?.enabled ? '' : 'opacity-50'
}`}
bodyStyle={{ padding: '16px' }}
hoverable
>
<div className='flex justify-between items-center h-full'>
<div className='flex-1 text-left'>
<div className='font-semibold text-sm text-gray-900 mb-1'>
{module.title}
</div>
<Text className='text-xs text-gray-600 leading-relaxed block'>
{module.description}
</Text>
</div>
<div className='ml-4'>
<Switch
checked={sidebarModulesUser[section.key]?.[module.key]}
onChange={handleModuleChange(section.key, module.key)}
size='default'
disabled={!sidebarModulesUser[section.key]?.enabled}
/>
</div>
</div>
</Card>
</Col>
))}
</Row>
</div>
))}
{/* 底部按钮 */}
<div className='flex justify-end gap-3 mt-6 pt-4 border-t border-gray-200'>
<Button
type='tertiary'
onClick={resetSidebarModules}
className='!rounded-lg'
>
{t('重置为默认')}
</Button>
<Button
type='primary'
onClick={onSubmit}
loading={loading}
className='!rounded-lg'
>
{t('保存设置')}
</Button>
</div>
</Card>
);
}
@@ -0,0 +1,242 @@
/*
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 } from 'react';
import { Button, Col, Form, Row, Spin } from '@douyinfe/semi-ui';
import {
compareObjects,
API,
showError,
showSuccess,
showWarning,
verifyJSON,
} from '../../../helpers';
import { useTranslation } from 'react-i18next';
export default function RequestRateLimit(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [inputs, setInputs] = useState({
ModelRequestRateLimitEnabled: false,
ModelRequestRateLimitCount: -1,
ModelRequestRateLimitSuccessCount: 1000,
ModelRequestRateLimitDurationMinutes: 1,
ModelRequestRateLimitGroup: '',
});
const refForm = useRef();
const [inputsRow, setInputsRow] = useState(inputs);
function onSubmit() {
const updateArray = compareObjects(inputs, inputsRow);
if (!updateArray.length) return showWarning(t('你似乎并没有修改什么'));
const requestQueue = updateArray.map((item) => {
let value = '';
if (typeof inputs[item.key] === 'boolean') {
value = String(inputs[item.key]);
} else {
value = inputs[item.key];
}
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('部分保存失败,请重试'));
}
for (let i = 0; i < res.length; i++) {
if (!res[i].data.success) {
return showError(res[i].data.message);
}
}
showSuccess(t('保存成功'));
props.refresh();
})
.catch(() => {
showError(t('保存失败,请重试'));
})
.finally(() => {
setLoading(false);
});
}
useEffect(() => {
const currentInputs = {};
for (let key in props.options) {
if (Object.keys(inputs).includes(key)) {
currentInputs[key] = 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.Switch
field={'ModelRequestRateLimitEnabled'}
label={t('启用用户模型请求速率限制(可能会影响高并发性能)')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={(value) => {
setInputs({
...inputs,
ModelRequestRateLimitEnabled: value,
});
}}
/>
</Col>
</Row>
<Row>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
label={t('限制周期')}
step={1}
min={0}
suffix={t('分钟')}
extraText={t('频率限制的周期(分钟)')}
field={'ModelRequestRateLimitDurationMinutes'}
onChange={(value) =>
setInputs({
...inputs,
ModelRequestRateLimitDurationMinutes: String(value),
})
}
/>
</Col>
</Row>
<Row>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
label={t('用户每周期最多请求次数')}
step={1}
min={0}
max={100000000}
suffix={t('次')}
extraText={t('包括失败请求的次数,0代表不限制')}
field={'ModelRequestRateLimitCount'}
onChange={(value) =>
setInputs({
...inputs,
ModelRequestRateLimitCount: String(value),
})
}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
label={t('用户每周期最多请求完成次数')}
step={1}
min={1}
max={100000000}
suffix={t('次')}
extraText={t('只包括请求成功的次数')}
field={'ModelRequestRateLimitSuccessCount'}
onChange={(value) =>
setInputs({
...inputs,
ModelRequestRateLimitSuccessCount: String(value),
})
}
/>
</Col>
</Row>
<Row>
<Col xs={24} sm={16}>
<Form.TextArea
label={t('分组速率限制')}
placeholder={t(
'{\n "default": [200, 100],\n "vip": [0, 1000]\n}',
)}
field={'ModelRequestRateLimitGroup'}
autosize={{ minRows: 5, maxRows: 15 }}
trigger='blur'
stopValidateWithError
rules={[
{
validator: (rule, value) => verifyJSON(value),
message: t('不是合法的 JSON 字符串'),
},
]}
extraText={
<div>
<p>{t('说明:')}</p>
<ul>
<li>
{t(
'使用 JSON 对象格式,格式为:{"组名": [最多请求次数, 最多请求完成次数]}',
)}
</li>
<li>
{t(
'示例:{"default": [200, 100], "vip": [0, 1000]}。',
)}
</li>
<li>
{t(
'[最多请求次数]必须大于等于0,[最多请求完成次数]必须大于等于1。',
)}
</li>
<li>
{t(
'[最多请求次数]和[最多请求完成次数]的最大值为2147483647。',
)}
</li>
<li>{t('分组速率配置优先级高于全局速率限制。')}</li>
<li>{t('限制周期统一使用上方配置的“限制周期”值。')}</li>
</ul>
</div>
}
onChange={(value) => {
setInputs({ ...inputs, ModelRequestRateLimitGroup: value });
}}
/>
</Col>
</Row>
<Row>
<Button size='default' onClick={onSubmit}>
{t('保存模型速率限制')}
</Button>
</Row>
</Form.Section>
</Form>
</Spin>
</>
);
}
@@ -0,0 +1,287 @@
/*
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 } from 'react';
import { Banner, Button, Col, Form, Row, Spin } from '@douyinfe/semi-ui';
import {
compareObjects,
API,
showError,
showSuccess,
showWarning,
verifyJSON,
} from '../../../helpers';
import { useTranslation } from 'react-i18next';
export default function GroupRatioSettings(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [inputs, setInputs] = useState({
GroupRatio: '',
UserUsableGroups: '',
GroupGroupRatio: '',
'group_ratio_setting.group_special_usable_group': '',
AutoGroups: '',
DefaultUseAutoGroup: false,
ShowGroupRatio: false,
});
const refForm = useRef();
const [inputsRow, setInputsRow] = useState(inputs);
async function onSubmit() {
try {
await refForm.current
.validate()
.then(async () => {
const updateArray = compareObjects(inputs, inputsRow);
if (!updateArray.length)
return showWarning(t('你似乎并没有修改什么'));
// 企业等级折扣/默认企业等级已迁移至「等级与模型访问」页统一配置,此处不再处理。
setLoading(true);
try {
for (const item of updateArray) {
const rawValue = inputs[item.key];
const value =
typeof rawValue === 'boolean' ? String(rawValue) : rawValue;
const res = await API.put('/api/option/', {
key: item.key,
value,
});
if (!res?.data?.success) {
showError(res?.data?.message || t('保存失败'));
return;
}
}
showSuccess(t('保存成功'));
props.refresh();
} catch (error) {
console.error('Unexpected error:', error);
showError(t('保存失败,请重试'));
} finally {
setLoading(false);
}
})
.catch(() => {
showError(t('请检查输入'));
});
} catch (error) {
showError(t('请检查输入'));
console.error(error);
}
}
useEffect(() => {
const currentInputs = {};
for (let key in props.options) {
if (Object.keys(inputs).includes(key)) {
currentInputs[key] = 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 }}
>
<Row gutter={16}>
<Col xs={24} sm={16}>
<Form.TextArea
label={t('分组倍率')}
placeholder={t('为一个 JSON 文本,键为分组名称,值为倍率')}
extraText={t(
'分组倍率设置,可以在此处新增分组或修改现有分组的倍率,格式为 JSON 字符串,例如:{"vip": 0.5, "test": 1},表示 vip 分组的倍率为 0.5,test 分组的倍率为 1',
)}
field={'GroupRatio'}
autosize={{ minRows: 6, maxRows: 12 }}
trigger='blur'
stopValidateWithError
rules={[
{
validator: (rule, value) => verifyJSON(value),
message: t('不是合法的 JSON 字符串'),
},
]}
onChange={(value) => setInputs({ ...inputs, GroupRatio: value })}
/>
</Col>
</Row>
<Row gutter={16}>
<Col xs={24} sm={16}>
<Form.TextArea
label={t('用户可选分组')}
placeholder={t('为一个 JSON 文本,键为分组名称,值为分组描述')}
extraText={t(
'用户新建令牌时可选的分组,格式为 JSON 字符串,例如:{"vip": "VIP 用户", "test": "测试"},表示用户可以选择 vip 分组和 test 分组',
)}
field={'UserUsableGroups'}
autosize={{ minRows: 6, maxRows: 12 }}
trigger='blur'
stopValidateWithError
rules={[
{
validator: (rule, value) => verifyJSON(value),
message: t('不是合法的 JSON 字符串'),
},
]}
onChange={(value) =>
setInputs({ ...inputs, UserUsableGroups: value })
}
/>
</Col>
</Row>
<Row gutter={16}>
<Col xs={24} sm={16}>
<Form.TextArea
label={t('分组特殊倍率')}
placeholder={t('为一个 JSON 文本')}
extraText={t(
'键为分组名称,值为另一个 JSON 对象,键为分组名称,值为该分组的用户的特殊分组倍率,例如:{"vip": {"default": 0.5, "test": 1}},表示 vip 分组的用户在使用default分组的令牌时倍率为0.5,使用test分组时倍率为1',
)}
field={'GroupGroupRatio'}
autosize={{ minRows: 6, maxRows: 12 }}
trigger='blur'
stopValidateWithError
rules={[
{
validator: (rule, value) => verifyJSON(value),
message: t('不是合法的 JSON 字符串'),
},
]}
onChange={(value) =>
setInputs({ ...inputs, GroupGroupRatio: value })
}
/>
</Col>
</Row>
<Row gutter={16}>
<Col xs={24} sm={16}>
<Banner
type='info'
closeIcon={null}
description={t(
'企业等级折扣与默认企业等级已迁移至「等级与模型访问」设置页,在企业等级编辑器中与模型可见/可调用一处配齐。',
)}
style={{ marginBottom: 12 }}
/>
</Col>
</Row>
<Row gutter={16}>
<Col xs={24} sm={16}>
<Form.TextArea
label={t('分组特殊可用分组')}
placeholder={t('为一个 JSON 文本')}
extraText={t(
'键为用户分组名称,值为操作映射对象。内层键以"+:"开头表示添加指定分组(键值为分组名称,值为描述),以"-:"开头表示移除指定分组(键值为分组名称),不带前缀的键直接添加该分组。例如:{"vip": {"+:premium": "高级分组", "special": "特殊分组", "-:default": "默认分组"}},表示 vip 分组的用户可以使用 premium 和 special 分组,同时移除 default 分组的访问权限',
)}
field={'group_ratio_setting.group_special_usable_group'}
autosize={{ minRows: 6, maxRows: 12 }}
trigger='blur'
stopValidateWithError
rules={[
{
validator: (rule, value) => verifyJSON(value),
message: t('不是合法的 JSON 字符串'),
},
]}
onChange={(value) =>
setInputs({
...inputs,
'group_ratio_setting.group_special_usable_group': value,
})
}
/>
</Col>
</Row>
<Row gutter={16}>
<Col xs={24} sm={16}>
<Form.TextArea
label={t('自动分组auto,从第一个开始选择')}
placeholder={t('为一个 JSON 文本')}
field={'AutoGroups'}
autosize={{ minRows: 6, maxRows: 12 }}
trigger='blur'
stopValidateWithError
rules={[
{
validator: (rule, value) => {
if (!value || value.trim() === '') {
return true; // Allow empty values
}
// First check if it's valid JSON
try {
const parsed = JSON.parse(value);
// Check if it's an array
if (!Array.isArray(parsed)) {
return false;
}
// Check if every element is a string
return parsed.every((item) => typeof item === 'string');
} catch (error) {
return false;
}
},
message: t('必须是有效的 JSON 字符串数组,例如:["g1","g2"]'),
},
]}
onChange={(value) => setInputs({ ...inputs, AutoGroups: value })}
/>
</Col>
</Row>
<Row gutter={16}>
<Col span={16}>
<Form.Switch
label={t(
'创建令牌默认选择auto分组,初始令牌也将设为auto(否则留空,为用户默认分组)',
)}
field={'DefaultUseAutoGroup'}
onChange={(value) =>
setInputs({ ...inputs, DefaultUseAutoGroup: value })
}
/>
</Col>
</Row>
<Row gutter={16}>
<Col span={16}>
<Form.Switch
label={t('向所有用户显示分组倍率')}
extraText={t(
'开启后,用户在模型服务页面可以看到分组倍率信息。关闭后(默认),普通用户无法看到倍率,避免困惑',
)}
field={'ShowGroupRatio'}
onChange={(value) =>
setInputs({ ...inputs, ShowGroupRatio: value })
}
/>
</Col>
</Row>
</Form>
<Button onClick={onSubmit}>{t('保存分组倍率设置')}</Button>
</Spin>
);
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,323 @@
/*
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 } from 'react';
import {
Button,
Col,
Form,
Popconfirm,
Row,
Space,
Spin,
} from '@douyinfe/semi-ui';
import {
compareObjects,
API,
showError,
showSuccess,
showWarning,
verifyJSON,
} from '../../../helpers';
import { useTranslation } from 'react-i18next';
export default function ModelRatioSettings(props) {
const [loading, setLoading] = useState(false);
const [inputs, setInputs] = useState({
ModelPrice: '',
ModelRatio: '',
CacheRatio: '',
CompletionRatio: '',
ImageRatio: '',
AudioRatio: '',
AudioCompletionRatio: '',
ExposeRatioEnabled: false,
});
const refForm = useRef();
const [inputsRow, setInputsRow] = useState(inputs);
const { t } = useTranslation();
async function onSubmit() {
try {
await refForm.current
.validate()
.then(() => {
const updateArray = compareObjects(inputs, inputsRow);
if (!updateArray.length)
return showWarning(t('你似乎并没有修改什么'));
const requestQueue = updateArray.map((item) => {
const value =
typeof inputs[item.key] === 'boolean'
? String(inputs[item.key])
: inputs[item.key];
return API.put('/api/option/', { key: item.key, value });
});
setLoading(true);
Promise.all(requestQueue)
.then((res) => {
if (res.includes(undefined)) {
return showError(
requestQueue.length > 1
? t('部分保存失败,请重试')
: t('保存失败'),
);
}
for (let i = 0; i < res.length; i++) {
if (!res[i].data.success) {
return showError(res[i].data.message);
}
}
showSuccess(t('保存成功'));
props.refresh();
})
.catch((error) => {
console.error('Unexpected error:', error);
showError(t('保存失败,请重试'));
})
.finally(() => {
setLoading(false);
});
})
.catch(() => {
showError(t('请检查输入'));
});
} catch (error) {
showError(t('请检查输入'));
console.error(error);
}
}
async function resetModelRatio() {
try {
let res = await API.post(`/api/option/rest_model_ratio`);
if (res.data.success) {
showSuccess(res.data.message);
props.refresh();
} else {
showError(res.data.message);
}
} catch (error) {
showError(error);
}
}
useEffect(() => {
const currentInputs = {};
for (let key in props.options) {
if (Object.keys(inputs).includes(key)) {
currentInputs[key] = 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 }}
>
<Row gutter={16}>
<Col xs={24} sm={16}>
<Form.TextArea
label={t('模型固定价格')}
extraText={t('一次调用消耗多少刀,优先级大于模型倍率')}
placeholder={t(
'为一个 JSON 文本,键为模型名称,值为一次调用消耗多少刀,比如 "gpt-4-gizmo-*": 0.1,一次消耗0.1刀',
)}
field={'ModelPrice'}
autosize={{ minRows: 6, maxRows: 12 }}
trigger='blur'
stopValidateWithError
rules={[
{
validator: (rule, value) => verifyJSON(value),
message: '不是合法的 JSON 字符串',
},
]}
onChange={(value) => setInputs({ ...inputs, ModelPrice: value })}
/>
</Col>
</Row>
<Row gutter={16}>
<Col xs={24} sm={16}>
<Form.TextArea
label={t('模型倍率')}
placeholder={t('为一个 JSON 文本,键为模型名称,值为倍率')}
field={'ModelRatio'}
autosize={{ minRows: 6, maxRows: 12 }}
trigger='blur'
stopValidateWithError
rules={[
{
validator: (rule, value) => verifyJSON(value),
message: '不是合法的 JSON 字符串',
},
]}
onChange={(value) => setInputs({ ...inputs, ModelRatio: value })}
/>
</Col>
</Row>
<Row gutter={16}>
<Col xs={24} sm={16}>
<Form.TextArea
label={t('提示缓存倍率')}
placeholder={t('为一个 JSON 文本,键为模型名称,值为倍率')}
field={'CacheRatio'}
autosize={{ minRows: 6, maxRows: 12 }}
trigger='blur'
stopValidateWithError
rules={[
{
validator: (rule, value) => verifyJSON(value),
message: '不是合法的 JSON 字符串',
},
]}
onChange={(value) => setInputs({ ...inputs, CacheRatio: value })}
/>
</Col>
</Row>
<Row gutter={16}>
<Col xs={24} sm={16}>
<Form.TextArea
label={t('模型补全倍率(仅对自定义模型有效)')}
extraText={t('仅对自定义模型有效')}
placeholder={t('为一个 JSON 文本,键为模型名称,值为倍率')}
field={'CompletionRatio'}
autosize={{ minRows: 6, maxRows: 12 }}
trigger='blur'
stopValidateWithError
rules={[
{
validator: (rule, value) => verifyJSON(value),
message: '不是合法的 JSON 字符串',
},
]}
onChange={(value) =>
setInputs({ ...inputs, CompletionRatio: value })
}
/>
</Col>
</Row>
<Row gutter={16}>
<Col xs={24} sm={16}>
<Form.TextArea
label={t('图片输入倍率(仅部分模型支持该计费)')}
extraText={t(
'图片输入相关的倍率设置,键为模型名称,值为倍率,仅部分模型支持该计费',
)}
placeholder={t(
'为一个 JSON 文本,键为模型名称,值为倍率,例如:{"gpt-image-1": 2}',
)}
field={'ImageRatio'}
autosize={{ minRows: 6, maxRows: 12 }}
trigger='blur'
stopValidateWithError
rules={[
{
validator: (rule, value) => verifyJSON(value),
message: '不是合法的 JSON 字符串',
},
]}
onChange={(value) => setInputs({ ...inputs, ImageRatio: value })}
/>
</Col>
</Row>
<Row gutter={16}>
<Col xs={24} sm={16}>
<Form.TextArea
label={t('音频倍率(仅部分模型支持该计费)')}
extraText={t('音频输入相关的倍率设置,键为模型名称,值为倍率')}
placeholder={t(
'为一个 JSON 文本,键为模型名称,值为倍率,例如:{"gpt-4o-audio-preview": 16}',
)}
field={'AudioRatio'}
autosize={{ minRows: 6, maxRows: 12 }}
trigger='blur'
stopValidateWithError
rules={[
{
validator: (rule, value) => verifyJSON(value),
message: '不是合法的 JSON 字符串',
},
]}
onChange={(value) => setInputs({ ...inputs, AudioRatio: value })}
/>
</Col>
</Row>
<Row gutter={16}>
<Col xs={24} sm={16}>
<Form.TextArea
label={t('音频补全倍率(仅部分模型支持该计费)')}
extraText={t(
'音频输出补全相关的倍率设置,键为模型名称,值为倍率',
)}
placeholder={t(
'为一个 JSON 文本,键为模型名称,值为倍率,例如:{"gpt-4o-realtime": 2}',
)}
field={'AudioCompletionRatio'}
autosize={{ minRows: 6, maxRows: 12 }}
trigger='blur'
stopValidateWithError
rules={[
{
validator: (rule, value) => verifyJSON(value),
message: '不是合法的 JSON 字符串',
},
]}
onChange={(value) =>
setInputs({ ...inputs, AudioCompletionRatio: value })
}
/>
</Col>
</Row>
<Row gutter={16}>
<Col span={16}>
<Form.Switch
label={t('暴露倍率接口')}
field={'ExposeRatioEnabled'}
onChange={(value) =>
setInputs({ ...inputs, ExposeRatioEnabled: value })
}
/>
</Col>
</Row>
</Form>
<Space>
<Button onClick={onSubmit}>{t('保存模型倍率设置')}</Button>
<Popconfirm
title={t('确定重置模型倍率吗?')}
content={t('此修改将不可逆')}
okType={'danger'}
position={'top'}
onConfirm={resetModelRatio}
>
<Button type={'danger'}>{t('重置模型倍率')}</Button>
</Popconfirm>
</Space>
</Spin>
);
}
@@ -0,0 +1,617 @@
/*
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 } from 'react';
import {
Table,
Button,
Input,
Modal,
Form,
Space,
Typography,
Radio,
Notification,
} from '@douyinfe/semi-ui';
import {
IconPlus,
IconSearch,
IconSave,
IconBolt,
} from '@douyinfe/semi-icons';
import { API, showError, showSuccess } from '../../../helpers';
import { useTranslation } from 'react-i18next';
export default function ModelRatioNotSetEditor(props) {
const { t } = useTranslation();
const [models, setModels] = useState([]);
const [visible, setVisible] = useState(false);
const [batchVisible, setBatchVisible] = useState(false);
const [currentModel, setCurrentModel] = useState(null);
const [searchText, setSearchText] = useState('');
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const [loading, setLoading] = useState(false);
const [enabledModels, setEnabledModels] = useState([]);
const [selectedRowKeys, setSelectedRowKeys] = useState([]);
const [batchFillType, setBatchFillType] = useState('ratio');
const [batchFillValue, setBatchFillValue] = useState('');
const [batchRatioValue, setBatchRatioValue] = useState('');
const [batchCompletionRatioValue, setBatchCompletionRatioValue] =
useState('');
const { Text } = Typography;
// 定义可选的每页显示条数
const pageSizeOptions = [10, 20, 50, 100];
const getAllEnabledModels = async () => {
try {
const res = await API.get('/api/channel/models_enabled');
const { success, message, data } = res.data;
if (success) {
setEnabledModels(data);
} else {
showError(message);
}
} catch (error) {
console.error(t('获取启用模型失败:'), error);
showError(t('获取启用模型失败'));
}
};
useEffect(() => {
// 获取所有启用的模型
getAllEnabledModels();
}, []);
useEffect(() => {
try {
const modelPrice = JSON.parse(props.options.ModelPrice || '{}');
const modelRatio = JSON.parse(props.options.ModelRatio || '{}');
const completionRatio = JSON.parse(props.options.CompletionRatio || '{}');
// 找出所有未设置价格和倍率的模型
const unsetModels = enabledModels.filter((modelName) => {
const hasPrice = modelPrice[modelName] !== undefined;
const hasRatio = modelRatio[modelName] !== undefined;
// 如果模型没有价格或者没有倍率设置,则显示
return !hasPrice && !hasRatio;
});
// 创建模型数据
const modelData = unsetModels.map((name) => ({
name,
price: modelPrice[name] || '',
ratio: modelRatio[name] || '',
completionRatio: completionRatio[name] || '',
}));
setModels(modelData);
// 清空选择
setSelectedRowKeys([]);
} catch (error) {
console.error(t('JSON解析错误:'), error);
}
}, [props.options, enabledModels]);
// 首先声明分页相关的工具函数
const getPagedData = (data, currentPage, pageSize) => {
const start = (currentPage - 1) * pageSize;
const end = start + pageSize;
return data.slice(start, end);
};
// 处理页面大小变化
const handlePageSizeChange = (size) => {
setPageSize(size);
// 重新计算当前页,避免数据丢失
const totalPages = Math.ceil(filteredModels.length / size);
if (currentPage > totalPages) {
setCurrentPage(totalPages || 1);
}
};
// 在 return 语句之前,先处理过滤和分页逻辑
const filteredModels = models.filter((model) =>
searchText ? model.name.includes(searchText) : true,
);
// 然后基于过滤后的数据计算分页数据
const pagedData = getPagedData(filteredModels, currentPage, pageSize);
const SubmitData = async () => {
setLoading(true);
const output = {
ModelPrice: JSON.parse(props.options.ModelPrice || '{}'),
ModelRatio: JSON.parse(props.options.ModelRatio || '{}'),
CompletionRatio: JSON.parse(props.options.CompletionRatio || '{}'),
};
try {
// 数据转换 - 只处理已修改的模型
models.forEach((model) => {
// 只有当用户设置了值时才更新
if (model.price !== '') {
// 如果价格不为空,则转换为浮点数,忽略倍率参数
output.ModelPrice[model.name] = parseFloat(model.price);
} else {
if (model.ratio !== '')
output.ModelRatio[model.name] = parseFloat(model.ratio);
if (model.completionRatio !== '')
output.CompletionRatio[model.name] = parseFloat(
model.completionRatio,
);
}
});
// 准备API请求数组
const finalOutput = {
ModelPrice: JSON.stringify(output.ModelPrice, null, 2),
ModelRatio: JSON.stringify(output.ModelRatio, null, 2),
CompletionRatio: JSON.stringify(output.CompletionRatio, null, 2),
};
const requestQueue = Object.entries(finalOutput).map(([key, value]) => {
return API.put('/api/option/', {
key,
value,
});
});
// 批量处理请求
const results = await Promise.all(requestQueue);
// 验证结果
if (requestQueue.length === 1) {
if (results.includes(undefined)) return;
} else if (requestQueue.length > 1) {
if (results.includes(undefined)) {
return showError(t('部分保存失败,请重试'));
}
}
// 检查每个请求的结果
for (const res of results) {
if (!res.data.success) {
return showError(res.data.message);
}
}
showSuccess(t('保存成功'));
props.refresh();
// 重新获取未设置的模型
getAllEnabledModels();
} catch (error) {
console.error(t('保存失败:'), error);
showError(t('保存失败,请重试'));
} finally {
setLoading(false);
}
};
const columns = [
{
title: t('模型名称'),
dataIndex: 'name',
key: 'name',
},
{
title: t('模型固定价格'),
dataIndex: 'price',
key: 'price',
render: (text, record) => (
<Input
value={text}
placeholder={t('按量计费')}
onChange={(value) => updateModel(record.name, 'price', value)}
/>
),
},
{
title: t('模型倍率'),
dataIndex: 'ratio',
key: 'ratio',
render: (text, record) => (
<Input
value={text}
placeholder={record.price !== '' ? t('模型倍率') : t('输入模型倍率')}
disabled={record.price !== ''}
onChange={(value) => updateModel(record.name, 'ratio', value)}
/>
),
},
{
title: t('补全倍率'),
dataIndex: 'completionRatio',
key: 'completionRatio',
render: (text, record) => (
<Input
value={text}
placeholder={record.price !== '' ? t('补全倍率') : t('输入补全倍率')}
disabled={record.price !== ''}
onChange={(value) =>
updateModel(record.name, 'completionRatio', value)
}
/>
),
},
];
const updateModel = (name, field, value) => {
if (value !== '' && isNaN(value)) {
showError(t('请输入数字'));
return;
}
setModels((prev) =>
prev.map((model) =>
model.name === name ? { ...model, [field]: value } : model,
),
);
};
const addModel = (values) => {
// 检查模型名称是否存在, 如果存在则拒绝添加
if (models.some((model) => model.name === values.name)) {
showError(t('模型名称已存在'));
return;
}
setModels((prev) => [
{
name: values.name,
price: values.price || '',
ratio: values.ratio || '',
completionRatio: values.completionRatio || '',
},
...prev,
]);
setVisible(false);
showSuccess(t('添加成功'));
};
// 批量填充功能
const handleBatchFill = () => {
if (selectedRowKeys.length === 0) {
showError(t('请先选择需要批量设置的模型'));
return;
}
if (batchFillType === 'bothRatio') {
if (batchRatioValue === '' || batchCompletionRatioValue === '') {
showError(t('请输入模型倍率和补全倍率'));
return;
}
if (isNaN(batchRatioValue) || isNaN(batchCompletionRatioValue)) {
showError(t('请输入有效的数字'));
return;
}
} else {
if (batchFillValue === '') {
showError(t('请输入填充值'));
return;
}
if (isNaN(batchFillValue)) {
showError(t('请输入有效的数字'));
return;
}
}
// 根据选择的类型批量更新模型
setModels((prev) =>
prev.map((model) => {
if (selectedRowKeys.includes(model.name)) {
if (batchFillType === 'price') {
return {
...model,
price: batchFillValue,
ratio: '',
completionRatio: '',
};
} else if (batchFillType === 'ratio') {
return {
...model,
price: '',
ratio: batchFillValue,
};
} else if (batchFillType === 'completionRatio') {
return {
...model,
price: '',
completionRatio: batchFillValue,
};
} else if (batchFillType === 'bothRatio') {
return {
...model,
price: '',
ratio: batchRatioValue,
completionRatio: batchCompletionRatioValue,
};
}
}
return model;
}),
);
setBatchVisible(false);
Notification.success({
title: t('批量设置成功'),
content: t('已为 {{count}} 个模型设置{{type}}', {
count: selectedRowKeys.length,
type:
batchFillType === 'price'
? t('固定价格')
: batchFillType === 'ratio'
? t('模型倍率')
: batchFillType === 'completionRatio'
? t('补全倍率')
: t('模型倍率和补全倍率'),
}),
duration: 3,
});
};
const handleBatchTypeChange = (value) => {
console.log(t('Changing batch type to:'), value);
setBatchFillType(value);
// 切换类型时清空对应的值
if (value !== 'bothRatio') {
setBatchFillValue('');
} else {
setBatchRatioValue('');
setBatchCompletionRatioValue('');
}
};
const rowSelection = {
selectedRowKeys,
onChange: (selectedKeys) => {
setSelectedRowKeys(selectedKeys);
},
};
return (
<>
<Space vertical align='start' style={{ width: '100%' }}>
<Space className='mt-2'>
<Button icon={<IconPlus />} onClick={() => setVisible(true)}>
{t('添加模型')}
</Button>
<Button
icon={<IconBolt />}
type='secondary'
onClick={() => setBatchVisible(true)}
disabled={selectedRowKeys.length === 0}
>
{t('批量设置')} ({selectedRowKeys.length})
</Button>
<Button
type='primary'
icon={<IconSave />}
onClick={SubmitData}
loading={loading}
>
{t('应用更改')}
</Button>
<Input
prefix={<IconSearch />}
placeholder={t('搜索模型名称')}
value={searchText}
onChange={(value) => {
setSearchText(value);
setCurrentPage(1);
}}
style={{ width: 200 }}
/>
</Space>
<Text>
{t('此页面仅显示未设置价格或倍率的模型,设置后将自动从列表中移除')}
</Text>
<Table
columns={columns}
dataSource={pagedData}
rowSelection={rowSelection}
rowKey='name'
pagination={{
currentPage: currentPage,
pageSize: pageSize,
total: filteredModels.length,
onPageChange: (page) => setCurrentPage(page),
onPageSizeChange: handlePageSizeChange,
pageSizeOptions: pageSizeOptions,
showTotal: true,
showSizeChanger: true,
}}
empty={
<div style={{ textAlign: 'center', padding: '20px' }}>
{t('没有未设置的模型')}
</div>
}
/>
</Space>
{/* 添加模型弹窗 */}
<Modal
title={t('添加模型')}
visible={visible}
onCancel={() => setVisible(false)}
onOk={() => {
currentModel && addModel(currentModel);
}}
>
<Form>
<Form.Input
field='name'
label={t('模型名称')}
placeholder='strawberry'
required
onChange={(value) =>
setCurrentModel((prev) => ({ ...prev, name: value }))
}
/>
<Form.Switch
field='priceMode'
label={
<>
{t('定价模式')}:
{currentModel?.priceMode ? t('固定价格') : t('倍率模式')}
</>
}
onChange={(checked) => {
setCurrentModel((prev) => ({
...prev,
price: '',
ratio: '',
completionRatio: '',
priceMode: checked,
}));
}}
/>
{currentModel?.priceMode ? (
<Form.Input
field='price'
label={t('固定价格(每次)')}
placeholder={t('输入每次价格')}
onChange={(value) =>
setCurrentModel((prev) => ({ ...prev, price: value }))
}
/>
) : (
<>
<Form.Input
field='ratio'
label={t('模型倍率')}
placeholder={t('输入模型倍率')}
onChange={(value) =>
setCurrentModel((prev) => ({ ...prev, ratio: value }))
}
/>
<Form.Input
field='completionRatio'
label={t('补全倍率')}
placeholder={t('输入补全价格')}
onChange={(value) =>
setCurrentModel((prev) => ({
...prev,
completionRatio: value,
}))
}
/>
</>
)}
</Form>
</Modal>
{/* 批量设置弹窗 */}
<Modal
title={t('批量设置模型参数')}
visible={batchVisible}
onCancel={() => setBatchVisible(false)}
onOk={handleBatchFill}
width={500}
>
<Form>
<Form.Section text={t('设置类型')}>
<div style={{ marginBottom: '16px' }}>
<Space>
<Radio
checked={batchFillType === 'price'}
onChange={() => handleBatchTypeChange('price')}
>
{t('固定价格')}
</Radio>
<Radio
checked={batchFillType === 'ratio'}
onChange={() => handleBatchTypeChange('ratio')}
>
{t('模型倍率')}
</Radio>
<Radio
checked={batchFillType === 'completionRatio'}
onChange={() => handleBatchTypeChange('completionRatio')}
>
{t('补全倍率')}
</Radio>
<Radio
checked={batchFillType === 'bothRatio'}
onChange={() => handleBatchTypeChange('bothRatio')}
>
{t('模型倍率和补全倍率同时设置')}
</Radio>
</Space>
</div>
</Form.Section>
{batchFillType === 'bothRatio' ? (
<>
<Form.Input
field='batchRatioValue'
label={t('模型倍率值')}
placeholder={t('请输入模型倍率')}
value={batchRatioValue}
onChange={(value) => setBatchRatioValue(value)}
/>
<Form.Input
field='batchCompletionRatioValue'
label={t('补全倍率值')}
placeholder={t('请输入补全倍率')}
value={batchCompletionRatioValue}
onChange={(value) => setBatchCompletionRatioValue(value)}
/>
</>
) : (
<Form.Input
field='batchFillValue'
label={
batchFillType === 'price'
? t('固定价格值')
: batchFillType === 'ratio'
? t('模型倍率值')
: t('补全倍率值')
}
placeholder={t('请输入数值')}
value={batchFillValue}
onChange={(value) => setBatchFillValue(value)}
/>
)}
<Text type='tertiary'>
{t('将为选中的 ')} <Text strong>{selectedRowKeys.length}</Text>{' '}
{t(' 个模型设置相同的值')}
</Text>
<div style={{ marginTop: '8px' }}>
<Text type='tertiary'>
{t('当前设置类型: ')}{' '}
<Text strong>
{batchFillType === 'price'
? t('固定价格')
: batchFillType === 'ratio'
? t('模型倍率')
: batchFillType === 'completionRatio'
? t('补全倍率')
: t('模型倍率和补全倍率')}
</Text>
</Text>
</div>
</Form>
</Modal>
</>
);
}
@@ -0,0 +1,756 @@
/*
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 } from 'react';
import {
Table,
Button,
Input,
Modal,
Form,
Space,
RadioGroup,
Radio,
Checkbox,
Tag,
} from '@douyinfe/semi-ui';
import {
IconDelete,
IconPlus,
IconSearch,
IconSave,
IconEdit,
} from '@douyinfe/semi-icons';
import { API, showError, showSuccess, getQuotaPerUnit } from '../../../helpers';
import { useTranslation } from 'react-i18next';
export default function ModelSettingsVisualEditor(props) {
const { t } = useTranslation();
const [models, setModels] = useState([]);
const [visible, setVisible] = useState(false);
const [isEditMode, setIsEditMode] = useState(false);
const [currentModel, setCurrentModel] = useState(null);
const [searchText, setSearchText] = useState('');
const [currentPage, setCurrentPage] = useState(1);
const [, setLoading] = useState(false);
const [pricingMode, setPricingMode] = useState('per-token'); // 'per-token' or 'per-request'
const [pricingSubMode, setPricingSubMode] = useState('ratio'); // 'ratio' or 'token-price'
const [conflictOnly, setConflictOnly] = useState(false);
const formRef = useRef(null);
const pageSize = 10;
const _quotaPerUnit = getQuotaPerUnit();
useEffect(() => {
try {
const modelPrice = JSON.parse(props.options.ModelPrice || '{}');
const modelRatio = JSON.parse(props.options.ModelRatio || '{}');
const completionRatio = JSON.parse(props.options.CompletionRatio || '{}');
// 合并所有模型名称
const modelNames = new Set([
...Object.keys(modelPrice),
...Object.keys(modelRatio),
...Object.keys(completionRatio),
]);
const modelData = Array.from(modelNames).map((name) => {
const price = modelPrice[name] === undefined ? '' : modelPrice[name];
const ratio = modelRatio[name] === undefined ? '' : modelRatio[name];
const comp =
completionRatio[name] === undefined ? '' : completionRatio[name];
return {
name,
price,
ratio,
completionRatio: comp,
hasConflict: price !== '' && (ratio !== '' || comp !== ''),
};
});
setModels(modelData);
} catch (error) {
console.error('JSON解析错误:', error);
}
}, [props.options]);
// 首先声明分页相关的工具函数
const getPagedData = (data, currentPage, pageSize) => {
const start = (currentPage - 1) * pageSize;
const end = start + pageSize;
return data.slice(start, end);
};
// 在 return 语句之前,先处理过滤和分页逻辑
const filteredModels = models.filter((model) => {
const keywordMatch = searchText ? model.name.includes(searchText) : true;
const conflictMatch = conflictOnly ? model.hasConflict : true;
return keywordMatch && conflictMatch;
});
// 然后基于过滤后的数据计算分页数据
const pagedData = getPagedData(filteredModels, currentPage, pageSize);
const SubmitData = async () => {
setLoading(true);
const output = {
ModelPrice: {},
ModelRatio: {},
CompletionRatio: {},
};
let _currentConvertModelName = '';
try {
// 数据转换
models.forEach((model) => {
_currentConvertModelName = model.name;
if (model.price !== '') {
// 如果价格不为空,则转换为浮点数,忽略倍率参数
output.ModelPrice[model.name] = parseFloat(model.price);
} else {
if (model.ratio !== '')
output.ModelRatio[model.name] = parseFloat(model.ratio);
if (model.completionRatio !== '')
output.CompletionRatio[model.name] = parseFloat(
model.completionRatio,
);
}
});
// 准备API请求数组
const finalOutput = {
ModelPrice: JSON.stringify(output.ModelPrice, null, 2),
ModelRatio: JSON.stringify(output.ModelRatio, null, 2),
CompletionRatio: JSON.stringify(output.CompletionRatio, null, 2),
};
const requestQueue = Object.entries(finalOutput).map(([key, value]) => {
return API.put('/api/option/', {
key,
value,
});
});
// 批量处理请求
const results = await Promise.all(requestQueue);
// 验证结果
if (requestQueue.length === 1) {
if (results.includes(undefined)) return;
} else if (requestQueue.length > 1) {
if (results.includes(undefined)) {
return showError(t('部分保存失败,请重试'));
}
}
// 检查每个请求的结果
for (const res of results) {
if (!res.data.success) {
return showError(res.data.message);
}
}
showSuccess(t('保存成功'));
props.refresh();
} catch (error) {
console.error('保存失败:', error);
showError(t('保存失败,请重试'));
} finally {
setLoading(false);
}
};
const columns = [
{
title: t('模型名称'),
dataIndex: 'name',
key: 'name',
render: (text, record) => (
<span>
{text}
{record.hasConflict && (
<Tag color='red' shape='circle' className='ml-2'>
{t('矛盾')}
</Tag>
)}
</span>
),
},
{
title: t('模型固定价格'),
dataIndex: 'price',
key: 'price',
render: (text, record) => (
<Input
value={text}
placeholder={t('按量计费')}
onChange={(value) => updateModel(record.name, 'price', value)}
/>
),
},
{
title: t('模型倍率'),
dataIndex: 'ratio',
key: 'ratio',
render: (text, record) => (
<Input
value={text}
placeholder={record.price !== '' ? t('模型倍率') : t('默认补全倍率')}
disabled={record.price !== ''}
onChange={(value) => updateModel(record.name, 'ratio', value)}
/>
),
},
{
title: t('补全倍率'),
dataIndex: 'completionRatio',
key: 'completionRatio',
render: (text, record) => (
<Input
value={text}
placeholder={record.price !== '' ? t('补全倍率') : t('默认补全倍率')}
disabled={record.price !== ''}
onChange={(value) =>
updateModel(record.name, 'completionRatio', value)
}
/>
),
},
{
title: t('操作'),
key: 'action',
render: (_, record) => (
<Space>
<Button
type='primary'
icon={<IconEdit />}
onClick={() => editModel(record)}
></Button>
<Button
icon={<IconDelete />}
type='danger'
onClick={() => deleteModel(record.name)}
/>
</Space>
),
},
];
const updateModel = (name, field, value) => {
if (isNaN(value)) {
showError(t('请输入数字'));
return;
}
setModels((prev) =>
prev.map((model) => {
if (model.name !== name) return model;
const updated = { ...model, [field]: value };
updated.hasConflict =
updated.price !== '' &&
(updated.ratio !== '' || updated.completionRatio !== '');
return updated;
}),
);
};
const deleteModel = (name) => {
setModels((prev) => prev.filter((model) => model.name !== name));
};
const calculateRatioFromTokenPrice = (tokenPrice) => {
return tokenPrice / 2;
};
const calculateCompletionRatioFromPrices = (
modelTokenPrice,
completionTokenPrice,
) => {
if (!modelTokenPrice || modelTokenPrice === '0') {
showError(t('模型价格不能为0'));
return '';
}
return completionTokenPrice / modelTokenPrice;
};
const handleTokenPriceChange = (value) => {
// Use a temporary variable to hold the new state
let newState = {
...(currentModel || {}),
tokenPrice: value,
ratio: 0,
};
if (!isNaN(value) && value !== '') {
const tokenPrice = parseFloat(value);
const ratio = calculateRatioFromTokenPrice(tokenPrice);
newState.ratio = ratio;
}
// Set the state with the complete updated object
setCurrentModel(newState);
};
const handleCompletionTokenPriceChange = (value) => {
// Use a temporary variable to hold the new state
let newState = {
...(currentModel || {}),
completionTokenPrice: value,
completionRatio: 0,
};
if (!isNaN(value) && value !== '' && currentModel?.tokenPrice) {
const completionTokenPrice = parseFloat(value);
const modelTokenPrice = parseFloat(currentModel.tokenPrice);
if (modelTokenPrice > 0) {
const completionRatio = calculateCompletionRatioFromPrices(
modelTokenPrice,
completionTokenPrice,
);
newState.completionRatio = completionRatio;
}
}
// Set the state with the complete updated object
setCurrentModel(newState);
};
const addOrUpdateModel = (values) => {
// Check if we're editing an existing model or adding a new one
const existingModelIndex = models.findIndex(
(model) => model.name === values.name,
);
if (existingModelIndex >= 0) {
// Update existing model
setModels((prev) =>
prev.map((model, index) => {
if (index !== existingModelIndex) return model;
const updated = {
name: values.name,
price: values.price || '',
ratio: values.ratio || '',
completionRatio: values.completionRatio || '',
};
updated.hasConflict =
updated.price !== '' &&
(updated.ratio !== '' || updated.completionRatio !== '');
return updated;
}),
);
setVisible(false);
showSuccess(t('更新成功'));
} else {
// Add new model
// Check if model name already exists
if (models.some((model) => model.name === values.name)) {
showError(t('模型名称已存在'));
return;
}
setModels((prev) => {
const newModel = {
name: values.name,
price: values.price || '',
ratio: values.ratio || '',
completionRatio: values.completionRatio || '',
};
newModel.hasConflict =
newModel.price !== '' &&
(newModel.ratio !== '' || newModel.completionRatio !== '');
return [newModel, ...prev];
});
setVisible(false);
showSuccess(t('添加成功'));
}
};
const calculateTokenPriceFromRatio = (ratio) => {
return ratio * 2;
};
const resetModalState = () => {
setCurrentModel(null);
setPricingMode('per-token');
setPricingSubMode('ratio');
setIsEditMode(false);
};
const editModel = (record) => {
setIsEditMode(true);
// Determine which pricing mode to use based on the model's current configuration
let initialPricingMode = 'per-token';
let initialPricingSubMode = 'ratio';
if (record.price !== '') {
initialPricingMode = 'per-request';
} else {
initialPricingMode = 'per-token';
// We default to ratio mode, but could set to token-price if needed
}
// Set the pricing modes for the form
setPricingMode(initialPricingMode);
setPricingSubMode(initialPricingSubMode);
// Create a copy of the model data to avoid modifying the original
const modelCopy = { ...record };
// If the model has ratio data and we want to populate token price fields
if (record.ratio) {
modelCopy.tokenPrice = calculateTokenPriceFromRatio(
parseFloat(record.ratio),
).toString();
if (record.completionRatio) {
modelCopy.completionTokenPrice = (
parseFloat(modelCopy.tokenPrice) * parseFloat(record.completionRatio)
).toString();
}
}
// Set the current model
setCurrentModel(modelCopy);
// Open the modal
setVisible(true);
// Use setTimeout to ensure the form is rendered before setting values
setTimeout(() => {
if (formRef.current) {
// Update the form fields based on pricing mode
const formValues = {
name: modelCopy.name,
};
if (initialPricingMode === 'per-request') {
formValues.priceInput = modelCopy.price;
} else if (initialPricingMode === 'per-token') {
formValues.ratioInput = modelCopy.ratio;
formValues.completionRatioInput = modelCopy.completionRatio;
formValues.modelTokenPrice = modelCopy.tokenPrice;
formValues.completionTokenPrice = modelCopy.completionTokenPrice;
}
formRef.current.setValues(formValues);
}
}, 0);
};
return (
<>
<Space vertical align='start' style={{ width: '100%' }}>
<Space className='mt-2'>
<Button
icon={<IconPlus />}
onClick={() => {
resetModalState();
setVisible(true);
}}
>
{t('添加模型')}
</Button>
<Button type='primary' icon={<IconSave />} onClick={SubmitData}>
{t('应用更改')}
</Button>
<Input
prefix={<IconSearch />}
placeholder={t('搜索模型名称')}
value={searchText}
onChange={(value) => {
setSearchText(value);
setCurrentPage(1);
}}
style={{ width: 200 }}
showClear
/>
<Checkbox
checked={conflictOnly}
onChange={(e) => {
setConflictOnly(e.target.checked);
setCurrentPage(1);
}}
>
{t('仅显示矛盾倍率')}
</Checkbox>
</Space>
<Table
columns={columns}
dataSource={pagedData}
pagination={{
currentPage: currentPage,
pageSize: pageSize,
total: filteredModels.length,
onPageChange: (page) => setCurrentPage(page),
showTotal: true,
showSizeChanger: false,
}}
/>
</Space>
<Modal
title={isEditMode ? t('编辑模型') : t('添加模型')}
visible={visible}
onCancel={() => {
resetModalState();
setVisible(false);
}}
onOk={() => {
if (currentModel) {
// If we're in token price mode, make sure ratio values are properly set
const valuesToSave = { ...currentModel };
if (
pricingMode === 'per-token' &&
pricingSubMode === 'token-price' &&
currentModel.tokenPrice
) {
// Calculate and set ratio from token price
const tokenPrice = parseFloat(currentModel.tokenPrice);
valuesToSave.ratio = (tokenPrice / 2).toString();
// Calculate and set completion ratio if both token prices are available
if (
currentModel.completionTokenPrice &&
currentModel.tokenPrice
) {
const completionPrice = parseFloat(
currentModel.completionTokenPrice,
);
const modelPrice = parseFloat(currentModel.tokenPrice);
if (modelPrice > 0) {
valuesToSave.completionRatio = (
completionPrice / modelPrice
).toString();
}
}
}
// Clear price if we're in per-token mode
if (pricingMode === 'per-token') {
valuesToSave.price = '';
} else {
// Clear ratios if we're in per-request mode
valuesToSave.ratio = '';
valuesToSave.completionRatio = '';
}
addOrUpdateModel(valuesToSave);
}
}}
>
<Form getFormApi={(api) => (formRef.current = api)}>
<Form.Input
field='name'
label={t('模型名称')}
placeholder='strawberry'
required
disabled={isEditMode}
onChange={(value) =>
setCurrentModel((prev) => ({ ...prev, name: value }))
}
/>
<Form.Section text={t('定价模式')}>
<div style={{ marginBottom: '16px' }}>
<RadioGroup
type='button'
value={pricingMode}
onChange={(e) => {
const newMode = e.target.value;
setPricingMode(newMode);
// Instead of resetting all values, convert between modes
if (currentModel) {
const updatedModel = { ...currentModel };
// Update formRef with converted values
if (formRef.current) {
const formValues = {
name: updatedModel.name,
};
if (newMode === 'per-request') {
formValues.priceInput = updatedModel.price || '';
} else if (newMode === 'per-token') {
formValues.ratioInput = updatedModel.ratio || '';
formValues.completionRatioInput =
updatedModel.completionRatio || '';
formValues.modelTokenPrice =
updatedModel.tokenPrice || '';
formValues.completionTokenPrice =
updatedModel.completionTokenPrice || '';
}
formRef.current.setValues(formValues);
}
// Update the model state
setCurrentModel(updatedModel);
}
}}
>
<Radio value='per-token'>{t('按量计费')}</Radio>
<Radio value='per-request'>{t('按次计费')}</Radio>
</RadioGroup>
</div>
</Form.Section>
{pricingMode === 'per-token' && (
<>
<Form.Section text={t('价格设置方式')}>
<div style={{ marginBottom: '16px' }}>
<RadioGroup
type='button'
value={pricingSubMode}
onChange={(e) => {
const newSubMode = e.target.value;
const oldSubMode = pricingSubMode;
setPricingSubMode(newSubMode);
// Handle conversion between submodes
if (currentModel) {
const updatedModel = { ...currentModel };
// Convert between ratio and token price
if (
oldSubMode === 'ratio' &&
newSubMode === 'token-price'
) {
if (updatedModel.ratio) {
updatedModel.tokenPrice =
calculateTokenPriceFromRatio(
parseFloat(updatedModel.ratio),
).toString();
if (updatedModel.completionRatio) {
updatedModel.completionTokenPrice = (
parseFloat(updatedModel.tokenPrice) *
parseFloat(updatedModel.completionRatio)
).toString();
}
}
} else if (
oldSubMode === 'token-price' &&
newSubMode === 'ratio'
) {
// Ratio values should already be calculated by the handlers
}
// Update the form values
if (formRef.current) {
const formValues = {};
if (newSubMode === 'ratio') {
formValues.ratioInput = updatedModel.ratio || '';
formValues.completionRatioInput =
updatedModel.completionRatio || '';
} else if (newSubMode === 'token-price') {
formValues.modelTokenPrice =
updatedModel.tokenPrice || '';
formValues.completionTokenPrice =
updatedModel.completionTokenPrice || '';
}
formRef.current.setValues(formValues);
}
setCurrentModel(updatedModel);
}
}}
>
<Radio value='ratio'>{t('按倍率设置')}</Radio>
<Radio value='token-price'>{t('按价格设置')}</Radio>
</RadioGroup>
</div>
</Form.Section>
{pricingSubMode === 'ratio' && (
<>
<Form.Input
field='ratioInput'
label={t('模型倍率')}
placeholder={t('输入模型倍率')}
onChange={(value) =>
setCurrentModel((prev) => ({
...(prev || {}),
ratio: value,
}))
}
initValue={currentModel?.ratio || ''}
/>
<Form.Input
field='completionRatioInput'
label={t('补全倍率')}
placeholder={t('输入补全倍率')}
onChange={(value) =>
setCurrentModel((prev) => ({
...(prev || {}),
completionRatio: value,
}))
}
initValue={currentModel?.completionRatio || ''}
/>
</>
)}
{pricingSubMode === 'token-price' && (
<>
<Form.Input
field='modelTokenPrice'
label={t('输入价格')}
onChange={(value) => {
handleTokenPriceChange(value);
}}
initValue={currentModel?.tokenPrice || ''}
suffix={t('¥/1M tokens')}
/>
<Form.Input
field='completionTokenPrice'
label={t('输出价格')}
onChange={(value) => {
handleCompletionTokenPriceChange(value);
}}
initValue={currentModel?.completionTokenPrice || ''}
suffix={t('¥/1M tokens')}
/>
</>
)}
</>
)}
{pricingMode === 'per-request' && (
<Form.Input
field='priceInput'
label={t('固定价格(每次)')}
placeholder={t('输入每次价格')}
onChange={(value) =>
setCurrentModel((prev) => ({
...(prev || {}),
price: value,
}))
}
initValue={currentModel?.price || ''}
/>
)}
</Form>
</Modal>
</>
);
}
@@ -0,0 +1,871 @@
/*
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, { useState, useCallback, useMemo, useEffect } from 'react';
import {
Button,
Table,
Tag,
Empty,
Checkbox,
Form,
Input,
Tooltip,
Select,
Modal,
} from '@douyinfe/semi-ui';
import { IconSearch } from '@douyinfe/semi-icons';
import {
RefreshCcw,
CheckSquare,
AlertTriangle,
CheckCircle,
} from 'lucide-react';
import {
API,
showError,
showSuccess,
showWarning,
stringToColor,
} from '../../../helpers';
import { useIsMobile } from '../../../hooks/common/useIsMobile';
import { DEFAULT_ENDPOINT } from '../../../constants';
import { useTranslation } from 'react-i18next';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../../components/common/illustrations';
import ChannelSelectorModal from '../../../components/settings/ChannelSelectorModal';
function ConflictConfirmModal({ t, visible, items, onOk, onCancel }) {
const isMobile = useIsMobile();
const columns = [
{ title: t('渠道'), dataIndex: 'channel' },
{ title: t('模型'), dataIndex: 'model' },
{
title: t('当前计费'),
dataIndex: 'current',
render: (text) => <div style={{ whiteSpace: 'pre-wrap' }}>{text}</div>,
},
{
title: t('修改为'),
dataIndex: 'newVal',
render: (text) => <div style={{ whiteSpace: 'pre-wrap' }}>{text}</div>,
},
];
return (
<Modal
title={t('确认冲突项修改')}
visible={visible}
onCancel={onCancel}
onOk={onOk}
size={isMobile ? 'full-width' : 'large'}
>
<Table
columns={columns}
dataSource={items}
pagination={false}
size='small'
/>
</Modal>
);
}
export default function UpstreamRatioSync(props) {
const { t } = useTranslation();
const [modalVisible, setModalVisible] = useState(false);
const [loading, setLoading] = useState(false);
const [syncLoading, setSyncLoading] = useState(false);
useIsMobile();
// 渠道选择相关
const [allChannels, setAllChannels] = useState([]);
const [selectedChannelIds, setSelectedChannelIds] = useState([]);
// 渠道端点配置
const [channelEndpoints, setChannelEndpoints] = useState({}); // { channelId: endpoint }
// 差异数据和测试结果
const [differences, setDifferences] = useState({});
const [resolutions, setResolutions] = useState({});
// 是否已经执行过同步
const [hasSynced, setHasSynced] = useState(false);
// 分页相关状态
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
// 搜索相关状态
const [searchKeyword, setSearchKeyword] = useState('');
// 倍率类型过滤
const [ratioTypeFilter, setRatioTypeFilter] = useState('');
// 冲突确认弹窗相关
const [confirmVisible, setConfirmVisible] = useState(false);
const [conflictItems, setConflictItems] = useState([]); // {channel, model, current, newVal, ratioType}
const channelSelectorRef = React.useRef(null);
useEffect(() => {
setCurrentPage(1);
}, [ratioTypeFilter, searchKeyword]);
const fetchAllChannels = async () => {
setLoading(true);
try {
const res = await API.get('/api/ratio_sync/channels');
if (res.data.success) {
const channels = res.data.data || [];
const transferData = channels.map((channel) => ({
key: channel.id,
label: channel.name,
value: channel.id,
disabled: false,
_originalData: channel,
}));
setAllChannels(transferData);
// 合并已有 endpoints,避免每次打开弹窗都重置
setChannelEndpoints((prev) => {
const merged = { ...prev };
transferData.forEach((channel) => {
const id = channel.key;
const base = channel._originalData?.base_url || '';
const name = channel.label || '';
const isOfficial =
id === -100 ||
base === 'https://basellm.github.io' ||
name === '官方倍率预设';
if (!merged[id]) {
merged[id] = isOfficial
? '/llm-metadata/api/newapi/ratio_config-v1-base.json'
: DEFAULT_ENDPOINT;
}
});
return merged;
});
} else {
showError(res.data.message);
}
} catch (error) {
showError(t('获取渠道失败:') + error.message);
} finally {
setLoading(false);
}
};
const confirmChannelSelection = () => {
const selected = allChannels
.filter((ch) => selectedChannelIds.includes(ch.value))
.map((ch) => ch._originalData);
if (selected.length === 0) {
showWarning(t('请至少选择一个渠道'));
return;
}
setModalVisible(false);
fetchRatiosFromChannels(selected);
};
const fetchRatiosFromChannels = async (channelList) => {
setSyncLoading(true);
const upstreams = channelList.map((ch) => ({
id: ch.id,
name: ch.name,
base_url: ch.base_url,
endpoint: channelEndpoints[ch.id] || DEFAULT_ENDPOINT,
}));
const payload = {
upstreams: upstreams,
timeout: 10,
};
try {
const res = await API.post('/api/ratio_sync/fetch', payload);
if (!res.data.success) {
showError(res.data.message || t('后端请求失败'));
setSyncLoading(false);
return;
}
const { differences = {}, test_results = [] } = res.data.data;
const errorResults = test_results.filter((r) => r.status === 'error');
if (errorResults.length > 0) {
showWarning(
t('部分渠道测试失败:') +
errorResults.map((r) => `${r.name}: ${r.error}`).join(', '),
);
}
setDifferences(differences);
setResolutions({});
setHasSynced(true);
if (Object.keys(differences).length === 0) {
showSuccess(t('未找到差异化倍率,无需同步'));
}
} catch (e) {
showError(t('请求后端接口失败:') + e.message);
} finally {
setSyncLoading(false);
}
};
function getBillingCategory(ratioType) {
return ratioType === 'model_price' ? 'price' : 'ratio';
}
const selectValue = useCallback(
(model, ratioType, value) => {
const category = getBillingCategory(ratioType);
setResolutions((prev) => {
const newModelRes = { ...(prev[model] || {}) };
Object.keys(newModelRes).forEach((rt) => {
if (getBillingCategory(rt) !== category) {
delete newModelRes[rt];
}
});
newModelRes[ratioType] = value;
return {
...prev,
[model]: newModelRes,
};
});
},
[setResolutions],
);
const applySync = async () => {
const currentRatios = {
ModelRatio: JSON.parse(props.options.ModelRatio || '{}'),
CompletionRatio: JSON.parse(props.options.CompletionRatio || '{}'),
CacheRatio: JSON.parse(props.options.CacheRatio || '{}'),
ModelPrice: JSON.parse(props.options.ModelPrice || '{}'),
};
const conflicts = [];
const getLocalBillingCategory = (model) => {
if (currentRatios.ModelPrice[model] !== undefined) return 'price';
if (
currentRatios.ModelRatio[model] !== undefined ||
currentRatios.CompletionRatio[model] !== undefined ||
currentRatios.CacheRatio[model] !== undefined
)
return 'ratio';
return null;
};
const findSourceChannel = (model, ratioType, value) => {
if (differences[model] && differences[model][ratioType]) {
const upMap = differences[model][ratioType].upstreams || {};
const entry = Object.entries(upMap).find(([_, v]) => v === value);
if (entry) return entry[0];
}
return t('未知');
};
Object.entries(resolutions).forEach(([model, ratios]) => {
const localCat = getLocalBillingCategory(model);
const newCat = 'model_price' in ratios ? 'price' : 'ratio';
if (localCat && localCat !== newCat) {
const currentDesc =
localCat === 'price'
? `${t('固定价格')} : ${currentRatios.ModelPrice[model]}`
: `${t('模型倍率')} : ${currentRatios.ModelRatio[model] ?? '-'}\n${t('补全倍率')} : ${currentRatios.CompletionRatio[model] ?? '-'}`;
let newDesc = '';
if (newCat === 'price') {
newDesc = `${t('固定价格')} : ${ratios['model_price']}`;
} else {
const newModelRatio = ratios['model_ratio'] ?? '-';
const newCompRatio = ratios['completion_ratio'] ?? '-';
newDesc = `${t('模型倍率')} : ${newModelRatio}\n${t('补全倍率')} : ${newCompRatio}`;
}
const channels = Object.entries(ratios)
.map(([rt, val]) => findSourceChannel(model, rt, val))
.filter((v, idx, arr) => arr.indexOf(v) === idx)
.join(', ');
conflicts.push({
channel: channels,
model,
current: currentDesc,
newVal: newDesc,
});
}
});
if (conflicts.length > 0) {
setConflictItems(conflicts);
setConfirmVisible(true);
return;
}
await performSync(currentRatios);
};
const performSync = useCallback(
async (currentRatios) => {
const finalRatios = {
ModelRatio: { ...currentRatios.ModelRatio },
CompletionRatio: { ...currentRatios.CompletionRatio },
CacheRatio: { ...currentRatios.CacheRatio },
ModelPrice: { ...currentRatios.ModelPrice },
};
Object.entries(resolutions).forEach(([model, ratios]) => {
const selectedTypes = Object.keys(ratios);
const hasPrice = selectedTypes.includes('model_price');
const hasRatio = selectedTypes.some((rt) => rt !== 'model_price');
if (hasPrice) {
delete finalRatios.ModelRatio[model];
delete finalRatios.CompletionRatio[model];
delete finalRatios.CacheRatio[model];
}
if (hasRatio) {
delete finalRatios.ModelPrice[model];
}
Object.entries(ratios).forEach(([ratioType, value]) => {
const optionKey = ratioType
.split('_')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join('');
finalRatios[optionKey][model] = parseFloat(value);
});
});
setLoading(true);
try {
const updates = Object.entries(finalRatios).map(([key, value]) =>
API.put('/api/option/', {
key,
value: JSON.stringify(value, null, 2),
}),
);
const results = await Promise.all(updates);
if (results.every((res) => res.data.success)) {
showSuccess(t('同步成功'));
props.refresh();
setDifferences((prevDifferences) => {
const newDifferences = { ...prevDifferences };
Object.entries(resolutions).forEach(([model, ratios]) => {
Object.keys(ratios).forEach((ratioType) => {
if (newDifferences[model] && newDifferences[model][ratioType]) {
delete newDifferences[model][ratioType];
if (Object.keys(newDifferences[model]).length === 0) {
delete newDifferences[model];
}
}
});
});
return newDifferences;
});
setResolutions({});
} else {
showError(t('部分保存失败'));
}
} catch (error) {
showError(t('保存失败'));
} finally {
setLoading(false);
}
},
[resolutions, props.options, props.refresh],
);
const getCurrentPageData = (dataSource) => {
const startIndex = (currentPage - 1) * pageSize;
const endIndex = startIndex + pageSize;
return dataSource.slice(startIndex, endIndex);
};
const renderHeader = () => (
<div className='flex flex-col w-full'>
<div className='flex flex-col md:flex-row justify-between items-center gap-4 w-full'>
<div className='flex flex-col md:flex-row gap-2 w-full md:w-auto order-2 md:order-1'>
<Button
icon={<RefreshCcw size={14} />}
className='w-full md:w-auto mt-2'
onClick={() => {
setModalVisible(true);
if (allChannels.length === 0) {
fetchAllChannels();
}
}}
>
{t('选择同步渠道')}
</Button>
{(() => {
const hasSelections = Object.keys(resolutions).length > 0;
return (
<Button
icon={<CheckSquare size={14} />}
type='secondary'
onClick={applySync}
disabled={!hasSelections}
className='w-full md:w-auto mt-2'
>
{t('应用同步')}
</Button>
);
})()}
<div className='flex flex-col sm:flex-row gap-2 w-full md:w-auto mt-2'>
<Input
prefix={<IconSearch size={14} />}
placeholder={t('搜索模型名称')}
value={searchKeyword}
onChange={setSearchKeyword}
className='w-full sm:w-64'
showClear
/>
<Select
placeholder={t('按倍率类型筛选')}
value={ratioTypeFilter}
onChange={setRatioTypeFilter}
className='w-full sm:w-48'
showClear
onClear={() => setRatioTypeFilter('')}
>
<Select.Option value='model_ratio'>{t('模型倍率')}</Select.Option>
<Select.Option value='completion_ratio'>
{t('补全倍率')}
</Select.Option>
<Select.Option value='cache_ratio'>{t('缓存倍率')}</Select.Option>
<Select.Option value='model_price'>{t('固定价格')}</Select.Option>
</Select>
</div>
</div>
</div>
</div>
);
// 差异表数据:useMemo 必须在组件顶层调用,不能放进 renderDifferenceTable 渲染函数内,
// 否则违反 React Hooks 调用规则(该函数在 JSX 中被条件调用)。
const dataSource = useMemo(() => {
const tmp = [];
Object.entries(differences).forEach(([model, ratioTypes]) => {
const hasPrice = 'model_price' in ratioTypes;
const hasOtherRatio = [
'model_ratio',
'completion_ratio',
'cache_ratio',
].some((rt) => rt in ratioTypes);
const billingConflict = hasPrice && hasOtherRatio;
Object.entries(ratioTypes).forEach(([ratioType, diff]) => {
tmp.push({
key: `${model}_${ratioType}`,
model,
ratioType,
current: diff.current,
upstreams: diff.upstreams,
confidence: diff.confidence || {},
billingConflict,
});
});
});
return tmp;
}, [differences]);
const filteredDataSource = useMemo(() => {
if (!searchKeyword.trim() && !ratioTypeFilter) {
return dataSource;
}
return dataSource.filter((item) => {
const matchesKeyword =
!searchKeyword.trim() ||
item.model.toLowerCase().includes(searchKeyword.toLowerCase().trim());
const matchesRatioType =
!ratioTypeFilter || item.ratioType === ratioTypeFilter;
return matchesKeyword && matchesRatioType;
});
}, [dataSource, searchKeyword, ratioTypeFilter]);
const upstreamNames = useMemo(() => {
const set = new Set();
filteredDataSource.forEach((row) => {
Object.keys(row.upstreams || {}).forEach((name) => set.add(name));
});
return Array.from(set);
}, [filteredDataSource]);
const renderDifferenceTable = () => {
if (filteredDataSource.length === 0) {
return (
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={
searchKeyword.trim()
? t('未找到匹配的模型')
: Object.keys(differences).length === 0
? hasSynced
? t('暂无差异化倍率显示')
: t('请先选择同步渠道')
: t('请先选择同步渠道')
}
style={{ padding: 30 }}
/>
);
}
const columns = [
{
title: t('模型'),
dataIndex: 'model',
fixed: 'left',
},
{
title: t('倍率类型'),
dataIndex: 'ratioType',
render: (text, record) => {
const typeMap = {
model_ratio: t('模型倍率'),
completion_ratio: t('补全倍率'),
cache_ratio: t('缓存倍率'),
model_price: t('固定价格'),
};
const baseTag = (
<Tag color={stringToColor(text)} shape='circle'>
{typeMap[text] || text}
</Tag>
);
if (record?.billingConflict) {
return (
<div className='flex items-center gap-1'>
{baseTag}
<Tooltip
position='top'
content={t(
'该模型存在固定价格与倍率计费方式冲突,请确认选择',
)}
>
<AlertTriangle size={14} className='text-yellow-500' />
</Tooltip>
</div>
);
}
return baseTag;
},
},
{
title: t('置信度'),
dataIndex: 'confidence',
render: (_, record) => {
const allConfident = Object.values(record.confidence || {}).every(
(v) => v !== false,
);
if (allConfident) {
return (
<Tooltip content={t('所有上游数据均可信')}>
<Tag
color='green'
shape='circle'
type='light'
prefixIcon={<CheckCircle size={14} />}
>
{t('可信')}
</Tag>
</Tooltip>
);
} else {
const untrustedSources = Object.entries(record.confidence || {})
.filter(([_, isConfident]) => isConfident === false)
.map(([name]) => name)
.join(', ');
return (
<Tooltip
content={t('以下上游数据可能不可信:') + untrustedSources}
>
<Tag
color='yellow'
shape='circle'
type='light'
prefixIcon={<AlertTriangle size={14} />}
>
{t('谨慎')}
</Tag>
</Tooltip>
);
}
},
},
{
title: t('当前值'),
dataIndex: 'current',
render: (text) => (
<Tag
color={text !== null && text !== undefined ? 'blue' : 'default'}
shape='circle'
>
{text !== null && text !== undefined ? text : t('未设置')}
</Tag>
),
},
...upstreamNames.map((upName) => {
const channelStats = (() => {
let selectableCount = 0;
let selectedCount = 0;
filteredDataSource.forEach((row) => {
const upstreamVal = row.upstreams?.[upName];
if (
upstreamVal !== null &&
upstreamVal !== undefined &&
upstreamVal !== 'same'
) {
selectableCount++;
const isSelected =
resolutions[row.model]?.[row.ratioType] === upstreamVal;
if (isSelected) {
selectedCount++;
}
}
});
return {
selectableCount,
selectedCount,
allSelected:
selectableCount > 0 && selectedCount === selectableCount,
partiallySelected:
selectedCount > 0 && selectedCount < selectableCount,
hasSelectableItems: selectableCount > 0,
};
})();
const handleBulkSelect = (checked) => {
if (checked) {
filteredDataSource.forEach((row) => {
const upstreamVal = row.upstreams?.[upName];
if (
upstreamVal !== null &&
upstreamVal !== undefined &&
upstreamVal !== 'same'
) {
selectValue(row.model, row.ratioType, upstreamVal);
}
});
} else {
setResolutions((prev) => {
const newRes = { ...prev };
filteredDataSource.forEach((row) => {
if (newRes[row.model]) {
delete newRes[row.model][row.ratioType];
if (Object.keys(newRes[row.model]).length === 0) {
delete newRes[row.model];
}
}
});
return newRes;
});
}
};
return {
title: channelStats.hasSelectableItems ? (
<Checkbox
checked={channelStats.allSelected}
indeterminate={channelStats.partiallySelected}
onChange={(e) => handleBulkSelect(e.target.checked)}
>
{upName}
</Checkbox>
) : (
<span>{upName}</span>
),
dataIndex: upName,
render: (_, record) => {
const upstreamVal = record.upstreams?.[upName];
const isConfident = record.confidence?.[upName] !== false;
if (upstreamVal === null || upstreamVal === undefined) {
return (
<Tag color='default' shape='circle'>
{t('未设置')}
</Tag>
);
}
if (upstreamVal === 'same') {
return (
<Tag color='blue' shape='circle'>
{t('与本地相同')}
</Tag>
);
}
const isSelected =
resolutions[record.model]?.[record.ratioType] === upstreamVal;
return (
<div className='flex items-center gap-2'>
<Checkbox
checked={isSelected}
onChange={(e) => {
const isChecked = e.target.checked;
if (isChecked) {
selectValue(record.model, record.ratioType, upstreamVal);
} else {
setResolutions((prev) => {
const newRes = { ...prev };
if (newRes[record.model]) {
delete newRes[record.model][record.ratioType];
if (Object.keys(newRes[record.model]).length === 0) {
delete newRes[record.model];
}
}
return newRes;
});
}
}}
>
{upstreamVal}
</Checkbox>
{!isConfident && (
<Tooltip
position='left'
content={t('该数据可能不可信,请谨慎使用')}
>
<AlertTriangle size={16} className='text-yellow-500' />
</Tooltip>
)}
</div>
);
},
};
}),
];
return (
<Table
columns={columns}
dataSource={getCurrentPageData(filteredDataSource)}
pagination={{
currentPage: currentPage,
pageSize: pageSize,
total: filteredDataSource.length,
showSizeChanger: true,
showQuickJumper: true,
pageSizeOptions: ['5', '10', '20', '50'],
onChange: (page, size) => {
setCurrentPage(page);
setPageSize(size);
},
onShowSizeChange: (current, size) => {
setCurrentPage(1);
setPageSize(size);
},
}}
scroll={{ x: 'max-content' }}
size='middle'
loading={loading || syncLoading}
/>
);
};
const updateChannelEndpoint = useCallback((channelId, endpoint) => {
setChannelEndpoints((prev) => ({ ...prev, [channelId]: endpoint }));
}, []);
const handleModalClose = () => {
setModalVisible(false);
if (channelSelectorRef.current) {
channelSelectorRef.current.resetPagination();
}
};
return (
<>
<Form.Section text={renderHeader()}>
{renderDifferenceTable()}
</Form.Section>
<ChannelSelectorModal
ref={channelSelectorRef}
t={t}
visible={modalVisible}
onCancel={handleModalClose}
onOk={confirmChannelSelection}
allChannels={allChannels}
selectedChannelIds={selectedChannelIds}
setSelectedChannelIds={setSelectedChannelIds}
channelEndpoints={channelEndpoints}
updateChannelEndpoint={updateChannelEndpoint}
/>
<ConflictConfirmModal
t={t}
visible={confirmVisible}
items={conflictItems}
onOk={async () => {
setConfirmVisible(false);
const curRatios = {
ModelRatio: JSON.parse(props.options.ModelRatio || '{}'),
CompletionRatio: JSON.parse(props.options.CompletionRatio || '{}'),
CacheRatio: JSON.parse(props.options.CacheRatio || '{}'),
ModelPrice: JSON.parse(props.options.ModelPrice || '{}'),
};
await performSync(curRatios);
}}
onCancel={() => setConfirmVisible(false)}
/>
</>
);
}
+121
View File
@@ -0,0 +1,121 @@
/* WeyAi 设置分组:云平台控制台风格的分区卡片,配色全部从 token 派生。 */
.weyai-settings {
--ws-line: var(--border-subtle);
--ws-muted: var(--text-secondary);
--ws-ink: var(--text-primary);
--ws-accent: var(--semi-color-primary);
--ws-accent-line: color-mix(
in srgb,
var(--semi-color-primary) 28%,
transparent
);
--ws-tint: color-mix(
in srgb,
var(--semi-color-primary) 5%,
var(--surface-card)
);
}
.weyai-section {
border: 1px solid var(--ws-line);
border-radius: 12px;
background: var(--surface-card);
overflow: hidden;
}
/* 个人 / 企业两张卡用主色边框与淡色标题带区分,其他分区保持中性 */
.weyai-section--accent {
border-color: var(--ws-accent-line);
/* 个人/企业并排时撑满 grid 单元格,两卡等高 */
height: 100%;
}
.weyai-section--accent .weyai-section__head {
background: var(--ws-tint);
}
.weyai-section__head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
padding: 12px 16px;
border-bottom: 1px solid var(--ws-line);
}
.weyai-section__title {
display: block;
font-size: 14px;
font-weight: 600;
line-height: 20px;
color: var(--ws-ink);
}
.weyai-section__desc {
display: block;
margin-top: 2px;
font-size: 12px;
line-height: 18px;
color: var(--ws-muted);
}
.weyai-section__body {
padding: 16px;
}
/* 分区内的小标题:文字 + 一条贯穿的细线 */
.weyai-subhead {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
font-size: 12px;
font-weight: 600;
color: var(--ws-muted);
}
.weyai-subhead::after {
content: '';
flex: 1;
height: 1px;
background: var(--ws-line);
}
/* 开放范围为「全部用户」时,个人/企业卡里的占位说明 */
.weyai-placeholder {
padding: 10px 12px;
border: 1px dashed var(--ws-line);
border-radius: 8px;
font-size: 12px;
line-height: 18px;
color: var(--ws-muted);
}
.weyai-settings button:focus-visible,
.weyai-settings .semi-select:focus-visible,
.weyai-settings .semi-input-wrapper:focus-within {
outline: 2px solid
color-mix(in srgb, var(--semi-color-primary) 55%, transparent);
outline-offset: 2px;
}
/* 下拉底部的失败态:可点击重试,与"没有匹配"的静态占位区分开 */
.weyai-placeholder--action {
cursor: pointer;
color: var(--semi-color-warning);
border-color: var(--semi-color-warning-light-active);
}
.weyai-placeholder--action:hover,
.weyai-placeholder--action:focus-visible {
background: var(--semi-color-warning-light-default);
outline: none;
}
/* 行内的"点击重试":嵌在提示句里,去掉按钮的内边距与高度,像一个链接 */
.weyai-settings .weyai-inline-action.semi-button {
height: auto;
padding: 0 2px;
font-size: inherit;
line-height: inherit;
vertical-align: baseline;
}
File diff suppressed because it is too large Load Diff
+69
View File
@@ -0,0 +1,69 @@
/*
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
*/
// WeyAi 设置的保存顺序。页面把每个配置项作为独立的 PUT 提交,任何一项都可能
// 被后端拒掉;这里决定先后,保证停在中途任何一步,库里都不会是
// "指定范围 + 四项开放名单全空"——那样全站用户的网页端入口一起消失,后端
// (model.validateWeyAiWebAccessNotEmpty)也会拒绝写成那个状态。
export const ACCESS_MODE_KEY = 'WeyAiWebAccessMode';
export const WEB_ENABLED_KEY = 'WeyAiWebEnabled';
// 公网访问开关:后端(model.validateWeyAiRemoteEnableReady)要求打开时地址与
// 客户端密钥已经落库,所以它和网页端开关一样放在最后一批
export const REMOTE_ENABLED_KEY = 'WeyAiRemoteEnabled';
// 开放范围模式:all 为全部用户;指定范围存为 list(与 service/client/config.go 的
// WebAccessModeList 一致)
export const ACCESS_MODE_ALL = 'all';
export const ACCESS_MODE_LIMITED = 'list';
// 「指定范围」的四项开放名单(黑名单不算):四项全空 = 没有任何人能用
export const OPEN_LIST_KEYS = [
'WeyAiWebAccessGroups',
'WeyAiWebAccessOrgs',
'WeyAiWebAccessOrgGroups',
'WeyAiWebAccessUsers',
];
/**
* 把待提交的 [{ key, value }](value 已序列化为字符串)分成四批,批内并行、
* 批间串行,前一批有失败就不再提交后面的批次:
* 1) 下面三种以外的全部改动。放开为「全部用户」、关闭总开关也在这一批:
* 先放开 / 先关,后面清名单才不会撞上空范围
* 2) 清空名单。要保留的名单此时已落库,清空不会把范围清成空
* 3) 收紧为「指定范围」。名单都成功了才切,失败时模式保持原值
* 4) 打开总开关(网页端、公网访问)。公网访问的开关要求地址与密钥已落库。首次开启同时选「指定范围」时,开关若先落库而后面任一批失败,
* 库里就是"已启用 + 全部用户",所有登录用户都能进——与管理员的意图相反。
* 开关最后一个落库,前面有失败就保持关闭
*/
export function planSaveStages(updates) {
const tightening = (item) =>
item.key === ACCESS_MODE_KEY && item.value === ACCESS_MODE_LIMITED;
const clearing = (item) =>
OPEN_LIST_KEYS.includes(item.key) && item.value === '';
const enabling = (item) =>
(item.key === WEB_ENABLED_KEY || item.key === REMOTE_ENABLED_KEY) &&
item.value === 'true';
return [
updates.filter(
(item) => !tightening(item) && !clearing(item) && !enabling(item),
),
updates.filter(clearing),
updates.filter(tightening),
updates.filter(enabling),
];
}
+148
View File
@@ -0,0 +1,148 @@
/*
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 assert from 'node:assert/strict';
import test from 'node:test';
import { OPEN_LIST_KEYS, planSaveStages } from './saveStages.js';
const keysOf = (stage) => stage.map((item) => item.key);
// 按批次顺序把改动落到"库"里,每落一项检查一次:任何时刻都不能是
// 「指定范围 + 四项开放名单全空」。批内并行,所以批内每种先后都要成立。
function assertNeverShutOut(stored, updates) {
const state = { ...stored };
const shutOut = () =>
state.WeyAiWebAccessMode === 'list' &&
OPEN_LIST_KEYS.every((key) => !state[key]);
assert.equal(shutOut(), false, 'the starting state must be usable');
for (const stage of planSaveStages(updates)) {
for (const order of [stage, [...stage].reverse()]) {
const snapshot = { ...state };
for (const item of order) {
snapshot[item.key] = item.value;
const mode = snapshot.WeyAiWebAccessMode;
const empty = OPEN_LIST_KEYS.every((key) => !snapshot[key]);
assert.equal(
mode === 'list' && empty,
false,
`shut out after saving ${item.key}`,
);
}
}
stage.forEach((item) => {
state[item.key] = item.value;
});
}
}
test('tightening to the restricted mode is saved after the lists', () => {
const updates = [
{ key: 'WeyAiWebAccessMode', value: 'list' },
{ key: 'WeyAiWebAccessUsers', value: '7' },
{ key: 'WeyAiDefaultModel', value: 'm' },
];
const [first, second, third, fourth] = planSaveStages(updates);
assert.deepEqual(keysOf(first), ['WeyAiWebAccessUsers', 'WeyAiDefaultModel']);
assert.deepEqual(second, []);
assert.deepEqual(keysOf(third), ['WeyAiWebAccessMode']);
assert.deepEqual(fourth, []);
assertNeverShutOut({ WeyAiWebAccessMode: 'all' }, updates);
});
test('turning the web client on is the very last write; turning it off is not held back', () => {
// 首次配置:开关 + 地址 + 密钥 + 指定范围 + 名单一次填完。开关若和地址一起先
// 落库而名单被拒,库里就是"已启用 + 全部用户",与管理员的意图相反
const updates = [
{ key: 'WeyAiWebEnabled', value: 'true' },
{ key: 'WeyAiWebUrl', value: 'https://ai.example.com' },
{ key: 'WeyAiWebAccessMode', value: 'list' },
{ key: 'WeyAiWebAccessGroups', value: 'vip' },
];
const stages = planSaveStages(updates);
assert.deepEqual(keysOf(stages[0]), ['WeyAiWebUrl', 'WeyAiWebAccessGroups']);
assert.deepEqual(keysOf(stages[2]), ['WeyAiWebAccessMode']);
assert.deepEqual(keysOf(stages[3]), ['WeyAiWebEnabled']);
const [off] = planSaveStages([{ key: 'WeyAiWebEnabled', value: 'false' }]);
assert.deepEqual(keysOf(off), ['WeyAiWebEnabled']);
});
test('replacing the only open list with another never passes through an empty scope', () => {
// 旧顺序是全部并行:清空先成功、新增被后端拒掉时,库里就是空范围
const updates = [
{ key: 'WeyAiWebAccessUsers', value: '' },
{ key: 'WeyAiWebAccessGroups', value: 'vip' },
];
const [first, second] = planSaveStages(updates);
assert.deepEqual(keysOf(first), ['WeyAiWebAccessGroups']);
assert.deepEqual(keysOf(second), ['WeyAiWebAccessUsers']);
assertNeverShutOut(
{ WeyAiWebAccessMode: 'list', WeyAiWebAccessUsers: '5' },
updates,
);
});
test('opening to all users goes first, so clearing the lists afterwards is safe', () => {
const updates = [
{ key: 'WeyAiWebAccessUsers', value: '' },
{ key: 'WeyAiWebAccessOrgs', value: '' },
{ key: 'WeyAiWebAccessMode', value: 'all' },
];
const [first, second, third, fourth] = planSaveStages(updates);
assert.deepEqual(keysOf(first), ['WeyAiWebAccessMode']);
assert.deepEqual(keysOf(second), [
'WeyAiWebAccessUsers',
'WeyAiWebAccessOrgs',
]);
assert.deepEqual(third, []);
assert.deepEqual(fourth, []);
assertNeverShutOut(
{
WeyAiWebAccessMode: 'list',
WeyAiWebAccessUsers: '5',
WeyAiWebAccessOrgs: '3',
},
updates,
);
});
test('the deny list is not an open list and is never held back', () => {
const [first, second] = planSaveStages([
{ key: 'WeyAiWebDenyUsers', value: '' },
]);
assert.deepEqual(keysOf(first), ['WeyAiWebDenyUsers']);
assert.deepEqual(second, []);
});
test('turning remote access on is saved after its address and secret', () => {
// 后端要求打开公网访问时地址与密钥已落库:同一次保存里它们必须先于开关
const updates = [
{ key: 'WeyAiRemoteEnabled', value: 'true' },
{ key: 'WeyAiRemoteUrl', value: 'https://my.remote.example.com' },
{ key: 'WeyAiRemoteClientSecret', value: 'x'.repeat(32) },
];
const stages = planSaveStages(updates);
assert.deepEqual(keysOf(stages[0]), [
'WeyAiRemoteUrl',
'WeyAiRemoteClientSecret',
]);
assert.deepEqual(keysOf(stages[3]), ['WeyAiRemoteEnabled']);
// 关闭不必等
const off = planSaveStages([{ key: 'WeyAiRemoteEnabled', value: 'false' }]);
assert.deepEqual(keysOf(off[0]), ['WeyAiRemoteEnabled']);
});
+335
View File
@@ -0,0 +1,335 @@
/*
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, { useContext, useEffect, useState } from 'react';
import { Layout, TabPane, Tabs } from '@douyinfe/semi-ui';
import { useNavigate, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { StatusContext } from '../../context/Status';
import {
ALWAYS_ADMIN_VISIBLE_TABS,
ROOT_ONLY_SETTING_TABS,
} from '../../constants/settingTabs';
import {
Settings,
Calculator,
Gauge,
Shapes,
Cog,
MoreHorizontal,
LayoutDashboard,
MessageSquare,
Palette,
CreditCard,
Coins,
Crown,
Headphones,
Video,
ShieldCheck,
ShieldAlert,
Layers,
} from 'lucide-react';
import SystemSetting from '../../components/settings/SystemSetting';
import { isAdmin, isRoot } from '../../helpers';
import OtherSetting from '../../components/settings/OtherSetting';
import OperationSetting from '../../components/settings/OperationSetting';
import DataSecuritySetting from '../../components/settings/DataSecuritySetting';
import ContentGuardSetting from '../../components/settings/ContentGuardSetting';
import RateLimitSetting from '../../components/settings/RateLimitSetting';
import ModelSetting from '../../components/settings/ModelSetting';
import DashboardSetting from '../../components/settings/DashboardSetting';
import RatioSetting from '../../components/settings/RatioSetting';
import LevelPolicySetting from '../../components/settings/LevelPolicySetting';
import ChatsSetting from '../../components/settings/ChatsSetting';
import DrawingSetting from '../../components/settings/DrawingSetting';
import PaymentSetting from '../../components/settings/PaymentSetting';
import CustomerServiceSetting from '../../components/settings/CustomerServiceSetting';
import TutorialVideoSetting from '../../components/settings/TutorialVideoSetting';
import AmountOptionsManager from './AmountOptionsManager';
import SettingsMembership from './Payment/SettingsMembership';
const Setting = () => {
const { t } = useTranslation();
const navigate = useNavigate();
const location = useLocation();
const [statusState] = useContext(StatusContext);
const [tabActiveKey, setTabActiveKey] = useState('1');
let panes = [];
const membershipPane = {
tab: (
<span style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
<Crown size={18} />
{t('会员管理')}
</span>
),
content: <SettingsMembership />,
itemKey: 'membership',
};
// 先构建全部 tab,再按角色 + 下放配置过滤可见性(见下方)。
{
panes.push({
tab: (
<span style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
<Settings size={18} />
{t('运营设置')}
</span>
),
content: <OperationSetting />,
itemKey: 'operation',
});
panes.push({
tab: (
<span style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
<ShieldCheck size={18} />
{t('数据安全')}
</span>
),
content: <DataSecuritySetting />,
itemKey: 'data-security',
});
panes.push({
tab: (
<span style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
<ShieldAlert size={18} />
{t('大模型内容防护')}
</span>
),
content: <ContentGuardSetting />,
itemKey: 'content-guard',
});
panes.push({
tab: (
<span style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
<LayoutDashboard size={18} />
{t('仪表盘设置')}
</span>
),
content: <DashboardSetting />,
itemKey: 'dashboard',
});
panes.push({
tab: (
<span style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
<MessageSquare size={18} />
{t('聊天设置')}
</span>
),
content: <ChatsSetting />,
itemKey: 'chats',
});
panes.push({
tab: (
<span style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
<Palette size={18} />
{t('绘图设置')}
</span>
),
content: <DrawingSetting />,
itemKey: 'drawing',
});
panes.push({
tab: (
<span style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
<CreditCard size={18} />
{t('支付设置')}
</span>
),
content: <PaymentSetting />,
itemKey: 'payment',
});
panes.push({
tab: (
<span style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
<Coins size={18} />
{t('充值档位管理')}
</span>
),
content: <AmountOptionsManager />,
itemKey: 'amount-options',
});
panes.push({
tab: (
<span style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
<Coins size={18} />
{t('企业充值档位')}
</span>
),
content: (
<AmountOptionsManager
apiPath='/api/user/payment/org-amount-options'
title={t('企业充值档位管理')}
/>
),
itemKey: 'org-amount-options',
});
panes.push(membershipPane);
panes.push({
tab: (
<span style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
<Calculator size={18} />
{t('分组与模型定价设置')}
</span>
),
content: <RatioSetting />,
itemKey: 'ratio',
});
panes.push({
tab: (
<span style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
<Layers size={18} />
{t('等级与模型访问')}
</span>
),
content: <LevelPolicySetting />,
itemKey: 'level_policy',
});
panes.push({
tab: (
<span style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
<Gauge size={18} />
{t('速率限制设置')}
</span>
),
content: <RateLimitSetting />,
itemKey: 'ratelimit',
});
panes.push({
tab: (
<span style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
<Shapes size={18} />
{t('模型相关设置')}
</span>
),
content: <ModelSetting />,
itemKey: 'models',
});
panes.push({
tab: (
<span style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
<Headphones size={18} />
{t('客服设置')}
</span>
),
content: <CustomerServiceSetting />,
itemKey: 'customer-service',
});
panes.push({
tab: (
<span style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
<Video size={18} />
{t('教程视频管理')}
</span>
),
content: <TutorialVideoSetting />,
itemKey: 'tutorial-video',
});
panes.push({
tab: (
<span style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
<Cog size={18} />
{t('系统设置')}
</span>
),
content: <SystemSetting />,
itemKey: 'system',
});
panes.push({
tab: (
<span style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
<MoreHorizontal size={18} />
{t('其他设置')}
</span>
),
content: <OtherSetting />,
itemKey: 'other',
});
}
// 解析 root 配置的「下放给普通管理员」tab 列表
let delegatedTabs = [];
try {
const raw = statusState?.status?.AdminDelegatedSettingTabs;
if (raw) delegatedTabs = JSON.parse(raw);
} catch (e) {
delegatedTabs = [];
}
// 可见性过滤:root 看全部;普通管理员看「会员管理 + 被下放的 tab」;其余看不到。
if (!isRoot()) {
if (isAdmin()) {
const allowed = new Set([
...ALWAYS_ADMIN_VISIBLE_TABS,
...delegatedTabs.filter((tab) => !ROOT_ONLY_SETTING_TABS.includes(tab)),
]);
panes = panes.filter((pane) => allowed.has(pane.itemKey));
} else {
panes = [];
}
}
const onChangeTab = (key) => {
setTabActiveKey(key);
navigate(`?tab=${key}`);
};
useEffect(() => {
// 非 root 的可见 tab 依赖 status 中的下放配置;status 未加载前不要急于重定向,
// 否则深链到「被下放 tab」会因 panes 尚未包含它而被错误重定向走。
if (!isRoot() && !statusState?.status) {
return;
}
const searchParams = new URLSearchParams(window.location.search);
const tab = searchParams.get('tab');
const preferredDefault = isRoot() ? 'operation' : 'membership';
const defaultTabKey = panes.some(
(pane) => pane.itemKey === preferredDefault,
)
? preferredDefault
: panes[0]?.itemKey;
const tabExists = panes.some((pane) => pane.itemKey === tab);
const nextTab = tab && tabExists ? tab : defaultTabKey;
setTabActiveKey(nextTab);
if (tab !== nextTab) {
navigate(`?tab=${nextTab}`, { replace: true });
}
}, [location.search, statusState?.status?.AdminDelegatedSettingTabs]);
return (
<div className='mt-[60px] px-2'>
<Layout>
<Layout.Content>
<Tabs
type='card'
collapsible
activeKey={tabActiveKey}
onChange={(key) => onChangeTab(key)}
>
{panes.map((pane) => (
<TabPane itemKey={pane.itemKey} tab={pane.tab} key={pane.itemKey}>
{tabActiveKey === pane.itemKey && pane.content}
</TabPane>
))}
</Tabs>
</Layout.Content>
</Layout>
</div>
);
};
export default Setting;