loop de requisiçoes na pag de meus dados
This commit is contained in:
parent
c04b0989d2
commit
a078204276
@ -34,42 +34,49 @@ export default function PatientProfile() {
|
||||
const { user, isLoading: isAuthLoading } = useAuthLayout({
|
||||
requiredRole: ["paciente", "admin", "medico", "gestor", "secretaria"],
|
||||
});
|
||||
const [patientData, setPatientData] = useState<PatientProfileData | null>(
|
||||
null
|
||||
);
|
||||
|
||||
const [patientData, setPatientData] = useState<PatientProfileData | null>(null);
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(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,
|
||||
|
||||
@ -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<UserLayoutData | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const router = useRouter();
|
||||
export function useAuthLayout(
|
||||
{ requiredRole }: UseAuthLayoutOptions = {}
|
||||
) {
|
||||
const [user, setUser] = useState<UserLayoutData | null>(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 };
|
||||
}
|
||||
|
||||
@ -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}`),
|
||||
|
||||
@ -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);
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user