Logs.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. import React, { useState } from 'react';
  2. import { Table, Button, Space, Input, Form, DatePicker, Select, Collapse, Row, Col } 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 UserSelect from '@/client/admin/components/UserSelect';
  7. import type { InferResponseType } from 'hono/client';
  8. import dayjs from 'dayjs';
  9. // 定义类型
  10. type LogfileItem = InferResponseType<typeof operationLogsClient.$get, 200>['data'][0];
  11. type LogfileListResponse = InferResponseType<typeof operationLogsClient.$get, 200>;
  12. const { RangePicker } = DatePicker;
  13. const { Panel } = Collapse;
  14. const Logs: React.FC = () => {
  15. const [form] = Form.useForm();
  16. const [advancedSearchExpanded, setAdvancedSearchExpanded] = useState(false);
  17. // 获取日志列表数据
  18. const fetchLogs = async ({
  19. page = 1,
  20. pageSize = 10,
  21. searchText = '',
  22. filters = {}
  23. }: {
  24. page?: number;
  25. pageSize?: number;
  26. searchText?: string;
  27. filters?: Record<string, any>;
  28. }): Promise<LogfileListResponse> => {
  29. const queryParams: Record<string, any> = { page, pageSize };
  30. if (searchText) queryParams.keyword = searchText;
  31. if (filters.resourceType) queryParams.resourceType = filters.resourceType;
  32. if (filters.action) queryParams.action = filters.action;
  33. if (filters.method) queryParams.method = filters.method;
  34. if (filters.endpoint) queryParams.endpoint = filters.endpoint;
  35. if (filters.userId) queryParams.userId = filters.userId;
  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. ipAddress: values.ipAddress,
  149. status: values.status,
  150. dateRange: values.dateRange
  151. }
  152. });
  153. },
  154. staleTime: 1000 * 60 * 5, // 5分钟缓存
  155. gcTime: 1000 * 60 * 30, // 30分钟垃圾回收
  156. });
  157. // 处理搜索
  158. const handleSearch = () => {
  159. refetch();
  160. };
  161. // 处理过滤
  162. const handleFilterChange = () => {
  163. refetch();
  164. };
  165. // 处理分页变化
  166. const handleTableChange = (pagination: any) => {
  167. form.setFieldsValue({ pagination });
  168. refetch();
  169. };
  170. // 重置过滤条件
  171. const handleResetFilters = () => {
  172. form.resetFields();
  173. refetch();
  174. };
  175. return (
  176. <div className="p-4">
  177. <div className="mb-6 flex justify-between items-center">
  178. <h2 className="text-2xl font-bold">系统日志管理</h2>
  179. </div>
  180. <div className="bg-white p-3 mb-4 rounded-lg shadow-sm transition-all duration-300 hover:shadow-md">
  181. <Form
  182. form={form}
  183. onValuesChange={handleFilterChange}
  184. initialValues={{
  185. pagination: {
  186. current: 1,
  187. pageSize: 10
  188. }
  189. }}
  190. layout="inline"
  191. >
  192. {/* 紧凑搜索区域 */}
  193. <div className="w-full">
  194. <Row gutter={12} align="middle" wrap={false}>
  195. <Col flex="auto">
  196. <Row gutter={12} wrap>
  197. <Col>
  198. <Form.Item name="resourceType" label="资源类型" style={{ marginBottom: 0 }}>
  199. <Select
  200. placeholder="全部类型"
  201. allowClear
  202. className="w-28"
  203. size="small"
  204. popupMatchSelectWidth={false}
  205. >
  206. <Select.Option value="user">用户</Select.Option>
  207. <Select.Option value="client">客户</Select.Option>
  208. <Select.Option value="contract">合同</Select.Option>
  209. <Select.Option value="permission">权限</Select.Option>
  210. <Select.Option value="role">角色</Select.Option>
  211. </Select>
  212. </Form.Item>
  213. </Col>
  214. <Col>
  215. <Form.Item name="action" label="操作" style={{ marginBottom: 0 }}>
  216. <Select
  217. placeholder="全部操作"
  218. allowClear
  219. className="w-28"
  220. size="small"
  221. popupMatchSelectWidth={false}
  222. >
  223. <Select.Option value="create">创建</Select.Option>
  224. <Select.Option value="update">更新</Select.Option>
  225. <Select.Option value="delete">删除</Select.Option>
  226. <Select.Option value="view">查看</Select.Option>
  227. <Select.Option value="login">登录</Select.Option>
  228. <Select.Option value="logout">登出</Select.Option>
  229. </Select>
  230. </Form.Item>
  231. </Col>
  232. <Col>
  233. <Form.Item name="status" label="状态" style={{ marginBottom: 0 }}>
  234. <Select placeholder="全部状态" allowClear className="w-24" size="small">
  235. <Select.Option value="success">成功</Select.Option>
  236. <Select.Option value="failed">失败</Select.Option>
  237. <Select.Option value="permission_denied">拒绝</Select.Option>
  238. </Select>
  239. </Form.Item>
  240. </Col>
  241. <Col>
  242. <Form.Item name="method" label="方法" style={{ marginBottom: 0 }}>
  243. <Select placeholder="全部" allowClear className="w-20" size="small">
  244. <Select.Option value="GET">GET</Select.Option>
  245. <Select.Option value="POST">POST</Select.Option>
  246. <Select.Option value="PUT">PUT</Select.Option>
  247. <Select.Option value="DELETE">DELETE</Select.Option>
  248. <Select.Option value="PATCH">PATCH</Select.Option>
  249. </Select>
  250. </Form.Item>
  251. </Col>
  252. <Col>
  253. <Form.Item name="searchText" style={{ marginBottom: 0 }}>
  254. <Input
  255. placeholder="关键词:日志内容、ID等"
  256. prefix={<SearchOutlined />}
  257. onPressEnter={handleSearch}
  258. allowClear
  259. className="w-48"
  260. size="small"
  261. />
  262. </Form.Item>
  263. </Col>
  264. </Row>
  265. </Col>
  266. <Col>
  267. <Space size={8}>
  268. <Button
  269. type="primary"
  270. icon={<FilterOutlined />}
  271. onClick={handleFilterChange}
  272. size="small"
  273. >
  274. 查询
  275. </Button>
  276. <Button
  277. onClick={handleResetFilters}
  278. size="small"
  279. >
  280. 重置
  281. </Button>
  282. <Button
  283. type="link"
  284. size="small"
  285. icon={advancedSearchExpanded ? <DownOutlined /> : <RightOutlined />}
  286. onClick={() => setAdvancedSearchExpanded(!advancedSearchExpanded)}
  287. >
  288. {advancedSearchExpanded ? '收起' : '高级'}
  289. </Button>
  290. </Space>
  291. </Col>
  292. </Row>
  293. {/* 高级搜索条件 - 直接展开显示 */}
  294. {advancedSearchExpanded && (
  295. <div className="mt-2 pt-2 border-t border-gray-100">
  296. <Row gutter={12} wrap>
  297. <Col>
  298. <Form.Item name="dateRange" label="操作时间" style={{ marginBottom: 0 }}>
  299. <RangePicker
  300. format="YYYY-MM-DD"
  301. className="w-56"
  302. allowClear
  303. size="small"
  304. placeholder={['开始日期', '结束日期']}
  305. />
  306. </Form.Item>
  307. </Col>
  308. <Col>
  309. <Form.Item name="userId" label="操作用户" style={{ marginBottom: 0 }}>
  310. <UserSelect
  311. placeholder="选择用户"
  312. className="w-36"
  313. style={{ fontSize: 12 }}
  314. />
  315. </Form.Item>
  316. </Col>
  317. <Col>
  318. <Form.Item name="ipAddress" label="IP地址" style={{ marginBottom: 0 }}>
  319. <Input
  320. placeholder="IP地址"
  321. allowClear
  322. className="w-28"
  323. size="small"
  324. />
  325. </Form.Item>
  326. </Col>
  327. <Col>
  328. <Form.Item name="endpoint" label="API端点" style={{ marginBottom: 0 }}>
  329. <Input
  330. placeholder="API端点"
  331. allowClear
  332. className="w-36"
  333. size="small"
  334. />
  335. </Form.Item>
  336. </Col>
  337. </Row>
  338. </div>
  339. )}
  340. </div>
  341. </Form>
  342. </div>
  343. <div className="bg-white p-6 mb-6 rounded-lg shadow-sm transition-all duration-300 hover:shadow-md">
  344. <Table
  345. columns={columns}
  346. dataSource={data?.data || []}
  347. rowKey="id"
  348. loading={isLoading}
  349. pagination={{
  350. current: data?.pagination.current || 1,
  351. pageSize: data?.pagination.pageSize || 10,
  352. total: data?.pagination.total || 0,
  353. showSizeChanger: true,
  354. showQuickJumper: true,
  355. showTotal: (total) => `共 ${total} 条记录`
  356. }}
  357. onChange={handleTableChange}
  358. bordered
  359. size="middle"
  360. scroll={{ x: 'max-content' }}
  361. rowClassName={(record, index) => index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}
  362. />
  363. </div>
  364. </div>
  365. );
  366. };
  367. export default Logs;