Merge branch 'Stage' of https://github.com/m1guelmcf/MedConnect into visual
@ -1,272 +1,238 @@
|
|||||||
|
// ARQUIVO COMPLETO COM A INTERFACE CORRIGIDA: app/doctor/consultas/page.tsx
|
||||||
|
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import type React from "react";
|
import type React from "react";
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect, useMemo } from "react";
|
||||||
import DoctorLayout from "@/components/doctor-layout";
|
import { useAuthLayout } from "@/hooks/useAuthLayout";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
||||||
|
import { patientsService } from "@/services/patientsApi.mjs";
|
||||||
|
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||||
|
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Clock, Calendar as CalendarIcon, MapPin, Phone, User, X, RefreshCw } from "lucide-react";
|
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Calendar as CalendarShadcn } from "@/components/ui/calendar";
|
||||||
|
import { Separator } from "@/components/ui/separator";
|
||||||
|
import { Clock, Calendar as CalendarIcon, User, X, RefreshCw, Loader2, MapPin, Phone, List } from "lucide-react";
|
||||||
|
import { format, isFuture, parseISO, isValid, isToday, isTomorrow } from "date-fns";
|
||||||
|
import { ptBR } from "date-fns/locale";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
// IMPORTAR O COMPONENTE CALENDÁRIO DA SHADCN
|
// Interfaces (sem alteração)
|
||||||
import { Calendar } from "@/components/ui/calendar";
|
interface EnrichedAppointment {
|
||||||
import { format } from "date-fns"; // Usaremos o date-fns para formatação e comparação de datas
|
id: string;
|
||||||
|
patientName: string;
|
||||||
const APPOINTMENTS_STORAGE_KEY = "clinic-appointments";
|
patientPhone: string;
|
||||||
|
scheduled_at: string;
|
||||||
// --- TIPAGEM DA CONSULTA SALVA NO LOCALSTORAGE ---
|
status: "requested" | "confirmed" | "completed" | "cancelled" | "checked_in" | "no_show";
|
||||||
interface LocalStorageAppointment {
|
location: string;
|
||||||
id: number;
|
|
||||||
patientName: string;
|
|
||||||
doctor: string;
|
|
||||||
specialty: string;
|
|
||||||
date: string; // Data no formato YYYY-MM-DD
|
|
||||||
time: string; // Hora no formato HH:MM
|
|
||||||
status: "agendada" | "confirmada" | "cancelada" | "realizada";
|
|
||||||
location: string;
|
|
||||||
phone: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const LOGGED_IN_DOCTOR_NAME = "Dr. João Santos";
|
|
||||||
|
|
||||||
// Função auxiliar para comparar se duas datas (Date objects) são o mesmo dia
|
|
||||||
const isSameDay = (date1: Date, date2: Date) => {
|
|
||||||
return date1.getFullYear() === date2.getFullYear() &&
|
|
||||||
date1.getMonth() === date2.getMonth() &&
|
|
||||||
date1.getDate() === date2.getDate();
|
|
||||||
};
|
|
||||||
|
|
||||||
// --- COMPONENTE PRINCIPAL ---
|
|
||||||
|
|
||||||
export default function DoctorAppointmentsPage() {
|
export default function DoctorAppointmentsPage() {
|
||||||
const [allAppointments, setAllAppointments] = useState<LocalStorageAppointment[]>([]);
|
const { user, isLoading: isAuthLoading } = useAuthLayout({ requiredRole: "medico" });
|
||||||
const [filteredAppointments, setFilteredAppointments] = useState<LocalStorageAppointment[]>([]);
|
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [allAppointments, setAllAppointments] = useState<EnrichedAppointment[]>([]);
|
||||||
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
|
const [selectedDate, setSelectedDate] = useState<Date | undefined>(new Date());
|
||||||
|
|
||||||
// NOVO ESTADO 1: Armazena os dias com consultas (para o calendário)
|
const fetchAppointments = async (authUserId: string) => {
|
||||||
const [bookedDays, setBookedDays] = useState<Date[]>([]);
|
setIsLoading(true);
|
||||||
|
try {
|
||||||
|
const allDoctors = await doctorsService.list();
|
||||||
|
const currentDoctor = allDoctors.find((doc: any) => doc.user_id === authUserId);
|
||||||
|
if (!currentDoctor) {
|
||||||
|
toast.error("Perfil de médico não encontrado para este usuário.");
|
||||||
|
return setIsLoading(false);
|
||||||
|
}
|
||||||
|
const doctorId = currentDoctor.id;
|
||||||
|
|
||||||
// NOVO ESTADO 2: Armazena a data selecionada no calendário
|
const [appointmentsList, patientsList] = await Promise.all([
|
||||||
const [selectedCalendarDate, setSelectedCalendarDate] = useState<Date | undefined>(new Date());
|
appointmentsService.search_appointment(`doctor_id=eq.${doctorId}&order=scheduled_at.asc`),
|
||||||
|
patientsService.list()
|
||||||
|
]);
|
||||||
|
|
||||||
useEffect(() => {
|
const patientsMap = new Map<string, { name: string; phone: string }>(
|
||||||
loadAppointments();
|
patientsList.map((p: any) => [p.id, { name: p.full_name, phone: p.phone_mobile }])
|
||||||
}, []);
|
);
|
||||||
|
|
||||||
// Efeito para filtrar a lista sempre que o calendário ou a lista completa for atualizada
|
const enrichedAppointments = appointmentsList.map((apt: any) => ({
|
||||||
useEffect(() => {
|
id: apt.id,
|
||||||
if (selectedCalendarDate) {
|
patientName: patientsMap.get(apt.patient_id)?.name || "Paciente Desconhecido",
|
||||||
const dateString = format(selectedCalendarDate, 'yyyy-MM-dd');
|
patientPhone: patientsMap.get(apt.patient_id)?.phone || "N/A",
|
||||||
|
scheduled_at: apt.scheduled_at,
|
||||||
|
status: apt.status,
|
||||||
|
location: "Consultório Principal",
|
||||||
|
}));
|
||||||
|
|
||||||
// Filtra a lista completa de agendamentos pela data selecionada
|
setAllAppointments(enrichedAppointments);
|
||||||
const todayAppointments = allAppointments
|
} catch (error) {
|
||||||
.filter(app => app.date === dateString)
|
console.error("Erro ao carregar a agenda:", error);
|
||||||
.sort((a, b) => a.time.localeCompare(b.time)); // Ordena por hora
|
toast.error("Não foi possível carregar sua agenda.");
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
setFilteredAppointments(todayAppointments);
|
useEffect(() => {
|
||||||
} else {
|
if (user?.id) {
|
||||||
// Se nenhuma data estiver selecionada (ou se for limpa), mostra todos (ou os de hoje)
|
fetchAppointments(user.id);
|
||||||
const todayDateString = format(new Date(), 'yyyy-MM-dd');
|
}
|
||||||
const todayAppointments = allAppointments
|
}, [user]);
|
||||||
.filter(app => app.date === todayDateString)
|
|
||||||
.sort((a, b) => a.time.localeCompare(b.time));
|
|
||||||
|
|
||||||
setFilteredAppointments(todayAppointments);
|
const groupedAppointments = useMemo(() => {
|
||||||
}
|
const appointmentsToDisplay = selectedDate
|
||||||
}, [allAppointments, selectedCalendarDate]);
|
? allAppointments.filter(app => app.scheduled_at && app.scheduled_at.startsWith(format(selectedDate, "yyyy-MM-dd")))
|
||||||
|
: allAppointments.filter(app => {
|
||||||
|
if (!app.scheduled_at) return false;
|
||||||
|
const dateObj = parseISO(app.scheduled_at);
|
||||||
|
return isValid(dateObj) && isFuture(dateObj);
|
||||||
|
});
|
||||||
|
|
||||||
const loadAppointments = () => {
|
return appointmentsToDisplay.reduce((acc, appointment) => {
|
||||||
setIsLoading(true);
|
const dateKey = format(parseISO(appointment.scheduled_at), "yyyy-MM-dd");
|
||||||
try {
|
if (!acc[dateKey]) acc[dateKey] = [];
|
||||||
const storedAppointmentsRaw = localStorage.getItem(APPOINTMENTS_STORAGE_KEY);
|
acc[dateKey].push(appointment);
|
||||||
const allAppts: LocalStorageAppointment[] = storedAppointmentsRaw ? JSON.parse(storedAppointmentsRaw) : [];
|
return acc;
|
||||||
|
}, {} as Record<string, EnrichedAppointment[]>);
|
||||||
|
}, [allAppointments, selectedDate]);
|
||||||
|
|
||||||
// ***** NENHUM FILTRO POR MÉDICO AQUI (Como solicitado) *****
|
const bookedDays = useMemo(() => {
|
||||||
const appointmentsToShow = allAppts;
|
return allAppointments
|
||||||
|
.map(app => app.scheduled_at ? new Date(app.scheduled_at) : null)
|
||||||
|
.filter((date): date is Date => date !== null);
|
||||||
|
}, [allAppointments]);
|
||||||
|
|
||||||
// 1. EXTRAI E PREPARA AS DATAS PARA O CALENDÁRIO
|
const formatDisplayDate = (dateString: string) => {
|
||||||
const uniqueBookedDates = Array.from(new Set(appointmentsToShow.map(app => app.date)));
|
const date = parseISO(dateString);
|
||||||
|
if (isToday(date)) return `Hoje, ${format(date, "dd 'de' MMMM", { locale: ptBR })}`;
|
||||||
|
if (isTomorrow(date)) return `Amanhã, ${format(date, "dd 'de' MMMM", { locale: ptBR })}`;
|
||||||
|
return format(date, "EEEE, dd 'de' MMMM", { locale: ptBR });
|
||||||
|
};
|
||||||
|
|
||||||
// Converte YYYY-MM-DD para objetos Date, garantindo que o tempo seja meia-noite (00:00:00)
|
const statusPT: Record<string, string> = {
|
||||||
const dateObjects = uniqueBookedDates.map(dateString => new Date(dateString + 'T00:00:00'));
|
confirmed: "Confirmada",
|
||||||
|
completed: "Concluída",
|
||||||
|
cancelled: "Cancelada",
|
||||||
|
requested: "Solicitada",
|
||||||
|
no_show: "oculta",
|
||||||
|
checked_in: "Aguardando",
|
||||||
|
};
|
||||||
|
|
||||||
setAllAppointments(appointmentsToShow);
|
const getStatusVariant = (status: EnrichedAppointment['status']) => {
|
||||||
setBookedDays(dateObjects);
|
switch (status) {
|
||||||
toast.success("Agenda atualizada com sucesso!");
|
case "confirmed": case "checked_in": return "text-foreground bg-blue-100 hover:bg-blue-150";
|
||||||
} catch (error) {
|
case "completed": return "text-foreground bg-green-100 hover:bg-green-150";
|
||||||
console.error("Erro ao carregar a agenda do LocalStorage:", error);
|
case "cancelled": case "no_show": return "text-foreground bg-red-200 hover:bg-red-250";
|
||||||
toast.error("Não foi possível carregar sua agenda.");
|
case "requested": return "text-foreground bg-yellow-100 hover:bg-yellow-150";
|
||||||
} finally {
|
default: return "border-gray bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90";
|
||||||
setIsLoading(false);
|
}
|
||||||
}
|
};
|
||||||
};
|
|
||||||
|
|
||||||
const getStatusVariant = (status: LocalStorageAppointment['status']) => {
|
const handleCancel = async (id: string) => {
|
||||||
// ... (código mantido)
|
// ... (função sem alteração)
|
||||||
switch (status) {
|
};
|
||||||
case "confirmada":
|
const handleReSchedule = (id: string) => {
|
||||||
case "agendada":
|
// ... (função sem alteração)
|
||||||
return "default";
|
};
|
||||||
case "realizada":
|
|
||||||
return "secondary";
|
|
||||||
case "cancelada":
|
|
||||||
return "destructive";
|
|
||||||
default:
|
|
||||||
return "outline";
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCancel = (id: number) => {
|
if (isAuthLoading) {
|
||||||
// ... (código mantido para cancelamento)
|
return <Sidebar><div>Carregando...</div></Sidebar>;
|
||||||
const storedAppointmentsRaw = localStorage.getItem(APPOINTMENTS_STORAGE_KEY);
|
}
|
||||||
const allAppts: LocalStorageAppointment[] = storedAppointmentsRaw ? JSON.parse(storedAppointmentsRaw) : [];
|
|
||||||
|
|
||||||
const updatedAppointments = allAppts.map(app =>
|
return (
|
||||||
app.id === id ? { ...app, status: "cancelada" as const } : app
|
<Sidebar>
|
||||||
);
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-bold text-foreground">Agenda Médica</h1>
|
||||||
|
<p className="text-muted-foreground">Consultas para {user?.name || "você"}</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<h2 className="text-xl font-semibold capitalize">
|
||||||
|
{selectedDate ? `Agenda de ${format(selectedDate, "dd/MM/yyyy")}` : "Próximas Consultas"}
|
||||||
|
</h2>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button onClick={() => setSelectedDate(undefined)} variant="ghost" size="sm"><List className="mr-2 h-4 w-4" />Mostrar Todas</Button>
|
||||||
|
<Button onClick={() => user?.id && fetchAppointments(user.id)} disabled={isLoading} variant="outline" size="sm"><RefreshCw className={`mr-2 h-4 w-4 ${isLoading ? 'animate-spin' : ''}`} />Atualizar</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="grid lg:grid-cols-3 gap-6">
|
||||||
|
<div className="lg:col-span-1">
|
||||||
|
<Card>
|
||||||
|
<CardHeader><CardTitle className="flex items-center"><CalendarIcon className="mr-2 h-5 w-5" />Filtrar por Data</CardTitle><CardDescription>Selecione um dia para ver os detalhes.</CardDescription></CardHeader>
|
||||||
|
<CardContent className="flex justify-center p-2">
|
||||||
|
<CalendarShadcn mode="single" selected={selectedDate} onSelect={setSelectedDate} modifiers={{ booked: bookedDays }} modifiersClassNames={{ booked: "bg-primary/20" }} className="rounded-md border p-2" locale={ptBR} />
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
<div className="lg:col-span-2 space-y-6">
|
||||||
|
{isLoading ? (
|
||||||
|
<div className="flex justify-center items-center h-48"><Loader2 className="h-8 w-8 animate-spin text-primary" /></div>
|
||||||
|
) : Object.keys(groupedAppointments).length === 0 ? (
|
||||||
|
<Card className="flex flex-col items-center justify-center h-48 text-center">
|
||||||
|
<CardHeader><CardTitle>Nenhuma consulta encontrada</CardTitle></CardHeader>
|
||||||
|
<CardContent><p className="text-muted-foreground">{selectedDate ? "Não há agendamentos para esta data." : "Não há próximas consultas agendadas."}</p></CardContent>
|
||||||
|
</Card>
|
||||||
|
) : (
|
||||||
|
Object.entries(groupedAppointments).map(([date, appointmentsForDay]) => (
|
||||||
|
<div key={date}>
|
||||||
|
<h3 className="text-lg font-semibold text-foreground mb-3 capitalize">{formatDisplayDate(date)}</h3>
|
||||||
|
<div className="space-y-4">
|
||||||
|
{appointmentsForDay.map((appointment) => {
|
||||||
|
const showActions = appointment.status === "requested" || appointment.status === "confirmed";
|
||||||
|
const scheduledAtDate = parseISO(appointment.scheduled_at);
|
||||||
|
return (
|
||||||
|
// *** INÍCIO DA MUDANÇA NO CARD ***
|
||||||
|
<Card key={appointment.id} className="shadow-sm hover:shadow-md transition-shadow">
|
||||||
|
<CardContent className="p-4 grid grid-cols-3 items-center gap-4">
|
||||||
|
{/* Coluna 1: Nome e Hora */}
|
||||||
|
<div className="col-span-1 flex flex-col gap-2">
|
||||||
|
<div className="font-semibold flex items-center text-foreground">
|
||||||
|
<User className="mr-2 h-4 w-4 text-primary" />
|
||||||
|
{appointment.patientName}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center text-sm text-muted-foreground">
|
||||||
|
<Clock className="mr-2 h-4 w-4" />
|
||||||
|
{format(scheduledAtDate, "HH:mm")}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
localStorage.setItem(APPOINTMENTS_STORAGE_KEY, JSON.stringify(updatedAppointments));
|
{/* Coluna 2: Status e Telefone */}
|
||||||
loadAppointments();
|
<div className="col-span-1 flex flex-col items-center gap-2">
|
||||||
toast.info(`Consulta cancelada com sucesso.`);
|
<Badge variant="outline" className={getStatusVariant(appointment.status)}>{statusPT[appointment.status].replace('_', ' ')}</Badge>
|
||||||
};
|
<div className="flex items-center text-sm text-muted-foreground">
|
||||||
|
<Phone className="mr-2 h-4 w-4" />
|
||||||
|
{appointment.patientPhone}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
const handleReSchedule = (id: number) => {
|
{/* Coluna 3: Ações */}
|
||||||
toast.info(`Reagendamento da Consulta ID: ${id}. Navegar para a página de agendamento.`);
|
<div className="col-span-1 flex justify-end">
|
||||||
};
|
{showActions && (
|
||||||
|
<div className="flex flex-col sm:flex-row gap-2">
|
||||||
const displayDate = selectedCalendarDate ?
|
<Button variant="outline" size="sm" onClick={() => handleReSchedule(appointment.id)}>
|
||||||
new Date(selectedCalendarDate).toLocaleDateString("pt-BR", { weekday: 'long', day: '2-digit', month: 'long' }) :
|
<RefreshCw className="mr-1.5 h-4 w-4" />Reagendar
|
||||||
"Selecione uma data";
|
</Button>
|
||||||
|
<Button variant="destructive" size="sm" onClick={() => handleCancel(appointment.id)}>
|
||||||
|
<X className="mr-1.5 h-4 w-4" />Cancelar
|
||||||
return (
|
</Button>
|
||||||
<DoctorLayout>
|
</div>
|
||||||
<div className="space-y-6">
|
)}
|
||||||
<div>
|
</div>
|
||||||
<h1 className="text-3xl font-bold text-gray-900">Agenda Médica Centralizada</h1>
|
</CardContent>
|
||||||
<p className="text-gray-600">Todas as consultas do sistema são exibidas aqui ({LOGGED_IN_DOCTOR_NAME})</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex justify-between items-center">
|
|
||||||
<h2 className="text-xl font-semibold">Consultas para: {displayDate}</h2>
|
|
||||||
<Button onClick={loadAppointments} disabled={isLoading} variant="outline" size="sm">
|
|
||||||
<RefreshCw className={`mr-2 h-4 w-4 ${isLoading ? 'animate-spin' : ''}`} />
|
|
||||||
Atualizar Agenda
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* NOVO LAYOUT DE DUAS COLUNAS */}
|
|
||||||
<div className="grid lg:grid-cols-3 gap-6">
|
|
||||||
|
|
||||||
{/* COLUNA 1: CALENDÁRIO */}
|
|
||||||
<div className="lg:col-span-1">
|
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle className="flex items-center">
|
|
||||||
<CalendarIcon className="mr-2 h-5 w-5" />
|
|
||||||
Calendário
|
|
||||||
</CardTitle>
|
|
||||||
<p className="text-sm text-gray-500">Dias em azul possuem agendamentos.</p>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="flex justify-center p-2">
|
|
||||||
<Calendar
|
|
||||||
mode="single"
|
|
||||||
selected={selectedCalendarDate}
|
|
||||||
onSelect={setSelectedCalendarDate}
|
|
||||||
initialFocus
|
|
||||||
// A CHAVE DO HIGHLIGHT: Passa o array de datas agendadas
|
|
||||||
modifiers={{ booked: bookedDays }}
|
|
||||||
// Define o estilo CSS para o modificador 'booked'
|
|
||||||
modifiersClassNames={{
|
|
||||||
booked: "bg-blue-600 text-white aria-selected:!bg-blue-700 hover:!bg-blue-700/90"
|
|
||||||
}}
|
|
||||||
className="rounded-md border p-2"
|
|
||||||
/>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
// *** FIM DA MUDANÇA NO CARD ***
|
||||||
|
);
|
||||||
{/* COLUNA 2: LISTA DE CONSULTAS FILTRADAS */}
|
})}
|
||||||
<div className="lg:col-span-2 space-y-4">
|
</div>
|
||||||
{isLoading ? (
|
<Separator className="my-6" />
|
||||||
<p className="text-center text-lg text-gray-500">Carregando a agenda...</p>
|
|
||||||
) : filteredAppointments.length === 0 ? (
|
|
||||||
<p className="text-center text-lg text-gray-500">Nenhuma consulta encontrada para a data selecionada.</p>
|
|
||||||
) : (
|
|
||||||
filteredAppointments.map((appointment) => {
|
|
||||||
const showActions = appointment.status === "agendada" || appointment.status === "confirmada";
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card key={appointment.id} className="shadow-lg">
|
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
|
||||||
<CardTitle className="text-xl font-semibold flex items-center">
|
|
||||||
<User className="mr-2 h-5 w-5 text-blue-600" />
|
|
||||||
{appointment.patientName}
|
|
||||||
</CardTitle>
|
|
||||||
<Badge variant={getStatusVariant(appointment.status)} className="uppercase">
|
|
||||||
{appointment.status}
|
|
||||||
</Badge>
|
|
||||||
</CardHeader>
|
|
||||||
|
|
||||||
<CardContent className="grid md:grid-cols-3 gap-4 pt-4">
|
|
||||||
{/* Detalhes e Ações... (mantidos) */}
|
|
||||||
<div className="space-y-3">
|
|
||||||
<div className="flex items-center text-sm text-gray-700">
|
|
||||||
<User className="mr-2 h-4 w-4 text-gray-500" />
|
|
||||||
<span className="font-semibold">Médico:</span> {appointment.doctor}
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center text-sm text-gray-700">
|
|
||||||
<CalendarIcon className="mr-2 h-4 w-4 text-gray-500" />
|
|
||||||
{new Date(appointment.date).toLocaleDateString("pt-BR", { timeZone: "UTC" })}
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center text-sm text-gray-700">
|
|
||||||
<Clock className="mr-2 h-4 w-4 text-gray-500" />
|
|
||||||
{appointment.time}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-3">
|
|
||||||
<div className="flex items-center text-sm text-gray-700">
|
|
||||||
<MapPin className="mr-2 h-4 w-4 text-gray-500" />
|
|
||||||
{appointment.location}
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center text-sm text-gray-700">
|
|
||||||
<Phone className="mr-2 h-4 w-4 text-gray-500" />
|
|
||||||
{appointment.phone || "N/A"}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex flex-col justify-center items-end">
|
|
||||||
{showActions && (
|
|
||||||
<div className="flex space-x-2">
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => handleReSchedule(appointment.id)}
|
|
||||||
>
|
|
||||||
<RefreshCw className="mr-2 h-4 w-4" />
|
|
||||||
Reagendar
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="destructive"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => handleCancel(appointment.id)}
|
|
||||||
>
|
|
||||||
<X className="mr-2 h-4 w-4" />
|
|
||||||
Cancelar
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
})
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
))
|
||||||
</DoctorLayout>
|
)}
|
||||||
);
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Sidebar>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
@ -1,37 +1,62 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import DoctorLayout from "@/components/doctor-layout";
|
import {
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
Card,
|
||||||
|
CardContent,
|
||||||
|
CardDescription,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from "@/components/ui/card";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Calendar, Clock, User, Trash2 } from "lucide-react";
|
import { Calendar, Clock, User, Trash2 } from "lucide-react";
|
||||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
import {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogAction,
|
||||||
|
AlertDialogCancel,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogTitle,
|
||||||
|
} from "@/components/ui/alert-dialog";
|
||||||
|
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { toast } from "@/hooks/use-toast";
|
import { toast } from "@/hooks/use-toast";
|
||||||
|
|
||||||
|
// --- IMPORTS ADICIONADOS PARA A CORREÇÃO ---
|
||||||
|
import { useAuthLayout } from "@/hooks/useAuthLayout";
|
||||||
|
import { patientsService } from "@/services/patientsApi.mjs";
|
||||||
|
// --- FIM DOS IMPORTS ADICIONADOS ---
|
||||||
|
|
||||||
|
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
||||||
|
import { format, parseISO, isAfter, isSameMonth, startOfToday } from "date-fns";
|
||||||
|
import { ptBR } from "date-fns/locale";
|
||||||
|
|
||||||
import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
||||||
import { exceptionsService } from "@/services/exceptionApi.mjs";
|
import { exceptionsService } from "@/services/exceptionApi.mjs";
|
||||||
import { doctorsService } from "@/services/doctorsApi.mjs";
|
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||||
import { usersService } from "@/services/usersApi.mjs";
|
import { usersService } from "@/services/usersApi.mjs";
|
||||||
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
import WeeklyScheduleCard from "@/components/ui/WeeklyScheduleCard";
|
||||||
|
|
||||||
type Availability = {
|
type Availability = {
|
||||||
id: string;
|
id: string;
|
||||||
doctor_id: string;
|
doctor_id: string;
|
||||||
weekday: string;
|
weekday: string;
|
||||||
start_time: string;
|
start_time: string;
|
||||||
end_time: string;
|
end_time: string;
|
||||||
slot_minutes: number;
|
slot_minutes: number;
|
||||||
appointment_type: string;
|
appointment_type: string;
|
||||||
active: boolean;
|
active: boolean;
|
||||||
created_at: string;
|
created_at: string;
|
||||||
updated_at: string;
|
updated_at: string;
|
||||||
created_by: string;
|
created_by: string;
|
||||||
updated_by: string | null;
|
updated_by: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
type Schedule = {
|
type Schedule = {
|
||||||
weekday: object;
|
weekday: object;
|
||||||
};
|
};
|
||||||
|
|
||||||
type Doctor = {
|
type Doctor = {
|
||||||
@ -61,36 +86,36 @@ type Doctor = {
|
|||||||
updated_by: string | null;
|
updated_by: string | null;
|
||||||
max_days_in_advance: number;
|
max_days_in_advance: number;
|
||||||
rating: number | null;
|
rating: number | null;
|
||||||
}
|
};
|
||||||
|
|
||||||
interface UserPermissions {
|
interface UserPermissions {
|
||||||
isAdmin: boolean;
|
isAdmin: boolean;
|
||||||
isManager: boolean;
|
isManager: boolean;
|
||||||
isDoctor: boolean;
|
isDoctor: boolean;
|
||||||
isSecretary: boolean;
|
isSecretary: boolean;
|
||||||
isAdminOrManager: boolean;
|
isAdminOrManager: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface UserData {
|
interface UserData {
|
||||||
user: {
|
user: {
|
||||||
id: string;
|
id: string;
|
||||||
email: string;
|
email: string;
|
||||||
email_confirmed_at: string | null;
|
email_confirmed_at: string | null;
|
||||||
created_at: string | null;
|
created_at: string | null;
|
||||||
last_sign_in_at: string | null;
|
last_sign_in_at: string | null;
|
||||||
};
|
};
|
||||||
profile: {
|
profile: {
|
||||||
id: string;
|
id: string;
|
||||||
full_name: string;
|
full_name: string;
|
||||||
email: string;
|
email: string;
|
||||||
phone: string;
|
phone: string;
|
||||||
avatar_url: string | null;
|
avatar_url: string | null;
|
||||||
disabled: boolean;
|
disabled: boolean;
|
||||||
created_at: string | null;
|
created_at: string | null;
|
||||||
updated_at: string | null;
|
updated_at: string | null;
|
||||||
};
|
};
|
||||||
roles: string[];
|
roles: string[];
|
||||||
permissions: UserPermissions;
|
permissions: UserPermissions;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Exception {
|
interface Exception {
|
||||||
@ -98,7 +123,7 @@ interface Exception {
|
|||||||
doctor_id: string;
|
doctor_id: string;
|
||||||
date: string; // formato YYYY-MM-DD
|
date: string; // formato YYYY-MM-DD
|
||||||
start_time: string | null; // null = dia inteiro
|
start_time: string | null; // null = dia inteiro
|
||||||
end_time: string | null; // null = dia inteiro
|
end_time: string | null; // null = dia inteiro
|
||||||
kind: "bloqueio" | "disponibilidade"; // tipos conhecidos
|
kind: "bloqueio" | "disponibilidade"; // tipos conhecidos
|
||||||
reason: string | null; // pode ser null
|
reason: string | null; // pode ser null
|
||||||
created_at: string; // timestamp ISO
|
created_at: string; // timestamp ISO
|
||||||
@ -106,7 +131,10 @@ interface Exception {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function PatientDashboard() {
|
export default function PatientDashboard() {
|
||||||
const [loggedDoctor, setLoggedDoctor] = useState<Doctor>();
|
// --- USA O HOOK DE AUTENTICAÇÃO PARA PEGAR O USUÁRIO LOGADO ---
|
||||||
|
const { user } = useAuthLayout({ requiredRole: ['medico'] });
|
||||||
|
|
||||||
|
const [loggedDoctor, setLoggedDoctor] = useState<Doctor | null>(null);
|
||||||
const [userData, setUserData] = useState<UserData>();
|
const [userData, setUserData] = useState<UserData>();
|
||||||
const [availability, setAvailability] = useState<any | null>(null);
|
const [availability, setAvailability] = useState<any | null>(null);
|
||||||
const [exceptions, setExceptions] = useState<Exception[]>([]);
|
const [exceptions, setExceptions] = useState<Exception[]>([]);
|
||||||
@ -116,56 +144,79 @@ export default function PatientDashboard() {
|
|||||||
const [exceptionToDelete, setExceptionToDelete] = useState<string | null>(null);
|
const [exceptionToDelete, setExceptionToDelete] = useState<string | null>(null);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
// Mapa de tradução
|
// --- ESTADOS PARA OS CARDS ATUALIZADOS ---
|
||||||
const weekdaysPT: Record<string, string> = {
|
const [nextAppointment, setNextAppointment] = useState<EnrichedAppointment | null>(null);
|
||||||
sunday: "Domingo",
|
const [monthlyCount, setMonthlyCount] = useState<number>(0);
|
||||||
monday: "Segunda",
|
|
||||||
tuesday: "Terça",
|
|
||||||
wednesday: "Quarta",
|
|
||||||
thursday: "Quinta",
|
|
||||||
friday: "Sexta",
|
|
||||||
saturday: "Sábado",
|
|
||||||
};
|
|
||||||
|
|
||||||
|
const weekdaysPT: Record<string, string> = { sunday: "Domingo", monday: "Segunda", tuesday: "Terça", wednesday: "Quarta", thursday: "Quinta", friday: "Sexta", saturday: "Sábado" };
|
||||||
|
|
||||||
|
// ▼▼▼ LÓGICA DE BUSCA CORRIGIDA E ATUALIZADA ▼▼▼
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchData = async () => {
|
const fetchData = async () => {
|
||||||
try {
|
if (!user?.id) return; // Aguarda o usuário ser carregado
|
||||||
const doctorsList: Doctor[] = await doctorsService.list();
|
|
||||||
const doctor = doctorsList[0];
|
|
||||||
|
|
||||||
// Salva no estado
|
try {
|
||||||
setLoggedDoctor(doctor);
|
// Encontra o perfil de médico correspondente ao usuário logado
|
||||||
|
const doctorsList: Doctor[] = await doctorsService.list();
|
||||||
|
const currentDoctor = doctorsList.find(doc => doc.user_id === user.id);
|
||||||
|
|
||||||
// Busca disponibilidade
|
if (!currentDoctor) {
|
||||||
const availabilityList = await AvailabilityService.list();
|
setError("Perfil de médico não encontrado para este usuário.");
|
||||||
|
return;
|
||||||
// Filtra já com a variável local
|
}
|
||||||
const filteredAvail = availabilityList.filter(
|
setLoggedDoctor(currentDoctor);
|
||||||
(disp: { doctor_id: string }) => disp.doctor_id === doctor?.id
|
|
||||||
);
|
|
||||||
setAvailability(filteredAvail);
|
|
||||||
|
|
||||||
// Busca exceções
|
// Busca todos os dados necessários em paralelo
|
||||||
const exceptionsList = await exceptionsService.list();
|
const [appointmentsList, patientsList, availabilityList, exceptionsList] = await Promise.all([
|
||||||
const filteredExc = exceptionsList.filter(
|
appointmentsService.list(),
|
||||||
(exc: { doctor_id: string }) => exc.doctor_id === doctor?.id
|
patientsService.list(),
|
||||||
);
|
AvailabilityService.list(),
|
||||||
console.log(exceptionsList)
|
exceptionsService.list()
|
||||||
setExceptions(filteredExc);
|
]);
|
||||||
|
|
||||||
} catch (e: any) {
|
// Mapeia pacientes por ID para consulta rápida
|
||||||
alert(`${e?.error} ${e?.message}`);
|
const patientsMap = new Map(patientsList.map((p: any) => [p.id, p.full_name]));
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
fetchData();
|
// Filtra e enriquece as consultas APENAS do médico logado
|
||||||
}, []);
|
const doctorAppointments = appointmentsList
|
||||||
|
.filter((apt: any) => apt.doctor_id === currentDoctor.id)
|
||||||
|
.map((apt: any): EnrichedAppointment => ({
|
||||||
|
...apt,
|
||||||
|
patientName: patientsMap.get(apt.patient_id) || "Paciente Desconhecido",
|
||||||
|
}));
|
||||||
|
|
||||||
|
// 1. Lógica para "Próxima Consulta"
|
||||||
|
const today = startOfToday();
|
||||||
|
const upcomingAppointments = doctorAppointments
|
||||||
|
.filter(apt => isAfter(parseISO(apt.scheduled_at), today))
|
||||||
|
.sort((a, b) => new Date(a.scheduled_at).getTime() - new Date(b.scheduled_at).getTime());
|
||||||
|
setNextAppointment(upcomingAppointments[0] || null);
|
||||||
|
|
||||||
|
// 2. Lógica para "Consultas Este Mês" (apenas ativas)
|
||||||
|
const activeStatuses = ['confirmed', 'requested', 'checked_in'];
|
||||||
|
const currentMonthAppointments = doctorAppointments.filter(apt =>
|
||||||
|
isSameMonth(parseISO(apt.scheduled_at), new Date()) && activeStatuses.includes(apt.status)
|
||||||
|
);
|
||||||
|
setMonthlyCount(currentMonthAppointments.length);
|
||||||
|
|
||||||
|
// Busca e filtra o restante dos dados
|
||||||
|
setAvailability(availabilityList.filter((d: any) => d.doctor_id === currentDoctor.id));
|
||||||
|
setExceptions(exceptionsList.filter((e: any) => e.doctor_id === currentDoctor.id));
|
||||||
|
|
||||||
|
} catch (e: any) {
|
||||||
|
setError(e?.message || "Erro ao buscar dados do dashboard");
|
||||||
|
console.error("Erro no dashboard:", e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchData();
|
||||||
|
}, [user]); // A busca de dados agora depende do usuário logado
|
||||||
|
// ▲▲▲ FIM DA LÓGICA DE BUSCA ATUALIZADA ▲▲▲
|
||||||
|
|
||||||
// Função auxiliar para filtrar o id do doctor correspondente ao user logado
|
|
||||||
function findDoctorById(id: string, doctors: Doctor[]) {
|
function findDoctorById(id: string, doctors: Doctor[]) {
|
||||||
return doctors.find((doctor) => doctor.user_id === id);
|
return doctors.find((doctor) => doctor.user_id === id);
|
||||||
}
|
}
|
||||||
|
|
||||||
const openDeleteDialog = (exceptionId: string) => {
|
const openDeleteDialog = (exceptionId: string) => {
|
||||||
setExceptionToDelete(exceptionId);
|
setExceptionToDelete(exceptionId);
|
||||||
setDeleteDialogOpen(true);
|
setDeleteDialogOpen(true);
|
||||||
@ -173,106 +224,98 @@ export default function PatientDashboard() {
|
|||||||
|
|
||||||
const handleDeleteException = async (ExceptionId: string) => {
|
const handleDeleteException = async (ExceptionId: string) => {
|
||||||
try {
|
try {
|
||||||
alert(ExceptionId)
|
|
||||||
const res = await exceptionsService.delete(ExceptionId);
|
const res = await exceptionsService.delete(ExceptionId);
|
||||||
|
if (res && res.error) { throw new Error(res.message || "A API retornou um erro"); }
|
||||||
let message = "Exceção deletada com sucesso";
|
toast({ title: "Sucesso", description: "Exceção deletada com sucesso" });
|
||||||
try {
|
|
||||||
if (res) {
|
|
||||||
throw new Error(`${res.error} ${res.message}` || "A API retornou erro");
|
|
||||||
} else {
|
|
||||||
console.log(message);
|
|
||||||
}
|
|
||||||
} catch {}
|
|
||||||
|
|
||||||
toast({
|
|
||||||
title: "Sucesso",
|
|
||||||
description: message,
|
|
||||||
});
|
|
||||||
|
|
||||||
setExceptions((prev: Exception[]) => prev.filter((p) => String(p.id) !== String(ExceptionId)));
|
setExceptions((prev: Exception[]) => prev.filter((p) => String(p.id) !== String(ExceptionId)));
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
toast({
|
toast({ title: "Erro", description: e?.message || "Não foi possível deletar a exceção" });
|
||||||
title: "Erro",
|
|
||||||
description: e?.message || "Não foi possível deletar a exceção",
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
setDeleteDialogOpen(false);
|
setDeleteDialogOpen(false);
|
||||||
setExceptionToDelete(null);
|
setExceptionToDelete(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
function formatAvailability(data: Availability[]) {
|
function formatAvailability(data: Availability[]) {
|
||||||
// Agrupar os horários por dia da semana
|
if (!data) return {};
|
||||||
const schedule = data.reduce((acc: any, item) => {
|
const schedule = data.reduce((acc: any, item) => {
|
||||||
const { weekday, start_time, end_time } = item;
|
const { weekday, start_time, end_time } = item;
|
||||||
|
if (!acc[weekday]) acc[weekday] = [];
|
||||||
// Se o dia ainda não existe, cria o array
|
acc[weekday].push({ start: start_time, end: end_time });
|
||||||
if (!acc[weekday]) {
|
|
||||||
acc[weekday] = [];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Adiciona o horário do dia
|
|
||||||
acc[weekday].push({
|
|
||||||
start: start_time,
|
|
||||||
end: end_time,
|
|
||||||
});
|
|
||||||
|
|
||||||
return acc;
|
return acc;
|
||||||
}, {} as Record<string, { start: string; end: string }[]>);
|
}, {} as Record<string, { start: string; end: string }[]>);
|
||||||
|
|
||||||
return schedule;
|
return schedule;
|
||||||
}
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (availability) {
|
if (availability) {
|
||||||
const formatted = formatAvailability(availability);
|
const formatted = formatAvailability(availability);
|
||||||
setSchedule(formatted);
|
setSchedule(formatted);
|
||||||
}
|
}
|
||||||
}, [availability]);
|
}, [availability]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DoctorLayout>
|
<Sidebar>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
|
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
|
||||||
<p className="text-gray-600">Bem-vindo ao seu portal de consultas médicas</p>
|
<p className="text-gray-600">
|
||||||
</div>
|
Bem-vindo ao seu portal de consultas médicas
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||||
|
{/* ▼▼▼ CARD "PRÓXIMA CONSULTA" CORRIGIDO PARA MOSTRAR NOME DO PACIENTE ▼▼▼ */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||||
<CardTitle className="text-sm font-medium">Próxima Consulta</CardTitle>
|
<CardTitle className="text-sm font-medium">Próxima Consulta</CardTitle>
|
||||||
<Calendar className="h-4 w-4 text-muted-foreground" />
|
<Calendar className="h-4 w-4 text-muted-foreground" />
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div className="text-2xl font-bold">02 out</div>
|
{nextAppointment ? (
|
||||||
<p className="text-xs text-muted-foreground">Dr. Silva - 14:30</p>
|
<>
|
||||||
|
<div className="text-2xl font-bold capitalize">
|
||||||
|
{format(parseISO(nextAppointment.scheduled_at), "dd MMM", { locale: ptBR })}
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{nextAppointment.patientName} - {format(parseISO(nextAppointment.scheduled_at), "HH:mm")}
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="text-2xl font-bold">Nenhuma</div>
|
||||||
|
<p className="text-xs text-muted-foreground">Sem próximas consultas</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
{/* ▲▲▲ FIM DO CARD ATUALIZADO ▲▲▲ */}
|
||||||
|
|
||||||
|
{/* ▼▼▼ CARD "CONSULTAS ESTE MÊS" CORRIGIDO PARA CONTAGEM CORRETA ▼▼▼ */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||||
<CardTitle className="text-sm font-medium">Consultas Este Mês</CardTitle>
|
<CardTitle className="text-sm font-medium">Consultas Este Mês</CardTitle>
|
||||||
<Clock className="h-4 w-4 text-muted-foreground" />
|
<Clock className="h-4 w-4 text-muted-foreground" />
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div className="text-2xl font-bold">4</div>
|
<div className="text-2xl font-bold">{monthlyCount}</div>
|
||||||
<p className="text-xs text-muted-foreground">4 agendadas</p>
|
<p className="text-xs text-muted-foreground">{monthlyCount === 1 ? '1 agendada' : `${monthlyCount} agendadas`}</p>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
{/* ▲▲▲ FIM DO CARD ATUALIZADO ▲▲▲ */}
|
||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||||
<CardTitle className="text-sm font-medium">Perfil</CardTitle>
|
<CardTitle className="text-sm font-medium">Perfil</CardTitle>
|
||||||
<User className="h-4 w-4 text-muted-foreground" />
|
<User className="h-4 w-4 text-muted-foreground" />
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div className="text-2xl font-bold">100%</div>
|
<div className="text-2xl font-bold">100%</div>
|
||||||
<p className="text-xs text-muted-foreground">Dados completos</p>
|
<p className="text-xs text-muted-foreground">Dados completos</p>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* O restante do código permanece o mesmo */}
|
||||||
<div className="grid md:grid-cols-2 gap-6">
|
<div className="grid md:grid-cols-2 gap-6">
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
@ -316,31 +359,7 @@ export default function PatientDashboard() {
|
|||||||
<CardTitle>Horário Semanal</CardTitle>
|
<CardTitle>Horário Semanal</CardTitle>
|
||||||
<CardDescription>Confira rapidamente a sua disponibilidade da semana</CardDescription>
|
<CardDescription>Confira rapidamente a sua disponibilidade da semana</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-4 grid md:grid-cols-7 gap-2">
|
<CardContent>{loggedDoctor && <WeeklyScheduleCard doctorId={loggedDoctor.id} />}</CardContent>
|
||||||
{["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"].map((day) => {
|
|
||||||
const times = schedule[day] || [];
|
|
||||||
return (
|
|
||||||
<div key={day} className="space-y-4">
|
|
||||||
<div className="flex flex-col items-center justify-between p-3 bg-blue-50 rounded-lg">
|
|
||||||
<div>
|
|
||||||
<p className="font-medium capitalize">{weekdaysPT[day]}</p>
|
|
||||||
</div>
|
|
||||||
<div className="text-center">
|
|
||||||
{times.length > 0 ? (
|
|
||||||
times.map((t, i) => (
|
|
||||||
<p key={i} className="text-sm text-gray-600">
|
|
||||||
{formatTime(t.start)} <br /> {formatTime(t.end)}
|
|
||||||
</p>
|
|
||||||
))
|
|
||||||
) : (
|
|
||||||
<p className="text-sm text-gray-400 italic">Sem horário</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
<div className="grid md:grid-cols-1 gap-6">
|
<div className="grid md:grid-cols-1 gap-6">
|
||||||
@ -353,7 +372,6 @@ export default function PatientDashboard() {
|
|||||||
<CardContent className="space-y-4 grid md:grid-cols-7 gap-2">
|
<CardContent className="space-y-4 grid md:grid-cols-7 gap-2">
|
||||||
{exceptions && exceptions.length > 0 ? (
|
{exceptions && exceptions.length > 0 ? (
|
||||||
exceptions.map((ex: Exception) => {
|
exceptions.map((ex: Exception) => {
|
||||||
// Formata data e hora
|
|
||||||
const date = new Date(ex.date).toLocaleDateString("pt-BR", {
|
const date = new Date(ex.date).toLocaleDateString("pt-BR", {
|
||||||
weekday: "long",
|
weekday: "long",
|
||||||
day: "2-digit",
|
day: "2-digit",
|
||||||
@ -361,18 +379,18 @@ export default function PatientDashboard() {
|
|||||||
timeZone: "UTC"
|
timeZone: "UTC"
|
||||||
});
|
});
|
||||||
|
|
||||||
const startTime = formatTime(ex.start_time);
|
const startTime = formatTime(ex.start_time);
|
||||||
const endTime = formatTime(ex.end_time);
|
const endTime = formatTime(ex.end_time);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div key={ex.id} className="space-y-4">
|
<div key={ex.id} className="space-y-4">
|
||||||
<div className="flex flex-col items-center justify-between p-3 bg-blue-50 rounded-lg shadow-sm">
|
<div className="flex flex-col items-center justify-between p-3 bg-blue-50 rounded-lg shadow-sm">
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<p className="font-semibold capitalize">{date}</p>
|
<p className="font-semibold capitalize">{date}</p>
|
||||||
<p className="text-sm text-gray-600">
|
<p className="text-sm text-gray-600">
|
||||||
{startTime && endTime
|
{startTime && endTime
|
||||||
? `${startTime} - ${endTime}`
|
? `${startTime} - ${endTime}`
|
||||||
: "Dia todo"}
|
: "Dia todo"}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-center mt-2">
|
<div className="text-center mt-2">
|
||||||
@ -409,6 +427,6 @@ export default function PatientDashboard() {
|
|||||||
</AlertDialogContent>
|
</AlertDialogContent>
|
||||||
</AlertDialog>
|
</AlertDialog>
|
||||||
</div>
|
</div>
|
||||||
</DoctorLayout>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -3,14 +3,12 @@
|
|||||||
import type React from "react";
|
import type React from "react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import DoctorLayout from "@/components/doctor-layout";
|
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
import { Clock, Calendar as CalendarIcon, MapPin, Phone, User, X, RefreshCw } from "lucide-react";
|
import { Calendar as CalendarIcon, RefreshCw } from "lucide-react";
|
||||||
import { Badge } from "@/components/ui/badge";
|
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { toast } from "@/hooks/use-toast";
|
import { toast } from "@/hooks/use-toast";
|
||||||
import { exceptionsService } from "@/services/exceptionApi.mjs";
|
import { exceptionsService } from "@/services/exceptionApi.mjs";
|
||||||
@ -19,6 +17,7 @@ import { exceptionsService } from "@/services/exceptionApi.mjs";
|
|||||||
import { Calendar } from "@/components/ui/calendar";
|
import { Calendar } from "@/components/ui/calendar";
|
||||||
import { format } from "date-fns"; // Usaremos o date-fns para formatação e comparação de datas
|
import { format } from "date-fns"; // Usaremos o date-fns para formatação e comparação de datas
|
||||||
import { doctorsService } from "@/services/doctorsApi.mjs";
|
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||||
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
type Doctor = {
|
type Doctor = {
|
||||||
id: string;
|
id: string;
|
||||||
@ -147,7 +146,7 @@ export default function ExceptionPage() {
|
|||||||
const displayDate = selectedCalendarDate ? new Date(selectedCalendarDate).toLocaleDateString("pt-BR", { weekday: "long", day: "2-digit", month: "long" }) : "Selecione uma data";
|
const displayDate = selectedCalendarDate ? new Date(selectedCalendarDate).toLocaleDateString("pt-BR", { weekday: "long", day: "2-digit", month: "long" }) : "Selecione uma data";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DoctorLayout>
|
<Sidebar>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-bold text-gray-900">Adicione exceções</h1>
|
<h1 className="text-3xl font-bold text-gray-900">Adicione exceções</h1>
|
||||||
@ -254,6 +253,6 @@ export default function ExceptionPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</DoctorLayout>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -6,8 +6,13 @@ import Link from "next/link";
|
|||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
import {
|
||||||
import DoctorLayout from "@/components/doctor-layout";
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
|
||||||
import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
||||||
import { usersService } from "@/services/usersApi.mjs";
|
import { usersService } from "@/services/usersApi.mjs";
|
||||||
@ -15,162 +20,203 @@ import { doctorsService } from "@/services/doctorsApi.mjs";
|
|||||||
|
|
||||||
import { toast } from "@/hooks/use-toast";
|
import { toast } from "@/hooks/use-toast";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card";
|
import {
|
||||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
Card,
|
||||||
import { Eye, Edit, Calendar, Trash2 } from "lucide-react";
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
CardDescription,
|
||||||
|
CardContent,
|
||||||
|
} from "@/components/ui/card";
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from "@/components/ui/dropdown-menu";
|
||||||
|
import { Edit, Trash2 } from "lucide-react";
|
||||||
import { AvailabilityEditModal } from "@/components/ui/availability-edit-modal";
|
import { AvailabilityEditModal } from "@/components/ui/availability-edit-modal";
|
||||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
import {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogAction,
|
||||||
|
AlertDialogCancel,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogTitle,
|
||||||
|
} from "@/components/ui/alert-dialog";
|
||||||
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
// ... (Interfaces de tipo omitidas para brevidade, pois não foram alteradas)
|
// ... (Interfaces de tipo omitidas para brevidade, pois não foram alteradas)
|
||||||
|
|
||||||
interface UserPermissions {
|
interface UserPermissions {
|
||||||
isAdmin: boolean;
|
isAdmin: boolean;
|
||||||
isManager: boolean;
|
isManager: boolean;
|
||||||
isDoctor: boolean;
|
isDoctor: boolean;
|
||||||
isSecretary: boolean;
|
isSecretary: boolean;
|
||||||
isAdminOrManager: boolean;
|
isAdminOrManager: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface UserData {
|
interface UserData {
|
||||||
user: {
|
user: {
|
||||||
id: string;
|
id: string;
|
||||||
email: string;
|
email: string;
|
||||||
email_confirmed_at: string | null;
|
email_confirmed_at: string | null;
|
||||||
created_at: string | null;
|
created_at: string | null;
|
||||||
last_sign_in_at: string | null;
|
last_sign_in_at: string | null;
|
||||||
};
|
};
|
||||||
profile: {
|
profile: {
|
||||||
id: string;
|
id: string;
|
||||||
full_name: string;
|
full_name: string;
|
||||||
email: string;
|
email: string;
|
||||||
phone: string;
|
phone: string;
|
||||||
avatar_url: string | null;
|
avatar_url: string | null;
|
||||||
disabled: boolean;
|
disabled: boolean;
|
||||||
created_at: string | null;
|
created_at: string | null;
|
||||||
updated_at: string | null;
|
updated_at: string | null;
|
||||||
};
|
};
|
||||||
roles: string[];
|
roles: string[];
|
||||||
permissions: UserPermissions;
|
permissions: UserPermissions;
|
||||||
}
|
}
|
||||||
|
|
||||||
type Doctor = {
|
type Doctor = {
|
||||||
id: string;
|
id: string;
|
||||||
user_id: string | null;
|
user_id: string | null;
|
||||||
crm: string;
|
crm: string;
|
||||||
crm_uf: string;
|
crm_uf: string;
|
||||||
specialty: string;
|
specialty: string;
|
||||||
full_name: string;
|
full_name: string;
|
||||||
cpf: string;
|
cpf: string;
|
||||||
email: string;
|
email: string;
|
||||||
phone_mobile: string | null;
|
phone_mobile: string | null;
|
||||||
phone2: string | null;
|
phone2: string | null;
|
||||||
cep: string | null;
|
cep: string | null;
|
||||||
street: string | null;
|
street: string | null;
|
||||||
number: string | null;
|
number: string | null;
|
||||||
complement: string | null;
|
complement: string | null;
|
||||||
neighborhood: string | null;
|
neighborhood: string | null;
|
||||||
city: string | null;
|
city: string | null;
|
||||||
state: string | null;
|
state: string | null;
|
||||||
birth_date: string | null;
|
birth_date: string | null;
|
||||||
rg: string | null;
|
rg: string | null;
|
||||||
active: boolean;
|
active: boolean;
|
||||||
created_at: string;
|
created_at: string;
|
||||||
updated_at: string;
|
updated_at: string;
|
||||||
created_by: string;
|
created_by: string;
|
||||||
updated_by: string | null;
|
updated_by: string | null;
|
||||||
max_days_in_advance: number;
|
max_days_in_advance: number;
|
||||||
rating: number | null;
|
rating: number | null;
|
||||||
}
|
};
|
||||||
|
|
||||||
type Availability = {
|
type Availability = {
|
||||||
id: string;
|
id: string;
|
||||||
doctor_id: string;
|
doctor_id: string;
|
||||||
weekday: string;
|
weekday: string;
|
||||||
start_time: string;
|
start_time: string;
|
||||||
end_time: string;
|
end_time: string;
|
||||||
slot_minutes: number;
|
slot_minutes: number;
|
||||||
appointment_type: string;
|
appointment_type: string;
|
||||||
active: boolean;
|
active: boolean;
|
||||||
created_at: string;
|
created_at: string;
|
||||||
updated_at: string;
|
updated_at: string;
|
||||||
created_by: string;
|
created_by: string;
|
||||||
updated_by: string | null;
|
updated_by: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function AvailabilityPage() {
|
export default function AvailabilityPage() {
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [schedule, setSchedule] = useState<Record<string, { start: string; end: string }[]>>({});
|
const [schedule, setSchedule] = useState<
|
||||||
const formatTime = (time?: string | null) => time?.split(":")?.slice(0, 2).join(":") ?? "";
|
Record<string, { start: string; end: string }[]>
|
||||||
const [userData, setUserData] = useState<UserData>();
|
>({});
|
||||||
const [availability, setAvailability] = useState<any | null>(null);
|
const formatTime = (time?: string | null) =>
|
||||||
const [doctorId, setDoctorId] = useState<string>();
|
time?.split(":")?.slice(0, 2).join(":") ?? "";
|
||||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
const [userData, setUserData] = useState<UserData>();
|
||||||
const [modalidadeConsulta, setModalidadeConsulta] = useState<string>("");
|
const [availability, setAvailability] = useState<any | null>(null);
|
||||||
const [selectedAvailability, setSelectedAvailability] = useState<Availability | null>(null);
|
const [doctorId, setDoctorId] = useState<string>();
|
||||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||||
|
const [modalidadeConsulta, setModalidadeConsulta] = useState<string>("");
|
||||||
const selectAvailability = (schedule: { start: string; end: string;}, day: string) => {
|
const [selectedAvailability, setSelectedAvailability] =
|
||||||
const selected = availability.filter((a: Availability) =>
|
useState<Availability | null>(null);
|
||||||
a.start_time === schedule.start &&
|
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||||
a.end_time === schedule.end &&
|
|
||||||
a.weekday === day
|
|
||||||
);
|
|
||||||
setSelectedAvailability(selected[0]);
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleOpenModal = (schedule: { start: string; end: string;}, day: string) => {
|
const selectAvailability = (
|
||||||
selectAvailability(schedule, day)
|
schedule: { start: string; end: string },
|
||||||
setIsModalOpen(true);
|
day: string
|
||||||
};
|
) => {
|
||||||
|
const selected = availability.filter(
|
||||||
const handleCloseModal = () => {
|
(a: Availability) =>
|
||||||
setSelectedAvailability(null);
|
a.start_time === schedule.start &&
|
||||||
setIsModalOpen(false);
|
a.end_time === schedule.end &&
|
||||||
|
a.weekday === day
|
||||||
|
);
|
||||||
|
setSelectedAvailability(selected[0]);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleOpenModal = (
|
||||||
|
schedule: { start: string; end: string },
|
||||||
|
day: string
|
||||||
|
) => {
|
||||||
|
selectAvailability(schedule, day);
|
||||||
|
setIsModalOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCloseModal = () => {
|
||||||
|
setSelectedAvailability(null);
|
||||||
|
setIsModalOpen(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleEdit = async (formData: {
|
||||||
|
start_time: "";
|
||||||
|
end_time: "";
|
||||||
|
slot_minutes: "";
|
||||||
|
appointment_type: "";
|
||||||
|
id: "";
|
||||||
|
}) => {
|
||||||
|
if (isLoading) return;
|
||||||
|
setIsLoading(true);
|
||||||
|
|
||||||
|
const apiPayload = {
|
||||||
|
start_time: formData.start_time,
|
||||||
|
end_time: formData.end_time,
|
||||||
|
slot_minutes: formData.slot_minutes,
|
||||||
|
appointment_type: formData.appointment_type,
|
||||||
};
|
};
|
||||||
|
console.log(apiPayload);
|
||||||
|
|
||||||
const handleEdit = async (formData:{ start_time: "", end_time: "", slot_minutes: "", appointment_type: "", id:""}) => {
|
try {
|
||||||
if (isLoading) return;
|
const res = await AvailabilityService.update(formData.id, apiPayload);
|
||||||
setIsLoading(true);
|
console.log(res);
|
||||||
|
|
||||||
const apiPayload = {
|
let message = "disponibilidade editada com sucesso";
|
||||||
start_time: formData.start_time,
|
try {
|
||||||
end_time: formData.end_time,
|
if (!res[0].id) {
|
||||||
slot_minutes: formData.slot_minutes,
|
throw new Error(
|
||||||
appointment_type: formData.appointment_type,
|
`${res.error} ${res.message}` || "A API retornou erro"
|
||||||
};
|
);
|
||||||
console.log(apiPayload);
|
} else {
|
||||||
|
console.log(message);
|
||||||
try {
|
|
||||||
const res = await AvailabilityService.update(formData.id, apiPayload);
|
|
||||||
console.log(res);
|
|
||||||
|
|
||||||
let message = "disponibilidade editada com sucesso";
|
|
||||||
try {
|
|
||||||
if (!res[0].id) {
|
|
||||||
throw new Error(`${res.error} ${res.message}` || "A API retornou erro");
|
|
||||||
} else {
|
|
||||||
console.log(message);
|
|
||||||
}
|
|
||||||
} catch {}
|
|
||||||
|
|
||||||
toast({
|
|
||||||
title: "Sucesso",
|
|
||||||
description: message,
|
|
||||||
});
|
|
||||||
router.push("#")
|
|
||||||
} catch (err: any) {
|
|
||||||
toast({
|
|
||||||
title: "Erro",
|
|
||||||
description: err?.message || "Não foi possível editar a disponibilidade",
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
handleCloseModal();
|
|
||||||
fetchData()
|
|
||||||
}
|
}
|
||||||
};
|
} catch {}
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: "Sucesso",
|
||||||
|
description: message,
|
||||||
|
});
|
||||||
|
router.push("#");
|
||||||
|
} catch (err: any) {
|
||||||
|
toast({
|
||||||
|
title: "Erro",
|
||||||
|
description:
|
||||||
|
err?.message || "Não foi possível editar a disponibilidade",
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
handleCloseModal();
|
||||||
|
fetchData();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// Mapa de tradução
|
// Mapa de tradução
|
||||||
const weekdaysPT: Record<string, string> = {
|
const weekdaysPT: Record<string, string> = {
|
||||||
@ -183,95 +229,96 @@ export default function AvailabilityPage() {
|
|||||||
saturday: "Sábado",
|
saturday: "Sábado",
|
||||||
};
|
};
|
||||||
const fetchData = async () => {
|
const fetchData = async () => {
|
||||||
try {
|
|
||||||
const loggedUser = await usersService.getMe();
|
|
||||||
const doctorList = await doctorsService.list();
|
|
||||||
setUserData(loggedUser);
|
|
||||||
const doctor = findDoctorById(loggedUser.user.id, doctorList);
|
|
||||||
setDoctorId(doctor?.id);
|
|
||||||
console.log(doctor);
|
|
||||||
// Busca disponibilidade
|
|
||||||
const availabilityList = await AvailabilityService.list();
|
|
||||||
|
|
||||||
// Filtra já com a variável local
|
|
||||||
const filteredAvail = availabilityList.filter(
|
|
||||||
(disp: { doctor_id: string }) => disp.doctor_id === doctor?.id
|
|
||||||
);
|
|
||||||
setAvailability(filteredAvail);
|
|
||||||
} catch (e: any) {
|
|
||||||
alert(`${e?.error} ${e?.message}`);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetchData();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
// Função auxiliar para filtrar o id do doctor correspondente ao user logado
|
|
||||||
function findDoctorById(id: string, doctors: Doctor[]) {
|
|
||||||
return doctors.find((doctor) => doctor.user_id === id);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
function formatAvailability(data: Availability[]) {
|
|
||||||
// Agrupar os horários por dia da semana
|
|
||||||
const schedule = data.reduce((acc: any, item) => {
|
|
||||||
const { weekday, start_time, end_time } = item;
|
|
||||||
|
|
||||||
// Se o dia ainda não existe, cria o array
|
|
||||||
if (!acc[weekday]) {
|
|
||||||
acc[weekday] = [];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Adiciona o horário do dia
|
|
||||||
acc[weekday].push({
|
|
||||||
start: start_time,
|
|
||||||
end: end_time,
|
|
||||||
});
|
|
||||||
|
|
||||||
return acc;
|
|
||||||
}, {} as Record<string, { start: string; end: string }[]>);
|
|
||||||
|
|
||||||
return schedule;
|
|
||||||
}
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (availability) {
|
|
||||||
const formatted = formatAvailability(availability);
|
|
||||||
setSchedule(formatted);
|
|
||||||
}
|
|
||||||
}, [availability]);
|
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
|
||||||
e.preventDefault();
|
|
||||||
if (isLoading) return;
|
|
||||||
setIsLoading(true);
|
|
||||||
const form = e.currentTarget;
|
|
||||||
const formData = new FormData(form);
|
|
||||||
|
|
||||||
const apiPayload = {
|
|
||||||
doctor_id: doctorId,
|
|
||||||
weekday: (formData.get("weekday") as string) || undefined,
|
|
||||||
start_time: (formData.get("horarioEntrada") as string) || undefined,
|
|
||||||
end_time: (formData.get("horarioSaida") as string) || undefined,
|
|
||||||
slot_minutes: Number(formData.get("duracaoConsulta")) || undefined,
|
|
||||||
appointment_type: modalidadeConsulta || undefined,
|
|
||||||
active: true,
|
|
||||||
};
|
|
||||||
console.log(apiPayload);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await AvailabilityService.create(apiPayload);
|
const loggedUser = await usersService.getMe();
|
||||||
console.log(res);
|
const doctorList = await doctorsService.list();
|
||||||
|
setUserData(loggedUser);
|
||||||
|
const doctor = findDoctorById(loggedUser.user.id, doctorList);
|
||||||
|
setDoctorId(doctor?.id);
|
||||||
|
console.log(doctor);
|
||||||
|
// Busca disponibilidade
|
||||||
|
const availabilityList = await AvailabilityService.list();
|
||||||
|
|
||||||
|
// Filtra já com a variável local
|
||||||
|
const filteredAvail = availabilityList.filter(
|
||||||
|
(disp: { doctor_id: string }) => disp.doctor_id === doctor?.id
|
||||||
|
);
|
||||||
|
setAvailability(filteredAvail);
|
||||||
|
} catch (e: any) {
|
||||||
|
alert(`${e?.error} ${e?.message}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
let message = "disponibilidade cadastrada com sucesso";
|
useEffect(() => {
|
||||||
try {
|
fetchData();
|
||||||
if (!res[0].id) {
|
}, []);
|
||||||
throw new Error(`${res.error} ${res.message}` || "A API retornou erro");
|
|
||||||
} else {
|
// Função auxiliar para filtrar o id do doctor correspondente ao user logado
|
||||||
console.log(message);
|
function findDoctorById(id: string, doctors: Doctor[]) {
|
||||||
}
|
return doctors.find((doctor) => doctor.user_id === id);
|
||||||
} catch {}
|
}
|
||||||
|
|
||||||
|
function formatAvailability(data: Availability[]) {
|
||||||
|
// Agrupar os horários por dia da semana
|
||||||
|
const schedule = data.reduce((acc: any, item) => {
|
||||||
|
const { weekday, start_time, end_time } = item;
|
||||||
|
|
||||||
|
// Se o dia ainda não existe, cria o array
|
||||||
|
if (!acc[weekday]) {
|
||||||
|
acc[weekday] = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Adiciona o horário do dia
|
||||||
|
acc[weekday].push({
|
||||||
|
start: start_time,
|
||||||
|
end: end_time,
|
||||||
|
});
|
||||||
|
|
||||||
|
return acc;
|
||||||
|
}, {} as Record<string, { start: string; end: string }[]>);
|
||||||
|
|
||||||
|
return schedule;
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (availability) {
|
||||||
|
const formatted = formatAvailability(availability);
|
||||||
|
setSchedule(formatted);
|
||||||
|
}
|
||||||
|
}, [availability]);
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (isLoading) return;
|
||||||
|
setIsLoading(true);
|
||||||
|
const form = e.currentTarget;
|
||||||
|
const formData = new FormData(form);
|
||||||
|
|
||||||
|
const apiPayload = {
|
||||||
|
doctor_id: doctorId,
|
||||||
|
weekday: (formData.get("weekday") as string) || undefined,
|
||||||
|
start_time: (formData.get("horarioEntrada") as string) || undefined,
|
||||||
|
end_time: (formData.get("horarioSaida") as string) || undefined,
|
||||||
|
slot_minutes: Number(formData.get("duracaoConsulta")) || undefined,
|
||||||
|
appointment_type: modalidadeConsulta || undefined,
|
||||||
|
active: true,
|
||||||
|
};
|
||||||
|
console.log(apiPayload);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await AvailabilityService.create(apiPayload);
|
||||||
|
console.log(res);
|
||||||
|
|
||||||
|
let message = "disponibilidade cadastrada com sucesso";
|
||||||
|
try {
|
||||||
|
if (!res[0].id) {
|
||||||
|
throw new Error(
|
||||||
|
`${res.error} ${res.message}` || "A API retornou erro"
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
console.log(message);
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
|
||||||
toast({
|
toast({
|
||||||
title: "Sucesso",
|
title: "Sucesso",
|
||||||
@ -284,14 +331,18 @@ export default function AvailabilityPage() {
|
|||||||
description: err?.message || "Não foi possível criar a disponibilidade",
|
description: err?.message || "Não foi possível criar a disponibilidade",
|
||||||
});
|
});
|
||||||
} finally {
|
} finally {
|
||||||
|
fetchData()
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const openDeleteDialog = (schedule: { start: string; end: string;}, day: string) => {
|
const openDeleteDialog = (
|
||||||
selectAvailability(schedule, day)
|
schedule: { start: string; end: string },
|
||||||
setDeleteDialogOpen(true);
|
day: string
|
||||||
};
|
) => {
|
||||||
|
selectAvailability(schedule, day);
|
||||||
|
setDeleteDialogOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
const handleDeleteAvailability = async (AvailabilityId: string) => {
|
const handleDeleteAvailability = async (AvailabilityId: string) => {
|
||||||
try {
|
try {
|
||||||
@ -318,109 +369,185 @@ export default function AvailabilityPage() {
|
|||||||
description: e?.message || "Não foi possível deletar a disponibilidade",
|
description: e?.message || "Não foi possível deletar a disponibilidade",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
fetchData()
|
||||||
setDeleteDialogOpen(false);
|
setDeleteDialogOpen(false);
|
||||||
setSelectedAvailability(null);
|
setSelectedAvailability(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DoctorLayout>
|
<Sidebar>
|
||||||
|
<div className="space-y-6 flex-1 overflow-y-auto p-6">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold text-gray-900">
|
||||||
|
Definir Disponibilidade
|
||||||
|
</h1>
|
||||||
|
<p className="text-gray-600">
|
||||||
|
Defina sua disponibilidade para consultas{" "}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form className="space-y-6" onSubmit={handleSubmit}>
|
||||||
|
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
||||||
|
<h2 className="text-lg font-semibold text-gray-900 mb-6">Dados </h2>
|
||||||
|
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="flex items-center justify-between">
|
{/* **AJUSTE DE RESPONSIVIDADE: DIAS DA SEMANA** */}
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-gray-900">Definir Disponibilidade</h1>
|
<Label className="text-sm font-medium text-gray-700">
|
||||||
<p className="text-gray-600">Defina sua disponibilidade para consultas </p>
|
Dia Da Semana
|
||||||
</div>
|
</Label>
|
||||||
|
{/* O antigo 'flex gap-4 mt-2 flex-nowrap' foi substituído por um grid responsivo: */}
|
||||||
|
<div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-7 gap-x-4 gap-y-2 mt-2">
|
||||||
|
<label className="flex items-center gap-1">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="weekday"
|
||||||
|
value="monday"
|
||||||
|
className="text-blue-600"
|
||||||
|
/>
|
||||||
|
<span className="whitespace-nowrap text-sm">Segunda</span>
|
||||||
|
</label>
|
||||||
|
<label className="flex items-center gap-1">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="weekday"
|
||||||
|
value="tuesday"
|
||||||
|
className="text-blue-600"
|
||||||
|
/>
|
||||||
|
<span className="whitespace-nowrap text-sm">Terça</span>
|
||||||
|
</label>
|
||||||
|
<label className="flex items-center gap-1">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="weekday"
|
||||||
|
value="wednesday"
|
||||||
|
className="text-blue-600"
|
||||||
|
/>
|
||||||
|
<span className="whitespace-nowrap text-sm">Quarta</span>
|
||||||
|
</label>
|
||||||
|
<label className="flex items-center gap-1">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="weekday"
|
||||||
|
value="thursday"
|
||||||
|
className="text-blue-600"
|
||||||
|
/>
|
||||||
|
<span className="whitespace-nowrap text-sm">Quinta</span>
|
||||||
|
</label>
|
||||||
|
<label className="flex items-center gap-1">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="weekday"
|
||||||
|
value="friday"
|
||||||
|
className="text-blue-600"
|
||||||
|
/>
|
||||||
|
<span className="whitespace-nowrap text-sm">Sexta</span>
|
||||||
|
</label>
|
||||||
|
<label className="flex items-center gap-1">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="weekday"
|
||||||
|
value="saturday"
|
||||||
|
className="text-blue-600"
|
||||||
|
/>
|
||||||
|
<span className="whitespace-nowrap text-sm">Sábado</span>
|
||||||
|
</label>
|
||||||
|
<label className="flex items-center gap-1">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="weekday"
|
||||||
|
value="sunday"
|
||||||
|
className="text-blue-600"
|
||||||
|
/>
|
||||||
|
<span className="whitespace-nowrap text-sm">Domingo</span>
|
||||||
|
</label>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<form className="space-y-6" onSubmit={handleSubmit}>
|
{/* **AJUSTE DE RESPONSIVIDADE: HORÁRIO E DURAÇÃO** */}
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
{/* Ajustado para 1 coluna em móvel, 2 em tablet e 5 em desktop (mantendo o que já existia com ajustes) */}
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Dados </h2>
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-6">
|
||||||
|
<div>
|
||||||
|
<Label
|
||||||
|
htmlFor="horarioEntrada"
|
||||||
|
className="text-sm font-medium text-gray-700"
|
||||||
|
>
|
||||||
|
Horario De Entrada
|
||||||
|
</Label>
|
||||||
|
<Input
|
||||||
|
type="time"
|
||||||
|
id="horarioEntrada"
|
||||||
|
name="horarioEntrada"
|
||||||
|
required
|
||||||
|
className="mt-1"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Label
|
||||||
|
htmlFor="horarioSaida"
|
||||||
|
className="text-sm font-medium text-gray-700"
|
||||||
|
>
|
||||||
|
Horario De Saida
|
||||||
|
</Label>
|
||||||
|
<Input
|
||||||
|
type="time"
|
||||||
|
id="horarioSaida"
|
||||||
|
name="horarioSaida"
|
||||||
|
required
|
||||||
|
className="mt-1"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Label
|
||||||
|
htmlFor="duracaoConsulta"
|
||||||
|
className="text-sm font-medium text-gray-700"
|
||||||
|
>
|
||||||
|
Duração Da Consulta (min)
|
||||||
|
</Label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
id="duracaoConsulta"
|
||||||
|
name="duracaoConsulta"
|
||||||
|
required
|
||||||
|
className="mt-1"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{/* O Select de modalidade fica fora deste grid para ocupar uma linha inteira em telas menores, como no original, garantindo clareza */}
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="space-y-6">
|
<div>
|
||||||
{/* **AJUSTE DE RESPONSIVIDADE: DIAS DA SEMANA** */}
|
<Label
|
||||||
<div>
|
htmlFor="modalidadeConsulta"
|
||||||
<Label className="text-sm font-medium text-gray-700">Dia Da Semana</Label>
|
className="text-sm font-medium text-gray-700"
|
||||||
{/* O antigo 'flex gap-4 mt-2 flex-nowrap' foi substituído por um grid responsivo: */}
|
>
|
||||||
<div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-7 gap-x-4 gap-y-2 mt-2">
|
Modalidade De Consulta
|
||||||
<label className="flex items-center gap-1">
|
</Label>
|
||||||
<input type="radio" name="weekday" value="monday" className="text-blue-600" />
|
<Select
|
||||||
<span className="whitespace-nowrap text-sm">Segunda</span>
|
onValueChange={(value) => setModalidadeConsulta(value)}
|
||||||
</label>
|
value={modalidadeConsulta}
|
||||||
<label className="flex items-center gap-1">
|
>
|
||||||
<input type="radio" name="weekday" value="tuesday" className="text-blue-600" />
|
<SelectTrigger className="mt-1">
|
||||||
<span className="whitespace-nowrap text-sm">Terça</span>
|
<SelectValue placeholder="Selecione" />
|
||||||
</label>
|
</SelectTrigger>
|
||||||
<label className="flex items-center gap-1">
|
<SelectContent>
|
||||||
<input type="radio" name="weekday" value="wednesday" className="text-blue-600" />
|
<SelectItem value="presencial">Presencial </SelectItem>
|
||||||
<span className="whitespace-nowrap text-sm">Quarta</span>
|
<SelectItem value="telemedicina">Telemedicina</SelectItem>
|
||||||
</label>
|
</SelectContent>
|
||||||
<label className="flex items-center gap-1">
|
</Select>
|
||||||
<input type="radio" name="weekday" value="thursday" className="text-blue-600" />
|
</div>
|
||||||
<span className="whitespace-nowrap text-sm">Quinta</span>
|
</div>
|
||||||
</label>
|
</div>
|
||||||
<label className="flex items-center gap-1">
|
|
||||||
<input type="radio" name="weekday" value="friday" className="text-blue-600" />
|
|
||||||
<span className="whitespace-nowrap text-sm">Sexta</span>
|
|
||||||
</label>
|
|
||||||
<label className="flex items-center gap-1">
|
|
||||||
<input type="radio" name="weekday" value="saturday" className="text-blue-600" />
|
|
||||||
<span className="whitespace-nowrap text-sm">Sábado</span>
|
|
||||||
</label>
|
|
||||||
<label className="flex items-center gap-1">
|
|
||||||
<input type="radio" name="weekday" value="sunday" className="text-blue-600" />
|
|
||||||
<span className="whitespace-nowrap text-sm">Domingo</span>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* **AJUSTE DE RESPONSIVIDADE: HORÁRIO E DURAÇÃO** */}
|
|
||||||
{/* Ajustado para 1 coluna em móvel, 2 em tablet e 5 em desktop (mantendo o que já existia com ajustes) */}
|
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-6">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="horarioEntrada" className="text-sm font-medium text-gray-700">
|
|
||||||
Horario De Entrada
|
|
||||||
</Label>
|
|
||||||
<Input type="time" id="horarioEntrada" name="horarioEntrada" required className="mt-1" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="horarioSaida" className="text-sm font-medium text-gray-700">
|
|
||||||
Horario De Saida
|
|
||||||
</Label>
|
|
||||||
<Input type="time" id="horarioSaida" name="horarioSaida" required className="mt-1" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="duracaoConsulta" className="text-sm font-medium text-gray-700">
|
|
||||||
Duração Da Consulta (min)
|
|
||||||
</Label>
|
|
||||||
<Input type="number" id="duracaoConsulta" name="duracaoConsulta" required className="mt-1" />
|
|
||||||
</div>
|
|
||||||
{/* O Select de modalidade fica fora deste grid para ocupar uma linha inteira em telas menores, como no original, garantindo clareza */}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="modalidadeConsulta" className="text-sm font-medium text-gray-700">
|
|
||||||
Modalidade De Consulta
|
|
||||||
</Label>
|
|
||||||
<Select onValueChange={(value) => setModalidadeConsulta(value)} value={modalidadeConsulta}>
|
|
||||||
<SelectTrigger className="mt-1">
|
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="presencial">Presencial </SelectItem>
|
|
||||||
<SelectItem value="telemedicina">Telemedicina</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* **AJUSTE DE RESPONSIVIDADE: BOTÕES DE AÇÃO** */}
|
{/* **AJUSTE DE RESPONSIVIDADE: BOTÕES DE AÇÃO** */}
|
||||||
{/* Alinha à direita em telas maiores e empilha (com o botão primário no final) em telas menores */}
|
{/* Alinha à direita em telas maiores e empilha (com o botão primário no final) em telas menores */}
|
||||||
|
{/* Alteração aqui: Adicionado w-full aos Links e Buttons para ocuparem a largura total em telas pequenas */}
|
||||||
<div className="flex flex-col-reverse sm:flex-row sm:justify-between gap-4">
|
<div className="flex flex-col-reverse sm:flex-row sm:justify-between gap-4">
|
||||||
<Link href="/doctor/disponibilidade/excecoes" className="w-full sm:w-auto">
|
<Link href="/doctor/disponibilidade/excecoes" className="w-full sm:w-auto">
|
||||||
<Button variant="default" className="w-full sm:w-auto">Adicionar Exceção</Button>
|
<Button variant="default" className="w-full sm:w-auto">Adicionar Exceção</Button>
|
||||||
</Link>
|
</Link>
|
||||||
<div className="flex gap-4 w-full sm:w-auto">
|
<div className="flex flex-col sm:flex-row gap-4 w-full sm:w-auto"> {/* Ajustado para empilhar os botões Cancelar e Salvar em telas pequenas */}
|
||||||
<Link href="/doctor/dashboard" className="w-full sm:w-auto">
|
<Link href="/doctor/dashboard" className="w-full sm:w-auto">
|
||||||
<Button variant="outline" className="w-full sm:w-auto">Cancelar</Button>
|
<Button variant="outline" className="w-full sm:w-auto">Cancelar</Button>
|
||||||
</Link>
|
</Link>
|
||||||
@ -452,7 +579,7 @@ export default function AvailabilityPage() {
|
|||||||
<div key={i}>
|
<div key={i}>
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<p className="text-sm text-gray-600 cursor-pointer p-1 rounded hover:text-accent-foreground hover:bg-gray-200 transition-colors duration-150">
|
<p className="text-sm text-gray-600 cursor-pointer rounded hover:text-accent-foreground hover:bg-gray-200 transition-colors duration-150">
|
||||||
{formatTime(t.start)} - {formatTime(t.end)}
|
{formatTime(t.start)} - {formatTime(t.end)}
|
||||||
</p>
|
</p>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
@ -506,6 +633,6 @@ export default function AvailabilityPage() {
|
|||||||
onSubmit={handleEdit}
|
onSubmit={handleEdit}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
</DoctorLayout>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -12,7 +12,7 @@ import { Textarea } from "@/components/ui/textarea";
|
|||||||
import { Checkbox } from "@/components/ui/checkbox";
|
import { Checkbox } from "@/components/ui/checkbox";
|
||||||
import { ArrowLeft, Save } from "lucide-react";
|
import { ArrowLeft, Save } from "lucide-react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import DoctorLayout from "@/components/doctor-layout";
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
// Mock data - in a real app, this would come from an API
|
// Mock data - in a real app, this would come from an API
|
||||||
const mockDoctors = [
|
const mockDoctors = [
|
||||||
@ -124,7 +124,7 @@ export default function EditarMedicoPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DoctorLayout>
|
<Sidebar>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex items-center gap-4">
|
||||||
<Link href="/medicos">
|
<Link href="/medicos">
|
||||||
@ -512,6 +512,6 @@ export default function EditarMedicoPage() {
|
|||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</DoctorLayout>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
import { useParams, useRouter } from "next/navigation";
|
import { useParams, useRouter } from "next/navigation";
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import DoctorLayout from "@/components/doctor-layout";
|
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
@ -17,6 +16,7 @@ import { format } from "date-fns";
|
|||||||
import TiptapEditor from "@/components/ui/tiptap-editor";
|
import TiptapEditor from "@/components/ui/tiptap-editor";
|
||||||
import { Skeleton } from "@/components/ui/skeleton";
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
import { reportsApi } from "@/services/reportsApi.mjs";
|
import { reportsApi } from "@/services/reportsApi.mjs";
|
||||||
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
export default function EditarLaudoPage() {
|
export default function EditarLaudoPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@ -108,7 +108,7 @@ export default function EditarLaudoPage() {
|
|||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
return (
|
return (
|
||||||
<DoctorLayout>
|
<Sidebar>
|
||||||
<div className="container mx-auto p-4">
|
<div className="container mx-auto p-4">
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
@ -130,12 +130,12 @@ export default function EditarLaudoPage() {
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
</DoctorLayout>
|
</Sidebar>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DoctorLayout>
|
<Sidebar>
|
||||||
<div className="container mx-auto p-4">
|
<div className="container mx-auto p-4">
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
@ -228,6 +228,6 @@ export default function EditarLaudoPage() {
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
</DoctorLayout>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -16,7 +16,7 @@ import { format } from "date-fns";
|
|||||||
import TiptapEditor from "@/components/ui/tiptap-editor";
|
import TiptapEditor from "@/components/ui/tiptap-editor";
|
||||||
|
|
||||||
import { reportsApi } from "@/services/reportsApi.mjs";
|
import { reportsApi } from "@/services/reportsApi.mjs";
|
||||||
import DoctorLayout from "@/components/doctor-layout";
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@ -96,7 +96,7 @@ export default function NovoLaudoPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DoctorLayout>
|
<Sidebar>
|
||||||
<div className="container mx-auto p-4">
|
<div className="container mx-auto p-4">
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
@ -184,6 +184,6 @@ export default function NovoLaudoPage() {
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
</DoctorLayout>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -8,7 +8,7 @@ import Link from 'next/link';
|
|||||||
import { useParams } from 'next/navigation';
|
import { useParams } from 'next/navigation';
|
||||||
import { api } from '@/services/api.mjs';
|
import { api } from '@/services/api.mjs';
|
||||||
import { reportsApi } from '@/services/reportsApi.mjs';
|
import { reportsApi } from '@/services/reportsApi.mjs';
|
||||||
import DoctorLayout from '@/components/doctor-layout';
|
import Sidebar from '@/components/Sidebar';
|
||||||
|
|
||||||
export default function LaudosPage() {
|
export default function LaudosPage() {
|
||||||
const [patient, setPatient] = useState(null);
|
const [patient, setPatient] = useState(null);
|
||||||
@ -49,7 +49,7 @@ export default function LaudosPage() {
|
|||||||
const paginate = (pageNumber) => setCurrentPage(pageNumber);
|
const paginate = (pageNumber) => setCurrentPage(pageNumber);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DoctorLayout>
|
<Sidebar>
|
||||||
<div className="container mx-auto p-4">
|
<div className="container mx-auto p-4">
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<p>Carregando...</p>
|
<p>Carregando...</p>
|
||||||
@ -123,6 +123,6 @@ export default function LaudosPage() {
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</DoctorLayout>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -9,7 +9,7 @@ import { Textarea } from "@/components/ui/textarea";
|
|||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
import { Upload, Plus, X, ChevronDown } from "lucide-react";
|
import { Upload, Plus, X, ChevronDown } from "lucide-react";
|
||||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
|
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
|
||||||
import DoctorLayout from "@/components/doctor-layout";
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
export default function NovoMedicoPage() {
|
export default function NovoMedicoPage() {
|
||||||
const [anexosOpen, setAnexosOpen] = useState(false);
|
const [anexosOpen, setAnexosOpen] = useState(false);
|
||||||
@ -24,7 +24,7 @@ export default function NovoMedicoPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DoctorLayout>
|
<Sidebar>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
@ -466,6 +466,6 @@ export default function NovoMedicoPage() {
|
|||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</DoctorLayout>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,8 +1,6 @@
|
|||||||
// app/doctor/pacientes/page.tsx (assumindo a localização)
|
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useState, useCallback } from "react";
|
import { useEffect, useState, useCallback } from "react";
|
||||||
import DoctorLayout from "@/components/doctor-layout";
|
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
@ -21,6 +19,7 @@ import {
|
|||||||
SelectValue,
|
SelectValue,
|
||||||
} from "@/components/ui/select";
|
} from "@/components/ui/select";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
interface Paciente {
|
interface Paciente {
|
||||||
id: string;
|
id: string;
|
||||||
@ -51,7 +50,7 @@ export default function PacientesPage() {
|
|||||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||||
|
|
||||||
// --- Lógica de Paginação INÍCIO ---
|
// --- Lógica de Paginação INÍCIO ---
|
||||||
const [itemsPerPage, setItemsPerPage] = useState(5);
|
const [itemsPerPage, setItemsPerPage] = useState(10);
|
||||||
const [currentPage, setCurrentPage] = useState(1);
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
|
|
||||||
const totalPages = Math.ceil(pacientes.length / itemsPerPage);
|
const totalPages = Math.ceil(pacientes.length / itemsPerPage);
|
||||||
@ -70,7 +69,7 @@ export default function PacientesPage() {
|
|||||||
const goToNextPage = () => {
|
const goToNextPage = () => {
|
||||||
setCurrentPage((prev) => Math.min(totalPages, prev + 1));
|
setCurrentPage((prev) => Math.min(totalPages, prev + 1));
|
||||||
};
|
};
|
||||||
|
|
||||||
// Lógica para gerar os números das páginas visíveis (máximo de 5)
|
// Lógica para gerar os números das páginas visíveis (máximo de 5)
|
||||||
const getVisiblePageNumbers = (totalPages: number, currentPage: number) => {
|
const getVisiblePageNumbers = (totalPages: number, currentPage: number) => {
|
||||||
const pages: number[] = [];
|
const pages: number[] = [];
|
||||||
@ -87,13 +86,13 @@ export default function PacientesPage() {
|
|||||||
endPage = Math.min(totalPages, maxVisiblePages);
|
endPage = Math.min(totalPages, maxVisiblePages);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (let i = startPage; i <= endPage; i++) {
|
for (let i = startPage; i <= endPage; i++) {
|
||||||
pages.push(i);
|
pages.push(i);
|
||||||
}
|
}
|
||||||
return pages;
|
return pages;
|
||||||
};
|
};
|
||||||
|
|
||||||
const visiblePageNumbers = getVisiblePageNumbers(totalPages, currentPage);
|
const visiblePageNumbers = getVisiblePageNumbers(totalPages, currentPage);
|
||||||
|
|
||||||
// Lógica para mudar itens por página, resetando para a página 1
|
// Lógica para mudar itens por página, resetando para a página 1
|
||||||
@ -103,7 +102,6 @@ export default function PacientesPage() {
|
|||||||
};
|
};
|
||||||
// --- Lógica de Paginação FIM ---
|
// --- Lógica de Paginação FIM ---
|
||||||
|
|
||||||
|
|
||||||
const handleOpenModal = (patient: Paciente) => {
|
const handleOpenModal = (patient: Paciente) => {
|
||||||
setSelectedPatient(patient);
|
setSelectedPatient(patient);
|
||||||
setIsModalOpen(true);
|
setIsModalOpen(true);
|
||||||
@ -171,23 +169,26 @@ export default function PacientesPage() {
|
|||||||
}, [fetchPacientes]);
|
}, [fetchPacientes]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DoctorLayout>
|
<Sidebar>
|
||||||
<div className="space-y-6 px-2 sm:px-4 md:px-6">
|
<div className="space-y-6 px-2 sm:px-4 md:px-6">
|
||||||
{/* Cabeçalho */}
|
{/* Cabeçalho */}
|
||||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
|
||||||
|
{" "}
|
||||||
|
{/* Ajustado para flex-col em telas pequenas */}
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-foreground">Pacientes</h1>
|
<h1 className="text-2xl font-bold text-foreground">Pacientes</h1>
|
||||||
<p className="text-muted-foreground text-sm sm:text-base">
|
<p className="text-muted-foreground text-sm sm:text-base">
|
||||||
Lista de pacientes vinculados
|
Lista de pacientes vinculados
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
{/* Adicione um seletor de itens por página ao lado de um botão de 'Novo Paciente' se aplicável */}
|
{/* Controles de filtro e novo paciente */}
|
||||||
<div className="flex gap-3">
|
{/* Alterado para que o Select e o Link ocupem a largura total em telas pequenas e fiquem lado a lado em telas maiores */}
|
||||||
|
<div className="flex flex-wrap gap-3 mt-4 sm:mt-0 w-full sm:w-auto justify-start sm:justify-end">
|
||||||
<Select
|
<Select
|
||||||
onValueChange={handleItemsPerPageChange}
|
onValueChange={handleItemsPerPageChange}
|
||||||
defaultValue={String(itemsPerPage)}
|
defaultValue={String(itemsPerPage)}
|
||||||
>
|
>
|
||||||
<SelectTrigger className="w-[140px]">
|
<SelectTrigger className="w-full sm:w-[140px]">
|
||||||
<SelectValue placeholder="Itens por pág." />
|
<SelectValue placeholder="Itens por pág." />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
@ -196,22 +197,21 @@ export default function PacientesPage() {
|
|||||||
<SelectItem value="20">20 por página</SelectItem>
|
<SelectItem value="20">20 por página</SelectItem>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
<Link href="/doctor/pacientes/novo">
|
|
||||||
<Button variant="default" className="bg-green-600 hover:bg-green-700">
|
|
||||||
Novo Paciente
|
|
||||||
</Button>
|
|
||||||
</Link>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
<div className="bg-card rounded-lg border border-border overflow-hidden shadow-md">
|
<div className="bg-card rounded-lg border border-border overflow-hidden shadow-md">
|
||||||
<div className="overflow-x-auto">
|
{/* Tabela para Telas Médias e Grandes */}
|
||||||
|
<div className="overflow-x-auto hidden md:block">
|
||||||
|
{" "}
|
||||||
|
{/* Esconde em telas pequenas */}
|
||||||
<table className="min-w-[600px] w-full">
|
<table className="min-w-[600px] w-full">
|
||||||
<thead className="bg-muted border-b border-border">
|
<thead className="bg-muted border-b border-border">
|
||||||
<tr>
|
<tr>
|
||||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground">Nome</th>
|
<th className="text-left p-3 sm:p-4 font-medium text-foreground">
|
||||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden md:table-cell">
|
Nome
|
||||||
|
</th>
|
||||||
|
<th className="text-left p-3 sm:p-4 font-medium text-foreground">
|
||||||
Telefone
|
Telefone
|
||||||
</th>
|
</th>
|
||||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden lg:table-cell">
|
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden lg:table-cell">
|
||||||
@ -226,24 +226,35 @@ export default function PacientesPage() {
|
|||||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden xl:table-cell">
|
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden xl:table-cell">
|
||||||
Próximo atendimento
|
Próximo atendimento
|
||||||
</th>
|
</th>
|
||||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground">Ações</th>
|
<th className="text-left p-3 sm:p-4 font-medium text-foreground">
|
||||||
|
Ações
|
||||||
|
</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan={7} className="p-6 text-muted-foreground text-center">
|
<td
|
||||||
|
colSpan={7}
|
||||||
|
className="p-6 text-muted-foreground text-center"
|
||||||
|
>
|
||||||
<Loader2 className="w-6 h-6 animate-spin mx-auto text-primary" />
|
<Loader2 className="w-6 h-6 animate-spin mx-auto text-primary" />
|
||||||
Carregando pacientes...
|
Carregando pacientes...
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
) : error ? (
|
) : error ? (
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan={7} className="p-6 text-red-600 text-center">{`Erro: ${error}`}</td>
|
<td
|
||||||
|
colSpan={7}
|
||||||
|
className="p-6 text-red-600 text-center"
|
||||||
|
>{`Erro: ${error}`}</td>
|
||||||
</tr>
|
</tr>
|
||||||
) : pacientes.length === 0 ? (
|
) : pacientes.length === 0 ? (
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan={7} className="p-8 text-center text-muted-foreground">
|
<td
|
||||||
|
colSpan={7}
|
||||||
|
className="p-8 text-center text-muted-foreground"
|
||||||
|
>
|
||||||
Nenhum paciente encontrado
|
Nenhum paciente encontrado
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
@ -254,7 +265,7 @@ export default function PacientesPage() {
|
|||||||
className="border-b border-border hover:bg-accent/40 transition-colors"
|
className="border-b border-border hover:bg-accent/40 transition-colors"
|
||||||
>
|
>
|
||||||
<td className="p-3 sm:p-4">{p.nome}</td>
|
<td className="p-3 sm:p-4">{p.nome}</td>
|
||||||
<td className="p-3 sm:p-4 text-muted-foreground hidden md:table-cell">
|
<td className="p-3 sm:p-4 text-muted-foreground">
|
||||||
{p.telefone}
|
{p.telefone}
|
||||||
</td>
|
</td>
|
||||||
<td className="p-3 sm:p-4 text-muted-foreground hidden lg:table-cell">
|
<td className="p-3 sm:p-4 text-muted-foreground hidden lg:table-cell">
|
||||||
@ -278,7 +289,9 @@ export default function PacientesPage() {
|
|||||||
</Button>
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
<DropdownMenuItem onClick={() => handleOpenModal(p)}>
|
<DropdownMenuItem
|
||||||
|
onClick={() => handleOpenModal(p)}
|
||||||
|
>
|
||||||
<Eye className="w-4 h-4 mr-2" />
|
<Eye className="w-4 h-4 mr-2" />
|
||||||
Ver detalhes
|
Ver detalhes
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
@ -290,11 +303,11 @@ export default function PacientesPage() {
|
|||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
// Simulação de exclusão (A exclusão real deve ser feita via API)
|
const newPacientes = pacientes.filter(
|
||||||
const newPacientes = pacientes.filter((pac) => pac.id !== p.id);
|
(pac) => pac.id !== p.id
|
||||||
|
);
|
||||||
setPacientes(newPacientes);
|
setPacientes(newPacientes);
|
||||||
alert(`Paciente ID: ${p.id} excluído`);
|
alert(`Paciente ID: ${p.id} excluído`);
|
||||||
// Necessário chamar a API de exclusão aqui
|
|
||||||
}}
|
}}
|
||||||
className="text-red-600 focus:bg-red-50 focus:text-red-600"
|
className="text-red-600 focus:bg-red-50 focus:text-red-600"
|
||||||
>
|
>
|
||||||
@ -311,10 +324,90 @@ export default function PacientesPage() {
|
|||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Paginação ATUALIZADA */}
|
{/* Layout em Cards/Lista para Telas Pequenas */}
|
||||||
|
<div className="md:hidden divide-y divide-border">
|
||||||
|
{" "}
|
||||||
|
{/* Visível apenas em telas pequenas */}
|
||||||
|
{loading ? (
|
||||||
|
<div className="p-6 text-muted-foreground text-center">
|
||||||
|
<Loader2 className="w-6 h-6 animate-spin mx-auto text-primary" />
|
||||||
|
Carregando pacientes...
|
||||||
|
</div>
|
||||||
|
) : error ? (
|
||||||
|
<div className="p-6 text-red-600 text-center">{`Erro: ${error}`}</div>
|
||||||
|
) : pacientes.length === 0 ? (
|
||||||
|
<div className="p-8 text-center text-muted-foreground">
|
||||||
|
Nenhum paciente encontrado
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
currentItems.map((p) => (
|
||||||
|
<div
|
||||||
|
key={p.id}
|
||||||
|
className="flex items-center justify-between p-4 hover:bg-accent/40 transition-colors"
|
||||||
|
>
|
||||||
|
<div className="flex-1 min-w-0 pr-4">
|
||||||
|
{" "}
|
||||||
|
{/* Adicionado padding à direita */}
|
||||||
|
<div className="text-base font-semibold text-foreground break-words">
|
||||||
|
{" "}
|
||||||
|
{/* Aumentado a fonte e break-words para evitar corte do nome */}
|
||||||
|
{p.nome || "—"}
|
||||||
|
</div>
|
||||||
|
{/* Removido o 'truncate' e adicionado 'break-words' no telefone */}
|
||||||
|
<div className="text-sm text-muted-foreground break-words">
|
||||||
|
Telefone: **{p.telefone || "N/A"}**
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="ml-4 flex-shrink-0">
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button variant="outline" size="icon">
|
||||||
|
<Eye className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end">
|
||||||
|
<DropdownMenuItem onClick={() => handleOpenModal(p)}>
|
||||||
|
<Eye className="w-4 h-4 mr-2" />
|
||||||
|
Ver detalhes
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem asChild>
|
||||||
|
<Link href={`/doctor/pacientes/${p.id}/laudos`}>
|
||||||
|
<Edit className="w-4 h-4 mr-2" />
|
||||||
|
Laudos
|
||||||
|
</Link>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem
|
||||||
|
onClick={() =>
|
||||||
|
alert(`Agenda para paciente ID: ${p.id}`)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Calendar className="w-4 h-4 mr-2" />
|
||||||
|
Ver agenda
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem
|
||||||
|
onClick={() => {
|
||||||
|
const newPacientes = pacientes.filter(
|
||||||
|
(pac) => pac.id !== p.id
|
||||||
|
);
|
||||||
|
setPacientes(newPacientes);
|
||||||
|
alert(`Paciente ID: ${p.id} excluído`);
|
||||||
|
}}
|
||||||
|
className="text-red-600 focus:bg-red-50 focus:text-red-600"
|
||||||
|
>
|
||||||
|
<Trash2 className="w-4 h-4 mr-2" />
|
||||||
|
Excluir
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Paginação */}
|
||||||
{totalPages > 1 && (
|
{totalPages > 1 && (
|
||||||
<div className="flex flex-wrap justify-center items-center gap-2 border-t border-border p-4 bg-muted/40">
|
<div className="flex flex-wrap justify-center items-center gap-2 border-t border-border p-4 bg-muted/40">
|
||||||
|
|
||||||
{/* Botão Anterior */}
|
{/* Botão Anterior */}
|
||||||
<button
|
<button
|
||||||
onClick={goToPrevPage}
|
onClick={goToPrevPage}
|
||||||
@ -331,14 +424,14 @@ export default function PacientesPage() {
|
|||||||
onClick={() => paginate(number)}
|
onClick={() => paginate(number)}
|
||||||
className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border border-border ${
|
className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border border-border ${
|
||||||
currentPage === number
|
currentPage === number
|
||||||
? "bg-green-600 text-primary-foreground shadow-md border-green-600"
|
? "bg-blue-600 text-primary-foreground shadow-md border-blue-600"
|
||||||
: "bg-secondary text-secondary-foreground hover:bg-secondary/80"
|
: "bg-secondary text-secondary-foreground hover:bg-secondary/80"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{number}
|
{number}
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
|
|
||||||
{/* Botão Próximo */}
|
{/* Botão Próximo */}
|
||||||
<button
|
<button
|
||||||
onClick={goToNextPage}
|
onClick={goToNextPage}
|
||||||
@ -347,11 +440,8 @@ export default function PacientesPage() {
|
|||||||
>
|
>
|
||||||
{"Próximo >"}
|
{"Próximo >"}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{/* Fim da Paginação ATUALIZADA */}
|
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@ -360,6 +450,6 @@ export default function PacientesPage() {
|
|||||||
isOpen={isModalOpen}
|
isOpen={isModalOpen}
|
||||||
onClose={handleCloseModal}
|
onClose={handleCloseModal}
|
||||||
/>
|
/>
|
||||||
</DoctorLayout>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import FinancierLayout from "@/components/finance-layout";
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
interface Paciente {
|
interface Paciente {
|
||||||
id: string;
|
id: string;
|
||||||
@ -14,43 +14,10 @@ interface Paciente {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function PacientesPage() {
|
export default function PacientesPage() {
|
||||||
const [pacientes, setPacientes] = useState<Paciente[]>([]);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
async function fetchPacientes() {
|
|
||||||
try {
|
|
||||||
setLoading(true);
|
|
||||||
setError(null);
|
|
||||||
const res = await fetch("https://mock.apidog.com/m1/1053378-0-default/pacientes");
|
|
||||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
||||||
const json = await res.json();
|
|
||||||
const items = Array.isArray(json?.data) ? json.data : [];
|
|
||||||
|
|
||||||
const mapped = items.map((p: any) => ({
|
|
||||||
id: String(p.id ?? ""),
|
|
||||||
nome: p.nome ?? "",
|
|
||||||
telefone: p?.contato?.celular ?? p?.contato?.telefone1 ?? p?.telefone ?? "",
|
|
||||||
cidade: p?.endereco?.cidade ?? p?.cidade ?? "",
|
|
||||||
estado: p?.endereco?.estado ?? p?.estado ?? "",
|
|
||||||
ultimoAtendimento: p.ultimo_atendimento ?? p.ultimoAtendimento ?? "",
|
|
||||||
proximoAtendimento: p.proximo_atendimento ?? p.proximoAtendimento ?? "",
|
|
||||||
}));
|
|
||||||
|
|
||||||
setPacientes(mapped);
|
|
||||||
} catch (e: any) {
|
|
||||||
setError(e?.message || "Erro ao carregar pacientes");
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fetchPacientes();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<FinancierLayout>
|
<Sidebar>
|
||||||
<div></div>
|
<div></div>
|
||||||
</FinancierLayout>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,8 +1,6 @@
|
|||||||
@import 'tailwindcss';
|
@import "tailwindcss";
|
||||||
@import 'tw-animate-css';
|
@import "tw-animate-css";
|
||||||
|
|
||||||
@custom-variant dark (&:is(.dark *));
|
@custom-variant dark (&:is(.dark *));
|
||||||
|
|
||||||
:root {
|
:root {
|
||||||
--background: oklch(1 0 0);
|
--background: oklch(1 0 0);
|
||||||
--foreground: oklch(0.145 0 0);
|
--foreground: oklch(0.145 0 0);
|
||||||
@ -75,33 +73,33 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.high-contrast {
|
.high-contrast {
|
||||||
--background: oklch(0 0 0);
|
--background: oklch(0 0 0);
|
||||||
--foreground: oklch(1 0.5 100);
|
--foreground: oklch(1 0.5 100);
|
||||||
--card: oklch(0 0 0);
|
--card: oklch(0 0 0);
|
||||||
--card-foreground: oklch(1 0.5 100);
|
--card-foreground: oklch(1 0.5 100);
|
||||||
--popover: oklch(0 0 0);
|
--popover: oklch(0 0 0);
|
||||||
--popover-foreground: oklch(1 0.5 100);
|
--popover-foreground: oklch(1 0.5 100);
|
||||||
--primary: oklch(1 0.5 100);
|
--primary: oklch(1 0.5 100);
|
||||||
--primary-foreground: oklch(0 0 0);
|
--primary-foreground: oklch(0 0 0);
|
||||||
--secondary: oklch(0 0 0);
|
--secondary: oklch(0 0 0);
|
||||||
--secondary-foreground: oklch(1 0.5 100);
|
--secondary-foreground: oklch(1 0.5 100);
|
||||||
--muted: oklch(0 0 0);
|
--muted: oklch(0 0 0);
|
||||||
--muted-foreground: oklch(1 0.5 100);
|
--muted-foreground: oklch(1 0.5 100);
|
||||||
--accent: oklch(0 0 0);
|
--accent: oklch(0 0 0);
|
||||||
--accent-foreground: oklch(1 0.5 100);
|
--accent-foreground: oklch(1 0.5 100);
|
||||||
--destructive: oklch(0.5 0.3 30);
|
--destructive: oklch(0.5 0.3 30);
|
||||||
--destructive-foreground: oklch(0 0 0);
|
--destructive-foreground: oklch(0 0 0);
|
||||||
--border: oklch(1 0.5 100);
|
--border: oklch(1 0.5 100);
|
||||||
--input: oklch(0 0 0);
|
--input: oklch(0 0 0);
|
||||||
--ring: oklch(1 0.5 100);
|
--ring: oklch(1 0.5 100);
|
||||||
--sidebar: oklch(0 0 0);
|
--sidebar: oklch(0 0 0);
|
||||||
--sidebar-foreground: oklch(1 0.5 100);
|
--sidebar-foreground: oklch(1 0.5 100);
|
||||||
--sidebar-primary: oklch(1 0.5 100);
|
--sidebar-primary: oklch(1 0.5 100);
|
||||||
--sidebar-primary-foreground: oklch(0 0 0);
|
--sidebar-primary-foreground: oklch(0 0 0);
|
||||||
--sidebar-accent: oklch(0 0 0);
|
--sidebar-accent: oklch(0 0 0);
|
||||||
--sidebar-accent-foreground: oklch(1 0.5 100);
|
--sidebar-accent-foreground: oklch(1 0.5 100);
|
||||||
--sidebar-border: oklch(1 0.5 100);
|
--sidebar-border: oklch(1 0.5 100);
|
||||||
--sidebar-ring: oklch(1 0.5 100);
|
--sidebar-ring: oklch(1 0.5 100);
|
||||||
}
|
}
|
||||||
|
|
||||||
@theme inline {
|
@theme inline {
|
||||||
@ -153,4 +151,4 @@
|
|||||||
@apply bg-background text-foreground;
|
@apply bg-background text-foreground;
|
||||||
transition: background-color 0.3s, color 0.3s;
|
transition: background-color 0.3s, color 0.3s;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,82 +1,260 @@
|
|||||||
// Caminho: app/login/page.tsx
|
// Caminho: app/login/page.tsx
|
||||||
|
|
||||||
|
"use client";
|
||||||
|
|
||||||
|
import { usersService } from "@/services/usersApi.mjs";
|
||||||
import { LoginForm } from "@/components/LoginForm";
|
import { LoginForm } from "@/components/LoginForm";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { ArrowLeft } from "lucide-react"; // Importa o ícone de seta
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { ArrowLeft, X } from "lucide-react";
|
||||||
|
import { useState } from "react";
|
||||||
|
import RenderFromTemplateContext from "next/dist/client/components/render-from-template-context";
|
||||||
|
|
||||||
export default function LoginPage() {
|
export default function LoginPage() {
|
||||||
return (
|
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||||
<div className="min-h-screen grid grid-cols-1 lg:grid-cols-2">
|
const [email, setEmail] = useState("");
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
{/* PAINEL ESQUERDO: O Formulário */}
|
const [message, setMessage] = useState<{
|
||||||
<div className="relative flex flex-col items-center justify-center p-8 bg-background">
|
type: "success" | "error";
|
||||||
|
text: string;
|
||||||
{/* Link para Voltar */}
|
} | null>(null);
|
||||||
<div className="absolute top-8 left-8">
|
|
||||||
<Link href="/" className="inline-flex items-center text-muted-foreground hover:text-primary transition-colors font-medium">
|
|
||||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
|
||||||
Voltar à página inicial
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* O contêiner principal que agora terá a sombra e o estilo de card */}
|
const handleOpenModal = () => {
|
||||||
<div className="w-full max-w-md bg-card p-10 rounded-2xl shadow-xl">
|
// Tenta pegar o email do input do formulário de login
|
||||||
<div className="text-center mb-8">
|
const emailInput = document.querySelector(
|
||||||
<h1 className="text-3xl font-bold text-foreground">Acesse sua conta</h1>
|
'input[type="email"]'
|
||||||
<p className="text-muted-foreground mt-2">Bem-vindo(a) de volta ao MedConnect!</p>
|
) as HTMLInputElement;
|
||||||
|
if (emailInput?.value) {
|
||||||
|
setEmail(emailInput.value);
|
||||||
|
}
|
||||||
|
setIsModalOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleResetPassword = async () => {
|
||||||
|
if (!email.trim()) {
|
||||||
|
setMessage({
|
||||||
|
type: "error",
|
||||||
|
text: "Por favor, insira um e-mail válido.",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsLoading(true);
|
||||||
|
setMessage(null);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Chama o método que já faz o fetch corretamente
|
||||||
|
const data = await usersService.resetPassword(email);
|
||||||
|
|
||||||
|
console.log("Resposta resetPassword:", data);
|
||||||
|
|
||||||
|
setMessage({
|
||||||
|
type: "success",
|
||||||
|
text: "E-mail de recuperação enviado! Verifique sua caixa de entrada.",
|
||||||
|
});
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
setIsModalOpen(false);
|
||||||
|
setMessage(null);
|
||||||
|
setEmail("");
|
||||||
|
}, 2000);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Erro no reset de senha:", error);
|
||||||
|
setMessage({
|
||||||
|
type: "error",
|
||||||
|
text:
|
||||||
|
error instanceof Error
|
||||||
|
? error.message
|
||||||
|
: "Erro ao enviar e-mail. Tente novamente.",
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const closeModal = () => {
|
||||||
|
setIsModalOpen(false);
|
||||||
|
setMessage(null);
|
||||||
|
setEmail("");
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="min-h-screen grid grid-cols-1 lg:grid-cols-2">
|
||||||
|
{/* PAINEL ESQUERDO: O Formulário */}
|
||||||
|
<div className="relative flex flex-col items-center justify-center p-8 bg-background">
|
||||||
|
{/* Link para Voltar */}
|
||||||
|
<div className="absolute top-8 left-8">
|
||||||
|
<Link
|
||||||
|
href="/"
|
||||||
|
className="inline-flex items-center text-muted-foreground hover:text-primary transition-colors font-medium"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||||
|
Voltar à página inicial
|
||||||
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<LoginForm>
|
{/* O contêiner principal que agora terá a sombra e o estilo de card */}
|
||||||
{/* Children para o LoginForm */}
|
<div className="w-full max-w-md bg-card p-10 rounded-2xl shadow-xl">
|
||||||
<div className="mt-4 text-center text-sm">
|
{/* NOVO: Bloco da Logo e Nome (Painel Esquerdo) */}
|
||||||
<Link href="/esqueci-minha-senha">
|
<div className="flex items-center justify-center space-x-3 mb-8">
|
||||||
<span className="text-muted-foreground hover:text-primary cursor-pointer underline">
|
<img
|
||||||
|
src="/Logo MedConnect.png" // Caminho da sua logo
|
||||||
|
alt="Logo MediConnect"
|
||||||
|
className="w-16 h-16 object-contain" // Mesmo tamanho que usamos na página inicial
|
||||||
|
/>
|
||||||
|
<span className="text-3xl font-extrabold text-primary">
|
||||||
|
MedConnect
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{/* FIM: Bloco da Logo e Nome */}
|
||||||
|
|
||||||
|
<div className="text-center mb-8">
|
||||||
|
{/* Título de boas-vindas movido para baixo da logo */}
|
||||||
|
<h1 className="text-3xl font-bold text-foreground">
|
||||||
|
Acesse sua conta
|
||||||
|
</h1>
|
||||||
|
<p className="text-muted-foreground mt-2">
|
||||||
|
Bem-vindo(a) de volta ao MedConnect!
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<LoginForm>
|
||||||
|
{/* Children para o LoginForm */}
|
||||||
|
<div className="mt-4 text-center text-sm">
|
||||||
|
<button
|
||||||
|
onClick={handleOpenModal}
|
||||||
|
className="text-muted-foreground hover:text-primary cursor-pointer underline bg-transparent border-none"
|
||||||
|
>
|
||||||
Esqueceu sua senha?
|
Esqueceu sua senha?
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</LoginForm>
|
||||||
|
|
||||||
|
<div className="mt-6 text-center text-sm">
|
||||||
|
<span className="text-muted-foreground">
|
||||||
|
Não tem uma conta de paciente?{" "}
|
||||||
|
</span>
|
||||||
|
<Link href="/patient/register">
|
||||||
|
<span className="font-semibold text-blue-600 hover:text-blue-700 hover:underline cursor-pointer">
|
||||||
|
Crie uma agora
|
||||||
</span>
|
</span>
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
</LoginForm>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="mt-6 text-center text-sm">
|
{/* PAINEL DIREITO: A Imagem e Branding */}
|
||||||
<span className="text-muted-foreground">Não tem uma conta de paciente? </span>
|
<div className="hidden lg:block relative">
|
||||||
<Link href="/patient/register">
|
{/* Usamos o componente <Image> para otimização e performance */}
|
||||||
<span className="font-semibold text-primary hover:underline cursor-pointer">
|
<Image
|
||||||
Crie uma agora
|
src="https://images.unsplash.com/photo-1576091160550-2173dba999ef?q=80&w=2070"
|
||||||
</span>
|
alt="Médica utilizando um tablet na clínica MedConnect"
|
||||||
</Link>
|
fill
|
||||||
|
style={{ objectFit: "cover" }}
|
||||||
|
priority
|
||||||
|
/>
|
||||||
|
{/* Camada de sobreposição para escurecer a imagem e destacar o texto */}
|
||||||
|
<div className="absolute inset-0 bg-primary/80 flex flex-col items-start justify-end p-12 text-left">
|
||||||
|
{/* BLOCO DE NOME ADICIONADO */}
|
||||||
|
<div className="mb-6 border-l-4 border-primary-foreground pl-4">
|
||||||
|
<h1 className="text-5xl font-extrabold text-primary-foreground tracking-wider">
|
||||||
|
MedConnect
|
||||||
|
</h1>
|
||||||
|
</div>
|
||||||
|
<h2 className="text-4xl font-bold text-primary-foreground leading-tight">
|
||||||
|
Tecnologia e Cuidado a Serviço da Sua Saúde.
|
||||||
|
</h2>
|
||||||
|
<p className="mt-4 text-lg text-primary-foreground/80">
|
||||||
|
Acesse seu portal para uma experiência de saúde integrada, segura
|
||||||
|
e eficiente.
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* PAINEL DIREITO: A Imagem e Branding */}
|
{/* Modal de Recuperação de Senha */}
|
||||||
<div className="hidden lg:block relative">
|
{isModalOpen && (
|
||||||
{/* Usamos o componente <Image> para otimização e performance */}
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
|
||||||
<Image
|
<div className="relative w-full max-w-md bg-card p-8 rounded-2xl shadow-2xl mx-4">
|
||||||
src="https://images.unsplash.com/photo-1576091160550-2173dba999ef?q=80&w=2070" // Uma imagem profissional de alta qualidade
|
{/* Botão de fechar */}
|
||||||
alt="Médica utilizando um tablet na clínica MedConnect"
|
<button
|
||||||
fill
|
onClick={closeModal}
|
||||||
style={{ objectFit: 'cover' }}
|
className="absolute top-4 right-4 text-muted-foreground hover:text-foreground transition-colors"
|
||||||
priority // Ajuda a carregar a imagem mais rápido
|
>
|
||||||
/>
|
<X className="w-5 h-5" />
|
||||||
{/* Camada de sobreposição para escurecer a imagem e destacar o texto */}
|
</button>
|
||||||
<div className="absolute inset-0 bg-primary/80 flex flex-col items-start justify-end p-12 text-left">
|
|
||||||
{/* BLOCO DE NOME ADICIONADO */}
|
|
||||||
<div className="mb-6 border-l-4 border-primary-foreground pl-4">
|
|
||||||
<h1 className="text-5xl font-extrabold text-primary-foreground tracking-wider">
|
|
||||||
MedConnect
|
|
||||||
</h1>
|
|
||||||
</div>
|
|
||||||
<h2 className="text-4xl font-bold text-primary-foreground leading-tight">
|
|
||||||
Tecnologia e Cuidado a Serviço da Sua Saúde.
|
|
||||||
</h2>
|
|
||||||
<p className="mt-4 text-lg text-primary-foreground/80">
|
|
||||||
Acesse seu portal para uma experiência de saúde integrada, segura e eficiente.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
</div>
|
{/* Cabeçalho */}
|
||||||
|
<div className="mb-6">
|
||||||
|
<h2 className="text-2xl font-bold text-foreground">
|
||||||
|
Recuperar Senha
|
||||||
|
</h2>
|
||||||
|
<p className="text-muted-foreground mt-2">
|
||||||
|
Insira seu e-mail e enviaremos um link para redefinir sua senha.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Input de e-mail */}
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label
|
||||||
|
htmlFor="email"
|
||||||
|
className="block text-sm font-medium text-foreground mb-2"
|
||||||
|
>
|
||||||
|
E-mail
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id="email"
|
||||||
|
type="email"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
placeholder="seu@email.com"
|
||||||
|
disabled={isLoading}
|
||||||
|
className="w-full"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Mensagem de feedback */}
|
||||||
|
{message && (
|
||||||
|
<div
|
||||||
|
className={`p-3 rounded-lg text-sm ${
|
||||||
|
message.type === "success"
|
||||||
|
? "bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300"
|
||||||
|
: "bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{message.text}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Botões */}
|
||||||
|
<div className="flex gap-3 pt-2">
|
||||||
|
{/* Botão Cancelar – Azul contornado */}
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={closeModal}
|
||||||
|
disabled={isLoading}
|
||||||
|
className="flex-1 bg-blue-600 hover:bg-blue-700 text-white"
|
||||||
|
>
|
||||||
|
Cancelar
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
{/* Botão Resetar Senha – Azul sólido */}
|
||||||
|
<Button
|
||||||
|
onClick={handleResetPassword}
|
||||||
|
disabled={isLoading}
|
||||||
|
className="flex-1 bg-blue-600 hover:bg-blue-700 text-white"
|
||||||
|
>
|
||||||
|
{isLoading ? "Enviando..." : "Resetar Senha"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,190 +1,242 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import ManagerLayout from "@/components/manager-layout";
|
import {
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
Card,
|
||||||
|
CardContent,
|
||||||
|
CardDescription,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from "@/components/ui/card";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Calendar, Clock, Plus, User } from "lucide-react";
|
import { Clock, Plus, User } from "lucide-react"; // Removi 'Calendar' que não estava sendo usado
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import React, { useState, useEffect } from "react";
|
import React, { useState, useEffect } from "react";
|
||||||
import { usersService } from "services/usersApi.mjs";
|
import { usersService } from "services/usersApi.mjs";
|
||||||
import { doctorsService } from "services/doctorsApi.mjs";
|
import { doctorsService } from "services/doctorsApi.mjs";
|
||||||
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
import { api } from "services/api.mjs"; // <-- ADICIONEI ESTE IMPORT
|
||||||
|
|
||||||
export default function ManagerDashboard() {
|
export default function ManagerDashboard() {
|
||||||
// 🔹 Estados para usuários
|
// 🔹 Estados para usuários
|
||||||
const [firstUser, setFirstUser] = useState<any>(null);
|
const [firstUser, setFirstUser] = useState<any>(null);
|
||||||
const [loadingUser, setLoadingUser] = useState(true);
|
const [loadingUser, setLoadingUser] = useState(true);
|
||||||
|
|
||||||
// 🔹 Estados para médicos
|
// 🔹 Estados para médicos
|
||||||
const [doctors, setDoctors] = useState<any[]>([]);
|
const [doctors, setDoctors] = useState<any[]>([]);
|
||||||
const [loadingDoctors, setLoadingDoctors] = useState(true);
|
const [loadingDoctors, setLoadingDoctors] = useState(true);
|
||||||
|
|
||||||
// 🔹 Buscar primeiro usuário
|
// 🔹 Buscar primeiro usuário (LÓGICA ATUALIZADA)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
async function fetchFirstUser() {
|
async function fetchFirstUser() {
|
||||||
|
setLoadingUser(true); // Garante que o estado de loading inicie como true
|
||||||
try {
|
try {
|
||||||
const data = await usersService.list_roles();
|
// 1. Busca a lista de usuários com seus cargos (roles)
|
||||||
if (Array.isArray(data) && data.length > 0) {
|
const rolesData = await usersService.list_roles();
|
||||||
setFirstUser(data[0]);
|
|
||||||
|
// 2. Verifica se a lista não está vazia
|
||||||
|
if (Array.isArray(rolesData) && rolesData.length > 0) {
|
||||||
|
const firstUserRole = rolesData[0];
|
||||||
|
const firstUserId = firstUserRole.user_id;
|
||||||
|
|
||||||
|
if (!firstUserId) {
|
||||||
|
throw new Error("O primeiro usuário da lista não possui um ID válido.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Usa o ID para buscar o perfil (com nome e email) do usuário
|
||||||
|
const profileData = await api.get(
|
||||||
|
`/rest/v1/profiles?select=full_name,email&id=eq.${firstUserId}`
|
||||||
|
);
|
||||||
|
|
||||||
|
// 4. Verifica se o perfil foi encontrado
|
||||||
|
if (Array.isArray(profileData) && profileData.length > 0) {
|
||||||
|
const userProfile = profileData[0];
|
||||||
|
// 5. Combina os dados do cargo e do perfil e atualiza o estado
|
||||||
|
setFirstUser({
|
||||||
|
...firstUserRole,
|
||||||
|
...userProfile
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// Se não encontrar o perfil, exibe os dados que temos
|
||||||
|
setFirstUser(firstUserRole);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Erro ao carregar usuário:", error);
|
console.error("Erro ao carregar usuário:", error);
|
||||||
|
setFirstUser(null); // Limpa o usuário em caso de erro
|
||||||
} finally {
|
} finally {
|
||||||
setLoadingUser(false);
|
setLoadingUser(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fetchFirstUser();
|
fetchFirstUser();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// 🔹 Buscar 3 primeiros médicos
|
// 🔹 Buscar 3 primeiros médicos
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
async function fetchDoctors() {
|
async function fetchDoctors() {
|
||||||
try {
|
try {
|
||||||
const data = await doctorsService.list(); // ajuste se seu service tiver outro método
|
const data = await doctorsService.list(); // ajuste se seu service tiver outro método
|
||||||
if (Array.isArray(data)) {
|
if (Array.isArray(data)) {
|
||||||
setDoctors(data.slice(0, 3)); // pega os 3 primeiros
|
setDoctors(data.slice(0, 3)); // pega os 3 primeiros
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Erro ao carregar médicos:", error);
|
|
||||||
} finally {
|
|
||||||
setLoadingDoctors(false);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Erro ao carregar médicos:", error);
|
||||||
|
} finally {
|
||||||
|
setLoadingDoctors(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fetchDoctors();
|
fetchDoctors();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ManagerLayout>
|
<Sidebar>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
{/* Cabeçalho */}
|
{/* Cabeçalho */}
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
|
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
|
||||||
<p className="text-gray-600">Bem-vindo ao seu portal de consultas médicas</p>
|
<p className="text-gray-600">
|
||||||
</div>
|
Bem-vindo ao seu portal de consultas médicas
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Cards principais */}
|
{/* Cards principais */}
|
||||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||||
{/* Card 1 */}
|
|
||||||
<Card>
|
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
|
||||||
<CardTitle className="text-sm font-medium">Relatórios gerenciais</CardTitle>
|
|
||||||
<Calendar className="h-4 w-4 text-muted-foreground" />
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<div className="text-2xl font-bold">0</div>
|
|
||||||
<p className="text-xs text-muted-foreground">Relatórios disponíveis</p>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* Card 2 — Gestão de usuários */}
|
|
||||||
<Card>
|
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
|
||||||
<CardTitle className="text-sm font-medium">Gestão de usuários</CardTitle>
|
|
||||||
<Clock className="h-4 w-4 text-muted-foreground" />
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
{loadingUser ? (
|
|
||||||
<div className="text-gray-500 text-sm">Carregando usuário...</div>
|
|
||||||
) : firstUser ? (
|
|
||||||
<>
|
|
||||||
<div className="text-2xl font-bold">{firstUser.full_name || "Sem nome"}</div>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
{firstUser.email || "Sem e-mail cadastrado"}
|
|
||||||
</p>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<div className="text-sm text-gray-500">Nenhum usuário encontrado</div>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* Card 3 — Perfil */}
|
{/* Card 2 — Gestão de usuários */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||||
<CardTitle className="text-sm font-medium">Perfil</CardTitle>
|
<CardTitle className="text-sm font-medium">
|
||||||
<User className="h-4 w-4 text-muted-foreground" />
|
Gestão de usuários
|
||||||
</CardHeader>
|
</CardTitle>
|
||||||
<CardContent>
|
<Clock className="h-4 w-4 text-muted-foreground" />
|
||||||
<div className="text-2xl font-bold">100%</div>
|
</CardHeader>
|
||||||
<p className="text-xs text-muted-foreground">Dados completos</p>
|
<CardContent>
|
||||||
</CardContent>
|
{loadingUser ? (
|
||||||
</Card>
|
<div className="text-gray-500 text-sm">
|
||||||
|
Carregando usuário...
|
||||||
</div>
|
</div>
|
||||||
|
) : firstUser ? (
|
||||||
{/* Cards secundários */}
|
<>
|
||||||
<div className="grid md:grid-cols-2 gap-6">
|
<div className="text-2xl font-bold">
|
||||||
{/* Card — Ações rápidas */}
|
{firstUser.full_name || "Sem nome"}
|
||||||
<Card>
|
</div>
|
||||||
<CardHeader>
|
<p className="text-xs text-muted-foreground">
|
||||||
<CardTitle>Ações Rápidas</CardTitle>
|
{firstUser.email || "Sem e-mail cadastrado"}
|
||||||
<CardDescription>Acesse rapidamente as principais funcionalidades</CardDescription>
|
</p>
|
||||||
</CardHeader>
|
</>
|
||||||
<CardContent className="space-y-4">
|
) : (
|
||||||
<Link href="/manager/home">
|
<div className="text-sm text-gray-500">
|
||||||
<Button className="w-full justify-start">
|
Nenhum usuário encontrado
|
||||||
<User className="mr-2 h-4 w-4" />
|
|
||||||
Gestão de Médicos
|
|
||||||
</Button>
|
|
||||||
</Link>
|
|
||||||
<Link href="/manager/usuario">
|
|
||||||
<Button variant="outline" className="w-full justify-start bg-transparent">
|
|
||||||
<User className="mr-2 h-4 w-4" />
|
|
||||||
Usuários Cadastrados
|
|
||||||
</Button>
|
|
||||||
</Link>
|
|
||||||
<Link href="/manager/home/novo">
|
|
||||||
<Button variant="outline" className="w-full justify-start bg-transparent">
|
|
||||||
<Plus className="mr-2 h-4 w-4" />
|
|
||||||
Adicionar Novo Médico
|
|
||||||
</Button>
|
|
||||||
</Link>
|
|
||||||
<Link href="/manager/usuario/novo">
|
|
||||||
<Button variant="outline" className="w-full justify-start bg-transparent">
|
|
||||||
<Plus className="mr-2 h-4 w-4" />
|
|
||||||
Criar novo Usuário
|
|
||||||
</Button>
|
|
||||||
</Link>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* Card — Gestão de Médicos */}
|
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle>Gestão de Médicos</CardTitle>
|
|
||||||
<CardDescription>Médicos cadastrados recentemente</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
{loadingDoctors ? (
|
|
||||||
<p className="text-sm text-gray-500">Carregando médicos...</p>
|
|
||||||
) : doctors.length === 0 ? (
|
|
||||||
<p className="text-sm text-gray-500">Nenhum médico cadastrado.</p>
|
|
||||||
) : (
|
|
||||||
<div className="space-y-4">
|
|
||||||
{doctors.map((doc, index) => (
|
|
||||||
<div
|
|
||||||
key={index}
|
|
||||||
className="flex items-center justify-between p-3 bg-green-50 rounded-lg border border-green-100"
|
|
||||||
>
|
|
||||||
<div>
|
|
||||||
<p className="font-medium">{doc.full_name || "Sem nome"}</p>
|
|
||||||
<p className="text-sm text-gray-600">
|
|
||||||
{doc.specialty || "Sem especialidade"}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className="text-right">
|
|
||||||
<p className="font-medium text-green-700">
|
|
||||||
{doc.active ? "Ativo" : "Inativo"}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
)}
|
||||||
</ManagerLayout>
|
</CardContent>
|
||||||
);
|
</Card>
|
||||||
}
|
|
||||||
|
{/* Card 3 — Perfil */}
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||||
|
<CardTitle className="text-sm font-medium">Perfil</CardTitle>
|
||||||
|
<User className="h-4 w-4 text-muted-foreground" />
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="text-2xl font-bold">100%</div>
|
||||||
|
<p className="text-xs text-muted-foreground">Dados completos</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Cards secundários */}
|
||||||
|
<div className="grid md:grid-cols-2 gap-6">
|
||||||
|
{/* Card — Ações rápidas */}
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Ações Rápidas</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Acesse rapidamente as principais funcionalidades
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
<Link href="/manager/home">
|
||||||
|
<Button className="w-full justify-start bg-blue-600 text-white hover:bg-blue-700">
|
||||||
|
<User className="mr-2 h-4 w-4 text-white" />
|
||||||
|
Gestão de Médicos
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
<Link href="/manager/usuario">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="w-full justify-start bg-transparent"
|
||||||
|
>
|
||||||
|
<User className="mr-2 h-4 w-4" />
|
||||||
|
Usuários Cadastrados
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
<Link href="/manager/home/novo">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="w-full justify-start bg-transparent"
|
||||||
|
>
|
||||||
|
<Plus className="mr-2 h-4 w-4" />
|
||||||
|
Adicionar Novo Médico
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
<Link href="/manager/usuario/novo">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="w-full justify-start bg-transparent"
|
||||||
|
>
|
||||||
|
<Plus className="mr-2 h-4 w-4" />
|
||||||
|
Criar novo Usuário
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Card — Gestão de Médicos */}
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Gestão de Médicos</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Médicos cadastrados recentemente
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{loadingDoctors ? (
|
||||||
|
<p className="text-sm text-gray-500">Carregando médicos...</p>
|
||||||
|
) : doctors.length === 0 ? (
|
||||||
|
<p className="text-sm text-gray-500">
|
||||||
|
Nenhum médico cadastrado.
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{doctors.map((doc, index) => (
|
||||||
|
<div
|
||||||
|
key={index}
|
||||||
|
className="flex items-center justify-between p-3 bg-green-50 rounded-lg border border-green-100"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<p className="font-medium">
|
||||||
|
{doc.full_name || "Sem nome"}
|
||||||
|
</p>
|
||||||
|
<p className="text-sm text-gray-600">
|
||||||
|
{doc.specialty || "Sem especialidade"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="text-right">
|
||||||
|
<p className="font-medium text-green-700">
|
||||||
|
{doc.active ? "Ativo" : "Inativo"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Sidebar>
|
||||||
|
);
|
||||||
|
}
|
||||||
185
app/manager/disponibilidade/page.tsx
Normal file
@ -0,0 +1,185 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
import WeeklyScheduleCard from "@/components/ui/WeeklyScheduleCard";
|
||||||
|
|
||||||
|
import { useEffect, useState, useMemo } from "react";
|
||||||
|
|
||||||
|
import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
||||||
|
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Filter } from "lucide-react";
|
||||||
|
|
||||||
|
type Doctor = {
|
||||||
|
id: string;
|
||||||
|
full_name: string;
|
||||||
|
specialty: string;
|
||||||
|
active: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Availability = {
|
||||||
|
id: string;
|
||||||
|
doctor_id: string;
|
||||||
|
weekday: string;
|
||||||
|
start_time: string;
|
||||||
|
end_time: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function AllAvailabilities() {
|
||||||
|
const [availabilities, setAvailabilities] = useState<Availability[] | null>(null);
|
||||||
|
const [doctors, setDoctors] = useState<Doctor[] | null>(null);
|
||||||
|
|
||||||
|
// 🔎 Filtros
|
||||||
|
const [search, setSearch] = useState("");
|
||||||
|
const [specialty, setSpecialty] = useState("all");
|
||||||
|
|
||||||
|
// 🔄 Paginação
|
||||||
|
const ITEMS_PER_PAGE = 6;
|
||||||
|
const [page, setPage] = useState(1);
|
||||||
|
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchData = async () => {
|
||||||
|
try {
|
||||||
|
const doctorsList = await doctorsService.list();
|
||||||
|
setDoctors(doctorsList);
|
||||||
|
|
||||||
|
const availabilityList = await AvailabilityService.list();
|
||||||
|
setAvailabilities(availabilityList);
|
||||||
|
} catch (e: any) {
|
||||||
|
alert(`${e?.error} ${e?.message}`);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchData();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// 🎯 Obter todas as especialidades existentes
|
||||||
|
const specialties = useMemo(() => {
|
||||||
|
if (!doctors) return [];
|
||||||
|
const unique = Array.from(new Set(doctors.map((d) => d.specialty)));
|
||||||
|
return unique;
|
||||||
|
}, [doctors]);
|
||||||
|
|
||||||
|
// 🔍 Filtrar médicos por especialidade + nome
|
||||||
|
const filteredDoctors = useMemo(() => {
|
||||||
|
if (!doctors) return [];
|
||||||
|
|
||||||
|
return doctors.filter((doctor) => (specialty === "all" ? true : doctor.specialty === specialty)).filter((doctor) => doctor.full_name.toLowerCase().includes(search.toLowerCase()));
|
||||||
|
}, [doctors, search, specialty]);
|
||||||
|
|
||||||
|
// 📄 Paginação (após filtros!)
|
||||||
|
const totalPages = Math.ceil(filteredDoctors.length / ITEMS_PER_PAGE);
|
||||||
|
const paginatedDoctors = filteredDoctors.slice((page - 1) * ITEMS_PER_PAGE, page * ITEMS_PER_PAGE);
|
||||||
|
|
||||||
|
const goNext = () => setPage((p) => Math.min(p + 1, totalPages));
|
||||||
|
const goPrev = () => setPage((p) => Math.max(p - 1, 1));
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<Sidebar>
|
||||||
|
<div className="p-6 text-gray-500">Carregando dados...</div>
|
||||||
|
</Sidebar>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!doctors || !availabilities) {
|
||||||
|
return (
|
||||||
|
<Sidebar>
|
||||||
|
<div className="p-6 text-red-600 font-medium">Não foi possível carregar médicos ou disponibilidades.</div>
|
||||||
|
</Sidebar>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Sidebar>
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-bold text-gray-900">Disponibilidade dos Médicos</h1>
|
||||||
|
<p className="text-gray-600">Visualize a agenda semanal individual de cada médico.</p>
|
||||||
|
</div>
|
||||||
|
<Card>
|
||||||
|
<CardContent>
|
||||||
|
{/* 🔎 Filtros */}
|
||||||
|
<div className="flex flex-col md:flex-row gap-4 items-center">
|
||||||
|
{/* Filtro por nome */}
|
||||||
|
<Filter className="w-4 h-4 mr-2" />
|
||||||
|
<Input
|
||||||
|
placeholder="Buscar por nome do médico..."
|
||||||
|
value={search}
|
||||||
|
onChange={(e) => {
|
||||||
|
setSearch(e.target.value);
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
className="w-full md:w-1/3"
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Filtro por especialidade */}
|
||||||
|
<Select
|
||||||
|
onValueChange={(value) => {
|
||||||
|
setSpecialty(value);
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
defaultValue="all"
|
||||||
|
>
|
||||||
|
<SelectTrigger className="w-full md:w-64">
|
||||||
|
<SelectValue placeholder="Especialidade" />
|
||||||
|
</SelectTrigger>
|
||||||
|
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="all">Todas as especialidades</SelectItem>
|
||||||
|
{specialties.map((sp) => (
|
||||||
|
<SelectItem key={sp} value={sp}>
|
||||||
|
{sp}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
{/* GRID de cards */}
|
||||||
|
<div className="grid md:grid-cols-1 lg:grid-cols-1 gap-6">
|
||||||
|
{paginatedDoctors.map((doctor) => {
|
||||||
|
const doctorAvailabilities = availabilities.filter((a) => a.doctor_id === doctor.id);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card key={doctor.id}>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-xl font-semibold">{doctor.full_name}</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
|
<CardContent>
|
||||||
|
<WeeklyScheduleCard doctorId={doctor.id} />
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 📄 Paginação */}
|
||||||
|
{totalPages > 1 && (
|
||||||
|
<div className="flex justify-center items-center gap-4 pt-4">
|
||||||
|
<Button variant="outline" onClick={goPrev} disabled={page === 1}>
|
||||||
|
Anterior
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<span className="text-gray-700 font-medium">
|
||||||
|
Página {page} de {totalPages}
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<Button variant="outline" onClick={goNext} disabled={page === totalPages}>
|
||||||
|
Próxima
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Sidebar>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -9,47 +9,47 @@ import { Label } from "@/components/ui/label"
|
|||||||
import { Textarea } from "@/components/ui/textarea"
|
import { Textarea } from "@/components/ui/textarea"
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||||
import { Checkbox } from "@/components/ui/checkbox"
|
import { Checkbox } from "@/components/ui/checkbox"
|
||||||
import { Save, Loader2, ArrowLeft } from "lucide-react"
|
import { Save, Loader2, ArrowLeft } from "lucide-react"
|
||||||
import ManagerLayout from "@/components/manager-layout"
|
import Sidebar from "@/components/Sidebar"
|
||||||
import { doctorsService } from "services/doctorsApi.mjs";
|
import { doctorsService } from "services/doctorsApi.mjs";
|
||||||
|
|
||||||
const UF_LIST = ["AC", "AL", "AP", "AM", "BA", "CE", "DF", "ES", "GO", "MA", "MT", "MS", "MG", "PA", "PB", "PR", "PE", "PI", "RJ", "RN", "RS", "RO", "RR", "SC", "SP", "SE", "TO"];
|
const UF_LIST = ["AC", "AL", "AP", "AM", "BA", "CE", "DF", "ES", "GO", "MA", "MT", "MS", "MG", "PA", "PB", "PR", "PE", "PI", "RJ", "RN", "RS", "RO", "RR", "SC", "SP", "SE", "TO"];
|
||||||
|
|
||||||
interface DoctorFormData {
|
interface DoctorFormData {
|
||||||
nomeCompleto: string;
|
nomeCompleto: string;
|
||||||
crm: string;
|
crm: string;
|
||||||
crmEstado: string;
|
crmEstado: string;
|
||||||
especialidade: string;
|
especialidade: string;
|
||||||
cpf: string;
|
cpf: string;
|
||||||
email: string;
|
email: string;
|
||||||
dataNascimento: string;
|
dataNascimento: string;
|
||||||
rg: string;
|
rg: string;
|
||||||
telefoneCelular: string;
|
telefoneCelular: string;
|
||||||
telefone2: string;
|
telefone2: string;
|
||||||
cep: string;
|
cep: string;
|
||||||
endereco: string;
|
endereco: string;
|
||||||
numero: string;
|
numero: string;
|
||||||
complemento: string;
|
complemento: string;
|
||||||
bairro: string;
|
bairro: string;
|
||||||
cidade: string;
|
cidade: string;
|
||||||
estado: string;
|
estado: string;
|
||||||
ativo: boolean;
|
ativo: boolean;
|
||||||
observacoes: string;
|
observacoes: string;
|
||||||
}
|
}
|
||||||
const apiMap: { [K in keyof DoctorFormData]: string | null } = {
|
const apiMap: { [K in keyof DoctorFormData]: string | null } = {
|
||||||
nomeCompleto: 'full_name', crm: 'crm', crmEstado: 'crm_uf', especialidade: 'specialty',
|
nomeCompleto: 'full_name', crm: 'crm', crmEstado: 'crm_uf', especialidade: 'specialty',
|
||||||
cpf: 'cpf', email: 'email', dataNascimento: 'birth_date', rg: 'rg',
|
cpf: 'cpf', email: 'email', dataNascimento: 'birth_date', rg: 'rg',
|
||||||
telefoneCelular: 'phone_mobile', telefone2: 'phone2', cep: 'cep',
|
telefoneCelular: 'phone_mobile', telefone2: 'phone2', cep: 'cep',
|
||||||
endereco: 'street', numero: 'number', complemento: 'complement',
|
endereco: 'street', numero: 'number', complemento: 'complement',
|
||||||
bairro: 'neighborhood', cidade: 'city', estado: 'state', ativo: 'active',
|
bairro: 'neighborhood', cidade: 'city', estado: 'state', ativo: 'active',
|
||||||
observacoes: null,
|
observacoes: null,
|
||||||
};
|
};
|
||||||
|
|
||||||
const defaultFormData: DoctorFormData = {
|
const defaultFormData: DoctorFormData = {
|
||||||
nomeCompleto: '', crm: '', crmEstado: '', especialidade: '', cpf: '', email: '',
|
nomeCompleto: '', crm: '', crmEstado: '', especialidade: '', cpf: '', email: '',
|
||||||
dataNascimento: '', rg: '', telefoneCelular: '', telefone2: '', cep: '',
|
dataNascimento: '', rg: '', telefoneCelular: '', telefone2: '', cep: '',
|
||||||
endereco: '', numero: '', complemento: '', bairro: '', cidade: '', estado: '',
|
endereco: '', numero: '', complemento: '', bairro: '', cidade: '', estado: '',
|
||||||
ativo: true, observacoes: '',
|
ativo: true, observacoes: '',
|
||||||
};
|
};
|
||||||
|
|
||||||
const cleanNumber = (value: string): string => value.replace(/\D/g, '');
|
const cleanNumber = (value: string): string => value.replace(/\D/g, '');
|
||||||
@ -73,420 +73,420 @@ const formatPhoneMobile = (value: string): string => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default function EditarMedicoPage() {
|
export default function EditarMedicoPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const params = useParams();
|
const params = useParams();
|
||||||
const id = Array.isArray(params.id) ? params.id[0] : params.id;
|
const id = Array.isArray(params.id) ? params.id[0] : params.id;
|
||||||
const [formData, setFormData] = useState<DoctorFormData>(defaultFormData);
|
const [formData, setFormData] = useState<DoctorFormData>(defaultFormData);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [isSaving, setIsSaving] = useState(false);
|
const [isSaving, setIsSaving] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const apiToFormMap: { [key: string]: keyof DoctorFormData } = {
|
const apiToFormMap: { [key: string]: keyof DoctorFormData } = {
|
||||||
'full_name': 'nomeCompleto', 'crm': 'crm', 'crm_uf': 'crmEstado', 'specialty': 'especialidade',
|
'full_name': 'nomeCompleto', 'crm': 'crm', 'crm_uf': 'crmEstado', 'specialty': 'especialidade',
|
||||||
'cpf': 'cpf', 'email': 'email', 'birth_date': 'dataNascimento', 'rg': 'rg',
|
'cpf': 'cpf', 'email': 'email', 'birth_date': 'dataNascimento', 'rg': 'rg',
|
||||||
'phone_mobile': 'telefoneCelular', 'phone2': 'telefone2', 'cep': 'cep',
|
'phone_mobile': 'telefoneCelular', 'phone2': 'telefone2', 'cep': 'cep',
|
||||||
'street': 'endereco', 'number': 'numero', 'complement': 'complemento',
|
'street': 'endereco', 'number': 'numero', 'complement': 'complemento',
|
||||||
'neighborhood': 'bairro', 'city': 'cidade', 'state': 'estado', 'active': 'ativo'
|
'neighborhood': 'bairro', 'city': 'cidade', 'state': 'estado', 'active': 'ativo'
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!id) return;
|
|
||||||
|
|
||||||
const fetchDoctor = async () => {
|
|
||||||
try {
|
|
||||||
const data = await doctorsService.getById(id);
|
|
||||||
|
|
||||||
if (!data) {
|
|
||||||
setError("Médico não encontrado.");
|
|
||||||
setLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const initialData: Partial<DoctorFormData> = {};
|
|
||||||
|
|
||||||
Object.keys(data).forEach(key => {
|
|
||||||
const formKey = apiToFormMap[key];
|
|
||||||
if (formKey) {
|
|
||||||
let value = data[key] === null ? '' : data[key];
|
|
||||||
if (formKey === 'ativo') {
|
|
||||||
value = !!value;
|
|
||||||
} else if (typeof value !== 'boolean') {
|
|
||||||
value = String(value);
|
|
||||||
}
|
|
||||||
initialData[formKey] = value as any;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
initialData.observacoes = "Observação carregada do sistema (exemplo de campo interno)";
|
|
||||||
|
|
||||||
setFormData(prev => ({ ...prev, ...initialData }));
|
|
||||||
} catch (e) {
|
|
||||||
console.error("Erro ao carregar dados:", e);
|
|
||||||
setError("Não foi possível carregar os dados do médico.");
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
fetchDoctor();
|
|
||||||
}, [id]);
|
|
||||||
|
|
||||||
const handleInputChange = (key: keyof DoctorFormData, value: string | boolean) => {
|
|
||||||
|
|
||||||
|
|
||||||
if (typeof value === 'string') {
|
|
||||||
let maskedValue = value;
|
|
||||||
if (key === 'cpf') maskedValue = formatCPF(value);
|
|
||||||
if (key === 'cep') maskedValue = formatCEP(value);
|
|
||||||
if (key === 'telefoneCelular' || key === 'telefone2') maskedValue = formatPhoneMobile(value);
|
|
||||||
|
|
||||||
setFormData((prev) => ({ ...prev, [key]: maskedValue }));
|
|
||||||
} else {
|
|
||||||
setFormData((prev) => ({ ...prev, [key]: value }));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!id) return;
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
const fetchDoctor = async () => {
|
||||||
e.preventDefault();
|
try {
|
||||||
setError(null);
|
const data = await doctorsService.getById(id);
|
||||||
setIsSaving(true);
|
|
||||||
|
|
||||||
if (!id) {
|
|
||||||
setError("ID do médico ausente.");
|
|
||||||
setIsSaving(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const finalPayload: { [key: string]: any } = {};
|
if (!data) {
|
||||||
const formKeys = Object.keys(formData) as Array<keyof DoctorFormData>;
|
setError("Médico não encontrado.");
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const initialData: Partial<DoctorFormData> = {};
|
||||||
formKeys.forEach((key) => {
|
|
||||||
const apiFieldName = apiMap[key];
|
Object.keys(data).forEach(key => {
|
||||||
|
const formKey = apiToFormMap[key];
|
||||||
if (!apiFieldName) return;
|
if (formKey) {
|
||||||
|
let value = data[key] === null ? '' : data[key];
|
||||||
|
if (formKey === 'ativo') {
|
||||||
|
value = !!value;
|
||||||
|
} else if (typeof value !== 'boolean') {
|
||||||
|
value = String(value);
|
||||||
|
}
|
||||||
|
initialData[formKey] = value as any;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
initialData.observacoes = "Observação carregada do sistema (exemplo de campo interno)";
|
||||||
|
|
||||||
|
setFormData(prev => ({ ...prev, ...initialData }));
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Erro ao carregar dados:", e);
|
||||||
|
setError("Não foi possível carregar os dados do médico.");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
fetchDoctor();
|
||||||
|
}, [id]);
|
||||||
|
|
||||||
|
const handleInputChange = (key: keyof DoctorFormData, value: string | boolean) => {
|
||||||
|
|
||||||
let value = formData[key];
|
|
||||||
|
|
||||||
if (typeof value === 'string') {
|
if (typeof value === 'string') {
|
||||||
let trimmedValue = value.trim();
|
let maskedValue = value;
|
||||||
if (trimmedValue === '') {
|
if (key === 'cpf') maskedValue = formatCPF(value);
|
||||||
finalPayload[apiFieldName] = null;
|
if (key === 'cep') maskedValue = formatCEP(value);
|
||||||
return;
|
if (key === 'telefoneCelular' || key === 'telefone2') maskedValue = formatPhoneMobile(value);
|
||||||
}
|
|
||||||
if (key === 'crmEstado' || key === 'estado') {
|
setFormData((prev) => ({ ...prev, [key]: maskedValue }));
|
||||||
trimmedValue = trimmedValue.toUpperCase();
|
} else {
|
||||||
}
|
setFormData((prev) => ({ ...prev, [key]: value }));
|
||||||
|
|
||||||
value = trimmedValue;
|
|
||||||
}
|
}
|
||||||
|
};
|
||||||
finalPayload[apiFieldName] = value;
|
|
||||||
});
|
|
||||||
|
|
||||||
delete finalPayload.user_id;
|
|
||||||
try {
|
|
||||||
await doctorsService.update(id, finalPayload);
|
|
||||||
router.push("/manager/home");
|
|
||||||
} catch (e: any) {
|
|
||||||
console.error("Erro ao salvar o médico:", e);
|
|
||||||
let detailedError = "Erro ao atualizar. Verifique os dados e tente novamente.";
|
|
||||||
|
|
||||||
if (e.message && e.message.includes("duplicate key value violates unique constraint")) {
|
|
||||||
detailedError = "O CPF ou CRM informado já está cadastrado em outro registro.";
|
|
||||||
} else if (e.message && e.message.includes("Detalhes:")) {
|
|
||||||
detailedError = e.message.split("Detalhes:")[1].trim();
|
|
||||||
} else if (e.message) {
|
|
||||||
detailedError = e.message;
|
|
||||||
}
|
|
||||||
|
|
||||||
setError(`Erro ao atualizar. Detalhes: ${detailedError}`);
|
|
||||||
} finally {
|
|
||||||
setIsSaving(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if (loading) {
|
|
||||||
return (
|
|
||||||
<ManagerLayout>
|
|
||||||
<div className="flex justify-center items-center h-full w-full py-16">
|
|
||||||
<Loader2 className="w-8 h-8 animate-spin text-green-600" />
|
|
||||||
<p className="ml-2 text-gray-600">Carregando dados do médico...</p>
|
|
||||||
</div>
|
|
||||||
</ManagerLayout>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ManagerLayout>
|
|
||||||
<div className="w-full space-y-6 p-4 md:p-8">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<h1 className="text-2xl font-bold text-gray-900">
|
|
||||||
Editar Médico: <span className="text-green-600">{formData.nomeCompleto}</span>
|
|
||||||
</h1>
|
|
||||||
<p className="text-sm text-gray-500">
|
|
||||||
Atualize as informações do médico (ID: {id}).
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<Link href="/manager/home">
|
|
||||||
<Button variant="outline">
|
|
||||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
|
||||||
Voltar
|
|
||||||
</Button>
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<form onSubmit={handleSubmit} className="space-y-6">
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
{error && (
|
setError(null);
|
||||||
<div className="p-3 bg-red-100 text-red-700 rounded-lg border border-red-300">
|
setIsSaving(true);
|
||||||
<p className="font-medium">Erro na Atualização:</p>
|
|
||||||
<p className="text-sm">{error}</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="space-y-4 p-4 border rounded-xl shadow-sm bg-white">
|
if (!id) {
|
||||||
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">
|
setError("ID do médico ausente.");
|
||||||
Dados Principais e Pessoais
|
setIsSaving(false);
|
||||||
</h2>
|
return;
|
||||||
<div className="grid md:grid-cols-4 gap-4">
|
}
|
||||||
<div className="space-y-2 col-span-2">
|
|
||||||
<Label htmlFor="nomeCompleto">Nome Completo (full_name)</Label>
|
const finalPayload: { [key: string]: any } = {};
|
||||||
<Input
|
const formKeys = Object.keys(formData) as Array<keyof DoctorFormData>;
|
||||||
id="nomeCompleto"
|
|
||||||
value={formData.nomeCompleto}
|
|
||||||
onChange={(e) => handleInputChange("nomeCompleto", e.target.value)}
|
formKeys.forEach((key) => {
|
||||||
placeholder="Nome do Médico"
|
const apiFieldName = apiMap[key];
|
||||||
/>
|
|
||||||
</div>
|
if (!apiFieldName) return;
|
||||||
<div className="space-y-2 col-span-1">
|
|
||||||
<Label htmlFor="crm">CRM</Label>
|
let value = formData[key];
|
||||||
<Input
|
|
||||||
id="crm"
|
if (typeof value === 'string') {
|
||||||
value={formData.crm}
|
let trimmedValue = value.trim();
|
||||||
onChange={(e) => handleInputChange("crm", e.target.value)}
|
if (trimmedValue === '') {
|
||||||
placeholder="Ex: 123456"
|
finalPayload[apiFieldName] = null;
|
||||||
/>
|
return;
|
||||||
</div>
|
}
|
||||||
<div className="space-y-2 col-span-1">
|
if (key === 'crmEstado' || key === 'estado') {
|
||||||
<Label htmlFor="crmEstado">UF do CRM (crm_uf)</Label>
|
trimmedValue = trimmedValue.toUpperCase();
|
||||||
<Select value={formData.crmEstado} onValueChange={(v) => handleInputChange("crmEstado", v)}>
|
}
|
||||||
<SelectTrigger id="crmEstado">
|
|
||||||
<SelectValue placeholder="UF" />
|
value = trimmedValue;
|
||||||
</SelectTrigger>
|
}
|
||||||
<SelectContent>
|
|
||||||
{UF_LIST.map(uf => (
|
finalPayload[apiFieldName] = value;
|
||||||
<SelectItem key={uf} value={uf}>{uf}</SelectItem>
|
});
|
||||||
))}
|
|
||||||
</SelectContent>
|
delete finalPayload.user_id;
|
||||||
</Select>
|
try {
|
||||||
</div>
|
await doctorsService.update(id, finalPayload);
|
||||||
</div>
|
router.push("/manager/home");
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Erro ao salvar o médico:", e);
|
||||||
<div className="grid md:grid-cols-3 gap-4">
|
let detailedError = "Erro ao atualizar. Verifique os dados e tente novamente.";
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="especialidade">Especialidade (specialty)</Label>
|
if (e.message && e.message.includes("duplicate key value violates unique constraint")) {
|
||||||
<Input
|
detailedError = "O CPF ou CRM informado já está cadastrado em outro registro.";
|
||||||
id="especialidade"
|
} else if (e.message && e.message.includes("Detalhes:")) {
|
||||||
value={formData.especialidade}
|
detailedError = e.message.split("Detalhes:")[1].trim();
|
||||||
onChange={(e) => handleInputChange("especialidade", e.target.value)}
|
} else if (e.message) {
|
||||||
placeholder="Ex: Cardiologia"
|
detailedError = e.message;
|
||||||
/>
|
}
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
setError(`Erro ao atualizar. Detalhes: ${detailedError}`);
|
||||||
<Label htmlFor="cpf">CPF</Label>
|
} finally {
|
||||||
<Input
|
setIsSaving(false);
|
||||||
id="cpf"
|
}
|
||||||
value={formData.cpf}
|
};
|
||||||
onChange={(e) => handleInputChange("cpf", e.target.value)}
|
if (loading) {
|
||||||
placeholder="000.000.000-00"
|
return (
|
||||||
maxLength={14}
|
<Sidebar>
|
||||||
/>
|
<div className="flex justify-center items-center h-full w-full py-16">
|
||||||
</div>
|
<Loader2 className="w-8 h-8 animate-spin text-green-600" />
|
||||||
<div className="space-y-2">
|
<p className="ml-2 text-gray-600">Carregando dados do médico...</p>
|
||||||
<Label htmlFor="rg">RG</Label>
|
|
||||||
<Input
|
|
||||||
id="rg"
|
|
||||||
value={formData.rg}
|
|
||||||
onChange={(e) => handleInputChange("rg", e.target.value)}
|
|
||||||
placeholder="00.000.000-0"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-4 gap-4">
|
|
||||||
<div className="space-y-2 col-span-2">
|
|
||||||
<Label htmlFor="email">E-mail</Label>
|
|
||||||
<Input
|
|
||||||
id="email"
|
|
||||||
type="email"
|
|
||||||
value={formData.email}
|
|
||||||
onChange={(e) => handleInputChange("email", e.target.value)}
|
|
||||||
placeholder="exemplo@dominio.com"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2 col-span-1">
|
|
||||||
<Label htmlFor="dataNascimento">Data de Nascimento (birth_date)</Label>
|
|
||||||
<Input
|
|
||||||
id="dataNascimento"
|
|
||||||
type="date"
|
|
||||||
value={formData.dataNascimento}
|
|
||||||
onChange={(e) => handleInputChange("dataNascimento", e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2 flex items-end justify-center pb-1">
|
|
||||||
<div className="flex items-center space-x-2">
|
|
||||||
<Checkbox
|
|
||||||
id="ativo"
|
|
||||||
checked={formData.ativo}
|
|
||||||
onCheckedChange={(checked) => handleInputChange("ativo", checked === true)}
|
|
||||||
/>
|
|
||||||
<Label htmlFor="ativo">Médico Ativo (active)</Label>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Sidebar>
|
||||||
</div>
|
);
|
||||||
</div>
|
}
|
||||||
|
|
||||||
<div className="space-y-4 p-4 border rounded-xl shadow-sm bg-white">
|
return (
|
||||||
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">
|
<Sidebar>
|
||||||
Contato e Endereço
|
<div className="w-full space-y-6 p-4 md:p-8">
|
||||||
</h2>
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
<h1 className="text-2xl font-bold text-gray-900">
|
||||||
<div className="space-y-2">
|
Editar Médico: <span className="text-green-600">{formData.nomeCompleto}</span>
|
||||||
<Label htmlFor="telefoneCelular">Telefone Celular (phone_mobile)</Label>
|
</h1>
|
||||||
<Input
|
<p className="text-sm text-gray-500">
|
||||||
id="telefoneCelular"
|
Atualize as informações do médico
|
||||||
value={formData.telefoneCelular}
|
</p>
|
||||||
onChange={(e) => handleInputChange("telefoneCelular", e.target.value)}
|
</div>
|
||||||
placeholder="(00) 00000-0000"
|
<Link href="/manager/home">
|
||||||
maxLength={15}
|
<Button variant="outline">
|
||||||
/>
|
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||||
</div>
|
Voltar
|
||||||
<div className="space-y-2">
|
</Button>
|
||||||
<Label htmlFor="telefone2">Telefone Adicional (phone2)</Label>
|
</Link>
|
||||||
<Input
|
</div>
|
||||||
id="telefone2"
|
|
||||||
value={formData.telefone2}
|
|
||||||
onChange={(e) => handleInputChange("telefone2", e.target.value)}
|
|
||||||
placeholder="(00) 00000-0000"
|
|
||||||
maxLength={15}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-6">
|
||||||
<div className="grid md:grid-cols-4 gap-4">
|
|
||||||
<div className="space-y-2 col-span-1">
|
|
||||||
<Label htmlFor="cep">CEP</Label>
|
|
||||||
<Input
|
|
||||||
id="cep"
|
|
||||||
value={formData.cep}
|
|
||||||
onChange={(e) => handleInputChange("cep", e.target.value)}
|
|
||||||
placeholder="00000-000"
|
|
||||||
maxLength={9}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2 col-span-3">
|
|
||||||
<Label htmlFor="endereco">Logradouro (street)</Label>
|
|
||||||
<Input
|
|
||||||
id="endereco"
|
|
||||||
value={formData.endereco}
|
|
||||||
onChange={(e) => handleInputChange("endereco", e.target.value)}
|
|
||||||
placeholder="Rua, Avenida, etc."
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-4 gap-4">
|
|
||||||
<div className="space-y-2 col-span-1">
|
|
||||||
<Label htmlFor="numero">Número</Label>
|
|
||||||
<Input
|
|
||||||
id="numero"
|
|
||||||
value={formData.numero}
|
|
||||||
onChange={(e) => handleInputChange("numero", e.target.value)}
|
|
||||||
placeholder="123"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2 col-span-3">
|
|
||||||
<Label htmlFor="complemento">Complemento</Label>
|
|
||||||
<Input
|
|
||||||
id="complemento"
|
|
||||||
value={formData.complemento}
|
|
||||||
onChange={(e) => handleInputChange("complemento", e.target.value)}
|
|
||||||
placeholder="Apto, Bloco, etc."
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-4 gap-4">
|
|
||||||
<div className="space-y-2 col-span-2">
|
|
||||||
<Label htmlFor="bairro">Bairro</Label>
|
|
||||||
<Input
|
|
||||||
id="bairro"
|
|
||||||
value={formData.bairro}
|
|
||||||
onChange={(e) => handleInputChange("bairro", e.target.value)}
|
|
||||||
placeholder="Bairro"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2 col-span-1">
|
|
||||||
<Label htmlFor="cidade">Cidade</Label>
|
|
||||||
<Input
|
|
||||||
id="cidade"
|
|
||||||
value={formData.cidade}
|
|
||||||
onChange={(e) => handleInputChange("cidade", e.target.value)}
|
|
||||||
placeholder="São Paulo"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2 col-span-1">
|
|
||||||
<Label htmlFor="estado">Estado (state)</Label>
|
|
||||||
<Input
|
|
||||||
id="estado"
|
|
||||||
value={formData.estado}
|
|
||||||
onChange={(e) => handleInputChange("estado", e.target.value)}
|
|
||||||
placeholder="SP"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
|
{error && (
|
||||||
<div className="space-y-4 p-4 border rounded-xl shadow-sm bg-white">
|
<div className="p-3 bg-red-100 text-red-700 rounded-lg border border-red-300">
|
||||||
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">
|
<p className="font-medium">Erro na Atualização:</p>
|
||||||
Observações (Apenas internas)
|
<p className="text-sm">{error}</p>
|
||||||
</h2>
|
</div>
|
||||||
<Textarea
|
)}
|
||||||
id="observacoes"
|
|
||||||
value={formData.observacoes}
|
<div className="space-y-4 p-4 border rounded-xl shadow-sm bg-white">
|
||||||
onChange={(e) => handleInputChange("observacoes", e.target.value)}
|
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">
|
||||||
placeholder="Notas internas sobre o médico..."
|
Dados Principais e Pessoais
|
||||||
className="min-h-[100px]"
|
</h2>
|
||||||
/>
|
<div className="grid md:grid-cols-4 gap-4">
|
||||||
</div>
|
<div className="space-y-2 col-span-2">
|
||||||
|
<Label htmlFor="nomeCompleto">Nome Completo (full_name)</Label>
|
||||||
|
<Input
|
||||||
|
id="nomeCompleto"
|
||||||
|
value={formData.nomeCompleto}
|
||||||
|
onChange={(e) => handleInputChange("nomeCompleto", e.target.value)}
|
||||||
|
placeholder="Nome do Médico"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2 col-span-1">
|
||||||
|
<Label htmlFor="crm">CRM</Label>
|
||||||
|
<Input
|
||||||
|
id="crm"
|
||||||
|
value={formData.crm}
|
||||||
|
onChange={(e) => handleInputChange("crm", e.target.value)}
|
||||||
|
placeholder="Ex: 123456"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2 col-span-1">
|
||||||
|
<Label htmlFor="crmEstado">UF do CRM (crm_uf)</Label>
|
||||||
|
<Select value={formData.crmEstado} onValueChange={(v) => handleInputChange("crmEstado", v)}>
|
||||||
|
<SelectTrigger id="crmEstado">
|
||||||
|
<SelectValue placeholder="UF" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{UF_LIST.map(uf => (
|
||||||
|
<SelectItem key={uf} value={uf}>{uf}</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
<div className="flex justify-end gap-4 pb-8 pt-4">
|
<div className="grid md:grid-cols-3 gap-4">
|
||||||
<Link href="/manager/home">
|
<div className="space-y-2">
|
||||||
<Button type="button" variant="outline" disabled={isSaving}>
|
<Label htmlFor="especialidade">Especialidade (specialty)</Label>
|
||||||
Cancelar
|
<Input
|
||||||
</Button>
|
id="especialidade"
|
||||||
</Link>
|
value={formData.especialidade}
|
||||||
<Button
|
onChange={(e) => handleInputChange("especialidade", e.target.value)}
|
||||||
type="submit"
|
placeholder="Ex: Cardiologia"
|
||||||
className="bg-green-600 hover:bg-green-700"
|
/>
|
||||||
disabled={isSaving}
|
</div>
|
||||||
>
|
<div className="space-y-2">
|
||||||
{isSaving ? (
|
<Label htmlFor="cpf">CPF</Label>
|
||||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
<Input
|
||||||
) : (
|
id="cpf"
|
||||||
<Save className="w-4 h-4 mr-2" />
|
value={formData.cpf}
|
||||||
)}
|
onChange={(e) => handleInputChange("cpf", e.target.value)}
|
||||||
{isSaving ? "Salvando..." : "Salvar Alterações"}
|
placeholder="000.000.000-00"
|
||||||
</Button>
|
maxLength={14}
|
||||||
</div>
|
/>
|
||||||
</form>
|
</div>
|
||||||
</div>
|
<div className="space-y-2">
|
||||||
</ManagerLayout>
|
<Label htmlFor="rg">RG</Label>
|
||||||
);
|
<Input
|
||||||
|
id="rg"
|
||||||
|
value={formData.rg}
|
||||||
|
onChange={(e) => handleInputChange("rg", e.target.value)}
|
||||||
|
placeholder="00.000.000-0"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid md:grid-cols-4 gap-4">
|
||||||
|
<div className="space-y-2 col-span-2">
|
||||||
|
<Label htmlFor="email">E-mail</Label>
|
||||||
|
<Input
|
||||||
|
id="email"
|
||||||
|
type="email"
|
||||||
|
value={formData.email}
|
||||||
|
onChange={(e) => handleInputChange("email", e.target.value)}
|
||||||
|
placeholder="exemplo@dominio.com"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2 col-span-1">
|
||||||
|
<Label htmlFor="dataNascimento">Data de Nascimento (birth_date)</Label>
|
||||||
|
<Input
|
||||||
|
id="dataNascimento"
|
||||||
|
type="date"
|
||||||
|
value={formData.dataNascimento}
|
||||||
|
onChange={(e) => handleInputChange("dataNascimento", e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2 flex items-end justify-center pb-1">
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<Checkbox
|
||||||
|
id="ativo"
|
||||||
|
checked={formData.ativo}
|
||||||
|
onCheckedChange={(checked) => handleInputChange("ativo", checked === true)}
|
||||||
|
/>
|
||||||
|
<Label htmlFor="ativo">Médico Ativo (active)</Label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-4 p-4 border rounded-xl shadow-sm bg-white">
|
||||||
|
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">
|
||||||
|
Contato e Endereço
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
<div className="grid md:grid-cols-2 gap-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="telefoneCelular">Telefone Celular (phone_mobile)</Label>
|
||||||
|
<Input
|
||||||
|
id="telefoneCelular"
|
||||||
|
value={formData.telefoneCelular}
|
||||||
|
onChange={(e) => handleInputChange("telefoneCelular", e.target.value)}
|
||||||
|
placeholder="(00) 00000-0000"
|
||||||
|
maxLength={15}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="telefone2">Telefone Adicional (phone2)</Label>
|
||||||
|
<Input
|
||||||
|
id="telefone2"
|
||||||
|
value={formData.telefone2}
|
||||||
|
onChange={(e) => handleInputChange("telefone2", e.target.value)}
|
||||||
|
placeholder="(00) 00000-0000"
|
||||||
|
maxLength={15}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
<div className="grid md:grid-cols-4 gap-4">
|
||||||
|
<div className="space-y-2 col-span-1">
|
||||||
|
<Label htmlFor="cep">CEP</Label>
|
||||||
|
<Input
|
||||||
|
id="cep"
|
||||||
|
value={formData.cep}
|
||||||
|
onChange={(e) => handleInputChange("cep", e.target.value)}
|
||||||
|
placeholder="00000-000"
|
||||||
|
maxLength={9}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2 col-span-3">
|
||||||
|
<Label htmlFor="endereco">Logradouro (street)</Label>
|
||||||
|
<Input
|
||||||
|
id="endereco"
|
||||||
|
value={formData.endereco}
|
||||||
|
onChange={(e) => handleInputChange("endereco", e.target.value)}
|
||||||
|
placeholder="Rua, Avenida, etc."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid md:grid-cols-4 gap-4">
|
||||||
|
<div className="space-y-2 col-span-1">
|
||||||
|
<Label htmlFor="numero">Número</Label>
|
||||||
|
<Input
|
||||||
|
id="numero"
|
||||||
|
value={formData.numero}
|
||||||
|
onChange={(e) => handleInputChange("numero", e.target.value)}
|
||||||
|
placeholder="123"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2 col-span-3">
|
||||||
|
<Label htmlFor="complemento">Complemento</Label>
|
||||||
|
<Input
|
||||||
|
id="complemento"
|
||||||
|
value={formData.complemento}
|
||||||
|
onChange={(e) => handleInputChange("complemento", e.target.value)}
|
||||||
|
placeholder="Apto, Bloco, etc."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid md:grid-cols-4 gap-4">
|
||||||
|
<div className="space-y-2 col-span-2">
|
||||||
|
<Label htmlFor="bairro">Bairro</Label>
|
||||||
|
<Input
|
||||||
|
id="bairro"
|
||||||
|
value={formData.bairro}
|
||||||
|
onChange={(e) => handleInputChange("bairro", e.target.value)}
|
||||||
|
placeholder="Bairro"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2 col-span-1">
|
||||||
|
<Label htmlFor="cidade">Cidade</Label>
|
||||||
|
<Input
|
||||||
|
id="cidade"
|
||||||
|
value={formData.cidade}
|
||||||
|
onChange={(e) => handleInputChange("cidade", e.target.value)}
|
||||||
|
placeholder="São Paulo"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2 col-span-1">
|
||||||
|
<Label htmlFor="estado">Estado (state)</Label>
|
||||||
|
<Input
|
||||||
|
id="estado"
|
||||||
|
value={formData.estado}
|
||||||
|
onChange={(e) => handleInputChange("estado", e.target.value)}
|
||||||
|
placeholder="SP"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
<div className="space-y-4 p-4 border rounded-xl shadow-sm bg-white">
|
||||||
|
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">
|
||||||
|
Observações (Apenas internas)
|
||||||
|
</h2>
|
||||||
|
<Textarea
|
||||||
|
id="observacoes"
|
||||||
|
value={formData.observacoes}
|
||||||
|
onChange={(e) => handleInputChange("observacoes", e.target.value)}
|
||||||
|
placeholder="Notas internas sobre o médico..."
|
||||||
|
className="min-h-[100px]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
<div className="flex justify-end gap-4 pb-8 pt-4">
|
||||||
|
<Link href="/manager/home">
|
||||||
|
<Button type="button" variant="outline" disabled={isSaving}>
|
||||||
|
Cancelar
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
className="bg-green-600 hover:bg-green-700"
|
||||||
|
disabled={isSaving}
|
||||||
|
>
|
||||||
|
{isSaving ? (
|
||||||
|
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<Save className="w-4 h-4 mr-2" />
|
||||||
|
)}
|
||||||
|
{isSaving ? "Salvando..." : "Salvar Alterações"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</Sidebar>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
@ -1,89 +1,91 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import React, { useEffect, useState, useCallback, useMemo } from "react"
|
import React, { useEffect, useState, useCallback, useMemo } from "react";
|
||||||
import ManagerLayout from "@/components/manager-layout";
|
import Link from "next/link";
|
||||||
import Link from "next/link"
|
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button";
|
||||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
import { Plus, Edit, Trash2, Eye, Calendar, Filter, Loader2, MoreVertical } from "lucide-react"
|
import { Edit, Trash2, Eye, Calendar, Loader2, MoreVertical } from "lucide-react";
|
||||||
import {
|
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||||
AlertDialog,
|
|
||||||
AlertDialogAction,
|
|
||||||
AlertDialogCancel,
|
|
||||||
AlertDialogContent,
|
|
||||||
AlertDialogDescription,
|
|
||||||
AlertDialogFooter,
|
|
||||||
AlertDialogHeader,
|
|
||||||
AlertDialogTitle,
|
|
||||||
} from "@/components/ui/alert-dialog"
|
|
||||||
|
|
||||||
import { doctorsService } from "services/doctorsApi.mjs";
|
// Imports dos Serviços
|
||||||
|
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||||
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
|
// --- NOVOS IMPORTS (Certifique-se que criou os arquivos no passo anterior) ---
|
||||||
|
import { FilterBar } from "@/components/ui/filter-bar";
|
||||||
|
import { normalizeSpecialty, getUniqueSpecialties } from "@/lib/normalization";
|
||||||
|
|
||||||
interface Doctor {
|
interface Doctor {
|
||||||
id: number;
|
id: number;
|
||||||
full_name: string;
|
full_name: string;
|
||||||
specialty: string;
|
specialty: string;
|
||||||
crm: string;
|
crm: string;
|
||||||
phone_mobile: string | null;
|
phone_mobile: string | null;
|
||||||
city: string | null;
|
city: string | null;
|
||||||
state: string | null;
|
state: string | null;
|
||||||
status?: string;
|
status?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
interface DoctorDetails {
|
interface DoctorDetails {
|
||||||
nome: string;
|
nome: string;
|
||||||
crm: string;
|
crm: string;
|
||||||
especialidade: string;
|
especialidade: string;
|
||||||
contato: {
|
contato: {
|
||||||
celular?: string;
|
celular?: string;
|
||||||
telefone1?: string;
|
telefone1?: string;
|
||||||
}
|
};
|
||||||
endereco: {
|
endereco: {
|
||||||
cidade?: string;
|
cidade?: string;
|
||||||
estado?: string;
|
estado?: string;
|
||||||
}
|
};
|
||||||
convenio?: string;
|
convenio?: string;
|
||||||
vip?: boolean;
|
vip?: boolean;
|
||||||
status?: string;
|
status?: string;
|
||||||
ultimo_atendimento?: string;
|
ultimo_atendimento?: string;
|
||||||
proximo_atendimento?: string;
|
proximo_atendimento?: string;
|
||||||
error?: string;
|
error?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function DoctorsPage() {
|
export default function DoctorsPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
|
// --- Estados de Dados ---
|
||||||
const [doctors, setDoctors] = useState<Doctor[]>([]);
|
const [doctors, setDoctors] = useState<Doctor[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// --- Estados de Modais ---
|
||||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
||||||
const [doctorDetails, setDoctorDetails] = useState<DoctorDetails | null>(null);
|
const [doctorDetails, setDoctorDetails] = useState<DoctorDetails | null>(null);
|
||||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||||
const [doctorToDeleteId, setDoctorToDeleteId] = useState<number | null>(null);
|
const [doctorToDeleteId, setDoctorToDeleteId] = useState<number | null>(null);
|
||||||
|
|
||||||
// --- Estados para Filtros ---
|
// --- Estados de Filtro e Busca ---
|
||||||
const [specialtyFilter, setSpecialtyFilter] = useState("all");
|
const [searchTerm, setSearchTerm] = useState("");
|
||||||
const [statusFilter, setStatusFilter] = useState("all");
|
const [filters, setFilters] = useState({
|
||||||
|
specialty: "all",
|
||||||
|
status: "all"
|
||||||
|
});
|
||||||
|
|
||||||
// --- Estados para Paginação ---
|
// --- Estados de Paginação ---
|
||||||
const [itemsPerPage, setItemsPerPage] = useState(10);
|
const [itemsPerPage, setItemsPerPage] = useState(10);
|
||||||
const [currentPage, setCurrentPage] = useState(1);
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
|
|
||||||
|
// 1. Buscar Médicos na API
|
||||||
const fetchDoctors = useCallback(async () => {
|
const fetchDoctors = useCallback(async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const data: Doctor[] = await doctorsService.list();
|
const data: Doctor[] = await doctorsService.list();
|
||||||
|
// Mockando status para visualização (conforme original)
|
||||||
const dataWithStatus = data.map((doc, index) => ({
|
const dataWithStatus = data.map((doc, index) => ({
|
||||||
...doc,
|
...doc,
|
||||||
status: index % 3 === 0 ? "Inativo" : index % 2 === 0 ? "Férias" : "Ativo"
|
status: index % 3 === 0 ? "Inativo" : index % 2 === 0 ? "Férias" : "Ativo",
|
||||||
}));
|
}));
|
||||||
setDoctors(dataWithStatus || []);
|
setDoctors(dataWithStatus || []);
|
||||||
setCurrentPage(1);
|
// Não resetamos a página aqui para manter a navegação fluida se apenas recarregar dados
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
console.error("Erro ao carregar lista de médicos:", e);
|
console.error("Erro ao carregar lista de médicos:", e);
|
||||||
setError("Não foi possível carregar a lista de médicos. Verifique a conexão com a API.");
|
setError("Não foi possível carregar a lista de médicos. Verifique a conexão com a API.");
|
||||||
@ -93,18 +95,99 @@ export default function DoctorsPage() {
|
|||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchDoctors();
|
||||||
|
}, [fetchDoctors]);
|
||||||
|
|
||||||
useEffect(() => {
|
// 2. Gerar lista única de especialidades (Normalizada)
|
||||||
fetchDoctors();
|
const uniqueSpecialties = useMemo(() => {
|
||||||
}, [fetchDoctors]);
|
return getUniqueSpecialties(doctors);
|
||||||
|
}, [doctors]);
|
||||||
|
|
||||||
|
// 3. Lógica de Filtragem Centralizada
|
||||||
|
const filteredDoctors = useMemo(() => {
|
||||||
|
return doctors.filter((doctor) => {
|
||||||
|
// Normaliza a especialidade do médico atual para comparar
|
||||||
|
const normalizedDocSpecialty = normalizeSpecialty(doctor.specialty);
|
||||||
|
|
||||||
|
// Filtros exatos
|
||||||
|
const specialtyMatch = filters.specialty === "all" || normalizedDocSpecialty === filters.specialty;
|
||||||
|
const statusMatch = filters.status === "all" || doctor.status === filters.status;
|
||||||
|
|
||||||
|
// Busca textual (Nome, Telefone, CRM)
|
||||||
|
const searchLower = searchTerm.toLowerCase();
|
||||||
|
const nameMatch = doctor.full_name?.toLowerCase().includes(searchLower);
|
||||||
|
const phoneMatch = doctor.phone_mobile?.includes(searchLower);
|
||||||
|
const crmMatch = doctor.crm?.toLowerCase().includes(searchLower);
|
||||||
|
|
||||||
const openDetailsDialog = async (doctor: Doctor) => {
|
return specialtyMatch && statusMatch && (searchTerm === "" || nameMatch || phoneMatch || crmMatch);
|
||||||
|
});
|
||||||
|
}, [doctors, filters, searchTerm]);
|
||||||
|
|
||||||
|
// --- Handlers de Controle (Com Reset de Paginação) ---
|
||||||
|
|
||||||
|
const handleSearch = (term: string) => {
|
||||||
|
setSearchTerm(term);
|
||||||
|
setCurrentPage(1); // Correção: Reseta para página 1 ao buscar
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFilterChange = (key: string, value: string) => {
|
||||||
|
setFilters(prev => ({ ...prev, [key]: value }));
|
||||||
|
setCurrentPage(1); // Correção: Reseta para página 1 ao filtrar
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleClearFilters = () => {
|
||||||
|
setSearchTerm("");
|
||||||
|
setFilters({ specialty: "all", status: "all" });
|
||||||
|
setCurrentPage(1); // Correção: Reseta para página 1 ao limpar
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleItemsPerPageChange = (value: string) => {
|
||||||
|
setItemsPerPage(Number(value));
|
||||||
|
setCurrentPage(1);
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- Lógica de Paginação ---
|
||||||
|
const totalPages = Math.ceil(filteredDoctors.length / itemsPerPage);
|
||||||
|
const indexOfLastItem = currentPage * itemsPerPage;
|
||||||
|
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
||||||
|
const currentItems = filteredDoctors.slice(indexOfFirstItem, indexOfLastItem);
|
||||||
|
|
||||||
|
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
|
||||||
|
const goToPrevPage = () => setCurrentPage((prev) => Math.max(1, prev - 1));
|
||||||
|
const goToNextPage = () => setCurrentPage((prev) => Math.min(totalPages, prev + 1));
|
||||||
|
|
||||||
|
const getVisiblePageNumbers = (totalPages: number, currentPage: number) => {
|
||||||
|
const pages: number[] = [];
|
||||||
|
const maxVisiblePages = 5;
|
||||||
|
const halfRange = Math.floor(maxVisiblePages / 2);
|
||||||
|
let startPage = Math.max(1, currentPage - halfRange);
|
||||||
|
let endPage = Math.min(totalPages, currentPage + halfRange);
|
||||||
|
|
||||||
|
if (endPage - startPage + 1 < maxVisiblePages) {
|
||||||
|
if (endPage === totalPages) {
|
||||||
|
startPage = Math.max(1, totalPages - maxVisiblePages + 1);
|
||||||
|
}
|
||||||
|
if (startPage === 1) {
|
||||||
|
endPage = Math.min(totalPages, maxVisiblePages);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let i = startPage; i <= endPage; i++) {
|
||||||
|
pages.push(i);
|
||||||
|
}
|
||||||
|
return pages;
|
||||||
|
};
|
||||||
|
|
||||||
|
const visiblePageNumbers = getVisiblePageNumbers(totalPages, currentPage);
|
||||||
|
|
||||||
|
// --- Handlers de Ações (Detalhes e Delete) ---
|
||||||
|
const openDetailsDialog = (doctor: Doctor) => {
|
||||||
setDetailsDialogOpen(true);
|
setDetailsDialogOpen(true);
|
||||||
setDoctorDetails({
|
setDoctorDetails({
|
||||||
nome: doctor.full_name,
|
nome: doctor.full_name,
|
||||||
crm: doctor.crm,
|
crm: doctor.crm,
|
||||||
especialidade: doctor.specialty,
|
especialidade: normalizeSpecialty(doctor.specialty), // Exibe normalizado
|
||||||
contato: { celular: doctor.phone_mobile ?? undefined },
|
contato: { celular: doctor.phone_mobile ?? undefined },
|
||||||
endereco: { cidade: doctor.city ?? undefined, estado: doctor.state ?? undefined },
|
endereco: { cidade: doctor.city ?? undefined, estado: doctor.state ?? undefined },
|
||||||
status: doctor.status || "Ativo",
|
status: doctor.status || "Ativo",
|
||||||
@ -115,6 +198,10 @@ export default function DoctorsPage() {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const openDeleteDialog = (doctorId: number) => {
|
||||||
|
setDoctorToDeleteId(doctorId);
|
||||||
|
setDeleteDialogOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
const handleDelete = async () => {
|
const handleDelete = async () => {
|
||||||
if (doctorToDeleteId === null) return;
|
if (doctorToDeleteId === null) return;
|
||||||
@ -132,139 +219,59 @@ export default function DoctorsPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const openDeleteDialog = (doctorId: number) => {
|
return (
|
||||||
setDoctorToDeleteId(doctorId);
|
<Sidebar>
|
||||||
setDeleteDialogOpen(true);
|
<div className="space-y-6 px-2 sm:px-4 md:px-6">
|
||||||
};
|
{/* Cabeçalho */}
|
||||||
|
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold text-gray-900">
|
||||||
|
Médicos Cadastrados
|
||||||
|
</h1>
|
||||||
|
<p className="text-sm text-gray-500">
|
||||||
|
Gerencie todos os profissionais de saúde.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
const uniqueSpecialties = useMemo(() => {
|
{/* --- NOVO COMPONENTE DE FILTRO --- */}
|
||||||
const specialties = doctors.map(doctor => doctor.specialty).filter(Boolean);
|
<FilterBar
|
||||||
return [...new Set(specialties)];
|
searchTerm={searchTerm}
|
||||||
}, [doctors]);
|
onSearch={handleSearch}
|
||||||
|
activeFilters={filters}
|
||||||
const filteredDoctors = doctors.filter(doctor => {
|
onFilterChange={handleFilterChange}
|
||||||
const specialtyMatch = specialtyFilter === "all" || doctor.specialty === specialtyFilter;
|
onClearFilters={handleClearFilters}
|
||||||
const statusMatch = statusFilter === "all" || doctor.status === statusFilter;
|
searchPlaceholder="Buscar por nome, CRM ou telefone..."
|
||||||
return specialtyMatch && statusMatch;
|
filters={[
|
||||||
});
|
{
|
||||||
|
key: "specialty",
|
||||||
const totalPages = Math.ceil(filteredDoctors.length / itemsPerPage);
|
label: "Especialidade",
|
||||||
const indexOfLastItem = currentPage * itemsPerPage;
|
options: uniqueSpecialties
|
||||||
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
},
|
||||||
const currentItems = filteredDoctors.slice(indexOfFirstItem, indexOfLastItem);
|
{
|
||||||
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
|
key: "status",
|
||||||
|
label: "Status",
|
||||||
const goToPrevPage = () => {
|
options: ["Ativo", "Férias", "Inativo"]
|
||||||
setCurrentPage((prev) => Math.max(1, prev - 1));
|
}
|
||||||
};
|
]}
|
||||||
|
>
|
||||||
const goToNextPage = () => {
|
{/* Seletor de Itens por Página (Filho do FilterBar) */}
|
||||||
setCurrentPage((prev) => Math.min(totalPages, prev + 1));
|
<div className="hidden lg:block">
|
||||||
};
|
<Select onValueChange={handleItemsPerPageChange} defaultValue={String(itemsPerPage)}>
|
||||||
|
<SelectTrigger className="w-[70px]">
|
||||||
const getVisiblePageNumbers = (totalPages: number, currentPage: number) => {
|
<SelectValue placeholder="10" />
|
||||||
const pages: number[] = [];
|
|
||||||
const maxVisiblePages = 5;
|
|
||||||
const halfRange = Math.floor(maxVisiblePages / 2);
|
|
||||||
let startPage = Math.max(1, currentPage - halfRange);
|
|
||||||
let endPage = Math.min(totalPages, currentPage + halfRange);
|
|
||||||
|
|
||||||
if (endPage - startPage + 1 < maxVisiblePages) {
|
|
||||||
if (endPage === totalPages) {
|
|
||||||
startPage = Math.max(1, totalPages - maxVisiblePages + 1);
|
|
||||||
}
|
|
||||||
if (startPage === 1) {
|
|
||||||
endPage = Math.min(totalPages, maxVisiblePages);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (let i = startPage; i <= endPage; i++) {
|
|
||||||
pages.push(i);
|
|
||||||
}
|
|
||||||
return pages;
|
|
||||||
};
|
|
||||||
|
|
||||||
const visiblePageNumbers = getVisiblePageNumbers(totalPages, currentPage);
|
|
||||||
|
|
||||||
const handleItemsPerPageChange = (value: string) => {
|
|
||||||
setItemsPerPage(Number(value));
|
|
||||||
setCurrentPage(1);
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ManagerLayout>
|
|
||||||
<div className="space-y-6 px-2 sm:px-4 md:px-6">
|
|
||||||
|
|
||||||
{/* Cabeçalho */}
|
|
||||||
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
|
|
||||||
<div>
|
|
||||||
<h1 className="text-2xl font-bold text-gray-900">Médicos Cadastrados</h1>
|
|
||||||
<p className="text-sm text-gray-500">Gerencie todos os profissionais de saúde.</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
|
|
||||||
{/* Filtros e Itens por Página */}
|
|
||||||
<div className="flex flex-wrap items-center gap-3 bg-white p-3 sm:p-4 rounded-lg border border-gray-200">
|
|
||||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
|
||||||
<span className="text-sm font-medium text-foreground">
|
|
||||||
Especialidade
|
|
||||||
</span>
|
|
||||||
<Select value={specialtyFilter} onValueChange={setSpecialtyFilter}>
|
|
||||||
<SelectTrigger className="w-[160px] sm:w-[180px]">
|
|
||||||
<SelectValue placeholder="Especialidade" />
|
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="all">Todas</SelectItem>
|
<SelectItem value="5">5</SelectItem>
|
||||||
{uniqueSpecialties.map(specialty => (
|
<SelectItem value="10">10</SelectItem>
|
||||||
<SelectItem key={specialty} value={specialty}>{specialty}</SelectItem>
|
<SelectItem value="20">20</SelectItem>
|
||||||
))}
|
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
</FilterBar>
|
||||||
<span className="text-sm font-medium text-foreground">
|
|
||||||
Status
|
|
||||||
</span>
|
|
||||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
|
||||||
<SelectTrigger className="w-[160px] sm:w-[180px]">
|
|
||||||
<SelectValue placeholder="Status" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="all">Todos</SelectItem>
|
|
||||||
<SelectItem value="Ativo">Ativo</SelectItem>
|
|
||||||
<SelectItem value="Férias">Férias</SelectItem>
|
|
||||||
<SelectItem value="Inativo">Inativo</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
|
||||||
<span className="text-sm font-medium text-foreground">
|
|
||||||
Itens por página
|
|
||||||
</span>
|
|
||||||
<Select
|
|
||||||
onValueChange={handleItemsPerPageChange}
|
|
||||||
defaultValue={String(itemsPerPage)}>
|
|
||||||
<SelectTrigger className="w-[140px]">
|
|
||||||
<SelectValue placeholder="Itens por pág." />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="5">5 por página</SelectItem>
|
|
||||||
<SelectItem value="10">10 por página</SelectItem>
|
|
||||||
<SelectItem value="20">20 por página</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
<Button variant="outline" className="ml-auto w-full md:w-auto">
|
|
||||||
<Filter className="w-4 h-4 mr-2" />
|
|
||||||
Filtro avançado
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
|
|
||||||
{/* Tabela de Médicos */}
|
{/* Tabela de Médicos */}
|
||||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-hidden">
|
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-hidden hidden md:block">
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="p-8 text-center text-gray-500">
|
<div className="p-8 text-center text-gray-500">
|
||||||
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
|
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
|
||||||
@ -287,25 +294,36 @@ export default function DoctorsPage() {
|
|||||||
<th className="text-left p-2 md:p-4 font-medium text-gray-700">Nome</th>
|
<th className="text-left p-2 md:p-4 font-medium text-gray-700">Nome</th>
|
||||||
<th className="text-left p-2 md:p-4 font-medium text-gray-700">CRM</th>
|
<th className="text-left p-2 md:p-4 font-medium text-gray-700">CRM</th>
|
||||||
<th className="text-left p-2 md:p-4 font-medium text-gray-700">Especialidade</th>
|
<th className="text-left p-2 md:p-4 font-medium text-gray-700">Especialidade</th>
|
||||||
<th className="text-left p-2 md:p-4 font-medium text-gray-700">Status</th>
|
<th className="text-left p-2 md:p-4 font-medium text-gray-700 hidden lg:table-cell">Status</th>
|
||||||
<th className="text-left p-2 md:p-4 font-medium text-gray-700">Cidade/Estado</th>
|
<th className="text-left p-2 md:p-4 font-medium text-gray-700 hidden xl:table-cell">Cidade/Estado</th>
|
||||||
<th className="text-right p-4 font-medium text-gray-700">Ações</th>
|
<th className="text-right p-4 font-medium text-gray-700">Ações</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody className="bg-white divide-y divide-gray-200">
|
<tbody className="bg-white divide-y divide-gray-200">
|
||||||
{currentItems.map((doctor) => (
|
{currentItems.map((doctor) => (
|
||||||
<tr key={doctor.id} className="hover:bg-gray-50 transition">
|
<tr key={doctor.id} className="hover:bg-gray-50 transition">
|
||||||
<td className="px-4 py-3 font-medium text-gray-900">{doctor.full_name}</td>
|
<td className="px-4 py-3 font-medium text-gray-900">
|
||||||
|
{doctor.full_name}
|
||||||
|
</td>
|
||||||
<td className="px-4 py-3 text-gray-500 hidden sm:table-cell">{doctor.crm}</td>
|
<td className="px-4 py-3 text-gray-500 hidden sm:table-cell">{doctor.crm}</td>
|
||||||
<td className="px-4 py-3 text-gray-500 hidden md:table-cell">{doctor.specialty}</td>
|
<td className="px-4 py-3 text-gray-500 hidden md:table-cell">
|
||||||
<td className="px-4 py-3 text-gray-500 hidden lg:table-cell">{doctor.status || "N/A"}</td>
|
{/* Exibe Especialidade Normalizada */}
|
||||||
|
{normalizeSpecialty(doctor.specialty)}
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-gray-500 hidden lg:table-cell">
|
||||||
|
<span className={`px-2 py-1 rounded-full text-xs ${
|
||||||
|
doctor.status === 'Ativo' ? 'bg-green-100 text-green-800' :
|
||||||
|
doctor.status === 'Inativo' ? 'bg-red-100 text-red-800' : 'bg-yellow-100 text-yellow-800'
|
||||||
|
}`}>
|
||||||
|
{doctor.status || "N/A"}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
<td className="px-4 py-3 text-gray-500 hidden xl:table-cell">
|
<td className="px-4 py-3 text-gray-500 hidden xl:table-cell">
|
||||||
{(doctor.city || doctor.state)
|
{(doctor.city || doctor.state)
|
||||||
? `${doctor.city || ""}${doctor.city && doctor.state ? '/' : ''}${doctor.state || ""}`
|
? `${doctor.city || ""}${doctor.city && doctor.state ? '/' : ''}${doctor.state || ""}`
|
||||||
: "N/A"}
|
: "N/A"}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-4 py-3 text-right">
|
<td className="px-4 py-3 text-right">
|
||||||
{/* ===== INÍCIO DA ALTERAÇÃO ===== */}
|
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<div className="text-black-600 cursor-pointer inline-block">
|
<div className="text-black-600 cursor-pointer inline-block">
|
||||||
@ -333,7 +351,6 @@ export default function DoctorsPage() {
|
|||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
{/* ===== FIM DA ALTERAÇÃO ===== */}
|
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
@ -343,48 +360,110 @@ export default function DoctorsPage() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Paginação */}
|
{/* Cards de Médicos (Mobile) */}
|
||||||
{totalPages > 1 && (
|
<div className="bg-white rounded-lg border border-gray-200 shadow-md p-4 block md:hidden">
|
||||||
<div className="flex flex-wrap justify-center items-center gap-2 mt-4 p-4 bg-white rounded-lg border border-gray-200 shadow-md">
|
{loading ? (
|
||||||
<button
|
<div className="p-8 text-center text-gray-500">
|
||||||
onClick={goToPrevPage}
|
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
|
||||||
disabled={currentPage === 1}
|
Carregando médicos...
|
||||||
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300"
|
</div>
|
||||||
>
|
) : error ? (
|
||||||
{"< Anterior"}
|
<div className="p-8 text-center text-red-600">{error}</div>
|
||||||
</button>
|
) : filteredDoctors.length === 0 ? (
|
||||||
|
<div className="p-8 text-center text-gray-500">
|
||||||
|
{doctors.length === 0
|
||||||
|
? <>Nenhum médico cadastrado. <Link href="/manager/home/novo" className="text-green-600 hover:underline">Adicione um novo</Link>.</>
|
||||||
|
: "Nenhum médico encontrado com os filtros aplicados."
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{currentItems.map((doctor) => (
|
||||||
|
<div key={doctor.id} className="bg-gray-50 rounded-lg p-4 flex justify-between items-center border border-gray-100">
|
||||||
|
<div>
|
||||||
|
<div className="font-semibold text-gray-900">{doctor.full_name}</div>
|
||||||
|
<div className="text-xs text-gray-500 mb-1">{doctor.phone_mobile}</div>
|
||||||
|
<div className="text-sm text-gray-600">{normalizeSpecialty(doctor.specialty)}</div>
|
||||||
|
<div className="text-xs mt-1">
|
||||||
|
<span className={`px-2 py-0.5 rounded-full text-xs ${
|
||||||
|
doctor.status === 'Ativo' ? 'bg-green-100 text-green-800' :
|
||||||
|
doctor.status === 'Inativo' ? 'bg-red-100 text-red-800' : 'bg-yellow-100 text-yellow-800'
|
||||||
|
}`}>
|
||||||
|
{doctor.status || "N/A"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
|
||||||
|
<span className="sr-only">Abrir menu</span>
|
||||||
|
<div className="font-bold text-gray-500">...</div>
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end">
|
||||||
|
<DropdownMenuItem onClick={() => openDetailsDialog(doctor)}>
|
||||||
|
<Eye className="mr-2 h-4 w-4" />
|
||||||
|
Ver detalhes
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem asChild>
|
||||||
|
<Link href={`/manager/home/${doctor.id}/editar`}>
|
||||||
|
<Edit className="mr-2 h-4 w-4" />
|
||||||
|
Editar
|
||||||
|
</Link>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(doctor.id)}>
|
||||||
|
<Trash2 className="mr-2 h-4 w-4" />
|
||||||
|
Excluir
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
{visiblePageNumbers.map((number) => (
|
{/* Paginação */}
|
||||||
<button
|
{totalPages > 1 && (
|
||||||
key={number}
|
<div className="flex flex-wrap justify-center items-center gap-2 mt-4 p-4 bg-white rounded-lg border border-gray-200 shadow-md">
|
||||||
onClick={() => paginate(number)}
|
<button
|
||||||
className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border border-gray-300 ${currentPage === number
|
onClick={goToPrevPage}
|
||||||
? "bg-green-600 text-white shadow-md border-green-600"
|
disabled={currentPage === 1}
|
||||||
: "bg-gray-100 text-gray-700 hover:bg-gray-200"
|
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300"
|
||||||
}`}
|
>
|
||||||
>
|
{"< Anterior"}
|
||||||
{number}
|
</button>
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
|
|
||||||
<button
|
{visiblePageNumbers.map((number) => (
|
||||||
onClick={goToNextPage}
|
<button
|
||||||
disabled={currentPage === totalPages}
|
key={number}
|
||||||
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300"
|
onClick={() => paginate(number)}
|
||||||
>
|
className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border border-gray-300 ${
|
||||||
{"Próximo >"}
|
currentPage === number
|
||||||
</button>
|
? "bg-blue-600 text-white shadow-md border-blue-600"
|
||||||
</div>
|
: "bg-gray-100 text-gray-700 hover:bg-gray-200"
|
||||||
)}
|
}`}
|
||||||
|
>
|
||||||
|
{number}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
|
||||||
{/* Dialogs de Exclusão e Detalhes */}
|
<button
|
||||||
|
onClick={goToNextPage}
|
||||||
|
disabled={currentPage === totalPages}
|
||||||
|
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300"
|
||||||
|
>
|
||||||
|
{"Próximo >"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Dialogs (Exclusão e Detalhes) */}
|
||||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||||
<AlertDialogContent>
|
<AlertDialogContent>
|
||||||
<AlertDialogHeader>
|
<AlertDialogHeader>
|
||||||
<AlertDialogTitle>Confirma a exclusão?</AlertDialogTitle>
|
<AlertDialogTitle>Confirma a exclusão?</AlertDialogTitle>
|
||||||
<AlertDialogDescription>
|
<AlertDialogDescription>Esta ação é irreversível e excluirá permanentemente o registro deste médico.</AlertDialogDescription>
|
||||||
Esta ação é irreversível e excluirá permanentemente o registro deste médico.
|
|
||||||
</AlertDialogDescription>
|
|
||||||
</AlertDialogHeader>
|
</AlertDialogHeader>
|
||||||
<AlertDialogFooter>
|
<AlertDialogFooter>
|
||||||
<AlertDialogCancel disabled={loading}>Cancelar</AlertDialogCancel>
|
<AlertDialogCancel disabled={loading}>Cancelar</AlertDialogCancel>
|
||||||
@ -396,42 +475,78 @@ export default function DoctorsPage() {
|
|||||||
</AlertDialogContent>
|
</AlertDialogContent>
|
||||||
</AlertDialog>
|
</AlertDialog>
|
||||||
|
|
||||||
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
<AlertDialog
|
||||||
<AlertDialogContent className="max-w-[95%] sm:max-w-lg">
|
open={detailsDialogOpen}
|
||||||
<AlertDialogHeader>
|
onOpenChange={setDetailsDialogOpen}
|
||||||
<AlertDialogTitle className="text-2xl">{doctorDetails?.nome}</AlertDialogTitle>
|
>
|
||||||
<AlertDialogDescription className="text-left text-gray-700">
|
<AlertDialogContent className="max-w-[95%] sm:max-w-lg">
|
||||||
{doctorDetails && (
|
<AlertDialogHeader>
|
||||||
<div className="space-y-3 text-left">
|
<AlertDialogTitle className="text-2xl">
|
||||||
<h3 className="font-semibold mt-2">Informações Principais</h3>
|
{doctorDetails?.nome}
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-y-2 gap-x-4 text-sm">
|
</AlertDialogTitle>
|
||||||
<div><strong>CRM:</strong> {doctorDetails.crm}</div>
|
<AlertDialogDescription className="text-left text-gray-700">
|
||||||
<div><strong>Especialidade:</strong> {doctorDetails.especialidade}</div>
|
{doctorDetails && (
|
||||||
<div><strong>Celular:</strong> {doctorDetails.contato.celular || 'N/A'}</div>
|
<div className="space-y-3 text-left">
|
||||||
<div><strong>Localização:</strong> {`${doctorDetails.endereco.cidade || 'N/A'}/${doctorDetails.endereco.estado || 'N/A'}`}</div>
|
<h3 className="font-semibold mt-2">
|
||||||
</div>
|
Informações Principais
|
||||||
|
</h3>
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-y-2 gap-x-4 text-sm">
|
||||||
|
<div>
|
||||||
|
<strong>CRM:</strong> {doctorDetails.crm}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<strong>Especialidade:</strong>{" "}
|
||||||
|
{doctorDetails.especialidade}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<strong>Celular:</strong>{" "}
|
||||||
|
{doctorDetails.contato.celular || "N/A"}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<strong>Localização:</strong>{" "}
|
||||||
|
{`${doctorDetails.endereco.cidade || "N/A"}/${
|
||||||
|
doctorDetails.endereco.estado || "N/A"
|
||||||
|
}`}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<h3 className="font-semibold mt-4">Atendimento e Convênio</h3>
|
<h3 className="font-semibold mt-4">
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-y-2 gap-x-4 text-sm">
|
Atendimento e Convênio
|
||||||
<div><strong>Convênio:</strong> {doctorDetails.convenio || 'N/A'}</div>
|
</h3>
|
||||||
<div><strong>VIP:</strong> {doctorDetails.vip ? "Sim" : "Não"}</div>
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-y-2 gap-x-4 text-sm">
|
||||||
<div><strong>Status:</strong> {doctorDetails.status || 'N/A'}</div>
|
<div>
|
||||||
<div><strong>Último atendimento:</strong> {doctorDetails.ultimo_atendimento || 'N/A'}</div>
|
<strong>Convênio:</strong>{" "}
|
||||||
<div><strong>Próximo atendimento:</strong> {doctorDetails.proximo_atendimento || 'N/A'}</div>
|
{doctorDetails.convenio || "N/A"}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<div>
|
||||||
)}
|
<strong>VIP:</strong>{" "}
|
||||||
{doctorDetails === null && !loading && (
|
{doctorDetails.vip ? "Sim" : "Não"}
|
||||||
<div className="text-red-600">Detalhes não disponíveis.</div>
|
</div>
|
||||||
)}
|
<div>
|
||||||
</AlertDialogDescription>
|
<strong>Status:</strong> {doctorDetails.status || "N/A"}
|
||||||
</AlertDialogHeader>
|
</div>
|
||||||
<AlertDialogFooter>
|
<div>
|
||||||
<AlertDialogCancel>Fechar</AlertDialogCancel>
|
<strong>Último atendimento:</strong>{" "}
|
||||||
</AlertDialogFooter>
|
{doctorDetails.ultimo_atendimento || "N/A"}
|
||||||
</AlertDialogContent>
|
</div>
|
||||||
</AlertDialog>
|
<div>
|
||||||
</div>
|
<strong>Próximo atendimento:</strong>{" "}
|
||||||
</ManagerLayout>
|
{doctorDetails.proximo_atendimento || "N/A"}
|
||||||
);
|
</div>
|
||||||
}
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{doctorDetails === null && !loading && (
|
||||||
|
<div className="text-red-600">Detalhes não disponíveis.</div>
|
||||||
|
)}
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>Fechar</AlertDialogCancel>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
</div>
|
||||||
|
</Sidebar>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@ -13,9 +13,8 @@ import { Checkbox } from "@/components/ui/checkbox";
|
|||||||
import { ArrowLeft, Save, Trash2, Paperclip, Upload } from "lucide-react";
|
import { ArrowLeft, Save, Trash2, Paperclip, Upload } from "lucide-react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { useToast } from "@/hooks/use-toast";
|
import { useToast } from "@/hooks/use-toast";
|
||||||
import SecretaryLayout from "@/components/secretary-layout";
|
|
||||||
import { patientsService } from "@/services/patientsApi.mjs";
|
import { patientsService } from "@/services/patientsApi.mjs";
|
||||||
import { json } from "stream/consumers";
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
export default function EditarPacientePage() {
|
export default function EditarPacientePage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@ -247,7 +246,7 @@ export default function EditarPacientePage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SecretaryLayout>
|
<Sidebar>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex items-center gap-4">
|
||||||
<Link href="/manager/pacientes">
|
<Link href="/manager/pacientes">
|
||||||
@ -677,6 +676,6 @@ export default function EditarPacientePage() {
|
|||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</SecretaryLayout>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, useEffect, useCallback } from "react";
|
import { useState, useEffect, useCallback } from "react";
|
||||||
@ -9,41 +8,41 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
|
|||||||
import { Plus, Edit, Trash2, Eye, Calendar, Filter, Loader2, MoreVertical } from "lucide-react";
|
import { Plus, Edit, Trash2, Eye, Calendar, Filter, Loader2, MoreVertical } from "lucide-react";
|
||||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||||
import { patientsService } from "@/services/patientsApi.mjs";
|
import { patientsService } from "@/services/patientsApi.mjs";
|
||||||
import ManagerLayout from "@/components/manager-layout";
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
// Defina o tamanho da página.
|
// Defina o tamanho da página.
|
||||||
const PAGE_SIZE = 5;
|
const PAGE_SIZE = 5;
|
||||||
|
|
||||||
export default function PacientesPage() {
|
export default function PacientesPage() {
|
||||||
// --- ESTADOS DE DADOS E GERAL ---
|
// --- ESTADOS DE DADOS E GERAL ---
|
||||||
const [searchTerm, setSearchTerm] = useState("");
|
const [searchTerm, setSearchTerm] = useState("");
|
||||||
const [convenioFilter, setConvenioFilter] = useState("all");
|
const [convenioFilter, setConvenioFilter] = useState("all");
|
||||||
const [vipFilter, setVipFilter] = useState("all");
|
const [vipFilter, setVipFilter] = useState("all");
|
||||||
|
|
||||||
// Lista completa, carregada da API uma única vez
|
|
||||||
const [allPatients, setAllPatients] = useState<any[]>([]);
|
|
||||||
// Lista após a aplicação dos filtros (base para a paginação)
|
|
||||||
const [filteredPatients, setFilteredPatients] = useState<any[]>([]);
|
|
||||||
|
|
||||||
const [loading, setLoading] = useState(true);
|
// Lista completa, carregada da API uma única vez
|
||||||
|
const [allPatients, setAllPatients] = useState<any[]>([]);
|
||||||
|
// Lista após a aplicação dos filtros (base para a paginação)
|
||||||
|
const [filteredPatients, setFilteredPatients] = useState<any[]>([]);
|
||||||
|
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
// --- ESTADOS DE PAGINAÇÃO ---
|
// --- ESTADOS DE PAGINAÇÃO ---
|
||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
|
|
||||||
// CÁLCULO DA PAGINAÇÃO
|
// CÁLCULO DA PAGINAÇÃO
|
||||||
const totalPages = Math.ceil(filteredPatients.length / PAGE_SIZE);
|
const totalPages = Math.ceil(filteredPatients.length / PAGE_SIZE);
|
||||||
const startIndex = (page - 1) * PAGE_SIZE;
|
const startIndex = (page - 1) * PAGE_SIZE;
|
||||||
const endIndex = startIndex + PAGE_SIZE;
|
const endIndex = startIndex + PAGE_SIZE;
|
||||||
// Pacientes a serem exibidos na tabela (aplicando a paginação)
|
// Pacientes a serem exibidos na tabela (aplicando a paginação)
|
||||||
const currentPatients = filteredPatients.slice(startIndex, endIndex);
|
const currentPatients = filteredPatients.slice(startIndex, endIndex);
|
||||||
|
|
||||||
// --- ESTADOS DE DIALOGS ---
|
// --- ESTADOS DE DIALOGS ---
|
||||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||||
const [patientToDelete, setPatientToDelete] = useState<string | null>(null);
|
const [patientToDelete, setPatientToDelete] = useState<string | null>(null);
|
||||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
||||||
const [patientDetails, setPatientDetails] = useState<any | null>(null);
|
const [patientDetails, setPatientDetails] = useState<any | null>(null);
|
||||||
|
|
||||||
// --- FUNÇÕES DE LÓGICA ---
|
// --- FUNÇÕES DE LÓGICA ---
|
||||||
|
|
||||||
// 1. Função para carregar TODOS os pacientes da API
|
// 1. Função para carregar TODOS os pacientes da API
|
||||||
@ -54,7 +53,7 @@ export default function PacientesPage() {
|
|||||||
try {
|
try {
|
||||||
// Como o backend retorna um array, chamamos sem paginação
|
// Como o backend retorna um array, chamamos sem paginação
|
||||||
const res = await patientsService.list();
|
const res = await patientsService.list();
|
||||||
|
|
||||||
const mapped = res.map((p: any) => ({
|
const mapped = res.map((p: any) => ({
|
||||||
id: String(p.id ?? ""),
|
id: String(p.id ?? ""),
|
||||||
nome: p.full_name ?? "—",
|
nome: p.full_name ?? "—",
|
||||||
@ -62,60 +61,57 @@ export default function PacientesPage() {
|
|||||||
cidade: p.city ?? "—",
|
cidade: p.city ?? "—",
|
||||||
estado: p.state ?? "—",
|
estado: p.state ?? "—",
|
||||||
// Formate as datas se necessário, aqui usamos como string
|
// Formate as datas se necessário, aqui usamos como string
|
||||||
ultimoAtendimento: p.last_visit_at?.split('T')[0] ?? "—",
|
ultimoAtendimento: p.last_visit_at?.split('T')[0] ?? "—",
|
||||||
proximoAtendimento: p.next_appointment_at?.split('T')[0] ?? "—",
|
proximoAtendimento: p.next_appointment_at ? p.next_appointment_at.split('T')[0].split('-').reverse().join('-') : "—",
|
||||||
vip: Boolean(p.vip ?? false),
|
vip: Boolean(p.vip ?? false),
|
||||||
convenio: p.convenio ?? "Particular", // Define um valor padrão
|
convenio: p.convenio ?? "Particular", // Define um valor padrão
|
||||||
status: p.status ?? undefined,
|
status: p.status ?? undefined,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
setAllPatients(mapped);
|
setAllPatients(mapped);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
setError(e?.message || "Erro ao buscar pacientes");
|
setError(e?.message || "Erro ao buscar pacientes");
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
},
|
}, []);
|
||||||
[]
|
|
||||||
);
|
|
||||||
|
|
||||||
// 2. Efeito para aplicar filtros e calcular a lista filtrada (chama-se quando allPatients ou filtros mudam)
|
// 2. Efeito para aplicar filtros e calcular a lista filtrada (chama-se quando allPatients ou filtros mudam)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const filtered = allPatients.filter((patient) => {
|
const filtered = allPatients.filter((patient) => {
|
||||||
// Filtro por termo de busca (Nome ou Telefone)
|
// Filtro por termo de busca (Nome ou Telefone)
|
||||||
const matchesSearch =
|
const matchesSearch =
|
||||||
patient.nome?.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
patient.nome?.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||||
patient.telefone?.includes(searchTerm);
|
patient.telefone?.includes(searchTerm);
|
||||||
|
|
||||||
// Filtro por Convênio
|
// Filtro por Convênio
|
||||||
const matchesConvenio =
|
const matchesConvenio =
|
||||||
convenioFilter === "all" ||
|
convenioFilter === "all" ||
|
||||||
patient.convenio === convenioFilter;
|
patient.convenio === convenioFilter;
|
||||||
|
|
||||||
// Filtro por VIP
|
// Filtro por VIP
|
||||||
const matchesVip =
|
const matchesVip =
|
||||||
vipFilter === "all" ||
|
vipFilter === "all" ||
|
||||||
(vipFilter === "vip" && patient.vip) ||
|
(vipFilter === "vip" && patient.vip) ||
|
||||||
(vipFilter === "regular" && !patient.vip);
|
(vipFilter === "regular" && !patient.vip);
|
||||||
|
|
||||||
return matchesSearch && matchesConvenio && matchesVip;
|
return matchesSearch && matchesConvenio && matchesVip;
|
||||||
});
|
});
|
||||||
|
|
||||||
setFilteredPatients(filtered);
|
setFilteredPatients(filtered);
|
||||||
// Garante que a página atual seja válida após a filtragem
|
// Garante que a página atual seja válida após a filtragem
|
||||||
setPage(1);
|
setPage(1);
|
||||||
}, [allPatients, searchTerm, convenioFilter, vipFilter]);
|
}, [allPatients, searchTerm, convenioFilter, vipFilter]);
|
||||||
|
|
||||||
// 3. Efeito inicial para buscar os pacientes
|
// 3. Efeito inicial para buscar os pacientes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchAllPacientes();
|
fetchAllPacientes();
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
|
||||||
// --- LÓGICA DE AÇÕES (DELETAR / VER DETALHES) ---
|
// --- LÓGICA DE AÇÕES (DELETAR / VER DETALHES) ---
|
||||||
|
|
||||||
const openDetailsDialog = async (patientId: string) => {
|
const openDetailsDialog = async (patientId: string) => {
|
||||||
setDetailsDialogOpen(true);
|
setDetailsDialogOpen(true);
|
||||||
setPatientDetails(null);
|
setPatientDetails(null);
|
||||||
@ -127,69 +123,81 @@ export default function PacientesPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDeletePatient = async (patientId: string) => {
|
const handleDeletePatient = async (patientId: string) => {
|
||||||
try {
|
try {
|
||||||
await patientsService.delete(patientId);
|
await patientsService.delete(patientId);
|
||||||
// Atualiza a lista completa para refletir a exclusão
|
// Atualiza a lista completa para refletir a exclusão
|
||||||
setAllPatients((prev) => prev.filter((p) => String(p.id) !== String(patientId)));
|
setAllPatients((prev) =>
|
||||||
} catch (e: any) {
|
prev.filter((p) => String(p.id) !== String(patientId))
|
||||||
alert(`Erro ao deletar paciente: ${e?.message || 'Erro desconhecido'}`);
|
);
|
||||||
}
|
} catch (e: any) {
|
||||||
setDeleteDialogOpen(false);
|
alert(`Erro ao deletar paciente: ${e?.message || "Erro desconhecido"}`);
|
||||||
setPatientToDelete(null);
|
}
|
||||||
};
|
setDeleteDialogOpen(false);
|
||||||
|
setPatientToDelete(null);
|
||||||
|
};
|
||||||
|
|
||||||
const openDeleteDialog = (patientId: string) => {
|
const openDeleteDialog = (patientId: string) => {
|
||||||
setPatientToDelete(patientId);
|
setPatientToDelete(patientId);
|
||||||
setDeleteDialogOpen(true);
|
setDeleteDialogOpen(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ManagerLayout>
|
<Sidebar>
|
||||||
<div className="space-y-6 px-2 sm:px-4 md:px-8">
|
<div className="space-y-6 px-2 sm:px-4 md:px-8">
|
||||||
{/* Header (Responsividade OK) */}
|
{/* Header (Responsividade OK) */}
|
||||||
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-xl md:text-2xl font-bold text-foreground">Pacientes</h1>
|
<h1 className="text-xl md:text-2xl font-bold text-foreground">
|
||||||
<p className="text-muted-foreground text-sm md:text-base">Gerencie as informações de seus pacientes</p>
|
Pacientes
|
||||||
</div>
|
</h1>
|
||||||
</div>
|
<p className="text-muted-foreground text-sm md:text-base">
|
||||||
|
Gerencie as informações de seus pacientes
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Bloco de Filtros (Responsividade APLICADA) */}
|
{/* Bloco de Filtros (Responsividade APLICADA) */}
|
||||||
|
{/* Adicionado flex-wrap para permitir que os itens quebrem para a linha de baixo */}
|
||||||
<div className="flex flex-wrap items-center gap-4 bg-card p-4 rounded-lg border border-border">
|
<div className="flex flex-wrap items-center gap-4 bg-card p-4 rounded-lg border border-border">
|
||||||
<Filter className="w-5 h-5 text-gray-400" />
|
<Filter className="w-5 h-5 text-gray-400" />
|
||||||
|
|
||||||
{/* Busca - Ocupa 100% no mobile, depois cresce */}
|
{/* Busca - Ocupa 100% no mobile, depois cresce */}
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
placeholder="Buscar por nome ou telefone..."
|
placeholder="Buscar por nome ou telefone..."
|
||||||
value={searchTerm}
|
value={searchTerm}
|
||||||
onChange={(e) => setSearchTerm(e.target.value)}
|
onChange={(e) => setSearchTerm(e.target.value)}
|
||||||
className="w-full sm:flex-grow sm:min-w-[150px] p-2 border rounded-md text-sm"
|
// w-full no mobile, depois flex-grow para ocupar o espaço disponível
|
||||||
|
className="w-full sm:flex-grow sm:max-w-[300px] p-2 border rounded-md text-sm"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Convênio - Ocupa metade da linha no mobile */}
|
{/* Convênio - Ocupa a largura total em telas pequenas, depois se ajusta */}
|
||||||
<div className="flex items-center gap-2 w-[calc(50%-8px)] sm:w-auto sm:flex-grow sm:max-w-[200px]">
|
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[200px]">
|
||||||
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">Convênio</span>
|
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">
|
||||||
<Select value={convenioFilter} onValueChange={setConvenioFilter}>
|
Convênio
|
||||||
<SelectTrigger className="w-full sm:w-40">
|
</span>
|
||||||
<SelectValue placeholder="Convênio" />
|
<Select value={convenioFilter} onValueChange={setConvenioFilter}>
|
||||||
</SelectTrigger>
|
<SelectTrigger className="w-full sm:w-40">
|
||||||
<SelectContent>
|
{" "}
|
||||||
<SelectItem value="all">Todos</SelectItem>
|
{/* w-full para mobile, w-40 para sm+ */}
|
||||||
<SelectItem value="Particular">Particular</SelectItem>
|
<SelectValue placeholder="Convênio" />
|
||||||
<SelectItem value="SUS">SUS</SelectItem>
|
</SelectTrigger>
|
||||||
<SelectItem value="Unimed">Unimed</SelectItem>
|
<SelectContent>
|
||||||
{/* Adicione outros convênios conforme necessário */}
|
<SelectItem value="all">Todos</SelectItem>
|
||||||
</SelectContent>
|
<SelectItem value="Particular">Particular</SelectItem>
|
||||||
</Select>
|
<SelectItem value="SUS">SUS</SelectItem>
|
||||||
</div>
|
<SelectItem value="Unimed">Unimed</SelectItem>
|
||||||
|
{/* Adicione outros convênios conforme necessário */}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* VIP - Ocupa a outra metade da linha no mobile */}
|
{/* VIP - Ocupa a largura total em telas pequenas, depois se ajusta */}
|
||||||
<div className="flex items-center gap-2 w-[calc(50%-8px)] sm:w-auto sm:flex-grow sm:max-w-[150px]">
|
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[150px]">
|
||||||
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">VIP</span>
|
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">VIP</span>
|
||||||
<Select value={vipFilter} onValueChange={setVipFilter}>
|
<Select value={vipFilter} onValueChange={setVipFilter}>
|
||||||
<SelectTrigger className="w-full sm:w-32">
|
<SelectTrigger className="w-full sm:w-32"> {/* w-full para mobile, w-32 para sm+ */}
|
||||||
<SelectValue placeholder="VIP" />
|
<SelectValue placeholder="VIP" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
@ -199,17 +207,18 @@ export default function PacientesPage() {
|
|||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Aniversariantes - Vai para a linha de baixo no mobile, ocupando 100% */}
|
{/* Aniversariantes - Ocupa 100% no mobile, e se alinha à direita no md+ */}
|
||||||
<Button variant="outline" className="w-full md:w-auto md:ml-auto">
|
<Button variant="outline" className="w-full md:w-auto md:ml-auto">
|
||||||
<Calendar className="w-4 h-4 mr-2" />
|
<Calendar className="w-4 h-4 mr-2" />
|
||||||
Aniversariantes
|
Aniversariantes
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Tabela (Responsividade APLICADA) */}
|
{/* --- SEÇÃO DE TABELA (VISÍVEL EM TELAS MAIORES OU IGUAIS A MD) --- */}
|
||||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md">
|
{/* Garantir que a tabela se esconda em telas menores e apareça em MD+ */}
|
||||||
<div className="overflow-x-auto">
|
<div className="bg-white rounded-lg border border-gray-200 shadow-md hidden md:block">
|
||||||
|
<div className="overflow-x-auto"> {/* Permite rolagem horizontal se a tabela for muito larga */}
|
||||||
{error ? (
|
{error ? (
|
||||||
<div className="p-6 text-red-600">{`Erro ao carregar pacientes: ${error}`}</div>
|
<div className="p-6 text-red-600">{`Erro ao carregar pacientes: ${error}`}</div>
|
||||||
) : loading ? (
|
) : loading ? (
|
||||||
@ -217,18 +226,14 @@ export default function PacientesPage() {
|
|||||||
<Loader2 className="w-6 h-6 mr-2 animate-spin text-green-600" /> Carregando pacientes...
|
<Loader2 className="w-6 h-6 mr-2 animate-spin text-green-600" /> Carregando pacientes...
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
// min-w ajustado para responsividade
|
<table className="w-full min-w-[650px]"> {/* min-w para evitar que a tabela se contraia demais */}
|
||||||
<table className="w-full min-w-[650px] md:min-w-[900px]">
|
|
||||||
<thead className="bg-gray-50 border-b border-gray-200">
|
<thead className="bg-gray-50 border-b border-gray-200">
|
||||||
<tr>
|
<tr>
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[20%]">Nome</th>
|
<th className="text-left p-4 font-medium text-gray-700 w-[20%]">Nome</th>
|
||||||
{/* Coluna oculta em telas muito pequenas */}
|
{/* Ajustes de visibilidade de colunas para diferentes breakpoints */}
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">Telefone</th>
|
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">Telefone</th>
|
||||||
{/* Coluna oculta em telas pequenas e muito pequenas */}
|
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden md:table-cell">Cidade / Estado</th>
|
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden md:table-cell">Cidade / Estado</th>
|
||||||
{/* Coluna oculta em telas muito pequenas */}
|
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">Convênio</th>
|
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">Convênio</th>
|
||||||
{/* Colunas ocultas em telas médias, pequenas e muito pequenas */}
|
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">Último atendimento</th>
|
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">Último atendimento</th>
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">Próximo atendimento</th>
|
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">Próximo atendimento</th>
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[5%]">Ações</th>
|
<th className="text-left p-4 font-medium text-gray-700 w-[5%]">Ações</th>
|
||||||
@ -257,13 +262,12 @@ export default function PacientesPage() {
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
{/* Aplicação das classes de visibilidade */}
|
|
||||||
<td className="p-4 text-gray-600 hidden sm:table-cell">{patient.telefone}</td>
|
<td className="p-4 text-gray-600 hidden sm:table-cell">{patient.telefone}</td>
|
||||||
<td className="p-4 text-gray-600 hidden md:table-cell">{`${patient.cidade} / ${patient.estado}`}</td>
|
<td className="p-4 text-gray-600 hidden md:table-cell">{`${patient.cidade} / ${patient.estado}`}</td>
|
||||||
<td className="p-4 text-gray-600 hidden sm:table-cell">{patient.convenio}</td>
|
<td className="p-4 text-gray-600 hidden sm:table-cell">{patient.convenio}</td>
|
||||||
<td className="p-4 text-gray-600 hidden lg:table-cell">{patient.ultimoAtendimento}</td>
|
<td className="p-4 text-gray-600 hidden lg:table-cell">{patient.ultimoAtendimento}</td>
|
||||||
<td className="p-4 text-gray-600 hidden lg:table-cell">{patient.proximoAtendimento}</td>
|
<td className="p-4 text-gray-600 hidden lg:table-cell">{patient.proximoAtendimento}</td>
|
||||||
|
|
||||||
<td className="p-4">
|
<td className="p-4">
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
@ -277,78 +281,70 @@ export default function PacientesPage() {
|
|||||||
Ver detalhes
|
Ver detalhes
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
|
||||||
<DropdownMenuItem asChild>
|
<DropdownMenuItem asChild>
|
||||||
<Link href={`/secretary/pacientes/${patient.id}/editar`} className="flex items-center w-full">
|
<Link href={`/secretary/pacientes/${patient.id}/editar`} className="flex items-center w-full">
|
||||||
<Edit className="w-4 h-4 mr-2" />
|
<Edit className="w-4 h-4 mr-2" />
|
||||||
Editar
|
Editar
|
||||||
</Link>
|
</Link>
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
|
||||||
<DropdownMenuItem>
|
<DropdownMenuItem>
|
||||||
<Calendar className="w-4 h-4 mr-2" />
|
<Calendar className="w-4 h-4 mr-2" />
|
||||||
Marcar consulta
|
Marcar consulta
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(String(patient.id))}>
|
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(String(patient.id))}>
|
||||||
<Trash2 className="w-4 h-4 mr-2" />
|
<Trash2 className="w-4 h-4 mr-2" />
|
||||||
Excluir
|
Excluir
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
</td>
|
</div>
|
||||||
</tr>
|
))}
|
||||||
))
|
|
||||||
)}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Paginação */}
|
|
||||||
{totalPages > 1 && !loading && (
|
|
||||||
<div className="flex flex-col sm:flex-row items-center justify-center p-4 border-t border-gray-200">
|
|
||||||
{/* Renderização dos botões de número de página (Limitando a 5) */}
|
|
||||||
<div className="flex space-x-2"> {/* Increased space-x for more separation */}
|
|
||||||
{/* Botão Anterior */}
|
|
||||||
<Button
|
|
||||||
onClick={() => setPage((prev) => Math.max(1, prev - 1))}
|
|
||||||
disabled={page === 1}
|
|
||||||
variant="outline"
|
|
||||||
size="lg" // Changed to "lg" for larger buttons
|
|
||||||
>
|
|
||||||
< Anterior
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
{Array.from({ length: totalPages }, (_, index) => index + 1)
|
|
||||||
.slice(Math.max(0, page - 3), Math.min(totalPages, page + 2))
|
|
||||||
.map((pageNumber) => (
|
|
||||||
<Button
|
|
||||||
key={pageNumber}
|
|
||||||
onClick={() => setPage(pageNumber)}
|
|
||||||
variant={pageNumber === page ? "default" : "outline"}
|
|
||||||
size="lg" // Changed to "lg" for larger buttons
|
|
||||||
className={pageNumber === page ? "bg-green-600 hover:bg-green-700 text-white" : "text-gray-700"}
|
|
||||||
>
|
|
||||||
{pageNumber}
|
|
||||||
</Button>
|
|
||||||
))}
|
|
||||||
|
|
||||||
{/* Botão Próximo */}
|
|
||||||
<Button
|
|
||||||
onClick={() => setPage((prev) => Math.min(totalPages, prev + 1))}
|
|
||||||
disabled={page === totalPages}
|
|
||||||
variant="outline"
|
|
||||||
size="lg" // Changed to "lg" for larger buttons
|
|
||||||
>
|
|
||||||
Próximo >
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Paginação */}
|
||||||
|
{totalPages > 1 && !loading && (
|
||||||
|
<div className="flex flex-col sm:flex-row items-center justify-center p-4 border-t border-gray-200">
|
||||||
|
<div className="flex space-x-2 flex-wrap justify-center"> {/* Adicionado flex-wrap e justify-center para botões da paginação */}
|
||||||
|
<Button
|
||||||
|
onClick={() => setPage((prev) => Math.max(1, prev - 1))}
|
||||||
|
disabled={page === 1}
|
||||||
|
variant="outline"
|
||||||
|
size="lg"
|
||||||
|
>
|
||||||
|
< Anterior
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
{Array.from({ length: totalPages }, (_, index) => index + 1)
|
||||||
|
.slice(Math.max(0, page - 3), Math.min(totalPages, page + 2))
|
||||||
|
.map((pageNumber) => (
|
||||||
|
<Button
|
||||||
|
key={pageNumber}
|
||||||
|
onClick={() => setPage(pageNumber)}
|
||||||
|
variant={pageNumber === page ? "default" : "outline"}
|
||||||
|
size="lg"
|
||||||
|
className={pageNumber === page ? "bg-green-600 hover:bg-green-700 text-white" : "text-gray-700"}
|
||||||
|
>
|
||||||
|
{pageNumber}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<Button
|
||||||
|
onClick={() => setPage((prev) => Math.min(totalPages, prev + 1))}
|
||||||
|
disabled={page === totalPages}
|
||||||
|
variant="outline"
|
||||||
|
size="lg"
|
||||||
|
>
|
||||||
|
Próximo >
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* AlertDialogs (Permanecem os mesmos) */}
|
{/* AlertDialogs (Permanecem os mesmos) */}
|
||||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||||
{/* ... (AlertDialog de Exclusão) ... */}
|
|
||||||
<AlertDialogContent>
|
<AlertDialogContent>
|
||||||
<AlertDialogHeader>
|
<AlertDialogHeader>
|
||||||
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
|
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
|
||||||
@ -364,7 +360,6 @@ export default function PacientesPage() {
|
|||||||
</AlertDialog>
|
</AlertDialog>
|
||||||
|
|
||||||
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
||||||
{/* ... (AlertDialog de Detalhes) ... */}
|
|
||||||
<AlertDialogContent>
|
<AlertDialogContent>
|
||||||
<AlertDialogHeader>
|
<AlertDialogHeader>
|
||||||
<AlertDialogTitle>Detalhes do Paciente</AlertDialogTitle>
|
<AlertDialogTitle>Detalhes do Paciente</AlertDialogTitle>
|
||||||
@ -378,67 +373,67 @@ export default function PacientesPage() {
|
|||||||
<div className="text-red-600 p-4">{patientDetails.error}</div>
|
<div className="text-red-600 p-4">{patientDetails.error}</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="grid gap-4 py-4">
|
<div className="grid gap-4 py-4">
|
||||||
<div className="grid grid-cols-2 gap-4">
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Nome Completo</p>
|
<p className="font-semibold">Nome Completo</p>
|
||||||
<p>{patientDetails.full_name}</p>
|
<p>{patientDetails.full_name}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Email</p>
|
<p className="font-semibold">Email</p>
|
||||||
<p>{patientDetails.email}</p>
|
<p>{patientDetails.email}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Telefone</p>
|
<p className="font-semibold">Telefone</p>
|
||||||
<p>{patientDetails.phone_mobile}</p>
|
<p>{patientDetails.phone_mobile}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Data de Nascimento</p>
|
<p className="font-semibold">Data de Nascimento</p>
|
||||||
<p>{patientDetails.birth_date}</p>
|
<p>{patientDetails.birth_date}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">CPF</p>
|
<p className="font-semibold">CPF</p>
|
||||||
<p>{patientDetails.cpf}</p>
|
<p>{patientDetails.cpf}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Tipo Sanguíneo</p>
|
<p className="font-semibold">Tipo Sanguíneo</p>
|
||||||
<p>{patientDetails.blood_type}</p>
|
<p>{patientDetails.blood_type}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Peso (kg)</p>
|
<p className="font-semibold">Peso (kg)</p>
|
||||||
<p>{patientDetails.weight_kg}</p>
|
<p>{patientDetails.weight_kg}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Altura (m)</p>
|
<p className="font-semibold">Altura (m)</p>
|
||||||
<p>{patientDetails.height_m}</p>
|
<p>{patientDetails.height_m}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="border-t pt-4 mt-4">
|
<div className="border-t pt-4 mt-4">
|
||||||
<h3 className="font-semibold mb-2">Endereço</h3>
|
<h3 className="font-semibold mb-2">Endereço</h3>
|
||||||
<div className="grid grid-cols-2 gap-4">
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Rua</p>
|
<p className="font-semibold">Rua</p>
|
||||||
<p>{`${patientDetails.street}, ${patientDetails.number}`}</p>
|
<p>{`${patientDetails.street}, ${patientDetails.number}`}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Complemento</p>
|
<p className="font-semibold">Complemento</p>
|
||||||
<p>{patientDetails.complement}</p>
|
<p>{patientDetails.complement}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Bairro</p>
|
<p className="font-semibold">Bairro</p>
|
||||||
<p>{patientDetails.neighborhood}</p>
|
<p>{patientDetails.neighborhood}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Cidade</p>
|
<p className="font-semibold">Cidade</p>
|
||||||
<p>{patientDetails.cidade}</p>
|
<p>{patientDetails.cidade}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Estado</p>
|
<p className="font-semibold">Estado</p>
|
||||||
<p>{patientDetails.estado}</p>
|
<p>{patientDetails.estado}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">CEP</p>
|
<p className="font-semibold">CEP</p>
|
||||||
<p>{patientDetails.cep}</p>
|
<p>{patientDetails.cep}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -451,6 +446,6 @@ export default function PacientesPage() {
|
|||||||
</AlertDialogContent>
|
</AlertDialogContent>
|
||||||
</AlertDialog>
|
</AlertDialog>
|
||||||
</div>
|
</div>
|
||||||
</ManagerLayout>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -8,7 +8,7 @@ import { Input } from "@/components/ui/input"
|
|||||||
import { Label } from "@/components/ui/label"
|
import { Label } from "@/components/ui/label"
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||||
import { Save, Loader2, ArrowLeft } from "lucide-react"
|
import { Save, Loader2, ArrowLeft } from "lucide-react"
|
||||||
import ManagerLayout from "@/components/manager-layout"
|
import Sidebar from "@/components/Sidebar"
|
||||||
|
|
||||||
// Mock user service for demonstration. Replace with your actual API service.
|
// Mock user service for demonstration. Replace with your actual API service.
|
||||||
const usersService = {
|
const usersService = {
|
||||||
@ -155,17 +155,17 @@ export default function EditarUsuarioPage() {
|
|||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
return (
|
return (
|
||||||
<ManagerLayout>
|
<Sidebar>
|
||||||
<div className="flex justify-center items-center h-full w-full py-16">
|
<div className="flex justify-center items-center h-full w-full py-16">
|
||||||
<Loader2 className="w-8 h-8 animate-spin text-green-600" />
|
<Loader2 className="w-8 h-8 animate-spin text-green-600" />
|
||||||
<p className="ml-2 text-gray-600">Carregando dados do usuário...</p>
|
<p className="ml-2 text-gray-600">Carregando dados do usuário...</p>
|
||||||
</div>
|
</div>
|
||||||
</ManagerLayout>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ManagerLayout>
|
<Sidebar>
|
||||||
<div className="w-full max-w-2xl mx-auto space-y-6 p-4 md:p-8">
|
<div className="w-full max-w-2xl mx-auto space-y-6 p-4 md:p-8">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
@ -274,6 +274,6 @@ export default function EditarUsuarioPage() {
|
|||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</ManagerLayout>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -1,4 +1,4 @@
|
|||||||
// /app/manager/usuario/novo/page.tsx
|
// ARQUIVO COMPLETO PARA: app/manager/usuario/novo/page.tsx
|
||||||
|
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
@ -9,11 +9,12 @@ import { Button } from "@/components/ui/button";
|
|||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
import { Save, Loader2, Pause } from "lucide-react";
|
import { Save, Loader2 } from "lucide-react";
|
||||||
import ManagerLayout from "@/components/manager-layout";
|
|
||||||
import { usersService } from "@/services/usersApi.mjs";
|
import { usersService } from "@/services/usersApi.mjs";
|
||||||
import { doctorsService } from "@/services/doctorsApi.mjs"; // Importação adicionada
|
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||||
import { login } from "services/api.mjs";
|
import { login } from "services/api.mjs";
|
||||||
|
import { isValidCPF } from "@/lib/utils"; // 1. IMPORTAÇÃO DA FUNÇÃO DE VALIDAÇÃO
|
||||||
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
interface UserFormData {
|
interface UserFormData {
|
||||||
email: string;
|
email: string;
|
||||||
@ -23,7 +24,6 @@ interface UserFormData {
|
|||||||
senha: string;
|
senha: string;
|
||||||
confirmarSenha: string;
|
confirmarSenha: string;
|
||||||
cpf: string;
|
cpf: string;
|
||||||
// Novos campos para Médico
|
|
||||||
crm: string;
|
crm: string;
|
||||||
crm_uf: string;
|
crm_uf: string;
|
||||||
specialty: string;
|
specialty: string;
|
||||||
@ -37,7 +37,6 @@ const defaultFormData: UserFormData = {
|
|||||||
senha: "",
|
senha: "",
|
||||||
confirmarSenha: "",
|
confirmarSenha: "",
|
||||||
cpf: "",
|
cpf: "",
|
||||||
// Valores iniciais para campos de Médico
|
|
||||||
crm: "",
|
crm: "",
|
||||||
crm_uf: "",
|
crm_uf: "",
|
||||||
specialty: "",
|
specialty: "",
|
||||||
@ -62,7 +61,6 @@ export default function NovoUsuarioPage() {
|
|||||||
if (key === "telefone") {
|
if (key === "telefone") {
|
||||||
updatedValue = formatPhone(value);
|
updatedValue = formatPhone(value);
|
||||||
} else if (key === "crm_uf") {
|
} else if (key === "crm_uf") {
|
||||||
// Converte UF para maiúsculas
|
|
||||||
updatedValue = value.toUpperCase();
|
updatedValue = value.toUpperCase();
|
||||||
}
|
}
|
||||||
setFormData((prev) => ({ ...prev, [key]: updatedValue }));
|
setFormData((prev) => ({ ...prev, [key]: updatedValue }));
|
||||||
@ -72,7 +70,7 @@ export default function NovoUsuarioPage() {
|
|||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setError(null);
|
setError(null);
|
||||||
|
|
||||||
if (!formData.email || !formData.nomeCompleto || !formData.papel || !formData.senha || !formData.confirmarSenha) {
|
if (!formData.email || !formData.nomeCompleto || !formData.papel || !formData.senha || !formData.confirmarSenha || !formData.cpf) {
|
||||||
setError("Por favor, preencha todos os campos obrigatórios.");
|
setError("Por favor, preencha todos os campos obrigatórios.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -82,7 +80,12 @@ export default function NovoUsuarioPage() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validação adicional para Médico
|
// 2. VALIDAÇÃO DO CPF ANTES DO ENVIO
|
||||||
|
if (!isValidCPF(formData.cpf)) {
|
||||||
|
setError("O CPF informado é inválido. Por favor, verifique os dígitos.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (formData.papel === "medico") {
|
if (formData.papel === "medico") {
|
||||||
if (!formData.crm || !formData.crm_uf) {
|
if (!formData.crm || !formData.crm_uf) {
|
||||||
setError("Para a função 'Médico', o CRM e a UF do CRM são obrigatórios.");
|
setError("Para a função 'Médico', o CRM e a UF do CRM são obrigatórios.");
|
||||||
@ -94,7 +97,6 @@ export default function NovoUsuarioPage() {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
if (formData.papel === "medico") {
|
if (formData.papel === "medico") {
|
||||||
// Lógica para criação de Médico
|
|
||||||
const doctorPayload = {
|
const doctorPayload = {
|
||||||
email: formData.email.trim().toLowerCase(),
|
email: formData.email.trim().toLowerCase(),
|
||||||
full_name: formData.nomeCompleto,
|
full_name: formData.nomeCompleto,
|
||||||
@ -102,41 +104,29 @@ export default function NovoUsuarioPage() {
|
|||||||
crm: formData.crm,
|
crm: formData.crm,
|
||||||
crm_uf: formData.crm_uf,
|
crm_uf: formData.crm_uf,
|
||||||
specialty: formData.specialty || null,
|
specialty: formData.specialty || null,
|
||||||
phone_mobile: formData.telefone || null, // Usando phone_mobile conforme o schema
|
phone_mobile: formData.telefone || null,
|
||||||
};
|
};
|
||||||
|
|
||||||
console.log("📤 Enviando payload para Médico:");
|
|
||||||
console.log(doctorPayload);
|
|
||||||
|
|
||||||
// Chamada ao endpoint específico para criação de médico
|
|
||||||
await doctorsService.create(doctorPayload);
|
await doctorsService.create(doctorPayload);
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
// Lógica para criação de Outras Roles
|
|
||||||
const isPatient = formData.papel === "paciente";
|
const isPatient = formData.papel === "paciente";
|
||||||
|
|
||||||
const userPayload = {
|
const userPayload = {
|
||||||
email: formData.email.trim().toLowerCase(),
|
email: formData.email.trim().toLowerCase(),
|
||||||
password: formData.senha,
|
password: formData.senha,
|
||||||
full_name: formData.nomeCompleto,
|
full_name: formData.nomeCompleto,
|
||||||
phone: formData.telefone || null,
|
phone: formData.telefone || null,
|
||||||
role: formData.papel,
|
roles: [formData.papel, "paciente"],
|
||||||
cpf: formData.cpf,
|
cpf: formData.cpf,
|
||||||
create_patient_record: isPatient, // true se a role for 'paciente'
|
create_patient_record: isPatient,
|
||||||
phone_mobile: isPatient ? formData.telefone || null : undefined, // Enviar phone_mobile se for paciente
|
phone_mobile: isPatient ? formData.telefone || null : undefined,
|
||||||
};
|
};
|
||||||
|
|
||||||
console.log("📤 Enviando payload para Usuário Comum:");
|
|
||||||
console.log(userPayload);
|
|
||||||
|
|
||||||
// Chamada ao endpoint padrão para criação de usuário
|
|
||||||
await usersService.create_user(userPayload);
|
await usersService.create_user(userPayload);
|
||||||
}
|
}
|
||||||
|
|
||||||
router.push("/manager/usuario");
|
router.push("/manager/usuario");
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
console.error("Erro ao criar usuário:", e);
|
console.error("Erro ao criar usuário:", e);
|
||||||
setError(e?.message || "Não foi possível criar o usuário. Verifique os dados e tente novamente.");
|
// 3. MENSAGEM DE ERRO MELHORADA
|
||||||
|
const detail = e.message?.split('detail:"')[1]?.split('"')[0] || e.message;
|
||||||
|
setError(detail.replace(/\\/g, "") || "Não foi possível criar o usuário. Verifique os dados e tente novamente.");
|
||||||
} finally {
|
} finally {
|
||||||
setIsSaving(false);
|
setIsSaving(false);
|
||||||
}
|
}
|
||||||
@ -145,7 +135,7 @@ export default function NovoUsuarioPage() {
|
|||||||
const isMedico = formData.papel === "medico";
|
const isMedico = formData.papel === "medico";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ManagerLayout>
|
<Sidebar>
|
||||||
<div className="w-full h-full p-4 md:p-8 flex justify-center items-start">
|
<div className="w-full h-full p-4 md:p-8 flex justify-center items-start">
|
||||||
<div className="w-full max-w-screen-lg space-y-8">
|
<div className="w-full max-w-screen-lg space-y-8">
|
||||||
<div className="flex items-center justify-between border-b pb-4">
|
<div className="flex items-center justify-between border-b pb-4">
|
||||||
@ -193,26 +183,22 @@ export default function NovoUsuarioPage() {
|
|||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Campos Condicionais para Médico */}
|
|
||||||
{isMedico && (
|
{isMedico && (
|
||||||
<>
|
<>
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="crm">CRM *</Label>
|
<Label htmlFor="crm">CRM *</Label>
|
||||||
<Input id="crm" value={formData.crm} onChange={(e) => handleInputChange("crm", e.target.value)} placeholder="Número do CRM" required />
|
<Input id="crm" value={formData.crm} onChange={(e) => handleInputChange("crm", e.target.value)} placeholder="Número do CRM" required />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="crm_uf">UF do CRM *</Label>
|
<Label htmlFor="crm_uf">UF do CRM *</Label>
|
||||||
<Input id="crm_uf" value={formData.crm_uf} onChange={(e) => handleInputChange("crm_uf", e.target.value)} placeholder="Ex: SP" maxLength={2} required />
|
<Input id="crm_uf" value={formData.crm_uf} onChange={(e) => handleInputChange("crm_uf", e.target.value)} placeholder="Ex: SP" maxLength={2} required />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2 md:col-span-2">
|
<div className="space-y-2 md:col-span-2">
|
||||||
<Label htmlFor="specialty">Especialidade (opcional)</Label>
|
<Label htmlFor="specialty">Especialidade (opcional)</Label>
|
||||||
<Input id="specialty" value={formData.specialty} onChange={(e) => handleInputChange("specialty", e.target.value)} placeholder="Ex: Cardiologia" />
|
<Input id="specialty" value={formData.specialty} onChange={(e) => handleInputChange("specialty", e.target.value)} placeholder="Ex: Cardiologia" />
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{/* Fim dos Campos Condicionais */}
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="senha">Senha *</Label>
|
<Label htmlFor="senha">Senha *</Label>
|
||||||
@ -233,7 +219,7 @@ export default function NovoUsuarioPage() {
|
|||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="cpf">Cpf *</Label>
|
<Label htmlFor="cpf">Cpf *</Label>
|
||||||
<Input id="cpf" type="cpf" value={formData.cpf} onChange={(e) => handleInputChange("cpf", e.target.value)} placeholder="xxx.xxx.xxx-xx" required />
|
<Input id="cpf" value={formData.cpf} onChange={(e) => handleInputChange("cpf", e.target.value)} placeholder="Apenas números" required />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex justify-end gap-4 pt-6 border-t mt-6">
|
<div className="flex justify-end gap-4 pt-6 border-t mt-6">
|
||||||
@ -250,6 +236,6 @@ export default function NovoUsuarioPage() {
|
|||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</ManagerLayout>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,44 +1,30 @@
|
|||||||
// app/manager/usuario/page.tsx
|
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import React, { useEffect, useState, useCallback } from "react";
|
import React, { useEffect, useState, useCallback } from "react";
|
||||||
import ManagerLayout from "@/components/manager-layout";
|
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
Select,
|
import { Input } from "@/components/ui/input"; // <--- 1. Importação Adicionada
|
||||||
SelectContent,
|
import { Plus, Eye, Filter, Loader2, Search } from "lucide-react"; // <--- 1. Ícone Search Adicionado
|
||||||
SelectItem,
|
import { AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from "@/components/ui/select";
|
|
||||||
import { Plus, Eye, Filter, Loader2 } from "lucide-react";
|
|
||||||
import {
|
|
||||||
AlertDialog,
|
|
||||||
AlertDialogCancel,
|
|
||||||
AlertDialogContent,
|
|
||||||
AlertDialogDescription,
|
|
||||||
AlertDialogFooter,
|
|
||||||
AlertDialogHeader,
|
|
||||||
AlertDialogTitle,
|
|
||||||
} from "@/components/ui/alert-dialog";
|
|
||||||
import { api, login } from "services/api.mjs";
|
import { api, login } from "services/api.mjs";
|
||||||
import { usersService } from "services/usersApi.mjs";
|
import { usersService } from "services/usersApi.mjs";
|
||||||
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
interface FlatUser {
|
interface FlatUser {
|
||||||
id: string;
|
id: string;
|
||||||
user_id: string;
|
user_id: string;
|
||||||
full_name?: string;
|
full_name?: string;
|
||||||
email: string;
|
email: string;
|
||||||
phone?: string | null;
|
phone?: string | null;
|
||||||
role: string;
|
role: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface UserInfoResponse {
|
interface UserInfoResponse {
|
||||||
user: any;
|
user: any;
|
||||||
profile: any;
|
profile: any;
|
||||||
roles: string[];
|
roles: string[];
|
||||||
permissions: Record<string, boolean>;
|
permissions: Record<string, boolean>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function UsersPage() {
|
export default function UsersPage() {
|
||||||
@ -46,384 +32,431 @@ export default function UsersPage() {
|
|||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
||||||
const [userDetails, setUserDetails] = useState<UserInfoResponse | null>(
|
const [userDetails, setUserDetails] = useState<UserInfoResponse | null>(null);
|
||||||
null
|
|
||||||
);
|
// --- Estados de Filtro ---
|
||||||
// Ajuste 1: Definir 'all' como valor inicial para garantir que todos os usuários sejam exibidos por padrão.
|
const [searchTerm, setSearchTerm] = useState(""); // <--- 2. Estado da busca
|
||||||
const [selectedRole, setSelectedRole] = useState<string>("all");
|
const [selectedRole, setSelectedRole] = useState<string>("all");
|
||||||
|
|
||||||
// --- Lógica de Paginação INÍCIO ---
|
// --- Lógica de Paginação INÍCIO ---
|
||||||
const [itemsPerPage, setItemsPerPage] = useState(10);
|
const [itemsPerPage, setItemsPerPage] = useState(10);
|
||||||
const [currentPage, setCurrentPage] = useState(1);
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
|
|
||||||
// Lógica para mudar itens por página, resetando para a página 1
|
const handleItemsPerPageChange = (value: string) => {
|
||||||
const handleItemsPerPageChange = (value: string) => {
|
setItemsPerPage(Number(value));
|
||||||
setItemsPerPage(Number(value));
|
setCurrentPage(1);
|
||||||
setCurrentPage(1); // Resetar para a primeira página
|
};
|
||||||
};
|
// --- Lógica de Paginação FIM ---
|
||||||
// --- Lógica de Paginação FIM ---
|
|
||||||
|
|
||||||
const fetchUsers = useCallback(async () => {
|
const fetchUsers = useCallback(async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const rolesData: any[] = await usersService.list_roles();
|
const rolesData: any[] = await usersService.list_roles();
|
||||||
const rolesArray = Array.isArray(rolesData) ? rolesData : [];
|
const rolesArray = Array.isArray(rolesData) ? rolesData : [];
|
||||||
|
|
||||||
const profilesData: any[] = await api.get(
|
const profilesData: any[] = await api.get(
|
||||||
`/rest/v1/profiles?select=id,full_name,email,phone`
|
`/rest/v1/profiles?select=id,full_name,email,phone`
|
||||||
);
|
);
|
||||||
|
|
||||||
const profilesById = new Map<string, any>();
|
const profilesById = new Map<string, any>();
|
||||||
if (Array.isArray(profilesData)) {
|
if (Array.isArray(profilesData)) {
|
||||||
for (const p of profilesData) {
|
for (const p of profilesData) {
|
||||||
if (p?.id) profilesById.set(p.id, p);
|
if (p?.id) profilesById.set(p.id, p);
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const mapped: FlatUser[] = rolesArray.map((roleItem) => {
|
|
||||||
const uid = roleItem.user_id;
|
|
||||||
const profile = profilesById.get(uid);
|
|
||||||
return {
|
|
||||||
id: uid,
|
|
||||||
user_id: uid,
|
|
||||||
full_name: profile?.full_name ?? "—",
|
|
||||||
email: profile?.email ?? "—",
|
|
||||||
phone: profile?.phone ?? "—",
|
|
||||||
role: roleItem.role ?? "—",
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
setUsers(mapped);
|
|
||||||
setCurrentPage(1); // Resetar a página após carregar
|
|
||||||
console.log("[fetchUsers] mapped count:", mapped.length);
|
|
||||||
} catch (err: any) {
|
|
||||||
console.error("Erro ao buscar usuários:", err);
|
|
||||||
setError("Não foi possível carregar os usuários. Veja console.");
|
|
||||||
setUsers([]);
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
}
|
||||||
}, []);
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
const mapped: FlatUser[] = rolesArray.map((roleItem) => {
|
||||||
const init = async () => {
|
const uid = roleItem.user_id;
|
||||||
try {
|
const profile = profilesById.get(uid);
|
||||||
await login();
|
return {
|
||||||
} catch (e) {
|
id: uid,
|
||||||
console.warn("login falhou no init:", e);
|
user_id: uid,
|
||||||
}
|
full_name: profile?.full_name ?? "—",
|
||||||
await fetchUsers();
|
email: profile?.email ?? "—",
|
||||||
|
phone: profile?.phone ?? "—",
|
||||||
|
role: roleItem.role ?? "—",
|
||||||
};
|
};
|
||||||
init();
|
});
|
||||||
}, [fetchUsers]);
|
|
||||||
|
|
||||||
const openDetailsDialog = async (flatUser: FlatUser) => {
|
setUsers(mapped);
|
||||||
setDetailsDialogOpen(true);
|
setCurrentPage(1);
|
||||||
setUserDetails(null);
|
} catch (err: any) {
|
||||||
|
console.error("Erro ao buscar usuários:", err);
|
||||||
|
setError("Não foi possível carregar os usuários. Veja console.");
|
||||||
|
setUsers([]);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
try {
|
useEffect(() => {
|
||||||
console.log("[openDetailsDialog] user_id:", flatUser.user_id);
|
const init = async () => {
|
||||||
const data = await usersService.full_data(flatUser.user_id);
|
try {
|
||||||
console.log("[openDetailsDialog] full_data returned:", data);
|
await login();
|
||||||
setUserDetails(data);
|
} catch (e) {
|
||||||
} catch (err: any) {
|
console.warn("login falhou no init:", e);
|
||||||
console.error("Erro ao carregar detalhes:", err);
|
}
|
||||||
setUserDetails({
|
await fetchUsers();
|
||||||
user: { id: flatUser.user_id, email: flatUser.email },
|
|
||||||
profile: { full_name: flatUser.full_name, phone: flatUser.phone },
|
|
||||||
roles: [flatUser.role],
|
|
||||||
permissions: {},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
init();
|
||||||
|
}, [fetchUsers]);
|
||||||
|
|
||||||
// 1. Filtragem
|
const openDetailsDialog = async (flatUser: FlatUser) => {
|
||||||
const filteredUsers =
|
setDetailsDialogOpen(true);
|
||||||
selectedRole && selectedRole !== "all"
|
setUserDetails(null);
|
||||||
? users.filter((u) => u.role === selectedRole)
|
|
||||||
: users;
|
|
||||||
|
|
||||||
// 2. Paginação (aplicada sobre a lista filtrada)
|
try {
|
||||||
const indexOfLastItem = currentPage * itemsPerPage;
|
const data = await usersService.full_data(flatUser.user_id);
|
||||||
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
setUserDetails(data);
|
||||||
const currentItems = filteredUsers.slice(indexOfFirstItem, indexOfLastItem);
|
} catch (err: any) {
|
||||||
|
console.error("Erro ao carregar detalhes:", err);
|
||||||
|
setUserDetails({
|
||||||
|
user: { id: flatUser.user_id, email: flatUser.email },
|
||||||
|
profile: { full_name: flatUser.full_name, phone: flatUser.phone },
|
||||||
|
roles: [flatUser.role],
|
||||||
|
permissions: {},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// Função para mudar de página
|
// --- 3. Lógica de Filtragem Atualizada ---
|
||||||
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
|
const filteredUsers = users.filter((u) => {
|
||||||
|
// Filtro por Papel (Role)
|
||||||
|
const roleMatch = selectedRole === "all" || u.role === selectedRole;
|
||||||
|
|
||||||
const totalPages = Math.ceil(filteredUsers.length / itemsPerPage);
|
// Filtro da Barra de Pesquisa (Nome, Email ou Telefone)
|
||||||
|
const searchLower = searchTerm.toLowerCase();
|
||||||
|
const nameMatch = u.full_name?.toLowerCase().includes(searchLower);
|
||||||
|
const emailMatch = u.email?.toLowerCase().includes(searchLower);
|
||||||
|
const phoneMatch = u.phone?.includes(searchLower);
|
||||||
|
|
||||||
|
const searchMatch = !searchTerm || nameMatch || emailMatch || phoneMatch;
|
||||||
|
|
||||||
// --- Funções e Lógica de Navegação ADICIONADAS ---
|
return roleMatch && searchMatch;
|
||||||
const goToPrevPage = () => {
|
});
|
||||||
setCurrentPage((prev) => Math.max(1, prev - 1));
|
|
||||||
};
|
|
||||||
|
|
||||||
const goToNextPage = () => {
|
const indexOfLastItem = currentPage * itemsPerPage;
|
||||||
setCurrentPage((prev) => Math.min(totalPages, prev + 1));
|
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
||||||
};
|
const currentItems = filteredUsers.slice(indexOfFirstItem, indexOfLastItem);
|
||||||
|
|
||||||
// Lógica para gerar os números das páginas visíveis
|
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
|
||||||
const getVisiblePageNumbers = (totalPages: number, currentPage: number) => {
|
|
||||||
const pages: number[] = [];
|
|
||||||
const maxVisiblePages = 5; // Número máximo de botões de página a serem exibidos (ex: 2, 3, 4, 5, 6)
|
|
||||||
const halfRange = Math.floor(maxVisiblePages / 2);
|
|
||||||
let startPage = Math.max(1, currentPage - halfRange);
|
|
||||||
let endPage = Math.min(totalPages, currentPage + halfRange);
|
|
||||||
|
|
||||||
// Ajusta para manter o número fixo de botões quando nos limites
|
const totalPages = Math.ceil(filteredUsers.length / itemsPerPage);
|
||||||
if (endPage - startPage + 1 < maxVisiblePages) {
|
|
||||||
if (endPage === totalPages) {
|
|
||||||
startPage = Math.max(1, totalPages - maxVisiblePages + 1);
|
|
||||||
}
|
|
||||||
if (startPage === 1) {
|
|
||||||
endPage = Math.min(totalPages, maxVisiblePages);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (let i = startPage; i <= endPage; i++) {
|
const goToPrevPage = () => {
|
||||||
pages.push(i);
|
setCurrentPage((prev) => Math.max(1, prev - 1));
|
||||||
}
|
};
|
||||||
return pages;
|
|
||||||
};
|
|
||||||
|
|
||||||
const visiblePageNumbers = getVisiblePageNumbers(totalPages, currentPage);
|
const goToNextPage = () => {
|
||||||
// --- Fim das Funções e Lógica de Navegação ADICIONADAS ---
|
setCurrentPage((prev) => Math.min(totalPages, prev + 1));
|
||||||
|
};
|
||||||
|
|
||||||
|
const getVisiblePageNumbers = (totalPages: number, currentPage: number) => {
|
||||||
|
const pages: number[] = [];
|
||||||
|
const maxVisiblePages = 5;
|
||||||
|
const halfRange = Math.floor(maxVisiblePages / 2);
|
||||||
|
let startPage = Math.max(1, currentPage - halfRange);
|
||||||
|
let endPage = Math.min(totalPages, currentPage + halfRange);
|
||||||
|
|
||||||
return (
|
if (endPage - startPage + 1 < maxVisiblePages) {
|
||||||
<ManagerLayout>
|
if (endPage === totalPages) {
|
||||||
<div className="space-y-6 px-2 sm:px-4 md:px-8">
|
startPage = Math.max(1, totalPages - maxVisiblePages + 1);
|
||||||
|
}
|
||||||
|
if (startPage === 1) {
|
||||||
|
endPage = Math.min(totalPages, maxVisiblePages);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
{/* Header */}
|
for (let i = startPage; i <= endPage; i++) {
|
||||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
pages.push(i);
|
||||||
<div>
|
}
|
||||||
<h1 className="text-2xl font-bold text-gray-900">Usuários</h1>
|
return pages;
|
||||||
<p className="text-sm text-gray-500">Gerencie usuários.</p>
|
};
|
||||||
</div>
|
|
||||||
<Link href="/manager/usuario/novo" className="w-full sm:w-auto">
|
|
||||||
<Button className="w-full sm:w-auto bg-green-600 hover:bg-green-700">
|
|
||||||
<Plus className="w-4 h-4 mr-2" /> Novo Usuário
|
|
||||||
</Button>
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Filtro e Itens por Página */}
|
const visiblePageNumbers = getVisiblePageNumbers(totalPages, currentPage);
|
||||||
<div className="flex flex-wrap items-center gap-3 bg-white p-4 rounded-lg border border-gray-200">
|
|
||||||
|
|
||||||
{/* Select de Filtro por Papel - Ajustado para resetar a página */}
|
return (
|
||||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
<Sidebar>
|
||||||
<span className="text-sm font-medium text-foreground">
|
<div className="space-y-6 px-2 sm:px-4 md:px-8">
|
||||||
Filtrar por papel
|
{/* Header */}
|
||||||
</span>
|
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||||
<Select
|
<div>
|
||||||
onValueChange={(value) => {
|
<h1 className="text-2xl font-bold text-gray-900">Usuários</h1>
|
||||||
setSelectedRole(value);
|
<p className="text-sm text-gray-500">Gerencie usuários.</p>
|
||||||
setCurrentPage(1); // Resetar para a primeira página ao mudar o filtro
|
</div>
|
||||||
|
<Link href="/manager/usuario/novo" className="w-full sm:w-auto">
|
||||||
|
<Button className="w-full sm:w-auto bg-blue-600 hover:bg-blue-700">
|
||||||
|
<Plus className="w-4 h-4 mr-2" /> Novo Usuário
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* --- 4. Filtro (Barra de Pesquisa + Selects) --- */}
|
||||||
|
<div className="flex flex-col md:flex-row items-start md:items-center gap-3 bg-white p-4 rounded-lg border border-gray-200">
|
||||||
|
|
||||||
|
{/* Barra de Pesquisa */}
|
||||||
|
<div className="relative w-full md:flex-1">
|
||||||
|
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
|
||||||
|
<Input
|
||||||
|
placeholder="Buscar por nome, e-mail ou telefone..."
|
||||||
|
value={searchTerm}
|
||||||
|
onChange={(e) => {
|
||||||
|
setSearchTerm(e.target.value);
|
||||||
|
setCurrentPage(1); // Reseta a paginação ao pesquisar
|
||||||
}}
|
}}
|
||||||
value={selectedRole}>
|
className="pl-10 w-full bg-gray-50 border-gray-200 focus:bg-white transition-colors"
|
||||||
|
/>
|
||||||
<SelectTrigger className="w-[180px]">
|
|
||||||
<SelectValue placeholder="Filtrar por papel" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="all">Todos</SelectItem>
|
|
||||||
<SelectItem value="admin">Admin</SelectItem>
|
|
||||||
<SelectItem value="gestor">Gestor</SelectItem>
|
|
||||||
<SelectItem value="medico">Médico</SelectItem>
|
|
||||||
<SelectItem value="secretaria">Secretária</SelectItem>
|
|
||||||
<SelectItem value="user">Usuário</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Select de Itens por Página */}
|
<div className="flex flex-wrap items-center gap-3 w-full md:w-auto">
|
||||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
{/* Select de Filtro por Papel */}
|
||||||
<span className="text-sm font-medium text-foreground">
|
<div className="flex items-center gap-2 w-full md:w-auto">
|
||||||
Itens por página
|
<Select
|
||||||
</span>
|
onValueChange={(value) => {
|
||||||
<Select
|
setSelectedRole(value);
|
||||||
onValueChange={handleItemsPerPageChange}
|
setCurrentPage(1);
|
||||||
defaultValue={String(itemsPerPage)}
|
}}
|
||||||
>
|
value={selectedRole}>
|
||||||
<SelectTrigger className="w-[140px]">
|
|
||||||
<SelectValue placeholder="Itens por pág." />
|
<SelectTrigger className="w-full sm:w-[150px]">
|
||||||
</SelectTrigger>
|
<SelectValue placeholder="Papel" />
|
||||||
<SelectContent>
|
</SelectTrigger>
|
||||||
<SelectItem value="5">5 por página</SelectItem>
|
<SelectContent>
|
||||||
<SelectItem value="10">10 por página</SelectItem>
|
<SelectItem value="all">Todos</SelectItem>
|
||||||
<SelectItem value="20">20 por página</SelectItem>
|
<SelectItem value="admin">Admin</SelectItem>
|
||||||
</SelectContent>
|
<SelectItem value="gestor">Gestor</SelectItem>
|
||||||
</Select>
|
<SelectItem value="medico">Médico</SelectItem>
|
||||||
|
<SelectItem value="secretaria">Secretária</SelectItem>
|
||||||
|
<SelectItem value="user">Usuário</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Select de Itens por Página */}
|
||||||
|
<div className="flex items-center gap-2 w-full md:w-auto">
|
||||||
|
<Select
|
||||||
|
onValueChange={handleItemsPerPageChange}
|
||||||
|
defaultValue={String(itemsPerPage)}
|
||||||
|
>
|
||||||
|
<SelectTrigger className="w-full sm:w-[80px]">
|
||||||
|
<SelectValue placeholder="10" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="5">5</SelectItem>
|
||||||
|
<SelectItem value="10">10</SelectItem>
|
||||||
|
<SelectItem value="20">20</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button variant="outline" className="ml-auto w-full md:w-auto hidden lg:flex">
|
||||||
|
<Filter className="w-4 h-4 mr-2" />
|
||||||
|
Filtros
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<Button variant="outline" className="ml-auto w-full md:w-auto">
|
|
||||||
<Filter className="w-4 h-4 mr-2" />
|
|
||||||
Filtro avançado
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
{/* Fim do Filtro e Itens por Página */}
|
{/* Fim do Filtro */}
|
||||||
|
|
||||||
{/* Tabela */}
|
{/* Tabela/Lista */}
|
||||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-x-auto">
|
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-x-auto">
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="p-8 text-center text-gray-500">
|
<div className="p-8 text-center text-gray-500">
|
||||||
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
|
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
|
||||||
Carregando usuários...
|
Carregando usuários...
|
||||||
</div>
|
|
||||||
) : error ? (
|
|
||||||
<div className="p-8 text-center text-red-600">{error}</div>
|
|
||||||
) : filteredUsers.length === 0 ? (
|
|
||||||
<div className="p-8 text-center text-gray-500">
|
|
||||||
Nenhum usuário encontrado com os filtros aplicados.
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<table className="min-w-full divide-y divide-gray-200">
|
|
||||||
<thead className="bg-gray-50 hidden md:table-header-group">
|
|
||||||
<tr>
|
|
||||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">ID</th>
|
|
||||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Nome</th>
|
|
||||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">E-mail</th>
|
|
||||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Telefone</th>
|
|
||||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Cargo</th>
|
|
||||||
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">Ações</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody className="bg-white divide-y divide-gray-200">
|
|
||||||
{/* Usando currentItems para a paginação */}
|
|
||||||
{currentItems.map((u) => (
|
|
||||||
<tr
|
|
||||||
key={u.id}
|
|
||||||
className="flex flex-col md:table-row md:flex-row border-b md:border-0 hover:bg-gray-50"
|
|
||||||
>
|
|
||||||
<td className="px-6 py-4 text-sm text-gray-500 break-all md:whitespace-nowrap">
|
|
||||||
{u.id}
|
|
||||||
</td>
|
|
||||||
<td className="px-6 py-4 text-sm text-gray-900">
|
|
||||||
{u.full_name}
|
|
||||||
</td>
|
|
||||||
<td className="px-6 py-4 text-sm text-gray-500 break-all">
|
|
||||||
{u.email}
|
|
||||||
</td>
|
|
||||||
<td className="px-6 py-4 text-sm text-gray-500">
|
|
||||||
{u.phone}
|
|
||||||
</td>
|
|
||||||
<td className="px-6 py-4 text-sm text-gray-500 capitalize">
|
|
||||||
{u.role}
|
|
||||||
</td>
|
|
||||||
<td className="px-6 py-4 text-right">
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="icon"
|
|
||||||
onClick={() => openDetailsDialog(u)}
|
|
||||||
title="Visualizar"
|
|
||||||
>
|
|
||||||
<Eye className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
))}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
{/* Paginação ATUALIZADA */}
|
|
||||||
{totalPages > 1 && (
|
|
||||||
<div className="flex flex-wrap justify-center items-center gap-2 mt-4 p-4 border-t border-gray-200">
|
|
||||||
|
|
||||||
{/* Botão Anterior */}
|
|
||||||
<button
|
|
||||||
onClick={goToPrevPage}
|
|
||||||
disabled={currentPage === 1}
|
|
||||||
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300"
|
|
||||||
>
|
|
||||||
{"< Anterior"}
|
|
||||||
</button>
|
|
||||||
|
|
||||||
{/* Números das Páginas */}
|
|
||||||
{visiblePageNumbers.map((number) => (
|
|
||||||
<button
|
|
||||||
key={number}
|
|
||||||
onClick={() => paginate(number)}
|
|
||||||
className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border border-gray-300 ${currentPage === number
|
|
||||||
? "bg-green-600 text-white shadow-md border-green-600"
|
|
||||||
: "bg-gray-100 text-gray-700 hover:bg-gray-200"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{number}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
|
|
||||||
{/* Botão Próximo */}
|
|
||||||
<button
|
|
||||||
onClick={goToNextPage}
|
|
||||||
disabled={currentPage === totalPages}
|
|
||||||
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300"
|
|
||||||
>
|
|
||||||
{"Próximo >"}
|
|
||||||
</button>
|
|
||||||
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{/* Fim da Paginação ATUALIZADA */}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Modal de Detalhes */}
|
|
||||||
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
|
||||||
<AlertDialogContent>
|
|
||||||
<AlertDialogHeader>
|
|
||||||
<AlertDialogTitle className="text-2xl">
|
|
||||||
{userDetails?.profile?.full_name || "Detalhes do Usuário"}
|
|
||||||
</AlertDialogTitle>
|
|
||||||
<AlertDialogDescription>
|
|
||||||
{!userDetails ? (
|
|
||||||
<div className="p-4 text-center text-gray-500">
|
|
||||||
<Loader2 className="w-6 h-6 animate-spin mx-auto mb-3 text-green-600" />
|
|
||||||
Buscando dados completos...
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="space-y-3 pt-2 text-left text-gray-700">
|
|
||||||
<div>
|
|
||||||
<strong>ID:</strong> {userDetails.user.id}
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<strong>E-mail:</strong> {userDetails.user.email}
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<strong>Nome completo:</strong>{" "}
|
|
||||||
{userDetails.profile.full_name}
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<strong>Telefone:</strong> {userDetails.profile.phone}
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<strong>Roles:</strong>{" "}
|
|
||||||
{userDetails.roles?.join(", ")}
|
|
||||||
</div>
|
|
||||||
{/* Melhoria na visualização das permissões no modal */}
|
|
||||||
<div className="pt-2">
|
|
||||||
<strong className="block mb-1">Permissões:</strong>
|
|
||||||
<ul className="list-disc list-inside space-y-0.5 text-sm">
|
|
||||||
{Object.entries(
|
|
||||||
userDetails.permissions || {}
|
|
||||||
).map(([k, v]) => (
|
|
||||||
<li key={k}>
|
|
||||||
{k}: <span className={`font-semibold ${v ? 'text-green-600' : 'text-red-600'}`}>{v ? "Sim" : "Não"}</span>
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</AlertDialogDescription>
|
|
||||||
</AlertDialogHeader>
|
|
||||||
<AlertDialogFooter>
|
|
||||||
<AlertDialogCancel>Fechar</AlertDialogCancel>
|
|
||||||
</AlertDialogFooter>
|
|
||||||
</AlertDialogContent>
|
|
||||||
</AlertDialog>
|
|
||||||
</div>
|
</div>
|
||||||
</ManagerLayout>
|
) : error ? (
|
||||||
);
|
<div className="p-8 text-center text-red-600">{error}</div>
|
||||||
}
|
) : filteredUsers.length === 0 ? (
|
||||||
|
<div className="p-8 text-center text-gray-500">
|
||||||
|
Nenhum usuário encontrado com os filtros aplicados.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{/* Tabela para Telas Médias e Grandes */}
|
||||||
|
<table className="min-w-full divide-y divide-gray-200 hidden md:table">
|
||||||
|
<thead className="bg-gray-50">
|
||||||
|
<tr>
|
||||||
|
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
|
||||||
|
Nome
|
||||||
|
</th>
|
||||||
|
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
|
||||||
|
E-mail
|
||||||
|
</th>
|
||||||
|
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
|
||||||
|
Telefone
|
||||||
|
</th>
|
||||||
|
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
|
||||||
|
Cargo
|
||||||
|
</th>
|
||||||
|
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">
|
||||||
|
Ações
|
||||||
|
</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="bg-white divide-y divide-gray-200">
|
||||||
|
{currentItems.map((u) => (
|
||||||
|
<tr key={u.id} className="hover:bg-gray-50">
|
||||||
|
<td className="px-6 py-4 text-sm text-gray-900">
|
||||||
|
{u.full_name}
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-4 text-sm text-gray-500 break-all">
|
||||||
|
{u.email}
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-4 text-sm text-gray-500">
|
||||||
|
{u.phone}
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-4 text-sm text-gray-500 capitalize">
|
||||||
|
{u.role}
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-4 text-right">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => openDetailsDialog(u)}
|
||||||
|
title="Visualizar"
|
||||||
|
>
|
||||||
|
<Eye className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
{/* Layout em Cards/Lista para Telas Pequenas */}
|
||||||
|
<div className="md:hidden divide-y divide-gray-200">
|
||||||
|
{currentItems.map((u) => (
|
||||||
|
<div key={u.id} className="flex items-center justify-between p-4 hover:bg-gray-50">
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="text-sm font-medium text-gray-900 truncate">
|
||||||
|
{u.full_name || "—"}
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-gray-500 truncate">
|
||||||
|
{u.email}
|
||||||
|
</div>
|
||||||
|
<div className="text-sm text-gray-500 capitalize mt-1">
|
||||||
|
{u.role || "—"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="ml-4 flex-shrink-0">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => openDetailsDialog(u)}
|
||||||
|
title="Visualizar"
|
||||||
|
>
|
||||||
|
<Eye className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Paginação */}
|
||||||
|
{totalPages > 1 && (
|
||||||
|
<div className="flex flex-wrap justify-center items-center gap-2 mt-4 p-4 border-t border-gray-200">
|
||||||
|
{/* Botão Anterior */}
|
||||||
|
<button
|
||||||
|
onClick={goToPrevPage}
|
||||||
|
disabled={currentPage === 1}
|
||||||
|
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300"
|
||||||
|
>
|
||||||
|
{"< Anterior"}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{/* Números das Páginas */}
|
||||||
|
{visiblePageNumbers.map((number) => (
|
||||||
|
<button
|
||||||
|
key={number}
|
||||||
|
onClick={() => paginate(number)}
|
||||||
|
className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border border-gray-300 ${
|
||||||
|
currentPage === number
|
||||||
|
? "bg-blue-600 text-white shadow-md border-blue-600"
|
||||||
|
: "bg-gray-100 text-gray-700 hover:bg-gray-200"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{number}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{/* Botão Próximo */}
|
||||||
|
<button
|
||||||
|
onClick={goToNextPage}
|
||||||
|
disabled={currentPage === totalPages}
|
||||||
|
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300"
|
||||||
|
>
|
||||||
|
{"Próximo >"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Modal de Detalhes */}
|
||||||
|
<AlertDialog
|
||||||
|
open={detailsDialogOpen}
|
||||||
|
onOpenChange={setDetailsDialogOpen}
|
||||||
|
>
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle className="text-2xl">
|
||||||
|
{userDetails?.profile?.full_name || "Detalhes do Usuário"}
|
||||||
|
</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>
|
||||||
|
{!userDetails ? (
|
||||||
|
<div className="p-4 text-center text-gray-500">
|
||||||
|
<Loader2 className="w-6 h-6 animate-spin mx-auto mb-3 text-green-600" />
|
||||||
|
Buscando dados completos...
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-3 pt-2 text-left text-gray-700">
|
||||||
|
<div>
|
||||||
|
<strong>ID:</strong> {userDetails.user.id}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<strong>E-mail:</strong> {userDetails.user.email}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<strong>Nome completo:</strong>{" "}
|
||||||
|
{userDetails.profile.full_name}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<strong>Telefone:</strong> {userDetails.profile.phone}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<strong>Roles:</strong> {userDetails.roles?.join(", ")}
|
||||||
|
</div>
|
||||||
|
<div className="pt-2">
|
||||||
|
<strong className="block mb-1">Permissões:</strong>
|
||||||
|
<ul className="list-disc list-inside space-y-0.5 text-sm">
|
||||||
|
{Object.entries(userDetails.permissions || {}).map(
|
||||||
|
([k, v]) => (
|
||||||
|
<li key={k}>
|
||||||
|
{k}:{" "}
|
||||||
|
<span
|
||||||
|
className={`font-semibold ${
|
||||||
|
v ? "text-green-600" : "text-red-600"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{v ? "Sim" : "Não"}
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
)
|
||||||
|
)}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>Fechar</AlertDialogCancel>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
</div>
|
||||||
|
</Sidebar>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
263
app/page.tsx
@ -1,112 +1,209 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import Link from "next/link"
|
import Link from "next/link";
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { Stethoscope, Baby, Microscope } from "lucide-react";
|
||||||
|
|
||||||
export default function InicialPage() {
|
export default function InicialPage() {
|
||||||
return (
|
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||||
<div className="min-h-screen flex flex-col bg-background">
|
|
||||||
{}
|
|
||||||
<div className="bg-primary text-primary-foreground text-sm py-2 px-6 flex justify-between">
|
|
||||||
<span> Horário: 08h00 - 21h00</span>
|
|
||||||
<span> Email: contato@mediconnect.com</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{}
|
return (
|
||||||
<header className="bg-card shadow-md py-4 px-6 flex justify-between items-center">
|
<div className="min-h-screen flex flex-col bg-white font-sans scroll-smooth text-[#1E2A78]">
|
||||||
<h1 className="text-2xl font-bold text-primary">MediConnect</h1>
|
{/* Barra superior */}
|
||||||
<nav className="flex space-x-6 text-muted-foreground font-medium">
|
<div className="bg-[#1E2A78] text-white text-sm py-2 px-4 md:px-6 flex justify-between items-center">
|
||||||
<Link href="/cadastro" className="hover:text-primary"> Home</Link>
|
<span className="hidden sm:inline">Horário: 08h00 - 21h00</span>
|
||||||
<a href="#about" className="hover:text-primary">Sobre</a>
|
<span className="hover:underline cursor-pointer transition">
|
||||||
<a href="#departments" className="hover:text-primary">Departamentos</a>
|
Email: contato@mediconnect.com
|
||||||
<a href="#doctors" className="hover:text-primary">Médicos</a>
|
</span>
|
||||||
<a href="#contact" className="hover:text-primary">Contato</a>
|
</div>
|
||||||
|
{/* Header */}
|
||||||
|
<header className="bg-white shadow-md py-4 px-4 md:px-6 flex justify-between items-center relative sticky top-0 z-50 backdrop-blur-md">
|
||||||
|
<a href="#home" className="flex items-center space-x-2 cursor-pointer">
|
||||||
|
<img
|
||||||
|
src="/android-chrome-512x512.png"
|
||||||
|
alt="Logo MediConnect"
|
||||||
|
className="w-20 h-20 object-contain transition-transform hover:scale-105"
|
||||||
|
/>
|
||||||
|
<h1 className="text-2xl font-extrabold text-[#1E2A78] tracking-tight">
|
||||||
|
MedConnect
|
||||||
|
</h1>
|
||||||
|
</a>
|
||||||
|
|
||||||
|
{/* Menu Mobile */}
|
||||||
|
<div className="md:hidden flex items-center space-x-4">
|
||||||
|
<Link href="/login">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="rounded-full px-4 py-2 text-sm border-2 border-[#007BFF] text-[#007BFF] hover:bg-[#007BFF] hover:text-white transition"
|
||||||
|
>
|
||||||
|
Login
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
<button
|
||||||
|
onClick={() => setIsMenuOpen(!isMenuOpen)}
|
||||||
|
className="text-[#1E2A78] focus:outline-none"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
className="w-6 h-6"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
>
|
||||||
|
{isMenuOpen ? (
|
||||||
|
<path
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
strokeWidth="2"
|
||||||
|
d="M6 18L18 6M6 6l12 12"
|
||||||
|
></path>
|
||||||
|
) : (
|
||||||
|
<path
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
strokeWidth="2"
|
||||||
|
d="M4 6h16M4 12h16M4 18h16"
|
||||||
|
></path>
|
||||||
|
)}
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Navegação */}
|
||||||
|
<nav
|
||||||
|
className={`${
|
||||||
|
isMenuOpen ? "block" : "hidden"
|
||||||
|
} absolute top-[76px] left-0 w-full bg-white shadow-md py-4 md:relative md:top-auto md:left-auto md:w-auto md:block md:bg-transparent md:shadow-none transition-all duration-300 z-10`}
|
||||||
|
>
|
||||||
|
<div className="flex flex-col md:flex-row space-y-4 md:space-y-0 md:space-x-8 text-gray-600 font-medium items-center">
|
||||||
|
<Link href="#home" className="hover:text-[#007BFF] transition">
|
||||||
|
Home
|
||||||
|
</Link>
|
||||||
|
<a href="#about" className="hover:text-[#007BFF] transition">
|
||||||
|
Sobre
|
||||||
|
</a>
|
||||||
|
<a href="#departments" className="hover:text-[#007BFF] transition">
|
||||||
|
Departamentos
|
||||||
|
</a>
|
||||||
|
<a href="#doctors" className="hover:text-[#007BFF] transition">
|
||||||
|
Médicos
|
||||||
|
</a>
|
||||||
|
<a href="#contact" className="hover:text-[#007BFF] transition">
|
||||||
|
Contato
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
</nav>
|
</nav>
|
||||||
<div className="flex space-x-4">
|
|
||||||
{}
|
{/* Login Desktop */}
|
||||||
<Link href="/login">
|
<div className="hidden md:flex space-x-4">
|
||||||
<Button
|
<Link href="/login">
|
||||||
variant="outline"
|
<Button
|
||||||
className="rounded-full px-6 py-2 border-2 transition cursor-pointer"
|
variant="outline"
|
||||||
>
|
className="rounded-full px-6 py-2 border-2 border-[#007BFF] text-[#007BFF] hover:bg-[#007BFF] hover:text-white transition cursor-pointer"
|
||||||
Login
|
>
|
||||||
</Button>
|
Login
|
||||||
</Link>
|
</Button>
|
||||||
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
{/* Hero Section */}
|
||||||
{}
|
<section className="flex flex-col md:flex-row items-center justify-between px-6 md:px-10 lg:px-20 py-20 bg-gradient-to-r from-[#1E2A78] via-[#007BFF] to-[#00BFFF] text-white">
|
||||||
<section className="flex flex-col md:flex-row items-center justify-between px-10 md:px-20 py-16 bg-background">
|
<div className="max-w-lg mx-auto md:mx-0">
|
||||||
<div className="max-w-lg">
|
<h2 className="uppercase text-sm tracking-widest opacity-80">
|
||||||
<h2 className="text-muted-foreground uppercase text-sm">Bem-vindo à Saúde Digital</h2>
|
Bem-vindo à Saúde Digital
|
||||||
<h1 className="text-4xl font-extrabold text-foreground leading-tight mt-2">
|
</h2>
|
||||||
|
<h1 className="text-4xl sm:text-5xl lg:text-6xl font-extrabold leading-tight mt-2 drop-shadow-lg">
|
||||||
Soluções Médicas <br /> & Cuidados com a Saúde
|
Soluções Médicas <br /> & Cuidados com a Saúde
|
||||||
</h1>
|
</h1>
|
||||||
<p className="text-muted-foreground mt-4">
|
<p className="mt-4 text-base leading-relaxed opacity-90">
|
||||||
Excelência em saúde há mais de 25 anos. Atendimento médicio com qualidade,segurança e carinho.
|
Excelência em saúde há mais de 25 anos. Atendimento médico com
|
||||||
|
qualidade, segurança e carinho.
|
||||||
</p>
|
</p>
|
||||||
<div className="mt-6 flex space-x-4">
|
<div className="mt-8 flex flex-col sm:flex-row space-y-4 sm:space-y-0 sm:space-x-4 justify-center md:justify-start">
|
||||||
<Button>
|
<Button className="px-8 py-3 text-base font-semibold bg-white text-[#1E2A78] hover:bg-[#EAF4FF] transition-all shadow-md">
|
||||||
Nossos Serviços
|
Nossos Serviços
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button className="px-8 py-3 text-base font-semibold bg-white text-[#1E2A78] hover:bg-[#EAF4FF] transition-all shadow-md">
|
||||||
variant="secondary"
|
|
||||||
>
|
|
||||||
Saiba Mais
|
Saiba Mais
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-10 md:mt-0">
|
<div className="mt-10 md:mt-0 flex justify-center">
|
||||||
<img
|
<img
|
||||||
src="https://t4.ftcdn.net/jpg/03/20/52/31/360_F_320523164_tx7Rdd7I2XDTvvKfz2oRuRpKOPE5z0ni.jpg"
|
src="https://t4.ftcdn.net/jpg/03/20/52/31/360_F_320523164_tx7Rdd7I2XDTvvKfz2oRuRpKOPE5z0ni.jpg"
|
||||||
alt="Médico"
|
alt="Médico"
|
||||||
className="w-80"
|
className="w-72 sm:w-96 lg:w-[28rem] h-auto object-cover rounded-2xl shadow-xl "
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
{/* Serviços */}
|
||||||
|
<section
|
||||||
|
id="departments"
|
||||||
|
className="py-20 px-6 md:px-10 lg:px-20 bg-[#F8FBFF]"
|
||||||
|
>
|
||||||
|
<h2 className="text-center text-3xl sm:text-4xl font-extrabold text-[#1E2A78]">
|
||||||
|
Cuidados completos para a sua saúde
|
||||||
|
</h2>
|
||||||
|
<p className="text-center text-gray-600 mt-3 text-base">
|
||||||
|
Serviços médicos que oferecemos
|
||||||
|
</p>
|
||||||
|
|
||||||
{}
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-10 mt-12 max-w-6xl mx-auto">
|
||||||
<section className="py-16 px-10 md:px-20 bg-card">
|
{/* Card */}
|
||||||
<h2 className="text-center text-3xl font-bold text-foreground">Cuidados completos para a sua saúde</h2>
|
{[
|
||||||
<p className="text-center text-muted-foreground mt-2">Serviços médicos que oferecemos</p>
|
{
|
||||||
|
title: "Clínica Geral",
|
||||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-8 mt-10">
|
desc: "Seu primeiro passo para o cuidado. Atendimento focado na prevenção e no diagnóstico inicial.",
|
||||||
<div className="p-6 bg-background rounded-xl shadow hover:shadow-lg transition">
|
Icon: Stethoscope,
|
||||||
<h3 className="text-xl font-semibold text-primary">Clínica Geral</h3>
|
},
|
||||||
<p className="text-muted-foreground mt-2">
|
{
|
||||||
Seu primeiro passo para o cuidado. Atendimento focado na prevenção e no diagnóstico inicial.
|
title: "Pediatria",
|
||||||
</p>
|
desc: "Cuidado gentil e especializado para garantir a saúde e o desenvolvimento de crianças e adolescentes.",
|
||||||
<Button className="mt-4">
|
Icon: Baby,
|
||||||
Agendar
|
},
|
||||||
</Button>
|
{
|
||||||
</div>
|
title: "Exames",
|
||||||
<div className="p-6 bg-background rounded-xl shadow hover:shadow-lg transition">
|
desc: "Resultados rápidos e precisos em exames laboratoriais e de imagem essenciais para seu diagnóstico.",
|
||||||
<h3 className="text-xl font-semibold text-primary">Pediatria</h3>
|
Icon: Microscope,
|
||||||
<p className="text-muted-foreground mt-2">
|
},
|
||||||
Cuidado gentil e especializado para garantir a saúde e o desenvolvimeto de crianças e adolescentes.
|
].map(({ title, desc, Icon }, index) => (
|
||||||
</p>
|
<div
|
||||||
<Button className="mt-4">
|
key={index}
|
||||||
Agendar
|
className="p-8 bg-white rounded-2xl shadow-md hover:shadow-xl transition-all duration-300 border border-[#E0E9FF] group"
|
||||||
</Button>
|
>
|
||||||
</div>
|
<div className="flex items-center space-x-3">
|
||||||
<div className="p-6 bg-background rounded-xl shadow hover:shadow-lg transition">
|
<Icon className="text-[#007BFF] w-6 h-6 group-hover:scale-110 transition-transform" />
|
||||||
<h3 className="text-xl font-semibold text-primary">Exames</h3>
|
<h3 className="text-xl font-semibold">{title}</h3>
|
||||||
<p className="text-muted-foreground mt-2">
|
</div>
|
||||||
Resultados rápidos e precisos em exames laboratoriais e de imagem essenciais para seu diagnóstico.
|
<p className="text-gray-600 mt-3 text-sm leading-relaxed">
|
||||||
</p>
|
{desc}
|
||||||
<Button className="mt-4">
|
</p>
|
||||||
Agendar
|
<Button className="mt-6 w-full bg-[#007BFF] hover:bg-[#005FCC] text-white transition">
|
||||||
</Button>
|
Agendar
|
||||||
</div>
|
</Button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
{/* Footer */}
|
||||||
{}
|
<footer className="bg-[#1E2A78] text-white py-8 text-center text-sm">
|
||||||
<footer className="bg-primary text-primary-foreground py-6 text-center">
|
<div className="space-y-2">
|
||||||
<p>© 2025 MediConnect</p>
|
<p>© 2025 MediConnect — Todos os direitos reservados</p>
|
||||||
|
<div className="flex justify-center space-x-6 opacity-80">
|
||||||
|
<a href="#about" className="hover:text-[#00BFFF] transition">
|
||||||
|
Sobre
|
||||||
|
</a>
|
||||||
|
<a href="#departments" className="hover:text-[#00BFFF] transition">
|
||||||
|
Serviços
|
||||||
|
</a>
|
||||||
|
<a href="#contact" className="hover:text-[#00BFFF] transition">
|
||||||
|
Contato
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,7 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import PatientLayout from "@/components/patient-layout";
|
|
||||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
@ -10,6 +9,7 @@ import { toast } from "sonner";
|
|||||||
|
|
||||||
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
||||||
import { usersService } from "@/services/usersApi.mjs";
|
import { usersService } from "@/services/usersApi.mjs";
|
||||||
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
// Tipagem correta para o usuário
|
// Tipagem correta para o usuário
|
||||||
interface UserProfile {
|
interface UserProfile {
|
||||||
@ -129,7 +129,7 @@ export default function PatientAppointmentsPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PatientLayout>
|
<Sidebar>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="flex justify-between items-center">
|
<div className="flex justify-between items-center">
|
||||||
<div>
|
<div>
|
||||||
@ -185,6 +185,6 @@ export default function PatientAppointmentsPage() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</PatientLayout>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,22 +1,32 @@
|
|||||||
import PatientLayout from "@/components/patient-layout"
|
import {
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
Card,
|
||||||
import { Button } from "@/components/ui/button"
|
CardContent,
|
||||||
import { Calendar, Clock, User, Plus } from "lucide-react"
|
CardDescription,
|
||||||
import Link from "next/link"
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from "@/components/ui/card";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Calendar, Clock, User, Plus } from "lucide-react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
export default function PatientDashboard() {
|
export default function PatientDashboard() {
|
||||||
return (
|
return (
|
||||||
<PatientLayout>
|
<Sidebar>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
|
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
|
||||||
<p className="text-gray-600">Bem-vindo ao seu portal de consultas médicas</p>
|
<p className="text-gray-600">
|
||||||
|
Bem-vindo ao seu portal de consultas médicas
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||||
<CardTitle className="text-sm font-medium">Próxima Consulta</CardTitle>
|
<CardTitle className="text-sm font-medium">
|
||||||
|
Próxima Consulta
|
||||||
|
</CardTitle>
|
||||||
<Calendar className="h-4 w-4 text-muted-foreground" />
|
<Calendar className="h-4 w-4 text-muted-foreground" />
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
@ -27,12 +37,16 @@ export default function PatientDashboard() {
|
|||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||||
<CardTitle className="text-sm font-medium">Consultas Este Mês</CardTitle>
|
<CardTitle className="text-sm font-medium">
|
||||||
|
Consultas Este Mês
|
||||||
|
</CardTitle>
|
||||||
<Clock className="h-4 w-4 text-muted-foreground" />
|
<Clock className="h-4 w-4 text-muted-foreground" />
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div className="text-2xl font-bold">3</div>
|
<div className="text-2xl font-bold">3</div>
|
||||||
<p className="text-xs text-muted-foreground">2 realizadas, 1 agendada</p>
|
<p className="text-xs text-muted-foreground">
|
||||||
|
2 realizadas, 1 agendada
|
||||||
|
</p>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
@ -52,23 +66,31 @@ export default function PatientDashboard() {
|
|||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Ações Rápidas</CardTitle>
|
<CardTitle>Ações Rápidas</CardTitle>
|
||||||
<CardDescription>Acesse rapidamente as principais funcionalidades</CardDescription>
|
<CardDescription>
|
||||||
|
Acesse rapidamente as principais funcionalidades
|
||||||
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-4">
|
<CardContent className="space-y-4">
|
||||||
<Link href="/patient/schedule">
|
<Link href="/patient/schedule">
|
||||||
<Button className="w-full justify-start">
|
<Button className="w-full justify-start bg-blue-600 text-white hover:bg-blue-700">
|
||||||
<Plus className="mr-2 h-4 w-4" />
|
<User className="mr-2 h-4 w-4 text-white" />
|
||||||
Agendar Nova Consulta
|
Agendar Nova Consulta
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
<Link href="/patient/appointments">
|
<Link href="/patient/appointments">
|
||||||
<Button variant="outline" className="w-full justify-start bg-transparent">
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="w-full justify-start bg-transparent"
|
||||||
|
>
|
||||||
<Calendar className="mr-2 h-4 w-4" />
|
<Calendar className="mr-2 h-4 w-4" />
|
||||||
Ver Minhas Consultas
|
Ver Minhas Consultas
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
<Link href="/patient/profile">
|
<Link href="/patient/profile">
|
||||||
<Button variant="outline" className="w-full justify-start bg-transparent">
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="w-full justify-start bg-transparent"
|
||||||
|
>
|
||||||
<User className="mr-2 h-4 w-4" />
|
<User className="mr-2 h-4 w-4" />
|
||||||
Atualizar Dados
|
Atualizar Dados
|
||||||
</Button>
|
</Button>
|
||||||
@ -108,6 +130,6 @@ export default function PatientDashboard() {
|
|||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</PatientLayout>
|
</Sidebar>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,56 +1,166 @@
|
|||||||
"use client"
|
// ARQUIVO COMPLETO PARA: app/patient/profile/page.tsx
|
||||||
|
|
||||||
import { useState, useEffect } from "react"
|
"use client";
|
||||||
import PatientLayout from "@/components/patient-layout"
|
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
|
||||||
import { Button } from "@/components/ui/button"
|
|
||||||
import { Input } from "@/components/ui/input"
|
|
||||||
import { Label } from "@/components/ui/label"
|
|
||||||
import { Textarea } from "@/components/ui/textarea"
|
|
||||||
import { User, Mail, Phone, Calendar, FileText } from "lucide-react"
|
|
||||||
|
|
||||||
interface PatientData {
|
import { useState, useEffect, useRef } from "react";
|
||||||
name: string
|
import Sidebar from "@/components/Sidebar";
|
||||||
email: string
|
import { useAuthLayout } from "@/hooks/useAuthLayout";
|
||||||
phone: string
|
import { patientsService } from "@/services/patientsApi.mjs";
|
||||||
cpf: string
|
import { api } from "@/services/api.mjs";
|
||||||
birthDate: string
|
|
||||||
address: string
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
|
import { User, Mail, Phone, Calendar, Upload } from "lucide-react";
|
||||||
|
import { toast } from "@/hooks/use-toast";
|
||||||
|
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||||
|
|
||||||
|
interface PatientProfileData {
|
||||||
|
name: string;
|
||||||
|
email: string;
|
||||||
|
phone: string;
|
||||||
|
cpf: string;
|
||||||
|
birthDate: string;
|
||||||
|
cep: string;
|
||||||
|
street: string;
|
||||||
|
number: string;
|
||||||
|
city: string;
|
||||||
|
avatarFullUrl?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function PatientProfile() {
|
export default function PatientProfile() {
|
||||||
const [patientData, setPatientData] = useState<PatientData>({
|
const { user, isLoading: isAuthLoading } = useAuthLayout({
|
||||||
name: "",
|
requiredRole: ["paciente", "admin", "medico", "gestor", "secretaria"],
|
||||||
email: "",
|
});
|
||||||
phone: "",
|
const [patientData, setPatientData] = useState<PatientProfileData | null>(
|
||||||
cpf: "",
|
null
|
||||||
birthDate: "",
|
);
|
||||||
address: "",
|
const [isEditing, setIsEditing] = useState(false);
|
||||||
})
|
const [isSaving, setIsSaving] = useState(false);
|
||||||
const [isEditing, setIsEditing] = useState(false)
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const data = localStorage.getItem("patientData")
|
if (user?.id) {
|
||||||
if (data) {
|
const fetchPatientDetails = async () => {
|
||||||
setPatientData(JSON.parse(data))
|
try {
|
||||||
|
const patientDetails = await patientsService.getById(user.id);
|
||||||
|
setPatientData({
|
||||||
|
name: patientDetails.full_name || user.name,
|
||||||
|
email: user.email,
|
||||||
|
phone: patientDetails.phone_mobile || "",
|
||||||
|
cpf: patientDetails.cpf || "",
|
||||||
|
birthDate: patientDetails.birth_date || "",
|
||||||
|
cep: patientDetails.cep || "",
|
||||||
|
street: patientDetails.street || "",
|
||||||
|
number: patientDetails.number || "",
|
||||||
|
city: patientDetails.city || "",
|
||||||
|
avatarFullUrl: user.avatarFullUrl,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Erro ao buscar detalhes do paciente:", error);
|
||||||
|
toast({
|
||||||
|
title: "Erro",
|
||||||
|
description: "Não foi possível carregar seus dados completos.",
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
fetchPatientDetails();
|
||||||
}
|
}
|
||||||
}, [])
|
}, [user]);
|
||||||
|
|
||||||
const handleSave = () => {
|
const handleInputChange = (
|
||||||
localStorage.setItem("patientData", JSON.stringify(patientData))
|
field: keyof PatientProfileData,
|
||||||
setIsEditing(false)
|
value: string
|
||||||
alert("Dados atualizados com sucesso!")
|
) => {
|
||||||
}
|
setPatientData((prev) => (prev ? { ...prev, [field]: value } : null));
|
||||||
|
};
|
||||||
|
|
||||||
const handleInputChange = (field: keyof PatientData, value: string) => {
|
const handleSave = async () => {
|
||||||
setPatientData((prev) => ({
|
if (!patientData || !user) return;
|
||||||
...prev,
|
setIsSaving(true);
|
||||||
[field]: value,
|
try {
|
||||||
}))
|
const patientPayload = {
|
||||||
|
full_name: patientData.name,
|
||||||
|
cpf: patientData.cpf,
|
||||||
|
birth_date: patientData.birthDate,
|
||||||
|
phone_mobile: patientData.phone,
|
||||||
|
cep: patientData.cep,
|
||||||
|
street: patientData.street,
|
||||||
|
number: patientData.number,
|
||||||
|
city: patientData.city,
|
||||||
|
};
|
||||||
|
await patientsService.update(user.id, patientPayload);
|
||||||
|
toast({
|
||||||
|
title: "Sucesso!",
|
||||||
|
description: "Seus dados foram atualizados.",
|
||||||
|
});
|
||||||
|
setIsEditing(false);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Erro ao salvar dados:", error);
|
||||||
|
toast({
|
||||||
|
title: "Erro",
|
||||||
|
description: "Não foi possível salvar suas alterações.",
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setIsSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAvatarClick = () => {
|
||||||
|
fileInputRef.current?.click();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAvatarUpload = async (
|
||||||
|
event: React.ChangeEvent<HTMLInputElement>
|
||||||
|
) => {
|
||||||
|
const file = event.target.files?.[0];
|
||||||
|
if (!file || !user) return;
|
||||||
|
|
||||||
|
const fileExt = file.name.split(".").pop();
|
||||||
|
|
||||||
|
// *** A CORREÇÃO ESTÁ AQUI ***
|
||||||
|
// O caminho salvo no banco de dados não deve conter o nome do bucket.
|
||||||
|
const filePath = `${user.id}/avatar.${fileExt}`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await api.storage.upload("avatars", filePath, file);
|
||||||
|
await api.patch(`/rest/v1/profiles?id=eq.${user.id}`, {
|
||||||
|
avatar_url: filePath,
|
||||||
|
});
|
||||||
|
|
||||||
|
const newFullUrl = `https://yuanqfswhberkoevtmfr.supabase.co/storage/v1/object/public/avatars/${filePath}?t=${new Date().getTime()}`;
|
||||||
|
setPatientData((prev) =>
|
||||||
|
prev ? { ...prev, avatarFullUrl: newFullUrl } : null
|
||||||
|
);
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: "Sucesso!",
|
||||||
|
description: "Sua foto de perfil foi atualizada.",
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Erro no upload do avatar:", error);
|
||||||
|
toast({
|
||||||
|
title: "Erro de Upload",
|
||||||
|
description: "Não foi possível enviar sua foto.",
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isAuthLoading || !patientData) {
|
||||||
|
return (
|
||||||
|
<Sidebar>
|
||||||
|
<div>Carregando seus dados...</div>
|
||||||
|
</Sidebar>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PatientLayout>
|
<Sidebar>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="flex justify-between items-center">
|
<div className="flex justify-between items-center">
|
||||||
<div>
|
<div>
|
||||||
@ -59,9 +169,14 @@ export default function PatientProfile() {
|
|||||||
</div>
|
</div>
|
||||||
<Button
|
<Button
|
||||||
onClick={() => (isEditing ? handleSave() : setIsEditing(true))}
|
onClick={() => (isEditing ? handleSave() : setIsEditing(true))}
|
||||||
variant={isEditing ? "default" : "outline"}
|
disabled={isSaving}
|
||||||
|
className="bg-blue-600 hover:bg-blue-700 text-white"
|
||||||
>
|
>
|
||||||
{isEditing ? "Salvar Alterações" : "Editar Dados"}
|
{isEditing
|
||||||
|
? isSaving
|
||||||
|
? "Salvando..."
|
||||||
|
: "Salvar Alterações"
|
||||||
|
: "Editar Dados"}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@ -73,20 +188,21 @@ export default function PatientProfile() {
|
|||||||
<User className="mr-2 h-5 w-5" />
|
<User className="mr-2 h-5 w-5" />
|
||||||
Informações Pessoais
|
Informações Pessoais
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
<CardDescription>Seus dados pessoais básicos</CardDescription>
|
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-4">
|
<CardContent className="space-y-4">
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
<div className="grid md:grid-cols-2 gap-4">
|
||||||
<div className="space-y-2">
|
<div>
|
||||||
<Label htmlFor="name">Nome Completo</Label>
|
<Label htmlFor="name">Nome Completo</Label>
|
||||||
<Input
|
<Input
|
||||||
id="name"
|
id="name"
|
||||||
value={patientData.name}
|
value={patientData.name}
|
||||||
onChange={(e) => handleInputChange("name", e.target.value)}
|
onChange={(e) =>
|
||||||
|
handleInputChange("name", e.target.value)
|
||||||
|
}
|
||||||
disabled={!isEditing}
|
disabled={!isEditing}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
<div>
|
||||||
<Label htmlFor="cpf">CPF</Label>
|
<Label htmlFor="cpf">CPF</Label>
|
||||||
<Input
|
<Input
|
||||||
id="cpf"
|
id="cpf"
|
||||||
@ -96,60 +212,95 @@ export default function PatientProfile() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div>
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="birthDate">Data de Nascimento</Label>
|
<Label htmlFor="birthDate">Data de Nascimento</Label>
|
||||||
<Input
|
<Input
|
||||||
id="birthDate"
|
id="birthDate"
|
||||||
type="date"
|
type="date"
|
||||||
value={patientData.birthDate}
|
value={patientData.birthDate}
|
||||||
onChange={(e) => handleInputChange("birthDate", e.target.value)}
|
onChange={(e) =>
|
||||||
|
handleInputChange("birthDate", e.target.value)
|
||||||
|
}
|
||||||
disabled={!isEditing}
|
disabled={!isEditing}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="flex items-center">
|
<CardTitle className="flex items-center">
|
||||||
<Mail className="mr-2 h-5 w-5" />
|
<Mail className="mr-2 h-5 w-5" />
|
||||||
Contato
|
Contato e Endereço
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
<CardDescription>Informações de contato</CardDescription>
|
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-4">
|
<CardContent className="space-y-4">
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
<div className="grid md:grid-cols-2 gap-4">
|
||||||
<div className="space-y-2">
|
<div>
|
||||||
<Label htmlFor="email">Email</Label>
|
<Label htmlFor="email">Email</Label>
|
||||||
<Input
|
<Input
|
||||||
id="email"
|
id="email"
|
||||||
type="email"
|
type="email"
|
||||||
value={patientData.email}
|
value={patientData.email}
|
||||||
onChange={(e) => handleInputChange("email", e.target.value)}
|
disabled
|
||||||
disabled={!isEditing}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
<div>
|
||||||
<Label htmlFor="phone">Telefone</Label>
|
<Label htmlFor="phone">Telefone</Label>
|
||||||
<Input
|
<Input
|
||||||
id="phone"
|
id="phone"
|
||||||
value={patientData.phone}
|
value={patientData.phone}
|
||||||
onChange={(e) => handleInputChange("phone", e.target.value)}
|
onChange={(e) =>
|
||||||
|
handleInputChange("phone", e.target.value)
|
||||||
|
}
|
||||||
disabled={!isEditing}
|
disabled={!isEditing}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="grid md:grid-cols-3 gap-4">
|
||||||
<div className="space-y-2">
|
<div>
|
||||||
<Label htmlFor="address">Endereço</Label>
|
<Label htmlFor="cep">CEP</Label>
|
||||||
<Textarea
|
<Input
|
||||||
id="address"
|
id="cep"
|
||||||
value={patientData.address}
|
value={patientData.cep}
|
||||||
onChange={(e) => handleInputChange("address", e.target.value)}
|
onChange={(e) => handleInputChange("cep", e.target.value)}
|
||||||
disabled={!isEditing}
|
disabled={!isEditing}
|
||||||
rows={3}
|
/>
|
||||||
/>
|
</div>
|
||||||
|
<div className="md:col-span-2">
|
||||||
|
<Label htmlFor="street">Rua / Logradouro</Label>
|
||||||
|
<Input
|
||||||
|
id="street"
|
||||||
|
value={patientData.street}
|
||||||
|
onChange={(e) =>
|
||||||
|
handleInputChange("street", e.target.value)
|
||||||
|
}
|
||||||
|
disabled={!isEditing}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="grid md:grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="number">Número</Label>
|
||||||
|
<Input
|
||||||
|
id="number"
|
||||||
|
value={patientData.number}
|
||||||
|
onChange={(e) =>
|
||||||
|
handleInputChange("number", e.target.value)
|
||||||
|
}
|
||||||
|
disabled={!isEditing}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="city">Cidade</Label>
|
||||||
|
<Input
|
||||||
|
id="city"
|
||||||
|
value={patientData.city}
|
||||||
|
onChange={(e) =>
|
||||||
|
handleInputChange("city", e.target.value)
|
||||||
|
}
|
||||||
|
disabled={!isEditing}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
@ -162,15 +313,38 @@ export default function PatientProfile() {
|
|||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-4">
|
<CardContent className="space-y-4">
|
||||||
<div className="flex items-center space-x-3">
|
<div className="flex items-center space-x-3">
|
||||||
<div className="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center">
|
<div className="relative">
|
||||||
<User className="h-6 w-6 text-blue-600" />
|
<Avatar
|
||||||
|
className="w-16 h-16 cursor-pointer"
|
||||||
|
onClick={handleAvatarClick}
|
||||||
|
>
|
||||||
|
<AvatarImage src={patientData.avatarFullUrl} />
|
||||||
|
<AvatarFallback className="text-2xl">
|
||||||
|
{patientData.name
|
||||||
|
.split(" ")
|
||||||
|
.map((n) => n[0])
|
||||||
|
.join("")}
|
||||||
|
</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<div
|
||||||
|
className="absolute bottom-0 right-0 bg-primary text-primary-foreground rounded-full p-1 cursor-pointer hover:bg-primary/80"
|
||||||
|
onClick={handleAvatarClick}
|
||||||
|
>
|
||||||
|
<Upload className="w-3 h-3" />
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
ref={fileInputRef}
|
||||||
|
onChange={handleAvatarUpload}
|
||||||
|
className="hidden"
|
||||||
|
accept="image/png, image/jpeg"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-medium">{patientData.name}</p>
|
<p className="font-medium">{patientData.name}</p>
|
||||||
<p className="text-sm text-gray-500">Paciente</p>
|
<p className="text-sm text-gray-500">Paciente</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-3 pt-4 border-t">
|
<div className="space-y-3 pt-4 border-t">
|
||||||
<div className="flex items-center text-sm">
|
<div className="flex items-center text-sm">
|
||||||
<Mail className="mr-2 h-4 w-4 text-gray-500" />
|
<Mail className="mr-2 h-4 w-4 text-gray-500" />
|
||||||
@ -178,45 +352,25 @@ export default function PatientProfile() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="flex items-center text-sm">
|
<div className="flex items-center text-sm">
|
||||||
<Phone className="mr-2 h-4 w-4 text-gray-500" />
|
<Phone className="mr-2 h-4 w-4 text-gray-500" />
|
||||||
<span>{patientData.phone}</span>
|
<span>{patientData.phone || "Não informado"}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center text-sm">
|
<div className="flex items-center text-sm">
|
||||||
<Calendar className="mr-2 h-4 w-4 text-gray-500" />
|
<Calendar className="mr-2 h-4 w-4 text-gray-500" />
|
||||||
<span>
|
<span>
|
||||||
{patientData.birthDate
|
{patientData.birthDate
|
||||||
? new Date(patientData.birthDate).toLocaleDateString("pt-BR")
|
? new Date(patientData.birthDate).toLocaleDateString(
|
||||||
|
"pt-BR",
|
||||||
|
{ timeZone: "UTC" }
|
||||||
|
)
|
||||||
: "Não informado"}
|
: "Não informado"}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle className="flex items-center">
|
|
||||||
<FileText className="mr-2 h-5 w-5" />
|
|
||||||
Documentos
|
|
||||||
</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="space-y-3">
|
|
||||||
<Button variant="outline" size="sm" className="w-full justify-start bg-transparent">
|
|
||||||
<FileText className="mr-2 h-4 w-4" />
|
|
||||||
Carteirinha do Convênio
|
|
||||||
</Button>
|
|
||||||
<Button variant="outline" size="sm" className="w-full justify-start bg-transparent">
|
|
||||||
<FileText className="mr-2 h-4 w-4" />
|
|
||||||
Histórico Médico
|
|
||||||
</Button>
|
|
||||||
<Button variant="outline" size="sm" className="w-full justify-start bg-transparent">
|
|
||||||
<FileText className="mr-2 h-4 w-4" />
|
|
||||||
Exames Recentes
|
|
||||||
</Button>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</PatientLayout>
|
</Sidebar>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,7 +1,6 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import type React from "react"
|
import type React from "react"
|
||||||
|
|
||||||
import { useState } from "react"
|
import { useState } from "react"
|
||||||
import { useRouter } from "next/navigation"
|
import { useRouter } from "next/navigation"
|
||||||
import Link from "next/link"
|
import Link from "next/link"
|
||||||
@ -9,24 +8,24 @@ import { Button } from "@/components/ui/button"
|
|||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||||
import { Input } from "@/components/ui/input"
|
import { Input } from "@/components/ui/input"
|
||||||
import { Label } from "@/components/ui/label"
|
import { Label } from "@/components/ui/label"
|
||||||
import { Textarea } from "@/components/ui/textarea"
|
import { ArrowLeft, Loader2 } from "lucide-react"
|
||||||
import { Eye, EyeOff, ArrowLeft } from "lucide-react"
|
import { useToast } from "@/hooks/use-toast"
|
||||||
|
import { usersService } from "@/services/usersApi.mjs" // Mantém a importação
|
||||||
|
import { isValidCPF } from "@/lib/utils"
|
||||||
|
|
||||||
export default function PatientRegister() {
|
export default function PatientRegister() {
|
||||||
const [showPassword, setShowPassword] = useState(false)
|
// REMOVIDO: Estados para 'showPassword' e 'showConfirmPassword'
|
||||||
const [showConfirmPassword, setShowConfirmPassword] = useState(false)
|
|
||||||
const [formData, setFormData] = useState({
|
const [formData, setFormData] = useState({
|
||||||
name: "",
|
name: "",
|
||||||
email: "",
|
email: "",
|
||||||
password: "",
|
|
||||||
confirmPassword: "",
|
|
||||||
phone: "",
|
phone: "",
|
||||||
cpf: "",
|
cpf: "",
|
||||||
birthDate: "",
|
birthDate: "",
|
||||||
address: "",
|
// REMOVIDO: Campos 'password' e 'confirmPassword'
|
||||||
})
|
})
|
||||||
const [isLoading, setIsLoading] = useState(false)
|
const [isLoading, setIsLoading] = useState(false)
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
const { toast } = useToast()
|
||||||
|
|
||||||
const handleInputChange = (field: string, value: string) => {
|
const handleInputChange = (field: string, value: string) => {
|
||||||
setFormData((prev) => ({
|
setFormData((prev) => ({
|
||||||
@ -37,22 +36,52 @@ export default function PatientRegister() {
|
|||||||
|
|
||||||
const handleRegister = async (e: React.FormEvent) => {
|
const handleRegister = async (e: React.FormEvent) => {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
|
setIsLoading(true)
|
||||||
|
|
||||||
if (formData.password !== formData.confirmPassword) {
|
// --- VALIDAÇÃO DE CPF ---
|
||||||
alert("As senhas não coincidem!")
|
if (!isValidCPF(formData.cpf)) {
|
||||||
|
toast({
|
||||||
|
title: "CPF Inválido",
|
||||||
|
description: "O CPF informado não é válido. Verifique os dígitos.",
|
||||||
|
variant: "destructive",
|
||||||
|
})
|
||||||
|
setIsLoading(false)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
setIsLoading(true)
|
// --- LÓGICA DE REGISTRO COM ENDPOINT PÚBLICO ---
|
||||||
|
try {
|
||||||
|
// ALTERADO: Payload ajustado para o endpoint 'register-patient'
|
||||||
|
const payload = {
|
||||||
|
email: formData.email.trim().toLowerCase(),
|
||||||
|
full_name: formData.name,
|
||||||
|
phone_mobile: formData.phone, // O endpoint espera 'phone_mobile'
|
||||||
|
cpf: formData.cpf.replace(/\D/g, ''),
|
||||||
|
birth_date: formData.birthDate,
|
||||||
|
}
|
||||||
|
|
||||||
// Simulação de registro - em produção, conectar com API real
|
// ALTERADO: Chamada para a nova função de serviço
|
||||||
setTimeout(() => {
|
await usersService.registerPatient(payload)
|
||||||
// Salvar dados do usuário no localStorage para simulação
|
|
||||||
const { confirmPassword, ...userData } = formData
|
// ALTERADO: Mensagem de sucesso para refletir o fluxo de confirmação por e-mail
|
||||||
localStorage.setItem("patientData", JSON.stringify(userData))
|
toast({
|
||||||
router.push("/patient/dashboard")
|
title: "Cadastro enviado com sucesso!",
|
||||||
|
description: "Enviamos um link de confirmação para o seu e-mail. Por favor, verifique sua caixa de entrada para ativar sua conta.",
|
||||||
|
})
|
||||||
|
|
||||||
|
// Redireciona para a página de login
|
||||||
|
router.push("/login")
|
||||||
|
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error("Erro no registro:", error)
|
||||||
|
toast({
|
||||||
|
title: "Erro ao Criar Conta",
|
||||||
|
description: error.message || "Não foi possível concluir o cadastro. Verifique seus dados e tente novamente.",
|
||||||
|
variant: "destructive",
|
||||||
|
})
|
||||||
|
} finally {
|
||||||
setIsLoading(false)
|
setIsLoading(false)
|
||||||
}, 1000)
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@ -67,136 +96,85 @@ export default function PatientRegister() {
|
|||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader className="text-center">
|
<CardHeader className="text-center">
|
||||||
<CardTitle className="text-2xl">Cadastro de Paciente</CardTitle>
|
<CardTitle className="text-2xl">Crie sua Conta de Paciente</CardTitle>
|
||||||
<CardDescription>Preencha seus dados para criar sua conta</CardDescription>
|
<CardDescription>Preencha seus dados para acessar o portal MedConnect</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<form onSubmit={handleRegister} className="space-y-4">
|
<form onSubmit={handleRegister} className="space-y-4">
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
<div className="grid md:grid-cols-2 gap-4">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="name">Nome Completo</Label>
|
<Label htmlFor="name">Nome Completo *</Label>
|
||||||
<Input
|
<Input
|
||||||
id="name"
|
id="name"
|
||||||
value={formData.name}
|
value={formData.name}
|
||||||
onChange={(e) => handleInputChange("name", e.target.value)}
|
onChange={(e) => handleInputChange("name", e.target.value)}
|
||||||
required
|
required
|
||||||
|
disabled={isLoading}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="cpf">CPF</Label>
|
<Label htmlFor="cpf">CPF *</Label>
|
||||||
<Input
|
<Input
|
||||||
id="cpf"
|
id="cpf"
|
||||||
value={formData.cpf}
|
value={formData.cpf}
|
||||||
onChange={(e) => handleInputChange("cpf", e.target.value)}
|
onChange={(e) => handleInputChange("cpf", e.target.value)}
|
||||||
placeholder="000.000.000-00"
|
placeholder="000.000.000-00"
|
||||||
required
|
required
|
||||||
|
disabled={isLoading}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
<div className="grid md:grid-cols-2 gap-4">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="email">Email</Label>
|
<Label htmlFor="email">Email *</Label>
|
||||||
<Input
|
<Input
|
||||||
id="email"
|
id="email"
|
||||||
type="email"
|
type="email"
|
||||||
value={formData.email}
|
value={formData.email}
|
||||||
onChange={(e) => handleInputChange("email", e.target.value)}
|
onChange={(e) => handleInputChange("email", e.target.value)}
|
||||||
required
|
required
|
||||||
|
disabled={isLoading}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="phone">Telefone</Label>
|
<Label htmlFor="phone">Telefone *</Label>
|
||||||
<Input
|
<Input
|
||||||
id="phone"
|
id="phone"
|
||||||
value={formData.phone}
|
value={formData.phone}
|
||||||
onChange={(e) => handleInputChange("phone", e.target.value)}
|
onChange={(e) => handleInputChange("phone", e.target.value)}
|
||||||
placeholder="(11) 99999-9999"
|
placeholder="(11) 99999-9999"
|
||||||
required
|
required
|
||||||
|
disabled={isLoading}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="birthDate">Data de Nascimento</Label>
|
<Label htmlFor="birthDate">Data de Nascimento *</Label>
|
||||||
<Input
|
<Input
|
||||||
id="birthDate"
|
id="birthDate"
|
||||||
type="date"
|
type="date"
|
||||||
value={formData.birthDate}
|
value={formData.birthDate}
|
||||||
onChange={(e) => handleInputChange("birthDate", e.target.value)}
|
onChange={(e) => handleInputChange("birthDate", e.target.value)}
|
||||||
required
|
required
|
||||||
|
disabled={isLoading}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
{/* REMOVIDO: Seção de senha e confirmação de senha */}
|
||||||
<Label htmlFor="address">Endereço</Label>
|
|
||||||
<Textarea
|
|
||||||
id="address"
|
|
||||||
value={formData.address}
|
|
||||||
onChange={(e) => handleInputChange("address", e.target.value)}
|
|
||||||
placeholder="Rua, número, bairro, cidade, estado"
|
|
||||||
rows={3}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="password">Senha</Label>
|
|
||||||
<div className="relative">
|
|
||||||
<Input
|
|
||||||
id="password"
|
|
||||||
type={showPassword ? "text" : "password"}
|
|
||||||
value={formData.password}
|
|
||||||
onChange={(e) => handleInputChange("password", e.target.value)}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
|
|
||||||
onClick={() => setShowPassword(!showPassword)}
|
|
||||||
>
|
|
||||||
{showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="confirmPassword">Confirmar Senha</Label>
|
|
||||||
<div className="relative">
|
|
||||||
<Input
|
|
||||||
id="confirmPassword"
|
|
||||||
type={showConfirmPassword ? "text" : "password"}
|
|
||||||
value={formData.confirmPassword}
|
|
||||||
onChange={(e) => handleInputChange("confirmPassword", e.target.value)}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
|
|
||||||
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
|
|
||||||
>
|
|
||||||
{showConfirmPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Button type="submit" className="w-full" disabled={isLoading}>
|
<Button type="submit" className="w-full" disabled={isLoading}>
|
||||||
{isLoading ? "Criando conta..." : "Criar Conta"}
|
{isLoading ? <><Loader2 className="mr-2 h-4 w-4 animate-spin" /> Criando conta...</> : "Criar Conta"}
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<div className="mt-6 text-center">
|
<div className="mt-6 text-center">
|
||||||
<p className="text-sm text-gray-600">
|
<p className="text-sm text-gray-600">
|
||||||
Já tem uma conta?{" "}
|
Já tem uma conta?{" "}
|
||||||
<Link href="/patient/login" className="text-blue-600 hover:underline">
|
<Link href="/login" className="text-blue-600 hover:underline">
|
||||||
Faça login aqui
|
Faça login aqui
|
||||||
</Link>
|
</Link>
|
||||||
</p>
|
</p>
|
||||||
@ -206,4 +184,4 @@ export default function PatientRegister() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@ -1,13 +1,13 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useState, useEffect } from "react"
|
import { useState, useEffect } from "react"
|
||||||
import PatientLayout from "@/components/patient-layout"
|
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||||
import { Badge } from "@/components/ui/badge"
|
import { Badge } from "@/components/ui/badge"
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button"
|
||||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"
|
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"
|
||||||
import { toast } from "@/hooks/use-toast"
|
import { toast } from "@/hooks/use-toast"
|
||||||
import { FileText, Download, Eye, Calendar, User, X } from "lucide-react"
|
import { FileText, Download, Eye, Calendar, User, X } from "lucide-react"
|
||||||
|
import Sidebar from "@/components/Sidebar"
|
||||||
|
|
||||||
interface Report {
|
interface Report {
|
||||||
id: string
|
id: string
|
||||||
@ -287,7 +287,7 @@ export default function ReportsPage() {
|
|||||||
const pendingReports = reports.filter((report) => report.status === "pendente")
|
const pendingReports = reports.filter((report) => report.status === "pendente")
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PatientLayout>
|
<Sidebar>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-bold text-gray-900">Meus Laudos</h1>
|
<h1 className="text-3xl font-bold text-gray-900">Meus Laudos</h1>
|
||||||
@ -536,6 +536,6 @@ export default function ReportsPage() {
|
|||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
</div>
|
</div>
|
||||||
</PatientLayout>
|
</Sidebar>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,555 +1,12 @@
|
|||||||
"use client";
|
// app/patient/appointments/page.tsx
|
||||||
|
import Sidebar from "@/components/Sidebar";
|
||||||
import { usersService } from "services/usersApi.mjs";
|
import ScheduleForm from "@/components/schedule/schedule-form";
|
||||||
import { doctorsService } from "services/doctorsApi.mjs";
|
|
||||||
import { appointmentsService } from "services/appointmentsApi.mjs";
|
|
||||||
import { AvailabilityService } from "services/availabilityApi.mjs";
|
|
||||||
import { Calendar as CalendarShadcn } from "@/components/ui/calendar";
|
|
||||||
import { format, addDays } from "date-fns";
|
|
||||||
|
|
||||||
import { useState, useEffect, useCallback, useRef } from "react";
|
|
||||||
import { Calendar, Clock, User, StickyNote } from "lucide-react";
|
|
||||||
import PatientLayout from "@/components/patient-layout";
|
|
||||||
import {
|
|
||||||
Card,
|
|
||||||
CardContent,
|
|
||||||
CardHeader,
|
|
||||||
CardTitle,
|
|
||||||
} from "@/components/ui/card";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { Label } from "@/components/ui/label";
|
|
||||||
import {
|
|
||||||
Select,
|
|
||||||
SelectContent,
|
|
||||||
SelectItem,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from "@/components/ui/select";
|
|
||||||
import { Textarea } from "@/components/ui/textarea";
|
|
||||||
import { toast } from "@/hooks/use-toast";
|
|
||||||
|
|
||||||
|
|
||||||
interface Doctor {
|
export default function PatientAppointments() {
|
||||||
id: string;
|
|
||||||
full_name: string;
|
|
||||||
specialty: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Disponibilidade {
|
|
||||||
id?: string;
|
|
||||||
doctor_id?: string;
|
|
||||||
weekday: string;
|
|
||||||
start_time: string;
|
|
||||||
end_time: string;
|
|
||||||
slot_minutes?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function ScheduleAppointment() {
|
|
||||||
const [selectedDoctor, setSelectedDoctor] = useState("");
|
|
||||||
const [selectedDate, setSelectedDate] = useState("");
|
|
||||||
const [selectedTime, setSelectedTime] = useState("");
|
|
||||||
const [doctors, setDoctors] = useState<Doctor[]>([]);
|
|
||||||
const [availableTimes, setAvailableTimes] = useState<string[]>([]);
|
|
||||||
const [loadingSlots, setLoadingSlots] = useState(false);
|
|
||||||
const [loadingDoctors, setLoadingDoctors] = useState(true);
|
|
||||||
const [tipoConsulta, setTipoConsulta] = useState("presencial");
|
|
||||||
const [duracao, setDuracao] = useState("30");
|
|
||||||
const [notes, setNotes] = useState("");
|
|
||||||
const [disponibilidades, setDisponibilidades] = useState<Disponibilidade[]>([]);
|
|
||||||
const [availableWeekdays, setAvailableWeekdays] = useState<number[]>([]); // 1..7
|
|
||||||
const [availabilityCounts, setAvailabilityCounts] = useState<Record<string, number>>({}); // "yyyy-MM-dd" -> count
|
|
||||||
|
|
||||||
const calendarRef = useRef<HTMLDivElement | null>(null);
|
|
||||||
const tooltipRef = useRef<HTMLDivElement | null>(null);
|
|
||||||
const [tooltip, setTooltip] = useState<{ x: number; y: number; text: string } | null>(null);
|
|
||||||
|
|
||||||
// --- Helpers ---
|
|
||||||
const getWeekdayNumber = (weekday: string) =>
|
|
||||||
["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
|
|
||||||
.indexOf(weekday.toLowerCase()) + 1; // monday=1 ... sunday=7
|
|
||||||
|
|
||||||
const getBrazilDate = (date: Date) =>
|
|
||||||
new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), 12, 0, 0));
|
|
||||||
|
|
||||||
// --- Fetch doctors ---
|
|
||||||
const fetchDoctors = useCallback(async () => {
|
|
||||||
setLoadingDoctors(true);
|
|
||||||
try {
|
|
||||||
const data: Doctor[] = await doctorsService.list();
|
|
||||||
setDoctors(data || []);
|
|
||||||
} catch (e) {
|
|
||||||
console.error("Erro ao buscar médicos:", e);
|
|
||||||
toast({ title: "Erro", description: "Não foi possível carregar médicos." });
|
|
||||||
} finally {
|
|
||||||
setLoadingDoctors(false);
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
// --- Load disponibilidades details for selected doctor and compute weekdays ---
|
|
||||||
const loadDoctorDisponibilidades = useCallback(async (doctorId?: string) => {
|
|
||||||
if (!doctorId) {
|
|
||||||
setDisponibilidades([]);
|
|
||||||
setAvailableWeekdays([]);
|
|
||||||
setAvailabilityCounts({});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const disp: Disponibilidade[] = await AvailabilityService.listById(doctorId);
|
|
||||||
setDisponibilidades(disp || []);
|
|
||||||
const nums = (disp || []).map((d) => getWeekdayNumber(d.weekday)).filter(Boolean);
|
|
||||||
setAvailableWeekdays(Array.from(new Set(nums)));
|
|
||||||
// compute counts preview for next 90 days
|
|
||||||
await computeAvailabilityCountsPreview(doctorId, disp || []);
|
|
||||||
} catch (e) {
|
|
||||||
console.error("Erro disponibilidades:", e);
|
|
||||||
setDisponibilidades([]);
|
|
||||||
setAvailableWeekdays([]);
|
|
||||||
setAvailabilityCounts({});
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
// --- Compute availability counts for next 90 days (efficient) ---
|
|
||||||
const computeAvailabilityCountsPreview = async (doctorId: string, dispList: Disponibilidade[]) => {
|
|
||||||
try {
|
|
||||||
const today = new Date();
|
|
||||||
const start = format(today, "yyyy-MM-dd");
|
|
||||||
const endDate = addDays(today, 90);
|
|
||||||
const end = format(endDate, "yyyy-MM-dd");
|
|
||||||
|
|
||||||
// fetch appointments for this doctor for the whole window (one call)
|
|
||||||
const appointments = await appointmentsService.search_appointment(
|
|
||||||
`doctor_id=eq.${doctorId}&scheduled_at=gte.${start}T00:00:00Z&scheduled_at=lt.${end}T23:59:59Z`
|
|
||||||
);
|
|
||||||
|
|
||||||
// group appointments by date
|
|
||||||
const apptsByDate: Record<string, number> = {};
|
|
||||||
(appointments || []).forEach((a: any) => {
|
|
||||||
const d = String(a.scheduled_at).split("T")[0];
|
|
||||||
apptsByDate[d] = (apptsByDate[d] || 0) + 1;
|
|
||||||
});
|
|
||||||
|
|
||||||
const counts: Record<string, number> = {};
|
|
||||||
for (let i = 0; i <= 90; i++) {
|
|
||||||
const d = addDays(today, i);
|
|
||||||
const key = format(d, "yyyy-MM-dd");
|
|
||||||
const dayOfWeek = d.getDay() === 0 ? 7 : d.getDay(); // 1..7
|
|
||||||
|
|
||||||
// find all disponibilidades matching this weekday
|
|
||||||
const dailyDisp = dispList.filter((p) => getWeekdayNumber(p.weekday) === dayOfWeek);
|
|
||||||
|
|
||||||
if (dailyDisp.length === 0) {
|
|
||||||
counts[key] = 0;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// compute total possible slots for the day summing multiple intervals
|
|
||||||
let possible = 0;
|
|
||||||
dailyDisp.forEach((p) => {
|
|
||||||
const [sh, sm] = p.start_time.split(":").map(Number);
|
|
||||||
const [eh, em] = p.end_time.split(":").map(Number);
|
|
||||||
const startMin = sh * 60 + sm;
|
|
||||||
const endMin = eh * 60 + em;
|
|
||||||
const slot = p.slot_minutes || 30;
|
|
||||||
// inclusive handling: if start==end -> 1 slot? normally not, we do Math.floor((end - start)/slot) + 1 if end >= start
|
|
||||||
if (endMin >= startMin) {
|
|
||||||
possible += Math.floor((endMin - startMin) / slot) + 1;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const occupied = apptsByDate[key] || 0;
|
|
||||||
const free = Math.max(0, possible - occupied);
|
|
||||||
counts[key] = free;
|
|
||||||
}
|
|
||||||
|
|
||||||
setAvailabilityCounts(counts);
|
|
||||||
} catch (e) {
|
|
||||||
console.error("Erro ao calcular contagens de disponibilidade:", e);
|
|
||||||
setAvailabilityCounts({});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// --- When doctor changes ---
|
|
||||||
useEffect(() => {
|
|
||||||
fetchDoctors();
|
|
||||||
}, [fetchDoctors]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (selectedDoctor) {
|
|
||||||
loadDoctorDisponibilidades(selectedDoctor);
|
|
||||||
} else {
|
|
||||||
setDisponibilidades([]);
|
|
||||||
setAvailableWeekdays([]);
|
|
||||||
setAvailabilityCounts({});
|
|
||||||
}
|
|
||||||
setSelectedDate("");
|
|
||||||
setSelectedTime("");
|
|
||||||
setAvailableTimes([]);
|
|
||||||
}, [selectedDoctor, loadDoctorDisponibilidades]);
|
|
||||||
|
|
||||||
// --- Fetch available times for date --- (same logic, but shows toast if none)
|
|
||||||
const fetchAvailableSlots = useCallback(
|
|
||||||
async (doctorId: string, date: string) => {
|
|
||||||
if (!doctorId || !date) return;
|
|
||||||
setLoadingSlots(true);
|
|
||||||
setAvailableTimes([]);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const disponibilidades: Disponibilidade[] = await AvailabilityService.listById(doctorId);
|
|
||||||
|
|
||||||
const consultas = await appointmentsService.search_appointment(
|
|
||||||
`doctor_id=eq.${doctorId}&scheduled_at=gte.${date}T00:00:00Z&scheduled_at=lt.${date}T23:59:59Z`
|
|
||||||
);
|
|
||||||
|
|
||||||
const diaJS = new Date(date).getDay(); // 0..6
|
|
||||||
const diaAPI = diaJS === 0 ? 7 : diaJS;
|
|
||||||
|
|
||||||
const disponibilidadeDia = disponibilidades.find(
|
|
||||||
(d) => getWeekdayNumber(d.weekday) === diaAPI
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!disponibilidadeDia) {
|
|
||||||
setAvailableTimes([]);
|
|
||||||
toast({ title: "Nenhuma disponibilidade", description: "Nenhuma disponibilidade cadastrada para este dia." });
|
|
||||||
setLoadingSlots(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const [startHour, startMin] = disponibilidadeDia.start_time.split(":").map(Number);
|
|
||||||
const [endHour, endMin] = disponibilidadeDia.end_time.split(":").map(Number);
|
|
||||||
const slot = disponibilidadeDia.slot_minutes || 30;
|
|
||||||
|
|
||||||
const horariosGerados: string[] = [];
|
|
||||||
let atual = new Date(date);
|
|
||||||
atual.setHours(startHour, startMin, 0, 0);
|
|
||||||
|
|
||||||
const end = new Date(date);
|
|
||||||
end.setHours(endHour, endMin, 0, 0);
|
|
||||||
|
|
||||||
while (atual <= end) {
|
|
||||||
horariosGerados.push(atual.toTimeString().slice(0, 5));
|
|
||||||
atual = new Date(atual.getTime() + slot * 60000);
|
|
||||||
}
|
|
||||||
|
|
||||||
const ocupados = (consultas || []).map((c: any) =>
|
|
||||||
String(c.scheduled_at).split("T")[1]?.slice(0, 5)
|
|
||||||
);
|
|
||||||
|
|
||||||
const livres = horariosGerados.filter((h) => !ocupados.includes(h));
|
|
||||||
|
|
||||||
if (livres.length === 0) {
|
|
||||||
toast({ title: "Sem horários livres", description: "Todos os horários estão ocupados neste dia." });
|
|
||||||
}
|
|
||||||
|
|
||||||
setAvailableTimes(livres);
|
|
||||||
} catch (err) {
|
|
||||||
console.error(err);
|
|
||||||
setAvailableTimes([]);
|
|
||||||
toast({ title: "Erro", description: "Falha ao carregar horários." });
|
|
||||||
} finally {
|
|
||||||
setLoadingSlots(false);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[]
|
|
||||||
);
|
|
||||||
|
|
||||||
// run fetchAvailableSlots when date changes
|
|
||||||
useEffect(() => {
|
|
||||||
if (selectedDoctor && selectedDate) {
|
|
||||||
fetchAvailableSlots(selectedDoctor, selectedDate);
|
|
||||||
} else {
|
|
||||||
setAvailableTimes([]);
|
|
||||||
}
|
|
||||||
setSelectedTime("");
|
|
||||||
}, [selectedDoctor, selectedDate, fetchAvailableSlots]);
|
|
||||||
|
|
||||||
// --- Submit ---
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
|
|
||||||
if (!selectedDoctor || !selectedDate || !selectedTime) {
|
|
||||||
toast({ title: "Preencha os campos", description: "Selecione médico, data e horário." });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const doctor = doctors.find((d) => d.id === selectedDoctor);
|
|
||||||
const paciente = await usersService.getMe();
|
|
||||||
|
|
||||||
const body = {
|
|
||||||
doctor_id: doctor?.id,
|
|
||||||
patient_id: paciente.user.id,
|
|
||||||
scheduled_at: `${selectedDate}T${selectedTime}:00`, // saving as local-ish string (you chose UTC elsewhere)
|
|
||||||
duration_minutes: Number(duracao),
|
|
||||||
notes,
|
|
||||||
appointment_type: tipoConsulta,
|
|
||||||
};
|
|
||||||
|
|
||||||
await appointmentsService.create(body);
|
|
||||||
toast({ title: "Agendado", description: "Consulta agendada com sucesso." });
|
|
||||||
|
|
||||||
// reset
|
|
||||||
setSelectedDoctor("");
|
|
||||||
setSelectedDate("");
|
|
||||||
setSelectedTime("");
|
|
||||||
setAvailableTimes([]);
|
|
||||||
setNotes("");
|
|
||||||
// refresh counts
|
|
||||||
if (selectedDoctor) computeAvailabilityCountsPreview(selectedDoctor, disponibilidades);
|
|
||||||
} catch (err) {
|
|
||||||
console.error(err);
|
|
||||||
toast({ title: "Erro", description: "Falha ao agendar consulta." });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// --- Calendar tooltip via event delegation ---
|
|
||||||
useEffect(() => {
|
|
||||||
const cont = calendarRef.current;
|
|
||||||
if (!cont) return;
|
|
||||||
|
|
||||||
const onMove = (ev: MouseEvent) => {
|
|
||||||
const target = ev.target as HTMLElement | null;
|
|
||||||
if (!target) return;
|
|
||||||
// find closest button that likely is a day cell
|
|
||||||
const btn = target.closest("button");
|
|
||||||
if (!btn) {
|
|
||||||
setTooltip(null);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// many calendar implementations put the date in aria-label, e.g. "November 13, 2025"
|
|
||||||
const aria = btn.getAttribute("aria-label") || btn.textContent || "";
|
|
||||||
// try to parse date from aria-label: new Date(aria) works for many locales
|
|
||||||
const parsed = new Date(aria);
|
|
||||||
if (isNaN(parsed.getTime())) {
|
|
||||||
// sometimes aria-label is like "13" (just day) - try data-day attribute
|
|
||||||
const dataDay = btn.getAttribute("data-day");
|
|
||||||
if (dataDay) {
|
|
||||||
// try parse yyyy-mm-dd
|
|
||||||
const pd = new Date(dataDay);
|
|
||||||
if (!isNaN(pd.getTime())) {
|
|
||||||
const key = format(pd, "yyyy-MM-dd");
|
|
||||||
const count = availabilityCounts[key] ?? 0;
|
|
||||||
setTooltip({
|
|
||||||
x: ev.pageX + 10,
|
|
||||||
y: ev.pageY + 10,
|
|
||||||
text: `${count} horário${count !== 1 ? "s" : ""} disponíveis`,
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
setTooltip(null);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// parsed is valid - convert to yyyy-MM-dd
|
|
||||||
const key = format(getBrazilDate(parsed), "yyyy-MM-dd");
|
|
||||||
const count = availabilityCounts[key] ?? 0;
|
|
||||||
setTooltip({
|
|
||||||
x: ev.pageX + 10,
|
|
||||||
y: ev.pageY + 10,
|
|
||||||
text: `${count} horário${count !== 1 ? "s" : ""} disponíveis`,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const onLeave = () => setTooltip(null);
|
|
||||||
|
|
||||||
cont.addEventListener("mousemove", onMove);
|
|
||||||
cont.addEventListener("mouseleave", onLeave);
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
cont.removeEventListener("mousemove", onMove);
|
|
||||||
cont.removeEventListener("mouseleave", onLeave);
|
|
||||||
};
|
|
||||||
}, [availabilityCounts]);
|
|
||||||
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PatientLayout>
|
<Sidebar>
|
||||||
<div className="max-w-6xl mx-auto space-y-4 px-4">
|
<ScheduleForm />
|
||||||
<h1 className="text-2xl font-semibold">Agendar Consulta</h1>
|
</Sidebar>
|
||||||
|
|
||||||
<Card className="border rounded-xl shadow-sm">
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle>Dados da Consulta</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
|
|
||||||
<CardContent>
|
|
||||||
<form onSubmit={handleSubmit} className="grid grid-cols-1 lg:grid-cols-2 gap-6 w-full">
|
|
||||||
{/* LEFT */}
|
|
||||||
<div className="space-y-3">
|
|
||||||
<div>
|
|
||||||
<Label className="text-sm">Médico</Label>
|
|
||||||
<Select value={selectedDoctor} onValueChange={setSelectedDoctor}>
|
|
||||||
<SelectTrigger>
|
|
||||||
<SelectValue placeholder="Selecione o médico">
|
|
||||||
{selectedDoctor && doctors.find(d => d.id === selectedDoctor)?.full_name}
|
|
||||||
</SelectValue>
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
{loadingDoctors ? (
|
|
||||||
<SelectItem value="loading" disabled>Carregando...</SelectItem>
|
|
||||||
) : (
|
|
||||||
doctors.map((d) => (
|
|
||||||
<SelectItem key={d.id} value={d.id}>
|
|
||||||
{d.full_name} — {d.specialty}
|
|
||||||
</SelectItem>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<Label className="text-sm">Data</Label>
|
|
||||||
<div ref={calendarRef} className="rounded-lg border p-2">
|
|
||||||
<CalendarShadcn
|
|
||||||
mode="single"
|
|
||||||
disabled={!selectedDoctor}
|
|
||||||
selected={selectedDate ? new Date(selectedDate + "T12:00:00") : undefined}
|
|
||||||
onSelect={(date) => {
|
|
||||||
if (!date) return;
|
|
||||||
const fixedDate = new Date(date.getTime() + 12 * 60 * 60 * 1000);
|
|
||||||
const formatted = format(fixedDate, "yyyy-MM-dd");
|
|
||||||
setSelectedDate(formatted);
|
|
||||||
}}
|
|
||||||
className="rounded-md border shadow-sm p-2"
|
|
||||||
modifiers={{ selected: selectedDate ? new Date(selectedDate + 'T12:00:00') : undefined }}
|
|
||||||
modifiersClassNames={{
|
|
||||||
selected:
|
|
||||||
"bg-blue-600 text-white hover:bg-blue-700 rounded-md",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
</div>
|
|
||||||
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<Label className="text-sm">Observações</Label>
|
|
||||||
<Textarea
|
|
||||||
placeholder="Instruções para o médico..."
|
|
||||||
value={notes}
|
|
||||||
onChange={(e) => setNotes(e.target.value)}
|
|
||||||
className="mt-2"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* RIGHT */}
|
|
||||||
<div className="space-y-3">
|
|
||||||
<Card className="shadow-md rounded-xl bg-blue-50 border border-blue-200">
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle className="text-blue-700">Resumo</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="space-y-2 text-gray-900 text-sm">
|
|
||||||
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<User className="h-4 w-4 text-blue-600" />
|
|
||||||
<div className="text-xs">
|
|
||||||
{selectedDoctor ? (
|
|
||||||
<div className="font-medium">
|
|
||||||
{doctors.find((d) => d.id === selectedDoctor)?.full_name}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="text-gray-500">Médico</div>
|
|
||||||
)}
|
|
||||||
<div className="text-xs text-gray-500">
|
|
||||||
{selectedDoctor ? doctors.find(d => d.id === selectedDoctor)?.specialty : ""}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="text-xs text-gray-600">{tipoConsulta} • {duracao} min</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Calendar className="h-4 w-4 text-blue-600" />
|
|
||||||
<div>
|
|
||||||
{selectedDate ? (
|
|
||||||
<div className="font-medium">{selectedDate.split("-").reverse().join("/")}</div>
|
|
||||||
) : (
|
|
||||||
<div className="text-gray-500">Data</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="text-xs text-gray-600">—</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Horário */}
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label>Horário</Label>
|
|
||||||
<Select onValueChange={setSelectedTime} disabled={
|
|
||||||
loadingSlots || availableTimes.length === 0
|
|
||||||
} >
|
|
||||||
<SelectTrigger> <SelectValue placeholder={
|
|
||||||
loadingSlots ? "Carregando horários..." : availableTimes.length === 0 ? "Nenhum horário disponível" : "Selecione o horário"
|
|
||||||
} />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent> {
|
|
||||||
availableTimes.map((h) => ( <SelectItem key={h} value={h}> {h} </SelectItem> ))
|
|
||||||
} </SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{notes && (
|
|
||||||
<div className="flex items-start gap-2 text-sm">
|
|
||||||
<StickyNote className="h-4 w-4" />
|
|
||||||
<div className="italic text-gray-700">{notes}</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<Button
|
|
||||||
type="submit"
|
|
||||||
className="w-full md:w-auto px-4 py-1.5 text-sm bg-blue-600 text-white hover:bg-blue-700"
|
|
||||||
disabled={!selectedDoctor || !selectedDate || !selectedTime}
|
|
||||||
>
|
|
||||||
Agendar
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="outline"
|
|
||||||
onClick={() => {
|
|
||||||
setSelectedDoctor("");
|
|
||||||
setSelectedDate("");
|
|
||||||
setSelectedTime("");
|
|
||||||
setAvailableTimes([]);
|
|
||||||
setNotes("");
|
|
||||||
}}
|
|
||||||
className="px-3"
|
|
||||||
>
|
|
||||||
Limpar
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* Tooltip element */}
|
|
||||||
{tooltip && (
|
|
||||||
<div
|
|
||||||
ref={tooltipRef}
|
|
||||||
style={{
|
|
||||||
position: "absolute",
|
|
||||||
left: tooltip.x,
|
|
||||||
top: tooltip.y,
|
|
||||||
zIndex: 60,
|
|
||||||
background: "rgba(0,0,0,0.85)",
|
|
||||||
color: "white",
|
|
||||||
padding: "6px 8px",
|
|
||||||
borderRadius: 6,
|
|
||||||
fontSize: 12,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{tooltip.text}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</PatientLayout>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,201 +1,287 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import SecretaryLayout from "@/components/secretary-layout";
|
import {
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
Card,
|
||||||
|
CardContent,
|
||||||
|
CardDescription,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from "@/components/ui/card";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
import { Dialog } from "@/components/ui/dialog";
|
||||||
import { Input } from "@/components/ui/input";
|
import {
|
||||||
import { Label } from "@/components/ui/label";
|
Calendar,
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
Clock,
|
||||||
import { Calendar, Clock, MapPin, Phone, User, Trash2, Pencil } from "lucide-react";
|
MapPin,
|
||||||
|
Phone,
|
||||||
|
User,
|
||||||
|
Trash2,
|
||||||
|
Pencil,
|
||||||
|
} from "lucide-react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
||||||
import { patientsService } from "@/services/patientsApi.mjs";
|
import { patientsService } from "@/services/patientsApi.mjs";
|
||||||
import { doctorsService } from "@/services/doctorsApi.mjs";
|
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||||
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
export default function SecretaryAppointments() {
|
export default function SecretaryAppointments() {
|
||||||
const [appointments, setAppointments] = useState<any[]>([]);
|
const [appointments, setAppointments] = useState<any[]>([]);
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
const [selectedAppointment, setSelectedAppointment] = useState<any>(null);
|
const [selectedAppointment, setSelectedAppointment] = useState<any>(null);
|
||||||
|
|
||||||
// Estados dos Modais
|
// Estados dos Modais
|
||||||
const [deleteModal, setDeleteModal] = useState(false);
|
const [deleteModal, setDeleteModal] = useState(false);
|
||||||
const [editModal, setEditModal] = useState(false);
|
const [editModal, setEditModal] = useState(false);
|
||||||
|
|
||||||
// Estado para o formulário de edição
|
// Estado para o formulário de edição
|
||||||
const [editFormData, setEditFormData] = useState({
|
const [editFormData, setEditFormData] = useState({
|
||||||
date: "",
|
date: "",
|
||||||
time: "",
|
time: "",
|
||||||
status: "",
|
status: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
const fetchData = async () => {
|
||||||
|
setIsLoading(true);
|
||||||
|
try {
|
||||||
|
// 1. DEFINIR O PARÂMETRO DE ORDENAÇÃO
|
||||||
|
// 'scheduled_at.desc' ordena pela data do agendamento, em ordem descendente (mais recentes primeiro).
|
||||||
|
const queryParams = "order=scheduled_at.desc";
|
||||||
|
|
||||||
|
const [appointmentList, patientList, doctorList] = await Promise.all([
|
||||||
|
// 2. USAR A FUNÇÃO DE BUSCA COM O PARÂMETRO DE ORDENAÇÃO
|
||||||
|
appointmentsService.search_appointment(queryParams),
|
||||||
|
patientsService.list(),
|
||||||
|
doctorsService.list(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const patientMap = new Map(patientList.map((p: any) => [p.id, p]));
|
||||||
|
const doctorMap = new Map(doctorList.map((d: any) => [d.id, d]));
|
||||||
|
|
||||||
|
const enrichedAppointments = appointmentList.map((apt: any) => ({
|
||||||
|
...apt,
|
||||||
|
patient: patientMap.get(apt.patient_id) || {
|
||||||
|
full_name: "Paciente não encontrado",
|
||||||
|
},
|
||||||
|
doctor: doctorMap.get(apt.doctor_id) || {
|
||||||
|
full_name: "Médico não encontrado",
|
||||||
|
specialty: "N/A",
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
setAppointments(enrichedAppointments);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Falha ao buscar agendamentos:", error);
|
||||||
|
toast.error("Não foi possível carregar a lista de agendamentos.");
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchData();
|
||||||
|
}, []); // Array vazio garante que a busca ocorra apenas uma vez, no carregamento da página.
|
||||||
|
|
||||||
|
// --- LÓGICA DE EDIÇÃO ---
|
||||||
|
const handleEdit = (appointment: any) => {
|
||||||
|
setSelectedAppointment(appointment);
|
||||||
|
const appointmentDate = new Date(appointment.scheduled_at);
|
||||||
|
|
||||||
|
setEditFormData({
|
||||||
|
date: appointmentDate.toISOString().split("T")[0],
|
||||||
|
time: appointmentDate.toLocaleTimeString("pt-BR", {
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
timeZone: "UTC",
|
||||||
|
}),
|
||||||
|
status: appointment.status,
|
||||||
});
|
});
|
||||||
|
setEditModal(true);
|
||||||
|
};
|
||||||
|
|
||||||
const fetchData = async () => {
|
const confirmEdit = async () => {
|
||||||
setIsLoading(true);
|
if (
|
||||||
try {
|
!selectedAppointment ||
|
||||||
// 1. DEFINIR O PARÂMETRO DE ORDENAÇÃO
|
!editFormData.date ||
|
||||||
// 'scheduled_at.desc' ordena pela data do agendamento, em ordem descendente (mais recentes primeiro).
|
!editFormData.time ||
|
||||||
const queryParams = 'order=scheduled_at.desc';
|
!editFormData.status
|
||||||
|
) {
|
||||||
|
toast.error("Todos os campos são obrigatórios para a edição.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const [appointmentList, patientList, doctorList] = await Promise.all([
|
try {
|
||||||
// 2. USAR A FUNÇÃO DE BUSCA COM O PARÂMETRO DE ORDENAÇÃO
|
const newScheduledAt = new Date(
|
||||||
appointmentsService.search_appointment(queryParams),
|
`${editFormData.date}T${editFormData.time}:00Z`
|
||||||
patientsService.list(),
|
).toISOString();
|
||||||
doctorsService.list(),
|
const updatePayload = {
|
||||||
]);
|
scheduled_at: newScheduledAt,
|
||||||
|
status: editFormData.status,
|
||||||
|
};
|
||||||
|
|
||||||
const patientMap = new Map(patientList.map((p: any) => [p.id, p]));
|
await appointmentsService.update(selectedAppointment.id, updatePayload);
|
||||||
const doctorMap = new Map(doctorList.map((d: any) => [d.id, d]));
|
|
||||||
|
|
||||||
const enrichedAppointments = appointmentList.map((apt: any) => ({
|
// 3. RECARREGAR OS DADOS APÓS A EDIÇÃO
|
||||||
...apt,
|
// Isso garante que a lista permaneça ordenada corretamente se a data for alterada.
|
||||||
patient: patientMap.get(apt.patient_id) || { full_name: "Paciente não encontrado" },
|
fetchData();
|
||||||
doctor: doctorMap.get(apt.doctor_id) || { full_name: "Médico não encontrado", specialty: "N/A" },
|
|
||||||
}));
|
|
||||||
|
|
||||||
setAppointments(enrichedAppointments);
|
setEditModal(false);
|
||||||
} catch (error) {
|
toast.success("Consulta atualizada com sucesso!");
|
||||||
console.error("Falha ao buscar agendamentos:", error);
|
} catch (error) {
|
||||||
toast.error("Não foi possível carregar a lista de agendamentos.");
|
console.error("Erro ao atualizar consulta:", error);
|
||||||
} finally {
|
toast.error("Não foi possível atualizar a consulta.");
|
||||||
setIsLoading(false);
|
}
|
||||||
}
|
};
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
// --- LÓGICA DE DELEÇÃO ---
|
||||||
fetchData();
|
const handleDelete = (appointment: any) => {
|
||||||
}, []); // Array vazio garante que a busca ocorra apenas uma vez, no carregamento da página.
|
setSelectedAppointment(appointment);
|
||||||
|
setDeleteModal(true);
|
||||||
|
};
|
||||||
|
|
||||||
// --- LÓGICA DE EDIÇÃO ---
|
const confirmDelete = async () => {
|
||||||
const handleEdit = (appointment: any) => {
|
if (!selectedAppointment) return;
|
||||||
setSelectedAppointment(appointment);
|
try {
|
||||||
const appointmentDate = new Date(appointment.scheduled_at);
|
await appointmentsService.delete(selectedAppointment.id);
|
||||||
|
setAppointments((prev) =>
|
||||||
|
prev.filter((apt) => apt.id !== selectedAppointment.id)
|
||||||
|
);
|
||||||
|
setDeleteModal(false);
|
||||||
|
toast.success("Consulta deletada com sucesso!");
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Erro ao deletar consulta:", error);
|
||||||
|
toast.error("Não foi possível deletar a consulta.");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
setEditFormData({
|
const getStatusBadge = (status: string) => {
|
||||||
date: appointmentDate.toISOString().split('T')[0],
|
switch (status) {
|
||||||
time: appointmentDate.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit', timeZone: 'UTC' }),
|
case "requested":
|
||||||
status: appointment.status,
|
return (
|
||||||
});
|
<Badge className="bg-yellow-100 text-yellow-800">Solicitada</Badge>
|
||||||
setEditModal(true);
|
);
|
||||||
};
|
case "confirmed":
|
||||||
|
return <Badge className="bg-blue-100 text-blue-800">Confirmada</Badge>;
|
||||||
|
case "checked_in":
|
||||||
|
return (
|
||||||
|
<Badge className="bg-indigo-100 text-indigo-800">Check-in</Badge>
|
||||||
|
);
|
||||||
|
case "completed":
|
||||||
|
return <Badge className="bg-green-100 text-green-800">Realizada</Badge>;
|
||||||
|
case "cancelled":
|
||||||
|
return <Badge className="bg-red-100 text-red-800">Cancelada</Badge>;
|
||||||
|
case "no_show":
|
||||||
|
return (
|
||||||
|
<Badge className="bg-gray-100 text-gray-800">Não Compareceu</Badge>
|
||||||
|
);
|
||||||
|
default:
|
||||||
|
return <Badge variant="secondary">{status}</Badge>;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const confirmEdit = async () => {
|
const timeSlots = [
|
||||||
if (!selectedAppointment || !editFormData.date || !editFormData.time || !editFormData.status) {
|
"08:00",
|
||||||
toast.error("Todos os campos são obrigatórios para a edição.");
|
"08:30",
|
||||||
return;
|
"09:00",
|
||||||
}
|
"09:30",
|
||||||
|
"10:00",
|
||||||
|
"10:30",
|
||||||
|
"11:00",
|
||||||
|
"11:30",
|
||||||
|
"14:00",
|
||||||
|
"14:30",
|
||||||
|
"15:00",
|
||||||
|
"15:30",
|
||||||
|
"16:00",
|
||||||
|
"16:30",
|
||||||
|
"17:00",
|
||||||
|
"17:30",
|
||||||
|
];
|
||||||
|
const appointmentStatuses = [
|
||||||
|
"requested",
|
||||||
|
"confirmed",
|
||||||
|
"checked_in",
|
||||||
|
"completed",
|
||||||
|
"cancelled",
|
||||||
|
"no_show",
|
||||||
|
];
|
||||||
|
|
||||||
try {
|
return (
|
||||||
const newScheduledAt = new Date(`${editFormData.date}T${editFormData.time}:00Z`).toISOString();
|
<Sidebar>
|
||||||
const updatePayload = {
|
<div className="space-y-6">
|
||||||
scheduled_at: newScheduledAt,
|
<div className="flex justify-between items-center">
|
||||||
status: editFormData.status,
|
<div>
|
||||||
};
|
<h1 className="text-3xl font-bold text-gray-900">
|
||||||
|
Consultas Agendadas
|
||||||
|
</h1>
|
||||||
|
<p className="text-gray-600">Gerencie as consultas dos pacientes</p>
|
||||||
|
</div>
|
||||||
|
<Link href="/secretary/schedule">
|
||||||
|
<Button className="bg-blue-600 hover:bg-blue-700 text-white">
|
||||||
|
<Calendar className="mr-2 h-4 w-4 text-white" />
|
||||||
|
Agendar Nova Consulta
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
|
||||||
await appointmentsService.update(selectedAppointment.id, updatePayload);
|
<div className="grid gap-6">
|
||||||
|
{isLoading ? (
|
||||||
// 3. RECARREGAR OS DADOS APÓS A EDIÇÃO
|
<p>Carregando consultas...</p>
|
||||||
// Isso garante que a lista permaneça ordenada corretamente se a data for alterada.
|
) : appointments.length > 0 ? (
|
||||||
fetchData();
|
appointments.map((appointment) => (
|
||||||
|
<Card key={appointment.id}>
|
||||||
setEditModal(false);
|
<CardHeader>
|
||||||
toast.success("Consulta atualizada com sucesso!");
|
<div className="flex justify-between items-start">
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Erro ao atualizar consulta:", error);
|
|
||||||
toast.error("Não foi possível atualizar a consulta.");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// --- LÓGICA DE DELEÇÃO ---
|
|
||||||
const handleDelete = (appointment: any) => {
|
|
||||||
setSelectedAppointment(appointment);
|
|
||||||
setDeleteModal(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
const confirmDelete = async () => {
|
|
||||||
if (!selectedAppointment) return;
|
|
||||||
try {
|
|
||||||
await appointmentsService.delete(selectedAppointment.id);
|
|
||||||
setAppointments((prev) => prev.filter((apt) => apt.id !== selectedAppointment.id));
|
|
||||||
setDeleteModal(false);
|
|
||||||
toast.success("Consulta deletada com sucesso!");
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Erro ao deletar consulta:", error);
|
|
||||||
toast.error("Não foi possível deletar a consulta.");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const getStatusBadge = (status: string) => {
|
|
||||||
switch (status) {
|
|
||||||
case "requested": return <Badge className="bg-yellow-100 text-yellow-800">Solicitada</Badge>;
|
|
||||||
case "confirmed": return <Badge className="bg-blue-100 text-blue-800">Confirmada</Badge>;
|
|
||||||
case "checked_in": return <Badge className="bg-indigo-100 text-indigo-800">Check-in</Badge>;
|
|
||||||
case "completed": return <Badge className="bg-green-100 text-green-800">Realizada</Badge>;
|
|
||||||
case "cancelled": return <Badge className="bg-red-100 text-red-800">Cancelada</Badge>;
|
|
||||||
case "no_show": return <Badge className="bg-gray-100 text-gray-800">Não Compareceu</Badge>;
|
|
||||||
default: return <Badge variant="secondary">{status}</Badge>;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const timeSlots = ["08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30"];
|
|
||||||
const appointmentStatuses = ["requested", "confirmed", "checked_in", "completed", "cancelled", "no_show"];
|
|
||||||
|
|
||||||
return (
|
|
||||||
<SecretaryLayout>
|
|
||||||
<div className="space-y-6">
|
|
||||||
<div className="flex justify-between items-center">
|
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-bold text-gray-900">Consultas Agendadas</h1>
|
<CardTitle className="text-lg">
|
||||||
<p className="text-gray-600">Gerencie as consultas dos pacientes</p>
|
{appointment.doctor.full_name}
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
{appointment.doctor.specialty}
|
||||||
|
</CardDescription>
|
||||||
</div>
|
</div>
|
||||||
<Link href="/secretary/schedule">
|
{getStatusBadge(appointment.status)}
|
||||||
<Button><Calendar className="mr-2 h-4 w-4" /> Agendar Nova Consulta</Button>
|
</div>
|
||||||
</Link>
|
</CardHeader>
|
||||||
</div>
|
<CardContent>
|
||||||
|
<div className="grid md:grid-cols-2 gap-4">
|
||||||
<div className="grid gap-6">
|
<div className="space-y-3">
|
||||||
{isLoading ? <p>Carregando consultas...</p> : appointments.length > 0 ? (
|
<div className="flex items-center text-sm text-gray-800 font-medium">
|
||||||
appointments.map((appointment) => (
|
<User className="mr-2 h-4 w-4 text-gray-600" />
|
||||||
<Card key={appointment.id}>
|
{appointment.patient.full_name}
|
||||||
<CardHeader>
|
</div>
|
||||||
<div className="flex justify-between items-start">
|
<div className="flex items-center text-sm text-gray-600">
|
||||||
<div>
|
<Calendar className="mr-2 h-4 w-4" />
|
||||||
<CardTitle className="text-lg">{appointment.doctor.full_name}</CardTitle>
|
{new Date(appointment.scheduled_at).toLocaleDateString(
|
||||||
<CardDescription>{appointment.doctor.specialty}</CardDescription>
|
"pt-BR",
|
||||||
</div>
|
{ timeZone: "UTC" }
|
||||||
{getStatusBadge(appointment.status)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
<div className="flex items-center text-sm text-gray-600">
|
||||||
<CardContent>
|
<Clock className="mr-2 h-4 w-4" />
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
{new Date(appointment.scheduled_at).toLocaleTimeString(
|
||||||
<div className="space-y-3">
|
"pt-BR",
|
||||||
<div className="flex items-center text-sm text-gray-800 font-medium">
|
{
|
||||||
<User className="mr-2 h-4 w-4 text-gray-600" />
|
hour: "2-digit",
|
||||||
{appointment.patient.full_name}
|
minute: "2-digit",
|
||||||
</div>
|
timeZone: "UTC",
|
||||||
<div className="flex items-center text-sm text-gray-600">
|
}
|
||||||
<Calendar className="mr-2 h-4 w-4" />
|
)}
|
||||||
{new Date(appointment.scheduled_at).toLocaleDateString("pt-BR", { timeZone: "UTC" })}
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center text-sm text-gray-600">
|
<div className="space-y-3">
|
||||||
<Clock className="mr-2 h-4 w-4" />
|
<div className="flex items-center text-sm text-gray-600">
|
||||||
{new Date(appointment.scheduled_at).toLocaleTimeString("pt-BR", { hour: '2-digit', minute: '2-digit', timeZone: "UTC" })}
|
<MapPin className="mr-2 h-4 w-4" />
|
||||||
</div>
|
{appointment.doctor.location || "Local a definir"}
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-3">
|
<div className="flex items-center text-sm text-gray-600">
|
||||||
<div className="flex items-center text-sm text-gray-600">
|
<Phone className="mr-2 h-4 w-4" />
|
||||||
<MapPin className="mr-2 h-4 w-4" />
|
{appointment.doctor.phone || "N/A"}
|
||||||
{appointment.doctor.location || "Local a definir"}
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center text-sm text-gray-600">
|
</div>
|
||||||
<Phone className="mr-2 h-4 w-4" />
|
|
||||||
{appointment.doctor.phone || "N/A"}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex gap-2 mt-4 pt-4 border-t">
|
<div className="flex gap-2 mt-4 pt-4 border-t">
|
||||||
<Button variant="outline" size="sm" onClick={() => handleEdit(appointment)}>
|
<Button variant="outline" size="sm" onClick={() => handleEdit(appointment)}>
|
||||||
@ -216,15 +302,15 @@ export default function SecretaryAppointments() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* MODAL DE EDIÇÃO */}
|
{/* MODAL DE EDIÇÃO */}
|
||||||
<Dialog open={editModal} onOpenChange={setEditModal}>
|
<Dialog open={editModal} onOpenChange={setEditModal}>
|
||||||
{/* ... (código do modal de edição) ... */}
|
{/* ... (código do modal de edição) ... */}
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|
||||||
{/* Modal de Deleção */}
|
{/* Modal de Deleção */}
|
||||||
<Dialog open={deleteModal} onOpenChange={setDeleteModal}>
|
<Dialog open={deleteModal} onOpenChange={setDeleteModal}>
|
||||||
{/* ... (código do modal de deleção) ... */}
|
{/* ... (código do modal de deleção) ... */}
|
||||||
</Dialog>
|
</Dialog>
|
||||||
</SecretaryLayout>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,12 +1,11 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import SecretaryLayout from "@/components/secretary-layout";
|
|
||||||
import {
|
import {
|
||||||
Card,
|
Card,
|
||||||
CardContent,
|
CardContent,
|
||||||
CardDescription,
|
CardDescription,
|
||||||
CardHeader,
|
CardHeader,
|
||||||
CardTitle,
|
CardTitle,
|
||||||
} from "@/components/ui/card";
|
} from "@/components/ui/card";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Calendar, Clock, User, Plus } from "lucide-react";
|
import { Calendar, Clock, User, Plus } from "lucide-react";
|
||||||
@ -14,291 +13,293 @@ import Link from "next/link";
|
|||||||
import React, { useState, useEffect } from "react";
|
import React, { useState, useEffect } from "react";
|
||||||
import { patientsService } from "@/services/patientsApi.mjs";
|
import { patientsService } from "@/services/patientsApi.mjs";
|
||||||
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
||||||
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
export default function SecretaryDashboard() {
|
export default function SecretaryDashboard() {
|
||||||
// Estados
|
// Estados
|
||||||
const [patients, setPatients] = useState<any[]>([]);
|
const [patients, setPatients] = useState<any[]>([]);
|
||||||
const [loadingPatients, setLoadingPatients] = useState(true);
|
const [loadingPatients, setLoadingPatients] = useState(true);
|
||||||
|
|
||||||
const [firstConfirmed, setFirstConfirmed] = useState<any>(null);
|
const [firstConfirmed, setFirstConfirmed] = useState<any>(null);
|
||||||
const [nextAgendada, setNextAgendada] = useState<any>(null);
|
const [nextAgendada, setNextAgendada] = useState<any>(null);
|
||||||
const [loadingAppointments, setLoadingAppointments] = useState(true);
|
const [loadingAppointments, setLoadingAppointments] = useState(true);
|
||||||
|
|
||||||
// 🔹 Buscar pacientes
|
// 🔹 Buscar pacientes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
async function fetchPatients() {
|
async function fetchPatients() {
|
||||||
try {
|
try {
|
||||||
const data = await patientsService.list();
|
const data = await patientsService.list();
|
||||||
if (Array.isArray(data)) {
|
if (Array.isArray(data)) {
|
||||||
setPatients(data.slice(0, 3));
|
setPatients(data.slice(0, 3));
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Erro ao carregar pacientes:", error);
|
|
||||||
} finally {
|
|
||||||
setLoadingPatients(false);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
fetchPatients();
|
} catch (error) {
|
||||||
}, []);
|
console.error("Erro ao carregar pacientes:", error);
|
||||||
|
} finally {
|
||||||
|
setLoadingPatients(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fetchPatients();
|
||||||
|
}, []);
|
||||||
|
|
||||||
// 🔹 Buscar consultas (confirmadas + 1ª do mês)
|
// 🔹 Buscar consultas (confirmadas + 1ª do mês)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
async function fetchAppointments() {
|
async function fetchAppointments() {
|
||||||
try {
|
try {
|
||||||
const hoje = new Date();
|
const hoje = new Date();
|
||||||
const inicioMes = new Date(hoje.getFullYear(), hoje.getMonth(), 1);
|
const inicioMes = new Date(hoje.getFullYear(), hoje.getMonth(), 1);
|
||||||
const fimMes = new Date(hoje.getFullYear(), hoje.getMonth() + 1, 0);
|
const fimMes = new Date(hoje.getFullYear(), hoje.getMonth() + 1, 0);
|
||||||
|
|
||||||
// Mesmo parâmetro de ordenação da página /secretary/appointments
|
// Mesmo parâmetro de ordenação da página /secretary/appointments
|
||||||
const queryParams = "order=scheduled_at.desc";
|
const queryParams = "order=scheduled_at.desc";
|
||||||
const data = await appointmentsService.search_appointment(queryParams);
|
const data = await appointmentsService.search_appointment(queryParams);
|
||||||
|
|
||||||
if (!Array.isArray(data) || data.length === 0) {
|
if (!Array.isArray(data) || data.length === 0) {
|
||||||
setFirstConfirmed(null);
|
setFirstConfirmed(null);
|
||||||
setNextAgendada(null);
|
setNextAgendada(null);
|
||||||
return;
|
return;
|
||||||
}
|
|
||||||
|
|
||||||
// 🩵 1️⃣ Consultas confirmadas (para o card “Próxima Consulta Confirmada”)
|
|
||||||
const confirmadas = data.filter((apt: any) => {
|
|
||||||
const dataConsulta = new Date(apt.scheduled_at || apt.date);
|
|
||||||
return apt.status === "confirmed" && dataConsulta >= hoje;
|
|
||||||
});
|
|
||||||
|
|
||||||
confirmadas.sort(
|
|
||||||
(a: any, b: any) =>
|
|
||||||
new Date(a.scheduled_at || a.date).getTime() -
|
|
||||||
new Date(b.scheduled_at || b.date).getTime()
|
|
||||||
);
|
|
||||||
|
|
||||||
setFirstConfirmed(confirmadas[0] || null);
|
|
||||||
|
|
||||||
// 💙 2️⃣ Consultas deste mês — pegar sempre a 1ª (mais próxima)
|
|
||||||
const consultasMes = data.filter((apt: any) => {
|
|
||||||
const dataConsulta = new Date(apt.scheduled_at);
|
|
||||||
return dataConsulta >= inicioMes && dataConsulta <= fimMes;
|
|
||||||
});
|
|
||||||
|
|
||||||
if (consultasMes.length > 0) {
|
|
||||||
consultasMes.sort(
|
|
||||||
(a: any, b: any) =>
|
|
||||||
new Date(a.scheduled_at).getTime() -
|
|
||||||
new Date(b.scheduled_at).getTime()
|
|
||||||
);
|
|
||||||
setNextAgendada(consultasMes[0]);
|
|
||||||
} else {
|
|
||||||
setNextAgendada(null);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Erro ao carregar consultas:", error);
|
|
||||||
} finally {
|
|
||||||
setLoadingAppointments(false);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fetchAppointments();
|
// 🩵 1️⃣ Consultas confirmadas (para o card “Próxima Consulta Confirmada”)
|
||||||
}, []);
|
const confirmadas = data.filter((apt: any) => {
|
||||||
|
const dataConsulta = new Date(apt.scheduled_at || apt.date);
|
||||||
|
return apt.status === "confirmed" && dataConsulta >= hoje;
|
||||||
|
});
|
||||||
|
|
||||||
return (
|
confirmadas.sort(
|
||||||
<SecretaryLayout>
|
(a: any, b: any) =>
|
||||||
<div className="space-y-6">
|
new Date(a.scheduled_at || a.date).getTime() -
|
||||||
{/* Cabeçalho */}
|
new Date(b.scheduled_at || b.date).getTime()
|
||||||
<div>
|
);
|
||||||
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
|
|
||||||
<p className="text-gray-600">Bem-vindo ao seu portal de consultas médicas</p>
|
setFirstConfirmed(confirmadas[0] || null);
|
||||||
|
|
||||||
|
// 💙 2️⃣ Consultas deste mês — pegar sempre a 1ª (mais próxima)
|
||||||
|
const consultasMes = data.filter((apt: any) => {
|
||||||
|
const dataConsulta = new Date(apt.scheduled_at);
|
||||||
|
return dataConsulta >= inicioMes && dataConsulta <= fimMes;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (consultasMes.length > 0) {
|
||||||
|
consultasMes.sort(
|
||||||
|
(a: any, b: any) =>
|
||||||
|
new Date(a.scheduled_at).getTime() -
|
||||||
|
new Date(b.scheduled_at).getTime()
|
||||||
|
);
|
||||||
|
setNextAgendada(consultasMes[0]);
|
||||||
|
} else {
|
||||||
|
setNextAgendada(null);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Erro ao carregar consultas:", error);
|
||||||
|
} finally {
|
||||||
|
setLoadingAppointments(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchAppointments();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Sidebar>
|
||||||
|
<div className="space-y-6">
|
||||||
|
{/* Cabeçalho */}
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
|
||||||
|
<p className="text-gray-600">
|
||||||
|
Bem-vindo ao seu portal de consultas médicas
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Cards principais */}
|
||||||
|
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||||
|
{/* Próxima Consulta Confirmada */}
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||||
|
<CardTitle className="text-sm font-medium">
|
||||||
|
Próxima Consulta Confirmada
|
||||||
|
</CardTitle>
|
||||||
|
<Calendar className="h-4 w-4 text-muted-foreground" />
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{loadingAppointments ? (
|
||||||
|
<div className="text-gray-500 text-sm">
|
||||||
|
Carregando próxima consulta...
|
||||||
</div>
|
</div>
|
||||||
|
) : firstConfirmed ? (
|
||||||
{/* Cards principais */}
|
<>
|
||||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
<div className="text-2xl font-bold">
|
||||||
{/* Próxima Consulta Confirmada */}
|
{new Date(
|
||||||
<Card>
|
firstConfirmed.scheduled_at || firstConfirmed.date
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
).toLocaleDateString("pt-BR")}
|
||||||
<CardTitle className="text-sm font-medium">
|
</div>
|
||||||
Próxima Consulta Confirmada
|
<p className="text-xs text-muted-foreground">
|
||||||
</CardTitle>
|
{firstConfirmed.doctor_name
|
||||||
<Calendar className="h-4 w-4 text-muted-foreground" />
|
? `Dr(a). ${firstConfirmed.doctor_name}`
|
||||||
</CardHeader>
|
: "Médico não informado"}{" "}
|
||||||
<CardContent>
|
-{" "}
|
||||||
{loadingAppointments ? (
|
{new Date(firstConfirmed.scheduled_at).toLocaleTimeString(
|
||||||
<div className="text-gray-500 text-sm">
|
"pt-BR",
|
||||||
Carregando próxima consulta...
|
{
|
||||||
</div>
|
hour: "2-digit",
|
||||||
) : firstConfirmed ? (
|
minute: "2-digit",
|
||||||
<>
|
}
|
||||||
<div className="text-2xl font-bold">
|
)}
|
||||||
{new Date(
|
</p>
|
||||||
firstConfirmed.scheduled_at || firstConfirmed.date
|
</>
|
||||||
).toLocaleDateString("pt-BR")}
|
) : (
|
||||||
</div>
|
<div className="text-sm text-gray-500">
|
||||||
<p className="text-xs text-muted-foreground">
|
Nenhuma consulta confirmada encontrada
|
||||||
{firstConfirmed.doctor_name
|
|
||||||
? `Dr(a). ${firstConfirmed.doctor_name}`
|
|
||||||
: "Médico não informado"}{" "}
|
|
||||||
-{" "}
|
|
||||||
{new Date(
|
|
||||||
firstConfirmed.scheduled_at
|
|
||||||
).toLocaleTimeString("pt-BR", {
|
|
||||||
hour: "2-digit",
|
|
||||||
minute: "2-digit",
|
|
||||||
})}
|
|
||||||
</p>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<div className="text-sm text-gray-500">
|
|
||||||
Nenhuma consulta confirmada encontrada
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* Consultas Este Mês */}
|
|
||||||
<Card>
|
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
|
||||||
<CardTitle className="text-sm font-medium">
|
|
||||||
Consultas Este Mês
|
|
||||||
</CardTitle>
|
|
||||||
<Clock className="h-4 w-4 text-muted-foreground" />
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
{loadingAppointments ? (
|
|
||||||
<div className="text-gray-500 text-sm">
|
|
||||||
Carregando consultas...
|
|
||||||
</div>
|
|
||||||
) : nextAgendada ? (
|
|
||||||
<>
|
|
||||||
<div className="text-lg font-bold text-gray-900">
|
|
||||||
{new Date(
|
|
||||||
nextAgendada.scheduled_at
|
|
||||||
).toLocaleDateString("pt-BR", {
|
|
||||||
day: "2-digit",
|
|
||||||
month: "2-digit",
|
|
||||||
year: "numeric",
|
|
||||||
})}{" "}
|
|
||||||
às{" "}
|
|
||||||
{new Date(
|
|
||||||
nextAgendada.scheduled_at
|
|
||||||
).toLocaleTimeString("pt-BR", {
|
|
||||||
hour: "2-digit",
|
|
||||||
minute: "2-digit",
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
{nextAgendada.doctor_name
|
|
||||||
? `Dr(a). ${nextAgendada.doctor_name}`
|
|
||||||
: "Médico não informado"}
|
|
||||||
</p>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
{nextAgendada.patient_name
|
|
||||||
? `Paciente: ${nextAgendada.patient_name}`
|
|
||||||
: ""}
|
|
||||||
</p>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<div className="text-sm text-gray-500">
|
|
||||||
Nenhuma consulta agendada neste mês
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* Perfil */}
|
|
||||||
<Card>
|
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
|
||||||
<CardTitle className="text-sm font-medium">Perfil</CardTitle>
|
|
||||||
<User className="h-4 w-4 text-muted-foreground" />
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<div className="text-2xl font-bold">100%</div>
|
|
||||||
<p className="text-xs text-muted-foreground">Dados completos</p>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
{/* Cards Secundários */}
|
{/* Consultas Este Mês */}
|
||||||
<div className="grid md:grid-cols-2 gap-6">
|
<Card>
|
||||||
{/* Ações rápidas */}
|
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||||
<Card>
|
<CardTitle className="text-sm font-medium">
|
||||||
<CardHeader>
|
Consultas Este Mês
|
||||||
<CardTitle>Ações Rápidas</CardTitle>
|
</CardTitle>
|
||||||
<CardDescription>
|
<Clock className="h-4 w-4 text-muted-foreground" />
|
||||||
Acesse rapidamente as principais funcionalidades
|
</CardHeader>
|
||||||
</CardDescription>
|
<CardContent>
|
||||||
</CardHeader>
|
{loadingAppointments ? (
|
||||||
<CardContent className="space-y-4">
|
<div className="text-gray-500 text-sm">
|
||||||
<Link href="/secretary/schedule">
|
Carregando consultas...
|
||||||
<Button className="w-full justify-start">
|
|
||||||
<Plus className="mr-2 h-4 w-4" />
|
|
||||||
Agendar Nova Consulta
|
|
||||||
</Button>
|
|
||||||
</Link>
|
|
||||||
<Link href="/secretary/appointments">
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
className="w-full justify-start bg-transparent"
|
|
||||||
>
|
|
||||||
<Calendar className="mr-2 h-4 w-4" />
|
|
||||||
Ver Consultas
|
|
||||||
</Button>
|
|
||||||
</Link>
|
|
||||||
<Link href="/secretary/pacientes">
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
className="w-full justify-start bg-transparent"
|
|
||||||
>
|
|
||||||
<User className="mr-2 h-4 w-4" />
|
|
||||||
Gerenciar Pacientes
|
|
||||||
</Button>
|
|
||||||
</Link>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* Pacientes */}
|
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle>Pacientes</CardTitle>
|
|
||||||
<CardDescription>
|
|
||||||
Últimos pacientes cadastrados
|
|
||||||
</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
{loadingPatients ? (
|
|
||||||
<p className="text-sm text-gray-500">
|
|
||||||
Carregando pacientes...
|
|
||||||
</p>
|
|
||||||
) : patients.length === 0 ? (
|
|
||||||
<p className="text-sm text-gray-500">
|
|
||||||
Nenhum paciente cadastrado.
|
|
||||||
</p>
|
|
||||||
) : (
|
|
||||||
<div className="space-y-4">
|
|
||||||
{patients.map((patient, index) => (
|
|
||||||
<div
|
|
||||||
key={index}
|
|
||||||
className="flex items-center justify-between p-3 bg-blue-50 rounded-lg border border-blue-100"
|
|
||||||
>
|
|
||||||
<div>
|
|
||||||
<p className="font-medium text-gray-900">
|
|
||||||
{patient.full_name || "Sem nome"}
|
|
||||||
</p>
|
|
||||||
<p className="text-sm text-gray-600">
|
|
||||||
{patient.phone_mobile ||
|
|
||||||
patient.phone1 ||
|
|
||||||
"Sem telefone"}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className="text-right">
|
|
||||||
<p className="font-medium text-blue-700">
|
|
||||||
{patient.convenio || "Particular"}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
) : nextAgendada ? (
|
||||||
</SecretaryLayout>
|
<>
|
||||||
);
|
<div className="text-lg font-bold text-gray-900">
|
||||||
|
{new Date(nextAgendada.scheduled_at).toLocaleDateString(
|
||||||
|
"pt-BR",
|
||||||
|
{
|
||||||
|
day: "2-digit",
|
||||||
|
month: "2-digit",
|
||||||
|
year: "numeric",
|
||||||
|
}
|
||||||
|
)}{" "}
|
||||||
|
às{" "}
|
||||||
|
{new Date(nextAgendada.scheduled_at).toLocaleTimeString(
|
||||||
|
"pt-BR",
|
||||||
|
{
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
}
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{nextAgendada.doctor_name
|
||||||
|
? `Dr(a). ${nextAgendada.doctor_name}`
|
||||||
|
: "Médico não informado"}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{nextAgendada.patient_name
|
||||||
|
? `Paciente: ${nextAgendada.patient_name}`
|
||||||
|
: ""}
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<div className="text-sm text-gray-500">
|
||||||
|
Nenhuma consulta agendada neste mês
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Perfil */}
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||||
|
<CardTitle className="text-sm font-medium">Perfil</CardTitle>
|
||||||
|
<User className="h-4 w-4 text-muted-foreground" />
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="text-2xl font-bold">100%</div>
|
||||||
|
<p className="text-xs text-muted-foreground">Dados completos</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Cards Secundários */}
|
||||||
|
<div className="grid md:grid-cols-2 gap-6">
|
||||||
|
{/* Ações rápidas */}
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Ações Rápidas</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Acesse rapidamente as principais funcionalidades
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
<Link href="/secretary/schedule">
|
||||||
|
<Button className="w-full justify-start bg-blue-600 text-white hover:bg-blue-700">
|
||||||
|
<User className="mr-2 h-4 w-4 text-white" />
|
||||||
|
Agendar Nova Consulta
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
<Link href="/secretary/appointments">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="w-full justify-start bg-transparent"
|
||||||
|
>
|
||||||
|
<Calendar className="mr-2 h-4 w-4" />
|
||||||
|
Ver Consultas
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
<Link href="/secretary/pacientes">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="w-full justify-start bg-transparent"
|
||||||
|
>
|
||||||
|
<User className="mr-2 h-4 w-4" />
|
||||||
|
Gerenciar Pacientes
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Pacientes */}
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Pacientes</CardTitle>
|
||||||
|
<CardDescription>Últimos pacientes cadastrados</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{loadingPatients ? (
|
||||||
|
<p className="text-sm text-gray-500">Carregando pacientes...</p>
|
||||||
|
) : patients.length === 0 ? (
|
||||||
|
<p className="text-sm text-gray-500">
|
||||||
|
Nenhum paciente cadastrado.
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{patients.map((patient, index) => (
|
||||||
|
<div
|
||||||
|
key={index}
|
||||||
|
className="flex items-center justify-between p-3 bg-blue-50 rounded-lg border border-blue-100"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<p className="font-medium text-gray-900">
|
||||||
|
{patient.full_name || "Sem nome"}
|
||||||
|
</p>
|
||||||
|
<p className="text-sm text-gray-600">
|
||||||
|
{patient.phone_mobile ||
|
||||||
|
patient.phone1 ||
|
||||||
|
"Sem telefone"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="text-right">
|
||||||
|
<p className="font-medium text-blue-700">
|
||||||
|
{patient.convenio || "Particular"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Sidebar>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -13,9 +13,8 @@ import { Checkbox } from "@/components/ui/checkbox";
|
|||||||
import { ArrowLeft, Save, Trash2, Paperclip, Upload } from "lucide-react";
|
import { ArrowLeft, Save, Trash2, Paperclip, Upload } from "lucide-react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { useToast } from "@/hooks/use-toast";
|
import { useToast } from "@/hooks/use-toast";
|
||||||
import SecretaryLayout from "@/components/secretary-layout";
|
|
||||||
import { patientsService } from "@/services/patientsApi.mjs";
|
import { patientsService } from "@/services/patientsApi.mjs";
|
||||||
import { json } from "stream/consumers";
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
export default function EditarPacientePage() {
|
export default function EditarPacientePage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@ -81,6 +80,12 @@ export default function EditarPacientePage() {
|
|||||||
heightM?: string;
|
heightM?: string;
|
||||||
bmi?: string;
|
bmi?: string;
|
||||||
bloodType?: string;
|
bloodType?: string;
|
||||||
|
// Adicionei os campos do convênio para o tipo FormData
|
||||||
|
convenio?: string;
|
||||||
|
plano?: string;
|
||||||
|
numeroMatricula?: string;
|
||||||
|
validadeCarteira?: string;
|
||||||
|
alergias?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
@ -133,6 +138,11 @@ export default function EditarPacientePage() {
|
|||||||
heightM: "",
|
heightM: "",
|
||||||
bmi: "",
|
bmi: "",
|
||||||
bloodType: "",
|
bloodType: "",
|
||||||
|
convenio: "",
|
||||||
|
plano: "",
|
||||||
|
numeroMatricula: "",
|
||||||
|
validadeCarteira: "",
|
||||||
|
alergias: "",
|
||||||
});
|
});
|
||||||
|
|
||||||
const [isGuiaConvenio, setIsGuiaConvenio] = useState(false);
|
const [isGuiaConvenio, setIsGuiaConvenio] = useState(false);
|
||||||
@ -141,7 +151,7 @@ export default function EditarPacientePage() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
async function fetchPatient() {
|
async function fetchPatient() {
|
||||||
try {
|
try {
|
||||||
const res = await patientsService.getById(patientId);
|
const res = await patientsService.getById(patientId);
|
||||||
// Map API snake_case/nested to local camelCase form
|
// Map API snake_case/nested to local camelCase form
|
||||||
setFormData({
|
setFormData({
|
||||||
id: res[0]?.id ?? "",
|
id: res[0]?.id ?? "",
|
||||||
@ -192,6 +202,12 @@ export default function EditarPacientePage() {
|
|||||||
heightM: res[0]?.height_m ? String(res[0].height_m) : "",
|
heightM: res[0]?.height_m ? String(res[0].height_m) : "",
|
||||||
bmi: res[0]?.bmi ? String(res[0].bmi) : "",
|
bmi: res[0]?.bmi ? String(res[0].bmi) : "",
|
||||||
bloodType: res[0]?.blood_type ?? "",
|
bloodType: res[0]?.blood_type ?? "",
|
||||||
|
// Os campos de convênio e alergias não vêm da API, então os deixamos vazios ou com valores padrão
|
||||||
|
convenio: "",
|
||||||
|
plano: "",
|
||||||
|
numeroMatricula: "",
|
||||||
|
validadeCarteira: "",
|
||||||
|
alergias: "",
|
||||||
});
|
});
|
||||||
|
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
@ -238,8 +254,8 @@ export default function EditarPacientePage() {
|
|||||||
router.push("/secretary/pacientes");
|
router.push("/secretary/pacientes");
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
console.error("Erro ao atualizar paciente:", err);
|
console.error("Erro ao atualizar paciente:", err);
|
||||||
toast({
|
toast({
|
||||||
title: "Erro",
|
title: "Erro",
|
||||||
description: err?.message || "Não foi possível atualizar o paciente",
|
description: err?.message || "Não foi possível atualizar o paciente",
|
||||||
variant: "destructive"
|
variant: "destructive"
|
||||||
});
|
});
|
||||||
@ -247,67 +263,46 @@ export default function EditarPacientePage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SecretaryLayout>
|
<Sidebar>
|
||||||
<div className="space-y-6">
|
{/* O espaçamento foi reduzido aqui: de `p-4 sm:p-6 lg:p-8` para `p-2 sm:p-4 lg:p-6` */}
|
||||||
<div className="flex items-center gap-4">
|
<div className="space-y-6 p-2 sm:p-4 lg:p-6 max-w-10xl mx-auto"> {/* Alterado padding responsivo */}
|
||||||
<Link href="/secretary/pacientes">
|
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
|
||||||
<Button variant="ghost" size="sm">
|
<div className="flex items-center gap-4">
|
||||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
<Link href="/secretary/pacientes">
|
||||||
Voltar
|
<Button variant="ghost" size="sm">
|
||||||
</Button>
|
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||||
</Link>
|
Voltar
|
||||||
<div>
|
</Button>
|
||||||
<h1 className="text-2xl font-bold text-gray-900">Editar Paciente</h1>
|
</Link>
|
||||||
<p className="text-gray-600">Atualize as informações do paciente</p>
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold text-gray-900">Editar Paciente</h1>
|
||||||
|
<p className="text-gray-600">Atualize as informações do paciente</p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Anexos Section */}
|
{/* Anexos Section - Movido para fora do cabeçalho para melhor organização e responsividade */}
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Anexos</h2>
|
|
||||||
<div className="flex items-center gap-3 mb-4">
|
|
||||||
<input ref={anexoInputRef} type="file" className="hidden" />
|
|
||||||
<Button type="button" variant="outline" disabled={isUploadingAnexo}>
|
|
||||||
<Paperclip className="w-4 h-4 mr-2" /> {isUploadingAnexo ? "Enviando..." : "Adicionar anexo"}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
{anexos.length === 0 ? (
|
|
||||||
<p className="text-sm text-gray-500">Nenhum anexo encontrado.</p>
|
|
||||||
) : (
|
|
||||||
<ul className="divide-y">
|
|
||||||
{anexos.map((a) => (
|
|
||||||
<li key={a.id} className="flex items-center justify-between py-2">
|
|
||||||
<div className="flex items-center gap-2 min-w-0">
|
|
||||||
<Paperclip className="w-4 h-4 text-gray-500 shrink-0" />
|
|
||||||
<span className="text-sm text-gray-800 truncate">{a.nome || a.filename || `Anexo ${a.id}`}</span>
|
|
||||||
</div>
|
|
||||||
<Button type="button" variant="ghost" className="text-red-600">
|
|
||||||
<Trash2 className="w-4 h-4 mr-1" /> Remover
|
|
||||||
</Button>
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<form onSubmit={handleSubmit} className="space-y-8">
|
<form onSubmit={handleSubmit} className="space-y-8">
|
||||||
|
{/* Dados Pessoais Section */}
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Dados Pessoais</h2>
|
<h2 className="text-lg font-semibold text-gray-900 mb-6">Dados Pessoais</h2>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||||
{/* Photo upload */}
|
{/* Photo upload */}
|
||||||
<div className="space-y-2">
|
<div className="space-y-2 col-span-1 md:col-span-2 lg:col-span-1">
|
||||||
<Label>Foto do paciente</Label>
|
<Label>Foto do paciente</Label>
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex flex-col sm:flex-row items-center gap-4">
|
||||||
<div className="w-20 h-20 rounded-full bg-gray-100 overflow-hidden flex items-center justify-center">
|
<div className="w-20 h-20 rounded-full bg-gray-100 overflow-hidden flex items-center justify-center">
|
||||||
{photoUrl ? (
|
{photoUrl ? (
|
||||||
// eslint-disable-next-line @next/next/no-img-element
|
// eslint-disable-next-line @next/next/no-img-element
|
||||||
<img src={photoUrl} alt="Foto do paciente" className="w-full h-full object-cover" />
|
<img src={photoUrl} alt="Foto do paciente" className="w-full h-full object-cover" />
|
||||||
) : (
|
) : (
|
||||||
<span className="text-gray-400 text-sm">Sem foto</span>
|
<span className="text-gray-400 text-sm text-center">Sem foto</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex gap-2">
|
<div className="flex flex-col sm:flex-row gap-2 mt-2 sm:mt-0">
|
||||||
<input ref={fileInputRef} type="file" accept="image/*" className="hidden" />
|
<input ref={fileInputRef} type="file" accept="image/*" className="hidden" />
|
||||||
<Button type="button" variant="outline" disabled={isUploadingPhoto}>
|
<Button type="button" variant="outline" disabled={isUploadingPhoto}>
|
||||||
{isUploadingPhoto ? "Enviando..." : "Enviar foto"}
|
{isUploadingPhoto ? "Enviando..." : "Enviar foto"}
|
||||||
@ -337,7 +332,7 @@ export default function EditarPacientePage() {
|
|||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label>Sexo *</Label>
|
<Label>Sexo *</Label>
|
||||||
<div className="flex gap-4">
|
<div className="flex flex-col sm:flex-row gap-4">
|
||||||
<div className="flex items-center space-x-2">
|
<div className="flex items-center space-x-2">
|
||||||
<input type="radio" id="Masculino" name="sexo" value="Masculino" checked={formData.sexo === "Masculino"} onChange={(e) => handleInputChange("sexo", e.target.value)} className="w-4 h-4 text-blue-600" />
|
<input type="radio" id="Masculino" name="sexo" value="Masculino" checked={formData.sexo === "Masculino"} onChange={(e) => handleInputChange("sexo", e.target.value)} className="w-4 h-4 text-blue-600" />
|
||||||
<Label htmlFor="Masculino">Masculino</Label>
|
<Label htmlFor="Masculino">Masculino</Label>
|
||||||
@ -404,7 +399,7 @@ export default function EditarPacientePage() {
|
|||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="profissao">Profissão</Label>
|
<Label htmlFor="profissao">Profissão</Label>
|
||||||
<Input id="profissao" value={formData.profession} onChange={(e) => handleInputChange("profession", e.target.value)} />
|
<Input id="profissao" value={formData.profession} onChange={(e) => handleInputChange("profissao", e.target.value)} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
@ -478,12 +473,12 @@ export default function EditarPacientePage() {
|
|||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="email">E-mail *</Label>
|
<Label htmlFor="email">E-mail *</Label>
|
||||||
<Input id="email" type="email" value={formData.email} onChange={(e) => handleInputChange("email", e.target.value)} required/>
|
<Input id="email" type="email" value={formData.email} onChange={(e) => handleInputChange("email", e.target.value)} required />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="celular">Celular *</Label>
|
<Label htmlFor="celular">Celular *</Label>
|
||||||
<Input id="celular" value={formData.phoneMobile} onChange={(e) => handleInputChange("phoneMobile", e.target.value)} placeholder="(00) 00000-0000" required/>
|
<Input id="celular" value={formData.phoneMobile} onChange={(e) => handleInputChange("phoneMobile", e.target.value)} placeholder="(00) 00000-0000" required />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
@ -615,7 +610,7 @@ export default function EditarPacientePage() {
|
|||||||
|
|
||||||
<div className="mt-6">
|
<div className="mt-6">
|
||||||
<Label htmlFor="alergias">Alergias</Label>
|
<Label htmlFor="alergias">Alergias</Label>
|
||||||
<Textarea id="alergias" onChange={(e) => handleInputChange("alergias", e.target.value)} placeholder="Ex: AAS, Dipirona, etc." className="mt-2" />
|
<Textarea id="alergias" value={formData.alergias} onChange={(e) => handleInputChange("alergias", e.target.value)} placeholder="Ex: AAS, Dipirona, etc." className="mt-2" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@ -626,7 +621,7 @@ export default function EditarPacientePage() {
|
|||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="convenio">Convênio</Label>
|
<Label htmlFor="convenio">Convênio</Label>
|
||||||
<Select onValueChange={(value) => handleInputChange("convenio", value)}>
|
<Select value={formData.convenio} onValueChange={(value) => handleInputChange("convenio", value)}>
|
||||||
<SelectTrigger>
|
<SelectTrigger>
|
||||||
<SelectValue placeholder="Selecione" />
|
<SelectValue placeholder="Selecione" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
@ -642,17 +637,17 @@ export default function EditarPacientePage() {
|
|||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="plano">Plano</Label>
|
<Label htmlFor="plano">Plano</Label>
|
||||||
<Input id="plano" onChange={(e) => handleInputChange("plano", e.target.value)} />
|
<Input id="plano" value={formData.plano} onChange={(e) => handleInputChange("plano", e.target.value)} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="numeroMatricula">Nº de matrícula</Label>
|
<Label htmlFor="numeroMatricula">Nº de matrícula</Label>
|
||||||
<Input id="numeroMatricula" onChange={(e) => handleInputChange("numeroMatricula", e.target.value)} />
|
<Input id="numeroMatricula" value={formData.numeroMatricula} onChange={(e) => handleInputChange("numeroMatricula", e.target.value)} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="validadeCarteira">Validade da Carteira</Label>
|
<Label htmlFor="validadeCarteira">Validade da Carteira</Label>
|
||||||
<Input id="validadeCarteira" type="date" onChange={(e) => handleInputChange("validadeCarteira", e.target.value)} disabled={validadeIndeterminada} />
|
<Input id="validadeCarteira" type="date" value={formData.validadeCarteira} onChange={(e) => handleInputChange("validadeCarteira", e.target.value)} disabled={validadeIndeterminada} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@ -664,19 +659,19 @@ export default function EditarPacientePage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex justify-end gap-4">
|
<div className="flex flex-col sm:flex-row justify-end gap-4">
|
||||||
<Link href="/secretary/pacientes">
|
<Link href="/secretary/pacientes">
|
||||||
<Button type="button" variant="outline">
|
<Button type="button" variant="outline" className="w-full sm:w-auto">
|
||||||
Cancelar
|
Cancelar
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
<Button type="submit" className="bg-blue-600 hover:bg-blue-700">
|
<Button type="submit" className="bg-blue-600 hover:bg-blue-700 w-full sm:w-auto">
|
||||||
<Save className="w-4 h-4 mr-2" />
|
<Save className="w-4 h-4 mr-2" />
|
||||||
Salvar Alterações
|
Salvar Alterações
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</SecretaryLayout>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -1,4 +1,3 @@
|
|||||||
// Caminho: app/(manager)/usuario/novo/page.tsx
|
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
@ -7,13 +6,9 @@ import Link from "next/link";
|
|||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
// O Select foi removido pois não é mais necessário
|
|
||||||
import { Save, Loader2 } from "lucide-react";
|
import { Save, Loader2 } from "lucide-react";
|
||||||
import ManagerLayout from "@/components/manager-layout";
|
|
||||||
// Os imports originais foram mantidos, como solicitado
|
|
||||||
import { usersService } from "services/usersApi.mjs";
|
import { usersService } from "services/usersApi.mjs";
|
||||||
import { doctorsService } from "services/doctorsApi.mjs";
|
import Sidebar from "@/components/Sidebar";
|
||||||
import { login } from "services/api.mjs";
|
|
||||||
|
|
||||||
// Interface simplificada para refletir apenas os campos necessários
|
// Interface simplificada para refletir apenas os campos necessários
|
||||||
interface UserFormData {
|
interface UserFormData {
|
||||||
@ -97,19 +92,23 @@ export default function NovoUsuarioPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ManagerLayout>
|
<Sidebar>
|
||||||
<div className="w-full h-full p-4 md:p-8 flex justify-center items-start">
|
{/* Container principal com padding responsivo e centralização */}
|
||||||
<div className="w-full max-w-screen-lg space-y-8">
|
<div className="w-full h-full p-4 md:p-8 lg:p-12 flex justify-center items-start">
|
||||||
<div className="flex items-center justify-between border-b pb-4">
|
{/* Conteúdo do formulário com largura máxima para telas maiores */}
|
||||||
|
<div className="w-full max-w-screen-md lg:max-w-screen-lg space-y-8">
|
||||||
|
{/* Cabeçalho da página */}
|
||||||
|
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between border-b pb-4 gap-4"> {/* Ajustado para empilhar em telas pequenas */}
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-extrabold text-gray-900">Novo Usuário</h1>
|
<h1 className="text-2xl sm:text-3xl font-extrabold text-gray-900">Novo Usuário</h1> {/* Tamanho de texto responsivo */}
|
||||||
<p className="text-md text-gray-500">Preencha os dados para cadastrar um novo usuário no sistema.</p>
|
<p className="text-sm sm:text-md text-gray-500">Preencha os dados para cadastrar um novo usuário no sistema.</p> {/* Tamanho de texto responsivo */}
|
||||||
</div>
|
</div>
|
||||||
<Link href="/manager/usuario">
|
<Link href="/manager/usuario">
|
||||||
<Button variant="outline">Cancelar</Button>
|
<Button variant="outline" className="w-full sm:w-auto">Cancelar</Button> {/* Botão ocupa largura total em telas pequenas */}
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Formulário */}
|
||||||
<form onSubmit={handleSubmit} className="space-y-6 bg-white p-6 md:p-10 border rounded-xl shadow-lg">
|
<form onSubmit={handleSubmit} className="space-y-6 bg-white p-6 md:p-10 border rounded-xl shadow-lg">
|
||||||
{error && (
|
{error && (
|
||||||
<div className="p-4 bg-red-50 text-red-700 rounded-lg border border-red-300">
|
<div className="p-4 bg-red-50 text-red-700 rounded-lg border border-red-300">
|
||||||
@ -118,8 +117,9 @@ export default function NovoUsuarioPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Campos do formulário em grid responsivo */}
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||||
<div className="space-y-2 md:col-span-2">
|
<div className="space-y-2 md:col-span-2"> {/* Nome Completo ocupa 2 colunas em telas maiores */}
|
||||||
<Label htmlFor="nomeCompleto">Nome Completo *</Label>
|
<Label htmlFor="nomeCompleto">Nome Completo *</Label>
|
||||||
<Input id="nomeCompleto" value={formData.nomeCompleto} onChange={(e) => handleInputChange("nomeCompleto", e.target.value)} placeholder="Nome e Sobrenome" required />
|
<Input id="nomeCompleto" value={formData.nomeCompleto} onChange={(e) => handleInputChange("nomeCompleto", e.target.value)} placeholder="Nome e Sobrenome" required />
|
||||||
</div>
|
</div>
|
||||||
@ -129,7 +129,10 @@ export default function NovoUsuarioPage() {
|
|||||||
<Input id="email" type="email" value={formData.email} onChange={(e) => handleInputChange("email", e.target.value)} placeholder="exemplo@dominio.com" required />
|
<Input id="email" type="email" value={formData.email} onChange={(e) => handleInputChange("email", e.target.value)} placeholder="exemplo@dominio.com" required />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* O seletor de Papel (Função) foi removido */}
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="telefone">Telefone</Label>
|
||||||
|
<Input id="telefone" value={formData.telefone} onChange={(e) => handleInputChange("telefone", e.target.value)} placeholder="(00) 00000-0000" maxLength={15} />
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="senha">Senha *</Label>
|
<Label htmlFor="senha">Senha *</Label>
|
||||||
@ -141,25 +144,21 @@ export default function NovoUsuarioPage() {
|
|||||||
<Input id="confirmarSenha" type="password" value={formData.confirmarSenha} onChange={(e) => handleInputChange("confirmarSenha", e.target.value)} placeholder="Repita a senha" required />
|
<Input id="confirmarSenha" type="password" value={formData.confirmarSenha} onChange={(e) => handleInputChange("confirmarSenha", e.target.value)} placeholder="Repita a senha" required />
|
||||||
{formData.senha && formData.confirmarSenha && formData.senha !== formData.confirmarSenha && <p className="text-xs text-red-500">As senhas não coincidem.</p>}
|
{formData.senha && formData.confirmarSenha && formData.senha !== formData.confirmarSenha && <p className="text-xs text-red-500">As senhas não coincidem.</p>}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2 md:col-span-2"> {/* CPF ocupa 2 colunas em telas maiores */}
|
||||||
<Label htmlFor="telefone">Telefone</Label>
|
<Label htmlFor="cpf">CPF *</Label>
|
||||||
<Input id="telefone" value={formData.telefone} onChange={(e) => handleInputChange("telefone", e.target.value)} placeholder="(00) 00000-0000" maxLength={15} />
|
<Input id="cpf" value={formData.cpf} onChange={(e) => handleInputChange("cpf", e.target.value)} placeholder="xxx.xxx.xxx-xx" required />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
{/* Botões de ação */}
|
||||||
<Label htmlFor="cpf">Cpf *</Label>
|
<div className="flex flex-col sm:flex-row justify-end gap-4 pt-6 border-t mt-6"> {/* Botões empilhados em telas pequenas */}
|
||||||
<Input id="cpf" value={formData.cpf} onChange={(e) => handleInputChange("cpf", e.target.value)} placeholder="xxx.xxx.xxx-xx" required />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex justify-end gap-4 pt-6 border-t mt-6">
|
|
||||||
<Link href="/manager/usuario">
|
<Link href="/manager/usuario">
|
||||||
<Button type="button" variant="outline" disabled={isSaving}>
|
<Button type="button" variant="outline" disabled={isSaving} className="w-full sm:w-auto">
|
||||||
Cancelar
|
Cancelar
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
<Button type="submit" className="bg-green-600 hover:bg-green-700" disabled={isSaving}>
|
<Button type="submit" className="bg-green-600 hover:bg-green-700 w-full sm:w-auto" disabled={isSaving}>
|
||||||
{isSaving ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Save className="w-4 h-4 mr-2" />}
|
{isSaving ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Save className="w-4 h-4 mr-2" />}
|
||||||
{isSaving ? "Salvando..." : "Salvar Usuário"}
|
{isSaving ? "Salvando..." : "Salvar Usuário"}
|
||||||
</Button>
|
</Button>
|
||||||
@ -167,6 +166,6 @@ export default function NovoUsuarioPage() {
|
|||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</ManagerLayout>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -10,6 +10,7 @@ import { Plus, Edit, Trash2, Eye, Calendar, Filter, Loader2, MoreVertical } from
|
|||||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||||
import SecretaryLayout from "@/components/secretary-layout";
|
import SecretaryLayout from "@/components/secretary-layout";
|
||||||
import { patientsService } from "@/services/patientsApi.mjs";
|
import { patientsService } from "@/services/patientsApi.mjs";
|
||||||
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
// Defina o tamanho da página.
|
// Defina o tamanho da página.
|
||||||
const PAGE_SIZE = 5;
|
const PAGE_SIZE = 5;
|
||||||
@ -69,16 +70,14 @@ export default function PacientesPage() {
|
|||||||
status: p.status ?? undefined,
|
status: p.status ?? undefined,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
setAllPatients(mapped);
|
setAllPatients(mapped);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
setError(e?.message || "Erro ao buscar pacientes");
|
setError(e?.message || "Erro ao buscar pacientes");
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
},
|
}, []);
|
||||||
[]
|
|
||||||
);
|
|
||||||
|
|
||||||
// 2. Efeito para aplicar filtros e calcular a lista filtrada (chama-se quando allPatients ou filtros mudam)
|
// 2. Efeito para aplicar filtros e calcular a lista filtrada (chama-se quando allPatients ou filtros mudam)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@ -107,12 +106,11 @@ export default function PacientesPage() {
|
|||||||
setPage(1);
|
setPage(1);
|
||||||
}, [allPatients, searchTerm, convenioFilter, vipFilter]);
|
}, [allPatients, searchTerm, convenioFilter, vipFilter]);
|
||||||
|
|
||||||
// 3. Efeito inicial para buscar os pacientes
|
// 3. Efeito inicial para buscar os pacientes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchAllPacientes();
|
fetchAllPacientes();
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
|
||||||
// --- LÓGICA DE AÇÕES (DELETAR / VER DETALHES) ---
|
// --- LÓGICA DE AÇÕES (DELETAR / VER DETALHES) ---
|
||||||
|
|
||||||
@ -127,41 +125,47 @@ export default function PacientesPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDeletePatient = async (patientId: string) => {
|
const handleDeletePatient = async (patientId: string) => {
|
||||||
try {
|
try {
|
||||||
await patientsService.delete(patientId);
|
await patientsService.delete(patientId);
|
||||||
// Atualiza a lista completa para refletir a exclusão
|
// Atualiza a lista completa para refletir a exclusão
|
||||||
setAllPatients((prev) => prev.filter((p) => String(p.id) !== String(patientId)));
|
setAllPatients((prev) =>
|
||||||
} catch (e: any) {
|
prev.filter((p) => String(p.id) !== String(patientId))
|
||||||
alert(`Erro ao deletar paciente: ${e?.message || 'Erro desconhecido'}`);
|
);
|
||||||
}
|
} catch (e: any) {
|
||||||
setDeleteDialogOpen(false);
|
alert(`Erro ao deletar paciente: ${e?.message || "Erro desconhecido"}`);
|
||||||
setPatientToDelete(null);
|
}
|
||||||
};
|
setDeleteDialogOpen(false);
|
||||||
|
setPatientToDelete(null);
|
||||||
|
};
|
||||||
|
|
||||||
const openDeleteDialog = (patientId: string) => {
|
const openDeleteDialog = (patientId: string) => {
|
||||||
setPatientToDelete(patientId);
|
setPatientToDelete(patientId);
|
||||||
setDeleteDialogOpen(true);
|
setDeleteDialogOpen(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SecretaryLayout>
|
<Sidebar>
|
||||||
<div className="space-y-6 px-2 sm:px-4 md:px-8">
|
<div className="space-y-6 px-2 sm:px-4 md:px-8">
|
||||||
{/* Header (Responsividade OK) */}
|
{/* Header (Responsividade OK) */}
|
||||||
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-xl md:text-2xl font-bold text-foreground">Pacientes</h1>
|
<h1 className="text-xl md:text-2xl font-bold text-foreground">
|
||||||
<p className="text-muted-foreground text-sm md:text-base">Gerencie as informações de seus pacientes</p>
|
Pacientes
|
||||||
</div>
|
</h1>
|
||||||
<div className="flex gap-2">
|
<p className="text-muted-foreground text-sm md:text-base">
|
||||||
<Link href="/secretary/pacientes/novo" className="w-full md:w-auto">
|
Gerencie as informações de seus pacientes
|
||||||
<Button className="w-full bg-green-600 hover:bg-green-700">
|
</p>
|
||||||
<Plus className="w-4 h-4 mr-2" />
|
</div>
|
||||||
Adicionar
|
<div className="flex gap-2">
|
||||||
</Button>
|
<Link href="/secretary/pacientes/novo" className="w-full md:w-auto">
|
||||||
</Link>
|
<Button className="w-full bg-blue-600 hover:bg-blue-700">
|
||||||
</div>
|
<Plus className="w-4 h-4 mr-2" />
|
||||||
</div>
|
Adicionar
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Bloco de Filtros (Responsividade APLICADA) */}
|
{/* Bloco de Filtros (Responsividade APLICADA) */}
|
||||||
<div className="flex flex-wrap items-center gap-4 bg-card p-4 rounded-lg border border-border">
|
<div className="flex flex-wrap items-center gap-4 bg-card p-4 rounded-lg border border-border">
|
||||||
@ -176,28 +180,32 @@ export default function PacientesPage() {
|
|||||||
className="w-full sm:flex-grow sm:min-w-[150px] p-2 border rounded-md text-sm"
|
className="w-full sm:flex-grow sm:min-w-[150px] p-2 border rounded-md text-sm"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Convênio - Ocupa metade da linha no mobile */}
|
{/* Convênio - Ocupa a largura total em telas pequenas, depois se ajusta */}
|
||||||
<div className="flex items-center gap-2 w-[calc(50%-8px)] sm:w-auto sm:flex-grow sm:max-w-[200px]">
|
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[200px]">
|
||||||
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">Convênio</span>
|
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">
|
||||||
<Select value={convenioFilter} onValueChange={setConvenioFilter}>
|
Convênio
|
||||||
<SelectTrigger className="w-full sm:w-40">
|
</span>
|
||||||
<SelectValue placeholder="Convênio" />
|
<Select value={convenioFilter} onValueChange={setConvenioFilter}>
|
||||||
</SelectTrigger>
|
<SelectTrigger className="w-full sm:w-40">
|
||||||
<SelectContent>
|
{" "}
|
||||||
<SelectItem value="all">Todos</SelectItem>
|
{/* w-full para mobile, w-40 para sm+ */}
|
||||||
<SelectItem value="Particular">Particular</SelectItem>
|
<SelectValue placeholder="Convênio" />
|
||||||
<SelectItem value="SUS">SUS</SelectItem>
|
</SelectTrigger>
|
||||||
<SelectItem value="Unimed">Unimed</SelectItem>
|
<SelectContent>
|
||||||
{/* Adicione outros convênios conforme necessário */}
|
<SelectItem value="all">Todos</SelectItem>
|
||||||
</SelectContent>
|
<SelectItem value="Particular">Particular</SelectItem>
|
||||||
</Select>
|
<SelectItem value="SUS">SUS</SelectItem>
|
||||||
</div>
|
<SelectItem value="Unimed">Unimed</SelectItem>
|
||||||
|
{/* Adicione outros convênios conforme necessário */}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* VIP - Ocupa a outra metade da linha no mobile */}
|
{/* VIP - Ocupa a largura total em telas pequenas, depois se ajusta */}
|
||||||
<div className="flex items-center gap-2 w-[calc(50%-8px)] sm:w-auto sm:flex-grow sm:max-w-[150px]">
|
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[150px]">
|
||||||
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">VIP</span>
|
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">VIP</span>
|
||||||
<Select value={vipFilter} onValueChange={setVipFilter}>
|
<Select value={vipFilter} onValueChange={setVipFilter}>
|
||||||
<SelectTrigger className="w-full sm:w-32">
|
<SelectTrigger className="w-full sm:w-32"> {/* w-full para mobile, w-32 para sm+ */}
|
||||||
<SelectValue placeholder="VIP" />
|
<SelectValue placeholder="VIP" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
@ -207,259 +215,396 @@ export default function PacientesPage() {
|
|||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Aniversariantes - Vai para a linha de baixo no mobile, ocupando 100% */}
|
|
||||||
<Button variant="outline" className="w-full md:w-auto md:ml-auto">
|
|
||||||
<Calendar className="w-4 h-4 mr-2" />
|
|
||||||
Aniversariantes
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Tabela (Responsividade APLICADA) */}
|
{/* --- SEÇÃO DE TABELA (VISÍVEL EM TELAS MAIORES OU IGUAIS A MD) --- */}
|
||||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md">
|
{/* Garantir que a tabela se esconda em telas menores e apareça em MD+ */}
|
||||||
<div className="overflow-x-auto">
|
<div className="bg-white rounded-lg border border-gray-200 shadow-md hidden md:block">
|
||||||
{error ? (
|
<div className="overflow-x-auto">
|
||||||
<div className="p-6 text-red-600">{`Erro ao carregar pacientes: ${error}`}</div>
|
{" "}
|
||||||
) : loading ? (
|
{/* Permite rolagem horizontal se a tabela for muito larga */}
|
||||||
<div className="p-6 text-center text-gray-500 flex items-center justify-center">
|
{error ? (
|
||||||
<Loader2 className="w-6 h-6 mr-2 animate-spin text-green-600" /> Carregando pacientes...
|
<div className="p-6 text-red-600">{`Erro ao carregar pacientes: ${error}`}</div>
|
||||||
|
) : loading ? (
|
||||||
|
<div className="p-6 text-center text-gray-500 flex items-center justify-center">
|
||||||
|
<Loader2 className="w-6 h-6 mr-2 animate-spin text-green-600" />{" "}
|
||||||
|
Carregando pacientes...
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<table className="w-full min-w-[650px]">
|
||||||
|
{" "}
|
||||||
|
{/* min-w para evitar que a tabela se contraia demais */}
|
||||||
|
<thead className="bg-gray-50 border-b border-gray-200">
|
||||||
|
<tr>
|
||||||
|
<th className="text-left p-4 font-medium text-gray-700 w-[20%]">
|
||||||
|
Nome
|
||||||
|
</th>
|
||||||
|
{/* Ajustes de visibilidade de colunas para diferentes breakpoints */}
|
||||||
|
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">
|
||||||
|
Telefone
|
||||||
|
</th>
|
||||||
|
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden md:table-cell">
|
||||||
|
Cidade / Estado
|
||||||
|
</th>
|
||||||
|
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">
|
||||||
|
Convênio
|
||||||
|
</th>
|
||||||
|
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">
|
||||||
|
Último atendimento
|
||||||
|
</th>
|
||||||
|
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">
|
||||||
|
Próximo atendimento
|
||||||
|
</th>
|
||||||
|
<th className="text-left p-4 font-medium text-gray-700 w-[5%]">
|
||||||
|
Ações
|
||||||
|
</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{currentPatients.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={7} className="p-8 text-center text-gray-500">
|
||||||
|
{allPatients.length === 0
|
||||||
|
? "Nenhum paciente cadastrado"
|
||||||
|
: "Nenhum paciente encontrado com os filtros aplicados"}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : (
|
||||||
|
currentPatients.map((patient) => (
|
||||||
|
<tr
|
||||||
|
key={patient.id}
|
||||||
|
className="border-b border-gray-100 hover:bg-gray-50"
|
||||||
|
>
|
||||||
|
<td className="p-4">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
|
||||||
|
<span className="text-blue-600 font-medium text-sm">
|
||||||
|
{patient.nome?.charAt(0) || "?"}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
|
||||||
// min-w ajustado para responsividade
|
|
||||||
<table className="w-full min-w-[650px] md:min-w-[900px]">
|
|
||||||
<thead className="bg-gray-50 border-b border-gray-200">
|
|
||||||
<tr>
|
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[20%]">Nome</th>
|
|
||||||
{/* Coluna oculta em telas muito pequenas */}
|
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">Telefone</th>
|
|
||||||
{/* Coluna oculta em telas pequenas e muito pequenas */}
|
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden md:table-cell">Cidade / Estado</th>
|
|
||||||
{/* Coluna oculta em telas muito pequenas */}
|
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">Convênio</th>
|
|
||||||
{/* Colunas ocultas em telas médias, pequenas e muito pequenas */}
|
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">Último atendimento</th>
|
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">Próximo atendimento</th>
|
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[5%]">Ações</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{currentPatients.length === 0 ? (
|
|
||||||
<tr>
|
|
||||||
<td colSpan={7} className="p-8 text-center text-gray-500">
|
|
||||||
{allPatients.length === 0 ? "Nenhum paciente cadastrado" : "Nenhum paciente encontrado com os filtros aplicados"}
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
) : (
|
|
||||||
currentPatients.map((patient) => (
|
|
||||||
<tr key={patient.id} className="border-b border-gray-100 hover:bg-gray-50">
|
|
||||||
<td className="p-4">
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<div className="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
|
|
||||||
<span className="text-green-600 font-medium text-sm">{patient.nome?.charAt(0) || "?"}</span>
|
|
||||||
</div>
|
|
||||||
<span className="font-medium text-gray-900">
|
|
||||||
{patient.nome}
|
|
||||||
{patient.vip && (
|
|
||||||
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-600 bg-purple-100 rounded-full">VIP</span>
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
{/* Aplicação das classes de visibilidade */}
|
|
||||||
<td className="p-4 text-gray-600 hidden sm:table-cell">{patient.telefone}</td>
|
|
||||||
<td className="p-4 text-gray-600 hidden md:table-cell">{`${patient.cidade} / ${patient.estado}`}</td>
|
|
||||||
<td className="p-4 text-gray-600 hidden sm:table-cell">{patient.convenio}</td>
|
|
||||||
<td className="p-4 text-gray-600 hidden lg:table-cell">{patient.ultimoAtendimento}</td>
|
|
||||||
<td className="p-4 text-gray-600 hidden lg:table-cell">{patient.proximoAtendimento}</td>
|
|
||||||
|
|
||||||
<td className="p-4">
|
<span className="font-medium text-gray-900">
|
||||||
<DropdownMenu>
|
{patient.nome}
|
||||||
<DropdownMenuTrigger asChild>
|
{patient.vip && (
|
||||||
<Button variant="ghost" className="h-8 w-8 p-0">
|
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-600 bg-purple-100 rounded-full">
|
||||||
<span className="sr-only">Abrir menu</span>
|
VIP
|
||||||
<MoreVertical className="h-4 w-4" />
|
</span>
|
||||||
</Button>
|
)}
|
||||||
</DropdownMenuTrigger>
|
</span>
|
||||||
<DropdownMenuContent align="end">
|
</div>
|
||||||
<DropdownMenuItem onClick={() => openDetailsDialog(String(patient.id))}>
|
</td>
|
||||||
<Eye className="w-4 h-4 mr-2" />
|
<td className="p-4 text-gray-600 hidden sm:table-cell">
|
||||||
Ver detalhes
|
{patient.telefone}
|
||||||
</DropdownMenuItem>
|
</td>
|
||||||
|
<td className="p-4 text-gray-600 hidden md:table-cell">{`${patient.cidade} / ${patient.estado}`}</td>
|
||||||
|
<td className="p-4 text-gray-600 hidden sm:table-cell">
|
||||||
|
{patient.convenio}
|
||||||
|
</td>
|
||||||
|
<td className="p-4 text-gray-600 hidden lg:table-cell">
|
||||||
|
{patient.ultimoAtendimento}
|
||||||
|
</td>
|
||||||
|
<td className="p-4 text-gray-600 hidden lg:table-cell">
|
||||||
|
{patient.proximoAtendimento}
|
||||||
|
</td>
|
||||||
|
|
||||||
<DropdownMenuItem asChild>
|
<td className="p-4">
|
||||||
<Link href={`/secretary/pacientes/${patient.id}/editar`} className="flex items-center w-full">
|
<DropdownMenu>
|
||||||
<Edit className="w-4 h-4 mr-2" />
|
<DropdownMenuTrigger asChild>
|
||||||
Editar
|
<div className="text-blue-600 cursor-pointer">
|
||||||
</Link>
|
Ações
|
||||||
</DropdownMenuItem>
|
</div>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end">
|
||||||
|
<DropdownMenuItem
|
||||||
|
onClick={() =>
|
||||||
|
openDetailsDialog(String(patient.id))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Eye className="w-4 h-4 mr-2" />
|
||||||
|
Ver detalhes
|
||||||
|
</DropdownMenuItem>
|
||||||
|
|
||||||
<DropdownMenuItem>
|
<DropdownMenuItem asChild>
|
||||||
<Calendar className="w-4 h-4 mr-2" />
|
<Link
|
||||||
Marcar consulta
|
href={`/secretary/pacientes/${patient.id}/editar`}
|
||||||
</DropdownMenuItem>
|
className="flex items-center w-full"
|
||||||
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(String(patient.id))}>
|
|
||||||
<Trash2 className="w-4 h-4 mr-2" />
|
|
||||||
Excluir
|
|
||||||
</DropdownMenuItem>
|
|
||||||
</DropdownMenuContent>
|
|
||||||
</DropdownMenu>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Paginação */}
|
|
||||||
{totalPages > 1 && !loading && (
|
|
||||||
<div className="flex flex-col sm:flex-row items-center justify-center p-4 border-t border-gray-200">
|
|
||||||
{/* Renderização dos botões de número de página (Limitando a 5) */}
|
|
||||||
<div className="flex space-x-2"> {/* Increased space-x for more separation */}
|
|
||||||
{/* Botão Anterior */}
|
|
||||||
<Button
|
|
||||||
onClick={() => setPage((prev) => Math.max(1, prev - 1))}
|
|
||||||
disabled={page === 1}
|
|
||||||
variant="outline"
|
|
||||||
size="lg" // Changed to "lg" for larger buttons
|
|
||||||
>
|
>
|
||||||
< Anterior
|
<Edit className="w-4 h-4 mr-2" />
|
||||||
</Button>
|
Editar
|
||||||
|
</Link>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
|
||||||
{Array.from({ length: totalPages }, (_, index) => index + 1)
|
<DropdownMenuItem>
|
||||||
.slice(Math.max(0, page - 3), Math.min(totalPages, page + 2))
|
<Calendar className="w-4 h-4 mr-2" />
|
||||||
.map((pageNumber) => (
|
Marcar consulta
|
||||||
<Button
|
</DropdownMenuItem>
|
||||||
key={pageNumber}
|
<DropdownMenuItem
|
||||||
onClick={() => setPage(pageNumber)}
|
className="text-red-600"
|
||||||
variant={pageNumber === page ? "default" : "outline"}
|
onClick={() =>
|
||||||
size="lg" // Changed to "lg" for larger buttons
|
openDeleteDialog(String(patient.id))
|
||||||
className={pageNumber === page ? "bg-green-600 hover:bg-green-700 text-white" : "text-gray-700"}
|
}
|
||||||
>
|
>
|
||||||
{pageNumber}
|
<Trash2 className="w-4 h-4 mr-2" />
|
||||||
</Button>
|
|
||||||
))}
|
|
||||||
|
|
||||||
{/* Botão Próximo */}
|
|
||||||
<Button
|
|
||||||
onClick={() => setPage((prev) => Math.min(totalPages, prev + 1))}
|
|
||||||
disabled={page === totalPages}
|
|
||||||
variant="outline"
|
|
||||||
size="lg" // Changed to "lg" for larger buttons
|
|
||||||
>
|
|
||||||
Próximo >
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* AlertDialogs (Permanecem os mesmos) */}
|
|
||||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
|
||||||
{/* ... (AlertDialog de Exclusão) ... */}
|
|
||||||
<AlertDialogContent>
|
|
||||||
<AlertDialogHeader>
|
|
||||||
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
|
|
||||||
<AlertDialogDescription>Tem certeza que deseja excluir este paciente? Esta ação não pode ser desfeita.</AlertDialogDescription>
|
|
||||||
</AlertDialogHeader>
|
|
||||||
<AlertDialogFooter>
|
|
||||||
<AlertDialogCancel>Cancelar</AlertDialogCancel>
|
|
||||||
<AlertDialogAction onClick={() => patientToDelete && handleDeletePatient(patientToDelete)} className="bg-red-600 hover:bg-red-700">
|
|
||||||
Excluir
|
Excluir
|
||||||
</AlertDialogAction>
|
</DropdownMenuItem>
|
||||||
</AlertDialogFooter>
|
</DropdownMenuContent>
|
||||||
</AlertDialogContent>
|
</DropdownMenu>
|
||||||
</AlertDialog>
|
</td>
|
||||||
|
</tr>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
{/* --- SEÇÃO DE CARDS (VISÍVEL APENAS EM TELAS MENORES QUE MD) --- */}
|
||||||
{/* ... (AlertDialog de Detalhes) ... */}
|
{/* Garantir que os cards apareçam em telas menores e se escondam em MD+ */}
|
||||||
<AlertDialogContent>
|
<div className="bg-white rounded-lg border border-gray-200 shadow-md p-4 block md:hidden">
|
||||||
<AlertDialogHeader>
|
{error ? (
|
||||||
<AlertDialogTitle>Detalhes do Paciente</AlertDialogTitle>
|
<div className="p-6 text-red-600">{`Erro ao carregar pacientes: ${error}`}</div>
|
||||||
<AlertDialogDescription>
|
) : loading ? (
|
||||||
{patientDetails === null ? (
|
<div className="p-6 text-center text-gray-500 flex items-center justify-center">
|
||||||
<div className="text-gray-500">
|
<Loader2 className="w-6 h-6 mr-2 animate-spin text-green-600" />{" "}
|
||||||
<Loader2 className="w-6 h-6 animate-spin mx-auto text-green-600 my-4" />
|
Carregando pacientes...
|
||||||
Carregando...
|
|
||||||
</div>
|
|
||||||
) : patientDetails?.error ? (
|
|
||||||
<div className="text-red-600 p-4">{patientDetails.error}</div>
|
|
||||||
) : (
|
|
||||||
<div className="grid gap-4 py-4">
|
|
||||||
<div className="grid grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Nome Completo</p>
|
|
||||||
<p>{patientDetails.full_name}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Email</p>
|
|
||||||
<p>{patientDetails.email}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Telefone</p>
|
|
||||||
<p>{patientDetails.phone_mobile}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Data de Nascimento</p>
|
|
||||||
<p>{patientDetails.birth_date}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">CPF</p>
|
|
||||||
<p>{patientDetails.cpf}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Tipo Sanguíneo</p>
|
|
||||||
<p>{patientDetails.blood_type}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Peso (kg)</p>
|
|
||||||
<p>{patientDetails.weight_kg}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Altura (m)</p>
|
|
||||||
<p>{patientDetails.height_m}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="border-t pt-4 mt-4">
|
|
||||||
<h3 className="font-semibold mb-2">Endereço</h3>
|
|
||||||
<div className="grid grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Rua</p>
|
|
||||||
<p>{`${patientDetails.street}, ${patientDetails.number}`}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Complemento</p>
|
|
||||||
<p>{patientDetails.complement}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Bairro</p>
|
|
||||||
<p>{patientDetails.neighborhood}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Cidade</p>
|
|
||||||
<p>{patientDetails.cidade}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Estado</p>
|
|
||||||
<p>{patientDetails.estado}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">CEP</p>
|
|
||||||
<p>{patientDetails.cep}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</AlertDialogDescription>
|
|
||||||
</AlertDialogHeader>
|
|
||||||
<AlertDialogFooter>
|
|
||||||
<AlertDialogCancel>Fechar</AlertDialogCancel>
|
|
||||||
</AlertDialogFooter>
|
|
||||||
</AlertDialogContent>
|
|
||||||
</AlertDialog>
|
|
||||||
</div>
|
</div>
|
||||||
</SecretaryLayout>
|
) : filteredPatients.length === 0 ? (
|
||||||
);
|
<div className="p-8 text-center text-gray-500">
|
||||||
}
|
{allPatients.length === 0
|
||||||
|
? "Nenhum paciente cadastrado"
|
||||||
|
: "Nenhum paciente encontrado com os filtros aplicados"}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{currentPatients.map((patient) => (
|
||||||
|
<div
|
||||||
|
key={patient.id}
|
||||||
|
className="bg-gray-50 rounded-lg p-4 flex flex-col sm:flex-row justify-between items-start sm:items-center border border-gray-200"
|
||||||
|
>
|
||||||
|
<div className="flex-grow mb-2 sm:mb-0">
|
||||||
|
<div className="font-semibold text-lg text-gray-900 flex items-center">
|
||||||
|
{patient.nome}
|
||||||
|
{patient.vip && (
|
||||||
|
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-600 bg-purple-100 rounded-full">
|
||||||
|
VIP
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="text-sm text-gray-600">
|
||||||
|
Telefone: {patient.telefone}
|
||||||
|
</div>
|
||||||
|
<div className="text-sm text-gray-600">
|
||||||
|
Convênio: {patient.convenio}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<div className="w-full">
|
||||||
|
<Button variant="outline" className="w-full">
|
||||||
|
Ações
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end">
|
||||||
|
<DropdownMenuItem
|
||||||
|
onClick={() => openDetailsDialog(String(patient.id))}
|
||||||
|
>
|
||||||
|
<Eye className="w-4 h-4 mr-2" />
|
||||||
|
Ver detalhes
|
||||||
|
</DropdownMenuItem>
|
||||||
|
|
||||||
|
<DropdownMenuItem asChild>
|
||||||
|
<Link
|
||||||
|
href={`/secretary/pacientes/${patient.id}/editar`}
|
||||||
|
className="flex items-center w-full"
|
||||||
|
>
|
||||||
|
<Edit className="w-4 h-4 mr-2" />
|
||||||
|
Editar
|
||||||
|
</Link>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
|
||||||
|
<DropdownMenuItem>
|
||||||
|
<Calendar className="w-4 h-4 mr-2" />
|
||||||
|
Marcar consulta
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem
|
||||||
|
className="text-red-600"
|
||||||
|
onClick={() => openDeleteDialog(String(patient.id))}
|
||||||
|
>
|
||||||
|
<Trash2 className="w-4 h-4 mr-2" />
|
||||||
|
Excluir
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Paginação */}
|
||||||
|
{totalPages > 1 && !loading && (
|
||||||
|
<div className="flex flex-col sm:flex-row items-center justify-center p-4 border-t border-gray-200">
|
||||||
|
<div className="flex space-x-2 flex-wrap justify-center">
|
||||||
|
{" "}
|
||||||
|
{/* Adicionado flex-wrap e justify-center para botões da paginação */}
|
||||||
|
<Button
|
||||||
|
onClick={() => setPage((prev) => Math.max(1, prev - 1))}
|
||||||
|
disabled={page === 1}
|
||||||
|
variant="outline"
|
||||||
|
size="lg"
|
||||||
|
>
|
||||||
|
< Anterior
|
||||||
|
</Button>
|
||||||
|
{Array.from({ length: totalPages }, (_, index) => index + 1)
|
||||||
|
.slice(Math.max(0, page - 3), Math.min(totalPages, page + 2))
|
||||||
|
.map((pageNumber) => (
|
||||||
|
<Button
|
||||||
|
key={pageNumber}
|
||||||
|
onClick={() => setPage(pageNumber)}
|
||||||
|
variant={pageNumber === page ? "default" : "outline"}
|
||||||
|
size="lg"
|
||||||
|
className={
|
||||||
|
pageNumber === page
|
||||||
|
? "bg-blue-600 hover:bg-blue-700 text-white"
|
||||||
|
: "text-gray-700"
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{pageNumber}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
<Button
|
||||||
|
onClick={() =>
|
||||||
|
setPage((prev) => Math.min(totalPages, prev + 1))
|
||||||
|
}
|
||||||
|
disabled={page === totalPages}
|
||||||
|
variant="outline"
|
||||||
|
size="lg"
|
||||||
|
>
|
||||||
|
Próximo >
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* AlertDialogs (Permanecem os mesmos) */}
|
||||||
|
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>
|
||||||
|
Tem certeza que deseja excluir este paciente? Esta ação não pode
|
||||||
|
ser desfeita.
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>Cancelar</AlertDialogCancel>
|
||||||
|
<AlertDialogAction
|
||||||
|
onClick={() =>
|
||||||
|
patientToDelete && handleDeletePatient(patientToDelete)
|
||||||
|
}
|
||||||
|
className="bg-red-600 hover:bg-red-700"
|
||||||
|
>
|
||||||
|
Excluir
|
||||||
|
</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
|
||||||
|
<AlertDialog
|
||||||
|
open={detailsDialogOpen}
|
||||||
|
onOpenChange={setDetailsDialogOpen}
|
||||||
|
>
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle>Detalhes do Paciente</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>
|
||||||
|
{patientDetails === null ? (
|
||||||
|
<div className="text-gray-500">
|
||||||
|
<Loader2 className="w-6 h-6 animate-spin mx-auto text-green-600 my-4" />
|
||||||
|
Carregando...
|
||||||
|
</div>
|
||||||
|
) : patientDetails?.error ? (
|
||||||
|
<div className="text-red-600 p-4">{patientDetails.error}</div>
|
||||||
|
) : (
|
||||||
|
<div className="grid gap-4 py-4">
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold">Nome Completo</p>
|
||||||
|
<p>{patientDetails.full_name}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold">Email</p>
|
||||||
|
<p>{patientDetails.email}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold">Telefone</p>
|
||||||
|
<p>{patientDetails.phone_mobile}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold">Data de Nascimento</p>
|
||||||
|
<p>{patientDetails.birth_date}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold">CPF</p>
|
||||||
|
<p>{patientDetails.cpf}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold">Tipo Sanguíneo</p>
|
||||||
|
<p>{patientDetails.blood_type}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold">Peso (kg)</p>
|
||||||
|
<p>{patientDetails.weight_kg}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold">Altura (m)</p>
|
||||||
|
<p>{patientDetails.height_m}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="border-t pt-4 mt-4">
|
||||||
|
<h3 className="font-semibold mb-2">Endereço</h3>
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold">Rua</p>
|
||||||
|
<p>{`${patientDetails.street}, ${patientDetails.number}`}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold">Complemento</p>
|
||||||
|
<p>{patientDetails.complement}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold">Bairro</p>
|
||||||
|
<p>{patientDetails.neighborhood}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold">Cidade</p>
|
||||||
|
<p>{patientDetails.cidade}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold">Estado</p>
|
||||||
|
<p>{patientDetails.estado}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold">CEP</p>
|
||||||
|
<p>{patientDetails.cep}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>Fechar</AlertDialogCancel>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
</div>
|
||||||
|
</Sidebar>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@ -1,355 +1,11 @@
|
|||||||
"use client";
|
import Sidebar from "@/components/Sidebar";
|
||||||
import type React from "react";
|
import ScheduleForm from "@/components/schedule/schedule-form";
|
||||||
import { useState, useEffect } from "react";
|
|
||||||
import { useRouter } from "next/navigation";
|
|
||||||
import SecretaryLayout from "@/components/secretary-layout";
|
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { Input } from "@/components/ui/input";
|
|
||||||
import { Label } from "@/components/ui/label";
|
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
|
||||||
import { Textarea } from "@/components/ui/textarea";
|
|
||||||
import { Calendar, Clock, User } from "lucide-react"; // Importações que você já tinha
|
|
||||||
import { patientsService } from "@/services/patientsApi.mjs";
|
|
||||||
import { doctorsService } from "@/services/doctorsApi.mjs";
|
|
||||||
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
|
||||||
import { usersService } from "@/services/usersApi.mjs";
|
|
||||||
import { toast } from "sonner"; // Para notificações
|
|
||||||
|
|
||||||
export default function ScheduleAppointment() {
|
export default function SecretaryAppointments() {
|
||||||
const router = useRouter();
|
return (
|
||||||
const [patients, setPatients] = useState<any[]>([]);
|
<Sidebar>
|
||||||
const [doctors, setDoctors] = useState<any[]>([]);
|
<ScheduleForm />
|
||||||
const [currentUserId, setCurrentUserId] = useState<string | null>(null);
|
</Sidebar>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Estados de loading e error para feedback visual e depuração
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
|
|
||||||
// Estados do formulário
|
|
||||||
const [selectedPatient, setSelectedPatient] = useState("");
|
|
||||||
const [selectedDoctor, setSelectedDoctor] = useState("");
|
|
||||||
const [selectedDate, setSelectedDate] = useState("");
|
|
||||||
const [selectedTime, setSelectedTime] = useState("");
|
|
||||||
const [appointmentType, setAppointmentType] = useState("presencial");
|
|
||||||
const [durationMinutes, setDurationMinutes] = useState("30");
|
|
||||||
const [chiefComplaint, setChiefComplaint] = useState("");
|
|
||||||
const [patientNotes, setPatientNotes] = useState("");
|
|
||||||
const [internalNotes, setInternalNotes] = useState("");
|
|
||||||
const [insuranceProvider, setInsuranceProvider] = useState("");
|
|
||||||
|
|
||||||
const availableTimes = [
|
|
||||||
"08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30",
|
|
||||||
"14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30"
|
|
||||||
];
|
|
||||||
|
|
||||||
// --- NOVO/ATUALIZADO useEffect COM LOGS PARA DEPURAR ---
|
|
||||||
useEffect(() => {
|
|
||||||
const fetchInitialData = async () => {
|
|
||||||
setLoading(true);
|
|
||||||
setError(null); // Limpa qualquer erro anterior ao iniciar uma nova busca
|
|
||||||
|
|
||||||
const results = await Promise.allSettled([
|
|
||||||
patientsService.list(),
|
|
||||||
doctorsService.list(),
|
|
||||||
usersService.getMe()
|
|
||||||
]);
|
|
||||||
|
|
||||||
const [patientResult, doctorResult, userResult] = results;
|
|
||||||
let hasFetchError = false; // Flag para saber se houve algum erro geral
|
|
||||||
|
|
||||||
// Checar pacientes
|
|
||||||
if (patientResult.status === 'fulfilled') {
|
|
||||||
setPatients(patientResult.value || []);
|
|
||||||
console.log("Pacientes carregados com sucesso:", patientResult.value);
|
|
||||||
} else {
|
|
||||||
console.error("ERRO AO CARREGAR PACIENTES:", patientResult.reason);
|
|
||||||
hasFetchError = true;
|
|
||||||
toast.error("Erro ao carregar lista de pacientes."); // Notificação para o usuário
|
|
||||||
}
|
|
||||||
|
|
||||||
// Checar médicos
|
|
||||||
if (doctorResult.status === 'fulfilled') {
|
|
||||||
setDoctors(doctorResult.value || []);
|
|
||||||
console.log("Médicos carregados com sucesso:", doctorResult.value); // <-- CRÍTICO PARA DEPURAR
|
|
||||||
} else {
|
|
||||||
console.error("ERRO AO CARREGAR MÉDICOS:", doctorResult.reason);
|
|
||||||
hasFetchError = true;
|
|
||||||
setError("Falha ao carregar médicos."); // Define o erro para ser exibido no dropdown
|
|
||||||
toast.error("Erro ao carregar lista de médicos."); // Notificação para o usuário
|
|
||||||
}
|
|
||||||
|
|
||||||
// Checar usuário logado
|
|
||||||
if (userResult.status === 'fulfilled' && userResult.value?.user?.id) {
|
|
||||||
setCurrentUserId(userResult.value.user.id);
|
|
||||||
console.log("ID do usuário logado carregado:", userResult.value.user.id);
|
|
||||||
} else {
|
|
||||||
const reason = userResult.status === 'rejected' ? userResult.reason : "API não retornou um ID de usuário.";
|
|
||||||
console.error("ERRO AO CARREGAR USUÁRIO:", reason);
|
|
||||||
hasFetchError = true;
|
|
||||||
toast.error("Não foi possível identificar o usuário logado. Por favor, faça login novamente."); // Notificação
|
|
||||||
// Não definimos setError aqui, pois um erro no usuário não impede a renderização de médicos/pacientes
|
|
||||||
}
|
|
||||||
|
|
||||||
// Se houve qualquer erro na busca, defina uma mensagem geral de erro se não houver uma mais específica.
|
|
||||||
if (hasFetchError && !error) { // Se 'error' já foi definido por um problema específico, mantenha-o.
|
|
||||||
setError("Alguns dados não puderam ser carregados. Verifique o console.");
|
|
||||||
}
|
|
||||||
|
|
||||||
setLoading(false); // Finaliza o estado de carregamento
|
|
||||||
console.log("Estado de carregamento finalizado:", false);
|
|
||||||
};
|
|
||||||
|
|
||||||
fetchInitialData();
|
|
||||||
}, []); // O array de dependências vazio significa que ele roda apenas uma vez após a montagem inicial
|
|
||||||
|
|
||||||
// --- LOGS PARA VERIFICAR OS ESTADOS ANTES DA RENDERIZAÇÃO ---
|
|
||||||
console.log("Estado 'loading' no render:", loading);
|
|
||||||
console.log("Estado 'error' no render:", error);
|
|
||||||
console.log("Conteúdo de 'doctors' no render:", doctors);
|
|
||||||
console.log("Número de médicos em 'doctors':", doctors.length);
|
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
console.log("Botão de submit clicado!"); // Log para confirmar que o clique funciona
|
|
||||||
|
|
||||||
if (!currentUserId) {
|
|
||||||
toast.error("Sessão de usuário inválida. Por favor, faça login novamente.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!selectedPatient || !selectedDoctor || !selectedDate || !selectedTime) {
|
|
||||||
toast.error("Paciente, médico, data e horário são obrigatórios.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const scheduledAt = new Date(`${selectedDate}T${selectedTime}:00Z`).toISOString();
|
|
||||||
|
|
||||||
const newAppointmentData = {
|
|
||||||
patient_id: selectedPatient,
|
|
||||||
doctor_id: selectedDoctor,
|
|
||||||
scheduled_at: scheduledAt,
|
|
||||||
duration_minutes: parseInt(durationMinutes, 10),
|
|
||||||
appointment_type: appointmentType,
|
|
||||||
status: "requested",
|
|
||||||
chief_complaint: chiefComplaint || null,
|
|
||||||
patient_notes: patientNotes || null,
|
|
||||||
notes: internalNotes || null,
|
|
||||||
insurance_provider: insuranceProvider || null,
|
|
||||||
created_by: currentUserId,
|
|
||||||
};
|
|
||||||
|
|
||||||
console.log("🚀 Enviando os seguintes dados para a API:", newAppointmentData);
|
|
||||||
|
|
||||||
// A chamada para a API de criação
|
|
||||||
await appointmentsService.create(newAppointmentData);
|
|
||||||
|
|
||||||
toast.success("Consulta agendada com sucesso!");
|
|
||||||
router.push("/secretary/appointments");
|
|
||||||
} catch (error) {
|
|
||||||
console.error("❌ Erro ao criar agendamento:", error);
|
|
||||||
toast.error("Ocorreu um erro ao agendar a consulta. Verifique o console.");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
return (
|
|
||||||
<SecretaryLayout>
|
|
||||||
<div className="space-y-6">
|
|
||||||
<div>
|
|
||||||
<h1 className="text-3xl font-bold text-gray-900">Agendar Consulta</h1>
|
|
||||||
<p className="text-gray-600">Preencha os detalhes para criar um novo agendamento</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid lg:grid-cols-3 gap-6">
|
|
||||||
<div className="lg:col-span-2">
|
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle>Dados da Consulta</CardTitle>
|
|
||||||
<CardDescription>Preencha as informações para agendar a consulta</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<form onSubmit={handleSubmit} className="space-y-6">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="patient">Paciente</Label>
|
|
||||||
<Select value={selectedPatient} onValueChange={setSelectedPatient}>
|
|
||||||
<SelectTrigger>
|
|
||||||
<SelectValue placeholder="Selecione um paciente" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
{loading ? (
|
|
||||||
<SelectItem value="loading-patients" disabled>Carregando pacientes...</SelectItem>
|
|
||||||
) : error && patients.length === 0 ? ( // Se erro e não há pacientes
|
|
||||||
<SelectItem value="error-patients" disabled>Erro ao carregar pacientes</SelectItem>
|
|
||||||
) : patients.length === 0 ? ( // Se não há erro mas a lista está vazia
|
|
||||||
<SelectItem value="no-patients" disabled>Nenhum paciente encontrado</SelectItem>
|
|
||||||
) : (
|
|
||||||
patients.map((p) => (
|
|
||||||
<SelectItem key={p.id} value={p.id}>
|
|
||||||
{p.full_name}
|
|
||||||
</SelectItem>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="doctor">Médico</Label>
|
|
||||||
<Select value={selectedDoctor} onValueChange={setSelectedDoctor}>
|
|
||||||
<SelectTrigger>
|
|
||||||
<SelectValue placeholder="Selecione um médico" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
{/* Lógica condicional para o estado de carregamento, erro ou lista vazia */}
|
|
||||||
{loading ? (
|
|
||||||
<SelectItem value="loading" disabled>Carregando médicos...</SelectItem>
|
|
||||||
) : error && doctors.length === 0 ? ( // Se há erro E a lista de médicos está vazia
|
|
||||||
<SelectItem value="error" disabled>Erro ao carregar médicos</SelectItem>
|
|
||||||
) : doctors.length === 0 ? ( // Se não há erro mas a lista está vazia
|
|
||||||
<SelectItem value="no-doctors" disabled>Nenhum médico encontrado</SelectItem>
|
|
||||||
) : (
|
|
||||||
doctors.map((d) => (
|
|
||||||
<SelectItem key={d.id} value={d.id}>
|
|
||||||
{d.full_name} - {d.specialty}
|
|
||||||
</SelectItem>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* O restante do formulário permanece o mesmo */}
|
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="date">Data</Label>
|
|
||||||
<Input
|
|
||||||
id="date"
|
|
||||||
type="date"
|
|
||||||
value={selectedDate}
|
|
||||||
onChange={(e) => setSelectedDate(e.target.value)}
|
|
||||||
min={new Date().toISOString().split("T")[0]} // Garante que a data mínima é hoje
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="time">Horário</Label>
|
|
||||||
<Select value={selectedTime} onValueChange={setSelectedTime}>
|
|
||||||
<SelectTrigger>
|
|
||||||
<SelectValue placeholder="Selecione um horário" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
{availableTimes.map((time) => (
|
|
||||||
<SelectItem key={time} value={time}>
|
|
||||||
{time}
|
|
||||||
</SelectItem>
|
|
||||||
))}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="appointmentType">Tipo de Consulta</Label>
|
|
||||||
<Select value={appointmentType} onValueChange={setAppointmentType}>
|
|
||||||
<SelectTrigger><SelectValue /></SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="presencial">Presencial</SelectItem>
|
|
||||||
<SelectItem value="telemedicina">Telemedicina</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="duration">Duração (minutos)</Label>
|
|
||||||
<Input
|
|
||||||
id="duration"
|
|
||||||
type="number"
|
|
||||||
value={durationMinutes}
|
|
||||||
onChange={(e) => setDurationMinutes(e.target.value)}
|
|
||||||
placeholder="Ex: 30"
|
|
||||||
min="1" // Duração mínima
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="insurance">Convênio (opcional)</Label>
|
|
||||||
<Input
|
|
||||||
id="insurance"
|
|
||||||
placeholder="Nome do convênio do paciente"
|
|
||||||
value={insuranceProvider}
|
|
||||||
onChange={(e) => setInsuranceProvider(e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="chiefComplaint">Queixa Principal (opcional)</Label>
|
|
||||||
<Textarea
|
|
||||||
id="chiefComplaint"
|
|
||||||
placeholder="Descreva brevemente o motivo da consulta..."
|
|
||||||
value={chiefComplaint}
|
|
||||||
onChange={(e) => setChiefComplaint(e.target.value)}
|
|
||||||
rows={2}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="patientNotes">Observações do Paciente (opcional)</Label>
|
|
||||||
<Textarea
|
|
||||||
id="patientNotes"
|
|
||||||
placeholder="Anotações relevantes informadas pelo paciente..."
|
|
||||||
value={patientNotes}
|
|
||||||
onChange={(e) => setPatientNotes(e.target.value)}
|
|
||||||
rows={2}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="internalNotes">Observações Internas (opcional)</Label>
|
|
||||||
<Textarea
|
|
||||||
id="internalNotes"
|
|
||||||
placeholder="Anotações para a equipe da clínica..."
|
|
||||||
value={internalNotes}
|
|
||||||
onChange={(e) => setInternalNotes(e.target.value)}
|
|
||||||
rows={2}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Button
|
|
||||||
type="submit"
|
|
||||||
className="w-full"
|
|
||||||
// Remova temporariamente '|| !currentUserId || loading' para testar
|
|
||||||
disabled={!selectedPatient || !selectedDoctor || !selectedDate || !selectedTime /* || !currentUserId || loading */}
|
|
||||||
>
|
|
||||||
Agendar Consulta
|
|
||||||
</Button>
|
|
||||||
</form>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-6">
|
|
||||||
{/* Card de Resumo e Informações Importantes (se houver, adicione aqui) */}
|
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle>Informações Rápidas</CardTitle>
|
|
||||||
<CardDescription>Ajuda e status</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="space-y-4">
|
|
||||||
{loading && (
|
|
||||||
<p className="text-sm text-blue-600 flex items-center"><Clock className="mr-2 h-4 w-4" /> Carregando dados iniciais...</p>
|
|
||||||
)}
|
|
||||||
{error && (
|
|
||||||
<p className="text-sm text-red-600 flex items-center">
|
|
||||||
<User className="mr-2 h-4 w-4" /> {error}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
{!currentUserId && !loading && (
|
|
||||||
<p className="text-sm text-red-600 flex items-center"><User className="mr-2 h-4 w-4" /> Usuário não identificado. Recarregue a página.</p>
|
|
||||||
)}
|
|
||||||
<p className="text-sm text-gray-500 flex items-center">
|
|
||||||
<Calendar className="mr-2 h-4 w-4" /> Selecione uma data e horário válidos.
|
|
||||||
</p>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</SecretaryLayout>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -1,11 +1,10 @@
|
|||||||
// Caminho: components/LoginForm.tsx
|
// ARQUIVO COMPLETO E CORRIGIDO PARA: components/LoginForm.tsx
|
||||||
|
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import type React from "react";
|
import type React from "react";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
|
|
||||||
// Nossos serviços de API centralizados e limpos
|
|
||||||
import { login, api } from "@/services/api.mjs";
|
import { login, api } from "@/services/api.mjs";
|
||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
@ -14,198 +13,218 @@ import { Label } from "@/components/ui/label";
|
|||||||
import { Card, CardContent } from "@/components/ui/card";
|
import { Card, CardContent } from "@/components/ui/card";
|
||||||
import { useToast } from "@/hooks/use-toast";
|
import { useToast } from "@/hooks/use-toast";
|
||||||
import { Eye, EyeOff, Mail, Lock, Loader2 } from "lucide-react";
|
import { Eye, EyeOff, Mail, Lock, Loader2 } from "lucide-react";
|
||||||
|
import { usersService } from "@/services/usersApi.mjs";
|
||||||
|
|
||||||
interface LoginFormProps {
|
interface LoginFormProps {
|
||||||
children?: React.ReactNode;
|
children?: React.ReactNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface FormState {
|
interface FormState {
|
||||||
email: string;
|
email: string;
|
||||||
password: string;
|
password: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function LoginForm({ children }: LoginFormProps) {
|
export function LoginForm({ children }: LoginFormProps) {
|
||||||
const [form, setForm] = useState<FormState>({ email: "", password: "" });
|
const [form, setForm] = useState<FormState>({ email: "", password: "" });
|
||||||
const [showPassword, setShowPassword] = useState(false);
|
const [showPassword, setShowPassword] = useState(false);
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
|
|
||||||
// --- NOVOS ESTADOS PARA CONTROLE DE MÚLTIPLOS PERFIS ---
|
const [userRoles, setUserRoles] = useState<string[]>([]);
|
||||||
const [userRoles, setUserRoles] = useState<string[]>([]);
|
const [authenticatedUser, setAuthenticatedUser] = useState<any>(null);
|
||||||
const [authenticatedUser, setAuthenticatedUser] = useState<any>(null);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* --- NOVA FUNÇÃO ---
|
* --- NOVA FUNÇÃO ---
|
||||||
* Finaliza o login com o perfil de dashboard escolhido e redireciona.
|
* Finaliza o login com o perfil de dashboard escolhido e redireciona.
|
||||||
*/
|
*/
|
||||||
const handleRoleSelection = (selectedDashboardRole: string) => {
|
const handleRoleSelection = (selectedDashboardRole: string, user: any) => {
|
||||||
const user = authenticatedUser;
|
if (!user) {
|
||||||
if (!user) {
|
toast({
|
||||||
toast({ title: "Erro de Sessão", description: "Não foi possível encontrar os dados do usuário. Tente novamente.", variant: "destructive" });
|
title: "Erro de Sessão",
|
||||||
setUserRoles([]); // Volta para a tela de login
|
description:
|
||||||
return;
|
"Não foi possível encontrar os dados do usuário. Tente novamente.",
|
||||||
}
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
setUserRoles([]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const completeUserInfo = { ...user, user_metadata: { ...user.user_metadata, role: selectedDashboardRole } };
|
const roleInLowerCase = selectedDashboardRole.toLowerCase();
|
||||||
localStorage.setItem("user_info", JSON.stringify(completeUserInfo));
|
console.log("Salvando no localStorage com o perfil:", roleInLowerCase);
|
||||||
|
|
||||||
let redirectPath = "";
|
const completeUserInfo = {
|
||||||
switch (selectedDashboardRole) {
|
...user,
|
||||||
case "manager":
|
user_metadata: { ...user.user_metadata, role: roleInLowerCase },
|
||||||
redirectPath = "/manager/home";
|
|
||||||
break;
|
|
||||||
case "doctor":
|
|
||||||
redirectPath = "/doctor/medicos";
|
|
||||||
break;
|
|
||||||
case "secretary":
|
|
||||||
redirectPath = "/secretary/pacientes";
|
|
||||||
break;
|
|
||||||
case "patient":
|
|
||||||
redirectPath = "/patient/dashboard";
|
|
||||||
break;
|
|
||||||
case "finance":
|
|
||||||
redirectPath = "/finance/home";
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (redirectPath) {
|
|
||||||
toast({ title: `Entrando como ${selectedDashboardRole}...` });
|
|
||||||
router.push(redirectPath);
|
|
||||||
} else {
|
|
||||||
toast({ title: "Erro", description: "Perfil selecionado inválido.", variant: "destructive" });
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
localStorage.setItem("user_info", JSON.stringify(completeUserInfo));
|
||||||
|
|
||||||
/**
|
let redirectPath = "";
|
||||||
* --- FUNÇÃO ATUALIZADA ---
|
switch (selectedDashboardRole) {
|
||||||
* Lida com a submissão do formulário, busca os perfis e decide o próximo passo.
|
case "gestor":
|
||||||
*/
|
redirectPath = "/manager/dashboard";
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
break;
|
||||||
e.preventDefault();
|
case "admin":
|
||||||
setIsLoading(true);
|
redirectPath = "/manager/dashboard";
|
||||||
localStorage.removeItem("token");
|
break;
|
||||||
localStorage.removeItem("user_info");
|
case "medico":
|
||||||
|
redirectPath = "/doctor/dashboard";
|
||||||
|
break;
|
||||||
|
case "secretaria":
|
||||||
|
redirectPath = "/secretary/dashboard";
|
||||||
|
break;
|
||||||
|
case "paciente":
|
||||||
|
redirectPath = "/patient/dashboard";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
if (redirectPath) {
|
||||||
// A chamada de login continua a mesma
|
toast({ title: `Entrando como ${selectedDashboardRole}...` });
|
||||||
const authData = await login(form.email, form.password);
|
router.push(redirectPath);
|
||||||
const user = authData.user;
|
} else {
|
||||||
if (!user || !user.id) {
|
toast({
|
||||||
throw new Error("Resposta de autenticação inválida.");
|
title: "Erro",
|
||||||
}
|
description: "Perfil selecionado inválido.",
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// Armazena o usuário para uso posterior na seleção de perfil
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
setAuthenticatedUser(user);
|
e.preventDefault();
|
||||||
|
setIsLoading(true);
|
||||||
|
localStorage.removeItem("token");
|
||||||
|
localStorage.removeItem("user_info");
|
||||||
|
|
||||||
// A busca de roles também continua a mesma, usando nosso 'api.get'
|
try {
|
||||||
const rolesData = await api.get(`/rest/v1/user_roles?user_id=eq.${user.id}&select=role`);
|
const authData = await login(form.email, form.password);
|
||||||
|
const user = authData.user;
|
||||||
|
if (!user || !user.id) {
|
||||||
|
throw new Error("Resposta de autenticação inválida.");
|
||||||
|
}
|
||||||
|
|
||||||
if (!rolesData || rolesData.length === 0) {
|
const rolesData = await api.get(
|
||||||
throw new Error("Nenhum perfil de acesso foi encontrado para este usuário.");
|
`/rest/v1/user_roles?user_id=eq.${user.id}&select=role`
|
||||||
}
|
);
|
||||||
|
|
||||||
const rolesFromApi: string[] = rolesData.map((r: any) => r.role);
|
const me = await usersService.getMeSimple();
|
||||||
|
console.log(me.roles);
|
||||||
|
|
||||||
// --- AQUI COMEÇA A NOVA LÓGICA DE DECISÃO ---
|
if (!me.roles || me.roles.length === 0) {
|
||||||
|
throw new Error(
|
||||||
|
"Nenhum perfil de acesso foi encontrado para este usuário."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Caso 1: Usuário é ADMIN, mostra todos os dashboards possíveis.
|
handleRoleSelection(me.roles[0], user);
|
||||||
if (rolesFromApi.includes("admin")) {
|
} catch (error) {
|
||||||
setUserRoles(["manager", "doctor", "secretary", "paciente", "finance"]);
|
localStorage.removeItem("token");
|
||||||
setIsLoading(false); // Para o loading para mostrar a tela de seleção
|
localStorage.removeItem("user_info");
|
||||||
return;
|
toast({
|
||||||
}
|
title: "Erro no Login",
|
||||||
|
description:
|
||||||
|
error instanceof Error
|
||||||
|
? error.message
|
||||||
|
: "Ocorreu um erro inesperado.",
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// Mapeia os roles da API para os perfis de dashboard que o usuário pode acessar
|
// Estado para guardar os botões de seleção de perfil
|
||||||
const displayRoles = new Set<string>();
|
const [roleSelectionUI, setRoleSelectionUI] =
|
||||||
rolesFromApi.forEach((role) => {
|
useState<React.ReactNode | null>(null);
|
||||||
switch (role) {
|
|
||||||
case "gestor":
|
|
||||||
displayRoles.add("manager");
|
|
||||||
displayRoles.add("finance");
|
|
||||||
break;
|
|
||||||
case "medico":
|
|
||||||
displayRoles.add("doctor");
|
|
||||||
break;
|
|
||||||
case "secretaria":
|
|
||||||
displayRoles.add("secretary");
|
|
||||||
break;
|
|
||||||
case "paciente": // Mapeamento de 'patient' (ou outro nome que você use para paciente)
|
|
||||||
displayRoles.add("patient");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const finalRoles = Array.from(displayRoles);
|
return (
|
||||||
|
<Card className="w-full bg-transparent border-0 shadow-none">
|
||||||
// Caso 2: Se o usuário tem apenas UM perfil de dashboard, redireciona direto.
|
<CardContent className="p-0">
|
||||||
if (finalRoles.length === 1) {
|
{!roleSelectionUI ? (
|
||||||
handleRoleSelection(finalRoles[0]);
|
<form onSubmit={handleSubmit} className="space-y-6">
|
||||||
}
|
<div className="space-y-2">
|
||||||
// Caso 3: Se tem múltiplos perfis (ex: 'gestor'), mostra a tela de seleção.
|
<Label htmlFor="email">E-mail</Label>
|
||||||
else {
|
<div className="relative">
|
||||||
setUserRoles(finalRoles);
|
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground w-5 h-5" />
|
||||||
setIsLoading(false);
|
<Input
|
||||||
}
|
id="email"
|
||||||
} catch (error) {
|
type="email"
|
||||||
localStorage.removeItem("token");
|
placeholder="seu.email@exemplo.com"
|
||||||
localStorage.removeItem("user_info");
|
value={form.email}
|
||||||
|
onChange={(e) => setForm({ ...form, email: e.target.value })}
|
||||||
toast({
|
className="pl-10 h-11 focus-visible:ring-blue-600 focus-visible:ring-2"
|
||||||
title: "Erro no Login",
|
required
|
||||||
description: error instanceof Error ? error.message : "Ocorreu um erro inesperado.",
|
disabled={isLoading}
|
||||||
variant: "destructive",
|
autoComplete="username"
|
||||||
});
|
/>
|
||||||
}
|
</div>
|
||||||
|
</div>
|
||||||
setIsLoading(false);
|
<div className="space-y-2">
|
||||||
};
|
<Label htmlFor="password">Senha</Label>
|
||||||
|
<div className="relative">
|
||||||
// --- JSX ATUALIZADO COM RENDERIZAÇÃO CONDICIONAL ---
|
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground w-5 h-5" />
|
||||||
return (
|
<Input
|
||||||
<Card className="w-full bg-transparent border-0 shadow-none">
|
id="password"
|
||||||
<CardContent className="p-0">
|
type={showPassword ? "text" : "password"}
|
||||||
{userRoles.length === 0 ? (
|
placeholder="Digite sua senha"
|
||||||
// VISÃO 1: Formulário de Login (se nenhum perfil foi carregado ainda)
|
value={form.password}
|
||||||
<form onSubmit={handleSubmit} className="space-y-6">
|
onChange={(e) =>
|
||||||
<div className="space-y-2">
|
setForm({ ...form, password: e.target.value })
|
||||||
<Label htmlFor="email">E-mail</Label>
|
}
|
||||||
<div className="relative">
|
className="pl-10 pr-12 h-11 focus-visible:ring-blue-600 focus-visible:ring-2"
|
||||||
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground w-5 h-5" />
|
required
|
||||||
<Input id="email" type="email" placeholder="seu.email@exemplo.com" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} className="pl-10 h-11" required disabled={isLoading} autoComplete="username" />
|
disabled={isLoading}
|
||||||
</div>
|
autoComplete="current-password"
|
||||||
</div>
|
/>
|
||||||
<div className="space-y-2">
|
<button
|
||||||
<Label htmlFor="password">Senha</Label>
|
type="button"
|
||||||
<div className="relative">
|
onClick={() => setShowPassword(!showPassword)}
|
||||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground w-5 h-5" />
|
className="absolute right-2 top-1/2 -translate-y-1/2 h-8 w-8 p-0 text-muted-foreground hover:text-foreground"
|
||||||
<Input id="password" type={showPassword ? "text" : "password"} placeholder="Digite sua senha" value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} className="pl-10 pr-12 h-11" required disabled={isLoading} autoComplete="current-password" />
|
disabled={isLoading}
|
||||||
<button type="button" onClick={() => setShowPassword(!showPassword)} className="absolute right-2 top-1/2 -translate-y-1/2 h-8 w-8 p-0 text-muted-foreground hover:text-foreground" disabled={isLoading}>
|
>
|
||||||
{showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
|
{showPassword ? (
|
||||||
</button>
|
<EyeOff className="w-5 h-5" />
|
||||||
</div>
|
) : (
|
||||||
</div>
|
<Eye className="w-5 h-5" />
|
||||||
<Button type="submit" className="w-full h-11 text-base font-semibold" disabled={isLoading}>
|
)}
|
||||||
{isLoading ? <Loader2 className="w-5 h-5 animate-spin" /> : "Entrar"}
|
</button>
|
||||||
</Button>
|
</div>
|
||||||
</form>
|
</div>
|
||||||
) : (
|
<Button
|
||||||
// VISÃO 2: Tela de Seleção de Perfil (se múltiplos perfis foram encontrados)
|
type="submit"
|
||||||
<div className="space-y-4 animate-in fade-in-50">
|
className="w-full h-11 bg-blue-600 hover:bg-blue-700 text-white"
|
||||||
<h3 className="text-lg font-medium text-center text-foreground">Você tem múltiplos perfis</h3>
|
disabled={isLoading}
|
||||||
<p className="text-sm text-muted-foreground text-center">Selecione com qual perfil deseja entrar:</p>
|
>
|
||||||
<div className="flex flex-col space-y-3 pt-2">
|
{isLoading ? (
|
||||||
{userRoles.map((role) => (
|
<Loader2 className="w-5 h-5 animate-spin" />
|
||||||
<Button key={role} variant="outline" className="h-11 text-base" onClick={() => handleRoleSelection(role)}>
|
) : (
|
||||||
Entrar como: {role.charAt(0).toUpperCase() + role.slice(1)}
|
"Entrar"
|
||||||
</Button>
|
)}
|
||||||
))}
|
</Button>
|
||||||
</div>
|
</form>
|
||||||
</div>
|
) : (
|
||||||
)}
|
<div className="space-y-4 animate-in fade-in-50">
|
||||||
|
<h3 className="text-lg font-medium text-center text-foreground">
|
||||||
{children}
|
Você tem múltiplos perfis
|
||||||
</CardContent>
|
</h3>
|
||||||
</Card>
|
<p className="text-sm text-muted-foreground text-center">
|
||||||
);
|
Selecione com qual perfil deseja entrar:
|
||||||
|
</p>
|
||||||
|
<div className="flex flex-col space-y-3 pt-2">
|
||||||
|
{userRoles.map((role) => (
|
||||||
|
<Button
|
||||||
|
key={role}
|
||||||
|
variant="outline"
|
||||||
|
className="h-11 text-base"
|
||||||
|
onClick={() => handleRoleSelection(role, authenticatedUser)}
|
||||||
|
>
|
||||||
|
Entrar como: {role.charAt(0).toUpperCase() + role.slice(1)}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{children}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
331
components/Sidebar.tsx
Normal file
@ -0,0 +1,331 @@
|
|||||||
|
// Caminho: [seu-caminho]/ManagerLayout.tsx
|
||||||
|
"use client";
|
||||||
|
|
||||||
|
import type React from "react";
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import { useRouter, usePathname } from "next/navigation";
|
||||||
|
import Link from "next/link";
|
||||||
|
import Cookies from "js-cookie";
|
||||||
|
import { api } from "@/services/api.mjs";
|
||||||
|
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
|
||||||
|
import {
|
||||||
|
LogOut,
|
||||||
|
ChevronLeft,
|
||||||
|
ChevronRight,
|
||||||
|
Home,
|
||||||
|
CalendarCheck2,
|
||||||
|
ClipboardPlus,
|
||||||
|
CalendarClock,
|
||||||
|
Users,
|
||||||
|
SquareUser,
|
||||||
|
ClipboardList,
|
||||||
|
Stethoscope,
|
||||||
|
ClipboardMinus,
|
||||||
|
} from "lucide-react";
|
||||||
|
|
||||||
|
import SidebarUserSection from "@/components/ui/userToolTip";
|
||||||
|
|
||||||
|
interface UserData {
|
||||||
|
id: string;
|
||||||
|
email: string;
|
||||||
|
app_metadata: {
|
||||||
|
user_role: string;
|
||||||
|
};
|
||||||
|
user_metadata: {
|
||||||
|
cpf: string;
|
||||||
|
email_verified: boolean;
|
||||||
|
full_name: string;
|
||||||
|
phone_mobile: string;
|
||||||
|
role: string;
|
||||||
|
};
|
||||||
|
identities: {
|
||||||
|
identity_id: string;
|
||||||
|
id: string;
|
||||||
|
user_id: string;
|
||||||
|
provider: string;
|
||||||
|
}[];
|
||||||
|
is_anonymous: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MenuItem {
|
||||||
|
href: string;
|
||||||
|
icon: React.ElementType;
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SidebarProps {
|
||||||
|
children: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Sidebar({ children }: SidebarProps) {
|
||||||
|
const [userData, setUserData] = useState<UserData>();
|
||||||
|
const [role, setRole] = useState<string>();
|
||||||
|
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
|
||||||
|
const [showLogoutDialog, setShowLogoutDialog] = useState(false);
|
||||||
|
const router = useRouter();
|
||||||
|
const pathname = usePathname();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const userInfoString = localStorage.getItem("user_info");
|
||||||
|
const token = localStorage.getItem("token");
|
||||||
|
|
||||||
|
if (userInfoString && token) {
|
||||||
|
const userInfo = JSON.parse(userInfoString);
|
||||||
|
|
||||||
|
setUserData({
|
||||||
|
id: userInfo.id ?? "",
|
||||||
|
email: userInfo.email ?? "",
|
||||||
|
app_metadata: {
|
||||||
|
user_role: userInfo.app_metadata?.user_role ?? "patient",
|
||||||
|
},
|
||||||
|
user_metadata: {
|
||||||
|
cpf: userInfo.user_metadata?.cpf ?? "",
|
||||||
|
email_verified: userInfo.user_metadata?.email_verified ?? false,
|
||||||
|
full_name: userInfo.user_metadata?.full_name ?? "",
|
||||||
|
phone_mobile: userInfo.user_metadata?.phone_mobile ?? "",
|
||||||
|
role: userInfo.user_metadata?.role ?? "",
|
||||||
|
},
|
||||||
|
identities:
|
||||||
|
userInfo.identities?.map((identity: any) => ({
|
||||||
|
identity_id: identity.identity_id ?? "",
|
||||||
|
id: identity.id ?? "",
|
||||||
|
user_id: identity.user_id ?? "",
|
||||||
|
provider: identity.provider ?? "",
|
||||||
|
})) ?? [],
|
||||||
|
is_anonymous: userInfo.is_anonymous ?? false,
|
||||||
|
});
|
||||||
|
setRole(userInfo.user_metadata?.role);
|
||||||
|
} else {
|
||||||
|
router.push("/login");
|
||||||
|
}
|
||||||
|
}, [router]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handleResize = () => {
|
||||||
|
if (window.innerWidth < 1024) {
|
||||||
|
setSidebarCollapsed(true);
|
||||||
|
} else {
|
||||||
|
setSidebarCollapsed(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
handleResize();
|
||||||
|
window.addEventListener("resize", handleResize);
|
||||||
|
return () => window.removeEventListener("resize", handleResize);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleLogout = () => setShowLogoutDialog(true);
|
||||||
|
|
||||||
|
const confirmLogout = async () => {
|
||||||
|
try {
|
||||||
|
await api.logout();
|
||||||
|
} catch (error) {
|
||||||
|
} finally {
|
||||||
|
localStorage.removeItem("user_info");
|
||||||
|
localStorage.removeItem("token");
|
||||||
|
Cookies.remove("access_token");
|
||||||
|
|
||||||
|
setShowLogoutDialog(false);
|
||||||
|
router.push("/");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const cancelLogout = () => setShowLogoutDialog(false);
|
||||||
|
|
||||||
|
const SetMenuItems = (role: any) => {
|
||||||
|
const patientItems: MenuItem[] = [
|
||||||
|
{ href: "/patient/dashboard", icon: Home, label: "Dashboard" },
|
||||||
|
{
|
||||||
|
href: "/patient/schedule",
|
||||||
|
icon: CalendarClock,
|
||||||
|
label: "Agendar Consulta",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: "/patient/appointments",
|
||||||
|
icon: CalendarCheck2,
|
||||||
|
label: "Minhas Consultas",
|
||||||
|
},
|
||||||
|
{ href: "/patient/reports", icon: ClipboardPlus, label: "Meus Laudos" },
|
||||||
|
{ href: "/patient/profile", icon: SquareUser, label: "Meus Dados" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const doctorItems: MenuItem[] = [
|
||||||
|
{ href: "/doctor/dashboard", icon: Home, label: "Dashboard" },
|
||||||
|
{ href: "/doctor/medicos", icon: Users, label: "Gestão de Pacientes" },
|
||||||
|
{ href: "/doctor/consultas", icon: CalendarCheck2, label: "Consultas" },
|
||||||
|
{
|
||||||
|
href: "/doctor/disponibilidade",
|
||||||
|
icon: ClipboardList,
|
||||||
|
label: "Disponibilidade",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const secretaryItems: MenuItem[] = [
|
||||||
|
{ href: "/secretary/dashboard", icon: Home, label: "Dashboard" },
|
||||||
|
{
|
||||||
|
href: "/secretary/appointments",
|
||||||
|
icon: CalendarCheck2,
|
||||||
|
label: "Consultas",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: "/secretary/schedule",
|
||||||
|
icon: CalendarClock,
|
||||||
|
label: "Agendar Consulta",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: "/secretary/pacientes",
|
||||||
|
icon: Users,
|
||||||
|
label: "Gestão de Pacientes",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const managerItems: MenuItem[] = [
|
||||||
|
{ href: "/manager/dashboard", icon: Home, label: "Dashboard" },
|
||||||
|
{ href: "/manager/usuario", icon: Users, label: "Gestão de Usuários" },
|
||||||
|
{ href: "/manager/home", icon: Stethoscope, label: "Gestão de Médicos" },
|
||||||
|
{ href: "/manager/pacientes", icon: Users, label: "Gestão de Pacientes" },
|
||||||
|
{ href: "/secretary/appointments", icon: CalendarCheck2, label: "Consultas" },
|
||||||
|
{ href: "/manager/disponibilidade", icon: ClipboardList, label: "Disponibilidade" },
|
||||||
|
];
|
||||||
|
|
||||||
|
switch (role) {
|
||||||
|
case "gestor":
|
||||||
|
case "admin":
|
||||||
|
return managerItems;
|
||||||
|
case "medico":
|
||||||
|
return doctorItems;
|
||||||
|
case "secretaria":
|
||||||
|
return secretaryItems;
|
||||||
|
case "paciente":
|
||||||
|
default:
|
||||||
|
return patientItems;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const menuItems = SetMenuItems(role);
|
||||||
|
|
||||||
|
if (!userData) {
|
||||||
|
return (
|
||||||
|
<div className="flex h-screen w-full items-center justify-center">
|
||||||
|
Carregando...
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-gray-50 flex">
|
||||||
|
<div
|
||||||
|
className={`fixed top-0 h-screen flex flex-col z-30 transition-all duration-300
|
||||||
|
${sidebarCollapsed ? "w-16" : "w-64"}
|
||||||
|
bg-[#123965] text-white`}
|
||||||
|
>
|
||||||
|
{/* TOPO */}
|
||||||
|
<div className="p-4 border-b border-white/10 flex items-center justify-between">
|
||||||
|
{!sidebarCollapsed && (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<div className="bg-white p-1 rounded-lg">
|
||||||
|
<img
|
||||||
|
src="/Logo MedConnect.png"
|
||||||
|
alt="Logo MedConnect"
|
||||||
|
className="w-12 h-12 object-contain"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<span className="font-semibold text-white text-lg">
|
||||||
|
MedConnect
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
|
||||||
|
className="p-1 text-white hover:bg-white/10 cursor-pointer"
|
||||||
|
>
|
||||||
|
{sidebarCollapsed ? (
|
||||||
|
<ChevronRight className="w-5 h-5" />
|
||||||
|
) : (
|
||||||
|
<ChevronLeft className="w-5 h-5" />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* MENU */}
|
||||||
|
<nav className="flex-1 p-3 overflow-y-auto">
|
||||||
|
{menuItems.map((item) => {
|
||||||
|
const Icon = item.icon;
|
||||||
|
const isActive = pathname === item.href;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Link key={item.label} href={item.href}>
|
||||||
|
<div
|
||||||
|
className={`
|
||||||
|
flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors
|
||||||
|
${
|
||||||
|
isActive
|
||||||
|
? "bg-white/20 text-white font-semibold"
|
||||||
|
: "text-white/80 hover:bg-white/10 hover:text-white"
|
||||||
|
}
|
||||||
|
`}
|
||||||
|
>
|
||||||
|
<Icon className="w-5 h-5 flex-shrink-0" />
|
||||||
|
{!sidebarCollapsed && (
|
||||||
|
<span className="font-medium">{item.label}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
{/* PERFIL ORIGINAL + NOME BRANCO */}
|
||||||
|
<div className="mt-auto p-3 border-t border-white/10">
|
||||||
|
<SidebarUserSection
|
||||||
|
userData={userData}
|
||||||
|
sidebarCollapsed={sidebarCollapsed}
|
||||||
|
handleLogout={handleLogout}
|
||||||
|
isActive={role !== "paciente"}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className={`flex-1 flex flex-col transition-all duration-300 ${
|
||||||
|
sidebarCollapsed ? "ml-16" : "ml-64"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<main className="flex-1 p-4 md:p-6">{children}</main>
|
||||||
|
</div>
|
||||||
|
<Dialog open={showLogoutDialog} onOpenChange={setShowLogoutDialog}>
|
||||||
|
<DialogContent className="sm:max-w-md">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Confirmar Saída</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Deseja realmente sair do sistema? Você precisará fazer login
|
||||||
|
novamente.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<DialogFooter className="flex gap-2">
|
||||||
|
<Button variant="outline" onClick={cancelLogout}>
|
||||||
|
Cancelar
|
||||||
|
</Button>
|
||||||
|
<Button variant="destructive" onClick={confirmLogout}>
|
||||||
|
<LogOut className="mr-2 h-4 w-4" />
|
||||||
|
Sair
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -1,466 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import type React from "react";
|
|
||||||
import { useState, useEffect } from "react";
|
|
||||||
import { useRouter, usePathname } from "next/navigation";
|
|
||||||
import Link from "next/link";
|
|
||||||
import Cookies from "js-cookie"; // Manteremos para o logout, se necessário
|
|
||||||
import { api } from "@/services/api.mjs";
|
|
||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { Input } from "@/components/ui/input";
|
|
||||||
import { Badge } from "@/components/ui/badge";
|
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogDescription,
|
|
||||||
DialogFooter,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
} from "@/components/ui/dialog";
|
|
||||||
import {
|
|
||||||
Search,
|
|
||||||
Bell,
|
|
||||||
Calendar,
|
|
||||||
Clock,
|
|
||||||
User,
|
|
||||||
LogOut,
|
|
||||||
Menu,
|
|
||||||
X,
|
|
||||||
Home,
|
|
||||||
FileText,
|
|
||||||
ChevronLeft,
|
|
||||||
ChevronRight,
|
|
||||||
} from "lucide-react";
|
|
||||||
|
|
||||||
interface DoctorData {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
email: string;
|
|
||||||
phone: string;
|
|
||||||
cpf: string;
|
|
||||||
crm: string;
|
|
||||||
specialty: string;
|
|
||||||
department: string;
|
|
||||||
permissions: object;
|
|
||||||
role: string
|
|
||||||
}
|
|
||||||
|
|
||||||
interface PatientLayoutProps {
|
|
||||||
children: React.ReactNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function DoctorLayout({ children }: PatientLayoutProps) {
|
|
||||||
const [doctorData, setDoctorData] = useState<DoctorData | null>(null);
|
|
||||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
|
|
||||||
const [showLogoutDialog, setShowLogoutDialog] = useState(false);
|
|
||||||
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
|
|
||||||
const [windowWidth, setWindowWidth] = useState(0);
|
|
||||||
const isMobile = windowWidth < 1024;
|
|
||||||
const router = useRouter();
|
|
||||||
const pathname = usePathname();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const userInfoString = localStorage.getItem("user_info");
|
|
||||||
// --- ALTERAÇÃO PRINCIPAL AQUI ---
|
|
||||||
// Procurando o token no localStorage, onde ele foi realmente salvo.
|
|
||||||
const token = localStorage.getItem("token");
|
|
||||||
|
|
||||||
if (userInfoString && token) {
|
|
||||||
const userInfo = JSON.parse(userInfoString);
|
|
||||||
|
|
||||||
setDoctorData({
|
|
||||||
id: userInfo.id || "",
|
|
||||||
name: userInfo.user_metadata?.full_name || "Doutor(a)",
|
|
||||||
email: userInfo.email || "",
|
|
||||||
specialty: userInfo.user_metadata?.specialty || "Especialidade",
|
|
||||||
phone: userInfo.phone || "",
|
|
||||||
cpf: "",
|
|
||||||
crm: "",
|
|
||||||
department: "",
|
|
||||||
permissions: {},
|
|
||||||
role: userInfo.role
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
// Se não encontrar, aí sim redireciona.
|
|
||||||
router.push("/login");
|
|
||||||
}
|
|
||||||
}, [router]);
|
|
||||||
|
|
||||||
// O restante do seu código permanece exatamente o mesmo...
|
|
||||||
useEffect(() => {
|
|
||||||
const handleResize = () => setWindowWidth(window.innerWidth);
|
|
||||||
handleResize();
|
|
||||||
window.addEventListener("resize", handleResize);
|
|
||||||
return () => window.removeEventListener("resize", handleResize);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (isMobile) {
|
|
||||||
setSidebarCollapsed(true);
|
|
||||||
} else {
|
|
||||||
setSidebarCollapsed(false);
|
|
||||||
}
|
|
||||||
}, [isMobile]);
|
|
||||||
|
|
||||||
const handleLogout = () => {
|
|
||||||
setShowLogoutDialog(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
// --- ALTERAÇÃO 2: A função de logout agora é MUITO mais simples ---
|
|
||||||
const confirmLogout = async () => {
|
|
||||||
try {
|
|
||||||
// Chama a função centralizada para fazer o logout no servidor
|
|
||||||
await api.logout();
|
|
||||||
} catch (error) {
|
|
||||||
// O erro já é logado dentro da função api.logout, não precisamos fazer nada aqui
|
|
||||||
} finally {
|
|
||||||
// A responsabilidade do componente é apenas limpar o estado local e redirecionar
|
|
||||||
localStorage.removeItem("user_info");
|
|
||||||
localStorage.removeItem("token");
|
|
||||||
Cookies.remove("access_token"); // Limpeza de segurança
|
|
||||||
|
|
||||||
setShowLogoutDialog(false);
|
|
||||||
router.push("/"); // Redireciona para a home
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const cancelLogout = () => {
|
|
||||||
setShowLogoutDialog(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
const toggleMobileMenu = () => {
|
|
||||||
setIsMobileMenuOpen(!isMobileMenuOpen);
|
|
||||||
};
|
|
||||||
|
|
||||||
const menuItems = [
|
|
||||||
{
|
|
||||||
href: "/doctor/dashboard",
|
|
||||||
icon: Home,
|
|
||||||
label: "Dashboard",
|
|
||||||
// Botão para o dashboard do médico
|
|
||||||
},
|
|
||||||
{
|
|
||||||
href: "/doctor/consultas",
|
|
||||||
icon: Calendar,
|
|
||||||
label: "Consultas",
|
|
||||||
// Botão para página de consultas marcadas do médico atual
|
|
||||||
},
|
|
||||||
{
|
|
||||||
href: "/doctor/medicos",
|
|
||||||
icon: User,
|
|
||||||
label: "Pacientes",
|
|
||||||
// Botão para a página de visualização de todos os pacientes
|
|
||||||
},
|
|
||||||
{
|
|
||||||
href: "/doctor/disponibilidade",
|
|
||||||
icon: Calendar,
|
|
||||||
label: "Disponibilidade",
|
|
||||||
// Botão para o dashboard do médico
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
if (!doctorData) {
|
|
||||||
return <div>Carregando...</div>;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
// O restante do seu código JSX permanece exatamente o mesmo
|
|
||||||
<div className="min-h-screen bg-background flex">
|
|
||||||
<div
|
|
||||||
className={`bg-card border-r border transition-all duration-300 ${
|
|
||||||
sidebarCollapsed ? "w-16" : "w-64"
|
|
||||||
} fixed left-0 top-0 h-screen flex flex-col z-50`}
|
|
||||||
>
|
|
||||||
<div className="p-4 border-b border">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
{!sidebarCollapsed && (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<div className="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center">
|
|
||||||
<div className="w-4 h-4 bg-white rounded-sm"></div>
|
|
||||||
</div>
|
|
||||||
<span className="font-semibold text-gray-900">MediConnect</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
|
|
||||||
className="p-1"
|
|
||||||
>
|
|
||||||
{sidebarCollapsed ? (
|
|
||||||
<ChevronRight className="w-4 h-4" />
|
|
||||||
) : (
|
|
||||||
<ChevronLeft className="w-4 h-4" />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<nav className="flex-1 p-2 overflow-y-auto">
|
|
||||||
{menuItems.map((item) => {
|
|
||||||
const Icon = item.icon;
|
|
||||||
const isActive =
|
|
||||||
pathname === item.href ||
|
|
||||||
(item.href !== "/" && pathname.startsWith(item.href));
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Link key={item.href} href={item.href}>
|
|
||||||
<div
|
|
||||||
className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${
|
|
||||||
isActive
|
|
||||||
? "bg-blue-50 text-blue-600 border-r-2 border-blue-600"
|
|
||||||
: "text-gray-600 hover:bg-gray-50"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<Icon className="w-5 h-5 flex-shrink-0" />
|
|
||||||
{!sidebarCollapsed && (
|
|
||||||
<span className="font-medium">{item.label}</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</Link>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</nav>
|
|
||||||
// ... (seu código anterior)
|
|
||||||
{/* Sidebar para desktop */}
|
|
||||||
<div
|
|
||||||
className={`bg-white border-r border-gray-200 transition-all duration-300 ${
|
|
||||||
sidebarCollapsed ? "w-16" : "w-64"
|
|
||||||
} fixed left-0 top-0 h-screen flex flex-col z-50`}
|
|
||||||
>
|
|
||||||
<div className="p-4 border-b border-gray-200">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
{!sidebarCollapsed && (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<div className="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center">
|
|
||||||
<div className="w-4 h-4 bg-white rounded-sm"></div>
|
|
||||||
</div>
|
|
||||||
<span className="font-semibold text-gray-900">
|
|
||||||
MediConnect
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
|
|
||||||
className="p-1"
|
|
||||||
>
|
|
||||||
{sidebarCollapsed ? (
|
|
||||||
<ChevronRight className="w-4 h-4" />
|
|
||||||
) : (
|
|
||||||
<ChevronLeft className="w-4 h-4" />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<nav className="flex-1 p-2 overflow-y-auto">
|
|
||||||
{menuItems.map((item) => {
|
|
||||||
const Icon = item.icon;
|
|
||||||
const isActive =
|
|
||||||
pathname === item.href ||
|
|
||||||
(item.href !== "/" && pathname.startsWith(item.href));
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Link key={item.href} href={item.href}>
|
|
||||||
<div
|
|
||||||
className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${
|
|
||||||
isActive
|
|
||||||
? "bg-blue-50 text-blue-600 border-r-2 border-blue-600"
|
|
||||||
: "text-gray-600 hover:bg-gray-50"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<Icon className="w-5 h-5 flex-shrink-0" />
|
|
||||||
{!sidebarCollapsed && (
|
|
||||||
<span className="font-medium">{item.label}</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</Link>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</nav>
|
|
||||||
|
|
||||||
<div className="border-t p-4 mt-auto">
|
|
||||||
<div className="flex items-center space-x-3 mb-4">
|
|
||||||
{!sidebarCollapsed && (
|
|
||||||
<>
|
|
||||||
<Avatar>
|
|
||||||
<AvatarImage src="/placeholder.svg?height=40&width=40" />
|
|
||||||
<AvatarFallback>
|
|
||||||
{doctorData.name
|
|
||||||
.split(" ")
|
|
||||||
.map((n) => n[0])
|
|
||||||
.join("")}
|
|
||||||
|
|
||||||
</AvatarFallback>
|
|
||||||
</Avatar>
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<p className="text-sm font-medium text-gray-900 truncate">
|
|
||||||
{doctorData.name}
|
|
||||||
</p>
|
|
||||||
<p className="text-xs text-gray-500 truncate">
|
|
||||||
{doctorData.specialty}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{sidebarCollapsed && (
|
|
||||||
<Avatar className="mx-auto">
|
|
||||||
<AvatarImage src="/placeholder.svg?height=40&width=40" />
|
|
||||||
<AvatarFallback>
|
|
||||||
{doctorData.name
|
|
||||||
.split(" ")
|
|
||||||
.map((n) => n[0])
|
|
||||||
.join("")}
|
|
||||||
</AvatarFallback>
|
|
||||||
</Avatar>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div
|
|
||||||
className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors text-muted-foreground hover:bg-accent cursor-pointer ${
|
|
||||||
sidebarCollapsed ? "justify-center" : ""
|
|
||||||
}`}
|
|
||||||
onClick={handleLogout}
|
|
||||||
>
|
|
||||||
<LogOut className="w-5 h-5 flex-shrink-0" />
|
|
||||||
{!sidebarCollapsed && <span className="font-medium">Sair</span>}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{isMobileMenuOpen && (
|
|
||||||
<div
|
|
||||||
className="fixed inset-0 bg-black bg-opacity-50 z-40 md:hidden"
|
|
||||||
onClick={toggleMobileMenu}
|
|
||||||
></div>
|
|
||||||
)}
|
|
||||||
<div
|
|
||||||
className={`bg-white border-r border-gray-200 fixed left-0 top-0 h-screen flex flex-col z-50 transition-transform duration-300 md:hidden ${
|
|
||||||
isMobileMenuOpen ? "translate-x-0 w-64" : "-translate-x-full w-64"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<div className="p-4 border-b border-gray-200 flex items-center justify-between">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<div className="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center">
|
|
||||||
<div className="w-4 h-4 bg-white rounded-sm"></div>
|
|
||||||
</div>
|
|
||||||
<span className="font-semibold text-gray-900">Hospital System</span>
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
onClick={toggleMobileMenu}
|
|
||||||
className="p-1"
|
|
||||||
>
|
|
||||||
<X className="w-4 h-4" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<nav className="flex-1 p-2 overflow-y-auto">
|
|
||||||
{menuItems.map((item) => {
|
|
||||||
const Icon = item.icon;
|
|
||||||
const isActive =
|
|
||||||
pathname === item.href ||
|
|
||||||
(item.href !== "/" && pathname.startsWith(item.href));
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Link key={item.href} href={item.href} onClick={toggleMobileMenu}>
|
|
||||||
<div
|
|
||||||
className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${
|
|
||||||
isActive
|
|
||||||
? "bg-accent text-accent-foreground border-r-2 border-primary"
|
|
||||||
: "text-muted-foreground hover:bg-accent"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<Icon className="w-5 h-5 flex-shrink-0" />
|
|
||||||
<span className="font-medium">{item.label}</span>
|
|
||||||
</div>
|
|
||||||
</Link>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</nav>
|
|
||||||
|
|
||||||
<div className="border-t p-4 mt-auto">
|
|
||||||
<div className="flex items-center space-x-3 mb-4">
|
|
||||||
<Avatar>
|
|
||||||
<AvatarImage src="/placeholder.svg?height=40&width=40" />
|
|
||||||
<AvatarFallback>
|
|
||||||
{doctorData.name
|
|
||||||
.split(" ")
|
|
||||||
.map((n) => n[0])
|
|
||||||
.join("")}
|
|
||||||
</AvatarFallback>
|
|
||||||
</Avatar>
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<p className="text-sm font-medium text-gray-900 truncate">
|
|
||||||
{doctorData.name}
|
|
||||||
</p>
|
|
||||||
<p className="text-xs text-gray-500 truncate">
|
|
||||||
{doctorData.specialty}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
className="w-full bg-transparent"
|
|
||||||
onClick={() => {
|
|
||||||
handleLogout();
|
|
||||||
toggleMobileMenu();
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<LogOut className="mr-2 h-4 w-4" />
|
|
||||||
Sair
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div
|
|
||||||
className={`flex-1 flex flex-col transition-all duration-300 ${
|
|
||||||
sidebarCollapsed ? "ml-16" : "ml-64"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<header className="bg-card border-b border px-6 py-4">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div className="flex items-center gap-4 flex-1"></div>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
<Button variant="ghost" size="sm" className="relative">
|
|
||||||
<Bell className="w-5 h-5" />
|
|
||||||
<Badge className="absolute -top-1 -right-1 w-5 h-5 p-0 flex items-center justify-center bg-red-500 text-white text-xs">
|
|
||||||
1
|
|
||||||
</Badge>
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<main className="flex-1 p-6">{children}</main>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Dialog open={showLogoutDialog} onOpenChange={setShowLogoutDialog}>
|
|
||||||
<DialogContent className="sm:max-w-md">
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle>Confirmar Saída</DialogTitle>
|
|
||||||
<DialogDescription>
|
|
||||||
Deseja realmente sair do sistema? Você precisará fazer login
|
|
||||||
novamente para acessar sua conta.
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
<DialogFooter className="flex gap-2">
|
|
||||||
<Button variant="outline" onClick={cancelLogout}>
|
|
||||||
Cancelar
|
|
||||||
</Button>
|
|
||||||
<Button variant="destructive" onClick={confirmLogout}>
|
|
||||||
<LogOut className="mr-2 h-4 w-4" />
|
|
||||||
Sair
|
|
||||||
</Button>
|
|
||||||
</DialogFooter>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -1,283 +0,0 @@
|
|||||||
// Caminho: [seu-caminho]/FinancierLayout.tsx
|
|
||||||
"use client";
|
|
||||||
|
|
||||||
import Cookies from "js-cookie";
|
|
||||||
import type React from "react";
|
|
||||||
import { useState, useEffect } from "react";
|
|
||||||
import { useRouter, usePathname } from "next/navigation";
|
|
||||||
import Link from "next/link";
|
|
||||||
import { api } from "@/services/api.mjs";
|
|
||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { Input } from "@/components/ui/input";
|
|
||||||
import { Badge } from "@/components/ui/badge";
|
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogDescription,
|
|
||||||
DialogFooter,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
} from "@/components/ui/dialog";
|
|
||||||
import {
|
|
||||||
Search,
|
|
||||||
Bell,
|
|
||||||
Calendar,
|
|
||||||
Clock,
|
|
||||||
User,
|
|
||||||
LogOut,
|
|
||||||
Menu,
|
|
||||||
X,
|
|
||||||
Home,
|
|
||||||
FileText,
|
|
||||||
ChevronLeft,
|
|
||||||
ChevronRight,
|
|
||||||
} from "lucide-react";
|
|
||||||
|
|
||||||
interface FinancierData {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
email: string;
|
|
||||||
phone: string;
|
|
||||||
cpf: string;
|
|
||||||
department: string;
|
|
||||||
permissions: object;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface PatientLayoutProps {
|
|
||||||
children: React.ReactNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function FinancierLayout({ children }: PatientLayoutProps) {
|
|
||||||
const [financierData, setFinancierData] = useState<FinancierData | null>(
|
|
||||||
null
|
|
||||||
);
|
|
||||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
|
|
||||||
const [showLogoutDialog, setShowLogoutDialog] = useState(false);
|
|
||||||
const router = useRouter();
|
|
||||||
const pathname = usePathname();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const userInfoString = localStorage.getItem("user_info");
|
|
||||||
// --- ALTERAÇÃO 1: Buscando o token no localStorage ---
|
|
||||||
const token = localStorage.getItem("token");
|
|
||||||
|
|
||||||
if (userInfoString && token) {
|
|
||||||
const userInfo = JSON.parse(userInfoString);
|
|
||||||
|
|
||||||
setFinancierData({
|
|
||||||
id: userInfo.id || "",
|
|
||||||
name: userInfo.user_metadata?.full_name || "Financeiro",
|
|
||||||
email: userInfo.email || "",
|
|
||||||
department:
|
|
||||||
userInfo.user_metadata?.department || "Departamento Financeiro",
|
|
||||||
phone: userInfo.phone || "",
|
|
||||||
cpf: "",
|
|
||||||
permissions: {},
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
// --- ALTERAÇÃO 2: Redirecionando para o login central ---
|
|
||||||
router.push("/login");
|
|
||||||
}
|
|
||||||
}, [router]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const handleResize = () => {
|
|
||||||
if (window.innerWidth < 1024) {
|
|
||||||
setSidebarCollapsed(true);
|
|
||||||
} else {
|
|
||||||
setSidebarCollapsed(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
handleResize();
|
|
||||||
window.addEventListener("resize", handleResize);
|
|
||||||
return () => window.removeEventListener("resize", handleResize);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleLogout = () => {
|
|
||||||
setShowLogoutDialog(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
// --- ALTERAÇÃO 2: A função de logout agora é MUITO mais simples ---
|
|
||||||
const confirmLogout = async () => {
|
|
||||||
try {
|
|
||||||
// Chama a função centralizada para fazer o logout no servidor
|
|
||||||
await api.logout();
|
|
||||||
} catch (error) {
|
|
||||||
// O erro já é logado dentro da função api.logout, não precisamos fazer nada aqui
|
|
||||||
} finally {
|
|
||||||
// A responsabilidade do componente é apenas limpar o estado local e redirecionar
|
|
||||||
localStorage.removeItem("user_info");
|
|
||||||
localStorage.removeItem("token");
|
|
||||||
Cookies.remove("access_token"); // Limpeza de segurança
|
|
||||||
|
|
||||||
setShowLogoutDialog(false);
|
|
||||||
router.push("/"); // Redireciona para a home
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const cancelLogout = () => {
|
|
||||||
setShowLogoutDialog(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
const menuItems = [
|
|
||||||
{ href: "#", icon: Home, label: "Dashboard" },
|
|
||||||
{ href: "#", icon: Calendar, label: "Relatórios financeiros" },
|
|
||||||
{ href: "#", icon: User, label: "Finanças Gerais" },
|
|
||||||
{ href: "#", icon: Calendar, label: "Configurações" },
|
|
||||||
];
|
|
||||||
|
|
||||||
if (!financierData) {
|
|
||||||
return (
|
|
||||||
<div className="flex h-screen w-full items-center justify-center">
|
|
||||||
Carregando...
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
// O restante do seu código JSX permanece inalterado
|
|
||||||
<div className="min-h-screen bg-background flex">
|
|
||||||
<div
|
|
||||||
className={`bg-card border-r border-border transition-all duration-300 ${
|
|
||||||
sidebarCollapsed ? "w-16" : "w-64"
|
|
||||||
} fixed left-0 top-0 h-screen flex flex-col z-10`}
|
|
||||||
>
|
|
||||||
<div className="p-4 border-b border-border">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
{!sidebarCollapsed && (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
|
|
||||||
<div className="w-4 h-4 bg-primary-foreground rounded-sm"></div>
|
|
||||||
</div>
|
|
||||||
<span className="font-semibold text-foreground">
|
|
||||||
MediConnect
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
|
|
||||||
className="p-1"
|
|
||||||
>
|
|
||||||
{sidebarCollapsed ? (
|
|
||||||
<ChevronRight className="w-4 h-4" />
|
|
||||||
) : (
|
|
||||||
<ChevronLeft className="w-4 h-4" />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<nav className="flex-1 p-2 overflow-y-auto">
|
|
||||||
{menuItems.map((item) => {
|
|
||||||
const Icon = item.icon;
|
|
||||||
const isActive =
|
|
||||||
pathname === item.href ||
|
|
||||||
(item.href !== "/" && pathname.startsWith(item.href));
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Link key={item.href} href={item.href}>
|
|
||||||
<div
|
|
||||||
className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${
|
|
||||||
isActive
|
|
||||||
? "bg-accent text-accent-foreground"
|
|
||||||
: "text-muted-foreground hover:bg-accent hover:text-accent-foreground"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<Icon className="w-5 h-5 flex-shrink-0" />
|
|
||||||
{!sidebarCollapsed && (
|
|
||||||
<span className="font-medium">{item.label}</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</Link>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</nav>
|
|
||||||
|
|
||||||
<div className="border-t p-4 mt-auto">
|
|
||||||
<div className="flex items-center space-x-3 mb-4">
|
|
||||||
<Avatar>
|
|
||||||
<AvatarImage src="/placeholder.svg?height=40&width=40" />
|
|
||||||
<AvatarFallback>
|
|
||||||
{financierData.name
|
|
||||||
.split(" ")
|
|
||||||
.map((n) => n[0])
|
|
||||||
.join("")}
|
|
||||||
</AvatarFallback>
|
|
||||||
</Avatar>
|
|
||||||
{!sidebarCollapsed && (
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<p className="text-sm font-medium text-foreground truncate">
|
|
||||||
{financierData.name}
|
|
||||||
</p>
|
|
||||||
<p className="text-xs text-muted-foreground truncate">
|
|
||||||
{financierData.department}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
className={
|
|
||||||
sidebarCollapsed
|
|
||||||
? "w-full bg-transparent flex justify-center items-center p-2"
|
|
||||||
: "w-full bg-transparent"
|
|
||||||
}
|
|
||||||
onClick={handleLogout}
|
|
||||||
>
|
|
||||||
<LogOut className={sidebarCollapsed ? "h-5 w-5" : "mr-2 h-4 w-4"} />
|
|
||||||
{!sidebarCollapsed && "Sair"}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div
|
|
||||||
className={`flex-1 flex flex-col transition-all duration-300 ${
|
|
||||||
sidebarCollapsed ? "ml-16" : "ml-64"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<header className="bg-card border-b border-border px-6 py-4">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div className="flex items-center gap-4 flex-1 max-w-md"></div>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
<Button variant="ghost" size="sm" className="relative">
|
|
||||||
<Bell className="w-5 h-5" />
|
|
||||||
<Badge className="absolute -top-1 -right-1 w-5 h-5 p-0 flex items-center justify-center bg-destructive text-destructive-foreground text-xs">
|
|
||||||
1
|
|
||||||
</Badge>
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<main className="flex-1 p-6">{children}</main>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Dialog open={showLogoutDialog} onOpenChange={setShowLogoutDialog}>
|
|
||||||
<DialogContent className="sm:max-w-md">
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle>Confirmar Saída</DialogTitle>
|
|
||||||
<DialogDescription>
|
|
||||||
Deseja realmente sair do sistema? Você precisará fazer login
|
|
||||||
novamente para acessar sua conta.
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
<DialogFooter className="flex gap-2">
|
|
||||||
<Button variant="outline" onClick={cancelLogout}>
|
|
||||||
Cancelar
|
|
||||||
</Button>
|
|
||||||
<Button variant="destructive" onClick={confirmLogout}>
|
|
||||||
<LogOut className="mr-2 h-4 w-4" />
|
|
||||||
Sair
|
|
||||||
</Button>
|
|
||||||
</DialogFooter>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -1,227 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import type React from "react"
|
|
||||||
|
|
||||||
import { useState, useEffect } from "react"
|
|
||||||
import Link from "next/link"
|
|
||||||
import { useRouter, usePathname } from "next/navigation"
|
|
||||||
import { Button } from "@/components/ui/button"
|
|
||||||
import { Input } from "@/components/ui/input"
|
|
||||||
import { Badge } from "@/components/ui/badge"
|
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
|
|
||||||
import {
|
|
||||||
Search,
|
|
||||||
Bell,
|
|
||||||
Settings,
|
|
||||||
Users,
|
|
||||||
UserCheck,
|
|
||||||
Calendar,
|
|
||||||
Clock,
|
|
||||||
User,
|
|
||||||
LogOut,
|
|
||||||
FileText,
|
|
||||||
BarChart3,
|
|
||||||
Home,
|
|
||||||
ChevronLeft,
|
|
||||||
ChevronRight,
|
|
||||||
} from "lucide-react"
|
|
||||||
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogDescription,
|
|
||||||
DialogFooter,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
} from "@/components/ui/dialog"
|
|
||||||
|
|
||||||
interface PatientData {
|
|
||||||
name: string
|
|
||||||
email: string
|
|
||||||
phone: string
|
|
||||||
cpf: string
|
|
||||||
birthDate: string
|
|
||||||
address: string
|
|
||||||
}
|
|
||||||
|
|
||||||
interface HospitalLayoutProps {
|
|
||||||
children: React.ReactNode
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function HospitalLayout({ children }: HospitalLayoutProps) {
|
|
||||||
const [patientData, setPatientData] = useState<PatientData | null>(null)
|
|
||||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(false)
|
|
||||||
const [showLogoutDialog, setShowLogoutDialog] = useState(false)
|
|
||||||
const router = useRouter()
|
|
||||||
const pathname = usePathname()
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const data = localStorage.getItem("patientData")
|
|
||||||
if (data) {
|
|
||||||
setPatientData(JSON.parse(data))
|
|
||||||
} else {
|
|
||||||
router.push("/patient/login")
|
|
||||||
}
|
|
||||||
}, [router])
|
|
||||||
|
|
||||||
const handleLogout = () => {
|
|
||||||
setShowLogoutDialog(true)
|
|
||||||
}
|
|
||||||
|
|
||||||
const confirmLogout = () => {
|
|
||||||
localStorage.removeItem("patientData")
|
|
||||||
setShowLogoutDialog(false)
|
|
||||||
router.push("/")
|
|
||||||
}
|
|
||||||
|
|
||||||
const cancelLogout = () => {
|
|
||||||
setShowLogoutDialog(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
const menuItems = [
|
|
||||||
{
|
|
||||||
href: "/patient/dashboard",
|
|
||||||
icon: Home,
|
|
||||||
label: "Dashboard",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
href: "/patient/appointments",
|
|
||||||
icon: Calendar,
|
|
||||||
label: "Minhas Consultas",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
href: "/patient/schedule",
|
|
||||||
icon: Clock,
|
|
||||||
label: "Agendar Consulta",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
href: "/patient/reports",
|
|
||||||
icon: FileText,
|
|
||||||
label: "Meus Laudos",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
href: "/patient/profile",
|
|
||||||
icon: User,
|
|
||||||
label: "Meus Dados",
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
if (!patientData) {
|
|
||||||
return <div>Carregando...</div>
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen bg-background flex">
|
|
||||||
{/* Sidebar */}
|
|
||||||
<div
|
|
||||||
className={`bg-card border-r border-border transition-all duration-300 ${sidebarCollapsed ? "w-16" : "w-64"} h-screen flex flex-col`}
|
|
||||||
>
|
|
||||||
<div className="p-4 border-b border-border">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
{!sidebarCollapsed && (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
|
|
||||||
<div className="w-4 h-4 bg-primary-foreground rounded-sm"></div>
|
|
||||||
</div>
|
|
||||||
<span className="font-semibold text-foreground">MediConnect</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<Button variant="ghost" size="sm" onClick={() => setSidebarCollapsed(!sidebarCollapsed)} className="p-1">
|
|
||||||
{sidebarCollapsed ? <ChevronRight className="w-4 h-4" /> : <ChevronLeft className="w-4 h-4" />}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<nav className="flex-1 p-2">
|
|
||||||
{menuItems.map((item) => {
|
|
||||||
const Icon = item.icon
|
|
||||||
const isActive = pathname === item.href || (item.href !== "/" && pathname.startsWith(item.href))
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Link key={item.href} href={item.href}>
|
|
||||||
<div
|
|
||||||
className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${
|
|
||||||
isActive ? "bg-accent text-accent-foreground" : "text-muted-foreground hover:bg-accent hover:text-accent-foreground"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<Icon className="w-5 h-5 flex-shrink-0" />
|
|
||||||
{!sidebarCollapsed && <span className="font-medium">{item.label}</span>}
|
|
||||||
</div>
|
|
||||||
</Link>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</nav>
|
|
||||||
|
|
||||||
<div className="border-t p-4">
|
|
||||||
<div className="flex items-center space-x-3 mb-4">
|
|
||||||
<Avatar>
|
|
||||||
<AvatarImage src="/placeholder.svg?height=40&width=40" />
|
|
||||||
<AvatarFallback>
|
|
||||||
{patientData.name
|
|
||||||
.split(" ")
|
|
||||||
.map((n) => n[0])
|
|
||||||
.join("")}
|
|
||||||
</AvatarFallback>
|
|
||||||
</Avatar>
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<p className="text-sm font-medium text-foreground truncate">{patientData.name}</p>
|
|
||||||
<p className="text-xs text-muted-foreground truncate">{patientData.email}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<Button variant="outline" size="sm" className="w-full bg-transparent" onClick={handleLogout}>
|
|
||||||
<LogOut className="mr-2 h-4 w-4" />
|
|
||||||
Sair
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Main Content */}
|
|
||||||
<div className="flex-1 flex flex-col">
|
|
||||||
{/* Header */}
|
|
||||||
<header className="bg-card border-b border-border px-6 py-4">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div className="flex items-center gap-4 flex-1 max-w-md">
|
|
||||||
<div className="relative flex-1">
|
|
||||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground w-4 h-4" />
|
|
||||||
<Input placeholder="Buscar paciente" className="pl-10 bg-background border-border" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
<Button variant="ghost" size="sm" className="relative">
|
|
||||||
<Bell className="w-5 h-5" />
|
|
||||||
<Badge className="absolute -top-1 -right-1 w-5 h-5 p-0 flex items-center justify-center bg-destructive text-destructive-foreground text-xs">
|
|
||||||
1
|
|
||||||
</Badge>
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
{/* Page Content */}
|
|
||||||
<main className="flex-1 p-6">{children}</main>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Logout confirmation dialog */}
|
|
||||||
<Dialog open={showLogoutDialog} onOpenChange={setShowLogoutDialog}>
|
|
||||||
<DialogContent className="sm:max-w-md">
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle>Confirmar Saída</DialogTitle>
|
|
||||||
<DialogDescription>
|
|
||||||
Deseja realmente sair do sistema? Você precisará fazer login novamente para acessar sua conta.
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
<DialogFooter className="flex gap-2">
|
|
||||||
<Button variant="outline" onClick={cancelLogout}>
|
|
||||||
Cancelar
|
|
||||||
</Button>
|
|
||||||
<Button variant="destructive" onClick={confirmLogout}>
|
|
||||||
<LogOut className="mr-2 h-4 w-4" />
|
|
||||||
Sair
|
|
||||||
</Button>
|
|
||||||
</DialogFooter>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@ -1,262 +0,0 @@
|
|||||||
// Caminho: [seu-caminho]/ManagerLayout.tsx
|
|
||||||
"use client";
|
|
||||||
|
|
||||||
import type React from "react";
|
|
||||||
import { useState, useEffect } from "react";
|
|
||||||
import { useRouter, usePathname } from "next/navigation";
|
|
||||||
import Link from "next/link";
|
|
||||||
import Cookies from "js-cookie"; // Mantido apenas para a limpeza de segurança no logout
|
|
||||||
import { api } from "@/services/api.mjs";
|
|
||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { Input } from "@/components/ui/input";
|
|
||||||
import { Badge } from "@/components/ui/badge";
|
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogDescription,
|
|
||||||
DialogFooter,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
} from "@/components/ui/dialog";
|
|
||||||
import {
|
|
||||||
Search,
|
|
||||||
Bell,
|
|
||||||
Calendar,
|
|
||||||
User,
|
|
||||||
LogOut,
|
|
||||||
ChevronLeft,
|
|
||||||
ChevronRight,
|
|
||||||
Home,
|
|
||||||
} from "lucide-react";
|
|
||||||
|
|
||||||
interface ManagerData {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
email: string;
|
|
||||||
phone: string;
|
|
||||||
cpf: string;
|
|
||||||
department: string;
|
|
||||||
permissions: object;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ManagerLayoutProps {
|
|
||||||
children: React.ReactNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function ManagerLayout({ children }: ManagerLayoutProps) {
|
|
||||||
const [managerData, setManagerData] = useState<ManagerData | null>(null);
|
|
||||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
|
|
||||||
const [showLogoutDialog, setShowLogoutDialog] = useState(false);
|
|
||||||
const router = useRouter();
|
|
||||||
const pathname = usePathname();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const userInfoString = localStorage.getItem("user_info");
|
|
||||||
// --- ALTERAÇÃO 1: Buscando o token no localStorage ---
|
|
||||||
const token = localStorage.getItem("token");
|
|
||||||
|
|
||||||
if (userInfoString && token) {
|
|
||||||
const userInfo = JSON.parse(userInfoString);
|
|
||||||
|
|
||||||
setManagerData({
|
|
||||||
id: userInfo.id || "",
|
|
||||||
name: userInfo.user_metadata?.full_name || "Gestor(a)",
|
|
||||||
email: userInfo.email || "",
|
|
||||||
department: userInfo.user_metadata?.role || "Gestão",
|
|
||||||
phone: userInfo.phone || "",
|
|
||||||
cpf: "",
|
|
||||||
permissions: {},
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
// O redirecionamento para /login já estava correto. Ótimo!
|
|
||||||
router.push("/login");
|
|
||||||
}
|
|
||||||
}, [router]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const handleResize = () => {
|
|
||||||
if (window.innerWidth < 1024) {
|
|
||||||
setSidebarCollapsed(true);
|
|
||||||
} else {
|
|
||||||
setSidebarCollapsed(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
handleResize();
|
|
||||||
window.addEventListener("resize", handleResize);
|
|
||||||
return () => window.removeEventListener("resize", handleResize);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleLogout = () => setShowLogoutDialog(true);
|
|
||||||
|
|
||||||
// --- ALTERAÇÃO 2: A função de logout agora é MUITO mais simples ---
|
|
||||||
const confirmLogout = async () => {
|
|
||||||
try {
|
|
||||||
// Chama a função centralizada para fazer o logout no servidor
|
|
||||||
await api.logout();
|
|
||||||
} catch (error) {
|
|
||||||
// O erro já é logado dentro da função api.logout, não precisamos fazer nada aqui
|
|
||||||
} finally {
|
|
||||||
// A responsabilidade do componente é apenas limpar o estado local e redirecionar
|
|
||||||
localStorage.removeItem("user_info");
|
|
||||||
localStorage.removeItem("token");
|
|
||||||
Cookies.remove("access_token"); // Limpeza de segurança
|
|
||||||
|
|
||||||
setShowLogoutDialog(false);
|
|
||||||
router.push("/"); // Redireciona para a home
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const cancelLogout = () => setShowLogoutDialog(false);
|
|
||||||
|
|
||||||
const menuItems = [
|
|
||||||
{ href: "/manager/dashboard", icon: Home, label: "Dashboard" },
|
|
||||||
{ href: "#", icon: Calendar, label: "Relatórios gerenciais" },
|
|
||||||
{ href: "/manager/usuario", icon: User, label: "Gestão de Usuários" },
|
|
||||||
{ href: "/manager/home", icon: User, label: "Gestão de Médicos" },
|
|
||||||
{ href: "/manager/pacientes", icon: User, label: "Gestão de Pacientes" },
|
|
||||||
{ href: "#", icon: Calendar, label: "Configurações" },
|
|
||||||
];
|
|
||||||
|
|
||||||
if (!managerData) {
|
|
||||||
return (
|
|
||||||
<div className="flex h-screen w-full items-center justify-center">
|
|
||||||
Carregando...
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen bg-gray-50 flex">
|
|
||||||
<div
|
|
||||||
className={`bg-white border-r border-gray-200 transition-all duration-300 fixed top-0 h-screen flex flex-col z-30 ${
|
|
||||||
sidebarCollapsed ? "w-16" : "w-64"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<div className="p-4 border-b border-gray-200 flex items-center justify-between">
|
|
||||||
{!sidebarCollapsed && (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<div className="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center">
|
|
||||||
<div className="w-4 h-4 bg-white rounded-sm"></div>
|
|
||||||
</div>
|
|
||||||
<span className="font-semibold text-gray-900">MediConnect</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
|
|
||||||
className="p-1"
|
|
||||||
>
|
|
||||||
{sidebarCollapsed ? (
|
|
||||||
<ChevronRight className="w-4 h-4" />
|
|
||||||
) : (
|
|
||||||
<ChevronLeft className="w-4 h-4" />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<nav className="flex-1 p-2 overflow-y-auto">
|
|
||||||
{menuItems.map((item) => {
|
|
||||||
const Icon = item.icon;
|
|
||||||
const isActive = pathname === item.href;
|
|
||||||
return (
|
|
||||||
<Link key={item.label} href={item.href}>
|
|
||||||
<div
|
|
||||||
className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${
|
|
||||||
isActive
|
|
||||||
? "bg-blue-50 text-blue-600 border-r-2 border-blue-600"
|
|
||||||
: "text-gray-600 hover:bg-gray-50"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<Icon className="w-5 h-5 flex-shrink-0" />
|
|
||||||
{!sidebarCollapsed && (
|
|
||||||
<span className="font-medium">{item.label}</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</Link>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</nav>
|
|
||||||
|
|
||||||
<div className="border-t p-4 mt-auto">
|
|
||||||
<div className="flex items-center space-x-3 mb-4">
|
|
||||||
<Avatar>
|
|
||||||
<AvatarImage src="/placeholder.svg?height=40&width=40" />
|
|
||||||
<AvatarFallback>
|
|
||||||
{managerData.name
|
|
||||||
.split(" ")
|
|
||||||
.map((n) => n[0])
|
|
||||||
.join("")}
|
|
||||||
</AvatarFallback>
|
|
||||||
</Avatar>
|
|
||||||
{!sidebarCollapsed && (
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<p className="text-sm font-medium text-gray-900 truncate">
|
|
||||||
{managerData.name}
|
|
||||||
</p>
|
|
||||||
<p className="text-xs text-gray-500 truncate">
|
|
||||||
{managerData.department}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
className={
|
|
||||||
sidebarCollapsed
|
|
||||||
? "w-full bg-transparent flex justify-center items-center p-2"
|
|
||||||
: "w-full bg-transparent"
|
|
||||||
}
|
|
||||||
onClick={handleLogout}
|
|
||||||
>
|
|
||||||
<LogOut className={sidebarCollapsed ? "h-5 w-5" : "mr-2 h-4 w-4"} />
|
|
||||||
{!sidebarCollapsed && "Sair"}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div
|
|
||||||
className={`flex-1 flex flex-col transition-all duration-300 w-full ${
|
|
||||||
sidebarCollapsed ? "ml-16" : "ml-64"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<header className="bg-white border-b border-gray-200 px-4 md:px-6 py-4 flex items-center justify-between">
|
|
||||||
<div className="flex items-center gap-4 flex-1 max-w-md"></div>
|
|
||||||
<div className="flex items-center gap-4 ml-auto">
|
|
||||||
<Button variant="ghost" size="sm" className="relative">
|
|
||||||
<Bell className="w-5 h-5" />
|
|
||||||
<Badge className="absolute -top-1 -right-1 w-5 h-5 p-0 flex items-center justify-center bg-red-500 text-white text-xs">
|
|
||||||
1
|
|
||||||
</Badge>
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
<main className="flex-1 p-4 md:p-6">{children}</main>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Dialog open={showLogoutDialog} onOpenChange={setShowLogoutDialog}>
|
|
||||||
<DialogContent className="sm:max-w-md">
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle>Confirmar Saída</DialogTitle>
|
|
||||||
<DialogDescription>
|
|
||||||
Deseja realmente sair do sistema? Você precisará fazer login
|
|
||||||
novamente para acessar sua conta.
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
<DialogFooter className="flex gap-2">
|
|
||||||
<Button variant="outline" onClick={cancelLogout}>
|
|
||||||
Cancelar
|
|
||||||
</Button>
|
|
||||||
<Button variant="destructive" onClick={confirmLogout}>
|
|
||||||
<LogOut className="mr-2 h-4 w-4" />
|
|
||||||
Sair
|
|
||||||
</Button>
|
|
||||||
</DialogFooter>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -1,287 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import Cookies from "js-cookie";
|
|
||||||
import type React from "react";
|
|
||||||
import { useState, useEffect } from "react";
|
|
||||||
import Link from "next/link";
|
|
||||||
import { useRouter, usePathname } from "next/navigation";
|
|
||||||
import { api } from "@/services/api.mjs"; // Importando nosso cliente de API
|
|
||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { Input } from "@/components/ui/input";
|
|
||||||
import { Badge } from "@/components/ui/badge";
|
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
|
||||||
import {
|
|
||||||
Search,
|
|
||||||
Bell,
|
|
||||||
User,
|
|
||||||
LogOut,
|
|
||||||
FileText,
|
|
||||||
Clock,
|
|
||||||
Calendar,
|
|
||||||
Home,
|
|
||||||
ChevronLeft,
|
|
||||||
ChevronRight,
|
|
||||||
} from "lucide-react";
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogDescription,
|
|
||||||
DialogFooter,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
} from "@/components/ui/dialog";
|
|
||||||
|
|
||||||
interface PatientData {
|
|
||||||
name: string;
|
|
||||||
email: string;
|
|
||||||
phone: string;
|
|
||||||
cpf: string;
|
|
||||||
birthDate: string;
|
|
||||||
address: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface PatientLayoutProps {
|
|
||||||
children: React.ReactNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- ALTERAÇÃO 1: Renomeando o componente para maior clareza ---
|
|
||||||
export default function PatientLayout({ children }: PatientLayoutProps) {
|
|
||||||
const [patientData, setPatientData] = useState<PatientData | null>(null);
|
|
||||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
|
|
||||||
const [showLogoutDialog, setShowLogoutDialog] = useState(false);
|
|
||||||
const router = useRouter();
|
|
||||||
const pathname = usePathname();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const handleResize = () => {
|
|
||||||
if (window.innerWidth < 1024) {
|
|
||||||
setSidebarCollapsed(true);
|
|
||||||
} else {
|
|
||||||
setSidebarCollapsed(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
handleResize();
|
|
||||||
window.addEventListener("resize", handleResize);
|
|
||||||
return () => window.removeEventListener("resize", handleResize);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const userInfoString = localStorage.getItem("user_info");
|
|
||||||
// --- ALTERAÇÃO 2: Buscando o token no localStorage ---
|
|
||||||
const token = localStorage.getItem("token");
|
|
||||||
|
|
||||||
if (userInfoString && token) {
|
|
||||||
const userInfo = JSON.parse(userInfoString);
|
|
||||||
|
|
||||||
setPatientData({
|
|
||||||
name: userInfo.user_metadata?.full_name || "Paciente",
|
|
||||||
email: userInfo.email || "",
|
|
||||||
phone: userInfo.phone || "",
|
|
||||||
cpf: "",
|
|
||||||
birthDate: "",
|
|
||||||
address: "",
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
// --- ALTERAÇÃO 3: Redirecionando para o login central ---
|
|
||||||
router.push("/login");
|
|
||||||
}
|
|
||||||
}, [router]);
|
|
||||||
|
|
||||||
const handleLogout = () => setShowLogoutDialog(true);
|
|
||||||
|
|
||||||
// --- ALTERAÇÃO 4: Função de logout completa e padronizada ---
|
|
||||||
const confirmLogout = async () => {
|
|
||||||
try {
|
|
||||||
// Chama a função centralizada para fazer o logout no servidor
|
|
||||||
await api.logout();
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Erro ao tentar fazer logout no servidor:", error);
|
|
||||||
} finally {
|
|
||||||
// Limpeza completa e consistente do estado local
|
|
||||||
localStorage.removeItem("user_info");
|
|
||||||
localStorage.removeItem("token");
|
|
||||||
Cookies.remove("access_token"); // Limpeza de segurança
|
|
||||||
|
|
||||||
setShowLogoutDialog(false);
|
|
||||||
router.push("/"); // Redireciona para a página inicial
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const cancelLogout = () => setShowLogoutDialog(false);
|
|
||||||
|
|
||||||
const menuItems = [
|
|
||||||
{ href: "/patient/dashboard", icon: Home, label: "Dashboard" },
|
|
||||||
{
|
|
||||||
href: "/patient/appointments",
|
|
||||||
icon: Calendar,
|
|
||||||
label: "Minhas Consultas",
|
|
||||||
},
|
|
||||||
{ href: "/patient/schedule", icon: Clock, label: "Agendar Consulta" },
|
|
||||||
{ href: "/patient/reports", icon: FileText, label: "Meus Laudos" },
|
|
||||||
{ href: "/patient/profile", icon: User, label: "Meus Dados" },
|
|
||||||
];
|
|
||||||
|
|
||||||
if (!patientData) {
|
|
||||||
return (
|
|
||||||
<div className="flex h-screen w-full items-center justify-center">
|
|
||||||
Carregando...
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen bg-background flex">
|
|
||||||
{/* Sidebar */}
|
|
||||||
<div
|
|
||||||
className={`bg-card border-r border-border transition-all duration-300 ${
|
|
||||||
sidebarCollapsed ? "w-16" : "w-64"
|
|
||||||
} fixed left-0 top-0 h-screen flex flex-col z-10`}
|
|
||||||
>
|
|
||||||
{/* Header da Sidebar */}
|
|
||||||
<div className="p-4 border-b border-border">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
{!sidebarCollapsed && (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
|
|
||||||
<div className="w-4 h-4 bg-primary-foreground rounded-sm"></div>
|
|
||||||
</div>
|
|
||||||
<span className="font-semibold text-foreground">
|
|
||||||
MediConnect
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
|
|
||||||
className="p-1"
|
|
||||||
>
|
|
||||||
{sidebarCollapsed ? (
|
|
||||||
<ChevronRight className="w-4 h-4" />
|
|
||||||
) : (
|
|
||||||
<ChevronLeft className="w-4 h-4" />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Menu */}
|
|
||||||
<nav className="flex-1 p-2 overflow-y-auto">
|
|
||||||
{menuItems.map((item) => {
|
|
||||||
const Icon = item.icon;
|
|
||||||
const isActive =
|
|
||||||
pathname === item.href ||
|
|
||||||
(item.href !== "/" && pathname.startsWith(item.href));
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Link key={item.href} href={item.href}>
|
|
||||||
<div
|
|
||||||
className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${
|
|
||||||
isActive
|
|
||||||
? "bg-accent text-accent-foreground"
|
|
||||||
: "text-muted-foreground hover:bg-accent hover:text-accent-foreground"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<Icon className="w-5 h-5 flex-shrink-0" />
|
|
||||||
{!sidebarCollapsed && (
|
|
||||||
<span className="font-medium">{item.label}</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</Link>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</nav>
|
|
||||||
|
|
||||||
{/* Rodapé com Avatar e Logout */}
|
|
||||||
<div className="border-t p-4 mt-auto">
|
|
||||||
<div className="flex items-center space-x-3 mb-4">
|
|
||||||
<Avatar>
|
|
||||||
<AvatarImage src="/placeholder.svg?height=40&width=40" />
|
|
||||||
<AvatarFallback>
|
|
||||||
{patientData.name
|
|
||||||
.split(" ")
|
|
||||||
.map((n) => n[0])
|
|
||||||
.join("")}
|
|
||||||
</AvatarFallback>
|
|
||||||
</Avatar>
|
|
||||||
{!sidebarCollapsed && (
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<p className="text-sm font-medium text-foreground truncate">
|
|
||||||
{patientData.name}
|
|
||||||
</p>
|
|
||||||
<p className="text-xs text-muted-foreground truncate">
|
|
||||||
{patientData.email}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{/* Botão Sair - ajustado para responsividade */}
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
className={
|
|
||||||
sidebarCollapsed
|
|
||||||
? "w-full bg-transparent flex justify-center items-center p-2" // Centraliza o ícone quando colapsado
|
|
||||||
: "w-full bg-transparent"
|
|
||||||
}
|
|
||||||
onClick={handleLogout}
|
|
||||||
>
|
|
||||||
<LogOut className={sidebarCollapsed ? "h-5 w-5" : "mr-2 h-4 w-4"} />{" "}
|
|
||||||
{/* Remove margem quando colapsado */}
|
|
||||||
{!sidebarCollapsed && "Sair"}{" "}
|
|
||||||
{/* Mostra o texto apenas quando não está colapsado */}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Main Content */}
|
|
||||||
<div
|
|
||||||
className={`flex-1 flex flex-col transition-all duration-300 ${
|
|
||||||
sidebarCollapsed ? "ml-16" : "ml-64"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{/* Header */}
|
|
||||||
<header className="bg-card border-b border-border px-6 py-4">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div className="flex items-center gap-4 flex-1 max-w-md"></div>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
<Button variant="ghost" size="sm" className="relative">
|
|
||||||
<Bell className="w-5 h-5" />
|
|
||||||
<Badge className="absolute -top-1 -right-1 w-5 h-5 p-0 flex items-center justify-center bg-destructive text-destructive-foreground text-xs">
|
|
||||||
1
|
|
||||||
</Badge>
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
{/* Page Content */}
|
|
||||||
<main className="flex-1 p-6">{children}</main>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Logout confirmation dialog */}
|
|
||||||
<Dialog open={showLogoutDialog} onOpenChange={setShowLogoutDialog}>
|
|
||||||
<DialogContent className="sm:max-w-md">
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle>Confirmar Saída</DialogTitle>
|
|
||||||
<DialogDescription>
|
|
||||||
Deseja realmente sair do sistema? Você precisará fazer login
|
|
||||||
novamente para acessar sua conta.
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
<DialogFooter className="flex gap-2">
|
|
||||||
<Button variant="outline" onClick={cancelLogout}>
|
|
||||||
Cancelar
|
|
||||||
</Button>
|
|
||||||
<Button variant="destructive" onClick={confirmLogout}>
|
|
||||||
<LogOut className="mr-2 h-4 w-4" />
|
|
||||||
Sair
|
|
||||||
</Button>
|
|
||||||
</DialogFooter>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
647
components/schedule/schedule-form.tsx
Normal file
@ -0,0 +1,647 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect, useCallback, useRef } from "react";
|
||||||
|
import { usersService } from "@/services/usersApi.mjs";
|
||||||
|
import { patientsService } from "@/services/patientsApi.mjs";
|
||||||
|
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||||
|
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
||||||
|
import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
|
import { Calendar as CalendarShadcn } from "@/components/ui/calendar";
|
||||||
|
import { format, addDays } from "date-fns";
|
||||||
|
import { User, StickyNote, Check, ChevronsUpDown } from "lucide-react";
|
||||||
|
import { smsService } from "@/services/Sms.mjs";;
|
||||||
|
import { toast } from "@/hooks/use-toast";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
// Componentes do Combobox (Barra de Pesquisa)
|
||||||
|
import {
|
||||||
|
Command,
|
||||||
|
CommandEmpty,
|
||||||
|
CommandGroup,
|
||||||
|
CommandInput,
|
||||||
|
CommandItem,
|
||||||
|
CommandList,
|
||||||
|
} from "@/components/ui/command";
|
||||||
|
import {
|
||||||
|
Popover,
|
||||||
|
PopoverContent,
|
||||||
|
PopoverTrigger,
|
||||||
|
} from "@/components/ui/popover";
|
||||||
|
|
||||||
|
export default function ScheduleForm() {
|
||||||
|
// Estado do usuário e role
|
||||||
|
const [role, setRole] = useState<string>("paciente");
|
||||||
|
const [userId, setUserId] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Listas e seleções
|
||||||
|
const [patients, setPatients] = useState<any[]>([]);
|
||||||
|
const [selectedPatient, setSelectedPatient] = useState("");
|
||||||
|
const [openPatientCombobox, setOpenPatientCombobox] = useState(false);
|
||||||
|
|
||||||
|
const [doctors, setDoctors] = useState<any[]>([]);
|
||||||
|
const [selectedDoctor, setSelectedDoctor] = useState("");
|
||||||
|
const [openDoctorCombobox, setOpenDoctorCombobox] = useState(false); // Novo estado para médico
|
||||||
|
|
||||||
|
const [selectedDate, setSelectedDate] = useState("");
|
||||||
|
const [selectedTime, setSelectedTime] = useState("");
|
||||||
|
const [notes, setNotes] = useState("");
|
||||||
|
const [availableTimes, setAvailableTimes] = useState<string[]>([]);
|
||||||
|
const [loadingDoctors, setLoadingDoctors] = useState(true);
|
||||||
|
const [loadingSlots, setLoadingSlots] = useState(false);
|
||||||
|
|
||||||
|
// Outras configs
|
||||||
|
const [tipoConsulta] = useState("presencial");
|
||||||
|
const [duracao] = useState("30");
|
||||||
|
const [disponibilidades, setDisponibilidades] = useState<any[]>([]);
|
||||||
|
const [availabilityCounts, setAvailabilityCounts] = useState<
|
||||||
|
Record<string, number>
|
||||||
|
>({});
|
||||||
|
const [tooltip, setTooltip] = useState<{
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
text: string;
|
||||||
|
} | null>(null);
|
||||||
|
const calendarRef = useRef<HTMLDivElement | null>(null);
|
||||||
|
|
||||||
|
// Funções auxiliares
|
||||||
|
const getWeekdayNumber = (weekday: string) =>
|
||||||
|
[
|
||||||
|
"monday",
|
||||||
|
"tuesday",
|
||||||
|
"wednesday",
|
||||||
|
"thursday",
|
||||||
|
"friday",
|
||||||
|
"saturday",
|
||||||
|
"sunday",
|
||||||
|
].indexOf(weekday.toLowerCase()) + 1;
|
||||||
|
|
||||||
|
const getBrazilDate = (date: Date) =>
|
||||||
|
new Date(
|
||||||
|
Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), 12, 0, 0)
|
||||||
|
);
|
||||||
|
|
||||||
|
// 🔹 Buscar dados do usuário e role
|
||||||
|
useEffect(() => {
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
const me = await usersService.getMe();
|
||||||
|
const currentRole = me?.roles?.[0] || "paciente";
|
||||||
|
setRole(currentRole);
|
||||||
|
setUserId(me?.user?.id || null);
|
||||||
|
|
||||||
|
if (["secretaria", "gestor", "admin"].includes(currentRole)) {
|
||||||
|
const pats = await patientsService.list();
|
||||||
|
setPatients(pats || []);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Erro ao carregar usuário:", err);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// 🔹 Buscar médicos
|
||||||
|
const fetchDoctors = useCallback(async () => {
|
||||||
|
setLoadingDoctors(true);
|
||||||
|
try {
|
||||||
|
const data = await doctorsService.list();
|
||||||
|
setDoctors(data || []);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Erro ao buscar médicos:", err);
|
||||||
|
toast({
|
||||||
|
title: "Erro",
|
||||||
|
description: "Não foi possível carregar médicos.",
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setLoadingDoctors(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchDoctors();
|
||||||
|
}, [fetchDoctors]);
|
||||||
|
|
||||||
|
// 🔹 Buscar disponibilidades
|
||||||
|
const loadDoctorDisponibilidades = useCallback(async (doctorId?: string) => {
|
||||||
|
if (!doctorId) return;
|
||||||
|
try {
|
||||||
|
const disp = await AvailabilityService.listById(doctorId);
|
||||||
|
setDisponibilidades(disp || []);
|
||||||
|
await computeAvailabilityCountsPreview(doctorId, disp || []);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Erro ao buscar disponibilidades:", err);
|
||||||
|
setDisponibilidades([]);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const computeAvailabilityCountsPreview = async (
|
||||||
|
doctorId: string,
|
||||||
|
dispList: any[]
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
const today = new Date();
|
||||||
|
const start = format(today, "yyyy-MM-dd");
|
||||||
|
const endDate = addDays(today, 90);
|
||||||
|
const end = format(endDate, "yyyy-MM-dd");
|
||||||
|
|
||||||
|
const appointments = await appointmentsService.search_appointment(
|
||||||
|
`doctor_id=eq.${doctorId}&scheduled_at=gte.${start}T00:00:00Z&scheduled_at=lt.${end}T23:59:59Z`
|
||||||
|
);
|
||||||
|
|
||||||
|
const apptsByDate: Record<string, number> = {};
|
||||||
|
(appointments || []).forEach((a: any) => {
|
||||||
|
const d = String(a.scheduled_at).split("T")[0];
|
||||||
|
apptsByDate[d] = (apptsByDate[d] || 0) + 1;
|
||||||
|
});
|
||||||
|
|
||||||
|
const counts: Record<string, number> = {};
|
||||||
|
for (let i = 0; i <= 90; i++) {
|
||||||
|
const d = addDays(today, i);
|
||||||
|
const key = format(d, "yyyy-MM-dd");
|
||||||
|
const dayOfWeek = d.getDay() === 0 ? 7 : d.getDay();
|
||||||
|
const dailyDisp = dispList.filter(
|
||||||
|
(p) => getWeekdayNumber(p.weekday) === dayOfWeek
|
||||||
|
);
|
||||||
|
if (dailyDisp.length === 0) {
|
||||||
|
counts[key] = 0;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let possible = 0;
|
||||||
|
dailyDisp.forEach((p) => {
|
||||||
|
const [sh, sm] = p.start_time.split(":").map(Number);
|
||||||
|
const [eh, em] = p.end_time.split(":").map(Number);
|
||||||
|
const startMin = sh * 60 + sm;
|
||||||
|
const endMin = eh * 60 + em;
|
||||||
|
const slot = p.slot_minutes || 30;
|
||||||
|
if (endMin >= startMin)
|
||||||
|
possible += Math.floor((endMin - startMin) / slot) + 1;
|
||||||
|
});
|
||||||
|
const occupied = apptsByDate[key] || 0;
|
||||||
|
counts[key] = Math.max(0, possible - occupied);
|
||||||
|
}
|
||||||
|
setAvailabilityCounts(counts);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Erro ao calcular contagens:", err);
|
||||||
|
setAvailabilityCounts({});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 🔹 Quando médico muda
|
||||||
|
useEffect(() => {
|
||||||
|
if (selectedDoctor) {
|
||||||
|
loadDoctorDisponibilidades(selectedDoctor);
|
||||||
|
} else {
|
||||||
|
setDisponibilidades([]);
|
||||||
|
setAvailabilityCounts({});
|
||||||
|
}
|
||||||
|
setSelectedDate("");
|
||||||
|
setSelectedTime("");
|
||||||
|
setAvailableTimes([]);
|
||||||
|
}, [selectedDoctor, loadDoctorDisponibilidades]);
|
||||||
|
|
||||||
|
// 🔹 Buscar horários disponíveis
|
||||||
|
const fetchAvailableSlots = useCallback(
|
||||||
|
async (doctorId: string, date: string) => {
|
||||||
|
if (!doctorId || !date) return;
|
||||||
|
setLoadingSlots(true);
|
||||||
|
setAvailableTimes([]);
|
||||||
|
try {
|
||||||
|
const disponibilidades = await AvailabilityService.listById(doctorId);
|
||||||
|
const consultas = await appointmentsService.search_appointment(
|
||||||
|
`doctor_id=eq.${doctorId}&scheduled_at=gte.${date}T00:00:00Z&scheduled_at=lt.${date}T23:59:59Z`
|
||||||
|
);
|
||||||
|
const diaJS = new Date(date).getDay();
|
||||||
|
const diaAPI = diaJS === 0 ? 7 : diaJS;
|
||||||
|
const disponibilidadeDia = disponibilidades.find(
|
||||||
|
(d: any) => getWeekdayNumber(d.weekday) === diaAPI
|
||||||
|
);
|
||||||
|
if (!disponibilidadeDia) {
|
||||||
|
toast({
|
||||||
|
title: "Nenhuma disponibilidade",
|
||||||
|
description: "Nenhum horário para este dia.",
|
||||||
|
});
|
||||||
|
return setAvailableTimes([]);
|
||||||
|
}
|
||||||
|
const [startHour, startMin] = disponibilidadeDia.start_time
|
||||||
|
.split(":")
|
||||||
|
.map(Number);
|
||||||
|
const [endHour, endMin] = disponibilidadeDia.end_time
|
||||||
|
.split(":")
|
||||||
|
.map(Number);
|
||||||
|
const slot = disponibilidadeDia.slot_minutes || 30;
|
||||||
|
const horariosGerados: string[] = [];
|
||||||
|
let atual = new Date(date);
|
||||||
|
atual.setHours(startHour, startMin, 0, 0);
|
||||||
|
const end = new Date(date);
|
||||||
|
end.setHours(endHour, endMin, 0, 0);
|
||||||
|
while (atual <= end) {
|
||||||
|
horariosGerados.push(atual.toTimeString().slice(0, 5));
|
||||||
|
atual = new Date(atual.getTime() + slot * 60000);
|
||||||
|
}
|
||||||
|
const ocupados = (consultas || []).map((c: any) =>
|
||||||
|
String(c.scheduled_at).split("T")[1]?.slice(0, 5)
|
||||||
|
);
|
||||||
|
const livres = horariosGerados.filter((h) => !ocupados.includes(h));
|
||||||
|
setAvailableTimes(livres);
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
toast({ title: "Erro", description: "Falha ao carregar horários." });
|
||||||
|
} finally {
|
||||||
|
setLoadingSlots(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (selectedDoctor && selectedDate)
|
||||||
|
fetchAvailableSlots(selectedDoctor, selectedDate);
|
||||||
|
}, [selectedDoctor, selectedDate, fetchAvailableSlots]);
|
||||||
|
|
||||||
|
// 🔹 Submeter agendamento
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
const isSecretaryLike = ["secretaria", "admin", "gestor"].includes(role);
|
||||||
|
const patientId = isSecretaryLike ? selectedPatient : userId;
|
||||||
|
|
||||||
|
if (!patientId || !selectedDoctor || !selectedDate || !selectedTime) {
|
||||||
|
toast({ title: "Campos obrigatórios", description: "Preencha todos os campos." });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const body = {
|
||||||
|
doctor_id: selectedDoctor,
|
||||||
|
patient_id: patientId,
|
||||||
|
scheduled_at: `${selectedDate}T${selectedTime}:00`,
|
||||||
|
duration_minutes: Number(duracao),
|
||||||
|
notes,
|
||||||
|
appointment_type: tipoConsulta,
|
||||||
|
};
|
||||||
|
|
||||||
|
await appointmentsService.create(body);
|
||||||
|
|
||||||
|
const dateFormatted = selectedDate.split("-").reverse().join("/");
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: "Consulta agendada!",
|
||||||
|
description: `Consulta marcada para ${dateFormatted} às ${selectedTime} com o(a) médico(a) ${
|
||||||
|
doctors.find((d) => d.id === selectedDoctor)?.full_name || ""
|
||||||
|
}.`,
|
||||||
|
});
|
||||||
|
|
||||||
|
let phoneNumber = "+5511999999999";
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (isSecretaryLike) {
|
||||||
|
const patient = patients.find((p: any) => p.id === patientId);
|
||||||
|
const rawPhone = patient?.phone || patient?.phone_mobile || null;
|
||||||
|
if (rawPhone) phoneNumber = rawPhone;
|
||||||
|
} else {
|
||||||
|
const me = await usersService.getMe();
|
||||||
|
const rawPhone =
|
||||||
|
me?.profile?.phone ||
|
||||||
|
(typeof me?.profile === "object" && "phone_mobile" in me.profile ? (me.profile as any).phone_mobile : null) ||
|
||||||
|
(typeof me === "object" && "user_metadata" in me ? (me as any).user_metadata?.phone : null) ||
|
||||||
|
null;
|
||||||
|
if (rawPhone) phoneNumber = rawPhone;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 🔹 Normaliza para formato internacional (+55)
|
||||||
|
if (phoneNumber) {
|
||||||
|
phoneNumber = phoneNumber.replace(/\D/g, "");
|
||||||
|
if (!phoneNumber.startsWith("55")) phoneNumber = `55${phoneNumber}`;
|
||||||
|
phoneNumber = `+${phoneNumber}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("📞 Telefone usado:", phoneNumber);
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("⚠️ Não foi possível obter telefone do paciente:", err);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 💬 envia o SMS de confirmação
|
||||||
|
// 💬 Envia o SMS de lembrete (sem mostrar nada ao paciente)
|
||||||
|
// 💬 Envia o SMS de lembrete (somente loga no console, não mostra no sistema)
|
||||||
|
try {
|
||||||
|
const smsRes = await smsService.sendSms({
|
||||||
|
phone_number: phoneNumber,
|
||||||
|
message: `Lembrete: sua consulta é em ${dateFormatted} às ${selectedTime} na Clínica MediConnect.`,
|
||||||
|
patient_id: patientId,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (smsRes?.success) {
|
||||||
|
console.log("✅ SMS enviado com sucesso:", smsRes.message_sid);
|
||||||
|
} else {
|
||||||
|
console.warn("⚠️ Falha no envio do SMS:", smsRes);
|
||||||
|
}
|
||||||
|
} catch (smsErr) {
|
||||||
|
console.error("❌ Erro ao enviar SMS:", smsErr);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 🧹 limpa os campos
|
||||||
|
setSelectedDoctor("");
|
||||||
|
setSelectedDate("");
|
||||||
|
setSelectedTime("");
|
||||||
|
setNotes("");
|
||||||
|
setSelectedPatient("");
|
||||||
|
} catch (err) {
|
||||||
|
console.error("❌ Erro ao agendar consulta:", err);
|
||||||
|
toast({ title: "Erro", description: "Falha ao agendar consulta." });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 🔹 Tooltip no calendário
|
||||||
|
useEffect(() => {
|
||||||
|
const cont = calendarRef.current;
|
||||||
|
if (!cont) return;
|
||||||
|
const onMove = (ev: MouseEvent) => {
|
||||||
|
const target = ev.target as HTMLElement | null;
|
||||||
|
const btn = target?.closest("button");
|
||||||
|
if (!btn) return setTooltip(null);
|
||||||
|
const aria = btn.getAttribute("aria-label") || btn.textContent || "";
|
||||||
|
const parsed = new Date(aria);
|
||||||
|
if (isNaN(parsed.getTime())) return setTooltip(null);
|
||||||
|
const key = format(getBrazilDate(parsed), "yyyy-MM-dd");
|
||||||
|
const count = availabilityCounts[key] ?? 0;
|
||||||
|
setTooltip({
|
||||||
|
x: ev.pageX + 10,
|
||||||
|
y: ev.pageY + 10,
|
||||||
|
text: `${count} horário${count !== 1 ? "s" : ""} disponíveis`,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const onLeave = () => setTooltip(null);
|
||||||
|
cont.addEventListener("mousemove", onMove);
|
||||||
|
cont.addEventListener("mouseleave", onLeave);
|
||||||
|
return () => {
|
||||||
|
cont.removeEventListener("mousemove", onMove);
|
||||||
|
cont.removeEventListener("mouseleave", onLeave);
|
||||||
|
};
|
||||||
|
}, [availabilityCounts]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="max-w-6xl mx-auto space-y-4 px-4">
|
||||||
|
<h1 className="text-2xl font-semibold">Agendar Consulta</h1>
|
||||||
|
|
||||||
|
<Card className="border rounded-xl shadow-sm">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Dados da Consulta</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<form onSubmit={handleSubmit} className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||||
|
<div className="space-y-4"> {/* Ajuste: maior espaçamento vertical geral */}
|
||||||
|
|
||||||
|
{/* Se secretária/gestor/admin → COMBOBOX de Paciente */}
|
||||||
|
{["secretaria", "gestor", "admin"].includes(role) && (
|
||||||
|
<div className="flex flex-col gap-2"> {/* Ajuste: gap entre Label e Input */}
|
||||||
|
<Label>Paciente</Label>
|
||||||
|
<Popover open={openPatientCombobox} onOpenChange={setOpenPatientCombobox}>
|
||||||
|
<PopoverTrigger asChild>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
role="combobox"
|
||||||
|
aria-expanded={openPatientCombobox}
|
||||||
|
className="w-full justify-between"
|
||||||
|
>
|
||||||
|
{selectedPatient
|
||||||
|
? patients.find((p) => p.id === selectedPatient)?.full_name
|
||||||
|
: "Selecione o paciente..."}
|
||||||
|
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||||
|
</Button>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent className="w-[350px] p-0">
|
||||||
|
<Command>
|
||||||
|
<CommandInput placeholder="Buscar paciente..." />
|
||||||
|
<CommandList>
|
||||||
|
<CommandEmpty>Nenhum paciente encontrado.</CommandEmpty>
|
||||||
|
<CommandGroup>
|
||||||
|
{patients.map((patient) => (
|
||||||
|
<CommandItem
|
||||||
|
key={patient.id}
|
||||||
|
value={patient.full_name}
|
||||||
|
onSelect={() => {
|
||||||
|
setSelectedPatient(patient.id === selectedPatient ? "" : patient.id);
|
||||||
|
setOpenPatientCombobox(false);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Check
|
||||||
|
className={cn(
|
||||||
|
"mr-2 h-4 w-4",
|
||||||
|
selectedPatient === patient.id ? "opacity-100" : "opacity-0"
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
{patient.full_name}
|
||||||
|
</CommandItem>
|
||||||
|
))}
|
||||||
|
</CommandGroup>
|
||||||
|
</CommandList>
|
||||||
|
</Command>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* COMBOBOX de Médico (Nova funcionalidade) */}
|
||||||
|
<div className="flex flex-col gap-2"> {/* Ajuste: gap entre Label e Input */}
|
||||||
|
<Label>Médico</Label>
|
||||||
|
<Popover open={openDoctorCombobox} onOpenChange={setOpenDoctorCombobox}>
|
||||||
|
<PopoverTrigger asChild>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
role="combobox"
|
||||||
|
aria-expanded={openDoctorCombobox}
|
||||||
|
className="w-full justify-between"
|
||||||
|
disabled={loadingDoctors}
|
||||||
|
>
|
||||||
|
{loadingDoctors
|
||||||
|
? "Carregando médicos..."
|
||||||
|
: selectedDoctor
|
||||||
|
? doctors.find((d) => d.id === selectedDoctor)?.full_name
|
||||||
|
: "Selecione o médico..."}
|
||||||
|
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||||
|
</Button>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent className="w-[350px] p-0">
|
||||||
|
<Command>
|
||||||
|
<CommandInput placeholder="Buscar médico..." />
|
||||||
|
<CommandList>
|
||||||
|
<CommandEmpty>Nenhum médico encontrado.</CommandEmpty>
|
||||||
|
<CommandGroup>
|
||||||
|
{doctors.map((doctor) => (
|
||||||
|
<CommandItem
|
||||||
|
key={doctor.id}
|
||||||
|
value={doctor.full_name}
|
||||||
|
onSelect={() => {
|
||||||
|
setSelectedDoctor(doctor.id === selectedDoctor ? "" : doctor.id);
|
||||||
|
setOpenDoctorCombobox(false);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Check
|
||||||
|
className={cn(
|
||||||
|
"mr-2 h-4 w-4",
|
||||||
|
selectedDoctor === doctor.id ? "opacity-100" : "opacity-0"
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<div className="flex flex-col">
|
||||||
|
<span>{doctor.full_name}</span>
|
||||||
|
<span className="text-xs text-muted-foreground">{doctor.specialty}</span>
|
||||||
|
</div>
|
||||||
|
</CommandItem>
|
||||||
|
))}
|
||||||
|
</CommandGroup>
|
||||||
|
</CommandList>
|
||||||
|
</Command>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<Label>Data</Label>
|
||||||
|
<div ref={calendarRef} className="rounded-lg border p-2">
|
||||||
|
<CalendarShadcn
|
||||||
|
mode="single"
|
||||||
|
disabled={!selectedDoctor}
|
||||||
|
selected={
|
||||||
|
selectedDate
|
||||||
|
? new Date(selectedDate + "T12:00:00")
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
onSelect={(date) => {
|
||||||
|
if (!date) return;
|
||||||
|
const formatted = format(
|
||||||
|
new Date(date.getTime() + 12 * 60 * 60 * 1000),
|
||||||
|
"yyyy-MM-dd"
|
||||||
|
);
|
||||||
|
setSelectedDate(formatted);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<Label>Observações</Label>
|
||||||
|
<Textarea
|
||||||
|
placeholder="Instruções para o médico..."
|
||||||
|
value={notes}
|
||||||
|
onChange={(e) => setNotes(e.target.value)}
|
||||||
|
className="mt-1"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-4"> {/* Ajuste: Espaçamento no lado direito também */}
|
||||||
|
<Card className="shadow-md rounded-xl bg-blue-50 border border-blue-200">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-blue-700">Resumo</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-2 text-gray-900 text-sm">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<User className="h-4 w-4 text-blue-600" />
|
||||||
|
<div className="text-xs">
|
||||||
|
{selectedDoctor
|
||||||
|
? doctors.find((d) => d.id === selectedDoctor)
|
||||||
|
?.full_name
|
||||||
|
: "Médico"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-gray-600">
|
||||||
|
{tipoConsulta} • {duracao} min
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Horário</Label>
|
||||||
|
<Select
|
||||||
|
onValueChange={setSelectedTime}
|
||||||
|
disabled={loadingSlots || availableTimes.length === 0}
|
||||||
|
>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue
|
||||||
|
placeholder={
|
||||||
|
loadingSlots
|
||||||
|
? "Carregando horários..."
|
||||||
|
: availableTimes.length === 0
|
||||||
|
? "Nenhum horário disponível"
|
||||||
|
: "Selecione o horário"
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{availableTimes.map((h) => (
|
||||||
|
<SelectItem key={h} value={h}>
|
||||||
|
{h}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{notes && (
|
||||||
|
<div className="flex items-start gap-2 text-sm">
|
||||||
|
<StickyNote className="h-4 w-4" />
|
||||||
|
<div className="italic text-gray-700">{notes}</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
className="w-full md:w-auto px-4 py-1.5 text-sm bg-blue-600 text-white hover:bg-blue-700"
|
||||||
|
disabled={!selectedDoctor || !selectedDate || !selectedTime}
|
||||||
|
>
|
||||||
|
Agendar
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => {
|
||||||
|
setSelectedDoctor("");
|
||||||
|
setSelectedDate("");
|
||||||
|
setSelectedTime("");
|
||||||
|
setNotes("");
|
||||||
|
setSelectedPatient("");
|
||||||
|
}}
|
||||||
|
className="px-3"
|
||||||
|
>
|
||||||
|
Limpar
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{tooltip && (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
position: "absolute",
|
||||||
|
left: tooltip.x,
|
||||||
|
top: tooltip.y,
|
||||||
|
zIndex: 60,
|
||||||
|
background: "rgba(0,0,0,0.85)",
|
||||||
|
color: "white",
|
||||||
|
padding: "6px 8px",
|
||||||
|
borderRadius: 6,
|
||||||
|
fontSize: 12,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{tooltip.text}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -1,279 +0,0 @@
|
|||||||
// Caminho: app/(secretary)/layout.tsx (ou o caminho do seu arquivo)
|
|
||||||
"use client";
|
|
||||||
|
|
||||||
import type React from "react";
|
|
||||||
import { useState, useEffect } from "react";
|
|
||||||
import { useRouter, usePathname } from "next/navigation";
|
|
||||||
import Link from "next/link";
|
|
||||||
import Cookies from "js-cookie";
|
|
||||||
import { api } from "@/services/api.mjs"; // Importando nosso cliente de API central
|
|
||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { Input } from "@/components/ui/input";
|
|
||||||
import { Badge } from "@/components/ui/badge";
|
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogDescription,
|
|
||||||
DialogFooter,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
} from "@/components/ui/dialog";
|
|
||||||
import {
|
|
||||||
Search,
|
|
||||||
Bell,
|
|
||||||
Calendar,
|
|
||||||
Clock,
|
|
||||||
User,
|
|
||||||
LogOut,
|
|
||||||
Home,
|
|
||||||
ChevronLeft,
|
|
||||||
ChevronRight,
|
|
||||||
} from "lucide-react";
|
|
||||||
|
|
||||||
interface SecretaryData {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
email: string;
|
|
||||||
phone: string;
|
|
||||||
cpf: string;
|
|
||||||
employeeId: string;
|
|
||||||
department: string;
|
|
||||||
permissions: object;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface SecretaryLayoutProps {
|
|
||||||
children: React.ReactNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function SecretaryLayout({ children }: SecretaryLayoutProps) {
|
|
||||||
const [secretaryData, setSecretaryData] = useState<SecretaryData | null>(
|
|
||||||
null
|
|
||||||
);
|
|
||||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
|
|
||||||
const [showLogoutDialog, setShowLogoutDialog] = useState(false);
|
|
||||||
const router = useRouter();
|
|
||||||
const pathname = usePathname();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const userInfoString = localStorage.getItem("user_info");
|
|
||||||
// --- ALTERAÇÃO 1: Buscando o token no localStorage ---
|
|
||||||
const token = localStorage.getItem("token");
|
|
||||||
|
|
||||||
if (userInfoString && token) {
|
|
||||||
const userInfo = JSON.parse(userInfoString);
|
|
||||||
|
|
||||||
setSecretaryData({
|
|
||||||
id: userInfo.id || "",
|
|
||||||
name: userInfo.user_metadata?.full_name || "Secretária",
|
|
||||||
email: userInfo.email || "",
|
|
||||||
department: userInfo.user_metadata?.department || "Atendimento",
|
|
||||||
phone: userInfo.phone || "",
|
|
||||||
cpf: "",
|
|
||||||
employeeId: "",
|
|
||||||
permissions: {},
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
// --- ALTERAÇÃO 2: Redirecionando para o login central ---
|
|
||||||
router.push("/login");
|
|
||||||
}
|
|
||||||
}, [router]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const handleResize = () => {
|
|
||||||
if (window.innerWidth < 1024) {
|
|
||||||
setSidebarCollapsed(true);
|
|
||||||
} else {
|
|
||||||
setSidebarCollapsed(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
handleResize();
|
|
||||||
window.addEventListener("resize", handleResize);
|
|
||||||
return () => window.removeEventListener("resize", handleResize);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleLogout = () => setShowLogoutDialog(true);
|
|
||||||
|
|
||||||
// --- ALTERAÇÃO 3: Função de logout completa e padronizada ---
|
|
||||||
const confirmLogout = async () => {
|
|
||||||
try {
|
|
||||||
// Chama a função centralizada para fazer o logout no servidor
|
|
||||||
await api.logout();
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Erro ao tentar fazer logout no servidor:", error);
|
|
||||||
} finally {
|
|
||||||
// Limpeza completa e consistente do estado local
|
|
||||||
localStorage.removeItem("user_info");
|
|
||||||
localStorage.removeItem("token");
|
|
||||||
Cookies.remove("access_token"); // Limpeza de segurança
|
|
||||||
|
|
||||||
setShowLogoutDialog(false);
|
|
||||||
router.push("/"); // Redireciona para a página inicial
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const cancelLogout = () => setShowLogoutDialog(false);
|
|
||||||
|
|
||||||
const menuItems = [
|
|
||||||
{ href: "/secretary/dashboard", icon: Home, label: "Dashboard" },
|
|
||||||
{ href: "/secretary/appointments", icon: Calendar, label: "Consultas" },
|
|
||||||
{ href: "/secretary/schedule", icon: Clock, label: "Agendar Consulta" },
|
|
||||||
{ href: "/secretary/pacientes", icon: User, label: "Pacientes" },
|
|
||||||
];
|
|
||||||
|
|
||||||
if (!secretaryData) {
|
|
||||||
return (
|
|
||||||
<div className="flex h-screen w-full items-center justify-center">
|
|
||||||
Carregando...
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen bg-background flex">
|
|
||||||
{/* Sidebar */}
|
|
||||||
<div
|
|
||||||
className={`bg-card border-r border-border transition-all duration-300
|
|
||||||
${sidebarCollapsed ? "w-16" : "w-64"}
|
|
||||||
fixed left-0 top-0 h-screen flex flex-col z-10`}
|
|
||||||
>
|
|
||||||
<div className="p-4 border-b border-border">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
{!sidebarCollapsed && (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
|
|
||||||
<div className="w-4 h-4 bg-primary-foreground rounded-sm"></div>
|
|
||||||
</div>
|
|
||||||
<span className="font-semibold text-foreground">
|
|
||||||
MediConnect
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
|
|
||||||
className="p-1"
|
|
||||||
>
|
|
||||||
{sidebarCollapsed ? (
|
|
||||||
<ChevronRight className="w-4 h-4" />
|
|
||||||
) : (
|
|
||||||
<ChevronLeft className="w-4 h-4" />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<nav className="flex-1 p-2 overflow-y-auto">
|
|
||||||
{menuItems.map((item) => {
|
|
||||||
const Icon = item.icon;
|
|
||||||
const isActive =
|
|
||||||
pathname === item.href ||
|
|
||||||
(item.href !== "/" && pathname.startsWith(item.href));
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Link key={item.href} href={item.href}>
|
|
||||||
<div
|
|
||||||
className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${
|
|
||||||
isActive
|
|
||||||
? "bg-accent text-accent-foreground"
|
|
||||||
: "text-muted-foreground hover:bg-accent hover:text-accent-foreground"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<Icon className="w-5 h-5 flex-shrink-0" />
|
|
||||||
{!sidebarCollapsed && (
|
|
||||||
<span className="font-medium">{item.label}</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</Link>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</nav>
|
|
||||||
|
|
||||||
<div className="border-t p-4 mt-auto">
|
|
||||||
<div className="flex items-center space-x-3 mb-4">
|
|
||||||
<Avatar>
|
|
||||||
<AvatarImage src="/placeholder.svg?height=40&width=40" />
|
|
||||||
<AvatarFallback>
|
|
||||||
{secretaryData.name
|
|
||||||
.split(" ")
|
|
||||||
.map((n) => n[0])
|
|
||||||
.join("")}
|
|
||||||
</AvatarFallback>
|
|
||||||
</Avatar>
|
|
||||||
{!sidebarCollapsed && (
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<p className="text-sm font-medium text-foreground truncate">
|
|
||||||
{secretaryData.name}
|
|
||||||
</p>
|
|
||||||
<p className="text-xs text-muted-foreground truncate">
|
|
||||||
{secretaryData.email}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
className={
|
|
||||||
sidebarCollapsed
|
|
||||||
? "w-full bg-transparent flex justify-center items-center p-2"
|
|
||||||
: "w-full bg-transparent"
|
|
||||||
}
|
|
||||||
onClick={handleLogout}
|
|
||||||
>
|
|
||||||
<LogOut className={sidebarCollapsed ? "h-5 w-5" : "mr-2 h-4 w-4"} />
|
|
||||||
{!sidebarCollapsed && "Sair"}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Main Content */}
|
|
||||||
<div
|
|
||||||
className={`flex-1 flex flex-col transition-all duration-300 ${
|
|
||||||
sidebarCollapsed ? "ml-16" : "ml-64"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<header className="bg-card border-b border-border px-6 py-4">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div className="flex items-center gap-4 flex-1 max-w-md"></div>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
<Button variant="ghost" size="sm" className="relative">
|
|
||||||
<Bell className="w-5 h-5" />
|
|
||||||
<Badge className="absolute -top-1 -right-1 w-5 h-5 p-0 flex items-center justify-center bg-destructive text-destructive-foreground text-xs">
|
|
||||||
1
|
|
||||||
</Badge>
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<main className="flex-1 p-6">{children}</main>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Logout confirmation dialog */}
|
|
||||||
<Dialog open={showLogoutDialog} onOpenChange={setShowLogoutDialog}>
|
|
||||||
<DialogContent className="sm:max-w-md">
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle>Confirmar Saída</DialogTitle>
|
|
||||||
<DialogDescription>
|
|
||||||
Deseja realmente sair do sistema? Você precisará fazer login
|
|
||||||
novamente para acessar sua conta.
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
<DialogFooter className="flex gap-2">
|
|
||||||
<Button variant="outline" onClick={cancelLogout}>
|
|
||||||
Cancelar
|
|
||||||
</Button>
|
|
||||||
<Button variant="destructive" onClick={confirmLogout}>
|
|
||||||
<LogOut className="mr-2 h-4 w-4" />
|
|
||||||
Sair
|
|
||||||
</Button>
|
|
||||||
</DialogFooter>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
105
components/ui/WeeklyScheduleCard.tsx
Normal file
@ -0,0 +1,105 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card";
|
||||||
|
import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
||||||
|
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||||
|
|
||||||
|
type Availability = {
|
||||||
|
id: string;
|
||||||
|
doctor_id: string;
|
||||||
|
weekday: string;
|
||||||
|
start_time: string;
|
||||||
|
end_time: string;
|
||||||
|
slot_minutes: number;
|
||||||
|
appointment_type: string;
|
||||||
|
active: boolean;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
created_by: string;
|
||||||
|
updated_by: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
interface WeeklyScheduleProps {
|
||||||
|
doctorId?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function WeeklyScheduleCard({ doctorId }: WeeklyScheduleProps) {
|
||||||
|
const [schedule, setSchedule] = useState<Record<string, { start: string; end: string }[]>>({});
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
|
const weekdaysPT: Record<string, string> = {
|
||||||
|
sunday: "Domingo",
|
||||||
|
monday: "Segunda",
|
||||||
|
tuesday: "Terça",
|
||||||
|
wednesday: "Quarta",
|
||||||
|
thursday: "Quinta",
|
||||||
|
friday: "Sexta",
|
||||||
|
saturday: "Sábado",
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatTime = (time?: string | null) => time?.split(":")?.slice(0, 2).join(":") ?? "";
|
||||||
|
|
||||||
|
function formatAvailability(data: Availability[]) {
|
||||||
|
const grouped = data.reduce((acc: any, item) => {
|
||||||
|
const { weekday, start_time, end_time } = item;
|
||||||
|
|
||||||
|
if (!acc[weekday]) acc[weekday] = [];
|
||||||
|
|
||||||
|
acc[weekday].push({ start: start_time, end: end_time });
|
||||||
|
|
||||||
|
return acc;
|
||||||
|
}, {});
|
||||||
|
|
||||||
|
return grouped;
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchSchedule = async () => {
|
||||||
|
try {
|
||||||
|
const availabilityList = await AvailabilityService.list();
|
||||||
|
|
||||||
|
const filtered = availabilityList.filter((a: Availability) => a.doctor_id == doctorId);
|
||||||
|
|
||||||
|
const formatted = formatAvailability(filtered);
|
||||||
|
setSchedule(formatted);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Erro ao carregar horários:", err);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchSchedule();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4 grid md:grid-cols-7 gap-2">
|
||||||
|
{loading ? (
|
||||||
|
<p className="text-sm text-gray-500 col-span-7 text-center">Carregando...</p>
|
||||||
|
) : (
|
||||||
|
["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "Saturday"].map((day) => {
|
||||||
|
const times = schedule[day] || [];
|
||||||
|
return (
|
||||||
|
<div key={day} className="space-y-4">
|
||||||
|
<div className="flex flex-col items-center justify-between p-3 bg-blue-50 rounded-lg">
|
||||||
|
<p className="font-medium capitalize">{weekdaysPT[day]}</p>
|
||||||
|
<div className="text-center">
|
||||||
|
{times.length > 0 ? (
|
||||||
|
times.map((t, i) => (
|
||||||
|
<p key={i} className="text-sm text-gray-600">
|
||||||
|
{formatTime(t.start)} <br /> {formatTime(t.end)}
|
||||||
|
</p>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<p className="text-sm text-gray-400 italic">Sem horário</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -1,3 +1,5 @@
|
|||||||
|
// CÓDIGO CORRIGIDO PARA: components/ui/button.tsx
|
||||||
|
|
||||||
import * as React from 'react'
|
import * as React from 'react'
|
||||||
import { Slot } from '@radix-ui/react-slot'
|
import { Slot } from '@radix-ui/react-slot'
|
||||||
import { cva, type VariantProps } from 'class-variance-authority'
|
import { cva, type VariantProps } from 'class-variance-authority'
|
||||||
@ -9,16 +11,11 @@ const buttonVariants = cva(
|
|||||||
{
|
{
|
||||||
variants: {
|
variants: {
|
||||||
variant: {
|
variant: {
|
||||||
default:
|
default: 'bg-primary text-primary-foreground shadow-xs hover:bg-primary/90',
|
||||||
'bg-primary text-primary-foreground shadow-xs hover:bg-primary/90',
|
destructive: 'bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60',
|
||||||
destructive:
|
outline: 'border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50',
|
||||||
'bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60',
|
secondary: 'bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80',
|
||||||
outline:
|
ghost: 'hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50',
|
||||||
'border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50',
|
|
||||||
secondary:
|
|
||||||
'bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80',
|
|
||||||
ghost:
|
|
||||||
'hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50',
|
|
||||||
link: 'text-primary underline-offset-4 hover:underline',
|
link: 'text-primary underline-offset-4 hover:underline',
|
||||||
},
|
},
|
||||||
size: {
|
size: {
|
||||||
@ -57,4 +54,4 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
|||||||
)
|
)
|
||||||
Button.displayName = 'Button'
|
Button.displayName = 'Button'
|
||||||
|
|
||||||
export { Button, buttonVariants }
|
export { Button, buttonVariants }
|
||||||
115
components/ui/filter-bar.tsx
Normal file
@ -0,0 +1,115 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import React from "react";
|
||||||
|
import { Search, Filter, X } from "lucide-react";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
|
||||||
|
export interface FilterOption {
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FilterConfig {
|
||||||
|
key: string; // O nome do estado que vai guardar esse valor (ex: 'specialty')
|
||||||
|
label: string; // O placeholder do select (ex: 'Especialidade')
|
||||||
|
options: FilterOption[] | string[]; // Opções do dropdown
|
||||||
|
}
|
||||||
|
|
||||||
|
interface FilterBarProps {
|
||||||
|
onSearch: (term: string) => void;
|
||||||
|
searchTerm: string;
|
||||||
|
searchPlaceholder?: string;
|
||||||
|
filters?: FilterConfig[];
|
||||||
|
activeFilters: Record<string, string>;
|
||||||
|
onFilterChange: (key: string, value: string) => void;
|
||||||
|
onClearFilters?: () => void;
|
||||||
|
className?: string;
|
||||||
|
children?: React.ReactNode; // Para botões extras (ex: "Novo Médico", paginação)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function FilterBar({
|
||||||
|
onSearch,
|
||||||
|
searchTerm,
|
||||||
|
searchPlaceholder = "Pesquisar...",
|
||||||
|
filters = [],
|
||||||
|
activeFilters,
|
||||||
|
onFilterChange,
|
||||||
|
onClearFilters,
|
||||||
|
children,
|
||||||
|
className,
|
||||||
|
}: FilterBarProps) {
|
||||||
|
|
||||||
|
// Verifica se tem algum filtro ativo para mostrar o botão de limpar
|
||||||
|
const hasActiveFilters =
|
||||||
|
searchTerm !== "" ||
|
||||||
|
Object.values(activeFilters).some(val => val !== "all" && val !== "");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={`flex flex-col md:flex-row items-start md:items-center gap-3 bg-white p-4 rounded-lg border border-gray-200 ${className}`}>
|
||||||
|
|
||||||
|
{/* Barra de Pesquisa */}
|
||||||
|
<div className="relative w-full md:flex-1">
|
||||||
|
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
|
||||||
|
<Input
|
||||||
|
placeholder={searchPlaceholder}
|
||||||
|
value={searchTerm}
|
||||||
|
onChange={(e) => onSearch(e.target.value)}
|
||||||
|
className="pl-10 w-full bg-gray-50 border-gray-200 focus:bg-white transition-colors"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Filtros Dinâmicos (Selects) */}
|
||||||
|
<div className="flex flex-wrap items-center gap-3 w-full md:w-auto">
|
||||||
|
{filters.map((filter) => (
|
||||||
|
<div key={filter.key} className="w-full sm:w-auto">
|
||||||
|
<Select
|
||||||
|
value={activeFilters[filter.key] || "all"}
|
||||||
|
onValueChange={(value) => onFilterChange(filter.key, value)}
|
||||||
|
>
|
||||||
|
<SelectTrigger className="w-full sm:w-[180px]">
|
||||||
|
<SelectValue placeholder={filter.label} />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="all">Todos: {filter.label}</SelectItem>
|
||||||
|
{filter.options.map((opt) => {
|
||||||
|
// Suporta tanto array de strings quanto array de objetos {label, value}
|
||||||
|
const value = typeof opt === 'string' ? opt : opt.value;
|
||||||
|
const label = typeof opt === 'string' ? opt : opt.label;
|
||||||
|
return (
|
||||||
|
<SelectItem key={value} value={value}>
|
||||||
|
{label}
|
||||||
|
</SelectItem>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{/* Botão de Limpar Filtros */}
|
||||||
|
{hasActiveFilters && onClearFilters && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={onClearFilters}
|
||||||
|
className="text-gray-500 hover:text-red-600"
|
||||||
|
title="Limpar filtros"
|
||||||
|
>
|
||||||
|
<X className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Botões Extras (ex: Novo Médico, Paginação) passados como children */}
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -1,96 +1,147 @@
|
|||||||
'use client'
|
"use client";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter, DialogClose
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
} from "@/components/ui/dialog";
|
} from "@/components/ui/dialog";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
|
||||||
|
interface Paciente {
|
||||||
|
id: string;
|
||||||
|
nome: string;
|
||||||
|
telefone: string;
|
||||||
|
cidade: string;
|
||||||
|
estado: string;
|
||||||
|
email?: string;
|
||||||
|
birth_date?: string;
|
||||||
|
cpf?: string;
|
||||||
|
blood_type?: string;
|
||||||
|
weight_kg?: number;
|
||||||
|
height_m?: number;
|
||||||
|
street?: string;
|
||||||
|
number?: string;
|
||||||
|
complement?: string;
|
||||||
|
neighborhood?: string;
|
||||||
|
cep?: string;
|
||||||
|
[key: string]: any; // Para permitir outras propriedades se necessário
|
||||||
|
}
|
||||||
|
|
||||||
interface PatientDetailsModalProps {
|
interface PatientDetailsModalProps {
|
||||||
|
patient: Paciente | null;
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
patient: any;
|
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function PatientDetailsModal({ patient, isOpen, onClose }: PatientDetailsModalProps) {
|
export function PatientDetailsModal({
|
||||||
|
patient,
|
||||||
|
isOpen,
|
||||||
|
onClose,
|
||||||
|
}: PatientDetailsModalProps) {
|
||||||
if (!patient) return null;
|
if (!patient) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||||
<DialogContent className="sm:max-w-[600px]">
|
<DialogContent className="max-w-[95%] sm:max-w-lg max-h-[90vh] overflow-y-auto">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>Detalhes do Paciente</DialogTitle>
|
<DialogTitle className="text-xl font-bold">Detalhes do Paciente</DialogTitle>
|
||||||
<DialogDescription>Informações detalhadas sobre o paciente.</DialogDescription>
|
<DialogDescription>
|
||||||
|
Informações detalhadas sobre o paciente.
|
||||||
|
</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
<div className="grid gap-4 py-4">
|
|
||||||
<div className="grid grid-cols-2 gap-4">
|
<div className="space-y-4 py-2">
|
||||||
|
{/* Grid Principal */}
|
||||||
|
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Nome Completo</p>
|
<p className="font-semibold text-gray-900">Nome Completo</p>
|
||||||
<p>{patient.nome}</p>
|
<p className="text-gray-700">{patient.nome}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* CORREÇÃO AQUI: Adicionado 'break-all' para quebrar o email */}
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Email</p>
|
<p className="font-semibold text-gray-900">Email</p>
|
||||||
<p>{patient.email}</p>
|
<p className="text-gray-700 break-all">{patient.email || "N/A"}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Telefone</p>
|
<p className="font-semibold text-gray-900">Telefone</p>
|
||||||
<p>{patient.telefone}</p>
|
<p className="text-gray-700">{patient.telefone}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Data de Nascimento</p>
|
<p className="font-semibold text-gray-900">Data de Nascimento</p>
|
||||||
<p>{patient.birth_date}</p>
|
<p className="text-gray-700">{patient.birth_date || "N/A"}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">CPF</p>
|
<p className="font-semibold text-gray-900">CPF</p>
|
||||||
<p>{patient.cpf}</p>
|
<p className="text-gray-700">{patient.cpf || "N/A"}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Tipo Sanguíneo</p>
|
<p className="font-semibold text-gray-900">Tipo Sanguíneo</p>
|
||||||
<p>{patient.blood_type}</p>
|
<p className="text-gray-700">{patient.blood_type || "N/A"}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Peso (kg)</p>
|
<p className="font-semibold text-gray-900">Peso (kg)</p>
|
||||||
<p>{patient.weight_kg}</p>
|
<p className="text-gray-700">{patient.weight_kg || "0"}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Altura (m)</p>
|
<p className="font-semibold text-gray-900">Altura (m)</p>
|
||||||
<p>{patient.height_m}</p>
|
<p className="text-gray-700">{patient.height_m || "0"}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="border-t pt-4 mt-4">
|
|
||||||
<h3 className="font-semibold mb-2">Endereço</h3>
|
<hr className="border-gray-200" />
|
||||||
<div className="grid grid-cols-2 gap-4">
|
|
||||||
|
{/* Seção de Endereço */}
|
||||||
|
<div>
|
||||||
|
<h4 className="font-semibold mb-3 text-gray-900">Endereço</h4>
|
||||||
|
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Rua</p>
|
<p className="font-semibold text-gray-900">Rua</p>
|
||||||
<p>{`${patient.street}, ${patient.number}`}</p>
|
<p className="text-gray-700">
|
||||||
|
{patient.street && patient.street !== "N/A"
|
||||||
|
? `${patient.street}, ${patient.number || ""}`
|
||||||
|
: "N/A"}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Complemento</p>
|
<p className="font-semibold text-gray-900">Complemento</p>
|
||||||
<p>{patient.complement}</p>
|
<p className="text-gray-700">{patient.complement || "N/A"}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Bairro</p>
|
<p className="font-semibold text-gray-900">Bairro</p>
|
||||||
<p>{patient.neighborhood}</p>
|
<p className="text-gray-700">{patient.neighborhood || "N/A"}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Cidade</p>
|
<p className="font-semibold text-gray-900">Cidade</p>
|
||||||
<p>{patient.cidade}</p>
|
<p className="text-gray-700">{patient.cidade || "N/A"}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Estado</p>
|
<p className="font-semibold text-gray-900">Estado</p>
|
||||||
<p>{patient.estado}</p>
|
<p className="text-gray-700">{patient.estado || "N/A"}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">CEP</p>
|
<p className="font-semibold text-gray-900">CEP</p>
|
||||||
<p>{patient.cep}</p>
|
<p className="text-gray-700">{patient.cep || "N/A"}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
<DialogClose asChild>
|
<Button variant="secondary" onClick={onClose} className="w-full sm:w-auto">
|
||||||
<button type="button" className="px-4 py-2 bg-gray-200 rounded-md">Fechar</button>
|
Fechar
|
||||||
</DialogClose>
|
</Button>
|
||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
143
components/ui/userToolTip.tsx
Normal file
@ -0,0 +1,143 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
CalendarCheck2,
|
||||||
|
CalendarClock,
|
||||||
|
ClipboardPlus,
|
||||||
|
Home,
|
||||||
|
LogOut,
|
||||||
|
SquareUser,
|
||||||
|
} from "lucide-react";
|
||||||
|
import {
|
||||||
|
Popover,
|
||||||
|
PopoverTrigger,
|
||||||
|
PopoverContent,
|
||||||
|
} from "@/components/ui/popover";
|
||||||
|
import { usePathname } from "next/navigation";
|
||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
|
interface UserData {
|
||||||
|
user_metadata: {
|
||||||
|
full_name: string;
|
||||||
|
};
|
||||||
|
app_metadata: {
|
||||||
|
user_role: string;
|
||||||
|
};
|
||||||
|
email: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
userData: UserData;
|
||||||
|
sidebarCollapsed: boolean;
|
||||||
|
handleLogout: () => void;
|
||||||
|
isActive: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function SidebarUserSection({
|
||||||
|
userData,
|
||||||
|
sidebarCollapsed,
|
||||||
|
handleLogout,
|
||||||
|
isActive,
|
||||||
|
}: Props) {
|
||||||
|
const pathname = usePathname();
|
||||||
|
const menuItems: any[] = [
|
||||||
|
{
|
||||||
|
href: "/patient/schedule",
|
||||||
|
icon: CalendarClock,
|
||||||
|
label: "Agendar Consulta",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: "/patient/appointments",
|
||||||
|
icon: CalendarCheck2,
|
||||||
|
label: "Minhas Consultas",
|
||||||
|
},
|
||||||
|
{ href: "/patient/reports", icon: ClipboardPlus, label: "Meus Laudos" },
|
||||||
|
{ href: "/patient/profile", icon: SquareUser, label: "Meus Dados" },
|
||||||
|
];
|
||||||
|
return (
|
||||||
|
<div className="border-t p-4 mt-auto">
|
||||||
|
{/* POPUP DE INFORMAÇÕES DO USUÁRIO */}
|
||||||
|
<Popover>
|
||||||
|
<PopoverTrigger asChild>
|
||||||
|
<div
|
||||||
|
className={`flex items-center space-x-3 mb-4 p-2 rounded-md transition-colors ${
|
||||||
|
isActive ? "cursor-pointer" : "cursor-default pointer-events-none"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Avatar>
|
||||||
|
<AvatarImage src="/placeholder.svg?height=40&width=40" />
|
||||||
|
<AvatarFallback>
|
||||||
|
{userData.user_metadata.full_name
|
||||||
|
.split(" ")
|
||||||
|
.map((n) => n[0])
|
||||||
|
.join("")}
|
||||||
|
</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
|
||||||
|
{!sidebarCollapsed && (
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<p className="text-sm font-medium text-white truncate">
|
||||||
|
{userData.user_metadata.full_name}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-white truncate">
|
||||||
|
{userData.app_metadata.user_role}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</PopoverTrigger>
|
||||||
|
|
||||||
|
{/* Card flutuante */}
|
||||||
|
<PopoverContent
|
||||||
|
align="center"
|
||||||
|
side="top"
|
||||||
|
className="w-64 p-4 shadow-lg border bg-white"
|
||||||
|
>
|
||||||
|
<nav>
|
||||||
|
{menuItems.map((item) => {
|
||||||
|
const Icon = item.icon;
|
||||||
|
const isActive = pathname === item.href;
|
||||||
|
return (
|
||||||
|
<Link key={item.label} href={item.href}>
|
||||||
|
<div
|
||||||
|
className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${
|
||||||
|
isActive
|
||||||
|
? "bg-blue-50 text-blue-600 border-r-2 border-blue-600"
|
||||||
|
: "text-gray-600 hover:bg-gray-50"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Icon className="w-5 h-5 flex-shrink-0" />
|
||||||
|
{!sidebarCollapsed && (
|
||||||
|
<span className="font-medium">{item.label}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</nav>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
{/* Botão de sair */}
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
className={
|
||||||
|
sidebarCollapsed
|
||||||
|
? "w-full bg-white text-black flex justify-center items-center p-2 hover:bg-gray-200"
|
||||||
|
: "w-full bg-white text-black hover:bg-gray-200 cursor-pointer"
|
||||||
|
}
|
||||||
|
onClick={handleLogout}
|
||||||
|
>
|
||||||
|
<LogOut
|
||||||
|
className={
|
||||||
|
sidebarCollapsed ? "h-5 w-5 text-black" : "mr-2 h-4 w-4 text-black"
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{!sidebarCollapsed && "Sair"}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
68
hooks/useAuthLayout.ts
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
// ARQUIVO COMPLETO PARA: hooks/useAuthLayout.ts
|
||||||
|
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { usersService } from "@/services/usersApi.mjs";
|
||||||
|
import { toast } from "@/hooks/use-toast";
|
||||||
|
|
||||||
|
interface UserLayoutData {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
email: string;
|
||||||
|
roles: string[];
|
||||||
|
avatar_url?: string;
|
||||||
|
avatarFullUrl?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface UseAuthLayoutOptions {
|
||||||
|
requiredRole?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAuthLayout({ requiredRole }: UseAuthLayoutOptions = {}) {
|
||||||
|
const [user, setUser] = useState<UserLayoutData | null>(null);
|
||||||
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchUserData = async () => {
|
||||||
|
try {
|
||||||
|
const fullUserData = await usersService.getMe();
|
||||||
|
|
||||||
|
if (!fullUserData.roles.some((role) => requiredRole?.includes(role))) {
|
||||||
|
console.error(`Acesso negado. Requer perfil '${requiredRole}', mas o usuário tem '${fullUserData.roles.join(", ")}'.`);
|
||||||
|
toast({
|
||||||
|
title: "Acesso Negado",
|
||||||
|
description: "Você não tem permissão para acessar esta página.",
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
router.push("/");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const avatarPath = fullUserData.profile.avatar_url;
|
||||||
|
|
||||||
|
// *** A CORREÇÃO ESTÁ AQUI ***
|
||||||
|
// Adicionamos o nome do bucket 'avatars' na URL final.
|
||||||
|
const avatarFullUrl = avatarPath ? `https://yuanqfswhberkoevtmfr.supabase.co/storage/v1/object/public/avatars/${avatarPath}` : undefined;
|
||||||
|
|
||||||
|
setUser({
|
||||||
|
id: fullUserData.user.id,
|
||||||
|
name: fullUserData.profile.full_name || "Usuário",
|
||||||
|
email: fullUserData.user.email,
|
||||||
|
roles: fullUserData.roles,
|
||||||
|
avatar_url: avatarPath,
|
||||||
|
avatarFullUrl: avatarFullUrl,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Falha na autenticação do layout:", error);
|
||||||
|
router.push("/login");
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchUserData();
|
||||||
|
}, [router, requiredRole]);
|
||||||
|
|
||||||
|
return { user, isLoading };
|
||||||
|
}
|
||||||
94
lib/normalization.ts
Normal file
@ -0,0 +1,94 @@
|
|||||||
|
// lib/normalization.ts
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mapa de normalização.
|
||||||
|
* A chave é o termo "sujo" (em minúsculo) e o valor é o termo "Canônico" (Bonito).
|
||||||
|
*/
|
||||||
|
const SPECIALTY_MAPPING: Record<string, string> = {
|
||||||
|
// --- Cardiologia ---
|
||||||
|
"cardiologista": "Cardiologia",
|
||||||
|
"cardio": "Cardiologia",
|
||||||
|
"cardiologia": "Cardiologia",
|
||||||
|
|
||||||
|
// --- Dermatologia ---
|
||||||
|
"dermatologista": "Dermatologia",
|
||||||
|
"dermato": "Dermatologia",
|
||||||
|
"dermatologia": "Dermatologia",
|
||||||
|
|
||||||
|
// --- Ortopedia ---
|
||||||
|
"ortopedista": "Ortopedia",
|
||||||
|
"ortopedia": "Ortopedia",
|
||||||
|
|
||||||
|
// --- Ginecologia ---
|
||||||
|
"ginecologista": "Ginecologia",
|
||||||
|
"ginecologia": "Ginecologia",
|
||||||
|
"ginecologistaa": "Ginecologia", // Erro de digitação comum
|
||||||
|
"gineco": "Ginecologia",
|
||||||
|
|
||||||
|
// --- Pediatria ---
|
||||||
|
"pediatra": "Pediatria",
|
||||||
|
"pediatria": "Pediatria",
|
||||||
|
|
||||||
|
// --- Clínica Geral (Onde estava o erro) ---
|
||||||
|
"clinico geral": "Clínica Geral",
|
||||||
|
"clínico geral": "Clínica Geral",
|
||||||
|
"clinica geral": "Clínica Geral",
|
||||||
|
"clínica geral": "Clínica Geral", // <--- ADICIONADO
|
||||||
|
"geral": "Clínica Geral",
|
||||||
|
"medico geral": "Clínica Geral",
|
||||||
|
"médico geral": "Clínica Geral",
|
||||||
|
|
||||||
|
// --- Neurologia ---
|
||||||
|
"neurologista": "Neurologia",
|
||||||
|
"neurologia": "Neurologia",
|
||||||
|
"neuro": "Neurologia",
|
||||||
|
"neurocirurgiao": "Neurocirurgia",
|
||||||
|
"neurocirurgião": "Neurocirurgia",
|
||||||
|
|
||||||
|
// --- Limpeza de Lixo / Outros ---
|
||||||
|
"asdw": "Outros",
|
||||||
|
"teste": "Outros",
|
||||||
|
"n/a": "Não Informado", // <--- Transforma o "N/A" da imagem
|
||||||
|
"na": "Não Informado",
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Recebe uma especialidade suja e retorna a versão limpa.
|
||||||
|
*/
|
||||||
|
export function normalizeSpecialty(raw: string | null | undefined): string {
|
||||||
|
if (!raw) return "Não Informado";
|
||||||
|
|
||||||
|
// Remove espaços extras e joga para minúsculo
|
||||||
|
const lower = raw.trim().toLowerCase();
|
||||||
|
|
||||||
|
// Se for uma string vazia ou traço
|
||||||
|
if (lower === "" || lower === "-") return "Não Informado";
|
||||||
|
|
||||||
|
// Verifica no mapa
|
||||||
|
if (SPECIALTY_MAPPING[lower]) {
|
||||||
|
return SPECIALTY_MAPPING[lower];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback: Capitaliza a primeira letra de cada palavra
|
||||||
|
// Ex: "cirurgia plastica" -> "Cirurgia Plastica"
|
||||||
|
return lower.replace(/\b\w/g, (l) => l.toUpperCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extrai uma lista única de especialidades normalizadas.
|
||||||
|
*/
|
||||||
|
export function getUniqueSpecialties(items: any[]): string[] {
|
||||||
|
const specialties = new Set<string>();
|
||||||
|
|
||||||
|
items.forEach(item => {
|
||||||
|
// Normaliza antes de adicionar ao Set
|
||||||
|
const normalized = normalizeSpecialty(item.specialty);
|
||||||
|
|
||||||
|
// Só adiciona se não for "Não Informado" ou "Outros" (Opcional: remova o if se quiser mostrar tudo)
|
||||||
|
if (normalized && normalized !== "Não Informado") {
|
||||||
|
specialties.add(normalized);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return Array.from(specialties).sort();
|
||||||
|
}
|
||||||
46
lib/utils.ts
@ -1,6 +1,52 @@
|
|||||||
|
// ARQUIVO: lib/utils.ts
|
||||||
|
|
||||||
import { clsx, type ClassValue } from 'clsx'
|
import { clsx, type ClassValue } from 'clsx'
|
||||||
import { twMerge } from 'tailwind-merge'
|
import { twMerge } from 'tailwind-merge'
|
||||||
|
|
||||||
export function cn(...inputs: ClassValue[]) {
|
export function cn(...inputs: ClassValue[]) {
|
||||||
return twMerge(clsx(inputs))
|
return twMerge(clsx(inputs))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ADICIONE A FUNÇÃO ABAIXO
|
||||||
|
export function isValidCPF(cpf: string | null | undefined): boolean {
|
||||||
|
if (!cpf) return false;
|
||||||
|
|
||||||
|
// Remove caracteres não numéricos
|
||||||
|
const cpfDigits = cpf.replace(/\D/g, '');
|
||||||
|
|
||||||
|
if (cpfDigits.length !== 11 || /^(\d)\1+$/.test(cpfDigits)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
let sum = 0;
|
||||||
|
let remainder;
|
||||||
|
|
||||||
|
for (let i = 1; i <= 9; i++) {
|
||||||
|
sum += parseInt(cpfDigits.substring(i - 1, i)) * (11 - i);
|
||||||
|
}
|
||||||
|
|
||||||
|
remainder = (sum * 10) % 11;
|
||||||
|
if (remainder === 10 || remainder === 11) {
|
||||||
|
remainder = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (remainder !== parseInt(cpfDigits.substring(9, 10))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
sum = 0;
|
||||||
|
for (let i = 1; i <= 10; i++) {
|
||||||
|
sum += parseInt(cpfDigits.substring(i - 1, i)) * (12 - i);
|
||||||
|
}
|
||||||
|
|
||||||
|
remainder = (sum * 10) % 11;
|
||||||
|
if (remainder === 10 || remainder === 11) {
|
||||||
|
remainder = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (remainder !== parseInt(cpfDigits.substring(10, 11))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
BIN
public/Logo MedConnect.png
Normal file
|
After Width: | Height: | Size: 30 KiB |
BIN
public/android-chrome-192x192.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
BIN
public/android-chrome-512x512.png
Normal file
|
After Width: | Height: | Size: 33 KiB |
BIN
public/apple-touch-icon.png
Normal file
|
After Width: | Height: | Size: 8.9 KiB |
BIN
public/favicon-16x16.png
Normal file
|
After Width: | Height: | Size: 303 B |
BIN
public/favicon-32x32.png
Normal file
|
After Width: | Height: | Size: 670 B |
BIN
public/favicon.ico
Normal file
|
After Width: | Height: | Size: 15 KiB |
58
services/Sms.mjs
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
/**
|
||||||
|
* Serviço de SMS via Supabase Edge Function (sem backend)
|
||||||
|
* Usa o token JWT salvo no localStorage (chave: "token")
|
||||||
|
*/
|
||||||
|
|
||||||
|
const SUPABASE_FUNCTION_URL =
|
||||||
|
"https://yuanqfswhberkoevtmfr.supabase.co/functions/v1/send-sms";
|
||||||
|
|
||||||
|
export const smsService = {
|
||||||
|
/**
|
||||||
|
* Envia um SMS de lembrete via Twilio
|
||||||
|
* @param {Object} params
|
||||||
|
* @param {string} params.phone_number - Ex: +5511999999999
|
||||||
|
* @param {string} params.message - Mensagem de texto
|
||||||
|
* @param {string} [params.patient_id] - ID opcional do paciente
|
||||||
|
*/
|
||||||
|
async sendSms({ phone_number, message, patient_id }) {
|
||||||
|
try {
|
||||||
|
// 🔹 Busca o token salvo pelo login
|
||||||
|
const token = localStorage.getItem("token");
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
console.error("❌ Nenhum token JWT encontrado no localStorage (chave: 'token').");
|
||||||
|
return { success: false, error: "Token JWT não encontrado." };
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = JSON.stringify({
|
||||||
|
phone_number,
|
||||||
|
message,
|
||||||
|
patient_id,
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log("[smsService] Enviando SMS para:", phone_number);
|
||||||
|
|
||||||
|
const response = await fetch(SUPABASE_FUNCTION_URL, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Bearer ${token}`, // 🔑 autenticação Supabase
|
||||||
|
},
|
||||||
|
body,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await response.json();
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
console.error("❌ Falha no envio do SMS:", result);
|
||||||
|
return { success: false, error: result };
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("✅ SMS enviado com sucesso:", result);
|
||||||
|
return result;
|
||||||
|
} catch (err) {
|
||||||
|
console.error("❌ Erro inesperado ao enviar SMS:", err);
|
||||||
|
return { success: false, error: err.message };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
@ -89,11 +89,20 @@ async function request(endpoint, options = {}) {
|
|||||||
|
|
||||||
// --- CORREÇÃO 1: PARA O SUBMIT DO AGENDAMENTO ---
|
// --- CORREÇÃO 1: PARA O SUBMIT DO AGENDAMENTO ---
|
||||||
// Se a resposta for um sucesso de criação (201) ou sem conteúdo (204), não quebra.
|
// Se a resposta for um sucesso de criação (201) ou sem conteúdo (204), não quebra.
|
||||||
if (response.status === 201 || response.status === 204) {
|
// --- CORREÇÃO: funções do Supabase retornam 200 ou 201, nunca queremos perder o body ---
|
||||||
return null;
|
if (response.status === 204) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const text = await response.text();
|
||||||
|
try {
|
||||||
|
return JSON.parse(text);
|
||||||
|
} catch {
|
||||||
|
return text || null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return response.json();
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Exportamos o objeto 'api' com os métodos que os componentes vão usar.
|
// Exportamos o objeto 'api' com os métodos que os componentes vão usar.
|
||||||
@ -106,4 +115,25 @@ export const api = {
|
|||||||
patch: (endpoint, data, options) => request(endpoint, { method: "PATCH", body: JSON.stringify(data), ...options }),
|
patch: (endpoint, data, options) => request(endpoint, { method: "PATCH", body: JSON.stringify(data), ...options }),
|
||||||
delete: (endpoint, options) => request(endpoint, { method: "DELETE", ...options }),
|
delete: (endpoint, options) => request(endpoint, { method: "DELETE", ...options }),
|
||||||
logout: logout,
|
logout: logout,
|
||||||
|
storage: {
|
||||||
|
async upload(bucket, path, file) {
|
||||||
|
const token = localStorage.getItem("token");
|
||||||
|
const response = await fetch(`${BASE_URL}/storage/v1/object/${bucket}/${path}`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': file.type,
|
||||||
|
'apikey': API_KEY,
|
||||||
|
'Authorization': `Bearer ${token}`,
|
||||||
|
'x-upsert': 'true' // Isso faz com que o arquivo seja substituído se já existir
|
||||||
|
},
|
||||||
|
body: file,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorBody = await response.json();
|
||||||
|
throw new Error(`Erro no upload: ${errorBody.message}`);
|
||||||
|
}
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@ -45,4 +45,7 @@ export const appointmentsService = {
|
|||||||
* @returns {Promise<object>} - Uma promessa que resolve com a resposta da API.
|
* @returns {Promise<object>} - Uma promessa que resolve com a resposta da API.
|
||||||
*/
|
*/
|
||||||
delete: (id) => api.delete(`/rest/v1/appointments?id=eq.${id}`),
|
delete: (id) => api.delete(`/rest/v1/appointments?id=eq.${id}`),
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
};
|
};
|
||||||
@ -1,60 +1,98 @@
|
|||||||
import { api } from "./api.mjs";
|
import { api } from "./api.mjs";
|
||||||
|
|
||||||
export const usersService = {
|
export const usersService = {
|
||||||
// Função getMe corrigida para chamar a si mesma pelo nome
|
// Função getMe corrigida para chamar a si mesma pelo nome
|
||||||
async getMe() {
|
async getMe() {
|
||||||
const sessionData = await api.getSession();
|
const sessionData = await api.getSession();
|
||||||
if (!sessionData?.id) {
|
if (!sessionData?.id) {
|
||||||
console.error("Sessão não encontrada ou usuário sem ID.", sessionData);
|
console.error("Sessão não encontrada ou usuário sem ID.", sessionData);
|
||||||
throw new Error("Usuário não autenticado.");
|
throw new Error("Usuário não autenticado.");
|
||||||
}
|
}
|
||||||
// Chamando a outra função do serviço pelo nome explícito
|
// Chamando a outra função do serviço pelo nome explícito
|
||||||
return usersService.full_data(sessionData.id);
|
return usersService.full_data(sessionData.id);
|
||||||
},
|
},
|
||||||
|
|
||||||
async list_roles() {
|
async list_roles() {
|
||||||
return await api.get(`/rest/v1/user_roles?select=id,user_id,role,created_at`);
|
return await api.get(`/rest/v1/user_roles?select=id,user_id,role,created_at`);
|
||||||
},
|
},
|
||||||
|
|
||||||
async create_user(data) {
|
async create_user(data) {
|
||||||
// Esta é a função usada no page.tsx para criar usuários que não são médicos
|
// Esta é a função usada no page.tsx para criar usuários que não são médicos
|
||||||
return await api.post(`/functions/v1/create-user-with-password`, data);
|
return await api.post(`/functions/v1/create-user-with-password`, data);
|
||||||
},
|
},
|
||||||
|
|
||||||
async full_data(user_id) {
|
// --- NOVA FUNÇÃO ADICIONADA AQUI ---
|
||||||
if (!user_id) throw new Error("user_id é obrigatório");
|
// Esta função chama o endpoint público de registro de paciente.
|
||||||
|
async registerPatient(data) {
|
||||||
|
// POR QUÊ? Este endpoint é público e não requer token JWT, resolvendo o erro 401.
|
||||||
|
return await api.post("/functions/v1/register-patient", data);
|
||||||
|
},
|
||||||
|
// --- FIM DA NOVA FUNÇÃO ---
|
||||||
|
|
||||||
const [profile] = await api.get(`/rest/v1/profiles?id=eq.${user_id}`);
|
async getMeSimple() {
|
||||||
const [role] = await api.get(`/rest/v1/user_roles?user_id=eq.${user_id}`);
|
return await api.post(`/functions/v1/user-info`);
|
||||||
const permissions = {
|
},
|
||||||
isAdmin: role?.role === "admin",
|
|
||||||
isManager: role?.role === "gestor",
|
|
||||||
isDoctor: role?.role === "medico",
|
|
||||||
isSecretary: role?.role === "secretaria",
|
|
||||||
isAdminOrManager:
|
|
||||||
role?.role === "admin" || role?.role === "gestor" ? true : false,
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
async full_data(user_id) {
|
||||||
user: {
|
if (!user_id) throw new Error("user_id é obrigatório");
|
||||||
id: user_id,
|
|
||||||
email: profile?.email ?? "—",
|
const [profile] = await api.get(`/rest/v1/profiles?id=eq.${user_id}`);
|
||||||
email_confirmed_at: null,
|
const [role] = await api.get(`/rest/v1/user_roles?user_id=eq.${user_id}`);
|
||||||
created_at: profile?.created_at ?? "—",
|
const permissions = {
|
||||||
last_sign_in_at: null,
|
isAdmin: role?.role === "admin",
|
||||||
},
|
isManager: role?.role === "gestor",
|
||||||
profile: {
|
isDoctor: role?.role === "medico",
|
||||||
id: profile?.id ?? user_id,
|
isSecretary: role?.role === "secretaria",
|
||||||
full_name: profile?.full_name ?? "—",
|
isAdminOrManager: role?.role === "admin" || role?.role === "gestor" ? true : false,
|
||||||
email: profile?.email ?? "—",
|
};
|
||||||
phone: profile?.phone ?? "—",
|
|
||||||
avatar_url: profile?.avatar_url ?? null,
|
return {
|
||||||
disabled: profile?.disabled ?? false,
|
user: {
|
||||||
created_at: profile?.created_at ?? null,
|
id: user_id,
|
||||||
updated_at: profile?.updated_at ?? null,
|
email: profile?.email ?? "—",
|
||||||
},
|
email_confirmed_at: null,
|
||||||
roles: [role?.role ?? "—"],
|
created_at: profile?.created_at ?? "—",
|
||||||
permissions,
|
last_sign_in_at: null,
|
||||||
};
|
},
|
||||||
},
|
profile: {
|
||||||
};
|
id: profile?.id ?? user_id,
|
||||||
|
full_name: profile?.full_name ?? "—",
|
||||||
|
email: profile?.email ?? "—",
|
||||||
|
phone: profile?.phone ?? "—",
|
||||||
|
avatar_url: profile?.avatar_url ?? null,
|
||||||
|
disabled: profile?.disabled ?? false,
|
||||||
|
created_at: profile?.created_at ?? null,
|
||||||
|
updated_at: profile?.updated_at ?? null,
|
||||||
|
},
|
||||||
|
roles: [role?.role ?? "—"],
|
||||||
|
permissions,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
async resetPassword(email) {
|
||||||
|
if (!email) throw new Error("Email é obrigatório para resetar a senha.");
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${process.env.NEXT_PUBLIC_SUPABASE_URL}/auth/v1/recover`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
apikey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ email }),
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
console.error("Erro no resetPassword:", res.status, data);
|
||||||
|
throw new Error(`Erro ${res.status}: ${data.message || "Falha ao resetar senha."}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("✅ Reset de senha:", data);
|
||||||
|
return data;
|
||||||
|
} catch (err) {
|
||||||
|
console.error("❌ Erro na chamada resetPassword:", err);
|
||||||
|
throw new Error(err.message || "Erro inesperado na recuperação de senha.");
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|||||||