Files
monkey-ai-web/src/components/settings/PersonalSetting.jsx
T
qiubaishen a57aae3043 sync: 同步 monkey-ai@weiyuan(ddc5b9443) 的 web/ 到 ui-optimization
- 合入 weiyuan 新功能前端:分佣 V2 / 伙伴工作台、智能路由、企业资金与分析、官网设置与预约演示等,
  semi-ui 已全部迁移到 antd 6 / @/components/ui,不重新引入 Semi
- 分佣二级菜单与页头去重、伙伴入口探测(企业伙伴走企业中心「企业分佣」)、超管侧栏入口恢复
- 适配层 DatePicker / TimePicker 统一 onChange(Date|Date[]|null, 文本) 契约;生产构建剔除调试日志
- 图片链接刷新:同任务请求复用、后台刷新不弹全局错误、离页停止批量请求
- 恢复 bun.lock(与 package-lock.json 共存);docs 规范与 CHANGELOG 更新
- 停止跟踪 .env.playwright.local(本地登录凭据,已加入 .gitignore)
2026-11-18 10:22:02 +08:00

737 lines
24 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
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 { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import { Check as ActionCheck } from '@/components/common/icons/ActionIcons';
import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import { writeClipboardText } from '../../helpers/clipboard';
import React, { useContext, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import UserCenterPageHeader from '../common/UserCenterPageHeader';
import { useConsolePage } from '../console/ConsoleContext';
import {
API,
showError,
showInfo,
showSuccess,
setStatusData,
prepareCredentialCreationOptions,
buildRegistrationResult,
isPasskeySupported,
setUserData,
clearUserData,
renderQuota,
isRoot,
isAdmin,
USER_AVATAR_TYPES,
getAvatarPresetById,
getDefaultAvatarPresetId,
getUserAvatarUrl,
parseUserSetting,
} from '../../helpers';
import { UserContext } from '../../context/User';
import { Tag as AntTag } from 'antd';
import { Avatar, Tooltip, Card, Tabs } from '@/components/ui';
import { useTranslation } from 'react-i18next';
// 导入内容区组件
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';
import './personal/personal-settings.css';
// 设置页签(原型为纯文字页签,选中态由 Ant Design Tabs 呈现)
const NAV_ITEMS = [
{ key: 'avatar', label: '头像设置' },
{ key: 'binding', label: '账号绑定' },
{ key: 'security', label: '安全设置' },
{ key: 'notification', label: '通知设置' },
];
const PersonalSetting = () => {
const consolePage = useConsolePage();
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,
});
const onMount = useEffectEvent(() => {
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(() => onMount(), [onMount]);
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]);
const onScopeChange2 = useEffectEvent(() => {
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),
}));
}
});
useEffect(
() => onScopeChange2(),
[onScopeChange2, 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:走公共 copy,HTTP 部署下 navigator.clipboard 为 undefined,
// 直接调用 writeText 会同步抛错,.catch 降级永远走不到。
const copyUserId = async () => {
const userId = String(userState?.user?.id || '');
writeClipboardText(userId)
.then(() => {
setUserIdCopied(true);
setTimeout(() => setUserIdCopied(false), 2000);
})
.catch(() => {
showError(t('复制失败,请手动复制'));
});
};
// 获取用户名
const getUsername = () => userState.user?.username || 'User';
const getDisplayName = () => userState.user?.display_name || getUsername();
const getAvatarText = () => getUsername().slice(0, 2).toUpperCase();
const userAvatarUrl = getUserAvatarUrl(userState?.user);
// 获取角色标签
const getRoleTag = () => {
if (isRoot()) return { text: t('超级管理员') };
if (isAdmin()) return { text: t('管理员') };
return { text: t('普通用户') };
};
// 渲染内容区域
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={`ui-personal-settings ${consolePage ? 'console-personal' : 'min-h-screen pt-16 sm:pt-20'}`}
>
<div
className={`ui-personal-inner ${consolePage ? 'console-content' : 'uc-page'}`}
>
{!consolePage && (
<UserCenterPageHeader
title={t('个人设置')}
subtitle={t('管理你的平台形象、账户安全与通知偏好')}
/>
)}
<Card className='ui-personal-profile'>
<div className='ui-profile-identity'>
<span className='ui-profile-avatar'>
<Avatar shape='square' size={54} src={userAvatarUrl}>
{getAvatarText()}
</Avatar>
</span>
<div className='ui-profile-meta'>
<div className='ui-profile-name'>
<strong>{getDisplayName()}</strong>
<AntTag color='gold' variant='filled'>
{roleInfo.text}
</AntTag>
</div>
<div className='ui-profile-sub'>
<span>
{t('用户名')}:{getUsername()}
</span>
<span aria-hidden='true'>·</span>
<Tooltip
content={userIdCopied ? t('已复制') : t('点击复制用户ID')}
>
<button
type='button'
className='app-action-button ui-profile-id'
onClick={copyUserId}
>
{I18N_TECHNICAL_TEXT.ID_PREFIX_CJK}
{userState?.user?.id}
{userIdCopied && <ActionCheck size={12} />}
</button>
</Tooltip>
<span aria-hidden='true'>·</span>
<span>
{t('分组')}:{userState?.user?.group || '-'}
</span>
</div>
</div>
</div>
<div className='ui-profile-stats'>
<div>
<span>{t('可用余额')}</span>
<strong>{renderQuota(userState?.user?.quota)}</strong>
</div>
<div>
<span>{t('累计支出')}</span>
<strong>{renderQuota(userState?.user?.used_quota)}</strong>
</div>
<div>
<span>{t('调用次数')}</span>
<strong>{userState?.user?.request_count || 0}</strong>
</div>
</div>
</Card>
<Card className='ui-personal-content'>
<Tabs
activeKey={activeNav}
onChange={setActiveNav}
tabList={NAV_ITEMS.map((item) => ({
itemKey: item.key,
tab: t(item.label),
label: t(item.label),
}))}
/>
{renderContent()}
</Card>
</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;