ImportDetailDialog.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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, calculateCintasSummaries } from '@/app/actions/imports';
  9. interface CintasSummary {
  10. id: number;
  11. week: string;
  12. trrTotal: number;
  13. fourWkAverages: number;
  14. trrPlus4Wk: number;
  15. powerAdds: number;
  16. weekId: number;
  17. importId: number;
  18. }
  19. interface ImportDetail {
  20. id: number;
  21. name: string;
  22. importDate: Date;
  23. layout: {
  24. id: number;
  25. name: string;
  26. sections: Array<{
  27. id: number;
  28. name: string;
  29. tableName: string;
  30. fields: Array<{
  31. id: number;
  32. name: string;
  33. createdAt: Date;
  34. updatedAt: Date;
  35. layoutSectionId: number;
  36. cellPosition: string;
  37. dataType: string;
  38. dataTypeFormat: string | null;
  39. importTableColumnName: string;
  40. importColumnOrderNumber: number;
  41. }>;
  42. }>;
  43. };
  44. cintasSummaries: CintasSummary[];
  45. file?: {
  46. id: string;
  47. filename: string;
  48. size: number;
  49. contentType: string;
  50. };
  51. }
  52. interface ImportDetailDialogProps {
  53. open: boolean;
  54. onOpenChange: (open: boolean) => void;
  55. importId: number;
  56. }
  57. export function ImportDetailDialog({ open, onOpenChange, importId }: ImportDetailDialogProps) {
  58. const [importDetail, setImportDetail] = useState<ImportDetail | null>(null);
  59. const [loading, setLoading] = useState(true);
  60. const [calculating, setCalculating] = useState(false);
  61. const [processing, setProcessing] = useState(false);
  62. const [importStatus, setImportStatus] = useState<'idle' | 'processing' | 'completed' | 'failed'>('idle');
  63. const { toast } = useToast();
  64. const loadImportDetail = useCallback(async () => {
  65. try {
  66. const result = await getImportById(importId);
  67. if (result.success && result.data) {
  68. setImportDetail(result.data);
  69. } else {
  70. toast({
  71. title: 'Error',
  72. description: result.error || 'Failed to load import details',
  73. variant: 'destructive',
  74. });
  75. setImportDetail(null);
  76. }
  77. } catch {
  78. toast({
  79. title: 'Error',
  80. description: 'Failed to load import details',
  81. variant: 'destructive',
  82. });
  83. setImportDetail(null);
  84. } finally {
  85. setLoading(false);
  86. }
  87. }, [importId, toast]);
  88. useEffect(() => {
  89. if (open && importId) {
  90. loadImportDetail();
  91. }
  92. }, [open, importId, loadImportDetail]);
  93. async function handleCalculateSummaries() {
  94. setCalculating(true);
  95. try {
  96. const result = await calculateCintasSummaries(importId);
  97. if (result.success) {
  98. toast({
  99. title: 'Success',
  100. description: 'Cintas summaries calculated successfully',
  101. });
  102. loadImportDetail();
  103. } else {
  104. toast({
  105. title: 'Error',
  106. description: result.error || 'Failed to calculate summaries',
  107. variant: 'destructive',
  108. });
  109. }
  110. } catch {
  111. toast({
  112. title: 'Error',
  113. description: 'Failed to calculate summaries',
  114. variant: 'destructive',
  115. });
  116. } finally {
  117. setCalculating(false);
  118. }
  119. }
  120. async function handleTriggerImport() {
  121. if (!importDetail?.file) {
  122. toast({
  123. title: 'Error',
  124. description: 'No file attached to this import',
  125. variant: 'destructive',
  126. });
  127. return;
  128. }
  129. setProcessing(true);
  130. setImportStatus('processing');
  131. try {
  132. const response = await fetch(`/api/imports/${importId}/trigger`, {
  133. method: 'POST',
  134. });
  135. const result = await response.json();
  136. if (result.success) {
  137. toast({
  138. title: 'Success',
  139. description: 'Import process started successfully',
  140. });
  141. // Set up WebSocket connection for progress updates
  142. const ws = new WebSocket(`ws://localhost:3001/import-progress/${importId}`);
  143. ws.onmessage = (event) => {
  144. const progress = JSON.parse(event.data);
  145. if (progress.status === 'completed') {
  146. setImportStatus('completed');
  147. setProcessing(false);
  148. ws.close();
  149. toast({
  150. title: 'Import Complete',
  151. description: `Successfully imported ${progress.totalInserted || 0} rows`,
  152. });
  153. } else if (progress.status === 'failed') {
  154. setImportStatus('failed');
  155. setProcessing(false);
  156. ws.close();
  157. toast({
  158. title: 'Import Failed',
  159. description: progress.errors?.[0] || 'Import process failed',
  160. variant: 'destructive',
  161. });
  162. }
  163. };
  164. ws.onerror = () => {
  165. setProcessing(false);
  166. setImportStatus('failed');
  167. toast({
  168. title: 'Connection Error',
  169. description: 'Failed to connect to import progress server',
  170. variant: 'destructive',
  171. });
  172. };
  173. } else {
  174. toast({
  175. title: 'Error',
  176. description: result.error || 'Failed to start import process',
  177. variant: 'destructive',
  178. });
  179. setProcessing(false);
  180. setImportStatus('failed');
  181. }
  182. } catch {
  183. toast({
  184. title: 'Error',
  185. description: 'Failed to trigger import process',
  186. variant: 'destructive',
  187. });
  188. setProcessing(false);
  189. setImportStatus('failed');
  190. }
  191. }
  192. if (loading) {
  193. return (
  194. <Dialog open={open} onOpenChange={onOpenChange}>
  195. <DialogContent className="max-w-4xl max-h-[80vh]">
  196. <DialogHeader>
  197. <DialogTitle>Loading Import Details</DialogTitle>
  198. <DialogDescription>
  199. Please wait while we load the import information...
  200. </DialogDescription>
  201. </DialogHeader>
  202. <div className="flex justify-center py-8">
  203. <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
  204. </div>
  205. </DialogContent>
  206. </Dialog>
  207. );
  208. }
  209. if (!importDetail) return null;
  210. return (
  211. <Dialog open={open} onOpenChange={onOpenChange}>
  212. <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
  213. <DialogHeader>
  214. <DialogTitle>Import Details</DialogTitle>
  215. <DialogDescription>
  216. View detailed information about this import
  217. </DialogDescription>
  218. </DialogHeader>
  219. <div className="space-y-6">
  220. <Card>
  221. <CardHeader>
  222. <CardTitle>Import Information</CardTitle>
  223. </CardHeader>
  224. <CardContent className="space-y-2">
  225. <div className="flex justify-between">
  226. <span className="font-medium">Name:</span>
  227. <span>{importDetail.name}</span>
  228. </div>
  229. <div className="flex justify-between">
  230. <span className="font-medium">Layout:</span>
  231. <span>{importDetail.layout.name}</span>
  232. </div>
  233. <div className="flex justify-between">
  234. <span className="font-medium">Import Date:</span>
  235. <span>{format(importDetail.importDate, 'PPpp')}</span>
  236. </div>
  237. {importDetail.file && (
  238. <div className="flex justify-between">
  239. <span className="font-medium">File:</span>
  240. <span>{importDetail.file.filename}</span>
  241. </div>
  242. )}
  243. </CardContent>
  244. </Card>
  245. <Card>
  246. <CardHeader>
  247. <CardTitle>Layout Configuration</CardTitle>
  248. </CardHeader>
  249. <CardContent>
  250. <div className="space-y-4">
  251. {importDetail.layout.sections.map((section) => (
  252. <div key={section.id} className="border rounded-lg p-4">
  253. <h4 className="font-medium mb-2">{section.name}</h4>
  254. <p className="text-sm text-muted-foreground mb-2">
  255. Table: {section.tableName}
  256. </p>
  257. <div className="grid gap-1">
  258. {section.fields.map((field) => (
  259. <div key={field.importTableColumnName} className="text-sm">
  260. <span className="font-medium">{field.name}:</span>
  261. <span className="ml-2 text-muted-foreground">
  262. {field.importTableColumnName}
  263. </span>
  264. </div>
  265. ))}
  266. </div>
  267. </div>
  268. ))}
  269. </div>
  270. </CardContent>
  271. </Card>
  272. <Card>
  273. <CardHeader>
  274. <div className="flex justify-between items-center">
  275. <CardTitle>Import Actions</CardTitle>
  276. <div className="flex gap-2">
  277. <Button
  278. onClick={handleTriggerImport}
  279. disabled={processing || !importDetail.file}
  280. size="sm"
  281. variant="default"
  282. >
  283. {processing ? 'Processing...' : 'Start Import'}
  284. </Button>
  285. <Button
  286. onClick={handleCalculateSummaries}
  287. disabled={calculating || processing}
  288. size="sm"
  289. variant="secondary"
  290. >
  291. {calculating ? 'Calculating...' : 'Calculate Summaries'}
  292. </Button>
  293. </div>
  294. </div>
  295. </CardHeader>
  296. <CardContent>
  297. {importStatus === 'processing' && (
  298. <div className="flex items-center gap-2 text-sm text-blue-600">
  299. <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"></div>
  300. Import is currently processing...
  301. </div>
  302. )}
  303. {importStatus === 'completed' && (
  304. <div className="text-sm text-green-600">
  305. Import completed successfully!
  306. </div>
  307. )}
  308. {importStatus === 'failed' && (
  309. <div className="text-sm text-red-600">
  310. Import failed. Please check the logs for details.
  311. </div>
  312. )}
  313. {!importDetail.file && (
  314. <div className="text-sm text-yellow-600">
  315. No file attached. Please upload a file before starting import.
  316. </div>
  317. )}
  318. </CardContent>
  319. </Card>
  320. <Card>
  321. <CardHeader>
  322. <CardTitle>Cintas Summaries</CardTitle>
  323. </CardHeader>
  324. <CardContent>
  325. {importDetail.cintasSummaries.length === 0 ? (
  326. <p className="text-muted-foreground">No summaries calculated yet</p>
  327. ) : (
  328. <div className="overflow-x-auto">
  329. <table className="w-full text-sm">
  330. <thead>
  331. <tr className="border-b">
  332. <th className="text-left py-2">Week</th>
  333. <th className="text-right py-2">TRR Total</th>
  334. <th className="text-right py-2">4WK Averages</th>
  335. <th className="text-right py-2">TRR + 4WK</th>
  336. <th className="text-right py-2">Power Adds</th>
  337. </tr>
  338. </thead>
  339. <tbody>
  340. {importDetail.cintasSummaries.map((summary) => (
  341. <tr key={summary.id} className="border-b">
  342. <td className="py-2">{summary.week}</td>
  343. <td className="text-right py-2">{summary.trrTotal}</td>
  344. <td className="text-right py-2">{summary.fourWkAverages}</td>
  345. <td className="text-right py-2">{summary.trrPlus4Wk}</td>
  346. <td className="text-right py-2">{summary.powerAdds}</td>
  347. </tr>
  348. ))}
  349. </tbody>
  350. </table>
  351. </div>
  352. )}
  353. </CardContent>
  354. </Card>
  355. </div>
  356. <div className="flex justify-end gap-2 mt-6">
  357. <Button onClick={() => onOpenChange(false)}>Close</Button>
  358. </div>
  359. </DialogContent>
  360. </Dialog>
  361. );
  362. }