From ffde55f58926dc78af79136f9b746e06a6cff2e1 Mon Sep 17 00:00:00 2001 From: Guilherme Bano Date: Wed, 18 Feb 2026 23:21:14 -0300 Subject: [PATCH 1/6] =?UTF-8?q?ajuste=20de=20layout=20mobile,=20melhorias?= =?UTF-8?q?=20e=20cria=C3=A7=C3=A3o=20de=20novas=20fun=C3=A7=C3=B5es.=20De?= =?UTF-8?q?talhes=20adicionados=20no=20CHANGELOG.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 25 ++ app/(dashboard)/ajustes/actions.ts | 6 + app/(dashboard)/ajustes/data.ts | 4 + app/(dashboard)/ajustes/page.tsx | 40 ++- .../cartoes/[cartaoId]/fatura/page.tsx | 6 +- .../categorias/[categoryId]/page.tsx | 6 +- .../contas/[contaId]/extrato/page.tsx | 6 +- app/(dashboard)/lancamentos/page.tsx | 8 +- app/(dashboard)/layout.tsx | 2 +- .../pagadores/[pagadorId]/page.tsx | 5 + .../gastos-por-categoria/layout.tsx | 23 ++ .../gastos-por-categoria/loading.tsx | 30 ++ .../relatorios/gastos-por-categoria/page.tsx | 100 ++++++ components/ajustes/changelog-tab.tsx | 33 ++ components/ajustes/preferences-form.tsx | 133 +++++++- ...expenses-by-category-widget-with-chart.tsx | 316 +++++++++++------- components/header-dashboard.tsx | 2 +- .../lancamentos/page/lancamentos-page.tsx | 6 + .../lancamentos/table/lancamentos-table.tsx | 203 +++++++---- components/month-picker/month-navigation.tsx | 2 +- components/orcamentos/budgets-page.tsx | 58 ++-- components/sidebar/nav-link.tsx | 6 + db/schema.ts | 2 + docker-compose.yml | 2 + drizzle/0017_add_extrato_note_as_column.sql | 1 + drizzle/0018_add_lancamentos_column_order.sql | 1 + lib/changelog/parse-changelog.ts | 9 + lib/lancamentos/column-order.ts | 33 ++ package.json | 2 +- 29 files changed, 857 insertions(+), 213 deletions(-) create mode 100644 app/(dashboard)/relatorios/gastos-por-categoria/layout.tsx create mode 100644 app/(dashboard)/relatorios/gastos-por-categoria/loading.tsx create mode 100644 app/(dashboard)/relatorios/gastos-por-categoria/page.tsx create mode 100644 drizzle/0017_add_extrato_note_as_column.sql create mode 100644 drizzle/0018_add_lancamentos_column_order.sql create mode 100644 lib/lancamentos/column-order.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ffd5e4..2157d8e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,30 @@ 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/), e este projeto adere ao [Versionamento Semântico](https://semver.org/lang/pt-BR/). +## [1.6.0] - 2026-02-18 + +### Adicionado + +- Item "Gastos por categoria" no menu lateral (seção Análise), com link para `/relatorios/gastos-por-categoria` +- Gráfico de pizza moderno (estilo donut) na página Gastos por categoria: fatias com espaçamento, labels de percentual nas fatias maiores, legenda ao lado +- Fatias do gráfico e itens da legenda clicáveis — navegam para a página de detalhe da categoria no período selecionado +- Preferência "Anotações em coluna" em Ajustes > Extrato e lançamentos: quando ativa, a anotação dos lançamentos aparece em coluna na tabela; quando inativa, permanece no balão (tooltip) no ícone +- Preferência "Ordem das colunas" em Ajustes > Extrato e lançamentos: lista ordenável por arraste para definir a ordem das colunas na tabela do extrato e dos lançamentos (Estabelecimento, Transação, Valor, etc.); a linha inteira é arrastável +- Coluna `extrato_note_as_column` e `lancamentos_column_order` na tabela `preferencias_usuario` (migrations 0017 e 0018) +- Constantes e labels das colunas reordenáveis em `lib/lancamentos/column-order.ts` + +### Alterado + +- Tooltip do gráfico de pizza em Gastos por categoria oculto no mobile (evita informação flutuante em telas pequenas) +- Header do dashboard fixo apenas no mobile (`fixed top-0` com `md:static`); conteúdo com `pt-12 md:pt-0` para não ficar sob o header +- Abas da página Ajustes (Preferências, Companion, etc.): no mobile, rolagem horizontal com seta indicando mais opções à direita; scrollbar oculta +- Botões "Novo orçamento" e "Copiar orçamentos do último mês": no mobile, rolagem horizontal (`h-8`, `text-xs`) +- Botões "Nova Receita", "Nova Despesa" e ícone de múltiplos lançamentos: no mobile, mesma rolagem horizontal + botões menores +- Tabela de lançamentos aplica a ordem de colunas salva nas preferências (extrato, lançamentos, categoria, fatura, pagador) +- Adicionado variavel no docker compose para manter o caminho do volume no compose up/down + +**Contribuições:** [Guilherme Bano](https://github.com/Gbano1) + ## [1.5.3] - 2026-02-21 ### Adicionado @@ -222,3 +246,4 @@ e este projeto adere ao [Versionamento Semântico](https://semver.org/lang/pt-BR - Atualização de dependências - Aplicada formatação no código + diff --git a/app/(dashboard)/ajustes/actions.ts b/app/(dashboard)/ajustes/actions.ts index 73760db..0776328 100644 --- a/app/(dashboard)/ajustes/actions.ts +++ b/app/(dashboard)/ajustes/actions.ts @@ -70,6 +70,8 @@ const VALID_FONTS = [ const updatePreferencesSchema = z.object({ disableMagnetlines: z.boolean(), + extratoNoteAsColumn: z.boolean(), + lancamentosColumnOrder: z.array(z.string()).nullable(), systemFont: z.enum(VALID_FONTS).default("ai-sans"), moneyFont: z.enum(VALID_FONTS).default("ai-sans"), }); @@ -417,6 +419,8 @@ export async function updatePreferencesAction( .update(schema.preferenciasUsuario) .set({ disableMagnetlines: validated.disableMagnetlines, + extratoNoteAsColumn: validated.extratoNoteAsColumn, + lancamentosColumnOrder: validated.lancamentosColumnOrder, systemFont: validated.systemFont, moneyFont: validated.moneyFont, updatedAt: new Date(), @@ -427,6 +431,8 @@ export async function updatePreferencesAction( await db.insert(schema.preferenciasUsuario).values({ userId: session.user.id, disableMagnetlines: validated.disableMagnetlines, + extratoNoteAsColumn: validated.extratoNoteAsColumn, + lancamentosColumnOrder: validated.lancamentosColumnOrder, systemFont: validated.systemFont, moneyFont: validated.moneyFont, }); diff --git a/app/(dashboard)/ajustes/data.ts b/app/(dashboard)/ajustes/data.ts index 84ed107..3f19f56 100644 --- a/app/(dashboard)/ajustes/data.ts +++ b/app/(dashboard)/ajustes/data.ts @@ -4,6 +4,8 @@ import { db, schema } from "@/lib/db"; export interface UserPreferences { disableMagnetlines: boolean; + extratoNoteAsColumn: boolean; + lancamentosColumnOrder: string[] | null; systemFont: string; moneyFont: string; } @@ -32,6 +34,8 @@ export async function fetchUserPreferences( const result = await db .select({ disableMagnetlines: schema.preferenciasUsuario.disableMagnetlines, + extratoNoteAsColumn: schema.preferenciasUsuario.extratoNoteAsColumn, + lancamentosColumnOrder: schema.preferenciasUsuario.lancamentosColumnOrder, systemFont: schema.preferenciasUsuario.systemFont, moneyFont: schema.preferenciasUsuario.moneyFont, }) diff --git a/app/(dashboard)/ajustes/page.tsx b/app/(dashboard)/ajustes/page.tsx index 9c46a6f..376cdf2 100644 --- a/app/(dashboard)/ajustes/page.tsx +++ b/app/(dashboard)/ajustes/page.tsx @@ -1,3 +1,4 @@ +import { RiArrowRightSLine } from "@remixicon/react"; import { headers } from "next/headers"; import { redirect } from "next/navigation"; @@ -35,17 +36,28 @@ export default async function Page() { return (
- - Preferências - Companion - Alterar nome - Alterar senha - Alterar e-mail - Changelog - - Deletar conta - - + {/* No mobile: rolagem horizontal + seta indicando mais opções à direita */} +
+
+ + Preferências + Companion + Alterar nome + Alterar senha + Alterar e-mail + Changelog + + Deletar conta + + +
+
+ +
+
@@ -61,6 +73,12 @@ export default async function Page() { disableMagnetlines={ userPreferences?.disableMagnetlines ?? false } + extratoNoteAsColumn={ + userPreferences?.extratoNoteAsColumn ?? false + } + lancamentosColumnOrder={ + userPreferences?.lancamentosColumnOrder ?? null + } systemFont={userPreferences?.systemFont ?? "ai-sans"} moneyFont={userPreferences?.moneyFont ?? "ai-sans"} /> diff --git a/app/(dashboard)/cartoes/[cartaoId]/fatura/page.tsx b/app/(dashboard)/cartoes/[cartaoId]/fatura/page.tsx index 7b5e6a3..0a7654d 100644 --- a/app/(dashboard)/cartoes/[cartaoId]/fatura/page.tsx +++ b/app/(dashboard)/cartoes/[cartaoId]/fatura/page.tsx @@ -1,5 +1,6 @@ import { RiPencilLine } from "@remixicon/react"; import { notFound } from "next/navigation"; +import { fetchUserPreferences } from "@/app/(dashboard)/ajustes/data"; import { getRecentEstablishmentsAction } from "@/app/(dashboard)/lancamentos/actions"; import { CardDialog } from "@/components/cartoes/card-dialog"; import type { Card } from "@/components/cartoes/types"; @@ -51,12 +52,13 @@ export default async function Page({ params, searchParams }: PageProps) { notFound(); } - const [filterSources, logoOptions, invoiceData, estabelecimentos] = + const [filterSources, logoOptions, invoiceData, estabelecimentos, userPreferences] = await Promise.all([ fetchLancamentoFilterSources(userId), loadLogoOptions(), fetchInvoiceData(userId, cartaoId, selectedPeriod), getRecentEstablishmentsAction(), + fetchUserPreferences(userId), ]); const sluggedFilters = buildSluggedFilters(filterSources); const slugMaps = buildSlugMaps(sluggedFilters); @@ -182,6 +184,8 @@ export default async function Page({ params, searchParams }: PageProps) { selectedPeriod={selectedPeriod} estabelecimentos={estabelecimentos} allowCreate + noteAsColumn={userPreferences?.extratoNoteAsColumn ?? false} + columnOrder={userPreferences?.lancamentosColumnOrder ?? null} defaultCartaoId={card.id} defaultPaymentMethod="Cartão de crédito" lockCartaoSelection diff --git a/app/(dashboard)/categorias/[categoryId]/page.tsx b/app/(dashboard)/categorias/[categoryId]/page.tsx index e897c5d..ded00a2 100644 --- a/app/(dashboard)/categorias/[categoryId]/page.tsx +++ b/app/(dashboard)/categorias/[categoryId]/page.tsx @@ -1,4 +1,5 @@ import { notFound } from "next/navigation"; +import { fetchUserPreferences } from "@/app/(dashboard)/ajustes/data"; import { getRecentEstablishmentsAction } from "@/app/(dashboard)/lancamentos/actions"; import { CategoryDetailHeader } from "@/components/categorias/category-detail-header"; import { LancamentosPage } from "@/components/lancamentos/page/lancamentos-page"; @@ -36,10 +37,11 @@ export default async function Page({ params, searchParams }: PageProps) { const periodoParam = getSingleParam(resolvedSearchParams, "periodo"); const { period: selectedPeriod } = parsePeriodParam(periodoParam); - const [detail, filterSources, estabelecimentos] = await Promise.all([ + const [detail, filterSources, estabelecimentos, userPreferences] = await Promise.all([ fetchCategoryDetails(userId, categoryId, selectedPeriod), fetchLancamentoFilterSources(userId), getRecentEstablishmentsAction(), + fetchUserPreferences(userId), ]); if (!detail) { @@ -92,6 +94,8 @@ export default async function Page({ params, searchParams }: PageProps) { selectedPeriod={detail.period} estabelecimentos={estabelecimentos} allowCreate={true} + noteAsColumn={userPreferences?.extratoNoteAsColumn ?? false} + columnOrder={userPreferences?.lancamentosColumnOrder ?? null} /> ); diff --git a/app/(dashboard)/contas/[contaId]/extrato/page.tsx b/app/(dashboard)/contas/[contaId]/extrato/page.tsx index b0acf53..6537bdb 100644 --- a/app/(dashboard)/contas/[contaId]/extrato/page.tsx +++ b/app/(dashboard)/contas/[contaId]/extrato/page.tsx @@ -1,5 +1,6 @@ import { RiPencilLine } from "@remixicon/react"; import { notFound } from "next/navigation"; +import { fetchUserPreferences } from "@/app/(dashboard)/ajustes/data"; import { getRecentEstablishmentsAction } from "@/app/(dashboard)/lancamentos/actions"; import { AccountDialog } from "@/components/contas/account-dialog"; import { AccountStatementCard } from "@/components/contas/account-statement-card"; @@ -57,12 +58,13 @@ export default async function Page({ params, searchParams }: PageProps) { notFound(); } - const [filterSources, logoOptions, accountSummary, estabelecimentos] = + const [filterSources, logoOptions, accountSummary, estabelecimentos, userPreferences] = await Promise.all([ fetchLancamentoFilterSources(userId), loadLogoOptions(), fetchAccountSummary(userId, contaId, selectedPeriod), getRecentEstablishmentsAction(), + fetchUserPreferences(userId), ]); const sluggedFilters = buildSluggedFilters(filterSources); const slugMaps = buildSlugMaps(sluggedFilters); @@ -161,6 +163,8 @@ export default async function Page({ params, searchParams }: PageProps) { selectedPeriod={selectedPeriod} estabelecimentos={estabelecimentos} allowCreate={false} + noteAsColumn={userPreferences?.extratoNoteAsColumn ?? false} + columnOrder={userPreferences?.lancamentosColumnOrder ?? null} /> diff --git a/app/(dashboard)/lancamentos/page.tsx b/app/(dashboard)/lancamentos/page.tsx index 7ad5fc9..5cd3fad 100644 --- a/app/(dashboard)/lancamentos/page.tsx +++ b/app/(dashboard)/lancamentos/page.tsx @@ -1,3 +1,4 @@ +import { fetchUserPreferences } from "@/app/(dashboard)/ajustes/data"; import { LancamentosPage } from "@/components/lancamentos/page/lancamentos-page"; import MonthNavigation from "@/components/month-picker/month-navigation"; import { getUserId } from "@/lib/auth/server"; @@ -31,7 +32,10 @@ export default async function Page({ searchParams }: PageProps) { const searchFilters = extractLancamentoSearchFilters(resolvedSearchParams); - const filterSources = await fetchLancamentoFilterSources(userId); + const [filterSources, userPreferences] = await Promise.all([ + fetchLancamentoFilterSources(userId), + fetchUserPreferences(userId), + ]); const sluggedFilters = buildSluggedFilters(filterSources); const slugMaps = buildSlugMaps(sluggedFilters); @@ -80,6 +84,8 @@ export default async function Page({ searchParams }: PageProps) { contaCartaoFilterOptions={contaCartaoFilterOptions} selectedPeriod={selectedPeriod} estabelecimentos={estabelecimentos} + noteAsColumn={userPreferences?.extratoNoteAsColumn ?? false} + columnOrder={userPreferences?.lancamentosColumnOrder ?? null} /> ); diff --git a/app/(dashboard)/layout.tsx b/app/(dashboard)/layout.tsx index 1773a8b..7df5fb6 100644 --- a/app/(dashboard)/layout.tsx +++ b/app/(dashboard)/layout.tsx @@ -70,7 +70,7 @@ export default async function DashboardLayout({ /> -
+
{children} diff --git a/app/(dashboard)/pagadores/[pagadorId]/page.tsx b/app/(dashboard)/pagadores/[pagadorId]/page.tsx index ddc7866..3f40f53 100644 --- a/app/(dashboard)/pagadores/[pagadorId]/page.tsx +++ b/app/(dashboard)/pagadores/[pagadorId]/page.tsx @@ -4,6 +4,7 @@ import { RiWallet3Line, } from "@remixicon/react"; import { notFound } from "next/navigation"; +import { fetchUserPreferences } from "@/app/(dashboard)/ajustes/data"; import { getRecentEstablishmentsAction } from "@/app/(dashboard)/lancamentos/actions"; import { LancamentosPage as LancamentosSection } from "@/components/lancamentos/page/lancamentos-page"; import type { @@ -168,6 +169,7 @@ export default async function Page({ params, searchParams }: PageProps) { shareRows, currentUserShare, estabelecimentos, + userPreferences, ] = await Promise.all([ fetchPagadorLancamentos(filters), fetchPagadorMonthlyBreakdown({ @@ -203,6 +205,7 @@ export default async function Page({ params, searchParams }: PageProps) { sharesPromise, currentUserSharePromise, getRecentEstablishmentsAction(), + fetchUserPreferences(userId), ]); const mappedLancamentos = mapLancamentosData(lancamentoRows); @@ -381,6 +384,8 @@ export default async function Page({ params, searchParams }: PageProps) { selectedPeriod={selectedPeriod} estabelecimentos={estabelecimentos} allowCreate={canEdit} + noteAsColumn={userPreferences?.extratoNoteAsColumn ?? false} + columnOrder={userPreferences?.lancamentosColumnOrder ?? null} importPagadorOptions={loggedUserOptionSets?.pagadorOptions} importSplitPagadorOptions={ loggedUserOptionSets?.splitPagadorOptions diff --git a/app/(dashboard)/relatorios/gastos-por-categoria/layout.tsx b/app/(dashboard)/relatorios/gastos-por-categoria/layout.tsx new file mode 100644 index 0000000..9942029 --- /dev/null +++ b/app/(dashboard)/relatorios/gastos-por-categoria/layout.tsx @@ -0,0 +1,23 @@ +import { RiPieChartLine } from "@remixicon/react"; +import PageDescription from "@/components/page-description"; + +export const metadata = { + title: "Gastos por categoria | OpenMonetis", +}; + +export default function GastosPorCategoriaLayout({ + children, +}: { + children: React.ReactNode; +}) { + return ( +
+ } + title="Gastos por categoria" + subtitle="Visualize suas despesas divididas por categoria no mês selecionado. Altere o mês para comparar períodos." + /> + {children} +
+ ); +} diff --git a/app/(dashboard)/relatorios/gastos-por-categoria/loading.tsx b/app/(dashboard)/relatorios/gastos-por-categoria/loading.tsx new file mode 100644 index 0000000..895a15e --- /dev/null +++ b/app/(dashboard)/relatorios/gastos-por-categoria/loading.tsx @@ -0,0 +1,30 @@ +import { Skeleton } from "@/components/ui/skeleton"; + +export default function GastosPorCategoriaLoading() { + return ( +
+
+ +
+
+ + +
+
+ {Array.from({ length: 5 }).map((_, i) => ( +
+
+ +
+ + +
+
+ +
+ ))} +
+
+
+ ); +} diff --git a/app/(dashboard)/relatorios/gastos-por-categoria/page.tsx b/app/(dashboard)/relatorios/gastos-por-categoria/page.tsx new file mode 100644 index 0000000..2fa7a57 --- /dev/null +++ b/app/(dashboard)/relatorios/gastos-por-categoria/page.tsx @@ -0,0 +1,100 @@ +import { + RiArrowDownSFill, + RiArrowUpSFill, + RiPieChartLine, +} from "@remixicon/react"; +import MonthNavigation from "@/components/month-picker/month-navigation"; +import { ExpensesByCategoryWidgetWithChart } from "@/components/dashboard/expenses-by-category-widget-with-chart"; +import MoneyValues from "@/components/money-values"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { getUserId } from "@/lib/auth/server"; +import { fetchExpensesByCategory } from "@/lib/dashboard/categories/expenses-by-category"; +import { calculatePercentageChange } from "@/lib/utils/math"; +import { parsePeriodParam } from "@/lib/utils/period"; + +type PageSearchParams = Promise>; + +type PageProps = { + searchParams?: PageSearchParams; +}; + +const getSingleParam = ( + params: Record | undefined, + key: string, +) => { + const value = params?.[key]; + if (!value) return null; + return Array.isArray(value) ? (value[0] ?? null) : value; +}; + +export default async function GastosPorCategoriaPage({ + searchParams, +}: PageProps) { + const userId = await getUserId(); + const resolvedSearchParams = searchParams ? await searchParams : undefined; + const periodoParam = getSingleParam(resolvedSearchParams, "periodo"); + + const { period: selectedPeriod } = parsePeriodParam(periodoParam); + + const data = await fetchExpensesByCategory(userId, selectedPeriod); + const percentageChange = calculatePercentageChange( + data.currentTotal, + data.previousTotal, + ); + const hasIncrease = percentageChange !== null && percentageChange > 0; + const hasDecrease = percentageChange !== null && percentageChange < 0; + + return ( +
+ + + + + + + Resumo do mês + + + +
+
+

+ Total de despesas no mês +

+ +
+ {percentageChange !== null && ( + + {hasIncrease && } + {hasDecrease && } + {percentageChange > 0 ? "+" : ""} + {percentageChange.toFixed(1)}% em relação ao mês anterior + + )} +
+

+ Mês anterior: +

+
+
+ + + + +
+ ); +} diff --git a/components/ajustes/changelog-tab.tsx b/components/ajustes/changelog-tab.tsx index 8208c87..b81a18c 100644 --- a/components/ajustes/changelog-tab.tsx +++ b/components/ajustes/changelog-tab.tsx @@ -1,7 +1,17 @@ +import Link from "next/link"; import { Badge } from "@/components/ui/badge"; import { Card } from "@/components/ui/card"; import type { ChangelogVersion } from "@/lib/changelog/parse-changelog"; +/** Converte "[texto](url)" em link; texto simples fica como está */ +function parseContributorLine(content: string) { + const linkMatch = content.match(/^\[([^\]]+)\]\((https?:\/\/[^)]+)\)$/); + if (linkMatch) { + return { label: linkMatch[1], url: linkMatch[2] }; + } + return { label: content, url: null }; +} + const sectionBadgeVariant: Record< string, "success" | "info" | "destructive" | "secondary" @@ -46,6 +56,29 @@ export function ChangelogTab({ versions }: { versions: ChangelogVersion[] }) {
))} + {version.contributor && ( +
+ + Contribuições:{" "} + {(() => { + const { label, url } = parseContributorLine(version.contributor); + if (url) { + return ( + + {label} + + ); + } + return {label}; + })()} + +
+ )}
))} diff --git a/components/ajustes/preferences-form.tsx b/components/ajustes/preferences-form.tsx index 454617c..ae209e2 100644 --- a/components/ajustes/preferences-form.tsx +++ b/components/ajustes/preferences-form.tsx @@ -1,5 +1,17 @@ "use client"; +import { + DndContext, + closestCenter, + type DragEndEvent, + KeyboardSensor, + PointerSensor, + useSensor, + useSensors, +} from "@dnd-kit/core"; +import { arrayMove, SortableContext, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable"; +import { CSS } from "@dnd-kit/utilities"; +import { RiDragMove2Line } from "@remixicon/react"; import { useRouter } from "next/navigation"; import { useEffect, useState, useTransition } from "react"; import { toast } from "sonner"; @@ -15,16 +27,58 @@ import { SelectValue, } from "@/components/ui/select"; import { Switch } from "@/components/ui/switch"; +import { + DEFAULT_LANCAMENTOS_COLUMN_ORDER, + LANCAMENTOS_COLUMN_LABELS, +} from "@/lib/lancamentos/column-order"; import { FONT_OPTIONS, getFontVariable } from "@/public/fonts/font_index"; interface PreferencesFormProps { disableMagnetlines: boolean; + extratoNoteAsColumn: boolean; + lancamentosColumnOrder: string[] | null; systemFont: string; moneyFont: string; } +function SortableColumnItem({ id }: { id: string }) { + const { + attributes, + listeners, + setNodeRef, + transform, + transition, + isDragging, + } = useSortable({ id }); + + const style = { + transform: CSS.Transform.toString(transform), + transition, + }; + + const label = LANCAMENTOS_COLUMN_LABELS[id] ?? id; + + return ( +
+ + {label} +
+ ); +} + export function PreferencesForm({ disableMagnetlines, + extratoNoteAsColumn: initialExtratoNoteAsColumn, + lancamentosColumnOrder: initialColumnOrder, systemFont: initialSystemFont, moneyFont: initialMoneyFont, }: PreferencesFormProps) { @@ -32,10 +86,33 @@ export function PreferencesForm({ const [isPending, startTransition] = useTransition(); const [magnetlinesDisabled, setMagnetlinesDisabled] = useState(disableMagnetlines); + const [extratoNoteAsColumn, setExtratoNoteAsColumn] = + useState(initialExtratoNoteAsColumn); + const [columnOrder, setColumnOrder] = useState( + initialColumnOrder && initialColumnOrder.length > 0 + ? initialColumnOrder + : DEFAULT_LANCAMENTOS_COLUMN_ORDER, + ); const [selectedSystemFont, setSelectedSystemFont] = useState(initialSystemFont); const [selectedMoneyFont, setSelectedMoneyFont] = useState(initialMoneyFont); + const sensors = useSensors( + useSensor(PointerSensor, { activationConstraint: { distance: 8 } }), + useSensor(KeyboardSensor), + ); + + const handleColumnDragEnd = (event: DragEndEvent) => { + const { active, over } = event; + if (over && active.id !== over.id) { + setColumnOrder((items) => { + const oldIndex = items.indexOf(active.id as string); + const newIndex = items.indexOf(over.id as string); + return arrayMove(items, oldIndex, newIndex); + }); + } + }; + const fontCtx = useFont(); // Live preview: update CSS vars when font selection changes @@ -53,6 +130,8 @@ export function PreferencesForm({ startTransition(async () => { const result = await updatePreferencesAction({ disableMagnetlines: magnetlinesDisabled, + extratoNoteAsColumn, + lancamentosColumnOrder: columnOrder, systemFont: selectedSystemFont, moneyFont: selectedMoneyFont, }); @@ -148,7 +227,59 @@ export function PreferencesForm({
- {/* Seção 3: Dashboard */} + {/* Seção: Extrato / Lançamentos */} +
+
+

Extrato e lançamentos

+

+ Como exibir anotações e a ordem das colunas na tabela de movimentações. +

+
+ +
+
+ +

+ Quando ativo, as anotações aparecem em uma coluna na tabela. Quando desativado, aparecem em um balão ao passar o mouse no ícone. +

+
+ +
+ +
+ +

+ Arraste os itens para definir a ordem em que as colunas aparecem na tabela do extrato e dos lançamentos. +

+ + +
+ {columnOrder.map((id) => ( + + ))} +
+
+
+
+
+ +
+ + {/* Seção: Dashboard */}

Dashboard

diff --git a/components/dashboard/expenses-by-category-widget-with-chart.tsx b/components/dashboard/expenses-by-category-widget-with-chart.tsx index 669a825..0dd2de3 100644 --- a/components/dashboard/expenses-by-category-widget-with-chart.tsx +++ b/components/dashboard/expenses-by-category-widget-with-chart.tsx @@ -4,20 +4,19 @@ import { RiArrowDownSFill, RiArrowUpSFill, RiExternalLinkLine, - RiListUnordered, - RiPieChart2Line, RiPieChartLine, RiWallet3Line, } from "@remixicon/react"; import Link from "next/link"; -import { useMemo, useState } from "react"; -import { Pie, PieChart, Tooltip } from "recharts"; +import { useRouter } from "next/navigation"; +import { useMemo } from "react"; +import { Cell, Pie, PieChart, Tooltip } from "recharts"; import { CategoryIconBadge } from "@/components/categorias/category-icon-badge"; +import { useIsMobile } from "@/hooks/use-mobile"; import MoneyValues from "@/components/money-values"; import { type ChartConfig, ChartContainer } from "@/components/ui/chart"; import type { ExpensesByCategoryData } from "@/lib/dashboard/categories/expenses-by-category"; import { formatPeriodForUrl } from "@/lib/utils/period"; -import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs"; import { WidgetEmptyState } from "../widget-empty-state"; type ExpensesByCategoryWidgetWithChartProps = { @@ -35,11 +34,21 @@ const formatCurrency = (value: number) => currency: "BRL", }).format(value); +type ChartDataItem = { + category: string; + name: string; + value: number; + percentage: number; + fill: string | undefined; + href: string | undefined; +}; + export function ExpensesByCategoryWidgetWithChart({ data, period, }: ExpensesByCategoryWidgetWithChartProps) { - const [activeTab, setActiveTab] = useState<"list" | "chart">("list"); + const router = useRouter(); + const isMobile = useIsMobile(); const periodParam = formatPeriodForUrl(period); // Configuração do chart com cores do CSS @@ -80,50 +89,68 @@ export function ExpensesByCategoryWidgetWithChart({ return config; }, [data.categories]); - // Preparar dados para o gráfico de pizza - Top 7 + Outros - const chartData = useMemo(() => { + // Preparar dados para o gráfico de pizza - Top 7 + Outros (com href para navegação) + const chartData = useMemo((): ChartDataItem[] => { + const buildItem = ( + categoryId: string, + name: string, + value: number, + percentage: number, + fill: string | undefined, + ): ChartDataItem => ({ + category: categoryId, + name, + value, + percentage, + fill, + href: + categoryId === "outros" + ? undefined + : `/categorias/${categoryId}?periodo=${periodParam}`, + }); + if (data.categories.length <= 7) { - return data.categories.map((category) => ({ - category: category.categoryId, - name: category.categoryName, - value: category.currentAmount, - percentage: category.percentageOfTotal, - fill: chartConfig[category.categoryId]?.color, - })); + return data.categories.map((category) => + buildItem( + category.categoryId, + category.categoryName, + category.currentAmount, + category.percentageOfTotal, + chartConfig[category.categoryId]?.color, + ), + ); } - // Pegar top 7 categorias const top7 = data.categories.slice(0, 7); const others = data.categories.slice(7); - - // Somar o restante const othersTotal = others.reduce((sum, cat) => sum + cat.currentAmount, 0); const othersPercentage = others.reduce( (sum, cat) => sum + cat.percentageOfTotal, 0, ); - const top7Data = top7.map((category) => ({ - category: category.categoryId, - name: category.categoryName, - value: category.currentAmount, - percentage: category.percentageOfTotal, - fill: chartConfig[category.categoryId]?.color, - })); - - // Adicionar "Outros" se houver + const top7Data = top7.map((category) => + buildItem( + category.categoryId, + category.categoryName, + category.currentAmount, + category.percentageOfTotal, + chartConfig[category.categoryId]?.color, + ), + ); if (others.length > 0) { - top7Data.push({ - category: "outros", - name: "Outros", - value: othersTotal, - percentage: othersPercentage, - fill: chartConfig.outros?.color, - }); + top7Data.push( + buildItem( + "outros", + "Outros", + othersTotal, + othersPercentage, + chartConfig.outros?.color, + ), + ); } - return top7Data; - }, [data.categories, chartConfig]); + }, [data.categories, chartConfig, periodParam]); if (data.categories.length === 0) { return ( @@ -136,25 +163,146 @@ export function ExpensesByCategoryWidgetWithChart({ } return ( - setActiveTab(v as "list" | "chart")} - className="w-full" - > -
- - - - Lista - - - - Gráfico - - +
+ {/* Gráfico de pizza (donut) — fatias clicáveis */} +
+ + + { + if (payload?.href) router.push(payload.href); + }} + label={(props: { + cx?: number; + cy?: number; + midAngle?: number; + innerRadius?: number; + outerRadius?: number; + percent?: number; + }) => { + const { cx = 0, cy = 0, midAngle = 0, innerRadius = 0, outerRadius = 0, percent = 0 } = props; + const percentage = percent * 100; + if (percentage < 6) return null; + const radius = (Number(innerRadius) + Number(outerRadius)) / 2; + const x = cx + radius * Math.cos(-midAngle * (Math.PI / 180)); + const y = cy + radius * Math.sin(-midAngle * (Math.PI / 180)); + return ( + + {formatPercentage(percentage)} + + ); + }} + labelLine={false} + > + {chartData.map((entry, index) => ( + + ))} + + {!isMobile && ( + { + if (active && payload?.length) { + const d = payload[0].payload as ChartDataItem; + return ( +
+
+ + {d.name} + + + {formatCurrency(d.value)} + + + {formatPercentage(d.percentage)} do total + + {d.href && ( + + Clique para ver detalhes + + )} +
+
+ ); + } + return null; + }} + cursor={false} + /> + )} +
+
+ + {/* Legenda clicável */} +
+ {chartData.map((entry, index) => { + const content = ( + <> + + + {entry.name} + + + {formatPercentage(entry.percentage)} + + + ); + return entry.href ? ( + + {content} + + ) : ( +
+ {content} +
+ ); + })} +
- + {/* Lista de categorias */} +
{data.categories.map((category, index) => { const hasIncrease = @@ -264,65 +412,7 @@ export function ExpensesByCategoryWidgetWithChart({ ); })}
- - - -
- - - formatPercentage(entry.percentage)} - outerRadius={75} - dataKey="value" - nameKey="category" - /> - { - if (active && payload && payload.length) { - const data = payload[0].payload; - return ( -
-
-
- - {data.name} - - - {formatCurrency(data.value)} - - - {formatPercentage(data.percentage)} do total - -
-
-
- ); - } - return null; - }} - /> -
-
- -
- {chartData.map((entry, index) => ( -
-
- - {entry.name} - -
- ))} -
-
- - +
+
); } diff --git a/components/header-dashboard.tsx b/components/header-dashboard.tsx index 9baa8af..7df29b9 100644 --- a/components/header-dashboard.tsx +++ b/components/header-dashboard.tsx @@ -16,7 +16,7 @@ export async function SiteHeader({ notificationsSnapshot }: SiteHeaderProps) { const _user = await getUser(); return ( -
+
diff --git a/components/lancamentos/page/lancamentos-page.tsx b/components/lancamentos/page/lancamentos-page.tsx index 912f1af..7fe938f 100644 --- a/components/lancamentos/page/lancamentos-page.tsx +++ b/components/lancamentos/page/lancamentos-page.tsx @@ -48,6 +48,8 @@ interface LancamentosPageProps { selectedPeriod: string; estabelecimentos: string[]; allowCreate?: boolean; + noteAsColumn?: boolean; + columnOrder?: string[] | null; defaultCartaoId?: string | null; defaultPaymentMethod?: string | null; lockCartaoSelection?: boolean; @@ -76,6 +78,8 @@ export function LancamentosPage({ selectedPeriod, estabelecimentos, allowCreate = true, + noteAsColumn = false, + columnOrder = null, defaultCartaoId, defaultPaymentMethod, lockCartaoSelection, @@ -377,6 +381,8 @@ export function LancamentosPage({ { type BuildColumnsArgs = { currentUserId: string; + noteAsColumn: boolean; onEdit?: (item: LancamentoItem) => void; onCopy?: (item: LancamentoItem) => void; onImport?: (item: LancamentoItem) => void; @@ -106,6 +109,7 @@ type BuildColumnsArgs = { const buildColumns = ({ currentUserId, + noteAsColumn, onEdit, onCopy, onImport, @@ -269,7 +273,7 @@ const buildColumns = ({ )} - {hasNote ? ( + {!noteAsColumn && hasNote ? ( @@ -493,6 +497,24 @@ const buildColumns = ({ }, ]; + if (noteAsColumn) { + const contaCartaoIndex = columns.findIndex((c) => c.id === "contaCartao"); + const noteColumn: ColumnDef = { + accessorKey: "note", + header: "Anotação", + cell: ({ row }) => { + const note = row.original.note; + if (!note?.trim()) return ; + return ( + + {note} + + ); + }, + }; + columns.splice(contaCartaoIndex, 0, noteColumn); + } + if (showActions) { columns.push({ id: "actions", @@ -645,9 +667,51 @@ const buildColumns = ({ return columns; }; +const FIXED_START_IDS = ["select", "purchaseDate"]; +const FIXED_END_IDS = ["actions"]; + +function getColumnId(col: ColumnDef): string { + const c = col as { id?: string; accessorKey?: string }; + return c.id ?? c.accessorKey ?? ""; +} + +function reorderColumnsByPreference( + columns: ColumnDef[], + orderPreference: string[] | null | undefined, +): ColumnDef[] { + if (!orderPreference || orderPreference.length === 0) return columns; + + const order = orderPreference; + const fixedStart: ColumnDef[] = []; + const reorderable: ColumnDef[] = []; + const fixedEnd: ColumnDef[] = []; + + for (const col of columns) { + const id = getColumnId(col as ColumnDef); + if (FIXED_START_IDS.includes(id)) fixedStart.push(col); + else if (FIXED_END_IDS.includes(id)) fixedEnd.push(col); + else reorderable.push(col); + } + + const sorted = [...reorderable].sort((a, b) => { + const idA = getColumnId(a as ColumnDef); + const idB = getColumnId(b as ColumnDef); + const indexA = order.indexOf(idA); + const indexB = order.indexOf(idB); + if (indexA === -1 && indexB === -1) return 0; + if (indexA === -1) return 1; + if (indexB === -1) return -1; + return indexA - indexB; + }); + + return [...fixedStart, ...sorted, ...fixedEnd]; +} + type LancamentosTableProps = { data: LancamentoItem[]; currentUserId: string; + noteAsColumn?: boolean; + columnOrder?: string[] | null; pagadorFilterOptions?: LancamentoFilterOption[]; categoriaFilterOptions?: LancamentoFilterOption[]; contaCartaoFilterOptions?: ContaCartaoFilterOption[]; @@ -672,6 +736,8 @@ type LancamentosTableProps = { export function LancamentosTable({ data, currentUserId, + noteAsColumn = false, + columnOrder: columnOrderPreference = null, pagadorFilterOptions = [], categoriaFilterOptions = [], contaCartaoFilterOptions = [], @@ -704,23 +770,10 @@ export function LancamentosTable({ }); const [rowSelection, setRowSelection] = useState({}); - const columns = useMemo( - () => - buildColumns({ - currentUserId, - onEdit, - onCopy, - onImport, - onConfirmDelete, - onViewDetails, - onToggleSettlement, - onAnticipate, - onViewAnticipationHistory, - isSettlementLoading: isSettlementLoading ?? (() => false), - showActions, - }), - [ + const columns = useMemo(() => { + const built = buildColumns({ currentUserId, + noteAsColumn, onEdit, onCopy, onImport, @@ -729,10 +782,28 @@ export function LancamentosTable({ onToggleSettlement, onAnticipate, onViewAnticipationHistory, - isSettlementLoading, + isSettlementLoading: isSettlementLoading ?? (() => false), showActions, - ], - ); + }); + const order = columnOrderPreference?.length + ? columnOrderPreference + : DEFAULT_LANCAMENTOS_COLUMN_ORDER; + return reorderColumnsByPreference(built, order); + }, [ + currentUserId, + noteAsColumn, + columnOrderPreference, + onEdit, + onCopy, + onImport, + onConfirmDelete, + onViewDetails, + onToggleSettlement, + onAnticipate, + onViewAnticipationHistory, + isSettlementLoading, + showActions, + ]); const table = useReactTable({ data, @@ -789,47 +860,57 @@ export function LancamentosTable({ {showTopControls ? (
{onCreate || onMassAdd ? ( -
- {onCreate ? ( - <> - - - - ) : null} - {onMassAdd ? ( - - - - - -

Adicionar múltiplos lançamentos

-
-
- ) : null} +
+
+
+ {onCreate ? ( + <> + + + + ) : null} + {onMassAdd ? ( + + + + + +

Adicionar múltiplos lançamentos

+
+
+ ) : null} +
+
+
+ +
) : ( diff --git a/components/month-picker/month-navigation.tsx b/components/month-picker/month-navigation.tsx index 0fa3966..f60eda8 100644 --- a/components/month-picker/month-navigation.tsx +++ b/components/month-picker/month-navigation.tsx @@ -79,7 +79,7 @@ export default function MonthNavigation() { }; return ( - +
-
- - - Novo orçamento + {/* No mobile: rolagem horizontal + seta + botões menores */} +
+
+
+ + + Novo orçamento + + } + /> + - } - /> -
+
+
- - Copiar orçamentos do último mês - + +
{hasBudgets ? ( diff --git a/components/sidebar/nav-link.tsx b/components/sidebar/nav-link.tsx index 268eec0..d9bd771 100644 --- a/components/sidebar/nav-link.tsx +++ b/components/sidebar/nav-link.tsx @@ -7,6 +7,7 @@ import { RiDashboardLine, RiFileChartLine, RiFundsLine, + RiPieChartLine, RiGroupLine, RiInboxLine, RiPriceTag3Line, @@ -160,6 +161,11 @@ export function createSidebarNavData( url: "/relatorios/tendencias", icon: RiFileChartLine, }, + { + title: "Gastos por categoria", + url: "/relatorios/gastos-por-categoria", + icon: RiPieChartLine, + }, { title: "Uso de Cartões", url: "/relatorios/uso-cartoes", diff --git a/db/schema.ts b/db/schema.ts index 40d969b..fa9b6b9 100644 --- a/db/schema.ts +++ b/db/schema.ts @@ -107,8 +107,10 @@ export const preferenciasUsuario = pgTable("preferencias_usuario", { .unique() .references(() => user.id, { onDelete: "cascade" }), disableMagnetlines: boolean("disable_magnetlines").notNull().default(false), + extratoNoteAsColumn: boolean("extrato_note_as_column").notNull().default(false), systemFont: text("system_font").notNull().default("ai-sans"), moneyFont: text("money_font").notNull().default("ai-sans"), + lancamentosColumnOrder: jsonb("lancamentos_column_order").$type(), dashboardWidgets: jsonb("dashboard_widgets").$type<{ order: string[]; hidden: string[]; diff --git a/docker-compose.yml b/docker-compose.yml index dd686a3..a8c432f 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -29,6 +29,8 @@ services: POSTGRES_USER: ${POSTGRES_USER:-openmonetis} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-openmonetis_dev_password} POSTGRES_DB: ${POSTGRES_DB:-openmonetis_db} + # Garante que os dados ficam no volume montado (evita perda após down/up) + PGDATA: /var/lib/postgresql/data # Configurações de performance POSTGRES_INITDB_ARGS: "-E UTF8 --locale=C" diff --git a/drizzle/0017_add_extrato_note_as_column.sql b/drizzle/0017_add_extrato_note_as_column.sql new file mode 100644 index 0000000..92dd36b --- /dev/null +++ b/drizzle/0017_add_extrato_note_as_column.sql @@ -0,0 +1 @@ +ALTER TABLE "preferencias_usuario" ADD COLUMN IF NOT EXISTS "extrato_note_as_column" boolean DEFAULT false NOT NULL; diff --git a/drizzle/0018_add_lancamentos_column_order.sql b/drizzle/0018_add_lancamentos_column_order.sql new file mode 100644 index 0000000..59eb499 --- /dev/null +++ b/drizzle/0018_add_lancamentos_column_order.sql @@ -0,0 +1 @@ +ALTER TABLE "preferencias_usuario" ADD COLUMN IF NOT EXISTS "lancamentos_column_order" jsonb; diff --git a/lib/changelog/parse-changelog.ts b/lib/changelog/parse-changelog.ts index 9e9a317..57d60da 100644 --- a/lib/changelog/parse-changelog.ts +++ b/lib/changelog/parse-changelog.ts @@ -10,6 +10,8 @@ export type ChangelogVersion = { version: string; date: string; sections: ChangelogSection[]; + /** Linha de contribuições/autor (pode conter markdown, ex: [Nome](url)) */ + contributor?: string; }; export function parseChangelog(): ChangelogVersion[] { @@ -49,6 +51,13 @@ export function parseChangelog(): ChangelogVersion[] { const itemMatch = line.match(/^- (.+)$/); if (itemMatch && currentSection) { currentSection.items.push(itemMatch[1]); + continue; + } + + // **Contribuições:** ou **Autor:** com texto/link opcional + const contributorMatch = line.match(/^\*\*(?:Contribuições|Autor):\*\*\s*(.+)$/); + if (contributorMatch && currentVersion) { + currentVersion.contributor = contributorMatch[1].trim() || undefined; } } diff --git a/lib/lancamentos/column-order.ts b/lib/lancamentos/column-order.ts new file mode 100644 index 0000000..9413235 --- /dev/null +++ b/lib/lancamentos/column-order.ts @@ -0,0 +1,33 @@ +/** + * Ids das colunas reordenáveis da tabela de lançamentos (extrato). + * select, purchaseDate e actions são fixos (início, oculto, fim). + */ +export const LANCAMENTOS_REORDERABLE_COLUMN_IDS = [ + "name", + "transactionType", + "amount", + "condition", + "paymentMethod", + "categoriaName", + "pagadorName", + "note", + "contaCartao", +] as const; + +export type LancamentosColumnId = (typeof LANCAMENTOS_REORDERABLE_COLUMN_IDS)[number]; + +export const LANCAMENTOS_COLUMN_LABELS: Record = { + name: "Estabelecimento", + transactionType: "Transação", + amount: "Valor", + condition: "Condição", + paymentMethod: "Forma de Pagamento", + categoriaName: "Categoria", + pagadorName: "Pagador", + note: "Anotação", + contaCartao: "Conta/Cartão", +}; + +export const DEFAULT_LANCAMENTOS_COLUMN_ORDER: string[] = [ + ...LANCAMENTOS_REORDERABLE_COLUMN_IDS, +]; diff --git a/package.json b/package.json index 6ae80ea..779802a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "openmonetis", - "version": "1.5.3", + "version": "1.6.0", "private": true, "scripts": { "dev": "next dev --turbopack", From 9b78f839bf11f93cfee05df16b9c4912094f2de4 Mon Sep 17 00:00:00 2001 From: Guilherme Bano Date: Fri, 20 Feb 2026 00:39:50 -0300 Subject: [PATCH 2/6] Adicionado aba de estabelecimentos e feita ajuste de interface. Detalhes adicionados no CHANGELOG.md --- CHANGELOG.md | 14 ++ app/(dashboard)/contas/actions.ts | 13 +- app/(dashboard)/estabelecimentos/actions.ts | 102 ++++++++++++ app/(dashboard)/estabelecimentos/data.ts | 66 ++++++++ app/(dashboard)/estabelecimentos/layout.tsx | 23 +++ app/(dashboard)/estabelecimentos/loading.tsx | 19 +++ app/(dashboard)/estabelecimentos/page.tsx | 14 ++ app/(dashboard)/lancamentos/actions.ts | 78 +++++---- ...expenses-by-category-widget-with-chart.tsx | 18 +- .../estabelecimento-create-dialog.tsx | 97 +++++++++++ .../estabelecimentos-page.tsx | 154 ++++++++++++++++++ .../lancamentos/page/lancamentos-page.tsx | 1 + .../shared/estabelecimento-input.tsx | 2 +- .../lancamentos/table/lancamentos-filters.tsx | 54 +++++- .../lancamentos/table/lancamentos-table.tsx | 3 + components/sidebar/nav-link.tsx | 6 + components/ui/chart.tsx | 24 ++- db/schema.ts | 35 ++++ drizzle/0019_add_estabelecimentos.sql | 16 ++ lib/actions/helpers.ts | 1 + lib/lancamentos/page-helpers.ts | 6 + lib/transferencias/constants.ts | 2 + package.json | 2 +- 23 files changed, 695 insertions(+), 55 deletions(-) create mode 100644 app/(dashboard)/estabelecimentos/actions.ts create mode 100644 app/(dashboard)/estabelecimentos/data.ts create mode 100644 app/(dashboard)/estabelecimentos/layout.tsx create mode 100644 app/(dashboard)/estabelecimentos/loading.tsx create mode 100644 app/(dashboard)/estabelecimentos/page.tsx create mode 100644 components/estabelecimentos/estabelecimento-create-dialog.tsx create mode 100644 components/estabelecimentos/estabelecimentos-page.tsx create mode 100644 drizzle/0019_add_estabelecimentos.sql diff --git a/CHANGELOG.md b/CHANGELOG.md index 2157d8e..c6604dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,20 @@ 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/), e este projeto adere ao [Versionamento Semântico](https://semver.org/lang/pt-BR/). +## [1.6.1] - 2026-02-18 + +### Adicionado + +- Aba "Estabelecimentos" no menu lateral (Gestão Financeira): listagem de estabelecimentos com quantidade de lançamentos, criação de novos, exclusão (apenas quando não há lançamentos vinculados) e link "Ver vinculados" para lançamentos filtrados pelo estabelecimento +- Tabela `estabelecimentos` (migration 0019) e sugestões de estabelecimento nos lançamentos passam a incluir nomes cadastrados nessa tabela +- Filtro "Estabelecimento" no drawer de Filtros da página de lançamentos; parâmetro `estabelecimento` na URL para filtrar por nome + +### Alterado + +- Transferências entre contas: nome do estabelecimento passa a ser "Saída - Transf. entre contas" na saída e "Entrada - Transf. entre contas" na entrada e adicionando em anotação no formato "de {conta origem} -> {conta destino}" +- Gráfico de pizza (Gastos por categoria): cores das fatias alinhadas às cores dos ícones das categorias na lista (paleta `getCategoryColor`) +- ChartContainer (Recharts): renderização do gráfico apenas após montagem no cliente e uso de `minWidth`/`minHeight` no ResponsiveContainer para evitar aviso "width(-1) and height(-1)" no console + ## [1.6.0] - 2026-02-18 ### Adicionado diff --git a/app/(dashboard)/contas/actions.ts b/app/(dashboard)/contas/actions.ts index 58dddb6..1c623be 100644 --- a/app/(dashboard)/contas/actions.ts +++ b/app/(dashboard)/contas/actions.ts @@ -22,7 +22,8 @@ import { noteSchema, uuidSchema } from "@/lib/schemas/common"; import { TRANSFER_CATEGORY_NAME, TRANSFER_CONDITION, - TRANSFER_ESTABLISHMENT, + TRANSFER_ESTABLISHMENT_ENTRADA, + TRANSFER_ESTABLISHMENT_SAIDA, TRANSFER_PAYMENT_METHOD, } from "@/lib/transferencias/constants"; import { formatDecimalForDbRequired } from "@/lib/utils/currency"; @@ -341,12 +342,14 @@ export async function transferBetweenAccountsAction( ); } + const transferNote = `de ${fromAccount.name} -> ${toAccount.name}`; + // Create outgoing transaction (transfer from source account) await tx.insert(lancamentos).values({ condition: TRANSFER_CONDITION, - name: `${TRANSFER_ESTABLISHMENT} → ${toAccount.name}`, + name: TRANSFER_ESTABLISHMENT_SAIDA, paymentMethod: TRANSFER_PAYMENT_METHOD, - note: `Transferência para ${toAccount.name}`, + note: transferNote, amount: formatDecimalForDbRequired(-Math.abs(data.amount)), purchaseDate: data.date, transactionType: "Transferência", @@ -362,9 +365,9 @@ export async function transferBetweenAccountsAction( // Create incoming transaction (transfer to destination account) await tx.insert(lancamentos).values({ condition: TRANSFER_CONDITION, - name: `${TRANSFER_ESTABLISHMENT} ← ${fromAccount.name}`, + name: TRANSFER_ESTABLISHMENT_ENTRADA, paymentMethod: TRANSFER_PAYMENT_METHOD, - note: `Transferência de ${fromAccount.name}`, + note: transferNote, amount: formatDecimalForDbRequired(Math.abs(data.amount)), purchaseDate: data.date, transactionType: "Transferência", diff --git a/app/(dashboard)/estabelecimentos/actions.ts b/app/(dashboard)/estabelecimentos/actions.ts new file mode 100644 index 0000000..4b1f38d --- /dev/null +++ b/app/(dashboard)/estabelecimentos/actions.ts @@ -0,0 +1,102 @@ +"use server"; + +import { and, eq } from "drizzle-orm"; +import { z } from "zod"; +import { estabelecimentos, lancamentos } from "@/db/schema"; +import { + type ActionResult, + handleActionError, + revalidateForEntity, +} from "@/lib/actions/helpers"; +import { getUser } from "@/lib/auth/server"; +import { db } from "@/lib/db"; +import { uuidSchema } from "@/lib/schemas/common"; + +const createSchema = z.object({ + name: z + .string({ message: "Informe o nome do estabelecimento." }) + .trim() + .min(1, "Informe o nome do estabelecimento."), +}); + +const deleteSchema = z.object({ + id: uuidSchema("Estabelecimento"), +}); + +export async function createEstabelecimentoAction( + input: z.infer, +): Promise { + try { + const user = await getUser(); + const data = createSchema.parse(input); + + await db.insert(estabelecimentos).values({ + name: data.name, + userId: user.id, + }); + + revalidateForEntity("estabelecimentos"); + + return { success: true, message: "Estabelecimento criado com sucesso." }; + } catch (error) { + return handleActionError(error); + } +} + +export async function deleteEstabelecimentoAction( + input: z.infer, +): Promise { + try { + const user = await getUser(); + const data = deleteSchema.parse(input); + + const row = await db.query.estabelecimentos.findFirst({ + columns: { id: true, name: true }, + where: and( + eq(estabelecimentos.id, data.id), + eq(estabelecimentos.userId, user.id), + ), + }); + + if (!row) { + return { + success: false, + error: "Estabelecimento não encontrado.", + }; + } + + const [linked] = await db + .select({ id: lancamentos.id }) + .from(lancamentos) + .where( + and( + eq(lancamentos.userId, user.id), + eq(lancamentos.name, row.name), + ), + ) + .limit(1); + + if (linked) { + return { + success: false, + error: + "Não é possível excluir: existem lançamentos vinculados a este estabelecimento. Remova ou altere os lançamentos primeiro.", + }; + } + + await db + .delete(estabelecimentos) + .where( + and( + eq(estabelecimentos.id, data.id), + eq(estabelecimentos.userId, user.id), + ), + ); + + revalidateForEntity("estabelecimentos"); + + return { success: true, message: "Estabelecimento excluído com sucesso." }; + } catch (error) { + return handleActionError(error); + } +} diff --git a/app/(dashboard)/estabelecimentos/data.ts b/app/(dashboard)/estabelecimentos/data.ts new file mode 100644 index 0000000..fb2940f --- /dev/null +++ b/app/(dashboard)/estabelecimentos/data.ts @@ -0,0 +1,66 @@ +import { count, eq } from "drizzle-orm"; +import { estabelecimentos, lancamentos } from "@/db/schema"; +import { db } from "@/lib/db"; + +export type EstabelecimentoRow = { + name: string; + lancamentosCount: number; + estabelecimentoId: string | null; +}; + +export async function fetchEstabelecimentosForUser( + userId: string, +): Promise { + const [countsByName, estabelecimentosRows] = await Promise.all([ + db + .select({ + name: lancamentos.name, + count: count().as("count"), + }) + .from(lancamentos) + .where(eq(lancamentos.userId, userId)) + .groupBy(lancamentos.name), + db.query.estabelecimentos.findMany({ + columns: { id: true, name: true }, + where: eq(estabelecimentos.userId, userId), + }), + ]); + + const map = new Map< + string, + { lancamentosCount: number; estabelecimentoId: string | null } + >(); + + for (const row of countsByName) { + const name = row.name?.trim(); + if (name == null || name.length === 0) continue; + map.set(name, { + lancamentosCount: Number(row.count ?? 0), + estabelecimentoId: null, + }); + } + + for (const row of estabelecimentosRows) { + const name = row.name?.trim(); + if (name == null || name.length === 0) continue; + const existing = map.get(name); + if (existing) { + existing.estabelecimentoId = row.id; + } else { + map.set(name, { + lancamentosCount: 0, + estabelecimentoId: row.id, + }); + } + } + + return Array.from(map.entries()) + .map(([name, data]) => ({ + name, + lancamentosCount: data.lancamentosCount, + estabelecimentoId: data.estabelecimentoId, + })) + .sort((a, b) => + a.name.localeCompare(b.name, "pt-BR", { sensitivity: "base" }), + ); +} diff --git a/app/(dashboard)/estabelecimentos/layout.tsx b/app/(dashboard)/estabelecimentos/layout.tsx new file mode 100644 index 0000000..8c5ec5a --- /dev/null +++ b/app/(dashboard)/estabelecimentos/layout.tsx @@ -0,0 +1,23 @@ +import { RiStore2Line } from "@remixicon/react"; +import PageDescription from "@/components/page-description"; + +export const metadata = { + title: "Estabelecimentos | OpenMonetis", +}; + +export default function RootLayout({ + children, +}: { + children: React.ReactNode; +}) { + return ( +
+ } + title="Estabelecimentos" + subtitle="Gerencie os estabelecimentos dos seus lançamentos. Crie novos, exclua os que não têm lançamentos vinculados e abra o que está vinculado a cada um." + /> + {children} +
+ ); +} diff --git a/app/(dashboard)/estabelecimentos/loading.tsx b/app/(dashboard)/estabelecimentos/loading.tsx new file mode 100644 index 0000000..8f2159c --- /dev/null +++ b/app/(dashboard)/estabelecimentos/loading.tsx @@ -0,0 +1,19 @@ +import { Skeleton } from "@/components/ui/skeleton"; + +export default function Loading() { + return ( +
+
+ +
+
+
+ + + + +
+
+
+ ); +} diff --git a/app/(dashboard)/estabelecimentos/page.tsx b/app/(dashboard)/estabelecimentos/page.tsx new file mode 100644 index 0000000..71a7eba --- /dev/null +++ b/app/(dashboard)/estabelecimentos/page.tsx @@ -0,0 +1,14 @@ +import { EstabelecimentosPage } from "@/components/estabelecimentos/estabelecimentos-page"; +import { getUserId } from "@/lib/auth/server"; +import { fetchEstabelecimentosForUser } from "./data"; + +export default async function Page() { + const userId = await getUserId(); + const rows = await fetchEstabelecimentosForUser(userId); + + return ( +
+ +
+ ); +} diff --git a/app/(dashboard)/lancamentos/actions.ts b/app/(dashboard)/lancamentos/actions.ts index b6364a8..a120b62 100644 --- a/app/(dashboard)/lancamentos/actions.ts +++ b/app/(dashboard)/lancamentos/actions.ts @@ -7,6 +7,7 @@ import { cartoes, categorias, contas, + estabelecimentos, lancamentos, pagadores, } from "@/db/schema"; @@ -1639,43 +1640,64 @@ export async function deleteMultipleLancamentosAction( } } -// Get unique establishment names from the last 3 months +// Get unique establishment names: from estabelecimentos table + last 3 months from lancamentos export async function getRecentEstablishmentsAction(): Promise { try { const user = await getUser(); - // Calculate date 3 months ago const threeMonthsAgo = new Date(); threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3); - // Fetch establishment names from the last 3 months - const results = await db - .select({ name: lancamentos.name }) - .from(lancamentos) - .where( - and( - eq(lancamentos.userId, user.id), - gte(lancamentos.purchaseDate, threeMonthsAgo), - ), - ) - .orderBy(desc(lancamentos.purchaseDate)); - - // Remove duplicates and filter empty names - const uniqueNames = Array.from( - new Set( - results - .map((r) => r.name) - .filter( - (name): name is string => - name != null && - name.trim().length > 0 && - !name.toLowerCase().startsWith("pagamento fatura"), + const [estabelecimentosRows, lancamentosResults] = await Promise.all([ + db.query.estabelecimentos.findMany({ + columns: { name: true }, + where: eq(estabelecimentos.userId, user.id), + }), + db + .select({ name: lancamentos.name }) + .from(lancamentos) + .where( + and( + eq(lancamentos.userId, user.id), + gte(lancamentos.purchaseDate, threeMonthsAgo), ), - ), - ); + ) + .orderBy(desc(lancamentos.purchaseDate)), + ]); - // Return top 50 most recent unique establishments - return uniqueNames.slice(0, 100); + const fromTable = estabelecimentosRows + .map((r) => r.name) + .filter( + (name): name is string => + name != null && name.trim().length > 0, + ); + const fromLancamentos = lancamentosResults + .map((r) => r.name) + .filter( + (name): name is string => + name != null && + name.trim().length > 0 && + !name.toLowerCase().startsWith("pagamento fatura"), + ); + + const seen = new Set(); + const unique: string[] = []; + for (const name of fromTable) { + const key = name.trim(); + if (!seen.has(key)) { + seen.add(key); + unique.push(key); + } + } + for (const name of fromLancamentos) { + const key = name.trim(); + if (!seen.has(key)) { + seen.add(key); + unique.push(key); + } + } + + return unique.slice(0, 100); } catch (error) { console.error("Error fetching recent establishments:", error); return []; diff --git a/components/dashboard/expenses-by-category-widget-with-chart.tsx b/components/dashboard/expenses-by-category-widget-with-chart.tsx index 0dd2de3..904244e 100644 --- a/components/dashboard/expenses-by-category-widget-with-chart.tsx +++ b/components/dashboard/expenses-by-category-widget-with-chart.tsx @@ -16,6 +16,7 @@ import { useIsMobile } from "@/hooks/use-mobile"; import MoneyValues from "@/components/money-values"; import { type ChartConfig, ChartContainer } from "@/components/ui/chart"; import type { ExpensesByCategoryData } from "@/lib/dashboard/categories/expenses-by-category"; +import { getCategoryColor } from "@/lib/utils/category-colors"; import { formatPeriodForUrl } from "@/lib/utils/period"; import { WidgetEmptyState } from "../widget-empty-state"; @@ -51,24 +52,15 @@ export function ExpensesByCategoryWidgetWithChart({ const isMobile = useIsMobile(); const periodParam = formatPeriodForUrl(period); - // Configuração do chart com cores do CSS + // Configuração do chart com as mesmas cores dos ícones das categorias (getCategoryColor) const chartConfig = useMemo(() => { const config: ChartConfig = {}; - const colors = [ - "var(--chart-1)", - "var(--chart-2)", - "var(--chart-3)", - "var(--chart-4)", - "var(--chart-5)", - "var(--chart-1)", - "var(--chart-2)", - ]; if (data.categories.length <= 7) { data.categories.forEach((category, index) => { config[category.categoryId] = { label: category.categoryName, - color: colors[index % colors.length], + color: getCategoryColor(index), }; }); } else { @@ -77,12 +69,12 @@ export function ExpensesByCategoryWidgetWithChart({ top7.forEach((category, index) => { config[category.categoryId] = { label: category.categoryName, - color: colors[index % colors.length], + color: getCategoryColor(index), }; }); config.outros = { label: "Outros", - color: "var(--chart-6)", + color: getCategoryColor(7), }; } diff --git a/components/estabelecimentos/estabelecimento-create-dialog.tsx b/components/estabelecimentos/estabelecimento-create-dialog.tsx new file mode 100644 index 0000000..be7056e --- /dev/null +++ b/components/estabelecimentos/estabelecimento-create-dialog.tsx @@ -0,0 +1,97 @@ +"use client"; + +import { useState, useTransition } from "react"; +import { toast } from "sonner"; +import { createEstabelecimentoAction } from "@/app/(dashboard)/estabelecimentos/actions"; +import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from "@/components/ui/dialog"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { RiAddCircleLine } from "@remixicon/react"; + +interface EstabelecimentoCreateDialogProps { + trigger?: React.ReactNode; +} + +export function EstabelecimentoCreateDialog({ + trigger, +}: EstabelecimentoCreateDialogProps) { + const [open, setOpen] = useState(false); + const [name, setName] = useState(""); + const [isPending, startTransition] = useTransition(); + + const handleSubmit = (e: React.FormEvent) => { + e.preventDefault(); + const trimmed = name.trim(); + if (!trimmed) return; + + startTransition(async () => { + const result = await createEstabelecimentoAction({ name: trimmed }); + if (result.success) { + toast.success(result.message); + setName(""); + setOpen(false); + } else { + toast.error(result.error); + } + }); + }; + + return ( + + + {trigger ?? ( + + )} + + +
+ + Novo estabelecimento + + Adicione um nome para usar nos lançamentos. Ele aparecerá na lista + e nas sugestões ao criar ou editar lançamentos. + + +
+
+ + setName(e.target.value)} + placeholder="Ex: Supermercado, Posto, Farmácia" + disabled={isPending} + autoFocus + /> +
+
+ + + + +
+
+
+ ); +} diff --git a/components/estabelecimentos/estabelecimentos-page.tsx b/components/estabelecimentos/estabelecimentos-page.tsx new file mode 100644 index 0000000..a208bd5 --- /dev/null +++ b/components/estabelecimentos/estabelecimentos-page.tsx @@ -0,0 +1,154 @@ +"use client"; + +import { RiDeleteBin5Line, RiExternalLinkLine } from "@remixicon/react"; +import Link from "next/link"; +import { useCallback, useState } from "react"; +import { toast } from "sonner"; +import { deleteEstabelecimentoAction } from "@/app/(dashboard)/estabelecimentos/actions"; +import { ConfirmActionDialog } from "@/components/confirm-action-dialog"; +import { Button } from "@/components/ui/button"; +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from "@/components/ui/table"; +import { EstabelecimentoLogo } from "@/components/lancamentos/shared/estabelecimento-logo"; +import { EstabelecimentoCreateDialog } from "./estabelecimento-create-dialog"; +import type { EstabelecimentoRow } from "@/app/(dashboard)/estabelecimentos/data"; + +interface EstabelecimentosPageProps { + rows: EstabelecimentoRow[]; +} + +function buildLancamentosUrl(name: string): string { + const params = new URLSearchParams(); + params.set("estabelecimento", name); + return `/lancamentos?${params.toString()}`; +} + +export function EstabelecimentosPage({ rows }: EstabelecimentosPageProps) { + const [deleteOpen, setDeleteOpen] = useState(false); + const [rowToDelete, setRowToDelete] = useState( + null, + ); + + const handleDeleteRequest = useCallback((row: EstabelecimentoRow) => { + setRowToDelete(row); + setDeleteOpen(true); + }, []); + + const handleDeleteOpenChange = useCallback((open: boolean) => { + setDeleteOpen(open); + if (!open) setRowToDelete(null); + }, []); + + const handleDeleteConfirm = useCallback(async () => { + if (!rowToDelete?.estabelecimentoId) return; + + const result = await deleteEstabelecimentoAction({ + id: rowToDelete.estabelecimentoId, + }); + + if (result.success) { + toast.success(result.message); + setDeleteOpen(false); + setRowToDelete(null); + return; + } + + toast.error(result.error); + throw new Error(result.error); + }, [rowToDelete]); + + const canDelete = (row: EstabelecimentoRow) => + row.lancamentosCount === 0 && row.estabelecimentoId != null; + + return ( + <> +
+
+ +
+ + {rows.length === 0 ? ( +
+ Nenhum estabelecimento ainda. Crie um ou use a lista que será + preenchida conforme você adiciona lançamentos. +
+ ) : ( +
+ + + + Estabelecimento + Lançamentos + Ações + + + + {rows.map((row) => ( + + +
+ + {row.name} +
+
+ + {row.lancamentosCount} + + +
+ + +
+
+
+ ))} +
+
+
+ )} +
+ + + + ); +} diff --git a/components/lancamentos/page/lancamentos-page.tsx b/components/lancamentos/page/lancamentos-page.tsx index 7fe938f..ac6b739 100644 --- a/components/lancamentos/page/lancamentos-page.tsx +++ b/components/lancamentos/page/lancamentos-page.tsx @@ -386,6 +386,7 @@ export function LancamentosPage({ pagadorFilterOptions={pagadorFilterOptions} categoriaFilterOptions={categoriaFilterOptions} contaCartaoFilterOptions={contaCartaoFilterOptions} + estabelecimentosOptions={estabelecimentos} selectedPeriod={selectedPeriod} onCreate={allowCreate ? handleCreate : undefined} onMassAdd={allowCreate ? handleMassAdd : undefined} diff --git a/components/lancamentos/shared/estabelecimento-input.tsx b/components/lancamentos/shared/estabelecimento-input.tsx index ab8a8bb..c538595 100644 --- a/components/lancamentos/shared/estabelecimento-input.tsx +++ b/components/lancamentos/shared/estabelecimento-input.tsx @@ -33,7 +33,7 @@ export function EstabelecimentoInput({ value, onChange, estabelecimentos = [], - placeholder = "Ex.: Padaria", + placeholder = "Ex.: Padaria, Transferência, Saldo inicial", required = false, maxLength = 20, }: EstabelecimentoInputProps) { diff --git a/components/lancamentos/table/lancamentos-filters.tsx b/components/lancamentos/table/lancamentos-filters.tsx index ec26803..a5e4ecd 100644 --- a/components/lancamentos/table/lancamentos-filters.tsx +++ b/components/lancamentos/table/lancamentos-filters.tsx @@ -122,6 +122,7 @@ interface LancamentosFiltersProps { pagadorOptions: LancamentoFilterOption[]; categoriaOptions: LancamentoFilterOption[]; contaCartaoOptions: ContaCartaoFilterOption[]; + estabelecimentosOptions?: string[]; className?: string; exportButton?: ReactNode; hideAdvancedFilters?: boolean; @@ -131,6 +132,7 @@ export function LancamentosFilters({ pagadorOptions, categoriaOptions, contaCartaoOptions, + estabelecimentosOptions = [], className, exportButton, hideAdvancedFilters = false, @@ -235,6 +237,16 @@ export function LancamentosFilters({ ? contaCartaoOptions.find((option) => option.slug === contaCartaoValue) : null; + const estabelecimentoParam = searchParams.get("estabelecimento"); + const estabelecimentoOptionsForSelect = [ + ...(estabelecimentoParam && + estabelecimentoParam.trim() && + !estabelecimentosOptions.includes(estabelecimentoParam.trim()) + ? [estabelecimentoParam.trim()] + : []), + ...estabelecimentosOptions, + ]; + const [categoriaOpen, setCategoriaOpen] = useState(false); const [drawerOpen, setDrawerOpen] = useState(false); @@ -244,7 +256,8 @@ export function LancamentosFilters({ searchParams.get("pagamento") || searchParams.get("pagador") || searchParams.get("categoria") || - searchParams.get("contaCartao"); + searchParams.get("contaCartao") || + searchParams.get("estabelecimento"); const handleResetFilters = () => { handleReset(); @@ -518,6 +531,45 @@ export function LancamentosFilters({
+ + {estabelecimentoOptionsForSelect.length > 0 || + estabelecimentoParam?.trim() ? ( +
+ + +
+ ) : null}
diff --git a/components/lancamentos/table/lancamentos-table.tsx b/components/lancamentos/table/lancamentos-table.tsx index b57fc9b..068274d 100644 --- a/components/lancamentos/table/lancamentos-table.tsx +++ b/components/lancamentos/table/lancamentos-table.tsx @@ -715,6 +715,7 @@ type LancamentosTableProps = { pagadorFilterOptions?: LancamentoFilterOption[]; categoriaFilterOptions?: LancamentoFilterOption[]; contaCartaoFilterOptions?: ContaCartaoFilterOption[]; + estabelecimentosOptions?: string[]; selectedPeriod?: string; onCreate?: (type: "Despesa" | "Receita") => void; onMassAdd?: () => void; @@ -741,6 +742,7 @@ export function LancamentosTable({ pagadorFilterOptions = [], categoriaFilterOptions = [], contaCartaoFilterOptions = [], + estabelecimentosOptions = [], selectedPeriod, onCreate, onMassAdd, @@ -921,6 +923,7 @@ export function LancamentosTable({ pagadorOptions={pagadorFilterOptions} categoriaOptions={categoriaFilterOptions} contaCartaoOptions={contaCartaoFilterOptions} + estabelecimentosOptions={estabelecimentosOptions} className="w-full lg:flex-1 lg:justify-end" hideAdvancedFilters={hasOtherUserData} exportButton={ diff --git a/components/sidebar/nav-link.tsx b/components/sidebar/nav-link.tsx index d9bd771..790091c 100644 --- a/components/sidebar/nav-link.tsx +++ b/components/sidebar/nav-link.tsx @@ -13,6 +13,7 @@ import { RiPriceTag3Line, RiSettings2Line, RiSparklingLine, + RiStore2Line, RiTodoLine, } from "@remixicon/react"; @@ -125,6 +126,11 @@ export function createSidebarNavData( url: "/orcamentos", icon: RiFundsLine, }, + { + title: "Estabelecimentos", + url: "/estabelecimentos", + icon: RiStore2Line, + }, ], }, { diff --git a/components/ui/chart.tsx b/components/ui/chart.tsx index 0eff464..206d35c 100644 --- a/components/ui/chart.tsx +++ b/components/ui/chart.tsx @@ -49,24 +49,36 @@ function ChartContainer({ }) { const uniqueId = React.useId(); const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`; + const [mounted, setMounted] = React.useState(false); + + React.useEffect(() => { + setMounted(true); + }, []); return (
-
- - {children} - +
+ {mounted ? ( + + {children} + + ) : null}
diff --git a/db/schema.ts b/db/schema.ts index fa9b6b9..e2dbec8 100644 --- a/db/schema.ts +++ b/db/schema.ts @@ -190,6 +190,30 @@ export const categorias = pgTable( }), ); +export const estabelecimentos = pgTable( + "estabelecimentos", + { + id: uuid("id").primaryKey().default(sql`gen_random_uuid()`), + name: text("nome").notNull(), + userId: text("user_id") + .notNull() + .references(() => user.id, { onDelete: "cascade" }), + createdAt: timestamp("created_at", { + mode: "date", + withTimezone: true, + }) + .notNull() + .defaultNow(), + }, + (table) => ({ + userIdIdx: index("estabelecimentos_user_id_idx").on(table.userId), + userIdNameUnique: uniqueIndex("estabelecimentos_user_id_nome_key").on( + table.userId, + table.name, + ), + }), +); + export const pagadores = pgTable( "pagadores", { @@ -635,6 +659,7 @@ export const userRelations = relations(user, ({ many, one }) => ({ cartoes: many(cartoes), categorias: many(categorias), contas: many(contas), + estabelecimentos: many(estabelecimentos), faturas: many(faturas), lancamentos: many(lancamentos), orcamentos: many(orcamentos), @@ -676,6 +701,16 @@ export const categoriasRelations = relations(categorias, ({ one, many }) => ({ orcamentos: many(orcamentos), })); +export const estabelecimentosRelations = relations( + estabelecimentos, + ({ one }) => ({ + user: one(user, { + fields: [estabelecimentos.userId], + references: [user.id], + }), + }), +); + export const pagadoresRelations = relations(pagadores, ({ one, many }) => ({ user: one(user, { fields: [pagadores.userId], diff --git a/drizzle/0019_add_estabelecimentos.sql b/drizzle/0019_add_estabelecimentos.sql new file mode 100644 index 0000000..b7cb94d --- /dev/null +++ b/drizzle/0019_add_estabelecimentos.sql @@ -0,0 +1,16 @@ +CREATE TABLE IF NOT EXISTS "estabelecimentos" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "nome" text NOT NULL, + "user_id" text NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE INDEX IF NOT EXISTS "estabelecimentos_user_id_idx" ON "estabelecimentos" ("user_id"); + +CREATE UNIQUE INDEX IF NOT EXISTS "estabelecimentos_user_id_nome_key" ON "estabelecimentos" ("user_id", "nome"); + +DO $$ BEGIN + ALTER TABLE "estabelecimentos" ADD CONSTRAINT "estabelecimentos_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action; +EXCEPTION + WHEN duplicate_object THEN null; +END $$; diff --git a/lib/actions/helpers.ts b/lib/actions/helpers.ts index 0271d80..c901a64 100644 --- a/lib/actions/helpers.ts +++ b/lib/actions/helpers.ts @@ -25,6 +25,7 @@ export const revalidateConfig = { cartoes: ["/cartoes", "/contas", "/lancamentos"], contas: ["/contas", "/lancamentos"], categorias: ["/categorias"], + estabelecimentos: ["/estabelecimentos", "/lancamentos"], orcamentos: ["/orcamentos"], pagadores: ["/pagadores"], anotacoes: ["/anotacoes", "/anotacoes/arquivadas"], diff --git a/lib/lancamentos/page-helpers.ts b/lib/lancamentos/page-helpers.ts index 9674985..11cc7e0 100644 --- a/lib/lancamentos/page-helpers.ts +++ b/lib/lancamentos/page-helpers.ts @@ -37,6 +37,7 @@ export type LancamentoSearchFilters = { categoriaFilter: string | null; contaCartaoFilter: string | null; searchFilter: string | null; + estabelecimentoFilter: string | null; }; type BaseSluggedOption = { @@ -122,6 +123,7 @@ export const extractLancamentoSearchFilters = ( categoriaFilter: getSingleParam(params, "categoria"), contaCartaoFilter: getSingleParam(params, "contaCartao"), searchFilter: getSingleParam(params, "q"), + estabelecimentoFilter: getSingleParam(params, "estabelecimento"), }); const normalizeLabel = (value: string | null | undefined) => @@ -368,6 +370,10 @@ export const buildLancamentoWhere = ({ } } + if (filters.estabelecimentoFilter?.trim()) { + where.push(eq(lancamentos.name, filters.estabelecimentoFilter.trim())); + } + const searchPattern = buildSearchPattern(filters.searchFilter); if (searchPattern) { where.push( diff --git a/lib/transferencias/constants.ts b/lib/transferencias/constants.ts index af25310..71fcf54 100644 --- a/lib/transferencias/constants.ts +++ b/lib/transferencias/constants.ts @@ -1,5 +1,7 @@ export const TRANSFER_CATEGORY_NAME = "Transferência interna"; export const TRANSFER_ESTABLISHMENT = "Transf. entre contas"; +export const TRANSFER_ESTABLISHMENT_SAIDA = "Saída - Transf. entre contas"; +export const TRANSFER_ESTABLISHMENT_ENTRADA = "Entrada - Transf. entre contas"; export const TRANSFER_PAGADOR = "Admin"; export const TRANSFER_PAYMENT_METHOD = "Pix"; export const TRANSFER_CONDITION = "À vista"; diff --git a/package.json b/package.json index 779802a..8702c97 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "openmonetis", - "version": "1.6.0", + "version": "1.6.1", "private": true, "scripts": { "dev": "next dev --turbopack", From 7b3979ad8e0380fe05c488d6e93fbde9f490a74f Mon Sep 17 00:00:00 2001 From: Guilherme Bano Date: Fri, 20 Feb 2026 09:59:16 -0300 Subject: [PATCH 3/6] =?UTF-8?q?Feito=20uma=20corre=C3=A7=C3=A3o=20de=20bug?= =?UTF-8?q?=20onde=20o=20di=C3=A1logo=20principal=20de=20nova=20conta=20fe?= =?UTF-8?q?chava=20inesperadamente?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 6 ++++++ components/cartoes/card-dialog.tsx | 27 ++++++++++++++++++++++++--- components/contas/account-dialog.tsx | 27 ++++++++++++++++++++++++--- components/logo-picker.tsx | 8 +++++++- package.json | 2 +- 5 files changed, 62 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c6604dc..b450c0d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ 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/), e este projeto adere ao [Versionamento Semântico](https://semver.org/lang/pt-BR/). +## [1.6.2] - 2026-02-19 + +### Corrigido + +- Bug no mobile onde, ao selecionar um logo no diálogo de criação de conta/cartão, o diálogo principal fechava inesperadamente: adicionado `stopPropagation` nos eventos de click/touch dos botões de logo e delay com `requestAnimationFrame` antes de fechar o seletor de logo + ## [1.6.1] - 2026-02-18 ### Adicionado diff --git a/components/cartoes/card-dialog.tsx b/components/cartoes/card-dialog.tsx index 87d71d3..4ddcbfc 100644 --- a/components/cartoes/card-dialog.tsx +++ b/components/cartoes/card-dialog.tsx @@ -126,7 +126,10 @@ export function CardDialog({ currentName: formState.name, onUpdate: (updates) => { updateFields(updates); - setLogoDialogOpen(false); + // Delay closing to avoid race condition on mobile + requestAnimationFrame(() => { + setLogoDialogOpen(false); + }); }, }); @@ -188,11 +191,29 @@ export function CardDialog({ : "Atualize as informações do cartão selecionado."; const submitLabel = mode === "create" ? "Salvar cartão" : "Atualizar cartão"; + const handleMainDialogOpenChange = useCallback( + (open: boolean) => { + if (!open && logoDialogOpen) { + return; + } + setDialogOpen(open); + }, + [logoDialogOpen, setDialogOpen], + ); + return ( <> - + {trigger ? {trigger} : null} - + { + if (logoDialogOpen) e.preventDefault(); + }} + onInteractOutside={(e) => { + if (logoDialogOpen) e.preventDefault(); + }} + > {title} {description} diff --git a/components/contas/account-dialog.tsx b/components/contas/account-dialog.tsx index f9747f2..81fb443 100644 --- a/components/contas/account-dialog.tsx +++ b/components/contas/account-dialog.tsx @@ -152,7 +152,10 @@ export function AccountDialog({ currentName: formState.name, onUpdate: (updates) => { updateFields(updates); - setLogoDialogOpen(false); + // Delay closing to avoid race condition on mobile + requestAnimationFrame(() => { + setLogoDialogOpen(false); + }); }, }); @@ -205,11 +208,29 @@ export function AccountDialog({ : "Atualize as informações da conta selecionada."; const submitLabel = mode === "create" ? "Salvar conta" : "Atualizar conta"; + const handleMainDialogOpenChange = useCallback( + (open: boolean) => { + if (!open && logoDialogOpen) { + return; + } + setDialogOpen(open); + }, + [logoDialogOpen, setDialogOpen], + ); + return ( <> - + {trigger ? {trigger} : null} - + { + if (logoDialogOpen) e.preventDefault(); + }} + onInteractOutside={(e) => { + if (logoDialogOpen) e.preventDefault(); + }} + > {title} {description} diff --git a/components/logo-picker.tsx b/components/logo-picker.tsx index 44d97e5..786fbe0 100644 --- a/components/logo-picker.tsx +++ b/components/logo-picker.tsx @@ -158,7 +158,13 @@ export function LogoPickerDialog({ + + Atualizar página + + ); +} From 94f6b0a986f5e8aa1abb522675d3cf14a0b91ae3 Mon Sep 17 00:00:00 2001 From: Guilherme Bano Date: Fri, 20 Feb 2026 23:38:13 -0300 Subject: [PATCH 5/6] =?UTF-8?q?Corre=C3=A7=C3=A3o=20de=20integra=C3=A7?= =?UTF-8?q?=C3=A3o=20com=20o=20resend?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 2 +- CHANGELOG.md | 11 +++++++++++ app/(dashboard)/pagadores/[pagadorId]/actions.ts | 4 ++-- docker-compose.yml | 2 +- lib/email/resend.ts | 16 ++++++++++++++++ lib/pagadores/notifications.ts | 4 ++-- package.json | 2 +- 7 files changed, 34 insertions(+), 7 deletions(-) create mode 100644 lib/email/resend.ts diff --git a/.env.example b/.env.example index a97e03d..39627b7 100644 --- a/.env.example +++ b/.env.example @@ -25,7 +25,7 @@ DB_PORT=5432 # === Email (Opcional) === # Provider: Resend (https://resend.com) RESEND_API_KEY= -RESEND_FROM_EMAIL=OpenMonetis +RESEND_FROM_EMAIL="OpenMonetis " # === OAuth (Opcional) === # Google: https://console.cloud.google.com/apis/credentials diff --git a/CHANGELOG.md b/CHANGELOG.md index b450c0d..4c89aa4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,17 @@ 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/), e este projeto adere ao [Versionamento Semântico](https://semver.org/lang/pt-BR/). +## [1.6.3] - 2026-02-19 + +### Corrigido + +- E-mail Resend: variável `RESEND_FROM_EMAIL` não era lida do `.env` (valores com espaço precisam estar entre aspas). Leitura centralizada em `lib/email/resend.ts` com `getResendFromEmail()` e carregamento explícito do `.env` no contexto de Server Actions + +### Alterado + +- `.env.example`: `RESEND_FROM_EMAIL` com valor entre aspas e comentário para uso em Docker/produção +- `docker-compose.yml`: env do app passa `RESEND_FROM_EMAIL` (em vez de `EMAIL_FROM`) para o container, alinhado ao nome usado pela aplicação + ## [1.6.2] - 2026-02-19 ### Corrigido diff --git a/app/(dashboard)/pagadores/[pagadorId]/actions.ts b/app/(dashboard)/pagadores/[pagadorId]/actions.ts index c30e862..e3871ab 100644 --- a/app/(dashboard)/pagadores/[pagadorId]/actions.ts +++ b/app/(dashboard)/pagadores/[pagadorId]/actions.ts @@ -5,6 +5,7 @@ import { revalidatePath } from "next/cache"; import { Resend } from "resend"; import { z } from "zod"; import { lancamentos, pagadores } from "@/db/schema"; +import { getResendFromEmail } from "@/lib/email/resend"; import { getUser } from "@/lib/auth/server"; import { db } from "@/lib/db"; import { @@ -418,8 +419,7 @@ export async function sendPagadorSummaryAction( } const resendApiKey = process.env.RESEND_API_KEY; - const resendFrom = - process.env.RESEND_FROM_EMAIL ?? "OpenMonetis "; + const resendFrom = getResendFromEmail(); if (!resendApiKey) { return { diff --git a/docker-compose.yml b/docker-compose.yml index a8c432f..26b6b8e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -93,7 +93,7 @@ services: # Configurações de email (se usar) RESEND_API_KEY: ${RESEND_API_KEY:-} - EMAIL_FROM: ${EMAIL_FROM:-} + RESEND_FROM_EMAIL: ${RESEND_FROM_EMAIL:-} # Configurações de OAuth (se usar) GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID:-} diff --git a/lib/email/resend.ts b/lib/email/resend.ts new file mode 100644 index 0000000..99482bd --- /dev/null +++ b/lib/email/resend.ts @@ -0,0 +1,16 @@ +import { config } from "dotenv"; + +/** + * Endereço "from" para envio de e-mails via Resend. + * Lê RESEND_FROM_EMAIL do .env (valor deve estar entre aspas se tiver espaço: + * Garante carregamento do .env no contexto da chamada (ex.: Server Actions). + */ +const FALLBACK_FROM = "OpenMonetis "; + +export function getResendFromEmail(): string { + // Garantir que .env foi carregado (não sobrescreve variáveis já definidas) + config({ path: ".env" }); + const raw = process.env.RESEND_FROM_EMAIL; + const value = typeof raw === "string" ? raw.trim() : ""; + return value.length > 0 ? value : FALLBACK_FROM; +} diff --git a/lib/pagadores/notifications.ts b/lib/pagadores/notifications.ts index 1c8fb19..92e92d5 100644 --- a/lib/pagadores/notifications.ts +++ b/lib/pagadores/notifications.ts @@ -1,6 +1,7 @@ import { inArray } from "drizzle-orm"; import { Resend } from "resend"; import { pagadores } from "@/db/schema"; +import { getResendFromEmail } from "@/lib/email/resend"; import { db } from "@/lib/db"; type ActionType = "created" | "deleted"; @@ -118,8 +119,7 @@ export async function sendPagadorAutoEmails({ } const resendApiKey = process.env.RESEND_API_KEY; - const resendFrom = - process.env.RESEND_FROM_EMAIL ?? "OpenMonetis "; + const resendFrom = getResendFromEmail(); if (!resendApiKey) { console.warn( diff --git a/package.json b/package.json index 6797940..df75ced 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "openmonetis", - "version": "1.6.2", + "version": "1.6.3", "private": true, "scripts": { "dev": "next dev --turbopack", From f640990912fff47267c6d5db2138d1c955ecb578 Mon Sep 17 00:00:00 2001 From: Felipe Coutinho Date: Sat, 21 Feb 2026 21:27:37 +0000 Subject: [PATCH 6/6] =?UTF-8?q?chore:=20remover=20p=C3=A1ginas=20estabelec?= =?UTF-8?q?imentos=20e=20gastos-por-categoria?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Remove /estabelecimentos e todos seus componentes e actions - Remove /relatorios/gastos-por-categoria e seus arquivos - Remove tabela `estabelecimentos` do schema e migration 0019 - Remove nav items de ambas as features do sidebar - Reverte widget expenses-by-category ao estado original - Remove filtro de estabelecimento dos lançamentos (filters, table, page-helpers) - Reverte getRecentEstablishmentsAction para query apenas em lancamentos - Limpa CHANGELOG removendo entradas das features removidas --- CHANGELOG.md | 11 - app/(dashboard)/estabelecimentos/actions.ts | 102 ------ app/(dashboard)/estabelecimentos/data.ts | 66 ---- app/(dashboard)/estabelecimentos/layout.tsx | 23 -- app/(dashboard)/estabelecimentos/loading.tsx | 19 - app/(dashboard)/estabelecimentos/page.tsx | 14 - app/(dashboard)/lancamentos/actions.ts | 78 ++-- .../gastos-por-categoria/layout.tsx | 23 -- .../gastos-por-categoria/loading.tsx | 30 -- .../relatorios/gastos-por-categoria/page.tsx | 100 ------ ...expenses-by-category-widget-with-chart.tsx | 334 +++++++----------- .../estabelecimento-create-dialog.tsx | 97 ----- .../estabelecimentos-page.tsx | 154 -------- .../lancamentos/page/lancamentos-page.tsx | 1 - .../lancamentos/table/lancamentos-filters.tsx | 54 +-- .../lancamentos/table/lancamentos-table.tsx | 3 - components/sidebar/nav-link.tsx | 12 - db/schema.ts | 35 -- drizzle/0019_add_estabelecimentos.sql | 16 - lib/lancamentos/page-helpers.ts | 6 - 20 files changed, 155 insertions(+), 1023 deletions(-) delete mode 100644 app/(dashboard)/estabelecimentos/actions.ts delete mode 100644 app/(dashboard)/estabelecimentos/data.ts delete mode 100644 app/(dashboard)/estabelecimentos/layout.tsx delete mode 100644 app/(dashboard)/estabelecimentos/loading.tsx delete mode 100644 app/(dashboard)/estabelecimentos/page.tsx delete mode 100644 app/(dashboard)/relatorios/gastos-por-categoria/layout.tsx delete mode 100644 app/(dashboard)/relatorios/gastos-por-categoria/loading.tsx delete mode 100644 app/(dashboard)/relatorios/gastos-por-categoria/page.tsx delete mode 100644 components/estabelecimentos/estabelecimento-create-dialog.tsx delete mode 100644 components/estabelecimentos/estabelecimentos-page.tsx delete mode 100644 drizzle/0019_add_estabelecimentos.sql diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c89aa4..be1368c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,25 +24,15 @@ e este projeto adere ao [Versionamento Semântico](https://semver.org/lang/pt-BR ## [1.6.1] - 2026-02-18 -### Adicionado - -- Aba "Estabelecimentos" no menu lateral (Gestão Financeira): listagem de estabelecimentos com quantidade de lançamentos, criação de novos, exclusão (apenas quando não há lançamentos vinculados) e link "Ver vinculados" para lançamentos filtrados pelo estabelecimento -- Tabela `estabelecimentos` (migration 0019) e sugestões de estabelecimento nos lançamentos passam a incluir nomes cadastrados nessa tabela -- Filtro "Estabelecimento" no drawer de Filtros da página de lançamentos; parâmetro `estabelecimento` na URL para filtrar por nome - ### Alterado - Transferências entre contas: nome do estabelecimento passa a ser "Saída - Transf. entre contas" na saída e "Entrada - Transf. entre contas" na entrada e adicionando em anotação no formato "de {conta origem} -> {conta destino}" -- Gráfico de pizza (Gastos por categoria): cores das fatias alinhadas às cores dos ícones das categorias na lista (paleta `getCategoryColor`) - ChartContainer (Recharts): renderização do gráfico apenas após montagem no cliente e uso de `minWidth`/`minHeight` no ResponsiveContainer para evitar aviso "width(-1) and height(-1)" no console ## [1.6.0] - 2026-02-18 ### Adicionado -- Item "Gastos por categoria" no menu lateral (seção Análise), com link para `/relatorios/gastos-por-categoria` -- Gráfico de pizza moderno (estilo donut) na página Gastos por categoria: fatias com espaçamento, labels de percentual nas fatias maiores, legenda ao lado -- Fatias do gráfico e itens da legenda clicáveis — navegam para a página de detalhe da categoria no período selecionado - Preferência "Anotações em coluna" em Ajustes > Extrato e lançamentos: quando ativa, a anotação dos lançamentos aparece em coluna na tabela; quando inativa, permanece no balão (tooltip) no ícone - Preferência "Ordem das colunas" em Ajustes > Extrato e lançamentos: lista ordenável por arraste para definir a ordem das colunas na tabela do extrato e dos lançamentos (Estabelecimento, Transação, Valor, etc.); a linha inteira é arrastável - Coluna `extrato_note_as_column` e `lancamentos_column_order` na tabela `preferencias_usuario` (migrations 0017 e 0018) @@ -50,7 +40,6 @@ e este projeto adere ao [Versionamento Semântico](https://semver.org/lang/pt-BR ### Alterado -- Tooltip do gráfico de pizza em Gastos por categoria oculto no mobile (evita informação flutuante em telas pequenas) - Header do dashboard fixo apenas no mobile (`fixed top-0` com `md:static`); conteúdo com `pt-12 md:pt-0` para não ficar sob o header - Abas da página Ajustes (Preferências, Companion, etc.): no mobile, rolagem horizontal com seta indicando mais opções à direita; scrollbar oculta - Botões "Novo orçamento" e "Copiar orçamentos do último mês": no mobile, rolagem horizontal (`h-8`, `text-xs`) diff --git a/app/(dashboard)/estabelecimentos/actions.ts b/app/(dashboard)/estabelecimentos/actions.ts deleted file mode 100644 index 4b1f38d..0000000 --- a/app/(dashboard)/estabelecimentos/actions.ts +++ /dev/null @@ -1,102 +0,0 @@ -"use server"; - -import { and, eq } from "drizzle-orm"; -import { z } from "zod"; -import { estabelecimentos, lancamentos } from "@/db/schema"; -import { - type ActionResult, - handleActionError, - revalidateForEntity, -} from "@/lib/actions/helpers"; -import { getUser } from "@/lib/auth/server"; -import { db } from "@/lib/db"; -import { uuidSchema } from "@/lib/schemas/common"; - -const createSchema = z.object({ - name: z - .string({ message: "Informe o nome do estabelecimento." }) - .trim() - .min(1, "Informe o nome do estabelecimento."), -}); - -const deleteSchema = z.object({ - id: uuidSchema("Estabelecimento"), -}); - -export async function createEstabelecimentoAction( - input: z.infer, -): Promise { - try { - const user = await getUser(); - const data = createSchema.parse(input); - - await db.insert(estabelecimentos).values({ - name: data.name, - userId: user.id, - }); - - revalidateForEntity("estabelecimentos"); - - return { success: true, message: "Estabelecimento criado com sucesso." }; - } catch (error) { - return handleActionError(error); - } -} - -export async function deleteEstabelecimentoAction( - input: z.infer, -): Promise { - try { - const user = await getUser(); - const data = deleteSchema.parse(input); - - const row = await db.query.estabelecimentos.findFirst({ - columns: { id: true, name: true }, - where: and( - eq(estabelecimentos.id, data.id), - eq(estabelecimentos.userId, user.id), - ), - }); - - if (!row) { - return { - success: false, - error: "Estabelecimento não encontrado.", - }; - } - - const [linked] = await db - .select({ id: lancamentos.id }) - .from(lancamentos) - .where( - and( - eq(lancamentos.userId, user.id), - eq(lancamentos.name, row.name), - ), - ) - .limit(1); - - if (linked) { - return { - success: false, - error: - "Não é possível excluir: existem lançamentos vinculados a este estabelecimento. Remova ou altere os lançamentos primeiro.", - }; - } - - await db - .delete(estabelecimentos) - .where( - and( - eq(estabelecimentos.id, data.id), - eq(estabelecimentos.userId, user.id), - ), - ); - - revalidateForEntity("estabelecimentos"); - - return { success: true, message: "Estabelecimento excluído com sucesso." }; - } catch (error) { - return handleActionError(error); - } -} diff --git a/app/(dashboard)/estabelecimentos/data.ts b/app/(dashboard)/estabelecimentos/data.ts deleted file mode 100644 index fb2940f..0000000 --- a/app/(dashboard)/estabelecimentos/data.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { count, eq } from "drizzle-orm"; -import { estabelecimentos, lancamentos } from "@/db/schema"; -import { db } from "@/lib/db"; - -export type EstabelecimentoRow = { - name: string; - lancamentosCount: number; - estabelecimentoId: string | null; -}; - -export async function fetchEstabelecimentosForUser( - userId: string, -): Promise { - const [countsByName, estabelecimentosRows] = await Promise.all([ - db - .select({ - name: lancamentos.name, - count: count().as("count"), - }) - .from(lancamentos) - .where(eq(lancamentos.userId, userId)) - .groupBy(lancamentos.name), - db.query.estabelecimentos.findMany({ - columns: { id: true, name: true }, - where: eq(estabelecimentos.userId, userId), - }), - ]); - - const map = new Map< - string, - { lancamentosCount: number; estabelecimentoId: string | null } - >(); - - for (const row of countsByName) { - const name = row.name?.trim(); - if (name == null || name.length === 0) continue; - map.set(name, { - lancamentosCount: Number(row.count ?? 0), - estabelecimentoId: null, - }); - } - - for (const row of estabelecimentosRows) { - const name = row.name?.trim(); - if (name == null || name.length === 0) continue; - const existing = map.get(name); - if (existing) { - existing.estabelecimentoId = row.id; - } else { - map.set(name, { - lancamentosCount: 0, - estabelecimentoId: row.id, - }); - } - } - - return Array.from(map.entries()) - .map(([name, data]) => ({ - name, - lancamentosCount: data.lancamentosCount, - estabelecimentoId: data.estabelecimentoId, - })) - .sort((a, b) => - a.name.localeCompare(b.name, "pt-BR", { sensitivity: "base" }), - ); -} diff --git a/app/(dashboard)/estabelecimentos/layout.tsx b/app/(dashboard)/estabelecimentos/layout.tsx deleted file mode 100644 index 8c5ec5a..0000000 --- a/app/(dashboard)/estabelecimentos/layout.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { RiStore2Line } from "@remixicon/react"; -import PageDescription from "@/components/page-description"; - -export const metadata = { - title: "Estabelecimentos | OpenMonetis", -}; - -export default function RootLayout({ - children, -}: { - children: React.ReactNode; -}) { - return ( -
- } - title="Estabelecimentos" - subtitle="Gerencie os estabelecimentos dos seus lançamentos. Crie novos, exclua os que não têm lançamentos vinculados e abra o que está vinculado a cada um." - /> - {children} -
- ); -} diff --git a/app/(dashboard)/estabelecimentos/loading.tsx b/app/(dashboard)/estabelecimentos/loading.tsx deleted file mode 100644 index 8f2159c..0000000 --- a/app/(dashboard)/estabelecimentos/loading.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { Skeleton } from "@/components/ui/skeleton"; - -export default function Loading() { - return ( -
-
- -
-
-
- - - - -
-
-
- ); -} diff --git a/app/(dashboard)/estabelecimentos/page.tsx b/app/(dashboard)/estabelecimentos/page.tsx deleted file mode 100644 index 71a7eba..0000000 --- a/app/(dashboard)/estabelecimentos/page.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { EstabelecimentosPage } from "@/components/estabelecimentos/estabelecimentos-page"; -import { getUserId } from "@/lib/auth/server"; -import { fetchEstabelecimentosForUser } from "./data"; - -export default async function Page() { - const userId = await getUserId(); - const rows = await fetchEstabelecimentosForUser(userId); - - return ( -
- -
- ); -} diff --git a/app/(dashboard)/lancamentos/actions.ts b/app/(dashboard)/lancamentos/actions.ts index a120b62..b6364a8 100644 --- a/app/(dashboard)/lancamentos/actions.ts +++ b/app/(dashboard)/lancamentos/actions.ts @@ -7,7 +7,6 @@ import { cartoes, categorias, contas, - estabelecimentos, lancamentos, pagadores, } from "@/db/schema"; @@ -1640,64 +1639,43 @@ export async function deleteMultipleLancamentosAction( } } -// Get unique establishment names: from estabelecimentos table + last 3 months from lancamentos +// Get unique establishment names from the last 3 months export async function getRecentEstablishmentsAction(): Promise { try { const user = await getUser(); + // Calculate date 3 months ago const threeMonthsAgo = new Date(); threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3); - const [estabelecimentosRows, lancamentosResults] = await Promise.all([ - db.query.estabelecimentos.findMany({ - columns: { name: true }, - where: eq(estabelecimentos.userId, user.id), - }), - db - .select({ name: lancamentos.name }) - .from(lancamentos) - .where( - and( - eq(lancamentos.userId, user.id), - gte(lancamentos.purchaseDate, threeMonthsAgo), + // Fetch establishment names from the last 3 months + const results = await db + .select({ name: lancamentos.name }) + .from(lancamentos) + .where( + and( + eq(lancamentos.userId, user.id), + gte(lancamentos.purchaseDate, threeMonthsAgo), + ), + ) + .orderBy(desc(lancamentos.purchaseDate)); + + // Remove duplicates and filter empty names + const uniqueNames = Array.from( + new Set( + results + .map((r) => r.name) + .filter( + (name): name is string => + name != null && + name.trim().length > 0 && + !name.toLowerCase().startsWith("pagamento fatura"), ), - ) - .orderBy(desc(lancamentos.purchaseDate)), - ]); + ), + ); - const fromTable = estabelecimentosRows - .map((r) => r.name) - .filter( - (name): name is string => - name != null && name.trim().length > 0, - ); - const fromLancamentos = lancamentosResults - .map((r) => r.name) - .filter( - (name): name is string => - name != null && - name.trim().length > 0 && - !name.toLowerCase().startsWith("pagamento fatura"), - ); - - const seen = new Set(); - const unique: string[] = []; - for (const name of fromTable) { - const key = name.trim(); - if (!seen.has(key)) { - seen.add(key); - unique.push(key); - } - } - for (const name of fromLancamentos) { - const key = name.trim(); - if (!seen.has(key)) { - seen.add(key); - unique.push(key); - } - } - - return unique.slice(0, 100); + // Return top 50 most recent unique establishments + return uniqueNames.slice(0, 100); } catch (error) { console.error("Error fetching recent establishments:", error); return []; diff --git a/app/(dashboard)/relatorios/gastos-por-categoria/layout.tsx b/app/(dashboard)/relatorios/gastos-por-categoria/layout.tsx deleted file mode 100644 index 9942029..0000000 --- a/app/(dashboard)/relatorios/gastos-por-categoria/layout.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { RiPieChartLine } from "@remixicon/react"; -import PageDescription from "@/components/page-description"; - -export const metadata = { - title: "Gastos por categoria | OpenMonetis", -}; - -export default function GastosPorCategoriaLayout({ - children, -}: { - children: React.ReactNode; -}) { - return ( -
- } - title="Gastos por categoria" - subtitle="Visualize suas despesas divididas por categoria no mês selecionado. Altere o mês para comparar períodos." - /> - {children} -
- ); -} diff --git a/app/(dashboard)/relatorios/gastos-por-categoria/loading.tsx b/app/(dashboard)/relatorios/gastos-por-categoria/loading.tsx deleted file mode 100644 index 895a15e..0000000 --- a/app/(dashboard)/relatorios/gastos-por-categoria/loading.tsx +++ /dev/null @@ -1,30 +0,0 @@ -import { Skeleton } from "@/components/ui/skeleton"; - -export default function GastosPorCategoriaLoading() { - return ( -
-
- -
-
- - -
-
- {Array.from({ length: 5 }).map((_, i) => ( -
-
- -
- - -
-
- -
- ))} -
-
-
- ); -} diff --git a/app/(dashboard)/relatorios/gastos-por-categoria/page.tsx b/app/(dashboard)/relatorios/gastos-por-categoria/page.tsx deleted file mode 100644 index 2fa7a57..0000000 --- a/app/(dashboard)/relatorios/gastos-por-categoria/page.tsx +++ /dev/null @@ -1,100 +0,0 @@ -import { - RiArrowDownSFill, - RiArrowUpSFill, - RiPieChartLine, -} from "@remixicon/react"; -import MonthNavigation from "@/components/month-picker/month-navigation"; -import { ExpensesByCategoryWidgetWithChart } from "@/components/dashboard/expenses-by-category-widget-with-chart"; -import MoneyValues from "@/components/money-values"; -import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; -import { getUserId } from "@/lib/auth/server"; -import { fetchExpensesByCategory } from "@/lib/dashboard/categories/expenses-by-category"; -import { calculatePercentageChange } from "@/lib/utils/math"; -import { parsePeriodParam } from "@/lib/utils/period"; - -type PageSearchParams = Promise>; - -type PageProps = { - searchParams?: PageSearchParams; -}; - -const getSingleParam = ( - params: Record | undefined, - key: string, -) => { - const value = params?.[key]; - if (!value) return null; - return Array.isArray(value) ? (value[0] ?? null) : value; -}; - -export default async function GastosPorCategoriaPage({ - searchParams, -}: PageProps) { - const userId = await getUserId(); - const resolvedSearchParams = searchParams ? await searchParams : undefined; - const periodoParam = getSingleParam(resolvedSearchParams, "periodo"); - - const { period: selectedPeriod } = parsePeriodParam(periodoParam); - - const data = await fetchExpensesByCategory(userId, selectedPeriod); - const percentageChange = calculatePercentageChange( - data.currentTotal, - data.previousTotal, - ); - const hasIncrease = percentageChange !== null && percentageChange > 0; - const hasDecrease = percentageChange !== null && percentageChange < 0; - - return ( -
- - - - - - - Resumo do mês - - - -
-
-

- Total de despesas no mês -

- -
- {percentageChange !== null && ( - - {hasIncrease && } - {hasDecrease && } - {percentageChange > 0 ? "+" : ""} - {percentageChange.toFixed(1)}% em relação ao mês anterior - - )} -
-

- Mês anterior: -

-
-
- - - - -
- ); -} diff --git a/components/dashboard/expenses-by-category-widget-with-chart.tsx b/components/dashboard/expenses-by-category-widget-with-chart.tsx index 904244e..669a825 100644 --- a/components/dashboard/expenses-by-category-widget-with-chart.tsx +++ b/components/dashboard/expenses-by-category-widget-with-chart.tsx @@ -4,20 +4,20 @@ import { RiArrowDownSFill, RiArrowUpSFill, RiExternalLinkLine, + RiListUnordered, + RiPieChart2Line, RiPieChartLine, RiWallet3Line, } from "@remixicon/react"; import Link from "next/link"; -import { useRouter } from "next/navigation"; -import { useMemo } from "react"; -import { Cell, Pie, PieChart, Tooltip } from "recharts"; +import { useMemo, useState } from "react"; +import { Pie, PieChart, Tooltip } from "recharts"; import { CategoryIconBadge } from "@/components/categorias/category-icon-badge"; -import { useIsMobile } from "@/hooks/use-mobile"; import MoneyValues from "@/components/money-values"; import { type ChartConfig, ChartContainer } from "@/components/ui/chart"; import type { ExpensesByCategoryData } from "@/lib/dashboard/categories/expenses-by-category"; -import { getCategoryColor } from "@/lib/utils/category-colors"; import { formatPeriodForUrl } from "@/lib/utils/period"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs"; import { WidgetEmptyState } from "../widget-empty-state"; type ExpensesByCategoryWidgetWithChartProps = { @@ -35,32 +35,31 @@ const formatCurrency = (value: number) => currency: "BRL", }).format(value); -type ChartDataItem = { - category: string; - name: string; - value: number; - percentage: number; - fill: string | undefined; - href: string | undefined; -}; - export function ExpensesByCategoryWidgetWithChart({ data, period, }: ExpensesByCategoryWidgetWithChartProps) { - const router = useRouter(); - const isMobile = useIsMobile(); + const [activeTab, setActiveTab] = useState<"list" | "chart">("list"); const periodParam = formatPeriodForUrl(period); - // Configuração do chart com as mesmas cores dos ícones das categorias (getCategoryColor) + // Configuração do chart com cores do CSS const chartConfig = useMemo(() => { const config: ChartConfig = {}; + const colors = [ + "var(--chart-1)", + "var(--chart-2)", + "var(--chart-3)", + "var(--chart-4)", + "var(--chart-5)", + "var(--chart-1)", + "var(--chart-2)", + ]; if (data.categories.length <= 7) { data.categories.forEach((category, index) => { config[category.categoryId] = { label: category.categoryName, - color: getCategoryColor(index), + color: colors[index % colors.length], }; }); } else { @@ -69,80 +68,62 @@ export function ExpensesByCategoryWidgetWithChart({ top7.forEach((category, index) => { config[category.categoryId] = { label: category.categoryName, - color: getCategoryColor(index), + color: colors[index % colors.length], }; }); config.outros = { label: "Outros", - color: getCategoryColor(7), + color: "var(--chart-6)", }; } return config; }, [data.categories]); - // Preparar dados para o gráfico de pizza - Top 7 + Outros (com href para navegação) - const chartData = useMemo((): ChartDataItem[] => { - const buildItem = ( - categoryId: string, - name: string, - value: number, - percentage: number, - fill: string | undefined, - ): ChartDataItem => ({ - category: categoryId, - name, - value, - percentage, - fill, - href: - categoryId === "outros" - ? undefined - : `/categorias/${categoryId}?periodo=${periodParam}`, - }); - + // Preparar dados para o gráfico de pizza - Top 7 + Outros + const chartData = useMemo(() => { if (data.categories.length <= 7) { - return data.categories.map((category) => - buildItem( - category.categoryId, - category.categoryName, - category.currentAmount, - category.percentageOfTotal, - chartConfig[category.categoryId]?.color, - ), - ); + return data.categories.map((category) => ({ + category: category.categoryId, + name: category.categoryName, + value: category.currentAmount, + percentage: category.percentageOfTotal, + fill: chartConfig[category.categoryId]?.color, + })); } + // Pegar top 7 categorias const top7 = data.categories.slice(0, 7); const others = data.categories.slice(7); + + // Somar o restante const othersTotal = others.reduce((sum, cat) => sum + cat.currentAmount, 0); const othersPercentage = others.reduce( (sum, cat) => sum + cat.percentageOfTotal, 0, ); - const top7Data = top7.map((category) => - buildItem( - category.categoryId, - category.categoryName, - category.currentAmount, - category.percentageOfTotal, - chartConfig[category.categoryId]?.color, - ), - ); + const top7Data = top7.map((category) => ({ + category: category.categoryId, + name: category.categoryName, + value: category.currentAmount, + percentage: category.percentageOfTotal, + fill: chartConfig[category.categoryId]?.color, + })); + + // Adicionar "Outros" se houver if (others.length > 0) { - top7Data.push( - buildItem( - "outros", - "Outros", - othersTotal, - othersPercentage, - chartConfig.outros?.color, - ), - ); + top7Data.push({ + category: "outros", + name: "Outros", + value: othersTotal, + percentage: othersPercentage, + fill: chartConfig.outros?.color, + }); } + return top7Data; - }, [data.categories, chartConfig, periodParam]); + }, [data.categories, chartConfig]); if (data.categories.length === 0) { return ( @@ -155,146 +136,25 @@ export function ExpensesByCategoryWidgetWithChart({ } return ( -
- {/* Gráfico de pizza (donut) — fatias clicáveis */} -
- - - { - if (payload?.href) router.push(payload.href); - }} - label={(props: { - cx?: number; - cy?: number; - midAngle?: number; - innerRadius?: number; - outerRadius?: number; - percent?: number; - }) => { - const { cx = 0, cy = 0, midAngle = 0, innerRadius = 0, outerRadius = 0, percent = 0 } = props; - const percentage = percent * 100; - if (percentage < 6) return null; - const radius = (Number(innerRadius) + Number(outerRadius)) / 2; - const x = cx + radius * Math.cos(-midAngle * (Math.PI / 180)); - const y = cy + radius * Math.sin(-midAngle * (Math.PI / 180)); - return ( - - {formatPercentage(percentage)} - - ); - }} - labelLine={false} - > - {chartData.map((entry, index) => ( - - ))} - - {!isMobile && ( - { - if (active && payload?.length) { - const d = payload[0].payload as ChartDataItem; - return ( -
-
- - {d.name} - - - {formatCurrency(d.value)} - - - {formatPercentage(d.percentage)} do total - - {d.href && ( - - Clique para ver detalhes - - )} -
-
- ); - } - return null; - }} - cursor={false} - /> - )} -
-
- - {/* Legenda clicável */} -
- {chartData.map((entry, index) => { - const content = ( - <> - - - {entry.name} - - - {formatPercentage(entry.percentage)} - - - ); - return entry.href ? ( - - {content} - - ) : ( -
- {content} -
- ); - })} -
+ setActiveTab(v as "list" | "chart")} + className="w-full" + > +
+ + + + Lista + + + + Gráfico + +
- {/* Lista de categorias */} -
+
{data.categories.map((category, index) => { const hasIncrease = @@ -404,7 +264,65 @@ export function ExpensesByCategoryWidgetWithChart({ ); })}
-
-
+ + + +
+ + + formatPercentage(entry.percentage)} + outerRadius={75} + dataKey="value" + nameKey="category" + /> + { + if (active && payload && payload.length) { + const data = payload[0].payload; + return ( +
+
+
+ + {data.name} + + + {formatCurrency(data.value)} + + + {formatPercentage(data.percentage)} do total + +
+
+
+ ); + } + return null; + }} + /> +
+
+ +
+ {chartData.map((entry, index) => ( +
+
+ + {entry.name} + +
+ ))} +
+
+ + ); } diff --git a/components/estabelecimentos/estabelecimento-create-dialog.tsx b/components/estabelecimentos/estabelecimento-create-dialog.tsx deleted file mode 100644 index be7056e..0000000 --- a/components/estabelecimentos/estabelecimento-create-dialog.tsx +++ /dev/null @@ -1,97 +0,0 @@ -"use client"; - -import { useState, useTransition } from "react"; -import { toast } from "sonner"; -import { createEstabelecimentoAction } from "@/app/(dashboard)/estabelecimentos/actions"; -import { Button } from "@/components/ui/button"; -import { - Dialog, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, - DialogTrigger, -} from "@/components/ui/dialog"; -import { Input } from "@/components/ui/input"; -import { Label } from "@/components/ui/label"; -import { RiAddCircleLine } from "@remixicon/react"; - -interface EstabelecimentoCreateDialogProps { - trigger?: React.ReactNode; -} - -export function EstabelecimentoCreateDialog({ - trigger, -}: EstabelecimentoCreateDialogProps) { - const [open, setOpen] = useState(false); - const [name, setName] = useState(""); - const [isPending, startTransition] = useTransition(); - - const handleSubmit = (e: React.FormEvent) => { - e.preventDefault(); - const trimmed = name.trim(); - if (!trimmed) return; - - startTransition(async () => { - const result = await createEstabelecimentoAction({ name: trimmed }); - if (result.success) { - toast.success(result.message); - setName(""); - setOpen(false); - } else { - toast.error(result.error); - } - }); - }; - - return ( - - - {trigger ?? ( - - )} - - -
- - Novo estabelecimento - - Adicione um nome para usar nos lançamentos. Ele aparecerá na lista - e nas sugestões ao criar ou editar lançamentos. - - -
-
- - setName(e.target.value)} - placeholder="Ex: Supermercado, Posto, Farmácia" - disabled={isPending} - autoFocus - /> -
-
- - - - -
-
-
- ); -} diff --git a/components/estabelecimentos/estabelecimentos-page.tsx b/components/estabelecimentos/estabelecimentos-page.tsx deleted file mode 100644 index a208bd5..0000000 --- a/components/estabelecimentos/estabelecimentos-page.tsx +++ /dev/null @@ -1,154 +0,0 @@ -"use client"; - -import { RiDeleteBin5Line, RiExternalLinkLine } from "@remixicon/react"; -import Link from "next/link"; -import { useCallback, useState } from "react"; -import { toast } from "sonner"; -import { deleteEstabelecimentoAction } from "@/app/(dashboard)/estabelecimentos/actions"; -import { ConfirmActionDialog } from "@/components/confirm-action-dialog"; -import { Button } from "@/components/ui/button"; -import { - Table, - TableBody, - TableCell, - TableHead, - TableHeader, - TableRow, -} from "@/components/ui/table"; -import { EstabelecimentoLogo } from "@/components/lancamentos/shared/estabelecimento-logo"; -import { EstabelecimentoCreateDialog } from "./estabelecimento-create-dialog"; -import type { EstabelecimentoRow } from "@/app/(dashboard)/estabelecimentos/data"; - -interface EstabelecimentosPageProps { - rows: EstabelecimentoRow[]; -} - -function buildLancamentosUrl(name: string): string { - const params = new URLSearchParams(); - params.set("estabelecimento", name); - return `/lancamentos?${params.toString()}`; -} - -export function EstabelecimentosPage({ rows }: EstabelecimentosPageProps) { - const [deleteOpen, setDeleteOpen] = useState(false); - const [rowToDelete, setRowToDelete] = useState( - null, - ); - - const handleDeleteRequest = useCallback((row: EstabelecimentoRow) => { - setRowToDelete(row); - setDeleteOpen(true); - }, []); - - const handleDeleteOpenChange = useCallback((open: boolean) => { - setDeleteOpen(open); - if (!open) setRowToDelete(null); - }, []); - - const handleDeleteConfirm = useCallback(async () => { - if (!rowToDelete?.estabelecimentoId) return; - - const result = await deleteEstabelecimentoAction({ - id: rowToDelete.estabelecimentoId, - }); - - if (result.success) { - toast.success(result.message); - setDeleteOpen(false); - setRowToDelete(null); - return; - } - - toast.error(result.error); - throw new Error(result.error); - }, [rowToDelete]); - - const canDelete = (row: EstabelecimentoRow) => - row.lancamentosCount === 0 && row.estabelecimentoId != null; - - return ( - <> -
-
- -
- - {rows.length === 0 ? ( -
- Nenhum estabelecimento ainda. Crie um ou use a lista que será - preenchida conforme você adiciona lançamentos. -
- ) : ( -
- - - - Estabelecimento - Lançamentos - Ações - - - - {rows.map((row) => ( - - -
- - {row.name} -
-
- - {row.lancamentosCount} - - -
- - -
-
-
- ))} -
-
-
- )} -
- - - - ); -} diff --git a/components/lancamentos/page/lancamentos-page.tsx b/components/lancamentos/page/lancamentos-page.tsx index ac6b739..7fe938f 100644 --- a/components/lancamentos/page/lancamentos-page.tsx +++ b/components/lancamentos/page/lancamentos-page.tsx @@ -386,7 +386,6 @@ export function LancamentosPage({ pagadorFilterOptions={pagadorFilterOptions} categoriaFilterOptions={categoriaFilterOptions} contaCartaoFilterOptions={contaCartaoFilterOptions} - estabelecimentosOptions={estabelecimentos} selectedPeriod={selectedPeriod} onCreate={allowCreate ? handleCreate : undefined} onMassAdd={allowCreate ? handleMassAdd : undefined} diff --git a/components/lancamentos/table/lancamentos-filters.tsx b/components/lancamentos/table/lancamentos-filters.tsx index a5e4ecd..ec26803 100644 --- a/components/lancamentos/table/lancamentos-filters.tsx +++ b/components/lancamentos/table/lancamentos-filters.tsx @@ -122,7 +122,6 @@ interface LancamentosFiltersProps { pagadorOptions: LancamentoFilterOption[]; categoriaOptions: LancamentoFilterOption[]; contaCartaoOptions: ContaCartaoFilterOption[]; - estabelecimentosOptions?: string[]; className?: string; exportButton?: ReactNode; hideAdvancedFilters?: boolean; @@ -132,7 +131,6 @@ export function LancamentosFilters({ pagadorOptions, categoriaOptions, contaCartaoOptions, - estabelecimentosOptions = [], className, exportButton, hideAdvancedFilters = false, @@ -237,16 +235,6 @@ export function LancamentosFilters({ ? contaCartaoOptions.find((option) => option.slug === contaCartaoValue) : null; - const estabelecimentoParam = searchParams.get("estabelecimento"); - const estabelecimentoOptionsForSelect = [ - ...(estabelecimentoParam && - estabelecimentoParam.trim() && - !estabelecimentosOptions.includes(estabelecimentoParam.trim()) - ? [estabelecimentoParam.trim()] - : []), - ...estabelecimentosOptions, - ]; - const [categoriaOpen, setCategoriaOpen] = useState(false); const [drawerOpen, setDrawerOpen] = useState(false); @@ -256,8 +244,7 @@ export function LancamentosFilters({ searchParams.get("pagamento") || searchParams.get("pagador") || searchParams.get("categoria") || - searchParams.get("contaCartao") || - searchParams.get("estabelecimento"); + searchParams.get("contaCartao"); const handleResetFilters = () => { handleReset(); @@ -531,45 +518,6 @@ export function LancamentosFilters({
- - {estabelecimentoOptionsForSelect.length > 0 || - estabelecimentoParam?.trim() ? ( -
- - -
- ) : null}
diff --git a/components/lancamentos/table/lancamentos-table.tsx b/components/lancamentos/table/lancamentos-table.tsx index 068274d..b57fc9b 100644 --- a/components/lancamentos/table/lancamentos-table.tsx +++ b/components/lancamentos/table/lancamentos-table.tsx @@ -715,7 +715,6 @@ type LancamentosTableProps = { pagadorFilterOptions?: LancamentoFilterOption[]; categoriaFilterOptions?: LancamentoFilterOption[]; contaCartaoFilterOptions?: ContaCartaoFilterOption[]; - estabelecimentosOptions?: string[]; selectedPeriod?: string; onCreate?: (type: "Despesa" | "Receita") => void; onMassAdd?: () => void; @@ -742,7 +741,6 @@ export function LancamentosTable({ pagadorFilterOptions = [], categoriaFilterOptions = [], contaCartaoFilterOptions = [], - estabelecimentosOptions = [], selectedPeriod, onCreate, onMassAdd, @@ -923,7 +921,6 @@ export function LancamentosTable({ pagadorOptions={pagadorFilterOptions} categoriaOptions={categoriaFilterOptions} contaCartaoOptions={contaCartaoFilterOptions} - estabelecimentosOptions={estabelecimentosOptions} className="w-full lg:flex-1 lg:justify-end" hideAdvancedFilters={hasOtherUserData} exportButton={ diff --git a/components/sidebar/nav-link.tsx b/components/sidebar/nav-link.tsx index 790091c..268eec0 100644 --- a/components/sidebar/nav-link.tsx +++ b/components/sidebar/nav-link.tsx @@ -7,13 +7,11 @@ import { RiDashboardLine, RiFileChartLine, RiFundsLine, - RiPieChartLine, RiGroupLine, RiInboxLine, RiPriceTag3Line, RiSettings2Line, RiSparklingLine, - RiStore2Line, RiTodoLine, } from "@remixicon/react"; @@ -126,11 +124,6 @@ export function createSidebarNavData( url: "/orcamentos", icon: RiFundsLine, }, - { - title: "Estabelecimentos", - url: "/estabelecimentos", - icon: RiStore2Line, - }, ], }, { @@ -167,11 +160,6 @@ export function createSidebarNavData( url: "/relatorios/tendencias", icon: RiFileChartLine, }, - { - title: "Gastos por categoria", - url: "/relatorios/gastos-por-categoria", - icon: RiPieChartLine, - }, { title: "Uso de Cartões", url: "/relatorios/uso-cartoes", diff --git a/db/schema.ts b/db/schema.ts index e2dbec8..fa9b6b9 100644 --- a/db/schema.ts +++ b/db/schema.ts @@ -190,30 +190,6 @@ export const categorias = pgTable( }), ); -export const estabelecimentos = pgTable( - "estabelecimentos", - { - id: uuid("id").primaryKey().default(sql`gen_random_uuid()`), - name: text("nome").notNull(), - userId: text("user_id") - .notNull() - .references(() => user.id, { onDelete: "cascade" }), - createdAt: timestamp("created_at", { - mode: "date", - withTimezone: true, - }) - .notNull() - .defaultNow(), - }, - (table) => ({ - userIdIdx: index("estabelecimentos_user_id_idx").on(table.userId), - userIdNameUnique: uniqueIndex("estabelecimentos_user_id_nome_key").on( - table.userId, - table.name, - ), - }), -); - export const pagadores = pgTable( "pagadores", { @@ -659,7 +635,6 @@ export const userRelations = relations(user, ({ many, one }) => ({ cartoes: many(cartoes), categorias: many(categorias), contas: many(contas), - estabelecimentos: many(estabelecimentos), faturas: many(faturas), lancamentos: many(lancamentos), orcamentos: many(orcamentos), @@ -701,16 +676,6 @@ export const categoriasRelations = relations(categorias, ({ one, many }) => ({ orcamentos: many(orcamentos), })); -export const estabelecimentosRelations = relations( - estabelecimentos, - ({ one }) => ({ - user: one(user, { - fields: [estabelecimentos.userId], - references: [user.id], - }), - }), -); - export const pagadoresRelations = relations(pagadores, ({ one, many }) => ({ user: one(user, { fields: [pagadores.userId], diff --git a/drizzle/0019_add_estabelecimentos.sql b/drizzle/0019_add_estabelecimentos.sql deleted file mode 100644 index b7cb94d..0000000 --- a/drizzle/0019_add_estabelecimentos.sql +++ /dev/null @@ -1,16 +0,0 @@ -CREATE TABLE IF NOT EXISTS "estabelecimentos" ( - "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, - "nome" text NOT NULL, - "user_id" text NOT NULL, - "created_at" timestamp with time zone DEFAULT now() NOT NULL -); - -CREATE INDEX IF NOT EXISTS "estabelecimentos_user_id_idx" ON "estabelecimentos" ("user_id"); - -CREATE UNIQUE INDEX IF NOT EXISTS "estabelecimentos_user_id_nome_key" ON "estabelecimentos" ("user_id", "nome"); - -DO $$ BEGIN - ALTER TABLE "estabelecimentos" ADD CONSTRAINT "estabelecimentos_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action; -EXCEPTION - WHEN duplicate_object THEN null; -END $$; diff --git a/lib/lancamentos/page-helpers.ts b/lib/lancamentos/page-helpers.ts index 11cc7e0..9674985 100644 --- a/lib/lancamentos/page-helpers.ts +++ b/lib/lancamentos/page-helpers.ts @@ -37,7 +37,6 @@ export type LancamentoSearchFilters = { categoriaFilter: string | null; contaCartaoFilter: string | null; searchFilter: string | null; - estabelecimentoFilter: string | null; }; type BaseSluggedOption = { @@ -123,7 +122,6 @@ export const extractLancamentoSearchFilters = ( categoriaFilter: getSingleParam(params, "categoria"), contaCartaoFilter: getSingleParam(params, "contaCartao"), searchFilter: getSingleParam(params, "q"), - estabelecimentoFilter: getSingleParam(params, "estabelecimento"), }); const normalizeLabel = (value: string | null | undefined) => @@ -370,10 +368,6 @@ export const buildLancamentoWhere = ({ } } - if (filters.estabelecimentoFilter?.trim()) { - where.push(eq(lancamentos.name, filters.estabelecimentoFilter.trim())); - } - const searchPattern = buildSearchPattern(filters.searchFilter); if (searchPattern) { where.push(