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

@@ -4,7 +4,7 @@ import { and, eq } from "drizzle-orm";
import { z } from "zod"; import { z } from "zod";
import { anotacoes } from "@/db/schema"; import { anotacoes } from "@/db/schema";
import { handleActionError, revalidateForEntity } from "@/lib/actions/helpers"; import { handleActionError, revalidateForEntity } from "@/lib/actions/helpers";
import type { ActionResult } from "@/lib/actions/types"; import type { ActionResult } from "@/lib/types/actions";
import { getUser } from "@/lib/auth/server"; import { getUser } from "@/lib/auth/server";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { uuidSchema } from "@/lib/schemas/common"; import { uuidSchema } from "@/lib/schemas/common";

View File

@@ -1,9 +1,5 @@
import { and, eq, gte, lte, ne, or } from "drizzle-orm"; import { and, eq, gte, lte, ne, or } from "drizzle-orm";
import { getRecentEstablishmentsAction } from "@/app/(dashboard)/lancamentos/actions"; import { getRecentEstablishmentsAction } from "@/app/(dashboard)/lancamentos/actions";
import type {
CalendarData,
CalendarEvent,
} from "@/components/calendario/types";
import { cartoes, lancamentos } from "@/db/schema"; import { cartoes, lancamentos } from "@/db/schema";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { import {
@@ -13,24 +9,13 @@ import {
mapLancamentosData, mapLancamentosData,
} from "@/lib/lancamentos/page-helpers"; } from "@/lib/lancamentos/page-helpers";
import { PAGADOR_ROLE_ADMIN } from "@/lib/pagadores/constants"; import { PAGADOR_ROLE_ADMIN } from "@/lib/pagadores/constants";
import type { CalendarData, CalendarEvent } from "@/lib/types/calendario";
import { formatDateKey } from "@/lib/utils/calendario";
import { parsePeriod } from "@/lib/utils/period";
const PAYMENT_METHOD_BOLETO = "Boleto"; const PAYMENT_METHOD_BOLETO = "Boleto";
const TRANSACTION_TYPE_TRANSFERENCIA = "Transferência"; const TRANSACTION_TYPE_TRANSFERENCIA = "Transferência";
const toDateKey = (date: Date) => date.toISOString().slice(0, 10);
const parsePeriod = (period: string) => {
const [yearStr, monthStr] = period.split("-");
const year = Number.parseInt(yearStr ?? "", 10);
const month = Number.parseInt(monthStr ?? "", 10);
if (Number.isNaN(year) || Number.isNaN(month) || month < 1 || month > 12) {
throw new Error(`Período inválido: ${period}`);
}
return { year, monthIndex: month - 1 };
};
const clampDayInMonth = (year: number, monthIndex: number, day: number) => { const clampDayInMonth = (year: number, monthIndex: number, day: number) => {
const lastDay = new Date(Date.UTC(year, monthIndex + 1, 0)).getUTCDate(); const lastDay = new Date(Date.UTC(year, monthIndex + 1, 0)).getUTCDate();
if (day < 1) return 1; if (day < 1) return 1;
@@ -52,11 +37,12 @@ export const fetchCalendarData = async ({
userId, userId,
period, period,
}: FetchCalendarDataParams): Promise<CalendarData> => { }: FetchCalendarDataParams): Promise<CalendarData> => {
const { year, monthIndex } = parsePeriod(period); const { year, month } = parsePeriod(period);
const monthIndex = month - 1;
const rangeStart = new Date(Date.UTC(year, monthIndex, 1)); const rangeStart = new Date(Date.UTC(year, monthIndex, 1));
const rangeEnd = new Date(Date.UTC(year, monthIndex + 1, 0)); const rangeEnd = new Date(Date.UTC(year, monthIndex + 1, 0));
const rangeStartKey = toDateKey(rangeStart); const rangeStartKey = formatDateKey(rangeStart);
const rangeEndKey = toDateKey(rangeEnd); const rangeEndKey = formatDateKey(rangeEnd);
const [lancamentoRows, cardRows, filterSources] = await Promise.all([ const [lancamentoRows, cardRows, filterSources] = await Promise.all([
db.query.lancamentos.findMany({ db.query.lancamentos.findMany({
@@ -161,7 +147,7 @@ export const fetchCalendarData = async ({
} }
const normalizedDay = clampDayInMonth(year, monthIndex, dueDayNumber); const normalizedDay = clampDayInMonth(year, monthIndex, dueDayNumber);
const dueDateKey = toDateKey( const dueDateKey = formatDateKey(
new Date(Date.UTC(year, monthIndex, normalizedDay)), new Date(Date.UTC(year, monthIndex, normalizedDay)),
); );

View File

@@ -1,11 +1,11 @@
import { MonthlyCalendar } from "@/components/calendario/monthly-calendar"; import { MonthlyCalendar } from "@/components/calendario/monthly-calendar";
import type { CalendarPeriod } from "@/components/calendario/types";
import MonthNavigation from "@/components/month-picker/month-navigation"; import MonthNavigation from "@/components/month-picker/month-navigation";
import { getUserId } from "@/lib/auth/server"; import { getUserId } from "@/lib/auth/server";
import { import {
getSingleParam, getSingleParam,
type ResolvedSearchParams, type ResolvedSearchParams,
} from "@/lib/lancamentos/page-helpers"; } from "@/lib/lancamentos/page-helpers";
import type { CalendarPeriod } from "@/lib/types/calendario";
import { parsePeriodParam } from "@/lib/utils/period"; import { parsePeriodParam } from "@/lib/utils/period";
import { fetchCalendarData } from "./data"; import { fetchCalendarData } from "./data";

View File

@@ -8,7 +8,7 @@ import type { Categoria } from "@/db/schema";
import { getUserId } from "@/lib/auth/server"; import { getUserId } from "@/lib/auth/server";
import { fetchCategoryChartData } from "@/lib/relatorios/fetch-category-chart-data"; import { fetchCategoryChartData } from "@/lib/relatorios/fetch-category-chart-data";
import { fetchCategoryReport } from "@/lib/relatorios/fetch-category-report"; import { fetchCategoryReport } from "@/lib/relatorios/fetch-category-report";
import type { CategoryReportFilters } from "@/lib/relatorios/types"; import type { CategoryReportFilters } from "@/lib/types/relatorios";
import { validateDateRange } from "@/lib/relatorios/utils"; import { validateDateRange } from "@/lib/relatorios/utils";
import { addMonthsToPeriod, getCurrentPeriod } from "@/lib/utils/period"; import { addMonthsToPeriod, getCurrentPeriod } from "@/lib/utils/period";
import { fetchUserCategories } from "./data"; import { fetchUserCategories } from "./data";

View File

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

View File

@@ -1,7 +1,6 @@
"use client"; "use client";
import { RiCheckLine } from "@remixicon/react"; import { RiCheckLine } from "@remixicon/react";
import { useMemo } from "react";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { import {
@@ -13,14 +12,13 @@ import {
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import {
buildNoteDisplayTitle,
formatNoteCreatedAtLong,
} from "@/lib/notes/formatters";
import { Card } from "../ui/card"; import { Card } from "../ui/card";
import { type Note, sortTasksByStatus } from "./types"; import { type Note, sortTasksByStatus } from "./types";
const DATE_FORMATTER = new Intl.DateTimeFormat("pt-BR", {
dateStyle: "long",
timeStyle: "short",
});
interface NoteDetailsDialogProps { interface NoteDetailsDialogProps {
note: Note | null; note: Note | null;
open: boolean; open: boolean;
@@ -32,26 +30,14 @@ export function NoteDetailsDialog({
open, open,
onOpenChange, onOpenChange,
}: NoteDetailsDialogProps) { }: 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) { if (!note) {
return null; 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 isTask = note.type === "tarefa";
const completedCount = tasks.filter((t) => t.completed).length; const completedCount = tasks.filter((t) => t.completed).length;
const totalCount = tasks.length; const totalCount = tasks.length;

View File

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

View File

@@ -2,8 +2,8 @@
import { DayCell } from "@/components/calendario/day-cell"; import { DayCell } from "@/components/calendario/day-cell";
import type { CalendarDay } from "@/components/calendario/types"; import type { CalendarDay } from "@/lib/types/calendario";
import { WEEK_DAYS_SHORT } from "@/components/calendario/utils"; import { WEEK_DAYS_SHORT } from "@/lib/utils/calendario";
import { cn } from "@/lib/utils/ui"; import { cn } from "@/lib/utils/ui";
type CalendarGridProps = { type CalendarGridProps = {
@@ -18,10 +18,10 @@ export function CalendarGrid({
onCreateDay, onCreateDay,
}: CalendarGridProps) { }: CalendarGridProps) {
return ( 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"> <div className="grid grid-cols-7 text-sm font-semibold uppercase tracking-wide text-muted-foreground">
{WEEK_DAYS_SHORT.map((dayName) => ( {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} {dayName}
</span> </span>
))} ))}

View File

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

View File

@@ -2,7 +2,7 @@
import { RiAddLine } from "@remixicon/react"; import { RiAddLine } from "@remixicon/react";
import type { KeyboardEvent, MouseEvent } from "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 { currencyFormatter } from "@/lib/lancamentos/formatting-helpers";
import { cn } from "@/lib/utils/ui"; import { cn } from "@/lib/utils/ui";

View File

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

View File

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

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

View File

@@ -2,10 +2,10 @@
import { RiPieChartLine } from "@remixicon/react"; import { RiPieChartLine } from "@remixicon/react";
import { CategoryIconBadge } from "@/components/categorias/category-icon-badge"; 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 { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress"; 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"; import type { CardDetailData } from "@/lib/relatorios/cartoes-report";
type CardCategoryBreakdownProps = { type CardCategoryBreakdownProps = {

View File

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

View File

@@ -1,11 +1,11 @@
"use client"; "use client";
import { RiShoppingBag3Line } from "@remixicon/react"; 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 { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress"; 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"; import type { CardDetailData } from "@/lib/relatorios/cartoes-report";
type CardTopExpensesProps = { type CardTopExpensesProps = {

View File

@@ -16,7 +16,10 @@ import {
ChartContainer, ChartContainer,
ChartTooltip, ChartTooltip,
} from "@/components/ui/chart"; } from "@/components/ui/chart";
import { resolveLogoSrc } from "@/lib/logo";
import type { CardDetailData } from "@/lib/relatorios/cartoes-report"; import type { CardDetailData } from "@/lib/relatorios/cartoes-report";
import { formatCurrency, formatCurrencyCompact } from "@/lib/utils/currency";
import { formatPercentage } from "@/lib/utils/percentage";
type CardUsageChartProps = { type CardUsageChartProps = {
data: CardDetailData["monthlyUsage"]; data: CardDetailData["monthlyUsage"];
@@ -34,48 +37,14 @@ const chartConfig = {
}, },
} satisfies 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) { 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 // Always show last 12 months
const chartData = data.slice(-12).map((item) => ({ const chartData = data.slice(-12).map((item) => ({
month: item.periodLabel, month: item.periodLabel,
amount: item.amount, amount: item.amount,
})); }));
const logoPath = resolveLogoPath(card.logo); const logoPath = resolveLogoSrc(card.logo);
return ( return (
<Card> <Card>
@@ -124,7 +93,17 @@ export function CardUsageChart({ data, limit, card }: CardUsageChartProps) {
axisLine={false} axisLine={false}
tickMargin={8} tickMargin={8}
className="text-xs" 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 && ( {limit > 0 && (
<ReferenceLine <ReferenceLine
@@ -159,7 +138,10 @@ export function CardUsageChart({ data, limit, card }: CardUsageChartProps) {
Uso Uso
</span> </span>
<span className="text-xs font-medium tabular-nums"> <span className="text-xs font-medium tabular-nums">
{formatCurrency(value)} {formatCurrency(value, {
maximumFractionDigits: 0,
minimumFractionDigits: 0,
})}
</span> </span>
</div> </div>
{limit > 0 && ( {limit > 0 && (
@@ -168,7 +150,10 @@ export function CardUsageChart({ data, limit, card }: CardUsageChartProps) {
% do Limite % do Limite
</span> </span>
<span className="text-xs font-medium tabular-nums"> <span className="text-xs font-medium tabular-nums">
{usagePercent.toFixed(0)}% {formatPercentage(usagePercent, {
maximumFractionDigits: 0,
minimumFractionDigits: 0,
})}
</span> </span>
</div> </div>
)} )}

View File

@@ -4,59 +4,24 @@ import { RiBankCard2Line } from "@remixicon/react";
import Image from "next/image"; import Image from "next/image";
import Link from "next/link"; import Link from "next/link";
import { useSearchParams } from "next/navigation"; 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 { Card, CardContent } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress"; 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 type { CartoesReportData } from "@/lib/relatorios/cartoes-report";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { formatCurrency } from "@/lib/utils/currency";
import { formatPercentage } from "@/lib/utils/percentage";
type CardsOverviewProps = { type CardsOverviewProps = {
data: CartoesReportData; data: CartoesReportData;
}; };
const BRAND_ASSETS: Record<string, string> = {
visa: "/bandeiras/visa.svg",
mastercard: "/bandeiras/mastercard.svg",
amex: "/bandeiras/amex.svg",
american: "/bandeiras/amex.svg",
elo: "/bandeiras/elo.svg",
hipercard: "/bandeiras/hipercard.svg",
hiper: "/bandeiras/hipercard.svg",
};
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) { export function CardsOverview({ data }: CardsOverviewProps) {
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const periodoParam = searchParams.get("periodo"); 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) => { const getUsageColor = (percent: number) => {
if (percent < 50) return "bg-success"; if (percent < 50) return "bg-success";
if (percent < 80) return "bg-warning"; if (percent < 80) return "bg-warning";
@@ -107,7 +72,10 @@ export function CardsOverview({ data }: CardsOverviewProps) {
/> />
) : ( ) : (
<p className="text-2xl font-semibold"> <p className="text-2xl font-semibold">
{card.value.toFixed(0)}% {formatPercentage(card.value, {
maximumFractionDigits: 0,
minimumFractionDigits: 0,
})}
</p> </p>
)} )}
</CardContent> </CardContent>
@@ -120,8 +88,8 @@ export function CardsOverview({ data }: CardsOverviewProps) {
{/* Cards list */} {/* Cards list */}
<div className="grid gap-2 grid-cols-2 lg:grid-cols-4 xl:grid-cols-4"> <div className="grid gap-2 grid-cols-2 lg:grid-cols-4 xl:grid-cols-4">
{data.cards.map((card) => { {data.cards.map((card) => {
const logoPath = resolveLogoPath(card.logo); const logoPath = resolveLogoSrc(card.logo);
const brandAsset = resolveBrandAsset(card.brand); const brandAsset = resolveCardBrandAsset(card.brand);
const isSelected = data.selectedCard?.card.id === card.id; const isSelected = data.selectedCard?.card.id === card.id;
return ( return (
@@ -174,7 +142,10 @@ export function CardsOverview({ data }: CardsOverviewProps) {
)} )}
/> />
<span className="text-xs font-medium tabular-nums"> <span className="text-xs font-medium tabular-nums">
{card.usagePercent.toFixed(0)}% {formatPercentage(card.usagePercent, {
maximumFractionDigits: 0,
minimumFractionDigits: 0,
})}
</span> </span>
</div> </div>
</div> </div>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,11 +1,11 @@
"use client"; "use client";
import { RiStore2Line } from "@remixicon/react"; 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 { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress"; 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"; import type { TopEstabelecimentosData } from "@/lib/relatorios/estabelecimentos/fetch-data";
type EstablishmentsListProps = { type EstablishmentsListProps = {

View File

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

View File

@@ -2,10 +2,10 @@
import { RiPriceTag3Line } from "@remixicon/react"; import { RiPriceTag3Line } from "@remixicon/react";
import { CategoryIconBadge } from "@/components/categorias/category-icon-badge"; 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 { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress"; 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"; import type { TopEstabelecimentosData } from "@/lib/relatorios/estabelecimentos/fetch-data";
type TopCategoriesProps = { type TopCategoriesProps = {

51
lib/notes/formatters.ts Normal file
View File

@@ -0,0 +1,51 @@
type NoteTasksSummaryInput = {
type: string;
tasks?: Array<{ completed: boolean }> | null;
};
const NOTE_CREATED_AT_FORMATTER = new Intl.DateTimeFormat("pt-BR", {
dateStyle: "medium",
});
const NOTE_CREATED_AT_LONG_FORMATTER = new Intl.DateTimeFormat("pt-BR", {
dateStyle: "long",
timeStyle: "short",
});
const parseNoteDate = (value: string | Date | null | undefined) => {
if (!value) {
return null;
}
const parsed = value instanceof Date ? value : new Date(value);
return Number.isNaN(parsed.getTime()) ? null : parsed;
};
export const buildNoteDisplayTitle = (value: string | null | undefined) => {
const trimmed = value?.trim() ?? "";
return trimmed.length > 0 ? trimmed : "Anotação sem título";
};
export const getNoteTasksSummary = (note: NoteTasksSummaryInput) => {
if (note.type !== "tarefa") {
return "Nota";
}
const tasks = note.tasks ?? [];
const completed = tasks.filter((task) => task.completed).length;
return `${completed}/${tasks.length} concluídas`;
};
export const formatNoteCreatedAt = (
value: string | Date | null | undefined,
) => {
const parsed = parseNoteDate(value);
return parsed ? NOTE_CREATED_AT_FORMATTER.format(parsed) : null;
};
export const formatNoteCreatedAtLong = (
value: string | Date | null | undefined,
) => {
const parsed = parseNoteDate(value);
return parsed ? NOTE_CREATED_AT_LONG_FORMATTER.format(parsed) : null;
};

View File

@@ -20,8 +20,13 @@ import {
} from "@/db/schema"; } from "@/db/schema";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { PAGADOR_ROLE_ADMIN } from "@/lib/pagadores/constants"; import { PAGADOR_ROLE_ADMIN } from "@/lib/pagadores/constants";
import { formatDateOnly } from "@/lib/utils/date";
import { safeToNumber } from "@/lib/utils/number"; import { safeToNumber } from "@/lib/utils/number";
import { getPreviousPeriod } from "@/lib/utils/period"; import {
buildPeriodWindow,
formatCompactPeriodLabel,
getPreviousPeriod,
} from "@/lib/utils/period";
const DESPESA = "Despesa"; const DESPESA = "Despesa";
@@ -75,6 +80,49 @@ export type CartoesReportData = {
selectedCard: CardDetailData | null; selectedCard: CardDetailData | null;
}; };
type CardRow = {
id: string;
name: string;
brand: string | null;
logo: string | null;
limit: unknown;
status: string;
};
type CardUsageRow = {
cartaoId: string | null;
totalAmount: unknown;
};
type MonthlyUsageRow = {
period: string;
totalAmount: unknown;
};
type CategoryAmountRow = {
categoriaId: string | null;
totalAmount: unknown;
};
type CategoryInfoRow = {
id: string;
name: string;
icon: string | null;
};
type TopExpenseRow = {
id: string;
name: string;
amount: unknown;
purchaseDate: Date | string | null;
categoriaId: string | null;
};
type InvoiceStatusRow = {
period: string;
status: string | null;
};
export async function fetchCartoesReportData( export async function fetchCartoesReportData(
userId: string, userId: string,
currentPeriod: string, currentPeriod: string,
@@ -83,7 +131,7 @@ export async function fetchCartoesReportData(
const previousPeriod = getPreviousPeriod(currentPeriod); const previousPeriod = getPreviousPeriod(currentPeriod);
// Fetch all active cards (not inactive) // Fetch all active cards (not inactive)
const allCards = await db const allCards = (await db
.select({ .select({
id: cartoes.id, id: cartoes.id,
name: cartoes.name, name: cartoes.name,
@@ -95,7 +143,7 @@ export async function fetchCartoesReportData(
.from(cartoes) .from(cartoes)
.where( .where(
and(eq(cartoes.userId, userId), not(ilike(cartoes.status, "inativo"))), and(eq(cartoes.userId, userId), not(ilike(cartoes.status, "inativo"))),
); )) as CardRow[];
if (allCards.length === 0) { if (allCards.length === 0) {
return { return {
@@ -110,7 +158,7 @@ export async function fetchCartoesReportData(
const cardIds = allCards.map((c) => c.id); const cardIds = allCards.map((c) => c.id);
// Fetch current period usage by card (recorrente só conta quando a data da ocorrência já passou) // Fetch current period usage by card (recorrente só conta quando a data da ocorrência já passou)
const currentUsageData = await db const currentUsageData = (await db
.select({ .select({
cartaoId: lancamentos.cartaoId, cartaoId: lancamentos.cartaoId,
totalAmount: sum(lancamentos.amount).as("total"), totalAmount: sum(lancamentos.amount).as("total"),
@@ -130,10 +178,10 @@ export async function fetchCartoesReportData(
), ),
), ),
) )
.groupBy(lancamentos.cartaoId); .groupBy(lancamentos.cartaoId)) as CardUsageRow[];
// Fetch previous period usage by card // Fetch previous period usage by card
const previousUsageData = await db const previousUsageData = (await db
.select({ .select({
cartaoId: lancamentos.cartaoId, cartaoId: lancamentos.cartaoId,
totalAmount: sum(lancamentos.amount).as("total"), totalAmount: sum(lancamentos.amount).as("total"),
@@ -149,7 +197,7 @@ export async function fetchCartoesReportData(
inArray(lancamentos.cartaoId, cardIds), inArray(lancamentos.cartaoId, cardIds),
), ),
) )
.groupBy(lancamentos.cartaoId); .groupBy(lancamentos.cartaoId)) as CardUsageRow[];
const currentUsageMap = new Map<string, number>(); const currentUsageMap = new Map<string, number>();
for (const row of currentUsageData) { for (const row of currentUsageData) {
@@ -246,32 +294,12 @@ async function fetchCardDetail(
currentPeriod: string, currentPeriod: string,
): Promise<CardDetailData> { ): Promise<CardDetailData> {
// Build period range for last 12 months // Build period range for last 12 months
const periods: string[] = []; const periods = buildPeriodWindow(currentPeriod, 12);
let p = currentPeriod;
for (let i = 0; i < 12; i++) {
periods.unshift(p);
p = getPreviousPeriod(p);
}
const startPeriod = periods[0]; const startPeriod = periods[0];
const monthLabels = [
"Jan",
"Fev",
"Mar",
"Abr",
"Mai",
"Jun",
"Jul",
"Ago",
"Set",
"Out",
"Nov",
"Dez",
];
// Fetch monthly usage // Fetch monthly usage
const monthlyData = await db const monthlyData = (await db
.select({ .select({
period: lancamentos.period, period: lancamentos.period,
totalAmount: sum(lancamentos.amount).as("total"), totalAmount: sum(lancamentos.amount).as("total"),
@@ -289,20 +317,19 @@ async function fetchCardDetail(
), ),
) )
.groupBy(lancamentos.period) .groupBy(lancamentos.period)
.orderBy(lancamentos.period); .orderBy(lancamentos.period)) as MonthlyUsageRow[];
const monthlyUsage = periods.map((period) => { const monthlyUsage = periods.map((period) => {
const data = monthlyData.find((d) => d.period === period); const data = monthlyData.find((d) => d.period === period);
const [year, month] = period.split("-");
return { return {
period, period,
periodLabel: `${monthLabels[parseInt(month, 10) - 1]}/${year.slice(2)}`, periodLabel: formatCompactPeriodLabel(period),
amount: Math.abs(safeToNumber(data?.totalAmount)), amount: Math.abs(safeToNumber(data?.totalAmount)),
}; };
}); });
// Fetch category breakdown for current period // Fetch category breakdown for current period
const categoryData = await db const categoryData = (await db
.select({ .select({
categoriaId: lancamentos.categoriaId, categoriaId: lancamentos.categoriaId,
totalAmount: sum(lancamentos.amount).as("total"), totalAmount: sum(lancamentos.amount).as("total"),
@@ -318,7 +345,7 @@ async function fetchCardDetail(
eq(lancamentos.transactionType, DESPESA), eq(lancamentos.transactionType, DESPESA),
), ),
) )
.groupBy(lancamentos.categoriaId); .groupBy(lancamentos.categoriaId)) as CategoryAmountRow[];
// Fetch category names // Fetch category names
const categoryIds = categoryData const categoryIds = categoryData
@@ -327,15 +354,15 @@ async function fetchCardDetail(
const categoryNames = const categoryNames =
categoryIds.length > 0 categoryIds.length > 0
? await db ? ((await db
.select({ .select({
id: categorias.id, id: categorias.id,
name: categorias.name, name: categorias.name,
icon: categorias.icon, icon: categorias.icon,
}) })
.from(categorias) .from(categorias)
.where(inArray(categorias.id, categoryIds)) .where(inArray(categorias.id, categoryIds))) as CategoryInfoRow[])
: []; : ([] as CategoryInfoRow[]);
const categoryNameMap = new Map(categoryNames.map((c) => [c.id, c])); const categoryNameMap = new Map(categoryNames.map((c) => [c.id, c]));
@@ -363,7 +390,7 @@ async function fetchCardDetail(
.slice(0, 10); .slice(0, 10);
// Fetch top expenses for current period // Fetch top expenses for current period
const topExpensesData = await db const topExpensesData = (await db
.select({ .select({
id: lancamentos.id, id: lancamentos.id,
name: lancamentos.name, name: lancamentos.name,
@@ -383,7 +410,7 @@ async function fetchCardDetail(
), ),
) )
.orderBy(lancamentos.amount) .orderBy(lancamentos.amount)
.limit(10); .limit(10)) as TopExpenseRow[];
const topExpenses = topExpensesData.map((expense) => { const topExpenses = topExpensesData.map((expense) => {
const catInfo = expense.categoriaId const catInfo = expense.categoriaId
@@ -393,15 +420,18 @@ async function fetchCardDetail(
id: expense.id, id: expense.id,
name: expense.name, name: expense.name,
amount: Math.abs(safeToNumber(expense.amount)), amount: Math.abs(safeToNumber(expense.amount)),
date: expense.purchaseDate date:
? new Date(expense.purchaseDate).toLocaleDateString("pt-BR") formatDateOnly(expense.purchaseDate, {
: "", day: "2-digit",
month: "2-digit",
year: "numeric",
}) ?? "",
category: catInfo?.name || null, category: catInfo?.name || null,
}; };
}); });
// Fetch invoice status for last 6 months // Fetch invoice status for last 6 months
const invoiceData = await db const invoiceData = (await db
.select({ .select({
period: faturas.period, period: faturas.period,
status: faturas.paymentStatus, status: faturas.paymentStatus,
@@ -415,7 +445,7 @@ async function fetchCardDetail(
lte(faturas.period, currentPeriod), lte(faturas.period, currentPeriod),
), ),
) )
.orderBy(faturas.period); .orderBy(faturas.period)) as InvoiceStatusRow[];
const invoiceStatus = periods.map((period) => { const invoiceStatus = periods.map((period) => {
const invoice = invoiceData.find((i) => i.period === period); const invoice = invoiceData.find((i) => i.period === period);

View File

@@ -1,11 +1,10 @@
import { format } from "date-fns";
import { ptBR } from "date-fns/locale";
import { and, eq, inArray, isNull, or, sql } from "drizzle-orm"; import { and, eq, inArray, isNull, or, sql } from "drizzle-orm";
import { categorias, lancamentos } from "@/db/schema"; import { categorias, lancamentos } from "@/db/schema";
import { ACCOUNT_AUTO_INVOICE_NOTE_PREFIX } from "@/lib/contas/constants"; import { ACCOUNT_AUTO_INVOICE_NOTE_PREFIX } from "@/lib/contas/constants";
import { toNumber } from "@/lib/dashboard/common";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { getAdminPagadorId } from "@/lib/pagadores/get-admin-id"; import { getAdminPagadorId } from "@/lib/pagadores/get-admin-id";
import { safeToNumber as toNumber } from "@/lib/utils/number";
import { formatPeriodMonthShort } from "@/lib/utils/period";
import { generatePeriodRange } from "./utils"; import { generatePeriodRange } from "./utils";
export type CategoryChartData = { export type CategoryChartData = {
@@ -127,13 +126,7 @@ export async function fetchCategoryChartData(
} }
const chartData = periods.map((period) => { const chartData = periods.map((period) => {
const [year, month] = period.split("-"); const monthLabel = formatPeriodMonthShort(period).toUpperCase();
const date = new Date(
Number.parseInt(year, 10),
Number.parseInt(month, 10) - 1,
1,
);
const monthLabel = format(date, "MMM", { locale: ptBR }).toUpperCase();
const dataPoint: { month: string; [key: string]: number | string } = { const dataPoint: { month: string; [key: string]: number | string } = {
month: monthLabel, month: monthLabel,
@@ -146,15 +139,9 @@ export async function fetchCategoryChartData(
return dataPoint; return dataPoint;
}); });
const months = periods.map((period) => { const months = periods.map((period) =>
const [year, month] = period.split("-"); formatPeriodMonthShort(period).toUpperCase(),
const date = new Date( );
Number.parseInt(year, 10),
Number.parseInt(month, 10) - 1,
1,
);
return format(date, "MMM", { locale: ptBR }).toUpperCase();
});
const categories = Array.from(categoryMap.values()).map((cat) => ({ const categories = Array.from(categoryMap.values()).map((cat) => ({
id: cat.id, id: cat.id,

View File

@@ -1,9 +1,9 @@
import { and, eq, inArray, isNull, or, sql } from "drizzle-orm"; import { and, eq, inArray, isNull, or, sql } from "drizzle-orm";
import { categorias, lancamentos } from "@/db/schema"; import { categorias, lancamentos } from "@/db/schema";
import { ACCOUNT_AUTO_INVOICE_NOTE_PREFIX } from "@/lib/contas/constants"; import { ACCOUNT_AUTO_INVOICE_NOTE_PREFIX } from "@/lib/contas/constants";
import { toNumber } from "@/lib/dashboard/common";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { getAdminPagadorId } from "@/lib/pagadores/get-admin-id"; import { getAdminPagadorId } from "@/lib/pagadores/get-admin-id";
import { safeToNumber as toNumber } from "@/lib/utils/number";
import type { import type {
CategoryReportData, CategoryReportData,
CategoryReportFilters, CategoryReportFilters,

View File

@@ -1,52 +1,7 @@
/** export type {
* Types for Category Report feature CategoryReportData,
*/ CategoryReportFilters,
CategoryReportItem,
/** DateRangeValidation,
* Monthly data for a specific category in a specific period MonthlyData,
*/ } from "@/lib/types/relatorios";
export type MonthlyData = {
period: string; // Format: "YYYY-MM"
amount: number; // Total amount for this category in this period
previousAmount: number; // Amount from previous period (for comparison)
percentageChange: number | null; // Percentage change from previous period
};
/**
* Single category item in the report
*/
export type CategoryReportItem = {
categoryId: string;
name: string;
icon: string | null;
type: "despesa" | "receita";
monthlyData: Map<string, MonthlyData>; // Key: period (YYYY-MM)
total: number; // Total across all periods
};
/**
* Complete category report data structure
*/
export type CategoryReportData = {
categories: CategoryReportItem[]; // All categories with their data
periods: string[]; // All periods in the report (sorted chronologically)
totals: Map<string, number>; // Total per period across all categories
grandTotal: number; // Total of all categories and all periods
};
/**
* Filters for category report query
*/
export type CategoryReportFilters = {
startPeriod: string; // Format: "YYYY-MM"
endPeriod: string; // Format: "YYYY-MM"
categoryIds?: string[]; // Optional: filter by specific categories
};
/**
* Validation result for date range
*/
export type DateRangeValidation = {
isValid: boolean;
error?: string;
};

View File

@@ -1,6 +1,11 @@
import type { DateRangeValidation } from "@/lib/types/relatorios";
import { calculatePercentageChange } from "@/lib/utils/math"; import { calculatePercentageChange } from "@/lib/utils/math";
import { buildPeriodRange, MONTH_NAMES, parsePeriod } from "@/lib/utils/period"; import { formatPercentageChange as formatPercentageChangeValue } from "@/lib/utils/percentage";
import type { DateRangeValidation } from "./types"; import {
buildPeriodRange,
formatShortPeriodLabel,
parsePeriod,
} from "@/lib/utils/period";
// Re-export for convenience // Re-export for convenience
export { calculatePercentageChange }; export { calculatePercentageChange };
@@ -14,14 +19,8 @@ export { calculatePercentageChange };
*/ */
export function formatPeriodLabel(period: string): string { export function formatPeriodLabel(period: string): string {
try { try {
const { year, month } = parsePeriod(period); parsePeriod(period);
const monthName = MONTH_NAMES[month - 1]; return formatShortPeriodLabel(period);
// Capitalize first letter and take first 3 chars
const shortMonth =
monthName.charAt(0).toUpperCase() + monthName.slice(1, 3);
return `${shortMonth}/${year}`;
} catch { } catch {
return period; // Return original if parsing fails return period; // Return original if parsing fails
} }
@@ -102,14 +101,5 @@ export function validateDateRange(
* @returns Formatted percentage string * @returns Formatted percentage string
*/ */
export function formatPercentageChange(change: number | null): string { export function formatPercentageChange(change: number | null): string {
if (change === null) return "-"; return formatPercentageChangeValue(change);
const absChange = Math.abs(change);
const sign = change >= 0 ? "+" : "-";
// Use one decimal place if less than 10%
const formatted =
absChange < 10 ? absChange.toFixed(1) : Math.round(absChange).toString();
return `${sign}${formatted}%`;
} }

View File

@@ -1,6 +1,7 @@
import type { CalendarDay, CalendarEvent } from "@/components/calendario/types"; import type { CalendarDay, CalendarEvent } from "@/lib/types/calendario";
import { toDateOnlyString } from "@/lib/utils/date";
export const formatDateKey = (date: Date) => date.toISOString().slice(0, 10); export const formatDateKey = (date: Date) => toDateOnlyString(date) ?? "";
const getWeekdayIndex = (date: Date) => { const getWeekdayIndex = (date: Date) => {
const day = date.getUTCDay(); // 0 (domingo) - 6 (sábado) const day = date.getUTCDay(); // 0 (domingo) - 6 (sábado)