forked from RiseUP/riseup-squad21
configuração do envio de sms
This commit is contained in:
parent
6daa0d247f
commit
0fcc7ae97b
@ -207,46 +207,101 @@ export default function ScheduleForm() {
|
|||||||
}, [selectedDoctor, selectedDate, fetchAvailableSlots]);
|
}, [selectedDoctor, selectedDate, fetchAvailableSlots]);
|
||||||
|
|
||||||
// 🔹 Submeter agendamento
|
// 🔹 Submeter agendamento
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
// 🔹 Submeter agendamento
|
||||||
e.preventDefault();
|
// 🔹 Submeter agendamento
|
||||||
|
// 🔹 Submeter agendamento
|
||||||
|
// 🔹 Submeter agendamento
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
const isSecretaryLike = ["secretaria", "admin", "gestor"].includes(role);
|
const isSecretaryLike = ["secretaria", "admin", "gestor"].includes(role);
|
||||||
const patientId = isSecretaryLike ? selectedPatient : userId;
|
const patientId = isSecretaryLike ? selectedPatient : userId;
|
||||||
|
|
||||||
if (!patientId || !selectedDoctor || !selectedDate || !selectedTime) {
|
if (!patientId || !selectedDoctor || !selectedDate || !selectedTime) {
|
||||||
toast({ title: "Campos obrigatórios", description: "Preencha todos os campos." });
|
toast({ title: "Campos obrigatórios", description: "Preencha todos os campos." });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const body = {
|
||||||
|
doctor_id: selectedDoctor,
|
||||||
|
patient_id: patientId,
|
||||||
|
scheduled_at: `${selectedDate}T${selectedTime}:00`,
|
||||||
|
duration_minutes: Number(duracao),
|
||||||
|
notes,
|
||||||
|
appointment_type: tipoConsulta,
|
||||||
|
};
|
||||||
|
|
||||||
|
// ✅ mantém o fluxo original de criação (funcional)
|
||||||
|
await appointmentsService.create(body);
|
||||||
|
|
||||||
|
const dateFormatted = selectedDate.split("-").reverse().join("/");
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: "Consulta agendada!",
|
||||||
|
description: `Consulta marcada para ${dateFormatted} às ${selectedTime} com o(a) médico(a) ${
|
||||||
|
doctors.find((d) => d.id === selectedDoctor)?.full_name || ""
|
||||||
|
}.`,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 📞 busca o telefone corretamente
|
||||||
|
let phoneNumber = "+5511999999999"; // fallback
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const body = {
|
if (isSecretaryLike) {
|
||||||
doctor_id: selectedDoctor,
|
// se for secretária/admin → usa paciente selecionado
|
||||||
patient_id: patientId,
|
const patient = patients.find((p: any) => p.id === patientId);
|
||||||
scheduled_at: `${selectedDate}T${selectedTime}:00`,
|
if (patient?.phone_number) phoneNumber = patient.phone_number;
|
||||||
duration_minutes: Number(duracao),
|
} else {
|
||||||
notes,
|
// se for paciente → usa o service do próprio user
|
||||||
appointment_type: tipoConsulta,
|
const me = await usersService.getMe();
|
||||||
};
|
if (me?.profile?.phone) phoneNumber = me.profile.phone;
|
||||||
|
}
|
||||||
|
|
||||||
await appointmentsService.create(body);
|
// padroniza número para formato internacional (+55)
|
||||||
const dateFormatted = selectedDate.split("-").reverse().join("/");
|
if (phoneNumber) {
|
||||||
toast({
|
phoneNumber = phoneNumber.replace(/\D/g, ""); // remove caracteres não numéricos
|
||||||
title: "Consulta agendada!",
|
if (!phoneNumber.startsWith("55")) phoneNumber = `55${phoneNumber}`;
|
||||||
description: `Consulta marcada para ${dateFormatted} às ${selectedTime} com o(a) médico(a) ${
|
phoneNumber = `+${phoneNumber}`;
|
||||||
doctors.find((d) => d.id === selectedDoctor)?.full_name || ""
|
}
|
||||||
}.`,
|
|
||||||
});
|
|
||||||
|
|
||||||
setSelectedDoctor("");
|
|
||||||
setSelectedDate("");
|
|
||||||
setSelectedTime("");
|
|
||||||
setNotes("");
|
|
||||||
setSelectedPatient("");
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.warn("Não foi possível obter telefone do paciente:", err);
|
||||||
toast({ title: "Erro", description: "Falha ao agendar consulta." });
|
|
||||||
}
|
}
|
||||||
};
|
|
||||||
|
// 💬 envia o SMS de confirmação
|
||||||
|
// 💬 Envia o SMS de lembrete (sem mostrar nada ao paciente)
|
||||||
|
try {
|
||||||
|
const smsRes = await appointmentsService.send_sms({
|
||||||
|
phone_number: phoneNumber,
|
||||||
|
message: `Lembrete: sua consulta é em ${dateFormatted} às ${selectedTime} na Clínica MediConnect.`,
|
||||||
|
patient_id: patientId,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (smsRes?.success) {
|
||||||
|
console.log("✅ SMS enviado com sucesso:", smsRes.message_sid || smsRes.sid || "(sem SID retornado)");
|
||||||
|
} else {
|
||||||
|
console.warn("⚠️ Falha no envio do SMS:", smsRes);
|
||||||
|
}
|
||||||
|
} catch (smsErr) {
|
||||||
|
console.error("❌ Erro ao enviar SMS:", smsErr);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// 🧹 limpa os campos
|
||||||
|
setSelectedDoctor("");
|
||||||
|
setSelectedDate("");
|
||||||
|
setSelectedTime("");
|
||||||
|
setNotes("");
|
||||||
|
setSelectedPatient("");
|
||||||
|
} catch (err) {
|
||||||
|
console.error("❌ Erro ao agendar consulta:", err);
|
||||||
|
toast({ title: "Erro", description: "Falha ao agendar consulta." });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// 🔹 Tooltip no calendário
|
// 🔹 Tooltip no calendário
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|||||||
@ -45,4 +45,7 @@ export const appointmentsService = {
|
|||||||
* @returns {Promise<object>} - Uma promessa que resolve com a resposta da API.
|
* @returns {Promise<object>} - Uma promessa que resolve com a resposta da API.
|
||||||
*/
|
*/
|
||||||
delete: (id) => api.delete(`/rest/v1/appointments?id=eq.${id}`),
|
delete: (id) => api.delete(`/rest/v1/appointments?id=eq.${id}`),
|
||||||
|
|
||||||
|
send_sms: (data) => api.post("/functions/v1/send-sms", data)
|
||||||
|
|
||||||
};
|
};
|
||||||
Loading…
x
Reference in New Issue
Block a user