Users.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  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. 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. <div className="flex justify-between items-center mt-4">
  304. <div className="text-sm text-muted-foreground">
  305. 第 {searchParams.page} 页,共 {Math.ceil(totalCount / searchParams.limit)} 页
  306. </div>
  307. <div className="flex gap-2">
  308. <Button
  309. variant="outline"
  310. size="sm"
  311. disabled={searchParams.page <= 1}
  312. onClick={() => handlePageChange(searchParams.page - 1, searchParams.limit)}
  313. >
  314. 上一页
  315. </Button>
  316. <Button
  317. variant="outline"
  318. size="sm"
  319. disabled={searchParams.page >= Math.ceil(totalCount / searchParams.limit)}
  320. onClick={() => handlePageChange(searchParams.page + 1, searchParams.limit)}
  321. >
  322. 下一页
  323. </Button>
  324. </div>
  325. </div>
  326. </CardContent>
  327. </Card>
  328. {/* 创建/编辑用户对话框 */}
  329. <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
  330. <DialogContent className="sm:max-w-[500px]">
  331. <DialogHeader>
  332. <DialogTitle>
  333. {editingUser ? '编辑用户' : '创建用户'}
  334. </DialogTitle>
  335. <DialogDescription>
  336. {editingUser ? '编辑现有用户信息' : '创建一个新的用户账户'}
  337. </DialogDescription>
  338. </DialogHeader>
  339. {isCreateForm ? (
  340. <Form {...createForm}>
  341. <form onSubmit={createForm.handleSubmit(handleCreateSubmit)} className="space-y-4">
  342. <FormField
  343. control={createForm.control}
  344. name="username"
  345. render={({ field }) => (
  346. <FormItem>
  347. <FormLabel>用户名</FormLabel>
  348. <FormControl>
  349. <Input placeholder="请输入用户名" {...field} />
  350. </FormControl>
  351. <FormMessage />
  352. </FormItem>
  353. )}
  354. />
  355. <FormField
  356. control={createForm.control}
  357. name="nickname"
  358. render={({ field }) => (
  359. <FormItem>
  360. <FormLabel>昵称</FormLabel>
  361. <FormControl>
  362. <Input placeholder="请输入昵称" {...field} value={field.value || ''} />
  363. </FormControl>
  364. <FormMessage />
  365. </FormItem>
  366. )}
  367. />
  368. <FormField
  369. control={createForm.control}
  370. name="email"
  371. render={({ field }) => (
  372. <FormItem>
  373. <FormLabel>邮箱</FormLabel>
  374. <FormControl>
  375. <Input type="email" placeholder="请输入邮箱" {...field} value={field.value || ''} />
  376. </FormControl>
  377. <FormMessage />
  378. </FormItem>
  379. )}
  380. />
  381. <FormField
  382. control={createForm.control}
  383. name="phone"
  384. render={({ field }) => (
  385. <FormItem>
  386. <FormLabel>手机号</FormLabel>
  387. <FormControl>
  388. <Input placeholder="请输入手机号" {...field} value={field.value || ''} />
  389. </FormControl>
  390. <FormMessage />
  391. </FormItem>
  392. )}
  393. />
  394. <FormField
  395. control={createForm.control}
  396. name="name"
  397. render={({ field }) => (
  398. <FormItem>
  399. <FormLabel>真实姓名</FormLabel>
  400. <FormControl>
  401. <Input placeholder="请输入真实姓名" {...field} value={field.value || ''} />
  402. </FormControl>
  403. <FormMessage />
  404. </FormItem>
  405. )}
  406. />
  407. <FormField
  408. control={createForm.control}
  409. name="password"
  410. render={({ field }) => (
  411. <FormItem>
  412. <FormLabel>密码</FormLabel>
  413. <FormControl>
  414. <Input type="password" placeholder="请输入密码" {...field} />
  415. </FormControl>
  416. <FormMessage />
  417. </FormItem>
  418. )}
  419. />
  420. <FormField
  421. control={createForm.control}
  422. name="isDisabled"
  423. render={({ field }) => (
  424. <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
  425. <div className="space-y-0.5">
  426. <FormLabel className="text-base">用户状态</FormLabel>
  427. <FormDescription>
  428. 禁用后用户将无法登录系统
  429. </FormDescription>
  430. </div>
  431. <FormControl>
  432. <Switch
  433. checked={field.value === 1}
  434. onCheckedChange={(checked) => field.onChange(checked ? 1 : 0)}
  435. />
  436. </FormControl>
  437. </FormItem>
  438. )}
  439. />
  440. <DialogFooter>
  441. <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
  442. 取消
  443. </Button>
  444. <Button type="submit">
  445. 创建用户
  446. </Button>
  447. </DialogFooter>
  448. </form>
  449. </Form>
  450. ) : (
  451. <Form {...updateForm}>
  452. <form onSubmit={updateForm.handleSubmit(handleUpdateSubmit)} className="space-y-4">
  453. <FormField
  454. control={updateForm.control}
  455. name="username"
  456. render={({ field }) => (
  457. <FormItem>
  458. <FormLabel>用户名</FormLabel>
  459. <FormControl>
  460. <Input placeholder="请输入用户名" {...field} value={field.value || ''} />
  461. </FormControl>
  462. <FormMessage />
  463. </FormItem>
  464. )}
  465. />
  466. <FormField
  467. control={updateForm.control}
  468. name="nickname"
  469. render={({ field }) => (
  470. <FormItem>
  471. <FormLabel>昵称</FormLabel>
  472. <FormControl>
  473. <Input placeholder="请输入昵称" {...field} value={field.value || ''} />
  474. </FormControl>
  475. <FormMessage />
  476. </FormItem>
  477. )}
  478. />
  479. <FormField
  480. control={updateForm.control}
  481. name="email"
  482. render={({ field }) => (
  483. <FormItem>
  484. <FormLabel>邮箱</FormLabel>
  485. <FormControl>
  486. <Input type="email" placeholder="请输入邮箱" {...field} value={field.value || ''} />
  487. </FormControl>
  488. <FormMessage />
  489. </FormItem>
  490. )}
  491. />
  492. <FormField
  493. control={updateForm.control}
  494. name="phone"
  495. render={({ field }) => (
  496. <FormItem>
  497. <FormLabel>手机号</FormLabel>
  498. <FormControl>
  499. <Input placeholder="请输入手机号" {...field} value={field.value || ''} />
  500. </FormControl>
  501. <FormMessage />
  502. </FormItem>
  503. )}
  504. />
  505. <FormField
  506. control={updateForm.control}
  507. name="name"
  508. render={({ field }) => (
  509. <FormItem>
  510. <FormLabel>真实姓名</FormLabel>
  511. <FormControl>
  512. <Input placeholder="请输入真实姓名" {...field} value={field.value || ''} />
  513. </FormControl>
  514. <FormMessage />
  515. </FormItem>
  516. )}
  517. />
  518. <FormField
  519. control={updateForm.control}
  520. name="password"
  521. render={({ field }) => (
  522. <FormItem>
  523. <FormLabel>新密码</FormLabel>
  524. <FormControl>
  525. <Input type="password" placeholder="留空则不修改密码" {...field} />
  526. </FormControl>
  527. <FormMessage />
  528. </FormItem>
  529. )}
  530. />
  531. <FormField
  532. control={updateForm.control}
  533. name="isDisabled"
  534. render={({ field }) => (
  535. <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
  536. <div className="space-y-0.5">
  537. <FormLabel className="text-base">用户状态</FormLabel>
  538. <FormDescription>
  539. 禁用后用户将无法登录系统
  540. </FormDescription>
  541. </div>
  542. <FormControl>
  543. <Switch
  544. checked={field.value === 1}
  545. onCheckedChange={(checked) => field.onChange(checked ? 1 : 0)}
  546. />
  547. </FormControl>
  548. </FormItem>
  549. )}
  550. />
  551. <DialogFooter>
  552. <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
  553. 取消
  554. </Button>
  555. <Button type="submit">
  556. 更新用户
  557. </Button>
  558. </DialogFooter>
  559. </form>
  560. </Form>
  561. )}
  562. </DialogContent>
  563. </Dialog>
  564. {/* 删除确认对话框 */}
  565. <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
  566. <DialogContent>
  567. <DialogHeader>
  568. <DialogTitle>确认删除</DialogTitle>
  569. <DialogDescription>
  570. 确定要删除这个用户吗?此操作无法撤销。
  571. </DialogDescription>
  572. </DialogHeader>
  573. <DialogFooter>
  574. <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
  575. 取消
  576. </Button>
  577. <Button variant="destructive" onClick={confirmDelete}>
  578. 删除
  579. </Button>
  580. </DialogFooter>
  581. </DialogContent>
  582. </Dialog>
  583. </div>
  584. );
  585. };