refactor: migrate from ESLint to Biome and extract SQL queries to data.ts

- Replace ESLint with Biome for linting and formatting
- Configure Biome with tabs, double quotes, and organized imports
- Move all SQL/Drizzle queries from page.tsx files to data.ts files
- Create new data.ts files for: ajustes, dashboard, relatorios/categorias
- Update existing data.ts files: extrato, fatura (add lancamentos queries)
- Remove all drizzle-orm imports from page.tsx files
- Update README.md with new tooling info

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Felipe Coutinho
2026-01-27 13:15:37 +00:00
parent 8ffe61c59b
commit a7f63fb77a
442 changed files with 66141 additions and 69292 deletions

View File

@@ -1,424 +1,424 @@
"use client";
import { RiLoader4Line } from "@remixicon/react";
import {
createInstallmentAnticipationAction,
getEligibleInstallmentsAction,
useCallback,
useEffect,
useMemo,
useState,
useTransition,
} from "react";
import { toast } from "sonner";
import {
createInstallmentAnticipationAction,
getEligibleInstallmentsAction,
} from "@/app/(dashboard)/lancamentos/anticipation-actions";
import { CategoryIcon } from "@/components/categorias/category-icon";
import { InstallmentSelectionTable } from "./installment-selection-table";
import MoneyValues from "@/components/money-values";
import { PeriodPicker } from "@/components/period-picker";
import { Button } from "@/components/ui/button";
import { CurrencyInput } from "@/components/ui/currency-input";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import {
Field,
FieldContent,
FieldGroup,
FieldLabel,
FieldLegend,
Field,
FieldContent,
FieldGroup,
FieldLabel,
FieldLegend,
} from "@/components/ui/field";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { PeriodPicker } from "@/components/period-picker";
import { useControlledState } from "@/hooks/use-controlled-state";
import { useFormState } from "@/hooks/use-form-state";
import type { EligibleInstallment } from "@/lib/installments/anticipation-types";
import { RiLoader4Line } from "@remixicon/react";
import {
useCallback,
useEffect,
useMemo,
useState,
useTransition,
} from "react";
import { toast } from "sonner";
import MoneyValues from "@/components/money-values";
import { InstallmentSelectionTable } from "./installment-selection-table";
interface AnticipateInstallmentsDialogProps {
trigger?: React.ReactNode;
seriesId: string;
lancamentoName: string;
categorias: Array<{ id: string; name: string; icon: string | null }>;
pagadores: Array<{ id: string; name: string }>;
defaultPeriod: string;
open?: boolean;
onOpenChange?: (open: boolean) => void;
trigger?: React.ReactNode;
seriesId: string;
lancamentoName: string;
categorias: Array<{ id: string; name: string; icon: string | null }>;
pagadores: Array<{ id: string; name: string }>;
defaultPeriod: string;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}
type AnticipationFormValues = {
anticipationPeriod: string;
discount: number;
pagadorId: string;
categoriaId: string;
note: string;
anticipationPeriod: string;
discount: number;
pagadorId: string;
categoriaId: string;
note: string;
};
export function AnticipateInstallmentsDialog({
trigger,
seriesId,
lancamentoName,
categorias,
pagadores,
defaultPeriod,
open,
onOpenChange,
trigger,
seriesId,
lancamentoName,
categorias,
pagadores,
defaultPeriod,
open,
onOpenChange,
}: AnticipateInstallmentsDialogProps) {
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [isPending, startTransition] = useTransition();
const [isLoadingInstallments, setIsLoadingInstallments] = useState(false);
const [eligibleInstallments, setEligibleInstallments] = useState<
EligibleInstallment[]
>([]);
const [selectedIds, setSelectedIds] = useState<string[]>([]);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [isPending, startTransition] = useTransition();
const [isLoadingInstallments, setIsLoadingInstallments] = useState(false);
const [eligibleInstallments, setEligibleInstallments] = useState<
EligibleInstallment[]
>([]);
const [selectedIds, setSelectedIds] = useState<string[]>([]);
// Use controlled state hook for dialog open state
const [dialogOpen, setDialogOpen] = useControlledState(
open,
false,
onOpenChange
);
// Use controlled state hook for dialog open state
const [dialogOpen, setDialogOpen] = useControlledState(
open,
false,
onOpenChange,
);
// Use form state hook for form management
const { formState, updateField, setFormState } =
useFormState<AnticipationFormValues>({
anticipationPeriod: defaultPeriod,
discount: 0,
pagadorId: "",
categoriaId: "",
note: "",
});
// Use form state hook for form management
const { formState, updateField, setFormState } =
useFormState<AnticipationFormValues>({
anticipationPeriod: defaultPeriod,
discount: 0,
pagadorId: "",
categoriaId: "",
note: "",
});
// Buscar parcelas elegíveis ao abrir o dialog
useEffect(() => {
if (dialogOpen) {
setIsLoadingInstallments(true);
setSelectedIds([]);
setErrorMessage(null);
// Buscar parcelas elegíveis ao abrir o dialog
useEffect(() => {
if (dialogOpen) {
setIsLoadingInstallments(true);
setSelectedIds([]);
setErrorMessage(null);
getEligibleInstallmentsAction(seriesId)
.then((result) => {
if (result.success && result.data) {
setEligibleInstallments(result.data);
getEligibleInstallmentsAction(seriesId)
.then((result) => {
if (result.success && result.data) {
setEligibleInstallments(result.data);
// Pré-preencher pagador e categoria da primeira parcela
if (result.data.length > 0) {
const first = result.data[0];
setFormState({
anticipationPeriod: defaultPeriod,
discount: 0,
pagadorId: first.pagadorId ?? "",
categoriaId: first.categoriaId ?? "",
note: "",
});
}
} else {
toast.error(result.error || "Erro ao carregar parcelas");
setEligibleInstallments([]);
}
})
.catch((error) => {
console.error("Erro ao buscar parcelas:", error);
toast.error("Erro ao carregar parcelas elegíveis");
setEligibleInstallments([]);
})
.finally(() => {
setIsLoadingInstallments(false);
});
}
}, [dialogOpen, seriesId, defaultPeriod, setFormState]);
// Pré-preencher pagador e categoria da primeira parcela
if (result.data.length > 0) {
const first = result.data[0];
setFormState({
anticipationPeriod: defaultPeriod,
discount: 0,
pagadorId: first.pagadorId ?? "",
categoriaId: first.categoriaId ?? "",
note: "",
});
}
} else {
toast.error(result.error || "Erro ao carregar parcelas");
setEligibleInstallments([]);
}
})
.catch((error) => {
console.error("Erro ao buscar parcelas:", error);
toast.error("Erro ao carregar parcelas elegíveis");
setEligibleInstallments([]);
})
.finally(() => {
setIsLoadingInstallments(false);
});
}
}, [dialogOpen, seriesId, defaultPeriod, setFormState]);
const totalAmount = useMemo(() => {
return eligibleInstallments
.filter((inst) => selectedIds.includes(inst.id))
.reduce((sum, inst) => sum + Number(inst.amount), 0);
}, [eligibleInstallments, selectedIds]);
const totalAmount = useMemo(() => {
return eligibleInstallments
.filter((inst) => selectedIds.includes(inst.id))
.reduce((sum, inst) => sum + Number(inst.amount), 0);
}, [eligibleInstallments, selectedIds]);
const finalAmount = useMemo(() => {
// Se for despesa (negativo), soma o desconto para reduzir
// Se for receita (positivo), subtrai o desconto
const discount = Number(formState.discount) || 0;
return totalAmount < 0 ? totalAmount + discount : totalAmount - discount;
}, [totalAmount, formState.discount]);
const finalAmount = useMemo(() => {
// Se for despesa (negativo), soma o desconto para reduzir
// Se for receita (positivo), subtrai o desconto
const discount = Number(formState.discount) || 0;
return totalAmount < 0 ? totalAmount + discount : totalAmount - discount;
}, [totalAmount, formState.discount]);
const handleSubmit = useCallback(
(event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setErrorMessage(null);
const handleSubmit = useCallback(
(event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setErrorMessage(null);
if (selectedIds.length === 0) {
const message = "Selecione pelo menos uma parcela para antecipar.";
setErrorMessage(message);
toast.error(message);
return;
}
if (selectedIds.length === 0) {
const message = "Selecione pelo menos uma parcela para antecipar.";
setErrorMessage(message);
toast.error(message);
return;
}
if (formState.anticipationPeriod.length === 0) {
const message = "Informe o período da antecipação.";
setErrorMessage(message);
toast.error(message);
return;
}
if (formState.anticipationPeriod.length === 0) {
const message = "Informe o período da antecipação.";
setErrorMessage(message);
toast.error(message);
return;
}
const discount = Number(formState.discount) || 0;
if (discount > Math.abs(totalAmount)) {
const message =
"O desconto não pode ser maior que o valor total das parcelas.";
setErrorMessage(message);
toast.error(message);
return;
}
const discount = Number(formState.discount) || 0;
if (discount > Math.abs(totalAmount)) {
const message =
"O desconto não pode ser maior que o valor total das parcelas.";
setErrorMessage(message);
toast.error(message);
return;
}
startTransition(async () => {
const result = await createInstallmentAnticipationAction({
seriesId,
installmentIds: selectedIds,
anticipationPeriod: formState.anticipationPeriod,
discount: Number(formState.discount) || 0,
pagadorId: formState.pagadorId || undefined,
categoriaId: formState.categoriaId || undefined,
note: formState.note || undefined,
});
startTransition(async () => {
const result = await createInstallmentAnticipationAction({
seriesId,
installmentIds: selectedIds,
anticipationPeriod: formState.anticipationPeriod,
discount: Number(formState.discount) || 0,
pagadorId: formState.pagadorId || undefined,
categoriaId: formState.categoriaId || undefined,
note: formState.note || undefined,
});
if (result.success) {
toast.success(result.message);
setDialogOpen(false);
} else {
const errorMsg = result.error || "Erro ao criar antecipação";
setErrorMessage(errorMsg);
toast.error(errorMsg);
}
});
},
[selectedIds, formState, seriesId, setDialogOpen]
);
if (result.success) {
toast.success(result.message);
setDialogOpen(false);
} else {
const errorMsg = result.error || "Erro ao criar antecipação";
setErrorMessage(errorMsg);
toast.error(errorMsg);
}
});
},
[selectedIds, formState, seriesId, setDialogOpen, totalAmount],
);
const handleCancel = useCallback(() => {
setDialogOpen(false);
}, [setDialogOpen]);
const handleCancel = useCallback(() => {
setDialogOpen(false);
}, [setDialogOpen]);
return (
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
{trigger && <DialogTrigger asChild>{trigger}</DialogTrigger>}
<DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto px-6 py-5 sm:px-8 sm:py-6">
<DialogHeader>
<DialogTitle>Antecipar Parcelas</DialogTitle>
<DialogDescription>{lancamentoName}</DialogDescription>
</DialogHeader>
return (
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
{trigger && <DialogTrigger asChild>{trigger}</DialogTrigger>}
<DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto px-6 py-5 sm:px-8 sm:py-6">
<DialogHeader>
<DialogTitle>Antecipar Parcelas</DialogTitle>
<DialogDescription>{lancamentoName}</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
{/* Seção 1: Seleção de Parcelas */}
<FieldGroup className="gap-1">
<FieldLegend>Parcelas Disponíveis</FieldLegend>
<form onSubmit={handleSubmit} className="space-y-4">
{/* Seção 1: Seleção de Parcelas */}
<FieldGroup className="gap-1">
<FieldLegend>Parcelas Disponíveis</FieldLegend>
{isLoadingInstallments ? (
<div className="flex items-center justify-center rounded-lg border border-dashed p-8">
<RiLoader4Line className="size-6 animate-spin text-muted-foreground" />
<span className="ml-2 text-sm text-muted-foreground">
Carregando parcelas...
</span>
</div>
) : (
<div className="max-h-[280px] overflow-y-auto rounded-lg border">
<InstallmentSelectionTable
installments={eligibleInstallments}
selectedIds={selectedIds}
onSelectionChange={setSelectedIds}
/>
</div>
)}
</FieldGroup>
{isLoadingInstallments ? (
<div className="flex items-center justify-center rounded-lg border border-dashed p-8">
<RiLoader4Line className="size-6 animate-spin text-muted-foreground" />
<span className="ml-2 text-sm text-muted-foreground">
Carregando parcelas...
</span>
</div>
) : (
<div className="max-h-[280px] overflow-y-auto rounded-lg border">
<InstallmentSelectionTable
installments={eligibleInstallments}
selectedIds={selectedIds}
onSelectionChange={setSelectedIds}
/>
</div>
)}
</FieldGroup>
{/* Seção 2: Configuração da Antecipação */}
<FieldGroup className="gap-1">
<FieldLegend>Configuração</FieldLegend>
{/* Seção 2: Configuração da Antecipação */}
<FieldGroup className="gap-1">
<FieldLegend>Configuração</FieldLegend>
<div className="grid gap-2 sm:grid-cols-2">
<Field className="gap-1">
<FieldLabel htmlFor="anticipation-period">Período</FieldLabel>
<FieldContent>
<PeriodPicker
value={formState.anticipationPeriod}
onChange={(value) =>
updateField("anticipationPeriod", value)
}
disabled={isPending}
className="w-full"
/>
</FieldContent>
</Field>
<div className="grid gap-2 sm:grid-cols-2">
<Field className="gap-1">
<FieldLabel htmlFor="anticipation-period">Período</FieldLabel>
<FieldContent>
<PeriodPicker
value={formState.anticipationPeriod}
onChange={(value) =>
updateField("anticipationPeriod", value)
}
disabled={isPending}
className="w-full"
/>
</FieldContent>
</Field>
<Field className="gap-1">
<FieldLabel htmlFor="anticipation-discount">
Desconto
</FieldLabel>
<FieldContent>
<CurrencyInput
id="anticipation-discount"
value={formState.discount}
onValueChange={(value) =>
updateField("discount", value ?? 0)
}
placeholder="R$ 0,00"
disabled={isPending}
/>
</FieldContent>
</Field>
<Field className="gap-1">
<FieldLabel htmlFor="anticipation-discount">
Desconto
</FieldLabel>
<FieldContent>
<CurrencyInput
id="anticipation-discount"
value={formState.discount}
onValueChange={(value) =>
updateField("discount", value ?? 0)
}
placeholder="R$ 0,00"
disabled={isPending}
/>
</FieldContent>
</Field>
<Field className="gap-1">
<FieldLabel htmlFor="anticipation-pagador">Pagador</FieldLabel>
<FieldContent>
<Select
value={formState.pagadorId}
onValueChange={(value) => updateField("pagadorId", value)}
disabled={isPending}
>
<SelectTrigger id="anticipation-pagador" className="w-full">
<SelectValue placeholder="Padrão" />
</SelectTrigger>
<SelectContent>
{pagadores.map((pagador) => (
<SelectItem key={pagador.id} value={pagador.id}>
{pagador.name}
</SelectItem>
))}
</SelectContent>
</Select>
</FieldContent>
</Field>
<Field className="gap-1">
<FieldLabel htmlFor="anticipation-pagador">Pagador</FieldLabel>
<FieldContent>
<Select
value={formState.pagadorId}
onValueChange={(value) => updateField("pagadorId", value)}
disabled={isPending}
>
<SelectTrigger id="anticipation-pagador" className="w-full">
<SelectValue placeholder="Padrão" />
</SelectTrigger>
<SelectContent>
{pagadores.map((pagador) => (
<SelectItem key={pagador.id} value={pagador.id}>
{pagador.name}
</SelectItem>
))}
</SelectContent>
</Select>
</FieldContent>
</Field>
<Field className="gap-1">
<FieldLabel htmlFor="anticipation-categoria">
Categoria
</FieldLabel>
<FieldContent>
<Select
value={formState.categoriaId}
onValueChange={(value) => updateField("categoriaId", value)}
disabled={isPending}
>
<SelectTrigger
id="anticipation-categoria"
className="w-full"
>
<SelectValue placeholder="Padrão" />
</SelectTrigger>
<SelectContent>
{categorias.map((categoria) => (
<SelectItem key={categoria.id} value={categoria.id}>
<div className="flex items-center gap-2">
<CategoryIcon
name={categoria.icon ?? undefined}
className="size-4"
/>
<span>{categoria.name}</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</FieldContent>
</Field>
<Field className="gap-1">
<FieldLabel htmlFor="anticipation-categoria">
Categoria
</FieldLabel>
<FieldContent>
<Select
value={formState.categoriaId}
onValueChange={(value) => updateField("categoriaId", value)}
disabled={isPending}
>
<SelectTrigger
id="anticipation-categoria"
className="w-full"
>
<SelectValue placeholder="Padrão" />
</SelectTrigger>
<SelectContent>
{categorias.map((categoria) => (
<SelectItem key={categoria.id} value={categoria.id}>
<div className="flex items-center gap-2">
<CategoryIcon
name={categoria.icon ?? undefined}
className="size-4"
/>
<span>{categoria.name}</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</FieldContent>
</Field>
<Field className="sm:col-span-2">
<FieldLabel htmlFor="anticipation-note">Observação</FieldLabel>
<FieldContent>
<Textarea
id="anticipation-note"
value={formState.note}
onChange={(e) => updateField("note", e.target.value)}
placeholder="Observação (opcional)"
rows={2}
disabled={isPending}
/>
</FieldContent>
</Field>
</div>
</FieldGroup>
<Field className="sm:col-span-2">
<FieldLabel htmlFor="anticipation-note">Observação</FieldLabel>
<FieldContent>
<Textarea
id="anticipation-note"
value={formState.note}
onChange={(e) => updateField("note", e.target.value)}
placeholder="Observação (opcional)"
rows={2}
disabled={isPending}
/>
</FieldContent>
</Field>
</div>
</FieldGroup>
{/* Seção 3: Resumo */}
{selectedIds.length > 0 && (
<div className="rounded-lg border bg-muted/20 p-3">
<h4 className="text-sm font-semibold mb-2">Resumo</h4>
<dl className="space-y-1.5 text-sm">
<div className="flex items-center justify-between">
<dt className="text-muted-foreground">
{selectedIds.length} parcela
{selectedIds.length > 1 ? "s" : ""}
</dt>
<dd className="font-medium tabular-nums">
<MoneyValues amount={totalAmount} className="text-sm" />
</dd>
</div>
{Number(formState.discount) > 0 && (
<div className="flex items-center justify-between">
<dt className="text-muted-foreground">Desconto</dt>
<dd className="font-medium tabular-nums text-green-600">
-{" "}
<MoneyValues
amount={Number(formState.discount)}
className="text-sm"
/>
</dd>
</div>
)}
<div className="flex items-center justify-between border-t pt-1.5">
<dt className="font-medium">Total</dt>
<dd className="text-base font-semibold tabular-nums text-primary">
<MoneyValues amount={finalAmount} className="text-sm" />
</dd>
</div>
</dl>
</div>
)}
{/* Seção 3: Resumo */}
{selectedIds.length > 0 && (
<div className="rounded-lg border bg-muted/20 p-3">
<h4 className="text-sm font-semibold mb-2">Resumo</h4>
<dl className="space-y-1.5 text-sm">
<div className="flex items-center justify-between">
<dt className="text-muted-foreground">
{selectedIds.length} parcela
{selectedIds.length > 1 ? "s" : ""}
</dt>
<dd className="font-medium tabular-nums">
<MoneyValues amount={totalAmount} className="text-sm" />
</dd>
</div>
{Number(formState.discount) > 0 && (
<div className="flex items-center justify-between">
<dt className="text-muted-foreground">Desconto</dt>
<dd className="font-medium tabular-nums text-green-600">
-{" "}
<MoneyValues
amount={Number(formState.discount)}
className="text-sm"
/>
</dd>
</div>
)}
<div className="flex items-center justify-between border-t pt-1.5">
<dt className="font-medium">Total</dt>
<dd className="text-base font-semibold tabular-nums text-primary">
<MoneyValues amount={finalAmount} className="text-sm" />
</dd>
</div>
</dl>
</div>
)}
{/* Mensagem de erro */}
{errorMessage && (
<div
className="rounded-lg border border-destructive/50 bg-destructive/10 p-3 text-sm text-destructive"
role="alert"
>
{errorMessage}
</div>
)}
{/* Mensagem de erro */}
{errorMessage && (
<div
className="rounded-lg border border-destructive/50 bg-destructive/10 p-3 text-sm text-destructive"
role="alert"
>
{errorMessage}
</div>
)}
<DialogFooter className="gap-3">
<Button
type="button"
variant="outline"
onClick={handleCancel}
disabled={isPending}
>
Cancelar
</Button>
<Button
type="submit"
disabled={isPending || selectedIds.length === 0}
>
{isPending ? (
<>
<RiLoader4Line className="mr-2 size-4 animate-spin" />
Antecipando...
</>
) : (
"Confirmar Antecipação"
)}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
<DialogFooter className="gap-3">
<Button
type="button"
variant="outline"
onClick={handleCancel}
disabled={isPending}
>
Cancelar
</Button>
<Button
type="submit"
disabled={isPending || selectedIds.length === 0}
>
{isPending ? (
<>
<RiLoader4Line className="mr-2 size-4 animate-spin" />
Antecipando...
</>
) : (
"Confirmar Antecipação"
)}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}

View File

@@ -1,135 +1,143 @@
"use client";
import { getInstallmentAnticipationsAction } from "@/app/(dashboard)/lancamentos/anticipation-actions";
import { AnticipationCard } from "../../shared/anticipation-card";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription } from "@/components/ui/empty";
import { useControlledState } from "@/hooks/use-controlled-state";
import type { InstallmentAnticipationWithRelations } from "@/lib/installments/anticipation-types";
import { RiCalendarCheckLine, RiLoader4Line } from "@remixicon/react";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { RiCalendarCheckLine, RiLoader4Line } from "@remixicon/react";
import { getInstallmentAnticipationsAction } from "@/app/(dashboard)/lancamentos/anticipation-actions";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import {
Empty,
EmptyDescription,
EmptyHeader,
EmptyMedia,
EmptyTitle,
} from "@/components/ui/empty";
import { useControlledState } from "@/hooks/use-controlled-state";
import type { InstallmentAnticipationWithRelations } from "@/lib/installments/anticipation-types";
import { AnticipationCard } from "../../shared/anticipation-card";
interface AnticipationHistoryDialogProps {
trigger?: React.ReactNode;
seriesId: string;
lancamentoName: string;
open?: boolean;
onOpenChange?: (open: boolean) => void;
onViewLancamento?: (lancamentoId: string) => void;
trigger?: React.ReactNode;
seriesId: string;
lancamentoName: string;
open?: boolean;
onOpenChange?: (open: boolean) => void;
onViewLancamento?: (lancamentoId: string) => void;
}
export function AnticipationHistoryDialog({
trigger,
seriesId,
lancamentoName,
open,
onOpenChange,
onViewLancamento,
trigger,
seriesId,
lancamentoName,
open,
onOpenChange,
onViewLancamento,
}: AnticipationHistoryDialogProps) {
const [isLoading, setIsLoading] = useState(false);
const [anticipations, setAnticipations] = useState<
InstallmentAnticipationWithRelations[]
>([]);
const [isLoading, setIsLoading] = useState(false);
const [anticipations, setAnticipations] = useState<
InstallmentAnticipationWithRelations[]
>([]);
// Use controlled state hook for dialog open state
const [dialogOpen, setDialogOpen] = useControlledState(
open,
false,
onOpenChange
);
// Use controlled state hook for dialog open state
const [dialogOpen, setDialogOpen] = useControlledState(
open,
false,
onOpenChange,
);
// Buscar antecipações ao abrir o dialog
useEffect(() => {
if (dialogOpen) {
loadAnticipations();
}
}, [dialogOpen, seriesId]);
// Buscar antecipações ao abrir o dialog
useEffect(() => {
if (dialogOpen) {
loadAnticipations();
}
}, [dialogOpen, loadAnticipations]);
const loadAnticipations = async () => {
setIsLoading(true);
const loadAnticipations = async () => {
setIsLoading(true);
try {
const result = await getInstallmentAnticipationsAction(seriesId);
try {
const result = await getInstallmentAnticipationsAction(seriesId);
if (result.success && result.data) {
setAnticipations(result.data);
} else {
toast.error(result.error || "Erro ao carregar histórico de antecipações");
setAnticipations([]);
}
} catch (error) {
console.error("Erro ao buscar antecipações:", error);
toast.error("Erro ao carregar histórico de antecipações");
setAnticipations([]);
} finally {
setIsLoading(false);
}
};
if (result.success && result.data) {
setAnticipations(result.data);
} else {
toast.error(
result.error || "Erro ao carregar histórico de antecipações",
);
setAnticipations([]);
}
} catch (error) {
console.error("Erro ao buscar antecipações:", error);
toast.error("Erro ao carregar histórico de antecipações");
setAnticipations([]);
} finally {
setIsLoading(false);
}
};
const handleCanceled = () => {
// Recarregar lista após cancelamento
loadAnticipations();
};
const handleCanceled = () => {
// Recarregar lista após cancelamento
loadAnticipations();
};
return (
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
{trigger && <DialogTrigger asChild>{trigger}</DialogTrigger>}
<DialogContent className="max-w-3xl px-6 py-5 sm:px-8 sm:py-6">
<DialogHeader>
<DialogTitle>Histórico de Antecipações</DialogTitle>
<DialogDescription>{lancamentoName}</DialogDescription>
</DialogHeader>
return (
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
{trigger && <DialogTrigger asChild>{trigger}</DialogTrigger>}
<DialogContent className="max-w-3xl px-6 py-5 sm:px-8 sm:py-6">
<DialogHeader>
<DialogTitle>Histórico de Antecipações</DialogTitle>
<DialogDescription>{lancamentoName}</DialogDescription>
</DialogHeader>
<div className="max-h-[60vh] space-y-4 overflow-y-auto pr-2">
{isLoading ? (
<div className="flex items-center justify-center rounded-lg border border-dashed p-12">
<RiLoader4Line className="size-6 animate-spin text-muted-foreground" />
<span className="ml-2 text-sm text-muted-foreground">
Carregando histórico...
</span>
</div>
) : anticipations.length === 0 ? (
<Empty>
<EmptyHeader>
<EmptyMedia variant="icon">
<RiCalendarCheckLine className="size-6 text-muted-foreground" />
</EmptyMedia>
<EmptyTitle>Nenhuma antecipação registrada</EmptyTitle>
<EmptyDescription>
As antecipações realizadas para esta compra parcelada aparecerão aqui.
</EmptyDescription>
</EmptyHeader>
</Empty>
) : (
anticipations.map((anticipation) => (
<AnticipationCard
key={anticipation.id}
anticipation={anticipation}
onViewLancamento={onViewLancamento}
onCanceled={handleCanceled}
/>
))
)}
</div>
<div className="max-h-[60vh] space-y-4 overflow-y-auto pr-2">
{isLoading ? (
<div className="flex items-center justify-center rounded-lg border border-dashed p-12">
<RiLoader4Line className="size-6 animate-spin text-muted-foreground" />
<span className="ml-2 text-sm text-muted-foreground">
Carregando histórico...
</span>
</div>
) : anticipations.length === 0 ? (
<Empty>
<EmptyHeader>
<EmptyMedia variant="icon">
<RiCalendarCheckLine className="size-6 text-muted-foreground" />
</EmptyMedia>
<EmptyTitle>Nenhuma antecipação registrada</EmptyTitle>
<EmptyDescription>
As antecipações realizadas para esta compra parcelada
aparecerão aqui.
</EmptyDescription>
</EmptyHeader>
</Empty>
) : (
anticipations.map((anticipation) => (
<AnticipationCard
key={anticipation.id}
anticipation={anticipation}
onViewLancamento={onViewLancamento}
onCanceled={handleCanceled}
/>
))
)}
</div>
{!isLoading && anticipations.length > 0 && (
<div className="border-t pt-4 text-center text-sm text-muted-foreground">
{anticipations.length}{" "}
{anticipations.length === 1
? "antecipação encontrada"
: "antecipações encontradas"}
</div>
)}
</DialogContent>
</Dialog>
);
{!isLoading && anticipations.length > 0 && (
<div className="border-t pt-4 text-center text-sm text-muted-foreground">
{anticipations.length}{" "}
{anticipations.length === 1
? "antecipação encontrada"
: "antecipações encontradas"}
</div>
)}
</DialogContent>
</Dialog>
);
}

View File

@@ -1,155 +1,155 @@
"use client";
import { format } from "date-fns";
import { ptBR } from "date-fns/locale";
import MoneyValues from "@/components/money-values";
import { Badge } from "@/components/ui/badge";
import { Checkbox } from "@/components/ui/checkbox";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import type { EligibleInstallment } from "@/lib/installments/anticipation-types";
import { formatCurrentInstallment } from "@/lib/installments/utils";
import { cn } from "@/lib/utils/ui";
import { format } from "date-fns";
import { ptBR } from "date-fns/locale";
import MoneyValues from "@/components/money-values";
interface InstallmentSelectionTableProps {
installments: EligibleInstallment[];
selectedIds: string[];
onSelectionChange: (ids: string[]) => void;
installments: EligibleInstallment[];
selectedIds: string[];
onSelectionChange: (ids: string[]) => void;
}
export function InstallmentSelectionTable({
installments,
selectedIds,
onSelectionChange,
installments,
selectedIds,
onSelectionChange,
}: InstallmentSelectionTableProps) {
const toggleSelection = (id: string) => {
const newSelection = selectedIds.includes(id)
? selectedIds.filter((selectedId) => selectedId !== id)
: [...selectedIds, id];
onSelectionChange(newSelection);
};
const toggleSelection = (id: string) => {
const newSelection = selectedIds.includes(id)
? selectedIds.filter((selectedId) => selectedId !== id)
: [...selectedIds, id];
onSelectionChange(newSelection);
};
const toggleAll = () => {
if (selectedIds.length === installments.length && installments.length > 0) {
onSelectionChange([]);
} else {
onSelectionChange(installments.map((inst) => inst.id));
}
};
const toggleAll = () => {
if (selectedIds.length === installments.length && installments.length > 0) {
onSelectionChange([]);
} else {
onSelectionChange(installments.map((inst) => inst.id));
}
};
const formatPeriod = (period: string) => {
const [year, month] = period.split("-");
const date = new Date(Number(year), Number(month) - 1);
return format(date, "MMM/yyyy", { locale: ptBR });
};
const formatPeriod = (period: string) => {
const [year, month] = period.split("-");
const date = new Date(Number(year), Number(month) - 1);
return format(date, "MMM/yyyy", { locale: ptBR });
};
const formatDate = (date: Date | null) => {
if (!date) return "—";
return format(date, "dd/MM/yyyy", { locale: ptBR });
};
const formatDate = (date: Date | null) => {
if (!date) return "—";
return format(date, "dd/MM/yyyy", { locale: ptBR });
};
if (installments.length === 0) {
return (
<div className="rounded-lg border border-dashed p-8 text-center">
<p className="text-sm text-muted-foreground">
Nenhuma parcela elegível para antecipação encontrada.
</p>
<p className="mt-1 text-xs text-muted-foreground">
Todas as parcelas desta compra foram pagas ou antecipadas.
</p>
</div>
);
}
if (installments.length === 0) {
return (
<div className="rounded-lg border border-dashed p-8 text-center">
<p className="text-sm text-muted-foreground">
Nenhuma parcela elegível para antecipação encontrada.
</p>
<p className="mt-1 text-xs text-muted-foreground">
Todas as parcelas desta compra foram pagas ou antecipadas.
</p>
</div>
);
}
return (
<div className="overflow-hidden rounded-lg border">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-12">
<Checkbox
checked={
selectedIds.length === installments.length &&
installments.length > 0
}
onCheckedChange={toggleAll}
aria-label="Selecionar todas as parcelas"
/>
</TableHead>
<TableHead>Parcela</TableHead>
<TableHead>Período</TableHead>
<TableHead>Vencimento</TableHead>
<TableHead className="text-right">Valor</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{installments.map((inst) => {
const isSelected = selectedIds.includes(inst.id);
return (
<TableRow
key={inst.id}
className={cn(
"cursor-pointer transition-colors",
isSelected && "bg-muted/50"
)}
onClick={() => toggleSelection(inst.id)}
>
<TableCell onClick={(e) => e.stopPropagation()}>
<Checkbox
checked={isSelected}
onCheckedChange={() => toggleSelection(inst.id)}
aria-label={`Selecionar parcela ${inst.currentInstallment}`}
/>
</TableCell>
<TableCell>
<Badge variant="outline">
{formatCurrentInstallment(
inst.currentInstallment ?? 0,
inst.installmentCount ?? 0
)}
</Badge>
</TableCell>
<TableCell className="font-medium">
{formatPeriod(inst.period)}
</TableCell>
<TableCell className="text-muted-foreground">
{formatDate(inst.dueDate)}
</TableCell>
<TableCell className="text-right font-semibold tabular-nums">
<MoneyValues amount={Number(inst.amount)} />
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
return (
<div className="overflow-hidden rounded-lg border">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-12">
<Checkbox
checked={
selectedIds.length === installments.length &&
installments.length > 0
}
onCheckedChange={toggleAll}
aria-label="Selecionar todas as parcelas"
/>
</TableHead>
<TableHead>Parcela</TableHead>
<TableHead>Período</TableHead>
<TableHead>Vencimento</TableHead>
<TableHead className="text-right">Valor</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{installments.map((inst) => {
const isSelected = selectedIds.includes(inst.id);
return (
<TableRow
key={inst.id}
className={cn(
"cursor-pointer transition-colors",
isSelected && "bg-muted/50",
)}
onClick={() => toggleSelection(inst.id)}
>
<TableCell onClick={(e) => e.stopPropagation()}>
<Checkbox
checked={isSelected}
onCheckedChange={() => toggleSelection(inst.id)}
aria-label={`Selecionar parcela ${inst.currentInstallment}`}
/>
</TableCell>
<TableCell>
<Badge variant="outline">
{formatCurrentInstallment(
inst.currentInstallment ?? 0,
inst.installmentCount ?? 0,
)}
</Badge>
</TableCell>
<TableCell className="font-medium">
{formatPeriod(inst.period)}
</TableCell>
<TableCell className="text-muted-foreground">
{formatDate(inst.dueDate)}
</TableCell>
<TableCell className="text-right font-semibold tabular-nums">
<MoneyValues amount={Number(inst.amount)} />
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
{selectedIds.length > 0 && (
<div className="border-t bg-muted/20 px-4 py-3">
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">
{selectedIds.length}{" "}
{selectedIds.length === 1
? "parcela selecionada"
: "parcelas selecionadas"}
</span>
<span className="font-semibold">
Total:{" "}
<MoneyValues
amount={installments
.filter((inst) => selectedIds.includes(inst.id))
.reduce((sum, inst) => sum + Number(inst.amount), 0)}
/>
</span>
</div>
</div>
)}
</div>
);
{selectedIds.length > 0 && (
<div className="border-t bg-muted/20 px-4 py-3">
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">
{selectedIds.length}{" "}
{selectedIds.length === 1
? "parcela selecionada"
: "parcelas selecionadas"}
</span>
<span className="font-semibold">
Total:{" "}
<MoneyValues
amount={installments
.filter((inst) => selectedIds.includes(inst.id))
.reduce((sum, inst) => sum + Number(inst.amount), 0)}
/>
</span>
</div>
</div>
)}
</div>
);
}