Commit f0925dc1 by CaIon

feat: Enhance user settings and notification options

parent f502e49c
package constant package constant
var ( var (
UserSettingNotifyType = "notify_type" // QuotaWarningType 额度预警类型 UserSettingNotifyType = "notify_type" // QuotaWarningType 额度预警类型
UserSettingQuotaWarningThreshold = "quota_warning_threshold" // QuotaWarningThreshold 额度预警阈值 UserSettingQuotaWarningThreshold = "quota_warning_threshold" // QuotaWarningThreshold 额度预警阈值
UserSettingWebhookUrl = "webhook_url" // WebhookUrl webhook地址 UserSettingWebhookUrl = "webhook_url" // WebhookUrl webhook地址
UserSettingWebhookSecret = "webhook_secret" // WebhookSecret webhook密钥 UserSettingWebhookSecret = "webhook_secret" // WebhookSecret webhook密钥
UserSettingNotificationEmail = "notification_email" // NotificationEmail 通知邮箱地址 UserSettingNotificationEmail = "notification_email" // NotificationEmail 通知邮箱地址
UserAcceptUnsetRatioModel = "accept_unset_model_ratio_model" // AcceptUnsetRatioModel 是否接受未设置价格的模型
) )
var ( var (
......
...@@ -105,6 +105,11 @@ func testChannel(channel *model.Channel, testModel string) (err error, openAIErr ...@@ -105,6 +105,11 @@ func testChannel(channel *model.Channel, testModel string) (err error, openAIErr
request := buildTestRequest(testModel) request := buildTestRequest(testModel)
common.SysLog(fmt.Sprintf("testing channel %d with model %s , info %v ", channel.Id, testModel, info)) common.SysLog(fmt.Sprintf("testing channel %d with model %s , info %v ", channel.Id, testModel, info))
priceData, err := helper.ModelPriceHelper(c, info, 0, int(request.MaxTokens))
if err != nil {
return err, nil
}
adaptor.Init(info) adaptor.Init(info)
convertedRequest, err := adaptor.ConvertOpenAIRequest(c, info, request) convertedRequest, err := adaptor.ConvertOpenAIRequest(c, info, request)
...@@ -143,10 +148,7 @@ func testChannel(channel *model.Channel, testModel string) (err error, openAIErr ...@@ -143,10 +148,7 @@ func testChannel(channel *model.Channel, testModel string) (err error, openAIErr
return err, nil return err, nil
} }
info.PromptTokens = usage.PromptTokens info.PromptTokens = usage.PromptTokens
priceData, err := helper.ModelPriceHelper(c, info, usage.PromptTokens, int(request.MaxTokens))
if err != nil {
return err, nil
}
quota := 0 quota := 0
if !priceData.UsePrice { if !priceData.UsePrice {
quota = usage.PromptTokens + int(math.Round(float64(usage.CompletionTokens)*priceData.CompletionRatio)) quota = usage.PromptTokens + int(math.Round(float64(usage.CompletionTokens)*priceData.CompletionRatio))
......
...@@ -913,11 +913,12 @@ func TopUp(c *gin.Context) { ...@@ -913,11 +913,12 @@ func TopUp(c *gin.Context) {
} }
type UpdateUserSettingRequest struct { type UpdateUserSettingRequest struct {
QuotaWarningType string `json:"notify_type"` QuotaWarningType string `json:"notify_type"`
QuotaWarningThreshold float64 `json:"quota_warning_threshold"` QuotaWarningThreshold float64 `json:"quota_warning_threshold"`
WebhookUrl string `json:"webhook_url,omitempty"` WebhookUrl string `json:"webhook_url,omitempty"`
WebhookSecret string `json:"webhook_secret,omitempty"` WebhookSecret string `json:"webhook_secret,omitempty"`
NotificationEmail string `json:"notification_email,omitempty"` NotificationEmail string `json:"notification_email,omitempty"`
AcceptUnsetModelRatioModel bool `json:"accept_unset_model_ratio_model"`
} }
func UpdateUserSetting(c *gin.Context) { func UpdateUserSetting(c *gin.Context) {
...@@ -993,6 +994,7 @@ func UpdateUserSetting(c *gin.Context) { ...@@ -993,6 +994,7 @@ func UpdateUserSetting(c *gin.Context) {
settings := map[string]interface{}{ settings := map[string]interface{}{
constant.UserSettingNotifyType: req.QuotaWarningType, constant.UserSettingNotifyType: req.QuotaWarningType,
constant.UserSettingQuotaWarningThreshold: req.QuotaWarningThreshold, constant.UserSettingQuotaWarningThreshold: req.QuotaWarningThreshold,
"accept_unset_model_ratio_model": req.AcceptUnsetModelRatioModel,
} }
// 如果是webhook类型,添加webhook相关设置 // 如果是webhook类型,添加webhook相关设置
......
...@@ -4,6 +4,7 @@ import ( ...@@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"one-api/common" "one-api/common"
constant2 "one-api/constant"
relaycommon "one-api/relay/common" relaycommon "one-api/relay/common"
"one-api/setting" "one-api/setting"
"one-api/setting/operation_setting" "one-api/setting/operation_setting"
...@@ -40,10 +41,19 @@ func ModelPriceHelper(c *gin.Context, info *relaycommon.RelayInfo, promptTokens ...@@ -40,10 +41,19 @@ func ModelPriceHelper(c *gin.Context, info *relaycommon.RelayInfo, promptTokens
var success bool var success bool
modelRatio, success = operation_setting.GetModelRatio(info.OriginModelName) modelRatio, success = operation_setting.GetModelRatio(info.OriginModelName)
if !success { if !success {
if info.UserId == 1 { acceptUnsetRatio := false
return PriceData{}, fmt.Errorf("模型 %s 倍率或价格未配置,请设置或开始自用模式;Model %s ratio or price not set, please set or start self-use mode", info.OriginModelName, info.OriginModelName) if accept, ok := info.UserSetting[constant2.UserAcceptUnsetRatioModel]; ok {
} else { b, ok := accept.(bool)
return PriceData{}, fmt.Errorf("模型 %s 倍率或价格未配置, 请联系管理员设置;Model %s ratio or price not set, please contact administrator to set", info.OriginModelName, info.OriginModelName) if ok {
acceptUnsetRatio = b
}
}
if !acceptUnsetRatio {
if info.UserId == 1 {
return PriceData{}, fmt.Errorf("模型 %s 倍率或价格未配置,请设置或开始自用模式;Model %s ratio or price not set, please set or start self-use mode", info.OriginModelName, info.OriginModelName)
} else {
return PriceData{}, fmt.Errorf("模型 %s 倍率或价格未配置, 请联系管理员设置;Model %s ratio or price not set, please contact administrator to set", info.OriginModelName, info.OriginModelName)
}
} }
} }
completionRatio = operation_setting.GetCompletionRatio(info.OriginModelName) completionRatio = operation_setting.GetCompletionRatio(info.OriginModelName)
......
This source diff could not be displayed because it is too large. You can view the blob instead.
import React, {useContext, useEffect, useState} from 'react'; import React, { useContext, useEffect, useState } from 'react';
import {useNavigate} from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { import {
API, API,
copy, copy,
isRoot, isRoot,
showError, showError,
showInfo, showInfo,
showSuccess, showSuccess
} from '../helpers'; } from '../helpers';
import Turnstile from 'react-turnstile'; import Turnstile from 'react-turnstile';
import {UserContext} from '../context/User'; import { UserContext } from '../context/User';
import {onGitHubOAuthClicked, onOIDCClicked, onLinuxDOOAuthClicked} from './utils'; import { onGitHubOAuthClicked, onOIDCClicked, onLinuxDOOAuthClicked } from './utils';
import { import {
Avatar, Avatar,
Banner, Banner,
Button, Button,
Card, Card,
Descriptions, Descriptions,
Image, Image,
Input, Input,
InputNumber, InputNumber,
Layout, Layout,
Modal, Modal,
Space, Space,
Tag, Tag,
Typography, Typography,
Collapsible, Collapsible,
Select, Select,
Radio, Radio,
RadioGroup, RadioGroup,
AutoComplete, AutoComplete,
Checkbox,
Tabs,
TabPane
} from '@douyinfe/semi-ui'; } from '@douyinfe/semi-ui';
import { import {
getQuotaPerUnit, getQuotaPerUnit,
renderQuota, renderQuota,
renderQuotaWithPrompt, renderQuotaWithPrompt,
stringToColor, stringToColor
} from '../helpers/render'; } from '../helpers/render';
import TelegramLoginButton from 'react-telegram-login'; import TelegramLoginButton from 'react-telegram-login';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
const PersonalSetting = () => { const PersonalSetting = () => {
const [userState, userDispatch] = useContext(UserContext); const [userState, userDispatch] = useContext(UserContext);
let navigate = useNavigate(); let navigate = useNavigate();
const { t } = useTranslation(); const { t } = useTranslation();
const [inputs, setInputs] = useState({ const [inputs, setInputs] = useState({
wechat_verification_code: '', wechat_verification_code: '',
email_verification_code: '', email_verification_code: '',
email: '', email: '',
self_account_deletion_confirmation: '', self_account_deletion_confirmation: '',
set_new_password: '', set_new_password: '',
set_new_password_confirmation: '', set_new_password_confirmation: ''
}); });
const [status, setStatus] = useState({}); const [status, setStatus] = useState({});
const [showChangePasswordModal, setShowChangePasswordModal] = useState(false); const [showChangePasswordModal, setShowChangePasswordModal] = useState(false);
const [showWeChatBindModal, setShowWeChatBindModal] = useState(false); const [showWeChatBindModal, setShowWeChatBindModal] = useState(false);
const [showEmailBindModal, setShowEmailBindModal] = useState(false); const [showEmailBindModal, setShowEmailBindModal] = useState(false);
const [showAccountDeleteModal, setShowAccountDeleteModal] = useState(false); const [showAccountDeleteModal, setShowAccountDeleteModal] = useState(false);
const [turnstileEnabled, setTurnstileEnabled] = useState(false); const [turnstileEnabled, setTurnstileEnabled] = useState(false);
const [turnstileSiteKey, setTurnstileSiteKey] = useState(''); const [turnstileSiteKey, setTurnstileSiteKey] = useState('');
const [turnstileToken, setTurnstileToken] = useState(''); const [turnstileToken, setTurnstileToken] = useState('');
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [disableButton, setDisableButton] = useState(false); const [disableButton, setDisableButton] = useState(false);
const [countdown, setCountdown] = useState(30); const [countdown, setCountdown] = useState(30);
const [affLink, setAffLink] = useState(''); const [affLink, setAffLink] = useState('');
const [systemToken, setSystemToken] = useState(''); const [systemToken, setSystemToken] = useState('');
const [models, setModels] = useState([]); const [models, setModels] = useState([]);
const [openTransfer, setOpenTransfer] = useState(false); const [openTransfer, setOpenTransfer] = useState(false);
const [transferAmount, setTransferAmount] = useState(0); const [transferAmount, setTransferAmount] = useState(0);
const [isModelsExpanded, setIsModelsExpanded] = useState(() => { const [isModelsExpanded, setIsModelsExpanded] = useState(() => {
// Initialize from localStorage if available // Initialize from localStorage if available
const savedState = localStorage.getItem('modelsExpanded'); const savedState = localStorage.getItem('modelsExpanded');
return savedState ? JSON.parse(savedState) : false; return savedState ? JSON.parse(savedState) : false;
}); });
const MODELS_DISPLAY_COUNT = 10; // 默认显示的模型数量 const MODELS_DISPLAY_COUNT = 10; // 默认显示的模型数量
const [notificationSettings, setNotificationSettings] = useState({ const [notificationSettings, setNotificationSettings] = useState({
warningType: 'email', warningType: 'email',
warningThreshold: 100000, warningThreshold: 100000,
webhookUrl: '', webhookUrl: '',
webhookSecret: '', webhookSecret: '',
notificationEmail: '' notificationEmail: '',
acceptUnsetModelRatioModel: false
});
const [showWebhookDocs, setShowWebhookDocs] = useState(false);
useEffect(() => {
let status = localStorage.getItem('status');
if (status) {
status = JSON.parse(status);
setStatus(status);
if (status.turnstile_check) {
setTurnstileEnabled(true);
setTurnstileSiteKey(status.turnstile_site_key);
}
}
getUserData().then((res) => {
console.log(userState);
}); });
const [showWebhookDocs, setShowWebhookDocs] = useState(false); loadModels().then();
getAffLink().then();
setTransferAmount(getQuotaPerUnit());
}, []);
useEffect(() => { useEffect(() => {
let status = localStorage.getItem('status'); let countdownInterval = null;
if (status) { if (disableButton && countdown > 0) {
status = JSON.parse(status); countdownInterval = setInterval(() => {
setStatus(status); setCountdown(countdown - 1);
if (status.turnstile_check) { }, 1000);
setTurnstileEnabled(true); } else if (countdown === 0) {
setTurnstileSiteKey(status.turnstile_site_key); setDisableButton(false);
} setCountdown(30);
} }
getUserData().then((res) => { return () => clearInterval(countdownInterval); // Clean up on unmount
console.log(userState); }, [disableButton, countdown]);
});
loadModels().then();
getAffLink().then();
setTransferAmount(getQuotaPerUnit());
}, []);
useEffect(() => { useEffect(() => {
let countdownInterval = null; if (userState?.user?.setting) {
if (disableButton && countdown > 0) { const settings = JSON.parse(userState.user.setting);
countdownInterval = setInterval(() => { setNotificationSettings({
setCountdown(countdown - 1); warningType: settings.notify_type || 'email',
}, 1000); warningThreshold: settings.quota_warning_threshold || 500000,
} else if (countdown === 0) { webhookUrl: settings.webhook_url || '',
setDisableButton(false); webhookSecret: settings.webhook_secret || '',
setCountdown(30); notificationEmail: settings.notification_email || '',
} acceptUnsetModelRatioModel: settings.accept_unset_model_ratio_model || false
return () => clearInterval(countdownInterval); // Clean up on unmount });
}, [disableButton, countdown]); }
}, [userState?.user?.setting]);
useEffect(() => { // Save models expanded state to localStorage whenever it changes
if (userState?.user?.setting) { useEffect(() => {
const settings = JSON.parse(userState.user.setting); localStorage.setItem('modelsExpanded', JSON.stringify(isModelsExpanded));
setNotificationSettings({ }, [isModelsExpanded]);
warningType: settings.notify_type || 'email',
warningThreshold: settings.quota_warning_threshold || 500000,
webhookUrl: settings.webhook_url || '',
webhookSecret: settings.webhook_secret || '',
notificationEmail: settings.notification_email || ''
});
}
}, [userState?.user?.setting]);
// Save models expanded state to localStorage whenever it changes const handleInputChange = (name, value) => {
useEffect(() => { setInputs((inputs) => ({ ...inputs, [name]: value }));
localStorage.setItem('modelsExpanded', JSON.stringify(isModelsExpanded)); };
}, [isModelsExpanded]);
const handleInputChange = (name, value) => { const generateAccessToken = async () => {
setInputs((inputs) => ({...inputs, [name]: value})); const res = await API.get('/api/user/token');
}; const { success, message, data } = res.data;
if (success) {
setSystemToken(data);
await copy(data);
showSuccess(t('令牌已重置并已复制到剪贴板'));
} else {
showError(message);
}
};
const generateAccessToken = async () => { const getAffLink = async () => {
const res = await API.get('/api/user/token'); const res = await API.get('/api/user/aff');
const {success, message, data} = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
setSystemToken(data); let link = `${window.location.origin}/register?aff=${data}`;
await copy(data); setAffLink(link);
showSuccess(t('令牌已重置并已复制到剪贴板')); } else {
} else { showError(message);
showError(message); }
} };
};
const getAffLink = async () => { const getUserData = async () => {
const res = await API.get('/api/user/aff'); let res = await API.get(`/api/user/self`);
const {success, message, data} = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
let link = `${window.location.origin}/register?aff=${data}`; userDispatch({ type: 'login', payload: data });
setAffLink(link); } else {
} else { showError(message);
showError(message); }
} };
};
const getUserData = async () => { const loadModels = async () => {
let res = await API.get(`/api/user/self`); let res = await API.get(`/api/user/models`);
const {success, message, data} = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
userDispatch({type: 'login', payload: data}); if (data != null) {
} else { setModels(data);
showError(message); }
} } else {
}; showError(message);
}
};
const loadModels = async () => { const handleAffLinkClick = async (e) => {
let res = await API.get(`/api/user/models`); e.target.select();
const {success, message, data} = res.data; await copy(e.target.value);
if (success) { showSuccess(t('邀请链接已复制到剪切板'));
if (data != null) { };
setModels(data);
}
} else {
showError(message);
}
};
const handleAffLinkClick = async (e) => { const handleSystemTokenClick = async (e) => {
e.target.select(); e.target.select();
await copy(e.target.value); await copy(e.target.value);
showSuccess(t('邀请链接已复制到剪切板')); showSuccess(t('系统令牌已复制到剪切板'));
}; };
const handleSystemTokenClick = async (e) => { const deleteAccount = async () => {
e.target.select(); if (inputs.self_account_deletion_confirmation !== userState.user.username) {
await copy(e.target.value); showError(t('请输入你的账户名以确认删除!'));
showSuccess(t('系统令牌已复制到剪切板')); return;
}; }
const deleteAccount = async () => { const res = await API.delete('/api/user/self');
if (inputs.self_account_deletion_confirmation !== userState.user.username) { const { success, message } = res.data;
showError(t('请输入你的账户名以确认删除!'));
return;
}
const res = await API.delete('/api/user/self'); if (success) {
const {success, message} = res.data; showSuccess(t('账户已删除!'));
await API.get('/api/user/logout');
userDispatch({ type: 'logout' });
localStorage.removeItem('user');
navigate('/login');
} else {
showError(message);
}
};
if (success) { const bindWeChat = async () => {
showSuccess(t('账户已删除!')); if (inputs.wechat_verification_code === '') return;
await API.get('/api/user/logout'); const res = await API.get(
userDispatch({type: 'logout'}); `/api/oauth/wechat/bind?code=${inputs.wechat_verification_code}`
localStorage.removeItem('user'); );
navigate('/login'); const { success, message } = res.data;
} else { if (success) {
showError(message); showSuccess(t('微信账户绑定成功!'));
} setShowWeChatBindModal(false);
}; } else {
showError(message);
}
};
const bindWeChat = async () => { const changePassword = async () => {
if (inputs.wechat_verification_code === '') return; if (inputs.set_new_password !== inputs.set_new_password_confirmation) {
const res = await API.get( showError(t('两次输入的密码不一致!'));
`/api/oauth/wechat/bind?code=${inputs.wechat_verification_code}`, return;
); }
const {success, message} = res.data; const res = await API.put(`/api/user/self`, {
if (success) { password: inputs.set_new_password
showSuccess(t('微信账户绑定成功!')); });
setShowWeChatBindModal(false); const { success, message } = res.data;
} else { if (success) {
showError(message); showSuccess(t('密码修改成功!'));
} setShowWeChatBindModal(false);
}; } else {
showError(message);
}
setShowChangePasswordModal(false);
};
const changePassword = async () => { const transfer = async () => {
if (inputs.set_new_password !== inputs.set_new_password_confirmation) { if (transferAmount < getQuotaPerUnit()) {
showError(t('两次输入的密码不一致!')); showError(t('划转金额最低为') + ' ' + renderQuota(getQuotaPerUnit()));
return; return;
} }
const res = await API.put(`/api/user/self`, { const res = await API.post(`/api/user/aff_transfer`, {
password: inputs.set_new_password, quota: transferAmount
}); });
const {success, message} = res.data; const { success, message } = res.data;
if (success) { if (success) {
showSuccess(t('密码修改成功!')); showSuccess(message);
setShowWeChatBindModal(false); setOpenTransfer(false);
} else { getUserData().then();
showError(message); } else {
} showError(message);
setShowChangePasswordModal(false); }
}; };
const transfer = async () => { const sendVerificationCode = async () => {
if (transferAmount < getQuotaPerUnit()) { if (inputs.email === '') {
showError(t('划转金额最低为') + ' ' + renderQuota(getQuotaPerUnit())); showError(t('请输入邮箱!'));
return; return;
} }
const res = await API.post(`/api/user/aff_transfer`, { setDisableButton(true);
quota: transferAmount, if (turnstileEnabled && turnstileToken === '') {
}); showInfo('请稍后几秒重试,Turnstile 正在检查用户环境!');
const {success, message} = res.data; return;
if (success) { }
showSuccess(message); setLoading(true);
setOpenTransfer(false); const res = await API.get(
getUserData().then(); `/api/verification?email=${inputs.email}&turnstile=${turnstileToken}`
} else { );
showError(message); const { success, message } = res.data;
} if (success) {
}; showSuccess(t('验证码发送成功,请检查邮箱!'));
} else {
showError(message);
}
setLoading(false);
};
const sendVerificationCode = async () => { const bindEmail = async () => {
if (inputs.email === '') { if (inputs.email_verification_code === '') {
showError(t('请输入邮箱!')); showError(t('请输入邮箱验证码!'));
return; return;
} }
setDisableButton(true); setLoading(true);
if (turnstileEnabled && turnstileToken === '') { const res = await API.get(
showInfo('请稍后几秒重试,Turnstile 正在检查用户环境!'); `/api/oauth/email/bind?email=${inputs.email}&code=${inputs.email_verification_code}`
return; );
} const { success, message } = res.data;
setLoading(true); if (success) {
const res = await API.get( showSuccess(t('邮箱账户绑定成功!'));
`/api/verification?email=${inputs.email}&turnstile=${turnstileToken}`, setShowEmailBindModal(false);
); userState.user.email = inputs.email;
const {success, message} = res.data; } else {
if (success) { showError(message);
showSuccess(t('验证码发送成功,请检查邮箱!')); }
} else { setLoading(false);
showError(message); };
}
setLoading(false);
};
const bindEmail = async () => { const getUsername = () => {
if (inputs.email_verification_code === '') { if (userState.user) {
showError(t('请输入邮箱验证码!')); return userState.user.username;
return; } else {
} return 'null';
setLoading(true); }
const res = await API.get( };
`/api/oauth/email/bind?email=${inputs.email}&code=${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 getUsername = () => { const handleCancel = () => {
if (userState.user) { setOpenTransfer(false);
return userState.user.username; };
} else {
return 'null';
}
};
const handleCancel = () => { const copyText = async (text) => {
setOpenTransfer(false); if (await copy(text)) {
}; showSuccess(t('已复制:') + text);
} else {
// setSearchKeyword(text);
Modal.error({ title: t('无法复制到剪贴板,请手动复制'), content: text });
}
};
const copyText = async (text) => { const handleNotificationSettingChange = (type, value) => {
if (await copy(text)) { setNotificationSettings(prev => ({
showSuccess(t('已复制:') + text); ...prev,
} else { [type]: value.target ? value.target.value : value // 处理 Radio 事件对象
// setSearchKeyword(text); }));
Modal.error({title: t('无法复制到剪贴板,请手动复制'), content: text}); };
}
};
const handleNotificationSettingChange = (type, value) => { const saveNotificationSettings = async () => {
setNotificationSettings(prev => ({ try {
...prev, const res = await API.put('/api/user/setting', {
[type]: value.target ? value.target.value : value // 处理 Radio 事件对象 notify_type: notificationSettings.warningType,
})); quota_warning_threshold: parseFloat(notificationSettings.warningThreshold),
}; webhook_url: notificationSettings.webhookUrl,
webhook_secret: notificationSettings.webhookSecret,
notification_email: notificationSettings.notificationEmail,
accept_unset_model_ratio_model: notificationSettings.acceptUnsetModelRatioModel
});
const saveNotificationSettings = async () => { if (res.data.success) {
try { showSuccess(t('通知设置已更新'));
const res = await API.put('/api/user/setting', { await getUserData();
notify_type: notificationSettings.warningType, } else {
quota_warning_threshold: parseFloat(notificationSettings.warningThreshold), showError(res.data.message);
webhook_url: notificationSettings.webhookUrl, }
webhook_secret: notificationSettings.webhookSecret, } catch (error) {
notification_email: notificationSettings.notificationEmail showError(t('更新通知设置失败'));
}); }
};
if (res.data.success) {
showSuccess(t('通知设置已更新'));
await getUserData();
} else {
showError(res.data.message);
}
} catch (error) {
showError(t('更新通知设置失败'));
}
};
return ( return (
<div> <div>
<Layout> <Layout>
<Layout.Content> <Layout.Content>
<Modal <Modal
title={t('请输入要划转的数量')} title={t('请输入要划转的数量')}
visible={openTransfer} visible={openTransfer}
onOk={transfer} onOk={transfer}
onCancel={handleCancel} onCancel={handleCancel}
maskClosable={false} maskClosable={false}
size={'small'} size={'small'}
centered={true} centered={true}
>
<div style={{ marginTop: 20 }}>
<Typography.Text>{t('可用额度')}{renderQuotaWithPrompt(userState?.user?.aff_quota)}</Typography.Text>
<Input
style={{ marginTop: 5 }}
value={userState?.user?.aff_quota}
disabled={true}
></Input>
</div>
<div style={{ marginTop: 20 }}>
<Typography.Text>
{t('划转额度')}{renderQuotaWithPrompt(transferAmount)} {t('最低') + renderQuota(getQuotaPerUnit())}
</Typography.Text>
<div>
<InputNumber
min={0}
style={{ marginTop: 5 }}
value={transferAmount}
onChange={(value) => setTransferAmount(value)}
disabled={false}
></InputNumber>
</div>
</div>
</Modal>
<div>
<Card
title={
<Card.Meta
avatar={
<Avatar
size="default"
color={stringToColor(getUsername())}
style={{ marginRight: 4 }}
> >
<div style={{marginTop: 20}}> {typeof getUsername() === 'string' &&
<Typography.Text>{t('可用额度')}{renderQuotaWithPrompt(userState?.user?.aff_quota)}</Typography.Text> getUsername().slice(0, 1)}
<Input </Avatar>
style={{marginTop: 5}} }
value={userState?.user?.aff_quota} title={<Typography.Text>{getUsername()}</Typography.Text>}
disabled={true} description={
></Input> isRoot() ? (
</div> <Tag color="red">{t('管理员')}</Tag>
<div style={{marginTop: 20}}> ) : (
<Typography.Text> <Tag color="blue">{t('普通用户')}</Tag>
{t('划转额度')}{renderQuotaWithPrompt(transferAmount)} {t('最低') + renderQuota(getQuotaPerUnit())} )
</Typography.Text> }
<div> ></Card.Meta>
<InputNumber }
min={0} headerExtraContent={
style={{marginTop: 5}} <>
value={transferAmount} <Space vertical align="start">
onChange={(value) => setTransferAmount(value)} <Tag color="green">{'ID: ' + userState?.user?.id}</Tag>
disabled={false} <Tag color="blue">{userState?.user?.group}</Tag>
></InputNumber> </Space>
</div> </>
</div> }
</Modal> footer={
<div> <>
<Card <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
title={ <Typography.Title heading={6}>{t('可用模型')}</Typography.Title>
<Card.Meta </div>
avatar={ <div style={{ marginTop: 10 }}>
<Avatar {models.length <= MODELS_DISPLAY_COUNT ? (
size='default' <Space wrap>
color={stringToColor(getUsername())} {models.map((model) => (
style={{marginRight: 4}} <Tag
> key={model}
{typeof getUsername() === 'string' && color="cyan"
getUsername().slice(0, 1)} onClick={() => {
</Avatar> copyText(model);
} }}
title={<Typography.Text>{getUsername()}</Typography.Text>} >
description={ {model}
isRoot() ? ( </Tag>
<Tag color='red'>{t('管理员')}</Tag> ))}
) : ( </Space>
<Tag color='blue'>{t('普通用户')}</Tag> ) : (
) <>
} <Collapsible isOpen={isModelsExpanded}>
></Card.Meta> <Space wrap>
} {models.map((model) => (
headerExtraContent={ <Tag
<> key={model}
<Space vertical align='start'> color="cyan"
<Tag color='green'>{'ID: ' + userState?.user?.id}</Tag> onClick={() => {
<Tag color='blue'>{userState?.user?.group}</Tag> copyText(model);
</Space> }}
</> >
} {model}
footer={ </Tag>
<> ))}
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}> <Tag
<Typography.Title heading={6}>{t('可用模型')}</Typography.Title> color="blue"
</div> type="light"
<div style={{marginTop: 10}}> style={{ cursor: 'pointer' }}
{models.length <= MODELS_DISPLAY_COUNT ? ( onClick={() => setIsModelsExpanded(false)}
<Space wrap> >
{models.map((model) => ( {t('收起')}
<Tag </Tag>
key={model} </Space>
color='cyan' </Collapsible>
onClick={() => { {!isModelsExpanded && (
copyText(model); <Space wrap>
}} {models.slice(0, MODELS_DISPLAY_COUNT).map((model) => (
> <Tag
{model} key={model}
</Tag> color="cyan"
))} onClick={() => {
</Space> copyText(model);
) : ( }}
<> >
<Collapsible isOpen={isModelsExpanded}> {model}
<Space wrap> </Tag>
{models.map((model) => ( ))}
<Tag <Tag
key={model} color="blue"
color='cyan' type="light"
onClick={() => { style={{ cursor: 'pointer' }}
copyText(model); onClick={() => setIsModelsExpanded(true)}
}} >
> {t('更多')} {models.length - MODELS_DISPLAY_COUNT} {t('个模型')}
{model} </Tag>
</Tag> </Space>
))} )}
<Tag </>
color='blue' )}
type="light" </div>
style={{ cursor: 'pointer' }} </>
onClick={() => setIsModelsExpanded(false)}
>
{t('收起')}
</Tag>
</Space>
</Collapsible>
{!isModelsExpanded && (
<Space wrap>
{models.slice(0, MODELS_DISPLAY_COUNT).map((model) => (
<Tag
key={model}
color='cyan'
onClick={() => {
copyText(model);
}}
>
{model}
</Tag>
))}
<Tag
color='blue'
type="light"
style={{ cursor: 'pointer' }}
onClick={() => setIsModelsExpanded(true)}
>
{t('更多')} {models.length - MODELS_DISPLAY_COUNT} {t('个模型')}
</Tag>
</Space>
)}
</>
)}
</div>
</>
} }
> >
<Descriptions row> <Descriptions row>
<Descriptions.Item itemKey={t('当前余额')}> <Descriptions.Item itemKey={t('当前余额')}>
{renderQuota(userState?.user?.quota)} {renderQuota(userState?.user?.quota)}
</Descriptions.Item> </Descriptions.Item>
<Descriptions.Item itemKey={t('历史消耗')}> <Descriptions.Item itemKey={t('历史消耗')}>
{renderQuota(userState?.user?.used_quota)} {renderQuota(userState?.user?.used_quota)}
</Descriptions.Item> </Descriptions.Item>
<Descriptions.Item itemKey={t('请求次数')}> <Descriptions.Item itemKey={t('请求次数')}>
{userState.user?.request_count} {userState.user?.request_count}
</Descriptions.Item> </Descriptions.Item>
</Descriptions> </Descriptions>
</Card> </Card>
<Card <Card
style={{marginTop: 10}} style={{ marginTop: 10 }}
footer={ footer={
<div> <div>
<Typography.Text>{t('邀请链接')}</Typography.Text> <Typography.Text>{t('邀请链接')}</Typography.Text>
<Input <Input
style={{marginTop: 10}} style={{ marginTop: 10 }}
value={affLink} value={affLink}
onClick={handleAffLinkClick} onClick={handleAffLinkClick}
readOnly readOnly
/> />
</div> </div>
} }
> >
<Typography.Title heading={6}>{t('邀请信息')}</Typography.Title> <Typography.Title heading={6}>{t('邀请信息')}</Typography.Title>
<div style={{marginTop: 10}}> <div style={{ marginTop: 10 }}>
<Descriptions row> <Descriptions row>
<Descriptions.Item itemKey={t('待使用收益')}> <Descriptions.Item itemKey={t('待使用收益')}>
<span style={{color: 'rgba(var(--semi-red-5), 1)'}}> <span style={{ color: 'rgba(var(--semi-red-5), 1)' }}>
{renderQuota(userState?.user?.aff_quota)} {renderQuota(userState?.user?.aff_quota)}
</span> </span>
<Button <Button
type={'secondary'} type={'secondary'}
onClick={() => setOpenTransfer(true)} onClick={() => setOpenTransfer(true)}
size={'small'} size={'small'}
style={{marginLeft: 10}} style={{ marginLeft: 10 }}
> >
{t('划转')} {t('划转')}
</Button> </Button>
</Descriptions.Item> </Descriptions.Item>
<Descriptions.Item itemKey={t('总收益')}> <Descriptions.Item itemKey={t('总收益')}>
{renderQuota(userState?.user?.aff_history_quota)} {renderQuota(userState?.user?.aff_history_quota)}
</Descriptions.Item> </Descriptions.Item>
<Descriptions.Item itemKey={t('邀请人数')}> <Descriptions.Item itemKey={t('邀请人数')}>
{userState?.user?.aff_count} {userState?.user?.aff_count}
</Descriptions.Item> </Descriptions.Item>
</Descriptions> </Descriptions>
</div> </div>
</Card> </Card>
<Card style={{marginTop: 10}}> <Card style={{ marginTop: 10 }}>
<Typography.Title heading={6}>{t('个人信息')}</Typography.Title> <Typography.Title heading={6}>{t('个人信息')}</Typography.Title>
<div style={{marginTop: 20}}> <div style={{ marginTop: 20 }}>
<Typography.Text strong>{t('邮箱')}</Typography.Text> <Typography.Text strong>{t('邮箱')}</Typography.Text>
<div <div
style={{display: 'flex', justifyContent: 'space-between'}} style={{ display: 'flex', justifyContent: 'space-between' }}
> >
<div> <div>
<Input <Input
value={ value={
userState.user && userState.user.email !== '' userState.user && userState.user.email !== ''
? userState.user.email ? userState.user.email
: t('未绑定') : t('未绑定')
} }
readonly={true} readonly={true}
></Input> ></Input>
</div> </div>
<div> <div>
<Button <Button
onClick={() => { onClick={() => {
setShowEmailBindModal(true); setShowEmailBindModal(true);
}} }}
> >
{userState.user && userState.user.email !== '' {userState.user && userState.user.email !== ''
? t('修改绑定') ? t('修改绑定')
: t('绑定邮箱')} : t('绑定邮箱')}
</Button> </Button>
</div> </div>
</div> </div>
</div> </div>
<div style={{marginTop: 10}}> <div style={{ marginTop: 10 }}>
<Typography.Text strong>{t('微信')}</Typography.Text> <Typography.Text strong>{t('微信')}</Typography.Text>
<div style={{display: 'flex', justifyContent: 'space-between'}}> <div style={{ display: 'flex', justifyContent: 'space-between' }}>
<div> <div>
<Input <Input
value={ value={
userState.user && userState.user.wechat_id !== '' userState.user && userState.user.wechat_id !== ''
? t('已绑定') ? t('已绑定')
: t('未绑定') : t('未绑定')
} }
readonly={true} readonly={true}
></Input> ></Input>
</div> </div>
<div> <div>
<Button <Button
disabled={!status.wechat_login} disabled={!status.wechat_login}
onClick={() => { onClick={() => {
setShowWeChatBindModal(true); setShowWeChatBindModal(true);
}} }}
> >
{userState.user && userState.user.wechat_id !== '' {userState.user && userState.user.wechat_id !== ''
? t('修改绑定') ? t('修改绑定')
: status.wechat_login : status.wechat_login
? t('绑定') ? t('绑定')
: t('未启用')} : t('未启用')}
</Button> </Button>
</div> </div>
</div> </div>
</div> </div>
<div style={{marginTop: 10}}> <div style={{ marginTop: 10 }}>
<Typography.Text strong>{t('GitHub')}</Typography.Text> <Typography.Text strong>{t('GitHub')}</Typography.Text>
<div <div
style={{display: 'flex', justifyContent: 'space-between'}} style={{ display: 'flex', justifyContent: 'space-between' }}
> >
<div> <div>
<Input <Input
value={ value={
userState.user && userState.user.github_id !== '' userState.user && userState.user.github_id !== ''
? userState.user.github_id ? userState.user.github_id
: t('未绑定') : t('未绑定')
} }
readonly={true} readonly={true}
></Input> ></Input>
</div> </div>
<div> <div>
<Button <Button
onClick={() => { onClick={() => {
onGitHubOAuthClicked(status.github_client_id); onGitHubOAuthClicked(status.github_client_id);
}} }}
disabled={ disabled={
(userState.user && userState.user.github_id !== '') || (userState.user && userState.user.github_id !== '') ||
!status.github_oauth !status.github_oauth
} }
> >
{status.github_oauth ? t('绑定') : t('未启用')} {status.github_oauth ? t('绑定') : t('未启用')}
</Button> </Button>
</div> </div>
</div> </div>
</div> </div>
<div style={{marginTop: 10}}> <div style={{ marginTop: 10 }}>
<Typography.Text strong>{t('OIDC')}</Typography.Text> <Typography.Text strong>{t('OIDC')}</Typography.Text>
<div <div
style={{display: 'flex', justifyContent: 'space-between'}} style={{ display: 'flex', justifyContent: 'space-between' }}
> >
<div> <div>
<Input <Input
value={ value={
userState.user && userState.user.oidc_id !== '' userState.user && userState.user.oidc_id !== ''
? userState.user.oidc_id ? userState.user.oidc_id
: t('未绑定') : t('未绑定')
} }
readonly={true} readonly={true}
></Input> ></Input>
</div> </div>
<div> <div>
<Button <Button
onClick={() => { onClick={() => {
onOIDCClicked(status.oidc_authorization_endpoint, status.oidc_client_id); onOIDCClicked(status.oidc_authorization_endpoint, status.oidc_client_id);
}} }}
disabled={ disabled={
(userState.user && userState.user.oidc_id !== '') || (userState.user && userState.user.oidc_id !== '') ||
!status.oidc_enabled !status.oidc_enabled
} }
> >
{status.oidc_enabled ? t('绑定') : t('未启用')} {status.oidc_enabled ? t('绑定') : t('未启用')}
</Button> </Button>
</div> </div>
</div> </div>
</div> </div>
<div style={{marginTop: 10}}> <div style={{ marginTop: 10 }}>
<Typography.Text strong>{t('Telegram')}</Typography.Text> <Typography.Text strong>{t('Telegram')}</Typography.Text>
<div <div
style={{display: 'flex', justifyContent: 'space-between'}} style={{ display: 'flex', justifyContent: 'space-between' }}
> >
<div> <div>
<Input <Input
value={ value={
userState.user && userState.user.telegram_id !== '' userState.user && userState.user.telegram_id !== ''
? userState.user.telegram_id ? userState.user.telegram_id
: t('未绑定') : t('未绑定')
} }
readonly={true} readonly={true}
></Input> ></Input>
</div> </div>
<div> <div>
{status.telegram_oauth ? ( {status.telegram_oauth ? (
userState.user.telegram_id !== '' ? ( userState.user.telegram_id !== '' ? (
<Button disabled={true}>{t('已绑定')}</Button> <Button disabled={true}>{t('已绑定')}</Button>
) : ( ) : (
<TelegramLoginButton <TelegramLoginButton
dataAuthUrl='/api/oauth/telegram/bind' dataAuthUrl="/api/oauth/telegram/bind"
botName={status.telegram_bot_name} botName={status.telegram_bot_name}
/> />
) )
) : ( ) : (
<Button disabled={true}>{t('未启用')}</Button> <Button disabled={true}>{t('未启用')}</Button>
)} )}
</div> </div>
</div> </div>
</div> </div>
<div style={{marginTop: 10}}> <div style={{ marginTop: 10 }}>
<Typography.Text strong>{t('LinuxDO')}</Typography.Text> <Typography.Text strong>{t('LinuxDO')}</Typography.Text>
<div <div
style={{display: 'flex', justifyContent: 'space-between'}} style={{ display: 'flex', justifyContent: 'space-between' }}
> >
<div> <div>
<Input <Input
value={ value={
userState.user && userState.user.linux_do_id !== '' userState.user && userState.user.linux_do_id !== ''
? userState.user.linux_do_id ? userState.user.linux_do_id
: t('未绑定') : t('未绑定')
} }
readonly={true} readonly={true}
></Input> ></Input>
</div> </div>
<div> <div>
<Button <Button
onClick={() => { onClick={() => {
onLinuxDOOAuthClicked(status.linuxdo_client_id); onLinuxDOOAuthClicked(status.linuxdo_client_id);
}} }}
disabled={ disabled={
(userState.user && userState.user.linux_do_id !== '') || (userState.user && userState.user.linux_do_id !== '') ||
!status.linuxdo_oauth !status.linuxdo_oauth
} }
> >
{status.linuxdo_oauth ? t('绑定') : t('未启用')} {status.linuxdo_oauth ? t('绑定') : t('未启用')}
</Button> </Button>
</div> </div>
</div> </div>
</div> </div>
<div style={{marginTop: 10}}> <div style={{ marginTop: 10 }}>
<Space> <Space>
<Button onClick={generateAccessToken}> <Button onClick={generateAccessToken}>
{t('生成系统访问令牌')} {t('生成系统访问令牌')}
</Button> </Button>
<Button <Button
onClick={() => { onClick={() => {
setShowChangePasswordModal(true); setShowChangePasswordModal(true);
}} }}
> >
{t('修改密码')} {t('修改密码')}
</Button> </Button>
<Button <Button
type={'danger'} type={'danger'}
onClick={() => { onClick={() => {
setShowAccountDeleteModal(true); setShowAccountDeleteModal(true);
}} }}
> >
{t('删除个人账户')} {t('删除个人账户')}
</Button> </Button>
</Space> </Space>
{systemToken && ( {systemToken && (
<Input <Input
readOnly readOnly
value={systemToken} value={systemToken}
onClick={handleSystemTokenClick} onClick={handleSystemTokenClick}
style={{marginTop: '10px'}} style={{ marginTop: '10px' }}
/> />
)} )}
<Modal <Modal
onCancel={() => setShowWeChatBindModal(false)} onCancel={() => setShowWeChatBindModal(false)}
visible={showWeChatBindModal} visible={showWeChatBindModal}
size={'small'} size={'small'}
> >
<Image src={status.wechat_qrcode}/> <Image src={status.wechat_qrcode} />
<div style={{textAlign: 'center'}}> <div style={{ textAlign: 'center' }}>
<p> <p>
微信扫码关注公众号,输入「验证码」获取验证码(三分钟内有效) 微信扫码关注公众号,输入「验证码」获取验证码(三分钟内有效)
</p> </p>
</div> </div>
<Input <Input
placeholder='验证码' placeholder="验证码"
name='wechat_verification_code' name="wechat_verification_code"
value={inputs.wechat_verification_code} value={inputs.wechat_verification_code}
onChange={(v) => onChange={(v) =>
handleInputChange('wechat_verification_code', v) handleInputChange('wechat_verification_code', v)
} }
/> />
<Button color='' fluid size='large' onClick={bindWeChat}> <Button color="" fluid size="large" onClick={bindWeChat}>
{t('绑定')} {t('绑定')}
</Button> </Button>
</Modal> </Modal>
</div> </div>
</Card> </Card>
<Card style={{marginTop: 10}}> <Card style={{ marginTop: 10 }}>
<Typography.Title heading={6}>{t('通知设置')}</Typography.Title> <Tabs type="line" defaultActiveKey="price">
<div style={{marginTop: 20}}> <TabPane tab={t('价格设置')} itemKey="price">
<Typography.Text strong>{t('通知方式')}</Typography.Text> <div style={{ marginTop: 20 }}>
<div style={{marginTop: 10}}> <Typography.Text strong>{t('接受未设置价格模型')}</Typography.Text>
<RadioGroup <div style={{ marginTop: 10 }}>
value={notificationSettings.warningType} <Checkbox
onChange={value => handleNotificationSettingChange('warningType', value)} checked={notificationSettings.acceptUnsetModelRatioModel}
> onChange={e => handleNotificationSettingChange('acceptUnsetModelRatioModel', e.target.checked)}
<Radio value="email">{t('邮件通知')}</Radio> >
<Radio value="webhook">{t('Webhook通知')}</Radio> {t('接受未设置价格模型')}
</RadioGroup> </Checkbox>
</div> <Typography.Text type="secondary" style={{ marginTop: 8, display: 'block' }}>
{t('当模型没有设置价格时仍接受调用,仅当您信任该网站时使用,可能会产生高额费用')}
</Typography.Text>
</div>
</div>
</TabPane>
<TabPane tab={t('通知设置')} itemKey="notification">
<div style={{ marginTop: 20 }}>
<Typography.Text strong>{t('通知方式')}</Typography.Text>
<div style={{ marginTop: 10 }}>
<RadioGroup
value={notificationSettings.warningType}
onChange={value => handleNotificationSettingChange('warningType', value)}
>
<Radio value="email">{t('邮件通知')}</Radio>
<Radio value="webhook">{t('Webhook通知')}</Radio>
</RadioGroup>
</div>
</div>
{notificationSettings.warningType === 'webhook' && (
<>
<div style={{ marginTop: 20 }}>
<Typography.Text strong>{t('Webhook地址')}</Typography.Text>
<div style={{ marginTop: 10 }}>
<Input
value={notificationSettings.webhookUrl}
onChange={val => handleNotificationSettingChange('webhookUrl', val)}
placeholder={t('请输入Webhook地址,例如: https://example.com/webhook')}
/>
<Typography.Text type="secondary" style={{ marginTop: 8, display: 'block' }}>
{t('只支持https,系统将以 POST 方式发送通知,请确保地址可以接收 POST 请求')}
</Typography.Text>
<Typography.Text type="secondary" style={{ marginTop: 8, display: 'block' }}>
<div style={{ cursor: 'pointer' }} onClick={() => setShowWebhookDocs(!showWebhookDocs)}>
{t('Webhook请求结构')} {showWebhookDocs ? '▼' : '▶'}
</div> </div>
{notificationSettings.warningType === 'webhook' && ( <Collapsible isOpen={showWebhookDocs}>
<> <pre style={{
<div style={{marginTop: 20}}> marginTop: 4,
<Typography.Text strong>{t('Webhook地址')}</Typography.Text> background: 'var(--semi-color-fill-0)',
<div style={{marginTop: 10}}> padding: 8,
<Input borderRadius: 4
value={notificationSettings.webhookUrl} }}>
onChange={val => handleNotificationSettingChange('webhookUrl', val)}
placeholder={t('请输入Webhook地址,例如: https://example.com/webhook')}
/>
<Typography.Text type="secondary" style={{marginTop: 8, display: 'block'}}>
{t('只支持https,系统将以 POST 方式发送通知,请确保地址可以接收 POST 请求')}
</Typography.Text>
<Typography.Text type="secondary" style={{marginTop: 8, display: 'block'}}>
<div style={{cursor: 'pointer'}} onClick={() => setShowWebhookDocs(!showWebhookDocs)}>
{t('Webhook请求结构')} {showWebhookDocs ? '▼' : '▶'}
</div>
<Collapsible isOpen={showWebhookDocs}>
<pre style={{marginTop: 4, background: 'var(--semi-color-fill-0)', padding: 8, borderRadius: 4}}>
{`{ {`{
"type": "quota_exceed", // 通知类型 "type": "quota_exceed", // 通知类型
"title": "标题", // 通知标题 "title": "标题", // 通知标题
...@@ -835,202 +863,205 @@ const PersonalSetting = () => { ...@@ -835,202 +863,205 @@ const PersonalSetting = () => {
"values": ["$0.99"], "values": ["$0.99"],
"timestamp": 1739950503 "timestamp": 1739950503
}`} }`}
</pre> </pre>
</Collapsible> </Collapsible>
</Typography.Text> </Typography.Text>
</div> </div>
</div> </div>
<div style={{marginTop: 20}}> <div style={{ marginTop: 20 }}>
<Typography.Text strong>{t('接口凭证(可选)')}</Typography.Text> <Typography.Text strong>{t('接口凭证(可选)')}</Typography.Text>
<div style={{marginTop: 10}}> <div style={{ marginTop: 10 }}>
<Input <Input
value={notificationSettings.webhookSecret} value={notificationSettings.webhookSecret}
onChange={val => handleNotificationSettingChange('webhookSecret', val)} onChange={val => handleNotificationSettingChange('webhookSecret', val)}
placeholder={t('请输入密钥')} placeholder={t('请输入密钥')}
/> />
<Typography.Text type="secondary" style={{marginTop: 8, display: 'block'}}> <Typography.Text type="secondary" style={{ marginTop: 8, display: 'block' }}>
{t('密钥将以 Bearer 方式添加到请求头中,用于验证webhook请求的合法性')} {t('密钥将以 Bearer 方式添加到请求头中,用于验证webhook请求的合法性')}
</Typography.Text> </Typography.Text>
<Typography.Text type="secondary" style={{marginTop: 4, display: 'block'}}> <Typography.Text type="secondary" style={{ marginTop: 4, display: 'block' }}>
{t('Authorization: Bearer your-secret-key')} {t('Authorization: Bearer your-secret-key')}
</Typography.Text> </Typography.Text>
</div> </div>
</div> </div>
</> </>
)} )}
{notificationSettings.warningType === 'email' && ( {notificationSettings.warningType === 'email' && (
<div style={{marginTop: 20}}> <div style={{ marginTop: 20 }}>
<Typography.Text strong>{t('通知邮箱')}</Typography.Text> <Typography.Text strong>{t('通知邮箱')}</Typography.Text>
<div style={{marginTop: 10}}> <div style={{ marginTop: 10 }}>
<Input <Input
value={notificationSettings.notificationEmail} value={notificationSettings.notificationEmail}
onChange={val => handleNotificationSettingChange('notificationEmail', val)} onChange={val => handleNotificationSettingChange('notificationEmail', val)}
placeholder={t('留空则使用账号绑定的邮箱')} placeholder={t('留空则使用账号绑定的邮箱')}
/> />
<Typography.Text type="secondary" style={{marginTop: 8, display: 'block'}}> <Typography.Text type="secondary" style={{ marginTop: 8, display: 'block' }}>
{t('设置用于接收额度预警的邮箱地址,不填则使用账号绑定的邮箱')} {t('设置用于接收额度预警的邮箱地址,不填则使用账号绑定的邮箱')}
</Typography.Text> </Typography.Text>
</div> </div>
</div>
)}
<div style={{marginTop: 20}}>
<Typography.Text strong>{t('额度预警阈值')} {renderQuotaWithPrompt(notificationSettings.warningThreshold)}</Typography.Text>
<div style={{marginTop: 10}}>
<AutoComplete
value={notificationSettings.warningThreshold}
onChange={val => handleNotificationSettingChange('warningThreshold', val)}
style={{width: 200}}
placeholder={t('请输入预警额度')}
data={[
{ value: 100000, label: '0.2$' },
{ value: 500000, label: '1$' },
{ value: 1000000, label: '5$' },
{ value: 5000000, label: '10$' }
]}
/>
</div>
<Typography.Text type="secondary" style={{marginTop: 10, display: 'block'}}>
{t('当剩余额度低于此数值时,系统将通过选择的方式发送通知')}
</Typography.Text>
</div>
<div style={{marginTop: 20}}>
<Button type="primary" onClick={saveNotificationSettings}>
{t('保存设置')}
</Button>
</div>
</Card>
<Modal
onCancel={() => setShowEmailBindModal(false)}
onOk={bindEmail}
visible={showEmailBindModal}
size={'small'}
centered={true}
maskClosable={false}
>
<Typography.Title heading={6}>{t('绑定邮箱地址')}</Typography.Title>
<div
style={{
marginTop: 20,
display: 'flex',
justifyContent: 'space-between',
}}
>
<Input
fluid
placeholder='输入邮箱地址'
onChange={(value) => handleInputChange('email', value)}
name='email'
type='email'
/>
<Button
onClick={sendVerificationCode}
disabled={disableButton || loading}
>
{disableButton ? `重新发送 (${countdown})` : '获取验证码'}
</Button>
</div>
<div style={{marginTop: 10}}>
<Input
fluid
placeholder='验证码'
name='email_verification_code'
value={inputs.email_verification_code}
onChange={(value) =>
handleInputChange('email_verification_code', value)
}
/>
</div>
{turnstileEnabled ? (
<Turnstile
sitekey={turnstileSiteKey}
onVerify={(token) => {
setTurnstileToken(token);
}}
/>
) : (
<></>
)}
</Modal>
<Modal
onCancel={() => setShowAccountDeleteModal(false)}
visible={showAccountDeleteModal}
size={'small'}
centered={true}
onOk={deleteAccount}
>
<div style={{marginTop: 20}}>
<Banner
type='danger'
description='您正在删除自己的帐户,将清空所有数据且不可恢复'
closeIcon={null}
/>
</div>
<div style={{marginTop: 20}}>
<Input
placeholder={`输入你的账户名 ${userState?.user?.username} 以确认删除`}
name='self_account_deletion_confirmation'
value={inputs.self_account_deletion_confirmation}
onChange={(value) =>
handleInputChange(
'self_account_deletion_confirmation',
value,
)
}
/>
{turnstileEnabled ? (
<Turnstile
sitekey={turnstileSiteKey}
onVerify={(token) => {
setTurnstileToken(token);
}}
/>
) : (
<></>
)}
</div>
</Modal>
<Modal
onCancel={() => setShowChangePasswordModal(false)}
visible={showChangePasswordModal}
size={'small'}
centered={true}
onOk={changePassword}
>
<div style={{marginTop: 20}}>
<Input
name='set_new_password'
placeholder={t('新密码')}
value={inputs.set_new_password}
onChange={(value) =>
handleInputChange('set_new_password', value)
}
/>
<Input
style={{marginTop: 20}}
name='set_new_password_confirmation'
placeholder={t('确认新密码')}
value={inputs.set_new_password_confirmation}
onChange={(value) =>
handleInputChange('set_new_password_confirmation', value)
}
/>
{turnstileEnabled ? (
<Turnstile
sitekey={turnstileSiteKey}
onVerify={(token) => {
setTurnstileToken(token);
}}
/>
) : (
<></>
)}
</div>
</Modal>
</div> </div>
</Layout.Content> )}
</Layout> <div style={{ marginTop: 20 }}>
</div> <Typography.Text
); strong>{t('额度预警阈值')} {renderQuotaWithPrompt(notificationSettings.warningThreshold)}</Typography.Text>
<div style={{ marginTop: 10 }}>
<AutoComplete
value={notificationSettings.warningThreshold}
onChange={val => handleNotificationSettingChange('warningThreshold', val)}
style={{ width: 200 }}
placeholder={t('请输入预警额度')}
data={[
{ value: 100000, label: '0.2$' },
{ value: 500000, label: '1$' },
{ value: 1000000, label: '5$' },
{ value: 5000000, label: '10$' }
]}
/>
</div>
<Typography.Text type="secondary" style={{ marginTop: 10, display: 'block' }}>
{t('当剩余额度低于此数值时,系统将通过选择的方式发送通知')}
</Typography.Text>
</div>
</TabPane>
</Tabs>
<div style={{ marginTop: 20 }}>
<Button type="primary" onClick={saveNotificationSettings}>
{t('保存设置')}
</Button>
</div>
</Card>
<Modal
onCancel={() => setShowEmailBindModal(false)}
onOk={bindEmail}
visible={showEmailBindModal}
size={'small'}
centered={true}
maskClosable={false}
>
<Typography.Title heading={6}>{t('绑定邮箱地址')}</Typography.Title>
<div
style={{
marginTop: 20,
display: 'flex',
justifyContent: 'space-between'
}}
>
<Input
fluid
placeholder="输入邮箱地址"
onChange={(value) => handleInputChange('email', value)}
name="email"
type="email"
/>
<Button
onClick={sendVerificationCode}
disabled={disableButton || loading}
>
{disableButton ? `重新发送 (${countdown})` : '获取验证码'}
</Button>
</div>
<div style={{ marginTop: 10 }}>
<Input
fluid
placeholder="验证码"
name="email_verification_code"
value={inputs.email_verification_code}
onChange={(value) =>
handleInputChange('email_verification_code', value)
}
/>
</div>
{turnstileEnabled ? (
<Turnstile
sitekey={turnstileSiteKey}
onVerify={(token) => {
setTurnstileToken(token);
}}
/>
) : (
<></>
)}
</Modal>
<Modal
onCancel={() => setShowAccountDeleteModal(false)}
visible={showAccountDeleteModal}
size={'small'}
centered={true}
onOk={deleteAccount}
>
<div style={{ marginTop: 20 }}>
<Banner
type="danger"
description="您正在删除自己的帐户,将清空所有数据且不可恢复"
closeIcon={null}
/>
</div>
<div style={{ marginTop: 20 }}>
<Input
placeholder={`输入你的账户名 ${userState?.user?.username} 以确认删除`}
name="self_account_deletion_confirmation"
value={inputs.self_account_deletion_confirmation}
onChange={(value) =>
handleInputChange(
'self_account_deletion_confirmation',
value
)
}
/>
{turnstileEnabled ? (
<Turnstile
sitekey={turnstileSiteKey}
onVerify={(token) => {
setTurnstileToken(token);
}}
/>
) : (
<></>
)}
</div>
</Modal>
<Modal
onCancel={() => setShowChangePasswordModal(false)}
visible={showChangePasswordModal}
size={'small'}
centered={true}
onOk={changePassword}
>
<div style={{ marginTop: 20 }}>
<Input
name="set_new_password"
placeholder={t('新密码')}
value={inputs.set_new_password}
onChange={(value) =>
handleInputChange('set_new_password', value)
}
/>
<Input
style={{ marginTop: 20 }}
name="set_new_password_confirmation"
placeholder={t('确认新密码')}
value={inputs.set_new_password_confirmation}
onChange={(value) =>
handleInputChange('set_new_password_confirmation', value)
}
/>
{turnstileEnabled ? (
<Turnstile
sitekey={turnstileSiteKey}
onVerify={(token) => {
setTurnstileToken(token);
}}
/>
) : (
<></>
)}
</div>
</Modal>
</div>
</Layout.Content>
</Layout>
</div>
);
}; };
export default PersonalSetting; export default PersonalSetting;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment