Users.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  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 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. <AvatarSelector
  419. value={field.value || undefined}
  420. onChange={(value) => field.onChange(value)}
  421. maxSize={2}
  422. uploadPath="/avatars"
  423. uploadButtonText="上传头像"
  424. previewSize="medium"
  425. placeholder="选择头像"
  426. />
  427. </FormControl>
  428. <FormMessage />
  429. </FormItem>
  430. )}
  431. />
  432. <FormField
  433. control={createForm.control}
  434. name="isDisabled"
  435. render={({ field }) => (
  436. <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
  437. <div className="space-y-0.5">
  438. <FormLabel className="text-base">用户状态</FormLabel>
  439. <FormDescription>
  440. 禁用后用户将无法登录系统
  441. </FormDescription>
  442. </div>
  443. <FormControl>
  444. <Switch
  445. checked={field.value === 1}
  446. onCheckedChange={(checked) => field.onChange(checked ? 1 : 0)}
  447. />
  448. </FormControl>
  449. </FormItem>
  450. )}
  451. />
  452. <DialogFooter>
  453. <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
  454. 取消
  455. </Button>
  456. <Button type="submit">
  457. 创建用户
  458. </Button>
  459. </DialogFooter>
  460. </form>
  461. </Form>
  462. ) : (
  463. <Form {...updateForm}>
  464. <form onSubmit={updateForm.handleSubmit(handleUpdateSubmit)} className="space-y-4">
  465. <FormField
  466. control={updateForm.control}
  467. name="username"
  468. render={({ field }) => (
  469. <FormItem>
  470. <FormLabel className="flex items-center">
  471. 用户名
  472. <span className="text-red-500 ml-1">*</span>
  473. </FormLabel>
  474. <FormControl>
  475. <Input placeholder="请输入用户名" {...field} />
  476. </FormControl>
  477. <FormMessage />
  478. </FormItem>
  479. )}
  480. />
  481. <FormField
  482. control={updateForm.control}
  483. name="nickname"
  484. render={({ field }) => (
  485. <FormItem>
  486. <FormLabel>昵称</FormLabel>
  487. <FormControl>
  488. <Input placeholder="请输入昵称" {...field} />
  489. </FormControl>
  490. <FormMessage />
  491. </FormItem>
  492. )}
  493. />
  494. <FormField
  495. control={updateForm.control}
  496. name="email"
  497. render={({ field }) => (
  498. <FormItem>
  499. <FormLabel>邮箱</FormLabel>
  500. <FormControl>
  501. <Input type="email" placeholder="请输入邮箱" {...field} />
  502. </FormControl>
  503. <FormMessage />
  504. </FormItem>
  505. )}
  506. />
  507. <FormField
  508. control={updateForm.control}
  509. name="phone"
  510. render={({ field }) => (
  511. <FormItem>
  512. <FormLabel>手机号</FormLabel>
  513. <FormControl>
  514. <Input placeholder="请输入手机号" {...field} />
  515. </FormControl>
  516. <FormMessage />
  517. </FormItem>
  518. )}
  519. />
  520. <FormField
  521. control={updateForm.control}
  522. name="name"
  523. render={({ field }) => (
  524. <FormItem>
  525. <FormLabel>真实姓名</FormLabel>
  526. <FormControl>
  527. <Input placeholder="请输入真实姓名" {...field} />
  528. </FormControl>
  529. <FormMessage />
  530. </FormItem>
  531. )}
  532. />
  533. <FormField
  534. control={updateForm.control}
  535. name="password"
  536. render={({ field }) => (
  537. <FormItem>
  538. <FormLabel>新密码</FormLabel>
  539. <FormControl>
  540. <Input type="password" placeholder="留空则不修改密码" {...field} />
  541. </FormControl>
  542. <FormMessage />
  543. </FormItem>
  544. )}
  545. />
  546. <FormField
  547. control={updateForm.control}
  548. name="avatarFileId"
  549. render={({ field }) => (
  550. <FormItem>
  551. <FormLabel>头像</FormLabel>
  552. <FormControl>
  553. <AvatarSelector
  554. value={field.value || undefined}
  555. onChange={(value) => field.onChange(value)}
  556. maxSize={2}
  557. uploadPath="/avatars"
  558. uploadButtonText="上传头像"
  559. previewSize="medium"
  560. placeholder="选择头像"
  561. />
  562. </FormControl>
  563. <FormMessage />
  564. </FormItem>
  565. )}
  566. />
  567. <FormField
  568. control={updateForm.control}
  569. name="isDisabled"
  570. render={({ field }) => (
  571. <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
  572. <div className="space-y-0.5">
  573. <FormLabel className="text-base">用户状态</FormLabel>
  574. <FormDescription>
  575. 禁用后用户将无法登录系统
  576. </FormDescription>
  577. </div>
  578. <FormControl>
  579. <Switch
  580. checked={field.value === 1}
  581. onCheckedChange={(checked) => field.onChange(checked ? 1 : 0)}
  582. />
  583. </FormControl>
  584. </FormItem>
  585. )}
  586. />
  587. <DialogFooter>
  588. <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
  589. 取消
  590. </Button>
  591. <Button type="submit">
  592. 更新用户
  593. </Button>
  594. </DialogFooter>
  595. </form>
  596. </Form>
  597. )}
  598. </DialogContent>
  599. </Dialog>
  600. {/* Avatar selector is now integrated within the form */}
  601. {/* 删除确认对话框 */}
  602. <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
  603. <DialogContent>
  604. <DialogHeader>
  605. <DialogTitle>确认删除</DialogTitle>
  606. <DialogDescription>
  607. 确定要删除这个用户吗?此操作无法撤销。
  608. </DialogDescription>
  609. </DialogHeader>
  610. <DialogFooter>
  611. <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
  612. 取消
  613. </Button>
  614. <Button variant="destructive" onClick={confirmDelete}>
  615. 删除
  616. </Button>
  617. </DialogFooter>
  618. </DialogContent>
  619. </Dialog>
  620. </div>
  621. );
  622. };