refactor: modularize road management modules
This commit is contained in:
@@ -1,497 +1,120 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { 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 {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Loader2, CheckCircle2, Layers, MapPin, Building2, Route, X } from 'lucide-react';
|
||||
import { DataTable } from '@/components/data-table';
|
||||
import { useCallback, useState } from 'react';
|
||||
import { Layers, Plus } from 'lucide-react';
|
||||
|
||||
import { PageHeader } from '@/components/page-header';
|
||||
import { projectService } from '@/services/api';
|
||||
import { ProjectCreate, Project, ProjectUpdate } from '@/types';
|
||||
import { ColumnDef } from '@tanstack/react-table';
|
||||
import { toast } from 'sonner';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { PoweredBy } from '@/components/powered-by';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import type { Project } from '@/types';
|
||||
|
||||
import { ProjectDialog } from './components/ProjectDialog';
|
||||
import { ProjectTable } from './components/ProjectTable';
|
||||
import { useProjectColumns } from './components/ProjectColumns';
|
||||
import { useProjectFilters } from './hooks/useProjectFilters';
|
||||
import { useProjectForm } from './hooks/useProjectForm';
|
||||
import { useDeleteProjectMutation, useProjectsQuery } from './hooks/useProjectQueries';
|
||||
|
||||
export default function ProjectPage() {
|
||||
const [projects, setProjects] = useState<Project[]>([]);
|
||||
const [totalItems, setTotalItems] = useState(0);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isDialogOpen, setIsDialogOpen] = useState(false);
|
||||
const { skip, setSkip, limit, setLimit } = useProjectFilters();
|
||||
const projectsQuery = useProjectsQuery({ skip, limit });
|
||||
const deleteProjectMutation = useDeleteProjectMutation();
|
||||
const projectForm = useProjectForm({
|
||||
onSaved: () => setIsDialogOpen(false),
|
||||
});
|
||||
const {
|
||||
register,
|
||||
onSubmit,
|
||||
openCreate: prepareCreateProject,
|
||||
openEdit: prepareEditProject,
|
||||
resetForm,
|
||||
projectId,
|
||||
errors,
|
||||
touchedFields,
|
||||
canSubmit,
|
||||
isSaving,
|
||||
} = projectForm;
|
||||
|
||||
// Pagination state
|
||||
const [skip, setSkip] = useState(0);
|
||||
const [limit, setLimit] = useState(10);
|
||||
const openCreate = useCallback(() => {
|
||||
prepareCreateProject();
|
||||
setIsDialogOpen(true);
|
||||
}, [prepareCreateProject]);
|
||||
|
||||
// Editing state
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [currentProject, setCurrentProject] = useState<Project | null>(null);
|
||||
const openEdit = useCallback(
|
||||
(project: Project) => {
|
||||
prepareEditProject(project);
|
||||
setIsDialogOpen(true);
|
||||
},
|
||||
[prepareEditProject],
|
||||
);
|
||||
|
||||
// Form fields
|
||||
const [name, setName] = useState('');
|
||||
const [state, setState] = useState('');
|
||||
const [corridorName, setCorridorName] = useState('');
|
||||
const [startLat, setStartLat] = useState('');
|
||||
const [startLng, setStartLng] = useState('');
|
||||
const [endLat, setEndLat] = useState('');
|
||||
const [endLng, setEndLng] = useState('');
|
||||
|
||||
// Load projects
|
||||
const loadProjects = async (currentSkip = skip, currentLimit = limit) => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
const data = await projectService.getProjects({ skip: currentSkip, limit: currentLimit });
|
||||
setProjects(data.items);
|
||||
setTotalItems(data.totalItems);
|
||||
} catch (err) {
|
||||
setError('Failed to load projects. Please check if the backend is running.');
|
||||
} finally {
|
||||
// Add a small delay for animation stability
|
||||
setTimeout(() => {
|
||||
setIsLoading(false);
|
||||
}, 800);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
loadProjects(skip, limit);
|
||||
}, [skip, limit]);
|
||||
|
||||
const resetForm = () => {
|
||||
setName('');
|
||||
setState('');
|
||||
setCorridorName('');
|
||||
setStartLat('');
|
||||
setStartLng('');
|
||||
setEndLat('');
|
||||
setEndLng('');
|
||||
setError(null);
|
||||
setIsEditing(false);
|
||||
setCurrentProject(null);
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!name.trim()) {
|
||||
setError('Project name is required');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
if (isEditing && currentProject) {
|
||||
const data: ProjectUpdate = {
|
||||
name: name.trim(),
|
||||
state: state.trim() || null,
|
||||
corridor_name: corridorName.trim() || null,
|
||||
start_lat: startLat ? parseFloat(startLat) : null,
|
||||
start_lng: startLng ? parseFloat(startLng) : null,
|
||||
end_lat: endLat ? parseFloat(endLat) : null,
|
||||
end_lng: endLng ? parseFloat(endLng) : null,
|
||||
};
|
||||
await projectService.updateProject(currentProject.id, data);
|
||||
toast.success('Project Updated', {
|
||||
description: `${name} has been updated successfully at ${new Date().toLocaleTimeString()}`,
|
||||
});
|
||||
} else {
|
||||
const data: ProjectCreate = {
|
||||
name: name.trim(),
|
||||
state: state.trim() || null,
|
||||
corridor_name: corridorName.trim() || null,
|
||||
start_lat: startLat ? parseFloat(startLat) : null,
|
||||
start_lng: startLng ? parseFloat(startLng) : null,
|
||||
end_lat: endLat ? parseFloat(endLat) : null,
|
||||
end_lng: endLng ? parseFloat(endLng) : null,
|
||||
};
|
||||
await projectService.createProject(data);
|
||||
toast.success('Project Created', {
|
||||
description: `${name} has been established successfully at ${new Date().toLocaleTimeString()}`,
|
||||
});
|
||||
const handleDialogOpenChange = useCallback(
|
||||
(open: boolean) => {
|
||||
setIsDialogOpen(open);
|
||||
if (!open) {
|
||||
resetForm();
|
||||
}
|
||||
|
||||
// Refresh projects list
|
||||
await loadProjects();
|
||||
|
||||
// Close modal and reset form immediately
|
||||
setIsModalOpen(false);
|
||||
resetForm();
|
||||
} catch (err) {
|
||||
const message =
|
||||
err instanceof Error ? err.message : `Failed to ${isEditing ? 'update' : 'create'} project`;
|
||||
setError(message);
|
||||
toast.error('Operation Failed', {
|
||||
description: message,
|
||||
});
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEdit = (project: Project) => {
|
||||
setIsEditing(true);
|
||||
setCurrentProject(project);
|
||||
setName(project.name || '');
|
||||
setState(project.state || '');
|
||||
setCorridorName(project.corridor_name || '');
|
||||
setStartLat(project.start_lat?.toString() || '');
|
||||
setStartLng(project.start_lng?.toString() || '');
|
||||
setEndLat(project.end_lat?.toString() || '');
|
||||
setEndLng(project.end_lng?.toString() || '');
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
const handleDelete = async (project: Project) => {
|
||||
if (!confirm(`Are you sure you want to delete project "${project.name}"?`)) return;
|
||||
|
||||
try {
|
||||
setIsLoading(true);
|
||||
await projectService.deleteProject(project.id);
|
||||
toast.success('Project Deleted', {
|
||||
description: `${project.name} has been removed from the system.`,
|
||||
});
|
||||
await loadProjects();
|
||||
} catch (err) {
|
||||
setError('Failed to delete project');
|
||||
toast.error('Deletion Failed', {
|
||||
description:
|
||||
'The project could not be removed. Please try again or check your permissions.',
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const columns: ColumnDef<Project>[] = [
|
||||
{
|
||||
accessorKey: 'name',
|
||||
header: 'Project Name',
|
||||
cell: ({ row }) => <div className="font-semibold">{row.original.name}</div>,
|
||||
},
|
||||
{
|
||||
accessorKey: 'state',
|
||||
header: 'State',
|
||||
cell: ({ row }) => {
|
||||
const project = row.original;
|
||||
if (!project.state) return <span>—</span>;
|
||||
[resetForm],
|
||||
);
|
||||
|
||||
const states = project.state
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
if (states.length === 0) return <span>—</span>;
|
||||
|
||||
const firstState = states[0];
|
||||
const remainingStates = states.slice(1);
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Badge variant="secondary">{firstState}</Badge>
|
||||
|
||||
{remainingStates.length > 0 && (
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<button className="flex items-center justify-center rounded-full bg-muted/50 hover:bg-muted px-1.5 py-0.5 text-[10px] font-bold text-muted-foreground transition-colors border border-border/40">
|
||||
+{remainingStates.length}
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-2" align="start">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<p className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider mb-0.5 px-1">
|
||||
Other States
|
||||
</p>
|
||||
{remainingStates.map((item, idx) => (
|
||||
<Badge key={idx} variant="secondary">
|
||||
{item}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
const deleteProject = useCallback(
|
||||
(project: Project) => {
|
||||
if (!confirm(`Are you sure you want to delete project "${project.name}"?`)) {
|
||||
return;
|
||||
}
|
||||
deleteProjectMutation.mutate(project);
|
||||
},
|
||||
{
|
||||
accessorKey: 'corridor_name',
|
||||
header: 'Corridor',
|
||||
},
|
||||
];
|
||||
[deleteProjectMutation],
|
||||
);
|
||||
|
||||
const columns = useProjectColumns();
|
||||
const projects = projectsQuery.data?.items ?? [];
|
||||
const total = projectsQuery.data?.totalItems ?? 0;
|
||||
|
||||
return (
|
||||
<>
|
||||
<main className="relative z-10">
|
||||
{/* Refined Header */}
|
||||
<div className="mb-8">
|
||||
<PageHeader
|
||||
title="Project Management"
|
||||
description="Manage road infrastructure projects"
|
||||
icon={Layers}
|
||||
actions={
|
||||
<Button
|
||||
onClick={() => {
|
||||
setIsEditing(false);
|
||||
setIsModalOpen(true);
|
||||
}}
|
||||
>
|
||||
<Layers className="mr-2 h-5 w-5" />
|
||||
Add New Project
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<main className="relative z-10 space-y-5">
|
||||
<PageHeader
|
||||
title="Project Management"
|
||||
description="Manage road infrastructure projects"
|
||||
icon={Layers}
|
||||
actions={
|
||||
<Button onClick={openCreate} size="sm">
|
||||
<Plus />
|
||||
Add Project
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Data Table */}
|
||||
<div>
|
||||
<DataTable
|
||||
title="Projects"
|
||||
data={projects}
|
||||
columns={columns}
|
||||
onEdit={handleEdit}
|
||||
onDelete={handleDelete}
|
||||
isLoading={isLoading}
|
||||
pagination={{
|
||||
skip,
|
||||
limit,
|
||||
totalItems,
|
||||
onPageChange: setSkip,
|
||||
onLimitChange: (newLimit) => {
|
||||
setLimit(newLimit);
|
||||
setSkip(0); // Reset skip when limit changes
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<ProjectTable
|
||||
columns={columns}
|
||||
projects={projects}
|
||||
isLoading={projectsQuery.isLoading || deleteProjectMutation.isPending}
|
||||
skip={skip}
|
||||
limit={limit}
|
||||
total={total}
|
||||
onPageChange={setSkip}
|
||||
onLimitChange={setLimit}
|
||||
onEdit={openEdit}
|
||||
onDelete={deleteProject}
|
||||
/>
|
||||
|
||||
<PoweredBy />
|
||||
</main>
|
||||
|
||||
{/* Modal Dialog */}
|
||||
<Dialog
|
||||
open={isModalOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setIsModalOpen(false);
|
||||
resetForm();
|
||||
} else {
|
||||
setIsModalOpen(true);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogContent className="max-w-2xl" onOpenAutoFocus={(e) => e.preventDefault()}>
|
||||
<DialogHeader className="gap-2">
|
||||
<DialogTitle className="flex items-center gap-3 text-xl">
|
||||
<div className="p-2 rounded-lg bg-primary text-primary-foreground shadow-sm">
|
||||
<Layers className="h-5 w-5" />
|
||||
</div>
|
||||
{isEditing ? 'Edit Project Details' : 'Create New Project'}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-sm">
|
||||
{isEditing
|
||||
? 'Update the technical specifications for your road infrastructure project.'
|
||||
: 'Provide the essential road data to establish a new analysis project.'}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
{/* Project Name */}
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="name"
|
||||
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
|
||||
>
|
||||
Project Name <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="Enter a descriptive project name..."
|
||||
className="h-11 bg-muted/20 border-border/60"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* State & Corridor Row */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-5">
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="state"
|
||||
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
|
||||
>
|
||||
State{' '}
|
||||
<span className="text-[10px] lowercase font-normal opacity-70">(Optional)</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="state"
|
||||
value={state}
|
||||
onChange={(e) => setState(e.target.value)}
|
||||
placeholder="e.g. Maharashtra"
|
||||
className="h-11 bg-muted/20 border-border/60"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="corridor"
|
||||
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider flex items-center gap-2"
|
||||
>
|
||||
<Route className="h-3.5 w-3.5 opacity-60" />
|
||||
Corridor Name{' '}
|
||||
<span className="text-[10px] lowercase font-normal opacity-70">(Optional)</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="corridor"
|
||||
value={corridorName}
|
||||
onChange={(e) => setCorridorName(e.target.value)}
|
||||
placeholder="e.g. Mumbai-Goa Highway"
|
||||
className="h-11 bg-muted/20 border-border/60"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* GPS Coordinates Grid */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8 pt-2">
|
||||
{/* Start Point */}
|
||||
<div className="space-y-4">
|
||||
<p className="text-[11px] font-black text-muted-foreground tracking-widest flex items-center gap-2">
|
||||
<MapPin className="h-3.5 w-3.5 opacity-60" /> START POINT
|
||||
</p>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="start-lat"
|
||||
className="text-[10px] font-bold text-muted-foreground uppercase opacity-70"
|
||||
>
|
||||
Lat
|
||||
</Label>
|
||||
<Input
|
||||
id="start-lat"
|
||||
type="number"
|
||||
step="any"
|
||||
value={startLat}
|
||||
onChange={(e) => setStartLat(e.target.value)}
|
||||
placeholder="0.0000"
|
||||
className="h-10 bg-muted/10 border-border/40 text-xs font-mono"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="start-lng"
|
||||
className="text-[10px] font-bold text-muted-foreground uppercase opacity-70"
|
||||
>
|
||||
Lng
|
||||
</Label>
|
||||
<Input
|
||||
id="start-lng"
|
||||
type="number"
|
||||
step="any"
|
||||
value={startLng}
|
||||
onChange={(e) => setStartLng(e.target.value)}
|
||||
placeholder="0.0000"
|
||||
className="h-10 bg-muted/10 border-border/40 text-xs font-mono"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* End Point */}
|
||||
<div className="space-y-4">
|
||||
<p className="text-[11px] font-black text-muted-foreground tracking-widest flex items-center gap-2">
|
||||
<MapPin className="h-3.5 w-3.5 opacity-60" /> END POINT
|
||||
</p>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="end-lat"
|
||||
className="text-[10px] font-bold text-muted-foreground uppercase opacity-70"
|
||||
>
|
||||
Lat
|
||||
</Label>
|
||||
<Input
|
||||
id="end-lat"
|
||||
type="number"
|
||||
step="any"
|
||||
value={endLat}
|
||||
onChange={(e) => setEndLat(e.target.value)}
|
||||
placeholder="0.0000"
|
||||
className="h-10 bg-muted/10 border-border/40 text-xs font-mono"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="end-lng"
|
||||
className="text-[10px] font-bold text-muted-foreground uppercase opacity-70"
|
||||
>
|
||||
Lng
|
||||
</Label>
|
||||
<Input
|
||||
id="end-lng"
|
||||
type="number"
|
||||
step="any"
|
||||
value={endLng}
|
||||
onChange={(e) => setEndLng(e.target.value)}
|
||||
placeholder="0.0000"
|
||||
className="h-10 bg-muted/10 border-border/40 text-xs font-mono"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Submit Button */}
|
||||
<div className="flex gap-4 pt-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setIsModalOpen(false);
|
||||
resetForm();
|
||||
}}
|
||||
disabled={isSubmitting}
|
||||
className="flex-1 h-12 font-bold uppercase tracking-wider text-xs border-border/80 hover:bg-muted/50"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={isSubmitting || !name.trim()}
|
||||
className="flex-1 h-12 font-bold uppercase tracking-wider text-xs shadow-lg shadow-primary/20"
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
<span>{isEditing ? 'Updating...' : 'Creating...'}</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
{isEditing ? (
|
||||
<CheckCircle2 className="h-4 w-4" />
|
||||
) : (
|
||||
<Layers className="h-4 w-4" />
|
||||
)}
|
||||
<span>{isEditing ? 'Update Project' : 'Create Project'}</span>
|
||||
</div>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<ProjectDialog
|
||||
open={isDialogOpen}
|
||||
onOpenChange={handleDialogOpenChange}
|
||||
projectId={projectId}
|
||||
register={register}
|
||||
errors={errors}
|
||||
touchedFields={touchedFields}
|
||||
onSubmit={onSubmit}
|
||||
canSubmit={canSubmit}
|
||||
isSaving={isSaving}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user