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({
|
const { user, isLoading: isAuthLoading } = useAuthLayout({
|
||||||
requiredRole: ["paciente", "admin", "medico", "gestor", "secretaria"],
|
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 [isEditing, setIsEditing] = useState(false);
|
||||||
const [isSaving, setIsSaving] = useState(false);
|
const [isSaving, setIsSaving] = useState(false);
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (user?.id) {
|
console.log("PatientProfile MONTADO");
|
||||||
const fetchPatientDetails = async () => {
|
}, []);
|
||||||
try {
|
|
||||||
const patientDetails = await patientsService.getById(user.id);
|
|
||||||
setPatientData({
|
useEffect(() => {
|
||||||
name: patientDetails.full_name || user.name,
|
const userId = user?.id;
|
||||||
email: user.email,
|
if (!userId) return;
|
||||||
phone: patientDetails.phone_mobile || "",
|
|
||||||
cpf: patientDetails.cpf || "",
|
const fetchPatientDetails = async () => {
|
||||||
birthDate: patientDetails.birth_date || "",
|
try {
|
||||||
cep: patientDetails.cep || "",
|
const patientDetails = await patientsService.getById(userId);
|
||||||
street: patientDetails.street || "",
|
setPatientData({
|
||||||
number: patientDetails.number || "",
|
name: patientDetails.full_name || user.name,
|
||||||
city: patientDetails.city || "",
|
email: user.email,
|
||||||
avatarFullUrl: user.avatarFullUrl,
|
phone: patientDetails.phone_mobile || "",
|
||||||
});
|
cpf: patientDetails.cpf || "",
|
||||||
} catch (error) {
|
birthDate: patientDetails.birth_date || "",
|
||||||
console.error("Erro ao buscar detalhes do paciente:", error);
|
cep: patientDetails.cep || "",
|
||||||
toast({
|
street: patientDetails.street || "",
|
||||||
title: "Erro",
|
number: patientDetails.number || "",
|
||||||
description: "Não foi possível carregar seus dados completos.",
|
city: patientDetails.city || "",
|
||||||
variant: "destructive",
|
avatarFullUrl: user.avatarFullUrl,
|
||||||
});
|
});
|
||||||
}
|
} catch (error) {
|
||||||
};
|
console.error("Erro ao buscar detalhes do paciente:", error);
|
||||||
fetchPatientDetails();
|
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 = (
|
const handleInputChange = (
|
||||||
field: keyof PatientProfileData,
|
field: keyof PatientProfileData,
|
||||||
|
|||||||
@ -6,63 +6,72 @@ import { usersService } from "@/services/usersApi.mjs";
|
|||||||
import { toast } from "@/hooks/use-toast";
|
import { toast } from "@/hooks/use-toast";
|
||||||
|
|
||||||
interface UserLayoutData {
|
interface UserLayoutData {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
email: string;
|
email: string;
|
||||||
roles: string[];
|
roles: string[];
|
||||||
avatar_url?: string;
|
avatar_url?: string;
|
||||||
avatarFullUrl?: string;
|
avatarFullUrl?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface UseAuthLayoutOptions {
|
interface UseAuthLayoutOptions {
|
||||||
requiredRole?: string[];
|
requiredRole?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useAuthLayout({ requiredRole }: UseAuthLayoutOptions = {}) {
|
export function useAuthLayout(
|
||||||
const [user, setUser] = useState<UserLayoutData | null>(null);
|
{ requiredRole }: UseAuthLayoutOptions = {}
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
) {
|
||||||
const router = useRouter();
|
const [user, setUser] = useState<UserLayoutData | null>(null);
|
||||||
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchUserData = async () => {
|
const fetchUserData = async () => {
|
||||||
try {
|
try {
|
||||||
const fullUserData = await usersService.getMe();
|
const fullUserData = await usersService.getMe();
|
||||||
|
|
||||||
if (!fullUserData.roles.some((role) => requiredRole?.includes(role))) {
|
// só verifica papel se requiredRole existir
|
||||||
console.error(`Acesso negado. Requer perfil '${requiredRole}', mas o usuário tem '${fullUserData.roles.join(", ")}'.`);
|
if (
|
||||||
toast({
|
requiredRole &&
|
||||||
title: "Acesso Negado",
|
!fullUserData.roles.some((role: string) =>
|
||||||
description: "Você não tem permissão para acessar esta página.",
|
requiredRole.includes(role)
|
||||||
variant: "destructive",
|
)
|
||||||
});
|
) {
|
||||||
router.push("/");
|
console.error(
|
||||||
return;
|
`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 ***
|
setUser({
|
||||||
// Adicionamos o nome do bucket 'avatars' na URL final.
|
id: fullUserData.user.id,
|
||||||
const avatarFullUrl = avatarPath ? `https://yuanqfswhberkoevtmfr.supabase.co/storage/v1/object/public/avatars/${avatarPath}` : undefined;
|
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({
|
fetchUserData();
|
||||||
id: fullUserData.user.id,
|
}, [router]); // não depende mais de requiredRole
|
||||||
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();
|
return { user, isLoading };
|
||||||
}, [router, requiredRole]);
|
|
||||||
|
|
||||||
return { user, isLoading };
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,7 +2,11 @@ import { api } from "./api.mjs";
|
|||||||
|
|
||||||
export const patientsService = {
|
export const patientsService = {
|
||||||
list: () => api.get("/rest/v1/patients"),
|
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),
|
create: (data) => api.post("/rest/v1/patients", data),
|
||||||
update: (id, data) => api.patch(`/rest/v1/patients?id=eq.${id}`, data),
|
update: (id, data) => api.patch(`/rest/v1/patients?id=eq.${id}`, data),
|
||||||
delete: (id) => api.delete(`/rest/v1/patients?id=eq.${id}`),
|
delete: (id) => api.delete(`/rest/v1/patients?id=eq.${id}`),
|
||||||
|
|||||||
@ -3,6 +3,7 @@ import { api } from "./api.mjs";
|
|||||||
export const usersService = {
|
export const usersService = {
|
||||||
// Função getMe corrigida para chamar a si mesma pelo nome
|
// Função getMe corrigida para chamar a si mesma pelo nome
|
||||||
async getMe() {
|
async getMe() {
|
||||||
|
console.log("getMe chamado");
|
||||||
const sessionData = await api.getSession();
|
const sessionData = await api.getSession();
|
||||||
if (!sessionData?.id) {
|
if (!sessionData?.id) {
|
||||||
console.error("Sessão não encontrada ou usuário sem ID.", sessionData);
|
console.error("Sessão não encontrada ou usuário sem ID.", sessionData);
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user