feat(dashboard): confirmação de pagamento com conta e data para faturas e boletos

- widget de faturas abre modal com seleção de conta de origem e data antes de pagar
- widget de boletos ganha a mesma paridade: modal com conta de pagamento e data
- toggleTransactionSettlementAction aceita paymentAccountId e paymentDate opcionais
- DashboardBill expõe accountId para inicializar o modal com a conta já vinculada

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Felipe Coutinho
2026-05-02 22:08:16 +00:00
parent 4bea6330bf
commit 0f5c735be0
8 changed files with 441 additions and 105 deletions

View File

@@ -5,6 +5,13 @@ export type DashboardBill = {
dueDate: string | null; dueDate: string | null;
boletoPaymentDate: string | null; boletoPaymentDate: string | null;
isSettled: boolean; isSettled: boolean;
accountId: string | null;
};
export type BillPaymentAccountOption = {
value: string;
label: string;
logo: string | null;
}; };
export type DashboardBillsSnapshot = { export type DashboardBillsSnapshot = {

View File

@@ -1,5 +1,6 @@
"use client"; "use client";
import { useEffect, useRef, useState } from "react";
import { import {
type BillDialogState, type BillDialogState,
getCurrentBillDateString, getCurrentBillDateString,
@@ -20,12 +21,26 @@ type BillWidgetController = Omit<
> & { > & {
selectedBill: DashboardBill | null; selectedBill: DashboardBill | null;
modalState: BillDialogState; modalState: BillDialogState;
paymentAccountId: string;
setPaymentAccountId: (accountId: string) => void;
paymentDate: Date;
setPaymentDate: (date: Date) => void;
}; };
const toIsoDate = (date: Date) => date.toISOString().split("T")[0] ?? "";
export function useBillWidgetController( export function useBillWidgetController(
bills?: DashboardBill[], bills?: DashboardBill[],
): BillWidgetController { ): BillWidgetController {
const safeBills = bills ?? EMPTY_BILLS; const safeBills = bills ?? EMPTY_BILLS;
const [paymentAccountId, setPaymentAccountId] = useState<string>("");
const [paymentDate, setPaymentDate] = useState<Date>(() => new Date());
const paymentAccountIdRef = useRef(paymentAccountId);
const paymentDateRef = useRef(paymentDate);
paymentAccountIdRef.current = paymentAccountId;
paymentDateRef.current = paymentDate;
const controller = usePaymentDialogController({ const controller = usePaymentDialogController({
items: safeBills, items: safeBills,
getItemId: (bill) => bill.id, getItemId: (bill) => bill.id,
@@ -34,13 +49,36 @@ export function useBillWidgetController(
toggleTransactionSettlementAction({ toggleTransactionSettlementAction({
id: bill.id, id: bill.id,
value: true, value: true,
paymentAccountId: paymentAccountIdRef.current || null,
paymentDate: toIsoDate(paymentDateRef.current),
}), }),
applyConfirmedState: (bill) => applyConfirmedState: (bill) =>
markBillAsSettled(bill, getCurrentBillDateString()), markBillAsSettled(
{
...bill,
accountId: paymentAccountIdRef.current || bill.accountId,
},
toIsoDate(paymentDateRef.current) || getCurrentBillDateString(),
),
}); });
const selectedBillId = controller.selectedItem?.id ?? null;
const selectedBillAccountId = controller.selectedItem?.accountId ?? "";
useEffect(() => {
if (!selectedBillId) {
return;
}
setPaymentAccountId(selectedBillAccountId ?? "");
setPaymentDate(new Date());
}, [selectedBillId, selectedBillAccountId]);
return { return {
...controller, ...controller,
selectedBill: controller.selectedItem, selectedBill: controller.selectedItem,
paymentAccountId,
setPaymentAccountId,
paymentDate,
setPaymentDate,
}; };
} }

View File

@@ -1,5 +1,4 @@
import { import {
RiBarcodeFill,
RiCalendarLine, RiCalendarLine,
RiLoader4Line, RiLoader4Line,
RiMoneyDollarCircleLine, RiMoneyDollarCircleLine,
@@ -9,11 +8,18 @@ import {
formatBillDateLabel, formatBillDateLabel,
getBillStatusBadgeVariant, getBillStatusBadgeVariant,
} from "@/features/dashboard/bills/bills-helpers"; } from "@/features/dashboard/bills/bills-helpers";
import type { DashboardBill } from "@/features/dashboard/bills/bills-queries"; import type {
BillPaymentAccountOption,
DashboardBill,
} from "@/features/dashboard/bills/bills-queries";
import { AccountCardSelectContent } from "@/features/transactions/components/select-items";
import { EstablishmentLogo } from "@/shared/components/entity-avatar";
import MoneyValues from "@/shared/components/money-values"; import MoneyValues from "@/shared/components/money-values";
import { PaymentSuccess } from "@/shared/components/payment-success"; import { PaymentSuccess } from "@/shared/components/payment-success";
import { Badge } from "@/shared/components/ui/badge"; import { Badge } from "@/shared/components/ui/badge";
import { Button } from "@/shared/components/ui/button"; import { Button } from "@/shared/components/ui/button";
import { Card } from "@/shared/components/ui/card";
import { DatePicker } from "@/shared/components/ui/date-picker";
import { import {
Dialog, Dialog,
DialogContent, DialogContent,
@@ -22,12 +28,26 @@ import {
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
} from "@/shared/components/ui/dialog"; } from "@/shared/components/ui/dialog";
import { Label } from "@/shared/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/shared/components/ui/select";
import { Separator } from "@/shared/components/ui/separator";
type BillPaymentDialogProps = { type BillPaymentDialogProps = {
bill: DashboardBill | null; bill: DashboardBill | null;
open: boolean; open: boolean;
modalState: BillDialogState; modalState: BillDialogState;
isPending: boolean; isPending: boolean;
paymentAccountId: string;
onPaymentAccountChange: (accountId: string) => void;
paymentDate: Date;
onPaymentDateChange: (date: Date) => void;
paymentAccountOptions: BillPaymentAccountOption[];
onClose: () => void; onClose: () => void;
onConfirm: () => void; onConfirm: () => void;
}; };
@@ -37,6 +57,11 @@ export function BillPaymentDialog({
open, open,
modalState, modalState,
isPending, isPending,
paymentAccountId,
onPaymentAccountChange,
paymentDate,
onPaymentDateChange,
paymentAccountOptions,
onClose, onClose,
onConfirm, onConfirm,
}: BillPaymentDialogProps) { }: BillPaymentDialogProps) {
@@ -44,6 +69,14 @@ export function BillPaymentDialog({
const dueLabel = bill const dueLabel = bill
? formatBillDateLabel(bill.dueDate, "Vencimento:") ? formatBillDateLabel(bill.dueDate, "Vencimento:")
: null; : null;
const paidLabel = bill
? formatBillDateLabel(bill.boletoPaymentDate, "Pago em:")
: null;
const isBillPending = bill ? !bill.isSettled : false;
const paymentDateValue = paymentDate.toISOString().split("T")[0] ?? "";
const selectedAccount = paymentAccountOptions.find(
(option) => option.value === paymentAccountId,
);
return ( return (
<Dialog <Dialog
@@ -78,13 +111,12 @@ export function BillPaymentDialog({
<> <>
<DialogHeader> <DialogHeader>
<div className="mb-1 flex items-center gap-3"> <div className="mb-1 flex items-center gap-3">
<div className="flex size-10 items-center justify-center rounded-full bg-primary/10">
<RiBarcodeFill className="size-5 text-primary" />
</div>
<div> <div>
<DialogTitle>Confirmar pagamento</DialogTitle> <DialogTitle>Confirmar pagamento</DialogTitle>
<DialogDescription className="mt-0.5 text-xs"> <DialogDescription className="mt-1 text-xs">
Boleto {isBillPending
? "Escolha a conta de origem e a data em que o boleto foi pago."
: "Boleto"}
</DialogDescription> </DialogDescription>
</div> </div>
</div> </div>
@@ -92,62 +124,118 @@ export function BillPaymentDialog({
{bill ? ( {bill ? (
<div className="space-y-3"> <div className="space-y-3">
{/* Card principal */} <Card className="flex flex-row items-start gap-2 p-4">
<div className="rounded-xl border p-3"> <EstablishmentLogo
<p className="mb-1 text-xs font-medium text-muted-foreground uppercase tracking-wide"> name={bill.name}
size={36}
className="size-9 shrink-0"
/>
<div className="min-w-0">
<p className="text-xs font-medium text-muted-foreground uppercase">
Boleto Boleto
</p> </p>
<p className="text-base font-semibold text-foreground"> <p className="truncate text-base font-semibold text-foreground">
{bill.name} {bill.name}
</p> </p>
</div> </div>
</Card>
{/* Métricas */}
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div className="rounded-xl border p-3"> <Card className="p-3">
<div className="mb-1.5 flex items-center gap-1.5 text-muted-foreground"> <div className="flex items-center gap-1.5 text-muted-foreground">
<RiMoneyDollarCircleLine className="size-3.5" /> <RiMoneyDollarCircleLine className="size-3.5" />
<span className="text-xs font-medium uppercase tracking-wide"> <span className="text-xs font-medium uppercase">
Valor Valor
</span> </span>
</div> </div>
<MoneyValues <MoneyValues
amount={bill.amount} amount={bill.amount}
className="text-lg font-semibold" className="text-xl font-semibold"
/> />
</div> </Card>
<div className="rounded-xl border p-3"> <Card className="p-3">
<div className="mb-1.5 flex items-center gap-1.5 text-muted-foreground"> <div className="flex items-center gap-1.5 text-muted-foreground">
<RiCalendarLine className="size-3.5" /> <RiCalendarLine className="size-3.5" />
<span className="text-xs font-medium uppercase tracking-wide"> <span className="text-xs font-medium uppercase">
Vencimento {bill.isSettled ? "Pago em" : "Vencimento"}
</span> </span>
</div> </div>
<p className="text-sm font-medium text-foreground"> <p className="font-semibold">
{dueLabel?.replace("Vencimento: ", "") ?? "—"} {bill.isSettled
? (paidLabel?.replace("Pago em: ", "") ?? "—")
: (dueLabel?.replace("Vencimento: ", "") ?? "—")}
</p> </p>
</div> </Card>
</div> </div>
{/* Status */} <Separator />
{isBillPending ? (
<div className="space-y-3">
<div className="space-y-2">
<Label htmlFor="bill-widget-payment-account">
Conta de pagamento
</Label>
<Select
value={paymentAccountId}
onValueChange={onPaymentAccountChange}
disabled={
isProcessing || paymentAccountOptions.length === 0
}
>
<SelectTrigger
id="bill-widget-payment-account"
className="w-full"
>
<SelectValue placeholder="Selecione uma conta">
{selectedAccount ? (
<AccountCardSelectContent
label={selectedAccount.label}
logo={selectedAccount.logo}
/>
) : null}
</SelectValue>
</SelectTrigger>
<SelectContent>
{paymentAccountOptions.map((option) => (
<SelectItem key={option.value} value={option.value}>
<AccountCardSelectContent
label={option.label}
logo={option.logo}
/>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="bill-widget-payment-date">
Data do pagamento
</Label>
<DatePicker
id="bill-widget-payment-date"
value={paymentDateValue}
onChange={(value) => {
if (value) {
onPaymentDateChange(new Date(`${value}T00:00:00`));
}
}}
disabled={isProcessing}
/>
</div>
</div>
) : (
<div className="flex items-center justify-between rounded-xl border p-3"> <div className="flex items-center justify-between rounded-xl border p-3">
<span className="text-sm text-muted-foreground"> <span className="text-sm text-muted-foreground">
Status atual Status atual
</span> </span>
<Badge <Badge variant={getBillStatusBadgeVariant("Pago")}>
variant={getBillStatusBadgeVariant( Pago
bill.isSettled ? "Pago" : "Pendente",
)}
>
{bill.isSettled ? "Pago" : "Pendente"}
</Badge> </Badge>
</div> </div>
)}
{/* Aviso */}
<p className="px-1 text-xs text-muted-foreground">
Você poderá editar o lançamento depois, se necessário.
</p>
</div> </div>
) : null} ) : null}
@@ -163,7 +251,13 @@ export function BillPaymentDialog({
<Button <Button
type="button" type="button"
onClick={onConfirm} onClick={onConfirm}
disabled={isProcessing || !bill || bill.isSettled} disabled={
isProcessing ||
!bill ||
bill.isSettled ||
(isBillPending &&
(!paymentAccountId || paymentAccountOptions.length === 0))
}
> >
{isProcessing ? ( {isProcessing ? (
<> <>

View File

@@ -1,5 +1,4 @@
import { import {
RiBankCardLine,
RiCalendarLine, RiCalendarLine,
RiLoader4Line, RiLoader4Line,
RiMoneyDollarCircleLine, RiMoneyDollarCircleLine,
@@ -10,11 +9,17 @@ import {
type InvoiceDialogState, type InvoiceDialogState,
parseInvoiceDueDate, parseInvoiceDueDate,
} from "@/features/dashboard/invoices/invoices-helpers"; } from "@/features/dashboard/invoices/invoices-helpers";
import type { DashboardInvoice } from "@/features/dashboard/invoices/invoices-queries"; import type {
DashboardInvoice,
InvoicePaymentAccountOption,
} from "@/features/dashboard/invoices/invoices-queries";
import { AccountCardSelectContent } from "@/features/transactions/components/select-items";
import MoneyValues from "@/shared/components/money-values"; import MoneyValues from "@/shared/components/money-values";
import { PaymentSuccess } from "@/shared/components/payment-success"; import { PaymentSuccess } from "@/shared/components/payment-success";
import { Badge } from "@/shared/components/ui/badge"; import { Badge } from "@/shared/components/ui/badge";
import { Button } from "@/shared/components/ui/button"; import { Button } from "@/shared/components/ui/button";
import { Card } from "@/shared/components/ui/card";
import { DatePicker } from "@/shared/components/ui/date-picker";
import { import {
Dialog, Dialog,
DialogContent, DialogContent,
@@ -23,6 +28,15 @@ import {
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
} from "@/shared/components/ui/dialog"; } from "@/shared/components/ui/dialog";
import { Label } from "@/shared/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/shared/components/ui/select";
import { Separator } from "@/shared/components/ui/separator";
import { import {
INVOICE_PAYMENT_STATUS, INVOICE_PAYMENT_STATUS,
INVOICE_STATUS_LABEL, INVOICE_STATUS_LABEL,
@@ -34,6 +48,11 @@ type InvoicePaymentDialogProps = {
open: boolean; open: boolean;
modalState: InvoiceDialogState; modalState: InvoiceDialogState;
isPending: boolean; isPending: boolean;
paymentAccountId: string;
onPaymentAccountChange: (accountId: string) => void;
paymentDate: Date;
onPaymentDateChange: (date: Date) => void;
paymentAccountOptions: InvoicePaymentAccountOption[];
onClose: () => void; onClose: () => void;
onConfirm: () => void; onConfirm: () => void;
}; };
@@ -43,6 +62,11 @@ export function InvoicePaymentDialog({
open, open,
modalState, modalState,
isPending, isPending,
paymentAccountId,
onPaymentAccountChange,
paymentDate,
onPaymentDateChange,
paymentAccountOptions,
onClose, onClose,
onConfirm, onConfirm,
}: InvoicePaymentDialogProps) { }: InvoicePaymentDialogProps) {
@@ -51,6 +75,12 @@ export function InvoicePaymentDialog({
const dueInfo = invoice const dueInfo = invoice
? parseInvoiceDueDate(invoice.period, invoice.dueDay) ? parseInvoiceDueDate(invoice.period, invoice.dueDay)
: null; : null;
const isInvoicePending =
invoice?.paymentStatus === INVOICE_PAYMENT_STATUS.PENDING;
const paymentDateValue = paymentDate.toISOString().split("T")[0] ?? "";
const selectedAccount = paymentAccountOptions.find(
(option) => option.value === paymentAccountId,
);
return ( return (
<Dialog <Dialog
@@ -85,13 +115,12 @@ export function InvoicePaymentDialog({
<> <>
<DialogHeader> <DialogHeader>
<div className="mb-1 flex items-center gap-3"> <div className="mb-1 flex items-center gap-3">
<div className="flex size-10 items-center justify-center rounded-full bg-primary/10">
<RiBankCardLine className="size-5 text-primary" />
</div>
<div> <div>
<DialogTitle>Confirmar pagamento</DialogTitle> <DialogTitle>Confirmar pagamento</DialogTitle>
<DialogDescription className="mt-0.5 text-xs"> <DialogDescription className="mt-1 text-xs">
Fatura do cartão {isInvoicePending
? "Escolha a conta de origem e a data em que a fatura foi paga."
: "Fatura do cartão"}
</DialogDescription> </DialogDescription>
</div> </div>
</div> </div>
@@ -99,8 +128,7 @@ export function InvoicePaymentDialog({
{invoice ? ( {invoice ? (
<div className="space-y-3"> <div className="space-y-3">
{/* Card principal */} <Card className="flex flex-row items-start gap-2 p-4">
<div className="flex items-center gap-3 rounded-xl border p-4">
<InvoiceLogo <InvoiceLogo
cardName={invoice.cardName} cardName={invoice.cardName}
logo={invoice.logo} logo={invoice.logo}
@@ -110,48 +138,106 @@ export function InvoicePaymentDialog({
fallbackClassName="text-xs" fallbackClassName="text-xs"
/> />
<div className="min-w-0"> <div className="min-w-0">
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide"> <p className="text-xs font-medium text-muted-foreground uppercase">
Cartão Cartão
</p> </p>
<p className="truncate text-base font-semibold text-foreground"> <p className="truncate text-base font-semibold text-foreground">
{invoice.cardName} {invoice.cardName}
</p> </p>
</div> </div>
</div> </Card>
{/* Métricas */}
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div className="rounded-xl border p-3"> <Card className="p-3">
<div className="mb-1.5 flex items-center gap-1.5 text-muted-foreground"> <div className="flex items-center gap-1.5 text-muted-foreground">
<RiMoneyDollarCircleLine className="size-3.5" /> <RiMoneyDollarCircleLine className="size-3.5" />
<span className="text-xs font-medium uppercase tracking-wide"> <span className="text-xs font-medium uppercase">
Total da fatura Total da fatura
</span> </span>
</div> </div>
<MoneyValues <MoneyValues
amount={Math.abs(invoice.totalAmount)} amount={Math.abs(invoice.totalAmount)}
className="text-lg font-semibold" className="text-xl font-semibold"
/> />
</div> </Card>
<div className="rounded-xl border p-3"> <Card className="p-3">
<div className="mb-1.5 flex items-center gap-1.5 text-muted-foreground"> <div className="flex items-center gap-1.5 text-muted-foreground">
<RiCalendarLine className="size-3.5" /> <RiCalendarLine className="size-3.5" />
<span className="text-xs font-medium uppercase tracking-wide"> <span className="text-xs font-medium uppercase">
{invoice.paymentStatus === INVOICE_PAYMENT_STATUS.PAID {invoice.paymentStatus === INVOICE_PAYMENT_STATUS.PAID
? "Pago em" ? "Pago em"
: "Vencimento"} : "Vencimento"}
</span> </span>
</div> </div>
<p className="text-sm font-medium text-foreground"> <div className="font-semibold">
{invoice.paymentStatus === INVOICE_PAYMENT_STATUS.PAID {invoice.paymentStatus === INVOICE_PAYMENT_STATUS.PAID
? (paymentInfo?.label ?? "—") ? (paymentInfo?.label?.replace(/^Pago em\s*/u, "") ??
: (dueInfo?.label ?? "—")} "—")
</p> : (dueInfo?.label?.replace(/^Vence (em|dia)\s*/u, "") ??
"—")}
</div> </div>
</Card>
</div> </div>
{/* Status */} <Separator />
{isInvoicePending ? (
<div className="space-y-3">
<div className="space-y-2">
<Label htmlFor="invoice-widget-payment-account">
Conta de pagamento
</Label>
<Select
value={paymentAccountId}
onValueChange={onPaymentAccountChange}
disabled={
isProcessing || paymentAccountOptions.length === 0
}
>
<SelectTrigger
id="invoice-widget-payment-account"
className="w-full"
>
<SelectValue placeholder="Selecione uma conta">
{selectedAccount ? (
<AccountCardSelectContent
label={selectedAccount.label}
logo={selectedAccount.logo}
/>
) : null}
</SelectValue>
</SelectTrigger>
<SelectContent>
{paymentAccountOptions.map((option) => (
<SelectItem key={option.value} value={option.value}>
<AccountCardSelectContent
label={option.label}
logo={option.logo}
/>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="invoice-widget-payment-date">
Data do pagamento
</Label>
<DatePicker
id="invoice-widget-payment-date"
value={paymentDateValue}
onChange={(value) => {
if (value) {
onPaymentDateChange(new Date(`${value}T00:00:00`));
}
}}
disabled={isProcessing}
/>
</div>
</div>
) : (
<div className="flex items-center justify-between rounded-xl border p-3"> <div className="flex items-center justify-between rounded-xl border p-3">
<span className="text-sm text-muted-foreground"> <span className="text-sm text-muted-foreground">
Status atual Status atual
@@ -164,12 +250,7 @@ export function InvoicePaymentDialog({
{INVOICE_STATUS_LABEL[invoice.paymentStatus]} {INVOICE_STATUS_LABEL[invoice.paymentStatus]}
</Badge> </Badge>
</div> </div>
)}
{/* Aviso */}
<p className="px-1 text-xs text-muted-foreground">
Vamos registrar a fatura como paga. Você poderá editar depois
se necessário.
</p>
</div> </div>
) : null} ) : null}
@@ -185,7 +266,12 @@ export function InvoicePaymentDialog({
<Button <Button
type="button" type="button"
onClick={onConfirm} onClick={onConfirm}
disabled={isProcessing || !invoice} disabled={
isProcessing ||
!invoice ||
(isInvoicePending &&
(!paymentAccountId || paymentAccountOptions.length === 0))
}
> >
{isProcessing ? ( {isProcessing ? (
<> <>

View File

@@ -1,5 +1,8 @@
import type { InvoiceDialogState } from "@/features/dashboard/invoices/invoices-helpers"; import type { InvoiceDialogState } from "@/features/dashboard/invoices/invoices-helpers";
import type { DashboardInvoice } from "@/features/dashboard/invoices/invoices-queries"; import type {
DashboardInvoice,
InvoicePaymentAccountOption,
} from "@/features/dashboard/invoices/invoices-queries";
import { InvoicePaymentDialog } from "./invoice-payment-dialog"; import { InvoicePaymentDialog } from "./invoice-payment-dialog";
import { InvoicesList } from "./invoices-list"; import { InvoicesList } from "./invoices-list";
@@ -9,6 +12,11 @@ type InvoicesWidgetViewProps = {
isModalOpen: boolean; isModalOpen: boolean;
modalState: InvoiceDialogState; modalState: InvoiceDialogState;
isPending: boolean; isPending: boolean;
paymentAccountId: string;
onPaymentAccountChange: (accountId: string) => void;
paymentDate: Date;
onPaymentDateChange: (date: Date) => void;
paymentAccountOptions: InvoicePaymentAccountOption[];
onOpenPaymentDialog: (invoiceId: string) => void; onOpenPaymentDialog: (invoiceId: string) => void;
onClosePaymentDialog: () => void; onClosePaymentDialog: () => void;
onConfirmPayment: () => void; onConfirmPayment: () => void;
@@ -20,6 +28,11 @@ export function InvoicesWidgetView({
isModalOpen, isModalOpen,
modalState, modalState,
isPending, isPending,
paymentAccountId,
onPaymentAccountChange,
paymentDate,
onPaymentDateChange,
paymentAccountOptions,
onOpenPaymentDialog, onOpenPaymentDialog,
onClosePaymentDialog, onClosePaymentDialog,
onConfirmPayment, onConfirmPayment,
@@ -35,6 +48,11 @@ export function InvoicesWidgetView({
open={isModalOpen} open={isModalOpen}
modalState={modalState} modalState={modalState}
isPending={isPending} isPending={isPending}
paymentAccountId={paymentAccountId}
onPaymentAccountChange={onPaymentAccountChange}
paymentDate={paymentDate}
onPaymentDateChange={onPaymentDateChange}
paymentAccountOptions={paymentAccountOptions}
onClose={onClosePaymentDialog} onClose={onClosePaymentDialog}
onConfirm={onConfirmPayment} onConfirm={onConfirmPayment}
/> />

View File

@@ -1,20 +1,31 @@
"use client"; "use client";
import type { DashboardInvoice } from "@/features/dashboard/invoices/invoices-queries"; import type {
DashboardInvoice,
InvoicePaymentAccountOption,
} from "@/features/dashboard/invoices/invoices-queries";
import { useInvoicesWidgetController } from "@/features/dashboard/invoices/use-invoices-widget-controller"; import { useInvoicesWidgetController } from "@/features/dashboard/invoices/use-invoices-widget-controller";
import { InvoicesWidgetView } from "../invoices/invoices-widget-view"; import { InvoicesWidgetView } from "../invoices/invoices-widget-view";
type InvoicesWidgetProps = { type InvoicesWidgetProps = {
invoices: DashboardInvoice[]; invoices: DashboardInvoice[];
paymentAccountOptions: InvoicePaymentAccountOption[];
}; };
export function InvoicesWidget({ invoices }: InvoicesWidgetProps) { export function InvoicesWidget({
invoices,
paymentAccountOptions,
}: InvoicesWidgetProps) {
const { const {
items, items,
selectedInvoice, selectedInvoice,
isModalOpen, isModalOpen,
modalState, modalState,
isPending, isPending,
paymentAccountId,
setPaymentAccountId,
paymentDate,
setPaymentDate,
openPaymentDialog, openPaymentDialog,
closePaymentDialog, closePaymentDialog,
confirmPayment, confirmPayment,
@@ -27,6 +38,11 @@ export function InvoicesWidget({ invoices }: InvoicesWidgetProps) {
isModalOpen={isModalOpen} isModalOpen={isModalOpen}
modalState={modalState} modalState={modalState}
isPending={isPending} isPending={isPending}
paymentAccountId={paymentAccountId}
onPaymentAccountChange={setPaymentAccountId}
paymentDate={paymentDate}
onPaymentDateChange={setPaymentDate}
paymentAccountOptions={paymentAccountOptions}
onOpenPaymentDialog={openPaymentDialog} onOpenPaymentDialog={openPaymentDialog}
onClosePaymentDialog={closePaymentDialog} onClosePaymentDialog={closePaymentDialog}
onConfirmPayment={confirmPayment} onConfirmPayment={confirmPayment}

View File

@@ -1,5 +1,11 @@
import { and, eq, ilike, inArray, isNotNull, sql } from "drizzle-orm"; import { and, eq, ilike, inArray, isNotNull, sql } from "drizzle-orm";
import { cards, invoices, payers, transactions } from "@/db/schema"; import {
cards,
financialAccounts,
invoices,
payers,
transactions,
} from "@/db/schema";
import { ACCOUNT_AUTO_INVOICE_NOTE_PREFIX } from "@/shared/lib/accounts/constants"; import { ACCOUNT_AUTO_INVOICE_NOTE_PREFIX } from "@/shared/lib/accounts/constants";
import { db } from "@/shared/lib/db"; import { db } from "@/shared/lib/db";
import { import {
@@ -31,6 +37,13 @@ type RawDashboardInvoice = {
totalAmount: string | number | null; totalAmount: string | number | null;
transactionCount: string | number | null; transactionCount: string | number | null;
invoiceCreatedAt: Date | null; invoiceCreatedAt: Date | null;
cardAccountId: string | null;
};
export type InvoicePaymentAccountOption = {
value: string;
label: string;
logo: string | null;
}; };
type RawInvoiceBreakdownRow = { type RawInvoiceBreakdownRow = {
@@ -63,11 +76,13 @@ export type DashboardInvoice = {
totalAmount: number; totalAmount: number;
paidAt: string | null; paidAt: string | null;
pagadorBreakdown: InvoicePagadorBreakdown[]; pagadorBreakdown: InvoicePagadorBreakdown[];
defaultPaymentAccountId: string | null;
}; };
type DashboardInvoicesSnapshot = { type DashboardInvoicesSnapshot = {
invoices: DashboardInvoice[]; invoices: DashboardInvoice[];
totalPending: number; totalPending: number;
paymentAccountOptions: InvoicePaymentAccountOption[];
}; };
const isInvoiceStatus = (value: unknown): value is InvoicePaymentStatus => const isInvoiceStatus = (value: unknown): value is InvoicePaymentStatus =>
@@ -148,7 +163,7 @@ export async function fetchDashboardInvoices(
} }
} }
const [rows, breakdownRows] = (await Promise.all([ const [rows, breakdownRows, accountRows] = (await Promise.all([
db db
.select({ .select({
invoiceId: invoices.id, invoiceId: invoices.id,
@@ -159,6 +174,7 @@ export async function fetchDashboardInvoices(
period: invoices.period, period: invoices.period,
paymentStatus: invoices.paymentStatus, paymentStatus: invoices.paymentStatus,
invoiceCreatedAt: invoices.createdAt, invoiceCreatedAt: invoices.createdAt,
cardAccountId: cards.accountId,
totalAmount: sql<number | null>` totalAmount: sql<number | null>`
COALESCE(SUM(${transactions.amount}), 0) COALESCE(SUM(${transactions.amount}), 0)
`, `,
@@ -190,6 +206,7 @@ export async function fetchDashboardInvoices(
cards.status, cards.status,
cards.logo, cards.logo,
cards.dueDay, cards.dueDay,
cards.accountId,
invoices.period, invoices.period,
invoices.paymentStatus, invoices.paymentStatus,
), ),
@@ -218,7 +235,29 @@ export async function fetchDashboardInvoices(
payers.name, payers.name,
payers.avatarUrl, payers.avatarUrl,
), ),
])) as [RawDashboardInvoice[], RawInvoiceBreakdownRow[]]; db
.select({
id: financialAccounts.id,
name: financialAccounts.name,
logo: financialAccounts.logo,
})
.from(financialAccounts)
.where(eq(financialAccounts.userId, userId)),
])) as [
RawDashboardInvoice[],
RawInvoiceBreakdownRow[],
{ id: string; name: string; logo: string | null }[],
];
const paymentAccountOptions: InvoicePaymentAccountOption[] = accountRows
.map((account) => ({
value: account.id,
label: account.name,
logo: account.logo,
}))
.sort((a, b) =>
a.label.localeCompare(b.label, "pt-BR", { sensitivity: "base" }),
);
const groupedBreakdown = new Map< const groupedBreakdown = new Map<
string, string,
@@ -336,6 +375,7 @@ export async function fetchDashboardInvoices(
pagadorBreakdown: ( pagadorBreakdown: (
breakdownMap.get(`${row.cardId}:${resolvedPeriod}`) ?? [] breakdownMap.get(`${row.cardId}:${resolvedPeriod}`) ?? []
).sort((a, b) => b.amount - a.amount), ).sort((a, b) => b.amount - a.amount),
defaultPaymentAccountId: row.cardAccountId ?? null,
}); });
} }
@@ -399,5 +439,6 @@ export async function fetchDashboardInvoices(
return { return {
invoices: invoiceList, invoices: invoiceList,
totalPending, totalPending,
paymentAccountOptions,
}; };
} }

View File

@@ -1,5 +1,6 @@
"use client"; "use client";
import { useEffect, useRef, useState } from "react";
import { import {
getCurrentDateString, getCurrentDateString,
type InvoiceDialogState, type InvoiceDialogState,
@@ -20,27 +21,62 @@ type InvoicesWidgetController = Omit<
> & { > & {
selectedInvoice: DashboardInvoice | null; selectedInvoice: DashboardInvoice | null;
modalState: InvoiceDialogState; modalState: InvoiceDialogState;
paymentAccountId: string;
setPaymentAccountId: (accountId: string) => void;
paymentDate: Date;
setPaymentDate: (date: Date) => void;
}; };
export function useInvoicesWidgetController( export function useInvoicesWidgetController(
invoices: DashboardInvoice[], invoices: DashboardInvoice[],
): InvoicesWidgetController { ): InvoicesWidgetController {
const [paymentAccountId, setPaymentAccountId] = useState<string>("");
const [paymentDate, setPaymentDate] = useState<Date>(() => new Date());
const paymentAccountIdRef = useRef(paymentAccountId);
const paymentDateRef = useRef(paymentDate);
paymentAccountIdRef.current = paymentAccountId;
paymentDateRef.current = paymentDate;
const controller = usePaymentDialogController({ const controller = usePaymentDialogController({
items: invoices, items: invoices,
getItemId: (invoice) => invoice.id, getItemId: (invoice) => invoice.id,
isItemConfirmed: (invoice) => isInvoicePaid(invoice.paymentStatus), isItemConfirmed: (invoice) => isInvoicePaid(invoice.paymentStatus),
executeConfirm: (invoice) => executeConfirm: (invoice) => {
updateInvoicePaymentStatusAction({ const accountId = paymentAccountIdRef.current || undefined;
const date = paymentDateRef.current;
const isoDate = date.toISOString().split("T")[0];
return updateInvoicePaymentStatusAction({
cardId: invoice.cardId, cardId: invoice.cardId,
period: invoice.period, period: invoice.period,
status: INVOICE_PAYMENT_STATUS.PAID, status: INVOICE_PAYMENT_STATUS.PAID,
}), paymentAccountId: accountId,
paymentDate: isoDate,
});
},
applyConfirmedState: (invoice) => applyConfirmedState: (invoice) =>
markInvoiceAsPaid(invoice, getCurrentDateString()), markInvoiceAsPaid(invoice, getCurrentDateString()),
}); });
const selectedInvoiceId = controller.selectedItem?.id ?? null;
const selectedDefaultAccountId =
controller.selectedItem?.defaultPaymentAccountId ?? "";
useEffect(() => {
if (!selectedInvoiceId) {
return;
}
setPaymentAccountId(selectedDefaultAccountId);
setPaymentDate(new Date());
}, [selectedInvoiceId, selectedDefaultAccountId]);
return { return {
...controller, ...controller,
selectedInvoice: controller.selectedItem, selectedInvoice: controller.selectedItem,
paymentAccountId,
setPaymentAccountId,
paymentDate,
setPaymentDate,
}; };
} }