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:
Felipe Coutinho
2026-01-04 03:03:09 +00:00
parent d192f47bc7
commit 4237062bde
54 changed files with 2987 additions and 472 deletions

View File

@@ -11,21 +11,15 @@ import { toast } from "sonner";
interface PreferencesFormProps {
disableMagnetlines: boolean;
periodMonthsBefore: number;
periodMonthsAfter: number;
}
export function PreferencesForm({
disableMagnetlines,
periodMonthsBefore,
periodMonthsAfter,
}: PreferencesFormProps) {
const router = useRouter();
const [isPending, startTransition] = useTransition();
const [magnetlinesDisabled, setMagnetlinesDisabled] =
useState(disableMagnetlines);
const [monthsBefore, setMonthsBefore] = useState(periodMonthsBefore);
const [monthsAfter, setMonthsAfter] = useState(periodMonthsAfter);
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
@@ -33,8 +27,6 @@ export function PreferencesForm({
startTransition(async () => {
const result = await updatePreferencesAction({
disableMagnetlines: magnetlinesDisabled,
periodMonthsBefore: monthsBefore,
periodMonthsAfter: monthsAfter,
});
if (result.success) {
@@ -74,58 +66,6 @@ export function PreferencesForm({
disabled={isPending}
/>
</div>
<div className="space-y-4 rounded-lg border border-dashed p-4">
<div>
<h3 className="text-base font-medium mb-2">
Seleção de Período
</h3>
<p className="text-sm text-muted-foreground mb-4">
Configure quantos meses antes e depois do mês atual serão exibidos
nos seletores de período.
</p>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="monthsBefore" className="text-sm">
Meses anteriores
</Label>
<Input
id="monthsBefore"
type="number"
min={1}
max={24}
value={monthsBefore}
onChange={(e) => setMonthsBefore(Number(e.target.value))}
disabled={isPending}
className="w-full"
/>
<p className="text-xs text-muted-foreground">
1 a 24 meses
</p>
</div>
<div className="space-y-2">
<Label htmlFor="monthsAfter" className="text-sm">
Meses posteriores
</Label>
<Input
id="monthsAfter"
type="number"
min={1}
max={24}
value={monthsAfter}
onChange={(e) => setMonthsAfter(Number(e.target.value))}
disabled={isPending}
className="w-full"
/>
<p className="text-xs text-muted-foreground">
1 a 24 meses
</p>
</div>
</div>
</div>
</div>
<div className="flex justify-end">

View File

@@ -118,7 +118,6 @@ export function MonthlyCalendar({
cartaoOptions={formOptions.cartaoOptions}
categoriaOptions={formOptions.categoriaOptions}
estabelecimentos={formOptions.estabelecimentos}
periodPreferences={formOptions.periodPreferences}
defaultPeriod={period.period}
defaultPurchaseDate={createDate ?? undefined}
/>

View File

@@ -1,5 +1,4 @@
import type { LancamentoItem, SelectOption } from "@/components/lancamentos/types";
import type { PeriodPreferences } from "@/lib/user-preferences/period";
export type CalendarEventType = "lancamento" | "boleto" | "cartao";
@@ -54,7 +53,6 @@ export type CalendarFormOptions = {
cartaoOptions: SelectOption[];
categoriaOptions: SelectOption[];
estabelecimentos: string[];
periodPreferences: PeriodPreferences;
};
export type CalendarData = {

View File

@@ -32,11 +32,10 @@ import {
SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { PeriodPicker } from "@/components/period-picker";
import { useControlledState } from "@/hooks/use-controlled-state";
import { useFormState } from "@/hooks/use-form-state";
import type { EligibleInstallment } from "@/lib/installments/anticipation-types";
import type { PeriodPreferences } from "@/lib/user-preferences/period";
import { createMonthOptions } from "@/lib/utils/period";
import { RiLoader4Line } from "@remixicon/react";
import {
useCallback,
@@ -55,7 +54,6 @@ interface AnticipateInstallmentsDialogProps {
categorias: Array<{ id: string; name: string; icon: string | null }>;
pagadores: Array<{ id: string; name: string }>;
defaultPeriod: string;
periodPreferences: PeriodPreferences;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}
@@ -75,7 +73,6 @@ export function AnticipateInstallmentsDialog({
categorias,
pagadores,
defaultPeriod,
periodPreferences,
open,
onOpenChange,
}: AnticipateInstallmentsDialogProps) {
@@ -104,16 +101,6 @@ export function AnticipateInstallmentsDialog({
note: "",
});
const periodOptions = useMemo(
() =>
createMonthOptions(
formState.anticipationPeriod,
periodPreferences.monthsBefore,
periodPreferences.monthsAfter
),
[formState.anticipationPeriod, periodPreferences.monthsBefore, periodPreferences.monthsAfter]
);
// Buscar parcelas elegíveis ao abrir o dialog
useEffect(() => {
if (dialogOpen) {
@@ -262,24 +249,14 @@ export function AnticipateInstallmentsDialog({
<Field className="gap-1">
<FieldLabel htmlFor="anticipation-period">Período</FieldLabel>
<FieldContent>
<Select
<PeriodPicker
value={formState.anticipationPeriod}
onValueChange={(value) =>
onChange={(value) =>
updateField("anticipationPeriod", value)
}
disabled={isPending}
>
<SelectTrigger id="anticipation-period" className="w-full">
<SelectValue placeholder="Selecione o período" />
</SelectTrigger>
<SelectContent>
{periodOptions.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
className="w-full"
/>
</FieldContent>
</Field>

View File

@@ -2,13 +2,7 @@
import { Label } from "@/components/ui/label";
import { DatePicker } from "@/components/ui/date-picker";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { PeriodPicker } from "@/components/period-picker";
import { CurrencyInput } from "@/components/ui/currency-input";
import { CalculatorDialogButton } from "@/components/calculadora/calculator-dialog";
import { RiCalculatorLine } from "@remixicon/react";
@@ -19,8 +13,7 @@ export function BasicFieldsSection({
formState,
onFieldChange,
estabelecimentos,
monthOptions,
}: BasicFieldsSectionProps) {
}: Omit<BasicFieldsSectionProps, "monthOptions">) {
return (
<>
<div className="flex w-full flex-col gap-2 md:flex-row">
@@ -37,21 +30,11 @@ export function BasicFieldsSection({
<div className="w-1/2 space-y-1">
<Label htmlFor="period">Período</Label>
<Select
<PeriodPicker
value={formState.period}
onValueChange={(value) => onFieldChange("period", value)}
>
<SelectTrigger id="period" className="w-full">
<SelectValue placeholder="Selecione" />
</SelectTrigger>
<SelectContent>
{monthOptions.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
onChange={(value) => onFieldChange("period", value)}
className="w-full"
/>
</div>
</div>

View File

@@ -1,5 +1,4 @@
import type { LancamentoFormState } from "@/lib/lancamentos/form-helpers";
import type { PeriodPreferences } from "@/lib/user-preferences/period";
import type { LancamentoItem, SelectOption } from "../../types";
export type FormState = LancamentoFormState;
@@ -18,7 +17,6 @@ export interface LancamentoDialogProps {
estabelecimentos: string[];
lancamento?: LancamentoItem;
defaultPeriod?: string;
periodPreferences: PeriodPreferences;
defaultCartaoId?: string | null;
defaultPaymentMethod?: string | null;
defaultPurchaseDate?: string | null;
@@ -48,7 +46,6 @@ export interface BaseFieldSectionProps {
export interface BasicFieldsSectionProps extends BaseFieldSectionProps {
estabelecimentos: string[];
monthOptions: Array<{ value: string; label: string }>;
}
export interface CategorySectionProps extends BaseFieldSectionProps {

View File

@@ -22,7 +22,6 @@ import {
applyFieldDependencies,
buildLancamentoInitialState,
} from "@/lib/lancamentos/form-helpers";
import { createMonthOptions } from "@/lib/utils/period";
import {
useCallback,
useEffect,
@@ -58,7 +57,6 @@ export function LancamentoDialog({
estabelecimentos,
lancamento,
defaultPeriod,
periodPreferences,
defaultCartaoId,
defaultPaymentMethod,
defaultPurchaseDate,
@@ -125,15 +123,6 @@ export function LancamentoDialog({
return groupAndSortCategorias(filtered);
}, [categoriaOptions, formState.transactionType]);
const monthOptions = useMemo(
() =>
createMonthOptions(
formState.period,
periodPreferences.monthsBefore,
periodPreferences.monthsAfter
),
[formState.period, periodPreferences.monthsBefore, periodPreferences.monthsAfter]
);
const handleFieldChange = useCallback(
<Key extends keyof FormState>(key: Key, value: FormState[Key]) => {
@@ -352,7 +341,6 @@ export function LancamentoDialog({
formState={formState}
onFieldChange={handleFieldChange}
estabelecimentos={estabelecimentos}
monthOptions={monthOptions}
/>
<CategorySection

View File

@@ -23,11 +23,10 @@ import {
} from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { Spinner } from "@/components/ui/spinner";
import { PeriodPicker } from "@/components/period-picker";
import { groupAndSortCategorias } from "@/lib/lancamentos/categoria-helpers";
import { LANCAMENTO_PAYMENT_METHODS } from "@/lib/lancamentos/constants";
import { getTodayDateString } from "@/lib/utils/date";
import { createMonthOptions } from "@/lib/utils/period";
import type { PeriodPreferences } from "@/lib/user-preferences/period";
import { RiAddLine, RiDeleteBinLine } from "@remixicon/react";
import { useMemo, useState } from "react";
import { toast } from "sonner";
@@ -52,7 +51,6 @@ interface MassAddDialogProps {
categoriaOptions: SelectOption[];
estabelecimentos: string[];
selectedPeriod: string;
periodPreferences: PeriodPreferences;
defaultPagadorId?: string | null;
}
@@ -93,7 +91,6 @@ export function MassAddDialog({
categoriaOptions,
estabelecimentos,
selectedPeriod,
periodPreferences,
defaultPagadorId,
}: MassAddDialogProps) {
const [loading, setLoading] = useState(false);
@@ -120,17 +117,6 @@ export function MassAddDialog({
},
]);
// Period options
const periodOptions = useMemo(
() =>
createMonthOptions(
selectedPeriod,
periodPreferences.monthsBefore,
periodPreferences.monthsAfter
),
[selectedPeriod, periodPreferences.monthsBefore, periodPreferences.monthsAfter]
);
// Categorias agrupadas e filtradas por tipo de transação
const groupedCategorias = useMemo(() => {
const filtered = categoriaOptions.filter(
@@ -336,18 +322,11 @@ export function MassAddDialog({
{/* Period */}
<div className="space-y-2">
<Label htmlFor="period">Período</Label>
<Select value={period} onValueChange={setPeriod}>
<SelectTrigger id="period" className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
{periodOptions.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
<PeriodPicker
value={period}
onChange={setPeriod}
className="w-full truncate"
/>
</div>
{/* Conta/Cartao */}

View File

@@ -25,7 +25,6 @@ import type {
LancamentoItem,
SelectOption,
} from "../types";
import type { PeriodPreferences } from "@/lib/user-preferences/period";
interface LancamentosPageProps {
lancamentos: LancamentoItem[];
@@ -40,7 +39,6 @@ interface LancamentosPageProps {
contaCartaoFilterOptions: ContaCartaoFilterOption[];
selectedPeriod: string;
estabelecimentos: string[];
periodPreferences: PeriodPreferences;
allowCreate?: boolean;
defaultCartaoId?: string | null;
defaultPaymentMethod?: string | null;
@@ -61,7 +59,6 @@ export function LancamentosPage({
contaCartaoFilterOptions,
selectedPeriod,
estabelecimentos,
periodPreferences,
allowCreate = true,
defaultCartaoId,
defaultPaymentMethod,
@@ -357,7 +354,6 @@ export function LancamentosPage({
categoriaOptions={categoriaOptions}
estabelecimentos={estabelecimentos}
defaultPeriod={selectedPeriod}
periodPreferences={periodPreferences}
defaultCartaoId={defaultCartaoId}
defaultPaymentMethod={defaultPaymentMethod}
lockCartaoSelection={lockCartaoSelection}
@@ -383,7 +379,6 @@ export function LancamentosPage({
estabelecimentos={estabelecimentos}
lancamento={lancamentoToCopy ?? undefined}
defaultPeriod={selectedPeriod}
periodPreferences={periodPreferences}
/>
<LancamentoDialog
@@ -399,7 +394,6 @@ export function LancamentosPage({
estabelecimentos={estabelecimentos}
lancamento={selectedLancamento ?? undefined}
defaultPeriod={selectedPeriod}
periodPreferences={periodPreferences}
onBulkEditRequest={handleBulkEditRequest}
/>
@@ -479,7 +473,6 @@ export function LancamentosPage({
categoriaOptions={categoriaOptions}
estabelecimentos={estabelecimentos}
selectedPeriod={selectedPeriod}
periodPreferences={periodPreferences}
defaultPagadorId={defaultPagadorId}
/>
) : null}
@@ -515,7 +508,6 @@ export function LancamentosPage({
name: p.label,
}))}
defaultPeriod={selectedPeriod}
periodPreferences={periodPreferences}
/>
)}

View File

@@ -8,7 +8,7 @@ import LoadingSpinner from "./loading-spinner";
import NavigationButton from "./nav-button";
import ReturnButton from "./return-button";
export default function MonthPicker() {
export default function MonthNavigation() {
const {
monthNames,
currentMonth,

View File

@@ -24,10 +24,9 @@ import {
SelectValue,
} from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import { PeriodPicker } from "@/components/period-picker";
import { useControlledState } from "@/hooks/use-controlled-state";
import { useFormState } from "@/hooks/use-form-state";
import type { PeriodPreferences } from "@/lib/user-preferences/period";
import { createMonthOptions } from "@/lib/utils/period";
import {
useCallback,
useEffect,
@@ -45,7 +44,6 @@ interface BudgetDialogProps {
budget?: Budget;
categories: BudgetCategory[];
defaultPeriod: string;
periodPreferences: PeriodPreferences;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}
@@ -68,7 +66,6 @@ export function BudgetDialog({
budget,
categories,
defaultPeriod,
periodPreferences,
open,
onOpenChange,
}: BudgetDialogProps) {
@@ -110,16 +107,6 @@ export function BudgetDialog({
}
}, [dialogOpen]);
const periodOptions = useMemo(
() =>
createMonthOptions(
formState.period,
periodPreferences.monthsBefore,
periodPreferences.monthsAfter
),
[formState.period, periodPreferences.monthsBefore, periodPreferences.monthsAfter]
);
const handleSubmit = useCallback(
(event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
@@ -244,21 +231,11 @@ export function BudgetDialog({
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="budget-period">Período</Label>
<Select
<PeriodPicker
value={formState.period}
onValueChange={(value) => updateField("period", value)}
>
<SelectTrigger id="budget-period" className="w-full">
<SelectValue placeholder="Selecione o período" />
</SelectTrigger>
<SelectContent className="max-h-64">
{periodOptions.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
onChange={(value) => updateField("period", value)}
className="w-full"
/>
</div>
<div className="space-y-2">

View File

@@ -4,7 +4,6 @@ import { deleteBudgetAction } from "@/app/(dashboard)/orcamentos/actions";
import { ConfirmActionDialog } from "@/components/confirm-action-dialog";
import { EmptyState } from "@/components/empty-state";
import { Button } from "@/components/ui/button";
import type { PeriodPreferences } from "@/lib/user-preferences/period";
import { RiAddCircleLine, RiFundsLine } from "@remixicon/react";
import { useCallback, useState } from "react";
import { toast } from "sonner";
@@ -18,7 +17,6 @@ interface BudgetsPageProps {
categories: BudgetCategory[];
selectedPeriod: string;
periodLabel: string;
periodPreferences: PeriodPreferences;
}
export function BudgetsPage({
@@ -26,7 +24,6 @@ export function BudgetsPage({
categories,
selectedPeriod,
periodLabel,
periodPreferences,
}: BudgetsPageProps) {
const [editOpen, setEditOpen] = useState(false);
const [selectedBudget, setSelectedBudget] = useState<Budget | null>(null);
@@ -94,7 +91,6 @@ export function BudgetsPage({
mode="create"
categories={categories}
defaultPeriod={selectedPeriod}
periodPreferences={periodPreferences}
trigger={
<Button disabled={categories.length === 0}>
<RiAddCircleLine className="size-4" />
@@ -132,7 +128,6 @@ export function BudgetsPage({
budget={selectedBudget ?? undefined}
categories={categories}
defaultPeriod={selectedPeriod}
periodPreferences={periodPreferences}
open={editOpen && !!selectedBudget}
onOpenChange={handleEditOpenChange}
/>

View File

@@ -0,0 +1,91 @@
"use client";
import { Button } from "@/components/ui/button";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { MonthPicker } from "@/components/ui/monthpicker";
import { RiCalendarLine } from "@remixicon/react";
import { useState } from "react";
import { format } from "date-fns";
import { ptBR } from "date-fns/locale";
import { cn } from "@/lib/utils/ui";
interface PeriodPickerProps {
value: string; // "YYYY-MM" format
onChange: (value: string) => void;
disabled?: boolean;
className?: string;
placeholder?: string;
variant?: "default" | "outline" | "ghost";
size?: "default" | "sm" | "lg";
}
export function PeriodPicker({
value,
onChange,
disabled = false,
className,
placeholder = "Selecione o período",
variant = "outline",
size = "default",
}: PeriodPickerProps) {
const [open, setOpen] = 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 formatDisplay = (period: string): string => {
try {
const date = periodToDate(period);
return format(date, "MMMM yyyy", { locale: ptBR });
} catch {
return placeholder;
}
};
const handleSelect = (date: Date) => {
const period = dateToPeriod(date);
onChange(period);
setOpen(false);
};
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant={variant}
size={size}
disabled={disabled}
className={cn(
"justify-start text-left font-normal capitalize",
!value && "text-muted-foreground",
className
)}
>
<RiCalendarLine className="h-4 w-4" />
{value ? formatDisplay(value) : placeholder}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<MonthPicker
selectedMonth={value ? periodToDate(value) : new Date()}
onMonthSelect={handleSelect}
/>
</PopoverContent>
</Popover>
);
}

View 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>
);
}

View 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>
);
}

View 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>
);
}

View 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>
);
}

View 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>
);
}

View 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>
);
}

View 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>
);
}

View 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";

View 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;
}

View File

@@ -5,9 +5,9 @@ import {
RiBankLine,
RiCalendarEventLine,
RiDashboardLine,
RiFileChartLine,
RiFundsLine,
RiGroupLine,
RiLineChartLine,
RiPriceTag3Line,
RiSettingsLine,
RiSparklingLine,
@@ -125,14 +125,6 @@ export function createSidebarNavData(pagadores: PagadorLike[]): SidebarNavData {
title: "Categorias",
url: "/categorias",
icon: RiPriceTag3Line,
items: [
{
title: "Histórico",
url: "/categorias/historico",
key: "historico-categorias",
icon: RiLineChartLine,
},
],
},
],
},
@@ -159,6 +151,16 @@ export function createSidebarNavData(pagadores: PagadorLike[]): SidebarNavData {
},
],
},
{
title: "Relatórios",
items: [
{
title: "Categorias",
url: "/relatorios/categorias",
icon: RiFileChartLine,
},
],
},
],
navSecondary: [
// {

View File

@@ -0,0 +1,193 @@
import { Skeleton } from "@/components/ui/skeleton";
import { Card } from "@/components/ui/card";
import {
Table,
TableBody,
TableCell,
TableFooter,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
/**
* Skeleton para a página de relatórios de categorias
* Mantém a mesma estrutura de filtros, tabs e conteúdo
*/
export function CategoryReportSkeleton() {
return (
<div className="flex flex-col gap-6">
{/* Filters Skeleton */}
<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 MultiSelect */}
<Skeleton className="h-10 w-[200px] rounded-2xl bg-foreground/10" />
{/* Start Period */}
<Skeleton className="h-10 w-[150px] rounded-2xl bg-foreground/10" />
{/* End Period */}
<Skeleton className="h-10 w-[150px] rounded-2xl bg-foreground/10" />
{/* Clear Button */}
<Skeleton className="h-8 w-16 rounded-2xl bg-foreground/10" />
</div>
{/* Export Button */}
<Skeleton className="h-10 w-[120px] rounded-2xl bg-foreground/10" />
</div>
</div>
{/* Tabs Skeleton */}
<Tabs value="table" className="w-full">
<TabsList>
<div className="flex gap-1">
<Skeleton className="h-10 w-[100px] rounded-2xl bg-foreground/10" />
<Skeleton className="h-10 w-[100px] rounded-2xl bg-foreground/10" />
</div>
</TabsList>
<TabsContent value="table" className="mt-4">
{/* Desktop Table Skeleton */}
<div className="hidden md:block">
<CategoryReportTableSkeleton />
</div>
{/* Mobile Cards Skeleton */}
<div className="md:hidden space-y-3">
{Array.from({ length: 5 }).map((_, i) => (
<Card key={i} className="p-4">
<div className="space-y-3">
{/* Category name with icon */}
<div className="flex items-center gap-2">
<Skeleton className="size-4 rounded-2xl bg-foreground/10" />
<Skeleton className="h-5 w-32 rounded-2xl bg-foreground/10" />
</div>
{/* Type badge */}
<Skeleton className="h-6 w-20 rounded-2xl bg-foreground/10" />
{/* Values */}
<div className="space-y-2">
{Array.from({ length: 3 }).map((_, j) => (
<div
key={j}
className="flex items-center justify-between"
>
<Skeleton className="h-4 w-24 rounded-2xl bg-foreground/10" />
<Skeleton className="h-4 w-20 rounded-2xl bg-foreground/10" />
</div>
))}
</div>
</div>
</Card>
))}
</div>
</TabsContent>
<TabsContent value="chart" className="mt-4">
{/* Chart Skeleton */}
<Card className="p-6">
<div className="space-y-4">
{/* Chart title area */}
<div className="flex items-center justify-between">
<Skeleton className="h-6 w-48 rounded-2xl bg-foreground/10" />
<Skeleton className="h-8 w-32 rounded-2xl bg-foreground/10" />
</div>
{/* Chart area */}
<Skeleton className="h-[400px] w-full rounded-2xl bg-foreground/10" />
{/* Legend */}
<div className="flex flex-wrap gap-4 justify-center">
{Array.from({ length: 6 }).map((_, i) => (
<div key={i} className="flex items-center gap-2">
<Skeleton className="size-3 rounded-full bg-foreground/10" />
<Skeleton className="h-4 w-20 rounded-2xl bg-foreground/10" />
</div>
))}
</div>
</div>
</Card>
</TabsContent>
</Tabs>
</div>
);
}
/**
* Skeleton para a tabela de relatórios de categorias
* Mantém a estrutura de colunas: Categoria, Tipo, múltiplos períodos, Total
*/
function CategoryReportTableSkeleton() {
// Simula 6 períodos (colunas)
const periodColumns = 6;
return (
<Card className="px-6 py-4">
<Table>
<TableHeader>
<TableRow>
{/* Categoria */}
<TableHead className="w-[280px] min-w-[280px]">
<Skeleton className="h-4 w-20 rounded-2xl bg-foreground/10" />
</TableHead>
{/* Period columns */}
{Array.from({ length: periodColumns }).map((_, i) => (
<TableHead key={i} className="text-right min-w-[120px]">
<Skeleton className="h-4 w-16 rounded-2xl bg-foreground/10 ml-auto" />
</TableHead>
))}
{/* Total */}
<TableHead className="text-right min-w-[120px]">
<Skeleton className="h-4 w-10 rounded-2xl bg-foreground/10 ml-auto" />
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{Array.from({ length: 8 }).map((_, rowIndex) => (
<TableRow key={rowIndex}>
{/* Category name with dot and icon */}
<TableCell>
<div className="flex items-center gap-2">
<Skeleton className="size-2 rounded-full bg-foreground/10" />
<Skeleton className="size-4 rounded-2xl bg-foreground/10" />
<Skeleton className="h-4 w-32 rounded-2xl bg-foreground/10" />
</div>
</TableCell>
{/* Period values */}
{Array.from({ length: periodColumns }).map((_, colIndex) => (
<TableCell key={colIndex} className="text-right">
<div className="flex flex-col items-end gap-1">
<Skeleton className="h-4 w-20 rounded-2xl bg-foreground/10" />
{colIndex > 0 && (
<Skeleton className="h-3 w-16 rounded-2xl bg-foreground/10" />
)}
</div>
</TableCell>
))}
{/* Total */}
<TableCell className="text-right">
<Skeleton className="h-4 w-24 rounded-2xl bg-foreground/10" />
</TableCell>
</TableRow>
))}
</TableBody>
<TableFooter>
<TableRow>
{/* Total label */}
<TableCell className="font-bold">
<Skeleton className="h-5 w-16 rounded-2xl bg-foreground/10" />
</TableCell>
{/* Period totals */}
{Array.from({ length: periodColumns }).map((_, i) => (
<TableCell key={i} className="text-right">
<Skeleton className="h-5 w-24 rounded-2xl bg-foreground/10 ml-auto" />
</TableCell>
))}
{/* Grand total */}
<TableCell className="text-right">
<Skeleton className="h-5 w-28 rounded-2xl bg-foreground/10 ml-auto" />
</TableCell>
</TableRow>
</TableFooter>
</Table>
</Card>
);
}

View File

@@ -3,6 +3,7 @@
* Facilita a importação em outros componentes
*/
export { AccountStatementCardSkeleton } from "./account-statement-card-skeleton";
export { CategoryReportSkeleton } from "./category-report-skeleton";
export { DashboardGridSkeleton } from "./dashboard-grid-skeleton";
export { FilterSkeleton } from "./filter-skeleton";
export { InvoiceSummaryCardSkeleton } from "./invoice-summary-card-skeleton";

View File

@@ -37,13 +37,13 @@ export function TypeBadge({ type, className }: TypeBadgeProps) {
const colorClass = isTransferencia
? "text-blue-700 dark:text-blue-400"
: (isReceita || isSaldoInicial)
: isReceita || isSaldoInicial
? "text-green-700 dark:text-green-400"
: "text-red-700 dark:text-red-400";
const dotColor = isTransferencia
? "bg-blue-700 dark:bg-blue-400"
: (isReceita || isSaldoInicial)
: isReceita || isSaldoInicial
? "bg-green-600 dark:bg-green-400"
: "bg-red-600 dark:bg-red-400";

View File

@@ -1,11 +1,11 @@
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import * as React from "react";
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils/ui";
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive hover:scale-105 transition-transform",
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {
variant: {
@@ -34,27 +34,29 @@ const buttonVariants = cva(
size: "default",
},
}
);
)
function Button({
className,
variant,
size,
variant = "default",
size = "default",
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean;
asChild?: boolean
}) {
const Comp = asChild ? Slot : "button";
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="button"
data-variant={variant}
data-size={size}
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
);
)
}
export { Button, buttonVariants };
export { Button, buttonVariants }

View File

@@ -0,0 +1,219 @@
"use client";
import * as React from "react";
import { RiArrowLeftSFill, RiArrowRightSFill } from "@remixicon/react";
import { buttonVariants } from "./button";
import { cn } from "@/lib/utils/ui";
type Month = {
number: number;
name: string;
};
const MONTHS: Month[][] = [
[
{ number: 0, name: "Jan" },
{ number: 1, name: "Fev" },
{ number: 2, name: "Mar" },
{ number: 3, name: "Abr" },
],
[
{ number: 4, name: "Mai" },
{ number: 5, name: "Jun" },
{ number: 6, name: "Jul" },
{ number: 7, name: "Ago" },
],
[
{ number: 8, name: "Set" },
{ number: 9, name: "Out" },
{ number: 10, name: "Nov" },
{ number: 11, name: "Dez" },
],
];
type MonthCalProps = {
selectedMonth?: Date;
onMonthSelect?: (date: Date) => void;
onYearForward?: () => void;
onYearBackward?: () => void;
callbacks?: {
yearLabel?: (year: number) => string;
monthLabel?: (month: Month) => string;
};
variant?: {
calendar?: {
main?: ButtonVariant;
selected?: ButtonVariant;
};
chevrons?: ButtonVariant;
};
minDate?: Date;
maxDate?: Date;
disabledDates?: Date[];
};
type ButtonVariant =
| "default"
| "outline"
| "ghost"
| "link"
| "destructive"
| "secondary"
| null
| undefined;
function MonthPicker({
onMonthSelect,
selectedMonth,
minDate,
maxDate,
disabledDates,
callbacks,
onYearBackward,
onYearForward,
variant,
className,
...props
}: React.HTMLAttributes<HTMLDivElement> & MonthCalProps) {
return (
<div className={cn("min-w-[200px] w-[280px] p-3", className)} {...props}>
<div className="flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0">
<div className="space-y-4 w-full">
<MonthCal
onMonthSelect={onMonthSelect}
callbacks={callbacks}
selectedMonth={selectedMonth}
onYearBackward={onYearBackward}
onYearForward={onYearForward}
variant={variant}
minDate={minDate}
maxDate={maxDate}
disabledDates={disabledDates}
></MonthCal>
</div>
</div>
</div>
);
}
function MonthCal({
selectedMonth,
onMonthSelect,
callbacks,
variant,
minDate,
maxDate,
disabledDates,
onYearBackward,
onYearForward,
}: MonthCalProps) {
const [year, setYear] = React.useState<number>(
selectedMonth?.getFullYear() ?? new Date().getFullYear()
);
const [month, setMonth] = React.useState<number>(
selectedMonth?.getMonth() ?? new Date().getMonth()
);
const [menuYear, setMenuYear] = React.useState<number>(year);
if (minDate && maxDate && minDate > maxDate) minDate = maxDate;
const disabledDatesMapped = disabledDates?.map((d) => {
return { year: d.getFullYear(), month: d.getMonth() };
});
return (
<>
<div className="flex justify-center pt-1 relative items-center">
<div className="text-sm font-bold">
{callbacks?.yearLabel ? callbacks?.yearLabel(menuYear) : menuYear}
</div>
<div className="space-x-1 flex items-center">
<button
onClick={() => {
setMenuYear(menuYear - 1);
if (onYearBackward) onYearBackward();
}}
className={cn(
buttonVariants({ variant: variant?.chevrons ?? "outline" }),
"inline-flex items-center justify-center h-7 w-7 p-0 absolute left-1"
)}
>
<RiArrowLeftSFill className="opacity-50 size-4" />
</button>
<button
onClick={() => {
setMenuYear(menuYear + 1);
if (onYearForward) onYearForward();
}}
className={cn(
buttonVariants({ variant: variant?.chevrons ?? "outline" }),
"inline-flex items-center justify-center h-7 w-7 p-0 absolute right-1"
)}
>
<RiArrowRightSFill className="opacity-50 size-4" />
</button>
</div>
</div>
<table className="w-full border-collapse space-y-1">
<tbody>
{MONTHS.map((monthRow, a) => {
return (
<tr key={"row-" + a} className="flex w-full mt-2">
{monthRow.map((m) => {
return (
<td
key={m.number}
className="h-10 w-1/4 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20"
>
<button
onClick={() => {
setMonth(m.number);
setYear(menuYear);
if (onMonthSelect)
onMonthSelect(new Date(menuYear, m.number));
}}
disabled={
(maxDate
? menuYear > maxDate?.getFullYear() ||
(menuYear == maxDate?.getFullYear() &&
m.number > maxDate.getMonth())
: false) ||
(minDate
? menuYear < minDate?.getFullYear() ||
(menuYear == minDate?.getFullYear() &&
m.number < minDate.getMonth())
: false) ||
(disabledDatesMapped
? disabledDatesMapped?.some(
(d) => d.year == menuYear && d.month == m.number
)
: false)
}
className={cn(
buttonVariants({
variant:
month == m.number && menuYear == year
? variant?.calendar?.selected ?? "default"
: variant?.calendar?.main ?? "ghost",
}),
"h-full w-full p-0 font-normal aria-selected:opacity-100"
)}
>
{callbacks?.monthLabel
? callbacks.monthLabel(m)
: m.name}
</button>
</td>
);
})}
</tr>
);
})}
</tbody>
</table>
</>
);
}
MonthPicker.displayName = "MonthPicker";
export { MonthPicker };

View File

@@ -386,7 +386,7 @@ function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
<div
data-slot="sidebar-group"
data-sidebar="group"
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
className={cn("relative flex w-full min-w-0 flex-col px-2 py-1", className)}
{...props}
/>
);