import { useEffectEvent } from '../../../../hooks/common/useEffectEvent'; import React, { useEffect, useState, useRef } from 'react'; import { useTranslation } from 'react-i18next'; import { API, showError, showSuccess, renderQuota } from '../../../../helpers'; import { useIsMobile } from '../../../../hooks/common/useIsMobile'; import { Button, Modal, SideSheet, Spin, Typography, Card, Form, Avatar, Row, Col, } from '@/components/ui'; import QuotaInput, { FormQuotaInput } from '../../../common/ui/QuotaInput'; import { User as ActionUser, Link as ActionLink, Users as ActionUsers, Plus as ActionPlus, } from '@/components/common/icons/ActionIcons'; import { toGroupList } from '@/helpers/groupList'; const { Text } = Typography; const EditUserModal = (props) => { const { t } = useTranslation(); const userId = props.editingUser.id; const [loading, setLoading] = useState(true); const [loadedUserId, setLoadedUserId] = useState(null); const [submitting, setSubmitting] = useState(false); const pending = useRef(false); const [addQuotaModalOpen, setIsModalOpen] = useState(false); const [addQuotaLocal, setAddQuotaLocal] = useState(''); const isMobile = useIsMobile(); const [groupOptions, setGroupOptions] = useState([]); const [levelOptions, setLevelOptions] = useState([]); const formApiRef = useRef(null); const isEdit = Boolean(userId); const ready = loadedUserId === (userId ?? false); const getInitValues = () => ({ username: '', display_name: '', password: '', github_id: '', oidc_id: '', discord_id: '', wechat_id: '', telegram_id: '', email: '', quota: 0, group: userId ? ['default'] : 'default', level: '', remark: '', }); const fetchGroups = async () => { try { let res = await API.get(`/api/group/`); setGroupOptions(res.data.data.map((g) => ({ label: g, value: g }))); } catch (e) { showError(e.message); } }; const fetchLevels = async () => { try { // 个人等级下拉:选项取 personal 注册表。空选项 = 不受限(存量默认)。 // 走 /api/group/personal_levels(AdminAuth,仅返回 code+名称),普通管理员也能取到选项; // /api/level 仍受 level_policy 权限控制,不在此使用。 // skipErrorHandler:失败时静默降级为仅「不限制」,不弹全局错误。 let res = await API.get(`/api/group/personal_levels`, { skipErrorHandler: true, }); if (res?.data?.success) { const opts = (res.data.data?.levels || []).map((l) => ({ label: l.name ? `${l.name} (${l.code})` : l.code, value: l.code, })); setLevelOptions([{ label: t('不限制(默认)'), value: '' }, ...opts]); } else { setLevelOptions([{ label: t('不限制(默认)'), value: '' }]); } } catch (e) { // 请求失败或未配置:静默降级为仅「不限制」 setLevelOptions([{ label: t('不限制(默认)'), value: '' }]); } }; const handleCancel = () => { if (pending.current) return; setIsModalOpen(false); setAddQuotaLocal(''); props.handleClose(); }; const onScopeChange = useEffectEvent(async (isCurrent) => { setLoading(true); setLoadedUserId(null); const url = userId ? `/api/user/${userId}` : '/api/user/self'; if (userId) { fetchGroups(); fetchLevels(); } try { const { data: response } = await API.get(url); if (!isCurrent()) return; if (response.success) { formApiRef.current?.setValues({ ...getInitValues(), ...response.data, ...(userId && { group: toGroupList(response.data.group ?? 'default'), }), password: '', }); setLoadedUserId(userId ?? false); } else { showError(response.message); } } catch { // The API client reports request failures. } finally { if (isCurrent()) setLoading(false); } }); useEffect(() => { if (!props.visible) return; let current = true; onScopeChange(() => current); return () => { current = false; }; }, [onScopeChange, props.visible, userId]); /* ----------------------- submit ----------------------- */ const submit = async (values) => { if (!ready || pending.current) return; pending.current = true; setSubmitting(true); try { const payload = { ...values }; if (typeof payload.quota === 'string') payload.quota = parseInt(payload.quota) || 0; if (typeof payload.gift_quota === 'string') payload.gift_quota = parseInt(payload.gift_quota) || 0; if (userId) { payload.id = parseInt(userId); payload.group = toGroupList(values.group).join(','); } const url = userId ? '/api/user/' : '/api/user/self'; const { data } = await API.put(url, payload); if (data.success) { showSuccess(t('用户信息更新成功!')); props.refresh(); props.handleClose(); } else { showError(data.message); } } catch { // The API client reports request failures. } finally { pending.current = false; setSubmitting(false); } }; /* --------------------- quota helper -------------------- */ const addLocalQuota = () => { const current = parseInt(formApiRef.current?.getValue('quota') || 0); const delta = parseInt(addQuotaLocal) || 0; formApiRef.current?.setValue('quota', current + delta); }; /* --------------------------- UI --------------------------- */ return ( <> } onCancel={handleCancel} >
(formApiRef.current = api)} onSubmit={submit} > {() => (
{/* 基本信息 */}
{t('基本信息')}
{t('用户的基本账户信息')}
{/* 权限设置 */} {userId && (
{t('权限设置')}
{t('用户分组和额度管理')}
)}
{/* 添加额度模态框 */} { addLocalQuota(); setIsModalOpen(false); }} onCancel={() => setIsModalOpen(false)} closable={null} title={
{t('添加额度')}
} >
{(() => { const current = formApiRef.current?.getValue('quota') || 0; return ( {`${t('新额度:')}${renderQuota(current)} + ${renderQuota(addQuotaLocal || 0)} = ${renderQuota(current + parseInt(addQuotaLocal || 0))}`} ); })()}
); }; export default EditUserModal;