1
This commit is contained in:
@@ -0,0 +1,395 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import {
|
||||
Button, Card, Checkbox, Form, Input, InputNumber, message, Modal, Popconfirm, Select, Space, Switch, Table, Tabs, Tag, Typography,
|
||||
} from 'antd';
|
||||
import {
|
||||
UserOutlined, WalletOutlined, SearchOutlined, StopOutlined, CheckCircleOutlined, PlusOutlined, MenuOutlined, LockOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { getAdminUsers, adjustCredits, toggleUserStatus, createUser, updateUserMenus, getMenuConfigs, resetUserPassword } from '../api';
|
||||
import type { AdminUser } from '../types';
|
||||
import { formatDate } from '../utils/formatDate';
|
||||
|
||||
const AdminUsers: React.FC = () => {
|
||||
const [users, setUsers] = useState<AdminUser[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [search, setSearch] = useState('');
|
||||
const [activeTab, setActiveTab] = useState<string>('frontend');
|
||||
const [creditModal, setCreditModal] = useState<{ open: boolean; user: AdminUser | null }>({ open: false, user: null });
|
||||
const [createModal, setCreateModal] = useState(false);
|
||||
const [createType, setCreateType] = useState<string>('frontend');
|
||||
const [menuModal, setMenuModal] = useState<{ open: boolean; user: AdminUser | null }>({ open: false, user: null });
|
||||
const [allMenus, setAllMenus] = useState<any[]>([]);
|
||||
const [checkedMenus, setCheckedMenus] = useState<string[]>([]);
|
||||
const [resetPwdModal, setResetPwdModal] = useState<{ open: boolean; user: AdminUser | null }>({ open: false, user: null });
|
||||
const [form] = Form.useForm();
|
||||
const [createForm] = Form.useForm();
|
||||
const [resetPwdForm] = Form.useForm();
|
||||
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await getAdminUsers(search || undefined);
|
||||
setUsers(data);
|
||||
} catch { /* auth error handled by client */ }
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useEffect(() => { load(); }, []);
|
||||
|
||||
const handleSearch = () => load();
|
||||
|
||||
const handleAdjustCredits = async () => {
|
||||
try {
|
||||
const values = await form.validateFields();
|
||||
const { user } = creditModal;
|
||||
if (!user) return;
|
||||
await adjustCredits(user.id, values.amount, values.description);
|
||||
message.success(`已${values.amount > 0 ? '增加' : '扣除'} ${Math.abs(values.amount)} 积分`);
|
||||
setCreditModal({ open: false, user: null });
|
||||
form.resetFields();
|
||||
load();
|
||||
} catch { /* validation */ }
|
||||
};
|
||||
|
||||
const handleToggleStatus = async (user: AdminUser) => {
|
||||
await toggleUserStatus(user.id, !user.isActive);
|
||||
message.success(user.isActive ? '已禁用该用户' : '已启用该用户');
|
||||
load();
|
||||
};
|
||||
|
||||
const handleCreateUser = async () => {
|
||||
try {
|
||||
const values = await createForm.validateFields();
|
||||
const userType = values.user_type || 'frontend';
|
||||
await createUser({
|
||||
username: userType === 'admin' ? values.username : undefined,
|
||||
password: values.password,
|
||||
email: values.email || undefined,
|
||||
phone: userType === 'frontend' ? values.phone : (values.phone || undefined),
|
||||
credits: values.credits || 0,
|
||||
user_type: userType,
|
||||
});
|
||||
message.success('用户创建成功');
|
||||
setCreateModal(false);
|
||||
createForm.resetFields();
|
||||
setCreateType('frontend');
|
||||
load();
|
||||
} catch { /* validation */ }
|
||||
};
|
||||
|
||||
const openMenuModal = async (user: AdminUser) => {
|
||||
try {
|
||||
const menus = await getMenuConfigs();
|
||||
const isAdminUser = user.userType === 'admin';
|
||||
setAllMenus(menus.filter((m: any) => {
|
||||
const target = m.menu_target ?? m.menuTarget ?? 'frontend';
|
||||
return isAdminUser ? (target === 'admin' || target === 'both') : (target === 'frontend' || target === 'both');
|
||||
}));
|
||||
setCheckedMenus(user.allowedMenus || []);
|
||||
setMenuModal({ open: true, user });
|
||||
} catch {
|
||||
message.error('加载菜单失败');
|
||||
}
|
||||
};
|
||||
|
||||
// Build structured menu display: groups with children, and top-level pages
|
||||
const menuGroups = allMenus.filter((m: any) => (m.menu_type ?? m.menuType) === 'group');
|
||||
const menuPages = allMenus.filter((m: any) => (m.menu_type ?? m.menuType) !== 'group');
|
||||
const childMap: Record<string, any[]> = {};
|
||||
menuPages.filter((m: any) => m.parent_id ?? m.parentId).forEach((m: any) => {
|
||||
const pid = m.parent_id ?? m.parentId;
|
||||
if (!childMap[pid]) childMap[pid] = [];
|
||||
childMap[pid].push(m);
|
||||
});
|
||||
const topLevelPages = menuPages.filter((m: any) => !(m.parent_id ?? m.parentId));
|
||||
|
||||
const handleSaveMenus = async () => {
|
||||
const { user } = menuModal;
|
||||
if (!user) return;
|
||||
try {
|
||||
await updateUserMenus(user.id, checkedMenus.length > 0 ? checkedMenus : null);
|
||||
message.success('菜单权限已更新');
|
||||
setMenuModal({ open: false, user: null });
|
||||
load();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '保存失败');
|
||||
}
|
||||
};
|
||||
|
||||
const handleResetPassword = async () => {
|
||||
try {
|
||||
const values = await resetPwdForm.validateFields();
|
||||
const { user } = resetPwdModal;
|
||||
if (!user) return;
|
||||
await resetUserPassword(user.id, values.newPassword);
|
||||
message.success(`已重置 ${user.username} 的密码`);
|
||||
setResetPwdModal({ open: false, user: null });
|
||||
resetPwdForm.resetFields();
|
||||
} catch { /* validation */ }
|
||||
};
|
||||
|
||||
const filteredUsers = users.filter(u => u.userType === activeTab);
|
||||
const isAdminTab = activeTab === 'admin';
|
||||
|
||||
const columns = [
|
||||
{
|
||||
title: '用户', key: 'user', width: 200,
|
||||
render: (_: any, r: AdminUser) => (
|
||||
<Space>
|
||||
<div style={{
|
||||
width: 32, height: 32, borderRadius: 8,
|
||||
background: r.isAdmin ? 'linear-gradient(135deg, #f59e0b, #f97316)' : 'linear-gradient(135deg, #6366f1, #8b5cf6)',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
color: '#fff', fontSize: 13, fontWeight: 700,
|
||||
}}>
|
||||
{r.username.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
<div>
|
||||
<div style={{ fontWeight: 600 }}>
|
||||
{r.username}
|
||||
{r.isAdmin && <Tag color="orange" style={{ marginLeft: 6, fontSize: 10 }}>管理员</Tag>}
|
||||
</div>
|
||||
<div style={{ color: '#94a3b8', fontSize: 12 }}>{r.email}</div>
|
||||
</div>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
...(!isAdminTab ? [{
|
||||
title: '积分余额', dataIndex: 'credits', width: 120, sorter: (a: AdminUser, b: AdminUser) => a.credits - b.credits,
|
||||
render: (v: number) => (
|
||||
<Typography.Text strong style={{ color: v > 0 ? '#10b981' : '#ef4444', fontSize: 15 }}>
|
||||
{v.toLocaleString()}
|
||||
</Typography.Text>
|
||||
),
|
||||
}] : []),
|
||||
{
|
||||
title: '手机号', dataIndex: 'phone', width: 130,
|
||||
render: (v: string) => <Typography.Text type="secondary">{v || '-'}</Typography.Text>,
|
||||
},
|
||||
{
|
||||
title: '状态', dataIndex: 'isActive', width: 80,
|
||||
render: (v: boolean) => (
|
||||
<Tag color={v ? 'green' : 'red'}>{v ? '正常' : '禁用'}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '注册时间', dataIndex: 'createdAt', width: 120,
|
||||
render: (v: string) => <Typography.Text type="secondary" style={{ fontSize: 12 }}>{formatDate(v)}</Typography.Text>,
|
||||
},
|
||||
{
|
||||
title: '最后登录', dataIndex: 'lastLoginAt', width: 140,
|
||||
render: (v: string) => <Typography.Text type="secondary" style={{ fontSize: 12 }}>{formatDate(v)}</Typography.Text>,
|
||||
},
|
||||
{
|
||||
title: '操作', key: 'action', width: 320, fixed: 'right' as const,
|
||||
render: (_: any, r: AdminUser) => (
|
||||
<Space size={4}>
|
||||
{!isAdminTab && (
|
||||
<Button type="link" size="small" icon={<WalletOutlined />}
|
||||
onClick={() => { setCreditModal({ open: true, user: r }); form.resetFields(); }}>
|
||||
调整积分
|
||||
</Button>
|
||||
)}
|
||||
<Button type="link" size="small" icon={<MenuOutlined />}
|
||||
onClick={() => openMenuModal(r)}>
|
||||
菜单权限
|
||||
</Button>
|
||||
<Button type="link" size="small" icon={<LockOutlined />}
|
||||
onClick={() => { setResetPwdModal({ open: true, user: r }); resetPwdForm.resetFields(); }}>
|
||||
重置密码
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title={r.isActive ? '确定禁用该用户?' : '确定启用该用户?'}
|
||||
onConfirm={() => handleToggleStatus(r)}
|
||||
>
|
||||
<Button type="link" size="small" danger={r.isActive}
|
||||
icon={r.isActive ? <StopOutlined /> : <CheckCircleOutlined />}>
|
||||
{r.isActive ? '禁用' : '启用'}
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Card bordered={false} style={{ borderRadius: 12, border: '1px solid #f0f0f5' }}>
|
||||
{/* Search bar */}
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
|
||||
<div style={{ display: 'flex', gap: 12 }}>
|
||||
<Input
|
||||
placeholder="搜索用户名或手机号"
|
||||
prefix={<SearchOutlined style={{ color: '#94a3b8' }} />}
|
||||
value={search}
|
||||
onChange={e => setSearch(e.target.value)}
|
||||
onPressEnter={handleSearch}
|
||||
style={{ width: 280, borderRadius: 8 }}
|
||||
allowClear
|
||||
/>
|
||||
<Button type="primary" onClick={handleSearch} style={{ borderRadius: 8 }}>搜索</Button>
|
||||
</div>
|
||||
<Button type="primary" icon={<PlusOutlined />}
|
||||
onClick={() => { setCreateType(activeTab); createForm.setFieldsValue({ user_type: activeTab }); setCreateModal(true); }}
|
||||
style={{ borderRadius: 8 }}>
|
||||
创建用户
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Tabs
|
||||
activeKey={activeTab}
|
||||
onChange={setActiveTab}
|
||||
items={[
|
||||
{ key: 'frontend', label: '前台用户' },
|
||||
{ key: 'admin', label: '后台用户' },
|
||||
]}
|
||||
/>
|
||||
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={filteredUsers}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
pagination={{ pageSize: 10, showTotal: (t) => `共 ${t} 个用户` }}
|
||||
scroll={{ x: 1000 }}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{/* Adjust Credits Modal */}
|
||||
<Modal
|
||||
title={<Space><WalletOutlined />调整积分 - {creditModal.user?.username}</Space>}
|
||||
open={creditModal.open}
|
||||
onOk={handleAdjustCredits}
|
||||
onCancel={() => { setCreditModal({ open: false, user: null }); form.resetFields(); }}
|
||||
okText="确认" cancelText="取消" width={440}
|
||||
>
|
||||
<div style={{ marginBottom: 16, padding: '12px 16px', background: '#f8fafc', borderRadius: 8 }}>
|
||||
<span style={{ color: '#64748b' }}>当前积分:</span>
|
||||
<span style={{ fontWeight: 800, fontSize: 18, color: '#6366f1' }}>
|
||||
{creditModal.user?.credits.toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form.Item name="amount" label="积分变动"
|
||||
rules={[{ required: true, message: '请输入积分数量' }]}>
|
||||
<InputNumber
|
||||
style={{ width: '100%' }}
|
||||
size="large"
|
||||
placeholder="正数增加,负数扣除"
|
||||
formatter={v => `${v}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="description" label="原因"
|
||||
rules={[{ required: true, message: '请输入调整原因' }]}>
|
||||
<Input.TextArea rows={2} placeholder="请输入调整原因" size="large" />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
{/* Create User Modal */}
|
||||
<Modal
|
||||
title={<Space><UserOutlined />创建用户</Space>}
|
||||
open={createModal}
|
||||
onOk={handleCreateUser}
|
||||
onCancel={() => { setCreateModal(false); createForm.resetFields(); setCreateType('frontend'); }}
|
||||
okText="创建" cancelText="取消" width={480}
|
||||
>
|
||||
<Form form={createForm} layout="vertical" style={{ marginTop: 16 }}
|
||||
onValuesChange={(changed) => { if (changed.user_type) setCreateType(changed.user_type); }}
|
||||
>
|
||||
<Form.Item name="user_type" label="用户类型" initialValue="frontend" rules={[{ required: true }]}>
|
||||
<Select size="large" options={[
|
||||
{ value: 'frontend', label: '前端用户' },
|
||||
{ value: 'admin', label: '后台管理员' },
|
||||
]} />
|
||||
</Form.Item>
|
||||
{createType === 'frontend' ? (
|
||||
<Form.Item name="phone" label="手机号" rules={[{ required: true, message: '请输入手机号' }, { pattern: /^1\d{10}$/, message: '请输入正确的手机号' }]}>
|
||||
<Input placeholder="请输入手机号" maxLength={11} size="large" />
|
||||
</Form.Item>
|
||||
) : (
|
||||
<Form.Item name="username" label="用户名" rules={[{ required: true, message: '请输入用户名' }]}>
|
||||
<Input placeholder="请输入用户名" size="large" />
|
||||
</Form.Item>
|
||||
)}
|
||||
<Form.Item name="password" label="密码" rules={[{ required: true, min: 6, message: '密码至少6位' }]}>
|
||||
<Input.Password placeholder="请输入密码(至少6位)" size="large" />
|
||||
</Form.Item>
|
||||
{createType === 'frontend' && (
|
||||
<Form.Item name="credits" label="初始积分" initialValue={0}>
|
||||
<InputNumber min={0} style={{ width: '100%' }} size="large" />
|
||||
</Form.Item>
|
||||
)}
|
||||
<Form.Item name="email" label="邮箱">
|
||||
<Input placeholder="选填" size="large" />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
{/* Menu Permission Modal */}
|
||||
<Modal
|
||||
title={<Space><MenuOutlined />菜单权限 - {menuModal.user?.username} ({menuModal.user?.userType === 'admin' ? '后台菜单' : '前台菜单'})</Space>}
|
||||
open={menuModal.open}
|
||||
onOk={handleSaveMenus}
|
||||
onCancel={() => { setMenuModal({ open: false, user: null }); }}
|
||||
okText="保存" cancelText="取消" width={520}
|
||||
>
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 13 }}>
|
||||
勾选该用户可访问的菜单,不勾选则显示全部菜单
|
||||
</Typography.Text>
|
||||
</div>
|
||||
<div style={{ padding: '12px 16px', background: '#f8fafc', borderRadius: 8, maxHeight: 400, overflow: 'auto' }}>
|
||||
<Checkbox.Group value={checkedMenus} onChange={(vals) => setCheckedMenus(vals as string[])}>
|
||||
<Space direction="vertical" size={8} style={{ width: '100%' }}>
|
||||
{/* Top-level pages */}
|
||||
{topLevelPages.map((m: any) => (
|
||||
<Checkbox key={m.path} value={m.path} style={{ width: '100%' }}>
|
||||
{m.label}
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12, marginLeft: 8 }}>{m.path}</Typography.Text>
|
||||
</Checkbox>
|
||||
))}
|
||||
{/* Groups with their children */}
|
||||
{menuGroups.map((g: any) => {
|
||||
const children = childMap[g.id] || [];
|
||||
if (children.length === 0) return null;
|
||||
return (
|
||||
<div key={g.id}>
|
||||
<div style={{ fontWeight: 600, fontSize: 13, color: '#6366f1', marginBottom: 4, marginTop: 4 }}>
|
||||
{g.label}
|
||||
</div>
|
||||
<Space direction="vertical" size={4} style={{ paddingLeft: 12, width: '100%' }}>
|
||||
{children.map((c: any) => (
|
||||
<Checkbox key={c.path} value={c.path} style={{ width: '100%' }}>
|
||||
{c.label}
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12, marginLeft: 8 }}>{c.path}</Typography.Text>
|
||||
</Checkbox>
|
||||
))}
|
||||
</Space>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</Space>
|
||||
</Checkbox.Group>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
{/* Reset Password Modal */}
|
||||
<Modal
|
||||
title={<Space><LockOutlined />重置密码 - {resetPwdModal.user?.username}</Space>}
|
||||
open={resetPwdModal.open}
|
||||
onOk={handleResetPassword}
|
||||
onCancel={() => { setResetPwdModal({ open: false, user: null }); resetPwdForm.resetFields(); }}
|
||||
okText="确认重置" cancelText="取消" width={420}
|
||||
>
|
||||
<Form form={resetPwdForm} layout="vertical" style={{ marginTop: 16 }}>
|
||||
<Form.Item name="newPassword" label="新密码" rules={[{ required: true, min: 6, message: '密码至少6位' }]}>
|
||||
<Input.Password placeholder="请输入新密码(至少6位)" size="large" />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AdminUsers;
|
||||
Reference in New Issue
Block a user