Implementado API para agendar com médicos #18

Merged
LiraS2 merged 1 commits from StsDanilo/riseup-squad21:Agendamento-pacientes-com-medicos-da-API into main 2025-10-04 22:22:01 +00:00

View File

@ -1,7 +1,7 @@
"use client"; "use client";
import type React from "react"; import type React from "react";
import { useState } from "react"; import { useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { toast } from "sonner"; import { toast } from "sonner";
@ -17,15 +17,24 @@ 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 { Calendar, Clock, User } from "lucide-react";
import { doctorsService } from "services/doctorsApi.mjs";
// Interface para o estado local do formulário (sem alterações) // Interface para o estado local do formulário (sem alterações)
interface AppointmentFormState { interface AppointmentFormState {
doctorId: string; id: string;
date: string; date: string;
time: string; time: string;
observations: string; observations: string;
} }
interface Doctor {
id: string;
full_name: string;
specialty: string;
phone_mobile: string;
}
// --- DADOS MOCKADOS (ALTERAÇÃO 1: Adicionando location e phone) --- // --- DADOS MOCKADOS (ALTERAÇÃO 1: Adicionando location e phone) ---
const doctors = [ const doctors = [
{ id: "1", name: "Dr. João Silva", specialty: "Cardiologia", location: "Consultório A - 2º andar", phone: "(11) 3333-4444" }, { id: "1", name: "Dr. João Silva", specialty: "Cardiologia", location: "Consultório A - 2º andar", phone: "(11) 3333-4444" },
@ -37,16 +46,40 @@ const availableTimes = ["09:00", "09:30", "10:00", "10:30", "14:00", "14:30", "1
export default function ScheduleAppointmentPage() { export default function ScheduleAppointmentPage() {
const router = useRouter(); const router = useRouter();
const [doctors, setDoctors] = useState<Doctor[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// [SINCRONIZAÇÃO 1 - continuação] - Obtendo a lista de agendamentos existentes // [SINCRONIZAÇÃO 1 - continuação] - Obtendo a lista de agendamentos existentes
const { addAppointment, appointments } = useAppointments(); const { addAppointment, appointments } = useAppointments();
const [formData, setFormData] = useState<AppointmentFormState>({ const [formData, setFormData] = useState<AppointmentFormState>({
doctorId: "", id: "",
date: "", date: "",
time: "", time: "",
observations: "", observations: "",
}); });
const fetchDoctors = useCallback(async () => {
setLoading(true);
setError(null);
try {
const data: Doctor[] = await doctorsService.list();
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);
}
}, []);
useEffect(() => {
fetchDoctors();
}, [fetchDoctors]);
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => { const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const { name, value } = e.target; const { name, value } = e.target;
setFormData(prevState => ({ ...prevState, [name]: value })); setFormData(prevState => ({ ...prevState, [name]: value }));
@ -58,18 +91,18 @@ export default function ScheduleAppointmentPage() {
const handleSubmit = (e: React.FormEvent) => { const handleSubmit = (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
if (!formData.doctorId || !formData.date || !formData.time) { if (!formData.id || !formData.date || !formData.time) {
toast.error("Por favor, preencha os campos de médico, data e horário."); toast.error("Por favor, preencha os campos de médico, data e horário.");
return; return;
} }
const selectedDoctor = doctors.find(doc => doc.id === formData.doctorId); const selectedDoctor = doctors.find(doc => doc.id === formData.id);
if (!selectedDoctor) return; if (!selectedDoctor) return;
// Validação de conflito (sem alterações, já estava correta) // Validação de conflito (sem alterações, já estava correta)
const isConflict = appointments.some( const isConflict = appointments.some(
(apt) => (apt) =>
apt.doctorName === selectedDoctor.name && apt.doctorName === selectedDoctor.full_name &&
apt.date === formData.date && apt.date === formData.date &&
apt.time === formData.time apt.time === formData.time
); );
@ -82,13 +115,13 @@ export default function ScheduleAppointmentPage() {
// [ALTERAÇÃO 2] - Utilizando os dados do médico selecionado para location e phone // [ALTERAÇÃO 2] - Utilizando os dados do médico selecionado para location e phone
// e removendo os placeholders. // e removendo os placeholders.
addAppointment({ addAppointment({
doctorName: selectedDoctor.name, doctorName: selectedDoctor.full_name,
specialty: selectedDoctor.specialty, specialty: selectedDoctor.specialty,
date: formData.date, date: formData.date,
time: formData.time, time: formData.time,
observations: formData.observations, observations: formData.observations,
location: selectedDoctor.location, // Usando a localização do médico phone: selectedDoctor.phone_mobile,
phone: selectedDoctor.phone, // Usando o telefone do médico location: ""
}); });
toast.success("Consulta agendada com sucesso!"); toast.success("Consulta agendada com sucesso!");
@ -118,8 +151,8 @@ export default function ScheduleAppointmentPage() {
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="doctor">Médico</Label> <Label htmlFor="doctor">Médico</Label>
<Select <Select
value={formData.doctorId} value={formData.id}
onValueChange={(value) => handleSelectChange('doctorId', value)} onValueChange={(value) => handleSelectChange('id', value)}
> >
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder="Seleione um médico" /> <SelectValue placeholder="Seleione um médico" />
@ -127,7 +160,7 @@ export default function ScheduleAppointmentPage() {
<SelectContent> <SelectContent>
{doctors.map((doctor) => ( {doctors.map((doctor) => (
<SelectItem key={doctor.id} value={doctor.id}> <SelectItem key={doctor.id} value={doctor.id}>
{doctor.name} - {doctor.specialty} {doctor.full_name} - {doctor.specialty}
</SelectItem> </SelectItem>
))} ))}
</SelectContent> </SelectContent>
@ -195,10 +228,10 @@ export default function ScheduleAppointmentPage() {
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
<CardContent className="space-y-3 text-sm"> <CardContent className="space-y-3 text-sm">
{formData.doctorId ? ( {formData.id ? (
<div className="flex items-center"> <div className="flex items-center">
<User className="mr-2 h-4 w-4 text-gray-500" /> <User className="mr-2 h-4 w-4 text-gray-500" />
<span>{doctors.find((d) => d.id === formData.doctorId)?.name}</span> <span>{doctors.find((d) => d.id === formData.id)?.full_name}</span>
</div> </div>
) : <p className="text-gray-500">Preencha o formulário...</p>} ) : <p className="text-gray-500">Preencha o formulário...</p>}