ImportDetailDialog.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. setProgress(0);
  100. setProcessedRecords(0);
  101. setTotalRecords(0);
  102. try {
  103. console.log('[IMPORT_DIALOG] 🚀 Starting import for ID:', importId);
  104. const result = await triggerImportProcess(importId);
  105. console.log('[IMPORT_DIALOG] 📊 triggerImportProcess result:', result);
  106. if (result.success) {
  107. toast({
  108. title: 'Success',
  109. description: result.message || 'Import process started successfully',
  110. });
  111. console.log('[IMPORT_DIALOG] 🔄 Starting poll for import progress...');
  112. // Poll for import progress until completion
  113. const pollInterval = setInterval(async () => {
  114. try {
  115. const progressResult = await getImportProgress(importId);
  116. console.log('[IMPORT_DIALOG] 📈 Progress result:', progressResult);
  117. if (progressResult.success && progressResult.data) {
  118. const { status, progress: prog, processedRecords: procRecs, totalRecords: totRecs, errorMessage } = progressResult.data;
  119. // Update progress display
  120. setProgress(prog);
  121. setProcessedRecords(procRecs);
  122. setTotalRecords(totRecs);
  123. setImportStatus(status as 'idle' | 'processing' | 'completed' | 'failed');
  124. if (status === 'completed') {
  125. console.log('[IMPORT_DIALOG] ✅ Import completed!');
  126. clearInterval(pollInterval);
  127. setProcessing(false);
  128. setImportStatus('completed');
  129. toast({
  130. title: 'Import Complete',
  131. description: `Successfully imported ${totRecs} records`,
  132. });
  133. loadImportDetail();
  134. } else if (status === 'failed') {
  135. console.error('[IMPORT_DIALOG] ❌ Import failed:', errorMessage);
  136. clearInterval(pollInterval);
  137. setProcessing(false);
  138. setImportStatus('failed');
  139. toast({
  140. title: 'Import Failed',
  141. description: errorMessage || 'Import processing failed',
  142. variant: 'destructive',
  143. });
  144. } else {
  145. console.log('[IMPORT_DIALOG] ⏳ Import status:', status, { procRecs, totRecs });
  146. }
  147. }
  148. } catch (error) {
  149. console.error('[IMPORT_DIALOG] ❌ Error polling import progress:', error);
  150. clearInterval(pollInterval);
  151. setProcessing(false);
  152. setImportStatus('failed');
  153. }
  154. }, 1000); // Poll every second
  155. } else {
  156. console.error('[IMPORT_DIALOG] ❌ triggerImportProcess failed:', result.error);
  157. toast({
  158. title: 'Error',
  159. description: result.error || 'Failed to start import process',
  160. variant: 'destructive',
  161. });
  162. setProcessing(false);
  163. setImportStatus('failed');
  164. }
  165. } catch {
  166. console.error('[IMPORT_DIALOG] ❌ Exception in handleTriggerImport');
  167. toast({
  168. title: 'Error',
  169. description: 'Failed to trigger import process',
  170. variant: 'destructive',
  171. });
  172. setProcessing(false);
  173. setImportStatus('failed');
  174. }
  175. }
  176. if (loading) {
  177. return (
  178. <Dialog open={open} onOpenChange={onOpenChange}>
  179. <DialogContent className="max-w-4xl max-h-[80vh]">
  180. <DialogHeader>
  181. <DialogTitle>Loading Import Details</DialogTitle>
  182. <DialogDescription>
  183. Please wait while we load the import information...
  184. </DialogDescription>
  185. </DialogHeader>
  186. <div className="flex justify-center py-8">
  187. <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
  188. </div>
  189. </DialogContent>
  190. </Dialog>
  191. );
  192. }
  193. if (!importDetail) return null;
  194. return (
  195. <Dialog open={open} onOpenChange={onOpenChange}>
  196. <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
  197. <DialogHeader>
  198. <DialogTitle>Import Details</DialogTitle>
  199. <DialogDescription>
  200. View detailed information about this import
  201. </DialogDescription>
  202. </DialogHeader>
  203. <div className="space-y-6">
  204. <Card>
  205. <CardHeader>
  206. <CardTitle>Import Information</CardTitle>
  207. </CardHeader>
  208. <CardContent className="space-y-2">
  209. <div className="flex justify-between">
  210. <span className="font-medium">Name:</span>
  211. <span>{importDetail.name}</span>
  212. </div>
  213. <div className="flex justify-between">
  214. <span className="font-medium">Layout:</span>
  215. <span>{importDetail.layout.name}</span>
  216. </div>
  217. <div className="flex justify-between">
  218. <span className="font-medium">Import Date:</span>
  219. <span>{format(importDetail.importDate, 'PPpp')}</span>
  220. </div>
  221. {importDetail.file && (
  222. <div className="flex justify-between">
  223. <span className="font-medium">File:</span>
  224. <span>{importDetail.file.filename}</span>
  225. </div>
  226. )}
  227. </CardContent>
  228. </Card>
  229. <Card>
  230. <CardHeader>
  231. <CardTitle>Layout Configuration</CardTitle>
  232. </CardHeader>
  233. <CardContent>
  234. <div className="space-y-4">
  235. {importDetail.layout.sections.map((section) => (
  236. <div key={section.id} className="border rounded-lg p-4">
  237. <h4 className="font-medium mb-2">{section.name}</h4>
  238. <p className="text-sm text-muted-foreground mb-2">
  239. Table: {section.tableName}
  240. </p>
  241. <div className="grid gap-1">
  242. {section.fields.map((field) => (
  243. <div key={field.importTableColumnName} className="text-sm">
  244. <span className="font-medium">{field.name}:</span>
  245. <span className="ml-2 text-muted-foreground">
  246. {field.importTableColumnName}
  247. </span>
  248. </div>
  249. ))}
  250. </div>
  251. </div>
  252. ))}
  253. </div>
  254. </CardContent>
  255. </Card>
  256. <Card>
  257. <CardHeader>
  258. <div className="flex justify-between items-center">
  259. <CardTitle>Import Actions</CardTitle>
  260. <Button
  261. onClick={handleTriggerImport}
  262. disabled={processing || !importDetail.file}
  263. size="sm"
  264. variant="default"
  265. >
  266. {processing ? 'Processing...' : 'Start Import'}
  267. </Button>
  268. </div>
  269. </CardHeader>
  270. <CardContent>
  271. {importStatus === 'processing' && (
  272. <div className="space-y-2">
  273. <div className="flex items-center gap-2 text-sm text-blue-600">
  274. <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"></div>
  275. Import is currently processing...
  276. </div>
  277. <div className="text-xs text-muted-foreground">
  278. Progress: {processedRecords} / {totalRecords} records ({progress}%)
  279. </div>
  280. </div>
  281. )}
  282. {importStatus === 'completed' && (
  283. <div className="text-sm text-green-600">
  284. Import completed successfully!
  285. </div>
  286. )}
  287. {importStatus === 'failed' && (
  288. <div className="text-sm text-red-600">
  289. Import failed. Please check the logs for details.
  290. </div>
  291. )}
  292. {!importDetail.file && (
  293. <div className="text-sm text-yellow-600">
  294. No file attached. Please upload a file before starting import.
  295. </div>
  296. )}
  297. </CardContent>
  298. </Card>
  299. </div>
  300. <div className="flex justify-end gap-2 mt-6">
  301. <Button onClick={() => onOpenChange(false)}>Close</Button>
  302. </div>
  303. </DialogContent>
  304. </Dialog>
  305. );
  306. }