agendamento secretaria

This commit is contained in:
Gabriel Lira Figueira 2025-10-30 00:47:18 -03:00
parent b8937e1310
commit 2a015a7f63
3 changed files with 228 additions and 75 deletions

View File

@ -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<any[]>([]);
const [doctors, setDoctors] = useState<any[]>([]);
const [currentUserId, setCurrentUserId] = useState<string | null>(null); // 2. NOVO ESTADO PARA O ID DO USUÁRIO
const [currentUserId, setCurrentUserId] = useState<string | null>(null);
// Estados de loading e error para feedback visual e depuração
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(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 (
<SecretaryLayout>
<div className="space-y-6">
@ -129,20 +169,66 @@ export default function ScheduleAppointment() {
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-6">
{/* O restante do formulário permanece exatamente o mesmo */}
<div className="space-y-2">
<Label htmlFor="patient">Paciente</Label>
<Select value={selectedPatient} onValueChange={setSelectedPatient}><SelectTrigger><SelectValue placeholder="Selecione um paciente" /></SelectTrigger><SelectContent>{patients.map((p) => (<SelectItem key={p.id} value={p.id}>{p.full_name}</SelectItem>))}</SelectContent></Select>
</div>
<div className="space-y-2">
<Label htmlFor="doctor">Médico</Label>
<Select value={selectedDoctor} onValueChange={setSelectedDoctor}><SelectTrigger><SelectValue placeholder="Selecione um médico" /></SelectTrigger><SelectContent>{doctors.map((d) => (<SelectItem key={d.id} value={d.id}>{d.full_name} - {d.specialty}</SelectItem>))}</SelectContent></Select>
<Select value={selectedPatient} onValueChange={setSelectedPatient}>
<SelectTrigger>
<SelectValue placeholder="Selecione um paciente" />
</SelectTrigger>
<SelectContent>
{loading ? (
<SelectItem value="loading-patients" disabled>Carregando pacientes...</SelectItem>
) : error && patients.length === 0 ? ( // Se erro e não há pacientes
<SelectItem value="error-patients" disabled>Erro ao carregar pacientes</SelectItem>
) : patients.length === 0 ? ( // Se não há erro mas a lista está vazia
<SelectItem value="no-patients" disabled>Nenhum paciente encontrado</SelectItem>
) : (
patients.map((p) => (
<SelectItem key={p.id} value={p.id}>
{p.full_name}
</SelectItem>
))
)}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="doctor">Médico</Label>
<Select value={selectedDoctor} onValueChange={setSelectedDoctor}>
<SelectTrigger>
<SelectValue placeholder="Selecione um médico" />
</SelectTrigger>
<SelectContent>
{/* Lógica condicional para o estado de carregamento, erro ou lista vazia */}
{loading ? (
<SelectItem value="loading" disabled>Carregando médicos...</SelectItem>
) : error && doctors.length === 0 ? ( // Se há erro E a lista de médicos está vazia
<SelectItem value="error" disabled>Erro ao carregar médicos</SelectItem>
) : doctors.length === 0 ? ( // Se não há erro mas a lista está vazia
<SelectItem value="no-doctors" disabled>Nenhum médico encontrado</SelectItem>
) : (
doctors.map((d) => (
<SelectItem key={d.id} value={d.id}>
{d.full_name} - {d.specialty}
</SelectItem>
))
)}
</SelectContent>
</Select>
</div>
{/* O restante do formulário permanece o mesmo */}
<div className="grid md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="date">Data</Label>
<Input id="date" type="date" value={selectedDate} onChange={(e) => setSelectedDate(e.target.value)} min={new Date().toISOString().split("T")[0]} />
<Input
id="date"
type="date"
value={selectedDate}
onChange={(e) => setSelectedDate(e.target.value)}
min={new Date().toISOString().split("T")[0]} // Garante que a data mínima é hoje
/>
</div>
<div className="space-y-2">
<Label htmlFor="time">Horário</Label>
@ -164,40 +250,103 @@ export default function ScheduleAppointment() {
<div className="grid md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="appointmentType">Tipo de Consulta</Label>
<Select value={appointmentType} onValueChange={setAppointmentType}><SelectTrigger><SelectValue /></SelectTrigger><SelectContent><SelectItem value="presencial">Presencial</SelectItem><SelectItem value="telemedicina">Telemedicina</SelectItem></SelectContent></Select>
<Select value={appointmentType} onValueChange={setAppointmentType}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="presencial">Presencial</SelectItem>
<SelectItem value="telemedicina">Telemedicina</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="duration">Duração (minutos)</Label>
<Input id="duration" type="number" value={durationMinutes} onChange={(e) => setDurationMinutes(e.target.value)} placeholder="Ex: 30" />
<Input
id="duration"
type="number"
value={durationMinutes}
onChange={(e) => setDurationMinutes(e.target.value)}
placeholder="Ex: 30"
min="1" // Duração mínima
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="insurance">Convênio (opcional)</Label>
<Input id="insurance" placeholder="Nome do convênio do paciente" value={insuranceProvider} onChange={(e) => setInsuranceProvider(e.target.value)} />
<Input
id="insurance"
placeholder="Nome do convênio do paciente"
value={insuranceProvider}
onChange={(e) => setInsuranceProvider(e.target.value)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="chiefComplaint">Queixa Principal (opcional)</Label>
<Textarea id="chiefComplaint" placeholder="Descreva brevemente o motivo da consulta..." value={chiefComplaint} onChange={(e) => setChiefComplaint(e.target.value)} rows={2} />
<Textarea
id="chiefComplaint"
placeholder="Descreva brevemente o motivo da consulta..."
value={chiefComplaint}
onChange={(e) => setChiefComplaint(e.target.value)}
rows={2}
/>
</div>
<div className="space-y-2">
<Label htmlFor="patientNotes">Observações do Paciente (opcional)</Label>
<Textarea id="patientNotes" placeholder="Anotações relevantes informadas pelo paciente..." value={patientNotes} onChange={(e) => setPatientNotes(e.target.value)} rows={2} />
<Textarea
id="patientNotes"
placeholder="Anotações relevantes informadas pelo paciente..."
value={patientNotes}
onChange={(e) => setPatientNotes(e.target.value)}
rows={2}
/>
</div>
<div className="space-y-2">
<Label htmlFor="internalNotes">Observações Internas (opcional)</Label>
<Textarea id="internalNotes" placeholder="Anotações para a equipe da clínica..." value={internalNotes} onChange={(e) => setInternalNotes(e.target.value)} rows={2} />
<Textarea
id="internalNotes"
placeholder="Anotações para a equipe da clínica..."
value={internalNotes}
onChange={(e) => setInternalNotes(e.target.value)}
rows={2}
/>
</div>
<Button type="submit" className="w-full" disabled={!selectedPatient || !selectedDoctor || !selectedDate || !selectedTime || !currentUserId}>
Agendar Consulta
</Button>
<Button
type="submit"
className="w-full"
// Remova temporariamente '|| !currentUserId || loading' para testar
disabled={!selectedPatient || !selectedDoctor || !selectedDate || !selectedTime /* || !currentUserId || loading */}
>
Agendar Consulta
</Button>
</form>
</CardContent>
</Card>
</div>
<div className="space-y-6">
{/* Card de Resumo e Informações Importantes */}
{/* Card de Resumo e Informações Importantes (se houver, adicione aqui) */}
<Card>
<CardHeader>
<CardTitle>Informações Rápidas</CardTitle>
<CardDescription>Ajuda e status</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{loading && (
<p className="text-sm text-blue-600 flex items-center"><Clock className="mr-2 h-4 w-4" /> Carregando dados iniciais...</p>
)}
{error && (
<p className="text-sm text-red-600 flex items-center">
<User className="mr-2 h-4 w-4" /> {error}
</p>
)}
{!currentUserId && !loading && (
<p className="text-sm text-red-600 flex items-center"><User className="mr-2 h-4 w-4" /> Usuário não identificado. Recarregue a página.</p>
)}
<p className="text-sm text-gray-500 flex items-center">
<Calendar className="mr-2 h-4 w-4" /> Selecione uma data e horário válidos.
</p>
</CardContent>
</Card>
</div>
</div>
</div>

View File

@ -1,15 +1,14 @@
// SUBSTITUA TODO O CONTEÚDO DE services/api.mjs POR ESTE CÓDIGO
// Caminho: services/api.mjs
// As suas variáveis de ambiente já estão corretas no arquivo .env.local
const BASE_URL = process.env.NEXT_PUBLIC_SUPABASE_URL;
const API_KEY = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
/**
* Função de login que o seu formulário vai chamar.
* Ela autentica e salva o token no localStorage.
* Função de login que o seu formulário usa.
* Ela continua exatamente como era.
*/
let loginPromise = null;
export async function login() {
console.log("🔐 Iniciando login...");
const res = await fetch(`${BASE_URL}/auth/v1/token?grant_type=password`, {
@ -42,7 +41,7 @@ export async function login() {
}
/**
* Função de logout que o seu DashboardLayout vai chamar.
* Função de logout.
*/
async function logout() {
const token = localStorage.getItem("token");
@ -57,17 +56,16 @@ async function logout() {
},
});
} catch (error) {
console.error("Falha ao invalidar token no servidor (pode ser normal se o token já expirou):", error);
console.error("Falha ao invalidar token no servidor:", error);
} finally {
// Limpa os dados do cliente independentemente do resultado do servidor
localStorage.removeItem("token");
localStorage.removeItem("user_info");
}
}
/**
* Função genérica e centralizada para fazer requisições autenticadas.
* Ela pega o token do localStorage automaticamente.
* Função genérica para fazer requisições.
* Agora com a correção para respostas vazias.
*/
async function request(endpoint, options = {}) {
const token = typeof window !== 'undefined' ? localStorage.getItem("token") : null;
@ -75,7 +73,6 @@ async function request(endpoint, options = {}) {
const headers = {
"Content-Type": "application/json",
"apikey": API_KEY,
// Adiciona o cabeçalho de autorização apenas se o token existir
...(token && { "Authorization": `Bearer ${token}` }),
...options.headers,
};
@ -88,21 +85,23 @@ async function request(endpoint, options = {}) {
throw new Error(`Erro na API: ${errorBody.message || JSON.stringify(errorBody)}`);
}
// Se a resposta for 204 No Content (como em um DELETE), não tenta fazer o parse do JSON
if (response.status === 204) {
// --- CORREÇÃO 1: PARA O SUBMIT DO AGENDAMENTO ---
// Se a resposta for um sucesso de criação (201) ou sem conteúdo (204), não quebra.
if (response.status === 201 || response.status === 204) {
return null;
}
return response.json();
}
// Exportamos um objeto 'api' com os métodos que os componentes vão usar.
// Exportamos o objeto 'api' com os métodos que os componentes vão usar.
export const api = {
// --- CORREÇÃO 2: PARA CARREGAR O ID DO USUÁRIO ---
getSession: () => request('/auth/v1/user'),
get: (endpoint, options) => request(endpoint, { method: "GET", ...options }),
post: (endpoint, data, options) => request(endpoint, { method: "POST", body: JSON.stringify(data), ...options }),
patch: (endpoint, data, options) => request(endpoint, { method: "PATCH", body: JSON.stringify(data), ...options }),
delete: (endpoint, options) => request(endpoint, { method: "DELETE", ...options }),
logout: logout, // Exportando a função de logout
};
logout: logout,
};

View File

@ -1,26 +1,32 @@
// SUBSTITUA O OBJETO INTEIRO EM services/usersApi.mjs
import { api } from "./api.mjs";
export const usersService = {
// Função getMe corrigida para chamar a si mesma pelo nome
async getMe() {
const sessionData = await api.getSession();
if (!sessionData?.id) {
console.error("Sessão não encontrada ou usuário sem ID.", sessionData);
throw new Error("Usuário não autenticado.");
}
// Chamando a outra função do serviço pelo nome explícito
return usersService.full_data(sessionData.id);
},
async list_roles() {
// continua usando /rest/v1 normalmente
return await api.get(`/rest/v1/user_roles?select=id,user_id,role,created_at`);
},
async create_user(data) {
// continua usando a Edge Function corretamente
return await api.post(`/functions/v1/create-user-with-password
`, data);
return await api.post(`/functions/v1/create-user-with-password`, data);
},
// 🚀 Busca dados completos do usuário direto do banco
async full_data(user_id) {
if (!user_id) throw new Error("user_id é obrigatório");
// Busca o perfil
const [profile] = await api.get(`/rest/v1/profiles?id=eq.${user_id}`);
// Busca o papel (role)
const [role] = await api.get(`/rest/v1/user_roles?user_id=eq.${user_id}`);
// Busca as permissões se existirem em alguma tabela
const permissions = {
isAdmin: role?.role === "admin",
isManager: role?.role === "gestor",
@ -30,7 +36,6 @@ export const usersService = {
role?.role === "admin" || role?.role === "gestor" ? true : false,
};
// Monta o objeto no mesmo formato do endpoint `user-info`
return {
user: {
id: user_id,