544 lines
23 KiB
TypeScript
544 lines
23 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useMemo, useState } from "react";
|
|
import Link from "next/link";
|
|
import {
|
|
AlertCircle,
|
|
Calendar,
|
|
CalendarRange,
|
|
CheckCircle2,
|
|
ChevronLeft,
|
|
ChevronRight,
|
|
Filter,
|
|
GanttChartSquare,
|
|
Layers,
|
|
Search,
|
|
} from "lucide-react";
|
|
|
|
import { Badge } from "@/components/ui/badge";
|
|
import { Button } from "@/components/ui/button";
|
|
import { Card, CardContent } from "@/components/ui/card";
|
|
import { Checkbox } from "@/components/ui/checkbox";
|
|
import { Input } from "@/components/ui/input";
|
|
import {
|
|
Select,
|
|
SelectContent,
|
|
SelectItem,
|
|
SelectTrigger,
|
|
SelectValue,
|
|
} from "@/components/ui/select";
|
|
import { Skeleton } from "@/components/ui/skeleton";
|
|
import { getProjects } from "@/lib/projectsService";
|
|
import { Project, ProjectStatus } from "@/types/project";
|
|
|
|
const MONTH_WIDTH_PX = 72;
|
|
const ROW_HEIGHT_PX = 52;
|
|
|
|
type ProjectStatusFilter = "all" | ProjectStatus;
|
|
type ZoomLevel = "compact" | "normal" | "detailed";
|
|
|
|
const STATUS_LABELS: Record<ProjectStatus, string> = {
|
|
"0": "Borrador",
|
|
"1": "Abierto",
|
|
"2": "Cerrado",
|
|
};
|
|
|
|
const STATUS_BADGE_CLASS: Record<ProjectStatus, string> = {
|
|
"0": "bg-gray-100 text-gray-700 border-gray-200 dark:bg-gray-800 dark:text-gray-300 dark:border-gray-700",
|
|
"1": "bg-blue-100 text-blue-700 border-blue-200 dark:bg-blue-900/35 dark:text-blue-300 dark:border-blue-800",
|
|
"2": "bg-green-100 text-green-700 border-green-200 dark:bg-green-900/35 dark:text-green-300 dark:border-green-800",
|
|
};
|
|
|
|
const BAR_COLOR_BY_STATUS: Record<ProjectStatus, { base: string; fill: string }> = {
|
|
"0": { base: "bg-gray-200 dark:bg-gray-700", fill: "bg-gray-500 dark:bg-gray-400" },
|
|
"1": { base: "bg-blue-100 dark:bg-blue-950/50", fill: "bg-gradient-to-r from-blue-500 to-violet-600" },
|
|
"2": { base: "bg-green-100 dark:bg-green-950/50", fill: "bg-gradient-to-r from-emerald-500 to-green-600" },
|
|
};
|
|
|
|
interface TimelineMonth {
|
|
month: number;
|
|
year: number;
|
|
label: string;
|
|
}
|
|
|
|
interface PlannedProject {
|
|
project: Project;
|
|
start: Date;
|
|
end: Date;
|
|
startOffsetDays: number;
|
|
durationDays: number;
|
|
}
|
|
|
|
function getMonthsBetween(start: Date, end: Date): TimelineMonth[] {
|
|
const months: TimelineMonth[] = [];
|
|
const current = new Date(start.getFullYear(), start.getMonth(), 1);
|
|
const endMonth = new Date(end.getFullYear(), end.getMonth(), 1);
|
|
|
|
while (current <= endMonth) {
|
|
months.push({
|
|
month: current.getMonth(),
|
|
year: current.getFullYear(),
|
|
label: current.toLocaleDateString("es-ES", { month: "short", year: "numeric" }),
|
|
});
|
|
current.setMonth(current.getMonth() + 1);
|
|
}
|
|
|
|
return months;
|
|
}
|
|
|
|
function getDaysBetween(start: Date, end: Date): number {
|
|
const msPerDay = 1000 * 60 * 60 * 24;
|
|
const startMidnight = new Date(start.getFullYear(), start.getMonth(), start.getDate());
|
|
const endMidnight = new Date(end.getFullYear(), end.getMonth(), end.getDate());
|
|
return Math.floor((endMidnight.getTime() - startMidnight.getTime()) / msPerDay);
|
|
}
|
|
|
|
function clamp(value: number, min: number, max: number): number {
|
|
return Math.min(max, Math.max(min, value));
|
|
}
|
|
|
|
function parseProjectDates(project: Project): { start: Date; end: Date } | null {
|
|
const start = new Date(project.startDate);
|
|
const end = new Date(project.endDate);
|
|
if (isNaN(start.getTime()) || isNaN(end.getTime())) return null;
|
|
|
|
if (start <= end) return { start, end };
|
|
return { start: end, end: start };
|
|
}
|
|
|
|
function formatDate(date: Date): string {
|
|
return date.toLocaleDateString("es-ES", {
|
|
day: "2-digit",
|
|
month: "short",
|
|
year: "numeric",
|
|
});
|
|
}
|
|
|
|
export default function GanttPage() {
|
|
const [projects, setProjects] = useState<Project[]>([]);
|
|
const [loading, setLoading] = useState(true);
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
const [statusFilter, setStatusFilter] = useState<ProjectStatusFilter>("all");
|
|
const [search, setSearch] = useState("");
|
|
const [zoom, setZoom] = useState<ZoomLevel>("normal");
|
|
const [selectedIds, setSelectedIds] = useState<number[]>([]);
|
|
const [showSelectionPanel, setShowSelectionPanel] = useState(true);
|
|
|
|
useEffect(() => {
|
|
async function load() {
|
|
try {
|
|
setLoading(true);
|
|
const data = await getProjects();
|
|
const sorted = [...data].sort((a, b) => {
|
|
const da = parseProjectDates(a)?.start.getTime() ?? Number.MAX_SAFE_INTEGER;
|
|
const db = parseProjectDates(b)?.start.getTime() ?? Number.MAX_SAFE_INTEGER;
|
|
return da - db;
|
|
});
|
|
setProjects(sorted);
|
|
setSelectedIds(sorted.map((project) => project.id));
|
|
setError(null);
|
|
} catch (err) {
|
|
console.error("Error loading projects:", err);
|
|
setError("No se pudieron cargar los proyectos para el Gantt");
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}
|
|
|
|
load();
|
|
}, []);
|
|
|
|
const filteredProjects = useMemo(() => {
|
|
return projects.filter((project) => {
|
|
const statusOk = statusFilter === "all" || project.status === statusFilter;
|
|
const searchValue = search.trim().toLowerCase();
|
|
const searchOk =
|
|
searchValue.length === 0 ||
|
|
project.name.toLowerCase().includes(searchValue) ||
|
|
project.client.toLowerCase().includes(searchValue) ||
|
|
project.ref.toLowerCase().includes(searchValue);
|
|
|
|
return statusOk && searchOk;
|
|
});
|
|
}, [projects, search, statusFilter]);
|
|
|
|
useEffect(() => {
|
|
setSelectedIds((current) => {
|
|
const available = new Set(filteredProjects.map((project) => project.id));
|
|
const kept = current.filter((id) => available.has(id));
|
|
if (kept.length === current.length) return current;
|
|
return kept;
|
|
});
|
|
}, [filteredProjects]);
|
|
|
|
const visibleProjects = useMemo(() => {
|
|
const selected = new Set(selectedIds);
|
|
return filteredProjects.filter((project) => selected.has(project.id));
|
|
}, [filteredProjects, selectedIds]);
|
|
|
|
const { timelineStart, timelineEnd, months, totalDays } = useMemo(() => {
|
|
const projectsWithDates = visibleProjects
|
|
.map((project) => ({ project, parsed: parseProjectDates(project) }))
|
|
.filter((item): item is { project: Project; parsed: { start: Date; end: Date } } => item.parsed !== null);
|
|
|
|
if (projectsWithDates.length === 0) {
|
|
const now = new Date();
|
|
const start = new Date(now.getFullYear(), now.getMonth() - 2, 1);
|
|
const end = new Date(now.getFullYear(), now.getMonth() + 3, 0);
|
|
const monthList = getMonthsBetween(start, end);
|
|
return {
|
|
timelineStart: start,
|
|
timelineEnd: end,
|
|
months: monthList,
|
|
totalDays: Math.max(1, getDaysBetween(start, end) + 1),
|
|
};
|
|
}
|
|
|
|
const minStart = new Date(
|
|
Math.min(...projectsWithDates.map((item) => item.parsed.start.getTime()))
|
|
);
|
|
const maxEnd = new Date(
|
|
Math.max(...projectsWithDates.map((item) => item.parsed.end.getTime()))
|
|
);
|
|
|
|
const start = new Date(minStart.getFullYear(), minStart.getMonth(), 1);
|
|
const end = new Date(maxEnd.getFullYear(), maxEnd.getMonth() + 1, 0);
|
|
const monthList = getMonthsBetween(start, end);
|
|
|
|
return {
|
|
timelineStart: start,
|
|
timelineEnd: end,
|
|
months: monthList,
|
|
totalDays: Math.max(1, getDaysBetween(start, end) + 1),
|
|
};
|
|
}, [visibleProjects]);
|
|
|
|
const todayPercent = useMemo(() => {
|
|
const now = new Date();
|
|
if (now < timelineStart || now > timelineEnd) return null;
|
|
const offset = getDaysBetween(timelineStart, now);
|
|
return clamp((offset / totalDays) * 100, 0, 100);
|
|
}, [timelineEnd, timelineStart, totalDays]);
|
|
|
|
const plannedRows = useMemo<PlannedProject[]>(() => {
|
|
return visibleProjects
|
|
.map((project) => {
|
|
const parsed = parseProjectDates(project);
|
|
if (!parsed) return null;
|
|
|
|
const startOffsetDays = clamp(getDaysBetween(timelineStart, parsed.start), 0, totalDays - 1);
|
|
const durationDays = Math.max(1, getDaysBetween(parsed.start, parsed.end) + 1);
|
|
|
|
return {
|
|
project,
|
|
start: parsed.start,
|
|
end: parsed.end,
|
|
startOffsetDays,
|
|
durationDays,
|
|
};
|
|
})
|
|
.filter((item): item is PlannedProject => item !== null);
|
|
}, [timelineStart, totalDays, visibleProjects]);
|
|
|
|
const timelineWidth = months.length * MONTH_WIDTH_PX;
|
|
|
|
const stats = useMemo(() => {
|
|
const total = visibleProjects.length;
|
|
const open = visibleProjects.filter((project) => project.status === "1").length;
|
|
const closed = visibleProjects.filter((project) => project.status === "2").length;
|
|
const draft = visibleProjects.filter((project) => project.status === "0").length;
|
|
return { total, open, closed, draft };
|
|
}, [visibleProjects]);
|
|
|
|
const selectAll = () => setSelectedIds(filteredProjects.map((project) => project.id));
|
|
const clearSelection = () => setSelectedIds([]);
|
|
|
|
const toggleProjectSelection = (projectId: number, checked: boolean) => {
|
|
setSelectedIds((current) => {
|
|
if (checked && current.includes(projectId)) return current;
|
|
if (!checked && !current.includes(projectId)) return current;
|
|
return checked ? [...current, projectId] : current.filter((id) => id !== projectId);
|
|
});
|
|
};
|
|
|
|
if (error) {
|
|
return (
|
|
<div className="min-h-screen bg-background flex items-center justify-center px-4">
|
|
<div className="text-center max-w-md">
|
|
<AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-3" />
|
|
<h2 className="text-lg font-semibold text-foreground">Error cargando el Gantt</h2>
|
|
<p className="text-sm text-muted-foreground mt-1">{error}</p>
|
|
<Button onClick={() => window.location.reload()} className="mt-4">Reintentar</Button>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<div className="min-h-screen bg-background">
|
|
<section className="border-b bg-gradient-to-r from-blue-50/70 via-background to-violet-50/70 dark:from-blue-950/25 dark:via-background dark:to-violet-950/25">
|
|
<div className="px-4 sm:px-6 lg:px-8 py-5 space-y-4">
|
|
<div className="flex items-start justify-between gap-4 flex-wrap">
|
|
<div className="flex items-center gap-3">
|
|
<div className="p-2 rounded-lg bg-gradient-to-r from-blue-500 to-violet-600 shadow-sm">
|
|
<GanttChartSquare className="w-5 h-5 text-white" />
|
|
</div>
|
|
<div>
|
|
<h1 className="text-2xl font-bold text-foreground">Roadmap de Proyectos</h1>
|
|
<p className="text-sm text-muted-foreground">Vista global rediseñada para planificación ejecutiva</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex items-center gap-2 flex-wrap">
|
|
<Button
|
|
variant={showSelectionPanel ? "default" : "outline"}
|
|
onClick={() => setShowSelectionPanel((current) => !current)}
|
|
className="gap-2"
|
|
>
|
|
<Layers className="w-4 h-4" />
|
|
{showSelectionPanel ? "Ocultar selección" : "Mostrar selección"}
|
|
</Button>
|
|
|
|
<div className="relative">
|
|
<Search className="w-4 h-4 text-muted-foreground absolute left-2.5 top-2.5" />
|
|
<Input
|
|
value={search}
|
|
onChange={(event) => setSearch(event.target.value)}
|
|
placeholder="Buscar proyecto..."
|
|
className="pl-8 w-56"
|
|
/>
|
|
</div>
|
|
|
|
<Select value={statusFilter} onValueChange={(value: ProjectStatusFilter) => setStatusFilter(value)}>
|
|
<SelectTrigger className="w-40">
|
|
<Filter className="w-4 h-4 mr-2" />
|
|
<SelectValue placeholder="Estado" />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
<SelectItem value="all">Todos</SelectItem>
|
|
<SelectItem value="0">Borrador</SelectItem>
|
|
<SelectItem value="1">Abierto</SelectItem>
|
|
<SelectItem value="2">Cerrado</SelectItem>
|
|
</SelectContent>
|
|
</Select>
|
|
|
|
<Select value={zoom} onValueChange={(value: ZoomLevel) => setZoom(value)}>
|
|
<SelectTrigger className="w-36">
|
|
<CalendarRange className="w-4 h-4 mr-2" />
|
|
<SelectValue placeholder="Zoom" />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
<SelectItem value="compact">Compacto</SelectItem>
|
|
<SelectItem value="normal">Normal</SelectItem>
|
|
<SelectItem value="detailed">Detallado</SelectItem>
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex items-center gap-2 flex-wrap">
|
|
<Badge variant="outline" className="bg-background/80">{stats.total} visibles</Badge>
|
|
<Badge variant="outline" className="bg-background/80">{stats.open} abiertos</Badge>
|
|
<Badge variant="outline" className="bg-background/80">{stats.closed} cerrados</Badge>
|
|
<Badge variant="outline" className="bg-background/80">{stats.draft} borradores</Badge>
|
|
</div>
|
|
</div>
|
|
</section>
|
|
|
|
<main className="px-4 sm:px-6 lg:px-8 py-6">
|
|
{loading ? (
|
|
<GanttSkeleton />
|
|
) : (
|
|
<div className={`grid grid-cols-1 gap-4 ${showSelectionPanel ? "xl:grid-cols-[320px_1fr]" : "xl:grid-cols-1"}`}>
|
|
{showSelectionPanel && (
|
|
<Card className="border shadow-sm">
|
|
<CardContent className="p-4 space-y-3">
|
|
<div className="flex items-center justify-between">
|
|
<h2 className="text-sm font-semibold text-foreground flex items-center gap-2">
|
|
<Layers className="w-4 h-4" />
|
|
Selección de proyectos
|
|
</h2>
|
|
<span className="text-xs text-muted-foreground">{selectedIds.length}/{filteredProjects.length}</span>
|
|
</div>
|
|
|
|
<div className="flex items-center gap-2">
|
|
<Button variant="outline" size="sm" onClick={selectAll}>Seleccionar todos</Button>
|
|
<Button variant="ghost" size="sm" onClick={clearSelection}>Limpiar</Button>
|
|
</div>
|
|
|
|
<div className="max-h-[60vh] overflow-auto border rounded-md">
|
|
{filteredProjects.length === 0 ? (
|
|
<div className="p-4 text-sm text-muted-foreground">No hay proyectos con este filtro.</div>
|
|
) : (
|
|
filteredProjects.map((project) => {
|
|
const checked = selectedIds.includes(project.id);
|
|
return (
|
|
<label
|
|
key={project.id}
|
|
className="flex items-start gap-2.5 p-2.5 border-b last:border-b-0 hover:bg-muted/50 cursor-pointer"
|
|
>
|
|
<Checkbox
|
|
checked={checked}
|
|
onCheckedChange={(value) => toggleProjectSelection(project.id, Boolean(value))}
|
|
className="mt-0.5"
|
|
/>
|
|
<div className="min-w-0 flex-1">
|
|
<p className="text-sm font-medium text-foreground truncate">{project.name}</p>
|
|
<div className="mt-1 flex items-center gap-2">
|
|
<Badge variant="outline" className={`text-[10px] px-1.5 py-0 h-5 ${STATUS_BADGE_CLASS[project.status]}`}>
|
|
{STATUS_LABELS[project.status]}
|
|
</Badge>
|
|
<span className="text-[11px] text-muted-foreground truncate">{project.client}</span>
|
|
</div>
|
|
</div>
|
|
</label>
|
|
);
|
|
})
|
|
)}
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
)}
|
|
|
|
<Card className="border shadow-sm overflow-hidden">
|
|
<CardContent className="p-0">
|
|
{plannedRows.length === 0 ? (
|
|
<div className="py-14 px-6 text-center">
|
|
<Calendar className="w-10 h-10 text-muted-foreground/60 mx-auto mb-3" />
|
|
<p className="font-medium text-foreground">No hay proyectos seleccionados para mostrar</p>
|
|
<p className="text-sm text-muted-foreground mt-1">
|
|
Selecciona proyectos en el panel izquierdo para ver el cronograma.
|
|
</p>
|
|
</div>
|
|
) : (
|
|
<div className="overflow-auto">
|
|
<div style={{ width: `${Math.max(980, timelineWidth + 320)}px` }}>
|
|
<div className="grid grid-cols-[320px_1fr] border-b sticky top-0 z-10 bg-card/95 backdrop-blur">
|
|
<div className="h-12 flex items-center px-4 text-xs font-semibold text-muted-foreground border-r sticky left-0 z-20 bg-card/95">
|
|
Proyecto
|
|
</div>
|
|
<div className="h-12 flex">
|
|
{months.map((month) => (
|
|
<div
|
|
key={`${month.year}-${month.month}`}
|
|
className="border-r flex items-center justify-center"
|
|
style={{ width: `${MONTH_WIDTH_PX}px` }}
|
|
>
|
|
<span className="text-[11px] font-medium text-muted-foreground uppercase">{month.label}</span>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</div>
|
|
|
|
{plannedRows.map((row) => {
|
|
const barStyle = BAR_COLOR_BY_STATUS[row.project.status];
|
|
const leftPercent = (row.startOffsetDays / totalDays) * 100;
|
|
const widthPercent = (row.durationDays / totalDays) * 100;
|
|
const isCompleted = row.project.progress >= 100;
|
|
|
|
return (
|
|
<div key={row.project.id} className="grid grid-cols-[320px_1fr] border-b" style={{ minHeight: `${ROW_HEIGHT_PX}px` }}>
|
|
<Link
|
|
href={`/proyectos/${row.project.id}`}
|
|
className="px-4 py-2.5 border-r hover:bg-muted/50 transition-colors flex items-center sticky left-0 z-10 bg-background"
|
|
>
|
|
<div className="min-w-0">
|
|
<p className="text-sm font-medium text-foreground truncate">{row.project.name}</p>
|
|
<div className="mt-1 flex items-center gap-2">
|
|
<Badge variant="outline" className={`text-[10px] px-1.5 py-0 h-5 ${STATUS_BADGE_CLASS[row.project.status]}`}>
|
|
{STATUS_LABELS[row.project.status]}
|
|
</Badge>
|
|
<span className="text-[11px] text-muted-foreground">{row.project.progress}%</span>
|
|
{isCompleted && <CheckCircle2 className="w-3.5 h-3.5 text-green-500" />}
|
|
</div>
|
|
</div>
|
|
</Link>
|
|
|
|
<div className="relative">
|
|
<div className="absolute inset-0 flex pointer-events-none">
|
|
{months.map((month) => (
|
|
<div key={`grid-${row.project.id}-${month.year}-${month.month}`} className="border-r" style={{ width: `${MONTH_WIDTH_PX}px` }} />
|
|
))}
|
|
</div>
|
|
|
|
{todayPercent !== null && (
|
|
<div
|
|
className="absolute top-0 bottom-0 w-px bg-red-400/70 z-[1]"
|
|
style={{ left: `${todayPercent}%` }}
|
|
/>
|
|
)}
|
|
|
|
<Link
|
|
href={`/proyectos/${row.project.id}`}
|
|
className="absolute top-1/2 -translate-y-1/2 h-8 rounded-md transition-all hover:scale-[1.01] hover:shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
|
|
style={{
|
|
left: `${leftPercent}%`,
|
|
width: `${Math.max(widthPercent, 1.2)}%`,
|
|
minWidth: zoom === "compact" ? "18px" : zoom === "normal" ? "22px" : "26px",
|
|
}}
|
|
>
|
|
<div className={`absolute inset-0 rounded-md ${barStyle.base}`} />
|
|
<div
|
|
className={`absolute inset-y-0 left-0 rounded-md ${barStyle.fill}`}
|
|
style={{ width: `${clamp(row.project.progress, 0, 100)}%` }}
|
|
/>
|
|
<div className="relative h-full px-2 flex items-center justify-between z-10">
|
|
{zoom !== "compact" && (
|
|
<span className="text-[11px] font-semibold text-white drop-shadow truncate">
|
|
{zoom === "detailed" ? `${row.project.progress}%` : row.project.progress >= 35 ? `${row.project.progress}%` : ""}
|
|
</span>
|
|
)}
|
|
{zoom === "detailed" && (
|
|
<span className="text-[10px] text-white/95 hidden md:inline-flex items-center gap-1">
|
|
<ChevronLeft className="w-3 h-3 rotate-180" />
|
|
{formatDate(row.start)}
|
|
<ChevronRight className="w-3 h-3" />
|
|
{formatDate(row.end)}
|
|
</span>
|
|
)}
|
|
</div>
|
|
</Link>
|
|
</div>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
</div>
|
|
)}
|
|
</CardContent>
|
|
</Card>
|
|
</div>
|
|
)}
|
|
</main>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function GanttSkeleton() {
|
|
return (
|
|
<div className="grid grid-cols-1 xl:grid-cols-[320px_1fr] gap-4">
|
|
<Card className="border">
|
|
<CardContent className="p-4 space-y-3">
|
|
<Skeleton className="h-5 w-40" />
|
|
<div className="space-y-2">
|
|
{Array.from({ length: 7 }).map((_, index) => (
|
|
<Skeleton key={index} className="h-14 w-full" />
|
|
))}
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
<Card className="border">
|
|
<CardContent className="p-0">
|
|
<div className="space-y-0">
|
|
<Skeleton className="h-12 w-full rounded-none" />
|
|
{Array.from({ length: 8 }).map((_, index) => (
|
|
<Skeleton key={index} className="h-[52px] w-full rounded-none border-t" />
|
|
))}
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
</div>
|
|
);
|
|
}
|