fix(boletos): diferencia pagamentos e recebimentos

This commit is contained in:
Felipe Coutinho
2026-05-31 15:18:55 -03:00
parent 35abe1b0bf
commit 99bc049cf4
10 changed files with 130 additions and 58 deletions

View File

@@ -81,6 +81,8 @@ const renderLancamento = (
const renderBoleto = (event: Extract<CalendarEvent, { type: "boleto" }>) => {
const isPaid = Boolean(event.transaction.isSettled);
const isIncome = event.transaction.transactionType === "Receita";
const settlementLabel = isIncome ? "Recebido" : "Pago";
const dueDateLabel = formatFinancialDateLabel(
event.transaction.dueDate,
"Vence em",
@@ -89,7 +91,7 @@ const renderBoleto = (event: Extract<CalendarEvent, { type: "boleto" }>) => {
const paymentDateLabel = isPaid
? formatFinancialDateLabel(
event.transaction.boletoPaymentDate,
"Pago em",
`${settlementLabel} em`,
DATE_FORMAT,
)
: null;
@@ -109,7 +111,9 @@ const renderBoleto = (event: Extract<CalendarEvent, { type: "boleto" }>) => {
<span className="text-success">{paymentDateLabel}</span>
)}
</div>
<Badge variant="outline">{isPaid ? "Pago" : "Pendente"}</Badge>
<Badge variant="outline">
{isPaid ? settlementLabel : "Pendente"}
</Badge>
</div>
<MoneyValues
className="font-medium whitespace-nowrap"

View File

@@ -1,18 +1,28 @@
import type { DashboardBill } from "@/features/dashboard/bills/bills-queries";
import type { PaymentDialogState } from "@/features/dashboard/payments/use-payment-dialog-controller";
import { getBusinessDateString, isDateOnlyPast } from "@/shared/utils/date";
import {
getBusinessDateString,
isDateOnlyPast,
parseUtcDateString,
toDateOnlyString,
} from "@/shared/utils/date";
import {
buildFinancialStatusLabel,
buildRelativeFinancialStatusLabel,
formatFinancialDateLabel,
formatRelativeFinancialDateLabel,
} from "@/shared/utils/financial-dates";
export type BillDialogState = PaymentDialogState;
type BillStatusDateItem = Pick<
DashboardBill,
"dueDate" | "boletoPaymentDate" | "isSettled"
"dueDate" | "boletoPaymentDate" | "isSettled" | "transactionType"
>;
export const isIncomeBill = (bill: Pick<DashboardBill, "transactionType">) => {
return bill.transactionType === "Receita";
};
export const formatBillDateLabel = (value: string | null, prefix?: string) => {
return formatFinancialDateLabel(value, prefix);
};
@@ -22,10 +32,15 @@ export const buildBillStatusLabel = (bill: BillStatusDateItem) => {
isSettled: bill.isSettled,
dueDate: bill.dueDate,
paidAt: bill.boletoPaymentDate,
paidPrefix: isIncomeBill(bill) ? "Recebido em" : "Pago em",
});
};
export const buildBillWidgetStatusLabel = (bill: BillStatusDateItem) => {
if (bill.isSettled && isIncomeBill(bill)) {
return formatRelativeFinancialDateLabel(bill.boletoPaymentDate, "received");
}
return buildRelativeFinancialStatusLabel({
isSettled: bill.isSettled,
dueDate: bill.dueDate,
@@ -43,6 +58,34 @@ export const isBillOverdue = (bill: DashboardBill) => {
return isDateOnlyPast(bill.dueDate);
};
export const formatBillWidgetOverdueLabel = (
bill: Pick<DashboardBill, "dueDate" | "isSettled" | "transactionType">,
): string | null => {
if (bill.isSettled) {
return null;
}
const dueDateValue = toDateOnlyString(bill.dueDate);
const todayValue = getBusinessDateString();
if (!dueDateValue || dueDateValue >= todayValue) {
return null;
}
const dueDate = parseUtcDateString(dueDateValue);
const today = parseUtcDateString(todayValue);
if (!dueDate || !today) {
return null;
}
const overdueDays = Math.round(
(today.getTime() - dueDate.getTime()) / (24 * 60 * 60 * 1000),
);
const overdueLabel = isIncomeBill(bill) ? "Atrasada" : "Atrasado";
return overdueDays === 1
? `${overdueLabel} · venceu ontem`
: `${overdueLabel} · venceu há ${overdueDays} dias`;
};
export const getBillStatusBadgeVariant = (
statusLabel: string,
): "success" | "info" => {

View File

@@ -1,9 +1,11 @@
import { RiCheckboxCircleFill, RiExternalLinkLine } from "@remixicon/react";
import { RiCheckboxCircleFill } from "@remixicon/react";
import Link from "next/link";
import {
buildBillStatusLabel,
buildBillWidgetStatusLabel,
formatBillWidgetOverdueLabel,
isBillOverdue,
isIncomeBill,
} from "@/features/dashboard/bills/bills-helpers";
import type { DashboardBill } from "@/features/dashboard/bills/bills-queries";
import { EstablishmentLogo } from "@/shared/components/entity-avatar";
@@ -36,8 +38,10 @@ export function BillListItem({ bill, period, onPay }: BillListItemProps) {
const statusLabel = buildBillWidgetStatusLabel(bill);
const absoluteStatusLabel = buildBillStatusLabel(bill);
const overdue = isBillOverdue(bill);
const income = isIncomeBill(bill);
const overdueLabel = formatBillWidgetOverdueLabel(bill);
const statusTooltipLabel =
statusLabel && statusLabel !== absoluteStatusLabel
overdueLabel || (statusLabel && statusLabel !== absoluteStatusLabel)
? absoluteStatusLabel
: null;
const href = buildTransactionsHref(bill.name, period);
@@ -53,10 +57,6 @@ export function BillListItem({ bill, period, onPay }: BillListItemProps) {
className="inline-flex max-w-full items-center gap-1 text-sm font-medium text-foreground underline-offset-2 hover:text-primary hover:underline"
>
<span className="truncate">{bill.name}</span>
<RiExternalLinkLine
className="size-3 shrink-0 text-muted-foreground"
aria-hidden
/>
</Link>
<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
{statusLabel ? (
@@ -67,9 +67,10 @@ export function BillListItem({ bill, period, onPay }: BillListItemProps) {
className={cn(
"cursor-help rounded-full py-0.5",
bill.isSettled && "text-success font-semibold",
overdue && "text-destructive font-semibold",
)}
>
{statusLabel}
{overdueLabel ?? statusLabel}
</span>
</TooltipTrigger>
<TooltipContent side="top">
@@ -81,9 +82,10 @@ export function BillListItem({ bill, period, onPay }: BillListItemProps) {
className={cn(
"rounded-full py-0.5",
bill.isSettled && "text-success font-semibold",
overdue && "text-destructive font-semibold",
)}
>
{statusLabel}
{overdueLabel ?? statusLabel}
</span>
)
) : null}
@@ -93,29 +95,35 @@ export function BillListItem({ bill, period, onPay }: BillListItemProps) {
<div className="flex shrink-0 flex-col items-end">
<MoneyValues className="font-medium" amount={bill.amount} />
<Button
type="button"
size="sm"
variant="link"
className="h-auto p-0 disabled:opacity-100"
disabled={bill.isSettled}
onClick={() => onPay(bill.id)}
>
{bill.isSettled ? (
<span className="flex items-center gap-0.5 text-success">
<RiCheckboxCircleFill className="size-3.5" /> Pago
</span>
) : overdue ? (
<span className="overdue-blink">
<span className="overdue-blink-primary text-destructive">
Atrasado
{bill.isSettled ? (
<span className="flex h-7 items-center gap-0.5 text-xs font-medium text-success">
<RiCheckboxCircleFill className="size-3.5" />{" "}
{income ? "Recebido" : "Pago"}
</span>
) : (
<Button
type="button"
size="sm"
variant="link"
className="-mr-1.5 h-7 px-1.5 py-0"
onClick={() => onPay(bill.id)}
>
{overdue ? (
<span className="overdue-blink">
<span className="overdue-blink-primary text-destructive">
{income ? "Atrasada" : "Atrasado"}
</span>
<span className="overdue-blink-secondary">
{income ? "Receber" : "Pagar"}
</span>
</span>
<span className="overdue-blink-secondary">Pagar</span>
</span>
) : (
"Pagar"
)}
</Button>
) : income ? (
"Receber"
) : (
"Pagar"
)}
</Button>
)}
</div>
</li>
);

View File

@@ -7,6 +7,7 @@ import {
type BillDialogState,
formatBillDateLabel,
getBillStatusBadgeVariant,
isIncomeBill,
} from "@/features/dashboard/bills/bills-helpers";
import type {
BillPaymentAccountOption,
@@ -66,11 +67,13 @@ export function BillPaymentDialog({
onConfirm,
}: BillPaymentDialogProps) {
const isProcessing = modalState === "processing" || isPending;
const income = bill ? isIncomeBill(bill) : false;
const settlementLabel = income ? "Recebido" : "Pago";
const dueLabel = bill
? formatBillDateLabel(bill.dueDate, "Vencimento:")
: null;
const paidLabel = bill
? formatBillDateLabel(bill.boletoPaymentDate, "Pago em:")
? formatBillDateLabel(bill.boletoPaymentDate, `${settlementLabel} em:`)
: null;
const isBillPending = bill ? !bill.isSettled : false;
const paymentDateValue = paymentDate.toISOString().split("T")[0] ?? "";
@@ -103,8 +106,8 @@ export function BillPaymentDialog({
>
{modalState === "success" ? (
<PaymentSuccess
title="Pagamento registrado!"
description="Atualizamos o status do boleto para pago. Em instantes ele aparecerá como baixado no histórico."
title={income ? "Recebimento registrado!" : "Pagamento registrado!"}
description={`Atualizamos o status do boleto para ${income ? "recebido" : "pago"}. Em instantes ele aparecerá como baixado no histórico.`}
onClose={onClose}
/>
) : (
@@ -112,10 +115,12 @@ export function BillPaymentDialog({
<DialogHeader>
<div className="mb-1 flex items-center gap-3">
<div>
<DialogTitle>Confirmar pagamento</DialogTitle>
<DialogTitle>
{income ? "Confirmar recebimento" : "Confirmar pagamento"}
</DialogTitle>
<DialogDescription className="mt-1 text-xs">
{isBillPending
? "Escolha a conta de origem e a data em que o boleto foi pago."
? `Escolha a conta de ${income ? "destino" : "origem"} e a data em que o boleto foi ${income ? "recebido" : "pago"}.`
: "Boleto"}
</DialogDescription>
</div>
@@ -158,12 +163,15 @@ export function BillPaymentDialog({
<div className="flex items-center gap-1.5 text-muted-foreground">
<RiCalendarLine className="size-3.5" />
<span className="text-xs font-medium uppercase">
{bill.isSettled ? "Pago em" : "Vencimento"}
{bill.isSettled
? `${settlementLabel} em`
: "Vencimento"}
</span>
</div>
<p className="font-semibold">
{bill.isSettled
? (paidLabel?.replace("Pago em: ", "") ?? "—")
? (paidLabel?.replace(`${settlementLabel} em: `, "") ??
"—")
: (dueLabel?.replace("Vencimento: ", "") ?? "—")}
</p>
</Card>
@@ -175,7 +183,7 @@ export function BillPaymentDialog({
<div className="space-y-3">
<div className="space-y-2">
<Label htmlFor="bill-widget-payment-account">
Conta de pagamento
Conta de {income ? "recebimento" : "pagamento"}
</Label>
<Select
value={paymentAccountId}
@@ -212,7 +220,7 @@ export function BillPaymentDialog({
<div className="space-y-2">
<Label htmlFor="bill-widget-payment-date">
Data do pagamento
Data do {income ? "recebimento" : "pagamento"}
</Label>
<DatePicker
id="bill-widget-payment-date"
@@ -231,8 +239,8 @@ export function BillPaymentDialog({
<span className="text-sm text-muted-foreground">
Status atual
</span>
<Badge variant={getBillStatusBadgeVariant("Pago")}>
Pago
<Badge variant={getBillStatusBadgeVariant(settlementLabel)}>
{settlementLabel}
</Badge>
</div>
)}

View File

@@ -15,7 +15,7 @@ export function BillsList({ bills, period, onPay }: BillsListProps) {
<WidgetEmptyState
icon={<RiBarcodeFill className="size-6 text-muted-foreground" />}
title="Nenhum boleto cadastrado para o período selecionado"
description="Cadastre boletos para monitorar os pagamentos aqui."
description="Cadastre boletos para monitorar os vencimentos aqui."
/>
);
}

View File

@@ -41,9 +41,7 @@ export function BillsWidgetView({
}: BillsWidgetViewProps) {
return (
<>
<div className="flex flex-col gap-4">
<BillsList bills={bills} period={period} onPay={onOpenPaymentDialog} />
</div>
<BillsList bills={bills} period={period} onPay={onOpenPaymentDialog} />
<BillPaymentDialog
bill={selectedBill}

View File

@@ -30,7 +30,7 @@ export function PayerBoletoCard({ items }: PayerBoletoCardProps) {
<WidgetEmptyState
icon={<RiBarcodeLine className="size-6 text-muted-foreground" />}
title="Nenhum boleto cadastrado para o período"
description="Quando houver despesas registradas com boleto, elas aparecerão aqui."
description="Quando houver lançamentos registrados com boleto, eles aparecerão aqui."
/>
</CardContent>
);

View File

@@ -608,7 +608,12 @@ export async function toggleTransactionSettlementAction(
const data = toggleSettlementSchema.parse(input);
const existing = await db.query.transactions.findFirst({
columns: { id: true, paymentMethod: true, accountId: true },
columns: {
id: true,
paymentMethod: true,
accountId: true,
transactionType: true,
},
where: and(
eq(transactions.id, data.id),
eq(transactions.userId, user.id),
@@ -627,6 +632,7 @@ export async function toggleTransactionSettlementAction(
}
const isBoleto = existing.paymentMethod === "Boleto";
const isIncomeBill = isBoleto && existing.transactionType === "Receita";
const customPaymentDate =
isBoleto && data.value && data.paymentDate
? parseLocalDateString(data.paymentDate)
@@ -652,7 +658,7 @@ export async function toggleTransactionSettlementAction(
if (!paymentAccount) {
return {
success: false,
error: "Conta de pagamento não encontrada.",
error: `Conta de ${isIncomeBill ? "recebimento" : "pagamento"} não encontrada.`,
};
}
}
@@ -682,8 +688,8 @@ export async function toggleTransactionSettlementAction(
return {
success: true,
message: data.value
? "Lançamento marcado como pago."
: "Pagamento desfeito com sucesso.",
? `Lançamento marcado como ${isIncomeBill ? "recebido" : "pago"}.`
: `${isIncomeBill ? "Recebimento" : "Pagamento"} desfeito com sucesso.`,
};
} catch (error) {
return handleActionError(error);

View File

@@ -63,6 +63,7 @@ export type PayerBoletoItem = {
dueDate: string | null;
boletoPaymentDate: string | null;
isSettled: boolean;
transactionType: string;
};
export type PayerPaymentStatusData = {
@@ -322,6 +323,7 @@ export async function fetchPayerBoletoItems({
dueDate: transactions.dueDate,
boletoPaymentDate: transactions.boletoPaymentDate,
isSettled: transactions.isSettled,
transactionType: transactions.transactionType,
})
.from(transactions)
.leftJoin(
@@ -350,6 +352,7 @@ export async function fetchPayerBoletoItems({
dueDate: toDateOnlyString(row.dueDate),
boletoPaymentDate: toDateOnlyString(row.boletoPaymentDate),
isSettled: Boolean(row.isSettled),
transactionType: row.transactionType,
});
}

View File

@@ -19,7 +19,7 @@ type FinancialDueDateInfo = {
date: string | null;
};
type RelativeFinancialDateContext = "due" | "paid";
type RelativeFinancialDateContext = "due" | "paid" | "received";
export function formatFinancialDateLabel(
value: string | null,
@@ -75,15 +75,17 @@ export function formatRelativeFinancialDateLabel(
return formatFinancialDateLabel(normalizedValue, "Vence em");
}
const settlementLabel = context === "received" ? "Recebido" : "Pago";
if (normalizedValue === referenceDate) {
return "Pago hoje";
return `${settlementLabel} hoje`;
}
if (normalizedValue === yesterday) {
return "Pago ontem";
return `${settlementLabel} ontem`;
}
return formatFinancialDateLabel(normalizedValue, "Pago em");
return formatFinancialDateLabel(normalizedValue, `${settlementLabel} em`);
}
export function buildFinancialStatusLabel({