forked from RiseUP/riseup-squad21
agendamento dos pacientes
This commit is contained in:
parent
55125f1c44
commit
b791186640
@ -1,285 +1,340 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import Link from "next/link";
|
|
||||||
import { toast } from "sonner";
|
|
||||||
import { useAppointments, Appointment } from "../../context/AppointmentsContext";
|
|
||||||
|
|
||||||
// Componentes de UI e Ícones
|
|
||||||
import PatientLayout from "@/components/patient-layout";
|
import PatientLayout from "@/components/patient-layout";
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogClose } from "@/components/ui/dialog";
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import { Textarea } from "@/components/ui/textarea";
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
import { Calendar, Clock, MapPin, Phone, CalendarDays, X, Trash2 } from "lucide-react";
|
import { Calendar, Clock, MapPin, Phone, User, X, CalendarDays } from "lucide-react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
|
||||||
export default function PatientAppointmentsPage() {
|
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
||||||
const { appointments, updateAppointment, deleteAppointment } = useAppointments();
|
import { patientsService } from "@/services/patientsApi.mjs";
|
||||||
|
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||||
|
|
||||||
// Estados para controlar os modais e os dados do formulário
|
const APPOINTMENTS_STORAGE_KEY = "clinic-appointments";
|
||||||
const [isRescheduleModalOpen, setRescheduleModalOpen] = useState(false);
|
|
||||||
const [isCancelModalOpen, setCancelModalOpen] = useState(false);
|
|
||||||
const [selectedAppointment, setSelectedAppointment] = useState<Appointment | null>(null);
|
|
||||||
|
|
||||||
|
// Simulação do paciente logado
|
||||||
|
const LOGGED_PATIENT_ID = "P001";
|
||||||
|
|
||||||
|
export default function PatientAppointments() {
|
||||||
|
const [appointments, setAppointments] = useState<any[]>([]);
|
||||||
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
|
const [selectedAppointment, setSelectedAppointment] = useState<any>(null);
|
||||||
|
|
||||||
|
// Modais
|
||||||
|
const [rescheduleModal, setRescheduleModal] = useState(false);
|
||||||
|
const [cancelModal, setCancelModal] = useState(false);
|
||||||
|
|
||||||
|
// Formulário de reagendamento/cancelamento
|
||||||
const [rescheduleData, setRescheduleData] = useState({ date: "", time: "", reason: "" });
|
const [rescheduleData, setRescheduleData] = useState({ date: "", time: "", reason: "" });
|
||||||
const [cancelReason, setCancelReason] = useState("");
|
const [cancelReason, setCancelReason] = useState("");
|
||||||
|
|
||||||
// --- MANIPULADORES DE EVENTOS ---
|
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",
|
||||||
|
];
|
||||||
|
|
||||||
const handleRescheduleClick = (appointment: Appointment) => {
|
const fetchData = async () => {
|
||||||
setSelectedAppointment(appointment);
|
setIsLoading(true);
|
||||||
// Preenche o formulário com os dados atuais da consulta
|
try {
|
||||||
setRescheduleData({ date: appointment.date, time: appointment.time, reason: appointment.observations || "" });
|
const [appointmentList, patientList, doctorList] = await Promise.all([
|
||||||
setRescheduleModalOpen(true);
|
appointmentsService.list(),
|
||||||
};
|
patientsService.list(),
|
||||||
|
doctorsService.list(),
|
||||||
|
]);
|
||||||
|
|
||||||
const handleCancelClick = (appointment: Appointment) => {
|
const doctorMap = new Map(doctorList.map((d: any) => [d.id, d]));
|
||||||
setSelectedAppointment(appointment);
|
const patientMap = new Map(patientList.map((p: any) => [p.id, p]));
|
||||||
setCancelReason(""); // Limpa o motivo ao abrir
|
|
||||||
setCancelModalOpen(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
const confirmReschedule = () => {
|
// Filtra apenas as consultas do paciente logado
|
||||||
if (!rescheduleData.date || !rescheduleData.time) {
|
const patientAppointments = appointmentList
|
||||||
toast.error("Por favor, selecione uma nova data e horário");
|
.filter((apt: any) => apt.patient_id === LOGGED_PATIENT_ID)
|
||||||
return;
|
.map((apt: any) => ({
|
||||||
}
|
...apt,
|
||||||
if (selectedAppointment) {
|
doctor: doctorMap.get(apt.doctor_id) || { full_name: "Médico não encontrado", specialty: "N/A" },
|
||||||
updateAppointment(selectedAppointment.id, {
|
patient: patientMap.get(apt.patient_id) || { full_name: "Paciente não encontrado" },
|
||||||
date: rescheduleData.date,
|
}));
|
||||||
time: rescheduleData.time,
|
|
||||||
observations: rescheduleData.reason, // Atualiza as observações com o motivo
|
setAppointments(patientAppointments);
|
||||||
});
|
} catch (error) {
|
||||||
toast.success("Consulta reagendada com sucesso!");
|
console.error("Erro ao carregar consultas:", error);
|
||||||
setRescheduleModalOpen(false);
|
toast.error("Não foi possível carregar suas consultas.");
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const confirmCancel = () => {
|
useEffect(() => {
|
||||||
if (cancelReason.trim().length < 10) {
|
fetchData();
|
||||||
toast.error("Por favor, forneça um motivo com pelo menos 10 caracteres.");
|
}, []);
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (selectedAppointment) {
|
|
||||||
// Apenas atualiza o status e adiciona o motivo do cancelamento nas observações
|
|
||||||
updateAppointment(selectedAppointment.id, {
|
|
||||||
status: "Cancelada",
|
|
||||||
observations: `Motivo do cancelamento: ${cancelReason}`
|
|
||||||
});
|
|
||||||
toast.success("Consulta cancelada com sucesso!");
|
|
||||||
setCancelModalOpen(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleDeleteClick = (appointmentId: string) => {
|
const getStatusBadge = (status: string) => {
|
||||||
if (window.confirm("Tem certeza que deseja excluir permanentemente esta consulta? Esta ação não pode ser desfeita.")) {
|
|
||||||
deleteAppointment(appointmentId);
|
|
||||||
toast.success("Consulta excluída do histórico.");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// --- LÓGICA AUXILIAR ---
|
|
||||||
|
|
||||||
const getStatusBadge = (status: Appointment['status']) => {
|
|
||||||
switch (status) {
|
switch (status) {
|
||||||
case "Agendada": return <Badge className="bg-blue-100 text-blue-800 font-medium">Agendada</Badge>;
|
case "requested":
|
||||||
case "Realizada": return <Badge className="bg-green-100 text-green-800 font-medium">Realizada</Badge>;
|
return <Badge className="bg-yellow-100 text-yellow-800">Solicitada</Badge>;
|
||||||
case "Cancelada": return <Badge className="bg-red-100 text-red-800 font-medium">Cancelada</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 timeSlots = ["08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "14:00", "14:30", "15:00", "15:30"];
|
const handleReschedule = (appointment: any) => {
|
||||||
const today = new Date();
|
setSelectedAppointment(appointment);
|
||||||
today.setHours(0, 0, 0, 0); // Zera o horário para comparar apenas o dia
|
setRescheduleData({ date: "", time: "", reason: "" });
|
||||||
|
setRescheduleModal(true);
|
||||||
|
};
|
||||||
|
|
||||||
// ETAPA 1: ORDENAÇÃO DAS CONSULTAS
|
const handleCancel = (appointment: any) => {
|
||||||
// Cria uma cópia do array e o ordena
|
setSelectedAppointment(appointment);
|
||||||
const sortedAppointments = [...appointments].sort((a, b) => {
|
setCancelReason("");
|
||||||
const statusWeight = { 'Agendada': 1, 'Realizada': 2, 'Cancelada': 3 };
|
setCancelModal(true);
|
||||||
|
};
|
||||||
|
|
||||||
// Primeiro, ordena por status (Agendada vem primeiro)
|
const confirmReschedule = async () => {
|
||||||
if (statusWeight[a.status] !== statusWeight[b.status]) {
|
if (!rescheduleData.date || !rescheduleData.time) {
|
||||||
return statusWeight[a.status] - statusWeight[b.status];
|
toast.error("Por favor, selecione uma nova data e horário.");
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
try {
|
||||||
|
const newScheduledAt = new Date(`${rescheduleData.date}T${rescheduleData.time}:00Z`).toISOString();
|
||||||
|
|
||||||
// Se o status for o mesmo, ordena por data (mais recente/futura no topo)
|
await appointmentsService.update(selectedAppointment.id, {
|
||||||
return new Date(b.date).getTime() - new Date(a.date).getTime();
|
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.");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PatientLayout>
|
<PatientLayout>
|
||||||
<div className="space-y-8">
|
<div className="space-y-6">
|
||||||
<div className="flex justify-between items-center">
|
<div className="flex justify-between items-center">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-bold text-gray-900">Minhas Consultas</h1>
|
<h1 className="text-3xl font-bold text-gray-900">Minhas Consultas</h1>
|
||||||
<p className="text-gray-600">Histórico e consultas agendadas</p>
|
<p className="text-gray-600">Veja, reagende ou cancele suas consultas</p>
|
||||||
</div>
|
</div>
|
||||||
<Link href="/patient/schedule">
|
|
||||||
<Button className="bg-gray-800 hover:bg-gray-900 text-white">
|
|
||||||
<Calendar className="mr-2 h-4 w-4" />
|
|
||||||
Agendar Nova Consulta
|
|
||||||
</Button>
|
|
||||||
</Link>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid gap-6">
|
<div className="grid gap-6">
|
||||||
{/* Utiliza o array ORDENADO para a renderização */}
|
{isLoading ? (
|
||||||
{sortedAppointments.map((appointment) => {
|
<p>Carregando suas consultas...</p>
|
||||||
const appointmentDate = new Date(appointment.date);
|
) : appointments.length > 0 ? (
|
||||||
let displayStatus = appointment.status;
|
appointments.map((appointment) => (
|
||||||
|
<Card key={appointment.id}>
|
||||||
if (appointment.status === 'Agendada' && appointmentDate < today) {
|
|
||||||
displayStatus = 'Realizada';
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card key={appointment.id} className="overflow-hidden">
|
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<div className="flex justify-between items-start">
|
<div className="flex justify-between items-start">
|
||||||
<div>
|
<div>
|
||||||
<CardTitle className="text-xl">{appointment.doctorName}</CardTitle>
|
<CardTitle className="text-lg">{appointment.doctor.full_name}</CardTitle>
|
||||||
<CardDescription>{appointment.specialty}</CardDescription>
|
<CardDescription>{appointment.doctor.specialty}</CardDescription>
|
||||||
</div>
|
</div>
|
||||||
{getStatusBadge(displayStatus)}
|
{getStatusBadge(appointment.status)}
|
||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div className="grid md:grid-cols-2 gap-x-8 gap-y-4 mb-6">
|
<div className="grid md:grid-cols-2 gap-3">
|
||||||
<div className="space-y-4">
|
<div className="space-y-2 text-sm text-gray-700">
|
||||||
<div className="flex items-center text-sm text-gray-700">
|
<div className="flex items-center">
|
||||||
<Calendar className="mr-3 h-4 w-4 text-gray-500" />
|
<Calendar className="mr-2 h-4 w-4 text-gray-500" />
|
||||||
{new Date(appointment.date).toLocaleDateString("pt-BR", { timeZone: 'UTC' })}
|
{new Date(appointment.scheduled_at).toLocaleDateString("pt-BR", { timeZone: "UTC" })}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center text-sm text-gray-700">
|
<div className="flex items-center">
|
||||||
<Clock className="mr-3 h-4 w-4 text-gray-500" />
|
<Clock className="mr-2 h-4 w-4 text-gray-500" />
|
||||||
{appointment.time}
|
{new Date(appointment.scheduled_at).toLocaleTimeString("pt-BR", {
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
timeZone: "UTC",
|
||||||
|
})}
|
||||||
</div>
|
</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>
|
||||||
<div className="space-y-4">
|
<div className="flex items-center">
|
||||||
<div className="flex items-center text-sm text-gray-700">
|
<Phone className="mr-2 h-4 w-4 text-gray-500" />
|
||||||
<MapPin className="mr-3 h-4 w-4 text-gray-500" />
|
{appointment.doctor.phone || "N/A"}
|
||||||
{appointment.location || 'Local não informado'}
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center text-sm text-gray-700">
|
|
||||||
<Phone className="mr-3 h-4 w-4 text-gray-500" />
|
|
||||||
{appointment.phone || 'Telefone não informado'}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Container ÚNICO para todas as ações */}
|
{appointment.status !== "cancelled" && (
|
||||||
<div className="flex gap-2 pt-4 border-t">
|
<div className="flex gap-2 mt-4 pt-4 border-t">
|
||||||
{(displayStatus === "Agendada") && (
|
<Button variant="outline" size="sm" onClick={() => handleReschedule(appointment)}>
|
||||||
<>
|
|
||||||
<Button variant="outline" size="sm" onClick={() => handleRescheduleClick(appointment)}>
|
|
||||||
<CalendarDays className="mr-2 h-4 w-4" />
|
<CalendarDays className="mr-2 h-4 w-4" />
|
||||||
Reagendar
|
Reagendar
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="ghost" size="sm" className="text-orange-600 hover:text-orange-700 hover:bg-orange-50" onClick={() => handleCancelClick(appointment)}>
|
<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" />
|
<X className="mr-2 h-4 w-4" />
|
||||||
Cancelar
|
Cancelar
|
||||||
</Button>
|
</Button>
|
||||||
</>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{(displayStatus === "Realizada" || displayStatus === "Cancelada") && (
|
|
||||||
<Button variant="ghost" size="sm" className="text-red-600 hover:text-red-700 hover:bg-red-50" onClick={() => handleDeleteClick(appointment.id)}>
|
|
||||||
<Trash2 className="mr-2 h-4 w-4" />
|
|
||||||
Excluir do Histórico
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
);
|
))
|
||||||
})}
|
) : (
|
||||||
|
<p className="text-gray-600">Você ainda não possui consultas agendadas.</p>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* ETAPA 2: CONSTRUÇÃO DOS MODAIS */}
|
{/* MODAL DE REAGENDAMENTO */}
|
||||||
|
<Dialog open={rescheduleModal} onOpenChange={setRescheduleModal}>
|
||||||
{/* Modal de Reagendamento */}
|
<DialogContent className="sm:max-w-[425px]">
|
||||||
<Dialog open={isRescheduleModalOpen} onOpenChange={setRescheduleModalOpen}>
|
|
||||||
<DialogContent>
|
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>Reagendar Consulta</DialogTitle>
|
<DialogTitle>Reagendar Consulta</DialogTitle>
|
||||||
<DialogDescription>
|
<DialogDescription>
|
||||||
Reagendar consulta com {selectedAppointment?.doctorName}.
|
Escolha uma nova data e horário para sua consulta com{" "}
|
||||||
|
<strong>{selectedAppointment?.doctor?.full_name}</strong>.
|
||||||
</DialogDescription>
|
</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
<div className="grid gap-4 py-4">
|
<div className="grid gap-4 py-4">
|
||||||
<div className="grid grid-cols-4 items-center gap-4">
|
<div className="grid gap-2">
|
||||||
<Label htmlFor="date" className="text-right">Nova Data</Label>
|
<Label htmlFor="date">Nova Data</Label>
|
||||||
<Input
|
<Input
|
||||||
id="date"
|
id="date"
|
||||||
type="date"
|
type="date"
|
||||||
value={rescheduleData.date}
|
value={rescheduleData.date}
|
||||||
onChange={(e) => setRescheduleData({...rescheduleData, date: e.target.value})}
|
onChange={(e) => setRescheduleData((prev) => ({ ...prev, date: e.target.value }))}
|
||||||
className="col-span-3"
|
min={new Date().toISOString().split("T")[0]}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="grid grid-cols-4 items-center gap-4">
|
<div className="grid gap-2">
|
||||||
<Label htmlFor="time" className="text-right">Novo Horário</Label>
|
<Label htmlFor="time">Novo Horário</Label>
|
||||||
<Select
|
<Select
|
||||||
value={rescheduleData.time}
|
value={rescheduleData.time}
|
||||||
onValueChange={(value) => setRescheduleData({...rescheduleData, time: value})}
|
onValueChange={(value) => setRescheduleData((prev) => ({ ...prev, time: value }))}
|
||||||
>
|
>
|
||||||
<SelectTrigger className="col-span-3">
|
<SelectTrigger>
|
||||||
<SelectValue placeholder="Selecione um horário" />
|
<SelectValue placeholder="Selecione um horário" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
{timeSlots.map(time => <SelectItem key={time} value={time}>{time}</SelectItem>)}
|
{timeSlots.map((time) => (
|
||||||
|
<SelectItem key={time} value={time}>
|
||||||
|
{time}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
<div className="grid grid-cols-4 items-center gap-4">
|
<div className="grid gap-2">
|
||||||
<Label htmlFor="reason" className="text-right">Motivo</Label>
|
<Label htmlFor="reason">Motivo (opcional)</Label>
|
||||||
<Textarea
|
<Textarea
|
||||||
id="reason"
|
id="reason"
|
||||||
placeholder="Informe o motivo do reagendamento (opcional)"
|
placeholder="Explique brevemente o motivo do reagendamento..."
|
||||||
value={rescheduleData.reason}
|
value={rescheduleData.reason}
|
||||||
onChange={(e) => setRescheduleData({...rescheduleData, reason: e.target.value})}
|
onChange={(e) => setRescheduleData((prev) => ({ ...prev, reason: e.target.value }))}
|
||||||
className="col-span-3"
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
<DialogClose asChild>
|
<Button variant="outline" onClick={() => setRescheduleModal(false)}>
|
||||||
<Button type="button" variant="outline">Cancelar</Button>
|
Cancelar
|
||||||
</DialogClose>
|
</Button>
|
||||||
<Button type="button" onClick={confirmReschedule}>Confirmar Reagendamento</Button>
|
<Button onClick={confirmReschedule}>Confirmar</Button>
|
||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|
||||||
{/* Modal de Cancelamento */}
|
{/* MODAL DE CANCELAMENTO */}
|
||||||
<Dialog open={isCancelModalOpen} onOpenChange={setCancelModalOpen}>
|
<Dialog open={cancelModal} onOpenChange={setCancelModal}>
|
||||||
<DialogContent>
|
<DialogContent className="sm:max-w-[425px]">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>Cancelar Consulta</DialogTitle>
|
<DialogTitle>Cancelar Consulta</DialogTitle>
|
||||||
<DialogDescription>
|
<DialogDescription>
|
||||||
Você tem certeza que deseja cancelar sua consulta com {selectedAppointment?.doctorName}? Esta ação não pode ser desfeita.
|
Deseja realmente cancelar sua consulta com{" "}
|
||||||
|
<strong>{selectedAppointment?.doctor?.full_name}</strong>?
|
||||||
</DialogDescription>
|
</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
<div className="py-4">
|
<div className="grid gap-4 py-4">
|
||||||
<Label htmlFor="cancelReason">Motivo do Cancelamento (obrigatório)</Label>
|
<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
|
<Textarea
|
||||||
id="cancelReason"
|
id="cancel-reason"
|
||||||
placeholder="Por favor, descreva o motivo do cancelamento..."
|
placeholder="Informe o motivo do cancelamento (mínimo 10 caracteres)"
|
||||||
value={cancelReason}
|
value={cancelReason}
|
||||||
onChange={(e) => setCancelReason(e.target.value)}
|
onChange={(e) => setCancelReason(e.target.value)}
|
||||||
className="mt-2"
|
className="min-h-[100px]"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
<DialogClose asChild>
|
<Button variant="outline" onClick={() => setCancelModal(false)}>
|
||||||
<Button type="button" variant="outline">Voltar</Button>
|
Voltar
|
||||||
</DialogClose>
|
</Button>
|
||||||
<Button type="button" variant="destructive" onClick={confirmCancel}>Confirmar Cancelamento</Button>
|
<Button variant="destructive" onClick={confirmCancel}>
|
||||||
|
Confirmar Cancelamento
|
||||||
|
</Button>
|
||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|||||||
@ -1,8 +1,7 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import type React from "react"
|
|
||||||
import { useState, useEffect, useCallback } from "react"
|
import { useState, useEffect, useCallback } from "react"
|
||||||
// Importações de componentes omitidas para brevidade, mas estão no código original
|
import { Calendar, Clock, User } from "lucide-react"
|
||||||
import PatientLayout from "@/components/patient-layout"
|
import PatientLayout from "@/components/patient-layout"
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button"
|
||||||
@ -10,49 +9,53 @@ import { Input } from "@/components/ui/input"
|
|||||||
import { Label } from "@/components/ui/label"
|
import { Label } from "@/components/ui/label"
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||||
import { Textarea } from "@/components/ui/textarea"
|
import { Textarea } from "@/components/ui/textarea"
|
||||||
import { Calendar, Clock, User } from "lucide-react"
|
import { doctorsService } from "services/doctorsApi.mjs"
|
||||||
import { doctorsService } from "services/doctorsApi.mjs";
|
|
||||||
|
|
||||||
interface Doctor {
|
interface Doctor {
|
||||||
id: string;
|
id: string
|
||||||
full_name: string;
|
full_name: string
|
||||||
specialty: string;
|
specialty: string
|
||||||
phone_mobile: string;
|
phone_mobile: string
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Chave do LocalStorage, a mesma usada em secretarypage.tsx
|
const APPOINTMENTS_STORAGE_KEY = "clinic-appointments"
|
||||||
const APPOINTMENTS_STORAGE_KEY = "clinic-appointments";
|
|
||||||
|
|
||||||
export default function ScheduleAppointment() {
|
export default function ScheduleAppointment() {
|
||||||
const [selectedDoctor, setSelectedDoctor] = useState("")
|
const [selectedDoctor, setSelectedDoctor] = useState("")
|
||||||
const [selectedDate, setSelectedDate] = useState("")
|
const [selectedDate, setSelectedDate] = useState("")
|
||||||
const [selectedTime, setSelectedTime] = useState("")
|
const [selectedTime, setSelectedTime] = useState("")
|
||||||
const [notes, setNotes] = useState("")
|
const [notes, setNotes] = useState("")
|
||||||
const [doctors, setDoctors] = useState<Doctor[]>([]);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
|
|
||||||
|
// 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 [doctors, setDoctors] = useState<Doctor[]>([])
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
|
||||||
const fetchDoctors = useCallback(async () => {
|
const fetchDoctors = useCallback(async () => {
|
||||||
setLoading(true);
|
setLoading(true)
|
||||||
setError(null);
|
setError(null)
|
||||||
try {
|
try {
|
||||||
|
const data: Doctor[] = await doctorsService.list()
|
||||||
const data: Doctor[] = await doctorsService.list();
|
setDoctors(data || [])
|
||||||
setDoctors(data || []);
|
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
console.error("Erro ao carregar lista de médicos:", e);
|
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.");
|
setError("Não foi possível carregar a lista de médicos. Verifique a conexão com a API.")
|
||||||
setDoctors([]);
|
setDoctors([])
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false)
|
||||||
}
|
}
|
||||||
}, []);
|
}, [])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchDoctors();
|
fetchDoctors()
|
||||||
}, [fetchDoctors]);
|
}, [fetchDoctors])
|
||||||
|
|
||||||
const availableTimes = [
|
const availableTimes = [
|
||||||
"08:00",
|
"08:00",
|
||||||
@ -73,49 +76,54 @@ export default function ScheduleAppointment() {
|
|||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
|
|
||||||
const doctorDetails = doctors.find((d) => d.id === selectedDoctor)
|
const doctorDetails = doctors.find((d) => d.id === selectedDoctor)
|
||||||
|
|
||||||
// --- SIMULAÇÃO DO PACIENTE LOGADO ---
|
|
||||||
// Você só tem um usuário para cada role. Vamos simular um paciente:
|
|
||||||
const patientDetails = {
|
const patientDetails = {
|
||||||
id: "P001",
|
id: "P001",
|
||||||
full_name: "Paciente Exemplo Único", // Este nome aparecerá na agenda do médico
|
full_name: "Paciente Exemplo Único",
|
||||||
location: "Clínica Geral",
|
location: "Clínica Geral",
|
||||||
phone: "(11) 98765-4321"
|
phone: "(11) 98765-4321",
|
||||||
};
|
}
|
||||||
|
|
||||||
if (!patientDetails || !doctorDetails) {
|
if (!patientDetails || !doctorDetails) {
|
||||||
alert("Erro: Selecione o médico ou dados do paciente indisponíveis.");
|
alert("Erro: Selecione o médico ou dados do paciente indisponíveis.")
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const newAppointment = {
|
const newAppointment = {
|
||||||
id: new Date().getTime(), // ID único simples
|
id: new Date().getTime(),
|
||||||
patientName: patientDetails.full_name,
|
patientName: patientDetails.full_name,
|
||||||
doctor: doctorDetails.full_name, // Nome completo do médico (necessário para a listagem)
|
doctor: doctorDetails.full_name,
|
||||||
specialty: doctorDetails.specialty,
|
specialty: doctorDetails.specialty,
|
||||||
date: selectedDate,
|
date: selectedDate,
|
||||||
time: selectedTime,
|
time: selectedTime,
|
||||||
|
tipoConsulta,
|
||||||
|
duracao,
|
||||||
|
convenio,
|
||||||
|
queixa,
|
||||||
|
obsPaciente,
|
||||||
|
obsInternas,
|
||||||
|
notes,
|
||||||
status: "agendada",
|
status: "agendada",
|
||||||
phone: patientDetails.phone,
|
phone: patientDetails.phone,
|
||||||
};
|
}
|
||||||
|
|
||||||
// 1. Carrega agendamentos existentes
|
const storedAppointmentsRaw = localStorage.getItem(APPOINTMENTS_STORAGE_KEY)
|
||||||
const storedAppointmentsRaw = localStorage.getItem(APPOINTMENTS_STORAGE_KEY);
|
const currentAppointments = storedAppointmentsRaw ? JSON.parse(storedAppointmentsRaw) : []
|
||||||
const currentAppointments = storedAppointmentsRaw ? JSON.parse(storedAppointmentsRaw) : [];
|
const updatedAppointments = [...currentAppointments, newAppointment]
|
||||||
|
localStorage.setItem(APPOINTMENTS_STORAGE_KEY, JSON.stringify(updatedAppointments))
|
||||||
|
|
||||||
// 2. Adiciona o novo agendamento
|
alert(`Consulta com ${doctorDetails.full_name} agendada com sucesso!`)
|
||||||
const updatedAppointments = [...currentAppointments, newAppointment];
|
|
||||||
|
|
||||||
// 3. Salva a lista atualizada no LocalStorage
|
// resetar campos
|
||||||
localStorage.setItem(APPOINTMENTS_STORAGE_KEY, JSON.stringify(updatedAppointments));
|
setSelectedDoctor("")
|
||||||
|
setSelectedDate("")
|
||||||
alert(`Consulta com ${doctorDetails.full_name} agendada com sucesso!`);
|
setSelectedTime("")
|
||||||
|
setNotes("")
|
||||||
// Limpar o formulário após o sucesso (opcional)
|
setTipoConsulta("presencial")
|
||||||
setSelectedDoctor("");
|
setDuracao("30")
|
||||||
setSelectedDate("");
|
setConvenio("")
|
||||||
setSelectedTime("");
|
setQueixa("")
|
||||||
setNotes("");
|
setObsPaciente("")
|
||||||
|
setObsInternas("")
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@ -135,6 +143,9 @@ export default function ScheduleAppointment() {
|
|||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<form onSubmit={handleSubmit} className="space-y-6">
|
<form onSubmit={handleSubmit} className="space-y-6">
|
||||||
|
|
||||||
|
|
||||||
|
{/* Médico */}
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="doctor">Médico</Label>
|
<Label htmlFor="doctor">Médico</Label>
|
||||||
<Select value={selectedDoctor} onValueChange={setSelectedDoctor}>
|
<Select value={selectedDoctor} onValueChange={setSelectedDoctor}>
|
||||||
@ -142,15 +153,26 @@ export default function ScheduleAppointment() {
|
|||||||
<SelectValue placeholder="Selecione um médico" />
|
<SelectValue placeholder="Selecione um médico" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
{doctors.map((doctor) => (
|
{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}>
|
<SelectItem key={doctor.id} value={doctor.id}>
|
||||||
{doctor.full_name} - {doctor.specialty}
|
{doctor.full_name} - {doctor.specialty}
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
))}
|
))
|
||||||
|
)}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Data e horário */}
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
<div className="grid md:grid-cols-2 gap-4">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="date">Data</Label>
|
<Label htmlFor="date">Data</Label>
|
||||||
@ -179,9 +201,81 @@ export default function ScheduleAppointment() {
|
|||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
</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 className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="notes">Observações (opcional)</Label>
|
<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
|
<Textarea
|
||||||
id="notes"
|
id="notes"
|
||||||
placeholder="Descreva brevemente o motivo da consulta ou observações importantes"
|
placeholder="Descreva brevemente o motivo da consulta ou observações importantes"
|
||||||
@ -191,7 +285,12 @@ export default function ScheduleAppointment() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Button type="submit" className="w-full" disabled={!selectedDoctor || !selectedDate || !selectedTime}>
|
{/* Botão */}
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
className="w-full"
|
||||||
|
disabled={!selectedDoctor || !selectedDate || !selectedTime}
|
||||||
|
>
|
||||||
Agendar Consulta
|
Agendar Consulta
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
@ -199,6 +298,7 @@ export default function ScheduleAppointment() {
|
|||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Resumo */}
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
@ -211,14 +311,18 @@ export default function ScheduleAppointment() {
|
|||||||
{selectedDoctor && (
|
{selectedDoctor && (
|
||||||
<div className="flex items-center space-x-2">
|
<div className="flex items-center space-x-2">
|
||||||
<User className="h-4 w-4 text-gray-500" />
|
<User className="h-4 w-4 text-gray-500" />
|
||||||
<span className="text-sm">{doctors.find((d) => d.id === selectedDoctor)?.full_name}</span>
|
<span className="text-sm">
|
||||||
|
{doctors.find((d) => d.id === selectedDoctor)?.full_name}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{selectedDate && (
|
{selectedDate && (
|
||||||
<div className="flex items-center space-x-2">
|
<div className="flex items-center space-x-2">
|
||||||
<Calendar className="h-4 w-4 text-gray-500" />
|
<Calendar className="h-4 w-4 text-gray-500" />
|
||||||
<span className="text-sm">{new Date(selectedDate).toLocaleDateString("pt-BR")}</span>
|
<span className="text-sm">
|
||||||
|
{new Date(selectedDate).toLocaleDateString("pt-BR")}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user