add-list-appointments-endpoints

This commit is contained in:
João Gustavo 2025-10-18 14:52:26 -03:00
parent 84cc56b017
commit 23e0765c5b
2 changed files with 269 additions and 180 deletions

View File

@ -1,7 +1,7 @@
"use client"; "use client";
import Link from "next/link"; import Link from "next/link";
import { useState } from "react"; import { useEffect, useState } from "react";
import { import {
MoreHorizontal, MoreHorizontal,
PlusCircle, PlusCircle,
@ -10,6 +10,7 @@ import {
Edit, Edit,
Trash2, Trash2,
ArrowLeft, ArrowLeft,
Loader2,
} from "lucide-react"; } from "lucide-react";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
@ -53,10 +54,10 @@ import {
SelectValue, SelectValue,
} from "@/components/ui/select"; } from "@/components/ui/select";
import { mockAppointments, mockProfessionals } from "@/lib/mocks/appointment-mocks"; import { mockProfessionals } from "@/lib/mocks/appointment-mocks";
import { listarAgendamentos, buscarPacientesPorIds, buscarMedicosPorIds } from "@/lib/api";
import { CalendarRegistrationForm } from "@/components/forms/calendar-registration-form"; import { CalendarRegistrationForm } from "@/components/forms/calendar-registration-form";
const formatDate = (date: string | Date) => { const formatDate = (date: string | Date) => {
if (!date) return ""; if (!date) return "";
return new Date(date).toLocaleDateString("pt-BR", { return new Date(date).toLocaleDateString("pt-BR", {
@ -69,37 +70,41 @@ const formatDate = (date: string | Date) => {
}; };
const capitalize = (s: string) => { const capitalize = (s: string) => {
if (typeof s !== 'string' || s.length === 0) return ''; if (typeof s !== "string" || s.length === 0) return "";
return s.charAt(0).toUpperCase() + s.slice(1); return s.charAt(0).toUpperCase() + s.slice(1);
}; };
export default function ConsultasPage() { export default function ConsultasPage() {
const [appointments, setAppointments] = useState(mockAppointments); const [appointments, setAppointments] = useState<any[]>([]);
const [isLoading, setIsLoading] = useState<boolean>(true);
const [showForm, setShowForm] = useState(false); const [showForm, setShowForm] = useState(false);
const [editingAppointment, setEditingAppointment] = useState<any | null>(null); const [editingAppointment, setEditingAppointment] = useState<any | null>(null);
const [viewingAppointment, setViewingAppointment] = useState<any | null>(null); const [viewingAppointment, setViewingAppointment] = useState<any | null>(null);
const mapAppointmentToFormData = (appointment: any) => { const mapAppointmentToFormData = (appointment: any) => {
const professional = mockProfessionals.find(p => p.id === appointment.professional); const professional = mockProfessionals.find((p) => p.id === appointment.professional);
const appointmentDate = new Date(appointment.time); const appointmentDate = new Date(appointment.time || appointment.scheduled_at || Date.now());
return { return {
id: appointment.id, id: appointment.id,
patientName: appointment.patient, patientName: appointment.patient,
professionalName: professional ? professional.name : '', professionalName: professional ? professional.name : "",
appointmentDate: appointmentDate.toISOString().split('T')[0], appointmentDate: appointmentDate.toISOString().split("T")[0],
startTime: appointmentDate.toTimeString().split(' ')[0].substring(0, 5), startTime: appointmentDate.toTimeString().split(" ")[0].substring(0, 5),
endTime: new Date(appointmentDate.getTime() + appointment.duration * 60000).toTimeString().split(' ')[0].substring(0, 5), endTime: new Date(appointmentDate.getTime() + (appointment.duration || 30) * 60000)
status: appointment.status, .toTimeString()
appointmentType: appointment.type, .split(" ")[0]
notes: appointment.notes, .substring(0, 5),
cpf: '', status: appointment.status,
rg: '', appointmentType: appointment.type,
birthDate: '', notes: appointment.notes || "",
phoneCode: '+55', cpf: "",
phoneNumber: '', rg: "",
email: '', birthDate: "",
unit: 'nei', phoneCode: "+55",
phoneNumber: "",
email: "",
unit: "nei",
}; };
}; };
@ -114,7 +119,7 @@ export default function ConsultasPage() {
setEditingAppointment(formData); setEditingAppointment(formData);
setShowForm(true); setShowForm(true);
}; };
const handleView = (appointment: any) => { const handleView = (appointment: any) => {
setViewingAppointment(appointment); setViewingAppointment(appointment);
}; };
@ -125,40 +130,116 @@ export default function ConsultasPage() {
}; };
const handleSave = (formData: any) => { const handleSave = (formData: any) => {
const updatedAppointment = { const updatedAppointment = {
id: formData.id, id: formData.id,
patient: formData.patientName, patient: formData.patientName,
time: new Date(`${formData.appointmentDate}T${formData.startTime}`).toISOString(), time: new Date(`${formData.appointmentDate}T${formData.startTime}`).toISOString(),
duration: 30, duration: 30,
type: formData.appointmentType as any, type: formData.appointmentType as any,
status: formData.status as any, status: formData.status as any,
professional: appointments.find(a => a.id === formData.id)?.professional || '', professional: appointments.find((a) => a.id === formData.id)?.professional || "",
notes: formData.notes, notes: formData.notes,
}; };
setAppointments(prev => setAppointments((prev) => prev.map((a) => (a.id === updatedAppointment.id ? updatedAppointment : a)));
prev.map(a => a.id === updatedAppointment.id ? updatedAppointment : a) handleCancel();
);
handleCancel();
}; };
useEffect(() => {
let mounted = true;
async function load() {
try {
const arr = await listarAgendamentos("select=*&order=scheduled_at.desc&limit=200");
if (!mounted) return;
// Collect unique patient_ids and doctor_ids
const patientIds = new Set<string>();
const doctorIds = new Set<string>();
for (const a of arr || []) {
if (a.patient_id) patientIds.add(String(a.patient_id));
if (a.doctor_id) doctorIds.add(String(a.doctor_id));
}
// Batch fetch patients and doctors
const patientsMap = new Map<string, any>();
const doctorsMap = new Map<string, any>();
try {
if (patientIds.size) {
const list = await buscarPacientesPorIds(Array.from(patientIds));
for (const p of list || []) patientsMap.set(String(p.id), p);
}
} catch (e) {
console.warn("[ConsultasPage] Falha ao buscar pacientes em lote", e);
}
try {
if (doctorIds.size) {
const list = await buscarMedicosPorIds(Array.from(doctorIds));
for (const d of list || []) doctorsMap.set(String(d.id), d);
}
} catch (e) {
console.warn("[ConsultasPage] Falha ao buscar médicos em lote", e);
}
// Map appointments using the maps
const mapped = (arr || []).map((a: any) => {
const patient = a.patient_id ? patientsMap.get(String(a.patient_id))?.full_name || String(a.patient_id) : "";
const professional = a.doctor_id ? doctorsMap.get(String(a.doctor_id))?.full_name || String(a.doctor_id) : "";
return {
id: a.id,
patient,
time: a.scheduled_at || a.created_at || "",
duration: a.duration_minutes || 30,
type: a.appointment_type || "presencial",
status: a.status || "requested",
professional,
notes: a.notes || a.patient_notes || "",
};
});
setAppointments(mapped);
setIsLoading(false);
} catch (err) {
console.warn("[ConsultasPage] Falha ao carregar agendamentos, usando mocks", err);
setAppointments([]);
setIsLoading(false);
}
}
load();
return () => {
mounted = false;
};
}, []);
// editing view: render the calendar registration form with controlled data
if (showForm && editingAppointment) { if (showForm && editingAppointment) {
const [localForm, setLocalForm] = useState<any>(editingAppointment);
const onFormChange = (d: any) => setLocalForm(d);
const saveLocal = () => {
handleSave(localForm);
};
return ( return (
<div className="space-y-6 p-6 bg-background"> <div className="space-y-6 p-6 bg-background">
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
<Button type="button" variant="ghost" size="icon" onClick={handleCancel}> <Button type="button" variant="ghost" size="icon" onClick={handleCancel}>
<ArrowLeft className="h-4 w-4" /> <ArrowLeft className="h-4 w-4" />
</Button> </Button>
<h1 className="text-lg font-semibold md:text-2xl">Editar Consulta</h1> <h1 className="text-lg font-semibold md:text-2xl">Editar Consulta</h1>
</div>
<CalendarRegistrationForm
initialData={editingAppointment}
onSave={handleSave}
onCancel={handleCancel}
/>
</div> </div>
) <CalendarRegistrationForm formData={localForm} onFormChange={onFormChange} />
<div className="flex gap-2 justify-end">
<Button variant="outline" onClick={handleCancel}>
Cancelar
</Button>
<Button onClick={saveLocal}>Salvar</Button>
</div>
</div>
);
} }
return ( return (
@ -172,9 +253,7 @@ export default function ConsultasPage() {
<Link href="/agenda"> <Link href="/agenda">
<Button size="sm" className="h-8 gap-1"> <Button size="sm" className="h-8 gap-1">
<PlusCircle className="h-3.5 w-3.5" /> <PlusCircle className="h-3.5 w-3.5" />
<span className="sr-only sm:not-sr-only sm:whitespace-nowrap"> <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">Agendar Nova Consulta</span>
Agendar Nova Consulta
</span>
</Button> </Button>
</Link> </Link>
</div> </div>
@ -183,17 +262,11 @@ export default function ConsultasPage() {
<Card> <Card>
<CardHeader> <CardHeader>
<CardTitle>Consultas Agendadas</CardTitle> <CardTitle>Consultas Agendadas</CardTitle>
<CardDescription> <CardDescription>Visualize, filtre e gerencie todas as consultas da clínica.</CardDescription>
Visualize, filtre e gerencie todas as consultas da clínica.
</CardDescription>
<div className="pt-4 flex flex-wrap items-center gap-4"> <div className="pt-4 flex flex-wrap items-center gap-4">
<div className="relative flex-1 min-w-[250px]"> <div className="relative flex-1 min-w-[250px]">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" /> <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
<Input <Input type="search" placeholder="Buscar por..." className="pl-8 w-full" />
type="search"
placeholder="Buscar por..."
className="pl-8 w-full"
/>
</div> </div>
<Select> <Select>
<SelectTrigger className="w-[180px]"> <SelectTrigger className="w-[180px]">
@ -210,80 +283,79 @@ export default function ConsultasPage() {
</div> </div>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<Table> {isLoading ? (
<TableHeader> <div className="w-full py-12 flex justify-center items-center">
<TableRow> <Loader2 className="animate-spin mr-2" />
<TableHead>Paciente</TableHead> <span>Carregando agendamentos...</span>
<TableHead>Médico</TableHead> </div>
<TableHead>Status</TableHead> ) : (
<TableHead>Data e Hora</TableHead> <Table>
<TableHead>Ações</TableHead> <TableHeader>
</TableRow> <TableRow>
</TableHeader> <TableHead>Paciente</TableHead>
<TableBody> <TableHead>Médico</TableHead>
{appointments.map((appointment) => { <TableHead>Status</TableHead>
const professional = mockProfessionals.find( <TableHead>Data e Hora</TableHead>
(p) => p.id === appointment.professional <TableHead>Ações</TableHead>
); </TableRow>
return ( </TableHeader>
<TableRow key={appointment.id}> <TableBody>
<TableCell className="font-medium"> {appointments.map((appointment) => {
{appointment.patient} // appointment.professional may now contain the doctor's name (resolved)
</TableCell> const professionalLookup = mockProfessionals.find((p) => p.id === appointment.professional);
<TableCell> const professionalName = typeof appointment.professional === "string" && appointment.professional && !professionalLookup
{professional ? professional.name : "Não encontrado"} ? appointment.professional
</TableCell> : (professionalLookup ? professionalLookup.name : (appointment.professional || "Não encontrado"));
<TableCell>
<Badge return (
variant={ <TableRow key={appointment.id}>
appointment.status === "confirmed" <TableCell className="font-medium">{appointment.patient}</TableCell>
? "default" <TableCell>{professionalName}</TableCell>
: appointment.status === "pending" <TableCell>
? "secondary" <Badge
: "destructive" variant={
} appointment.status === "confirmed"
className={ ? "default"
appointment.status === "confirmed" ? "bg-green-600" : "" : appointment.status === "pending"
} ? "secondary"
> : "destructive"
{capitalize(appointment.status)} }
</Badge> className={appointment.status === "confirmed" ? "bg-green-600" : ""}
</TableCell> >
<TableCell>{formatDate(appointment.time)}</TableCell> {capitalize(appointment.status)}
<TableCell> </Badge>
<DropdownMenu> </TableCell>
<DropdownMenuTrigger asChild> <TableCell>{formatDate(appointment.time)}</TableCell>
<button className="h-8 w-8 p-0 flex items-center justify-center rounded-md hover:bg-accent"> <TableCell>
<span className="sr-only">Abrir menu</span> <DropdownMenu>
<MoreHorizontal className="h-4 w-4" /> <DropdownMenuTrigger asChild>
</button> <button className="h-8 w-8 p-0 flex items-center justify-center rounded-md hover:bg-accent">
</DropdownMenuTrigger> <span className="sr-only">Abrir menu</span>
<DropdownMenuContent align="end"> <MoreHorizontal className="h-4 w-4" />
<DropdownMenuItem </button>
onClick={() => handleView(appointment)} </DropdownMenuTrigger>
> <DropdownMenuContent align="end">
<Eye className="mr-2 h-4 w-4" /> <DropdownMenuItem onClick={() => handleView(appointment)}>
Ver <Eye className="mr-2 h-4 w-4" />
</DropdownMenuItem> Ver
<DropdownMenuItem onClick={() => handleEdit(appointment)}> </DropdownMenuItem>
<Edit className="mr-2 h-4 w-4" /> <DropdownMenuItem onClick={() => handleEdit(appointment)}>
Editar <Edit className="mr-2 h-4 w-4" />
</DropdownMenuItem> Editar
<DropdownMenuItem </DropdownMenuItem>
onClick={() => handleDelete(appointment.id)} <DropdownMenuItem onClick={() => handleDelete(appointment.id)} className="text-destructive">
className="text-destructive" <Trash2 className="mr-2 h-4 w-4" />
> Excluir
<Trash2 className="mr-2 h-4 w-4" /> </DropdownMenuItem>
Excluir </DropdownMenuContent>
</DropdownMenuItem> </DropdownMenu>
</DropdownMenuContent> </TableCell>
</DropdownMenu> </TableRow>
</TableCell> );
</TableRow> })}
); </TableBody>
})} </Table>
</TableBody> )}
</Table>
</CardContent> </CardContent>
</Card> </Card>
@ -292,62 +364,44 @@ export default function ConsultasPage() {
<DialogContent> <DialogContent>
<DialogHeader> <DialogHeader>
<DialogTitle>Detalhes da Consulta</DialogTitle> <DialogTitle>Detalhes da Consulta</DialogTitle>
<DialogDescription> <DialogDescription>Informações detalhadas da consulta de {viewingAppointment?.patient}.</DialogDescription>
Informações detalhadas da consulta de {viewingAppointment?.patient}.
</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 grid-cols-4 items-center gap-4">
<Label htmlFor="name" className="text-right"> <Label htmlFor="name" className="text-right">Paciente</Label>
Paciente
</Label>
<span className="col-span-3">{viewingAppointment?.patient}</span> <span className="col-span-3">{viewingAppointment?.patient}</span>
</div> </div>
<div className="grid grid-cols-4 items-center gap-4"> <div className="grid grid-cols-4 items-center gap-4">
<Label className="text-right"> <Label className="text-right">Médico</Label>
Médico <span className="col-span-3">{viewingAppointment?.professional || 'Não encontrado'}</span>
</Label>
<span className="col-span-3">
{mockProfessionals.find(p => p.id === viewingAppointment?.professional)?.name || "Não encontrado"}
</span>
</div> </div>
<div className="grid grid-cols-4 items-center gap-4"> <div className="grid grid-cols-4 items-center gap-4">
<Label className="text-right"> <Label className="text-right">Data e Hora</Label>
Data e Hora
</Label>
<span className="col-span-3">{viewingAppointment?.time ? formatDate(viewingAppointment.time) : ''}</span> <span className="col-span-3">{viewingAppointment?.time ? formatDate(viewingAppointment.time) : ''}</span>
</div> </div>
<div className="grid grid-cols-4 items-center gap-4"> <div className="grid grid-cols-4 items-center gap-4">
<Label className="text-right"> <Label className="text-right">Status</Label>
Status
</Label>
<span className="col-span-3"> <span className="col-span-3">
<Badge <Badge
variant={ variant={
viewingAppointment?.status === "confirmed" viewingAppointment?.status === "confirmed"
? "default" ? "default"
: viewingAppointment?.status === "pending" : viewingAppointment?.status === "pending"
? "secondary" ? "secondary"
: "destructive" : "destructive"
} }
className={ className={viewingAppointment?.status === "confirmed" ? "bg-green-600" : ""}
viewingAppointment?.status === "confirmed" ? "bg-green-600" : "" >
} {capitalize(viewingAppointment?.status || "")}
> </Badge>
{capitalize(viewingAppointment?.status || '')}
</Badge>
</span> </span>
</div> </div>
<div className="grid grid-cols-4 items-center gap-4"> <div className="grid grid-cols-4 items-center gap-4">
<Label className="text-right"> <Label className="text-right">Tipo</Label>
Tipo <span className="col-span-3">{capitalize(viewingAppointment?.type || "")}</span>
</Label>
<span className="col-span-3">{capitalize(viewingAppointment?.type || '')}</span>
</div> </div>
<div className="grid grid-cols-4 items-center gap-4"> <div className="grid grid-cols-4 items-center gap-4">
<Label className="text-right"> <Label className="text-right">Observações</Label>
Observações
</Label>
<span className="col-span-3">{viewingAppointment?.notes || "Nenhuma"}</span> <span className="col-span-3">{viewingAppointment?.notes || "Nenhuma"}</span>
</div> </div>
</div> </div>
@ -358,5 +412,5 @@ export default function ConsultasPage() {
</Dialog> </Dialog>
)} )}
</div> </div>
); );
} }

View File

@ -944,6 +944,41 @@ export type Report = {
created_by?: string; created_by?: string;
}; };
// ===== AGENDAMENTOS =====
export type Appointment = {
id: string;
order_number?: string | null;
patient_id?: string | null;
doctor_id?: string | null;
scheduled_at?: string | null;
duration_minutes?: number | null;
appointment_type?: string | null;
status?: string | null;
chief_complaint?: string | null;
patient_notes?: string | null;
notes?: string | null;
insurance_provider?: string | null;
checked_in_at?: string | null;
completed_at?: string | null;
cancelled_at?: string | null;
cancellation_reason?: string | null;
created_at?: string | null;
updated_at?: string | null;
created_by?: string | null;
updated_by?: string | null;
};
/**
* Lista agendamentos via REST (GET /rest/v1/appointments)
* Aceita query string completa (ex: `?select=*&limit=100&order=scheduled_at.desc`)
*/
export async function listarAgendamentos(query?: string): Promise<Appointment[]> {
const qs = query && String(query).trim() ? (String(query).startsWith('?') ? query : `?${query}`) : '';
const url = `${REST}/appointments${qs}`;
const res = await fetch(url, { method: 'GET', headers: baseHeaders() });
return await parse<Appointment[]>(res);
}
/** /**
* Buscar relatório por ID (tenta múltiplas estratégias: id, order_number, patient_id) * Buscar relatório por ID (tenta múltiplas estratégias: id, order_number, patient_id)
* Retorna o primeiro relatório encontrado ou lança erro 404 quando não achar. * Retorna o primeiro relatório encontrado ou lança erro 404 quando não achar.