mirror of
https://github.com/felipegcoutinho/openmonetis.git
synced 2026-03-10 04:51:47 +00:00
feat: adição de novos ícones SVG e configuração do ambiente
- Adicionados ícones SVG para ChatGPT, Claude, Gemini e OpenRouter - Implementados ícones para modos claro e escuro do ChatGPT - Criado script de inicialização para PostgreSQL com extensão pgcrypto - Adicionado script de configuração de ambiente que faz backup do .env - Configurado tsconfig.json para TypeScript com opções de compilação
This commit is contained in:
143
components/ajustes/delete-account-form.tsx
Normal file
143
components/ajustes/delete-account-form.tsx
Normal file
@@ -0,0 +1,143 @@
|
||||
"use client";
|
||||
|
||||
import { deleteAccountAction } from "@/app/(dashboard)/ajustes/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { authClient } from "@/lib/auth/client";
|
||||
import { RiAlertLine } from "@remixicon/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState, useTransition } from "react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
export function DeleteAccountForm() {
|
||||
const router = useRouter();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [confirmation, setConfirmation] = useState("");
|
||||
|
||||
const handleDelete = () => {
|
||||
startTransition(async () => {
|
||||
const result = await deleteAccountAction({
|
||||
confirmation,
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
// Fazer logout e redirecionar para página de login
|
||||
await authClient.signOut();
|
||||
router.push("/");
|
||||
} else {
|
||||
toast.error(result.error);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const handleOpenModal = () => {
|
||||
setConfirmation("");
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
const handleCloseModal = () => {
|
||||
if (isPending) return;
|
||||
setConfirmation("");
|
||||
setIsModalOpen(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="rounded-lg border border-destructive/50 bg-destructive/10 p-4 space-y-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<RiAlertLine className="size-5 text-destructive mt-0.5" />
|
||||
<div className="flex-1 space-y-1">
|
||||
<h3 className="font-medium text-destructive">
|
||||
Remoção definitiva de conta
|
||||
</h3>
|
||||
<p className="text-sm text-foreground">
|
||||
Ao prosseguir, sua conta e todos os dados associados serão
|
||||
excluídos de forma irreversível.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ul className="list-disc list-inside text-sm text-muted-foreground space-y-1 pl-8">
|
||||
<li>Lançamentos, anexos e notas</li>
|
||||
<li>Contas, cartões, orçamentos e categorias</li>
|
||||
<li>Pagadores (incluindo o pagador padrão)</li>
|
||||
<li>Preferências e configurações</li>
|
||||
</ul>
|
||||
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={handleOpenModal}
|
||||
disabled={isPending}
|
||||
>
|
||||
Deletar conta
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
|
||||
<DialogContent
|
||||
className="max-w-md"
|
||||
onEscapeKeyDown={(e) => {
|
||||
if (isPending) e.preventDefault();
|
||||
}}
|
||||
onPointerDownOutside={(e) => {
|
||||
if (isPending) e.preventDefault();
|
||||
}}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Você tem certeza?</DialogTitle>
|
||||
<DialogDescription>
|
||||
Essa ação não pode ser desfeita. Isso irá deletar permanentemente
|
||||
sua conta e remover seus dados de nossos servidores.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="confirmation">
|
||||
Para confirmar, digite <strong>DELETAR</strong> no campo abaixo.
|
||||
</Label>
|
||||
<Input
|
||||
id="confirmation"
|
||||
value={confirmation}
|
||||
onChange={(e) => setConfirmation(e.target.value)}
|
||||
disabled={isPending}
|
||||
placeholder="DELETAR"
|
||||
autoComplete="off"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="sm:justify-end">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={handleCloseModal}
|
||||
disabled={isPending}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
onClick={handleDelete}
|
||||
disabled={isPending || confirmation !== "DELETAR"}
|
||||
>
|
||||
{isPending ? "Deletando..." : "Deletar"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
71
components/ajustes/update-email-form.tsx
Normal file
71
components/ajustes/update-email-form.tsx
Normal file
@@ -0,0 +1,71 @@
|
||||
"use client";
|
||||
|
||||
import { updateEmailAction } from "@/app/(dashboard)/ajustes/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { useState, useTransition } from "react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
type UpdateEmailFormProps = {
|
||||
currentEmail: string;
|
||||
};
|
||||
|
||||
export function UpdateEmailForm({ currentEmail }: UpdateEmailFormProps) {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [newEmail, setNewEmail] = useState("");
|
||||
const [confirmEmail, setConfirmEmail] = useState("");
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
startTransition(async () => {
|
||||
const result = await updateEmailAction({
|
||||
newEmail,
|
||||
confirmEmail,
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
setNewEmail("");
|
||||
setConfirmEmail("");
|
||||
} else {
|
||||
toast.error(result.error);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="newEmail">Novo e-mail</Label>
|
||||
<Input
|
||||
id="newEmail"
|
||||
type="email"
|
||||
value={newEmail}
|
||||
onChange={(e) => setNewEmail(e.target.value)}
|
||||
disabled={isPending}
|
||||
placeholder={currentEmail}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="confirmEmail">Confirmar novo e-mail</Label>
|
||||
<Input
|
||||
id="confirmEmail"
|
||||
type="email"
|
||||
value={confirmEmail}
|
||||
onChange={(e) => setConfirmEmail(e.target.value)}
|
||||
disabled={isPending}
|
||||
placeholder="repita o e-mail"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button type="submit" disabled={isPending}>
|
||||
{isPending ? "Atualizando..." : "Atualizar e-mail"}
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
71
components/ajustes/update-name-form.tsx
Normal file
71
components/ajustes/update-name-form.tsx
Normal file
@@ -0,0 +1,71 @@
|
||||
"use client";
|
||||
|
||||
import { updateNameAction } from "@/app/(dashboard)/ajustes/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { useState, useTransition } from "react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
type UpdateNameFormProps = {
|
||||
currentName: string;
|
||||
};
|
||||
|
||||
export function UpdateNameForm({ currentName }: UpdateNameFormProps) {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
// Dividir o nome atual em primeiro nome e sobrenome
|
||||
const nameParts = currentName.split(" ");
|
||||
const initialFirstName = nameParts[0] || "";
|
||||
const initialLastName = nameParts.slice(1).join(" ") || "";
|
||||
|
||||
const [firstName, setFirstName] = useState(initialFirstName);
|
||||
const [lastName, setLastName] = useState(initialLastName);
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
startTransition(async () => {
|
||||
const result = await updateNameAction({
|
||||
firstName,
|
||||
lastName,
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
} else {
|
||||
toast.error(result.error);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="firstName">Primeiro nome</Label>
|
||||
<Input
|
||||
id="firstName"
|
||||
value={firstName}
|
||||
onChange={(e) => setFirstName(e.target.value)}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="lastName">Sobrenome</Label>
|
||||
<Input
|
||||
id="lastName"
|
||||
value={lastName}
|
||||
onChange={(e) => setLastName(e.target.value)}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button type="submit" disabled={isPending}>
|
||||
{isPending ? "Atualizando..." : "Atualizar nome"}
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
98
components/ajustes/update-password-form.tsx
Normal file
98
components/ajustes/update-password-form.tsx
Normal file
@@ -0,0 +1,98 @@
|
||||
"use client";
|
||||
|
||||
import { updatePasswordAction } from "@/app/(dashboard)/ajustes/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { RiEyeLine, RiEyeOffLine } from "@remixicon/react";
|
||||
import { useState, useTransition } from "react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
export function UpdatePasswordForm() {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [newPassword, setNewPassword] = useState("");
|
||||
const [confirmPassword, setConfirmPassword] = useState("");
|
||||
const [showNewPassword, setShowNewPassword] = useState(false);
|
||||
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
startTransition(async () => {
|
||||
const result = await updatePasswordAction({
|
||||
newPassword,
|
||||
confirmPassword,
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
setNewPassword("");
|
||||
setConfirmPassword("");
|
||||
} else {
|
||||
toast.error(result.error);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="newPassword">Nova senha</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="newPassword"
|
||||
type={showNewPassword ? "text" : "password"}
|
||||
value={newPassword}
|
||||
onChange={(e) => setNewPassword(e.target.value)}
|
||||
disabled={isPending}
|
||||
placeholder="Mínimo de 6 caracteres"
|
||||
required
|
||||
minLength={6}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowNewPassword(!showNewPassword)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{showNewPassword ? (
|
||||
<RiEyeOffLine size={20} />
|
||||
) : (
|
||||
<RiEyeLine size={20} />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="confirmPassword">Confirmar nova senha</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="confirmPassword"
|
||||
type={showConfirmPassword ? "text" : "password"}
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
disabled={isPending}
|
||||
placeholder="Repita a senha"
|
||||
required
|
||||
minLength={6}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{showConfirmPassword ? (
|
||||
<RiEyeOffLine size={20} />
|
||||
) : (
|
||||
<RiEyeLine size={20} />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button type="submit" disabled={isPending}>
|
||||
{isPending ? "Atualizando..." : "Atualizar senha"}
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
122
components/animated-theme-toggler.tsx
Normal file
122
components/animated-theme-toggler.tsx
Normal file
@@ -0,0 +1,122 @@
|
||||
"use client";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import { RiMoonClearLine, RiSunLine } from "@remixicon/react";
|
||||
|
||||
interface AnimatedThemeTogglerProps
|
||||
extends React.ComponentPropsWithoutRef<"button"> {
|
||||
duration?: number;
|
||||
}
|
||||
|
||||
export const AnimatedThemeToggler = ({
|
||||
className,
|
||||
duration = 400,
|
||||
...props
|
||||
}: AnimatedThemeTogglerProps) => {
|
||||
const [isDark, setIsDark] = useState(false);
|
||||
const buttonRef = useRef<HTMLButtonElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const updateTheme = () => {
|
||||
setIsDark(document.documentElement.classList.contains("dark"));
|
||||
};
|
||||
|
||||
updateTheme();
|
||||
|
||||
const observer = new MutationObserver(updateTheme);
|
||||
observer.observe(document.documentElement, {
|
||||
attributes: true,
|
||||
attributeFilter: ["class"],
|
||||
});
|
||||
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
const toggleTheme = useCallback(async () => {
|
||||
if (!buttonRef.current) return;
|
||||
|
||||
await document.startViewTransition(() => {
|
||||
flushSync(() => {
|
||||
const newTheme = !isDark;
|
||||
setIsDark(newTheme);
|
||||
document.documentElement.classList.toggle("dark");
|
||||
localStorage.setItem("theme", newTheme ? "dark" : "light");
|
||||
});
|
||||
}).ready;
|
||||
|
||||
const { top, left, width, height } =
|
||||
buttonRef.current.getBoundingClientRect();
|
||||
const x = left + width / 2;
|
||||
const y = top + height / 2;
|
||||
const maxRadius = Math.hypot(
|
||||
Math.max(left, window.innerWidth - left),
|
||||
Math.max(top, window.innerHeight - top)
|
||||
);
|
||||
|
||||
document.documentElement.animate(
|
||||
{
|
||||
clipPath: [
|
||||
`circle(0px at ${x}px ${y}px)`,
|
||||
`circle(${maxRadius}px at ${x}px ${y}px)`,
|
||||
],
|
||||
},
|
||||
{
|
||||
duration,
|
||||
easing: "ease-in-out",
|
||||
pseudoElement: "::view-transition-new(root)",
|
||||
}
|
||||
);
|
||||
}, [isDark, duration]);
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
ref={buttonRef}
|
||||
type="button"
|
||||
onClick={toggleTheme}
|
||||
data-state={isDark ? "dark" : "light"}
|
||||
className={cn(
|
||||
buttonVariants({ variant: "ghost", size: "icon-sm" }),
|
||||
"group relative text-muted-foreground transition-all duration-200",
|
||||
"hover:text-foreground focus-visible:ring-2 focus-visible:ring-primary/40",
|
||||
"data-[state=open]:bg-accent/60 data-[state=open]:text-foreground border",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className="pointer-events-none absolute inset-0 -z-10 opacity-0 transition-opacity duration-200 data-[state=dark]:opacity-100"
|
||||
>
|
||||
<span className="absolute inset-0 bg-linear-to-br from-amber-500/5 via-transparent to-amber-500/15 dark:from-amber-500/10 dark:to-amber-500/30" />
|
||||
</span>
|
||||
{isDark ? (
|
||||
<RiSunLine
|
||||
className="size-4 transition-transform duration-200"
|
||||
aria-hidden
|
||||
/>
|
||||
) : (
|
||||
<RiMoonClearLine
|
||||
className="size-4 transition-transform duration-200"
|
||||
aria-hidden
|
||||
/>
|
||||
)}
|
||||
<span className="sr-only">
|
||||
{isDark ? "Ativar tema claro" : "Ativar tema escuro"}
|
||||
</span>
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom" sideOffset={8}>
|
||||
{isDark ? "Tema claro" : "Tema escuro"}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
};
|
||||
139
components/anotacoes/note-card.tsx
Normal file
139
components/anotacoes/note-card.tsx
Normal file
@@ -0,0 +1,139 @@
|
||||
"use client";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardFooter } from "@/components/ui/card";
|
||||
import { RiDeleteBin5Line, RiEyeLine, RiPencilLine } from "@remixicon/react";
|
||||
import { CheckIcon } from "lucide-react";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import type { Note } from "./types";
|
||||
|
||||
const DATE_FORMATTER = new Intl.DateTimeFormat("pt-BR", {
|
||||
dateStyle: "medium",
|
||||
});
|
||||
|
||||
interface NoteCardProps {
|
||||
note: Note;
|
||||
onEdit?: (note: Note) => void;
|
||||
onDetails?: (note: Note) => void;
|
||||
onRemove?: (note: Note) => void;
|
||||
}
|
||||
|
||||
export function NoteCard({ note, onEdit, onDetails, onRemove }: NoteCardProps) {
|
||||
const { formattedDate, displayTitle } = useMemo(() => {
|
||||
const resolvedTitle = note.title.trim().length
|
||||
? note.title
|
||||
: "Anotação sem título";
|
||||
|
||||
return {
|
||||
displayTitle: resolvedTitle,
|
||||
formattedDate: DATE_FORMATTER.format(new Date(note.createdAt)),
|
||||
};
|
||||
}, [note.createdAt, note.title]);
|
||||
|
||||
const isTask = note.type === "tarefa";
|
||||
const tasks = note.tasks || [];
|
||||
const completedCount = tasks.filter((t) => t.completed).length;
|
||||
const totalCount = tasks.length;
|
||||
|
||||
const actions = [
|
||||
{
|
||||
label: "editar",
|
||||
icon: <RiPencilLine className="size-4" aria-hidden />,
|
||||
onClick: onEdit,
|
||||
variant: "default" as const,
|
||||
},
|
||||
{
|
||||
label: "detalhes",
|
||||
icon: <RiEyeLine className="size-4" aria-hidden />,
|
||||
onClick: onDetails,
|
||||
variant: "default" as const,
|
||||
},
|
||||
{
|
||||
label: "remover",
|
||||
icon: <RiDeleteBin5Line className="size-4" aria-hidden />,
|
||||
onClick: onRemove,
|
||||
variant: "destructive" as const,
|
||||
},
|
||||
].filter((action) => typeof action.onClick === "function");
|
||||
|
||||
return (
|
||||
<Card className="h-[300px] w-[440px] gap-0">
|
||||
<CardContent className="flex flex-1 flex-col gap-4">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex flex-col gap-2">
|
||||
<h3 className="text-lg font-semibold leading-tight text-foreground wrap-break-word">
|
||||
{displayTitle}
|
||||
</h3>
|
||||
{isTask && (
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{completedCount}/{totalCount} concluídas
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-xs font-medium uppercase tracking-wide text-muted-foreground whitespace-nowrap">
|
||||
{formattedDate}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{isTask ? (
|
||||
<div className="flex-1 overflow-auto space-y-2">
|
||||
{tasks.slice(0, 4).map((task) => (
|
||||
<div key={task.id} className="flex items-start gap-2 text-sm">
|
||||
<div
|
||||
className={`mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-sm border ${
|
||||
task.completed
|
||||
? "bg-green-600 border-green-600"
|
||||
: "border-input"
|
||||
}`}
|
||||
>
|
||||
{task.completed && (
|
||||
<CheckIcon className="h-3 w-3 text-background" />
|
||||
)}
|
||||
</div>
|
||||
<span
|
||||
className={`leading-relaxed ${
|
||||
task.completed
|
||||
? "line-through text-muted-foreground"
|
||||
: "text-foreground"
|
||||
}`}
|
||||
>
|
||||
{task.text}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
{tasks.length > 4 && (
|
||||
<p className="text-xs text-muted-foreground pl-5 py-1">
|
||||
+{tasks.length - 4}{" "}
|
||||
{tasks.length - 4 === 1 ? "tarefa" : "tarefas"}...
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<p className="flex-1 overflow-auto whitespace-pre-line text-sm text-muted-foreground wrap-break-word leading-relaxed">
|
||||
{note.description}
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
{actions.length > 0 ? (
|
||||
<CardFooter className="flex flex-wrap gap-3 px-6 pt-3 text-sm">
|
||||
{actions.map(({ label, icon, onClick, variant }) => (
|
||||
<button
|
||||
key={label}
|
||||
type="button"
|
||||
onClick={() => onClick?.(note)}
|
||||
className={`flex items-center gap-1 font-medium transition-opacity hover:opacity-80 ${
|
||||
variant === "destructive" ? "text-destructive" : "text-primary"
|
||||
}`}
|
||||
aria-label={`${label} anotação`}
|
||||
>
|
||||
{icon}
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</CardFooter>
|
||||
) : null}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
118
components/anotacoes/note-details-dialog.tsx
Normal file
118
components/anotacoes/note-details-dialog.tsx
Normal file
@@ -0,0 +1,118 @@
|
||||
"use client";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { CheckIcon } from "lucide-react";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import type { Note } from "./types";
|
||||
|
||||
const DATE_FORMATTER = new Intl.DateTimeFormat("pt-BR", {
|
||||
dateStyle: "long",
|
||||
timeStyle: "short",
|
||||
});
|
||||
|
||||
interface NoteDetailsDialogProps {
|
||||
note: Note | null;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function NoteDetailsDialog({
|
||||
note,
|
||||
open,
|
||||
onOpenChange,
|
||||
}: NoteDetailsDialogProps) {
|
||||
const { formattedDate, displayTitle } = useMemo(() => {
|
||||
if (!note) {
|
||||
return { formattedDate: "", displayTitle: "" };
|
||||
}
|
||||
|
||||
const title = note.title.trim().length ? note.title : "Anotação sem título";
|
||||
|
||||
return {
|
||||
formattedDate: DATE_FORMATTER.format(new Date(note.createdAt)),
|
||||
displayTitle: title,
|
||||
};
|
||||
}, [note]);
|
||||
|
||||
if (!note) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const isTask = note.type === "tarefa";
|
||||
const tasks = note.tasks || [];
|
||||
const completedCount = tasks.filter((t) => t.completed).length;
|
||||
const totalCount = tasks.length;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
{displayTitle}
|
||||
{isTask && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{completedCount}/{totalCount}
|
||||
</Badge>
|
||||
)}
|
||||
</DialogTitle>
|
||||
<DialogDescription>{formattedDate}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{isTask ? (
|
||||
<div className="max-h-[320px] overflow-auto space-y-3">
|
||||
{tasks.map((task) => (
|
||||
<div
|
||||
key={task.id}
|
||||
className="flex items-start gap-3 p-3 rounded-lg border bg-card"
|
||||
>
|
||||
<div
|
||||
className={`mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-sm border ${
|
||||
task.completed
|
||||
? "bg-green-600 border-green-600"
|
||||
: "border-input"
|
||||
}`}
|
||||
>
|
||||
{task.completed && (
|
||||
<CheckIcon className="h-4 w-4 text-primary-foreground" />
|
||||
)}
|
||||
</div>
|
||||
<span
|
||||
className={`text-sm ${
|
||||
task.completed
|
||||
? "line-through text-muted-foreground"
|
||||
: "text-foreground"
|
||||
}`}
|
||||
>
|
||||
{task.text}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="max-h-[320px] overflow-auto whitespace-pre-line wrap-break-word text-sm text-foreground">
|
||||
{note.description}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="outline">
|
||||
Fechar
|
||||
</Button>
|
||||
</DialogClose>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
470
components/anotacoes/note-dialog.tsx
Normal file
470
components/anotacoes/note-dialog.tsx
Normal file
@@ -0,0 +1,470 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
createNoteAction,
|
||||
updateNoteAction,
|
||||
} from "@/app/(dashboard)/anotacoes/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { useControlledState } from "@/hooks/use-controlled-state";
|
||||
import { useFormState } from "@/hooks/use-form-state";
|
||||
import { PlusIcon, Trash2Icon } from "lucide-react";
|
||||
import {
|
||||
type ReactNode,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
useTransition,
|
||||
} from "react";
|
||||
import { toast } from "sonner";
|
||||
import type { Note, NoteFormValues, Task } from "./types";
|
||||
|
||||
type NoteDialogMode = "create" | "update";
|
||||
interface NoteDialogProps {
|
||||
mode: NoteDialogMode;
|
||||
trigger?: ReactNode;
|
||||
note?: Note;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
const MAX_TITLE = 30;
|
||||
const MAX_DESC = 350;
|
||||
const normalize = (s: string) => s.replace(/\s+/g, " ").trim();
|
||||
|
||||
const buildInitialValues = (note?: Note): NoteFormValues => ({
|
||||
title: note?.title ?? "",
|
||||
description: note?.description ?? "",
|
||||
type: note?.type ?? "nota",
|
||||
tasks: note?.tasks ?? [],
|
||||
});
|
||||
|
||||
const generateTaskId = () => {
|
||||
return `task-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
|
||||
};
|
||||
|
||||
export function NoteDialog({
|
||||
mode,
|
||||
trigger,
|
||||
note,
|
||||
open,
|
||||
onOpenChange,
|
||||
}: NoteDialogProps) {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [newTaskText, setNewTaskText] = useState("");
|
||||
|
||||
const titleRef = useRef<HTMLInputElement>(null);
|
||||
const descRef = useRef<HTMLTextAreaElement>(null);
|
||||
const newTaskRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// Use controlled state hook for dialog open state
|
||||
const [dialogOpen, setDialogOpen] = useControlledState(
|
||||
open,
|
||||
false,
|
||||
onOpenChange
|
||||
);
|
||||
|
||||
const initialState = buildInitialValues(note);
|
||||
|
||||
// Use form state hook for form management
|
||||
const { formState, updateField, setFormState } =
|
||||
useFormState<NoteFormValues>(initialState);
|
||||
|
||||
useEffect(() => {
|
||||
if (dialogOpen) {
|
||||
setFormState(buildInitialValues(note));
|
||||
setErrorMessage(null);
|
||||
setNewTaskText("");
|
||||
requestAnimationFrame(() => titleRef.current?.focus());
|
||||
}
|
||||
}, [dialogOpen, note, setFormState]);
|
||||
|
||||
const title = mode === "create" ? "Nova anotação" : "Editar anotação";
|
||||
const description =
|
||||
mode === "create"
|
||||
? "Escolha entre uma nota simples ou uma lista de tarefas."
|
||||
: "Altere o título e/ou conteúdo desta anotação.";
|
||||
const submitLabel =
|
||||
mode === "create" ? "Salvar anotação" : "Atualizar anotação";
|
||||
|
||||
const titleCount = formState.title.length;
|
||||
const descCount = formState.description.length;
|
||||
const isNote = formState.type === "nota";
|
||||
|
||||
const onlySpaces =
|
||||
normalize(formState.title).length === 0 ||
|
||||
(isNote && normalize(formState.description).length === 0) ||
|
||||
(!isNote && (!formState.tasks || formState.tasks.length === 0));
|
||||
|
||||
const invalidLen = titleCount > MAX_TITLE || descCount > MAX_DESC;
|
||||
|
||||
const unchanged =
|
||||
mode === "update" &&
|
||||
normalize(formState.title) === normalize(note?.title ?? "") &&
|
||||
normalize(formState.description) === normalize(note?.description ?? "") &&
|
||||
JSON.stringify(formState.tasks) === JSON.stringify(note?.tasks);
|
||||
|
||||
const disableSubmit = isPending || onlySpaces || unchanged || invalidLen;
|
||||
|
||||
const handleOpenChange = useCallback(
|
||||
(v: boolean) => {
|
||||
setDialogOpen(v);
|
||||
if (!v) setErrorMessage(null);
|
||||
},
|
||||
[setDialogOpen]
|
||||
);
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(e: React.KeyboardEvent) => {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === "Enter")
|
||||
(e.currentTarget as HTMLFormElement).requestSubmit();
|
||||
if (e.key === "Escape") handleOpenChange(false);
|
||||
},
|
||||
[handleOpenChange]
|
||||
);
|
||||
|
||||
const handleAddTask = useCallback(() => {
|
||||
const text = normalize(newTaskText);
|
||||
if (!text) return;
|
||||
|
||||
const newTask: Task = {
|
||||
id: generateTaskId(),
|
||||
text,
|
||||
completed: false,
|
||||
};
|
||||
|
||||
updateField("tasks", [...(formState.tasks || []), newTask]);
|
||||
setNewTaskText("");
|
||||
requestAnimationFrame(() => newTaskRef.current?.focus());
|
||||
}, [newTaskText, formState.tasks, updateField]);
|
||||
|
||||
const handleRemoveTask = useCallback(
|
||||
(taskId: string) => {
|
||||
updateField(
|
||||
"tasks",
|
||||
(formState.tasks || []).filter((t) => t.id !== taskId)
|
||||
);
|
||||
},
|
||||
[formState.tasks, updateField]
|
||||
);
|
||||
|
||||
const handleToggleTask = useCallback(
|
||||
(taskId: string) => {
|
||||
updateField(
|
||||
"tasks",
|
||||
(formState.tasks || []).map((t) =>
|
||||
t.id === taskId ? { ...t, completed: !t.completed } : t
|
||||
)
|
||||
);
|
||||
},
|
||||
[formState.tasks, updateField]
|
||||
);
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
(e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
setErrorMessage(null);
|
||||
|
||||
const payload = {
|
||||
title: normalize(formState.title),
|
||||
description: normalize(formState.description),
|
||||
type: formState.type,
|
||||
tasks: formState.tasks,
|
||||
};
|
||||
|
||||
if (onlySpaces || invalidLen) {
|
||||
setErrorMessage("Preencha os campos respeitando os limites.");
|
||||
titleRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
if (mode === "update" && !note?.id) {
|
||||
const msg = "Não foi possível identificar a anotação a ser editada.";
|
||||
setErrorMessage(msg);
|
||||
toast.error(msg);
|
||||
return;
|
||||
}
|
||||
|
||||
if (unchanged) {
|
||||
toast.info("Nada para atualizar.");
|
||||
return;
|
||||
}
|
||||
|
||||
startTransition(async () => {
|
||||
let result;
|
||||
if (mode === "create") {
|
||||
result = await createNoteAction(payload);
|
||||
} else {
|
||||
if (!note?.id) {
|
||||
const msg = "ID da anotação não encontrado.";
|
||||
setErrorMessage(msg);
|
||||
toast.error(msg);
|
||||
return;
|
||||
}
|
||||
result = await updateNoteAction({ id: note.id, ...payload });
|
||||
}
|
||||
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
setDialogOpen(false);
|
||||
return;
|
||||
}
|
||||
setErrorMessage(result.error);
|
||||
toast.error(result.error);
|
||||
titleRef.current?.focus();
|
||||
});
|
||||
},
|
||||
[
|
||||
formState.title,
|
||||
formState.description,
|
||||
formState.type,
|
||||
formState.tasks,
|
||||
mode,
|
||||
note,
|
||||
setDialogOpen,
|
||||
onlySpaces,
|
||||
unchanged,
|
||||
invalidLen,
|
||||
]
|
||||
);
|
||||
|
||||
return (
|
||||
<Dialog open={dialogOpen} onOpenChange={handleOpenChange}>
|
||||
{trigger ? <DialogTrigger asChild>{trigger}</DialogTrigger> : null}
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form
|
||||
className="space-y-4"
|
||||
onSubmit={handleSubmit}
|
||||
onKeyDown={handleKeyDown}
|
||||
noValidate
|
||||
>
|
||||
{/* Seletor de Tipo - apenas no modo de criação */}
|
||||
{mode === "create" && (
|
||||
<div className="space-y-3">
|
||||
<label className="text-sm font-medium text-foreground">
|
||||
Tipo de anotação
|
||||
</label>
|
||||
<RadioGroup
|
||||
value={formState.type}
|
||||
onValueChange={(value) =>
|
||||
updateField("type", value as "nota" | "tarefa")
|
||||
}
|
||||
disabled={isPending}
|
||||
className="flex gap-4"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="nota" id="tipo-nota" />
|
||||
<label
|
||||
htmlFor="tipo-nota"
|
||||
className="text-sm cursor-pointer select-none"
|
||||
>
|
||||
Nota
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="tarefa" id="tipo-tarefa" />
|
||||
<label
|
||||
htmlFor="tipo-tarefa"
|
||||
className="text-sm cursor-pointer select-none"
|
||||
>
|
||||
Tarefas
|
||||
</label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Título */}
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="note-title"
|
||||
className="text-sm font-medium text-foreground"
|
||||
>
|
||||
Título
|
||||
</label>
|
||||
<Input
|
||||
id="note-title"
|
||||
ref={titleRef}
|
||||
value={formState.title}
|
||||
onChange={(e) => updateField("title", e.target.value)}
|
||||
placeholder={
|
||||
isNote ? "Ex.: Revisar metas do mês" : "Ex.: Tarefas da semana"
|
||||
}
|
||||
maxLength={MAX_TITLE}
|
||||
disabled={isPending}
|
||||
aria-describedby="note-title-help"
|
||||
required
|
||||
/>
|
||||
<p
|
||||
id="note-title-help"
|
||||
className="text-xs text-muted-foreground"
|
||||
aria-live="polite"
|
||||
>
|
||||
Até {MAX_TITLE} caracteres. Restantes:{" "}
|
||||
{Math.max(0, MAX_TITLE - titleCount)}.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Conteúdo - apenas para Notas */}
|
||||
{isNote && (
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="note-description"
|
||||
className="text-sm font-medium text-foreground"
|
||||
>
|
||||
Conteúdo
|
||||
</label>
|
||||
<Textarea
|
||||
id="note-description"
|
||||
className="field-sizing-fixed"
|
||||
ref={descRef}
|
||||
value={formState.description}
|
||||
onChange={(e) => updateField("description", e.target.value)}
|
||||
placeholder="Detalhe sua anotação..."
|
||||
rows={6}
|
||||
maxLength={MAX_DESC}
|
||||
disabled={isPending}
|
||||
aria-describedby="note-desc-help"
|
||||
required
|
||||
/>
|
||||
<p
|
||||
id="note-desc-help"
|
||||
className="text-xs text-muted-foreground"
|
||||
aria-live="polite"
|
||||
>
|
||||
Até {MAX_DESC} caracteres. Restantes:{" "}
|
||||
{Math.max(0, MAX_DESC - descCount)}.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Lista de Tarefas - apenas para Tarefas */}
|
||||
{!isNote && (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="new-task-input"
|
||||
className="text-sm font-medium text-foreground"
|
||||
>
|
||||
Adicionar tarefa
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="new-task-input"
|
||||
ref={newTaskRef}
|
||||
value={newTaskText}
|
||||
onChange={(e) => setNewTaskText(e.target.value)}
|
||||
placeholder="Ex.: Comprar ingredientes para o jantar"
|
||||
disabled={isPending}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
handleAddTask();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleAddTask}
|
||||
disabled={isPending || !normalize(newTaskText)}
|
||||
className="shrink-0"
|
||||
>
|
||||
<PlusIcon className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Pressione Enter ou clique no botão + para adicionar
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Lista de tarefas existentes */}
|
||||
{formState.tasks && formState.tasks.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium text-foreground">
|
||||
Tarefas ({formState.tasks.length})
|
||||
</label>
|
||||
<div className="space-y-2 max-h-[240px] overflow-y-auto pr-1">
|
||||
{formState.tasks.map((task) => (
|
||||
<div
|
||||
key={task.id}
|
||||
className="flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-accent/50 transition-colors"
|
||||
>
|
||||
<Checkbox
|
||||
checked={task.completed}
|
||||
onCheckedChange={() => handleToggleTask(task.id)}
|
||||
disabled={isPending}
|
||||
aria-label={`Marcar tarefa "${task.text}" como ${
|
||||
task.completed ? "não concluída" : "concluída"
|
||||
}`}
|
||||
/>
|
||||
<span
|
||||
className={`flex-1 text-sm wrap-break-word ${
|
||||
task.completed
|
||||
? "line-through text-muted-foreground"
|
||||
: "text-foreground"
|
||||
}`}
|
||||
>
|
||||
{task.text}
|
||||
</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleRemoveTask(task.id)}
|
||||
disabled={isPending}
|
||||
className="h-8 w-8 p-0 shrink-0 text-muted-foreground hover:text-destructive"
|
||||
aria-label={`Remover tarefa "${task.text}"`}
|
||||
>
|
||||
<Trash2Icon className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{errorMessage ? (
|
||||
<p className="text-sm text-destructive" role="alert">
|
||||
{errorMessage}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
disabled={isPending}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button type="submit" disabled={disableSubmit}>
|
||||
{isPending ? "Salvando..." : submitLabel}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
165
components/anotacoes/notes-page.tsx
Normal file
165
components/anotacoes/notes-page.tsx
Normal file
@@ -0,0 +1,165 @@
|
||||
"use client";
|
||||
|
||||
import { deleteNoteAction } from "@/app/(dashboard)/anotacoes/actions";
|
||||
import { ConfirmActionDialog } from "@/components/confirm-action-dialog";
|
||||
import { EmptyState } from "@/components/empty-state";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { RiAddCircleLine, RiFileListLine } from "@remixicon/react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Card } from "../ui/card";
|
||||
import { NoteCard } from "./note-card";
|
||||
import { NoteDetailsDialog } from "./note-details-dialog";
|
||||
import { NoteDialog } from "./note-dialog";
|
||||
import type { Note } from "./types";
|
||||
|
||||
interface NotesPageProps {
|
||||
notes: Note[];
|
||||
}
|
||||
|
||||
export function NotesPage({ notes }: NotesPageProps) {
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [noteToEdit, setNoteToEdit] = useState<Note | null>(null);
|
||||
const [detailsOpen, setDetailsOpen] = useState(false);
|
||||
const [noteDetails, setNoteDetails] = useState<Note | null>(null);
|
||||
const [removeOpen, setRemoveOpen] = useState(false);
|
||||
const [noteToRemove, setNoteToRemove] = useState<Note | null>(null);
|
||||
|
||||
const sortedNotes = useMemo(
|
||||
() =>
|
||||
[...notes].sort(
|
||||
(a, b) =>
|
||||
new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
|
||||
),
|
||||
[notes]
|
||||
);
|
||||
|
||||
const handleCreateOpenChange = useCallback((open: boolean) => {
|
||||
setCreateOpen(open);
|
||||
}, []);
|
||||
|
||||
const handleEditOpenChange = useCallback((open: boolean) => {
|
||||
setEditOpen(open);
|
||||
if (!open) {
|
||||
setNoteToEdit(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleDetailsOpenChange = useCallback((open: boolean) => {
|
||||
setDetailsOpen(open);
|
||||
if (!open) {
|
||||
setNoteDetails(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleRemoveOpenChange = useCallback((open: boolean) => {
|
||||
setRemoveOpen(open);
|
||||
if (!open) {
|
||||
setNoteToRemove(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleEditRequest = useCallback((note: Note) => {
|
||||
setNoteToEdit(note);
|
||||
setEditOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleDetailsRequest = useCallback((note: Note) => {
|
||||
setNoteDetails(note);
|
||||
setDetailsOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleRemoveRequest = useCallback((note: Note) => {
|
||||
setNoteToRemove(note);
|
||||
setRemoveOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleRemoveConfirm = useCallback(async () => {
|
||||
if (!noteToRemove) {
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await deleteNoteAction({ id: noteToRemove.id });
|
||||
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
return;
|
||||
}
|
||||
|
||||
toast.error(result.error);
|
||||
throw new Error(result.error);
|
||||
}, [noteToRemove]);
|
||||
|
||||
const removeTitle = noteToRemove
|
||||
? noteToRemove.title.trim().length
|
||||
? `Remover anotação "${noteToRemove.title}"?`
|
||||
: "Remover anotação?"
|
||||
: "Remover anotação?";
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex w-full flex-col gap-6">
|
||||
<div className="flex justify-start">
|
||||
<NoteDialog
|
||||
mode="create"
|
||||
open={createOpen}
|
||||
onOpenChange={handleCreateOpenChange}
|
||||
trigger={
|
||||
<Button>
|
||||
<RiAddCircleLine className="size-4" />
|
||||
Nova anotação
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{sortedNotes.length === 0 ? (
|
||||
<Card className="flex min-h-[50vh] w-full items-center justify-center py-12">
|
||||
<EmptyState
|
||||
media={<RiFileListLine className="size-6 text-primary" />}
|
||||
title="Nenhuma anotação registrada"
|
||||
description="Crie anotações personalizadas para acompanhar lembretes, decisões ou observações financeiras importantes."
|
||||
/>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-4">
|
||||
{sortedNotes.map((note) => (
|
||||
<NoteCard
|
||||
key={note.id}
|
||||
note={note}
|
||||
onEdit={handleEditRequest}
|
||||
onDetails={handleDetailsRequest}
|
||||
onRemove={handleRemoveRequest}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<NoteDialog
|
||||
mode="update"
|
||||
note={noteToEdit ?? undefined}
|
||||
open={editOpen}
|
||||
onOpenChange={handleEditOpenChange}
|
||||
/>
|
||||
|
||||
<NoteDetailsDialog
|
||||
note={noteDetails}
|
||||
open={detailsOpen}
|
||||
onOpenChange={handleDetailsOpenChange}
|
||||
/>
|
||||
|
||||
<ConfirmActionDialog
|
||||
open={removeOpen}
|
||||
onOpenChange={handleRemoveOpenChange}
|
||||
title={removeTitle}
|
||||
description="Essa ação não pode ser desfeita."
|
||||
confirmLabel="Remover"
|
||||
confirmVariant="destructive"
|
||||
pendingLabel="Removendo..."
|
||||
onConfirm={handleRemoveConfirm}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
23
components/anotacoes/types.ts
Normal file
23
components/anotacoes/types.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
export type NoteType = "nota" | "tarefa";
|
||||
|
||||
export interface Task {
|
||||
id: string;
|
||||
text: string;
|
||||
completed: boolean;
|
||||
}
|
||||
|
||||
export interface Note {
|
||||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
type: NoteType;
|
||||
tasks?: Task[];
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface NoteFormValues {
|
||||
title: string;
|
||||
description: string;
|
||||
type: NoteType;
|
||||
tasks?: Task[];
|
||||
}
|
||||
17
components/auth/auth-error-alert.tsx
Normal file
17
components/auth/auth-error-alert.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { RiTerminalLine } from "@remixicon/react";
|
||||
|
||||
interface AuthErrorAlertProps {
|
||||
error: string;
|
||||
}
|
||||
|
||||
export function AuthErrorAlert({ error }: AuthErrorAlertProps) {
|
||||
if (!error) return null;
|
||||
|
||||
return (
|
||||
<Alert className="mt-2 border border-red-500" variant="destructive">
|
||||
<RiTerminalLine className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
17
components/auth/auth-footer.tsx
Normal file
17
components/auth/auth-footer.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import { FieldDescription } from "@/components/ui/field";
|
||||
|
||||
export function AuthFooter() {
|
||||
return (
|
||||
<FieldDescription className="px-6 text-center">
|
||||
Ao continuar, você concorda com nossos{" "}
|
||||
<a href="/terms" className="underline underline-offset-4">
|
||||
Termos de Serviço
|
||||
</a>{" "}
|
||||
e{" "}
|
||||
<a href="/privacy" className="underline underline-offset-4">
|
||||
Política de Privacidade
|
||||
</a>
|
||||
.
|
||||
</FieldDescription>
|
||||
);
|
||||
}
|
||||
17
components/auth/auth-header.tsx
Normal file
17
components/auth/auth-header.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
|
||||
interface AuthHeaderProps {
|
||||
title: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export function AuthHeader({ title, description }: AuthHeaderProps) {
|
||||
return (
|
||||
<div className={cn("flex flex-col gap-1.5")}>
|
||||
<h1 className="text-xl font-semibold tracking-tight text-card-foreground">
|
||||
{title}
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground">{description}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
34
components/auth/auth-sidebar.tsx
Normal file
34
components/auth/auth-sidebar.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
import MagnetLines from "../magnet-lines";
|
||||
|
||||
function AuthSidebar() {
|
||||
return (
|
||||
<div className="relative hidden flex-col overflow-hidden bg-welcome-banner text-welcome-banner-foreground md:flex">
|
||||
<div className="absolute inset-0 flex items-center justify-center opacity-20 pointer-events-none">
|
||||
<MagnetLines
|
||||
rows={10}
|
||||
columns={16}
|
||||
containerSize="120%"
|
||||
lineColor="currentColor"
|
||||
lineWidth="0.35vmin"
|
||||
lineHeight="5vmin"
|
||||
baseAngle={-4}
|
||||
className="text-welcome-banner-foreground"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="relative flex flex-1 flex-col justify-between p-8">
|
||||
<div className="space-y-4">
|
||||
<h2 className="text-3xl font-semibold leading-tight">
|
||||
Controle suas finanças com clareza e foco diário.
|
||||
</h2>
|
||||
<p className="text-sm opacity-90">
|
||||
Centralize despesas, organize cartões e acompanhe metas mensais em
|
||||
um painel inteligente feito para o seu dia a dia.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default AuthSidebar;
|
||||
54
components/auth/google-auth-button.tsx
Normal file
54
components/auth/google-auth-button.tsx
Normal file
@@ -0,0 +1,54 @@
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { RiLoader4Line } from "@remixicon/react";
|
||||
|
||||
interface GoogleAuthButtonProps {
|
||||
onClick: () => void;
|
||||
loading?: boolean;
|
||||
disabled?: boolean;
|
||||
text?: string;
|
||||
}
|
||||
|
||||
export function GoogleAuthButton({
|
||||
onClick,
|
||||
loading = false,
|
||||
disabled = false,
|
||||
text = "Continuar com Google",
|
||||
}: GoogleAuthButtonProps) {
|
||||
return (
|
||||
<Button
|
||||
variant="outline"
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
disabled={disabled || loading}
|
||||
className="w-full gap-2"
|
||||
>
|
||||
{loading ? (
|
||||
<RiLoader4Line className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
className="h-5 w-5"
|
||||
>
|
||||
<path
|
||||
d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
|
||||
fill="#4285F4"
|
||||
/>
|
||||
<path
|
||||
d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
|
||||
fill="#34A853"
|
||||
/>
|
||||
<path
|
||||
d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
|
||||
fill="#FBBC05"
|
||||
/>
|
||||
<path
|
||||
d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
|
||||
fill="#EA4335"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
<span>{text}</span>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
187
components/auth/login-form.tsx
Normal file
187
components/auth/login-form.tsx
Normal file
@@ -0,0 +1,187 @@
|
||||
"use client";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import {
|
||||
Field,
|
||||
FieldDescription,
|
||||
FieldGroup,
|
||||
FieldLabel,
|
||||
FieldSeparator,
|
||||
} from "@/components/ui/field";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { authClient, googleSignInAvailable } from "@/lib/auth/client";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import { RiLoader4Line } from "@remixicon/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Logo } from "../logo";
|
||||
import { AuthErrorAlert } from "./auth-error-alert";
|
||||
import { AuthHeader } from "./auth-header";
|
||||
import AuthSidebar from "./auth-sidebar";
|
||||
import { GoogleAuthButton } from "./google-auth-button";
|
||||
|
||||
type DivProps = React.ComponentProps<"div">;
|
||||
|
||||
export function LoginForm({ className, ...props }: DivProps) {
|
||||
const router = useRouter();
|
||||
const isGoogleAvailable = googleSignInAvailable;
|
||||
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
|
||||
const [error, setError] = useState("");
|
||||
const [loadingEmail, setLoadingEmail] = useState(false);
|
||||
const [loadingGoogle, setLoadingGoogle] = useState(false);
|
||||
|
||||
async function handleSubmit(e: FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
|
||||
await authClient.signIn.email(
|
||||
{
|
||||
email,
|
||||
password,
|
||||
callbackURL: "/dashboard",
|
||||
rememberMe: false,
|
||||
},
|
||||
{
|
||||
onRequest: () => {
|
||||
setError("");
|
||||
setLoadingEmail(true);
|
||||
},
|
||||
onSuccess: () => {
|
||||
setLoadingEmail(false);
|
||||
toast.success("Login realizado com sucesso!");
|
||||
router.replace("/dashboard");
|
||||
},
|
||||
onError: (ctx) => {
|
||||
setError(ctx.error.message);
|
||||
setLoadingEmail(false);
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
async function handleGoogle() {
|
||||
if (!isGoogleAvailable) {
|
||||
setError("Login com Google não está disponível no momento.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Ativa loading antes de iniciar o fluxo OAuth
|
||||
setError("");
|
||||
setLoadingGoogle(true);
|
||||
|
||||
// OAuth redirect - o loading permanece até a página ser redirecionada
|
||||
await authClient.signIn.social(
|
||||
{
|
||||
provider: "google",
|
||||
callbackURL: "/dashboard",
|
||||
},
|
||||
{
|
||||
onError: (ctx) => {
|
||||
// Só desativa loading se houver erro
|
||||
setError(ctx.error.message);
|
||||
setLoadingGoogle(false);
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn("flex flex-col gap-6", className)} {...props}>
|
||||
<Logo className="mb-2" />
|
||||
<Card className="overflow-hidden p-0">
|
||||
<CardContent className="grid gap-0 p-0 md:grid-cols-[1.05fr_0.95fr]">
|
||||
<form
|
||||
className="flex flex-col gap-6 p-6 md:p-8"
|
||||
onSubmit={handleSubmit}
|
||||
noValidate
|
||||
>
|
||||
<FieldGroup className="gap-4">
|
||||
<AuthHeader
|
||||
title="Entrar no OpenSheets"
|
||||
description="Entre com a sua conta"
|
||||
/>
|
||||
|
||||
<AuthErrorAlert error={error} />
|
||||
|
||||
<Field>
|
||||
<FieldLabel htmlFor="email">E-mail</FieldLabel>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="Digite seu e-mail"
|
||||
autoComplete="email"
|
||||
required
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
aria-invalid={!!error}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<div className="flex items-center">
|
||||
<FieldLabel htmlFor="password">Senha</FieldLabel>
|
||||
</div>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
required
|
||||
placeholder="Digite sua senha"
|
||||
autoComplete="current-password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
aria-invalid={!!error}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={loadingEmail || loadingGoogle}
|
||||
className="w-full"
|
||||
>
|
||||
{loadingEmail ? (
|
||||
<RiLoader4Line className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
"Entrar"
|
||||
)}
|
||||
</Button>
|
||||
</Field>
|
||||
|
||||
<FieldSeparator className="my-2 *:data-[slot=field-separator-content]:bg-card">
|
||||
Ou continue com
|
||||
</FieldSeparator>
|
||||
|
||||
<Field>
|
||||
<GoogleAuthButton
|
||||
onClick={handleGoogle}
|
||||
loading={loadingGoogle}
|
||||
disabled={loadingEmail || loadingGoogle || !isGoogleAvailable}
|
||||
text="Entrar com Google"
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<FieldDescription className="text-center">
|
||||
Não tem uma conta?{" "}
|
||||
<a href="/signup" className="underline underline-offset-4">
|
||||
Inscreva-se
|
||||
</a>
|
||||
</FieldDescription>
|
||||
</FieldGroup>
|
||||
</form>
|
||||
|
||||
<AuthSidebar />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* <AuthFooter /> */}
|
||||
<FieldDescription className="text-center">
|
||||
<a href="/" className="underline underline-offset-4">
|
||||
Voltar para o site
|
||||
</a>
|
||||
</FieldDescription>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
56
components/auth/logout-button.tsx
Normal file
56
components/auth/logout-button.tsx
Normal file
@@ -0,0 +1,56 @@
|
||||
"use client";
|
||||
import { useState } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import { authClient } from "@/lib/auth/client";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Spinner } from "../ui/spinner";
|
||||
|
||||
export default function LogoutButton() {
|
||||
const router = useRouter();
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
async function handleLogOut() {
|
||||
await authClient.signOut({
|
||||
fetchOptions: {
|
||||
onSuccess: () => {
|
||||
router.push("/login");
|
||||
},
|
||||
onRequest: (_ctx) => {
|
||||
setLoading(true);
|
||||
},
|
||||
onResponse: (_ctx) => {
|
||||
setLoading(false);
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="link"
|
||||
size="sm"
|
||||
aria-busy={loading}
|
||||
data-loading={loading}
|
||||
onClick={handleLogOut}
|
||||
disabled={loading}
|
||||
className="text-destructive transition-all duration-200 border hover:text-destructive focus-visible:ring-destructive/30 data-[loading=true]:opacity-90"
|
||||
>
|
||||
{loading && <Spinner className="size-3.5 text-destructive" />}
|
||||
<span aria-live="polite">{loading ? "Saindo" : "Sair"}</span>
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom" sideOffset={8}>
|
||||
Encerrar sessão
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
199
components/auth/signup-form.tsx
Normal file
199
components/auth/signup-form.tsx
Normal file
@@ -0,0 +1,199 @@
|
||||
"use client";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import {
|
||||
Field,
|
||||
FieldDescription,
|
||||
FieldGroup,
|
||||
FieldLabel,
|
||||
FieldSeparator,
|
||||
} from "@/components/ui/field";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { authClient, googleSignInAvailable } from "@/lib/auth/client";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import { RiLoader4Line } from "@remixicon/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Logo } from "../logo";
|
||||
import { AuthErrorAlert } from "./auth-error-alert";
|
||||
import { AuthHeader } from "./auth-header";
|
||||
import AuthSidebar from "./auth-sidebar";
|
||||
import { GoogleAuthButton } from "./google-auth-button";
|
||||
|
||||
type DivProps = React.ComponentProps<"div">;
|
||||
|
||||
export function SignupForm({ className, ...props }: DivProps) {
|
||||
const router = useRouter();
|
||||
const isGoogleAvailable = googleSignInAvailable;
|
||||
|
||||
const [fullname, setFullname] = useState("");
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
|
||||
const [error, setError] = useState("");
|
||||
const [loadingEmail, setLoadingEmail] = useState(false);
|
||||
const [loadingGoogle, setLoadingGoogle] = useState(false);
|
||||
|
||||
async function handleSubmit(e: FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
|
||||
await authClient.signUp.email(
|
||||
{
|
||||
email,
|
||||
password,
|
||||
name: fullname,
|
||||
},
|
||||
{
|
||||
onRequest: () => {
|
||||
setError("");
|
||||
setLoadingEmail(true);
|
||||
},
|
||||
onSuccess: () => {
|
||||
setLoadingEmail(false);
|
||||
toast.success("Conta criada com sucesso!");
|
||||
router.replace("/dashboard");
|
||||
},
|
||||
onError: (ctx) => {
|
||||
setError(ctx.error.message);
|
||||
setLoadingEmail(false);
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
async function handleGoogle() {
|
||||
if (!isGoogleAvailable) {
|
||||
setError("Login com Google não está disponível no momento.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Ativa loading antes de iniciar o fluxo OAuth
|
||||
setError("");
|
||||
setLoadingGoogle(true);
|
||||
|
||||
// OAuth redirect - o loading permanece até a página ser redirecionada
|
||||
await authClient.signIn.social(
|
||||
{
|
||||
provider: "google",
|
||||
callbackURL: "/dashboard",
|
||||
},
|
||||
{
|
||||
onError: (ctx) => {
|
||||
// Só desativa loading se houver erro
|
||||
setError(ctx.error.message);
|
||||
setLoadingGoogle(false);
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn("flex flex-col gap-6", className)} {...props}>
|
||||
<Logo className="mb-2" />
|
||||
<Card className="overflow-hidden p-0">
|
||||
<CardContent className="grid gap-0 p-0 md:grid-cols-[1.05fr_0.95fr]">
|
||||
<form
|
||||
className="flex flex-col gap-6 p-6 md:p-8"
|
||||
onSubmit={handleSubmit}
|
||||
noValidate
|
||||
>
|
||||
<FieldGroup className="gap-4">
|
||||
<AuthHeader
|
||||
title="Criar sua conta"
|
||||
description="Comece com sua nova conta"
|
||||
/>
|
||||
|
||||
<AuthErrorAlert error={error} />
|
||||
|
||||
<Field>
|
||||
<FieldLabel htmlFor="name">Nome completo</FieldLabel>
|
||||
<Input
|
||||
id="name"
|
||||
type="text"
|
||||
placeholder="Digite seu nome"
|
||||
autoComplete="name"
|
||||
required
|
||||
value={fullname}
|
||||
onChange={(e) => setFullname(e.target.value)}
|
||||
aria-invalid={!!error}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel htmlFor="email">E-mail</FieldLabel>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="Digite seu e-mail"
|
||||
autoComplete="email"
|
||||
required
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
aria-invalid={!!error}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel htmlFor="password">Senha</FieldLabel>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
required
|
||||
autoComplete="new-password"
|
||||
placeholder="Crie uma senha forte"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
aria-invalid={!!error}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={loadingEmail || loadingGoogle}
|
||||
className="w-full"
|
||||
>
|
||||
{loadingEmail ? (
|
||||
<RiLoader4Line className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
"Criar conta"
|
||||
)}
|
||||
</Button>
|
||||
</Field>
|
||||
|
||||
<FieldSeparator className="my-2 *:data-[slot=field-separator-content]:bg-card">
|
||||
Ou continue com
|
||||
</FieldSeparator>
|
||||
|
||||
<Field>
|
||||
<GoogleAuthButton
|
||||
onClick={handleGoogle}
|
||||
loading={loadingGoogle}
|
||||
disabled={loadingEmail || loadingGoogle || !isGoogleAvailable}
|
||||
text="Continuar com Google"
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<FieldDescription className="text-center">
|
||||
Já tem uma conta?{" "}
|
||||
<a href="/login" className="underline underline-offset-4">
|
||||
Entrar
|
||||
</a>
|
||||
</FieldDescription>
|
||||
</FieldGroup>
|
||||
</form>
|
||||
|
||||
<AuthSidebar />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* <AuthFooter /> */}
|
||||
<FieldDescription className="text-center">
|
||||
<a href="/" className="underline underline-offset-4">
|
||||
Voltar para o site
|
||||
</a>
|
||||
</FieldDescription>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
109
components/calculadora/calculator-dialog.tsx
Normal file
109
components/calculadora/calculator-dialog.tsx
Normal file
@@ -0,0 +1,109 @@
|
||||
"use client";
|
||||
|
||||
import Calculator from "@/components/calculadora/calculator";
|
||||
import { Button, buttonVariants } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import { RiCalculatorFill, RiCalculatorLine } from "@remixicon/react";
|
||||
import * as React from "react";
|
||||
|
||||
type Variant = React.ComponentProps<typeof Button>["variant"];
|
||||
type Size = React.ComponentProps<typeof Button>["size"];
|
||||
|
||||
type CalculatorDialogButtonProps = {
|
||||
variant?: Variant;
|
||||
size?: Size;
|
||||
className?: string;
|
||||
children?: React.ReactNode;
|
||||
withTooltip?: boolean;
|
||||
};
|
||||
|
||||
export function CalculatorDialogButton({
|
||||
variant = "ghost",
|
||||
size = "sm",
|
||||
className,
|
||||
children,
|
||||
withTooltip = false,
|
||||
}: CalculatorDialogButtonProps) {
|
||||
const [open, setOpen] = React.useState(false);
|
||||
|
||||
// Se withTooltip for true, usa o estilo do header
|
||||
if (withTooltip) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<DialogTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Calculadora"
|
||||
aria-expanded={open}
|
||||
data-state={open ? "open" : "closed"}
|
||||
className={cn(
|
||||
buttonVariants({ variant: "ghost", size: "icon-sm" }),
|
||||
"group relative text-muted-foreground transition-all duration-200",
|
||||
"hover:text-foreground focus-visible:ring-2 focus-visible:ring-primary/40",
|
||||
"data-[state=open]:bg-accent/60 data-[state=open]:text-foreground border",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<RiCalculatorLine
|
||||
className={cn(
|
||||
"size-4 transition-transform duration-200",
|
||||
open ? "scale-90" : "scale-100"
|
||||
)}
|
||||
/>
|
||||
<span className="sr-only">Calculadora</span>
|
||||
</button>
|
||||
</DialogTrigger>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom" sideOffset={8}>
|
||||
Calculadora
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
<DialogContent className="p-4 sm:max-w-sm">
|
||||
<DialogHeader className="space-y-2">
|
||||
<DialogTitle className="flex items-center gap-2 text-lg">
|
||||
<RiCalculatorLine className="h-5 w-5" />
|
||||
Calculadora
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Calculator />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
// Estilo padrão para outros usos
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant={variant} size={size} className={cn(className)}>
|
||||
{children ?? (
|
||||
<RiCalculatorFill className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="p-4 sm:max-w-sm">
|
||||
<DialogHeader className="space-y-2">
|
||||
<DialogTitle className="flex items-center gap-2 text-lg">
|
||||
<RiCalculatorLine className="h-5 w-5" />
|
||||
Calculadora
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Calculator />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
49
components/calculadora/calculator-display.tsx
Normal file
49
components/calculadora/calculator-display.tsx
Normal file
@@ -0,0 +1,49 @@
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { RiCheckLine, RiFileCopyLine } from "@remixicon/react";
|
||||
|
||||
export type CalculatorDisplayProps = {
|
||||
history: string | null;
|
||||
expression: string;
|
||||
resultText: string | null;
|
||||
copied: boolean;
|
||||
onCopy: () => void;
|
||||
};
|
||||
|
||||
export function CalculatorDisplay({
|
||||
history,
|
||||
expression,
|
||||
resultText,
|
||||
copied,
|
||||
onCopy,
|
||||
}: CalculatorDisplayProps) {
|
||||
return (
|
||||
<div className="rounded-xl border bg-muted px-4 py-5 text-right">
|
||||
{history && (
|
||||
<div className="text-sm text-muted-foreground">{history}</div>
|
||||
)}
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<div className="text-right text-3xl font-semibold tracking-tight tabular-nums">
|
||||
{expression}
|
||||
</div>
|
||||
{resultText && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={onCopy}
|
||||
className="h-6 w-6 shrink-0 rounded-full p-0 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{copied ? (
|
||||
<RiCheckLine className="h-4 w-4" />
|
||||
) : (
|
||||
<RiFileCopyLine className="h-4 w-4" />
|
||||
)}
|
||||
<span className="sr-only">
|
||||
{copied ? "Resultado copiado" : "Copiar resultado"}
|
||||
</span>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
29
components/calculadora/calculator-keypad.tsx
Normal file
29
components/calculadora/calculator-keypad.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import { type CalculatorButtonConfig } from "@/hooks/use-calculator-state";
|
||||
|
||||
type CalculatorKeypadProps = {
|
||||
buttons: CalculatorButtonConfig[][];
|
||||
};
|
||||
|
||||
export function CalculatorKeypad({ buttons }: CalculatorKeypadProps) {
|
||||
return (
|
||||
<div className="grid grid-cols-4 gap-2">
|
||||
{buttons.flat().map((btn, index) => (
|
||||
<Button
|
||||
key={`${btn.label}-${index}`}
|
||||
type="button"
|
||||
variant={btn.variant ?? "outline"}
|
||||
onClick={btn.onClick}
|
||||
className={cn(
|
||||
"h-12 text-base font-semibold",
|
||||
btn.colSpan === 2 && "col-span-2",
|
||||
btn.colSpan === 3 && "col-span-3",
|
||||
)}
|
||||
>
|
||||
{btn.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
37
components/calculadora/calculator.tsx
Normal file
37
components/calculadora/calculator.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
"use client";
|
||||
|
||||
import { CalculatorKeypad } from "@/components/calculadora/calculator-keypad";
|
||||
import { useCalculatorKeyboard } from "@/hooks/use-calculator-keyboard";
|
||||
import { useCalculatorState } from "@/hooks/use-calculator-state";
|
||||
import { CalculatorDisplay } from "./calculator-display";
|
||||
|
||||
export default function Calculator() {
|
||||
const {
|
||||
expression,
|
||||
history,
|
||||
resultText,
|
||||
copied,
|
||||
buttons,
|
||||
copyToClipboard,
|
||||
pasteFromClipboard,
|
||||
} = useCalculatorState();
|
||||
|
||||
useCalculatorKeyboard({
|
||||
canCopy: Boolean(resultText),
|
||||
onCopy: copyToClipboard,
|
||||
onPaste: pasteFromClipboard,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<CalculatorDisplay
|
||||
history={history}
|
||||
expression={expression}
|
||||
resultText={resultText}
|
||||
copied={copied}
|
||||
onCopy={copyToClipboard}
|
||||
/>
|
||||
<CalculatorKeypad buttons={buttons} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
42
components/calendario/calendar-grid.tsx
Normal file
42
components/calendario/calendar-grid.tsx
Normal file
@@ -0,0 +1,42 @@
|
||||
"use client";
|
||||
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
|
||||
import type { CalendarDay } from "@/components/calendario/types";
|
||||
import { WEEK_DAYS_SHORT } from "@/components/calendario/utils";
|
||||
import { DayCell } from "@/components/calendario/day-cell";
|
||||
|
||||
type CalendarGridProps = {
|
||||
days: CalendarDay[];
|
||||
onSelectDay: (day: CalendarDay) => void;
|
||||
onCreateDay: (day: CalendarDay) => void;
|
||||
};
|
||||
|
||||
export function CalendarGrid({
|
||||
days,
|
||||
onSelectDay,
|
||||
onCreateDay,
|
||||
}: CalendarGridProps) {
|
||||
return (
|
||||
<div className="overflow-hidden rounded-lg bg-card drop-shadow-xs px-2">
|
||||
<div className="grid grid-cols-7 text-sm font-semibold uppercase tracking-wide text-muted-foreground">
|
||||
{WEEK_DAYS_SHORT.map((dayName) => (
|
||||
<span key={dayName} className="px-3 py-2 text-center">
|
||||
{dayName}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-7 gap-px bg-border/60 px-px pb-px pt-px">
|
||||
{days.map((day) => (
|
||||
<div
|
||||
key={day.date}
|
||||
className={cn("h-[150px] bg-card p-0.5", !day.isCurrentMonth && "")}
|
||||
>
|
||||
<DayCell day={day} onSelect={onSelectDay} onCreate={onCreateDay} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
36
components/calendario/calendar-legend.tsx
Normal file
36
components/calendario/calendar-legend.tsx
Normal file
@@ -0,0 +1,36 @@
|
||||
"use client";
|
||||
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
|
||||
import type { CalendarEvent } from "@/components/calendario/types";
|
||||
import { EVENT_TYPE_STYLES } from "@/components/calendario/day-cell";
|
||||
|
||||
const LEGEND_ITEMS: Array<{
|
||||
type: CalendarEvent["type"];
|
||||
label: string;
|
||||
}> = [
|
||||
{ type: "lancamento", label: "Lançamento financeiro" },
|
||||
{ type: "boleto", label: "Boleto com vencimento" },
|
||||
{ type: "cartao", label: "Vencimento de cartão" },
|
||||
];
|
||||
|
||||
export function CalendarLegend() {
|
||||
return (
|
||||
<div className="flex flex-wrap gap-3 rounded-lg border border-border/60 bg-muted/20 px-3 py-2 text-[11px] font-medium text-muted-foreground">
|
||||
{LEGEND_ITEMS.map((item) => {
|
||||
const style = EVENT_TYPE_STYLES[item.type];
|
||||
return (
|
||||
<span key={item.type} className="flex items-center gap-2">
|
||||
<span
|
||||
className={cn(
|
||||
"size-2.5 rounded-full border border-black/10 dark:border-white/20",
|
||||
style.dot
|
||||
)}
|
||||
/>
|
||||
{item.label}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
165
components/calendario/day-cell.tsx
Normal file
165
components/calendario/day-cell.tsx
Normal file
@@ -0,0 +1,165 @@
|
||||
"use client";
|
||||
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import { RiAddLine } from "@remixicon/react";
|
||||
import type { KeyboardEvent, MouseEvent } from "react";
|
||||
import type { CalendarDay, CalendarEvent } from "@/components/calendario/types";
|
||||
import { currencyFormatter } from "@/lib/lancamentos/formatting-helpers";
|
||||
|
||||
type DayCellProps = {
|
||||
day: CalendarDay;
|
||||
onSelect: (day: CalendarDay) => void;
|
||||
onCreate: (day: CalendarDay) => void;
|
||||
};
|
||||
|
||||
export const EVENT_TYPE_STYLES: Record<
|
||||
CalendarEvent["type"],
|
||||
{ wrapper: string; dot: string; accent?: string }
|
||||
> = {
|
||||
lancamento: {
|
||||
wrapper: "bg-cyan-600 text-cyan-50 dark:bg-cyan-500/30 dark:text-cyan-200",
|
||||
dot: "bg-cyan-600",
|
||||
},
|
||||
boleto: {
|
||||
wrapper: "bg-red-600 text-red-50 dark:bg-red-500/30 dark:text-red-200",
|
||||
dot: "bg-red-600",
|
||||
},
|
||||
cartao: {
|
||||
wrapper:
|
||||
"bg-violet-600 text-violet-50 dark:bg-violet-500/30 dark:text-violet-200",
|
||||
dot: "bg-violet-600",
|
||||
},
|
||||
};
|
||||
|
||||
const eventStyles = EVENT_TYPE_STYLES;
|
||||
|
||||
const formatCurrencyValue = (value: number | null | undefined) =>
|
||||
currencyFormatter.format(Math.abs(value ?? 0));
|
||||
|
||||
const formatAmount = (event: Extract<CalendarEvent, { type: "lancamento" }>) =>
|
||||
formatCurrencyValue(event.lancamento.amount);
|
||||
|
||||
const buildEventLabel = (event: CalendarEvent) => {
|
||||
switch (event.type) {
|
||||
case "lancamento": {
|
||||
return event.lancamento.name;
|
||||
}
|
||||
case "boleto": {
|
||||
return event.lancamento.name;
|
||||
}
|
||||
case "cartao": {
|
||||
return event.card.name;
|
||||
}
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
const buildEventComplement = (event: CalendarEvent) => {
|
||||
switch (event.type) {
|
||||
case "lancamento": {
|
||||
return formatAmount(event);
|
||||
}
|
||||
case "boleto": {
|
||||
return formatCurrencyValue(event.lancamento.amount);
|
||||
}
|
||||
case "cartao": {
|
||||
if (event.card.totalDue !== null) {
|
||||
return formatCurrencyValue(event.card.totalDue);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const DayEventPreview = ({ event }: { event: CalendarEvent }) => {
|
||||
const complement = buildEventComplement(event);
|
||||
const label = buildEventLabel(event);
|
||||
const style = eventStyles[event.type];
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex w-full items-center justify-between gap-2 rounded p-1 text-xs leading-tight",
|
||||
style.wrapper
|
||||
)}
|
||||
>
|
||||
<div className="flex min-w-0">
|
||||
<span className="truncate">{label}</span>
|
||||
</div>
|
||||
{complement ? (
|
||||
<span
|
||||
className={cn("shrink-0 font-semibold", style.accent ?? "text-xs")}
|
||||
>
|
||||
{complement}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export function DayCell({ day, onSelect, onCreate }: DayCellProps) {
|
||||
const previewEvents = day.events.slice(0, 3);
|
||||
const hasOverflow = day.events.length > 3;
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
|
||||
if (event.key === "Enter" || event.key === " " || event.key === "Space") {
|
||||
event.preventDefault();
|
||||
onSelect(day);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateClick = (event: MouseEvent<HTMLButtonElement>) => {
|
||||
event.stopPropagation();
|
||||
onCreate(day);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => onSelect(day)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className={cn(
|
||||
"flex h-full cursor-pointer flex-col gap-1.5 rounded-lg border border-transparent bg-card/80 p-2 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 hover:border-primary/40 hover:bg-primary/5 dark:hover:bg-primary/10",
|
||||
!day.isCurrentMonth && "opacity-60",
|
||||
day.isToday && "border-primary/70 bg-primary/5 hover:border-primary"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<span
|
||||
className={cn(
|
||||
"text-sm font-semibold leading-none",
|
||||
day.isToday
|
||||
? "text-orange-100 bg-primary size-5 rounded-full flex items-center justify-center"
|
||||
: "text-foreground/90"
|
||||
)}
|
||||
>
|
||||
{day.label}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCreateClick}
|
||||
className="flex size-6 items-center justify-center rounded-full border bg-muted text-muted-foreground transition-colors hover:bg-primary/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-1"
|
||||
aria-label={`Criar lançamento em ${day.date}`}
|
||||
>
|
||||
<RiAddLine className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-1 flex-col gap-1.5">
|
||||
{previewEvents.map((event) => (
|
||||
<DayEventPreview key={event.id} event={event} />
|
||||
))}
|
||||
|
||||
{hasOverflow ? (
|
||||
<span className="text-xs font-medium text-primary/80">
|
||||
+ ver mais
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
229
components/calendario/event-modal.tsx
Normal file
229
components/calendario/event-modal.tsx
Normal file
@@ -0,0 +1,229 @@
|
||||
"use client";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import { useMemo, type ReactNode } from "react";
|
||||
import type { CalendarDay, CalendarEvent } from "@/components/calendario/types";
|
||||
import { parseDateKey } from "@/components/calendario/utils";
|
||||
import { EVENT_TYPE_STYLES } from "@/components/calendario/day-cell";
|
||||
import { currencyFormatter } from "@/lib/lancamentos/formatting-helpers";
|
||||
|
||||
type EventModalProps = {
|
||||
open: boolean;
|
||||
day: CalendarDay | null;
|
||||
onClose: () => void;
|
||||
onCreate: (date: string) => void;
|
||||
};
|
||||
|
||||
const fullDateFormatter = new Intl.DateTimeFormat("pt-BR", {
|
||||
day: "numeric",
|
||||
month: "long",
|
||||
year: "numeric",
|
||||
});
|
||||
|
||||
const capitalize = (value: string) =>
|
||||
value.length > 0 ? value[0]?.toUpperCase().concat(value.slice(1)) : value;
|
||||
|
||||
const formatCurrency = (value: number, isReceita: boolean) => {
|
||||
const formatted = currencyFormatter.format(value ?? 0);
|
||||
return isReceita ? `+${formatted}` : formatted;
|
||||
};
|
||||
|
||||
const EventCard = ({
|
||||
children,
|
||||
type,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
type: CalendarEvent["type"];
|
||||
}) => {
|
||||
const style = EVENT_TYPE_STYLES[type];
|
||||
return (
|
||||
<div className="flex gap-3 rounded-xl border border-border/60 bg-card/85 p-4">
|
||||
<span
|
||||
className={cn("mt-1 size-2.5 shrink-0 rounded-full", style.dot)}
|
||||
aria-hidden
|
||||
/>
|
||||
<div className="flex flex-1 flex-col gap-2">{children}</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const renderLancamento = (
|
||||
event: Extract<CalendarEvent, { type: "lancamento" }>
|
||||
) => {
|
||||
const isReceita = event.lancamento.transactionType === "Receita";
|
||||
const subtitleParts = [
|
||||
event.lancamento.categoriaName,
|
||||
event.lancamento.paymentMethod,
|
||||
event.lancamento.pagadorName,
|
||||
].filter(Boolean);
|
||||
|
||||
return (
|
||||
<EventCard type="lancamento">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex flex-col">
|
||||
<span className="text-sm font-semibold">{event.lancamento.name}</span>
|
||||
{subtitleParts.length ? (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{subtitleParts.join(" • ")}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<span
|
||||
className={cn(
|
||||
"text-sm font-semibold",
|
||||
isReceita ? "text-emerald-600" : "text-foreground"
|
||||
)}
|
||||
>
|
||||
{formatCurrency(event.lancamento.amount, isReceita)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2 text-[11px] font-medium text-muted-foreground">
|
||||
<span className="rounded-full bg-muted px-2 py-0.5">
|
||||
{capitalize(event.lancamento.transactionType)}
|
||||
</span>
|
||||
<span className="rounded-full bg-muted px-2 py-0.5">
|
||||
{event.lancamento.condition}
|
||||
</span>
|
||||
<span className="rounded-full bg-muted px-2 py-0.5">
|
||||
{event.lancamento.paymentMethod}
|
||||
</span>
|
||||
</div>
|
||||
</EventCard>
|
||||
);
|
||||
};
|
||||
|
||||
const renderBoleto = (event: Extract<CalendarEvent, { type: "boleto" }>) => {
|
||||
const isPaid = Boolean(event.lancamento.isSettled);
|
||||
const dueDate = event.lancamento.dueDate;
|
||||
const formattedDueDate = dueDate
|
||||
? new Intl.DateTimeFormat("pt-BR").format(new Date(dueDate))
|
||||
: null;
|
||||
|
||||
return (
|
||||
<EventCard type="boleto">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex flex-col">
|
||||
<span className="text-sm font-semibold">{event.lancamento.name}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Boleto{formattedDueDate ? ` • Vence em ${formattedDueDate}` : ""}
|
||||
</span>
|
||||
</div>
|
||||
<span className="text-sm font-semibold text-foreground">
|
||||
{currencyFormatter.format(event.lancamento.amount ?? 0)}
|
||||
</span>
|
||||
</div>
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex w-fit items-center rounded-full px-2.5 py-0.5 text-[11px] font-semibold uppercase tracking-wide",
|
||||
isPaid
|
||||
? "bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-200"
|
||||
: "bg-amber-100 text-amber-700 dark:bg-amber-500/20 dark:text-amber-200"
|
||||
)}
|
||||
>
|
||||
{isPaid ? "Pago" : "Pendente"}
|
||||
</span>
|
||||
</EventCard>
|
||||
);
|
||||
};
|
||||
|
||||
const renderCard = (event: Extract<CalendarEvent, { type: "cartao" }>) => (
|
||||
<EventCard type="cartao">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex flex-col">
|
||||
<span className="text-sm font-semibold">Cartão {event.card.name}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Vencimento dia {event.card.dueDay}
|
||||
</span>
|
||||
</div>
|
||||
{event.card.totalDue !== null ? (
|
||||
<span className="text-sm font-semibold text-foreground">
|
||||
{currencyFormatter.format(event.card.totalDue)}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2 text-[11px] font-medium text-muted-foreground">
|
||||
<span className="rounded-full bg-muted px-2 py-0.5">
|
||||
Status: {event.card.status ?? "Indefinido"}
|
||||
</span>
|
||||
{event.card.closingDay ? (
|
||||
<span className="rounded-full bg-muted px-2 py-0.5">
|
||||
Fechamento dia {event.card.closingDay}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</EventCard>
|
||||
);
|
||||
|
||||
const renderEvent = (event: CalendarEvent) => {
|
||||
switch (event.type) {
|
||||
case "lancamento":
|
||||
return renderLancamento(event);
|
||||
case "boleto":
|
||||
return renderBoleto(event);
|
||||
case "cartao":
|
||||
return renderCard(event);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export function EventModal({ open, day, onClose, onCreate }: EventModalProps) {
|
||||
const formattedDate = useMemo(() => {
|
||||
if (!day) return "";
|
||||
const parsed = parseDateKey(day.date);
|
||||
return capitalize(fullDateFormatter.format(parsed));
|
||||
}, [day]);
|
||||
|
||||
const handleCreate = () => {
|
||||
if (!day) return;
|
||||
onClose();
|
||||
onCreate(day.date);
|
||||
};
|
||||
|
||||
const description = day?.events.length
|
||||
? "Confira os lançamentos e vencimentos cadastrados para este dia."
|
||||
: "Nenhum lançamento encontrado para este dia. Você pode criar um novo lançamento agora.";
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(value) => (!value ? onClose() : null)}>
|
||||
<DialogContent className="max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{formattedDate}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="max-h-[380px] space-y-3 overflow-y-auto pr-2">
|
||||
{day?.events.length ? (
|
||||
day.events.map((event) => (
|
||||
<div key={event.id}>{renderEvent(event)}</div>
|
||||
))
|
||||
) : (
|
||||
<div className="rounded-xl border border-dashed border-border/60 bg-muted/30 p-6 text-center text-sm text-muted-foreground">
|
||||
Nenhum lançamento ou vencimento registrado. Clique em{" "}
|
||||
<span className="font-medium text-primary">Novo lançamento</span>{" "}
|
||||
para começar.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter className="flex justify-end gap-2">
|
||||
<Button variant="outline" onClick={onClose}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button onClick={handleCreate} disabled={!day}>
|
||||
Novo lançamento
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
126
components/calendario/monthly-calendar.tsx
Normal file
126
components/calendario/monthly-calendar.tsx
Normal file
@@ -0,0 +1,126 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import { LancamentoDialog } from "@/components/lancamentos/dialogs/lancamento-dialog/lancamento-dialog";
|
||||
|
||||
import type {
|
||||
CalendarDay,
|
||||
CalendarEvent,
|
||||
CalendarFormOptions,
|
||||
CalendarPeriod,
|
||||
} from "@/components/calendario/types";
|
||||
import { buildCalendarDays } from "@/components/calendario/utils";
|
||||
import { CalendarGrid } from "@/components/calendario/calendar-grid";
|
||||
import { CalendarLegend } from "@/components/calendario/calendar-legend";
|
||||
import { EventModal } from "@/components/calendario/event-modal";
|
||||
|
||||
type MonthlyCalendarProps = {
|
||||
period: CalendarPeriod;
|
||||
events: CalendarEvent[];
|
||||
formOptions: CalendarFormOptions;
|
||||
};
|
||||
|
||||
const parsePeriod = (period: string) => {
|
||||
const [yearStr, monthStr] = period.split("-");
|
||||
const year = Number.parseInt(yearStr ?? "", 10);
|
||||
const month = Number.parseInt(monthStr ?? "", 10);
|
||||
|
||||
return { year, monthIndex: month - 1 };
|
||||
};
|
||||
|
||||
export function MonthlyCalendar({
|
||||
period,
|
||||
events,
|
||||
formOptions,
|
||||
}: MonthlyCalendarProps) {
|
||||
const { year, monthIndex } = useMemo(
|
||||
() => parsePeriod(period.period),
|
||||
[period.period]
|
||||
);
|
||||
|
||||
const eventsByDay = useMemo(() => {
|
||||
const map = new Map<string, CalendarEvent[]>();
|
||||
events.forEach((event) => {
|
||||
const list = map.get(event.date) ?? [];
|
||||
list.push(event);
|
||||
map.set(event.date, list);
|
||||
});
|
||||
return map;
|
||||
}, [events]);
|
||||
|
||||
const days = useMemo(
|
||||
() => buildCalendarDays({ year, monthIndex, events: eventsByDay }),
|
||||
[eventsByDay, monthIndex, year]
|
||||
);
|
||||
|
||||
const [selectedDay, setSelectedDay] = useState<CalendarDay | null>(null);
|
||||
const [isModalOpen, setModalOpen] = useState(false);
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [createDate, setCreateDate] = useState<string | null>(null);
|
||||
|
||||
const handleOpenCreate = useCallback((date: string) => {
|
||||
setCreateDate(date);
|
||||
setModalOpen(false);
|
||||
setCreateOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleDaySelect = useCallback((day: CalendarDay) => {
|
||||
setSelectedDay(day);
|
||||
setModalOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleCreateFromCell = useCallback(
|
||||
(day: CalendarDay) => {
|
||||
handleOpenCreate(day.date);
|
||||
},
|
||||
[handleOpenCreate]
|
||||
);
|
||||
|
||||
const handleModalClose = useCallback(() => {
|
||||
setModalOpen(false);
|
||||
setSelectedDay(null);
|
||||
}, []);
|
||||
|
||||
const handleCreateDialogChange = useCallback((open: boolean) => {
|
||||
setCreateOpen(open);
|
||||
if (!open) {
|
||||
setCreateDate(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="space-y-3">
|
||||
<CalendarLegend />
|
||||
<CalendarGrid
|
||||
days={days}
|
||||
onSelectDay={handleDaySelect}
|
||||
onCreateDay={handleCreateFromCell}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<EventModal
|
||||
open={isModalOpen}
|
||||
day={selectedDay}
|
||||
onClose={handleModalClose}
|
||||
onCreate={handleOpenCreate}
|
||||
/>
|
||||
|
||||
<LancamentoDialog
|
||||
mode="create"
|
||||
open={createOpen}
|
||||
onOpenChange={handleCreateDialogChange}
|
||||
pagadorOptions={formOptions.pagadorOptions}
|
||||
splitPagadorOptions={formOptions.splitPagadorOptions}
|
||||
defaultPagadorId={formOptions.defaultPagadorId}
|
||||
contaOptions={formOptions.contaOptions}
|
||||
cartaoOptions={formOptions.cartaoOptions}
|
||||
categoriaOptions={formOptions.categoriaOptions}
|
||||
estabelecimentos={formOptions.estabelecimentos}
|
||||
defaultPeriod={period.period}
|
||||
defaultPurchaseDate={createDate ?? undefined}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
61
components/calendario/types.ts
Normal file
61
components/calendario/types.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import type { LancamentoItem, SelectOption } from "@/components/lancamentos/types";
|
||||
|
||||
export type CalendarEventType = "lancamento" | "boleto" | "cartao";
|
||||
|
||||
export type CalendarEvent =
|
||||
| {
|
||||
id: string;
|
||||
type: "lancamento";
|
||||
date: string;
|
||||
lancamento: LancamentoItem;
|
||||
}
|
||||
| {
|
||||
id: string;
|
||||
type: "boleto";
|
||||
date: string;
|
||||
lancamento: LancamentoItem;
|
||||
}
|
||||
| {
|
||||
id: string;
|
||||
type: "cartao";
|
||||
date: string;
|
||||
card: {
|
||||
id: string;
|
||||
name: string;
|
||||
dueDay: string;
|
||||
closingDay: string;
|
||||
brand: string | null;
|
||||
status: string;
|
||||
logo: string | null;
|
||||
totalDue: number | null;
|
||||
};
|
||||
};
|
||||
|
||||
export type CalendarPeriod = {
|
||||
period: string;
|
||||
monthName: string;
|
||||
year: number;
|
||||
};
|
||||
|
||||
export type CalendarDay = {
|
||||
date: string;
|
||||
label: string;
|
||||
isCurrentMonth: boolean;
|
||||
isToday: boolean;
|
||||
events: CalendarEvent[];
|
||||
};
|
||||
|
||||
export type CalendarFormOptions = {
|
||||
pagadorOptions: SelectOption[];
|
||||
splitPagadorOptions: SelectOption[];
|
||||
defaultPagadorId: string | null;
|
||||
contaOptions: SelectOption[];
|
||||
cartaoOptions: SelectOption[];
|
||||
categoriaOptions: SelectOption[];
|
||||
estabelecimentos: string[];
|
||||
};
|
||||
|
||||
export type CalendarData = {
|
||||
events: CalendarEvent[];
|
||||
formOptions: CalendarFormOptions;
|
||||
};
|
||||
61
components/calendario/utils.ts
Normal file
61
components/calendario/utils.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import type { CalendarDay, CalendarEvent } from "@/components/calendario/types";
|
||||
|
||||
export const formatDateKey = (date: Date) => date.toISOString().slice(0, 10);
|
||||
|
||||
export const parseDateKey = (value: string) => {
|
||||
const [yearStr, monthStr, dayStr] = value.split("-");
|
||||
const year = Number.parseInt(yearStr ?? "", 10);
|
||||
const month = Number.parseInt(monthStr ?? "", 10);
|
||||
const day = Number.parseInt(dayStr ?? "", 10);
|
||||
|
||||
return new Date(Date.UTC(year, (month ?? 1) - 1, day ?? 1));
|
||||
};
|
||||
|
||||
const getWeekdayIndex = (date: Date) => {
|
||||
const day = date.getUTCDay(); // 0 (domingo) - 6 (sábado)
|
||||
// Ajusta para segunda-feira como primeiro dia
|
||||
return day === 0 ? 6 : day - 1;
|
||||
};
|
||||
|
||||
export const buildCalendarDays = ({
|
||||
year,
|
||||
monthIndex,
|
||||
events,
|
||||
}: {
|
||||
year: number;
|
||||
monthIndex: number;
|
||||
events: Map<string, CalendarEvent[]>;
|
||||
}): CalendarDay[] => {
|
||||
const startOfMonth = new Date(Date.UTC(year, monthIndex, 1));
|
||||
const offset = getWeekdayIndex(startOfMonth);
|
||||
const startDate = new Date(Date.UTC(year, monthIndex, 1 - offset));
|
||||
const totalCells = 42; // 6 semanas
|
||||
const now = new Date();
|
||||
const todayKey = formatDateKey(
|
||||
new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()))
|
||||
);
|
||||
|
||||
const days: CalendarDay[] = [];
|
||||
|
||||
for (let index = 0; index < totalCells; index += 1) {
|
||||
const currentDate = new Date(startDate);
|
||||
currentDate.setUTCDate(startDate.getUTCDate() + index);
|
||||
|
||||
const dateKey = formatDateKey(currentDate);
|
||||
const isCurrentMonth = currentDate.getUTCMonth() === monthIndex;
|
||||
const dateLabel = currentDate.getUTCDate().toString();
|
||||
const eventsForDay = events.get(dateKey) ?? [];
|
||||
|
||||
days.push({
|
||||
date: dateKey,
|
||||
label: dateLabel,
|
||||
isCurrentMonth,
|
||||
isToday: dateKey === todayKey,
|
||||
events: eventsForDay,
|
||||
});
|
||||
}
|
||||
|
||||
return days;
|
||||
};
|
||||
|
||||
export const WEEK_DAYS_SHORT = ["Seg", "Ter", "Qua", "Qui", "Sex", "Sáb", "Dom"];
|
||||
250
components/cartoes/card-dialog.tsx
Normal file
250
components/cartoes/card-dialog.tsx
Normal file
@@ -0,0 +1,250 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
createCardAction,
|
||||
updateCardAction,
|
||||
} from "@/app/(dashboard)/cartoes/actions";
|
||||
import { LogoPickerDialog, LogoPickerTrigger } from "@/components/logo-picker";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import { useControlledState } from "@/hooks/use-controlled-state";
|
||||
import { useFormState } from "@/hooks/use-form-state";
|
||||
import { useLogoSelection } from "@/hooks/use-logo-selection";
|
||||
import { deriveNameFromLogo, normalizeLogo } from "@/lib/logo";
|
||||
import { formatLimitInput } from "@/lib/utils/currency";
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
useTransition,
|
||||
} from "react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { DEFAULT_CARD_BRANDS, DEFAULT_CARD_STATUS } from "./constants";
|
||||
import { CardFormFields } from "./card-form-fields";
|
||||
import type { Card, CardFormValues } from "./types";
|
||||
|
||||
type AccountOption = {
|
||||
id: string;
|
||||
name: string;
|
||||
logo: string | null;
|
||||
};
|
||||
|
||||
interface CardDialogProps {
|
||||
mode: "create" | "update";
|
||||
trigger?: React.ReactNode;
|
||||
logoOptions: string[];
|
||||
accounts: AccountOption[];
|
||||
card?: Card;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
const buildInitialValues = ({
|
||||
card,
|
||||
logoOptions,
|
||||
accounts,
|
||||
}: {
|
||||
card?: Card;
|
||||
logoOptions: string[];
|
||||
accounts: AccountOption[];
|
||||
}): CardFormValues => {
|
||||
const fallbackLogo = logoOptions[0] ?? "";
|
||||
const selectedLogo = normalizeLogo(card?.logo) || fallbackLogo;
|
||||
const derivedName = deriveNameFromLogo(selectedLogo);
|
||||
|
||||
return {
|
||||
name: card?.name ?? derivedName,
|
||||
brand: card?.brand ?? DEFAULT_CARD_BRANDS[0],
|
||||
status: card?.status ?? DEFAULT_CARD_STATUS[0],
|
||||
closingDay: card?.closingDay ?? "01",
|
||||
dueDay: card?.dueDay ?? "10",
|
||||
limit: formatLimitInput(card?.limit ?? null),
|
||||
note: card?.note ?? "",
|
||||
logo: selectedLogo,
|
||||
contaId: card?.contaId ?? accounts[0]?.id ?? "",
|
||||
};
|
||||
};
|
||||
|
||||
export function CardDialog({
|
||||
mode,
|
||||
trigger,
|
||||
logoOptions,
|
||||
accounts,
|
||||
card,
|
||||
open,
|
||||
onOpenChange,
|
||||
}: CardDialogProps) {
|
||||
const [logoDialogOpen, setLogoDialogOpen] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
// Use controlled state hook for dialog open state
|
||||
const [dialogOpen, setDialogOpen] = useControlledState(
|
||||
open,
|
||||
false,
|
||||
onOpenChange
|
||||
);
|
||||
|
||||
const initialState = useMemo(
|
||||
() => buildInitialValues({ card, logoOptions, accounts }),
|
||||
[card, logoOptions, accounts]
|
||||
);
|
||||
|
||||
// Use form state hook for form management
|
||||
const { formState, updateField, updateFields, setFormState } =
|
||||
useFormState<CardFormValues>(initialState);
|
||||
|
||||
// Reset form when dialog opens
|
||||
useEffect(() => {
|
||||
if (dialogOpen) {
|
||||
setFormState(initialState);
|
||||
setErrorMessage(null);
|
||||
}
|
||||
}, [dialogOpen, initialState, setFormState]);
|
||||
|
||||
// Close logo dialog when main dialog closes
|
||||
useEffect(() => {
|
||||
if (!dialogOpen) {
|
||||
setErrorMessage(null);
|
||||
setLogoDialogOpen(false);
|
||||
}
|
||||
}, [dialogOpen]);
|
||||
|
||||
// Use logo selection hook
|
||||
const handleLogoSelection = useLogoSelection({
|
||||
mode,
|
||||
currentLogo: formState.logo,
|
||||
currentName: formState.name,
|
||||
onUpdate: (updates) => {
|
||||
updateFields(updates);
|
||||
setLogoDialogOpen(false);
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
(event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setErrorMessage(null);
|
||||
|
||||
if (mode === "update" && !card?.id) {
|
||||
const message = "Cartão inválido.";
|
||||
setErrorMessage(message);
|
||||
toast.error(message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!formState.contaId) {
|
||||
const message = "Selecione a conta vinculada.";
|
||||
setErrorMessage(message);
|
||||
toast.error(message);
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = { ...formState };
|
||||
|
||||
if (!payload.logo) {
|
||||
const message = "Selecione um logo.";
|
||||
setErrorMessage(message);
|
||||
toast.error(message);
|
||||
return;
|
||||
}
|
||||
|
||||
startTransition(async () => {
|
||||
const result =
|
||||
mode === "create"
|
||||
? await createCardAction(payload)
|
||||
: await updateCardAction({
|
||||
id: card?.id ?? "",
|
||||
...payload,
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
setDialogOpen(false);
|
||||
setFormState(initialState);
|
||||
return;
|
||||
}
|
||||
|
||||
setErrorMessage(result.error);
|
||||
toast.error(result.error);
|
||||
});
|
||||
},
|
||||
[card?.id, formState, initialState, mode, setDialogOpen, setFormState]
|
||||
);
|
||||
|
||||
const title = mode === "create" ? "Novo cartão" : "Editar cartão";
|
||||
const description =
|
||||
mode === "create"
|
||||
? "Inclua um novo cartão de crédito para acompanhar seus gastos."
|
||||
: "Atualize as informações do cartão selecionado.";
|
||||
const submitLabel = mode === "create" ? "Salvar cartão" : "Atualizar cartão";
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||
{trigger ? <DialogTrigger asChild>{trigger}</DialogTrigger> : null}
|
||||
<DialogContent className="">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form className="flex flex-col gap-5" onSubmit={handleSubmit}>
|
||||
<LogoPickerTrigger
|
||||
selectedLogo={formState.logo}
|
||||
disabled={logoOptions.length === 0}
|
||||
helperText="Clique para escolher o logo do cartão"
|
||||
onOpen={() => {
|
||||
if (logoOptions.length > 0) {
|
||||
setLogoDialogOpen(true);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
<CardFormFields
|
||||
values={formState}
|
||||
accountOptions={accounts}
|
||||
onChange={updateField}
|
||||
/>
|
||||
|
||||
{errorMessage && (
|
||||
<p className="text-sm text-destructive">{errorMessage}</p>
|
||||
)}
|
||||
|
||||
<DialogFooter className="gap-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setDialogOpen(false)}
|
||||
disabled={isPending}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button type="submit" disabled={isPending}>
|
||||
{isPending ? "Salvando..." : submitLabel}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<LogoPickerDialog
|
||||
open={logoDialogOpen}
|
||||
logos={logoOptions}
|
||||
value={formState.logo}
|
||||
onOpenChange={setLogoDialogOpen}
|
||||
onSelect={handleLogoSelection}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
214
components/cartoes/card-form-fields.tsx
Normal file
214
components/cartoes/card-form-fields.tsx
Normal file
@@ -0,0 +1,214 @@
|
||||
"use client";
|
||||
|
||||
import { CurrencyInput } from "@/components/ui/currency-input";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
DAYS_IN_MONTH,
|
||||
DEFAULT_CARD_BRANDS,
|
||||
DEFAULT_CARD_STATUS,
|
||||
} from "./constants";
|
||||
import type { CardFormValues } from "./types";
|
||||
import {
|
||||
BrandSelectContent,
|
||||
StatusSelectContent,
|
||||
AccountSelectContent,
|
||||
} from "./card-select-items";
|
||||
|
||||
interface AccountOption {
|
||||
id: string;
|
||||
name: string;
|
||||
logo: string | null;
|
||||
}
|
||||
|
||||
interface CardFormFieldsProps {
|
||||
values: CardFormValues;
|
||||
accountOptions: AccountOption[];
|
||||
onChange: (field: keyof CardFormValues, value: string) => void;
|
||||
}
|
||||
|
||||
const ensureOption = (options: string[], value: string) => {
|
||||
if (!value) {
|
||||
return options;
|
||||
}
|
||||
return options.includes(value) ? options : [value, ...options];
|
||||
};
|
||||
|
||||
export function CardFormFields({
|
||||
values,
|
||||
accountOptions,
|
||||
onChange,
|
||||
}: CardFormFieldsProps) {
|
||||
const brands = ensureOption(
|
||||
DEFAULT_CARD_BRANDS as unknown as string[],
|
||||
values.brand
|
||||
);
|
||||
const statuses = ensureOption(
|
||||
DEFAULT_CARD_STATUS as unknown as string[],
|
||||
values.status
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="card-name">Nome do cartão</Label>
|
||||
<Input
|
||||
id="card-name"
|
||||
value={values.name}
|
||||
onChange={(event) => onChange("name", event.target.value)}
|
||||
placeholder="Ex.: Nubank Platinum"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="card-brand">Bandeira</Label>
|
||||
<Select
|
||||
value={values.brand}
|
||||
onValueChange={(value) => onChange("brand", value)}
|
||||
>
|
||||
<SelectTrigger id="card-brand" className="w-full">
|
||||
<SelectValue placeholder="Selecione a bandeira">
|
||||
{values.brand && <BrandSelectContent label={values.brand} />}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{brands.map((brand) => (
|
||||
<SelectItem key={brand} value={brand}>
|
||||
<BrandSelectContent label={brand} />
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="card-status">Status</Label>
|
||||
<Select
|
||||
value={values.status}
|
||||
onValueChange={(value) => onChange("status", value)}
|
||||
>
|
||||
<SelectTrigger id="card-status" className="w-full">
|
||||
<SelectValue placeholder="Selecione o status">
|
||||
{values.status && <StatusSelectContent label={values.status} />}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{statuses.map((status) => (
|
||||
<SelectItem key={status} value={status}>
|
||||
<StatusSelectContent label={status} />
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="card-limit">Limite (R$)</Label>
|
||||
<CurrencyInput
|
||||
id="card-limit"
|
||||
value={values.limit}
|
||||
onValueChange={(value) => onChange("limit", value)}
|
||||
placeholder="R$ 0,00"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="card-closing-day">Dia de fechamento</Label>
|
||||
<Select
|
||||
value={values.closingDay}
|
||||
onValueChange={(value) => onChange("closingDay", value)}
|
||||
>
|
||||
<SelectTrigger id="card-closing-day" className="w-full">
|
||||
<SelectValue placeholder="Dia de fechamento" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{DAYS_IN_MONTH.map((day) => (
|
||||
<SelectItem key={day} value={day}>
|
||||
Dia {day}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="card-due-day">Dia de vencimento</Label>
|
||||
<Select
|
||||
value={values.dueDay}
|
||||
onValueChange={(value) => onChange("dueDay", value)}
|
||||
>
|
||||
<SelectTrigger id="card-due-day" className="w-full">
|
||||
<SelectValue placeholder="Dia de vencimento" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{DAYS_IN_MONTH.map((day) => (
|
||||
<SelectItem key={day} value={day}>
|
||||
Dia {day}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2 sm:col-span-2">
|
||||
<Label htmlFor="card-account">Conta vinculada</Label>
|
||||
<Select
|
||||
value={values.contaId}
|
||||
onValueChange={(value) => onChange("contaId", value)}
|
||||
disabled={accountOptions.length === 0}
|
||||
>
|
||||
<SelectTrigger id="card-account" className="w-full">
|
||||
<SelectValue
|
||||
placeholder={
|
||||
accountOptions.length === 0
|
||||
? "Cadastre uma conta primeiro"
|
||||
: "Selecione a conta"
|
||||
}
|
||||
>
|
||||
{values.contaId && (() => {
|
||||
const selectedAccount = accountOptions.find(
|
||||
(acc) => acc.id === values.contaId
|
||||
);
|
||||
return selectedAccount ? (
|
||||
<AccountSelectContent
|
||||
label={selectedAccount.name}
|
||||
logo={selectedAccount.logo}
|
||||
/>
|
||||
) : null;
|
||||
})()}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{accountOptions.map((account) => (
|
||||
<SelectItem key={account.id} value={account.id}>
|
||||
<AccountSelectContent
|
||||
label={account.name}
|
||||
logo={account.logo}
|
||||
/>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2 sm:col-span-2">
|
||||
<Label htmlFor="card-note">Anotação</Label>
|
||||
<Textarea
|
||||
id="card-note"
|
||||
value={values.note}
|
||||
onChange={(event) => onChange("note", event.target.value)}
|
||||
placeholder="Observações sobre este cartão"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
307
components/cartoes/card-item.tsx
Normal file
307
components/cartoes/card-item.tsx
Normal file
@@ -0,0 +1,307 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
} from "@/components/ui/card";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import {
|
||||
RiChat3Line,
|
||||
RiDeleteBin5Line,
|
||||
RiEyeLine,
|
||||
RiPencilLine,
|
||||
} from "@remixicon/react";
|
||||
import Image from "next/image";
|
||||
import { useMemo } from "react";
|
||||
import MoneyValues from "../money-values";
|
||||
|
||||
interface CardItemProps {
|
||||
name: string;
|
||||
brand: string;
|
||||
status: string;
|
||||
closingDay: string;
|
||||
dueDay: string;
|
||||
limit: number | null;
|
||||
limitInUse?: number | null;
|
||||
limitAvailable?: number | null;
|
||||
contaName: string;
|
||||
logo?: string | null;
|
||||
note?: string | null;
|
||||
onEdit?: () => void;
|
||||
onInvoice?: () => void;
|
||||
onRemove?: () => void;
|
||||
}
|
||||
|
||||
const BRAND_ASSETS: Record<string, string> = {
|
||||
visa: "/bandeiras/visa.svg",
|
||||
mastercard: "/bandeiras/mastercard.svg",
|
||||
amex: "/bandeiras/amex.svg",
|
||||
american: "/bandeiras/amex.svg",
|
||||
elo: "/bandeiras/elo.svg",
|
||||
hipercard: "/bandeiras/hipercard.svg",
|
||||
hiper: "/bandeiras/hipercard.svg",
|
||||
};
|
||||
|
||||
const resolveBrandAsset = (brand: string) => {
|
||||
const normalized = brand.trim().toLowerCase();
|
||||
|
||||
const match = (
|
||||
Object.keys(BRAND_ASSETS) as Array<keyof typeof BRAND_ASSETS>
|
||||
).find((entry) => normalized.includes(entry));
|
||||
|
||||
return match ? BRAND_ASSETS[match] : null;
|
||||
};
|
||||
|
||||
const formatDay = (value: string) => value.padStart(2, "0");
|
||||
|
||||
export function CardItem({
|
||||
name,
|
||||
brand,
|
||||
status,
|
||||
closingDay,
|
||||
dueDay,
|
||||
limit,
|
||||
limitInUse,
|
||||
limitAvailable,
|
||||
contaName: _contaName,
|
||||
logo,
|
||||
note,
|
||||
onEdit,
|
||||
onInvoice,
|
||||
onRemove,
|
||||
}: CardItemProps) {
|
||||
void _contaName;
|
||||
|
||||
const limitTotal = limit ?? null;
|
||||
const used =
|
||||
limitInUse ??
|
||||
(limitTotal !== null && limitAvailable !== null
|
||||
? Math.max(limitTotal - limitAvailable, 0)
|
||||
: limitTotal !== null
|
||||
? 0
|
||||
: null);
|
||||
|
||||
const available =
|
||||
limitAvailable ??
|
||||
(limitTotal !== null && used !== null
|
||||
? Math.max(limitTotal - used, 0)
|
||||
: null);
|
||||
|
||||
const usagePercent =
|
||||
limitTotal && limitTotal > 0 && used !== null
|
||||
? Math.min(Math.max((used / limitTotal) * 100, 0), 100)
|
||||
: 0;
|
||||
|
||||
const logoPath = useMemo(() => {
|
||||
if (!logo) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (
|
||||
logo.startsWith("http://") ||
|
||||
logo.startsWith("https://") ||
|
||||
logo.startsWith("data:")
|
||||
) {
|
||||
return logo;
|
||||
}
|
||||
|
||||
return logo.startsWith("/") ? logo : `/logos/${logo}`;
|
||||
}, [logo]);
|
||||
|
||||
const brandAsset = useMemo(() => resolveBrandAsset(brand), [brand]);
|
||||
|
||||
const isInactive = useMemo(
|
||||
() => status?.toLowerCase() === "inativo",
|
||||
[status]
|
||||
);
|
||||
|
||||
const metrics = useMemo(() => {
|
||||
if (limitTotal === null) return null;
|
||||
|
||||
return [
|
||||
{ label: "Limite Total", value: limitTotal },
|
||||
{ label: "Em uso", value: used },
|
||||
{ label: "Disponível", value: available },
|
||||
];
|
||||
}, [available, limitTotal, used]);
|
||||
|
||||
const actions = useMemo(
|
||||
() => [
|
||||
{
|
||||
label: "editar",
|
||||
icon: <RiPencilLine className="size-4" aria-hidden />,
|
||||
onClick: onEdit,
|
||||
className: "text-primary",
|
||||
},
|
||||
{
|
||||
label: "ver fatura",
|
||||
icon: <RiEyeLine className="size-4" aria-hidden />,
|
||||
onClick: onInvoice,
|
||||
className: "text-primary",
|
||||
},
|
||||
{
|
||||
label: "remover",
|
||||
icon: <RiDeleteBin5Line className="size-4" aria-hidden />,
|
||||
onClick: onRemove,
|
||||
className: "text-destructive",
|
||||
},
|
||||
],
|
||||
[onEdit, onInvoice, onRemove]
|
||||
);
|
||||
|
||||
return (
|
||||
<Card className="flex p-6 h-[300px] w-[440px]">
|
||||
<CardHeader className="space-y-2 px-0 pb-0">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="flex flex-1 items-center gap-2">
|
||||
{logoPath ? (
|
||||
<div className="flex size-10 shrink-0 items-center justify-center overflow-hidden">
|
||||
<Image
|
||||
src={logoPath}
|
||||
alt={`Logo do cartão ${name}`}
|
||||
width={42}
|
||||
height={42}
|
||||
className={cn(
|
||||
"rounded-lg",
|
||||
isInactive && "grayscale opacity-40"
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<h3 className="truncate text-sm font-semibold text-foreground sm:text-base">
|
||||
{name}
|
||||
</h3>
|
||||
{note ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="text-muted-foreground/70 transition-colors hover:text-foreground"
|
||||
aria-label="Observações do cartão"
|
||||
>
|
||||
<RiChat3Line className="size-3.5" />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" align="start">
|
||||
{note}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{status ? (
|
||||
<span className="text-xs tracking-wide text-muted-foreground">
|
||||
{status}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{brandAsset ? (
|
||||
<div className="flex items-center justify-center rounded-lg py-1">
|
||||
<Image
|
||||
src={brandAsset}
|
||||
alt={`Bandeira ${brand}`}
|
||||
width={42}
|
||||
height={42}
|
||||
className={cn(
|
||||
"h-6 w-auto rounded",
|
||||
isInactive && "grayscale opacity-40"
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-sm font-medium text-muted-foreground">
|
||||
{brand}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between border-y border-dashed py-3 text-xs font-medium text-muted-foreground sm:text-sm">
|
||||
<span>
|
||||
Fecha dia{" "}
|
||||
<span className="font-semibold text-foreground">
|
||||
{formatDay(closingDay)}
|
||||
</span>
|
||||
</span>
|
||||
<span>
|
||||
Vence dia{" "}
|
||||
<span className="font-semibold text-foreground">
|
||||
{formatDay(dueDay)}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="flex flex-1 flex-col gap-5 px-0">
|
||||
{metrics ? (
|
||||
<>
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div className="flex flex-col items-start gap-1">
|
||||
<p className="text-sm font-semibold text-foreground">
|
||||
<MoneyValues amount={metrics[0].value} />
|
||||
</p>
|
||||
<span className="text-xs font-medium text-muted-foreground">
|
||||
{metrics[0].label}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col items-center gap-1">
|
||||
<p className="flex items-center gap-1.5 text-sm font-semibold text-foreground">
|
||||
<span className="size-2 rounded-full bg-primary" />
|
||||
<MoneyValues amount={metrics[1].value} />
|
||||
</p>
|
||||
<span className="text-xs font-medium text-muted-foreground">
|
||||
{metrics[1].label}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col items-end gap-1">
|
||||
<p className="text-sm font-semibold text-foreground">
|
||||
<MoneyValues amount={metrics[2].value} />
|
||||
</p>
|
||||
<span className="text-xs font-medium text-muted-foreground">
|
||||
{metrics[2].label}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Progress value={usagePercent} className="h-3" />
|
||||
</>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Ainda não há limite registrado para este cartão.
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
<CardFooter className="mt-auto flex flex-wrap gap-4 px-0 text-sm">
|
||||
{actions.map(({ label, icon, onClick, className }) => (
|
||||
<button
|
||||
key={label}
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className={cn(
|
||||
"flex items-center gap-1 font-medium transition-opacity hover:opacity-80",
|
||||
className
|
||||
)}
|
||||
>
|
||||
{icon}
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
89
components/cartoes/card-select-items.tsx
Normal file
89
components/cartoes/card-select-items.tsx
Normal file
@@ -0,0 +1,89 @@
|
||||
"use client";
|
||||
|
||||
import DotIcon from "@/components/dot-icon";
|
||||
import Image from "next/image";
|
||||
import { RiBankLine } from "@remixicon/react";
|
||||
|
||||
type SelectItemContentProps = {
|
||||
label: string;
|
||||
logo?: string | null;
|
||||
};
|
||||
|
||||
const resolveLogoSrc = (logo: string | null) => {
|
||||
if (!logo) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const fileName = logo.split("/").filter(Boolean).pop() ?? logo;
|
||||
return `/logos/${fileName}`;
|
||||
};
|
||||
|
||||
const getBrandLogo = (brand: string): string | null => {
|
||||
const brandMap: Record<string, string> = {
|
||||
Visa: "visa.png",
|
||||
Mastercard: "mastercard.png",
|
||||
Elo: "elo.png",
|
||||
};
|
||||
|
||||
return brandMap[brand] ?? null;
|
||||
};
|
||||
|
||||
export function BrandSelectContent({ label }: { label: string }) {
|
||||
const brandLogo = getBrandLogo(label);
|
||||
const logoSrc = brandLogo ? `/logos/${brandLogo}` : null;
|
||||
|
||||
return (
|
||||
<span className="flex items-center gap-2">
|
||||
{logoSrc ? (
|
||||
<Image
|
||||
src={logoSrc}
|
||||
alt={`Logo ${label}`}
|
||||
width={24}
|
||||
height={24}
|
||||
className="rounded object-contain"
|
||||
/>
|
||||
) : (
|
||||
<RiBankLine className="size-5 text-muted-foreground" aria-hidden />
|
||||
)}
|
||||
<span>{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function StatusSelectContent({ label }: { label: string }) {
|
||||
const isActive = label === "Ativo";
|
||||
|
||||
return (
|
||||
<span className="flex items-center gap-2">
|
||||
<DotIcon
|
||||
bg_dot={
|
||||
isActive
|
||||
? "bg-emerald-600 dark:bg-emerald-300"
|
||||
: "bg-slate-400 dark:bg-slate-500"
|
||||
}
|
||||
/>
|
||||
<span>{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function AccountSelectContent({ label, logo }: SelectItemContentProps) {
|
||||
const logoSrc = resolveLogoSrc(logo);
|
||||
|
||||
return (
|
||||
<span className="flex items-center gap-2">
|
||||
{logoSrc ? (
|
||||
<Image
|
||||
src={logoSrc}
|
||||
alt={`Logo de ${label}`}
|
||||
width={20}
|
||||
height={20}
|
||||
className="rounded"
|
||||
/>
|
||||
) : (
|
||||
<RiBankLine className="size-4 text-muted-foreground" aria-hidden />
|
||||
)}
|
||||
<span>{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
173
components/cartoes/cards-page.tsx
Normal file
173
components/cartoes/cards-page.tsx
Normal file
@@ -0,0 +1,173 @@
|
||||
"use client";
|
||||
|
||||
import { deleteCardAction } from "@/app/(dashboard)/cartoes/actions";
|
||||
import { ConfirmActionDialog } from "@/components/confirm-action-dialog";
|
||||
import { EmptyState } from "@/components/empty-state";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { RiAddCircleLine, RiBankCardLine } from "@remixicon/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { CardDialog } from "./card-dialog";
|
||||
import { CardItem } from "./card-item";
|
||||
|
||||
type AccountOption = {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
|
||||
interface CardsPageProps {
|
||||
cards: Card[];
|
||||
accounts: AccountOption[];
|
||||
logoOptions: string[];
|
||||
}
|
||||
|
||||
export function CardsPage({ cards, accounts, logoOptions }: CardsPageProps) {
|
||||
const router = useRouter();
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [selectedCard, setSelectedCard] = useState<Card | null>(null);
|
||||
const [removeOpen, setRemoveOpen] = useState(false);
|
||||
const [cardToRemove, setCardToRemove] = useState<Card | null>(null);
|
||||
|
||||
const hasCards = cards.length > 0;
|
||||
|
||||
const orderedCards = useMemo(
|
||||
() =>
|
||||
[...cards].sort((a, b) => {
|
||||
// Coloca inativos no final
|
||||
const aIsInactive = a.status?.toLowerCase() === "inativo";
|
||||
const bIsInactive = b.status?.toLowerCase() === "inativo";
|
||||
|
||||
if (aIsInactive && !bIsInactive) return 1;
|
||||
if (!aIsInactive && bIsInactive) return -1;
|
||||
|
||||
// Mesma ordem alfabética dentro de cada grupo
|
||||
return a.name.localeCompare(b.name, "pt-BR", { sensitivity: "base" });
|
||||
}),
|
||||
[cards]
|
||||
);
|
||||
|
||||
const handleEdit = useCallback((card: Card) => {
|
||||
setSelectedCard(card);
|
||||
setEditOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleEditOpenChange = useCallback((open: boolean) => {
|
||||
setEditOpen(open);
|
||||
if (!open) {
|
||||
setSelectedCard(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleRemoveRequest = useCallback((card: Card) => {
|
||||
setCardToRemove(card);
|
||||
setRemoveOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleInvoice = useCallback(
|
||||
(card: Card) => {
|
||||
router.push(`/cartoes/${card.id}/fatura`);
|
||||
},
|
||||
[router]
|
||||
);
|
||||
|
||||
const handleRemoveOpenChange = useCallback((open: boolean) => {
|
||||
setRemoveOpen(open);
|
||||
if (!open) {
|
||||
setCardToRemove(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleRemoveConfirm = useCallback(async () => {
|
||||
if (!cardToRemove) {
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await deleteCardAction({ id: cardToRemove.id });
|
||||
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
return;
|
||||
}
|
||||
|
||||
toast.error(result.error);
|
||||
throw new Error(result.error);
|
||||
}, [cardToRemove]);
|
||||
|
||||
const removeTitle = cardToRemove
|
||||
? `Remover cartão "${cardToRemove.name}"?`
|
||||
: "Remover cartão?";
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex w-full flex-col gap-6">
|
||||
<div className="flex justify-start">
|
||||
<CardDialog
|
||||
mode="create"
|
||||
accounts={accounts}
|
||||
logoOptions={logoOptions}
|
||||
trigger={
|
||||
<Button>
|
||||
<RiAddCircleLine className="size-4" />
|
||||
Novo cartão
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{hasCards ? (
|
||||
<div className="flex flex-wrap gap-4">
|
||||
{orderedCards.map((card) => (
|
||||
<CardItem
|
||||
key={card.id}
|
||||
name={card.name}
|
||||
brand={card.brand}
|
||||
status={card.status}
|
||||
closingDay={card.closingDay}
|
||||
dueDay={card.dueDay}
|
||||
limit={card.limit}
|
||||
limitInUse={card.limitInUse ?? null}
|
||||
limitAvailable={card.limitAvailable ?? card.limit ?? null}
|
||||
contaName={card.contaName}
|
||||
logo={card.logo}
|
||||
note={card.note}
|
||||
onEdit={() => handleEdit(card)}
|
||||
onInvoice={() => handleInvoice(card)}
|
||||
onRemove={() => handleRemoveRequest(card)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<Card className="flex w-full items-center justify-center py-12">
|
||||
<EmptyState
|
||||
media={<RiBankCardLine className="size-6 text-primary" />}
|
||||
title="Nenhum cartão cadastrado"
|
||||
description="Adicione seu primeiro cartão para acompanhar limites e faturas com mais controle."
|
||||
/>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<CardDialog
|
||||
mode="update"
|
||||
accounts={accounts}
|
||||
logoOptions={logoOptions}
|
||||
card={selectedCard ?? undefined}
|
||||
open={editOpen && !!selectedCard}
|
||||
onOpenChange={handleEditOpenChange}
|
||||
/>
|
||||
|
||||
<ConfirmActionDialog
|
||||
open={removeOpen && !!cardToRemove}
|
||||
onOpenChange={handleRemoveOpenChange}
|
||||
title={removeTitle}
|
||||
description="Ao remover este cartão, os registros relacionados a ele serão excluídos permanentemente."
|
||||
confirmLabel="Remover cartão"
|
||||
pendingLabel="Removendo..."
|
||||
confirmVariant="destructive"
|
||||
onConfirm={handleRemoveConfirm}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
7
components/cartoes/constants.ts
Normal file
7
components/cartoes/constants.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export const DEFAULT_CARD_BRANDS = ["Visa", "Mastercard", "Elo"] as const;
|
||||
|
||||
export const DEFAULT_CARD_STATUS = ["Ativo", "Inativo"] as const;
|
||||
|
||||
export const DAYS_IN_MONTH = Array.from({ length: 31 }, (_, index) =>
|
||||
String(index + 1).padStart(2, "0")
|
||||
);
|
||||
27
components/cartoes/types.ts
Normal file
27
components/cartoes/types.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
export type Card = {
|
||||
id: string;
|
||||
name: string;
|
||||
brand: string;
|
||||
status: string;
|
||||
closingDay: string;
|
||||
dueDay: string;
|
||||
note: string | null;
|
||||
logo: string | null;
|
||||
limit: number | null;
|
||||
contaId: string;
|
||||
contaName: string;
|
||||
limitInUse?: number | null;
|
||||
limitAvailable?: number | null;
|
||||
};
|
||||
|
||||
export type CardFormValues = {
|
||||
name: string;
|
||||
brand: string;
|
||||
status: string;
|
||||
closingDay: string;
|
||||
dueDay: string;
|
||||
limit: string;
|
||||
note: string;
|
||||
logo: string;
|
||||
contaId: string;
|
||||
};
|
||||
167
components/categorias/categories-page.tsx
Normal file
167
components/categorias/categories-page.tsx
Normal file
@@ -0,0 +1,167 @@
|
||||
"use client";
|
||||
|
||||
import { deleteCategoryAction } from "@/app/(dashboard)/categorias/actions";
|
||||
import { ConfirmActionDialog } from "@/components/confirm-action-dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import {
|
||||
CATEGORY_TYPE_LABEL,
|
||||
CATEGORY_TYPES,
|
||||
} from "@/lib/categorias/constants";
|
||||
import { RiAddCircleLine } from "@remixicon/react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { CategoryCard } from "./category-card";
|
||||
import { CategoryDialog } from "./category-dialog";
|
||||
import type { Category, CategoryType } from "./types";
|
||||
|
||||
interface CategoriesPageProps {
|
||||
categories: Category[];
|
||||
}
|
||||
|
||||
export function CategoriesPage({ categories }: CategoriesPageProps) {
|
||||
const [activeType, setActiveType] = useState<CategoryType>(CATEGORY_TYPES[0]);
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [selectedCategory, setSelectedCategory] = useState<Category | null>(
|
||||
null
|
||||
);
|
||||
const [removeOpen, setRemoveOpen] = useState(false);
|
||||
const [categoryToRemove, setCategoryToRemove] = useState<Category | null>(
|
||||
null
|
||||
);
|
||||
|
||||
const categoriesByType = useMemo(() => {
|
||||
const base = Object.fromEntries(
|
||||
CATEGORY_TYPES.map((type) => [type, [] as Category[]])
|
||||
) as Record<CategoryType, Category[]>;
|
||||
|
||||
categories.forEach((category) => {
|
||||
base[category.type]?.push(category);
|
||||
});
|
||||
|
||||
CATEGORY_TYPES.forEach((type) => {
|
||||
base[type].sort((a, b) =>
|
||||
a.name.localeCompare(b.name, "pt-BR", { sensitivity: "base" })
|
||||
);
|
||||
});
|
||||
|
||||
return base;
|
||||
}, [categories]);
|
||||
|
||||
const handleEdit = useCallback((category: Category) => {
|
||||
setSelectedCategory(category);
|
||||
setEditOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleEditOpenChange = useCallback((open: boolean) => {
|
||||
setEditOpen(open);
|
||||
if (!open) {
|
||||
setSelectedCategory(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleRemoveRequest = useCallback((category: Category) => {
|
||||
setCategoryToRemove(category);
|
||||
setRemoveOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleRemoveOpenChange = useCallback((open: boolean) => {
|
||||
setRemoveOpen(open);
|
||||
if (!open) {
|
||||
setCategoryToRemove(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleRemoveConfirm = useCallback(async () => {
|
||||
if (!categoryToRemove) {
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await deleteCategoryAction({ id: categoryToRemove.id });
|
||||
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
return;
|
||||
}
|
||||
|
||||
toast.error(result.error);
|
||||
throw new Error(result.error);
|
||||
}, [categoryToRemove]);
|
||||
|
||||
const removeTitle = categoryToRemove
|
||||
? `Remover categoria "${categoryToRemove.name}"?`
|
||||
: "Remover categoria?";
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex w-full flex-col gap-6">
|
||||
<div className="flex justify-start">
|
||||
<CategoryDialog
|
||||
mode="create"
|
||||
defaultType={activeType}
|
||||
trigger={
|
||||
<Button>
|
||||
<RiAddCircleLine className="size-4" />
|
||||
Nova categoria
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Tabs
|
||||
value={activeType}
|
||||
onValueChange={(value) => setActiveType(value as CategoryType)}
|
||||
className="w-full"
|
||||
>
|
||||
<TabsList>
|
||||
{CATEGORY_TYPES.map((type) => (
|
||||
<TabsTrigger key={type} value={type}>
|
||||
{CATEGORY_TYPE_LABEL[type]}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
|
||||
{CATEGORY_TYPES.map((type) => (
|
||||
<TabsContent key={type} value={type} className="mt-4">
|
||||
{categoriesByType[type].length === 0 ? (
|
||||
<div className="flex min-h-[280px] items-center justify-center rounded-lg border border-dashed bg-muted/10 p-10 text-center text-sm text-muted-foreground">
|
||||
Ainda não há categorias de{" "}
|
||||
{CATEGORY_TYPE_LABEL[type].toLowerCase()}.
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||
{categoriesByType[type].map((category) => (
|
||||
<CategoryCard
|
||||
key={category.id}
|
||||
category={category}
|
||||
onEdit={handleEdit}
|
||||
onRemove={handleRemoveRequest}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</TabsContent>
|
||||
))}
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
<CategoryDialog
|
||||
mode="update"
|
||||
category={selectedCategory ?? undefined}
|
||||
open={editOpen && !!selectedCategory}
|
||||
onOpenChange={handleEditOpenChange}
|
||||
/>
|
||||
|
||||
<ConfirmActionDialog
|
||||
open={removeOpen && !!categoryToRemove}
|
||||
onOpenChange={handleRemoveOpenChange}
|
||||
title={removeTitle}
|
||||
description="Ao remover esta categoria, os lançamentos associados serão desrelacionados."
|
||||
confirmLabel="Remover categoria"
|
||||
pendingLabel="Removendo..."
|
||||
confirmVariant="destructive"
|
||||
onConfirm={handleRemoveConfirm}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
94
components/categorias/category-card.tsx
Normal file
94
components/categorias/category-card.tsx
Normal file
@@ -0,0 +1,94 @@
|
||||
"use client";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { RiDeleteBin5Line, RiMore2Fill, RiPencilLine } from "@remixicon/react";
|
||||
import Link from "next/link";
|
||||
import { TypeBadge } from "../type-badge";
|
||||
import { CategoryIcon } from "./category-icon";
|
||||
import type { Category } from "./types";
|
||||
|
||||
interface CategoryCardProps {
|
||||
category: Category;
|
||||
onEdit: (category: Category) => void;
|
||||
onRemove: (category: Category) => void;
|
||||
}
|
||||
|
||||
export function CategoryCard({
|
||||
category,
|
||||
onEdit,
|
||||
onRemove,
|
||||
}: CategoryCardProps) {
|
||||
// Categorias protegidas que não podem ser editadas ou removidas
|
||||
const categoriasProtegidas = [
|
||||
"Transferência interna",
|
||||
"Saldo inicial",
|
||||
"Pagamentos",
|
||||
];
|
||||
const isProtegida = categoriasProtegidas.includes(category.name);
|
||||
const canEdit = !isProtegida;
|
||||
const canRemove = !isProtegida;
|
||||
|
||||
return (
|
||||
<Card className="group py-2">
|
||||
<CardContent className="p-2">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex items-start gap-2">
|
||||
<span className="flex size-11 items-center justify-center text-primary">
|
||||
<CategoryIcon name={category.icon} className="size-6" />
|
||||
</span>
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-base font-medium leading-tight">
|
||||
<Link
|
||||
href={`/categorias/${category.id}`}
|
||||
className="underline-offset-4 hover:underline"
|
||||
>
|
||||
{category.name}
|
||||
</Link>
|
||||
</h3>
|
||||
<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
||||
<TypeBadge type={category.type} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className="opacity-0 transition-opacity group-hover:opacity-100"
|
||||
>
|
||||
<RiMore2Fill className="size-4" />
|
||||
<span className="sr-only">Abrir ações da categoria</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem
|
||||
onSelect={() => onEdit(category)}
|
||||
disabled={!canEdit}
|
||||
>
|
||||
<RiPencilLine className="mr-2 size-4" />
|
||||
Editar
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
variant="destructive"
|
||||
onSelect={() => onRemove(category)}
|
||||
disabled={!canRemove}
|
||||
>
|
||||
<RiDeleteBin5Line className="mr-2 size-4" />
|
||||
Remover
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
149
components/categorias/category-detail-header.tsx
Normal file
149
components/categorias/category-detail-header.tsx
Normal file
@@ -0,0 +1,149 @@
|
||||
import { type CategoryType } from "@/lib/categorias/constants";
|
||||
import { currencyFormatter } from "@/lib/lancamentos/formatting-helpers";
|
||||
import { getIconComponent } from "@/lib/utils/icons";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import { RiArrowDownLine, RiArrowUpLine } from "@remixicon/react";
|
||||
import { TypeBadge } from "../type-badge";
|
||||
import { Card } from "../ui/card";
|
||||
|
||||
const buildInitials = (value: string) => {
|
||||
const parts = value.trim().split(/\s+/).filter(Boolean);
|
||||
if (parts.length === 0) {
|
||||
return "CT";
|
||||
}
|
||||
if (parts.length === 1) {
|
||||
const firstPart = parts[0];
|
||||
return firstPart ? firstPart.slice(0, 2).toUpperCase() : "CT";
|
||||
}
|
||||
const firstChar = parts[0]?.[0] ?? "";
|
||||
const secondChar = parts[1]?.[0] ?? "";
|
||||
return `${firstChar}${secondChar}`.toUpperCase() || "CT";
|
||||
};
|
||||
|
||||
type CategorySummary = {
|
||||
id: string;
|
||||
name: string;
|
||||
icon: string | null;
|
||||
type: CategoryType;
|
||||
};
|
||||
|
||||
type CategoryDetailHeaderProps = {
|
||||
category: CategorySummary;
|
||||
currentPeriodLabel: string;
|
||||
previousPeriodLabel: string;
|
||||
currentTotal: number;
|
||||
previousTotal: number;
|
||||
percentageChange: number | null;
|
||||
transactionCount: number;
|
||||
};
|
||||
|
||||
export function CategoryDetailHeader({
|
||||
category,
|
||||
currentPeriodLabel,
|
||||
previousPeriodLabel,
|
||||
currentTotal,
|
||||
previousTotal,
|
||||
percentageChange,
|
||||
transactionCount,
|
||||
}: CategoryDetailHeaderProps) {
|
||||
const IconComponent = category.icon ? getIconComponent(category.icon) : null;
|
||||
const initials = buildInitials(category.name);
|
||||
|
||||
const isIncrease =
|
||||
typeof percentageChange === "number" && percentageChange > 0;
|
||||
const isDecrease =
|
||||
typeof percentageChange === "number" && percentageChange < 0;
|
||||
|
||||
const variationColor =
|
||||
category.type === "receita"
|
||||
? isIncrease
|
||||
? "text-emerald-600"
|
||||
: isDecrease
|
||||
? "text-rose-600"
|
||||
: "text-muted-foreground"
|
||||
: isIncrease
|
||||
? "text-rose-600"
|
||||
: isDecrease
|
||||
? "text-emerald-600"
|
||||
: "text-muted-foreground";
|
||||
|
||||
const variationIcon =
|
||||
isIncrease || isDecrease ? (
|
||||
isIncrease ? (
|
||||
<RiArrowUpLine className="size-4" aria-hidden />
|
||||
) : (
|
||||
<RiArrowDownLine className="size-4" aria-hidden />
|
||||
)
|
||||
) : null;
|
||||
|
||||
const variationLabel =
|
||||
typeof percentageChange === "number"
|
||||
? `${percentageChange > 0 ? "+" : ""}${Math.abs(percentageChange).toFixed(
|
||||
1
|
||||
)}%`
|
||||
: "—";
|
||||
|
||||
return (
|
||||
<Card className="px-4">
|
||||
<div className="flex flex-col gap-6 lg:flex-row lg:items-center lg:justify-between">
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="flex size-12 items-center justify-center rounded-xl bg-muted border text-primary">
|
||||
{IconComponent ? (
|
||||
<IconComponent className="size-6" aria-hidden />
|
||||
) : (
|
||||
<span className="text-sm font-semibold uppercase text-muted-foreground">
|
||||
{initials}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-xl font-semibold leading-tight">
|
||||
{category.name}
|
||||
</h1>
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
|
||||
<TypeBadge type={category.type} />
|
||||
<span>
|
||||
{transactionCount}{" "}
|
||||
{transactionCount === 1 ? "lançamento" : "lançamentos"} no{" "}
|
||||
período
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid w-full gap-4 sm:grid-cols-2 lg:w-auto lg:grid-cols-3">
|
||||
<div>
|
||||
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
||||
Total em {currentPeriodLabel}
|
||||
</p>
|
||||
<p className="mt-1 text-2xl font-semibold">
|
||||
{currencyFormatter.format(currentTotal)}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
||||
Total em {previousPeriodLabel}
|
||||
</p>
|
||||
<p className="mt-1 text-lg font-medium text-muted-foreground">
|
||||
{currencyFormatter.format(previousTotal)}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
||||
Variação vs mês anterior
|
||||
</p>
|
||||
<div
|
||||
className={cn(
|
||||
"mt-1 flex items-center gap-1 text-xl font-semibold",
|
||||
variationColor
|
||||
)}
|
||||
>
|
||||
{variationIcon}
|
||||
<span>{variationLabel}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
189
components/categorias/category-dialog.tsx
Normal file
189
components/categorias/category-dialog.tsx
Normal file
@@ -0,0 +1,189 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
createCategoryAction,
|
||||
updateCategoryAction,
|
||||
} from "@/app/(dashboard)/categorias/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import { useControlledState } from "@/hooks/use-controlled-state";
|
||||
import { useFormState } from "@/hooks/use-form-state";
|
||||
import { CATEGORY_TYPES } from "@/lib/categorias/constants";
|
||||
import { getDefaultIconForType } from "@/lib/categorias/icons";
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
useTransition,
|
||||
} from "react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { CategoryFormFields } from "./category-form-fields";
|
||||
import type { Category, CategoryFormValues } from "./types";
|
||||
|
||||
interface CategoryDialogProps {
|
||||
mode: "create" | "update";
|
||||
trigger?: React.ReactNode;
|
||||
category?: Category;
|
||||
defaultType?: CategoryFormValues["type"];
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
const buildInitialValues = ({
|
||||
category,
|
||||
defaultType,
|
||||
}: {
|
||||
category?: Category;
|
||||
defaultType?: CategoryFormValues["type"];
|
||||
}): CategoryFormValues => {
|
||||
const initialType = category?.type ?? defaultType ?? CATEGORY_TYPES[0];
|
||||
const fallbackIcon = getDefaultIconForType(initialType);
|
||||
const existingIcon = category?.icon ?? "";
|
||||
const icon = existingIcon || fallbackIcon;
|
||||
|
||||
return {
|
||||
name: category?.name ?? "",
|
||||
type: initialType,
|
||||
icon,
|
||||
};
|
||||
};
|
||||
|
||||
export function CategoryDialog({
|
||||
mode,
|
||||
trigger,
|
||||
category,
|
||||
defaultType,
|
||||
open,
|
||||
onOpenChange,
|
||||
}: CategoryDialogProps) {
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
// Use controlled state hook for dialog open state
|
||||
const [dialogOpen, setDialogOpen] = useControlledState(
|
||||
open,
|
||||
false,
|
||||
onOpenChange
|
||||
);
|
||||
|
||||
const initialState = useMemo(
|
||||
() =>
|
||||
buildInitialValues({
|
||||
category,
|
||||
defaultType,
|
||||
}),
|
||||
[category, defaultType]
|
||||
);
|
||||
|
||||
// Use form state hook for form management
|
||||
const { formState, updateField, setFormState } =
|
||||
useFormState<CategoryFormValues>(initialState);
|
||||
|
||||
// Reset form when dialog opens
|
||||
useEffect(() => {
|
||||
if (dialogOpen) {
|
||||
setFormState(initialState);
|
||||
setErrorMessage(null);
|
||||
}
|
||||
}, [dialogOpen, initialState, setFormState]);
|
||||
|
||||
// Clear error when dialog closes
|
||||
useEffect(() => {
|
||||
if (!dialogOpen) {
|
||||
setErrorMessage(null);
|
||||
}
|
||||
}, [dialogOpen]);
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
(event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setErrorMessage(null);
|
||||
|
||||
if (mode === "update" && !category?.id) {
|
||||
const message = "Categoria inválida.";
|
||||
setErrorMessage(message);
|
||||
toast.error(message);
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = {
|
||||
name: formState.name.trim(),
|
||||
type: formState.type,
|
||||
icon: formState.icon.trim(),
|
||||
};
|
||||
|
||||
startTransition(async () => {
|
||||
const result =
|
||||
mode === "create"
|
||||
? await createCategoryAction(payload)
|
||||
: await updateCategoryAction({
|
||||
id: category?.id ?? "",
|
||||
...payload,
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
setDialogOpen(false);
|
||||
setFormState(initialState);
|
||||
return;
|
||||
}
|
||||
|
||||
setErrorMessage(result.error);
|
||||
toast.error(result.error);
|
||||
});
|
||||
},
|
||||
[category?.id, formState, initialState, mode, setDialogOpen, setFormState]
|
||||
);
|
||||
|
||||
const title = mode === "create" ? "Nova categoria" : "Editar categoria";
|
||||
const description =
|
||||
mode === "create"
|
||||
? "Crie uma categoria para organizar seus lançamentos."
|
||||
: "Atualize os detalhes da categoria selecionada.";
|
||||
const submitLabel =
|
||||
mode === "create" ? "Salvar categoria" : "Atualizar categoria";
|
||||
|
||||
return (
|
||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||
{trigger ? <DialogTrigger asChild>{trigger}</DialogTrigger> : null}
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form className="flex flex-col gap-5" onSubmit={handleSubmit}>
|
||||
<CategoryFormFields values={formState} onChange={updateField} />
|
||||
|
||||
{errorMessage && (
|
||||
<p className="text-sm text-destructive">{errorMessage}</p>
|
||||
)}
|
||||
|
||||
<DialogFooter className="gap-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setDialogOpen(false)}
|
||||
disabled={isPending}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button type="submit" disabled={isPending}>
|
||||
{isPending ? "Salvando..." : submitLabel}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
128
components/categorias/category-form-fields.tsx
Normal file
128
components/categorias/category-form-fields.tsx
Normal file
@@ -0,0 +1,128 @@
|
||||
"use client";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
CATEGORY_TYPE_LABEL,
|
||||
CATEGORY_TYPES,
|
||||
} from "@/lib/categorias/constants";
|
||||
import { getCategoryIconOptions } from "@/lib/categorias/icons";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import { RiMoreLine } from "@remixicon/react";
|
||||
import { useState } from "react";
|
||||
|
||||
import { CategoryIcon } from "./category-icon";
|
||||
import { TypeSelectContent } from "./category-select-items";
|
||||
import type { CategoryFormValues } from "./types";
|
||||
|
||||
interface CategoryFormFieldsProps {
|
||||
values: CategoryFormValues;
|
||||
onChange: (field: keyof CategoryFormValues, value: string) => void;
|
||||
}
|
||||
|
||||
export function CategoryFormFields({
|
||||
values,
|
||||
onChange,
|
||||
}: CategoryFormFieldsProps) {
|
||||
const [popoverOpen, setPopoverOpen] = useState(false);
|
||||
const iconOptions = getCategoryIconOptions();
|
||||
|
||||
const handleIconSelect = (icon: string) => {
|
||||
onChange("icon", icon);
|
||||
setPopoverOpen(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-1 gap-4">
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="category-name">Nome</Label>
|
||||
<Input
|
||||
id="category-name"
|
||||
value={values.name}
|
||||
onChange={(event) => onChange("name", event.target.value)}
|
||||
placeholder="Ex.: Alimentação"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="category-type">Tipo da categoria</Label>
|
||||
<Select
|
||||
value={values.type}
|
||||
onValueChange={(value) => onChange("type", value)}
|
||||
>
|
||||
<SelectTrigger id="category-type" className="w-full">
|
||||
<SelectValue placeholder="Selecione o tipo">
|
||||
{values.type && (
|
||||
<TypeSelectContent label={CATEGORY_TYPE_LABEL[values.type]} />
|
||||
)}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{CATEGORY_TYPES.map((type) => (
|
||||
<SelectItem key={type} value={type}>
|
||||
<TypeSelectContent label={CATEGORY_TYPE_LABEL[type]} />
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>Ícone</Label>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex size-12 items-center justify-center rounded-lg border bg-muted/30 text-primary">
|
||||
{values.icon ? (
|
||||
<CategoryIcon name={values.icon} className="size-7" />
|
||||
) : (
|
||||
<RiMoreLine className="size-6 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
<Popover open={popoverOpen} onOpenChange={setPopoverOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button type="button" variant="outline" className="flex-1">
|
||||
Selecionar ícone
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-[480px] p-3" align="start">
|
||||
<div className="grid max-h-96 grid-cols-8 gap-2 overflow-y-auto">
|
||||
{iconOptions.map((option) => (
|
||||
<button
|
||||
key={option.value}
|
||||
type="button"
|
||||
onClick={() => handleIconSelect(option.value)}
|
||||
className={cn(
|
||||
"flex size-12 items-center justify-center rounded-lg border transition-all hover:border-primary hover:bg-primary/5",
|
||||
values.icon === option.value
|
||||
? "border-primary bg-primary/10 text-primary"
|
||||
: "border-border text-muted-foreground hover:text-primary"
|
||||
)}
|
||||
title={option.label}
|
||||
>
|
||||
<CategoryIcon name={option.value} className="size-6" />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Escolha um ícone que represente melhor esta categoria.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
28
components/categorias/category-icon.tsx
Normal file
28
components/categorias/category-icon.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
"use client";
|
||||
|
||||
import type { RemixiconComponentType } from "@remixicon/react";
|
||||
import * as RemixIcons from "@remixicon/react";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
|
||||
const ICONS = RemixIcons as Record<string, RemixiconComponentType | undefined>;
|
||||
const FALLBACK_ICON = ICONS["RiPriceTag3Line"];
|
||||
|
||||
interface CategoryIconProps {
|
||||
name?: string | null;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function CategoryIcon({ name, className }: CategoryIconProps) {
|
||||
const IconComponent =
|
||||
(name ? ICONS[name] : undefined) ?? FALLBACK_ICON ?? null;
|
||||
|
||||
if (!IconComponent) {
|
||||
return (
|
||||
<span className={cn("text-xs text-muted-foreground", className)}>
|
||||
{name ?? "Categoria"}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
return <IconComponent className={cn("size-5", className)} aria-hidden />;
|
||||
}
|
||||
20
components/categorias/category-select-items.tsx
Normal file
20
components/categorias/category-select-items.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
"use client";
|
||||
|
||||
import DotIcon from "@/components/dot-icon";
|
||||
|
||||
export function TypeSelectContent({ label }: { label: string }) {
|
||||
const isReceita = label === "Receita";
|
||||
|
||||
return (
|
||||
<span className="flex items-center gap-2">
|
||||
<DotIcon
|
||||
bg_dot={
|
||||
isReceita
|
||||
? "bg-emerald-600 dark:bg-emerald-300"
|
||||
: "bg-rose-600 dark:bg-rose-300"
|
||||
}
|
||||
/>
|
||||
<span>{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
18
components/categorias/types.ts
Normal file
18
components/categorias/types.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
export {
|
||||
CATEGORY_TYPES,
|
||||
CATEGORY_TYPE_LABEL,
|
||||
} from "@/lib/categorias/constants";
|
||||
export type { CategoryType } from "@/lib/categorias/constants";
|
||||
|
||||
export type Category = {
|
||||
id: string;
|
||||
name: string;
|
||||
type: CategoryType;
|
||||
icon: string | null;
|
||||
};
|
||||
|
||||
export type CategoryFormValues = {
|
||||
name: string;
|
||||
type: CategoryType;
|
||||
icon: string;
|
||||
};
|
||||
116
components/confirm-action-dialog.tsx
Normal file
116
components/confirm-action-dialog.tsx
Normal file
@@ -0,0 +1,116 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import { type VariantProps } from "class-variance-authority";
|
||||
import { useCallback, useMemo, useState, useTransition } from "react";
|
||||
|
||||
interface ConfirmActionDialogProps {
|
||||
trigger?: React.ReactNode;
|
||||
title: string;
|
||||
description?: string;
|
||||
confirmLabel?: string;
|
||||
cancelLabel?: string;
|
||||
pendingLabel?: string;
|
||||
confirmVariant?: VariantProps<typeof buttonVariants>["variant"];
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
onConfirm?: () => Promise<void> | void;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function ConfirmActionDialog({
|
||||
trigger,
|
||||
title,
|
||||
description,
|
||||
confirmLabel = "Confirmar",
|
||||
cancelLabel = "Cancelar",
|
||||
pendingLabel,
|
||||
confirmVariant = "default",
|
||||
open,
|
||||
onOpenChange,
|
||||
onConfirm,
|
||||
disabled = false,
|
||||
className,
|
||||
}: ConfirmActionDialogProps) {
|
||||
const [internalOpen, setInternalOpen] = useState(false);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const dialogOpen = open ?? internalOpen;
|
||||
|
||||
const setDialogOpen = useCallback(
|
||||
(value: boolean) => {
|
||||
if (open === undefined) {
|
||||
setInternalOpen(value);
|
||||
}
|
||||
onOpenChange?.(value);
|
||||
},
|
||||
[onOpenChange, open]
|
||||
);
|
||||
|
||||
const resolvedPendingLabel = useMemo(
|
||||
() => pendingLabel ?? confirmLabel,
|
||||
[pendingLabel, confirmLabel]
|
||||
);
|
||||
|
||||
const handleConfirm = useCallback(() => {
|
||||
if (!onConfirm) {
|
||||
setDialogOpen(false);
|
||||
return;
|
||||
}
|
||||
|
||||
startTransition(async () => {
|
||||
try {
|
||||
await onConfirm();
|
||||
setDialogOpen(false);
|
||||
} catch {
|
||||
// Mantém o diálogo aberto para que o chamador trate o erro.
|
||||
}
|
||||
});
|
||||
}, [onConfirm, setDialogOpen]);
|
||||
|
||||
return (
|
||||
<AlertDialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||
{trigger ? (
|
||||
<AlertDialogTrigger asChild>{trigger}</AlertDialogTrigger>
|
||||
) : null}
|
||||
<AlertDialogContent className={className}>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{title}</AlertDialogTitle>
|
||||
{description ? (
|
||||
<AlertDialogDescription>{description}</AlertDialogDescription>
|
||||
) : null}
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel
|
||||
disabled={isPending || disabled}
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
{cancelLabel}
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleConfirm}
|
||||
disabled={isPending || disabled}
|
||||
className={cn(
|
||||
buttonVariants({ variant: confirmVariant }),
|
||||
"w-full sm:w-auto"
|
||||
)}
|
||||
>
|
||||
{isPending ? resolvedPendingLabel : confirmLabel}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
128
components/contas/account-card.tsx
Normal file
128
components/contas/account-card.tsx
Normal file
@@ -0,0 +1,128 @@
|
||||
"use client";
|
||||
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import {
|
||||
RiArrowLeftRightLine,
|
||||
RiDeleteBin5Line,
|
||||
RiEyeOffLine,
|
||||
RiFileList2Line,
|
||||
RiPencilLine,
|
||||
} from "@remixicon/react";
|
||||
import type React from "react";
|
||||
import MoneyValues from "../money-values";
|
||||
import { Card, CardContent, CardFooter } from "../ui/card";
|
||||
|
||||
interface AccountCardProps {
|
||||
accountName: string;
|
||||
accountType: string;
|
||||
balance: number;
|
||||
status?: string;
|
||||
icon?: React.ReactNode;
|
||||
excludeFromBalance?: boolean;
|
||||
onViewStatement?: () => void;
|
||||
onEdit?: () => void;
|
||||
onRemove?: () => void;
|
||||
onTransfer?: () => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function AccountCard({
|
||||
accountName,
|
||||
accountType,
|
||||
balance,
|
||||
status,
|
||||
icon,
|
||||
excludeFromBalance,
|
||||
onViewStatement,
|
||||
onEdit,
|
||||
onRemove,
|
||||
onTransfer,
|
||||
className,
|
||||
}: AccountCardProps) {
|
||||
const isInactive = status?.toLowerCase() === "inativa";
|
||||
|
||||
const actions = [
|
||||
{
|
||||
label: "editar",
|
||||
icon: <RiPencilLine className="size-4" aria-hidden />,
|
||||
onClick: onEdit,
|
||||
variant: "default" as const,
|
||||
},
|
||||
{
|
||||
label: "extrato",
|
||||
icon: <RiFileList2Line className="size-4" aria-hidden />,
|
||||
onClick: onViewStatement,
|
||||
variant: "default" as const,
|
||||
},
|
||||
{
|
||||
label: "transferir",
|
||||
icon: <RiArrowLeftRightLine className="size-4" aria-hidden />,
|
||||
onClick: onTransfer,
|
||||
variant: "default" as const,
|
||||
},
|
||||
{
|
||||
label: "remover",
|
||||
icon: <RiDeleteBin5Line className="size-4" aria-hidden />,
|
||||
onClick: onRemove,
|
||||
variant: "destructive" as const,
|
||||
},
|
||||
].filter((action) => typeof action.onClick === "function");
|
||||
|
||||
return (
|
||||
<Card className={cn("h-full w-96 gap-0", className)}>
|
||||
<CardContent className="flex flex-1 flex-col gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
{icon ? (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-center",
|
||||
isInactive && "[&_img]:grayscale [&_img]:opacity-40"
|
||||
)}
|
||||
>
|
||||
{icon}
|
||||
</div>
|
||||
) : null}
|
||||
<h2 className="text-lg font-semibold text-foreground">
|
||||
{accountName}
|
||||
</h2>
|
||||
{excludeFromBalance ? (
|
||||
<div
|
||||
className="flex items-center gap-1 text-muted-foreground"
|
||||
title="Excluída do saldo geral"
|
||||
>
|
||||
<RiEyeOffLine className="size-4" aria-hidden />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm text-muted-foreground">Saldo</p>
|
||||
<p className="text-3xl text-foreground">
|
||||
<MoneyValues amount={balance} className="text-3xl" />
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">{accountType}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
{actions.length > 0 ? (
|
||||
<CardFooter className="flex flex-wrap gap-3 px-6 pt-6 text-sm">
|
||||
{actions.map(({ label, icon, onClick, variant }) => (
|
||||
<button
|
||||
key={label}
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className={cn(
|
||||
"flex items-center gap-1 font-medium transition-opacity hover:opacity-80",
|
||||
variant === "destructive" ? "text-destructive" : "text-primary"
|
||||
)}
|
||||
aria-label={`${label} conta`}
|
||||
>
|
||||
{icon}
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</CardFooter>
|
||||
) : null}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
268
components/contas/account-dialog.tsx
Normal file
268
components/contas/account-dialog.tsx
Normal file
@@ -0,0 +1,268 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
createAccountAction,
|
||||
updateAccountAction,
|
||||
} from "@/app/(dashboard)/contas/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
useTransition,
|
||||
} from "react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { LogoPickerDialog, LogoPickerTrigger } from "@/components/logo-picker";
|
||||
import { useControlledState } from "@/hooks/use-controlled-state";
|
||||
import { useFormState } from "@/hooks/use-form-state";
|
||||
import { useLogoSelection } from "@/hooks/use-logo-selection";
|
||||
import { deriveNameFromLogo, normalizeLogo } from "@/lib/logo";
|
||||
import { formatInitialBalanceInput } from "@/lib/utils/currency";
|
||||
|
||||
import { AccountFormFields } from "./account-form-fields";
|
||||
import type { Account, AccountFormValues } from "./types";
|
||||
|
||||
const DEFAULT_ACCOUNT_TYPES = [
|
||||
"Conta Corrente",
|
||||
"Conta Poupança",
|
||||
"Carteira Digital",
|
||||
"Conta Investimento",
|
||||
"Cartão Pré-pago",
|
||||
] as const;
|
||||
|
||||
const DEFAULT_ACCOUNT_STATUS = ["Ativa", "Inativa"] as const;
|
||||
|
||||
interface AccountDialogProps {
|
||||
mode: "create" | "update";
|
||||
trigger?: React.ReactNode;
|
||||
logoOptions: string[];
|
||||
account?: Account;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
const buildInitialValues = ({
|
||||
account,
|
||||
logoOptions,
|
||||
accountTypes,
|
||||
accountStatuses,
|
||||
}: {
|
||||
account?: Account;
|
||||
logoOptions: string[];
|
||||
accountTypes: string[];
|
||||
accountStatuses: string[];
|
||||
}): AccountFormValues => {
|
||||
const fallbackLogo = logoOptions[0] ?? "";
|
||||
const selectedLogo = normalizeLogo(account?.logo) || fallbackLogo;
|
||||
const derivedName = deriveNameFromLogo(selectedLogo);
|
||||
|
||||
return {
|
||||
name: account?.name ?? derivedName,
|
||||
accountType: account?.accountType ?? accountTypes[0] ?? "",
|
||||
status: account?.status ?? accountStatuses[0] ?? "",
|
||||
note: account?.note ?? "",
|
||||
logo: selectedLogo,
|
||||
initialBalance: formatInitialBalanceInput(account?.initialBalance ?? 0),
|
||||
excludeFromBalance: account?.excludeFromBalance ?? false,
|
||||
};
|
||||
};
|
||||
|
||||
export function AccountDialog({
|
||||
mode,
|
||||
trigger,
|
||||
logoOptions,
|
||||
account,
|
||||
open,
|
||||
onOpenChange,
|
||||
}: AccountDialogProps) {
|
||||
const [logoDialogOpen, setLogoDialogOpen] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
// Use controlled state hook for dialog open state
|
||||
const [dialogOpen, setDialogOpen] = useControlledState(
|
||||
open,
|
||||
false,
|
||||
onOpenChange
|
||||
);
|
||||
|
||||
const accountTypes = useMemo(() => {
|
||||
const values = new Set<string>(DEFAULT_ACCOUNT_TYPES);
|
||||
if (account?.accountType) {
|
||||
values.add(account.accountType);
|
||||
}
|
||||
return Array.from(values);
|
||||
}, [account?.accountType]);
|
||||
|
||||
const accountStatuses = useMemo(() => {
|
||||
const values = new Set<string>(DEFAULT_ACCOUNT_STATUS);
|
||||
if (account?.status) {
|
||||
values.add(account.status);
|
||||
}
|
||||
return Array.from(values);
|
||||
}, [account?.status]);
|
||||
|
||||
const initialState = useMemo(
|
||||
() =>
|
||||
buildInitialValues({
|
||||
account,
|
||||
logoOptions,
|
||||
accountTypes,
|
||||
accountStatuses,
|
||||
}),
|
||||
[account, logoOptions, accountTypes, accountStatuses]
|
||||
);
|
||||
|
||||
// Use form state hook for form management
|
||||
const { formState, updateField, updateFields, setFormState } =
|
||||
useFormState<AccountFormValues>(initialState);
|
||||
|
||||
// Reset form when dialog opens
|
||||
useEffect(() => {
|
||||
if (dialogOpen) {
|
||||
setFormState(initialState);
|
||||
setErrorMessage(null);
|
||||
}
|
||||
}, [dialogOpen, initialState, setFormState]);
|
||||
|
||||
// Close logo dialog when main dialog closes
|
||||
useEffect(() => {
|
||||
if (!dialogOpen) {
|
||||
setErrorMessage(null);
|
||||
setLogoDialogOpen(false);
|
||||
}
|
||||
}, [dialogOpen]);
|
||||
|
||||
// Use logo selection hook
|
||||
const handleLogoSelection = useLogoSelection({
|
||||
mode,
|
||||
currentLogo: formState.logo,
|
||||
currentName: formState.name,
|
||||
onUpdate: (updates) => {
|
||||
updateFields(updates);
|
||||
setLogoDialogOpen(false);
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
(event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setErrorMessage(null);
|
||||
|
||||
if (mode === "update" && !account?.id) {
|
||||
const message = "Conta inválida.";
|
||||
setErrorMessage(message);
|
||||
toast.error(message);
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = { ...formState };
|
||||
|
||||
if (!payload.logo) {
|
||||
setErrorMessage("Selecione um logo.");
|
||||
return;
|
||||
}
|
||||
|
||||
startTransition(async () => {
|
||||
const result =
|
||||
mode === "create"
|
||||
? await createAccountAction(payload)
|
||||
: await updateAccountAction({
|
||||
id: account?.id ?? "",
|
||||
...payload,
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
setDialogOpen(false);
|
||||
setFormState(initialState);
|
||||
return;
|
||||
}
|
||||
|
||||
setErrorMessage(result.error);
|
||||
toast.error(result.error);
|
||||
});
|
||||
},
|
||||
[account?.id, formState, initialState, mode, setDialogOpen, setFormState]
|
||||
);
|
||||
|
||||
const title = mode === "create" ? "Nova conta" : "Editar conta";
|
||||
const description =
|
||||
mode === "create"
|
||||
? "Cadastre uma nova conta para organizar seus lançamentos."
|
||||
: "Atualize as informações da conta selecionada.";
|
||||
const submitLabel = mode === "create" ? "Salvar conta" : "Atualizar conta";
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||
{trigger ? <DialogTrigger asChild>{trigger}</DialogTrigger> : null}
|
||||
<DialogContent className="sm:max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form className="flex flex-col gap-5" onSubmit={handleSubmit}>
|
||||
<div className="flex flex-col gap-2">
|
||||
<LogoPickerTrigger
|
||||
selectedLogo={formState.logo}
|
||||
disabled={logoOptions.length === 0}
|
||||
onOpen={() => {
|
||||
if (logoOptions.length > 0) {
|
||||
setLogoDialogOpen(true);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<AccountFormFields
|
||||
values={formState}
|
||||
accountTypes={accountTypes}
|
||||
accountStatuses={accountStatuses}
|
||||
onChange={updateField}
|
||||
showInitialBalance={mode === "create"}
|
||||
/>
|
||||
|
||||
{errorMessage && (
|
||||
<p className="text-sm text-destructive">{errorMessage}</p>
|
||||
)}
|
||||
|
||||
<DialogFooter className="gap-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setDialogOpen(false)}
|
||||
disabled={isPending}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button type="submit" disabled={isPending}>
|
||||
{isPending ? "Salvando..." : submitLabel}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<LogoPickerDialog
|
||||
open={logoDialogOpen}
|
||||
logos={logoOptions}
|
||||
value={formState.logo}
|
||||
onOpenChange={setLogoDialogOpen}
|
||||
onSelect={handleLogoSelection}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
123
components/contas/account-form-fields.tsx
Normal file
123
components/contas/account-form-fields.tsx
Normal file
@@ -0,0 +1,123 @@
|
||||
"use client";
|
||||
|
||||
import { CurrencyInput } from "@/components/ui/currency-input";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { StatusSelectContent } from "./account-select-items";
|
||||
|
||||
import type { AccountFormValues } from "./types";
|
||||
|
||||
interface AccountFormFieldsProps {
|
||||
values: AccountFormValues;
|
||||
accountTypes: string[];
|
||||
accountStatuses: string[];
|
||||
onChange: (field: keyof AccountFormValues, value: string) => void;
|
||||
showInitialBalance?: boolean;
|
||||
}
|
||||
|
||||
export function AccountFormFields({
|
||||
values,
|
||||
accountTypes,
|
||||
accountStatuses,
|
||||
onChange,
|
||||
showInitialBalance = true,
|
||||
}: AccountFormFieldsProps) {
|
||||
return (
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="account-name">Nome</Label>
|
||||
<Input
|
||||
id="account-name"
|
||||
value={values.name}
|
||||
onChange={(event) => onChange("name", event.target.value)}
|
||||
placeholder="Ex.: Nubank"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="account-type">Tipo de conta</Label>
|
||||
<Select
|
||||
value={values.accountType}
|
||||
onValueChange={(value) => onChange("accountType", value)}
|
||||
>
|
||||
<SelectTrigger id="account-type" className="w-full">
|
||||
<SelectValue placeholder="Selecione o tipo" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{accountTypes.map((type) => (
|
||||
<SelectItem key={type} value={type}>
|
||||
{type}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2 sm:col-span-2">
|
||||
<Label htmlFor="account-status">Status</Label>
|
||||
<Select
|
||||
value={values.status}
|
||||
onValueChange={(value) => onChange("status", value)}
|
||||
>
|
||||
<SelectTrigger id="account-status" className="w-full">
|
||||
<SelectValue placeholder="Selecione o status">
|
||||
{values.status && <StatusSelectContent label={values.status} />}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{accountStatuses.map((status) => (
|
||||
<SelectItem key={status} value={status}>
|
||||
<StatusSelectContent label={status} />
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{showInitialBalance ? (
|
||||
<div className="flex flex-col gap-2 sm:col-span-2">
|
||||
<Label htmlFor="account-initial-balance">Saldo inicial</Label>
|
||||
<CurrencyInput
|
||||
id="account-initial-balance"
|
||||
value={values.initialBalance}
|
||||
onValueChange={(value) => onChange("initialBalance", value)}
|
||||
placeholder="R$ 0,00"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="flex flex-col gap-2 sm:col-span-2">
|
||||
<Label htmlFor="account-note">Anotação</Label>
|
||||
<Textarea
|
||||
id="account-note"
|
||||
value={values.note}
|
||||
onChange={(event) => onChange("note", event.target.value)}
|
||||
placeholder="Informações adicionais sobre a conta"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 sm:col-span-2">
|
||||
<Checkbox
|
||||
id="exclude-from-balance"
|
||||
checked={values.excludeFromBalance}
|
||||
onCheckedChange={(checked) =>
|
||||
onChange("excludeFromBalance", checked ? "true" : "false")
|
||||
}
|
||||
/>
|
||||
<Label htmlFor="exclude-from-balance" className="cursor-pointer text-sm font-normal">
|
||||
Excluir do saldo total (útil para contas de investimento ou reserva)
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
20
components/contas/account-select-items.tsx
Normal file
20
components/contas/account-select-items.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
"use client";
|
||||
|
||||
import DotIcon from "@/components/dot-icon";
|
||||
|
||||
export function StatusSelectContent({ label }: { label: string }) {
|
||||
const isActive = label === "Ativa";
|
||||
|
||||
return (
|
||||
<span className="flex items-center gap-2">
|
||||
<DotIcon
|
||||
bg_dot={
|
||||
isActive
|
||||
? "bg-emerald-600 dark:bg-emerald-300"
|
||||
: "bg-slate-400 dark:bg-slate-500"
|
||||
}
|
||||
/>
|
||||
<span>{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
219
components/contas/account-statement-card.tsx
Normal file
219
components/contas/account-statement-card.tsx
Normal file
@@ -0,0 +1,219 @@
|
||||
"use client";
|
||||
import MoneyValues from "@/components/money-values";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import { RiInformationLine } from "@remixicon/react";
|
||||
import Image from "next/image";
|
||||
import { useMemo, type ReactNode } from "react";
|
||||
|
||||
type DetailValue = string | number | ReactNode;
|
||||
|
||||
type AccountStatementCardProps = {
|
||||
accountName: string;
|
||||
accountType: string;
|
||||
status: string;
|
||||
periodLabel: string;
|
||||
currentBalance: number;
|
||||
openingBalance: number;
|
||||
totalIncomes: number;
|
||||
totalExpenses: number;
|
||||
logo?: string | null;
|
||||
actions?: React.ReactNode;
|
||||
};
|
||||
|
||||
const resolveLogoPath = (logo?: string | null) => {
|
||||
if (!logo) return null;
|
||||
if (
|
||||
logo.startsWith("http://") ||
|
||||
logo.startsWith("https://") ||
|
||||
logo.startsWith("data:")
|
||||
) {
|
||||
return logo;
|
||||
}
|
||||
|
||||
return logo.startsWith("/") ? logo : `/logos/${logo}`;
|
||||
};
|
||||
|
||||
const getAccountStatusBadgeVariant = (
|
||||
status: string
|
||||
): "success" | "secondary" => {
|
||||
const normalizedStatus = status.toLowerCase();
|
||||
if (normalizedStatus === "ativa") {
|
||||
return "success";
|
||||
}
|
||||
return "outline";
|
||||
};
|
||||
|
||||
export function AccountStatementCard({
|
||||
accountName,
|
||||
accountType,
|
||||
status,
|
||||
periodLabel,
|
||||
currentBalance,
|
||||
openingBalance,
|
||||
totalIncomes,
|
||||
totalExpenses,
|
||||
logo,
|
||||
actions,
|
||||
}: AccountStatementCardProps) {
|
||||
const logoPath = useMemo(() => resolveLogoPath(logo), [logo]);
|
||||
|
||||
const formatCurrency = (value: number) =>
|
||||
value.toLocaleString("pt-BR", {
|
||||
style: "currency",
|
||||
currency: "BRL",
|
||||
});
|
||||
|
||||
return (
|
||||
<Card className="border">
|
||||
<CardHeader className="flex flex-col gap-3">
|
||||
<div className="flex items-start gap-3">
|
||||
{logoPath ? (
|
||||
<div className="flex size-12 shrink-0 items-center justify-center overflow-hidden rounded-lg border border-border/60 bg-background">
|
||||
<Image
|
||||
src={logoPath}
|
||||
alt={`Logo da conta ${accountName}`}
|
||||
width={48}
|
||||
height={48}
|
||||
className="h-full w-full object-contain"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="flex w-full items-start justify-between gap-3">
|
||||
<div className="space-y-1">
|
||||
<CardTitle className="text-xl font-semibold text-foreground">
|
||||
{accountName}
|
||||
</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Extrato de {periodLabel}
|
||||
</p>
|
||||
</div>
|
||||
{actions ? <div className="shrink-0">{actions}</div> : null}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-4 border-t border-border/60 border-dashed pt-4">
|
||||
{/* Destaque Principal */}
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<DetailItem
|
||||
label="Saldo atual"
|
||||
value={<MoneyValues amount={currentBalance} className="text-2xl" />}
|
||||
tooltip="Saldo inicial do período + entradas - saídas realizadas neste mês."
|
||||
/>
|
||||
<DetailItem
|
||||
label="Status da conta"
|
||||
value={
|
||||
<div className="flex items-center">
|
||||
<Badge
|
||||
variant={getAccountStatusBadgeVariant(status)}
|
||||
className="text-xs"
|
||||
>
|
||||
{status}
|
||||
</Badge>
|
||||
</div>
|
||||
}
|
||||
tooltip="Indica se a conta está ativa para lançamentos ou foi desativada."
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Movimentação do Período */}
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
|
||||
<DetailItem
|
||||
label="Saldo inicial"
|
||||
value={
|
||||
<MoneyValues
|
||||
amount={openingBalance}
|
||||
className="font-medium text-foreground"
|
||||
/>
|
||||
}
|
||||
tooltip="Saldo inicial cadastrado na conta somado aos lançamentos pagos anteriores a este mês."
|
||||
/>
|
||||
<DetailItem
|
||||
label="Entradas"
|
||||
value={
|
||||
<span className="font-medium text-emerald-600">
|
||||
{formatCurrency(totalIncomes)}
|
||||
</span>
|
||||
}
|
||||
tooltip="Total de receitas deste mês classificadas como pagas para esta conta."
|
||||
/>
|
||||
<DetailItem
|
||||
label="Saídas"
|
||||
value={
|
||||
<span className="font-medium text-destructive">
|
||||
{formatCurrency(totalExpenses)}
|
||||
</span>
|
||||
}
|
||||
tooltip="Total de despesas pagas neste mês (considerando divisão entre pagadores)."
|
||||
/>
|
||||
<DetailItem
|
||||
label="Resultado"
|
||||
value={
|
||||
<MoneyValues
|
||||
amount={totalIncomes - totalExpenses}
|
||||
className={cn(
|
||||
"font-semibold",
|
||||
totalIncomes - totalExpenses >= 0
|
||||
? "text-emerald-600"
|
||||
: "text-destructive"
|
||||
)}
|
||||
/>
|
||||
}
|
||||
tooltip="Diferença entre entradas e saídas do mês; positivo indica saldo crescente."
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Informações da Conta */}
|
||||
<DetailItem
|
||||
label="Tipo da conta"
|
||||
value={accountType}
|
||||
tooltip="Classificação definida na criação da conta (corrente, poupança, etc.)."
|
||||
className="sm:w-1/2"
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function DetailItem({
|
||||
label,
|
||||
value,
|
||||
className,
|
||||
tooltip,
|
||||
}: {
|
||||
label: string;
|
||||
value: DetailValue;
|
||||
className?: string;
|
||||
tooltip?: string;
|
||||
}) {
|
||||
return (
|
||||
<div className={cn("space-y-1", className)}>
|
||||
<span className="flex items-center gap-1 text-xs font-medium uppercase text-muted-foreground/80">
|
||||
{label}
|
||||
{tooltip ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<RiInformationLine className="size-3.5 cursor-help text-muted-foreground/60" />
|
||||
</TooltipTrigger>
|
||||
<TooltipContent
|
||||
side="top"
|
||||
align="start"
|
||||
className="max-w-xs text-xs"
|
||||
>
|
||||
{tooltip}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</span>
|
||||
<div className="text-base text-foreground">{value}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
206
components/contas/accounts-page.tsx
Normal file
206
components/contas/accounts-page.tsx
Normal file
@@ -0,0 +1,206 @@
|
||||
"use client";
|
||||
|
||||
import { deleteAccountAction } from "@/app/(dashboard)/contas/actions";
|
||||
import { ConfirmActionDialog } from "@/components/confirm-action-dialog";
|
||||
import { AccountCard } from "@/components/contas/account-card";
|
||||
import { EmptyState } from "@/components/empty-state";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { getCurrentPeriod } from "@/lib/utils/period";
|
||||
import { RiAddCircleLine, RiBankLine } from "@remixicon/react";
|
||||
import Image from "next/image";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Card } from "../ui/card";
|
||||
import { AccountDialog } from "./account-dialog";
|
||||
import { TransferDialog } from "./transfer-dialog";
|
||||
import type { Account } from "./types";
|
||||
|
||||
interface AccountsPageProps {
|
||||
accounts: Account[];
|
||||
logoOptions: string[];
|
||||
}
|
||||
|
||||
const resolveLogoSrc = (logo: string | null) => {
|
||||
if (!logo) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const fileName = logo.split("/").filter(Boolean).pop() ?? logo;
|
||||
return `/logos/${fileName}`;
|
||||
};
|
||||
|
||||
export function AccountsPage({ accounts, logoOptions }: AccountsPageProps) {
|
||||
const router = useRouter();
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [selectedAccount, setSelectedAccount] = useState<Account | null>(null);
|
||||
const [removeOpen, setRemoveOpen] = useState(false);
|
||||
const [accountToRemove, setAccountToRemove] = useState<Account | null>(null);
|
||||
const [transferOpen, setTransferOpen] = useState(false);
|
||||
const [transferFromAccount, setTransferFromAccount] =
|
||||
useState<Account | null>(null);
|
||||
|
||||
const hasAccounts = accounts.length > 0;
|
||||
|
||||
const orderedAccounts = useMemo(() => {
|
||||
return [...accounts].sort((a, b) => {
|
||||
// Coloca inativas no final
|
||||
const aIsInactive = a.status?.toLowerCase() === "inativa";
|
||||
const bIsInactive = b.status?.toLowerCase() === "inativa";
|
||||
|
||||
if (aIsInactive && !bIsInactive) return 1;
|
||||
if (!aIsInactive && bIsInactive) return -1;
|
||||
|
||||
// Mesma ordem alfabética dentro de cada grupo
|
||||
return a.name.localeCompare(b.name, "pt-BR", { sensitivity: "base" });
|
||||
});
|
||||
}, [accounts]);
|
||||
|
||||
const handleEdit = useCallback((account: Account) => {
|
||||
setSelectedAccount(account);
|
||||
setEditOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleEditOpenChange = useCallback((open: boolean) => {
|
||||
setEditOpen(open);
|
||||
if (!open) {
|
||||
setSelectedAccount(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleRemoveRequest = useCallback((account: Account) => {
|
||||
setAccountToRemove(account);
|
||||
setRemoveOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleRemoveOpenChange = useCallback((open: boolean) => {
|
||||
setRemoveOpen(open);
|
||||
if (!open) {
|
||||
setAccountToRemove(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleRemoveConfirm = useCallback(async () => {
|
||||
if (!accountToRemove) {
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await deleteAccountAction({ id: accountToRemove.id });
|
||||
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
return;
|
||||
}
|
||||
|
||||
toast.error(result.error);
|
||||
throw new Error(result.error);
|
||||
}, [accountToRemove]);
|
||||
|
||||
const handleTransferRequest = useCallback((account: Account) => {
|
||||
setTransferFromAccount(account);
|
||||
setTransferOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleTransferOpenChange = useCallback((open: boolean) => {
|
||||
setTransferOpen(open);
|
||||
if (!open) {
|
||||
setTransferFromAccount(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const removeTitle = accountToRemove
|
||||
? `Remover conta "${accountToRemove.name}"?`
|
||||
: "Remover conta?";
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex w-full flex-col gap-6">
|
||||
<div className="flex justify-start">
|
||||
<AccountDialog
|
||||
mode="create"
|
||||
logoOptions={logoOptions}
|
||||
trigger={
|
||||
<Button>
|
||||
<RiAddCircleLine className="size-4" />
|
||||
Nova conta
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{hasAccounts ? (
|
||||
<div className="flex flex-wrap gap-4">
|
||||
{orderedAccounts.map((account) => {
|
||||
const logoSrc = resolveLogoSrc(account.logo);
|
||||
|
||||
return (
|
||||
<AccountCard
|
||||
key={account.id}
|
||||
accountName={account.name}
|
||||
accountType={`${account.accountType} • ${account.status}`}
|
||||
balance={account.balance ?? account.initialBalance ?? 0}
|
||||
status={account.status}
|
||||
excludeFromBalance={account.excludeFromBalance}
|
||||
icon={
|
||||
logoSrc ? (
|
||||
<Image
|
||||
src={logoSrc}
|
||||
alt={`Logo da conta ${account.name}`}
|
||||
width={42}
|
||||
height={42}
|
||||
className="rounded-lg"
|
||||
/>
|
||||
) : undefined
|
||||
}
|
||||
onEdit={() => handleEdit(account)}
|
||||
onRemove={() => handleRemoveRequest(account)}
|
||||
onTransfer={() => handleTransferRequest(account)}
|
||||
onViewStatement={() =>
|
||||
router.push(`/contas/${account.id}/extrato`)
|
||||
}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<Card className="flex min-h-[50vh] w-full items-center justify-center py-12">
|
||||
<EmptyState
|
||||
media={<RiBankLine className="size-6 text-primary" />}
|
||||
title="Nenhuma conta cadastrada"
|
||||
description="Cadastre sua primeira conta para começar a organizar os lançamentos."
|
||||
/>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<AccountDialog
|
||||
mode="update"
|
||||
logoOptions={logoOptions}
|
||||
account={selectedAccount ?? undefined}
|
||||
open={editOpen && !!selectedAccount}
|
||||
onOpenChange={handleEditOpenChange}
|
||||
/>
|
||||
|
||||
<ConfirmActionDialog
|
||||
open={removeOpen && !!accountToRemove}
|
||||
onOpenChange={handleRemoveOpenChange}
|
||||
title={removeTitle}
|
||||
description="Ao remover esta conta, todos os dados relacionados a ela serão perdidos."
|
||||
confirmLabel="Remover conta"
|
||||
pendingLabel="Removendo..."
|
||||
confirmVariant="destructive"
|
||||
onConfirm={handleRemoveConfirm}
|
||||
/>
|
||||
|
||||
{transferFromAccount && (
|
||||
<TransferDialog
|
||||
accounts={accounts}
|
||||
fromAccountId={transferFromAccount.id}
|
||||
currentPeriod={getCurrentPeriod()}
|
||||
open={transferOpen}
|
||||
onOpenChange={handleTransferOpenChange}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
223
components/contas/transfer-dialog.tsx
Normal file
223
components/contas/transfer-dialog.tsx
Normal file
@@ -0,0 +1,223 @@
|
||||
"use client";
|
||||
|
||||
import { transferBetweenAccountsAction } from "@/app/(dashboard)/contas/actions";
|
||||
import type { AccountData } from "@/app/(dashboard)/contas/data";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CurrencyInput } from "@/components/ui/currency-input";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { useControlledState } from "@/hooks/use-controlled-state";
|
||||
import { formatDateForDb } from "@/lib/utils/date";
|
||||
import { useMemo, useState, useTransition } from "react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
interface TransferDialogProps {
|
||||
trigger?: React.ReactNode;
|
||||
accounts: AccountData[];
|
||||
fromAccountId: string;
|
||||
currentPeriod: string;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function TransferDialog({
|
||||
trigger,
|
||||
accounts,
|
||||
fromAccountId,
|
||||
currentPeriod,
|
||||
open,
|
||||
onOpenChange,
|
||||
}: TransferDialogProps) {
|
||||
const [dialogOpen, setDialogOpen] = useControlledState(
|
||||
open,
|
||||
false,
|
||||
onOpenChange
|
||||
);
|
||||
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
|
||||
// Form state
|
||||
const [toAccountId, setToAccountId] = useState("");
|
||||
const [amount, setAmount] = useState("");
|
||||
const [date, setDate] = useState(formatDateForDb(new Date()));
|
||||
const [period, setPeriod] = useState(currentPeriod);
|
||||
|
||||
// Available destination accounts (exclude source account)
|
||||
const availableAccounts = useMemo(
|
||||
() => accounts.filter((account) => account.id !== fromAccountId),
|
||||
[accounts, fromAccountId]
|
||||
);
|
||||
|
||||
// Source account info
|
||||
const fromAccount = useMemo(
|
||||
() => accounts.find((account) => account.id === fromAccountId),
|
||||
[accounts, fromAccountId]
|
||||
);
|
||||
|
||||
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setErrorMessage(null);
|
||||
|
||||
if (!toAccountId) {
|
||||
setErrorMessage("Selecione a conta de destino.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (toAccountId === fromAccountId) {
|
||||
setErrorMessage("Selecione uma conta de destino diferente da origem.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!amount || parseFloat(amount.replace(",", ".")) <= 0) {
|
||||
setErrorMessage("Informe um valor válido maior que zero.");
|
||||
return;
|
||||
}
|
||||
|
||||
startTransition(async () => {
|
||||
const result = await transferBetweenAccountsAction({
|
||||
fromAccountId,
|
||||
toAccountId,
|
||||
amount,
|
||||
date: new Date(date),
|
||||
period,
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
setDialogOpen(false);
|
||||
// Reset form
|
||||
setToAccountId("");
|
||||
setAmount("");
|
||||
setDate(formatDateForDb(new Date()));
|
||||
setPeriod(currentPeriod);
|
||||
return;
|
||||
}
|
||||
|
||||
setErrorMessage(result.error);
|
||||
toast.error(result.error);
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||
{trigger ? <DialogTrigger asChild>{trigger}</DialogTrigger> : null}
|
||||
<DialogContent className="sm:max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Transferir entre contas</DialogTitle>
|
||||
<DialogDescription>
|
||||
Registre uma transferência de valores entre suas contas.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form className="flex flex-col gap-5" onSubmit={handleSubmit}>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="transfer-date">Data da transferência</Label>
|
||||
<Input
|
||||
id="transfer-date"
|
||||
type="date"
|
||||
value={date}
|
||||
onChange={(e) => setDate(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="transfer-period">Período</Label>
|
||||
<Input
|
||||
id="transfer-period"
|
||||
type="month"
|
||||
value={period}
|
||||
onChange={(e) => setPeriod(e.target.value)}
|
||||
placeholder="AAAA-MM"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2 sm:col-span-2">
|
||||
<Label htmlFor="transfer-amount">Valor</Label>
|
||||
<CurrencyInput
|
||||
id="transfer-amount"
|
||||
value={amount}
|
||||
onValueChange={setAmount}
|
||||
placeholder="R$ 0,00"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2 sm:col-span-2">
|
||||
<Label htmlFor="from-account">Conta de origem</Label>
|
||||
<Input
|
||||
id="from-account"
|
||||
value={fromAccount?.name || ""}
|
||||
disabled
|
||||
className="bg-muted"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2 sm:col-span-2">
|
||||
<Label htmlFor="to-account">Conta de destino</Label>
|
||||
{availableAccounts.length === 0 ? (
|
||||
<div className="rounded-md border border-border bg-muted p-3 text-sm text-muted-foreground">
|
||||
É necessário ter mais de uma conta cadastrada para realizar
|
||||
transferências.
|
||||
</div>
|
||||
) : (
|
||||
<Select value={toAccountId} onValueChange={setToAccountId}>
|
||||
<SelectTrigger id="to-account" className="w-full">
|
||||
<SelectValue placeholder="Selecione a conta de destino" />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="w-full">
|
||||
{availableAccounts.map((account) => (
|
||||
<SelectItem key={account.id} value={account.id}>
|
||||
{account.name} - {account.accountType}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{errorMessage && (
|
||||
<p className="text-sm text-destructive">{errorMessage}</p>
|
||||
)}
|
||||
|
||||
<DialogFooter className="gap-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setDialogOpen(false)}
|
||||
disabled={isPending}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={isPending || availableAccounts.length === 0}
|
||||
>
|
||||
{isPending ? "Processando..." : "Confirmar transferência"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
21
components/contas/types.ts
Normal file
21
components/contas/types.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
export type Account = {
|
||||
id: string;
|
||||
name: string;
|
||||
accountType: string;
|
||||
status: string;
|
||||
note: string | null;
|
||||
logo: string | null;
|
||||
initialBalance: number;
|
||||
balance?: number | null;
|
||||
excludeFromBalance?: boolean;
|
||||
};
|
||||
|
||||
export type AccountFormValues = {
|
||||
name: string;
|
||||
accountType: string;
|
||||
status: string;
|
||||
note: string;
|
||||
logo: string;
|
||||
initialBalance: string;
|
||||
excludeFromBalance: boolean;
|
||||
};
|
||||
364
components/dashboard/boletos-widget.tsx
Normal file
364
components/dashboard/boletos-widget.tsx
Normal file
@@ -0,0 +1,364 @@
|
||||
"use client";
|
||||
|
||||
import { toggleLancamentoSettlementAction } from "@/app/(dashboard)/lancamentos/actions";
|
||||
import MoneyValues from "@/components/money-values";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CardContent } from "@/components/ui/card";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter as ModalFooter,
|
||||
} from "@/components/ui/dialog";
|
||||
import type { DashboardBoleto } from "@/lib/dashboard/boletos";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import {
|
||||
RiBarcodeFill,
|
||||
RiCheckboxCircleFill,
|
||||
RiCheckboxCircleLine,
|
||||
RiLoader4Line,
|
||||
} from "@remixicon/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useMemo, useState, useTransition } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { WidgetEmptyState } from "../widget-empty-state";
|
||||
|
||||
type BoletosWidgetProps = {
|
||||
boletos: DashboardBoleto[];
|
||||
};
|
||||
|
||||
type ModalState = "idle" | "processing" | "success";
|
||||
|
||||
const DATE_FORMATTER = new Intl.DateTimeFormat("pt-BR", {
|
||||
day: "2-digit",
|
||||
month: "short",
|
||||
year: "numeric",
|
||||
timeZone: "UTC",
|
||||
});
|
||||
|
||||
const buildDateLabel = (value: string | null, prefix?: string) => {
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [year, month, day] = value.split("-").map((part) => Number(part));
|
||||
if (!year || !month || !day) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const formatted = DATE_FORMATTER.format(
|
||||
new Date(Date.UTC(year, month - 1, day))
|
||||
);
|
||||
|
||||
return prefix ? `${prefix} ${formatted}` : formatted;
|
||||
};
|
||||
|
||||
const buildStatusLabel = (boleto: DashboardBoleto) => {
|
||||
if (boleto.isSettled) {
|
||||
return buildDateLabel(boleto.boletoPaymentDate, "Pago em");
|
||||
}
|
||||
|
||||
return buildDateLabel(boleto.dueDate, "Vence em");
|
||||
};
|
||||
|
||||
const getTodayDateString = () => {
|
||||
const now = new Date();
|
||||
const year = now.getFullYear();
|
||||
const month = String(now.getMonth() + 1).padStart(2, "0");
|
||||
const day = String(now.getDate()).padStart(2, "0");
|
||||
return `${year}-${month}-${day}`;
|
||||
};
|
||||
|
||||
export function BoletosWidget({ boletos }: BoletosWidgetProps) {
|
||||
const router = useRouter();
|
||||
const [items, setItems] = useState(boletos);
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [modalState, setModalState] = useState<ModalState>("idle");
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
useEffect(() => {
|
||||
setItems(boletos);
|
||||
}, [boletos]);
|
||||
|
||||
const selectedBoleto = useMemo(
|
||||
() => items.find((boleto) => boleto.id === selectedId) ?? null,
|
||||
[items, selectedId]
|
||||
);
|
||||
|
||||
const isProcessing = modalState === "processing" || isPending;
|
||||
|
||||
const selectedBoletoDueLabel = selectedBoleto
|
||||
? buildDateLabel(selectedBoleto.dueDate, "Vencimento:")
|
||||
: null;
|
||||
|
||||
const handleOpenModal = (boletoId: string) => {
|
||||
setSelectedId(boletoId);
|
||||
setModalState("idle");
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
const resetModalState = () => {
|
||||
setIsModalOpen(false);
|
||||
setSelectedId(null);
|
||||
setModalState("idle");
|
||||
};
|
||||
|
||||
const handleConfirmPayment = () => {
|
||||
if (!selectedBoleto || selectedBoleto.isSettled || isProcessing) {
|
||||
return;
|
||||
}
|
||||
|
||||
setModalState("processing");
|
||||
|
||||
startTransition(async () => {
|
||||
const result = await toggleLancamentoSettlementAction({
|
||||
id: selectedBoleto.id,
|
||||
value: true,
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
toast.error(result.error);
|
||||
setModalState("idle");
|
||||
return;
|
||||
}
|
||||
|
||||
setItems((previous) =>
|
||||
previous.map((boleto) =>
|
||||
boleto.id === selectedBoleto.id
|
||||
? {
|
||||
...boleto,
|
||||
isSettled: true,
|
||||
boletoPaymentDate: getTodayDateString(),
|
||||
}
|
||||
: boleto
|
||||
)
|
||||
);
|
||||
toast.success(result.message);
|
||||
router.refresh();
|
||||
setModalState("success");
|
||||
});
|
||||
};
|
||||
|
||||
const getStatusBadgeVariant = (status: string): "success" | "info" => {
|
||||
const normalizedStatus = status.toLowerCase();
|
||||
if (normalizedStatus === "pendente") {
|
||||
return "info";
|
||||
}
|
||||
return "success";
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<CardContent className="flex flex-col gap-4 px-0">
|
||||
{items.length === 0 ? (
|
||||
<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."
|
||||
/>
|
||||
) : (
|
||||
<ul className="flex flex-col">
|
||||
{items.map((boleto) => {
|
||||
const statusLabel = buildStatusLabel(boleto);
|
||||
|
||||
return (
|
||||
<li
|
||||
key={boleto.id}
|
||||
className="flex items-center justify-between border-b border-dashed last:border-b-0 last:pb-0"
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-3 py-2">
|
||||
<div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-muted">
|
||||
<RiBarcodeFill className="size-5" />
|
||||
</div>
|
||||
|
||||
<div className="min-w-0">
|
||||
<span className="block truncate text-sm font-medium text-foreground">
|
||||
{boleto.name}
|
||||
</span>
|
||||
<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
||||
<span
|
||||
className={cn(
|
||||
"rounded-full py-0.5",
|
||||
boleto.isSettled &&
|
||||
"text-green-600 dark:text-green-400"
|
||||
)}
|
||||
>
|
||||
{statusLabel}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex shrink-0 flex-col items-end">
|
||||
<MoneyValues amount={boleto.amount} />
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="link"
|
||||
className="h-auto p-0 disabled:opacity-100"
|
||||
disabled={boleto.isSettled}
|
||||
onClick={() => handleOpenModal(boleto.id)}
|
||||
>
|
||||
{boleto.isSettled ? (
|
||||
<span className="flex items-center gap-1 text-green-600 dark:text-green-400">
|
||||
<RiCheckboxCircleFill className="size-3" /> Pago
|
||||
</span>
|
||||
) : (
|
||||
"Pagar"
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
<Dialog
|
||||
open={isModalOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
if (isProcessing) {
|
||||
return;
|
||||
}
|
||||
resetModalState();
|
||||
return;
|
||||
}
|
||||
setIsModalOpen(true);
|
||||
}}
|
||||
>
|
||||
<DialogContent
|
||||
className="max-w-md"
|
||||
onEscapeKeyDown={(event) => {
|
||||
if (isProcessing) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
resetModalState();
|
||||
}}
|
||||
onPointerDownOutside={(event) => {
|
||||
if (isProcessing) {
|
||||
event.preventDefault();
|
||||
}
|
||||
}}
|
||||
>
|
||||
{modalState === "success" ? (
|
||||
<div className="flex flex-col items-center gap-4 py-6 text-center">
|
||||
<div className="flex size-16 items-center justify-center rounded-full bg-emerald-500/10 text-emerald-500">
|
||||
<RiCheckboxCircleLine className="size-8" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<DialogTitle className="text-base">
|
||||
Pagamento registrado!
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-sm">
|
||||
Atualizamos o status do boleto para pago. Em instantes ele
|
||||
aparecerá como baixado no histórico.
|
||||
</DialogDescription>
|
||||
</div>
|
||||
<ModalFooter className="sm:justify-center">
|
||||
<Button
|
||||
type="button"
|
||||
onClick={resetModalState}
|
||||
className="sm:w-auto"
|
||||
>
|
||||
Fechar
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<DialogHeader className="gap-3 text-center sm:text-left">
|
||||
<DialogTitle>Confirmar pagamento do boleto</DialogTitle>
|
||||
<DialogDescription>
|
||||
Confirme os dados para registrar o pagamento. Você poderá
|
||||
editar o lançamento depois, se necessário.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{selectedBoleto ? (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col items-center gap-3 rounded-lg border border-border/60 bg-muted/50 p-4 text-center sm:flex-row sm:text-left">
|
||||
<div className="flex size-12 shrink-0 items-center justify-center">
|
||||
<RiBarcodeFill className="size-8" />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium text-foreground">
|
||||
{selectedBoleto.name}
|
||||
</p>
|
||||
{selectedBoletoDueLabel ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{selectedBoletoDueLabel}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-3 text-sm">
|
||||
<div className="flex items-center justify-between rounded border border-border/60 px-3 py-2">
|
||||
<span className="text-xs uppercase text-muted-foreground/80">
|
||||
Valor do boleto
|
||||
</span>
|
||||
<MoneyValues
|
||||
amount={selectedBoleto.amount}
|
||||
className="text-lg"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between rounded border border-border/60 px-3 py-2">
|
||||
<span className="text-xs uppercase text-muted-foreground/80">
|
||||
Status atual
|
||||
</span>
|
||||
<span className="text-sm font-medium">
|
||||
<Badge
|
||||
variant={getStatusBadgeVariant(
|
||||
selectedBoleto.isSettled ? "Pago" : "Pendente"
|
||||
)}
|
||||
className="text-xs"
|
||||
>
|
||||
{selectedBoleto.isSettled ? "Pago" : "Pendente"}
|
||||
</Badge>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<ModalFooter className="sm:justify-end">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={resetModalState}
|
||||
disabled={isProcessing}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleConfirmPayment}
|
||||
disabled={
|
||||
isProcessing || !selectedBoleto || selectedBoleto.isSettled
|
||||
}
|
||||
className="relative"
|
||||
>
|
||||
{isProcessing ? (
|
||||
<>
|
||||
<RiLoader4Line className="mr-1.5 size-4 animate-spin" />
|
||||
Processando...
|
||||
</>
|
||||
) : (
|
||||
"Confirmar pagamento"
|
||||
)}
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
25
components/dashboard/dashboard-grid.tsx
Normal file
25
components/dashboard/dashboard-grid.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
import WidgetCard from "@/components/widget-card";
|
||||
import type { DashboardData } from "@/lib/dashboard/fetch-dashboard-data";
|
||||
import { widgetsConfig } from "@/lib/dashboard/widgets/widgets-config";
|
||||
|
||||
type DashboardGridProps = {
|
||||
data: DashboardData;
|
||||
period: string;
|
||||
};
|
||||
|
||||
export function DashboardGrid({ data, period }: DashboardGridProps) {
|
||||
return (
|
||||
<section className="grid grid-cols-1 gap-3 @4xl/main:grid-cols-2 @6xl/main:grid-cols-3">
|
||||
{widgetsConfig.map((widget) => (
|
||||
<WidgetCard
|
||||
key={widget.id}
|
||||
title={widget.title}
|
||||
subtitle={widget.subtitle}
|
||||
icon={widget.icon}
|
||||
>
|
||||
{widget.component({ data, period })}
|
||||
</WidgetCard>
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
76
components/dashboard/dashboard-welcome.tsx
Normal file
76
components/dashboard/dashboard-welcome.tsx
Normal file
@@ -0,0 +1,76 @@
|
||||
"use client";
|
||||
|
||||
import { main_font } from "@/public/fonts/font_index";
|
||||
import MagnetLines from "../magnet-lines";
|
||||
import { Card } from "../ui/card";
|
||||
|
||||
type DashboardWelcomeProps = {
|
||||
name?: string | null;
|
||||
};
|
||||
|
||||
const capitalizeFirstLetter = (value: string) =>
|
||||
value.length > 0 ? value[0]?.toUpperCase() + value.slice(1) : value;
|
||||
|
||||
const formatCurrentDate = (date = new Date()) => {
|
||||
const formatted = new Intl.DateTimeFormat("pt-BR", {
|
||||
weekday: "long",
|
||||
day: "numeric",
|
||||
month: "long",
|
||||
year: "numeric",
|
||||
timeZone: "America/Sao_Paulo",
|
||||
}).format(date);
|
||||
|
||||
return capitalizeFirstLetter(formatted);
|
||||
};
|
||||
|
||||
const getGreeting = () => {
|
||||
const now = new Date();
|
||||
|
||||
// Get hour in Brasilia timezone
|
||||
const brasiliaHour = new Intl.DateTimeFormat("pt-BR", {
|
||||
hour: "numeric",
|
||||
hour12: false,
|
||||
timeZone: "America/Sao_Paulo",
|
||||
}).format(now);
|
||||
|
||||
const hour = parseInt(brasiliaHour, 10);
|
||||
|
||||
if (hour >= 5 && hour < 12) {
|
||||
return "Bom dia";
|
||||
} else if (hour >= 12 && hour < 18) {
|
||||
return "Boa tarde";
|
||||
} else {
|
||||
return "Boa noite";
|
||||
}
|
||||
};
|
||||
|
||||
export function DashboardWelcome({ name }: DashboardWelcomeProps) {
|
||||
const displayName = name && name.trim().length > 0 ? name : "Administrador";
|
||||
const formattedDate = formatCurrentDate();
|
||||
const greeting = getGreeting();
|
||||
|
||||
return (
|
||||
<Card
|
||||
className={`${main_font.className} relative px-6 py-12 bg-welcome-banner border-none shadow-lg overflow-hidden`}
|
||||
>
|
||||
<div className="absolute inset-0 flex items-center justify-center opacity-20 pointer-events-none">
|
||||
<MagnetLines
|
||||
rows={8}
|
||||
columns={16}
|
||||
containerSize="100%"
|
||||
lineColor="currentColor"
|
||||
lineWidth="0.4vmin"
|
||||
lineHeight="5vmin"
|
||||
baseAngle={0}
|
||||
className="text-welcome-banner-foreground"
|
||||
/>
|
||||
</div>
|
||||
<div className="relative tracking-tight text-welcome-banner-foreground">
|
||||
<h1 className="text-xl font-medium">
|
||||
{greeting}, {displayName}! <span aria-hidden="true">👋</span>
|
||||
</h1>
|
||||
<p className="mt-2 text-sm opacity-90">{formattedDate}</p>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
179
components/dashboard/expenses-by-category-widget.tsx
Normal file
179
components/dashboard/expenses-by-category-widget.tsx
Normal file
@@ -0,0 +1,179 @@
|
||||
import MoneyValues from "@/components/money-values";
|
||||
import type { ExpensesByCategoryData } from "@/lib/dashboard/categories/expenses-by-category";
|
||||
import { getIconComponent } from "@/lib/utils/icons";
|
||||
import { formatPeriodForUrl } from "@/lib/utils/period";
|
||||
import {
|
||||
RiArrowDownLine,
|
||||
RiArrowUpLine,
|
||||
RiExternalLinkLine,
|
||||
RiPieChartLine,
|
||||
RiWallet3Line,
|
||||
} from "@remixicon/react";
|
||||
import Link from "next/link";
|
||||
import { WidgetEmptyState } from "../widget-empty-state";
|
||||
|
||||
type ExpensesByCategoryWidgetProps = {
|
||||
data: ExpensesByCategoryData;
|
||||
period: string;
|
||||
};
|
||||
|
||||
const buildInitials = (value: string) => {
|
||||
const parts = value.trim().split(/\s+/).filter(Boolean);
|
||||
if (parts.length === 0) {
|
||||
return "CT";
|
||||
}
|
||||
if (parts.length === 1) {
|
||||
const firstPart = parts[0];
|
||||
return firstPart ? firstPart.slice(0, 2).toUpperCase() : "CT";
|
||||
}
|
||||
const firstChar = parts[0]?.[0] ?? "";
|
||||
const secondChar = parts[1]?.[0] ?? "";
|
||||
return `${firstChar}${secondChar}`.toUpperCase() || "CT";
|
||||
};
|
||||
|
||||
const formatPercentage = (value: number) => {
|
||||
return `${Math.abs(value).toFixed(0)}%`;
|
||||
};
|
||||
|
||||
export function ExpensesByCategoryWidget({
|
||||
data,
|
||||
period,
|
||||
}: ExpensesByCategoryWidgetProps) {
|
||||
const periodParam = formatPeriodForUrl(period);
|
||||
|
||||
if (data.categories.length === 0) {
|
||||
return (
|
||||
<WidgetEmptyState
|
||||
icon={<RiPieChartLine className="size-6 text-muted-foreground" />}
|
||||
title="Nenhuma despesa encontrada"
|
||||
description="Quando houver despesas registradas, elas aparecerão aqui."
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col px-0">
|
||||
{data.categories.map((category) => {
|
||||
const IconComponent = category.categoryIcon
|
||||
? getIconComponent(category.categoryIcon)
|
||||
: null;
|
||||
const initials = buildInitials(category.categoryName);
|
||||
const hasIncrease =
|
||||
category.percentageChange !== null && category.percentageChange > 0;
|
||||
const hasDecrease =
|
||||
category.percentageChange !== null && category.percentageChange < 0;
|
||||
const hasBudget = category.budgetAmount !== null;
|
||||
const budgetExceeded =
|
||||
hasBudget &&
|
||||
category.budgetUsedPercentage !== null &&
|
||||
category.budgetUsedPercentage > 100;
|
||||
|
||||
const formatCurrency = (value: number) =>
|
||||
new Intl.NumberFormat("pt-BR", {
|
||||
style: "currency",
|
||||
currency: "BRL",
|
||||
}).format(value);
|
||||
|
||||
const exceededAmount =
|
||||
budgetExceeded && category.budgetAmount
|
||||
? category.currentAmount - category.budgetAmount
|
||||
: 0;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={category.categoryId}
|
||||
className="flex flex-col py-2 border-b border-dashed last:border-0"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
||||
<div className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted">
|
||||
{IconComponent ? (
|
||||
<IconComponent className="size-4 text-foreground" />
|
||||
) : (
|
||||
<span className="text-xs font-semibold uppercase text-muted-foreground">
|
||||
{initials}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<Link
|
||||
href={`/categorias/${category.categoryId}?periodo=${periodParam}`}
|
||||
className="flex max-w-full items-center gap-1 text-sm font-medium text-foreground underline-offset-2 hover:underline"
|
||||
>
|
||||
<span className="truncate">{category.categoryName}</span>
|
||||
<RiExternalLinkLine
|
||||
className="size-3 shrink-0 text-muted-foreground"
|
||||
aria-hidden
|
||||
/>
|
||||
</Link>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<span>
|
||||
{formatPercentage(category.percentageOfTotal)} da despesa
|
||||
total
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex shrink-0 flex-col items-end gap-0.5">
|
||||
<MoneyValues
|
||||
className="text-foreground"
|
||||
amount={category.currentAmount}
|
||||
/>
|
||||
{category.percentageChange !== null && (
|
||||
<span
|
||||
className={`flex items-center gap-0.5 text-xs ${
|
||||
hasIncrease
|
||||
? "text-red-600"
|
||||
: hasDecrease
|
||||
? "text-green-600"
|
||||
: "text-muted-foreground"
|
||||
}`}
|
||||
>
|
||||
{hasIncrease && <RiArrowUpLine className="size-3" />}
|
||||
{hasDecrease && <RiArrowDownLine className="size-3" />}
|
||||
{formatPercentage(category.percentageChange)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{hasBudget && category.budgetUsedPercentage !== null && (
|
||||
<div className="ml-11 flex items-center gap-1.5 text-xs">
|
||||
<RiWallet3Line
|
||||
className={`size-3 ${
|
||||
budgetExceeded
|
||||
? "text-red-600"
|
||||
: "text-blue-600 dark:text-blue-400"
|
||||
}`}
|
||||
/>
|
||||
<span
|
||||
className={
|
||||
budgetExceeded
|
||||
? "text-red-600"
|
||||
: "text-blue-600 dark:text-blue-400"
|
||||
}
|
||||
>
|
||||
{budgetExceeded ? (
|
||||
<>
|
||||
{formatPercentage(category.budgetUsedPercentage)} do
|
||||
limite • excedeu em {formatCurrency(exceededAmount)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{formatPercentage(category.budgetUsedPercentage)} do
|
||||
limite
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
182
components/dashboard/income-by-category-widget.tsx
Normal file
182
components/dashboard/income-by-category-widget.tsx
Normal file
@@ -0,0 +1,182 @@
|
||||
import MoneyValues from "@/components/money-values";
|
||||
import type { IncomeByCategoryData } from "@/lib/dashboard/categories/income-by-category";
|
||||
import { getIconComponent } from "@/lib/utils/icons";
|
||||
import { formatPeriodForUrl } from "@/lib/utils/period";
|
||||
import {
|
||||
RiArrowDownLine,
|
||||
RiArrowUpLine,
|
||||
RiExternalLinkLine,
|
||||
RiPieChartLine,
|
||||
RiWallet3Line,
|
||||
} from "@remixicon/react";
|
||||
import Link from "next/link";
|
||||
import { WidgetEmptyState } from "../widget-empty-state";
|
||||
|
||||
type IncomeByCategoryWidgetProps = {
|
||||
data: IncomeByCategoryData;
|
||||
period: string;
|
||||
};
|
||||
|
||||
const buildInitials = (value: string) => {
|
||||
const parts = value.trim().split(/\s+/).filter(Boolean);
|
||||
if (parts.length === 0) {
|
||||
return "CT";
|
||||
}
|
||||
if (parts.length === 1) {
|
||||
const firstPart = parts[0];
|
||||
return firstPart ? firstPart.slice(0, 2).toUpperCase() : "CT";
|
||||
}
|
||||
const firstChar = parts[0]?.[0] ?? "";
|
||||
const secondChar = parts[1]?.[0] ?? "";
|
||||
return `${firstChar}${secondChar}`.toUpperCase() || "CT";
|
||||
};
|
||||
|
||||
const formatPercentage = (value: number) => {
|
||||
return `${Math.abs(value).toFixed(1)}%`;
|
||||
};
|
||||
|
||||
export function IncomeByCategoryWidget({
|
||||
data,
|
||||
period,
|
||||
}: IncomeByCategoryWidgetProps) {
|
||||
const periodParam = formatPeriodForUrl(period);
|
||||
|
||||
if (data.categories.length === 0) {
|
||||
return (
|
||||
<WidgetEmptyState
|
||||
icon={<RiPieChartLine className="size-6 text-muted-foreground" />}
|
||||
title="Nenhuma receita encontrada"
|
||||
description="Quando houver receitas registradas, elas aparecerão aqui."
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2 px-0">
|
||||
{data.categories.map((category) => {
|
||||
const IconComponent = category.categoryIcon
|
||||
? getIconComponent(category.categoryIcon)
|
||||
: null;
|
||||
const initials = buildInitials(category.categoryName);
|
||||
const hasIncrease =
|
||||
category.percentageChange !== null && category.percentageChange > 0;
|
||||
const hasDecrease =
|
||||
category.percentageChange !== null && category.percentageChange < 0;
|
||||
const hasBudget = category.budgetAmount !== null;
|
||||
const budgetExceeded =
|
||||
hasBudget &&
|
||||
category.budgetUsedPercentage !== null &&
|
||||
category.budgetUsedPercentage > 100;
|
||||
|
||||
const formatCurrency = (value: number) =>
|
||||
new Intl.NumberFormat("pt-BR", {
|
||||
style: "currency",
|
||||
currency: "BRL",
|
||||
}).format(value);
|
||||
|
||||
const exceededAmount =
|
||||
budgetExceeded && category.budgetAmount
|
||||
? category.currentAmount - category.budgetAmount
|
||||
: 0;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={category.categoryId}
|
||||
className="flex flex-col gap-1.5 py-2 border-b border-dashed last:border-0"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
||||
<div className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted">
|
||||
{IconComponent ? (
|
||||
<IconComponent className="size-4 text-foreground" />
|
||||
) : (
|
||||
<span className="text-xs font-semibold uppercase text-muted-foreground">
|
||||
{initials}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<Link
|
||||
href={`/categorias/${category.categoryId}?periodo=${periodParam}`}
|
||||
className="flex max-w-full items-center gap-1 text-sm font-medium text-foreground underline-offset-2 hover:underline"
|
||||
>
|
||||
<span className="truncate">{category.categoryName}</span>
|
||||
<RiExternalLinkLine
|
||||
className="size-3 shrink-0 text-muted-foreground"
|
||||
aria-hidden
|
||||
/>
|
||||
</Link>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<span>
|
||||
{formatPercentage(category.percentageOfTotal)} da receita
|
||||
total
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex shrink-0 flex-col items-end gap-0.5">
|
||||
<MoneyValues
|
||||
className="text-foreground"
|
||||
amount={category.currentAmount}
|
||||
/>
|
||||
{category.percentageChange !== null && (
|
||||
<span
|
||||
className={`flex items-center gap-0.5 text-xs ${
|
||||
hasIncrease
|
||||
? "text-green-600"
|
||||
: hasDecrease
|
||||
? "text-red-600"
|
||||
: "text-muted-foreground"
|
||||
}`}
|
||||
>
|
||||
{hasIncrease && <RiArrowUpLine className="size-3" />}
|
||||
{hasDecrease && <RiArrowDownLine className="size-3" />}
|
||||
{formatPercentage(category.percentageChange)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{hasBudget &&
|
||||
category.budgetUsedPercentage !== null &&
|
||||
category.budgetAmount !== null && (
|
||||
<div className="ml-11 flex items-center gap-1.5 text-xs">
|
||||
<RiWallet3Line
|
||||
className={`size-3 ${
|
||||
budgetExceeded
|
||||
? "text-red-600"
|
||||
: "text-blue-600 dark:text-blue-400"
|
||||
}`}
|
||||
/>
|
||||
<span
|
||||
className={
|
||||
budgetExceeded
|
||||
? "text-red-600"
|
||||
: "text-blue-600 dark:text-blue-400"
|
||||
}
|
||||
>
|
||||
{budgetExceeded ? (
|
||||
<>
|
||||
{formatPercentage(category.budgetUsedPercentage)} do
|
||||
limite {formatCurrency(category.budgetAmount)} • excedeu
|
||||
em {formatCurrency(exceededAmount)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{formatPercentage(category.budgetUsedPercentage)} do
|
||||
limite {formatCurrency(category.budgetAmount)}
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
175
components/dashboard/income-expense-balance-widget.tsx
Normal file
175
components/dashboard/income-expense-balance-widget.tsx
Normal file
@@ -0,0 +1,175 @@
|
||||
"use client";
|
||||
|
||||
import { CardContent } from "@/components/ui/card";
|
||||
import {
|
||||
ChartContainer,
|
||||
ChartTooltip,
|
||||
type ChartConfig,
|
||||
} from "@/components/ui/chart";
|
||||
import { WidgetEmptyState } from "@/components/widget-empty-state";
|
||||
import type { IncomeExpenseBalanceData } from "@/lib/dashboard/income-expense-balance";
|
||||
import { RiLineChartLine } from "@remixicon/react";
|
||||
import { Bar, BarChart, CartesianGrid, XAxis } from "recharts";
|
||||
|
||||
type IncomeExpenseBalanceWidgetProps = {
|
||||
data: IncomeExpenseBalanceData;
|
||||
};
|
||||
|
||||
const chartConfig = {
|
||||
receita: {
|
||||
label: "Receita",
|
||||
color: "var(--chart-1)",
|
||||
},
|
||||
despesa: {
|
||||
label: "Despesa",
|
||||
color: "var(--chart-2)",
|
||||
},
|
||||
balanco: {
|
||||
label: "Balanço",
|
||||
color: "var(--chart-3)",
|
||||
},
|
||||
} satisfies ChartConfig;
|
||||
|
||||
export function IncomeExpenseBalanceWidget({
|
||||
data,
|
||||
}: IncomeExpenseBalanceWidgetProps) {
|
||||
const chartData = data.months.map((month) => ({
|
||||
month: month.monthLabel,
|
||||
receita: month.income,
|
||||
despesa: month.expense,
|
||||
balanco: month.balance,
|
||||
}));
|
||||
|
||||
// Verifica se todos os valores são zero
|
||||
const isEmpty = chartData.every(
|
||||
(item) => item.receita === 0 && item.despesa === 0 && item.balanco === 0
|
||||
);
|
||||
|
||||
if (isEmpty) {
|
||||
return (
|
||||
<CardContent className="px-0">
|
||||
<WidgetEmptyState
|
||||
icon={<RiLineChartLine className="size-6 text-muted-foreground" />}
|
||||
title="Nenhuma movimentação financeira no período"
|
||||
description="Registre receitas e despesas para visualizar o balanço mensal."
|
||||
/>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<CardContent className="space-y-4 px-0">
|
||||
<ChartContainer
|
||||
config={chartConfig}
|
||||
className="h-[270px] w-full aspect-auto"
|
||||
>
|
||||
<BarChart
|
||||
data={chartData}
|
||||
margin={{ top: 20, right: 10, left: 10, bottom: 5 }}
|
||||
>
|
||||
<CartesianGrid strokeDasharray="3 3" vertical={false} />
|
||||
<XAxis
|
||||
dataKey="month"
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
tickMargin={8}
|
||||
/>
|
||||
<ChartTooltip
|
||||
content={({ active, payload }) => {
|
||||
if (!active || !payload || payload.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const formatCurrency = (value: number) => {
|
||||
return new Intl.NumberFormat("pt-BR", {
|
||||
style: "currency",
|
||||
currency: "BRL",
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
}).format(value);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border bg-background p-2 shadow-sm">
|
||||
<div className="grid gap-2">
|
||||
{payload.map((entry) => {
|
||||
const config =
|
||||
chartConfig[entry.dataKey as keyof typeof chartConfig];
|
||||
const value = entry.value as number;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={entry.dataKey}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<div
|
||||
className="h-2.5 w-2.5 rounded"
|
||||
style={{ backgroundColor: config?.color }}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{config?.label}:
|
||||
</span>
|
||||
<span className="text-xs font-medium">
|
||||
{formatCurrency(value)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
cursor={{ fill: "hsl(var(--muted))", opacity: 0.3 }}
|
||||
/>
|
||||
<Bar
|
||||
dataKey="receita"
|
||||
fill={chartConfig.receita.color}
|
||||
radius={[4, 4, 0, 0]}
|
||||
maxBarSize={60}
|
||||
/>
|
||||
<Bar
|
||||
dataKey="despesa"
|
||||
fill={chartConfig.despesa.color}
|
||||
radius={[4, 4, 0, 0]}
|
||||
maxBarSize={60}
|
||||
/>
|
||||
<Bar
|
||||
dataKey="balanco"
|
||||
fill={chartConfig.balanco.color}
|
||||
radius={[4, 4, 0, 0]}
|
||||
maxBarSize={60}
|
||||
/>
|
||||
</BarChart>
|
||||
</ChartContainer>
|
||||
<div className="flex items-center justify-center gap-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className="h-3 w-3 rounded"
|
||||
style={{ backgroundColor: chartConfig.receita.color }}
|
||||
/>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{chartConfig.receita.label}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className="h-3 w-3 rounded"
|
||||
style={{ backgroundColor: chartConfig.despesa.color }}
|
||||
/>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{chartConfig.despesa.label}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className="h-3 w-3 rounded"
|
||||
style={{ backgroundColor: chartConfig.balanco.color }}
|
||||
/>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{chartConfig.balanco.label}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
190
components/dashboard/installment-expenses-widget.tsx
Normal file
190
components/dashboard/installment-expenses-widget.tsx
Normal file
@@ -0,0 +1,190 @@
|
||||
import MoneyValues from "@/components/money-values";
|
||||
import { CardContent } from "@/components/ui/card";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import type { InstallmentExpensesData } from "@/lib/dashboard/expenses/installment-expenses";
|
||||
import {
|
||||
calculateLastInstallmentDate,
|
||||
formatLastInstallmentDate,
|
||||
} from "@/lib/installments/utils";
|
||||
import { RiNumbersLine } from "@remixicon/react";
|
||||
import Image from "next/image";
|
||||
import { Progress } from "../ui/progress";
|
||||
import { WidgetEmptyState } from "../widget-empty-state";
|
||||
|
||||
type InstallmentExpensesWidgetProps = {
|
||||
data: InstallmentExpensesData;
|
||||
};
|
||||
|
||||
const buildCompactInstallmentLabel = (
|
||||
currentInstallment: number | null,
|
||||
installmentCount: number | null
|
||||
) => {
|
||||
if (currentInstallment && installmentCount) {
|
||||
return `${currentInstallment} de ${installmentCount}`;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const isLastInstallment = (
|
||||
currentInstallment: number | null,
|
||||
installmentCount: number | null
|
||||
) => {
|
||||
if (!currentInstallment || !installmentCount) return false;
|
||||
return currentInstallment === installmentCount && installmentCount > 1;
|
||||
};
|
||||
|
||||
const calculateRemainingInstallments = (
|
||||
currentInstallment: number | null,
|
||||
installmentCount: number | null
|
||||
) => {
|
||||
if (!currentInstallment || !installmentCount) return 0;
|
||||
return Math.max(0, installmentCount - currentInstallment);
|
||||
};
|
||||
|
||||
const calculateRemainingAmount = (
|
||||
amount: number,
|
||||
currentInstallment: number | null,
|
||||
installmentCount: number | null
|
||||
) => {
|
||||
const remaining = calculateRemainingInstallments(
|
||||
currentInstallment,
|
||||
installmentCount
|
||||
);
|
||||
return amount * remaining;
|
||||
};
|
||||
|
||||
const formatEndDate = (
|
||||
period: string,
|
||||
currentInstallment: number | null,
|
||||
installmentCount: number | null
|
||||
) => {
|
||||
if (!currentInstallment || !installmentCount) return null;
|
||||
|
||||
const lastDate = calculateLastInstallmentDate(
|
||||
period,
|
||||
currentInstallment,
|
||||
installmentCount
|
||||
);
|
||||
|
||||
return formatLastInstallmentDate(lastDate);
|
||||
};
|
||||
|
||||
const buildProgress = (
|
||||
currentInstallment: number | null,
|
||||
installmentCount: number | null
|
||||
) => {
|
||||
if (!currentInstallment || !installmentCount || installmentCount <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return Math.min(
|
||||
100,
|
||||
Math.max(0, (currentInstallment / installmentCount) * 100)
|
||||
);
|
||||
};
|
||||
|
||||
export function InstallmentExpensesWidget({
|
||||
data,
|
||||
}: InstallmentExpensesWidgetProps) {
|
||||
if (data.expenses.length === 0) {
|
||||
return (
|
||||
<WidgetEmptyState
|
||||
icon={<RiNumbersLine className="size-6 text-muted-foreground" />}
|
||||
title="Nenhuma despesa parcelada"
|
||||
description="Lançamentos parcelados aparecerão aqui conforme forem registrados."
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<CardContent className="flex flex-col gap-4 px-0">
|
||||
<ul className="flex flex-col gap-2">
|
||||
{data.expenses.map((expense) => {
|
||||
const compactLabel = buildCompactInstallmentLabel(
|
||||
expense.currentInstallment,
|
||||
expense.installmentCount
|
||||
);
|
||||
const isLast = isLastInstallment(
|
||||
expense.currentInstallment,
|
||||
expense.installmentCount
|
||||
);
|
||||
const remainingInstallments = calculateRemainingInstallments(
|
||||
expense.currentInstallment,
|
||||
expense.installmentCount
|
||||
);
|
||||
const remainingAmount = calculateRemainingAmount(
|
||||
expense.amount,
|
||||
expense.currentInstallment,
|
||||
expense.installmentCount
|
||||
);
|
||||
const endDate = formatEndDate(
|
||||
expense.period,
|
||||
expense.currentInstallment,
|
||||
expense.installmentCount
|
||||
);
|
||||
const progress = buildProgress(
|
||||
expense.currentInstallment,
|
||||
expense.installmentCount
|
||||
);
|
||||
|
||||
return (
|
||||
<li
|
||||
key={expense.id}
|
||||
className="flex items-center gap-3 border-b border-dashed pb-2 last:border-b-0 last:pb-0"
|
||||
>
|
||||
<div className="min-w-0 flex-1 ">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<p className="truncate text-sm font-medium text-foreground">
|
||||
{expense.name}
|
||||
</p>
|
||||
{compactLabel && (
|
||||
<span className="inline-flex shrink-0 items-center gap-1 text-xs font-medium text-muted-foreground">
|
||||
{compactLabel}
|
||||
{isLast && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span className="inline-flex">
|
||||
<Image
|
||||
src="/icones/party.svg"
|
||||
alt="Última parcela"
|
||||
width={14}
|
||||
height={14}
|
||||
className="h-3.5 w-3.5"
|
||||
/>
|
||||
<span className="sr-only">Última parcela</span>
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top">
|
||||
Última parcela!
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<MoneyValues amount={expense.amount} className="shrink-0" />
|
||||
</div>
|
||||
<Progress value={progress} className="h-2" />
|
||||
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Restantes {remainingInstallments}
|
||||
{endDate && ` • Termina em ${endDate}`}
|
||||
{" • Restante "}
|
||||
<MoneyValues
|
||||
amount={remainingAmount}
|
||||
className="inline-block font-medium"
|
||||
/>
|
||||
</p>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
561
components/dashboard/invoices-widget.tsx
Normal file
561
components/dashboard/invoices-widget.tsx
Normal file
@@ -0,0 +1,561 @@
|
||||
"use client";
|
||||
import { updateInvoicePaymentStatusAction } from "@/app/(dashboard)/cartoes/[cartaoId]/fatura/actions";
|
||||
import MoneyValues from "@/components/money-values";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CardContent } from "@/components/ui/card";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter as ModalFooter,
|
||||
} from "@/components/ui/dialog";
|
||||
import type { DashboardInvoice } from "@/lib/dashboard/invoices";
|
||||
import { INVOICE_PAYMENT_STATUS, INVOICE_STATUS_LABEL } from "@/lib/faturas";
|
||||
import { getAvatarSrc } from "@/lib/pagadores/utils";
|
||||
import { formatPeriodForUrl } from "@/lib/utils/period";
|
||||
import {
|
||||
RiBillLine,
|
||||
RiCheckboxCircleFill,
|
||||
RiCheckboxCircleLine,
|
||||
RiExternalLinkLine,
|
||||
RiLoader4Line,
|
||||
} from "@remixicon/react";
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useMemo, useState, useTransition } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Badge } from "../ui/badge";
|
||||
import {
|
||||
HoverCard,
|
||||
HoverCardContent,
|
||||
HoverCardTrigger,
|
||||
} from "../ui/hover-card";
|
||||
import { WidgetEmptyState } from "../widget-empty-state";
|
||||
|
||||
type InvoicesWidgetProps = {
|
||||
invoices: DashboardInvoice[];
|
||||
};
|
||||
|
||||
type ModalState = "idle" | "processing" | "success";
|
||||
|
||||
const DUE_DATE_FORMATTER = new Intl.DateTimeFormat("pt-BR", {
|
||||
day: "2-digit",
|
||||
month: "short",
|
||||
year: "numeric",
|
||||
timeZone: "UTC",
|
||||
});
|
||||
|
||||
const resolveLogoPath = (logo: string | null) => {
|
||||
if (!logo) {
|
||||
return null;
|
||||
}
|
||||
if (/^(https?:\/\/|data:)/.test(logo)) {
|
||||
return logo;
|
||||
}
|
||||
return logo.startsWith("/") ? logo : `/logos/${logo}`;
|
||||
};
|
||||
|
||||
const buildInitials = (value: string) => {
|
||||
const parts = value.trim().split(/\s+/).filter(Boolean);
|
||||
if (parts.length === 0) {
|
||||
return "CC";
|
||||
}
|
||||
if (parts.length === 1) {
|
||||
const firstPart = parts[0];
|
||||
return firstPart ? firstPart.slice(0, 2).toUpperCase() : "CC";
|
||||
}
|
||||
const firstChar = parts[0]?.[0] ?? "";
|
||||
const secondChar = parts[1]?.[0] ?? "";
|
||||
return `${firstChar}${secondChar}`.toUpperCase() || "CC";
|
||||
};
|
||||
|
||||
const parseDueDate = (period: string, dueDay: string) => {
|
||||
const [yearStr, monthStr] = period.split("-");
|
||||
const dayNumber = Number.parseInt(dueDay, 10);
|
||||
const year = Number.parseInt(yearStr ?? "", 10);
|
||||
const month = Number.parseInt(monthStr ?? "", 10);
|
||||
|
||||
if (
|
||||
Number.isNaN(dayNumber) ||
|
||||
Number.isNaN(year) ||
|
||||
Number.isNaN(month) ||
|
||||
period.length !== 7
|
||||
) {
|
||||
return {
|
||||
label: `Vence dia ${dueDay}`,
|
||||
};
|
||||
}
|
||||
|
||||
const date = new Date(Date.UTC(year, month - 1, dayNumber));
|
||||
return {
|
||||
label: `Vence em ${DUE_DATE_FORMATTER.format(date)}`,
|
||||
};
|
||||
};
|
||||
|
||||
const formatPaymentDate = (value: string | null) => {
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [yearStr, monthStr, dayStr] = value.split("-");
|
||||
const year = Number.parseInt(yearStr ?? "", 10);
|
||||
const month = Number.parseInt(monthStr ?? "", 10);
|
||||
const day = Number.parseInt(dayStr ?? "", 10);
|
||||
|
||||
if (
|
||||
Number.isNaN(year) ||
|
||||
Number.isNaN(month) ||
|
||||
Number.isNaN(day) ||
|
||||
yearStr?.length !== 4 ||
|
||||
monthStr?.length !== 2 ||
|
||||
dayStr?.length !== 2
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const date = new Date(Date.UTC(year, month - 1, day));
|
||||
return {
|
||||
label: `Pago em ${DUE_DATE_FORMATTER.format(date)}`,
|
||||
};
|
||||
};
|
||||
|
||||
const getTodayDateString = () => {
|
||||
const now = new Date();
|
||||
const year = now.getFullYear();
|
||||
const month = String(now.getMonth() + 1).padStart(2, "0");
|
||||
const day = String(now.getDate()).padStart(2, "0");
|
||||
return `${year}-${month}-${day}`;
|
||||
};
|
||||
|
||||
const formatSharePercentage = (value: number) => {
|
||||
if (!Number.isFinite(value) || value <= 0) {
|
||||
return "0%";
|
||||
}
|
||||
const digits = value >= 10 ? 0 : value >= 1 ? 1 : 2;
|
||||
return (
|
||||
value.toLocaleString("pt-BR", {
|
||||
minimumFractionDigits: digits,
|
||||
maximumFractionDigits: digits,
|
||||
}) + "%"
|
||||
);
|
||||
};
|
||||
|
||||
const getShareLabel = (amount: number, total: number) => {
|
||||
if (total <= 0) {
|
||||
return "0% do total";
|
||||
}
|
||||
const percentage = (amount / total) * 100;
|
||||
return `${formatSharePercentage(percentage)} do total`;
|
||||
};
|
||||
|
||||
export function InvoicesWidget({ invoices }: InvoicesWidgetProps) {
|
||||
const router = useRouter();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [items, setItems] = useState(invoices);
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
const [modalState, setModalState] = useState<ModalState>("idle");
|
||||
|
||||
useEffect(() => {
|
||||
setItems(invoices);
|
||||
}, [invoices]);
|
||||
|
||||
const selectedInvoice = useMemo(
|
||||
() => items.find((invoice) => invoice.id === selectedId) ?? null,
|
||||
[items, selectedId]
|
||||
);
|
||||
|
||||
const selectedLogo = useMemo(
|
||||
() => (selectedInvoice ? resolveLogoPath(selectedInvoice.logo) : null),
|
||||
[selectedInvoice]
|
||||
);
|
||||
|
||||
const selectedPaymentInfo = useMemo(
|
||||
() => (selectedInvoice ? formatPaymentDate(selectedInvoice.paidAt) : null),
|
||||
[selectedInvoice]
|
||||
);
|
||||
|
||||
const handleOpenModal = (invoiceId: string) => {
|
||||
setSelectedId(invoiceId);
|
||||
setModalState("idle");
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
const handleCloseModal = () => {
|
||||
setIsModalOpen(false);
|
||||
setModalState("idle");
|
||||
setSelectedId(null);
|
||||
};
|
||||
|
||||
const handleConfirmPayment = () => {
|
||||
if (!selectedInvoice) {
|
||||
return;
|
||||
}
|
||||
|
||||
setModalState("processing");
|
||||
|
||||
startTransition(async () => {
|
||||
const result = await updateInvoicePaymentStatusAction({
|
||||
cartaoId: selectedInvoice.cardId,
|
||||
period: selectedInvoice.period,
|
||||
status: INVOICE_PAYMENT_STATUS.PAID,
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
setItems((previous) =>
|
||||
previous.map((invoice) =>
|
||||
invoice.id === selectedInvoice.id
|
||||
? {
|
||||
...invoice,
|
||||
paymentStatus: INVOICE_PAYMENT_STATUS.PAID,
|
||||
paidAt: getTodayDateString(),
|
||||
}
|
||||
: invoice
|
||||
)
|
||||
);
|
||||
setModalState("success");
|
||||
router.refresh();
|
||||
return;
|
||||
}
|
||||
|
||||
toast.error(result.error);
|
||||
setModalState("idle");
|
||||
});
|
||||
};
|
||||
|
||||
const getStatusBadgeVariant = (status: string): "success" | "info" => {
|
||||
const normalizedStatus = status.toLowerCase();
|
||||
if (normalizedStatus === "em aberto") {
|
||||
return "info";
|
||||
}
|
||||
return "success";
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<CardContent className="flex flex-col gap-4 px-0">
|
||||
{items.length === 0 ? (
|
||||
<WidgetEmptyState
|
||||
icon={<RiBillLine className="size-6 text-muted-foreground" />}
|
||||
title="Nenhuma fatura para o período selecionado"
|
||||
description="Quando houver cartões com compras registradas, eles aparecerão aqui."
|
||||
/>
|
||||
) : (
|
||||
<ul className="flex flex-col">
|
||||
{items.map((invoice) => {
|
||||
const logo = resolveLogoPath(invoice.logo);
|
||||
const initials = buildInitials(invoice.cardName);
|
||||
const dueInfo = parseDueDate(invoice.period, invoice.dueDay);
|
||||
const isPaid =
|
||||
invoice.paymentStatus === INVOICE_PAYMENT_STATUS.PAID;
|
||||
const paymentInfo = formatPaymentDate(invoice.paidAt);
|
||||
|
||||
return (
|
||||
<li
|
||||
key={invoice.id}
|
||||
className="flex items-center justify-between border-b border-dashed last:border-b-0 last:pb-0"
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2 py-2">
|
||||
<div className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-lg">
|
||||
{logo ? (
|
||||
<Image
|
||||
src={logo}
|
||||
alt={`Logo do cartão ${invoice.cardName}`}
|
||||
width={44}
|
||||
height={44}
|
||||
className="h-full w-full object-contain"
|
||||
/>
|
||||
) : (
|
||||
<span className="text-sm font-semibold uppercase text-muted-foreground">
|
||||
{initials}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="min-w-0">
|
||||
{(() => {
|
||||
const breakdown = invoice.pagadorBreakdown ?? [];
|
||||
const hasBreakdown = breakdown.length > 0;
|
||||
const linkNode = (
|
||||
<Link
|
||||
prefetch
|
||||
href={`/cartoes/${
|
||||
invoice.cardId
|
||||
}/fatura?periodo=${formatPeriodForUrl(
|
||||
invoice.period
|
||||
)}`}
|
||||
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">{invoice.cardName}</span>
|
||||
<RiExternalLinkLine
|
||||
className="size-3 shrink-0 text-muted-foreground"
|
||||
aria-hidden
|
||||
/>
|
||||
</Link>
|
||||
);
|
||||
|
||||
if (!hasBreakdown) {
|
||||
return linkNode;
|
||||
}
|
||||
|
||||
const totalForShare = Math.abs(invoice.totalAmount);
|
||||
|
||||
return (
|
||||
<HoverCard openDelay={150}>
|
||||
<HoverCardTrigger asChild>
|
||||
{linkNode}
|
||||
</HoverCardTrigger>
|
||||
<HoverCardContent
|
||||
align="start"
|
||||
className="w-72 space-y-3"
|
||||
>
|
||||
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
||||
Distribuição por pagador
|
||||
</p>
|
||||
<ul className="space-y-2">
|
||||
{breakdown.map((share, index) => (
|
||||
<li
|
||||
key={`${invoice.id}-${
|
||||
share.pagadorId ??
|
||||
share.pagadorName ??
|
||||
index
|
||||
}`}
|
||||
className="flex items-center gap-3"
|
||||
>
|
||||
<Avatar className="size-9">
|
||||
<AvatarImage
|
||||
src={getAvatarSrc(share.pagadorAvatar)}
|
||||
alt={`Avatar de ${share.pagadorName}`}
|
||||
/>
|
||||
<AvatarFallback>
|
||||
{buildInitials(share.pagadorName)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm font-medium text-foreground">
|
||||
{share.pagadorName}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{getShareLabel(
|
||||
share.amount,
|
||||
totalForShare
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-sm font-semibold text-foreground">
|
||||
<MoneyValues amount={share.amount} />
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</HoverCardContent>
|
||||
</HoverCard>
|
||||
);
|
||||
})()}
|
||||
<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
||||
{!isPaid ? <span>{dueInfo.label}</span> : null}
|
||||
{isPaid && paymentInfo ? (
|
||||
<span className="text-green-600 dark:text-green-400">
|
||||
{paymentInfo.label}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex shrink-0 flex-col items-end">
|
||||
<MoneyValues amount={invoice.totalAmount} />
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
disabled={isPaid}
|
||||
onClick={() => handleOpenModal(invoice.id)}
|
||||
variant={"link"}
|
||||
className="p-0 h-auto disabled:opacity-100"
|
||||
>
|
||||
{isPaid ? (
|
||||
<span className="text-green-600 dark:text-green-400 flex items-center gap-1">
|
||||
<RiCheckboxCircleFill className="size-3" /> Pago
|
||||
</span>
|
||||
) : (
|
||||
<span>Pagar</span>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
<Dialog
|
||||
open={isModalOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
handleCloseModal();
|
||||
return;
|
||||
}
|
||||
setIsModalOpen(true);
|
||||
}}
|
||||
>
|
||||
<DialogContent
|
||||
className="max-w-md"
|
||||
onEscapeKeyDown={(event) => {
|
||||
if (modalState === "processing") {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
handleCloseModal();
|
||||
}}
|
||||
onPointerDownOutside={(event) => {
|
||||
if (modalState === "processing") {
|
||||
event.preventDefault();
|
||||
}
|
||||
}}
|
||||
>
|
||||
{modalState === "success" ? (
|
||||
<div className="flex flex-col items-center gap-4 py-6 text-center">
|
||||
<div className="flex size-16 items-center justify-center rounded-full bg-emerald-500/10 text-emerald-500">
|
||||
<RiCheckboxCircleLine className="size-8" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<DialogTitle className="text-base">
|
||||
Pagamento confirmado!
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-sm">
|
||||
Atualizamos o status da fatura. O lançamento do pagamento
|
||||
aparecerá no extrato em instantes.
|
||||
</DialogDescription>
|
||||
</div>
|
||||
<ModalFooter className="sm:justify-center">
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleCloseModal}
|
||||
className="sm:w-auto"
|
||||
>
|
||||
Fechar
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<DialogHeader className="gap-3">
|
||||
<DialogTitle>Confirmar pagamento</DialogTitle>
|
||||
<DialogDescription>
|
||||
Revise os dados antes de confirmar. Vamos registrar a fatura
|
||||
como paga.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{selectedInvoice ? (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex items-center gap-3 rounded-lg border border-border/60 bg-muted/50 p-3">
|
||||
<div className="flex size-12 shrink-0 items-center justify-center overflow-hidden rounded-lg border border-border/60 bg-background">
|
||||
{selectedLogo ? (
|
||||
<Image
|
||||
src={selectedLogo}
|
||||
alt={`Logo do cartão ${selectedInvoice.cardName}`}
|
||||
width={48}
|
||||
height={48}
|
||||
className="h-full w-full object-contain"
|
||||
/>
|
||||
) : (
|
||||
<span className="text-sm font-semibold uppercase text-muted-foreground">
|
||||
{buildInitials(selectedInvoice.cardName)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">Cartão</p>
|
||||
<p className="text-base font-semibold text-foreground">
|
||||
{selectedInvoice.cardName}
|
||||
</p>
|
||||
{selectedInvoice.paymentStatus !==
|
||||
INVOICE_PAYMENT_STATUS.PAID ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{
|
||||
parseDueDate(
|
||||
selectedInvoice.period,
|
||||
selectedInvoice.dueDay
|
||||
).label
|
||||
}
|
||||
</p>
|
||||
) : null}
|
||||
{selectedInvoice.paymentStatus ===
|
||||
INVOICE_PAYMENT_STATUS.PAID && selectedPaymentInfo ? (
|
||||
<p className="text-xs text-emerald-600">
|
||||
{selectedPaymentInfo.label}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-3 text-sm sm:grid-cols-1">
|
||||
<div className="rounded border border-border/60 px-3 items-center py-2 flex justify-between">
|
||||
<span className="text-xs uppercase text-muted-foreground/80">
|
||||
Valor da fatura
|
||||
</span>
|
||||
<MoneyValues
|
||||
amount={selectedInvoice.totalAmount}
|
||||
className="text-lg"
|
||||
/>
|
||||
</div>
|
||||
<div className="rounded border border-border/60 px-3 py-2 flex justify-between items-center">
|
||||
<span className="text-xs uppercase text-muted-foreground/80">
|
||||
Status atual
|
||||
</span>
|
||||
<span className="block text-sm">
|
||||
<Badge
|
||||
variant={getStatusBadgeVariant(
|
||||
INVOICE_STATUS_LABEL[selectedInvoice.paymentStatus]
|
||||
)}
|
||||
className="text-xs"
|
||||
>
|
||||
{INVOICE_STATUS_LABEL[selectedInvoice.paymentStatus]}
|
||||
</Badge>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<ModalFooter className="sm:justify-end">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={handleCloseModal}
|
||||
disabled={modalState === "processing"}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleConfirmPayment}
|
||||
disabled={modalState === "processing" || isPending}
|
||||
className="relative"
|
||||
>
|
||||
{modalState === "processing" || isPending ? (
|
||||
<>
|
||||
<RiLoader4Line className="mr-1.5 size-4 animate-spin" />
|
||||
Processando...
|
||||
</>
|
||||
) : (
|
||||
"Confirmar pagamento"
|
||||
)}
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
130
components/dashboard/my-accounts-widget.tsx
Normal file
130
components/dashboard/my-accounts-widget.tsx
Normal file
@@ -0,0 +1,130 @@
|
||||
import {
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
} from "@/components/ui/card";
|
||||
import type { DashboardAccount } from "@/lib/dashboard/accounts";
|
||||
import { formatPeriodForUrl } from "@/lib/utils/period";
|
||||
import { RiBarChartBoxLine } from "@remixicon/react";
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import MoneyValues from "../money-values";
|
||||
import { WidgetEmptyState } from "../widget-empty-state";
|
||||
|
||||
type MyAccountsWidgetProps = {
|
||||
accounts: DashboardAccount[];
|
||||
totalBalance: number;
|
||||
maxVisible?: number;
|
||||
period: string;
|
||||
};
|
||||
|
||||
const resolveLogoSrc = (logo: string | null) => {
|
||||
if (!logo) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const fileName = logo.split("/").filter(Boolean).pop() ?? logo;
|
||||
return `/logos/${fileName}`;
|
||||
};
|
||||
|
||||
const buildInitials = (name: string) => {
|
||||
const parts = name.trim().split(/\s+/).filter(Boolean);
|
||||
if (parts.length === 0) return "CC";
|
||||
if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
|
||||
return `${parts[0][0] ?? ""}${parts[1][0] ?? ""}`.toUpperCase();
|
||||
};
|
||||
|
||||
export function MyAccountsWidget({
|
||||
accounts,
|
||||
totalBalance,
|
||||
maxVisible = 5,
|
||||
period,
|
||||
}: MyAccountsWidgetProps) {
|
||||
const visibleAccounts = accounts.filter(
|
||||
(account) => !account.excludeFromBalance
|
||||
);
|
||||
const displayedAccounts = visibleAccounts.slice(0, maxVisible);
|
||||
const remainingCount = visibleAccounts.length - displayedAccounts.length;
|
||||
|
||||
return (
|
||||
<>
|
||||
<CardHeader className="pb-4 px-0">
|
||||
<CardDescription>Saldo Total</CardDescription>
|
||||
<div className="text-2xl text-foreground">
|
||||
<MoneyValues amount={totalBalance} />
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="py-2 px-0">
|
||||
{displayedAccounts.length === 0 ? (
|
||||
<div className="-mt-10">
|
||||
<WidgetEmptyState
|
||||
icon={
|
||||
<RiBarChartBoxLine className="size-6 text-muted-foreground" />
|
||||
}
|
||||
title="Você ainda não adicionou nenhuma conta"
|
||||
description="Cadastre suas contas bancárias para acompanhar os saldos e movimentações."
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<ul className="flex flex-col">
|
||||
{displayedAccounts.map((account) => {
|
||||
const logoSrc = resolveLogoSrc(account.logo);
|
||||
const initials = buildInitials(account.name);
|
||||
|
||||
return (
|
||||
<li
|
||||
key={account.id}
|
||||
className="flex items-center justify-between gap-2 border-b border-dashed py-1"
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-3">
|
||||
{logoSrc ? (
|
||||
<div className="relative size-10 overflow-hidden">
|
||||
<Image
|
||||
src={logoSrc}
|
||||
alt={`Logo da conta ${account.name}`}
|
||||
fill
|
||||
className="object-contain rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-secondary text-sm font-semibold uppercase text-secondary-foreground">
|
||||
{initials}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="min-w-0">
|
||||
<Link
|
||||
prefetch
|
||||
href={`/contas/${
|
||||
account.id
|
||||
}/extrato?periodo=${formatPeriodForUrl(period)}`}
|
||||
className="truncate font-medium text-foreground hover:text-primary hover:underline"
|
||||
>
|
||||
<span className="truncate text-sm">{account.name}</span>
|
||||
</Link>
|
||||
<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
||||
<span className="truncate">{account.accountType}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col items-end gap-0.5 text-right">
|
||||
<MoneyValues amount={account.balance} />
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
{visibleAccounts.length > displayedAccounts.length ? (
|
||||
<CardFooter className="border-border/60 border-t pt-4 text-sm text-muted-foreground">
|
||||
+{remainingCount} contas não exibidas
|
||||
</CardFooter>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
88
components/dashboard/payment-conditions-widget.tsx
Normal file
88
components/dashboard/payment-conditions-widget.tsx
Normal file
@@ -0,0 +1,88 @@
|
||||
import MoneyValues from "@/components/money-values";
|
||||
import type { PaymentConditionsData } from "@/lib/dashboard/payments/payment-conditions";
|
||||
import {
|
||||
RiCheckLine,
|
||||
RiLoader2Fill,
|
||||
RiRefreshLine,
|
||||
RiSlideshowLine,
|
||||
} from "@remixicon/react";
|
||||
import type { ReactNode } from "react";
|
||||
import { Progress } from "../ui/progress";
|
||||
import { WidgetEmptyState } from "../widget-empty-state";
|
||||
|
||||
type PaymentConditionsWidgetProps = {
|
||||
data: PaymentConditionsData;
|
||||
};
|
||||
|
||||
const CONDITION_ICON_CLASSES =
|
||||
"flex size-10 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground";
|
||||
|
||||
const CONDITION_ICONS: Record<string, ReactNode> = {
|
||||
"À vista": <RiCheckLine className="size-5" aria-hidden />,
|
||||
Parcelado: <RiLoader2Fill className="size-5" aria-hidden />,
|
||||
Recorrente: <RiRefreshLine className="size-5" aria-hidden />,
|
||||
};
|
||||
|
||||
const formatPercentage = (value: number) =>
|
||||
new Intl.NumberFormat("pt-BR", {
|
||||
minimumFractionDigits: 0,
|
||||
maximumFractionDigits: 1,
|
||||
}).format(value);
|
||||
|
||||
export function PaymentConditionsWidget({
|
||||
data,
|
||||
}: PaymentConditionsWidgetProps) {
|
||||
if (data.conditions.length === 0) {
|
||||
return (
|
||||
<WidgetEmptyState
|
||||
icon={<RiSlideshowLine className="size-6 text-muted-foreground" />}
|
||||
title="Nenhuma despesa encontrada"
|
||||
description="As distribuições por condição aparecerão conforme novos lançamentos."
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 px-0">
|
||||
<ul className="flex flex-col gap-2">
|
||||
{data.conditions.map((condition) => {
|
||||
const Icon =
|
||||
CONDITION_ICONS[condition.condition] ?? CONDITION_ICONS["À vista"];
|
||||
const percentageLabel = formatPercentage(condition.percentage);
|
||||
|
||||
return (
|
||||
<li
|
||||
key={condition.condition}
|
||||
className="flex items-center gap-3 border-b border-dashed pb-4 last:border-b-0 last:pb-0"
|
||||
>
|
||||
<div className={CONDITION_ICON_CLASSES}>{Icon}</div>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<p className="font-medium text-foreground text-sm">
|
||||
{condition.condition}
|
||||
</p>
|
||||
<MoneyValues amount={condition.amount} />
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span>
|
||||
{condition.transactions}{" "}
|
||||
{condition.transactions === 1
|
||||
? "lançamento"
|
||||
: "lançamentos"}
|
||||
</span>
|
||||
<span>{percentageLabel}%</span>
|
||||
</div>
|
||||
|
||||
<div className="mt-1">
|
||||
<Progress value={condition.percentage} />
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
87
components/dashboard/payment-methods-widget.tsx
Normal file
87
components/dashboard/payment-methods-widget.tsx
Normal file
@@ -0,0 +1,87 @@
|
||||
import MoneyValues from "@/components/money-values";
|
||||
import type { PaymentMethodsData } from "@/lib/dashboard/payments/payment-methods";
|
||||
import { getPaymentMethodIcon } from "@/lib/utils/icons";
|
||||
import { RiBankCardLine, RiMoneyDollarCircleLine } from "@remixicon/react";
|
||||
import { Progress } from "../ui/progress";
|
||||
import { WidgetEmptyState } from "../widget-empty-state";
|
||||
|
||||
type PaymentMethodsWidgetProps = {
|
||||
data: PaymentMethodsData;
|
||||
};
|
||||
|
||||
const ICON_WRAPPER_CLASS =
|
||||
"flex size-10 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground";
|
||||
|
||||
const formatPercentage = (value: number) =>
|
||||
new Intl.NumberFormat("pt-BR", {
|
||||
minimumFractionDigits: 0,
|
||||
maximumFractionDigits: 1,
|
||||
}).format(value);
|
||||
|
||||
const resolveIcon = (paymentMethod: string | null | undefined) => {
|
||||
if (!paymentMethod) {
|
||||
return <RiMoneyDollarCircleLine className="size-5" aria-hidden />;
|
||||
}
|
||||
|
||||
const icon = getPaymentMethodIcon(paymentMethod);
|
||||
if (icon) {
|
||||
return icon;
|
||||
}
|
||||
|
||||
return <RiBankCardLine className="size-5" aria-hidden />;
|
||||
};
|
||||
|
||||
export function PaymentMethodsWidget({ data }: PaymentMethodsWidgetProps) {
|
||||
if (data.methods.length === 0) {
|
||||
return (
|
||||
<WidgetEmptyState
|
||||
icon={
|
||||
<RiMoneyDollarCircleLine className="size-6 text-muted-foreground" />
|
||||
}
|
||||
title="Nenhuma despesa encontrada"
|
||||
description="Cadastre despesas para visualizar a distribuição por forma de pagamento."
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 px-0">
|
||||
<ul className="flex flex-col gap-2">
|
||||
{data.methods.map((method) => {
|
||||
const icon = resolveIcon(method.paymentMethod);
|
||||
const percentageLabel = formatPercentage(method.percentage);
|
||||
|
||||
return (
|
||||
<li
|
||||
key={method.paymentMethod}
|
||||
className="flex items-center gap-3 border-b border-dashed pb-4 last:border-b-0 last:pb-0"
|
||||
>
|
||||
<div className={ICON_WRAPPER_CLASS}>{icon}</div>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<p className="font-medium text-foreground text-sm">
|
||||
{method.paymentMethod}
|
||||
</p>
|
||||
<MoneyValues amount={method.amount} />
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span>
|
||||
{method.transactions}{" "}
|
||||
{method.transactions === 1 ? "lançamento" : "lançamentos"}
|
||||
</span>
|
||||
<span>{percentageLabel}%</span>
|
||||
</div>
|
||||
|
||||
<div className="mt-1">
|
||||
<Progress value={method.percentage} />
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
100
components/dashboard/payment-status-widget.tsx
Normal file
100
components/dashboard/payment-status-widget.tsx
Normal file
@@ -0,0 +1,100 @@
|
||||
"use client";
|
||||
|
||||
import MoneyValues from "@/components/money-values";
|
||||
import { CardContent } from "@/components/ui/card";
|
||||
import { WidgetEmptyState } from "@/components/widget-empty-state";
|
||||
import type { PaymentStatusData } from "@/lib/dashboard/payments/payment-status";
|
||||
import {
|
||||
RiCheckboxCircleLine,
|
||||
RiHourglass2Line,
|
||||
RiWallet3Line,
|
||||
} from "@remixicon/react";
|
||||
import { Progress } from "../ui/progress";
|
||||
|
||||
type PaymentStatusWidgetProps = {
|
||||
data: PaymentStatusData;
|
||||
};
|
||||
|
||||
type CategorySectionProps = {
|
||||
title: string;
|
||||
total: number;
|
||||
confirmed: number;
|
||||
pending: number;
|
||||
};
|
||||
|
||||
function CategorySection({
|
||||
title,
|
||||
total,
|
||||
confirmed,
|
||||
pending,
|
||||
}: CategorySectionProps) {
|
||||
// Usa valores absolutos para calcular percentual corretamente
|
||||
const absTotal = Math.abs(total);
|
||||
const absConfirmed = Math.abs(confirmed);
|
||||
const confirmedPercentage =
|
||||
absTotal > 0 ? (absConfirmed / absTotal) * 100 : 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium text-foreground">{title}</span>
|
||||
<MoneyValues amount={total} />
|
||||
</div>
|
||||
|
||||
{/* Barra de progresso */}
|
||||
<Progress value={confirmedPercentage} className="h-2" />
|
||||
|
||||
{/* Status de confirmados e pendentes */}
|
||||
<div className="flex items-center justify-between gap-4 text-sm">
|
||||
<div className="flex items-center gap-1.5 ">
|
||||
<RiCheckboxCircleLine className="size-3 text-emerald-600" />
|
||||
<MoneyValues amount={confirmed} />
|
||||
<span className="text-xs text-muted-foreground">confirmados</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1.5 ">
|
||||
<RiHourglass2Line className="size-3 text-orange-500" />
|
||||
<MoneyValues amount={pending} />
|
||||
<span className="text-xs text-muted-foreground">pendentes</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PaymentStatusWidget({ data }: PaymentStatusWidgetProps) {
|
||||
const isEmpty = data.income.total === 0 && data.expenses.total === 0;
|
||||
|
||||
if (isEmpty) {
|
||||
return (
|
||||
<CardContent className="px-0">
|
||||
<WidgetEmptyState
|
||||
icon={<RiWallet3Line className="size-6 text-muted-foreground" />}
|
||||
title="Nenhum valor a receber ou pagar no período"
|
||||
description="Registre lançamentos para visualizar os valores confirmados e pendentes."
|
||||
/>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<CardContent className="space-y-6 px-0">
|
||||
<CategorySection
|
||||
title="A Receber"
|
||||
total={data.income.total}
|
||||
confirmed={data.income.confirmed}
|
||||
pending={data.income.pending}
|
||||
/>
|
||||
|
||||
{/* Linha divisória pontilhada */}
|
||||
<div className="border-t border-dashed" />
|
||||
|
||||
<CategorySection
|
||||
title="A Pagar"
|
||||
total={data.expenses.total}
|
||||
confirmed={data.expenses.confirmed}
|
||||
pending={data.expenses.pending}
|
||||
/>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
228
components/dashboard/purchases-by-category-widget.tsx
Normal file
228
components/dashboard/purchases-by-category-widget.tsx
Normal file
@@ -0,0 +1,228 @@
|
||||
"use client";
|
||||
|
||||
import MoneyValues from "@/components/money-values";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { CATEGORY_TYPE_LABEL } from "@/lib/categorias/constants";
|
||||
import type { PurchasesByCategoryData } from "@/lib/dashboard/purchases-by-category";
|
||||
import { RiArrowDownLine, RiStore3Line } from "@remixicon/react";
|
||||
import Image from "next/image";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { WidgetEmptyState } from "../widget-empty-state";
|
||||
|
||||
type PurchasesByCategoryWidgetProps = {
|
||||
data: PurchasesByCategoryData;
|
||||
};
|
||||
|
||||
const resolveLogoPath = (logo: string | null) => {
|
||||
if (!logo) {
|
||||
return null;
|
||||
}
|
||||
if (/^(https?:\/\/|data:)/.test(logo)) {
|
||||
return logo;
|
||||
}
|
||||
return logo.startsWith("/") ? logo : `/logos/${logo}`;
|
||||
};
|
||||
|
||||
const buildInitials = (value: string) => {
|
||||
const parts = value.trim().split(/\s+/).filter(Boolean);
|
||||
if (parts.length === 0) {
|
||||
return "LC";
|
||||
}
|
||||
if (parts.length === 1) {
|
||||
const firstPart = parts[0];
|
||||
return firstPart ? firstPart.slice(0, 2).toUpperCase() : "LC";
|
||||
}
|
||||
const firstChar = parts[0]?.[0] ?? "";
|
||||
const secondChar = parts[1]?.[0] ?? "";
|
||||
return `${firstChar}${secondChar}`.toUpperCase() || "LC";
|
||||
};
|
||||
|
||||
const formatTransactionDate = (date: Date) => {
|
||||
const formatter = new Intl.DateTimeFormat("pt-BR", {
|
||||
weekday: "short",
|
||||
day: "2-digit",
|
||||
month: "short",
|
||||
timeZone: "UTC",
|
||||
});
|
||||
|
||||
const formatted = formatter.format(date);
|
||||
// Capitaliza a primeira letra do dia da semana
|
||||
return formatted.charAt(0).toUpperCase() + formatted.slice(1);
|
||||
};
|
||||
|
||||
const STORAGE_KEY = "purchases-by-category-selected";
|
||||
|
||||
export function PurchasesByCategoryWidget({
|
||||
data,
|
||||
}: PurchasesByCategoryWidgetProps) {
|
||||
// Inicializa com a categoria salva ou a primeira disponível
|
||||
const [selectedCategoryId, setSelectedCategoryId] = useState<string>(() => {
|
||||
if (typeof window === "undefined") {
|
||||
const firstCategory = data.categories[0];
|
||||
return firstCategory ? firstCategory.id : "";
|
||||
}
|
||||
|
||||
const saved = sessionStorage.getItem(STORAGE_KEY);
|
||||
if (saved && data.categories.some((cat) => cat.id === saved)) {
|
||||
return saved;
|
||||
}
|
||||
|
||||
const firstCategory = data.categories[0];
|
||||
return firstCategory ? firstCategory.id : "";
|
||||
});
|
||||
|
||||
// Agrupa categorias por tipo
|
||||
const categoriesByType = useMemo(() => {
|
||||
const grouped: Record<string, typeof data.categories> = {};
|
||||
|
||||
for (const category of data.categories) {
|
||||
if (!grouped[category.type]) {
|
||||
grouped[category.type] = [];
|
||||
}
|
||||
const typeGroup = grouped[category.type];
|
||||
if (typeGroup) {
|
||||
typeGroup.push(category);
|
||||
}
|
||||
}
|
||||
|
||||
return grouped;
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [data.categories]);
|
||||
|
||||
// Salva a categoria selecionada quando mudar
|
||||
useEffect(() => {
|
||||
if (selectedCategoryId) {
|
||||
sessionStorage.setItem(STORAGE_KEY, selectedCategoryId);
|
||||
}
|
||||
}, [selectedCategoryId]);
|
||||
|
||||
// Atualiza a categoria selecionada se ela não existir mais na lista
|
||||
useEffect(() => {
|
||||
if (
|
||||
selectedCategoryId &&
|
||||
!data.categories.some((cat) => cat.id === selectedCategoryId)
|
||||
) {
|
||||
const firstCategory = data.categories[0];
|
||||
if (firstCategory) {
|
||||
setSelectedCategoryId(firstCategory.id);
|
||||
} else {
|
||||
setSelectedCategoryId("");
|
||||
}
|
||||
}
|
||||
}, [data.categories, selectedCategoryId]);
|
||||
|
||||
const currentTransactions = useMemo(() => {
|
||||
if (!selectedCategoryId) {
|
||||
return [];
|
||||
}
|
||||
return data.transactionsByCategory[selectedCategoryId] ?? [];
|
||||
}, [selectedCategoryId, data.transactionsByCategory]);
|
||||
|
||||
const selectedCategory = useMemo(() => {
|
||||
return data.categories.find((cat) => cat.id === selectedCategoryId);
|
||||
}, [data.categories, selectedCategoryId]);
|
||||
|
||||
if (data.categories.length === 0) {
|
||||
return (
|
||||
<WidgetEmptyState
|
||||
icon={<RiStore3Line className="size-6 text-muted-foreground" />}
|
||||
title="Nenhuma categoria encontrada"
|
||||
description="Crie categorias de despesas ou receitas para visualizar as compras."
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 px-0">
|
||||
<div className="flex items-center gap-3">
|
||||
<Select
|
||||
value={selectedCategoryId}
|
||||
onValueChange={setSelectedCategoryId}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="Selecione uma categoria" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{Object.entries(categoriesByType).map(([type, categories]) => (
|
||||
<div key={type}>
|
||||
<div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground">
|
||||
{CATEGORY_TYPE_LABEL[
|
||||
type as keyof typeof CATEGORY_TYPE_LABEL
|
||||
] ?? type}
|
||||
</div>
|
||||
{categories.map((category) => (
|
||||
<SelectItem key={category.id} value={category.id}>
|
||||
{category.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{currentTransactions.length === 0 ? (
|
||||
<WidgetEmptyState
|
||||
icon={<RiArrowDownLine className="size-6 text-muted-foreground" />}
|
||||
title="Nenhuma compra encontrada"
|
||||
description={
|
||||
selectedCategory
|
||||
? `Não há lançamentos na categoria "${selectedCategory.name}".`
|
||||
: "Selecione uma categoria para visualizar as compras."
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<ul className="flex flex-col">
|
||||
{currentTransactions.map((transaction) => {
|
||||
const logo = resolveLogoPath(transaction.logo);
|
||||
const initials = buildInitials(transaction.name);
|
||||
|
||||
return (
|
||||
<li
|
||||
key={transaction.id}
|
||||
className="flex items-center justify-between gap-3 border-b border-dashed py-2 last:border-b-0 last:pb-0"
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-3">
|
||||
<div className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted">
|
||||
{logo ? (
|
||||
<Image
|
||||
src={logo}
|
||||
alt={`Logo de ${transaction.name}`}
|
||||
width={48}
|
||||
height={48}
|
||||
className="h-full w-full object-contain"
|
||||
/>
|
||||
) : (
|
||||
<span className="text-sm font-semibold uppercase text-muted-foreground">
|
||||
{initials}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm font-medium text-foreground">
|
||||
{transaction.name}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{formatTransactionDate(transaction.purchaseDate)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="shrink-0 text-foreground">
|
||||
<MoneyValues amount={transaction.amount} />
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
109
components/dashboard/recent-transactions-widget.tsx
Normal file
109
components/dashboard/recent-transactions-widget.tsx
Normal file
@@ -0,0 +1,109 @@
|
||||
import MoneyValues from "@/components/money-values";
|
||||
import type { RecentTransactionsData } from "@/lib/dashboard/recent-transactions";
|
||||
import { RiExchangeLine } from "@remixicon/react";
|
||||
import Image from "next/image";
|
||||
import { WidgetEmptyState } from "../widget-empty-state";
|
||||
|
||||
type RecentTransactionsWidgetProps = {
|
||||
data: RecentTransactionsData;
|
||||
};
|
||||
|
||||
const resolveLogoPath = (logo: string | null) => {
|
||||
if (!logo) {
|
||||
return null;
|
||||
}
|
||||
if (/^(https?:\/\/|data:)/.test(logo)) {
|
||||
return logo;
|
||||
}
|
||||
return logo.startsWith("/") ? logo : `/logos/${logo}`;
|
||||
};
|
||||
|
||||
const buildInitials = (value: string) => {
|
||||
const parts = value.trim().split(/\s+/).filter(Boolean);
|
||||
if (parts.length === 0) {
|
||||
return "LC";
|
||||
}
|
||||
if (parts.length === 1) {
|
||||
const firstPart = parts[0];
|
||||
return firstPart ? firstPart.slice(0, 2).toUpperCase() : "LC";
|
||||
}
|
||||
const firstChar = parts[0]?.[0] ?? "";
|
||||
const secondChar = parts[1]?.[0] ?? "";
|
||||
return `${firstChar}${secondChar}`.toUpperCase() || "LC";
|
||||
};
|
||||
|
||||
const formatTransactionDate = (date: Date) => {
|
||||
const formatter = new Intl.DateTimeFormat("pt-BR", {
|
||||
weekday: "short",
|
||||
day: "2-digit",
|
||||
month: "short",
|
||||
timeZone: "UTC",
|
||||
});
|
||||
|
||||
const formatted = formatter.format(date);
|
||||
// Capitaliza a primeira letra do dia da semana
|
||||
return formatted.charAt(0).toUpperCase() + formatted.slice(1);
|
||||
};
|
||||
|
||||
export function RecentTransactionsWidget({
|
||||
data,
|
||||
}: RecentTransactionsWidgetProps) {
|
||||
return (
|
||||
<div className="flex flex-col px-0">
|
||||
{data.transactions.length === 0 ? (
|
||||
<WidgetEmptyState
|
||||
icon={<RiExchangeLine className="size-6 text-muted-foreground" />}
|
||||
title="Nenhum lançamento encontrado"
|
||||
description="Quando houver despesas registradas, elas aparecerão aqui."
|
||||
/>
|
||||
) : (
|
||||
<ul className="flex flex-col">
|
||||
{data.transactions.map((transaction) => {
|
||||
const logo = resolveLogoPath(
|
||||
transaction.cardLogo ?? transaction.accountLogo
|
||||
);
|
||||
const initials = buildInitials(transaction.name);
|
||||
|
||||
return (
|
||||
<li
|
||||
key={transaction.id}
|
||||
className="flex items-center justify-between gap-3 border-b border-dashed py-2 last:border-b-0 last:pb-0"
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-3">
|
||||
<div className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-lg">
|
||||
{logo ? (
|
||||
<Image
|
||||
src={logo}
|
||||
alt={`Logo de ${transaction.name}`}
|
||||
width={48}
|
||||
height={48}
|
||||
className="h-full w-full object-contain"
|
||||
/>
|
||||
) : (
|
||||
<span className="text-sm font-semibold uppercase text-muted-foreground">
|
||||
{initials}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm font-medium text-foreground">
|
||||
{transaction.name}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{formatTransactionDate(transaction.purchaseDate)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="shrink-0 text-foreground">
|
||||
<MoneyValues amount={transaction.amount} />
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
67
components/dashboard/recurring-expenses-widget.tsx
Normal file
67
components/dashboard/recurring-expenses-widget.tsx
Normal file
@@ -0,0 +1,67 @@
|
||||
import MoneyValues from "@/components/money-values";
|
||||
import { CardContent } from "@/components/ui/card";
|
||||
import type { RecurringExpensesData } from "@/lib/dashboard/expenses/recurring-expenses";
|
||||
import { RiRefreshLine } from "@remixicon/react";
|
||||
import { WidgetEmptyState } from "../widget-empty-state";
|
||||
|
||||
type RecurringExpensesWidgetProps = {
|
||||
data: RecurringExpensesData;
|
||||
};
|
||||
|
||||
const formatOccurrences = (value: number | null) => {
|
||||
if (!value) {
|
||||
return "Recorrência contínua";
|
||||
}
|
||||
|
||||
return `${value} recorrências`;
|
||||
};
|
||||
|
||||
export function RecurringExpensesWidget({
|
||||
data,
|
||||
}: RecurringExpensesWidgetProps) {
|
||||
if (data.expenses.length === 0) {
|
||||
return (
|
||||
<WidgetEmptyState
|
||||
icon={<RiRefreshLine className="size-6 text-muted-foreground" />}
|
||||
title="Nenhuma despesa recorrente"
|
||||
description="Lançamentos recorrentes aparecerão aqui conforme forem registrados."
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<CardContent className="flex flex-col gap-4 px-0">
|
||||
<ul className="flex flex-col gap-2">
|
||||
{data.expenses.map((expense) => {
|
||||
return (
|
||||
<li
|
||||
key={expense.id}
|
||||
className="flex items-start gap-3 border-b border-dashed pb-2 last:border-b-0 last:pb-0"
|
||||
>
|
||||
<div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-muted">
|
||||
<RiRefreshLine className="size-5 text-foreground" />
|
||||
</div>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<p className="truncate text-foreground text-sm font-medium">
|
||||
{expense.name}
|
||||
</p>
|
||||
|
||||
<MoneyValues amount={expense.amount} />
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
||||
<span className="inline-flex items-center gap-1">
|
||||
{expense.paymentMethod}
|
||||
</span>
|
||||
•<span>{formatOccurrences(expense.recurrenceCount)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
97
components/dashboard/section-cards.tsx
Normal file
97
components/dashboard/section-cards.tsx
Normal file
@@ -0,0 +1,97 @@
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
Card,
|
||||
CardAction,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import type { DashboardCardMetrics } from "@/lib/dashboard/metrics";
|
||||
import {
|
||||
RiArrowDownLine,
|
||||
RiArrowUpLine,
|
||||
RiCurrencyLine,
|
||||
RiIncreaseDecreaseLine,
|
||||
RiSubtractLine,
|
||||
} from "@remixicon/react";
|
||||
import MoneyValues from "../money-values";
|
||||
|
||||
type SectionCardsProps = {
|
||||
metrics: DashboardCardMetrics;
|
||||
};
|
||||
|
||||
type Trend = "up" | "down" | "flat";
|
||||
|
||||
const TREND_THRESHOLD = 0.005;
|
||||
|
||||
const CARDS = [
|
||||
{ label: "Receitas", key: "receitas", icon: RiArrowUpLine },
|
||||
{ label: "Despesas", key: "despesas", icon: RiArrowDownLine },
|
||||
{ label: "Balanço", key: "balanco", icon: RiIncreaseDecreaseLine },
|
||||
{ label: "Previsto", key: "previsto", icon: RiCurrencyLine },
|
||||
] as const;
|
||||
|
||||
const TREND_ICONS = {
|
||||
up: RiArrowUpLine,
|
||||
down: RiArrowDownLine,
|
||||
flat: RiSubtractLine,
|
||||
} as const;
|
||||
|
||||
const getTrend = (current: number, previous: number): Trend => {
|
||||
const diff = current - previous;
|
||||
if (diff > TREND_THRESHOLD) return "up";
|
||||
if (diff < -TREND_THRESHOLD) return "down";
|
||||
return "flat";
|
||||
};
|
||||
|
||||
const getPercentChange = (current: number, previous: number): string => {
|
||||
const EPSILON = 0.01; // Considera valores menores que 1 centavo como zero
|
||||
|
||||
if (Math.abs(previous) < EPSILON) {
|
||||
if (Math.abs(current) < EPSILON) return "0%";
|
||||
return "—";
|
||||
}
|
||||
|
||||
const change = ((current - previous) / Math.abs(previous)) * 100;
|
||||
return Number.isFinite(change) && Math.abs(change) < 1000000
|
||||
? `${change > 0 ? "+" : ""}${change.toFixed(1)}%`
|
||||
: "—";
|
||||
};
|
||||
|
||||
export function SectionCards({ metrics }: SectionCardsProps) {
|
||||
return (
|
||||
<div className="*:data-[slot=card]:from-primary/5 *:data-[slot=card]:to-card dark:*:data-[slot=card]:bg-card grid grid-cols-1 gap-3 @xl/main:grid-cols-2 @5xl/main:grid-cols-4">
|
||||
{CARDS.map(({ label, key, icon: Icon }) => {
|
||||
const metric = metrics[key];
|
||||
const trend = getTrend(metric.current, metric.previous);
|
||||
const TrendIcon = TREND_ICONS[trend];
|
||||
|
||||
return (
|
||||
<Card key={label} className="@container/card gap-2">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-1">
|
||||
<Icon className="size-4" />
|
||||
{label}
|
||||
</CardTitle>
|
||||
<MoneyValues className="text-2xl" amount={metric.current} />
|
||||
<CardAction>
|
||||
<Badge variant="outline">
|
||||
<TrendIcon />
|
||||
{getPercentChange(metric.current, metric.previous)}
|
||||
</Badge>
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
<CardFooter className="flex-col items-start gap-1.5 text-sm">
|
||||
<div className="line-clamp-1 flex gap-2 text-sm">
|
||||
Mês anterior:
|
||||
</div>
|
||||
<div className="text-muted-foreground">
|
||||
<MoneyValues amount={metric.previous} />
|
||||
</div>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
101
components/dashboard/top-establishments-widget.tsx
Normal file
101
components/dashboard/top-establishments-widget.tsx
Normal file
@@ -0,0 +1,101 @@
|
||||
import MoneyValues from "@/components/money-values";
|
||||
import type { TopEstablishmentsData } from "@/lib/dashboard/top-establishments";
|
||||
import { RiStore2Line } from "@remixicon/react";
|
||||
import Image from "next/image";
|
||||
import { WidgetEmptyState } from "../widget-empty-state";
|
||||
|
||||
type TopEstablishmentsWidgetProps = {
|
||||
data: TopEstablishmentsData;
|
||||
};
|
||||
|
||||
const resolveLogoPath = (logo: string | null) => {
|
||||
if (!logo) {
|
||||
return null;
|
||||
}
|
||||
if (/^(https?:\/\/|data:)/.test(logo)) {
|
||||
return logo;
|
||||
}
|
||||
return logo.startsWith("/") ? logo : `/logos/${logo}`;
|
||||
};
|
||||
|
||||
const buildInitials = (value: string) => {
|
||||
const parts = value.trim().split(/\s+/).filter(Boolean);
|
||||
if (parts.length === 0) {
|
||||
return "LC";
|
||||
}
|
||||
if (parts.length === 1) {
|
||||
const firstPart = parts[0];
|
||||
return firstPart ? firstPart.slice(0, 2).toUpperCase() : "LC";
|
||||
}
|
||||
const firstChar = parts[0]?.[0] ?? "";
|
||||
const secondChar = parts[1]?.[0] ?? "";
|
||||
return `${firstChar}${secondChar}`.toUpperCase() || "LC";
|
||||
};
|
||||
|
||||
const formatOccurrencesLabel = (occurrences: number) => {
|
||||
if (occurrences === 1) {
|
||||
return "1 lançamento";
|
||||
}
|
||||
return `${occurrences} lançamentos`;
|
||||
};
|
||||
|
||||
export function TopEstablishmentsWidget({
|
||||
data,
|
||||
}: TopEstablishmentsWidgetProps) {
|
||||
return (
|
||||
<div className="flex flex-col px-0">
|
||||
{data.establishments.length === 0 ? (
|
||||
<WidgetEmptyState
|
||||
icon={<RiStore2Line className="size-6 text-muted-foreground" />}
|
||||
title="Nenhum estabelecimento encontrado"
|
||||
description="Quando houver despesas registradas, elas aparecerão aqui."
|
||||
/>
|
||||
) : (
|
||||
<ul className="flex flex-col">
|
||||
{data.establishments.map((establishment) => {
|
||||
const logo = resolveLogoPath(establishment.logo);
|
||||
const initials = buildInitials(establishment.name);
|
||||
|
||||
return (
|
||||
<li
|
||||
key={establishment.id}
|
||||
className="flex items-center justify-between gap-3 border-b border-dashed py-2 last:border-b-0 last:pb-0"
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-3">
|
||||
<div className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted">
|
||||
{logo ? (
|
||||
<Image
|
||||
src={logo}
|
||||
alt={`Logo de ${establishment.name}`}
|
||||
width={48}
|
||||
height={48}
|
||||
className="h-full w-full object-contain"
|
||||
/>
|
||||
) : (
|
||||
<span className="text-sm font-semibold uppercase text-muted-foreground">
|
||||
{initials}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm font-medium text-foreground">
|
||||
{establishment.name}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{formatOccurrencesLabel(establishment.occurrences)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="shrink-0 text-foreground">
|
||||
<MoneyValues amount={establishment.amount} />
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
177
components/dashboard/top-expenses-widget.tsx
Normal file
177
components/dashboard/top-expenses-widget.tsx
Normal file
@@ -0,0 +1,177 @@
|
||||
"use client";
|
||||
|
||||
import MoneyValues from "@/components/money-values";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import type { TopExpense, TopExpensesData } from "@/lib/dashboard/expenses/top-expenses";
|
||||
import { RiArrowUpDoubleLine } from "@remixicon/react";
|
||||
import Image from "next/image";
|
||||
import { useMemo, useState } from "react";
|
||||
import { WidgetEmptyState } from "../widget-empty-state";
|
||||
|
||||
type TopExpensesWidgetProps = {
|
||||
allExpenses: TopExpensesData;
|
||||
cardOnlyExpenses: TopExpensesData;
|
||||
};
|
||||
|
||||
const resolveLogoPath = (logo: string | null) => {
|
||||
if (!logo) {
|
||||
return null;
|
||||
}
|
||||
if (/^(https?:\/\/|data:)/.test(logo)) {
|
||||
return logo;
|
||||
}
|
||||
return logo.startsWith("/") ? logo : `/logos/${logo}`;
|
||||
};
|
||||
|
||||
const buildInitials = (value: string) => {
|
||||
const parts = value.trim().split(/\s+/).filter(Boolean);
|
||||
if (parts.length === 0) {
|
||||
return "LC";
|
||||
}
|
||||
if (parts.length === 1) {
|
||||
const firstPart = parts[0];
|
||||
return firstPart ? firstPart.slice(0, 2).toUpperCase() : "LC";
|
||||
}
|
||||
const firstChar = parts[0]?.[0] ?? "";
|
||||
const secondChar = parts[1]?.[0] ?? "";
|
||||
return `${firstChar}${secondChar}`.toUpperCase() || "LC";
|
||||
};
|
||||
|
||||
const formatTransactionDate = (date: Date) => {
|
||||
const formatter = new Intl.DateTimeFormat("pt-BR", {
|
||||
weekday: "short",
|
||||
day: "2-digit",
|
||||
month: "short",
|
||||
timeZone: "UTC",
|
||||
});
|
||||
|
||||
const formatted = formatter.format(date);
|
||||
// Capitaliza a primeira letra do dia da semana
|
||||
return formatted.charAt(0).toUpperCase() + formatted.slice(1);
|
||||
};
|
||||
|
||||
const shouldIncludeExpense = (expense: TopExpense) => {
|
||||
const normalizedName = expense.name.trim().toLowerCase();
|
||||
|
||||
if (normalizedName === "saldo inicial") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (normalizedName.includes("fatura")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
const isCardExpense = (expense: TopExpense) =>
|
||||
expense.paymentMethod?.toLowerCase().includes("cartão") ?? false;
|
||||
|
||||
export function TopExpensesWidget({
|
||||
allExpenses,
|
||||
cardOnlyExpenses,
|
||||
}: TopExpensesWidgetProps) {
|
||||
const [cardOnly, setCardOnly] = useState(false);
|
||||
const normalizedAllExpenses = useMemo(() => {
|
||||
return allExpenses.expenses.filter(shouldIncludeExpense);
|
||||
}, [allExpenses]);
|
||||
|
||||
const normalizedCardOnlyExpenses = useMemo(() => {
|
||||
const merged = [...cardOnlyExpenses.expenses, ...normalizedAllExpenses];
|
||||
const seen = new Set<string>();
|
||||
|
||||
return merged.filter((expense) => {
|
||||
if (seen.has(expense.id)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!isCardExpense(expense) || !shouldIncludeExpense(expense)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
seen.add(expense.id);
|
||||
return true;
|
||||
});
|
||||
}, [cardOnlyExpenses, normalizedAllExpenses]);
|
||||
|
||||
const data = cardOnly
|
||||
? { expenses: normalizedCardOnlyExpenses }
|
||||
: { expenses: normalizedAllExpenses };
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 px-0">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<label
|
||||
htmlFor="card-only-toggle"
|
||||
className="text-sm text-muted-foreground"
|
||||
>
|
||||
{cardOnly
|
||||
? "Somente cartões de crédito ou débito."
|
||||
: "Todas as despesas"}
|
||||
</label>
|
||||
<Switch
|
||||
id="card-only-toggle"
|
||||
checked={cardOnly}
|
||||
onCheckedChange={setCardOnly}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{data.expenses.length === 0 ? (
|
||||
<div className="-mt-10">
|
||||
<WidgetEmptyState
|
||||
icon={
|
||||
<RiArrowUpDoubleLine className="size-6 text-muted-foreground" />
|
||||
}
|
||||
title="Nenhuma despesa encontrada"
|
||||
description="Quando houver despesas registradas, elas aparecerão aqui."
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<ul className="flex flex-col">
|
||||
{data.expenses.map((expense) => {
|
||||
const logo = resolveLogoPath(expense.logo);
|
||||
const initials = buildInitials(expense.name);
|
||||
|
||||
return (
|
||||
<li
|
||||
key={expense.id}
|
||||
className="flex items-center justify-between gap-3 border-b border-dashed py-2 last:border-b-0 last:pb-0"
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-3">
|
||||
<div className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted">
|
||||
{logo ? (
|
||||
<Image
|
||||
src={logo}
|
||||
alt={`Logo de ${expense.name}`}
|
||||
width={48}
|
||||
height={48}
|
||||
className="h-full w-full object-contain"
|
||||
/>
|
||||
) : (
|
||||
<span className="text-sm font-semibold uppercase text-muted-foreground">
|
||||
{initials}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm font-medium text-foreground">
|
||||
{expense.name}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{formatTransactionDate(expense.purchaseDate)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="shrink-0 text-foreground">
|
||||
<MoneyValues amount={expense.amount} />
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
11
components/dot-icon.tsx
Normal file
11
components/dot-icon.tsx
Normal file
@@ -0,0 +1,11 @@
|
||||
type DotIconProps = {
|
||||
bg_dot: string;
|
||||
};
|
||||
|
||||
export default function DotIcon({ bg_dot }: DotIconProps) {
|
||||
return (
|
||||
<span>
|
||||
<span className={`${bg_dot} flex h-2 w-2 rounded-full`}></span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
53
components/empty-state.tsx
Normal file
53
components/empty-state.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
import {
|
||||
Empty,
|
||||
EmptyContent,
|
||||
EmptyDescription,
|
||||
EmptyHeader,
|
||||
EmptyMedia,
|
||||
EmptyTitle,
|
||||
} from "@/components/ui/empty";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
interface EmptyStateProps {
|
||||
title: ReactNode;
|
||||
description?: ReactNode;
|
||||
action?: ReactNode;
|
||||
media?: ReactNode;
|
||||
mediaVariant?: "default" | "icon";
|
||||
className?: string;
|
||||
contentClassName?: string;
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
export function EmptyState({
|
||||
title,
|
||||
description,
|
||||
media,
|
||||
mediaVariant = "default",
|
||||
className,
|
||||
contentClassName,
|
||||
children,
|
||||
}: EmptyStateProps) {
|
||||
const hasContent = Boolean(children);
|
||||
|
||||
return (
|
||||
<Empty className={cn("w-full max-w-xl min-h-[320px]", className)}>
|
||||
<EmptyHeader>
|
||||
{media ? (
|
||||
<EmptyMedia variant={mediaVariant} className="mb-0">
|
||||
{media}
|
||||
</EmptyMedia>
|
||||
) : null}
|
||||
<EmptyTitle>{title}</EmptyTitle>
|
||||
{description ? (
|
||||
<EmptyDescription>{description}</EmptyDescription>
|
||||
) : null}
|
||||
</EmptyHeader>
|
||||
|
||||
{hasContent ? (
|
||||
<EmptyContent className={cn(contentClassName)}>{children}</EmptyContent>
|
||||
) : null}
|
||||
</Empty>
|
||||
);
|
||||
}
|
||||
75
components/faturas/edit-payment-date-dialog.tsx
Normal file
75
components/faturas/edit-payment-date-dialog.tsx
Normal file
@@ -0,0 +1,75 @@
|
||||
"use client";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DatePicker } from "@/components/ui/date-picker";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { useState } from "react";
|
||||
|
||||
type EditPaymentDateDialogProps = {
|
||||
trigger: React.ReactNode;
|
||||
currentDate: Date;
|
||||
onDateChange: (date: Date) => void;
|
||||
};
|
||||
|
||||
export function EditPaymentDateDialog({
|
||||
trigger,
|
||||
currentDate,
|
||||
onDateChange,
|
||||
}: EditPaymentDateDialogProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [selectedDate, setSelectedDate] = useState<Date>(currentDate);
|
||||
|
||||
const handleSave = () => {
|
||||
onDateChange(selectedDate);
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>{trigger}</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Editar data de pagamento</DialogTitle>
|
||||
<DialogDescription>
|
||||
Selecione a data em que o pagamento foi realizado.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="payment-date">Data de pagamento</Label>
|
||||
<DatePicker
|
||||
id="payment-date"
|
||||
value={selectedDate.toISOString().split("T")[0] ?? ""}
|
||||
onChange={(value) => {
|
||||
if (value) {
|
||||
setSelectedDate(new Date(value));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button type="button" onClick={handleSave}>
|
||||
Salvar
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
361
components/faturas/invoice-summary-card.tsx
Normal file
361
components/faturas/invoice-summary-card.tsx
Normal file
@@ -0,0 +1,361 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
updateInvoicePaymentStatusAction,
|
||||
updatePaymentDateAction,
|
||||
} from "@/app/(dashboard)/cartoes/[cartaoId]/fatura/actions";
|
||||
import DotIcon from "@/components/dot-icon";
|
||||
import MoneyValues from "@/components/money-values";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import {
|
||||
INVOICE_PAYMENT_STATUS,
|
||||
INVOICE_STATUS_BADGE_VARIANT,
|
||||
INVOICE_STATUS_DESCRIPTION,
|
||||
INVOICE_STATUS_LABEL,
|
||||
type InvoicePaymentStatus,
|
||||
} from "@/lib/faturas";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import { RiEditLine } from "@remixicon/react";
|
||||
import Image from "next/image";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useMemo, useState, useTransition } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { EditPaymentDateDialog } from "./edit-payment-date-dialog";
|
||||
|
||||
type InvoiceSummaryCardProps = {
|
||||
cartaoId: string;
|
||||
period: string;
|
||||
cardName: string;
|
||||
cardBrand: string | null;
|
||||
cardStatus: string | null;
|
||||
closingDay: string;
|
||||
dueDay: string;
|
||||
periodLabel: string;
|
||||
totalAmount: number;
|
||||
limitAmount: number | null;
|
||||
invoiceStatus: InvoicePaymentStatus;
|
||||
paymentDate: Date | null;
|
||||
logo?: string | null;
|
||||
actions?: React.ReactNode;
|
||||
};
|
||||
|
||||
const BRAND_ASSETS: Record<string, string> = {
|
||||
visa: "/bandeiras/visa.svg",
|
||||
mastercard: "/bandeiras/mastercard.svg",
|
||||
amex: "/bandeiras/amex.svg",
|
||||
american: "/bandeiras/amex.svg",
|
||||
elo: "/bandeiras/elo.svg",
|
||||
hipercard: "/bandeiras/hipercard.svg",
|
||||
hiper: "/bandeiras/hipercard.svg",
|
||||
};
|
||||
|
||||
const resolveBrandAsset = (brand: string) => {
|
||||
const normalized = brand.trim().toLowerCase();
|
||||
|
||||
const match = (
|
||||
Object.keys(BRAND_ASSETS) as Array<keyof typeof BRAND_ASSETS>
|
||||
).find((entry) => normalized.includes(entry));
|
||||
|
||||
return match ? BRAND_ASSETS[match] : null;
|
||||
};
|
||||
|
||||
const actionLabelByStatus: Record<InvoicePaymentStatus, string> = {
|
||||
[INVOICE_PAYMENT_STATUS.PENDING]: "Marcar como paga",
|
||||
[INVOICE_PAYMENT_STATUS.PAID]: "Desfazer pagamento",
|
||||
};
|
||||
|
||||
const actionVariantByStatus: Record<
|
||||
InvoicePaymentStatus,
|
||||
"default" | "outline"
|
||||
> = {
|
||||
[INVOICE_PAYMENT_STATUS.PENDING]: "default",
|
||||
[INVOICE_PAYMENT_STATUS.PAID]: "outline",
|
||||
};
|
||||
|
||||
const formatDay = (value: string) => value.padStart(2, "0");
|
||||
|
||||
const resolveLogoPath = (logo?: string | null) => {
|
||||
if (!logo) return null;
|
||||
if (
|
||||
logo.startsWith("http://") ||
|
||||
logo.startsWith("https://") ||
|
||||
logo.startsWith("data:")
|
||||
) {
|
||||
return logo;
|
||||
}
|
||||
|
||||
return logo.startsWith("/") ? logo : `/logos/${logo}`;
|
||||
};
|
||||
|
||||
const getCardStatusDotColor = (status: string | null) => {
|
||||
if (!status) return "bg-gray-400";
|
||||
const normalizedStatus = status.toLowerCase();
|
||||
if (normalizedStatus === "ativo" || normalizedStatus === "active") {
|
||||
return "bg-green-500";
|
||||
}
|
||||
return "bg-gray-400";
|
||||
};
|
||||
|
||||
export function InvoiceSummaryCard({
|
||||
cartaoId,
|
||||
period,
|
||||
cardName,
|
||||
cardBrand,
|
||||
cardStatus,
|
||||
closingDay,
|
||||
dueDay,
|
||||
periodLabel,
|
||||
totalAmount,
|
||||
limitAmount,
|
||||
invoiceStatus,
|
||||
paymentDate: initialPaymentDate,
|
||||
logo,
|
||||
actions,
|
||||
}: InvoiceSummaryCardProps) {
|
||||
const router = useRouter();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [paymentDate, setPaymentDate] = useState<Date>(
|
||||
initialPaymentDate ?? new Date()
|
||||
);
|
||||
|
||||
// Atualizar estado quando initialPaymentDate mudar
|
||||
useEffect(() => {
|
||||
if (initialPaymentDate) {
|
||||
setPaymentDate(initialPaymentDate);
|
||||
}
|
||||
}, [initialPaymentDate]);
|
||||
|
||||
const logoPath = useMemo(() => resolveLogoPath(logo), [logo]);
|
||||
|
||||
const brandAsset = useMemo(
|
||||
() => (cardBrand ? resolveBrandAsset(cardBrand) : null),
|
||||
[cardBrand]
|
||||
);
|
||||
|
||||
const limitLabel = useMemo(() => {
|
||||
if (typeof limitAmount !== "number") return "—";
|
||||
return limitAmount.toLocaleString("pt-BR", {
|
||||
style: "currency",
|
||||
currency: "BRL",
|
||||
maximumFractionDigits: 2,
|
||||
});
|
||||
}, [limitAmount]);
|
||||
|
||||
const targetStatus =
|
||||
invoiceStatus === INVOICE_PAYMENT_STATUS.PAID
|
||||
? INVOICE_PAYMENT_STATUS.PENDING
|
||||
: INVOICE_PAYMENT_STATUS.PAID;
|
||||
|
||||
const handleAction = () => {
|
||||
startTransition(async () => {
|
||||
const result = await updateInvoicePaymentStatusAction({
|
||||
cartaoId,
|
||||
period,
|
||||
status: targetStatus,
|
||||
paymentDate:
|
||||
targetStatus === INVOICE_PAYMENT_STATUS.PAID
|
||||
? paymentDate.toISOString().split("T")[0]
|
||||
: undefined,
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
router.refresh();
|
||||
return;
|
||||
}
|
||||
|
||||
toast.error(result.error);
|
||||
});
|
||||
};
|
||||
|
||||
const handleDateChange = (newDate: Date) => {
|
||||
setPaymentDate(newDate);
|
||||
startTransition(async () => {
|
||||
const result = await updatePaymentDateAction({
|
||||
cartaoId,
|
||||
period,
|
||||
paymentDate: newDate.toISOString().split("T")[0] ?? "",
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
router.refresh();
|
||||
return;
|
||||
}
|
||||
|
||||
toast.error(result.error);
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="border">
|
||||
<CardHeader className="flex flex-col gap-3">
|
||||
<div className="flex items-start gap-3">
|
||||
{logoPath ? (
|
||||
<div className="flex size-12 shrink-0 items-center justify-center overflow-hidden rounded-lg border border-border/60 bg-background">
|
||||
<Image
|
||||
src={logoPath}
|
||||
alt={`Logo do cartão ${cardName}`}
|
||||
width={48}
|
||||
height={48}
|
||||
className="h-full w-full object-contain"
|
||||
/>
|
||||
</div>
|
||||
) : cardBrand ? (
|
||||
<span className="flex size-12 shrink-0 items-center justify-center rounded-lg border border-border/60 bg-background text-sm font-semibold text-muted-foreground">
|
||||
{cardBrand}
|
||||
</span>
|
||||
) : null}
|
||||
|
||||
<div className="flex w-full items-start justify-between gap-3">
|
||||
<div className="space-y-1">
|
||||
<CardTitle className="text-xl font-semibold text-foreground">
|
||||
{cardName}
|
||||
</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Fatura de {periodLabel}
|
||||
</p>
|
||||
</div>
|
||||
{actions ? <div className="shrink-0">{actions}</div> : null}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-4 border-t border-border/60 border-dashed pt-4">
|
||||
{/* Destaque Principal */}
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<DetailItem
|
||||
label="Valor total"
|
||||
value={
|
||||
<MoneyValues
|
||||
amount={totalAmount}
|
||||
className="text-2xl text-foreground"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<DetailItem
|
||||
label="Status da fatura"
|
||||
value={
|
||||
<Badge
|
||||
variant={INVOICE_STATUS_BADGE_VARIANT[invoiceStatus]}
|
||||
className="text-xs"
|
||||
>
|
||||
{INVOICE_STATUS_LABEL[invoiceStatus]}
|
||||
</Badge>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Informações Gerais */}
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
|
||||
<DetailItem
|
||||
label="Fechamento"
|
||||
value={
|
||||
<span className="font-medium">Dia {formatDay(closingDay)}</span>
|
||||
}
|
||||
/>
|
||||
<DetailItem
|
||||
label="Vencimento"
|
||||
value={<span className="font-medium">Dia {formatDay(dueDay)}</span>}
|
||||
/>
|
||||
<DetailItem
|
||||
label="Bandeira"
|
||||
value={
|
||||
brandAsset ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<Image
|
||||
src={brandAsset}
|
||||
alt={`Bandeira ${cardBrand}`}
|
||||
width={32}
|
||||
height={32}
|
||||
className="h-5 w-auto rounded"
|
||||
/>
|
||||
<span className="truncate">{cardBrand}</span>
|
||||
</div>
|
||||
) : cardBrand ? (
|
||||
<span className="truncate">{cardBrand}</span>
|
||||
) : (
|
||||
<span className="text-muted-foreground">—</span>
|
||||
)
|
||||
}
|
||||
/>
|
||||
<DetailItem
|
||||
label="Status cartão"
|
||||
value={
|
||||
cardStatus ? (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<DotIcon bg_dot={getCardStatusDotColor(cardStatus)} />
|
||||
<span className="truncate">{cardStatus}</span>
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-muted-foreground">—</span>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DetailItem
|
||||
label="Limite do cartão"
|
||||
value={limitLabel}
|
||||
className="sm:w-1/2"
|
||||
/>
|
||||
|
||||
{/* Ações */}
|
||||
<div className="flex flex-col gap-2 pt-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{INVOICE_STATUS_DESCRIPTION[invoiceStatus]}
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant={actionVariantByStatus[invoiceStatus]}
|
||||
disabled={isPending}
|
||||
onClick={handleAction}
|
||||
className="w-full shrink-0 sm:w-auto"
|
||||
>
|
||||
{isPending ? "Salvando..." : actionLabelByStatus[invoiceStatus]}
|
||||
</Button>
|
||||
{invoiceStatus === INVOICE_PAYMENT_STATUS.PAID && (
|
||||
<EditPaymentDateDialog
|
||||
trigger={
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="shrink-0"
|
||||
aria-label="Editar data de pagamento"
|
||||
>
|
||||
<RiEditLine className="size-4" />
|
||||
</Button>
|
||||
}
|
||||
currentDate={paymentDate}
|
||||
onDateChange={handleDateChange}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
type DetailItemProps = {
|
||||
label?: string;
|
||||
value: React.ReactNode;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
function DetailItem({ label, value, className }: DetailItemProps) {
|
||||
return (
|
||||
<div className={cn("space-y-1", className)}>
|
||||
{label && (
|
||||
<span className="block text-xs font-medium uppercase text-muted-foreground/80">
|
||||
{label}
|
||||
</span>
|
||||
)}
|
||||
<div className="text-base text-foreground">{value}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
32
components/header-dashboard.tsx
Normal file
32
components/header-dashboard.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
import { NotificationBell } from "@/components/notifications/notification-bell";
|
||||
import { SidebarTrigger } from "@/components/ui/sidebar";
|
||||
import type { DashboardNotificationsSnapshot } from "@/lib/dashboard/notifications";
|
||||
import LogoutButton from "./auth/logout-button";
|
||||
import { AnimatedThemeToggler } from "./animated-theme-toggler";
|
||||
import { PrivacyModeToggle } from "./privacy-mode-toggle";
|
||||
import { CalculatorDialogButton } from "./calculadora/calculator-dialog";
|
||||
|
||||
type SiteHeaderProps = {
|
||||
notificationsSnapshot: DashboardNotificationsSnapshot;
|
||||
};
|
||||
|
||||
export function SiteHeader({ notificationsSnapshot }: SiteHeaderProps) {
|
||||
return (
|
||||
<header className="border-b flex h-12 shrink-0 items-center gap-2 transition-[width,height] ease-linear group-has-data-[collapsible=icon]/sidebar-wrapper:h-12">
|
||||
<div className="flex w-full items-center gap-1 px-4 lg:gap-2 lg:px-6">
|
||||
<SidebarTrigger className="-ml-1" />
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<CalculatorDialogButton withTooltip />
|
||||
<span className="text-muted-foreground">|</span>
|
||||
<NotificationBell
|
||||
notifications={notificationsSnapshot.notifications}
|
||||
totalCount={notificationsSnapshot.totalCount}
|
||||
/>
|
||||
<PrivacyModeToggle />
|
||||
<AnimatedThemeToggler />
|
||||
<LogoutButton />
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
110
components/insights/insights-grid.tsx
Normal file
110
components/insights/insights-grid.tsx
Normal file
@@ -0,0 +1,110 @@
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import type {
|
||||
InsightCategoryId,
|
||||
InsightsResponse,
|
||||
} from "@/lib/schemas/insights";
|
||||
import { INSIGHT_CATEGORIES } from "@/lib/schemas/insights";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import {
|
||||
RiChatAi3Line,
|
||||
RiEyeLine,
|
||||
RiFlashlightLine,
|
||||
RiLightbulbLine,
|
||||
RiRocketLine,
|
||||
type RemixiconComponentType,
|
||||
} from "@remixicon/react";
|
||||
import { format } from "date-fns";
|
||||
import { ptBR } from "date-fns/locale";
|
||||
|
||||
interface InsightsGridProps {
|
||||
insights: InsightsResponse;
|
||||
}
|
||||
|
||||
const CATEGORY_ICONS: Record<InsightCategoryId, RemixiconComponentType> = {
|
||||
behaviors: RiEyeLine,
|
||||
triggers: RiFlashlightLine,
|
||||
recommendations: RiLightbulbLine,
|
||||
improvements: RiRocketLine,
|
||||
};
|
||||
|
||||
const CATEGORY_COLORS: Record<
|
||||
InsightCategoryId,
|
||||
{ titleText: string; chatAiIcon: string }
|
||||
> = {
|
||||
behaviors: {
|
||||
titleText: "text-orange-700 dark:text-orange-400",
|
||||
chatAiIcon: "text-orange-600 dark:text-orange-400",
|
||||
},
|
||||
triggers: {
|
||||
titleText: "text-amber-700 dark:text-amber-400 ",
|
||||
chatAiIcon: "text-amber-600 dark:text-amber-400",
|
||||
},
|
||||
recommendations: {
|
||||
titleText: "text-sky-700 dark:text-sky-400",
|
||||
chatAiIcon: "text-sky-600 dark:text-sky-400",
|
||||
},
|
||||
improvements: {
|
||||
titleText: "text-emerald-700 dark:text-emerald-400",
|
||||
chatAiIcon: "text-emerald-600 dark:text-emerald-400",
|
||||
},
|
||||
};
|
||||
|
||||
export function InsightsGrid({ insights }: InsightsGridProps) {
|
||||
// Formatar o período para exibição
|
||||
const [year, month] = insights.month.split("-");
|
||||
const periodDate = new Date(parseInt(year), parseInt(month) - 1);
|
||||
const formattedPeriod = format(periodDate, "MMMM 'de' yyyy", {
|
||||
locale: ptBR,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-2 px-1 text-muted-foreground">
|
||||
<p>
|
||||
No período selecionado ({formattedPeriod}), identificamos os
|
||||
principais comportamentos e gatilhos que impactaram seu padrão de
|
||||
consumo.
|
||||
</p>
|
||||
<p>Segue um panorama prático com recomendações acionáveis.</p>
|
||||
</div>
|
||||
|
||||
{/* Grid de Cards */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
{insights.categories.map((categoryData) => {
|
||||
const categoryConfig = INSIGHT_CATEGORIES[categoryData.category];
|
||||
const colors = CATEGORY_COLORS[categoryData.category];
|
||||
const Icon = CATEGORY_ICONS[categoryData.category];
|
||||
|
||||
return (
|
||||
<Card
|
||||
key={categoryData.category}
|
||||
className="relative overflow-hidden"
|
||||
>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Icon className={cn("size-5", colors.chatAiIcon)} />
|
||||
<CardTitle className={cn("font-semibold", colors.titleText)}>
|
||||
{categoryConfig.title}
|
||||
</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{categoryData.items.map((item, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex flex-1 border-b border-dashed py-2.5 gap-2 items-start last:border-0"
|
||||
>
|
||||
<RiChatAi3Line
|
||||
className={cn("size-4 shrink-0", colors.chatAiIcon)}
|
||||
/>
|
||||
<span className="text-sm">{item.text}</span>
|
||||
</div>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
255
components/insights/insights-page.tsx
Normal file
255
components/insights/insights-page.tsx
Normal file
@@ -0,0 +1,255 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
generateInsightsAction,
|
||||
loadSavedInsightsAction,
|
||||
saveInsightsAction,
|
||||
deleteSavedInsightsAction,
|
||||
} from "@/app/(dashboard)/insights/actions";
|
||||
import { DEFAULT_MODEL } from "@/app/(dashboard)/insights/data";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader } from "@/components/ui/card";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import type { InsightsResponse } from "@/lib/schemas/insights";
|
||||
import { RiDeleteBinLine, RiSaveLine, RiSparklingLine } from "@remixicon/react";
|
||||
import { useEffect, useState, useTransition } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { EmptyState } from "../empty-state";
|
||||
import { InsightsGrid } from "./insights-grid";
|
||||
import { ModelSelector } from "./model-selector";
|
||||
import { format } from "date-fns";
|
||||
import { ptBR } from "date-fns/locale";
|
||||
|
||||
interface InsightsPageProps {
|
||||
period: string;
|
||||
onAnalyze?: () => void;
|
||||
}
|
||||
|
||||
export function InsightsPage({ period, onAnalyze }: InsightsPageProps) {
|
||||
const [selectedModel, setSelectedModel] = useState(DEFAULT_MODEL);
|
||||
const [insights, setInsights] = useState<InsightsResponse | null>(null);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [isSaving, startSaveTransition] = useTransition();
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isSaved, setIsSaved] = useState(false);
|
||||
const [savedDate, setSavedDate] = useState<Date | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
// Carregar insights salvos ao montar o componente
|
||||
useEffect(() => {
|
||||
const loadSaved = async () => {
|
||||
try {
|
||||
const result = await loadSavedInsightsAction(period);
|
||||
if (result.success && result.data) {
|
||||
setInsights(result.data.insights);
|
||||
setSelectedModel(result.data.modelId);
|
||||
setIsSaved(true);
|
||||
setSavedDate(result.data.createdAt);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Error loading saved insights:", err);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadSaved();
|
||||
}, [period]);
|
||||
|
||||
const handleAnalyze = () => {
|
||||
setError(null);
|
||||
setIsSaved(false);
|
||||
setSavedDate(null);
|
||||
onAnalyze?.();
|
||||
startTransition(async () => {
|
||||
try {
|
||||
const result = await generateInsightsAction(period, selectedModel);
|
||||
|
||||
if (result.success) {
|
||||
setInsights(result.data);
|
||||
toast.success("Insights gerados com sucesso!");
|
||||
} else {
|
||||
setError(result.error);
|
||||
toast.error(result.error);
|
||||
}
|
||||
} catch (err) {
|
||||
const errorMessage = "Erro inesperado ao gerar insights.";
|
||||
setError(errorMessage);
|
||||
toast.error(errorMessage);
|
||||
console.error("Error generating insights:", err);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
if (!insights) return;
|
||||
|
||||
startSaveTransition(async () => {
|
||||
try {
|
||||
const result = await saveInsightsAction(period, selectedModel, insights);
|
||||
|
||||
if (result.success) {
|
||||
setIsSaved(true);
|
||||
setSavedDate(result.data.createdAt);
|
||||
toast.success("Análise salva com sucesso!");
|
||||
} else {
|
||||
toast.error(result.error);
|
||||
}
|
||||
} catch (err) {
|
||||
toast.error("Erro ao salvar análise.");
|
||||
console.error("Error saving insights:", err);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const handleDelete = () => {
|
||||
startSaveTransition(async () => {
|
||||
try {
|
||||
const result = await deleteSavedInsightsAction(period);
|
||||
|
||||
if (result.success) {
|
||||
setIsSaved(false);
|
||||
setSavedDate(null);
|
||||
toast.success("Análise removida com sucesso!");
|
||||
} else {
|
||||
toast.error(result.error);
|
||||
}
|
||||
} catch (err) {
|
||||
toast.error("Erro ao remover análise.");
|
||||
console.error("Error deleting insights:", err);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
{/* Model Selector */}
|
||||
<ModelSelector
|
||||
value={selectedModel}
|
||||
onValueChange={setSelectedModel}
|
||||
disabled={isPending}
|
||||
/>
|
||||
|
||||
{/* Analyze Button */}
|
||||
<div className="flex items-center gap-3 flex-wrap">
|
||||
<Button
|
||||
onClick={handleAnalyze}
|
||||
disabled={isPending || isLoading}
|
||||
className="bg-linear-to-r from-primary to-emerald-400 dark:from-primary-dark dark:to-emerald-600"
|
||||
>
|
||||
<RiSparklingLine className="mr-2 size-5" aria-hidden="true" />
|
||||
{isPending ? "Analisando..." : "Gerar análise inteligente"}
|
||||
</Button>
|
||||
|
||||
{insights && !error && (
|
||||
<Button
|
||||
onClick={isSaved ? handleDelete : handleSave}
|
||||
disabled={isSaving || isPending || isLoading}
|
||||
variant={isSaved ? "destructive" : "outline"}
|
||||
>
|
||||
{isSaved ? (
|
||||
<>
|
||||
<RiDeleteBinLine className="mr-2 size-4" />
|
||||
{isSaving ? "Removendo..." : "Remover análise"}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<RiSaveLine className="mr-2 size-4" />
|
||||
{isSaving ? "Salvando..." : "Salvar análise"}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{isSaved && savedDate && (
|
||||
<span className="text-sm text-muted-foreground">
|
||||
Salva em {format(new Date(savedDate), "dd/MM/yyyy 'às' HH:mm", { locale: ptBR })}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Content Area */}
|
||||
<div className="min-h-[400px]">
|
||||
{(isPending || isLoading) && <LoadingState />}
|
||||
{!isPending && !isLoading && !insights && !error && (
|
||||
<Card className="flex min-h-[50vh] w-full items-center justify-center py-12">
|
||||
<EmptyState
|
||||
media={<RiSparklingLine className="size-6 text-primary" />}
|
||||
title="Nenhuma análise realizada"
|
||||
description="Clique no botão acima para gerar insights inteligentes sobre seus
|
||||
dados financeiros do mês selecionado."
|
||||
/>
|
||||
</Card>
|
||||
)}
|
||||
{!isPending && !isLoading && error && (
|
||||
<ErrorState error={error} onRetry={handleAnalyze} />
|
||||
)}
|
||||
{!isPending && !isLoading && insights && !error && (
|
||||
<InsightsGrid insights={insights} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LoadingState() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Intro text skeleton */}
|
||||
<div className="space-y-2 px-1">
|
||||
<Skeleton className="h-5 w-full max-w-2xl" />
|
||||
<Skeleton className="h-5 w-full max-w-md" />
|
||||
</div>
|
||||
|
||||
{/* Grid de Cards */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
{Array.from({ length: 4 }).map((_, i) => (
|
||||
<Card key={i} className="relative overflow-hidden">
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="size-5 rounded" />
|
||||
<Skeleton className="h-5 w-32" />
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{Array.from({ length: 4 }).map((_, j) => (
|
||||
<div
|
||||
key={j}
|
||||
className="flex flex-1 border-b border-dashed py-2.5 gap-2 items-start last:border-0"
|
||||
>
|
||||
<Skeleton className="size-4 shrink-0 rounded" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ErrorState({
|
||||
error,
|
||||
onRetry,
|
||||
}: {
|
||||
error: string;
|
||||
onRetry: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center gap-4 py-12 px-4 text-center">
|
||||
<div className="flex flex-col gap-2">
|
||||
<h3 className="text-lg font-semibold text-destructive">
|
||||
Erro ao gerar insights
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground max-w-md">{error}</p>
|
||||
</div>
|
||||
<Button onClick={onRetry} variant="outline">
|
||||
Tentar novamente
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
236
components/insights/model-selector.tsx
Normal file
236
components/insights/model-selector.tsx
Normal file
@@ -0,0 +1,236 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
AVAILABLE_MODELS,
|
||||
DEFAULT_PROVIDER,
|
||||
PROVIDERS,
|
||||
type AIProvider,
|
||||
} from "@/app/(dashboard)/insights/data";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { RiExternalLinkLine } from "@remixicon/react";
|
||||
import Image from "next/image";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Card } from "../ui/card";
|
||||
|
||||
interface ModelSelectorProps {
|
||||
value: string;
|
||||
onValueChange: (value: string) => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
const PROVIDER_ICON_PATHS: Record<
|
||||
AIProvider,
|
||||
{ light: string; dark?: string }
|
||||
> = {
|
||||
openai: {
|
||||
light: "/providers/chatgpt.svg",
|
||||
dark: "/providers/chatgpt_dark_mode.svg",
|
||||
},
|
||||
anthropic: {
|
||||
light: "/providers/claude.svg",
|
||||
},
|
||||
google: {
|
||||
light: "/providers/gemini.svg",
|
||||
},
|
||||
openrouter: {
|
||||
light: "/providers/openrouter_light.svg",
|
||||
dark: "/providers/openrouter_dark.svg",
|
||||
},
|
||||
};
|
||||
|
||||
export function ModelSelector({
|
||||
value,
|
||||
onValueChange,
|
||||
disabled,
|
||||
}: ModelSelectorProps) {
|
||||
// Estado para armazenar o provider selecionado manualmente
|
||||
const [selectedProvider, setSelectedProvider] = useState<AIProvider | null>(
|
||||
null
|
||||
);
|
||||
const [customModel, setCustomModel] = useState(value);
|
||||
|
||||
// Sincronizar customModel quando value mudar (importante para pré-carregamento)
|
||||
useEffect(() => {
|
||||
// Se o value tem "/" é um modelo OpenRouter customizado
|
||||
if (value.includes("/")) {
|
||||
setCustomModel(value);
|
||||
setSelectedProvider("openrouter");
|
||||
} else {
|
||||
setCustomModel(value);
|
||||
// Limpar selectedProvider para deixar o useMemo detectar automaticamente
|
||||
setSelectedProvider(null);
|
||||
}
|
||||
}, [value]);
|
||||
|
||||
// Determinar provider atual baseado no modelo selecionado ou provider manual
|
||||
const currentProvider = useMemo(() => {
|
||||
// Se há um provider selecionado manualmente, use-o
|
||||
if (selectedProvider) {
|
||||
return selectedProvider;
|
||||
}
|
||||
|
||||
// Se o modelo tem "/" é OpenRouter
|
||||
if (value.includes("/")) {
|
||||
return "openrouter";
|
||||
}
|
||||
|
||||
// Caso contrário, tente detectar baseado no modelo
|
||||
const model = AVAILABLE_MODELS.find((m) => m.id === value);
|
||||
return model?.provider ?? DEFAULT_PROVIDER;
|
||||
}, [value, selectedProvider]);
|
||||
|
||||
// Agrupar modelos por provider
|
||||
const modelsByProvider = useMemo(() => {
|
||||
const grouped: Record<
|
||||
AIProvider,
|
||||
Array<(typeof AVAILABLE_MODELS)[number]>
|
||||
> = {
|
||||
openai: [],
|
||||
anthropic: [],
|
||||
google: [],
|
||||
openrouter: [],
|
||||
};
|
||||
|
||||
AVAILABLE_MODELS.forEach((model) => {
|
||||
grouped[model.provider].push(model);
|
||||
});
|
||||
|
||||
return grouped;
|
||||
}, []);
|
||||
|
||||
// Atualizar provider (seleciona primeiro modelo daquele provider)
|
||||
const handleProviderChange = (newProvider: AIProvider) => {
|
||||
setSelectedProvider(newProvider);
|
||||
|
||||
if (newProvider === "openrouter") {
|
||||
// Para OpenRouter, usa o modelo customizado ou limpa o valor
|
||||
onValueChange(customModel || "");
|
||||
return;
|
||||
}
|
||||
|
||||
const firstModel = modelsByProvider[newProvider][0];
|
||||
if (firstModel) {
|
||||
onValueChange(firstModel.id);
|
||||
}
|
||||
};
|
||||
|
||||
// Atualizar modelo customizado do OpenRouter
|
||||
const handleCustomModelChange = (modelName: string) => {
|
||||
setCustomModel(modelName);
|
||||
onValueChange(modelName);
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="grid grid-cols-1 lg:grid-cols-[1fr,auto] gap-6 items-start p-6">
|
||||
{/* Descrição */}
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-lg font-semibold">Definir modelo de análise</h3>
|
||||
<p className="text-sm text-muted-foreground leading-relaxed">
|
||||
Escolha o provedor de IA e o modelo específico que será utilizado para
|
||||
gerar insights sobre seus dados financeiros. <br />
|
||||
Diferentes modelos podem oferecer perspectivas variadas na análise.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Seletor */}
|
||||
<div className="flex flex-col gap-4 min-w-xs">
|
||||
<RadioGroup
|
||||
value={currentProvider}
|
||||
onValueChange={(v) => handleProviderChange(v as AIProvider)}
|
||||
disabled={disabled}
|
||||
className="gap-3"
|
||||
>
|
||||
{(Object.keys(PROVIDERS) as AIProvider[]).map((providerId) => {
|
||||
const provider = PROVIDERS[providerId];
|
||||
const iconPaths = PROVIDER_ICON_PATHS[providerId];
|
||||
|
||||
return (
|
||||
<div key={providerId} className="flex items-center gap-3">
|
||||
<RadioGroupItem
|
||||
value={providerId}
|
||||
id={`provider-${providerId}`}
|
||||
disabled={disabled}
|
||||
/>
|
||||
<div className="size-6 relative">
|
||||
<Image
|
||||
src={iconPaths.light}
|
||||
alt={provider.name}
|
||||
width={22}
|
||||
height={22}
|
||||
className={iconPaths.dark ? "dark:hidden" : ""}
|
||||
/>
|
||||
{iconPaths.dark && (
|
||||
<Image
|
||||
src={iconPaths.dark}
|
||||
alt={provider.name}
|
||||
width={22}
|
||||
height={22}
|
||||
className="hidden dark:block"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<Label
|
||||
htmlFor={`provider-${providerId}`}
|
||||
className="text-sm font-medium cursor-pointer flex-1"
|
||||
>
|
||||
{provider.name}
|
||||
</Label>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</RadioGroup>
|
||||
|
||||
{/* Seletor de Modelo */}
|
||||
{currentProvider === "openrouter" ? (
|
||||
<div className="space-y-2">
|
||||
<Input
|
||||
value={customModel}
|
||||
onChange={(e) => handleCustomModelChange(e.target.value)}
|
||||
placeholder="Ex: anthropic/claude-3.5-sonnet"
|
||||
disabled={disabled}
|
||||
className="border-none bg-neutral-200 dark:bg-neutral-800"
|
||||
/>
|
||||
<a
|
||||
href="https://openrouter.ai/models"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<RiExternalLinkLine className="h-3 w-3" />
|
||||
Ver modelos disponíveis no OpenRouter
|
||||
</a>
|
||||
</div>
|
||||
) : (
|
||||
<Select
|
||||
value={value}
|
||||
onValueChange={onValueChange}
|
||||
disabled={disabled}
|
||||
>
|
||||
<SelectTrigger
|
||||
disabled={disabled}
|
||||
className="border-none bg-neutral-200 dark:bg-neutral-800"
|
||||
>
|
||||
<SelectValue placeholder="Selecione um modelo" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{modelsByProvider[currentProvider].map((model) => (
|
||||
<SelectItem key={model.id} value={model.id}>
|
||||
{model.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,489 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
createInstallmentAnticipationAction,
|
||||
getEligibleInstallmentsAction,
|
||||
} from "@/app/(dashboard)/lancamentos/anticipation-actions";
|
||||
import { CategoryIcon } from "@/components/categorias/category-icon";
|
||||
import { InstallmentSelectionTable } from "./installment-selection-table";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CurrencyInput } from "@/components/ui/currency-input";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
Field,
|
||||
FieldContent,
|
||||
FieldGroup,
|
||||
FieldLabel,
|
||||
FieldLegend,
|
||||
} from "@/components/ui/field";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
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";
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
type AnticipationFormValues = {
|
||||
anticipationPeriod: string;
|
||||
discount: number;
|
||||
pagadorId: string;
|
||||
categoriaId: string;
|
||||
note: string;
|
||||
};
|
||||
|
||||
type SelectOption = {
|
||||
value: string;
|
||||
label: string;
|
||||
};
|
||||
|
||||
const monthFormatter = new Intl.DateTimeFormat("pt-BR", {
|
||||
month: "long",
|
||||
year: "numeric",
|
||||
});
|
||||
|
||||
const formatPeriodLabel = (period: string) => {
|
||||
const [year, month] = period.split("-").map(Number);
|
||||
if (!year || !month) {
|
||||
return period;
|
||||
}
|
||||
const date = new Date(year, month - 1, 1);
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return period;
|
||||
}
|
||||
const label = monthFormatter.format(date);
|
||||
return label.charAt(0).toUpperCase() + label.slice(1);
|
||||
};
|
||||
|
||||
const buildPeriodOptions = (currentValue?: string): SelectOption[] => {
|
||||
const now = new Date();
|
||||
const options: SelectOption[] = [];
|
||||
|
||||
// Adiciona opções de 3 meses no passado até 6 meses no futuro
|
||||
for (let offset = -3; offset <= 6; offset += 1) {
|
||||
const date = new Date(now.getFullYear(), now.getMonth() + offset, 1);
|
||||
const value = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
|
||||
2,
|
||||
"0"
|
||||
)}`;
|
||||
options.push({ value, label: formatPeriodLabel(value) });
|
||||
}
|
||||
|
||||
// Adiciona o valor atual se não estiver na lista
|
||||
if (
|
||||
currentValue &&
|
||||
!options.some((option) => option.value === currentValue)
|
||||
) {
|
||||
options.push({
|
||||
value: currentValue,
|
||||
label: formatPeriodLabel(currentValue),
|
||||
});
|
||||
}
|
||||
|
||||
return options.sort((a, b) => a.value.localeCompare(b.value));
|
||||
};
|
||||
|
||||
export function AnticipateInstallmentsDialog({
|
||||
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[]>([]);
|
||||
|
||||
// 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: "",
|
||||
});
|
||||
|
||||
const periodOptions = useMemo(
|
||||
() => buildPeriodOptions(formState.anticipationPeriod),
|
||||
[formState.anticipationPeriod]
|
||||
);
|
||||
|
||||
// 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);
|
||||
|
||||
// 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 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);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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,
|
||||
});
|
||||
|
||||
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]
|
||||
);
|
||||
|
||||
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>
|
||||
|
||||
<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>
|
||||
|
||||
{/* 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>
|
||||
<Select
|
||||
value={formState.anticipationPeriod}
|
||||
onValueChange={(value) =>
|
||||
updateField("anticipationPeriod", value)
|
||||
}
|
||||
disabled={isPending}
|
||||
>
|
||||
<SelectTrigger id="anticipation-period" className="w-full">
|
||||
<SelectValue placeholder="Selecione o período" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{periodOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</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-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>
|
||||
|
||||
{/* 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>
|
||||
)}
|
||||
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
"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 { useEffect, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { RiCalendarCheckLine, RiLoader4Line } from "@remixicon/react";
|
||||
|
||||
interface AnticipationHistoryDialogProps {
|
||||
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,
|
||||
}: AnticipationHistoryDialogProps) {
|
||||
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
|
||||
);
|
||||
|
||||
// Buscar antecipações ao abrir o dialog
|
||||
useEffect(() => {
|
||||
if (dialogOpen) {
|
||||
loadAnticipations();
|
||||
}
|
||||
}, [dialogOpen, seriesId]);
|
||||
|
||||
const loadAnticipations = async () => {
|
||||
setIsLoading(true);
|
||||
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
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>
|
||||
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
"use client";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import {
|
||||
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;
|
||||
}
|
||||
|
||||
export function InstallmentSelectionTable({
|
||||
installments,
|
||||
selectedIds,
|
||||
onSelectionChange,
|
||||
}: InstallmentSelectionTableProps) {
|
||||
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 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 });
|
||||
};
|
||||
|
||||
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 já 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>
|
||||
|
||||
{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>
|
||||
);
|
||||
}
|
||||
162
components/lancamentos/dialogs/bulk-action-dialog.tsx
Normal file
162
components/lancamentos/dialogs/bulk-action-dialog.tsx
Normal file
@@ -0,0 +1,162 @@
|
||||
"use client";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
|
||||
import { useState } from "react";
|
||||
|
||||
export type BulkActionScope = "current" | "future" | "all";
|
||||
|
||||
type BulkActionDialogProps = {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
actionType: "edit" | "delete";
|
||||
seriesType: "installment" | "recurring";
|
||||
currentNumber?: number;
|
||||
totalCount?: number;
|
||||
onConfirm: (scope: BulkActionScope) => void;
|
||||
};
|
||||
|
||||
export function BulkActionDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
actionType,
|
||||
seriesType,
|
||||
currentNumber,
|
||||
totalCount,
|
||||
onConfirm,
|
||||
}: BulkActionDialogProps) {
|
||||
const [scope, setScope] = useState<BulkActionScope>("current");
|
||||
|
||||
const handleConfirm = () => {
|
||||
onConfirm(scope);
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const seriesLabel =
|
||||
seriesType === "installment" ? "parcelamento" : "recorrência";
|
||||
const actionLabel = actionType === "edit" ? "editar" : "remover";
|
||||
|
||||
const getDescription = () => {
|
||||
if (seriesType === "installment" && currentNumber && totalCount) {
|
||||
return `Este lançamento faz parte de um ${seriesLabel} (${currentNumber}/${totalCount}). Escolha o que deseja ${actionLabel}:`;
|
||||
}
|
||||
return `Este lançamento faz parte de uma ${seriesLabel}. Escolha o que deseja ${actionLabel}:`;
|
||||
};
|
||||
|
||||
const getCurrentLabel = () => {
|
||||
if (seriesType === "installment" && currentNumber) {
|
||||
return `Apenas esta parcela (${currentNumber}/${totalCount})`;
|
||||
}
|
||||
return "Apenas este lançamento";
|
||||
};
|
||||
|
||||
const getFutureLabel = () => {
|
||||
if (seriesType === "installment" && currentNumber && totalCount) {
|
||||
const remaining = totalCount - currentNumber + 1;
|
||||
return `Esta e as próximas parcelas (${remaining} ${
|
||||
remaining === 1 ? "parcela" : "parcelas"
|
||||
})`;
|
||||
}
|
||||
return "Este e os próximos lançamentos";
|
||||
};
|
||||
|
||||
const getAllLabel = () => {
|
||||
if (seriesType === "installment" && totalCount) {
|
||||
return `Todas as parcelas (${totalCount} ${
|
||||
totalCount === 1 ? "parcela" : "parcelas"
|
||||
})`;
|
||||
}
|
||||
return `Todos os lançamentos da ${seriesLabel}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="capitalize">
|
||||
{actionLabel} {seriesLabel}
|
||||
</DialogTitle>
|
||||
<DialogDescription>{getDescription()}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<RadioGroup
|
||||
value={scope}
|
||||
onValueChange={(v) => setScope(v as BulkActionScope)}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-start space-x-3">
|
||||
<RadioGroupItem value="current" id="current" className="mt-0.5" />
|
||||
<div className="flex-1">
|
||||
<Label
|
||||
htmlFor="current"
|
||||
className="text-sm cursor-pointer font-medium"
|
||||
>
|
||||
{getCurrentLabel()}
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Aplica a alteração apenas neste lançamento
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start space-x-3">
|
||||
<RadioGroupItem value="future" id="future" className="mt-0.5" />
|
||||
<div className="flex-1">
|
||||
<Label
|
||||
htmlFor="future"
|
||||
className="text-sm cursor-pointer font-medium"
|
||||
>
|
||||
{getFutureLabel()}
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Aplica a alteração neste e nos próximos lançamentos da série
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start space-x-3">
|
||||
<RadioGroupItem value="all" id="all" className="mt-0.5" />
|
||||
<div className="flex-1">
|
||||
<Label
|
||||
htmlFor="all"
|
||||
className="text-sm cursor-pointer font-medium"
|
||||
>
|
||||
{getAllLabel()}
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Aplica a alteração em todos os lançamentos da série
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
|
||||
<DialogFooter className="gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleConfirm}
|
||||
variant={actionType === "delete" ? "destructive" : "default"}
|
||||
>
|
||||
Confirmar
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
210
components/lancamentos/dialogs/lancamento-details-dialog.tsx
Normal file
210
components/lancamentos/dialogs/lancamento-details-dialog.tsx
Normal file
@@ -0,0 +1,210 @@
|
||||
"use client";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
} from "@/components/ui/card";
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { getPaymentMethodIcon } from "@/lib/utils/icons";
|
||||
import {
|
||||
currencyFormatter,
|
||||
formatCondition,
|
||||
formatDate,
|
||||
formatPeriod,
|
||||
getTransactionBadgeVariant,
|
||||
} from "@/lib/lancamentos/formatting-helpers";
|
||||
import { InstallmentTimeline } from "../shared/installment-timeline";
|
||||
import type { LancamentoItem } from "../types";
|
||||
|
||||
interface LancamentoDetailsDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
lancamento: LancamentoItem | null;
|
||||
}
|
||||
|
||||
export function LancamentoDetailsDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
lancamento,
|
||||
}: LancamentoDetailsDialogProps) {
|
||||
if (!lancamento) return null;
|
||||
|
||||
const isInstallment =
|
||||
lancamento.condition?.toLowerCase() === "parcelado" &&
|
||||
lancamento.currentInstallment &&
|
||||
lancamento.installmentCount;
|
||||
|
||||
const valorParcela = Math.abs(lancamento.amount);
|
||||
const totalParcelas = lancamento.installmentCount ?? 1;
|
||||
const parcelaAtual = lancamento.currentInstallment ?? 1;
|
||||
const valorTotal = isInstallment
|
||||
? valorParcela * totalParcelas
|
||||
: valorParcela;
|
||||
const valorRestante = isInstallment
|
||||
? valorParcela * (totalParcelas - parcelaAtual)
|
||||
: 0;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="p-0 sm:max-w-xl">
|
||||
<Card className="gap-2 space-y-4">
|
||||
<CardHeader className="flex flex-row items-start border-b">
|
||||
<div>
|
||||
<DialogTitle className="group flex items-center gap-2 text-lg">
|
||||
#{lancamento.id}
|
||||
</DialogTitle>
|
||||
<CardDescription>
|
||||
{formatDate(lancamento.purchaseDate)}
|
||||
</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="text-sm">
|
||||
<div className="grid gap-3">
|
||||
<ul className="grid gap-3">
|
||||
<DetailRow label="Descrição" value={lancamento.name} />
|
||||
|
||||
<DetailRow
|
||||
label="Período"
|
||||
value={formatPeriod(lancamento.period)}
|
||||
/>
|
||||
|
||||
<li className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">
|
||||
Forma de Pagamento
|
||||
</span>
|
||||
<span className="flex items-center gap-1.5">
|
||||
{getPaymentMethodIcon(lancamento.paymentMethod)}
|
||||
<span className="capitalize">
|
||||
{lancamento.paymentMethod}
|
||||
</span>
|
||||
</span>
|
||||
</li>
|
||||
|
||||
<DetailRow
|
||||
label={lancamento.cartaoName ? "Cartão" : "Conta"}
|
||||
value={lancamento.cartaoName ?? lancamento.contaName ?? "—"}
|
||||
/>
|
||||
|
||||
<DetailRow
|
||||
label="Categoria"
|
||||
value={lancamento.categoriaName ?? "—"}
|
||||
/>
|
||||
|
||||
<li className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">
|
||||
Tipo de Transação
|
||||
</span>
|
||||
<span className="capitalize">
|
||||
<Badge
|
||||
variant={getTransactionBadgeVariant(
|
||||
lancamento.transactionType
|
||||
)}
|
||||
>
|
||||
{lancamento.transactionType}
|
||||
</Badge>
|
||||
</span>
|
||||
</li>
|
||||
|
||||
<DetailRow
|
||||
label="Condição"
|
||||
value={formatCondition(lancamento.condition)}
|
||||
/>
|
||||
|
||||
<li className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">Responsável</span>
|
||||
<span className="flex items-center gap-2 capitalize">
|
||||
<span>{lancamento.pagadorName}</span>
|
||||
</span>
|
||||
</li>
|
||||
|
||||
<DetailRow
|
||||
label="Status"
|
||||
value={lancamento.isSettled ? "Pago" : "Pendente"}
|
||||
/>
|
||||
|
||||
{lancamento.note && (
|
||||
<DetailRow label="Notas" value={lancamento.note} />
|
||||
)}
|
||||
</ul>
|
||||
|
||||
<ul className="mb-6 grid gap-3">
|
||||
{isInstallment && (
|
||||
<li className="mt-4">
|
||||
<InstallmentTimeline
|
||||
purchaseDate={new Date(lancamento.purchaseDate)}
|
||||
currentInstallment={parcelaAtual}
|
||||
totalInstallments={totalParcelas}
|
||||
period={lancamento.period}
|
||||
/>
|
||||
</li>
|
||||
)}
|
||||
|
||||
<DetailRow
|
||||
label={isInstallment ? "Valor da Parcela" : "Valor"}
|
||||
value={currencyFormatter.format(valorParcela)}
|
||||
/>
|
||||
|
||||
{isInstallment && (
|
||||
<DetailRow
|
||||
label="Valor Restante"
|
||||
value={currencyFormatter.format(valorRestante)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{lancamento.recurrenceCount && (
|
||||
<DetailRow
|
||||
label="Quantidade de Recorrências"
|
||||
value={`${lancamento.recurrenceCount} meses`}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!isInstallment && <Separator className="my-2" />}
|
||||
|
||||
<li className="flex items-center justify-between font-semibold">
|
||||
<span className="text-muted-foreground">Total da Compra</span>
|
||||
<span className="text-lg">
|
||||
{currencyFormatter.format(valorTotal)}
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button className="w-full" type="button">
|
||||
Entendi
|
||||
</Button>
|
||||
</DialogClose>
|
||||
</DialogFooter>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
interface DetailRowProps {
|
||||
label: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
function DetailRow({ label, value }: DetailRowProps) {
|
||||
return (
|
||||
<li className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">{label}</span>
|
||||
<span className="capitalize">{value}</span>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
"use client";
|
||||
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { DatePicker } from "@/components/ui/date-picker";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { CurrencyInput } from "@/components/ui/currency-input";
|
||||
import { CalculatorDialogButton } from "@/components/calculadora/calculator-dialog";
|
||||
import { RiCalculatorLine } from "@remixicon/react";
|
||||
import { EstabelecimentoInput } from "../../shared/estabelecimento-input";
|
||||
import type { BasicFieldsSectionProps } from "./lancamento-dialog-types";
|
||||
|
||||
export function BasicFieldsSection({
|
||||
formState,
|
||||
onFieldChange,
|
||||
estabelecimentos,
|
||||
monthOptions,
|
||||
}: BasicFieldsSectionProps) {
|
||||
return (
|
||||
<>
|
||||
<div className="flex w-full flex-col gap-2 md:flex-row">
|
||||
<div className="w-1/2 space-y-1">
|
||||
<Label htmlFor="purchaseDate">Data da transação</Label>
|
||||
<DatePicker
|
||||
id="purchaseDate"
|
||||
value={formState.purchaseDate}
|
||||
onChange={(value) => onFieldChange("purchaseDate", value)}
|
||||
placeholder="Data da transação"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="w-1/2 space-y-1">
|
||||
<Label htmlFor="period">Período</Label>
|
||||
<Select
|
||||
value={formState.period}
|
||||
onValueChange={(value) => onFieldChange("period", value)}
|
||||
>
|
||||
<SelectTrigger id="period" className="w-full">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{monthOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex w-full flex-col gap-2 md:flex-row">
|
||||
<div className="w-1/2 space-y-1">
|
||||
<Label htmlFor="name">Estabelecimento</Label>
|
||||
<EstabelecimentoInput
|
||||
id="name"
|
||||
value={formState.name}
|
||||
onChange={(value) => onFieldChange("name", value)}
|
||||
estabelecimentos={estabelecimentos}
|
||||
placeholder="Ex.: Padaria"
|
||||
maxLength={20}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="w-1/2 space-y-1">
|
||||
<Label htmlFor="amount">Valor</Label>
|
||||
<div className="relative">
|
||||
<CurrencyInput
|
||||
id="amount"
|
||||
value={formState.amount}
|
||||
onValueChange={(value) => onFieldChange("amount", value)}
|
||||
placeholder="R$ 0,00"
|
||||
required
|
||||
className="pr-10"
|
||||
/>
|
||||
<CalculatorDialogButton
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className="absolute right-1 top-1/2 h-7 w-7 -translate-y-1/2"
|
||||
>
|
||||
<RiCalculatorLine className="h-4 w-4 text-muted-foreground" />
|
||||
</CalculatorDialogButton>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
"use client";
|
||||
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { DatePicker } from "@/components/ui/date-picker";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import type { BoletoFieldsSectionProps } from "./lancamento-dialog-types";
|
||||
|
||||
export function BoletoFieldsSection({
|
||||
formState,
|
||||
onFieldChange,
|
||||
showPaymentDate,
|
||||
}: BoletoFieldsSectionProps) {
|
||||
return (
|
||||
<div className="flex w-full flex-col gap-2 md:flex-row">
|
||||
<div
|
||||
className={cn(
|
||||
"space-y-2 w-full",
|
||||
showPaymentDate ? "md:w-1/2" : "md:w-full"
|
||||
)}
|
||||
>
|
||||
<Label htmlFor="dueDate">Vencimento do boleto</Label>
|
||||
<DatePicker
|
||||
id="dueDate"
|
||||
value={formState.dueDate}
|
||||
onChange={(value) => onFieldChange("dueDate", value)}
|
||||
placeholder="Selecione o vencimento"
|
||||
/>
|
||||
</div>
|
||||
{showPaymentDate ? (
|
||||
<div className="space-y-2 w-full md:w-1/2">
|
||||
<Label htmlFor="boletoPaymentDate">Pagamento do boleto</Label>
|
||||
<DatePicker
|
||||
id="boletoPaymentDate"
|
||||
value={formState.boletoPaymentDate}
|
||||
onChange={(value) => onFieldChange("boletoPaymentDate", value)}
|
||||
placeholder="Selecione a data de pagamento"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
"use client";
|
||||
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { LANCAMENTO_TRANSACTION_TYPES } from "@/lib/lancamentos/constants";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import {
|
||||
CategoriaSelectContent,
|
||||
TransactionTypeSelectContent,
|
||||
} from "../../select-items";
|
||||
import type { CategorySectionProps } from "./lancamento-dialog-types";
|
||||
|
||||
export function CategorySection({
|
||||
formState,
|
||||
onFieldChange,
|
||||
categoriaOptions,
|
||||
categoriaGroups,
|
||||
isUpdateMode,
|
||||
}: CategorySectionProps) {
|
||||
return (
|
||||
<div className="flex w-full flex-col gap-2 md:flex-row">
|
||||
{!isUpdateMode ? (
|
||||
<div className="w-full space-y-1 md:w-1/2">
|
||||
<Label htmlFor="transactionType">Tipo de transação</Label>
|
||||
<Select
|
||||
value={formState.transactionType}
|
||||
onValueChange={(value) => onFieldChange("transactionType", value)}
|
||||
>
|
||||
<SelectTrigger id="transactionType" className="w-full">
|
||||
<SelectValue placeholder="Selecione">
|
||||
{formState.transactionType && (
|
||||
<TransactionTypeSelectContent
|
||||
label={formState.transactionType}
|
||||
/>
|
||||
)}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{LANCAMENTO_TRANSACTION_TYPES.filter(
|
||||
(type) => type !== "Transferência"
|
||||
).map((type) => (
|
||||
<SelectItem key={type} value={type}>
|
||||
<TransactionTypeSelectContent label={type} />
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
"space-y-1 w-full",
|
||||
!isUpdateMode ? "md:w-1/2" : "md:w-full"
|
||||
)}
|
||||
>
|
||||
<Label htmlFor="categoria">Categoria</Label>
|
||||
<Select
|
||||
value={formState.categoriaId}
|
||||
onValueChange={(value) => onFieldChange("categoriaId", value)}
|
||||
>
|
||||
<SelectTrigger id="categoria" className="w-full">
|
||||
<SelectValue placeholder="Selecione">
|
||||
{formState.categoriaId &&
|
||||
(() => {
|
||||
const selectedOption = categoriaOptions.find(
|
||||
(opt) => opt.value === formState.categoriaId
|
||||
);
|
||||
return selectedOption ? (
|
||||
<CategoriaSelectContent
|
||||
label={selectedOption.label}
|
||||
icon={selectedOption.icon}
|
||||
/>
|
||||
) : null;
|
||||
})()}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{categoriaGroups.map((group) => (
|
||||
<SelectGroup key={group.label}>
|
||||
<SelectLabel>{group.label}</SelectLabel>
|
||||
{group.options.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
<CategoriaSelectContent
|
||||
label={option.label}
|
||||
icon={option.icon}
|
||||
/>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
"use client";
|
||||
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { LANCAMENTO_CONDITIONS } from "@/lib/lancamentos/constants";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import { ConditionSelectContent } from "../../select-items";
|
||||
import type { ConditionSectionProps } from "./lancamento-dialog-types";
|
||||
|
||||
export function ConditionSection({
|
||||
formState,
|
||||
onFieldChange,
|
||||
showInstallments,
|
||||
showRecurrence,
|
||||
}: ConditionSectionProps) {
|
||||
return (
|
||||
<div className="flex w-full flex-col gap-2 md:flex-row">
|
||||
<div
|
||||
className={cn(
|
||||
"space-y-2 w-full",
|
||||
showInstallments || showRecurrence ? "md:w-1/2" : "md:w-full"
|
||||
)}
|
||||
>
|
||||
<Label htmlFor="condition">Condição</Label>
|
||||
<Select
|
||||
value={formState.condition}
|
||||
onValueChange={(value) => onFieldChange("condition", value)}
|
||||
>
|
||||
<SelectTrigger id="condition" className="w-full">
|
||||
<SelectValue placeholder="Selecione">
|
||||
{formState.condition && (
|
||||
<ConditionSelectContent label={formState.condition} />
|
||||
)}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{LANCAMENTO_CONDITIONS.map((condition) => (
|
||||
<SelectItem key={condition} value={condition}>
|
||||
<ConditionSelectContent label={condition} />
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{showInstallments ? (
|
||||
<div className="space-y-2 w-full md:w-1/2">
|
||||
<Label htmlFor="installmentCount">Parcelado em</Label>
|
||||
<Select
|
||||
value={formState.installmentCount}
|
||||
onValueChange={(value) => onFieldChange("installmentCount", value)}
|
||||
>
|
||||
<SelectTrigger id="installmentCount" className="w-full">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{[...Array(24)].map((_, index) => (
|
||||
<SelectItem key={index + 2} value={String(index + 2)}>
|
||||
{index + 2}x
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{showRecurrence ? (
|
||||
<div className="space-y-2 w-full md:w-1/2">
|
||||
<Label htmlFor="recurrenceCount">Lançamento fixo</Label>
|
||||
<Select
|
||||
value={formState.recurrenceCount}
|
||||
onValueChange={(value) => onFieldChange("recurrenceCount", value)}
|
||||
>
|
||||
<SelectTrigger id="recurrenceCount" className="w-full">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{[...Array(24)].map((_, index) => (
|
||||
<SelectItem key={index + 2} value={String(index + 2)}>
|
||||
Por {index + 2} meses
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { LancamentoFormState } from "@/lib/lancamentos/form-helpers";
|
||||
import type { LancamentoItem, SelectOption } from "../../types";
|
||||
|
||||
export type FormState = LancamentoFormState;
|
||||
|
||||
export interface LancamentoDialogProps {
|
||||
mode: "create" | "update";
|
||||
trigger?: React.ReactNode;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
pagadorOptions: SelectOption[];
|
||||
splitPagadorOptions: SelectOption[];
|
||||
defaultPagadorId?: string | null;
|
||||
contaOptions: SelectOption[];
|
||||
cartaoOptions: SelectOption[];
|
||||
categoriaOptions: SelectOption[];
|
||||
estabelecimentos: string[];
|
||||
lancamento?: LancamentoItem;
|
||||
defaultPeriod?: string;
|
||||
defaultCartaoId?: string | null;
|
||||
defaultPaymentMethod?: string | null;
|
||||
defaultPurchaseDate?: string | null;
|
||||
lockCartaoSelection?: boolean;
|
||||
lockPaymentMethod?: boolean;
|
||||
onBulkEditRequest?: (data: {
|
||||
id: string;
|
||||
name: string;
|
||||
categoriaId: string | undefined;
|
||||
note: string;
|
||||
pagadorId: string | undefined;
|
||||
contaId: string | undefined;
|
||||
cartaoId: string | undefined;
|
||||
amount: number;
|
||||
dueDate: string | null;
|
||||
boletoPaymentDate: string | null;
|
||||
}) => void;
|
||||
}
|
||||
|
||||
export interface BaseFieldSectionProps {
|
||||
formState: FormState;
|
||||
onFieldChange: <Key extends keyof FormState>(
|
||||
key: Key,
|
||||
value: FormState[Key]
|
||||
) => void;
|
||||
}
|
||||
|
||||
export interface BasicFieldsSectionProps extends BaseFieldSectionProps {
|
||||
estabelecimentos: string[];
|
||||
monthOptions: Array<{ value: string; label: string }>;
|
||||
}
|
||||
|
||||
export interface CategorySectionProps extends BaseFieldSectionProps {
|
||||
categoriaOptions: SelectOption[];
|
||||
categoriaGroups: Array<{
|
||||
label: string;
|
||||
options: SelectOption[];
|
||||
}>;
|
||||
isUpdateMode: boolean;
|
||||
}
|
||||
|
||||
export interface SplitAndSettlementSectionProps extends BaseFieldSectionProps {
|
||||
showSettledToggle: boolean;
|
||||
}
|
||||
|
||||
export interface PagadorSectionProps extends BaseFieldSectionProps {
|
||||
pagadorOptions: SelectOption[];
|
||||
secondaryPagadorOptions: SelectOption[];
|
||||
}
|
||||
|
||||
export interface PaymentMethodSectionProps extends BaseFieldSectionProps {
|
||||
contaOptions: SelectOption[];
|
||||
cartaoOptions: SelectOption[];
|
||||
isUpdateMode: boolean;
|
||||
disablePaymentMethod: boolean;
|
||||
disableCartaoSelect: boolean;
|
||||
}
|
||||
|
||||
export interface BoletoFieldsSectionProps extends BaseFieldSectionProps {
|
||||
showPaymentDate: boolean;
|
||||
}
|
||||
|
||||
export interface ConditionSectionProps extends BaseFieldSectionProps {
|
||||
showInstallments: boolean;
|
||||
showRecurrence: boolean;
|
||||
}
|
||||
|
||||
export type NoteSectionProps = BaseFieldSectionProps;
|
||||
@@ -0,0 +1,421 @@
|
||||
"use client";
|
||||
import {
|
||||
createLancamentoAction,
|
||||
updateLancamentoAction,
|
||||
} from "@/app/(dashboard)/lancamentos/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import { useControlledState } from "@/hooks/use-controlled-state";
|
||||
import {
|
||||
filterSecondaryPagadorOptions,
|
||||
groupAndSortCategorias,
|
||||
} from "@/lib/lancamentos/categoria-helpers";
|
||||
import {
|
||||
applyFieldDependencies,
|
||||
buildLancamentoInitialState,
|
||||
} from "@/lib/lancamentos/form-helpers";
|
||||
import { createMonthOptions } from "@/lib/utils/period";
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
useTransition,
|
||||
} from "react";
|
||||
import { toast } from "sonner";
|
||||
import { BasicFieldsSection } from "./basic-fields-section";
|
||||
import { BoletoFieldsSection } from "./boleto-fields-section";
|
||||
import { CategorySection } from "./category-section";
|
||||
import { ConditionSection } from "./condition-section";
|
||||
import type {
|
||||
FormState,
|
||||
LancamentoDialogProps,
|
||||
} from "./lancamento-dialog-types";
|
||||
import { NoteSection } from "./note-section";
|
||||
import { PagadorSection } from "./pagador-section";
|
||||
import { PaymentMethodSection } from "./payment-method-section";
|
||||
import { SplitAndSettlementSection } from "./split-settlement-section";
|
||||
|
||||
export function LancamentoDialog({
|
||||
mode,
|
||||
trigger,
|
||||
open,
|
||||
onOpenChange,
|
||||
pagadorOptions,
|
||||
splitPagadorOptions,
|
||||
defaultPagadorId,
|
||||
contaOptions,
|
||||
cartaoOptions,
|
||||
categoriaOptions,
|
||||
estabelecimentos,
|
||||
lancamento,
|
||||
defaultPeriod,
|
||||
defaultCartaoId,
|
||||
defaultPaymentMethod,
|
||||
defaultPurchaseDate,
|
||||
lockCartaoSelection,
|
||||
lockPaymentMethod,
|
||||
onBulkEditRequest,
|
||||
}: LancamentoDialogProps) {
|
||||
const [dialogOpen, setDialogOpen] = useControlledState(
|
||||
open,
|
||||
false,
|
||||
onOpenChange
|
||||
);
|
||||
|
||||
const [formState, setFormState] = useState<FormState>(() =>
|
||||
buildLancamentoInitialState(lancamento, defaultPagadorId, defaultPeriod, {
|
||||
defaultCartaoId,
|
||||
defaultPaymentMethod,
|
||||
defaultPurchaseDate,
|
||||
})
|
||||
);
|
||||
const [periodDirty, setPeriodDirty] = useState(false);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (dialogOpen) {
|
||||
setFormState(
|
||||
buildLancamentoInitialState(
|
||||
lancamento,
|
||||
defaultPagadorId,
|
||||
defaultPeriod,
|
||||
{
|
||||
defaultCartaoId,
|
||||
defaultPaymentMethod,
|
||||
defaultPurchaseDate,
|
||||
}
|
||||
)
|
||||
);
|
||||
setErrorMessage(null);
|
||||
setPeriodDirty(false);
|
||||
}
|
||||
}, [
|
||||
dialogOpen,
|
||||
lancamento,
|
||||
defaultPagadorId,
|
||||
defaultPeriod,
|
||||
defaultCartaoId,
|
||||
defaultPaymentMethod,
|
||||
defaultPurchaseDate,
|
||||
]);
|
||||
|
||||
const primaryPagador = formState.pagadorId;
|
||||
|
||||
const secondaryPagadorOptions = useMemo(
|
||||
() => filterSecondaryPagadorOptions(splitPagadorOptions, primaryPagador),
|
||||
[splitPagadorOptions, primaryPagador]
|
||||
);
|
||||
|
||||
const categoriaGroups = useMemo(() => {
|
||||
const filtered = categoriaOptions.filter(
|
||||
(option) =>
|
||||
option.group?.toLowerCase() === formState.transactionType.toLowerCase()
|
||||
);
|
||||
return groupAndSortCategorias(filtered);
|
||||
}, [categoriaOptions, formState.transactionType]);
|
||||
|
||||
const monthOptions = useMemo(
|
||||
() => createMonthOptions(formState.period),
|
||||
[formState.period]
|
||||
);
|
||||
|
||||
const handleFieldChange = useCallback(
|
||||
<Key extends keyof FormState>(key: Key, value: FormState[Key]) => {
|
||||
if (key === "period") {
|
||||
setPeriodDirty(true);
|
||||
}
|
||||
|
||||
setFormState((prev) => {
|
||||
const dependencies = applyFieldDependencies(
|
||||
key,
|
||||
value,
|
||||
prev,
|
||||
periodDirty
|
||||
);
|
||||
|
||||
return {
|
||||
...prev,
|
||||
[key]: value,
|
||||
...dependencies,
|
||||
};
|
||||
});
|
||||
},
|
||||
[periodDirty]
|
||||
);
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
(event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setErrorMessage(null);
|
||||
|
||||
if (!formState.purchaseDate) {
|
||||
const message = "Informe a data da transação.";
|
||||
setErrorMessage(message);
|
||||
toast.error(message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!formState.name.trim()) {
|
||||
const message = "Informe a descrição do lançamento.";
|
||||
setErrorMessage(message);
|
||||
toast.error(message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (formState.isSplit && !formState.pagadorId) {
|
||||
const message =
|
||||
"Selecione o pagador principal para dividir o lançamento.";
|
||||
setErrorMessage(message);
|
||||
toast.error(message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (formState.isSplit && !formState.secondaryPagadorId) {
|
||||
const message =
|
||||
"Selecione o pagador secundário para dividir o lançamento.";
|
||||
setErrorMessage(message);
|
||||
toast.error(message);
|
||||
return;
|
||||
}
|
||||
|
||||
const amountValue = Number(formState.amount);
|
||||
if (Number.isNaN(amountValue)) {
|
||||
const message = "Informe um valor válido.";
|
||||
setErrorMessage(message);
|
||||
toast.error(message);
|
||||
return;
|
||||
}
|
||||
|
||||
const sanitizedAmount = Math.abs(amountValue);
|
||||
|
||||
const payload = {
|
||||
purchaseDate: formState.purchaseDate,
|
||||
period: formState.period,
|
||||
name: formState.name.trim(),
|
||||
transactionType: formState.transactionType,
|
||||
amount: sanitizedAmount,
|
||||
condition: formState.condition,
|
||||
paymentMethod: formState.paymentMethod,
|
||||
pagadorId: formState.pagadorId,
|
||||
secondaryPagadorId: formState.isSplit
|
||||
? formState.secondaryPagadorId
|
||||
: undefined,
|
||||
isSplit: formState.isSplit,
|
||||
contaId: formState.contaId,
|
||||
cartaoId: formState.cartaoId,
|
||||
categoriaId: formState.categoriaId,
|
||||
note: formState.note.trim() || undefined,
|
||||
isSettled:
|
||||
formState.paymentMethod === "Cartão de crédito"
|
||||
? null
|
||||
: Boolean(formState.isSettled),
|
||||
installmentCount:
|
||||
formState.condition === "Parcelado" && formState.installmentCount
|
||||
? Number(formState.installmentCount)
|
||||
: undefined,
|
||||
recurrenceCount:
|
||||
formState.condition === "Recorrente" && formState.recurrenceCount
|
||||
? Number(formState.recurrenceCount)
|
||||
: undefined,
|
||||
dueDate:
|
||||
formState.paymentMethod === "Boleto" && formState.dueDate
|
||||
? formState.dueDate
|
||||
: undefined,
|
||||
boletoPaymentDate:
|
||||
mode === "update" &&
|
||||
formState.paymentMethod === "Boleto" &&
|
||||
formState.boletoPaymentDate
|
||||
? formState.boletoPaymentDate
|
||||
: undefined,
|
||||
};
|
||||
|
||||
startTransition(async () => {
|
||||
if (mode === "create") {
|
||||
const result = await createLancamentoAction(payload);
|
||||
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
setDialogOpen(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setErrorMessage(result.error);
|
||||
toast.error(result.error);
|
||||
return;
|
||||
}
|
||||
|
||||
// Update mode
|
||||
const hasSeriesId = Boolean(lancamento?.seriesId);
|
||||
|
||||
if (hasSeriesId && onBulkEditRequest) {
|
||||
// Para lançamentos em série, abre o diálogo de bulk action
|
||||
onBulkEditRequest({
|
||||
id: lancamento?.id ?? "",
|
||||
name: formState.name.trim(),
|
||||
categoriaId: formState.categoriaId,
|
||||
note: formState.note.trim() || "",
|
||||
pagadorId: formState.pagadorId,
|
||||
contaId: formState.contaId,
|
||||
cartaoId: formState.cartaoId,
|
||||
amount: sanitizedAmount,
|
||||
dueDate:
|
||||
formState.paymentMethod === "Boleto"
|
||||
? formState.dueDate || null
|
||||
: null,
|
||||
boletoPaymentDate:
|
||||
mode === "update" && formState.paymentMethod === "Boleto"
|
||||
? formState.boletoPaymentDate || null
|
||||
: null,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Atualização normal para lançamentos únicos ou todos os campos
|
||||
const result = await updateLancamentoAction({
|
||||
id: lancamento?.id ?? "",
|
||||
...payload,
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
setDialogOpen(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setErrorMessage(result.error);
|
||||
toast.error(result.error);
|
||||
});
|
||||
},
|
||||
[
|
||||
formState,
|
||||
mode,
|
||||
lancamento?.id,
|
||||
lancamento?.seriesId,
|
||||
setDialogOpen,
|
||||
onBulkEditRequest,
|
||||
]
|
||||
);
|
||||
|
||||
const title = mode === "create" ? "Novo lançamento" : "Editar lançamento";
|
||||
const description =
|
||||
mode === "create"
|
||||
? "Informe os dados abaixo para registrar um novo lançamento."
|
||||
: "Atualize as informações do lançamento selecionado.";
|
||||
const submitLabel = mode === "create" ? "Salvar lançamento" : "Atualizar";
|
||||
|
||||
const showInstallments = formState.condition === "Parcelado";
|
||||
const showRecurrence = formState.condition === "Recorrente";
|
||||
const showDueDate = formState.paymentMethod === "Boleto";
|
||||
const showPaymentDate = mode === "update" && showDueDate;
|
||||
const showSettledToggle = formState.paymentMethod !== "Cartão de crédito";
|
||||
const isUpdateMode = mode === "update";
|
||||
const disablePaymentMethod = Boolean(lockPaymentMethod && mode === "create");
|
||||
const disableCartaoSelect = Boolean(lockCartaoSelection && mode === "create");
|
||||
|
||||
return (
|
||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||
{trigger ? <DialogTrigger asChild>{trigger}</DialogTrigger> : null}
|
||||
<DialogContent className="sm:max-w-xl p-6 sm:px-8">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form
|
||||
className="space-y-2 -mx-6 max-h-[80vh] overflow-y-auto px-6 pb-1"
|
||||
onSubmit={handleSubmit}
|
||||
>
|
||||
<BasicFieldsSection
|
||||
formState={formState}
|
||||
onFieldChange={handleFieldChange}
|
||||
estabelecimentos={estabelecimentos}
|
||||
monthOptions={monthOptions}
|
||||
/>
|
||||
|
||||
<CategorySection
|
||||
formState={formState}
|
||||
onFieldChange={handleFieldChange}
|
||||
categoriaOptions={categoriaOptions}
|
||||
categoriaGroups={categoriaGroups}
|
||||
isUpdateMode={isUpdateMode}
|
||||
/>
|
||||
|
||||
{!isUpdateMode ? (
|
||||
<SplitAndSettlementSection
|
||||
formState={formState}
|
||||
onFieldChange={handleFieldChange}
|
||||
showSettledToggle={showSettledToggle}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<PagadorSection
|
||||
formState={formState}
|
||||
onFieldChange={handleFieldChange}
|
||||
pagadorOptions={pagadorOptions}
|
||||
secondaryPagadorOptions={secondaryPagadorOptions}
|
||||
/>
|
||||
|
||||
<PaymentMethodSection
|
||||
formState={formState}
|
||||
onFieldChange={handleFieldChange}
|
||||
contaOptions={contaOptions}
|
||||
cartaoOptions={cartaoOptions}
|
||||
isUpdateMode={isUpdateMode}
|
||||
disablePaymentMethod={disablePaymentMethod}
|
||||
disableCartaoSelect={disableCartaoSelect}
|
||||
/>
|
||||
|
||||
{showDueDate ? (
|
||||
<BoletoFieldsSection
|
||||
formState={formState}
|
||||
onFieldChange={handleFieldChange}
|
||||
showPaymentDate={showPaymentDate}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{!isUpdateMode ? (
|
||||
<ConditionSection
|
||||
formState={formState}
|
||||
onFieldChange={handleFieldChange}
|
||||
showInstallments={showInstallments}
|
||||
showRecurrence={showRecurrence}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<NoteSection
|
||||
formState={formState}
|
||||
onFieldChange={handleFieldChange}
|
||||
/>
|
||||
|
||||
{errorMessage ? (
|
||||
<p className="text-sm text-destructive">{errorMessage}</p>
|
||||
) : null}
|
||||
|
||||
<DialogFooter className="gap-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setDialogOpen(false)}
|
||||
disabled={isPending}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button type="submit" disabled={isPending}>
|
||||
{isPending ? "Salvando..." : submitLabel}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
"use client";
|
||||
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import type { NoteSectionProps } from "./lancamento-dialog-types";
|
||||
|
||||
export function NoteSection({ formState, onFieldChange }: NoteSectionProps) {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="note">Anotação</Label>
|
||||
<Textarea
|
||||
id="note"
|
||||
value={formState.note}
|
||||
onChange={(event) => onFieldChange("note", event.target.value)}
|
||||
placeholder="Adicione observações sobre o lançamento"
|
||||
rows={2}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
"use client";
|
||||
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { PagadorSelectContent } from "../../select-items";
|
||||
import type { PagadorSectionProps } from "./lancamento-dialog-types";
|
||||
|
||||
export function PagadorSection({
|
||||
formState,
|
||||
onFieldChange,
|
||||
pagadorOptions,
|
||||
secondaryPagadorOptions,
|
||||
}: PagadorSectionProps) {
|
||||
return (
|
||||
<div className="flex w-full flex-col gap-2 md:flex-row">
|
||||
<div className="w-full space-y-1">
|
||||
<Label htmlFor="pagador">Pagador</Label>
|
||||
<Select
|
||||
value={formState.pagadorId}
|
||||
onValueChange={(value) => onFieldChange("pagadorId", value)}
|
||||
>
|
||||
<SelectTrigger id="pagador" className="w-full">
|
||||
<SelectValue placeholder="Selecione">
|
||||
{formState.pagadorId &&
|
||||
(() => {
|
||||
const selectedOption = pagadorOptions.find(
|
||||
(opt) => opt.value === formState.pagadorId
|
||||
);
|
||||
return selectedOption ? (
|
||||
<PagadorSelectContent
|
||||
label={selectedOption.label}
|
||||
avatarUrl={selectedOption.avatarUrl}
|
||||
/>
|
||||
) : null;
|
||||
})()}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{pagadorOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
<PagadorSelectContent
|
||||
label={option.label}
|
||||
avatarUrl={option.avatarUrl}
|
||||
/>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{formState.isSplit ? (
|
||||
<div className="w-full space-y-1">
|
||||
<Label htmlFor="secondaryPagador">Dividir com</Label>
|
||||
<Select
|
||||
value={formState.secondaryPagadorId}
|
||||
onValueChange={(value) =>
|
||||
onFieldChange("secondaryPagadorId", value)
|
||||
}
|
||||
>
|
||||
<SelectTrigger
|
||||
id="secondaryPagador"
|
||||
disabled={secondaryPagadorOptions.length === 0}
|
||||
className={"w-full"}
|
||||
>
|
||||
<SelectValue placeholder="Selecione">
|
||||
{formState.secondaryPagadorId &&
|
||||
(() => {
|
||||
const selectedOption = secondaryPagadorOptions.find(
|
||||
(opt) => opt.value === formState.secondaryPagadorId
|
||||
);
|
||||
return selectedOption ? (
|
||||
<PagadorSelectContent
|
||||
label={selectedOption.label}
|
||||
avatarUrl={selectedOption.avatarUrl}
|
||||
/>
|
||||
) : null;
|
||||
})()}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{secondaryPagadorOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
<PagadorSelectContent
|
||||
label={option.label}
|
||||
avatarUrl={option.avatarUrl}
|
||||
/>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
"use client";
|
||||
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { LANCAMENTO_PAYMENT_METHODS } from "@/lib/lancamentos/constants";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import {
|
||||
PaymentMethodSelectContent,
|
||||
ContaCartaoSelectContent,
|
||||
} from "../../select-items";
|
||||
import type { PaymentMethodSectionProps } from "./lancamento-dialog-types";
|
||||
|
||||
export function PaymentMethodSection({
|
||||
formState,
|
||||
onFieldChange,
|
||||
contaOptions,
|
||||
cartaoOptions,
|
||||
isUpdateMode,
|
||||
disablePaymentMethod,
|
||||
disableCartaoSelect,
|
||||
}: PaymentMethodSectionProps) {
|
||||
const isCartaoSelected = formState.paymentMethod === "Cartão de crédito";
|
||||
const showContaSelect = [
|
||||
"Pix",
|
||||
"Dinheiro",
|
||||
"Boleto",
|
||||
"Cartão de débito",
|
||||
].includes(formState.paymentMethod);
|
||||
|
||||
return (
|
||||
<>
|
||||
{!isUpdateMode ? (
|
||||
<div className="flex w-full flex-col gap-2 md:flex-row">
|
||||
<div
|
||||
className={cn(
|
||||
"space-y-1 w-full",
|
||||
isCartaoSelected || showContaSelect ? "md:w-1/2" : "md:w-full"
|
||||
)}
|
||||
>
|
||||
<Label htmlFor="paymentMethod">Forma de pagamento</Label>
|
||||
<Select
|
||||
value={formState.paymentMethod}
|
||||
onValueChange={(value) => onFieldChange("paymentMethod", value)}
|
||||
disabled={disablePaymentMethod}
|
||||
>
|
||||
<SelectTrigger
|
||||
id="paymentMethod"
|
||||
className="w-full"
|
||||
disabled={disablePaymentMethod}
|
||||
>
|
||||
<SelectValue placeholder="Selecione" className="w-full">
|
||||
{formState.paymentMethod && (
|
||||
<PaymentMethodSelectContent label={formState.paymentMethod} />
|
||||
)}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{LANCAMENTO_PAYMENT_METHODS.map((method) => (
|
||||
<SelectItem key={method} value={method}>
|
||||
<PaymentMethodSelectContent label={method} />
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{isCartaoSelected ? (
|
||||
<div className="space-y-1 w-full md:w-1/2">
|
||||
<Label htmlFor="cartao">Cartão</Label>
|
||||
<Select
|
||||
value={formState.cartaoId}
|
||||
onValueChange={(value) => onFieldChange("cartaoId", value)}
|
||||
disabled={disableCartaoSelect}
|
||||
>
|
||||
<SelectTrigger
|
||||
id="cartao"
|
||||
className="w-full"
|
||||
disabled={disableCartaoSelect}
|
||||
>
|
||||
<SelectValue placeholder="Selecione">
|
||||
{formState.cartaoId &&
|
||||
(() => {
|
||||
const selectedOption = cartaoOptions.find(
|
||||
(opt) => opt.value === formState.cartaoId
|
||||
);
|
||||
return selectedOption ? (
|
||||
<ContaCartaoSelectContent
|
||||
label={selectedOption.label}
|
||||
logo={selectedOption.logo}
|
||||
isCartao={true}
|
||||
/>
|
||||
) : null;
|
||||
})()}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{cartaoOptions.length === 0 ? (
|
||||
<div className="px-2 py-6 text-center">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Nenhum cartão cadastrado
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
cartaoOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
<ContaCartaoSelectContent
|
||||
label={option.label}
|
||||
logo={option.logo}
|
||||
isCartao={true}
|
||||
/>
|
||||
</SelectItem>
|
||||
))
|
||||
)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!isCartaoSelected && showContaSelect ? (
|
||||
<div
|
||||
className={cn(
|
||||
"space-y-1 w-full",
|
||||
!isUpdateMode ? "md:w-1/2" : "md:w-full"
|
||||
)}
|
||||
>
|
||||
<Label htmlFor="conta">Conta</Label>
|
||||
<Select
|
||||
value={formState.contaId}
|
||||
onValueChange={(value) => onFieldChange("contaId", value)}
|
||||
>
|
||||
<SelectTrigger id="conta" className="w-full">
|
||||
<SelectValue placeholder="Selecione">
|
||||
{formState.contaId &&
|
||||
(() => {
|
||||
const selectedOption = contaOptions.find(
|
||||
(opt) => opt.value === formState.contaId
|
||||
);
|
||||
return selectedOption ? (
|
||||
<ContaCartaoSelectContent
|
||||
label={selectedOption.label}
|
||||
logo={selectedOption.logo}
|
||||
isCartao={false}
|
||||
/>
|
||||
) : null;
|
||||
})()}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{contaOptions.length === 0 ? (
|
||||
<div className="px-2 py-6 text-center">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Nenhuma conta cadastrada
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
contaOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
<ContaCartaoSelectContent
|
||||
label={option.label}
|
||||
logo={option.logo}
|
||||
isCartao={false}
|
||||
/>
|
||||
</SelectItem>
|
||||
))
|
||||
)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{isUpdateMode ? (
|
||||
<div className="flex w-full flex-col gap-2 md:flex-row">
|
||||
{isCartaoSelected ? (
|
||||
<div
|
||||
className={cn(
|
||||
"space-y-1 w-full",
|
||||
!isUpdateMode ? "md:w-1/2" : "md:w-full"
|
||||
)}
|
||||
>
|
||||
<Label htmlFor="cartaoUpdate">Cartão</Label>
|
||||
<Select
|
||||
value={formState.cartaoId}
|
||||
onValueChange={(value) => onFieldChange("cartaoId", value)}
|
||||
>
|
||||
<SelectTrigger id="cartaoUpdate" className="w-full">
|
||||
<SelectValue placeholder="Selecione">
|
||||
{formState.cartaoId &&
|
||||
(() => {
|
||||
const selectedOption = cartaoOptions.find(
|
||||
(opt) => opt.value === formState.cartaoId
|
||||
);
|
||||
return selectedOption ? (
|
||||
<ContaCartaoSelectContent
|
||||
label={selectedOption.label}
|
||||
logo={selectedOption.logo}
|
||||
isCartao={true}
|
||||
/>
|
||||
) : null;
|
||||
})()}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{cartaoOptions.length === 0 ? (
|
||||
<div className="px-2 py-6 text-center">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Nenhum cartão cadastrado
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
cartaoOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
<ContaCartaoSelectContent
|
||||
label={option.label}
|
||||
logo={option.logo}
|
||||
isCartao={true}
|
||||
/>
|
||||
</SelectItem>
|
||||
))
|
||||
)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!isCartaoSelected && showContaSelect ? (
|
||||
<div
|
||||
className={cn(
|
||||
"space-y-1 w-full",
|
||||
!isUpdateMode ? "md:w-1/2" : "md:w-full"
|
||||
)}
|
||||
>
|
||||
<Label htmlFor="contaUpdate">Conta</Label>
|
||||
<Select
|
||||
value={formState.contaId}
|
||||
onValueChange={(value) => onFieldChange("contaId", value)}
|
||||
>
|
||||
<SelectTrigger id="contaUpdate" className="w-full">
|
||||
<SelectValue placeholder="Selecione">
|
||||
{formState.contaId &&
|
||||
(() => {
|
||||
const selectedOption = contaOptions.find(
|
||||
(opt) => opt.value === formState.contaId
|
||||
);
|
||||
return selectedOption ? (
|
||||
<ContaCartaoSelectContent
|
||||
label={selectedOption.label}
|
||||
logo={selectedOption.logo}
|
||||
isCartao={false}
|
||||
/>
|
||||
) : null;
|
||||
})()}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{contaOptions.length === 0 ? (
|
||||
<div className="px-2 py-6 text-center">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Nenhuma conta cadastrada
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
contaOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
<ContaCartaoSelectContent
|
||||
label={option.label}
|
||||
logo={option.logo}
|
||||
isCartao={false}
|
||||
/>
|
||||
</SelectItem>
|
||||
))
|
||||
)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
"use client";
|
||||
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import type { SplitAndSettlementSectionProps } from "./lancamento-dialog-types";
|
||||
|
||||
export function SplitAndSettlementSection({
|
||||
formState,
|
||||
onFieldChange,
|
||||
showSettledToggle,
|
||||
}: SplitAndSettlementSectionProps) {
|
||||
return (
|
||||
<div className="flex w-full flex-col gap-2 py-2 md:flex-row">
|
||||
<div
|
||||
className={cn(
|
||||
"space-y-1",
|
||||
showSettledToggle ? "md:w-1/2 md:pr-2" : "md:w-full"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm text-foreground">Dividir lançamento</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Selecione para atribuir parte do valor a outro pagador.
|
||||
</p>
|
||||
</div>
|
||||
<Checkbox
|
||||
checked={formState.isSplit}
|
||||
onCheckedChange={(checked) =>
|
||||
onFieldChange("isSplit", Boolean(checked))
|
||||
}
|
||||
aria-label="Dividir lançamento"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{showSettledToggle ? (
|
||||
<div className="space-y-1 md:w-1/2 md:pr-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm text-foreground">Marcar como pago</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Indica que o lançamento já foi pago ou recebido.
|
||||
</p>
|
||||
</div>
|
||||
<Checkbox
|
||||
checked={Boolean(formState.isSettled)}
|
||||
onCheckedChange={(checked) =>
|
||||
onFieldChange("isSettled", Boolean(checked))
|
||||
}
|
||||
aria-label="Marcar como concluído"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
608
components/lancamentos/dialogs/mass-add-dialog.tsx
Normal file
608
components/lancamentos/dialogs/mass-add-dialog.tsx
Normal file
@@ -0,0 +1,608 @@
|
||||
"use client";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CurrencyInput } from "@/components/ui/currency-input";
|
||||
import { DatePicker } from "@/components/ui/date-picker";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { groupAndSortCategorias } from "@/lib/lancamentos/categoria-helpers";
|
||||
import { LANCAMENTO_PAYMENT_METHODS } from "@/lib/lancamentos/constants";
|
||||
import { getTodayDateString } from "@/lib/utils/date";
|
||||
import { createMonthOptions } from "@/lib/utils/period";
|
||||
import { RiAddLine, RiDeleteBinLine } from "@remixicon/react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { EstabelecimentoInput } from "../shared/estabelecimento-input";
|
||||
import type { SelectOption } from "../../types";
|
||||
import {
|
||||
CategoriaSelectContent,
|
||||
ConditionSelectContent,
|
||||
ContaCartaoSelectContent,
|
||||
PagadorSelectContent,
|
||||
PaymentMethodSelectContent,
|
||||
TransactionTypeSelectContent,
|
||||
} from "../select-items";
|
||||
|
||||
interface MassAddDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onSubmit: (data: MassAddFormData) => Promise<void>;
|
||||
pagadorOptions: SelectOption[];
|
||||
contaOptions: SelectOption[];
|
||||
cartaoOptions: SelectOption[];
|
||||
categoriaOptions: SelectOption[];
|
||||
estabelecimentos: string[];
|
||||
selectedPeriod: string;
|
||||
defaultPagadorId?: string | null;
|
||||
}
|
||||
|
||||
export interface MassAddFormData {
|
||||
fixedFields: {
|
||||
transactionType?: string;
|
||||
pagadorId?: string;
|
||||
paymentMethod?: string;
|
||||
condition?: string;
|
||||
period?: string;
|
||||
contaId?: string;
|
||||
cartaoId?: string;
|
||||
};
|
||||
transactions: Array<{
|
||||
purchaseDate: string;
|
||||
name: string;
|
||||
amount: string;
|
||||
categoriaId?: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
interface TransactionRow {
|
||||
id: string;
|
||||
purchaseDate: string;
|
||||
name: string;
|
||||
amount: string;
|
||||
categoriaId: string | undefined;
|
||||
}
|
||||
|
||||
export function MassAddDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onSubmit,
|
||||
pagadorOptions,
|
||||
contaOptions,
|
||||
cartaoOptions,
|
||||
categoriaOptions,
|
||||
estabelecimentos,
|
||||
selectedPeriod,
|
||||
defaultPagadorId,
|
||||
}: MassAddDialogProps) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
// Fixed fields state (sempre ativos, sem checkboxes)
|
||||
const [transactionType, setTransactionType] = useState<string>("Despesa");
|
||||
const [pagadorId, setPagadorId] = useState<string | undefined>(
|
||||
defaultPagadorId ?? undefined
|
||||
);
|
||||
const [paymentMethod, setPaymentMethod] = useState<string>(
|
||||
LANCAMENTO_PAYMENT_METHODS[0]
|
||||
);
|
||||
const [condition, setCondition] = useState<string>("À vista");
|
||||
const [period, setPeriod] = useState<string>(selectedPeriod);
|
||||
const [contaId, setContaId] = useState<string | undefined>();
|
||||
const [cartaoId, setCartaoId] = useState<string | undefined>();
|
||||
|
||||
// Transaction rows
|
||||
const [transactions, setTransactions] = useState<TransactionRow[]>([
|
||||
{
|
||||
id: crypto.randomUUID(),
|
||||
purchaseDate: getTodayDateString(),
|
||||
name: "",
|
||||
amount: "",
|
||||
categoriaId: undefined,
|
||||
},
|
||||
]);
|
||||
|
||||
// Period options
|
||||
const periodOptions = useMemo(
|
||||
() => createMonthOptions(selectedPeriod, 3),
|
||||
[selectedPeriod]
|
||||
);
|
||||
|
||||
// Categorias agrupadas e filtradas por tipo de transação
|
||||
const groupedCategorias = useMemo(() => {
|
||||
const filtered = categoriaOptions.filter(
|
||||
(option) => option.group?.toLowerCase() === transactionType.toLowerCase()
|
||||
);
|
||||
return groupAndSortCategorias(filtered);
|
||||
}, [categoriaOptions, transactionType]);
|
||||
|
||||
const addTransaction = () => {
|
||||
setTransactions([
|
||||
...transactions,
|
||||
{
|
||||
id: crypto.randomUUID(),
|
||||
purchaseDate: getTodayDateString(),
|
||||
name: "",
|
||||
amount: "",
|
||||
categoriaId: undefined,
|
||||
},
|
||||
]);
|
||||
};
|
||||
|
||||
const removeTransaction = (id: string) => {
|
||||
if (transactions.length === 1) {
|
||||
toast.error("É necessário ter pelo menos uma transação");
|
||||
return;
|
||||
}
|
||||
setTransactions(transactions.filter((t) => t.id !== id));
|
||||
};
|
||||
|
||||
const updateTransaction = (
|
||||
id: string,
|
||||
field: keyof TransactionRow,
|
||||
value: string | undefined
|
||||
) => {
|
||||
setTransactions(
|
||||
transactions.map((t) => (t.id === id ? { ...t, [field]: value } : t))
|
||||
);
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
// Validate conta/cartao selection
|
||||
if (paymentMethod === "Cartão de crédito" && !cartaoId) {
|
||||
toast.error("Selecione um cartão para continuar");
|
||||
return;
|
||||
}
|
||||
|
||||
if (paymentMethod !== "Cartão de crédito" && !contaId) {
|
||||
toast.error("Selecione uma conta para continuar");
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate transactions
|
||||
const invalidTransactions = transactions.filter(
|
||||
(t) => !t.name.trim() || !t.amount.trim() || !t.purchaseDate
|
||||
);
|
||||
|
||||
if (invalidTransactions.length > 0) {
|
||||
toast.error(
|
||||
"Preencha todos os campos obrigatórios das transações (data, estabelecimento e valor)"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Build form data
|
||||
const formData: MassAddFormData = {
|
||||
fixedFields: {
|
||||
transactionType,
|
||||
pagadorId,
|
||||
paymentMethod,
|
||||
condition,
|
||||
period,
|
||||
contaId: paymentMethod !== "Cartão de crédito" ? contaId : undefined,
|
||||
cartaoId: paymentMethod === "Cartão de crédito" ? cartaoId : undefined,
|
||||
},
|
||||
transactions: transactions.map((t) => ({
|
||||
purchaseDate: t.purchaseDate,
|
||||
name: t.name.trim(),
|
||||
amount: t.amount.trim(),
|
||||
categoriaId: t.categoriaId,
|
||||
})),
|
||||
};
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
await onSubmit(formData);
|
||||
onOpenChange(false);
|
||||
// Reset form
|
||||
setTransactionType("Despesa");
|
||||
setPagadorId(defaultPagadorId ?? undefined);
|
||||
setPaymentMethod(LANCAMENTO_PAYMENT_METHODS[0]);
|
||||
setCondition("À vista");
|
||||
setPeriod(selectedPeriod);
|
||||
setContaId(undefined);
|
||||
setCartaoId(undefined);
|
||||
setTransactions([
|
||||
{
|
||||
id: crypto.randomUUID(),
|
||||
purchaseDate: getTodayDateString(),
|
||||
name: "",
|
||||
amount: "",
|
||||
categoriaId: undefined,
|
||||
},
|
||||
]);
|
||||
} catch (_error) {
|
||||
// Error is handled by the onSubmit function
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-y-auto p-6 sm:px-8">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Adicionar múltiplos lançamentos</DialogTitle>
|
||||
<DialogDescription>
|
||||
Configure os valores padrão e adicione várias transações de uma vez.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-6">
|
||||
{/* Fixed Fields Section */}
|
||||
<div className="space-y-4">
|
||||
<h3 className="text-sm font-semibold">Valores Padrão</h3>
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{/* Transaction Type */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="transaction-type">Tipo de Transação</Label>
|
||||
<Select
|
||||
value={transactionType}
|
||||
onValueChange={setTransactionType}
|
||||
>
|
||||
<SelectTrigger id="transaction-type" className="w-full">
|
||||
<SelectValue>
|
||||
{transactionType && (
|
||||
<TransactionTypeSelectContent label={transactionType} />
|
||||
)}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="Despesa">
|
||||
<TransactionTypeSelectContent label="Despesa" />
|
||||
</SelectItem>
|
||||
<SelectItem value="Receita">
|
||||
<TransactionTypeSelectContent label="Receita" />
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Pagador */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="pagador">Pagador</Label>
|
||||
<Select value={pagadorId} onValueChange={setPagadorId}>
|
||||
<SelectTrigger id="pagador" className="w-full">
|
||||
<SelectValue placeholder="Selecione o pagador">
|
||||
{pagadorId &&
|
||||
(() => {
|
||||
const selectedOption = pagadorOptions.find(
|
||||
(opt) => opt.value === pagadorId
|
||||
);
|
||||
return selectedOption ? (
|
||||
<PagadorSelectContent
|
||||
label={selectedOption.label}
|
||||
avatarUrl={selectedOption.avatarUrl}
|
||||
/>
|
||||
) : null;
|
||||
})()}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{pagadorOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
<PagadorSelectContent
|
||||
label={option.label}
|
||||
avatarUrl={option.avatarUrl}
|
||||
/>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Payment Method */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="payment-method">Forma de Pagamento</Label>
|
||||
<Select
|
||||
value={paymentMethod}
|
||||
onValueChange={(value) => {
|
||||
setPaymentMethod(value);
|
||||
// Reset conta/cartao when changing payment method
|
||||
if (value === "Cartão de crédito") {
|
||||
setContaId(undefined);
|
||||
} else {
|
||||
setCartaoId(undefined);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger id="payment-method" className="w-full">
|
||||
<SelectValue>
|
||||
{paymentMethod && (
|
||||
<PaymentMethodSelectContent label={paymentMethod} />
|
||||
)}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{LANCAMENTO_PAYMENT_METHODS.map((method) => (
|
||||
<SelectItem key={method} value={method}>
|
||||
<PaymentMethodSelectContent label={method} />
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Condition */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="condition">Condição</Label>
|
||||
<Select value={condition} onValueChange={setCondition} disabled>
|
||||
<SelectTrigger id="condition" className="w-full">
|
||||
<SelectValue>
|
||||
{condition && (
|
||||
<ConditionSelectContent label={condition} />
|
||||
)}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="À vista">
|
||||
<ConditionSelectContent label="À vista" />
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Period */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="period">Período</Label>
|
||||
<Select value={period} onValueChange={setPeriod}>
|
||||
<SelectTrigger id="period" className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{periodOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Conta/Cartao */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="conta-cartao">
|
||||
{paymentMethod === "Cartão de crédito" ? "Cartão" : "Conta"}
|
||||
</Label>
|
||||
{paymentMethod === "Cartão de crédito" ? (
|
||||
<Select value={cartaoId} onValueChange={setCartaoId}>
|
||||
<SelectTrigger id="conta-cartao" className="w-full">
|
||||
<SelectValue placeholder="Selecione o cartão">
|
||||
{cartaoId &&
|
||||
(() => {
|
||||
const selectedOption = cartaoOptions.find(
|
||||
(opt) => opt.value === cartaoId
|
||||
);
|
||||
return selectedOption ? (
|
||||
<ContaCartaoSelectContent
|
||||
label={selectedOption.label}
|
||||
logo={selectedOption.logo}
|
||||
isCartao={true}
|
||||
/>
|
||||
) : null;
|
||||
})()}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{cartaoOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
<ContaCartaoSelectContent
|
||||
label={option.label}
|
||||
logo={option.logo}
|
||||
isCartao={true}
|
||||
/>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
) : (
|
||||
<Select value={contaId} onValueChange={setContaId}>
|
||||
<SelectTrigger id="conta-cartao" className="w-full">
|
||||
<SelectValue placeholder="Selecione a conta">
|
||||
{contaId &&
|
||||
(() => {
|
||||
const selectedOption = contaOptions.find(
|
||||
(opt) => opt.value === contaId
|
||||
);
|
||||
return selectedOption ? (
|
||||
<ContaCartaoSelectContent
|
||||
label={selectedOption.label}
|
||||
logo={selectedOption.logo}
|
||||
isCartao={false}
|
||||
/>
|
||||
) : null;
|
||||
})()}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{contaOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
<ContaCartaoSelectContent
|
||||
label={option.label}
|
||||
logo={option.logo}
|
||||
isCartao={false}
|
||||
/>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Transactions Section */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-sm font-semibold">Transações</h3>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={addTransaction}
|
||||
>
|
||||
<RiAddLine className="size-4" />
|
||||
Adicionar linha
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
{transactions.map((transaction, index) => (
|
||||
<div
|
||||
key={transaction.id}
|
||||
className="grid gap-2 border-b pb-3 border-dashed last:border-0"
|
||||
>
|
||||
<div className="flex gap-2 w-full">
|
||||
<div className="w-full">
|
||||
<Label
|
||||
htmlFor={`date-${transaction.id}`}
|
||||
className="sr-only"
|
||||
>
|
||||
Data {index + 1}
|
||||
</Label>
|
||||
<DatePicker
|
||||
id={`date-${transaction.id}`}
|
||||
value={transaction.purchaseDate}
|
||||
onChange={(value) =>
|
||||
updateTransaction(
|
||||
transaction.id,
|
||||
"purchaseDate",
|
||||
value
|
||||
)
|
||||
}
|
||||
placeholder="Data"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="w-full">
|
||||
<Label
|
||||
htmlFor={`name-${transaction.id}`}
|
||||
className="sr-only"
|
||||
>
|
||||
Estabelecimento {index + 1}
|
||||
</Label>
|
||||
<EstabelecimentoInput
|
||||
id={`name-${transaction.id}`}
|
||||
placeholder="Local"
|
||||
value={transaction.name}
|
||||
onChange={(value) =>
|
||||
updateTransaction(transaction.id, "name", value)
|
||||
}
|
||||
estabelecimentos={estabelecimentos}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="w-full">
|
||||
<Label
|
||||
htmlFor={`amount-${transaction.id}`}
|
||||
className="sr-only"
|
||||
>
|
||||
Valor {index + 1}
|
||||
</Label>
|
||||
<CurrencyInput
|
||||
id={`amount-${transaction.id}`}
|
||||
placeholder="R$ 0,00"
|
||||
value={transaction.amount}
|
||||
onValueChange={(value) =>
|
||||
updateTransaction(transaction.id, "amount", value)
|
||||
}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="w-full">
|
||||
<Label
|
||||
htmlFor={`categoria-${transaction.id}`}
|
||||
className="sr-only"
|
||||
>
|
||||
Categoria {index + 1}
|
||||
</Label>
|
||||
<Select
|
||||
value={transaction.categoriaId}
|
||||
onValueChange={(value) =>
|
||||
updateTransaction(
|
||||
transaction.id,
|
||||
"categoriaId",
|
||||
value
|
||||
)
|
||||
}
|
||||
>
|
||||
<SelectTrigger
|
||||
id={`categoria-${transaction.id}`}
|
||||
className="w-42 truncate"
|
||||
>
|
||||
<SelectValue placeholder="Categoria" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{groupedCategorias.map((group) => (
|
||||
<SelectGroup key={group.label}>
|
||||
<SelectLabel>{group.label}</SelectLabel>
|
||||
{group.options.map((option) => (
|
||||
<SelectItem
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
>
|
||||
<CategoriaSelectContent
|
||||
label={option.label}
|
||||
icon={option.icon}
|
||||
/>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => removeTransaction(transaction.id)}
|
||||
disabled={transactions.length === 1}
|
||||
>
|
||||
<RiDeleteBinLine className="size-4" />
|
||||
<span className="sr-only">Remover transação</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={loading}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button onClick={handleSubmit} disabled={loading}>
|
||||
{loading && <Spinner className="size-4" />}
|
||||
Criar {transactions.length}{" "}
|
||||
{transactions.length === 1 ? "lançamento" : "lançamentos"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
23
components/lancamentos/index.ts
Normal file
23
components/lancamentos/index.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
// Main page component
|
||||
export { default as LancamentosPage } from "./page/lancamentos-page";
|
||||
|
||||
// Table components
|
||||
export { default as LancamentosTable } from "./table/lancamentos-table";
|
||||
export { default as LancamentosFilters } from "./table/lancamentos-filters";
|
||||
|
||||
// Main dialogs
|
||||
export { default as LancamentoDialog } from "./dialogs/lancamento-dialog/lancamento-dialog";
|
||||
export { default as LancamentoDetailsDialog } from "./dialogs/lancamento-details-dialog";
|
||||
export { default as MassAddDialog } from "./dialogs/mass-add-dialog";
|
||||
export { default as BulkActionDialog } from "./dialogs/bulk-action-dialog";
|
||||
export { default as AnticipateInstallmentsDialog } from "./dialogs/anticipate-installments-dialog/anticipate-installments-dialog";
|
||||
|
||||
// Shared components
|
||||
export { default as EstabelecimentoInput } from "./shared/estabelecimento-input";
|
||||
export { default as InstallmentTimeline } from "./shared/installment-timeline";
|
||||
export { default as AnticipationCard } from "./shared/anticipation-card";
|
||||
|
||||
// Types and utilities
|
||||
export type * from "./types";
|
||||
export type * from "./dialogs/lancamento-dialog/lancamento-dialog-types";
|
||||
export * from "./select-items";
|
||||
503
components/lancamentos/page/lancamentos-page.tsx
Normal file
503
components/lancamentos/page/lancamentos-page.tsx
Normal file
@@ -0,0 +1,503 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
createMassLancamentosAction,
|
||||
deleteLancamentoAction,
|
||||
deleteLancamentoBulkAction,
|
||||
deleteMultipleLancamentosAction,
|
||||
toggleLancamentoSettlementAction,
|
||||
updateLancamentoBulkAction,
|
||||
} from "@/app/(dashboard)/lancamentos/actions";
|
||||
import { ConfirmActionDialog } from "@/components/confirm-action-dialog";
|
||||
import { useCallback, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { AnticipateInstallmentsDialog } from "../dialogs/anticipate-installments-dialog/anticipate-installments-dialog";
|
||||
import { AnticipationHistoryDialog } from "../dialogs/anticipate-installments-dialog/anticipation-history-dialog";
|
||||
import { BulkActionDialog, type BulkActionScope } from "../dialogs/bulk-action-dialog";
|
||||
import { LancamentoDetailsDialog } from "../dialogs/lancamento-details-dialog";
|
||||
import { LancamentoDialog } from "../dialogs/lancamento-dialog/lancamento-dialog";
|
||||
import { LancamentosTable } from "../table/lancamentos-table";
|
||||
import { MassAddDialog, type MassAddFormData } from "../dialogs/mass-add-dialog";
|
||||
import type {
|
||||
ContaCartaoFilterOption,
|
||||
LancamentoFilterOption,
|
||||
LancamentoItem,
|
||||
SelectOption,
|
||||
} from "../types";
|
||||
|
||||
interface LancamentosPageProps {
|
||||
lancamentos: LancamentoItem[];
|
||||
pagadorOptions: SelectOption[];
|
||||
splitPagadorOptions: SelectOption[];
|
||||
defaultPagadorId: string | null;
|
||||
contaOptions: SelectOption[];
|
||||
cartaoOptions: SelectOption[];
|
||||
categoriaOptions: SelectOption[];
|
||||
pagadorFilterOptions: LancamentoFilterOption[];
|
||||
categoriaFilterOptions: LancamentoFilterOption[];
|
||||
contaCartaoFilterOptions: ContaCartaoFilterOption[];
|
||||
selectedPeriod: string;
|
||||
estabelecimentos: string[];
|
||||
allowCreate?: boolean;
|
||||
defaultCartaoId?: string | null;
|
||||
defaultPaymentMethod?: string | null;
|
||||
lockCartaoSelection?: boolean;
|
||||
lockPaymentMethod?: boolean;
|
||||
}
|
||||
|
||||
export function LancamentosPage({
|
||||
lancamentos,
|
||||
pagadorOptions,
|
||||
splitPagadorOptions,
|
||||
defaultPagadorId,
|
||||
contaOptions,
|
||||
cartaoOptions,
|
||||
categoriaOptions,
|
||||
pagadorFilterOptions,
|
||||
categoriaFilterOptions,
|
||||
contaCartaoFilterOptions,
|
||||
selectedPeriod,
|
||||
estabelecimentos,
|
||||
allowCreate = true,
|
||||
defaultCartaoId,
|
||||
defaultPaymentMethod,
|
||||
lockCartaoSelection,
|
||||
lockPaymentMethod,
|
||||
}: LancamentosPageProps) {
|
||||
const [selectedLancamento, setSelectedLancamento] =
|
||||
useState<LancamentoItem | null>(null);
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [massAddOpen, setMassAddOpen] = useState(false);
|
||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||
const [lancamentoToDelete, setLancamentoToDelete] =
|
||||
useState<LancamentoItem | null>(null);
|
||||
const [detailsOpen, setDetailsOpen] = useState(false);
|
||||
const [settlementLoadingId, setSettlementLoadingId] = useState<string | null>(
|
||||
null
|
||||
);
|
||||
const [bulkEditOpen, setBulkEditOpen] = useState(false);
|
||||
const [bulkDeleteOpen, setBulkDeleteOpen] = useState(false);
|
||||
const [pendingEditData, setPendingEditData] = useState<{
|
||||
id: string;
|
||||
name: string;
|
||||
categoriaId: string | undefined;
|
||||
note: string;
|
||||
pagadorId: string | undefined;
|
||||
contaId: string | undefined;
|
||||
cartaoId: string | undefined;
|
||||
amount: number;
|
||||
dueDate: string | null;
|
||||
boletoPaymentDate: string | null;
|
||||
lancamento: LancamentoItem;
|
||||
} | null>(null);
|
||||
const [pendingDeleteData, setPendingDeleteData] =
|
||||
useState<LancamentoItem | null>(null);
|
||||
const [multipleBulkDeleteOpen, setMultipleBulkDeleteOpen] = useState(false);
|
||||
const [pendingMultipleDeleteData, setPendingMultipleDeleteData] = useState<
|
||||
LancamentoItem[]
|
||||
>([]);
|
||||
const [anticipateOpen, setAnticipateOpen] = useState(false);
|
||||
const [anticipationHistoryOpen, setAnticipationHistoryOpen] = useState(false);
|
||||
const [selectedForAnticipation, setSelectedForAnticipation] =
|
||||
useState<LancamentoItem | null>(null);
|
||||
|
||||
const handleToggleSettlement = useCallback(async (item: LancamentoItem) => {
|
||||
if (item.paymentMethod === "Cartão de crédito") {
|
||||
toast.info(
|
||||
"Pagamentos com cartão são conciliados automaticamente. Ajuste pelo cartão."
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const supportedMethods = ["Pix", "Boleto", "Dinheiro", "Cartão de débito"];
|
||||
if (!supportedMethods.includes(item.paymentMethod)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextValue = !Boolean(item.isSettled);
|
||||
|
||||
try {
|
||||
setSettlementLoadingId(item.id);
|
||||
const result = await toggleLancamentoSettlementAction({
|
||||
id: item.id,
|
||||
value: nextValue,
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.error);
|
||||
}
|
||||
|
||||
toast.success(result.message);
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Não foi possível atualizar o pagamento.";
|
||||
toast.error(message);
|
||||
} finally {
|
||||
setSettlementLoadingId(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleDelete = useCallback(async () => {
|
||||
if (!lancamentoToDelete) {
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await deleteLancamentoAction({
|
||||
id: lancamentoToDelete.id,
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
toast.error(result.error);
|
||||
throw new Error(result.error);
|
||||
}
|
||||
|
||||
toast.success(result.message);
|
||||
setDeleteOpen(false);
|
||||
}, [lancamentoToDelete]);
|
||||
|
||||
const handleBulkDelete = useCallback(
|
||||
async (scope: BulkActionScope) => {
|
||||
if (!pendingDeleteData) {
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await deleteLancamentoBulkAction({
|
||||
id: pendingDeleteData.id,
|
||||
scope,
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
toast.error(result.error);
|
||||
throw new Error(result.error);
|
||||
}
|
||||
|
||||
toast.success(result.message);
|
||||
setBulkDeleteOpen(false);
|
||||
setPendingDeleteData(null);
|
||||
},
|
||||
[pendingDeleteData]
|
||||
);
|
||||
|
||||
const handleBulkEditRequest = useCallback(
|
||||
(data: {
|
||||
id: string;
|
||||
name: string;
|
||||
categoriaId: string | undefined;
|
||||
note: string;
|
||||
pagadorId: string | undefined;
|
||||
contaId: string | undefined;
|
||||
cartaoId: string | undefined;
|
||||
amount: number;
|
||||
dueDate: string | null;
|
||||
boletoPaymentDate: string | null;
|
||||
}) => {
|
||||
if (!selectedLancamento) {
|
||||
return;
|
||||
}
|
||||
|
||||
setPendingEditData({
|
||||
...data,
|
||||
lancamento: selectedLancamento,
|
||||
});
|
||||
setEditOpen(false);
|
||||
setBulkEditOpen(true);
|
||||
},
|
||||
[selectedLancamento]
|
||||
);
|
||||
|
||||
const handleBulkEdit = useCallback(
|
||||
async (scope: BulkActionScope) => {
|
||||
if (!pendingEditData) {
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await updateLancamentoBulkAction({
|
||||
id: pendingEditData.id,
|
||||
scope,
|
||||
name: pendingEditData.name,
|
||||
categoriaId: pendingEditData.categoriaId,
|
||||
note: pendingEditData.note,
|
||||
pagadorId: pendingEditData.pagadorId,
|
||||
contaId: pendingEditData.contaId,
|
||||
cartaoId: pendingEditData.cartaoId,
|
||||
amount: pendingEditData.amount,
|
||||
dueDate: pendingEditData.dueDate,
|
||||
boletoPaymentDate: pendingEditData.boletoPaymentDate,
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
toast.error(result.error);
|
||||
throw new Error(result.error);
|
||||
}
|
||||
|
||||
toast.success(result.message);
|
||||
setBulkEditOpen(false);
|
||||
setPendingEditData(null);
|
||||
},
|
||||
[pendingEditData]
|
||||
);
|
||||
|
||||
const handleMassAddSubmit = useCallback(async (data: MassAddFormData) => {
|
||||
const result = await createMassLancamentosAction(data);
|
||||
|
||||
if (!result.success) {
|
||||
toast.error(result.error);
|
||||
throw new Error(result.error);
|
||||
}
|
||||
|
||||
toast.success(result.message);
|
||||
}, []);
|
||||
|
||||
const handleMultipleBulkDelete = useCallback((items: LancamentoItem[]) => {
|
||||
setPendingMultipleDeleteData(items);
|
||||
setMultipleBulkDeleteOpen(true);
|
||||
}, []);
|
||||
|
||||
const confirmMultipleBulkDelete = useCallback(async () => {
|
||||
if (pendingMultipleDeleteData.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const ids = pendingMultipleDeleteData.map((item) => item.id);
|
||||
const result = await deleteMultipleLancamentosAction({ ids });
|
||||
|
||||
if (!result.success) {
|
||||
toast.error(result.error);
|
||||
throw new Error(result.error);
|
||||
}
|
||||
|
||||
toast.success(result.message);
|
||||
setMultipleBulkDeleteOpen(false);
|
||||
setPendingMultipleDeleteData([]);
|
||||
}, [pendingMultipleDeleteData]);
|
||||
|
||||
const handleCreate = useCallback(() => {
|
||||
setCreateOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleMassAdd = useCallback(() => {
|
||||
setMassAddOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleEdit = useCallback((item: LancamentoItem) => {
|
||||
setSelectedLancamento(item);
|
||||
setEditOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleConfirmDelete = useCallback((item: LancamentoItem) => {
|
||||
if (item.seriesId) {
|
||||
setPendingDeleteData(item);
|
||||
setBulkDeleteOpen(true);
|
||||
} else {
|
||||
setLancamentoToDelete(item);
|
||||
setDeleteOpen(true);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleViewDetails = useCallback((item: LancamentoItem) => {
|
||||
setSelectedLancamento(item);
|
||||
setDetailsOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleAnticipate = useCallback((item: LancamentoItem) => {
|
||||
setSelectedForAnticipation(item);
|
||||
setAnticipateOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleViewAnticipationHistory = useCallback((item: LancamentoItem) => {
|
||||
setSelectedForAnticipation(item);
|
||||
setAnticipationHistoryOpen(true);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<LancamentosTable
|
||||
data={lancamentos}
|
||||
pagadorFilterOptions={pagadorFilterOptions}
|
||||
categoriaFilterOptions={categoriaFilterOptions}
|
||||
contaCartaoFilterOptions={contaCartaoFilterOptions}
|
||||
onCreate={allowCreate ? handleCreate : undefined}
|
||||
onMassAdd={allowCreate ? handleMassAdd : undefined}
|
||||
onEdit={handleEdit}
|
||||
onConfirmDelete={handleConfirmDelete}
|
||||
onBulkDelete={handleMultipleBulkDelete}
|
||||
onViewDetails={handleViewDetails}
|
||||
onToggleSettlement={handleToggleSettlement}
|
||||
onAnticipate={handleAnticipate}
|
||||
onViewAnticipationHistory={handleViewAnticipationHistory}
|
||||
isSettlementLoading={(id) => settlementLoadingId === id}
|
||||
/>
|
||||
|
||||
{allowCreate ? (
|
||||
<LancamentoDialog
|
||||
mode="create"
|
||||
open={createOpen}
|
||||
onOpenChange={setCreateOpen}
|
||||
pagadorOptions={pagadorOptions}
|
||||
splitPagadorOptions={splitPagadorOptions}
|
||||
defaultPagadorId={defaultPagadorId}
|
||||
contaOptions={contaOptions}
|
||||
cartaoOptions={cartaoOptions}
|
||||
categoriaOptions={categoriaOptions}
|
||||
estabelecimentos={estabelecimentos}
|
||||
defaultPeriod={selectedPeriod}
|
||||
defaultCartaoId={defaultCartaoId}
|
||||
defaultPaymentMethod={defaultPaymentMethod}
|
||||
lockCartaoSelection={lockCartaoSelection}
|
||||
lockPaymentMethod={lockPaymentMethod}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<LancamentoDialog
|
||||
mode="update"
|
||||
open={editOpen && !!selectedLancamento}
|
||||
onOpenChange={setEditOpen}
|
||||
pagadorOptions={pagadorOptions}
|
||||
splitPagadorOptions={splitPagadorOptions}
|
||||
defaultPagadorId={defaultPagadorId}
|
||||
contaOptions={contaOptions}
|
||||
cartaoOptions={cartaoOptions}
|
||||
categoriaOptions={categoriaOptions}
|
||||
estabelecimentos={estabelecimentos}
|
||||
lancamento={selectedLancamento ?? undefined}
|
||||
defaultPeriod={selectedPeriod}
|
||||
onBulkEditRequest={handleBulkEditRequest}
|
||||
/>
|
||||
|
||||
<LancamentoDetailsDialog
|
||||
open={detailsOpen && !!selectedLancamento}
|
||||
onOpenChange={(open) => {
|
||||
setDetailsOpen(open);
|
||||
if (!open) {
|
||||
setSelectedLancamento(null);
|
||||
}
|
||||
}}
|
||||
lancamento={detailsOpen ? selectedLancamento : null}
|
||||
/>
|
||||
|
||||
<ConfirmActionDialog
|
||||
open={deleteOpen && !!lancamentoToDelete}
|
||||
onOpenChange={setDeleteOpen}
|
||||
title={
|
||||
lancamentoToDelete
|
||||
? `Remover lançamento "${lancamentoToDelete.name}"?`
|
||||
: "Remover lançamento?"
|
||||
}
|
||||
description="Essa ação é irreversível e removerá o lançamento de forma permanente."
|
||||
confirmLabel="Remover"
|
||||
pendingLabel="Removendo..."
|
||||
confirmVariant="destructive"
|
||||
onConfirm={handleDelete}
|
||||
disabled={!lancamentoToDelete}
|
||||
/>
|
||||
|
||||
<BulkActionDialog
|
||||
open={bulkDeleteOpen && !!pendingDeleteData}
|
||||
onOpenChange={setBulkDeleteOpen}
|
||||
actionType="delete"
|
||||
seriesType={
|
||||
pendingDeleteData?.condition === "Parcelado"
|
||||
? "installment"
|
||||
: "recurring"
|
||||
}
|
||||
currentNumber={pendingDeleteData?.currentInstallment ?? undefined}
|
||||
totalCount={
|
||||
pendingDeleteData?.installmentCount ??
|
||||
pendingDeleteData?.recurrenceCount ??
|
||||
undefined
|
||||
}
|
||||
onConfirm={handleBulkDelete}
|
||||
/>
|
||||
|
||||
<BulkActionDialog
|
||||
open={bulkEditOpen && !!pendingEditData}
|
||||
onOpenChange={setBulkEditOpen}
|
||||
actionType="edit"
|
||||
seriesType={
|
||||
pendingEditData?.lancamento.condition === "Parcelado"
|
||||
? "installment"
|
||||
: "recurring"
|
||||
}
|
||||
currentNumber={
|
||||
pendingEditData?.lancamento.currentInstallment ?? undefined
|
||||
}
|
||||
totalCount={
|
||||
pendingEditData?.lancamento.installmentCount ??
|
||||
pendingEditData?.lancamento.recurrenceCount ??
|
||||
undefined
|
||||
}
|
||||
onConfirm={handleBulkEdit}
|
||||
/>
|
||||
|
||||
{allowCreate ? (
|
||||
<MassAddDialog
|
||||
open={massAddOpen}
|
||||
onOpenChange={setMassAddOpen}
|
||||
onSubmit={handleMassAddSubmit}
|
||||
pagadorOptions={pagadorOptions}
|
||||
contaOptions={contaOptions}
|
||||
cartaoOptions={cartaoOptions}
|
||||
categoriaOptions={categoriaOptions}
|
||||
estabelecimentos={estabelecimentos}
|
||||
selectedPeriod={selectedPeriod}
|
||||
defaultPagadorId={defaultPagadorId}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<ConfirmActionDialog
|
||||
open={multipleBulkDeleteOpen && pendingMultipleDeleteData.length > 0}
|
||||
onOpenChange={setMultipleBulkDeleteOpen}
|
||||
title={`Remover ${pendingMultipleDeleteData.length} ${
|
||||
pendingMultipleDeleteData.length === 1 ? "lançamento" : "lançamentos"
|
||||
}?`}
|
||||
description="Essa ação é irreversível e removerá os lançamentos selecionados de forma permanente."
|
||||
confirmLabel="Remover"
|
||||
pendingLabel="Removendo..."
|
||||
confirmVariant="destructive"
|
||||
onConfirm={confirmMultipleBulkDelete}
|
||||
disabled={pendingMultipleDeleteData.length === 0}
|
||||
/>
|
||||
|
||||
{/* Dialogs de Antecipação */}
|
||||
{selectedForAnticipation && (
|
||||
<AnticipateInstallmentsDialog
|
||||
open={anticipateOpen}
|
||||
onOpenChange={setAnticipateOpen}
|
||||
seriesId={selectedForAnticipation.seriesId!}
|
||||
lancamentoName={selectedForAnticipation.name}
|
||||
categorias={categoriaOptions.map((c) => ({
|
||||
id: c.value,
|
||||
name: c.label,
|
||||
icon: c.icon ?? null,
|
||||
}))}
|
||||
pagadores={pagadorOptions.map((p) => ({
|
||||
id: p.value,
|
||||
name: p.label,
|
||||
}))}
|
||||
defaultPeriod={selectedPeriod}
|
||||
/>
|
||||
)}
|
||||
|
||||
{selectedForAnticipation && (
|
||||
<AnticipationHistoryDialog
|
||||
open={anticipationHistoryOpen}
|
||||
onOpenChange={setAnticipationHistoryOpen}
|
||||
seriesId={selectedForAnticipation.seriesId!}
|
||||
lancamentoName={selectedForAnticipation.name}
|
||||
onViewLancamento={(lancamentoId) => {
|
||||
const lancamento = lancamentos.find((l) => l.id === lancamentoId);
|
||||
if (lancamento) {
|
||||
setSelectedLancamento(lancamento);
|
||||
setDetailsOpen(true);
|
||||
setAnticipationHistoryOpen(false);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
120
components/lancamentos/select-items.tsx
Normal file
120
components/lancamentos/select-items.tsx
Normal file
@@ -0,0 +1,120 @@
|
||||
"use client";
|
||||
|
||||
import { CategoryIcon } from "@/components/categorias/category-icon";
|
||||
import DotIcon from "@/components/dot-icon";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { getAvatarSrc } from "@/lib/pagadores/utils";
|
||||
import { getConditionIcon, getPaymentMethodIcon } from "@/lib/utils/icons";
|
||||
import { RiBankCard2Line, RiBankLine } from "@remixicon/react";
|
||||
import Image from "next/image";
|
||||
|
||||
type SelectItemContentProps = {
|
||||
label: string;
|
||||
avatarUrl?: string | null;
|
||||
logo?: string | null;
|
||||
icon?: string | null;
|
||||
};
|
||||
|
||||
export function PagadorSelectContent({
|
||||
label,
|
||||
avatarUrl,
|
||||
}: SelectItemContentProps) {
|
||||
const avatarSrc = getAvatarSrc(avatarUrl);
|
||||
const initial = label.charAt(0).toUpperCase() || "?";
|
||||
|
||||
return (
|
||||
<span className="flex items-center gap-2">
|
||||
<Avatar className="size-5 border border-border/60 bg-background">
|
||||
<AvatarImage src={avatarSrc} alt={`Avatar de ${label}`} />
|
||||
<AvatarFallback className="text-[10px] font-medium uppercase">
|
||||
{initial}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span>{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function CategoriaSelectContent({
|
||||
label,
|
||||
icon,
|
||||
}: SelectItemContentProps) {
|
||||
return (
|
||||
<span className="flex items-center gap-2">
|
||||
<CategoryIcon name={icon} className="size-4" />
|
||||
<span>{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function TransactionTypeSelectContent({ label }: { label: string }) {
|
||||
const colorMap: Record<string, string> = {
|
||||
Receita: "bg-emerald-600 dark:bg-emerald-400",
|
||||
Despesa: "bg-red-600 dark:bg-red-400",
|
||||
Transferência: "bg-blue-600 dark:bg-blue-400",
|
||||
};
|
||||
|
||||
return (
|
||||
<span className="flex items-center gap-2">
|
||||
<DotIcon bg_dot={colorMap[label]} />
|
||||
<span>{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function PaymentMethodSelectContent({ label }: { label: string }) {
|
||||
const icon = getPaymentMethodIcon(label);
|
||||
|
||||
return (
|
||||
<span className="flex items-center gap-2">
|
||||
{icon}
|
||||
<span>{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function ConditionSelectContent({ label }: { label: string }) {
|
||||
const icon = getConditionIcon(label);
|
||||
|
||||
return (
|
||||
<span className="flex items-center gap-2">
|
||||
{icon}
|
||||
<span>{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function ContaCartaoSelectContent({
|
||||
label,
|
||||
logo,
|
||||
isCartao,
|
||||
}: SelectItemContentProps & { isCartao?: boolean }) {
|
||||
const resolveLogoSrc = (logoPath: string | null) => {
|
||||
if (!logoPath) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const fileName = logoPath.split("/").filter(Boolean).pop() ?? logoPath;
|
||||
return `/logos/${fileName}`;
|
||||
};
|
||||
|
||||
const logoSrc = resolveLogoSrc(logo);
|
||||
const Icon = isCartao ? RiBankCard2Line : RiBankLine;
|
||||
|
||||
return (
|
||||
<span className="flex items-center gap-2">
|
||||
{logoSrc ? (
|
||||
<Image
|
||||
src={logoSrc}
|
||||
alt={`Logo de ${label}`}
|
||||
width={20}
|
||||
height={20}
|
||||
className="rounded"
|
||||
/>
|
||||
) : (
|
||||
<Icon className="size-4 text-muted-foreground" aria-hidden />
|
||||
)}
|
||||
<span>{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
205
components/lancamentos/shared/anticipation-card.tsx
Normal file
205
components/lancamentos/shared/anticipation-card.tsx
Normal file
@@ -0,0 +1,205 @@
|
||||
"use client";
|
||||
|
||||
import { cancelInstallmentAnticipationAction } from "@/app/(dashboard)/lancamentos/anticipation-actions";
|
||||
import { ConfirmActionDialog } from "@/components/confirm-action-dialog";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import type { InstallmentAnticipationWithRelations } from "@/lib/installments/anticipation-types";
|
||||
import { RiCalendarCheckLine, RiCloseLine, RiEyeLine } from "@remixicon/react";
|
||||
import { format } from "date-fns";
|
||||
import { ptBR } from "date-fns/locale";
|
||||
import { useTransition } from "react";
|
||||
import { toast } from "sonner";
|
||||
import MoneyValues from "@/components/money-values";
|
||||
|
||||
interface AnticipationCardProps {
|
||||
anticipation: InstallmentAnticipationWithRelations;
|
||||
onViewLancamento?: (lancamentoId: string) => void;
|
||||
onCanceled?: () => void;
|
||||
}
|
||||
|
||||
const monthFormatter = new Intl.DateTimeFormat("pt-BR", {
|
||||
month: "long",
|
||||
year: "numeric",
|
||||
});
|
||||
|
||||
const formatPeriodLabel = (period: string) => {
|
||||
const [year, month] = period.split("-").map(Number);
|
||||
if (!year || !month) {
|
||||
return period;
|
||||
}
|
||||
const date = new Date(year, month - 1, 1);
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return period;
|
||||
}
|
||||
const label = monthFormatter.format(date);
|
||||
return label.charAt(0).toUpperCase() + label.slice(1);
|
||||
};
|
||||
|
||||
export function AnticipationCard({
|
||||
anticipation,
|
||||
onViewLancamento,
|
||||
onCanceled,
|
||||
}: AnticipationCardProps) {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
const isSettled = anticipation.lancamento.isSettled === true;
|
||||
const canCancel = !isSettled;
|
||||
|
||||
const formatDate = (date: Date) => {
|
||||
return format(date, "dd 'de' MMMM 'de' yyyy", { locale: ptBR });
|
||||
};
|
||||
|
||||
const handleCancel = async () => {
|
||||
startTransition(async () => {
|
||||
const result = await cancelInstallmentAnticipationAction({
|
||||
anticipationId: anticipation.id,
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
onCanceled?.();
|
||||
} else {
|
||||
toast.error(result.error || "Erro ao cancelar antecipação");
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const handleViewLancamento = () => {
|
||||
onViewLancamento?.(anticipation.lancamentoId);
|
||||
};
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-start justify-between space-y-0 pb-3">
|
||||
<div className="space-y-1">
|
||||
<CardTitle className="text-base">
|
||||
{anticipation.installmentCount}{" "}
|
||||
{anticipation.installmentCount === 1
|
||||
? "parcela antecipada"
|
||||
: "parcelas antecipadas"}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
<RiCalendarCheckLine className="mr-1 inline size-3.5" />
|
||||
{formatDate(anticipation.anticipationDate)}
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Badge variant="secondary">
|
||||
{formatPeriodLabel(anticipation.anticipationPeriod)}
|
||||
</Badge>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-3">
|
||||
<dl className="grid grid-cols-2 gap-3 text-sm">
|
||||
<div>
|
||||
<dt className="text-muted-foreground">Valor Original</dt>
|
||||
<dd className="mt-1 font-medium tabular-nums">
|
||||
<MoneyValues amount={Number(anticipation.totalAmount)} />
|
||||
</dd>
|
||||
</div>
|
||||
|
||||
{Number(anticipation.discount) > 0 && (
|
||||
<div>
|
||||
<dt className="text-muted-foreground">Desconto</dt>
|
||||
<dd className="mt-1 font-medium tabular-nums text-green-600">
|
||||
- <MoneyValues amount={Number(anticipation.discount)} />
|
||||
</dd>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={Number(anticipation.discount) > 0 ? "col-span-2 border-t pt-3" : ""}>
|
||||
<dt className="text-muted-foreground">
|
||||
{Number(anticipation.discount) > 0 ? "Valor Final" : "Valor Total"}
|
||||
</dt>
|
||||
<dd className="mt-1 text-lg font-semibold tabular-nums text-primary">
|
||||
<MoneyValues
|
||||
amount={
|
||||
Number(anticipation.totalAmount) < 0
|
||||
? Number(anticipation.totalAmount) + Number(anticipation.discount)
|
||||
: Number(anticipation.totalAmount) - Number(anticipation.discount)
|
||||
}
|
||||
/>
|
||||
</dd>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<dt className="text-muted-foreground">Status do Lançamento</dt>
|
||||
<dd className="mt-1">
|
||||
<Badge variant={isSettled ? "success" : "outline"}>
|
||||
{isSettled ? "Pago" : "Pendente"}
|
||||
</Badge>
|
||||
</dd>
|
||||
</div>
|
||||
|
||||
{anticipation.pagador && (
|
||||
<div>
|
||||
<dt className="text-muted-foreground">Pagador</dt>
|
||||
<dd className="mt-1 font-medium">{anticipation.pagador.name}</dd>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{anticipation.categoria && (
|
||||
<div>
|
||||
<dt className="text-muted-foreground">Categoria</dt>
|
||||
<dd className="mt-1 font-medium">
|
||||
{anticipation.categoria.name}
|
||||
</dd>
|
||||
</div>
|
||||
)}
|
||||
</dl>
|
||||
|
||||
{anticipation.note && (
|
||||
<div className="rounded-lg border bg-muted/20 p-3">
|
||||
<dt className="text-xs font-medium text-muted-foreground">
|
||||
Observação
|
||||
</dt>
|
||||
<dd className="mt-1 text-sm">{anticipation.note}</dd>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
<CardFooter className="flex flex-wrap items-center justify-between gap-2 border-t pt-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleViewLancamento}
|
||||
disabled={isPending}
|
||||
>
|
||||
<RiEyeLine className="mr-2 size-4" />
|
||||
Ver Lançamento
|
||||
</Button>
|
||||
|
||||
{canCancel && (
|
||||
<ConfirmActionDialog
|
||||
trigger={
|
||||
<Button variant="destructive" size="sm" disabled={isPending}>
|
||||
<RiCloseLine className="mr-2 size-4" />
|
||||
Cancelar Antecipação
|
||||
</Button>
|
||||
}
|
||||
title="Cancelar antecipação?"
|
||||
description="Esta ação irá reverter a antecipação e restaurar as parcelas originais. O lançamento de antecipação será removido."
|
||||
confirmLabel="Cancelar Antecipação"
|
||||
confirmVariant="destructive"
|
||||
pendingLabel="Cancelando..."
|
||||
onConfirm={handleCancel}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isSettled && (
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Não é possível cancelar uma antecipação paga
|
||||
</div>
|
||||
)}
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
129
components/lancamentos/shared/estabelecimento-input.tsx
Normal file
129
components/lancamentos/shared/estabelecimento-input.tsx
Normal file
@@ -0,0 +1,129 @@
|
||||
"use client";
|
||||
|
||||
import { RiCheckLine, RiSearchLine } from "@remixicon/react";
|
||||
import * as React from "react";
|
||||
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
} from "@/components/ui/command";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
|
||||
export interface EstabelecimentoInputProps {
|
||||
id?: string;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
estabelecimentos: string[];
|
||||
placeholder?: string;
|
||||
required?: boolean;
|
||||
maxLength?: number;
|
||||
}
|
||||
|
||||
export function EstabelecimentoInput({
|
||||
id,
|
||||
value,
|
||||
onChange,
|
||||
estabelecimentos = [],
|
||||
placeholder = "Ex.: Padaria",
|
||||
required = false,
|
||||
maxLength = 20,
|
||||
}: EstabelecimentoInputProps) {
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const [searchValue, setSearchValue] = React.useState("");
|
||||
|
||||
const handleSelect = (selectedValue: string) => {
|
||||
onChange(selectedValue);
|
||||
setOpen(false);
|
||||
setSearchValue("");
|
||||
};
|
||||
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newValue = e.target.value;
|
||||
onChange(newValue);
|
||||
setSearchValue(newValue);
|
||||
|
||||
// Open popover when user types and there are suggestions
|
||||
if (newValue.length > 0 && estabelecimentos.length > 0) {
|
||||
setOpen(true);
|
||||
}
|
||||
};
|
||||
|
||||
const filteredEstabelecimentos = React.useMemo(() => {
|
||||
if (!searchValue) return estabelecimentos;
|
||||
|
||||
const lowerSearch = searchValue.toLowerCase();
|
||||
return estabelecimentos.filter((item) =>
|
||||
item.toLowerCase().includes(lowerSearch)
|
||||
);
|
||||
}, [estabelecimentos, searchValue]);
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id={id}
|
||||
value={value}
|
||||
onChange={handleInputChange}
|
||||
placeholder={placeholder}
|
||||
required={required}
|
||||
maxLength={maxLength}
|
||||
autoComplete="off"
|
||||
onFocus={() => {
|
||||
if (estabelecimentos.length > 0) {
|
||||
setOpen(true);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{estabelecimentos.length > 0 && (
|
||||
<RiSearchLine className="absolute right-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground pointer-events-none" />
|
||||
)}
|
||||
</div>
|
||||
</PopoverTrigger>
|
||||
{estabelecimentos.length > 0 && (
|
||||
<PopoverContent
|
||||
className="p-0 w-[--radix-popover-trigger-width]"
|
||||
align="start"
|
||||
onOpenAutoFocus={(e) => e.preventDefault()}
|
||||
>
|
||||
<Command>
|
||||
<CommandList className="max-h-[300px] overflow-y-auto">
|
||||
<CommandEmpty className="p-6">
|
||||
Nenhum estabelecimento encontrado.
|
||||
</CommandEmpty>
|
||||
<CommandGroup className="p-1">
|
||||
{filteredEstabelecimentos.map((item) => (
|
||||
<CommandItem
|
||||
key={item}
|
||||
value={item}
|
||||
onSelect={() => handleSelect(item)}
|
||||
className="cursor-pointer gap-1"
|
||||
>
|
||||
<RiCheckLine
|
||||
className={cn(
|
||||
"size-4 shrink-0",
|
||||
value === item
|
||||
? "opacity-100 text-green-500"
|
||||
: "opacity-5"
|
||||
)}
|
||||
/>
|
||||
<span className="truncate flex-1">{item}</span>
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
)}
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user