/* 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 . For commercial licensing, please contact support@quantumnous.com */ import React, { useContext, useEffect, useState, useRef, useMemo } from 'react'; import { StatusContext } from '../../../context/Status'; import { Banner, Button, Col, Form, Row, Spin, Modal, Select, InputGroup, Input, } from '@/components/ui'; import { API, isRoot, showError, showSuccess, showWarning, } from '../../../helpers'; import { useTranslation } from 'react-i18next'; const API_MAPPING = { DocsLink: 'general_setting.docs_link', QuotaDisplayType: 'general_setting.quota_display_type', CustomCurrencySymbol: 'general_setting.custom_currency_symbol', CustomCurrencyExchangeRate: 'general_setting.custom_currency_exchange_rate', }; const DEFAULT_INPUTS = { TopUpLink: '', DocsLink: '', QuotaDisplayType: 'USD', CustomCurrencySymbol: '¤', CustomCurrencyExchangeRate: '', QuotaPerUnit: '', RetryTimes: '', USDExchangeRate: '', DisplayTokenStatEnabled: false, DefaultCollapseSidebar: false, DemoSiteEnabled: false, SelfUseModeEnabled: false, LanguageSwitchEnabled: true, CommissionEnabled: true, CosEnabled: false, CosSecretId: '', CosSecretKey: '', CosBucket: '', CosRegion: '', CosBaseUrl: '', CosPrivate: true, CosPresignExpireSeconds: 86400, GlobalPromptArchiveEnabled: false, }; export default function GeneralSettings(props) { const { t } = useTranslation(); const [loading, setLoading] = useState(false); const [showQuotaWarning, setShowQuotaWarning] = useState(false); const [testingCos, setTestingCos] = useState(false); const [statusState, statusDispatch] = useContext(StatusContext); const [inputs, setInputs] = useState(DEFAULT_INPUTS); const refForm = useRef(); const [inputsRow, setInputsRow] = useState(inputs); function handleFieldChange(fieldName) { return (value) => { setInputs((inputs) => ({ ...inputs, [fieldName]: value })); }; } function onSubmit() { // 直接从Form API获取所有表单值,这是最可靠的方式 const formValues = refForm.current?.getValues?.(); if (!formValues) { showError(t('获取表单数据失败')); return; } // 合并表单值和inputs状态中的非表单字段。 // 注意:额度展示类型(QuotaDisplayType)与自定义汇率走的是裸 Select/Input // (非 Form 字段),不会出现在 getValues() 里——漏合并会导致“改了保存不上、 // 刷新后弹回原值”的静默丢失。 const mergedValues = { ...formValues, USDExchangeRate: inputs.USDExchangeRate, QuotaPerUnit: inputs.QuotaPerUnit, QuotaDisplayType: inputs.QuotaDisplayType, CustomCurrencyExchangeRate: inputs.CustomCurrencyExchangeRate, }; // 构建需要更新的数据 const updateArray = []; for (const key in mergedValues) { if (mergedValues.hasOwnProperty(key) && inputsRow.hasOwnProperty(key)) { const currentValue = mergedValues[key]; const originalValue = inputsRow[key]; // 与后端脱敏规则对齐(controller/option.go 按后缀 Token/Secret/Key 判定): // 用 includes 会误伤 CosSecretId(明文回读、非脱敏字段),导致每次保存 // 都把它当“用户新填的敏感值”重复提交。 const isSensitiveField = key.endsWith('Token') || key.endsWith('Secret') || key.endsWith('Key'); // 如果值发生了变化,或者是敏感字段且用户填写了值,则添加到更新列表 if ( currentValue !== originalValue || (isSensitiveField && currentValue !== '') ) { // 如果是映射字段,使用后端Key const apiKey = API_MAPPING[key] || key; updateArray.push({ key: apiKey, oldValue: originalValue, newValue: currentValue, }); } } } if (!updateArray.length) { showWarning(t('你似乎并没有修改什么')); return; } // 构建API请求 const requestQueue = updateArray.map((item) => { let value = ''; if (typeof item.newValue === 'boolean') { value = String(item.newValue); } else { value = item.newValue; } // 调试输出 console.log(`提交字段: ${item.key}, 值: ${value}`); return API.put('/api/option/', { key: item.key, value, }); }); setLoading(true); Promise.all(requestQueue) .then((res) => { if (requestQueue.length === 1) { if (res.includes(undefined)) return; } else if (requestQueue.length > 1) { if (res.includes(undefined)) return showError(t('部分保存失败,请重试')); } showSuccess(t('保存成功')); // 分佣总开关决定侧栏/顶栏的分佣入口,保存成功后同步到全局 status, // 否则要整页刷新菜单才会跟着变。 const commissionIndex = updateArray.findIndex( (item) => item.key === 'CommissionEnabled', ); if ( commissionIndex >= 0 && res[commissionIndex]?.data?.success && statusState?.status ) { statusDispatch({ type: 'set', payload: { ...statusState.status, commission_enabled: updateArray[commissionIndex].newValue, }, }); } // 刷新数据 props.refresh(); }) .catch(() => { showError(t('保存失败,请重试')); }) .finally(() => { setLoading(false); }); } async function testCosConnection() { setTestingCos(true); try { const res = await API.post('/api/option/test_cos'); if (res.data.success) { showSuccess(res.data.message || t('COS连接测试成功')); } else { showError(res.data.message || t('COS连接测试失败')); } } catch (error) { showError( t('COS连接测试失败: {{value}}', { value: error.message || t('未知错误'), }), ); } finally { setTestingCos(false); } } // 计算展示在输入框中的“1 USD = X ”中的 X const combinedRate = useMemo(() => { const type = inputs.QuotaDisplayType; if (type === 'USD') return '1'; if (type === 'CNY') return String(inputs['USDExchangeRate'] || ''); if (type === 'TOKENS') return String(inputs['QuotaPerUnit'] || ''); if (type === 'CUSTOM') return String(inputs.CustomCurrencyExchangeRate || ''); return ''; }, [inputs]); const onCombinedRateChange = (val) => { const type = inputs.QuotaDisplayType; if (type === 'CNY') { handleFieldChange('USDExchangeRate')(val); } else if (type === 'TOKENS') { handleFieldChange('QuotaPerUnit')(val); } else if (type === 'CUSTOM') { handleFieldChange('CustomCurrencyExchangeRate')(val); } }; useEffect(() => { // 初始化所有inputs中定义的字段,确保不会丢失任何字段 const currentInputs = { ...DEFAULT_INPUTS }; // 反向映射:从API Key映射到前端Key const reverseMap = {}; Object.keys(API_MAPPING).forEach((frontendKey) => { reverseMap[API_MAPPING[frontendKey]] = frontendKey; }); // 然后用props.options中的值覆盖,处理敏感字段 for (let key in props.options) { // 检查是否是直接匹配的Key if (Object.keys(currentInputs).includes(key)) { let value = props.options[key]; // 将敏感字段的掩码值转换为空字符串,方便用户输入 if (value === '***ALREADY_SET***') { value = ''; } // 布尔字段后端存字符串 'true'/'false',需转回布尔: // 否则字符串 'false' 为真值会让 Switch 恒显示开启(与实际保存状态不符) if (typeof currentInputs[key] === 'boolean') { value = value === true || value === 'true'; } currentInputs[key] = value; } // 检查是否是需要映射的Key else if ( reverseMap[key] && Object.keys(currentInputs).includes(reverseMap[key]) ) { let value = props.options[key]; if (value === '***ALREADY_SET***') { value = ''; } currentInputs[reverseMap[key]] = value; } } // 若旧字段存在且新字段缺失,则做一次兜底映射 if ( props.options['general_setting.quota_display_type'] === undefined && props.options?.DisplayInCurrencyEnabled !== undefined ) { currentInputs.QuotaDisplayType = props.options.DisplayInCurrencyEnabled ? 'USD' : 'TOKENS'; } // 回填自定义货币相关字段(如果后端已存在)- 这些已经在上面的循环中通过映射处理了,但为了保险起见(如果后端key不在props.options遍历中?) // props.options 遍历应该覆盖了所有后端返回的key。所以不需要额外的逻辑,只要映射表正确。 setInputs(currentInputs); setInputsRow(structuredClone(currentInputs)); refForm.current.setValues(currentInputs); }, [props.options]); return ( <>
(refForm.current = formAPI)} style={{ marginBottom: 15 }} > {/* 单位美元额度已合入汇率组合控件(TOKENS 模式下编辑),不再单独展示 */} {/* 分佣总开关仅超级管理员可改(后端未登记到下放清单,默认 root-only) */} {isRoot() && ( )}

{t( '配置腾讯云COS后,生成的图片将自动上传到对象存储,方便用户访问和管理。请确保填写正确的配置信息。', )}

{t('私有访问模式说明:')}

  • {t( '开启私有访问: 图片URL会包含临时签名,可保护图片安全,但URL会在指定时间后过期', )}
  • {t( '关闭私有访问: 图片URL永久有效,但需要将COS Bucket权限设置为"公有读私有写"', )}
  • {t( '推荐设置: 开启私有访问 + 过期时间设为24小时(86400秒)以上', )}
} bordered fullMode={false} closeIcon={null} />

{t( '实验性功能:开启后平台将异步记录所有用户对话中的「用户输入提示词」及其调用统计(接口调用次数、总花费)至平台数据库 prompt_traces 表,仅用于 token 运营与模型训练数据研究,不是用户数据备份/存档功能。', )}

{t( '与企业自有库采集相互独立、互不影响(企业开关开启时其数据同时写入企业自己配置的数据库)。开启前请确认符合隐私合规要求。', )}

} bordered fullMode={false} closeIcon={null} />
setShowQuotaWarning(false)} onCancel={() => setShowQuotaWarning(false)} closeOnEsc={true} width={500} > ); }