diff --git a/src/components/AgendarConsulta/FormNovaConsulta.jsx b/src/components/AgendarConsulta/FormNovaConsulta.jsx index 435bc8ee..d45e6596 100644 --- a/src/components/AgendarConsulta/FormNovaConsulta.jsx +++ b/src/components/AgendarConsulta/FormNovaConsulta.jsx @@ -1,57 +1,20 @@ import InputMask from "react-input-mask"; import "./style/formagendamentos.css"; import { useState, useEffect } from "react"; +import { GetPatientByCPF } from "../utils/Functions-Endpoints/Patient"; +import { GetDoctorByName } from "../utils/Functions-Endpoints/Doctor"; +import { useAuth } from "../utils/AuthProvider"; +const FormNovaConsulta = ({ onCancel, onSave }) => { + const {getAuthorizationHeader} = useAuth() -const FormNovaConsulta = ({ onCancel, patientID }) => { - const [selectedFile, setSelectedFile] = useState(null); const [anexos, setAnexos] = useState([]); const [loadingAnexos, setLoadingAnexos] = useState(false); - const [paciente, setPaciente] = useState({}) + const [agendamento, setAgendamento] = useState({}) const [acessibilidade, setAcessibilidade] = useState({cadeirante:false,idoso:false,gravida:false,bebe:false, autista:false }) - useEffect(() => { - if (!patientID) return; - - const fetchAnexos = async () => { - setLoadingAnexos(true); - try { - const res = await fetch(`https://mock.apidog.com/m1/1053378-0-default/pacientes/${patientID}/anexos`); - const data = await res.json(); - setAnexos(data.data || []); - } catch (err) { - console.error("Erro ao buscar anexos:", err); - } finally { - setLoadingAnexos(false); - } - }; - - fetchAnexos(); - }, [patientID]); - - const handleUpload = async () => { - if (!selectedFile) return; - - const formData = new FormData(); - formData.append("file", selectedFile); - - try { - const res = await fetch(`https://mock.apidog.com/m1/1053378-0-default/pacientes/${patientID}/anexos`, { - method: "POST", - body: formData - }); - if (res.ok) { - const novoAnexo = await res.json(); - setAnexos(prev => [...prev, novoAnexo]); - setSelectedFile(null); - } else { - console.error("Erro ao enviar anexo"); - } - } catch (err) { - console.error("Erro ao enviar anexo:", err); - } - }; + let authHeader = getAuthorizationHeader() const handleclickAcessibilidade = (id) => { @@ -62,112 +25,68 @@ const FormNovaConsulta = ({ onCancel, patientID }) => { else if(resultado === true){ setAcessibilidade({...acessibilidade, [id]:false})} console.log(id) } - - const FormatCPF = (valor) => { - console.log(valor) + const FormatCPF = (valor) => { const digits = String(valor).replace(/\D/g, '').slice(0, 11); - BuscarPacienteExistentePeloCPF(valor) - return digits .replace(/(\d{3})(\d)/, '$1.$2') .replace(/(\d{3})(\d)/, '$1.$2') .replace(/(\d{3})(\d{1,2})$/, '$1-$2'); } - - const FormatTelefones = (valor) => { - const digits = String(valor).replace(/\D/g, '').slice(0, 11); - return digits - .replace(/(\d)/, '($1') - .replace(/(\d{2})(\d)/, '$1) $2' ) - .replace(/(\d)(\d{4})/, '$1 $2') - .replace(/(\d{4})(\d{4})/, '$1-$2') - } - - - const BuscarCPFnoBancodeDados = async (cpf) => { - - var myHeaders = new Headers(); - myHeaders.append("Authorization", "Bearer "); - myHeaders.append("Content-Type", "application/json"); - - var raw = JSON.stringify({ - "cpf": cpf - }); - - var requestOptions = { - method: 'POST', - headers: myHeaders, - body: raw, - redirect: 'follow' - }; - - const response = await fetch("https://mock.apidog.com/m1/1053378-0-default/pacientes/validar-cpf", requestOptions); - const result = await response.json(); - return result - - - } - - const BuscarPacienteExistentePeloCPF = async (value) => { - - if(isNaN(value[13]) === false && value.length === 14)try { - const result = await BuscarCPFnoBancodeDados(value); - console.log("Resultado:", result); - - if (result.data.existe === true){ - - var myHeaders = new Headers(); - myHeaders.append("Authorization", "Bearer "); - - var requestOptions = { - method: 'GET', - headers: myHeaders, - redirect: 'follow' - }; - - fetch("https://mock.apidog.com/m1/1053378-0-default/pacientes/", requestOptions) - .then(response => response.json()) - .then(result => setPaciente(result.data)) - .catch(error => console.log('error', error)); - } - - - - } catch (error) { - console.log("error", error); - } - //BuscarCPFnoBancodeDados(value) - } + const handleChange = (e) => { const {value, name} = e.target; - console.log(value, name) + console.log(value, name, agendamento) if(name === 'email'){ - setPaciente({...paciente, contato:{ - ...paciente.contato, + setAgendamento({...agendamento, contato:{ + ...agendamento.contato, email:value }}) - } else if(name === 'telefone'){ - setPaciente({...paciente, contato:{ - ...paciente.contato, - telefone1:FormatTelefones(value) - }}) + }else if(name === 'cpf'){ + + let cpfFormatted = FormatCPF(value) + const fetchPatient = async () => { + let patientData = await GetPatientByCPF(cpfFormatted, authHeader); + if (patientData) { + setAgendamento((prev) => ({ + ...prev, + nome: patientData.full_name, + patient_id: patientData.id + })); + }} + setAgendamento(prev => ({ ...prev, cpf: cpfFormatted })) + fetchPatient() + }else if(name==='convenio'){ + setAgendamento({...agendamento,insurance_provider:value}) + }else if(name ==='profissional'){ + + + const fetchDoctor = async () => { + let DoctorData = await GetDoctorByName(value, authHeader) + if(DoctorData){ + setAgendamento((prev) => ({ + ...prev, + doctor_id:DoctorData.id + })) + }} + fetchDoctor() } else{ - setPaciente({...paciente,[name]:value}) + setAgendamento({...agendamento,[name]:value}) } } const handleSubmit = (e) => { e.preventDefault(); alert("Agendamento salvo!"); + onSave(agendamento) }; return ( @@ -180,57 +99,33 @@ const FormNovaConsulta = ({ onCancel, patientID }) => {
- +
- e.target.value = FormatCPF(e.target.value)} /> +
-
- - -
+
-
-
- - -
- -
- - -
- -
- - -
-
+
- + + +
-
- - -
- -
- - -
+

Informações adicionais

@@ -243,7 +138,7 @@ const FormNovaConsulta = ({ onCancel, patientID }) => { onChange={(e) => setSelectedFile(e.target.files[0])} /> {selectedFile && ( - )} @@ -291,7 +186,7 @@ const FormNovaConsulta = ({ onCancel, patientID }) => {
- +
diff --git a/src/components/utils/Functions-Endpoints/Doctor.js b/src/components/utils/Functions-Endpoints/Doctor.js index 2d6046f9..0aa4f437 100644 --- a/src/components/utils/Functions-Endpoints/Doctor.js +++ b/src/components/utils/Functions-Endpoints/Doctor.js @@ -23,4 +23,36 @@ return DictMedico } -export {GetDoctorByID} \ No newline at end of file +const GetAllDoctors = async (authHeader) => { + var myHeaders = new Headers(); + myHeaders.append("apikey", API_KEY); + myHeaders.append("Authorization", authHeader); + + var requestOptions = { + method: 'GET', + headers: myHeaders, + redirect: 'follow' + }; + + const result = await fetch("https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/doctors", requestOptions) + const DictMedicos = await result.json() + return DictMedicos + } + + +const GetDoctorByName = async (nome, authHeader) => { + const Medicos = await GetAllDoctors(authHeader) + + for (let i = 0; i < Medicos.length; i++) { + + if (Medicos[i].full_name === nome) { + console.log('Medico encontrado:', Medicos[i]); + return Medicos[i]; + } + else{console.log("nada encontrado")} + } + + +} + +export {GetDoctorByID, GetDoctorByName} \ No newline at end of file diff --git a/src/pages/Agendamento.jsx b/src/pages/Agendamento.jsx index d693cfee..c99ef275 100644 --- a/src/pages/Agendamento.jsx +++ b/src/pages/Agendamento.jsx @@ -1,23 +1,81 @@ -import React, { useState, useMemo } from 'react'; +import React, { useState, useMemo, useEffect } from 'react'; +import API_KEY from '../components/utils/apiKeys.js'; import TabelaAgendamentoDia from '../components/AgendarConsulta/TabelaAgendamentoDia'; import TabelaAgendamentoSemana from '../components/AgendarConsulta/TabelaAgendamentoSemana'; import TabelaAgendamentoMes from '../components/AgendarConsulta/TabelaAgendamentoMes'; import FormNovaConsulta from '../components/AgendarConsulta/FormNovaConsulta'; - +import { useAuth } from '../components/utils/AuthProvider.js'; // ✨ NOVO: Caminho de importação corrigido com base na sua estrutura de pastas import AgendamentosMes from '../components/AgendarConsulta/DadosConsultasMock.js'; + import dayjs from 'dayjs'; import "./style/Agendamento.css"; import './style/FilaEspera.css'; const Agendamento = () => { - const [FiladeEspera, setFiladeEspera] = useState(false); + const [FiladeEspera, setFiladeEspera] = useState(false); const [tabela, setTabela] = useState('diario'); const [PageNovaConsulta, setPageConsulta] = useState(false); const [searchTerm, setSearchTerm] = useState(''); + const [agendamentos, setAgendamentos] = useState() + const {getAuthorizationHeader} = useAuth() + + let authHeader = getAuthorizationHeader() + + const handleSave = (Dict) => { + let DataAtual = dayjs() + var myHeaders = new Headers(); + myHeaders.append("apikey", API_KEY); + myHeaders.append("Authorization", authHeader); + myHeaders.append("Content-Type", "application/json"); + +var raw = JSON.stringify({ + "patient_id": Dict.patient_id, + "doctor_id": Dict.doctor_id, + "scheduled_at": DataAtual, + "duration_minutes": 30, + "appointment_type": "presencial", + "chief_complaint": "Dor de cabeça há 3 ", + "patient_notes": "Prefiro horário pela manhã", + "insurance_provider": "Unimed", + "created_by": "87f2662c-9da7-45c0-9e05-521d9d92d105" +}); + +var requestOptions = { + method: 'POST', + headers: myHeaders, + body: raw, + redirect: 'follow' +}; + +fetch("https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/appointments", requestOptions) + .then(response => response.text()) + .then(result => console.log(result)) + .catch(error => console.log('error', error)); + + } + + // Requisição inicial para mnostrar os agendamentos do banco de dados + useEffect(() => { + var myHeaders = new Headers(); + myHeaders.append("Authorization", authHeader); + myHeaders.append("apikey", API_KEY) + + var requestOptions = { + method: 'GET', + headers: myHeaders, + redirect: 'follow' + }; + + fetch("https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/appointments?select&doctor_id&patient_id&status&scheduled_at&order&limit&offset", requestOptions) + .then(response => response.json()) + .then(result => setAgendamentos(result)) + .catch(error => console.log('error', error)); + }, []) + // Dados da fila de espera (sem alteração) const filaEsperaData = [ @@ -216,7 +274,7 @@ const Agendamento = () => { ) : ( - + )} )