feat: Implement time range filtering in the Gantt chart and refine the tooltip formatter in the statistics page.

This commit is contained in:
marcos 2026-01-30 23:41:25 +01:00
parent 8994c240eb
commit 819378fb29
2 changed files with 226 additions and 150 deletions

View File

@ -7,8 +7,8 @@ import {
ChevronLeft, ChevronLeft,
ChevronRight, ChevronRight,
Calendar, Calendar,
ZoomIn, History,
ZoomOut, Clock,
Filter, Filter,
} from "lucide-react"; } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
@ -52,6 +52,7 @@ const STATUS_LABELS: Record<ProjectStatus, string> = {
}; };
type ViewMode = "month" | "quarter" | "year"; type ViewMode = "month" | "quarter" | "year";
type TimeRange = "future" | "past" | "all";
function getProjectColor(index: number) { function getProjectColor(index: number) {
return PROJECT_COLORS[index % PROJECT_COLORS.length]; return PROJECT_COLORS[index % PROJECT_COLORS.length];
@ -97,6 +98,7 @@ export default function GanttPage() {
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [viewMode, setViewMode] = useState<ViewMode>("month"); const [viewMode, setViewMode] = useState<ViewMode>("month");
const [statusFilter, setStatusFilter] = useState<string>("all"); const [statusFilter, setStatusFilter] = useState<string>("all");
const [timeRange, setTimeRange] = useState<TimeRange>("future");
const [viewOffset, setViewOffset] = useState(0); const [viewOffset, setViewOffset] = useState(0);
useEffect(() => { useEffect(() => {
@ -118,42 +120,110 @@ export default function GanttPage() {
// Filtrar proyectos // Filtrar proyectos
const filteredProjects = useMemo(() => { const filteredProjects = useMemo(() => {
if (statusFilter === "all") return projects; let filtered = projects;
return projects.filter(p => p.status === statusFilter);
}, [projects, statusFilter]);
// Calcular rango de fechas del timeline // Filtrar por estado
const { timelineStart, timelineEnd, months } = useMemo(() => { if (statusFilter !== "all") {
if (filteredProjects.length === 0) { filtered = filtered.filter(p => p.status === statusFilter);
}
// Filtrar por rango temporal
const now = new Date(); const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
if (timeRange === "future") {
// Proyectos que terminan hoy o en el futuro
filtered = filtered.filter(p => new Date(p.endDate) >= today);
} else if (timeRange === "past") {
// Proyectos que ya terminaron
filtered = filtered.filter(p => new Date(p.endDate) < today);
}
// "all" no filtra
return filtered;
}, [projects, statusFilter, timeRange]);
// Calcular rango de fechas del timeline basado en los proyectos
// - Futuro: desde el mes actual hasta el fin del proyecto más tardío
// - Pasado: desde el inicio del proyecto más antiguo hasta el mes actual
// - Todo: desde el inicio del proyecto más antiguo hasta el fin del más tardío
const { timelineStart, timelineEnd, months } = useMemo(() => {
const now = new Date();
const currentMonthStart = new Date(now.getFullYear(), now.getMonth(), 1);
const currentMonthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0);
// Si no hay proyectos, mostrar 12 meses desde el actual
if (filteredProjects.length === 0) {
const start = new Date(now.getFullYear(), now.getMonth() - 6, 1);
const end = new Date(now.getFullYear(), now.getMonth() + 6, 0);
return { return {
timelineStart: new Date(now.getFullYear(), now.getMonth(), 1), timelineStart: start,
timelineEnd: new Date(now.getFullYear(), now.getMonth() + 6, 0), timelineEnd: end,
months: [], months: getMonthsBetween(start, end),
}; };
} }
const allDates = filteredProjects.flatMap(p => [new Date(p.startDate), new Date(p.endDate)]); // Calcular fechas extremas de los proyectos
const minDate = new Date(Math.min(...allDates.map(d => d.getTime()))); const allStartDates = filteredProjects.map(p => new Date(p.startDate));
const maxDate = new Date(Math.max(...allDates.map(d => d.getTime()))); const allEndDates = filteredProjects.map(p => new Date(p.endDate));
const minProjectStart = new Date(Math.min(...allStartDates.map(d => d.getTime())));
const maxProjectEnd = new Date(Math.max(...allEndDates.map(d => d.getTime())));
// Añadir margen de un mes antes y después if (timeRange === "future") {
const start = new Date(minDate.getFullYear(), minDate.getMonth() - 1, 1); // Desde el mes actual hasta el fin del proyecto más tardío
const end = new Date(maxDate.getFullYear(), maxDate.getMonth() + 2, 0); const start = currentMonthStart;
const end = new Date(maxProjectEnd.getFullYear(), maxProjectEnd.getMonth() + 1, 0);
return { return {
timelineStart: start, timelineStart: start,
timelineEnd: end, timelineEnd: end,
months: getMonthsBetween(start, end), months: getMonthsBetween(start, end),
}; };
}, [filteredProjects]); } else if (timeRange === "past") {
// Desde el inicio del proyecto más antiguo hasta el mes actual
const start = new Date(minProjectStart.getFullYear(), minProjectStart.getMonth(), 1);
const end = currentMonthEnd;
return {
timelineStart: start,
timelineEnd: end,
months: getMonthsBetween(start, end),
};
} else {
// "all" - Desde el inicio del proyecto más antiguo hasta el fin del más tardío
const start = new Date(minProjectStart.getFullYear(), minProjectStart.getMonth(), 1);
const end = new Date(maxProjectEnd.getFullYear(), maxProjectEnd.getMonth() + 1, 0);
return {
timelineStart: start,
timelineEnd: end,
months: getMonthsBetween(start, end),
};
}
}, [filteredProjects, timeRange]);
// Calcular meses visibles según el modo de vista // Calcular meses visibles según el modo de vista
// En modo "todo", mostrar TODOS los meses (scroll horizontal en el timeline)
// En modo "pasado", empezamos desde los meses más recientes
const visibleMonths = useMemo(() => { const visibleMonths = useMemo(() => {
// En modo "todo", mostrar todos los meses
if (timeRange === "all") {
return months;
}
const monthsToShow = viewMode === "month" ? 3 : viewMode === "quarter" ? 6 : 12; const monthsToShow = viewMode === "month" ? 3 : viewMode === "quarter" ? 6 : 12;
if (timeRange === "past") {
// En pasado, viewOffset 0 = meses más recientes (final del array)
const maxOffset = Math.max(0, months.length - monthsToShow);
const startIdx = Math.max(0, maxOffset - viewOffset);
return months.slice(startIdx, startIdx + monthsToShow);
} else {
// En futuro, viewOffset 0 = primeros meses
const startIdx = Math.max(0, Math.min(viewOffset, months.length - monthsToShow)); const startIdx = Math.max(0, Math.min(viewOffset, months.length - monthsToShow));
return months.slice(startIdx, startIdx + monthsToShow); return months.slice(startIdx, startIdx + monthsToShow);
}, [months, viewMode, viewOffset]); }
}, [months, viewMode, viewOffset, timeRange]);
// Calcular el ancho total en días para los meses visibles // Calcular el ancho total en días para los meses visibles
const { totalDays, visibleStart, visibleEnd } = useMemo(() => { const { totalDays, visibleStart, visibleEnd } = useMemo(() => {
@ -174,8 +244,10 @@ export default function GanttPage() {
}, [visibleMonths]); }, [visibleMonths]);
// Navegación // Navegación
const monthsToShow = viewMode === "month" ? 3 : viewMode === "quarter" ? 6 : 12;
const maxOffset = Math.max(0, months.length - monthsToShow);
const canGoBack = viewOffset > 0; const canGoBack = viewOffset > 0;
const canGoForward = viewOffset + (viewMode === "month" ? 3 : viewMode === "quarter" ? 6 : 12) < months.length; const canGoForward = viewOffset < maxOffset;
const goBack = () => { const goBack = () => {
const step = viewMode === "month" ? 1 : viewMode === "quarter" ? 3 : 6; const step = viewMode === "month" ? 1 : viewMode === "quarter" ? 3 : 6;
@ -184,16 +256,11 @@ export default function GanttPage() {
const goForward = () => { const goForward = () => {
const step = viewMode === "month" ? 1 : viewMode === "quarter" ? 3 : 6; const step = viewMode === "month" ? 1 : viewMode === "quarter" ? 3 : 6;
const maxOffset = Math.max(0, months.length - (viewMode === "month" ? 3 : viewMode === "quarter" ? 6 : 12));
setViewOffset(Math.min(maxOffset, viewOffset + step)); setViewOffset(Math.min(maxOffset, viewOffset + step));
}; };
const goToToday = () => { const goToToday = () => {
const now = new Date(); setViewOffset(0); // Volver al mes actual
const todayIndex = months.findIndex(m => m.month === now.getMonth() && m.year === now.getFullYear());
if (todayIndex >= 0) {
setViewOffset(Math.max(0, todayIndex - 1));
}
}; };
if (error) { if (error) {
@ -214,11 +281,11 @@ export default function GanttPage() {
} }
return ( return (
<div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100"> <div className="h-screen flex flex-col bg-gradient-to-br from-gray-50 to-gray-100">
{/* Header */} {/* Header - siempre visible */}
<header className="bg-white border-b border-gray-200 sticky top-0 z-10"> <header className="bg-white border-b border-gray-200 flex-shrink-0 z-10">
<div className="max-w-full mx-auto px-4 sm:px-6 lg:px-8 py-4"> <div className="px-4 sm:px-6 lg:px-8 py-4">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between flex-wrap gap-4">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<div className="p-2 bg-gradient-to-r from-blue-500 to-purple-600 rounded-lg"> <div className="p-2 bg-gradient-to-r from-blue-500 to-purple-600 rounded-lg">
<GanttIcon className="w-6 h-6 text-white" /> <GanttIcon className="w-6 h-6 text-white" />
@ -232,7 +299,7 @@ export default function GanttPage() {
</div> </div>
{/* Controles */} {/* Controles */}
<div className="flex items-center gap-3"> <div className="flex items-center gap-3 flex-wrap">
{/* Filtro de estado */} {/* Filtro de estado */}
<Select value={statusFilter} onValueChange={setStatusFilter}> <Select value={statusFilter} onValueChange={setStatusFilter}>
<SelectTrigger className="w-40"> <SelectTrigger className="w-40">
@ -247,6 +314,34 @@ export default function GanttPage() {
</SelectContent> </SelectContent>
</Select> </Select>
{/* Selector de rango temporal */}
<div className="flex items-center gap-1 border rounded-lg p-1">
<Button
variant={timeRange === "past" ? "default" : "ghost"}
size="sm"
onClick={() => { setTimeRange("past"); setViewOffset(0); }}
>
<History className="w-4 h-4 mr-1" />
Pasado
</Button>
<Button
variant={timeRange === "future" ? "default" : "ghost"}
size="sm"
onClick={() => { setTimeRange("future"); setViewOffset(0); }}
>
<Clock className="w-4 h-4 mr-1" />
Futuro
</Button>
<Button
variant={timeRange === "all" ? "default" : "ghost"}
size="sm"
onClick={() => { setTimeRange("all"); setViewOffset(0); }}
>
<Calendar className="w-4 h-4 mr-1" />
Todo
</Button>
</div>
{/* Selector de vista */} {/* Selector de vista */}
<Select value={viewMode} onValueChange={(v: ViewMode) => setViewMode(v)}> <Select value={viewMode} onValueChange={(v: ViewMode) => setViewMode(v)}>
<SelectTrigger className="w-32"> <SelectTrigger className="w-32">
@ -264,9 +359,9 @@ export default function GanttPage() {
<Button variant="outline" size="icon" onClick={goBack} disabled={!canGoBack}> <Button variant="outline" size="icon" onClick={goBack} disabled={!canGoBack}>
<ChevronLeft className="w-4 h-4" /> <ChevronLeft className="w-4 h-4" />
</Button> </Button>
<Button variant="outline" size="sm" onClick={goToToday}> <Button variant="outline" size="sm" onClick={goToToday} disabled={viewOffset === 0}>
<Calendar className="w-4 h-4 mr-1" /> <Calendar className="w-4 h-4 mr-1" />
Hoy Inicio
</Button> </Button>
<Button variant="outline" size="icon" onClick={goForward} disabled={!canGoForward}> <Button variant="outline" size="icon" onClick={goForward} disabled={!canGoForward}>
<ChevronRight className="w-4 h-4" /> <ChevronRight className="w-4 h-4" />
@ -277,8 +372,8 @@ export default function GanttPage() {
</div> </div>
</header> </header>
{/* Content */} {/* Content - área scrollable */}
<main className="max-w-full mx-auto px-4 sm:px-6 lg:px-8 py-6"> <main className="flex-1 overflow-auto px-4 sm:px-6 lg:px-8 py-6">
{loading ? ( {loading ? (
<GanttSkeleton /> <GanttSkeleton />
) : filteredProjects.length === 0 ? ( ) : filteredProjects.length === 0 ? (
@ -290,10 +385,10 @@ export default function GanttPage() {
</CardContent> </CardContent>
</Card> </Card>
) : ( ) : (
<Card className="border-gray-200 overflow-hidden"> <Card className="border-gray-200 w-full">
<CardContent className="p-0"> <CardContent className="p-0 overflow-hidden">
<div className="flex"> <div className="flex w-full overflow-hidden">
{/* Columna de nombres de proyectos */} {/* Columna de nombres de proyectos - fija */}
<div className="w-64 flex-shrink-0 border-r border-gray-200 bg-gray-50"> <div className="w-64 flex-shrink-0 border-r border-gray-200 bg-gray-50">
{/* Header */} {/* Header */}
<div className="h-16 border-b border-gray-200 flex items-center px-4"> <div className="h-16 border-b border-gray-200 flex items-center px-4">
@ -321,27 +416,27 @@ export default function GanttPage() {
})} })}
</div> </div>
{/* Timeline */} {/* Timeline - scroll horizontal en modo "todo" */}
<div className="flex-1 overflow-x-auto"> <div
className={`${timeRange === "all" ? "overflow-x-auto overflow-y-hidden" : "overflow-hidden"}`}
style={{ width: "calc(100% - 256px)" }}
>
<div style={{ width: timeRange === "all" ? `${visibleMonths.length * 100}px` : "100%" }}>
{/* Header con meses */} {/* Header con meses */}
<div className="h-16 border-b border-gray-200 flex"> <div className="h-16 border-b border-gray-200 flex">
{visibleMonths.map((month, idx) => { {visibleMonths.map((month) => {
const daysInMonth = getDaysInMonth(month.month, month.year);
const widthPercent = (daysInMonth / totalDays) * 100;
const isCurrentMonth = new Date().getMonth() === month.month && new Date().getFullYear() === month.year; const isCurrentMonth = new Date().getMonth() === month.month && new Date().getFullYear() === month.year;
return ( return (
<div <div
key={`${month.year}-${month.month}`} key={`${month.year}-${month.month}`}
className={`flex-shrink-0 border-r border-gray-200 flex flex-col justify-center px-2 ${ className={`flex-1 border-r border-gray-200 flex flex-col justify-center px-2 ${
isCurrentMonth ? "bg-blue-50" : "bg-white" isCurrentMonth ? "bg-blue-50" : "bg-white"
}`} }`}
style={{ width: `${widthPercent}%`, minWidth: "80px" }}
> >
<span className={`text-xs font-medium ${isCurrentMonth ? "text-blue-700" : "text-gray-600"}`}> <span className={`text-xs font-medium ${isCurrentMonth ? "text-blue-700" : "text-gray-600"}`}>
{month.label} {month.label}
</span> </span>
<span className="text-xs text-gray-400">{daysInMonth} días</span>
</div> </div>
); );
})} })}
@ -354,7 +449,7 @@ export default function GanttPage() {
const projectStart = new Date(project.startDate); const projectStart = new Date(project.startDate);
const projectEnd = new Date(project.endDate); const projectEnd = new Date(project.endDate);
// Calcular posición y ancho de la barra // Calcular posición y ancho de la barra basado en días
const startOffset = Math.max(0, getDaysBetween(visibleStart, projectStart)); const startOffset = Math.max(0, getDaysBetween(visibleStart, projectStart));
const endOffset = Math.min(totalDays, getDaysBetween(visibleStart, projectEnd)); const endOffset = Math.min(totalDays, getDaysBetween(visibleStart, projectEnd));
@ -372,18 +467,15 @@ export default function GanttPage() {
> >
{/* Grid de meses */} {/* Grid de meses */}
<div className="absolute inset-0 flex"> <div className="absolute inset-0 flex">
{visibleMonths.map((month, idx) => { {visibleMonths.map((month) => {
const daysInMonth = getDaysInMonth(month.month, month.year);
const monthWidthPercent = (daysInMonth / totalDays) * 100;
const isCurrentMonth = new Date().getMonth() === month.month && new Date().getFullYear() === month.year; const isCurrentMonth = new Date().getMonth() === month.month && new Date().getFullYear() === month.year;
return ( return (
<div <div
key={`grid-${month.year}-${month.month}`} key={`grid-${month.year}-${month.month}`}
className={`flex-shrink-0 border-r border-gray-100 ${ className={`flex-1 border-r border-gray-100 ${
isCurrentMonth ? "bg-blue-50/30" : "" isCurrentMonth ? "bg-blue-50/30" : ""
}`} }`}
style={{ width: `${monthWidthPercent}%`, minWidth: "80px" }}
/> />
); );
})} })}
@ -443,29 +535,10 @@ export default function GanttPage() {
</TooltipProvider> </TooltipProvider>
</div> </div>
</div> </div>
</div>
</CardContent> </CardContent>
</Card> </Card>
)} )}
{/* Leyenda */}
{!loading && filteredProjects.length > 0 && (
<div className="mt-6 flex flex-wrap items-center gap-6">
<div className="flex items-center gap-2">
<div className="w-16 h-4 bg-gray-200 rounded relative overflow-hidden">
<div className="absolute inset-y-0 left-0 w-1/2 bg-blue-500 rounded" />
</div>
<span className="text-sm text-gray-600">Progreso del proyecto</span>
</div>
<div className="flex items-center gap-2">
<div className="w-4 h-4 bg-blue-50 border-2 border-blue-500 rounded" />
<span className="text-sm text-gray-600">Mes actual</span>
</div>
<div className="flex items-center gap-2">
<div className="w-4 h-4 bg-gray-200 ring-2 ring-red-400 rounded" />
<span className="text-sm text-gray-600">Proyecto retrasado</span>
</div>
</div>
)}
</main> </main>
</div> </div>
); );

View File

@ -299,7 +299,10 @@ function BudgetBarChart({ projects, title, maxItems = 6 }: BudgetBarChartProps)
<XAxis type="number" tickFormatter={(v) => `${(v / 1000).toFixed(0)}k`} fontSize={11} /> <XAxis type="number" tickFormatter={(v) => `${(v / 1000).toFixed(0)}k`} fontSize={11} />
<YAxis type="category" dataKey="name" width={100} fontSize={10} /> <YAxis type="category" dataKey="name" width={100} fontSize={10} />
<Tooltip <Tooltip
formatter={(value, name) => [`€${Number(value ?? 0).toLocaleString("es-ES")}`, name === 'presupuesto' ? 'Presupuesto' : 'Gastado']} formatter={(value, name) => {
const label = name === 'presupuesto' ? 'Presupuesto' : name === 'gastado' ? 'Gastado' : String(name);
return [`€${Number(value ?? 0).toLocaleString("es-ES")}`, label];
}}
labelFormatter={(label, payload) => payload?.[0]?.payload?.fullName || label} labelFormatter={(label, payload) => payload?.[0]?.payload?.fullName || label}
contentStyle={{ fontSize: '12px' }} contentStyle={{ fontSize: '12px' }}
/> />