Logs.tsx 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. import React, { useState } from 'react';
  2. import { Table, Button, Space, Input, Form, DatePicker, Select, Collapse } from 'antd';
  3. import { SearchOutlined, FilterOutlined, DownOutlined, RightOutlined } from '@ant-design/icons';
  4. import { useQuery } from '@tanstack/react-query';
  5. import { operationLogsClient } from '@/client/api';
  6. import type { InferResponseType } from 'hono/client';
  7. import dayjs from 'dayjs';
  8. // 定义类型
  9. type LogfileItem = InferResponseType<typeof operationLogsClient.$get, 200>['data'][0];
  10. type LogfileListResponse = InferResponseType<typeof operationLogsClient.$get, 200>;
  11. const { RangePicker } = DatePicker;
  12. const { Panel } = Collapse;
  13. const Logs: React.FC = () => {
  14. const [form] = Form.useForm();
  15. const [advancedSearchExpanded, setAdvancedSearchExpanded] = useState(false);
  16. // 获取日志列表数据
  17. const fetchLogs = async ({
  18. page = 1,
  19. pageSize = 10,
  20. searchText = '',
  21. filters = {}
  22. }: {
  23. page?: number;
  24. pageSize?: number;
  25. searchText?: string;
  26. filters?: Record<string, any>;
  27. }): Promise<LogfileListResponse> => {
  28. const queryParams: Record<string, any> = { page, pageSize };
  29. if (searchText) queryParams.keyword = searchText;
  30. if (filters.resourceType) queryParams.resourceType = filters.resourceType;
  31. if (filters.action) queryParams.action = filters.action;
  32. if (filters.method) queryParams.method = filters.method;
  33. if (filters.endpoint) queryParams.endpoint = filters.endpoint;
  34. if (filters.userId) queryParams.userId = filters.userId;
  35. if (filters.username) queryParams.username = filters.username;
  36. if (filters.ipAddress) queryParams.ipAddress = filters.ipAddress;
  37. if (filters.status) queryParams.status = filters.status;
  38. if (filters.dateRange?.[0]) queryParams.startDate = filters.dateRange[0].format('YYYY-MM-DD');
  39. if (filters.dateRange?.[1]) queryParams.endDate = filters.dateRange[1].format('YYYY-MM-DD');
  40. const response = await operationLogsClient.$get({ query: queryParams });
  41. if (!response.ok) throw new Error('Failed to fetch logs');
  42. return response.json() as Promise<LogfileListResponse>;
  43. };
  44. // 表格列定义
  45. const columns = [
  46. {
  47. title: '日志ID',
  48. dataIndex: 'id',
  49. key: 'id',
  50. width: 80,
  51. },
  52. {
  53. title: '资源类型',
  54. dataIndex: 'resourceType',
  55. key: 'resourceType',
  56. width: 120,
  57. },
  58. {
  59. title: '资源ID',
  60. dataIndex: 'resourceId',
  61. key: 'resourceId',
  62. width: 120,
  63. },
  64. {
  65. title: '操作',
  66. dataIndex: 'action',
  67. key: 'action',
  68. width: 100,
  69. },
  70. {
  71. title: 'HTTP方法',
  72. dataIndex: 'method',
  73. key: 'method',
  74. width: 100,
  75. },
  76. {
  77. title: 'API端点',
  78. dataIndex: 'endpoint',
  79. key: 'endpoint',
  80. width: 200,
  81. },
  82. {
  83. title: '状态',
  84. dataIndex: 'status',
  85. key: 'status',
  86. width: 100,
  87. render: (status: string) => {
  88. switch (status) {
  89. case 'success':
  90. return <span style={{ color: '#52c41a' }}>成功</span>;
  91. case 'failed':
  92. return <span style={{ color: '#ff4d4f' }}>失败</span>;
  93. case 'permission_denied':
  94. return <span style={{ color: '#faad14' }}>权限拒绝</span>;
  95. default:
  96. return status;
  97. }
  98. },
  99. },
  100. {
  101. title: '耗时(ms)',
  102. dataIndex: 'duration',
  103. key: 'duration',
  104. width: 100,
  105. },
  106. {
  107. title: '操作用户ID',
  108. dataIndex: 'userId',
  109. key: 'userId',
  110. width: 100,
  111. },
  112. {
  113. title: '用户名',
  114. dataIndex: 'username',
  115. key: 'username',
  116. width: 120,
  117. },
  118. {
  119. title: 'IP地址',
  120. dataIndex: 'ipAddress',
  121. key: 'ipAddress',
  122. width: 150,
  123. },
  124. {
  125. title: '创建时间',
  126. dataIndex: 'createdAt',
  127. key: 'createdAt',
  128. width: 180,
  129. render: (time: string) => time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-',
  130. },
  131. ];
  132. // 使用React Query v5实现数据获取
  133. const { data, isLoading, refetch } = useQuery({
  134. queryKey: ['logs', form.getFieldsValue(), form.getFieldValue('searchText')],
  135. queryFn: ({ signal }) => {
  136. const values = form.getFieldsValue();
  137. const searchText = form.getFieldValue('searchText') || '';
  138. return fetchLogs({
  139. page: values.pagination?.current || 1,
  140. pageSize: values.pagination?.pageSize || 10,
  141. searchText,
  142. filters: {
  143. resourceType: values.resourceType,
  144. action: values.action,
  145. method: values.method,
  146. endpoint: values.endpoint,
  147. userId: values.userId,
  148. username: values.username,
  149. ipAddress: values.ipAddress,
  150. status: values.status,
  151. dateRange: values.dateRange
  152. }
  153. });
  154. },
  155. staleTime: 1000 * 60 * 5, // 5分钟缓存
  156. gcTime: 1000 * 60 * 30, // 30分钟垃圾回收
  157. });
  158. // 处理搜索
  159. const handleSearch = () => {
  160. refetch();
  161. };
  162. // 处理过滤
  163. const handleFilterChange = () => {
  164. refetch();
  165. };
  166. // 处理分页变化
  167. const handleTableChange = (pagination: any) => {
  168. form.setFieldsValue({ pagination });
  169. refetch();
  170. };
  171. // 重置过滤条件
  172. const handleResetFilters = () => {
  173. form.resetFields();
  174. refetch();
  175. };
  176. return (
  177. <div className="p-4">
  178. <div className="flex justify-between items-center mb-4">
  179. <h2 className="text-xl font-bold">系统日志管理</h2>
  180. </div>
  181. <div className="bg-white p-4 mb-4 rounded-lg shadow-sm">
  182. <Form
  183. form={form}
  184. onValuesChange={handleFilterChange}
  185. initialValues={{
  186. pagination: {
  187. current: 1,
  188. pageSize: 10
  189. }
  190. }}
  191. >
  192. {/* 常用搜索项 */}
  193. <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-2 mb-2">
  194. <Form.Item name="resourceType" label="资源类型" className="mb-1">
  195. <Input placeholder="请输入资源类型" size="small" />
  196. </Form.Item>
  197. <Form.Item name="action" label="操作动作" className="mb-1">
  198. <Input placeholder="请输入操作动作" size="small" />
  199. </Form.Item>
  200. <Form.Item name="status" label="状态" className="mb-1">
  201. <Select placeholder="请选择状态" size="small">
  202. <Select.Option value="">全部</Select.Option>
  203. <Select.Option value="success">成功</Select.Option>
  204. <Select.Option value="failed">失败</Select.Option>
  205. <Select.Option value="permission_denied">权限拒绝</Select.Option>
  206. </Select>
  207. </Form.Item>
  208. <Form.Item name="dateRange" label="操作时间" className="mb-1">
  209. <RangePicker format="YYYY-MM-DD" className="w-full" size="small" />
  210. </Form.Item>
  211. </div>
  212. {/* 高级搜索项折叠面板 */}
  213. <Collapse
  214. ghost
  215. expandIcon={({ isActive }) => isActive ? <DownOutlined /> : <RightOutlined />}
  216. className="mb-3"
  217. >
  218. <Panel header="高级搜索" key="1">
  219. <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-2">
  220. <Form.Item name="method" label="HTTP方法" className="mb-1">
  221. <Input placeholder="请输入HTTP方法" size="small" />
  222. </Form.Item>
  223. <Form.Item name="endpoint" label="API端点" className="mb-1">
  224. <Input placeholder="请输入API端点" size="small" />
  225. </Form.Item>
  226. <Form.Item name="userId" label="操作用户ID" className="mb-1">
  227. <Input placeholder="请输入用户ID" size="small" />
  228. </Form.Item>
  229. <Form.Item name="username" label="用户名" className="mb-1">
  230. <Input placeholder="请输入用户名" size="small" />
  231. </Form.Item>
  232. <Form.Item name="ipAddress" label="IP地址" className="mb-1">
  233. <Input placeholder="请输入IP地址" size="small" />
  234. </Form.Item>
  235. </div>
  236. </Panel>
  237. </Collapse>
  238. {/* 操作按钮和搜索框 */}
  239. <div className="flex flex-col sm:flex-row gap-2">
  240. <div className="flex gap-2">
  241. <Button type="primary" icon={<FilterOutlined />} onClick={handleFilterChange} size="small">
  242. 筛选
  243. </Button>
  244. <Button onClick={handleResetFilters} size="small">
  245. 重置
  246. </Button>
  247. </div>
  248. <div className="flex-grow flex gap-2">
  249. <Form.Item name="searchText" className="flex-grow mb-0">
  250. <Input
  251. placeholder="搜索日志内容"
  252. prefix={<SearchOutlined />}
  253. onPressEnter={handleSearch}
  254. size="small"
  255. />
  256. </Form.Item>
  257. <Button type="default" onClick={handleSearch} size="small">
  258. 搜索
  259. </Button>
  260. </div>
  261. </div>
  262. </Form>
  263. </div>
  264. <Table
  265. columns={columns}
  266. dataSource={data?.data || []}
  267. rowKey="id"
  268. loading={isLoading}
  269. pagination={{
  270. current: data?.pagination.current || 1,
  271. pageSize: data?.pagination.pageSize || 10,
  272. total: data?.pagination.total || 0,
  273. showSizeChanger: true,
  274. showQuickJumper: true,
  275. showTotal: (total) => `共 ${total} 条记录`
  276. }}
  277. onChange={handleTableChange}
  278. bordered
  279. size="middle"
  280. />
  281. </div>
  282. );
  283. };
  284. export default Logs;