forked from RiseUP/riseup-squad21
Merge pull request 'Adicionada função de marcar consulta' (#10) from StsDanilo/riseup-squad21:marcar-consulta into main
Reviewed-on: RiseUP/riseup-squad21#10
This commit is contained in:
commit
9af06b739f
112
app/context/AppointmentsContext.tsx
Normal file
112
app/context/AppointmentsContext.tsx
Normal file
@ -0,0 +1,112 @@
|
||||
"use client";
|
||||
|
||||
import React, { createContext, useContext, useState, ReactNode } from 'react';
|
||||
|
||||
// A interface Appointment permanece a mesma
|
||||
export interface Appointment {
|
||||
id: string;
|
||||
doctorName: string;
|
||||
specialty: string;
|
||||
date: string;
|
||||
time: string;
|
||||
location: string;
|
||||
phone: string;
|
||||
status: 'Agendada' | 'Realizada' | 'Cancelada';
|
||||
observations?: string;
|
||||
}
|
||||
|
||||
export interface AppointmentsContextType {
|
||||
appointments: Appointment[];
|
||||
addAppointment: (appointmentData: Omit<Appointment, 'id' | 'status'>) => void;
|
||||
updateAppointment: (appointmentId: string, updatedData: Partial<Omit<Appointment, 'id'>>) => void;
|
||||
// [NOVA FUNÇÃO] Adicionando a assinatura da função de exclusão ao nosso contrato
|
||||
deleteAppointment: (appointmentId: string) => void;
|
||||
}
|
||||
|
||||
const AppointmentsContext = createContext<AppointmentsContextType | undefined>(undefined);
|
||||
|
||||
// Os dados iniciais permanecem os mesmos
|
||||
const initialAppointments: Appointment[] = [
|
||||
{
|
||||
id: '1',
|
||||
doctorName: "Dr. João Silva",
|
||||
specialty: "Cardiologia",
|
||||
date: "2024-08-15",
|
||||
time: "14:30",
|
||||
status: "Agendada",
|
||||
location: "Consultório A - 2º andar",
|
||||
phone: "(11) 3333-4444",
|
||||
observations: "Paciente relata dor no peito.",
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
doctorName: "Dra. Maria Santos",
|
||||
specialty: "Dermatologia",
|
||||
date: "2024-09-10",
|
||||
time: "10:00",
|
||||
status: "Agendada",
|
||||
location: "Consultório B - 1º andar",
|
||||
phone: "(11) 3333-5555",
|
||||
},
|
||||
{
|
||||
id: '3',
|
||||
doctorName: "Dr. Pedro Costa",
|
||||
specialty: "Ortopedia",
|
||||
date: "2024-07-08",
|
||||
time: "16:00",
|
||||
status: "Realizada",
|
||||
location: "Consultório C - 3º andar",
|
||||
phone: "(11) 3333-6666",
|
||||
},
|
||||
];
|
||||
|
||||
export function AppointmentsProvider({ children }: { children: ReactNode }) {
|
||||
const [appointments, setAppointments] = useState<Appointment[]>(initialAppointments);
|
||||
|
||||
const addAppointment = (appointmentData: Omit<Appointment, 'id' | 'status'>) => {
|
||||
const newAppointment: Appointment = {
|
||||
id: Date.now().toString(),
|
||||
status: 'Agendada',
|
||||
...appointmentData,
|
||||
};
|
||||
setAppointments((prev) => [...prev, newAppointment]);
|
||||
};
|
||||
|
||||
const updateAppointment = (appointmentId: string, updatedData: Partial<Omit<Appointment, 'id'>>) => {
|
||||
setAppointments((prev) =>
|
||||
prev.map((apt) =>
|
||||
apt.id === appointmentId ? { ...apt, ...updatedData } : apt
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
// [NOVA FUNÇÃO] Implementando a lógica de exclusão real
|
||||
const deleteAppointment = (appointmentId: string) => {
|
||||
setAppointments((prev) =>
|
||||
// O método 'filter' cria um novo array com todos os itens
|
||||
// EXCETO aquele cujo ID corresponde ao que queremos excluir.
|
||||
prev.filter((apt) => apt.id !== appointmentId)
|
||||
);
|
||||
};
|
||||
|
||||
const value = {
|
||||
appointments,
|
||||
addAppointment,
|
||||
updateAppointment,
|
||||
deleteAppointment, // Disponibilizando a nova função para os componentes
|
||||
};
|
||||
|
||||
return (
|
||||
<AppointmentsContext.Provider value={value}>
|
||||
{children}
|
||||
</AppointmentsContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useAppointments() {
|
||||
const context = useContext(AppointmentsContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('useAppointments deve ser usado dentro de um AppointmentsProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
@ -3,6 +3,8 @@ import { GeistSans } from 'geist/font/sans'
|
||||
import { GeistMono } from 'geist/font/mono'
|
||||
import { Analytics } from '@vercel/analytics/next'
|
||||
import './globals.css'
|
||||
// [PASSO 1.2] - Importando o nosso provider
|
||||
import { AppointmentsProvider } from './context/AppointmentsContext'
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Clinic App',
|
||||
@ -18,9 +20,12 @@ export default function RootLayout({
|
||||
return (
|
||||
<html lang="en">
|
||||
<body className={`font-sans ${GeistSans.variable} ${GeistMono.variable}`}>
|
||||
{children}
|
||||
{/* [PASSO 1.2] - Envolvendo a aplicação com o provider */}
|
||||
<AppointmentsProvider>
|
||||
{children}
|
||||
</AppointmentsProvider>
|
||||
<Analytics />
|
||||
</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
}
|
||||
@ -1,139 +1,125 @@
|
||||
"use client";
|
||||
|
||||
import { useState } 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 { Card, CardContent, CardDescription, CardHeader, CardTitle } 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 { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogClose } 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, CalendarDays, X } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import Link from "next/link";
|
||||
import { Calendar, Clock, MapPin, Phone, CalendarDays, X, Trash2 } from "lucide-react";
|
||||
|
||||
export default function PatientAppointments() {
|
||||
const [appointments, setAppointments] = useState([
|
||||
{
|
||||
id: 1,
|
||||
doctor: "Dr. João Silva",
|
||||
specialty: "Cardiologia",
|
||||
date: "2024-01-15",
|
||||
time: "14:30",
|
||||
status: "agendada",
|
||||
location: "Consultório A - 2º andar",
|
||||
phone: "(11) 3333-4444",
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
doctor: "Dra. Maria Santos",
|
||||
specialty: "Dermatologia",
|
||||
date: "2024-01-22",
|
||||
time: "10:00",
|
||||
status: "agendada",
|
||||
location: "Consultório B - 1º andar",
|
||||
phone: "(11) 3333-5555",
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
doctor: "Dr. Pedro Costa",
|
||||
specialty: "Ortopedia",
|
||||
date: "2024-01-08",
|
||||
time: "16:00",
|
||||
status: "realizada",
|
||||
location: "Consultório C - 3º andar",
|
||||
phone: "(11) 3333-6666",
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
doctor: "Dra. Ana Lima",
|
||||
specialty: "Ginecologia",
|
||||
date: "2024-01-05",
|
||||
time: "09:30",
|
||||
status: "realizada",
|
||||
location: "Consultório D - 2º andar",
|
||||
phone: "(11) 3333-7777",
|
||||
},
|
||||
]);
|
||||
export default function PatientAppointmentsPage() {
|
||||
const { appointments, updateAppointment, deleteAppointment } = useAppointments();
|
||||
|
||||
const [rescheduleModal, setRescheduleModal] = useState(false);
|
||||
const [cancelModal, setCancelModal] = useState(false);
|
||||
const [selectedAppointment, setSelectedAppointment] = useState<any>(null);
|
||||
const [rescheduleData, setRescheduleData] = useState({
|
||||
date: "",
|
||||
time: "",
|
||||
reason: "",
|
||||
});
|
||||
// Estados para controlar os modais e os dados do formulário
|
||||
const [isRescheduleModalOpen, setRescheduleModalOpen] = useState(false);
|
||||
const [isCancelModalOpen, setCancelModalOpen] = useState(false);
|
||||
const [selectedAppointment, setSelectedAppointment] = useState<Appointment | null>(null);
|
||||
|
||||
const [rescheduleData, setRescheduleData] = useState({ date: "", time: "", reason: "" });
|
||||
const [cancelReason, setCancelReason] = useState("");
|
||||
|
||||
const handleReschedule = (appointment: any) => {
|
||||
// --- MANIPULADORES DE EVENTOS ---
|
||||
|
||||
const handleRescheduleClick = (appointment: Appointment) => {
|
||||
setSelectedAppointment(appointment);
|
||||
setRescheduleData({ date: "", time: "", reason: "" });
|
||||
setRescheduleModal(true);
|
||||
// Preenche o formulário com os dados atuais da consulta
|
||||
setRescheduleData({ date: appointment.date, time: appointment.time, reason: appointment.observations || "" });
|
||||
setRescheduleModalOpen(true);
|
||||
};
|
||||
|
||||
const handleCancel = (appointment: any) => {
|
||||
const handleCancelClick = (appointment: Appointment) => {
|
||||
setSelectedAppointment(appointment);
|
||||
setCancelReason("");
|
||||
setCancelModal(true);
|
||||
setCancelReason(""); // Limpa o motivo ao abrir
|
||||
setCancelModalOpen(true);
|
||||
};
|
||||
|
||||
|
||||
const confirmReschedule = () => {
|
||||
if (!rescheduleData.date || !rescheduleData.time) {
|
||||
toast.error("Por favor, selecione uma nova data e horário");
|
||||
return;
|
||||
}
|
||||
|
||||
setAppointments((prev) => prev.map((apt) => (apt.id === selectedAppointment.id ? { ...apt, date: rescheduleData.date, time: rescheduleData.time } : apt)));
|
||||
|
||||
setRescheduleModal(false);
|
||||
toast.success("Consulta reagendada com sucesso!");
|
||||
if (selectedAppointment) {
|
||||
updateAppointment(selectedAppointment.id, {
|
||||
date: rescheduleData.date,
|
||||
time: rescheduleData.time,
|
||||
observations: rescheduleData.reason, // Atualiza as observações com o motivo
|
||||
});
|
||||
toast.success("Consulta reagendada com sucesso!");
|
||||
setRescheduleModalOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
const confirmCancel = () => {
|
||||
if (!cancelReason.trim()) {
|
||||
toast.error("O motivo do cancelamento é obrigatório");
|
||||
return;
|
||||
}
|
||||
|
||||
if (cancelReason.trim().length < 10) {
|
||||
toast.error("Por favor, forneça um motivo mais detalhado (mínimo 10 caracteres)");
|
||||
toast.error("Por favor, forneça um motivo com pelo menos 10 caracteres.");
|
||||
return;
|
||||
}
|
||||
|
||||
setAppointments((prev) => prev.map((apt) => (apt.id === selectedAppointment.id ? { ...apt, status: "cancelada" } : apt)));
|
||||
|
||||
setCancelModal(false);
|
||||
toast.success("Consulta cancelada com sucesso!");
|
||||
};
|
||||
|
||||
const getStatusBadge = (status: string) => {
|
||||
switch (status) {
|
||||
case "agendada":
|
||||
return <Badge className="bg-blue-100 text-blue-800">Agendada</Badge>;
|
||||
case "realizada":
|
||||
return <Badge className="bg-green-100 text-green-800">Realizada</Badge>;
|
||||
case "cancelada":
|
||||
return <Badge className="bg-red-100 text-red-800">Cancelada</Badge>;
|
||||
default:
|
||||
return <Badge variant="secondary">{status}</Badge>;
|
||||
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 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 handleDeleteClick = (appointmentId: 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) {
|
||||
case "Agendada": return <Badge className="bg-blue-100 text-blue-800 font-medium">Agendada</Badge>;
|
||||
case "Realizada": return <Badge className="bg-green-100 text-green-800 font-medium">Realizada</Badge>;
|
||||
case "Cancelada": return <Badge className="bg-red-100 text-red-800 font-medium">Cancelada</Badge>;
|
||||
}
|
||||
};
|
||||
|
||||
const timeSlots = ["08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "14:00", "14:30", "15:00", "15:30"];
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0); // Zera o horário para comparar apenas o dia
|
||||
|
||||
// ETAPA 1: ORDENAÇÃO DAS CONSULTAS
|
||||
// Cria uma cópia do array e o ordena
|
||||
const sortedAppointments = [...appointments].sort((a, b) => {
|
||||
const statusWeight = { 'Agendada': 1, 'Realizada': 2, 'Cancelada': 3 };
|
||||
|
||||
// Primeiro, ordena por status (Agendada vem primeiro)
|
||||
if (statusWeight[a.status] !== statusWeight[b.status]) {
|
||||
return statusWeight[a.status] - statusWeight[b.status];
|
||||
}
|
||||
|
||||
// Se o status for o mesmo, ordena por data (mais recente/futura no topo)
|
||||
return new Date(b.date).getTime() - new Date(a.date).getTime();
|
||||
});
|
||||
|
||||
return (
|
||||
<PatientLayout>
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-8">
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">Minhas Consultas</h1>
|
||||
<p className="text-gray-600">Histórico e consultas agendadas</p>
|
||||
</div>
|
||||
<Link href="/patient/schedule">
|
||||
<Button>
|
||||
<Button className="bg-gray-800 hover:bg-gray-900 text-white">
|
||||
<Calendar className="mr-2 h-4 w-4" />
|
||||
Agendar Nova Consulta
|
||||
</Button>
|
||||
@ -141,124 +127,162 @@ export default function PatientAppointments() {
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6">
|
||||
{appointments.map((appointment) => (
|
||||
<Card key={appointment.id}>
|
||||
<CardHeader>
|
||||
<div className="flex justify-between items-start">
|
||||
<div>
|
||||
<CardTitle className="text-lg">{appointment.doctor}</CardTitle>
|
||||
<CardDescription>{appointment.specialty}</CardDescription>
|
||||
</div>
|
||||
{getStatusBadge(appointment.status)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center text-sm text-gray-600">
|
||||
<Calendar className="mr-2 h-4 w-4" />
|
||||
{new Date(appointment.date).toLocaleDateString("pt-BR")}
|
||||
</div>
|
||||
<div className="flex items-center text-sm text-gray-600">
|
||||
<Clock className="mr-2 h-4 w-4" />
|
||||
{appointment.time}
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center text-sm text-gray-600">
|
||||
<MapPin className="mr-2 h-4 w-4" />
|
||||
{appointment.location}
|
||||
</div>
|
||||
<div className="flex items-center text-sm text-gray-600">
|
||||
<Phone className="mr-2 h-4 w-4" />
|
||||
{appointment.phone}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/* Utiliza o array ORDENADO para a renderização */}
|
||||
{sortedAppointments.map((appointment) => {
|
||||
const appointmentDate = new Date(appointment.date);
|
||||
let displayStatus = appointment.status;
|
||||
|
||||
{appointment.status === "agendada" && (
|
||||
<div className="flex gap-2 mt-4 pt-4 border-t">
|
||||
<Button variant="outline" size="sm" onClick={() => handleReschedule(appointment)}>
|
||||
if (appointment.status === 'Agendada' && appointmentDate < today) {
|
||||
displayStatus = 'Realizada';
|
||||
}
|
||||
|
||||
return (
|
||||
<Card key={appointment.id} className="overflow-hidden">
|
||||
<CardHeader>
|
||||
<div className="flex justify-between items-start">
|
||||
<div>
|
||||
<CardTitle className="text-xl">{appointment.doctorName}</CardTitle>
|
||||
<CardDescription>{appointment.specialty}</CardDescription>
|
||||
</div>
|
||||
{getStatusBadge(displayStatus)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid md:grid-cols-2 gap-x-8 gap-y-4 mb-6">
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center text-sm text-gray-700">
|
||||
<Calendar className="mr-3 h-4 w-4 text-gray-500" />
|
||||
{new Date(appointment.date).toLocaleDateString("pt-BR", { timeZone: 'UTC' })}
|
||||
</div>
|
||||
<div className="flex items-center text-sm text-gray-700">
|
||||
<Clock className="mr-3 h-4 w-4 text-gray-500" />
|
||||
{appointment.time}
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center text-sm text-gray-700">
|
||||
<MapPin className="mr-3 h-4 w-4 text-gray-500" />
|
||||
{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>
|
||||
|
||||
{/* Container ÚNICO para todas as ações */}
|
||||
<div className="flex gap-2 pt-4 border-t">
|
||||
{(displayStatus === "Agendada") && (
|
||||
<>
|
||||
<Button variant="outline" size="sm" onClick={() => handleRescheduleClick(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 bg-transparent" onClick={() => handleCancel(appointment)}>
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" className="text-orange-600 hover:text-orange-700 hover:bg-orange-50" onClick={() => handleCancelClick(appointment)}>
|
||||
<X className="mr-2 h-4 w-4" />
|
||||
Cancelar
|
||||
</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>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ETAPA 2: CONSTRUÇÃO DOS MODAIS */}
|
||||
|
||||
<Dialog open={rescheduleModal} onOpenChange={setRescheduleModal}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
{/* Modal de Reagendamento */}
|
||||
<Dialog open={isRescheduleModalOpen} onOpenChange={setRescheduleModalOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Reagendar Consulta</DialogTitle>
|
||||
<DialogDescription>Reagendar consulta com {selectedAppointment?.doctor}</DialogDescription>
|
||||
<DialogDescription>
|
||||
Reagendar consulta com {selectedAppointment?.doctorName}.
|
||||
</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 className="grid grid-cols-4 items-center gap-4">
|
||||
<Label htmlFor="date" className="text-right">Nova Data</Label>
|
||||
<Input
|
||||
id="date"
|
||||
type="date"
|
||||
value={rescheduleData.date}
|
||||
onChange={(e) => setRescheduleData({...rescheduleData, date: e.target.value})}
|
||||
className="col-span-3"
|
||||
/>
|
||||
</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>
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label htmlFor="time" className="text-right">Novo Horário</Label>
|
||||
<Select
|
||||
value={rescheduleData.time}
|
||||
onValueChange={(value) => setRescheduleData({...rescheduleData, time: value})}
|
||||
>
|
||||
<SelectTrigger className="col-span-3">
|
||||
<SelectValue placeholder="Selecione um horário" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{timeSlots.map((time) => (
|
||||
<SelectItem key={time} value={time}>
|
||||
{time}
|
||||
</SelectItem>
|
||||
))}
|
||||
{timeSlots.map(time => <SelectItem key={time} value={time}>{time}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="reason">Motivo do Reagendamento (opcional)</Label>
|
||||
<Textarea id="reason" placeholder="Informe o motivo do reagendamento..." value={rescheduleData.reason} onChange={(e) => setRescheduleData((prev) => ({ ...prev, reason: e.target.value }))} />
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label htmlFor="reason" className="text-right">Motivo</Label>
|
||||
<Textarea
|
||||
id="reason"
|
||||
placeholder="Informe o motivo do reagendamento (opcional)"
|
||||
value={rescheduleData.reason}
|
||||
onChange={(e) => setRescheduleData({...rescheduleData, reason: e.target.value})}
|
||||
className="col-span-3"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setRescheduleModal(false)}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button onClick={confirmReschedule}>Confirmar Reagendamento</Button>
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="outline">Cancelar</Button>
|
||||
</DialogClose>
|
||||
<Button type="button" onClick={confirmReschedule}>Confirmar Reagendamento</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={cancelModal} onOpenChange={setCancelModal}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
{/* Modal de Cancelamento */}
|
||||
<Dialog open={isCancelModalOpen} onOpenChange={setCancelModalOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Cancelar Consulta</DialogTitle>
|
||||
<DialogDescription>Tem certeza que deseja cancelar a consulta com {selectedAppointment?.doctor}?</DialogDescription>
|
||||
<DialogDescription>
|
||||
Você tem certeza que deseja cancelar sua consulta com {selectedAppointment?.doctorName}? Esta ação não pode ser desfeita.
|
||||
</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="Por favor, informe o motivo do cancelamento... (obrigatório)" value={cancelReason} onChange={(e) => setCancelReason(e.target.value)} required className={`min-h-[100px] ${!cancelReason.trim() && cancelModal ? "border-red-300 focus:border-red-500" : ""}`} />
|
||||
<p className="text-xs text-gray-500">Mínimo de 10 caracteres. Este campo é obrigatório.</p>
|
||||
</div>
|
||||
<div className="py-4">
|
||||
<Label htmlFor="cancelReason">Motivo do Cancelamento (obrigatório)</Label>
|
||||
<Textarea
|
||||
id="cancelReason"
|
||||
placeholder="Por favor, descreva o motivo do cancelamento..."
|
||||
value={cancelReason}
|
||||
onChange={(e) => setCancelReason(e.target.value)}
|
||||
className="mt-2"
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setCancelModal(false)}>
|
||||
Voltar
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={confirmCancel} disabled={!cancelReason.trim() || cancelReason.trim().length < 10}>
|
||||
Confirmar Cancelamento
|
||||
</Button>
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="outline">Voltar</Button>
|
||||
</DialogClose>
|
||||
<Button type="button" variant="destructive" onClick={confirmCancel}>Confirmar Cancelamento</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</PatientLayout>
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -1,50 +1,102 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import type React from "react"
|
||||
import type React from "react";
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { useState } from "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 { Calendar, Clock, User } from "lucide-react"
|
||||
// [SINCRONIZAÇÃO 1] - Importando a lista de 'appointments' para a validação de conflito
|
||||
import { useAppointments } from "../../context/AppointmentsContext";
|
||||
|
||||
export default function ScheduleAppointment() {
|
||||
const [selectedDoctor, setSelectedDoctor] = useState("")
|
||||
const [selectedDate, setSelectedDate] = useState("")
|
||||
const [selectedTime, setSelectedTime] = useState("")
|
||||
const [notes, setNotes] = useState("")
|
||||
// Componentes de UI e Layout
|
||||
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 { Calendar, Clock, User } from "lucide-react";
|
||||
|
||||
const doctors = [
|
||||
{ id: "1", name: "Dr. João Silva", specialty: "Cardiologia" },
|
||||
{ id: "2", name: "Dra. Maria Santos", specialty: "Dermatologia" },
|
||||
{ id: "3", name: "Dr. Pedro Costa", specialty: "Ortopedia" },
|
||||
{ id: "4", name: "Dra. Ana Lima", specialty: "Ginecologia" },
|
||||
]
|
||||
// Interface para o estado local do formulário (sem alterações)
|
||||
interface AppointmentFormState {
|
||||
doctorId: string;
|
||||
date: string;
|
||||
time: string;
|
||||
observations: string;
|
||||
}
|
||||
|
||||
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",
|
||||
]
|
||||
// --- DADOS MOCKADOS (ALTERAÇÃO 1: Adicionando location e phone) ---
|
||||
const doctors = [
|
||||
{ id: "1", name: "Dr. João Silva", specialty: "Cardiologia", location: "Consultório A - 2º andar", phone: "(11) 3333-4444" },
|
||||
{ id: "2", name: "Dra. Maria Santos", specialty: "Dermatologia", location: "Consultório B - 1º andar", phone: "(11) 3333-5555" },
|
||||
{ id: "3", name: "Dr. Pedro Costa", specialty: "Ortopedia", location: "Consultório C - 3º andar", phone: "(11) 3333-6666" },
|
||||
];
|
||||
const availableTimes = ["09:00", "09:30", "10:00", "10:30", "14:00", "14:30", "15:00"];
|
||||
// -------------------------------------------------------------
|
||||
|
||||
export default function ScheduleAppointmentPage() {
|
||||
const router = useRouter();
|
||||
// [SINCRONIZAÇÃO 1 - continuação] - Obtendo a lista de agendamentos existentes
|
||||
const { addAppointment, appointments } = useAppointments();
|
||||
|
||||
const [formData, setFormData] = useState<AppointmentFormState>({
|
||||
doctorId: "",
|
||||
date: "",
|
||||
time: "",
|
||||
observations: "",
|
||||
});
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
|
||||
const { name, value } = e.target;
|
||||
setFormData(prevState => ({ ...prevState, [name]: value }));
|
||||
};
|
||||
|
||||
const handleSelectChange = (name: keyof AppointmentFormState, value: string) => {
|
||||
setFormData(prevState => ({ ...prevState, [name]: value }));
|
||||
};
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
// Aqui você implementaria a lógica para salvar o agendamento
|
||||
alert("Consulta agendada com sucesso!")
|
||||
}
|
||||
e.preventDefault();
|
||||
if (!formData.doctorId || !formData.date || !formData.time) {
|
||||
toast.error("Por favor, preencha os campos de médico, data e horário.");
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedDoctor = doctors.find(doc => doc.id === formData.doctorId);
|
||||
if (!selectedDoctor) return;
|
||||
|
||||
// Validação de conflito (sem alterações, já estava correta)
|
||||
const isConflict = appointments.some(
|
||||
(apt) =>
|
||||
apt.doctorName === selectedDoctor.name &&
|
||||
apt.date === formData.date &&
|
||||
apt.time === formData.time
|
||||
);
|
||||
|
||||
if (isConflict) {
|
||||
toast.error("Este horário já está ocupado para o médico selecionado.");
|
||||
return;
|
||||
}
|
||||
|
||||
// [ALTERAÇÃO 2] - Utilizando os dados do médico selecionado para location e phone
|
||||
// e removendo os placeholders.
|
||||
addAppointment({
|
||||
doctorName: selectedDoctor.name,
|
||||
specialty: selectedDoctor.specialty,
|
||||
date: formData.date,
|
||||
time: formData.time,
|
||||
observations: formData.observations,
|
||||
location: selectedDoctor.location, // Usando a localização do médico
|
||||
phone: selectedDoctor.phone, // Usando o telefone do médico
|
||||
});
|
||||
|
||||
toast.success("Consulta agendada com sucesso!");
|
||||
router.push('/patient/appointments');
|
||||
};
|
||||
|
||||
// Validação de data passada (sem alterações, já estava correta)
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
|
||||
return (
|
||||
<PatientLayout>
|
||||
@ -54,7 +106,7 @@ export default function ScheduleAppointment() {
|
||||
<p className="text-gray-600">Escolha o médico, data e horário para sua consulta</p>
|
||||
</div>
|
||||
|
||||
<div className="grid lg:grid-cols-3 gap-6">
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
|
||||
<div className="lg:col-span-2">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
@ -65,9 +117,12 @@ export default function ScheduleAppointment() {
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="doctor">Médico</Label>
|
||||
<Select value={selectedDoctor} onValueChange={setSelectedDoctor}>
|
||||
<Select
|
||||
value={formData.doctorId}
|
||||
onValueChange={(value) => handleSelectChange('doctorId', value)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Selecione um médico" />
|
||||
<SelectValue placeholder="Seleione um médico" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{doctors.map((doctor) => (
|
||||
@ -79,21 +134,24 @@ export default function ScheduleAppointment() {
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="date">Data</Label>
|
||||
<Input
|
||||
id="date"
|
||||
name="date"
|
||||
type="date"
|
||||
value={selectedDate}
|
||||
onChange={(e) => setSelectedDate(e.target.value)}
|
||||
min={new Date().toISOString().split("T")[0]}
|
||||
value={formData.date}
|
||||
onChange={handleChange}
|
||||
min={today}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="time">Horário</Label>
|
||||
<Select value={selectedTime} onValueChange={setSelectedTime}>
|
||||
<Select
|
||||
value={formData.time}
|
||||
onValueChange={(value) => handleSelectChange('time', value)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Selecione um horário" />
|
||||
</SelectTrigger>
|
||||
@ -109,17 +167,18 @@ export default function ScheduleAppointment() {
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="notes">Observações (opcional)</Label>
|
||||
<Label htmlFor="observations">Observações (opcional)</Label>
|
||||
<Textarea
|
||||
id="notes"
|
||||
id="observations"
|
||||
name="observations"
|
||||
placeholder="Descreva brevemente o motivo da consulta ou observações importantes"
|
||||
value={notes}
|
||||
onChange={(e) => setNotes(e.target.value)}
|
||||
rows={3}
|
||||
value={formData.observations}
|
||||
onChange={handleChange}
|
||||
rows={4}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="w-full" disabled={!selectedDoctor || !selectedDate || !selectedTime}>
|
||||
<Button type="submit" className="w-full bg-gray-600 hover:bg-gray-700 text-white text-base py-6">
|
||||
Agendar Consulta
|
||||
</Button>
|
||||
</form>
|
||||
@ -130,30 +189,30 @@ export default function ScheduleAppointment() {
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center">
|
||||
<CardTitle className="flex items-center text-base">
|
||||
<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)?.name}</span>
|
||||
<CardContent className="space-y-3 text-sm">
|
||||
{formData.doctorId ? (
|
||||
<div className="flex items-center">
|
||||
<User className="mr-2 h-4 w-4 text-gray-500" />
|
||||
<span>{doctors.find((d) => d.id === formData.doctorId)?.name}</span>
|
||||
</div>
|
||||
) : <p className="text-gray-500">Preencha o formulário...</p>}
|
||||
|
||||
{formData.date && (
|
||||
<div className="flex items-center">
|
||||
<Calendar className="mr-2 h-4 w-4 text-gray-500" />
|
||||
<span>{new Date(formData.date).toLocaleDateString("pt-BR", { timeZone: 'UTC' })}</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>
|
||||
{formData.time && (
|
||||
<div className="flex items-center">
|
||||
<Clock className="mr-2 h-4 w-4 text-gray-500" />
|
||||
<span>{formData.time}</span>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
@ -161,18 +220,20 @@ export default function ScheduleAppointment() {
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Informações Importantes</CardTitle>
|
||||
<CardTitle className="text-base">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>
|
||||
<ul className="space-y-2 text-sm text-gray-600 list-disc list-inside">
|
||||
<li>Chegue com 15 minutos de antecedência</li>
|
||||
<li>Traga documento com foto</li>
|
||||
<li>Traga carteirinha do convênio</li>
|
||||
<li>Traga exames anteriores, se houver</li>
|
||||
</ul>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</PatientLayout>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user