2
0

Users.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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. avatarFileId: user.avatarFileId,
  121. isDisabled: user.isDisabled,
  122. });
  123. setIsModalOpen(true);
  124. };
  125. // 处理创建表单提交
  126. const handleCreateSubmit = async (data: CreateUserFormData) => {
  127. try {
  128. const res = await userClient.$post({
  129. json: data
  130. });
  131. if (res.status !== 201) {
  132. throw new Error('创建用户失败');
  133. }
  134. toast.success('用户创建成功');
  135. setIsModalOpen(false);
  136. refetch();
  137. } catch (error) {
  138. console.error('创建用户失败:', error);
  139. toast.error('创建失败,请重试');
  140. }
  141. };
  142. // 处理更新表单提交
  143. const handleUpdateSubmit = async (data: UpdateUserFormData) => {
  144. if (!editingUser) return;
  145. try {
  146. const res = await userClient[':id']['$put']({
  147. param: { id: editingUser.id },
  148. json: data
  149. });
  150. if (res.status !== 200) {
  151. throw new Error('更新用户失败');
  152. }
  153. toast.success('用户更新成功');
  154. setIsModalOpen(false);
  155. refetch();
  156. } catch (error) {
  157. console.error('更新用户失败:', error);
  158. toast.error('更新失败,请重试');
  159. }
  160. };
  161. // 处理删除用户
  162. const handleDeleteUser = (id: number) => {
  163. setUserToDelete(id);
  164. setDeleteDialogOpen(true);
  165. };
  166. const confirmDelete = async () => {
  167. if (!userToDelete) return;
  168. try {
  169. const res = await userClient[':id']['$delete']({
  170. param: { id: userToDelete }
  171. });
  172. if (res.status !== 204) {
  173. throw new Error('删除用户失败');
  174. }
  175. toast.success('用户删除成功');
  176. refetch();
  177. } catch (error) {
  178. console.error('删除用户失败:', error);
  179. toast.error('删除失败,请重试');
  180. } finally {
  181. setDeleteDialogOpen(false);
  182. setUserToDelete(null);
  183. }
  184. };
  185. // 渲染加载骨架
  186. if (isLoading) {
  187. return (
  188. <div className="space-y-4">
  189. <div className="flex justify-between items-center">
  190. <h1 className="text-2xl font-bold">用户管理</h1>
  191. <Button disabled>
  192. <Plus className="mr-2 h-4 w-4" />
  193. 创建用户
  194. </Button>
  195. </div>
  196. <Card>
  197. <CardHeader>
  198. <Skeleton className="h-6 w-1/4" />
  199. </CardHeader>
  200. <CardContent>
  201. <div className="space-y-2">
  202. <Skeleton className="h-4 w-full" />
  203. <Skeleton className="h-4 w-full" />
  204. <Skeleton className="h-4 w-full" />
  205. </div>
  206. </CardContent>
  207. </Card>
  208. </div>
  209. );
  210. }
  211. return (
  212. <div className="space-y-4">
  213. <div className="flex justify-between items-center">
  214. <h1 className="text-2xl font-bold">用户管理</h1>
  215. <Button onClick={handleCreateUser}>
  216. <Plus className="mr-2 h-4 w-4" />
  217. 创建用户
  218. </Button>
  219. </div>
  220. <Card>
  221. <CardHeader>
  222. <CardTitle>用户列表</CardTitle>
  223. <CardDescription>
  224. 管理系统中的所有用户,共 {totalCount} 位用户
  225. </CardDescription>
  226. </CardHeader>
  227. <CardContent>
  228. <div className="mb-4">
  229. <form onSubmit={handleSearch} className="flex gap-2">
  230. <div className="relative flex-1 max-w-sm">
  231. <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
  232. <Input
  233. placeholder="搜索用户名、昵称或邮箱..."
  234. value={searchParams.search}
  235. onChange={(e) => setSearchParams(prev => ({ ...prev, search: e.target.value }))}
  236. className="pl-8"
  237. />
  238. </div>
  239. <Button type="submit" variant="outline">
  240. 搜索
  241. </Button>
  242. </form>
  243. </div>
  244. <div className="rounded-md border">
  245. <Table>
  246. <TableHeader>
  247. <TableRow>
  248. <TableHead>头像</TableHead>
  249. <TableHead>用户名</TableHead>
  250. <TableHead>昵称</TableHead>
  251. <TableHead>邮箱</TableHead>
  252. <TableHead>真实姓名</TableHead>
  253. <TableHead>角色</TableHead>
  254. <TableHead>状态</TableHead>
  255. <TableHead>创建时间</TableHead>
  256. <TableHead className="text-right">操作</TableHead>
  257. </TableRow>
  258. </TableHeader>
  259. <TableBody>
  260. {users.map((user) => (
  261. <TableRow key={user.id}>
  262. <TableCell>
  263. <div className="w-10 h-10">
  264. {user.avatarFile?.fullUrl ? (
  265. <img
  266. src={user.avatarFile.fullUrl}
  267. alt={user.username}
  268. className="w-10 h-10 rounded-full object-cover"
  269. />
  270. ) : (
  271. <div className="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center">
  272. <span className="text-sm font-medium text-gray-500">
  273. {user.username?.charAt(0)?.toUpperCase() || 'U'}
  274. </span>
  275. </div>
  276. )}
  277. </div>
  278. </TableCell>
  279. <TableCell className="font-medium">{user.username}</TableCell>
  280. <TableCell>{user.nickname || '-'}</TableCell>
  281. <TableCell>{user.email || '-'}</TableCell>
  282. <TableCell>{user.name || '-'}</TableCell>
  283. <TableCell>
  284. <Badge
  285. variant={user.roles?.some((role: any) => role.name === 'admin') ? 'destructive' : 'default'}
  286. className="capitalize"
  287. >
  288. {user.roles?.some((role: any) => role.name === 'admin') ? '管理员' : '普通用户'}
  289. </Badge>
  290. </TableCell>
  291. <TableCell>
  292. <Badge
  293. variant={user.isDisabled === 1 ? 'secondary' : 'default'}
  294. >
  295. {user.isDisabled === 1 ? '禁用' : '启用'}
  296. </Badge>
  297. </TableCell>
  298. <TableCell>
  299. {format(new Date(user.createdAt), 'yyyy-MM-dd HH:mm')}
  300. </TableCell>
  301. <TableCell className="text-right">
  302. <div className="flex justify-end gap-2">
  303. <Button
  304. variant="ghost"
  305. size="icon"
  306. onClick={() => handleEditUser(user)}
  307. >
  308. <Edit className="h-4 w-4" />
  309. </Button>
  310. <Button
  311. variant="ghost"
  312. size="icon"
  313. onClick={() => handleDeleteUser(user.id)}
  314. >
  315. <Trash2 className="h-4 w-4" />
  316. </Button>
  317. </div>
  318. </TableCell>
  319. </TableRow>
  320. ))}
  321. </TableBody>
  322. </Table>
  323. </div>
  324. <DataTablePagination
  325. currentPage={searchParams.page}
  326. totalCount={totalCount}
  327. pageSize={searchParams.limit}
  328. onPageChange={handlePageChange}
  329. />
  330. </CardContent>
  331. </Card>
  332. {/* 创建/编辑用户对话框 */}
  333. <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
  334. <DialogContent className="sm:max-w-[500px] max-h-[90vh] overflow-y-auto">
  335. <DialogHeader>
  336. <DialogTitle>
  337. {editingUser ? '编辑用户' : '创建用户'}
  338. </DialogTitle>
  339. <DialogDescription>
  340. {editingUser ? '编辑现有用户信息' : '创建一个新的用户账户'}
  341. </DialogDescription>
  342. </DialogHeader>
  343. {isCreateForm ? (
  344. <Form {...createForm}>
  345. <form onSubmit={createForm.handleSubmit(handleCreateSubmit)} className="space-y-4">
  346. <FormField
  347. control={createForm.control}
  348. name="username"
  349. render={({ field }) => (
  350. <FormItem>
  351. <FormLabel className="flex items-center">
  352. 用户名
  353. <span className="text-red-500 ml-1">*</span>
  354. </FormLabel>
  355. <FormControl>
  356. <Input placeholder="请输入用户名" {...field} />
  357. </FormControl>
  358. <FormMessage />
  359. </FormItem>
  360. )}
  361. />
  362. <FormField
  363. control={createForm.control}
  364. name="nickname"
  365. render={({ field }) => (
  366. <FormItem>
  367. <FormLabel>昵称</FormLabel>
  368. <FormControl>
  369. <Input placeholder="请输入昵称" {...field} />
  370. </FormControl>
  371. <FormMessage />
  372. </FormItem>
  373. )}
  374. />
  375. <FormField
  376. control={createForm.control}
  377. name="email"
  378. render={({ field }) => (
  379. <FormItem>
  380. <FormLabel>邮箱</FormLabel>
  381. <FormControl>
  382. <Input type="email" placeholder="请输入邮箱" {...field} />
  383. </FormControl>
  384. <FormMessage />
  385. </FormItem>
  386. )}
  387. />
  388. <FormField
  389. control={createForm.control}
  390. name="phone"
  391. render={({ field }) => (
  392. <FormItem>
  393. <FormLabel>手机号</FormLabel>
  394. <FormControl>
  395. <Input placeholder="请输入手机号" {...field} />
  396. </FormControl>
  397. <FormMessage />
  398. </FormItem>
  399. )}
  400. />
  401. <FormField
  402. control={createForm.control}
  403. name="name"
  404. render={({ field }) => (
  405. <FormItem>
  406. <FormLabel>真实姓名</FormLabel>
  407. <FormControl>
  408. <Input placeholder="请输入真实姓名" {...field} />
  409. </FormControl>
  410. <FormMessage />
  411. </FormItem>
  412. )}
  413. />
  414. <FormField
  415. control={createForm.control}
  416. name="password"
  417. render={({ field }) => (
  418. <FormItem>
  419. <FormLabel className="flex items-center">
  420. 密码
  421. <span className="text-red-500 ml-1">*</span>
  422. </FormLabel>
  423. <FormControl>
  424. <Input type="password" placeholder="请输入密码" {...field} />
  425. </FormControl>
  426. <FormMessage />
  427. </FormItem>
  428. )}
  429. />
  430. <FormField
  431. control={createForm.control}
  432. name="avatarFileId"
  433. render={({ field }) => (
  434. <FormItem>
  435. <FormLabel>头像</FormLabel>
  436. <FormControl>
  437. <AvatarSelector
  438. value={field.value || undefined}
  439. onChange={(value) => field.onChange(value)}
  440. maxSize={2}
  441. uploadPath="/avatars"
  442. uploadButtonText="上传头像"
  443. previewSize="medium"
  444. placeholder="选择头像"
  445. />
  446. </FormControl>
  447. <FormMessage />
  448. </FormItem>
  449. )}
  450. />
  451. <FormField
  452. control={createForm.control}
  453. name="isDisabled"
  454. render={({ field }) => (
  455. <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
  456. <div className="space-y-0.5">
  457. <FormLabel className="text-base">用户状态</FormLabel>
  458. <FormDescription>
  459. 禁用后用户将无法登录系统
  460. </FormDescription>
  461. </div>
  462. <FormControl>
  463. <Switch
  464. checked={field.value === 1}
  465. onCheckedChange={(checked) => field.onChange(checked ? 1 : 0)}
  466. />
  467. </FormControl>
  468. </FormItem>
  469. )}
  470. />
  471. <DialogFooter>
  472. <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
  473. 取消
  474. </Button>
  475. <Button type="submit">
  476. 创建用户
  477. </Button>
  478. </DialogFooter>
  479. </form>
  480. </Form>
  481. ) : (
  482. <Form {...updateForm}>
  483. <form onSubmit={updateForm.handleSubmit(handleUpdateSubmit)} className="space-y-4">
  484. <FormField
  485. control={updateForm.control}
  486. name="username"
  487. render={({ field }) => (
  488. <FormItem>
  489. <FormLabel className="flex items-center">
  490. 用户名
  491. <span className="text-red-500 ml-1">*</span>
  492. </FormLabel>
  493. <FormControl>
  494. <Input placeholder="请输入用户名" {...field} />
  495. </FormControl>
  496. <FormMessage />
  497. </FormItem>
  498. )}
  499. />
  500. <FormField
  501. control={updateForm.control}
  502. name="nickname"
  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="email"
  516. render={({ field }) => (
  517. <FormItem>
  518. <FormLabel>邮箱</FormLabel>
  519. <FormControl>
  520. <Input type="email" placeholder="请输入邮箱" {...field} />
  521. </FormControl>
  522. <FormMessage />
  523. </FormItem>
  524. )}
  525. />
  526. <FormField
  527. control={updateForm.control}
  528. name="phone"
  529. render={({ field }) => (
  530. <FormItem>
  531. <FormLabel>手机号</FormLabel>
  532. <FormControl>
  533. <Input placeholder="请输入手机号" {...field} />
  534. </FormControl>
  535. <FormMessage />
  536. </FormItem>
  537. )}
  538. />
  539. <FormField
  540. control={updateForm.control}
  541. name="name"
  542. render={({ field }) => (
  543. <FormItem>
  544. <FormLabel>真实姓名</FormLabel>
  545. <FormControl>
  546. <Input placeholder="请输入真实姓名" {...field} />
  547. </FormControl>
  548. <FormMessage />
  549. </FormItem>
  550. )}
  551. />
  552. <FormField
  553. control={updateForm.control}
  554. name="password"
  555. render={({ field }) => (
  556. <FormItem>
  557. <FormLabel>新密码</FormLabel>
  558. <FormControl>
  559. <Input type="password" placeholder="留空则不修改密码" {...field} />
  560. </FormControl>
  561. <FormMessage />
  562. </FormItem>
  563. )}
  564. />
  565. <FormField
  566. control={updateForm.control}
  567. name="avatarFileId"
  568. render={({ field }) => (
  569. <FormItem>
  570. <FormLabel>头像</FormLabel>
  571. <FormControl>
  572. <AvatarSelector
  573. value={field.value || undefined}
  574. onChange={(value) => field.onChange(value)}
  575. maxSize={2}
  576. uploadPath="/avatars"
  577. uploadButtonText="上传头像"
  578. previewSize="medium"
  579. placeholder="选择头像"
  580. />
  581. </FormControl>
  582. <FormMessage />
  583. </FormItem>
  584. )}
  585. />
  586. <FormField
  587. control={updateForm.control}
  588. name="isDisabled"
  589. render={({ field }) => (
  590. <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
  591. <div className="space-y-0.5">
  592. <FormLabel className="text-base">用户状态</FormLabel>
  593. <FormDescription>
  594. 禁用后用户将无法登录系统
  595. </FormDescription>
  596. </div>
  597. <FormControl>
  598. <Switch
  599. checked={field.value === 1}
  600. onCheckedChange={(checked) => field.onChange(checked ? 1 : 0)}
  601. />
  602. </FormControl>
  603. </FormItem>
  604. )}
  605. />
  606. <DialogFooter>
  607. <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
  608. 取消
  609. </Button>
  610. <Button type="submit">
  611. 更新用户
  612. </Button>
  613. </DialogFooter>
  614. </form>
  615. </Form>
  616. )}
  617. </DialogContent>
  618. </Dialog>
  619. {/* Avatar selector is now integrated within the form */}
  620. {/* 删除确认对话框 */}
  621. <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
  622. <DialogContent>
  623. <DialogHeader>
  624. <DialogTitle>确认删除</DialogTitle>
  625. <DialogDescription>
  626. 确定要删除这个用户吗?此操作无法撤销。
  627. </DialogDescription>
  628. </DialogHeader>
  629. <DialogFooter>
  630. <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
  631. 取消
  632. </Button>
  633. <Button variant="destructive" onClick={confirmDelete}>
  634. 删除
  635. </Button>
  636. </DialogFooter>
  637. </DialogContent>
  638. </Dialog>
  639. </div>
  640. );
  641. };