feat: implementar relatórios de categorias e substituir seleção de período por picker visual

BREAKING CHANGE: Remove feature de seleção de período das preferências do usuário

  Alterações principais:

  - Adiciona sistema completo de relatórios por categoria
    - Cria página /relatorios/categorias com filtros e visualizações
    - Implementa tabela e gráfico de evolução mensal
    - Adiciona funcionalidade de exportação de dados
    - Cria skeleton otimizado para melhor UX de loading

  - Remove feature de seleção de período das preferências
    - Deleta lib/user-preferences/period.ts
    - Remove colunas periodMonthsBefore e periodMonthsAfter do schema
    - Remove todas as referências em 16+ arquivos
    - Atualiza database schema via Drizzle

  - Substitui Select de período por MonthPicker visual
    - Implementa componente PeriodPicker reutilizável
    - Integra shadcn MonthPicker customizado (português, Remix icons)
    - Substitui createMonthOptions em todos os formulários
    - Mantém formato "YYYY-MM" no banco de dados

  - Melhora design da tabela de relatórios
    - Mescla colunas Categoria e Tipo em uma única coluna
    - Substitui badge de tipo por dot colorido discreto
    - Reduz largura da tabela em ~120px
    - Atualiza skeleton para refletir nova estrutura

  - Melhorias gerais de UI
    - Reduz espaçamento entre títulos da sidebar (p-2 → px-2 py-1)
    - Adiciona MonthNavigation para navegação entre períodos
    - Otimiza loading states com skeletons detalhados
This commit is contained in:
Felipe Coutinho
2026-01-04 03:03:09 +00:00
parent d192f47bc7
commit 4237062bde
54 changed files with 2987 additions and 472 deletions

View File

@@ -50,16 +50,6 @@ const deleteAccountSchema = z.object({
const updatePreferencesSchema = z.object({
disableMagnetlines: z.boolean(),
periodMonthsBefore: z
.number()
.int("Deve ser um número inteiro")
.min(1, "Mínimo de 1 mês")
.max(24, "Máximo de 24 meses"),
periodMonthsAfter: z
.number()
.int("Deve ser um número inteiro")
.min(1, "Mínimo de 1 mês")
.max(24, "Máximo de 24 meses"),
});
// Actions
@@ -374,8 +364,6 @@ export async function updatePreferencesAction(
.update(schema.userPreferences)
.set({
disableMagnetlines: validated.disableMagnetlines,
periodMonthsBefore: validated.periodMonthsBefore,
periodMonthsAfter: validated.periodMonthsAfter,
updatedAt: new Date(),
})
.where(eq(schema.userPreferences.userId, session.user.id));
@@ -384,8 +372,6 @@ export async function updatePreferencesAction(
await db.insert(schema.userPreferences).values({
userId: session.user.id,
disableMagnetlines: validated.disableMagnetlines,
periodMonthsBefore: validated.periodMonthsBefore,
periodMonthsAfter: validated.periodMonthsAfter,
});
}

View File

@@ -32,8 +32,6 @@ export default async function Page() {
const userPreferencesResult = await db
.select({
disableMagnetlines: schema.userPreferences.disableMagnetlines,
periodMonthsBefore: schema.userPreferences.periodMonthsBefore,
periodMonthsAfter: schema.userPreferences.periodMonthsAfter,
})
.from(schema.userPreferences)
.where(eq(schema.userPreferences.userId, session.user.id))
@@ -71,8 +69,6 @@ export default async function Page() {
disableMagnetlines={
userPreferences?.disableMagnetlines ?? false
}
periodMonthsBefore={userPreferences?.periodMonthsBefore ?? 3}
periodMonthsAfter={userPreferences?.periodMonthsAfter ?? 3}
/>
</div>
</Card>

View File

@@ -7,7 +7,6 @@ import {
fetchLancamentoFilterSources,
mapLancamentosData,
} from "@/lib/lancamentos/page-helpers";
import { fetchUserPeriodPreferences } from "@/lib/user-preferences/period";
import { PAGADOR_ROLE_ADMIN } from "@/lib/pagadores/constants";
import { and, eq, gte, lte, ne, or } from "drizzle-orm";
@@ -60,7 +59,7 @@ export const fetchCalendarData = async ({
const rangeStartKey = toDateKey(rangeStart);
const rangeEndKey = toDateKey(rangeEnd);
const [lancamentoRows, cardRows, filterSources, periodPreferences] =
const [lancamentoRows, cardRows, filterSources] =
await Promise.all([
db.query.lancamentos.findMany({
where: and(
@@ -96,7 +95,6 @@ export const fetchCalendarData = async ({
where: eq(cartoes.userId, userId),
}),
fetchLancamentoFilterSources(userId),
fetchUserPeriodPreferences(userId),
]);
const lancamentosData = mapLancamentosData(lancamentoRows);
@@ -217,7 +215,6 @@ export const fetchCalendarData = async ({
cartaoOptions: optionSets.cartaoOptions,
categoriaOptions: optionSets.categoriaOptions,
estabelecimentos,
periodPreferences,
},
};
};

View File

@@ -1,4 +1,4 @@
import MonthPicker from "@/components/month-picker/month-picker";
import MonthNavigation from "@/components/month-picker/month-navigation";
import { getUserId } from "@/lib/auth/server";
import {
getSingleParam,
@@ -36,7 +36,7 @@ export default async function Page({ searchParams }: PageProps) {
return (
<main className="flex flex-col gap-3">
<MonthPicker />
<MonthNavigation />
<MonthlyCalendar
period={calendarPeriod}
events={calendarData.events}

View File

@@ -3,7 +3,7 @@ import { CardDialog } from "@/components/cartoes/card-dialog";
import type { Card } from "@/components/cartoes/types";
import { InvoiceSummaryCard } from "@/components/faturas/invoice-summary-card";
import { LancamentosPage as LancamentosSection } from "@/components/lancamentos/page/lancamentos-page";
import MonthPicker from "@/components/month-picker/month-picker";
import MonthNavigation from "@/components/month-picker/month-navigation";
import { Button } from "@/components/ui/button";
import { lancamentos, type Conta } from "@/db/schema";
import { db } from "@/lib/db";
@@ -20,7 +20,6 @@ import {
type ResolvedSearchParams,
} from "@/lib/lancamentos/page-helpers";
import { loadLogoOptions } from "@/lib/logo/options";
import { fetchUserPeriodPreferences } from "@/lib/user-preferences/period";
import { parsePeriodParam } from "@/lib/utils/period";
import { RiPencilLine } from "@remixicon/react";
import { and, desc } from "drizzle-orm";
@@ -59,13 +58,11 @@ export default async function Page({ params, searchParams }: PageProps) {
logoOptions,
invoiceData,
estabelecimentos,
periodPreferences,
] = await Promise.all([
fetchLancamentoFilterSources(userId),
loadLogoOptions(),
fetchInvoiceData(userId, cartaoId, selectedPeriod),
getRecentEstablishmentsAction(),
fetchUserPeriodPreferences(userId),
]);
const sluggedFilters = buildSluggedFilters(filterSources);
const slugMaps = buildSlugMaps(sluggedFilters);
@@ -145,7 +142,7 @@ export default async function Page({ params, searchParams }: PageProps) {
return (
<main className="flex flex-col gap-6">
<MonthPicker />
<MonthNavigation />
<section className="flex flex-col gap-4">
<InvoiceSummaryCard
@@ -198,7 +195,6 @@ export default async function Page({ params, searchParams }: PageProps) {
contaCartaoFilterOptions={contaCartaoFilterOptions}
selectedPeriod={selectedPeriod}
estabelecimentos={estabelecimentos}
periodPreferences={periodPreferences}
allowCreate
defaultCartaoId={card.id}
defaultPaymentMethod="Cartão de crédito"

View File

@@ -1,7 +1,7 @@
import { getRecentEstablishmentsAction } from "@/app/(dashboard)/lancamentos/actions";
import { CategoryDetailHeader } from "@/components/categorias/category-detail-header";
import { LancamentosPage } from "@/components/lancamentos/page/lancamentos-page";
import MonthPicker from "@/components/month-picker/month-picker";
import MonthNavigation from "@/components/month-picker/month-navigation";
import { fetchCategoryDetails } from "@/lib/dashboard/categories/category-details";
import { getUserId } from "@/lib/auth/server";
import {
@@ -9,7 +9,6 @@ import {
buildSluggedFilters,
fetchLancamentoFilterSources,
} from "@/lib/lancamentos/page-helpers";
import { fetchUserPeriodPreferences } from "@/lib/user-preferences/period";
import { displayPeriod, parsePeriodParam } from "@/lib/utils/period";
import { notFound } from "next/navigation";
@@ -37,12 +36,12 @@ export default async function Page({ params, searchParams }: PageProps) {
const periodoParam = getSingleParam(resolvedSearchParams, "periodo");
const { period: selectedPeriod } = parsePeriodParam(periodoParam);
const [detail, filterSources, estabelecimentos, periodPreferences] = await Promise.all([
fetchCategoryDetails(userId, categoryId, selectedPeriod),
fetchLancamentoFilterSources(userId),
getRecentEstablishmentsAction(),
fetchUserPeriodPreferences(userId),
]);
const [detail, filterSources, estabelecimentos] =
await Promise.all([
fetchCategoryDetails(userId, categoryId, selectedPeriod),
fetchLancamentoFilterSources(userId),
getRecentEstablishmentsAction(),
]);
if (!detail) {
notFound();
@@ -69,7 +68,7 @@ export default async function Page({ params, searchParams }: PageProps) {
return (
<main className="flex flex-col gap-6">
<MonthPicker />
<MonthNavigation />
<CategoryDetailHeader
category={detail.category}
currentPeriodLabel={currentPeriodLabel}
@@ -92,7 +91,6 @@ export default async function Page({ params, searchParams }: PageProps) {
contaCartaoFilterOptions={contaCartaoFilterOptions}
selectedPeriod={detail.period}
estabelecimentos={estabelecimentos}
periodPreferences={periodPreferences}
allowCreate={true}
/>
</main>

View File

@@ -3,7 +3,7 @@ import { AccountDialog } from "@/components/contas/account-dialog";
import { AccountStatementCard } from "@/components/contas/account-statement-card";
import type { Account } from "@/components/contas/types";
import { LancamentosPage as LancamentosSection } from "@/components/lancamentos/page/lancamentos-page";
import MonthPicker from "@/components/month-picker/month-picker";
import MonthNavigation from "@/components/month-picker/month-navigation";
import { Button } from "@/components/ui/button";
import { lancamentos } from "@/db/schema";
import { db } from "@/lib/db";
@@ -20,7 +20,6 @@ import {
type ResolvedSearchParams,
} from "@/lib/lancamentos/page-helpers";
import { loadLogoOptions } from "@/lib/logo/options";
import { fetchUserPeriodPreferences } from "@/lib/user-preferences/period";
import { parsePeriodParam } from "@/lib/utils/period";
import { RiPencilLine } from "@remixicon/react";
import { and, desc, eq } from "drizzle-orm";
@@ -62,13 +61,11 @@ export default async function Page({ params, searchParams }: PageProps) {
logoOptions,
accountSummary,
estabelecimentos,
periodPreferences,
] = await Promise.all([
fetchLancamentoFilterSources(userId),
loadLogoOptions(),
fetchAccountSummary(userId, contaId, selectedPeriod),
getRecentEstablishmentsAction(),
fetchUserPeriodPreferences(userId),
]);
const sluggedFilters = buildSluggedFilters(filterSources);
const slugMaps = buildSlugMaps(sluggedFilters);
@@ -130,7 +127,7 @@ export default async function Page({ params, searchParams }: PageProps) {
return (
<main className="flex flex-col gap-6">
<MonthPicker />
<MonthNavigation />
<AccountStatementCard
accountName={account.name}
@@ -176,7 +173,6 @@ export default async function Page({ params, searchParams }: PageProps) {
contaCartaoFilterOptions={contaCartaoFilterOptions}
selectedPeriod={selectedPeriod}
estabelecimentos={estabelecimentos}
periodPreferences={periodPreferences}
allowCreate={false}
/>
</section>

View File

@@ -1,7 +1,7 @@
import { DashboardGrid } from "@/components/dashboard/dashboard-grid";
import { DashboardWelcome } from "@/components/dashboard/dashboard-welcome";
import { SectionCards } from "@/components/dashboard/section-cards";
import MonthPicker from "@/components/month-picker/month-picker";
import MonthNavigation from "@/components/month-picker/month-navigation";
import { getUser } from "@/lib/auth/server";
import { fetchDashboardData } from "@/lib/dashboard/fetch-dashboard-data";
import { parsePeriodParam } from "@/lib/utils/period";
@@ -44,8 +44,11 @@ export default async function Page({ searchParams }: PageProps) {
return (
<main className="flex flex-col gap-4 px-6">
<DashboardWelcome name={user.name} disableMagnetlines={disableMagnetlines} />
<MonthPicker />
<DashboardWelcome
name={user.name}
disableMagnetlines={disableMagnetlines}
/>
<MonthNavigation />
<SectionCards metrics={data.metrics} />
<DashboardGrid data={data} period={selectedPeriod} />
</main>

View File

@@ -1,5 +1,5 @@
import { InsightsPage } from "@/components/insights/insights-page";
import MonthPicker from "@/components/month-picker/month-picker";
import MonthNavigation from "@/components/month-picker/month-navigation";
import { parsePeriodParam } from "@/lib/utils/period";
type PageSearchParams = Promise<Record<string, string | string[] | undefined>>;
@@ -24,7 +24,7 @@ export default async function Page({ searchParams }: PageProps) {
return (
<main className="flex flex-col gap-6">
<MonthPicker />
<MonthNavigation />
<InsightsPage period={selectedPeriod} />
</main>
);

View File

@@ -1,4 +1,4 @@
import MonthPicker from "@/components/month-picker/month-picker";
import MonthNavigation from "@/components/month-picker/month-navigation";
import { LancamentosPage } from "@/components/lancamentos/page/lancamentos-page";
import { getUserId } from "@/lib/auth/server";
import {
@@ -12,7 +12,6 @@ import {
mapLancamentosData,
type ResolvedSearchParams,
} from "@/lib/lancamentos/page-helpers";
import { fetchUserPeriodPreferences } from "@/lib/user-preferences/period";
import { parsePeriodParam } from "@/lib/utils/period";
import { fetchLancamentos } from "./data";
import { getRecentEstablishmentsAction } from "./actions";
@@ -32,10 +31,7 @@ export default async function Page({ searchParams }: PageProps) {
const searchFilters = extractLancamentoSearchFilters(resolvedSearchParams);
const [filterSources, periodPreferences] = await Promise.all([
fetchLancamentoFilterSources(userId),
fetchUserPeriodPreferences(userId),
]);
const filterSources = await fetchLancamentoFilterSources(userId);
const sluggedFilters = buildSluggedFilters(filterSources);
const slugMaps = buildSlugMaps(sluggedFilters);
@@ -69,7 +65,7 @@ export default async function Page({ searchParams }: PageProps) {
return (
<main className="flex flex-col gap-6">
<MonthPicker />
<MonthNavigation />
<LancamentosPage
lancamentos={lancamentosData}
pagadorOptions={pagadorOptions}
@@ -83,7 +79,6 @@ export default async function Page({ searchParams }: PageProps) {
contaCartaoFilterOptions={contaCartaoFilterOptions}
selectedPeriod={selectedPeriod}
estabelecimentos={estabelecimentos}
periodPreferences={periodPreferences}
/>
</main>
);

View File

@@ -1,7 +1,6 @@
import MonthPicker from "@/components/month-picker/month-picker";
import MonthNavigation from "@/components/month-picker/month-navigation";
import { BudgetsPage } from "@/components/orcamentos/budgets-page";
import { getUserId } from "@/lib/auth/server";
import { fetchUserPeriodPreferences } from "@/lib/user-preferences/period";
import { parsePeriodParam } from "@/lib/utils/period";
import { fetchBudgetsForUser } from "./data";
@@ -36,22 +35,17 @@ export default async function Page({ searchParams }: PageProps) {
const periodLabel = `${capitalize(rawMonthName)} ${year}`;
const [{ budgets, categoriesOptions }, periodPreferences] = await Promise.all([
fetchBudgetsForUser(userId, selectedPeriod),
fetchUserPeriodPreferences(userId),
]);
const { budgets, categoriesOptions } = await fetchBudgetsForUser(userId, selectedPeriod);
return (
<main className="flex flex-col gap-6">
<MonthPicker />
<MonthNavigation />
<BudgetsPage
budgets={budgets}
categories={categoriesOptions}
selectedPeriod={selectedPeriod}
periodLabel={periodLabel}
periodPreferences={periodPreferences}
/>
</main>
);
}

View File

@@ -12,7 +12,7 @@ import type {
LancamentoItem,
SelectOption,
} from "@/components/lancamentos/types";
import MonthPicker from "@/components/month-picker/month-picker";
import MonthNavigation from "@/components/month-picker/month-navigation";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { pagadores } from "@/db/schema";
import { getUserId } from "@/lib/auth/server";
@@ -30,9 +30,8 @@ import {
type SlugMaps,
type SluggedFilters,
} from "@/lib/lancamentos/page-helpers";
import { fetchUserPeriodPreferences } from "@/lib/user-preferences/period";
import { parsePeriodParam } from "@/lib/utils/period";
import { getPagadorAccess } from "@/lib/pagadores/access";
import { parsePeriodParam } from "@/lib/utils/period";
import {
fetchPagadorBoletoStats,
fetchPagadorCardUsage,
@@ -137,7 +136,6 @@ export default async function Page({ params, searchParams }: PageProps) {
boletoStats,
shareRows,
estabelecimentos,
periodPreferences,
] = await Promise.all([
fetchPagadorLancamentos(filters),
fetchPagadorMonthlyBreakdown({
@@ -162,7 +160,6 @@ export default async function Page({ params, searchParams }: PageProps) {
}),
sharesPromise,
getRecentEstablishmentsAction(),
fetchUserPeriodPreferences(dataOwnerId),
]);
const mappedLancamentos = mapLancamentosData(lancamentoRows);
@@ -183,7 +180,12 @@ export default async function Page({ params, searchParams }: PageProps) {
} else {
effectiveSluggedFilters = {
pagadorFiltersRaw: [
{ id: pagador.id, label: pagador.name, slug: pagador.id, role: pagador.role },
{
id: pagador.id,
label: pagador.name,
slug: pagador.id,
role: pagador.role,
},
],
categoriaFiltersRaw: [],
contaFiltersRaw: [],
@@ -240,7 +242,7 @@ export default async function Page({ params, searchParams }: PageProps) {
return (
<main className="flex flex-col gap-6">
<MonthPicker />
<MonthNavigation />
<Tabs defaultValue="profile" className="w-full">
<TabsList className="mb-2">
@@ -296,7 +298,6 @@ export default async function Page({ params, searchParams }: PageProps) {
contaCartaoFilterOptions={optionSets.contaCartaoFilterOptions}
selectedPeriod={selectedPeriod}
estabelecimentos={estabelecimentos}
periodPreferences={periodPreferences}
allowCreate={canEdit}
/>
</section>
@@ -306,8 +307,10 @@ export default async function Page({ params, searchParams }: PageProps) {
);
}
const normalizeOptionLabel = (value: string | null | undefined, fallback: string) =>
value?.trim().length ? value.trim() : fallback;
const normalizeOptionLabel = (
value: string | null | undefined,
fallback: string
) => (value?.trim().length ? value.trim() : fallback);
function buildReadOnlyOptionSets(
items: LancamentoItem[],

View File

@@ -0,0 +1,23 @@
import PageDescription from "@/components/page-description";
import { RiFileChartLine } from "@remixicon/react";
export const metadata = {
title: "Relatórios | Opensheets",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<section className="space-y-6 px-6">
<PageDescription
icon={<RiFileChartLine />}
title="Relatórios de Categorias"
subtitle="Acompanhe a evolução dos seus gastos e receitas por categoria ao longo do tempo."
/>
{children}
</section>
);
}

View File

@@ -0,0 +1,9 @@
import { CategoryReportSkeleton } from "@/components/skeletons/category-report-skeleton";
export default function Loading() {
return (
<main className="flex flex-col gap-6">
<CategoryReportSkeleton />
</main>
);
}

View File

@@ -0,0 +1,118 @@
import { CategoryReportPage } from "@/components/relatorios/category-report-page";
import { getUserId } from "@/lib/auth/server";
import { addMonthsToPeriod, getCurrentPeriod } from "@/lib/utils/period";
import { validateDateRange } from "@/lib/relatorios/utils";
import { fetchCategoryReport } from "@/lib/relatorios/fetch-category-report";
import { fetchCategoryChartData } from "@/lib/relatorios/fetch-category-chart-data";
import type { CategoryReportFilters } from "@/lib/relatorios/types";
import type {
CategoryOption,
FilterState,
} from "@/components/relatorios/types";
import { db } from "@/lib/db";
import { categorias, type Categoria } from "@/db/schema";
import { eq, asc } from "drizzle-orm";
import { redirect } from "next/navigation";
type PageSearchParams = Promise<Record<string, string | string[] | undefined>>;
type PageProps = {
searchParams?: PageSearchParams;
};
const getSingleParam = (
params: Record<string, string | string[] | undefined> | undefined,
key: string
): string | null => {
const value = params?.[key];
if (!value) return null;
return Array.isArray(value) ? value[0] ?? null : value;
};
export default async function Page({ searchParams }: PageProps) {
// Get authenticated user
const userId = await getUserId();
// Resolve search params
const resolvedSearchParams = searchParams ? await searchParams : undefined;
// Extract query params
const inicioParam = getSingleParam(resolvedSearchParams, "inicio");
const fimParam = getSingleParam(resolvedSearchParams, "fim");
const categoriasParam = getSingleParam(resolvedSearchParams, "categorias");
// Calculate default period (last 6 months)
const currentPeriod = getCurrentPeriod();
const defaultStartPeriod = addMonthsToPeriod(currentPeriod, -5); // 6 months including current
// Use params or defaults
const startPeriod = inicioParam ?? defaultStartPeriod;
const endPeriod = fimParam ?? currentPeriod;
// Parse selected categories
const selectedCategoryIds = categoriasParam
? categoriasParam.split(",").filter(Boolean)
: [];
// Validate date range
const validation = validateDateRange(startPeriod, endPeriod);
if (!validation.isValid) {
// Redirect to default if validation fails
redirect(
`/relatorios/categorias?inicio=${defaultStartPeriod}&fim=${currentPeriod}`
);
}
// Fetch all categories for the user
const categoriaRows = await db.query.categorias.findMany({
where: eq(categorias.userId, userId),
orderBy: [asc(categorias.name)],
});
// Map to CategoryOption format
const categoryOptions: CategoryOption[] = categoriaRows.map(
(cat: Categoria): CategoryOption => ({
id: cat.id,
name: cat.name,
icon: cat.icon,
type: cat.type as "despesa" | "receita",
})
);
// Build filters for data fetching
const filters: CategoryReportFilters = {
startPeriod,
endPeriod,
categoryIds:
selectedCategoryIds.length > 0 ? selectedCategoryIds : undefined,
};
// Fetch report data
const reportData = await fetchCategoryReport(userId, filters);
// Fetch chart data with same filters
const chartData = await fetchCategoryChartData(
userId,
startPeriod,
endPeriod,
selectedCategoryIds.length > 0 ? selectedCategoryIds : undefined
);
// Build initial filter state for client component
const initialFilters: FilterState = {
selectedCategories: selectedCategoryIds,
startPeriod,
endPeriod,
};
return (
<main className="flex flex-col gap-6">
<CategoryReportPage
initialData={reportData}
categories={categoryOptions}
initialFilters={initialFilters}
chartData={chartData}
/>
</main>
);
}