Merge pull request 'feature/add-appointments-endpoint' (#52) from feature/add-appointments-endpoint into develop
Reviewed-on: #52
This commit is contained in:
commit
8281d2ce5c
@ -11,10 +11,7 @@ import { EventInput } from "@fullcalendar/core/index.js";
|
|||||||
import { Sidebar } from "@/components/dashboard/sidebar";
|
import { Sidebar } from "@/components/dashboard/sidebar";
|
||||||
import { PagesHeader } from "@/components/dashboard/header";
|
import { PagesHeader } from "@/components/dashboard/header";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import { mockWaitingList } from "@/lib/mocks/appointment-mocks";
|
||||||
mockAppointments,
|
|
||||||
mockWaitingList,
|
|
||||||
} from "@/lib/mocks/appointment-mocks";
|
|
||||||
import "./index.css";
|
import "./index.css";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import {
|
import {
|
||||||
@ -30,7 +27,7 @@ const ListaEspera = dynamic(
|
|||||||
);
|
);
|
||||||
|
|
||||||
export default function AgendamentoPage() {
|
export default function AgendamentoPage() {
|
||||||
const [appointments, setAppointments] = useState(mockAppointments);
|
const [appointments, setAppointments] = useState<any[]>([]);
|
||||||
const [waitingList, setWaitingList] = useState(mockWaitingList);
|
const [waitingList, setWaitingList] = useState(mockWaitingList);
|
||||||
const [activeTab, setActiveTab] = useState<"calendar" | "espera">("calendar");
|
const [activeTab, setActiveTab] = useState<"calendar" | "espera">("calendar");
|
||||||
const [requestsList, setRequestsList] = useState<EventInput[]>();
|
const [requestsList, setRequestsList] = useState<EventInput[]>();
|
||||||
@ -47,23 +44,51 @@ export default function AgendamentoPage() {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let events: EventInput[] = [];
|
// Fetch real appointments and map to calendar events
|
||||||
appointments.forEach((obj) => {
|
let mounted = true;
|
||||||
const event: EventInput = {
|
(async () => {
|
||||||
title: `${obj.patient}: ${obj.type}`,
|
try {
|
||||||
start: new Date(obj.time),
|
// listarAgendamentos accepts a query string; request a reasonable limit and order
|
||||||
end: new Date(new Date(obj.time).getTime() + obj.duration * 60 * 1000),
|
const arr = await (await import('@/lib/api')).listarAgendamentos('select=*&order=scheduled_at.desc&limit=500').catch(() => []);
|
||||||
color:
|
if (!mounted) return;
|
||||||
obj.status === "confirmed"
|
if (!arr || !arr.length) {
|
||||||
? "#68d68a"
|
setAppointments([]);
|
||||||
: obj.status === "pending"
|
setRequestsList([]);
|
||||||
? "#ffe55f"
|
return;
|
||||||
: "#ff5f5fff",
|
}
|
||||||
};
|
|
||||||
events.push(event);
|
// Batch-fetch patient names for display
|
||||||
|
const patientIds = Array.from(new Set(arr.map((a: any) => a.patient_id).filter(Boolean)));
|
||||||
|
const patients = (patientIds && patientIds.length) ? await (await import('@/lib/api')).buscarPacientesPorIds(patientIds) : [];
|
||||||
|
const patientsById: Record<string, any> = {};
|
||||||
|
(patients || []).forEach((p: any) => { if (p && p.id) patientsById[String(p.id)] = p; });
|
||||||
|
|
||||||
|
setAppointments(arr || []);
|
||||||
|
|
||||||
|
const events: EventInput[] = (arr || []).map((obj: any) => {
|
||||||
|
const scheduled = obj.scheduled_at || obj.scheduledAt || obj.time || null;
|
||||||
|
const start = scheduled ? new Date(scheduled) : null;
|
||||||
|
const duration = Number(obj.duration_minutes ?? obj.duration ?? 30) || 30;
|
||||||
|
const patient = (patientsById[String(obj.patient_id)]?.full_name) || obj.patient_name || obj.patient_full_name || obj.patient || 'Paciente';
|
||||||
|
const title = `${patient}: ${obj.appointment_type ?? obj.type ?? ''}`.trim();
|
||||||
|
const color = obj.status === 'confirmed' ? '#68d68a' : obj.status === 'pending' ? '#ffe55f' : '#ff5f5fff';
|
||||||
|
return {
|
||||||
|
title,
|
||||||
|
start: start || new Date(),
|
||||||
|
end: start ? new Date(start.getTime() + duration * 60 * 1000) : undefined,
|
||||||
|
color,
|
||||||
|
extendedProps: { raw: obj },
|
||||||
|
} as EventInput;
|
||||||
});
|
});
|
||||||
setRequestsList(events);
|
setRequestsList(events || []);
|
||||||
}, [appointments]);
|
} catch (err) {
|
||||||
|
console.warn('[AgendamentoPage] falha ao carregar agendamentos', err);
|
||||||
|
setAppointments([]);
|
||||||
|
setRequestsList([]);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return () => { mounted = false; };
|
||||||
|
}, []);
|
||||||
|
|
||||||
// mantive para caso a lógica de salvar consulta passe a funcionar
|
// mantive para caso a lógica de salvar consulta passe a funcionar
|
||||||
const handleSaveAppointment = (appointment: any) => {
|
const handleSaveAppointment = (appointment: any) => {
|
||||||
|
|||||||
@ -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, useCallback } 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, atualizarAgendamento, buscarAgendamentoPorId, deletarAgendamento } 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,43 +70,81 @@ 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 [originalAppointments, setOriginalAppointments] = useState<any[]>([]);
|
||||||
|
const [searchValue, setSearchValue] = useState<string>('');
|
||||||
|
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);
|
||||||
|
// Local form state used when editing. Keep hook at top-level to avoid Hooks order changes.
|
||||||
|
const [localForm, setLocalForm] = useState<any | null>(null);
|
||||||
|
|
||||||
const mapAppointmentToFormData = (appointment: any) => {
|
const mapAppointmentToFormData = (appointment: any) => {
|
||||||
const professional = mockProfessionals.find(p => p.id === appointment.professional);
|
// prefer scheduled_at (ISO) if available
|
||||||
const appointmentDate = new Date(appointment.time);
|
const scheduledBase = appointment.scheduled_at || appointment.time || appointment.created_at || null;
|
||||||
|
const baseDate = scheduledBase ? new Date(scheduledBase) : new Date();
|
||||||
|
const duration = appointment.duration_minutes ?? appointment.duration ?? 30;
|
||||||
|
|
||||||
|
// compute start and end times (HH:MM)
|
||||||
|
const appointmentDateStr = baseDate.toISOString().split("T")[0];
|
||||||
|
const startTime = `${String(baseDate.getHours()).padStart(2, '0')}:${String(baseDate.getMinutes()).padStart(2, '0')}`;
|
||||||
|
const endDate = new Date(baseDate.getTime() + duration * 60000);
|
||||||
|
const endTime = `${String(endDate.getHours()).padStart(2, '0')}:${String(endDate.getMinutes()).padStart(2, '0')}`;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: appointment.id,
|
id: appointment.id,
|
||||||
patientName: appointment.patient,
|
patientName: appointment.patient,
|
||||||
professionalName: professional ? professional.name : '',
|
patientId: appointment.patient_id || appointment.patientId || null,
|
||||||
appointmentDate: appointmentDate.toISOString().split('T')[0],
|
professionalName: appointment.professional || "",
|
||||||
startTime: appointmentDate.toTimeString().split(' ')[0].substring(0, 5),
|
appointmentDate: appointmentDateStr,
|
||||||
endTime: new Date(appointmentDate.getTime() + appointment.duration * 60000).toTimeString().split(' ')[0].substring(0, 5),
|
startTime,
|
||||||
|
endTime,
|
||||||
status: appointment.status,
|
status: appointment.status,
|
||||||
appointmentType: appointment.type,
|
appointmentType: appointment.appointment_type || appointment.type,
|
||||||
notes: appointment.notes,
|
notes: appointment.notes || appointment.patient_notes || "",
|
||||||
cpf: '',
|
cpf: "",
|
||||||
rg: '',
|
rg: "",
|
||||||
birthDate: '',
|
birthDate: "",
|
||||||
phoneCode: '+55',
|
phoneCode: "+55",
|
||||||
phoneNumber: '',
|
phoneNumber: "",
|
||||||
email: '',
|
email: "",
|
||||||
unit: 'nei',
|
unit: "nei",
|
||||||
|
// API-editable fields (populate so the form shows existing values)
|
||||||
|
duration_minutes: duration,
|
||||||
|
chief_complaint: appointment.chief_complaint ?? null,
|
||||||
|
patient_notes: appointment.patient_notes ?? null,
|
||||||
|
insurance_provider: appointment.insurance_provider ?? null,
|
||||||
|
checked_in_at: appointment.checked_in_at ?? null,
|
||||||
|
completed_at: appointment.completed_at ?? null,
|
||||||
|
cancelled_at: appointment.cancelled_at ?? null,
|
||||||
|
cancellation_reason: appointment.cancellation_reason ?? appointment.cancellationReason ?? "",
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDelete = (appointmentId: string) => {
|
const handleDelete = async (appointmentId: string) => {
|
||||||
if (window.confirm("Tem certeza que deseja excluir esta consulta?")) {
|
if (!window.confirm("Tem certeza que deseja excluir esta consulta?")) return;
|
||||||
|
try {
|
||||||
|
// call server DELETE
|
||||||
|
await deletarAgendamento(appointmentId);
|
||||||
|
// remove from UI
|
||||||
setAppointments((prev) => prev.filter((a) => a.id !== appointmentId));
|
setAppointments((prev) => prev.filter((a) => a.id !== appointmentId));
|
||||||
|
// also update originalAppointments cache
|
||||||
|
setOriginalAppointments((prev) => (prev || []).filter((a) => a.id !== appointmentId));
|
||||||
|
alert('Agendamento excluído com sucesso.');
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[ConsultasPage] Falha ao excluir agendamento', err);
|
||||||
|
try {
|
||||||
|
const msg = err instanceof Error ? err.message : String(err);
|
||||||
|
alert('Falha ao excluir agendamento: ' + msg);
|
||||||
|
} catch (e) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -122,28 +161,241 @@ export default function ConsultasPage() {
|
|||||||
const handleCancel = () => {
|
const handleCancel = () => {
|
||||||
setEditingAppointment(null);
|
setEditingAppointment(null);
|
||||||
setShowForm(false);
|
setShowForm(false);
|
||||||
|
setLocalForm(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSave = (formData: any) => {
|
const handleSave = async (formData: any) => {
|
||||||
|
try {
|
||||||
|
// build scheduled_at ISO (formData.startTime is 'HH:MM')
|
||||||
|
const scheduled_at = new Date(`${formData.appointmentDate}T${formData.startTime}`).toISOString();
|
||||||
|
|
||||||
const updatedAppointment = {
|
// compute duration from start/end times when available
|
||||||
id: formData.id,
|
let duration_minutes = 30;
|
||||||
patient: formData.patientName,
|
try {
|
||||||
time: new Date(`${formData.appointmentDate}T${formData.startTime}`).toISOString(),
|
if (formData.startTime && formData.endTime) {
|
||||||
duration: 30,
|
const [sh, sm] = String(formData.startTime).split(":").map((n: string) => Number(n));
|
||||||
type: formData.appointmentType as any,
|
const [eh, em] = String(formData.endTime).split(":").map((n: string) => Number(n));
|
||||||
status: formData.status as any,
|
const start = (sh || 0) * 60 + (sm || 0);
|
||||||
professional: appointments.find(a => a.id === formData.id)?.professional || '',
|
const end = (eh || 0) * 60 + (em || 0);
|
||||||
notes: formData.notes,
|
if (!Number.isNaN(start) && !Number.isNaN(end) && end > start) duration_minutes = end - start;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// fallback to default
|
||||||
|
duration_minutes = 30;
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload: any = {
|
||||||
|
scheduled_at,
|
||||||
|
duration_minutes,
|
||||||
|
status: formData.status || undefined,
|
||||||
|
notes: formData.notes ?? null,
|
||||||
|
chief_complaint: formData.chief_complaint ?? null,
|
||||||
|
patient_notes: formData.patient_notes ?? null,
|
||||||
|
insurance_provider: formData.insurance_provider ?? null,
|
||||||
|
// convert local datetime-local inputs (which may be in 'YYYY-MM-DDTHH:MM' format) to proper ISO if present
|
||||||
|
checked_in_at: formData.checked_in_at ? new Date(formData.checked_in_at).toISOString() : null,
|
||||||
|
completed_at: formData.completed_at ? new Date(formData.completed_at).toISOString() : null,
|
||||||
|
cancelled_at: formData.cancelled_at ? new Date(formData.cancelled_at).toISOString() : null,
|
||||||
|
cancellation_reason: formData.cancellation_reason ?? null,
|
||||||
};
|
};
|
||||||
|
|
||||||
setAppointments(prev =>
|
// Call PATCH endpoint
|
||||||
prev.map(a => a.id === updatedAppointment.id ? updatedAppointment : a)
|
const updated = await atualizarAgendamento(formData.id, payload);
|
||||||
);
|
|
||||||
|
// Build UI-friendly row using server response and existing local fields
|
||||||
|
const existing = appointments.find((a) => a.id === formData.id) || {};
|
||||||
|
const mapped = {
|
||||||
|
id: updated.id,
|
||||||
|
patient: formData.patientName || existing.patient || '',
|
||||||
|
patient_id: existing.patient_id ?? null,
|
||||||
|
// preserve server-side fields so future edits read them
|
||||||
|
scheduled_at: updated.scheduled_at ?? scheduled_at,
|
||||||
|
duration_minutes: updated.duration_minutes ?? duration_minutes,
|
||||||
|
appointment_type: updated.appointment_type ?? formData.appointmentType ?? existing.type ?? 'presencial',
|
||||||
|
status: updated.status ?? formData.status ?? existing.status,
|
||||||
|
professional: existing.professional || formData.professionalName || '',
|
||||||
|
notes: updated.notes ?? updated.patient_notes ?? formData.notes ?? existing.notes ?? '',
|
||||||
|
chief_complaint: updated.chief_complaint ?? formData.chief_complaint ?? existing.chief_complaint ?? null,
|
||||||
|
patient_notes: updated.patient_notes ?? formData.patient_notes ?? existing.patient_notes ?? null,
|
||||||
|
insurance_provider: updated.insurance_provider ?? formData.insurance_provider ?? existing.insurance_provider ?? null,
|
||||||
|
checked_in_at: updated.checked_in_at ?? formData.checked_in_at ?? existing.checked_in_at ?? null,
|
||||||
|
completed_at: updated.completed_at ?? formData.completed_at ?? existing.completed_at ?? null,
|
||||||
|
cancelled_at: updated.cancelled_at ?? formData.cancelled_at ?? existing.cancelled_at ?? null,
|
||||||
|
cancellation_reason: updated.cancellation_reason ?? formData.cancellation_reason ?? existing.cancellation_reason ?? null,
|
||||||
|
};
|
||||||
|
|
||||||
|
setAppointments((prev) => prev.map((a) => (a.id === mapped.id ? mapped : a)));
|
||||||
handleCancel();
|
handleCancel();
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[ConsultasPage] Falha ao atualizar agendamento', err);
|
||||||
|
// Inform the user
|
||||||
|
try {
|
||||||
|
const msg = err instanceof Error ? err.message : String(err);
|
||||||
|
alert('Falha ao salvar alterações: ' + msg);
|
||||||
|
} catch (e) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Fetch and map appointments (used at load and when clearing search)
|
||||||
|
const fetchAndMapAppointments = async () => {
|
||||||
|
const arr = await listarAgendamentos("select=*&order=scheduled_at.desc&limit=200");
|
||||||
|
|
||||||
|
// 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,
|
||||||
|
patient_id: a.patient_id,
|
||||||
|
// keep some server-side fields so edit can access them later
|
||||||
|
scheduled_at: a.scheduled_at ?? a.time ?? a.created_at ?? null,
|
||||||
|
duration_minutes: a.duration_minutes ?? a.duration ?? null,
|
||||||
|
appointment_type: a.appointment_type ?? a.type ?? null,
|
||||||
|
status: a.status ?? "requested",
|
||||||
|
professional,
|
||||||
|
notes: a.notes || a.patient_notes || "",
|
||||||
|
// additional editable fields
|
||||||
|
chief_complaint: a.chief_complaint ?? null,
|
||||||
|
patient_notes: a.patient_notes ?? null,
|
||||||
|
insurance_provider: a.insurance_provider ?? null,
|
||||||
|
checked_in_at: a.checked_in_at ?? null,
|
||||||
|
completed_at: a.completed_at ?? null,
|
||||||
|
cancelled_at: a.cancelled_at ?? null,
|
||||||
|
cancellation_reason: a.cancellation_reason ?? a.cancellationReason ?? null,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
return mapped;
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let mounted = true;
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
const mapped = await fetchAndMapAppointments();
|
||||||
|
if (!mounted) return;
|
||||||
|
setAppointments(mapped);
|
||||||
|
setOriginalAppointments(mapped || []);
|
||||||
|
setIsLoading(false);
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("[ConsultasPage] Falha ao carregar agendamentos, usando mocks", err);
|
||||||
|
if (!mounted) return;
|
||||||
|
setAppointments([]);
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return () => { mounted = false; };
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Search box: allow fetching a single appointment by ID when pressing Enter
|
||||||
|
// Perform a local-only search against the already-loaded appointments.
|
||||||
|
// This intentionally does not call the server — it filters the cached list.
|
||||||
|
const performSearch = (val: string) => {
|
||||||
|
const trimmed = String(val || '').trim();
|
||||||
|
if (!trimmed) {
|
||||||
|
setAppointments(originalAppointments || []);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const q = trimmed.toLowerCase();
|
||||||
|
const localMatches = (originalAppointments || []).filter((a) => {
|
||||||
|
const patient = String(a.patient || '').toLowerCase();
|
||||||
|
const professional = String(a.professional || '').toLowerCase();
|
||||||
|
const pid = String(a.patient_id || '').toLowerCase();
|
||||||
|
const aid = String(a.id || '').toLowerCase();
|
||||||
|
return (
|
||||||
|
patient.includes(q) ||
|
||||||
|
professional.includes(q) ||
|
||||||
|
pid === q ||
|
||||||
|
aid === q
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
setAppointments(localMatches as any[]);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSearchKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault();
|
||||||
|
// keep behavior consistent: perform a local filter immediately
|
||||||
|
performSearch(searchValue);
|
||||||
|
} else if (e.key === 'Escape') {
|
||||||
|
setSearchValue('');
|
||||||
|
setAppointments(originalAppointments || []);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleClearSearch = async () => {
|
||||||
|
setSearchValue('');
|
||||||
|
setIsLoading(true);
|
||||||
|
try {
|
||||||
|
// Reset to the original cached list without refetching from server
|
||||||
|
setAppointments(originalAppointments || []);
|
||||||
|
} catch (err) {
|
||||||
|
setAppointments([]);
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Debounce live filtering as the user types. Operates only on the cached originalAppointments.
|
||||||
|
useEffect(() => {
|
||||||
|
const t = setTimeout(() => {
|
||||||
|
performSearch(searchValue);
|
||||||
|
}, 250);
|
||||||
|
return () => clearTimeout(t);
|
||||||
|
}, [searchValue, originalAppointments]);
|
||||||
|
|
||||||
|
// Keep localForm synchronized with editingAppointment
|
||||||
|
useEffect(() => {
|
||||||
if (showForm && editingAppointment) {
|
if (showForm && editingAppointment) {
|
||||||
|
setLocalForm(editingAppointment);
|
||||||
|
}
|
||||||
|
if (!showForm) setLocalForm(null);
|
||||||
|
}, [showForm, editingAppointment]);
|
||||||
|
|
||||||
|
const onFormChange = (d: any) => setLocalForm(d);
|
||||||
|
|
||||||
|
const saveLocal = async () => {
|
||||||
|
if (!localForm) return;
|
||||||
|
await handleSave(localForm);
|
||||||
|
};
|
||||||
|
|
||||||
|
// If editing, render the edit form as a focused view (keeps hooks stable)
|
||||||
|
if (showForm && 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">
|
||||||
@ -152,13 +404,15 @@ export default function ConsultasPage() {
|
|||||||
</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>
|
</div>
|
||||||
<CalendarRegistrationForm
|
<CalendarRegistrationForm formData={localForm} onFormChange={onFormChange} />
|
||||||
initialData={editingAppointment}
|
<div className="flex gap-2 justify-end">
|
||||||
onSave={handleSave}
|
<Button variant="outline" onClick={handleCancel}>
|
||||||
onCancel={handleCancel}
|
Cancelar
|
||||||
/>
|
</Button>
|
||||||
|
<Button onClick={saveLocal}>Salvar</Button>
|
||||||
</div>
|
</div>
|
||||||
)
|
</div>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@ -169,12 +423,11 @@ export default function ConsultasPage() {
|
|||||||
<p className="text-muted-foreground">Visualize, filtre e gerencie todas as consultas da clínica.</p>
|
<p className="text-muted-foreground">Visualize, filtre e gerencie todas as consultas da clínica.</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Link href="/agenda">
|
{/* Pass origin so the Agenda page can return to Consultas when cancelling */}
|
||||||
<Button size="sm" className="h-8 gap-1">
|
<Link href="/agenda?origin=consultas">
|
||||||
|
<Button size="sm" className="h-8 gap-1 bg-blue-600">
|
||||||
<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,18 +436,21 @@ 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="flex-1 min-w-[250px] flex gap-2 items-center">
|
||||||
|
<div className="relative flex-1">
|
||||||
<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"
|
type="search"
|
||||||
placeholder="Buscar por..."
|
placeholder="Buscar por..."
|
||||||
className="pl-8 w-full"
|
className="pl-8 pr-4 w-full shadow-sm border border-border bg-transparent"
|
||||||
|
value={searchValue}
|
||||||
|
onChange={(e) => setSearchValue(e.target.value)}
|
||||||
|
onKeyDown={handleSearchKeyDown}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
<Select>
|
<Select>
|
||||||
<SelectTrigger className="w-[180px]">
|
<SelectTrigger className="w-[180px]">
|
||||||
<SelectValue placeholder="Filtrar por status" />
|
<SelectValue placeholder="Filtrar por status" />
|
||||||
@ -210,6 +466,12 @@ export default function ConsultasPage() {
|
|||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
|
{isLoading ? (
|
||||||
|
<div className="w-full py-12 flex justify-center items-center">
|
||||||
|
<Loader2 className="animate-spin mr-2" />
|
||||||
|
<span>Carregando agendamentos...</span>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
<Table>
|
<Table>
|
||||||
<TableHeader>
|
<TableHeader>
|
||||||
<TableRow>
|
<TableRow>
|
||||||
@ -222,17 +484,16 @@ export default function ConsultasPage() {
|
|||||||
</TableHeader>
|
</TableHeader>
|
||||||
<TableBody>
|
<TableBody>
|
||||||
{appointments.map((appointment) => {
|
{appointments.map((appointment) => {
|
||||||
const professional = mockProfessionals.find(
|
// appointment.professional may now contain the doctor's name (resolved)
|
||||||
(p) => p.id === appointment.professional
|
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 (
|
return (
|
||||||
<TableRow key={appointment.id}>
|
<TableRow key={appointment.id}>
|
||||||
<TableCell className="font-medium">
|
<TableCell className="font-medium">{appointment.patient}</TableCell>
|
||||||
{appointment.patient}
|
<TableCell>{professionalName}</TableCell>
|
||||||
</TableCell>
|
|
||||||
<TableCell>
|
|
||||||
{professional ? professional.name : "Não encontrado"}
|
|
||||||
</TableCell>
|
|
||||||
<TableCell>
|
<TableCell>
|
||||||
<Badge
|
<Badge
|
||||||
variant={
|
variant={
|
||||||
@ -242,14 +503,12 @@ export default function ConsultasPage() {
|
|||||||
? "secondary"
|
? "secondary"
|
||||||
: "destructive"
|
: "destructive"
|
||||||
}
|
}
|
||||||
className={
|
className={appointment.status === "confirmed" ? "bg-green-600" : ""}
|
||||||
appointment.status === "confirmed" ? "bg-green-600" : ""
|
|
||||||
}
|
|
||||||
>
|
>
|
||||||
{capitalize(appointment.status)}
|
{capitalize(appointment.status)}
|
||||||
</Badge>
|
</Badge>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell>{formatDate(appointment.time)}</TableCell>
|
<TableCell>{formatDate(appointment.scheduled_at ?? appointment.time)}</TableCell>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
@ -259,9 +518,7 @@ export default function ConsultasPage() {
|
|||||||
</button>
|
</button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem onClick={() => handleView(appointment)}>
|
||||||
onClick={() => handleView(appointment)}
|
|
||||||
>
|
|
||||||
<Eye className="mr-2 h-4 w-4" />
|
<Eye className="mr-2 h-4 w-4" />
|
||||||
Ver
|
Ver
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
@ -269,10 +526,7 @@ export default function ConsultasPage() {
|
|||||||
<Edit className="mr-2 h-4 w-4" />
|
<Edit className="mr-2 h-4 w-4" />
|
||||||
Editar
|
Editar
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem onClick={() => handleDelete(appointment.id)} className="text-destructive">
|
||||||
onClick={() => handleDelete(appointment.id)}
|
|
||||||
className="text-destructive"
|
|
||||||
>
|
|
||||||
<Trash2 className="mr-2 h-4 w-4" />
|
<Trash2 className="mr-2 h-4 w-4" />
|
||||||
Excluir
|
Excluir
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
@ -284,6 +538,7 @@ export default function ConsultasPage() {
|
|||||||
})}
|
})}
|
||||||
</TableBody>
|
</TableBody>
|
||||||
</Table>
|
</Table>
|
||||||
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
@ -292,35 +547,23 @@ 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
|
<span className="col-span-3">{(viewingAppointment?.scheduled_at ?? viewingAppointment?.time) ? formatDate(viewingAppointment?.scheduled_at ?? viewingAppointment?.time) : ''}</span>
|
||||||
</Label>
|
|
||||||
<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={
|
||||||
@ -330,24 +573,18 @@ export default function ConsultasPage() {
|
|||||||
? "secondary"
|
? "secondary"
|
||||||
: "destructive"
|
: "destructive"
|
||||||
}
|
}
|
||||||
className={
|
className={viewingAppointment?.status === "confirmed" ? "bg-green-600" : ""}
|
||||||
viewingAppointment?.status === "confirmed" ? "bg-green-600" : ""
|
|
||||||
}
|
|
||||||
>
|
>
|
||||||
{capitalize(viewingAppointment?.status || '')}
|
{capitalize(viewingAppointment?.status || "")}
|
||||||
</Badge>
|
</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>
|
||||||
|
|||||||
@ -1,13 +1,17 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter, useSearchParams } from "next/navigation";
|
||||||
import { CalendarRegistrationForm } from "@/components/forms/calendar-registration-form";
|
import { CalendarRegistrationForm } from "@/components/forms/calendar-registration-form";
|
||||||
import HeaderAgenda from "@/components/agenda/HeaderAgenda";
|
import HeaderAgenda from "@/components/agenda/HeaderAgenda";
|
||||||
import FooterAgenda from "@/components/agenda/FooterAgenda";
|
import FooterAgenda from "@/components/agenda/FooterAgenda";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
|
import { criarAgendamento } from '@/lib/api';
|
||||||
|
import { toast } from '@/hooks/use-toast';
|
||||||
|
|
||||||
interface FormData {
|
interface FormData {
|
||||||
patientName?: string;
|
patientName?: string;
|
||||||
|
patientId?: string;
|
||||||
|
doctorId?: string;
|
||||||
cpf?: string;
|
cpf?: string;
|
||||||
rg?: string;
|
rg?: string;
|
||||||
birthDate?: string;
|
birthDate?: string;
|
||||||
@ -26,10 +30,15 @@ interface FormData {
|
|||||||
requestingProfessional?: string;
|
requestingProfessional?: string;
|
||||||
appointmentType?: string;
|
appointmentType?: string;
|
||||||
notes?: string;
|
notes?: string;
|
||||||
|
duration_minutes?: number;
|
||||||
|
chief_complaint?: string | null;
|
||||||
|
patient_notes?: string | null;
|
||||||
|
insurance_provider?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function NovoAgendamentoPage() {
|
export default function NovoAgendamentoPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const searchParams = useSearchParams();
|
||||||
const [formData, setFormData] = useState<FormData>({});
|
const [formData, setFormData] = useState<FormData>({});
|
||||||
|
|
||||||
const handleFormChange = (data: FormData) => {
|
const handleFormChange = (data: FormData) => {
|
||||||
@ -37,12 +46,46 @@ export default function NovoAgendamentoPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleSave = () => {
|
const handleSave = () => {
|
||||||
console.log("Salvando novo agendamento...", formData);
|
(async () => {
|
||||||
alert("Novo agendamento salvo (simulado)!");
|
try {
|
||||||
router.push("/consultas");
|
// basic validation
|
||||||
|
if (!formData.patientId && !(formData as any).patient_id) throw new Error('Patient ID é obrigatório');
|
||||||
|
if (!formData.doctorId && !(formData as any).doctor_id) throw new Error('Doctor ID é obrigatório');
|
||||||
|
if (!formData.appointmentDate) throw new Error('Data é obrigatória');
|
||||||
|
if (!formData.startTime) throw new Error('Horário de início é obrigatório');
|
||||||
|
|
||||||
|
const payload: any = {
|
||||||
|
patient_id: formData.patientId || (formData as any).patient_id,
|
||||||
|
doctor_id: formData.doctorId || (formData as any).doctor_id,
|
||||||
|
scheduled_at: new Date(`${formData.appointmentDate}T${formData.startTime}`).toISOString(),
|
||||||
|
duration_minutes: formData.duration_minutes ?? 30,
|
||||||
|
appointment_type: formData.appointmentType ?? 'presencial',
|
||||||
|
chief_complaint: formData.chief_complaint ?? null,
|
||||||
|
patient_notes: formData.patient_notes ?? null,
|
||||||
|
insurance_provider: formData.insurance_provider ?? null,
|
||||||
|
};
|
||||||
|
|
||||||
|
await criarAgendamento(payload);
|
||||||
|
// success
|
||||||
|
try { toast({ title: 'Agendamento criado', description: 'O agendamento foi criado com sucesso.' }); } catch {}
|
||||||
|
router.push('/consultas');
|
||||||
|
} catch (err: any) {
|
||||||
|
alert(err?.message ?? String(err));
|
||||||
|
}
|
||||||
|
})();
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleCancel = () => {
|
const handleCancel = () => {
|
||||||
|
// If origin was provided (eg: consultas), return there. Default to calendar.
|
||||||
|
try {
|
||||||
|
const origin = searchParams?.get?.('origin');
|
||||||
|
if (origin === 'consultas') {
|
||||||
|
router.push('/consultas');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// fallback
|
||||||
|
}
|
||||||
router.push("/calendar");
|
router.push("/calendar");
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -51,8 +94,9 @@ export default function NovoAgendamentoPage() {
|
|||||||
<HeaderAgenda />
|
<HeaderAgenda />
|
||||||
<main className="flex-1 mx-auto w-full max-w-7xl px-8 py-8">
|
<main className="flex-1 mx-auto w-full max-w-7xl px-8 py-8">
|
||||||
<CalendarRegistrationForm
|
<CalendarRegistrationForm
|
||||||
formData={formData}
|
formData={formData as any}
|
||||||
onFormChange={handleFormChange}
|
onFormChange={handleFormChange as any}
|
||||||
|
createMode
|
||||||
/>
|
/>
|
||||||
</main>
|
</main>
|
||||||
<FooterAgenda onSave={handleSave} onCancel={handleCancel} />
|
<FooterAgenda onSave={handleSave} onCancel={handleCancel} />
|
||||||
|
|||||||
@ -4,7 +4,7 @@ import SignatureCanvas from "react-signature-canvas";
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import ProtectedRoute from "@/components/ProtectedRoute";
|
import ProtectedRoute from "@/components/ProtectedRoute";
|
||||||
import { useAuth } from "@/hooks/useAuth";
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
import { buscarPacientes, listarPacientes, buscarPacientePorId, buscarPacientesPorIds, buscarMedicoPorId, buscarMedicosPorIds, buscarMedicos, type Paciente, buscarRelatorioPorId, atualizarMedico } from "@/lib/api";
|
import { buscarPacientes, listarPacientes, buscarPacientePorId, buscarPacientesPorIds, buscarMedicoPorId, buscarMedicosPorIds, buscarMedicos, listarAgendamentos, type Paciente, buscarRelatorioPorId, atualizarMedico } from "@/lib/api";
|
||||||
import { useReports } from "@/hooks/useReports";
|
import { useReports } from "@/hooks/useReports";
|
||||||
import { CreateReportData } from "@/types/report-types";
|
import { CreateReportData } from "@/types/report-types";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
@ -239,36 +239,127 @@ const ProfissionalPage = () => {
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
const [events, setEvents] = useState<any[]>([
|
const [events, setEvents] = useState<any[]>([]);
|
||||||
|
// Load real appointments for the logged in doctor and map to calendar events
|
||||||
{
|
useEffect(() => {
|
||||||
id: 1,
|
let mounted = true;
|
||||||
title: "Ana Souza",
|
(async () => {
|
||||||
type: "Cardiologia",
|
try {
|
||||||
time: "09:00",
|
// If we already have a doctorId (set earlier), use it. Otherwise try to resolve from the logged user
|
||||||
date: new Date().toISOString().split('T')[0],
|
let docId = doctorId;
|
||||||
pacienteId: "123.456.789-00",
|
if (!docId && user && user.email) {
|
||||||
color: colorsByType.Cardiologia
|
// buscarMedicos may return the doctor's record including id
|
||||||
},
|
try {
|
||||||
{
|
const docs = await buscarMedicos(user.email).catch(() => []);
|
||||||
id: 2,
|
if (Array.isArray(docs) && docs.length > 0) {
|
||||||
title: "Bruno Lima",
|
const chosen = docs.find(d => String((d as any).user_id) === String(user.id)) || docs[0];
|
||||||
type: "Cardiologia",
|
docId = (chosen as any)?.id ?? null;
|
||||||
time: "10:30",
|
if (mounted && !doctorId) setDoctorId(docId);
|
||||||
date: new Date().toISOString().split('T')[0],
|
|
||||||
pacienteId: "987.654.321-00",
|
|
||||||
color: colorsByType.Cardiologia
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 3,
|
|
||||||
title: "Carla Menezes",
|
|
||||||
type: "Dermatologia",
|
|
||||||
time: "14:00",
|
|
||||||
date: new Date().toISOString().split('T')[0],
|
|
||||||
pacienteId: "111.222.333-44",
|
|
||||||
color: colorsByType.Dermatologia
|
|
||||||
}
|
}
|
||||||
]);
|
} catch (e) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!docId) {
|
||||||
|
// nothing to fetch yet
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch appointments for this doctor. We'll ask for future and recent past appointments
|
||||||
|
// using a simple filter: doctor_id=eq.<docId>&order=scheduled_at.asc&limit=200
|
||||||
|
const qs = `?select=*&doctor_id=eq.${encodeURIComponent(String(docId))}&order=scheduled_at.asc&limit=200`;
|
||||||
|
const appts = await listarAgendamentos(qs).catch(() => []);
|
||||||
|
|
||||||
|
if (!mounted) return;
|
||||||
|
|
||||||
|
// Enrich appointments with patient names (batch fetch) and map to UI events
|
||||||
|
const patientIds = Array.from(new Set((appts || []).map((x:any) => String(x.patient_id || x.patient_id_raw || '').trim()).filter(Boolean)));
|
||||||
|
let patientMap = new Map<string, any>();
|
||||||
|
if (patientIds.length) {
|
||||||
|
try {
|
||||||
|
const patients = await buscarPacientesPorIds(patientIds).catch(() => []);
|
||||||
|
for (const p of patients || []) {
|
||||||
|
if (p && p.id) patientMap.set(String(p.id), p);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('[ProfissionalPage] falha ao buscar pacientes para eventos:', e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const mapped = (appts || []).map((a: any, idx: number) => {
|
||||||
|
const scheduled = a.scheduled_at || a.time || a.created_at || null;
|
||||||
|
// Use local date components to avoid UTC shift when showing the appointment day/time
|
||||||
|
let datePart = new Date().toISOString().split('T')[0];
|
||||||
|
let timePart = '';
|
||||||
|
if (scheduled) {
|
||||||
|
try {
|
||||||
|
const d = new Date(scheduled);
|
||||||
|
// build local date string YYYY-MM-DD using local getters
|
||||||
|
const y = d.getFullYear();
|
||||||
|
const m = String(d.getMonth() + 1).padStart(2, '0');
|
||||||
|
const day = String(d.getDate()).padStart(2, '0');
|
||||||
|
datePart = `${y}-${m}-${day}`;
|
||||||
|
timePart = `${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}`;
|
||||||
|
} catch (e) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const pid = a.patient_id || a.patient || a.patient_id_raw || a.patientId || null;
|
||||||
|
const patientObj = pid ? patientMap.get(String(pid)) : null;
|
||||||
|
const patientName = patientObj?.full_name || a.patient || a.patient_name || String(pid) || 'Paciente';
|
||||||
|
const patientIdVal = pid || null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: a.id ?? `srv-${idx}-${String(a.scheduled_at || a.created_at || idx)}`,
|
||||||
|
title: patientName || 'Paciente',
|
||||||
|
type: a.appointment_type || 'Consulta',
|
||||||
|
time: timePart || '',
|
||||||
|
date: datePart,
|
||||||
|
pacienteId: patientIdVal,
|
||||||
|
color: colorsByType[a.specialty as keyof typeof colorsByType] || '#4dabf7',
|
||||||
|
raw: a,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
setEvents(mapped);
|
||||||
|
|
||||||
|
// Helper: parse 'YYYY-MM-DD' into a local Date to avoid UTC parsing which can shift day
|
||||||
|
const parseYMDToLocal = (ymd?: string) => {
|
||||||
|
if (!ymd || typeof ymd !== 'string') return new Date();
|
||||||
|
const parts = ymd.split('-').map((p) => Number(p));
|
||||||
|
if (parts.length < 3 || parts.some((n) => Number.isNaN(n))) return new Date(ymd);
|
||||||
|
const [y, m, d] = parts;
|
||||||
|
return new Date(y, (m || 1) - 1, d || 1);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Set calendar view to nearest upcoming appointment (or today)
|
||||||
|
try {
|
||||||
|
const now = Date.now();
|
||||||
|
const upcoming = mapped.find((m:any) => {
|
||||||
|
if (!m.raw) return false;
|
||||||
|
const s = m.raw.scheduled_at || m.raw.time || m.raw.created_at;
|
||||||
|
if (!s) return false;
|
||||||
|
const t = new Date(s).getTime();
|
||||||
|
return !isNaN(t) && t >= now;
|
||||||
|
});
|
||||||
|
if (upcoming) {
|
||||||
|
setCurrentCalendarDate(parseYMDToLocal(upcoming.date));
|
||||||
|
} else if (mapped.length) {
|
||||||
|
// fallback: show the date of the first appointment
|
||||||
|
setCurrentCalendarDate(parseYMDToLocal(mapped[0].date));
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('[ProfissionalPage] falha ao carregar agendamentos do servidor:', err);
|
||||||
|
// Keep mocked/empty events if fetch fails
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return () => { mounted = false; };
|
||||||
|
}, [doctorId, user?.id, user?.email]);
|
||||||
const [editingEvent, setEditingEvent] = useState<any>(null);
|
const [editingEvent, setEditingEvent] = useState<any>(null);
|
||||||
const [showPopup, setShowPopup] = useState(false);
|
const [showPopup, setShowPopup] = useState(false);
|
||||||
const [showActionModal, setShowActionModal] = useState(false);
|
const [showActionModal, setShowActionModal] = useState(false);
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@ -200,7 +200,6 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|||||||
'apikey': ENV_CONFIG.SUPABASE_ANON_KEY,
|
'apikey': ENV_CONFIG.SUPABASE_ANON_KEY,
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
if (infoRes.ok) {
|
if (infoRes.ok) {
|
||||||
const info = await infoRes.json().catch(() => null)
|
const info = await infoRes.json().catch(() => null)
|
||||||
const roles: string[] = Array.isArray(info?.roles) ? info.roles : (info?.roles ? [info.roles] : [])
|
const roles: string[] = Array.isArray(info?.roles) ? info.roles : (info?.roles ? [info.roles] : [])
|
||||||
@ -218,6 +217,9 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|||||||
response.user.userType = derived
|
response.user.userType = derived
|
||||||
console.log('[AUTH] userType reconciled from roles ->', derived)
|
console.log('[AUTH] userType reconciled from roles ->', derived)
|
||||||
}
|
}
|
||||||
|
} else if (infoRes.status === 401 || infoRes.status === 403) {
|
||||||
|
// Authentication/permission issue: don't spam the console with raw response
|
||||||
|
console.warn('[AUTH] user-info returned', infoRes.status, '- skipping role reconciliation');
|
||||||
} else {
|
} else {
|
||||||
console.warn('[AUTH] Falha ao obter user-info para reconciliar roles:', infoRes.status)
|
console.warn('[AUTH] Falha ao obter user-info para reconciliar roles:', infoRes.status)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -724,10 +724,29 @@ async function parse<T>(res: Response): Promise<T> {
|
|||||||
rawText = '';
|
rawText = '';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
console.error('[API ERROR]', res.url, res.status, json, 'raw:', rawText);
|
|
||||||
const code = (json && (json.error?.code || json.code)) ?? res.status;
|
const code = (json && (json.error?.code || json.code)) ?? res.status;
|
||||||
const msg = (json && (json.error?.message || json.message || json.error)) ?? res.statusText;
|
const msg = (json && (json.error?.message || json.message || json.error)) ?? res.statusText;
|
||||||
|
|
||||||
|
// Special-case authentication/authorization errors to reduce noisy logs
|
||||||
|
if (res.status === 401) {
|
||||||
|
// If the server returned an empty body, avoid dumping raw text to console.error
|
||||||
|
if (!rawText && !json) {
|
||||||
|
console.warn('[API AUTH] 401 Unauthorized for', res.url, '- no auth token or token expired.');
|
||||||
|
} else {
|
||||||
|
console.warn('[API AUTH] 401 Unauthorized for', res.url, 'response:', json ?? rawText);
|
||||||
|
}
|
||||||
|
throw new Error('Você não está autenticado. Faça login novamente.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (res.status === 403) {
|
||||||
|
console.warn('[API AUTH] 403 Forbidden for', res.url, (json ?? rawText) ? 'response: ' + (json ?? rawText) : '');
|
||||||
|
throw new Error('Você não tem permissão para executar esta ação.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// For other errors, log a concise error and try to produce a friendly message
|
||||||
|
console.error('[API ERROR]', res.url, res.status, json ? json : 'no-json', rawText ? 'raw body present' : 'no raw body');
|
||||||
|
|
||||||
// Mensagens amigáveis para erros comuns
|
// Mensagens amigáveis para erros comuns
|
||||||
let friendlyMessage = msg;
|
let friendlyMessage = msg;
|
||||||
|
|
||||||
@ -741,28 +760,24 @@ async function parse<T>(res: Response): Promise<T> {
|
|||||||
friendlyMessage = 'Tipo de acesso inválido.';
|
friendlyMessage = 'Tipo de acesso inválido.';
|
||||||
} else if (msg?.includes('Missing required fields')) {
|
} else if (msg?.includes('Missing required fields')) {
|
||||||
friendlyMessage = 'Campos obrigatórios não preenchidos.';
|
friendlyMessage = 'Campos obrigatórios não preenchidos.';
|
||||||
} else if (res.status === 401) {
|
|
||||||
friendlyMessage = 'Você não está autenticado. Faça login novamente.';
|
|
||||||
} else if (res.status === 403) {
|
|
||||||
friendlyMessage = 'Você não tem permissão para criar usuários.';
|
|
||||||
} else if (res.status === 500) {
|
} else if (res.status === 500) {
|
||||||
friendlyMessage = 'Erro no servidor ao criar usuário. Entre em contato com o suporte.';
|
friendlyMessage = 'Erro no servidor ao criar usuário. Entre em contato com o suporte.';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Erro de CPF duplicado
|
// Erro de CPF duplicado
|
||||||
else if (code === '23505' && msg.includes('patients_cpf_key')) {
|
else if (code === '23505' && msg && msg.includes('patients_cpf_key')) {
|
||||||
friendlyMessage = 'Já existe um paciente cadastrado com este CPF. Por favor, verifique se o paciente já está registrado no sistema ou use um CPF diferente.';
|
friendlyMessage = 'Já existe um paciente cadastrado com este CPF. Por favor, verifique se o paciente já está registrado no sistema ou use um CPF diferente.';
|
||||||
}
|
}
|
||||||
// Erro de email duplicado (paciente)
|
// Erro de email duplicado (paciente)
|
||||||
else if (code === '23505' && msg.includes('patients_email_key')) {
|
else if (code === '23505' && msg && msg.includes('patients_email_key')) {
|
||||||
friendlyMessage = 'Já existe um paciente cadastrado com este email. Por favor, use um email diferente.';
|
friendlyMessage = 'Já existe um paciente cadastrado com este email. Por favor, use um email diferente.';
|
||||||
}
|
}
|
||||||
// Erro de CRM duplicado (médico)
|
// Erro de CRM duplicado (médico)
|
||||||
else if (code === '23505' && msg.includes('doctors_crm')) {
|
else if (code === '23505' && msg && msg.includes('doctors_crm')) {
|
||||||
friendlyMessage = 'Já existe um médico cadastrado com este CRM. Por favor, verifique se o médico já está registrado no sistema.';
|
friendlyMessage = 'Já existe um médico cadastrado com este CRM. Por favor, verifique se o médico já está registrado no sistema.';
|
||||||
}
|
}
|
||||||
// Erro de email duplicado (médico)
|
// Erro de email duplicado (médico)
|
||||||
else if (code === '23505' && msg.includes('doctors_email_key')) {
|
else if (code === '23505' && msg && msg.includes('doctors_email_key')) {
|
||||||
friendlyMessage = 'Já existe um médico cadastrado com este email. Por favor, use um email diferente.';
|
friendlyMessage = 'Já existe um médico cadastrado com este email. Por favor, use um email diferente.';
|
||||||
}
|
}
|
||||||
// Outros erros de constraint unique
|
// Outros erros de constraint unique
|
||||||
@ -944,6 +959,236 @@ 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;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Payload to create an appointment
|
||||||
|
export type AppointmentCreate = {
|
||||||
|
patient_id: string;
|
||||||
|
doctor_id: string;
|
||||||
|
scheduled_at: string; // ISO date-time
|
||||||
|
duration_minutes?: number;
|
||||||
|
appointment_type?: 'presencial' | 'telemedicina' | string;
|
||||||
|
chief_complaint?: string | null;
|
||||||
|
patient_notes?: string | null;
|
||||||
|
insurance_provider?: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Chama a Function `/functions/v1/get-available-slots` para obter os slots disponíveis de um médico
|
||||||
|
*/
|
||||||
|
export async function getAvailableSlots(input: { doctor_id: string; start_date: string; end_date: string; appointment_type?: string }): Promise<{ slots: Array<{ datetime: string; available: boolean }> }> {
|
||||||
|
if (!input || !input.doctor_id || !input.start_date || !input.end_date) {
|
||||||
|
throw new Error('Parâmetros inválidos. É necessário doctor_id, start_date e end_date.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const url = `${API_BASE}/functions/v1/get-available-slots`;
|
||||||
|
try {
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { ...baseHeaders(), 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ doctor_id: input.doctor_id, start_date: input.start_date, end_date: input.end_date, appointment_type: input.appointment_type ?? 'presencial' }),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Do not short-circuit; let parse() produce friendly errors
|
||||||
|
const parsed = await parse<{ slots: Array<{ datetime: string; available: boolean }> }>(res);
|
||||||
|
// Ensure consistent return shape
|
||||||
|
if (!parsed || !Array.isArray((parsed as any).slots)) return { slots: [] };
|
||||||
|
return parsed as { slots: Array<{ datetime: string; available: boolean }> };
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[getAvailableSlots] erro ao buscar horários disponíveis', err);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cria um agendamento (POST /rest/v1/appointments) verificando disponibilidade previamente
|
||||||
|
*/
|
||||||
|
export async function criarAgendamento(input: AppointmentCreate): Promise<Appointment> {
|
||||||
|
if (!input || !input.patient_id || !input.doctor_id || !input.scheduled_at) {
|
||||||
|
throw new Error('Parâmetros inválidos para criar agendamento. patient_id, doctor_id e scheduled_at são obrigatórios.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normalize scheduled_at to ISO
|
||||||
|
const scheduledDate = new Date(input.scheduled_at);
|
||||||
|
if (isNaN(scheduledDate.getTime())) throw new Error('scheduled_at inválido');
|
||||||
|
|
||||||
|
// Build day range for availability check (start of day to end of day of scheduled date)
|
||||||
|
const startDay = new Date(scheduledDate);
|
||||||
|
startDay.setHours(0, 0, 0, 0);
|
||||||
|
const endDay = new Date(scheduledDate);
|
||||||
|
endDay.setHours(23, 59, 59, 999);
|
||||||
|
|
||||||
|
// Query availability
|
||||||
|
const av = await getAvailableSlots({ doctor_id: input.doctor_id, start_date: startDay.toISOString(), end_date: endDay.toISOString(), appointment_type: input.appointment_type });
|
||||||
|
const scheduledMs = scheduledDate.getTime();
|
||||||
|
|
||||||
|
const matching = (av.slots || []).find((s) => {
|
||||||
|
try {
|
||||||
|
const dt = new Date(s.datetime).getTime();
|
||||||
|
// allow small tolerance (<= 60s) to account for formatting/timezone differences
|
||||||
|
return s.available && Math.abs(dt - scheduledMs) <= 60_000;
|
||||||
|
} catch (e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!matching) {
|
||||||
|
throw new Error('Horário não disponível para o médico no horário solicitado. Verifique a disponibilidade antes de agendar.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Determine created_by similar to other creators (prefer localStorage then user-info)
|
||||||
|
let createdBy: string | null = null;
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(AUTH_STORAGE_KEYS.USER);
|
||||||
|
if (raw) {
|
||||||
|
const parsed = JSON.parse(raw);
|
||||||
|
createdBy = parsed?.id ?? parsed?.user?.id ?? null;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!createdBy) {
|
||||||
|
try {
|
||||||
|
const info = await getUserInfo();
|
||||||
|
createdBy = info?.user?.id ?? null;
|
||||||
|
} catch (e) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload: any = {
|
||||||
|
patient_id: input.patient_id,
|
||||||
|
doctor_id: input.doctor_id,
|
||||||
|
scheduled_at: new Date(scheduledDate).toISOString(),
|
||||||
|
duration_minutes: input.duration_minutes ?? 30,
|
||||||
|
appointment_type: input.appointment_type ?? 'presencial',
|
||||||
|
chief_complaint: input.chief_complaint ?? null,
|
||||||
|
patient_notes: input.patient_notes ?? null,
|
||||||
|
insurance_provider: input.insurance_provider ?? null,
|
||||||
|
};
|
||||||
|
if (createdBy) payload.created_by = createdBy;
|
||||||
|
|
||||||
|
const url = `${REST}/appointments`;
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: withPrefer({ ...baseHeaders(), 'Content-Type': 'application/json' }, 'return=representation'),
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
|
||||||
|
const created = await parse<Appointment>(res);
|
||||||
|
return created;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Payload for updating an appointment (PATCH /rest/v1/appointments/{id})
|
||||||
|
export type AppointmentUpdate = Partial<{
|
||||||
|
scheduled_at: string;
|
||||||
|
duration_minutes: number;
|
||||||
|
status: 'requested' | 'confirmed' | 'checked_in' | 'in_progress' | 'completed' | 'cancelled' | 'no_show' | string;
|
||||||
|
chief_complaint: string | null;
|
||||||
|
notes: string | null;
|
||||||
|
patient_notes: string | null;
|
||||||
|
insurance_provider: string | null;
|
||||||
|
checked_in_at: string | null;
|
||||||
|
completed_at: string | null;
|
||||||
|
cancelled_at: string | null;
|
||||||
|
cancellation_reason: string | null;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Atualiza um agendamento existente (PATCH /rest/v1/appointments?id=eq.<id>)
|
||||||
|
*/
|
||||||
|
export async function atualizarAgendamento(id: string | number, input: AppointmentUpdate): Promise<Appointment> {
|
||||||
|
if (!id) throw new Error('ID do agendamento é obrigatório');
|
||||||
|
const url = `${REST}/appointments?id=eq.${encodeURIComponent(String(id))}`;
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: withPrefer({ ...baseHeaders(), 'Content-Type': 'application/json' }, 'return=representation'),
|
||||||
|
body: JSON.stringify(input),
|
||||||
|
});
|
||||||
|
const arr = await parse<Appointment[] | Appointment>(res);
|
||||||
|
return Array.isArray(arr) ? arr[0] : (arr as Appointment);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 headers = baseHeaders();
|
||||||
|
// If there is no auth token, avoid calling the endpoint which requires auth and return friendly error
|
||||||
|
const jwt = getAuthToken();
|
||||||
|
if (!jwt) {
|
||||||
|
throw new Error('Não autenticado. Faça login para listar agendamentos.');
|
||||||
|
}
|
||||||
|
const res = await fetch(url, { method: 'GET', headers });
|
||||||
|
if (!res.ok && res.status === 401) {
|
||||||
|
throw new Error('Não autenticado. Token ausente ou expirado. Faça login novamente.');
|
||||||
|
}
|
||||||
|
return await parse<Appointment[]>(res);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Buscar agendamento por ID (GET /rest/v1/appointments?id=eq.<id>)
|
||||||
|
* Retorna o primeiro agendamento encontrado ou lança erro 404.
|
||||||
|
*/
|
||||||
|
export async function buscarAgendamentoPorId(id: string | number, select: string = '*'): Promise<Appointment> {
|
||||||
|
const sId = String(id || '').trim();
|
||||||
|
if (!sId) throw new Error('ID é obrigatório para buscar agendamento');
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (select) params.set('select', select);
|
||||||
|
params.set('limit', '1');
|
||||||
|
const url = `${REST}/appointments?id=eq.${encodeURIComponent(sId)}&${params.toString()}`;
|
||||||
|
const headers = baseHeaders();
|
||||||
|
const arr = await fetchWithFallback<Appointment[]>(url, headers);
|
||||||
|
if (arr && arr.length) return arr[0];
|
||||||
|
throw new Error('404: Agendamento não encontrado');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deleta um agendamento por ID (DELETE /rest/v1/appointments?id=eq.<id>)
|
||||||
|
*/
|
||||||
|
export async function deletarAgendamento(id: string | number): Promise<void> {
|
||||||
|
if (!id) throw new Error('ID do agendamento é obrigatório');
|
||||||
|
const url = `${REST}/appointments?id=eq.${encodeURIComponent(String(id))}`;
|
||||||
|
// Request minimal return to get a 204 No Content when the delete succeeds.
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method: 'DELETE',
|
||||||
|
headers: withPrefer({ ...baseHeaders() }, 'return=minimal'),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.status === 204) return;
|
||||||
|
// Some deployments may return 200 with a representation — accept that too
|
||||||
|
if (res.status === 200) return;
|
||||||
|
// Otherwise surface a friendly error using parse()
|
||||||
|
await parse(res as Response);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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.
|
||||||
@ -1053,6 +1298,36 @@ export async function buscarPacientesPorIds(ids: Array<string | number>): Promis
|
|||||||
return unique;
|
return unique;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Busca pacientes atribuídos a um médico (usando o user_id do médico para consultar patient_assignments)
|
||||||
|
* - Primeiro busca o médico para obter o campo user_id
|
||||||
|
* - Consulta a tabela patient_assignments para obter patient_id vinculados ao user_id
|
||||||
|
* - Retorna os pacientes via buscarPacientesPorIds
|
||||||
|
*/
|
||||||
|
export async function buscarPacientesPorMedico(doctorId: string): Promise<Paciente[]> {
|
||||||
|
if (!doctorId) return [];
|
||||||
|
try {
|
||||||
|
// buscar médico para obter user_id
|
||||||
|
const medico = await buscarMedicoPorId(doctorId).catch(() => null);
|
||||||
|
const userId = medico?.user_id ?? medico?.created_by ?? null;
|
||||||
|
if (!userId) {
|
||||||
|
// se não houver user_id, não há uma forma confiável de mapear atribuições
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// buscar atribuições para esse user_id
|
||||||
|
const url = `${REST}/patient_assignments?user_id=eq.${encodeURIComponent(String(userId))}&select=patient_id`;
|
||||||
|
const res = await fetch(url, { method: 'GET', headers: baseHeaders() });
|
||||||
|
const rows = await parse<Array<{ patient_id?: string }>>(res).catch(() => []);
|
||||||
|
const ids = (rows || []).map((r) => r.patient_id).filter(Boolean) as string[];
|
||||||
|
if (!ids.length) return [];
|
||||||
|
return await buscarPacientesPorIds(ids);
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('[buscarPacientesPorMedico] falha ao obter pacientes do médico', doctorId, err);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function criarPaciente(input: PacienteInput): Promise<Paciente> {
|
export async function criarPaciente(input: PacienteInput): Promise<Paciente> {
|
||||||
const url = `${ENV_CONFIG.SUPABASE_URL}/rest/v1/patients`;
|
const url = `${ENV_CONFIG.SUPABASE_URL}/rest/v1/patients`;
|
||||||
const res = await fetch(url, {
|
const res = await fetch(url, {
|
||||||
@ -1638,11 +1913,23 @@ export async function getCurrentUser(): Promise<CurrentUser> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function getUserInfo(): Promise<UserInfo> {
|
export async function getUserInfo(): Promise<UserInfo> {
|
||||||
|
const jwt = getAuthToken();
|
||||||
|
if (!jwt) {
|
||||||
|
// No token available — avoid calling the protected function and throw a friendly error
|
||||||
|
throw new Error('Você não está autenticado. Faça login para acessar informações do usuário.');
|
||||||
|
}
|
||||||
|
|
||||||
const url = `${API_BASE}/functions/v1/user-info`;
|
const url = `${API_BASE}/functions/v1/user-info`;
|
||||||
const res = await fetch(url, {
|
const res = await fetch(url, {
|
||||||
method: "GET",
|
method: "GET",
|
||||||
headers: baseHeaders(),
|
headers: baseHeaders(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Avoid calling parse() for auth errors to prevent noisy console dumps
|
||||||
|
if (!res.ok && res.status === 401) {
|
||||||
|
throw new Error('Você não está autenticado. Faça login novamente.');
|
||||||
|
}
|
||||||
|
|
||||||
return await parse<UserInfo>(res);
|
return await parse<UserInfo>(res);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user