refactor: modify upload section

This commit is contained in:
2026-03-19 12:32:55 +05:30
parent 37d7a664e0
commit 8510bd9f32
11 changed files with 531 additions and 436 deletions

View File

@@ -33,7 +33,7 @@ const data = {
},
{
title: 'New Analysis',
url: ROUTES.NEW_ANALYSIS,
url: ROUTES.UPLOAD,
icon: Plus,
},
{

View File

@@ -1,6 +1,6 @@
'use client';
import { useState, useEffect } from 'react';
import { useState, useEffect, useRef } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
@@ -17,12 +17,23 @@ import { Project, Package as PackageType, Chainage, SessionContext } from '@/typ
import { cn } from '@/lib/utils';
type ProjectSelectionSectionProps = {
onSelectionComplete: (session: SessionContext) => void;
onSelectionComplete?: (session: SessionContext) => void;
onSelectionChange?: (session: SessionContext | null) => void;
asStep?: boolean;
hideButton?: boolean;
};
export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectionSectionProps) {
let globalProjectsCache: Project[] | null = null;
let projectsPromise: Promise<Project[]> | null = null;
export function ProjectSelectionSection({
onSelectionComplete,
onSelectionChange,
asStep = false,
hideButton = false
}: ProjectSelectionSectionProps) {
// Data states
const [projects, setProjects] = useState<Project[]>([]);
const [projects, setProjects] = useState<Project[]>(globalProjectsCache || []);
const [packages, setPackages] = useState<PackageType[]>([]);
const [chainages, setChainages] = useState<Chainage[]>([]);
@@ -32,7 +43,7 @@ export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectio
const [selectedChainage, setSelectedChainage] = useState<Chainage | null>(null);
// Loading states
const [loadingProjects, setLoadingProjects] = useState(true);
const [loadingProjects, setLoadingProjects] = useState(!globalProjectsCache);
const [loadingPackages, setLoadingPackages] = useState(false);
const [loadingChainages, setLoadingChainages] = useState(false);
@@ -41,20 +52,48 @@ export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectio
// Load projects on mount
useEffect(() => {
let isMounted = true;
const loadProjects = async () => {
// Use cache if we already have it
if (globalProjectsCache) {
if (isMounted) {
setProjects(globalProjectsCache);
setLoadingProjects(false);
}
return;
}
// If a fetch is already in flight, reuse that promise
if (!projectsPromise) {
projectsPromise = projectService.getProjects().then(data => {
globalProjectsCache = data.items;
return data.items;
}).catch(err => {
projectsPromise = null; // Reset on error to allow retry
throw err;
});
}
try {
setLoadingProjects(true);
setError(null);
const data = await projectService.getProjects();
setProjects(data.items);
const data = await projectsPromise;
if (isMounted) {
setProjects(data);
}
} catch (err) {
console.error('Failed to load projects:', err);
setError('Failed to load projects. Please check if the backend is running.');
if (isMounted) {
setError('Failed to load projects. Please check connection.');
}
} finally {
setLoadingProjects(false);
if (isMounted) {
setLoadingProjects(false);
}
}
};
loadProjects();
return () => { isMounted = false; };
}, []);
// Load packages when project changes
@@ -65,6 +104,7 @@ export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectio
return;
}
let isMounted = true;
const loadPackages = async () => {
try {
setLoadingPackages(true);
@@ -73,15 +113,22 @@ export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectio
setSelectedChainage(null);
setChainages([]);
const data = await packageService.getPackagesByProject(selectedProject.id);
setPackages(data.items);
if (isMounted) {
setPackages(data.items);
}
} catch (err) {
console.error('Failed to load packages:', err);
setError('Failed to load packages for the selected project.');
if (isMounted) {
console.error('Failed to load packages:', err);
setError('Failed to load packages for the selected project.');
}
} finally {
setLoadingPackages(false);
if (isMounted) {
setLoadingPackages(false);
}
}
};
loadPackages();
return () => { isMounted = false; };
}, [selectedProject]);
// Load chainages when package changes
@@ -92,21 +139,29 @@ export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectio
return;
}
let isMounted = true;
const loadChainages = async () => {
try {
setLoadingChainages(true);
setError(null);
setSelectedChainage(null);
const data = await chainageService.getChainagesByPackage(selectedPackage.id);
setChainages(data.items);
if (isMounted) {
setChainages(data.items);
}
} catch (err) {
console.error('Failed to load chainages:', err);
setError('Failed to load chainages for the selected package.');
if (isMounted) {
console.error('Failed to load chainages:', err);
setError('Failed to load chainages for the selected package.');
}
} finally {
setLoadingChainages(false);
if (isMounted) {
setLoadingChainages(false);
}
}
};
loadChainages();
return () => { isMounted = false; };
}, [selectedPackage]);
const handleProjectChange = (projectId: string) => {
@@ -124,8 +179,38 @@ export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectio
setSelectedChainage(chainage);
};
// Cache the last reported state to prevent infinite loops
const lastReportedIdRef = useRef<string | null>(null);
// Handle change reporting
useEffect(() => {
if (onSelectionChange) {
const currentIds = selectedProject && selectedPackage && selectedChainage
? `${selectedProject.id}-${selectedPackage.id}-${selectedChainage.id}`
: null;
if (currentIds !== lastReportedIdRef.current) {
lastReportedIdRef.current = currentIds;
if (selectedProject && selectedPackage && selectedChainage) {
onSelectionChange({
projectId: selectedProject.id,
projectName: selectedProject.name,
packageId: selectedPackage.id,
packageName: selectedPackage.name,
chainageId: selectedChainage.id,
chainageName: selectedChainage.segment_name,
chainageDirection: selectedChainage.direction,
});
} else {
onSelectionChange(null);
}
}
}
}, [selectedProject, selectedPackage, selectedChainage, onSelectionChange]);
const handleProceed = () => {
if (selectedProject && selectedPackage && selectedChainage) {
if (selectedProject && selectedPackage && selectedChainage && onSelectionComplete) {
onSelectionComplete({
projectId: selectedProject.id,
projectName: selectedProject.name,
@@ -148,6 +233,167 @@ export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectio
return 'pending';
};
const content = (
<>
{/* Error Display */}
{error && (
<div className="p-4 rounded-md bg-destructive/10 border border-destructive/20 text-destructive text-sm mb-6">
{error}
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
{/* Project Dropdown */}
<div className="space-y-2">
<Label htmlFor="project" className="text-sm font-semibold">
Project
</Label>
<Select
value={selectedProject?.id || ''}
onValueChange={handleProjectChange}
disabled={loadingProjects}
>
<SelectTrigger id="project" className="h-11">
{loadingProjects ? (
<div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
<span>Loading...</span>
</div>
) : (
<SelectValue placeholder="Select project" />
)}
</SelectTrigger>
<SelectContent>
{projects.map((project) => (
<SelectItem key={project.id} value={project.id}>
{project.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Package Dropdown */}
<div className="space-y-2">
<Label htmlFor="package" className="text-sm font-semibold">
Package
</Label>
<Select
value={selectedPackage?.id || ''}
onValueChange={handlePackageChange}
disabled={!selectedProject || loadingPackages}
>
<SelectTrigger id="package" className="h-11">
{loadingPackages ? (
<div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
<span>Loading...</span>
</div>
) : (
<SelectValue
placeholder={selectedProject ? 'Select package' : 'Select project first'}
/>
)}
</SelectTrigger>
<SelectContent>
{packages.map((pkg) => (
<SelectItem key={pkg.id} value={pkg.id}>
{pkg.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Chainage Dropdown */}
<div className="space-y-2">
<Label htmlFor="chainage" className="text-sm font-semibold">
Chainage
</Label>
<Select
value={selectedChainage?.id || ''}
onValueChange={handleChainageChange}
disabled={!selectedPackage || loadingChainages}
>
<SelectTrigger id="chainage" className="h-11">
{loadingChainages ? (
<div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
<span>Loading...</span>
</div>
) : (
<SelectValue
placeholder={selectedPackage ? 'Select chainage' : 'Select package first'}
/>
)}
</SelectTrigger>
<SelectContent>
{chainages.map((chn) => (
<SelectItem key={chn.id} value={chn.id}>
<div className="flex flex-col gap-0.5 py-0.5">
<span className="font-semibold text-sm">{chn.segment_name}</span>
<div className="flex items-center gap-2 text-[10px] text-muted-foreground font-medium">
<span>{chn.chainage_start_km}-{chn.chainage_end_km} km</span>
<span className="h-2.5 w-px bg-border" />
<span className="flex items-center gap-1 uppercase">
{chn.direction === 'UP' ? (
<ArrowUp className="h-2.5 w-2.5" />
) : (
<ArrowDown className="h-2.5 w-2.5" />
)}
{chn.direction}
</span>
</div>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
{/* Selected Summary - Only if not asStep or if specifically desired */}
{!asStep && isComplete && (
<div className="px-4 py-3 rounded-md bg-secondary/50 border text-sm mb-8">
<div className="flex items-center gap-2 flex-wrap text-muted-foreground">
<span className="font-semibold text-foreground">Selection:</span>
<span className="text-foreground">{selectedProject?.name}</span>
<span>/</span>
<span className="text-foreground">{selectedPackage?.name}</span>
<span>/</span>
<span className="text-foreground flex items-center gap-1.5">
{selectedChainage?.segment_name}
<span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-muted text-[10px] font-bold uppercase border">
{selectedChainage?.direction === 'UP' ? (
<ArrowUp className="h-2.5 w-2.5" />
) : (
<ArrowDown className="h-2.5 w-2.5" />
)}
{selectedChainage?.direction}
</span>
</span>
</div>
</div>
)}
{/* Proceed Button */}
{!hideButton && (
<Button
onClick={handleProceed}
disabled={!isComplete}
className="w-full h-14 text-base font-bold uppercase tracking-wider"
size="lg"
>
{isComplete ? 'Proceed to Upload' : 'Select all fields to proceed'}
</Button>
)}
</>
);
if (asStep) {
return content;
}
return (
<Card className="overflow-hidden">
<CardHeader className="pb-6">
@@ -203,157 +449,8 @@ export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectio
</div>
</CardHeader>
<CardContent className="space-y-8">
{/* Error Display */}
{error && (
<div className="p-4 rounded-md bg-destructive/10 border border-destructive/20 text-destructive text-sm">
{error}
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
{/* Project Dropdown */}
<div className="space-y-2">
<Label htmlFor="project" className="text-sm font-semibold">
Project
</Label>
<Select
value={selectedProject?.id || ''}
onValueChange={handleProjectChange}
disabled={loadingProjects}
>
<SelectTrigger id="project" className="h-11">
{loadingProjects ? (
<div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
<span>Loading...</span>
</div>
) : (
<SelectValue placeholder="Select project" />
)}
</SelectTrigger>
<SelectContent>
{projects.map((project) => (
<SelectItem key={project.id} value={project.id}>
{project.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Package Dropdown */}
<div className="space-y-2">
<Label htmlFor="package" className="text-sm font-semibold">
Package
</Label>
<Select
value={selectedPackage?.id || ''}
onValueChange={handlePackageChange}
disabled={!selectedProject || loadingPackages}
>
<SelectTrigger id="package" className="h-11">
{loadingPackages ? (
<div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
<span>Loading...</span>
</div>
) : (
<SelectValue
placeholder={selectedProject ? 'Select package' : 'Select project first'}
/>
)}
</SelectTrigger>
<SelectContent>
{packages.map((pkg) => (
<SelectItem key={pkg.id} value={pkg.id}>
{pkg.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Chainage Dropdown */}
<div className="space-y-2">
<Label htmlFor="chainage" className="text-sm font-semibold">
Chainage
</Label>
<Select
value={selectedChainage?.id || ''}
onValueChange={handleChainageChange}
disabled={!selectedPackage || loadingChainages}
>
<SelectTrigger id="chainage" className="h-11">
{loadingChainages ? (
<div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
<span>Loading...</span>
</div>
) : (
<SelectValue
placeholder={selectedPackage ? 'Select chainage' : 'Select package first'}
/>
)}
</SelectTrigger>
<SelectContent>
{chainages.map((chn) => (
<SelectItem key={chn.id} value={chn.id}>
<div className="flex flex-col gap-0.5 py-0.5">
<span className="font-semibold text-sm">{chn.segment_name}</span>
<div className="flex items-center gap-2 text-[10px] text-muted-foreground font-medium">
<span>{chn.chainage_start_km}-{chn.chainage_end_km} km</span>
<span className="h-2.5 w-px bg-border" />
<span className="flex items-center gap-1 uppercase">
{chn.direction === 'UP' ? (
<ArrowUp className="h-2.5 w-2.5" />
) : (
<ArrowDown className="h-2.5 w-2.5" />
)}
{chn.direction}
</span>
</div>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
{/* Selected Summary */}
{isComplete && (
<div className="px-4 py-3 rounded-md bg-secondary/50 border text-sm">
<div className="flex items-center gap-2 flex-wrap text-muted-foreground">
<span className="font-semibold text-foreground">Selection:</span>
<span className="text-foreground">{selectedProject?.name}</span>
<span>/</span>
<span className="text-foreground">{selectedPackage?.name}</span>
<span>/</span>
<span className="text-foreground flex items-center gap-1.5">
{selectedChainage?.segment_name}
<span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-muted text-[10px] font-bold uppercase border">
{selectedChainage?.direction === 'UP' ? (
<ArrowUp className="h-2.5 w-2.5" />
) : (
<ArrowDown className="h-2.5 w-2.5" />
)}
{selectedChainage?.direction}
</span>
</span>
</div>
</div>
)}
{/* Proceed Button */}
<Button
onClick={handleProceed}
disabled={!isComplete}
className="w-full h-12 text-base font-bold uppercase tracking-wide"
size="lg"
>
{isComplete ? 'Proceed to Upload' : 'Select all fields to proceed'}
</Button>
<CardContent className="pt-0">
{content}
</CardContent>
</Card>
);

View File

@@ -0,0 +1,66 @@
import * as React from 'react';
import { Check } from 'lucide-react';
import { cn } from '@/lib/utils';
interface StepperProps {
steps: {
title: string;
description?: string;
}[];
activeStep: number;
className?: string;
}
export function Stepper({ steps, activeStep, className }: StepperProps) {
return (
<div className={cn('w-full', className)}>
<div className="relative flex justify-between">
{/* Connection Lines */}
<div className="absolute top-5 left-0 right-0 h-0.5 bg-muted -z-10" />
<div
className="absolute top-5 left-0 h-0.5 bg-primary transition-all duration-500 -z-10"
style={{ width: `${(activeStep / (steps.length - 1)) * 100}%` }}
/>
{steps.map((step, index) => {
const isActive = index === activeStep;
const isCompleted = index < activeStep;
const isPending = index > activeStep;
return (
<div key={step.title} className="flex flex-col items-center flex-1">
<div
className={cn(
'w-10 h-10 rounded-full flex items-center justify-center text-sm font-semibold transition-all duration-300 border-2',
isActive
? 'bg-primary border-primary text-primary-foreground ring-4 ring-primary/10 scale-110'
: isCompleted
? 'bg-primary border-primary text-primary-foreground'
: 'bg-background border-muted text-muted-foreground',
)}
>
{isCompleted ? <Check className="h-5 w-5" /> : <span>{index + 1}</span>}
</div>
<div className="mt-4 text-center px-2">
<p
className={cn(
'text-sm font-bold transition-colors',
isActive ? 'text-foreground' : 'text-muted-foreground',
)}
>
{step.title}
</p>
{step.description && (
<p className="text-[11px] text-muted-foreground mt-1 line-clamp-1 max-w-[120px] mx-auto hidden md:block">
{step.description}
</p>
)}
</div>
</div>
);
})}
</div>
</div>
);
}