refactor: migrate from ESLint to Biome and extract SQL queries to data.ts
- Replace ESLint with Biome for linting and formatting - Configure Biome with tabs, double quotes, and organized imports - Move all SQL/Drizzle queries from page.tsx files to data.ts files - Create new data.ts files for: ajustes, dashboard, relatorios/categorias - Update existing data.ts files: extrato, fatura (add lancamentos queries) - Remove all drizzle-orm imports from page.tsx files - Update README.md with new tooling info Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,90 +1,90 @@
|
||||
import MoneyValues from "@/components/money-values";
|
||||
import { WidgetEmptyState } from "@/components/widget-empty-state";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import type { PagadorCardUsageItem } from "@/lib/pagadores/details";
|
||||
import { RiBankCard2Line } from "@remixicon/react";
|
||||
import Image from "next/image";
|
||||
import MoneyValues from "@/components/money-values";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { WidgetEmptyState } from "@/components/widget-empty-state";
|
||||
import type { PagadorCardUsageItem } from "@/lib/pagadores/details";
|
||||
|
||||
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}`;
|
||||
if (!logo) return null;
|
||||
if (
|
||||
logo.startsWith("http://") ||
|
||||
logo.startsWith("https://") ||
|
||||
logo.startsWith("data:")
|
||||
) {
|
||||
return logo;
|
||||
}
|
||||
return logo.startsWith("/") ? logo : `/logos/${logo}`;
|
||||
};
|
||||
|
||||
type PagadorCardUsageCardProps = {
|
||||
items: PagadorCardUsageItem[];
|
||||
items: PagadorCardUsageItem[];
|
||||
};
|
||||
|
||||
export function PagadorCardUsageCard({ items }: PagadorCardUsageCardProps) {
|
||||
return (
|
||||
<Card className="border">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-xl font-semibold">
|
||||
Cartões utilizados
|
||||
</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Valores por cartão neste período (inclui logo quando disponível).
|
||||
</p>
|
||||
</CardHeader>
|
||||
return (
|
||||
<Card className="border">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-xl font-semibold">
|
||||
Cartões utilizados
|
||||
</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Valores por cartão neste período (inclui logo quando disponível).
|
||||
</p>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-3 pt-2">
|
||||
{items.length === 0 ? (
|
||||
<WidgetEmptyState
|
||||
icon={<RiBankCard2Line className="size-6 text-muted-foreground" />}
|
||||
title="Nenhum lançamento com cartão de crédito"
|
||||
description="Quando houver despesas registradas com cartão, elas aparecerão aqui."
|
||||
/>
|
||||
) : (
|
||||
<ul className="space-y-3">
|
||||
{items.map((item) => {
|
||||
const logoPath = resolveLogoPath(item.logo);
|
||||
return (
|
||||
<li
|
||||
key={item.id}
|
||||
className="flex items-center justify-between gap-3 rounded-xl border border-border/80 px-4 py-3"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
{logoPath ? (
|
||||
<span className="flex size-10 items-center justify-center overflow-hidden rounded-lg border border-border/60 bg-background">
|
||||
<Image
|
||||
src={logoPath}
|
||||
alt={`Logo ${item.name}`}
|
||||
width={40}
|
||||
height={40}
|
||||
className="h-full w-full object-contain"
|
||||
/>
|
||||
</span>
|
||||
) : (
|
||||
<span className="flex size-10 items-center justify-center rounded-lg bg-muted text-xs font-semibold uppercase text-muted-foreground">
|
||||
{item.name.slice(0, 2)}
|
||||
</span>
|
||||
)}
|
||||
<CardContent className="space-y-3 pt-2">
|
||||
{items.length === 0 ? (
|
||||
<WidgetEmptyState
|
||||
icon={<RiBankCard2Line className="size-6 text-muted-foreground" />}
|
||||
title="Nenhum lançamento com cartão de crédito"
|
||||
description="Quando houver despesas registradas com cartão, elas aparecerão aqui."
|
||||
/>
|
||||
) : (
|
||||
<ul className="space-y-3">
|
||||
{items.map((item) => {
|
||||
const logoPath = resolveLogoPath(item.logo);
|
||||
return (
|
||||
<li
|
||||
key={item.id}
|
||||
className="flex items-center justify-between gap-3 rounded-xl border border-border/80 px-4 py-3"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
{logoPath ? (
|
||||
<span className="flex size-10 items-center justify-center overflow-hidden rounded-lg border border-border/60 bg-background">
|
||||
<Image
|
||||
src={logoPath}
|
||||
alt={`Logo ${item.name}`}
|
||||
width={40}
|
||||
height={40}
|
||||
className="h-full w-full object-contain"
|
||||
/>
|
||||
</span>
|
||||
) : (
|
||||
<span className="flex size-10 items-center justify-center rounded-lg bg-muted text-xs font-semibold uppercase text-muted-foreground">
|
||||
{item.name.slice(0, 2)}
|
||||
</span>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium text-foreground">
|
||||
{item.name}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Despesas no mês
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<MoneyValues
|
||||
amount={item.amount}
|
||||
className="text-lg font-semibold text-foreground"
|
||||
/>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium text-foreground">
|
||||
{item.name}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Despesas no mês
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<MoneyValues
|
||||
amount={item.amount}
|
||||
className="text-lg font-semibold text-foreground"
|
||||
/>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,107 +1,107 @@
|
||||
"use client";
|
||||
|
||||
import { WidgetEmptyState } from "@/components/widget-empty-state";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import {
|
||||
ChartContainer,
|
||||
ChartTooltip,
|
||||
ChartTooltipContent,
|
||||
} from "@/components/ui/chart";
|
||||
import type { PagadorHistoryPoint } from "@/lib/pagadores/details";
|
||||
import { RiBarChartLine } from "@remixicon/react";
|
||||
import {
|
||||
Bar,
|
||||
BarChart,
|
||||
CartesianGrid,
|
||||
LabelList,
|
||||
type LabelProps,
|
||||
XAxis,
|
||||
Bar,
|
||||
BarChart,
|
||||
CartesianGrid,
|
||||
LabelList,
|
||||
type LabelProps,
|
||||
XAxis,
|
||||
} from "recharts";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import {
|
||||
ChartContainer,
|
||||
ChartTooltip,
|
||||
ChartTooltipContent,
|
||||
} from "@/components/ui/chart";
|
||||
import { WidgetEmptyState } from "@/components/widget-empty-state";
|
||||
import { currencyFormatter } from "@/lib/lancamentos/formatting-helpers";
|
||||
import type { PagadorHistoryPoint } from "@/lib/pagadores/details";
|
||||
|
||||
const chartConfig = {
|
||||
despesas: {
|
||||
label: "Despesas",
|
||||
color: "hsl(356, 72%, 50%)",
|
||||
},
|
||||
despesas: {
|
||||
label: "Despesas",
|
||||
color: "hsl(356, 72%, 50%)",
|
||||
},
|
||||
};
|
||||
|
||||
type PagadorHistoryCardProps = {
|
||||
data: PagadorHistoryPoint[];
|
||||
data: PagadorHistoryPoint[];
|
||||
};
|
||||
|
||||
const ValueLabel = (props: LabelProps) => {
|
||||
const { x, y, value, width } = props;
|
||||
if (typeof x !== "number" || typeof y !== "number" || width === undefined) {
|
||||
return null;
|
||||
}
|
||||
const labelX = x + (Number(width) ?? 0) / 2;
|
||||
const amount =
|
||||
typeof value === "number" ? currencyFormatter.format(value) : value;
|
||||
const labelY = Math.max(y - 6, 12);
|
||||
return (
|
||||
<text
|
||||
x={labelX}
|
||||
y={labelY}
|
||||
fill="currentColor"
|
||||
textAnchor="middle"
|
||||
className="text-[11px] font-semibold text-muted-foreground"
|
||||
>
|
||||
{amount}
|
||||
</text>
|
||||
);
|
||||
const { x, y, value, width } = props;
|
||||
if (typeof x !== "number" || typeof y !== "number" || width === undefined) {
|
||||
return null;
|
||||
}
|
||||
const labelX = x + (Number(width) ?? 0) / 2;
|
||||
const amount =
|
||||
typeof value === "number" ? currencyFormatter.format(value) : value;
|
||||
const labelY = Math.max(y - 6, 12);
|
||||
return (
|
||||
<text
|
||||
x={labelX}
|
||||
y={labelY}
|
||||
fill="currentColor"
|
||||
textAnchor="middle"
|
||||
className="text-[11px] font-semibold text-muted-foreground"
|
||||
>
|
||||
{amount}
|
||||
</text>
|
||||
);
|
||||
};
|
||||
|
||||
export function PagadorHistoryCard({ data }: PagadorHistoryCardProps) {
|
||||
const hasData = data.length > 0;
|
||||
const hasData = data.length > 0;
|
||||
|
||||
return (
|
||||
<Card className="border">
|
||||
<CardHeader className="gap-1.5 pb-3">
|
||||
<CardTitle className="text-lg font-semibold">
|
||||
Evolução (últimos 6 meses)
|
||||
</CardTitle>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Despesas registradas para este pagador ao longo do tempo.
|
||||
</p>
|
||||
</CardHeader>
|
||||
return (
|
||||
<Card className="border">
|
||||
<CardHeader className="gap-1.5 pb-3">
|
||||
<CardTitle className="text-lg font-semibold">
|
||||
Evolução (últimos 6 meses)
|
||||
</CardTitle>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Despesas registradas para este pagador ao longo do tempo.
|
||||
</p>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="pt-0">
|
||||
{hasData ? (
|
||||
<ChartContainer
|
||||
config={chartConfig}
|
||||
className="mx-auto flex h-[210px] w-full max-w-[520px] items-center justify-center aspect-auto"
|
||||
>
|
||||
<BarChart
|
||||
data={data}
|
||||
barCategoryGap={16}
|
||||
margin={{ top: 28, right: 8, left: 8, bottom: 0 }}
|
||||
>
|
||||
<CartesianGrid strokeDasharray="3 3" vertical={false} />
|
||||
<XAxis
|
||||
dataKey="label"
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
tickMargin={8}
|
||||
/>
|
||||
<ChartTooltip content={<ChartTooltipContent />} />
|
||||
<Bar
|
||||
dataKey="despesas"
|
||||
fill="var(--color-despesas)"
|
||||
radius={[6, 6, 0, 0]}
|
||||
>
|
||||
<LabelList dataKey="despesas" content={<ValueLabel />} />
|
||||
</Bar>
|
||||
</BarChart>
|
||||
</ChartContainer>
|
||||
) : (
|
||||
<WidgetEmptyState
|
||||
icon={<RiBarChartLine className="size-6 text-muted-foreground" />}
|
||||
title="Sem dados para exibir"
|
||||
description="Ainda não há movimentações suficientes para gerar este gráfico."
|
||||
/>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
<CardContent className="pt-0">
|
||||
{hasData ? (
|
||||
<ChartContainer
|
||||
config={chartConfig}
|
||||
className="mx-auto flex h-[210px] w-full max-w-[520px] items-center justify-center aspect-auto"
|
||||
>
|
||||
<BarChart
|
||||
data={data}
|
||||
barCategoryGap={16}
|
||||
margin={{ top: 28, right: 8, left: 8, bottom: 0 }}
|
||||
>
|
||||
<CartesianGrid strokeDasharray="3 3" vertical={false} />
|
||||
<XAxis
|
||||
dataKey="label"
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
tickMargin={8}
|
||||
/>
|
||||
<ChartTooltip content={<ChartTooltipContent />} />
|
||||
<Bar
|
||||
dataKey="despesas"
|
||||
fill="var(--color-despesas)"
|
||||
radius={[6, 6, 0, 0]}
|
||||
>
|
||||
<LabelList dataKey="despesas" content={<ValueLabel />} />
|
||||
</Bar>
|
||||
</BarChart>
|
||||
</ChartContainer>
|
||||
) : (
|
||||
<WidgetEmptyState
|
||||
icon={<RiBarChartLine className="size-6 text-muted-foreground" />}
|
||||
title="Sem dados para exibir"
|
||||
description="Ainda não há movimentações suficientes para gerar este gráfico."
|
||||
/>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,486 +1,485 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
RiBankCard2Line,
|
||||
RiBillLine,
|
||||
RiExchangeDollarLine,
|
||||
RiMailLine,
|
||||
RiMailSendLine,
|
||||
RiUser3Line,
|
||||
RiVerifiedBadgeFill,
|
||||
} from "@remixicon/react";
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { type ReactNode, useMemo, useState, useTransition } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { sendPagadorSummaryAction } from "@/app/(dashboard)/pagadores/[pagadorId]/actions";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { PAGADOR_ROLE_ADMIN } from "@/lib/pagadores/constants";
|
||||
import { getAvatarSrc } from "@/lib/pagadores/utils";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import {
|
||||
RiBankCard2Line,
|
||||
RiBillLine,
|
||||
RiExchangeDollarLine,
|
||||
RiFileList3Line,
|
||||
RiMailLine,
|
||||
RiMailSendLine,
|
||||
RiUser3Line,
|
||||
RiVerifiedBadgeFill,
|
||||
} from "@remixicon/react";
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useMemo, useState, useTransition, type ReactNode } from "react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
type PagadorInfo = {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string | null;
|
||||
avatarUrl: string | null;
|
||||
status: string;
|
||||
note: string | null;
|
||||
role: string | null;
|
||||
isAutoSend: boolean;
|
||||
createdAt: string;
|
||||
lastMailAt: string | null;
|
||||
shareCode: string | null;
|
||||
canEdit: boolean;
|
||||
id: string;
|
||||
name: string;
|
||||
email: string | null;
|
||||
avatarUrl: string | null;
|
||||
status: string;
|
||||
note: string | null;
|
||||
role: string | null;
|
||||
isAutoSend: boolean;
|
||||
createdAt: string;
|
||||
lastMailAt: string | null;
|
||||
shareCode: string | null;
|
||||
canEdit: boolean;
|
||||
};
|
||||
|
||||
type PagadorSummaryPreview = {
|
||||
periodLabel: string;
|
||||
totalExpenses: number;
|
||||
paymentSplits: {
|
||||
card: number;
|
||||
boleto: number;
|
||||
instant: number;
|
||||
};
|
||||
cardUsage: { name: string; amount: number }[];
|
||||
boletoStats: {
|
||||
totalAmount: number;
|
||||
paidAmount: number;
|
||||
pendingAmount: number;
|
||||
paidCount: number;
|
||||
pendingCount: number;
|
||||
};
|
||||
lancamentoCount: number;
|
||||
periodLabel: string;
|
||||
totalExpenses: number;
|
||||
paymentSplits: {
|
||||
card: number;
|
||||
boleto: number;
|
||||
instant: number;
|
||||
};
|
||||
cardUsage: { name: string; amount: number }[];
|
||||
boletoStats: {
|
||||
totalAmount: number;
|
||||
paidAmount: number;
|
||||
pendingAmount: number;
|
||||
paidCount: number;
|
||||
pendingCount: number;
|
||||
};
|
||||
lancamentoCount: number;
|
||||
};
|
||||
|
||||
type PagadorInfoCardProps = {
|
||||
pagador: PagadorInfo;
|
||||
selectedPeriod: string;
|
||||
summary: PagadorSummaryPreview;
|
||||
pagador: PagadorInfo;
|
||||
selectedPeriod: string;
|
||||
summary: PagadorSummaryPreview;
|
||||
};
|
||||
|
||||
export function PagadorInfoCard({
|
||||
pagador,
|
||||
selectedPeriod,
|
||||
summary,
|
||||
pagador,
|
||||
selectedPeriod,
|
||||
summary,
|
||||
}: PagadorInfoCardProps) {
|
||||
const router = useRouter();
|
||||
const [isSending, startTransition] = useTransition();
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
const router = useRouter();
|
||||
const [isSending, startTransition] = useTransition();
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
|
||||
const avatarSrc = getAvatarSrc(pagador.avatarUrl);
|
||||
const createdAtLabel = formatDate(pagador.createdAt);
|
||||
const isAdmin = pagador.role === PAGADOR_ROLE_ADMIN;
|
||||
const avatarSrc = getAvatarSrc(pagador.avatarUrl);
|
||||
const createdAtLabel = formatDate(pagador.createdAt);
|
||||
const isAdmin = pagador.role === PAGADOR_ROLE_ADMIN;
|
||||
|
||||
const lastMailLabel = useMemo(() => {
|
||||
if (!pagador.lastMailAt) {
|
||||
return "Nunca enviado";
|
||||
}
|
||||
const date = new Date(pagador.lastMailAt);
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return "Nunca enviado";
|
||||
}
|
||||
return date.toLocaleString("pt-BR", {
|
||||
dateStyle: "short",
|
||||
timeStyle: "short",
|
||||
});
|
||||
}, [pagador.lastMailAt]);
|
||||
const lastMailLabel = useMemo(() => {
|
||||
if (!pagador.lastMailAt) {
|
||||
return "Nunca enviado";
|
||||
}
|
||||
const date = new Date(pagador.lastMailAt);
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return "Nunca enviado";
|
||||
}
|
||||
return date.toLocaleString("pt-BR", {
|
||||
dateStyle: "short",
|
||||
timeStyle: "short",
|
||||
});
|
||||
}, [pagador.lastMailAt]);
|
||||
|
||||
const disableSend = isSending || !pagador.email || !pagador.canEdit;
|
||||
const disableSend = isSending || !pagador.email || !pagador.canEdit;
|
||||
|
||||
const openConfirmDialog = () => {
|
||||
if (!pagador.email) {
|
||||
toast.error("Cadastre um e-mail para este pagador antes de enviar.");
|
||||
return;
|
||||
}
|
||||
setConfirmOpen(true);
|
||||
};
|
||||
const openConfirmDialog = () => {
|
||||
if (!pagador.email) {
|
||||
toast.error("Cadastre um e-mail para este pagador antes de enviar.");
|
||||
return;
|
||||
}
|
||||
setConfirmOpen(true);
|
||||
};
|
||||
|
||||
const handleSendSummary = () => {
|
||||
if (!pagador.email) {
|
||||
toast.error("Cadastre um e-mail para este pagador antes de enviar.");
|
||||
return;
|
||||
}
|
||||
const handleSendSummary = () => {
|
||||
if (!pagador.email) {
|
||||
toast.error("Cadastre um e-mail para este pagador antes de enviar.");
|
||||
return;
|
||||
}
|
||||
|
||||
startTransition(async () => {
|
||||
const result = await sendPagadorSummaryAction({
|
||||
pagadorId: pagador.id,
|
||||
period: selectedPeriod,
|
||||
});
|
||||
startTransition(async () => {
|
||||
const result = await sendPagadorSummaryAction({
|
||||
pagadorId: pagador.id,
|
||||
period: selectedPeriod,
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
toast.error(result.error);
|
||||
return;
|
||||
}
|
||||
if (!result.success) {
|
||||
toast.error(result.error);
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success(result.message);
|
||||
setConfirmOpen(false);
|
||||
router.refresh();
|
||||
});
|
||||
};
|
||||
toast.success(result.message);
|
||||
setConfirmOpen(false);
|
||||
router.refresh();
|
||||
});
|
||||
};
|
||||
|
||||
const getStatusBadgeVariant = (status: string): "success" | "secondary" => {
|
||||
const normalizedStatus = status.toLowerCase();
|
||||
if (normalizedStatus === "ativo") {
|
||||
return "success";
|
||||
}
|
||||
return "outline";
|
||||
};
|
||||
const getStatusBadgeVariant = (status: string): "success" | "secondary" => {
|
||||
const normalizedStatus = status.toLowerCase();
|
||||
if (normalizedStatus === "ativo") {
|
||||
return "success";
|
||||
}
|
||||
return "outline";
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="border gap-4">
|
||||
<CardHeader className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
|
||||
<div className="flex flex-1 items-start gap-4">
|
||||
<div className="relative flex size-16 shrink-0 items-center justify-center overflow-hidden">
|
||||
<Image
|
||||
src={avatarSrc}
|
||||
alt={`Avatar de ${pagador.name}`}
|
||||
width={64}
|
||||
height={64}
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
return (
|
||||
<Card className="border gap-4">
|
||||
<CardHeader className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
|
||||
<div className="flex flex-1 items-start gap-4">
|
||||
<div className="relative flex size-16 shrink-0 items-center justify-center overflow-hidden">
|
||||
<Image
|
||||
src={avatarSrc}
|
||||
alt={`Avatar de ${pagador.name}`}
|
||||
width={64}
|
||||
height={64}
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-1 flex-col gap-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<CardTitle className="text-xl font-semibold text-foreground">
|
||||
{pagador.name}
|
||||
</CardTitle>
|
||||
{isAdmin ? (
|
||||
<RiVerifiedBadgeFill
|
||||
className="size-4 text-sky-500"
|
||||
aria-hidden
|
||||
/>
|
||||
) : null}
|
||||
{pagador.isAutoSend ? (
|
||||
<RiMailSendLine
|
||||
className="size-4 text-primary"
|
||||
aria-label="Envio automático habilitado"
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
Criado em {createdAtLabel}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-1 flex-col gap-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<CardTitle className="text-xl font-semibold text-foreground">
|
||||
{pagador.name}
|
||||
</CardTitle>
|
||||
{isAdmin ? (
|
||||
<RiVerifiedBadgeFill
|
||||
className="size-4 text-sky-500"
|
||||
aria-hidden
|
||||
/>
|
||||
) : null}
|
||||
{pagador.isAutoSend ? (
|
||||
<RiMailSendLine
|
||||
className="size-4 text-primary"
|
||||
aria-label="Envio automático habilitado"
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
Criado em {createdAtLabel}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex w-full flex-col items-stretch gap-2 lg:w-auto lg:items-end">
|
||||
{pagador.canEdit ? (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
onClick={openConfirmDialog}
|
||||
disabled={disableSend}
|
||||
className="w-full min-w-[180px] lg:w-auto"
|
||||
>
|
||||
{isSending ? "Enviando..." : "Enviar resumo"}
|
||||
</Button>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Último envio: {lastMailLabel}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-xs font-medium text-amber-600">
|
||||
Acesso somente leitura
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<div className="flex w-full flex-col items-stretch gap-2 lg:w-auto lg:items-end">
|
||||
{pagador.canEdit ? (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
onClick={openConfirmDialog}
|
||||
disabled={disableSend}
|
||||
className="w-full min-w-[180px] lg:w-auto"
|
||||
>
|
||||
{isSending ? "Enviando..." : "Enviar resumo"}
|
||||
</Button>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Último envio: {lastMailLabel}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-xs font-medium text-amber-600">
|
||||
Acesso somente leitura
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="grid gap-4 border-t border-dashed border-border/60 pt-6 text-sm sm:grid-cols-2">
|
||||
<InfoItem
|
||||
label="E-mail"
|
||||
value={
|
||||
pagador.email ? (
|
||||
<Link
|
||||
prefetch
|
||||
href={`mailto:${pagador.email}`}
|
||||
className="inline-flex items-center gap-2 text-primary"
|
||||
>
|
||||
<RiMailLine className="size-4" aria-hidden />
|
||||
{pagador.email}
|
||||
</Link>
|
||||
) : (
|
||||
"—"
|
||||
)
|
||||
}
|
||||
/>
|
||||
<InfoItem
|
||||
label="Status"
|
||||
value={
|
||||
<Badge
|
||||
variant={getStatusBadgeVariant(pagador.status)}
|
||||
className="text-xs"
|
||||
>
|
||||
{pagador.status}
|
||||
</Badge>
|
||||
}
|
||||
/>
|
||||
<CardContent className="grid gap-4 border-t border-dashed border-border/60 pt-6 text-sm sm:grid-cols-2">
|
||||
<InfoItem
|
||||
label="E-mail"
|
||||
value={
|
||||
pagador.email ? (
|
||||
<Link
|
||||
prefetch
|
||||
href={`mailto:${pagador.email}`}
|
||||
className="inline-flex items-center gap-2 text-primary"
|
||||
>
|
||||
<RiMailLine className="size-4" aria-hidden />
|
||||
{pagador.email}
|
||||
</Link>
|
||||
) : (
|
||||
"—"
|
||||
)
|
||||
}
|
||||
/>
|
||||
<InfoItem
|
||||
label="Status"
|
||||
value={
|
||||
<Badge
|
||||
variant={getStatusBadgeVariant(pagador.status)}
|
||||
className="text-xs"
|
||||
>
|
||||
{pagador.status}
|
||||
</Badge>
|
||||
}
|
||||
/>
|
||||
|
||||
<InfoItem
|
||||
label="Papel"
|
||||
value={
|
||||
<span className="inline-flex items-center gap-2">
|
||||
<RiUser3Line className="size-4 text-muted-foreground" />
|
||||
{resolveRoleLabel(pagador.role)}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<InfoItem
|
||||
label="Envio automático"
|
||||
value={pagador.isAutoSend ? "Ativado" : "Desativado"}
|
||||
/>
|
||||
{!pagador.email ? (
|
||||
<InfoItem
|
||||
label="Aviso"
|
||||
value={
|
||||
<span className="text-[13px] text-amber-700">
|
||||
Cadastre um e-mail para permitir o envio automático.
|
||||
</span>
|
||||
}
|
||||
className="sm:col-span-2"
|
||||
/>
|
||||
) : null}
|
||||
<InfoItem
|
||||
label="Observações"
|
||||
value={
|
||||
pagador.note ? (
|
||||
<span className="text-muted-foreground">{pagador.note}</span>
|
||||
) : (
|
||||
"—"
|
||||
)
|
||||
}
|
||||
className="sm:col-span-2"
|
||||
/>
|
||||
</CardContent>
|
||||
<InfoItem
|
||||
label="Papel"
|
||||
value={
|
||||
<span className="inline-flex items-center gap-2">
|
||||
<RiUser3Line className="size-4 text-muted-foreground" />
|
||||
{resolveRoleLabel(pagador.role)}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<InfoItem
|
||||
label="Envio automático"
|
||||
value={pagador.isAutoSend ? "Ativado" : "Desativado"}
|
||||
/>
|
||||
{!pagador.email ? (
|
||||
<InfoItem
|
||||
label="Aviso"
|
||||
value={
|
||||
<span className="text-[13px] text-amber-700">
|
||||
Cadastre um e-mail para permitir o envio automático.
|
||||
</span>
|
||||
}
|
||||
className="sm:col-span-2"
|
||||
/>
|
||||
) : null}
|
||||
<InfoItem
|
||||
label="Observações"
|
||||
value={
|
||||
pagador.note ? (
|
||||
<span className="text-muted-foreground">{pagador.note}</span>
|
||||
) : (
|
||||
"—"
|
||||
)
|
||||
}
|
||||
className="sm:col-span-2"
|
||||
/>
|
||||
</CardContent>
|
||||
|
||||
{pagador.canEdit ? (
|
||||
<Dialog
|
||||
open={confirmOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (isSending) return;
|
||||
setConfirmOpen(open);
|
||||
}}
|
||||
>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Confirmar envio do resumo</DialogTitle>
|
||||
<DialogDescription>
|
||||
Resumo de{" "}
|
||||
<span className="font-semibold text-foreground">
|
||||
{summary.periodLabel}
|
||||
</span>{" "}
|
||||
para{" "}
|
||||
<span className="font-medium text-foreground">
|
||||
{pagador.email}
|
||||
</span>
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{pagador.canEdit ? (
|
||||
<Dialog
|
||||
open={confirmOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (isSending) return;
|
||||
setConfirmOpen(open);
|
||||
}}
|
||||
>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Confirmar envio do resumo</DialogTitle>
|
||||
<DialogDescription>
|
||||
Resumo de{" "}
|
||||
<span className="font-semibold text-foreground">
|
||||
{summary.periodLabel}
|
||||
</span>{" "}
|
||||
para{" "}
|
||||
<span className="font-medium text-foreground">
|
||||
{pagador.email}
|
||||
</span>
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* Total Geral */}
|
||||
<div className="rounded-lg border bg-muted/30 p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex size-10 items-center justify-center rounded-full bg-primary/10">
|
||||
<RiExchangeDollarLine className="size-5 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-muted-foreground">
|
||||
Total de Despesas
|
||||
</p>
|
||||
<p className="text-2xl font-bold text-foreground">
|
||||
{formatCurrency(summary.totalExpenses)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{summary.lancamentoCount} lançamentos
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-4">
|
||||
{/* Total Geral */}
|
||||
<div className="rounded-lg border bg-muted/30 p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex size-10 items-center justify-center rounded-full bg-primary/10">
|
||||
<RiExchangeDollarLine className="size-5 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-muted-foreground">
|
||||
Total de Despesas
|
||||
</p>
|
||||
<p className="text-2xl font-bold text-foreground">
|
||||
{formatCurrency(summary.totalExpenses)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{summary.lancamentoCount} lançamentos
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Grid de Formas de Pagamento */}
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
{/* Cartões */}
|
||||
<div className="rounded-lg border bg-background p-3">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-2">
|
||||
<RiBankCard2Line className="size-4" />
|
||||
<span className="text-xs font-semibold uppercase">
|
||||
Cartões
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-lg font-bold text-foreground">
|
||||
{formatCurrency(summary.paymentSplits.card)}
|
||||
</p>
|
||||
</div>
|
||||
{/* Grid de Formas de Pagamento */}
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
{/* Cartões */}
|
||||
<div className="rounded-lg border bg-background p-3">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-2">
|
||||
<RiBankCard2Line className="size-4" />
|
||||
<span className="text-xs font-semibold uppercase">
|
||||
Cartões
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-lg font-bold text-foreground">
|
||||
{formatCurrency(summary.paymentSplits.card)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Boletos */}
|
||||
<div className="rounded-lg border bg-background p-3">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-2">
|
||||
<RiBillLine className="size-4" />
|
||||
<span className="text-xs font-semibold uppercase">
|
||||
Boletos
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-lg font-bold text-foreground">
|
||||
{formatCurrency(summary.paymentSplits.boleto)}
|
||||
</p>
|
||||
</div>
|
||||
{/* Boletos */}
|
||||
<div className="rounded-lg border bg-background p-3">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-2">
|
||||
<RiBillLine className="size-4" />
|
||||
<span className="text-xs font-semibold uppercase">
|
||||
Boletos
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-lg font-bold text-foreground">
|
||||
{formatCurrency(summary.paymentSplits.boleto)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Instantâneo */}
|
||||
<div className="rounded-lg border bg-background p-3">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-2">
|
||||
<RiExchangeDollarLine className="size-4" />
|
||||
<span className="text-xs font-semibold uppercase">
|
||||
Pix/Débito
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-lg font-bold text-foreground">
|
||||
{formatCurrency(summary.paymentSplits.instant)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{/* Instantâneo */}
|
||||
<div className="rounded-lg border bg-background p-3">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-2">
|
||||
<RiExchangeDollarLine className="size-4" />
|
||||
<span className="text-xs font-semibold uppercase">
|
||||
Pix/Débito
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-lg font-bold text-foreground">
|
||||
{formatCurrency(summary.paymentSplits.instant)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Detalhes Adicionais */}
|
||||
<div className="space-y-3">
|
||||
{/* Cartões Utilizados */}
|
||||
{summary.cardUsage.length > 0 && (
|
||||
<div className="rounded-lg border bg-muted/20 p-3">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<RiBankCard2Line className="size-4 text-muted-foreground" />
|
||||
<span className="text-xs font-semibold uppercase text-muted-foreground">
|
||||
Cartões Utilizados
|
||||
</span>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
{summary.cardUsage.map((card, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-center justify-between text-sm"
|
||||
>
|
||||
<span className="text-foreground">{card.name}</span>
|
||||
<span className="font-medium text-foreground">
|
||||
{formatCurrency(card.amount)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{/* Detalhes Adicionais */}
|
||||
<div className="space-y-3">
|
||||
{/* Cartões Utilizados */}
|
||||
{summary.cardUsage.length > 0 && (
|
||||
<div className="rounded-lg border bg-muted/20 p-3">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<RiBankCard2Line className="size-4 text-muted-foreground" />
|
||||
<span className="text-xs font-semibold uppercase text-muted-foreground">
|
||||
Cartões Utilizados
|
||||
</span>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
{summary.cardUsage.map((card, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-center justify-between text-sm"
|
||||
>
|
||||
<span className="text-foreground">{card.name}</span>
|
||||
<span className="font-medium text-foreground">
|
||||
{formatCurrency(card.amount)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Status de Boletos */}
|
||||
{(summary.boletoStats.paidCount > 0 ||
|
||||
summary.boletoStats.pendingCount > 0) && (
|
||||
<div className="rounded-lg border bg-muted/20 p-3">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<RiBillLine className="size-4 text-muted-foreground" />
|
||||
<span className="text-xs font-semibold uppercase text-muted-foreground">
|
||||
Status de Boletos
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground">Pagos</p>
|
||||
<p className="text-sm font-semibold text-green-600">
|
||||
{formatCurrency(summary.boletoStats.paidAmount)}{" "}
|
||||
<span className="text-xs font-normal">
|
||||
({summary.boletoStats.paidCount})
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Pendentes
|
||||
</p>
|
||||
<p className="text-sm font-semibold text-amber-600">
|
||||
{formatCurrency(summary.boletoStats.pendingAmount)}{" "}
|
||||
<span className="text-xs font-normal">
|
||||
({summary.boletoStats.pendingCount})
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{/* Status de Boletos */}
|
||||
{(summary.boletoStats.paidCount > 0 ||
|
||||
summary.boletoStats.pendingCount > 0) && (
|
||||
<div className="rounded-lg border bg-muted/20 p-3">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<RiBillLine className="size-4 text-muted-foreground" />
|
||||
<span className="text-xs font-semibold uppercase text-muted-foreground">
|
||||
Status de Boletos
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground">Pagos</p>
|
||||
<p className="text-sm font-semibold text-green-600">
|
||||
{formatCurrency(summary.boletoStats.paidAmount)}{" "}
|
||||
<span className="text-xs font-normal">
|
||||
({summary.boletoStats.paidCount})
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Pendentes
|
||||
</p>
|
||||
<p className="text-sm font-semibold text-amber-600">
|
||||
{formatCurrency(summary.boletoStats.pendingAmount)}{" "}
|
||||
<span className="text-xs font-normal">
|
||||
({summary.boletoStats.pendingCount})
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={isSending}
|
||||
onClick={() => setConfirmOpen(false)}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleSendSummary}
|
||||
disabled={disableSend}
|
||||
>
|
||||
{isSending ? "Enviando..." : "Confirmar envio"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
) : null}
|
||||
</Card>
|
||||
);
|
||||
<DialogFooter className="gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={isSending}
|
||||
onClick={() => setConfirmOpen(false)}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleSendSummary}
|
||||
disabled={disableSend}
|
||||
>
|
||||
{isSending ? "Enviando..." : "Confirmar envio"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
) : null}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
const formatDate = (value: string) => {
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return "—";
|
||||
return date.toLocaleDateString("pt-BR", {
|
||||
day: "2-digit",
|
||||
month: "long",
|
||||
year: "numeric",
|
||||
});
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return "—";
|
||||
return date.toLocaleDateString("pt-BR", {
|
||||
day: "2-digit",
|
||||
month: "long",
|
||||
year: "numeric",
|
||||
});
|
||||
};
|
||||
|
||||
const resolveRoleLabel = (role: string | null) => {
|
||||
if (role === PAGADOR_ROLE_ADMIN) return "Administrador";
|
||||
return "Pagador";
|
||||
if (role === PAGADOR_ROLE_ADMIN) return "Administrador";
|
||||
return "Pagador";
|
||||
};
|
||||
|
||||
const formatCurrency = (value: number) =>
|
||||
value.toLocaleString("pt-BR", {
|
||||
style: "currency",
|
||||
currency: "BRL",
|
||||
maximumFractionDigits: 2,
|
||||
});
|
||||
value.toLocaleString("pt-BR", {
|
||||
style: "currency",
|
||||
currency: "BRL",
|
||||
maximumFractionDigits: 2,
|
||||
});
|
||||
|
||||
type InfoItemProps = {
|
||||
label: string;
|
||||
value: ReactNode;
|
||||
className?: string;
|
||||
label: string;
|
||||
value: ReactNode;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
function InfoItem({ label, value, className }: InfoItemProps) {
|
||||
return (
|
||||
<div className={cn("space-y-1", className)}>
|
||||
<span className="text-xs font-semibold uppercase tracking-wide text-muted-foreground/80">
|
||||
{label}
|
||||
</span>
|
||||
<div className="text-base text-foreground">{value}</div>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div className={cn("space-y-1", className)}>
|
||||
<span className="text-xs font-semibold uppercase tracking-wide text-muted-foreground/80">
|
||||
{label}
|
||||
</span>
|
||||
<div className="text-base text-foreground">{value}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,114 +1,114 @@
|
||||
"use client";
|
||||
|
||||
import { deletePagadorShareAction } from "@/app/(dashboard)/pagadores/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { RiLogoutBoxLine } from "@remixicon/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState, useTransition } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { deletePagadorShareAction } from "@/app/(dashboard)/pagadores/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
|
||||
interface PagadorLeaveShareCardProps {
|
||||
shareId: string;
|
||||
pagadorName: string;
|
||||
createdAt: string;
|
||||
shareId: string;
|
||||
pagadorName: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export function PagadorLeaveShareCard({
|
||||
shareId,
|
||||
pagadorName,
|
||||
createdAt,
|
||||
shareId,
|
||||
pagadorName,
|
||||
createdAt,
|
||||
}: PagadorLeaveShareCardProps) {
|
||||
const router = useRouter();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [showConfirm, setShowConfirm] = useState(false);
|
||||
const router = useRouter();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [showConfirm, setShowConfirm] = useState(false);
|
||||
|
||||
const handleLeave = () => {
|
||||
startTransition(async () => {
|
||||
const result = await deletePagadorShareAction({ shareId });
|
||||
const handleLeave = () => {
|
||||
startTransition(async () => {
|
||||
const result = await deletePagadorShareAction({ shareId });
|
||||
|
||||
if (!result.success) {
|
||||
toast.error(result.error);
|
||||
return;
|
||||
}
|
||||
if (!result.success) {
|
||||
toast.error(result.error);
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success("Você saiu do compartilhamento.");
|
||||
router.push("/pagadores");
|
||||
});
|
||||
};
|
||||
toast.success("Você saiu do compartilhamento.");
|
||||
router.push("/pagadores");
|
||||
});
|
||||
};
|
||||
|
||||
const formattedDate = new Date(createdAt).toLocaleDateString("pt-BR", {
|
||||
day: "2-digit",
|
||||
month: "long",
|
||||
year: "numeric",
|
||||
});
|
||||
const formattedDate = new Date(createdAt).toLocaleDateString("pt-BR", {
|
||||
day: "2-digit",
|
||||
month: "long",
|
||||
year: "numeric",
|
||||
});
|
||||
|
||||
return (
|
||||
<Card className="border">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base font-semibold">
|
||||
Acesso Compartilhado
|
||||
</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Você tem acesso somente leitura aos dados de{" "}
|
||||
<strong>{pagadorName}</strong>.
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex flex-col gap-2 rounded-lg border border-dashed p-4 text-sm">
|
||||
<span className="text-xs font-semibold uppercase text-muted-foreground/80">
|
||||
Informações do compartilhamento
|
||||
</span>
|
||||
<div className="flex flex-col gap-1">
|
||||
<p className="text-sm">
|
||||
<span className="text-muted-foreground">Acesso desde:</span>{" "}
|
||||
<strong>{formattedDate}</strong>
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Você pode visualizar os lançamentos, mas não pode criar ou editar.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
return (
|
||||
<Card className="border">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base font-semibold">
|
||||
Acesso Compartilhado
|
||||
</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Você tem acesso somente leitura aos dados de{" "}
|
||||
<strong>{pagadorName}</strong>.
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex flex-col gap-2 rounded-lg border border-dashed p-4 text-sm">
|
||||
<span className="text-xs font-semibold uppercase text-muted-foreground/80">
|
||||
Informações do compartilhamento
|
||||
</span>
|
||||
<div className="flex flex-col gap-1">
|
||||
<p className="text-sm">
|
||||
<span className="text-muted-foreground">Acesso desde:</span>{" "}
|
||||
<strong>{formattedDate}</strong>
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Você pode visualizar os lançamentos, mas não pode criar ou editar.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!showConfirm ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setShowConfirm(true)}
|
||||
className="w-full"
|
||||
>
|
||||
<RiLogoutBoxLine className="size-4" />
|
||||
Sair do compartilhamento
|
||||
</Button>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium text-destructive">
|
||||
Tem certeza que deseja sair? Você perderá o acesso aos dados de{" "}
|
||||
{pagadorName}.
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setShowConfirm(false)}
|
||||
disabled={isPending}
|
||||
className="flex-1"
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
onClick={handleLeave}
|
||||
disabled={isPending}
|
||||
className="flex-1"
|
||||
>
|
||||
{isPending ? "Saindo..." : "Confirmar saída"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
{!showConfirm ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setShowConfirm(true)}
|
||||
className="w-full"
|
||||
>
|
||||
<RiLogoutBoxLine className="size-4" />
|
||||
Sair do compartilhamento
|
||||
</Button>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium text-destructive">
|
||||
Tem certeza que deseja sair? Você perderá o acesso aos dados de{" "}
|
||||
{pagadorName}.
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setShowConfirm(false)}
|
||||
disabled={isPending}
|
||||
className="flex-1"
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
onClick={handleLeave}
|
||||
disabled={isPending}
|
||||
className="flex-1"
|
||||
>
|
||||
{isPending ? "Saindo..." : "Confirmar saída"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,119 +1,119 @@
|
||||
import type { CSSProperties } from "react";
|
||||
import MoneyValues from "@/components/money-values";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import type { PagadorMonthlyBreakdown } from "@/lib/pagadores/details";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import type { CSSProperties } from "react";
|
||||
|
||||
const segmentConfig = {
|
||||
card: {
|
||||
label: "Cartões",
|
||||
color: "bg-violet-500",
|
||||
},
|
||||
boleto: {
|
||||
label: "Boletos",
|
||||
color: "bg-amber-500",
|
||||
},
|
||||
instant: {
|
||||
label: "Pix/Débito/Dinheiro",
|
||||
color: "bg-emerald-500",
|
||||
},
|
||||
card: {
|
||||
label: "Cartões",
|
||||
color: "bg-violet-500",
|
||||
},
|
||||
boleto: {
|
||||
label: "Boletos",
|
||||
color: "bg-amber-500",
|
||||
},
|
||||
instant: {
|
||||
label: "Pix/Débito/Dinheiro",
|
||||
color: "bg-emerald-500",
|
||||
},
|
||||
} as const;
|
||||
|
||||
type PagadorMonthlySummaryCardProps = {
|
||||
periodLabel: string;
|
||||
breakdown: PagadorMonthlyBreakdown;
|
||||
periodLabel: string;
|
||||
breakdown: PagadorMonthlyBreakdown;
|
||||
};
|
||||
|
||||
export function PagadorMonthlySummaryCard({
|
||||
periodLabel,
|
||||
breakdown,
|
||||
periodLabel,
|
||||
breakdown,
|
||||
}: PagadorMonthlySummaryCardProps) {
|
||||
const splittableEntries = (
|
||||
Object.keys(segmentConfig) as Array<keyof typeof segmentConfig>
|
||||
).map((key) => ({
|
||||
key,
|
||||
...segmentConfig[key],
|
||||
value: breakdown.paymentSplits[key],
|
||||
}));
|
||||
const splittableEntries = (
|
||||
Object.keys(segmentConfig) as Array<keyof typeof segmentConfig>
|
||||
).map((key) => ({
|
||||
key,
|
||||
...segmentConfig[key],
|
||||
value: breakdown.paymentSplits[key],
|
||||
}));
|
||||
|
||||
const totalBase = splittableEntries.reduce(
|
||||
(sum, entry) => sum + entry.value,
|
||||
0
|
||||
);
|
||||
const totalBase = splittableEntries.reduce(
|
||||
(sum, entry) => sum + entry.value,
|
||||
0,
|
||||
);
|
||||
|
||||
let offset = 0;
|
||||
let offset = 0;
|
||||
|
||||
return (
|
||||
<Card className="border">
|
||||
<CardHeader className="flex flex-col gap-1.5 pb-4">
|
||||
<CardTitle className="text-lg font-semibold">Totais do mês</CardTitle>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{periodLabel} - despesas por forma de pagamento
|
||||
</p>
|
||||
</CardHeader>
|
||||
return (
|
||||
<Card className="border">
|
||||
<CardHeader className="flex flex-col gap-1.5 pb-4">
|
||||
<CardTitle className="text-lg font-semibold">Totais do mês</CardTitle>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{periodLabel} - despesas por forma de pagamento
|
||||
</p>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-4 pt-0">
|
||||
<div className="space-y-2">
|
||||
<div>
|
||||
<span className="text-[11px] uppercase tracking-wide text-muted-foreground">
|
||||
Total gasto no mês
|
||||
</span>
|
||||
<MoneyValues
|
||||
amount={breakdown.totalExpenses}
|
||||
className="block text-2xl font-semibold text-foreground"
|
||||
/>
|
||||
</div>
|
||||
<CardContent className="space-y-4 pt-0">
|
||||
<div className="space-y-2">
|
||||
<div>
|
||||
<span className="text-[11px] uppercase tracking-wide text-muted-foreground">
|
||||
Total gasto no mês
|
||||
</span>
|
||||
<MoneyValues
|
||||
amount={breakdown.totalExpenses}
|
||||
className="block text-2xl font-semibold text-foreground"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="relative h-1.5 w-full overflow-hidden rounded-full bg-muted">
|
||||
{splittableEntries.map((entry) => {
|
||||
const percent =
|
||||
totalBase > 0
|
||||
? Math.max((entry.value / totalBase) * 100, 0)
|
||||
: 0;
|
||||
const style: CSSProperties = {
|
||||
width: `${percent}%`,
|
||||
left: `${offset}%`,
|
||||
};
|
||||
offset += percent;
|
||||
return (
|
||||
<span
|
||||
key={entry.key}
|
||||
className={cn(
|
||||
"absolute inset-y-0 rounded-full transition-all",
|
||||
entry.color
|
||||
)}
|
||||
style={style}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative h-1.5 w-full overflow-hidden rounded-full bg-muted">
|
||||
{splittableEntries.map((entry) => {
|
||||
const percent =
|
||||
totalBase > 0
|
||||
? Math.max((entry.value / totalBase) * 100, 0)
|
||||
: 0;
|
||||
const style: CSSProperties = {
|
||||
width: `${percent}%`,
|
||||
left: `${offset}%`,
|
||||
};
|
||||
offset += percent;
|
||||
return (
|
||||
<span
|
||||
key={entry.key}
|
||||
className={cn(
|
||||
"absolute inset-y-0 rounded-full transition-all",
|
||||
entry.color,
|
||||
)}
|
||||
style={style}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
{splittableEntries.map((entry) => {
|
||||
const percent =
|
||||
totalBase > 0 ? Math.round((entry.value / totalBase) * 100) : 0;
|
||||
return (
|
||||
<div key={entry.key} className="space-y-1 rounded-lg border p-3">
|
||||
<span className="flex items-center gap-2 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground/70">
|
||||
<span
|
||||
className={cn("size-2 rounded-full", entry.color)}
|
||||
aria-hidden
|
||||
/>
|
||||
{entry.label}
|
||||
</span>
|
||||
<MoneyValues
|
||||
amount={entry.value}
|
||||
className="block text-lg font-semibold text-foreground"
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{percent}% das despesas
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
{splittableEntries.map((entry) => {
|
||||
const percent =
|
||||
totalBase > 0 ? Math.round((entry.value / totalBase) * 100) : 0;
|
||||
return (
|
||||
<div key={entry.key} className="space-y-1 rounded-lg border p-3">
|
||||
<span className="flex items-center gap-2 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground/70">
|
||||
<span
|
||||
className={cn("size-2 rounded-full", entry.color)}
|
||||
aria-hidden
|
||||
/>
|
||||
{entry.label}
|
||||
</span>
|
||||
<MoneyValues
|
||||
amount={entry.value}
|
||||
className="block text-lg font-semibold text-foreground"
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{percent}% das despesas
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,106 +1,106 @@
|
||||
import { RiBarcodeLine } from "@remixicon/react";
|
||||
import MoneyValues from "@/components/money-values";
|
||||
import { WidgetEmptyState } from "@/components/widget-empty-state";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { WidgetEmptyState } from "@/components/widget-empty-state";
|
||||
import type { PagadorBoletoStats } from "@/lib/pagadores/details";
|
||||
import { cn } from "@/lib/utils/ui";
|
||||
import { RiBarcodeLine } from "@remixicon/react";
|
||||
|
||||
type PagadorBoletoCardProps = {
|
||||
stats: PagadorBoletoStats;
|
||||
stats: PagadorBoletoStats;
|
||||
};
|
||||
|
||||
export function PagadorBoletoCard({ stats }: PagadorBoletoCardProps) {
|
||||
const total = stats.totalAmount;
|
||||
const paidPercent =
|
||||
total > 0 ? Math.round((stats.paidAmount / total) * 100) : 0;
|
||||
const pendingPercent =
|
||||
total > 0 ? Math.round((stats.pendingAmount / total) * 100) : 0;
|
||||
const total = stats.totalAmount;
|
||||
const paidPercent =
|
||||
total > 0 ? Math.round((stats.paidAmount / total) * 100) : 0;
|
||||
const pendingPercent =
|
||||
total > 0 ? Math.round((stats.pendingAmount / total) * 100) : 0;
|
||||
|
||||
return (
|
||||
<Card className="border">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-xl font-semibold">Boletos</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Totais por status considerando o período atual.
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4 pt-2">
|
||||
{total === 0 ? (
|
||||
<WidgetEmptyState
|
||||
icon={<RiBarcodeLine className="size-6 text-muted-foreground" />}
|
||||
title="Nenhum lançamento com boleto"
|
||||
description="Quando houver despesas registradas com boleto, elas aparecerão aqui."
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<div>
|
||||
<span className="text-xs uppercase tracking-wide text-muted-foreground">
|
||||
Total de boletos
|
||||
</span>
|
||||
<MoneyValues
|
||||
amount={total}
|
||||
className="block text-2xl font-semibold text-foreground"
|
||||
/>
|
||||
</div>
|
||||
return (
|
||||
<Card className="border">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-xl font-semibold">Boletos</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Totais por status considerando o período atual.
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4 pt-2">
|
||||
{total === 0 ? (
|
||||
<WidgetEmptyState
|
||||
icon={<RiBarcodeLine className="size-6 text-muted-foreground" />}
|
||||
title="Nenhum lançamento com boleto"
|
||||
description="Quando houver despesas registradas com boleto, elas aparecerão aqui."
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<div>
|
||||
<span className="text-xs uppercase tracking-wide text-muted-foreground">
|
||||
Total de boletos
|
||||
</span>
|
||||
<MoneyValues
|
||||
amount={total}
|
||||
className="block text-2xl font-semibold text-foreground"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 rounded-xl border border-dashed p-3">
|
||||
<StatusRow
|
||||
label="Pagos"
|
||||
amount={stats.paidAmount}
|
||||
count={stats.paidCount}
|
||||
percent={paidPercent}
|
||||
tone="success"
|
||||
/>
|
||||
<StatusRow
|
||||
label="Pendentes"
|
||||
amount={stats.pendingAmount}
|
||||
count={stats.pendingCount}
|
||||
percent={pendingPercent}
|
||||
tone="warning"
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
<div className="space-y-2 rounded-xl border border-dashed p-3">
|
||||
<StatusRow
|
||||
label="Pagos"
|
||||
amount={stats.paidAmount}
|
||||
count={stats.paidCount}
|
||||
percent={paidPercent}
|
||||
tone="success"
|
||||
/>
|
||||
<StatusRow
|
||||
label="Pendentes"
|
||||
amount={stats.pendingAmount}
|
||||
count={stats.pendingCount}
|
||||
percent={pendingPercent}
|
||||
tone="warning"
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
type StatusRowProps = {
|
||||
label: string;
|
||||
amount: number;
|
||||
count: number;
|
||||
percent: number;
|
||||
tone: "success" | "warning";
|
||||
label: string;
|
||||
amount: number;
|
||||
count: number;
|
||||
percent: number;
|
||||
tone: "success" | "warning";
|
||||
};
|
||||
|
||||
function StatusRow({ label, amount, count, percent, tone }: StatusRowProps) {
|
||||
const clampedPercent = Math.min(Math.max(percent, 0), 100);
|
||||
return (
|
||||
<div className="space-y-1 rounded-lg bg-muted/40 p-3">
|
||||
<div className="flex items-center justify-between text-sm font-semibold">
|
||||
<span>{label}</span>
|
||||
<span className="text-muted-foreground">{count} registros</span>
|
||||
</div>
|
||||
<MoneyValues
|
||||
amount={amount}
|
||||
className={cn(
|
||||
"text-xl font-semibold",
|
||||
tone === "success" ? "text-emerald-600" : "text-amber-600"
|
||||
)}
|
||||
/>
|
||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span>{clampedPercent}% do total</span>
|
||||
<div className="h-1.5 w-1/2 rounded-full bg-border/80">
|
||||
<div
|
||||
className={cn(
|
||||
"h-full rounded-full",
|
||||
tone === "success" ? "bg-emerald-500" : "bg-amber-500"
|
||||
)}
|
||||
style={{ width: `${clampedPercent}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
const clampedPercent = Math.min(Math.max(percent, 0), 100);
|
||||
return (
|
||||
<div className="space-y-1 rounded-lg bg-muted/40 p-3">
|
||||
<div className="flex items-center justify-between text-sm font-semibold">
|
||||
<span>{label}</span>
|
||||
<span className="text-muted-foreground">{count} registros</span>
|
||||
</div>
|
||||
<MoneyValues
|
||||
amount={amount}
|
||||
className={cn(
|
||||
"text-xl font-semibold",
|
||||
tone === "success" ? "text-emerald-600" : "text-amber-600",
|
||||
)}
|
||||
/>
|
||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span>{clampedPercent}% do total</span>
|
||||
<div className="h-1.5 w-1/2 rounded-full bg-border/80">
|
||||
<div
|
||||
className={cn(
|
||||
"h-full rounded-full",
|
||||
tone === "success" ? "bg-emerald-500" : "bg-amber-500",
|
||||
)}
|
||||
style={{ width: `${clampedPercent}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,160 +1,160 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
deletePagadorShareAction,
|
||||
regeneratePagadorShareCodeAction,
|
||||
} from "@/app/(dashboard)/pagadores/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { RiDeleteBin5Line } from "@remixicon/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState, useTransition } from "react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
deletePagadorShareAction,
|
||||
regeneratePagadorShareCodeAction,
|
||||
} from "@/app/(dashboard)/pagadores/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
|
||||
type PagadorShare = {
|
||||
id: string;
|
||||
userId: string;
|
||||
name: string;
|
||||
email: string;
|
||||
createdAt: string;
|
||||
id: string;
|
||||
userId: string;
|
||||
name: string;
|
||||
email: string;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
interface PagadorSharingCardProps {
|
||||
pagadorId: string;
|
||||
shareCode: string;
|
||||
shares: PagadorShare[];
|
||||
pagadorId: string;
|
||||
shareCode: string;
|
||||
shares: PagadorShare[];
|
||||
}
|
||||
|
||||
export function PagadorSharingCard({
|
||||
pagadorId,
|
||||
shareCode,
|
||||
shares,
|
||||
pagadorId,
|
||||
shareCode,
|
||||
shares,
|
||||
}: PagadorSharingCardProps) {
|
||||
const router = useRouter();
|
||||
const [currentCode, setCurrentCode] = useState(shareCode);
|
||||
const [regeneratePending, startRegenerate] = useTransition();
|
||||
const [removePendingId, setRemovePendingId] = useState<string | null>(null);
|
||||
const router = useRouter();
|
||||
const [currentCode, setCurrentCode] = useState(shareCode);
|
||||
const [regeneratePending, startRegenerate] = useTransition();
|
||||
const [removePendingId, setRemovePendingId] = useState<string | null>(null);
|
||||
|
||||
const handleCopyCode = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(currentCode);
|
||||
toast.success("Código copiado para a área de transferência.");
|
||||
} catch {
|
||||
toast.error("Não foi possível copiar o código.");
|
||||
}
|
||||
};
|
||||
const handleCopyCode = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(currentCode);
|
||||
toast.success("Código copiado para a área de transferência.");
|
||||
} catch {
|
||||
toast.error("Não foi possível copiar o código.");
|
||||
}
|
||||
};
|
||||
|
||||
const handleRegenerate = () => {
|
||||
startRegenerate(async () => {
|
||||
const result = await regeneratePagadorShareCodeAction({ pagadorId });
|
||||
const handleRegenerate = () => {
|
||||
startRegenerate(async () => {
|
||||
const result = await regeneratePagadorShareCodeAction({ pagadorId });
|
||||
|
||||
if (!result.success) {
|
||||
toast.error(result.error);
|
||||
return;
|
||||
}
|
||||
if (!result.success) {
|
||||
toast.error(result.error);
|
||||
return;
|
||||
}
|
||||
|
||||
setCurrentCode(result.code);
|
||||
toast.success("Novo código gerado com sucesso.");
|
||||
router.refresh();
|
||||
});
|
||||
};
|
||||
setCurrentCode(result.code);
|
||||
toast.success("Novo código gerado com sucesso.");
|
||||
router.refresh();
|
||||
});
|
||||
};
|
||||
|
||||
const handleRemove = (shareId: string) => {
|
||||
setRemovePendingId(shareId);
|
||||
startRegenerate(async () => {
|
||||
const result = await deletePagadorShareAction({ shareId });
|
||||
const handleRemove = (shareId: string) => {
|
||||
setRemovePendingId(shareId);
|
||||
startRegenerate(async () => {
|
||||
const result = await deletePagadorShareAction({ shareId });
|
||||
|
||||
if (!result.success) {
|
||||
toast.error(result.error);
|
||||
setRemovePendingId(null);
|
||||
return;
|
||||
}
|
||||
if (!result.success) {
|
||||
toast.error(result.error);
|
||||
setRemovePendingId(null);
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success(result.message);
|
||||
setRemovePendingId(null);
|
||||
router.refresh();
|
||||
});
|
||||
};
|
||||
toast.success(result.message);
|
||||
setRemovePendingId(null);
|
||||
router.refresh();
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="border">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base font-semibold">
|
||||
Compartilhamentos
|
||||
</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Compartilhe o código abaixo com outra pessoa. Ela poderá adicioná-lo
|
||||
na página de pagadores usando a opção Adicionar por código para ter
|
||||
acesso somente leitura.
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex flex-col gap-2 rounded-lg border border-dashed p-4 text-sm">
|
||||
<span className="text-xs font-semibold uppercase text-muted-foreground/80">
|
||||
Código de compartilhamento
|
||||
</span>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<code className="rounded bg-muted px-2 py-1 text-xs font-mono">
|
||||
{currentCode}
|
||||
</code>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={handleCopyCode}
|
||||
>
|
||||
Copiar
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
onClick={handleRegenerate}
|
||||
disabled={regeneratePending}
|
||||
>
|
||||
{regeneratePending ? "Gerando..." : "Gerar novo código"}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Gerar um novo código não remove acessos existentes, apenas impede
|
||||
que novos convites usem o código anterior.
|
||||
</p>
|
||||
</div>
|
||||
return (
|
||||
<Card className="border">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base font-semibold">
|
||||
Compartilhamentos
|
||||
</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Compartilhe o código abaixo com outra pessoa. Ela poderá adicioná-lo
|
||||
na página de pagadores usando a opção Adicionar por código para ter
|
||||
acesso somente leitura.
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex flex-col gap-2 rounded-lg border border-dashed p-4 text-sm">
|
||||
<span className="text-xs font-semibold uppercase text-muted-foreground/80">
|
||||
Código de compartilhamento
|
||||
</span>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<code className="rounded bg-muted px-2 py-1 text-xs font-mono">
|
||||
{currentCode}
|
||||
</code>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={handleCopyCode}
|
||||
>
|
||||
Copiar
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
onClick={handleRegenerate}
|
||||
disabled={regeneratePending}
|
||||
>
|
||||
{regeneratePending ? "Gerando..." : "Gerar novo código"}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Gerar um novo código não remove acessos existentes, apenas impede
|
||||
que novos convites usem o código anterior.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{shares.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Nenhum usuário com acesso de leitura.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="space-y-3">
|
||||
{shares.map((share) => (
|
||||
<li
|
||||
key={share.id}
|
||||
className="flex items-center justify-between rounded-lg border border-dashed p-4 text-sm"
|
||||
>
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium text-foreground">
|
||||
{share.name}
|
||||
</span>
|
||||
<span className="text-muted-foreground">{share.email}</span>
|
||||
<span className="text-xs text-muted-foreground/80">
|
||||
ID: ****{share.userId.slice(-4)}
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => handleRemove(share.id)}
|
||||
disabled={removePendingId === share.id}
|
||||
>
|
||||
<RiDeleteBin5Line className="size-4" />
|
||||
<span className="sr-only">Remover acesso</span>
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
{shares.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Nenhum usuário com acesso de leitura.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="space-y-3">
|
||||
{shares.map((share) => (
|
||||
<li
|
||||
key={share.id}
|
||||
className="flex items-center justify-between rounded-lg border border-dashed p-4 text-sm"
|
||||
>
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium text-foreground">
|
||||
{share.name}
|
||||
</span>
|
||||
<span className="text-muted-foreground">{share.email}</span>
|
||||
<span className="text-xs text-muted-foreground/80">
|
||||
ID: ****{share.userId.slice(-4)}
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => handleRemove(share.id)}
|
||||
disabled={removePendingId === share.id}
|
||||
>
|
||||
<RiDeleteBin5Line className="size-4" />
|
||||
<span className="sr-only">Remover acesso</span>
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,121 +1,121 @@
|
||||
"use client";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { PAGADOR_ROLE_ADMIN } from "@/lib/pagadores/constants";
|
||||
import { getAvatarSrc } from "@/lib/pagadores/utils";
|
||||
import {
|
||||
RiDeleteBin5Line,
|
||||
RiEyeLine,
|
||||
RiMailSendLine,
|
||||
RiPencilLine,
|
||||
RiVerifiedBadgeFill,
|
||||
RiDeleteBin5Line,
|
||||
RiEyeLine,
|
||||
RiMailSendLine,
|
||||
RiPencilLine,
|
||||
RiVerifiedBadgeFill,
|
||||
} from "@remixicon/react";
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import { useMemo } from "react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { PAGADOR_ROLE_ADMIN } from "@/lib/pagadores/constants";
|
||||
import { getAvatarSrc } from "@/lib/pagadores/utils";
|
||||
import type { Pagador } from "./types";
|
||||
|
||||
interface PagadorCardProps {
|
||||
pagador: Pagador;
|
||||
onEdit?: () => void;
|
||||
onRemove?: () => void;
|
||||
pagador: Pagador;
|
||||
onEdit?: () => void;
|
||||
onRemove?: () => void;
|
||||
}
|
||||
|
||||
export function PagadorCard({ pagador, onEdit, onRemove }: PagadorCardProps) {
|
||||
const avatarSrc = useMemo(
|
||||
() => getAvatarSrc(pagador.avatarUrl),
|
||||
[pagador.avatarUrl]
|
||||
);
|
||||
const avatarSrc = useMemo(
|
||||
() => getAvatarSrc(pagador.avatarUrl),
|
||||
[pagador.avatarUrl],
|
||||
);
|
||||
|
||||
const isAdmin = pagador.role === PAGADOR_ROLE_ADMIN;
|
||||
const isReadOnly = !pagador.canEdit;
|
||||
const isAdmin = pagador.role === PAGADOR_ROLE_ADMIN;
|
||||
const isReadOnly = !pagador.canEdit;
|
||||
|
||||
return (
|
||||
<Card className=" overflow-hidden px-6">
|
||||
{/* Avatar posicionado sobre o header */}
|
||||
<div className="relative flex flex-col items-start">
|
||||
<div className="relative mb-3 flex size-16 items-center justify-center overflow-hidden rounded-full border-background bg-background shadow-lg">
|
||||
<Image
|
||||
src={avatarSrc}
|
||||
alt={`Avatar de ${pagador.name}`}
|
||||
width={80}
|
||||
height={80}
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
return (
|
||||
<Card className=" overflow-hidden px-6">
|
||||
{/* Avatar posicionado sobre o header */}
|
||||
<div className="relative flex flex-col items-start">
|
||||
<div className="relative mb-3 flex size-16 items-center justify-center overflow-hidden rounded-full border-background bg-background shadow-lg">
|
||||
<Image
|
||||
src={avatarSrc}
|
||||
alt={`Avatar de ${pagador.name}`}
|
||||
width={80}
|
||||
height={80}
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Nome e badges */}
|
||||
<div className="flex items-center gap-1.5">
|
||||
<h3 className="text-base font-semibold text-foreground">
|
||||
{pagador.name}
|
||||
</h3>
|
||||
{isAdmin ? (
|
||||
<RiVerifiedBadgeFill className="size-4 text-blue-500" aria-hidden />
|
||||
) : null}
|
||||
{pagador.isAutoSend ? (
|
||||
<RiMailSendLine className="size-4 text-primary" aria-hidden />
|
||||
) : null}
|
||||
</div>
|
||||
{/* Nome e badges */}
|
||||
<div className="flex items-center gap-1.5">
|
||||
<h3 className="text-base font-semibold text-foreground">
|
||||
{pagador.name}
|
||||
</h3>
|
||||
{isAdmin ? (
|
||||
<RiVerifiedBadgeFill className="size-4 text-blue-500" aria-hidden />
|
||||
) : null}
|
||||
{pagador.isAutoSend ? (
|
||||
<RiMailSendLine className="size-4 text-primary" aria-hidden />
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{/* Email */}
|
||||
{pagador.email ? (
|
||||
<p className="mt-1 text-xs text-muted-foreground">{pagador.email}</p>
|
||||
) : (
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Sem Email cadastrado
|
||||
</p>
|
||||
)}
|
||||
{/* Email */}
|
||||
{pagador.email ? (
|
||||
<p className="mt-1 text-xs text-muted-foreground">{pagador.email}</p>
|
||||
) : (
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Sem Email cadastrado
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Status badges */}
|
||||
<div className="mt-2 flex flex-wrap items-center justify-center gap-1.5">
|
||||
<Badge
|
||||
variant={pagador.status === "Ativo" ? "success" : "outline"}
|
||||
className="text-xs"
|
||||
>
|
||||
{pagador.status}
|
||||
</Badge>
|
||||
{/* Status badges */}
|
||||
<div className="mt-2 flex flex-wrap items-center justify-center gap-1.5">
|
||||
<Badge
|
||||
variant={pagador.status === "Ativo" ? "success" : "outline"}
|
||||
className="text-xs"
|
||||
>
|
||||
{pagador.status}
|
||||
</Badge>
|
||||
|
||||
{isReadOnly ? (
|
||||
<Badge variant="outline" className="text-xs text-amber-600">
|
||||
Somente leitura
|
||||
</Badge>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
{isReadOnly ? (
|
||||
<Badge variant="outline" className="text-xs text-amber-600">
|
||||
Somente leitura
|
||||
</Badge>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer com links */}
|
||||
<div className="flex flex-wrap items-start justify-start gap-3 text-sm font-medium">
|
||||
{!isReadOnly && onEdit ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onEdit}
|
||||
className={`text-primary flex items-center gap-1 font-medium transition-opacity hover:opacity-80`}
|
||||
>
|
||||
<RiPencilLine className="size-4" aria-hidden />
|
||||
editar
|
||||
</button>
|
||||
) : null}
|
||||
{/* Footer com links */}
|
||||
<div className="flex flex-wrap items-start justify-start gap-3 text-sm font-medium">
|
||||
{!isReadOnly && onEdit ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onEdit}
|
||||
className={`text-primary flex items-center gap-1 font-medium transition-opacity hover:opacity-80`}
|
||||
>
|
||||
<RiPencilLine className="size-4" aria-hidden />
|
||||
editar
|
||||
</button>
|
||||
) : null}
|
||||
|
||||
<Link
|
||||
href={`/pagadores/${pagador.id}`}
|
||||
className={`text-primary flex items-center gap-1 font-medium transition-opacity hover:opacity-80`}
|
||||
>
|
||||
<RiEyeLine className="size-4" aria-hidden />
|
||||
detalhes
|
||||
</Link>
|
||||
<Link
|
||||
href={`/pagadores/${pagador.id}`}
|
||||
className={`text-primary flex items-center gap-1 font-medium transition-opacity hover:opacity-80`}
|
||||
>
|
||||
<RiEyeLine className="size-4" aria-hidden />
|
||||
detalhes
|
||||
</Link>
|
||||
|
||||
{!isAdmin && !isReadOnly && onRemove ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onRemove}
|
||||
className={`text-destructive flex items-center gap-1 font-medium transition-opacity hover:opacity-80`}
|
||||
>
|
||||
<RiDeleteBin5Line className="size-4" aria-hidden />
|
||||
remover
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
{!isAdmin && !isReadOnly && onRemove ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onRemove}
|
||||
className={`text-destructive flex items-center gap-1 font-medium transition-opacity hover:opacity-80`}
|
||||
>
|
||||
<RiDeleteBin5Line className="size-4" aria-hidden />
|
||||
remover
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,348 +1,347 @@
|
||||
"use client";
|
||||
import { RiCheckLine, RiCloseCircleLine } from "@remixicon/react";
|
||||
import Image from "next/image";
|
||||
import {
|
||||
createPagadorAction,
|
||||
updatePagadorAction,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
useTransition,
|
||||
} from "react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
createPagadorAction,
|
||||
updatePagadorAction,
|
||||
} from "@/app/(dashboard)/pagadores/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
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,
|
||||
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 {
|
||||
DEFAULT_PAGADOR_AVATAR,
|
||||
PAGADOR_STATUS_OPTIONS,
|
||||
type PagadorStatus,
|
||||
DEFAULT_PAGADOR_AVATAR,
|
||||
PAGADOR_STATUS_OPTIONS,
|
||||
type PagadorStatus,
|
||||
} from "@/lib/pagadores/constants";
|
||||
import { RiCheckLine, RiCloseCircleLine } from "@remixicon/react";
|
||||
import Image from "next/image";
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
useTransition,
|
||||
} from "react";
|
||||
import { toast } from "sonner";
|
||||
import { StatusSelectContent } from "./pagador-select-items";
|
||||
|
||||
import { getAvatarSrc } from "@/lib/pagadores/utils";
|
||||
import { StatusSelectContent } from "./pagador-select-items";
|
||||
import type { Pagador, PagadorFormValues } from "./types";
|
||||
|
||||
interface PagadorDialogProps {
|
||||
mode: "create" | "update";
|
||||
trigger?: React.ReactNode;
|
||||
pagador?: Pagador;
|
||||
avatarOptions: string[];
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
mode: "create" | "update";
|
||||
trigger?: React.ReactNode;
|
||||
pagador?: Pagador;
|
||||
avatarOptions: string[];
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
const buildInitialValues = ({
|
||||
pagador,
|
||||
avatarOptions,
|
||||
pagador,
|
||||
avatarOptions,
|
||||
}: {
|
||||
pagador?: Pagador;
|
||||
avatarOptions: string[];
|
||||
pagador?: Pagador;
|
||||
avatarOptions: string[];
|
||||
}): PagadorFormValues => {
|
||||
const defaultAvatar = avatarOptions[0] ?? DEFAULT_PAGADOR_AVATAR;
|
||||
const defaultAvatar = avatarOptions[0] ?? DEFAULT_PAGADOR_AVATAR;
|
||||
|
||||
return {
|
||||
name: pagador?.name ?? "",
|
||||
email: pagador?.email ?? "",
|
||||
status: (pagador?.status as PagadorStatus) ?? PAGADOR_STATUS_OPTIONS[0],
|
||||
avatarUrl: pagador?.avatarUrl ?? defaultAvatar,
|
||||
note: pagador?.note ?? "",
|
||||
isAutoSend: pagador?.isAutoSend ?? false,
|
||||
};
|
||||
return {
|
||||
name: pagador?.name ?? "",
|
||||
email: pagador?.email ?? "",
|
||||
status: (pagador?.status as PagadorStatus) ?? PAGADOR_STATUS_OPTIONS[0],
|
||||
avatarUrl: pagador?.avatarUrl ?? defaultAvatar,
|
||||
note: pagador?.note ?? "",
|
||||
isAutoSend: pagador?.isAutoSend ?? false,
|
||||
};
|
||||
};
|
||||
|
||||
export function PagadorDialog({
|
||||
mode,
|
||||
trigger,
|
||||
pagador,
|
||||
avatarOptions,
|
||||
open,
|
||||
onOpenChange,
|
||||
mode,
|
||||
trigger,
|
||||
pagador,
|
||||
avatarOptions,
|
||||
open,
|
||||
onOpenChange,
|
||||
}: PagadorDialogProps) {
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
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
|
||||
);
|
||||
// Use controlled state hook for dialog open state
|
||||
const [dialogOpen, setDialogOpen] = useControlledState(
|
||||
open,
|
||||
false,
|
||||
onOpenChange,
|
||||
);
|
||||
|
||||
const initialState = useMemo(
|
||||
() => buildInitialValues({ pagador, avatarOptions }),
|
||||
[pagador, avatarOptions]
|
||||
);
|
||||
const initialState = useMemo(
|
||||
() => buildInitialValues({ pagador, avatarOptions }),
|
||||
[pagador, avatarOptions],
|
||||
);
|
||||
|
||||
// Use form state hook for form management
|
||||
const { formState, updateField, setFormState } =
|
||||
useFormState<PagadorFormValues>(initialState);
|
||||
// Use form state hook for form management
|
||||
const { formState, updateField, setFormState } =
|
||||
useFormState<PagadorFormValues>(initialState);
|
||||
|
||||
const availableAvatars = useMemo(() => {
|
||||
const set = new Set<string>();
|
||||
avatarOptions.forEach((avatar) => set.add(avatar));
|
||||
set.add(initialState.avatarUrl);
|
||||
set.add(DEFAULT_PAGADOR_AVATAR);
|
||||
return Array.from(set).sort((a, b) =>
|
||||
a.localeCompare(b, "pt-BR", { sensitivity: "base" })
|
||||
);
|
||||
}, [avatarOptions, initialState.avatarUrl]);
|
||||
const availableAvatars = useMemo(() => {
|
||||
const set = new Set<string>();
|
||||
avatarOptions.forEach((avatar) => set.add(avatar));
|
||||
set.add(initialState.avatarUrl);
|
||||
set.add(DEFAULT_PAGADOR_AVATAR);
|
||||
return Array.from(set).sort((a, b) =>
|
||||
a.localeCompare(b, "pt-BR", { sensitivity: "base" }),
|
||||
);
|
||||
}, [avatarOptions, initialState.avatarUrl]);
|
||||
|
||||
// Reset form when dialog opens
|
||||
useEffect(() => {
|
||||
if (dialogOpen) {
|
||||
setFormState(initialState);
|
||||
setErrorMessage(null);
|
||||
}
|
||||
}, [dialogOpen, initialState, setFormState]);
|
||||
// Reset form when dialog opens
|
||||
useEffect(() => {
|
||||
if (dialogOpen) {
|
||||
setFormState(initialState);
|
||||
setErrorMessage(null);
|
||||
}
|
||||
}, [dialogOpen, initialState, setFormState]);
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
(event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setErrorMessage(null);
|
||||
const handleSubmit = useCallback(
|
||||
(event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setErrorMessage(null);
|
||||
|
||||
if (mode === "update" && !pagador?.id) {
|
||||
const message = "Pagador inválido.";
|
||||
setErrorMessage(message);
|
||||
toast.error(message);
|
||||
return;
|
||||
}
|
||||
if (mode === "update" && !pagador?.id) {
|
||||
const message = "Pagador inválido.";
|
||||
setErrorMessage(message);
|
||||
toast.error(message);
|
||||
return;
|
||||
}
|
||||
|
||||
const payload: {
|
||||
name: string;
|
||||
email?: string;
|
||||
status: PagadorStatus;
|
||||
avatarUrl: string;
|
||||
note: string;
|
||||
isAutoSend: boolean;
|
||||
} = {
|
||||
name: formState.name.trim(),
|
||||
status: formState.status,
|
||||
avatarUrl: formState.avatarUrl,
|
||||
note: formState.note.trim(),
|
||||
isAutoSend: formState.isAutoSend,
|
||||
};
|
||||
const payload: {
|
||||
name: string;
|
||||
email?: string;
|
||||
status: PagadorStatus;
|
||||
avatarUrl: string;
|
||||
note: string;
|
||||
isAutoSend: boolean;
|
||||
} = {
|
||||
name: formState.name.trim(),
|
||||
status: formState.status,
|
||||
avatarUrl: formState.avatarUrl,
|
||||
note: formState.note.trim(),
|
||||
isAutoSend: formState.isAutoSend,
|
||||
};
|
||||
|
||||
const emailValue = formState.email.trim();
|
||||
if (emailValue.length > 0) {
|
||||
payload.email = emailValue;
|
||||
}
|
||||
const emailValue = formState.email.trim();
|
||||
if (emailValue.length > 0) {
|
||||
payload.email = emailValue;
|
||||
}
|
||||
|
||||
startTransition(async () => {
|
||||
const result =
|
||||
mode === "create"
|
||||
? await createPagadorAction(payload)
|
||||
: await updatePagadorAction({
|
||||
id: pagador?.id ?? "",
|
||||
...payload,
|
||||
});
|
||||
startTransition(async () => {
|
||||
const result =
|
||||
mode === "create"
|
||||
? await createPagadorAction(payload)
|
||||
: await updatePagadorAction({
|
||||
id: pagador?.id ?? "",
|
||||
...payload,
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
setDialogOpen(false);
|
||||
setFormState(initialState);
|
||||
return;
|
||||
}
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
setDialogOpen(false);
|
||||
setFormState(initialState);
|
||||
return;
|
||||
}
|
||||
|
||||
setErrorMessage(result.error);
|
||||
toast.error(result.error);
|
||||
});
|
||||
},
|
||||
[formState, initialState, mode, pagador?.id, setDialogOpen, setFormState]
|
||||
);
|
||||
setErrorMessage(result.error);
|
||||
toast.error(result.error);
|
||||
});
|
||||
},
|
||||
[formState, initialState, mode, pagador?.id, setDialogOpen, setFormState],
|
||||
);
|
||||
|
||||
const title = mode === "create" ? "Novo pagador" : "Editar pagador";
|
||||
const description =
|
||||
mode === "create"
|
||||
? "Selecione um avatar e informe os detalhes para criar um novo pagador."
|
||||
: "Atualize os detalhes do pagador selecionado.";
|
||||
const submitLabel =
|
||||
mode === "create" ? "Salvar pagador" : "Atualizar pagador";
|
||||
const title = mode === "create" ? "Novo pagador" : "Editar pagador";
|
||||
const description =
|
||||
mode === "create"
|
||||
? "Selecione um avatar e informe os detalhes para criar um novo pagador."
|
||||
: "Atualize os detalhes do pagador selecionado.";
|
||||
const submitLabel =
|
||||
mode === "create" ? "Salvar pagador" : "Atualizar pagador";
|
||||
|
||||
return (
|
||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||
{trigger ? <DialogTrigger asChild>{trigger}</DialogTrigger> : null}
|
||||
<DialogContent className="max-w-2xl px-6 py-5 sm:px-8 sm:py-6">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
return (
|
||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||
{trigger ? <DialogTrigger asChild>{trigger}</DialogTrigger> : null}
|
||||
<DialogContent className="max-w-2xl px-6 py-5 sm:px-8 sm:py-6">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form className="flex flex-col gap-6" onSubmit={handleSubmit}>
|
||||
<fieldset className="flex flex-col gap-3">
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex w-full gap-2">
|
||||
<div className="flex flex-col gap-2 w-full">
|
||||
<Label htmlFor="pagador-name">Nome</Label>
|
||||
<Input
|
||||
id="pagador-name"
|
||||
value={formState.name}
|
||||
onChange={(event) =>
|
||||
updateField("name", event.target.value)
|
||||
}
|
||||
placeholder="Ex.: Felipe Coutinho"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<form className="flex flex-col gap-6" onSubmit={handleSubmit}>
|
||||
<fieldset className="flex flex-col gap-3">
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex w-full gap-2">
|
||||
<div className="flex flex-col gap-2 w-full">
|
||||
<Label htmlFor="pagador-name">Nome</Label>
|
||||
<Input
|
||||
id="pagador-name"
|
||||
value={formState.name}
|
||||
onChange={(event) =>
|
||||
updateField("name", event.target.value)
|
||||
}
|
||||
placeholder="Ex.: Felipe Coutinho"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2 w-full">
|
||||
<Label htmlFor="pagador-email">E-mail</Label>
|
||||
<Input
|
||||
id="pagador-email"
|
||||
type="email"
|
||||
value={formState.email}
|
||||
onChange={(event) =>
|
||||
updateField("email", event.target.value)
|
||||
}
|
||||
placeholder="Ex.: felipe@email.com"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2 w-full">
|
||||
<Label htmlFor="pagador-email">E-mail</Label>
|
||||
<Input
|
||||
id="pagador-email"
|
||||
type="email"
|
||||
value={formState.email}
|
||||
onChange={(event) =>
|
||||
updateField("email", event.target.value)
|
||||
}
|
||||
placeholder="Ex.: felipe@email.com"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="pagador-status">Status</Label>
|
||||
<Select
|
||||
value={formState.status}
|
||||
onValueChange={(value: PagadorStatus) =>
|
||||
updateField("status", value)
|
||||
}
|
||||
>
|
||||
<SelectTrigger id="pagador-status" className="w-full">
|
||||
<SelectValue placeholder="Selecione o status">
|
||||
{formState.status && (
|
||||
<StatusSelectContent label={formState.status} />
|
||||
)}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{PAGADOR_STATUS_OPTIONS.map((status) => (
|
||||
<SelectItem key={status} value={status}>
|
||||
<StatusSelectContent label={status} />
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="pagador-status">Status</Label>
|
||||
<Select
|
||||
value={formState.status}
|
||||
onValueChange={(value: PagadorStatus) =>
|
||||
updateField("status", value)
|
||||
}
|
||||
>
|
||||
<SelectTrigger id="pagador-status" className="w-full">
|
||||
<SelectValue placeholder="Selecione o status">
|
||||
{formState.status && (
|
||||
<StatusSelectContent label={formState.status} />
|
||||
)}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{PAGADOR_STATUS_OPTIONS.map((status) => (
|
||||
<SelectItem key={status} value={status}>
|
||||
<StatusSelectContent label={status} />
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<fieldset className="flex flex-col gap-3">
|
||||
<div className="flex items-start gap-3 rounded-lg border border-border/60 bg-muted/10 p-3">
|
||||
<Checkbox
|
||||
id="pagador-auto-send"
|
||||
checked={formState.isAutoSend}
|
||||
onCheckedChange={(checked) =>
|
||||
updateField("isAutoSend", Boolean(checked))
|
||||
}
|
||||
aria-label="Ativar envio automático"
|
||||
/>
|
||||
<div className="space-y-1">
|
||||
<Label
|
||||
htmlFor="pagador-auto-send"
|
||||
className="text-sm font-medium text-foreground"
|
||||
>
|
||||
Enviar automaticamente
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Dispare cobranças e lembretes sem intervenção manual.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset className="flex flex-col gap-3">
|
||||
<div className="flex items-start gap-3 rounded-lg border border-border/60 bg-muted/10 p-3">
|
||||
<Checkbox
|
||||
id="pagador-auto-send"
|
||||
checked={formState.isAutoSend}
|
||||
onCheckedChange={(checked) =>
|
||||
updateField("isAutoSend", Boolean(checked))
|
||||
}
|
||||
aria-label="Ativar envio automático"
|
||||
/>
|
||||
<div className="space-y-1">
|
||||
<Label
|
||||
htmlFor="pagador-auto-send"
|
||||
className="text-sm font-medium text-foreground"
|
||||
>
|
||||
Enviar automaticamente
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Dispare cobranças e lembretes sem intervenção manual.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset className="flex flex-col gap-3">
|
||||
<div className="grid grid-cols-4 gap-3 sm:grid-cols-5">
|
||||
{availableAvatars.length === 0 ? (
|
||||
<div className="col-span-5 flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed border-border/60 bg-muted/10 p-6 text-center text-sm text-muted-foreground">
|
||||
<RiCloseCircleLine className="size-6" />
|
||||
Nenhum avatar disponível. Adicione imagens em
|
||||
<span className="font-mono text-xs">public/avatares</span>
|
||||
.
|
||||
</div>
|
||||
) : null}
|
||||
{availableAvatars.map((avatar) => {
|
||||
const isSelected = avatar === formState.avatarUrl;
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
key={avatar}
|
||||
onClick={() => updateField("avatarUrl", avatar)}
|
||||
className="group relative flex items-center justify-center overflow-hidden rounded-xl border border-border/70 p-2 transition-all hover:border-primary/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40 focus-visible:ring-offset-2 data-[selected=true]:border-primary data-[selected=true]:bg-primary/10"
|
||||
data-selected={isSelected}
|
||||
aria-pressed={isSelected}
|
||||
>
|
||||
<span className="absolute inset-0 rounded-xl border-2 border-primary/80 opacity-0 transition-opacity group-data-[selected=true]:opacity-100" />
|
||||
{isSelected ? (
|
||||
<span className="absolute right-1 top-1 flex size-4 items-center justify-center rounded-full bg-sidebar-foreground text-primary-foreground shadow-sm">
|
||||
<RiCheckLine className="size-3.5" />
|
||||
</span>
|
||||
) : null}
|
||||
<Image
|
||||
src={getAvatarSrc(avatar)}
|
||||
alt={`Avatar ${avatar}`}
|
||||
width={72}
|
||||
height={72}
|
||||
className="size-12 rounded-lg object-cover"
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset className="flex flex-col gap-3">
|
||||
<div className="grid grid-cols-4 gap-3 sm:grid-cols-5">
|
||||
{availableAvatars.length === 0 ? (
|
||||
<div className="col-span-5 flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed border-border/60 bg-muted/10 p-6 text-center text-sm text-muted-foreground">
|
||||
<RiCloseCircleLine className="size-6" />
|
||||
Nenhum avatar disponível. Adicione imagens em
|
||||
<span className="font-mono text-xs">public/avatares</span>
|
||||
.
|
||||
</div>
|
||||
) : null}
|
||||
{availableAvatars.map((avatar) => {
|
||||
const isSelected = avatar === formState.avatarUrl;
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
key={avatar}
|
||||
onClick={() => updateField("avatarUrl", avatar)}
|
||||
className="group relative flex items-center justify-center overflow-hidden rounded-xl border border-border/70 p-2 transition-all hover:border-primary/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40 focus-visible:ring-offset-2 data-[selected=true]:border-primary data-[selected=true]:bg-primary/10"
|
||||
data-selected={isSelected}
|
||||
aria-pressed={isSelected}
|
||||
>
|
||||
<span className="absolute inset-0 rounded-xl border-2 border-primary/80 opacity-0 transition-opacity group-data-[selected=true]:opacity-100" />
|
||||
{isSelected ? (
|
||||
<span className="absolute right-1 top-1 flex size-4 items-center justify-center rounded-full bg-sidebar-foreground text-primary-foreground shadow-sm">
|
||||
<RiCheckLine className="size-3.5" />
|
||||
</span>
|
||||
) : null}
|
||||
<Image
|
||||
src={getAvatarSrc(avatar)}
|
||||
alt={`Avatar ${avatar}`}
|
||||
width={72}
|
||||
height={72}
|
||||
className="size-12 rounded-lg object-cover"
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="pagador-note">Anotações</Label>
|
||||
<Textarea
|
||||
id="pagador-note"
|
||||
rows={2}
|
||||
value={formState.note}
|
||||
onChange={(event) => updateField("note", event.target.value)}
|
||||
placeholder="Observações, preferências ou detalhes relevantes sobre este pagador"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="pagador-note">Anotações</Label>
|
||||
<Textarea
|
||||
id="pagador-note"
|
||||
rows={2}
|
||||
value={formState.note}
|
||||
onChange={(event) => updateField("note", event.target.value)}
|
||||
placeholder="Observações, preferências ou detalhes relevantes sobre este pagador"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
{errorMessage ? (
|
||||
<p className="text-sm text-destructive">{errorMessage}</p>
|
||||
) : null}
|
||||
{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>
|
||||
);
|
||||
<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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,18 +3,18 @@
|
||||
import DotIcon from "@/components/dot-icon";
|
||||
|
||||
export function StatusSelectContent({ label }: { label: string }) {
|
||||
const isActive = label === "Ativo";
|
||||
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>
|
||||
);
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,203 +1,202 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
deletePagadorAction,
|
||||
joinPagadorByShareCodeAction,
|
||||
} from "@/app/(dashboard)/pagadores/actions";
|
||||
import { PagadorCard } from "@/components/pagadores/pagador-card";
|
||||
import { PagadorDialog } from "@/components/pagadores/pagador-dialog";
|
||||
import { ConfirmActionDialog } from "@/components/confirm-action-dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { PAGADOR_ROLE_ADMIN } from "@/lib/pagadores/constants";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { RiAddCircleLine } from "@remixicon/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useCallback, useMemo, useState, useTransition } from "react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import {
|
||||
deletePagadorAction,
|
||||
joinPagadorByShareCodeAction,
|
||||
} from "@/app/(dashboard)/pagadores/actions";
|
||||
import { ConfirmActionDialog } from "@/components/confirm-action-dialog";
|
||||
import { PagadorCard } from "@/components/pagadores/pagador-card";
|
||||
import { PagadorDialog } from "@/components/pagadores/pagador-dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { PAGADOR_ROLE_ADMIN } from "@/lib/pagadores/constants";
|
||||
import type { Pagador } from "./types";
|
||||
import { RiAddCircleLine } from "@remixicon/react";
|
||||
|
||||
interface PagadoresPageProps {
|
||||
pagadores: Pagador[];
|
||||
avatarOptions: string[];
|
||||
pagadores: Pagador[];
|
||||
avatarOptions: string[];
|
||||
}
|
||||
|
||||
export function PagadoresPage({
|
||||
pagadores,
|
||||
avatarOptions,
|
||||
pagadores,
|
||||
avatarOptions,
|
||||
}: PagadoresPageProps) {
|
||||
const router = useRouter();
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [selectedPagador, setSelectedPagador] = useState<Pagador | null>(null);
|
||||
const [removeOpen, setRemoveOpen] = useState(false);
|
||||
const [pagadorToRemove, setPagadorToRemove] = useState<Pagador | null>(null);
|
||||
const [shareCodeInput, setShareCodeInput] = useState("");
|
||||
const [joinPending, startJoin] = useTransition();
|
||||
const router = useRouter();
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [selectedPagador, setSelectedPagador] = useState<Pagador | null>(null);
|
||||
const [removeOpen, setRemoveOpen] = useState(false);
|
||||
const [pagadorToRemove, setPagadorToRemove] = useState<Pagador | null>(null);
|
||||
const [shareCodeInput, setShareCodeInput] = useState("");
|
||||
const [joinPending, startJoin] = useTransition();
|
||||
|
||||
const orderedPagadores = useMemo(
|
||||
() =>
|
||||
[...pagadores].sort((a, b) => {
|
||||
// Admin sempre primeiro
|
||||
if (a.role === PAGADOR_ROLE_ADMIN && b.role !== PAGADOR_ROLE_ADMIN) {
|
||||
return -1;
|
||||
}
|
||||
if (a.role !== PAGADOR_ROLE_ADMIN && b.role === PAGADOR_ROLE_ADMIN) {
|
||||
return 1;
|
||||
}
|
||||
// Se ambos têm o mesmo tipo de role, ordena por nome
|
||||
return a.name.localeCompare(b.name, "pt-BR", { sensitivity: "base" });
|
||||
}),
|
||||
[pagadores]
|
||||
);
|
||||
const orderedPagadores = useMemo(
|
||||
() =>
|
||||
[...pagadores].sort((a, b) => {
|
||||
// Admin sempre primeiro
|
||||
if (a.role === PAGADOR_ROLE_ADMIN && b.role !== PAGADOR_ROLE_ADMIN) {
|
||||
return -1;
|
||||
}
|
||||
if (a.role !== PAGADOR_ROLE_ADMIN && b.role === PAGADOR_ROLE_ADMIN) {
|
||||
return 1;
|
||||
}
|
||||
// Se ambos têm o mesmo tipo de role, ordena por nome
|
||||
return a.name.localeCompare(b.name, "pt-BR", { sensitivity: "base" });
|
||||
}),
|
||||
[pagadores],
|
||||
);
|
||||
|
||||
const handleEdit = useCallback((pagador: Pagador) => {
|
||||
setSelectedPagador(pagador);
|
||||
setEditOpen(true);
|
||||
}, []);
|
||||
const handleEdit = useCallback((pagador: Pagador) => {
|
||||
setSelectedPagador(pagador);
|
||||
setEditOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleEditOpenChange = useCallback((open: boolean) => {
|
||||
setEditOpen(open);
|
||||
if (!open) {
|
||||
setSelectedPagador(null);
|
||||
}
|
||||
}, []);
|
||||
const handleEditOpenChange = useCallback((open: boolean) => {
|
||||
setEditOpen(open);
|
||||
if (!open) {
|
||||
setSelectedPagador(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleRemoveRequest = useCallback((pagador: Pagador) => {
|
||||
if (pagador.role === PAGADOR_ROLE_ADMIN) {
|
||||
toast.error("Pagadores administradores não podem ser removidos.");
|
||||
return;
|
||||
}
|
||||
setPagadorToRemove(pagador);
|
||||
setRemoveOpen(true);
|
||||
}, []);
|
||||
const handleRemoveRequest = useCallback((pagador: Pagador) => {
|
||||
if (pagador.role === PAGADOR_ROLE_ADMIN) {
|
||||
toast.error("Pagadores administradores não podem ser removidos.");
|
||||
return;
|
||||
}
|
||||
setPagadorToRemove(pagador);
|
||||
setRemoveOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleRemoveOpenChange = useCallback((open: boolean) => {
|
||||
setRemoveOpen(open);
|
||||
if (!open) {
|
||||
setPagadorToRemove(null);
|
||||
}
|
||||
}, []);
|
||||
const handleRemoveOpenChange = useCallback((open: boolean) => {
|
||||
setRemoveOpen(open);
|
||||
if (!open) {
|
||||
setPagadorToRemove(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleRemoveConfirm = useCallback(async () => {
|
||||
if (!pagadorToRemove) {
|
||||
return;
|
||||
}
|
||||
const handleRemoveConfirm = useCallback(async () => {
|
||||
if (!pagadorToRemove) {
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await deletePagadorAction({ id: pagadorToRemove.id });
|
||||
const result = await deletePagadorAction({ id: pagadorToRemove.id });
|
||||
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
return;
|
||||
}
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
return;
|
||||
}
|
||||
|
||||
toast.error(result.error);
|
||||
throw new Error(result.error);
|
||||
}, [pagadorToRemove]);
|
||||
toast.error(result.error);
|
||||
throw new Error(result.error);
|
||||
}, [pagadorToRemove]);
|
||||
|
||||
const removeTitle = pagadorToRemove
|
||||
? `Remover pagador "${pagadorToRemove.name}"?`
|
||||
: "Remover pagador?";
|
||||
const removeTitle = pagadorToRemove
|
||||
? `Remover pagador "${pagadorToRemove.name}"?`
|
||||
: "Remover pagador?";
|
||||
|
||||
const handleJoinByCode = useCallback(
|
||||
(event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
if (!shareCodeInput.trim()) {
|
||||
toast.error("Informe um código válido.");
|
||||
return;
|
||||
}
|
||||
const handleJoinByCode = useCallback(
|
||||
(event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
if (!shareCodeInput.trim()) {
|
||||
toast.error("Informe um código válido.");
|
||||
return;
|
||||
}
|
||||
|
||||
startJoin(async () => {
|
||||
const result = await joinPagadorByShareCodeAction({
|
||||
code: shareCodeInput.trim(),
|
||||
});
|
||||
startJoin(async () => {
|
||||
const result = await joinPagadorByShareCodeAction({
|
||||
code: shareCodeInput.trim(),
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
toast.error(result.error);
|
||||
return;
|
||||
}
|
||||
if (!result.success) {
|
||||
toast.error(result.error);
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success(result.message);
|
||||
setShareCodeInput("");
|
||||
router.refresh();
|
||||
});
|
||||
},
|
||||
[shareCodeInput, router]
|
||||
);
|
||||
toast.success(result.message);
|
||||
setShareCodeInput("");
|
||||
router.refresh();
|
||||
});
|
||||
},
|
||||
[shareCodeInput, router],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col gap-6 w-full">
|
||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<PagadorDialog
|
||||
mode="create"
|
||||
avatarOptions={avatarOptions}
|
||||
trigger={
|
||||
<Button>
|
||||
<RiAddCircleLine className="size-4" />
|
||||
Novo pagador
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<form
|
||||
onSubmit={handleJoinByCode}
|
||||
className="flex w-full flex-col gap-2 sm:w-auto sm:flex-row"
|
||||
>
|
||||
<Input
|
||||
placeholder="Código de Compartilhamento"
|
||||
value={shareCodeInput}
|
||||
onChange={(event) => setShareCodeInput(event.target.value)}
|
||||
disabled={joinPending}
|
||||
className="w-56 border-dashed"
|
||||
/>
|
||||
<Button type="submit" disabled={joinPending}>
|
||||
{joinPending ? "Adicionando..." : "Adicionar por código"}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col gap-6 w-full">
|
||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<PagadorDialog
|
||||
mode="create"
|
||||
avatarOptions={avatarOptions}
|
||||
trigger={
|
||||
<Button>
|
||||
<RiAddCircleLine className="size-4" />
|
||||
Novo pagador
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<form
|
||||
onSubmit={handleJoinByCode}
|
||||
className="flex w-full flex-col gap-2 sm:w-auto sm:flex-row"
|
||||
>
|
||||
<Input
|
||||
placeholder="Código de Compartilhamento"
|
||||
value={shareCodeInput}
|
||||
onChange={(event) => setShareCodeInput(event.target.value)}
|
||||
disabled={joinPending}
|
||||
className="w-56 border-dashed"
|
||||
/>
|
||||
<Button type="submit" disabled={joinPending}>
|
||||
{joinPending ? "Adicionando..." : "Adicionar por código"}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{orderedPagadores.length === 0 ? (
|
||||
<div className="flex min-h-[320px] items-center justify-center rounded-lg border border-dashed bg-muted/30">
|
||||
<div className="max-w-sm text-center text-sm text-muted-foreground">
|
||||
Cadastre seu primeiro pagador para organizar cobranças e
|
||||
pagamentos recorrentes.
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
|
||||
{orderedPagadores.map((pagador) => (
|
||||
<PagadorCard
|
||||
key={pagador.id}
|
||||
pagador={pagador}
|
||||
onEdit={pagador.canEdit ? () => handleEdit(pagador) : undefined}
|
||||
onRemove={
|
||||
pagador.canEdit && pagador.role !== PAGADOR_ROLE_ADMIN
|
||||
? () => handleRemoveRequest(pagador)
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{orderedPagadores.length === 0 ? (
|
||||
<div className="flex min-h-[320px] items-center justify-center rounded-lg border border-dashed bg-muted/30">
|
||||
<div className="max-w-sm text-center text-sm text-muted-foreground">
|
||||
Cadastre seu primeiro pagador para organizar cobranças e
|
||||
pagamentos recorrentes.
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
|
||||
{orderedPagadores.map((pagador) => (
|
||||
<PagadorCard
|
||||
key={pagador.id}
|
||||
pagador={pagador}
|
||||
onEdit={pagador.canEdit ? () => handleEdit(pagador) : undefined}
|
||||
onRemove={
|
||||
pagador.canEdit && pagador.role !== PAGADOR_ROLE_ADMIN
|
||||
? () => handleRemoveRequest(pagador)
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<PagadorDialog
|
||||
mode="update"
|
||||
pagador={selectedPagador ?? undefined}
|
||||
avatarOptions={avatarOptions}
|
||||
open={editOpen && !!selectedPagador}
|
||||
onOpenChange={handleEditOpenChange}
|
||||
/>
|
||||
<PagadorDialog
|
||||
mode="update"
|
||||
pagador={selectedPagador ?? undefined}
|
||||
avatarOptions={avatarOptions}
|
||||
open={editOpen && !!selectedPagador}
|
||||
onOpenChange={handleEditOpenChange}
|
||||
/>
|
||||
|
||||
<ConfirmActionDialog
|
||||
open={removeOpen && !!pagadorToRemove}
|
||||
onOpenChange={handleRemoveOpenChange}
|
||||
title={removeTitle}
|
||||
description="Ao remover este pagador, os registros relacionados a ele deixarão de ser associados automaticamente."
|
||||
confirmLabel="Remover pagador"
|
||||
pendingLabel="Removendo..."
|
||||
confirmVariant="destructive"
|
||||
onConfirm={handleRemoveConfirm}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
<ConfirmActionDialog
|
||||
open={removeOpen && !!pagadorToRemove}
|
||||
onOpenChange={handleRemoveOpenChange}
|
||||
title={removeTitle}
|
||||
description="Ao remover este pagador, os registros relacionados a ele deixarão de ser associados automaticamente."
|
||||
confirmLabel="Remover pagador"
|
||||
pendingLabel="Removendo..."
|
||||
confirmVariant="destructive"
|
||||
onConfirm={handleRemoveConfirm}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,27 +1,27 @@
|
||||
import type { PagadorStatus } from "@/lib/pagadores/constants";
|
||||
|
||||
export type Pagador = {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string | null;
|
||||
avatarUrl: string | null;
|
||||
status: PagadorStatus;
|
||||
note: string | null;
|
||||
role: string | null;
|
||||
isAutoSend: boolean;
|
||||
createdAt: string;
|
||||
canEdit: boolean;
|
||||
sharedByName?: string | null;
|
||||
sharedByEmail?: string | null;
|
||||
shareId?: string | null;
|
||||
shareCode?: string | null;
|
||||
id: string;
|
||||
name: string;
|
||||
email: string | null;
|
||||
avatarUrl: string | null;
|
||||
status: PagadorStatus;
|
||||
note: string | null;
|
||||
role: string | null;
|
||||
isAutoSend: boolean;
|
||||
createdAt: string;
|
||||
canEdit: boolean;
|
||||
sharedByName?: string | null;
|
||||
sharedByEmail?: string | null;
|
||||
shareId?: string | null;
|
||||
shareCode?: string | null;
|
||||
};
|
||||
|
||||
export type PagadorFormValues = {
|
||||
name: string;
|
||||
email: string;
|
||||
status: PagadorStatus;
|
||||
avatarUrl: string;
|
||||
note: string;
|
||||
isAutoSend: boolean;
|
||||
name: string;
|
||||
email: string;
|
||||
status: PagadorStatus;
|
||||
avatarUrl: string;
|
||||
note: string;
|
||||
isAutoSend: boolean;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user