Users.tsx 23 KB

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