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:
@@ -16,6 +16,7 @@ export function DashboardGrid({ data, period }: DashboardGridProps) {
|
||||
title={widget.title}
|
||||
subtitle={widget.subtitle}
|
||||
icon={widget.icon}
|
||||
action={widget.action}
|
||||
>
|
||||
{widget.component({ data, period })}
|
||||
</WidgetCard>
|
||||
|
||||
@@ -2,25 +2,19 @@
|
||||
|
||||
import MoneyValues from "@/components/money-values";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { RiPieChartLine } from "@remixicon/react";
|
||||
|
||||
type AnalysisSummaryPanelProps = {
|
||||
totalInstallments: number;
|
||||
totalInvoices: number;
|
||||
grandTotal: number;
|
||||
selectedCount: number;
|
||||
};
|
||||
|
||||
export function AnalysisSummaryPanel({
|
||||
totalInstallments,
|
||||
totalInvoices,
|
||||
grandTotal,
|
||||
selectedCount,
|
||||
}: AnalysisSummaryPanelProps) {
|
||||
const hasInstallments = totalInstallments > 0;
|
||||
const hasInvoices = totalInvoices > 0;
|
||||
|
||||
return (
|
||||
<Card className="border-primary/20">
|
||||
<CardHeader className="border-b">
|
||||
@@ -29,9 +23,9 @@ export function AnalysisSummaryPanel({
|
||||
<CardTitle className="text-base">Resumo</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4 pt-6">
|
||||
<CardContent className="flex flex-col gap-3 pt-4">
|
||||
{/* 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">
|
||||
Total Selecionado
|
||||
</p>
|
||||
@@ -40,67 +34,15 @@ export function AnalysisSummaryPanel({
|
||||
className="text-2xl font-bold text-primary"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{selectedCount} {selectedCount === 1 ? "item" : "itens"}
|
||||
{selectedCount} {selectedCount === 1 ? "parcela" : "parcelas"}
|
||||
</p>
|
||||
</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 */}
|
||||
{selectedCount === 0 && (
|
||||
<div className="rounded-lg bg-muted/50 p-3 text-center">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Selecione parcelas ou faturas para ver o resumo
|
||||
Selecione parcelas para ver o resumo
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -7,7 +7,6 @@ import { Separator } from "@/components/ui/separator";
|
||||
import { useMemo, useState } from "react";
|
||||
import type { InstallmentAnalysisData } from "./types";
|
||||
import { InstallmentGroupCard } from "./installment-group-card";
|
||||
import { PendingInvoiceCard } from "./pending-invoice-card";
|
||||
import { AnalysisSummaryPanel } from "./analysis-summary-panel";
|
||||
import {
|
||||
RiCalculatorLine,
|
||||
@@ -27,52 +26,38 @@ export function InstallmentAnalysisPage({
|
||||
Map<string, Set<string>>
|
||||
>(new Map());
|
||||
|
||||
// Estado para faturas selecionadas: Set<invoiceKey (cartaoId:period)>
|
||||
const [selectedInvoices, setSelectedInvoices] = useState<Set<string>>(
|
||||
new Set()
|
||||
);
|
||||
|
||||
// Calcular se está tudo selecionado
|
||||
// Calcular se está tudo selecionado (apenas parcelas não pagas)
|
||||
const isAllSelected = useMemo(() => {
|
||||
const allInstallmentsSelected = data.installmentGroups.every((group) => {
|
||||
const groupSelection = selectedInstallments.get(group.seriesId);
|
||||
if (!groupSelection) return false;
|
||||
return (
|
||||
groupSelection.size === group.pendingInstallments.length &&
|
||||
group.pendingInstallments.length > 0
|
||||
const unpaidInstallments = group.pendingInstallments.filter(
|
||||
(i) => !i.isSettled
|
||||
);
|
||||
if (!groupSelection || unpaidInstallments.length === 0) return false;
|
||||
return groupSelection.size === unpaidInstallments.length;
|
||||
});
|
||||
|
||||
const allInvoicesSelected =
|
||||
data.pendingInvoices.length === selectedInvoices.size;
|
||||
|
||||
return (
|
||||
allInstallmentsSelected &&
|
||||
allInvoicesSelected &&
|
||||
(data.installmentGroups.length > 0 || data.pendingInvoices.length > 0)
|
||||
);
|
||||
}, [selectedInstallments, selectedInvoices, data]);
|
||||
return allInstallmentsSelected && data.installmentGroups.length > 0;
|
||||
}, [selectedInstallments, data]);
|
||||
|
||||
// Função para selecionar/desselecionar tudo
|
||||
const toggleSelectAll = () => {
|
||||
if (isAllSelected) {
|
||||
// Desmarcar tudo
|
||||
setSelectedInstallments(new Map());
|
||||
setSelectedInvoices(new Set());
|
||||
} else {
|
||||
// Marcar tudo
|
||||
// Marcar tudo (exceto parcelas já pagas)
|
||||
const newInstallments = new Map<string, Set<string>>();
|
||||
data.installmentGroups.forEach((group) => {
|
||||
const ids = new Set(group.pendingInstallments.map((i) => i.id));
|
||||
newInstallments.set(group.seriesId, ids);
|
||||
const unpaidIds = group.pendingInstallments
|
||||
.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);
|
||||
setSelectedInvoices(newInvoices);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -112,20 +97,8 @@ export function InstallmentAnalysisPage({
|
||||
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
|
||||
const { totalInstallments, totalInvoices, grandTotal, selectedCount } =
|
||||
useMemo(() => {
|
||||
const { totalInstallments, grandTotal, selectedCount } = useMemo(() => {
|
||||
let installmentsSum = 0;
|
||||
let installmentsCount = 0;
|
||||
|
||||
@@ -138,7 +111,7 @@ export function InstallmentAnalysisPage({
|
||||
const installment = group.pendingInstallments.find(
|
||||
(i) => i.id === id
|
||||
);
|
||||
if (installment) {
|
||||
if (installment && !installment.isSettled) {
|
||||
installmentsSum += installment.amount;
|
||||
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 {
|
||||
totalInstallments: installmentsSum,
|
||||
totalInvoices: invoicesSum,
|
||||
grandTotal: installmentsSum + invoicesSum,
|
||||
selectedCount: installmentsCount + invoicesCount,
|
||||
grandTotal: installmentsSum,
|
||||
selectedCount: installmentsCount,
|
||||
};
|
||||
}, [selectedInstallments, selectedInvoices, data]);
|
||||
}, [selectedInstallments, data]);
|
||||
|
||||
const hasNoData =
|
||||
data.installmentGroups.length === 0 && data.pendingInvoices.length === 0;
|
||||
const hasNoData = data.installmentGroups.length === 0;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex size-10 items-center justify-center rounded-lg bg-primary/10">
|
||||
<RiCalculatorLine className="size-5 text-primary" />
|
||||
<div className="flex size-9 items-center justify-center rounded-lg bg-primary/10">
|
||||
<RiCalculatorLine className="size-4 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Análise de Parcelas e Faturas</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Veja quanto você gastaria pagando tudo que está em aberto
|
||||
<h1 className="text-xl font-bold">Análise de Parcelas</h1>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Quanto você gastaria pagando tudo que está em aberto
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Card de resumo principal */}
|
||||
<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">
|
||||
<p className="text-sm font-medium text-muted-foreground">
|
||||
<CardContent className="flex flex-col items-center justify-center gap-2 py-5">
|
||||
<p className="text-xs font-medium text-muted-foreground">
|
||||
Se você pagar tudo que está selecionado:
|
||||
</p>
|
||||
<MoneyValues
|
||||
amount={grandTotal}
|
||||
className="text-4xl font-bold text-primary"
|
||||
className="text-3xl font-bold text-primary"
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{selectedCount} {selectedCount === 1 ? "item" : "itens"} selecionados
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{selectedCount} {selectedCount === 1 ? "parcela" : "parcelas"} selecionadas
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -221,7 +178,7 @@ export function InstallmentAnalysisPage({
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid gap-6 lg:grid-cols-[1fr_320px]">
|
||||
<div className="grid gap-4 lg:grid-cols-[1fr_280px]">
|
||||
{/* Conteúdo principal */}
|
||||
<div className="flex flex-col gap-6">
|
||||
{/* Seção de Lançamentos Parcelados */}
|
||||
@@ -244,7 +201,9 @@ export function InstallmentAnalysisPage({
|
||||
onToggleGroup={() =>
|
||||
toggleGroupSelection(
|
||||
group.seriesId,
|
||||
group.pendingInstallments.map((i) => i.id)
|
||||
group.pendingInstallments
|
||||
.filter((i) => !i.isSettled)
|
||||
.map((i) => i.id)
|
||||
)
|
||||
}
|
||||
onToggleInstallment={(installmentId) =>
|
||||
@@ -256,38 +215,13 @@ export function InstallmentAnalysisPage({
|
||||
</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 */}
|
||||
{hasNoData && (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center justify-center gap-3 py-12">
|
||||
<RiCalculatorLine className="size-12 text-muted-foreground/50" />
|
||||
<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">
|
||||
Você está em dia com seus pagamentos!
|
||||
</p>
|
||||
@@ -302,7 +236,6 @@ export function InstallmentAnalysisPage({
|
||||
<div className="lg:sticky lg:top-4 lg:self-start">
|
||||
<AnalysisSummaryPanel
|
||||
totalInstallments={totalInstallments}
|
||||
totalInvoices={totalInvoices}
|
||||
grandTotal={grandTotal}
|
||||
selectedCount={selectedCount}
|
||||
/>
|
||||
|
||||
@@ -27,13 +27,17 @@ export function InstallmentGroupCard({
|
||||
}: InstallmentGroupCardProps) {
|
||||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
|
||||
const unpaidInstallments = group.pendingInstallments.filter(
|
||||
(i) => !i.isSettled
|
||||
);
|
||||
|
||||
const isFullySelected =
|
||||
selectedInstallments.size === group.pendingInstallments.length &&
|
||||
group.pendingInstallments.length > 0;
|
||||
selectedInstallments.size === unpaidInstallments.length &&
|
||||
unpaidInstallments.length > 0;
|
||||
|
||||
const isPartiallySelected =
|
||||
selectedInstallments.size > 0 &&
|
||||
selectedInstallments.size < group.pendingInstallments.length;
|
||||
selectedInstallments.size < unpaidInstallments.length;
|
||||
|
||||
const progress =
|
||||
group.totalInstallments > 0
|
||||
@@ -48,7 +52,7 @@ export function InstallmentGroupCard({
|
||||
|
||||
return (
|
||||
<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 */}
|
||||
<div className="flex items-start gap-3">
|
||||
<Checkbox
|
||||
@@ -61,8 +65,8 @@ export function InstallmentGroupCard({
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="font-medium">{group.name}</p>
|
||||
<div className="mt-1 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
||||
<p className="text-sm font-medium">{group.name}</p>
|
||||
<div className="mt-0.5 flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">
|
||||
{group.cartaoName && (
|
||||
<>
|
||||
<span>{group.cartaoName}</span>
|
||||
@@ -73,7 +77,7 @@ export function InstallmentGroupCard({
|
||||
</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
|
||||
amount={group.totalPendingAmount}
|
||||
className="text-sm font-semibold"
|
||||
@@ -88,7 +92,7 @@ export function InstallmentGroupCard({
|
||||
</div>
|
||||
|
||||
{/* Progress bar */}
|
||||
<div className="mt-3">
|
||||
<div className="mt-2">
|
||||
<div className="mb-1 flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span>
|
||||
{group.paidInstallments} de {group.totalInstallments} pagas
|
||||
@@ -100,7 +104,7 @@ export function InstallmentGroupCard({
|
||||
: "pendentes"}
|
||||
</span>
|
||||
</div>
|
||||
<Progress value={progress} className="h-2" />
|
||||
<Progress value={progress} className="h-1.5" />
|
||||
</div>
|
||||
|
||||
{/* 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">
|
||||
{group.pendingInstallments.map((installment) => {
|
||||
const isSelected = selectedInstallments.has(installment.id);
|
||||
const isPaid = installment.isSettled;
|
||||
const dueDate = installment.dueDate
|
||||
? format(installment.dueDate, "dd/MM/yyyy", { locale: ptBR })
|
||||
: format(installment.purchaseDate, "dd/MM/yyyy", {
|
||||
@@ -150,20 +155,27 @@ export function InstallmentGroupCard({
|
||||
key={installment.id}
|
||||
className={cn(
|
||||
"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
|
||||
checked={isSelected}
|
||||
onCheckedChange={() => onToggleInstallment(installment.id)}
|
||||
checked={isPaid ? false : isSelected}
|
||||
disabled={isPaid}
|
||||
onCheckedChange={() => !isPaid && onToggleInstallment(installment.id)}
|
||||
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="min-w-0">
|
||||
<p className="text-sm font-medium">
|
||||
<p className={cn("text-sm font-medium", isPaid && "line-through")}>
|
||||
Parcela {installment.currentInstallment}/
|
||||
{group.totalInstallments}
|
||||
{isPaid && (
|
||||
<Badge variant="secondary" className="ml-2 text-xs">
|
||||
Paga
|
||||
</Badge>
|
||||
)}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Vencimento: {dueDate}
|
||||
@@ -172,7 +184,7 @@ export function InstallmentGroupCard({
|
||||
|
||||
<MoneyValues
|
||||
amount={installment.amount}
|
||||
className="shrink-0 text-sm"
|
||||
className={cn("shrink-0 text-sm", isPaid && "opacity-60")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -10,9 +10,8 @@ import {
|
||||
calculateLastInstallmentDate,
|
||||
formatLastInstallmentDate,
|
||||
} from "@/lib/installments/utils";
|
||||
import { RiNumbersLine, RiArrowRightSLine } from "@remixicon/react";
|
||||
import { RiNumbersLine } from "@remixicon/react";
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import { Progress } from "../ui/progress";
|
||||
import { WidgetEmptyState } from "../widget-empty-state";
|
||||
|
||||
@@ -186,14 +185,6 @@ export function InstallmentExpensesWidget({
|
||||
);
|
||||
})}
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ type WidgetProps = {
|
||||
subtitle: string;
|
||||
children: React.ReactNode;
|
||||
icon: React.ReactElement;
|
||||
action?: React.ReactNode;
|
||||
};
|
||||
|
||||
export default function WidgetCard({
|
||||
@@ -31,6 +32,7 @@ export default function WidgetCard({
|
||||
subtitle,
|
||||
icon,
|
||||
children,
|
||||
action,
|
||||
}: WidgetProps) {
|
||||
const contentRef = useRef<HTMLDivElement | null>(null);
|
||||
const [hasOverflow, setHasOverflow] = useState(false);
|
||||
@@ -84,6 +86,7 @@ export default function WidgetCard({
|
||||
{subtitle}
|
||||
</CardDescription>
|
||||
</div>
|
||||
{action && <div className="shrink-0">{action}</div>}
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
|
||||
@@ -1,12 +1,28 @@
|
||||
import { cartoes, faturas, lancamentos, pagadores } from "@/db/schema";
|
||||
import { cartoes, lancamentos } from "@/db/schema";
|
||||
import {
|
||||
ACCOUNT_AUTO_INVOICE_NOTE_PREFIX,
|
||||
INITIAL_BALANCE_NOTE,
|
||||
} from "@/lib/accounts/constants";
|
||||
import { db } from "@/lib/db";
|
||||
import { toNumber } from "@/lib/dashboard/common";
|
||||
import { INVOICE_PAYMENT_STATUS } from "@/lib/faturas";
|
||||
import { and, eq, isNotNull, isNull, ne, or, sql } from "drizzle-orm";
|
||||
import { and, eq, isNotNull, isNull, 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 = {
|
||||
id: string;
|
||||
@@ -16,6 +32,7 @@ export type InstallmentDetail = {
|
||||
period: string;
|
||||
isAnticipated: boolean;
|
||||
purchaseDate: Date;
|
||||
isSettled: boolean;
|
||||
};
|
||||
|
||||
export type InstallmentGroup = {
|
||||
@@ -24,6 +41,7 @@ export type InstallmentGroup = {
|
||||
paymentMethod: string;
|
||||
cartaoId: string | null;
|
||||
cartaoName: string | null;
|
||||
cartaoDueDay: string | null;
|
||||
totalInstallments: number;
|
||||
paidInstallments: number;
|
||||
pendingInstallments: InstallmentDetail[];
|
||||
@@ -31,38 +49,15 @@ export type InstallmentGroup = {
|
||||
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 = {
|
||||
installmentGroups: InstallmentGroup[];
|
||||
pendingInvoices: PendingInvoice[];
|
||||
totalPendingInstallments: number;
|
||||
totalPendingInvoices: number;
|
||||
};
|
||||
|
||||
export async function fetchInstallmentAnalysis(
|
||||
userId: string
|
||||
): 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
|
||||
.select({
|
||||
id: lancamentos.id,
|
||||
@@ -75,9 +70,11 @@ export async function fetchInstallmentAnalysis(
|
||||
dueDate: lancamentos.dueDate,
|
||||
period: lancamentos.period,
|
||||
isAnticipated: lancamentos.isAnticipated,
|
||||
isSettled: lancamentos.isSettled,
|
||||
purchaseDate: lancamentos.purchaseDate,
|
||||
cartaoId: lancamentos.cartaoId,
|
||||
cartaoName: cartoes.name,
|
||||
cartaoDueDay: cartoes.dueDay,
|
||||
})
|
||||
.from(lancamentos)
|
||||
.leftJoin(cartoes, eq(lancamentos.cartaoId, cartoes.id))
|
||||
@@ -106,14 +103,21 @@ export async function fetchInstallmentAnalysis(
|
||||
if (!row.seriesId) continue;
|
||||
|
||||
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 = {
|
||||
id: row.id,
|
||||
currentInstallment: row.currentInstallment ?? 1,
|
||||
amount,
|
||||
dueDate: row.dueDate,
|
||||
dueDate: calculatedDueDate,
|
||||
period: row.period,
|
||||
isAnticipated: row.isAnticipated ?? false,
|
||||
purchaseDate: row.purchaseDate,
|
||||
isSettled: row.isSettled ?? false,
|
||||
};
|
||||
|
||||
if (seriesMap.has(row.seriesId)) {
|
||||
@@ -127,6 +131,7 @@ export async function fetchInstallmentAnalysis(
|
||||
paymentMethod: row.paymentMethod,
|
||||
cartaoId: row.cartaoId,
|
||||
cartaoName: row.cartaoName,
|
||||
cartaoDueDay: row.cartaoDueDay,
|
||||
totalInstallments: row.installmentCount ?? 0,
|
||||
paidInstallments: 0,
|
||||
pendingInstallments: [installmentDetail],
|
||||
@@ -145,92 +150,14 @@ export async function fetchInstallmentAnalysis(
|
||||
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
|
||||
const totalPendingInstallments = installmentGroups.reduce(
|
||||
(sum, group) => sum + group.totalPendingAmount,
|
||||
0
|
||||
);
|
||||
|
||||
const totalPendingInvoices = pendingInvoices.reduce(
|
||||
(sum, invoice) => sum + invoice.totalAmount,
|
||||
0
|
||||
);
|
||||
|
||||
return {
|
||||
installmentGroups,
|
||||
pendingInvoices,
|
||||
totalPendingInstallments,
|
||||
totalPendingInvoices,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import { RecentTransactionsWidget } from "@/components/dashboard/recent-transact
|
||||
import { RecurringExpensesWidget } from "@/components/dashboard/recurring-expenses-widget";
|
||||
import { TopEstablishmentsWidget } from "@/components/dashboard/top-establishments-widget";
|
||||
import { TopExpensesWidget } from "@/components/dashboard/top-expenses-widget";
|
||||
import Link from "next/link";
|
||||
import {
|
||||
RiArrowUpDoubleLine,
|
||||
RiBarChartBoxLine,
|
||||
@@ -38,6 +39,7 @@ export type WidgetConfig = {
|
||||
subtitle: string;
|
||||
icon: ReactNode;
|
||||
component: (props: { data: DashboardData; period: string }) => ReactNode;
|
||||
action?: ReactNode;
|
||||
};
|
||||
|
||||
export const widgetsConfig: WidgetConfig[] = [
|
||||
@@ -134,6 +136,14 @@ export const widgetsConfig: WidgetConfig[] = [
|
||||
component: ({ data }) => (
|
||||
<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",
|
||||
|
||||
Reference in New Issue
Block a user