commit
93ea8709d6
@ -2,180 +2,131 @@
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import PatientLayout from "@/components/patient-layout";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Calendar, Clock, MapPin, Phone, User, X, CalendarDays } from "lucide-react";
|
||||
import { Calendar, Clock, CalendarDays, X } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
||||
import { patientsService } from "@/services/patientsApi.mjs";
|
||||
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||
import { usersService } from "@/services/usersApi.mjs";
|
||||
|
||||
const APPOINTMENTS_STORAGE_KEY = "clinic-appointments";
|
||||
|
||||
interface UserPermissions {
|
||||
isAdmin: boolean;
|
||||
isManager: boolean;
|
||||
isDoctor: boolean;
|
||||
isSecretary: boolean;
|
||||
isAdminOrManager: boolean;
|
||||
// Tipagem correta para o usuário
|
||||
interface UserProfile {
|
||||
id: string;
|
||||
full_name: string;
|
||||
email: string;
|
||||
phone?: string;
|
||||
avatar_url?: string;
|
||||
}
|
||||
|
||||
interface UserData {
|
||||
user: {
|
||||
id: string;
|
||||
email: string;
|
||||
email_confirmed_at: string | null;
|
||||
created_at: string | null;
|
||||
last_sign_in_at: string | null;
|
||||
};
|
||||
profile: {
|
||||
id: string;
|
||||
full_name: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
avatar_url: string | null;
|
||||
disabled: boolean;
|
||||
created_at: string | null;
|
||||
updated_at: string | null;
|
||||
};
|
||||
roles: string[];
|
||||
permissions: UserPermissions;
|
||||
interface User {
|
||||
user: {
|
||||
id: string;
|
||||
email: string;
|
||||
};
|
||||
profile: UserProfile;
|
||||
roles: string[];
|
||||
permissions?: any;
|
||||
}
|
||||
|
||||
export default function PatientAppointments() {
|
||||
const [appointments, setAppointments] = useState<any[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [selectedAppointment, setSelectedAppointment] = useState<any>(null);
|
||||
const [userData, setUserData] = useState<UserData>();
|
||||
interface Appointment {
|
||||
id: string;
|
||||
doctor_id: string;
|
||||
scheduled_at: string;
|
||||
status: string;
|
||||
doctorName?: string;
|
||||
}
|
||||
|
||||
// Modais
|
||||
const [rescheduleModal, setRescheduleModal] = useState(false);
|
||||
const [cancelModal, setCancelModal] = useState(false);
|
||||
export default function PatientAppointmentsPage() {
|
||||
const [appointments, setAppointments] = useState<Appointment[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [userData, setUserData] = useState<User | null>(null);
|
||||
|
||||
// Formulário de reagendamento/cancelamento
|
||||
const [rescheduleData, setRescheduleData] = useState({ date: "", time: "", reason: "" });
|
||||
const [cancelReason, setCancelReason] = useState("");
|
||||
// --- Busca o usuário logado ---
|
||||
const fetchUser = async () => {
|
||||
try {
|
||||
const user: User = await usersService.getMe();
|
||||
if (!user.roles.includes("patient") && !user.roles.includes("user")) {
|
||||
toast.error("Apenas pacientes podem visualizar suas consultas.");
|
||||
setIsLoading(false);
|
||||
return null;
|
||||
}
|
||||
setUserData(user);
|
||||
return user;
|
||||
} catch (err) {
|
||||
console.error("Erro ao buscar usuário logado:", err);
|
||||
toast.error("Não foi possível identificar o usuário logado.");
|
||||
setIsLoading(false);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const timeSlots = ["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"];
|
||||
// --- Busca consultas do paciente ---
|
||||
const fetchAppointments = async (patientId: string) => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const queryParams = `patient_id=eq.${patientId}&order=scheduled_at.desc`;
|
||||
const appointmentsList: Appointment[] = await appointmentsService.search_appointment(queryParams);
|
||||
|
||||
const fetchData = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const queryParams = "order=scheduled_at.desc";
|
||||
const appointmentList = await appointmentsService.search_appointment(queryParams);
|
||||
const patientList = await patientsService.list();
|
||||
const doctorList = await doctorsService.list();
|
||||
// Buscar nome do médico para cada consulta
|
||||
const appointmentsWithDoctor = await Promise.all(
|
||||
appointmentsList.map(async (apt) => {
|
||||
let doctorName = apt.doctor_id;
|
||||
if (apt.doctor_id) {
|
||||
try {
|
||||
const doctorInfo = await usersService.full_data(apt.doctor_id);
|
||||
doctorName = doctorInfo?.profile?.full_name || apt.doctor_id;
|
||||
} catch (err) {
|
||||
console.error("Erro ao buscar nome do médico:", err);
|
||||
}
|
||||
}
|
||||
return { ...apt, doctorName };
|
||||
})
|
||||
);
|
||||
|
||||
const user = await usersService.getMe();
|
||||
setUserData(user);
|
||||
setAppointments(appointmentsWithDoctor);
|
||||
} catch (err) {
|
||||
console.error("Erro ao carregar consultas:", err);
|
||||
toast.error("Não foi possível carregar suas consultas.");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const doctorMap = new Map(doctorList.map((d: any) => [d.id, d]));
|
||||
const patientMap = new Map(patientList.map((p: any) => [p.id, p]));
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
const user = await fetchUser();
|
||||
if (user?.user.id) {
|
||||
await fetchAppointments(user.user.id);
|
||||
}
|
||||
})();
|
||||
}, []);
|
||||
|
||||
console.log(appointmentList);
|
||||
const getStatusBadge = (status: string) => {
|
||||
switch (status) {
|
||||
case "requested":
|
||||
return <Badge className="bg-yellow-100 text-yellow-800">Solicitada</Badge>;
|
||||
case "confirmed":
|
||||
return <Badge className="bg-blue-100 text-blue-800">Confirmada</Badge>;
|
||||
case "checked_in":
|
||||
return <Badge className="bg-indigo-100 text-indigo-800">Check-in</Badge>;
|
||||
case "completed":
|
||||
return <Badge className="bg-green-100 text-green-800">Realizada</Badge>;
|
||||
case "cancelled":
|
||||
return <Badge className="bg-red-100 text-red-800">Cancelada</Badge>;
|
||||
default:
|
||||
return <Badge variant="secondary">{status}</Badge>;
|
||||
}
|
||||
};
|
||||
|
||||
// Filtra apenas as consultas do paciente logado
|
||||
const patientAppointments = appointmentList
|
||||
.filter((apt: any) => apt.patient_id === userData?.user.id)
|
||||
.map((apt: any) => ({
|
||||
...apt,
|
||||
doctor: doctorMap.get(apt.doctor_id) || { full_name: "Médico não encontrado", specialty: "N/A" },
|
||||
patient: patientMap.get(apt.patient_id) || { full_name: "Paciente não encontrado" },
|
||||
}));
|
||||
const handleReschedule = (apt: Appointment) => {
|
||||
toast.info(`Funcionalidade de reagendamento da consulta ${apt.id} ainda não implementada`);
|
||||
};
|
||||
|
||||
setAppointments(patientAppointments);
|
||||
} catch (error) {
|
||||
console.error("Erro ao carregar consultas:", error);
|
||||
toast.error("Não foi possível carregar suas consultas.");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
const getStatusBadge = (status: string) => {
|
||||
switch (status) {
|
||||
case "requested":
|
||||
return <Badge className="bg-yellow-100 text-yellow-800">Solicitada</Badge>;
|
||||
case "confirmed":
|
||||
return <Badge className="bg-blue-100 text-blue-800">Confirmada</Badge>;
|
||||
case "checked_in":
|
||||
return <Badge className="bg-indigo-100 text-indigo-800">Check-in</Badge>;
|
||||
case "completed":
|
||||
return <Badge className="bg-green-100 text-green-800">Realizada</Badge>;
|
||||
case "cancelled":
|
||||
return <Badge className="bg-red-100 text-red-800">Cancelada</Badge>;
|
||||
default:
|
||||
return <Badge variant="secondary">{status}</Badge>;
|
||||
}
|
||||
};
|
||||
|
||||
const handleReschedule = (appointment: any) => {
|
||||
setSelectedAppointment(appointment);
|
||||
setRescheduleData({ date: "", time: "", reason: "" });
|
||||
setRescheduleModal(true);
|
||||
};
|
||||
|
||||
const handleCancel = (appointment: any) => {
|
||||
setSelectedAppointment(appointment);
|
||||
setCancelReason("");
|
||||
setCancelModal(true);
|
||||
};
|
||||
|
||||
const confirmReschedule = async () => {
|
||||
if (!rescheduleData.date || !rescheduleData.time) {
|
||||
toast.error("Por favor, selecione uma nova data e horário.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const newScheduledAt = new Date(`${rescheduleData.date}T${rescheduleData.time}:00Z`).toISOString();
|
||||
|
||||
await appointmentsService.update(selectedAppointment.id, {
|
||||
scheduled_at: newScheduledAt,
|
||||
status: "requested",
|
||||
});
|
||||
|
||||
setAppointments((prev) => prev.map((apt) => (apt.id === selectedAppointment.id ? { ...apt, scheduled_at: newScheduledAt, status: "requested" } : apt)));
|
||||
|
||||
setRescheduleModal(false);
|
||||
toast.success("Consulta reagendada com sucesso!");
|
||||
} catch (error) {
|
||||
console.error("Erro ao reagendar consulta:", error);
|
||||
toast.error("Não foi possível reagendar a consulta.");
|
||||
}
|
||||
};
|
||||
|
||||
const confirmCancel = async () => {
|
||||
if (!cancelReason.trim() || cancelReason.trim().length < 10) {
|
||||
toast.error("Por favor, informe um motivo de cancelamento (mínimo 10 caracteres).");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await appointmentsService.update(selectedAppointment.id, {
|
||||
status: "cancelled",
|
||||
cancel_reason: cancelReason,
|
||||
});
|
||||
|
||||
setAppointments((prev) => prev.map((apt) => (apt.id === selectedAppointment.id ? { ...apt, status: "cancelled" } : apt)));
|
||||
|
||||
setCancelModal(false);
|
||||
toast.success("Consulta cancelada com sucesso!");
|
||||
} catch (error) {
|
||||
console.error("Erro ao cancelar consulta:", error);
|
||||
toast.error("Não foi possível cancelar a consulta.");
|
||||
}
|
||||
};
|
||||
const handleCancel = (apt: Appointment) => {
|
||||
toast.info(`Funcionalidade de cancelamento da consulta ${apt.id} ainda não implementada`);
|
||||
};
|
||||
|
||||
return (
|
||||
<PatientLayout>
|
||||
@ -187,144 +138,53 @@ export default function PatientAppointments() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6">
|
||||
{isLoading ? (
|
||||
<p>Carregando suas consultas...</p>
|
||||
) : appointments.length > 0 ? (
|
||||
appointments.map((appointment) => (
|
||||
<Card key={appointment.id}>
|
||||
<CardHeader>
|
||||
<div className="flex justify-between items-start">
|
||||
<div>
|
||||
<CardTitle className="text-lg">{appointment.doctor.full_name}</CardTitle>
|
||||
<CardDescription>{appointment.doctor.specialty}</CardDescription>
|
||||
</div>
|
||||
{getStatusBadge(appointment.status)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid md:grid-cols-2 gap-3">
|
||||
<div className="space-y-2 text-sm text-gray-700">
|
||||
<div className="flex items-center">
|
||||
<Calendar className="mr-2 h-4 w-4 text-gray-500" />
|
||||
{new Date(appointment.scheduled_at).toLocaleDateString("pt-BR", { timeZone: "UTC" })}
|
||||
</div>
|
||||
<div className="flex items-center">
|
||||
<Clock className="mr-2 h-4 w-4 text-gray-500" />
|
||||
{new Date(appointment.scheduled_at).toLocaleTimeString("pt-BR", {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
timeZone: "UTC",
|
||||
})}
|
||||
</div>
|
||||
<div className="flex items-center">
|
||||
<MapPin className="mr-2 h-4 w-4 text-gray-500" />
|
||||
{appointment.doctor.location || "Local a definir"}
|
||||
</div>
|
||||
<div className="flex items-center">
|
||||
<Phone className="mr-2 h-4 w-4 text-gray-500" />
|
||||
{appointment.doctor.phone || "N/A"}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{appointment.status !== "cancelled" && (
|
||||
<div className="flex gap-2 mt-4 pt-4 border-t">
|
||||
<Button variant="outline" size="sm" onClick={() => handleReschedule(appointment)}>
|
||||
<CalendarDays className="mr-2 h-4 w-4" />
|
||||
Reagendar
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" className="text-red-600 hover:text-red-700 hover:bg-red-50" onClick={() => handleCancel(appointment)}>
|
||||
<X className="mr-2 h-4 w-4" />
|
||||
Cancelar
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
))
|
||||
) : (
|
||||
<Card className="p-6 text-center">
|
||||
<CalendarDays className="mx-auto h-12 w-12 text-muted-foreground mb-4" />
|
||||
<CardTitle className="text-xl">Nenhuma Consulta Encontrada</CardTitle>
|
||||
<CardDescription className="mt-2">
|
||||
Você ainda não possui consultas agendadas. Use o menu "Agendar Consulta" para começar.
|
||||
</CardDescription>
|
||||
</Card>
|
||||
<div className="grid gap-6">
|
||||
{isLoading ? (
|
||||
<p>Carregando consultas...</p>
|
||||
) : appointments.length === 0 ? (
|
||||
<p className="text-gray-600">Você ainda não possui consultas agendadas.</p>
|
||||
) : (
|
||||
appointments.map((apt) => (
|
||||
<Card key={apt.id}>
|
||||
<CardHeader className="flex justify-between items-start">
|
||||
<div>
|
||||
<CardTitle className="text-lg">{apt.doctorName}</CardTitle>
|
||||
<CardDescription>Especialidade: N/A</CardDescription>
|
||||
</div>
|
||||
{getStatusBadge(apt.status)}
|
||||
</CardHeader>
|
||||
<CardContent className="grid md:grid-cols-2 gap-3 text-sm text-gray-700">
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center">
|
||||
<Calendar className="mr-2 h-4 w-4 text-gray-500" />
|
||||
{new Date(apt.scheduled_at).toLocaleDateString("pt-BR")}
|
||||
</div>
|
||||
<div className="flex items-center">
|
||||
<Clock className="mr-2 h-4 w-4 text-gray-500" />
|
||||
{new Date(apt.scheduled_at).toLocaleTimeString("pt-BR", {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2 mt-4 pt-4 border-t">
|
||||
{apt.status !== "cancelled" && (
|
||||
<>
|
||||
<Button variant="outline" size="sm" onClick={() => handleReschedule(apt)}>
|
||||
<CalendarDays className="mr-2 h-4 w-4" /> Reagendar
|
||||
</Button>
|
||||
<Button variant="destructive" size="sm" onClick={() => handleCancel(apt)}>
|
||||
<X className="mr-2 h-4 w-4" /> Cancelar
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* MODAL DE REAGENDAMENTO */}
|
||||
<Dialog open={rescheduleModal} onOpenChange={setRescheduleModal}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Reagendar Consulta</DialogTitle>
|
||||
<DialogDescription>
|
||||
Escolha uma nova data e horário para sua consulta com <strong>{selectedAppointment?.doctor?.full_name}</strong>.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="date">Nova Data</Label>
|
||||
<Input id="date" type="date" value={rescheduleData.date} onChange={(e) => setRescheduleData((prev) => ({ ...prev, date: e.target.value }))} min={new Date().toISOString().split("T")[0]} />
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="time">Novo Horário</Label>
|
||||
<Select value={rescheduleData.time} onValueChange={(value) => setRescheduleData((prev) => ({ ...prev, time: value }))}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Selecione um horário" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{timeSlots.map((time) => (
|
||||
<SelectItem key={time} value={time}>
|
||||
{time}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="reason">Motivo (opcional)</Label>
|
||||
<Textarea id="reason" placeholder="Explique brevemente o motivo do reagendamento..." value={rescheduleData.reason} onChange={(e) => setRescheduleData((prev) => ({ ...prev, reason: e.target.value }))} />
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setRescheduleModal(false)}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button onClick={confirmReschedule}>Confirmar</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* MODAL DE CANCELAMENTO */}
|
||||
<Dialog open={cancelModal} onOpenChange={setCancelModal}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Cancelar Consulta</DialogTitle>
|
||||
<DialogDescription>
|
||||
Deseja realmente cancelar sua consulta com <strong>{selectedAppointment?.doctor?.full_name}</strong>?
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="cancel-reason" className="text-sm font-medium">
|
||||
Motivo do Cancelamento <span className="text-red-500">*</span>
|
||||
</Label>
|
||||
<Textarea id="cancel-reason" placeholder="Informe o motivo do cancelamento (mínimo 10 caracteres)" value={cancelReason} onChange={(e) => setCancelReason(e.target.value)} className="min-h-[100px]" />
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setCancelModal(false)}>
|
||||
Voltar
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={confirmCancel}>
|
||||
Confirmar Cancelamento
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</PatientLayout>
|
||||
);
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</PatientLayout>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,293 +1,555 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { Calendar, Clock, User } from "lucide-react";
|
||||
import PatientLayout from "@/components/patient-layout";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
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 { usersService } from "services/usersApi.mjs";
|
||||
import { doctorsService } from "services/doctorsApi.mjs";
|
||||
import { appointmentsService } from "services/appointmentsApi.mjs";
|
||||
import { AvailabilityService } from "services/availabilityApi.mjs";
|
||||
import { Calendar as CalendarShadcn } from "@/components/ui/calendar";
|
||||
import { format, addDays } from "date-fns";
|
||||
|
||||
import { useState, useEffect, useCallback, useRef } from "react";
|
||||
import { Calendar, Clock, User, StickyNote } from "lucide-react";
|
||||
import PatientLayout from "@/components/patient-layout";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { toast } from "@/hooks/use-toast";
|
||||
|
||||
|
||||
interface Doctor {
|
||||
id: string;
|
||||
full_name: string;
|
||||
specialty: string;
|
||||
phone_mobile: string;
|
||||
id: string;
|
||||
full_name: string;
|
||||
specialty: string;
|
||||
}
|
||||
|
||||
const APPOINTMENTS_STORAGE_KEY = "clinic-appointments";
|
||||
interface Disponibilidade {
|
||||
id?: string;
|
||||
doctor_id?: string;
|
||||
weekday: string;
|
||||
start_time: string;
|
||||
end_time: string;
|
||||
slot_minutes?: number;
|
||||
}
|
||||
|
||||
export default function ScheduleAppointment() {
|
||||
const [selectedDoctor, setSelectedDoctor] = useState("");
|
||||
const [selectedDate, setSelectedDate] = useState("");
|
||||
const [selectedTime, setSelectedTime] = useState("");
|
||||
const [notes, setNotes] = useState("");
|
||||
const [selectedDoctor, setSelectedDoctor] = useState("");
|
||||
const [selectedDate, setSelectedDate] = useState("");
|
||||
const [selectedTime, setSelectedTime] = useState("");
|
||||
const [doctors, setDoctors] = useState<Doctor[]>([]);
|
||||
const [availableTimes, setAvailableTimes] = useState<string[]>([]);
|
||||
const [loadingSlots, setLoadingSlots] = useState(false);
|
||||
const [loadingDoctors, setLoadingDoctors] = useState(true);
|
||||
const [tipoConsulta, setTipoConsulta] = useState("presencial");
|
||||
const [duracao, setDuracao] = useState("30");
|
||||
const [notes, setNotes] = useState("");
|
||||
const [disponibilidades, setDisponibilidades] = useState<Disponibilidade[]>([]);
|
||||
const [availableWeekdays, setAvailableWeekdays] = useState<number[]>([]); // 1..7
|
||||
const [availabilityCounts, setAvailabilityCounts] = useState<Record<string, number>>({}); // "yyyy-MM-dd" -> count
|
||||
|
||||
// novos campos
|
||||
const [tipoConsulta, setTipoConsulta] = useState("presencial");
|
||||
const [duracao, setDuracao] = useState("30");
|
||||
const [convenio, setConvenio] = useState("");
|
||||
const [queixa, setQueixa] = useState("");
|
||||
const [obsPaciente, setObsPaciente] = useState("");
|
||||
const [obsInternas, setObsInternas] = useState("");
|
||||
const calendarRef = useRef<HTMLDivElement | null>(null);
|
||||
const tooltipRef = useRef<HTMLDivElement | null>(null);
|
||||
const [tooltip, setTooltip] = useState<{ x: number; y: number; text: string } | null>(null);
|
||||
|
||||
const [doctors, setDoctors] = useState<Doctor[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
// --- Helpers ---
|
||||
const getWeekdayNumber = (weekday: string) =>
|
||||
["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
|
||||
.indexOf(weekday.toLowerCase()) + 1; // monday=1 ... sunday=7
|
||||
|
||||
const fetchDoctors = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data: Doctor[] = await doctorsService.list();
|
||||
console.log(data);
|
||||
setDoctors(data || []);
|
||||
} catch (e: any) {
|
||||
console.error("Erro ao carregar lista de médicos:", e);
|
||||
setError("Não foi possível carregar a lista de médicos. Verifique a conexão com a API.");
|
||||
setDoctors([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
const getBrazilDate = (date: Date) =>
|
||||
new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), 12, 0, 0));
|
||||
|
||||
// --- Fetch doctors ---
|
||||
const fetchDoctors = useCallback(async () => {
|
||||
setLoadingDoctors(true);
|
||||
try {
|
||||
const data: Doctor[] = await doctorsService.list();
|
||||
setDoctors(data || []);
|
||||
} catch (e) {
|
||||
console.error("Erro ao buscar médicos:", e);
|
||||
toast({ title: "Erro", description: "Não foi possível carregar médicos." });
|
||||
} finally {
|
||||
setLoadingDoctors(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// --- Load disponibilidades details for selected doctor and compute weekdays ---
|
||||
const loadDoctorDisponibilidades = useCallback(async (doctorId?: string) => {
|
||||
if (!doctorId) {
|
||||
setDisponibilidades([]);
|
||||
setAvailableWeekdays([]);
|
||||
setAvailabilityCounts({});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const disp: Disponibilidade[] = await AvailabilityService.listById(doctorId);
|
||||
setDisponibilidades(disp || []);
|
||||
const nums = (disp || []).map((d) => getWeekdayNumber(d.weekday)).filter(Boolean);
|
||||
setAvailableWeekdays(Array.from(new Set(nums)));
|
||||
// compute counts preview for next 90 days
|
||||
await computeAvailabilityCountsPreview(doctorId, disp || []);
|
||||
} catch (e) {
|
||||
console.error("Erro disponibilidades:", e);
|
||||
setDisponibilidades([]);
|
||||
setAvailableWeekdays([]);
|
||||
setAvailabilityCounts({});
|
||||
}
|
||||
}, []);
|
||||
|
||||
// --- Compute availability counts for next 90 days (efficient) ---
|
||||
const computeAvailabilityCountsPreview = async (doctorId: string, dispList: Disponibilidade[]) => {
|
||||
try {
|
||||
const today = new Date();
|
||||
const start = format(today, "yyyy-MM-dd");
|
||||
const endDate = addDays(today, 90);
|
||||
const end = format(endDate, "yyyy-MM-dd");
|
||||
|
||||
// fetch appointments for this doctor for the whole window (one call)
|
||||
const appointments = await appointmentsService.search_appointment(
|
||||
`doctor_id=eq.${doctorId}&scheduled_at=gte.${start}T00:00:00Z&scheduled_at=lt.${end}T23:59:59Z`
|
||||
);
|
||||
|
||||
// group appointments by date
|
||||
const apptsByDate: Record<string, number> = {};
|
||||
(appointments || []).forEach((a: any) => {
|
||||
const d = String(a.scheduled_at).split("T")[0];
|
||||
apptsByDate[d] = (apptsByDate[d] || 0) + 1;
|
||||
});
|
||||
|
||||
const counts: Record<string, number> = {};
|
||||
for (let i = 0; i <= 90; i++) {
|
||||
const d = addDays(today, i);
|
||||
const key = format(d, "yyyy-MM-dd");
|
||||
const dayOfWeek = d.getDay() === 0 ? 7 : d.getDay(); // 1..7
|
||||
|
||||
// find all disponibilidades matching this weekday
|
||||
const dailyDisp = dispList.filter((p) => getWeekdayNumber(p.weekday) === dayOfWeek);
|
||||
|
||||
if (dailyDisp.length === 0) {
|
||||
counts[key] = 0;
|
||||
continue;
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchDoctors();
|
||||
}, [fetchDoctors]);
|
||||
// compute total possible slots for the day summing multiple intervals
|
||||
let possible = 0;
|
||||
dailyDisp.forEach((p) => {
|
||||
const [sh, sm] = p.start_time.split(":").map(Number);
|
||||
const [eh, em] = p.end_time.split(":").map(Number);
|
||||
const startMin = sh * 60 + sm;
|
||||
const endMin = eh * 60 + em;
|
||||
const slot = p.slot_minutes || 30;
|
||||
// inclusive handling: if start==end -> 1 slot? normally not, we do Math.floor((end - start)/slot) + 1 if end >= start
|
||||
if (endMin >= startMin) {
|
||||
possible += Math.floor((endMin - startMin) / slot) + 1;
|
||||
}
|
||||
});
|
||||
|
||||
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 occupied = apptsByDate[key] || 0;
|
||||
const free = Math.max(0, possible - occupied);
|
||||
counts[key] = free;
|
||||
}
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setAvailabilityCounts(counts);
|
||||
} catch (e) {
|
||||
console.error("Erro ao calcular contagens de disponibilidade:", e);
|
||||
setAvailabilityCounts({});
|
||||
}
|
||||
};
|
||||
|
||||
const doctorDetails = doctors.find((d) => d.id === selectedDoctor);
|
||||
const patientDetails = {
|
||||
id: "P001",
|
||||
full_name: "Paciente Exemplo Único",
|
||||
location: "Clínica Geral",
|
||||
phone: "(11) 98765-4321",
|
||||
};
|
||||
// --- When doctor changes ---
|
||||
useEffect(() => {
|
||||
fetchDoctors();
|
||||
}, [fetchDoctors]);
|
||||
|
||||
if (!patientDetails || !doctorDetails) {
|
||||
alert("Erro: Selecione o médico ou dados do paciente indisponíveis.");
|
||||
useEffect(() => {
|
||||
if (selectedDoctor) {
|
||||
loadDoctorDisponibilidades(selectedDoctor);
|
||||
} else {
|
||||
setDisponibilidades([]);
|
||||
setAvailableWeekdays([]);
|
||||
setAvailabilityCounts({});
|
||||
}
|
||||
setSelectedDate("");
|
||||
setSelectedTime("");
|
||||
setAvailableTimes([]);
|
||||
}, [selectedDoctor, loadDoctorDisponibilidades]);
|
||||
|
||||
// --- Fetch available times for date --- (same logic, but shows toast if none)
|
||||
const fetchAvailableSlots = useCallback(
|
||||
async (doctorId: string, date: string) => {
|
||||
if (!doctorId || !date) return;
|
||||
setLoadingSlots(true);
|
||||
setAvailableTimes([]);
|
||||
|
||||
try {
|
||||
const disponibilidades: Disponibilidade[] = await AvailabilityService.listById(doctorId);
|
||||
|
||||
const consultas = await appointmentsService.search_appointment(
|
||||
`doctor_id=eq.${doctorId}&scheduled_at=gte.${date}T00:00:00Z&scheduled_at=lt.${date}T23:59:59Z`
|
||||
);
|
||||
|
||||
const diaJS = new Date(date).getDay(); // 0..6
|
||||
const diaAPI = diaJS === 0 ? 7 : diaJS;
|
||||
|
||||
const disponibilidadeDia = disponibilidades.find(
|
||||
(d) => getWeekdayNumber(d.weekday) === diaAPI
|
||||
);
|
||||
|
||||
if (!disponibilidadeDia) {
|
||||
setAvailableTimes([]);
|
||||
toast({ title: "Nenhuma disponibilidade", description: "Nenhuma disponibilidade cadastrada para este dia." });
|
||||
setLoadingSlots(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const [startHour, startMin] = disponibilidadeDia.start_time.split(":").map(Number);
|
||||
const [endHour, endMin] = disponibilidadeDia.end_time.split(":").map(Number);
|
||||
const slot = disponibilidadeDia.slot_minutes || 30;
|
||||
|
||||
const horariosGerados: string[] = [];
|
||||
let atual = new Date(date);
|
||||
atual.setHours(startHour, startMin, 0, 0);
|
||||
|
||||
const end = new Date(date);
|
||||
end.setHours(endHour, endMin, 0, 0);
|
||||
|
||||
while (atual <= end) {
|
||||
horariosGerados.push(atual.toTimeString().slice(0, 5));
|
||||
atual = new Date(atual.getTime() + slot * 60000);
|
||||
}
|
||||
|
||||
const ocupados = (consultas || []).map((c: any) =>
|
||||
String(c.scheduled_at).split("T")[1]?.slice(0, 5)
|
||||
);
|
||||
|
||||
const livres = horariosGerados.filter((h) => !ocupados.includes(h));
|
||||
|
||||
if (livres.length === 0) {
|
||||
toast({ title: "Sem horários livres", description: "Todos os horários estão ocupados neste dia." });
|
||||
}
|
||||
|
||||
setAvailableTimes(livres);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
setAvailableTimes([]);
|
||||
toast({ title: "Erro", description: "Falha ao carregar horários." });
|
||||
} finally {
|
||||
setLoadingSlots(false);
|
||||
}
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
// run fetchAvailableSlots when date changes
|
||||
useEffect(() => {
|
||||
if (selectedDoctor && selectedDate) {
|
||||
fetchAvailableSlots(selectedDoctor, selectedDate);
|
||||
} else {
|
||||
setAvailableTimes([]);
|
||||
}
|
||||
setSelectedTime("");
|
||||
}, [selectedDoctor, selectedDate, fetchAvailableSlots]);
|
||||
|
||||
// --- Submit ---
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!selectedDoctor || !selectedDate || !selectedTime) {
|
||||
toast({ title: "Preencha os campos", description: "Selecione médico, data e horário." });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const doctor = doctors.find((d) => d.id === selectedDoctor);
|
||||
const paciente = await usersService.getMe();
|
||||
|
||||
const body = {
|
||||
doctor_id: doctor?.id,
|
||||
patient_id: paciente.user.id,
|
||||
scheduled_at: `${selectedDate}T${selectedTime}:00`, // saving as local-ish string (you chose UTC elsewhere)
|
||||
duration_minutes: Number(duracao),
|
||||
notes,
|
||||
appointment_type: tipoConsulta,
|
||||
};
|
||||
|
||||
await appointmentsService.create(body);
|
||||
toast({ title: "Agendado", description: "Consulta agendada com sucesso." });
|
||||
|
||||
// reset
|
||||
setSelectedDoctor("");
|
||||
setSelectedDate("");
|
||||
setSelectedTime("");
|
||||
setAvailableTimes([]);
|
||||
setNotes("");
|
||||
// refresh counts
|
||||
if (selectedDoctor) computeAvailabilityCountsPreview(selectedDoctor, disponibilidades);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
toast({ title: "Erro", description: "Falha ao agendar consulta." });
|
||||
}
|
||||
};
|
||||
|
||||
// --- Calendar tooltip via event delegation ---
|
||||
useEffect(() => {
|
||||
const cont = calendarRef.current;
|
||||
if (!cont) return;
|
||||
|
||||
const onMove = (ev: MouseEvent) => {
|
||||
const target = ev.target as HTMLElement | null;
|
||||
if (!target) return;
|
||||
// find closest button that likely is a day cell
|
||||
const btn = target.closest("button");
|
||||
if (!btn) {
|
||||
setTooltip(null);
|
||||
return;
|
||||
}
|
||||
// many calendar implementations put the date in aria-label, e.g. "November 13, 2025"
|
||||
const aria = btn.getAttribute("aria-label") || btn.textContent || "";
|
||||
// try to parse date from aria-label: new Date(aria) works for many locales
|
||||
const parsed = new Date(aria);
|
||||
if (isNaN(parsed.getTime())) {
|
||||
// sometimes aria-label is like "13" (just day) - try data-day attribute
|
||||
const dataDay = btn.getAttribute("data-day");
|
||||
if (dataDay) {
|
||||
// try parse yyyy-mm-dd
|
||||
const pd = new Date(dataDay);
|
||||
if (!isNaN(pd.getTime())) {
|
||||
const key = format(pd, "yyyy-MM-dd");
|
||||
const count = availabilityCounts[key] ?? 0;
|
||||
setTooltip({
|
||||
x: ev.pageX + 10,
|
||||
y: ev.pageY + 10,
|
||||
text: `${count} horário${count !== 1 ? "s" : ""} disponíveis`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const newAppointment = {
|
||||
id: new Date().getTime(),
|
||||
patientName: patientDetails.full_name,
|
||||
doctor: doctorDetails.full_name,
|
||||
specialty: doctorDetails.specialty,
|
||||
date: selectedDate,
|
||||
time: selectedTime,
|
||||
tipoConsulta,
|
||||
duracao,
|
||||
convenio,
|
||||
queixa,
|
||||
obsPaciente,
|
||||
obsInternas,
|
||||
notes,
|
||||
status: "agendada",
|
||||
phone: patientDetails.phone,
|
||||
};
|
||||
|
||||
const storedAppointmentsRaw = localStorage.getItem(APPOINTMENTS_STORAGE_KEY);
|
||||
const currentAppointments = storedAppointmentsRaw ? JSON.parse(storedAppointmentsRaw) : [];
|
||||
const updatedAppointments = [...currentAppointments, newAppointment];
|
||||
localStorage.setItem(APPOINTMENTS_STORAGE_KEY, JSON.stringify(updatedAppointments));
|
||||
|
||||
alert(`Consulta com ${doctorDetails.full_name} agendada com sucesso!`);
|
||||
|
||||
// resetar campos
|
||||
setSelectedDoctor("");
|
||||
setSelectedDate("");
|
||||
setSelectedTime("");
|
||||
setNotes("");
|
||||
setTipoConsulta("presencial");
|
||||
setDuracao("30");
|
||||
setConvenio("");
|
||||
setQueixa("");
|
||||
setObsPaciente("");
|
||||
setObsInternas("");
|
||||
setTooltip(null);
|
||||
return;
|
||||
}
|
||||
// parsed is valid - convert to yyyy-MM-dd
|
||||
const key = format(getBrazilDate(parsed), "yyyy-MM-dd");
|
||||
const count = availabilityCounts[key] ?? 0;
|
||||
setTooltip({
|
||||
x: ev.pageX + 10,
|
||||
y: ev.pageY + 10,
|
||||
text: `${count} horário${count !== 1 ? "s" : ""} disponíveis`,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<PatientLayout>
|
||||
<div className="space-y-6">
|
||||
const onLeave = () => setTooltip(null);
|
||||
|
||||
cont.addEventListener("mousemove", onMove);
|
||||
cont.addEventListener("mouseleave", onLeave);
|
||||
|
||||
return () => {
|
||||
cont.removeEventListener("mousemove", onMove);
|
||||
cont.removeEventListener("mouseleave", onLeave);
|
||||
};
|
||||
}, [availabilityCounts]);
|
||||
|
||||
|
||||
return (
|
||||
<PatientLayout>
|
||||
<div className="max-w-6xl mx-auto space-y-4 px-4">
|
||||
<h1 className="text-2xl font-semibold">Agendar Consulta</h1>
|
||||
|
||||
<Card className="border rounded-xl shadow-sm">
|
||||
<CardHeader>
|
||||
<CardTitle>Dados da Consulta</CardTitle>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="grid grid-cols-1 lg:grid-cols-2 gap-6 w-full">
|
||||
{/* LEFT */}
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">Agendar Consulta</h1>
|
||||
<p className="text-gray-600">Escolha o médico, data e horário para sua consulta</p>
|
||||
<Label className="text-sm">Médico</Label>
|
||||
<Select value={selectedDoctor} onValueChange={setSelectedDoctor}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Selecione o médico">
|
||||
{selectedDoctor && doctors.find(d => d.id === selectedDoctor)?.full_name}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{loadingDoctors ? (
|
||||
<SelectItem value="loading" disabled>Carregando...</SelectItem>
|
||||
) : (
|
||||
doctors.map((d) => (
|
||||
<SelectItem key={d.id} value={d.id}>
|
||||
{d.full_name} — {d.specialty}
|
||||
</SelectItem>
|
||||
))
|
||||
)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="grid lg:grid-cols-3 gap-6">
|
||||
<div className="lg:col-span-2">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Dados da Consulta</CardTitle>
|
||||
<CardDescription>Preencha as informações para agendar sua consulta</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
{/* Médico */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="doctor">Médico</Label>
|
||||
<Select value={selectedDoctor} onValueChange={setSelectedDoctor} disabled={loading}>
|
||||
<SelectTrigger id="doctor">
|
||||
<SelectValue placeholder="Selecione um médico" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{loading ? (
|
||||
<SelectItem value="loading" disabled>
|
||||
Carregando médicos...
|
||||
</SelectItem>
|
||||
) : error ? (
|
||||
<SelectItem value="error" disabled>
|
||||
Erro ao carregar
|
||||
</SelectItem>
|
||||
) : (
|
||||
doctors.map((doctor) => (
|
||||
<SelectItem key={doctor.id} value={doctor.id}>
|
||||
{doctor.full_name} - {doctor.specialty}
|
||||
</SelectItem>
|
||||
))
|
||||
)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-sm">Data</Label>
|
||||
<div ref={calendarRef} className="rounded-lg border p-2">
|
||||
<CalendarShadcn
|
||||
mode="single"
|
||||
disabled={!selectedDoctor}
|
||||
selected={selectedDate ? new Date(selectedDate + "T12:00:00") : undefined}
|
||||
onSelect={(date) => {
|
||||
if (!date) return;
|
||||
const fixedDate = new Date(date.getTime() + 12 * 60 * 60 * 1000);
|
||||
const formatted = format(fixedDate, "yyyy-MM-dd");
|
||||
setSelectedDate(formatted);
|
||||
}}
|
||||
className="rounded-md border shadow-sm p-2"
|
||||
modifiers={{ selected: selectedDate ? new Date(selectedDate + 'T12:00:00') : undefined }}
|
||||
modifiersClassNames={{
|
||||
selected:
|
||||
"bg-blue-600 text-white hover:bg-blue-700 rounded-md",
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Data e horário */}
|
||||
<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]} />
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="time">Horário</Label>
|
||||
<Select value={selectedTime} onValueChange={setSelectedTime}>
|
||||
<SelectTrigger id="time">
|
||||
<SelectValue placeholder="Selecione um horário" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{availableTimes.map((time) => (
|
||||
<SelectItem key={time} value={time}>
|
||||
{time}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
{/* Tipo e Duração */}
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="tipoConsulta">Tipo de Consulta</Label>
|
||||
<Select value={tipoConsulta} onValueChange={setTipoConsulta}>
|
||||
<SelectTrigger id="tipoConsulta">
|
||||
<SelectValue placeholder="Selecione o tipo" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="presencial">Presencial</SelectItem>
|
||||
<SelectItem value="online">Telemedicina</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="duracao">Duração (minutos)</Label>
|
||||
<Input id="duracao" type="number" min={10} max={120} value={duracao} onChange={(e) => setDuracao(e.target.value)} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Convênio */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="convenio">Convênio (opcional)</Label>
|
||||
<Input id="convenio" placeholder="Nome do convênio do paciente" value={convenio} onChange={(e) => setConvenio(e.target.value)} />
|
||||
</div>
|
||||
|
||||
{/* Queixa Principal */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="queixa">Queixa Principal (opcional)</Label>
|
||||
<Textarea id="queixa" placeholder="Descreva brevemente o motivo da consulta..." value={queixa} onChange={(e) => setQueixa(e.target.value)} />
|
||||
</div>
|
||||
|
||||
{/* Observações do Paciente */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="obsPaciente">Observações do Paciente (opcional)</Label>
|
||||
<Textarea id="obsPaciente" placeholder="Anotações relevantes informadas pelo paciente..." value={obsPaciente} onChange={(e) => setObsPaciente(e.target.value)} />
|
||||
</div>
|
||||
|
||||
{/* Observações Internas */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="obsInternas">Observações Internas (opcional)</Label>
|
||||
<Textarea id="obsInternas" placeholder="Anotações para a equipe da clínica..." value={obsInternas} onChange={(e) => setObsInternas(e.target.value)} />
|
||||
</div>
|
||||
|
||||
{/* Observações gerais */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="notes">Observações gerais (opcional)</Label>
|
||||
<Textarea id="notes" placeholder="Descreva brevemente o motivo da consulta ou observações importantes" value={notes} onChange={(e) => setNotes(e.target.value)} rows={3} />
|
||||
</div>
|
||||
|
||||
{/* Botão */}
|
||||
<Button type="submit" className="w-full" disabled={!selectedDoctor || !selectedDate || !selectedTime}>
|
||||
Agendar Consulta
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Resumo */}
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center">
|
||||
<Calendar className="mr-2 h-5 w-5" />
|
||||
Resumo
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{selectedDoctor && (
|
||||
<div className="flex items-center space-x-2">
|
||||
<User className="h-4 w-4 text-gray-500" />
|
||||
<span className="text-sm">{doctors.find((d) => d.id === selectedDoctor)?.full_name}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selectedDate && (
|
||||
<div className="flex items-center space-x-2">
|
||||
<Calendar className="h-4 w-4 text-gray-500" />
|
||||
<span className="text-sm">{new Date(selectedDate).toLocaleDateString("pt-BR")}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selectedTime && (
|
||||
<div className="flex items-center space-x-2">
|
||||
<Clock className="h-4 w-4 text-gray-500" />
|
||||
<span className="text-sm">{selectedTime}</span>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Informações Importantes</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="text-sm text-gray-600 space-y-2">
|
||||
<p>• Chegue com 15 minutos de antecedência</p>
|
||||
<p>• Traga documento com foto</p>
|
||||
<p>• Traga carteirinha do convênio</p>
|
||||
<p>• Traga exames anteriores, se houver</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-sm">Observações</Label>
|
||||
<Textarea
|
||||
placeholder="Instruções para o médico..."
|
||||
value={notes}
|
||||
onChange={(e) => setNotes(e.target.value)}
|
||||
className="mt-2"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</PatientLayout>
|
||||
);
|
||||
</div>
|
||||
|
||||
{/* RIGHT */}
|
||||
<div className="space-y-3">
|
||||
<Card className="shadow-md rounded-xl bg-blue-50 border border-blue-200">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-blue-700">Resumo</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 text-gray-900 text-sm">
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<User className="h-4 w-4 text-blue-600" />
|
||||
<div className="text-xs">
|
||||
{selectedDoctor ? (
|
||||
<div className="font-medium">
|
||||
{doctors.find((d) => d.id === selectedDoctor)?.full_name}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-gray-500">Médico</div>
|
||||
)}
|
||||
<div className="text-xs text-gray-500">
|
||||
{selectedDoctor ? doctors.find(d => d.id === selectedDoctor)?.specialty : ""}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">{tipoConsulta} • {duracao} min</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Calendar className="h-4 w-4 text-blue-600" />
|
||||
<div>
|
||||
{selectedDate ? (
|
||||
<div className="font-medium">{selectedDate.split("-").reverse().join("/")}</div>
|
||||
) : (
|
||||
<div className="text-gray-500">Data</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">—</div>
|
||||
</div>
|
||||
|
||||
{/* Horário */}
|
||||
<div className="space-y-2">
|
||||
<Label>Horário</Label>
|
||||
<Select onValueChange={setSelectedTime} disabled={
|
||||
loadingSlots || availableTimes.length === 0
|
||||
} >
|
||||
<SelectTrigger> <SelectValue placeholder={
|
||||
loadingSlots ? "Carregando horários..." : availableTimes.length === 0 ? "Nenhum horário disponível" : "Selecione o horário"
|
||||
} />
|
||||
</SelectTrigger>
|
||||
<SelectContent> {
|
||||
availableTimes.map((h) => ( <SelectItem key={h} value={h}> {h} </SelectItem> ))
|
||||
} </SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{notes && (
|
||||
<div className="flex items-start gap-2 text-sm">
|
||||
<StickyNote className="h-4 w-4" />
|
||||
<div className="italic text-gray-700">{notes}</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full md:w-auto px-4 py-1.5 text-sm bg-blue-600 text-white hover:bg-blue-700"
|
||||
disabled={!selectedDoctor || !selectedDate || !selectedTime}
|
||||
>
|
||||
Agendar
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setSelectedDoctor("");
|
||||
setSelectedDate("");
|
||||
setSelectedTime("");
|
||||
setAvailableTimes([]);
|
||||
setNotes("");
|
||||
}}
|
||||
className="px-3"
|
||||
>
|
||||
Limpar
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Tooltip element */}
|
||||
{tooltip && (
|
||||
<div
|
||||
ref={tooltipRef}
|
||||
style={{
|
||||
position: "absolute",
|
||||
left: tooltip.x,
|
||||
top: tooltip.y,
|
||||
zIndex: 60,
|
||||
background: "rgba(0,0,0,0.85)",
|
||||
color: "white",
|
||||
padding: "6px 8px",
|
||||
borderRadius: 6,
|
||||
fontSize: 12,
|
||||
}}
|
||||
>
|
||||
{tooltip.text}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</PatientLayout>
|
||||
);
|
||||
}
|
||||
|
||||
@ -61,7 +61,7 @@ export function LoginForm({ children }: LoginFormProps) {
|
||||
case "secretary":
|
||||
redirectPath = "/secretary/pacientes";
|
||||
break;
|
||||
case "paciente":
|
||||
case "patient":
|
||||
redirectPath = "/patient/dashboard";
|
||||
break;
|
||||
case "finance":
|
||||
|
||||
@ -44,6 +44,7 @@ interface DoctorData {
|
||||
specialty: string;
|
||||
department: string;
|
||||
permissions: object;
|
||||
role: string
|
||||
}
|
||||
|
||||
interface PatientLayoutProps {
|
||||
@ -79,6 +80,7 @@ export default function DoctorLayout({ children }: PatientLayoutProps) {
|
||||
crm: "",
|
||||
department: "",
|
||||
permissions: {},
|
||||
role: userInfo.role
|
||||
});
|
||||
} else {
|
||||
// Se não encontrar, aí sim redireciona.
|
||||
@ -145,6 +147,12 @@ export default function DoctorLayout({ children }: PatientLayoutProps) {
|
||||
label: "Consultas",
|
||||
// Botão para página de consultas marcadas do médico atual
|
||||
},
|
||||
{
|
||||
href: "/doctor/medicos/editorlaudo",
|
||||
icon: Clock,
|
||||
label: "Editor de Laudo",
|
||||
// Botão para página do editor de laudo
|
||||
},
|
||||
{
|
||||
href: "/doctor/medicos",
|
||||
icon: User,
|
||||
@ -291,6 +299,7 @@ export default function DoctorLayout({ children }: PatientLayoutProps) {
|
||||
.split(" ")
|
||||
.map((n) => n[0])
|
||||
.join("")}
|
||||
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex-1 min-w-0">
|
||||
|
||||
@ -33,9 +33,11 @@ export async function login(email, senha) {
|
||||
const data = await res.json();
|
||||
console.log("✅ Login bem-sucedido:", data);
|
||||
|
||||
if (typeof window !== "undefined" && data.access_token) {
|
||||
if (typeof window !== "undefined" && data.access_token) {
|
||||
localStorage.setItem("token", data.access_token);
|
||||
}
|
||||
localStorage.setItem("user_info", JSON.stringify(data.user));
|
||||
}
|
||||
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
@ -1,5 +1,8 @@
|
||||
import { api } from "./api.mjs";
|
||||
|
||||
|
||||
|
||||
|
||||
export const appointmentsService = {
|
||||
/**
|
||||
* Busca por horários disponíveis para agendamento.
|
||||
|
||||
@ -6,4 +6,14 @@ export const AvailabilityService = {
|
||||
create: (data) => api.post("/rest/v1/doctor_availability", data),
|
||||
update: (id, data) => api.patch(`/rest/v1/doctor_availability?id=eq.${id}`, data),
|
||||
delete: (id) => api.delete(`/rest/v1/doctor_availability?id=eq.${id}`),
|
||||
|
||||
};
|
||||
export async function getDisponibilidadeByMedico(idMedico) {
|
||||
try {
|
||||
const response = await api.get(`/disponibilidade/${idMedico}`);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error("Erro ao buscar disponibilidade do médico:", error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user