ajustes visuais em todas as paginas

This commit is contained in:
m1guelmcf 2025-11-21 14:41:33 -03:00
parent abd1333f11
commit 6e62797526
13 changed files with 4816 additions and 3829 deletions

View File

@ -1,9 +1,24 @@
"use client"; "use client";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import {
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";
@ -16,22 +31,22 @@ import { usersService } from "@/services/usersApi.mjs";
import Sidebar from "@/components/Sidebar"; import Sidebar from "@/components/Sidebar";
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 +76,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 +113,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,309 +121,365 @@ interface Exception {
} }
export default function PatientDashboard() { export default function PatientDashboard() {
const [loggedDoctor, setLoggedDoctor] = useState<Doctor>(); const [loggedDoctor, setLoggedDoctor] = useState<Doctor>();
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[]>([]);
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 [deleteDialogOpen, setDeleteDialogOpen] = useState(false); >({});
const [exceptionToDelete, setExceptionToDelete] = useState<string | null>(null); const formatTime = (time?: string | null) =>
const [error, setError] = useState<string | null>(null); time?.split(":")?.slice(0, 2).join(":") ?? "";
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [exceptionToDelete, setExceptionToDelete] = useState<string | null>(
null
);
const [error, setError] = useState<string | null>(null);
// Mapa de tradução // Mapa de tradução
const weekdaysPT: Record<string, string> = { const weekdaysPT: Record<string, string> = {
sunday: "Domingo", sunday: "Domingo",
monday: "Segunda", monday: "Segunda",
tuesday: "Terça", tuesday: "Terça",
wednesday: "Quarta", wednesday: "Quarta",
thursday: "Quinta", thursday: "Quinta",
friday: "Sexta", friday: "Sexta",
saturday: "Sábado", saturday: "Sábado",
};
useEffect(() => {
const fetchData = async () => {
try {
const doctorsList: Doctor[] = await doctorsService.list();
const doctor = doctorsList[0];
// Salva no estado
setLoggedDoctor(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);
// Busca exceções
const exceptionsList = await exceptionsService.list();
const filteredExc = exceptionsList.filter(
(exc: { doctor_id: string }) => exc.doctor_id === doctor?.id
);
console.log(exceptionsList)
setExceptions(filteredExc);
} catch (e: any) {
alert(`${e?.error} ${e?.message}`);
}
}; };
fetchData(); useEffect(() => {
}, []); const fetchData = async () => {
try {
const doctorsList: Doctor[] = await doctorsService.list();
const doctor = doctorsList[0];
// Função auxiliar para filtrar o id do doctor correspondente ao user logado // Salva no estado
function findDoctorById(id: string, doctors: Doctor[]) { setLoggedDoctor(doctor);
return doctors.find((doctor) => doctor.user_id === id);
} // Busca disponibilidade
const availabilityList = await AvailabilityService.list();
const openDeleteDialog = (exceptionId: string) => {
setExceptionToDelete(exceptionId); // Filtra já com a variável local
setDeleteDialogOpen(true); const filteredAvail = availabilityList.filter(
(disp: { doctor_id: string }) => disp.doctor_id === doctor?.id
);
setAvailability(filteredAvail);
// Busca exceções
const exceptionsList = await exceptionsService.list();
const filteredExc = exceptionsList.filter(
(exc: { doctor_id: string }) => exc.doctor_id === doctor?.id
);
console.log(exceptionsList);
setExceptions(filteredExc);
} catch (e: any) {
alert(`${e?.error} ${e?.message}`);
}
}; };
const handleDeleteException = async (ExceptionId: string) => { fetchData();
try { }, []);
alert(ExceptionId)
const res = await exceptionsService.delete(ExceptionId);
let message = "Exceção deletada com sucesso"; // Função auxiliar para filtrar o id do doctor correspondente ao user logado
try { function findDoctorById(id: string, doctors: Doctor[]) {
if (res) { return doctors.find((doctor) => doctor.user_id === id);
throw new Error(`${res.error} ${res.message}` || "A API retornou erro"); }
} else {
console.log(message); const openDeleteDialog = (exceptionId: string) => {
setExceptionToDelete(exceptionId);
setDeleteDialogOpen(true);
};
const handleDeleteException = async (ExceptionId: string) => {
try {
alert(ExceptionId);
const res = await exceptionsService.delete(ExceptionId);
let message = "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))
);
} catch (e: any) {
toast({
title: "Erro",
description: e?.message || "Não foi possível deletar a exceção",
});
}
setDeleteDialogOpen(false);
setExceptionToDelete(null);
};
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]);
return (
<Sidebar>
<div className="space-y-6">
<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>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Próxima Consulta
</CardTitle>
<Calendar className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">02 out</div>
<p className="text-xs text-muted-foreground">Dr. Silva - 14:30</p>
</CardContent>
</Card>
<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>
<div className="text-2xl font-bold">4</div>
<p className="text-xs text-muted-foreground">4 agendadas</p>
</CardContent>
</Card>
<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 className="grid md:grid-cols-2 gap-6">
<Card>
<CardHeader>
<CardTitle>Ações Rápidas</CardTitle>
<CardDescription>
Acesse rapidamente as principais funcionalidades
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<Link href="/doctor/medicos/consultas">
<Button className="bg-blue-600 hover:bg-blue-700 text-white cursor-pointer">
<Calendar className="mr-2 h-4 w-4 text-white" />
Ver Minhas Consultas
</Button>
</Link>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Próximas Consultas</CardTitle>
<CardDescription>Suas consultas agendadas</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="flex items-center justify-between p-3 bg-blue-50 rounded-lg">
<div>
<p className="font-medium">Dr. João Santos</p>
<p className="text-sm text-gray-600">Cardiologia</p>
</div>
<div className="text-right">
<p className="font-medium">02 out</p>
<p className="text-sm text-gray-600">14:30</p>
</div>
</div>
</div>
</CardContent>
</Card>
</div>
<div className="grid md:grid-cols-1 gap-6">
<Card>
<CardHeader>
<CardTitle>Horário Semanal</CardTitle>
<CardDescription>
Confira rapidamente a sua disponibilidade da semana
</CardDescription>
</CardHeader>
<CardContent className="space-y-4 grid md:grid-cols-7 gap-2">
{[
"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>
</div>
<div className="grid md:grid-cols-1 gap-6">
<Card>
<CardHeader>
<CardTitle>Exceções</CardTitle>
<CardDescription>
Bloqueios e liberações eventuais de agenda
</CardDescription>
</CardHeader>
<CardContent className="space-y-4 grid md:grid-cols-7 gap-2">
{exceptions && exceptions.length > 0 ? (
exceptions.map((ex: Exception) => {
// Formata data e hora
const date = new Date(ex.date).toLocaleDateString("pt-BR", {
weekday: "long",
day: "2-digit",
month: "long",
timeZone: "UTC",
});
const startTime = formatTime(ex.start_time);
const endTime = formatTime(ex.end_time);
return (
<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="text-center">
<p className="font-semibold capitalize">{date}</p>
<p className="text-sm text-gray-600">
{startTime && endTime
? `${startTime} - ${endTime}`
: "Dia todo"}
</p>
</div>
<div className="text-center mt-2">
<p
className={`text-sm font-medium ${
ex.kind === "bloqueio"
? "text-red-600"
: "text-green-600"
}`}
>
{ex.kind === "bloqueio" ? "Bloqueio" : "Liberação"}
</p>
<p className="text-xs text-gray-500 italic">
{ex.reason || "Sem motivo especificado"}
</p>
</div>
<div>
<Button
className="text-red-600"
variant="outline"
onClick={() => openDeleteDialog(String(ex.id))}
>
<Trash2></Trash2>
</Button>
</div>
</div>
</div>
);
})
) : (
<p className="text-sm text-gray-400 italic col-span-7 text-center">
Nenhuma exceção registrada.
</p>
)}
</CardContent>
</Card>
</div>
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
<AlertDialogDescription>
Tem certeza que deseja excluir esta exceção? Esta ação não pode
ser desfeita.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancelar</AlertDialogCancel>
<AlertDialogAction
onClick={() =>
exceptionToDelete && handleDeleteException(exceptionToDelete)
} }
} catch {} className="bg-red-600 hover:bg-red-700"
>
toast({ Excluir
title: "Sucesso", </AlertDialogAction>
description: message, </AlertDialogFooter>
}); </AlertDialogContent>
</AlertDialog>
setExceptions((prev: Exception[]) => prev.filter((p) => String(p.id) !== String(ExceptionId))); </div>
} catch (e: any) { </Sidebar>
toast({ );
title: "Erro",
description: e?.message || "Não foi possível deletar a exceção",
});
}
setDeleteDialogOpen(false);
setExceptionToDelete(null);
};
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]);
return (
<Sidebar>
<div className="space-y-6">
<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>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Próxima Consulta</CardTitle>
<Calendar className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">02 out</div>
<p className="text-xs text-muted-foreground">Dr. Silva - 14:30</p>
</CardContent>
</Card>
<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>
<div className="text-2xl font-bold">4</div>
<p className="text-xs text-muted-foreground">4 agendadas</p>
</CardContent>
</Card>
<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 className="grid md:grid-cols-2 gap-6">
<Card>
<CardHeader>
<CardTitle>Ações Rápidas</CardTitle>
<CardDescription>Acesse rapidamente as principais funcionalidades</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<Link href="/doctor/medicos/consultas">
<Button className="w-full justify-start">
<Calendar className="mr-2 h-4 w-4" />
Ver Minhas Consultas
</Button>
</Link>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Próximas Consultas</CardTitle>
<CardDescription>Suas consultas agendadas</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="flex items-center justify-between p-3 bg-blue-50 rounded-lg">
<div>
<p className="font-medium">Dr. João Santos</p>
<p className="text-sm text-gray-600">Cardiologia</p>
</div>
<div className="text-right">
<p className="font-medium">02 out</p>
<p className="text-sm text-gray-600">14:30</p>
</div>
</div>
</div>
</CardContent>
</Card>
</div>
<div className="grid md:grid-cols-1 gap-6">
<Card>
<CardHeader>
<CardTitle>Horário Semanal</CardTitle>
<CardDescription>Confira rapidamente a sua disponibilidade da semana</CardDescription>
</CardHeader>
<CardContent className="space-y-4 grid md:grid-cols-7 gap-2">
{["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>
</div>
<div className="grid md:grid-cols-1 gap-6">
<Card>
<CardHeader>
<CardTitle>Exceções</CardTitle>
<CardDescription>Bloqueios e liberações eventuais de agenda</CardDescription>
</CardHeader>
<CardContent className="space-y-4 grid md:grid-cols-7 gap-2">
{exceptions && exceptions.length > 0 ? (
exceptions.map((ex: Exception) => {
// Formata data e hora
const date = new Date(ex.date).toLocaleDateString("pt-BR", {
weekday: "long",
day: "2-digit",
month: "long",
timeZone: "UTC"
});
const startTime = formatTime(ex.start_time);
const endTime = formatTime(ex.end_time);
return (
<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="text-center">
<p className="font-semibold capitalize">{date}</p>
<p className="text-sm text-gray-600">
{startTime && endTime
? `${startTime} - ${endTime}`
: "Dia todo"}
</p>
</div>
<div className="text-center mt-2">
<p className={`text-sm font-medium ${ex.kind === "bloqueio" ? "text-red-600" : "text-green-600"}`}>{ex.kind === "bloqueio" ? "Bloqueio" : "Liberação"}</p>
<p className="text-xs text-gray-500 italic">{ex.reason || "Sem motivo especificado"}</p>
</div>
<div>
<Button className="text-red-600" variant="outline" onClick={() => openDeleteDialog(String(ex.id))}>
<Trash2></Trash2>
</Button>
</div>
</div>
</div>
);
})
) : (
<p className="text-sm text-gray-400 italic col-span-7 text-center">Nenhuma exceção registrada.</p>
)}
</CardContent>
</Card>
</div>
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
<AlertDialogDescription>Tem certeza que deseja excluir esta exceção? Esta ação não pode ser desfeita.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancelar</AlertDialogCancel>
<AlertDialogAction onClick={() => exceptionToDelete && handleDeleteException(exceptionToDelete)} className="bg-red-600 hover:bg-red-700">
Excluir
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</Sidebar>
);
} }

File diff suppressed because it is too large Load Diff

View File

@ -2,414 +2,463 @@
import { useEffect, useState, useCallback } from "react"; import { useEffect, useState, useCallback } from "react";
import Link from "next/link"; import Link from "next/link";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Eye, Edit, Calendar, Trash2, Loader2 } from "lucide-react"; import { Eye, Edit, Calendar, Trash2, Loader2 } from "lucide-react";
import { api } from "@/services/api.mjs"; import { api } from "@/services/api.mjs";
import { PatientDetailsModal } from "@/components/ui/patient-details-modal"; import { PatientDetailsModal } from "@/components/ui/patient-details-modal";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import Sidebar from "@/components/Sidebar"; import Sidebar from "@/components/Sidebar";
interface Paciente { interface Paciente {
id: string; id: string;
nome: string; nome: string;
telefone: string; telefone: string;
cidade: string; cidade: string;
estado: string; estado: string;
ultimoAtendimento?: string; ultimoAtendimento?: string;
proximoAtendimento?: string; proximoAtendimento?: string;
email?: string; email?: string;
birth_date?: string; birth_date?: string;
cpf?: string; cpf?: string;
blood_type?: string; blood_type?: string;
weight_kg?: number; weight_kg?: number;
height_m?: number; height_m?: number;
street?: string; street?: string;
number?: string; number?: string;
complement?: string; complement?: string;
neighborhood?: string; neighborhood?: string;
cep?: string; cep?: string;
} }
export default function PacientesPage() { export default function PacientesPage() {
const [pacientes, setPacientes] = useState<Paciente[]>([]); const [pacientes, setPacientes] = useState<Paciente[]>([]);
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 [selectedPatient, setSelectedPatient] = useState<Paciente | null>(null); const [selectedPatient, setSelectedPatient] = useState<Paciente | null>(null);
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(5);
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
const totalPages = Math.ceil(pacientes.length / itemsPerPage); const totalPages = Math.ceil(pacientes.length / itemsPerPage);
const indexOfLastItem = currentPage * itemsPerPage; const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage; const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = pacientes.slice(indexOfFirstItem, indexOfLastItem); const currentItems = pacientes.slice(indexOfFirstItem, indexOfLastItem);
const paginate = (pageNumber: number) => setCurrentPage(pageNumber); const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
// Funções de Navegação // Funções de Navegação
const goToPrevPage = () => { const goToPrevPage = () => {
setCurrentPage((prev) => Math.max(1, prev - 1)); setCurrentPage((prev) => Math.max(1, prev - 1));
}; };
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[] = [];
const maxVisiblePages = 5; const maxVisiblePages = 5;
const halfRange = Math.floor(maxVisiblePages / 2); const halfRange = Math.floor(maxVisiblePages / 2);
let startPage = Math.max(1, currentPage - halfRange); let startPage = Math.max(1, currentPage - halfRange);
let endPage = Math.min(totalPages, currentPage + halfRange); let endPage = Math.min(totalPages, currentPage + halfRange);
if (endPage - startPage + 1 < maxVisiblePages) { if (endPage - startPage + 1 < maxVisiblePages) {
if (endPage === totalPages) { if (endPage === totalPages) {
startPage = Math.max(1, totalPages - maxVisiblePages + 1); startPage = Math.max(1, totalPages - maxVisiblePages + 1);
} }
if (startPage === 1) { if (startPage === 1) {
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
const handleItemsPerPageChange = (value: string) => { const handleItemsPerPageChange = (value: string) => {
setItemsPerPage(Number(value)); setItemsPerPage(Number(value));
setCurrentPage(1); setCurrentPage(1);
}; };
// --- Lógica de Paginação FIM --- // --- Lógica de Paginação FIM ---
const handleOpenModal = (patient: Paciente) => {
setSelectedPatient(patient);
setIsModalOpen(true);
};
const handleOpenModal = (patient: Paciente) => { const handleCloseModal = () => {
setSelectedPatient(patient); setSelectedPatient(null);
setIsModalOpen(true); setIsModalOpen(false);
}; };
const handleCloseModal = () => { const formatDate = (dateString: string | null | undefined) => {
setSelectedPatient(null); if (!dateString) return "N/A";
setIsModalOpen(false); try {
}; const date = new Date(dateString);
return new Intl.DateTimeFormat("pt-BR").format(date);
} catch (e) {
return dateString; // Retorna o string original se o formato for inválido
}
};
const formatDate = (dateString: string | null | undefined) => { const fetchPacientes = useCallback(async () => {
if (!dateString) return "N/A"; try {
try { setLoading(true);
const date = new Date(dateString); setError(null);
return new Intl.DateTimeFormat("pt-BR").format(date); const json = await api.get("/rest/v1/patients");
} catch (e) { const items = Array.isArray(json)
return dateString; // Retorna o string original se o formato for inválido ? json
} : Array.isArray(json?.data)
}; ? json.data
: [];
const fetchPacientes = useCallback(async () => { const mapped: Paciente[] = items.map((p: any) => ({
try { id: String(p.id ?? ""),
setLoading(true); nome: p.full_name ?? "—",
setError(null); telefone: p.phone_mobile ?? "N/A",
const json = await api.get("/rest/v1/patients"); cidade: p.city ?? "N/A",
const items = Array.isArray(json) estado: p.state ?? "N/A",
? json ultimoAtendimento: formatDate(p.created_at),
: Array.isArray(json?.data) proximoAtendimento: "N/A", // Necessita de lógica de agendamento real
? json.data email: p.email ?? "N/A",
: []; birth_date: p.birth_date ?? "N/A",
cpf: p.cpf ?? "N/A",
blood_type: p.blood_type ?? "N/A",
weight_kg: p.weight_kg ?? 0,
height_m: p.height_m ?? 0,
street: p.street ?? "N/A",
number: p.number ?? "N/A",
complement: p.complement ?? "N/A",
neighborhood: p.neighborhood ?? "N/A",
cep: p.cep ?? "N/A",
}));
const mapped: Paciente[] = items.map((p: any) => ({ setPacientes(mapped);
id: String(p.id ?? ""), setCurrentPage(1); // Resetar a página ao carregar novos dados
nome: p.full_name ?? "—", } catch (e: any) {
telefone: p.phone_mobile ?? "N/A", console.error("Erro ao carregar pacientes:", e);
cidade: p.city ?? "N/A", setError(e?.message || "Erro ao carregar pacientes");
estado: p.state ?? "N/A", } finally {
ultimoAtendimento: formatDate(p.created_at), setLoading(false);
proximoAtendimento: "N/A", // Necessita de lógica de agendamento real }
email: p.email ?? "N/A", }, []);
birth_date: p.birth_date ?? "N/A",
cpf: p.cpf ?? "N/A",
blood_type: p.blood_type ?? "N/A",
weight_kg: p.weight_kg ?? 0,
height_m: p.height_m ?? 0,
street: p.street ?? "N/A",
number: p.number ?? "N/A",
complement: p.complement ?? "N/A",
neighborhood: p.neighborhood ?? "N/A",
cep: p.cep ?? "N/A",
}));
setPacientes(mapped); useEffect(() => {
setCurrentPage(1); // Resetar a página ao carregar novos dados fetchPacientes();
} catch (e: any) { }, [fetchPacientes]);
console.error("Erro ao carregar pacientes:", e);
setError(e?.message || "Erro ao carregar pacientes");
} finally {
setLoading(false);
}
}, []);
useEffect(() => { return (
fetchPacientes(); <Sidebar>
}, [fetchPacientes]); <div className="space-y-6 px-2 sm:px-4 md:px-6">
{/* Cabeçalho */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
{" "}
{/* Ajustado para flex-col em telas pequenas */}
<div>
<h1 className="text-2xl font-bold text-foreground">Pacientes</h1>
<p className="text-muted-foreground text-sm sm:text-base">
Lista de pacientes vinculados
</p>
</div>
{/* Controles de filtro e novo paciente */}
{/* 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
onValueChange={handleItemsPerPageChange}
defaultValue={String(itemsPerPage)}
>
<SelectTrigger className="w-full sm: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>
<Link href="/doctor/pacientes/novo" className="w-full sm:w-auto">
<Button
variant="default"
className="bg-blue-600 hover:bg-blue-700 w-full sm:w-auto"
>
Novo Paciente
</Button>
</Link>
</div>
</div>
return ( <div className="bg-card rounded-lg border border-border overflow-hidden shadow-md">
<Sidebar> {/* Tabela para Telas Médias e Grandes */}
<div className="space-y-6 px-2 sm:px-4 md:px-6"> <div className="overflow-x-auto hidden md:block">
{/* Cabeçalho */} {" "}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3"> {/* Ajustado para flex-col em telas pequenas */} {/* Esconde em telas pequenas */}
<div> <table className="min-w-[600px] w-full">
<h1 className="text-2xl font-bold text-foreground">Pacientes</h1> <thead className="bg-muted border-b border-border">
<p className="text-muted-foreground text-sm sm:text-base"> <tr>
Lista de pacientes vinculados <th className="text-left p-3 sm:p-4 font-medium text-foreground">
</p> Nome
</th>
<th className="text-left p-3 sm:p-4 font-medium text-foreground">
Telefone
</th>
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden lg:table-cell">
Cidade
</th>
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden lg:table-cell">
Estado
</th>
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden xl:table-cell">
Último atendimento
</th>
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden xl:table-cell">
Próximo atendimento
</th>
<th className="text-left p-3 sm:p-4 font-medium text-foreground">
Ações
</th>
</tr>
</thead>
<tbody>
{loading ? (
<tr>
<td
colSpan={7}
className="p-6 text-muted-foreground text-center"
>
<Loader2 className="w-6 h-6 animate-spin mx-auto text-primary" />
Carregando pacientes...
</td>
</tr>
) : error ? (
<tr>
<td
colSpan={7}
className="p-6 text-red-600 text-center"
>{`Erro: ${error}`}</td>
</tr>
) : pacientes.length === 0 ? (
<tr>
<td
colSpan={7}
className="p-8 text-center text-muted-foreground"
>
Nenhum paciente encontrado
</td>
</tr>
) : (
currentItems.map((p) => (
<tr
key={p.id}
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 text-muted-foreground">
{p.telefone}
</td>
<td className="p-3 sm:p-4 text-muted-foreground hidden lg:table-cell">
{p.cidade}
</td>
<td className="p-3 sm:p-4 text-muted-foreground hidden lg:table-cell">
{p.estado}
</td>
<td className="p-3 sm:p-4 text-muted-foreground hidden xl:table-cell">
{p.ultimoAtendimento}
</td>
<td className="p-3 sm:p-4 text-muted-foreground hidden xl:table-cell">
{p.proximoAtendimento}
</td>
<td className="p-3 sm:p-4">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="text-primary hover:underline text-sm sm:text-base">
Ações
</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>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
{/* 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> </div>
{/* Controles de filtro e novo paciente */} {/* Removido o 'truncate' e adicionado 'break-words' no telefone */}
{/* 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="text-sm text-muted-foreground break-words">
<div className="flex flex-wrap gap-3 mt-4 sm:mt-0 w-full sm:w-auto justify-start sm:justify-end"> Telefone: **{p.telefone || "N/A"}**
<Select </div>
onValueChange={handleItemsPerPageChange} </div>
defaultValue={String(itemsPerPage)} <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}`)
}
> >
<SelectTrigger className="w-full sm:w-[140px]"> <Calendar className="w-4 h-4 mr-2" />
<SelectValue placeholder="Itens por pág." /> Ver agenda
</SelectTrigger> </DropdownMenuItem>
<SelectContent> <DropdownMenuItem
<SelectItem value="5">5 por página</SelectItem> onClick={() => {
<SelectItem value="10">10 por página</SelectItem> const newPacientes = pacientes.filter(
<SelectItem value="20">20 por página</SelectItem> (pac) => pac.id !== p.id
</SelectContent> );
</Select> setPacientes(newPacientes);
<Link href="/doctor/pacientes/novo" className="w-full sm:w-auto"> alert(`Paciente ID: ${p.id} excluído`);
<Button variant="default" className="bg-green-600 hover:bg-green-700 w-full sm:w-auto"> }}
Novo Paciente className="text-red-600 focus:bg-red-50 focus:text-red-600"
</Button> >
</Link> <Trash2 className="w-4 h-4 mr-2" />
</div> Excluir
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div> </div>
))
)}
</div>
{/* Paginação */}
{totalPages > 1 && (
<div className="flex flex-wrap justify-center items-center gap-2 border-t border-border p-4 bg-muted/40">
{/* 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-secondary text-secondary-foreground hover:bg-secondary/80 disabled:opacity-50 disabled:cursor-not-allowed border border-border"
>
{"< Anterior"}
</button>
<div className="bg-card rounded-lg border border-border overflow-hidden shadow-md"> {/* Números das Páginas */}
{/* Tabela para Telas Médias e Grandes */} {visiblePageNumbers.map((number) => (
<div className="overflow-x-auto hidden md:block"> {/* Esconde em telas pequenas */} <button
<table className="min-w-[600px] w-full"> key={number}
<thead className="bg-muted border-b border-border"> onClick={() => paginate(number)}
<tr> className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border border-border ${
<th className="text-left p-3 sm:p-4 font-medium text-foreground">Nome</th> currentPage === number
<th className="text-left p-3 sm:p-4 font-medium text-foreground"> ? "bg-blue-600 text-primary-foreground shadow-md border-blue-600"
Telefone : "bg-secondary text-secondary-foreground hover:bg-secondary/80"
</th> }`}
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden lg:table-cell"> >
Cidade {number}
</th> </button>
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden lg:table-cell"> ))}
Estado
</th>
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden xl:table-cell">
Último atendimento
</th>
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden xl:table-cell">
Próximo atendimento
</th>
<th className="text-left p-3 sm:p-4 font-medium text-foreground">Ações</th>
</tr>
</thead>
<tbody>
{loading ? (
<tr>
<td colSpan={7} className="p-6 text-muted-foreground text-center">
<Loader2 className="w-6 h-6 animate-spin mx-auto text-primary" />
Carregando pacientes...
</td>
</tr>
) : error ? (
<tr>
<td colSpan={7} className="p-6 text-red-600 text-center">{`Erro: ${error}`}</td>
</tr>
) : pacientes.length === 0 ? (
<tr>
<td colSpan={7} className="p-8 text-center text-muted-foreground">
Nenhum paciente encontrado
</td>
</tr>
) : (
currentItems.map((p) => (
<tr
key={p.id}
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 text-muted-foreground">
{p.telefone}
</td>
<td className="p-3 sm:p-4 text-muted-foreground hidden lg:table-cell">
{p.cidade}
</td>
<td className="p-3 sm:p-4 text-muted-foreground hidden lg:table-cell">
{p.estado}
</td>
<td className="p-3 sm:p-4 text-muted-foreground hidden xl:table-cell">
{p.ultimoAtendimento}
</td>
<td className="p-3 sm:p-4 text-muted-foreground hidden xl:table-cell">
{p.proximoAtendimento}
</td>
<td className="p-3 sm:p-4">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="text-primary hover:underline text-sm sm:text-base">
Ações
</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>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
{/* Layout em Cards/Lista para Telas Pequenas */} {/* Botão Próximo */}
<div className="md:hidden divide-y divide-border"> {/* Visível apenas em telas pequenas */} <button
{loading ? ( onClick={goToNextPage}
<div className="p-6 text-muted-foreground text-center"> disabled={currentPage === totalPages}
<Loader2 className="w-6 h-6 animate-spin mx-auto text-primary" /> className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-secondary text-secondary-foreground hover:bg-secondary/80 disabled:opacity-50 disabled:cursor-not-allowed border border-border"
Carregando pacientes... >
</div> {"Próximo >"}
) : error ? ( </button>
<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 && (
<div className="flex flex-wrap justify-center items-center gap-2 border-t border-border p-4 bg-muted/40">
{/* 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-secondary text-secondary-foreground hover:bg-secondary/80 disabled:opacity-50 disabled:cursor-not-allowed border border-border"
>
{"< 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-border ${
currentPage === number
? "bg-green-600 text-primary-foreground shadow-md border-green-600"
: "bg-secondary text-secondary-foreground hover:bg-secondary/80"
}`}
>
{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-secondary text-secondary-foreground hover:bg-secondary/80 disabled:opacity-50 disabled:cursor-not-allowed border border-border"
>
{"Próximo >"}
</button>
</div>
)}
</div>
</div> </div>
)}
</div>
</div>
<PatientDetailsModal <PatientDetailsModal
patient={selectedPatient} patient={selectedPatient}
@ -418,4 +467,4 @@ export default function PacientesPage() {
/> />
</Sidebar> </Sidebar>
); );
} }

View File

@ -1,6 +1,12 @@
"use client"; "use client";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import {
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 { Calendar, Clock, Plus, User } from "lucide-react";
import Link from "next/link"; import Link from "next/link";
@ -10,181 +16,212 @@ import { doctorsService } from "services/doctorsApi.mjs";
import Sidebar from "@/components/Sidebar"; import Sidebar from "@/components/Sidebar";
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
useEffect(() => { useEffect(() => {
async function fetchFirstUser() { async function fetchFirstUser() {
try { try {
const data = await usersService.list_roles(); const data = await usersService.list_roles();
if (Array.isArray(data) && data.length > 0) { if (Array.isArray(data) && data.length > 0) {
setFirstUser(data[0]); setFirstUser(data[0]);
}
} catch (error) {
console.error("Erro ao carregar usuário:", error);
} finally {
setLoadingUser(false);
}
} }
} catch (error) {
console.error("Erro ao carregar usuário:", error);
} finally {
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 (
<Sidebar> <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">
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">
{/* 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> </div>
) : firstUser ? (
{/* Cards principais */} <>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6"> <div className="text-2xl font-bold">
{/* Card 1 */} {firstUser.full_name || "Sem nome"}
<Card> </div>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2"> <p className="text-xs text-muted-foreground">
<CardTitle className="text-sm font-medium">Relatórios gerenciais</CardTitle> {firstUser.email || "Sem e-mail cadastrado"}
<Calendar className="h-4 w-4 text-muted-foreground" /> </p>
</CardHeader> </>
<CardContent> ) : (
<div className="text-2xl font-bold">0</div> <div className="text-sm text-gray-500">
<p className="text-xs text-muted-foreground">Relatórios disponíveis</p> Nenhum usuário encontrado
</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>
<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 */} {/* Card 3 — Perfil */}
<div className="grid md:grid-cols-2 gap-6"> <Card>
{/* 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">Perfil</CardTitle>
<CardHeader> <User className="h-4 w-4 text-muted-foreground" />
<CardTitle>Ações Rápidas</CardTitle> </CardHeader>
<CardDescription>Acesse rapidamente as principais funcionalidades</CardDescription> <CardContent>
</CardHeader> <div className="text-2xl font-bold">100%</div>
<CardContent className="space-y-4"> <p className="text-xs text-muted-foreground">Dados completos</p>
<Link href="/manager/home"> </CardContent>
<Button className="w-full justify-start"> </Card>
<User className="mr-2 h-4 w-4" /> </div>
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 */} {/* Cards secundários */}
<Card> <div className="grid md:grid-cols-2 gap-6">
<CardHeader> {/* Card — Ações rápidas */}
<CardTitle>Gestão de Médicos</CardTitle> <Card>
<CardDescription>Médicos cadastrados recentemente</CardDescription> <CardHeader>
</CardHeader> <CardTitle>Ações Rápidas</CardTitle>
<CardContent> <CardDescription>
{loadingDoctors ? ( Acesse rapidamente as principais funcionalidades
<p className="text-sm text-gray-500">Carregando médicos...</p> </CardDescription>
) : doctors.length === 0 ? ( </CardHeader>
<p className="text-sm text-gray-500">Nenhum médico cadastrado.</p> <CardContent className="space-y-4">
) : ( <Link href="/manager/home">
<div className="space-y-4"> <Button className="w-full justify-start bg-blue-600 text-white hover:bg-blue-700">
{doctors.map((doc, index) => ( <User className="mr-2 h-4 w-4 text-white" />
<div Gestão de Médicos
key={index} </Button>
className="flex items-center justify-between p-3 bg-green-50 rounded-lg border border-green-100" </Link>
> <Link href="/manager/usuario">
<div> <Button
<p className="font-medium">{doc.full_name || "Sem nome"}</p> variant="outline"
<p className="text-sm text-gray-600"> className="w-full justify-start bg-transparent"
{doc.specialty || "Sem especialidade"} >
</p> <User className="mr-2 h-4 w-4" />
</div> Usuários Cadastrados
<div className="text-right"> </Button>
<p className="font-medium text-green-700"> </Link>
{doc.active ? "Ativo" : "Inativo"} <Link href="/manager/home/novo">
</p> <Button
</div> variant="outline"
</div> className="w-full justify-start bg-transparent"
))} >
</div> <Plus className="mr-2 h-4 w-4" />
)} Adicionar Novo Médico
</CardContent> </Button>
</Card> </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> </div>
</div> )}
</Sidebar> </CardContent>
); </Card>
</div>
</div>
</Sidebar>
);
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -3,416 +3,451 @@
import React, { useEffect, useState, useCallback } from "react"; import React, { useEffect, useState, useCallback } from "react";
import Link from "next/link"; import Link from "next/link";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Plus, Eye, Filter, Loader2 } from "lucide-react"; import { Plus, Eye, Filter, Loader2 } from "lucide-react";
import { AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog"; 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"; 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() {
const [users, setUsers] = useState<FlatUser[]>([]); const [users, setUsers] = useState<FlatUser[]>([]);
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 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);
const handleItemsPerPageChange = (value: string) => { const handleItemsPerPageChange = (value: string) => {
setItemsPerPage(Number(value)); setItemsPerPage(Number(value));
setCurrentPage(1); setCurrentPage(1);
}; };
// --- 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);
} 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(() => {
const data = await usersService.full_data(flatUser.user_id); const init = async () => {
setUserDetails(data); try {
} catch (err: any) { await login();
console.error("Erro ao carregar detalhes:", err); } catch (e) {
setUserDetails({ console.warn("login falhou no init:", e);
user: { id: flatUser.user_id, email: flatUser.email }, }
profile: { full_name: flatUser.full_name, phone: flatUser.phone }, await fetchUsers();
roles: [flatUser.role],
permissions: {},
});
}
}; };
init();
}, [fetchUsers]);
const filteredUsers = const openDetailsDialog = async (flatUser: FlatUser) => {
selectedRole && selectedRole !== "all" setDetailsDialogOpen(true);
? users.filter((u) => u.role === selectedRole) setUserDetails(null);
: users;
const indexOfLastItem = currentPage * itemsPerPage; try {
const indexOfFirstItem = indexOfLastItem - itemsPerPage; const data = await usersService.full_data(flatUser.user_id);
const currentItems = filteredUsers.slice(indexOfFirstItem, indexOfLastItem); setUserDetails(data);
} 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: {},
});
}
};
const paginate = (pageNumber: number) => setCurrentPage(pageNumber); const filteredUsers =
selectedRole && selectedRole !== "all"
? users.filter((u) => u.role === selectedRole)
: users;
const totalPages = Math.ceil(filteredUsers.length / itemsPerPage); const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = filteredUsers.slice(indexOfFirstItem, indexOfLastItem);
const goToPrevPage = () => { const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
setCurrentPage((prev) => Math.max(1, prev - 1));
};
const goToNextPage = () => { const totalPages = Math.ceil(filteredUsers.length / itemsPerPage);
setCurrentPage((prev) => Math.min(totalPages, prev + 1));
};
const getVisiblePageNumbers = (totalPages: number, currentPage: number) => { const goToPrevPage = () => {
const pages: number[] = []; setCurrentPage((prev) => Math.max(1, prev - 1));
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) { const goToNextPage = () => {
if (endPage === totalPages) { setCurrentPage((prev) => Math.min(totalPages, prev + 1));
startPage = Math.max(1, totalPages - maxVisiblePages + 1); };
}
if (startPage === 1) {
endPage = Math.min(totalPages, maxVisiblePages);
}
}
for (let i = startPage; i <= endPage; i++) { const getVisiblePageNumbers = (totalPages: number, currentPage: number) => {
pages.push(i); const pages: number[] = [];
} const maxVisiblePages = 5;
return pages; const halfRange = Math.floor(maxVisiblePages / 2);
}; let startPage = Math.max(1, currentPage - halfRange);
let endPage = Math.min(totalPages, currentPage + halfRange);
const visiblePageNumbers = getVisiblePageNumbers(totalPages, currentPage); if (endPage - startPage + 1 < maxVisiblePages) {
if (endPage === totalPages) {
startPage = Math.max(1, totalPages - maxVisiblePages + 1);
}
if (startPage === 1) {
endPage = Math.min(totalPages, maxVisiblePages);
}
}
return ( for (let i = startPage; i <= endPage; i++) {
<Sidebar> pages.push(i);
<div className="space-y-6 px-2 sm:px-4 md:px-8"> }
return pages;
};
{/* Header */} const visiblePageNumbers = getVisiblePageNumbers(totalPages, currentPage);
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 className="text-2xl font-bold text-gray-900">Usuários</h1>
<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 */} return (
<div className="flex flex-wrap items-center gap-3 bg-white p-4 rounded-lg border border-gray-200"> <Sidebar>
<div className="space-y-6 px-2 sm:px-4 md:px-8">
{/* Header */}
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 className="text-2xl font-bold text-gray-900">Usuários</h1>
<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-blue-600 hover:bg-blue-700">
<Plus className="w-4 h-4 mr-2" /> Novo Usuário
</Button>
</Link>
</div>
{/* Select de Filtro por Papel - Ajustado para resetar a página */} {/* Filtro e Itens por Página */}
<div className="flex items-center gap-2 w-full md:w-auto"> <div className="flex flex-wrap items-center gap-3 bg-white p-4 rounded-lg border border-gray-200">
<span className="text-sm font-medium text-foreground whitespace-nowrap"> {/* Select de Filtro por Papel - Ajustado para resetar a página */}
Filtrar por papel <div className="flex items-center gap-2 w-full md:w-auto">
</span> <span className="text-sm font-medium text-foreground whitespace-nowrap">
<Select Filtrar por papel
onValueChange={(value) => { </span>
setSelectedRole(value); <Select
setCurrentPage(1); onValueChange={(value) => {
}} setSelectedRole(value);
value={selectedRole}> setCurrentPage(1);
}}
value={selectedRole}
>
<SelectTrigger className="w-full sm:w-[180px]">
{" "}
{/* w-full para mobile, w-[180px] para sm+ */}
<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>
<SelectTrigger className="w-full sm:w-[180px]"> {/* w-full para mobile, w-[180px] para sm+ */} {/* Select de Itens por Página */}
<SelectValue placeholder="Filtrar por papel" /> <div className="flex items-center gap-2 w-full md:w-auto">
</SelectTrigger> <span className="text-sm font-medium text-foreground whitespace-nowrap">
<SelectContent> Itens por página
<SelectItem value="all">Todos</SelectItem> </span>
<SelectItem value="admin">Admin</SelectItem> <Select
<SelectItem value="gestor">Gestor</SelectItem> onValueChange={handleItemsPerPageChange}
<SelectItem value="medico">Médico</SelectItem> defaultValue={String(itemsPerPage)}
<SelectItem value="secretaria">Secretária</SelectItem> >
<SelectItem value="user">Usuário</SelectItem> <SelectTrigger className="w-full sm:w-[140px]">
</SelectContent> {" "}
</Select> {/* w-full para mobile, w-[140px] para sm+ */}
</div> <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>
{/* Fim do Filtro e Itens por Página */}
{/* Select de Itens por Página */} {/* Tabela/Lista */}
<div className="flex items-center gap-2 w-full md:w-auto"> <div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-x-auto">
<span className="text-sm font-medium text-foreground whitespace-nowrap"> {loading ? (
Itens por página <div className="p-8 text-center text-gray-500">
</span> <Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
<Select Carregando usuários...
onValueChange={handleItemsPerPageChange}
defaultValue={String(itemsPerPage)}
>
<SelectTrigger className="w-full sm:w-[140px]"> {/* w-full para mobile, w-[140px] para sm+ */}
<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>
{/* Fim do Filtro e Itens por Página */}
{/* Tabela/Lista */}
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-x-auto">
{loading ? (
<div className="p-8 text-center text-gray-500">
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
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>
) : (
<>
{/* 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-sm text-gray-500 capitalize">
{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-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>
)}
</>
)}
</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> </div>
</Sidebar> ) : 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-sm text-gray-500 capitalize">
{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>
);
}

View File

@ -1,8 +1,14 @@
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import {
import { Button } from "@/components/ui/button" Card,
import { Calendar, Clock, User, Plus } from "lucide-react" CardContent,
import Link from "next/link" CardDescription,
import Sidebar from "@/components/Sidebar" 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 (
@ -10,13 +16,17 @@ export default function PatientDashboard() {
<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>
@ -109,5 +131,5 @@ export default function PatientDashboard() {
</div> </div>
</div> </div>
</Sidebar> </Sidebar>
) );
} }

View File

@ -18,243 +18,359 @@ import { toast } from "@/hooks/use-toast";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
interface PatientProfileData { interface PatientProfileData {
name: string; name: string;
email: string; email: string;
phone: string; phone: string;
cpf: string; cpf: string;
birthDate: string; birthDate: string;
cep: string; cep: string;
street: string; street: string;
number: string; number: string;
city: string; city: string;
avatarFullUrl?: string; avatarFullUrl?: string;
} }
export default function PatientProfile() { export default function PatientProfile() {
const { user, isLoading: isAuthLoading } = useAuthLayout({ requiredRole: ["paciente", "admin", "medico", "gestor", "secretaria"] }); const { user, isLoading: isAuthLoading } = useAuthLayout({
const [patientData, setPatientData] = useState<PatientProfileData | null>(null); requiredRole: ["paciente", "admin", "medico", "gestor", "secretaria"],
const [isEditing, setIsEditing] = useState(false); });
const [isSaving, setIsSaving] = useState(false); const [patientData, setPatientData] = useState<PatientProfileData | null>(
const fileInputRef = useRef<HTMLInputElement>(null); null
);
const [isEditing, setIsEditing] = useState(false);
const [isSaving, setIsSaving] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
useEffect(() => { useEffect(() => {
if (user?.id) { if (user?.id) {
const fetchPatientDetails = async () => { const fetchPatientDetails = async () => {
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 handleInputChange = (field: keyof PatientProfileData, value: string) => {
setPatientData((prev) => (prev ? { ...prev, [field]: value } : null));
};
const handleSave = async () => {
if (!patientData || !user) return;
setIsSaving(true);
try { try {
const patientPayload = { const patientDetails = await patientsService.getById(user.id);
full_name: patientData.name, setPatientData({
cpf: patientData.cpf, name: patientDetails.full_name || user.name,
birth_date: patientData.birthDate, email: user.email,
phone_mobile: patientData.phone, phone: patientDetails.phone_mobile || "",
cep: patientData.cep, cpf: patientDetails.cpf || "",
street: patientData.street, birthDate: patientDetails.birth_date || "",
number: patientData.number, cep: patientDetails.cep || "",
city: patientData.city, street: patientDetails.street || "",
}; number: patientDetails.number || "",
await patientsService.update(user.id, patientPayload); city: patientDetails.city || "",
toast({ title: "Sucesso!", description: "Seus dados foram atualizados." }); avatarFullUrl: user.avatarFullUrl,
setIsEditing(false); });
} catch (error) { } catch (error) {
console.error("Erro ao salvar dados:", error); console.error("Erro ao buscar detalhes do paciente:", error);
toast({ title: "Erro", description: "Não foi possível salvar suas alterações.", variant: "destructive" }); toast({
} finally { title: "Erro",
setIsSaving(false); description: "Não foi possível carregar seus dados completos.",
variant: "destructive",
});
} }
}; };
fetchPatientDetails();
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>
);
} }
}, [user]);
const handleInputChange = (
field: keyof PatientProfileData,
value: string
) => {
setPatientData((prev) => (prev ? { ...prev, [field]: value } : null));
};
const handleSave = async () => {
if (!patientData || !user) return;
setIsSaving(true);
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 ( return (
<Sidebar> <Sidebar>
<div className="space-y-6"> <div>Carregando seus dados...</div>
<div className="flex justify-between items-center"> </Sidebar>
<div>
<h1 className="text-3xl font-bold text-gray-900">Meus Dados</h1>
<p className="text-gray-600">Gerencie suas informações pessoais</p>
</div>
<Button onClick={() => (isEditing ? handleSave() : setIsEditing(true))} disabled={isSaving}>
{isEditing ? (isSaving ? "Salvando..." : "Salvar Alterações") : "Editar Dados"}
</Button>
</div>
<div className="grid lg:grid-cols-3 gap-6">
<div className="lg:col-span-2 space-y-6">
<Card>
<CardHeader>
<CardTitle className="flex items-center">
<User className="mr-2 h-5 w-5" />
Informações Pessoais
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid md:grid-cols-2 gap-4">
<div>
<Label htmlFor="name">Nome Completo</Label>
<Input id="name" value={patientData.name} onChange={(e) => handleInputChange("name", e.target.value)} disabled={!isEditing} />
</div>
<div>
<Label htmlFor="cpf">CPF</Label>
<Input id="cpf" value={patientData.cpf} onChange={(e) => handleInputChange("cpf", e.target.value)} disabled={!isEditing} />
</div>
</div>
<div>
<Label htmlFor="birthDate">Data de Nascimento</Label>
<Input id="birthDate" type="date" value={patientData.birthDate} onChange={(e) => handleInputChange("birthDate", e.target.value)} disabled={!isEditing} />
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="flex items-center">
<Mail className="mr-2 h-5 w-5" />
Contato e Endereço
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid md:grid-cols-2 gap-4">
<div>
<Label htmlFor="email">Email</Label>
<Input id="email" type="email" value={patientData.email} disabled />
</div>
<div>
<Label htmlFor="phone">Telefone</Label>
<Input id="phone" value={patientData.phone} onChange={(e) => handleInputChange("phone", e.target.value)} disabled={!isEditing} />
</div>
</div>
<div className="grid md:grid-cols-3 gap-4">
<div>
<Label htmlFor="cep">CEP</Label>
<Input id="cep" value={patientData.cep} onChange={(e) => handleInputChange("cep", e.target.value)} disabled={!isEditing} />
</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>
</CardContent>
</Card>
</div>
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle>Resumo do Perfil</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center space-x-3">
<div className="relative">
<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>
<p className="font-medium">{patientData.name}</p>
<p className="text-sm text-gray-500">Paciente</p>
</div>
</div>
<div className="space-y-3 pt-4 border-t">
<div className="flex items-center text-sm">
<Mail className="mr-2 h-4 w-4 text-gray-500" />
<span className="truncate">{patientData.email}</span>
</div>
<div className="flex items-center text-sm">
<Phone className="mr-2 h-4 w-4 text-gray-500" />
<span>{patientData.phone || "Não informado"}</span>
</div>
<div className="flex items-center text-sm">
<Calendar className="mr-2 h-4 w-4 text-gray-500" />
<span>{patientData.birthDate ? new Date(patientData.birthDate).toLocaleDateString("pt-BR", { timeZone: "UTC" }) : "Não informado"}</span>
</div>
</div>
</CardContent>
</Card>
</div>
</div>
</div>
</Sidebar>
); );
}
return (
<Sidebar>
<div className="space-y-6">
<div className="flex justify-between items-center">
<div>
<h1 className="text-3xl font-bold text-gray-900">Meus Dados</h1>
<p className="text-gray-600">Gerencie suas informações pessoais</p>
</div>
<Button
onClick={() => (isEditing ? handleSave() : setIsEditing(true))}
disabled={isSaving}
className="bg-blue-600 hover:bg-blue-700 text-white"
>
{isEditing
? isSaving
? "Salvando..."
: "Salvar Alterações"
: "Editar Dados"}
</Button>
</div>
<div className="grid lg:grid-cols-3 gap-6">
<div className="lg:col-span-2 space-y-6">
<Card>
<CardHeader>
<CardTitle className="flex items-center">
<User className="mr-2 h-5 w-5" />
Informações Pessoais
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid md:grid-cols-2 gap-4">
<div>
<Label htmlFor="name">Nome Completo</Label>
<Input
id="name"
value={patientData.name}
onChange={(e) =>
handleInputChange("name", e.target.value)
}
disabled={!isEditing}
/>
</div>
<div>
<Label htmlFor="cpf">CPF</Label>
<Input
id="cpf"
value={patientData.cpf}
onChange={(e) => handleInputChange("cpf", e.target.value)}
disabled={!isEditing}
/>
</div>
</div>
<div>
<Label htmlFor="birthDate">Data de Nascimento</Label>
<Input
id="birthDate"
type="date"
value={patientData.birthDate}
onChange={(e) =>
handleInputChange("birthDate", e.target.value)
}
disabled={!isEditing}
/>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="flex items-center">
<Mail className="mr-2 h-5 w-5" />
Contato e Endereço
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid md:grid-cols-2 gap-4">
<div>
<Label htmlFor="email">Email</Label>
<Input
id="email"
type="email"
value={patientData.email}
disabled
/>
</div>
<div>
<Label htmlFor="phone">Telefone</Label>
<Input
id="phone"
value={patientData.phone}
onChange={(e) =>
handleInputChange("phone", e.target.value)
}
disabled={!isEditing}
/>
</div>
</div>
<div className="grid md:grid-cols-3 gap-4">
<div>
<Label htmlFor="cep">CEP</Label>
<Input
id="cep"
value={patientData.cep}
onChange={(e) => handleInputChange("cep", e.target.value)}
disabled={!isEditing}
/>
</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>
</CardContent>
</Card>
</div>
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle>Resumo do Perfil</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center space-x-3">
<div className="relative">
<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>
<p className="font-medium">{patientData.name}</p>
<p className="text-sm text-gray-500">Paciente</p>
</div>
</div>
<div className="space-y-3 pt-4 border-t">
<div className="flex items-center text-sm">
<Mail className="mr-2 h-4 w-4 text-gray-500" />
<span className="truncate">{patientData.email}</span>
</div>
<div className="flex items-center text-sm">
<Phone className="mr-2 h-4 w-4 text-gray-500" />
<span>{patientData.phone || "Não informado"}</span>
</div>
<div className="flex items-center text-sm">
<Calendar className="mr-2 h-4 w-4 text-gray-500" />
<span>
{patientData.birthDate
? new Date(patientData.birthDate).toLocaleDateString(
"pt-BR",
{ timeZone: "UTC" }
)
: "Não informado"}
</span>
</div>
</div>
</CardContent>
</Card>
</div>
</div>
</div>
</Sidebar>
);
} }

View File

@ -1,11 +1,25 @@
"use client"; "use client";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import {
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 } from "@/components/ui/dialog"; import { Dialog } from "@/components/ui/dialog";
import { Calendar, Clock, MapPin, Phone, User, Trash2, Pencil } from "lucide-react"; import {
Calendar,
Clock,
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";
@ -14,214 +28,298 @@ import { doctorsService } from "@/services/doctorsApi.mjs";
import Sidebar from "@/components/Sidebar"; 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 (
<Sidebar>
<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="space-y-3">
<div className="flex items-center text-sm text-gray-800 font-medium">
<User className="mr-2 h-4 w-4 text-gray-600" />
{appointment.patient.full_name}
</div>
<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 className="flex items-center text-sm text-gray-600">
<Clock className="mr-2 h-4 w-4" />
{new Date(appointment.scheduled_at).toLocaleTimeString(
"pt-BR",
{
hour: "2-digit",
minute: "2-digit",
timeZone: "UTC",
}
)}
</div>
</div>
<div className="space-y-3">
<div className="flex items-center text-sm text-gray-600">
<MapPin className="mr-2 h-4 w-4" />
{appointment.doctor.location || "Local a definir"}
</div>
<div className="flex items-center text-sm text-gray-600">
<Phone className="mr-2 h-4 w-4" />
{appointment.doctor.phone || "N/A"}
</div>
</div>
</div>
<div className="grid gap-6"> <div className="flex gap-2 mt-4 pt-4 border-t">
{isLoading ? <p>Carregando consultas...</p> : appointments.length > 0 ? ( <Button
appointments.map((appointment) => ( variant="outline"
<Card key={appointment.id}> size="sm"
<CardHeader> onClick={() => handleEdit(appointment)}
<div className="flex justify-between items-start"> >
<div> <Pencil className="mr-2 h-4 w-4" />
<CardTitle className="text-lg">{appointment.doctor.full_name}</CardTitle> Editar
<CardDescription>{appointment.doctor.specialty}</CardDescription> </Button>
</div> <Button
{getStatusBadge(appointment.status)} variant="outline"
</div> size="sm"
</CardHeader> className="text-red-600 hover:text-red-700 hover:bg-red-50 bg-transparent"
<CardContent> onClick={() => handleDelete(appointment)}
<div className="grid md:grid-cols-2 gap-4"> >
<div className="space-y-3"> <Trash2 className="mr-2 h-4 w-4" />
<div className="flex items-center text-sm text-gray-800 font-medium"> Deletar
<User className="mr-2 h-4 w-4 text-gray-600" /> </Button>
{appointment.patient.full_name} </div>
</div> </CardContent>
<div className="flex items-center text-sm text-gray-600"> </Card>
<Calendar className="mr-2 h-4 w-4" /> ))
{new Date(appointment.scheduled_at).toLocaleDateString("pt-BR", { timeZone: "UTC" })} ) : (
</div> <p>Nenhuma consulta encontrada.</p>
<div className="flex items-center text-sm text-gray-600"> )}
<Clock className="mr-2 h-4 w-4" /> </div>
{new Date(appointment.scheduled_at).toLocaleTimeString("pt-BR", { hour: '2-digit', minute: '2-digit', timeZone: "UTC" })} </div>
</div>
</div>
<div className="space-y-3">
<div className="flex items-center text-sm text-gray-600">
<MapPin className="mr-2 h-4 w-4" />
{appointment.doctor.location || "Local a definir"}
</div>
<div className="flex items-center text-sm text-gray-600">
<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"> {/* MODAL DE EDIÇÃO */}
<Button variant="outline" size="sm" onClick={() => handleEdit(appointment)}> <Dialog open={editModal} onOpenChange={setEditModal}>
<Pencil className="mr-2 h-4 w-4" /> {/* ... (código do modal de edição) ... */}
Editar </Dialog>
</Button>
<Button variant="outline" size="sm" className="text-red-600 hover:text-red-700 hover:bg-red-50 bg-transparent" onClick={() => handleDelete(appointment)}>
<Trash2 className="mr-2 h-4 w-4" />
Deletar
</Button>
</div>
</CardContent>
</Card>
))
) : (
<p>Nenhuma consulta encontrada.</p>
)}
</div>
</div>
{/* MODAL DE EDIÇÃO */} {/* Modal de Deleção */}
<Dialog open={editModal} onOpenChange={setEditModal}> <Dialog open={deleteModal} onOpenChange={setDeleteModal}>
{/* ... (código do modal de edição) ... */} {/* ... (código do modal de deleção) ... */}
</Dialog> </Dialog>
</Sidebar>
{/* Modal de Deleção */} );
<Dialog open={deleteModal} onOpenChange={setDeleteModal}> }
{/* ... (código do modal de deleção) ... */}
</Dialog>
</Sidebar>
);
}

View File

@ -1,8 +1,11 @@
"use client"; "use client";
import { Card, CardContent, CardDescription, import {
CardHeader, Card,
CardTitle, CardContent,
CardDescription,
CardHeader,
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";
@ -13,289 +16,290 @@ import { appointmentsService } from "@/services/appointmentsApi.mjs";
import Sidebar from "@/components/Sidebar"; 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(
<Sidebar> (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 ? (
</Sidebar> <>
); <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>
);
} }

File diff suppressed because it is too large Load Diff

View File

@ -126,7 +126,7 @@ export default function SidebarUserSection({
className={ className={
sidebarCollapsed sidebarCollapsed
? "w-full bg-white text-black flex justify-center items-center p-2 hover:bg-gray-200" ? "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" : "w-full bg-white text-black hover:bg-gray-200 cursor-pointer"
} }
onClick={handleLogout} onClick={handleLogout}
> >