feat: add category breakdown by parent to statistics page and enhance pie chart with toggle for grouping options

This commit is contained in:
Julien Froidefond
2025-11-30 17:16:47 +01:00
parent 00dd8fc335
commit 032886dc1c
2 changed files with 174 additions and 74 deletions

View File

@@ -242,8 +242,39 @@ export default function StatisticsPage() {
icon: category?.icon || "HelpCircle", icon: category?.icon || "HelpCircle",
}; };
}) })
.sort((a, b) => b.value - a.value) .sort((a, b) => b.value - a.value);
.slice(0, 8);
// Category breakdown grouped by parent (expenses only)
const categoryTotalsByParent = new Map<string, number>();
transactions
.filter((t) => t.amount < 0)
.forEach((t) => {
const category = data.categories.find((c) => c.id === t.categoryId);
// Use parent category ID if exists, otherwise use the category itself
let groupId: string;
if (!category) {
groupId = "uncategorized";
} else if (category.parentId) {
groupId = category.parentId;
} else {
// Category is a parent itself
groupId = category.id;
}
const current = categoryTotalsByParent.get(groupId) || 0;
categoryTotalsByParent.set(groupId, current + Math.abs(t.amount));
});
const categoryChartDataByParent = Array.from(categoryTotalsByParent.entries())
.map(([groupId, total]) => {
const category = data.categories.find((c) => c.id === groupId);
return {
name: category?.name || "Non catégorisé",
value: Math.round(total),
color: category?.color || "#94a3b8",
icon: category?.icon || "HelpCircle",
};
})
.sort((a, b) => b.value - a.value);
// Top expenses - deduplicate by ID and sort by amount (most negative first) // Top expenses - deduplicate by ID and sort by amount (most negative first)
const uniqueTransactions = Array.from( const uniqueTransactions = Array.from(
@@ -537,6 +568,7 @@ export default function StatisticsPage() {
return { return {
monthlyChartData, monthlyChartData,
categoryChartData, categoryChartData,
categoryChartDataByParent,
topExpenses, topExpenses,
totalIncome, totalIncome,
totalExpenses, totalExpenses,
@@ -793,9 +825,11 @@ export default function StatisticsPage() {
{/* Analyse par Catégorie */} {/* Analyse par Catégorie */}
<section className="mb-8"> <section className="mb-8">
<h2 className="text-2xl font-semibold mb-4">Analyse par Catégorie</h2> <h2 className="text-2xl font-semibold mb-4">Analyse par Catégorie</h2>
<div className="grid gap-6 lg:grid-cols-2"> <div className="grid gap-6">
<CategoryPieChart <CategoryPieChart
data={stats.categoryChartData} data={stats.categoryChartData}
dataByParent={stats.categoryChartDataByParent}
categories={data.categories}
formatCurrency={formatCurrency} formatCurrency={formatCurrency}
/> />
<CategoryBarChart <CategoryBarChart

View File

@@ -1,6 +1,8 @@
"use client"; "use client";
import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { CategoryIcon } from "@/components/ui/category-icon"; import { CategoryIcon } from "@/components/ui/category-icon";
import { import {
PieChart, PieChart,
@@ -10,6 +12,8 @@ import {
ResponsiveContainer, ResponsiveContainer,
Legend, Legend,
} from "recharts"; } from "recharts";
import { Layers, List, ChevronDown, ChevronUp } from "lucide-react";
import type { Category } from "@/lib/types";
export interface CategoryChartData { export interface CategoryChartData {
name: string; name: string;
@@ -21,6 +25,8 @@ export interface CategoryChartData {
interface CategoryPieChartProps { interface CategoryPieChartProps {
data: CategoryChartData[]; data: CategoryChartData[];
dataByParent?: CategoryChartData[];
categories?: Category[];
formatCurrency: (amount: number) => string; formatCurrency: (amount: number) => string;
title?: string; title?: string;
height?: number; height?: number;
@@ -31,6 +37,8 @@ interface CategoryPieChartProps {
export function CategoryPieChart({ export function CategoryPieChart({
data, data,
dataByParent,
categories = [],
formatCurrency, formatCurrency,
title = "Répartition par catégorie", title = "Répartition par catégorie",
height = 300, height = 300,
@@ -38,18 +46,70 @@ export function CategoryPieChart({
outerRadius = 100, outerRadius = 100,
emptyMessage = "Pas de données pour cette période", emptyMessage = "Pas de données pour cette période",
}: CategoryPieChartProps) { }: CategoryPieChartProps) {
const [groupByParent, setGroupByParent] = useState(true);
const [isExpanded, setIsExpanded] = useState(false);
const hasParentData = dataByParent && dataByParent.length > 0;
const baseData = (groupByParent && hasParentData) ? dataByParent : data;
// Limit to top 8 by default, show all if expanded
const maxItems = 8;
const currentData = isExpanded ? baseData : baseData.slice(0, maxItems);
return ( return (
<Card> <Card>
<CardHeader> <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle>{title}</CardTitle> <CardTitle>{title}</CardTitle>
<div className="flex gap-2">
{hasParentData && (
<Button
variant={groupByParent ? "default" : "ghost"}
size="sm"
onClick={() => setGroupByParent(!groupByParent)}
title={groupByParent ? "Afficher toutes les catégories" : "Regrouper par catégories parentes"}
>
{groupByParent ? (
<>
<List className="w-4 h-4 mr-1" />
Par catégorie
</>
) : (
<>
<Layers className="w-4 h-4 mr-1" />
Par parent
</>
)}
</Button>
)}
{baseData.length > maxItems && (
<Button
variant="ghost"
size="sm"
onClick={() => setIsExpanded(!isExpanded)}
>
{isExpanded ? (
<>
<ChevronUp className="w-4 h-4 mr-1" />
Réduire
</>
) : (
<>
<ChevronDown className="w-4 h-4 mr-1" />
Voir tout ({baseData.length})
</>
)}
</Button>
)}
</div>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
{data.length > 0 ? ( {currentData.length > 0 ? (
<div style={{ height }}> <div className="flex flex-col lg:flex-row gap-6">
<ResponsiveContainer width="100%" height="100%"> {/* Graphique */}
<div className="flex-1" style={{ minHeight: height }}>
<ResponsiveContainer width="100%" height={height}>
<PieChart> <PieChart>
<Pie <Pie
data={data} data={currentData}
cx="50%" cx="50%"
cy="50%" cy="50%"
innerRadius={innerRadius} innerRadius={innerRadius}
@@ -57,7 +117,7 @@ export function CategoryPieChart({
paddingAngle={2} paddingAngle={2}
dataKey="value" dataKey="value"
> >
{data.map((entry, index) => ( {currentData.map((entry, index) => (
<Cell key={`cell-${index}`} fill={entry.color} /> <Cell key={`cell-${index}`} fill={entry.color} />
))} ))}
</Pie> </Pie>
@@ -93,31 +153,37 @@ export function CategoryPieChart({
); );
}} }}
/> />
<Legend
content={({ payload }) => (
<div className="flex flex-wrap justify-center gap-x-4 gap-y-1 mt-2">
{payload?.map((entry, index) => {
const item = data.find((d) => d.name === entry.value);
return (
<div
key={`legend-${index}`}
className="flex items-center gap-1.5 text-sm"
>
<CategoryIcon
icon={item?.icon || "HelpCircle"}
color={item?.color || "#94a3b8"}
size={14}
/>
<span className="text-foreground">{entry.value}</span>
</div>
);
})}
</div>
)}
/>
</PieChart> </PieChart>
</ResponsiveContainer> </ResponsiveContainer>
</div> </div>
{/* Légende */}
<div className="lg:w-[280px] lg:min-w-[280px]">
<div className="text-sm font-medium mb-3 text-muted-foreground">
Légende
</div>
<div className="max-h-[300px] overflow-y-auto overflow-x-hidden pr-2 space-y-2">
{currentData.map((item, index) => (
<div
key={`legend-${index}`}
className="flex items-center gap-2 text-sm"
>
<CategoryIcon
icon={item.icon}
color={item.color}
size={16}
/>
<span className="text-foreground flex-1 min-w-0 truncate">
{item.name}
</span>
<span className="text-foreground font-semibold tabular-nums whitespace-nowrap">
{formatCurrency(item.value)}
</span>
</div>
))}
</div>
</div>
</div>
) : ( ) : (
<div <div
style={{ height }} style={{ height }}