page.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. "use client";
  2. import { useState, useEffect } 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, History, PlusCircle } from 'lucide-react';
  6. import { UploadForm } from '@/app/components/uploadForm';
  7. import { createCintasImportRecord, processCintasImportData } from '@/app/actions/cintas-workflow';
  8. import { getImports, getImportSummary, generateImportSummary } from '@/app/actions/imports';
  9. import { useKindeBrowserClient } from "@kinde-oss/kinde-auth-nextjs";
  10. interface FileData {
  11. id: string;
  12. filename: string;
  13. mimetype: string;
  14. size: number;
  15. createdAt: string;
  16. updatedAt: string;
  17. }
  18. interface CintasSummary {
  19. id: number;
  20. week: string;
  21. trrTotal: number;
  22. fourWkAverages: number;
  23. trrPlus4Wk: number;
  24. powerAdds: number;
  25. weekId: number;
  26. }
  27. interface ImportRecord {
  28. id: number;
  29. name: string;
  30. importDate: string;
  31. fileId: string | null;
  32. file?: {
  33. filename: string;
  34. createdAt: string;
  35. };
  36. layout?: {
  37. name: string;
  38. };
  39. cintasSummaries?: CintasSummary[];
  40. }
  41. export default function CintasCalendarSummaryPage() {
  42. const { user } = useKindeBrowserClient();
  43. const [viewMode, setViewMode] = useState<'imports' | 'new-import' | 'summary' | 'new-summary'>('imports');
  44. const [currentStep, setCurrentStep] = useState(1);
  45. const [uploadedFile, setUploadedFile] = useState<FileData | null>(null);
  46. const [isProcessing, setIsProcessing] = useState(false);
  47. const [importRecord, setImportRecord] = useState<ImportRecord | null>(null);
  48. const [summaryData, setSummaryData] = useState<CintasSummary[]>([]);
  49. const [error, setError] = useState<string | null>(null);
  50. const [summaryExists, setSummaryExists] = useState(false);
  51. const [priorImports, setPriorImports] = useState<ImportRecord[]>([]);
  52. const [selectedImport, setSelectedImport] = useState<ImportRecord | null>(null);
  53. const [loadingImports, setLoadingImports] = useState(true);
  54. useEffect(() => {
  55. if (user) {
  56. loadPriorImports();
  57. }
  58. }, [user]);
  59. const loadPriorImports = async () => {
  60. try {
  61. setLoadingImports(true);
  62. setError(null); // Clear any previous errors
  63. if (!user?.id) {
  64. // Don't set error here, just return - user might still be loading
  65. return;
  66. }
  67. const result = await getImports(user.id);
  68. if (result.success && result.data) {
  69. // Map the data to match our ImportRecord interface
  70. const mappedData = result.data.map((item: any) => ({
  71. id: item.id,
  72. name: item.name,
  73. importDate: item.importDate,
  74. fileId: item.fileId,
  75. file: item.file ? {
  76. filename: item.file.filename,
  77. createdAt: item.file.createdAt
  78. } : undefined,
  79. cintasSummaries: item.cintasSummaries || []
  80. }));
  81. setPriorImports(mappedData);
  82. } else {
  83. setError(result.error || 'Failed to load prior imports');
  84. setPriorImports([]);
  85. }
  86. } catch (err) {
  87. setError(err instanceof Error ? err.message : 'Failed to load prior imports');
  88. setPriorImports([]);
  89. } finally {
  90. setLoadingImports(false);
  91. }
  92. };
  93. const handleFileUploaded = (file: FileData) => {
  94. setUploadedFile(file);
  95. setCurrentStep(2);
  96. setError(null);
  97. };
  98. const handleCreateImportRecord = async () => {
  99. if (!uploadedFile) return;
  100. setIsProcessing(true);
  101. setError(null);
  102. try {
  103. const result = await createCintasImportRecord(uploadedFile.id, uploadedFile.filename);
  104. if (result.success && result.data) {
  105. const importData = result.data;
  106. // Map the data to match the ImportRecord interface
  107. const importRecordData: ImportRecord = {
  108. id: importData.id,
  109. name: importData.name,
  110. importDate: importData.importDate.toISOString(),
  111. fileId: importData.fileId,
  112. file: importData.fileId ? {
  113. filename: uploadedFile.filename,
  114. createdAt: importData.createdAt?.toISOString() || new Date().toISOString()
  115. } : undefined,
  116. layout: {
  117. name: importData.layout?.name || 'Cintas Install Calendar'
  118. },
  119. cintasSummaries: []
  120. };
  121. setImportRecord(importRecordData);
  122. setSelectedImport(importRecordData);
  123. setCurrentStep(3);
  124. } else {
  125. setError(result.error || 'Failed to create import record');
  126. }
  127. } catch (err) {
  128. setError(err instanceof Error ? err.message : 'Unknown error occurred');
  129. } finally {
  130. setIsProcessing(false);
  131. }
  132. };
  133. const handleProcessImportData = async () => {
  134. if (!importRecord) return;
  135. setIsProcessing(true);
  136. setError(null);
  137. try {
  138. const result = await processCintasImportData(importRecord.id);
  139. if (result.success) {
  140. setCurrentStep(4);
  141. } else {
  142. setError(result.error || 'Failed to process import data');
  143. }
  144. } catch (err) {
  145. setError(err instanceof Error ? err.message : 'Unknown error occurred');
  146. } finally {
  147. setIsProcessing(false);
  148. }
  149. };
  150. const handleGenerateSummary = async () => {
  151. if (!importRecord) return;
  152. setIsProcessing(true);
  153. setError(null);
  154. try {
  155. const result = await generateImportSummary(importRecord.id);
  156. if (result.success && result.data) {
  157. const summaries = result.data.summary || [];
  158. setSummaryData(Array.isArray(summaries) ? summaries : []);
  159. setSummaryExists(summaries.length > 0);
  160. if (result.data.summaryGenerated || summaries.length > 0) {
  161. setCurrentStep(4);
  162. setViewMode('new-summary');
  163. }
  164. } else {
  165. throw new Error(result.error || 'Failed to generate summary');
  166. }
  167. } catch (err) {
  168. setError(err instanceof Error ? err.message : 'Failed to generate summary');
  169. } finally {
  170. setIsProcessing(false);
  171. }
  172. };
  173. const handleLoadImportSummary = async (importRecord: ImportRecord) => {
  174. try {
  175. setIsProcessing(true);
  176. setError(null);
  177. const result = await getImportSummary(importRecord.id);
  178. if (result.success && result.data) {
  179. setSelectedImport(importRecord);
  180. const summaries = result.data.summary?.cintasSummaries || [];
  181. setSummaryData(Array.isArray(summaries) ? summaries : []);
  182. setSummaryExists(summaries.length > 0);
  183. setViewMode('summary');
  184. } else {
  185. throw new Error(result.error || 'Failed to load summary');
  186. }
  187. } catch (err) {
  188. setError(err instanceof Error ? err.message : 'Failed to load summary');
  189. } finally {
  190. setIsProcessing(false);
  191. }
  192. };
  193. const handleStartNewImport = () => {
  194. setViewMode('new-import');
  195. setCurrentStep(1);
  196. setUploadedFile(null);
  197. setImportRecord(null);
  198. setSummaryData([]);
  199. setSummaryExists(false);
  200. setError(null);
  201. };
  202. const handleBackToImports = () => {
  203. setViewMode('imports');
  204. setSelectedImport(null);
  205. setSummaryData([]);
  206. loadPriorImports();
  207. };
  208. const formatDate = (dateString: string) => {
  209. return new Date(dateString).toLocaleDateString('en-US', {
  210. year: 'numeric',
  211. month: 'short',
  212. day: 'numeric',
  213. hour: '2-digit',
  214. minute: '2-digit'
  215. });
  216. };
  217. return (
  218. <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800">
  219. <div className="container mx-auto py-6 px-4 max-w-6xl">
  220. <div className="mb-8">
  221. <h1 className="text-3xl font-bold tracking-tight text-gray-900 dark:text-white">Cintas Install Calendar Summary</h1>
  222. <p className="text-muted-foreground dark:text-gray-300">
  223. View prior imports or create new ones to process installation calendar data
  224. </p>
  225. </div>
  226. {error && (
  227. <div className="mb-4 p-4 bg-red-50 border border-red-200 rounded-lg">
  228. <p className="text-sm text-red-800">{error}</p>
  229. </div>
  230. )}
  231. {/* Navigation Buttons */}
  232. <div className="mb-6 flex gap-4">
  233. <Button
  234. variant={viewMode === 'imports' ? 'default' : 'outline'}
  235. onClick={handleBackToImports}
  236. className="flex items-center gap-2"
  237. >
  238. <History className="h-4 w-4" />
  239. Prior Imports
  240. </Button>
  241. <Button
  242. variant={viewMode === 'new-import' ? 'default' : 'outline'}
  243. onClick={handleStartNewImport}
  244. className="flex items-center gap-2"
  245. >
  246. <PlusCircle className="h-4 w-4" />
  247. New Import
  248. </Button>
  249. </div>
  250. {/* Prior Imports View */}
  251. {viewMode === 'imports' && (
  252. <Card>
  253. <CardHeader>
  254. <CardTitle>Prior Imports</CardTitle>
  255. <CardDescription>
  256. Select an import to view its summary results
  257. </CardDescription>
  258. </CardHeader>
  259. <CardContent>
  260. {loadingImports ? (
  261. <div className="flex justify-center py-8">
  262. <Loader2 className="h-8 w-8 animate-spin" />
  263. </div>
  264. ) : priorImports.length === 0 ? (
  265. <div className="text-center py-8">
  266. <p className="text-muted-foreground mb-4">
  267. {user ? 'No prior imports found' : 'Please sign in to view imports'}
  268. </p>
  269. {user && (
  270. <Button onClick={handleStartNewImport}>
  271. Create First Import
  272. </Button>
  273. )}
  274. </div>
  275. ) : (
  276. <div className="space-y-4">
  277. {priorImports.map((importRecord) => (
  278. <div
  279. key={importRecord.id}
  280. className="border rounded-lg p-4 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors cursor-pointer"
  281. onClick={() => handleLoadImportSummary(importRecord)}
  282. >
  283. <div className="flex justify-between items-start">
  284. <div>
  285. <h3 className="font-semibold">{importRecord.name}</h3>
  286. <p className="text-sm text-muted-foreground">
  287. {formatDate(importRecord.importDate)}
  288. </p>
  289. {importRecord.file && (
  290. <p className="text-sm text-muted-foreground">
  291. File: {importRecord.file.filename}
  292. </p>
  293. )}
  294. </div>
  295. </div>
  296. </div>
  297. ))}
  298. </div>
  299. )}
  300. </CardContent>
  301. </Card>
  302. )}
  303. {/* New Import Workflow */}
  304. {(viewMode === 'new-import' || viewMode === 'new-summary') && (
  305. <div className="space-y-6">
  306. {/* Workflow Steps */}
  307. <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
  308. {[
  309. {
  310. id: 1,
  311. title: 'Upload Excel File',
  312. description: 'Upload the Cintas Install Calendar Excel file',
  313. icon: Upload,
  314. status: currentStep >= 1 ? (uploadedFile ? 'completed' : 'pending') : 'pending',
  315. },
  316. {
  317. id: 2,
  318. title: 'Create Import Record',
  319. description: 'Create import record with layout configuration',
  320. icon: FileText,
  321. status: currentStep >= 2 ? (importRecord ? 'completed' : 'pending') : 'disabled',
  322. },
  323. {
  324. id: 3,
  325. title: 'Import Data',
  326. description: 'Process Excel file and import data',
  327. icon: Database,
  328. status: currentStep > 3 ? 'completed' : (currentStep === 3 ? 'pending' : 'disabled'),
  329. },
  330. {
  331. id: 4,
  332. title: 'Generate Summary',
  333. description: 'Run summary calculations and display results',
  334. icon: BarChart3,
  335. status: currentStep >= 4 ? (summaryData.length > 0 ? 'completed' : 'pending') : 'disabled',
  336. },
  337. ].map((step) => {
  338. const Icon = step.icon;
  339. const getStatusColor = (status: string) => {
  340. switch (status) {
  341. case 'completed':
  342. return 'text-green-600 bg-green-50 border-green-200';
  343. case 'pending':
  344. return 'text-blue-600 bg-blue-50 border-blue-200';
  345. case 'disabled':
  346. return 'text-gray-400 bg-gray-50 border-gray-200';
  347. default:
  348. return 'text-gray-600 bg-gray-50 border-gray-200';
  349. }
  350. };
  351. return (
  352. <Card
  353. key={step.id}
  354. className={`border-2 ${getStatusColor(step.status)}`}
  355. >
  356. <CardHeader className="pb-3">
  357. <div className="flex items-center space-x-2">
  358. <Icon className="h-5 w-5" />
  359. <div>
  360. <CardTitle className="text-sm font-medium">
  361. Step {step.id}: {step.title}
  362. </CardTitle>
  363. </div>
  364. </div>
  365. </CardHeader>
  366. <CardContent>
  367. <CardDescription className="text-xs">
  368. {step.description}
  369. </CardDescription>
  370. </CardContent>
  371. </Card>
  372. );
  373. })}
  374. </div>
  375. {/* Step Content */}
  376. <div className="space-y-6">
  377. {currentStep === 1 && (
  378. <Card>
  379. <CardHeader>
  380. <CardTitle>Step 1: Upload Excel File</CardTitle>
  381. <CardDescription>
  382. Upload your Cintas Install Calendar Excel file to begin processing
  383. </CardDescription>
  384. </CardHeader>
  385. <CardContent>
  386. <div className="space-y-4">
  387. <UploadForm onFileUploaded={handleFileUploaded} />
  388. {uploadedFile && (
  389. <div className="mt-4 p-4 bg-green-50 border border-green-200 rounded-lg">
  390. <div className="flex items-center space-x-2">
  391. <CheckCircle className="h-5 w-5 text-green-600" />
  392. <div>
  393. <p className="text-sm font-medium text-green-800">File uploaded successfully!</p>
  394. <p className="text-sm text-green-600">
  395. {uploadedFile.filename} ({(uploadedFile.size / 1024 / 1024).toFixed(2)} MB)
  396. </p>
  397. </div>
  398. </div>
  399. </div>
  400. )}
  401. </div>
  402. </CardContent>
  403. </Card>
  404. )}
  405. {currentStep === 2 && (
  406. <Card>
  407. <CardHeader>
  408. <CardTitle>Step 2: Create Import Record</CardTitle>
  409. <CardDescription>
  410. Creating import record with Cintas Install Calendar layout configuration
  411. </CardDescription>
  412. </CardHeader>
  413. <CardContent>
  414. <div className="space-y-4">
  415. <p className="text-sm text-muted-foreground">
  416. File: {uploadedFile?.filename}
  417. </p>
  418. <Button
  419. onClick={handleCreateImportRecord}
  420. disabled={isProcessing}
  421. className="w-full"
  422. >
  423. {isProcessing ? (
  424. <>
  425. <Loader2 className="mr-2 h-4 w-4 animate-spin" />
  426. Creating Import Record...
  427. </>
  428. ) : (
  429. 'Create Import Record'
  430. )}
  431. </Button>
  432. </div>
  433. </CardContent>
  434. </Card>
  435. )}
  436. {currentStep === 3 && (
  437. <Card>
  438. <CardHeader>
  439. <CardTitle>Step 3: Import Data</CardTitle>
  440. <CardDescription>
  441. Processing Excel file and importing data into database
  442. </CardDescription>
  443. </CardHeader>
  444. <CardContent>
  445. <div className="space-y-4">
  446. <p className="text-sm text-muted-foreground">
  447. Import ID: {importRecord?.id}
  448. </p>
  449. <Button
  450. onClick={handleProcessImportData}
  451. disabled={isProcessing}
  452. className="w-full"
  453. >
  454. {isProcessing ? (
  455. <>
  456. <Loader2 className="mr-2 h-4 w-4 animate-spin" />
  457. Processing Import...
  458. </>
  459. ) : (
  460. 'Process Import'
  461. )}
  462. </Button>
  463. </div>
  464. </CardContent>
  465. </Card>
  466. )}
  467. {currentStep === 4 && (
  468. <Card>
  469. <CardHeader>
  470. <CardTitle>Step 4: Generate Summary</CardTitle>
  471. <CardDescription>
  472. Running summary calculations and displaying results
  473. </CardDescription>
  474. </CardHeader>
  475. <CardContent>
  476. <div className="space-y-4">
  477. <p className="text-sm text-muted-foreground">
  478. Import ID: {importRecord?.id}
  479. </p>
  480. <Button
  481. onClick={handleGenerateSummary}
  482. disabled={isProcessing}
  483. className="w-full"
  484. >
  485. {isProcessing ? (
  486. <>
  487. <Loader2 className="mr-2 h-4 w-4 animate-spin" />
  488. {summaryExists ? 'Loading Summary...' : 'Generating Summary...'}
  489. </>
  490. ) : (
  491. summaryExists ? 'Load Summary' : 'Generate Summary'
  492. )}
  493. </Button>
  494. </div>
  495. </CardContent>
  496. </Card>
  497. )}
  498. </div>
  499. </div>
  500. )}
  501. {/* Summary Results View */}
  502. {(viewMode === 'summary' || viewMode === 'new-summary') && selectedImport && (
  503. <Card>
  504. <CardHeader>
  505. <div className="flex justify-between items-start">
  506. <div>
  507. <CardTitle>Summary Results</CardTitle>
  508. <CardDescription>
  509. {selectedImport.name} - {formatDate(selectedImport.importDate)}
  510. </CardDescription>
  511. </div>
  512. <Button
  513. variant="outline"
  514. onClick={handleBackToImports}
  515. className="flex items-center gap-2"
  516. >
  517. <History className="h-4 w-4" />
  518. Back to Imports
  519. </Button>
  520. </div>
  521. </CardHeader>
  522. <CardContent>
  523. {isProcessing ? (
  524. <div className="flex justify-center py-8">
  525. <Loader2 className="h-8 w-8 animate-spin" />
  526. </div>
  527. ) : summaryData.length === 0 ? (
  528. <div className="text-center py-8">
  529. <p className="text-muted-foreground mb-4">No summary data available</p>
  530. <Button onClick={() => handleGenerateSummary()}>
  531. Generate Summary
  532. </Button>
  533. </div>
  534. ) : (
  535. <div className="overflow-x-auto">
  536. <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
  537. <thead className="bg-gray-50 dark:bg-gray-800">
  538. <tr>
  539. <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Week</th>
  540. <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>
  541. <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>
  542. <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>
  543. <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>
  544. </tr>
  545. </thead>
  546. <tbody className="bg-white divide-y divide-gray-200 dark:bg-gray-800 dark:divide-gray-700">
  547. {summaryData.map((item, index) => (
  548. <tr
  549. key={`${item.id}-${index}`}
  550. className={index % 2 === 0
  551. ? 'bg-white dark:bg-gray-800'
  552. : 'bg-gray-50 dark:bg-gray-700/50'
  553. }
  554. >
  555. <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">{item.week}</td>
  556. <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">{item.trrTotal}</td>
  557. <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">{item.fourWkAverages}</td>
  558. <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">{item.trrPlus4Wk}</td>
  559. <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">{item.powerAdds}</td>
  560. </tr>
  561. ))}
  562. </tbody>
  563. </table>
  564. </div>
  565. )}
  566. </CardContent>
  567. </Card>
  568. )}
  569. </div>
  570. </div>
  571. );
  572. }