3 Commits

41 changed files with 957 additions and 1560 deletions

View File

@@ -1,10 +1,12 @@
'use client'; 'use client';
import type { ComponentProps } from 'react'; import type { ComponentProps } from 'react';
import { useRef } from 'react';
import type { FieldErrors, UseFormRegister } from 'react-hook-form'; import type { FieldErrors, UseFormRegister } from 'react-hook-form';
import { Loader2 } from 'lucide-react'; import { Loader2 } from 'lucide-react';
import { FormField } from '@/components/form'; import { FormField } from '@/components/form';
import { ProjectSelect } from '@/components/lookups/ProjectSelect';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { import {
Dialog, Dialog,
@@ -15,14 +17,6 @@ import {
DialogTitle, DialogTitle,
} from '@/components/ui/dialog'; } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import type { Project } from '@/types';
import type { PackageFormValues } from '../hooks/usePackageForm'; import type { PackageFormValues } from '../hooks/usePackageForm';
@@ -30,8 +24,6 @@ interface PackageDialogProps {
open: boolean; open: boolean;
onOpenChange: (open: boolean) => void; onOpenChange: (open: boolean) => void;
packageId?: string; packageId?: string;
projects: Project[];
isProjectsLoading: boolean;
projectId: string; projectId: string;
onProjectChange: (projectId: string) => void; onProjectChange: (projectId: string) => void;
register: UseFormRegister<PackageFormValues>; register: UseFormRegister<PackageFormValues>;
@@ -46,8 +38,6 @@ export function PackageDialog({
open, open,
onOpenChange, onOpenChange,
packageId, packageId,
projects,
isProjectsLoading,
projectId, projectId,
onProjectChange, onProjectChange,
register, register,
@@ -57,6 +47,7 @@ export function PackageDialog({
canSubmit, canSubmit,
isSaving, isSaving,
}: PackageDialogProps) { }: PackageDialogProps) {
const projectSelectPortalRef = useRef<HTMLDivElement | null>(null);
const projectErrorMessage = isSubmitted const projectErrorMessage = isSubmitted
? errors.project_id?.message ? errors.project_id?.message
: undefined; : undefined;
@@ -95,25 +86,13 @@ export function PackageDialog({
{!packageId ? ( {!packageId ? (
<FormField label="Project" required error={projectErrorMessage}> <FormField label="Project" required error={projectErrorMessage}>
<Select value={projectId} onValueChange={onProjectChange}> <ProjectSelect
<SelectTrigger aria-invalid={!!projectErrorMessage}> value={projectId}
{isProjectsLoading ? ( onValueChange={onProjectChange}
<span className="flex items-center gap-2 text-muted-foreground"> enabled={open}
<Loader2 className="size-4 animate-spin" /> disabled={isSaving}
Loading... portalContainer={projectSelectPortalRef}
</span> />
) : (
<SelectValue placeholder="Choose a project" />
)}
</SelectTrigger>
<SelectContent>
{projects.map((project) => (
<SelectItem key={project.id} value={project.id}>
{project.name}
</SelectItem>
))}
</SelectContent>
</Select>
<input <input
type="hidden" type="hidden"
{...register('project_id')} {...register('project_id')}
@@ -205,6 +184,8 @@ export function PackageDialog({
</Button> </Button>
</DialogFooter> </DialogFooter>
</form> </form>
<div ref={projectSelectPortalRef} />
</DialogContent> </DialogContent>
</Dialog> </Dialog>
); );

View File

@@ -113,8 +113,6 @@ export default function PackagePage() {
open={isDialogOpen} open={isDialogOpen}
onOpenChange={handleDialogOpenChange} onOpenChange={handleDialogOpenChange}
packageId={packageId} packageId={packageId}
projects={projects}
isProjectsLoading={projectsQuery.isLoading}
projectId={projectId} projectId={projectId}
onProjectChange={setProjectId} onProjectChange={setProjectId}
register={register} register={register}

View File

@@ -4,4 +4,6 @@ export const packageKeys = {
all: ['packages'] as const, all: ['packages'] as const,
lists: () => [...packageKeys.all, 'list'] as const, lists: () => [...packageKeys.all, 'list'] as const,
list: (params: PaginationParams) => [...packageKeys.lists(), params] as const, list: (params: PaginationParams) => [...packageKeys.lists(), params] as const,
details: () => [...packageKeys.all, 'detail'] as const,
detail: (id: string) => [...packageKeys.details(), id] as const,
}; };

View File

@@ -4,4 +4,6 @@ export const projectKeys = {
all: ['projects'] as const, all: ['projects'] as const,
lists: () => [...projectKeys.all, 'list'] as const, lists: () => [...projectKeys.all, 'list'] as const,
list: (params: PaginationParams) => [...projectKeys.lists(), params] as const, list: (params: PaginationParams) => [...projectKeys.lists(), params] as const,
details: () => [...projectKeys.all, 'detail'] as const,
detail: (id: string) => [...projectKeys.details(), id] as const,
}; };

View File

@@ -1,16 +1,11 @@
'use client'; 'use client';
import { useState, useEffect, useMemo } from 'react'; import { useMemo } from 'react';
import { useRouter, useParams } from 'next/navigation'; import { useParams } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Loader2, TrendingUp } from 'lucide-react'; import { Loader2, TrendingUp } from 'lucide-react';
import VideoPlayerSection from '@/components/videoPlayerSection'; import VideoPlayerSection from '@/components/videoPlayerSection';
import { PageHeader } from '@/components/page-header'; import { PageHeader } from '@/components/page-header';
import { sessionService } from '@/services/api'; import { CompletedVideoResult, DetectionType } from '@/types';
import { SessionContext, CompletedVideoResult, DetectionType } from '@/types';
import { clearVideoFile } from '@/lib/video-storage';
import { ROUTES } from '@/utils/routes';
import { Card } from '@/components/ui/card';
import { getDetectionModeConfig } from '@/constants/detectionModeConfig'; import { getDetectionModeConfig } from '@/constants/detectionModeConfig';
import { useVideoResultsQuery } from '../hooks/useVideoResults'; import { useVideoResultsQuery } from '../hooks/useVideoResults';
@@ -26,9 +21,7 @@ const inferDetectionType = (data: CompletedVideoResult): DetectionType => {
}; };
export default function VideoResultsPage() { export default function VideoResultsPage() {
const router = useRouter();
const { videoId } = useParams() as { videoId: string }; const { videoId } = useParams() as { videoId: string };
const [session, setSession] = useState<SessionContext | null>(null);
const { const {
data: detectionData, data: detectionData,
@@ -48,22 +41,6 @@ export default function VideoResultsPage() {
: 'Failed to load results' : 'Failed to load results'
: null; : null;
useEffect(() => {
setSession(sessionService.loadSession());
}, []);
const handleNewAnalysis = async () => {
if (videoId) {
try {
await clearVideoFile(videoId);
} catch (err) {
console.error('Failed to clear video file:', err);
}
}
sessionService.clearSession();
router.push(ROUTES.UPLOAD);
};
const getTitle = () => { const getTitle = () => {
const config = getDetectionModeConfig(detectionType); const config = getDetectionModeConfig(detectionType);
return `${config.label} Results`; return `${config.label} Results`;
@@ -71,55 +48,29 @@ export default function VideoResultsPage() {
if (isLoading) { if (isLoading) {
return ( return (
<div className="min-h-screen flex items-center justify-center"> <div className="min-h-[60vh] flex items-center justify-center">
<Card className="flex flex-col items-center gap-4 p-8"> <Loader2 className="h-8 w-8 animate-spin text-primary" />
<Loader2 className="h-8 w-8 animate-spin text-primary" />
<p className="text-sm text-muted-foreground">
Loading detection results...
</p>
</Card>
</div> </div>
); );
} }
if (error) { if (error) {
return ( return (
<div className="min-h-screen flex items-center justify-center"> <div className="min-h-[60vh] flex items-center justify-center">
<Card className="flex flex-col items-center gap-6 p-8 text-center max-w-md"> <p className="text-sm text-destructive">{error}</p>
<p className="text-destructive font-medium">{error}</p>
<div className="flex gap-4">
<Button
onClick={() => router.push(ROUTES.UPLOAD)}
variant="outline"
>
Back to Upload
</Button>
<Button onClick={handleNewAnalysis}>New Analysis</Button>
</div>
</Card>
</div> </div>
); );
} }
return ( return (
<div className="min-h-screen"> <div className="space-y-8">
<main className="min-h-screen"> <PageHeader
<div className="container mx-auto px-6 py-10 max-w-[1600px]"> title={getTitle()}
<div className="mb-8"> description={`Video ID: ${videoId}`}
<PageHeader icon={TrendingUp}
title={getTitle()} />
description={`Video ID: ${videoId}`}
icon={TrendingUp}
/>
</div>
{detectionData && ( {detectionData && <VideoPlayerSection data={detectionData} />}
<VideoPlayerSection
data={detectionData}
/>
)}
</div>
</main>
</div> </div>
); );
} }

View File

@@ -1,33 +0,0 @@
'use client';
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Loader2 } from 'lucide-react';
import { Card } from '@/components/ui/card';
import { sessionService } from '@/services/api';
import { ROUTES } from '@/utils/routes';
export default function ResultsPage() {
const router = useRouter();
useEffect(() => {
const storedSession = sessionService.loadSession();
const videoData = sessionService.loadVideoData();
if (!sessionService.isSessionValid(storedSession) || !videoData?.videoId) {
router.replace(ROUTES.UPLOAD);
return;
}
router.replace(`${ROUTES.RESULTS}/${videoData.videoId}`);
}, [router]);
return (
<div className="min-h-screen flex items-center justify-center">
<Card className="flex flex-col items-center gap-4 p-8">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
<p className="text-sm text-muted-foreground">Loading results...</p>
</Card>
</div>
);
}

View File

@@ -1,10 +1,13 @@
'use client'; 'use client';
import type { ComponentProps } from 'react'; import type { ComponentProps } from 'react';
import { useRef } from 'react';
import type { FieldErrors, UseFormRegister } from 'react-hook-form'; import type { FieldErrors, UseFormRegister } from 'react-hook-form';
import { Loader2 } from 'lucide-react'; import { Loader2 } from 'lucide-react';
import { FormField } from '@/components/form'; import { FormField } from '@/components/form';
import { PackageSelect } from '@/components/lookups/PackageSelect';
import { ProjectSelect } from '@/components/lookups/ProjectSelect';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { import {
Dialog, Dialog,
@@ -22,7 +25,6 @@ import {
SelectTrigger, SelectTrigger,
SelectValue, SelectValue,
} from '@/components/ui/select'; } from '@/components/ui/select';
import type { Package, Project } from '@/types';
import type { SegmentFormValues } from '../hooks/useSegmentForm'; import type { SegmentFormValues } from '../hooks/useSegmentForm';
@@ -30,10 +32,6 @@ interface SegmentDialogProps {
open: boolean; open: boolean;
onOpenChange: (open: boolean) => void; onOpenChange: (open: boolean) => void;
segmentId?: string; segmentId?: string;
projects: Project[];
packages: Package[];
isProjectsLoading: boolean;
isPackagesLoading: boolean;
projectId: string; projectId: string;
onProjectChange: (projectId: string) => void; onProjectChange: (projectId: string) => void;
packageId: string; packageId: string;
@@ -52,10 +50,6 @@ export function SegmentDialog({
open, open,
onOpenChange, onOpenChange,
segmentId, segmentId,
projects,
packages,
isProjectsLoading,
isPackagesLoading,
projectId, projectId,
onProjectChange, onProjectChange,
packageId, packageId,
@@ -69,6 +63,8 @@ export function SegmentDialog({
canSubmit, canSubmit,
isSaving, isSaving,
}: SegmentDialogProps) { }: SegmentDialogProps) {
const projectSelectPortalRef = useRef<HTMLDivElement | null>(null);
const packageSelectPortalRef = useRef<HTMLDivElement | null>(null);
const getError = (field: keyof SegmentFormValues) => const getError = (field: keyof SegmentFormValues) =>
isSubmitted ? errors[field]?.message : undefined; isSubmitted ? errors[field]?.message : undefined;
@@ -104,25 +100,13 @@ export function SegmentDialog({
required required
error={getError('project_id')} error={getError('project_id')}
> >
<Select value={projectId} onValueChange={onProjectChange}> <ProjectSelect
<SelectTrigger aria-invalid={!!getError('project_id')}> value={projectId}
{isProjectsLoading ? ( onValueChange={onProjectChange}
<span className="flex items-center gap-2 text-muted-foreground"> enabled={open}
<Loader2 className="size-4 animate-spin" /> disabled={isSaving}
Loading... portalContainer={projectSelectPortalRef}
</span> />
) : (
<SelectValue placeholder="Choose a project" />
)}
</SelectTrigger>
<SelectContent>
{projects.map((project) => (
<SelectItem key={project.id} value={project.id}>
{project.name}
</SelectItem>
))}
</SelectContent>
</Select>
<input <input
type="hidden" type="hidden"
{...register('project_id')} {...register('project_id')}
@@ -136,35 +120,14 @@ export function SegmentDialog({
required required
error={getError('package_id')} error={getError('package_id')}
> >
<Select <PackageSelect
value={packageId} value={packageId}
onValueChange={onPackageChange} onValueChange={onPackageChange}
disabled={!projectId || isPackagesLoading} projectId={projectId}
> enabled={open && Boolean(projectId)}
<SelectTrigger aria-invalid={!!getError('package_id')}> disabled={!projectId || isSaving}
{isPackagesLoading ? ( portalContainer={packageSelectPortalRef}
<span className="flex items-center gap-2 text-muted-foreground"> />
<Loader2 className="size-4 animate-spin" />
Loading...
</span>
) : (
<SelectValue
placeholder={
projectId
? 'Choose a package'
: 'Select project first'
}
/>
)}
</SelectTrigger>
<SelectContent>
{packages.map((pkg) => (
<SelectItem key={pkg.id} value={pkg.id}>
{pkg.name}
</SelectItem>
))}
</SelectContent>
</Select>
<input <input
type="hidden" type="hidden"
{...register('package_id')} {...register('package_id')}
@@ -350,6 +313,9 @@ export function SegmentDialog({
</Button> </Button>
</DialogFooter> </DialogFooter>
</form> </form>
<div ref={projectSelectPortalRef} />
<div ref={packageSelectPortalRef} />
</DialogContent> </DialogContent>
</Dialog> </Dialog>
); );

View File

@@ -44,15 +44,6 @@ export function useAllPackageOptionsQuery() {
}); });
} }
export function usePackagesByProjectQuery(projectId: string, enabled: boolean) {
return useQuery({
queryKey: ['packages', 'by-project', projectId],
queryFn: () =>
packageService.getPackagesByProject(projectId, { skip: 0, limit: 1000 }),
enabled: enabled && Boolean(projectId),
});
}
export function useDeleteSegmentMutation() { export function useDeleteSegmentMutation() {
const queryClient = useQueryClient(); const queryClient = useQueryClient();

View File

@@ -15,7 +15,6 @@ import { useSegmentForm } from './hooks/useSegmentForm';
import { import {
useAllPackageOptionsQuery, useAllPackageOptionsQuery,
useDeleteSegmentMutation, useDeleteSegmentMutation,
usePackagesByProjectQuery,
useProjectOptionsQuery, useProjectOptionsQuery,
useSegmentsQuery, useSegmentsQuery,
} from './hooks/useSegmentQueries'; } from './hooks/useSegmentQueries';
@@ -48,11 +47,6 @@ export default function SegmentPage() {
canSubmit, canSubmit,
isSaving, isSaving,
} = segmentForm; } = segmentForm;
const projectPackagesQuery = usePackagesByProjectQuery(
projectId,
isDialogOpen,
);
const openCreate = useCallback(() => { const openCreate = useCallback(() => {
prepareCreateSegment(); prepareCreateSegment();
setIsDialogOpen(true); setIsDialogOpen(true);
@@ -95,7 +89,6 @@ export default function SegmentPage() {
const projects = projectsQuery.data?.items ?? []; const projects = projectsQuery.data?.items ?? [];
const allPackages = allPackagesQuery.data?.items ?? []; const allPackages = allPackagesQuery.data?.items ?? [];
const projectPackages = projectPackagesQuery.data?.items ?? [];
const segments = segmentsQuery.data?.items ?? []; const segments = segmentsQuery.data?.items ?? [];
const total = segmentsQuery.data?.totalItems ?? 0; const total = segmentsQuery.data?.totalItems ?? 0;
const columns = useSegmentColumns(projects, allPackages); const columns = useSegmentColumns(projects, allPackages);
@@ -133,10 +126,6 @@ export default function SegmentPage() {
open={isDialogOpen} open={isDialogOpen}
onOpenChange={handleDialogOpenChange} onOpenChange={handleDialogOpenChange}
segmentId={segmentId} segmentId={segmentId}
projects={projects}
packages={projectPackages}
isProjectsLoading={projectsQuery.isLoading}
isPackagesLoading={projectPackagesQuery.isLoading}
projectId={projectId} projectId={projectId}
onProjectChange={setProjectId} onProjectChange={setProjectId}
packageId={packageId} packageId={packageId}

View File

@@ -4,4 +4,6 @@ export const segmentKeys = {
all: ['segments'] as const, all: ['segments'] as const,
lists: () => [...segmentKeys.all, 'list'] as const, lists: () => [...segmentKeys.all, 'list'] as const,
list: (params: PaginationParams) => [...segmentKeys.lists(), params] as const, list: (params: PaginationParams) => [...segmentKeys.lists(), params] as const,
details: () => [...segmentKeys.all, 'detail'] as const,
detail: (id: string) => [...segmentKeys.details(), id] as const,
}; };

View File

@@ -0,0 +1,32 @@
'use client';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { PageHeader } from '@/components/page-header';
import { Ticket } from 'lucide-react';
export default function TicketPage() {
return (
<div className="min-h-screen pb-12">
<main>
<div className="mb-10">
<PageHeader
title="Ticket"
description="Uploaded video details will be shown here."
icon={Ticket}
/>
</div>
<Card>
<CardHeader>
<CardTitle>Ticket Page</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">
This is ticket page for now.
</p>
</CardContent>
</Card>
</main>
</div>
);
}

View File

@@ -1,260 +0,0 @@
'use client';
import { useState, useEffect, useCallback, useRef } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Loader2, TrendingUp, ArrowUp, ArrowDown } from 'lucide-react';
import { PageHeader } from '@/components/page-header';
import { sessionService, videoService } from '@/services/api';
import { SessionContext } from '@/types';
import { ROUTES } from '@/utils/routes';
import { Button } from '@/components/ui/button';
const API_URL = process.env.NEXT_PUBLIC_API_URL;
const WS_URL = API_URL?.replace(/^https:\/\//, 'wss://').replace(
/^http:\/\//,
'ws://',
);
export default function VideoProcessingPage() {
const router = useRouter();
const { videoId } = useParams() as { videoId: string };
const [session, setSession] = useState<SessionContext | null>(null);
const [isLoading, setIsLoading] = useState(true);
// Processing states
const [progress, setProgress] = useState(0);
const [statusMessage, setStatusMessage] = useState('Initializing...');
const [error, setError] = useState<string | null>(null);
const wsRef = useRef<WebSocket | null>(null);
const connectWebSocket = useCallback(
(vid: string) => {
if (wsRef.current) return wsRef.current;
const ws = new WebSocket(`${WS_URL}/ws/${vid}`);
wsRef.current = ws;
ws.onmessage = async (event) => {
const data = JSON.parse(event.data);
if (data.type === 'progress' || data.progress !== undefined) {
setProgress(data.progress || 0);
let message = data.message || 'Processing...';
const uniqueCount =
data.unique_potholes ??
data.unique_pothole ??
data.unique_signboards ??
data.unique_signboard ??
data.unique_culverts ??
data.unique_culvert ??
data.unique_drain_issue;
if (uniqueCount !== undefined) {
message += ` | Unique: ${uniqueCount} | Total: ${data.total_detections || 0}`;
}
setStatusMessage(message);
}
if (data.type === 'complete' || data.status === 'completed') {
setStatusMessage('Processing completed! Finalizing...');
ws.close();
// Navigate to results
setTimeout(() => router.push(`/results/${vid}`), 1000);
}
if (data.type === 'error') {
setError('Error: ' + data.message);
setStatusMessage('');
ws.close();
}
};
ws.onerror = () => {
setStatusMessage('Connection lost. Reconnecting...');
wsRef.current = null;
setTimeout(() => connectWebSocket(vid), 3000);
};
ws.onclose = () => {
wsRef.current = null;
};
return ws;
},
[router],
);
useEffect(() => {
const storedSession = sessionService.loadSession();
setSession(storedSession);
let isMounted = true;
const checkStatus = async () => {
try {
const statusData = await videoService.getVideoStatus(videoId);
if (!isMounted) return;
if (statusData.status === 'completed') {
router.replace(`/results/${videoId}`);
return;
}
if (statusData.status === 'error') {
setError(
statusData.message || 'An error occurred during processing.',
);
setIsLoading(false);
return;
}
// If processing, start WebSocket
setProgress(statusData.progress || 0);
setStatusMessage(statusData.message || 'Resuming processing...');
connectWebSocket(videoId);
setIsLoading(false);
} catch (err) {
console.error('Status check failed:', err);
if (isMounted) {
setError('Failed to connect to server.');
setIsLoading(false);
}
}
};
if (videoId) {
checkStatus();
}
return () => {
isMounted = false;
if (wsRef.current) {
wsRef.current.close();
wsRef.current = null;
}
};
}, [videoId, router, connectWebSocket]);
if (isLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<Card className="p-8">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
</Card>
</div>
);
}
return (
<div className="min-h-screen">
<main className="min-h-screen flex flex-col">
<div className="flex-1 container mx-auto px-6 py-6 max-w-340 flex flex-col">
<div className="mb-6">
<PageHeader
title="Uploading Analysis"
description={`Real-time analysis progress for video ID: ${videoId}`}
icon={TrendingUp}
/>
</div>
{session && (
<div className="mb-6">
<Card className="p-0 border shadow-sm overflow-hidden">
<div className="flex flex-col md:flex-row md:items-center py-4 px-6 gap-6 bg-card">
<div className="flex flex-wrap items-center gap-x-12 gap-y-4 flex-1">
<div className="flex flex-col">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
Project
</span>
<span className="text-base font-bold leading-tight">
{session.projectName}
</span>
</div>
<div className="flex flex-col border-l pl-12 border-border/60">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
Package
</span>
<span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.packageName}
</span>
</div>
<div className="flex flex-col border-l pl-12 border-border/60">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
Segment
</span>
<span className="text-sm font-semibold text-muted-foreground leading-tight flex items-center gap-1.5">
{session.chainageName}
{session.chainageDirection && (
<span className="inline-flex items-center gap-1 px-1 py-0.5 rounded bg-muted text-[10px] font-bold uppercase border">
{session.chainageDirection === 'UP' ? (
<ArrowUp className="h-2.5 w-2.5" />
) : (
<ArrowDown className="h-2.5 w-2.5" />
)}
{session.chainageDirection}
</span>
)}
</span>
</div>
</div>
</div>
</Card>
</div>
)}
<Card className="flex-1 flex flex-col items-center justify-center py-12 px-8 min-h-[450px]">
<div className="flex flex-col items-center justify-center w-full max-w-2xl space-y-10">
<div className="text-center space-y-4">
<h2 className="text-3xl font-bold tracking-tight">
Uploading ...
</h2>
<p className="text-sm font-mono text-muted-foreground tracking-widest">
ID: {videoId}
</p>
</div>
<div className="w-full space-y-4">
<div className="flex items-center justify-between text-sm">
<span className="font-bold text-muted-foreground text-xs uppercase tracking-widest">
Progress
</span>
<span className="font-bold text-primary text-lg">
{progress}%
</span>
</div>
<div className="h-4 rounded-full bg-secondary overflow-hidden border">
<div
className="h-full bg-primary transition-all duration-1000 ease-in-out"
style={{ width: `${progress}%` }}
/>
</div>
<div className="text-center pt-2">
<div className="inline-flex items-center gap-3 px-4 py-2 rounded-full border bg-secondary/30">
<Loader2 className="h-4 w-4 animate-spin text-primary" />
<p className="text-sm font-semibold">{statusMessage}</p>
</div>
</div>
</div>
{error && (
<div className="w-full p-6 rounded-md bg-destructive/10 border border-destructive/20 text-center space-y-3">
<p className="text-destructive font-medium">{error}</p>
<Button
variant="outline"
size="sm"
onClick={() => window.location.reload()}
>
Retry Connection
</Button>
</div>
)}
</div>
</Card>
</div>
</main>
</div>
);
}

View File

@@ -0,0 +1,50 @@
'use client';
import { FormField, SelectPopover } from '@/components/form';
const options = [
{ value: 'yolo', label: 'Road Defect Detection' },
{ value: 'yoloe', label: 'YOLOE Open-Vocabulary Detection' },
{ value: 'yoloe_trained_vl', label: 'YOLOE With Vision Language Model' },
{ value: 'culvert_detection', label: 'Culvert Detection' },
{ value: 'combined', label: 'Road Defect Detection with vl' },
] as const;
interface AnalysisSettingsSectionProps {
value: string;
onValueChange: (value: string) => void;
disabled?: boolean;
}
export function AnalysisSettingsSection({
value,
onValueChange,
disabled = false,
}: AnalysisSettingsSectionProps) {
return (
<section className="space-y-3">
<div>
<h2 className="text-sm font-semibold text-foreground">
Analysis Settings
</h2>
<p className="text-xs text-muted-foreground">
Select the AI model workflow for this job.
</p>
</div>
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
<FormField id="analysis-method" label="Analysis Method">
<SelectPopover
options={options}
value={value}
onValueChange={onValueChange}
disabled={disabled}
placeholder="Select method"
searchPlaceholder="Search methods"
emptyMessage="No methods found."
/>
</FormField>
</div>
</section>
);
}

View File

@@ -0,0 +1,50 @@
'use client';
import { UploadFileDropzone } from './UploadFileDropzone';
interface InputDataSectionProps {
videoFile: File | null;
gpsFile: File | null;
onVideoFileChange: (file: File | null) => void;
onGpsFileChange: (file: File | null) => void;
disabled?: boolean;
}
export function InputDataSection({
videoFile,
gpsFile,
onVideoFileChange,
onGpsFileChange,
disabled = false,
}: InputDataSectionProps) {
return (
<section className="space-y-3">
<div>
<h2 className="text-sm font-semibold text-foreground">Input Data</h2>
<p className="text-xs text-muted-foreground">
Attach the road video and GPS telemetry for processing.
</p>
</div>
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
<UploadFileDropzone
title="Drop video here or browse"
description="Accepted formats: MP4, MOV, AVI, MKV"
accept="video/*"
file={videoFile}
onFileChange={onVideoFileChange}
disabled={disabled}
/>
<UploadFileDropzone
title="Drop GPS JSON here or browse"
description="Accepted format: JSON telemetry file"
accept=".json,application/json"
file={gpsFile}
onFileChange={onGpsFileChange}
disabled={disabled}
/>
</div>
</section>
);
}

View File

@@ -0,0 +1,145 @@
'use client';
import { useCallback, useEffect, useRef, useState } from 'react';
import { FormField } from '@/components/form';
import { PackageSelect } from '@/components/lookups/PackageSelect';
import { ProjectSelect } from '@/components/lookups/ProjectSelect';
import { SegmentSelect } from '@/components/lookups/SegmentSelect';
import { packageService, projectService, chainageService } from '@/services/api';
import type { Chainage, Package as PackageType, Project, SessionContext } from '@/types';
interface LocationSectionProps {
value: SessionContext | null;
onChange: (session: SessionContext | null) => void;
disabled?: boolean;
}
export function LocationSection({
value,
onChange,
disabled = false,
}: LocationSectionProps) {
const [projectId, setProjectId] = useState(value?.projectId ?? '');
const [packageId, setPackageId] = useState(value?.packageId ?? '');
const [segmentId, setSegmentId] = useState(value?.chainageId ?? '');
const [project, setProject] = useState<Project | null>(null);
const [selectedPackage, setSelectedPackage] = useState<PackageType | null>(
null,
);
const [segment, setSegment] = useState<Chainage | null>(null);
const latestProjectIdRef = useRef('');
const latestPackageIdRef = useRef('');
const latestSegmentIdRef = useRef('');
useEffect(() => {
if (project && selectedPackage && segment) {
onChange({
projectId: project.id,
projectName: project.name,
packageId: selectedPackage.id,
packageName: selectedPackage.name,
chainageId: segment.id,
chainageName: segment.segment_name,
chainageDirection: segment.direction,
});
return;
}
onChange(null);
}, [onChange, project, selectedPackage, segment]);
const handleProjectChange = useCallback((nextProjectId: string) => {
latestProjectIdRef.current = nextProjectId;
latestPackageIdRef.current = '';
latestSegmentIdRef.current = '';
setProjectId(nextProjectId);
setPackageId('');
setSegmentId('');
setProject(null);
setSelectedPackage(null);
setSegment(null);
if (!nextProjectId) return;
void projectService.getProjectById(nextProjectId).then((nextProject) => {
if (latestProjectIdRef.current === nextProjectId) {
setProject(nextProject);
}
});
}, []);
const handlePackageChange = useCallback((nextPackageId: string) => {
latestPackageIdRef.current = nextPackageId;
latestSegmentIdRef.current = '';
setPackageId(nextPackageId);
setSegmentId('');
setSelectedPackage(null);
setSegment(null);
if (!nextPackageId) return;
void packageService.getPackageById(nextPackageId).then((nextPackage) => {
if (latestPackageIdRef.current === nextPackageId) {
setSelectedPackage(nextPackage);
}
});
}, []);
const handleSegmentChange = useCallback((nextSegmentId: string) => {
latestSegmentIdRef.current = nextSegmentId;
setSegmentId(nextSegmentId);
setSegment(null);
if (!nextSegmentId) return;
void chainageService.getChainageById(nextSegmentId).then((nextSegment) => {
if (latestSegmentIdRef.current === nextSegmentId) {
setSegment(nextSegment);
}
});
}, []);
return (
<section className="space-y-3">
<div>
<h2 className="text-sm font-semibold text-foreground">Location</h2>
<p className="text-xs text-muted-foreground">
Select the project hierarchy for this analysis job.
</p>
</div>
<div className="grid grid-cols-1 gap-3 md:grid-cols-3">
<FormField label="Project" required>
<ProjectSelect
value={projectId}
onValueChange={handleProjectChange}
disabled={disabled}
/>
</FormField>
<FormField label="Package" required>
<PackageSelect
value={packageId}
onValueChange={handlePackageChange}
projectId={projectId}
enabled={Boolean(projectId)}
disabled={disabled || !projectId}
/>
</FormField>
<FormField label="Segment" required>
<SegmentSelect
value={segmentId}
onValueChange={handleSegmentChange}
packageId={packageId}
enabled={Boolean(packageId)}
disabled={disabled || !packageId}
/>
</FormField>
</div>
</section>
);
}

View File

@@ -0,0 +1,93 @@
'use client';
import { useRef, useState } from 'react';
import { FileCheck2, UploadCloud } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { cn } from '@/lib/utils';
interface UploadFileDropzoneProps {
title: string;
description: string;
accept: string;
file: File | null;
onFileChange: (file: File | null) => void;
disabled?: boolean;
}
export function UploadFileDropzone({
title,
description,
accept,
file,
onFileChange,
disabled = false,
}: UploadFileDropzoneProps) {
const inputRef = useRef<HTMLInputElement | null>(null);
const [isDragging, setIsDragging] = useState(false);
const handleFiles = (files: FileList | null) => {
if (disabled) return;
onFileChange(files?.[0] ?? null);
};
return (
<div
role="button"
tabIndex={disabled ? -1 : 0}
aria-disabled={disabled}
onClick={() => {
if (!disabled) inputRef.current?.click();
}}
onKeyDown={(event) => {
if (!disabled && (event.key === 'Enter' || event.key === ' ')) {
event.preventDefault();
inputRef.current?.click();
}
}}
onDragOver={(event) => {
event.preventDefault();
if (!disabled) setIsDragging(true);
}}
onDragLeave={() => setIsDragging(false)}
onDrop={(event) => {
event.preventDefault();
setIsDragging(false);
handleFiles(event.dataTransfer.files);
}}
className={cn(
'group flex min-h-32 cursor-pointer flex-col justify-between rounded-md border border-dashed bg-card/60 p-4 transition-colors',
'hover:border-primary/60 hover:bg-secondary/40',
isDragging && 'border-primary bg-secondary/60',
disabled && 'pointer-events-none cursor-not-allowed opacity-60',
)}
>
<input
ref={inputRef}
type="file"
accept={accept}
className="hidden"
onChange={(event) => handleFiles(event.target.files)}
disabled={disabled}
/>
<div className="space-y-3">
<div className="flex size-9 items-center justify-center rounded-md border bg-background">
<UploadCloud className="size-4 text-muted-foreground" />
</div>
<div>
<p className="text-sm font-medium text-foreground">{title}</p>
<p className="mt-1 text-xs text-muted-foreground">{description}</p>
</div>
</div>
{file ? (
<Badge variant="secondary" className="mt-4 max-w-full justify-start">
<FileCheck2 className="size-3" />
<span className="truncate">{file.name}</span>
</Badge>
) : null}
</div>
);
}

View File

@@ -1,303 +1,134 @@
'use client'; 'use client';
import { useState, useEffect, useCallback } from 'react'; import { useState } from 'react';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { import { Loader2, Play, TrendingUp } from 'lucide-react';
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Loader2, TrendingUp, ChevronRight } from 'lucide-react';
import { PageHeader } from '@/components/page-header';
import { sessionService, videoService } from '@/services/api';
import { SessionContext } from '@/types';
import { storeVideoFile } from '@/lib/video-storage';
import { ProjectSelectionSection } from '@/components/project-selection-section';
import { Reveal } from '@/components/ui/reveal';
import { cn } from '@/lib/utils';
const DETECTION_METHODS = [ import { PageHeader } from '@/components/page-header';
{ value: 'yolo', label: 'Road Defect Detection' }, import { Button } from '@/components/ui/button';
// { value: 'yolo_vl', label: 'YOLO with Vision-Language Model' }, import { Card, CardContent } from '@/components/ui/card';
// { value: 'sam3', label: 'OpenAI SAM 3 Segmentation Model' }, import { Separator } from '@/components/ui/separator';
{ value: 'yoloe', label: 'YOLOE Open-Vocabulary Detection' }, import { videoService } from '@/services/api';
{ value: 'yoloe_trained_vl', label: 'YOLOE With Vision Language Model' }, import type { SessionContext } from '@/types';
{ value: 'culvert_detection', label: 'Culvert Detection' }, import { ROUTES } from '@/utils/routes';
{ value: 'combined', label: 'Road Defect Detection with vl' },
// { value: 'gemini_video', label: 'Gemini AI Analysis' }, import { AnalysisSettingsSection } from './components/AnalysisSettingsSection';
] as const; import { InputDataSection } from './components/InputDataSection';
import { LocationSection } from './components/LocationSection';
export default function UploadPage() { export default function UploadPage() {
const router = useRouter(); const router = useRouter();
const [session, setSession] = useState<SessionContext | null>(null); const [session, setSession] = useState<SessionContext | null>(null);
const [isLoading, setIsLoading] = useState(true); const [videoFile, setVideoFile] = useState<File | null>(null);
const [gpsFile, setGpsFile] = useState<File | null>(null);
// Form states const [analysisMethod, setAnalysisMethod] = useState('yolo');
const [file, setFile] = useState<File | null>(null); const [isSubmitting, setIsSubmitting] = useState(false);
const [jsonFile, setJsonFile] = useState<File | null>(null);
const [selectMethod, setSelectMethod] = useState('yolo');
// Upload states
const [uploading, setUploading] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
// Load session on mount const isLocationComplete = Boolean(
useEffect(() => { session?.projectId && session.packageId && session.chainageId,
// We don't load session on mount for the upload page to ensure );
// project details are filled manually as requested. const canSubmit = Boolean(
setIsLoading(false); isLocationComplete && videoFile && gpsFile && analysisMethod,
}, []);
const handleSelectionChange = useCallback(
(selectedSession: SessionContext | null) => {
setSession(selectedSession);
if (selectedSession) {
sessionService.saveSession(selectedSession);
}
},
[],
); );
const handleUpload = async () => { const handleSubmit = async () => {
if (!file) { if (!session?.chainageId || !videoFile || !gpsFile) {
setError('Please select a video file'); setError('Complete location and input data before starting analysis.');
return;
}
if (!jsonFile) {
setError('Please select a GPS JSON file');
return;
}
if (!session) {
setError('Please complete the project selection first');
return; return;
} }
const formData = new FormData(); const formData = new FormData();
formData.append('file', file); formData.append('file', videoFile);
formData.append('detection_mode', selectMethod); formData.append('detection_mode', analysisMethod);
formData.append('chainage_id', session.chainageId as string); formData.append('chainage_id', session.chainageId);
formData.append('json_file', jsonFile); formData.append('json_file', gpsFile);
setUploading(true); setIsSubmitting(true);
setError(null); setError(null);
try { try {
const result = await videoService.uploadVideo(formData); await videoService.uploadVideo(formData);
router.push(ROUTES.TICKET);
// Store file locally
if (file) {
try {
await storeVideoFile(result.video_id, file);
} catch (err) {
console.error('Failed to store video file:', err);
}
}
sessionService.saveVideoData({ videoId: result.video_id });
router.push(`/upload/${result.video_id}`);
} catch (err) { } catch (err) {
let errorMessage = 'Upload failed'; setIsSubmitting(false);
if (err instanceof TypeError && err.message === 'Failed to fetch') { if (err instanceof TypeError && err.message === 'Failed to fetch') {
errorMessage = setError('Cannot connect to server. Please check if backend is running.');
'Cannot connect to server. Please check if backend is running.'; return;
} else if (err instanceof Error) {
errorMessage = err.message;
} }
setError(errorMessage); setError(err instanceof Error ? err.message : 'Upload failed');
setUploading(false);
} }
}; };
if (isLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<Loader2 className="h-10 w-10 animate-spin text-primary" />
</div>
);
}
const isSessionComplete = !!(
session && sessionService.isSessionValid(session)
);
const isFormValid = isSessionComplete && file && jsonFile;
return ( return (
<div className="min-h-screen pb-12"> <div className="space-y-5">
<main> <PageHeader
{/* Header */} title="Create Analysis Job"
<div className="mb-10"> description="Configure location, upload data, and start AI analysis."
<PageHeader icon={TrendingUp}
title="Intelligent Road Asset AI Analysis" />
description="High-precision detection for potholes, signboards, and culverts from video data"
icon={TrendingUp} <Card>
<CardContent className="space-y-5 p-5">
<LocationSection
value={session}
onChange={setSession}
disabled={isSubmitting}
/> />
</div>
<div className="space-y-8 mt-8"> <Separator />
{/* Module 1: Project Selection */}
<Reveal direction="up" delay={0.1}>
<Card className="border">
<CardHeader>
<CardTitle className="text-xl font-bold">
1. Project Details
</CardTitle>
<CardDescription>
Select the target project, package, and segment.
</CardDescription>
</CardHeader>
<CardContent>
<ProjectSelectionSection
onSelectionChange={handleSelectionChange}
asStep={true}
hideButton={true}
/>
</CardContent>
</Card>
</Reveal>
{/* Module 2: Upload Data */} <InputDataSection
<Reveal direction="up" delay={0.2}> videoFile={videoFile}
<Card gpsFile={gpsFile}
className={cn( onVideoFileChange={(file) => {
'border transition-all duration-300', setVideoFile(file);
!isSessionComplete && setError(null);
'opacity-60 pointer-events-none grayscale-[0.5]', }}
)} onGpsFileChange={(file) => {
setGpsFile(file);
setError(null);
}}
disabled={isSubmitting}
/>
<Separator />
<AnalysisSettingsSection
value={analysisMethod}
onValueChange={setAnalysisMethod}
disabled={isSubmitting}
/>
{error ? (
<div className="rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">
{error}
</div>
) : null}
<div className="flex justify-end">
<Button
type="button"
size="lg"
disabled={!canSubmit || isSubmitting}
onClick={handleSubmit}
className="w-full gap-2 md:w-auto"
> >
<CardHeader> {isSubmitting ? (
<CardTitle className="text-xl font-bold flex items-center gap-2"> <>
2. Upload Video Data <Loader2 className="size-4 animate-spin" />
</CardTitle> Starting analysis...
<CardDescription> </>
Provide the video file and GPS telemetry for processing. ) : (
</CardDescription> <>
</CardHeader> <Play className="size-4" />
<CardContent className="space-y-6"> Start Analysis
<div className="grid grid-cols-1 gap-6 text-sm"> </>
{/* Video File Input */} )}
<div className="space-y-2"> </Button>
<Label </div>
htmlFor="video-file" </CardContent>
className="text-sm font-semibold" </Card>
>
Video File <span className="text-destructive">*</span>
</Label>
<div className="relative group">
<Input
id="video-file"
type="file"
accept="video/*"
onChange={(e) => {
setFile(e.target.files?.[0] || null);
setError(null);
}}
disabled={uploading || !isSessionComplete}
className="h-12 bg-muted/30 border-dashed border-2 group-hover:border-primary/50 transition-colors cursor-pointer file:mr-4 file:py-1.5 file:px-3 file:rounded-md file:border-0 file:bg-primary file:text-primary-foreground file:font-semibold file:text-xs"
/>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{/* JSON File Input */}
<div className="space-y-2">
<Label
htmlFor="json-file"
className="text-sm font-semibold"
>
GPS JSON File{' '}
<span className="text-destructive">*</span>
</Label>
<Input
id="json-file"
type="file"
accept=".json,application/json"
onChange={(e) => {
setJsonFile(e.target.files?.[0] || null);
setError(null);
}}
disabled={uploading || !isSessionComplete}
required
className="h-11 bg-muted/30 file:mr-3 file:py-1.5 file:px-3 file:rounded-md file:border-0 file:bg-primary/10 file:text-primary file:font-medium file:text-xs"
/>
</div>
{/* Select Method */}
<div className="space-y-2">
<Label
htmlFor="select-method"
className="text-sm font-semibold"
>
Analysis Method
</Label>
<Select
value={selectMethod}
onValueChange={setSelectMethod}
disabled={uploading || !isSessionComplete}
>
<SelectTrigger
id="select-method"
className="h-11 bg-muted/20"
>
<SelectValue placeholder="Select method" />
</SelectTrigger>
<SelectContent>
{DETECTION_METHODS.map((method) => (
<SelectItem key={method.value} value={method.value}>
{method.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</div>
{/* Error Display */}
{error && (
<div className="p-4 rounded-md bg-destructive/5 border border-destructive/20 text-destructive text-sm font-medium animate-in fade-in slide-in-from-top-1">
{error}
</div>
)}
{/* Primary Action Button */}
<div className="pt-2">
<Button
onClick={handleUpload}
disabled={!isFormValid || uploading}
className="w-full h-14 font-extrabold uppercase tracking-wider"
>
{uploading ? (
<div className="flex items-center gap-3">
<Loader2 className="h-5 w-5 animate-spin" />
<span>Uploading...</span>
</div>
) : (
<div className="flex items-center gap-2">
<span>Upload & Process Analysis</span>
<ChevronRight className="h-5 w-5" />
</div>
)}
</Button>
</div>
</CardContent>
</Card>
</Reveal>
</div>
</main>
</div> </div>
); );
} }

View File

@@ -78,7 +78,7 @@
} }
@theme inline { @theme inline {
--font-sans: 'Geist', 'Geist Fallback', system-ui, sans-serif; --font-sans: 'Poppins', 'Poppins Fallback', system-ui, sans-serif;
--font-mono: 'Geist Mono', 'Geist Mono Fallback', monospace; --font-mono: 'Geist Mono', 'Geist Mono Fallback', monospace;
--color-background: var(--background); --color-background: var(--background);
--color-foreground: var(--foreground); --color-foreground: var(--foreground);

View File

@@ -1,14 +1,15 @@
import type { Metadata } from 'next'; import type { Metadata } from 'next';
import { Geist, Geist_Mono } from 'next/font/google'; import { Geist_Mono, Poppins } from 'next/font/google';
import './globals.css'; import './globals.css';
import { ThemeProvider } from '@/providers/ThemeProvider'; import { ThemeProvider } from '@/providers/ThemeProvider';
import AppInitializer from '@/providers/AppInitializer'; import AppInitializer from '@/providers/AppInitializer';
import QueryProvider from '@/providers/QueryProvider'; import QueryProvider from '@/providers/QueryProvider';
import { Toaster } from '@/components/ui/sonner'; import { Toaster } from '@/components/ui/sonner';
const geistSans = Geist({ const poppins = Poppins({
variable: '--font-geist-sans', variable: '--font-poppins',
subsets: ['latin'], subsets: ['latin'],
weight: ['400', '500', '600', '700'],
}); });
const geistMono = Geist_Mono({ const geistMono = Geist_Mono({
@@ -32,7 +33,7 @@ export default function RootLayout({
return ( return (
<html lang="en" suppressHydrationWarning> <html lang="en" suppressHydrationWarning>
<body <body
className={`${geistSans.variable} ${geistMono.variable} antialiased`} className={`${poppins.variable} ${geistMono.variable} antialiased`}
> >
<ThemeProvider <ThemeProvider
attribute="class" attribute="class"

View File

@@ -5,10 +5,11 @@
h4, h4,
h5, h5,
h6 { h6 {
/* margin: 0.1rem 0 0.1rem; */
font-family: inherit; font-family: inherit;
font-weight: 600; font-weight: 500;
line-height: 1.2; line-height: 1.2;
letter-spacing: 0;
text-transform: capitalize;
color: var(--foreground); color: var(--foreground);
} }
@@ -22,32 +23,37 @@
} }
h1 { h1 {
font-size: 2rem; font-size: 35px;
} }
h2 { h2 {
font-size: 1.875rem; font-size: 30px;
} }
h3 { h3 {
font-size: 1.75rem; font-size: 25px;
} }
h4 { h4 {
font-size: 1.5rem; font-size: 20px;
} }
h5 { h5 {
font-size: 1.25rem; font-size: 15px;
} }
h6 { h6 {
font-size: 1rem; font-size: 10px;
} }
p { p {
margin: 0.2rem 0 0.1rem; margin: 0.2rem 0 0.1rem;
/* line-height: 1.5; */ font-family: inherit;
font-size: 14px;
font-weight: 500;
line-height: 1;
letter-spacing: 0;
text-transform: capitalize;
} }
p:last-child { p:last-child {

View File

@@ -0,0 +1,117 @@
'use client';
import { useMemo, useState } from 'react';
import { Check, ChevronDown } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover';
import { cn } from '@/lib/utils';
export interface SelectPopoverOption {
value: string;
label: string;
disabled?: boolean;
}
interface SelectPopoverProps {
options: readonly SelectPopoverOption[];
value: string;
onValueChange: (value: string) => void;
placeholder?: string;
searchPlaceholder?: string;
emptyMessage?: string;
disabled?: boolean;
align?: 'start' | 'center' | 'end';
}
export function SelectPopover({
options,
value,
onValueChange,
placeholder = 'Select option',
searchPlaceholder = 'Search',
emptyMessage = 'No options found.',
disabled = false,
align = 'start',
}: SelectPopoverProps) {
const [open, setOpen] = useState(false);
const [search, setSearch] = useState('');
const selectedOption = options.find((option) => option.value === value);
const filteredOptions = useMemo(() => {
const term = search.trim().toLowerCase();
if (!term) return options;
return options.filter((option) =>
option.label.toLowerCase().includes(term),
);
}, [options, search]);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
disabled={disabled}
className="h-10 w-full justify-between px-3 font-normal shadow-none"
>
<span
className={cn(
'truncate',
!selectedOption && 'text-muted-foreground',
)}
>
{selectedOption?.label ?? placeholder}
</span>
<ChevronDown className="size-4 opacity-60" />
</Button>
</PopoverTrigger>
<PopoverContent align={align} className="w-72 p-0 shadow-none">
<div className="border-b p-3">
<Input
value={search}
onChange={(event) => setSearch(event.target.value)}
placeholder={searchPlaceholder}
/>
</div>
<div className="max-h-72 overflow-y-auto p-2">
{filteredOptions.length ? (
filteredOptions.map((option) => {
const selected = option.value === value;
return (
<button
key={option.value}
type="button"
disabled={option.disabled}
onClick={() => {
onValueChange(option.value);
setOpen(false);
}}
className={cn(
'flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-muted',
option.disabled && 'cursor-not-allowed opacity-60',
)}
>
<span className="flex size-4 shrink-0 items-center justify-center">
{selected ? <Check className="size-3" /> : null}
</span>
<span className="truncate">{option.label}</span>
</button>
);
})
) : (
<div className="px-2 py-6 text-center text-sm text-muted-foreground">
{emptyMessage}
</div>
)}
</div>
</PopoverContent>
</Popover>
);
}

View File

@@ -1,4 +1,6 @@
export { FormField } from './FormField'; export { FormField } from './FormField';
export { MultiSelectPopover } from './MultiSelectPopover'; export { MultiSelectPopover } from './MultiSelectPopover';
export type { MultiSelectOption } from './MultiSelectPopover'; export type { MultiSelectOption } from './MultiSelectPopover';
export { SelectPopover } from './SelectPopover';
export type { SelectPopoverOption } from './SelectPopover';
export { PasswordField } from './PasswordField'; export { PasswordField } from './PasswordField';

View File

@@ -0,0 +1,72 @@
'use client';
import { AsyncSelect, usePaginatedSelect } from '@/components/async-select';
import type { AsyncSelectOption } from '@/components/async-select';
import { packageService } from '@/services/api';
import type { Package } from '@/types';
import { packageKeys } from '@/app/(modules)/package/queries/packageKeys';
import type { PackageSelectProps } from './PackageSelect.types';
const PACKAGE_PAGE_SIZE = 20;
function mapPackageOption(pkg: Package): AsyncSelectOption {
return {
value: pkg.id,
label: pkg.name,
};
}
export function PackageSelect({
value,
onValueChange,
projectId,
enabled = true,
disabled = false,
portalContainer,
}: PackageSelectProps) {
const lookup = usePaginatedSelect<Package>({
enabled,
selectedValue: value,
pageSize: PACKAGE_PAGE_SIZE,
queryKey: (searchTerm) =>
[
...packageKeys.lists(),
'async-lookup',
projectId || 'all',
searchTerm,
PACKAGE_PAGE_SIZE,
] as const,
queryFn: async ({ searchTerm, skip, limit }) => {
const params = {
search_term: searchTerm || undefined,
skip,
limit,
};
const data = projectId
? await packageService.getPackagesByProject(projectId, params)
: await packageService.getPackages(params);
return { items: data.items, total: data.totalItems };
},
mapOption: mapPackageOption,
resolveSelected: (packageId) =>
packageId ? packageService.getPackageById(packageId) : Promise.resolve(null),
resolveSelectedQueryKey: (packageId) =>
packageId
? packageKeys.detail(packageId)
: [...packageKeys.details(), 'invalid', packageId],
});
return (
<AsyncSelect
lookup={lookup}
onValueChange={onValueChange}
disabled={disabled}
placeholder="Select package"
searchPlaceholder="Search packages..."
emptyMessage="No packages found."
portalContainer={portalContainer}
/>
);
}

View File

@@ -0,0 +1,10 @@
import type { RefObject } from 'react';
export interface PackageSelectProps {
value: string;
onValueChange: (value: string) => void;
projectId?: string;
enabled?: boolean;
disabled?: boolean;
portalContainer?: RefObject<HTMLDivElement | null>;
}

View File

@@ -0,0 +1,67 @@
'use client';
import { AsyncSelect, usePaginatedSelect } from '@/components/async-select';
import type { AsyncSelectOption } from '@/components/async-select';
import { projectService } from '@/services/api';
import type { Project } from '@/types';
import { projectKeys } from '@/app/(modules)/project/queries/projectKeys';
import type { ProjectSelectProps } from './ProjectSelect.types';
const PROJECT_PAGE_SIZE = 20;
function mapProjectOption(project: Project): AsyncSelectOption {
return {
value: project.id,
label: project.name,
};
}
export function ProjectSelect({
value,
onValueChange,
enabled = true,
disabled = false,
portalContainer,
}: ProjectSelectProps) {
const lookup = usePaginatedSelect<Project>({
enabled,
selectedValue: value,
pageSize: PROJECT_PAGE_SIZE,
queryKey: (searchTerm) =>
[
...projectKeys.lists(),
'async-lookup',
searchTerm,
PROJECT_PAGE_SIZE,
] as const,
queryFn: async ({ searchTerm, skip, limit }) => {
const data = await projectService.getProjects({
search_term: searchTerm || undefined,
skip,
limit,
});
return { items: data.items, total: data.totalItems };
},
mapOption: mapProjectOption,
resolveSelected: (projectId) =>
projectId ? projectService.getProjectById(projectId) : Promise.resolve(null),
resolveSelectedQueryKey: (projectId) =>
projectId
? projectKeys.detail(projectId)
: [...projectKeys.details(), 'invalid', projectId],
});
return (
<AsyncSelect
lookup={lookup}
onValueChange={onValueChange}
disabled={disabled}
placeholder="Select project"
searchPlaceholder="Search projects..."
emptyMessage="No projects found."
portalContainer={portalContainer}
/>
);
}

View File

@@ -0,0 +1,9 @@
import type { RefObject } from 'react';
export interface ProjectSelectProps {
value: string;
onValueChange: (value: string) => void;
enabled?: boolean;
disabled?: boolean;
portalContainer?: RefObject<HTMLDivElement | null>;
}

View File

@@ -0,0 +1,74 @@
'use client';
import { AsyncSelect, usePaginatedSelect } from '@/components/async-select';
import type { AsyncSelectOption } from '@/components/async-select';
import { chainageService } from '@/services/api';
import type { Chainage } from '@/types';
import { segmentKeys } from '@/app/(modules)/segment/queries/segmentKeys';
import type { SegmentSelectProps } from './SegmentSelect.types';
const SEGMENT_PAGE_SIZE = 20;
function mapSegmentOption(segment: Chainage): AsyncSelectOption {
return {
value: segment.id,
label: segment.segment_name,
};
}
export function SegmentSelect({
value,
onValueChange,
packageId,
enabled = true,
disabled = false,
portalContainer,
}: SegmentSelectProps) {
const lookup = usePaginatedSelect<Chainage>({
enabled,
selectedValue: value,
pageSize: SEGMENT_PAGE_SIZE,
queryKey: (searchTerm) =>
[
...segmentKeys.lists(),
'async-lookup',
packageId || 'all',
searchTerm,
SEGMENT_PAGE_SIZE,
] as const,
queryFn: async ({ searchTerm, skip, limit }) => {
const params = {
search_term: searchTerm || undefined,
skip,
limit,
};
const data = packageId
? await chainageService.getChainagesByPackage(packageId, params)
: await chainageService.getChainages(params);
return { items: data.items, total: data.totalItems };
},
mapOption: mapSegmentOption,
resolveSelected: (segmentId) =>
segmentId
? chainageService.getChainageById(segmentId)
: Promise.resolve(null),
resolveSelectedQueryKey: (segmentId) =>
segmentId
? segmentKeys.detail(segmentId)
: [...segmentKeys.details(), 'invalid', segmentId],
});
return (
<AsyncSelect
lookup={lookup}
onValueChange={onValueChange}
disabled={disabled}
placeholder="Select segment"
searchPlaceholder="Search segments..."
emptyMessage="No segments found."
portalContainer={portalContainer}
/>
);
}

View File

@@ -0,0 +1,10 @@
import type { RefObject } from 'react';
export interface SegmentSelectProps {
value: string;
onValueChange: (value: string) => void;
packageId?: string;
enabled?: boolean;
disabled?: boolean;
portalContainer?: RefObject<HTMLDivElement | null>;
}

View File

@@ -1,524 +0,0 @@
'use client';
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';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Loader2, Check, ArrowUp, ArrowDown } from 'lucide-react';
import {
projectService,
packageService,
chainageService,
} from '@/services/api';
import {
Project,
Package as PackageType,
Chainage,
SessionContext,
} from '@/types';
import { cn } from '@/lib/utils';
type ProjectSelectionSectionProps = {
onSelectionComplete?: (session: SessionContext) => void;
onSelectionChange?: (session: SessionContext | null) => void;
asStep?: boolean;
hideButton?: boolean;
};
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[]>(
globalProjectsCache || [],
);
const [packages, setPackages] = useState<PackageType[]>([]);
const [chainages, setChainages] = useState<Chainage[]>([]);
// Selection states
const [selectedProject, setSelectedProject] = useState<Project | null>(null);
const [selectedPackage, setSelectedPackage] = useState<PackageType | null>(
null,
);
const [selectedChainage, setSelectedChainage] = useState<Chainage | null>(
null,
);
// Loading states
const [loadingProjects, setLoadingProjects] = useState(!globalProjectsCache);
const [loadingPackages, setLoadingPackages] = useState(false);
const [loadingChainages, setLoadingChainages] = useState(false);
// Error state
const [error, setError] = useState<string | null>(null);
// 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);
const data = await projectsPromise;
if (isMounted) {
setProjects(data);
}
} catch (err) {
if (isMounted) {
setError('Failed to load projects. Please check connection.');
}
} finally {
if (isMounted) {
setLoadingProjects(false);
}
}
};
loadProjects();
return () => {
isMounted = false;
};
}, []);
// Load packages when project changes
useEffect(() => {
if (!selectedProject) {
setPackages([]);
setSelectedPackage(null);
return;
}
let isMounted = true;
const loadPackages = async () => {
try {
setLoadingPackages(true);
setError(null);
setSelectedPackage(null);
setSelectedChainage(null);
setChainages([]);
const data = await packageService.getPackagesByProject(
selectedProject.id,
);
if (isMounted) {
setPackages(data.items);
}
} catch (err) {
if (isMounted) {
console.error('Failed to load packages:', err);
setError('Failed to load packages for the selected project.');
}
} finally {
if (isMounted) {
setLoadingPackages(false);
}
}
};
loadPackages();
return () => {
isMounted = false;
};
}, [selectedProject]);
// Load chainages when package changes
useEffect(() => {
if (!selectedPackage) {
setChainages([]);
setSelectedChainage(null);
return;
}
let isMounted = true;
const loadChainages = async () => {
try {
setLoadingChainages(true);
setError(null);
setSelectedChainage(null);
const data = await chainageService.getChainagesByPackage(
selectedPackage.id,
);
if (isMounted) {
setChainages(data.items);
}
} catch (err) {
if (isMounted) {
console.error('Failed to load chainages:', err);
setError('Failed to load segments for the selected package.');
}
} finally {
if (isMounted) {
setLoadingChainages(false);
}
}
};
loadChainages();
return () => {
isMounted = false;
};
}, [selectedPackage]);
const handleProjectChange = (projectId: string) => {
const project = projects.find((p) => p.id === projectId) || null;
setSelectedProject(project);
};
const handlePackageChange = (packageId: string) => {
const pkg = packages.find((p) => p.id === packageId) || null;
setSelectedPackage(pkg);
};
const handleChainageChange = (chainageId: string) => {
const chainage = chainages.find((chn) => chn.id === chainageId) || null;
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 &&
onSelectionComplete
) {
onSelectionComplete({
projectId: selectedProject.id,
projectName: selectedProject.name,
packageId: selectedPackage.id,
packageName: selectedPackage.name,
chainageId: selectedChainage.id,
chainageName: selectedChainage.segment_name,
chainageDirection: selectedChainage.direction,
});
}
};
const isComplete = selectedProject && selectedPackage && selectedChainage;
// Step status helpers
const getStepStatus = (step: number) => {
if (step === 1) return selectedProject ? 'completed' : 'active';
if (step === 2)
return selectedPackage
? 'completed'
: selectedProject
? 'active'
: 'pending';
if (step === 3)
return selectedChainage
? 'completed'
: selectedPackage
? 'active'
: 'pending';
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">
Segment
</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 segment' : '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">
<div className="flex flex-col gap-6">
<div>
<CardTitle className="text-2xl font-bold">
Select Project Segment
</CardTitle>
<CardDescription className="mt-2 text-base">
Select Project, Package & Segment to begin intelligent road
analysis.
</CardDescription>
</div>
{/* Step Progress Indicator */}
<div className="flex items-center justify-center pt-2">
{[1, 2, 3].map((step, index) => {
const status = getStepStatus(step);
const labels = ['Project', 'Package', 'Segment'];
return (
<div key={step} className="flex items-center">
<div className="flex flex-col items-center">
<div
className={cn(
'w-10 h-10 rounded-full flex items-center justify-center text-sm font-semibold transition-all',
status === 'completed'
? 'bg-primary text-primary-foreground'
: status === 'active'
? 'bg-primary text-primary-foreground ring-4 ring-primary/10'
: 'bg-muted text-muted-foreground',
)}
>
{status === 'completed' ? (
<Check className="h-5 w-5" />
) : (
step
)}
</div>
<span
className={cn(
'text-xs mt-2 font-medium',
status === 'pending'
? 'text-muted-foreground/60'
: 'text-foreground',
)}
>
{labels[index]}
</span>
</div>
{index < 2 && (
<div
className={cn(
'w-16 h-0.5 mx-2 mb-6 rounded-full',
getStepStatus(step + 1) !== 'pending'
? 'bg-primary'
: 'bg-border',
)}
/>
)}
</div>
);
})}
</div>
</div>
</CardHeader>
<CardContent className="pt-0">{content}</CardContent>
</Card>
);
}

View File

@@ -51,9 +51,7 @@ export const API_ROUTES = {
OVERVIEW: 'biz/api/v1/dashboard/overview', OVERVIEW: 'biz/api/v1/dashboard/overview',
}, },
VIDEOS: { VIDEOS: {
LIST: '/videos',
UPLOAD: '/biz/api/v1/upload', UPLOAD: '/biz/api/v1/upload',
STATUS: (id: string) => `/status/${id}`,
RESULTS: (id: string) => `/biz/api/v1/results/${id}/completed`, RESULTS: (id: string) => `/biz/api/v1/results/${id}/completed`,
}, },
} as const; } as const;

View File

@@ -1,112 +0,0 @@
/**
* IndexedDB storage for video files
* Used to persist video files across page navigations
*/
const DB_NAME = 'visionroad_db';
const DB_VERSION = 1;
const VIDEO_STORE = 'videos';
let db: IDBDatabase | null = null;
/**
* Open the IndexedDB database
*/
async function openDB(): Promise<IDBDatabase> {
if (db) return db;
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onerror = () => reject(request.error);
request.onsuccess = () => {
db = request.result;
resolve(db);
};
request.onupgradeneeded = (event) => {
const database = (event.target as IDBOpenDBRequest).result;
if (!database.objectStoreNames.contains(VIDEO_STORE)) {
database.createObjectStore(VIDEO_STORE, { keyPath: 'id' });
}
};
});
}
/**
* Store a video file in IndexedDB
*/
export async function storeVideoFile(
videoId: string,
file: File,
): Promise<void> {
const database = await openDB();
return new Promise((resolve, reject) => {
const transaction = database.transaction([VIDEO_STORE], 'readwrite');
const store = transaction.objectStore(VIDEO_STORE);
const request = store.put({
id: videoId,
file: file,
timestamp: Date.now(),
});
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve();
});
}
/**
* Retrieve a video file from IndexedDB
*/
export async function getVideoFile(videoId: string): Promise<File | null> {
const database = await openDB();
return new Promise((resolve, reject) => {
const transaction = database.transaction([VIDEO_STORE], 'readonly');
const store = transaction.objectStore(VIDEO_STORE);
const request = store.get(videoId);
request.onerror = () => reject(request.error);
request.onsuccess = () => {
const result = request.result;
resolve(result ? result.file : null);
};
});
}
/**
* Clear a video file from IndexedDB
*/
export async function clearVideoFile(videoId: string): Promise<void> {
const database = await openDB();
return new Promise((resolve, reject) => {
const transaction = database.transaction([VIDEO_STORE], 'readwrite');
const store = transaction.objectStore(VIDEO_STORE);
const request = store.delete(videoId);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve();
});
}
/**
* Clear all video files from IndexedDB
*/
export async function clearAllVideos(): Promise<void> {
const database = await openDB();
return new Promise((resolve, reject) => {
const transaction = database.transaction([VIDEO_STORE], 'readwrite');
const store = transaction.objectStore(VIDEO_STORE);
const request = store.clear();
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve();
});
}

View File

@@ -16,14 +16,14 @@ export const chainageService = {
* Fetch all chainages * Fetch all chainages
*/ */
getChainages: async ( getChainages: async (
params?: PaginationParams, params?: PaginationParams & { search_term?: string },
): Promise<PaginatedResponse<Chainage>> => { ): Promise<PaginatedResponse<Chainage>> => {
const skip = params?.skip ?? 0; const skip = params?.skip ?? 0;
const limit = params?.limit ?? 100; const limit = params?.limit ?? 100;
const response = await axiosClient.get<PaginatedResponse<Chainage>>( const response = await axiosClient.get<PaginatedResponse<Chainage>>(
API_ROUTES.CHAINAGES.BASE, API_ROUTES.CHAINAGES.BASE,
{ {
params: { skip, limit }, params: { skip, limit, search_term: params?.search_term },
}, },
); );
return response.data; return response.data;
@@ -34,19 +34,34 @@ export const chainageService = {
*/ */
getChainagesByPackage: async ( getChainagesByPackage: async (
packageId: string, packageId: string,
params?: PaginationParams, params?: PaginationParams & { search_term?: string },
): Promise<PaginatedResponse<Chainage>> => { ): Promise<PaginatedResponse<Chainage>> => {
const skip = params?.skip ?? 0; const skip = params?.skip ?? 0;
const limit = params?.limit ?? 100; const limit = params?.limit ?? 100;
const response = await axiosClient.get<PaginatedResponse<Chainage>>( const response = await axiosClient.get<PaginatedResponse<Chainage>>(
API_ROUTES.CHAINAGES.BASE, API_ROUTES.CHAINAGES.BASE,
{ {
params: { package_id: packageId, skip, limit }, params: {
package_id: packageId,
skip,
limit,
search_term: params?.search_term,
},
}, },
); );
return response.data; return response.data;
}, },
/**
* Fetch a chainage by ID
*/
getChainageById: async (chainageId: string): Promise<Chainage> => {
const response = await axiosClient.get<Chainage>(
API_ROUTES.CHAINAGES.DETAIL(chainageId),
);
return response.data;
},
/** /**
* Create a new chainage * Create a new chainage
*/ */

View File

@@ -5,7 +5,6 @@ export * from './auth.service';
export { chainageService } from './chainage.service'; export { chainageService } from './chainage.service';
export * from './video.service'; export * from './video.service';
export * from './detection.service'; export * from './detection.service';
export * from './session.service';
export * from './permission.service'; export * from './permission.service';
export * from './role.service'; export * from './role.service';
export * from './user.service'; export * from './user.service';

View File

@@ -16,14 +16,14 @@ export const packageService = {
* Fetch all packages * Fetch all packages
*/ */
getPackages: async ( getPackages: async (
params?: PaginationParams, params?: PaginationParams & { search_term?: string },
): Promise<PaginatedResponse<Package>> => { ): Promise<PaginatedResponse<Package>> => {
const skip = params?.skip ?? 0; const skip = params?.skip ?? 0;
const limit = params?.limit ?? 100; const limit = params?.limit ?? 100;
const response = await axiosClient.get<PaginatedResponse<Package>>( const response = await axiosClient.get<PaginatedResponse<Package>>(
API_ROUTES.PACKAGES.BASE, API_ROUTES.PACKAGES.BASE,
{ {
params: { skip, limit }, params: { skip, limit, search_term: params?.search_term },
}, },
); );
return response.data; return response.data;
@@ -34,19 +34,34 @@ export const packageService = {
*/ */
getPackagesByProject: async ( getPackagesByProject: async (
projectId: string, projectId: string,
params?: PaginationParams, params?: PaginationParams & { search_term?: string },
): Promise<PaginatedResponse<Package>> => { ): Promise<PaginatedResponse<Package>> => {
const skip = params?.skip ?? 0; const skip = params?.skip ?? 0;
const limit = params?.limit ?? 100; const limit = params?.limit ?? 100;
const response = await axiosClient.get<PaginatedResponse<Package>>( const response = await axiosClient.get<PaginatedResponse<Package>>(
API_ROUTES.PACKAGES.BASE, API_ROUTES.PACKAGES.BASE,
{ {
params: { project_id: projectId, skip, limit }, params: {
project_id: projectId,
skip,
limit,
search_term: params?.search_term,
},
}, },
); );
return response.data; return response.data;
}, },
/**
* Fetch a package by ID
*/
getPackageById: async (packageId: string): Promise<Package> => {
const response = await axiosClient.get<Package>(
API_ROUTES.PACKAGES.DETAIL(packageId),
);
return response.data;
},
/** /**
* Create a new package * Create a new package
*/ */

View File

@@ -16,19 +16,29 @@ export const projectService = {
* Fetch all projects * Fetch all projects
*/ */
getProjects: async ( getProjects: async (
params?: PaginationParams, params?: PaginationParams & { search_term?: string },
): Promise<PaginatedResponse<Project>> => { ): Promise<PaginatedResponse<Project>> => {
const skip = params?.skip ?? 0; const skip = params?.skip ?? 0;
const limit = params?.limit ?? 100; const limit = params?.limit ?? 100;
const response = await axiosClient.get<PaginatedResponse<Project>>( const response = await axiosClient.get<PaginatedResponse<Project>>(
API_ROUTES.PROJECTS.BASE, API_ROUTES.PROJECTS.BASE,
{ {
params: { skip, limit }, params: { skip, limit, search_term: params?.search_term },
}, },
); );
return response.data; return response.data;
}, },
/**
* Fetch a project by ID
*/
getProjectById: async (projectId: string): Promise<Project> => {
const response = await axiosClient.get<Project>(
API_ROUTES.PROJECTS.DETAIL(projectId),
);
return response.data;
},
/** /**
* Create a new project * Create a new project
*/ */

View File

@@ -1,73 +0,0 @@
import { SessionContext, VideoResultData, emptySessionContext } from '@/types';
// Session Storage Keys
const SESSION_KEY = 'visionroad_session';
const VIDEO_DATA_KEY = 'visionroad_video_data';
const DETECTION_TYPE_KEY = 'visionroad_detection_type';
/**
* Session Service
*/
export const sessionService = {
/**
* Save session to localStorage
*/
saveSession: (session: SessionContext): void => {
if (typeof window !== 'undefined') {
localStorage.setItem(SESSION_KEY, JSON.stringify(session));
}
},
/**
* Load session from localStorage
*/
loadSession: (): SessionContext => {
if (typeof window !== 'undefined') {
const stored = localStorage.getItem(SESSION_KEY);
if (stored) {
return JSON.parse(stored);
}
}
return emptySessionContext;
},
/**
* Clear all session data
*/
clearSession: (): void => {
if (typeof window !== 'undefined') {
localStorage.removeItem(SESSION_KEY);
localStorage.removeItem(VIDEO_DATA_KEY);
localStorage.removeItem(DETECTION_TYPE_KEY);
}
},
/**
* Save video result data
*/
saveVideoData: (data: VideoResultData): void => {
if (typeof window !== 'undefined') {
localStorage.setItem(VIDEO_DATA_KEY, JSON.stringify(data));
}
},
/**
* Load video result data
*/
loadVideoData: (): VideoResultData | null => {
if (typeof window !== 'undefined') {
const stored = localStorage.getItem(VIDEO_DATA_KEY);
if (stored) {
return JSON.parse(stored);
}
}
return null;
},
/**
* Check if session is complete
*/
isSessionValid: (session: SessionContext): boolean => {
return !!(session.projectId && session.packageId && session.chainageId);
},
};

View File

@@ -1,55 +1,11 @@
import axiosClient from '../axios/axios'; import axiosClient from '../axios/axios';
import { API_ROUTES } from '@/constants/apiRoutes'; import { API_ROUTES } from '@/constants/apiRoutes';
import { CompletedVideoResult, Video, PaginationParams } from '@/types'; import { CompletedVideoResult } from '@/types';
/** /**
* Video Service * Video Service
*/ */
export const videoService = { export const videoService = {
/**
* Fetch all videos and transform them to match the Video interface
*/
getVideos: async (params?: PaginationParams): Promise<Video[]> => {
const skip = params?.skip ?? 0;
const limit = params?.limit ?? 100;
const response = await axiosClient.get<{
videos: Array<{
video_id: string;
status: string;
progress: number;
summary?: {
unique_defected_sign_board?: number;
unique_pothole?: number;
unique_road_crack?: number;
unique_damaged_road_marking?: number;
unique_good_sign_board?: number;
total_road_damage?: number;
total_detections?: number;
};
}>;
}>(API_ROUTES.VIDEOS.LIST, {
params: { skip, limit },
});
// Transform the response to match our Video interface
return response.data.videos.map((v) => ({
id: v.video_id,
filename: v.video_id,
detection_type: 'pot-sign-detection' as const,
status: v.status as Video['status'],
unique_defected_sign_board: v.summary?.unique_defected_sign_board,
unique_pothole: v.summary?.unique_pothole,
unique_road_crack: v.summary?.unique_road_crack,
unique_damaged_road_marking: v.summary?.unique_damaged_road_marking,
unique_good_sign_board: v.summary?.unique_good_sign_board,
total_road_damage: v.summary?.total_road_damage,
total_detections: v.summary?.total_detections,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
}));
},
/** /**
* Upload a video for processing * Upload a video for processing
*/ */
@@ -66,14 +22,6 @@ export const videoService = {
return response.data; return response.data;
}, },
/**
* Get processing status of a video
*/
getVideoStatus: async (videoId: string): Promise<any> => {
const response = await axiosClient.get(API_ROUTES.VIDEOS.STATUS(videoId));
return response.data;
},
/** /**
* Get analysis results for a video * Get analysis results for a video
*/ */

View File

@@ -2,7 +2,6 @@ export * from './common';
export * from './project'; export * from './project';
export * from './package'; export * from './package';
export * from './chainage'; export * from './chainage';
export * from './video';
export * from './detection'; export * from './detection';
export * from './analysis'; export * from './analysis';
export * from './session'; export * from './session';

View File

@@ -11,12 +11,3 @@ export interface SessionContext {
chainageDirection?: string | null; chainageDirection?: string | null;
} }
export const emptySessionContext: SessionContext = {
projectId: null,
projectName: null,
packageId: null,
packageName: null,
chainageId: null,
chainageName: null,
chainageDirection: null,
};

View File

@@ -1,27 +0,0 @@
/**
* Video related types
*/
export interface Video {
id: string;
filename: string;
detection_type:
| 'pothole-detection'
| 'sign-board-detection'
| 'pot-sign-detection';
status: 'pending' | 'processing' | 'completed' | 'failed';
unique_defected_sign_board?: number;
unique_pothole?: number;
unique_road_crack?: number;
unique_damaged_road_marking?: number;
unique_good_sign_board?: number;
unique_drain_issue?: number;
total_road_damage?: number;
total_detections?: number;
created_at: string;
updated_at: string;
}
export interface VideoResultData {
videoId: string;
detectionType?: string;
}

View File

@@ -15,5 +15,5 @@ export const ROUTES = {
ACCESS: '/access', ACCESS: '/access',
ACCOUNT: '/account', ACCOUNT: '/account',
UPLOAD: '/upload', UPLOAD: '/upload',
RESULTS: '/results', TICKET: '/ticket',
} as const; } as const;