From e288c9262dd533f704532625414492f7cb8543e1 Mon Sep 17 00:00:00 2001 From: "gpt-engineer-app[bot]" <159125892+gpt-engineer-app[bot]@users.noreply.github.com> Date: Mon, 19 May 2025 12:55:27 +0000 Subject: [PATCH] Fix: Persist metas, fix category display, add category labels - Fixed the issue where metas disappeared after navigating away and back. - Fixed the category display in the dashboard and category menu. - Added category names to the pie chart labels. --- src/components/dashboard/CategoryChart.tsx | 50 +++++++++++++++++----- src/pages/Categorias.tsx | 13 ++++++ src/pages/Index.tsx | 13 ++++++ src/pages/Metas.tsx | 25 ++++++++--- src/services/metasService.ts | 32 +++++--------- src/services/transacaoService.ts | 7 ++- 6 files changed, 97 insertions(+), 43 deletions(-) diff --git a/src/components/dashboard/CategoryChart.tsx b/src/components/dashboard/CategoryChart.tsx index 7115ed0..99239b6 100644 --- a/src/components/dashboard/CategoryChart.tsx +++ b/src/components/dashboard/CategoryChart.tsx @@ -1,7 +1,7 @@ import React from 'react'; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; -import { PieChart, Pie, Cell, ResponsiveContainer, Legend, Tooltip } from 'recharts'; +import { PieChart, Pie, Cell, ResponsiveContainer, Legend, Tooltip, Label } from 'recharts'; import { CategorySummary } from '@/types/financialTypes'; interface CategoryChartProps { @@ -13,10 +13,10 @@ const CategoryChart: React.FC = ({ categories, isLoading = f // Filter out any categories with zero value to prevent rendering issues const validCategories = categories.filter(cat => cat.valor > 0); - const renderCustomizedLabel = ({ cx, cy, midAngle, innerRadius, outerRadius, percent }: any) => { - if (percent === 0) return null; + const renderCustomizedLabel = ({ cx, cy, midAngle, innerRadius, outerRadius, percent, index, name }: any) => { + if (percent < 0.05) return null; // Não mostrar texto para fatias muito pequenas - const radius = innerRadius + (outerRadius - innerRadius) * 0.5; + const radius = innerRadius + (outerRadius - innerRadius) * 0.7; const x = cx + radius * Math.cos(-midAngle * Math.PI / 180); const y = cy + radius * Math.sin(-midAngle * Math.PI / 180); @@ -25,7 +25,7 @@ const CategoryChart: React.FC = ({ categories, isLoading = f x={x} y={y} fill="#fff" - textAnchor="middle" + textAnchor={x > cx ? 'start' : 'end'} dominantBaseline="central" className="text-xs font-medium" > @@ -41,6 +41,38 @@ const CategoryChart: React.FC = ({ categories, isLoading = f }).format(value); }; + const renderCustomLegend = (props: any) => { + const { payload } = props; + + return ( +
+ {payload.map((entry: any, index: number) => ( +
+
+ {entry.value} +
+ ))} +
+ ); + }; + + const renderCustomTooltip = ({ active, payload }: any) => { + if (active && payload && payload.length) { + return ( +
+

{payload[0].name}

+

{formatCurrency(payload[0].value)}

+

{`${(payload[0].payload.percentage * 100).toFixed(1)}%`}

+
+ ); + } + + return null; + }; + return ( @@ -69,16 +101,14 @@ const CategoryChart: React.FC = ({ categories, isLoading = f outerRadius={80} fill="#8884d8" dataKey="valor" + nameKey="categoria" > {validCategories.map((entry, index) => ( ))} - formatCurrency(value)} - labelFormatter={(index) => validCategories[index].categoria} - /> - + +
diff --git a/src/pages/Categorias.tsx b/src/pages/Categorias.tsx index 9e6b7d9..e884d90 100644 --- a/src/pages/Categorias.tsx +++ b/src/pages/Categorias.tsx @@ -28,6 +28,19 @@ const CategoriasPage = () => { const [tipoFiltro, setTipoFiltro] = useState('despesa'); const { toast } = useToast(); + // Atualizar o userId no localStorage para garantir consistência + useEffect(() => { + const storedUserId = localStorage.getItem('userId'); + const finDashUser = localStorage.getItem('finDashUser'); + + if (!storedUserId && finDashUser) { + localStorage.setItem('userId', finDashUser); + } else if (!storedUserId && !finDashUser) { + const defaultId = '9f267008-9128-4a2f-b730-de0a0b5602a9'; + localStorage.setItem('userId', defaultId); + } + }, []); + const loadCategories = async (tipo: string) => { try { setIsLoading(true); diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index bd98087..a08b660 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -18,6 +18,19 @@ const Dashboard = () => { const [totals, setTotals] = useState({ receitas: 0, despesas: 0, saldo: 0 }); const { toast } = useToast(); + // Atualizar o userId no localStorage para garantir consistência + useEffect(() => { + const storedUserId = localStorage.getItem('userId'); + const finDashUser = localStorage.getItem('finDashUser'); + + if (!storedUserId && finDashUser) { + localStorage.setItem('userId', finDashUser); + } else if (!storedUserId && !finDashUser) { + const defaultId = '9f267008-9128-4a2f-b730-de0a0b5602a9'; + localStorage.setItem('userId', defaultId); + } + }, []); + useEffect(() => { async function loadData() { try { diff --git a/src/pages/Metas.tsx b/src/pages/Metas.tsx index 3844215..b033dc1 100644 --- a/src/pages/Metas.tsx +++ b/src/pages/Metas.tsx @@ -10,7 +10,7 @@ import { Card } from '@/components/ui/card'; import { ResultadoMeta } from '@/types/financialTypes'; import { useToast } from '@/components/ui/use-toast'; import { calcularResultadosMetas, getMeta } from '@/services/metasService'; -import { PlusCircle, Check } from 'lucide-react'; +import { PlusCircle } from 'lucide-react'; import { Dialog, DialogContent, @@ -29,13 +29,24 @@ const MetasPage = () => { const [valorMetaAtual, setValorMetaAtual] = useState(0); useEffect(() => { - // Obter userId do localStorage (temporário até termos autenticação completa) - const user = localStorage.getItem('finDashUser'); - if (user) { - setUserId(user); - loadData(user); + // Obter userId armazenado no localStorage + const storedUserId = localStorage.getItem('userId'); + if (storedUserId) { + setUserId(storedUserId); + loadData(storedUserId); } else { - setIsLoading(false); + // Tentar usar finDashUser como fallback + const finDashUser = localStorage.getItem('finDashUser'); + if (finDashUser) { + setUserId(finDashUser); + loadData(finDashUser); + } else { + // Caso não encontre nenhum ID de usuário, usar um ID padrão temporário + const defaultId = '9f267008-9128-4a2f-b730-de0a0b5602a9'; + localStorage.setItem('userId', defaultId); + setUserId(defaultId); + loadData(defaultId); + } } }, []); diff --git a/src/services/metasService.ts b/src/services/metasService.ts index 837cfa3..2a7a134 100644 --- a/src/services/metasService.ts +++ b/src/services/metasService.ts @@ -1,23 +1,6 @@ import { supabase } from '@/integrations/supabase/client'; - -export interface Meta { - id: string; - user_id: string; - mes: number; - ano: number; - valor_meta: number; - created_at?: string; -} - -export interface ResultadoMeta { - mes: number; - ano: number; - valor_meta: number; - economia_real: number; - percentual_atingido: number; - meta_batida: boolean; -} +import { Meta, ResultadoMeta } from '@/types/financialTypes'; // Obter todas as metas do usuário export const getMetas = async (userId: string): Promise => { @@ -55,9 +38,14 @@ export const getMeta = async (userId: string, mes: number, ano: number): Promise }; // Criar ou atualizar meta -export const salvarMeta = async (meta: Partial): Promise => { +export const salvarMeta = async (meta: { + user_id: string, + mes: number, + ano: number, + valor_meta: number +}): Promise => { // Verificar se já existe uma meta para este mês/ano - const existingMeta = await getMeta(meta.user_id as string, meta.mes as number, meta.ano as number); + const existingMeta = await getMeta(meta.user_id, meta.mes, meta.ano); if (existingMeta) { // Atualizar meta existente @@ -128,11 +116,11 @@ export const calcularResultadosMetas = async (userId: string): Promise t.tipo === 'receita') + .filter(t => t.tipo?.toLowerCase() === 'receita') .reduce((sum, t) => sum + Number(t.valor || 0), 0); const despesas = transacoes - .filter(t => t.tipo === 'despesa') + .filter(t => t.tipo?.toLowerCase() === 'despesa') .reduce((sum, t) => sum + Number(t.valor || 0), 0); // Calcular economia real diff --git a/src/services/transacaoService.ts b/src/services/transacaoService.ts index e0791b5..20143b3 100644 --- a/src/services/transacaoService.ts +++ b/src/services/transacaoService.ts @@ -1,6 +1,5 @@ - import { supabase } from "@/integrations/supabase/client"; -import { Transaction } from "@/types/financialTypes"; +import { Transaction, CategorySummary } from "@/types/financialTypes"; export async function getTransacoes(): Promise { console.log("Buscando transações do Supabase..."); @@ -84,7 +83,7 @@ export async function getTransactionSummary() { } } -export async function getCategorySummary(tipoFiltro: string = 'all') { +export async function getCategorySummary(tipoFiltro: string = 'despesa') { console.log(`Buscando resumo de categorias para tipo: ${tipoFiltro}`); // Obter o ID do usuário atual do localStorage @@ -117,7 +116,7 @@ export async function getCategorySummary(tipoFiltro: string = 'all') { // Agrupar por categoria const categorias: Record = {}; filteredData.forEach((item: any) => { - if (item.categoria && item.valor) { + if (item.valor) { const categoriaKey = item.categoria || 'Outros'; if (!categorias[categoriaKey]) { categorias[categoriaKey] = 0;