Users.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. import React, { useState } from 'react';
  2. import { useQuery } from '@tanstack/react-query';
  3. import { format } from 'date-fns';
  4. import { zhCN } from 'date-fns/locale';
  5. import { zodResolver } from '@hookform/resolvers/zod';
  6. import { useForm } from 'react-hook-form';
  7. import { toast } from 'sonner';
  8. import { Plus, Search, Edit, Trash2, Eye } from 'lucide-react';
  9. import { userClient } from '@/client/api';
  10. import type { InferResponseType, InferRequestType } from 'hono/client';
  11. import { UserType } from '@/server/modules/users/user.enum';
  12. import { CreateUserDto, UpdateUserDto } from '@/server/modules/users/user.schema';
  13. import { Button } from '@/client/components/ui/button';
  14. import { Input } from '@/client/components/ui/input';
  15. import { Badge } from '@/client/components/ui/badge';
  16. import { Card, CardContent, CardHeader, CardTitle } from '@/client/components/ui/card';
  17. import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/client/components/ui/table';
  18. import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/client/components/ui/dialog';
  19. import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/client/components/ui/form';
  20. import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/client/components/ui/select';
  21. import { Skeleton } from '@/client/components/ui/skeleton';
  22. import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/client/components/ui/alert-dialog';
  23. import { DataTablePagination } from '@/client/admin/components/DataTablePagination';
  24. type UserListResponse = InferResponseType<typeof userClient.$get, 200>;
  25. type UserDetailResponse = InferResponseType<typeof userClient[':id']['$get'], 200>;
  26. type CreateUserRequest = InferRequestType<typeof userClient.$post>['json'];
  27. type UpdateUserRequest = InferRequestType<typeof userClient[':id']['$put']>['json'];
  28. // 创建表单schema
  29. const createFormSchema = CreateUserDto;
  30. const updateFormSchema = UpdateUserDto;
  31. // 用户管理页面
  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 [isCreateForm, setIsCreateForm] = useState(true);
  40. const [editingUser, setEditingUser] = useState<any>(null);
  41. const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  42. const [userToDelete, setUserToDelete] = useState<number | null>(null);
  43. // 创建表单
  44. const createForm = useForm<CreateUserRequest>({
  45. resolver: zodResolver(createFormSchema),
  46. defaultValues: {
  47. username: '',
  48. password: '',
  49. email: null,
  50. phone: null,
  51. nickname: null,
  52. name: null,
  53. userType: UserType.STUDENT,
  54. isDisabled: 0
  55. }
  56. });
  57. // 更新表单
  58. const updateForm = useForm<UpdateUserRequest>({
  59. resolver: zodResolver(updateFormSchema),
  60. defaultValues: {
  61. username: '',
  62. email: null,
  63. phone: null,
  64. nickname: null,
  65. name: null,
  66. userType: UserType.STUDENT,
  67. isDisabled: 0
  68. }
  69. });
  70. // 获取用户列表
  71. const { data: usersData, isLoading, refetch } = useQuery({
  72. queryKey: ['users', searchParams],
  73. queryFn: async () => {
  74. const res = await userClient.$get({
  75. query: {
  76. page: searchParams.page,
  77. pageSize: searchParams.limit,
  78. keyword: searchParams.search
  79. }
  80. });
  81. if (res.status !== 200) {
  82. throw new Error('获取用户列表失败');
  83. }
  84. return await res.json();
  85. }
  86. });
  87. const users = usersData?.data || [];
  88. const totalCount = usersData?.pagination?.total || 0;
  89. // 处理搜索
  90. const handleSearch = (e: React.FormEvent) => {
  91. e.preventDefault();
  92. setSearchParams(prev => ({ ...prev, page: 1 }));
  93. };
  94. // 打开创建用户对话框
  95. const showCreateModal = () => {
  96. setIsCreateForm(true);
  97. setEditingUser(null);
  98. createForm.reset();
  99. setIsModalOpen(true);
  100. };
  101. // 打开编辑用户对话框
  102. const showEditModal = (user: any) => {
  103. setIsCreateForm(false);
  104. setEditingUser(user);
  105. updateForm.reset({
  106. username: user.username,
  107. email: user.email,
  108. phone: user.phone,
  109. nickname: user.nickname,
  110. name: user.name,
  111. userType: user.userType,
  112. isDisabled: user.isDisabled
  113. });
  114. setIsModalOpen(true);
  115. };
  116. // 处理创建用户
  117. const handleCreateSubmit = async (data: CreateUserRequest) => {
  118. try {
  119. const res = await userClient.$post({ json: data });
  120. if (res.status !== 201) {
  121. const error = await res.json();
  122. throw new Error(error.message || '创建用户失败');
  123. }
  124. toast.success('用户创建成功');
  125. setIsModalOpen(false);
  126. createForm.reset();
  127. refetch();
  128. } catch (error) {
  129. toast.error(error instanceof Error ? error.message : '创建失败,请重试');
  130. }
  131. };
  132. // 处理更新用户
  133. const handleUpdateSubmit = async (data: UpdateUserRequest) => {
  134. if (!editingUser) return;
  135. try {
  136. const res = await userClient[':id']['$put']({
  137. param: { id: editingUser.id.toString() },
  138. json: data
  139. });
  140. if (res.status !== 200) {
  141. const error = await res.json();
  142. throw new Error(error.message || '更新用户失败');
  143. }
  144. toast.success('用户更新成功');
  145. setIsModalOpen(false);
  146. updateForm.reset();
  147. refetch();
  148. } catch (error) {
  149. toast.error(error instanceof Error ? error.message : '更新失败,请重试');
  150. }
  151. };
  152. // 打开删除确认对话框
  153. const showDeleteDialog = (userId: number) => {
  154. setUserToDelete(userId);
  155. setDeleteDialogOpen(true);
  156. };
  157. // 处理删除用户
  158. const handleDelete = async () => {
  159. if (!userToDelete) return;
  160. try {
  161. const res = await userClient[':id']['$delete']({
  162. param: { id: userToDelete.toString() }
  163. });
  164. if (res.status !== 204) {
  165. throw new Error('删除用户失败');
  166. }
  167. toast.success('用户删除成功');
  168. setDeleteDialogOpen(false);
  169. setUserToDelete(null);
  170. refetch();
  171. } catch (error) {
  172. toast.error('删除失败,请重试');
  173. }
  174. };
  175. // 加载状态
  176. if (isLoading) {
  177. return (
  178. <div className="space-y-4">
  179. <div className="flex justify-between items-center">
  180. <Skeleton className="h-8 w-48" />
  181. <Skeleton className="h-10 w-32" />
  182. </div>
  183. <Card>
  184. <CardHeader>
  185. <Skeleton className="h-6 w-1/4" />
  186. </CardHeader>
  187. <CardContent>
  188. <div className="space-y-3">
  189. {[...Array(5)].map((_, i) => (
  190. <div key={i} className="flex gap-4">
  191. <Skeleton className="h-10 flex-1" />
  192. <Skeleton className="h-10 flex-1" />
  193. <Skeleton className="h-10 flex-1" />
  194. <Skeleton className="h-10 w-20" />
  195. </div>
  196. ))}
  197. </div>
  198. </CardContent>
  199. </Card>
  200. </div>
  201. );
  202. }
  203. return (
  204. <div className="space-y-4">
  205. {/* 页面标题 */}
  206. <div className="flex justify-between items-center">
  207. <h1 className="text-2xl font-bold">用户管理</h1>
  208. <Button onClick={showCreateModal}>
  209. <Plus className="mr-2 h-4 w-4" />
  210. 创建用户
  211. </Button>
  212. </div>
  213. {/* 搜索区域 */}
  214. <Card>
  215. <CardHeader>
  216. <CardTitle>用户列表</CardTitle>
  217. </CardHeader>
  218. <CardContent>
  219. <form onSubmit={handleSearch} className="flex gap-2 mb-4">
  220. <div className="relative flex-1 max-w-sm">
  221. <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
  222. <Input
  223. placeholder="搜索用户名/昵称/邮箱..."
  224. value={searchParams.search}
  225. onChange={(e) => setSearchParams(prev => ({ ...prev, search: e.target.value }))}
  226. className="pl-8"
  227. />
  228. </div>
  229. <Button type="submit" variant="outline">
  230. 搜索
  231. </Button>
  232. </form>
  233. {/* 用户表格 */}
  234. <div className="rounded-md border">
  235. <Table>
  236. <TableHeader>
  237. <TableRow>
  238. <TableHead>头像</TableHead>
  239. <TableHead>用户名</TableHead>
  240. <TableHead>昵称</TableHead>
  241. <TableHead>邮箱</TableHead>
  242. <TableHead>真实姓名</TableHead>
  243. <TableHead>用户类型</TableHead>
  244. <TableHead>状态</TableHead>
  245. <TableHead>创建时间</TableHead>
  246. <TableHead className="text-right">操作</TableHead>
  247. </TableRow>
  248. </TableHeader>
  249. <TableBody>
  250. {users.map((user) => (
  251. <TableRow key={user.id}>
  252. <TableCell>
  253. {user.avatarFile?.fullUrl ? (
  254. <img
  255. src={user.avatarFile.fullUrl}
  256. alt={user.nickname || user.username}
  257. className="w-8 h-8 rounded-full object-cover"
  258. />
  259. ) : (
  260. <div className="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center text-xs text-gray-500">
  261. {user.nickname ? user.nickname.charAt(0).toUpperCase() : user.username.charAt(0).toUpperCase()}
  262. </div>
  263. )}
  264. </TableCell>
  265. <TableCell className="font-medium">{user.username}</TableCell>
  266. <TableCell>{user.nickname || '-'}</TableCell>
  267. <TableCell>{user.email || '-'}</TableCell>
  268. <TableCell>{user.name || '-'}</TableCell>
  269. <TableCell>
  270. <Badge
  271. variant={
  272. user.userType === UserType.TEACHER ? 'default' :
  273. user.userType === UserType.STUDENT ? 'secondary' : 'outline'
  274. }
  275. className={
  276. user.userType === UserType.TEACHER ? 'bg-blue-100 text-blue-800' :
  277. user.userType === UserType.STUDENT ? 'bg-green-100 text-green-800' :
  278. 'bg-purple-100 text-purple-800'
  279. }
  280. >
  281. {user.userType === UserType.TEACHER ? '老师' :
  282. user.userType === UserType.STUDENT ? '学生' : '学员'}
  283. </Badge>
  284. </TableCell>
  285. <TableCell>
  286. <Badge
  287. variant={user.isDisabled === 0 ? 'default' : 'destructive'}
  288. className={user.isDisabled === 0 ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}
  289. >
  290. {user.isDisabled === 0 ? '启用' : '禁用'}
  291. </Badge>
  292. </TableCell>
  293. <TableCell>
  294. {user.createdAt ? format(new Date(user.createdAt), 'yyyy-MM-dd HH:mm', { locale: zhCN }) : '-'}
  295. </TableCell>
  296. <TableCell className="text-right">
  297. <div className="flex justify-end gap-2">
  298. <Button
  299. variant="ghost"
  300. size="sm"
  301. onClick={() => showEditModal(user)}
  302. >
  303. <Edit className="h-4 w-4" />
  304. </Button>
  305. <Button
  306. variant="ghost"
  307. size="sm"
  308. onClick={() => showDeleteDialog(user.id)}
  309. className="text-destructive hover:text-destructive"
  310. >
  311. <Trash2 className="h-4 w-4" />
  312. </Button>
  313. </div>
  314. </TableCell>
  315. </TableRow>
  316. ))}
  317. </TableBody>
  318. </Table>
  319. </div>
  320. {users.length === 0 && (
  321. <div className="text-center py-8">
  322. <p className="text-muted-foreground">暂无数据</p>
  323. </div>
  324. )}
  325. {/* 分页 */}
  326. <DataTablePagination
  327. currentPage={searchParams.page}
  328. pageSize={searchParams.limit}
  329. totalCount={totalCount}
  330. onPageChange={(page, limit) => setSearchParams(prev => ({ ...prev, page, limit }))}
  331. />
  332. </CardContent>
  333. </Card>
  334. {/* 创建/编辑用户对话框 */}
  335. <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
  336. <DialogContent className="sm:max-w-[500px] max-h-[90vh] overflow-y-auto">
  337. <DialogHeader>
  338. <DialogTitle>{isCreateForm ? '创建用户' : '编辑用户'}</DialogTitle>
  339. <DialogDescription>
  340. {isCreateForm ? '创建一个新的用户账户' : '编辑现有用户信息'}
  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>用户名</FormLabel>
  352. <FormControl>
  353. <Input placeholder="请输入用户名" {...field} />
  354. </FormControl>
  355. <FormMessage />
  356. </FormItem>
  357. )}
  358. />
  359. <FormField
  360. control={createForm.control}
  361. name="password"
  362. render={({ field }) => (
  363. <FormItem>
  364. <FormLabel>密码</FormLabel>
  365. <FormControl>
  366. <Input type="password" placeholder="请输入密码" {...field} />
  367. </FormControl>
  368. <FormMessage />
  369. </FormItem>
  370. )}
  371. />
  372. <FormField
  373. control={createForm.control}
  374. name="nickname"
  375. render={({ field }) => (
  376. <FormItem>
  377. <FormLabel>昵称</FormLabel>
  378. <FormControl>
  379. <Input placeholder="请输入昵称" {...field} />
  380. </FormControl>
  381. <FormMessage />
  382. </FormItem>
  383. )}
  384. />
  385. <FormField
  386. control={createForm.control}
  387. name="email"
  388. render={({ field }) => (
  389. <FormItem>
  390. <FormLabel>邮箱</FormLabel>
  391. <FormControl>
  392. <Input type="email" placeholder="请输入邮箱" {...field} />
  393. </FormControl>
  394. <FormMessage />
  395. </FormItem>
  396. )}
  397. />
  398. <FormField
  399. control={createForm.control}
  400. name="phone"
  401. render={({ field }) => (
  402. <FormItem>
  403. <FormLabel>手机号</FormLabel>
  404. <FormControl>
  405. <Input type="tel" placeholder="请输入手机号" {...field} />
  406. </FormControl>
  407. <FormMessage />
  408. </FormItem>
  409. )}
  410. />
  411. <FormField
  412. control={createForm.control}
  413. name="name"
  414. render={({ field }) => (
  415. <FormItem>
  416. <FormLabel>真实姓名</FormLabel>
  417. <FormControl>
  418. <Input placeholder="请输入真实姓名" {...field} />
  419. </FormControl>
  420. <FormMessage />
  421. </FormItem>
  422. )}
  423. />
  424. <FormField
  425. control={createForm.control}
  426. name="userType"
  427. render={({ field }) => (
  428. <FormItem>
  429. <FormLabel>用户类型</FormLabel>
  430. <Select onValueChange={field.onChange} defaultValue={field.value}>
  431. <FormControl>
  432. <SelectTrigger>
  433. <SelectValue placeholder="请选择用户类型" />
  434. </SelectTrigger>
  435. </FormControl>
  436. <SelectContent>
  437. <SelectItem value={UserType.TEACHER}>老师</SelectItem>
  438. <SelectItem value={UserType.STUDENT}>学生</SelectItem>
  439. <SelectItem value={UserType.TRAINEE}>学员</SelectItem>
  440. </SelectContent>
  441. </Select>
  442. <FormMessage />
  443. </FormItem>
  444. )}
  445. />
  446. <FormField
  447. control={createForm.control}
  448. name="isDisabled"
  449. render={({ field }) => (
  450. <FormItem>
  451. <FormLabel>状态</FormLabel>
  452. <Select onValueChange={(value) => field.onChange(parseInt(value))} defaultValue={field.value?.toString()}>
  453. <FormControl>
  454. <SelectTrigger>
  455. <SelectValue placeholder="请选择状态" />
  456. </SelectTrigger>
  457. </FormControl>
  458. <SelectContent>
  459. <SelectItem value="0">启用</SelectItem>
  460. <SelectItem value="1">禁用</SelectItem>
  461. </SelectContent>
  462. </Select>
  463. <FormMessage />
  464. </FormItem>
  465. )}
  466. />
  467. <DialogFooter>
  468. <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
  469. 取消
  470. </Button>
  471. <Button type="submit">创建</Button>
  472. </DialogFooter>
  473. </form>
  474. </Form>
  475. ) : (
  476. <Form {...updateForm}>
  477. <form onSubmit={updateForm.handleSubmit(handleUpdateSubmit)} className="space-y-4">
  478. <FormField
  479. control={updateForm.control}
  480. name="username"
  481. render={({ field }) => (
  482. <FormItem>
  483. <FormLabel>用户名</FormLabel>
  484. <FormControl>
  485. <Input placeholder="请输入用户名" {...field} />
  486. </FormControl>
  487. <FormMessage />
  488. </FormItem>
  489. )}
  490. />
  491. <FormField
  492. control={updateForm.control}
  493. name="nickname"
  494. render={({ field }) => (
  495. <FormItem>
  496. <FormLabel>昵称</FormLabel>
  497. <FormControl>
  498. <Input placeholder="请输入昵称" {...field} />
  499. </FormControl>
  500. <FormMessage />
  501. </FormItem>
  502. )}
  503. />
  504. <FormField
  505. control={updateForm.control}
  506. name="email"
  507. render={({ field }) => (
  508. <FormItem>
  509. <FormLabel>邮箱</FormLabel>
  510. <FormControl>
  511. <Input type="email" placeholder="请输入邮箱" {...field} />
  512. </FormControl>
  513. <FormMessage />
  514. </FormItem>
  515. )}
  516. />
  517. <FormField
  518. control={updateForm.control}
  519. name="phone"
  520. render={({ field }) => (
  521. <FormItem>
  522. <FormLabel>手机号</FormLabel>
  523. <FormControl>
  524. <Input type="tel" placeholder="请输入手机号" {...field} />
  525. </FormControl>
  526. <FormMessage />
  527. </FormItem>
  528. )}
  529. />
  530. <FormField
  531. control={updateForm.control}
  532. name="name"
  533. render={({ field }) => (
  534. <FormItem>
  535. <FormLabel>真实姓名</FormLabel>
  536. <FormControl>
  537. <Input placeholder="请输入真实姓名" {...field} />
  538. </FormControl>
  539. <FormMessage />
  540. </FormItem>
  541. )}
  542. />
  543. <FormField
  544. control={updateForm.control}
  545. name="userType"
  546. render={({ field }) => (
  547. <FormItem>
  548. <FormLabel>用户类型</FormLabel>
  549. <Select onValueChange={field.onChange} defaultValue={field.value}>
  550. <FormControl>
  551. <SelectTrigger>
  552. <SelectValue placeholder="请选择用户类型" />
  553. </SelectTrigger>
  554. </FormControl>
  555. <SelectContent>
  556. <SelectItem value={UserType.TEACHER}>老师</SelectItem>
  557. <SelectItem value={UserType.STUDENT}>学生</SelectItem>
  558. <SelectItem value={UserType.TRAINEE}>学员</SelectItem>
  559. </SelectContent>
  560. </Select>
  561. <FormMessage />
  562. </FormItem>
  563. )}
  564. />
  565. <FormField
  566. control={updateForm.control}
  567. name="isDisabled"
  568. render={({ field }) => (
  569. <FormItem>
  570. <FormLabel>状态</FormLabel>
  571. <Select onValueChange={(value) => field.onChange(parseInt(value))} defaultValue={field.value?.toString()}>
  572. <FormControl>
  573. <SelectTrigger>
  574. <SelectValue placeholder="请选择状态" />
  575. </SelectTrigger>
  576. </FormControl>
  577. <SelectContent>
  578. <SelectItem value="0">启用</SelectItem>
  579. <SelectItem value="1">禁用</SelectItem>
  580. </SelectContent>
  581. </Select>
  582. <FormMessage />
  583. </FormItem>
  584. )}
  585. />
  586. <DialogFooter>
  587. <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
  588. 取消
  589. </Button>
  590. <Button type="submit">更新</Button>
  591. </DialogFooter>
  592. </form>
  593. </Form>
  594. )}
  595. </DialogContent>
  596. </Dialog>
  597. {/* 删除确认对话框 */}
  598. <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
  599. <AlertDialogContent>
  600. <AlertDialogHeader>
  601. <AlertDialogTitle>确认删除</AlertDialogTitle>
  602. <AlertDialogDescription>
  603. 确定要删除这个用户吗?此操作无法撤销。
  604. </AlertDialogDescription>
  605. </AlertDialogHeader>
  606. <AlertDialogFooter>
  607. <AlertDialogCancel>取消</AlertDialogCancel>
  608. <AlertDialogAction onClick={handleDelete}>删除</AlertDialogAction>
  609. </AlertDialogFooter>
  610. </AlertDialogContent>
  611. </AlertDialog>
  612. </div>
  613. );
  614. };