Initial import of weiyuan frontend

This commit is contained in:
qiubaishen
2026-10-15 16:33:46 +08:00
commit d8f3aee261
774 changed files with 374914 additions and 0 deletions
@@ -0,0 +1,296 @@
/*
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,
forwardRef,
useImperativeHandle,
} from 'react';
import { useIsMobile } from '../../hooks/common/useIsMobile';
import {
Modal,
Table,
Input,
Space,
Highlight,
Select,
Tag,
} from '@douyinfe/semi-ui';
import { IconSearch } from '@douyinfe/semi-icons';
const ChannelSelectorModal = forwardRef(
(
{
visible,
onCancel,
onOk,
allChannels,
selectedChannelIds,
setSelectedChannelIds,
channelEndpoints,
updateChannelEndpoint,
t,
},
ref,
) => {
const [searchText, setSearchText] = useState('');
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const isMobile = useIsMobile();
const [filteredData, setFilteredData] = useState([]);
useImperativeHandle(ref, () => ({
resetPagination: () => {
setCurrentPage(1);
setSearchText('');
},
}));
// 官方渠道识别
const isOfficialChannel = (record) => {
const id = record?.key ?? record?.value ?? record?._originalData?.id;
const base = record?._originalData?.base_url || '';
const name = record?.label || '';
return (
id === -100 ||
base === 'https://basellm.github.io' ||
name === '官方倍率预设'
);
};
useEffect(() => {
if (!allChannels) return;
const searchLower = searchText.trim().toLowerCase();
const matched = searchLower
? allChannels.filter((item) => {
const name = (item.label || '').toLowerCase();
const baseUrl = (item._originalData?.base_url || '').toLowerCase();
return name.includes(searchLower) || baseUrl.includes(searchLower);
})
: allChannels;
const sorted = [...matched].sort((a, b) => {
const wa = isOfficialChannel(a) ? 0 : 1;
const wb = isOfficialChannel(b) ? 0 : 1;
return wa - wb;
});
setFilteredData(sorted);
}, [allChannels, searchText]);
const total = filteredData.length;
const paginatedData = filteredData.slice(
(currentPage - 1) * pageSize,
currentPage * pageSize,
);
const updateEndpoint = (channelId, endpoint) => {
if (typeof updateChannelEndpoint === 'function') {
updateChannelEndpoint(channelId, endpoint);
}
};
const renderEndpointCell = (text, record) => {
const channelId = record.key || record.value;
const currentEndpoint = channelEndpoints[channelId] || '';
const getEndpointType = (ep) => {
if (ep === '/api/ratio_config') return 'ratio_config';
if (ep === '/api/pricing') return 'pricing';
return 'custom';
};
const currentType = getEndpointType(currentEndpoint);
const handleTypeChange = (val) => {
if (val === 'ratio_config') {
updateEndpoint(channelId, '/api/ratio_config');
} else if (val === 'pricing') {
updateEndpoint(channelId, '/api/pricing');
} else {
if (currentType !== 'custom') {
updateEndpoint(channelId, '');
}
}
};
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<Select
size='small'
value={currentType}
onChange={handleTypeChange}
style={{ width: 120 }}
optionList={[
{ label: 'ratio_config', value: 'ratio_config' },
{ label: 'pricing', value: 'pricing' },
{ label: 'custom', value: 'custom' },
]}
/>
{currentType === 'custom' && (
<Input
size='small'
value={currentEndpoint}
onChange={(val) => updateEndpoint(channelId, val)}
placeholder='/your/endpoint'
style={{ width: 160, fontSize: 12 }}
/>
)}
</div>
);
};
const renderStatusCell = (record) => {
const status = record?._originalData?.status || 0;
const official = isOfficialChannel(record);
let statusTag = null;
switch (status) {
case 1:
statusTag = (
<Tag color='green' shape='circle'>
{t('已启用')}
</Tag>
);
break;
case 2:
statusTag = (
<Tag color='red' shape='circle'>
{t('已禁用')}
</Tag>
);
break;
case 3:
statusTag = (
<Tag color='yellow' shape='circle'>
{t('自动禁用')}
</Tag>
);
break;
default:
statusTag = (
<Tag color='grey' shape='circle'>
{t('未知状态')}
</Tag>
);
}
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
{statusTag}
{official && (
<Tag color='green' shape='circle' type='light'>
{t('官方')}
</Tag>
)}
</div>
);
};
const renderNameCell = (text) => (
<Highlight sourceString={text} searchWords={[searchText]} />
);
const renderBaseUrlCell = (text) => (
<Highlight sourceString={text} searchWords={[searchText]} />
);
const columns = [
{
title: t('名称'),
dataIndex: 'label',
render: renderNameCell,
},
{
title: t('源地址'),
dataIndex: '_originalData.base_url',
render: (_, record) =>
renderBaseUrlCell(record._originalData?.base_url || ''),
},
{
title: t('状态'),
dataIndex: '_originalData.status',
render: (_, record) => renderStatusCell(record),
},
{
title: t('同步接口'),
dataIndex: 'endpoint',
fixed: 'right',
render: renderEndpointCell,
},
];
const rowSelection = {
selectedRowKeys: selectedChannelIds,
onChange: (keys) => setSelectedChannelIds(keys),
};
return (
<Modal
visible={visible}
onCancel={onCancel}
onOk={onOk}
title={
<span className='text-lg font-semibold'>{t('选择同步渠道')}</span>
}
size={isMobile ? 'full-width' : 'large'}
keepDOM
lazyRender={false}
>
<Space vertical style={{ width: '100%' }}>
<Input
prefix={<IconSearch size={14} />}
placeholder={t('搜索渠道名称或地址')}
value={searchText}
onChange={setSearchText}
showClear
/>
<Table
columns={columns}
dataSource={paginatedData}
rowKey='key'
rowSelection={rowSelection}
pagination={{
currentPage: currentPage,
pageSize: pageSize,
total: total,
showSizeChanger: true,
showQuickJumper: true,
pageSizeOptions: ['10', '20', '50', '100'],
onChange: (page, size) => {
setCurrentPage(page);
setPageSize(size);
},
onShowSizeChange: (curr, size) => {
setCurrentPage(1);
setPageSize(size);
},
}}
size='small'
/>
</Space>
</Modal>
);
},
);
export default ChannelSelectorModal;
+82
View File
@@ -0,0 +1,82 @@
/*
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 { Card, Spin } from '@douyinfe/semi-ui';
import SettingsChats from '../../pages/Setting/Chat/SettingsChats';
import { API, showError, toBoolean } from '../../helpers';
const ChatsSetting = () => {
let [inputs, setInputs] = useState({
/* 聊天设置 */
Chats: '[]',
});
let [loading, setLoading] = useState(false);
const getOptions = async () => {
const res = await API.get('/api/option/');
const { success, message, data } = res.data;
if (success) {
let newInputs = {};
data.forEach((item) => {
if (
item.key.endsWith('Enabled') ||
['DefaultCollapseSidebar'].includes(item.key)
) {
newInputs[item.key] = toBoolean(item.value);
} else {
newInputs[item.key] = item.value;
}
});
setInputs(newInputs);
} else {
showError(message);
}
};
async function onRefresh() {
try {
setLoading(true);
await getOptions();
} catch (error) {
showError('刷新失败');
} finally {
setLoading(false);
}
}
useEffect(() => {
onRefresh();
}, []);
return (
<>
<Spin spinning={loading} size='large'>
{/* 聊天设置 */}
<Card style={{ marginTop: '10px' }}>
<SettingsChats options={inputs} refresh={onRefresh} />
</Card>
</Spin>
</>
);
};
export default ChatsSetting;
@@ -0,0 +1,729 @@
/*
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,
useMemo,
useRef,
useState,
} from 'react';
import {
Banner,
Button,
Card,
Descriptions,
Form,
Input,
Modal,
Space,
Spin,
Table,
TabPane,
Tabs,
Tag,
Typography,
} from '@douyinfe/semi-ui';
import { RefreshCw, Save, ShieldAlert, TestTube2 } from 'lucide-react';
import { API, showError, showSuccess } from '../../helpers';
import { useTranslation } from 'react-i18next';
import {
ENFORCE_CHECK_FIELDS,
normalizeContentGuardConfig,
} from './contentGuardConfig.js';
const DEFAULT_CONFIG = {
provider: 'uguard',
enabled: false,
mode: 'observe',
base_url: '',
api_key: '',
input_enabled: true,
output_enabled: true,
text_enabled: true,
image_enabled: true,
video_enabled: true,
text_timeout_ms: 30000,
image_timeout_ms: 60000,
video_timeout_ms: 180000,
text_concurrency: 16,
image_concurrency: 4,
video_concurrency: 2,
text_cluster_qps: 20,
image_cluster_qps: 5,
video_cluster_qps: 2,
observe_queue_size: 256,
observe_workers: 4,
stream_memory_threshold_bytes: 1048576,
stream_response_cap_bytes: 16777216,
stream_spool_cap_bytes: 1073741824,
image_temp_cap_bytes: 1073741824,
video_temp_cap_bytes: 10737418240,
groups: [],
user_ids: [],
confirm_enforce: false,
};
const errorMessage = (error) =>
error?.response?.data?.message || error?.message || '请求失败';
const statusTag = (config, t) => {
if (config.lifecycle_state === 'decommissioned') {
return <Tag color='grey'>{t('已永久下线')}</Tag>;
}
if (config.lifecycle_state === 'draining') {
return <Tag color='orange'>{t('清算中')}</Tag>;
}
if (config.emergency_disabled) {
return <Tag color='red'>{t('紧急关闭')}</Tag>;
}
return config.enabled ? (
<Tag color='green'>{t('运行中')}</Tag>
) : (
<Tag>{t('未启用')}</Tag>
);
};
export default function ContentGuardSetting() {
const { t } = useTranslation();
const formApi = useRef(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [config, setConfig] = useState(DEFAULT_CONFIG);
const [groups, setGroups] = useState([]);
const [users, setUsers] = useState([]);
const [logs, setLogs] = useState({ items: [], total: 0, page: 1, size: 20 });
const [metrics, setMetrics] = useState({});
const [decommission, setDecommission] = useState(null);
const [killReason, setKillReason] = useState('');
const [userKeyword, setUserKeyword] = useState('');
const [isEnforceMode, setIsEnforceMode] = useState(false);
const formValues = useMemo(
() => ({
...DEFAULT_CONFIG,
...config,
api_key: '',
confirm_enforce: false,
}),
[config],
);
const loadUsers = useCallback(async (keyword = '') => {
try {
const response = await API.get('/api/content-guard/users', {
params: { keyword, limit: 100 },
});
if (response.data.success) setUsers(response.data.data || []);
} catch (error) {
showError(errorMessage(error));
}
}, []);
const loadLogs = async (page = 1, size = logs.size || 20) => {
try {
const response = await API.get('/api/content-guard/logs', {
params: { page, size },
});
if (response.data.success) {
setLogs(response.data.data || { items: [], total: 0, page, size });
}
} catch (error) {
showError(errorMessage(error));
}
};
const loadAll = useCallback(async () => {
setLoading(true);
try {
const [configRes, groupsRes, metricsRes, decommissionRes, logsRes] =
await Promise.all([
API.get('/api/content-guard/config'),
API.get('/api/content-guard/groups'),
API.get('/api/content-guard/metrics', { params: { hours: 24 } }),
API.get('/api/content-guard/decommission'),
API.get('/api/content-guard/logs', { params: { page: 1, size: 20 } }),
]);
const nextConfig = configRes.data.data || DEFAULT_CONFIG;
setConfig(nextConfig);
setIsEnforceMode(nextConfig.mode === 'enforce');
setGroups(groupsRes.data.data || []);
setMetrics(metricsRes.data.data || {});
setDecommission(decommissionRes.data.data || null);
setLogs(logsRes.data.data || { items: [], total: 0, page: 1, size: 20 });
await loadUsers();
setTimeout(
() =>
formApi.current?.setValues({
...DEFAULT_CONFIG,
...nextConfig,
api_key: '',
}),
0,
);
} catch (error) {
showError(errorMessage(error));
} finally {
setLoading(false);
}
}, [loadUsers]);
useEffect(() => {
loadAll();
}, [loadAll]);
const handleModeChange = (event) => {
const mode = event?.target?.value;
setIsEnforceMode(mode === 'enforce');
if (mode === 'enforce') {
formApi.current?.setValues(
Object.fromEntries(ENFORCE_CHECK_FIELDS.map((field) => [field, true])),
);
}
};
const saveConfig = async (values) => {
const normalized = normalizeContentGuardConfig(values);
if (
normalized.enabled &&
normalized.mode === 'enforce' &&
!normalized.confirm_enforce
) {
showError(t('启用强制阻断模式前,请勾选风险确认'));
return;
}
setSaving(true);
try {
const response = await API.put('/api/content-guard/config', {
...normalized,
provider: 'uguard',
expected_version: config.version,
api_key: normalized.api_key || '',
});
if (!response.data.success) throw new Error(response.data.message);
const result = response.data.data;
setConfig(result.config);
formApi.current?.setValue('api_key', '');
if (result.activation_pending) {
showSuccess(
t('异步发布门禁已建立。节点确认完成后,请再次保存以正式启用。'),
);
} else {
showSuccess(t('防护配置已保存'));
}
await loadAll();
} catch (error) {
showError(errorMessage(error));
} finally {
setSaving(false);
}
};
const testPermission = async (kind) => {
try {
const response = await API.post('/api/content-guard/test', { kind });
const result = response.data.data;
showSuccess(`${kind}: ${result.safety}, ${result.latency_ms} ms`);
} catch (error) {
showError(errorMessage(error));
}
};
const setKillSwitch = async (disabled) => {
if (!killReason.trim()) {
showError(t('请填写操作原因'));
return;
}
try {
await API.post('/api/content-guard/kill-switch', {
expected_version: config.version,
disabled,
reason: killReason.trim(),
});
showSuccess(disabled ? t('已紧急关闭') : t('已解除紧急关闭'));
setKillReason('');
await loadAll();
} catch (error) {
showError(errorMessage(error));
}
};
const startDecommission = () => {
let confirmText = '';
Modal.confirm({
title: t('开始永久下线清算'),
content: (
<div>
<p>{t('此操作会立即停止新防护判定,并处理所有历史异步资源。')}</p>
<Input
placeholder='DECOMMISSION CONTENT GUARD'
onChange={(value) => (confirmText = value)}
/>
</div>
),
onOk: async () => {
if (confirmText !== 'DECOMMISSION CONTENT GUARD') {
showError(t('确认短语不正确'));
return Promise.reject();
}
await API.post('/api/content-guard/decommission/start', {
expected_version: config.version,
policy: 'block_unknown',
inflight_action: 'wait',
confirm: true,
});
await loadAll();
},
});
};
const completeDecommission = async () => {
try {
await API.post('/api/content-guard/decommission/complete', {
expected_version: decommission?.version,
confirm: 'DECOMMISSION CONTENT GUARD',
});
showSuccess(t('防护模块已永久下线,密钥和范围配置已清除'));
await loadAll();
} catch (error) {
showError(errorMessage(error));
}
};
const cancelDecommission = () => {
let reason = '';
Modal.confirm({
title: t('取消永久下线清算'),
content: (
<Input
placeholder={t('填写取消原因')}
onChange={(value) => (reason = value)}
/>
),
onOk: async () => {
if (!reason.trim()) {
showError(t('请填写取消原因'));
return Promise.reject();
}
await API.post('/api/content-guard/decommission/cancel', {
expected_version: decommission?.version,
reason: reason.trim(),
});
showSuccess(t('清算已取消;防护仍保持紧急关闭和未启用状态'));
await loadAll();
},
});
};
const auditColumns = [
{
title: t('时间'),
dataIndex: 'created_at',
render: (v) => new Date(v).toLocaleString(),
},
{ title: t('用户'), dataIndex: 'user_id', width: 80 },
{ title: t('分组'), dataIndex: 'using_group' },
{ title: t('模型'), dataIndex: 'model' },
{ title: t('方向'), dataIndex: 'direction' },
{ title: t('类型'), dataIndex: 'content_type' },
{
title: t('结果'),
dataIndex: 'safety',
render: (value) => (
<Tag
color={
value === '合规' ? 'green' : value === '违规' ? 'red' : 'orange'
}
>
{value || '-'}
</Tag>
),
},
{ title: t('动作'), dataIndex: 'action' },
{
title: t('耗时'),
dataIndex: 'latency_ms',
render: (v) => `${v || 0} ms`,
},
{ title: t('错误码'), dataIndex: 'error_code' },
];
if (loading) {
return <Spin spinning style={{ display: 'block', margin: '80px auto' }} />;
}
return (
<div style={{ padding: 20 }}>
<Space vertical align='start' spacing='medium' style={{ width: '100%' }}>
<Banner
fullMode={false}
type={config.available && config.schema_ready ? 'info' : 'warning'}
description={
config.available && config.schema_ready
? t(
'UGuard 仅作用于同时命中用户和实际调用分组的请求。未命中请求不会调用防护服务。',
)
: t('运行环境或数据库迁移尚未允许启用内容防护。')
}
/>
<Card style={{ width: '100%' }}>
<Space style={{ justifyContent: 'space-between', width: '100%' }}>
<Space>
<ShieldAlert size={20} />
<Typography.Title heading={4} style={{ margin: 0 }}>
{t('大模型内容防护')}
</Typography.Title>
{statusTag(config, t)}
</Space>
<Button
icon={<RefreshCw size={16} />}
onClick={loadAll}
aria-label={t('刷新')}
/>
</Space>
<Descriptions
row
size='small'
data={[
{ key: t('配置版本'), value: config.version },
{
key: t('节点确认'),
value: `${config.acknowledged_nodes}/${config.expected_nodes}`,
},
{
key: t('API Key'),
value: config.api_key_configured
? `****${config.api_key_suffix}`
: t('未配置'),
},
{ key: t('24小时检测'), value: metrics.total || 0 },
{ key: t('24小时阻断'), value: metrics.blocked || 0 },
]}
/>
</Card>
<Tabs type='line' style={{ width: '100%' }}>
<TabPane tab={t('配置')} itemKey='config'>
<Form
key={config.version}
initValues={formValues}
getFormApi={(api) => (formApi.current = api)}
onSubmit={saveConfig}
labelPosition='top'
>
<Card title={t('连接与生效范围')}>
<div className='grid grid-cols-1 gap-3 md:grid-cols-2'>
<Form.Switch field='enabled' label={t('启用内容防护')} />
<Form.RadioGroup
field='mode'
label={t('运行模式')}
onChange={handleModeChange}
options={[
{ label: t('观察'), value: 'observe' },
{ label: t('强制阻断'), value: 'enforce' },
]}
/>
<Form.Input
field='base_url'
label='Base URL'
placeholder='http://uguard.example.com'
/>
<Form.Input
field='api_key'
mode='password'
label='API Key'
placeholder={
config.api_key_configured
? t('留空保持当前密钥')
: t('请输入密钥')
}
/>
<Form.Select
field='groups'
label={t('启用分组')}
multiple
filter
optionList={groups.map((group) => ({
label: group,
value: group,
}))}
/>
<Form.Select
field='user_ids'
label={t('启用用户')}
multiple
filter
remote
onSearch={(value) => {
setUserKeyword(value);
loadUsers(value);
}}
optionList={users.map((user) => ({
value: user.id,
label: `${user.display_name || user.username} (#${user.id})`,
}))}
emptyContent={
userKeyword
? t('没有匹配用户')
: t('输入用户名或邮箱搜索')
}
/>
</div>
<Space wrap>
<Form.Switch
field='input_enabled'
label={t('检测输入')}
disabled={isEnforceMode}
/>
<Form.Switch
field='output_enabled'
label={t('检测输出')}
disabled={isEnforceMode}
/>
<Form.Switch
field='text_enabled'
label={t('文本')}
disabled={isEnforceMode}
/>
<Form.Switch
field='image_enabled'
label={t('图片')}
disabled={isEnforceMode}
/>
<Form.Switch
field='video_enabled'
label={t('视频')}
disabled={isEnforceMode}
/>
</Space>
<Form.Checkbox field='confirm_enforce'>
{t(
'我确认强制模式会在 UGuard 不可用、疑似、违规或未识别时拒绝命中请求',
)}
</Form.Checkbox>
</Card>
<Card title={t('性能与容量')} style={{ marginTop: 12 }}>
<div className='grid grid-cols-1 gap-3 md:grid-cols-3'>
{[
['text_timeout_ms', '文本超时(ms)'],
['image_timeout_ms', '图片超时(ms)'],
['video_timeout_ms', '视频超时(ms)'],
['text_concurrency', '文本并发'],
['image_concurrency', '图片并发'],
['video_concurrency', '视频并发'],
['text_cluster_qps', '文本集群QPS'],
['image_cluster_qps', '图片集群QPS'],
['video_cluster_qps', '视频集群QPS'],
['observe_queue_size', '观察队列'],
['observe_workers', '观察任务数'],
['stream_memory_threshold_bytes', '响应内存阈值(bytes)'],
['stream_response_cap_bytes', '单响应上限(bytes)'],
['stream_spool_cap_bytes', '响应临时空间预算(bytes)'],
['image_temp_cap_bytes', '图片临时空间预算(bytes)'],
['video_temp_cap_bytes', '视频临时空间预算(bytes)'],
].map(([field, label]) => (
<Form.InputNumber
key={field}
field={field}
label={t(label)}
min={1}
style={{ width: '100%' }}
/>
))}
</div>
<Descriptions
row
size='small'
style={{ marginTop: 12 }}
data={[
{
key: t('文本并发'),
value: `${metrics.runtime?.text_inflight || 0}/${metrics.runtime?.text_concurrency || 0}`,
},
{
key: t('图片并发'),
value: `${metrics.runtime?.image_inflight || 0}/${metrics.runtime?.image_concurrency || 0}`,
},
{
key: t('视频并发'),
value: `${metrics.runtime?.video_inflight || 0}/${metrics.runtime?.video_concurrency || 0}`,
},
{
key: t('观察队列'),
value: `${metrics.runtime?.observe_queue_depth || 0}/${metrics.runtime?.observe_queue_capacity || 0}`,
},
{
key: t('审计队列'),
value: `${metrics.runtime?.audit_queue_depth || 0}/${metrics.runtime?.audit_queue_capacity || 0}`,
},
{
key: t('审计丢弃'),
value: metrics.runtime?.audit_dropped || 0,
},
{
key: t('响应临时空间'),
value: `${metrics.runtime?.stream_temporary_bytes || 0} bytes`,
},
{
key: t('媒体临时空间'),
value: `${(metrics.runtime?.image_temporary_bytes || 0) + (metrics.runtime?.video_temporary_bytes || 0)} bytes`,
},
]}
/>
</Card>
<Space style={{ marginTop: 16 }}>
<Button
htmlType='submit'
type='primary'
loading={saving}
icon={<Save size={16} />}
>
{t('保存配置')}
</Button>
<Button
icon={<TestTube2 size={16} />}
onClick={() => testPermission('moderate')}
>
moderate
</Button>
<Button
icon={<TestTube2 size={16} />}
onClick={() => testPermission('stream_moderate')}
>
stream_moderate
</Button>
</Space>
</Form>
<Card title={t('紧急熔断')} style={{ marginTop: 12 }}>
<Space wrap>
<Input
value={killReason}
onChange={setKillReason}
placeholder={t('填写操作原因')}
style={{ width: 360, maxWidth: '100%' }}
/>
<Button type='danger' onClick={() => setKillSwitch(true)}>
{t('立即关闭')}
</Button>
<Button
disabled={!config.emergency_disabled}
onClick={() => setKillSwitch(false)}
>
{t('解除关闭')}
</Button>
</Space>
</Card>
</TabPane>
<TabPane tab={t('审计')} itemKey='audit'>
<Table
rowKey='id'
columns={auditColumns}
dataSource={logs.items || []}
scroll={{ x: 'max-content' }}
pagination={{
total: logs.total || 0,
pageSize: logs.size || 20,
currentPage: logs.page || 1,
showTotal: true,
onPageChange: (page) => loadLogs(page, logs.size || 20),
onPageSizeChange: (size) => loadLogs(1, size),
}}
/>
</TabPane>
<TabPane tab={t('永久下线')} itemKey='decommission'>
<Banner
fullMode={false}
type='warning'
description={t(
'永久下线用于未来彻底移除 UGuard。清算完成前,历史异步资源门禁不会被跳过。',
)}
/>
<Card style={{ marginTop: 12 }}>
<Descriptions
row
data={[
{
key: t('生命周期'),
value: decommission?.lifecycle_state || '-',
},
{ key: t('清算代次'), value: decommission?.generation || 0 },
{
key: t('活动租约'),
value: decommission?.active_leases || 0,
},
{
key: t('临时空间占用'),
value: `${decommission?.temporary_bytes || 0} bytes`,
},
{
key: t('清算动作'),
value: decommission?.retirement_actions || 0,
},
{
key: t('完成条件'),
value: decommission?.readiness ? t('已满足') : t('未满足'),
},
]}
/>
{!!decommission?.blocking_reasons?.length && (
<Banner
type='warning'
description={decommission.blocking_reasons.join(', ')}
/>
)}
<Space style={{ marginTop: 16 }}>
<Button
type='danger'
disabled={config.lifecycle_state !== 'active'}
onClick={startDecommission}
>
{t('开始清算')}
</Button>
<Button
disabled={
config.lifecycle_state !== 'draining' ||
!decommission?.cancel_allowed
}
onClick={cancelDecommission}
>
{t('取消清算')}
</Button>
<Button
type='danger'
disabled={
!decommission?.readiness ||
config.lifecycle_state !== 'draining'
}
onClick={completeDecommission}
>
{t('完成永久下线')}
</Button>
</Space>
</Card>
</TabPane>
</Tabs>
</Space>
</div>
);
}
@@ -0,0 +1,596 @@
/*
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, useCallback } from 'react';
import {
Card,
Table,
Button,
Modal,
Form,
Select,
Tag,
Avatar,
Popconfirm,
Typography,
Space,
Banner,
Spin,
Upload,
} from '@douyinfe/semi-ui';
import {
Plus,
Pencil,
Trash2,
Power,
PowerOff,
RefreshCw,
Users,
Headphones,
Upload as UploadIcon,
} from 'lucide-react';
import { API, showError, showSuccess } from '../../helpers';
import { useTranslation } from 'react-i18next';
const { Text } = Typography;
const CustomerServiceSetting = () => {
const { t } = useTranslation();
const [agents, setAgents] = useState([]);
const [loading, setLoading] = useState(false);
const [modalVisible, setModalVisible] = useState(false);
const [editingAgent, setEditingAgent] = useState(null);
const [formApi, setFormApi] = useState(null);
const [uploadingQrcode, setUploadingQrcode] = useState(false);
const [uploadingAvatar, setUploadingAvatar] = useState(false);
// 上传图片
const handleUpload = async (fileInfo, field) => {
const setUploading =
field === 'qrcode_url' ? setUploadingQrcode : setUploadingAvatar;
setUploading(true);
try {
const formData = new FormData();
// Semi UI 的 customRequest 回调中,fileInfo.fileInstance 是原始 File 对象
const file = fileInfo.fileInstance || fileInfo.file;
formData.append('file', file);
const res = await API.post('/api/customer-service/upload', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
if (res.data.success && res.data.data?.url) {
formApi?.setValue(field, res.data.data.url);
showSuccess(t('上传成功'));
fileInfo.onSuccess?.();
} else {
showError(res.data.message || t('上传失败'));
fileInfo.onError?.();
}
} catch (err) {
showError(t('上传失败'));
fileInfo.onError?.();
} finally {
setUploading(false);
}
};
// 工作日选项
const workDayOptions = [
{ label: t('周一'), value: '1' },
{ label: t('周二'), value: '2' },
{ label: t('周三'), value: '3' },
{ label: t('周四'), value: '4' },
{ label: t('周五'), value: '5' },
{ label: t('周六'), value: '6' },
{ label: t('周日'), value: '7' },
];
// 获取客服列表
const fetchAgents = useCallback(async () => {
setLoading(true);
try {
const res = await API.get('/api/customer-service/');
if (res.data.success) {
setAgents(res.data.data || []);
} else {
showError(res.data.message);
}
} catch (err) {
showError(t('获取客服列表失败'));
} finally {
setLoading(false);
}
}, [t]);
useEffect(() => {
fetchAgents();
}, [fetchAgents]);
// 打开新建/编辑弹窗
const openModal = (agent = null) => {
setEditingAgent(agent);
setModalVisible(true);
};
// 关闭弹窗
const closeModal = () => {
setModalVisible(false);
setEditingAgent(null);
if (formApi) {
formApi.reset();
}
};
// 提交表单
const handleSubmit = async () => {
if (!formApi) return;
try {
await formApi.validate();
const values = formApi.getValues();
// 处理工作日
const workDays = Array.isArray(values.work_days)
? values.work_days.join(',')
: values.work_days || '1,2,3,4,5';
// 处理工作时间(Form.Input 返回字符串,直接使用)
const workStartTime = values.work_start_time || '';
const workEndTime = values.work_end_time || '';
const payload = {
...values,
work_days: workDays,
work_start_time: workStartTime,
work_end_time: workEndTime,
weight: values.weight || 100,
max_sessions: values.max_sessions || 50,
priority: values.priority || 0,
status: values.status ?? 1,
};
if (editingAgent) {
payload.id = editingAgent.id;
const res = await API.put('/api/customer-service/', payload);
if (res.data.success) {
showSuccess(t('更新成功'));
closeModal();
fetchAgents();
} else {
showError(res.data.message);
}
} else {
const res = await API.post('/api/customer-service/', payload);
if (res.data.success) {
showSuccess(t('创建成功'));
closeModal();
fetchAgents();
} else {
showError(res.data.message);
}
}
} catch (err) {
// 表单验证失败或其他错误
if (err && err.message) {
showError(err.message);
}
}
};
// 删除客服
const handleDelete = async (id) => {
try {
const res = await API.delete(`/api/customer-service/${id}`);
if (res.data.success) {
showSuccess(t('删除成功'));
fetchAgents();
} else {
showError(res.data.message);
}
} catch (err) {
showError(t('删除失败'));
}
};
// 切换状态
const handleToggleStatus = async (agent) => {
const newStatus = agent.status === 1 ? 0 : 1;
try {
const res = await API.put(`/api/customer-service/${agent.id}/status`, {
status: newStatus,
});
if (res.data.success) {
showSuccess(newStatus === 1 ? t('已上线') : t('已下线'));
fetchAgents();
} else {
showError(res.data.message);
}
} catch (err) {
showError(t('操作失败'));
}
};
// 状态标签
const getStatusTag = (status) => {
const statusMap = {
1: { text: t('在线'), color: 'green' },
2: { text: t('忙碌'), color: 'orange' },
0: { text: t('离线'), color: 'grey' },
};
const s = statusMap[status] || statusMap[0];
return <Tag color={s.color}>{s.text}</Tag>;
};
// 表格列定义
const columns = [
{
title: t('客服'),
dataIndex: 'name',
render: (text, record) => (
<Space>
<Avatar
src={record.avatar}
size='small'
style={{ backgroundColor: '#87d068' }}
>
{text?.[0]?.toUpperCase()}
</Avatar>
<Text strong>{text}</Text>
</Space>
),
},
{
title: t('状态'),
dataIndex: 'status',
render: (status) => getStatusTag(status),
},
{
title: t('接待数'),
dataIndex: 'current_sessions',
render: (current, record) => (
<Text>
{current} / {record.max_sessions}
</Text>
),
},
{
title: t('权重'),
dataIndex: 'weight',
},
{
title: t('优先级'),
dataIndex: 'priority',
},
{
title: t('工作时间'),
dataIndex: 'work_start_time',
render: (start, record) => {
if (start && record.work_end_time) {
return `${start} - ${record.work_end_time}`;
}
return t('全天');
},
},
{
title: t('工作日'),
dataIndex: 'work_days',
render: (days) => {
if (!days) return t('工作日');
const dayNames = {
1: t('一'),
2: t('二'),
3: t('三'),
4: t('四'),
5: t('五'),
6: t('六'),
7: t('日'),
};
return days
.split(',')
.map((d) => dayNames[d] || d)
.join('、');
},
},
{
title: t('操作'),
dataIndex: 'action',
render: (_, record) => (
<Space>
<Button
icon={
record.status === 1 ? <PowerOff size={14} /> : <Power size={14} />
}
size='small'
type={record.status === 1 ? 'danger' : 'primary'}
onClick={() => handleToggleStatus(record)}
>
{record.status === 1 ? t('下线') : t('上线')}
</Button>
<Button
icon={<Pencil size={14} />}
size='small'
onClick={() => openModal(record)}
>
{t('编辑')}
</Button>
<Popconfirm
title={t('确认删除')}
content={t('确定要删除这个客服吗?')}
onConfirm={() => handleDelete(record.id)}
>
<Button icon={<Trash2 size={14} />} size='small' type='danger'>
{t('删除')}
</Button>
</Popconfirm>
</Space>
),
},
];
// 初始表单值
const getInitialValues = () => {
if (editingAgent) {
return {
...editingAgent,
work_days: editingAgent.work_days
? editingAgent.work_days.split(',')
: ['1', '2', '3', '4', '5'],
};
}
return {
status: 1,
weight: 100,
max_sessions: 50,
priority: 0,
work_days: ['1', '2', '3', '4', '5'],
};
};
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
<Card>
<div style={{ marginBottom: 16 }}>
<Banner
type='info'
icon={<Headphones size={16} />}
description={t(
'配置企业微信客服,支持多客服轮询、加权分配、最少接待等策略。客服链接可在企业微信管理后台的「微信客服」中获取。',
)}
/>
</div>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
marginBottom: 16,
}}
>
<Space>
<Users size={20} />
<Text strong style={{ fontSize: 16 }}>
{t('客服列表')}
</Text>
<Tag color='blue'>
{agents.length} {t('个客服')}
</Tag>
</Space>
<Space>
<Button
icon={<RefreshCw size={14} />}
onClick={fetchAgents}
loading={loading}
>
{t('刷新')}
</Button>
<Button
icon={<Plus size={14} />}
type='primary'
onClick={() => openModal()}
>
{t('添加客服')}
</Button>
</Space>
</div>
<Spin spinning={loading}>
<Table
columns={columns}
dataSource={agents}
rowKey='id'
pagination={false}
empty={t('暂无客服,请点击「添加客服」创建')}
/>
</Spin>
</Card>
{/* 新建/编辑弹窗 */}
<Modal
title={editingAgent ? t('编辑客服') : t('添加客服')}
visible={modalVisible}
onOk={handleSubmit}
onCancel={closeModal}
okText={t('保存')}
cancelText={t('取消')}
width={600}
>
<Form
getFormApi={(api) => setFormApi(api)}
initValues={getInitialValues()}
labelPosition='left'
labelWidth={100}
>
<Form.Input
field='name'
label={t('客服名称')}
placeholder={t('请输入客服名称')}
rules={[{ required: true, message: t('请输入客服名称') }]}
/>
<Form.Slot label={t('头像')}>
<div style={{ display: 'flex', gap: 8, alignItems: 'flex-start' }}>
<Form.Input
field='avatar'
noLabel
placeholder={t('图片链接或点击上传')}
style={{ flex: 1 }}
/>
<Upload
accept='image/*'
showUploadList={false}
customRequest={(fileInfo) => handleUpload(fileInfo, 'avatar')}
>
<Button
icon={<UploadIcon size={14} />}
loading={uploadingAvatar}
>
{t('上传')}
</Button>
</Upload>
</div>
</Form.Slot>
<Form.TextArea
field='wecom_url'
label={t('客服链接')}
placeholder={t('请输入企业微信客服链接')}
autosize={{ minRows: 2, maxRows: 4 }}
/>
<Form.Slot label={t('二维码')}>
<div
style={{
display: 'flex',
gap: 8,
alignItems: 'flex-start',
flexDirection: 'column',
}}
>
<div style={{ display: 'flex', gap: 8, width: '100%' }}>
<Form.Input
field='qrcode_url'
noLabel
placeholder={t('图片链接或点击上传')}
style={{ flex: 1 }}
/>
<Upload
accept='image/*'
showUploadList={false}
customRequest={(fileInfo) =>
handleUpload(fileInfo, 'qrcode_url')
}
>
<Button
icon={<UploadIcon size={14} />}
loading={uploadingQrcode}
>
{t('上传')}
</Button>
</Upload>
</div>
{formApi?.getValue('qrcode_url') && (
<img
src={formApi.getValue('qrcode_url')}
alt={t('二维码预览')}
style={{
maxWidth: 120,
maxHeight: 120,
borderRadius: 4,
border: '1px solid var(--semi-color-border)',
}}
/>
)}
</div>
</Form.Slot>
<Form.InputNumber
field='weight'
label={t('权重')}
placeholder='100'
min={0}
max={1000}
style={{ width: '100%' }}
extraText={t('权重越高,被分配的概率越大')}
/>
<Form.InputNumber
field='max_sessions'
label={t('最大接待数')}
placeholder='50'
min={1}
max={1000}
style={{ width: '100%' }}
extraText={t('达到最大接待数后将不再分配新用户')}
/>
<Form.InputNumber
field='priority'
label={t('优先级')}
placeholder='0'
min={0}
max={100}
style={{ width: '100%' }}
extraText={t('优先级越高,在优先级策略下优先分配')}
/>
<Form.Select
field='status'
label={t('状态')}
style={{ width: '100%' }}
>
<Select.Option value={1}>{t('在线')}</Select.Option>
<Select.Option value={2}>{t('忙碌')}</Select.Option>
<Select.Option value={0}>{t('离线')}</Select.Option>
</Form.Select>
<Form.CheckboxGroup
field='work_days'
label={t('工作日')}
options={workDayOptions}
direction='horizontal'
/>
<Form.Input
field='work_start_time'
label={t('上班时间')}
placeholder='09:00'
extraText={t('留空表示全天在线,格式:HH:MM')}
/>
<Form.Input
field='work_end_time'
label={t('下班时间')}
placeholder='18:00'
extraText={t('留空表示全天在线,格式:HH:MM')}
/>
<Form.TextArea
field='description'
label={t('描述')}
placeholder={t('请输入客服描述(可选)')}
autosize={{ minRows: 2, maxRows: 4 }}
/>
</Form>
</Modal>
</div>
);
};
export default CustomerServiceSetting;
@@ -0,0 +1,177 @@
/*
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, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Card, Spin, Modal } from '@douyinfe/semi-ui';
import { API, showError, showSuccess, toBoolean } from '../../helpers';
import SettingsAPIInfo from '../../pages/Setting/Dashboard/SettingsAPIInfo';
import SettingsAnnouncements from '../../pages/Setting/Dashboard/SettingsAnnouncements';
import SettingsFAQ from '../../pages/Setting/Dashboard/SettingsFAQ';
import SettingsUptimeKuma from '../../pages/Setting/Dashboard/SettingsUptimeKuma';
import SettingsDataDashboard from '../../pages/Setting/Dashboard/SettingsDataDashboard';
const DashboardSetting = () => {
const { t } = useTranslation();
let [inputs, setInputs] = useState({
'console_setting.api_info': '',
'console_setting.announcements': '',
'console_setting.faq': '',
'console_setting.uptime_kuma_groups': '',
'console_setting.api_info_enabled': '',
'console_setting.announcements_enabled': '',
'console_setting.faq_enabled': '',
'console_setting.uptime_kuma_enabled': '',
// 用于迁移检测的旧键,下个版本会删除
ApiInfo: '',
Announcements: '',
FAQ: '',
UptimeKumaUrl: '',
UptimeKumaSlug: '',
/* 数据看板 */
DataExportEnabled: false,
DataExportDefaultTime: 'hour',
DataExportInterval: 5,
});
let [loading, setLoading] = useState(false);
const [showMigrateModal, setShowMigrateModal] = useState(false); // 下个版本会删除
const getOptions = async () => {
const res = await API.get('/api/option/');
const { success, message, data } = res.data;
if (success) {
let newInputs = {};
data.forEach((item) => {
if (item.key in inputs) {
newInputs[item.key] = item.value;
}
if (item.key.endsWith('Enabled') && item.key === 'DataExportEnabled') {
newInputs[item.key] = toBoolean(item.value);
}
});
setInputs(newInputs);
} else {
showError(message);
}
};
async function onRefresh() {
try {
setLoading(true);
await getOptions();
} catch (error) {
showError(t('刷新失败'));
console.error(error);
} finally {
setLoading(false);
}
}
useEffect(() => {
onRefresh();
}, []);
// 用于迁移检测的旧键,下个版本会删除
const hasLegacyData = useMemo(() => {
const legacyKeys = [
'ApiInfo',
'Announcements',
'FAQ',
'UptimeKumaUrl',
'UptimeKumaSlug',
];
return legacyKeys.some((k) => inputs[k]);
}, [inputs]);
useEffect(() => {
if (hasLegacyData) {
setShowMigrateModal(true);
}
}, [hasLegacyData]);
const handleMigrate = async () => {
try {
setLoading(true);
await API.post('/api/option/migrate_console_setting');
showSuccess(t('旧配置迁移完成'));
await onRefresh();
setShowMigrateModal(false);
} catch (err) {
console.error(err);
showError(t('迁移失败: ') + (err.message || t('未知错误')));
} finally {
setLoading(false);
}
};
return (
<>
<Spin spinning={loading} size='large'>
{/* 用于迁移检测的旧键模态框,下个版本会删除 */}
<Modal
title={t('配置迁移确认')}
visible={showMigrateModal}
onOk={handleMigrate}
onCancel={() => setShowMigrateModal(false)}
confirmLoading={loading}
okText={t('确认迁移')}
cancelText={t('取消')}
>
<p>{t('检测到旧版本的配置数据,是否要迁移到新的配置格式?')}</p>
<p style={{ color: '#f57c00', marginTop: '10px' }}>
<strong>{t('注意:')}</strong>
{t(
'迁移过程中会自动处理数据格式转换,迁移完成后旧配置将被清除,请在迁移前在数据库中备份好旧配置。',
)}
</p>
</Modal>
{/* 数据看板设置 */}
<Card style={{ marginTop: '10px' }}>
<SettingsDataDashboard options={inputs} refresh={onRefresh} />
</Card>
{/* 系统公告管理 */}
<Card style={{ marginTop: '10px' }}>
<SettingsAnnouncements options={inputs} refresh={onRefresh} />
</Card>
{/* API信息管理 */}
<Card style={{ marginTop: '10px' }}>
<SettingsAPIInfo options={inputs} refresh={onRefresh} />
</Card>
{/* 常见问答管理 */}
<Card style={{ marginTop: '10px' }}>
<SettingsFAQ options={inputs} refresh={onRefresh} />
</Card>
{/* Uptime Kuma 监控设置 */}
<Card style={{ marginTop: '10px' }}>
<SettingsUptimeKuma options={inputs} refresh={onRefresh} />
</Card>
</Spin>
</>
);
};
export default DashboardSetting;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,84 @@
/*
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 { Card, Spin } from '@douyinfe/semi-ui';
import SettingsDrawing from '../../pages/Setting/Drawing/SettingsDrawing';
import { API, showError, toBoolean } from '../../helpers';
const DrawingSetting = () => {
let [inputs, setInputs] = useState({
/* 绘图设置 */
DrawingEnabled: false,
MjNotifyEnabled: false,
MjAccountFilterEnabled: false,
MjForwardUrlEnabled: false,
MjModeClearEnabled: false,
MjActionCheckSuccessEnabled: false,
});
let [loading, setLoading] = useState(false);
const getOptions = async () => {
const res = await API.get('/api/option/');
const { success, message, data } = res.data;
if (success) {
let newInputs = {};
data.forEach((item) => {
if (item.key.endsWith('Enabled')) {
newInputs[item.key] = toBoolean(item.value);
} else {
newInputs[item.key] = item.value;
}
});
setInputs(newInputs);
} else {
showError(message);
}
};
async function onRefresh() {
try {
setLoading(true);
await getOptions();
} catch (error) {
showError('刷新失败');
} finally {
setLoading(false);
}
}
useEffect(() => {
onRefresh();
}, []);
return (
<>
<Spin spinning={loading} size='large'>
{/* 绘图设置 */}
<Card style={{ marginTop: '10px' }}>
<SettingsDrawing options={inputs} refresh={onRefresh} />
</Card>
</Spin>
</>
);
};
export default DrawingSetting;
@@ -0,0 +1,18 @@
/* 等级与模型访问(level_policy)局部布局覆盖,全部只改尺寸不改配色 */
/* scroll.x 表格的 min-width:100% 铺满兜底已全局化到 index.css(.semi-table table),
此处不再重复。 */
/* 默认访问态 pureCard 单选:两张卡等分弹窗整行宽,避免随文案长短一宽一窄 */
.semi-radioGroup.level-access-radio {
display: flex;
width: 100%;
gap: 12px;
}
/* 三段类选择器压过 semi 自带的 .semi-radioGroup-horizontal .semi-radio 边距规则,
不依赖打包时的 CSS 先后顺序 */
.semi-radioGroup.level-access-radio .semi-radio {
flex: 1 1 0;
margin-right: 0;
min-width: 0;
}
File diff suppressed because it is too large Load Diff
+137
View File
@@ -0,0 +1,137 @@
/*
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 { Card, Spin } from '@douyinfe/semi-ui';
import { API, showError, toBoolean } from '../../helpers';
import { useTranslation } from 'react-i18next';
import SettingGeminiModel from '../../pages/Setting/Model/SettingGeminiModel';
import SettingClaudeModel from '../../pages/Setting/Model/SettingClaudeModel';
import SettingGlobalModel from '../../pages/Setting/Model/SettingGlobalModel';
import SettingModelCategory from '../../pages/Setting/Model/SettingModelCategory';
import SettingVideoModel from '../../pages/Setting/Model/SettingVideoModel';
import SettingImagePricing from '../../pages/Setting/Model/SettingImagePricing';
const ModelSetting = () => {
const { t: _t } = useTranslation();
let [inputs, setInputs] = useState({
'gemini.safety_settings': '',
'gemini.version_settings': '',
'gemini.supported_imagine_models': '',
'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,
'global.pass_through_request_enabled': false,
'global.thinking_model_blacklist': '[]',
'general_setting.ping_interval_enabled': false,
'general_setting.ping_interval_seconds': 60,
'gemini.thinking_adapter_enabled': false,
'gemini.thinking_adapter_budget_tokens_percentage': 0.6,
'video.custom_video_models': '[]',
'video.video_second_pricing': '[]',
'image.image_resolution_pricing': '[]',
});
let [loading, setLoading] = useState(false);
const getOptions = async () => {
const res = await API.get('/api/option/');
const { success, message, data } = res.data;
if (success) {
let newInputs = {};
data.forEach((item) => {
if (
item.key === 'gemini.safety_settings' ||
item.key === 'gemini.version_settings' ||
item.key === 'claude.model_headers_settings' ||
item.key === 'claude.default_max_tokens' ||
item.key === 'gemini.supported_imagine_models' ||
item.key === 'global.thinking_model_blacklist' ||
item.key === 'video.custom_video_models'
) {
if (item.value !== '') {
item.value = JSON.stringify(JSON.parse(item.value), null, 2);
}
}
if (item.key.endsWith('Enabled') || item.key.endsWith('enabled')) {
newInputs[item.key] = toBoolean(item.value);
} else {
newInputs[item.key] = item.value;
}
});
setInputs(newInputs);
} else {
showError(message);
}
};
async function onRefresh() {
try {
setLoading(true);
await getOptions();
// showSuccess('刷新成功');
} catch (error) {
showError('刷新失败');
console.error(error);
} finally {
setLoading(false);
}
}
useEffect(() => {
onRefresh();
}, []);
return (
<>
<Spin spinning={loading} size='large'>
{/* 模型分类管理 */}
<Card style={{ marginTop: '10px' }}>
<SettingModelCategory />
</Card>
{/* OpenAI */}
<Card style={{ marginTop: '10px' }}>
<SettingGlobalModel options={inputs} refresh={onRefresh} />
</Card>
{/* Gemini */}
<Card style={{ marginTop: '10px' }}>
<SettingGeminiModel options={inputs} refresh={onRefresh} />
</Card>
{/* Claude */}
<Card style={{ marginTop: '10px' }}>
<SettingClaudeModel options={inputs} refresh={onRefresh} />
</Card>
{/* Image pricing */}
<Card style={{ marginTop: '10px' }}>
<SettingImagePricing options={inputs} refresh={onRefresh} />
</Card>
{/* Video */}
<Card style={{ marginTop: '10px' }}>
<SettingVideoModel options={inputs} refresh={onRefresh} />
</Card>
</Spin>
</>
);
};
export default ModelSetting;
@@ -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 from 'react';
import { useTranslation } from 'react-i18next';
import { Input, InputNumber, Select } from '@douyinfe/semi-ui';
/**
* 通用通知渠道表单(受控组件)。按后端 dto.UserSetting 的通知子集工作,
* 支持 email / webhook / bark / gotify 四渠道。企业「通知预警」等场景复用。
*
* props:
* value: {
* notify_type, notification_email,
* webhook_url, webhook_secret,
* bark_url,
* gotify_url, gotify_token, gotify_priority
* }
* onChange(nextValue): 整对象回传
* disabled?: boolean
* channels?: 可选渠道白名单(如 ['email','webhook']),默认全部四种。
* 成员个人预警场景仅开放邮箱/Webhook。
* emailPlaceholder?: 通知邮箱输入框占位文案。默认"留空则使用企业联系邮箱"
* 是企业级预警的兜底语义;成员场景没有该兜底,须传入"必填"提示。
*/
const ALL_CHANNELS = ['email', 'webhook', 'bark', 'gotify'];
const NotifyChannelForm = ({
value = {},
onChange,
disabled = false,
channels,
emailPlaceholder,
}) => {
const { t } = useTranslation();
const v = value || {};
const allowed = ALL_CHANNELS.filter(
(c) => !Array.isArray(channels) || channels.includes(c),
);
const type =
v.notify_type && allowed.includes(v.notify_type)
? v.notify_type
: allowed[0] || 'email';
const patch = (fields) => onChange?.({ ...v, ...fields });
const Label = ({ children }) => (
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5'>
{children}
</label>
);
return (
<div className='space-y-4'>
<div className='max-w-xs'>
<Label>{t('通知渠道')}</Label>
<Select
value={type}
onChange={(val) => patch({ notify_type: val })}
disabled={disabled}
style={{ width: '100%' }}
optionList={[
{ value: 'email', label: t('邮件') },
{ value: 'webhook', label: 'Webhook' },
{ value: 'bark', label: 'Bark' },
{ value: 'gotify', label: 'Gotify' },
].filter((opt) => allowed.includes(opt.value))}
/>
</div>
{type === 'email' && (
<div className='max-w-md'>
<Label>{t('通知邮箱')}</Label>
<Input
value={v.notification_email || ''}
onChange={(val) => patch({ notification_email: val })}
placeholder={emailPlaceholder || t('留空则使用企业联系邮箱')}
disabled={disabled}
/>
</div>
)}
{type === 'webhook' && (
<div className='max-w-md space-y-3'>
<div>
<Label>{t('Webhook 地址')}</Label>
<Input
value={v.webhook_url || ''}
onChange={(val) => patch({ webhook_url: val })}
placeholder='https://example.com/webhook'
disabled={disabled}
/>
</div>
<div>
<Label>{t('接口凭证')}</Label>
<Input
value={v.webhook_secret || ''}
onChange={(val) => patch({ webhook_secret: val })}
placeholder={t('可选,将以 Bearer 方式加入请求头')}
disabled={disabled}
/>
</div>
</div>
)}
{type === 'bark' && (
<div className='max-w-md'>
<Label>{t('Bark 推送地址')}</Label>
<Input
value={v.bark_url || ''}
onChange={(val) => patch({ bark_url: val })}
placeholder='https://api.day.app/xxx'
disabled={disabled}
/>
</div>
)}
{type === 'gotify' && (
<div className='max-w-md space-y-3'>
<div>
<Label>{t('Gotify 服务器地址')}</Label>
<Input
value={v.gotify_url || ''}
onChange={(val) => patch({ gotify_url: val })}
placeholder='https://gotify.example.com'
disabled={disabled}
/>
</div>
<div>
<Label>{t('Gotify 应用令牌')}</Label>
<Input
value={v.gotify_token || ''}
onChange={(val) => patch({ gotify_token: val })}
disabled={disabled}
/>
</div>
<div>
<Label>{t('消息优先级')}</Label>
<InputNumber
value={v.gotify_priority ?? 0}
onChange={(val) => patch({ gotify_priority: val })}
min={0}
max={10}
disabled={disabled}
style={{ width: '100%' }}
/>
</div>
</div>
)}
</div>
);
};
export default NotifyChannelForm;
@@ -0,0 +1,243 @@
/*
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 { Card, Spin } from '@douyinfe/semi-ui';
import SettingsGeneral from '../../pages/Setting/Operation/SettingsGeneral';
import SettingsLanguage from '../../pages/Setting/Operation/SettingsLanguage';
import SettingsHeaderNavModules from '../../pages/Setting/Operation/SettingsHeaderNavModules';
import SettingsOrgUserNavModules from '../../pages/Setting/Operation/SettingsOrgUserNavModules';
import SettingsSidebarModulesAdmin from '../../pages/Setting/Operation/SettingsSidebarModulesAdmin';
import SettingsSensitiveWords from '../../pages/Setting/Operation/SettingsSensitiveWords';
import SettingsLog from '../../pages/Setting/Operation/SettingsLog';
import SettingsMonitoring from '../../pages/Setting/Operation/SettingsMonitoring';
import SettingsDashboardMonitor from '../../pages/Setting/Operation/SettingsDashboardMonitor';
import SettingsCreditLimit from '../../pages/Setting/Operation/SettingsCreditLimit';
import SettingsExperienceCenter from '../../pages/Setting/Operation/SettingsExperienceCenter';
import SettingsMarquee from '../../pages/Setting/Operation/SettingsMarquee';
import SettingsFallback from '../../pages/Setting/Operation/SettingsFallback';
import SettingsTheme from '../../pages/Setting/Operation/SettingsTheme';
import SettingsAdminDelegation from '../../pages/Setting/Operation/SettingsAdminDelegation';
import SettingsSkillInject from '../../pages/Setting/Operation/SettingsSkillInject';
import { API, showError, toBoolean } from '../../helpers';
const OperationSetting = () => {
let [inputs, setInputs] = useState({
/* 额度相关 */
QuotaForNewUser: 0,
PreConsumedQuota: 0,
QuotaForInviter: 0,
QuotaForInvitee: 0,
'quota_setting.enable_free_model_pre_consume': true,
/* 邀请消费返佣:布尔必须在此声明,getOptions 才会 toBoolean;
否则读回字符串 "false" 被当真值,返佣开关恒显示开启且关不掉 */
InviteRebateEnabled: false,
/* 通用设置 */
TopUpLink: '',
'general_setting.docs_link': '',
QuotaPerUnit: 0,
USDExchangeRate: 0,
RetryTimes: 0,
'general_setting.quota_display_type': 'USD',
DisplayTokenStatEnabled: false,
DefaultCollapseSidebar: false,
DemoSiteEnabled: false,
SelfUseModeEnabled: false,
/* 语言与地区(JSON,按 IP 国家自动选择界面语言) */
LanguageSetting: '',
/* 腾讯云COS配置 */
CosEnabled: false,
CosSecretId: '',
CosSecretKey: '',
CosBucket: '',
CosRegion: '',
CosBaseUrl: '',
/* 顶栏模块管理 */
HeaderNavModules: '',
/* 企业员工顶栏管理 */
HeaderNavModulesOrgUser: '',
/* 左侧边栏模块管理(管理员) */
SidebarModulesAdmin: '',
/* 主题色配置 */
ThemeConfig: '',
/* 主题预设模板覆盖 */
ThemePresets: '',
/* 敏感词设置 */
CheckSensitiveEnabled: false,
CheckSensitiveOnPromptEnabled: false,
SensitiveWords: '',
/* 日志设置 */
LogConsumeEnabled: false,
/* 提示词采集(实验性,方案 §35 一期) */
GlobalPromptArchiveEnabled: false,
/* 监控设置 */
ChannelDisableThreshold: 0,
QuotaRemindThreshold: 0,
AutomaticDisableChannelEnabled: false,
AutomaticEnableChannelEnabled: false,
ChannelServerErrorAutoDisableThreshold: '',
AutomaticDisableKeywords: '',
'monitor_setting.auto_test_channel_enabled': false,
'monitor_setting.auto_test_channel_minutes': 10,
ChannelAffinityEnabled: false,
ChannelAffinityTTL: '',
/* 体验中心设置 */
ExperienceCenterModels: '',
/* 跑马灯设置 */
MarqueeContent: '',
/* 下放给普通管理员的系统设置 tab(JSON 数组字符串) */
AdminDelegatedSettingTabs: '',
/* 兜底渠道设置(Phase 1-3)*/
'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',
'fallback_setting.allow_cross_group': false,
'fallback_setting.cross_border_allowed': false,
'fallback_setting.bound_user_allowed': false,
'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,
});
let [loading, setLoading] = useState(false);
const inputTypes = useRef(inputs);
const getOptions = useCallback(async () => {
const res = await API.get('/api/option/');
const { success, message, data } = res.data;
if (success) {
let newInputs = {};
data.forEach((item) => {
if (typeof inputTypes.current[item.key] === 'boolean') {
newInputs[item.key] = toBoolean(item.value);
} else {
newInputs[item.key] = item.value;
}
});
setInputs(newInputs);
} else {
showError(message);
}
}, []);
const onRefresh = useCallback(async () => {
try {
setLoading(true);
await getOptions();
// showSuccess('刷新成功');
} catch (error) {
showError('刷新失败');
} finally {
setLoading(false);
}
}, [getOptions]);
useEffect(() => {
onRefresh();
}, [onRefresh]);
return (
<>
<Spin spinning={loading} size='large'>
{/* 通用设置 */}
<Card style={{ marginTop: '10px' }}>
<SettingsGeneral options={inputs} refresh={onRefresh} />
</Card>
{/* 语言与地区 */}
<Card style={{ marginTop: '10px' }}>
<SettingsLanguage options={inputs} refresh={onRefresh} />
</Card>
{/* 主题色配置 */}
<div style={{ marginTop: '10px' }}>
<SettingsTheme options={inputs} refresh={onRefresh} />
</div>
{/* 顶栏模块管理 */}
<div style={{ marginTop: '10px' }}>
<SettingsHeaderNavModules options={inputs} refresh={onRefresh} />
</div>
{/* 企业员工顶栏管理 */}
<div style={{ marginTop: '10px' }}>
<SettingsOrgUserNavModules options={inputs} refresh={onRefresh} />
</div>
{/* 左侧边栏模块管理(管理员) */}
<div style={{ marginTop: '10px' }}>
<SettingsSidebarModulesAdmin options={inputs} refresh={onRefresh} />
</div>
{/* 屏蔽词过滤设置 */}
<Card style={{ marginTop: '10px' }}>
<SettingsSensitiveWords options={inputs} refresh={onRefresh} />
</Card>
{/* 日志设置 */}
<Card style={{ marginTop: '10px' }}>
<SettingsLog options={inputs} refresh={onRefresh} />
</Card>
{/* 监控设置 */}
<Card style={{ marginTop: '10px' }}>
<SettingsMonitoring options={inputs} refresh={onRefresh} />
</Card>
{/* 兜底渠道设置 */}
<Card style={{ marginTop: '10px' }}>
<SettingsFallback options={inputs} refresh={onRefresh} />
</Card>
{/* 技能注入(网关直连)设置 */}
<Card style={{ marginTop: '10px' }}>
<SettingsSkillInject options={inputs} refresh={onRefresh} />
</Card>
{/* 服务大盘监控设置 */}
<div style={{ marginTop: '10px' }}>
<SettingsDashboardMonitor />
</div>
{/* 额度设置 */}
<Card style={{ marginTop: '10px' }}>
<SettingsCreditLimit options={inputs} refresh={onRefresh} />
</Card>
{/* 跑马灯设置 */}
<Card style={{ marginTop: '10px' }}>
<SettingsMarquee options={inputs} refresh={onRefresh} />
</Card>
{/* 体验中心设置 */}
<SettingsExperienceCenter options={inputs} refresh={onRefresh} />
{/* 普通管理员可见的系统设置页(权限下放) */}
<SettingsAdminDelegation options={inputs} refresh={onRefresh} />
</Spin>
</>
);
};
export default OperationSetting;
+630
View File
@@ -0,0 +1,630 @@
/*
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, useRef, useState } from 'react';
import { Button, Col, Form, Row, Modal, Space, Card } from '@douyinfe/semi-ui';
import { API, showError, showSuccess, timestamp2string } from '../../helpers';
import { useTranslation } from 'react-i18next';
import { StatusContext } from '../../context/Status';
import Text from '@douyinfe/semi-ui/lib/es/typography/text';
const LEGAL_USER_AGREEMENT_KEY = 'legal.user_agreement';
const LEGAL_PRIVACY_POLICY_KEY = 'legal.privacy_policy';
const OtherSetting = () => {
const { t } = useTranslation();
let [inputs, setInputs] = useState({
Notice: '',
[LEGAL_USER_AGREEMENT_KEY]: '',
[LEGAL_PRIVACY_POLICY_KEY]: '',
SystemName: '',
Logo: '',
AuthBackgroundTheme: 'ocean',
Footer: '',
About: '',
HomePageContent: '',
ConsoleWelcomeTitle: '',
OfficialWebsite: '',
});
let [, setLoading] = useState(false);
const [showUpdateModal, setShowUpdateModal] = useState(false);
const [statusState] = useContext(StatusContext);
const [updateData] = useState({
tag_name: '',
content: '',
});
const updateOption = async (key, value) => {
setLoading(true);
const res = await API.put('/api/option/', {
key,
value,
});
const { success, message } = res.data;
if (success) {
setInputs((inputs) => ({ ...inputs, [key]: value }));
} else {
showError(message);
}
setLoading(false);
return success;
};
const [loadingInput, setLoadingInput] = useState({
Notice: false,
[LEGAL_USER_AGREEMENT_KEY]: false,
[LEGAL_PRIVACY_POLICY_KEY]: false,
SystemName: false,
Logo: false,
AuthBackgroundTheme: false,
HomePageContent: false,
About: false,
Footer: false,
CheckUpdate: false,
ConsoleWelcome: false,
OfficialWebsite: false,
});
const handleInputChange = async (value, e) => {
const name = e.target.id;
setInputs((inputs) => ({ ...inputs, [name]: value }));
};
// 通用设置
const formAPISettingGeneral = useRef();
// 通用设置 - Notice
const submitNotice = async () => {
try {
setLoadingInput((loadingInput) => ({ ...loadingInput, Notice: true }));
const ok = await updateOption('Notice', inputs.Notice);
if (ok) showSuccess(t('公告已更新'));
} catch (error) {
console.error(t('公告更新失败'), error);
showError(t('公告更新失败'));
} finally {
setLoadingInput((loadingInput) => ({ ...loadingInput, Notice: false }));
}
};
// 通用设置 - UserAgreement
const submitUserAgreement = async () => {
try {
setLoadingInput((loadingInput) => ({
...loadingInput,
[LEGAL_USER_AGREEMENT_KEY]: true,
}));
const ok = await updateOption(
LEGAL_USER_AGREEMENT_KEY,
inputs[LEGAL_USER_AGREEMENT_KEY],
);
if (ok) showSuccess(t('服务协议已更新'));
} catch (error) {
console.error(t('服务协议更新失败'), error);
showError(t('服务协议更新失败'));
} finally {
setLoadingInput((loadingInput) => ({
...loadingInput,
[LEGAL_USER_AGREEMENT_KEY]: false,
}));
}
};
// 通用设置 - PrivacyPolicy
const submitPrivacyPolicy = async () => {
try {
setLoadingInput((loadingInput) => ({
...loadingInput,
[LEGAL_PRIVACY_POLICY_KEY]: true,
}));
const ok = await updateOption(
LEGAL_PRIVACY_POLICY_KEY,
inputs[LEGAL_PRIVACY_POLICY_KEY],
);
if (ok) showSuccess(t('隐私政策已更新'));
} catch (error) {
console.error(t('隐私政策更新失败'), error);
showError(t('隐私政策更新失败'));
} finally {
setLoadingInput((loadingInput) => ({
...loadingInput,
[LEGAL_PRIVACY_POLICY_KEY]: false,
}));
}
};
// 个性化设置
const formAPIPersonalization = useRef();
// 个性化设置 - SystemName
const submitSystemName = async () => {
try {
setLoadingInput((loadingInput) => ({
...loadingInput,
SystemName: true,
}));
const ok = await updateOption('SystemName', inputs.SystemName);
if (ok) showSuccess(t('系统名称已更新'));
} catch (error) {
console.error(t('系统名称更新失败'), error);
showError(t('系统名称更新失败'));
} finally {
setLoadingInput((loadingInput) => ({
...loadingInput,
SystemName: false,
}));
}
};
// 个性化设置 - Logo
const submitLogo = async () => {
try {
setLoadingInput((loadingInput) => ({ ...loadingInput, Logo: true }));
const ok = await updateOption('Logo', inputs.Logo);
if (ok) showSuccess(t('Logo 已更新'));
} catch (error) {
console.error('Logo 更新失败', error);
showError(t('Logo 更新失败'));
} finally {
setLoadingInput((loadingInput) => ({ ...loadingInput, Logo: false }));
}
};
// 个性化设置 - 首页内容
const submitOption = async (key) => {
try {
setLoadingInput((loadingInput) => ({
...loadingInput,
HomePageContent: true,
}));
const ok = await updateOption(key, inputs[key]);
if (ok) showSuccess(t('首页内容已更新'));
} catch (error) {
console.error('首页内容更新失败', error);
showError(t('首页内容更新失败'));
} finally {
setLoadingInput((loadingInput) => ({
...loadingInput,
HomePageContent: false,
}));
}
};
// 个性化设置 - 登录页背景动画
const submitAuthBackgroundTheme = async () => {
try {
setLoadingInput((loadingInput) => ({
...loadingInput,
AuthBackgroundTheme: true,
}));
const ok = await updateOption(
'AuthBackgroundTheme',
inputs.AuthBackgroundTheme,
);
if (ok) {
showSuccess(t('登录页背景动画已更新'));
}
} catch (error) {
console.error('登录页背景动画更新失败', error);
showError(t('登录页背景动画更新失败'));
} finally {
setLoadingInput((loadingInput) => ({
...loadingInput,
AuthBackgroundTheme: false,
}));
}
};
// 个性化设置 - 关于
const submitAbout = async () => {
try {
setLoadingInput((loadingInput) => ({ ...loadingInput, About: true }));
const ok = await updateOption('About', inputs.About);
if (ok) showSuccess(t('关于内容已更新'));
} catch (error) {
console.error('关于内容更新失败', error);
showError(t('关于内容更新失败'));
} finally {
setLoadingInput((loadingInput) => ({ ...loadingInput, About: false }));
}
};
// 个性化设置 - 控制台欢迎语标题
const submitConsoleWelcome = async () => {
try {
setLoadingInput((loadingInput) => ({
...loadingInput,
ConsoleWelcome: true,
}));
const ok = await updateOption(
'ConsoleWelcomeTitle',
inputs.ConsoleWelcomeTitle,
);
if (ok) showSuccess(t('控制台欢迎语已更新'));
} catch (error) {
console.error('控制台欢迎语更新失败', error);
showError(t('控制台欢迎语更新失败'));
} finally {
setLoadingInput((loadingInput) => ({
...loadingInput,
ConsoleWelcome: false,
}));
}
};
// 个性化设置 - 官网链接(控制台欢迎语 / 关于页 / 检查更新弹窗共用)
const submitOfficialWebsite = async () => {
try {
setLoadingInput((loadingInput) => ({
...loadingInput,
OfficialWebsite: true,
}));
const ok = await updateOption('OfficialWebsite', inputs.OfficialWebsite);
if (ok) showSuccess(t('官网链接已更新'));
} catch (error) {
console.error('官网链接更新失败', error);
showError(t('官网链接更新失败'));
} finally {
setLoadingInput((loadingInput) => ({
...loadingInput,
OfficialWebsite: false,
}));
}
};
// 个性化设置 - 页脚
const submitFooter = async () => {
try {
setLoadingInput((loadingInput) => ({ ...loadingInput, Footer: true }));
const ok = await updateOption('Footer', inputs.Footer);
if (ok) showSuccess(t('页脚内容已更新'));
} catch (error) {
console.error('页脚内容更新失败', error);
showError(t('页脚内容更新失败'));
} finally {
setLoadingInput((loadingInput) => ({ ...loadingInput, Footer: false }));
}
};
const checkUpdate = async () => {
try {
setLoadingInput((loadingInput) => ({
...loadingInput,
CheckUpdate: true,
}));
// 版本检查已禁用 - Weelinking 是独立项目
showSuccess(t('当前已是最新版本'));
return;
// 以下代码已禁用
// const res = await fetch(
// 'https://api.github.com/repos/Calcium-Ion/new-api/releases/latest',
// {
// headers: {
// Accept: 'application/json',
// 'Content-Type': 'application/json',
// 'User-Agent': 'weelinking-update-checker',
// },
// },
// ).then((response) => response.json());
// const { tag_name, body } = res;
// if (tag_name === statusState?.status?.version) {
// showSuccess(`已是最新版本:${tag_name}`);
// } else {
// setUpdateData({
// tag_name: tag_name,
// content: marked.parse(body),
// });
// setShowUpdateModal(true);
// }
} catch (error) {
console.error('Failed to check for updates:', error);
showError(t('检查更新失败,请稍后再试'));
} finally {
setLoadingInput((loadingInput) => ({
...loadingInput,
CheckUpdate: false,
}));
}
};
const getOptions = async () => {
const res = await API.get('/api/option/');
const { success, message, data } = res.data;
if (success) {
let newInputs = {};
data.forEach((item) => {
if (item.key in inputs) {
newInputs[item.key] = item.value;
}
});
setInputs(newInputs);
formAPISettingGeneral.current.setValues(newInputs);
formAPIPersonalization.current.setValues(newInputs);
} else {
showError(message);
}
};
useEffect(() => {
getOptions();
}, []);
// 打开官网(可配置,未配置则按钮不显示)
const officialWebsite = (statusState?.status?.official_website || '').trim();
const openOfficialWebsite = () => {
if (officialWebsite) window.open(officialWebsite, '_blank');
};
const getStartTimeString = () => {
const timestamp = statusState?.status?.start_time;
return statusState.status ? timestamp2string(timestamp) : '';
};
return (
<Row>
<Col
span={24}
style={{
marginTop: '10px',
display: 'flex',
flexDirection: 'column',
gap: '10px',
}}
>
{/* 版本信息 */}
<Form>
<Card>
<Form.Section text={t('系统信息')}>
<Row>
<Col span={16}>
<Space>
<Text>
{t('当前版本')}:
{statusState?.status?.version || t('未知')}
</Text>
<Button
type='primary'
onClick={checkUpdate}
loading={loadingInput['CheckUpdate']}
>
{t('检查更新')}
</Button>
</Space>
</Col>
</Row>
<Row>
<Col span={16}>
<Text>
{t('启动时间')}:{getStartTimeString()}
</Text>
</Col>
</Row>
</Form.Section>
</Card>
</Form>
{/* 通用设置 */}
<Form
values={inputs}
getFormApi={(formAPI) => (formAPISettingGeneral.current = formAPI)}
>
<Card>
<Form.Section text={t('通用设置')}>
<Form.TextArea
label={t('公告')}
placeholder={t(
'在此输入新的公告内容,支持 Markdown & HTML 代码',
)}
field={'Notice'}
onChange={handleInputChange}
style={{ fontFamily: 'JetBrains Mono, Consolas' }}
autosize={{ minRows: 6, maxRows: 12 }}
/>
<Button onClick={submitNotice} loading={loadingInput['Notice']}>
{t('设置公告')}
</Button>
<Form.TextArea
label={t('服务协议')}
placeholder={t(
'在此输入服务协议内容,支持 Markdown & HTML 代码',
)}
field={LEGAL_USER_AGREEMENT_KEY}
onChange={handleInputChange}
style={{ fontFamily: 'JetBrains Mono, Consolas' }}
autosize={{ minRows: 6, maxRows: 12 }}
helpText={t(
'填写服务协议内容后,用户注册时将被要求勾选已阅读服务协议',
)}
/>
<Button
onClick={submitUserAgreement}
loading={loadingInput[LEGAL_USER_AGREEMENT_KEY]}
>
{t('设置服务协议')}
</Button>
<Form.TextArea
label={t('隐私政策')}
placeholder={t(
'在此输入隐私政策内容,支持 Markdown & HTML 代码',
)}
field={LEGAL_PRIVACY_POLICY_KEY}
onChange={handleInputChange}
style={{ fontFamily: 'JetBrains Mono, Consolas' }}
autosize={{ minRows: 6, maxRows: 12 }}
helpText={t(
'填写隐私政策内容后,用户注册时将被要求勾选已阅读隐私政策',
)}
/>
<Button
onClick={submitPrivacyPolicy}
loading={loadingInput[LEGAL_PRIVACY_POLICY_KEY]}
>
{t('设置隐私政策')}
</Button>
</Form.Section>
</Card>
</Form>
{/* 个性化设置 */}
<Form
values={inputs}
getFormApi={(formAPI) => (formAPIPersonalization.current = formAPI)}
>
<Card>
<Form.Section text={t('个性化设置')}>
<Form.Input
label={t('系统名称')}
placeholder={t('在此输入系统名称')}
field={'SystemName'}
onChange={handleInputChange}
/>
<Button
onClick={submitSystemName}
loading={loadingInput['SystemName']}
>
{t('设置系统名称')}
</Button>
<Form.Input
label={t('Logo 图片地址')}
placeholder={t('在此输入 Logo 图片地址')}
field={'Logo'}
onChange={handleInputChange}
/>
<Button onClick={submitLogo} loading={loadingInput['Logo']}>
{t('设置 Logo')}
</Button>
<Form.Select
label={t('登录页背景动画')}
field={'AuthBackgroundTheme'}
style={{ width: 280 }}
optionList={[
{ value: 'ocean', label: t('深海幽光(默认)') },
{ value: 'token-factory', label: t('Token 工厂 · 算力机房') },
{
value: 'token-factory-cinematic',
label: t('Token 工厂 · 电影级算力机房'),
},
{ value: 'none', label: t('无动画') },
]}
onChange={(value) =>
setInputs((inputs) => ({
...inputs,
AuthBackgroundTheme: value,
}))
}
helpText={t(
'登录、注册、企业登录、企业注册四个页面共用的背景动画',
)}
/>
<Button
onClick={submitAuthBackgroundTheme}
loading={loadingInput['AuthBackgroundTheme']}
>
{t('设置背景动画')}
</Button>
<Form.TextArea
label={t('首页内容')}
placeholder={t(
'在此输入首页内容,支持 Markdown & HTML 代码,设置后首页的状态信息将不再显示。如果输入的是一个链接,则会使用该链接作为 iframe 的 src 属性,这允许你设置任意网页作为首页',
)}
field={'HomePageContent'}
onChange={handleInputChange}
style={{ fontFamily: 'JetBrains Mono, Consolas' }}
autosize={{ minRows: 6, maxRows: 12 }}
/>
<Button
onClick={() => submitOption('HomePageContent')}
loading={loadingInput['HomePageContent']}
>
{t('设置首页内容')}
</Button>
<Form.TextArea
label={t('关于')}
placeholder={t(
'在此输入新的关于内容,支持 Markdown & HTML 代码。如果输入的是一个链接,则会使用该链接作为 iframe 的 src 属性,这允许你设置任意网页作为关于页面',
)}
field={'About'}
onChange={handleInputChange}
style={{ fontFamily: 'JetBrains Mono, Consolas' }}
autosize={{ minRows: 6, maxRows: 12 }}
/>
<Button onClick={submitAbout} loading={loadingInput['About']}>
{t('设置关于')}
</Button>
<Form.Input
label={t('官网链接')}
placeholder={t('例如 https://www.example.com')}
field={'OfficialWebsite'}
onChange={handleInputChange}
helpText={t(
'用于控制台欢迎语、关于页默认内容与检查更新弹窗,留空则不显示',
)}
/>
<Button
onClick={submitOfficialWebsite}
loading={loadingInput['OfficialWebsite']}
>
{t('设置官网链接')}
</Button>
<Form.Input
label={t('控制台欢迎语标题')}
placeholder={t('浏览器控制台(F12)打印的欢迎语标题')}
field={'ConsoleWelcomeTitle'}
onChange={handleInputChange}
helpText={t('标题与官网链接均留空则控制台不打印欢迎语')}
/>
<Button
onClick={submitConsoleWelcome}
loading={loadingInput['ConsoleWelcome']}
>
{t('设置控制台欢迎语')}
</Button>
<Form.Input
label={t('页脚')}
placeholder={t(
'在此输入新的页脚,留空则使用默认页脚,支持 HTML 代码',
)}
field={'Footer'}
onChange={handleInputChange}
/>
<Button onClick={submitFooter} loading={loadingInput['Footer']}>
{t('设置页脚')}
</Button>
</Form.Section>
</Card>
</Form>
</Col>
<Modal
title={t('新版本') + ':' + updateData.tag_name}
visible={showUpdateModal}
onCancel={() => setShowUpdateModal(false)}
footer={
officialWebsite
? [
<Button
key='details'
type='primary'
onClick={() => {
setShowUpdateModal(false);
openOfficialWebsite();
}}
>
{t('详情')}
</Button>,
]
: null
}
>
<div dangerouslySetInnerHTML={{ __html: updateData.content }}></div>
</Modal>
</Row>
);
};
export default OtherSetting;
+302
View File
@@ -0,0 +1,302 @@
/*
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 { Card, Spin } from '@douyinfe/semi-ui';
import SettingsGeneralPayment from '../../pages/Setting/Payment/SettingsGeneralPayment';
import SettingsPaymentGateway from '../../pages/Setting/Payment/SettingsPaymentGateway';
import SettingsPaymentGatewayStripe from '../../pages/Setting/Payment/SettingsPaymentGatewayStripe';
import SettingsPaymentGatewayPayPal from '../../pages/Setting/Payment/SettingsPaymentGatewayPayPal';
import SettingsPaymentGatewayCreem from '../../pages/Setting/Payment/SettingsPaymentGatewayCreem';
import SettingsPaymentWechat from '../../pages/Setting/Payment/SettingsPaymentWechat';
import SettingsPaymentAlipay from '../../pages/Setting/Payment/SettingsPaymentAlipay';
import SettingsNuonuoInvoice from '../../pages/Setting/Payment/SettingsNuonuoInvoice';
import { API, showError, toBoolean } from '../../helpers';
import { useTranslation } from 'react-i18next';
const PaymentSetting = () => {
const { t } = useTranslation();
let [inputs, setInputs] = useState({
ServerAddress: '',
PayAddress: '',
EpayId: '',
EpayKey: '',
Price: 7.3,
MinTopUp: 1,
TopupGroupRatio: '',
CustomCallbackAddress: '',
PayMethods: '',
AmountOptions: '',
AmountDiscount: '',
ShowDefaultPayMethods: true,
DisabledPayMethods: [],
StripeApiSecret: '',
StripeWebhookSecret: '',
StripePriceId: '',
StripeUnitPrice: 8.0,
StripeMinTopUp: 1,
StripePromotionCodesEnabled: false,
PayPalClientID: '',
PayPalClientSecret: '',
PayPalWebhookID: '',
PayPalSandbox: true,
PayPalMinTopUp: 1,
PayPalFXMode: 'manual',
PayPalFXProvider: 'open_exchange_rates',
PayPalFXAPIKey: '',
PayPalFXAdjustmentBps: 0,
// WeChat Pay Settings
WechatMchId: '',
WechatAppId: '',
WechatAPIv3Key: '',
WechatSerialNo: '',
WechatPrivateKey: '',
WechatNativeEnabled: false,
WechatH5Enabled: false,
WechatNotifyUrl: '',
WechatDescription: '平台充值',
WechatExpireMinutes: 30,
// Alipay Settings
AlipayAppId: '',
AlipayPrivateKey: '',
AlipayPublicKey: '',
AlipayPCEnabled: false,
AlipayWAPEnabled: false,
AlipayQREnabled: false,
AlipayIsSandbox: false,
AlipayNotifyUrl: '',
AlipayReturnUrl: '',
AlipaySubject: '平台充值',
AlipayExpireMinutes: 30,
// Nuonuo Invoice Settings
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,
});
let [loading, setLoading] = useState(false);
const getOptions = async () => {
const res = await API.get('/api/option/');
const { success, message, data } = res.data;
if (success) {
let newInputs = {};
data.forEach((item) => {
switch (item.key) {
case 'TopupGroupRatio':
try {
newInputs[item.key] = JSON.stringify(
JSON.parse(item.value),
null,
2,
);
} catch (error) {
console.error('解析TopupGroupRatio出错:', error);
newInputs[item.key] = item.value;
}
break;
case 'payment_setting.amount_options':
try {
newInputs['AmountOptions'] = JSON.stringify(
JSON.parse(item.value),
null,
2,
);
} catch (error) {
console.error('解析AmountOptions出错:', error);
newInputs['AmountOptions'] = item.value;
}
break;
case 'payment_setting.amount_discount':
try {
newInputs['AmountDiscount'] = JSON.stringify(
JSON.parse(item.value),
null,
2,
);
} catch (error) {
console.error('解析AmountDiscount出错:', error);
newInputs['AmountDiscount'] = item.value;
}
break;
case 'payment_setting.show_default_pay_methods':
newInputs['ShowDefaultPayMethods'] = toBoolean(item.value);
break;
case 'payment_setting.disabled_pay_methods':
try {
const parsed = JSON.parse(item.value);
newInputs['DisabledPayMethods'] = Array.isArray(parsed)
? parsed
: [];
} catch (error) {
console.error('解析DisabledPayMethods出错:', error);
newInputs['DisabledPayMethods'] = [];
}
break;
case 'Price':
case 'MinTopUp':
case 'StripeUnitPrice':
case 'StripeMinTopUp':
case 'PayPalMinTopUp':
case 'PayPalFXAdjustmentBps':
newInputs[item.key] = parseFloat(item.value);
break;
case 'WechatExpireMinutes':
case 'AlipayExpireMinutes':
newInputs[item.key] = parseInt(item.value) || 30;
break;
// Nuonuo Invoice Settings
case 'nuonuo_setting.enabled':
newInputs['NuonuoEnabled'] = toBoolean(item.value);
break;
case 'nuonuo_setting.app_key':
newInputs['NuonuoAppKey'] = item.value;
break;
case 'nuonuo_setting.app_secret':
newInputs['NuonuoAppSecret'] = item.value;
break;
case 'nuonuo_setting.api_url':
newInputs['NuonuoApiUrl'] = item.value;
break;
case 'nuonuo_setting.callback_url':
newInputs['NuonuoCallbackUrl'] = item.value;
break;
case 'nuonuo_setting.tax_num':
newInputs['NuonuoTaxNum'] = item.value;
break;
case 'nuonuo_setting.saler_name':
newInputs['NuonuoSalerName'] = item.value;
break;
case 'nuonuo_setting.saler_address':
newInputs['NuonuoSalerAddress'] = item.value;
break;
case 'nuonuo_setting.saler_tel':
newInputs['NuonuoSalerTel'] = item.value;
break;
case 'nuonuo_setting.saler_bank':
newInputs['NuonuoSalerBank'] = item.value;
break;
case 'nuonuo_setting.clerk':
newInputs['NuonuoClerk'] = item.value;
break;
case 'nuonuo_setting.extension_num':
newInputs['NuonuoExtensionNum'] = item.value;
break;
case 'nuonuo_setting.item_name':
newInputs['NuonuoItemName'] = item.value;
break;
case 'nuonuo_setting.tax_rate':
newInputs['NuonuoTaxRate'] = item.value;
break;
case 'nuonuo_setting.min_amount':
newInputs['NuonuoMinAmount'] = parseFloat(item.value) || 200;
break;
case 'nuonuo_setting.monthly_limit':
newInputs['NuonuoMonthlyLimit'] = parseInt(item.value) || 5;
break;
default:
// 处理所有布尔值字段
if (
item.key.endsWith('Enabled') ||
item.key === 'WechatUsePublicKey' ||
item.key === 'WechatUseManualCert' ||
item.key === 'AlipayIsSandbox' ||
item.key === 'PayPalSandbox'
) {
newInputs[item.key] = toBoolean(item.value);
} else {
newInputs[item.key] = item.value;
}
break;
}
});
// 使用合并方式设置状态,保留初始值
setInputs((prevInputs) => ({ ...prevInputs, ...newInputs }));
} else {
showError(t(message));
}
};
async function onRefresh() {
try {
setLoading(true);
await getOptions();
} catch (error) {
showError(t('刷新失败'));
} finally {
setLoading(false);
}
}
useEffect(() => {
onRefresh();
}, []);
return (
<>
<Spin spinning={loading} size='large'>
<Card style={{ marginTop: '10px' }}>
<SettingsGeneralPayment options={inputs} refresh={onRefresh} />
</Card>
<Card style={{ marginTop: '10px' }}>
<SettingsPaymentGateway options={inputs} refresh={onRefresh} />
</Card>
<Card style={{ marginTop: '10px' }}>
<SettingsPaymentGatewayStripe options={inputs} refresh={onRefresh} />
</Card>
<Card style={{ marginTop: '10px' }}>
<SettingsPaymentGatewayPayPal options={inputs} refresh={onRefresh} />
</Card>
<Card style={{ marginTop: '10px' }}>
<SettingsPaymentGatewayCreem options={inputs} refresh={onRefresh} />
</Card>
<Card style={{ marginTop: '10px' }}>
<SettingsPaymentWechat options={inputs} refresh={onRefresh} />
</Card>
<Card style={{ marginTop: '10px' }}>
<SettingsPaymentAlipay options={inputs} refresh={onRefresh} />
</Card>
<Card style={{ marginTop: '10px' }}>
<SettingsNuonuoInvoice options={inputs} refresh={onRefresh} />
</Card>
</Spin>
</>
);
};
export default PaymentSetting;
+932
View File
@@ -0,0 +1,932 @@
/*
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 { useNavigate } from 'react-router-dom';
import {
API,
showError,
showInfo,
showSuccess,
setStatusData,
prepareCredentialCreationOptions,
buildRegistrationResult,
isPasskeySupported,
setUserData,
clearUserData,
stringToColor,
renderQuota,
isRoot,
isAdmin,
USER_AVATAR_TYPES,
getAvatarPresetById,
getDefaultAvatarPresetId,
getUserAvatarUrl,
parseUserSetting,
} from '../../helpers';
import { UserContext } from '../../context/User';
import { Avatar, Tooltip } from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import {
User,
Link2,
Shield,
Bell,
Sparkles,
Crown,
Coins,
BarChart2,
Users,
ChevronRight,
Copy,
Check,
} from 'lucide-react';
// 导入内容区组件
import AccountBindingSection from './personal/sections/AccountBindingSection';
import SecuritySection from './personal/sections/SecuritySection';
import NotificationSection from './personal/sections/NotificationSection';
import AvatarSection from './personal/sections/AvatarSection';
// 导入模态框
import EmailBindModal from './personal/modals/EmailBindModal';
import WeChatBindModal from './personal/modals/WeChatBindModal';
import AccountDeleteModal from './personal/modals/AccountDeleteModal';
import ChangePasswordModal from './personal/modals/ChangePasswordModal';
// 导航项配置
// 统一使用系统主题色(brand)作为选中态配色
const NAV_ACTIVE_GRADIENT = 'from-brand-from to-brand-to';
const NAV_ACTIVE_CLASS =
'from-brand-from/10 to-brand-to/10 dark:from-brand-from/20 dark:to-brand-to/20';
const NAV_TEXT_CLASS = 'text-brand-deep dark:text-brand';
const NAV_ITEMS = [
{
key: 'avatar',
icon: User,
label: '头像设置',
description: '设置你的展示形象',
gradient: NAV_ACTIVE_GRADIENT,
activeClass: NAV_ACTIVE_CLASS,
textClass: NAV_TEXT_CLASS,
},
{
key: 'binding',
icon: Link2,
label: '账号绑定',
description: '管理邮箱和第三方登录',
gradient: NAV_ACTIVE_GRADIENT,
activeClass: NAV_ACTIVE_CLASS,
textClass: NAV_TEXT_CLASS,
},
{
key: 'security',
icon: Shield,
label: '安全设置',
description: '保护密码和登录设备',
gradient: NAV_ACTIVE_GRADIENT,
activeClass: NAV_ACTIVE_CLASS,
textClass: NAV_TEXT_CLASS,
},
{
key: 'notification',
icon: Bell,
label: '通知设置',
description: '配置额度预警通知',
gradient: NAV_ACTIVE_GRADIENT,
activeClass: NAV_ACTIVE_CLASS,
textClass: NAV_TEXT_CLASS,
},
];
const PersonalSetting = () => {
const [userState, userDispatch] = useContext(UserContext);
let navigate = useNavigate();
const { t } = useTranslation();
// 当前选中的导航项
const [activeNav, setActiveNav] = useState('avatar');
const [inputs, setInputs] = useState({
wechat_verification_code: '',
email_verification_code: '',
email: '',
self_account_deletion_confirmation: '',
original_password: '',
set_new_password: '',
set_new_password_confirmation: '',
});
const [status, setStatus] = useState({});
const [showChangePasswordModal, setShowChangePasswordModal] = useState(false);
const [showWeChatBindModal, setShowWeChatBindModal] = useState(false);
const [showEmailBindModal, setShowEmailBindModal] = useState(false);
const [showAccountDeleteModal, setShowAccountDeleteModal] = useState(false);
const [turnstileEnabled, setTurnstileEnabled] = useState(false);
const [turnstileSiteKey, setTurnstileSiteKey] = useState('');
const [turnstileToken, setTurnstileToken] = useState('');
const [loading, setLoading] = useState(false);
const [disableButton, setDisableButton] = useState(false);
const [countdown, setCountdown] = useState(30);
const [passkeyStatus, setPasskeyStatus] = useState({ enabled: false });
const [passkeyRegisterLoading, setPasskeyRegisterLoading] = useState(false);
const [passkeyDeleteLoading, setPasskeyDeleteLoading] = useState(false);
const [passkeySupported, setPasskeySupported] = useState(false);
const [userIdCopied, setUserIdCopied] = useState(false);
const [savingAvatarSettings, setSavingAvatarSettings] = useState(false);
const [avatarSettings, setAvatarSettings] = useState({
avatarType: USER_AVATAR_TYPES.PRESET,
avatarPreset: getDefaultAvatarPresetId(userState?.user),
customAvatarUrl: '',
});
const [notificationSettings, setNotificationSettings] = useState({
warningType: 'email',
warningThreshold: 100000,
webhookUrl: '',
webhookSecret: '',
notificationEmail: '',
barkUrl: '',
gotifyUrl: '',
gotifyToken: '',
gotifyPriority: 5,
acceptUnsetModelRatioModel: false,
recordIpLog: false,
});
useEffect(() => {
let saved = localStorage.getItem('status');
if (saved) {
const parsed = JSON.parse(saved);
setStatus(parsed);
if (parsed.turnstile_check) {
setTurnstileEnabled(true);
setTurnstileSiteKey(parsed.turnstile_site_key);
} else {
setTurnstileEnabled(false);
setTurnstileSiteKey('');
}
}
(async () => {
try {
const res = await API.get('/api/status');
const { success, data } = res.data;
if (success && data) {
setStatus(data);
setStatusData(data);
if (data.turnstile_check) {
setTurnstileEnabled(true);
setTurnstileSiteKey(data.turnstile_site_key);
} else {
setTurnstileEnabled(false);
setTurnstileSiteKey('');
}
}
} catch (e) {
// ignore
}
})();
getUserData();
isPasskeySupported()
.then(setPasskeySupported)
.catch(() => setPasskeySupported(false));
}, []);
useEffect(() => {
let countdownInterval = null;
if (disableButton && countdown > 0) {
countdownInterval = setInterval(() => {
setCountdown(countdown - 1);
}, 1000);
} else if (countdown === 0) {
setDisableButton(false);
setCountdown(30);
}
return () => clearInterval(countdownInterval);
}, [disableButton, countdown]);
useEffect(() => {
if (userState?.user?.setting) {
const settings = parseUserSetting(userState.user.setting);
setNotificationSettings({
warningType: ['email', 'webhook'].includes(settings.notify_type)
? settings.notify_type
: 'email',
warningThreshold: settings.quota_warning_threshold || 500000,
webhookUrl: settings.webhook_url || '',
webhookSecret: settings.webhook_secret || '',
notificationEmail: settings.notification_email || '',
barkUrl: settings.bark_url || '',
gotifyUrl: settings.gotify_url || '',
gotifyToken: settings.gotify_token || '',
gotifyPriority:
settings.gotify_priority !== undefined ? settings.gotify_priority : 5,
acceptUnsetModelRatioModel:
settings.accept_unset_model_ratio_model || false,
recordIpLog: settings.record_ip_log || false,
});
setAvatarSettings({
avatarType: Object.values(USER_AVATAR_TYPES).includes(
settings.avatar_type,
)
? settings.avatar_type
: USER_AVATAR_TYPES.PRESET,
avatarPreset: getAvatarPresetById(
settings.avatar_preset || getDefaultAvatarPresetId(userState.user),
).id,
customAvatarUrl: settings.custom_avatar_url || '',
});
} else if (userState?.user) {
setAvatarSettings((prev) => ({
...prev,
avatarPreset:
prev.avatarPreset || getDefaultAvatarPresetId(userState.user),
}));
}
}, [userState?.user?.id, userState?.user?.setting]);
const handleInputChange = (name, value) => {
setInputs((inputs) => ({ ...inputs, [name]: value }));
};
const loadPasskeyStatus = async () => {
try {
const res = await API.get('/api/user/passkey');
const { success, data, message } = res.data;
if (success) {
setPasskeyStatus({
enabled: data?.enabled || false,
last_used_at: data?.last_used_at || null,
backup_eligible: data?.backup_eligible || false,
backup_state: data?.backup_state || false,
});
} else {
showError(message);
}
} catch (error) {
// ignore
}
};
const handleRegisterPasskey = async () => {
if (!passkeySupported || !window.PublicKeyCredential) {
showInfo(t('当前设备不支持 Passkey'));
return;
}
setPasskeyRegisterLoading(true);
try {
const beginRes = await API.post('/api/user/passkey/register/begin');
const { success, message, data } = beginRes.data;
if (!success) {
showError(message || t('无法发起 Passkey 注册'));
return;
}
const publicKey = prepareCredentialCreationOptions(
data?.options || data?.publicKey || data,
);
const credential = await navigator.credentials.create({ publicKey });
const payload = buildRegistrationResult(credential);
if (!payload) {
showError(t('Passkey 注册失败,请重试'));
return;
}
const finishRes = await API.post(
'/api/user/passkey/register/finish',
payload,
);
if (finishRes.data.success) {
showSuccess(t('Passkey 注册成功'));
await loadPasskeyStatus();
} else {
showError(finishRes.data.message || t('Passkey 注册失败,请重试'));
}
} catch (error) {
if (error?.name === 'AbortError') {
showInfo(t('已取消 Passkey 注册'));
} else {
showError(t('Passkey 注册失败,请重试'));
}
} finally {
setPasskeyRegisterLoading(false);
}
};
const handleRemovePasskey = async () => {
setPasskeyDeleteLoading(true);
try {
const res = await API.delete('/api/user/passkey');
const { success, message } = res.data;
if (success) {
showSuccess(t('Passkey 已解绑'));
await loadPasskeyStatus();
} else {
showError(message || t('操作失败,请重试'));
}
} catch (error) {
showError(t('操作失败,请重试'));
} finally {
setPasskeyDeleteLoading(false);
}
};
const getUserData = async () => {
let res = await API.get(`/api/user/self`);
const { success, message, data } = res.data;
if (success) {
userDispatch({ type: 'login', payload: data });
setUserData(data);
await loadPasskeyStatus();
} else {
showError(message);
}
};
const deleteAccount = async () => {
if (inputs.self_account_deletion_confirmation !== userState.user.username) {
showError(t('请输入你的账户名以确认删除!'));
return;
}
const res = await API.delete('/api/user/self');
const { success, message } = res.data;
if (success) {
showSuccess(t('账户已删除!'));
await API.get('/api/user/logout');
userDispatch({ type: 'logout' });
clearUserData();
navigate('/login');
} else {
showError(message);
}
};
const bindWeChat = async () => {
if (inputs.wechat_verification_code === '') return;
const res = await API.get(
`/api/oauth/wechat/bind?code=${inputs.wechat_verification_code}`,
);
const { success, message } = res.data;
if (success) {
showSuccess(t('微信账户绑定成功!'));
setShowWeChatBindModal(false);
} else {
showError(message);
}
};
const hasPassword = userState.user?.has_password;
const changePassword = async () => {
if (hasPassword && inputs.original_password === '') {
showError(t('请输入原密码!'));
return;
}
if (inputs.set_new_password === '') {
showError(t('请输入新密码!'));
return;
}
if (hasPassword && inputs.original_password === inputs.set_new_password) {
showError(t('新密码需要和原密码不一致!'));
return;
}
if (inputs.set_new_password !== inputs.set_new_password_confirmation) {
showError(t('两次输入的密码不一致!'));
return;
}
const res = await API.put(`/api/user/self`, {
original_password: inputs.original_password,
password: inputs.set_new_password,
});
const { success, message } = res.data;
if (success) {
showSuccess(hasPassword ? t('密码修改成功!') : t('密码设置成功!'));
// 重新拉取用户数据以更新 has_password 状态
await getUserData();
} else {
showError(message);
}
setShowChangePasswordModal(false);
};
const sendVerificationCode = async () => {
if (inputs.email === '') {
showError(t('请输入邮箱!'));
return;
}
setDisableButton(true);
if (turnstileEnabled && turnstileToken === '') {
showInfo(t('请稍后几秒重试,Turnstile 正在检查用户环境!'));
return;
}
setLoading(true);
const res = await API.get(
`/api/verification?email=${encodeURIComponent(inputs.email)}&turnstile=${turnstileToken}`,
);
const { success, message } = res.data;
if (success) {
showSuccess(t('验证码发送成功,请检查邮箱!'));
} else {
showError(message);
}
setLoading(false);
};
const bindEmail = async () => {
if (inputs.email_verification_code === '') {
showError(t('请输入邮箱验证码!'));
return;
}
setLoading(true);
const res = await API.get(
`/api/oauth/email/bind?email=${encodeURIComponent(inputs.email)}&code=${encodeURIComponent(inputs.email_verification_code)}`,
);
const { success, message } = res.data;
if (success) {
showSuccess(t('邮箱账户绑定成功!'));
setShowEmailBindModal(false);
userState.user.email = inputs.email;
} else {
showError(message);
}
setLoading(false);
};
const handleNotificationSettingChange = (type, value) => {
setNotificationSettings((prev) => ({
...prev,
[type]: value.target
? value.target.value !== undefined
? value.target.value
: value.target.checked
: value,
}));
};
const handleAvatarSettingChange = (type, value) => {
setAvatarSettings((prev) => ({
...prev,
[type]: value,
}));
};
const buildUserSettingPayload = (
nextNotificationSettings = notificationSettings,
nextAvatarSettings = avatarSettings,
) => ({
notify_type: nextNotificationSettings.warningType,
quota_warning_threshold: parseFloat(
nextNotificationSettings.warningThreshold,
),
webhook_url: nextNotificationSettings.webhookUrl,
webhook_secret: nextNotificationSettings.webhookSecret,
notification_email: nextNotificationSettings.notificationEmail,
bark_url: nextNotificationSettings.barkUrl,
gotify_url: nextNotificationSettings.gotifyUrl,
gotify_token: nextNotificationSettings.gotifyToken,
gotify_priority: (() => {
const parsed = parseInt(nextNotificationSettings.gotifyPriority);
return isNaN(parsed) ? 5 : parsed;
})(),
accept_unset_model_ratio_model:
nextNotificationSettings.acceptUnsetModelRatioModel,
record_ip_log: nextNotificationSettings.recordIpLog,
avatar_type: nextAvatarSettings.avatarType,
avatar_preset: nextAvatarSettings.avatarPreset,
custom_avatar_url: nextAvatarSettings.customAvatarUrl,
});
const saveNotificationSettings = async () => {
try {
const res = await API.put('/api/user/setting', buildUserSettingPayload());
if (res.data.success) {
showSuccess(t('设置保存成功'));
await getUserData();
} else {
showError(res.data.message);
}
} catch (error) {
showError(t('设置保存失败'));
}
};
const saveAvatarSettings = async () => {
if (
avatarSettings.avatarType === USER_AVATAR_TYPES.CUSTOM &&
!avatarSettings.customAvatarUrl?.trim()
) {
showError(t('请先填写自定义头像图片 URL'));
return;
}
setSavingAvatarSettings(true);
try {
const res = await API.put('/api/user/setting', buildUserSettingPayload());
if (res.data.success) {
showSuccess(t('头像设置已保存'));
await getUserData();
} else {
showError(res.data.message);
}
} catch (error) {
showError(t('头像设置保存失败'));
} finally {
setSavingAvatarSettings(false);
}
};
// 复制用户ID
const copyUserId = () => {
const userId = String(userState?.user?.id || '');
navigator.clipboard
.writeText(userId)
.then(() => {
setUserIdCopied(true);
setTimeout(() => setUserIdCopied(false), 2000);
})
.catch(() => {
// 降级方案
const textarea = document.createElement('textarea');
textarea.value = userId;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
setUserIdCopied(true);
setTimeout(() => setUserIdCopied(false), 2000);
});
};
// 获取用户名
const getUsername = () => userState.user?.username || 'User';
const getAvatarText = () => getUsername().slice(0, 2).toUpperCase();
const userAvatarUrl = getUserAvatarUrl(userState?.user);
// 获取角色标签
const getRoleTag = () => {
if (isRoot())
return { text: t('超级管理员'), color: 'from-amber-500 to-orange-500' };
if (isAdmin())
return { text: t('管理员'), color: 'from-brand-from to-pink-500' };
return { text: t('普通用户'), color: 'from-blue-500 to-brand-to' };
};
// 渲染内容区域
const renderContent = () => {
const commonProps = { t, userState, status };
switch (activeNav) {
case 'avatar':
return (
<AvatarSection
{...commonProps}
avatarSettings={avatarSettings}
handleAvatarSettingChange={handleAvatarSettingChange}
saveAvatarSettings={saveAvatarSettings}
savingAvatarSettings={savingAvatarSettings}
/>
);
case 'binding':
return (
<AccountBindingSection
{...commonProps}
setShowEmailBindModal={setShowEmailBindModal}
setShowWeChatBindModal={setShowWeChatBindModal}
/>
);
case 'security':
return (
<SecuritySection
{...commonProps}
setShowChangePasswordModal={setShowChangePasswordModal}
setShowAccountDeleteModal={setShowAccountDeleteModal}
hasPassword={hasPassword}
passkeyStatus={passkeyStatus}
passkeySupported={passkeySupported}
passkeyRegisterLoading={passkeyRegisterLoading}
passkeyDeleteLoading={passkeyDeleteLoading}
onPasskeyRegister={handleRegisterPasskey}
onPasskeyDelete={handleRemovePasskey}
/>
);
case 'notification':
return (
<NotificationSection
{...commonProps}
notificationSettings={notificationSettings}
handleNotificationSettingChange={handleNotificationSettingChange}
saveNotificationSettings={saveNotificationSettings}
/>
);
default:
return null;
}
};
const roleInfo = getRoleTag();
return (
<div className='flex flex-col lg:flex-row min-h-screen pt-16 sm:pt-20 bg-[radial-gradient(circle_at_top_left,rgba(14,165,233,0.16),transparent_34%),radial-gradient(circle_at_bottom_right,rgba(245,158,11,0.13),transparent_30%),linear-gradient(135deg,rgba(248,250,252,0.92),rgba(241,245,249,0.72))] dark:bg-[radial-gradient(circle_at_top_left,rgba(14,165,233,0.16),transparent_34%),radial-gradient(circle_at_bottom_right,rgba(245,158,11,0.10),transparent_30%),linear-gradient(135deg,#0f172a,#111827)]'>
{/* 背景装饰 */}
<div className='fixed inset-0 pointer-events-none overflow-hidden'>
<div className='absolute top-20 right-20 w-64 h-64 bg-blue-400/10 dark:bg-blue-600/10 rounded-full blur-3xl' />
<div className='absolute bottom-20 left-20 w-80 h-80 bg-brand-from/10 dark:bg-brand-deep/10 rounded-full blur-3xl' />
</div>
{/* 移动端顶部导航 */}
<div className='lg:hidden sticky top-16 sm:top-20 z-20 bg-white/[0.72] dark:bg-slate-950/[0.72] backdrop-blur-2xl border-b border-white/60 dark:border-white/10'>
{/* 用户简要信息 */}
<div className='flex items-center gap-3 px-4 py-3 border-b border-gray-100 dark:border-gray-800'>
<Avatar
size='small'
src={userAvatarUrl}
color={stringToColor(getUsername())}
className='!w-8 !h-8'
>
{getAvatarText()}
</Avatar>
<div className='flex-1 min-w-0'>
<div className='text-sm font-semibold text-gray-900 dark:text-white truncate'>
{getUsername()}
</div>
<div className='text-xs text-gray-500'>
{renderQuota(userState?.user?.quota)}
</div>
</div>
</div>
{/* 横向滚动导航 */}
<div className='overflow-x-auto scrollbar-hide'>
<div className='flex gap-1 p-2 min-w-max'>
{NAV_ITEMS.map((item) => {
const Icon = item.icon;
const isActive = activeNav === item.key;
return (
<button
key={item.key}
onClick={() => setActiveNav(item.key)}
className={`flex items-center gap-1.5 px-3 py-2 rounded-xl text-sm font-medium whitespace-nowrap transition-all border ${
isActive
? `bg-gradient-to-r ${item.activeClass} ${item.textClass} border-white/70 dark:border-white/10 shadow-sm`
: 'text-gray-600 dark:text-gray-400 border-transparent hover:bg-white/60 dark:hover:bg-white/[0.06]'
}`}
>
<Icon size={16} />
<span>{t(item.label)}</span>
</button>
);
})}
</div>
</div>
</div>
{/* 左侧导航栏 - 仅桌面端 */}
<div className='hidden lg:block w-80 shrink-0 p-4 pr-0 relative z-10'>
<div className='sticky top-24 bg-white/[0.62] dark:bg-slate-950/[0.52] backdrop-blur-2xl rounded-[28px] border border-white/70 dark:border-white/10 shadow-[0_24px_70px_rgba(15,23,42,0.10)] overflow-hidden'>
{/* 用户信息头部 */}
<div className='relative p-6 border-b border-white/60 dark:border-white/10'>
{/* 装饰背景 */}
<div className='absolute inset-0 bg-gradient-to-br from-blue-500/5 via-brand-via/5 to-brand-to/5' />
<div className='absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-blue-400/10 to-transparent rounded-full blur-2xl' />
<div className='relative flex items-center gap-4'>
{/* 头像 */}
<div className='relative group'>
<div className='absolute inset-0 bg-gradient-to-br from-blue-500 to-brand-to rounded-full blur-md opacity-50 group-hover:opacity-70 transition-opacity' />
<Avatar
size='large'
src={userAvatarUrl}
color={stringToColor(getUsername())}
className='!w-14 !h-14 relative ring-2 ring-white dark:ring-gray-800'
>
{getAvatarText()}
</Avatar>
<span className='absolute -bottom-0.5 -right-0.5 w-4 h-4 bg-emerald-500 border-2 border-white dark:border-gray-800 rounded-full' />
</div>
{/* 用户信息 */}
<div className='flex-1 min-w-0'>
<div className='flex items-center gap-2'>
<h3 className='text-lg font-bold text-gray-900 dark:text-white truncate'>
{getUsername()}
</h3>
{isRoot() && <Crown size={14} className='text-amber-500' />}
</div>
<div className='flex items-center gap-2 mt-1'>
<span
className={`inline-flex items-center px-2 py-0.5 text-xs font-medium text-white rounded-full bg-gradient-to-r ${roleInfo.color}`}
>
{roleInfo.text}
</span>
<Tooltip
content={userIdCopied ? t('已复制') : t('点击复制用户ID')}
>
<button
onClick={copyUserId}
className='inline-flex items-center gap-1 text-xs text-gray-400 hover:text-blue-500 dark:hover:text-blue-400 transition-colors cursor-pointer group'
>
<span>ID: {userState?.user?.id}</span>
{userIdCopied ? (
<Check size={12} className='text-emerald-500' />
) : (
<Copy
size={12}
className='opacity-0 group-hover:opacity-100 transition-opacity'
/>
)}
</button>
</Tooltip>
</div>
</div>
</div>
{/* 余额显示 */}
<div className='relative mt-4 p-3 bg-white/[0.58] dark:bg-white/[0.055] rounded-2xl border border-white/70 dark:border-white/10'>
<div className='flex items-center justify-between'>
<div className='flex items-center gap-2'>
<Coins size={16} className='text-blue-500' />
<span className='text-sm text-gray-600 dark:text-gray-400'>
{t('当前余额')}
</span>
</div>
<Sparkles size={14} className='text-amber-500' />
</div>
<div className='mt-1 text-xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-blue-600 to-brand-to dark:from-blue-400 dark:to-brand-to'>
{renderQuota(userState?.user?.quota)}
</div>
</div>
{/* 快捷统计 */}
<div className='relative mt-3 grid grid-cols-2 gap-2'>
<Tooltip content={t('历史消耗总额')}>
<div className='flex items-center gap-2 p-2 bg-white/[0.58] dark:bg-white/[0.055] rounded-xl border border-white/60 dark:border-white/10 cursor-default'>
<BarChart2 size={14} className='text-gray-400' />
<span className='text-xs text-gray-500 dark:text-gray-400 truncate'>
{renderQuota(userState?.user?.used_quota)}
</span>
</div>
</Tooltip>
<Tooltip content={t('用户分组')}>
<div className='flex items-center gap-2 p-2 bg-white/[0.58] dark:bg-white/[0.055] rounded-xl border border-white/60 dark:border-white/10 cursor-default'>
<Users size={14} className='text-gray-400' />
<span className='text-xs text-gray-500 dark:text-gray-400 truncate'>
{userState?.user?.group || t('默认')}
</span>
</div>
</Tooltip>
</div>
</div>
{/* 导航菜单 */}
<nav className='p-3 space-y-2'>
{NAV_ITEMS.map((item) => {
const Icon = item.icon;
const isActive = activeNav === item.key;
return (
<button
key={item.key}
onClick={() => setActiveNav(item.key)}
className={`relative w-full flex items-center gap-3 px-4 py-3 rounded-2xl transition-all duration-200 group border ${
isActive
? `bg-gradient-to-r ${item.activeClass} border-white/70 dark:border-white/10 shadow-[0_12px_28px_rgba(15,23,42,0.08)]`
: 'border-transparent hover:bg-white/[0.52] dark:hover:bg-white/[0.055]'
}`}
>
{/* 图标 */}
<div
className={`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${
isActive
? `bg-gradient-to-br ${item.gradient} shadow-lg`
: 'bg-white/[0.65] dark:bg-white/[0.06] group-hover:bg-white dark:group-hover:bg-white/[0.1]'
}`}
>
<Icon
size={18}
className={
isActive
? 'text-white'
: 'text-gray-500 dark:text-gray-400'
}
/>
</div>
{/* 标签 */}
<span className='flex-1 text-left min-w-0'>
<span
className={`block text-sm font-semibold transition-colors ${
isActive
? item.textClass
: 'text-gray-700 dark:text-gray-200'
}`}
>
{t(item.label)}
</span>
<span className='mt-0.5 block text-[11px] text-gray-400 dark:text-gray-500 truncate'>
{t(item.description)}
</span>
</span>
{/* 箭头指示器 */}
<ChevronRight
size={16}
className={`transition-all ${
isActive
? `${item.textClass} translate-x-0 opacity-100`
: 'text-gray-300 -translate-x-2 opacity-0 group-hover:translate-x-0 group-hover:opacity-100'
}`}
/>
{/* 选中指示条 */}
{isActive && (
<div className={`absolute left-0 w-1 h-8 bg-gradient-to-b ${item.gradient} rounded-r-full`} />
)}
</button>
);
})}
</nav>
</div>
</div>
{/* 右侧内容区 */}
<div className='flex-1 p-3 sm:p-4 overflow-auto relative z-10'>
<div className='min-h-full bg-white/[0.58] dark:bg-slate-950/[0.46] backdrop-blur-2xl rounded-2xl lg:rounded-[28px] border border-white/70 dark:border-white/10 shadow-[0_24px_80px_rgba(15,23,42,0.10)] p-4 sm:p-6'>
{renderContent()}
</div>
</div>
{/* 模态框 */}
<EmailBindModal
t={t}
showEmailBindModal={showEmailBindModal}
setShowEmailBindModal={setShowEmailBindModal}
inputs={inputs}
handleInputChange={handleInputChange}
sendVerificationCode={sendVerificationCode}
bindEmail={bindEmail}
disableButton={disableButton}
loading={loading}
countdown={countdown}
turnstileEnabled={turnstileEnabled}
turnstileSiteKey={turnstileSiteKey}
setTurnstileToken={setTurnstileToken}
/>
<WeChatBindModal
t={t}
showWeChatBindModal={showWeChatBindModal}
setShowWeChatBindModal={setShowWeChatBindModal}
inputs={inputs}
handleInputChange={handleInputChange}
bindWeChat={bindWeChat}
status={status}
/>
<AccountDeleteModal
t={t}
showAccountDeleteModal={showAccountDeleteModal}
setShowAccountDeleteModal={setShowAccountDeleteModal}
inputs={inputs}
handleInputChange={handleInputChange}
deleteAccount={deleteAccount}
userState={userState}
turnstileEnabled={turnstileEnabled}
turnstileSiteKey={turnstileSiteKey}
setTurnstileToken={setTurnstileToken}
/>
<ChangePasswordModal
t={t}
showChangePasswordModal={showChangePasswordModal}
setShowChangePasswordModal={setShowChangePasswordModal}
inputs={inputs}
handleInputChange={handleInputChange}
changePassword={changePassword}
hasPassword={hasPassword}
turnstileEnabled={turnstileEnabled}
turnstileSiteKey={turnstileSiteKey}
setTurnstileToken={setTurnstileToken}
/>
</div>
);
};
export default PersonalSetting;
@@ -0,0 +1,89 @@
/*
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 { Card, Spin } from '@douyinfe/semi-ui';
import { API, showError, toBoolean } from '../../helpers';
import { useTranslation } from 'react-i18next';
import RequestRateLimit from '../../pages/Setting/RateLimit/SettingsRequestRateLimit';
const RateLimitSetting = () => {
const { t: _t } = useTranslation();
let [inputs, setInputs] = useState({
ModelRequestRateLimitEnabled: false,
ModelRequestRateLimitCount: 0,
ModelRequestRateLimitSuccessCount: 1000,
ModelRequestRateLimitDurationMinutes: 1,
ModelRequestRateLimitGroup: '',
});
let [loading, setLoading] = useState(false);
const getOptions = async () => {
const res = await API.get('/api/option/');
const { success, message, data } = res.data;
if (success) {
let newInputs = {};
data.forEach((item) => {
if (item.key === 'ModelRequestRateLimitGroup') {
item.value = JSON.stringify(JSON.parse(item.value), null, 2);
}
if (item.key.endsWith('Enabled')) {
newInputs[item.key] = toBoolean(item.value);
} else {
newInputs[item.key] = item.value;
}
});
setInputs(newInputs);
} else {
showError(message);
}
};
async function onRefresh() {
try {
setLoading(true);
await getOptions();
// showSuccess('刷新成功');
} catch (error) {
showError('刷新失败');
} finally {
setLoading(false);
}
}
useEffect(() => {
onRefresh();
}, []);
return (
<>
<Spin spinning={loading} size='large'>
{/* AI请求速率限制 */}
<Card style={{ marginTop: '10px' }}>
<RequestRateLimit options={inputs} refresh={onRefresh} />
</Card>
</Spin>
</>
);
};
export default RateLimitSetting;
+140
View File
@@ -0,0 +1,140 @@
/*
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 { Card, Spin, Tabs } from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import GroupRatioSettings from '../../pages/Setting/Ratio/GroupRatioSettings';
import ModelRatioSettings from '../../pages/Setting/Ratio/ModelRatioSettings';
import ModelSettingsVisualEditor from '../../pages/Setting/Ratio/ModelSettingsVisualEditor';
import ModelRatioNotSetEditor from '../../pages/Setting/Ratio/ModelRationNotSetEditor';
import UpstreamRatioSync from '../../pages/Setting/Ratio/UpstreamRatioSync';
import ModelOfficialPriceSettings from '../../pages/Setting/Ratio/ModelOfficialPriceSettings';
import ModelCostSettings from '../../pages/Setting/Ratio/ModelCostSettings';
import { API, isRoot, showError, toBoolean } from '../../helpers';
const RatioSetting = () => {
const { t } = useTranslation();
let [inputs, setInputs] = useState({
ModelPrice: '',
ModelRatio: '',
CacheRatio: '',
CompletionRatio: '',
GroupRatio: '',
GroupGroupRatio: '',
ModelOfficialPrice: '',
ImageRatio: '',
AudioRatio: '',
AudioCompletionRatio: '',
AutoGroups: '',
DefaultUseAutoGroup: false,
ExposeRatioEnabled: false,
UserUsableGroups: '',
'group_ratio_setting.group_special_usable_group': '',
});
const [loading, setLoading] = useState(false);
const getOptions = async () => {
const res = await API.get('/api/option/');
const { success, message, data } = res.data;
if (success) {
let newInputs = {};
data.forEach((item) => {
if (item.value.startsWith('{') || item.value.startsWith('[')) {
try {
item.value = JSON.stringify(JSON.parse(item.value), null, 2);
} catch (e) {
// 如果后端返回的不是合法 JSON,直接展示
}
}
if (['DefaultUseAutoGroup', 'ExposeRatioEnabled'].includes(item.key)) {
newInputs[item.key] = toBoolean(item.value);
} else {
newInputs[item.key] = item.value;
}
});
setInputs(newInputs);
} else {
showError(message);
}
};
const onRefresh = async () => {
try {
setLoading(true);
await getOptions();
} catch (error) {
showError(t('刷新失败'));
} finally {
setLoading(false);
}
};
useEffect(() => {
onRefresh();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<Spin spinning={loading} size='large'>
{/* 模型倍率设置以及可视化编辑器 */}
<Card style={{ marginTop: '10px' }}>
<Tabs type='card'>
<Tabs.TabPane tab={t('模型倍率设置')} itemKey='model'>
<ModelRatioSettings options={inputs} refresh={onRefresh} />
</Tabs.TabPane>
<Tabs.TabPane tab={t('分组倍率设置')} itemKey='group'>
<GroupRatioSettings options={inputs} refresh={onRefresh} />
</Tabs.TabPane>
<Tabs.TabPane tab={t('可视化倍率设置')} itemKey='visual'>
<ModelSettingsVisualEditor options={inputs} refresh={onRefresh} />
</Tabs.TabPane>
{/* 原厂价 = 成本兜底基准、成本价 = 商业秘密:两个页签都只对 root 开放。
后端已分别由 delegationDeniedKeys 与整组 RootAuth 拦住,这里同步隐藏
入口——否则被下放 tab 的普通管理员会看到一个填了存不进去的页面。 */}
{isRoot() && (
<Tabs.TabPane tab={t('模型原厂价格')} itemKey='official_price'>
<ModelOfficialPriceSettings
options={inputs}
refresh={onRefresh}
/>
</Tabs.TabPane>
)}
{isRoot() && (
<Tabs.TabPane tab={t('模型成本价格')} itemKey='model_cost'>
<ModelCostSettings />
</Tabs.TabPane>
)}
<Tabs.TabPane tab={t('未设置倍率模型')} itemKey='unset_models'>
<ModelRatioNotSetEditor options={inputs} refresh={onRefresh} />
</Tabs.TabPane>
<Tabs.TabPane tab={t('上游倍率同步')} itemKey='upstream_sync'>
<UpstreamRatioSync options={inputs} refresh={onRefresh} />
</Tabs.TabPane>
</Tabs>
</Card>
</Spin>
);
};
export default RatioSetting;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,528 @@
/*
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 { useTranslation } from 'react-i18next';
import {
Card,
Table,
Button,
Modal,
Form,
Toast,
Popconfirm,
Switch,
Tag,
Progress,
Empty,
} from '@douyinfe/semi-ui';
import {
IconPlus,
IconDelete,
IconEdit,
IconUpload,
IconPlayCircle,
IconEyeOpened,
} from '@douyinfe/semi-icons';
import { API } from '../../helpers';
const TutorialVideoSetting = () => {
const { t } = useTranslation();
const [videos, setVideos] = useState([]);
const [loading, setLoading] = useState(false);
const [uploadModalVisible, setUploadModalVisible] = useState(false);
const [editModalVisible, setEditModalVisible] = useState(false);
const [previewModalVisible, setPreviewModalVisible] = useState(false);
const [currentVideo, setCurrentVideo] = useState(null);
const [uploading, setUploading] = useState(false);
const [uploadProgress, setUploadProgress] = useState(0);
// 加载视频列表
const loadVideos = async () => {
setLoading(true);
try {
const res = await API.get('/api/admin/tutorial/videos');
if (res.data.success) {
setVideos(res.data.data || []);
} else {
Toast.error(res.data.message || t('加载失败'));
}
} catch (error) {
console.error('Load videos error:', error);
Toast.error(t('加载视频列表失败'));
} finally {
setLoading(false);
}
};
useEffect(() => {
loadVideos();
}, []);
// 格式化时长
const formatDuration = (seconds) => {
if (!seconds) return '--';
const mins = Math.floor(seconds / 60);
const secs = seconds % 60;
return `${mins}:${secs.toString().padStart(2, '0')}`;
};
// 格式化文件大小
const formatFileSize = (bytes) => {
if (!bytes) return '--';
if (bytes < 1024 * 1024) {
return `${(bytes / 1024).toFixed(1)} KB`;
}
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
};
// 上传视频
const handleUpload = async (values) => {
const { title, description, video, thumbnail, duration } = values;
if (!video || video.length === 0) {
Toast.error(t('请选择视频文件'));
return;
}
// 检查视频文件实例是否存在
const videoFile = video[0]?.fileInstance;
if (!videoFile) {
Toast.error(t('视频文件无效,请重新选择'));
return;
}
const formData = new FormData();
formData.append('title', title);
formData.append('description', description || '');
formData.append('video', videoFile);
formData.append('duration', duration || 0);
if (thumbnail && thumbnail.length > 0 && thumbnail[0]?.fileInstance) {
formData.append('thumbnail', thumbnail[0].fileInstance);
}
setUploading(true);
setUploadProgress(0);
try {
const res = await API.post('/api/admin/tutorial/video/upload', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
onUploadProgress: (progressEvent) => {
const progress = Math.round(
(progressEvent.loaded * 100) / progressEvent.total,
);
setUploadProgress(progress);
},
});
if (res.data.success) {
Toast.success(t('上传成功'));
setUploadModalVisible(false);
loadVideos();
} else {
Toast.error(res.data.message || t('上传失败'));
}
} catch (error) {
console.error('Upload error:', error);
Toast.error(t('上传失败'));
} finally {
setUploading(false);
setUploadProgress(0);
}
};
// 更新视频信息
const handleUpdate = async (values) => {
if (!currentVideo) return;
try {
const res = await API.put(
`/api/admin/tutorial/video/${currentVideo.id}`,
values,
);
if (res.data.success) {
Toast.success(t('更新成功'));
setEditModalVisible(false);
setCurrentVideo(null);
loadVideos();
} else {
Toast.error(res.data.message || t('更新失败'));
}
} catch (error) {
console.error('Update error:', error);
Toast.error(t('更新失败'));
}
};
// 删除视频
const handleDelete = async (id) => {
try {
const res = await API.delete(`/api/admin/tutorial/video/${id}`);
if (res.data.success) {
Toast.success(t('删除成功'));
loadVideos();
} else {
Toast.error(res.data.message || t('删除失败'));
}
} catch (error) {
console.error('Delete error:', error);
Toast.error(t('删除失败'));
}
};
// 切换状态
const handleToggleStatus = async (video) => {
const newStatus = video.status === 1 ? 0 : 1;
try {
const res = await API.put(`/api/admin/tutorial/video/${video.id}`, {
status: newStatus,
});
if (res.data.success) {
Toast.success(newStatus === 1 ? t('已启用') : t('已禁用'));
loadVideos();
} else {
Toast.error(res.data.message || t('操作失败'));
}
} catch (error) {
console.error('Toggle status error:', error);
Toast.error(t('操作失败'));
}
};
// 预览视频
const handlePreview = (video) => {
setCurrentVideo(video);
setPreviewModalVisible(true);
};
// 编辑视频
const handleEdit = (video) => {
setCurrentVideo(video);
setEditModalVisible(true);
};
const columns = [
{
title: t('排序'),
dataIndex: 'sort_order',
width: 70,
render: (text) => <Tag color='blue'>{text}</Tag>,
},
{
title: t('标题'),
dataIndex: 'title',
width: 200,
ellipsis: true,
},
{
title: t('描述'),
dataIndex: 'description',
width: 200,
ellipsis: true,
render: (text) => text || '-',
},
{
title: t('时长'),
dataIndex: 'duration',
width: 80,
render: (text) => formatDuration(text),
},
{
title: t('大小'),
dataIndex: 'file_size',
width: 100,
render: (text) => formatFileSize(text),
},
{
title: t('状态'),
dataIndex: 'status',
width: 80,
render: (status, record) => (
<Switch
checked={status === 1}
onChange={() => handleToggleStatus(record)}
checkedText={t('启用')}
uncheckedText={t('禁用')}
/>
),
},
{
title: t('操作'),
width: 180,
render: (_, record) => (
<div style={{ display: 'flex', gap: 8 }}>
<Button
icon={<IconEyeOpened />}
size='small'
theme='borderless'
onClick={() => handlePreview(record)}
/>
<Button
icon={<IconEdit />}
size='small'
theme='borderless'
onClick={() => handleEdit(record)}
/>
<Popconfirm
title={t('确定删除这个视频吗?')}
content={t('删除后将无法恢复')}
onConfirm={() => handleDelete(record.id)}
>
<Button
icon={<IconDelete />}
size='small'
theme='borderless'
type='danger'
/>
</Popconfirm>
</div>
),
},
];
return (
<div>
<Card
title={
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<IconPlayCircle size='large' />
{t('教程视频管理')}
</div>
}
headerExtraContent={
<Button
icon={<IconPlus />}
theme='solid'
onClick={() => setUploadModalVisible(true)}
>
{t('上传视频')}
</Button>
}
>
<Table
// 列宽合计 910px,窄屏必须给横向滚动
scroll={{ x: 'max-content' }}
columns={columns}
dataSource={videos}
loading={loading}
rowKey='id'
pagination={false}
empty={
<Empty
image={
<IconPlayCircle
style={{ fontSize: 48, color: 'var(--semi-color-text-3)' }}
/>
}
title={t('暂无视频')}
description={t('点击上方按钮上传教程视频')}
/>
}
/>
</Card>
{/* 上传视频弹窗 */}
<Modal
title={t('上传教程视频')}
visible={uploadModalVisible}
onCancel={() => setUploadModalVisible(false)}
footer={null}
width={500}
>
<Form onSubmit={handleUpload}>
<Form.Input
field='title'
label={t('视频标题')}
placeholder={t('请输入视频标题')}
rules={[{ required: true, message: t('请输入视频标题') }]}
/>
<Form.TextArea
field='description'
label={t('视频描述')}
placeholder={t('请输入视频描述(可选)')}
rows={3}
/>
<Form.InputNumber
field='duration'
label={t('视频时长(秒)')}
placeholder={t('请输入视频时长')}
min={0}
/>
<Form.Upload
field='video'
label={t('视频文件')}
accept='video/mp4,video/webm,video/quicktime'
maxSize={500 * 1024} // 500MB in KB
limit={1}
rules={[{ required: true, message: t('请选择视频文件') }]}
>
<Button icon={<IconUpload />} theme='light'>
{t('选择视频 (mp4/webm/mov, 最大500MB)')}
</Button>
</Form.Upload>
<Form.Upload
field='thumbnail'
label={t('缩略图')}
accept='image/jpeg,image/png,image/webp'
maxSize={5 * 1024} // 5MB in KB
limit={1}
listType='picture'
>
<Button icon={<IconUpload />} theme='light'>
{t('选择缩略图(可选)')}
</Button>
</Form.Upload>
{uploading && (
<div style={{ marginBottom: 16 }}>
<Progress percent={uploadProgress} showInfo />
</div>
)}
<div
style={{
display: 'flex',
justifyContent: 'flex-end',
gap: 8,
marginTop: 16,
}}
>
<Button onClick={() => setUploadModalVisible(false)}>
{t('取消')}
</Button>
<Button type='primary' htmlType='submit' loading={uploading}>
{uploading ? t('上传中...') : t('上传')}
</Button>
</div>
</Form>
</Modal>
{/* 编辑视频弹窗 */}
<Modal
title={t('编辑视频信息')}
visible={editModalVisible}
onCancel={() => {
setEditModalVisible(false);
setCurrentVideo(null);
}}
footer={null}
width={500}
>
{currentVideo && (
<Form
onSubmit={handleUpdate}
initValues={{
title: currentVideo.title,
description: currentVideo.description,
sort_order: currentVideo.sort_order,
duration: currentVideo.duration,
}}
>
<Form.Input
field='title'
label={t('视频标题')}
placeholder={t('请输入视频标题')}
rules={[{ required: true, message: t('请输入视频标题') }]}
/>
<Form.TextArea
field='description'
label={t('视频描述')}
placeholder={t('请输入视频描述')}
rows={3}
/>
<Form.InputNumber
field='sort_order'
label={t('排序')}
placeholder={t('数字越小越靠前')}
min={0}
/>
<Form.InputNumber
field='duration'
label={t('视频时长(秒)')}
placeholder={t('请输入视频时长')}
min={0}
/>
<div
style={{
display: 'flex',
justifyContent: 'flex-end',
gap: 8,
marginTop: 16,
}}
>
<Button
onClick={() => {
setEditModalVisible(false);
setCurrentVideo(null);
}}
>
{t('取消')}
</Button>
<Button type='primary' htmlType='submit'>
{t('保存')}
</Button>
</div>
</Form>
)}
</Modal>
{/* 预览视频弹窗 */}
<Modal
title={currentVideo?.title || t('视频预览')}
visible={previewModalVisible}
onCancel={() => {
setPreviewModalVisible(false);
setCurrentVideo(null);
}}
footer={null}
width={800}
>
{currentVideo && (
<div
style={{
position: 'relative',
paddingTop: '56.25%',
background: '#000',
borderRadius: 8,
overflow: 'hidden',
}}
>
<video
src={currentVideo.signed_url}
poster={currentVideo.thumbnail_url}
controls
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
objectFit: 'contain',
}}
/>
</div>
)}
</Modal>
</div>
);
};
export default TutorialVideoSetting;
@@ -0,0 +1,43 @@
/*
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
*/
export const ENFORCE_CHECK_FIELDS = [
'input_enabled',
'output_enabled',
'text_enabled',
'image_enabled',
'video_enabled',
];
const BOOLEAN_FIELDS = ['enabled', 'confirm_enforce', ...ENFORCE_CHECK_FIELDS];
const toBoolean = (value) => value === true || value === 1 || value === 'true';
export const normalizeContentGuardConfig = (values = {}) => {
const normalized = { ...values };
for (const field of BOOLEAN_FIELDS) {
normalized[field] = toBoolean(values[field]);
}
if (normalized.mode === 'enforce') {
for (const field of ENFORCE_CHECK_FIELDS) {
normalized[field] = true;
}
}
return normalized;
};
@@ -0,0 +1,78 @@
/*
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 {
ENFORCE_CHECK_FIELDS,
normalizeContentGuardConfig,
} from './contentGuardConfig.js';
test('normalizeContentGuardConfig enables every check in enforce mode', () => {
const config = normalizeContentGuardConfig({
enabled: true,
mode: 'enforce',
confirm_enforce: true,
input_enabled: false,
output_enabled: undefined,
text_enabled: 0,
image_enabled: null,
video_enabled: '',
});
for (const field of ENFORCE_CHECK_FIELDS) {
assert.equal(config[field], true, `${field} should be enabled`);
}
assert.equal(config.enabled, true);
assert.equal(config.confirm_enforce, true);
});
test('normalizeContentGuardConfig converts form booleans explicitly', () => {
const config = normalizeContentGuardConfig({
enabled: 0,
mode: 'observe',
confirm_enforce: undefined,
input_enabled: true,
output_enabled: false,
text_enabled: 1,
image_enabled: null,
video_enabled: '',
});
assert.deepEqual(
{
enabled: config.enabled,
confirm_enforce: config.confirm_enforce,
input_enabled: config.input_enabled,
output_enabled: config.output_enabled,
text_enabled: config.text_enabled,
image_enabled: config.image_enabled,
video_enabled: config.video_enabled,
},
{
enabled: false,
confirm_enforce: false,
input_enabled: true,
output_enabled: false,
text_enabled: true,
image_enabled: false,
video_enabled: false,
},
);
});
@@ -0,0 +1,657 @@
/*
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 from 'react';
import {
Button,
Card,
Input,
Space,
Typography,
Avatar,
Tabs,
TabPane,
Popover,
Modal,
} from '@douyinfe/semi-ui';
import {
IconMail,
IconShield,
IconGithubLogo,
IconKey,
IconLock,
IconDelete,
} from '@douyinfe/semi-icons';
import { UserPlus, ShieldCheck } from 'lucide-react';
import {
TelegramBrandIcon,
WechatBrandIcon,
LinuxBrandIcon,
DiscordBrandIcon,
} from '../../../common/icons/BrandIcons';
import TelegramLoginButton from 'react-telegram-login';
import {
onGitHubOAuthClicked,
onOIDCClicked,
onLinuxDOOAuthClicked,
onDiscordOAuthClicked,
} from '../../../../helpers';
import TwoFASetting from '../components/TwoFASetting';
const AccountManagement = ({
t,
userState,
status,
systemToken,
setShowEmailBindModal,
setShowWeChatBindModal,
generateAccessToken,
handleSystemTokenClick,
setShowChangePasswordModal,
setShowAccountDeleteModal,
passkeyStatus,
passkeySupported,
passkeyRegisterLoading,
passkeyDeleteLoading,
onPasskeyRegister,
onPasskeyDelete,
}) => {
const renderAccountInfo = (accountId, label) => {
if (!accountId || accountId === '') {
return <span className='text-gray-500'>{t('未绑定')}</span>;
}
const popContent = (
<div className='text-xs p-2'>
<Typography.Paragraph copyable={{ content: accountId }}>
{accountId}
</Typography.Paragraph>
{label ? (
<div className='mt-1 text-[11px] text-gray-500'>{label}</div>
) : null}
</div>
);
return (
<Popover content={popContent} position='top' trigger='hover'>
<span className='block max-w-full truncate text-gray-600 hover:text-blue-600 cursor-pointer'>
{accountId}
</span>
</Popover>
);
};
const isBound = (accountId) => Boolean(accountId);
const [showTelegramBindModal, setShowTelegramBindModal] =
React.useState(false);
const passkeyEnabled = passkeyStatus?.enabled;
const lastUsedLabel = passkeyStatus?.last_used_at
? new Date(passkeyStatus.last_used_at).toLocaleString()
: t('尚未使用');
return (
<Card className='!rounded-2xl'>
{/* 卡片头部 */}
<div className='flex items-center mb-4'>
<Avatar size='small' color='teal' className='mr-3 shadow-md'>
<UserPlus 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>
<Tabs type='card' defaultActiveKey='binding'>
{/* 账户绑定 Tab */}
<TabPane
tab={
<div className='flex items-center'>
<UserPlus size={16} className='mr-2' />
{t('账户绑定')}
</div>
}
itemKey='binding'
>
<div className='py-4'>
<div className='grid grid-cols-1 lg:grid-cols-2 gap-4'>
{/* 邮箱绑定 */}
<Card className='!rounded-xl'>
<div className='flex items-center justify-between gap-3'>
<div className='flex items-center flex-1 min-w-0'>
<div className='w-10 h-10 rounded-full bg-slate-100 dark:bg-slate-700 flex items-center justify-center mr-3 flex-shrink-0'>
<IconMail
size='default'
className='text-slate-600 dark:text-slate-300'
/>
</div>
<div className='flex-1 min-w-0'>
<div className='font-medium text-gray-900'>
{t('邮箱')}
</div>
<div className='text-sm text-gray-500 truncate'>
{renderAccountInfo(
userState.user?.email,
t('邮箱地址'),
)}
</div>
</div>
</div>
<div className='flex-shrink-0'>
<Button
type='primary'
theme='outline'
size='small'
onClick={() => setShowEmailBindModal(true)}
>
{isBound(userState.user?.email)
? t('修改绑定')
: t('绑定')}
</Button>
</div>
</div>
</Card>
{/* 微信绑定 */}
<Card className='!rounded-xl'>
<div className='flex items-center justify-between gap-3'>
<div className='flex items-center flex-1 min-w-0'>
<div className='w-10 h-10 rounded-full bg-slate-100 dark:bg-slate-700 flex items-center justify-center mr-3 flex-shrink-0'>
<WechatBrandIcon
size={20}
color='currentColor'
className='text-slate-600 dark:text-slate-300'
/>
</div>
<div className='flex-1 min-w-0'>
<div className='font-medium text-gray-900'>
{t('微信')}
</div>
<div className='text-sm text-gray-500 truncate'>
{!status.wechat_login
? t('未启用')
: isBound(userState.user?.wechat_id)
? t('已绑定')
: t('未绑定')}
</div>
</div>
</div>
<div className='flex-shrink-0'>
<Button
type='primary'
theme='outline'
size='small'
disabled={!status.wechat_login}
onClick={() => setShowWeChatBindModal(true)}
>
{isBound(userState.user?.wechat_id)
? t('修改绑定')
: status.wechat_login
? t('绑定')
: t('未启用')}
</Button>
</div>
</div>
</Card>
{/* GitHub绑定 */}
<Card className='!rounded-xl'>
<div className='flex items-center justify-between gap-3'>
<div className='flex items-center flex-1 min-w-0'>
<div className='w-10 h-10 rounded-full bg-slate-100 dark:bg-slate-700 flex items-center justify-center mr-3 flex-shrink-0'>
<IconGithubLogo
size='default'
className='text-slate-600 dark:text-slate-300'
/>
</div>
<div className='flex-1 min-w-0'>
<div className='font-medium text-gray-900'>
{t('GitHub')}
</div>
<div className='text-sm text-gray-500 truncate'>
{renderAccountInfo(
userState.user?.github_id,
t('GitHub ID'),
)}
</div>
</div>
</div>
<div className='flex-shrink-0'>
<Button
type='primary'
theme='outline'
size='small'
onClick={() =>
onGitHubOAuthClicked(status.github_client_id)
}
disabled={
isBound(userState.user?.github_id) ||
!status.github_oauth
}
>
{status.github_oauth ? t('绑定') : t('未启用')}
</Button>
</div>
</div>
</Card>
{/* Discord绑定 */}
<Card className='!rounded-xl'>
<div className='flex items-center justify-between gap-3'>
<div className='flex items-center flex-1 min-w-0'>
<div className='w-10 h-10 rounded-full bg-slate-100 dark:bg-slate-700 flex items-center justify-center mr-3 flex-shrink-0'>
<DiscordBrandIcon
size={20}
color='currentColor'
className='text-slate-600 dark:text-slate-300'
/>
</div>
<div className='flex-1 min-w-0'>
<div className='font-medium text-gray-900'>
{t('Discord')}
</div>
<div className='text-sm text-gray-500 truncate'>
{renderAccountInfo(
userState.user?.discord_id,
t('Discord ID'),
)}
</div>
</div>
</div>
<div className='flex-shrink-0'>
<Button
type='primary'
theme='outline'
size='small'
onClick={() =>
onDiscordOAuthClicked(status.discord_client_id)
}
disabled={
isBound(userState.user?.discord_id) ||
!status.discord_oauth
}
>
{status.discord_oauth ? t('绑定') : t('未启用')}
</Button>
</div>
</div>
</Card>
{/* OIDC绑定 */}
<Card className='!rounded-xl'>
<div className='flex items-center justify-between gap-3'>
<div className='flex items-center flex-1 min-w-0'>
<div className='w-10 h-10 rounded-full bg-slate-100 dark:bg-slate-700 flex items-center justify-center mr-3 flex-shrink-0'>
<IconShield
size='default'
className='text-slate-600 dark:text-slate-300'
/>
</div>
<div className='flex-1 min-w-0'>
<div className='font-medium text-gray-900'>
{t('OIDC')}
</div>
<div className='text-sm text-gray-500 truncate'>
{renderAccountInfo(
userState.user?.oidc_id,
t('OIDC ID'),
)}
</div>
</div>
</div>
<div className='flex-shrink-0'>
<Button
type='primary'
theme='outline'
size='small'
onClick={() =>
onOIDCClicked(
status.oidc_authorization_endpoint,
status.oidc_client_id,
)
}
disabled={
isBound(userState.user?.oidc_id) || !status.oidc_enabled
}
>
{status.oidc_enabled ? t('绑定') : t('未启用')}
</Button>
</div>
</div>
</Card>
{/* Telegram绑定 */}
<Card className='!rounded-xl'>
<div className='flex items-center justify-between gap-3'>
<div className='flex items-center flex-1 min-w-0'>
<div className='w-10 h-10 rounded-full bg-slate-100 dark:bg-slate-700 flex items-center justify-center mr-3 flex-shrink-0'>
<TelegramBrandIcon
size={20}
color='currentColor'
className='text-slate-600 dark:text-slate-300'
/>
</div>
<div className='flex-1 min-w-0'>
<div className='font-medium text-gray-900'>
{t('Telegram')}
</div>
<div className='text-sm text-gray-500 truncate'>
{renderAccountInfo(
userState.user?.telegram_id,
t('Telegram ID'),
)}
</div>
</div>
</div>
<div className='flex-shrink-0'>
{status.telegram_oauth ? (
isBound(userState.user?.telegram_id) ? (
<Button
disabled
size='small'
type='primary'
theme='outline'
>
{t('已绑定')}
</Button>
) : (
<Button
type='primary'
theme='outline'
size='small'
onClick={() => setShowTelegramBindModal(true)}
>
{t('绑定')}
</Button>
)
) : (
<Button
disabled
size='small'
type='primary'
theme='outline'
>
{t('未启用')}
</Button>
)}
</div>
</div>
</Card>
<Modal
title={t('绑定 Telegram')}
visible={showTelegramBindModal}
onCancel={() => setShowTelegramBindModal(false)}
footer={null}
>
<div className='my-3 text-sm text-gray-600'>
{t('点击下方按钮通过 Telegram 完成绑定')}
</div>
<div className='flex justify-center'>
<div className='scale-90'>
<TelegramLoginButton
dataAuthUrl='/api/oauth/telegram/bind'
botName={status.telegram_bot_name}
/>
</div>
</div>
</Modal>
{/* LinuxDO绑定 */}
<Card className='!rounded-xl'>
<div className='flex items-center justify-between gap-3'>
<div className='flex items-center flex-1 min-w-0'>
<div className='w-10 h-10 rounded-full bg-slate-100 dark:bg-slate-700 flex items-center justify-center mr-3 flex-shrink-0'>
<LinuxBrandIcon
size={20}
color='currentColor'
className='text-slate-600 dark:text-slate-300'
/>
</div>
<div className='flex-1 min-w-0'>
<div className='font-medium text-gray-900'>
{t('LinuxDO')}
</div>
<div className='text-sm text-gray-500 truncate'>
{renderAccountInfo(
userState.user?.linux_do_id,
t('LinuxDO ID'),
)}
</div>
</div>
</div>
<div className='flex-shrink-0'>
<Button
type='primary'
theme='outline'
size='small'
onClick={() =>
onLinuxDOOAuthClicked(status.linuxdo_client_id)
}
disabled={
isBound(userState.user?.linux_do_id) ||
!status.linuxdo_oauth
}
>
{status.linuxdo_oauth ? t('绑定') : t('未启用')}
</Button>
</div>
</div>
</Card>
</div>
</div>
</TabPane>
{/* 安全设置 Tab */}
<TabPane
tab={
<div className='flex items-center'>
<ShieldCheck size={16} className='mr-2' />
{t('安全设置')}
</div>
}
itemKey='security'
>
<div className='py-4'>
<div className='space-y-6'>
<Space vertical className='w-full'>
{/* 系统访问令牌 */}
<Card className='!rounded-xl w-full'>
<div className='flex flex-col sm:flex-row items-start sm:justify-between gap-4'>
<div className='flex items-start w-full sm:w-auto'>
<div className='w-12 h-12 rounded-full bg-slate-100 flex items-center justify-center mr-4 flex-shrink-0'>
<IconKey size='large' className='text-slate-600' />
</div>
<div className='flex-1'>
<Typography.Title heading={6} className='mb-1'>
{t('系统访问令牌')}
</Typography.Title>
<Typography.Text type='tertiary' className='text-sm'>
{t('用于API调用的身份验证令牌,请妥善保管')}
</Typography.Text>
{systemToken && (
<div className='mt-3'>
<Input
readonly
value={systemToken}
onClick={handleSystemTokenClick}
size='large'
prefix={<IconKey />}
className='system-token-input'
/>
</div>
)}
</div>
</div>
<Button
type='primary'
theme='solid'
onClick={generateAccessToken}
className='!bg-slate-600 hover:!bg-slate-700 w-full sm:w-auto'
icon={<IconKey />}
>
{systemToken ? t('重新生成') : t('生成令牌')}
</Button>
</div>
</Card>
{/* 密码管理 */}
<Card className='!rounded-xl w-full'>
<div className='flex flex-col sm:flex-row items-start sm:justify-between gap-4'>
<div className='flex items-start w-full sm:w-auto'>
<div className='w-12 h-12 rounded-full bg-slate-100 flex items-center justify-center mr-4 flex-shrink-0'>
<IconLock size='large' className='text-slate-600' />
</div>
<div>
<Typography.Title heading={6} className='mb-1'>
{t('密码管理')}
</Typography.Title>
<Typography.Text type='tertiary' className='text-sm'>
{t('定期更改密码可以提高账户安全性')}
</Typography.Text>
</div>
</div>
<Button
type='primary'
theme='solid'
onClick={() => setShowChangePasswordModal(true)}
className='!bg-slate-600 hover:!bg-slate-700 w-full sm:w-auto'
icon={<IconLock />}
>
{t('修改密码')}
</Button>
</div>
</Card>
{/* Passkey 设置 */}
<Card className='!rounded-xl w-full'>
<div className='flex flex-col sm:flex-row items-start sm:justify-between gap-4'>
<div className='flex items-start w-full sm:w-auto'>
<div className='w-12 h-12 rounded-full bg-slate-100 flex items-center justify-center mr-4 flex-shrink-0'>
<IconKey size='large' className='text-slate-600' />
</div>
<div>
<Typography.Title heading={6} className='mb-1'>
{t('Passkey 登录')}
</Typography.Title>
<Typography.Text type='tertiary' className='text-sm'>
{passkeyEnabled
? t('已启用 Passkey,无需密码即可登录')
: t('使用 Passkey 实现免密且更安全的登录体验')}
</Typography.Text>
<div className='mt-2 text-xs text-gray-500 space-y-1'>
<div>
{t('最后使用时间')}:{lastUsedLabel}
</div>
{/*{passkeyEnabled && (*/}
{/* <div>*/}
{/* {t('备份支持')}:*/}
{/* {passkeyStatus?.backup_eligible*/}
{/* ? t('支持备份')*/}
{/* : t('不支持')}*/}
{/* ,{t('备份状态')}:*/}
{/* {passkeyStatus?.backup_state ? t('已备份') : t('未备份')}*/}
{/* </div>*/}
{/*)}*/}
{!passkeySupported && (
<div className='text-amber-600'>
{t('当前设备不支持 Passkey')}
</div>
)}
</div>
</div>
</div>
<Button
type={passkeyEnabled ? 'danger' : 'primary'}
theme={passkeyEnabled ? 'solid' : 'solid'}
onClick={
passkeyEnabled
? () => {
Modal.confirm({
title: t('确认解绑 Passkey'),
content: t(
'解绑后将无法使用 Passkey 登录,确定要继续吗?',
),
okText: t('确认解绑'),
cancelText: t('取消'),
okType: 'danger',
onOk: onPasskeyDelete,
});
}
: onPasskeyRegister
}
className={`w-full sm:w-auto ${passkeyEnabled ? '!bg-slate-500 hover:!bg-slate-600' : ''}`}
icon={<IconKey />}
disabled={!passkeySupported && !passkeyEnabled}
loading={
passkeyEnabled
? passkeyDeleteLoading
: passkeyRegisterLoading
}
>
{passkeyEnabled ? t('解绑 Passkey') : t('注册 Passkey')}
</Button>
</div>
</Card>
{/* 两步验证设置 */}
<TwoFASetting t={t} />
{/* 危险区域 */}
<Card className='!rounded-xl w-full'>
<div className='flex flex-col sm:flex-row items-start sm:justify-between gap-4'>
<div className='flex items-start w-full sm:w-auto'>
<div className='w-12 h-12 rounded-full bg-slate-100 flex items-center justify-center mr-4 flex-shrink-0'>
<IconDelete size='large' className='text-slate-600' />
</div>
<div>
<Typography.Title
heading={6}
className='mb-1 text-slate-700'
>
{t('删除账户')}
</Typography.Title>
<Typography.Text type='tertiary' className='text-sm'>
{t('此操作不可逆,所有数据将被永久删除')}
</Typography.Text>
</div>
</div>
<Button
type='danger'
theme='solid'
onClick={() => setShowAccountDeleteModal(true)}
className='w-full sm:w-auto !bg-slate-500 hover:!bg-slate-600'
icon={<IconDelete />}
>
{t('删除账户')}
</Button>
</div>
</Card>
</Space>
</div>
</div>
</TabPane>
</Tabs>
</Card>
);
};
export default AccountManagement;
@@ -0,0 +1,280 @@
/*
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 {
Empty,
Skeleton,
Space,
Tag,
Collapsible,
Tabs,
TabPane,
Typography,
Avatar,
} from '@douyinfe/semi-ui';
import {
IllustrationNoContent,
IllustrationNoContentDark,
} from '../../../common/illustrations';
import { IconChevronDown, IconChevronUp } from '@douyinfe/semi-icons';
import { Settings } from 'lucide-react';
import { renderModelTag, getModelCategories } from '../../../../helpers';
const ModelsList = ({ t, models, modelsLoading, copyText }) => {
const [isModelsExpanded, setIsModelsExpanded] = useState(() => {
// Initialize from localStorage if available
const savedState = localStorage.getItem('modelsExpanded');
return savedState ? JSON.parse(savedState) : false;
});
const [activeModelCategory, setActiveModelCategory] = useState('all');
const MODELS_DISPLAY_COUNT = 25; // 默认显示的模型数量
// Save models expanded state to localStorage whenever it changes
useEffect(() => {
localStorage.setItem('modelsExpanded', JSON.stringify(isModelsExpanded));
}, [isModelsExpanded]);
return (
<div className='py-4'>
{/* 卡片头部 */}
<div className='flex items-center mb-4'>
<Avatar size='small' color='green' 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='bg-gray-50 dark:bg-gray-800 rounded-xl'>
{modelsLoading ? (
// 骨架屏加载状态 - 模拟实际加载后的布局
<div className='space-y-4'>
{/* 模拟分类标签 */}
<div
className='mb-4'
style={{ borderBottom: '1px solid var(--semi-color-border)' }}
>
<div className='flex overflow-x-auto py-2 gap-2'>
{Array.from({ length: 8 }).map((_, index) => (
<Skeleton.Button
key={`cat-${index}`}
style={{
width: index === 0 ? 130 : 100 + Math.random() * 50,
height: 36,
borderRadius: 8,
}}
/>
))}
</div>
</div>
{/* 模拟模型标签列表 */}
<div className='flex flex-wrap gap-2'>
{Array.from({ length: 20 }).map((_, index) => (
<Skeleton.Button
key={`model-${index}`}
style={{
width: 100 + Math.random() * 100,
height: 32,
borderRadius: 16,
margin: '4px',
}}
/>
))}
</div>
</div>
) : models.length === 0 ? (
<div className='py-8'>
<Empty
image={
<IllustrationNoContent style={{ width: 150, height: 150 }} />
}
darkModeImage={
<IllustrationNoContentDark
style={{ width: 150, height: 150 }}
/>
}
description={t('没有可用模型')}
style={{ padding: '24px 0' }}
/>
</div>
) : (
<>
{/* 模型分类标签页 */}
<div className='mb-4'>
<Tabs
type='card'
activeKey={activeModelCategory}
onChange={(key) => setActiveModelCategory(key)}
className='mt-2'
collapsible
>
{Object.entries(getModelCategories(t)).map(
([key, category]) => {
// 计算该分类下的模型数量
const modelCount =
key === 'all'
? models.length
: models.filter((model) =>
category.filter({ model_name: model }),
).length;
if (modelCount === 0 && key !== 'all') return null;
return (
<TabPane
tab={
<span className='flex items-center gap-2'>
{category.icon && (
<span className='w-4 h-4'>{category.icon}</span>
)}
{category.label}
<Tag
color={
activeModelCategory === key ? 'red' : 'grey'
}
size='small'
shape='circle'
>
{modelCount}
</Tag>
</span>
}
itemKey={key}
key={key}
/>
);
},
)}
</Tabs>
</div>
<div className='bg-white dark:bg-gray-700 rounded-lg p-3'>
{(() => {
// 根据当前选中的分类过滤模型
const categories = getModelCategories(t);
const filteredModels =
activeModelCategory === 'all'
? models
: models.filter((model) =>
categories[activeModelCategory].filter({
model_name: model,
}),
);
// 如果过滤后没有模型,显示空状态
if (filteredModels.length === 0) {
return (
<Empty
image={
<IllustrationNoContent
style={{ width: 120, height: 120 }}
/>
}
darkModeImage={
<IllustrationNoContentDark
style={{ width: 120, height: 120 }}
/>
}
description={t('该分类下没有可用模型')}
style={{ padding: '16px 0' }}
/>
);
}
if (filteredModels.length <= MODELS_DISPLAY_COUNT) {
return (
<Space wrap>
{filteredModels.map((model) =>
renderModelTag(model, {
size: 'small',
shape: 'circle',
onClick: () => copyText(model),
}),
)}
</Space>
);
} else {
return (
<>
<Collapsible isOpen={isModelsExpanded}>
<Space wrap>
{filteredModels.map((model) =>
renderModelTag(model, {
size: 'small',
shape: 'circle',
onClick: () => copyText(model),
}),
)}
<Tag
color='grey'
type='light'
className='cursor-pointer !rounded-lg'
onClick={() => setIsModelsExpanded(false)}
icon={<IconChevronUp />}
>
{t('收起')}
</Tag>
</Space>
</Collapsible>
{!isModelsExpanded && (
<Space wrap>
{filteredModels
.slice(0, MODELS_DISPLAY_COUNT)
.map((model) =>
renderModelTag(model, {
size: 'small',
shape: 'circle',
onClick: () => copyText(model),
}),
)}
<Tag
color='grey'
type='light'
className='cursor-pointer !rounded-lg'
onClick={() => setIsModelsExpanded(true)}
icon={<IconChevronDown />}
>
{t('更多')}{' '}
{filteredModels.length - MODELS_DISPLAY_COUNT}{' '}
{t('个模型')}
</Tag>
</Space>
)}
</>
);
}
})()}
</div>
</>
)}
</div>
</div>
);
};
export default ModelsList;
@@ -0,0 +1,899 @@
/*
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, { useRef, useEffect, useState, useContext } from 'react';
import {
Button,
Typography,
Card,
Avatar,
Form,
Radio,
Toast,
Tabs,
TabPane,
Switch,
Row,
Col,
} from '@douyinfe/semi-ui';
import { IconMail, IconKey, IconBell, IconLink } from '@douyinfe/semi-icons';
import { ShieldCheck, Bell, DollarSign, Settings } from 'lucide-react';
import {
renderQuotaWithPrompt,
API,
showSuccess,
showError,
} from '../../../../helpers';
import CodeViewer from '../../../playground/CodeViewer';
import { StatusContext } from '../../../../context/Status';
import { UserContext } from '../../../../context/User';
import { useUserPermissions } from '../../../../hooks/common/useUserPermissions';
import { useSidebar } from '../../../../hooks/common/useSidebar';
const NotificationSettings = ({
t,
notificationSettings,
handleNotificationSettingChange,
saveNotificationSettings,
}) => {
const formApiRef = useRef(null);
const [statusState] = useContext(StatusContext);
const [_userState] = useContext(UserContext);
// 左侧边栏设置相关状态
const [sidebarLoading, setSidebarLoading] = useState(false);
const [activeTabKey, setActiveTabKey] = useState('notification');
const [sidebarModulesUser, setSidebarModulesUser] = useState({
chat: {
enabled: true,
playground: true,
chat: true,
},
console: {
enabled: true,
detail: true,
token: true,
log: true,
midjourney: true,
task: true,
},
personal: {
enabled: true,
topup: true,
personal: true,
},
admin: {
enabled: true,
channel: true,
models: true,
redemption: true,
user: true,
setting: true,
},
});
const [adminConfig, setAdminConfig] = useState(null);
// 使用后端权限验证替代前端角色判断
const {
hasSidebarSettingsPermission,
isSidebarSectionAllowed,
isSidebarModuleAllowed,
} = useUserPermissions();
// 使用useSidebar钩子获取刷新方法
const { refreshUserConfig } = useSidebar();
// 左侧边栏设置处理函数
const handleSectionChange = (sectionKey) => {
return (checked) => {
const newModules = {
...sidebarModulesUser,
[sectionKey]: {
...sidebarModulesUser[sectionKey],
enabled: checked,
},
};
setSidebarModulesUser(newModules);
};
};
const handleModuleChange = (sectionKey, moduleKey) => {
return (checked) => {
const newModules = {
...sidebarModulesUser,
[sectionKey]: {
...sidebarModulesUser[sectionKey],
[moduleKey]: checked,
},
};
setSidebarModulesUser(newModules);
};
};
const saveSidebarSettings = async () => {
setSidebarLoading(true);
try {
const res = await API.put('/api/user/self', {
sidebar_modules: JSON.stringify(sidebarModulesUser),
});
if (res.data.success) {
showSuccess(t('侧边栏设置保存成功'));
// 刷新useSidebar钩子中的用户配置,实现实时更新
await refreshUserConfig();
} else {
showError(res.data.message);
}
} catch (error) {
showError(t('保存失败'));
}
setSidebarLoading(false);
};
const resetSidebarModules = () => {
const defaultConfig = {
chat: { enabled: true, playground: true, chat: true },
console: {
enabled: true,
detail: true,
token: true,
log: true,
midjourney: true,
task: true,
},
personal: { enabled: true, topup: true, personal: true },
admin: {
enabled: true,
channel: true,
models: true,
redemption: true,
user: true,
setting: true,
},
};
setSidebarModulesUser(defaultConfig);
};
// 加载左侧边栏配置
useEffect(() => {
const loadSidebarConfigs = async () => {
try {
// 获取管理员全局配置
if (statusState?.status?.SidebarModulesAdmin) {
const adminConf = JSON.parse(statusState.status.SidebarModulesAdmin);
setAdminConfig(adminConf);
}
// 获取用户个人配置
const userRes = await API.get('/api/user/self');
if (userRes.data.success && userRes.data.data.sidebar_modules) {
const userConf = JSON.parse(userRes.data.data.sidebar_modules);
setSidebarModulesUser(userConf);
}
} catch (error) {
console.error('加载边栏配置失败:', error);
}
};
loadSidebarConfigs();
}, [statusState]);
// 初始化表单值
useEffect(() => {
if (formApiRef.current && notificationSettings) {
formApiRef.current.setValues(notificationSettings);
}
}, [notificationSettings]);
// 处理表单字段变化
const handleFormChange = (field, value) => {
handleNotificationSettingChange(field, value);
};
// 检查功能是否被管理员允许
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),
);
// 表单提交
const handleSubmit = () => {
if (formApiRef.current) {
formApiRef.current
.validate()
.then(() => {
saveNotificationSettings();
})
.catch((errors) => {
console.log('表单验证失败:', errors);
Toast.error(t('请检查表单填写是否正确'));
});
} else {
saveNotificationSettings();
}
};
return (
<Card
className='!rounded-2xl shadow-sm border-0'
footer={
<div className='flex justify-end gap-3'>
{activeTabKey === 'sidebar' ? (
// 边栏设置标签页的按钮
<>
<Button
type='tertiary'
onClick={resetSidebarModules}
className='!rounded-lg'
>
{t('重置为默认')}
</Button>
<Button
type='primary'
onClick={saveSidebarSettings}
loading={sidebarLoading}
className='!rounded-lg'
>
{t('保存设置')}
</Button>
</>
) : (
// 其他标签页的通用保存按钮
<Button type='primary' onClick={handleSubmit}>
{t('保存设置')}
</Button>
)}
</div>
}
>
{/* 卡片头部 */}
<div className='flex items-center mb-4'>
<Avatar size='small' color='blue' className='mr-3 shadow-md'>
<Bell 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>
<Form
getFormApi={(api) => (formApiRef.current = api)}
initValues={notificationSettings}
onSubmit={handleSubmit}
>
{() => (
<Tabs
type='card'
defaultActiveKey='notification'
onChange={(key) => setActiveTabKey(key)}
>
{/* 通知配置 Tab */}
<TabPane
tab={
<div className='flex items-center'>
<Bell size={16} className='mr-2' />
{t('通知配置')}
</div>
}
itemKey='notification'
>
<div className='py-4'>
<Form.RadioGroup
field='warningType'
label={t('通知方式')}
initValue={notificationSettings.warningType}
onChange={(value) => handleFormChange('warningType', value)}
rules={[{ required: true, message: t('请选择通知方式') }]}
>
<Radio value='email'>{t('邮件通知')}</Radio>
<Radio value='webhook'>{t('Webhook通知')}</Radio>
<Radio value='bark'>{t('Bark通知')}</Radio>
<Radio value='gotify'>{t('Gotify通知')}</Radio>
</Form.RadioGroup>
<Form.AutoComplete
field='warningThreshold'
label={
<span>
{t('额度预警阈值')}{' '}
{renderQuotaWithPrompt(
notificationSettings.warningThreshold,
)}
</span>
}
placeholder={t('请输入预警额度')}
data={[
{ value: 100000, label: '0.2$' },
{ value: 500000, label: '1$' },
{ value: 1000000, label: '5$' },
{ value: 5000000, label: '10$' },
]}
onChange={(val) => handleFormChange('warningThreshold', val)}
prefix={<IconBell />}
extraText={t(
'当剩余额度低于此数值时,系统将通过选择的方式发送通知',
)}
style={{ width: '100%', maxWidth: '300px' }}
rules={[
{ required: true, message: t('请输入预警阈值') },
{
validator: (rule, value) => {
const numValue = Number(value);
if (isNaN(numValue) || numValue <= 0) {
return Promise.reject(t('预警阈值必须为正数'));
}
return Promise.resolve();
},
},
]}
/>
{/* 邮件通知设置 */}
{notificationSettings.warningType === 'email' && (
<Form.Input
field='notificationEmail'
label={t('通知邮箱')}
placeholder={t('留空则使用账号绑定的邮箱')}
onChange={(val) =>
handleFormChange('notificationEmail', val)
}
prefix={<IconMail />}
extraText={t(
'设置用于接收额度预警的邮箱地址,不填则使用账号绑定的邮箱',
)}
showClear
/>
)}
{/* Webhook通知设置 */}
{notificationSettings.warningType === 'webhook' && (
<>
<Form.Input
field='webhookUrl'
label={t('Webhook地址')}
placeholder={t(
'请输入Webhook地址,例如: https://example.com/webhook',
)}
onChange={(val) => handleFormChange('webhookUrl', val)}
prefix={<IconLink />}
extraText={t(
'只支持HTTPS,系统将以POST方式发送通知,请确保地址可以接收POST请求',
)}
showClear
rules={[
{
required:
notificationSettings.warningType === 'webhook',
message: t('请输入Webhook地址'),
},
{
pattern: /^https:\/\/.+/,
message: t('Webhook地址必须以https://开头'),
},
]}
/>
<Form.Input
field='webhookSecret'
label={t('接口凭证')}
placeholder={t('请输入密钥')}
onChange={(val) => handleFormChange('webhookSecret', val)}
prefix={<IconKey />}
extraText={t(
'密钥将以Bearer方式添加到请求头中,用于验证webhook请求的合法性',
)}
showClear
/>
<Form.Slot label={t('Webhook请求结构说明')}>
<div>
<div style={{ height: '200px', marginBottom: '12px' }}>
<CodeViewer
content={{
type: 'quota_exceed',
title: '额度预警通知',
content:
'您的额度即将用尽,当前剩余额度为 {{value}}',
values: ['¥0.99'],
timestamp: 1739950503,
}}
title='webhook'
language='json'
/>
</div>
<div className='text-xs text-gray-500 leading-relaxed'>
<div>
<strong>type:</strong>{' '}
{t('通知类型 (quota_exceed: 额度预警)')}{' '}
</div>
<div>
<strong>title:</strong> {t('通知标题')}
</div>
<div>
<strong>content:</strong>{' '}
{t('通知内容,支持 {{value}} 变量占位符')}
</div>
<div>
<strong>values:</strong>{' '}
{t('按顺序替换content中的变量占位符')}
</div>
<div>
<strong>timestamp:</strong> {t('Unix时间戳')}
</div>
</div>
</div>
</Form.Slot>
</>
)}
{/* Bark推送设置 */}
{notificationSettings.warningType === 'bark' && (
<>
<Form.Input
field='barkUrl'
label={t('Bark推送URL')}
placeholder={t(
'请输入Bark推送URL,例如: https://api.day.app/yourkey/{{title}}/{{content}}',
)}
onChange={(val) => handleFormChange('barkUrl', val)}
prefix={<IconLink />}
extraText={t(
'支持HTTP和HTTPS,模板变量: {{title}} (通知标题), {{content}} (通知内容)',
)}
showClear
rules={[
{
required: notificationSettings.warningType === 'bark',
message: t('请输入Bark推送URL'),
},
{
pattern: /^https?:\/\/.+/,
message: t('Bark推送URL必须以http://或https://开头'),
},
]}
/>
<div className='mt-3 p-4 bg-gray-50/50 rounded-xl'>
<div className='text-sm text-gray-700 mb-3'>
<strong>{t('模板示例')}</strong>
</div>
<div className='text-xs text-gray-600 font-mono bg-white p-3 rounded-lg shadow-sm mb-4'>
https://api.day.app/yourkey/{'{{title}}'}/
{'{{content}}'}?sound=alarm&group=quota
</div>
<div className='text-xs text-gray-500 space-y-2'>
<div>
• <strong>{'title'}:</strong> {t('通知标题')}
</div>
<div>
• <strong>{'content'}:</strong> {t('通知内容')}
</div>
<div className='mt-3 pt-3 border-t border-gray-200'>
<span className='text-gray-400'>
{t('更多参数请参考')}
</span>{' '}
<a
href='https://github.com/Finb/Bark'
target='_blank'
rel='noopener noreferrer'
className='text-blue-500 hover:text-blue-600 font-medium'
>
Bark {t('官方文档')}
</a>
</div>
</div>
</div>
</>
)}
{/* Gotify推送设置 */}
{notificationSettings.warningType === 'gotify' && (
<>
<Form.Input
field='gotifyUrl'
label={t('Gotify服务器地址')}
placeholder={t(
'请输入Gotify服务器地址,例如: https://gotify.example.com',
)}
onChange={(val) => handleFormChange('gotifyUrl', val)}
prefix={<IconLink />}
extraText={t(
'支持HTTP和HTTPS,填写Gotify服务器的完整URL地址',
)}
showClear
rules={[
{
required:
notificationSettings.warningType === 'gotify',
message: t('请输入Gotify服务器地址'),
},
{
pattern: /^https?:\/\/.+/,
message: t(
'Gotify服务器地址必须以http://或https://开头',
),
},
]}
/>
<Form.Input
field='gotifyToken'
label={t('Gotify应用令牌')}
placeholder={t('请输入Gotify应用令牌')}
onChange={(val) => handleFormChange('gotifyToken', val)}
prefix={<IconKey />}
extraText={t(
'在Gotify服务器创建应用后获得的令牌,用于发送通知',
)}
showClear
rules={[
{
required:
notificationSettings.warningType === 'gotify',
message: t('请输入Gotify应用令牌'),
},
]}
/>
<Form.AutoComplete
field='gotifyPriority'
label={t('消息优先级')}
placeholder={t('请选择消息优先级')}
data={[
{ value: 0, label: t('0 - 最低') },
{ value: 2, label: t('2 - 低') },
{ value: 5, label: t('5 - 正常(默认)') },
{ value: 8, label: t('8 - 高') },
{ value: 10, label: t('10 - 最高') },
]}
onChange={(val) =>
handleFormChange('gotifyPriority', val)
}
prefix={<IconBell />}
extraText={t('消息优先级,范围0-10,默认为5')}
style={{ width: '100%', maxWidth: '300px' }}
/>
<div className='mt-3 p-4 bg-gray-50/50 rounded-xl'>
<div className='text-sm text-gray-700 mb-3'>
<strong>{t('配置说明')}</strong>
</div>
<div className='text-xs text-gray-500 space-y-2'>
<div>
1. {t('在Gotify服务器的应用管理中创建新应用')}
</div>
<div>
2.{' '}
{t(
'复制应用的令牌(Token)并填写到上方的应用令牌字段',
)}
</div>
<div>3. {t('填写Gotify服务器的完整URL地址')}</div>
<div className='mt-3 pt-3 border-t border-gray-200'>
<span className='text-gray-400'>
{t('更多信息请参考')}
</span>{' '}
<a
href='https://gotify.net/'
target='_blank'
rel='noopener noreferrer'
className='text-blue-500 hover:text-blue-600 font-medium'
>
Gotify {t('官方文档')}
</a>
</div>
</div>
</div>
</>
)}
</div>
</TabPane>
{/* 价格设置 Tab */}
<TabPane
tab={
<div className='flex items-center'>
<DollarSign size={16} className='mr-2' />
{t('价格设置')}
</div>
}
itemKey='pricing'
>
<div className='py-4'>
<Form.Switch
field='acceptUnsetModelRatioModel'
label={t('接受未设置价格模型')}
checkedText={t('开')}
uncheckedText={t('关')}
onChange={(value) =>
handleFormChange('acceptUnsetModelRatioModel', value)
}
extraText={t(
'当模型没有设置价格时仍接受调用,仅当您信任该网站时使用,可能会产生高额费用',
)}
/>
</div>
</TabPane>
{/* 隐私设置 Tab */}
<TabPane
tab={
<div className='flex items-center'>
<ShieldCheck size={16} className='mr-2' />
{t('隐私设置')}
</div>
}
itemKey='privacy'
>
<div className='py-4'>
<Form.Switch
field='recordIpLog'
label={t('记录请求与错误日志IP')}
checkedText={t('开')}
uncheckedText={t('关')}
onChange={(value) => handleFormChange('recordIpLog', value)}
extraText={t(
'开启后,仅"消费"和"错误"日志将记录您的客户端IP地址',
)}
/>
</div>
</TabPane>
{/* 左侧边栏设置 Tab - 根据后端权限控制显示 */}
{hasSidebarSettingsPermission() && (
<TabPane
tab={
<div className='flex items-center'>
<Settings size={16} className='mr-2' />
{t('边栏设置')}
</div>
}
itemKey='sidebar'
>
<div className='py-4'>
<div className='mb-4'>
<Typography.Text
type='secondary'
size='small'
style={{
fontSize: '12px',
lineHeight: '1.5',
color: 'var(--semi-color-text-2)',
}}
>
{t('您可以个性化设置侧边栏的要显示功能')}
</Typography.Text>
</div>
{/* 边栏设置功能区域容器 */}
<div
className='border rounded-xl p-4'
style={{
borderColor: 'var(--semi-color-border)',
backgroundColor: 'var(--semi-color-bg-1)',
}}
>
{sectionConfigs.map((section) => (
<div key={section.key} className='mb-6'>
{/* 区域标题和总开关 */}
<div
className='flex justify-between items-center mb-4 p-4 rounded-lg'
style={{
backgroundColor: 'var(--semi-color-fill-0)',
border: '1px solid var(--semi-color-border-light)',
borderColor: 'var(--semi-color-fill-1)',
}}
>
<div>
<div className='font-semibold text-base text-gray-900 mb-1'>
{section.title}
</div>
<Typography.Text
type='secondary'
size='small'
style={{
fontSize: '12px',
lineHeight: '1.5',
color: 'var(--semi-color-text-2)',
}}
>
{section.description}
</Typography.Text>
</div>
<Switch
checked={sidebarModulesUser[section.key]?.enabled}
onChange={handleSectionChange(section.key)}
size='default'
/>
</div>
{/* 功能模块网格 */}
<Row gutter={[12, 12]}>
{section.modules
.filter((module) =>
isAllowedByAdmin(section.key, module.key),
)
.map((module) => (
<Col
key={module.key}
xs={24}
sm={24}
md={12}
lg={8}
xl={8}
>
<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>
<Typography.Text
type='secondary'
size='small'
className='block'
style={{
fontSize: '12px',
lineHeight: '1.5',
color: 'var(--semi-color-text-2)',
marginTop: '4px',
}}
>
{module.description}
</Typography.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>{' '}
{/* 关闭边栏设置功能区域容器 */}
</div>
</TabPane>
)}
</Tabs>
)}
</Form>
</Card>
);
};
export default NotificationSettings;
@@ -0,0 +1,723 @@
/*
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 { API, showError, showSuccess, showWarning } from '../../../../helpers';
import {
Banner,
Button,
Card,
Checkbox,
Divider,
Input,
Modal,
Tag,
Typography,
Steps,
Space,
Badge,
} from '@douyinfe/semi-ui';
import {
IconShield,
IconAlertTriangle,
IconRefresh,
IconCopy,
} from '@douyinfe/semi-icons';
import React, { useEffect, useState } from 'react';
import { QRCodeSVG } from 'qrcode.react';
const { Text, Paragraph } = Typography;
const TwoFASetting = ({ t }) => {
const [loading, setLoading] = useState(false);
const [status, setStatus] = useState({
enabled: false,
locked: false,
backup_codes_remaining: 0,
});
// 模态框状态
const [setupModalVisible, setSetupModalVisible] = useState(false);
const [, setEnableModalVisible] = useState(false);
const [disableModalVisible, setDisableModalVisible] = useState(false);
const [backupModalVisible, setBackupModalVisible] = useState(false);
// 表单数据
const [setupData, setSetupData] = useState(null);
const [verificationCode, setVerificationCode] = useState('');
const [backupCodes, setBackupCodes] = useState([]);
const [confirmDisable, setConfirmDisable] = useState(false);
const [currentStep, setCurrentStep] = useState(0);
// 获取2FA状态
const fetchStatus = async () => {
try {
const res = await API.get('/api/user/2fa/status');
if (res.data.success) {
setStatus(res.data.data);
}
} catch (error) {
showError(t('获取2FA状态失败'));
}
};
useEffect(() => {
fetchStatus();
}, []);
// 初始化2FA设置
const handleSetup2FA = async () => {
setLoading(true);
try {
const res = await API.post('/api/user/2fa/setup');
if (res.data.success) {
setSetupData(res.data.data);
setSetupModalVisible(true);
setCurrentStep(0);
} else {
showError(res.data.message);
}
} catch (error) {
showError(t('设置2FA失败'));
} finally {
setLoading(false);
}
};
// 启用2FA
const handleEnable2FA = async () => {
if (!verificationCode) {
showWarning(t('请输入验证码'));
return;
}
setLoading(true);
try {
const res = await API.post('/api/user/2fa/enable', {
code: verificationCode,
});
if (res.data.success) {
showSuccess(t('两步验证启用成功!'));
setEnableModalVisible(false);
setSetupModalVisible(false);
setVerificationCode('');
setCurrentStep(0);
fetchStatus();
} else {
showError(res.data.message);
}
} catch (error) {
showError(t('启用2FA失败'));
} finally {
setLoading(false);
}
};
// 禁用2FA
const handleDisable2FA = async () => {
if (!verificationCode) {
showWarning(t('请输入验证码或备用码'));
return;
}
if (!confirmDisable) {
showWarning(t('请确认您已了解禁用两步验证的后果'));
return;
}
setLoading(true);
try {
const res = await API.post('/api/user/2fa/disable', {
code: verificationCode,
});
if (res.data.success) {
showSuccess(t('两步验证已禁用'));
setDisableModalVisible(false);
setVerificationCode('');
setConfirmDisable(false);
fetchStatus();
} else {
showError(res.data.message);
}
} catch (error) {
showError(t('禁用2FA失败'));
} finally {
setLoading(false);
}
};
// 重新生成备用码
const handleRegenerateBackupCodes = async () => {
if (!verificationCode) {
showWarning(t('请输入验证码'));
return;
}
setLoading(true);
try {
const res = await API.post('/api/user/2fa/backup_codes', {
code: verificationCode,
});
if (res.data.success) {
setBackupCodes(res.data.data.backup_codes);
showSuccess(t('备用码重新生成成功'));
setVerificationCode('');
fetchStatus();
} else {
showError(res.data.message);
}
} catch (error) {
showError(t('重新生成备用码失败'));
} finally {
setLoading(false);
}
};
// 通用复制函数
const copyTextToClipboard = (text, successMessage = t('已复制到剪贴板')) => {
navigator.clipboard
.writeText(text)
.then(() => {
showSuccess(successMessage);
})
.catch(() => {
showError(t('复制失败,请手动复制'));
});
};
const copyBackupCodes = () => {
const codesText = backupCodes.join('\n');
copyTextToClipboard(codesText, t('备用码已复制到剪贴板'));
};
// 备用码展示组件
const BackupCodesDisplay = ({ codes, title, onCopy }) => {
return (
<Card className='!rounded-xl' style={{ width: '100%' }}>
<div className='space-y-3'>
<div className='flex items-center justify-between'>
<Text strong className='text-slate-700 dark:text-slate-200'>
{title}
</Text>
</div>
<div className='grid grid-cols-1 sm:grid-cols-2 gap-2'>
{codes.map((code, index) => (
<div key={index} className='rounded-lg p-3'>
<div className='flex items-center justify-between'>
<Text
code
className='text-sm font-mono text-slate-700 dark:text-slate-200'
>
{code}
</Text>
<Text type='quaternary' className='text-xs'>
#{(index + 1).toString().padStart(2, '0')}
</Text>
</div>
</div>
))}
</div>
<Divider margin={12} />
<Button
type='primary'
theme='solid'
icon={<IconCopy />}
onClick={onCopy}
className='!rounded-lg !bg-slate-600 hover:!bg-slate-700 w-full'
>
{t('复制所有代码')}
</Button>
</div>
</Card>
);
};
// 渲染设置模态框footer
const renderSetupModalFooter = () => {
return (
<>
{currentStep > 0 && (
<Button
onClick={() => setCurrentStep(currentStep - 1)}
className='!rounded-lg'
>
{t('上一步')}
</Button>
)}
{currentStep < 2 ? (
<Button
type='primary'
theme='solid'
onClick={() => setCurrentStep(currentStep + 1)}
className='!rounded-lg !bg-slate-600 hover:!bg-slate-700'
>
{t('下一步')}
</Button>
) : (
<Button
type='primary'
theme='solid'
loading={loading}
onClick={() => {
if (!verificationCode) {
showWarning(t('请输入验证码'));
return;
}
handleEnable2FA();
}}
className='!rounded-lg !bg-slate-600 hover:!bg-slate-700'
>
{t('完成设置并启用两步验证')}
</Button>
)}
</>
);
};
// 渲染禁用模态框footer
const renderDisableModalFooter = () => {
return (
<>
<Button
onClick={() => {
setDisableModalVisible(false);
setVerificationCode('');
setConfirmDisable(false);
}}
className='!rounded-lg'
>
{t('取消')}
</Button>
<Button
type='danger'
theme='solid'
loading={loading}
disabled={!confirmDisable || !verificationCode}
onClick={handleDisable2FA}
className='!rounded-lg !bg-slate-500 hover:!bg-slate-600'
>
{t('确认禁用')}
</Button>
</>
);
};
// 渲染重新生成模态框footer
const renderRegenerateModalFooter = () => {
if (backupCodes.length > 0) {
return (
<Button
type='primary'
theme='solid'
onClick={() => {
setBackupModalVisible(false);
setVerificationCode('');
setBackupCodes([]);
}}
className='!rounded-lg !bg-slate-600 hover:!bg-slate-700'
>
{t('完成')}
</Button>
);
}
return (
<>
<Button
onClick={() => {
setBackupModalVisible(false);
setVerificationCode('');
setBackupCodes([]);
}}
className='!rounded-lg'
>
{t('取消')}
</Button>
<Button
type='primary'
theme='solid'
loading={loading}
disabled={!verificationCode}
onClick={handleRegenerateBackupCodes}
className='!rounded-lg !bg-slate-600 hover:!bg-slate-700'
>
{t('生成新的备用码')}
</Button>
</>
);
};
return (
<>
<Card className='!rounded-xl w-full'>
<div className='flex flex-col sm:flex-row items-start sm:justify-between gap-4'>
<div className='flex items-start w-full sm:w-auto'>
<div className='w-12 h-12 rounded-full bg-slate-100 dark:bg-slate-700 flex items-center justify-center mr-4 flex-shrink-0'>
<IconShield
size='large'
className='text-slate-600 dark:text-slate-300'
/>
</div>
<div className='flex-1'>
<div className='flex items-center gap-2 mb-1'>
<Typography.Title heading={6} className='mb-0'>
{t('两步验证设置')}
</Typography.Title>
{status.enabled ? (
<Tag color='green' shape='circle' size='small'>
{t('已启用')}
</Tag>
) : (
<Tag color='red' shape='circle' size='small'>
{t('未启用')}
</Tag>
)}
{status.locked && (
<Tag color='orange' shape='circle' size='small'>
{t('账户已锁定')}
</Tag>
)}
</div>
<Typography.Text type='tertiary' className='text-sm'>
{t(
'两步验证(2FA)为您的账户提供额外的安全保护。启用后,登录时需要输入密码和验证器应用生成的验证码。',
)}
</Typography.Text>
{status.enabled && (
<div className='mt-2'>
<Text size='small' type='secondary'>
{t('剩余备用码:')}
{status.backup_codes_remaining || 0}
{t('个')}
</Text>
</div>
)}
</div>
</div>
<div className='flex flex-col space-y-2 w-full sm:w-auto'>
{!status.enabled ? (
<Button
type='primary'
theme='solid'
size='default'
onClick={handleSetup2FA}
loading={loading}
className='!rounded-lg !bg-slate-600 hover:!bg-slate-700'
icon={<IconShield />}
>
{t('启用验证')}
</Button>
) : (
<div className='flex flex-col space-y-2'>
<Button
type='danger'
theme='solid'
size='default'
onClick={() => setDisableModalVisible(true)}
className='!rounded-lg !bg-slate-500 hover:!bg-slate-600'
icon={<IconAlertTriangle />}
>
{t('禁用两步验证')}
</Button>
<Button
type='primary'
theme='solid'
size='default'
onClick={() => setBackupModalVisible(true)}
className='!rounded-lg'
icon={<IconRefresh />}
>
{t('重新生成备用码')}
</Button>
</div>
)}
</div>
</div>
</Card>
{/* 2FA设置模态框 */}
<Modal
title={
<div className='flex items-center'>
<IconShield className='mr-2 text-slate-600' />
{t('设置两步验证')}
</div>
}
visible={setupModalVisible}
onCancel={() => {
setSetupModalVisible(false);
setSetupData(null);
setCurrentStep(0);
setVerificationCode('');
}}
footer={renderSetupModalFooter()}
width={650}
style={{ maxWidth: '90vw' }}
>
{setupData && (
<div className='space-y-6'>
{/* 步骤进度 */}
<Steps type='basic' size='small' current={currentStep}>
<Steps.Step
title={t('扫描二维码')}
description={t('使用认证器应用扫描二维码')}
/>
<Steps.Step
title={t('保存备用码')}
description={t('保存备用码以备不时之需')}
/>
<Steps.Step
title={t('验证设置')}
description={t('输入验证码完成设置')}
/>
</Steps>
{/* 步骤内容 */}
<div className='rounded-xl'>
{currentStep === 0 && (
<div>
<Paragraph className='text-gray-600 dark:text-gray-300 mb-4'>
{t(
'使用认证器应用(如 Google Authenticator、Microsoft Authenticator)扫描下方二维码:',
)}
</Paragraph>
<div className='flex justify-center mb-4'>
<div className='bg-white p-4 rounded-lg shadow-sm'>
<QRCodeSVG value={setupData.qr_code_data} size={180} />
</div>
</div>
<div className='bg-blue-50 dark:bg-blue-900 rounded-lg p-3'>
<Text className='text-blue-800 dark:text-blue-200 text-sm'>
{t('或手动输入密钥:')}
<Text code copyable className='ml-2'>
{setupData.secret}
</Text>
</Text>
</div>
</div>
)}
{currentStep === 1 && (
<div className='space-y-4'>
{/* 备用码展示 */}
<BackupCodesDisplay
codes={setupData.backup_codes}
title={t('备用恢复代码')}
onCopy={() => {
const codesText = setupData.backup_codes.join('\n');
copyTextToClipboard(codesText, t('备用码已复制到剪贴板'));
}}
/>
</div>
)}
{currentStep === 2 && (
<Input
placeholder={t('输入认证器应用显示的6位数字验证码')}
value={verificationCode}
onChange={setVerificationCode}
size='large'
maxLength={6}
className='!rounded-lg'
/>
)}
</div>
</div>
)}
</Modal>
{/* 禁用2FA模态框 */}
<Modal
title={
<div className='flex items-center'>
<IconAlertTriangle className='mr-2 text-red-500' />
{t('禁用两步验证')}
</div>
}
visible={disableModalVisible}
onCancel={() => {
setDisableModalVisible(false);
setVerificationCode('');
setConfirmDisable(false);
}}
footer={renderDisableModalFooter()}
width={550}
style={{ maxWidth: '90vw' }}
>
<div className='space-y-6'>
{/* 警告提示 */}
<div className='rounded-xl'>
<Banner
type='warning'
description={t(
'警告:禁用两步验证将永久删除您的验证设置和所有备用码,此操作不可撤销!',
)}
className='!rounded-lg'
/>
</div>
{/* 内容区域 */}
<div className='space-y-4'>
<div>
<Text
strong
className='block mb-2 text-slate-700 dark:text-slate-200'
>
{t('禁用后的影响:')}
</Text>
<ul className='space-y-2 text-sm text-slate-600 dark:text-slate-300'>
<li className='flex items-start gap-2'>
<Badge dot type='warning' />
{t('降低您账户的安全性')}
</li>
<li className='flex items-start gap-2'>
<Badge dot type='warning' />
{t('需要重新完整设置才能再次启用')}
</li>
<li className='flex items-start gap-2'>
<Badge dot type='danger' />
{t('永久删除您的两步验证设置')}
</li>
<li className='flex items-start gap-2'>
<Badge dot type='danger' />
{t('永久删除所有备用码(包括未使用的)')}
</li>
</ul>
</div>
<Divider margin={16} />
<div className='space-y-4'>
<div>
<Text
strong
className='block mb-2 text-slate-700 dark:text-slate-200'
>
{t('验证身份')}
</Text>
<Input
placeholder={t('请输入认证器验证码或备用码')}
value={verificationCode}
onChange={setVerificationCode}
size='large'
className='!rounded-lg'
/>
</div>
<div>
<Checkbox
checked={confirmDisable}
onChange={(e) => setConfirmDisable(e.target.checked)}
className='text-sm'
>
{t(
'我已了解禁用两步验证将永久删除所有相关设置和备用码,此操作不可撤销',
)}
</Checkbox>
</div>
</div>
</div>
</div>
</Modal>
{/* 重新生成备用码模态框 */}
<Modal
title={
<div className='flex items-center'>
<IconRefresh className='mr-2 text-slate-600' />
{t('重新生成备用码')}
</div>
}
visible={backupModalVisible}
onCancel={() => {
setBackupModalVisible(false);
setVerificationCode('');
setBackupCodes([]);
}}
footer={renderRegenerateModalFooter()}
width={500}
style={{ maxWidth: '90vw' }}
>
<div className='space-y-6'>
{backupCodes.length === 0 ? (
<>
{/* 警告提示 */}
<div className='rounded-xl'>
<Banner
type='warning'
description={t(
'重新生成备用码将使现有的备用码失效,请确保您已保存了当前的备用码。',
)}
className='!rounded-lg'
/>
</div>
{/* 验证区域 */}
<div className='space-y-4'>
<div>
<Text
strong
className='block mb-2 text-slate-700 dark:text-slate-200'
>
{t('验证身份')}
</Text>
<Input
placeholder={t('请输入认证器验证码')}
value={verificationCode}
onChange={setVerificationCode}
size='large'
className='!rounded-lg'
/>
</div>
</div>
</>
) : (
<>
{/* 成功提示 */}
<Space vertical style={{ width: '100%' }}>
<div className='flex items-center justify-center gap-2'>
<Badge dot type='success' />
<Text
strong
className='text-lg text-slate-700 dark:text-slate-200'
>
{t('新的备用码已生成')}
</Text>
</div>
<Text className='text-slate-500 dark:text-slate-400 text-sm'>
{t('旧的备用码已失效,请保存新的备用码')}
</Text>
{/* 备用码展示 */}
<BackupCodesDisplay
codes={backupCodes}
title={t('新的备用恢复代码')}
onCopy={copyBackupCodes}
/>
</Space>
</>
)}
</div>
</Modal>
</>
);
};
export default TwoFASetting;
@@ -0,0 +1,226 @@
/*
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 from 'react';
import {
Avatar,
Card,
Tag,
Divider,
Typography,
Badge,
} from '@douyinfe/semi-ui';
import {
isRoot,
isAdmin,
renderQuota,
stringToColor,
} from '../../../../helpers';
import { Coins, BarChart2, Users } from 'lucide-react';
const UserInfoHeader = ({ t, userState }) => {
const getUsername = () => {
if (userState.user) {
// Use display_name if available, otherwise fallback to username
return userState.user.display_name || userState.user.username;
} else {
return 'null';
}
};
const getAvatarText = () => {
const username = getUsername();
if (username && username.length > 0) {
return username.slice(0, 2).toUpperCase();
}
return 'NA';
};
return (
<Card
className='!rounded-2xl overflow-hidden'
cover={
<div
className='relative h-32'
style={{
'--palette-primary-darkerChannel': '0 75 80',
backgroundImage: `linear-gradient(0deg, rgba(var(--palette-primary-darkerChannel) / 80%), rgba(var(--palette-primary-darkerChannel) / 80%)), url('/cover-4.webp')`,
backgroundSize: 'cover',
backgroundPosition: 'center',
backgroundRepeat: 'no-repeat',
}}
>
{/* 用户信息内容 */}
<div className='relative z-10 h-full flex flex-col justify-end p-6'>
<div className='flex items-center'>
<div className='flex items-stretch gap-3 sm:gap-4 flex-1 min-w-0'>
<Avatar size='large' color={stringToColor(getUsername())}>
{getAvatarText()}
</Avatar>
<div className='flex-1 min-w-0 flex flex-col justify-between'>
<div
className='text-3xl font-bold truncate'
style={{ color: 'white' }}
>
{getUsername()}
</div>
<div className='flex flex-wrap items-center gap-2'>
{isRoot() ? (
<Tag
size='large'
shape='circle'
style={{ color: 'white' }}
>
{t('超级管理员')}
</Tag>
) : isAdmin() ? (
<Tag
size='large'
shape='circle'
style={{ color: 'white' }}
>
{t('管理员')}
</Tag>
) : (
<Tag
size='large'
shape='circle'
style={{ color: 'white' }}
>
{t('普通用户')}
</Tag>
)}
<Tag size='large' shape='circle' style={{ color: 'white' }}>
ID: {userState?.user?.id}
</Tag>
</div>
</div>
</div>
</div>
</div>
</div>
}
>
{/* 当前余额和桌面版统计信息 */}
<div className='flex items-start justify-between gap-6'>
{/* 当前余额显示 */}
<Badge count={t('当前余额')} position='rightTop' type='danger'>
<div className='text-2xl sm:text-3xl md:text-4xl font-bold tracking-wide'>
{renderQuota(userState?.user?.quota)}
</div>
{userState?.user?.gift_quota > 0 && (
<div className='text-xs text-gray-500 mt-1'>
{t('另有赠送余额')} {renderQuota(userState?.user?.gift_quota)}
</div>
)}
</Badge>
{/* 桌面版统计信息(Semi UI 卡片) */}
<div className='hidden lg:block flex-shrink-0'>
<Card
size='small'
className='!rounded-xl'
bodyStyle={{ padding: '12px 16px' }}
>
<div className='flex items-center gap-4'>
<div className='flex items-center gap-2'>
<Coins size={16} />
<Typography.Text size='small' type='tertiary'>
{t('历史消耗')}
</Typography.Text>
<Typography.Text size='small' type='tertiary' strong>
{renderQuota(userState?.user?.used_quota)}
</Typography.Text>
</div>
<Divider layout='vertical' />
<div className='flex items-center gap-2'>
<BarChart2 size={16} />
<Typography.Text size='small' type='tertiary'>
{t('请求次数')}
</Typography.Text>
<Typography.Text size='small' type='tertiary' strong>
{userState.user?.request_count || 0}
</Typography.Text>
</div>
<Divider layout='vertical' />
<div className='flex items-center gap-2'>
<Users size={16} />
<Typography.Text size='small' type='tertiary'>
{t('用户分组')}
</Typography.Text>
<Typography.Text size='small' type='tertiary' strong>
{userState?.user?.group || t('默认')}
</Typography.Text>
</div>
</div>
</Card>
</div>
</div>
{/* 移动端和中等屏幕统计信息卡片 */}
<div className='lg:hidden mt-2'>
<Card
size='small'
className='!rounded-xl'
bodyStyle={{ padding: '12px 16px' }}
>
<div className='space-y-3'>
<div className='flex items-center justify-between'>
<div className='flex items-center gap-2'>
<Coins size={16} />
<Typography.Text size='small' type='tertiary'>
{t('历史消耗')}
</Typography.Text>
</div>
<Typography.Text size='small' type='tertiary' strong>
{renderQuota(userState?.user?.used_quota)}
</Typography.Text>
</div>
<Divider margin='8px' />
<div className='flex items-center justify-between'>
<div className='flex items-center gap-2'>
<BarChart2 size={16} />
<Typography.Text size='small' type='tertiary'>
{t('请求次数')}
</Typography.Text>
</div>
<Typography.Text size='small' type='tertiary' strong>
{userState.user?.request_count || 0}
</Typography.Text>
</div>
<Divider margin='8px' />
<div className='flex items-center justify-between'>
<div className='flex items-center gap-2'>
<Users size={16} />
<Typography.Text size='small' type='tertiary'>
{t('用户分组')}
</Typography.Text>
</div>
<Typography.Text size='small' type='tertiary' strong>
{userState?.user?.group || t('默认')}
</Typography.Text>
</div>
</div>
</Card>
</div>
</Card>
);
};
export default UserInfoHeader;
@@ -0,0 +1,94 @@
/*
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 from 'react';
import { Banner, Input, Modal, Typography } from '@douyinfe/semi-ui';
import { IconDelete, IconUser } from '@douyinfe/semi-icons';
import Turnstile from 'react-turnstile';
const AccountDeleteModal = ({
t,
showAccountDeleteModal,
setShowAccountDeleteModal,
inputs,
handleInputChange,
deleteAccount,
userState,
turnstileEnabled,
turnstileSiteKey,
setTurnstileToken,
}) => {
return (
<Modal
title={
<div className='flex items-center'>
<IconDelete className='mr-2 text-red-500' />
{t('删除账户确认')}
</div>
}
visible={showAccountDeleteModal}
onCancel={() => setShowAccountDeleteModal(false)}
onOk={deleteAccount}
size={'small'}
centered={true}
className='modern-modal'
>
<div className='space-y-4 py-4'>
<Banner
type='danger'
description={t('您正在删除自己的帐户,将清空所有数据且不可恢复')}
closeIcon={null}
className='!rounded-lg'
/>
<div>
<Typography.Text strong className='block mb-2 text-red-600'>
{t('请输入您的用户名以确认删除')}
</Typography.Text>
<Input
placeholder={t('输入你的账户名{{username}}以确认删除', {
username: ` ${userState?.user?.username} `,
})}
name='self_account_deletion_confirmation'
value={inputs.self_account_deletion_confirmation}
onChange={(value) =>
handleInputChange('self_account_deletion_confirmation', value)
}
size='large'
className='!rounded-lg'
prefix={<IconUser />}
/>
</div>
{turnstileEnabled && (
<div className='flex justify-center'>
<Turnstile
sitekey={turnstileSiteKey}
onVerify={(token) => {
setTurnstileToken(token);
}}
/>
</div>
)}
</div>
</Modal>
);
};
export default AccountDeleteModal;
@@ -0,0 +1,122 @@
/*
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 from 'react';
import { Input, Modal, Typography } from '@douyinfe/semi-ui';
import { IconLock } from '@douyinfe/semi-icons';
import Turnstile from 'react-turnstile';
const ChangePasswordModal = ({
t,
showChangePasswordModal,
setShowChangePasswordModal,
inputs,
handleInputChange,
changePassword,
hasPassword,
turnstileEnabled,
turnstileSiteKey,
setTurnstileToken,
}) => {
return (
<Modal
title={
<div className='flex items-center'>
<IconLock className='mr-2 text-orange-500' />
{hasPassword ? t('修改密码') : t('设置密码')}
</div>
}
visible={showChangePasswordModal}
onCancel={() => setShowChangePasswordModal(false)}
onOk={changePassword}
size={'small'}
centered={true}
className='modern-modal'
>
<div className='space-y-4 py-4'>
{hasPassword && (
<div>
<Typography.Text strong className='block mb-2'>
{t('原密码')}
</Typography.Text>
<Input
name='original_password'
placeholder={t('请输入原密码')}
type='password'
value={inputs.original_password}
onChange={(value) =>
handleInputChange('original_password', value)
}
size='large'
className='!rounded-lg'
prefix={<IconLock />}
/>
</div>
)}
<div>
<Typography.Text strong className='block mb-2'>
{t('新密码')}
</Typography.Text>
<Input
name='set_new_password'
placeholder={t('请输入新密码')}
type='password'
value={inputs.set_new_password}
onChange={(value) => handleInputChange('set_new_password', value)}
size='large'
className='!rounded-lg'
prefix={<IconLock />}
/>
</div>
<div>
<Typography.Text strong className='block mb-2'>
{t('确认新密码')}
</Typography.Text>
<Input
name='set_new_password_confirmation'
placeholder={t('请再次输入新密码')}
type='password'
value={inputs.set_new_password_confirmation}
onChange={(value) =>
handleInputChange('set_new_password_confirmation', value)
}
size='large'
className='!rounded-lg'
prefix={<IconLock />}
/>
</div>
{turnstileEnabled && (
<div className='flex justify-center'>
<Turnstile
sitekey={turnstileSiteKey}
onVerify={(token) => {
setTurnstileToken(token);
}}
/>
</div>
)}
</div>
</Modal>
);
};
export default ChangePasswordModal;
@@ -0,0 +1,108 @@
/*
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 from 'react';
import { Button, Input, Modal } from '@douyinfe/semi-ui';
import { IconMail, IconKey } from '@douyinfe/semi-icons';
import Turnstile from 'react-turnstile';
const EmailBindModal = ({
t,
showEmailBindModal,
setShowEmailBindModal,
inputs,
handleInputChange,
sendVerificationCode,
bindEmail,
disableButton,
loading,
countdown,
turnstileEnabled,
turnstileSiteKey,
setTurnstileToken,
}) => {
return (
<Modal
title={
<div className='flex items-center'>
<IconMail className='mr-2 text-blue-500' />
{t('绑定邮箱地址')}
</div>
}
visible={showEmailBindModal}
onCancel={() => setShowEmailBindModal(false)}
onOk={bindEmail}
size={'small'}
centered={true}
maskClosable={false}
className='modern-modal'
>
<div className='space-y-4 py-4'>
<div className='flex gap-3'>
<Input
placeholder={t('输入邮箱地址')}
onChange={(value) => handleInputChange('email', value)}
name='email'
type='email'
size='large'
className='!rounded-lg flex-1'
prefix={<IconMail />}
/>
<Button
onClick={sendVerificationCode}
disabled={disableButton || loading}
className='!rounded-lg'
type='primary'
theme='outline'
size='large'
>
{disableButton
? `${t('重新发送')} (${countdown})`
: t('获取验证码')}
</Button>
</div>
<Input
placeholder={t('验证码')}
name='email_verification_code'
value={inputs.email_verification_code}
onChange={(value) =>
handleInputChange('email_verification_code', value)
}
size='large'
className='!rounded-lg'
prefix={<IconKey />}
/>
{turnstileEnabled && (
<div className='flex justify-center'>
<Turnstile
sitekey={turnstileSiteKey}
onVerify={(token) => {
setTurnstileToken(token);
}}
/>
</div>
)}
</div>
</Modal>
);
};
export default EmailBindModal;
@@ -0,0 +1,80 @@
/*
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 from 'react';
import { Button, Input, Modal, Image } from '@douyinfe/semi-ui';
import { IconKey } from '@douyinfe/semi-icons';
import { WechatBrandIcon } from '../../../common/icons/BrandIcons';
const WeChatBindModal = ({
t,
showWeChatBindModal,
setShowWeChatBindModal,
inputs,
handleInputChange,
bindWeChat,
status,
}) => {
return (
<Modal
title={
<div className='flex items-center'>
<WechatBrandIcon className='mr-2' color='#07C160' size={20} />
{t('绑定微信账户')}
</div>
}
visible={showWeChatBindModal}
onCancel={() => setShowWeChatBindModal(false)}
footer={null}
size={'small'}
centered={true}
className='modern-modal'
>
<div className='space-y-4 py-4 text-center'>
<Image src={status.wechat_qrcode} className='mx-auto' />
<div className='text-gray-600'>
<p>
{t('微信扫码关注公众号,输入「验证码」获取验证码(三分钟内有效)')}
</p>
</div>
<Input
placeholder={t('验证码')}
name='wechat_verification_code'
value={inputs.wechat_verification_code}
onChange={(v) => handleInputChange('wechat_verification_code', v)}
size='large'
className='!rounded-lg'
prefix={<IconKey />}
/>
<Button
type='primary'
theme='solid'
size='large'
onClick={bindWeChat}
className='!rounded-lg w-full !bg-slate-600 hover:!bg-slate-700'
icon={<WechatBrandIcon size={16} color='currentColor' />}
>
{t('绑定')}
</Button>
</div>
</Modal>
);
};
export default WeChatBindModal;
@@ -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, { useState } from 'react';
import { Button, Popover, Typography, Modal } from '@douyinfe/semi-ui';
import { IconMail, IconShield, IconGithubLogo } from '@douyinfe/semi-icons';
import { Link2, ExternalLink, Check, X } from 'lucide-react';
import {
TelegramBrandIcon,
WechatBrandIcon,
LinuxBrandIcon,
DiscordBrandIcon,
} from '../../../common/icons/BrandIcons';
import TelegramLoginButton from 'react-telegram-login';
import {
onGitHubOAuthClicked,
onOIDCClicked,
onLinuxDOOAuthClicked,
onDiscordOAuthClicked,
} from '../../../../helpers';
// 绑定卡片配置
const BINDING_CARDS = [
{
key: 'email',
icon: IconMail,
gradient: 'from-blue-500 to-cyan-500',
panelClass:
'bg-gradient-to-br from-blue-50/78 to-cyan-50/70 dark:from-blue-500/[0.09] dark:to-cyan-400/[0.07]',
},
{
key: 'wechat',
icon: WechatBrandIcon,
gradient: 'from-green-500 to-emerald-500',
panelClass:
'bg-gradient-to-br from-green-50/78 to-emerald-50/70 dark:from-green-500/[0.09] dark:to-emerald-400/[0.07]',
isBrandIcon: true,
},
{
key: 'github',
icon: IconGithubLogo,
gradient: 'from-gray-700 to-gray-900',
panelClass:
'bg-gradient-to-br from-gray-50/88 to-slate-50/75 dark:from-slate-500/[0.10] dark:to-slate-700/[0.10]',
},
{
key: 'discord',
icon: DiscordBrandIcon,
gradient: 'from-brand-from to-brand-to',
panelClass:
'bg-gradient-to-br from-brand-from/10 to-brand-to/10 dark:from-brand-from/[0.14] dark:to-brand-to/[0.12]',
isBrandIcon: true,
},
{
key: 'oidc',
icon: IconShield,
gradient: 'from-orange-500 to-red-500',
panelClass:
'bg-gradient-to-br from-orange-50/78 to-red-50/70 dark:from-orange-500/[0.10] dark:to-red-500/[0.08]',
},
{
key: 'telegram',
icon: TelegramBrandIcon,
gradient: 'from-sky-500 to-blue-500',
panelClass:
'bg-gradient-to-br from-sky-50/78 to-blue-50/70 dark:from-sky-500/[0.10] dark:to-blue-500/[0.08]',
isBrandIcon: true,
},
{
key: 'linuxdo',
icon: LinuxBrandIcon,
gradient: 'from-yellow-500 to-orange-500',
panelClass:
'bg-gradient-to-br from-yellow-50/78 to-orange-50/70 dark:from-yellow-500/[0.10] dark:to-orange-500/[0.08]',
isBrandIcon: true,
},
];
const AccountBindingSection = ({
t,
userState,
status,
setShowEmailBindModal,
setShowWeChatBindModal,
}) => {
const [showTelegramBindModal, setShowTelegramBindModal] = useState(false);
const isBound = (accountId) => Boolean(accountId);
const renderAccountInfo = (accountId, label) => {
if (!accountId || accountId === '') {
return <span className='text-gray-400'>{t('未绑定')}</span>;
}
const popContent = (
<div className='text-xs p-2'>
<Typography.Paragraph copyable={{ content: accountId }}>
{accountId}
</Typography.Paragraph>
{label && <div className='mt-1 text-[11px] text-gray-500'>{label}</div>}
</div>
);
return (
<Popover content={popContent} position='top' trigger='hover'>
<span className='text-sm text-gray-600 dark:text-gray-300 hover:text-blue-600 cursor-pointer truncate max-w-[120px] inline-block'>
{accountId}
</span>
</Popover>
);
};
const getBindingData = (key) => {
switch (key) {
case 'email':
return {
name: t('邮箱'),
value: userState.user?.email,
label: t('邮箱地址'),
enabled: true,
onBind: () => setShowEmailBindModal(true),
};
case 'wechat':
return {
name: t('微信'),
value: userState.user?.wechat_id,
label: t('微信账号'),
enabled: status.wechat_login,
onBind: () => setShowWeChatBindModal(true),
};
case 'github':
return {
name: 'GitHub',
value: userState.user?.github_id,
label: 'GitHub ID',
enabled: status.github_oauth,
onBind: () => onGitHubOAuthClicked(status.github_client_id),
disableWhenBound: true,
};
case 'discord':
return {
name: 'Discord',
value: userState.user?.discord_id,
label: 'Discord ID',
enabled: status.discord_oauth,
onBind: () => onDiscordOAuthClicked(status.discord_client_id),
disableWhenBound: true,
};
case 'oidc':
return {
name: 'OIDC',
value: userState.user?.oidc_id,
label: 'OIDC ID',
enabled: status.oidc_enabled,
onBind: () =>
onOIDCClicked(
status.oidc_authorization_endpoint,
status.oidc_client_id,
),
disableWhenBound: true,
};
case 'telegram':
return {
name: 'Telegram',
value: userState.user?.telegram_id,
label: 'Telegram ID',
enabled: status.telegram_oauth,
onBind: () => setShowTelegramBindModal(true),
disableWhenBound: true,
};
case 'linuxdo':
return {
name: 'LinuxDO',
value: userState.user?.linux_do_id,
label: 'LinuxDO ID',
enabled: status.linuxdo_oauth,
onBind: () => onLinuxDOOAuthClicked(status.linuxdo_client_id),
disableWhenBound: true,
};
default:
return null;
}
};
return (
<div className='space-y-6'>
{/* 页面标题 */}
<div className='flex items-center gap-3 rounded-3xl border border-white/70 dark:border-white/10 bg-white/50 dark:bg-white/[0.045] backdrop-blur-xl px-5 py-4'>
<div className='w-11 h-11 rounded-2xl bg-gradient-to-br from-sky-500 to-cyan-400 flex items-center justify-center shadow-lg shadow-sky-500/20'>
<Link2 className='w-5 h-5 text-white' />
</div>
<div>
<h2 className='text-xl font-bold text-gray-900 dark:text-white'>
{t('账号绑定')}
</h2>
<p className='text-sm text-gray-500 dark:text-gray-400'>
{t('管理邮箱和第三方登录方式')}
</p>
</div>
</div>
{/* 绑定卡片网格 */}
<div className='grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4'>
{BINDING_CARDS.map((card) => {
const data = getBindingData(card.key);
if (!data) return null;
// 未启用的绑定方式不显示卡片
if (!data.enabled) return null;
const Icon = card.icon;
const bound = isBound(data.value);
const disabled = data.disableWhenBound && bound;
return (
<div
key={card.key}
className={`relative group p-5 rounded-[22px] border backdrop-blur-xl transition-all duration-300 ${
bound
? 'bg-white/62 dark:bg-white/[0.055] border-white/70 dark:border-white/10'
: `${card.panelClass} border-white/70 dark:border-white/10 hover:border-white dark:hover:border-white/20`
} hover:shadow-[0_18px_45px_rgba(15,23,42,0.10)] hover:-translate-y-0.5`}
>
{/* 状态指示器 */}
<div className='absolute top-3 right-3'>
{bound ? (
<div className='flex items-center gap-1 px-2 py-0.5 bg-emerald-100 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 rounded-full text-xs font-medium'>
<Check size={12} />
{t('已绑定')}
</div>
) : (
<div className='flex items-center gap-1 px-2 py-0.5 bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 rounded-full text-xs'>
<X size={12} />
{t('未绑定')}
</div>
)}
</div>
{/* 图标和名称 */}
<div className='flex items-center gap-3 mb-4 pr-20'>
<div
className={`w-12 h-12 rounded-2xl flex items-center justify-center bg-gradient-to-br ${card.gradient} shadow-lg`}
>
{card.isBrandIcon ? (
<Icon size={24} color='#FFFFFF' />
) : (
<Icon size='extra-large' className='text-white' />
)}
</div>
<div className='min-w-0'>
<h3 className='font-semibold text-gray-900 dark:text-white'>
{data.name}
</h3>
<div className='text-sm'>
{bound ? renderAccountInfo(data.value, data.label) : null}
</div>
</div>
</div>
{/* 操作按钮 */}
<Button
theme={bound ? 'light' : 'solid'}
type='primary'
size='small'
disabled={disabled}
onClick={data.onBind}
className={`w-full !rounded-lg ${
!bound
? `!bg-gradient-to-r ${card.gradient} !border-0 hover:opacity-90`
: ''
}`}
icon={bound ? null : <ExternalLink size={14} />}
>
{bound
? data.disableWhenBound
? t('已绑定')
: t('修改绑定')
: t('立即绑定')}
</Button>
</div>
);
})}
</div>
{/* Telegram 绑定弹窗 */}
<Modal
title={t('绑定 Telegram')}
visible={showTelegramBindModal}
onCancel={() => setShowTelegramBindModal(false)}
footer={null}
>
<div className='my-3 text-sm text-gray-600'>
{t('点击下方按钮通过 Telegram 完成绑定')}
</div>
<div className='flex justify-center'>
<div className='scale-90'>
<TelegramLoginButton
dataAuthUrl='/api/oauth/telegram/bind'
botName={status.telegram_bot_name}
/>
</div>
</div>
</Modal>
</div>
);
};
export default AccountBindingSection;
@@ -0,0 +1,234 @@
/*
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 from 'react';
import { Button, Input, Radio, RadioGroup, Tag } from '@douyinfe/semi-ui';
import { Image, Palette, Sparkles, Type, Wand2 } from 'lucide-react';
import {
CARTOON_AVATAR_PRESETS,
USER_AVATAR_TYPES,
getCartoonAvatarDataUrl,
getInitialAvatarDataUrl,
} from '../../../../helpers';
const AVATAR_TYPE_OPTIONS = [
{
value: USER_AVATAR_TYPES.PRESET,
label: '卡通形象',
desc: '从系统内置卡通头像中选择,适合默认展示',
icon: Palette,
},
{
value: USER_AVATAR_TYPES.INITIAL,
label: '姓名首字',
desc: '根据用户名自动生成简洁文字头像',
icon: Type,
},
{
value: USER_AVATAR_TYPES.CUSTOM,
label: '图片链接',
desc: '填写公网图片 URL,使用自己的头像',
icon: Image,
},
];
const AvatarSection = ({
t,
userState,
avatarSettings,
handleAvatarSettingChange,
saveAvatarSettings,
savingAvatarSettings,
}) => {
const username =
userState?.user?.display_name || userState?.user?.username || 'User';
const previewUrl =
avatarSettings.avatarType === USER_AVATAR_TYPES.CUSTOM &&
avatarSettings.customAvatarUrl
? avatarSettings.customAvatarUrl
: avatarSettings.avatarType === USER_AVATAR_TYPES.INITIAL
? getInitialAvatarDataUrl(username, 128)
: getCartoonAvatarDataUrl(avatarSettings.avatarPreset, 128);
const customAvatarInvalid =
avatarSettings.avatarType === USER_AVATAR_TYPES.CUSTOM &&
!avatarSettings.customAvatarUrl?.trim();
return (
<div className='space-y-6'>
<div className='flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 rounded-3xl border border-white/70 dark:border-white/10 bg-white/50 dark:bg-white/[0.045] backdrop-blur-xl px-5 py-4'>
<div className='flex items-center gap-3'>
<div className='w-11 h-11 rounded-2xl bg-gradient-to-br from-rose-500 to-orange-400 flex items-center justify-center shadow-lg shadow-rose-500/20'>
<Wand2 className='w-5 h-5 text-white' />
</div>
<div>
<h2 className='text-xl font-bold text-gray-900 dark:text-white'>
{t('头像设置')}
</h2>
<p className='text-sm text-gray-500 dark:text-gray-400'>
{t('选择你在平台内展示的头像样式')}
</p>
</div>
</div>
<Button
theme='solid'
loading={savingAvatarSettings}
disabled={customAvatarInvalid}
onClick={saveAvatarSettings}
className='!bg-gradient-to-r !from-rose-500 !to-orange-400 !border-0 !rounded-xl !shadow-lg !shadow-rose-500/20'
>
{t('保存头像')}
</Button>
</div>
<div className='grid grid-cols-1 xl:grid-cols-[280px_1fr] gap-5'>
<div className='relative overflow-hidden rounded-[28px] border border-white/70 dark:border-white/10 bg-white/[0.54] dark:bg-white/[0.045] p-5 shadow-[0_20px_55px_rgba(244,63,94,0.10)]'>
<div className='absolute inset-0 bg-[radial-gradient(circle_at_25%_20%,rgba(251,113,133,0.22),transparent_32%),radial-gradient(circle_at_90%_85%,rgba(251,146,60,0.16),transparent_34%)] pointer-events-none' />
<div className='relative flex flex-col items-center text-center'>
<div className='relative mb-4'>
<div className='absolute inset-0 rounded-[32px] bg-gradient-to-br from-rose-500 to-orange-400 blur-lg opacity-30' />
<img
src={previewUrl}
alt={t('头像预览')}
className='relative w-28 h-28 rounded-[32px] object-cover ring-4 ring-white/90 dark:ring-slate-950 shadow-xl'
/>
<span className='absolute -bottom-1 -right-1 w-6 h-6 rounded-full bg-emerald-500 border-4 border-white dark:border-slate-950' />
</div>
<div className='text-base font-semibold text-gray-900 dark:text-white'>
{username}
</div>
<div className='mt-2 text-xs text-gray-500 dark:text-gray-400 leading-relaxed'>
{t('该头像会同步展示在右上角用户入口和体验中心文本对话中。')}
</div>
<Tag
color='pink'
shape='circle'
className='mt-4 !bg-white/70 dark:!bg-white/[0.08]'
>
{t('实时预览')}
</Tag>
</div>
</div>
<div className='rounded-[28px] border border-white/70 dark:border-white/10 bg-white/50 dark:bg-white/[0.045] backdrop-blur-xl p-5'>
<div className='mb-5'>
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3'>
{t('头像类型')}
</label>
<RadioGroup
type='button'
value={avatarSettings.avatarType}
onChange={(e) =>
handleAvatarSettingChange('avatarType', e.target.value)
}
className='!flex !flex-wrap !gap-2'
>
{AVATAR_TYPE_OPTIONS.map((option) => {
const Icon = option.icon;
return (
<Radio key={option.value} value={option.value}>
<span className='inline-flex items-center gap-1.5'>
<Icon size={14} />
{t(option.label)}
</span>
</Radio>
);
})}
</RadioGroup>
<p className='mt-2 text-xs text-gray-500 dark:text-gray-400'>
{t(
AVATAR_TYPE_OPTIONS.find(
(item) => item.value === avatarSettings.avatarType,
)?.desc || '',
)}
</p>
</div>
{avatarSettings.avatarType === USER_AVATAR_TYPES.PRESET && (
<div>
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3'>
{t('选择卡通形象')}
</label>
<div className='grid grid-cols-2 sm:grid-cols-4 gap-3'>
{CARTOON_AVATAR_PRESETS.map((preset) => {
const selected = avatarSettings.avatarPreset === preset.id;
return (
<button
key={preset.id}
type='button'
onClick={() => {
handleAvatarSettingChange(
'avatarType',
USER_AVATAR_TYPES.PRESET,
);
handleAvatarSettingChange('avatarPreset', preset.id);
}}
className={`group relative rounded-2xl border p-3 transition-all duration-200 ${
selected
? 'border-rose-300 bg-white/[0.82] dark:bg-white/[0.08] shadow-lg shadow-rose-500/10'
: 'border-white/70 dark:border-white/10 bg-white/[0.46] dark:bg-white/[0.035] hover:border-rose-200 dark:hover:border-rose-400/25'
}`}
>
<img
src={getCartoonAvatarDataUrl(preset.id, 96)}
alt={preset.label}
className='mx-auto w-14 h-14 rounded-2xl object-cover transition-transform group-hover:scale-105'
/>
<div className='mt-2 text-xs font-medium text-gray-700 dark:text-gray-200 truncate'>
{t(preset.label)}
</div>
{selected && (
<Sparkles
size={16}
className='absolute top-2 right-2 text-rose-500'
/>
)}
</button>
);
})}
</div>
</div>
)}
{avatarSettings.avatarType === USER_AVATAR_TYPES.CUSTOM && (
<div className='rounded-2xl border border-sky-100 dark:border-sky-400/20 bg-sky-50/[0.55] dark:bg-sky-400/[0.06] p-4'>
<Input
value={avatarSettings.customAvatarUrl}
onChange={(value) =>
handleAvatarSettingChange('customAvatarUrl', value)
}
placeholder={t(
'请输入图片 URL,例如 https://example.com/avatar.png',
)}
prefix={<Image size={15} className='text-sky-500' />}
showClear
/>
<p className='mt-2 text-xs text-gray-500 dark:text-gray-400'>
{t('支持公网图片链接。若图片加载失败,会回退到默认卡通头像。')}
</p>
</div>
)}
</div>
</div>
</div>
);
};
export default AvatarSection;
@@ -0,0 +1,271 @@
/*
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, { useRef, useEffect } from 'react';
import { Button, Form, Toast } from '@douyinfe/semi-ui';
import { IconMail, IconKey, IconLink } from '@douyinfe/semi-icons';
import { Bell, Mail, Save, Webhook } from 'lucide-react';
import { FormQuotaInput } from '../../../common/ui/QuotaInput';
import CodeViewer from '../../../playground/CodeViewer';
const NotificationSection = ({
t,
notificationSettings,
handleNotificationSettingChange,
saveNotificationSettings,
}) => {
const formApiRef = useRef(null);
useEffect(() => {
if (formApiRef.current && notificationSettings) {
formApiRef.current.setValues(notificationSettings);
}
}, [notificationSettings]);
const handleFormChange = (field, value) => {
handleNotificationSettingChange(field, value);
};
const handleSubmit = () => {
if (formApiRef.current) {
formApiRef.current
.validate()
.then(() => {
saveNotificationSettings();
})
.catch((errors) => {
console.log('表单验证失败:', errors);
Toast.error(t('请检查表单填写是否正确'));
});
} else {
saveNotificationSettings();
}
};
// 通知方式选项(仅保留邮件通知和Webhook)
const notifyOptions = [
{
value: 'email',
label: t('邮件提醒'),
desc: t('发送到绑定邮箱或指定邮箱'),
icon: Mail,
selectedClass:
'border-sky-300 bg-sky-50/82 dark:bg-sky-500/[0.10] dark:border-sky-400/25',
iconClass: 'text-sky-500',
textClass: 'text-sky-700 dark:text-sky-300',
},
{
value: 'webhook',
label: 'Webhook',
desc: t('将提醒推送到外部系统'),
icon: Webhook,
selectedClass:
'border-amber-300 bg-amber-50/82 dark:bg-amber-500/[0.10] dark:border-amber-400/25',
iconClass: 'text-amber-500',
textClass: 'text-amber-700 dark:text-amber-300',
},
];
return (
<div className='space-y-6'>
{/* 页面标题 */}
<div className='flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 rounded-3xl border border-white/70 dark:border-white/10 bg-white/50 dark:bg-white/[0.045] backdrop-blur-xl px-5 py-4'>
<div className='flex items-center gap-3'>
<div className='w-11 h-11 rounded-2xl bg-gradient-to-br from-amber-500 to-yellow-400 flex items-center justify-center shadow-lg shadow-amber-500/20'>
<Bell className='w-5 h-5 text-white' />
</div>
<div>
<h2 className='text-xl font-bold text-gray-900 dark:text-white'>
{t('通知设置')}
</h2>
<p className='text-sm text-gray-500 dark:text-gray-400'>
{t('设置额度预警和系统提醒接收方式')}
</p>
</div>
</div>
<Button
theme='solid'
onClick={handleSubmit}
icon={<Save size={15} />}
className='!bg-gradient-to-r !from-amber-500 !to-yellow-400 !border-0 !rounded-xl !shadow-lg !shadow-amber-500/20'
>
{t('保存设置')}
</Button>
</div>
{/* 表单内容 */}
<div className='bg-white/50 dark:bg-white/[0.045] backdrop-blur-xl rounded-[28px] border border-white/70 dark:border-white/10 p-5 sm:p-6'>
<Form
getFormApi={(api) => (formApiRef.current = api)}
initValues={notificationSettings}
onSubmit={handleSubmit}
>
{/* 通知方式选择 */}
<div className='mb-6'>
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3'>
{t('通知方式')}
</label>
<div className='grid grid-cols-1 sm:grid-cols-2 gap-3'>
{notifyOptions.map((option) => {
const Icon = option.icon;
const isSelected =
notificationSettings.warningType === option.value;
return (
<button
key={option.value}
type='button'
onClick={() =>
handleFormChange('warningType', option.value)
}
className={`p-4 rounded-2xl border transition-all text-left ${
isSelected
? option.selectedClass
: 'border-white/70 dark:border-white/10 bg-white/48 dark:bg-white/[0.035] hover:bg-white/72 dark:hover:bg-white/[0.07]'
}`}
>
<div className='flex items-center gap-3'>
<div className='w-10 h-10 rounded-2xl bg-white/70 dark:bg-white/[0.07] flex items-center justify-center'>
<Icon
size={20}
className={isSelected ? option.iconClass : 'text-gray-400'}
/>
</div>
<div className='min-w-0'>
<div
className={`text-sm font-semibold ${
isSelected
? option.textClass
: 'text-gray-700 dark:text-gray-200'
}`}
>
{option.label}
</div>
<div className='mt-0.5 text-xs text-gray-500 dark:text-gray-400 truncate'>
{option.desc}
</div>
</div>
</div>
</button>
);
})}
</div>
</div>
{/* 预警阈值 */}
<FormQuotaInput
field='warningThreshold'
label={t('额度预警阈值')}
onChange={(val) => handleFormChange('warningThreshold', val)}
extraText={t(
'当剩余额度低于此数值时,系统将通过选择的方式发送通知',
)}
style={{ maxWidth: '320px', width: '100%' }}
rules={[
{ required: true, message: t('请输入预警阈值') },
{
validator: (rule, value) => {
const numValue = Number(value);
if (isNaN(numValue) || numValue <= 0) {
return Promise.reject(t('预警阈值必须为正数'));
}
return Promise.resolve();
},
},
]}
/>
{/* 邮件通知设置 */}
{notificationSettings.warningType === 'email' && (
<div className='mt-4 p-4 bg-sky-50/55 dark:bg-sky-500/[0.07] rounded-2xl border border-sky-100 dark:border-sky-400/20'>
<Form.Input
field='notificationEmail'
label={t('通知邮箱')}
placeholder={t('留空则使用账号绑定的邮箱')}
onChange={(val) => handleFormChange('notificationEmail', val)}
prefix={<IconMail />}
extraText={t(
'设置用于接收额度预警的邮箱地址,不填则使用账号绑定的邮箱',
)}
showClear
/>
</div>
)}
{/* Webhook通知设置 */}
{notificationSettings.warningType === 'webhook' && (
<div className='mt-4 p-4 bg-amber-50/55 dark:bg-amber-500/[0.07] rounded-2xl border border-amber-100 dark:border-amber-400/20 space-y-4'>
<Form.Input
field='webhookUrl'
label={t('Webhook地址')}
placeholder={t(
'请输入Webhook地址,例如: https://example.com/webhook',
)}
onChange={(val) => handleFormChange('webhookUrl', val)}
prefix={<IconLink />}
extraText={t('只支持HTTPS,系统将以POST方式发送通知')}
showClear
rules={[
{
required: notificationSettings.warningType === 'webhook',
message: t('请输入Webhook地址'),
},
{
pattern: /^https:\/\/.+/,
message: t('Webhook地址必须以https://开头'),
},
]}
/>
<Form.Input
field='webhookSecret'
label={t('接口凭证')}
placeholder={t('请输入密钥')}
onChange={(val) => handleFormChange('webhookSecret', val)}
prefix={<IconKey />}
extraText={t('密钥将以Bearer方式添加到请求头中')}
showClear
/>
<div>
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2'>
{t('Webhook请求结构说明')}
</label>
<div style={{ height: '180px' }}>
<CodeViewer
content={{
type: 'quota_exceed',
title: '额度预警通知',
content: '您的额度即将用尽,当前剩余额度为 {{value}}',
values: ['¥0.99'],
timestamp: 1739950503,
}}
title='webhook'
language='json'
/>
</div>
</div>
</div>
)}
</Form>
</div>
</div>
);
};
export default NotificationSection;
@@ -0,0 +1,146 @@
/*
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 from 'react';
import { Button, Switch } from '@douyinfe/semi-ui';
import { Lock, Eye, DollarSign, MapPin } from 'lucide-react';
const PrivacySection = ({
t,
notificationSettings,
handleNotificationSettingChange,
saveNotificationSettings,
}) => {
// 隐私设置卡片
const PrivacyCard = ({
icon: Icon,
gradient,
title,
description,
checked,
onChange,
}) => (
<div className='p-5 rounded-xl bg-white/50 dark:bg-gray-800/50 border border-gray-100 dark:border-gray-700/50 hover:shadow-lg transition-all'>
<div className='flex items-start gap-4'>
<div
className={`w-12 h-12 rounded-xl flex items-center justify-center bg-gradient-to-br ${gradient} shadow-lg flex-shrink-0`}
>
<Icon className='w-6 h-6 text-white' />
</div>
<div className='flex-1 min-w-0'>
<div className='flex items-center justify-between'>
<div>
<h3 className='font-semibold text-gray-900 dark:text-white mb-1'>
{title}
</h3>
<p className='text-sm text-gray-500 dark:text-gray-400'>
{description}
</p>
</div>
<Switch
checked={checked}
onChange={onChange}
size='large'
checkedText={t('开')}
uncheckedText={t('关')}
/>
</div>
</div>
</div>
</div>
);
return (
<div>
{/* 页面标题 */}
<div className='flex items-center justify-between mb-6'>
<div className='flex items-center gap-3'>
<div className='w-10 h-10 rounded-xl bg-gradient-to-br from-brand-from to-pink-600 flex items-center justify-center shadow-lg shadow-brand/25'>
<Lock className='w-5 h-5 text-white' />
</div>
<div>
<h2 className='text-xl font-bold text-gray-900 dark:text-white'>
{t('隐私设置')}
</h2>
<p className='text-sm text-gray-500 dark:text-gray-400'>
{t('控制您的数据记录和价格偏好')}
</p>
</div>
</div>
<Button
theme='solid'
onClick={saveNotificationSettings}
className='!bg-gradient-to-r !from-brand-from !to-pink-500 !border-0 !rounded-lg'
>
{t('保存设置')}
</Button>
</div>
{/* 隐私设置列表 */}
<div className='space-y-4'>
{/* IP记录设置 */}
<PrivacyCard
icon={MapPin}
gradient='from-rose-500 to-pink-500'
title={t('记录请求与错误日志IP')}
description={t('开启后,仅"消费"和"错误"日志将记录您的客户端IP地址')}
checked={notificationSettings.recordIpLog}
onChange={(value) =>
handleNotificationSettingChange('recordIpLog', value)
}
/>
{/* 未设置价格模型 */}
<PrivacyCard
icon={DollarSign}
gradient='from-amber-500 to-orange-500'
title={t('接受未设置价格模型')}
description={t(
'当模型没有设置价格时仍接受调用,仅当您信任该网站时使用,可能会产生高额费用',
)}
checked={notificationSettings.acceptUnsetModelRatioModel}
onChange={(value) =>
handleNotificationSettingChange('acceptUnsetModelRatioModel', value)
}
/>
</div>
{/* 提示信息 */}
<div className='mt-6 p-4 bg-brand/50 dark:bg-brand-deep/10 rounded-xl border border-brand/10 dark:border-brand-deep/30'>
<div className='flex items-start gap-3'>
<div className='w-8 h-8 rounded-lg bg-brand/10 dark:bg-brand-deep/30 flex items-center justify-center flex-shrink-0'>
<Eye size={16} className='text-brand' />
</div>
<div>
<h4 className='font-medium text-gray-900 dark:text-white mb-1'>
{t('隐私提示')}
</h4>
<p className='text-sm text-gray-500 dark:text-gray-400'>
{t(
'我们重视您的隐私。您的设置选择将仅应用于您的账户,不会影响其他用户。如需删除历史数据,请联系客服。',
)}
</p>
</div>
</div>
</div>
</div>
);
};
export default PrivacySection;
@@ -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 from 'react';
import { Button, Modal } from '@douyinfe/semi-ui';
import { IconLock, IconDelete } from '@douyinfe/semi-icons';
import { Shield, Lock, Fingerprint, Trash2, AlertTriangle } from 'lucide-react';
const SecuritySection = ({
t,
status,
setShowChangePasswordModal,
setShowAccountDeleteModal,
hasPassword,
passkeyStatus,
passkeySupported,
passkeyRegisterLoading,
passkeyDeleteLoading,
onPasskeyRegister,
onPasskeyDelete,
}) => {
const passkeyEnabled = passkeyStatus?.enabled;
const lastUsedLabel = passkeyStatus?.last_used_at
? new Date(passkeyStatus.last_used_at).toLocaleString()
: t('尚未使用');
// 安全设置卡片
const SecurityCard = ({
icon: Icon,
gradient,
title,
description,
children,
danger = false,
}) => (
<div
className={`p-5 rounded-[24px] border backdrop-blur-xl transition-all ${
danger
? 'bg-gradient-to-br from-red-50/70 to-rose-50/60 dark:from-red-500/[0.09] dark:to-rose-500/[0.07] border-red-100/80 dark:border-red-400/20'
: 'bg-white/54 dark:bg-white/[0.045] border-white/70 dark:border-white/10'
} hover:shadow-[0_18px_50px_rgba(15,23,42,0.10)]`}
>
<div className='flex items-start gap-4'>
<div
className={`w-12 h-12 rounded-2xl flex items-center justify-center bg-gradient-to-br ${gradient} shadow-lg flex-shrink-0`}
>
<Icon className='w-6 h-6 text-white' />
</div>
<div className='flex-1 min-w-0'>
<h3 className='font-semibold text-gray-900 dark:text-white mb-1'>
{title}
</h3>
<p className='text-sm text-gray-500 dark:text-gray-400 mb-4'>
{description}
</p>
{children}
</div>
</div>
</div>
);
return (
<div className='space-y-6'>
{/* 页面标题 */}
<div className='flex items-center gap-3 rounded-3xl border border-white/70 dark:border-white/10 bg-white/50 dark:bg-white/[0.045] backdrop-blur-xl px-5 py-4'>
<div className='w-11 h-11 rounded-2xl bg-gradient-to-br from-emerald-500 to-teal-400 flex items-center justify-center shadow-lg shadow-emerald-500/20'>
<Shield className='w-5 h-5 text-white' />
</div>
<div>
<h2 className='text-xl font-bold text-gray-900 dark:text-white'>
{t('安全设置')}
</h2>
<p className='text-sm text-gray-500 dark:text-gray-400'>
{t('集中管理密码和免密登录')}
</p>
</div>
</div>
{/* 安全设置卡片列表 */}
<div className='space-y-4'>
{/* 密码管理 */}
<SecurityCard
icon={Lock}
gradient='from-blue-500 to-brand-to'
title={t('密码管理')}
description={
hasPassword
? t('定期更改密码可以提高账户安全性')
: t('设置密码后可使用账号密码登录')
}
>
<Button
theme='solid'
onClick={() => setShowChangePasswordModal(true)}
className='!bg-gradient-to-r !from-blue-500 !to-brand-to !border-0 !rounded-lg'
icon={<IconLock />}
>
{hasPassword ? t('修改密码') : t('设置密码')}
</Button>
</SecurityCard>
{/* Passkey 登录 - 仅管理员启用时显示 */}
{status.passkey_login && (
<SecurityCard
icon={Fingerprint}
gradient={
passkeyEnabled
? 'from-emerald-500 to-teal-500'
: 'from-brand-from to-pink-500'
}
title={t('Passkey 登录')}
description={
passkeyEnabled
? t('已启用 Passkey,无需密码即可登录')
: t('使用 Passkey 实现免密且更安全的登录体验')
}
>
<div className='mb-4 space-y-2'>
<div className='flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400'>
<span>{t('最后使用时间')}:</span>
<span className='font-medium text-gray-700 dark:text-gray-300'>
{lastUsedLabel}
</span>
</div>
{!passkeySupported && (
<div className='flex items-center gap-2 text-sm text-amber-600 dark:text-amber-400'>
<AlertTriangle size={14} />
{t('当前设备不支持 Passkey')}
</div>
)}
</div>
<Button
theme='solid'
type={passkeyEnabled ? 'danger' : 'primary'}
onClick={
passkeyEnabled
? () => {
Modal.confirm({
title: t('确认解绑 Passkey'),
content: t(
'解绑后将无法使用 Passkey 登录,确定要继续吗?',
),
okText: t('确认解绑'),
cancelText: t('取消'),
okType: 'danger',
onOk: onPasskeyDelete,
});
}
: onPasskeyRegister
}
className={`!rounded-lg ${
passkeyEnabled
? '!bg-gradient-to-r !from-red-500 !to-rose-500 !border-0'
: '!bg-gradient-to-r !from-brand-from !to-pink-500 !border-0'
}`}
disabled={!passkeySupported && !passkeyEnabled}
loading={
passkeyEnabled ? passkeyDeleteLoading : passkeyRegisterLoading
}
>
{passkeyEnabled ? t('解绑 Passkey') : t('注册 Passkey')}
</Button>
</SecurityCard>
)}
{/* 危险区域 - 删除账户 */}
<SecurityCard
icon={Trash2}
gradient='from-red-500 to-rose-500'
title={t('删除账户')}
description={t('此操作不可逆,所有数据将被永久删除')}
danger
>
<Button
type='danger'
theme='solid'
onClick={() => setShowAccountDeleteModal(true)}
className='!bg-gradient-to-r !from-red-500 !to-rose-500 !border-0 !rounded-lg'
icon={<IconDelete />}
>
{t('删除账户')}
</Button>
</SecurityCard>
</div>
</div>
);
};
export default SecuritySection;
@@ -0,0 +1,373 @@
/*
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 { Button, Switch, Row, Col } from '@douyinfe/semi-ui';
import {
LayoutGrid,
MessageSquare,
BarChart2,
User,
Shield,
} from 'lucide-react';
import { API, showSuccess, showError } from '../../../../helpers';
import { StatusContext } from '../../../../context/Status';
import { useUserPermissions } from '../../../../hooks/common/useUserPermissions';
import { useSidebar } from '../../../../hooks/common/useSidebar';
const SidebarSection = ({ t }) => {
const [statusState] = useContext(StatusContext);
const [sidebarLoading, setSidebarLoading] = useState(false);
const [sidebarModulesUser, setSidebarModulesUser] = useState({
chat: { enabled: true, playground: true, chat: true },
console: {
enabled: true,
detail: true,
token: true,
log: true,
midjourney: true,
task: true,
monitor: true,
},
personal: { enabled: true, topup: true, personal: true },
admin: {
enabled: true,
analytics: true,
channel: true,
models: true,
redemption: true,
user: true,
subscription: true,
'admin-token': true,
organizations: true,
order: true,
invoice: true,
setting: true,
},
});
const [adminConfig, setAdminConfig] = useState(null);
const {
hasSidebarSettingsPermission,
isSidebarSectionAllowed,
isSidebarModuleAllowed,
} = useUserPermissions();
const { refreshUserConfig } = useSidebar();
const handleSectionChange = (sectionKey) => (checked) => {
setSidebarModulesUser((prev) => ({
...prev,
[sectionKey]: { ...prev[sectionKey], enabled: checked },
}));
};
const handleModuleChange = (sectionKey, moduleKey) => (checked) => {
setSidebarModulesUser((prev) => ({
...prev,
[sectionKey]: { ...prev[sectionKey], [moduleKey]: checked },
}));
};
const saveSidebarSettings = async () => {
setSidebarLoading(true);
try {
const res = await API.put('/api/user/self', {
sidebar_modules: JSON.stringify(sidebarModulesUser),
});
if (res.data.success) {
showSuccess(t('侧边栏设置保存成功'));
await refreshUserConfig();
} else {
showError(res.data.message);
}
} catch (error) {
showError(t('保存失败'));
}
setSidebarLoading(false);
};
const resetSidebarModules = () => {
setSidebarModulesUser({
chat: { enabled: true, playground: true, chat: true },
console: {
enabled: true,
detail: true,
token: true,
log: true,
midjourney: true,
task: true,
},
personal: { enabled: true, topup: true, personal: true },
admin: {
enabled: true,
channel: true,
models: true,
redemption: true,
user: true,
setting: true,
},
});
};
useEffect(() => {
const loadSidebarConfigs = async () => {
try {
if (statusState?.status?.SidebarModulesAdmin) {
setAdminConfig(JSON.parse(statusState.status.SidebarModulesAdmin));
}
const userRes = await API.get('/api/user/self');
if (userRes.data.success && userRes.data.data.sidebar_modules) {
setSidebarModulesUser(JSON.parse(userRes.data.data.sidebar_modules));
}
} catch (error) {
console.error('加载边栏配置失败:', error);
}
};
loadSidebarConfigs();
}, [statusState]);
const isAllowedByAdmin = (sectionKey, moduleKey = null) => {
if (!adminConfig) return true;
if (moduleKey) {
return (
adminConfig[sectionKey]?.enabled && adminConfig[sectionKey]?.[moduleKey]
);
}
return adminConfig[sectionKey]?.enabled;
};
// 区域配置
const sectionConfigs = [
{
key: 'chat',
title: t('聊天区域'),
description: t('操练场和聊天功能'),
icon: MessageSquare,
gradient: 'from-blue-500 to-cyan-500',
modules: [
{
key: 'playground',
title: t('操练场'),
description: t('AI模型测试环境'),
},
{ key: 'chat', title: t('聊天'), description: t('聊天会话管理') },
],
},
{
key: 'console',
title: t('控制台区域'),
description: t('数据管理和日志查看'),
icon: BarChart2,
gradient: 'from-emerald-500 to-teal-500',
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('用户个人功能'),
icon: User,
gradient: 'from-brand-from to-pink-500',
modules: [
{ key: 'topup', title: t('钱包管理'), description: t('余额充值管理') },
{
key: 'personal',
title: t('个人设置'),
description: t('个人信息设置'),
},
],
},
{
key: 'admin',
title: t('管理员区域'),
description: t('系统管理功能'),
icon: Shield,
gradient: 'from-orange-500 to-red-500',
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) => 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),
);
if (!hasSidebarSettingsPermission()) {
return (
<div className='flex items-center justify-center h-64 text-gray-500'>
{t('您没有权限访问此设置')}
</div>
);
}
return (
<div>
{/* 页面标题 */}
<div className='flex items-center justify-between mb-6'>
<div className='flex items-center gap-3'>
<div className='w-10 h-10 rounded-xl bg-gradient-to-br from-cyan-500 to-blue-600 flex items-center justify-center shadow-lg shadow-cyan-500/25'>
<LayoutGrid className='w-5 h-5 text-white' />
</div>
<div>
<h2 className='text-xl font-bold text-gray-900 dark:text-white'>
{t('边栏设置')}
</h2>
<p className='text-sm text-gray-500 dark:text-gray-400'>
{t('个性化设置侧边栏的显示功能')}
</p>
</div>
</div>
<div className='flex gap-2'>
<Button
type='tertiary'
theme='light'
onClick={resetSidebarModules}
className='!rounded-lg !border !border-gray-200 dark:!border-neutral-700'
style={{ color: '#4b5563' }}
>
{t('重置为默认')}
</Button>
<Button
theme='solid'
onClick={saveSidebarSettings}
loading={sidebarLoading}
className='!bg-gradient-to-r !from-cyan-500 !to-blue-500 !border-0 !rounded-lg'
>
{t('保存设置')}
</Button>
</div>
</div>
{/* 区域设置列表 */}
<div className='space-y-6'>
{sectionConfigs.map((section) => {
const Icon = section.icon;
return (
<div
key={section.key}
className='bg-white/50 dark:bg-gray-800/50 rounded-xl border border-gray-100 dark:border-gray-700/50 overflow-hidden'
>
{/* 区域标题和总开关 */}
<div
className={`flex justify-between items-center p-5 bg-gradient-to-r ${section.gradient} bg-opacity-5`}
>
<div className='flex items-center gap-3'>
<div
className={`w-10 h-10 rounded-lg bg-gradient-to-br ${section.gradient} flex items-center justify-center shadow-lg`}
>
<Icon className='w-5 h-5 text-white' />
</div>
<div>
<h3 className='font-semibold text-gray-900 dark:text-white'>
{section.title}
</h3>
<p className='text-sm text-gray-500 dark:text-gray-400'>
{section.description}
</p>
</div>
</div>
<Switch
checked={sidebarModulesUser[section.key]?.enabled}
onChange={handleSectionChange(section.key)}
size='large'
/>
</div>
{/* 功能模块网格 */}
<div className='p-5'>
<Row gutter={[12, 12]}>
{section.modules
.filter((module) =>
isAllowedByAdmin(section.key, module.key),
)
.map((module) => (
<Col key={module.key} xs={24} sm={12} md={8} lg={6}>
<div
className={`p-4 rounded-xl border transition-all ${
sidebarModulesUser[section.key]?.enabled
? 'border-gray-200 dark:border-gray-700 hover:border-blue-300 dark:hover:border-blue-700'
: 'border-gray-100 dark:border-gray-800 opacity-50'
}`}
>
<div className='flex justify-between items-center'>
<div>
<div className='font-medium text-sm text-gray-900 dark:text-white'>
{module.title}
</div>
<div className='text-xs text-gray-500 dark:text-gray-400 mt-0.5'>
{module.description}
</div>
</div>
<Switch
checked={
sidebarModulesUser[section.key]?.[module.key]
}
onChange={handleModuleChange(
section.key,
module.key,
)}
size='small'
disabled={
!sidebarModulesUser[section.key]?.enabled
}
/>
</div>
</div>
</Col>
))}
</Row>
</div>
</div>
);
})}
</div>
</div>
);
};
export default SidebarSection;