From 21aac7c495c70da0948dc8a60ea140ed5850162f Mon Sep 17 00:00:00 2001 From: Tiago Yamamoto Date: Thu, 5 Mar 2026 14:02:53 -0600 Subject: [PATCH] chore(frontend): add detailed dashboard navigation debug logs --- frontend/src/app/dashboard/page.tsx | 78 +++++++++++++++++++++-------- 1 file changed, 57 insertions(+), 21 deletions(-) diff --git a/frontend/src/app/dashboard/page.tsx b/frontend/src/app/dashboard/page.tsx index c26e190..9e08e6c 100644 --- a/frontend/src/app/dashboard/page.tsx +++ b/frontend/src/app/dashboard/page.tsx @@ -1,7 +1,7 @@ "use client"; import { useAuth } from "@/contexts/AuthContext"; -import { useRouter } from "next/navigation"; +import { usePathname, useRouter } from "next/navigation"; import { useState, useEffect } from "react"; import { UserRole } from "@/types/auth"; import { UserRoundCog, Rocket, Crown } from "lucide-react"; @@ -12,6 +12,7 @@ import { CadastroSuperadminModal } from "./components"; const Dashboard = () => { const { user: authUser, userRole, isAuthenticated } = useAuth(); const router = useRouter(); + const pathname = usePathname(); const [loading, setLoading] = useState(true); const [showCadastroSuperadminModal, setShowCadastroSuperadminModal] = useState(false); @@ -22,6 +23,28 @@ const Dashboard = () => { const [registroIncompleto, setRegistroIncompleto] = useState(false); const [userData, setUserData] = useState(null); + const debugLog = (icon: string, message: string, payload?: unknown) => { + if (payload !== undefined) { + console.log(`[Dashboard] ${icon} ${message}`, payload); + return; + } + console.log(`[Dashboard] ${icon} ${message}`); + }; + + const navigateWithDebug = (target: string, source: string) => { + const token = localStorage.getItem("access_token"); + debugLog("🧭", `Navegacao solicitada por '${source}'`, { + from: pathname, + to: target, + hasToken: Boolean(token), + userRole, + isAuthenticated, + userLevel: userData?.nivel, + isSuperadmin: userData?.superadmin, + }); + router.push(target); + }; + // Obter ID da empresa do usuário (se não for superadmin) const empresaId = (authUser as any)?.empresas?.[0] || null; @@ -37,31 +60,45 @@ const Dashboard = () => { empresaId: empresaId || undefined, }); + useEffect(() => { + debugLog("📍", "Rota atual alterada", { pathname }); + }, [pathname]); + // Verificar autenticação simples useEffect(() => { const checkAuth = async () => { try { // Verificar se há token armazenado const storedToken = localStorage.getItem('access_token'); + debugLog("🔐", "Validando sessao do dashboard", { hasToken: Boolean(storedToken), pathname }); if (!storedToken) { - router.push("/login"); + debugLog("⛔", "Token ausente. Redirecionando para login"); + navigateWithDebug("/login", "checkAuth:no-token"); return; } // Buscar dados do usuário da API - const response = await fetch(`${process.env.NEXT_PUBLIC_BFF_API_URL}/auth/me`, { + const authMeUrl = `${process.env.NEXT_PUBLIC_BFF_API_URL}/auth/me`; + debugLog("📡", "Consultando auth/me", { authMeUrl }); + const response = await fetch(authMeUrl, { method: "GET", headers: { "accept": "application/json", "Authorization": `Bearer ${storedToken}`, }, }); + debugLog("📨", "Resposta de auth/me", { status: response.status, ok: response.ok }); if (response.ok) { const userData = await response.json(); setUserData(userData); + debugLog("✅", "Usuario carregado para dashboard", { + id: userData?.id, + nivel: userData?.nivel, + superadmin: userData?.superadmin, + }); // Verificar se registro-completo é false if (userData["registro-completo"] === false) { @@ -69,25 +106,26 @@ const Dashboard = () => { } } else { localStorage.removeItem('access_token'); - router.push("/login"); + debugLog("⛔", "auth/me nao autorizado. Limpando token e redirecionando"); + navigateWithDebug("/login", "checkAuth:invalid-token"); return; } setShowQuickActions(true); } catch (error) { console.error("Erro ao verificar autenticação:", error); - router.push("/login"); + navigateWithDebug("/login", "checkAuth:exception"); } finally { setLoading(false); } }; checkAuth(); - }, [router]); + }, [pathname]); // Funções para lidar com o banner de registro completo const handleCompletarCadastro = () => { setRegistroIncompleto(false); - router.push("/completar-registro"); + navigateWithDebug("/completar-registro", "banner:completar-cadastro"); }; const handleFecharBanner = () => { @@ -487,7 +525,7 @@ const Dashboard = () => { href="/dashboard/empresa-novo" onClick={(event) => { event.preventDefault(); - router.push('/dashboard/empresa-novo'); + navigateWithDebug("/dashboard/empresa-novo", "quick-action:gestao-empresas"); }} className="bg-white hover:bg-gray-50 border border-gray-200 rounded-xl p-6 text-center transition-colors duration-200 cursor-pointer group min-h-[48px] block" > @@ -502,7 +540,7 @@ const Dashboard = () => { {/* Gestão de Produtos Venda - Oculto para colaborador */}