diff --git a/app/secretary/schedule/page.tsx b/app/secretary/schedule/page.tsx index c9995f1..a932669 100644 --- a/app/secretary/schedule/page.tsx +++ b/app/secretary/schedule/page.tsx @@ -12,72 +12,104 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@ import { Textarea } from "@/components/ui/textarea"; import { Calendar, Clock, User } from "lucide-react"; import { patientsService } from "@/services/patientsApi.mjs"; -import { doctorsService } from "@/services/doctorsApi.mjs"; // Importar o serviço de médicos +import { doctorsService } from "@/services/doctorsApi.mjs"; +import { appointmentsService } from "@/services/appointmentsApi.mjs"; +import { usersService } from "@/services/usersApi.mjs"; // 1. IMPORTAR O SERVIÇO DE USUÁRIOS import { toast } from "sonner"; -const APPOINTMENTS_STORAGE_KEY = "clinic-appointments"; - export default function ScheduleAppointment() { const router = useRouter(); const [patients, setPatients] = useState([]); - const [doctors, setDoctors] = useState([]); // Estado para armazenar os médicos da API + const [doctors, setDoctors] = useState([]); + const [currentUserId, setCurrentUserId] = useState(null); // 2. NOVO ESTADO PARA O ID DO USUÁRIO + + // Estados do formulário const [selectedPatient, setSelectedPatient] = useState(""); const [selectedDoctor, setSelectedDoctor] = useState(""); const [selectedDate, setSelectedDate] = useState(""); const [selectedTime, setSelectedTime] = useState(""); - const [notes, setNotes] = useState(""); + const [appointmentType, setAppointmentType] = useState("presencial"); + const [durationMinutes, setDurationMinutes] = useState("30"); + const [chiefComplaint, setChiefComplaint] = useState(""); + const [patientNotes, setPatientNotes] = useState(""); + const [internalNotes, setInternalNotes] = useState(""); + const [insuranceProvider, setInsuranceProvider] = useState(""); + const availableTimes = [ + "08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30", + "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30" + ]; + + // Efeito para carregar todos os dados iniciais (pacientes, médicos e usuário atual) useEffect(() => { - const fetchData = async () => { + const fetchInitialData = async () => { try { - // Carrega pacientes e médicos em paralelo para melhor performance - const [patientList, doctorList] = await Promise.all([ + // Busca tudo em paralelo para melhor performance + const [patientList, doctorList, currentUser] = await Promise.all([ patientsService.list(), - doctorsService.list() + doctorsService.list(), + usersService.summary_data() // 3. CHAMADA PARA BUSCAR O USUÁRIO ]); + setPatients(patientList); setDoctors(doctorList); + + if (currentUser && currentUser.id) { + setCurrentUserId(currentUser.id); // Armazena o ID do usuário no estado + console.log("Usuário logado identificado:", currentUser.id); + } else { + toast.error("Não foi possível identificar o usuário logado. O agendamento pode falhar."); + } + } catch (error) { console.error("Falha ao buscar dados iniciais:", error); - toast.error("Não foi possível carregar os dados de pacientes e médicos."); + toast.error("Não foi possível carregar os dados necessários para a página."); } }; - fetchData(); + fetchInitialData(); }, []); - const availableTimes = ["08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30"]; - - const handleSubmit = (e: React.FormEvent) => { + const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); - const patientDetails = patients.find((p) => String(p.id) === selectedPatient); - const doctorDetails = doctors.find((d) => String(d.id) === selectedDoctor); - - if (!patientDetails || !doctorDetails) { - toast.error("Erro ao encontrar detalhes do paciente ou médico."); + // 4. ADICIONAR VALIDAÇÃO PARA O ID DO USUÁRIO + if (!currentUserId) { + toast.error("Sessão de usuário inválida. Por favor, faça login novamente."); return; } - const newAppointment = { - id: new Date().getTime(), // ID único simples - patientName: patientDetails.full_name, - doctor: doctorDetails.full_name, // Usar full_name para consistência - specialty: doctorDetails.specialty, - date: selectedDate, - time: selectedTime, - status: "agendada", - location: doctorDetails.location || "Consultório a definir", // Fallback - phone: doctorDetails.phone || "N/A", // Fallback - }; + if (!selectedPatient || !selectedDoctor || !selectedDate || !selectedTime) { + toast.error("Paciente, médico, data e horário são obrigatórios."); + return; + } - const storedAppointmentsRaw = localStorage.getItem(APPOINTMENTS_STORAGE_KEY); - const currentAppointments = storedAppointmentsRaw ? JSON.parse(storedAppointmentsRaw) : []; - const updatedAppointments = [...currentAppointments, newAppointment]; + try { + const scheduledAt = new Date(`${selectedDate}T${selectedTime}:00Z`).toISOString(); - localStorage.setItem(APPOINTMENTS_STORAGE_KEY, JSON.stringify(updatedAppointments)); + const newAppointmentData = { + patient_id: selectedPatient, + doctor_id: selectedDoctor, + scheduled_at: scheduledAt, + duration_minutes: parseInt(durationMinutes, 10), + appointment_type: appointmentType, + status: "requested", + chief_complaint: chiefComplaint || null, + patient_notes: patientNotes || null, + notes: internalNotes || null, + insurance_provider: insuranceProvider || null, + created_by: currentUserId, // 5. INCLUIR O ID DO USUÁRIO NO OBJETO + }; - toast.success("Consulta agendada com sucesso!"); - router.push("/secretary/appointments"); + console.log("Enviando dados do agendamento:", newAppointmentData); // Log para depuração + + await appointmentsService.create(newAppointmentData); + + toast.success("Consulta agendada com sucesso!"); + router.push("/secretary/appointments"); + } catch (error) { + console.error("Erro ao criar agendamento:", error); + toast.error("Ocorreu um erro ao agendar a consulta. Tente novamente."); + } }; return ( @@ -85,7 +117,7 @@ export default function ScheduleAppointment() {

Agendar Consulta

-

Escolha o paciente, médico, data e horário para a consulta

+

Preencha os detalhes para criar um novo agendamento

@@ -97,48 +129,14 @@ export default function ScheduleAppointment() {
+ {/* O restante do formulário permanece exatamente o mesmo */}
- +
-
- +
@@ -146,7 +144,6 @@ export default function ScheduleAppointment() { setSelectedDate(e.target.value)} min={new Date().toISOString().split("T")[0]} />
-
PresencialTelemedicina +
+
+ + setDurationMinutes(e.target.value)} placeholder="Ex: 30" /> +
+
- -