Files

141 lines
12 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'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<HTMLFormElement>) {
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 <Dialog open onOpenChange={open => { if (!open && !busy) onClose(); }}>
<DialogContent className="account-dialog" showCloseButton={false} onEscapeKeyDown={event => { if (busy) event.preventDefault(); }} onPointerDownOutside={event => { if (busy) event.preventDefault(); }}>
<div className="account-dialog-heading"><DialogTitle>{title}</DialogTitle><DialogClose asChild><button type="button" className="account-icon-button" aria-label="关闭" disabled={busy}><X size={20} /></button></DialogClose></div>
<DialogDescription className="account-dialog-description">{creating ? '为指定用户创建账号,首次登录后由用户设置自己的密码。' : action.kind === 'reset-password' ? `为 ${action.user.displayName}(${action.user.username})设置新的临时密码,原有登录将失效。` : action.kind === 'disable' ? `停用后,${action.user.displayName} 将退出登录且无法再次登录。已登记的需求会保留。` : `启用后,${action.user.displayName} 可继续使用原账号和密码登录。`}</DialogDescription>
<form className="account-form" onSubmit={submit} aria-busy={busy}>
{error && <div className="error-banner" role="alert"><CircleAlert size={18} /><span>{error}</span></div>}
<fieldset disabled={busy}>
{creating && <>
<label className="account-field" htmlFor="new-username">登录账号
<input id="new-username" name="username" autoComplete="off" autoCapitalize="none" spellCheck={false} required minLength={3} maxLength={64} pattern="[a-zA-Z0-9][a-zA-Z0-9._@\-]{2,63}" aria-describedby="username-guidance" placeholder="例如 zhangsan" />
<small id="username-guidance">3–64 位,以字母或数字开头,可包含 . _ @ -;不区分大小写。</small>
</label>
<label className="account-field" htmlFor="new-displayName">用户姓名
<input id="new-displayName" name="displayName" autoComplete="off" required maxLength={80} placeholder="例如 张三" />
</label>
<label className="account-field" htmlFor="new-role">账号角色
<select id="new-role" name="role" defaultValue="user"><option value="user">业务用户</option><option value="admin">管理员</option></select>
<small>管理员可以开通、停用账号和重置密码。</small>
</label>
</>}
{settingPassword && <>
<label className="account-field" htmlFor="new-account-password">临时密码</label>
<div className="account-password-input">
<input id="new-account-password" name="password" type={visible ? 'text' : 'password'} autoComplete="new-password" required minLength={12} maxLength={128} aria-describedby="temporary-password-guidance" />
<button type="button" onClick={() => setVisible(!visible)} aria-label={visible ? '隐藏临时密码' : '显示临时密码'} aria-pressed={visible}>{visible ? <EyeOff size={19} /> : <Eye size={19} />}</button>
</div>
<small className="account-field-hint" id="temporary-password-guidance">12–128 个字符。请保存并告知用户,关闭后无法查看。</small>
</>}
<div className="account-dialog-actions"><button type="button" className="btn" onClick={onClose}>取消</button><button className={`btn ${action.kind === 'disable' ? 'danger-button' : 'primary'}`} type="submit">{busy ? <><LoaderCircle className="account-spinner" size={17} />正在保存…</> : title}</button></div>
</fieldset>
</form>
</DialogContent>
</Dialog>;
}
export function UserManagement({ currentUserId }: { currentUserId: string }) {
const [users, setUsers] = useState<AdminUser[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [query, setQuery] = useState('');
const [action, setAction] = useState<AccountAction | null>(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 <div className="account-admin-page">
<header className="account-admin-header"><Link className="account-back-link" href="/"><ArrowLeft size={18} />返回工作台</Link><div className="account-admin-brand"><div className="brand-mark" aria-hidden="true"><i /><i /><i /><i /></div><strong>需有序</strong></div></header>
<main className="account-admin-main">
<div className="page-heading"><div><h1>账号管理</h1><p>为指定用户开通访问权限,统一管理账号状态。</p></div><button className="btn primary" onClick={() => { setMessage(''); setAction({ kind: 'create' }); }}><Plus size={18} />开通账号</button></div>
<div className="info-banner account-admin-note"><ShieldCheck size={19} /><p>仅已开通且处于启用状态的账号可以登录。每位用户只能查看和管理自己登记的需求。</p></div>
{message && <div className="account-success" role="status"><CheckCircle2 size={18} /><span>{message}</span><button className="account-icon-button" aria-label="关闭操作提示" onClick={() => setMessage('')}><X size={18} /></button></div>}
{error && <div className="error-banner" role="alert"><CircleAlert size={18} /><span>{error}</span><button className="text-button" onClick={reload} disabled={loading}>重新加载</button></div>}
<section className="panel account-users-panel" aria-labelledby="users-list-heading" aria-busy={loading}>
<div className="account-users-toolbar"><div className="account-users-title"><UsersRound size={19} /><h2 id="users-list-heading">全部账号</h2><span>{users.length}</span></div><div className="account-users-tools"><label className="search-field"><Search size={17} /><input type="search" value={query} onChange={event => setQuery(event.target.value)} placeholder="搜索账号或姓名" aria-label="搜索账号或姓名" /></label><button className="account-icon-button" onClick={reload} disabled={loading} aria-label="刷新账号列表"><RotateCw size={18} className={loading ? 'account-spinner' : ''} /></button></div></div>
<div className="account-users-table-wrap"><table className="account-users-table"><thead><tr><th scope="col">用户</th><th scope="col">角色</th><th scope="col">状态</th><th scope="col">最近登录</th><th scope="col">操作</th></tr></thead><tbody>
{matching.map(user => <tr key={user.userId}><td><div className="account-user-identity"><span className="avatar"><UserRound size={19} /></span><div><strong>{user.displayName}{user.userId === currentUserId && <span className="account-self">我</span>}</strong><span>{user.username}</span></div></div></td><td><span className={user.role === 'admin' ? 'account-role-admin' : ''}>{user.role === 'admin' ? '管理员' : '业务用户'}</span></td><td><span className={`status ${user.disabled ? 'gray' : 'green'}`}>{user.disabled ? '已停用' : '已启用'}</span>{user.mustChangePassword && !user.disabled && <small className="account-password-pending">待设置密码</small>}</td><td className="account-login-date">{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 }) : '尚未登录'}</td><td><div className="account-row-actions">{user.userId === currentUserId ? <a className="text-button" href={appPath('/account/password')}><KeyRound size={15} />修改密码</a> : <><button className="text-button" onClick={() => setAction({ kind: 'reset-password', user })}>重置密码</button><button className={`text-button ${user.disabled ? '' : 'danger-text'}`} onClick={() => setAction({ kind: user.disabled ? 'enable' : 'disable', user })}>{user.disabled ? '启用' : '停用'}</button></>}</div></td></tr>)}
</tbody></table></div>
{loading && users.length === 0 && <div className="account-list-empty" role="status"><LoaderCircle className="account-spinner" size={24} /><p>正在加载账号…</p></div>}
{!loading && !matching.length && <div className="account-list-empty"><UsersRound size={28} /><h3>{query ? '没有找到匹配的账号' : error ? '账号列表暂不可用' : '暂无账号'}</h3><p>{query ? '试试其他账号或姓名。' : error ? '请重新加载后再试。' : '点击“开通账号”为指定用户添加访问权限。'}</p></div>}
<div className="account-users-footer">{search ? `找到 ${matching.length} 个账号` : `共 ${users.length} 个账号,${users.filter(user => !user.disabled).length} 个已启用`}<span>停用账号会保留已登记的需求</span></div>
</section>
</main>
{action && <AccountDialog action={action} onClose={() => setAction(null)} onSaved={saved} />}
</div>;
}