mirror of
https://github.com/felipegcoutinho/openmonetis.git
synced 2026-03-10 04:51:47 +00:00
feat: implementar relatórios de categorias e substituir seleção de período por picker visual
BREAKING CHANGE: Remove feature de seleção de período das preferências do usuário
Alterações principais:
- Adiciona sistema completo de relatórios por categoria
- Cria página /relatorios/categorias com filtros e visualizações
- Implementa tabela e gráfico de evolução mensal
- Adiciona funcionalidade de exportação de dados
- Cria skeleton otimizado para melhor UX de loading
- Remove feature de seleção de período das preferências
- Deleta lib/user-preferences/period.ts
- Remove colunas periodMonthsBefore e periodMonthsAfter do schema
- Remove todas as referências em 16+ arquivos
- Atualiza database schema via Drizzle
- Substitui Select de período por MonthPicker visual
- Implementa componente PeriodPicker reutilizável
- Integra shadcn MonthPicker customizado (português, Remix icons)
- Substitui createMonthOptions em todos os formulários
- Mantém formato "YYYY-MM" no banco de dados
- Melhora design da tabela de relatórios
- Mescla colunas Categoria e Tipo em uma única coluna
- Substitui badge de tipo por dot colorido discreto
- Reduz largura da tabela em ~120px
- Atualiza skeleton para refletir nova estrutura
- Melhorias gerais de UI
- Reduz espaçamento entre títulos da sidebar (p-2 → px-2 py-1)
- Adiciona MonthNavigation para navegação entre períodos
- Otimiza loading states com skeletons detalhados
This commit is contained in:
46
components/relatorios/category-cell.tsx
Normal file
46
components/relatorios/category-cell.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
"use client";
|
||||
|
||||
import { formatCurrency, formatPercentageChange } from "@/lib/relatorios/utils";
|
||||
import { RiArrowDownLine, RiArrowUpLine } from "@remixicon/react";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
|
||||
interface CategoryCellProps {
|
||||
value: number;
|
||||
previousValue: number;
|
||||
categoryType: "despesa" | "receita";
|
||||
isFirstMonth: boolean;
|
||||
}
|
||||
|
||||
export function CategoryCell({
|
||||
value,
|
||||
previousValue,
|
||||
categoryType,
|
||||
isFirstMonth,
|
||||
}: CategoryCellProps) {
|
||||
const percentageChange =
|
||||
!isFirstMonth && previousValue !== 0
|
||||
? ((value - previousValue) / previousValue) * 100
|
||||
: null;
|
||||
|
||||
const isIncrease = percentageChange !== null && percentageChange > 0;
|
||||
const isDecrease = percentageChange !== null && percentageChange < 0;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-end gap-0.5">
|
||||
<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>
|
||||
);
|
||||
}
|
||||
63
components/relatorios/category-report-cards.tsx
Normal file
63
components/relatorios/category-report-cards.tsx
Normal file
@@ -0,0 +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 type { CategoryReportData } from "@/lib/relatorios/types";
|
||||
import { CategoryCell } from "./category-cell";
|
||||
|
||||
interface CategoryReportCardsProps {
|
||||
data: CategoryReportData;
|
||||
}
|
||||
|
||||
export function CategoryReportCards({ data }: CategoryReportCardsProps) {
|
||||
const { categories, periods } = data;
|
||||
|
||||
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 (
|
||||
<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>
|
||||
);
|
||||
}
|
||||
213
components/relatorios/category-report-chart.tsx
Normal file
213
components/relatorios/category-report-chart.tsx
Normal file
@@ -0,0 +1,213 @@
|
||||
"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";
|
||||
|
||||
interface CategoryReportChartProps {
|
||||
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
|
||||
];
|
||||
|
||||
const MAX_CATEGORIES_IN_CHART = 15;
|
||||
|
||||
export function CategoryReportChart({ data }: CategoryReportChartProps) {
|
||||
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"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// 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 };
|
||||
});
|
||||
|
||||
// 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,
|
||||
};
|
||||
|
||||
// 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 { 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 (
|
||||
<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>
|
||||
|
||||
{/* 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>
|
||||
);
|
||||
}
|
||||
348
components/relatorios/category-report-export.tsx
Normal file
348
components/relatorios/category-report-export.tsx
Normal file
@@ -0,0 +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,
|
||||
} from "@remixicon/react";
|
||||
import { toast } from "sonner";
|
||||
import { useState } from "react";
|
||||
import jsPDF from "jspdf";
|
||||
import autoTable from "jspdf-autotable";
|
||||
import * as XLSX from "xlsx";
|
||||
|
||||
interface CategoryReportExportProps {
|
||||
data: CategoryReportData;
|
||||
filters: FilterState;
|
||||
}
|
||||
|
||||
export function CategoryReportExport({
|
||||
data,
|
||||
filters,
|
||||
}: CategoryReportExportProps) {
|
||||
const [isExporting, setIsExporting] = useState(false);
|
||||
|
||||
const getFileName = (extension: string) => {
|
||||
const start = filters.startPeriod;
|
||||
const end = filters.endPeriod;
|
||||
return `relatorio-categorias-${start}-${end}.${extension}`;
|
||||
};
|
||||
|
||||
const exportToCSV = () => {
|
||||
try {
|
||||
setIsExporting(true);
|
||||
|
||||
// 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];
|
||||
|
||||
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);
|
||||
|
||||
// Add indicator as text
|
||||
if (!isFirstMonth && percentageChange != null) {
|
||||
const arrow = percentageChange > 0 ? "↑" : "↓";
|
||||
cellValue += ` (${arrow}${formatPercentageChange(
|
||||
percentageChange
|
||||
)})`;
|
||||
}
|
||||
|
||||
row.push(cellValue);
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
// 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);
|
||||
|
||||
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);
|
||||
|
||||
// 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];
|
||||
|
||||
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);
|
||||
|
||||
// Add indicator as text
|
||||
if (!isFirstMonth && percentageChange != null) {
|
||||
const arrow = percentageChange > 0 ? "↑" : "↓";
|
||||
cellValue += ` (${arrow}${formatPercentageChange(
|
||||
percentageChange
|
||||
)})`;
|
||||
}
|
||||
|
||||
row.push(cellValue);
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
// 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
|
||||
];
|
||||
|
||||
// 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);
|
||||
}
|
||||
};
|
||||
|
||||
const exportToPDF = () => {
|
||||
try {
|
||||
setIsExporting(true);
|
||||
|
||||
// Create PDF
|
||||
const doc = new jsPDF({ orientation: "landscape" });
|
||||
|
||||
// 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);
|
||||
|
||||
// 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];
|
||||
|
||||
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);
|
||||
|
||||
// Add indicator as text
|
||||
if (!isFirstMonth && percentageChange != null) {
|
||||
const arrow = percentageChange > 0 ? "↑" : "↓";
|
||||
cellValue += `\n(${arrow}${formatPercentageChange(
|
||||
percentageChange
|
||||
)})`;
|
||||
}
|
||||
|
||||
row.push(cellValue);
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
// 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];
|
||||
|
||||
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"));
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
309
components/relatorios/category-report-filters.tsx
Normal file
309
components/relatorios/category-report-filters.tsx
Normal file
@@ -0,0 +1,309 @@
|
||||
"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";
|
||||
import { format } from "date-fns";
|
||||
import { ptBR } from "date-fns/locale";
|
||||
import type { CategoryReportFiltersProps, FilterState } from "./types";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
/**
|
||||
* Category Report Filters Component
|
||||
* Provides filters for categories selection and date range
|
||||
*/
|
||||
export function CategoryReportFilters({
|
||||
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);
|
||||
|
||||
// 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}`;
|
||||
};
|
||||
|
||||
// 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]);
|
||||
|
||||
// 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];
|
||||
|
||||
onFiltersChange({
|
||||
...filters,
|
||||
selectedCategories: newSelected,
|
||||
});
|
||||
};
|
||||
|
||||
// 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 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);
|
||||
}
|
||||
};
|
||||
|
||||
// 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,
|
||||
});
|
||||
};
|
||||
|
||||
// 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]);
|
||||
|
||||
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;
|
||||
|
||||
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>
|
||||
|
||||
{/* 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>
|
||||
|
||||
{/* Export Button */}
|
||||
{exportButton}
|
||||
</div>
|
||||
|
||||
{/* Validation Message */}
|
||||
{!validation.isValid && validation.error && (
|
||||
<div className="text-sm text-destructive">
|
||||
{validation.error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
194
components/relatorios/category-report-page.tsx
Normal file
194
components/relatorios/category-report-page.tsx
Normal file
@@ -0,0 +1,194 @@
|
||||
"use client";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { useCallback, useMemo, useState, useTransition } from "react";
|
||||
import type { CategoryReportData } from "@/lib/relatorios/types";
|
||||
import type { CategoryOption, FilterState } from "./types";
|
||||
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";
|
||||
|
||||
interface CategoryReportPageProps {
|
||||
initialData: CategoryReportData;
|
||||
categories: CategoryOption[];
|
||||
initialFilters: FilterState;
|
||||
chartData: CategoryChartData;
|
||||
}
|
||||
|
||||
export function CategoryReportPage({
|
||||
initialData,
|
||||
categories,
|
||||
initialFilters,
|
||||
chartData,
|
||||
}: CategoryReportPageProps) {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
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";
|
||||
|
||||
// Debounce timer
|
||||
const [debounceTimer, setDebounceTimer] = useState<NodeJS.Timeout | null>(
|
||||
null
|
||||
);
|
||||
|
||||
const handleFiltersChange = useCallback(
|
||||
(newFilters: FilterState) => {
|
||||
setFilters(newFilters);
|
||||
|
||||
// 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());
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
// 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);
|
||||
|
||||
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]
|
||||
);
|
||||
|
||||
// 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 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} />}
|
||||
/>
|
||||
|
||||
{/* 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"
|
||||
/>
|
||||
)}
|
||||
|
||||
{!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"
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 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>
|
||||
|
||||
{/* Mobile Cards */}
|
||||
<CategoryReportCards data={data} />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="chart" className="mt-4">
|
||||
<CategoryReportChart data={chartData} />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
108
components/relatorios/category-report-table.tsx
Normal file
108
components/relatorios/category-report-table.tsx
Normal file
@@ -0,0 +1,108 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableFooter,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { getIconComponent } from "@/lib/utils/icons";
|
||||
import { formatPeriodLabel } from "@/lib/relatorios/utils";
|
||||
import type { CategoryReportData } from "@/lib/relatorios/types";
|
||||
import { CategoryCell } from "./category-cell";
|
||||
import { formatCurrency } from "@/lib/relatorios/utils";
|
||||
import { Card } from "../ui/card";
|
||||
import DotIcon from "../dot-icon";
|
||||
|
||||
interface CategoryReportTableProps {
|
||||
data: CategoryReportData;
|
||||
}
|
||||
|
||||
export function CategoryReportTable({ data }: CategoryReportTableProps) {
|
||||
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>
|
||||
|
||||
<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 (
|
||||
<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>Total Geral</TableCell>
|
||||
{periods.map((period) => {
|
||||
const periodTotal = totals.get(period) ?? 0;
|
||||
return (
|
||||
<TableCell key={period} className="text-right font-semibold">
|
||||
{formatCurrency(periodTotal)}
|
||||
</TableCell>
|
||||
);
|
||||
})}
|
||||
<TableCell className="text-right font-semibold">
|
||||
{formatCurrency(grandTotal)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableFooter>
|
||||
</Table>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
8
components/relatorios/index.ts
Normal file
8
components/relatorios/index.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
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";
|
||||
34
components/relatorios/types.ts
Normal file
34
components/relatorios/types.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* UI types for Category Report components
|
||||
*/
|
||||
|
||||
/**
|
||||
* Category option for report filters
|
||||
* Includes type field for filtering despesas/receitas
|
||||
*/
|
||||
export interface CategoryOption {
|
||||
id: string;
|
||||
name: string;
|
||||
icon: string | null;
|
||||
type: "despesa" | "receita";
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter state for category report
|
||||
* 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"
|
||||
}
|
||||
|
||||
/**
|
||||
* Props for CategoryReportFilters component
|
||||
*/
|
||||
export interface CategoryReportFiltersProps {
|
||||
categories: CategoryOption[];
|
||||
filters: FilterState;
|
||||
onFiltersChange: (filters: FilterState) => void;
|
||||
isLoading?: boolean;
|
||||
}
|
||||
Reference in New Issue
Block a user