Users.tsx 22 KB

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