page.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. "use client";
  2. import { useState } from 'react';
  3. import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
  4. import { Button } from '@/components/ui/button';
  5. import { Upload, FileText, Database, BarChart3, CheckCircle, Loader2 } from 'lucide-react';
  6. import { UploadForm } from '@/app/components/uploadForm';
  7. import { createCintasImportRecord, processCintasImportData } from '@/app/actions/cintas-workflow';
  8. interface FileData {
  9. id: string;
  10. filename: string;
  11. mimetype: string;
  12. size: number;
  13. createdAt: string;
  14. updatedAt: string;
  15. }
  16. interface CintasSummary {
  17. id: number;
  18. week: string;
  19. trrTotal: number;
  20. fourWkAverages: number;
  21. trrPlus4Wk: number;
  22. powerAdds: number;
  23. weekId: number;
  24. }
  25. export default function CintasCalendarSummaryPage() {
  26. const [currentStep, setCurrentStep] = useState(1);
  27. const [uploadedFile, setUploadedFile] = useState<FileData | null>(null);
  28. const [isProcessing, setIsProcessing] = useState(false);
  29. const [importRecord, setImportRecord] = useState<any>(null);
  30. const [summaryData, setSummaryData] = useState<CintasSummary[]>([]);
  31. const [error, setError] = useState<string | null>(null);
  32. const [summaryExists, setSummaryExists] = useState(false);
  33. const handleFileUploaded = (file: FileData) => {
  34. setUploadedFile(file);
  35. setCurrentStep(2);
  36. setError(null);
  37. };
  38. const handleCreateImportRecord = async () => {
  39. if (!uploadedFile) return;
  40. setIsProcessing(true);
  41. setError(null);
  42. try {
  43. const result = await createCintasImportRecord(uploadedFile.id, uploadedFile.filename);
  44. if (result.success) {
  45. setImportRecord(result.data);
  46. setCurrentStep(3);
  47. } else {
  48. setError(result.error || 'Failed to create import record');
  49. }
  50. } catch (err) {
  51. setError(err instanceof Error ? err.message : 'Unknown error occurred');
  52. } finally {
  53. setIsProcessing(false);
  54. }
  55. };
  56. const handleProcessImportData = async () => {
  57. if (!importRecord) return;
  58. setIsProcessing(true);
  59. setError(null);
  60. try {
  61. const result = await processCintasImportData(importRecord.id);
  62. if (result.success) {
  63. setCurrentStep(4);
  64. } else {
  65. setError(result.error || 'Failed to process import data');
  66. }
  67. } catch (err) {
  68. setError(err instanceof Error ? err.message : 'Unknown error occurred');
  69. } finally {
  70. setIsProcessing(false);
  71. }
  72. };
  73. const handleGenerateSummary = async () => {
  74. if (!importRecord) return;
  75. setIsProcessing(true);
  76. setError(null);
  77. try {
  78. // Call the new POST endpoint to generate summary
  79. const response = await fetch(`/api/imports/${importRecord.id}/summary`, {
  80. method: 'POST',
  81. headers: {
  82. 'Content-Type': 'application/json',
  83. },
  84. });
  85. const data = await response.json();
  86. if (response.ok) {
  87. setSummaryData(data.summary || []);
  88. setSummaryExists(true);
  89. // If summary was just generated, mark as completed
  90. if (data.summaryGenerated) {
  91. setCurrentStep(4);
  92. }
  93. } else {
  94. throw new Error(data.error || 'Failed to generate summary');
  95. }
  96. } catch (err) {
  97. setError(err instanceof Error ? err.message : 'Failed to generate summary');
  98. } finally {
  99. setIsProcessing(false);
  100. }
  101. };
  102. const steps = [
  103. {
  104. id: 1,
  105. title: 'Upload Excel File',
  106. description: 'Upload the Cintas Install Calendar Excel file to blob storage',
  107. icon: Upload,
  108. status: currentStep >= 1 ? (uploadedFile ? 'completed' : 'pending') : 'pending',
  109. },
  110. {
  111. id: 2,
  112. title: 'Create Import Record',
  113. description: 'Create an import record with Cintas Install Calendar layout configuration',
  114. icon: FileText,
  115. status: currentStep >= 2 ? (importRecord ? 'completed' : 'pending') : 'disabled',
  116. },
  117. {
  118. id: 3,
  119. title: 'Import Data',
  120. description: 'Read the Excel file and import data into PostgreSQL database',
  121. icon: Database,
  122. status: currentStep > 3 ? 'completed' : (currentStep === 3 ? 'pending' : 'disabled'),
  123. },
  124. {
  125. id: 4,
  126. title: 'Generate Summary',
  127. description: 'Run summary calculations and display results',
  128. icon: BarChart3,
  129. status: currentStep >= 4 ? (summaryData.length > 0 ? 'completed' : 'pending') : 'disabled',
  130. },
  131. ];
  132. const getStepStatusColor = (status: string) => {
  133. switch (status) {
  134. case 'completed':
  135. return 'text-green-600 bg-green-50 border-green-200';
  136. case 'pending':
  137. return 'text-blue-600 bg-blue-50 border-blue-200';
  138. case 'disabled':
  139. return 'text-gray-400 bg-gray-50 border-gray-200';
  140. default:
  141. return 'text-gray-600 bg-gray-50 border-gray-200';
  142. }
  143. };
  144. return (
  145. <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800">
  146. <div className="container mx-auto py-6 px-4 max-w-6xl">
  147. <div className="mb-8">
  148. <h1 className="text-3xl font-bold tracking-tight text-gray-900 dark:text-white">Cintas Install Calendar Summary</h1>
  149. <p className="text-muted-foreground dark:text-gray-300">
  150. Follow the workflow steps to upload and process the installation calendar data
  151. </p>
  152. </div>
  153. {error && (
  154. <div className="mb-4 p-4 bg-red-50 border border-red-200 rounded-lg">
  155. <p className="text-sm text-red-800">{error}</p>
  156. </div>
  157. )}
  158. {/* Workflow Steps */}
  159. <div className="mb-8">
  160. <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
  161. {steps.map((step) => {
  162. const Icon = step.icon;
  163. return (
  164. <Card
  165. key={step.id}
  166. className={`border-2 ${getStepStatusColor(step.status)}`}
  167. >
  168. <CardHeader className="pb-3">
  169. <div className="flex items-center space-x-2">
  170. <Icon className="h-5 w-5" />
  171. <div>
  172. <CardTitle className="text-sm font-medium">
  173. Step {step.id}: {step.title}
  174. </CardTitle>
  175. </div>
  176. </div>
  177. </CardHeader>
  178. <CardContent>
  179. <CardDescription className="text-xs">
  180. {step.description}
  181. </CardDescription>
  182. </CardContent>
  183. </Card>
  184. );
  185. })}
  186. </div>
  187. </div>
  188. {/* Step Content */}
  189. <div className="grid gap-6">
  190. {currentStep === 1 && (
  191. <Card>
  192. <CardHeader>
  193. <CardTitle>Step 1: Upload Excel File</CardTitle>
  194. <CardDescription>
  195. Upload your Cintas Install Calendar Excel file to begin processing
  196. </CardDescription>
  197. </CardHeader>
  198. <CardContent>
  199. <div className="space-y-4">
  200. <UploadForm onFileUploaded={handleFileUploaded} />
  201. {uploadedFile && (
  202. <div className="mt-4 p-4 bg-green-50 border border-green-200 rounded-lg">
  203. <div className="flex items-center space-x-2">
  204. <CheckCircle className="h-5 w-5 text-green-600" />
  205. <div>
  206. <p className="text-sm font-medium text-green-800">File uploaded successfully!</p>
  207. <p className="text-sm text-green-600">
  208. {uploadedFile.filename} ({(uploadedFile.size / 1024 / 1024).toFixed(2)} MB)
  209. </p>
  210. </div>
  211. </div>
  212. </div>
  213. )}
  214. </div>
  215. </CardContent>
  216. </Card>
  217. )}
  218. {currentStep === 2 && (
  219. <Card>
  220. <CardHeader>
  221. <CardTitle>Step 2: Create Import Record</CardTitle>
  222. <CardDescription>
  223. Creating import record with Cintas Install Calendar layout configuration
  224. </CardDescription>
  225. </CardHeader>
  226. <CardContent>
  227. <div className="space-y-4">
  228. <p className="text-sm text-muted-foreground">
  229. File: {uploadedFile?.filename}
  230. </p>
  231. <Button
  232. onClick={handleCreateImportRecord}
  233. disabled={isProcessing}
  234. className="w-full"
  235. >
  236. {isProcessing ? (
  237. <>
  238. <Loader2 className="mr-2 h-4 w-4 animate-spin" />
  239. Creating Import Record...
  240. </>
  241. ) : (
  242. 'Create Import Record'
  243. )}
  244. </Button>
  245. </div>
  246. </CardContent>
  247. </Card>
  248. )}
  249. {currentStep === 3 && (
  250. <Card>
  251. <CardHeader>
  252. <CardTitle>Step 3: Import Data</CardTitle>
  253. <CardDescription>
  254. Processing Excel file and importing data into database
  255. </CardDescription>
  256. </CardHeader>
  257. <CardContent>
  258. <div className="space-y-4">
  259. <p className="text-sm text-muted-foreground">
  260. Import ID: {importRecord?.id}
  261. </p>
  262. <Button
  263. onClick={handleProcessImportData}
  264. disabled={isProcessing}
  265. className="w-full"
  266. >
  267. {isProcessing ? (
  268. <>
  269. <Loader2 className="mr-2 h-4 w-4 animate-spin" />
  270. Processing Import...
  271. </>
  272. ) : (
  273. 'Process Import'
  274. )}
  275. </Button>
  276. </div>
  277. </CardContent>
  278. </Card>
  279. )}
  280. {currentStep === 4 && (
  281. <Card>
  282. <CardHeader>
  283. <CardTitle>Step 4: Generate Summary</CardTitle>
  284. <CardDescription>
  285. Running summary calculations and displaying results
  286. </CardDescription>
  287. </CardHeader>
  288. <CardContent>
  289. <div className="space-y-4">
  290. <p className="text-sm text-muted-foreground">
  291. Import ID: {importRecord?.id}
  292. </p>
  293. <Button
  294. onClick={handleGenerateSummary}
  295. disabled={isProcessing}
  296. className="w-full"
  297. >
  298. {isProcessing ? (
  299. <>
  300. <Loader2 className="mr-2 h-4 w-4 animate-spin" />
  301. {summaryExists ? 'Loading Summary...' : 'Generating Summary...'}
  302. </>
  303. ) : (
  304. summaryExists ? 'Load Summary' : 'Generate Summary'
  305. )}
  306. </Button>
  307. {summaryData.length > 0 && (
  308. <div className="mt-6">
  309. <h3 className="text-lg font-semibold mb-4">Summary Results</h3>
  310. <div className="overflow-x-auto">
  311. <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
  312. <thead className="bg-gray-50 dark:bg-gray-800">
  313. <tr>
  314. <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Week</th>
  315. <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">TRR Total</th>
  316. <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">4 Week Avg</th>
  317. <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">TRR + 4Wk</th>
  318. <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Power Adds</th>
  319. </tr>
  320. </thead>
  321. <tbody className="bg-white divide-y divide-gray-200 dark:bg-gray-800 dark:divide-gray-700">
  322. {summaryData.map((item, index) => (
  323. <tr
  324. key={`${item.id}-${index}`}
  325. className={index % 2 === 0
  326. ? 'bg-white dark:bg-gray-800'
  327. : 'bg-gray-50 dark:bg-gray-700/50'
  328. }
  329. >
  330. <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">{item.week}</td>
  331. <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">{item.trrTotal}</td>
  332. <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">{item.fourWkAverages}</td>
  333. <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">{item.trrPlus4Wk}</td>
  334. <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">{item.powerAdds}</td>
  335. </tr>
  336. ))}
  337. </tbody>
  338. </table>
  339. </div>
  340. </div>
  341. )}
  342. </div>
  343. </CardContent>
  344. </Card>
  345. )}
  346. {/* Navigation */}
  347. <div className="flex justify-between">
  348. <Button
  349. variant="outline"
  350. onClick={() => setCurrentStep(Math.max(1, currentStep - 1))}
  351. disabled={currentStep === 1}
  352. >
  353. Previous
  354. </Button>
  355. <Button
  356. onClick={() => setCurrentStep(Math.min(4, currentStep + 1))}
  357. disabled={currentStep === 4 || (currentStep === 1 && !uploadedFile)}
  358. >
  359. {currentStep === 4 ? 'Complete' : 'Next'}
  360. </Button>
  361. </div>
  362. </div>
  363. </div>
  364. </div>
  365. );
  366. }