Users.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. import React, { useState } from 'react';
  2. import { useQuery } from '@tanstack/react-query';
  3. import { format } from 'date-fns';
  4. import { Plus, Search, Edit, Trash2 } from 'lucide-react';
  5. import { userClient } from '@/client/api';
  6. import type { InferRequestType, InferResponseType } from 'hono/client';
  7. import { Button } from '@/client/components/ui/button';
  8. import { Input } from '@/client/components/ui/input';
  9. import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/client/components/ui/card';
  10. import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/client/components/ui/table';
  11. import { Badge } from '@/client/components/ui/badge';
  12. import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/client/components/ui/dialog';
  13. import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/client/components/ui/form';
  14. import { DataTablePagination } from '@/client/admin-shadcn/components/DataTablePagination';
  15. import { useForm } from 'react-hook-form';
  16. import { zodResolver } from '@hookform/resolvers/zod';
  17. import { toast } from 'sonner';
  18. import { Skeleton } from '@/client/components/ui/skeleton';
  19. import { Switch } from '@/client/components/ui/switch';
  20. import { DisabledStatus } from '@/share/types';
  21. import { CreateUserDto, UpdateUserDto } from '@/server/modules/users/user.schema';
  22. // 使用RPC方式提取类型
  23. type CreateUserRequest = InferRequestType<typeof userClient.$post>['json'];
  24. type UpdateUserRequest = InferRequestType<typeof userClient[':id']['$put']>['json'];
  25. type UserResponse = InferResponseType<typeof userClient.$get, 200>['data'][0];
  26. // 直接使用后端定义的 schema
  27. const createUserFormSchema = CreateUserDto;
  28. const updateUserFormSchema = UpdateUserDto;
  29. type CreateUserFormData = CreateUserRequest;
  30. type UpdateUserFormData = UpdateUserRequest;
  31. export const UsersPage = () => {
  32. const [searchParams, setSearchParams] = useState({
  33. page: 1,
  34. limit: 10,
  35. search: ''
  36. });
  37. const [isModalOpen, setIsModalOpen] = useState(false);
  38. const [editingUser, setEditingUser] = useState<any>(null);
  39. const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  40. const [userToDelete, setUserToDelete] = useState<number | null>(null);
  41. const [isCreateForm, setIsCreateForm] = useState(true);
  42. const createForm = useForm<CreateUserFormData>({
  43. resolver: zodResolver(createUserFormSchema),
  44. defaultValues: {
  45. username: '',
  46. nickname: undefined,
  47. email: null,
  48. phone: null,
  49. name: null,
  50. password: '',
  51. isDisabled: DisabledStatus.ENABLED,
  52. },
  53. });
  54. const updateForm = useForm<UpdateUserFormData>({
  55. resolver: zodResolver(updateUserFormSchema),
  56. defaultValues: {
  57. username: undefined,
  58. nickname: undefined,
  59. email: null,
  60. phone: null,
  61. name: null,
  62. password: undefined,
  63. isDisabled: undefined,
  64. },
  65. });
  66. const { data: usersData, isLoading, refetch } = useQuery({
  67. queryKey: ['users', searchParams],
  68. queryFn: async () => {
  69. const res = await userClient.$get({
  70. query: {
  71. page: searchParams.page,
  72. pageSize: searchParams.limit,
  73. keyword: searchParams.search
  74. }
  75. });
  76. if (res.status !== 200) {
  77. throw new Error('获取用户列表失败');
  78. }
  79. return await res.json();
  80. }
  81. });
  82. const users = usersData?.data || [];
  83. const totalCount = usersData?.pagination?.total || 0;
  84. // 处理搜索
  85. const handleSearch = (e: React.FormEvent) => {
  86. e.preventDefault();
  87. setSearchParams(prev => ({ ...prev, page: 1 }));
  88. };
  89. // 处理分页
  90. const handlePageChange = (page: number, limit: number) => {
  91. setSearchParams(prev => ({ ...prev, page, limit }));
  92. };
  93. // 打开创建用户对话框
  94. const handleCreateUser = () => {
  95. setEditingUser(null);
  96. setIsCreateForm(true);
  97. createForm.reset({
  98. username: '',
  99. nickname: null,
  100. email: null,
  101. phone: null,
  102. name: null,
  103. password: '',
  104. isDisabled: DisabledStatus.ENABLED,
  105. });
  106. setIsModalOpen(true);
  107. };
  108. // 打开编辑用户对话框
  109. const handleEditUser = (user: UserResponse) => {
  110. setEditingUser(user);
  111. setIsCreateForm(false);
  112. updateForm.reset({
  113. username: user.username,
  114. nickname: user.nickname,
  115. email: user.email,
  116. phone: user.phone,
  117. name: user.name,
  118. isDisabled: user.isDisabled,
  119. });
  120. setIsModalOpen(true);
  121. };
  122. // 处理创建表单提交
  123. const handleCreateSubmit = async (data: CreateUserFormData) => {
  124. try {
  125. const res = await userClient.$post({
  126. json: data
  127. });
  128. if (res.status !== 201) {
  129. throw new Error('创建用户失败');
  130. }
  131. toast.success('用户创建成功');
  132. setIsModalOpen(false);
  133. refetch();
  134. } catch (error) {
  135. console.error('创建用户失败:', error);
  136. toast.error('创建失败,请重试');
  137. }
  138. };
  139. // 处理更新表单提交
  140. const handleUpdateSubmit = async (data: UpdateUserFormData) => {
  141. if (!editingUser) return;
  142. try {
  143. const res = await userClient[':id']['$put']({
  144. param: { id: editingUser.id },
  145. json: data
  146. });
  147. if (res.status !== 200) {
  148. throw new Error('更新用户失败');
  149. }
  150. toast.success('用户更新成功');
  151. setIsModalOpen(false);
  152. refetch();
  153. } catch (error) {
  154. console.error('更新用户失败:', error);
  155. toast.error('更新失败,请重试');
  156. }
  157. };
  158. // 处理删除用户
  159. const handleDeleteUser = (id: number) => {
  160. setUserToDelete(id);
  161. setDeleteDialogOpen(true);
  162. };
  163. const confirmDelete = async () => {
  164. if (!userToDelete) return;
  165. try {
  166. const res = await userClient[':id']['$delete']({
  167. param: { id: userToDelete }
  168. });
  169. if (res.status !== 204) {
  170. throw new Error('删除用户失败');
  171. }
  172. toast.success('用户删除成功');
  173. refetch();
  174. } catch (error) {
  175. console.error('删除用户失败:', error);
  176. toast.error('删除失败,请重试');
  177. } finally {
  178. setDeleteDialogOpen(false);
  179. setUserToDelete(null);
  180. }
  181. };
  182. // 渲染加载骨架
  183. if (isLoading) {
  184. return (
  185. <div className="space-y-4">
  186. <div className="flex justify-between items-center">
  187. <h1 className="text-2xl font-bold">用户管理</h1>
  188. <Button disabled>
  189. <Plus className="mr-2 h-4 w-4" />
  190. 创建用户
  191. </Button>
  192. </div>
  193. <Card>
  194. <CardHeader>
  195. <Skeleton className="h-6 w-1/4" />
  196. </CardHeader>
  197. <CardContent>
  198. <div className="space-y-2">
  199. <Skeleton className="h-4 w-full" />
  200. <Skeleton className="h-4 w-full" />
  201. <Skeleton className="h-4 w-full" />
  202. </div>
  203. </CardContent>
  204. </Card>
  205. </div>
  206. );
  207. }
  208. return (
  209. <div className="space-y-4">
  210. <div className="flex justify-between items-center">
  211. <h1 className="text-2xl font-bold">用户管理</h1>
  212. <Button onClick={handleCreateUser}>
  213. <Plus className="mr-2 h-4 w-4" />
  214. 创建用户
  215. </Button>
  216. </div>
  217. <Card>
  218. <CardHeader>
  219. <CardTitle>用户列表</CardTitle>
  220. <CardDescription>
  221. 管理系统中的所有用户,共 {totalCount} 位用户
  222. </CardDescription>
  223. </CardHeader>
  224. <CardContent>
  225. <div className="mb-4">
  226. <form onSubmit={handleSearch} className="flex gap-2">
  227. <div className="relative flex-1 max-w-sm">
  228. <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
  229. <Input
  230. placeholder="搜索用户名、昵称或邮箱..."
  231. value={searchParams.search}
  232. onChange={(e) => setSearchParams(prev => ({ ...prev, search: e.target.value }))}
  233. className="pl-8"
  234. />
  235. </div>
  236. <Button type="submit" variant="outline">
  237. 搜索
  238. </Button>
  239. </form>
  240. </div>
  241. <div className="rounded-md border">
  242. <Table>
  243. <TableHeader>
  244. <TableRow>
  245. <TableHead>用户名</TableHead>
  246. <TableHead>昵称</TableHead>
  247. <TableHead>邮箱</TableHead>
  248. <TableHead>真实姓名</TableHead>
  249. <TableHead>角色</TableHead>
  250. <TableHead>状态</TableHead>
  251. <TableHead>创建时间</TableHead>
  252. <TableHead className="text-right">操作</TableHead>
  253. </TableRow>
  254. </TableHeader>
  255. <TableBody>
  256. {users.map((user) => (
  257. <TableRow key={user.id}>
  258. <TableCell className="font-medium">{user.username}</TableCell>
  259. <TableCell>{user.nickname || '-'}</TableCell>
  260. <TableCell>{user.email || '-'}</TableCell>
  261. <TableCell>{user.name || '-'}</TableCell>
  262. <TableCell>
  263. <Badge
  264. variant={user.roles?.some((role: any) => role.name === 'admin') ? 'destructive' : 'default'}
  265. className="capitalize"
  266. >
  267. {user.roles?.some((role: any) => role.name === 'admin') ? '管理员' : '普通用户'}
  268. </Badge>
  269. </TableCell>
  270. <TableCell>
  271. <Badge
  272. variant={user.isDisabled === 1 ? 'secondary' : 'default'}
  273. >
  274. {user.isDisabled === 1 ? '禁用' : '启用'}
  275. </Badge>
  276. </TableCell>
  277. <TableCell>
  278. {format(new Date(user.createdAt), 'yyyy-MM-dd HH:mm')}
  279. </TableCell>
  280. <TableCell className="text-right">
  281. <div className="flex justify-end gap-2">
  282. <Button
  283. variant="ghost"
  284. size="icon"
  285. onClick={() => handleEditUser(user)}
  286. >
  287. <Edit className="h-4 w-4" />
  288. </Button>
  289. <Button
  290. variant="ghost"
  291. size="icon"
  292. onClick={() => handleDeleteUser(user.id)}
  293. >
  294. <Trash2 className="h-4 w-4" />
  295. </Button>
  296. </div>
  297. </TableCell>
  298. </TableRow>
  299. ))}
  300. </TableBody>
  301. </Table>
  302. </div>
  303. <DataTablePagination
  304. currentPage={searchParams.page}
  305. totalCount={totalCount}
  306. pageSize={searchParams.limit}
  307. onPageChange={handlePageChange}
  308. />
  309. </CardContent>
  310. </Card>
  311. {/* 创建/编辑用户对话框 */}
  312. <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
  313. <DialogContent className="sm:max-w-[500px]">
  314. <DialogHeader>
  315. <DialogTitle>
  316. {editingUser ? '编辑用户' : '创建用户'}
  317. </DialogTitle>
  318. <DialogDescription>
  319. {editingUser ? '编辑现有用户信息' : '创建一个新的用户账户'}
  320. </DialogDescription>
  321. </DialogHeader>
  322. {isCreateForm ? (
  323. <Form {...createForm}>
  324. <form onSubmit={createForm.handleSubmit(handleCreateSubmit)} className="space-y-4">
  325. <FormField
  326. control={createForm.control}
  327. name="username"
  328. render={({ field }) => (
  329. <FormItem>
  330. <FormLabel className="flex items-center">
  331. 用户名
  332. <span className="text-red-500 ml-1">*</span>
  333. </FormLabel>
  334. <FormControl>
  335. <Input placeholder="请输入用户名" {...field} />
  336. </FormControl>
  337. <FormMessage />
  338. </FormItem>
  339. )}
  340. />
  341. <FormField
  342. control={createForm.control}
  343. name="nickname"
  344. render={({ field }) => (
  345. <FormItem>
  346. <FormLabel>昵称</FormLabel>
  347. <FormControl>
  348. <Input placeholder="请输入昵称" {...field} />
  349. </FormControl>
  350. <FormMessage />
  351. </FormItem>
  352. )}
  353. />
  354. <FormField
  355. control={createForm.control}
  356. name="email"
  357. render={({ field }) => (
  358. <FormItem>
  359. <FormLabel>邮箱</FormLabel>
  360. <FormControl>
  361. <Input type="email" placeholder="请输入邮箱" {...field} />
  362. </FormControl>
  363. <FormMessage />
  364. </FormItem>
  365. )}
  366. />
  367. <FormField
  368. control={createForm.control}
  369. name="phone"
  370. render={({ field }) => (
  371. <FormItem>
  372. <FormLabel>手机号</FormLabel>
  373. <FormControl>
  374. <Input placeholder="请输入手机号" {...field} />
  375. </FormControl>
  376. <FormMessage />
  377. </FormItem>
  378. )}
  379. />
  380. <FormField
  381. control={createForm.control}
  382. name="name"
  383. render={({ field }) => (
  384. <FormItem>
  385. <FormLabel>真实姓名</FormLabel>
  386. <FormControl>
  387. <Input placeholder="请输入真实姓名" {...field} />
  388. </FormControl>
  389. <FormMessage />
  390. </FormItem>
  391. )}
  392. />
  393. <FormField
  394. control={createForm.control}
  395. name="password"
  396. render={({ field }) => (
  397. <FormItem>
  398. <FormLabel className="flex items-center">
  399. 密码
  400. <span className="text-red-500 ml-1">*</span>
  401. </FormLabel>
  402. <FormControl>
  403. <Input type="password" placeholder="请输入密码" {...field} />
  404. </FormControl>
  405. <FormMessage />
  406. </FormItem>
  407. )}
  408. />
  409. <FormField
  410. control={createForm.control}
  411. name="isDisabled"
  412. render={({ field }) => (
  413. <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
  414. <div className="space-y-0.5">
  415. <FormLabel className="text-base">用户状态</FormLabel>
  416. <FormDescription>
  417. 禁用后用户将无法登录系统
  418. </FormDescription>
  419. </div>
  420. <FormControl>
  421. <Switch
  422. checked={field.value === 1}
  423. onCheckedChange={(checked) => field.onChange(checked ? 1 : 0)}
  424. />
  425. </FormControl>
  426. </FormItem>
  427. )}
  428. />
  429. <DialogFooter>
  430. <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
  431. 取消
  432. </Button>
  433. <Button type="submit">
  434. 创建用户
  435. </Button>
  436. </DialogFooter>
  437. </form>
  438. </Form>
  439. ) : (
  440. <Form {...updateForm}>
  441. <form onSubmit={updateForm.handleSubmit(handleUpdateSubmit)} className="space-y-4">
  442. <FormField
  443. control={updateForm.control}
  444. name="username"
  445. render={({ field }) => (
  446. <FormItem>
  447. <FormLabel className="flex items-center">
  448. 用户名
  449. <span className="text-red-500 ml-1">*</span>
  450. </FormLabel>
  451. <FormControl>
  452. <Input placeholder="请输入用户名" {...field} />
  453. </FormControl>
  454. <FormMessage />
  455. </FormItem>
  456. )}
  457. />
  458. <FormField
  459. control={updateForm.control}
  460. name="nickname"
  461. render={({ field }) => (
  462. <FormItem>
  463. <FormLabel>昵称</FormLabel>
  464. <FormControl>
  465. <Input placeholder="请输入昵称" {...field} />
  466. </FormControl>
  467. <FormMessage />
  468. </FormItem>
  469. )}
  470. />
  471. <FormField
  472. control={updateForm.control}
  473. name="email"
  474. render={({ field }) => (
  475. <FormItem>
  476. <FormLabel>邮箱</FormLabel>
  477. <FormControl>
  478. <Input type="email" placeholder="请输入邮箱" {...field} />
  479. </FormControl>
  480. <FormMessage />
  481. </FormItem>
  482. )}
  483. />
  484. <FormField
  485. control={updateForm.control}
  486. name="phone"
  487. render={({ field }) => (
  488. <FormItem>
  489. <FormLabel>手机号</FormLabel>
  490. <FormControl>
  491. <Input placeholder="请输入手机号" {...field} />
  492. </FormControl>
  493. <FormMessage />
  494. </FormItem>
  495. )}
  496. />
  497. <FormField
  498. control={updateForm.control}
  499. name="name"
  500. render={({ field }) => (
  501. <FormItem>
  502. <FormLabel>真实姓名</FormLabel>
  503. <FormControl>
  504. <Input placeholder="请输入真实姓名" {...field} />
  505. </FormControl>
  506. <FormMessage />
  507. </FormItem>
  508. )}
  509. />
  510. <FormField
  511. control={updateForm.control}
  512. name="password"
  513. render={({ field }) => (
  514. <FormItem>
  515. <FormLabel>新密码</FormLabel>
  516. <FormControl>
  517. <Input type="password" placeholder="留空则不修改密码" {...field} />
  518. </FormControl>
  519. <FormMessage />
  520. </FormItem>
  521. )}
  522. />
  523. <FormField
  524. control={updateForm.control}
  525. name="isDisabled"
  526. render={({ field }) => (
  527. <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
  528. <div className="space-y-0.5">
  529. <FormLabel className="text-base">用户状态</FormLabel>
  530. <FormDescription>
  531. 禁用后用户将无法登录系统
  532. </FormDescription>
  533. </div>
  534. <FormControl>
  535. <Switch
  536. checked={field.value === 1}
  537. onCheckedChange={(checked) => field.onChange(checked ? 1 : 0)}
  538. />
  539. </FormControl>
  540. </FormItem>
  541. )}
  542. />
  543. <DialogFooter>
  544. <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
  545. 取消
  546. </Button>
  547. <Button type="submit">
  548. 更新用户
  549. </Button>
  550. </DialogFooter>
  551. </form>
  552. </Form>
  553. )}
  554. </DialogContent>
  555. </Dialog>
  556. {/* 删除确认对话框 */}
  557. <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
  558. <DialogContent>
  559. <DialogHeader>
  560. <DialogTitle>确认删除</DialogTitle>
  561. <DialogDescription>
  562. 确定要删除这个用户吗?此操作无法撤销。
  563. </DialogDescription>
  564. </DialogHeader>
  565. <DialogFooter>
  566. <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
  567. 取消
  568. </Button>
  569. <Button variant="destructive" onClick={confirmDelete}>
  570. 删除
  571. </Button>
  572. </DialogFooter>
  573. </DialogContent>
  574. </Dialog>
  575. </div>
  576. );
  577. };