Users.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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>用户名</FormLabel>
  347. <FormControl>
  348. <Input placeholder="请输入用户名" {...field} />
  349. </FormControl>
  350. <FormMessage />
  351. </FormItem>
  352. )}
  353. />
  354. <FormField
  355. control={createForm.control}
  356. name="nickname"
  357. render={({ field }) => (
  358. <FormItem>
  359. <FormLabel>昵称</FormLabel>
  360. <FormControl>
  361. <Input placeholder="请输入昵称" {...field} />
  362. </FormControl>
  363. <FormMessage />
  364. </FormItem>
  365. )}
  366. />
  367. <FormField
  368. control={createForm.control}
  369. name="email"
  370. render={({ field }) => (
  371. <FormItem>
  372. <FormLabel>邮箱</FormLabel>
  373. <FormControl>
  374. <Input type="email" placeholder="请输入邮箱" {...field} />
  375. </FormControl>
  376. <FormMessage />
  377. </FormItem>
  378. )}
  379. />
  380. <FormField
  381. control={createForm.control}
  382. name="phone"
  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="name"
  396. render={({ field }) => (
  397. <FormItem>
  398. <FormLabel>真实姓名</FormLabel>
  399. <FormControl>
  400. <Input placeholder="请输入真实姓名" {...field} />
  401. </FormControl>
  402. <FormMessage />
  403. </FormItem>
  404. )}
  405. />
  406. <FormField
  407. control={createForm.control}
  408. name="password"
  409. render={({ field }) => (
  410. <FormItem>
  411. <FormLabel>密码</FormLabel>
  412. <FormControl>
  413. <Input type="password" placeholder="请输入密码" {...field} />
  414. </FormControl>
  415. <FormMessage />
  416. </FormItem>
  417. )}
  418. />
  419. <FormField
  420. control={createForm.control}
  421. name="isDisabled"
  422. render={({ field }) => (
  423. <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
  424. <div className="space-y-0.5">
  425. <FormLabel className="text-base">用户状态</FormLabel>
  426. <FormDescription>
  427. 禁用后用户将无法登录系统
  428. </FormDescription>
  429. </div>
  430. <FormControl>
  431. <Switch
  432. checked={field.value === 1}
  433. onCheckedChange={(checked) => field.onChange(checked ? 1 : 0)}
  434. />
  435. </FormControl>
  436. </FormItem>
  437. )}
  438. />
  439. <DialogFooter>
  440. <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
  441. 取消
  442. </Button>
  443. <Button type="submit">
  444. 创建用户
  445. </Button>
  446. </DialogFooter>
  447. </form>
  448. </Form>
  449. ) : (
  450. <Form {...updateForm}>
  451. <form onSubmit={updateForm.handleSubmit(handleUpdateSubmit)} className="space-y-4">
  452. <FormField
  453. control={updateForm.control}
  454. name="username"
  455. render={({ field }) => (
  456. <FormItem>
  457. <FormLabel>用户名</FormLabel>
  458. <FormControl>
  459. <Input placeholder="请输入用户名" {...field} />
  460. </FormControl>
  461. <FormMessage />
  462. </FormItem>
  463. )}
  464. />
  465. <FormField
  466. control={updateForm.control}
  467. name="nickname"
  468. render={({ field }) => (
  469. <FormItem>
  470. <FormLabel>昵称</FormLabel>
  471. <FormControl>
  472. <Input placeholder="请输入昵称" {...field} />
  473. </FormControl>
  474. <FormMessage />
  475. </FormItem>
  476. )}
  477. />
  478. <FormField
  479. control={updateForm.control}
  480. name="email"
  481. render={({ field }) => (
  482. <FormItem>
  483. <FormLabel>邮箱</FormLabel>
  484. <FormControl>
  485. <Input type="email" placeholder="请输入邮箱" {...field} />
  486. </FormControl>
  487. <FormMessage />
  488. </FormItem>
  489. )}
  490. />
  491. <FormField
  492. control={updateForm.control}
  493. name="phone"
  494. render={({ field }) => (
  495. <FormItem>
  496. <FormLabel>手机号</FormLabel>
  497. <FormControl>
  498. <Input placeholder="请输入手机号" {...field} />
  499. </FormControl>
  500. <FormMessage />
  501. </FormItem>
  502. )}
  503. />
  504. <FormField
  505. control={updateForm.control}
  506. name="name"
  507. render={({ field }) => (
  508. <FormItem>
  509. <FormLabel>真实姓名</FormLabel>
  510. <FormControl>
  511. <Input placeholder="请输入真实姓名" {...field} />
  512. </FormControl>
  513. <FormMessage />
  514. </FormItem>
  515. )}
  516. />
  517. <FormField
  518. control={updateForm.control}
  519. name="password"
  520. render={({ field }) => (
  521. <FormItem>
  522. <FormLabel>新密码</FormLabel>
  523. <FormControl>
  524. <Input type="password" placeholder="留空则不修改密码" {...field} />
  525. </FormControl>
  526. <FormMessage />
  527. </FormItem>
  528. )}
  529. />
  530. <FormField
  531. control={updateForm.control}
  532. name="isDisabled"
  533. render={({ field }) => (
  534. <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
  535. <div className="space-y-0.5">
  536. <FormLabel className="text-base">用户状态</FormLabel>
  537. <FormDescription>
  538. 禁用后用户将无法登录系统
  539. </FormDescription>
  540. </div>
  541. <FormControl>
  542. <Switch
  543. checked={field.value === 1}
  544. onCheckedChange={(checked) => field.onChange(checked ? 1 : 0)}
  545. />
  546. </FormControl>
  547. </FormItem>
  548. )}
  549. />
  550. <DialogFooter>
  551. <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
  552. 取消
  553. </Button>
  554. <Button type="submit">
  555. 更新用户
  556. </Button>
  557. </DialogFooter>
  558. </form>
  559. </Form>
  560. )}
  561. </DialogContent>
  562. </Dialog>
  563. {/* 删除确认对话框 */}
  564. <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
  565. <DialogContent>
  566. <DialogHeader>
  567. <DialogTitle>确认删除</DialogTitle>
  568. <DialogDescription>
  569. 确定要删除这个用户吗?此操作无法撤销。
  570. </DialogDescription>
  571. </DialogHeader>
  572. <DialogFooter>
  573. <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
  574. 取消
  575. </Button>
  576. <Button variant="destructive" onClick={confirmDelete}>
  577. 删除
  578. </Button>
  579. </DialogFooter>
  580. </DialogContent>
  581. </Dialog>
  582. </div>
  583. );
  584. };