riseup-squad23/src/pages/paciente/CadastroConsulta.jsx
2025-12-04 11:06:18 -03:00

113 lines
3.3 KiB
JavaScript

//ConsultaCadastroManager.jsx
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuth } from '../../_assets/utils/AuthProvider'
import { UserInfos } from '../../_assets/utils/Functions-Endpoints/General'
import API_KEY from '../../_assets/utils/apiKeys'
import dayjs from 'dayjs'
import FormConsultaPaciente from '../../components/paciente/FormConsultaPaciente'
const ConsultaCadastroManager = () => {
const { getAuthorizationHeader, user } = useAuth();
const navigate = useNavigate();
const [Dict, setDict] = useState({});
// patient_id fixo do Pedro Abravanel
const [patientId, setPatientId] = useState('bf7d8323-05e1-437a-817c-f08eb5f174ef');
const [idUsuario, setIDusuario] = useState('');
const authHeader = getAuthorizationHeader();
// Opcional: ainda tenta buscar infos do usuário, mas NÃO mostra mais alerta
useEffect(() => {
const ColherInfoUsuario = async () => {
try {
if (!authHeader) return;
const result = await UserInfos(authHeader);
const pid =
result?.patient_id ||
result?.profile?.id ||
user?.patient_id ||
user?.profile?.id ||
user?.user?.id;
if (pid) {
setPatientId(pid);
}
setIDusuario(result?.profile?.id || pid || '');
} catch (e) {
console.error('Erro ao colher infos do usuário:', e);
}
};
ColherInfoUsuario();
}, [authHeader, user]);
const handleSave = (Dict) => {
// se por algum motivo não tiver, usa o fixo do Pedro
const finalPatientId = patientId || 'bf7d8323-05e1-437a-817c-f08eb5f174ef';
const myHeaders = new Headers();
myHeaders.append('apikey', API_KEY);
myHeaders.append('Authorization', authHeader);
myHeaders.append('Content-Type', 'application/json');
const raw = JSON.stringify({
patient_id: finalPatientId, // paciente Pedro
doctor_id: Dict.doctor_id,
scheduled_at: `${Dict.dataAtendimento}T${Dict.horarioInicio}:00.000Z`,
duration_minutes: 30,
appointment_type: Dict.tipo_consulta,
patient_notes: 'Prefiro horário pela manhã',
insurance_provider: Dict.convenio,
status: 'confirmed',
created_by: idUsuario || finalPatientId,
});
const requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow',
};
fetch(
'https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/appointments',
requestOptions
)
.then(async (response) => {
if (!response.ok) {
const text = await response.text();
throw new Error(`Erro ao salvar consulta: ${response.status} - ${text}`);
}
return response.text();
})
.then(() => {
alert('Consulta solicitada com sucesso!');
navigate('/paciente/agendamento/'); // volta para o calendário
})
.catch((error) => {
console.error('error', error);
alert('Erro ao salvar a consulta. Tente novamente.');
});
};
return (
<div>
<FormConsultaPaciente
agendamento={Dict}
setAgendamento={setDict}
onSave={handleSave}
onCancel={() => navigate('/paciente/agendamento/')}
/>
</div>
);
};
export default ConsultaCadastroManager;