From a07820427636cba2b85c47fb2ff19ef4e41f0372 Mon Sep 17 00:00:00 2001 From: m1guelmcf Date: Mon, 1 Dec 2025 15:14:44 -0300 Subject: [PATCH] =?UTF-8?q?loop=20de=20requisi=C3=A7oes=20na=20pag=20de=20?= =?UTF-8?q?meus=20dados?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/patient/profile/page.tsx | 67 ++++++++++++---------- hooks/useAuthLayout.ts | 105 +++++++++++++++++++---------------- services/patientsApi.mjs | 6 +- services/usersApi.mjs | 1 + 4 files changed, 100 insertions(+), 79 deletions(-) diff --git a/app/patient/profile/page.tsx b/app/patient/profile/page.tsx index 5b3f8af..fb03df2 100644 --- a/app/patient/profile/page.tsx +++ b/app/patient/profile/page.tsx @@ -34,42 +34,49 @@ export default function PatientProfile() { const { user, isLoading: isAuthLoading } = useAuthLayout({ requiredRole: ["paciente", "admin", "medico", "gestor", "secretaria"], }); - const [patientData, setPatientData] = useState( - null - ); + + const [patientData, setPatientData] = useState(null); const [isEditing, setIsEditing] = useState(false); const [isSaving, setIsSaving] = useState(false); const fileInputRef = useRef(null); useEffect(() => { - if (user?.id) { - const fetchPatientDetails = async () => { - try { - const patientDetails = await patientsService.getById(user.id); - setPatientData({ - name: patientDetails.full_name || user.name, - email: user.email, - phone: patientDetails.phone_mobile || "", - cpf: patientDetails.cpf || "", - birthDate: patientDetails.birth_date || "", - cep: patientDetails.cep || "", - street: patientDetails.street || "", - number: patientDetails.number || "", - city: patientDetails.city || "", - avatarFullUrl: user.avatarFullUrl, - }); - } catch (error) { - console.error("Erro ao buscar detalhes do paciente:", error); - toast({ - title: "Erro", - description: "Não foi possível carregar seus dados completos.", - variant: "destructive", - }); - } - }; - fetchPatientDetails(); + console.log("PatientProfile MONTADO"); +}, []); + + + useEffect(() => { + const userId = user?.id; + if (!userId) return; + + const fetchPatientDetails = async () => { + try { + const patientDetails = await patientsService.getById(userId); + setPatientData({ + name: patientDetails.full_name || user.name, + email: user.email, + phone: patientDetails.phone_mobile || "", + cpf: patientDetails.cpf || "", + birthDate: patientDetails.birth_date || "", + cep: patientDetails.cep || "", + street: patientDetails.street || "", + number: patientDetails.number || "", + city: patientDetails.city || "", + avatarFullUrl: user.avatarFullUrl, + }); + } catch (error) { + console.error("Erro ao buscar detalhes do paciente:", error); + toast({ + title: "Erro", + description: "Não foi possível carregar seus dados completos.", + variant: "destructive", + }); } - }, [user]); + }; + + fetchPatientDetails(); +}, [user?.id, user?.name, user?.email, user?.avatarFullUrl]); + const handleInputChange = ( field: keyof PatientProfileData, diff --git a/hooks/useAuthLayout.ts b/hooks/useAuthLayout.ts index ad0d4ed..a20a6a9 100644 --- a/hooks/useAuthLayout.ts +++ b/hooks/useAuthLayout.ts @@ -6,63 +6,72 @@ import { usersService } from "@/services/usersApi.mjs"; import { toast } from "@/hooks/use-toast"; interface UserLayoutData { - id: string; - name: string; - email: string; - roles: string[]; - avatar_url?: string; - avatarFullUrl?: string; + id: string; + name: string; + email: string; + roles: string[]; + avatar_url?: string; + avatarFullUrl?: string; } interface UseAuthLayoutOptions { - requiredRole?: string[]; + requiredRole?: string[]; } -export function useAuthLayout({ requiredRole }: UseAuthLayoutOptions = {}) { - const [user, setUser] = useState(null); - const [isLoading, setIsLoading] = useState(true); - const router = useRouter(); +export function useAuthLayout( + { requiredRole }: UseAuthLayoutOptions = {} +) { + const [user, setUser] = useState(null); + const [isLoading, setIsLoading] = useState(true); + const router = useRouter(); - useEffect(() => { - const fetchUserData = async () => { - try { - const fullUserData = await usersService.getMe(); + useEffect(() => { + const fetchUserData = async () => { + try { + const fullUserData = await usersService.getMe(); - if (!fullUserData.roles.some((role) => requiredRole?.includes(role))) { - console.error(`Acesso negado. Requer perfil '${requiredRole}', mas o usuário tem '${fullUserData.roles.join(", ")}'.`); - toast({ - title: "Acesso Negado", - description: "Você não tem permissão para acessar esta página.", - variant: "destructive", - }); - router.push("/"); - return; - } + // só verifica papel se requiredRole existir + if ( + requiredRole && + !fullUserData.roles.some((role: string) => + requiredRole.includes(role) + ) + ) { + console.error( + `Acesso negado. Requer perfil '${requiredRole}', mas o usuário tem '${fullUserData.roles.join(", ")}'.` + ); + toast({ + title: "Acesso Negado", + description: "Você não tem permissão para acessar esta página.", + variant: "destructive", + }); + router.push("/"); + return; + } - const avatarPath = fullUserData.profile.avatar_url; + const avatarPath = fullUserData.profile.avatar_url; + const avatarFullUrl = avatarPath + ? `https://yuanqfswhberkoevtmfr.supabase.co/storage/v1/object/public/avatars/${avatarPath}` + : undefined; - // *** A CORREÇÃO ESTÁ AQUI *** - // Adicionamos o nome do bucket 'avatars' na URL final. - const avatarFullUrl = avatarPath ? `https://yuanqfswhberkoevtmfr.supabase.co/storage/v1/object/public/avatars/${avatarPath}` : undefined; + setUser({ + id: fullUserData.user.id, + name: fullUserData.profile.full_name || "Usuário", + email: fullUserData.user.email, + roles: fullUserData.roles, + avatar_url: avatarPath, + avatarFullUrl, + }); + } catch (error) { + console.error("Falha na autenticação do layout:", error); + router.push("/login"); + } finally { + setIsLoading(false); + } + }; - setUser({ - id: fullUserData.user.id, - name: fullUserData.profile.full_name || "Usuário", - email: fullUserData.user.email, - roles: fullUserData.roles, - avatar_url: avatarPath, - avatarFullUrl: avatarFullUrl, - }); - } catch (error) { - console.error("Falha na autenticação do layout:", error); - router.push("/login"); - } finally { - setIsLoading(false); - } - }; + fetchUserData(); + }, [router]); // não depende mais de requiredRole - fetchUserData(); - }, [router, requiredRole]); - - return { user, isLoading }; + return { user, isLoading }; } diff --git a/services/patientsApi.mjs b/services/patientsApi.mjs index 5eb1e7c..05f2e5f 100644 --- a/services/patientsApi.mjs +++ b/services/patientsApi.mjs @@ -2,7 +2,11 @@ import { api } from "./api.mjs"; export const patientsService = { list: () => api.get("/rest/v1/patients"), - getById: (id) => api.get(`/rest/v1/patients?id=eq.${id}`), + getById: (id) => { + console.log("getById chamado", id); + return api.get(`/rest/v1/patients?id=eq.${id}`); +}, + create: (data) => api.post("/rest/v1/patients", data), update: (id, data) => api.patch(`/rest/v1/patients?id=eq.${id}`, data), delete: (id) => api.delete(`/rest/v1/patients?id=eq.${id}`), diff --git a/services/usersApi.mjs b/services/usersApi.mjs index b041336..70a5963 100644 --- a/services/usersApi.mjs +++ b/services/usersApi.mjs @@ -3,6 +3,7 @@ import { api } from "./api.mjs"; export const usersService = { // Função getMe corrigida para chamar a si mesma pelo nome async getMe() { + console.log("getMe chamado"); const sessionData = await api.getSession(); if (!sessionData?.id) { console.error("Sessão não encontrada ou usuário sem ID.", sessionData);