feat(reports): melhora notas, calendario e analises

This commit is contained in:
Felipe Coutinho
2026-03-09 17:14:04 +00:00
parent ada1377640
commit 6205dee42a
35 changed files with 429 additions and 590 deletions

View File

@@ -8,15 +8,11 @@ import {
RiInboxUnarchiveLine,
RiPencilLine,
} from "@remixicon/react";
import { useMemo } from "react";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardFooter } from "@/components/ui/card";
import { buildNoteDisplayTitle } from "@/lib/notes/formatters";
import { type Note, sortTasksByStatus } from "./types";
const DATE_FORMATTER = new Intl.DateTimeFormat("pt-BR", {
dateStyle: "medium",
});
interface NoteCardProps {
note: Note;
onEdit?: (note: Note) => void;
@@ -34,20 +30,10 @@ export function NoteCard({
onArquivar,
isArquivadas = false,
}: NoteCardProps) {
const { displayTitle } = useMemo(() => {
const resolvedTitle = note.title.trim().length
? note.title
: "Anotação sem título";
return {
displayTitle: resolvedTitle,
formattedDate: DATE_FORMATTER.format(new Date(note.createdAt)),
};
}, [note.createdAt, note.title]);
const displayTitle = buildNoteDisplayTitle(note.title);
const isTask = note.type === "tarefa";
const tasks = note.tasks || [];
const sortedTasks = useMemo(() => sortTasksByStatus(tasks), [tasks]);
const sortedTasks = sortTasksByStatus(tasks);
const completedCount = tasks.filter((t) => t.completed).length;
const totalCount = tasks.length;

View File

@@ -1,7 +1,6 @@
"use client";
import { RiCheckLine } from "@remixicon/react";
import { useMemo } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
@@ -13,14 +12,13 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
buildNoteDisplayTitle,
formatNoteCreatedAtLong,
} from "@/lib/notes/formatters";
import { Card } from "../ui/card";
import { type Note, sortTasksByStatus } from "./types";
const DATE_FORMATTER = new Intl.DateTimeFormat("pt-BR", {
dateStyle: "long",
timeStyle: "short",
});
interface NoteDetailsDialogProps {
note: Note | null;
open: boolean;
@@ -32,26 +30,14 @@ export function NoteDetailsDialog({
open,
onOpenChange,
}: NoteDetailsDialogProps) {
const { formattedDate, displayTitle } = useMemo(() => {
if (!note) {
return { formattedDate: "", displayTitle: "" };
}
const title = note.title.trim().length ? note.title : "Anotação sem título";
return {
formattedDate: DATE_FORMATTER.format(new Date(note.createdAt)),
displayTitle: title,
};
}, [note]);
const tasks = note?.tasks || [];
const sortedTasks = useMemo(() => sortTasksByStatus(tasks), [tasks]);
if (!note) {
return null;
}
const formattedDate = formatNoteCreatedAtLong(note.createdAt) ?? "";
const displayTitle = buildNoteDisplayTitle(note.title);
const tasks = note.tasks || [];
const sortedTasks = sortTasksByStatus(tasks);
const isTask = note.type === "tarefa";
const completedCount = tasks.filter((t) => t.completed).length;
const totalCount = tasks.length;

View File

@@ -1,13 +1,13 @@
"use client";
import { RiAddCircleLine, RiTodoLine } from "@remixicon/react";
import { useCallback, useMemo, useState } from "react";
import { useMemo, useState } from "react";
import { toast } from "sonner";
import {
arquivarAnotacaoAction,
deleteNoteAction,
} from "@/app/(dashboard)/anotacoes/actions";
import { ConfirmActionDialog } from "@/components/confirm-action-dialog";
import { ConfirmActionDialog } from "@/components/shared/confirm-action-dialog";
import { EmptyState } from "@/components/shared/empty-state";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
@@ -34,76 +34,78 @@ export function NotesPage({ notes, archivedNotes }: NotesPageProps) {
const [arquivarOpen, setArquivarOpen] = useState(false);
const [noteToArquivar, setNoteToArquivar] = useState<Note | null>(null);
const sortNotes = useCallback(
(list: Note[]) =>
[...list].sort(
const sortedNotes = useMemo(
() =>
[...notes].sort(
(a, b) =>
new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
),
[],
[notes],
);
const sortedNotes = useMemo(() => sortNotes(notes), [notes, sortNotes]);
const sortedArchivedNotes = useMemo(
() => sortNotes(archivedNotes),
[archivedNotes, sortNotes],
() =>
[...archivedNotes].sort(
(a, b) =>
new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
),
[archivedNotes],
);
const isArquivadas = activeTab === "arquivadas";
const handleCreateOpenChange = useCallback((open: boolean) => {
const handleCreateOpenChange = (open: boolean) => {
setCreateOpen(open);
}, []);
};
const handleEditOpenChange = useCallback((open: boolean) => {
const handleEditOpenChange = (open: boolean) => {
setEditOpen(open);
if (!open) {
setNoteToEdit(null);
}
}, []);
};
const handleDetailsOpenChange = useCallback((open: boolean) => {
const handleDetailsOpenChange = (open: boolean) => {
setDetailsOpen(open);
if (!open) {
setNoteDetails(null);
}
}, []);
};
const handleRemoveOpenChange = useCallback((open: boolean) => {
const handleRemoveOpenChange = (open: boolean) => {
setRemoveOpen(open);
if (!open) {
setNoteToRemove(null);
}
}, []);
};
const handleArquivarOpenChange = useCallback((open: boolean) => {
const handleArquivarOpenChange = (open: boolean) => {
setArquivarOpen(open);
if (!open) {
setNoteToArquivar(null);
}
}, []);
};
const handleEditRequest = useCallback((note: Note) => {
const handleEditRequest = (note: Note) => {
setNoteToEdit(note);
setEditOpen(true);
}, []);
};
const handleDetailsRequest = useCallback((note: Note) => {
const handleDetailsRequest = (note: Note) => {
setNoteDetails(note);
setDetailsOpen(true);
}, []);
};
const handleRemoveRequest = useCallback((note: Note) => {
const handleRemoveRequest = (note: Note) => {
setNoteToRemove(note);
setRemoveOpen(true);
}, []);
};
const handleArquivarRequest = useCallback((note: Note) => {
const handleArquivarRequest = (note: Note) => {
setNoteToArquivar(note);
setArquivarOpen(true);
}, []);
};
const handleArquivarConfirm = useCallback(async () => {
const handleArquivarConfirm = async () => {
if (!noteToArquivar) {
return;
}
@@ -120,9 +122,9 @@ export function NotesPage({ notes, archivedNotes }: NotesPageProps) {
toast.error(result.error);
throw new Error(result.error);
}, [noteToArquivar, isArquivadas]);
};
const handleRemoveConfirm = useCallback(async () => {
const handleRemoveConfirm = async () => {
if (!noteToRemove) {
return;
}
@@ -136,7 +138,7 @@ export function NotesPage({ notes, archivedNotes }: NotesPageProps) {
toast.error(result.error);
throw new Error(result.error);
}, [noteToRemove]);
};
const removeTitle = noteToRemove
? noteToRemove.title.trim().length

View File

@@ -2,8 +2,8 @@
import { DayCell } from "@/components/calendario/day-cell";
import type { CalendarDay } from "@/components/calendario/types";
import { WEEK_DAYS_SHORT } from "@/components/calendario/utils";
import type { CalendarDay } from "@/lib/types/calendario";
import { WEEK_DAYS_SHORT } from "@/lib/utils/calendario";
import { cn } from "@/lib/utils/ui";
type CalendarGridProps = {
@@ -18,10 +18,10 @@ export function CalendarGrid({
onCreateDay,
}: CalendarGridProps) {
return (
<div className="overflow-hidden rounded-lg bg-card drop-shadow-xs px-2">
<div className="overflow-hidden rounded-lg bg-card drop-shadow-xs border-none">
<div className="grid grid-cols-7 text-sm font-semibold uppercase tracking-wide text-muted-foreground">
{WEEK_DAYS_SHORT.map((dayName) => (
<span key={dayName} className="px-3 py-2 text-center">
<span key={dayName} className="px-3 py-2 text-center text-primary">
{dayName}
</span>
))}

View File

@@ -1,8 +1,9 @@
"use client";
import { EVENT_TYPE_STYLES } from "@/components/calendario/day-cell";
import type { CalendarEvent } from "@/components/calendario/types";
import { cn } from "@/lib/utils/ui";
import type { CalendarEvent } from "@/lib/types/calendario";
import StatusDot from "../shared/status-dot";
import { Card } from "../ui/card";
const LEGEND_ITEMS: Array<{
type?: CalendarEvent["type"];
@@ -17,17 +18,17 @@ const LEGEND_ITEMS: Array<{
export function CalendarLegend() {
return (
<div className="flex flex-wrap gap-3 rounded-sm border border-border/60 bg-muted/20 p-2 text-xs font-medium text-muted-foreground">
<Card className="flex flex-row gap-2 p-2 text-sm">
{LEGEND_ITEMS.map((item, index) => {
const dotColor =
item.dotColor || (item.type ? EVENT_TYPE_STYLES[item.type].dot : "");
return (
<span key={item.type || index} className="flex items-center gap-2">
<span className={cn("size-3 rounded-full", dotColor)} />
<StatusDot color={dotColor} />
{item.label}
</span>
);
})}
</div>
</Card>
);
}

View File

@@ -2,7 +2,7 @@
import { RiAddLine } from "@remixicon/react";
import type { KeyboardEvent, MouseEvent } from "react";
import type { CalendarDay, CalendarEvent } from "@/components/calendario/types";
import type { CalendarDay, CalendarEvent } from "@/lib/types/calendario";
import { currencyFormatter } from "@/lib/lancamentos/formatting-helpers";
import { cn } from "@/lib/utils/ui";

View File

@@ -2,7 +2,7 @@
import type { ReactNode } from "react";
import { EVENT_TYPE_STYLES } from "@/components/calendario/day-cell";
import type { CalendarDay, CalendarEvent } from "@/components/calendario/types";
import MoneyValues from "@/components/shared/money-values";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -12,9 +12,10 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import type { CalendarDay, CalendarEvent } from "@/lib/types/calendario";
import { friendlyDate, parseLocalDateString } from "@/lib/utils/date";
import { formatFinancialDateLabel } from "@/lib/utils/financial-dates";
import { cn } from "@/lib/utils/ui";
import MoneyValues from "../money-values";
import { Badge } from "../ui/badge";
import { Card } from "../ui/card";
@@ -93,9 +94,11 @@ const renderLancamento = (
const renderBoleto = (event: Extract<CalendarEvent, { type: "boleto" }>) => {
const isPaid = Boolean(event.lancamento.isSettled);
const dueDate = event.lancamento.dueDate;
const formattedDueDate = dueDate
? new Intl.DateTimeFormat("pt-BR").format(new Date(dueDate))
: null;
const dueDateLabel = formatFinancialDateLabel(dueDate, "Vence em", {
day: "2-digit",
month: "2-digit",
year: "numeric",
});
return (
<EventCard type="boleto">
@@ -106,9 +109,9 @@ const renderBoleto = (event: Extract<CalendarEvent, { type: "boleto" }>) => {
{event.lancamento.name}
</span>
{formattedDueDate && (
{dueDateLabel && (
<span className="text-xs text-muted-foreground leading-tight">
Vence em {formattedDueDate}
{dueDateLabel}
</span>
)}
</div>

View File

@@ -1,17 +1,18 @@
"use client";
import { useCallback, useMemo, useState } from "react";
import { useMemo, useState } from "react";
import { CalendarGrid } from "@/components/calendario/calendar-grid";
import { CalendarLegend } from "@/components/calendario/calendar-legend";
import { EventModal } from "@/components/calendario/event-modal";
import { LancamentoDialog } from "@/components/lancamentos/dialogs/lancamento-dialog/lancamento-dialog";
import type {
CalendarDay,
CalendarEvent,
CalendarFormOptions,
CalendarPeriod,
} from "@/components/calendario/types";
import { buildCalendarDays } from "@/components/calendario/utils";
import { LancamentoDialog } from "@/components/lancamentos/dialogs/lancamento-dialog/lancamento-dialog";
} from "@/lib/types/calendario";
import { buildCalendarDays } from "@/lib/utils/calendario";
import { parsePeriod } from "@/lib/utils/period";
type MonthlyCalendarProps = {
period: CalendarPeriod;
@@ -19,23 +20,13 @@ type MonthlyCalendarProps = {
formOptions: CalendarFormOptions;
};
const parsePeriod = (period: string) => {
const [yearStr, monthStr] = period.split("-");
const year = Number.parseInt(yearStr ?? "", 10);
const month = Number.parseInt(monthStr ?? "", 10);
return { year, monthIndex: month - 1 };
};
export function MonthlyCalendar({
period,
events,
formOptions,
}: MonthlyCalendarProps) {
const { year, monthIndex } = useMemo(
() => parsePeriod(period.period),
[period.period],
);
const { year, month } = parsePeriod(period.period);
const monthIndex = month - 1;
const eventsByDay = useMemo(() => {
const map = new Map<string, CalendarEvent[]>();
@@ -57,35 +48,32 @@ export function MonthlyCalendar({
const [createOpen, setCreateOpen] = useState(false);
const [createDate, setCreateDate] = useState<string | null>(null);
const handleOpenCreate = useCallback((date: string) => {
const handleOpenCreate = (date: string) => {
setCreateDate(date);
setModalOpen(false);
setCreateOpen(true);
}, []);
};
const handleDaySelect = useCallback((day: CalendarDay) => {
const handleDaySelect = (day: CalendarDay) => {
setSelectedDay(day);
setModalOpen(true);
}, []);
};
const handleCreateFromCell = useCallback(
(day: CalendarDay) => {
handleOpenCreate(day.date);
},
[handleOpenCreate],
);
const handleCreateFromCell = (day: CalendarDay) => {
handleOpenCreate(day.date);
};
const handleModalClose = useCallback(() => {
const handleModalClose = () => {
setModalOpen(false);
setSelectedDay(null);
}, []);
};
const handleCreateDialogChange = useCallback((open: boolean) => {
const handleCreateDialogChange = (open: boolean) => {
setCreateOpen(open);
if (!open) {
setCreateDate(null);
}
}, []);
};
return (
<>

View File

@@ -1,62 +0,0 @@
import type {
LancamentoItem,
SelectOption,
} from "@/components/lancamentos/types";
export type CalendarEvent =
| {
id: string;
type: "lancamento";
date: string;
lancamento: LancamentoItem;
}
| {
id: string;
type: "boleto";
date: string;
lancamento: LancamentoItem;
}
| {
id: string;
type: "cartao";
date: string;
card: {
id: string;
name: string;
dueDay: string;
closingDay: string;
brand: string | null;
status: string;
logo: string | null;
totalDue: number | null;
};
};
export type CalendarPeriod = {
period: string;
monthName: string;
year: number;
};
export type CalendarDay = {
date: string;
label: string;
isCurrentMonth: boolean;
isToday: boolean;
events: CalendarEvent[];
};
export type CalendarFormOptions = {
pagadorOptions: SelectOption[];
splitPagadorOptions: SelectOption[];
defaultPagadorId: string | null;
contaOptions: SelectOption[];
cartaoOptions: SelectOption[];
categoriaOptions: SelectOption[];
estabelecimentos: string[];
};
export type CalendarData = {
events: CalendarEvent[];
formOptions: CalendarFormOptions;
};

View File

@@ -1,60 +0,0 @@
import type { CalendarDay, CalendarEvent } from "@/components/calendario/types";
export const formatDateKey = (date: Date) => date.toISOString().slice(0, 10);
const getWeekdayIndex = (date: Date) => {
const day = date.getUTCDay(); // 0 (domingo) - 6 (sábado)
// Ajusta para segunda-feira como primeiro dia
return day === 0 ? 6 : day - 1;
};
export const buildCalendarDays = ({
year,
monthIndex,
events,
}: {
year: number;
monthIndex: number;
events: Map<string, CalendarEvent[]>;
}): CalendarDay[] => {
const startOfMonth = new Date(Date.UTC(year, monthIndex, 1));
const offset = getWeekdayIndex(startOfMonth);
const startDate = new Date(Date.UTC(year, monthIndex, 1 - offset));
const totalCells = 42; // 6 semanas
const now = new Date();
const todayKey = formatDateKey(
new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate())),
);
const days: CalendarDay[] = [];
for (let index = 0; index < totalCells; index += 1) {
const currentDate = new Date(startDate);
currentDate.setUTCDate(startDate.getUTCDate() + index);
const dateKey = formatDateKey(currentDate);
const isCurrentMonth = currentDate.getUTCMonth() === monthIndex;
const dateLabel = currentDate.getUTCDate().toString();
const eventsForDay = events.get(dateKey) ?? [];
days.push({
date: dateKey,
label: dateLabel,
isCurrentMonth,
isToday: dateKey === todayKey,
events: eventsForDay,
});
}
return days;
};
export const WEEK_DAYS_SHORT = [
"Seg",
"Ter",
"Qua",
"Qui",
"Sex",
"Sáb",
"Dom",
];

View File

@@ -6,14 +6,13 @@ import {
RiLightbulbLine,
RiRocketLine,
} from "@remixicon/react";
import { format } from "date-fns";
import { ptBR } from "date-fns/locale";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import type {
InsightCategoryId,
InsightsResponse,
} from "@/lib/schemas/insights";
import { INSIGHT_CATEGORIES } from "@/lib/schemas/insights";
import { displayPeriod } from "@/lib/utils/period";
import { cn } from "@/lib/utils/ui";
interface InsightsGridProps {
@@ -50,12 +49,7 @@ const CATEGORY_COLORS: Record<
};
export function InsightsGrid({ insights }: InsightsGridProps) {
// Formatar o período para exibição
const [year, month] = insights.month.split("-");
const periodDate = new Date(parseInt(year, 10), parseInt(month, 10) - 1);
const formattedPeriod = format(periodDate, "MMMM 'de' yyyy", {
locale: ptBR,
});
const formattedPeriod = displayPeriod(insights.month);
return (
<div className="space-y-6">

View File

@@ -2,10 +2,10 @@
import { RiPieChartLine } from "@remixicon/react";
import { CategoryIconBadge } from "@/components/categorias/category-icon-badge";
import MoneyValues from "@/components/money-values";
import MoneyValues from "@/components/shared/money-values";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { WidgetEmptyState } from "@/components/widget-empty-state";
import { WidgetEmptyState } from "@/components/shared/widget-empty-state";
import type { CardDetailData } from "@/lib/relatorios/cartoes-report";
type CardCategoryBreakdownProps = {

View File

@@ -10,36 +10,14 @@ import {
} from "@/components/ui/tooltip";
import type { CardDetailData } from "@/lib/relatorios/cartoes-report";
import { cn } from "@/lib/utils";
import { formatCurrency } from "@/lib/utils/currency";
import { formatPeriodMonthShort } from "@/lib/utils/period";
type CardInvoiceStatusProps = {
data: CardDetailData["invoiceStatus"];
};
const monthLabels = [
"Jan",
"Fev",
"Mar",
"Abr",
"Mai",
"Jun",
"Jul",
"Ago",
"Set",
"Out",
"Nov",
"Dez",
];
export function CardInvoiceStatus({ data }: CardInvoiceStatusProps) {
const formatCurrency = (value: number) => {
return new Intl.NumberFormat("pt-BR", {
style: "currency",
currency: "BRL",
minimumFractionDigits: 0,
maximumFractionDigits: 0,
}).format(value);
};
const getStatusColor = (status: string | null) => {
switch (status) {
case "pago":
@@ -66,11 +44,6 @@ export function CardInvoiceStatus({ data }: CardInvoiceStatusProps) {
}
};
const formatPeriodShort = (period: string) => {
const [, month] = period.split("-");
return monthLabels[parseInt(month, 10) - 1];
};
return (
<Card>
<CardHeader className="pb-2">
@@ -93,13 +66,16 @@ export function CardInvoiceStatus({ data }: CardInvoiceStatusProps) {
)}
/>
<span className="text-xs text-muted-foreground">
{formatPeriodShort(invoice.period)}
{formatPeriodMonthShort(invoice.period)}
</span>
</div>
</TooltipTrigger>
<TooltipContent side="top">
<p className="font-medium">
{formatCurrency(invoice.amount)}
{formatCurrency(invoice.amount, {
maximumFractionDigits: 0,
minimumFractionDigits: 0,
})}
</p>
<p className="text-xs ">{getStatusLabel(invoice.status)}</p>
</TooltipContent>

View File

@@ -1,11 +1,11 @@
"use client";
import { RiShoppingBag3Line } from "@remixicon/react";
import MoneyValues from "@/components/money-values";
import MoneyValues from "@/components/shared/money-values";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { WidgetEmptyState } from "@/components/widget-empty-state";
import { WidgetEmptyState } from "@/components/shared/widget-empty-state";
import type { CardDetailData } from "@/lib/relatorios/cartoes-report";
type CardTopExpensesProps = {

View File

@@ -16,7 +16,10 @@ import {
ChartContainer,
ChartTooltip,
} from "@/components/ui/chart";
import { resolveLogoSrc } from "@/lib/logo";
import type { CardDetailData } from "@/lib/relatorios/cartoes-report";
import { formatCurrency, formatCurrencyCompact } from "@/lib/utils/currency";
import { formatPercentage } from "@/lib/utils/percentage";
type CardUsageChartProps = {
data: CardDetailData["monthlyUsage"];
@@ -34,48 +37,14 @@ const chartConfig = {
},
} satisfies ChartConfig;
const resolveLogoPath = (logo: string | null) => {
if (!logo) return null;
if (
logo.startsWith("http://") ||
logo.startsWith("https://") ||
logo.startsWith("data:")
) {
return logo;
}
return logo.startsWith("/") ? logo : `/logos/${logo}`;
};
export function CardUsageChart({ data, limit, card }: CardUsageChartProps) {
const formatCurrency = (value: number) => {
return new Intl.NumberFormat("pt-BR", {
style: "currency",
currency: "BRL",
minimumFractionDigits: 0,
maximumFractionDigits: 0,
}).format(value);
};
const formatCurrencyCompact = (value: number) => {
if (Math.abs(value) >= 1000) {
return new Intl.NumberFormat("pt-BR", {
style: "currency",
currency: "BRL",
minimumFractionDigits: 0,
maximumFractionDigits: 0,
notation: "compact",
}).format(value);
}
return formatCurrency(value);
};
// Always show last 12 months
const chartData = data.slice(-12).map((item) => ({
month: item.periodLabel,
amount: item.amount,
}));
const logoPath = resolveLogoPath(card.logo);
const logoPath = resolveLogoSrc(card.logo);
return (
<Card>
@@ -124,7 +93,17 @@ export function CardUsageChart({ data, limit, card }: CardUsageChartProps) {
axisLine={false}
tickMargin={8}
className="text-xs"
tickFormatter={formatCurrencyCompact}
tickFormatter={(value) =>
Math.abs(Number(value)) >= 1000
? formatCurrencyCompact(Number(value), {
maximumFractionDigits: 0,
minimumFractionDigits: 0,
})
: formatCurrency(Number(value), {
maximumFractionDigits: 0,
minimumFractionDigits: 0,
})
}
/>
{limit > 0 && (
<ReferenceLine
@@ -159,7 +138,10 @@ export function CardUsageChart({ data, limit, card }: CardUsageChartProps) {
Uso
</span>
<span className="text-xs font-medium tabular-nums">
{formatCurrency(value)}
{formatCurrency(value, {
maximumFractionDigits: 0,
minimumFractionDigits: 0,
})}
</span>
</div>
{limit > 0 && (
@@ -168,7 +150,10 @@ export function CardUsageChart({ data, limit, card }: CardUsageChartProps) {
% do Limite
</span>
<span className="text-xs font-medium tabular-nums">
{usagePercent.toFixed(0)}%
{formatPercentage(usagePercent, {
maximumFractionDigits: 0,
minimumFractionDigits: 0,
})}
</span>
</div>
)}

View File

@@ -4,59 +4,24 @@ import { RiBankCard2Line } from "@remixicon/react";
import Image from "next/image";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import MoneyValues from "@/components/money-values";
import MoneyValues from "@/components/shared/money-values";
import { Card, CardContent } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { resolveCardBrandAsset } from "@/lib/cartoes/brand-assets";
import { resolveLogoSrc } from "@/lib/logo";
import type { CartoesReportData } from "@/lib/relatorios/cartoes-report";
import { cn } from "@/lib/utils";
import { formatCurrency } from "@/lib/utils/currency";
import { formatPercentage } from "@/lib/utils/percentage";
type CardsOverviewProps = {
data: CartoesReportData;
};
const BRAND_ASSETS: Record<string, string> = {
visa: "/bandeiras/visa.svg",
mastercard: "/bandeiras/mastercard.svg",
amex: "/bandeiras/amex.svg",
american: "/bandeiras/amex.svg",
elo: "/bandeiras/elo.svg",
hipercard: "/bandeiras/hipercard.svg",
hiper: "/bandeiras/hipercard.svg",
};
const resolveBrandAsset = (brand: string | null) => {
if (!brand) return null;
const normalized = brand.trim().toLowerCase();
const match = (
Object.keys(BRAND_ASSETS) as Array<keyof typeof BRAND_ASSETS>
).find((entry) => normalized.includes(entry));
return match ? BRAND_ASSETS[match] : null;
};
const resolveLogoPath = (logo: string | null) => {
if (!logo) return null;
if (
logo.startsWith("http://") ||
logo.startsWith("https://") ||
logo.startsWith("data:")
) {
return logo;
}
return logo.startsWith("/") ? logo : `/logos/${logo}`;
};
export function CardsOverview({ data }: CardsOverviewProps) {
const searchParams = useSearchParams();
const periodoParam = searchParams.get("periodo");
const formatCurrency = (value: number) =>
new Intl.NumberFormat("pt-BR", {
style: "currency",
currency: "BRL",
minimumFractionDigits: 0,
maximumFractionDigits: 0,
}).format(value);
const getUsageColor = (percent: number) => {
if (percent < 50) return "bg-success";
if (percent < 80) return "bg-warning";
@@ -107,7 +72,10 @@ export function CardsOverview({ data }: CardsOverviewProps) {
/>
) : (
<p className="text-2xl font-semibold">
{card.value.toFixed(0)}%
{formatPercentage(card.value, {
maximumFractionDigits: 0,
minimumFractionDigits: 0,
})}
</p>
)}
</CardContent>
@@ -120,8 +88,8 @@ export function CardsOverview({ data }: CardsOverviewProps) {
{/* Cards list */}
<div className="grid gap-2 grid-cols-2 lg:grid-cols-4 xl:grid-cols-4">
{data.cards.map((card) => {
const logoPath = resolveLogoPath(card.logo);
const brandAsset = resolveBrandAsset(card.brand);
const logoPath = resolveLogoSrc(card.logo);
const brandAsset = resolveCardBrandAsset(card.brand);
const isSelected = data.selectedCard?.card.id === card.id;
return (
@@ -174,7 +142,10 @@ export function CardsOverview({ data }: CardsOverviewProps) {
)}
/>
<span className="text-xs font-medium tabular-nums">
{card.usagePercent.toFixed(0)}%
{formatPercentage(card.usagePercent, {
maximumFractionDigits: 0,
minimumFractionDigits: 0,
})}
</span>
</div>
</div>

View File

@@ -8,7 +8,7 @@ import { formatCurrency } from "@/lib/lancamentos/formatting-helpers";
import type {
CategoryReportData,
CategoryReportItem,
} from "@/lib/relatorios/types";
} from "@/lib/types/relatorios";
import { formatPeriodLabel } from "@/lib/relatorios/utils";
import { formatPeriodForUrl } from "@/lib/utils/period";
import { CategoryCell } from "./category-cell";
@@ -20,11 +20,18 @@ interface CategoryReportCardsProps {
interface CategoryCardProps {
category: CategoryReportItem;
periods: string[];
periodCount: number;
colorIndex: number;
}
function CategoryCard({ category, periods, colorIndex }: CategoryCardProps) {
function CategoryCard({
category,
periods,
periodCount,
colorIndex,
}: CategoryCardProps) {
const periodParam = formatPeriodForUrl(periods[periods.length - 1]);
const averageMonthlyTotal = category.total / periodCount;
return (
<Card>
@@ -65,6 +72,10 @@ function CategoryCard({ category, periods, colorIndex }: CategoryCardProps) {
</div>
);
})}
<div className="flex items-center justify-between font-semibold text-info">
<span>Média mensal</span>
<span>{formatCurrency(averageMonthlyTotal)}</span>
</div>
<div className="flex items-center justify-between pt-2 font-semibold">
<span>Total</span>
<span>{formatCurrency(category.total)}</span>
@@ -78,6 +89,7 @@ interface SectionProps {
title: string;
categories: CategoryReportItem[];
periods: string[];
periodCount: number;
colorIndexOffset: number;
total: number;
}
@@ -86,6 +98,7 @@ function Section({
title,
categories,
periods,
periodCount,
colorIndexOffset,
total,
}: SectionProps) {
@@ -93,21 +106,29 @@ function Section({
return null;
}
const averageMonthlyTotal = total / periodCount;
return (
<div className="space-y-3">
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
{title}
</span>
<span className="text-sm text-muted-foreground">
{formatCurrency(total)}
</span>
<div className="flex flex-col items-end">
<span className="text-sm text-muted-foreground">
{formatCurrency(total)}
</span>
<span className="text-xs font-semibold text-info">
Média: {formatCurrency(averageMonthlyTotal)}
</span>
</div>
</div>
{categories.map((category, index) => (
<CategoryCard
key={category.categoryId}
category={category}
periods={periods}
periodCount={periodCount}
colorIndex={colorIndexOffset + index}
/>
))}
@@ -117,6 +138,7 @@ function Section({
export function CategoryReportCards({ data }: CategoryReportCardsProps) {
const { categories, periods } = data;
const periodCount = Math.max(periods.length, 1);
// Separate categories by type and calculate totals
const { receitas, despesas, receitasTotal, despesasTotal } = useMemo(() => {
@@ -145,6 +167,7 @@ export function CategoryReportCards({ data }: CategoryReportCardsProps) {
title="Despesas"
categories={despesas}
periods={periods}
periodCount={periodCount}
colorIndexOffset={0}
total={despesasTotal}
/>
@@ -154,6 +177,7 @@ export function CategoryReportCards({ data }: CategoryReportCardsProps) {
title="Receitas"
categories={receitas}
periods={periods}
periodCount={periodCount}
colorIndexOffset={despesas.length}
total={receitasTotal}
/>

View File

@@ -19,11 +19,12 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { formatCurrency } from "@/lib/lancamentos/formatting-helpers";
import type { CategoryReportData } from "@/lib/relatorios/types";
import {
formatPercentageChange,
formatPeriodLabel,
} from "@/lib/relatorios/utils";
import type { CategoryReportData } from "@/lib/types/relatorios";
import { formatDateTime } from "@/lib/utils/date";
import {
getPrimaryPdfColor,
loadExportLogoDataUrl,
@@ -201,8 +202,8 @@ export function CategoryReportExport({
const doc = new jsPDF({ orientation: "landscape" });
const primaryColor = getPrimaryPdfColor();
const [smallLogoDataUrl, textLogoDataUrl] = await Promise.all([
loadExportLogoDataUrl("/logo_small.png"),
loadExportLogoDataUrl("/logo_text.png"),
loadExportLogoDataUrl("/imagens/logo_small.png"),
loadExportLogoDataUrl("/imagens/logo_text.png"),
]);
let brandingEndX = 14;
@@ -232,7 +233,13 @@ export function CategoryReportExport({
22,
);
doc.text(
`Gerado em: ${new Date().toLocaleDateString("pt-BR")}`,
`Gerado em: ${
formatDateTime(new Date(), {
day: "2-digit",
month: "2-digit",
year: "numeric",
}) ?? "—"
}`,
titleX,
27,
);

View File

@@ -5,8 +5,6 @@ import {
RiCheckLine,
RiExpandUpDownLine,
} from "@remixicon/react";
import { format } from "date-fns";
import { ptBR } from "date-fns/locale";
import type { ReactNode } from "react";
import { useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
@@ -26,6 +24,13 @@ import {
} from "@/components/ui/popover";
import { validateDateRange } from "@/lib/relatorios/utils";
import { getIconComponent } from "@/lib/utils/icons";
import {
addMonthsToPeriod,
dateToPeriod,
formatShortPeriodLabel,
getCurrentPeriod,
periodToDate,
} from "@/lib/utils/period";
import type { CategoryReportFiltersProps } from "./types";
/**
@@ -44,25 +49,6 @@ export function CategoryReportFilters({
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;
@@ -126,10 +112,8 @@ export function CategoryReportFilters({
// 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);
const currentPeriod = getCurrentPeriod();
const startPeriod = addMonthsToPeriod(currentPeriod, -5);
onFiltersChange({
selectedCategories: [],
@@ -138,27 +122,19 @@ export function CategoryReportFilters({
});
};
// Validate date range
const validation = useMemo(() => {
if (!filters.startPeriod || !filters.endPeriod) {
return { isValid: true };
}
return validateDateRange(filters.startPeriod, filters.endPeriod);
}, [filters.startPeriod, filters.endPeriod]);
const validation =
!filters.startPeriod || !filters.endPeriod
? { isValid: true }
: validateDateRange(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]);
const selectedText =
selectedCategories.length === 0
? "Categoria"
: selectedCategories.length === categories.length
? "Todas"
: selectedCategories.length === 1
? selectedCategories[0].name
: `${selectedCategories.length} selecionadas`;
return (
<div className="flex flex-col gap-4">
@@ -261,7 +237,7 @@ export function CategoryReportFilters({
disabled={isLoading}
>
<RiCalendarLine className="mr-2 h-4 w-4" />
{formatMonthYear(filters.startPeriod)}
{formatShortPeriodLabel(filters.startPeriod)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
@@ -281,7 +257,7 @@ export function CategoryReportFilters({
disabled={isLoading}
>
<RiCalendarLine className="mr-2 h-4 w-4" />
{formatMonthYear(filters.endPeriod)}
{formatShortPeriodLabel(filters.endPeriod)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">

View File

@@ -6,13 +6,13 @@ import {
RiTable2,
} from "@remixicon/react";
import { useRouter, useSearchParams } from "next/navigation";
import { useCallback, useMemo, useState, useTransition } from "react";
import { useEffect, useRef, useState, useTransition } from "react";
import { EmptyState } from "@/components/shared/empty-state";
import { CategoryReportSkeleton } from "@/components/shared/skeletons/category-report-skeleton";
import { Card } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import type { CategoryChartData } from "@/lib/relatorios/fetch-category-chart-data";
import type { CategoryReportData } from "@/lib/relatorios/types";
import type { CategoryReportData } from "@/lib/types/relatorios";
import { CategoryReportCards } from "./category-report-cards";
import { CategoryReportChart } from "./category-report-chart";
import { CategoryReportExport } from "./category-report-export";
@@ -38,76 +38,62 @@ export function CategoryReportPage({
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 debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const handleFiltersChange = useCallback(
(newFilters: FilterState) => {
setFilters(newFilters);
// Clear existing timer
if (debounceTimer) {
clearTimeout(debounceTimer);
useEffect(() => {
return () => {
if (debounceTimerRef.current) {
clearTimeout(debounceTimerRef.current);
}
};
}, []);
// Set new debounced timer (300ms)
const timer = setTimeout(() => {
startTransition(() => {
// Build new URL with query params
const params = new URLSearchParams(searchParams.toString());
const handleFiltersChange = (newFilters: FilterState) => {
setFilters(newFilters);
params.set("inicio", newFilters.startPeriod);
params.set("fim", newFilters.endPeriod);
if (debounceTimerRef.current) {
clearTimeout(debounceTimerRef.current);
}
if (newFilters.selectedCategories.length > 0) {
params.set("categorias", newFilters.selectedCategories.join(","));
} else {
params.delete("categorias");
}
debounceTimerRef.current = setTimeout(() => {
startTransition(() => {
const params = new URLSearchParams(searchParams.toString());
// Preserve current tab
const currentTab = searchParams.get("aba");
if (currentTab) {
params.set("aba", currentTab);
}
params.set("inicio", newFilters.startPeriod);
params.set("fim", newFilters.endPeriod);
// Navigate with new params (this will trigger server component re-render)
router.push(`?${params.toString()}`, { scroll: false });
});
}, 300);
if (newFilters.selectedCategories.length > 0) {
params.set("categorias", newFilters.selectedCategories.join(","));
} else {
params.delete("categorias");
}
setDebounceTimer(timer);
},
[debounceTimer, router, searchParams],
);
const currentTab = searchParams.get("aba");
if (currentTab) {
params.set("aba", currentTab);
}
// 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],
);
router.push(`?${params.toString()}`, { scroll: false });
});
}, 300);
};
// Update data when initialData changes (from server)
useMemo(() => {
setData(initialData);
}, [initialData]);
const handleTabChange = (value: string) => {
const params = new URLSearchParams(searchParams.toString());
params.set("aba", value);
router.push(`?${params.toString()}`, { scroll: false });
};
// Check if no categories are available
const hasNoCategories = categories.length === 0;
// Check if no data in period
const hasNoData = data.categories.length === 0 && !hasNoCategories;
const hasNoData = initialData.categories.length === 0 && !hasNoCategories;
return (
<div className="flex flex-col gap-6">
@@ -116,7 +102,9 @@ export function CategoryReportPage({
categories={categories}
filters={filters}
onFiltersChange={handleFiltersChange}
exportButton={<CategoryReportExport data={data} filters={filters} />}
exportButton={
<CategoryReportExport data={initialData} filters={filters} />
}
/>
{/* Loading State */}
@@ -180,11 +168,11 @@ export function CategoryReportPage({
<TabsContent value="table" className="mt-4">
{/* Desktop Table */}
<div className="hidden md:block">
<CategoryReportTable data={data} />
<CategoryReportTable data={initialData} />
</div>
{/* Mobile Cards */}
<CategoryReportCards data={data} />
<CategoryReportCards data={initialData} />
</TabsContent>
<TabsContent value="chart" className="mt-4">

View File

@@ -4,7 +4,7 @@ import { useMemo } from "react";
import type {
CategoryReportData,
CategoryReportItem,
} from "@/lib/relatorios/types";
} from "@/lib/types/relatorios";
import { CategoryTable } from "./category-table";
interface CategoryReportTableProps {

View File

@@ -3,6 +3,7 @@
import Link from "next/link";
import { useMemo } from "react";
import { CategoryIconBadge } from "@/components/categorias/category-icon-badge";
import StatusDot from "@/components/shared/status-dot";
import {
Table,
TableBody,
@@ -13,10 +14,9 @@ import {
TableRow,
} from "@/components/ui/table";
import { formatCurrency } from "@/lib/lancamentos/formatting-helpers";
import type { CategoryReportItem } from "@/lib/relatorios/types";
import { formatPeriodLabel } from "@/lib/relatorios/utils";
import type { CategoryReportItem } from "@/lib/types/relatorios";
import { formatPeriodForUrl } from "@/lib/utils/period";
import DotIcon from "../dot-icon";
import { Card } from "../ui/card";
import { CategoryCell } from "./category-cell";
@@ -37,6 +37,7 @@ export function CategoryTable({
const sectionTotals = useMemo(() => {
const totalsMap = new Map<string, number>();
let grandTotal = 0;
const periodCount = Math.max(periods.length, 1);
for (const category of categories) {
grandTotal += category.total;
@@ -47,7 +48,11 @@ export function CategoryTable({
}
}
return { totalsMap, grandTotal };
return {
totalsMap,
grandTotal,
averageMonthlyTotal: grandTotal / periodCount,
};
}, [categories, periods]);
if (categories.length === 0) {
@@ -59,7 +64,7 @@ export function CategoryTable({
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[280px] min-w-[280px] font-bold">
<TableHead className="w-[240px] min-w-[240px] font-bold">
Categoria
</TableHead>
{periods.map((period) => (
@@ -70,6 +75,9 @@ export function CategoryTable({
{formatPeriodLabel(period)}
</TableHead>
))}
<TableHead className="text-right min-w-[140px] font-bold">
Média
</TableHead>
<TableHead className="text-right min-w-[120px] font-bold">
Total
</TableHead>
@@ -85,7 +93,7 @@ export function CategoryTable({
<TableRow key={category.categoryId}>
<TableCell>
<div className="flex items-center gap-2">
<DotIcon
<StatusDot
color={
category.type === "receita"
? "bg-success"
@@ -121,6 +129,9 @@ export function CategoryTable({
</TableCell>
);
})}
<TableCell className="text-right font-semibold text-info">
{formatCurrency(category.total / Math.max(periods.length, 1))}
</TableCell>
<TableCell className="text-right font-semibold">
{formatCurrency(category.total)}
</TableCell>
@@ -140,6 +151,9 @@ export function CategoryTable({
</TableCell>
);
})}
<TableCell className="text-right font-semibold text-info">
{formatCurrency(sectionTotals.averageMonthlyTotal)}
</TableCell>
<TableCell className="text-right font-semibold">
{formatCurrency(sectionTotals.grandTotal)}
</TableCell>

View File

@@ -1,11 +1,11 @@
"use client";
import { RiStore2Line } from "@remixicon/react";
import MoneyValues from "@/components/money-values";
import MoneyValues from "@/components/shared/money-values";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { WidgetEmptyState } from "@/components/widget-empty-state";
import { WidgetEmptyState } from "@/components/shared/widget-empty-state";
import type { TopEstabelecimentosData } from "@/lib/relatorios/estabelecimentos/fetch-data";
type EstablishmentsListProps = {

View File

@@ -6,7 +6,7 @@ import {
RiRepeatLine,
RiStore2Line,
} from "@remixicon/react";
import MoneyValues from "@/components/money-values";
import MoneyValues from "@/components/shared/money-values";
import { Card, CardContent } from "@/components/ui/card";
import type { TopEstabelecimentosData } from "@/lib/relatorios/estabelecimentos/fetch-data";

View File

@@ -2,10 +2,10 @@
import { RiPriceTag3Line } from "@remixicon/react";
import { CategoryIconBadge } from "@/components/categorias/category-icon-badge";
import MoneyValues from "@/components/money-values";
import MoneyValues from "@/components/shared/money-values";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { WidgetEmptyState } from "@/components/widget-empty-state";
import { WidgetEmptyState } from "@/components/shared/widget-empty-state";
import type { TopEstabelecimentosData } from "@/lib/relatorios/estabelecimentos/fetch-data";
type TopCategoriesProps = {