- {/* Header */}
+
Atenção
- {/* Body */}
+
- Por favor, preencha:
+ {cpfError ? 'Problema com o CPF:' : 'Por favor, preencha:'}
- {!formData.full_name &&
- Nome
}
- {!formData.cpf &&
- CPF
}
- {!formData.email &&
- Email
}
- {!formData.phone_mobile &&
- Telefone
}
+ {cpfError ? (
+
{cpfError}
+ ) : (
+ <>
+ {!formData.full_name &&
- Nome
}
+ {!formData.cpf &&
- CPF
}
+ {!formData.email &&
- Email
}
+ {!formData.phone_mobile &&
- Telefone
}
+ >
+ )}
- {/* Footer */}
+
)}
- {/* Modal de sucesso */}
- {showSuccessModal && (
-
-
- {/* Header */}
-
-
Sucesso
-
-
- {/* Body */}
-
-
- O cadastro do paciente foi realizado com sucesso.
-
-
-
- {/* Footer */}
-
-
-
-)}
-
);
}
diff --git a/src/pages/DoctorCadastroManager.jsx b/src/pages/DoctorCadastroManager.jsx
index 2aeca70..450e7f7 100644
--- a/src/pages/DoctorCadastroManager.jsx
+++ b/src/pages/DoctorCadastroManager.jsx
@@ -5,88 +5,305 @@ import API_KEY from '../components/utils/apiKeys';
import { useNavigate, useLocation } from 'react-router-dom';
function DoctorCadastroManager() {
- const [DoctorDict, setDoctorDict] = useState({})
+ const [doctorData, setDoctorData] = useState({});
+ const [isLoading, setIsLoading] = useState(false);
+ const [showSuccessModal, setShowSuccessModal] = useState(false);
+ const [showErrorModal, setShowErrorModal] = useState(false);
+ const [errorMessage, setErrorMessage] = useState('');
+
const navigate = useNavigate();
const location = useLocation();
const { getAuthorizationHeader, isAuthenticated } = useAuth();
const handleSaveDoctor = async (doctorData) => {
+ setIsLoading(true);
const authHeader = getAuthorizationHeader();
- var myHeaders = new Headers();
- myHeaders.append("Content-Type", "application/json");
- myHeaders.append("apikey", API_KEY);
- myHeaders.append("Authorization", authHeader);
-
- console.log(' Dados recebidos do Form:', doctorData);
-
- const cleanedData = {
- full_name: doctorData.full_name,
- cpf: doctorData.cpf ? doctorData.cpf.replace(/\D/g, '') : null,
- birth_date: doctorData.birth_date || null,
- email: doctorData.email,
- phone_mobile: doctorData.phone_mobile ? doctorData.phone_mobile.replace(/\D/g, '') : null,
- crm_uf: doctorData.crm_uf,
- crm: doctorData.crm,
- specialty: doctorData.specialty || null,
- cep: doctorData.cep ? doctorData.cep.replace(/\D/g, '') : null,
- street: doctorData.street || null,
- neighborhood: doctorData.neighborhood || null,
- city: doctorData.city || null,
- state: doctorData.state || null,
- number: doctorData.number || null,
- complement: doctorData.complement || null,
- phone2: doctorData.phone2 ? doctorData.phone2.replace(/\D/g, '') : null,
- };
-
- console.log(' Dados limpos para envio:', cleanedData);
-
- var raw = JSON.stringify(cleanedData);
-
- var requestOptions = {
- method: 'POST',
- headers: myHeaders,
- body: raw,
- redirect: 'follow'
- };
-
try {
+ var myHeaders = new Headers();
+ myHeaders.append("Content-Type", "application/json");
+ myHeaders.append("apikey", API_KEY);
+ myHeaders.append("Authorization", authHeader);
+
+ console.log('Dados recebidos do Form:', doctorData);
+
+ const cleanedData = {
+ full_name: doctorData.full_name,
+ cpf: doctorData.cpf ? doctorData.cpf.replace(/\D/g, '') : null,
+ birth_date: doctorData.birth_date || null,
+ email: doctorData.email,
+ phone_mobile: doctorData.phone_mobile ? doctorData.phone_mobile.replace(/\D/g, '') : null,
+ crm_uf: doctorData.crm_uf,
+ crm: doctorData.crm,
+ specialty: doctorData.specialty || null,
+ cep: doctorData.cep ? doctorData.cep.replace(/\D/g, '') : null,
+ street: doctorData.street || null,
+ neighborhood: doctorData.neighborhood || null,
+ city: doctorData.city || null,
+ state: doctorData.state || null,
+ number: doctorData.number || null,
+ complement: doctorData.complement || null,
+ phone2: doctorData.phone2 ? doctorData.phone2.replace(/\D/g, '') : null,
+ };
+
+ console.log('Dados limpos para envio:', cleanedData);
+
+ var raw = JSON.stringify(cleanedData);
+
+ var requestOptions = {
+ method: 'POST',
+ headers: myHeaders,
+ body: raw,
+ redirect: 'follow'
+ };
+
const response = await fetch("https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/doctors", requestOptions);
- console.log(" Status da resposta:", response.status);
- console.log(" Response ok:", response.ok);
+ console.log("Status da resposta:", response.status);
+ console.log("Response ok:", response.ok);
if (!response.ok) {
- let errorMessage = `Erro HTTP: ${response.status}`;
- try {
- const errorData = await response.json();
- console.error(" Erro detalhado:", errorData);
- errorMessage = errorData.message || errorData.details || errorMessage;
- } catch (e) {
- const errorText = await response.text();
- console.error(" Erro texto:", errorText);
- errorMessage = errorText || errorMessage;
+ let errorMessage = `Erro ao salvar médico (${response.status})`;
+
+
+ const responseText = await response.text();
+ console.log("Conteúdo da resposta:", responseText);
+
+ if (responseText) {
+ try {
+ const errorData = JSON.parse(responseText);
+ console.error("Erro detalhado:", errorData);
+ errorMessage = errorData.message || errorData.details || errorMessage;
+ } catch (jsonError) {
+
+ errorMessage = responseText || errorMessage;
+ }
+ } else {
+ errorMessage = `Resposta vazia do servidor (${response.status})`;
}
+
throw new Error(errorMessage);
}
- const result = await response.json();
- console.log("Médico salvo no backend:", result);
+ const responseText = await response.text();
+ let result = null;
+
+ if (responseText) {
+ try {
+ result = JSON.parse(responseText);
+ console.log("Médico salvo no backend:", result);
+ } catch (jsonError) {
+ console.warn("Resposta não é JSON válido, mas request foi bem-sucedido");
+ result = { success: true, status: response.status };
+ }
+ } else {
+ console.log("Resposta vazia - assumindo sucesso");
+ result = { success: true, status: response.status };
+ }
- // Redireciona para a lista de médicos do perfil atual
- const prefixo = location.pathname.split("/")[1];
- navigate(`/${prefixo}/medicos`);
-
- return result;
+
+ setShowSuccessModal(true);
} catch (error) {
- console.error(" Erro ao salvar Médico:", error);
- throw error;
+ console.error("Erro ao salvar Médico:", error);
+
+ let userFriendlyMessage = error.message;
+
+ if (error.message.includes('doctors_cpf_key') || error.message.includes('duplicate key')) {
+ userFriendlyMessage = 'Já existe um médico cadastrado com este CPF. Verifique os dados ou edite o médico existente.';
+ } else if (error.message.includes('Unexpected end of JSON input')) {
+ userFriendlyMessage = 'Erro de comunicação com o servidor. Tente novamente.';
+ }
+
+ setErrorMessage(userFriendlyMessage);
+ setShowErrorModal(true);
+ } finally {
+ setIsLoading(false);
}
};
+ const handleCloseSuccessModal = () => {
+ setShowSuccessModal(false);
+
+ const prefixo = location.pathname.split("/")[1];
+ navigate(`/${prefixo}/medicos`);
+ };
+
+ const handleCloseErrorModal = () => {
+ setShowErrorModal(false);
+ };
+
return (
<>
+
+ {showSuccessModal && (
+
+
+
+
Sucesso
+
+ ×
+
+
+
+
+
+ Médico cadastrado com sucesso!
+
+
+
+
+
+ Fechar
+
+
+
+
+ )}
+
+
+ {showErrorModal && (
+
+
+
+
Erro
+
+ ×
+
+
+
+
+
+
+
+ Fechar
+
+
+
+
+ )}
+
Cadastro de Médicos
@@ -95,9 +312,9 @@ function DoctorCadastroManager() {
diff --git a/src/pages/PatientCadastroManager.jsx b/src/pages/PatientCadastroManager.jsx
index 21f6ad6..701e6b5 100644
--- a/src/pages/PatientCadastroManager.jsx
+++ b/src/pages/PatientCadastroManager.jsx
@@ -1,37 +1,98 @@
import {useState} from 'react';
import React from 'react';
-import { useNavigate, useLocation } from 'react-router-dom';
+import { useNavigate } from 'react-router-dom';
import PatientForm from '../components/patients/PatientForm';
import API_KEY from '../components/utils/apiKeys';
import { useAuth } from '../components/utils/AuthProvider';
function PatientCadastroManager( {setCurrentPage} ) {
- const navigate = useNavigate();
- const location = useLocation();
+ const navigate = useNavigate()
const [showModal, setShowModal] = useState(false);
const [infosModal, setInfosModal] = useState({title:'', message:''});
+ const [isLoading, setIsLoading] = useState(false);
const { getAuthorizationHeader, isAuthenticated } = useAuth();
const [formData, setFormData] = useState({})
+
+
+ const validarCPF = (cpf) => {
+ cpf = cpf.replace(/\D/g, '');
+
+ if (cpf.length !== 11) return false;
+
+
+ if (/^(\d)\1+$/.test(cpf)) return false;
+
+ let soma = 0;
+ let resto;
+
+ for (let i = 1; i <= 9; i++) {
+ soma = soma + parseInt(cpf.substring(i-1, i)) * (11 - i);
+ }
+
+ resto = (soma * 10) % 11;
+ if ((resto === 10) || (resto === 11)) resto = 0;
+ if (resto !== parseInt(cpf.substring(9, 10))) return false;
+
+ soma = 0;
+ for (let i = 1; i <= 10; i++) {
+ soma = soma + parseInt(cpf.substring(i-1, i)) * (12 - i);
+ }
+
+ resto = (soma * 10) % 11;
+ if ((resto === 10) || (resto === 11)) resto = 0;
+ if (resto !== parseInt(cpf.substring(10, 11))) return false;
+
+ return true;
+ }
const handleSavePatient = async (patientData) => {
- console.log('🔄 Iniciando salvamento do paciente:', patientData);
+ console.log(' Iniciando salvamento do paciente:', patientData);
+ setIsLoading(true);
try {
+
+ console.log(' Verificando autenticação...');
+ if (!isAuthenticated) {
+ throw new Error('Usuário não autenticado');
+ }
+
const authHeader = getAuthorizationHeader();
+ console.log(' Header de autorização:', authHeader ? 'Presente' : 'Faltando');
+
+ if (!authHeader) {
+ throw new Error('Header de autorização não encontrado');
+ }
+
+
+ const cpfLimpo = patientData.cpf.replace(/\D/g, '');
+ if (!validarCPF(cpfLimpo)) {
+ throw new Error('CPF inválido. Por favor, verifique o número digitado.');
+ }
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("apikey", API_KEY);
myHeaders.append("Authorization", authHeader);
+ myHeaders.append("Prefer", "return=representation");
+
+ console.log(' Headers configurados:', {
+ 'Content-Type': 'application/json',
+ 'apikey': API_KEY ? 'Presente' : 'Faltando',
+ 'Authorization': authHeader ? 'Presente' : 'Faltando',
+ 'Prefer': 'return=representation'
+ });
const cleanedData = {
full_name: patientData.full_name,
- cpf: patientData.cpf.replace(/\D/g, ''),
- birth_date: patientData.birth_date,
- sex: patientData.sex,
+ cpf: cpfLimpo,
email: patientData.email,
phone_mobile: patientData.phone_mobile,
+
+ birth_date: patientData.birth_date || null,
+ sex: patientData.sex === 'Masculino' ? 'M' :
+ patientData.sex === 'Feminino' ? 'F' :
+ patientData.sex || null,
social_name: patientData.social_name || null,
rg: patientData.rg || null,
blood_type: patientData.blood_type || null,
@@ -41,9 +102,14 @@ function PatientCadastroManager( {setCurrentPage} ) {
notes: patientData.notes || null,
};
- console.log('📤 Dados limpos para envio:', cleanedData);
+ console.log(' Dados limpos para envio:', cleanedData);
+
+ if (!cleanedData.full_name || !cleanedData.cpf || !cleanedData.email || !cleanedData.phone_mobile) {
+ throw new Error('Dados obrigatórios faltando: nome, CPF, email e telefone são necessários');
+ }
var raw = JSON.stringify(cleanedData);
+ console.log(' Payload JSON:', raw);
var requestOptions = {
method: 'POST',
@@ -52,39 +118,74 @@ function PatientCadastroManager( {setCurrentPage} ) {
redirect: 'follow'
};
+ console.log(' Fazendo requisição para API...');
const response = await fetch("https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/patients", requestOptions);
- console.log('📨 Status da resposta:', response.status);
+ console.log(' Status da resposta:', response.status);
console.log(' Response ok:', response.ok);
+ let responseData;
+ try {
+ responseData = await response.json();
+ console.log(' Corpo da resposta:', responseData);
+ } catch (jsonError) {
+ console.log(' Não foi possível parsear JSON da resposta:', jsonError);
+ responseData = { error: 'Resposta inválida da API' };
+ }
+
+
if (!response.ok) {
- let errorMessage = `Erro HTTP: ${response.status}`;
- try {
- const errorData = await response.json();
- errorMessage = errorData.message || errorData.details || errorMessage;
- } catch (e) {
- const errorText = await response.text();
- errorMessage = errorText || errorMessage;
+ console.error(' Erro da API - Detalhes:', {
+ status: response.status,
+ statusText: response.statusText,
+ data: responseData
+ });
+
+ let errorMessage = 'Erro ao salvar paciente';
+
+ if (response.status === 401) {
+ errorMessage = 'Não autorizado. Verifique suas credenciais.';
+ } else if (response.status === 403) {
+ errorMessage = 'Acesso proibido. Verifique suas permissões.';
+ } else if (response.status === 409) {
+ errorMessage = 'Paciente com este CPF já existe.';
+ } else if (response.status === 400) {
+ errorMessage = `Dados inválidos: ${responseData.details || responseData.message || 'Verifique os campos'}`;
+ } else if (response.status === 422) {
+ errorMessage = `Dados de entrada inválidos: ${responseData.details || 'Verifique o formato dos dados'}`;
+ } else if (response.status >= 500) {
+ errorMessage = 'Erro interno do servidor. Tente novamente mais tarde.';
+ } else {
+ errorMessage = `Erro ${response.status}: ${responseData.message || responseData.error || 'Erro desconhecido'}`;
}
+
throw new Error(errorMessage);
}
- const result = await response.json();
- console.log("Paciente salvo no backend:", result);
-
- // Redireciona para a lista de pacientes do perfil atual
- const prefixo = location.pathname.split("/")[1];
- navigate(`/${prefixo}/pacientes`);
-
- return result;
-
- } catch (error) {
- console.error(error);
+ console.log(' Paciente salvo com sucesso:', responseData);
+
+
setInfosModal({
- title: 'Erro de conexão',
- message: 'Não foi possível conectar ao servidor. Verifique sua internet e tente novamente.'
+ title: 'Sucesso',
+ message: 'O cadastro do paciente foi realizado com sucesso.'
});
setShowModal(true);
+
+
+ setTimeout(() => {
+ setShowModal(false);
+ navigate('/secretaria/pacientes');
+ }, 2000);
+
+ } catch (error) {
+ console.error(' Erro completo ao salvar paciente:', error);
+ setInfosModal({
+ title: 'Erro',
+ message: error.message || 'Não foi possível conectar ao servidor. Verifique sua internet e tente novamente.'
+ });
+ setShowModal(true);
+ } finally {
+ setIsLoading(false);
}
};
@@ -92,44 +193,117 @@ function PatientCadastroManager( {setCurrentPage} ) {
<>
{showModal &&(
-
-
-
-
-
{infosModal.title}
- setShowModal(false)}
- >
-
-
-
- setShowModal(false)}
- >
- Fechar
-
-
+
+
+
+
+
{infosModal.title}
+ setShowModal(false)}
+ style={{
+ background: "none",
+ border: "none",
+ fontSize: "20px",
+ color: "#fff",
+ cursor: "pointer",
+ }}
+ >
+ ×
+
+
+
+
+
+
+ {infosModal.message}
+
+ {infosModal.title === 'Erro' && (
+
+
+ )}
+
+
+
+
+ {
+ setShowModal(false);
+ if (infosModal.title === 'Sucesso') {
+ navigate('/secretaria/pacientes');
+ }
+ }}
+ style={{
+ backgroundColor: "#1e3a8a",
+ color: "#fff",
+ border: "none",
+ padding: "8px 20px",
+ borderRadius: "6px",
+ cursor: "pointer",
+ fontSize: "1rem",
+ fontWeight: "bold",
+ }}
+ >
+ Fechar
+
)}
Cadastro de Pacientes
+ {isLoading && (
+
+
+ Salvando paciente...
+
+ )}
navigate('/secretaria/pacientes')}
formData={formData}
setFormData={setFormData}
+ isLoading={isLoading}
/>