page.tsx 22 KB

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