将 admin 8 文件 ~50 处 raw red/green/yellow/amber/blue 类替换为语义 token (error/success/warning/info),使其错误/成功/警告框在暗黑模式正确反色。 - tailwind.config.js: error 补 text 子键(原缺,text-error 暗黑底仅 3.3:1 不达 AA) - globals.css: 新增 --color-error-text;html[data-theme='dark'] 补四语义色的 *-bg(深色底)与 *-text(浅色,暗底达 AA)覆盖,原暗黑块完全漏掉这些变量 - 映射纪律:语义框 bg-<c>-bg border border-border-secondary text-<c>-text; 危险按钮 bg-error/bg-success hover:bg-*-hover text-white;字段校验 border-error 验证:type-check 0 errors;lint 0 errors;单测 1624 passed;视觉回归 22 passed; Playwright 实测 8 变量 light/dark 翻转 + 真实登录错误框背景反色确认。 Co-Authored-By: 阿睿 <workbuddy@tencent.com>
540 lines
20 KiB
TypeScript
540 lines
20 KiB
TypeScript
'use client';
|
|
|
|
import { useEffect, useState, useCallback } from 'react';
|
|
import { useRouter } from 'next/navigation';
|
|
import { useAuth } from '@/components/admin/auth-context';
|
|
import { adminApi } from '@/lib/admin-api';
|
|
import { toast } from '@/components/ui/sonner';
|
|
import {
|
|
AlertDialog,
|
|
AlertDialogAction,
|
|
AlertDialogCancel,
|
|
AlertDialogContent,
|
|
AlertDialogDescription,
|
|
AlertDialogFooter,
|
|
AlertDialogHeader,
|
|
AlertDialogTitle,
|
|
} from '@/components/ui/alert-dialog';
|
|
import { Plus, Edit, Trash2, Search, UserCog, Shield, Mail, Calendar } from 'lucide-react';
|
|
|
|
interface UserData {
|
|
id: string;
|
|
username: string;
|
|
nickname: string;
|
|
email: string;
|
|
phone: string;
|
|
status: number;
|
|
role: string;
|
|
roles: Array<{ code: string; name: string }>;
|
|
createdAt: string;
|
|
updatedAt: string;
|
|
}
|
|
|
|
interface RoleData {
|
|
code: string;
|
|
name: string;
|
|
builtin: boolean;
|
|
}
|
|
|
|
const ROLE_LABELS: Record<string, string> = {
|
|
super_admin: '超级管理员',
|
|
content_admin: '内容管理员',
|
|
content_editor: '内容编辑',
|
|
reviewer: '审核员',
|
|
readonly: '只读用户',
|
|
};
|
|
|
|
const ROLE_COLORS: Record<string, string> = {
|
|
super_admin: 'bg-error-bg text-error-text',
|
|
content_admin: 'bg-info-bg text-info-text',
|
|
content_editor: 'bg-success-bg text-success-text',
|
|
reviewer: 'bg-warning-bg text-warning-text',
|
|
readonly: 'bg-bg-hover text-text-secondary',
|
|
};
|
|
|
|
export default function UsersPage() {
|
|
const { user, loading: authLoading } = useAuth();
|
|
const router = useRouter();
|
|
|
|
const [users, setUsers] = useState<UserData[]>([]);
|
|
const [total, setTotal] = useState(0);
|
|
const [page, setPage] = useState(1);
|
|
const [search, setSearch] = useState('');
|
|
const [loading, setLoading] = useState(true);
|
|
const [error, setError] = useState('');
|
|
const [roles, setRoles] = useState<RoleData[]>([]);
|
|
const pageSize = 20;
|
|
|
|
// Create/Edit dialog state
|
|
const [dialogOpen, setDialogOpen] = useState(false);
|
|
const [editingUser, setEditingUser] = useState<UserData | null>(null);
|
|
const [formData, setFormData] = useState({
|
|
username: '',
|
|
password: '',
|
|
nickname: '',
|
|
email: '',
|
|
phone: '',
|
|
roleCodes: [] as string[],
|
|
});
|
|
const [saving, setSaving] = useState(false);
|
|
|
|
// Delete dialog state
|
|
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
|
const [pendingDeleteId, setPendingDeleteId] = useState<string | null>(null);
|
|
|
|
const fetchUsers = useCallback(async () => {
|
|
setLoading(true);
|
|
setError('');
|
|
try {
|
|
const query = new URLSearchParams();
|
|
query.set('page', String(page));
|
|
query.set('pageSize', String(pageSize));
|
|
if (search) query.set('search', search);
|
|
|
|
const data = await adminApi.request<{
|
|
users: UserData[];
|
|
total: number;
|
|
page: number;
|
|
pageSize: number;
|
|
totalPages: number;
|
|
}>(`/api/admin/users?${query.toString()}`);
|
|
setUsers(data.users || []);
|
|
setTotal(data.total || 0);
|
|
} catch (err) {
|
|
setError(err instanceof Error ? err.message : '加载失败');
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, [page, search]);
|
|
|
|
const fetchRoles = useCallback(async () => {
|
|
try {
|
|
const data = await adminApi.getRoles();
|
|
setRoles(data.roles || []);
|
|
} catch {
|
|
// Roles fetch is secondary
|
|
}
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
if (!authLoading && !user) {
|
|
router.push('/admin/login');
|
|
return;
|
|
}
|
|
if (user) {
|
|
fetchUsers();
|
|
fetchRoles();
|
|
}
|
|
}, [user, authLoading, router, fetchUsers, fetchRoles]);
|
|
|
|
const openCreateDialog = () => {
|
|
setEditingUser(null);
|
|
setFormData({ username: '', password: '', nickname: '', email: '', phone: '', roleCodes: [] });
|
|
setDialogOpen(true);
|
|
};
|
|
|
|
const openEditDialog = (u: UserData) => {
|
|
setEditingUser(u);
|
|
setFormData({
|
|
username: u.username,
|
|
password: '',
|
|
nickname: u.nickname,
|
|
email: u.email,
|
|
phone: u.phone,
|
|
roleCodes: u.roles.map((r) => r.code),
|
|
});
|
|
setDialogOpen(true);
|
|
};
|
|
|
|
const handleSave = async () => {
|
|
if (editingUser) {
|
|
// Update
|
|
if (!formData.nickname && !formData.email) {
|
|
toast.error('请填写昵称或邮箱');
|
|
return;
|
|
}
|
|
setSaving(true);
|
|
try {
|
|
const body: Record<string, unknown> = {
|
|
nickname: formData.nickname,
|
|
email: formData.email,
|
|
phone: formData.phone,
|
|
roleCodes: formData.roleCodes,
|
|
};
|
|
if (formData.password) body.password = formData.password;
|
|
await adminApi.request(`/api/admin/users?id=${editingUser.id}`, {
|
|
method: 'PUT',
|
|
body: JSON.stringify(body),
|
|
});
|
|
toast.success('用户更新成功');
|
|
setDialogOpen(false);
|
|
fetchUsers();
|
|
} catch (err) {
|
|
toast.error(err instanceof Error ? err.message : '更新失败');
|
|
} finally {
|
|
setSaving(false);
|
|
}
|
|
} else {
|
|
// Create
|
|
if (!formData.username || !formData.password) {
|
|
toast.error('用户名和密码必填');
|
|
return;
|
|
}
|
|
if (formData.username.length < 3) {
|
|
toast.error('用户名长度不能少于 3 位');
|
|
return;
|
|
}
|
|
if (formData.password.length < 6) {
|
|
toast.error('密码长度不能少于 6 位');
|
|
return;
|
|
}
|
|
setSaving(true);
|
|
try {
|
|
await adminApi.request('/api/admin/users', {
|
|
method: 'POST',
|
|
body: JSON.stringify(formData),
|
|
});
|
|
toast.success('用户创建成功');
|
|
setDialogOpen(false);
|
|
fetchUsers();
|
|
} catch (err) {
|
|
toast.error(err instanceof Error ? err.message : '创建失败');
|
|
} finally {
|
|
setSaving(false);
|
|
}
|
|
}
|
|
};
|
|
|
|
const handleDelete = async () => {
|
|
if (!pendingDeleteId) return;
|
|
try {
|
|
await adminApi.request(`/api/admin/users?id=${pendingDeleteId}`, { method: 'DELETE' });
|
|
toast.success('用户已删除');
|
|
setDeleteDialogOpen(false);
|
|
setPendingDeleteId(null);
|
|
fetchUsers();
|
|
} catch (err) {
|
|
toast.error(err instanceof Error ? err.message : '删除失败');
|
|
}
|
|
};
|
|
|
|
const toggleRole = (code: string) => {
|
|
setFormData((prev) => ({
|
|
...prev,
|
|
roleCodes: prev.roleCodes.includes(code)
|
|
? prev.roleCodes.filter((r) => r !== code)
|
|
: [...prev.roleCodes, code],
|
|
}));
|
|
};
|
|
|
|
const totalPages = Math.ceil(total / pageSize);
|
|
|
|
if (authLoading || (!user && typeof window !== 'undefined')) {
|
|
return (
|
|
<div className="flex items-center justify-center h-64">
|
|
<div className="animate-spin w-8 h-8 border-2 border-border-dark border-t-transparent rounded-full" />
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<div className="space-y-6">
|
|
<div className="flex items-center justify-between">
|
|
<div>
|
|
<h1 className="text-xl font-bold text-text-primary">用户管理</h1>
|
|
<p className="text-sm text-text-muted mt-1">管理系统用户与角色分配</p>
|
|
</div>
|
|
<button
|
|
onClick={openCreateDialog}
|
|
className="flex items-center gap-2 px-4 py-2 bg-dark-bg text-white rounded-lg text-sm font-medium hover:bg-dark-bg-secondary transition-colors"
|
|
>
|
|
<Plus className="w-4 h-4" />
|
|
创建用户
|
|
</button>
|
|
</div>
|
|
|
|
{/* Search */}
|
|
<div className="relative">
|
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-text-muted" />
|
|
<input
|
|
type="text"
|
|
placeholder="搜索用户名、昵称或邮箱..."
|
|
value={search}
|
|
onChange={(e) => { setSearch(e.target.value); setPage(1); }}
|
|
className="w-full pl-10 pr-4 py-2 border border-border-primary rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-border-primary"
|
|
/>
|
|
</div>
|
|
|
|
{error && (
|
|
<div className="p-4 bg-error-bg border border-border-secondary rounded-lg text-sm text-error-text">
|
|
{error}
|
|
</div>
|
|
)}
|
|
|
|
{/* Users table */}
|
|
<div className="bg-bg-primary rounded-lg border border-border-primary overflow-hidden">
|
|
<div className="overflow-x-auto">
|
|
<table className="w-full text-sm">
|
|
<thead>
|
|
<tr className="border-b border-border-primary bg-bg-secondary">
|
|
<th className="text-left px-4 py-3 font-medium text-text-tertiary">用户名</th>
|
|
<th className="text-left px-4 py-3 font-medium text-text-tertiary">昵称</th>
|
|
<th className="text-left px-4 py-3 font-medium text-text-tertiary">邮箱</th>
|
|
<th className="text-left px-4 py-3 font-medium text-text-tertiary">角色</th>
|
|
<th className="text-left px-4 py-3 font-medium text-text-tertiary">状态</th>
|
|
<th className="text-left px-4 py-3 font-medium text-text-tertiary">创建时间</th>
|
|
<th className="text-right px-4 py-3 font-medium text-text-tertiary">操作</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{loading ? (
|
|
<tr>
|
|
<td colSpan={7} className="px-4 py-12 text-center text-text-muted">
|
|
<div className="flex items-center justify-center gap-2">
|
|
<div className="animate-spin w-4 h-4 border-2 border-border-secondary border-t-transparent rounded-full" />
|
|
加载中...
|
|
</div>
|
|
</td>
|
|
</tr>
|
|
) : users.length === 0 ? (
|
|
<tr>
|
|
<td colSpan={7} className="px-4 py-12 text-center text-text-muted">
|
|
暂无用户数据
|
|
</td>
|
|
</tr>
|
|
) : (
|
|
users.map((u) => (
|
|
<tr key={u.id} className="border-b border-border-light hover:bg-bg-secondary">
|
|
<td className="px-4 py-3">
|
|
<div className="flex items-center gap-2">
|
|
<UserCog className="w-4 h-4 text-text-muted" />
|
|
<span className="font-medium text-text-primary">{u.username}</span>
|
|
</div>
|
|
</td>
|
|
<td className="px-4 py-3 text-text-tertiary">{u.nickname || '-'}</td>
|
|
<td className="px-4 py-3">
|
|
{u.email ? (
|
|
<a href={`mailto:${u.email}`} className="text-text-tertiary hover:text-text-primary flex items-center gap-1">
|
|
<Mail className="w-3 h-3" />
|
|
{u.email}
|
|
</a>
|
|
) : (
|
|
<span className="text-text-muted">-</span>
|
|
)}
|
|
</td>
|
|
<td className="px-4 py-3">
|
|
<div className="flex flex-wrap gap-1">
|
|
{u.roles.map((r) => (
|
|
<span
|
|
key={r.code}
|
|
className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${
|
|
ROLE_COLORS[r.code] || 'bg-bg-hover text-text-secondary'
|
|
}`}
|
|
>
|
|
<Shield className="w-3 h-3" />
|
|
{r.name || ROLE_LABELS[r.code] || r.code}
|
|
</span>
|
|
))}
|
|
{u.roles.length === 0 && (
|
|
<span className="text-xs text-text-muted">无角色</span>
|
|
)}
|
|
</div>
|
|
</td>
|
|
<td className="px-4 py-3">
|
|
<span
|
|
className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
|
|
u.status === 1
|
|
? 'bg-success-bg text-success-text'
|
|
: 'bg-error-bg text-error-text'
|
|
}`}
|
|
>
|
|
{u.status === 1 ? '启用' : '禁用'}
|
|
</span>
|
|
</td>
|
|
<td className="px-4 py-3 text-text-muted text-xs">
|
|
<div className="flex items-center gap-1">
|
|
<Calendar className="w-3 h-3" />
|
|
{new Date(u.createdAt).toLocaleDateString('zh-CN')}
|
|
</div>
|
|
</td>
|
|
<td className="px-4 py-3 text-right">
|
|
<div className="flex items-center justify-end gap-1">
|
|
<button
|
|
onClick={() => openEditDialog(u)}
|
|
className="p-1.5 rounded hover:bg-bg-hover text-text-muted hover:text-text-secondary"
|
|
title="编辑"
|
|
>
|
|
<Edit className="w-4 h-4" />
|
|
</button>
|
|
<button
|
|
onClick={() => { setPendingDeleteId(u.id); setDeleteDialogOpen(true); }}
|
|
className="p-1.5 rounded hover:bg-error-bg text-text-muted hover:text-error-text"
|
|
title="删除"
|
|
>
|
|
<Trash2 className="w-4 h-4" />
|
|
</button>
|
|
</div>
|
|
</td>
|
|
</tr>
|
|
))
|
|
)}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
|
|
{/* Pagination */}
|
|
{totalPages > 1 && (
|
|
<div className="flex items-center justify-between px-4 py-3 border-t border-border-primary bg-bg-secondary">
|
|
<span className="text-sm text-text-muted">
|
|
共 {total} 条,第 {page}/{totalPages} 页
|
|
</span>
|
|
<div className="flex items-center gap-2">
|
|
<button
|
|
onClick={() => setPage((p) => Math.max(1, p - 1))}
|
|
disabled={page <= 1}
|
|
className="px-3 py-1.5 text-sm rounded border border-border-primary hover:bg-bg-hover disabled:opacity-50 disabled:cursor-not-allowed"
|
|
>
|
|
上一页
|
|
</button>
|
|
<button
|
|
onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
|
|
disabled={page >= totalPages}
|
|
className="px-3 py-1.5 text-sm rounded border border-border-primary hover:bg-bg-hover disabled:opacity-50 disabled:cursor-not-allowed"
|
|
>
|
|
下一页
|
|
</button>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
{/* Create/Edit Dialog */}
|
|
{dialogOpen && (
|
|
<div className="fixed inset-0 z-50 flex items-center justify-center">
|
|
<div className="fixed inset-0 bg-overlay/50" onClick={() => setDialogOpen(false)} />
|
|
<div className="relative bg-bg-primary rounded-lg shadow-xl w-full max-w-md mx-4 p-6">
|
|
<h2 className="text-lg font-bold text-text-primary mb-4">
|
|
{editingUser ? '编辑用户' : '创建用户'}
|
|
</h2>
|
|
|
|
<div className="space-y-4">
|
|
<div>
|
|
<label className="block text-sm font-medium text-text-secondary mb-1">用户名</label>
|
|
<input
|
|
type="text"
|
|
value={formData.username}
|
|
onChange={(e) => setFormData((p) => ({ ...p, username: e.target.value }))}
|
|
disabled={!!editingUser}
|
|
className="w-full px-3 py-2 border border-border-primary rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-border-primary disabled:bg-bg-hover disabled:text-text-muted"
|
|
placeholder="3-32 位字母/数字/下划线"
|
|
/>
|
|
</div>
|
|
|
|
<div>
|
|
<label className="block text-sm font-medium text-text-secondary mb-1">
|
|
{editingUser ? '新密码(留空不修改)' : '密码'}
|
|
</label>
|
|
<input
|
|
type="password"
|
|
value={formData.password}
|
|
onChange={(e) => setFormData((p) => ({ ...p, password: e.target.value }))}
|
|
className="w-full px-3 py-2 border border-border-primary rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-border-primary"
|
|
placeholder={editingUser ? '留空保持原密码' : '至少 6 位'}
|
|
/>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-2 gap-4">
|
|
<div>
|
|
<label className="block text-sm font-medium text-text-secondary mb-1">昵称</label>
|
|
<input
|
|
type="text"
|
|
value={formData.nickname}
|
|
onChange={(e) => setFormData((p) => ({ ...p, nickname: e.target.value }))}
|
|
className="w-full px-3 py-2 border border-border-primary rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-border-primary"
|
|
/>
|
|
</div>
|
|
<div>
|
|
<label className="block text-sm font-medium text-text-secondary mb-1">邮箱</label>
|
|
<input
|
|
type="email"
|
|
value={formData.email}
|
|
onChange={(e) => setFormData((p) => ({ ...p, email: e.target.value }))}
|
|
className="w-full px-3 py-2 border border-border-primary rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-border-primary"
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
<div>
|
|
<label className="block text-sm font-medium text-text-secondary mb-1">手机号</label>
|
|
<input
|
|
type="tel"
|
|
value={formData.phone}
|
|
onChange={(e) => setFormData((p) => ({ ...p, phone: e.target.value }))}
|
|
className="w-full px-3 py-2 border border-border-primary rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-border-primary"
|
|
/>
|
|
</div>
|
|
|
|
<div>
|
|
<label className="block text-sm font-medium text-text-secondary mb-2">角色分配</label>
|
|
<div className="flex flex-wrap gap-2">
|
|
{roles.map((r) => (
|
|
<button
|
|
key={r.code}
|
|
type="button"
|
|
onClick={() => toggleRole(r.code)}
|
|
className={`px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors ${
|
|
formData.roleCodes.includes(r.code)
|
|
? 'bg-dark-bg text-white border-border-dark'
|
|
: 'bg-bg-primary text-text-tertiary border-border-primary hover:border-border-secondary'
|
|
}`}
|
|
>
|
|
{r.name}
|
|
</button>
|
|
))}
|
|
{roles.length === 0 && (
|
|
<span className="text-xs text-text-muted">加载角色中...</span>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex items-center justify-end gap-3 mt-6 pt-4 border-t border-border-light">
|
|
<button
|
|
onClick={() => setDialogOpen(false)}
|
|
className="px-4 py-2 text-sm text-text-tertiary hover:text-text-primary"
|
|
>
|
|
取消
|
|
</button>
|
|
<button
|
|
onClick={handleSave}
|
|
disabled={saving}
|
|
className="flex items-center gap-2 px-4 py-2 bg-dark-bg text-white rounded-lg text-sm font-medium hover:bg-dark-bg-secondary disabled:opacity-50 transition-colors"
|
|
>
|
|
{saving && <div className="animate-spin w-4 h-4 border-2 border-white border-t-transparent rounded-full" />}
|
|
{editingUser ? '保存更改' : '创建用户'}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{/* Delete confirmation */}
|
|
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
|
<AlertDialogContent>
|
|
<AlertDialogHeader>
|
|
<AlertDialogTitle>确认删除</AlertDialogTitle>
|
|
<AlertDialogDescription>
|
|
删除后该用户将无法登录系统,此操作不可撤销。
|
|
</AlertDialogDescription>
|
|
</AlertDialogHeader>
|
|
<AlertDialogFooter>
|
|
<AlertDialogCancel>取消</AlertDialogCancel>
|
|
<AlertDialogAction onClick={handleDelete} className="bg-error hover:bg-error-hover">
|
|
确认删除
|
|
</AlertDialogAction>
|
|
</AlertDialogFooter>
|
|
</AlertDialogContent>
|
|
</AlertDialog>
|
|
</div>
|
|
);
|
|
} |