Users.tsx 23 KB

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