| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653 |
- import React, { useState } from 'react';
- import { useQuery } from '@tanstack/react-query';
- import { format } from 'date-fns';
- import { Plus, Search, Edit, Trash2 } from 'lucide-react';
- import { userClient } from '@/client/api';
- import type { InferRequestType, InferResponseType } from 'hono/client';
- import { Button } from '@/client/components/ui/button';
- import { Input } from '@/client/components/ui/input';
- import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/client/components/ui/card';
- import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/client/components/ui/table';
- import { Badge } from '@/client/components/ui/badge';
- import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/client/components/ui/dialog';
- import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/client/components/ui/form';
- import { useForm } from 'react-hook-form';
- import { zodResolver } from '@hookform/resolvers/zod';
- import { z } from 'zod';
- import { toast } from 'sonner';
- import { Skeleton } from '@/client/components/ui/skeleton';
- import { Switch } from '@/client/components/ui/switch';
- // 使用RPC方式提取类型
- type CreateUserRequest = InferRequestType<typeof userClient.$post>['json'];
- type UpdateUserRequest = InferRequestType<typeof userClient[':id']['$put']>['json'];
- type UserResponse = InferResponseType<typeof userClient.$get, 200>['data'][0];
- // 创建用户表单Schema - 与后端CreateUserSchema保持一致
- const createUserFormSchema = z.object({
- username: z.string().min(3, '用户名至少3个字符'),
- nickname: z.string().optional(),
- email: z.string().email('请输入有效的邮箱地址').optional().transform(val => val === '' ? null : val),
- phone: z.string().regex(/^1[3-9]\d{9}$/, '请输入有效的手机号').optional().transform(val => val === '' ? null : val),
- name: z.string().optional().transform(val => val === '' ? null : val),
- password: z.string().min(6, '密码至少6个字符'),
- isDisabled: z.boolean().default(false),
- });
- // 更新用户表单Schema - 与后端UpdateUserSchema保持一致
- const updateUserFormSchema = z.object({
- username: z.string().min(3, '用户名至少3个字符').optional(),
- nickname: z.string().optional(),
- email: z.string().email('请输入有效的邮箱地址').optional().transform(val => val === '' ? null : val),
- phone: z.string().regex(/^1[3-9]\d{9}$/, '请输入有效的手机号').optional().transform(val => val === '' ? null : val),
- name: z.string().optional().transform(val => val === '' ? null : val),
- password: z.string().min(6, '密码至少6个字符').optional(),
- isDisabled: z.boolean().optional(),
- });
- type CreateUserFormData = z.infer<typeof createUserFormSchema>;
- type UpdateUserFormData = z.infer<typeof updateUserFormSchema>;
- export const UsersPage = () => {
- const [searchParams, setSearchParams] = useState({
- page: 1,
- limit: 10,
- search: ''
- });
- const [isModalOpen, setIsModalOpen] = useState(false);
- const [editingUser, setEditingUser] = useState<any>(null);
- const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
- const [userToDelete, setUserToDelete] = useState<number | null>(null);
- const [isCreateForm, setIsCreateForm] = useState(true);
-
- const createForm = useForm<CreateUserFormData>({
- resolver: zodResolver(createUserFormSchema),
- defaultValues: {
- username: '',
- nickname: '',
- email: '',
- phone: '',
- name: '',
- password: '',
- isDisabled: false,
- },
- });
- const updateForm = useForm<UpdateUserFormData>({
- resolver: zodResolver(updateUserFormSchema),
- defaultValues: {
- username: '',
- nickname: '',
- email: '',
- phone: '',
- name: '',
- password: '',
- isDisabled: false,
- },
- });
- const { data: usersData, isLoading, refetch } = useQuery({
- queryKey: ['users', searchParams],
- queryFn: async () => {
- const res = await userClient.$get({
- query: {
- page: searchParams.page,
- pageSize: searchParams.limit,
- keyword: searchParams.search
- }
- });
- if (res.status !== 200) {
- throw new Error('获取用户列表失败');
- }
- return await res.json();
- }
- });
- const users = usersData?.data || [];
- const totalCount = usersData?.pagination?.total || 0;
- // 处理搜索
- const handleSearch = (e: React.FormEvent) => {
- e.preventDefault();
- setSearchParams(prev => ({ ...prev, page: 1 }));
- };
- // 处理分页
- const handlePageChange = (page: number, limit: number) => {
- setSearchParams(prev => ({ ...prev, page, limit }));
- };
- // 打开创建用户对话框
- const handleCreateUser = () => {
- setEditingUser(null);
- setIsCreateForm(true);
- createForm.reset({
- username: '',
- nickname: '',
- email: '',
- phone: '',
- name: '',
- password: '',
- isDisabled: false,
- });
- setIsModalOpen(true);
- };
- // 打开编辑用户对话框
- const handleEditUser = (user: UserResponse) => {
- setEditingUser(user);
- setIsCreateForm(false);
- updateForm.reset({
- username: user.username,
- nickname: user.nickname || '',
- email: user.email || '',
- phone: user.phone || '',
- name: user.name || '',
- isDisabled: user.isDisabled === 1,
- });
- setIsModalOpen(true);
- };
- // 处理创建表单提交
- const handleCreateSubmit = async (data: CreateUserFormData) => {
- try {
- const submitData: CreateUserRequest = {
- ...data,
- isDisabled: data.isDisabled ? 1 : 0,
- };
- const res = await userClient.$post({
- json: submitData
- });
- if (res.status !== 201) {
- throw new Error('创建用户失败');
- }
- toast.success('用户创建成功');
- setIsModalOpen(false);
- refetch();
- } catch (error) {
- console.error('创建用户失败:', error);
- toast.error('创建失败,请重试');
- }
- };
- // 处理更新表单提交
- const handleUpdateSubmit = async (data: UpdateUserFormData) => {
- if (!editingUser) return;
-
- try {
- const submitData: UpdateUserRequest = {
- ...data,
- isDisabled: data.isDisabled !== undefined ? (data.isDisabled ? 1 : 0) : undefined,
- };
- const res = await userClient[':id']['$put']({
- param: { id: editingUser.id },
- json: submitData
- });
- if (res.status !== 200) {
- throw new Error('更新用户失败');
- }
- toast.success('用户更新成功');
- setIsModalOpen(false);
- refetch();
- } catch (error) {
- console.error('更新用户失败:', error);
- toast.error('更新失败,请重试');
- }
- };
- // 处理删除用户
- const handleDeleteUser = (id: number) => {
- setUserToDelete(id);
- setDeleteDialogOpen(true);
- };
- const confirmDelete = async () => {
- if (!userToDelete) return;
-
- try {
- const res = await userClient[':id']['$delete']({
- param: { id: userToDelete }
- });
- if (res.status !== 204) {
- throw new Error('删除用户失败');
- }
- toast.success('用户删除成功');
- refetch();
- } catch (error) {
- console.error('删除用户失败:', error);
- toast.error('删除失败,请重试');
- } finally {
- setDeleteDialogOpen(false);
- setUserToDelete(null);
- }
- };
- // 渲染加载骨架
- if (isLoading) {
- return (
- <div className="space-y-4">
- <div className="flex justify-between items-center">
- <h1 className="text-2xl font-bold">用户管理</h1>
- <Button disabled>
- <Plus className="mr-2 h-4 w-4" />
- 创建用户
- </Button>
- </div>
-
- <Card>
- <CardHeader>
- <Skeleton className="h-6 w-1/4" />
- </CardHeader>
- <CardContent>
- <div className="space-y-2">
- <Skeleton className="h-4 w-full" />
- <Skeleton className="h-4 w-full" />
- <Skeleton className="h-4 w-full" />
- </div>
- </CardContent>
- </Card>
- </div>
- );
- }
- return (
- <div className="space-y-4">
- <div className="flex justify-between items-center">
- <h1 className="text-2xl font-bold">用户管理</h1>
- <Button onClick={handleCreateUser}>
- <Plus className="mr-2 h-4 w-4" />
- 创建用户
- </Button>
- </div>
- <Card>
- <CardHeader>
- <CardTitle>用户列表</CardTitle>
- <CardDescription>
- 管理系统中的所有用户,共 {totalCount} 位用户
- </CardDescription>
- </CardHeader>
- <CardContent>
- <div className="mb-4">
- <form onSubmit={handleSearch} className="flex gap-2">
- <div className="relative flex-1 max-w-sm">
- <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
- <Input
- placeholder="搜索用户名、昵称或邮箱..."
- value={searchParams.search}
- onChange={(e) => setSearchParams(prev => ({ ...prev, search: e.target.value }))}
- className="pl-8"
- />
- </div>
- <Button type="submit" variant="outline">
- 搜索
- </Button>
- </form>
- </div>
- <div className="rounded-md border">
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead>用户名</TableHead>
- <TableHead>昵称</TableHead>
- <TableHead>邮箱</TableHead>
- <TableHead>真实姓名</TableHead>
- <TableHead>角色</TableHead>
- <TableHead>状态</TableHead>
- <TableHead>创建时间</TableHead>
- <TableHead className="text-right">操作</TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {users.map((user) => (
- <TableRow key={user.id}>
- <TableCell className="font-medium">{user.username}</TableCell>
- <TableCell>{user.nickname || '-'}</TableCell>
- <TableCell>{user.email || '-'}</TableCell>
- <TableCell>{user.name || '-'}</TableCell>
- <TableCell>
- <Badge
- variant={user.roles?.some((role: any) => role.name === 'admin') ? 'destructive' : 'default'}
- className="capitalize"
- >
- {user.roles?.some((role: any) => role.name === 'admin') ? '管理员' : '普通用户'}
- </Badge>
- </TableCell>
- <TableCell>
- <Badge
- variant={user.isDisabled === 1 ? 'secondary' : 'default'}
- >
- {user.isDisabled === 1 ? '禁用' : '启用'}
- </Badge>
- </TableCell>
- <TableCell>
- {format(new Date(user.createdAt), 'yyyy-MM-dd HH:mm')}
- </TableCell>
- <TableCell className="text-right">
- <div className="flex justify-end gap-2">
- <Button
- variant="ghost"
- size="icon"
- onClick={() => handleEditUser(user)}
- >
- <Edit className="h-4 w-4" />
- </Button>
- <Button
- variant="ghost"
- size="icon"
- onClick={() => handleDeleteUser(user.id)}
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- </div>
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- </div>
- <div className="flex justify-between items-center mt-4">
- <div className="text-sm text-muted-foreground">
- 第 {searchParams.page} 页,共 {Math.ceil(totalCount / searchParams.limit)} 页
- </div>
- <div className="flex gap-2">
- <Button
- variant="outline"
- size="sm"
- disabled={searchParams.page <= 1}
- onClick={() => handlePageChange(searchParams.page - 1, searchParams.limit)}
- >
- 上一页
- </Button>
- <Button
- variant="outline"
- size="sm"
- disabled={searchParams.page >= Math.ceil(totalCount / searchParams.limit)}
- onClick={() => handlePageChange(searchParams.page + 1, searchParams.limit)}
- >
- 下一页
- </Button>
- </div>
- </div>
- </CardContent>
- </Card>
- {/* 创建/编辑用户对话框 */}
- <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
- <DialogContent className="sm:max-w-[500px]">
- <DialogHeader>
- <DialogTitle>
- {editingUser ? '编辑用户' : '创建用户'}
- </DialogTitle>
- <DialogDescription>
- {editingUser ? '编辑现有用户信息' : '创建一个新的用户账户'}
- </DialogDescription>
- </DialogHeader>
-
- {isCreateForm ? (
- <Form {...createForm}>
- <form onSubmit={createForm.handleSubmit(handleCreateSubmit)} className="space-y-4">
- <FormField
- control={createForm.control}
- name="username"
- render={({ field }) => (
- <FormItem>
- <FormLabel>用户名</FormLabel>
- <FormControl>
- <Input placeholder="请输入用户名" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={createForm.control}
- name="nickname"
- render={({ field }) => (
- <FormItem>
- <FormLabel>昵称</FormLabel>
- <FormControl>
- <Input placeholder="请输入昵称" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={createForm.control}
- name="email"
- render={({ field }) => (
- <FormItem>
- <FormLabel>邮箱</FormLabel>
- <FormControl>
- <Input type="email" placeholder="请输入邮箱" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={createForm.control}
- name="phone"
- render={({ field }) => (
- <FormItem>
- <FormLabel>手机号</FormLabel>
- <FormControl>
- <Input placeholder="请输入手机号" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={createForm.control}
- name="name"
- render={({ field }) => (
- <FormItem>
- <FormLabel>真实姓名</FormLabel>
- <FormControl>
- <Input placeholder="请输入真实姓名" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={createForm.control}
- name="password"
- render={({ field }) => (
- <FormItem>
- <FormLabel>密码</FormLabel>
- <FormControl>
- <Input type="password" placeholder="请输入密码" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={createForm.control}
- name="isDisabled"
- render={({ field }) => (
- <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
- <div className="space-y-0.5">
- <FormLabel className="text-base">用户状态</FormLabel>
- <FormDescription>
- 禁用后用户将无法登录系统
- </FormDescription>
- </div>
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- </FormItem>
- )}
- />
- <DialogFooter>
- <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
- 取消
- </Button>
- <Button type="submit">
- 创建用户
- </Button>
- </DialogFooter>
- </form>
- </Form>
- ) : (
- <Form {...updateForm}>
- <form onSubmit={updateForm.handleSubmit(handleUpdateSubmit)} className="space-y-4">
- <FormField
- control={updateForm.control}
- name="username"
- render={({ field }) => (
- <FormItem>
- <FormLabel>用户名</FormLabel>
- <FormControl>
- <Input placeholder="请输入用户名" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={updateForm.control}
- name="nickname"
- render={({ field }) => (
- <FormItem>
- <FormLabel>昵称</FormLabel>
- <FormControl>
- <Input placeholder="请输入昵称" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={updateForm.control}
- name="email"
- render={({ field }) => (
- <FormItem>
- <FormLabel>邮箱</FormLabel>
- <FormControl>
- <Input type="email" placeholder="请输入邮箱" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={updateForm.control}
- name="phone"
- render={({ field }) => (
- <FormItem>
- <FormLabel>手机号</FormLabel>
- <FormControl>
- <Input placeholder="请输入手机号" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={updateForm.control}
- name="name"
- render={({ field }) => (
- <FormItem>
- <FormLabel>真实姓名</FormLabel>
- <FormControl>
- <Input placeholder="请输入真实姓名" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={updateForm.control}
- name="password"
- render={({ field }) => (
- <FormItem>
- <FormLabel>新密码</FormLabel>
- <FormControl>
- <Input type="password" placeholder="留空则不修改密码" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={updateForm.control}
- name="isDisabled"
- render={({ field }) => (
- <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
- <div className="space-y-0.5">
- <FormLabel className="text-base">用户状态</FormLabel>
- <FormDescription>
- 禁用后用户将无法登录系统
- </FormDescription>
- </div>
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- </FormItem>
- )}
- />
- <DialogFooter>
- <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
- 取消
- </Button>
- <Button type="submit">
- 更新用户
- </Button>
- </DialogFooter>
- </form>
- </Form>
- )}
- </DialogContent>
- </Dialog>
- {/* 删除确认对话框 */}
- <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>确认删除</DialogTitle>
- <DialogDescription>
- 确定要删除这个用户吗?此操作无法撤销。
- </DialogDescription>
- </DialogHeader>
- <DialogFooter>
- <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
- 取消
- </Button>
- <Button variant="destructive" onClick={confirmDelete}>
- 删除
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- </div>
- );
- };
|