feat(v1.5.3): status de pagamento no painel do pagador + SEO landing + WebP

- Card de Status de Pagamento com totais pagos/pendentes e lista de boletos individuais
- Validação obrigatória de categoria/conta/cartão no dialog de lançamento (client + server)
- SEO completo na landing: Open Graph, Twitter Card, JSON-LD, sitemap.xml, robots.txt
- Imagens convertidas de PNG para WebP (performance)
- HTML lang corrigido para pt-BR; template de título dinâmico

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Felipe Coutinho
2026-02-21 17:48:52 +00:00
parent 5638ccc36a
commit 31fe752b7d
32 changed files with 600 additions and 176 deletions

View File

@@ -5,6 +5,27 @@ Todas as mudanças notáveis deste projeto serão documentadas neste arquivo.
O formato é baseado em [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/), O formato é baseado em [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/),
e este projeto adere ao [Versionamento Semântico](https://semver.org/lang/pt-BR/). e este projeto adere ao [Versionamento Semântico](https://semver.org/lang/pt-BR/).
## [1.5.3] - 2026-02-21
### Adicionado
- Painel do pagador: card "Status de Pagamento" com totais pagos/pendentes e listagem individual de boletos com data de vencimento, data de pagamento e status
- Funções `fetchPagadorBoletoItems` e `fetchPagadorPaymentStatus` em `lib/pagadores/details.ts`
- SEO completo na landing page: metadata Open Graph, Twitter Card, JSON-LD Schema.org, sitemap.xml (`/app/sitemap.ts`) e robots.txt (`/app/robots.ts`)
- Layout específico da landing page (`app/(landing-page)/layout.tsx`) com metadados ricos
### Corrigido
- Validação obrigatória de categoria, conta e cartão no dialog de lançamento — agora validada no cliente (antes do submit) e no servidor via Zod
- Atributo `lang` do HTML corrigido de `en` para `pt-BR`
### Alterado
- Painel do pagador reorganizado em grid de 3 colunas com cards de Faturas, Boletos e Status de Pagamento
- `PagadorBoletoCard` refatorado para exibir lista de boletos individuais em vez de resumo agregado
- Imagens da landing page convertidas de PNG para WebP (melhora de performance)
- Template de título dinâmico no layout raiz (`%s | OpenMonetis`)
## [1.5.2] - 2026-02-16 ## [1.5.2] - 2026-02-16
### Alterado ### Alterado

View File

@@ -182,6 +182,30 @@ const refineLancamento = (
data: z.infer<typeof baseFields> & { id?: string }, data: z.infer<typeof baseFields> & { id?: string },
ctx: z.RefinementCtx, ctx: z.RefinementCtx,
) => { ) => {
if (!data.categoriaId) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["categoriaId"],
message: "Selecione uma categoria.",
});
}
if (data.paymentMethod === "Cartão de crédito") {
if (!data.cartaoId) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["cartaoId"],
message: "Selecione o cartão.",
});
}
} else if (!data.contaId) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["contaId"],
message: "Selecione a conta.",
});
}
if (data.condition === "Parcelado") { if (data.condition === "Parcelado") {
if (!data.installmentCount) { if (!data.installmentCount) {
ctx.addIssue({ ctx.addIssue({

View File

@@ -1,3 +1,8 @@
import {
RiBankCard2Line,
RiBarcodeLine,
RiWallet3Line,
} from "@remixicon/react";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { getRecentEstablishmentsAction } from "@/app/(dashboard)/lancamentos/actions"; import { getRecentEstablishmentsAction } from "@/app/(dashboard)/lancamentos/actions";
import { LancamentosPage as LancamentosSection } from "@/components/lancamentos/page/lancamentos-page"; import { LancamentosPage as LancamentosSection } from "@/components/lancamentos/page/lancamentos-page";
@@ -13,9 +18,13 @@ import { PagadorHistoryCard } from "@/components/pagadores/details/pagador-histo
import { PagadorInfoCard } from "@/components/pagadores/details/pagador-info-card"; import { PagadorInfoCard } from "@/components/pagadores/details/pagador-info-card";
import { PagadorLeaveShareCard } from "@/components/pagadores/details/pagador-leave-share-card"; import { PagadorLeaveShareCard } from "@/components/pagadores/details/pagador-leave-share-card";
import { PagadorMonthlySummaryCard } from "@/components/pagadores/details/pagador-monthly-summary-card"; import { PagadorMonthlySummaryCard } from "@/components/pagadores/details/pagador-monthly-summary-card";
import { PagadorBoletoCard } from "@/components/pagadores/details/pagador-payment-method-cards"; import {
PagadorBoletoCard,
PagadorPaymentStatusCard,
} from "@/components/pagadores/details/pagador-payment-method-cards";
import { PagadorSharingCard } from "@/components/pagadores/details/pagador-sharing-card"; import { PagadorSharingCard } from "@/components/pagadores/details/pagador-sharing-card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import WidgetCard from "@/components/widget-card";
import type { pagadores } from "@/db/schema"; import type { pagadores } from "@/db/schema";
import { getUserId } from "@/lib/auth/server"; import { getUserId } from "@/lib/auth/server";
import { import {
@@ -34,10 +43,12 @@ import {
} from "@/lib/lancamentos/page-helpers"; } from "@/lib/lancamentos/page-helpers";
import { getPagadorAccess } from "@/lib/pagadores/access"; import { getPagadorAccess } from "@/lib/pagadores/access";
import { import {
fetchPagadorBoletoItems,
fetchPagadorBoletoStats, fetchPagadorBoletoStats,
fetchPagadorCardUsage, fetchPagadorCardUsage,
fetchPagadorHistory, fetchPagadorHistory,
fetchPagadorMonthlyBreakdown, fetchPagadorMonthlyBreakdown,
fetchPagadorPaymentStatus,
} from "@/lib/pagadores/details"; } from "@/lib/pagadores/details";
import { parsePeriodParam } from "@/lib/utils/period"; import { parsePeriodParam } from "@/lib/utils/period";
import { import {
@@ -152,6 +163,8 @@ export default async function Page({ params, searchParams }: PageProps) {
historyData, historyData,
cardUsage, cardUsage,
boletoStats, boletoStats,
boletoItems,
paymentStatus,
shareRows, shareRows,
currentUserShare, currentUserShare,
estabelecimentos, estabelecimentos,
@@ -177,6 +190,16 @@ export default async function Page({ params, searchParams }: PageProps) {
pagadorId: pagador.id, pagadorId: pagador.id,
period: selectedPeriod, period: selectedPeriod,
}), }),
fetchPagadorBoletoItems({
userId: dataOwnerId,
pagadorId: pagador.id,
period: selectedPeriod,
}),
fetchPagadorPaymentStatus({
userId: dataOwnerId,
pagadorId: pagador.id,
period: selectedPeriod,
}),
sharesPromise, sharesPromise,
currentUserSharePromise, currentUserSharePromise,
getRecentEstablishmentsAction(), getRecentEstablishmentsAction(),
@@ -308,7 +331,7 @@ export default async function Page({ params, searchParams }: PageProps) {
</TabsContent> </TabsContent>
<TabsContent value="painel" className="space-y-4"> <TabsContent value="painel" className="space-y-4">
<section className="grid gap-4 lg:grid-cols-2"> <section className="grid gap-3 lg:grid-cols-2">
<PagadorMonthlySummaryCard <PagadorMonthlySummaryCard
periodLabel={periodLabel} periodLabel={periodLabel}
breakdown={monthlyBreakdown} breakdown={monthlyBreakdown}
@@ -316,9 +339,28 @@ export default async function Page({ params, searchParams }: PageProps) {
<PagadorHistoryCard data={historyData} /> <PagadorHistoryCard data={historyData} />
</section> </section>
<section className="grid gap-4 lg:grid-cols-2"> <section className="grid gap-3 lg:grid-cols-3">
<WidgetCard
title="Minhas Faturas"
subtitle="Valores por cartão neste período"
icon={<RiBankCard2Line className="size-4" />}
>
<PagadorCardUsageCard items={cardUsage} /> <PagadorCardUsageCard items={cardUsage} />
<PagadorBoletoCard stats={boletoStats} /> </WidgetCard>
<WidgetCard
title="Boletos"
subtitle="Boletos registrados neste período"
icon={<RiBarcodeLine className="size-4" />}
>
<PagadorBoletoCard items={boletoItems} />
</WidgetCard>
<WidgetCard
title="Status de Pagamento"
subtitle="Situação das despesas no período"
icon={<RiWallet3Line className="size-4" />}
>
<PagadorPaymentStatusCard data={paymentStatus} />
</WidgetCard>
</section> </section>
</TabsContent> </TabsContent>

View File

@@ -0,0 +1,95 @@
import type { Metadata } from "next";
import type { ReactNode } from "react";
const BASE_URL = process.env.PUBLIC_DOMAIN
? `https://${process.env.PUBLIC_DOMAIN}`
: "https://openmonetis.com";
const TITLE = "OpenMonetis | Finanças pessoais self-hosted e open source";
const DESCRIPTION =
"Aplicativo self-hosted de finanças pessoais. Controle lançamentos, cartões, orçamentos e categorias com total privacidade. Open source e gratuito.";
export const metadata: Metadata = {
metadataBase: new URL(BASE_URL),
title: TITLE,
description: DESCRIPTION,
keywords: [
"finanças pessoais",
"controle financeiro",
"self-hosted",
"open source",
"gestão financeira",
"orçamento pessoal",
"lançamentos financeiros",
"cartão de crédito",
"planejamento financeiro",
],
alternates: {
canonical: "/",
},
openGraph: {
type: "website",
locale: "pt_BR",
url: "/",
siteName: "OpenMonetis",
title: TITLE,
description: DESCRIPTION,
images: [
{
url: "/dashboard-preview-light.webp",
width: 1920,
height: 1080,
alt: "OpenMonetis — Dashboard de finanças pessoais",
},
],
},
twitter: {
card: "summary_large_image",
title: TITLE,
description: DESCRIPTION,
images: ["/dashboard-preview-light.webp"],
},
robots: {
index: true,
follow: true,
googleBot: {
index: true,
follow: true,
"max-image-preview": "large",
"max-snippet": -1,
},
},
};
export default function LandingLayout({ children }: { children: ReactNode }) {
const jsonLd = {
"@context": "https://schema.org",
"@type": "SoftwareApplication",
name: "OpenMonetis",
applicationCategory: "FinanceApplication",
operatingSystem: "Web",
offers: {
"@type": "Offer",
price: "0",
priceCurrency: "BRL",
},
description: DESCRIPTION,
url: BASE_URL,
isAccessibleForFree: true,
author: {
"@type": "Organization",
name: "OpenMonetis",
url: BASE_URL,
},
};
return (
<>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
/>
{children}
</>
);
}

View File

@@ -120,20 +120,20 @@ const screenshotSections = [
{ {
title: "Lançamentos", title: "Lançamentos",
description: "Registre e organize todas as suas transações financeiras", description: "Registre e organize todas as suas transações financeiras",
lightSrc: "/preview-lancamentos-light.png", lightSrc: "/preview-lancamentos-light.webp",
darkSrc: "/preview-lancamentos-dark.png", darkSrc: "/preview-lancamentos-dark.webp",
}, },
{ {
title: "Calendário", title: "Calendário",
description: "Visualize suas finanças no calendário mensal", description: "Visualize suas finanças no calendário mensal",
lightSrc: "/preview-calendario-light.png", lightSrc: "/preview-calendario-light.webp",
darkSrc: "/preview-calendario-dark.png", darkSrc: "/preview-calendario-dark.webp",
}, },
{ {
title: "Cartões", title: "Cartões",
description: "Acompanhe faturas, limites e vencimentos dos seus cartões", description: "Acompanhe faturas, limites e vencimentos dos seus cartões",
lightSrc: "/preview-cartao-light.png", lightSrc: "/preview-cartao-light.webp",
darkSrc: "/preview-cartao-dark.png", darkSrc: "/preview-cartao-dark.webp",
}, },
]; ];
@@ -355,7 +355,7 @@ export default async function Page() {
<AnimateOnScroll> <AnimateOnScroll>
<div> <div>
<Image <Image
src="/dashboard-preview-light.png" src="/dashboard-preview-light.webp"
alt="openmonetis Dashboard Preview" alt="openmonetis Dashboard Preview"
width={1920} width={1920}
height={1080} height={1080}
@@ -363,7 +363,7 @@ export default async function Page() {
priority priority
/> />
<Image <Image
src="/dashboard-preview-dark.png" src="/dashboard-preview-dark.webp"
alt="openmonetis Dashboard Preview" alt="openmonetis Dashboard Preview"
width={1920} width={1920}
height={1080} height={1080}
@@ -609,7 +609,7 @@ export default async function Page() {
<div className="order-1 md:order-2 flex items-center justify-center"> <div className="order-1 md:order-2 flex items-center justify-center">
<div className="w-full max-w-[220px] md:max-w-[260px]"> <div className="w-full max-w-[220px] md:max-w-[260px]">
<Image <Image
src="/openmonetis_companion.png" src="/openmonetis_companion.webp"
alt="OpenMonetis Companion App" alt="OpenMonetis Companion App"
width={1080} width={1080}
height={2217} height={2217}

View File

@@ -7,7 +7,10 @@ import { allFontVariables } from "@/public/fonts/font_index";
import "./globals.css"; import "./globals.css";
export const metadata: Metadata = { export const metadata: Metadata = {
title: "OpenMonetis | Suas finanças, do seu jeito", title: {
default: "OpenMonetis | Suas finanças, do seu jeito",
template: "%s | OpenMonetis",
},
description: description:
"Controle suas finanças pessoais de forma simples e transparente.", "Controle suas finanças pessoais de forma simples e transparente.",
}; };
@@ -18,7 +21,7 @@ export default function RootLayout({
children: React.ReactNode; children: React.ReactNode;
}>) { }>) {
return ( return (
<html lang="en" className={allFontVariables} suppressHydrationWarning> <html lang="pt-BR" className={allFontVariables} suppressHydrationWarning>
<head> <head>
<meta name="apple-mobile-web-app-title" content="OpenMonetis" /> <meta name="apple-mobile-web-app-title" content="OpenMonetis" />
</head> </head>

36
app/robots.ts Normal file
View File

@@ -0,0 +1,36 @@
import type { MetadataRoute } from "next";
const BASE_URL = process.env.PUBLIC_DOMAIN
? `https://${process.env.PUBLIC_DOMAIN}`
: "https://openmonetis.com";
export default function robots(): MetadataRoute.Robots {
return {
rules: [
{
userAgent: "*",
allow: "/",
disallow: [
"/dashboard",
"/lancamentos",
"/contas",
"/cartoes",
"/categorias",
"/orcamentos",
"/pagadores",
"/anotacoes",
"/insights",
"/calendario",
"/consultor",
"/ajustes",
"/relatorios",
"/top-estabelecimentos",
"/pre-lancamentos",
"/login",
"/api/",
],
},
],
sitemap: `${BASE_URL}/sitemap.xml`,
};
}

16
app/sitemap.ts Normal file
View File

@@ -0,0 +1,16 @@
import type { MetadataRoute } from "next";
const BASE_URL = process.env.PUBLIC_DOMAIN
? `https://${process.env.PUBLIC_DOMAIN}`
: "https://openmonetis.com";
export default function sitemap(): MetadataRoute.Sitemap {
return [
{
url: BASE_URL,
lastModified: new Date(),
changeFrequency: "monthly",
priority: 1,
},
];
}

View File

@@ -215,6 +215,27 @@ export function LancamentoDialog({
const sanitizedAmount = Math.abs(amountValue); const sanitizedAmount = Math.abs(amountValue);
if (!formState.categoriaId) {
const message = "Selecione uma categoria.";
setErrorMessage(message);
toast.error(message);
return;
}
if (formState.paymentMethod === "Cartão de crédito") {
if (!formState.cartaoId) {
const message = "Selecione o cartão.";
setErrorMessage(message);
toast.error(message);
return;
}
} else if (!formState.contaId) {
const message = "Selecione a conta.";
setErrorMessage(message);
toast.error(message);
return;
}
const payload = { const payload = {
purchaseDate: formState.purchaseDate, purchaseDate: formState.purchaseDate,
period: formState.period, period: formState.period,
@@ -382,6 +403,7 @@ export function LancamentoDialog({
<form <form
className="space-y-2 -mx-6 max-h-[80vh] overflow-y-auto px-6 pb-1" className="space-y-2 -mx-6 max-h-[80vh] overflow-y-auto px-6 pb-1"
onSubmit={handleSubmit} onSubmit={handleSubmit}
noValidate
> >
<BasicFieldsSection <BasicFieldsSection
formState={formState} formState={formState}

View File

@@ -1,7 +1,7 @@
import { RiBankCard2Line } from "@remixicon/react"; import { RiBankCard2Line } from "@remixicon/react";
import Image from "next/image"; import Image from "next/image";
import MoneyValues from "@/components/money-values"; import MoneyValues from "@/components/money-values";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { CardContent } from "@/components/ui/card";
import { WidgetEmptyState } from "@/components/widget-empty-state"; import { WidgetEmptyState } from "@/components/widget-empty-state";
import type { PagadorCardUsageItem } from "@/lib/pagadores/details"; import type { PagadorCardUsageItem } from "@/lib/pagadores/details";
@@ -17,57 +17,64 @@ const resolveLogoPath = (logo?: string | null) => {
return logo.startsWith("/") ? logo : `/logos/${logo}`; return logo.startsWith("/") ? logo : `/logos/${logo}`;
}; };
const buildInitials = (value: string) => {
const parts = value.trim().split(/\s+/).filter(Boolean);
if (parts.length === 0) return "CC";
if (parts.length === 1) {
const firstPart = parts[0];
return firstPart ? firstPart.slice(0, 2).toUpperCase() : "CC";
}
const firstChar = parts[0]?.[0] ?? "";
const secondChar = parts[1]?.[0] ?? "";
return `${firstChar}${secondChar}`.toUpperCase() || "CC";
};
type PagadorCardUsageCardProps = { type PagadorCardUsageCardProps = {
items: PagadorCardUsageItem[]; items: PagadorCardUsageItem[];
}; };
export function PagadorCardUsageCard({ items }: PagadorCardUsageCardProps) { export function PagadorCardUsageCard({ items }: PagadorCardUsageCardProps) {
if (items.length === 0) {
return ( return (
<Card className="border"> <CardContent className="px-0">
<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 <WidgetEmptyState
icon={<RiBankCard2Line className="size-6 text-muted-foreground" />} icon={<RiBankCard2Line className="size-6 text-muted-foreground" />}
title="Nenhum lançamento com cartão de crédito" title="Nenhum lançamento com cartão de crédito"
description="Quando houver despesas registradas com cartão, elas aparecerão aqui." description="Quando houver despesas registradas com cartão, elas aparecerão aqui."
/> />
) : ( </CardContent>
<ul className="space-y-3"> );
}
return (
<CardContent className="flex flex-col gap-4 px-0">
<ul className="flex flex-col">
{items.map((item) => { {items.map((item) => {
const logoPath = resolveLogoPath(item.logo); const logoPath = resolveLogoPath(item.logo);
const initials = buildInitials(item.name);
return ( return (
<li <li
key={item.id} key={item.id}
className="flex items-center justify-between gap-3 rounded-xl border border-border/80 px-4 py-3" className="flex items-center justify-between border-b border-dashed last:border-b-0 last:pb-0"
> >
<div className="flex items-center gap-3"> <div className="flex min-w-0 flex-1 items-center gap-2 py-2">
<div className="flex size-9 shrink-0 items-center justify-center overflow-hidden rounded-full">
{logoPath ? ( {logoPath ? (
<span className="flex size-10 items-center justify-center overflow-hidden rounded-full border border-border/60 bg-background">
<Image <Image
src={logoPath} src={logoPath}
alt={`Logo ${item.name}`} alt={`Logo do cartão ${item.name}`}
width={40} width={36}
height={40} height={36}
className="h-full w-full object-contain" className="h-full w-full object-contain"
/> />
</span>
) : ( ) : (
<span className="flex size-10 items-center justify-center rounded-full bg-muted text-xs font-semibold uppercase text-muted-foreground"> <span className="text-sm font-semibold uppercase text-muted-foreground">
{item.name.slice(0, 2)} {initials}
</span> </span>
)} )}
</div>
<div className="flex flex-col"> <div className="min-w-0">
<span className="font-medium text-foreground"> <span className="block truncate text-sm font-medium text-foreground">
{item.name} {item.name}
</span> </span>
<span className="text-xs text-muted-foreground"> <span className="text-xs text-muted-foreground">
@@ -75,16 +82,11 @@ export function PagadorCardUsageCard({ items }: PagadorCardUsageCardProps) {
</span> </span>
</div> </div>
</div> </div>
<MoneyValues <MoneyValues amount={item.amount} />
amount={item.amount}
className="text-lg font-semibold text-foreground"
/>
</li> </li>
); );
})} })}
</ul> </ul>
)}
</CardContent> </CardContent>
</Card>
); );
} }

View File

@@ -44,19 +44,19 @@ export function PagadorMonthlySummaryCard({
let offset = 0; let offset = 0;
return ( return (
<Card className="border"> <Card>
<CardHeader className="flex flex-col gap-1.5 pb-4"> <CardHeader className="flex flex-col gap-1.5">
<CardTitle className="text-lg font-semibold">Totais do mês</CardTitle> <CardTitle className="text-lg font-semibold">Totais do mês</CardTitle>
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
{periodLabel} - despesas por forma de pagamento {periodLabel} - Despesas por forma de pagamento
</p> </p>
</CardHeader> </CardHeader>
<CardContent className="space-y-4 pt-0"> <CardContent className="space-y-4 pt-0">
<div className="space-y-2"> <div className="space-y-2">
<div> <div>
<span className="text-[11px] uppercase tracking-wide text-muted-foreground"> <span className="text-xs tracking-wide text-muted-foreground">
Total gasto no mês Total
</span> </span>
<MoneyValues <MoneyValues
amount={breakdown.totalExpenses} amount={breakdown.totalExpenses}

View File

@@ -1,108 +1,163 @@
import { RiBarcodeLine } from "@remixicon/react"; import {
RiBarcodeLine,
RiCheckboxCircleLine,
RiHourglass2Line,
RiWallet3Line,
} from "@remixicon/react";
import { EstabelecimentoLogo } from "@/components/lancamentos/shared/estabelecimento-logo";
import MoneyValues from "@/components/money-values"; import MoneyValues from "@/components/money-values";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { CardContent } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator"; import { Progress } from "@/components/ui/progress";
import { WidgetEmptyState } from "@/components/widget-empty-state"; import { WidgetEmptyState } from "@/components/widget-empty-state";
import type { PagadorBoletoStats } from "@/lib/pagadores/details"; import type {
PagadorBoletoItem,
PagadorPaymentStatusData,
} from "@/lib/pagadores/details";
import { cn } from "@/lib/utils/ui"; import { cn } from "@/lib/utils/ui";
type PagadorBoletoCardProps = { // --- Boleto helpers ---
stats: PagadorBoletoStats;
const DATE_FORMATTER = new Intl.DateTimeFormat("pt-BR", {
day: "2-digit",
month: "short",
year: "numeric",
timeZone: "UTC",
});
const buildDateLabel = (value: string | null, prefix?: string) => {
if (!value) return null;
const [year, month, day] = value.split("-").map((part) => Number(part));
if (!year || !month || !day) return null;
const formatted = DATE_FORMATTER.format(
new Date(Date.UTC(year, month - 1, day)),
);
return prefix ? `${prefix} ${formatted}` : formatted;
}; };
export function PagadorBoletoCard({ stats }: PagadorBoletoCardProps) { const buildStatusLabel = (item: PagadorBoletoItem) => {
const total = stats.totalAmount; if (item.isSettled) return buildDateLabel(item.boletoPaymentDate, "Pago em");
const paidPercent = return buildDateLabel(item.dueDate, "Vence em");
total > 0 ? Math.round((stats.paidAmount / total) * 100) : 0; };
const pendingPercent =
total > 0 ? Math.round((stats.pendingAmount / total) * 100) : 0;
// --- PagadorBoletoCard ---
type PagadorBoletoCardProps = {
items: PagadorBoletoItem[];
};
export function PagadorBoletoCard({ items }: PagadorBoletoCardProps) {
if (items.length === 0) {
return ( return (
<Card className="border"> <CardContent className="px-0">
<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 <WidgetEmptyState
icon={<RiBarcodeLine className="size-6 text-muted-foreground" />} icon={<RiBarcodeLine className="size-6 text-muted-foreground" />}
title="Nenhum lançamento com boleto" title="Nenhum boleto cadastrado para o período"
description="Quando houver despesas registradas com boleto, elas aparecerão aqui." 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 border rounded-lg p-3">
<StatusRow
label="Pagos"
amount={stats.paidAmount}
count={stats.paidCount}
percent={paidPercent}
tone="success"
/>
<Separator />
<StatusRow
label="Pendentes"
amount={stats.pendingAmount}
count={stats.pendingCount}
percent={pendingPercent}
tone="warning"
/>
</div>
</>
)}
</CardContent> </CardContent>
</Card> );
}
return (
<CardContent className="flex flex-col gap-4 px-0">
<ul className="flex flex-col">
{items.map((item) => {
const statusLabel = buildStatusLabel(item);
return (
<li
key={item.id}
className="flex items-center justify-between border-b border-dashed last:border-b-0 last:pb-0"
>
<div className="flex min-w-0 flex-1 items-center gap-3 py-2">
<EstabelecimentoLogo name={item.name} size={36} />
<div className="min-w-0">
<span className="block truncate text-sm font-medium text-foreground">
{item.name}
</span>
{statusLabel ? (
<span
className={cn(
"text-xs text-muted-foreground",
item.isSettled && "text-success",
)}
>
{statusLabel}
</span>
) : null}
</div>
</div>
<MoneyValues amount={item.amount} />
</li>
);
})}
</ul>
</CardContent>
); );
} }
type StatusRowProps = { // --- PagadorPaymentStatusCard ---
label: string;
amount: number; type PagadorPaymentStatusCardProps = {
count: number; data: PagadorPaymentStatusData;
percent: number;
tone: "success" | "warning";
}; };
function StatusRow({ label, amount, count, percent, tone }: StatusRowProps) { export function PagadorPaymentStatusCard({
const clampedPercent = Math.min(Math.max(percent, 0), 100); data,
}: PagadorPaymentStatusCardProps) {
const { paidAmount, paidCount, pendingAmount, pendingCount, totalAmount } =
data;
if (totalAmount === 0) {
return ( return (
<div className="space-y-1 rounded p-3"> <CardContent className="px-0">
<div className="flex items-center justify-between text-sm font-semibold"> <WidgetEmptyState
<span>{label}</span> icon={<RiWallet3Line className="size-6 text-muted-foreground" />}
<span className="text-muted-foreground">{count} registros</span> title="Nenhuma despesa no período"
</div> description="Registre lançamentos para visualizar o status de pagamento."
<MoneyValues
amount={amount}
className={cn(
"text-xl font-semibold",
tone === "success" ? "text-success" : "text-warning",
)}
/>
<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-success" : "bg-warning",
)}
style={{ width: `${clampedPercent}%` }}
/> />
</CardContent>
);
}
const paidPercentage = (paidAmount / totalAmount) * 100;
return (
<CardContent className="space-y-6 px-0">
<div className="space-y-2">
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-foreground">Pago</span>
<MoneyValues amount={paidAmount} />
</div>
<Progress value={paidPercentage} className="h-2" />
<div className="flex items-center justify-between gap-4 text-sm">
<div className="flex items-center gap-1.5">
<RiCheckboxCircleLine className="size-3 text-success" />
<MoneyValues amount={paidAmount} />
<span className="text-xs text-muted-foreground">
({paidCount} registro{paidCount !== 1 ? "s" : ""})
</span>
</div> </div>
</div> </div>
</div> </div>
<div className="border-t border-dashed" />
<div className="space-y-2">
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-foreground">Pendente</span>
<MoneyValues amount={pendingAmount} />
</div>
<Progress value={100 - paidPercentage} className="h-2" />
<div className="flex items-center justify-between gap-4 text-sm">
<div className="flex items-center gap-1.5">
<RiHourglass2Line className="size-3 text-warning" />
<MoneyValues amount={pendingAmount} />
<span className="text-xs text-muted-foreground">
({pendingCount} registro{pendingCount !== 1 ? "s" : ""})
</span>
</div>
</div>
</div>
</CardContent>
); );
} }

View File

@@ -1,5 +1,6 @@
import { import {
and, and,
asc,
eq, eq,
gte, gte,
ilike, ilike,
@@ -47,6 +48,29 @@ export type PagadorBoletoStats = {
pendingCount: number; pendingCount: number;
}; };
export type PagadorBoletoItem = {
id: string;
name: string;
amount: number;
dueDate: string | null;
boletoPaymentDate: string | null;
isSettled: boolean;
};
export type PagadorPaymentStatusData = {
paidAmount: number;
paidCount: number;
pendingAmount: number;
pendingCount: number;
totalAmount: number;
};
const toISODate = (value: Date | string | null | undefined): string | null => {
if (!value) return null;
if (value instanceof Date) return value.toISOString().slice(0, 10);
return typeof value === "string" ? value : null;
};
const toNumber = (value: string | number | bigint | null) => { const toNumber = (value: string | number | bigint | null) => {
if (typeof value === "number") { if (typeof value === "number") {
return value; return value;
@@ -323,3 +347,87 @@ export async function fetchPagadorBoletoStats({
pendingCount, pendingCount,
}; };
} }
export async function fetchPagadorBoletoItems({
userId,
pagadorId,
period,
}: BaseFilters): Promise<PagadorBoletoItem[]> {
const rows = await db
.select({
id: lancamentos.id,
name: lancamentos.name,
amount: lancamentos.amount,
dueDate: lancamentos.dueDate,
boletoPaymentDate: lancamentos.boletoPaymentDate,
isSettled: lancamentos.isSettled,
})
.from(lancamentos)
.where(
and(
eq(lancamentos.userId, userId),
eq(lancamentos.pagadorId, pagadorId),
eq(lancamentos.period, period),
eq(lancamentos.paymentMethod, PAYMENT_METHOD_BOLETO),
excludeAutoInvoiceEntries(),
),
)
.orderBy(asc(lancamentos.dueDate));
return rows.map((row) => ({
id: row.id,
name: row.name,
amount: Math.abs(toNumber(row.amount)),
dueDate: toISODate(row.dueDate),
boletoPaymentDate: toISODate(row.boletoPaymentDate),
isSettled: Boolean(row.isSettled),
}));
}
export async function fetchPagadorPaymentStatus({
userId,
pagadorId,
period,
}: BaseFilters): Promise<PagadorPaymentStatusData> {
const rows = await db
.select({
paidAmount: sql<string>`coalesce(sum(case when ${lancamentos.isSettled} = true then abs(${lancamentos.amount}) else 0 end), 0)`,
paidCount: sql<number>`sum(case when ${lancamentos.isSettled} = true then 1 else 0 end)`,
pendingAmount: sql<string>`coalesce(sum(case when (${lancamentos.isSettled} = false or ${lancamentos.isSettled} is null) then abs(${lancamentos.amount}) else 0 end), 0)`,
pendingCount: sql<number>`sum(case when (${lancamentos.isSettled} = false or ${lancamentos.isSettled} is null) then 1 else 0 end)`,
})
.from(lancamentos)
.where(
and(
eq(lancamentos.userId, userId),
eq(lancamentos.pagadorId, pagadorId),
eq(lancamentos.period, period),
eq(lancamentos.transactionType, DESPESA),
excludeAutoInvoiceEntries(),
),
);
const row = rows[0];
if (!row) {
return {
paidAmount: 0,
paidCount: 0,
pendingAmount: 0,
pendingCount: 0,
totalAmount: 0,
};
}
const paidAmount = toNumber(row.paidAmount);
const paidCount = toNumber(row.paidCount);
const pendingAmount = toNumber(row.pendingAmount);
const pendingCount = toNumber(row.pendingCount);
return {
paidAmount,
paidCount,
pendingAmount,
pendingCount,
totalAmount: paidAmount + pendingAmount,
};
}

View File

@@ -1,6 +1,6 @@
{ {
"name": "openmonetis", "name": "openmonetis",
"version": "1.5.2", "version": "1.5.3",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next dev --turbopack", "dev": "next dev --turbopack",

Binary file not shown.

Before

Width:  |  Height:  |  Size: 911 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 163 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 909 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 150 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 904 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 152 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 933 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 160 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 839 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 859 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 169 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 262 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 272 KiB