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";
import Link from "next/link";
import { useState } from "react";
import { useEffect, useState } from "react";
import {
MoreHorizontal,
PlusCircle,
@ -10,6 +10,7 @@ import {
Edit,
Trash2,
ArrowLeft,
Loader2,
} from "lucide-react";
import { Badge } from "@/components/ui/badge";
@ -53,10 +54,10 @@ import {
SelectValue,
} 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";
const formatDate = (date: string | Date) => {
if (!date) return "";
return new Date(date).toLocaleDateString("pt-BR", {
@ -69,37 +70,41 @@ const formatDate = (date: string | Date) => {
};
const capitalize = (s: string) => {
if (typeof s !== 'string' || s.length === 0) return '';
return s.charAt(0).toUpperCase() + s.slice(1);
if (typeof s !== "string" || s.length === 0) return "";
return s.charAt(0).toUpperCase() + s.slice(1);
};
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 [editingAppointment, setEditingAppointment] = useState<any | null>(null);
const [viewingAppointment, setViewingAppointment] = useState<any | null>(null);
const mapAppointmentToFormData = (appointment: any) => {
const professional = mockProfessionals.find(p => p.id === appointment.professional);
const appointmentDate = new Date(appointment.time);
const professional = mockProfessionals.find((p) => p.id === appointment.professional);
const appointmentDate = new Date(appointment.time || appointment.scheduled_at || Date.now());
return {
id: appointment.id,
patientName: appointment.patient,
professionalName: professional ? professional.name : '',
appointmentDate: appointmentDate.toISOString().split('T')[0],
startTime: appointmentDate.toTimeString().split(' ')[0].substring(0, 5),
endTime: new Date(appointmentDate.getTime() + appointment.duration * 60000).toTimeString().split(' ')[0].substring(0, 5),
status: appointment.status,
appointmentType: appointment.type,
notes: appointment.notes,
cpf: '',
rg: '',
birthDate: '',
phoneCode: '+55',
phoneNumber: '',
email: '',
unit: 'nei',
id: appointment.id,
patientName: appointment.patient,
professionalName: professional ? professional.name : "",
appointmentDate: appointmentDate.toISOString().split("T")[0],
startTime: appointmentDate.toTimeString().split(" ")[0].substring(0, 5),
endTime: new Date(appointmentDate.getTime() + (appointment.duration || 30) * 60000)
.toTimeString()
.split(" ")[0]
.substring(0, 5),
status: appointment.status,
appointmentType: appointment.type,
notes: appointment.notes || "",
cpf: "",
rg: "",
birthDate: "",
phoneCode: "+55",
phoneNumber: "",
email: "",
unit: "nei",
};
};
@ -125,40 +130,116 @@ export default function ConsultasPage() {
};
const handleSave = (formData: any) => {
const updatedAppointment = {
id: formData.id,
patient: formData.patientName,
time: new Date(`${formData.appointmentDate}T${formData.startTime}`).toISOString(),
duration: 30,
type: formData.appointmentType as any,
status: formData.status as any,
professional: appointments.find(a => a.id === formData.id)?.professional || '',
notes: formData.notes,
id: formData.id,
patient: formData.patientName,
time: new Date(`${formData.appointmentDate}T${formData.startTime}`).toISOString(),
duration: 30,
type: formData.appointmentType as any,
status: formData.status as any,
professional: appointments.find((a) => a.id === formData.id)?.professional || "",
notes: formData.notes,
};
setAppointments(prev =>
prev.map(a => a.id === updatedAppointment.id ? updatedAppointment : a)
);
setAppointments((prev) => prev.map((a) => (a.id === updatedAppointment.id ? updatedAppointment : a)));
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) {
const [localForm, setLocalForm] = useState<any>(editingAppointment);
const onFormChange = (d: any) => setLocalForm(d);
const saveLocal = () => {
handleSave(localForm);
};
return (
<div className="space-y-6 p-6 bg-background">
<div className="flex items-center gap-4">
<Button type="button" variant="ghost" size="icon" onClick={handleCancel}>
<ArrowLeft className="h-4 w-4" />
</Button>
<h1 className="text-lg font-semibold md:text-2xl">Editar Consulta</h1>
</div>
<CalendarRegistrationForm
initialData={editingAppointment}
onSave={handleSave}
onCancel={handleCancel}
/>
<div className="space-y-6 p-6 bg-background">
<div className="flex items-center gap-4">
<Button type="button" variant="ghost" size="icon" onClick={handleCancel}>
<ArrowLeft className="h-4 w-4" />
</Button>
<h1 className="text-lg font-semibold md:text-2xl">Editar Consulta</h1>
</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 (
@ -172,9 +253,7 @@ export default function ConsultasPage() {
<Link href="/agenda">
<Button size="sm" className="h-8 gap-1">
<PlusCircle className="h-3.5 w-3.5" />
<span className="sr-only sm:not-sr-only sm:whitespace-nowrap">
Agendar Nova Consulta
</span>
<span className="sr-only sm:not-sr-only sm:whitespace-nowrap">Agendar Nova Consulta</span>
</Button>
</Link>
</div>
@ -183,17 +262,11 @@ export default function ConsultasPage() {
<Card>
<CardHeader>
<CardTitle>Consultas Agendadas</CardTitle>
<CardDescription>
Visualize, filtre e gerencie todas as consultas da clínica.
</CardDescription>
<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="relative flex-1 min-w-[250px]">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
type="search"
placeholder="Buscar por..."
className="pl-8 w-full"
/>
<Input type="search" placeholder="Buscar por..." className="pl-8 w-full" />
</div>
<Select>
<SelectTrigger className="w-[180px]">
@ -210,80 +283,79 @@ export default function ConsultasPage() {
</div>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>Paciente</TableHead>
<TableHead>Médico</TableHead>
<TableHead>Status</TableHead>
<TableHead>Data e Hora</TableHead>
<TableHead>Ações</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{appointments.map((appointment) => {
const professional = mockProfessionals.find(
(p) => p.id === appointment.professional
);
return (
<TableRow key={appointment.id}>
<TableCell className="font-medium">
{appointment.patient}
</TableCell>
<TableCell>
{professional ? professional.name : "Não encontrado"}
</TableCell>
<TableCell>
<Badge
variant={
appointment.status === "confirmed"
? "default"
: appointment.status === "pending"
? "secondary"
: "destructive"
}
className={
appointment.status === "confirmed" ? "bg-green-600" : ""
}
>
{capitalize(appointment.status)}
</Badge>
</TableCell>
<TableCell>{formatDate(appointment.time)}</TableCell>
<TableCell>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="h-8 w-8 p-0 flex items-center justify-center rounded-md hover:bg-accent">
<span className="sr-only">Abrir menu</span>
<MoreHorizontal className="h-4 w-4" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={() => handleView(appointment)}
>
<Eye className="mr-2 h-4 w-4" />
Ver
</DropdownMenuItem>
<DropdownMenuItem onClick={() => handleEdit(appointment)}>
<Edit className="mr-2 h-4 w-4" />
Editar
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => handleDelete(appointment.id)}
className="text-destructive"
>
<Trash2 className="mr-2 h-4 w-4" />
Excluir
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
{isLoading ? (
<div className="w-full py-12 flex justify-center items-center">
<Loader2 className="animate-spin mr-2" />
<span>Carregando agendamentos...</span>
</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Paciente</TableHead>
<TableHead>Médico</TableHead>
<TableHead>Status</TableHead>
<TableHead>Data e Hora</TableHead>
<TableHead>Ações</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{appointments.map((appointment) => {
// appointment.professional may now contain the doctor's name (resolved)
const professionalLookup = mockProfessionals.find((p) => p.id === appointment.professional);
const professionalName = typeof appointment.professional === "string" && appointment.professional && !professionalLookup
? appointment.professional
: (professionalLookup ? professionalLookup.name : (appointment.professional || "Não encontrado"));
return (
<TableRow key={appointment.id}>
<TableCell className="font-medium">{appointment.patient}</TableCell>
<TableCell>{professionalName}</TableCell>
<TableCell>
<Badge
variant={
appointment.status === "confirmed"
? "default"
: appointment.status === "pending"
? "secondary"
: "destructive"
}
className={appointment.status === "confirmed" ? "bg-green-600" : ""}
>
{capitalize(appointment.status)}
</Badge>
</TableCell>
<TableCell>{formatDate(appointment.time)}</TableCell>
<TableCell>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="h-8 w-8 p-0 flex items-center justify-center rounded-md hover:bg-accent">
<span className="sr-only">Abrir menu</span>
<MoreHorizontal className="h-4 w-4" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => handleView(appointment)}>
<Eye className="mr-2 h-4 w-4" />
Ver
</DropdownMenuItem>
<DropdownMenuItem onClick={() => handleEdit(appointment)}>
<Edit className="mr-2 h-4 w-4" />
Editar
</DropdownMenuItem>
<DropdownMenuItem onClick={() => handleDelete(appointment.id)} className="text-destructive">
<Trash2 className="mr-2 h-4 w-4" />
Excluir
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
)}
</CardContent>
</Card>
@ -292,62 +364,44 @@ export default function ConsultasPage() {
<DialogContent>
<DialogHeader>
<DialogTitle>Detalhes da Consulta</DialogTitle>
<DialogDescription>
Informações detalhadas da consulta de {viewingAppointment?.patient}.
</DialogDescription>
<DialogDescription>Informações detalhadas da consulta de {viewingAppointment?.patient}.</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="name" className="text-right">
Paciente
</Label>
<Label htmlFor="name" className="text-right">Paciente</Label>
<span className="col-span-3">{viewingAppointment?.patient}</span>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<Label className="text-right">
Médico
</Label>
<span className="col-span-3">
{mockProfessionals.find(p => p.id === viewingAppointment?.professional)?.name || "Não encontrado"}
</span>
<Label className="text-right">Médico</Label>
<span className="col-span-3">{viewingAppointment?.professional || 'Não encontrado'}</span>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<Label className="text-right">
Data e Hora
</Label>
<Label className="text-right">Data e Hora</Label>
<span className="col-span-3">{viewingAppointment?.time ? formatDate(viewingAppointment.time) : ''}</span>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<Label className="text-right">
Status
</Label>
<Label className="text-right">Status</Label>
<span className="col-span-3">
<Badge
variant={
viewingAppointment?.status === "confirmed"
? "default"
: viewingAppointment?.status === "pending"
? "secondary"
: "destructive"
}
className={
viewingAppointment?.status === "confirmed" ? "bg-green-600" : ""
}
>
{capitalize(viewingAppointment?.status || '')}
</Badge>
<Badge
variant={
viewingAppointment?.status === "confirmed"
? "default"
: viewingAppointment?.status === "pending"
? "secondary"
: "destructive"
}
className={viewingAppointment?.status === "confirmed" ? "bg-green-600" : ""}
>
{capitalize(viewingAppointment?.status || "")}
</Badge>
</span>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<Label className="text-right">
Tipo
</Label>
<span className="col-span-3">{capitalize(viewingAppointment?.type || '')}</span>
<div className="grid grid-cols-4 items-center gap-4">
<Label className="text-right">Tipo</Label>
<span className="col-span-3">{capitalize(viewingAppointment?.type || "")}</span>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<Label className="text-right">
Observações
</Label>
<div className="grid grid-cols-4 items-center gap-4">
<Label className="text-right">Observações</Label>
<span className="col-span-3">{viewingAppointment?.notes || "Nenhuma"}</span>
</div>
</div>
@ -358,5 +412,5 @@ export default function ConsultasPage() {
</Dialog>
)}
</div>
);
}
);
}

View File

@ -944,6 +944,41 @@ export type Report = {
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)
* Retorna o primeiro relatório encontrado ou lança erro 404 quando não achar.