feat(reports): melhora notas, calendario e analises

This commit is contained in:
Felipe Coutinho
2026-03-09 17:14:04 +00:00
parent ada1377640
commit 6205dee42a
35 changed files with 429 additions and 590 deletions

View File

@@ -2,10 +2,10 @@
import { RiPieChartLine } from "@remixicon/react";
import { CategoryIconBadge } from "@/components/categorias/category-icon-badge";
import MoneyValues from "@/components/money-values";
import MoneyValues from "@/components/shared/money-values";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { WidgetEmptyState } from "@/components/widget-empty-state";
import { WidgetEmptyState } from "@/components/shared/widget-empty-state";
import type { CardDetailData } from "@/lib/relatorios/cartoes-report";
type CardCategoryBreakdownProps = {

View File

@@ -10,36 +10,14 @@ import {
} from "@/components/ui/tooltip";
import type { CardDetailData } from "@/lib/relatorios/cartoes-report";
import { cn } from "@/lib/utils";
import { formatCurrency } from "@/lib/utils/currency";
import { formatPeriodMonthShort } from "@/lib/utils/period";
type CardInvoiceStatusProps = {
data: CardDetailData["invoiceStatus"];
};
const monthLabels = [
"Jan",
"Fev",
"Mar",
"Abr",
"Mai",
"Jun",
"Jul",
"Ago",
"Set",
"Out",
"Nov",
"Dez",
];
export function CardInvoiceStatus({ data }: CardInvoiceStatusProps) {
const formatCurrency = (value: number) => {
return new Intl.NumberFormat("pt-BR", {
style: "currency",
currency: "BRL",
minimumFractionDigits: 0,
maximumFractionDigits: 0,
}).format(value);
};
const getStatusColor = (status: string | null) => {
switch (status) {
case "pago":
@@ -66,11 +44,6 @@ export function CardInvoiceStatus({ data }: CardInvoiceStatusProps) {
}
};
const formatPeriodShort = (period: string) => {
const [, month] = period.split("-");
return monthLabels[parseInt(month, 10) - 1];
};
return (
<Card>
<CardHeader className="pb-2">
@@ -93,13 +66,16 @@ export function CardInvoiceStatus({ data }: CardInvoiceStatusProps) {
)}
/>
<span className="text-xs text-muted-foreground">
{formatPeriodShort(invoice.period)}
{formatPeriodMonthShort(invoice.period)}
</span>
</div>
</TooltipTrigger>
<TooltipContent side="top">
<p className="font-medium">
{formatCurrency(invoice.amount)}
{formatCurrency(invoice.amount, {
maximumFractionDigits: 0,
minimumFractionDigits: 0,
})}
</p>
<p className="text-xs ">{getStatusLabel(invoice.status)}</p>
</TooltipContent>

View File

@@ -1,11 +1,11 @@
"use client";
import { RiShoppingBag3Line } from "@remixicon/react";
import MoneyValues from "@/components/money-values";
import MoneyValues from "@/components/shared/money-values";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { WidgetEmptyState } from "@/components/widget-empty-state";
import { WidgetEmptyState } from "@/components/shared/widget-empty-state";
import type { CardDetailData } from "@/lib/relatorios/cartoes-report";
type CardTopExpensesProps = {

View File

@@ -16,7 +16,10 @@ import {
ChartContainer,
ChartTooltip,
} from "@/components/ui/chart";
import { resolveLogoSrc } from "@/lib/logo";
import type { CardDetailData } from "@/lib/relatorios/cartoes-report";
import { formatCurrency, formatCurrencyCompact } from "@/lib/utils/currency";
import { formatPercentage } from "@/lib/utils/percentage";
type CardUsageChartProps = {
data: CardDetailData["monthlyUsage"];
@@ -34,48 +37,14 @@ const chartConfig = {
},
} satisfies ChartConfig;
const resolveLogoPath = (logo: string | null) => {
if (!logo) return null;
if (
logo.startsWith("http://") ||
logo.startsWith("https://") ||
logo.startsWith("data:")
) {
return logo;
}
return logo.startsWith("/") ? logo : `/logos/${logo}`;
};
export function CardUsageChart({ data, limit, card }: CardUsageChartProps) {
const formatCurrency = (value: number) => {
return new Intl.NumberFormat("pt-BR", {
style: "currency",
currency: "BRL",
minimumFractionDigits: 0,
maximumFractionDigits: 0,
}).format(value);
};
const formatCurrencyCompact = (value: number) => {
if (Math.abs(value) >= 1000) {
return new Intl.NumberFormat("pt-BR", {
style: "currency",
currency: "BRL",
minimumFractionDigits: 0,
maximumFractionDigits: 0,
notation: "compact",
}).format(value);
}
return formatCurrency(value);
};
// Always show last 12 months
const chartData = data.slice(-12).map((item) => ({
month: item.periodLabel,
amount: item.amount,
}));
const logoPath = resolveLogoPath(card.logo);
const logoPath = resolveLogoSrc(card.logo);
return (
<Card>
@@ -124,7 +93,17 @@ export function CardUsageChart({ data, limit, card }: CardUsageChartProps) {
axisLine={false}
tickMargin={8}
className="text-xs"
tickFormatter={formatCurrencyCompact}
tickFormatter={(value) =>
Math.abs(Number(value)) >= 1000
? formatCurrencyCompact(Number(value), {
maximumFractionDigits: 0,
minimumFractionDigits: 0,
})
: formatCurrency(Number(value), {
maximumFractionDigits: 0,
minimumFractionDigits: 0,
})
}
/>
{limit > 0 && (
<ReferenceLine
@@ -159,7 +138,10 @@ export function CardUsageChart({ data, limit, card }: CardUsageChartProps) {
Uso
</span>
<span className="text-xs font-medium tabular-nums">
{formatCurrency(value)}
{formatCurrency(value, {
maximumFractionDigits: 0,
minimumFractionDigits: 0,
})}
</span>
</div>
{limit > 0 && (
@@ -168,7 +150,10 @@ export function CardUsageChart({ data, limit, card }: CardUsageChartProps) {
% do Limite
</span>
<span className="text-xs font-medium tabular-nums">
{usagePercent.toFixed(0)}%
{formatPercentage(usagePercent, {
maximumFractionDigits: 0,
minimumFractionDigits: 0,
})}
</span>
</div>
)}

View File

@@ -4,59 +4,24 @@ import { RiBankCard2Line } from "@remixicon/react";
import Image from "next/image";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import MoneyValues from "@/components/money-values";
import MoneyValues from "@/components/shared/money-values";
import { Card, CardContent } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { resolveCardBrandAsset } from "@/lib/cartoes/brand-assets";
import { resolveLogoSrc } from "@/lib/logo";
import type { CartoesReportData } from "@/lib/relatorios/cartoes-report";
import { cn } from "@/lib/utils";
import { formatCurrency } from "@/lib/utils/currency";
import { formatPercentage } from "@/lib/utils/percentage";
type CardsOverviewProps = {
data: CartoesReportData;
};
const BRAND_ASSETS: Record<string, string> = {
visa: "/bandeiras/visa.svg",
mastercard: "/bandeiras/mastercard.svg",
amex: "/bandeiras/amex.svg",
american: "/bandeiras/amex.svg",
elo: "/bandeiras/elo.svg",
hipercard: "/bandeiras/hipercard.svg",
hiper: "/bandeiras/hipercard.svg",
};
const resolveBrandAsset = (brand: string | null) => {
if (!brand) return null;
const normalized = brand.trim().toLowerCase();
const match = (
Object.keys(BRAND_ASSETS) as Array<keyof typeof BRAND_ASSETS>
).find((entry) => normalized.includes(entry));
return match ? BRAND_ASSETS[match] : null;
};
const resolveLogoPath = (logo: string | null) => {
if (!logo) return null;
if (
logo.startsWith("http://") ||
logo.startsWith("https://") ||
logo.startsWith("data:")
) {
return logo;
}
return logo.startsWith("/") ? logo : `/logos/${logo}`;
};
export function CardsOverview({ data }: CardsOverviewProps) {
const searchParams = useSearchParams();
const periodoParam = searchParams.get("periodo");
const formatCurrency = (value: number) =>
new Intl.NumberFormat("pt-BR", {
style: "currency",
currency: "BRL",
minimumFractionDigits: 0,
maximumFractionDigits: 0,
}).format(value);
const getUsageColor = (percent: number) => {
if (percent < 50) return "bg-success";
if (percent < 80) return "bg-warning";
@@ -107,7 +72,10 @@ export function CardsOverview({ data }: CardsOverviewProps) {
/>
) : (
<p className="text-2xl font-semibold">
{card.value.toFixed(0)}%
{formatPercentage(card.value, {
maximumFractionDigits: 0,
minimumFractionDigits: 0,
})}
</p>
)}
</CardContent>
@@ -120,8 +88,8 @@ export function CardsOverview({ data }: CardsOverviewProps) {
{/* Cards list */}
<div className="grid gap-2 grid-cols-2 lg:grid-cols-4 xl:grid-cols-4">
{data.cards.map((card) => {
const logoPath = resolveLogoPath(card.logo);
const brandAsset = resolveBrandAsset(card.brand);
const logoPath = resolveLogoSrc(card.logo);
const brandAsset = resolveCardBrandAsset(card.brand);
const isSelected = data.selectedCard?.card.id === card.id;
return (
@@ -174,7 +142,10 @@ export function CardsOverview({ data }: CardsOverviewProps) {
)}
/>
<span className="text-xs font-medium tabular-nums">
{card.usagePercent.toFixed(0)}%
{formatPercentage(card.usagePercent, {
maximumFractionDigits: 0,
minimumFractionDigits: 0,
})}
</span>
</div>
</div>

View File

@@ -8,7 +8,7 @@ import { formatCurrency } from "@/lib/lancamentos/formatting-helpers";
import type {
CategoryReportData,
CategoryReportItem,
} from "@/lib/relatorios/types";
} from "@/lib/types/relatorios";
import { formatPeriodLabel } from "@/lib/relatorios/utils";
import { formatPeriodForUrl } from "@/lib/utils/period";
import { CategoryCell } from "./category-cell";
@@ -20,11 +20,18 @@ interface CategoryReportCardsProps {
interface CategoryCardProps {
category: CategoryReportItem;
periods: string[];
periodCount: number;
colorIndex: number;
}
function CategoryCard({ category, periods, colorIndex }: CategoryCardProps) {
function CategoryCard({
category,
periods,
periodCount,
colorIndex,
}: CategoryCardProps) {
const periodParam = formatPeriodForUrl(periods[periods.length - 1]);
const averageMonthlyTotal = category.total / periodCount;
return (
<Card>
@@ -65,6 +72,10 @@ function CategoryCard({ category, periods, colorIndex }: CategoryCardProps) {
</div>
);
})}
<div className="flex items-center justify-between font-semibold text-info">
<span>Média mensal</span>
<span>{formatCurrency(averageMonthlyTotal)}</span>
</div>
<div className="flex items-center justify-between pt-2 font-semibold">
<span>Total</span>
<span>{formatCurrency(category.total)}</span>
@@ -78,6 +89,7 @@ interface SectionProps {
title: string;
categories: CategoryReportItem[];
periods: string[];
periodCount: number;
colorIndexOffset: number;
total: number;
}
@@ -86,6 +98,7 @@ function Section({
title,
categories,
periods,
periodCount,
colorIndexOffset,
total,
}: SectionProps) {
@@ -93,21 +106,29 @@ function Section({
return null;
}
const averageMonthlyTotal = total / periodCount;
return (
<div className="space-y-3">
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
{title}
</span>
<span className="text-sm text-muted-foreground">
{formatCurrency(total)}
</span>
<div className="flex flex-col items-end">
<span className="text-sm text-muted-foreground">
{formatCurrency(total)}
</span>
<span className="text-xs font-semibold text-info">
Média: {formatCurrency(averageMonthlyTotal)}
</span>
</div>
</div>
{categories.map((category, index) => (
<CategoryCard
key={category.categoryId}
category={category}
periods={periods}
periodCount={periodCount}
colorIndex={colorIndexOffset + index}
/>
))}
@@ -117,6 +138,7 @@ function Section({
export function CategoryReportCards({ data }: CategoryReportCardsProps) {
const { categories, periods } = data;
const periodCount = Math.max(periods.length, 1);
// Separate categories by type and calculate totals
const { receitas, despesas, receitasTotal, despesasTotal } = useMemo(() => {
@@ -145,6 +167,7 @@ export function CategoryReportCards({ data }: CategoryReportCardsProps) {
title="Despesas"
categories={despesas}
periods={periods}
periodCount={periodCount}
colorIndexOffset={0}
total={despesasTotal}
/>
@@ -154,6 +177,7 @@ export function CategoryReportCards({ data }: CategoryReportCardsProps) {
title="Receitas"
categories={receitas}
periods={periods}
periodCount={periodCount}
colorIndexOffset={despesas.length}
total={receitasTotal}
/>

View File

@@ -19,11 +19,12 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { formatCurrency } from "@/lib/lancamentos/formatting-helpers";
import type { CategoryReportData } from "@/lib/relatorios/types";
import {
formatPercentageChange,
formatPeriodLabel,
} from "@/lib/relatorios/utils";
import type { CategoryReportData } from "@/lib/types/relatorios";
import { formatDateTime } from "@/lib/utils/date";
import {
getPrimaryPdfColor,
loadExportLogoDataUrl,
@@ -201,8 +202,8 @@ export function CategoryReportExport({
const doc = new jsPDF({ orientation: "landscape" });
const primaryColor = getPrimaryPdfColor();
const [smallLogoDataUrl, textLogoDataUrl] = await Promise.all([
loadExportLogoDataUrl("/logo_small.png"),
loadExportLogoDataUrl("/logo_text.png"),
loadExportLogoDataUrl("/imagens/logo_small.png"),
loadExportLogoDataUrl("/imagens/logo_text.png"),
]);
let brandingEndX = 14;
@@ -232,7 +233,13 @@ export function CategoryReportExport({
22,
);
doc.text(
`Gerado em: ${new Date().toLocaleDateString("pt-BR")}`,
`Gerado em: ${
formatDateTime(new Date(), {
day: "2-digit",
month: "2-digit",
year: "numeric",
}) ?? "—"
}`,
titleX,
27,
);

View File

@@ -5,8 +5,6 @@ import {
RiCheckLine,
RiExpandUpDownLine,
} from "@remixicon/react";
import { format } from "date-fns";
import { ptBR } from "date-fns/locale";
import type { ReactNode } from "react";
import { useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
@@ -26,6 +24,13 @@ import {
} from "@/components/ui/popover";
import { validateDateRange } from "@/lib/relatorios/utils";
import { getIconComponent } from "@/lib/utils/icons";
import {
addMonthsToPeriod,
dateToPeriod,
formatShortPeriodLabel,
getCurrentPeriod,
periodToDate,
} from "@/lib/utils/period";
import type { CategoryReportFiltersProps } from "./types";
/**
@@ -44,25 +49,6 @@ export function CategoryReportFilters({
const [startMonthOpen, setStartMonthOpen] = useState(false);
const [endMonthOpen, setEndMonthOpen] = useState(false);
// Convert period string (YYYY-MM) to Date object
const periodToDate = (period: string): Date => {
const [year, month] = period.split("-").map(Number);
return new Date(year, month - 1, 1);
};
// Convert Date object to period string (YYYY-MM)
const dateToPeriod = (date: Date): string => {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
return `${year}-${month}`;
};
// Format date for display
const formatMonthYear = (period: string): string => {
const date = periodToDate(period);
return format(date, "MMM/yyyy", { locale: ptBR });
};
// Filter categories by search
const filteredCategories = useMemo(() => {
if (!searchValue) return categories;
@@ -126,10 +112,8 @@ export function CategoryReportFilters({
// Handle reset all filters
const handleReset = () => {
const currentPeriod = new Date().toISOString().slice(0, 7);
const defaultStartPeriod = new Date();
defaultStartPeriod.setMonth(defaultStartPeriod.getMonth() - 5);
const startPeriod = defaultStartPeriod.toISOString().slice(0, 7);
const currentPeriod = getCurrentPeriod();
const startPeriod = addMonthsToPeriod(currentPeriod, -5);
onFiltersChange({
selectedCategories: [],
@@ -138,27 +122,19 @@ export function CategoryReportFilters({
});
};
// Validate date range
const validation = useMemo(() => {
if (!filters.startPeriod || !filters.endPeriod) {
return { isValid: true };
}
return validateDateRange(filters.startPeriod, filters.endPeriod);
}, [filters.startPeriod, filters.endPeriod]);
const validation =
!filters.startPeriod || !filters.endPeriod
? { isValid: true }
: validateDateRange(filters.startPeriod, filters.endPeriod);
// Display text for selected categories
const selectedText = useMemo(() => {
if (selectedCategories.length === 0) {
return "Categoria";
}
if (selectedCategories.length === categories.length) {
return "Todas";
}
if (selectedCategories.length === 1) {
return selectedCategories[0].name;
}
return `${selectedCategories.length} selecionadas`;
}, [selectedCategories, categories.length]);
const selectedText =
selectedCategories.length === 0
? "Categoria"
: selectedCategories.length === categories.length
? "Todas"
: selectedCategories.length === 1
? selectedCategories[0].name
: `${selectedCategories.length} selecionadas`;
return (
<div className="flex flex-col gap-4">
@@ -261,7 +237,7 @@ export function CategoryReportFilters({
disabled={isLoading}
>
<RiCalendarLine className="mr-2 h-4 w-4" />
{formatMonthYear(filters.startPeriod)}
{formatShortPeriodLabel(filters.startPeriod)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
@@ -281,7 +257,7 @@ export function CategoryReportFilters({
disabled={isLoading}
>
<RiCalendarLine className="mr-2 h-4 w-4" />
{formatMonthYear(filters.endPeriod)}
{formatShortPeriodLabel(filters.endPeriod)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">

View File

@@ -6,13 +6,13 @@ import {
RiTable2,
} from "@remixicon/react";
import { useRouter, useSearchParams } from "next/navigation";
import { useCallback, useMemo, useState, useTransition } from "react";
import { useEffect, useRef, useState, useTransition } from "react";
import { EmptyState } from "@/components/shared/empty-state";
import { CategoryReportSkeleton } from "@/components/shared/skeletons/category-report-skeleton";
import { Card } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import type { CategoryChartData } from "@/lib/relatorios/fetch-category-chart-data";
import type { CategoryReportData } from "@/lib/relatorios/types";
import type { CategoryReportData } from "@/lib/types/relatorios";
import { CategoryReportCards } from "./category-report-cards";
import { CategoryReportChart } from "./category-report-chart";
import { CategoryReportExport } from "./category-report-export";
@@ -38,76 +38,62 @@ export function CategoryReportPage({
const [isPending, startTransition] = useTransition();
const [filters, setFilters] = useState<FilterState>(initialFilters);
const [data, setData] = useState<CategoryReportData>(initialData);
// Get active tab from URL or default to "table"
const activeTab = searchParams.get("aba") || "table";
// Debounce timer
const [debounceTimer, setDebounceTimer] = useState<NodeJS.Timeout | null>(
null,
);
const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const handleFiltersChange = useCallback(
(newFilters: FilterState) => {
setFilters(newFilters);
// Clear existing timer
if (debounceTimer) {
clearTimeout(debounceTimer);
useEffect(() => {
return () => {
if (debounceTimerRef.current) {
clearTimeout(debounceTimerRef.current);
}
};
}, []);
// Set new debounced timer (300ms)
const timer = setTimeout(() => {
startTransition(() => {
// Build new URL with query params
const params = new URLSearchParams(searchParams.toString());
const handleFiltersChange = (newFilters: FilterState) => {
setFilters(newFilters);
params.set("inicio", newFilters.startPeriod);
params.set("fim", newFilters.endPeriod);
if (debounceTimerRef.current) {
clearTimeout(debounceTimerRef.current);
}
if (newFilters.selectedCategories.length > 0) {
params.set("categorias", newFilters.selectedCategories.join(","));
} else {
params.delete("categorias");
}
debounceTimerRef.current = setTimeout(() => {
startTransition(() => {
const params = new URLSearchParams(searchParams.toString());
// Preserve current tab
const currentTab = searchParams.get("aba");
if (currentTab) {
params.set("aba", currentTab);
}
params.set("inicio", newFilters.startPeriod);
params.set("fim", newFilters.endPeriod);
// Navigate with new params (this will trigger server component re-render)
router.push(`?${params.toString()}`, { scroll: false });
});
}, 300);
if (newFilters.selectedCategories.length > 0) {
params.set("categorias", newFilters.selectedCategories.join(","));
} else {
params.delete("categorias");
}
setDebounceTimer(timer);
},
[debounceTimer, router, searchParams],
);
const currentTab = searchParams.get("aba");
if (currentTab) {
params.set("aba", currentTab);
}
// Handle tab change
const handleTabChange = useCallback(
(value: string) => {
const params = new URLSearchParams(searchParams.toString());
params.set("aba", value);
router.push(`?${params.toString()}`, { scroll: false });
},
[router, searchParams],
);
router.push(`?${params.toString()}`, { scroll: false });
});
}, 300);
};
// Update data when initialData changes (from server)
useMemo(() => {
setData(initialData);
}, [initialData]);
const handleTabChange = (value: string) => {
const params = new URLSearchParams(searchParams.toString());
params.set("aba", value);
router.push(`?${params.toString()}`, { scroll: false });
};
// Check if no categories are available
const hasNoCategories = categories.length === 0;
// Check if no data in period
const hasNoData = data.categories.length === 0 && !hasNoCategories;
const hasNoData = initialData.categories.length === 0 && !hasNoCategories;
return (
<div className="flex flex-col gap-6">
@@ -116,7 +102,9 @@ export function CategoryReportPage({
categories={categories}
filters={filters}
onFiltersChange={handleFiltersChange}
exportButton={<CategoryReportExport data={data} filters={filters} />}
exportButton={
<CategoryReportExport data={initialData} filters={filters} />
}
/>
{/* Loading State */}
@@ -180,11 +168,11 @@ export function CategoryReportPage({
<TabsContent value="table" className="mt-4">
{/* Desktop Table */}
<div className="hidden md:block">
<CategoryReportTable data={data} />
<CategoryReportTable data={initialData} />
</div>
{/* Mobile Cards */}
<CategoryReportCards data={data} />
<CategoryReportCards data={initialData} />
</TabsContent>
<TabsContent value="chart" className="mt-4">

View File

@@ -4,7 +4,7 @@ import { useMemo } from "react";
import type {
CategoryReportData,
CategoryReportItem,
} from "@/lib/relatorios/types";
} from "@/lib/types/relatorios";
import { CategoryTable } from "./category-table";
interface CategoryReportTableProps {

View File

@@ -3,6 +3,7 @@
import Link from "next/link";
import { useMemo } from "react";
import { CategoryIconBadge } from "@/components/categorias/category-icon-badge";
import StatusDot from "@/components/shared/status-dot";
import {
Table,
TableBody,
@@ -13,10 +14,9 @@ import {
TableRow,
} from "@/components/ui/table";
import { formatCurrency } from "@/lib/lancamentos/formatting-helpers";
import type { CategoryReportItem } from "@/lib/relatorios/types";
import { formatPeriodLabel } from "@/lib/relatorios/utils";
import type { CategoryReportItem } from "@/lib/types/relatorios";
import { formatPeriodForUrl } from "@/lib/utils/period";
import DotIcon from "../dot-icon";
import { Card } from "../ui/card";
import { CategoryCell } from "./category-cell";
@@ -37,6 +37,7 @@ export function CategoryTable({
const sectionTotals = useMemo(() => {
const totalsMap = new Map<string, number>();
let grandTotal = 0;
const periodCount = Math.max(periods.length, 1);
for (const category of categories) {
grandTotal += category.total;
@@ -47,7 +48,11 @@ export function CategoryTable({
}
}
return { totalsMap, grandTotal };
return {
totalsMap,
grandTotal,
averageMonthlyTotal: grandTotal / periodCount,
};
}, [categories, periods]);
if (categories.length === 0) {
@@ -59,7 +64,7 @@ export function CategoryTable({
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[280px] min-w-[280px] font-bold">
<TableHead className="w-[240px] min-w-[240px] font-bold">
Categoria
</TableHead>
{periods.map((period) => (
@@ -70,6 +75,9 @@ export function CategoryTable({
{formatPeriodLabel(period)}
</TableHead>
))}
<TableHead className="text-right min-w-[140px] font-bold">
Média
</TableHead>
<TableHead className="text-right min-w-[120px] font-bold">
Total
</TableHead>
@@ -85,7 +93,7 @@ export function CategoryTable({
<TableRow key={category.categoryId}>
<TableCell>
<div className="flex items-center gap-2">
<DotIcon
<StatusDot
color={
category.type === "receita"
? "bg-success"
@@ -121,6 +129,9 @@ export function CategoryTable({
</TableCell>
);
})}
<TableCell className="text-right font-semibold text-info">
{formatCurrency(category.total / Math.max(periods.length, 1))}
</TableCell>
<TableCell className="text-right font-semibold">
{formatCurrency(category.total)}
</TableCell>
@@ -140,6 +151,9 @@ export function CategoryTable({
</TableCell>
);
})}
<TableCell className="text-right font-semibold text-info">
{formatCurrency(sectionTotals.averageMonthlyTotal)}
</TableCell>
<TableCell className="text-right font-semibold">
{formatCurrency(sectionTotals.grandTotal)}
</TableCell>

View File

@@ -1,11 +1,11 @@
"use client";
import { RiStore2Line } from "@remixicon/react";
import MoneyValues from "@/components/money-values";
import MoneyValues from "@/components/shared/money-values";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { WidgetEmptyState } from "@/components/widget-empty-state";
import { WidgetEmptyState } from "@/components/shared/widget-empty-state";
import type { TopEstabelecimentosData } from "@/lib/relatorios/estabelecimentos/fetch-data";
type EstablishmentsListProps = {

View File

@@ -6,7 +6,7 @@ import {
RiRepeatLine,
RiStore2Line,
} from "@remixicon/react";
import MoneyValues from "@/components/money-values";
import MoneyValues from "@/components/shared/money-values";
import { Card, CardContent } from "@/components/ui/card";
import type { TopEstabelecimentosData } from "@/lib/relatorios/estabelecimentos/fetch-data";

View File

@@ -2,10 +2,10 @@
import { RiPriceTag3Line } from "@remixicon/react";
import { CategoryIconBadge } from "@/components/categorias/category-icon-badge";
import MoneyValues from "@/components/money-values";
import MoneyValues from "@/components/shared/money-values";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { WidgetEmptyState } from "@/components/widget-empty-state";
import { WidgetEmptyState } from "@/components/shared/widget-empty-state";
import type { TopEstabelecimentosData } from "@/lib/relatorios/estabelecimentos/fetch-data";
type TopCategoriesProps = {