feat(admin): enhance admin dashboard, user management, and content editor UX
- Dashboard: add stats API with content status distribution, recent notifications, and recent content updates; display active users, pending reviews, unread counts - User management: full CRUD with role assignment, search, pagination, delete dialog - Notification center: list with unread filter, mark as read, mark all as read, pagination, and auto-refresh unread count - Content editor: form validation (required fields, slug format, blur-triggered errors), auto-save with 3s debounce and status indicator, publish confirmation dialog, unsaved changes warning on leave - Admin layout: add navigation links for user management, roles, and notifications - admin-api: make request() method public for custom API calls - gitignore: add reports/mutation/ to exclude mutation test output
This commit is contained in:
@@ -0,0 +1,540 @@
|
||||
'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-red-100 text-red-700',
|
||||
content_admin: 'bg-blue-100 text-blue-700',
|
||||
content_editor: 'bg-green-100 text-green-700',
|
||||
reviewer: 'bg-amber-100 text-amber-700',
|
||||
readonly: 'bg-gray-100 text-gray-700',
|
||||
};
|
||||
|
||||
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-gray-900 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-gray-900">用户管理</h1>
|
||||
<p className="text-sm text-gray-500 mt-1">管理系统用户与角色分配</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={openCreateDialog}
|
||||
className="flex items-center gap-2 px-4 py-2 bg-gray-900 text-white rounded-lg text-sm font-medium hover:bg-gray-800 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-gray-400" />
|
||||
<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-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-200"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="p-4 bg-red-50 border border-red-200 rounded-lg text-sm text-red-600">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Users table */}
|
||||
<div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-gray-200 bg-gray-50">
|
||||
<th className="text-left px-4 py-3 font-medium text-gray-600">用户名</th>
|
||||
<th className="text-left px-4 py-3 font-medium text-gray-600">昵称</th>
|
||||
<th className="text-left px-4 py-3 font-medium text-gray-600">邮箱</th>
|
||||
<th className="text-left px-4 py-3 font-medium text-gray-600">角色</th>
|
||||
<th className="text-left px-4 py-3 font-medium text-gray-600">状态</th>
|
||||
<th className="text-left px-4 py-3 font-medium text-gray-600">创建时间</th>
|
||||
<th className="text-right px-4 py-3 font-medium text-gray-600">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{loading ? (
|
||||
<tr>
|
||||
<td colSpan={7} className="px-4 py-12 text-center text-gray-400">
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<div className="animate-spin w-4 h-4 border-2 border-gray-400 border-t-transparent rounded-full" />
|
||||
加载中...
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
) : users.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={7} className="px-4 py-12 text-center text-gray-400">
|
||||
暂无用户数据
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
users.map((u) => (
|
||||
<tr key={u.id} className="border-b border-gray-100 hover:bg-gray-50">
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<UserCog className="w-4 h-4 text-gray-400" />
|
||||
<span className="font-medium text-gray-900">{u.username}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-gray-600">{u.nickname || '-'}</td>
|
||||
<td className="px-4 py-3">
|
||||
{u.email ? (
|
||||
<a href={`mailto:${u.email}`} className="text-gray-600 hover:text-gray-900 flex items-center gap-1">
|
||||
<Mail className="w-3 h-3" />
|
||||
{u.email}
|
||||
</a>
|
||||
) : (
|
||||
<span className="text-gray-400">-</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-gray-100 text-gray-700'
|
||||
}`}
|
||||
>
|
||||
<Shield className="w-3 h-3" />
|
||||
{r.name || ROLE_LABELS[r.code] || r.code}
|
||||
</span>
|
||||
))}
|
||||
{u.roles.length === 0 && (
|
||||
<span className="text-xs text-gray-400">无角色</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-green-100 text-green-700'
|
||||
: 'bg-red-100 text-red-700'
|
||||
}`}
|
||||
>
|
||||
{u.status === 1 ? '启用' : '禁用'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-gray-500 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-gray-100 text-gray-500 hover:text-gray-700"
|
||||
title="编辑"
|
||||
>
|
||||
<Edit className="w-4 h-4" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => { setPendingDeleteId(u.id); setDeleteDialogOpen(true); }}
|
||||
className="p-1.5 rounded hover:bg-red-50 text-gray-500 hover:text-red-600"
|
||||
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-gray-200 bg-gray-50">
|
||||
<span className="text-sm text-gray-500">
|
||||
共 {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-gray-200 hover:bg-gray-100 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-gray-200 hover:bg-gray-100 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-black/50" onClick={() => setDialogOpen(false)} />
|
||||
<div className="relative bg-white rounded-lg shadow-xl w-full max-w-md mx-4 p-6">
|
||||
<h2 className="text-lg font-bold text-gray-900 mb-4">
|
||||
{editingUser ? '编辑用户' : '创建用户'}
|
||||
</h2>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 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-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-200 disabled:bg-gray-100 disabled:text-gray-400"
|
||||
placeholder="3-32 位字母/数字/下划线"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 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-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-200"
|
||||
placeholder={editingUser ? '留空保持原密码' : '至少 6 位'}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 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-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-200"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 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-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-200"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 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-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-200"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 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-gray-900 text-white border-gray-900'
|
||||
: 'bg-white text-gray-600 border-gray-200 hover:border-gray-400'
|
||||
}`}
|
||||
>
|
||||
{r.name}
|
||||
</button>
|
||||
))}
|
||||
{roles.length === 0 && (
|
||||
<span className="text-xs text-gray-400">加载角色中...</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-end gap-3 mt-6 pt-4 border-t border-gray-100">
|
||||
<button
|
||||
onClick={() => setDialogOpen(false)}
|
||||
className="px-4 py-2 text-sm text-gray-600 hover:text-gray-900"
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={saving}
|
||||
className="flex items-center gap-2 px-4 py-2 bg-gray-900 text-white rounded-lg text-sm font-medium hover:bg-gray-800 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-red-600 hover:bg-red-700">
|
||||
确认删除
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user