refactor: migrate from ESLint to Biome and extract SQL queries to data.ts

- Replace ESLint with Biome for linting and formatting
- Configure Biome with tabs, double quotes, and organized imports
- Move all SQL/Drizzle queries from page.tsx files to data.ts files
- Create new data.ts files for: ajustes, dashboard, relatorios/categorias
- Update existing data.ts files: extrato, fatura (add lancamentos queries)
- Remove all drizzle-orm imports from page.tsx files
- Update README.md with new tooling info

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Felipe Coutinho
2026-01-27 13:15:37 +00:00
parent 8ffe61c59b
commit a7f63fb77a
442 changed files with 66141 additions and 69292 deletions

View File

@@ -1,121 +1,121 @@
"use client";
import { RiPieChartLine } from "@remixicon/react";
import MoneyValues from "@/components/money-values";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { WidgetEmptyState } from "@/components/widget-empty-state";
import type { CardDetailData } from "@/lib/relatorios/cartoes-report";
import {
buildCategoryInitials,
getCategoryBgColor,
getCategoryColor,
buildCategoryInitials,
getCategoryBgColor,
getCategoryColor,
} from "@/lib/utils/category-colors";
import { getIconComponent } from "@/lib/utils/icons";
import { title_font } from "@/public/fonts/font_index";
import { RiPieChartLine } from "@remixicon/react";
type CardCategoryBreakdownProps = {
data: CardDetailData["categoryBreakdown"];
data: CardDetailData["categoryBreakdown"];
};
export function CardCategoryBreakdown({ data }: CardCategoryBreakdownProps) {
if (data.length === 0) {
return (
<Card className="h-full">
<CardHeader className="pb-3">
<CardTitle
className={`${title_font.className} flex items-center gap-1.5 text-base`}
>
<RiPieChartLine className="size-4 text-primary" />
Gastos por Categoria
</CardTitle>
</CardHeader>
<CardContent>
<WidgetEmptyState
icon={<RiPieChartLine className="size-6 text-muted-foreground" />}
title="Nenhuma categoria encontrada"
description="Quando houver despesas categorizadas, elas aparecerão aqui."
/>
</CardContent>
</Card>
);
}
if (data.length === 0) {
return (
<Card className="h-full">
<CardHeader className="pb-3">
<CardTitle
className={`${title_font.className} flex items-center gap-1.5 text-base`}
>
<RiPieChartLine className="size-4 text-primary" />
Gastos por Categoria
</CardTitle>
</CardHeader>
<CardContent>
<WidgetEmptyState
icon={<RiPieChartLine className="size-6 text-muted-foreground" />}
title="Nenhuma categoria encontrada"
description="Quando houver despesas categorizadas, elas aparecerão aqui."
/>
</CardContent>
</Card>
);
}
const totalAmount = data.reduce((acc, c) => acc + c.amount, 0);
const _totalAmount = data.reduce((acc, c) => acc + c.amount, 0);
return (
<Card className="h-full">
<CardHeader className="pb-3">
<CardTitle
className={`${title_font.className} flex items-center gap-1.5 text-base`}
>
<RiPieChartLine className="size-4 text-primary" />
Gastos por Categoria
</CardTitle>
</CardHeader>
return (
<Card className="h-full">
<CardHeader className="pb-3">
<CardTitle
className={`${title_font.className} flex items-center gap-1.5 text-base`}
>
<RiPieChartLine className="size-4 text-primary" />
Gastos por Categoria
</CardTitle>
</CardHeader>
<CardContent className="pt-0">
<div className="flex flex-col">
{data.map((category, index) => {
const IconComponent = category.icon
? getIconComponent(category.icon)
: null;
const color = getCategoryColor(index);
const bgColor = getCategoryBgColor(index);
const initials = buildCategoryInitials(category.name);
<CardContent className="pt-0">
<div className="flex flex-col">
{data.map((category, index) => {
const IconComponent = category.icon
? getIconComponent(category.icon)
: null;
const color = getCategoryColor(index);
const bgColor = getCategoryBgColor(index);
const initials = buildCategoryInitials(category.name);
return (
<div
key={category.id}
className="flex flex-col py-2 border-b border-dashed last:border-0"
>
<div className="flex items-center justify-between gap-3">
<div className="flex min-w-0 flex-1 items-center gap-2">
<div
className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-lg"
style={{ backgroundColor: bgColor }}
>
{IconComponent ? (
<IconComponent className="size-4" style={{ color }} />
) : (
<span
className="text-xs font-semibold uppercase"
style={{ color }}
>
{initials}
</span>
)}
</div>
return (
<div
key={category.id}
className="flex flex-col py-2 border-b border-dashed last:border-0"
>
<div className="flex items-center justify-between gap-3">
<div className="flex min-w-0 flex-1 items-center gap-2">
<div
className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-lg"
style={{ backgroundColor: bgColor }}
>
{IconComponent ? (
<IconComponent className="size-4" style={{ color }} />
) : (
<span
className="text-xs font-semibold uppercase"
style={{ color }}
>
{initials}
</span>
)}
</div>
{/* Name and percentage */}
<div className="min-w-0 flex-1">
<span className="text-sm font-medium truncate block">
{category.name}
</span>
<span className="text-xs text-muted-foreground">
{category.percent.toFixed(0)}% do total
</span>
</div>
</div>
{/* Name and percentage */}
<div className="min-w-0 flex-1">
<span className="text-sm font-medium truncate block">
{category.name}
</span>
<span className="text-xs text-muted-foreground">
{category.percent.toFixed(0)}% do total
</span>
</div>
</div>
{/* Value */}
<div className="flex shrink-0 flex-col items-end">
<MoneyValues
className="text-foreground"
amount={category.amount}
/>
</div>
</div>
{/* Value */}
<div className="flex shrink-0 flex-col items-end">
<MoneyValues
className="text-foreground"
amount={category.amount}
/>
</div>
</div>
{/* Progress bar */}
<div className="ml-12 mt-1.5">
<Progress className="h-1.5" value={category.percent} />
</div>
</div>
);
})}
</div>
</CardContent>
</Card>
);
{/* Progress bar */}
<div className="ml-12 mt-1.5">
<Progress className="h-1.5" value={category.percent} />
</div>
</div>
);
})}
</div>
</CardContent>
</Card>
);
}

View File

@@ -1,113 +1,113 @@
"use client";
import { RiBankCard2Fill } from "@remixicon/react";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import type { CardDetailData } from "@/lib/relatorios/cartoes-report";
import { title_font } from "@/public/fonts/font_index";
import { RiBankCard2Fill } from "@remixicon/react";
type CardInvoiceStatusProps = {
data: CardDetailData["invoiceStatus"];
data: CardDetailData["invoiceStatus"];
};
const monthLabels = [
"Jan",
"Fev",
"Mar",
"Abr",
"Mai",
"Jun",
"Jul",
"Ago",
"Set",
"Out",
"Nov",
"Dez",
"Jan",
"Fev",
"Mar",
"Abr",
"Mai",
"Jun",
"Jul",
"Ago",
"Set",
"Out",
"Nov",
"Dez",
];
export function CardInvoiceStatus({ data }: CardInvoiceStatusProps) {
const formatCurrency = (value: number) => {
return new Intl.NumberFormat("pt-BR", {
style: "currency",
currency: "BRL",
minimumFractionDigits: 0,
maximumFractionDigits: 0,
}).format(value);
};
const formatCurrency = (value: number) => {
return new Intl.NumberFormat("pt-BR", {
style: "currency",
currency: "BRL",
minimumFractionDigits: 0,
maximumFractionDigits: 0,
}).format(value);
};
const getStatusBadge = (status: string | null) => {
switch (status) {
case "pago":
return (
<Badge
variant="outline"
className="bg-green-50 text-green-700 border-green-200 dark:bg-green-950 dark:text-green-400 dark:border-green-900"
>
Pago
</Badge>
);
case "pendente":
return (
<Badge
variant="outline"
className="bg-yellow-50 text-yellow-700 border-yellow-200 dark:bg-yellow-950 dark:text-yellow-400 dark:border-yellow-900"
>
Pendente
</Badge>
);
case "atrasado":
return (
<Badge
variant="outline"
className="bg-red-50 text-red-700 border-red-200 dark:bg-red-950 dark:text-red-400 dark:border-red-900"
>
Atrasado
</Badge>
);
default:
return (
<Badge variant="outline" className="text-muted-foreground">
</Badge>
);
}
};
const getStatusBadge = (status: string | null) => {
switch (status) {
case "pago":
return (
<Badge
variant="outline"
className="bg-green-50 text-green-700 border-green-200 dark:bg-green-950 dark:text-green-400 dark:border-green-900"
>
Pago
</Badge>
);
case "pendente":
return (
<Badge
variant="outline"
className="bg-yellow-50 text-yellow-700 border-yellow-200 dark:bg-yellow-950 dark:text-yellow-400 dark:border-yellow-900"
>
Pendente
</Badge>
);
case "atrasado":
return (
<Badge
variant="outline"
className="bg-red-50 text-red-700 border-red-200 dark:bg-red-950 dark:text-red-400 dark:border-red-900"
>
Atrasado
</Badge>
);
default:
return (
<Badge variant="outline" className="text-muted-foreground">
</Badge>
);
}
};
const formatPeriod = (period: string) => {
const [year, month] = period.split("-");
return `${monthLabels[parseInt(month, 10) - 1]}/${year.slice(2)}`;
};
const formatPeriod = (period: string) => {
const [year, month] = period.split("-");
return `${monthLabels[parseInt(month, 10) - 1]}/${year.slice(2)}`;
};
return (
<Card>
<CardHeader className="pb-2">
<CardTitle
className={`${title_font.className} flex items-center gap-1.5 text-base`}
>
<RiBankCard2Fill className="size-4 text-primary" />
Status das Faturas
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-2">
{[...data].reverse().map((invoice) => (
<div
key={invoice.period}
className="flex items-center justify-between py-2 border-b last:border-b-0"
>
<div className="flex items-center gap-3">
<span className="text-sm font-medium w-16">
{formatPeriod(invoice.period)}
</span>
{getStatusBadge(invoice.status)}
</div>
<span className="text-sm font-bold">
{formatCurrency(invoice.amount)}
</span>
</div>
))}
</div>
</CardContent>
</Card>
);
return (
<Card>
<CardHeader className="pb-2">
<CardTitle
className={`${title_font.className} flex items-center gap-1.5 text-base`}
>
<RiBankCard2Fill className="size-4 text-primary" />
Status das Faturas
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-2">
{[...data].reverse().map((invoice) => (
<div
key={invoice.period}
className="flex items-center justify-between py-2 border-b last:border-b-0"
>
<div className="flex items-center gap-3">
<span className="text-sm font-medium w-16">
{formatPeriod(invoice.period)}
</span>
{getStatusBadge(invoice.status)}
</div>
<span className="text-sm font-bold">
{formatCurrency(invoice.amount)}
</span>
</div>
))}
</div>
</CardContent>
</Card>
);
}

View File

@@ -1,5 +1,6 @@
"use client";
import { RiShoppingBag3Line } from "@remixicon/react";
import MoneyValues from "@/components/money-values";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
@@ -7,106 +8,105 @@ import { Progress } from "@/components/ui/progress";
import { WidgetEmptyState } from "@/components/widget-empty-state";
import type { CardDetailData } from "@/lib/relatorios/cartoes-report";
import { title_font } from "@/public/fonts/font_index";
import { RiShoppingBag3Line } from "@remixicon/react";
type CardTopExpensesProps = {
data: CardDetailData["topExpenses"];
data: CardDetailData["topExpenses"];
};
export function CardTopExpenses({ data }: CardTopExpensesProps) {
if (data.length === 0) {
return (
<Card className="h-full">
<CardHeader className="pb-3">
<CardTitle
className={`${title_font.className} flex items-center gap-1.5 text-base`}
>
<RiShoppingBag3Line className="size-4 text-primary" />
Top 10 Gastos do Mês
</CardTitle>
</CardHeader>
<CardContent>
<WidgetEmptyState
icon={
<RiShoppingBag3Line className="size-6 text-muted-foreground" />
}
title="Nenhum gasto encontrado"
description="Quando houver gastos registrados, eles aparecerão aqui."
/>
</CardContent>
</Card>
);
}
if (data.length === 0) {
return (
<Card className="h-full">
<CardHeader className="pb-3">
<CardTitle
className={`${title_font.className} flex items-center gap-1.5 text-base`}
>
<RiShoppingBag3Line className="size-4 text-primary" />
Top 10 Gastos do Mês
</CardTitle>
</CardHeader>
<CardContent>
<WidgetEmptyState
icon={
<RiShoppingBag3Line className="size-6 text-muted-foreground" />
}
title="Nenhum gasto encontrado"
description="Quando houver gastos registrados, eles aparecerão aqui."
/>
</CardContent>
</Card>
);
}
const maxAmount = Math.max(...data.map((e) => e.amount));
const maxAmount = Math.max(...data.map((e) => e.amount));
return (
<Card className="h-full">
<CardHeader className="pb-3">
<CardTitle
className={`${title_font.className} flex items-center gap-1.5 text-base`}
>
<RiShoppingBag3Line className="size-4 text-primary" />
Top 10 Gastos do Mês
</CardTitle>
</CardHeader>
<CardContent className="pt-0">
<div className="flex flex-col">
{data.map((expense, index) => (
<div
key={expense.id}
className="flex flex-col py-2 border-b border-dashed last:border-0"
>
<div className="flex items-center justify-between gap-3">
<div className="flex min-w-0 flex-1 items-center gap-2">
{/* Rank number */}
<div className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted">
<span className="text-sm font-semibold text-muted-foreground">
{index + 1}
</span>
</div>
return (
<Card className="h-full">
<CardHeader className="pb-3">
<CardTitle
className={`${title_font.className} flex items-center gap-1.5 text-base`}
>
<RiShoppingBag3Line className="size-4 text-primary" />
Top 10 Gastos do Mês
</CardTitle>
</CardHeader>
<CardContent className="pt-0">
<div className="flex flex-col">
{data.map((expense, index) => (
<div
key={expense.id}
className="flex flex-col py-2 border-b border-dashed last:border-0"
>
<div className="flex items-center justify-between gap-3">
<div className="flex min-w-0 flex-1 items-center gap-2">
{/* Rank number */}
<div className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted">
<span className="text-sm font-semibold text-muted-foreground">
{index + 1}
</span>
</div>
{/* Name and details */}
<div className="min-w-0 flex-1">
<span className="text-sm font-medium truncate block">
{expense.name}
</span>
<div className="flex items-center gap-1 mt-0.5 flex-wrap">
<span className="text-xs text-muted-foreground">
{expense.date}
</span>
{expense.category && (
<Badge
variant="secondary"
className="text-xs px-1.5 py-0 h-5"
>
{expense.category}
</Badge>
)}
</div>
</div>
</div>
{/* Name and details */}
<div className="min-w-0 flex-1">
<span className="text-sm font-medium truncate block">
{expense.name}
</span>
<div className="flex items-center gap-1 mt-0.5 flex-wrap">
<span className="text-xs text-muted-foreground">
{expense.date}
</span>
{expense.category && (
<Badge
variant="secondary"
className="text-xs px-1.5 py-0 h-5"
>
{expense.category}
</Badge>
)}
</div>
</div>
</div>
{/* Value */}
<div className="flex shrink-0 flex-col items-end">
<MoneyValues
className="text-red-600 dark:text-red-500"
amount={expense.amount}
/>
</div>
</div>
{/* Value */}
<div className="flex shrink-0 flex-col items-end">
<MoneyValues
className="text-red-600 dark:text-red-500"
amount={expense.amount}
/>
</div>
</div>
{/* Progress bar */}
<div className="ml-12 mt-1.5">
<Progress
className="h-1.5"
value={(expense.amount / maxAmount) * 100}
/>
</div>
</div>
))}
</div>
</CardContent>
</Card>
);
{/* Progress bar */}
<div className="ml-12 mt-1.5">
<Progress
className="h-1.5"
value={(expense.amount / maxAmount) * 100}
/>
</div>
</div>
))}
</div>
</CardContent>
</Card>
);
}

View File

@@ -1,222 +1,222 @@
"use client";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import {
ChartContainer,
ChartTooltip,
type ChartConfig,
} from "@/components/ui/chart";
import type { CardDetailData } from "@/lib/relatorios/cartoes-report";
import { cn } from "@/lib/utils";
import { RiBankCard2Line } from "@remixicon/react";
import Image from "next/image";
import { useState } from "react";
import {
Bar,
BarChart,
CartesianGrid,
ReferenceLine,
XAxis,
YAxis,
Bar,
BarChart,
CartesianGrid,
ReferenceLine,
XAxis,
YAxis,
} from "recharts";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import {
type ChartConfig,
ChartContainer,
ChartTooltip,
} from "@/components/ui/chart";
import type { CardDetailData } from "@/lib/relatorios/cartoes-report";
import { cn } from "@/lib/utils";
type CardUsageChartProps = {
data: CardDetailData["monthlyUsage"];
limit: number;
card: {
name: string;
logo: string | null;
};
data: CardDetailData["monthlyUsage"];
limit: number;
card: {
name: string;
logo: string | null;
};
};
const chartConfig = {
amount: {
label: "Uso",
color: "#3b82f6",
},
amount: {
label: "Uso",
color: "#3b82f6",
},
} satisfies ChartConfig;
type PeriodFilter = "3" | "6" | "12";
const filterOptions: { value: PeriodFilter; label: string }[] = [
{ value: "3", label: "3 meses" },
{ value: "6", label: "6 meses" },
{ value: "12", label: "12 meses" },
{ value: "3", label: "3 meses" },
{ value: "6", label: "6 meses" },
{ value: "12", label: "12 meses" },
];
const resolveLogoPath = (logo: string | null) => {
if (!logo) return null;
if (
logo.startsWith("http://") ||
logo.startsWith("https://") ||
logo.startsWith("data:")
) {
return logo;
}
return logo.startsWith("/") ? logo : `/logos/${logo}`;
if (!logo) return null;
if (
logo.startsWith("http://") ||
logo.startsWith("https://") ||
logo.startsWith("data:")
) {
return logo;
}
return logo.startsWith("/") ? logo : `/logos/${logo}`;
};
export function CardUsageChart({ data, limit, card }: CardUsageChartProps) {
const [period, setPeriod] = useState<PeriodFilter>("6");
const [period, setPeriod] = useState<PeriodFilter>("6");
const formatCurrency = (value: number) => {
return new Intl.NumberFormat("pt-BR", {
style: "currency",
currency: "BRL",
minimumFractionDigits: 0,
maximumFractionDigits: 0,
}).format(value);
};
const formatCurrency = (value: number) => {
return new Intl.NumberFormat("pt-BR", {
style: "currency",
currency: "BRL",
minimumFractionDigits: 0,
maximumFractionDigits: 0,
}).format(value);
};
const formatCurrencyCompact = (value: number) => {
if (Math.abs(value) >= 1000) {
return new Intl.NumberFormat("pt-BR", {
style: "currency",
currency: "BRL",
minimumFractionDigits: 0,
maximumFractionDigits: 0,
notation: "compact",
}).format(value);
}
return formatCurrency(value);
};
const formatCurrencyCompact = (value: number) => {
if (Math.abs(value) >= 1000) {
return new Intl.NumberFormat("pt-BR", {
style: "currency",
currency: "BRL",
minimumFractionDigits: 0,
maximumFractionDigits: 0,
notation: "compact",
}).format(value);
}
return formatCurrency(value);
};
// Filter data based on selected period
const filteredData = data.slice(-Number(period));
// Filter data based on selected period
const filteredData = data.slice(-Number(period));
const chartData = filteredData.map((item) => ({
month: item.periodLabel,
amount: item.amount,
}));
const chartData = filteredData.map((item) => ({
month: item.periodLabel,
amount: item.amount,
}));
const logoPath = resolveLogoPath(card.logo);
const logoPath = resolveLogoPath(card.logo);
return (
<Card>
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
{/* Card logo and name on the left */}
<div className="flex items-center gap-2">
{logoPath ? (
<div className="flex size-10 shrink-0 items-center justify-center">
<Image
src={logoPath}
alt={`Logo ${card.name}`}
width={32}
height={32}
className="rounded object-contain"
/>
</div>
) : (
<div className="flex size-10 shrink-0 items-center justify-center">
<RiBankCard2Line className="size-5 text-muted-foreground" />
</div>
)}
<span className="text-base font-semibold">{card.name}</span>
</div>
return (
<Card>
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
{/* Card logo and name on the left */}
<div className="flex items-center gap-2">
{logoPath ? (
<div className="flex size-10 shrink-0 items-center justify-center">
<Image
src={logoPath}
alt={`Logo ${card.name}`}
width={32}
height={32}
className="rounded object-contain"
/>
</div>
) : (
<div className="flex size-10 shrink-0 items-center justify-center">
<RiBankCard2Line className="size-5 text-muted-foreground" />
</div>
)}
<span className="text-base font-semibold">{card.name}</span>
</div>
{/* Filters on the right */}
<div className="flex items-center gap-1">
{filterOptions.map((option) => (
<Button
key={option.value}
variant={period === option.value ? "default" : "outline"}
size="sm"
onClick={() => setPeriod(option.value)}
className={cn(
"h-7 text-xs",
period === option.value && "pointer-events-none",
)}
>
{option.label}
</Button>
))}
</div>
</div>
</CardHeader>
<CardContent>
<ChartContainer config={chartConfig} className="h-[280px] w-full">
<BarChart
data={chartData}
margin={{ top: 10, right: 10, left: 0, bottom: 0 }}
>
<CartesianGrid strokeDasharray="3 3" vertical={false} />
<XAxis
dataKey="month"
tickLine={false}
axisLine={false}
tickMargin={8}
className="text-xs"
/>
<YAxis
tickLine={false}
axisLine={false}
tickMargin={8}
className="text-xs"
tickFormatter={formatCurrencyCompact}
/>
{limit > 0 && (
<ReferenceLine
y={limit}
stroke="#ef4444"
strokeDasharray="3 3"
label={{
value: "Limite",
position: "right",
className: "text-xs fill-red-500",
}}
/>
)}
<ChartTooltip
content={({ active, payload }) => {
if (!active || !payload || payload.length === 0) {
return null;
}
{/* Filters on the right */}
<div className="flex items-center gap-1">
{filterOptions.map((option) => (
<Button
key={option.value}
variant={period === option.value ? "default" : "outline"}
size="sm"
onClick={() => setPeriod(option.value)}
className={cn(
"h-7 text-xs",
period === option.value && "pointer-events-none",
)}
>
{option.label}
</Button>
))}
</div>
</div>
</CardHeader>
<CardContent>
<ChartContainer config={chartConfig} className="h-[280px] w-full">
<BarChart
data={chartData}
margin={{ top: 10, right: 10, left: 0, bottom: 0 }}
>
<CartesianGrid strokeDasharray="3 3" vertical={false} />
<XAxis
dataKey="month"
tickLine={false}
axisLine={false}
tickMargin={8}
className="text-xs"
/>
<YAxis
tickLine={false}
axisLine={false}
tickMargin={8}
className="text-xs"
tickFormatter={formatCurrencyCompact}
/>
{limit > 0 && (
<ReferenceLine
y={limit}
stroke="#ef4444"
strokeDasharray="3 3"
label={{
value: "Limite",
position: "right",
className: "text-xs fill-red-500",
}}
/>
)}
<ChartTooltip
content={({ active, payload }) => {
if (!active || !payload || payload.length === 0) {
return null;
}
const data = payload[0].payload;
const value = data.amount as number;
const usagePercent = limit > 0 ? (value / limit) * 100 : 0;
const data = payload[0].payload;
const value = data.amount as number;
const usagePercent = limit > 0 ? (value / limit) * 100 : 0;
return (
<div className="rounded-lg border bg-background p-3 shadow-lg">
<div className="mb-2 text-xs font-medium text-muted-foreground">
{data.month}
</div>
<div className="space-y-1">
<div className="flex items-center justify-between gap-4">
<span className="text-xs text-muted-foreground">
Uso
</span>
<span className="text-xs font-medium tabular-nums">
{formatCurrency(value)}
</span>
</div>
{limit > 0 && (
<div className="flex items-center justify-between gap-4">
<span className="text-xs text-muted-foreground">
% do Limite
</span>
<span className="text-xs font-medium tabular-nums">
{usagePercent.toFixed(0)}%
</span>
</div>
)}
</div>
</div>
);
}}
cursor={{ fill: "hsl(var(--muted))", opacity: 0.3 }}
/>
<Bar
dataKey="amount"
fill="var(--primary)"
radius={[4, 4, 0, 0]}
maxBarSize={50}
/>
</BarChart>
</ChartContainer>
</CardContent>
</Card>
);
return (
<div className="rounded-lg border bg-background p-3 shadow-lg">
<div className="mb-2 text-xs font-medium text-muted-foreground">
{data.month}
</div>
<div className="space-y-1">
<div className="flex items-center justify-between gap-4">
<span className="text-xs text-muted-foreground">
Uso
</span>
<span className="text-xs font-medium tabular-nums">
{formatCurrency(value)}
</span>
</div>
{limit > 0 && (
<div className="flex items-center justify-between gap-4">
<span className="text-xs text-muted-foreground">
% do Limite
</span>
<span className="text-xs font-medium tabular-nums">
{usagePercent.toFixed(0)}%
</span>
</div>
)}
</div>
</div>
);
}}
cursor={{ fill: "hsl(var(--muted))", opacity: 0.3 }}
/>
<Bar
dataKey="amount"
fill="var(--primary)"
radius={[4, 4, 0, 0]}
maxBarSize={50}
/>
</BarChart>
</ChartContainer>
</CardContent>
</Card>
);
}

View File

@@ -1,229 +1,229 @@
"use client";
import {
RiArrowDownLine,
RiArrowUpLine,
RiBankCard2Line,
} from "@remixicon/react";
import Image from "next/image";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import type { CartoesReportData } from "@/lib/relatorios/cartoes-report";
import { cn } from "@/lib/utils";
import { title_font } from "@/public/fonts/font_index";
import {
RiArrowDownLine,
RiArrowUpLine,
RiBankCard2Line,
} from "@remixicon/react";
import Image from "next/image";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
type CardsOverviewProps = {
data: CartoesReportData;
data: CartoesReportData;
};
const BRAND_ASSETS: Record<string, string> = {
visa: "/bandeiras/visa.svg",
mastercard: "/bandeiras/mastercard.svg",
amex: "/bandeiras/amex.svg",
american: "/bandeiras/amex.svg",
elo: "/bandeiras/elo.svg",
hipercard: "/bandeiras/hipercard.svg",
hiper: "/bandeiras/hipercard.svg",
visa: "/bandeiras/visa.svg",
mastercard: "/bandeiras/mastercard.svg",
amex: "/bandeiras/amex.svg",
american: "/bandeiras/amex.svg",
elo: "/bandeiras/elo.svg",
hipercard: "/bandeiras/hipercard.svg",
hiper: "/bandeiras/hipercard.svg",
};
const resolveBrandAsset = (brand: string | null) => {
if (!brand) return null;
const normalized = brand.trim().toLowerCase();
const match = (
Object.keys(BRAND_ASSETS) as Array<keyof typeof BRAND_ASSETS>
).find((entry) => normalized.includes(entry));
return match ? BRAND_ASSETS[match] : null;
if (!brand) return null;
const normalized = brand.trim().toLowerCase();
const match = (
Object.keys(BRAND_ASSETS) as Array<keyof typeof BRAND_ASSETS>
).find((entry) => normalized.includes(entry));
return match ? BRAND_ASSETS[match] : null;
};
const resolveLogoPath = (logo: string | null) => {
if (!logo) return null;
if (
logo.startsWith("http://") ||
logo.startsWith("https://") ||
logo.startsWith("data:")
) {
return logo;
}
return logo.startsWith("/") ? logo : `/logos/${logo}`;
if (!logo) return null;
if (
logo.startsWith("http://") ||
logo.startsWith("https://") ||
logo.startsWith("data:")
) {
return logo;
}
return logo.startsWith("/") ? logo : `/logos/${logo}`;
};
export function CardsOverview({ data }: CardsOverviewProps) {
const searchParams = useSearchParams();
const periodoParam = searchParams.get("periodo");
const searchParams = useSearchParams();
const periodoParam = searchParams.get("periodo");
const formatCurrency = (value: number) => {
return new Intl.NumberFormat("pt-BR", {
style: "currency",
currency: "BRL",
minimumFractionDigits: 0,
maximumFractionDigits: 0,
}).format(value);
};
const formatCurrency = (value: number) => {
return new Intl.NumberFormat("pt-BR", {
style: "currency",
currency: "BRL",
minimumFractionDigits: 0,
maximumFractionDigits: 0,
}).format(value);
};
const getUsageColor = (percent: number) => {
if (percent < 50) return "bg-green-500";
if (percent < 80) return "bg-yellow-500";
return "bg-red-500";
};
const getUsageColor = (percent: number) => {
if (percent < 50) return "bg-green-500";
if (percent < 80) return "bg-yellow-500";
return "bg-red-500";
};
const buildUrl = (cardId: string) => {
const params = new URLSearchParams();
if (periodoParam) params.set("periodo", periodoParam);
params.set("cartao", cardId);
return `/relatorios/cartoes?${params.toString()}`;
};
const buildUrl = (cardId: string) => {
const params = new URLSearchParams();
if (periodoParam) params.set("periodo", periodoParam);
params.set("cartao", cardId);
return `/relatorios/cartoes?${params.toString()}`;
};
if (data.cards.length === 0) {
return (
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-base font-bold flex items-center gap-2">
<RiBankCard2Line className="size-4" />
Resumo dos Cartões
</CardTitle>
</CardHeader>
<CardContent>
<div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
<RiBankCard2Line className="size-8 mb-2" />
<p className="text-sm">Nenhum cartão ativo encontrado</p>
</div>
</CardContent>
</Card>
);
}
if (data.cards.length === 0) {
return (
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-base font-bold flex items-center gap-2">
<RiBankCard2Line className="size-4" />
Resumo dos Cartões
</CardTitle>
</CardHeader>
<CardContent>
<div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
<RiBankCard2Line className="size-8 mb-2" />
<p className="text-sm">Nenhum cartão ativo encontrado</p>
</div>
</CardContent>
</Card>
);
}
return (
<Card>
<CardHeader className="pb-2">
<CardTitle
className={`${title_font.className} flex items-center gap-1.5 text-base`}
>
<RiBankCard2Line className="size-4 text-primary" />
Resumo dos Cartões
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid gap-3 sm:grid-cols-3">
<div className="p-3 rounded-lg border bg-muted/30">
<p className="text-xs text-muted-foreground">Limite Total</p>
<p className="text-lg font-semibold">
{formatCurrency(data.totalLimit)}
</p>
</div>
<div className="p-3 rounded-lg border bg-muted/30">
<p className="text-xs text-muted-foreground">Uso Total</p>
<p className="text-lg font-semibold">
{formatCurrency(data.totalUsage)}
</p>
</div>
<div className="p-3 rounded-lg border bg-muted/30">
<p className="text-xs text-muted-foreground">Utilização</p>
<p className="text-lg font-semibold">
{data.totalUsagePercent.toFixed(0)}%
</p>
</div>
</div>
return (
<Card>
<CardHeader className="pb-2">
<CardTitle
className={`${title_font.className} flex items-center gap-1.5 text-base`}
>
<RiBankCard2Line className="size-4 text-primary" />
Resumo dos Cartões
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid gap-3 sm:grid-cols-3">
<div className="p-3 rounded-lg border bg-muted/30">
<p className="text-xs text-muted-foreground">Limite Total</p>
<p className="text-lg font-semibold">
{formatCurrency(data.totalLimit)}
</p>
</div>
<div className="p-3 rounded-lg border bg-muted/30">
<p className="text-xs text-muted-foreground">Uso Total</p>
<p className="text-lg font-semibold">
{formatCurrency(data.totalUsage)}
</p>
</div>
<div className="p-3 rounded-lg border bg-muted/30">
<p className="text-xs text-muted-foreground">Utilização</p>
<p className="text-lg font-semibold">
{data.totalUsagePercent.toFixed(0)}%
</p>
</div>
</div>
<div className="flex flex-col">
{data.cards.map((card) => {
const logoPath = resolveLogoPath(card.logo);
const brandAsset = resolveBrandAsset(card.brand);
<div className="flex flex-col">
{data.cards.map((card) => {
const logoPath = resolveLogoPath(card.logo);
const brandAsset = resolveBrandAsset(card.brand);
return (
<Link
key={card.id}
href={buildUrl(card.id)}
className={cn(
"flex flex-col py-2 border-b border-dashed last:border-0 transition-colors hover:bg-muted/50",
data.selectedCard?.card.id === card.id && "bg-muted/30",
)}
>
<div className="flex items-center justify-between gap-3">
<div className="flex min-w-0 flex-1 items-center gap-2">
{/* Logo container - size-10 like expenses-by-category */}
<div className="flex size-10 shrink-0 items-center justify-center">
{logoPath ? (
<Image
src={logoPath}
alt={`Logo ${card.name}`}
width={28}
height={28}
className="rounded object-contain"
/>
) : (
<RiBankCard2Line className="size-4 text-muted-foreground" />
)}
</div>
return (
<Link
key={card.id}
href={buildUrl(card.id)}
className={cn(
"flex flex-col py-2 border-b border-dashed last:border-0 transition-colors hover:bg-muted/50",
data.selectedCard?.card.id === card.id && "bg-muted/30",
)}
>
<div className="flex items-center justify-between gap-3">
<div className="flex min-w-0 flex-1 items-center gap-2">
{/* Logo container - size-10 like expenses-by-category */}
<div className="flex size-10 shrink-0 items-center justify-center">
{logoPath ? (
<Image
src={logoPath}
alt={`Logo ${card.name}`}
width={28}
height={28}
className="rounded object-contain"
/>
) : (
<RiBankCard2Line className="size-4 text-muted-foreground" />
)}
</div>
{/* Name and brand */}
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="text-sm font-medium truncate">
{card.name}
</span>
{brandAsset && (
<Image
src={brandAsset}
alt={`Bandeira ${card.brand}`}
width={24}
height={16}
className="h-2.5 w-auto shrink-0"
/>
)}
</div>
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span>
{formatCurrency(card.currentUsage)} /{" "}
{formatCurrency(card.limit)}
</span>
</div>
</div>
</div>
{/* Name and brand */}
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="text-sm font-medium truncate">
{card.name}
</span>
{brandAsset && (
<Image
src={brandAsset}
alt={`Bandeira ${card.brand}`}
width={24}
height={16}
className="h-2.5 w-auto shrink-0"
/>
)}
</div>
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span>
{formatCurrency(card.currentUsage)} /{" "}
{formatCurrency(card.limit)}
</span>
</div>
</div>
</div>
{/* Trend and percentage */}
<div className="flex shrink-0 flex-col items-end gap-0.5">
<span className="text-sm font-medium">
{card.usagePercent.toFixed(0)}%
</span>
<div className="flex items-center gap-1">
{card.trend === "up" && (
<RiArrowUpLine className="size-3 text-red-500" />
)}
{card.trend === "down" && (
<RiArrowDownLine className="size-3 text-green-500" />
)}
<span
className={cn(
"text-xs",
card.trend === "up" && "text-red-500",
card.trend === "down" && "text-green-500",
card.trend === "stable" && "text-muted-foreground",
)}
>
{card.changePercent > 0 ? "+" : ""}
{card.changePercent.toFixed(0)}%
</span>
</div>
</div>
</div>
{/* Trend and percentage */}
<div className="flex shrink-0 flex-col items-end gap-0.5">
<span className="text-sm font-medium">
{card.usagePercent.toFixed(0)}%
</span>
<div className="flex items-center gap-1">
{card.trend === "up" && (
<RiArrowUpLine className="size-3 text-red-500" />
)}
{card.trend === "down" && (
<RiArrowDownLine className="size-3 text-green-500" />
)}
<span
className={cn(
"text-xs",
card.trend === "up" && "text-red-500",
card.trend === "down" && "text-green-500",
card.trend === "stable" && "text-muted-foreground",
)}
>
{card.changePercent > 0 ? "+" : ""}
{card.changePercent.toFixed(0)}%
</span>
</div>
</div>
</div>
{/* Progress bar - aligned with content */}
<div className="ml-12 mt-1.5">
<Progress
value={Math.min(card.usagePercent, 100)}
className={cn(
"h-1.5",
`[&>div]:${getUsageColor(card.usagePercent)}`,
)}
/>
</div>
</Link>
);
})}
</div>
</CardContent>
</Card>
);
{/* Progress bar - aligned with content */}
<div className="ml-12 mt-1.5">
<Progress
value={Math.min(card.usagePercent, 100)}
className={cn(
"h-1.5",
`[&>div]:${getUsageColor(card.usagePercent)}`,
)}
/>
</div>
</Link>
);
})}
</div>
</CardContent>
</Card>
);
}

View File

@@ -1,46 +1,46 @@
"use client";
import { RiArrowDownLine, RiArrowUpLine } from "@remixicon/react";
import { formatCurrency, formatPercentageChange } from "@/lib/relatorios/utils";
import { cn } from "@/lib/utils/ui";
import { RiArrowDownLine, RiArrowUpLine } from "@remixicon/react";
interface CategoryCellProps {
value: number;
previousValue: number;
categoryType: "despesa" | "receita";
isFirstMonth: boolean;
value: number;
previousValue: number;
categoryType: "despesa" | "receita";
isFirstMonth: boolean;
}
export function CategoryCell({
value,
previousValue,
categoryType,
isFirstMonth,
value,
previousValue,
categoryType,
isFirstMonth,
}: CategoryCellProps) {
const percentageChange =
!isFirstMonth && previousValue !== 0
? ((value - previousValue) / previousValue) * 100
: null;
const percentageChange =
!isFirstMonth && previousValue !== 0
? ((value - previousValue) / previousValue) * 100
: null;
const isIncrease = percentageChange !== null && percentageChange > 0;
const isDecrease = percentageChange !== null && percentageChange < 0;
const isIncrease = percentageChange !== null && percentageChange > 0;
const isDecrease = percentageChange !== null && percentageChange < 0;
return (
<div className="flex flex-col items-end gap-0.5 min-h-9">
<span className="font-medium">{formatCurrency(value)}</span>
{!isFirstMonth && percentageChange !== null && (
<div
className={cn(
"flex items-center gap-0.5 text-xs",
isIncrease && "text-red-600 dark:text-red-400",
isDecrease && "text-green-600 dark:text-green-400"
)}
>
{isIncrease && <RiArrowUpLine className="h-3 w-3" />}
{isDecrease && <RiArrowDownLine className="h-3 w-3" />}
<span>{formatPercentageChange(percentageChange)}</span>
</div>
)}
</div>
);
return (
<div className="flex flex-col items-end gap-0.5 min-h-9">
<span className="font-medium">{formatCurrency(value)}</span>
{!isFirstMonth && percentageChange !== null && (
<div
className={cn(
"flex items-center gap-0.5 text-xs",
isIncrease && "text-red-600 dark:text-red-400",
isDecrease && "text-green-600 dark:text-green-400",
)}
>
{isIncrease && <RiArrowUpLine className="h-3 w-3" />}
{isDecrease && <RiArrowDownLine className="h-3 w-3" />}
<span>{formatPercentageChange(percentageChange)}</span>
</div>
)}
</div>
);
}

View File

@@ -1,63 +1,63 @@
"use client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { TypeBadge } from "@/components/type-badge";
import { getIconComponent } from "@/lib/utils/icons";
import { formatPeriodLabel, formatCurrency } from "@/lib/relatorios/utils";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import type { CategoryReportData } from "@/lib/relatorios/types";
import { formatCurrency, formatPeriodLabel } from "@/lib/relatorios/utils";
import { getIconComponent } from "@/lib/utils/icons";
import { CategoryCell } from "./category-cell";
interface CategoryReportCardsProps {
data: CategoryReportData;
data: CategoryReportData;
}
export function CategoryReportCards({ data }: CategoryReportCardsProps) {
const { categories, periods } = data;
const { categories, periods } = data;
return (
<div className="md:hidden space-y-4">
{categories.map((category) => {
const Icon = category.icon ? getIconComponent(category.icon) : null;
return (
<div className="md:hidden space-y-4">
{categories.map((category) => {
const Icon = category.icon ? getIconComponent(category.icon) : null;
return (
<Card key={category.categoryId}>
<CardHeader>
<CardTitle className="flex items-center gap-2">
{Icon && <Icon className="h-5 w-5 shrink-0" />}
<span className="flex-1 truncate">{category.name}</span>
<TypeBadge type={category.type} />
</CardTitle>
</CardHeader>
<CardContent className="space-y-2">
{periods.map((period, periodIndex) => {
const monthData = category.monthlyData.get(period);
const isFirstMonth = periodIndex === 0;
return (
<Card key={category.categoryId}>
<CardHeader>
<CardTitle className="flex items-center gap-2">
{Icon && <Icon className="h-5 w-5 shrink-0" />}
<span className="flex-1 truncate">{category.name}</span>
<TypeBadge type={category.type} />
</CardTitle>
</CardHeader>
<CardContent className="space-y-2">
{periods.map((period, periodIndex) => {
const monthData = category.monthlyData.get(period);
const isFirstMonth = periodIndex === 0;
return (
<div
key={period}
className="flex items-center justify-between py-2 border-b last:border-b-0"
>
<span className="text-sm text-muted-foreground">
{formatPeriodLabel(period)}
</span>
<CategoryCell
value={monthData?.amount ?? 0}
previousValue={monthData?.previousAmount ?? 0}
categoryType={category.type}
isFirstMonth={isFirstMonth}
/>
</div>
);
})}
<div className="flex items-center justify-between pt-2 font-semibold">
<span>Total</span>
<span>{formatCurrency(category.total)}</span>
</div>
</CardContent>
</Card>
);
})}
</div>
);
return (
<div
key={period}
className="flex items-center justify-between py-2 border-b last:border-b-0"
>
<span className="text-sm text-muted-foreground">
{formatPeriodLabel(period)}
</span>
<CategoryCell
value={monthData?.amount ?? 0}
previousValue={monthData?.previousAmount ?? 0}
categoryType={category.type}
isFirstMonth={isFirstMonth}
/>
</div>
);
})}
<div className="flex items-center justify-between pt-2 font-semibold">
<span>Total</span>
<span>{formatCurrency(category.total)}</span>
</div>
</CardContent>
</Card>
);
})}
</div>
);
}

View File

@@ -1,213 +1,215 @@
"use client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { EmptyState } from "@/components/empty-state";
import { RiPieChartLine } from "@remixicon/react";
import type { CategoryChartData } from "@/lib/relatorios/fetch-category-chart-data";
import {
Area,
AreaChart,
CartesianGrid,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import { currencyFormatter } from "@/lib/lancamentos/formatting-helpers";
import { useMemo } from "react";
import {
Area,
AreaChart,
CartesianGrid,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import { EmptyState } from "@/components/empty-state";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { currencyFormatter } from "@/lib/lancamentos/formatting-helpers";
import type { CategoryChartData } from "@/lib/relatorios/fetch-category-chart-data";
interface CategoryReportChartProps {
data: CategoryChartData;
data: CategoryChartData;
}
const CHART_COLORS = [
"#ef4444", // red-500
"#3b82f6", // blue-500
"#10b981", // emerald-500
"#f59e0b", // amber-500
"#8b5cf6", // violet-500
"#ec4899", // pink-500
"#14b8a6", // teal-500
"#f97316", // orange-500
"#06b6d4", // cyan-500
"#84cc16", // lime-500
"#ef4444", // red-500
"#3b82f6", // blue-500
"#10b981", // emerald-500
"#f59e0b", // amber-500
"#8b5cf6", // violet-500
"#ec4899", // pink-500
"#14b8a6", // teal-500
"#f97316", // orange-500
"#06b6d4", // cyan-500
"#84cc16", // lime-500
];
const MAX_CATEGORIES_IN_CHART = 15;
export function CategoryReportChart({ data }: CategoryReportChartProps) {
const { chartData, categories } = data;
const { chartData, categories } = data;
// Check if there's no data
if (categories.length === 0 || chartData.length === 0) {
return (
<EmptyState
title="Nenhum dado disponível"
description="Não há transações no período selecionado para as categorias filtradas."
media={<RiPieChartLine className="h-12 w-12" />}
mediaVariant="icon"
/>
);
}
// Check if there's no data
if (categories.length === 0 || chartData.length === 0) {
return (
<EmptyState
title="Nenhum dado disponível"
description="Não há transações no período selecionado para as categorias filtradas."
media={<RiPieChartLine className="h-12 w-12" />}
mediaVariant="icon"
/>
);
}
// Get top 10 categories by total spending
const { topCategories, filteredChartData } = useMemo(() => {
// Calculate total for each category across all periods
const categoriesWithTotal = categories.map((category) => {
const total = chartData.reduce((sum, dataPoint) => {
const value = dataPoint[category.name];
return sum + (typeof value === "number" ? value : 0);
}, 0);
// Get top 10 categories by total spending
const { topCategories, filteredChartData } = useMemo(() => {
// Calculate total for each category across all periods
const categoriesWithTotal = categories.map((category) => {
const total = chartData.reduce((sum, dataPoint) => {
const value = dataPoint[category.name];
return sum + (typeof value === "number" ? value : 0);
}, 0);
return { ...category, total };
});
return { ...category, total };
});
// Sort by total (descending) and take top 10
const sorted = categoriesWithTotal
.sort((a, b) => b.total - a.total)
.slice(0, MAX_CATEGORIES_IN_CHART);
// Sort by total (descending) and take top 10
const sorted = categoriesWithTotal
.sort((a, b) => b.total - a.total)
.slice(0, MAX_CATEGORIES_IN_CHART);
// Filter chartData to include only top categories
const topCategoryNames = new Set(sorted.map((cat) => cat.name));
const filtered = chartData.map((dataPoint) => {
const filteredPoint: { month: string; [key: string]: number | string } = {
month: dataPoint.month,
};
// Filter chartData to include only top categories
const _topCategoryNames = new Set(sorted.map((cat) => cat.name));
const filtered = chartData.map((dataPoint) => {
const filteredPoint: { month: string; [key: string]: number | string } = {
month: dataPoint.month,
};
// Only include data for top categories
for (const cat of sorted) {
if (dataPoint[cat.name] !== undefined) {
filteredPoint[cat.name] = dataPoint[cat.name];
}
}
// Only include data for top categories
for (const cat of sorted) {
if (dataPoint[cat.name] !== undefined) {
filteredPoint[cat.name] = dataPoint[cat.name];
}
}
return filteredPoint;
});
return filteredPoint;
});
return { topCategories: sorted, filteredChartData: filtered };
}, [categories, chartData]);
return { topCategories: sorted, filteredChartData: filtered };
}, [categories, chartData]);
return (
<Card>
<CardHeader>
<CardTitle>Evolução por Categoria - Top {topCategories.length}</CardTitle>
</CardHeader>
<CardContent>
<div className="h-[400px] w-full">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={filteredChartData}>
<defs>
{topCategories.map((category, index) => {
const color = CHART_COLORS[index % CHART_COLORS.length];
return (
<linearGradient
key={category.id}
id={`gradient-${category.id}`}
x1="0"
y1="0"
x2="0"
y2="1"
>
<stop offset="5%" stopColor={color} stopOpacity={0.3} />
<stop offset="95%" stopColor={color} stopOpacity={0} />
</linearGradient>
);
})}
</defs>
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
<XAxis
dataKey="month"
className="text-xs"
tick={{ fill: "hsl(var(--muted-foreground))" }}
/>
<YAxis
className="text-xs"
tick={{ fill: "hsl(var(--muted-foreground))" }}
tickFormatter={(value) => {
if (value >= 1000) {
return `${(value / 1000).toFixed(0)}k`;
}
return value.toString();
}}
/>
<Tooltip
content={({ active, payload }) => {
if (!active || !payload || payload.length === 0) {
return null;
}
return (
<Card>
<CardHeader>
<CardTitle>
Evolução por Categoria - Top {topCategories.length}
</CardTitle>
</CardHeader>
<CardContent>
<div className="h-[400px] w-full">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={filteredChartData}>
<defs>
{topCategories.map((category, index) => {
const color = CHART_COLORS[index % CHART_COLORS.length];
return (
<linearGradient
key={category.id}
id={`gradient-${category.id}`}
x1="0"
y1="0"
x2="0"
y2="1"
>
<stop offset="5%" stopColor={color} stopOpacity={0.3} />
<stop offset="95%" stopColor={color} stopOpacity={0} />
</linearGradient>
);
})}
</defs>
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
<XAxis
dataKey="month"
className="text-xs"
tick={{ fill: "hsl(var(--muted-foreground))" }}
/>
<YAxis
className="text-xs"
tick={{ fill: "hsl(var(--muted-foreground))" }}
tickFormatter={(value) => {
if (value >= 1000) {
return `${(value / 1000).toFixed(0)}k`;
}
return value.toString();
}}
/>
<Tooltip
content={({ active, payload }) => {
if (!active || !payload || payload.length === 0) {
return null;
}
return (
<div className="rounded-lg border bg-background p-3 shadow-md">
<div className="mb-2 font-semibold">
{payload[0]?.payload?.month}
</div>
<div className="space-y-1">
{payload.map((entry, index) => {
if (entry.dataKey === "month") return null;
return (
<div className="rounded-lg border bg-background p-3 shadow-md">
<div className="mb-2 font-semibold">
{payload[0]?.payload?.month}
</div>
<div className="space-y-1">
{payload.map((entry, index) => {
if (entry.dataKey === "month") return null;
return (
<div
key={index}
className="flex items-center justify-between gap-4 text-sm"
>
<div className="flex items-center gap-2">
<div
className="h-2 w-2 rounded-full"
style={{ backgroundColor: entry.color }}
/>
<span className="text-muted-foreground">
{entry.name}
</span>
</div>
<span className="font-medium">
{currencyFormatter.format(
Number(entry.value) || 0
)}
</span>
</div>
);
})}
</div>
</div>
);
}}
/>
{topCategories.map((category, index) => {
const color = CHART_COLORS[index % CHART_COLORS.length];
return (
<Area
key={category.id}
type="monotone"
dataKey={category.name}
stroke={color}
strokeWidth={2}
fill={`url(#gradient-${category.id})`}
fillOpacity={1}
/>
);
})}
</AreaChart>
</ResponsiveContainer>
</div>
return (
<div
key={index}
className="flex items-center justify-between gap-4 text-sm"
>
<div className="flex items-center gap-2">
<div
className="h-2 w-2 rounded-full"
style={{ backgroundColor: entry.color }}
/>
<span className="text-muted-foreground">
{entry.name}
</span>
</div>
<span className="font-medium">
{currencyFormatter.format(
Number(entry.value) || 0,
)}
</span>
</div>
);
})}
</div>
</div>
);
}}
/>
{topCategories.map((category, index) => {
const color = CHART_COLORS[index % CHART_COLORS.length];
return (
<Area
key={category.id}
type="monotone"
dataKey={category.name}
stroke={color}
strokeWidth={2}
fill={`url(#gradient-${category.id})`}
fillOpacity={1}
/>
);
})}
</AreaChart>
</ResponsiveContainer>
</div>
{/* Legend */}
<div className="mt-4 flex flex-wrap gap-4">
{topCategories.map((category, index) => {
const color = CHART_COLORS[index % CHART_COLORS.length];
return (
<div key={category.id} className="flex items-center gap-2">
<div
className="h-3 w-3 rounded-full"
style={{ backgroundColor: color }}
/>
<span className="text-sm text-muted-foreground">
{category.name}
</span>
</div>
);
})}
</div>
</CardContent>
</Card>
);
{/* Legend */}
<div className="mt-4 flex flex-wrap gap-4">
{topCategories.map((category, index) => {
const color = CHART_COLORS[index % CHART_COLORS.length];
return (
<div key={category.id} className="flex items-center gap-2">
<div
className="h-3 w-3 rounded-full"
style={{ backgroundColor: color }}
/>
<span className="text-sm text-muted-foreground">
{category.name}
</span>
</div>
);
})}
</div>
</CardContent>
</Card>
);
}

View File

@@ -1,348 +1,348 @@
"use client";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import type { CategoryReportData } from "@/lib/relatorios/types";
import type { FilterState } from "./types";
import {
formatPeriodLabel,
formatCurrency,
formatPercentageChange,
} from "@/lib/relatorios/utils";
import {
RiDownloadLine,
RiFileExcelLine,
RiFilePdfLine,
RiFileTextLine,
RiDownloadLine,
RiFileExcelLine,
RiFilePdfLine,
RiFileTextLine,
} from "@remixicon/react";
import { toast } from "sonner";
import { useState } from "react";
import jsPDF from "jspdf";
import autoTable from "jspdf-autotable";
import { useState } from "react";
import { toast } from "sonner";
import * as XLSX from "xlsx";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import type { CategoryReportData } from "@/lib/relatorios/types";
import {
formatCurrency,
formatPercentageChange,
formatPeriodLabel,
} from "@/lib/relatorios/utils";
import type { FilterState } from "./types";
interface CategoryReportExportProps {
data: CategoryReportData;
filters: FilterState;
data: CategoryReportData;
filters: FilterState;
}
export function CategoryReportExport({
data,
filters,
data,
filters,
}: CategoryReportExportProps) {
const [isExporting, setIsExporting] = useState(false);
const [isExporting, setIsExporting] = useState(false);
const getFileName = (extension: string) => {
const start = filters.startPeriod;
const end = filters.endPeriod;
return `relatorio-categorias-${start}-${end}.${extension}`;
};
const getFileName = (extension: string) => {
const start = filters.startPeriod;
const end = filters.endPeriod;
return `relatorio-categorias-${start}-${end}.${extension}`;
};
const exportToCSV = () => {
try {
setIsExporting(true);
const exportToCSV = () => {
try {
setIsExporting(true);
// Build CSV content
const headers = [
"Categoria",
...data.periods.map(formatPeriodLabel),
"Total",
];
const rows: string[][] = [];
// Build CSV content
const headers = [
"Categoria",
...data.periods.map(formatPeriodLabel),
"Total",
];
const rows: string[][] = [];
// Add category rows
data.categories.forEach((category) => {
const row: string[] = [category.name];
// Add category rows
data.categories.forEach((category) => {
const row: string[] = [category.name];
data.periods.forEach((period, periodIndex) => {
const monthData = category.monthlyData.get(period);
const value = monthData?.amount ?? 0;
const percentageChange = monthData?.percentageChange;
const isFirstMonth = periodIndex === 0;
data.periods.forEach((period, periodIndex) => {
const monthData = category.monthlyData.get(period);
const value = monthData?.amount ?? 0;
const percentageChange = monthData?.percentageChange;
const isFirstMonth = periodIndex === 0;
let cellValue = formatCurrency(value);
let cellValue = formatCurrency(value);
// Add indicator as text
if (!isFirstMonth && percentageChange != null) {
const arrow = percentageChange > 0 ? "↑" : "↓";
cellValue += ` (${arrow}${formatPercentageChange(
percentageChange
)})`;
}
// Add indicator as text
if (!isFirstMonth && percentageChange != null) {
const arrow = percentageChange > 0 ? "↑" : "↓";
cellValue += ` (${arrow}${formatPercentageChange(
percentageChange,
)})`;
}
row.push(cellValue);
});
row.push(cellValue);
});
row.push(formatCurrency(category.total));
rows.push(row);
});
row.push(formatCurrency(category.total));
rows.push(row);
});
// Add totals row
const totalsRow = ["Total Geral"];
data.periods.forEach((period) => {
totalsRow.push(formatCurrency(data.totals.get(period) ?? 0));
});
totalsRow.push(formatCurrency(data.grandTotal));
rows.push(totalsRow);
// Add totals row
const totalsRow = ["Total Geral"];
data.periods.forEach((period) => {
totalsRow.push(formatCurrency(data.totals.get(period) ?? 0));
});
totalsRow.push(formatCurrency(data.grandTotal));
rows.push(totalsRow);
// Generate CSV string
const csvContent = [
headers.join(","),
...rows.map((row) => row.map((cell) => `"${cell}"`).join(",")),
].join("\n");
// Generate CSV string
const csvContent = [
headers.join(","),
...rows.map((row) => row.map((cell) => `"${cell}"`).join(",")),
].join("\n");
// Create blob and download
const blob = new Blob(["\uFEFF" + csvContent], {
type: "text/csv;charset=utf-8;",
});
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = getFileName("csv");
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
// Create blob and download
const blob = new Blob([`\uFEFF${csvContent}`], {
type: "text/csv;charset=utf-8;",
});
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = getFileName("csv");
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
toast.success("Relatório exportado em CSV com sucesso!");
} catch (error) {
console.error("Error exporting to CSV:", error);
toast.error("Erro ao exportar relatório em CSV");
} finally {
setIsExporting(false);
}
};
toast.success("Relatório exportado em CSV com sucesso!");
} catch (error) {
console.error("Error exporting to CSV:", error);
toast.error("Erro ao exportar relatório em CSV");
} finally {
setIsExporting(false);
}
};
const exportToExcel = () => {
try {
setIsExporting(true);
const exportToExcel = () => {
try {
setIsExporting(true);
// Build data array
const headers = [
"Categoria",
...data.periods.map(formatPeriodLabel),
"Total",
];
const rows: (string | number)[][] = [];
// Build data array
const headers = [
"Categoria",
...data.periods.map(formatPeriodLabel),
"Total",
];
const rows: (string | number)[][] = [];
// Add category rows
data.categories.forEach((category) => {
const row: (string | number)[] = [category.name];
// Add category rows
data.categories.forEach((category) => {
const row: (string | number)[] = [category.name];
data.periods.forEach((period, periodIndex) => {
const monthData = category.monthlyData.get(period);
const value = monthData?.amount ?? 0;
const percentageChange = monthData?.percentageChange;
const isFirstMonth = periodIndex === 0;
data.periods.forEach((period, periodIndex) => {
const monthData = category.monthlyData.get(period);
const value = monthData?.amount ?? 0;
const percentageChange = monthData?.percentageChange;
const isFirstMonth = periodIndex === 0;
let cellValue: string = formatCurrency(value);
let cellValue: string = formatCurrency(value);
// Add indicator as text
if (!isFirstMonth && percentageChange != null) {
const arrow = percentageChange > 0 ? "↑" : "↓";
cellValue += ` (${arrow}${formatPercentageChange(
percentageChange
)})`;
}
// Add indicator as text
if (!isFirstMonth && percentageChange != null) {
const arrow = percentageChange > 0 ? "↑" : "↓";
cellValue += ` (${arrow}${formatPercentageChange(
percentageChange,
)})`;
}
row.push(cellValue);
});
row.push(cellValue);
});
row.push(formatCurrency(category.total));
rows.push(row);
});
row.push(formatCurrency(category.total));
rows.push(row);
});
// Add totals row
const totalsRow: (string | number)[] = ["Total Geral"];
data.periods.forEach((period) => {
totalsRow.push(formatCurrency(data.totals.get(period) ?? 0));
});
totalsRow.push(formatCurrency(data.grandTotal));
rows.push(totalsRow);
// Add totals row
const totalsRow: (string | number)[] = ["Total Geral"];
data.periods.forEach((period) => {
totalsRow.push(formatCurrency(data.totals.get(period) ?? 0));
});
totalsRow.push(formatCurrency(data.grandTotal));
rows.push(totalsRow);
// Create worksheet
const ws = XLSX.utils.aoa_to_sheet([headers, ...rows]);
// Create worksheet
const ws = XLSX.utils.aoa_to_sheet([headers, ...rows]);
// Set column widths
ws["!cols"] = [
{ wch: 20 }, // Categoria
...data.periods.map(() => ({ wch: 15 })), // Periods
{ wch: 15 }, // Total
];
// Set column widths
ws["!cols"] = [
{ wch: 20 }, // Categoria
...data.periods.map(() => ({ wch: 15 })), // Periods
{ wch: 15 }, // Total
];
// Create workbook and download
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Relatório de Categorias");
XLSX.writeFile(wb, getFileName("xlsx"));
// Create workbook and download
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Relatório de Categorias");
XLSX.writeFile(wb, getFileName("xlsx"));
toast.success("Relatório exportado em Excel com sucesso!");
} catch (error) {
console.error("Error exporting to Excel:", error);
toast.error("Erro ao exportar relatório em Excel");
} finally {
setIsExporting(false);
}
};
toast.success("Relatório exportado em Excel com sucesso!");
} catch (error) {
console.error("Error exporting to Excel:", error);
toast.error("Erro ao exportar relatório em Excel");
} finally {
setIsExporting(false);
}
};
const exportToPDF = () => {
try {
setIsExporting(true);
const exportToPDF = () => {
try {
setIsExporting(true);
// Create PDF
const doc = new jsPDF({ orientation: "landscape" });
// Create PDF
const doc = new jsPDF({ orientation: "landscape" });
// Add header
doc.setFontSize(16);
doc.text("Relatório de Categorias por Período", 14, 15);
// Add header
doc.setFontSize(16);
doc.text("Relatório de Categorias por Período", 14, 15);
doc.setFontSize(10);
doc.text(
`Período: ${formatPeriodLabel(
filters.startPeriod
)} - ${formatPeriodLabel(filters.endPeriod)}`,
14,
22
);
doc.text(`Gerado em: ${new Date().toLocaleDateString("pt-BR")}`, 14, 27);
doc.setFontSize(10);
doc.text(
`Período: ${formatPeriodLabel(
filters.startPeriod,
)} - ${formatPeriodLabel(filters.endPeriod)}`,
14,
22,
);
doc.text(`Gerado em: ${new Date().toLocaleDateString("pt-BR")}`, 14, 27);
// Build table data
const headers = [
["Categoria", ...data.periods.map(formatPeriodLabel), "Total"],
];
const body: string[][] = [];
// Build table data
const headers = [
["Categoria", ...data.periods.map(formatPeriodLabel), "Total"],
];
const body: string[][] = [];
// Add category rows
data.categories.forEach((category) => {
const row: string[] = [category.name];
// Add category rows
data.categories.forEach((category) => {
const row: string[] = [category.name];
data.periods.forEach((period, periodIndex) => {
const monthData = category.monthlyData.get(period);
const value = monthData?.amount ?? 0;
const percentageChange = monthData?.percentageChange;
const isFirstMonth = periodIndex === 0;
data.periods.forEach((period, periodIndex) => {
const monthData = category.monthlyData.get(period);
const value = monthData?.amount ?? 0;
const percentageChange = monthData?.percentageChange;
const isFirstMonth = periodIndex === 0;
let cellValue = formatCurrency(value);
let cellValue = formatCurrency(value);
// Add indicator as text
if (!isFirstMonth && percentageChange != null) {
const arrow = percentageChange > 0 ? "↑" : "↓";
cellValue += `\n(${arrow}${formatPercentageChange(
percentageChange
)})`;
}
// Add indicator as text
if (!isFirstMonth && percentageChange != null) {
const arrow = percentageChange > 0 ? "↑" : "↓";
cellValue += `\n(${arrow}${formatPercentageChange(
percentageChange,
)})`;
}
row.push(cellValue);
});
row.push(cellValue);
});
row.push(formatCurrency(category.total));
body.push(row);
});
row.push(formatCurrency(category.total));
body.push(row);
});
// Add totals row
const totalsRow = ["Total Geral"];
data.periods.forEach((period) => {
totalsRow.push(formatCurrency(data.totals.get(period) ?? 0));
});
totalsRow.push(formatCurrency(data.grandTotal));
body.push(totalsRow);
// Add totals row
const totalsRow = ["Total Geral"];
data.periods.forEach((period) => {
totalsRow.push(formatCurrency(data.totals.get(period) ?? 0));
});
totalsRow.push(formatCurrency(data.grandTotal));
body.push(totalsRow);
// Generate table with autoTable
autoTable(doc, {
head: headers,
body: body,
startY: 32,
styles: {
fontSize: 8,
cellPadding: 2,
},
headStyles: {
fillColor: [59, 130, 246], // Blue
textColor: 255,
fontStyle: "bold",
},
footStyles: {
fillColor: [229, 231, 235], // Gray
textColor: 0,
fontStyle: "bold",
},
columnStyles: {
0: { cellWidth: 35 }, // Categoria column wider
},
didParseCell: (cellData) => {
// Style totals row
if (
cellData.row.index === body.length - 1 &&
cellData.section === "body"
) {
cellData.cell.styles.fillColor = [243, 244, 246];
cellData.cell.styles.fontStyle = "bold";
}
// Generate table with autoTable
autoTable(doc, {
head: headers,
body: body,
startY: 32,
styles: {
fontSize: 8,
cellPadding: 2,
},
headStyles: {
fillColor: [59, 130, 246], // Blue
textColor: 255,
fontStyle: "bold",
},
footStyles: {
fillColor: [229, 231, 235], // Gray
textColor: 0,
fontStyle: "bold",
},
columnStyles: {
0: { cellWidth: 35 }, // Categoria column wider
},
didParseCell: (cellData) => {
// Style totals row
if (
cellData.row.index === body.length - 1 &&
cellData.section === "body"
) {
cellData.cell.styles.fillColor = [243, 244, 246];
cellData.cell.styles.fontStyle = "bold";
}
// Color coding for category rows (despesa/receita)
if (
cellData.section === "body" &&
cellData.row.index < body.length - 1
) {
const categoryIndex = cellData.row.index;
const category = data.categories[categoryIndex];
// Color coding for category rows (despesa/receita)
if (
cellData.section === "body" &&
cellData.row.index < body.length - 1
) {
const categoryIndex = cellData.row.index;
const category = data.categories[categoryIndex];
if (category && cellData.column.index > 0) {
// Apply subtle background colors
if (category.type === "despesa") {
cellData.cell.styles.textColor = [220, 38, 38]; // Red text
} else if (category.type === "receita") {
cellData.cell.styles.textColor = [22, 163, 74]; // Green text
}
}
}
},
margin: { top: 32 },
});
if (category && cellData.column.index > 0) {
// Apply subtle background colors
if (category.type === "despesa") {
cellData.cell.styles.textColor = [220, 38, 38]; // Red text
} else if (category.type === "receita") {
cellData.cell.styles.textColor = [22, 163, 74]; // Green text
}
}
}
},
margin: { top: 32 },
});
// Save PDF
doc.save(getFileName("pdf"));
// Save PDF
doc.save(getFileName("pdf"));
toast.success("Relatório exportado em PDF com sucesso!");
} catch (error) {
console.error("Error exporting to PDF:", error);
toast.error("Erro ao exportar relatório em PDF");
} finally {
setIsExporting(false);
}
};
toast.success("Relatório exportado em PDF com sucesso!");
} catch (error) {
console.error("Error exporting to PDF:", error);
toast.error("Erro ao exportar relatório em PDF");
} finally {
setIsExporting(false);
}
};
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="outline"
className="text-sm border-dashed"
disabled={isExporting || data.categories.length === 0}
aria-label="Exportar relatório de categorias"
>
<RiDownloadLine className="mr-2 h-4 w-4" aria-hidden="true" />
{isExporting ? "Exportando..." : "Exportar"}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={exportToCSV} disabled={isExporting}>
<RiFileTextLine className="mr-2 h-4 w-4" aria-hidden="true" />
Exportar como CSV
</DropdownMenuItem>
<DropdownMenuItem onClick={exportToExcel} disabled={isExporting}>
<RiFileExcelLine className="mr-2 h-4 w-4" aria-hidden="true" />
Exportar como Excel (.xlsx)
</DropdownMenuItem>
<DropdownMenuItem onClick={exportToPDF} disabled={isExporting}>
<RiFilePdfLine className="mr-2 h-4 w-4" aria-hidden="true" />
Exportar como PDF
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="outline"
className="text-sm border-dashed"
disabled={isExporting || data.categories.length === 0}
aria-label="Exportar relatório de categorias"
>
<RiDownloadLine className="mr-2 h-4 w-4" aria-hidden="true" />
{isExporting ? "Exportando..." : "Exportar"}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={exportToCSV} disabled={isExporting}>
<RiFileTextLine className="mr-2 h-4 w-4" aria-hidden="true" />
Exportar como CSV
</DropdownMenuItem>
<DropdownMenuItem onClick={exportToExcel} disabled={isExporting}>
<RiFileExcelLine className="mr-2 h-4 w-4" aria-hidden="true" />
Exportar como Excel (.xlsx)
</DropdownMenuItem>
<DropdownMenuItem onClick={exportToPDF} disabled={isExporting}>
<RiFilePdfLine className="mr-2 h-4 w-4" aria-hidden="true" />
Exportar como PDF
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}

View File

@@ -1,309 +1,317 @@
"use client";
import { Button } from "@/components/ui/button";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { MonthPicker } from "@/components/ui/monthpicker";
import { validateDateRange } from "@/lib/relatorios/utils";
import { getIconComponent } from "@/lib/utils/icons";
import { cn } from "@/lib/utils/ui";
import { RiCheckLine, RiExpandUpDownLine, RiCalendarLine } from "@remixicon/react";
import { useMemo, useState } from "react";
RiCalendarLine,
RiCheckLine,
RiExpandUpDownLine,
} from "@remixicon/react";
import { format } from "date-fns";
import { ptBR } from "date-fns/locale";
import type { CategoryReportFiltersProps, FilterState } from "./types";
import type { ReactNode } from "react";
import { useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command";
import { MonthPicker } from "@/components/ui/monthpicker";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { validateDateRange } from "@/lib/relatorios/utils";
import { getIconComponent } from "@/lib/utils/icons";
import type { CategoryReportFiltersProps } from "./types";
/**
* Category Report Filters Component
* Provides filters for categories selection and date range
*/
export function CategoryReportFilters({
categories,
filters,
onFiltersChange,
isLoading = false,
exportButton,
categories,
filters,
onFiltersChange,
isLoading = false,
exportButton,
}: CategoryReportFiltersProps & { exportButton?: ReactNode }) {
const [open, setOpen] = useState(false);
const [searchValue, setSearchValue] = useState("");
const [startMonthOpen, setStartMonthOpen] = useState(false);
const [endMonthOpen, setEndMonthOpen] = useState(false);
const [open, setOpen] = useState(false);
const [searchValue, setSearchValue] = useState("");
const [startMonthOpen, setStartMonthOpen] = useState(false);
const [endMonthOpen, setEndMonthOpen] = useState(false);
// Convert period string (YYYY-MM) to Date object
const periodToDate = (period: string): Date => {
const [year, month] = period.split("-").map(Number);
return new Date(year, month - 1, 1);
};
// Convert period string (YYYY-MM) to Date object
const periodToDate = (period: string): Date => {
const [year, month] = period.split("-").map(Number);
return new Date(year, month - 1, 1);
};
// Convert Date object to period string (YYYY-MM)
const dateToPeriod = (date: Date): string => {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
return `${year}-${month}`;
};
// Convert Date object to period string (YYYY-MM)
const dateToPeriod = (date: Date): string => {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
return `${year}-${month}`;
};
// Format date for display
const formatMonthYear = (period: string): string => {
const date = periodToDate(period);
return format(date, "MMM/yyyy", { locale: ptBR });
};
// Format date for display
const formatMonthYear = (period: string): string => {
const date = periodToDate(period);
return format(date, "MMM/yyyy", { locale: ptBR });
};
// Filter categories by search
const filteredCategories = useMemo(() => {
if (!searchValue) return categories;
const search = searchValue.toLowerCase();
return categories.filter((cat) =>
cat.name.toLowerCase().includes(search)
);
}, [categories, searchValue]);
// Filter categories by search
const filteredCategories = useMemo(() => {
if (!searchValue) return categories;
const search = searchValue.toLowerCase();
return categories.filter((cat) => cat.name.toLowerCase().includes(search));
}, [categories, searchValue]);
// Get selected categories for display
const selectedCategories = useMemo(() => {
if (filters.selectedCategories.length === 0) return [];
return categories.filter((cat) =>
filters.selectedCategories.includes(cat.id)
);
}, [categories, filters.selectedCategories]);
// Get selected categories for display
const selectedCategories = useMemo(() => {
if (filters.selectedCategories.length === 0) return [];
return categories.filter((cat) =>
filters.selectedCategories.includes(cat.id),
);
}, [categories, filters.selectedCategories]);
// Handle category toggle
const handleCategoryToggle = (categoryId: string) => {
const newSelected = filters.selectedCategories.includes(categoryId)
? filters.selectedCategories.filter((id) => id !== categoryId)
: [...filters.selectedCategories, categoryId];
// Handle category toggle
const handleCategoryToggle = (categoryId: string) => {
const newSelected = filters.selectedCategories.includes(categoryId)
? filters.selectedCategories.filter((id) => id !== categoryId)
: [...filters.selectedCategories, categoryId];
onFiltersChange({
...filters,
selectedCategories: newSelected,
});
};
onFiltersChange({
...filters,
selectedCategories: newSelected,
});
};
// Handle select all
const handleSelectAll = () => {
onFiltersChange({
...filters,
selectedCategories: categories.map((cat) => cat.id),
});
setOpen(false);
};
// Handle select all
const handleSelectAll = () => {
onFiltersChange({
...filters,
selectedCategories: categories.map((cat) => cat.id),
});
setOpen(false);
};
// Handle clear all
const handleClearAll = () => {
onFiltersChange({
...filters,
selectedCategories: [],
});
setOpen(false);
};
// Handle clear all
const handleClearAll = () => {
onFiltersChange({
...filters,
selectedCategories: [],
});
setOpen(false);
};
// Handle date change from MonthPicker
const handleDateChange = (field: "startPeriod" | "endPeriod", date: Date) => {
const period = dateToPeriod(date);
onFiltersChange({
...filters,
[field]: period,
});
// Handle date change from MonthPicker
const handleDateChange = (field: "startPeriod" | "endPeriod", date: Date) => {
const period = dateToPeriod(date);
onFiltersChange({
...filters,
[field]: period,
});
// Close the popover after selection
if (field === "startPeriod") {
setStartMonthOpen(false);
} else {
setEndMonthOpen(false);
}
};
// Close the popover after selection
if (field === "startPeriod") {
setStartMonthOpen(false);
} else {
setEndMonthOpen(false);
}
};
// Handle reset all filters
const handleReset = () => {
const currentPeriod = new Date().toISOString().slice(0, 7);
const defaultStartPeriod = new Date();
defaultStartPeriod.setMonth(defaultStartPeriod.getMonth() - 5);
const startPeriod = defaultStartPeriod.toISOString().slice(0, 7);
// Handle reset all filters
const handleReset = () => {
const currentPeriod = new Date().toISOString().slice(0, 7);
const defaultStartPeriod = new Date();
defaultStartPeriod.setMonth(defaultStartPeriod.getMonth() - 5);
const startPeriod = defaultStartPeriod.toISOString().slice(0, 7);
onFiltersChange({
selectedCategories: [],
startPeriod,
endPeriod: currentPeriod,
});
};
onFiltersChange({
selectedCategories: [],
startPeriod,
endPeriod: currentPeriod,
});
};
// Validate date range
const validation = useMemo(() => {
if (!filters.startPeriod || !filters.endPeriod) {
return { isValid: true };
}
return validateDateRange(filters.startPeriod, filters.endPeriod);
}, [filters.startPeriod, filters.endPeriod]);
// Validate date range
const validation = useMemo(() => {
if (!filters.startPeriod || !filters.endPeriod) {
return { isValid: true };
}
return validateDateRange(filters.startPeriod, filters.endPeriod);
}, [filters.startPeriod, filters.endPeriod]);
// Display text for selected categories
const selectedText = useMemo(() => {
if (selectedCategories.length === 0) {
return "Categoria";
}
if (selectedCategories.length === categories.length) {
return "Todas";
}
if (selectedCategories.length === 1) {
return selectedCategories[0].name;
}
return `${selectedCategories.length} selecionadas`;
}, [selectedCategories, categories.length]);
// Display text for selected categories
const selectedText = useMemo(() => {
if (selectedCategories.length === 0) {
return "Categoria";
}
if (selectedCategories.length === categories.length) {
return "Todas";
}
if (selectedCategories.length === 1) {
return selectedCategories[0].name;
}
return `${selectedCategories.length} selecionadas`;
}, [selectedCategories, categories.length]);
return (
<div className="flex flex-col gap-4">
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="flex flex-wrap items-center gap-2">
{/* Category Multi-Select */}
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
aria-label="Selecionar categorias para filtrar"
className="w-[180px] justify-between text-sm border-dashed border-input"
disabled={isLoading}
>
<span className="truncate">{selectedText}</span>
<RiExpandUpDownLine className="ml-2 h-4 w-4 shrink-0 opacity-50" aria-hidden="true" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[220px] p-0" align="start">
<Command>
<CommandInput
placeholder="Buscar categoria..."
value={searchValue}
onValueChange={setSearchValue}
/>
<CommandList>
<CommandEmpty>Nenhuma categoria encontrada.</CommandEmpty>
<CommandGroup>
{/* Select All / Clear All */}
<div className="flex gap-1 p-2 border-b">
<Button
variant="ghost"
size="sm"
className="h-7 text-xs flex-1"
onClick={handleSelectAll}
>
Todas
</Button>
<Button
variant="ghost"
size="sm"
className="h-7 text-xs flex-1"
onClick={handleClearAll}
>
Limpar
</Button>
</div>
return (
<div className="flex flex-col gap-4">
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="flex flex-wrap items-center gap-2">
{/* Category Multi-Select */}
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
aria-label="Selecionar categorias para filtrar"
className="w-[180px] justify-between text-sm border-dashed border-input"
disabled={isLoading}
>
<span className="truncate">{selectedText}</span>
<RiExpandUpDownLine
className="ml-2 h-4 w-4 shrink-0 opacity-50"
aria-hidden="true"
/>
</Button>
</PopoverTrigger>
<PopoverContent className="w-[220px] p-0" align="start">
<Command>
<CommandInput
placeholder="Buscar categoria..."
value={searchValue}
onValueChange={setSearchValue}
/>
<CommandList>
<CommandEmpty>Nenhuma categoria encontrada.</CommandEmpty>
<CommandGroup>
{/* Select All / Clear All */}
<div className="flex gap-1 p-2 border-b">
<Button
variant="ghost"
size="sm"
className="h-7 text-xs flex-1"
onClick={handleSelectAll}
>
Todas
</Button>
<Button
variant="ghost"
size="sm"
className="h-7 text-xs flex-1"
onClick={handleClearAll}
>
Limpar
</Button>
</div>
{/* Category List */}
{filteredCategories.map((category) => {
const isSelected = filters.selectedCategories.includes(
category.id
);
const IconComponent = category.icon
? getIconComponent(category.icon)
: null;
{/* Category List */}
{filteredCategories.map((category) => {
const isSelected = filters.selectedCategories.includes(
category.id,
);
const IconComponent = category.icon
? getIconComponent(category.icon)
: null;
return (
<CommandItem
key={category.id}
value={category.id}
onSelect={() => handleCategoryToggle(category.id)}
className="cursor-pointer"
>
<div className="flex items-center gap-2 flex-1">
{IconComponent && (
<IconComponent className="h-4 w-4 shrink-0" aria-hidden="true" />
)}
<span className="truncate">{category.name}</span>
</div>
{isSelected && (
<RiCheckLine className="ml-auto h-4 w-4" aria-hidden="true" />
)}
</CommandItem>
);
})}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
return (
<CommandItem
key={category.id}
value={category.id}
onSelect={() => handleCategoryToggle(category.id)}
className="cursor-pointer"
>
<div className="flex items-center gap-2 flex-1">
{IconComponent && (
<IconComponent
className="h-4 w-4 shrink-0"
aria-hidden="true"
/>
)}
<span className="truncate">{category.name}</span>
</div>
{isSelected && (
<RiCheckLine
className="ml-auto h-4 w-4"
aria-hidden="true"
/>
)}
</CommandItem>
);
})}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
{/* Start Period Picker */}
<Popover open={startMonthOpen} onOpenChange={setStartMonthOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
className="w-[150px] justify-start text-sm border-dashed"
disabled={isLoading}
>
<RiCalendarLine className="mr-2 h-4 w-4" />
{formatMonthYear(filters.startPeriod)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<MonthPicker
selectedMonth={periodToDate(filters.startPeriod)}
onMonthSelect={(date) => handleDateChange("startPeriod", date)}
/>
</PopoverContent>
</Popover>
{/* Start Period Picker */}
<Popover open={startMonthOpen} onOpenChange={setStartMonthOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
className="w-[150px] justify-start text-sm border-dashed"
disabled={isLoading}
>
<RiCalendarLine className="mr-2 h-4 w-4" />
{formatMonthYear(filters.startPeriod)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<MonthPicker
selectedMonth={periodToDate(filters.startPeriod)}
onMonthSelect={(date) => handleDateChange("startPeriod", date)}
/>
</PopoverContent>
</Popover>
{/* End Period Picker */}
<Popover open={endMonthOpen} onOpenChange={setEndMonthOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
className="w-[150px] justify-start text-sm border-dashed"
disabled={isLoading}
>
<RiCalendarLine className="mr-2 h-4 w-4" />
{formatMonthYear(filters.endPeriod)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<MonthPicker
selectedMonth={periodToDate(filters.endPeriod)}
onMonthSelect={(date) => handleDateChange("endPeriod", date)}
/>
</PopoverContent>
</Popover>
{/* End Period Picker */}
<Popover open={endMonthOpen} onOpenChange={setEndMonthOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
className="w-[150px] justify-start text-sm border-dashed"
disabled={isLoading}
>
<RiCalendarLine className="mr-2 h-4 w-4" />
{formatMonthYear(filters.endPeriod)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<MonthPicker
selectedMonth={periodToDate(filters.endPeriod)}
onMonthSelect={(date) => handleDateChange("endPeriod", date)}
/>
</PopoverContent>
</Popover>
{/* Reset Button */}
<Button
type="button"
variant="link"
size="sm"
onClick={handleReset}
disabled={isLoading}
>
Limpar
</Button>
</div>
{/* Reset Button */}
<Button
type="button"
variant="link"
size="sm"
onClick={handleReset}
disabled={isLoading}
>
Limpar
</Button>
</div>
{/* Export Button */}
{exportButton}
</div>
{/* Export Button */}
{exportButton}
</div>
{/* Validation Message */}
{!validation.isValid && validation.error && (
<div className="text-sm text-destructive">
{validation.error}
</div>
)}
</div>
);
{/* Validation Message */}
{!validation.isValid && validation.error && (
<div className="text-sm text-destructive">{validation.error}</div>
)}
</div>
);
}

View File

@@ -1,194 +1,193 @@
"use client";
import {
RiFilter3Line,
RiLineChartLine,
RiPieChartLine,
RiTable2,
} from "@remixicon/react";
import { useRouter, useSearchParams } from "next/navigation";
import { useCallback, useMemo, useState, useTransition } from "react";
import { EmptyState } from "@/components/empty-state";
import { CategoryReportSkeleton } from "@/components/skeletons/category-report-skeleton";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import type { CategoryChartData } from "@/lib/relatorios/fetch-category-chart-data";
import type { CategoryReportData } from "@/lib/relatorios/types";
import type { CategoryOption, FilterState } from "./types";
import { CategoryReportCards } from "./category-report-cards";
import { CategoryReportChart } from "./category-report-chart";
import { CategoryReportExport } from "./category-report-export";
import { CategoryReportFilters } from "./category-report-filters";
import { CategoryReportTable } from "./category-report-table";
import { CategoryReportCards } from "./category-report-cards";
import { CategoryReportExport } from "./category-report-export";
import { Skeleton } from "@/components/ui/skeleton";
import { EmptyState } from "@/components/empty-state";
import {
RiFilter3Line,
RiPieChartLine,
RiTable2,
RiLineChartLine,
} from "@remixicon/react";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { CategoryReportChart } from "./category-report-chart";
import type { CategoryChartData } from "@/lib/relatorios/fetch-category-chart-data";
import { CategoryReportSkeleton } from "@/components/skeletons/category-report-skeleton";
import type { CategoryOption, FilterState } from "./types";
interface CategoryReportPageProps {
initialData: CategoryReportData;
categories: CategoryOption[];
initialFilters: FilterState;
chartData: CategoryChartData;
initialData: CategoryReportData;
categories: CategoryOption[];
initialFilters: FilterState;
chartData: CategoryChartData;
}
export function CategoryReportPage({
initialData,
categories,
initialFilters,
chartData,
initialData,
categories,
initialFilters,
chartData,
}: CategoryReportPageProps) {
const router = useRouter();
const searchParams = useSearchParams();
const [isPending, startTransition] = useTransition();
const router = useRouter();
const searchParams = useSearchParams();
const [isPending, startTransition] = useTransition();
const [filters, setFilters] = useState<FilterState>(initialFilters);
const [data, setData] = useState<CategoryReportData>(initialData);
const [filters, setFilters] = useState<FilterState>(initialFilters);
const [data, setData] = useState<CategoryReportData>(initialData);
// Get active tab from URL or default to "table"
const activeTab = searchParams.get("aba") || "table";
// Get active tab from URL or default to "table"
const activeTab = searchParams.get("aba") || "table";
// Debounce timer
const [debounceTimer, setDebounceTimer] = useState<NodeJS.Timeout | null>(
null
);
// Debounce timer
const [debounceTimer, setDebounceTimer] = useState<NodeJS.Timeout | null>(
null,
);
const handleFiltersChange = useCallback(
(newFilters: FilterState) => {
setFilters(newFilters);
const handleFiltersChange = useCallback(
(newFilters: FilterState) => {
setFilters(newFilters);
// Clear existing timer
if (debounceTimer) {
clearTimeout(debounceTimer);
}
// Clear existing timer
if (debounceTimer) {
clearTimeout(debounceTimer);
}
// Set new debounced timer (300ms)
const timer = setTimeout(() => {
startTransition(() => {
// Build new URL with query params
const params = new URLSearchParams(searchParams.toString());
// Set new debounced timer (300ms)
const timer = setTimeout(() => {
startTransition(() => {
// Build new URL with query params
const params = new URLSearchParams(searchParams.toString());
params.set("inicio", newFilters.startPeriod);
params.set("fim", newFilters.endPeriod);
params.set("inicio", newFilters.startPeriod);
params.set("fim", newFilters.endPeriod);
if (newFilters.selectedCategories.length > 0) {
params.set("categorias", newFilters.selectedCategories.join(","));
} else {
params.delete("categorias");
}
if (newFilters.selectedCategories.length > 0) {
params.set("categorias", newFilters.selectedCategories.join(","));
} else {
params.delete("categorias");
}
// Preserve current tab
const currentTab = searchParams.get("aba");
if (currentTab) {
params.set("aba", currentTab);
}
// Preserve current tab
const currentTab = searchParams.get("aba");
if (currentTab) {
params.set("aba", currentTab);
}
// Navigate with new params (this will trigger server component re-render)
router.push(`?${params.toString()}`, { scroll: false });
});
}, 300);
// Navigate with new params (this will trigger server component re-render)
router.push(`?${params.toString()}`, { scroll: false });
});
}, 300);
setDebounceTimer(timer);
},
[debounceTimer, router, searchParams]
);
setDebounceTimer(timer);
},
[debounceTimer, router, searchParams],
);
// Handle tab change
const handleTabChange = useCallback(
(value: string) => {
const params = new URLSearchParams(searchParams.toString());
params.set("aba", value);
router.push(`?${params.toString()}`, { scroll: false });
},
[router, searchParams]
);
// Handle tab change
const handleTabChange = useCallback(
(value: string) => {
const params = new URLSearchParams(searchParams.toString());
params.set("aba", value);
router.push(`?${params.toString()}`, { scroll: false });
},
[router, searchParams],
);
// Update data when initialData changes (from server)
useMemo(() => {
setData(initialData);
}, [initialData]);
// Update data when initialData changes (from server)
useMemo(() => {
setData(initialData);
}, [initialData]);
// Check if no categories are available
const hasNoCategories = categories.length === 0;
// Check if no categories are available
const hasNoCategories = categories.length === 0;
// Check if no data in period
const hasNoData = data.categories.length === 0 && !hasNoCategories;
// Check if no data in period
const hasNoData = data.categories.length === 0 && !hasNoCategories;
return (
<div className="flex flex-col gap-6">
{/* Filters */}
<CategoryReportFilters
categories={categories}
filters={filters}
onFiltersChange={handleFiltersChange}
exportButton={<CategoryReportExport data={data} filters={filters} />}
/>
return (
<div className="flex flex-col gap-6">
{/* Filters */}
<CategoryReportFilters
categories={categories}
filters={filters}
onFiltersChange={handleFiltersChange}
exportButton={<CategoryReportExport data={data} filters={filters} />}
/>
{/* Loading State */}
{isPending && <CategoryReportSkeleton />}
{/* Loading State */}
{isPending && <CategoryReportSkeleton />}
{/* Empty States */}
{!isPending && hasNoCategories && (
<EmptyState
title="Nenhuma categoria cadastrada"
description="Você precisa cadastrar categorias antes de visualizar o relatório."
media={<RiPieChartLine className="h-12 w-12" />}
mediaVariant="icon"
/>
)}
{/* Empty States */}
{!isPending && hasNoCategories && (
<EmptyState
title="Nenhuma categoria cadastrada"
description="Você precisa cadastrar categorias antes de visualizar o relatório."
media={<RiPieChartLine className="h-12 w-12" />}
mediaVariant="icon"
/>
)}
{!isPending &&
!hasNoCategories &&
hasNoData &&
filters.selectedCategories.length === 0 && (
<EmptyState
title="Selecione pelo menos uma categoria"
description="Use o filtro acima para selecionar as categorias que deseja visualizar no relatório."
media={<RiFilter3Line className="h-12 w-12" />}
mediaVariant="icon"
/>
)}
{!isPending &&
!hasNoCategories &&
hasNoData &&
filters.selectedCategories.length === 0 && (
<EmptyState
title="Selecione pelo menos uma categoria"
description="Use o filtro acima para selecionar as categorias que deseja visualizar no relatório."
media={<RiFilter3Line className="h-12 w-12" />}
mediaVariant="icon"
/>
)}
{!isPending &&
!hasNoCategories &&
hasNoData &&
filters.selectedCategories.length > 0 && (
<EmptyState
title="Nenhum lançamento encontrado"
description="Não há transações no período selecionado para as categorias filtradas."
media={<RiPieChartLine className="h-12 w-12" />}
mediaVariant="icon"
/>
)}
{!isPending &&
!hasNoCategories &&
hasNoData &&
filters.selectedCategories.length > 0 && (
<EmptyState
title="Nenhum lançamento encontrado"
description="Não há transações no período selecionado para as categorias filtradas."
media={<RiPieChartLine className="h-12 w-12" />}
mediaVariant="icon"
/>
)}
{/* Tabs: Table and Chart */}
{!isPending && !hasNoCategories && !hasNoData && (
<Tabs
value={activeTab}
onValueChange={handleTabChange}
className="w-full"
>
<TabsList>
<TabsTrigger value="table">
<RiTable2 className="h-4 w-4 mr-2" />
Tabela
</TabsTrigger>
<TabsTrigger value="chart">
<RiLineChartLine className="h-4 w-4 mr-2" />
Gráfico
</TabsTrigger>
</TabsList>
{/* Tabs: Table and Chart */}
{!isPending && !hasNoCategories && !hasNoData && (
<Tabs
value={activeTab}
onValueChange={handleTabChange}
className="w-full"
>
<TabsList>
<TabsTrigger value="table">
<RiTable2 className="h-4 w-4 mr-2" />
Tabela
</TabsTrigger>
<TabsTrigger value="chart">
<RiLineChartLine className="h-4 w-4 mr-2" />
Gráfico
</TabsTrigger>
</TabsList>
<TabsContent value="table" className="mt-4">
{/* Desktop Table */}
<div className="hidden md:block">
<CategoryReportTable data={data} />
</div>
<TabsContent value="table" className="mt-4">
{/* Desktop Table */}
<div className="hidden md:block">
<CategoryReportTable data={data} />
</div>
{/* Mobile Cards */}
<CategoryReportCards data={data} />
</TabsContent>
{/* Mobile Cards */}
<CategoryReportCards data={data} />
</TabsContent>
<TabsContent value="chart" className="mt-4">
<CategoryReportChart data={chartData} />
</TabsContent>
</Tabs>
)}
</div>
);
<TabsContent value="chart" className="mt-4">
<CategoryReportChart data={chartData} />
</TabsContent>
</Tabs>
)}
</div>
);
}

View File

@@ -1,13 +1,13 @@
"use client";
import {
Table,
TableBody,
TableCell,
TableFooter,
TableHead,
TableHeader,
TableRow,
Table,
TableBody,
TableCell,
TableFooter,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import type { CategoryReportData } from "@/lib/relatorios/types";
import { formatCurrency, formatPeriodLabel } from "@/lib/relatorios/utils";
@@ -17,94 +17,94 @@ import { Card } from "../ui/card";
import { CategoryCell } from "./category-cell";
interface CategoryReportTableProps {
data: CategoryReportData;
data: CategoryReportData;
}
export function CategoryReportTable({ data }: CategoryReportTableProps) {
const { categories, periods, totals, grandTotal } = data;
const { categories, periods, totals, grandTotal } = data;
return (
<Card className="px-6 py-4">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[280px] min-w-[280px] font-bold">
Categoria
</TableHead>
{periods.map((period) => (
<TableHead
key={period}
className="text-right min-w-[120px] font-bold"
>
{formatPeriodLabel(period)}
</TableHead>
))}
<TableHead className="text-right min-w-[120px] font-bold">
Total
</TableHead>
</TableRow>
</TableHeader>
return (
<Card className="px-6 py-4">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[280px] min-w-[280px] font-bold">
Categoria
</TableHead>
{periods.map((period) => (
<TableHead
key={period}
className="text-right min-w-[120px] font-bold"
>
{formatPeriodLabel(period)}
</TableHead>
))}
<TableHead className="text-right min-w-[120px] font-bold">
Total
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{categories.map((category) => {
const Icon = category.icon ? getIconComponent(category.icon) : null;
const isReceita = category.type.toLowerCase() === "receita";
const dotColor = isReceita
? "bg-green-600 dark:bg-green-400"
: "bg-red-600 dark:bg-red-400";
<TableBody>
{categories.map((category) => {
const Icon = category.icon ? getIconComponent(category.icon) : null;
const isReceita = category.type.toLowerCase() === "receita";
const dotColor = isReceita
? "bg-green-600 dark:bg-green-400"
: "bg-red-600 dark:bg-red-400";
return (
<TableRow key={category.categoryId}>
<TableCell>
<div className="flex items-center gap-2">
<DotIcon bg_dot={dotColor} />
{Icon && <Icon className="h-4 w-4 shrink-0" />}
<span className="font-bold truncate">{category.name}</span>
</div>
</TableCell>
{periods.map((period, periodIndex) => {
const monthData = category.monthlyData.get(period);
const isFirstMonth = periodIndex === 0;
return (
<TableRow key={category.categoryId}>
<TableCell>
<div className="flex items-center gap-2">
<DotIcon bg_dot={dotColor} />
{Icon && <Icon className="h-4 w-4 shrink-0" />}
<span className="font-bold truncate">{category.name}</span>
</div>
</TableCell>
{periods.map((period, periodIndex) => {
const monthData = category.monthlyData.get(period);
const isFirstMonth = periodIndex === 0;
return (
<TableCell key={period} className="text-right">
<CategoryCell
value={monthData?.amount ?? 0}
previousValue={monthData?.previousAmount ?? 0}
categoryType={category.type}
isFirstMonth={isFirstMonth}
/>
</TableCell>
);
})}
<TableCell className="text-right font-semibold">
{formatCurrency(category.total)}
</TableCell>
</TableRow>
);
})}
</TableBody>
return (
<TableCell key={period} className="text-right">
<CategoryCell
value={monthData?.amount ?? 0}
previousValue={monthData?.previousAmount ?? 0}
categoryType={category.type}
isFirstMonth={isFirstMonth}
/>
</TableCell>
);
})}
<TableCell className="text-right font-semibold">
{formatCurrency(category.total)}
</TableCell>
</TableRow>
);
})}
</TableBody>
<TableFooter>
<TableRow>
<TableCell className="min-h-[2.5rem]">Total Geral</TableCell>
{periods.map((period) => {
const periodTotal = totals.get(period) ?? 0;
return (
<TableCell
key={period}
className="text-right font-semibold min-h-8"
>
{formatCurrency(periodTotal)}
</TableCell>
);
})}
<TableCell className="text-right font-semibold min-h-8">
{formatCurrency(grandTotal)}
</TableCell>
</TableRow>
</TableFooter>
</Table>
</Card>
);
<TableFooter>
<TableRow>
<TableCell className="min-h-[2.5rem]">Total Geral</TableCell>
{periods.map((period) => {
const periodTotal = totals.get(period) ?? 0;
return (
<TableCell
key={period}
className="text-right font-semibold min-h-8"
>
{formatCurrency(periodTotal)}
</TableCell>
);
})}
<TableCell className="text-right font-semibold min-h-8">
{formatCurrency(grandTotal)}
</TableCell>
</TableRow>
</TableFooter>
</Table>
</Card>
);
}

View File

@@ -1,8 +1,12 @@
export { CategoryCell } from "./category-cell";
export { CategoryReportCards } from "./category-report-cards";
export { CategoryReportChart } from "./category-report-chart";
export { CategoryReportExport } from "./category-report-export";
export { CategoryReportFilters } from "./category-report-filters";
export { CategoryReportPage } from "./category-report-page";
export { CategoryReportTable } from "./category-report-table";
export { CategoryReportCards } from "./category-report-cards";
export { CategoryReportFilters } from "./category-report-filters";
export { CategoryReportExport } from "./category-report-export";
export { CategoryReportChart } from "./category-report-chart";
export { CategoryCell } from "./category-cell";
export type { CategoryOption, FilterState, CategoryReportFiltersProps } from "./types";
export type {
CategoryOption,
CategoryReportFiltersProps,
FilterState,
} from "./types";

View File

@@ -7,10 +7,10 @@
* Includes type field for filtering despesas/receitas
*/
export interface CategoryOption {
id: string;
name: string;
icon: string | null;
type: "despesa" | "receita";
id: string;
name: string;
icon: string | null;
type: "despesa" | "receita";
}
/**
@@ -18,17 +18,17 @@ export interface CategoryOption {
* Manages selected categories and date range
*/
export interface FilterState {
selectedCategories: string[]; // Array of category IDs
startPeriod: string; // Format: "YYYY-MM"
endPeriod: string; // Format: "YYYY-MM"
selectedCategories: string[]; // Array of category IDs
startPeriod: string; // Format: "YYYY-MM"
endPeriod: string; // Format: "YYYY-MM"
}
/**
* Props for CategoryReportFilters component
*/
export interface CategoryReportFiltersProps {
categories: CategoryOption[];
filters: FilterState;
onFiltersChange: (filters: FilterState) => void;
isLoading?: boolean;
categories: CategoryOption[];
filters: FilterState;
onFiltersChange: (filters: FilterState) => void;
isLoading?: boolean;
}