Mudanças pos feedback de davi

This commit is contained in:
Caio Miguel Lima Nunes 2025-09-04 17:32:19 -03:00
parent 5534568e20
commit 9c0911396e
11 changed files with 751 additions and 177 deletions

View File

@ -11,17 +11,19 @@ import Table from "./pages/Table"; // <-- ADIÇÃO AQUI
import DataTable from "./pages/DataTable";
import Files from "./pages/files";
import EmailApp from "./pages/EmailApp";
import ChatApp from "./pages/ChatApp";
//import ChatApp from "./pages/ChatApp";
import GalleryApp from "./pages/GalleryApp";
import FormLayout from './pages/FormLayout';
import EditPage from './pages/EditPage';
import PatientList from './components/patients/PatientList';
import PatientForm from "./components/patients/PatientForm";
import Details from './pages/Details';
//import DoctorEditPage from './components/doctors/DoctorEditPage';
import DoctorTable from './pages/DoctorTable';
import DoctorFormLayout from './pages/DoctorFormLayout';
function App() {
const [isSidebarActive, setIsSidebarActive] = useState(true);
const [currentPage, setCurrentPage] = useState('dashboard');
const [currentPage, setCurrentPage] = useState('table ');
const [patientID, setPatientID] = useState(0)
@ -36,9 +38,15 @@ const renderPageContent = () => {
if (currentPage === 'form-layout') {
return <FormLayout/>;
}
else if(currentPage === 'doctor-form-layout'){
return <DoctorFormLayout/>
}
else if (currentPage === 'table') {
return <Table setCurrentPage={setCurrentPage} setPatientID={setPatientID}/>;
}
else if(currentPage === 'doctor-table'){
return <DoctorTable setCurrentPage={setCurrentPage} setPatientID={setPatientID}/>
}
else if (currentPage === 'data-table') {
return <DataTable />;
}
@ -48,16 +56,18 @@ const renderPageContent = () => {
else if (currentPage === 'email-app') {
return <EmailApp />;
}
else if (currentPage === 'chat-app') {
return <ChatApp />;
}
//else if (currentPage === 'chat-app') {
// return <ChatApp />;
//}
else if (currentPage === 'gallery-app') {
return <GalleryApp />;
}
else if(currentPage === 'edit-page-paciente'){
return <EditPage id={patientID} />
}
// else if(currentPage === 'doctor-form-layout'){
// return <DoctorEditPage id={patientID} />
//}
else if(currentPage === 'details-page-paciente'){
return <Details/>
}

View File

@ -56,11 +56,7 @@ function Sidebar(props) {
props.setCurrentPage('dashboard');
}}
>
<img
src="/assets/images/logo/logo.png.png"
alt="Logo"
style={{ width: '120px', height: '40px' }}
/>
<hi>MediConnect</hi>
</a>
</div>
<div className="toggler">

View File

@ -0,0 +1,310 @@
import React, { useState } from 'react';
import InputMask from "react-input-mask";
function DoctorForm({ onSave, onCancel, PatientDict }) {
const FormatTelefones = (valor) => {
const digits = String(valor).replace(/\D/g, '').slice(0, 11);
return digits
.replace(/(\d)/, '($1') // 123 -> 123.
.replace(/(\d{2})(\d)/, '$1) $2' )
.replace(/(\d)(\d{4})/, '$1 $2')
.replace(/(\d{4})(\d{4})/, '$1-$2')
}
const FormatCPF = (valor) => {
const digits = String(valor).replace(/\D/g, '').slice(0, 11);
return digits
.replace(/(\d{3})(\d)/, '$1.$2') // 123 -> 123.
.replace(/(\d{3})(\d)/, '$1.$2') // 123.456 -> 123.456.
.replace(/(\d{3})(\d{1,2})$/, '$1-$2'); // 123.456.789 -> 123.456.789-01
}
const [formData, setFormData] = useState({
nome: PatientDict.nome,
nomeSocial: PatientDict.nome_social,
dataNascimento: PatientDict.data_nascimento,
genero: PatientDict.sexo,
//documento: '',
//numeroDocumento: '',
cpf: PatientDict.cpf,
profissao: PatientDict.profissao ,
//nomeConjuge: '',
//outroId: '',
cep: '',
cidade: PatientDict.cidade,
estado: PatientDict.estado,
bairro: PatientDict.bairro,
rua: PatientDict.logradouro,
numero: '',
complemento: '',
email: PatientDict.email,
telefone1: PatientDict.celular,
telefone2: '',
telefone3: '',
observacoes: ''
});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({
...formData,
[name]: value
});
if(name.includes('cpf')){
let cpfFormatado = FormatCPF(e.target.value)
setFormData({...formData,
[name]: cpfFormatado,}
)}
else if(name.includes('telefone')){
let telefoneFormatado = FormatTelefones(value)
console.log(telefoneFormatado)
setFormData({...formData,
[name]: telefoneFormatado
})
}
};
// Função para buscar endereço pelo CEP
const handleCepBlur = async () => {
const cep = formData.cep.replace(/\D/g, '');
if (cep.length === 8) {
try {
const response = await fetch(`https://viacep.com.br/ws/${cep}/json/`);
const data = await response.json();
if (!data.erro) {
setFormData((prev) => ({
...prev,
rua: data.logradouro || '',
bairro: data.bairro || '',
cidade: data.localidade || '',
estado: data.uf || ''
}));
} else {
alert('CEP não encontrado!');
}
} catch (error) {
alert('Erro ao buscar o CEP.');
}
}
};
const handleSubmit = () => {
if (!formData.nome || !formData.cpf || !formData.genero || !formData.dataNascimento || !formData.email){
alert('Por favor, preencha: Nome ,CPF, Gênero, Data de nascimento e Email.');
return;
}
onSave(
{nome: formData.nome,
nomeSocial: formData.nomeSocial,
dataNascimento: formData.dataNascimento,
genero: formData.genero,
//documento: formData.documento,
//numeroDocumento: formData.numeroDocumento,
cpf: formData.cpf,
profissao: formData.profissao,
//nomeConjuge: formData.nomeConjuge,
//outroId: formData.outroId,
endereco: {
cep: formData.cep,
cidade: formData.cidade,
estado: formData.estado,
bairro: formData.bairro,
logradouro: formData.rua,
numero: formData.numero,
complemento: formData.complemento,
},
contato: {
email: formData.email,
telefone1: formData.telefone1,
telefone2: formData.telefone2,
telefone3: formData.telefone3,
},
observacoes: formData.observacoes,
}
);
};
return (
<div className="card p-3">
<h3 className="mb-3 text-center">MediConnect</h3>
{/* ------------------ DADOS PESSOAIS ------------------ */}
<h5 className="mb-3">Dados Pessoais</h5>
<div className="row">
<div className="col-md-6 mb-3">
<label>Nome: *</label>
<input type="text" className="form-control" name="nome" value={formData.nome} onChange={handleChange} />
</div>
<div className="col-md-6 mb-3">
<label>Nome social:</label>
<input type="text" className="form-control" name="nomeSocial" value={formData.nomeSocial} onChange={handleChange} />
</div>
<div className="col-md-6 mb-3">
<label>Data de nascimento:</label>
<input type="date" className="form-control" name="dataNascimento" value={formData.dataNascimento} onChange={handleChange} />
</div>
<div className="col-md-6 mb-3">
<label>Gênero: *</label>
<select className="form-control" name="genero" value={formData.genero} onChange={handleChange}>
<option value="">Selecione</option>
<option value="Masculino">Masculino</option>
<option value="Feminino">Feminino</option>
<option value="Outro">Outro</option>
</select>
</div>
{/*
<div className="col-md-6 mb-3">
<label>Outro documento:</label>
<input type="text" className="form-control" name="documento" value={formData.documento} onChange={handleChange} />
</div>
<div className="col-md-6 mb-3">
<label>Número do documento:</label>
<input type="text" className="form-control" name="numeroDocumento" value={formData.numeroDocumento} onChange={handleChange} />
</div>
*/}
<div className="col-md-6 mb-3">
<label>CPF: *</label>
<input type="text" className="form-control" name="cpf" value={formData.cpf} onChange={ handleChange} />
</div>
<div className="col-md-6 mb-3">
<label>Especialização:</label>
<select
className="form-control"
name="profissao"
value={formData.profissao}
onChange={handleChange}
>
<option value="">Selecione uma especialização</option>
<option value="Cardiologia">Clínica médica (clínico geral)</option>
<option value="Dermatologia">Pediatria</option>
<option value="Ginecologia">Ginecologia e obstetrícia</option>
<option value="Pediatria">Cardiologia</option>
<option value="Ortopedia">Ortopedia e traumatologia</option>
<option value="Oftalmologia">Oftalmologia</option>
<option value="Neurologia">Otorrinolaringologia</option>
<option value="Psiquiatria">Dermatologia</option>
<option value="Endocrinologia">Neurologia</option>
<option value="Oncologia">Psiquiatria</option>
<option value="Oncologia">Endocrinologia</option>
<option value="Oncologia">Gastroenterologia</option>
<option value="Oncologia">Urologia</option>
</select>
</div>
{/*
<div className="col-md-6 mb-3">
<label>Nome do esposo(a):</label>
<input type="text" className="form-control" name="nomeConjuge" value={formData.nomeConjuge} onChange={handleChange} />
</div>
<div className="col-md-6 mb-3">
<label>Identificador de outro sistema:</label>
<input type="text" className="form-control" name="outroId" value={formData.outroId} onChange={handleChange} />
</div>
*/}
</div>
{/* ------------------ ENDEREÇO ------------------ */}
<h5>Endereço</h5>
<div className="row">
<div className="col-md-4 mb-3">
<label>CEP:</label>
<input type="text" className="form-control" name="cep" value={formData.cep} onChange={handleChange} onBlur={handleCepBlur} />
</div>
<div className="col-md-8 mb-3">
<label>Rua:</label>
<input type="text" className="form-control" name="rua" value={formData.rua} onChange={handleChange} />
</div>
<div className="col-md-6 mb-3">
<label>Bairro:</label>
<input type="text" className="form-control" name="bairro" value={formData.bairro} onChange={handleChange} />
</div>
<div className="col-md-4 mb-3">
<label>Cidade:</label>
<input type="text" className="form-control" name="cidade" value={formData.cidade} onChange={handleChange} />
</div>
<div className="col-md-2 mb-3">
<label>Estado:</label>
<input type="text" className="form-control" name="estado" value={formData.estado} onChange={handleChange} />
</div>
<div className="col-md-4 mb-3">
<label>Número:</label>
<input type="text" className="form-control" name="numero" value={formData.numero} onChange={handleChange} />
</div>
<div className="col-md-8 mb-3">
<label>Complemento:</label>
<input type="text" className="form-control" name="complemento" value={formData.complemento} onChange={handleChange} />
</div>
</div>
{/* ------------------ CONTATO ------------------ */}
<h5>Contato</h5>
<div className="row">
<div className="col-md-6 mb-3">
<label>E-mail: *</label>
<input type="email" className="form-control" name="email" value={formData.email} onChange={handleChange} />
</div>
<div className="col-md-6 mb-3">
<label>Telefone: *</label>
<input type="text" className="form-control" name="telefone1" value={formData.telefone1} onChange={handleChange} />
</div>
<div className="col-md-6 mb-3">
<label>Telefone 2:</label>
<input type="text" className="form-control" name="telefone2" value={formData.telefone2} onChange={handleChange} />
</div>
<div className="col-md-6 mb-3">
<label>Telefone 3:</label>
<input type="text" className="form-control" name="telefone3" value={formData.telefone3} onChange={handleChange} />
</div>
</div>
{/* ------------------ INFORMAÇÕES ADICIONAIS ------------------ */}
<h5>Informações Adicionais</h5>
<div className="mb-3">
<label>Observações:</label>
<textarea className="form-control" name="observacoes" value={formData.observacoes} onChange={handleChange}></textarea>
</div>
{/* Botões */}
<div className="mt-3">
<button className="btn btn-success me-2" onClick={handleSubmit}>
Salvar Paciente
</button>
<button className="btn btn-light" onClick={onCancel}>
Cancelar
</button>
</div>
</div>
);
}
export default DoctorForm;

View File

@ -0,0 +1,20 @@
import React from 'react';
// Este componente recebe uma função 'onAddDoctor' para avisar que o botão foi clicado
function DoctorList({ onAddPatient }) {
return (
<div className="card">
<div className="card-header">
<h4 className="card-title">Médicos</h4>
</div>
<div className="card-body">
<p>Gerencie os médicos cadastrados no sistema.</p>
<button className="btn btn-primary" onClick={onAddPatient}>
<i className="bi bi-plus-circle"></i> Adicionar Médico
</button>
</div>
</div>
);
}
export default DoctorList;

View File

@ -90,6 +90,13 @@ function PatientForm({ onSave, onCancel, PatientDict }) {
})
}
else if(name.includes('cep')){
const digitsCep = String(value).replace(/\D/g, '').slice(0, 8);
setFormData({...formData,
[name]: digitsCep
})
}
};
@ -120,10 +127,11 @@ function PatientForm({ onSave, onCancel, PatientDict }) {
};
const handleSubmit = () => {
if (!formData.nome || !formData.cpf || !formData.genero || !formData.dataNascimento){
alert('Por favor, preencha Nome ,CPF, Gênero e data de nascimento.');
if (!formData.nome || !formData.cpf || !formData.genero || !formData.dataNascimento || !formData.email||!formData.telefone1){
alert('Por favor, preencha: Nome ,CPF, Gênero, Data de nascimento, telefone e Email.');
return;
}
onSave(
{nome: formData.nome,
nomeSocial: formData.nomeSocial,
@ -167,13 +175,13 @@ function PatientForm({ onSave, onCancel, PatientDict }) {
return (
<div className="card p-3">
<h3 className="mb-3 text-center">MedicoConnect</h3>
<h3 className="mb-3 text-center">MediConnect</h3>
{/* ------------------ DADOS PESSOAIS ------------------ */}
<h5 className="mb-3">Dados Pessoais</h5>
<div className="row">
<div className="col-md-6 mb-3">
<label>Nome:</label>
<label>Nome: *</label>
<input type="text" className="form-control" name="nome" value={formData.nome} onChange={handleChange} />
</div>
<div className="col-md-6 mb-3">
@ -181,11 +189,11 @@ function PatientForm({ onSave, onCancel, PatientDict }) {
<input type="text" className="form-control" name="nomeSocial" value={formData.nomeSocial} onChange={handleChange} />
</div>
<div className="col-md-6 mb-3">
<label>Data de nascimento:</label>
<label>Data de nascimento: *</label>
<input type="date" className="form-control" name="dataNascimento" value={formData.dataNascimento} onChange={handleChange} />
</div>
<div className="col-md-6 mb-3">
<label>Gênero:</label>
<label>Gênero: *</label>
<select className="form-control" name="genero" value={formData.genero} onChange={handleChange}>
<option value="">Selecione</option>
<option value="Masculino">Masculino</option>
@ -202,7 +210,7 @@ function PatientForm({ onSave, onCancel, PatientDict }) {
<input type="text" className="form-control" name="numeroDocumento" value={formData.numeroDocumento} onChange={handleChange} />
</div>
<div className="col-md-6 mb-3">
<label>CPF:</label>
<label>CPF: *</label>
<input type="text" className="form-control" name="cpf" value={formData.cpf} onChange={ handleChange} />
</div>
<div className="col-md-6 mb-3">
@ -280,11 +288,11 @@ function PatientForm({ onSave, onCancel, PatientDict }) {
<h5>Contato</h5>
<div className="row">
<div className="col-md-6 mb-3">
<label>Email:</label>
<label>Email: *</label>
<input type="email" className="form-control" name="email" value={formData.email} onChange={handleChange} />
</div>
<div className="col-md-6 mb-3">
<label>Telefone:</label>
<label>Telefone: *</label>
<input type="text" className="form-control" name="telefone1" value={formData.telefone1} onChange={handleChange} />
</div>
<div className="col-md-6 mb-3">

View File

@ -3,93 +3,29 @@
"name": "Menu",
"isTitle": true
},
{
"name": "Dashboard",
"url": "dashboard",
"icon": "grid-fill"
},
{
"name": "Form Layout",
"name": "Cadastro de Pacientes",
"url": "form-layout",
"icon": "file-earmark-medical-fill"
},
{
"name": "Table",
"name": "Cadastro do Médico",
"url": "doctor-form-layout",
"icon": "file-earmark-medical-fill"
},
{
"name": "Lista de Pacientes",
"icon": "table",
"url": "table"
},
{
"name": "Data Table",
"icon": "table",
"url": "data-table"
},
{
"name": "Files",
"icon": "folder",
"url": "files"
},
"name": "Lista de Médico",
"icon": "table",
"url": "doctor-table"
}
{
"name": "comunicação",
"isTitle": true
},
{
"name": "Email App",
"icon": "envelope",
"url": "email-app"
},
{
"name": "Chat App",
"icon": "chat-dots",
"url": "chat-app"
},
{
"name": "GalleryApp",
"icon": "gallery-fill",
"url": "gallery-app"
},
{
"name": "Account",
"key": "account",
"icon": "person-circle",
"submenu": [
{
"name": "Profile",
"url": "account-profile.html"
},
{
"name": "Security",
"url": "account-security.html"
}
]
},
{
"name": "Authentication",
"key": "auth",
"icon": "person-badge-fill",
"submenu": [
{
"name": "Login",
"url": "auth-login.html"
},
{
"name": "Register",
"url": "auth-register.html"
},
{
"name": "Forgot Password",
"url": "auth-forgot-password.html"
}
]
}
]

View File

@ -0,0 +1,52 @@
// import React from 'react'
// import DoctorForm from '../components/doctors/DoctorForm'
// import {useEffect, useState} from 'react'
// const EditPage = ( {id}) => {
// const [PatientToPUT, setPatientPUT] = useState({})
// var requestOptions = {
// method: 'GET',
// redirect: 'follow'
// };
// useEffect(() => {
// fetch(`https://mock.apidog.com/m1/1053378-0-default/pacientes/${id}`, requestOptions)
// .then(response => response.json())
// .then(result => result.data)
// .then(data => console.log(data))
// .catch(error => console.log('error', error));
// }, [])
// const HandlePutPatient = () => {
// console.log('médico atualizado')
// }
// return (
// <div>
// <button>Voltar para lista sem salvar</button>
// <PatientForm
// onSave={HandlePutPatient}
// onCancel={console.log('Não atualizar')}
// PatientDict={PatientToPUT}
// />
// </div>
// )
// }
// export default EditPage

View File

@ -0,0 +1,69 @@
import React, { useState } from 'react';
// Importamos os dois novos componentes que criamos
import DoctorList from '../components/doctors/DoctorList';
import DoctorForm from '../components/doctors/DoctorForm';
function FormLayout( ) {
// Este estado vai controlar qual "tela" mostrar: 'list' (lista) ou 'form' (formulário)
const [view, setView] = useState('form');
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
// Função que será chamada para "salvar" o paciente
const handleSavePatient = (patientData) => {
console.log('Salvando médico:', patientData);
var raw = JSON.stringify(patientData)
var requestOptions = {
method:'POST',
header: myHeaders,
body:raw,
redirect:'follow'
}
fetch("https://mock.apidog.com/m1/1053378-0-default/pacientes", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
alert(`Médico "${patientData.nome}" salvo com sucesso!`); //altere isso para integração com backend
// Após salvar, voltamos para a tela de lista
setView('list');
};
return (
<>
<div className="page-heading">
<h3>Cadastro de Médicos</h3>
</div>
<div className="page-content">
<section className="row">
<div className="col-12">
{/* Aqui está a lógica principal: */}
{/* Se a view for 'list', mostramos a lista com o botão. */}
{/* Se for 'form', mostramos o formulário de cadastro. */}
{view === 'list' ? (
<DoctorList onAddPatient={() => setView('form')} />
) : (
<DoctorForm
onSave={handleSavePatient}
onCancel={() => setView('list')}
PatientDict={{}}
/>
)}
</div>
</section>
</div>
</>
);
}
export default FormLayout;

157
src/pages/DoctorTable.jsx Normal file
View File

@ -0,0 +1,157 @@
import React, { useState, useEffect } from 'react';
import DoctorList from '../components/doctors/DoctorList';
import DoctorForm from '../components/doctors/DoctorForm';
function TableDoctor({ setCurrentPage, setPatientID }) {
const [pacientes, setPacientes] = useState([]);
const [search, setSearch] = useState("");
// Função para excluir médicos
const deletePatient = async (id) => {
const requestOptionsDelete = { method: "DELETE", redirect: "follow" };
if (!window.confirm("Tem certeza que deseja excluir este médico?")) return;
await fetch(
`https://mock.apidog.com/m1/1053378-0-default/pacientes/${id}`,
requestOptionsDelete
)
.then((response) => response.text())
.then((mensage) => console.log(mensage))
.catch((error) => console.log("Deu problema", error));
};
const onChange = (e, id) => {
let value = e.target.value;
if (value === "verdetalhes") {
setCurrentPage("details-page-paciente");
}
if (value === "editar") {
setCurrentPage("edit-page-paciente");
setPatientID(id);
}
if (value === "excluir") {
console.log(`Excluir ${id}`);
deletePatient(id);
}
};
var requestOptions = {
method: "GET",
redirect: "follow",
};
useEffect(() => {
fetch(
"https://mock.apidog.com/m1/1053378-0-default/pacientes",
requestOptions
)
.then((response) => response.json())
.then((result) => setPacientes(result["data"]))
.catch((error) =>
console.log("Erro para encontrar médicos no banco de dados", error)
);
}, []);
// Filtrar médicos pelo campo de pesquisa (nome, cpf, email, telefone)
const pacientesFiltrados = pacientes.filter((paciente) =>
`${paciente.nome} ${paciente.cpf} ${paciente.email} ${paciente.telefone}`
.toLowerCase()
.includes(search.toLowerCase())
);
return (
<>
<div className="page-heading">
<h3>Lista de Médicos</h3>
</div>
<div className="page-content">
<section className="row">
<div className="col-12">
<div className="card">
{/* Header com título e botão alinhados */}
<div className="card-header d-flex justify-content-between align-items-center">
<h4 className="card-title mb-0">Médicos Cadastrados</h4>
<button
className="btn btn-primary"
onClick={() => setCurrentPage("form-layout")}
>
<i className="bi bi-plus-circle"></i> Adicionar Médico
</button>
</div>
<div className="card-body">
{/* Barra de pesquisa abaixo do título */}
<div className="mb-3">
<input
type="text"
placeholder="Pesquisar médico..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="form-control"
/>
</div>
<div className="table-responsive">
<table className="table table-striped table-hover">
<thead>
<tr>
<th>Nome</th>
<th>CPF</th>
<th>Email</th>
<th>Telefone</th>
<th>Opções</th>
</tr>
</thead>
<tbody>
{pacientesFiltrados.length > 0 ? (
pacientesFiltrados.map((paciente) => (
<tr key={paciente.id}>
<td>{paciente.nome}</td>
<td>{paciente.cpf}</td>
<td>{paciente.email}</td>
<td>{paciente.telefone}</td>
<td>
<span
className={`badge ${
paciente.ativo === "ativo"
? "bg-success"
: "bg-danger"
}`}
>
{paciente.ativo}
</span>
</td>
<td>
<select onChange={(e) => onChange(e, paciente.id)}>
<option value="">:</option>
<option value="verdetalhes">Ver detalhes</option>
<option value="editar">Editar</option>
<option value="excluir">Excluir</option>
</select>
</td>
</tr>
))
) : (
<tr>
<td colSpan="6" className="text-center">
Nenhum paciente encontrado.
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
</div>
</div>
</section>
</div>
</>
);
}
export default TableDoctor;

View File

@ -6,8 +6,8 @@ import PatientForm from '../components/patients/PatientForm';
function FormLayout( ) {
// Este estado vai controlar qual "tela" mostrar: 'list' (lista) ou 'form' (formulário)
const [view, setView] = useState('list');
const [view, setView] = useState('form');
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
@ -40,7 +40,7 @@ function FormLayout( ) {
return (
<>
<div className="page-heading">
<h3>Gerenciamento de Pacientes</h3>
<h3>Cadastro de Pacientes</h3>
</div>
<div className="page-content">
<section className="row">

View File

@ -1,89 +1,100 @@
import React, { useState, useEffect } from 'react';
import PatientList from '../components/patients/PatientList';
import PatientForm from '../components/patients/PatientForm';
function TablePaciente({ setCurrentPage, setPatientID }) {
const [pacientes, setPacientes] = useState([]);
const [search, setSearch] = useState("");
function Table( {setCurrentPage, setPatientID}) {
// Função para excluir paciente
const deletePatient = async (id) => {
const requestOptionsDelete = { method: "DELETE", redirect: "follow" };
if (!window.confirm("Tem certeza que deseja excluir este paciente?")) return;
// Função para excluir paciente
const deletePatient = async (id) => {
const requestOptionsDelete = {method: 'DELETE',redirect:'follow' };
if (!window.confirm('Tem certeza que deseja excluir este paciente?')) return;
const response = await fetch(`https://mock.apidog.com/m1/1053378-0-default/pacientes/${id}`, requestOptionsDelete)
.then(response => response.text())
.then(mensage => console.log(mensage))
.catch(error => console.log('Deu problema', error))
}
await fetch(
`https://mock.apidog.com/m1/1053378-0-default/pacientes/${id}`,
requestOptionsDelete
)
.then((response) => response.text())
.then((mensage) => console.log(mensage))
.catch((error) => console.log("Deu problema", error));
};
const onChange = (e, id) => {
let value = e.target.value
console.log(e.target.value)
let value = e.target.value;
if(value === 'verdetalhes'){
setCurrentPage('details-page-paciente')
if (value === "verdetalhes") {
setCurrentPage("details-page-paciente");
}
if(value === 'editar')
{setCurrentPage('edit-page-paciente')
setPatientID(id)
}
if(value === 'excluir'){
console.log(`Excluir ${id}`)
deletePatient(id)
if (value === "editar") {
setCurrentPage("edit-page-paciente");
setPatientID(id);
}
}
//const [resposta, setResposta] = useState(dadosEstáticos);
//const { data: pacientes, pagination } = resposta;
let [pacientes, setPacientes] = useState([])
if (value === "excluir") {
console.log(`Excluir ${id}`);
deletePatient(id);
}
};
var requestOptions = {
method:'GET',
redirect:'follow'
}
method: "GET",
redirect: "follow",
};
useEffect(() => {
console.log('hsjduhdeu')
fetch('https://mock.apidog.com/m1/1053378-0-default/pacientes', requestOptions)
.then(response => response.json())
.then(result => setPacientes(result['data']))
.catch(error => console.log('Erro para encontrar pacientes no banco de dados', error))}, [])
useEffect(() => {
fetch(
"https://mock.apidog.com/m1/1053378-0-default/pacientes",
requestOptions
)
.then((response) => response.json())
.then((result) => setPacientes(result["data"]))
.catch((error) =>
console.log("Erro para encontrar pacientes no banco de dados", error)
);
}, []);
// Filtrar pacientes pelo campo de pesquisa (nome, cpf, email, telefone)
const pacientesFiltrados = pacientes.filter((paciente) =>
`${paciente.nome} ${paciente.cpf} ${paciente.email} ${paciente.telefone}`
.toLowerCase()
.includes(search.toLowerCase())
);
return (
<>
<div className="page-heading">
<h3>Tabela de Pacientes</h3>
<h3>Lista de Pacientes</h3>
</div>
<div className="page-content">
<section className="row">
<div className="col-12">
<div className="card">
<div className="card-header">
<h4 className="card-title">Pacientes Cadastrados</h4>
{/* Header com título e botão alinhados */}
<div className="card-header d-flex justify-content-between align-items-center">
<h4 className="card-title mb-0">Pacientes Cadastrados</h4>
<button
className="btn btn-primary"
onClick={() => setCurrentPage("form-layout")}
>
<i className="bi bi-plus-circle"></i> Adicionar Paciente
</button>
</div>
<div className="card-body">
{/* Barra de pesquisa abaixo do título */}
<div className="mb-3">
<input
type="text"
placeholder="Pesquisar paciente..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="form-control"
/>
</div>
<div className="table-responsive">
<table className="table table-striped table-hover">
<thead>
@ -92,37 +103,44 @@ useEffect(() => {
<th>CPF</th>
<th>Email</th>
<th>Telefone</th>
<th>Status</th>
<th>Opções</th>
</tr>
</thead>
<tbody>
{pacientes.length > 0 ? (
pacientes.map(paciente => (
{pacientesFiltrados.length > 0 ? (
pacientesFiltrados.map((paciente) => (
<tr key={paciente.id}>
<td>{paciente.nome}</td>
<td>{paciente.cpf}</td>
<td>{paciente.email}</td>
<td>{paciente.telefone}</td>
<td>
<span className={`badge ${paciente.status === 'ativo' ? 'bg-success' : 'bg-danger'}`}>
{paciente.status}
<span
className={`badge ${
paciente.ativo === "ativo"
? "bg-success"
: "bg-danger"
}`}
>
{paciente.ativo}
</span>
</td>
<td>
<select name="" id="" onChange={(e) => onChange(e,paciente.id)}>
<option value="">:</option>
<option value="verdetalhes">Ver detalhes</option>
<option value="editar">Editar</option>
<option value="excluir">Excluir</option>
</select></td>
<td>
<select onChange={(e) => onChange(e, paciente.id)}>
<option value=""> </option>
<option value="verdetalhes">Ver detalhes</option>
<option value="editar">Editar</option>
<option value="excluir">Excluir</option>
</select>
</td>
</tr>
))
) : (
<tr>
<td colSpan="5" className="text-center">Nenhum paciente encontrado.</td>
<td colSpan="6" className="text-center">
Nenhum paciente encontrado.
</td>
</tr>
)}
</tbody>
@ -136,6 +154,4 @@ useEffect(() => {
</>
);
}
export default Table;
export default TablePaciente;