Users.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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 AvatarSelector from '@/client/admin-shadcn/components/AvatarSelector';
  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. // Avatar selector is now integrated, no separate state needed
  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>创建时间</TableHead>
  255. <TableHead className="text-right">操作</TableHead>
  256. </TableRow>
  257. </TableHeader>
  258. <TableBody>
  259. {users.map((user) => (
  260. <TableRow key={user.id}>
  261. <TableCell>
  262. <div className="w-10 h-10">
  263. {user.avatarFile?.fullUrl ? (
  264. <img
  265. src={user.avatarFile.fullUrl}
  266. alt={user.username}
  267. className="w-10 h-10 rounded-full object-cover"
  268. />
  269. ) : (
  270. <div className="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center">
  271. <span className="text-sm font-medium text-gray-500">
  272. {user.username?.charAt(0)?.toUpperCase() || 'U'}
  273. </span>
  274. </div>
  275. )}
  276. </div>
  277. </TableCell>
  278. <TableCell className="font-medium">{user.username}</TableCell>
  279. <TableCell>{user.nickname || '-'}</TableCell>
  280. <TableCell>{user.email || '-'}</TableCell>
  281. <TableCell>{user.name || '-'}</TableCell>
  282. <TableCell>
  283. <Badge
  284. variant={user.roles?.some((role: any) => role.name === 'admin') ? 'destructive' : 'default'}
  285. className="capitalize"
  286. >
  287. {user.roles?.some((role: any) => role.name === 'admin') ? '管理员' : '普通用户'}
  288. </Badge>
  289. </TableCell>
  290. <TableCell>
  291. <Badge
  292. variant={user.isDisabled === 1 ? 'secondary' : 'default'}
  293. >
  294. {user.isDisabled === 1 ? '禁用' : '启用'}
  295. </Badge>
  296. </TableCell>
  297. <TableCell>
  298. {format(new Date(user.createdAt), 'yyyy-MM-dd HH:mm')}
  299. </TableCell>
  300. <TableCell className="text-right">
  301. <div className="flex justify-end gap-2">
  302. <Button
  303. variant="ghost"
  304. size="icon"
  305. onClick={() => handleEditUser(user)}
  306. >
  307. <Edit className="h-4 w-4" />
  308. </Button>
  309. <Button
  310. variant="ghost"
  311. size="icon"
  312. onClick={() => handleDeleteUser(user.id)}
  313. >
  314. <Trash2 className="h-4 w-4" />
  315. </Button>
  316. </div>
  317. </TableCell>
  318. </TableRow>
  319. ))}
  320. </TableBody>
  321. </Table>
  322. </div>
  323. <DataTablePagination
  324. currentPage={searchParams.page}
  325. totalCount={totalCount}
  326. pageSize={searchParams.limit}
  327. onPageChange={handlePageChange}
  328. />
  329. </CardContent>
  330. </Card>
  331. {/* 创建/编辑用户对话框 */}
  332. <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
  333. <DialogContent className="sm:max-w-[500px]">
  334. <DialogHeader>
  335. <DialogTitle>
  336. {editingUser ? '编辑用户' : '创建用户'}
  337. </DialogTitle>
  338. <DialogDescription>
  339. {editingUser ? '编辑现有用户信息' : '创建一个新的用户账户'}
  340. </DialogDescription>
  341. </DialogHeader>
  342. {isCreateForm ? (
  343. <Form {...createForm}>
  344. <form onSubmit={createForm.handleSubmit(handleCreateSubmit)} className="space-y-4">
  345. <FormField
  346. control={createForm.control}
  347. name="username"
  348. render={({ field }) => (
  349. <FormItem>
  350. <FormLabel className="flex items-center">
  351. 用户名
  352. <span className="text-red-500 ml-1">*</span>
  353. </FormLabel>
  354. <FormControl>
  355. <Input placeholder="请输入用户名" {...field} />
  356. </FormControl>
  357. <FormMessage />
  358. </FormItem>
  359. )}
  360. />
  361. <FormField
  362. control={createForm.control}
  363. name="nickname"
  364. render={({ field }) => (
  365. <FormItem>
  366. <FormLabel>昵称</FormLabel>
  367. <FormControl>
  368. <Input placeholder="请输入昵称" {...field} />
  369. </FormControl>
  370. <FormMessage />
  371. </FormItem>
  372. )}
  373. />
  374. <FormField
  375. control={createForm.control}
  376. name="email"
  377. render={({ field }) => (
  378. <FormItem>
  379. <FormLabel>邮箱</FormLabel>
  380. <FormControl>
  381. <Input type="email" placeholder="请输入邮箱" {...field} />
  382. </FormControl>
  383. <FormMessage />
  384. </FormItem>
  385. )}
  386. />
  387. <FormField
  388. control={createForm.control}
  389. name="phone"
  390. render={({ field }) => (
  391. <FormItem>
  392. <FormLabel>手机号</FormLabel>
  393. <FormControl>
  394. <Input placeholder="请输入手机号" {...field} />
  395. </FormControl>
  396. <FormMessage />
  397. </FormItem>
  398. )}
  399. />
  400. <FormField
  401. control={createForm.control}
  402. name="name"
  403. render={({ field }) => (
  404. <FormItem>
  405. <FormLabel>真实姓名</FormLabel>
  406. <FormControl>
  407. <Input placeholder="请输入真实姓名" {...field} />
  408. </FormControl>
  409. <FormMessage />
  410. </FormItem>
  411. )}
  412. />
  413. <FormField
  414. control={createForm.control}
  415. name="password"
  416. render={({ field }) => (
  417. <FormItem>
  418. <FormLabel className="flex items-center">
  419. 密码
  420. <span className="text-red-500 ml-1">*</span>
  421. </FormLabel>
  422. <FormControl>
  423. <Input type="password" placeholder="请输入密码" {...field} />
  424. </FormControl>
  425. <FormMessage />
  426. </FormItem>
  427. )}
  428. />
  429. <FormField
  430. control={createForm.control}
  431. name="avatarFileId"
  432. render={({ field }) => (
  433. <FormItem>
  434. <FormLabel>头像</FormLabel>
  435. <FormControl>
  436. <AvatarSelector
  437. value={field.value || undefined}
  438. onChange={(value) => field.onChange(value)}
  439. maxSize={2}
  440. uploadPath="/avatars"
  441. uploadButtonText="上传头像"
  442. previewSize="medium"
  443. placeholder="选择头像"
  444. />
  445. </FormControl>
  446. <FormMessage />
  447. </FormItem>
  448. )}
  449. />
  450. <FormField
  451. control={createForm.control}
  452. name="isDisabled"
  453. render={({ field }) => (
  454. <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
  455. <div className="space-y-0.5">
  456. <FormLabel className="text-base">用户状态</FormLabel>
  457. <FormDescription>
  458. 禁用后用户将无法登录系统
  459. </FormDescription>
  460. </div>
  461. <FormControl>
  462. <Switch
  463. checked={field.value === 1}
  464. onCheckedChange={(checked) => field.onChange(checked ? 1 : 0)}
  465. />
  466. </FormControl>
  467. </FormItem>
  468. )}
  469. />
  470. <DialogFooter>
  471. <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
  472. 取消
  473. </Button>
  474. <Button type="submit">
  475. 创建用户
  476. </Button>
  477. </DialogFooter>
  478. </form>
  479. </Form>
  480. ) : (
  481. <Form {...updateForm}>
  482. <form onSubmit={updateForm.handleSubmit(handleUpdateSubmit)} className="space-y-4">
  483. <FormField
  484. control={updateForm.control}
  485. name="username"
  486. render={({ field }) => (
  487. <FormItem>
  488. <FormLabel className="flex items-center">
  489. 用户名
  490. <span className="text-red-500 ml-1">*</span>
  491. </FormLabel>
  492. <FormControl>
  493. <Input placeholder="请输入用户名" {...field} />
  494. </FormControl>
  495. <FormMessage />
  496. </FormItem>
  497. )}
  498. />
  499. <FormField
  500. control={updateForm.control}
  501. name="nickname"
  502. render={({ field }) => (
  503. <FormItem>
  504. <FormLabel>昵称</FormLabel>
  505. <FormControl>
  506. <Input placeholder="请输入昵称" {...field} />
  507. </FormControl>
  508. <FormMessage />
  509. </FormItem>
  510. )}
  511. />
  512. <FormField
  513. control={updateForm.control}
  514. name="email"
  515. render={({ field }) => (
  516. <FormItem>
  517. <FormLabel>邮箱</FormLabel>
  518. <FormControl>
  519. <Input type="email" placeholder="请输入邮箱" {...field} />
  520. </FormControl>
  521. <FormMessage />
  522. </FormItem>
  523. )}
  524. />
  525. <FormField
  526. control={updateForm.control}
  527. name="phone"
  528. render={({ field }) => (
  529. <FormItem>
  530. <FormLabel>手机号</FormLabel>
  531. <FormControl>
  532. <Input placeholder="请输入手机号" {...field} />
  533. </FormControl>
  534. <FormMessage />
  535. </FormItem>
  536. )}
  537. />
  538. <FormField
  539. control={updateForm.control}
  540. name="name"
  541. render={({ field }) => (
  542. <FormItem>
  543. <FormLabel>真实姓名</FormLabel>
  544. <FormControl>
  545. <Input placeholder="请输入真实姓名" {...field} />
  546. </FormControl>
  547. <FormMessage />
  548. </FormItem>
  549. )}
  550. />
  551. <FormField
  552. control={updateForm.control}
  553. name="password"
  554. render={({ field }) => (
  555. <FormItem>
  556. <FormLabel>新密码</FormLabel>
  557. <FormControl>
  558. <Input type="password" placeholder="留空则不修改密码" {...field} />
  559. </FormControl>
  560. <FormMessage />
  561. </FormItem>
  562. )}
  563. />
  564. <FormField
  565. control={updateForm.control}
  566. name="avatarFileId"
  567. render={({ field }) => (
  568. <FormItem>
  569. <FormLabel>头像</FormLabel>
  570. <FormControl>
  571. <AvatarSelector
  572. value={field.value || undefined}
  573. onChange={(value) => field.onChange(value)}
  574. maxSize={2}
  575. uploadPath="/avatars"
  576. uploadButtonText="上传头像"
  577. previewSize="medium"
  578. placeholder="选择头像"
  579. />
  580. </FormControl>
  581. <FormMessage />
  582. </FormItem>
  583. )}
  584. />
  585. <FormField
  586. control={updateForm.control}
  587. name="isDisabled"
  588. render={({ field }) => (
  589. <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
  590. <div className="space-y-0.5">
  591. <FormLabel className="text-base">用户状态</FormLabel>
  592. <FormDescription>
  593. 禁用后用户将无法登录系统
  594. </FormDescription>
  595. </div>
  596. <FormControl>
  597. <Switch
  598. checked={field.value === 1}
  599. onCheckedChange={(checked) => field.onChange(checked ? 1 : 0)}
  600. />
  601. </FormControl>
  602. </FormItem>
  603. )}
  604. />
  605. <DialogFooter>
  606. <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
  607. 取消
  608. </Button>
  609. <Button type="submit">
  610. 更新用户
  611. </Button>
  612. </DialogFooter>
  613. </form>
  614. </Form>
  615. )}
  616. </DialogContent>
  617. </Dialog>
  618. {/* Avatar selector is now integrated within the form */}
  619. {/* 删除确认对话框 */}
  620. <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
  621. <DialogContent>
  622. <DialogHeader>
  623. <DialogTitle>确认删除</DialogTitle>
  624. <DialogDescription>
  625. 确定要删除这个用户吗?此操作无法撤销。
  626. </DialogDescription>
  627. </DialogHeader>
  628. <DialogFooter>
  629. <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
  630. 取消
  631. </Button>
  632. <Button variant="destructive" onClick={confirmDelete}>
  633. 删除
  634. </Button>
  635. </DialogFooter>
  636. </DialogContent>
  637. </Dialog>
  638. </div>
  639. );
  640. };