diff --git a/components/WeeklyGrid.tsx b/components/WeeklyGrid.tsx index 7f99d5d..35f437e 100644 --- a/components/WeeklyGrid.tsx +++ b/components/WeeklyGrid.tsx @@ -1,4 +1,4 @@ -import React, { useMemo } from 'react'; +import React, { useMemo, useState } from 'react'; import { CombinedKPIs } from '../types'; import { pivotWeeklySalesData, WeeklyPivotRow } from '../services/dataProcessor'; @@ -6,23 +6,60 @@ interface WeeklyGridProps { data: CombinedKPIs[]; } +type SortConfig = { + key: string; // weekKey + direction: 'asc' | 'desc'; +} | null; + const WeeklyGrid: React.FC = ({ data }) => { const { rows, weeks } = useMemo(() => pivotWeeklySalesData(data), [data]); - // Group rows by 'line' + // Default sort: most recent week, descending + const [sortConfig, setSortConfig] = useState(() => { + if (weeks.length > 0) { + return { key: weeks[0], direction: 'desc' }; + } + return null; + }); + + const handleSort = (weekKey: string) => { + setSortConfig(prev => { + if (prev?.key === weekKey) { + return { key: weekKey, direction: prev.direction === 'asc' ? 'desc' : 'asc' }; + } + return { key: weekKey, direction: 'desc' }; + }); + }; + + // Group and Sort rows const groupedRows = useMemo(() => { const groups: { [line: string]: WeeklyPivotRow[] } = {}; - rows.forEach(row => { + + // Clone and sort rows based on config + const sortedRows = [...rows]; + if (sortConfig) { + sortedRows.sort((a, b) => { + const valA = a.unitsByWeek[sortConfig.key] || 0; + const valB = b.unitsByWeek[sortConfig.key] || 0; + if (sortConfig.direction === 'asc') { + return valA - valB; + } + return valB - valA; + }); + } + + sortedRows.forEach(row => { const line = row.line || 'Uncategorized'; if (!groups[line]) groups[line] = []; groups[line].push(row); }); + // Sort lines alphabetically return Object.keys(groups).sort().reduce((acc, line) => { acc[line] = groups[line]; return acc; }, {} as { [line: string]: WeeklyPivotRow[] }); - }, [rows]); + }, [rows, sortConfig]); // Calculate totals per week const weekTotals = useMemo(() => { @@ -53,8 +90,17 @@ const WeeklyGrid: React.FC = ({ data }) => { Product Details {weeks.map(week => ( - - {week.split('-')[1]}/{week.split('-')[0].slice(-2)} + handleSort(week)} + > +
+ {week.split('-')[1]}/{week.split('-')[0].slice(-2)} + {sortConfig?.key === week && ( + {sortConfig.direction === 'asc' ? '↑' : '↓'} + )} +
))} @@ -91,9 +137,9 @@ const WeeklyGrid: React.FC = ({ data }) => { const val = row.unitsByWeek[week] || 0; const prevVal = row.unitsByWeek[weeks[idx + 1]] || 0; return ( - +
- 0 ? 'text-white' : 'text-slate-700'}`}> + 0 ? (sortConfig?.key === week ? 'text-indigo-400' : 'text-white') : 'text-slate-700'}`}> {val > 0 ? val.toLocaleString('de-DE') : '-'} {val > 0 && renderGrowth(val, prevVal)}