PlatformManagement.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. import React, { useState } from 'react';
  2. import { useQuery, useMutation } from '@tanstack/react-query';
  3. import { Plus, Edit, Trash2, Search } from 'lucide-react';
  4. import { format } from 'date-fns';
  5. import { Input } from '@d8d/shared-ui-components/components/ui/input';
  6. import { Button } from '@d8d/shared-ui-components/components/ui/button';
  7. import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@d8d/shared-ui-components/components/ui/card';
  8. import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@d8d/shared-ui-components/components/ui/table';
  9. import { Skeleton } from '@d8d/shared-ui-components/components/ui/skeleton';
  10. import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@d8d/shared-ui-components/components/ui/dialog';
  11. import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@d8d/shared-ui-components/components/ui/form';
  12. import { useForm } from 'react-hook-form';
  13. import { zodResolver } from '@hookform/resolvers/zod';
  14. import { toast } from 'sonner';
  15. import { DataTablePagination } from '@d8d/shared-ui-components/components/admin/DataTablePagination';
  16. import { platformClientManager } from '../api/platformClient';
  17. import { CreatePlatformSchema, UpdatePlatformSchema } from '@d8d/allin-platform-module/schemas';
  18. import type { CreatePlatformRequest, UpdatePlatformRequest } from '../api/types';
  19. interface PlatformSearchParams {
  20. page: number;
  21. limit: number;
  22. search: string;
  23. }
  24. import type { PlatformResponse } from '../api/types';
  25. const PlatformManagement: React.FC = () => {
  26. const [searchParams, setSearchParams] = useState<PlatformSearchParams>({ page: 1, limit: 10, search: '' });
  27. const [isModalOpen, setIsModalOpen] = useState(false);
  28. const [isCreateForm, setIsCreateForm] = useState(true);
  29. const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  30. const [platformToDelete, setPlatformToDelete] = useState<number | null>(null);
  31. // 表单实例
  32. const createForm = useForm<CreatePlatformRequest>({
  33. resolver: zodResolver(CreatePlatformSchema),
  34. defaultValues: {
  35. platformName: '',
  36. contactPerson: '',
  37. contactPhone: '',
  38. contactEmail: undefined
  39. }
  40. });
  41. const updateForm = useForm<UpdatePlatformRequest>({
  42. resolver: zodResolver(UpdatePlatformSchema),
  43. defaultValues: {}
  44. });
  45. // 数据查询
  46. const { data, isLoading, refetch } = useQuery({
  47. queryKey: ['platforms', searchParams],
  48. queryFn: async () => {
  49. const res = await platformClientManager.get().getAllPlatforms.$get({
  50. query: {
  51. skip: (searchParams.page - 1) * searchParams.limit,
  52. take: searchParams.limit
  53. }
  54. });
  55. if (res.status !== 200) throw new Error('获取平台列表失败');
  56. return await res.json();
  57. },
  58. initialData: {
  59. data: [],
  60. total: 0
  61. }
  62. });
  63. // 创建平台
  64. const createMutation = useMutation({
  65. mutationFn: async (data: CreatePlatformRequest) => {
  66. const res = await platformClientManager.get().createPlatform.$post({ json: data });
  67. if (res.status !== 200) throw new Error('创建平台失败');
  68. return await res.json();
  69. },
  70. onSuccess: () => {
  71. toast.success('平台创建成功');
  72. setIsModalOpen(false);
  73. createForm.reset();
  74. refetch();
  75. },
  76. onError: (error) => {
  77. toast.error(error instanceof Error ? error.message : '创建平台失败');
  78. }
  79. });
  80. // 更新平台
  81. const updateMutation = useMutation({
  82. mutationFn: async (data: UpdatePlatformRequest) => {
  83. const res = await platformClientManager.get().updatePlatform.$post({
  84. json: data
  85. });
  86. if (res.status !== 200) throw new Error('更新平台失败');
  87. return await res.json();
  88. },
  89. onSuccess: () => {
  90. toast.success('平台更新成功');
  91. setIsModalOpen(false);
  92. refetch();
  93. },
  94. onError: (error) => {
  95. toast.error(error instanceof Error ? error.message : '更新平台失败');
  96. }
  97. });
  98. // 删除平台
  99. const deleteMutation = useMutation({
  100. mutationFn: async (id: number) => {
  101. const res = await platformClientManager.get().deletePlatform.$post({
  102. json: { id }
  103. });
  104. if (res.status !== 200) throw new Error('删除平台失败');
  105. return await res.json();
  106. },
  107. onSuccess: () => {
  108. toast.success('平台删除成功');
  109. setDeleteDialogOpen(false);
  110. setPlatformToDelete(null);
  111. refetch();
  112. },
  113. onError: (error) => {
  114. toast.error(error instanceof Error ? error.message : '删除平台失败');
  115. }
  116. });
  117. // 处理搜索
  118. const handleSearch = (e: React.FormEvent) => {
  119. e.preventDefault();
  120. if (searchParams.search.trim()) {
  121. // 如果有搜索关键词,使用搜索接口
  122. const searchQuery = async () => {
  123. const res = await platformClientManager.get().searchPlatforms.$get({
  124. query: {
  125. name: searchParams.search,
  126. skip: 0,
  127. take: searchParams.limit
  128. }
  129. });
  130. if (res.status !== 200) throw new Error('搜索平台失败');
  131. return await res.json();
  132. };
  133. searchQuery().then(() => {
  134. // 暂时使用refetch,实际应该更新数据
  135. refetch();
  136. }).catch(error => {
  137. toast.error(error instanceof Error ? error.message : '搜索失败');
  138. });
  139. } else {
  140. // 没有搜索关键词,使用普通列表接口
  141. setSearchParams(prev => ({ ...prev, page: 1 }));
  142. refetch();
  143. }
  144. };
  145. // 处理创建平台
  146. const handleCreatePlatform = () => {
  147. setIsCreateForm(true);
  148. createForm.reset();
  149. setIsModalOpen(true);
  150. };
  151. // 处理编辑平台
  152. const handleEditPlatform = (platform: PlatformResponse) => {
  153. setIsCreateForm(false);
  154. updateForm.reset({
  155. id: platform.id,
  156. platformName: platform.platformName || undefined,
  157. contactPerson: platform.contactPerson || undefined,
  158. contactPhone: platform.contactPhone || undefined,
  159. contactEmail: platform.contactEmail || undefined
  160. });
  161. setIsModalOpen(true);
  162. };
  163. // 处理删除平台
  164. const handleDeletePlatform = (id: number) => {
  165. setPlatformToDelete(id);
  166. setDeleteDialogOpen(true);
  167. };
  168. // 确认删除
  169. const confirmDelete = () => {
  170. if (platformToDelete) {
  171. deleteMutation.mutate(platformToDelete);
  172. }
  173. };
  174. // 处理创建表单提交
  175. const handleCreateSubmit = async (data: CreatePlatformRequest) => {
  176. try {
  177. await createMutation.mutateAsync(data);
  178. } catch (error) {
  179. throw error;
  180. }
  181. };
  182. // 处理编辑表单提交
  183. const handleUpdateSubmit = async (data: UpdatePlatformRequest) => {
  184. try {
  185. await updateMutation.mutateAsync(data);
  186. } catch (error) {
  187. throw error;
  188. }
  189. };
  190. // 日期格式化函数
  191. const formatDate = (dateString: string): string => {
  192. if (!dateString) return '';
  193. try {
  194. const date = new Date(dateString);
  195. if (isNaN(date.getTime())) return dateString;
  196. return format(date, 'yyyy-MM-dd HH:mm');
  197. } catch (error) {
  198. return dateString;
  199. }
  200. };
  201. return (
  202. <div className="space-y-4">
  203. <div className="flex justify-between items-center">
  204. <h1 className="text-2xl font-bold">平台管理</h1>
  205. <Button onClick={handleCreatePlatform} data-testid="create-platform-button">
  206. <Plus className="mr-2 h-4 w-4" />
  207. 创建平台
  208. </Button>
  209. </div>
  210. <Card>
  211. <CardHeader>
  212. <CardTitle>平台列表</CardTitle>
  213. <CardDescription>管理所有用人平台</CardDescription>
  214. </CardHeader>
  215. <CardContent>
  216. <div className="mb-4">
  217. <form onSubmit={handleSearch} className="flex gap-2">
  218. <div className="relative flex-1 max-w-sm">
  219. <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
  220. <Input
  221. placeholder="搜索平台名称..."
  222. value={searchParams.search}
  223. onChange={(e) => setSearchParams(prev => ({ ...prev, search: e.target.value }))}
  224. className="pl-8"
  225. data-testid="search-input"
  226. />
  227. </div>
  228. <Button type="submit" variant="outline" data-testid="search-button">
  229. 搜索
  230. </Button>
  231. </form>
  232. </div>
  233. <div className="rounded-md border">
  234. <div className="relative w-full overflow-x-auto">
  235. <Table>
  236. <TableHeader>
  237. <TableRow>
  238. <TableHead>平台ID</TableHead>
  239. <TableHead>平台名称</TableHead>
  240. <TableHead>联系人</TableHead>
  241. <TableHead>联系电话</TableHead>
  242. <TableHead>联系邮箱</TableHead>
  243. <TableHead>创建时间</TableHead>
  244. <TableHead className="text-right">操作</TableHead>
  245. </TableRow>
  246. </TableHeader>
  247. <TableBody>
  248. {isLoading ? (
  249. Array.from({ length: 5 }).map((_, index) => (
  250. <TableRow key={index}>
  251. <TableCell><Skeleton className="h-4 w-8" /></TableCell>
  252. <TableCell><Skeleton className="h-4 w-32" /></TableCell>
  253. <TableCell><Skeleton className="h-4 w-20" /></TableCell>
  254. <TableCell><Skeleton className="h-4 w-24" /></TableCell>
  255. <TableCell><Skeleton className="h-4 w-32" /></TableCell>
  256. <TableCell><Skeleton className="h-4 w-24" /></TableCell>
  257. <TableCell>
  258. <div className="flex justify-end gap-2">
  259. <Skeleton className="h-8 w-8 rounded" />
  260. <Skeleton className="h-8 w-8 rounded" />
  261. </div>
  262. </TableCell>
  263. </TableRow>
  264. ))
  265. ) : data?.data && data.data.length > 0 ? (
  266. data.data.map((platform: PlatformResponse) => (
  267. <TableRow key={platform.id}>
  268. <TableCell>{platform.id}</TableCell>
  269. <TableCell>{platform.platformName || '-'}</TableCell>
  270. <TableCell>{platform.contactPerson || '-'}</TableCell>
  271. <TableCell>{platform.contactPhone || '-'}</TableCell>
  272. <TableCell>{platform.contactEmail || '-'}</TableCell>
  273. <TableCell>{formatDate(platform.createTime)}</TableCell>
  274. <TableCell className="text-right">
  275. <div className="flex justify-end gap-2">
  276. <Button
  277. variant="ghost"
  278. size="icon"
  279. onClick={() => handleEditPlatform(platform)}
  280. data-testid={`edit-button-${platform.id}`}
  281. >
  282. <Edit className="h-4 w-4" />
  283. </Button>
  284. <Button
  285. variant="ghost"
  286. size="icon"
  287. onClick={() => handleDeletePlatform(platform.id)}
  288. data-testid={`delete-button-${platform.id}`}
  289. >
  290. <Trash2 className="h-4 w-4" />
  291. </Button>
  292. </div>
  293. </TableCell>
  294. </TableRow>
  295. ))
  296. ) : (
  297. <TableRow>
  298. <TableCell colSpan={7} className="text-center py-8">
  299. <p className="text-muted-foreground">暂无平台数据</p>
  300. </TableCell>
  301. </TableRow>
  302. )}
  303. </TableBody>
  304. </Table>
  305. </div>
  306. </div>
  307. {data.total > 0 && (<DataTablePagination
  308. currentPage={searchParams.page}
  309. pageSize={searchParams.limit}
  310. totalCount={data?.total || 0}
  311. onPageChange={(page, limit) => setSearchParams(prev => ({ ...prev, page, limit }))}
  312. />)}
  313. </CardContent>
  314. </Card>
  315. {/* 创建/编辑对话框 */}
  316. <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
  317. <DialogContent className="sm:max-w-[500px] max-h-[90vh] overflow-y-auto">
  318. <DialogHeader>
  319. <DialogTitle data-testid={isCreateForm ? 'create-platform-dialog-title' : 'edit-platform-dialog-title'}>{isCreateForm ? '创建平台' : '编辑平台'}</DialogTitle>
  320. <DialogDescription>
  321. {isCreateForm ? '创建一个新的用人平台' : '编辑现有平台信息'}
  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="platformName"
  330. render={({ field }) => (
  331. <FormItem>
  332. <FormLabel className="flex items-center">
  333. 平台名称 <span className="text-red-500 ml-1">*</span>
  334. </FormLabel>
  335. <FormControl>
  336. <Input placeholder="请输入平台名称" {...field} data-testid="platform-name-input" />
  337. </FormControl>
  338. <FormMessage />
  339. </FormItem>
  340. )}
  341. />
  342. <FormField
  343. control={createForm.control}
  344. name="contactPerson"
  345. render={({ field }) => (
  346. <FormItem>
  347. <FormLabel>联系人</FormLabel>
  348. <FormControl>
  349. <Input placeholder="请输入联系人姓名" {...field} data-testid="contact-person-input" />
  350. </FormControl>
  351. <FormMessage />
  352. </FormItem>
  353. )}
  354. />
  355. <FormField
  356. control={createForm.control}
  357. name="contactPhone"
  358. render={({ field }) => (
  359. <FormItem>
  360. <FormLabel>联系电话</FormLabel>
  361. <FormControl>
  362. <Input placeholder="请输入联系电话" {...field} data-testid="contact-phone-input" />
  363. </FormControl>
  364. <FormMessage />
  365. </FormItem>
  366. )}
  367. />
  368. <FormField
  369. control={createForm.control}
  370. name="contactEmail"
  371. render={({ field }) => (
  372. <FormItem>
  373. <FormLabel>联系邮箱</FormLabel>
  374. <FormControl>
  375. <Input
  376. placeholder="请输入联系邮箱"
  377. value={field.value || ''}
  378. onChange={field.onChange}
  379. onBlur={field.onBlur}
  380. name={field.name}
  381. ref={field.ref}
  382. data-testid="contact-email-input"
  383. />
  384. </FormControl>
  385. <FormMessage />
  386. </FormItem>
  387. )}
  388. />
  389. <DialogFooter>
  390. <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
  391. 取消
  392. </Button>
  393. <Button type="submit" disabled={createMutation.isPending} data-testid="create-submit-button">
  394. 创建
  395. </Button>
  396. </DialogFooter>
  397. </form>
  398. </Form>
  399. ) : (
  400. <Form {...updateForm}>
  401. <form onSubmit={updateForm.handleSubmit(handleUpdateSubmit)} className="space-y-4">
  402. <FormField
  403. control={updateForm.control}
  404. name="platformName"
  405. render={({ field }) => (
  406. <FormItem>
  407. <FormLabel className="flex items-center">
  408. 平台名称 <span className="text-red-500 ml-1">*</span>
  409. </FormLabel>
  410. <FormControl>
  411. <Input placeholder="请输入平台名称" {...field} data-testid="platform-name-input" />
  412. </FormControl>
  413. <FormMessage />
  414. </FormItem>
  415. )}
  416. />
  417. <FormField
  418. control={updateForm.control}
  419. name="contactPerson"
  420. render={({ field }) => (
  421. <FormItem>
  422. <FormLabel>联系人</FormLabel>
  423. <FormControl>
  424. <Input placeholder="请输入联系人姓名" {...field} data-testid="contact-person-input" />
  425. </FormControl>
  426. <FormMessage />
  427. </FormItem>
  428. )}
  429. />
  430. <FormField
  431. control={updateForm.control}
  432. name="contactPhone"
  433. render={({ field }) => (
  434. <FormItem>
  435. <FormLabel>联系电话</FormLabel>
  436. <FormControl>
  437. <Input placeholder="请输入联系电话" {...field} data-testid="contact-phone-input" />
  438. </FormControl>
  439. <FormMessage />
  440. </FormItem>
  441. )}
  442. />
  443. <FormField
  444. control={updateForm.control}
  445. name="contactEmail"
  446. render={({ field }) => (
  447. <FormItem>
  448. <FormLabel>联系邮箱</FormLabel>
  449. <FormControl>
  450. <Input
  451. placeholder="请输入联系邮箱"
  452. value={field.value || ''}
  453. onChange={field.onChange}
  454. onBlur={field.onBlur}
  455. name={field.name}
  456. ref={field.ref}
  457. data-testid="contact-email-input"
  458. />
  459. </FormControl>
  460. <FormMessage />
  461. </FormItem>
  462. )}
  463. />
  464. <DialogFooter>
  465. <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
  466. 取消
  467. </Button>
  468. <Button type="submit" disabled={updateMutation.isPending} data-testid="update-submit-button">
  469. 更新
  470. </Button>
  471. </DialogFooter>
  472. </form>
  473. </Form>
  474. )}
  475. </DialogContent>
  476. </Dialog>
  477. {/* 删除确认对话框 */}
  478. <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
  479. <DialogContent>
  480. <DialogHeader>
  481. <DialogTitle>确认删除</DialogTitle>
  482. <DialogDescription>
  483. 确定要删除这个平台吗?此操作无法撤销。
  484. </DialogDescription>
  485. </DialogHeader>
  486. <DialogFooter>
  487. <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
  488. 取消
  489. </Button>
  490. <Button
  491. variant="destructive"
  492. onClick={confirmDelete}
  493. disabled={deleteMutation.isPending}
  494. data-testid="confirm-delete-button"
  495. >
  496. {deleteMutation.isPending ? '删除中...' : '删除'}
  497. </Button>
  498. </DialogFooter>
  499. </DialogContent>
  500. </Dialog>
  501. </div>
  502. );
  503. };
  504. export default PlatformManagement;