Files
fintrack/components/dashboard/category-breakdown.tsx

98 lines
2.9 KiB
TypeScript

"use client";
import {
CategoryPieChart,
type CategoryChartData,
} from "@/components/statistics/category-pie-chart";
import type { BankingData } from "@/lib/types";
interface CategoryBreakdownProps {
data: BankingData;
}
export function CategoryBreakdown({ data }: CategoryBreakdownProps) {
// Get current month expenses by category
const thisMonth = new Date();
thisMonth.setDate(1);
const thisMonthStr = thisMonth.toISOString().slice(0, 7);
const monthExpenses = data.transactions.filter(
(t) => t.date.startsWith(thisMonthStr) && t.amount < 0,
);
const categoryTotals = new Map<string, number>();
monthExpenses.forEach((t) => {
const catId = t.categoryId || "uncategorized";
const current = categoryTotals.get(catId) || 0;
categoryTotals.set(catId, current + Math.abs(t.amount));
});
const chartData: CategoryChartData[] = Array.from(categoryTotals.entries())
.map(([categoryId, total]) => {
const category = data.categories.find((c) => c.id === categoryId);
return {
name: category?.name || "Non catégorisé",
value: total,
color: category?.color || "#94a3b8",
icon: category?.icon || "HelpCircle",
categoryId: categoryId === "uncategorized" ? null : categoryId,
};
})
.sort((a, b) => b.value - a.value);
// Category breakdown grouped by parent
const categoryTotalsByParent = new Map<string, number>();
monthExpenses.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 chartDataByParent: CategoryChartData[] = Array.from(
categoryTotalsByParent.entries(),
)
.map(([groupId, total]) => {
const category = data.categories.find((c) => c.id === groupId);
return {
name: category?.name || "Non catégorisé",
value: total,
color: category?.color || "#94a3b8",
icon: category?.icon || "HelpCircle",
categoryId: groupId === "uncategorized" ? null : groupId,
};
})
.sort((a, b) => b.value - a.value);
const formatCurrency = (value: number) => {
return new Intl.NumberFormat("fr-FR", {
style: "currency",
currency: "EUR",
}).format(value);
};
return (
<CategoryPieChart
data={chartData}
dataByParent={chartDataByParent}
categories={data.categories}
formatCurrency={formatCurrency}
title="Dépenses par catégorie"
height={250}
innerRadius={50}
outerRadius={80}
emptyMessage="Pas de données ce mois-ci"
/>
);
}