ImportDetailDialog.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. 'use client';
  2. import { useState, useEffect, useCallback } from 'react';
  3. import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
  4. import { Button } from '@/components/ui/button';
  5. import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
  6. import { format } from 'date-fns';
  7. import { useToast } from '@/hooks/use-toast';
  8. import { getImportById, triggerImportProcess, getImportProgress } from '@/app/actions/imports';
  9. interface ImportDetail {
  10. id: number;
  11. name: string;
  12. importDate: Date;
  13. layout: {
  14. id: number;
  15. name: string;
  16. sections: Array<{
  17. id: number;
  18. name: string;
  19. tableName: string;
  20. fields: Array<{
  21. id: number;
  22. name: string;
  23. createdAt: Date;
  24. updatedAt: Date;
  25. layoutSectionId: number;
  26. cellPosition: string;
  27. dataType: string;
  28. dataTypeFormat: string | null;
  29. importTableColumnName: string;
  30. importColumnOrderNumber: number;
  31. }>;
  32. }>;
  33. };
  34. file?: {
  35. id: string;
  36. filename: string;
  37. mimetype: string;
  38. size: number;
  39. data: Uint8Array;
  40. userId: string | null;
  41. createdAt: Date;
  42. updatedAt: Date;
  43. } | null;
  44. }
  45. interface ImportDetailDialogProps {
  46. open: boolean;
  47. onOpenChange: (open: boolean) => void;
  48. importId: number;
  49. }
  50. export function ImportDetailDialog({ open, onOpenChange, importId }: ImportDetailDialogProps) {
  51. const [importDetail, setImportDetail] = useState<ImportDetail | null>(null);
  52. const [loading, setLoading] = useState(true);
  53. const [processing, setProcessing] = useState(false);
  54. const [importStatus, setImportStatus] = useState<'idle' | 'processing' | 'completed' | 'failed'>('idle');
  55. const [progress, setProgress] = useState(0);
  56. const [processedRecords, setProcessedRecords] = useState(0);
  57. const [totalRecords, setTotalRecords] = useState(0);
  58. const { toast } = useToast();
  59. const loadImportDetail = useCallback(async () => {
  60. try {
  61. const result = await getImportById(importId);
  62. if (result.success && result.data) {
  63. setImportDetail(result.data);
  64. } else {
  65. toast({
  66. title: 'Error',
  67. description: result.error || 'Failed to load import details',
  68. variant: 'destructive',
  69. });
  70. setImportDetail(null);
  71. }
  72. } catch {
  73. toast({
  74. title: 'Error',
  75. description: 'Failed to load import details',
  76. variant: 'destructive',
  77. });
  78. setImportDetail(null);
  79. } finally {
  80. setLoading(false);
  81. }
  82. }, [importId, toast]);
  83. useEffect(() => {
  84. if (open && importId) {
  85. loadImportDetail();
  86. }
  87. }, [open, importId, loadImportDetail]);
  88. async function handleTriggerImport() {
  89. if (!importDetail?.file) {
  90. toast({
  91. title: 'Error',
  92. description: 'No file attached to this import',
  93. variant: 'destructive',
  94. });
  95. return;
  96. }
  97. setProcessing(true);
  98. setImportStatus('processing');
  99. try {
  100. const result = await triggerImportProcess(importId);
  101. if (result.success) {
  102. toast({
  103. title: 'Success',
  104. description: result.message || 'Import process started successfully',
  105. });
  106. // Poll for import progress until completion
  107. const pollInterval = setInterval(async () => {
  108. try {
  109. const progressResult = await getImportProgress(importId);
  110. if (progressResult.success && progressResult.data) {
  111. const { status, progress, processedRecords, totalRecords } = progressResult.data;
  112. // Update progress display
  113. setProgress(progress);
  114. setProcessedRecords(processedRecords);
  115. setTotalRecords(totalRecords);
  116. if (status === 'completed') {
  117. clearInterval(pollInterval);
  118. setProcessing(false);
  119. setImportStatus('completed');
  120. toast({
  121. title: 'Import Complete',
  122. description: `Successfully imported ${totalRecords} records`,
  123. });
  124. loadImportDetail();
  125. } else if (status === 'failed') {
  126. clearInterval(pollInterval);
  127. setProcessing(false);
  128. setImportStatus('failed');
  129. toast({
  130. title: 'Import Failed',
  131. description: progressResult.data.errorMessage || 'Import processing failed',
  132. variant: 'destructive',
  133. });
  134. }
  135. }
  136. } catch (error) {
  137. console.error('Error polling import progress:', error);
  138. clearInterval(pollInterval);
  139. setProcessing(false);
  140. setImportStatus('failed');
  141. }
  142. }, 1000); // Poll every second
  143. } else {
  144. toast({
  145. title: 'Error',
  146. description: result.error || 'Failed to start import process',
  147. variant: 'destructive',
  148. });
  149. setProcessing(false);
  150. setImportStatus('failed');
  151. }
  152. } catch {
  153. toast({
  154. title: 'Error',
  155. description: 'Failed to trigger import process',
  156. variant: 'destructive',
  157. });
  158. setProcessing(false);
  159. setImportStatus('failed');
  160. }
  161. }
  162. if (loading) {
  163. return (
  164. <Dialog open={open} onOpenChange={onOpenChange}>
  165. <DialogContent className="max-w-4xl max-h-[80vh]">
  166. <DialogHeader>
  167. <DialogTitle>Loading Import Details</DialogTitle>
  168. <DialogDescription>
  169. Please wait while we load the import information...
  170. </DialogDescription>
  171. </DialogHeader>
  172. <div className="flex justify-center py-8">
  173. <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
  174. </div>
  175. </DialogContent>
  176. </Dialog>
  177. );
  178. }
  179. if (!importDetail) return null;
  180. return (
  181. <Dialog open={open} onOpenChange={onOpenChange}>
  182. <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
  183. <DialogHeader>
  184. <DialogTitle>Import Details</DialogTitle>
  185. <DialogDescription>
  186. View detailed information about this import
  187. </DialogDescription>
  188. </DialogHeader>
  189. <div className="space-y-6">
  190. <Card>
  191. <CardHeader>
  192. <CardTitle>Import Information</CardTitle>
  193. </CardHeader>
  194. <CardContent className="space-y-2">
  195. <div className="flex justify-between">
  196. <span className="font-medium">Name:</span>
  197. <span>{importDetail.name}</span>
  198. </div>
  199. <div className="flex justify-between">
  200. <span className="font-medium">Layout:</span>
  201. <span>{importDetail.layout.name}</span>
  202. </div>
  203. <div className="flex justify-between">
  204. <span className="font-medium">Import Date:</span>
  205. <span>{format(importDetail.importDate, 'PPpp')}</span>
  206. </div>
  207. {importDetail.file && (
  208. <div className="flex justify-between">
  209. <span className="font-medium">File:</span>
  210. <span>{importDetail.file.filename}</span>
  211. </div>
  212. )}
  213. </CardContent>
  214. </Card>
  215. <Card>
  216. <CardHeader>
  217. <CardTitle>Layout Configuration</CardTitle>
  218. </CardHeader>
  219. <CardContent>
  220. <div className="space-y-4">
  221. {importDetail.layout.sections.map((section) => (
  222. <div key={section.id} className="border rounded-lg p-4">
  223. <h4 className="font-medium mb-2">{section.name}</h4>
  224. <p className="text-sm text-muted-foreground mb-2">
  225. Table: {section.tableName}
  226. </p>
  227. <div className="grid gap-1">
  228. {section.fields.map((field) => (
  229. <div key={field.importTableColumnName} className="text-sm">
  230. <span className="font-medium">{field.name}:</span>
  231. <span className="ml-2 text-muted-foreground">
  232. {field.importTableColumnName}
  233. </span>
  234. </div>
  235. ))}
  236. </div>
  237. </div>
  238. ))}
  239. </div>
  240. </CardContent>
  241. </Card>
  242. <Card>
  243. <CardHeader>
  244. <div className="flex justify-between items-center">
  245. <CardTitle>Import Actions</CardTitle>
  246. <Button
  247. onClick={handleTriggerImport}
  248. disabled={processing || !importDetail.file}
  249. size="sm"
  250. variant="default"
  251. >
  252. {processing ? 'Processing...' : 'Start Import'}
  253. </Button>
  254. </div>
  255. </CardHeader>
  256. <CardContent>
  257. {importStatus === 'processing' && (
  258. <div className="flex items-center gap-2 text-sm text-blue-600">
  259. <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"></div>
  260. Import is currently processing...
  261. </div>
  262. )}
  263. {importStatus === 'completed' && (
  264. <div className="text-sm text-green-600">
  265. Import completed successfully!
  266. </div>
  267. )}
  268. {importStatus === 'failed' && (
  269. <div className="text-sm text-red-600">
  270. Import failed. Please check the logs for details.
  271. </div>
  272. )}
  273. {!importDetail.file && (
  274. <div className="text-sm text-yellow-600">
  275. No file attached. Please upload a file before starting import.
  276. </div>
  277. )}
  278. </CardContent>
  279. </Card>
  280. </div>
  281. <div className="flex justify-end gap-2 mt-6">
  282. <Button onClick={() => onOpenChange(false)}>Close</Button>
  283. </div>
  284. </DialogContent>
  285. </Dialog>
  286. );
  287. }