page.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. /* eslint-disable @typescript-eslint/no-explicit-any */
  2. "use client";
  3. import { useState } from 'react';
  4. import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
  5. import { Button } from '@/components/ui/button';
  6. import { Upload, FileText, Database, BarChart3, CheckCircle, Loader2 } from 'lucide-react';
  7. import { UploadForm } from '@/app/components/uploadForm';
  8. import { createCintasImportRecord, processCintasImportData } from '@/app/actions/cintas-workflow';
  9. interface FileData {
  10. id: string;
  11. filename: string;
  12. mimetype: string;
  13. size: number;
  14. createdAt: string;
  15. updatedAt: string;
  16. }
  17. interface CintasSummary {
  18. id: number;
  19. week: string;
  20. trrTotal: number;
  21. fourWkAverages: number;
  22. trrPlus4Wk: number;
  23. powerAdds: number;
  24. weekId: number;
  25. }
  26. export default function CintasCalendarSummaryPage() {
  27. const [currentStep, setCurrentStep] = useState(1);
  28. const [uploadedFile, setUploadedFile] = useState<FileData | null>(null);
  29. const [isProcessing, setIsProcessing] = useState(false);
  30. const [importRecord, setImportRecord] = useState<any>(null);
  31. const [summaryData, setSummaryData] = useState<CintasSummary[]>([]);
  32. const [error, setError] = useState<string | null>(null);
  33. const [summaryExists, setSummaryExists] = useState(false);
  34. const handleFileUploaded = (file: FileData) => {
  35. setUploadedFile(file);
  36. setCurrentStep(2);
  37. setError(null);
  38. };
  39. const handleCreateImportRecord = async () => {
  40. if (!uploadedFile) return;
  41. setIsProcessing(true);
  42. setError(null);
  43. try {
  44. const result = await createCintasImportRecord(uploadedFile.id, uploadedFile.filename);
  45. if (result.success) {
  46. setImportRecord(result.data);
  47. setCurrentStep(3);
  48. } else {
  49. setError(result.error || 'Failed to create import record');
  50. }
  51. } catch (err) {
  52. setError(err instanceof Error ? err.message : 'Unknown error occurred');
  53. } finally {
  54. setIsProcessing(false);
  55. }
  56. };
  57. const handleProcessImportData = async () => {
  58. if (!importRecord) return;
  59. setIsProcessing(true);
  60. setError(null);
  61. try {
  62. const result = await processCintasImportData(importRecord.id);
  63. if (result.success) {
  64. setCurrentStep(4);
  65. } else {
  66. setError(result.error || 'Failed to process import data');
  67. }
  68. } catch (err) {
  69. setError(err instanceof Error ? err.message : 'Unknown error occurred');
  70. } finally {
  71. setIsProcessing(false);
  72. }
  73. };
  74. const handleGenerateSummary = async () => {
  75. if (!importRecord) return;
  76. setIsProcessing(true);
  77. setError(null);
  78. try {
  79. // Call the new POST endpoint to generate summary
  80. const response = await fetch(`/api/imports/${importRecord.id}/summary`, {
  81. method: 'POST',
  82. headers: {
  83. 'Content-Type': 'application/json',
  84. },
  85. });
  86. const data = await response.json();
  87. if (response.ok) {
  88. setSummaryData(data.summary || []);
  89. setSummaryExists(true);
  90. // If summary was just generated, mark as completed
  91. if (data.summaryGenerated) {
  92. setCurrentStep(4);
  93. }
  94. } else {
  95. throw new Error(data.error || 'Failed to generate summary');
  96. }
  97. } catch (err) {
  98. setError(err instanceof Error ? err.message : 'Failed to generate summary');
  99. } finally {
  100. setIsProcessing(false);
  101. }
  102. };
  103. const steps = [
  104. {
  105. id: 1,
  106. title: 'Upload Excel File',
  107. description: 'Upload the Cintas Install Calendar Excel file to blob storage',
  108. icon: Upload,
  109. status: currentStep >= 1 ? (uploadedFile ? 'completed' : 'pending') : 'pending',
  110. },
  111. {
  112. id: 2,
  113. title: 'Create Import Record',
  114. description: 'Create an import record with Cintas Install Calendar layout configuration',
  115. icon: FileText,
  116. status: currentStep >= 2 ? (importRecord ? 'completed' : 'pending') : 'disabled',
  117. },
  118. {
  119. id: 3,
  120. title: 'Import Data',
  121. description: 'Read the Excel file and import data into PostgreSQL database',
  122. icon: Database,
  123. status: currentStep > 3 ? 'completed' : (currentStep === 3 ? 'pending' : 'disabled'),
  124. },
  125. {
  126. id: 4,
  127. title: 'Generate Summary',
  128. description: 'Run summary calculations and display results',
  129. icon: BarChart3,
  130. status: currentStep >= 4 ? (summaryData.length > 0 ? 'completed' : 'pending') : 'disabled',
  131. },
  132. ];
  133. const getStepStatusColor = (status: string) => {
  134. switch (status) {
  135. case 'completed':
  136. return 'text-green-600 bg-green-50 border-green-200';
  137. case 'pending':
  138. return 'text-blue-600 bg-blue-50 border-blue-200';
  139. case 'disabled':
  140. return 'text-gray-400 bg-gray-50 border-gray-200';
  141. default:
  142. return 'text-gray-600 bg-gray-50 border-gray-200';
  143. }
  144. };
  145. return (
  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">Cintas Install Calendar Summary</h1>
  149. <p className="text-muted-foreground">
  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. );
  365. }