From 2a015a7f63d25b4fc4d510f769ea414c29a61de0 Mon Sep 17 00:00:00 2001 From: Gabriel Lira Figueira Date: Thu, 30 Oct 2025 00:47:18 -0300 Subject: [PATCH] agendamento secretaria --- app/secretary/schedule/page.tsx | 245 +++++++++++++++++++++++++------- services/api.mjs | 35 +++-- services/usersApi.mjs | 23 +-- 3 files changed, 228 insertions(+), 75 deletions(-) diff --git a/app/secretary/schedule/page.tsx b/app/secretary/schedule/page.tsx index a932669..7eeb2c3 100644 --- a/app/secretary/schedule/page.tsx +++ b/app/secretary/schedule/page.tsx @@ -1,5 +1,4 @@ "use client"; - import type React from "react"; import { useState, useEffect } from "react"; import { useRouter } from "next/navigation"; @@ -10,18 +9,22 @@ import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Textarea } from "@/components/ui/textarea"; -import { Calendar, Clock, User } from "lucide-react"; +import { Calendar, Clock, User } from "lucide-react"; // Importações que você já tinha import { patientsService } from "@/services/patientsApi.mjs"; 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"; +import { usersService } from "@/services/usersApi.mjs"; +import { toast } from "sonner"; // Para notificações export default function ScheduleAppointment() { const router = useRouter(); const [patients, setPatients] = useState([]); const [doctors, setDoctors] = useState([]); - const [currentUserId, setCurrentUserId] = useState(null); // 2. NOVO ESTADO PARA O ID DO USUÁRIO + const [currentUserId, setCurrentUserId] = useState(null); + + // Estados de loading e error para feedback visual e depuração + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); // Estados do formulário const [selectedPatient, setSelectedPatient] = useState(""); @@ -40,39 +43,76 @@ export default function ScheduleAppointment() { "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) + // --- NOVO/ATUALIZADO useEffect COM LOGS PARA DEPURAR --- useEffect(() => { const fetchInitialData = async () => { - try { - // Busca tudo em paralelo para melhor performance - const [patientList, doctorList, currentUser] = await Promise.all([ - patientsService.list(), - doctorsService.list(), - usersService.summary_data() // 3. CHAMADA PARA BUSCAR O USUÁRIO - ]); + setLoading(true); + setError(null); // Limpa qualquer erro anterior ao iniciar uma nova busca - setPatients(patientList); - setDoctors(doctorList); + const results = await Promise.allSettled([ + patientsService.list(), + doctorsService.list(), + usersService.getMe() + ]); - 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."); - } + const [patientResult, doctorResult, userResult] = results; + let hasFetchError = false; // Flag para saber se houve algum erro geral - } catch (error) { - console.error("Falha ao buscar dados iniciais:", error); - toast.error("Não foi possível carregar os dados necessários para a página."); + // Checar pacientes + if (patientResult.status === 'fulfilled') { + setPatients(patientResult.value || []); + console.log("Pacientes carregados com sucesso:", patientResult.value); + } else { + console.error("ERRO AO CARREGAR PACIENTES:", patientResult.reason); + hasFetchError = true; + toast.error("Erro ao carregar lista de pacientes."); // Notificação para o usuário } + + // Checar médicos + if (doctorResult.status === 'fulfilled') { + setDoctors(doctorResult.value || []); + console.log("Médicos carregados com sucesso:", doctorResult.value); // <-- CRÍTICO PARA DEPURAR + } else { + console.error("ERRO AO CARREGAR MÉDICOS:", doctorResult.reason); + hasFetchError = true; + setError("Falha ao carregar médicos."); // Define o erro para ser exibido no dropdown + toast.error("Erro ao carregar lista de médicos."); // Notificação para o usuário + } + + // Checar usuário logado + if (userResult.status === 'fulfilled' && userResult.value?.user?.id) { + setCurrentUserId(userResult.value.user.id); + console.log("ID do usuário logado carregado:", userResult.value.user.id); + } else { + const reason = userResult.status === 'rejected' ? userResult.reason : "API não retornou um ID de usuário."; + console.error("ERRO AO CARREGAR USUÁRIO:", reason); + hasFetchError = true; + toast.error("Não foi possível identificar o usuário logado. Por favor, faça login novamente."); // Notificação + // Não definimos setError aqui, pois um erro no usuário não impede a renderização de médicos/pacientes + } + + // Se houve qualquer erro na busca, defina uma mensagem geral de erro se não houver uma mais específica. + if (hasFetchError && !error) { // Se 'error' já foi definido por um problema específico, mantenha-o. + setError("Alguns dados não puderam ser carregados. Verifique o console."); + } + + setLoading(false); // Finaliza o estado de carregamento + console.log("Estado de carregamento finalizado:", false); }; + fetchInitialData(); - }, []); + }, []); // O array de dependências vazio significa que ele roda apenas uma vez após a montagem inicial + + // --- LOGS PARA VERIFICAR OS ESTADOS ANTES DA RENDERIZAÇÃO --- + console.log("Estado 'loading' no render:", loading); + console.log("Estado 'error' no render:", error); + console.log("Conteúdo de 'doctors' no render:", doctors); + console.log("Número de médicos em 'doctors':", doctors.length); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); + console.log("Botão de submit clicado!"); // Log para confirmar que o clique funciona - // 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; @@ -97,21 +137,21 @@ export default function ScheduleAppointment() { patient_notes: patientNotes || null, notes: internalNotes || null, insurance_provider: insuranceProvider || null, - created_by: currentUserId, // 5. INCLUIR O ID DO USUÁRIO NO OBJETO + created_by: currentUserId, }; - console.log("Enviando dados do agendamento:", newAppointmentData); // Log para depuração + console.log("🚀 Enviando os seguintes dados para a API:", newAppointmentData); + // A chamada para a API de criaçã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."); + console.error("❌ Erro ao criar agendamento:", error); + toast.error("Ocorreu um erro ao agendar a consulta. Verifique o console."); } }; - return (
@@ -129,20 +169,66 @@ export default function ScheduleAppointment() {
- {/* O restante do formulário permanece exatamente o mesmo */}
- -
-
- - +
+
+ + +
+ + {/* O restante do formulário permanece o mesmo */}
- setSelectedDate(e.target.value)} min={new Date().toISOString().split("T")[0]} /> + setSelectedDate(e.target.value)} + min={new Date().toISOString().split("T")[0]} // Garante que a data mínima é hoje + />
@@ -164,40 +250,103 @@ export default function ScheduleAppointment() {
- +
- setDurationMinutes(e.target.value)} placeholder="Ex: 30" /> + setDurationMinutes(e.target.value)} + placeholder="Ex: 30" + min="1" // Duração mínima + />
- setInsuranceProvider(e.target.value)} /> + setInsuranceProvider(e.target.value)} + />
-