SettingsSidebarModulesUser.jsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. /*
  2. Copyright (C) 2025 QuantumNous
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <https://www.gnu.org/licenses/>.
  13. For commercial licensing, please contact support@quantumnous.com
  14. */
  15. import { useState, useEffect, useContext } from 'react';
  16. import { useTranslation } from 'react-i18next';
  17. import { Card, Button, Switch, Typography, Row, Col, Avatar } from '@douyinfe/semi-ui';
  18. import { API, showSuccess, showError } from '../../../helpers';
  19. import { StatusContext } from '../../../context/Status';
  20. import { UserContext } from '../../../context/User';
  21. import { useUserPermissions } from '../../../hooks/common/useUserPermissions';
  22. import { useSidebar } from '../../../hooks/common/useSidebar';
  23. import { Settings } from 'lucide-react';
  24. const { Text } = Typography;
  25. export default function SettingsSidebarModulesUser() {
  26. const { t } = useTranslation();
  27. const [loading, setLoading] = useState(false);
  28. const [statusState] = useContext(StatusContext);
  29. // 使用后端权限验证替代前端角色判断
  30. const {
  31. permissions,
  32. loading: permissionsLoading,
  33. hasSidebarSettingsPermission,
  34. isSidebarSectionAllowed,
  35. isSidebarModuleAllowed,
  36. } = useUserPermissions();
  37. // 使用useSidebar钩子获取刷新方法
  38. const { refreshUserConfig } = useSidebar();
  39. // 如果没有边栏设置权限,不显示此组件
  40. if (!permissionsLoading && !hasSidebarSettingsPermission()) {
  41. return null;
  42. }
  43. // 权限加载中,显示加载状态
  44. if (permissionsLoading) {
  45. return null;
  46. }
  47. // 根据用户权限生成默认配置
  48. const generateDefaultConfig = () => {
  49. const defaultConfig = {};
  50. // 聊天区域 - 所有用户都可以访问
  51. if (isSidebarSectionAllowed('chat')) {
  52. defaultConfig.chat = {
  53. enabled: true,
  54. playground: isSidebarModuleAllowed('chat', 'playground'),
  55. chat: isSidebarModuleAllowed('chat', 'chat')
  56. };
  57. }
  58. // 控制台区域 - 所有用户都可以访问
  59. if (isSidebarSectionAllowed('console')) {
  60. defaultConfig.console = {
  61. enabled: true,
  62. detail: isSidebarModuleAllowed('console', 'detail'),
  63. token: isSidebarModuleAllowed('console', 'token'),
  64. log: isSidebarModuleAllowed('console', 'log'),
  65. midjourney: isSidebarModuleAllowed('console', 'midjourney'),
  66. task: isSidebarModuleAllowed('console', 'task')
  67. };
  68. }
  69. // 个人中心区域 - 所有用户都可以访问
  70. if (isSidebarSectionAllowed('personal')) {
  71. defaultConfig.personal = {
  72. enabled: true,
  73. topup: isSidebarModuleAllowed('personal', 'topup'),
  74. personal: isSidebarModuleAllowed('personal', 'personal')
  75. };
  76. }
  77. // 管理员区域 - 只有管理员可以访问
  78. if (isSidebarSectionAllowed('admin')) {
  79. defaultConfig.admin = {
  80. enabled: true,
  81. channel: isSidebarModuleAllowed('admin', 'channel'),
  82. models: isSidebarModuleAllowed('admin', 'models'),
  83. redemption: isSidebarModuleAllowed('admin', 'redemption'),
  84. user: isSidebarModuleAllowed('admin', 'user'),
  85. setting: isSidebarModuleAllowed('admin', 'setting')
  86. };
  87. }
  88. return defaultConfig;
  89. };
  90. // 用户个人左侧边栏模块设置
  91. const [sidebarModulesUser, setSidebarModulesUser] = useState({});
  92. // 管理员全局配置
  93. const [adminConfig, setAdminConfig] = useState(null);
  94. // 处理区域级别开关变更
  95. function handleSectionChange(sectionKey) {
  96. return (checked) => {
  97. const newModules = {
  98. ...sidebarModulesUser,
  99. [sectionKey]: {
  100. ...sidebarModulesUser[sectionKey],
  101. enabled: checked
  102. }
  103. };
  104. setSidebarModulesUser(newModules);
  105. console.log('用户边栏区域配置变更:', sectionKey, checked, newModules);
  106. };
  107. }
  108. // 处理功能级别开关变更
  109. function handleModuleChange(sectionKey, moduleKey) {
  110. return (checked) => {
  111. const newModules = {
  112. ...sidebarModulesUser,
  113. [sectionKey]: {
  114. ...sidebarModulesUser[sectionKey],
  115. [moduleKey]: checked
  116. }
  117. };
  118. setSidebarModulesUser(newModules);
  119. console.log('用户边栏功能配置变更:', sectionKey, moduleKey, checked, newModules);
  120. };
  121. }
  122. // 重置为默认配置(基于权限过滤)
  123. function resetSidebarModules() {
  124. const defaultConfig = generateDefaultConfig();
  125. setSidebarModulesUser(defaultConfig);
  126. showSuccess(t('已重置为默认配置'));
  127. console.log('用户边栏配置重置为默认:', defaultConfig);
  128. }
  129. // 保存配置
  130. async function onSubmit() {
  131. setLoading(true);
  132. try {
  133. console.log('保存用户边栏配置:', sidebarModulesUser);
  134. const res = await API.put('/api/user/self', {
  135. sidebar_modules: JSON.stringify(sidebarModulesUser),
  136. });
  137. const { success, message } = res.data;
  138. if (success) {
  139. showSuccess(t('保存成功'));
  140. console.log('用户边栏配置保存成功');
  141. // 刷新useSidebar钩子中的用户配置,实现实时更新
  142. await refreshUserConfig();
  143. console.log('用户边栏配置已刷新,边栏将立即更新');
  144. } else {
  145. showError(message);
  146. console.error('用户边栏配置保存失败:', message);
  147. }
  148. } catch (error) {
  149. showError(t('保存失败,请重试'));
  150. console.error('用户边栏配置保存异常:', error);
  151. } finally {
  152. setLoading(false);
  153. }
  154. }
  155. // 统一的配置加载逻辑
  156. useEffect(() => {
  157. const loadConfigs = async () => {
  158. try {
  159. // 获取管理员全局配置
  160. if (statusState?.status?.SidebarModulesAdmin) {
  161. const adminConf = JSON.parse(statusState.status.SidebarModulesAdmin);
  162. setAdminConfig(adminConf);
  163. console.log('加载管理员边栏配置:', adminConf);
  164. }
  165. // 获取用户个人配置
  166. const userRes = await API.get('/api/user/self');
  167. if (userRes.data.success && userRes.data.data.sidebar_modules) {
  168. let userConf;
  169. // 检查sidebar_modules是字符串还是对象
  170. if (typeof userRes.data.data.sidebar_modules === 'string') {
  171. userConf = JSON.parse(userRes.data.data.sidebar_modules);
  172. } else {
  173. userConf = userRes.data.data.sidebar_modules;
  174. }
  175. console.log('从API加载的用户配置:', userConf);
  176. // 确保用户配置也经过权限过滤
  177. const filteredUserConf = {};
  178. Object.keys(userConf).forEach(sectionKey => {
  179. if (isSidebarSectionAllowed(sectionKey)) {
  180. filteredUserConf[sectionKey] = { ...userConf[sectionKey] };
  181. // 过滤不允许的模块
  182. Object.keys(userConf[sectionKey]).forEach(moduleKey => {
  183. if (moduleKey !== 'enabled' && !isSidebarModuleAllowed(sectionKey, moduleKey)) {
  184. delete filteredUserConf[sectionKey][moduleKey];
  185. }
  186. });
  187. }
  188. });
  189. setSidebarModulesUser(filteredUserConf);
  190. console.log('权限过滤后的用户配置:', filteredUserConf);
  191. } else {
  192. // 如果用户没有配置,使用权限过滤后的默认配置
  193. const defaultConfig = generateDefaultConfig();
  194. setSidebarModulesUser(defaultConfig);
  195. console.log('用户无配置,使用默认配置:', defaultConfig);
  196. }
  197. } catch (error) {
  198. console.error('加载边栏配置失败:', error);
  199. // 出错时也使用默认配置
  200. const defaultConfig = generateDefaultConfig();
  201. setSidebarModulesUser(defaultConfig);
  202. }
  203. };
  204. // 只有权限加载完成且有边栏设置权限时才加载配置
  205. if (!permissionsLoading && hasSidebarSettingsPermission()) {
  206. loadConfigs();
  207. }
  208. }, [statusState, permissionsLoading, hasSidebarSettingsPermission, isSidebarSectionAllowed, isSidebarModuleAllowed]);
  209. // 检查功能是否被管理员允许
  210. const isAllowedByAdmin = (sectionKey, moduleKey = null) => {
  211. if (!adminConfig) return true;
  212. if (moduleKey) {
  213. return adminConfig[sectionKey]?.enabled && adminConfig[sectionKey]?.[moduleKey];
  214. } else {
  215. return adminConfig[sectionKey]?.enabled;
  216. }
  217. };
  218. // 区域配置数据(根据后端权限过滤)
  219. const sectionConfigs = [
  220. {
  221. key: 'chat',
  222. title: t('聊天区域'),
  223. description: t('操练场和聊天功能'),
  224. modules: [
  225. { key: 'playground', title: t('操练场'), description: t('AI模型测试环境') },
  226. { key: 'chat', title: t('聊天'), description: t('聊天会话管理') }
  227. ]
  228. },
  229. {
  230. key: 'console',
  231. title: t('控制台区域'),
  232. description: t('数据管理和日志查看'),
  233. modules: [
  234. { key: 'detail', title: t('数据看板'), description: t('系统数据统计') },
  235. { key: 'token', title: t('令牌管理'), description: t('API令牌管理') },
  236. { key: 'log', title: t('使用日志'), description: t('API使用记录') },
  237. { key: 'midjourney', title: t('绘图日志'), description: t('绘图任务记录') },
  238. { key: 'task', title: t('任务日志'), description: t('系统任务记录') }
  239. ]
  240. },
  241. {
  242. key: 'personal',
  243. title: t('个人中心区域'),
  244. description: t('用户个人功能'),
  245. modules: [
  246. { key: 'topup', title: t('钱包管理'), description: t('余额充值管理') },
  247. { key: 'personal', title: t('个人设置'), description: t('个人信息设置') }
  248. ]
  249. },
  250. {
  251. key: 'admin',
  252. title: t('管理员区域'),
  253. description: t('系统管理功能'),
  254. modules: [
  255. { key: 'channel', title: t('渠道管理'), description: t('API渠道配置') },
  256. { key: 'models', title: t('模型管理'), description: t('AI模型配置') },
  257. { key: 'redemption', title: t('兑换码管理'), description: t('兑换码生成管理') },
  258. { key: 'user', title: t('用户管理'), description: t('用户账户管理') },
  259. { key: 'setting', title: t('系统设置'), description: t('系统参数配置') }
  260. ]
  261. }
  262. ].filter(section => {
  263. // 使用后端权限验证替代前端角色判断
  264. return isSidebarSectionAllowed(section.key);
  265. }).map(section => ({
  266. ...section,
  267. modules: section.modules.filter(module =>
  268. isSidebarModuleAllowed(section.key, module.key)
  269. )
  270. })).filter(section =>
  271. // 过滤掉没有可用模块的区域
  272. section.modules.length > 0 && isAllowedByAdmin(section.key)
  273. );
  274. return (
  275. <Card className='!rounded-2xl shadow-sm border-0'>
  276. {/* 卡片头部 */}
  277. <div className='flex items-center mb-4'>
  278. <Avatar size='small' color='purple' className='mr-3 shadow-md'>
  279. <Settings size={16} />
  280. </Avatar>
  281. <div>
  282. <Typography.Text className='text-lg font-medium'>
  283. {t('左侧边栏个人设置')}
  284. </Typography.Text>
  285. <div className='text-xs text-gray-600'>
  286. {t('个性化设置左侧边栏的显示内容')}
  287. </div>
  288. </div>
  289. </div>
  290. <div className='mb-4'>
  291. <Text type="secondary" className='text-sm text-gray-600'>
  292. {t('您可以个性化设置侧边栏的要显示功能')}
  293. </Text>
  294. </div>
  295. {sectionConfigs.map((section) => (
  296. <div key={section.key} className='mb-6'>
  297. {/* 区域标题和总开关 */}
  298. <div className='flex justify-between items-center mb-4 p-4 bg-gray-50 rounded-xl border border-gray-200'>
  299. <div>
  300. <div className='font-semibold text-base text-gray-900 mb-1'>
  301. {section.title}
  302. </div>
  303. <Text className='text-xs text-gray-600'>
  304. {section.description}
  305. </Text>
  306. </div>
  307. <Switch
  308. checked={sidebarModulesUser[section.key]?.enabled}
  309. onChange={handleSectionChange(section.key)}
  310. size="default"
  311. />
  312. </div>
  313. {/* 功能模块网格 */}
  314. <Row gutter={[12, 12]}>
  315. {section.modules.map((module) => (
  316. <Col key={module.key} xs={24} sm={12} md={8} lg={6} xl={6}>
  317. <Card
  318. className={`!rounded-xl border border-gray-200 hover:border-blue-300 transition-all duration-200 ${
  319. sidebarModulesUser[section.key]?.enabled ? '' : 'opacity-50'
  320. }`}
  321. bodyStyle={{ padding: '16px' }}
  322. hoverable
  323. >
  324. <div className='flex justify-between items-center h-full'>
  325. <div className='flex-1 text-left'>
  326. <div className='font-semibold text-sm text-gray-900 mb-1'>
  327. {module.title}
  328. </div>
  329. <Text className='text-xs text-gray-600 leading-relaxed block'>
  330. {module.description}
  331. </Text>
  332. </div>
  333. <div className='ml-4'>
  334. <Switch
  335. checked={sidebarModulesUser[section.key]?.[module.key]}
  336. onChange={handleModuleChange(section.key, module.key)}
  337. size="default"
  338. disabled={!sidebarModulesUser[section.key]?.enabled}
  339. />
  340. </div>
  341. </div>
  342. </Card>
  343. </Col>
  344. ))}
  345. </Row>
  346. </div>
  347. ))}
  348. {/* 底部按钮 */}
  349. <div className='flex justify-end gap-3 mt-6 pt-4 border-t border-gray-200'>
  350. <Button
  351. type='tertiary'
  352. onClick={resetSidebarModules}
  353. className='!rounded-lg'
  354. >
  355. {t('重置为默认')}
  356. </Button>
  357. <Button
  358. type='primary'
  359. onClick={onSubmit}
  360. loading={loading}
  361. className='!rounded-lg'
  362. >
  363. {t('保存设置')}
  364. </Button>
  365. </div>
  366. </Card>
  367. );
  368. }