Activities.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. import React from 'react';
  2. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  3. import { Button } from '@/client/components/ui/button';
  4. import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/client/components/ui/card';
  5. import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/client/components/ui/table';
  6. import { DataTablePagination } from '../components/DataTablePagination';
  7. import { Plus, Edit, Trash2, Calendar, Search, Filter, Power } from 'lucide-react';
  8. import { useState, useCallback } from 'react';
  9. import { activityClient } from '@/client/api';
  10. import type { InferResponseType, InferRequestType } from 'hono/client';
  11. import { Input } from '@/client/components/ui/input';
  12. import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/client/components/ui/select';
  13. import { Badge } from '@/client/components/ui/badge';
  14. import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/client/components/ui/dialog';
  15. import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/client/components/ui/alert-dialog';
  16. import { ActivityForm } from '../components/ActivityForm';
  17. import type { CreateActivityInput, UpdateActivityInput } from '@d8d/server/modules/activities/activity.schema';
  18. import { LocationSelect } from '../components/LocationSelect';
  19. // 类型提取规范
  20. type ActivityResponse = InferResponseType<typeof activityClient.$get, 200>['data'][0];
  21. type CreateActivityRequest = InferRequestType<typeof activityClient.$post>['json'];
  22. type UpdateActivityRequest = InferRequestType<typeof activityClient[':id']['$put']>['json'];
  23. // 统一操作处理函数
  24. const handleOperation = async (operation: () => Promise<any>) => {
  25. try {
  26. await operation();
  27. // toast.success('操作成功');
  28. console.log('操作成功');
  29. } catch (error) {
  30. console.error('操作失败:', error);
  31. // toast.error('操作失败,请重试');
  32. throw error;
  33. }
  34. };
  35. // 防抖搜索函数
  36. const debounce = (func: Function, delay: number) => {
  37. let timeoutId: NodeJS.Timeout;
  38. return (...args: any[]) => {
  39. clearTimeout(timeoutId);
  40. timeoutId = setTimeout(() => func(...args), delay);
  41. };
  42. };
  43. export const ActivitiesPage: React.FC = () => {
  44. const queryClient = useQueryClient();
  45. const [page, setPage] = useState(1);
  46. const [pageSize, setPageSize] = useState(20);
  47. const [keyword, setKeyword] = useState('');
  48. const [typeFilter, setTypeFilter] = useState<string>('all');
  49. const [locationFilter, setLocationFilter] = useState<number | undefined>(undefined);
  50. const [isFormOpen, setIsFormOpen] = useState(false);
  51. const [editingActivity, setEditingActivity] = useState<ActivityResponse | null>(null);
  52. const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
  53. const [activityToDelete, setActivityToDelete] = useState<ActivityResponse | null>(null);
  54. const [statusConfirmOpen, setStatusConfirmOpen] = useState(false);
  55. const [activityToToggle, setActivityToToggle] = useState<ActivityResponse | null>(null);
  56. // 防抖搜索
  57. const debouncedSearch = useCallback(
  58. debounce((searchKeyword: string) => {
  59. setKeyword(searchKeyword);
  60. setPage(1); // 搜索时重置到第一页
  61. }, 300),
  62. []
  63. );
  64. // 获取活动列表 - 使用RPC客户端
  65. const { data, isLoading, error } = useQuery({
  66. queryKey: ['activities', page, pageSize, keyword, typeFilter, locationFilter],
  67. queryFn: async () => {
  68. const query: any = {
  69. page,
  70. pageSize
  71. };
  72. if (keyword) {
  73. query.keyword = keyword;
  74. }
  75. const filters: any = {};
  76. if (typeFilter !== 'all') {
  77. filters.type = typeFilter;
  78. }
  79. if (locationFilter) {
  80. filters.venueLocationId = locationFilter;
  81. }
  82. if (Object.keys(filters).length > 0) {
  83. query.filters = JSON.stringify(filters);
  84. }
  85. const res = await activityClient.$get({
  86. query
  87. });
  88. if (res.status !== 200) throw new Error('获取活动列表失败');
  89. return await res.json();
  90. },
  91. staleTime: 5 * 60 * 1000, // 5分钟缓存
  92. });
  93. // 创建活动 - 使用RPC客户端
  94. const createMutation = useMutation({
  95. mutationFn: async (data: CreateActivityRequest) => {
  96. await handleOperation(async () => {
  97. const res = await activityClient.$post({ json: data });
  98. if (res.status !== 201) throw new Error('创建活动失败');
  99. });
  100. },
  101. onSuccess: () => {
  102. queryClient.invalidateQueries({ queryKey: ['activities'] });
  103. setIsFormOpen(false);
  104. },
  105. });
  106. // 更新活动 - 使用RPC客户端
  107. const updateMutation = useMutation({
  108. mutationFn: async ({ id, data }: { id: number; data: UpdateActivityRequest }) => {
  109. await handleOperation(async () => {
  110. const res = await activityClient[':id'].$put({
  111. param: { id },
  112. json: data
  113. });
  114. if (res.status !== 200) throw new Error('更新活动失败');
  115. });
  116. },
  117. onSuccess: () => {
  118. queryClient.invalidateQueries({ queryKey: ['activities'] });
  119. setIsFormOpen(false);
  120. setEditingActivity(null);
  121. },
  122. });
  123. // 启用/禁用活动 - 使用RPC客户端
  124. const toggleStatusMutation = useMutation({
  125. mutationFn: async ({ id, isDisabled }: { id: number; isDisabled: number }) => {
  126. await handleOperation(async () => {
  127. const res = await activityClient[':id'].$put({
  128. param: { id },
  129. json: { isDisabled }
  130. });
  131. if (res.status !== 200) throw new Error('更新活动状态失败');
  132. });
  133. },
  134. onSuccess: () => {
  135. queryClient.invalidateQueries({ queryKey: ['activities'] });
  136. },
  137. });
  138. // 删除活动 - 使用RPC客户端
  139. const deleteMutation = useMutation({
  140. mutationFn: async (id: number) => {
  141. await handleOperation(async () => {
  142. const res = await activityClient[':id'].$delete({
  143. param: { id }
  144. });
  145. if (res.status !== 204) throw new Error('删除活动失败');
  146. });
  147. },
  148. onSuccess: () => {
  149. queryClient.invalidateQueries({ queryKey: ['activities'] });
  150. },
  151. });
  152. // 处理表单提交
  153. const handleFormSubmit = async (data: CreateActivityInput | UpdateActivityInput) => {
  154. if (editingActivity) {
  155. await updateMutation.mutateAsync({
  156. id: editingActivity.id,
  157. data: data as UpdateActivityRequest
  158. });
  159. } else {
  160. await createMutation.mutateAsync(data as CreateActivityRequest);
  161. }
  162. };
  163. // 打开创建表单
  164. const handleCreate = () => {
  165. setEditingActivity(null);
  166. setIsFormOpen(true);
  167. };
  168. // 打开编辑表单
  169. const handleEdit = (activity: ActivityResponse) => {
  170. setEditingActivity(activity);
  171. setIsFormOpen(true);
  172. };
  173. // 关闭表单
  174. const handleFormClose = () => {
  175. setIsFormOpen(false);
  176. setEditingActivity(null);
  177. };
  178. // 切换活动状态
  179. const handleToggleStatus = (activity: ActivityResponse) => {
  180. setActivityToToggle(activity);
  181. setStatusConfirmOpen(true);
  182. };
  183. if (error) {
  184. return (
  185. <div className="p-6">
  186. <Card>
  187. <CardContent className="pt-6">
  188. <div className="text-center text-red-500">
  189. 加载活动数据失败: {error.message}
  190. </div>
  191. </CardContent>
  192. </Card>
  193. </div>
  194. );
  195. }
  196. return (
  197. <div className="p-6">
  198. <div className="flex items-center justify-between mb-6">
  199. <div>
  200. <h1 className="text-3xl font-bold tracking-tight" data-testid="activity-management-title">活动管理</h1>
  201. <p className="text-muted-foreground">
  202. 管理旅行活动,包括去程和返程活动
  203. </p>
  204. </div>
  205. <Button onClick={handleCreate} data-testid="create-activity-button">
  206. <Plus className="h-4 w-4 mr-2" />
  207. 新建活动
  208. </Button>
  209. </div>
  210. <Card>
  211. <CardHeader>
  212. <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
  213. <div>
  214. <CardTitle>活动列表</CardTitle>
  215. <CardDescription>
  216. 当前共有 {data?.pagination.total || 0} 个活动
  217. </CardDescription>
  218. </div>
  219. <div className="flex gap-2">
  220. {/* 搜索框 */}
  221. <div className="relative w-full sm:w-64">
  222. <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
  223. <Input
  224. placeholder="搜索活动名称或描述..."
  225. className="pl-8"
  226. onChange={(e) => debouncedSearch(e.target.value)}
  227. data-testid="activity-search-input"
  228. />
  229. </div>
  230. {/* 类型筛选 */}
  231. <Select value={typeFilter} onValueChange={setTypeFilter}>
  232. <SelectTrigger className="w-32" data-testid="activity-type-filter">
  233. <Filter className="h-4 w-4 mr-2" />
  234. <SelectValue placeholder="类型" />
  235. </SelectTrigger>
  236. <SelectContent>
  237. <SelectItem value="all">全部类型</SelectItem>
  238. <SelectItem value="departure">去程</SelectItem>
  239. <SelectItem value="return">返程</SelectItem>
  240. </SelectContent>
  241. </Select>
  242. {/* 地点筛选 */}
  243. <LocationSelect
  244. value={locationFilter}
  245. onValueChange={setLocationFilter}
  246. placeholder="选择地点..."
  247. />
  248. </div>
  249. </div>
  250. </CardHeader>
  251. <CardContent>
  252. {/* 筛选标签 */}
  253. {(keyword || typeFilter !== 'all' || locationFilter) && (
  254. <div className="flex flex-wrap gap-2 mb-4">
  255. {keyword && (
  256. <Badge variant="secondary" className="flex items-center gap-1">
  257. 搜索: {keyword}
  258. <button
  259. onClick={() => {
  260. setKeyword('');
  261. const input = document.querySelector('input[placeholder="搜索活动名称或描述..."]') as HTMLInputElement;
  262. if (input) input.value = '';
  263. }}
  264. className="ml-1 hover:text-red-500"
  265. >
  266. ×
  267. </button>
  268. </Badge>
  269. )}
  270. {typeFilter !== 'all' && (
  271. <Badge variant="secondary" className="flex items-center gap-1">
  272. 类型: {typeFilter === 'departure' ? '去程' : '返程'}
  273. <button
  274. onClick={() => setTypeFilter('all')}
  275. className="ml-1 hover:text-red-500"
  276. >
  277. ×
  278. </button>
  279. </Badge>
  280. )}
  281. {locationFilter && (
  282. <Badge variant="secondary" className="flex items-center gap-1">
  283. 地点: {data?.data?.find((a: ActivityResponse) => a.venueLocationId === locationFilter)?.venueLocation?.name || '未知地点'}
  284. <button
  285. onClick={() => setLocationFilter(undefined)}
  286. className="ml-1 hover:text-red-500"
  287. >
  288. ×
  289. </button>
  290. </Badge>
  291. )}
  292. </div>
  293. )}
  294. <div className="rounded-md border">
  295. <Table data-testid="activity-table">
  296. <TableHeader>
  297. <TableRow>
  298. <TableHead>活动名称</TableHead>
  299. <TableHead>类型</TableHead>
  300. <TableHead>举办地点</TableHead>
  301. <TableHead>开始时间</TableHead>
  302. <TableHead>结束时间</TableHead>
  303. <TableHead>状态</TableHead>
  304. <TableHead className="text-right">操作</TableHead>
  305. </TableRow>
  306. </TableHeader>
  307. <TableBody>
  308. {isLoading ? (
  309. <TableRow>
  310. <TableCell colSpan={7} className="text-center py-4">
  311. 加载中...
  312. </TableCell>
  313. </TableRow>
  314. ) : data?.data && data.data.length > 0 ? (
  315. data.data.map((activity: ActivityResponse) => (
  316. <TableRow key={activity.id}>
  317. <TableCell>
  318. <div className="flex items-center gap-2">
  319. <Calendar className="h-4 w-4 text-blue-500" />
  320. <span>{activity.name}</span>
  321. </div>
  322. </TableCell>
  323. <TableCell>
  324. <span className={`px-2 py-1 rounded-full text-xs ${
  325. activity.type === 'departure'
  326. ? 'bg-blue-100 text-blue-800'
  327. : 'bg-green-100 text-green-800'
  328. }`}>
  329. {activity.type === 'departure' ? '去程' : '返程'}
  330. </span>
  331. </TableCell>
  332. <TableCell>
  333. {activity.venueLocation ? (
  334. <div className="flex flex-col">
  335. <span className="font-medium">{activity.venueLocation.name}</span>
  336. <span className="text-xs text-muted-foreground">
  337. {activity.venueLocation.address}
  338. </span>
  339. </div>
  340. ) : (
  341. <span className="text-muted-foreground">未设置地点</span>
  342. )}
  343. </TableCell>
  344. <TableCell>
  345. {new Date(activity.startDate).toLocaleString('zh-CN')}
  346. </TableCell>
  347. <TableCell>
  348. {new Date(activity.endDate).toLocaleString('zh-CN')}
  349. </TableCell>
  350. <TableCell>
  351. <span className={`px-2 py-1 rounded-full text-xs ${
  352. activity.isDisabled === 0
  353. ? 'bg-green-100 text-green-800'
  354. : 'bg-red-100 text-red-800'
  355. }`}>
  356. {activity.isDisabled === 0 ? '启用' : '禁用'}
  357. </span>
  358. </TableCell>
  359. <TableCell className="text-right">
  360. <div className="flex justify-end gap-2">
  361. <Button
  362. variant={activity.isDisabled === 0 ? "outline" : "default"}
  363. size="sm"
  364. onClick={() => handleToggleStatus(activity)}
  365. disabled={toggleStatusMutation.isPending}
  366. data-testid={`toggle-activity-${activity.id}-status`}
  367. >
  368. <Power className="h-4 w-4 mr-1" />
  369. {activity.isDisabled === 0 ? '禁用' : '启用'}
  370. </Button>
  371. <Button
  372. variant="outline"
  373. size="sm"
  374. onClick={() => handleEdit(activity)}
  375. data-testid={`edit-activity-${activity.id}`}
  376. >
  377. <Edit className="h-4 w-4" />
  378. </Button>
  379. <Button
  380. variant="destructive"
  381. size="sm"
  382. onClick={() => {
  383. setActivityToDelete(activity);
  384. setDeleteConfirmOpen(true);
  385. }}
  386. data-testid={`delete-activity-${activity.id}`}
  387. >
  388. <Trash2 className="h-4 w-4" />
  389. </Button>
  390. </div>
  391. </TableCell>
  392. </TableRow>
  393. ))
  394. ) : (
  395. <TableRow>
  396. <TableCell colSpan={7} className="text-center py-4">
  397. 暂无活动数据
  398. </TableCell>
  399. </TableRow>
  400. )}
  401. </TableBody>
  402. </Table>
  403. </div>
  404. {data && (
  405. <DataTablePagination
  406. currentPage={data.pagination.current}
  407. totalCount={data.pagination.total}
  408. pageSize={data.pagination.pageSize}
  409. onPageChange={(page, pageSize) => {
  410. setPage(page);
  411. setPageSize(pageSize);
  412. }}
  413. />
  414. )}
  415. </CardContent>
  416. </Card>
  417. {/* 活动表单对话框 */}
  418. <Dialog open={isFormOpen} onOpenChange={setIsFormOpen}>
  419. <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
  420. <DialogHeader>
  421. <DialogTitle>
  422. {editingActivity ? '编辑活动' : '创建活动'}
  423. </DialogTitle>
  424. <DialogDescription>
  425. {editingActivity ? '修改活动信息' : '创建新的旅行活动'}
  426. </DialogDescription>
  427. </DialogHeader>
  428. <ActivityForm
  429. initialData={editingActivity ? {
  430. id: editingActivity.id,
  431. name: editingActivity.name,
  432. description: editingActivity.description,
  433. type: editingActivity.type,
  434. startDate: new Date(editingActivity.startDate),
  435. endDate: new Date(editingActivity.endDate),
  436. isDisabled: editingActivity.isDisabled
  437. } : undefined}
  438. onSubmit={handleFormSubmit}
  439. onCancel={handleFormClose}
  440. isLoading={createMutation.isPending || updateMutation.isPending}
  441. />
  442. </DialogContent>
  443. </Dialog>
  444. {/* 删除确认对话框 */}
  445. <AlertDialog open={deleteConfirmOpen} onOpenChange={setDeleteConfirmOpen}>
  446. <AlertDialogContent data-testid="delete-confirm-dialog">
  447. <AlertDialogHeader>
  448. <AlertDialogTitle>确认删除</AlertDialogTitle>
  449. <AlertDialogDescription>
  450. 确定要删除活动 "{activityToDelete?.name}" 吗?此操作不可撤销。
  451. </AlertDialogDescription>
  452. </AlertDialogHeader>
  453. <AlertDialogFooter>
  454. <AlertDialogCancel>取消</AlertDialogCancel>
  455. <AlertDialogAction
  456. onClick={() => {
  457. if (activityToDelete) {
  458. deleteMutation.mutate(activityToDelete.id);
  459. }
  460. setDeleteConfirmOpen(false);
  461. setActivityToDelete(null);
  462. }}
  463. className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
  464. >
  465. 删除
  466. </AlertDialogAction>
  467. </AlertDialogFooter>
  468. </AlertDialogContent>
  469. </AlertDialog>
  470. {/* 启用/禁用确认对话框 */}
  471. <AlertDialog open={statusConfirmOpen} onOpenChange={setStatusConfirmOpen}>
  472. <AlertDialogContent data-testid="status-confirm-dialog">
  473. <AlertDialogHeader>
  474. <AlertDialogTitle>确认状态切换</AlertDialogTitle>
  475. <AlertDialogDescription>
  476. 确定要{activityToToggle?.isDisabled === 0 ? '禁用' : '启用'}活动 "{activityToToggle?.name}" 吗?
  477. </AlertDialogDescription>
  478. </AlertDialogHeader>
  479. <AlertDialogFooter>
  480. <AlertDialogCancel>取消</AlertDialogCancel>
  481. <AlertDialogAction
  482. onClick={() => {
  483. if (activityToToggle) {
  484. const newStatus = activityToToggle.isDisabled === 0 ? 1 : 0;
  485. toggleStatusMutation.mutate({
  486. id: activityToToggle.id,
  487. isDisabled: newStatus
  488. });
  489. }
  490. setStatusConfirmOpen(false);
  491. setActivityToToggle(null);
  492. }}
  493. >
  494. {activityToToggle?.isDisabled === 0 ? '禁用' : '启用'}
  495. </AlertDialogAction>
  496. </AlertDialogFooter>
  497. </AlertDialogContent>
  498. </AlertDialog>
  499. </div>
  500. );
  501. };