From fe488e4dd0a94fc7bc93c27977da7c005dec693c Mon Sep 17 00:00:00 2001 From: joao_pedro Date: Mon, 20 Oct 2025 08:57:45 -0300 Subject: [PATCH 1/4] configuracoes iniciais --- src/components/utils/fetchErros/ModalErro.jsx | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/components/utils/fetchErros/ModalErro.jsx diff --git a/src/components/utils/fetchErros/ModalErro.jsx b/src/components/utils/fetchErros/ModalErro.jsx new file mode 100644 index 0000000..4cc7b55 --- /dev/null +++ b/src/components/utils/fetchErros/ModalErro.jsx @@ -0,0 +1,53 @@ +import React from "react"; +import { useState } from "react"; + + +function ModalErro ({showModal, setShowModal}) { +//const [showModal, setShowModal] = useState() + + +return( + +
+ +{showModal ? + +
+ +
+
+
Atenção
+ +
+ +
+ +
+ +
+ +
+
+
+ : null +} +
+ +); + + +} + + + +export default ModalErro \ No newline at end of file From edfe985512d689edbab57f3fdff282fe8584b2dd Mon Sep 17 00:00:00 2001 From: joao_pedro Date: Tue, 21 Oct 2025 09:14:58 -0300 Subject: [PATCH 2/4] Problema de token expirado resolvido e modal dos erros --- src/components/utils/AuthProvider.js | 30 ++++++++- src/components/utils/fetchErros/ModalErro.jsx | 30 +++++---- src/pages/Login.jsx | 2 +- src/pages/TablePaciente.jsx | 64 ++++++++++++++++--- 4 files changed, 104 insertions(+), 22 deletions(-) diff --git a/src/components/utils/AuthProvider.js b/src/components/utils/AuthProvider.js index 28d8f38..14d636c 100644 --- a/src/components/utils/AuthProvider.js +++ b/src/components/utils/AuthProvider.js @@ -1,5 +1,5 @@ import React, { createContext, useContext, useState, useEffect } from 'react'; - +import API_KEY from './apiKeys'; // 1. Criação do Contexto const AuthContext = createContext(null); @@ -41,6 +41,8 @@ export function AuthProvider({ children }) { * @param {Object} tokenResponse O objeto completo retornado pelo Supabase Auth. */ const setAuthTokens = (tokenResponse) => { + console.log("TOKEN ADICIONADO") + if (tokenResponse && tokenResponse.access_token && tokenResponse.token_type) { // 1. Atualiza o estado do React setAccessToken(tokenResponse.access_token); @@ -77,6 +79,29 @@ export function AuthProvider({ children }) { // --- VALOR DO CONTEXTO --- + const RefreshingToken = () => { + console.log("refresh token", refreshToken) + var myHeaders = new Headers(); + myHeaders.append("Content-Type", "application/json"); + myHeaders.append("apikey", API_KEY) + + var raw = JSON.stringify({ + "refresh_token": refreshToken + }); + + var requestOptions = { + method: 'POST', + headers: myHeaders, + body: raw, + redirect: 'follow' + }; + + fetch(`https://yuanqfswhberkoevtmfr.supabase.co/auth/v1/token?grant_type=refresh_token`, requestOptions) + .then(response => response.json()) + .then(result => setAuthTokens(result)) + .catch(error => console.log('error', error)); + } + const contextValue = { accessToken, tokenType, @@ -85,8 +110,11 @@ export function AuthProvider({ children }) { setAuthTokens, // Usado para CRIAR/MUDAR (Login/Refresh) clearAuthTokens, // Usado para MUDAR (Logout) getAuthorizationHeader, // Usado para PEGAR (Endpoints) + RefreshingToken }; + + return ( {children} diff --git a/src/components/utils/fetchErros/ModalErro.jsx b/src/components/utils/fetchErros/ModalErro.jsx index 4cc7b55..92663ab 100644 --- a/src/components/utils/fetchErros/ModalErro.jsx +++ b/src/components/utils/fetchErros/ModalErro.jsx @@ -1,10 +1,19 @@ import React from "react"; -import { useState } from "react"; +import { useState, useEffect } from "react"; +import { useAuth } from "../AuthProvider"; +function ModalErro ({showModal, setShowModal, ErrorData}) { +const {RefreshingToken} = useAuth() -function ModalErro ({showModal, setShowModal}) { -//const [showModal, setShowModal] = useState() +console.log("eerrroror", ErrorData) +useEffect(() => { +if( ErrorData.httpStatus === 401){ + setShowModal(false) + RefreshingToken() + console.log('uaua') +} +}, []) return( @@ -15,24 +24,21 @@ return(
-
-
Atenção
- +
+
{`(Erro ${ErrorData.httpStatus})`}
+
+ + {ErrorData.message}
diff --git a/src/pages/Login.jsx b/src/pages/Login.jsx index 9275a93..c9bb231 100644 --- a/src/pages/Login.jsx +++ b/src/pages/Login.jsx @@ -116,7 +116,7 @@ function Login({ onEnterSystem }) { if (data.access_token) { const UserData = await UserInfos(`bearer ${data.access_token}`); console.log(UserData, "Dados do usuário"); - + if (UserData?.roles?.includes("admin")) { navigate(`/admin/`); } else if (UserData?.roles?.includes("secretaria")) { diff --git a/src/pages/TablePaciente.jsx b/src/pages/TablePaciente.jsx index 53b5c79..6d269f1 100644 --- a/src/pages/TablePaciente.jsx +++ b/src/pages/TablePaciente.jsx @@ -3,10 +3,10 @@ import { Link } from "react-router-dom"; import API_KEY from "../components/utils/apiKeys"; import { useAuth } from "../components/utils/AuthProvider"; import "./style/TablePaciente.css"; - +import ModalErro from "../components/utils/fetchErros/ModalErro"; function TablePaciente({ setCurrentPage, setPatientID }) { - const { getAuthorizationHeader, isAuthenticated } = useAuth(); + const { getAuthorizationHeader, isAuthenticated, RefreshingToken } = useAuth(); const [pacientes, setPacientes] = useState([]); const [search, setSearch] = useState(""); @@ -24,6 +24,10 @@ function TablePaciente({ setCurrentPage, setPatientID }) { const [showDeleteModal, setShowDeleteModal] = useState(false); const [selectedPatientId, setSelectedPatientId] = useState(null); + const [showModalError, setShowModalError] = useState(false); + + const [ ErrorInfo, setErrorInfo] = useState({}) + const GetAnexos = async (id) => { var myHeaders = new Headers(); myHeaders.append("Authorization", "Bearer "); @@ -114,10 +118,53 @@ function TablePaciente({ setCurrentPage, setPatientID }) { redirect: 'follow' }; - fetch("https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/patients", requestOptions) - .then(response => response.json()) - .then(result => setPacientes(result)) - .catch(error => console.log('error', error)); + fetch("https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/patients", requestOptions) // <-- Verifique se a URL está correta (patients) + .then(response => { + + // 1. VERIFICAÇÃO DO STATUS HTTP (Se não for 2xx) + if (!response.ok) { + + // Lemos o corpo do erro JSON (PostgREST envia o JSON mesmo no 404/401) + return response.json().then(errorData => { + + // 2. CRIAMOS O OBJETO DE ERRO CUSTOMIZADO COM TODOS OS DADOS NECESSÁRIOS + const errorObject = { + httpStatus: response.status, // 404, 401, 400, etc. + apiCode: errorData.code, // PGRST205, 42501, etc. + message: errorData.message || response.statusText, + details: errorData.details, + hint: errorData.hint + }; + + // 3. LOG (para debug) + console.error("ERRO DETALHADO:", errorObject); + + // 4. FORÇAMOS A FALHA DA PROMISE LANÇANDO O OBJETO CUSTOMIZADO + // NOTA: Ao lançar um objeto customizado, ele se torna o argumento 'error' no .catch + throw errorObject; + }); + } + + // 3. Se a resposta for OK (2xx), processamos o JSON normalmente + return response.json(); + }) + .then(result => { + // 4. Bloco de SUCESSO + setPacientes(result); + console.log("Sucesso:", result); + + // IMPORTANTE: Se o modal estava aberto, feche-o no sucesso + setShowModalError(false); + }) + .catch(error => { + // 5. Bloco de ERRO (Captura erros de rede ou o erro lançado pelo 'throw') + //console.error('Falha na requisição:', error.message); + if(error.httpStatus === 401){ + RefreshingToken() + } + setErrorInfo(error) + setShowModalError(true); + }); }, [isAuthenticated, getAuthorizationHeader]); const ehAniversariante = (dataNascimento) => { @@ -199,11 +246,12 @@ function TablePaciente({ setCurrentPage, setPatientID }) { }) : []; useEffect(() => { - console.log(` Pacientes totais: ${pacientes.length}, Filtrados: ${pacientesFiltrados.length}`); + console.log(` Pacientes totais: ${pacientes?.length}, Filtrados: ${pacientesFiltrados?.length}`); }, [pacientes, pacientesFiltrados, search]); return ( <> +

Lista de Pacientes

@@ -382,7 +430,7 @@ function TablePaciente({ setCurrentPage, setPatientID }) {
- {pacientesFiltrados.length} de {pacientes.length} pacientes encontrados + {pacientesFiltrados?.length} de {pacientes?.length} pacientes encontrados
From c6523f1b0d8e32e42bec4151df3a44f6d692a7f6 Mon Sep 17 00:00:00 2001 From: joao_pedro Date: Wed, 22 Oct 2025 10:32:06 -0300 Subject: [PATCH 3/4] Solucao para token expirado --- src/components/utils/Functions-Endpoints/General.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/components/utils/Functions-Endpoints/General.js b/src/components/utils/Functions-Endpoints/General.js index e77f9f8..862375c 100644 --- a/src/components/utils/Functions-Endpoints/General.js +++ b/src/components/utils/Functions-Endpoints/General.js @@ -24,4 +24,9 @@ import API_KEY from "../apiKeys"; return userInfoData } +const UploadFotoAvatar = ( userID,access_token,file) => { + + +} + export {UserInfos} \ No newline at end of file From 8878ad6cedf44e812ee1d2f437786c657ae5e46e Mon Sep 17 00:00:00 2001 From: joao_pedro Date: Thu, 23 Oct 2025 06:34:25 -0300 Subject: [PATCH 4/4] Criacao de uma mensagem para o erro --- src/components/utils/fetchErros/ModalErro.jsx | 11 ++++++++--- src/pages/TablePaciente.jsx | 13 +++---------- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/src/components/utils/fetchErros/ModalErro.jsx b/src/components/utils/fetchErros/ModalErro.jsx index 92663ab..c1d1912 100644 --- a/src/components/utils/fetchErros/ModalErro.jsx +++ b/src/components/utils/fetchErros/ModalErro.jsx @@ -5,6 +5,8 @@ import { useAuth } from "../AuthProvider"; function ModalErro ({showModal, setShowModal, ErrorData}) { const {RefreshingToken} = useAuth() + const [modalMensagem, setModalMensagem] = useState("") + console.log("eerrroror", ErrorData) useEffect(() => { @@ -12,8 +14,11 @@ if( ErrorData.httpStatus === 401){ setShowModal(false) RefreshingToken() console.log('uaua') -} -}, []) +}else if(ErrorData.httpStatus === 404){ + setModalMensagem("Erro interno do sistema") +}else{setModalMensagem(ErrorData.mensagem)} + +}, [ErrorData]) return( @@ -31,7 +36,7 @@ return(
- {ErrorData.message} + {modalMensagem}
diff --git a/src/pages/TablePaciente.jsx b/src/pages/TablePaciente.jsx index 6d269f1..bdcbff0 100644 --- a/src/pages/TablePaciente.jsx +++ b/src/pages/TablePaciente.jsx @@ -104,7 +104,6 @@ function TablePaciente({ setCurrentPage, setPatientID }) { }; useEffect(() => { - const authHeader = getAuthorizationHeader() console.log(authHeader, 'aqui autorização') @@ -118,29 +117,23 @@ function TablePaciente({ setCurrentPage, setPatientID }) { redirect: 'follow' }; - fetch("https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/patients", requestOptions) // <-- Verifique se a URL está correta (patients) + fetch("https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/patients", requestOptions) .then(response => { // 1. VERIFICAÇÃO DO STATUS HTTP (Se não for 2xx) if (!response.ok) { - // Lemos o corpo do erro JSON (PostgREST envia o JSON mesmo no 404/401) return response.json().then(errorData => { - // 2. CRIAMOS O OBJETO DE ERRO CUSTOMIZADO COM TODOS OS DADOS NECESSÁRIOS const errorObject = { - httpStatus: response.status, // 404, 401, 400, etc. - apiCode: errorData.code, // PGRST205, 42501, etc. + httpStatus: response.status, + apiCode: errorData.code, message: errorData.message || response.statusText, details: errorData.details, hint: errorData.hint }; - // 3. LOG (para debug) console.error("ERRO DETALHADO:", errorObject); - - // 4. FORÇAMOS A FALHA DA PROMISE LANÇANDO O OBJETO CUSTOMIZADO - // NOTA: Ao lançar um objeto customizado, ele se torna o argumento 'error' no .catch throw errorObject; }); }