'use client'; import { appPath } from '@/lib/base-path'; import { useCallback, useEffect, useState, type FormEvent } from 'react'; import Link from 'next/link'; import { ArrowLeft, CheckCircle2, CircleAlert, Eye, EyeOff, KeyRound, LoaderCircle, Plus, RotateCw, Search, ShieldCheck, UserRound, UsersRound, X } from 'lucide-react'; import { Dialog, DialogClose, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog'; import type { AdminUser } from '@/lib/server/auth'; type AccountAction = { kind: 'create' } | { kind: 'reset-password' | 'disable' | 'enable'; user: AdminUser }; async function readResponse(response: Response) { const data = await response.json() as { error?: string; users?: AdminUser[] }; if (!response.ok) throw new Error(data.error || '操作失败,请稍后重试。'); return data; } function AccountDialog({ action, onClose, onSaved }: { action: AccountAction; onClose: () => void; onSaved: (message: string) => void }) { const [busy, setBusy] = useState(false); const [visible, setVisible] = useState(false); const [error, setError] = useState(''); const creating = action.kind === 'create'; const settingPassword = creating || action.kind === 'reset-password'; const title = creating ? '开通账号' : action.kind === 'reset-password' ? '重置密码' : action.kind === 'disable' ? '停用账号' : '启用账号'; async function submit(event: FormEvent) { event.preventDefault(); const fields = new FormData(event.currentTarget); setBusy(true); setError(''); try { const body = action.kind === 'create' ? { username: String(fields.get('username')).trim(), displayName: String(fields.get('displayName')).trim(), password: fields.get('password'), role: fields.get('role') } : { id: action.user.userId, action: action.kind, ...(settingPassword ? { password: fields.get('password') } : {}) }; await readResponse(await fetch(appPath('/api/admin/users'), { method: creating ? 'POST' : 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), })); const name = action.kind === 'create' ? String(fields.get('displayName')).trim() : action.user.displayName; onSaved(action.kind === 'create' ? `已为 ${name} 开通账号,请将账号和临时密码告知本人。` : action.kind === 'reset-password' ? `已重置 ${name} 的密码,下次登录时需要设置新密码。` : `已${action.kind === 'disable' ? '停用' : '启用'} ${name} 的账号。`); } catch (cause) { setError(cause instanceof Error ? cause.message : '无法连接服务,请检查网络后重试。'); setBusy(false); } } return { if (!open && !busy) onClose(); }}> { if (busy) event.preventDefault(); }} onPointerDownOutside={event => { if (busy) event.preventDefault(); }}>
{title}
{creating ? '为指定用户创建账号,首次登录后由用户设置自己的密码。' : action.kind === 'reset-password' ? `为 ${action.user.displayName}(${action.user.username})设置新的临时密码,原有登录将失效。` : action.kind === 'disable' ? `停用后,${action.user.displayName} 将退出登录且无法再次登录。已登记的需求会保留。` : `启用后,${action.user.displayName} 可继续使用原账号和密码登录。`}
{error &&
{error}
}
{creating && <> } {settingPassword && <>
12–128 个字符。请保存并告知用户,关闭后无法查看。 }
; } export function UserManagement({ currentUserId }: { currentUserId: string }) { const [users, setUsers] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(''); const [query, setQuery] = useState(''); const [action, setAction] = useState(null); const [message, setMessage] = useState(''); const load = useCallback((signal?: AbortSignal) => fetch(appPath('/api/admin/users'), { cache: 'no-store', signal }) .then(readResponse) .then(data => { if (!signal?.aborted) { setUsers(data.users || []); setError(''); } }).catch(cause => { if (!signal?.aborted) setError(cause instanceof Error ? cause.message : '无法加载账号,请重试。'); }).finally(() => { if (!signal?.aborted) setLoading(false); }), []); useEffect(() => { const controller = new AbortController(); void load(controller.signal); return () => controller.abort(); }, [load]); const search = query.trim().toLocaleLowerCase(); const matching = users.filter(user => `${user.username} ${user.displayName}`.toLocaleLowerCase().includes(search)); function reload() { setLoading(true); void load(); } function saved(text: string) { setAction(null); setMessage(text); reload(); } return
返回工作台
需有序

账号管理

为指定用户开通访问权限,统一管理账号状态。

仅已开通且处于启用状态的账号可以登录。每位用户只能查看和管理自己登记的需求。

{message &&
{message}
} {error &&
{error}
}

全部账号

{users.length}
{matching.map(user => )}
用户角色状态最近登录操作
{user.displayName}{user.userId === currentUserId && 我}{user.username}
{user.role === 'admin' ? '管理员' : '业务用户'}{user.disabled ? '已停用' : '已启用'}{user.mustChangePassword && !user.disabled && 待设置密码}{user.lastLoginAt ? new Date(user.lastLoginAt).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false }) : '尚未登录'}
{user.userId === currentUserId ? 修改密码 : <>}
{loading && users.length === 0 &&

正在加载账号…

} {!loading && !matching.length &&

{query ? '没有找到匹配的账号' : error ? '账号列表暂不可用' : '暂无账号'}

{query ? '试试其他账号或姓名。' : error ? '请重新加载后再试。' : '点击“开通账号”为指定用户添加访问权限。'}

}
{search ? `找到 ${matching.length} 个账号` : `共 ${users.length} 个账号,${users.filter(user => !user.disabled).length} 个已启用`}停用账号会保留已登记的需求
{action && setAction(null)} onSaved={saved} />}
; }