Reports.tsx 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. import { useEffect, useState, useCallback } from 'react';
  2. import {
  3. Table,
  4. Button,
  5. Space,
  6. Modal,
  7. message,
  8. Typography,
  9. Tooltip,
  10. Popconfirm,
  11. Card,
  12. Descriptions,
  13. Tag,
  14. Empty
  15. } from 'antd';
  16. import {
  17. DownloadOutlined,
  18. DeleteOutlined,
  19. ReloadOutlined,
  20. EyeOutlined,
  21. FileWordOutlined,
  22. CheckCircleOutlined
  23. } from '@ant-design/icons';
  24. import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
  25. import type { Report } from '../types';
  26. import { reportService } from '../services/reports';
  27. import { usePagination } from '../hooks/usePagination';
  28. import { formatDateTime } from '../utils';
  29. const { Title, Text } = Typography;
  30. export default function Reports() {
  31. const [reports, setReports] = useState<Report[]>([]);
  32. const [loading, setLoading] = useState(false);
  33. const [detailModalVisible, setDetailModalVisible] = useState(false);
  34. const [selectedReport, setSelectedReport] = useState<Report | null>(null);
  35. const [deleting, setDeleting] = useState<number | null>(null);
  36. const [downloading, setDownloading] = useState<number | null>(null);
  37. const pagination = usePagination(10);
  38. // Fetch reports with specific page/pageSize
  39. const fetchReportsWithParams = useCallback(async (page: number, pageSize: number) => {
  40. try {
  41. setLoading(true);
  42. const response = await reportService.getReports({
  43. page,
  44. pageSize,
  45. });
  46. setReports(response.data);
  47. pagination.setTotal(response.pagination.total);
  48. } catch (error) {
  49. message.error('Failed to load reports');
  50. } finally {
  51. setLoading(false);
  52. }
  53. // eslint-disable-next-line react-hooks/exhaustive-deps
  54. }, []);
  55. // Wrapper for refresh button
  56. const fetchReports = useCallback(() => {
  57. fetchReportsWithParams(pagination.page, pagination.pageSize);
  58. }, [fetchReportsWithParams, pagination.page, pagination.pageSize]);
  59. // Initial load only
  60. useEffect(() => {
  61. fetchReportsWithParams(pagination.page, pagination.pageSize);
  62. // eslint-disable-next-line react-hooks/exhaustive-deps
  63. }, []);
  64. // Handle table pagination change
  65. const handleTableChange = async (paginationConfig: TablePaginationConfig) => {
  66. const newPage = paginationConfig.current ?? pagination.page;
  67. const newPageSize = paginationConfig.pageSize ?? pagination.pageSize;
  68. pagination.setPage(newPage);
  69. if (newPageSize !== pagination.pageSize) {
  70. pagination.setPageSize(newPageSize);
  71. }
  72. // Directly fetch with new params
  73. await fetchReportsWithParams(newPage, newPageSize);
  74. };
  75. // Format file size
  76. const formatFileSize = (bytes: number): string => {
  77. if (bytes === 0) return '0 Bytes';
  78. const k = 1024;
  79. const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  80. const i = Math.floor(Math.log(bytes) / Math.log(k));
  81. return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  82. };
  83. // Handle view report detail
  84. const handleViewReport = async (report: Report) => {
  85. try {
  86. const detail = await reportService.getReportDetail(report.id);
  87. setSelectedReport(detail);
  88. setDetailModalVisible(true);
  89. } catch (error) {
  90. message.error('Failed to load report details');
  91. }
  92. };
  93. // Handle download report
  94. const handleDownloadReport = async (report: Report) => {
  95. try {
  96. setDownloading(report.id);
  97. const blob = await reportService.downloadReport(report.id);
  98. // Create download link
  99. const url = window.URL.createObjectURL(blob);
  100. const link = document.createElement('a');
  101. link.href = url;
  102. link.download = report.file_name || `report-${report.id}.docx`;
  103. document.body.appendChild(link);
  104. link.click();
  105. document.body.removeChild(link);
  106. window.URL.revokeObjectURL(url);
  107. message.success('Report downloaded successfully');
  108. } catch (error) {
  109. message.error('Failed to download report');
  110. } finally {
  111. setDownloading(null);
  112. }
  113. };
  114. // Handle delete report
  115. const handleDeleteReport = async (reportId: number) => {
  116. try {
  117. setDeleting(reportId);
  118. await reportService.deleteReport(reportId);
  119. message.success('Report deleted successfully');
  120. fetchReports();
  121. } catch (error: unknown) {
  122. const err = error as { response?: { data?: { error?: { message?: string } } } };
  123. message.error(err.response?.data?.error?.message || 'Failed to delete report');
  124. } finally {
  125. setDeleting(null);
  126. }
  127. };
  128. // Table columns
  129. const columns: ColumnsType<Report> = [
  130. {
  131. title: 'ID',
  132. dataIndex: 'id',
  133. key: 'id',
  134. width: 80
  135. },
  136. {
  137. title: 'File Name',
  138. dataIndex: 'file_name',
  139. key: 'file_name',
  140. ellipsis: true,
  141. render: (fileName: string) => (
  142. <Space>
  143. <FileWordOutlined style={{ color: '#2b579a' }} />
  144. <Text ellipsis style={{ maxWidth: 300 }}>{fileName}</Text>
  145. </Space>
  146. ),
  147. },
  148. {
  149. title: 'Task ID',
  150. dataIndex: 'task_id',
  151. key: 'task_id',
  152. width: 100,
  153. render: (taskId: number) => (
  154. <Tag color="blue">#{taskId}</Tag>
  155. ),
  156. },
  157. {
  158. title: 'File Size',
  159. dataIndex: 'file_size',
  160. key: 'file_size',
  161. width: 120,
  162. render: (size: number) => formatFileSize(size),
  163. },
  164. {
  165. title: 'Created At',
  166. dataIndex: 'created_at',
  167. key: 'created_at',
  168. width: 180,
  169. render: (date: string) => formatDateTime(date),
  170. },
  171. {
  172. title: 'Actions',
  173. key: 'actions',
  174. width: 180,
  175. render: (_: unknown, record: Report) => (
  176. <Space>
  177. <Tooltip title="View Details">
  178. <Button
  179. size="small"
  180. icon={<EyeOutlined />}
  181. onClick={() => handleViewReport(record)}
  182. />
  183. </Tooltip>
  184. <Tooltip title="Download">
  185. <Button
  186. size="small"
  187. type="primary"
  188. icon={<DownloadOutlined />}
  189. loading={downloading === record.id}
  190. onClick={() => handleDownloadReport(record)}
  191. />
  192. </Tooltip>
  193. <Popconfirm
  194. title="Delete Report"
  195. description="Are you sure you want to delete this report?"
  196. onConfirm={() => handleDeleteReport(record.id)}
  197. okText="Yes"
  198. cancelText="No"
  199. >
  200. <Tooltip title="Delete">
  201. <Button
  202. size="small"
  203. danger
  204. icon={<DeleteOutlined />}
  205. loading={deleting === record.id}
  206. />
  207. </Tooltip>
  208. </Popconfirm>
  209. </Space>
  210. ),
  211. },
  212. ];
  213. return (
  214. <div>
  215. <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
  216. <Title level={2} style={{ margin: 0 }}>Reports</Title>
  217. <Button
  218. icon={<ReloadOutlined />}
  219. onClick={fetchReports}
  220. loading={loading}
  221. >
  222. Refresh
  223. </Button>
  224. </div>
  225. <Table
  226. columns={columns}
  227. dataSource={reports}
  228. rowKey="id"
  229. loading={loading}
  230. pagination={{
  231. current: pagination.page,
  232. pageSize: pagination.pageSize,
  233. total: pagination.total,
  234. showSizeChanger: true,
  235. showQuickJumper: false,
  236. pageSizeOptions: ['10', '20', '50', '100'],
  237. showTotal: (total: number) => `Total ${total} reports`,
  238. }}
  239. onChange={handleTableChange}
  240. locale={{
  241. emptyText: (
  242. <Empty
  243. image={Empty.PRESENTED_IMAGE_SIMPLE}
  244. description="No reports found"
  245. />
  246. ),
  247. }}
  248. />
  249. {/* Report Detail Modal */}
  250. <Modal
  251. title={
  252. <Space>
  253. <FileWordOutlined style={{ color: '#2b579a' }} />
  254. <span>Report Details</span>
  255. </Space>
  256. }
  257. open={detailModalVisible}
  258. onCancel={() => {
  259. setDetailModalVisible(false);
  260. setSelectedReport(null);
  261. }}
  262. footer={
  263. <Space>
  264. <Button onClick={() => setDetailModalVisible(false)}>
  265. Close
  266. </Button>
  267. {selectedReport && (
  268. <Button
  269. type="primary"
  270. icon={<DownloadOutlined />}
  271. loading={downloading === selectedReport.id}
  272. onClick={() => handleDownloadReport(selectedReport)}
  273. >
  274. Download
  275. </Button>
  276. )}
  277. </Space>
  278. }
  279. width={600}
  280. >
  281. {selectedReport && (
  282. <Card size="small">
  283. <Descriptions column={1} size="small" bordered>
  284. <Descriptions.Item label="Report ID">
  285. {selectedReport.id}
  286. </Descriptions.Item>
  287. <Descriptions.Item label="File Name">
  288. <Space>
  289. <FileWordOutlined style={{ color: '#2b579a' }} />
  290. {selectedReport.file_name}
  291. </Space>
  292. </Descriptions.Item>
  293. <Descriptions.Item label="Task ID">
  294. <Tag color="blue">#{selectedReport.task_id}</Tag>
  295. </Descriptions.Item>
  296. <Descriptions.Item label="File Size">
  297. {formatFileSize(selectedReport.file_size)}
  298. </Descriptions.Item>
  299. <Descriptions.Item label="File Path">
  300. <Text type="secondary" copyable>
  301. {selectedReport.file_path}
  302. </Text>
  303. </Descriptions.Item>
  304. <Descriptions.Item label="Created At">
  305. {formatDateTime(selectedReport.created_at)}
  306. </Descriptions.Item>
  307. <Descriptions.Item label="Status">
  308. <Tag color="success" icon={<CheckCircleOutlined />}>
  309. Available
  310. </Tag>
  311. </Descriptions.Item>
  312. </Descriptions>
  313. </Card>
  314. )}
  315. </Modal>
  316. </div>
  317. );
  318. }