routes1
This commit is contained in:
commit
9a663d88ec
@ -1,138 +1,271 @@
|
|||||||
import React, { useState } from "react";
|
import React, { useState } from "react";
|
||||||
import { Link } from "react-router-dom";
|
import { Link, useNavigate } from "react-router-dom";
|
||||||
import menuItems from "../data/sidebar-items-medico.json"; // Use "sidebar-items-secretaria.json" para secretaria e "sidebar-items-adm.json" para ADM
|
import menuItems from "../data/sidebar-items-medico.json";
|
||||||
import TrocardePerfis from "./TrocardePerfis";
|
import TrocardePerfis from "./TrocardePerfis";
|
||||||
|
|
||||||
|
function Sidebar({ menuItems }) {
|
||||||
|
const [isActive, setIsActive] = useState(true);
|
||||||
|
const [openSubmenu, setOpenSubmenu] = useState(null);
|
||||||
|
const [showLogoutModal, setShowLogoutModal] = useState(false);
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
// 1. Recebe 'menuItems' e 'onLogout' como props
|
const toggleSidebar = () => {
|
||||||
function Sidebar({ menuItems, onLogout }) {
|
setIsActive(!isActive);
|
||||||
const [isActive, setIsActive] = useState(true);
|
};
|
||||||
const [openSubmenu, setOpenSubmenu] = useState(null);
|
|
||||||
|
|
||||||
const toggleSidebar = () => {
|
const handleSubmenuClick = (submenuName) => {
|
||||||
setIsActive(!isActive);
|
setOpenSubmenu(openSubmenu === submenuName ? null : submenuName);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSubmenuClick = (submenuName) => {
|
const handleLogoutClick = () => {
|
||||||
setOpenSubmenu(openSubmenu === submenuName ? null : submenuName);
|
setShowLogoutModal(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
const renderLink = (item) => {
|
const handleLogoutConfirm = async () => {
|
||||||
// Links internos (rotas do React Router)
|
try {
|
||||||
if (item.url && item.url.startsWith("/")) {
|
const token = localStorage.getItem('token') ||
|
||||||
return (
|
localStorage.getItem('authToken') ||
|
||||||
<Link to={item.url} className="sidebar-link">
|
localStorage.getItem('userToken') ||
|
||||||
{item.icon && <i className={`bi bi-${item.icon}`}></i>}
|
localStorage.getItem('access_token') ||
|
||||||
<span>{item.name}</span>
|
sessionStorage.getItem('token') ||
|
||||||
</Link>
|
sessionStorage.getItem('authToken');
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Links externos
|
if (token) {
|
||||||
return (
|
const response = await fetch('https://mock.apidog.com/m1/1053378-0-default/auth/v1/logout', {
|
||||||
<a
|
method: 'POST',
|
||||||
href={item.url}
|
headers: {
|
||||||
className="sidebar-link"
|
'Content-Type': 'application/json',
|
||||||
target="_blank"
|
'Authorization': `Bearer ${token}`
|
||||||
rel="noreferrer"
|
}
|
||||||
>
|
});
|
||||||
{item.icon && <i className={`bi bi-${item.icon}`}></i>}
|
|
||||||
<span>{item.name}</span>
|
|
||||||
</a>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
if (response.status === 204) {
|
||||||
<div id="sidebar" className={isActive ? "active" : ""}>
|
console.log('Logout realizado com sucesso');
|
||||||
<div className="sidebar-wrapper active">
|
} else if (response.status === 401) {
|
||||||
<div className="sidebar-header">
|
console.log('Token inválido ou expirado');
|
||||||
{/* ... Header... */}
|
} else {
|
||||||
<div className="d-flex justify-content-between">
|
try {
|
||||||
<div className="logo">
|
const errorData = await response.json();
|
||||||
<Link to="/">
|
console.error('Erro no logout:', errorData);
|
||||||
<h1>MediConnect</h1>
|
} catch {
|
||||||
</Link>
|
console.error('Erro no logout - status:', response.status);
|
||||||
</div>
|
}
|
||||||
<div className="toggler">
|
}
|
||||||
<button
|
}
|
||||||
type="button"
|
|
||||||
className="sidebar-hide d-xl-none d-block btn"
|
clearAuthData();
|
||||||
onClick={toggleSidebar}
|
navigate('/login');
|
||||||
>
|
|
||||||
<i className="bi bi-x bi-middle"></i>
|
} catch (error) {
|
||||||
</button>
|
console.error('Erro durante logout:', error);
|
||||||
</div>
|
clearAuthData();
|
||||||
</div>
|
navigate('/login');
|
||||||
</div>
|
} finally {
|
||||||
|
setShowLogoutModal(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const clearAuthData = () => {
|
||||||
|
localStorage.removeItem('token');
|
||||||
|
localStorage.removeItem('authToken');
|
||||||
|
localStorage.removeItem('userToken');
|
||||||
|
localStorage.removeItem('access_token');
|
||||||
|
localStorage.removeItem('user');
|
||||||
|
localStorage.removeItem('auth');
|
||||||
|
localStorage.removeItem('userData');
|
||||||
|
|
||||||
|
sessionStorage.removeItem('token');
|
||||||
|
sessionStorage.removeItem('authToken');
|
||||||
|
sessionStorage.removeItem('userToken');
|
||||||
|
sessionStorage.removeItem('access_token');
|
||||||
|
sessionStorage.removeItem('user');
|
||||||
|
sessionStorage.removeItem('auth');
|
||||||
|
sessionStorage.removeItem('userData');
|
||||||
|
|
||||||
|
if (window.caches) {
|
||||||
|
caches.keys().then(names => {
|
||||||
|
names.forEach(name => {
|
||||||
|
if (name.includes('auth') || name.includes('api')) {
|
||||||
|
caches.delete(name);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleLogoutCancel = () => {
|
||||||
|
setShowLogoutModal(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderLink = (item) => {
|
||||||
|
if (item.url && item.url.startsWith("/")) {
|
||||||
|
return (
|
||||||
|
<Link to={item.url} className="sidebar-link">
|
||||||
|
{item.icon && <i className={`bi bi-${item.icon}`}></i>}
|
||||||
|
<span>{item.name}</span>
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
<div className="sidebar-menu">
|
|
||||||
<ul className="menu">
|
|
||||||
{menuItems && menuItems.map((item, index) => {
|
|
||||||
if (item.isTitle) {
|
|
||||||
return (
|
return (
|
||||||
<li key={index} className="sidebar-title">
|
<a
|
||||||
{item.name}
|
href={item.url}
|
||||||
</li>
|
className="sidebar-link"
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
>
|
||||||
|
{item.icon && <i className={`bi bi-${item.icon}`}></i>}
|
||||||
|
<span>{item.name}</span>
|
||||||
|
</a>
|
||||||
);
|
);
|
||||||
}
|
};
|
||||||
|
|
||||||
if (item.submenu) {
|
return (
|
||||||
return (
|
<>
|
||||||
<li
|
{showLogoutModal && (
|
||||||
key={index}
|
<div className="modal-overlay" style={{
|
||||||
className={`sidebar-item has-sub ${
|
position: 'fixed',
|
||||||
openSubmenu === item.key ? "active" : ""
|
top: 0,
|
||||||
}`}
|
left: 0,
|
||||||
>
|
right: 0,
|
||||||
{/* ... Lógica de Submenu ... */}
|
bottom: 0,
|
||||||
<button
|
backgroundColor: 'rgba(0, 0, 0, 0.5)',
|
||||||
type="button"
|
display: 'flex',
|
||||||
className="sidebar-link btn"
|
justifyContent: 'center',
|
||||||
onClick={() => handleSubmenuClick(item.key)}
|
alignItems: 'center',
|
||||||
>
|
zIndex: 9999
|
||||||
<i className={`bi bi-${item.icon}`}></i>
|
}}>
|
||||||
<span>{item.name}</span>
|
<div className="modal-content" style={{
|
||||||
</button>
|
backgroundColor: 'white',
|
||||||
<ul
|
padding: '2rem',
|
||||||
className={`submenu ${
|
borderRadius: '8px',
|
||||||
openSubmenu === item.key ? "active" : ""
|
boxShadow: '0 4px 6px rgba(0, 0, 0, 0.1)',
|
||||||
}`}
|
maxWidth: '400px',
|
||||||
>
|
width: '90%'
|
||||||
{item.submenu.map((subItem, subIndex) => (
|
}}>
|
||||||
<li key={subIndex} className="submenu-item">
|
<h3 style={{ marginBottom: '1rem' }}>Confirmar Logout</h3>
|
||||||
{renderLink(subItem)}
|
<p style={{ marginBottom: '2rem' }}>Tem certeza que deseja encerrar a sessão?</p>
|
||||||
</li>
|
<div style={{ display: 'flex', gap: '1rem', justifyContent: 'flex-end' }}>
|
||||||
))}
|
<button
|
||||||
</ul>
|
onClick={handleLogoutCancel}
|
||||||
</li>
|
style={{
|
||||||
);
|
padding: '0.5rem 1rem',
|
||||||
}
|
border: '1px solid #ccc',
|
||||||
|
borderRadius: '4px',
|
||||||
|
backgroundColor: 'transparent',
|
||||||
|
cursor: 'pointer'
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Cancelar
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={handleLogoutConfirm}
|
||||||
|
style={{
|
||||||
|
padding: '0.5rem 1rem',
|
||||||
|
border: 'none',
|
||||||
|
borderRadius: '4px',
|
||||||
|
backgroundColor: '#dc3545',
|
||||||
|
color: 'white',
|
||||||
|
cursor: 'pointer'
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Sair
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
return (
|
<div id="sidebar" className={isActive ? "active" : ""}>
|
||||||
<li key={index} className="sidebar-item">
|
<div className="sidebar-wrapper active">
|
||||||
{renderLink(item)}
|
<div className="sidebar-header">
|
||||||
</li>
|
<div className="d-flex justify-content-between">
|
||||||
);
|
<div className="logo">
|
||||||
})}
|
<Link to="/">
|
||||||
{/* 3. Adiciona o botão de logout no final do menu */}
|
<h1>MediConnect</h1>
|
||||||
<li className="sidebar-item" onClick={onLogout}>
|
</Link>
|
||||||
<button type="button" className="sidebar-link btn">
|
</div>
|
||||||
<i className="bi bi-box-arrow-right"></i>
|
<div className="toggler">
|
||||||
<span>Sair (Logout)</span>
|
<button
|
||||||
</button>
|
type="button"
|
||||||
</li>
|
className="sidebar-hide d-xl-none d-block btn"
|
||||||
|
onClick={toggleSidebar}
|
||||||
|
>
|
||||||
|
<i className="bi bi-x bi-middle"></i>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<TrocardePerfis />
|
<div className="sidebar-menu">
|
||||||
|
<ul className="menu">
|
||||||
|
{menuItems && menuItems.map((item, index) => {
|
||||||
|
if (item.isTitle) {
|
||||||
|
return (
|
||||||
|
<li key={index} className="sidebar-title">
|
||||||
|
{item.name}
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
</ul>
|
if (item.submenu) {
|
||||||
</div>
|
return (
|
||||||
|
<li
|
||||||
|
key={index}
|
||||||
|
className={`sidebar-item has-sub ${openSubmenu === item.key ? "active" : ""
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="sidebar-link btn"
|
||||||
|
onClick={() => handleSubmenuClick(item.key)}
|
||||||
|
>
|
||||||
|
<i className={`bi bi-${item.icon}`}></i>
|
||||||
|
<span>{item.name}</span>
|
||||||
|
</button>
|
||||||
|
<ul
|
||||||
|
className={`submenu ${openSubmenu === item.key ? "active" : ""
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{item.submenu.map((subItem, subIndex) => (
|
||||||
|
<li key={subIndex} className="submenu-item">
|
||||||
|
{renderLink(subItem)}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
<button className="sidebar-toggler btn x" onClick={toggleSidebar}>
|
return (
|
||||||
<i data-feather="x"></i>
|
<li key={index} className="sidebar-item">
|
||||||
</button>
|
{renderLink(item)}
|
||||||
</div>
|
</li>
|
||||||
</div>
|
);
|
||||||
);
|
})}
|
||||||
|
|
||||||
|
<li className="sidebar-item">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="sidebar-link btn"
|
||||||
|
onClick={handleLogoutClick}
|
||||||
|
>
|
||||||
|
<i className="bi bi-box-arrow-right"></i>
|
||||||
|
<span>Sair (Logout)</span>
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
|
||||||
|
<TrocardePerfis />
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button className="sidebar-toggler btn x" onClick={toggleSidebar}>
|
||||||
|
<i data-feather="x"></i>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default Sidebar;
|
export default Sidebar;
|
||||||
@ -1,11 +1,10 @@
|
|||||||
import React, { useState } from 'react';
|
import React, { useState, useRef } from 'react';
|
||||||
import { Link,useNavigate, useLocation } from 'react-router-dom';
|
import { Link, useNavigate, useLocation } from 'react-router-dom';
|
||||||
|
|
||||||
function DoctorForm({ onSave, onCancel, formData, setFormData }) {
|
function DoctorForm({ onSave, onCancel, formData, setFormData, isLoading }) {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
|
|
||||||
// Funções para formatar telefone e CPF
|
|
||||||
const FormatTelefones = (valor) => {
|
const FormatTelefones = (valor) => {
|
||||||
const digits = String(valor).replace(/\D/g, '').slice(0, 11);
|
const digits = String(valor).replace(/\D/g, '').slice(0, 11);
|
||||||
return digits
|
return digits
|
||||||
@ -23,20 +22,53 @@ function DoctorForm({ onSave, onCancel, formData, setFormData }) {
|
|||||||
.replace(/(\d{3})(\d{1,2})$/, '$1-$2');
|
.replace(/(\d{3})(\d{1,2})$/, '$1-$2');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
const validarCPF = (cpf) => {
|
||||||
|
const cpfLimpo = cpf.replace(/\D/g, '');
|
||||||
|
|
||||||
|
if (cpfLimpo.length !== 11) return false;
|
||||||
|
|
||||||
|
|
||||||
|
if (/^(\d)\1+$/.test(cpfLimpo)) return false;
|
||||||
|
|
||||||
|
|
||||||
|
let soma = 0;
|
||||||
|
for (let i = 0; i < 9; i++) {
|
||||||
|
soma += parseInt(cpfLimpo.charAt(i)) * (10 - i);
|
||||||
|
}
|
||||||
|
let resto = 11 - (soma % 11);
|
||||||
|
let digito1 = resto === 10 || resto === 11 ? 0 : resto;
|
||||||
|
|
||||||
|
|
||||||
|
soma = 0;
|
||||||
|
for (let i = 0; i < 10; i++) {
|
||||||
|
soma += parseInt(cpfLimpo.charAt(i)) * (11 - i);
|
||||||
|
}
|
||||||
|
resto = 11 - (soma % 11);
|
||||||
|
let digito2 = resto === 10 || resto === 11 ? 0 : resto;
|
||||||
|
|
||||||
|
|
||||||
|
return digito1 === parseInt(cpfLimpo.charAt(9)) && digito2 === parseInt(cpfLimpo.charAt(10));
|
||||||
|
};
|
||||||
|
|
||||||
const [avatarUrl, setAvatarUrl] = useState(null);
|
const [avatarUrl, setAvatarUrl] = useState(null);
|
||||||
|
const [showRequiredModal, setShowRequiredModal] = useState(false);
|
||||||
|
const [emptyFields, setEmptyFields] = useState([]);
|
||||||
|
const [cpfError, setCpfError] = useState('');
|
||||||
|
|
||||||
|
const nomeRef = useRef(null);
|
||||||
|
const cpfRef = useRef(null);
|
||||||
|
const emailRef = useRef(null);
|
||||||
|
const telefoneRef = useRef(null);
|
||||||
|
const crmUfRef = useRef(null);
|
||||||
|
const crmRef = useRef(null);
|
||||||
|
|
||||||
const [collapsedSections, setCollapsedSections] = useState({
|
const [collapsedSections, setCollapsedSections] = useState({
|
||||||
dadosPessoais: true,
|
dadosPessoais: true,
|
||||||
infoMedicas: false,
|
|
||||||
infoConvenio: false,
|
|
||||||
endereco: false,
|
|
||||||
contato: false,
|
contato: false,
|
||||||
|
endereco: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
const [showModal, setShowModal] = useState(false);
|
|
||||||
const [showSuccessModal, setShowSuccessModal] = useState(false);
|
|
||||||
const [errorModalMsg, setErrorModalMsg] = useState('');
|
|
||||||
|
|
||||||
const handleToggleCollapse = (section) => {
|
const handleToggleCollapse = (section) => {
|
||||||
setCollapsedSections(prevState => ({
|
setCollapsedSections(prevState => ({
|
||||||
...prevState,
|
...prevState,
|
||||||
@ -47,6 +79,16 @@ function DoctorForm({ onSave, onCancel, formData, setFormData }) {
|
|||||||
const handleChange = (e) => {
|
const handleChange = (e) => {
|
||||||
const { name, value, type, checked, files } = e.target;
|
const { name, value, type, checked, files } = e.target;
|
||||||
|
|
||||||
|
|
||||||
|
if (value && emptyFields.includes(name)) {
|
||||||
|
setEmptyFields(prev => prev.filter(field => field !== name));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if (name === 'cpf' && cpfError) {
|
||||||
|
setCpfError('');
|
||||||
|
}
|
||||||
|
|
||||||
if (type === 'checkbox') {
|
if (type === 'checkbox') {
|
||||||
setFormData(prev => ({ ...prev, [name]: checked }));
|
setFormData(prev => ({ ...prev, [name]: checked }));
|
||||||
} else if (type === 'file') {
|
} else if (type === 'file') {
|
||||||
@ -65,6 +107,16 @@ function DoctorForm({ onSave, onCancel, formData, setFormData }) {
|
|||||||
} else if (name.includes('cpf')) {
|
} else if (name.includes('cpf')) {
|
||||||
let cpfFormatado = FormatCPF(value);
|
let cpfFormatado = FormatCPF(value);
|
||||||
setFormData(prev => ({ ...prev, [name]: cpfFormatado }));
|
setFormData(prev => ({ ...prev, [name]: cpfFormatado }));
|
||||||
|
|
||||||
|
|
||||||
|
const cpfLimpo = cpfFormatado.replace(/\D/g, '');
|
||||||
|
if (cpfLimpo.length === 11) {
|
||||||
|
if (!validarCPF(cpfFormatado)) {
|
||||||
|
setCpfError('CPF inválido');
|
||||||
|
} else {
|
||||||
|
setCpfError('');
|
||||||
|
}
|
||||||
|
}
|
||||||
} else if (name.includes('phone')) {
|
} else if (name.includes('phone')) {
|
||||||
let telefoneFormatado = FormatTelefones(value);
|
let telefoneFormatado = FormatTelefones(value);
|
||||||
setFormData(prev => ({ ...prev, [name]: telefoneFormatado }));
|
setFormData(prev => ({ ...prev, [name]: telefoneFormatado }));
|
||||||
@ -88,48 +140,133 @@ function DoctorForm({ onSave, onCancel, formData, setFormData }) {
|
|||||||
state: data.uf || ''
|
state: data.uf || ''
|
||||||
}));
|
}));
|
||||||
} else {
|
} else {
|
||||||
setErrorModalMsg('CEP não encontrado!');
|
setShowRequiredModal(true);
|
||||||
setShowModal(true);
|
setEmptyFields(['cep']);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setErrorModalMsg('Erro ao buscar o CEP.');
|
setShowRequiredModal(true);
|
||||||
setShowModal(true);
|
setEmptyFields(['cep']);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
const scrollToEmptyField = (fieldName) => {
|
||||||
|
let fieldRef = null;
|
||||||
|
|
||||||
|
switch (fieldName) {
|
||||||
|
case 'full_name':
|
||||||
|
fieldRef = nomeRef;
|
||||||
|
setCollapsedSections(prev => ({ ...prev, dadosPessoais: true }));
|
||||||
|
break;
|
||||||
|
case 'cpf':
|
||||||
|
fieldRef = cpfRef;
|
||||||
|
setCollapsedSections(prev => ({ ...prev, dadosPessoais: true }));
|
||||||
|
break;
|
||||||
|
case 'email':
|
||||||
|
fieldRef = emailRef;
|
||||||
|
setCollapsedSections(prev => ({ ...prev, contato: true }));
|
||||||
|
break;
|
||||||
|
case 'phone_mobile':
|
||||||
|
fieldRef = telefoneRef;
|
||||||
|
setCollapsedSections(prev => ({ ...prev, contato: true }));
|
||||||
|
break;
|
||||||
|
case 'crm_uf':
|
||||||
|
fieldRef = crmUfRef;
|
||||||
|
setCollapsedSections(prev => ({ ...prev, dadosPessoais: true }));
|
||||||
|
break;
|
||||||
|
case 'crm':
|
||||||
|
fieldRef = crmRef;
|
||||||
|
setCollapsedSections(prev => ({ ...prev, dadosPessoais: true }));
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
if (fieldRef.current) {
|
||||||
|
fieldRef.current.scrollIntoView({
|
||||||
|
behavior: 'smooth',
|
||||||
|
block: 'center'
|
||||||
|
});
|
||||||
|
fieldRef.current.focus();
|
||||||
|
|
||||||
|
|
||||||
|
fieldRef.current.style.border = '2px solid #dc3545';
|
||||||
|
fieldRef.current.style.boxShadow = '0 0 0 0.2rem rgba(220, 53, 69, 0.25)';
|
||||||
|
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
if (fieldRef.current) {
|
||||||
|
fieldRef.current.style.border = '';
|
||||||
|
fieldRef.current.style.boxShadow = '';
|
||||||
|
}
|
||||||
|
}, 3000);
|
||||||
|
}
|
||||||
|
}, 300);
|
||||||
|
};
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
if (!formData.full_name || !formData.cpf || !formData.email || !formData.phone_mobile || !formData.crm_uf || !formData.crm) {
|
|
||||||
setErrorModalMsg('Por favor, preencha todos os campos obrigatórios.');
|
const missingFields = [];
|
||||||
setShowModal(true);
|
if (!formData.full_name) missingFields.push('full_name');
|
||||||
|
if (!formData.cpf) missingFields.push('cpf');
|
||||||
|
if (!formData.email) missingFields.push('email');
|
||||||
|
if (!formData.phone_mobile) missingFields.push('phone_mobile');
|
||||||
|
if (!formData.crm_uf) missingFields.push('crm_uf');
|
||||||
|
if (!formData.crm) missingFields.push('crm');
|
||||||
|
|
||||||
|
if (missingFields.length > 0) {
|
||||||
|
setEmptyFields(missingFields);
|
||||||
|
setShowRequiredModal(true);
|
||||||
|
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
if (missingFields.length > 0) {
|
||||||
|
scrollToEmptyField(missingFields[0]);
|
||||||
|
}
|
||||||
|
}, 500);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
const cpfLimpo = formData.cpf.replace(/\D/g, '');
|
const cpfLimpo = formData.cpf.replace(/\D/g, '');
|
||||||
if (cpfLimpo.length !== 11) {
|
if (cpfLimpo.length !== 11) {
|
||||||
setErrorModalMsg('CPF inválido. Por favor, verifique o número digitado.');
|
setShowRequiredModal(true);
|
||||||
setShowModal(true);
|
setEmptyFields(['cpf']);
|
||||||
|
setCpfError('CPF deve ter 11 dígitos');
|
||||||
|
setTimeout(() => scrollToEmptyField('cpf'), 500);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if (!validarCPF(formData.cpf)) {
|
||||||
|
setShowRequiredModal(true);
|
||||||
|
setEmptyFields(['cpf']);
|
||||||
|
setCpfError('CPF inválido');
|
||||||
|
setTimeout(() => scrollToEmptyField('cpf'), 500);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await onSave({ ...formData });
|
await onSave({ ...formData });
|
||||||
setShowSuccessModal(true);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setErrorModalMsg('médico salvo com sucesso');
|
|
||||||
setShowModal(true);
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleCloseSuccessModal = () => {
|
const handleModalClose = () => {
|
||||||
setShowSuccessModal(false);
|
setShowRequiredModal(false);
|
||||||
const prefixo = location.pathname.split("/")[1];
|
|
||||||
navigate(`/${prefixo}/medicos`);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{showModal && (
|
|
||||||
|
{showRequiredModal && (
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
display: "flex",
|
display: "flex",
|
||||||
@ -165,7 +302,7 @@ function DoctorForm({ onSave, onCancel, formData, setFormData }) {
|
|||||||
>
|
>
|
||||||
<h5 style={{ color: "#fff", margin: 0, fontSize: "1.2rem", fontWeight: "bold" }}>Atenção</h5>
|
<h5 style={{ color: "#fff", margin: 0, fontSize: "1.2rem", fontWeight: "bold" }}>Atenção</h5>
|
||||||
<button
|
<button
|
||||||
onClick={() => setShowModal(false)}
|
onClick={handleModalClose}
|
||||||
style={{
|
style={{
|
||||||
background: "none",
|
background: "none",
|
||||||
border: "none",
|
border: "none",
|
||||||
@ -179,9 +316,23 @@ function DoctorForm({ onSave, onCancel, formData, setFormData }) {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div style={{ padding: "25px 20px" }}>
|
<div style={{ padding: "25px 20px" }}>
|
||||||
<p style={{ color: "#111", fontSize: "1.1rem", margin: 0, fontWeight: "600" }}>
|
<p style={{ color: "#111", fontSize: "1.1rem", margin: "0 0 15px 0", fontWeight: "bold" }}>
|
||||||
{errorModalMsg}
|
{cpfError ? 'Problema com o CPF:' : 'Por favor, preencha:'}
|
||||||
</p>
|
</p>
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px', marginLeft: '10px' }}>
|
||||||
|
{cpfError ? (
|
||||||
|
<p style={{ color: "#111", fontSize: "1.1rem", margin: 0, fontWeight: "600" }}>{cpfError}</p>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{!formData.full_name && <p style={{ color: "#111", fontSize: "1.1rem", margin: 0, fontWeight: "600" }}>- Nome</p>}
|
||||||
|
{!formData.cpf && <p style={{ color: "#111", fontSize: "1.1rem", margin: 0, fontWeight: "600" }}>- CPF</p>}
|
||||||
|
{!formData.email && <p style={{ color: "#111", fontSize: "1.1rem", margin: 0, fontWeight: "600" }}>- Email</p>}
|
||||||
|
{!formData.phone_mobile && <p style={{ color: "#111", fontSize: "1.1rem", margin: 0, fontWeight: "600" }}>- Telefone</p>}
|
||||||
|
{!formData.crm_uf && <p style={{ color: "#111", fontSize: "1.1rem", margin: 0, fontWeight: "600" }}>- Estado do CRM</p>}
|
||||||
|
{!formData.crm && <p style={{ color: "#111", fontSize: "1.1rem", margin: 0, fontWeight: "600" }}>- CRM</p>}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div
|
<div
|
||||||
@ -193,91 +344,7 @@ function DoctorForm({ onSave, onCancel, formData, setFormData }) {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<button
|
<button
|
||||||
onClick={() => setShowModal(false)}
|
onClick={handleModalClose}
|
||||||
style={{
|
|
||||||
backgroundColor: "#1e3a8a",
|
|
||||||
color: "#fff",
|
|
||||||
border: "none",
|
|
||||||
padding: "8px 20px",
|
|
||||||
borderRadius: "6px",
|
|
||||||
cursor: "pointer",
|
|
||||||
fontSize: "1rem",
|
|
||||||
fontWeight: "bold",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Fechar
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{showSuccessModal && (
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
display: "flex",
|
|
||||||
justifyContent: "center",
|
|
||||||
alignItems: "center",
|
|
||||||
position: "fixed",
|
|
||||||
top: 0,
|
|
||||||
left: 0,
|
|
||||||
width: "100%",
|
|
||||||
height: "100%",
|
|
||||||
backgroundColor: "rgba(0,0,0,0.5)",
|
|
||||||
zIndex: 9999,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
backgroundColor: "#fff",
|
|
||||||
borderRadius: "10px",
|
|
||||||
width: "400px",
|
|
||||||
maxWidth: "90%",
|
|
||||||
boxShadow: "0 5px 15px rgba(0,0,0,0.3)",
|
|
||||||
overflow: "hidden",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
backgroundColor: "#1e3a8a",
|
|
||||||
padding: "15px 20px",
|
|
||||||
display: "flex",
|
|
||||||
justifyContent: "space-between",
|
|
||||||
alignItems: "center",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<h5 style={{ color: "#fff", margin: 0, fontSize: "1.2rem", fontWeight: "bold" }}>Sucesso</h5>
|
|
||||||
<button
|
|
||||||
onClick={handleCloseSuccessModal}
|
|
||||||
style={{
|
|
||||||
background: "none",
|
|
||||||
border: "none",
|
|
||||||
fontSize: "20px",
|
|
||||||
color: "#fff",
|
|
||||||
cursor: "pointer",
|
|
||||||
fontWeight: "bold",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
×
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style={{ padding: "25px 20px" }}>
|
|
||||||
<p style={{ color: "#111", fontSize: "1.1rem", margin: 0, fontWeight: "600" }}>
|
|
||||||
Médico salvo com sucesso!
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
display: "flex",
|
|
||||||
justifyContent: "flex-end",
|
|
||||||
padding: "15px 20px",
|
|
||||||
borderTop: "1px solid #ddd",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<button
|
|
||||||
onClick={handleCloseSuccessModal}
|
|
||||||
style={{
|
style={{
|
||||||
backgroundColor: "#1e3a8a",
|
backgroundColor: "#1e3a8a",
|
||||||
color: "#fff",
|
color: "#fff",
|
||||||
@ -352,7 +419,14 @@ function DoctorForm({ onSave, onCancel, formData, setFormData }) {
|
|||||||
|
|
||||||
<div className="col-md-6 mb-3">
|
<div className="col-md-6 mb-3">
|
||||||
<label style={{ fontSize: '1.1rem' }}>Nome: *</label>
|
<label style={{ fontSize: '1.1rem' }}>Nome: *</label>
|
||||||
<input type="text" className="form-control" name="full_name" value={formData.full_name || ''} onChange={handleChange} />
|
<input
|
||||||
|
ref={nomeRef}
|
||||||
|
type="text"
|
||||||
|
className="form-control"
|
||||||
|
name="full_name"
|
||||||
|
value={formData.full_name || ''}
|
||||||
|
onChange={handleChange}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="col-md-6 mb-3">
|
<div className="col-md-6 mb-3">
|
||||||
<label style={{ fontSize: '1.1rem' }}>Data de nascimento:</label>
|
<label style={{ fontSize: '1.1rem' }}>Data de nascimento:</label>
|
||||||
@ -360,12 +434,30 @@ function DoctorForm({ onSave, onCancel, formData, setFormData }) {
|
|||||||
</div>
|
</div>
|
||||||
<div className="col-md-6 mb-3">
|
<div className="col-md-6 mb-3">
|
||||||
<label style={{ fontSize: '1.1rem' }}>CPF: *</label>
|
<label style={{ fontSize: '1.1rem' }}>CPF: *</label>
|
||||||
<input type="text" className="form-control" name="cpf" value={formData.cpf || ''} onChange={handleChange} />
|
<input
|
||||||
|
ref={cpfRef}
|
||||||
|
type="text"
|
||||||
|
className={`form-control ${cpfError ? 'is-invalid' : ''}`}
|
||||||
|
name="cpf"
|
||||||
|
value={formData.cpf || ''}
|
||||||
|
onChange={handleChange}
|
||||||
|
/>
|
||||||
|
{cpfError && (
|
||||||
|
<div className="invalid-feedback" style={{ display: 'block' }}>
|
||||||
|
{cpfError}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="col-md-6 mb-3">
|
<div className="col-md-6 mb-3">
|
||||||
<label style={{ fontSize: '1.1rem' }}>Estado do CRM: *</label>
|
<label style={{ fontSize: '1.1rem' }}>Estado do CRM: *</label>
|
||||||
<select className="form-control" name="crm_uf" value={formData.crm_uf || ''} onChange={handleChange}>
|
<select
|
||||||
|
ref={crmUfRef}
|
||||||
|
className="form-control"
|
||||||
|
name="crm_uf"
|
||||||
|
value={formData.crm_uf || ''}
|
||||||
|
onChange={handleChange}
|
||||||
|
>
|
||||||
<option value="">Selecione</option>
|
<option value="">Selecione</option>
|
||||||
<option value="AP">AP</option>
|
<option value="AP">AP</option>
|
||||||
<option value="AL">AL</option>
|
<option value="AL">AL</option>
|
||||||
@ -398,7 +490,14 @@ function DoctorForm({ onSave, onCancel, formData, setFormData }) {
|
|||||||
|
|
||||||
<div className="col-md-6 mb-3">
|
<div className="col-md-6 mb-3">
|
||||||
<label style={{ fontSize: '1.1rem' }}>CRM: *</label>
|
<label style={{ fontSize: '1.1rem' }}>CRM: *</label>
|
||||||
<input type="text" className="form-control" name="crm" value={formData.crm || ''} onChange={handleChange} />
|
<input
|
||||||
|
ref={crmRef}
|
||||||
|
type="text"
|
||||||
|
className="form-control"
|
||||||
|
name="crm"
|
||||||
|
value={formData.crm || ''}
|
||||||
|
onChange={handleChange}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="col-md-6 mb-3">
|
<div className="col-md-6 mb-3">
|
||||||
@ -437,11 +536,25 @@ function DoctorForm({ onSave, onCancel, formData, setFormData }) {
|
|||||||
<div className="row mt-3">
|
<div className="row mt-3">
|
||||||
<div className="col-md-6 mb-3">
|
<div className="col-md-6 mb-3">
|
||||||
<label style={{ fontSize: '1.1rem' }}>Email: *</label>
|
<label style={{ fontSize: '1.1rem' }}>Email: *</label>
|
||||||
<input type="email" className="form-control" name="email" value={formData.email || ''} onChange={handleChange} />
|
<input
|
||||||
|
ref={emailRef}
|
||||||
|
type="email"
|
||||||
|
className="form-control"
|
||||||
|
name="email"
|
||||||
|
value={formData.email || ''}
|
||||||
|
onChange={handleChange}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="col-md-6 mb-3">
|
<div className="col-md-6 mb-3">
|
||||||
<label style={{ fontSize: '1.1rem' }}>Telefone: *</label>
|
<label style={{ fontSize: '1.1rem' }}>Telefone: *</label>
|
||||||
<input type="text" className="form-control" name="phone_mobile" value={formData.phone_mobile || ''} onChange={handleChange} />
|
<input
|
||||||
|
ref={telefoneRef}
|
||||||
|
type="text"
|
||||||
|
className="form-control"
|
||||||
|
name="phone_mobile"
|
||||||
|
value={formData.phone_mobile || ''}
|
||||||
|
onChange={handleChange}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="col-md-6 mb-3">
|
<div className="col-md-6 mb-3">
|
||||||
<label style={{ fontSize: '1.1rem' }}>Telefone 2:</label>
|
<label style={{ fontSize: '1.1rem' }}>Telefone 2:</label>
|
||||||
@ -498,11 +611,20 @@ function DoctorForm({ onSave, onCancel, formData, setFormData }) {
|
|||||||
<button
|
<button
|
||||||
className="btn btn-success me-3"
|
className="btn btn-success me-3"
|
||||||
onClick={handleSubmit}
|
onClick={handleSubmit}
|
||||||
|
disabled={isLoading}
|
||||||
style={{ fontSize: '1.2rem', padding: '0.75rem 1.5rem' }}
|
style={{ fontSize: '1.2rem', padding: '0.75rem 1.5rem' }}
|
||||||
>
|
>
|
||||||
Salvar Médico
|
{isLoading ? 'Salvando...' : 'Salvar Médico'}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
<Link to={`/${location.pathname.split("/")[1]}/medicos`}>
|
||||||
|
<button
|
||||||
|
className="btn btn-light"
|
||||||
|
style={{ fontSize: '1.2rem', padding: '0.75rem 1.5rem' }}
|
||||||
|
>
|
||||||
|
Cancelar
|
||||||
|
</button>
|
||||||
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
|
|||||||
@ -1,16 +1,12 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
import { Link,useNavigate, useLocation } from 'react-router-dom';
|
import { Link } from 'react-router-dom';
|
||||||
import { FormatTelefones, FormatPeso, FormatCPF } from '../utils/Formatar/Format';
|
import { FormatTelefones, FormatPeso, FormatCPF } from '../utils/Formatar/Format';
|
||||||
|
|
||||||
function PatientForm({ onSave, formData, setFormData }) {
|
function PatientForm({ onSave, onCancel, formData, setFormData, isLoading }) {
|
||||||
|
|
||||||
|
|
||||||
const [errorModalMsg, setErrorModalMsg] = useState("");
|
|
||||||
const [showModal, setShowModal] = useState(false);
|
|
||||||
const [pacienteExistente, setPacienteExistente] = useState(null);
|
|
||||||
const [showSuccessModal, setShowSuccessModal] = useState(false);
|
|
||||||
|
|
||||||
const [avatarUrl, setAvatarUrl] = useState(null);
|
const [avatarUrl, setAvatarUrl] = useState(null);
|
||||||
|
const [showRequiredModal, setShowRequiredModal] = useState(false);
|
||||||
|
const [emptyFields, setEmptyFields] = useState([]);
|
||||||
|
const [cpfError, setCpfError] = useState('');
|
||||||
const [collapsedSections, setCollapsedSections] = useState({
|
const [collapsedSections, setCollapsedSections] = useState({
|
||||||
dadosPessoais: true,
|
dadosPessoais: true,
|
||||||
infoMedicas: false,
|
infoMedicas: false,
|
||||||
@ -19,6 +15,41 @@ function PatientForm({ onSave, formData, setFormData }) {
|
|||||||
contato: false,
|
contato: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const nomeRef = useRef(null);
|
||||||
|
const cpfRef = useRef(null);
|
||||||
|
const emailRef = useRef(null);
|
||||||
|
const telefoneRef = useRef(null);
|
||||||
|
|
||||||
|
|
||||||
|
const validarCPF = (cpf) => {
|
||||||
|
const cpfLimpo = cpf.replace(/\D/g, '');
|
||||||
|
|
||||||
|
|
||||||
|
if (cpfLimpo.length !== 11) return false;
|
||||||
|
|
||||||
|
|
||||||
|
if (/^(\d)\1+$/.test(cpfLimpo)) return false;
|
||||||
|
|
||||||
|
|
||||||
|
let soma = 0;
|
||||||
|
for (let i = 0; i < 9; i++) {
|
||||||
|
soma += parseInt(cpfLimpo.charAt(i)) * (10 - i);
|
||||||
|
}
|
||||||
|
let resto = 11 - (soma % 11);
|
||||||
|
let digito1 = resto === 10 || resto === 11 ? 0 : resto;
|
||||||
|
|
||||||
|
|
||||||
|
soma = 0;
|
||||||
|
for (let i = 0; i < 10; i++) {
|
||||||
|
soma += parseInt(cpfLimpo.charAt(i)) * (11 - i);
|
||||||
|
}
|
||||||
|
resto = 11 - (soma % 11);
|
||||||
|
let digito2 = resto === 10 || resto === 11 ? 0 : resto;
|
||||||
|
|
||||||
|
|
||||||
|
return digito1 === parseInt(cpfLimpo.charAt(9)) && digito2 === parseInt(cpfLimpo.charAt(10));
|
||||||
|
};
|
||||||
|
|
||||||
const handleToggleCollapse = (section) => {
|
const handleToggleCollapse = (section) => {
|
||||||
setCollapsedSections(prev => ({
|
setCollapsedSections(prev => ({
|
||||||
...prev,
|
...prev,
|
||||||
@ -40,6 +71,16 @@ function PatientForm({ onSave, formData, setFormData }) {
|
|||||||
const handleChange = (e) => {
|
const handleChange = (e) => {
|
||||||
const { name, value, type, checked, files } = e.target;
|
const { name, value, type, checked, files } = e.target;
|
||||||
|
|
||||||
|
|
||||||
|
if (value && emptyFields.includes(name)) {
|
||||||
|
setEmptyFields(prev => prev.filter(field => field !== name));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if (name === 'cpf' && cpfError) {
|
||||||
|
setCpfError('');
|
||||||
|
}
|
||||||
|
|
||||||
if (type === 'file') {
|
if (type === 'file') {
|
||||||
setFormData(prev => ({ ...prev, [name]: files[0] }));
|
setFormData(prev => ({ ...prev, [name]: files[0] }));
|
||||||
|
|
||||||
@ -51,7 +92,17 @@ function PatientForm({ onSave, formData, setFormData }) {
|
|||||||
setAvatarUrl(null);
|
setAvatarUrl(null);
|
||||||
}
|
}
|
||||||
} else if (name === 'cpf') {
|
} else if (name === 'cpf') {
|
||||||
setFormData(prev => ({ ...prev, cpf: FormatCPF(value) }));
|
const cpfFormatado = FormatCPF(value);
|
||||||
|
setFormData(prev => ({ ...prev, cpf: cpfFormatado }));
|
||||||
|
|
||||||
|
const cpfLimpo = cpfFormatado.replace(/\D/g, '');
|
||||||
|
if (cpfLimpo.length === 11) {
|
||||||
|
if (!validarCPF(cpfFormatado)) {
|
||||||
|
setCpfError('CPF inválido');
|
||||||
|
} else {
|
||||||
|
setCpfError('');
|
||||||
|
}
|
||||||
|
}
|
||||||
} else if (name.includes('phone')) {
|
} else if (name.includes('phone')) {
|
||||||
setFormData(prev => ({ ...prev, [name]: FormatTelefones(value) }));
|
setFormData(prev => ({ ...prev, [name]: FormatTelefones(value) }));
|
||||||
} else if (name.includes('weight_kg') || name.includes('height_m')) {
|
} else if (name.includes('weight_kg') || name.includes('height_m')) {
|
||||||
@ -63,35 +114,114 @@ function PatientForm({ onSave, formData, setFormData }) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const scrollToEmptyField = (fieldName) => {
|
||||||
|
let fieldRef = null;
|
||||||
|
|
||||||
|
switch (fieldName) {
|
||||||
|
case 'full_name':
|
||||||
|
fieldRef = nomeRef;
|
||||||
|
|
||||||
|
setCollapsedSections(prev => ({ ...prev, dadosPessoais: true }));
|
||||||
|
break;
|
||||||
|
case 'cpf':
|
||||||
|
fieldRef = cpfRef;
|
||||||
|
setCollapsedSections(prev => ({ ...prev, dadosPessoais: true }));
|
||||||
|
break;
|
||||||
|
case 'email':
|
||||||
|
fieldRef = emailRef;
|
||||||
|
setCollapsedSections(prev => ({ ...prev, contato: true }));
|
||||||
|
break;
|
||||||
|
case 'phone_mobile':
|
||||||
|
fieldRef = telefoneRef;
|
||||||
|
setCollapsedSections(prev => ({ ...prev, contato: true }));
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
if (fieldRef.current) {
|
||||||
|
fieldRef.current.scrollIntoView({
|
||||||
|
behavior: 'smooth',
|
||||||
|
block: 'center'
|
||||||
|
});
|
||||||
|
fieldRef.current.focus();
|
||||||
|
|
||||||
|
|
||||||
|
fieldRef.current.style.border = '2px solid #dc3545';
|
||||||
|
fieldRef.current.style.boxShadow = '0 0 0 0.2rem rgba(220, 53, 69, 0.25)';
|
||||||
|
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
if (fieldRef.current) {
|
||||||
|
fieldRef.current.style.border = '';
|
||||||
|
fieldRef.current.style.boxShadow = '';
|
||||||
|
}
|
||||||
|
}, 3000);
|
||||||
|
}
|
||||||
|
}, 300);
|
||||||
|
};
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
// ALTERADO: Nome, CPF, Email e Telefone
|
|
||||||
if (!formData.full_name || !formData.cpf || !formData.email || !formData.phone_mobile) {
|
const missingFields = [];
|
||||||
setErrorModalMsg('Por favor, preencha Nome, CPF, Email e Telefone.');
|
if (!formData.full_name) missingFields.push('full_name');
|
||||||
setShowModal(true);
|
if (!formData.cpf) missingFields.push('cpf');
|
||||||
|
if (!formData.email) missingFields.push('email');
|
||||||
|
if (!formData.phone_mobile) missingFields.push('phone_mobile');
|
||||||
|
|
||||||
|
if (missingFields.length > 0) {
|
||||||
|
setEmptyFields(missingFields);
|
||||||
|
setShowRequiredModal(true);
|
||||||
|
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
if (missingFields.length > 0) {
|
||||||
|
scrollToEmptyField(missingFields[0]);
|
||||||
|
}
|
||||||
|
}, 500);
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
const cpfLimpo = formData.cpf.replace(/\D/g, '');
|
const cpfLimpo = formData.cpf.replace(/\D/g, '');
|
||||||
if (cpfLimpo.length !== 11) {
|
if (cpfLimpo.length !== 11) {
|
||||||
setErrorModalMsg('CPF inválido. Por favor, verifique o número digitado.');
|
setShowRequiredModal(true);
|
||||||
setShowModal(true);
|
setEmptyFields(['cpf']);
|
||||||
|
setCpfError('CPF deve ter 11 dígitos');
|
||||||
|
setTimeout(() => scrollToEmptyField('cpf'), 500);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
|
||||||
await onSave({ ...formData, bmi: parseFloat(formData.bmi) || 0 });
|
if (!validarCPF(formData.cpf)) {
|
||||||
setShowSuccessModal(true);
|
setShowRequiredModal(true);
|
||||||
} catch (error) {
|
setEmptyFields(['cpf']);
|
||||||
setErrorModalMsg('Erro ao salvar paciente. Tente novamente.');
|
setCpfError('CPF inválido');
|
||||||
setShowModal(true);
|
setTimeout(() => scrollToEmptyField('cpf'), 500);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||||
|
if (!emailRegex.test(formData.email)) {
|
||||||
|
throw new Error('Email inválido. Por favor, verifique o email digitado.');
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
await onSave({ ...formData, bmi: parseFloat(formData.bmi) || null });
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleModalClose = () => {
|
||||||
|
setShowRequiredModal(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="card p-3">
|
<div className="card p-3">
|
||||||
<h3 className="mb-4 text-center" style={{ fontSize: '2.5rem' }}>MediConnect</h3>
|
<h3 className="mb-4 text-center" style={{ fontSize: '2.5rem' }}>MediConnect</h3>
|
||||||
|
|
||||||
{/* DADOS PESSOAIS - MANTIDO O LAYOUT ORIGINAL */}
|
{/* DADOS PESSOAIS */}
|
||||||
<div className="mb-5 p-4 border rounded shadow-sm">
|
<div className="mb-5 p-4 border rounded shadow-sm">
|
||||||
<h4 className="mb-4 cursor-pointer d-flex justify-content-between align-items-center" onClick={() => handleToggleCollapse('dadosPessoais')} style={{ fontSize: '1.8rem' }}>
|
<h4 className="mb-4 cursor-pointer d-flex justify-content-between align-items-center" onClick={() => handleToggleCollapse('dadosPessoais')} style={{ fontSize: '1.8rem' }}>
|
||||||
Dados Pessoais
|
Dados Pessoais
|
||||||
@ -141,10 +271,20 @@ function PatientForm({ onSave, formData, setFormData }) {
|
|||||||
{formData.foto && <span className="ms-2" style={{ fontSize: '1rem' }}>{formData.foto.name}</span>}
|
{formData.foto && <span className="ms-2" style={{ fontSize: '1rem' }}>{formData.foto.name}</span>}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{/* CADASTRO - MANTIDO O LAYOUT ORIGINAL COM COLUNAS */}
|
|
||||||
|
{/* CAMPOS OBRIGATÓRIOS */}
|
||||||
<div className="col-md-6 mb-3">
|
<div className="col-md-6 mb-3">
|
||||||
<label style={{ fontSize: '1.1rem' }}>Nome: *</label>
|
<label style={{ fontSize: '1.1rem' }}>Nome: *</label>
|
||||||
<input type="text" className="form-control" name="full_name" value={formData.full_name || ''} onChange={handleChange} style={{ fontSize: '1.1rem' }} />
|
<input
|
||||||
|
ref={nomeRef}
|
||||||
|
type="text"
|
||||||
|
className="form-control"
|
||||||
|
name="full_name"
|
||||||
|
value={formData.full_name || ''}
|
||||||
|
onChange={handleChange}
|
||||||
|
style={{ fontSize: '1.1rem' }}
|
||||||
|
required
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="col-md-6 mb-3">
|
<div className="col-md-6 mb-3">
|
||||||
<label style={{ fontSize: '1.1rem' }}>Nome social:</label>
|
<label style={{ fontSize: '1.1rem' }}>Nome social:</label>
|
||||||
@ -152,11 +292,25 @@ function PatientForm({ onSave, formData, setFormData }) {
|
|||||||
</div>
|
</div>
|
||||||
<div className="col-md-6 mb-3">
|
<div className="col-md-6 mb-3">
|
||||||
<label style={{ fontSize: '1.1rem' }}>Data de nascimento:</label>
|
<label style={{ fontSize: '1.1rem' }}>Data de nascimento:</label>
|
||||||
<input type="date" className="form-control" name="birth_date" value={formData.birth_date || ''} onChange={handleChange} style={{ fontSize: '1.1rem' }} />
|
<input
|
||||||
|
type="date"
|
||||||
|
className="form-control"
|
||||||
|
name="birth_date"
|
||||||
|
value={formData.birth_date || ''}
|
||||||
|
onChange={handleChange}
|
||||||
|
style={{ fontSize: '1.1rem' }}
|
||||||
|
min="1900-01-01" max="2025-09-24"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="col-md-6 mb-3">
|
<div className="col-md-6 mb-3">
|
||||||
<label style={{ fontSize: '1.1rem' }}>Gênero:</label>
|
<label style={{ fontSize: '1.1rem' }}>Gênero:</label>
|
||||||
<select className="form-control" name="sex" value={formData.sex || ''} onChange={handleChange} style={{ fontSize: '1.1rem' }}>
|
<select
|
||||||
|
className="form-control"
|
||||||
|
name="sex"
|
||||||
|
value={formData.sex || ''}
|
||||||
|
onChange={handleChange}
|
||||||
|
style={{ fontSize: '1.1rem' }}
|
||||||
|
>
|
||||||
<option value="">Selecione</option>
|
<option value="">Selecione</option>
|
||||||
<option value="Masculino">Masculino</option>
|
<option value="Masculino">Masculino</option>
|
||||||
<option value="Feminino">Feminino</option>
|
<option value="Feminino">Feminino</option>
|
||||||
@ -165,7 +319,21 @@ function PatientForm({ onSave, formData, setFormData }) {
|
|||||||
</div>
|
</div>
|
||||||
<div className="col-md-6 mb-3">
|
<div className="col-md-6 mb-3">
|
||||||
<label style={{ fontSize: '1.1rem' }}>CPF: *</label>
|
<label style={{ fontSize: '1.1rem' }}>CPF: *</label>
|
||||||
<input type="text" className="form-control" name="cpf" value={formData.cpf || ''} onChange={handleChange} style={{ fontSize: '1.1rem' }} />
|
<input
|
||||||
|
ref={cpfRef}
|
||||||
|
type="text"
|
||||||
|
className={`form-control ${cpfError ? 'is-invalid' : ''}`}
|
||||||
|
name="cpf"
|
||||||
|
value={formData.cpf || ''}
|
||||||
|
onChange={handleChange}
|
||||||
|
style={{ fontSize: '1.1rem' }}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
{cpfError && (
|
||||||
|
<div className="invalid-feedback" style={{ display: 'block' }}>
|
||||||
|
{cpfError}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="col-md-6 mb-3">
|
<div className="col-md-6 mb-3">
|
||||||
<label style={{ fontSize: '1.1rem' }}>RG:</label>
|
<label style={{ fontSize: '1.1rem' }}>RG:</label>
|
||||||
@ -254,7 +422,7 @@ function PatientForm({ onSave, formData, setFormData }) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* CAMPOS MOVIDOS */}
|
{/* CAMPOS ADICIONAIS */}
|
||||||
<div className="col-md-12 mb-3 mt-3">
|
<div className="col-md-12 mb-3 mt-3">
|
||||||
<label style={{ fontSize: '1.1rem' }}>Observações:</label>
|
<label style={{ fontSize: '1.1rem' }}>Observações:</label>
|
||||||
<textarea className="form-control" name="notes" value={formData.notes || ''} onChange={handleChange} style={{ fontSize: '1.1rem' }} placeholder='alergias, doenças crônicas, informações sobre porteses ou marca-passo, etc'></textarea>
|
<textarea className="form-control" name="notes" value={formData.notes || ''} onChange={handleChange} style={{ fontSize: '1.1rem' }} placeholder='alergias, doenças crônicas, informações sobre porteses ou marca-passo, etc'></textarea>
|
||||||
@ -272,7 +440,7 @@ function PatientForm({ onSave, formData, setFormData }) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* INFORMAÇÕES MÉDICAS - MANTIDO O LAYOUT ORIGINAL */}
|
{/* INFORMAÇÕES MÉDICAS */}
|
||||||
<div className="mb-5 p-4 border rounded shadow-sm">
|
<div className="mb-5 p-4 border rounded shadow-sm">
|
||||||
<h4 className="mb-4 cursor-pointer d-flex justify-content-between align-items-center" onClick={() => handleToggleCollapse('infoMedicas')} style={{ fontSize: '1.8rem' }}>
|
<h4 className="mb-4 cursor-pointer d-flex justify-content-between align-items-center" onClick={() => handleToggleCollapse('infoMedicas')} style={{ fontSize: '1.8rem' }}>
|
||||||
Informações Médicas
|
Informações Médicas
|
||||||
@ -313,7 +481,7 @@ function PatientForm({ onSave, formData, setFormData }) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* INFORMAÇÕES DE CONVÊNIO - MANTIDO O LAYOUT ORIGINAL */}
|
{/* INFORMAÇÕES DE CONVÊNIO */}
|
||||||
<div className="mb-5 p-4 border rounded shadow-sm">
|
<div className="mb-5 p-4 border rounded shadow-sm">
|
||||||
<h4 className="mb-4 cursor-pointer d-flex justify-content-between align-items-center" onClick={() => handleToggleCollapse('infoConvenio')} style={{ fontSize: '1.8rem' }}>
|
<h4 className="mb-4 cursor-pointer d-flex justify-content-between align-items-center" onClick={() => handleToggleCollapse('infoConvenio')} style={{ fontSize: '1.8rem' }}>
|
||||||
Informações de convênio
|
Informações de convênio
|
||||||
@ -366,7 +534,7 @@ function PatientForm({ onSave, formData, setFormData }) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* ENDEREÇO - MANTIDO O LAYOUT ORIGINAL */}
|
{/* ENDEREÇO */}
|
||||||
<div className="mb-5 p-4 border rounded shadow-sm">
|
<div className="mb-5 p-4 border rounded shadow-sm">
|
||||||
<h4 className="mb-4 cursor-pointer d-flex justify-content-between align-items-center" onClick={() => handleToggleCollapse('endereco')} style={{ fontSize: '1.8rem' }}>
|
<h4 className="mb-4 cursor-pointer d-flex justify-content-between align-items-center" onClick={() => handleToggleCollapse('endereco')} style={{ fontSize: '1.8rem' }}>
|
||||||
Endereço
|
Endereço
|
||||||
@ -408,7 +576,6 @@ function PatientForm({ onSave, formData, setFormData }) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* CONTATO - MANTIDO O LAYOUT ORIGINAL */}
|
|
||||||
<div className="mb-5 p-4 border rounded shadow-sm">
|
<div className="mb-5 p-4 border rounded shadow-sm">
|
||||||
<h4 className="mb-4 cursor-pointer d-flex justify-content-between align-items-center" onClick={() => handleToggleCollapse('contato')} style={{ fontSize: '1.8rem' }}>
|
<h4 className="mb-4 cursor-pointer d-flex justify-content-between align-items-center" onClick={() => handleToggleCollapse('contato')} style={{ fontSize: '1.8rem' }}>
|
||||||
Contato
|
Contato
|
||||||
@ -420,11 +587,29 @@ function PatientForm({ onSave, formData, setFormData }) {
|
|||||||
<div className="row mt-3">
|
<div className="row mt-3">
|
||||||
<div className="col-md-6 mb-3">
|
<div className="col-md-6 mb-3">
|
||||||
<label style={{ fontSize: '1.1rem' }}>Email: *</label>
|
<label style={{ fontSize: '1.1rem' }}>Email: *</label>
|
||||||
<input type="email" className="form-control" name="email" value={formData.email || ''} onChange={handleChange} style={{ fontSize: '1.1rem' }} />
|
<input
|
||||||
|
ref={emailRef}
|
||||||
|
type="email"
|
||||||
|
className="form-control"
|
||||||
|
name="email"
|
||||||
|
value={formData.email || ''}
|
||||||
|
onChange={handleChange}
|
||||||
|
style={{ fontSize: '1.1rem' }}
|
||||||
|
required
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="col-md-6 mb-3">
|
<div className="col-md-6 mb-3">
|
||||||
<label style={{ fontSize: '1.1rem' }}>Telefone: *</label>
|
<label style={{ fontSize: '1.1rem' }}>Telefone: *</label>
|
||||||
<input type="text" className="form-control" name="phone_mobile" value={formData.phone_mobile || ''} onChange={handleChange} style={{ fontSize: '1.1rem' }} />
|
<input
|
||||||
|
ref={telefoneRef}
|
||||||
|
type="text"
|
||||||
|
className="form-control"
|
||||||
|
name="phone_mobile"
|
||||||
|
value={formData.phone_mobile || ''}
|
||||||
|
onChange={handleChange}
|
||||||
|
style={{ fontSize: '1.1rem' }}
|
||||||
|
required
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="col-md-6 mb-3">
|
<div className="col-md-6 mb-3">
|
||||||
<label style={{ fontSize: '1.1rem' }}>Telefone 2:</label>
|
<label style={{ fontSize: '1.1rem' }}>Telefone 2:</label>
|
||||||
@ -438,16 +623,8 @@ function PatientForm({ onSave, formData, setFormData }) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Botões */}
|
|
||||||
<div className="mt-3 text-center">
|
|
||||||
<button className="btn btn-success me-3" onClick={handleSubmit} style={{ fontSize: '1.2rem', padding: '0.75rem 1.5rem' }}>
|
|
||||||
Salvar Paciente
|
|
||||||
</button>
|
|
||||||
|
|
||||||
</div>
|
{showRequiredModal && (
|
||||||
|
|
||||||
{/* Modal de erro - EXATAMENTE COMO NA IMAGEM */}
|
|
||||||
{showModal && (
|
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
display: "flex",
|
display: "flex",
|
||||||
@ -472,7 +649,7 @@ function PatientForm({ onSave, formData, setFormData }) {
|
|||||||
overflow: "hidden",
|
overflow: "hidden",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{/* Header */}
|
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
backgroundColor: "#1e3a8a",
|
backgroundColor: "#1e3a8a",
|
||||||
@ -484,7 +661,7 @@ function PatientForm({ onSave, formData, setFormData }) {
|
|||||||
>
|
>
|
||||||
<h5 style={{ color: "#fff", margin: 0, fontSize: "1.2rem", fontWeight: "bold" }}>Atenção</h5>
|
<h5 style={{ color: "#fff", margin: 0, fontSize: "1.2rem", fontWeight: "bold" }}>Atenção</h5>
|
||||||
<button
|
<button
|
||||||
onClick={() => setShowModal(false)}
|
onClick={handleModalClose}
|
||||||
style={{
|
style={{
|
||||||
background: "none",
|
background: "none",
|
||||||
border: "none",
|
border: "none",
|
||||||
@ -497,20 +674,26 @@ function PatientForm({ onSave, formData, setFormData }) {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Body */}
|
|
||||||
<div style={{ padding: "25px 20px" }}>
|
<div style={{ padding: "25px 20px" }}>
|
||||||
<p style={{ color: "#111", fontSize: "1.1rem", margin: "0 0 15px 0", fontWeight: "bold" }}>
|
<p style={{ color: "#111", fontSize: "1.1rem", margin: "0 0 15px 0", fontWeight: "bold" }}>
|
||||||
Por favor, preencha:
|
{cpfError ? 'Problema com o CPF:' : 'Por favor, preencha:'}
|
||||||
</p>
|
</p>
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px', marginLeft: '10px' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px', marginLeft: '10px' }}>
|
||||||
{!formData.full_name && <p style={{ color: "#111", fontSize: "1.1rem", margin: 0, fontWeight: "600" }}>- Nome</p>}
|
{cpfError ? (
|
||||||
{!formData.cpf && <p style={{ color: "#111", fontSize: "1.1rem", margin: 0, fontWeight: "600" }}>- CPF</p>}
|
<p style={{ color: "#111", fontSize: "1.1rem", margin: 0, fontWeight: "600" }}>{cpfError}</p>
|
||||||
{!formData.email && <p style={{ color: "#111", fontSize: "1.1rem", margin: 0, fontWeight: "600" }}>- Email</p>}
|
) : (
|
||||||
{!formData.phone_mobile && <p style={{ color: "#111", fontSize: "1.1rem", margin: 0, fontWeight: "600" }}>- Telefone</p>}
|
<>
|
||||||
|
{!formData.full_name && <p style={{ color: "#111", fontSize: "1.1rem", margin: 0, fontWeight: "600" }}>- Nome</p>}
|
||||||
|
{!formData.cpf && <p style={{ color: "#111", fontSize: "1.1rem", margin: 0, fontWeight: "600" }}>- CPF</p>}
|
||||||
|
{!formData.email && <p style={{ color: "#111", fontSize: "1.1rem", margin: 0, fontWeight: "600" }}>- Email</p>}
|
||||||
|
{!formData.phone_mobile && <p style={{ color: "#111", fontSize: "1.1rem", margin: 0, fontWeight: "600" }}>- Telefone</p>}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Footer */}
|
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
display: "flex",
|
display: "flex",
|
||||||
@ -520,7 +703,7 @@ function PatientForm({ onSave, formData, setFormData }) {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<button
|
<button
|
||||||
onClick={() => setShowModal(false)}
|
onClick={handleModalClose}
|
||||||
style={{
|
style={{
|
||||||
backgroundColor: "#1e3a8a",
|
backgroundColor: "#1e3a8a",
|
||||||
color: "#fff",
|
color: "#fff",
|
||||||
@ -539,94 +722,18 @@ function PatientForm({ onSave, formData, setFormData }) {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Modal de sucesso */}
|
|
||||||
{showSuccessModal && (
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
display: "flex",
|
|
||||||
justifyContent: "center",
|
|
||||||
alignItems: "center",
|
|
||||||
position: "fixed",
|
|
||||||
top: 0,
|
|
||||||
left: 0,
|
|
||||||
width: "100%",
|
|
||||||
height: "100%",
|
|
||||||
backgroundColor: "rgba(0,0,0,0.5)",
|
|
||||||
zIndex: 9999,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
backgroundColor: "#fff",
|
|
||||||
borderRadius: "10px",
|
|
||||||
width: "400px",
|
|
||||||
maxWidth: "90%",
|
|
||||||
boxShadow: "0 5px 15px rgba(0,0,0,0.3)",
|
|
||||||
overflow: "hidden",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{/* Header */}
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
backgroundColor: "#1e3a8a",
|
|
||||||
padding: "15px 20px",
|
|
||||||
display: "flex",
|
|
||||||
justifyContent: "space-between",
|
|
||||||
alignItems: "center",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<h5 style={{ color: "#fff", margin: 0, fontSize: "1.2rem", fontWeight: "bold" }}>Sucesso</h5>
|
|
||||||
<button
|
|
||||||
onClick={() => setShowSuccessModal(false)}
|
|
||||||
style={{
|
|
||||||
background: "none",
|
|
||||||
border: "none",
|
|
||||||
fontSize: "20px",
|
|
||||||
color: "#fff",
|
|
||||||
cursor: "pointer",
|
|
||||||
fontWeight: "bold",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
×
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Body */}
|
<div className="mt-3 text-center">
|
||||||
<div style={{ padding: "25px 20px" }}>
|
<button className="btn btn-success me-3" onClick={handleSubmit} disabled={isLoading} style={{ fontSize: '1.2rem', padding: '0.75rem 1.5rem' }}>
|
||||||
<p style={{ color: "#111", fontSize: "1.1rem", margin: 0, fontWeight: "600" }}>
|
{isLoading ? 'Salvando...' : 'Salvar Paciente'}
|
||||||
O cadastro do paciente foi realizado com sucesso.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Footer */}
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
display: "flex",
|
|
||||||
justifyContent: "flex-end",
|
|
||||||
padding: "15px 20px",
|
|
||||||
borderTop: "1px solid #ddd",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<button
|
|
||||||
onClick={() => setShowSuccessModal(false)}
|
|
||||||
style={{
|
|
||||||
backgroundColor: "#1e3a8a",
|
|
||||||
color: "#fff",
|
|
||||||
border: "none",
|
|
||||||
padding: "8px 20px",
|
|
||||||
borderRadius: "6px",
|
|
||||||
cursor: "pointer",
|
|
||||||
fontSize: "1rem",
|
|
||||||
fontWeight: "bold",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Fechar
|
|
||||||
</button>
|
</button>
|
||||||
|
<Link to='/secretaria/pacientes'>
|
||||||
|
<button className="btn btn-light" style={{ fontSize: '1.2rem', padding: '0.75rem 1.5rem' }}>
|
||||||
|
Cancelar
|
||||||
|
</button>
|
||||||
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -5,88 +5,305 @@ import API_KEY from '../components/utils/apiKeys';
|
|||||||
import { useNavigate, useLocation } from 'react-router-dom';
|
import { useNavigate, useLocation } from 'react-router-dom';
|
||||||
|
|
||||||
function DoctorCadastroManager() {
|
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 navigate = useNavigate();
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const { getAuthorizationHeader, isAuthenticated } = useAuth();
|
const { getAuthorizationHeader, isAuthenticated } = useAuth();
|
||||||
|
|
||||||
const handleSaveDoctor = async (doctorData) => {
|
const handleSaveDoctor = async (doctorData) => {
|
||||||
|
setIsLoading(true);
|
||||||
const authHeader = getAuthorizationHeader();
|
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 {
|
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);
|
const response = await fetch("https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/doctors", requestOptions);
|
||||||
|
|
||||||
console.log(" Status da resposta:", response.status);
|
console.log("Status da resposta:", response.status);
|
||||||
console.log(" Response ok:", response.ok);
|
console.log("Response ok:", response.ok);
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
let errorMessage = `Erro HTTP: ${response.status}`;
|
let errorMessage = `Erro ao salvar médico (${response.status})`;
|
||||||
try {
|
|
||||||
const errorData = await response.json();
|
|
||||||
console.error(" Erro detalhado:", errorData);
|
const responseText = await response.text();
|
||||||
errorMessage = errorData.message || errorData.details || errorMessage;
|
console.log("Conteúdo da resposta:", responseText);
|
||||||
} catch (e) {
|
|
||||||
const errorText = await response.text();
|
if (responseText) {
|
||||||
console.error(" Erro texto:", errorText);
|
try {
|
||||||
errorMessage = errorText || errorMessage;
|
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);
|
throw new Error(errorMessage);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await response.json();
|
const responseText = await response.text();
|
||||||
console.log("Médico salvo no backend:", result);
|
let result = null;
|
||||||
|
|
||||||
// Redireciona para a lista de médicos do perfil atual
|
if (responseText) {
|
||||||
const prefixo = location.pathname.split("/")[1];
|
try {
|
||||||
navigate(`/${prefixo}/medicos`);
|
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 };
|
||||||
|
}
|
||||||
|
|
||||||
return result;
|
|
||||||
|
setShowSuccessModal(true);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(" Erro ao salvar Médico:", error);
|
console.error("Erro ao salvar Médico:", error);
|
||||||
throw 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 (
|
return (
|
||||||
<>
|
<>
|
||||||
|
|
||||||
|
{showSuccessModal && (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "center",
|
||||||
|
alignItems: "center",
|
||||||
|
position: "fixed",
|
||||||
|
top: 0,
|
||||||
|
left: 0,
|
||||||
|
width: "100%",
|
||||||
|
height: "100%",
|
||||||
|
backgroundColor: "rgba(0,0,0,0.5)",
|
||||||
|
zIndex: 9999,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
backgroundColor: "#fff",
|
||||||
|
borderRadius: "10px",
|
||||||
|
width: "400px",
|
||||||
|
maxWidth: "90%",
|
||||||
|
boxShadow: "0 5px 15px rgba(0,0,0,0.3)",
|
||||||
|
overflow: "hidden",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
backgroundColor: "#28a745",
|
||||||
|
padding: "15px 20px",
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "space-between",
|
||||||
|
alignItems: "center",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<h5 style={{ color: "#fff", margin: 0, fontSize: "1.2rem", fontWeight: "bold" }}>Sucesso</h5>
|
||||||
|
<button
|
||||||
|
onClick={handleCloseSuccessModal}
|
||||||
|
style={{
|
||||||
|
background: "none",
|
||||||
|
border: "none",
|
||||||
|
fontSize: "20px",
|
||||||
|
color: "#fff",
|
||||||
|
cursor: "pointer",
|
||||||
|
fontWeight: "bold",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style={{ padding: "25px 20px" }}>
|
||||||
|
<p style={{ color: "#111", fontSize: "1.1rem", margin: 0, fontWeight: "600" }}>
|
||||||
|
Médico cadastrado com sucesso!
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "flex-end",
|
||||||
|
padding: "15px 20px",
|
||||||
|
borderTop: "1px solid #ddd",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
onClick={handleCloseSuccessModal}
|
||||||
|
style={{
|
||||||
|
backgroundColor: "#28a745",
|
||||||
|
color: "#fff",
|
||||||
|
border: "none",
|
||||||
|
padding: "8px 20px",
|
||||||
|
borderRadius: "6px",
|
||||||
|
cursor: "pointer",
|
||||||
|
fontSize: "1rem",
|
||||||
|
fontWeight: "bold",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Fechar
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
|
||||||
|
{showErrorModal && (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "center",
|
||||||
|
alignItems: "center",
|
||||||
|
position: "fixed",
|
||||||
|
top: 0,
|
||||||
|
left: 0,
|
||||||
|
width: "100%",
|
||||||
|
height: "100%",
|
||||||
|
backgroundColor: "rgba(0,0,0,0.5)",
|
||||||
|
zIndex: 9999,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
backgroundColor: "#fff",
|
||||||
|
borderRadius: "10px",
|
||||||
|
width: "400px",
|
||||||
|
maxWidth: "90%",
|
||||||
|
boxShadow: "0 5px 15px rgba(0,0,0,0.3)",
|
||||||
|
overflow: "hidden",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
backgroundColor: "#dc3545",
|
||||||
|
padding: "15px 20px",
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "space-between",
|
||||||
|
alignItems: "center",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<h5 style={{ color: "#fff", margin: 0, fontSize: "1.2rem", fontWeight: "bold" }}>Erro</h5>
|
||||||
|
<button
|
||||||
|
onClick={handleCloseErrorModal}
|
||||||
|
style={{
|
||||||
|
background: "none",
|
||||||
|
border: "none",
|
||||||
|
fontSize: "20px",
|
||||||
|
color: "#fff",
|
||||||
|
cursor: "pointer",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style={{ padding: "25px 20px" }}>
|
||||||
|
<p style={{ color: "#111", fontSize: "1.1rem", margin: 0, fontWeight: "600" }}>
|
||||||
|
{errorMessage}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "flex-end",
|
||||||
|
padding: "15px 20px",
|
||||||
|
borderTop: "1px solid #ddd",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
onClick={handleCloseErrorModal}
|
||||||
|
style={{
|
||||||
|
backgroundColor: "#dc3545",
|
||||||
|
color: "#fff",
|
||||||
|
border: "none",
|
||||||
|
padding: "8px 20px",
|
||||||
|
borderRadius: "6px",
|
||||||
|
cursor: "pointer",
|
||||||
|
fontSize: "1rem",
|
||||||
|
fontWeight: "bold",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Fechar
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="page-heading">
|
<div className="page-heading">
|
||||||
<h3>Cadastro de Médicos</h3>
|
<h3>Cadastro de Médicos</h3>
|
||||||
</div>
|
</div>
|
||||||
@ -95,9 +312,9 @@ function DoctorCadastroManager() {
|
|||||||
<div className="col-12">
|
<div className="col-12">
|
||||||
<DoctorForm
|
<DoctorForm
|
||||||
onSave={handleSaveDoctor}
|
onSave={handleSaveDoctor}
|
||||||
|
formData={doctorData}
|
||||||
formData={DoctorDict}
|
setFormData={setDoctorData}
|
||||||
setFormData={setDoctorDict}
|
isLoading={isLoading}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@ -1,37 +1,98 @@
|
|||||||
import {useState} from 'react';
|
import {useState} from 'react';
|
||||||
import React 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 PatientForm from '../components/patients/PatientForm';
|
||||||
import API_KEY from '../components/utils/apiKeys';
|
import API_KEY from '../components/utils/apiKeys';
|
||||||
import { useAuth } from '../components/utils/AuthProvider';
|
import { useAuth } from '../components/utils/AuthProvider';
|
||||||
|
|
||||||
function PatientCadastroManager( {setCurrentPage} ) {
|
function PatientCadastroManager( {setCurrentPage} ) {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate()
|
||||||
const location = useLocation();
|
|
||||||
const [showModal, setShowModal] = useState(false);
|
const [showModal, setShowModal] = useState(false);
|
||||||
const [infosModal, setInfosModal] = useState({title:'', message:''});
|
const [infosModal, setInfosModal] = useState({title:'', message:''});
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
|
||||||
const { getAuthorizationHeader, isAuthenticated } = useAuth();
|
const { getAuthorizationHeader, isAuthenticated } = useAuth();
|
||||||
const [formData, setFormData] = useState({})
|
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) => {
|
const handleSavePatient = async (patientData) => {
|
||||||
console.log('🔄 Iniciando salvamento do paciente:', patientData);
|
console.log(' Iniciando salvamento do paciente:', patientData);
|
||||||
|
setIsLoading(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
||||||
|
console.log(' Verificando autenticação...');
|
||||||
|
if (!isAuthenticated) {
|
||||||
|
throw new Error('Usuário não autenticado');
|
||||||
|
}
|
||||||
|
|
||||||
const authHeader = getAuthorizationHeader();
|
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();
|
var myHeaders = new Headers();
|
||||||
myHeaders.append("Content-Type", "application/json");
|
myHeaders.append("Content-Type", "application/json");
|
||||||
myHeaders.append("apikey", API_KEY);
|
myHeaders.append("apikey", API_KEY);
|
||||||
myHeaders.append("Authorization", authHeader);
|
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 = {
|
const cleanedData = {
|
||||||
full_name: patientData.full_name,
|
full_name: patientData.full_name,
|
||||||
cpf: patientData.cpf.replace(/\D/g, ''),
|
cpf: cpfLimpo,
|
||||||
birth_date: patientData.birth_date,
|
|
||||||
sex: patientData.sex,
|
|
||||||
email: patientData.email,
|
email: patientData.email,
|
||||||
phone_mobile: patientData.phone_mobile,
|
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,
|
social_name: patientData.social_name || null,
|
||||||
rg: patientData.rg || null,
|
rg: patientData.rg || null,
|
||||||
blood_type: patientData.blood_type || null,
|
blood_type: patientData.blood_type || null,
|
||||||
@ -41,9 +102,14 @@ function PatientCadastroManager( {setCurrentPage} ) {
|
|||||||
notes: patientData.notes || null,
|
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);
|
var raw = JSON.stringify(cleanedData);
|
||||||
|
console.log(' Payload JSON:', raw);
|
||||||
|
|
||||||
var requestOptions = {
|
var requestOptions = {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@ -52,39 +118,74 @@ function PatientCadastroManager( {setCurrentPage} ) {
|
|||||||
redirect: 'follow'
|
redirect: 'follow'
|
||||||
};
|
};
|
||||||
|
|
||||||
|
console.log(' Fazendo requisição para API...');
|
||||||
const response = await fetch("https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/patients", requestOptions);
|
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);
|
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) {
|
if (!response.ok) {
|
||||||
let errorMessage = `Erro HTTP: ${response.status}`;
|
console.error(' Erro da API - Detalhes:', {
|
||||||
try {
|
status: response.status,
|
||||||
const errorData = await response.json();
|
statusText: response.statusText,
|
||||||
errorMessage = errorData.message || errorData.details || errorMessage;
|
data: responseData
|
||||||
} catch (e) {
|
});
|
||||||
const errorText = await response.text();
|
|
||||||
errorMessage = errorText || errorMessage;
|
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);
|
throw new Error(errorMessage);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await response.json();
|
console.log(' Paciente salvo com sucesso:', responseData);
|
||||||
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);
|
|
||||||
setInfosModal({
|
setInfosModal({
|
||||||
title: 'Erro de conexão',
|
title: 'Sucesso',
|
||||||
message: 'Não foi possível conectar ao servidor. Verifique sua internet e tente novamente.'
|
message: 'O cadastro do paciente foi realizado com sucesso.'
|
||||||
});
|
});
|
||||||
setShowModal(true);
|
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} ) {
|
|||||||
<>
|
<>
|
||||||
<div className="page-heading">
|
<div className="page-heading">
|
||||||
{showModal &&(
|
{showModal &&(
|
||||||
<div className="modal" style={{ display: 'block', backgroundColor: 'rgba(0,0,0,0.5)' }}>
|
<div
|
||||||
<div className="modal-dialog">
|
style={{
|
||||||
<div className="modal-content">
|
display: "flex",
|
||||||
<div className="modal-header bg-danger text-white">
|
justifyContent: "center",
|
||||||
<h5 className="modal-title">{infosModal.title}</h5>
|
alignItems: "center",
|
||||||
<button
|
position: "fixed",
|
||||||
type="button"
|
top: 0,
|
||||||
className="btn-close"
|
left: 0,
|
||||||
onClick={() => setShowModal(false)}
|
width: "100%",
|
||||||
></button>
|
height: "100%",
|
||||||
</div>
|
backgroundColor: "rgba(0,0,0,0.5)",
|
||||||
<div className="modal-body">
|
zIndex: 9999,
|
||||||
<p>{infosModal.message}</p>
|
}}
|
||||||
</div>
|
>
|
||||||
<div className="modal-footer">
|
<div
|
||||||
<button
|
style={{
|
||||||
type="button"
|
backgroundColor: "#fff",
|
||||||
className="btn btn-primary"
|
borderRadius: "10px",
|
||||||
onClick={() => setShowModal(false)}
|
width: "400px",
|
||||||
>
|
maxWidth: "90%",
|
||||||
Fechar
|
boxShadow: "0 5px 15px rgba(0,0,0,0.3)",
|
||||||
</button>
|
overflow: "hidden",
|
||||||
</div>
|
}}
|
||||||
|
>
|
||||||
|
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
backgroundColor: infosModal.title === 'Sucesso' ? "#28a745" : "#dc3545",
|
||||||
|
padding: "15px 20px",
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "space-between",
|
||||||
|
alignItems: "center",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<h5 style={{ color: "#fff", margin: 0, fontSize: "1.2rem", fontWeight: "bold" }}>{infosModal.title}</h5>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowModal(false)}
|
||||||
|
style={{
|
||||||
|
background: "none",
|
||||||
|
border: "none",
|
||||||
|
fontSize: "20px",
|
||||||
|
color: "#fff",
|
||||||
|
cursor: "pointer",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
<div style={{ padding: "25px 20px" }}>
|
||||||
|
<p style={{ color: "#111", fontSize: "1.1rem", margin: 0, fontWeight: "600" }}>
|
||||||
|
{infosModal.message}
|
||||||
|
</p>
|
||||||
|
{infosModal.title === 'Erro' && (
|
||||||
|
<p style={{ color: "#666", fontSize: "0.9rem", margin: "10px 0 0 0" }}>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "flex-end",
|
||||||
|
padding: "15px 20px",
|
||||||
|
borderTop: "1px solid #ddd",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
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
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<h3>Cadastro de Pacientes</h3>
|
<h3>Cadastro de Pacientes</h3>
|
||||||
|
{isLoading && (
|
||||||
|
<div className="alert alert-info">
|
||||||
|
<div className="spinner-border spinner-border-sm me-2" role="status"></div>
|
||||||
|
Salvando paciente...
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="page-content">
|
<div className="page-content">
|
||||||
<section className="row">
|
<section className="row">
|
||||||
<div className="col-12">
|
<div className="col-12">
|
||||||
<PatientForm
|
<PatientForm
|
||||||
onSave={handleSavePatient}
|
onSave={handleSavePatient}
|
||||||
|
onCancel={() => navigate('/secretaria/pacientes')}
|
||||||
formData={formData}
|
formData={formData}
|
||||||
setFormData={setFormData}
|
setFormData={setFormData}
|
||||||
|
isLoading={isLoading}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user