refactor: ajustar feature de análise de parcelas

Melhorias na funcionalidade de análise de parcelas:

- Cálculo correto de vencimento baseado no dia de vencimento do cartão
- Identificação de parcelas pagas com indicador visual
- Parcelas pagas não podem ser selecionadas
- Remoção completa da funcionalidade de faturas (apenas parcelas)
- Layout mais compacto com espaçamentos reduzidos
- Botão "Análise" discreto ao lado do título do widget
- Card de resumo simplificado
- Tamanhos de fonte e ícones reduzidos
- Progress bar mais fina (h-1.5)
This commit is contained in:
Claude
2025-11-16 16:15:43 +00:00
parent 115cb8836c
commit 4411d992fa
8 changed files with 134 additions and 315 deletions

View File

@@ -16,6 +16,7 @@ export function DashboardGrid({ data, period }: DashboardGridProps) {
title={widget.title} title={widget.title}
subtitle={widget.subtitle} subtitle={widget.subtitle}
icon={widget.icon} icon={widget.icon}
action={widget.action}
> >
{widget.component({ data, period })} {widget.component({ data, period })}
</WidgetCard> </WidgetCard>

View File

@@ -2,25 +2,19 @@
import MoneyValues from "@/components/money-values"; import MoneyValues from "@/components/money-values";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { RiPieChartLine } from "@remixicon/react"; import { RiPieChartLine } from "@remixicon/react";
type AnalysisSummaryPanelProps = { type AnalysisSummaryPanelProps = {
totalInstallments: number; totalInstallments: number;
totalInvoices: number;
grandTotal: number; grandTotal: number;
selectedCount: number; selectedCount: number;
}; };
export function AnalysisSummaryPanel({ export function AnalysisSummaryPanel({
totalInstallments, totalInstallments,
totalInvoices,
grandTotal, grandTotal,
selectedCount, selectedCount,
}: AnalysisSummaryPanelProps) { }: AnalysisSummaryPanelProps) {
const hasInstallments = totalInstallments > 0;
const hasInvoices = totalInvoices > 0;
return ( return (
<Card className="border-primary/20"> <Card className="border-primary/20">
<CardHeader className="border-b"> <CardHeader className="border-b">
@@ -29,9 +23,9 @@ export function AnalysisSummaryPanel({
<CardTitle className="text-base">Resumo</CardTitle> <CardTitle className="text-base">Resumo</CardTitle>
</div> </div>
</CardHeader> </CardHeader>
<CardContent className="flex flex-col gap-4 pt-6"> <CardContent className="flex flex-col gap-3 pt-4">
{/* Total geral */} {/* Total geral */}
<div className="flex flex-col items-center gap-2 rounded-lg bg-primary/10 p-4"> <div className="flex flex-col items-center gap-2 rounded-lg bg-primary/10 p-3">
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground"> <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
Total Selecionado Total Selecionado
</p> </p>
@@ -40,67 +34,15 @@ export function AnalysisSummaryPanel({
className="text-2xl font-bold text-primary" className="text-2xl font-bold text-primary"
/> />
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
{selectedCount} {selectedCount === 1 ? "item" : "itens"} {selectedCount} {selectedCount === 1 ? "parcela" : "parcelas"}
</p> </p>
</div> </div>
<Separator />
{/* Breakdown */}
<div className="flex flex-col gap-3">
<p className="text-sm font-medium">Detalhamento</p>
{/* Parcelas */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<div className="size-2 rounded-full bg-blue-500" />
<span className="text-sm text-muted-foreground">Parcelas</span>
</div>
<MoneyValues amount={totalInstallments} className="text-sm" />
</div>
{/* Faturas */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<div className="size-2 rounded-full bg-purple-500" />
<span className="text-sm text-muted-foreground">Faturas</span>
</div>
<MoneyValues amount={totalInvoices} className="text-sm" />
</div>
</div>
<Separator />
{/* Percentuais */}
{grandTotal > 0 && (
<div className="flex flex-col gap-2">
<p className="text-sm font-medium">Distribuição</p>
{hasInstallments && (
<div className="flex items-center justify-between text-xs">
<span className="text-muted-foreground">Parcelas</span>
<span className="font-medium">
{((totalInstallments / grandTotal) * 100).toFixed(1)}%
</span>
</div>
)}
{hasInvoices && (
<div className="flex items-center justify-between text-xs">
<span className="text-muted-foreground">Faturas</span>
<span className="font-medium">
{((totalInvoices / grandTotal) * 100).toFixed(1)}%
</span>
</div>
)}
</div>
)}
{/* Mensagem quando nada está selecionado */} {/* Mensagem quando nada está selecionado */}
{selectedCount === 0 && ( {selectedCount === 0 && (
<div className="rounded-lg bg-muted/50 p-3 text-center"> <div className="rounded-lg bg-muted/50 p-3 text-center">
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
Selecione parcelas ou faturas para ver o resumo Selecione parcelas para ver o resumo
</p> </p>
</div> </div>
)} )}

View File

@@ -7,7 +7,6 @@ import { Separator } from "@/components/ui/separator";
import { useMemo, useState } from "react"; import { useMemo, useState } from "react";
import type { InstallmentAnalysisData } from "./types"; import type { InstallmentAnalysisData } from "./types";
import { InstallmentGroupCard } from "./installment-group-card"; import { InstallmentGroupCard } from "./installment-group-card";
import { PendingInvoiceCard } from "./pending-invoice-card";
import { AnalysisSummaryPanel } from "./analysis-summary-panel"; import { AnalysisSummaryPanel } from "./analysis-summary-panel";
import { import {
RiCalculatorLine, RiCalculatorLine,
@@ -27,52 +26,38 @@ export function InstallmentAnalysisPage({
Map<string, Set<string>> Map<string, Set<string>>
>(new Map()); >(new Map());
// Estado para faturas selecionadas: Set<invoiceKey (cartaoId:period)> // Calcular se está tudo selecionado (apenas parcelas não pagas)
const [selectedInvoices, setSelectedInvoices] = useState<Set<string>>(
new Set()
);
// Calcular se está tudo selecionado
const isAllSelected = useMemo(() => { const isAllSelected = useMemo(() => {
const allInstallmentsSelected = data.installmentGroups.every((group) => { const allInstallmentsSelected = data.installmentGroups.every((group) => {
const groupSelection = selectedInstallments.get(group.seriesId); const groupSelection = selectedInstallments.get(group.seriesId);
if (!groupSelection) return false; const unpaidInstallments = group.pendingInstallments.filter(
return ( (i) => !i.isSettled
groupSelection.size === group.pendingInstallments.length &&
group.pendingInstallments.length > 0
); );
if (!groupSelection || unpaidInstallments.length === 0) return false;
return groupSelection.size === unpaidInstallments.length;
}); });
const allInvoicesSelected = return allInstallmentsSelected && data.installmentGroups.length > 0;
data.pendingInvoices.length === selectedInvoices.size; }, [selectedInstallments, data]);
return (
allInstallmentsSelected &&
allInvoicesSelected &&
(data.installmentGroups.length > 0 || data.pendingInvoices.length > 0)
);
}, [selectedInstallments, selectedInvoices, data]);
// Função para selecionar/desselecionar tudo // Função para selecionar/desselecionar tudo
const toggleSelectAll = () => { const toggleSelectAll = () => {
if (isAllSelected) { if (isAllSelected) {
// Desmarcar tudo // Desmarcar tudo
setSelectedInstallments(new Map()); setSelectedInstallments(new Map());
setSelectedInvoices(new Set());
} else { } else {
// Marcar tudo // Marcar tudo (exceto parcelas já pagas)
const newInstallments = new Map<string, Set<string>>(); const newInstallments = new Map<string, Set<string>>();
data.installmentGroups.forEach((group) => { data.installmentGroups.forEach((group) => {
const ids = new Set(group.pendingInstallments.map((i) => i.id)); const unpaidIds = group.pendingInstallments
newInstallments.set(group.seriesId, ids); .filter((i) => !i.isSettled)
.map((i) => i.id);
if (unpaidIds.length > 0) {
newInstallments.set(group.seriesId, new Set(unpaidIds));
}
}); });
const newInvoices = new Set(
data.pendingInvoices.map((inv) => `${inv.cartaoId}:${inv.period}`)
);
setSelectedInstallments(newInstallments); setSelectedInstallments(newInstallments);
setSelectedInvoices(newInvoices);
} }
}; };
@@ -112,20 +97,8 @@ export function InstallmentAnalysisPage({
setSelectedInstallments(newMap); setSelectedInstallments(newMap);
}; };
// Função para selecionar/desselecionar fatura
const toggleInvoiceSelection = (invoiceKey: string) => {
const newSet = new Set(selectedInvoices);
if (newSet.has(invoiceKey)) {
newSet.delete(invoiceKey);
} else {
newSet.add(invoiceKey);
}
setSelectedInvoices(newSet);
};
// Calcular totais // Calcular totais
const { totalInstallments, totalInvoices, grandTotal, selectedCount } = const { totalInstallments, grandTotal, selectedCount } = useMemo(() => {
useMemo(() => {
let installmentsSum = 0; let installmentsSum = 0;
let installmentsCount = 0; let installmentsCount = 0;
@@ -138,7 +111,7 @@ export function InstallmentAnalysisPage({
const installment = group.pendingInstallments.find( const installment = group.pendingInstallments.find(
(i) => i.id === id (i) => i.id === id
); );
if (installment) { if (installment && !installment.isSettled) {
installmentsSum += installment.amount; installmentsSum += installment.amount;
installmentsCount++; installmentsCount++;
} }
@@ -146,58 +119,42 @@ export function InstallmentAnalysisPage({
} }
}); });
let invoicesSum = 0;
let invoicesCount = 0;
selectedInvoices.forEach((key) => {
const [cartaoId, period] = key.split(":");
const invoice = data.pendingInvoices.find(
(inv) => inv.cartaoId === cartaoId && inv.period === period
);
if (invoice) {
invoicesSum += invoice.totalAmount;
invoicesCount++;
}
});
return { return {
totalInstallments: installmentsSum, totalInstallments: installmentsSum,
totalInvoices: invoicesSum, grandTotal: installmentsSum,
grandTotal: installmentsSum + invoicesSum, selectedCount: installmentsCount,
selectedCount: installmentsCount + invoicesCount,
}; };
}, [selectedInstallments, selectedInvoices, data]); }, [selectedInstallments, data]);
const hasNoData = const hasNoData = data.installmentGroups.length === 0;
data.installmentGroups.length === 0 && data.pendingInvoices.length === 0;
return ( return (
<div className="flex flex-col gap-6"> <div className="flex flex-col gap-4">
{/* Header */} {/* Header */}
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<div className="flex size-10 items-center justify-center rounded-lg bg-primary/10"> <div className="flex size-9 items-center justify-center rounded-lg bg-primary/10">
<RiCalculatorLine className="size-5 text-primary" /> <RiCalculatorLine className="size-4 text-primary" />
</div> </div>
<div> <div>
<h1 className="text-2xl font-bold">Análise de Parcelas e Faturas</h1> <h1 className="text-xl font-bold">Análise de Parcelas</h1>
<p className="text-sm text-muted-foreground"> <p className="text-xs text-muted-foreground">
Veja quanto você gastaria pagando tudo que está em aberto Quanto você gastaria pagando tudo que está em aberto
</p> </p>
</div> </div>
</div> </div>
{/* Card de resumo principal */} {/* Card de resumo principal */}
<Card className="border-primary/20 bg-gradient-to-br from-primary/5 to-primary/10"> <Card className="border-primary/20 bg-gradient-to-br from-primary/5 to-primary/10">
<CardContent className="flex flex-col items-center justify-center gap-3 py-8"> <CardContent className="flex flex-col items-center justify-center gap-2 py-5">
<p className="text-sm font-medium text-muted-foreground"> <p className="text-xs font-medium text-muted-foreground">
Se você pagar tudo que está selecionado: Se você pagar tudo que está selecionado:
</p> </p>
<MoneyValues <MoneyValues
amount={grandTotal} amount={grandTotal}
className="text-4xl font-bold text-primary" className="text-3xl font-bold text-primary"
/> />
<p className="text-sm text-muted-foreground"> <p className="text-xs text-muted-foreground">
{selectedCount} {selectedCount === 1 ? "item" : "itens"} selecionados {selectedCount} {selectedCount === 1 ? "parcela" : "parcelas"} selecionadas
</p> </p>
</CardContent> </CardContent>
</Card> </Card>
@@ -221,7 +178,7 @@ export function InstallmentAnalysisPage({
</div> </div>
)} )}
<div className="grid gap-6 lg:grid-cols-[1fr_320px]"> <div className="grid gap-4 lg:grid-cols-[1fr_280px]">
{/* Conteúdo principal */} {/* Conteúdo principal */}
<div className="flex flex-col gap-6"> <div className="flex flex-col gap-6">
{/* Seção de Lançamentos Parcelados */} {/* Seção de Lançamentos Parcelados */}
@@ -244,7 +201,9 @@ export function InstallmentAnalysisPage({
onToggleGroup={() => onToggleGroup={() =>
toggleGroupSelection( toggleGroupSelection(
group.seriesId, group.seriesId,
group.pendingInstallments.map((i) => i.id) group.pendingInstallments
.filter((i) => !i.isSettled)
.map((i) => i.id)
) )
} }
onToggleInstallment={(installmentId) => onToggleInstallment={(installmentId) =>
@@ -256,38 +215,13 @@ export function InstallmentAnalysisPage({
</div> </div>
)} )}
{/* Seção de Faturas Pendentes */}
{data.pendingInvoices.length > 0 && (
<div className="flex flex-col gap-4">
<div className="flex items-center gap-2">
<Separator className="flex-1" />
<h2 className="text-lg font-semibold">Faturas Pendentes</h2>
<Separator className="flex-1" />
</div>
<div className="flex flex-col gap-3">
{data.pendingInvoices.map((invoice) => {
const invoiceKey = `${invoice.cartaoId}:${invoice.period}`;
return (
<PendingInvoiceCard
key={invoiceKey}
invoice={invoice}
isSelected={selectedInvoices.has(invoiceKey)}
onToggle={() => toggleInvoiceSelection(invoiceKey)}
/>
);
})}
</div>
</div>
)}
{/* Estado vazio */} {/* Estado vazio */}
{hasNoData && ( {hasNoData && (
<Card> <Card>
<CardContent className="flex flex-col items-center justify-center gap-3 py-12"> <CardContent className="flex flex-col items-center justify-center gap-3 py-12">
<RiCalculatorLine className="size-12 text-muted-foreground/50" /> <RiCalculatorLine className="size-12 text-muted-foreground/50" />
<div className="text-center"> <div className="text-center">
<p className="font-medium">Nenhuma parcela ou fatura pendente</p> <p className="font-medium">Nenhuma parcela pendente</p>
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">
Você está em dia com seus pagamentos! Você está em dia com seus pagamentos!
</p> </p>
@@ -302,7 +236,6 @@ export function InstallmentAnalysisPage({
<div className="lg:sticky lg:top-4 lg:self-start"> <div className="lg:sticky lg:top-4 lg:self-start">
<AnalysisSummaryPanel <AnalysisSummaryPanel
totalInstallments={totalInstallments} totalInstallments={totalInstallments}
totalInvoices={totalInvoices}
grandTotal={grandTotal} grandTotal={grandTotal}
selectedCount={selectedCount} selectedCount={selectedCount}
/> />

View File

@@ -27,13 +27,17 @@ export function InstallmentGroupCard({
}: InstallmentGroupCardProps) { }: InstallmentGroupCardProps) {
const [isExpanded, setIsExpanded] = useState(false); const [isExpanded, setIsExpanded] = useState(false);
const unpaidInstallments = group.pendingInstallments.filter(
(i) => !i.isSettled
);
const isFullySelected = const isFullySelected =
selectedInstallments.size === group.pendingInstallments.length && selectedInstallments.size === unpaidInstallments.length &&
group.pendingInstallments.length > 0; unpaidInstallments.length > 0;
const isPartiallySelected = const isPartiallySelected =
selectedInstallments.size > 0 && selectedInstallments.size > 0 &&
selectedInstallments.size < group.pendingInstallments.length; selectedInstallments.size < unpaidInstallments.length;
const progress = const progress =
group.totalInstallments > 0 group.totalInstallments > 0
@@ -48,7 +52,7 @@ export function InstallmentGroupCard({
return ( return (
<Card className={cn(isFullySelected && "border-primary/50")}> <Card className={cn(isFullySelected && "border-primary/50")}>
<CardContent className="flex flex-col gap-3 py-4"> <CardContent className="flex flex-col gap-2 py-3">
{/* Header do card */} {/* Header do card */}
<div className="flex items-start gap-3"> <div className="flex items-start gap-3">
<Checkbox <Checkbox
@@ -61,8 +65,8 @@ export function InstallmentGroupCard({
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<div className="flex items-start justify-between gap-3"> <div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<p className="font-medium">{group.name}</p> <p className="text-sm font-medium">{group.name}</p>
<div className="mt-1 flex flex-wrap items-center gap-2 text-xs text-muted-foreground"> <div className="mt-0.5 flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">
{group.cartaoName && ( {group.cartaoName && (
<> <>
<span>{group.cartaoName}</span> <span>{group.cartaoName}</span>
@@ -73,7 +77,7 @@ export function InstallmentGroupCard({
</div> </div>
</div> </div>
<div className="flex shrink-0 flex-col items-end gap-1"> <div className="flex shrink-0 flex-col items-end gap-0.5">
<MoneyValues <MoneyValues
amount={group.totalPendingAmount} amount={group.totalPendingAmount}
className="text-sm font-semibold" className="text-sm font-semibold"
@@ -88,7 +92,7 @@ export function InstallmentGroupCard({
</div> </div>
{/* Progress bar */} {/* Progress bar */}
<div className="mt-3"> <div className="mt-2">
<div className="mb-1 flex items-center justify-between text-xs text-muted-foreground"> <div className="mb-1 flex items-center justify-between text-xs text-muted-foreground">
<span> <span>
{group.paidInstallments} de {group.totalInstallments} pagas {group.paidInstallments} de {group.totalInstallments} pagas
@@ -100,7 +104,7 @@ export function InstallmentGroupCard({
: "pendentes"} : "pendentes"}
</span> </span>
</div> </div>
<Progress value={progress} className="h-2" /> <Progress value={progress} className="h-1.5" />
</div> </div>
{/* Badges de status */} {/* Badges de status */}
@@ -139,6 +143,7 @@ export function InstallmentGroupCard({
<div className="ml-9 mt-2 flex flex-col gap-2 border-l-2 border-muted pl-4"> <div className="ml-9 mt-2 flex flex-col gap-2 border-l-2 border-muted pl-4">
{group.pendingInstallments.map((installment) => { {group.pendingInstallments.map((installment) => {
const isSelected = selectedInstallments.has(installment.id); const isSelected = selectedInstallments.has(installment.id);
const isPaid = installment.isSettled;
const dueDate = installment.dueDate const dueDate = installment.dueDate
? format(installment.dueDate, "dd/MM/yyyy", { locale: ptBR }) ? format(installment.dueDate, "dd/MM/yyyy", { locale: ptBR })
: format(installment.purchaseDate, "dd/MM/yyyy", { : format(installment.purchaseDate, "dd/MM/yyyy", {
@@ -150,20 +155,27 @@ export function InstallmentGroupCard({
key={installment.id} key={installment.id}
className={cn( className={cn(
"flex items-center gap-3 rounded-md border p-2 transition-colors", "flex items-center gap-3 rounded-md border p-2 transition-colors",
isSelected && "border-primary/50 bg-primary/5" isSelected && !isPaid && "border-primary/50 bg-primary/5",
isPaid && "bg-muted/50 opacity-60"
)} )}
> >
<Checkbox <Checkbox
checked={isSelected} checked={isPaid ? false : isSelected}
onCheckedChange={() => onToggleInstallment(installment.id)} disabled={isPaid}
onCheckedChange={() => !isPaid && onToggleInstallment(installment.id)}
aria-label={`Selecionar parcela ${installment.currentInstallment} de ${group.totalInstallments}`} aria-label={`Selecionar parcela ${installment.currentInstallment} de ${group.totalInstallments}`}
/> />
<div className="flex min-w-0 flex-1 items-center justify-between gap-3"> <div className="flex min-w-0 flex-1 items-center justify-between gap-3">
<div className="min-w-0"> <div className="min-w-0">
<p className="text-sm font-medium"> <p className={cn("text-sm font-medium", isPaid && "line-through")}>
Parcela {installment.currentInstallment}/ Parcela {installment.currentInstallment}/
{group.totalInstallments} {group.totalInstallments}
{isPaid && (
<Badge variant="secondary" className="ml-2 text-xs">
Paga
</Badge>
)}
</p> </p>
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
Vencimento: {dueDate} Vencimento: {dueDate}
@@ -172,7 +184,7 @@ export function InstallmentGroupCard({
<MoneyValues <MoneyValues
amount={installment.amount} amount={installment.amount}
className="shrink-0 text-sm" className={cn("shrink-0 text-sm", isPaid && "opacity-60")}
/> />
</div> </div>
</div> </div>

View File

@@ -10,9 +10,8 @@ import {
calculateLastInstallmentDate, calculateLastInstallmentDate,
formatLastInstallmentDate, formatLastInstallmentDate,
} from "@/lib/installments/utils"; } from "@/lib/installments/utils";
import { RiNumbersLine, RiArrowRightSLine } from "@remixicon/react"; import { RiNumbersLine } from "@remixicon/react";
import Image from "next/image"; import Image from "next/image";
import Link from "next/link";
import { Progress } from "../ui/progress"; import { Progress } from "../ui/progress";
import { WidgetEmptyState } from "../widget-empty-state"; import { WidgetEmptyState } from "../widget-empty-state";
@@ -186,14 +185,6 @@ export function InstallmentExpensesWidget({
); );
})} })}
</ul> </ul>
<Link
href="/dashboard/analise-parcelas"
className="flex items-center justify-center gap-1 px-6 py-2 text-sm font-medium text-primary hover:underline"
>
Ver Análise Completa
<RiArrowRightSLine className="size-4" />
</Link>
</CardContent> </CardContent>
); );
} }

View File

@@ -24,6 +24,7 @@ type WidgetProps = {
subtitle: string; subtitle: string;
children: React.ReactNode; children: React.ReactNode;
icon: React.ReactElement; icon: React.ReactElement;
action?: React.ReactNode;
}; };
export default function WidgetCard({ export default function WidgetCard({
@@ -31,6 +32,7 @@ export default function WidgetCard({
subtitle, subtitle,
icon, icon,
children, children,
action,
}: WidgetProps) { }: WidgetProps) {
const contentRef = useRef<HTMLDivElement | null>(null); const contentRef = useRef<HTMLDivElement | null>(null);
const [hasOverflow, setHasOverflow] = useState(false); const [hasOverflow, setHasOverflow] = useState(false);
@@ -84,6 +86,7 @@ export default function WidgetCard({
{subtitle} {subtitle}
</CardDescription> </CardDescription>
</div> </div>
{action && <div className="shrink-0">{action}</div>}
</div> </div>
</CardHeader> </CardHeader>

View File

@@ -1,12 +1,28 @@
import { cartoes, faturas, lancamentos, pagadores } from "@/db/schema"; import { cartoes, lancamentos } from "@/db/schema";
import { import {
ACCOUNT_AUTO_INVOICE_NOTE_PREFIX, ACCOUNT_AUTO_INVOICE_NOTE_PREFIX,
INITIAL_BALANCE_NOTE, INITIAL_BALANCE_NOTE,
} from "@/lib/accounts/constants"; } from "@/lib/accounts/constants";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { toNumber } from "@/lib/dashboard/common"; import { toNumber } from "@/lib/dashboard/common";
import { INVOICE_PAYMENT_STATUS } from "@/lib/faturas"; import { and, eq, isNotNull, isNull, or, sql } from "drizzle-orm";
import { and, eq, isNotNull, isNull, ne, or, sql } from "drizzle-orm";
// Calcula a data de vencimento baseada no período e dia de vencimento do cartão
function calculateDueDate(period: string, dueDay: string | null): Date | null {
if (!dueDay) return null;
try {
const [year, month] = period.split("-");
if (!year || !month) return null;
const day = parseInt(dueDay, 10);
if (isNaN(day)) return null;
return new Date(parseInt(year), parseInt(month) - 1, day);
} catch {
return null;
}
}
export type InstallmentDetail = { export type InstallmentDetail = {
id: string; id: string;
@@ -16,6 +32,7 @@ export type InstallmentDetail = {
period: string; period: string;
isAnticipated: boolean; isAnticipated: boolean;
purchaseDate: Date; purchaseDate: Date;
isSettled: boolean;
}; };
export type InstallmentGroup = { export type InstallmentGroup = {
@@ -24,6 +41,7 @@ export type InstallmentGroup = {
paymentMethod: string; paymentMethod: string;
cartaoId: string | null; cartaoId: string | null;
cartaoName: string | null; cartaoName: string | null;
cartaoDueDay: string | null;
totalInstallments: number; totalInstallments: number;
paidInstallments: number; paidInstallments: number;
pendingInstallments: InstallmentDetail[]; pendingInstallments: InstallmentDetail[];
@@ -31,38 +49,15 @@ export type InstallmentGroup = {
firstPurchaseDate: Date; firstPurchaseDate: Date;
}; };
export type PendingInvoiceLancamento = {
id: string;
name: string;
amount: number;
purchaseDate: Date;
condition: string;
currentInstallment: number | null;
installmentCount: number | null;
};
export type PendingInvoice = {
invoiceId: string | null;
cartaoId: string;
cartaoName: string;
cartaoLogo: string | null;
period: string;
totalAmount: number;
dueDay: string;
lancamentos: PendingInvoiceLancamento[];
};
export type InstallmentAnalysisData = { export type InstallmentAnalysisData = {
installmentGroups: InstallmentGroup[]; installmentGroups: InstallmentGroup[];
pendingInvoices: PendingInvoice[];
totalPendingInstallments: number; totalPendingInstallments: number;
totalPendingInvoices: number;
}; };
export async function fetchInstallmentAnalysis( export async function fetchInstallmentAnalysis(
userId: string userId: string
): Promise<InstallmentAnalysisData> { ): Promise<InstallmentAnalysisData> {
// 1. Buscar todos os lançamentos parcelados não antecipados e não pagos // 1. Buscar todos os lançamentos parcelados não antecipados
const installmentRows = await db const installmentRows = await db
.select({ .select({
id: lancamentos.id, id: lancamentos.id,
@@ -75,9 +70,11 @@ export async function fetchInstallmentAnalysis(
dueDate: lancamentos.dueDate, dueDate: lancamentos.dueDate,
period: lancamentos.period, period: lancamentos.period,
isAnticipated: lancamentos.isAnticipated, isAnticipated: lancamentos.isAnticipated,
isSettled: lancamentos.isSettled,
purchaseDate: lancamentos.purchaseDate, purchaseDate: lancamentos.purchaseDate,
cartaoId: lancamentos.cartaoId, cartaoId: lancamentos.cartaoId,
cartaoName: cartoes.name, cartaoName: cartoes.name,
cartaoDueDay: cartoes.dueDay,
}) })
.from(lancamentos) .from(lancamentos)
.leftJoin(cartoes, eq(lancamentos.cartaoId, cartoes.id)) .leftJoin(cartoes, eq(lancamentos.cartaoId, cartoes.id))
@@ -106,14 +103,21 @@ export async function fetchInstallmentAnalysis(
if (!row.seriesId) continue; if (!row.seriesId) continue;
const amount = Math.abs(toNumber(row.amount)); const amount = Math.abs(toNumber(row.amount));
// Calcular vencimento correto baseado no período e dia de vencimento do cartão
const calculatedDueDate = row.cartaoDueDay
? calculateDueDate(row.period, row.cartaoDueDay)
: row.dueDate;
const installmentDetail: InstallmentDetail = { const installmentDetail: InstallmentDetail = {
id: row.id, id: row.id,
currentInstallment: row.currentInstallment ?? 1, currentInstallment: row.currentInstallment ?? 1,
amount, amount,
dueDate: row.dueDate, dueDate: calculatedDueDate,
period: row.period, period: row.period,
isAnticipated: row.isAnticipated ?? false, isAnticipated: row.isAnticipated ?? false,
purchaseDate: row.purchaseDate, purchaseDate: row.purchaseDate,
isSettled: row.isSettled ?? false,
}; };
if (seriesMap.has(row.seriesId)) { if (seriesMap.has(row.seriesId)) {
@@ -127,6 +131,7 @@ export async function fetchInstallmentAnalysis(
paymentMethod: row.paymentMethod, paymentMethod: row.paymentMethod,
cartaoId: row.cartaoId, cartaoId: row.cartaoId,
cartaoName: row.cartaoName, cartaoName: row.cartaoName,
cartaoDueDay: row.cartaoDueDay,
totalInstallments: row.installmentCount ?? 0, totalInstallments: row.installmentCount ?? 0,
paidInstallments: 0, paidInstallments: 0,
pendingInstallments: [installmentDetail], pendingInstallments: [installmentDetail],
@@ -145,92 +150,14 @@ export async function fetchInstallmentAnalysis(
return group; return group;
}); });
// 2. Buscar faturas pendentes
const invoiceRows = await db
.select({
invoiceId: faturas.id,
cardId: cartoes.id,
cardName: cartoes.name,
cardLogo: cartoes.logo,
dueDay: cartoes.dueDay,
period: faturas.period,
paymentStatus: faturas.paymentStatus,
})
.from(faturas)
.innerJoin(cartoes, eq(faturas.cartaoId, cartoes.id))
.where(
and(
eq(faturas.userId, userId),
eq(faturas.paymentStatus, INVOICE_PAYMENT_STATUS.PENDING)
)
);
// Buscar lançamentos de cada fatura pendente
const pendingInvoices: PendingInvoice[] = [];
for (const invoice of invoiceRows) {
const invoiceLancamentos = await db
.select({
id: lancamentos.id,
name: lancamentos.name,
amount: lancamentos.amount,
purchaseDate: lancamentos.purchaseDate,
condition: lancamentos.condition,
currentInstallment: lancamentos.currentInstallment,
installmentCount: lancamentos.installmentCount,
})
.from(lancamentos)
.where(
and(
eq(lancamentos.userId, userId),
eq(lancamentos.cartaoId, invoice.cardId),
eq(lancamentos.period, invoice.period ?? "")
)
)
.orderBy(lancamentos.purchaseDate);
const totalAmount = invoiceLancamentos.reduce(
(sum, l) => sum + Math.abs(toNumber(l.amount)),
0
);
if (totalAmount > 0) {
pendingInvoices.push({
invoiceId: invoice.invoiceId,
cartaoId: invoice.cardId,
cartaoName: invoice.cardName,
cartaoLogo: invoice.cardLogo,
period: invoice.period ?? "",
totalAmount,
dueDay: invoice.dueDay,
lancamentos: invoiceLancamentos.map((l) => ({
id: l.id,
name: l.name,
amount: Math.abs(toNumber(l.amount)),
purchaseDate: l.purchaseDate,
condition: l.condition,
currentInstallment: l.currentInstallment,
installmentCount: l.installmentCount,
})),
});
}
}
// Calcular totais // Calcular totais
const totalPendingInstallments = installmentGroups.reduce( const totalPendingInstallments = installmentGroups.reduce(
(sum, group) => sum + group.totalPendingAmount, (sum, group) => sum + group.totalPendingAmount,
0 0
); );
const totalPendingInvoices = pendingInvoices.reduce(
(sum, invoice) => sum + invoice.totalAmount,
0
);
return { return {
installmentGroups, installmentGroups,
pendingInvoices,
totalPendingInstallments, totalPendingInstallments,
totalPendingInvoices,
}; };
} }

View File

@@ -13,6 +13,7 @@ import { RecentTransactionsWidget } from "@/components/dashboard/recent-transact
import { RecurringExpensesWidget } from "@/components/dashboard/recurring-expenses-widget"; import { RecurringExpensesWidget } from "@/components/dashboard/recurring-expenses-widget";
import { TopEstablishmentsWidget } from "@/components/dashboard/top-establishments-widget"; import { TopEstablishmentsWidget } from "@/components/dashboard/top-establishments-widget";
import { TopExpensesWidget } from "@/components/dashboard/top-expenses-widget"; import { TopExpensesWidget } from "@/components/dashboard/top-expenses-widget";
import Link from "next/link";
import { import {
RiArrowUpDoubleLine, RiArrowUpDoubleLine,
RiBarChartBoxLine, RiBarChartBoxLine,
@@ -38,6 +39,7 @@ export type WidgetConfig = {
subtitle: string; subtitle: string;
icon: ReactNode; icon: ReactNode;
component: (props: { data: DashboardData; period: string }) => ReactNode; component: (props: { data: DashboardData; period: string }) => ReactNode;
action?: ReactNode;
}; };
export const widgetsConfig: WidgetConfig[] = [ export const widgetsConfig: WidgetConfig[] = [
@@ -134,6 +136,14 @@ export const widgetsConfig: WidgetConfig[] = [
component: ({ data }) => ( component: ({ data }) => (
<InstallmentExpensesWidget data={data.installmentExpensesData} /> <InstallmentExpensesWidget data={data.installmentExpensesData} />
), ),
action: (
<Link
href="/dashboard/analise-parcelas"
className="text-xs font-medium text-muted-foreground hover:text-primary transition-colors"
>
Análise
</Link>
),
}, },
{ {
id: "top-expenses", id: "top-expenses",