commit
d699b1ab69
@ -31,7 +31,7 @@ interface EnrichedAppointment {
|
||||
}
|
||||
|
||||
export default function DoctorAppointmentsPage() {
|
||||
const { user, isLoading: isAuthLoading } = useAuthLayout({ requiredRole: 'medico' });
|
||||
const { user, isLoading: isAuthLoading } = useAuthLayout({ requiredRole: "medico" });
|
||||
|
||||
const [allAppointments, setAllAppointments] = useState<EnrichedAppointment[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
@ -111,13 +111,22 @@ export default function DoctorAppointmentsPage() {
|
||||
return format(date, "EEEE, dd 'de' MMMM", { locale: ptBR });
|
||||
};
|
||||
|
||||
const statusPT: Record<string, string> = {
|
||||
confirmed: "Confirmada",
|
||||
completed: "Concluída",
|
||||
cancelled: "Cancelada",
|
||||
requested: "Solicitada",
|
||||
no_show: "oculta",
|
||||
checked_in: "Aguardando",
|
||||
};
|
||||
|
||||
const getStatusVariant = (status: EnrichedAppointment['status']) => {
|
||||
switch (status) {
|
||||
case "confirmed": case "checked_in": return "default";
|
||||
case "completed": return "secondary";
|
||||
case "cancelled": case "no_show": return "destructive";
|
||||
case "requested": return "outline";
|
||||
default: return "outline";
|
||||
case "confirmed": case "checked_in": return "text-foreground bg-blue-100 hover:bg-blue-150";
|
||||
case "completed": return "text-foreground bg-green-100 hover:bg-green-150";
|
||||
case "cancelled": case "no_show": return "text-foreground bg-red-200 hover:bg-red-250";
|
||||
case "requested": return "text-foreground bg-yellow-100 hover:bg-yellow-150";
|
||||
default: return "border-gray bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90";
|
||||
}
|
||||
};
|
||||
|
||||
@ -191,7 +200,7 @@ export default function DoctorAppointmentsPage() {
|
||||
|
||||
{/* Coluna 2: Status e Telefone */}
|
||||
<div className="col-span-1 flex flex-col items-center gap-2">
|
||||
<Badge variant={getStatusVariant(appointment.status)} className="capitalize text-xs">{appointment.status.replace('_', ' ')}</Badge>
|
||||
<Badge variant="outline" className={getStatusVariant(appointment.status)}>{statusPT[appointment.status].replace('_', ' ')}</Badge>
|
||||
<div className="flex items-center text-sm text-muted-foreground">
|
||||
<Phone className="mr-2 h-4 w-4" />
|
||||
{appointment.patientPhone}
|
||||
|
||||
@ -1,19 +1,44 @@
|
||||
"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 { 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 { useEffect, useState } from "react";
|
||||
import { toast } from "@/hooks/use-toast";
|
||||
|
||||
// --- IMPORTS ADICIONADOS PARA A CORREÇÃO ---
|
||||
import { useAuthLayout } from "@/hooks/useAuthLayout";
|
||||
import { patientsService } from "@/services/patientsApi.mjs";
|
||||
// --- FIM DOS IMPORTS ADICIONADOS ---
|
||||
|
||||
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
||||
import { format, parseISO, isAfter, isSameMonth, startOfToday } from "date-fns";
|
||||
import { ptBR } from "date-fns/locale";
|
||||
|
||||
import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
||||
import { exceptionsService } from "@/services/exceptionApi.mjs";
|
||||
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||
import { usersService } from "@/services/usersApi.mjs";
|
||||
import Sidebar from "@/components/Sidebar";
|
||||
import WeeklyScheduleCard from "@/components/ui/WeeklyScheduleCard";
|
||||
|
||||
type Availability = {
|
||||
id: string;
|
||||
@ -61,7 +86,7 @@ type Doctor = {
|
||||
updated_by: string | null;
|
||||
max_days_in_advance: number;
|
||||
rating: number | null;
|
||||
}
|
||||
};
|
||||
|
||||
interface UserPermissions {
|
||||
isAdmin: boolean;
|
||||
@ -106,7 +131,10 @@ interface Exception {
|
||||
}
|
||||
|
||||
export default function PatientDashboard() {
|
||||
const [loggedDoctor, setLoggedDoctor] = useState<Doctor>();
|
||||
// --- USA O HOOK DE AUTENTICAÇÃO PARA PEGAR O USUÁRIO LOGADO ---
|
||||
const { user } = useAuthLayout({ requiredRole: ['medico'] });
|
||||
|
||||
const [loggedDoctor, setLoggedDoctor] = useState<Doctor | null>(null);
|
||||
const [userData, setUserData] = useState<UserData>();
|
||||
const [availability, setAvailability] = useState<any | null>(null);
|
||||
const [exceptions, setExceptions] = useState<Exception[]>([]);
|
||||
@ -116,52 +144,75 @@ export default function PatientDashboard() {
|
||||
const [exceptionToDelete, setExceptionToDelete] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Mapa de tradução
|
||||
const weekdaysPT: Record<string, string> = {
|
||||
sunday: "Domingo",
|
||||
monday: "Segunda",
|
||||
tuesday: "Terça",
|
||||
wednesday: "Quarta",
|
||||
thursday: "Quinta",
|
||||
friday: "Sexta",
|
||||
saturday: "Sábado",
|
||||
};
|
||||
// --- ESTADOS PARA OS CARDS ATUALIZADOS ---
|
||||
const [nextAppointment, setNextAppointment] = useState<EnrichedAppointment | null>(null);
|
||||
const [monthlyCount, setMonthlyCount] = useState<number>(0);
|
||||
|
||||
const weekdaysPT: Record<string, string> = { sunday: "Domingo", monday: "Segunda", tuesday: "Terça", wednesday: "Quarta", thursday: "Quinta", friday: "Sexta", saturday: "Sábado" };
|
||||
|
||||
// ▼▼▼ LÓGICA DE BUSCA CORRIGIDA E ATUALIZADA ▼▼▼
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
if (!user?.id) return; // Aguarda o usuário ser carregado
|
||||
|
||||
try {
|
||||
// Encontra o perfil de médico correspondente ao usuário logado
|
||||
const doctorsList: Doctor[] = await doctorsService.list();
|
||||
const doctor = doctorsList[0];
|
||||
const currentDoctor = doctorsList.find(doc => doc.user_id === user.id);
|
||||
|
||||
// Salva no estado
|
||||
setLoggedDoctor(doctor);
|
||||
if (!currentDoctor) {
|
||||
setError("Perfil de médico não encontrado para este usuário.");
|
||||
return;
|
||||
}
|
||||
setLoggedDoctor(currentDoctor);
|
||||
|
||||
// Busca disponibilidade
|
||||
const availabilityList = await AvailabilityService.list();
|
||||
// Busca todos os dados necessários em paralelo
|
||||
const [appointmentsList, patientsList, availabilityList, exceptionsList] = await Promise.all([
|
||||
appointmentsService.list(),
|
||||
patientsService.list(),
|
||||
AvailabilityService.list(),
|
||||
exceptionsService.list()
|
||||
]);
|
||||
|
||||
// Filtra já com a variável local
|
||||
const filteredAvail = availabilityList.filter(
|
||||
(disp: { doctor_id: string }) => disp.doctor_id === doctor?.id
|
||||
// Mapeia pacientes por ID para consulta rápida
|
||||
const patientsMap = new Map(patientsList.map((p: any) => [p.id, p.full_name]));
|
||||
|
||||
// Filtra e enriquece as consultas APENAS do médico logado
|
||||
const doctorAppointments = appointmentsList
|
||||
.filter((apt: any) => apt.doctor_id === currentDoctor.id)
|
||||
.map((apt: any): EnrichedAppointment => ({
|
||||
...apt,
|
||||
patientName: patientsMap.get(apt.patient_id) || "Paciente Desconhecido",
|
||||
}));
|
||||
|
||||
// 1. Lógica para "Próxima Consulta"
|
||||
const today = startOfToday();
|
||||
const upcomingAppointments = doctorAppointments
|
||||
.filter(apt => isAfter(parseISO(apt.scheduled_at), today))
|
||||
.sort((a, b) => new Date(a.scheduled_at).getTime() - new Date(b.scheduled_at).getTime());
|
||||
setNextAppointment(upcomingAppointments[0] || null);
|
||||
|
||||
// 2. Lógica para "Consultas Este Mês" (apenas ativas)
|
||||
const activeStatuses = ['confirmed', 'requested', 'checked_in'];
|
||||
const currentMonthAppointments = doctorAppointments.filter(apt =>
|
||||
isSameMonth(parseISO(apt.scheduled_at), new Date()) && activeStatuses.includes(apt.status)
|
||||
);
|
||||
setAvailability(filteredAvail);
|
||||
setMonthlyCount(currentMonthAppointments.length);
|
||||
|
||||
// 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);
|
||||
// Busca e filtra o restante dos dados
|
||||
setAvailability(availabilityList.filter((d: any) => d.doctor_id === currentDoctor.id));
|
||||
setExceptions(exceptionsList.filter((e: any) => e.doctor_id === currentDoctor.id));
|
||||
|
||||
} catch (e: any) {
|
||||
alert(`${e?.error} ${e?.message}`);
|
||||
setError(e?.message || "Erro ao buscar dados do dashboard");
|
||||
console.error("Erro no dashboard:", e);
|
||||
}
|
||||
};
|
||||
|
||||
fetchData();
|
||||
}, []);
|
||||
}, [user]); // A busca de dados agora depende do usuário logado
|
||||
// ▲▲▲ FIM DA LÓGICA DE BUSCA ATUALIZADA ▲▲▲
|
||||
|
||||
// Função auxiliar para filtrar o id do doctor correspondente ao user logado
|
||||
function findDoctorById(id: string, doctors: Doctor[]) {
|
||||
return doctors.find((doctor) => doctor.user_id === id);
|
||||
}
|
||||
@ -173,53 +224,25 @@ export default function PatientDashboard() {
|
||||
|
||||
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,
|
||||
});
|
||||
|
||||
if (res && res.error) { throw new Error(res.message || "A API retornou um erro"); }
|
||||
toast({ title: "Sucesso", description: "Exceção deletada com sucesso" });
|
||||
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",
|
||||
});
|
||||
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
|
||||
if (!data) return {};
|
||||
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,
|
||||
});
|
||||
|
||||
if (!acc[weekday]) acc[weekday] = [];
|
||||
acc[weekday].push({ start: start_time, end: end_time });
|
||||
return acc;
|
||||
}, {} as Record<string, { start: string; end: string }[]>);
|
||||
|
||||
return schedule;
|
||||
}
|
||||
|
||||
@ -235,31 +258,50 @@ export default function PatientDashboard() {
|
||||
<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>
|
||||
<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 "PRÓXIMA CONSULTA" CORRIGIDO PARA MOSTRAR NOME DO PACIENTE ▼▼▼ */}
|
||||
<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>
|
||||
{nextAppointment ? (
|
||||
<>
|
||||
<div className="text-2xl font-bold capitalize">
|
||||
{format(parseISO(nextAppointment.scheduled_at), "dd MMM", { locale: ptBR })}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{nextAppointment.patientName} - {format(parseISO(nextAppointment.scheduled_at), "HH:mm")}
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="text-2xl font-bold">Nenhuma</div>
|
||||
<p className="text-xs text-muted-foreground">Sem próximas consultas</p>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
{/* ▲▲▲ FIM DO CARD ATUALIZADO ▲▲▲ */}
|
||||
|
||||
{/* ▼▼▼ CARD "CONSULTAS ESTE MÊS" CORRIGIDO PARA CONTAGEM CORRETA ▼▼▼ */}
|
||||
<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>
|
||||
<div className="text-2xl font-bold">{monthlyCount}</div>
|
||||
<p className="text-xs text-muted-foreground">{monthlyCount === 1 ? '1 agendada' : `${monthlyCount} agendadas`}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{/* ▲▲▲ FIM DO CARD ATUALIZADO ▲▲▲ */}
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
@ -273,6 +315,7 @@ export default function PatientDashboard() {
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* O restante do código permanece o mesmo */}
|
||||
<div className="grid md:grid-cols-2 gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
@ -316,31 +359,7 @@ export default function PatientDashboard() {
|
||||
<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>
|
||||
<CardContent>{loggedDoctor && <WeeklyScheduleCard doctorId={loggedDoctor.id} />}</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-1 gap-6">
|
||||
@ -353,7 +372,6 @@ export default function PatientDashboard() {
|
||||
<CardContent className="space-y-4 grid md:grid-cols-7 gap-2">
|
||||
{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",
|
||||
|
||||
@ -6,7 +6,13 @@ import Link from "next/link";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
|
||||
import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
||||
import { usersService } from "@/services/usersApi.mjs";
|
||||
@ -14,11 +20,31 @@ import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||
|
||||
import { toast } from "@/hooks/use-toast";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card";
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||
import {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
} from "@/components/ui/card";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { Edit, Trash2 } from "lucide-react";
|
||||
import { AvailabilityEditModal } from "@/components/ui/availability-edit-modal";
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import Sidebar from "@/components/Sidebar";
|
||||
|
||||
// ... (Interfaces de tipo omitidas para brevidade, pois não foram alteradas)
|
||||
@ -80,7 +106,7 @@ type Doctor = {
|
||||
updated_by: string | null;
|
||||
max_days_in_advance: number;
|
||||
rating: number | null;
|
||||
}
|
||||
};
|
||||
|
||||
type Availability = {
|
||||
id: string;
|
||||
@ -101,27 +127,38 @@ export default function AvailabilityPage() {
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const router = useRouter();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [schedule, setSchedule] = useState<Record<string, { start: string; end: string }[]>>({});
|
||||
const formatTime = (time?: string | null) => time?.split(":")?.slice(0, 2).join(":") ?? "";
|
||||
const [schedule, setSchedule] = useState<
|
||||
Record<string, { start: string; end: string }[]>
|
||||
>({});
|
||||
const formatTime = (time?: string | null) =>
|
||||
time?.split(":")?.slice(0, 2).join(":") ?? "";
|
||||
const [userData, setUserData] = useState<UserData>();
|
||||
const [availability, setAvailability] = useState<any | null>(null);
|
||||
const [doctorId, setDoctorId] = useState<string>();
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [modalidadeConsulta, setModalidadeConsulta] = useState<string>("");
|
||||
const [selectedAvailability, setSelectedAvailability] = useState<Availability | null>(null);
|
||||
const [selectedAvailability, setSelectedAvailability] =
|
||||
useState<Availability | null>(null);
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
|
||||
const selectAvailability = (schedule: { start: string; end: string;}, day: string) => {
|
||||
const selected = availability.filter((a: Availability) =>
|
||||
const selectAvailability = (
|
||||
schedule: { start: string; end: string },
|
||||
day: string
|
||||
) => {
|
||||
const selected = availability.filter(
|
||||
(a: Availability) =>
|
||||
a.start_time === schedule.start &&
|
||||
a.end_time === schedule.end &&
|
||||
a.weekday === day
|
||||
);
|
||||
setSelectedAvailability(selected[0]);
|
||||
}
|
||||
};
|
||||
|
||||
const handleOpenModal = (schedule: { start: string; end: string;}, day: string) => {
|
||||
selectAvailability(schedule, day)
|
||||
const handleOpenModal = (
|
||||
schedule: { start: string; end: string },
|
||||
day: string
|
||||
) => {
|
||||
selectAvailability(schedule, day);
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
@ -130,7 +167,13 @@ export default function AvailabilityPage() {
|
||||
setIsModalOpen(false);
|
||||
};
|
||||
|
||||
const handleEdit = async (formData:{ start_time: "", end_time: "", slot_minutes: "", appointment_type: "", id:""}) => {
|
||||
const handleEdit = async (formData: {
|
||||
start_time: "";
|
||||
end_time: "";
|
||||
slot_minutes: "";
|
||||
appointment_type: "";
|
||||
id: "";
|
||||
}) => {
|
||||
if (isLoading) return;
|
||||
setIsLoading(true);
|
||||
|
||||
@ -149,7 +192,9 @@ export default function AvailabilityPage() {
|
||||
let message = "disponibilidade editada com sucesso";
|
||||
try {
|
||||
if (!res[0].id) {
|
||||
throw new Error(`${res.error} ${res.message}` || "A API retornou erro");
|
||||
throw new Error(
|
||||
`${res.error} ${res.message}` || "A API retornou erro"
|
||||
);
|
||||
} else {
|
||||
console.log(message);
|
||||
}
|
||||
@ -159,16 +204,17 @@ export default function AvailabilityPage() {
|
||||
title: "Sucesso",
|
||||
description: message,
|
||||
});
|
||||
router.push("#")
|
||||
router.push("#");
|
||||
} catch (err: any) {
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: err?.message || "Não foi possível editar a disponibilidade",
|
||||
description:
|
||||
err?.message || "Não foi possível editar a disponibilidade",
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
handleCloseModal();
|
||||
fetchData()
|
||||
fetchData();
|
||||
}
|
||||
};
|
||||
|
||||
@ -212,7 +258,6 @@ export default function AvailabilityPage() {
|
||||
return doctors.find((doctor) => doctor.user_id === id);
|
||||
}
|
||||
|
||||
|
||||
function formatAvailability(data: Availability[]) {
|
||||
// Agrupar os horários por dia da semana
|
||||
const schedule = data.reduce((acc: any, item) => {
|
||||
@ -267,7 +312,9 @@ export default function AvailabilityPage() {
|
||||
let message = "disponibilidade cadastrada com sucesso";
|
||||
try {
|
||||
if (!res[0].id) {
|
||||
throw new Error(`${res.error} ${res.message}` || "A API retornou erro");
|
||||
throw new Error(
|
||||
`${res.error} ${res.message}` || "A API retornou erro"
|
||||
);
|
||||
} else {
|
||||
console.log(message);
|
||||
}
|
||||
@ -284,12 +331,16 @@ export default function AvailabilityPage() {
|
||||
description: err?.message || "Não foi possível criar a disponibilidade",
|
||||
});
|
||||
} finally {
|
||||
fetchData()
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const openDeleteDialog = (schedule: { start: string; end: string;}, day: string) => {
|
||||
selectAvailability(schedule, day)
|
||||
const openDeleteDialog = (
|
||||
schedule: { start: string; end: string },
|
||||
day: string
|
||||
) => {
|
||||
selectAvailability(schedule, day);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
@ -318,6 +369,7 @@ export default function AvailabilityPage() {
|
||||
description: e?.message || "Não foi possível deletar a disponibilidade",
|
||||
});
|
||||
}
|
||||
fetchData()
|
||||
setDeleteDialogOpen(false);
|
||||
setSelectedAvailability(null);
|
||||
};
|
||||
@ -327,8 +379,12 @@ export default function AvailabilityPage() {
|
||||
<div className="space-y-6 flex-1 overflow-y-auto p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Definir Disponibilidade</h1>
|
||||
<p className="text-gray-600">Defina sua disponibilidade para consultas </p>
|
||||
<h1 className="text-2xl font-bold text-gray-900">
|
||||
Definir Disponibilidade
|
||||
</h1>
|
||||
<p className="text-gray-600">
|
||||
Defina sua disponibilidade para consultas{" "}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -339,35 +395,72 @@ export default function AvailabilityPage() {
|
||||
<div className="space-y-6">
|
||||
{/* **AJUSTE DE RESPONSIVIDADE: DIAS DA SEMANA** */}
|
||||
<div>
|
||||
<Label className="text-sm font-medium text-gray-700">Dia Da Semana</Label>
|
||||
<Label className="text-sm font-medium text-gray-700">
|
||||
Dia Da Semana
|
||||
</Label>
|
||||
{/* O antigo 'flex gap-4 mt-2 flex-nowrap' foi substituído por um grid responsivo: */}
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-7 gap-x-4 gap-y-2 mt-2">
|
||||
<label className="flex items-center gap-1">
|
||||
<input type="radio" name="weekday" value="monday" className="text-blue-600" />
|
||||
<input
|
||||
type="radio"
|
||||
name="weekday"
|
||||
value="monday"
|
||||
className="text-blue-600"
|
||||
/>
|
||||
<span className="whitespace-nowrap text-sm">Segunda</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1">
|
||||
<input type="radio" name="weekday" value="tuesday" className="text-blue-600" />
|
||||
<input
|
||||
type="radio"
|
||||
name="weekday"
|
||||
value="tuesday"
|
||||
className="text-blue-600"
|
||||
/>
|
||||
<span className="whitespace-nowrap text-sm">Terça</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1">
|
||||
<input type="radio" name="weekday" value="wednesday" className="text-blue-600" />
|
||||
<input
|
||||
type="radio"
|
||||
name="weekday"
|
||||
value="wednesday"
|
||||
className="text-blue-600"
|
||||
/>
|
||||
<span className="whitespace-nowrap text-sm">Quarta</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1">
|
||||
<input type="radio" name="weekday" value="thursday" className="text-blue-600" />
|
||||
<input
|
||||
type="radio"
|
||||
name="weekday"
|
||||
value="thursday"
|
||||
className="text-blue-600"
|
||||
/>
|
||||
<span className="whitespace-nowrap text-sm">Quinta</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1">
|
||||
<input type="radio" name="weekday" value="friday" className="text-blue-600" />
|
||||
<input
|
||||
type="radio"
|
||||
name="weekday"
|
||||
value="friday"
|
||||
className="text-blue-600"
|
||||
/>
|
||||
<span className="whitespace-nowrap text-sm">Sexta</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1">
|
||||
<input type="radio" name="weekday" value="saturday" className="text-blue-600" />
|
||||
<input
|
||||
type="radio"
|
||||
name="weekday"
|
||||
value="saturday"
|
||||
className="text-blue-600"
|
||||
/>
|
||||
<span className="whitespace-nowrap text-sm">Sábado</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1">
|
||||
<input type="radio" name="weekday" value="sunday" className="text-blue-600" />
|
||||
<input
|
||||
type="radio"
|
||||
name="weekday"
|
||||
value="sunday"
|
||||
className="text-blue-600"
|
||||
/>
|
||||
<span className="whitespace-nowrap text-sm">Domingo</span>
|
||||
</label>
|
||||
</div>
|
||||
@ -377,31 +470,64 @@ export default function AvailabilityPage() {
|
||||
{/* Ajustado para 1 coluna em móvel, 2 em tablet e 5 em desktop (mantendo o que já existia com ajustes) */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-6">
|
||||
<div>
|
||||
<Label htmlFor="horarioEntrada" className="text-sm font-medium text-gray-700">
|
||||
<Label
|
||||
htmlFor="horarioEntrada"
|
||||
className="text-sm font-medium text-gray-700"
|
||||
>
|
||||
Horario De Entrada
|
||||
</Label>
|
||||
<Input type="time" id="horarioEntrada" name="horarioEntrada" required className="mt-1" />
|
||||
<Input
|
||||
type="time"
|
||||
id="horarioEntrada"
|
||||
name="horarioEntrada"
|
||||
required
|
||||
className="mt-1"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="horarioSaida" className="text-sm font-medium text-gray-700">
|
||||
<Label
|
||||
htmlFor="horarioSaida"
|
||||
className="text-sm font-medium text-gray-700"
|
||||
>
|
||||
Horario De Saida
|
||||
</Label>
|
||||
<Input type="time" id="horarioSaida" name="horarioSaida" required className="mt-1" />
|
||||
<Input
|
||||
type="time"
|
||||
id="horarioSaida"
|
||||
name="horarioSaida"
|
||||
required
|
||||
className="mt-1"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="duracaoConsulta" className="text-sm font-medium text-gray-700">
|
||||
<Label
|
||||
htmlFor="duracaoConsulta"
|
||||
className="text-sm font-medium text-gray-700"
|
||||
>
|
||||
Duração Da Consulta (min)
|
||||
</Label>
|
||||
<Input type="number" id="duracaoConsulta" name="duracaoConsulta" required className="mt-1" />
|
||||
<Input
|
||||
type="number"
|
||||
id="duracaoConsulta"
|
||||
name="duracaoConsulta"
|
||||
required
|
||||
className="mt-1"
|
||||
/>
|
||||
</div>
|
||||
{/* O Select de modalidade fica fora deste grid para ocupar uma linha inteira em telas menores, como no original, garantindo clareza */}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="modalidadeConsulta" className="text-sm font-medium text-gray-700">
|
||||
<Label
|
||||
htmlFor="modalidadeConsulta"
|
||||
className="text-sm font-medium text-gray-700"
|
||||
>
|
||||
Modalidade De Consulta
|
||||
</Label>
|
||||
<Select onValueChange={(value) => setModalidadeConsulta(value)} value={modalidadeConsulta}>
|
||||
<Select
|
||||
onValueChange={(value) => setModalidadeConsulta(value)}
|
||||
value={modalidadeConsulta}
|
||||
>
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
@ -453,7 +579,7 @@ export default function AvailabilityPage() {
|
||||
<div key={i}>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<p className="text-sm text-gray-600 cursor-pointer p-1 rounded hover:text-accent-foreground hover:bg-gray-200 transition-colors duration-150">
|
||||
<p className="text-sm text-gray-600 cursor-pointer rounded hover:text-accent-foreground hover:bg-gray-200 transition-colors duration-150">
|
||||
{formatTime(t.start)} - {formatTime(t.end)}
|
||||
</p>
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
@ -144,10 +144,6 @@ export default function EditarLaudoPage() {
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="order_number">Nº do Pedido</Label>
|
||||
<Input id="order_number" value={formData.order_number || ''} onChange={handleInputChange} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="exam">Exame</Label>
|
||||
<Input id="exam" value={formData.exam || ''} onChange={handleInputChange} />
|
||||
|
||||
@ -1,4 +1,3 @@
|
||||
|
||||
"use client";
|
||||
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
@ -106,10 +105,6 @@ export default function NovoLaudoPage() {
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="order_number">Nº do Pedido</Label>
|
||||
<Input id="order_number" value={formData.order_number} onChange={handleInputChange} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="exam">Exame</Label>
|
||||
<Input id="exam" value={formData.exam} onChange={handleInputChange} />
|
||||
|
||||
@ -2,11 +2,23 @@
|
||||
|
||||
import { useEffect, useState, useCallback } from "react";
|
||||
import Link from "next/link";
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||
import { Eye, Edit, Calendar, Trash2, Loader2 } from "lucide-react";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { Eye, Edit, Calendar, Trash2, Loader2, MoreVertical, Filter } from "lucide-react";
|
||||
import { api } from "@/services/api.mjs";
|
||||
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 { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import Sidebar from "@/components/Sidebar";
|
||||
|
||||
@ -29,6 +41,9 @@ interface Paciente {
|
||||
complement?: string;
|
||||
neighborhood?: string;
|
||||
cep?: string;
|
||||
// NOVOS CAMPOS PARA O FILTRO
|
||||
convenio?: string;
|
||||
vip?: string;
|
||||
}
|
||||
|
||||
export default function PacientesPage() {
|
||||
@ -38,19 +53,44 @@ export default function PacientesPage() {
|
||||
const [selectedPatient, setSelectedPatient] = useState<Paciente | null>(null);
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
|
||||
// --- Lógica de Paginação INÍCIO ---
|
||||
const [itemsPerPage, setItemsPerPage] = useState(5);
|
||||
// --- ESTADOS DOS FILTROS ---
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
const [convenioFilter, setConvenioFilter] = useState("todos");
|
||||
const [vipFilter, setVipFilter] = useState("todos");
|
||||
|
||||
// --- Lógica de Filtragem ---
|
||||
const filteredPacientes = pacientes.filter((p) => {
|
||||
// 1. Filtro de Texto (Nome ou Telefone)
|
||||
const searchLower = searchTerm.toLowerCase();
|
||||
const matchesSearch = p.nome?.toLowerCase().includes(searchLower) || p.telefone?.includes(searchLower);
|
||||
|
||||
// 2. Filtro de Convênio
|
||||
// Se for "todos", passa. Se não, verifica se o convênio do paciente é igual ao selecionado.
|
||||
const matchesConvenio = convenioFilter === "todos" || (p.convenio?.toLowerCase() === convenioFilter);
|
||||
|
||||
// 3. Filtro VIP
|
||||
// Se for "todos", passa. Se não, verifica se o status VIP é igual ao selecionado.
|
||||
const matchesVip = vipFilter === "todos" || (p.vip?.toLowerCase() === vipFilter);
|
||||
|
||||
return matchesSearch && matchesConvenio && matchesVip;
|
||||
});
|
||||
|
||||
// --- Lógica de Paginação ---
|
||||
const [itemsPerPage, setItemsPerPage] = useState(10);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
|
||||
const totalPages = Math.ceil(pacientes.length / itemsPerPage);
|
||||
// Resetar página quando qualquer filtro mudar
|
||||
useEffect(() => {
|
||||
setCurrentPage(1);
|
||||
}, [searchTerm, convenioFilter, vipFilter, itemsPerPage]);
|
||||
|
||||
const totalPages = Math.ceil(filteredPacientes.length / itemsPerPage);
|
||||
const indexOfLastItem = currentPage * itemsPerPage;
|
||||
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
||||
const currentItems = pacientes.slice(indexOfFirstItem, indexOfLastItem);
|
||||
const currentItems = filteredPacientes.slice(indexOfFirstItem, indexOfLastItem);
|
||||
|
||||
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
|
||||
|
||||
// Funções de Navegação
|
||||
const goToPrevPage = () => {
|
||||
setCurrentPage((prev) => Math.max(1, prev - 1));
|
||||
};
|
||||
@ -59,7 +99,6 @@ export default function PacientesPage() {
|
||||
setCurrentPage((prev) => Math.min(totalPages, prev + 1));
|
||||
};
|
||||
|
||||
// Lógica para gerar os números das páginas visíveis (máximo de 5)
|
||||
const getVisiblePageNumbers = (totalPages: number, currentPage: number) => {
|
||||
const pages: number[] = [];
|
||||
const maxVisiblePages = 5;
|
||||
@ -84,13 +123,10 @@ export default function PacientesPage() {
|
||||
|
||||
const visiblePageNumbers = getVisiblePageNumbers(totalPages, currentPage);
|
||||
|
||||
// Lógica para mudar itens por página, resetando para a página 1
|
||||
const handleItemsPerPageChange = (value: string) => {
|
||||
setItemsPerPage(Number(value));
|
||||
setCurrentPage(1);
|
||||
};
|
||||
// --- Lógica de Paginação FIM ---
|
||||
|
||||
|
||||
const handleOpenModal = (patient: Paciente) => {
|
||||
setSelectedPatient(patient);
|
||||
@ -108,7 +144,7 @@ export default function PacientesPage() {
|
||||
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
|
||||
return dateString;
|
||||
}
|
||||
};
|
||||
|
||||
@ -130,7 +166,7 @@ export default function PacientesPage() {
|
||||
cidade: p.city ?? "N/A",
|
||||
estado: p.state ?? "N/A",
|
||||
ultimoAtendimento: formatDate(p.created_at),
|
||||
proximoAtendimento: "N/A", // Necessita de lógica de agendamento real
|
||||
proximoAtendimento: "N/A",
|
||||
email: p.email ?? "N/A",
|
||||
birth_date: p.birth_date ?? "N/A",
|
||||
cpf: p.cpf ?? "N/A",
|
||||
@ -142,10 +178,14 @@ export default function PacientesPage() {
|
||||
complement: p.complement ?? "N/A",
|
||||
neighborhood: p.neighborhood ?? "N/A",
|
||||
cep: p.cep ?? "N/A",
|
||||
|
||||
// ⚠️ ATENÇÃO: Verifique o nome real desses campos na sua API
|
||||
// Se a API não retorna, estou colocando valores padrão para teste
|
||||
convenio: p.insurance_plan || p.convenio || "Unimed", // Exemplo: mapeie o campo correto
|
||||
vip: p.is_vip ? "Sim" : "Não", // Exemplo: se for booleano converta para string
|
||||
}));
|
||||
|
||||
setPacientes(mapped);
|
||||
setCurrentPage(1); // Resetar a página ao carregar novos dados
|
||||
} catch (e: any) {
|
||||
console.error("Erro ao carregar pacientes:", e);
|
||||
setError(e?.message || "Erro ao carregar pacientes");
|
||||
@ -161,23 +201,73 @@ export default function PacientesPage() {
|
||||
return (
|
||||
<Sidebar>
|
||||
<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 className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
|
||||
<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">
|
||||
</div>
|
||||
|
||||
{/* --- BARRA DE PESQUISA COM FILTROS ATIVOS --- */}
|
||||
<div className="flex flex-col md:flex-row gap-4 items-center p-2 border border-border rounded-lg bg-card shadow-sm">
|
||||
|
||||
{/* Input de Busca */}
|
||||
<div className="flex items-center gap-3 flex-1 w-full px-2">
|
||||
<Filter className="w-5 h-5 text-muted-foreground flex-shrink-0" />
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Buscar por nome ou telefone..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="border-0 focus-visible:ring-0 shadow-none bg-transparent px-0 h-auto text-base placeholder:text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Filtros e Paginação */}
|
||||
<div className="flex flex-wrap items-center gap-4 w-full md:w-auto px-2 border-t md:border-t-0 md:border-l border-border pt-2 md:pt-0 justify-end">
|
||||
|
||||
{/* FILTRO CONVÊNIO */}
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium whitespace-nowrap text-muted-foreground hidden lg:inline">Convênio</span>
|
||||
<Select value={convenioFilter} onValueChange={setConvenioFilter}>
|
||||
<SelectTrigger className="w-[100px] h-8 border-border bg-transparent focus:ring-0">
|
||||
<SelectValue placeholder="Todos" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="todos">Todos</SelectItem>
|
||||
{/* Certifique-se que o 'value' aqui seja minúsculo para bater com a lógica do filtro */}
|
||||
<SelectItem value="unimed">Unimed</SelectItem>
|
||||
<SelectItem value="bradesco">Bradesco</SelectItem>
|
||||
<SelectItem value="particular">Particular</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* FILTRO VIP */}
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium whitespace-nowrap text-muted-foreground hidden lg:inline">VIP</span>
|
||||
<Select value={vipFilter} onValueChange={setVipFilter}>
|
||||
<SelectTrigger className="w-[90px] h-8 border-border bg-transparent focus:ring-0">
|
||||
<SelectValue placeholder="Todos" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="todos">Todos</SelectItem>
|
||||
<SelectItem value="sim">Sim</SelectItem>
|
||||
<SelectItem value="não">Não</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* PAGINAÇÃO */}
|
||||
<div className="flex items-center gap-2 pl-2 md:border-l border-border">
|
||||
<Select
|
||||
onValueChange={handleItemsPerPageChange}
|
||||
defaultValue={String(itemsPerPage)}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-[140px]">
|
||||
<SelectValue placeholder="Itens por pág." />
|
||||
<SelectTrigger className="w-[130px] h-8 border-border bg-transparent focus:ring-0">
|
||||
<SelectValue placeholder="Paginação" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="5">5 por página</SelectItem>
|
||||
@ -185,37 +275,23 @@ export default function PacientesPage() {
|
||||
<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-green-600 hover:bg-green-700 w-full sm:w-auto">
|
||||
Novo Paciente
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
{/* Tabela de Dados */}
|
||||
<div className="bg-card rounded-lg border border-border overflow-hidden shadow-md">
|
||||
{/* Tabela para Telas Médias e Grandes */}
|
||||
<div className="overflow-x-auto hidden md:block"> {/* Esconde em telas pequenas */}
|
||||
<div className="overflow-x-auto hidden md:block">
|
||||
<table className="min-w-[600px] w-full">
|
||||
<thead className="bg-muted border-b border-border">
|
||||
<tr>
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground">Nome</th>
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground">
|
||||
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">Telefone</th>
|
||||
{/* Coluna Convênio visível para teste */}
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden lg:table-cell">Convênio</th>
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden lg:table-cell">VIP</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">Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@ -231,40 +307,27 @@ export default function PacientesPage() {
|
||||
<tr>
|
||||
<td colSpan={7} className="p-6 text-red-600 text-center">{`Erro: ${error}`}</td>
|
||||
</tr>
|
||||
) : pacientes.length === 0 ? (
|
||||
) : filteredPacientes.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={7} className="p-8 text-center text-muted-foreground">
|
||||
Nenhum paciente encontrado
|
||||
Nenhum paciente encontrado com esses filtros.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
currentItems.map((p) => (
|
||||
<tr
|
||||
key={p.id}
|
||||
className="border-b border-border hover:bg-accent/40 transition-colors"
|
||||
>
|
||||
<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 text-muted-foreground">{p.telefone}</td>
|
||||
<td className="p-3 sm:p-4 text-muted-foreground hidden lg:table-cell">{p.convenio}</td>
|
||||
<td className="p-3 sm:p-4 text-muted-foreground hidden lg:table-cell">{p.vip}</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">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="text-primary hover:underline text-sm sm:text-base">
|
||||
Ações
|
||||
</button>
|
||||
<Button variant="ghost" className="h-8 w-8 p-0">
|
||||
<span className="sr-only">Abrir menu</span>
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => handleOpenModal(p)}>
|
||||
@ -272,26 +335,11 @@ export default function PacientesPage() {
|
||||
Ver detalhes
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/doctor/pacientes/${p.id}/laudos`}>
|
||||
<Link href={`/doctor/medicos/${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>
|
||||
@ -302,29 +350,26 @@ export default function PacientesPage() {
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Layout em Cards/Lista para Telas Pequenas */}
|
||||
<div className="md:hidden divide-y divide-border"> {/* Visível apenas em telas pequenas */}
|
||||
{/* Cards para Mobile */}
|
||||
<div className="md:hidden divide-y divide-border">
|
||||
{loading ? (
|
||||
<div className="p-6 text-muted-foreground text-center">
|
||||
<Loader2 className="w-6 h-6 animate-spin mx-auto text-primary" />
|
||||
Carregando pacientes...
|
||||
Carregando...
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="p-6 text-red-600 text-center">{`Erro: ${error}`}</div>
|
||||
) : pacientes.length === 0 ? (
|
||||
) : filteredPacientes.length === 0 ? (
|
||||
<div className="p-8 text-center text-muted-foreground">
|
||||
Nenhum paciente encontrado
|
||||
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 */}
|
||||
<div className="flex-1 min-w-0 pr-4">
|
||||
<div className="text-base font-semibold text-foreground break-words">
|
||||
{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 className="text-sm text-muted-foreground">
|
||||
{p.telefone} | {p.convenio} | VIP: {p.vip}
|
||||
</div>
|
||||
</div>
|
||||
<div className="ml-4 flex-shrink-0">
|
||||
@ -345,21 +390,6 @@ export default function PacientesPage() {
|
||||
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>
|
||||
@ -368,12 +398,9 @@ export default function PacientesPage() {
|
||||
)}
|
||||
</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}
|
||||
@ -382,14 +409,13 @@ export default function PacientesPage() {
|
||||
{"< 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-blue-600 text-primary-foreground shadow-md border-blue-600"
|
||||
: "bg-secondary text-secondary-foreground hover:bg-secondary/80"
|
||||
}`}
|
||||
>
|
||||
@ -397,7 +423,6 @@ export default function PacientesPage() {
|
||||
</button>
|
||||
))}
|
||||
|
||||
{/* Botão Próximo */}
|
||||
<button
|
||||
onClick={goToNextPage}
|
||||
disabled={currentPage === totalPages}
|
||||
@ -405,7 +430,6 @@ export default function PacientesPage() {
|
||||
>
|
||||
{"Próximo >"}
|
||||
</button>
|
||||
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@ -1,8 +1,6 @@
|
||||
@import 'tailwindcss';
|
||||
@import 'tw-animate-css';
|
||||
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
:root {
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.145 0 0);
|
||||
|
||||
@ -138,7 +138,7 @@ export default function LoginPage() {
|
||||
Não tem uma conta de paciente?{" "}
|
||||
</span>
|
||||
<Link href="/patient/register">
|
||||
<span className="font-semibold text-primary hover:underline cursor-pointer">
|
||||
<span className="font-semibold text-blue-600 hover:text-blue-700 hover:underline cursor-pointer">
|
||||
Crie uma agora
|
||||
</span>
|
||||
</Link>
|
||||
@ -232,18 +232,21 @@ export default function LoginPage() {
|
||||
|
||||
{/* Botões */}
|
||||
<div className="flex gap-3 pt-2">
|
||||
{/* Botão Cancelar – Azul contornado */}
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={closeModal}
|
||||
disabled={isLoading}
|
||||
className="flex-1"
|
||||
className="flex-1 bg-blue-600 hover:bg-blue-700 text-white"
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
|
||||
{/* Botão Resetar Senha – Azul sólido */}
|
||||
<Button
|
||||
onClick={handleResetPassword}
|
||||
disabled={isLoading}
|
||||
className="flex-1"
|
||||
className="flex-1 bg-blue-600 hover:bg-blue-700 text-white"
|
||||
>
|
||||
{isLoading ? "Enviando..." : "Resetar Senha"}
|
||||
</Button>
|
||||
|
||||
@ -1,13 +1,20 @@
|
||||
"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 { Calendar, Clock, Plus, User } from "lucide-react";
|
||||
import { Clock, Plus, User } from "lucide-react"; // Removi 'Calendar' que não estava sendo usado
|
||||
import Link from "next/link";
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { usersService } from "services/usersApi.mjs";
|
||||
import { doctorsService } from "services/doctorsApi.mjs";
|
||||
import Sidebar from "@/components/Sidebar";
|
||||
import { api } from "services/api.mjs"; // <-- ADICIONEI ESTE IMPORT
|
||||
|
||||
export default function ManagerDashboard() {
|
||||
// 🔹 Estados para usuários
|
||||
@ -18,16 +25,44 @@ export default function ManagerDashboard() {
|
||||
const [doctors, setDoctors] = useState<any[]>([]);
|
||||
const [loadingDoctors, setLoadingDoctors] = useState(true);
|
||||
|
||||
// 🔹 Buscar primeiro usuário
|
||||
// 🔹 Buscar primeiro usuário (LÓGICA ATUALIZADA)
|
||||
useEffect(() => {
|
||||
async function fetchFirstUser() {
|
||||
setLoadingUser(true); // Garante que o estado de loading inicie como true
|
||||
try {
|
||||
const data = await usersService.list_roles();
|
||||
if (Array.isArray(data) && data.length > 0) {
|
||||
setFirstUser(data[0]);
|
||||
// 1. Busca a lista de usuários com seus cargos (roles)
|
||||
const rolesData = await usersService.list_roles();
|
||||
|
||||
// 2. Verifica se a lista não está vazia
|
||||
if (Array.isArray(rolesData) && rolesData.length > 0) {
|
||||
const firstUserRole = rolesData[0];
|
||||
const firstUserId = firstUserRole.user_id;
|
||||
|
||||
if (!firstUserId) {
|
||||
throw new Error("O primeiro usuário da lista não possui um ID válido.");
|
||||
}
|
||||
|
||||
// 3. Usa o ID para buscar o perfil (com nome e email) do usuário
|
||||
const profileData = await api.get(
|
||||
`/rest/v1/profiles?select=full_name,email&id=eq.${firstUserId}`
|
||||
);
|
||||
|
||||
// 4. Verifica se o perfil foi encontrado
|
||||
if (Array.isArray(profileData) && profileData.length > 0) {
|
||||
const userProfile = profileData[0];
|
||||
// 5. Combina os dados do cargo e do perfil e atualiza o estado
|
||||
setFirstUser({
|
||||
...firstUserRole,
|
||||
...userProfile
|
||||
});
|
||||
} else {
|
||||
// Se não encontrar o perfil, exibe os dados que temos
|
||||
setFirstUser(firstUserRole);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Erro ao carregar usuário:", error);
|
||||
setFirstUser(null); // Limpa o usuário em caso de erro
|
||||
} finally {
|
||||
setLoadingUser(false);
|
||||
}
|
||||
@ -60,41 +95,41 @@ export default function ManagerDashboard() {
|
||||
{/* 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>
|
||||
<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>
|
||||
<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 className="text-gray-500 text-sm">
|
||||
Carregando usuário...
|
||||
</div>
|
||||
) : firstUser ? (
|
||||
<>
|
||||
<div className="text-2xl font-bold">{firstUser.full_name || "Sem nome"}</div>
|
||||
<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>
|
||||
<div className="text-sm text-gray-500">
|
||||
Nenhum usuário encontrado
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
@ -118,29 +153,40 @@ export default function ManagerDashboard() {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Ações Rápidas</CardTitle>
|
||||
<CardDescription>Acesse rapidamente as principais funcionalidades</CardDescription>
|
||||
<CardDescription>
|
||||
Acesse rapidamente as principais funcionalidades
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<Link href="/manager/home">
|
||||
<Button className="w-full justify-start">
|
||||
<User className="mr-2 h-4 w-4" />
|
||||
<Button className="w-full justify-start bg-blue-600 text-white hover:bg-blue-700">
|
||||
<User className="mr-2 h-4 w-4 text-white" />
|
||||
Gestão de Médicos
|
||||
</Button>
|
||||
</Link>
|
||||
<Link href="/manager/usuario">
|
||||
<Button variant="outline" className="w-full justify-start bg-transparent">
|
||||
<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">
|
||||
<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">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full justify-start bg-transparent"
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Criar novo Usuário
|
||||
</Button>
|
||||
@ -152,13 +198,17 @@ export default function ManagerDashboard() {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Gestão de Médicos</CardTitle>
|
||||
<CardDescription>Médicos cadastrados recentemente</CardDescription>
|
||||
<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>
|
||||
<p className="text-sm text-gray-500">
|
||||
Nenhum médico cadastrado.
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{doctors.map((doc, index) => (
|
||||
@ -167,7 +217,9 @@ export default function ManagerDashboard() {
|
||||
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="font-medium">
|
||||
{doc.full_name || "Sem nome"}
|
||||
</p>
|
||||
<p className="text-sm text-gray-600">
|
||||
{doc.specialty || "Sem especialidade"}
|
||||
</p>
|
||||
|
||||
185
app/manager/disponibilidade/page.tsx
Normal file
185
app/manager/disponibilidade/page.tsx
Normal file
@ -0,0 +1,185 @@
|
||||
"use client";
|
||||
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import Sidebar from "@/components/Sidebar";
|
||||
import WeeklyScheduleCard from "@/components/ui/WeeklyScheduleCard";
|
||||
|
||||
import { useEffect, useState, useMemo } from "react";
|
||||
|
||||
import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
||||
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Filter } from "lucide-react";
|
||||
|
||||
type Doctor = {
|
||||
id: string;
|
||||
full_name: string;
|
||||
specialty: string;
|
||||
active: boolean;
|
||||
};
|
||||
|
||||
type Availability = {
|
||||
id: string;
|
||||
doctor_id: string;
|
||||
weekday: string;
|
||||
start_time: string;
|
||||
end_time: string;
|
||||
};
|
||||
|
||||
export default function AllAvailabilities() {
|
||||
const [availabilities, setAvailabilities] = useState<Availability[] | null>(null);
|
||||
const [doctors, setDoctors] = useState<Doctor[] | null>(null);
|
||||
|
||||
// 🔎 Filtros
|
||||
const [search, setSearch] = useState("");
|
||||
const [specialty, setSpecialty] = useState("all");
|
||||
|
||||
// 🔄 Paginação
|
||||
const ITEMS_PER_PAGE = 6;
|
||||
const [page, setPage] = useState(1);
|
||||
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
const doctorsList = await doctorsService.list();
|
||||
setDoctors(doctorsList);
|
||||
|
||||
const availabilityList = await AvailabilityService.list();
|
||||
setAvailabilities(availabilityList);
|
||||
} catch (e: any) {
|
||||
alert(`${e?.error} ${e?.message}`);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
// 🎯 Obter todas as especialidades existentes
|
||||
const specialties = useMemo(() => {
|
||||
if (!doctors) return [];
|
||||
const unique = Array.from(new Set(doctors.map((d) => d.specialty)));
|
||||
return unique;
|
||||
}, [doctors]);
|
||||
|
||||
// 🔍 Filtrar médicos por especialidade + nome
|
||||
const filteredDoctors = useMemo(() => {
|
||||
if (!doctors) return [];
|
||||
|
||||
return doctors.filter((doctor) => (specialty === "all" ? true : doctor.specialty === specialty)).filter((doctor) => doctor.full_name.toLowerCase().includes(search.toLowerCase()));
|
||||
}, [doctors, search, specialty]);
|
||||
|
||||
// 📄 Paginação (após filtros!)
|
||||
const totalPages = Math.ceil(filteredDoctors.length / ITEMS_PER_PAGE);
|
||||
const paginatedDoctors = filteredDoctors.slice((page - 1) * ITEMS_PER_PAGE, page * ITEMS_PER_PAGE);
|
||||
|
||||
const goNext = () => setPage((p) => Math.min(p + 1, totalPages));
|
||||
const goPrev = () => setPage((p) => Math.max(p - 1, 1));
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="p-6 text-gray-500">Carregando dados...</div>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
|
||||
if (!doctors || !availabilities) {
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="p-6 text-red-600 font-medium">Não foi possível carregar médicos ou disponibilidades.</div>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">Disponibilidade dos Médicos</h1>
|
||||
<p className="text-gray-600">Visualize a agenda semanal individual de cada médico.</p>
|
||||
</div>
|
||||
<Card>
|
||||
<CardContent>
|
||||
{/* 🔎 Filtros */}
|
||||
<div className="flex flex-col md:flex-row gap-4 items-center">
|
||||
{/* Filtro por nome */}
|
||||
<Filter className="w-4 h-4 mr-2" />
|
||||
<Input
|
||||
placeholder="Buscar por nome do médico..."
|
||||
value={search}
|
||||
onChange={(e) => {
|
||||
setSearch(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
className="w-full md:w-1/3"
|
||||
/>
|
||||
|
||||
{/* Filtro por especialidade */}
|
||||
<Select
|
||||
onValueChange={(value) => {
|
||||
setSpecialty(value);
|
||||
setPage(1);
|
||||
}}
|
||||
defaultValue="all"
|
||||
>
|
||||
<SelectTrigger className="w-full md:w-64">
|
||||
<SelectValue placeholder="Especialidade" />
|
||||
</SelectTrigger>
|
||||
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todas as especialidades</SelectItem>
|
||||
{specialties.map((sp) => (
|
||||
<SelectItem key={sp} value={sp}>
|
||||
{sp}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{/* GRID de cards */}
|
||||
<div className="grid md:grid-cols-1 lg:grid-cols-1 gap-6">
|
||||
{paginatedDoctors.map((doctor) => {
|
||||
const doctorAvailabilities = availabilities.filter((a) => a.doctor_id === doctor.id);
|
||||
|
||||
return (
|
||||
<Card key={doctor.id}>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-xl font-semibold">{doctor.full_name}</CardTitle>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent>
|
||||
<WeeklyScheduleCard doctorId={doctor.id} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* 📄 Paginação */}
|
||||
{totalPages > 1 && (
|
||||
<div className="flex justify-center items-center gap-4 pt-4">
|
||||
<Button variant="outline" onClick={goPrev} disabled={page === 1}>
|
||||
Anterior
|
||||
</Button>
|
||||
|
||||
<span className="text-gray-700 font-medium">
|
||||
Página {page} de {totalPages}
|
||||
</span>
|
||||
|
||||
<Button variant="outline" onClick={goNext} disabled={page === totalPages}>
|
||||
Próxima
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
@ -225,7 +225,7 @@ export default function EditarMedicoPage() {
|
||||
Editar Médico: <span className="text-green-600">{formData.nomeCompleto}</span>
|
||||
</h1>
|
||||
<p className="text-sm text-gray-500">
|
||||
Atualize as informações do médico (ID: {id}).
|
||||
Atualize as informações do médico
|
||||
</p>
|
||||
</div>
|
||||
<Link href="/manager/home">
|
||||
|
||||
@ -1,17 +1,20 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState, useCallback, useMemo } from "react"
|
||||
import Link from "next/link"
|
||||
import React, { useEffect, useState, useCallback, useMemo } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { Edit, Trash2, Eye, Calendar, Filter, Loader2 } from "lucide-react"
|
||||
import { Edit, Trash2, Eye, Calendar, Filter, Loader2, MoreVertical } from "lucide-react"
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog"
|
||||
|
||||
import { doctorsService } from "services/doctorsApi.mjs";
|
||||
import Sidebar from "@/components/Sidebar";
|
||||
|
||||
// --- NOVOS IMPORTS (Certifique-se que criou os arquivos no passo anterior) ---
|
||||
import { FilterBar } from "@/components/ui/filter-bar";
|
||||
import { normalizeSpecialty, getUniqueSpecialties } from "@/lib/normalization";
|
||||
|
||||
interface Doctor {
|
||||
id: number;
|
||||
@ -47,33 +50,41 @@ interface DoctorDetails {
|
||||
export default function DoctorsPage() {
|
||||
const router = useRouter();
|
||||
|
||||
// --- Estados de Dados ---
|
||||
const [doctors, setDoctors] = useState<Doctor[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// --- Estados de Modais ---
|
||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
||||
const [doctorDetails, setDoctorDetails] = useState<DoctorDetails | null>(null);
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [doctorToDeleteId, setDoctorToDeleteId] = useState<number | null>(null);
|
||||
|
||||
// --- Estados para Filtros ---
|
||||
const [specialtyFilter, setSpecialtyFilter] = useState("all");
|
||||
const [statusFilter, setStatusFilter] = useState("all");
|
||||
// --- Estados de Filtro e Busca ---
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
const [filters, setFilters] = useState({
|
||||
specialty: "all",
|
||||
status: "all"
|
||||
});
|
||||
|
||||
// --- Estados para Paginação ---
|
||||
// --- Estados de Paginação ---
|
||||
const [itemsPerPage, setItemsPerPage] = useState(10);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
|
||||
// 1. Buscar Médicos na API
|
||||
const fetchDoctors = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data: Doctor[] = await doctorsService.list();
|
||||
// Mockando status para visualização (conforme original)
|
||||
const dataWithStatus = data.map((doc, index) => ({
|
||||
...doc,
|
||||
status: index % 3 === 0 ? "Inativo" : index % 2 === 0 ? "Férias" : "Ativo",
|
||||
}));
|
||||
setDoctors(dataWithStatus || []);
|
||||
setCurrentPage(1);
|
||||
// Não resetamos a página aqui para manter a navegação fluida se apenas recarregar dados
|
||||
} catch (e: any) {
|
||||
console.error("Erro ao carregar lista de médicos:", e);
|
||||
setError("Não foi possível carregar a lista de médicos. Verifique a conexão com a API.");
|
||||
@ -87,67 +98,63 @@ export default function DoctorsPage() {
|
||||
fetchDoctors();
|
||||
}, [fetchDoctors]);
|
||||
|
||||
const openDetailsDialog = async (doctor: Doctor) => {
|
||||
setDetailsDialogOpen(true);
|
||||
setDoctorDetails({
|
||||
nome: doctor.full_name,
|
||||
crm: doctor.crm,
|
||||
especialidade: doctor.specialty,
|
||||
contato: { celular: doctor.phone_mobile ?? undefined },
|
||||
endereco: { cidade: doctor.city ?? undefined, estado: doctor.state ?? undefined },
|
||||
status: doctor.status || "Ativo",
|
||||
convenio: "Particular",
|
||||
vip: false,
|
||||
ultimo_atendimento: "N/A",
|
||||
proximo_atendimento: "N/A",
|
||||
});
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (doctorToDeleteId === null) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
await doctorsService.delete(doctorToDeleteId);
|
||||
setDeleteDialogOpen(false);
|
||||
setDoctorToDeleteId(null);
|
||||
await fetchDoctors();
|
||||
} catch (e) {
|
||||
console.error("Erro ao excluir:", e);
|
||||
alert("Erro ao excluir médico.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const openDeleteDialog = (doctorId: number) => {
|
||||
setDoctorToDeleteId(doctorId);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
// 2. Gerar lista única de especialidades (Normalizada)
|
||||
const uniqueSpecialties = useMemo(() => {
|
||||
const specialties = doctors.map((doctor) => doctor.specialty).filter(Boolean);
|
||||
return [...new Set(specialties)];
|
||||
return getUniqueSpecialties(doctors);
|
||||
}, [doctors]);
|
||||
|
||||
const filteredDoctors = doctors.filter((doctor) => {
|
||||
const specialtyMatch = specialtyFilter === "all" || doctor.specialty === specialtyFilter;
|
||||
const statusMatch = statusFilter === "all" || doctor.status === statusFilter;
|
||||
return specialtyMatch && statusMatch;
|
||||
});
|
||||
// 3. Lógica de Filtragem Centralizada
|
||||
const filteredDoctors = useMemo(() => {
|
||||
return doctors.filter((doctor) => {
|
||||
// Normaliza a especialidade do médico atual para comparar
|
||||
const normalizedDocSpecialty = normalizeSpecialty(doctor.specialty);
|
||||
|
||||
// Filtros exatos
|
||||
const specialtyMatch = filters.specialty === "all" || normalizedDocSpecialty === filters.specialty;
|
||||
const statusMatch = filters.status === "all" || doctor.status === filters.status;
|
||||
|
||||
// Busca textual (Nome, Telefone, CRM)
|
||||
const searchLower = searchTerm.toLowerCase();
|
||||
const nameMatch = doctor.full_name?.toLowerCase().includes(searchLower);
|
||||
const phoneMatch = doctor.phone_mobile?.includes(searchLower);
|
||||
const crmMatch = doctor.crm?.toLowerCase().includes(searchLower);
|
||||
|
||||
return specialtyMatch && statusMatch && (searchTerm === "" || nameMatch || phoneMatch || crmMatch);
|
||||
});
|
||||
}, [doctors, filters, searchTerm]);
|
||||
|
||||
// --- Handlers de Controle (Com Reset de Paginação) ---
|
||||
|
||||
const handleSearch = (term: string) => {
|
||||
setSearchTerm(term);
|
||||
setCurrentPage(1); // Correção: Reseta para página 1 ao buscar
|
||||
};
|
||||
|
||||
const handleFilterChange = (key: string, value: string) => {
|
||||
setFilters(prev => ({ ...prev, [key]: value }));
|
||||
setCurrentPage(1); // Correção: Reseta para página 1 ao filtrar
|
||||
};
|
||||
|
||||
const handleClearFilters = () => {
|
||||
setSearchTerm("");
|
||||
setFilters({ specialty: "all", status: "all" });
|
||||
setCurrentPage(1); // Correção: Reseta para página 1 ao limpar
|
||||
};
|
||||
|
||||
const handleItemsPerPageChange = (value: string) => {
|
||||
setItemsPerPage(Number(value));
|
||||
setCurrentPage(1);
|
||||
};
|
||||
|
||||
// --- Lógica de Paginação ---
|
||||
const totalPages = Math.ceil(filteredDoctors.length / itemsPerPage);
|
||||
const indexOfLastItem = currentPage * itemsPerPage;
|
||||
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
||||
const currentItems = filteredDoctors.slice(indexOfFirstItem, indexOfLastItem);
|
||||
|
||||
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
|
||||
|
||||
const goToPrevPage = () => {
|
||||
setCurrentPage((prev) => Math.max(1, prev - 1));
|
||||
};
|
||||
|
||||
const goToNextPage = () => {
|
||||
setCurrentPage((prev) => Math.min(totalPages, prev + 1));
|
||||
};
|
||||
const goToPrevPage = () => setCurrentPage((prev) => Math.max(1, prev - 1));
|
||||
const goToNextPage = () => setCurrentPage((prev) => Math.min(totalPages, prev + 1));
|
||||
|
||||
const getVisiblePageNumbers = (totalPages: number, currentPage: number) => {
|
||||
const pages: number[] = [];
|
||||
@ -173,9 +180,42 @@ export default function DoctorsPage() {
|
||||
|
||||
const visiblePageNumbers = getVisiblePageNumbers(totalPages, currentPage);
|
||||
|
||||
const handleItemsPerPageChange = (value: string) => {
|
||||
setItemsPerPage(Number(value));
|
||||
setCurrentPage(1);
|
||||
// --- Handlers de Ações (Detalhes e Delete) ---
|
||||
const openDetailsDialog = (doctor: Doctor) => {
|
||||
setDetailsDialogOpen(true);
|
||||
setDoctorDetails({
|
||||
nome: doctor.full_name,
|
||||
crm: doctor.crm,
|
||||
especialidade: normalizeSpecialty(doctor.specialty), // Exibe normalizado
|
||||
contato: { celular: doctor.phone_mobile ?? undefined },
|
||||
endereco: { cidade: doctor.city ?? undefined, estado: doctor.state ?? undefined },
|
||||
status: doctor.status || "Ativo",
|
||||
convenio: "Particular",
|
||||
vip: false,
|
||||
ultimo_atendimento: "N/A",
|
||||
proximo_atendimento: "N/A",
|
||||
});
|
||||
};
|
||||
|
||||
const openDeleteDialog = (doctorId: number) => {
|
||||
setDoctorToDeleteId(doctorId);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (doctorToDeleteId === null) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
await doctorsService.delete(doctorToDeleteId);
|
||||
setDeleteDialogOpen(false);
|
||||
setDoctorToDeleteId(null);
|
||||
await fetchDoctors();
|
||||
} catch (e) {
|
||||
console.error("Erro ao excluir:", e);
|
||||
alert("Erro ao excluir médico.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
@ -184,63 +224,52 @@ export default function DoctorsPage() {
|
||||
{/* Cabeçalho */}
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Médicos Cadastrados</h1>
|
||||
<p className="text-sm text-gray-500">Gerencie todos os profissionais de saúde.</p>
|
||||
<h1 className="text-2xl font-bold text-gray-900">
|
||||
Médicos Cadastrados
|
||||
</h1>
|
||||
<p className="text-sm text-gray-500">
|
||||
Gerencie todos os profissionais de saúde.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filtros e Itens por Página */}
|
||||
<div className="flex flex-wrap items-center gap-3 bg-white p-3 sm:p-4 rounded-lg border border-gray-200">
|
||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
||||
<span className="text-sm font-medium text-foreground">Especialidade</span>
|
||||
<Select value={specialtyFilter} onValueChange={setSpecialtyFilter}>
|
||||
<SelectTrigger className="w-[160px] sm:w-[180px]">
|
||||
<SelectValue placeholder="Especialidade" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todas</SelectItem>
|
||||
{uniqueSpecialties.map((specialty) => (
|
||||
<SelectItem key={specialty} value={specialty}>
|
||||
{specialty}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
||||
<span className="text-sm font-medium text-foreground">Status</span>
|
||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
||||
<SelectTrigger className="w-[160px] sm:w-[180px]">
|
||||
<SelectValue placeholder="Status" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todos</SelectItem>
|
||||
<SelectItem value="Ativo">Ativo</SelectItem>
|
||||
<SelectItem value="Férias">Férias</SelectItem>
|
||||
<SelectItem value="Inativo">Inativo</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
||||
<span className="text-sm font-medium text-foreground">Itens por página</span>
|
||||
{/* --- NOVO COMPONENTE DE FILTRO --- */}
|
||||
<FilterBar
|
||||
searchTerm={searchTerm}
|
||||
onSearch={handleSearch}
|
||||
activeFilters={filters}
|
||||
onFilterChange={handleFilterChange}
|
||||
onClearFilters={handleClearFilters}
|
||||
searchPlaceholder="Buscar por nome, CRM ou telefone..."
|
||||
filters={[
|
||||
{
|
||||
key: "specialty",
|
||||
label: "Especialidade",
|
||||
options: uniqueSpecialties
|
||||
},
|
||||
{
|
||||
key: "status",
|
||||
label: "Status",
|
||||
options: ["Ativo", "Férias", "Inativo"]
|
||||
}
|
||||
]}
|
||||
>
|
||||
{/* Seletor de Itens por Página (Filho do FilterBar) */}
|
||||
<div className="hidden lg:block">
|
||||
<Select onValueChange={handleItemsPerPageChange} defaultValue={String(itemsPerPage)}>
|
||||
<SelectTrigger className="w-[140px]">
|
||||
<SelectValue placeholder="Itens por pág." />
|
||||
<SelectTrigger className="w-[70px]">
|
||||
<SelectValue placeholder="10" />
|
||||
</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>
|
||||
<SelectItem value="5">5</SelectItem>
|
||||
<SelectItem value="10">10</SelectItem>
|
||||
<SelectItem value="20">20</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<Button variant="outline" className="ml-auto w-full md:w-auto">
|
||||
<Filter className="w-4 h-4 mr-2" />
|
||||
Filtro avançado
|
||||
</Button>
|
||||
</div>
|
||||
</FilterBar>
|
||||
|
||||
{/* Tabela de Médicos (Visível em Telas Médias e Maiores) */}
|
||||
{/* Tabela de Médicos */}
|
||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-hidden hidden md:block">
|
||||
{loading ? (
|
||||
<div className="p-8 text-center text-gray-500">
|
||||
@ -272,10 +301,22 @@ export default function DoctorsPage() {
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{currentItems.map((doctor) => (
|
||||
<tr key={doctor.id} className="hover:bg-gray-50 transition">
|
||||
<td className="px-4 py-3 font-medium text-gray-900">{doctor.full_name}</td>
|
||||
<td className="px-4 py-3 font-medium text-gray-900">
|
||||
{doctor.full_name}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-gray-500 hidden sm:table-cell">{doctor.crm}</td>
|
||||
<td className="px-4 py-3 text-gray-500 hidden md:table-cell">{doctor.specialty}</td>
|
||||
<td className="px-4 py-3 text-gray-500 hidden lg:table-cell">{doctor.status || "N/A"}</td>
|
||||
<td className="px-4 py-3 text-gray-500 hidden md:table-cell">
|
||||
{/* Exibe Especialidade Normalizada */}
|
||||
{normalizeSpecialty(doctor.specialty)}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-gray-500 hidden lg:table-cell">
|
||||
<span className={`px-2 py-1 rounded-full text-xs ${
|
||||
doctor.status === 'Ativo' ? 'bg-green-100 text-green-800' :
|
||||
doctor.status === 'Inativo' ? 'bg-red-100 text-red-800' : 'bg-yellow-100 text-yellow-800'
|
||||
}`}>
|
||||
{doctor.status || "N/A"}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-gray-500 hidden xl:table-cell">
|
||||
{(doctor.city || doctor.state)
|
||||
? `${doctor.city || ""}${doctor.city && doctor.state ? '/' : ''}${doctor.state || ""}`
|
||||
@ -284,7 +325,10 @@ export default function DoctorsPage() {
|
||||
<td className="px-4 py-3 text-right">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<div className="text-blue-600 cursor-pointer inline-block">Ações</div>
|
||||
<Button variant="ghost" className="h-8 w-8 p-0">
|
||||
<span className="sr-only">Abrir menu</span>
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => openDetailsDialog(doctor)}>
|
||||
@ -316,7 +360,7 @@ export default function DoctorsPage() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Cards de Médicos (Visível Apenas em Telas Pequenas) */}
|
||||
{/* Cards de Médicos (Mobile) */}
|
||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md p-4 block md:hidden">
|
||||
{loading ? (
|
||||
<div className="p-8 text-center text-gray-500">
|
||||
@ -335,14 +379,26 @@ export default function DoctorsPage() {
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{currentItems.map((doctor) => (
|
||||
<div key={doctor.id} className="bg-white-50 rounded-lg p-4 flex justify-between items-center border border-white-200">
|
||||
<div key={doctor.id} className="bg-gray-50 rounded-lg p-4 flex justify-between items-center border border-gray-100">
|
||||
<div>
|
||||
<div className="font-semibold text-gray-900">{doctor.full_name}</div>
|
||||
<div className="text-sm text-gray-600">{doctor.specialty}</div>
|
||||
<div className="text-xs text-gray-500 mb-1">{doctor.phone_mobile}</div>
|
||||
<div className="text-sm text-gray-600">{normalizeSpecialty(doctor.specialty)}</div>
|
||||
<div className="text-xs mt-1">
|
||||
<span className={`px-2 py-0.5 rounded-full text-xs ${
|
||||
doctor.status === 'Ativo' ? 'bg-green-100 text-green-800' :
|
||||
doctor.status === 'Inativo' ? 'bg-red-100 text-red-800' : 'bg-yellow-100 text-yellow-800'
|
||||
}`}>
|
||||
{doctor.status || "N/A"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<div className="text-blue-600 cursor-pointer inline-block">Ações</div>
|
||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
|
||||
<span className="sr-only">Abrir menu</span>
|
||||
<div className="font-bold text-gray-500">...</div>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => openDetailsDialog(doctor)}>
|
||||
@ -355,10 +411,6 @@ export default function DoctorsPage() {
|
||||
Editar
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem>
|
||||
<Calendar className="mr-2 h-4 w-4" />
|
||||
Marcar consulta
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(doctor.id)}>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Excluir
|
||||
@ -388,7 +440,7 @@ export default function DoctorsPage() {
|
||||
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-blue-600 text-white shadow-md border-blue-600"
|
||||
: "bg-gray-100 text-gray-700 hover:bg-gray-200"
|
||||
}`}
|
||||
>
|
||||
@ -406,7 +458,7 @@ export default function DoctorsPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Dialogs de Exclusão e Detalhes */}
|
||||
{/* Dialogs (Exclusão e Detalhes) */}
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
@ -423,50 +475,70 @@ export default function DoctorsPage() {
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
||||
<AlertDialog
|
||||
open={detailsDialogOpen}
|
||||
onOpenChange={setDetailsDialogOpen}
|
||||
>
|
||||
<AlertDialogContent className="max-w-[95%] sm:max-w-lg">
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="text-2xl">{doctorDetails?.nome}</AlertDialogTitle>
|
||||
<AlertDialogTitle className="text-2xl">
|
||||
{doctorDetails?.nome}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription className="text-left text-gray-700">
|
||||
{doctorDetails && (
|
||||
<div className="space-y-3 text-left">
|
||||
<h3 className="font-semibold mt-2">Informações Principais</h3>
|
||||
<h3 className="font-semibold mt-2">
|
||||
Informações Principais
|
||||
</h3>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-y-2 gap-x-4 text-sm">
|
||||
<div>
|
||||
<strong>CRM:</strong> {doctorDetails.crm}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Especialidade:</strong> {doctorDetails.especialidade}
|
||||
<strong>Especialidade:</strong>{" "}
|
||||
{doctorDetails.especialidade}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Celular:</strong> {doctorDetails.contato.celular || "N/A"}
|
||||
<strong>Celular:</strong>{" "}
|
||||
{doctorDetails.contato.celular || "N/A"}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Localização:</strong> {`${doctorDetails.endereco.cidade || "N/A"}/${doctorDetails.endereco.estado || "N/A"}`}
|
||||
<strong>Localização:</strong>{" "}
|
||||
{`${doctorDetails.endereco.cidade || "N/A"}/${
|
||||
doctorDetails.endereco.estado || "N/A"
|
||||
}`}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3 className="font-semibold mt-4">Atendimento e Convênio</h3>
|
||||
<h3 className="font-semibold mt-4">
|
||||
Atendimento e Convênio
|
||||
</h3>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-y-2 gap-x-4 text-sm">
|
||||
<div>
|
||||
<strong>Convênio:</strong> {doctorDetails.convenio || "N/A"}
|
||||
<strong>Convênio:</strong>{" "}
|
||||
{doctorDetails.convenio || "N/A"}
|
||||
</div>
|
||||
<div>
|
||||
<strong>VIP:</strong> {doctorDetails.vip ? "Sim" : "Não"}
|
||||
<strong>VIP:</strong>{" "}
|
||||
{doctorDetails.vip ? "Sim" : "Não"}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Status:</strong> {doctorDetails.status || "N/A"}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Último atendimento:</strong> {doctorDetails.ultimo_atendimento || "N/A"}
|
||||
<strong>Último atendimento:</strong>{" "}
|
||||
{doctorDetails.ultimo_atendimento || "N/A"}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Próximo atendimento:</strong> {doctorDetails.proximo_atendimento || "N/A"}
|
||||
<strong>Próximo atendimento:</strong>{" "}
|
||||
{doctorDetails.proximo_atendimento || "N/A"}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{doctorDetails === null && !loading && <div className="text-red-600">Detalhes não disponíveis.</div>}
|
||||
{doctorDetails === null && !loading && (
|
||||
<div className="text-red-600">Detalhes não disponíveis.</div>
|
||||
)}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
|
||||
@ -5,7 +5,7 @@ import Link from "next/link";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Edit, Trash2, Eye, Calendar, Filter, Loader2 } from "lucide-react";
|
||||
import { Edit, Trash2, Eye, Calendar, Filter, Loader2, MoreVertical } from "lucide-react";
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||
import { patientsService } from "@/services/patientsApi.mjs";
|
||||
import Sidebar from "@/components/Sidebar";
|
||||
@ -75,9 +75,7 @@ export default function PacientesPage() {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[]
|
||||
);
|
||||
}, []);
|
||||
|
||||
// 2. Efeito para aplicar filtros e calcular a lista filtrada (chama-se quando allPatients ou filtros mudam)
|
||||
useEffect(() => {
|
||||
@ -112,7 +110,6 @@ export default function PacientesPage() {
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
|
||||
// --- LÓGICA DE AÇÕES (DELETAR / VER DETALHES) ---
|
||||
|
||||
const openDetailsDialog = async (patientId: string) => {
|
||||
@ -130,9 +127,11 @@ export default function PacientesPage() {
|
||||
try {
|
||||
await patientsService.delete(patientId);
|
||||
// Atualiza a lista completa para refletir a exclusão
|
||||
setAllPatients((prev) => prev.filter((p) => String(p.id) !== String(patientId)));
|
||||
setAllPatients((prev) =>
|
||||
prev.filter((p) => String(p.id) !== String(patientId))
|
||||
);
|
||||
} catch (e: any) {
|
||||
alert(`Erro ao deletar paciente: ${e?.message || 'Erro desconhecido'}`);
|
||||
alert(`Erro ao deletar paciente: ${e?.message || "Erro desconhecido"}`);
|
||||
}
|
||||
setDeleteDialogOpen(false);
|
||||
setPatientToDelete(null);
|
||||
@ -149,8 +148,12 @@ export default function PacientesPage() {
|
||||
{/* Header (Responsividade OK) */}
|
||||
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-xl md:text-2xl font-bold text-foreground">Pacientes</h1>
|
||||
<p className="text-muted-foreground text-sm md:text-base">Gerencie as informações de seus pacientes</p>
|
||||
<h1 className="text-xl md:text-2xl font-bold text-foreground">
|
||||
Pacientes
|
||||
</h1>
|
||||
<p className="text-muted-foreground text-sm md:text-base">
|
||||
Gerencie as informações de seus pacientes
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -171,9 +174,13 @@ export default function PacientesPage() {
|
||||
|
||||
{/* Convênio - Ocupa a largura total em telas pequenas, depois se ajusta */}
|
||||
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[200px]">
|
||||
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">Convênio</span>
|
||||
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">
|
||||
Convênio
|
||||
</span>
|
||||
<Select value={convenioFilter} onValueChange={setConvenioFilter}>
|
||||
<SelectTrigger className="w-full sm:w-40"> {/* w-full para mobile, w-40 para sm+ */}
|
||||
<SelectTrigger className="w-full sm:w-40">
|
||||
{" "}
|
||||
{/* w-full para mobile, w-40 para sm+ */}
|
||||
<SelectValue placeholder="Convênio" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@ -201,79 +208,118 @@ export default function PacientesPage() {
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Aniversariantes - Ocupa 100% no mobile, e se alinha à direita no md+ */}
|
||||
<Button variant="outline" className="w-full md:w-auto md:ml-auto">
|
||||
<Calendar className="w-4 h-4 mr-2" />
|
||||
Aniversariantes
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* --- SEÇÃO DE TABELA (VISÍVEL EM TELAS MAIORES OU IGUAIS A MD) --- */}
|
||||
{/* Garantir que a tabela se esconda em telas menores e apareça em MD+ */}
|
||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md hidden md:block">
|
||||
<div className="overflow-x-auto"> {/* Permite rolagem horizontal se a tabela for muito larga */}
|
||||
<div className="overflow-x-auto">
|
||||
{" "}
|
||||
{/* Permite rolagem horizontal se a tabela for muito larga */}
|
||||
{error ? (
|
||||
<div className="p-6 text-red-600">{`Erro ao carregar pacientes: ${error}`}</div>
|
||||
) : loading ? (
|
||||
<div className="p-6 text-center text-gray-500 flex items-center justify-center">
|
||||
<Loader2 className="w-6 h-6 mr-2 animate-spin text-green-600" /> Carregando pacientes...
|
||||
<Loader2 className="w-6 h-6 mr-2 animate-spin text-green-600" />{" "}
|
||||
Carregando pacientes...
|
||||
</div>
|
||||
) : (
|
||||
<table className="w-full min-w-[650px]"> {/* min-w para evitar que a tabela se contraia demais */}
|
||||
<table className="w-full min-w-[650px]">
|
||||
{" "}
|
||||
{/* min-w para evitar que a tabela se contraia demais */}
|
||||
<thead className="bg-gray-50 border-b border-gray-200">
|
||||
<tr>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[20%]">Nome</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[20%]">
|
||||
Nome
|
||||
</th>
|
||||
{/* Ajustes de visibilidade de colunas para diferentes breakpoints */}
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">Telefone</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden md:table-cell">Cidade / Estado</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">Convênio</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">Último atendimento</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">Próximo atendimento</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[5%]">Ações</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">
|
||||
Telefone
|
||||
</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden md:table-cell">
|
||||
Cidade / Estado
|
||||
</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">
|
||||
Convênio
|
||||
</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">
|
||||
Último atendimento
|
||||
</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">
|
||||
Próximo atendimento
|
||||
</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[5%]">
|
||||
Ações
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{currentPatients.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={7} className="p-8 text-center text-gray-500">
|
||||
{allPatients.length === 0 ? "Nenhum paciente cadastrado" : "Nenhum paciente encontrado com os filtros aplicados"}
|
||||
{allPatients.length === 0
|
||||
? "Nenhum paciente cadastrado"
|
||||
: "Nenhum paciente encontrado com os filtros aplicados"}
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
currentPatients.map((patient) => (
|
||||
<tr key={patient.id} className="border-b border-gray-100 hover:bg-gray-50">
|
||||
<tr
|
||||
key={patient.id}
|
||||
className="border-b border-gray-100 hover:bg-gray-50"
|
||||
>
|
||||
<td className="p-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
|
||||
<span className="text-green-600 font-medium text-sm">{patient.nome?.charAt(0) || "?"}</span>
|
||||
<div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
|
||||
<span className="text-blue-600 font-medium text-sm">
|
||||
{patient.nome?.charAt(0) || "?"}
|
||||
</span>
|
||||
</div>
|
||||
<span className="font-medium text-gray-900">
|
||||
{patient.nome}
|
||||
{patient.vip && (
|
||||
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-600 bg-purple-100 rounded-full">VIP</span>
|
||||
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-600 bg-purple-100 rounded-full">
|
||||
VIP
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="p-4 text-gray-600 hidden sm:table-cell">{patient.telefone}</td>
|
||||
<td className="p-4 text-gray-600 hidden sm:table-cell">
|
||||
{patient.telefone}
|
||||
</td>
|
||||
<td className="p-4 text-gray-600 hidden md:table-cell">{`${patient.cidade} / ${patient.estado}`}</td>
|
||||
<td className="p-4 text-gray-600 hidden sm:table-cell">{patient.convenio}</td>
|
||||
<td className="p-4 text-gray-600 hidden lg:table-cell">{patient.ultimoAtendimento}</td>
|
||||
<td className="p-4 text-gray-600 hidden lg:table-cell">{patient.proximoAtendimento}</td>
|
||||
<td className="p-4 text-gray-600 hidden sm:table-cell">
|
||||
{patient.convenio}
|
||||
</td>
|
||||
<td className="p-4 text-gray-600 hidden lg:table-cell">
|
||||
{patient.ultimoAtendimento}
|
||||
</td>
|
||||
<td className="p-4 text-gray-600 hidden lg:table-cell">
|
||||
{patient.proximoAtendimento}
|
||||
</td>
|
||||
|
||||
<td className="p-4">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<div className="text-blue-600 cursor-pointer">Ações</div>
|
||||
<div className="text-black-600 cursor-pointer">
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</div>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => openDetailsDialog(String(patient.id))}>
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
openDetailsDialog(String(patient.id))
|
||||
}
|
||||
>
|
||||
<Eye className="w-4 h-4 mr-2" />
|
||||
Ver detalhes
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/secretary/pacientes/${patient.id}/editar`} className="flex items-center w-full">
|
||||
<Link
|
||||
href={`/secretary/pacientes/${patient.id}/editar`}
|
||||
className="flex items-center w-full"
|
||||
>
|
||||
<Edit className="w-4 h-4 mr-2" />
|
||||
Editar
|
||||
</Link>
|
||||
@ -283,7 +329,12 @@ export default function PacientesPage() {
|
||||
<Calendar className="w-4 h-4 mr-2" />
|
||||
Marcar consulta
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(String(patient.id))}>
|
||||
<DropdownMenuItem
|
||||
className="text-red-600"
|
||||
onClick={() =>
|
||||
openDeleteDialog(String(patient.id))
|
||||
}
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
Excluir
|
||||
</DropdownMenuItem>
|
||||
@ -299,70 +350,12 @@ export default function PacientesPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* --- SEÇÃO DE CARDS (VISÍVEL APENAS EM TELAS MENORES QUE MD) --- */}
|
||||
{/* Garantir que os cards apareçam em telas menores e se escondam em MD+ */}
|
||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md p-4 block md:hidden">
|
||||
{error ? (
|
||||
<div className="p-6 text-red-600">{`Erro ao carregar pacientes: ${error}`}</div>
|
||||
) : loading ? (
|
||||
<div className="p-6 text-center text-gray-500 flex items-center justify-center">
|
||||
<Loader2 className="w-6 h-6 mr-2 animate-spin text-green-600" /> Carregando pacientes...
|
||||
</div>
|
||||
) : filteredPatients.length === 0 ? (
|
||||
<div className="p-8 text-center text-gray-500">
|
||||
{allPatients.length === 0 ? "Nenhum paciente cadastrado" : "Nenhum paciente encontrado com os filtros aplicados"}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{currentPatients.map((patient) => (
|
||||
<div key={patient.id} className="bg-gray-50 rounded-lg p-4 flex flex-col sm:flex-row justify-between items-start sm:items-center border border-gray-200">
|
||||
<div className="flex-grow mb-2 sm:mb-0">
|
||||
<div className="font-semibold text-lg text-gray-900 flex items-center">
|
||||
{patient.nome}
|
||||
{patient.vip && (
|
||||
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-600 bg-purple-100 rounded-full">VIP</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-sm text-gray-600">Telefone: {patient.telefone}</div>
|
||||
<div className="text-sm text-gray-600">Convênio: {patient.convenio}</div>
|
||||
</div>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<div className="w-full"><Button variant="outline" className="w-full">Ações</Button></div>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => openDetailsDialog(String(patient.id))}>
|
||||
<Eye className="w-4 h-4 mr-2" />
|
||||
Ver detalhes
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/secretary/pacientes/${patient.id}/editar`} className="flex items-center w-full">
|
||||
<Edit className="w-4 h-4 mr-2" />
|
||||
Editar
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem>
|
||||
<Calendar className="w-4 h-4 mr-2" />
|
||||
Marcar consulta
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(String(patient.id))}>
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
Excluir
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Paginação */}
|
||||
{totalPages > 1 && !loading && (
|
||||
<div className="flex flex-col sm:flex-row items-center justify-center p-4 border-t border-gray-200">
|
||||
<div className="flex space-x-2 flex-wrap justify-center"> {/* Adicionado flex-wrap e justify-center para botões da paginação */}
|
||||
<div className="flex space-x-2 flex-wrap justify-center">
|
||||
{" "}
|
||||
{/* Adicionado flex-wrap e justify-center para botões da paginação */}
|
||||
<Button
|
||||
onClick={() => setPage((prev) => Math.max(1, prev - 1))}
|
||||
disabled={page === 1}
|
||||
@ -371,7 +364,6 @@ export default function PacientesPage() {
|
||||
>
|
||||
< Anterior
|
||||
</Button>
|
||||
|
||||
{Array.from({ length: totalPages }, (_, index) => index + 1)
|
||||
.slice(Math.max(0, page - 3), Math.min(totalPages, page + 2))
|
||||
.map((pageNumber) => (
|
||||
@ -380,14 +372,19 @@ export default function PacientesPage() {
|
||||
onClick={() => setPage(pageNumber)}
|
||||
variant={pageNumber === page ? "default" : "outline"}
|
||||
size="lg"
|
||||
className={pageNumber === page ? "bg-green-600 hover:bg-green-700 text-white" : "text-gray-700"}
|
||||
className={
|
||||
pageNumber === page
|
||||
? "bg-blue-600 hover:bg-blue-700 text-white"
|
||||
: "text-gray-700"
|
||||
}
|
||||
>
|
||||
{pageNumber}
|
||||
</Button>
|
||||
))}
|
||||
|
||||
<Button
|
||||
onClick={() => setPage((prev) => Math.min(totalPages, prev + 1))}
|
||||
onClick={() =>
|
||||
setPage((prev) => Math.min(totalPages, prev + 1))
|
||||
}
|
||||
disabled={page === totalPages}
|
||||
variant="outline"
|
||||
size="lg"
|
||||
@ -403,18 +400,29 @@ export default function PacientesPage() {
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
|
||||
<AlertDialogDescription>Tem certeza que deseja excluir este paciente? Esta ação não pode ser desfeita.</AlertDialogDescription>
|
||||
<AlertDialogDescription>
|
||||
Tem certeza que deseja excluir este paciente? Esta ação não pode
|
||||
ser desfeita.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancelar</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={() => patientToDelete && handleDeletePatient(patientToDelete)} className="bg-red-600 hover:bg-red-700">
|
||||
<AlertDialogAction
|
||||
onClick={() =>
|
||||
patientToDelete && handleDeletePatient(patientToDelete)
|
||||
}
|
||||
className="bg-red-600 hover:bg-red-700"
|
||||
>
|
||||
Excluir
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
||||
<AlertDialog
|
||||
open={detailsDialogOpen}
|
||||
onOpenChange={setDetailsDialogOpen}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Detalhes do Paciente</AlertDialogTitle>
|
||||
|
||||
@ -4,7 +4,8 @@ import React, { useEffect, useState, useCallback } from "react";
|
||||
import Link from "next/link";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Plus, Eye, Filter, Loader2 } from "lucide-react";
|
||||
import { Input } from "@/components/ui/input"; // <--- 1. Importação Adicionada
|
||||
import { Plus, Eye, Filter, Loader2, Search } from "lucide-react"; // <--- 1. Ícone Search Adicionado
|
||||
import { AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||
import { api, login } from "services/api.mjs";
|
||||
import { usersService } from "services/usersApi.mjs";
|
||||
@ -31,9 +32,10 @@ export default function UsersPage() {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
||||
const [userDetails, setUserDetails] = useState<UserInfoResponse | null>(
|
||||
null
|
||||
);
|
||||
const [userDetails, setUserDetails] = useState<UserInfoResponse | null>(null);
|
||||
|
||||
// --- Estados de Filtro ---
|
||||
const [searchTerm, setSearchTerm] = useState(""); // <--- 2. Estado da busca
|
||||
const [selectedRole, setSelectedRole] = useState<string>("all");
|
||||
|
||||
// --- Lógica de Paginação INÍCIO ---
|
||||
@ -118,10 +120,21 @@ export default function UsersPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const filteredUsers =
|
||||
selectedRole && selectedRole !== "all"
|
||||
? users.filter((u) => u.role === selectedRole)
|
||||
: users;
|
||||
// --- 3. Lógica de Filtragem Atualizada ---
|
||||
const filteredUsers = users.filter((u) => {
|
||||
// Filtro por Papel (Role)
|
||||
const roleMatch = selectedRole === "all" || u.role === selectedRole;
|
||||
|
||||
// Filtro da Barra de Pesquisa (Nome, Email ou Telefone)
|
||||
const searchLower = searchTerm.toLowerCase();
|
||||
const nameMatch = u.full_name?.toLowerCase().includes(searchLower);
|
||||
const emailMatch = u.email?.toLowerCase().includes(searchLower);
|
||||
const phoneMatch = u.phone?.includes(searchLower);
|
||||
|
||||
const searchMatch = !searchTerm || nameMatch || emailMatch || phoneMatch;
|
||||
|
||||
return roleMatch && searchMatch;
|
||||
});
|
||||
|
||||
const indexOfLastItem = currentPage * itemsPerPage;
|
||||
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
||||
@ -166,7 +179,6 @@ export default function UsersPage() {
|
||||
return (
|
||||
<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>
|
||||
@ -174,20 +186,32 @@ export default function UsersPage() {
|
||||
<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">
|
||||
<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>
|
||||
|
||||
{/* Filtro e Itens por Página */}
|
||||
<div className="flex flex-wrap items-center gap-3 bg-white p-4 rounded-lg border border-gray-200">
|
||||
{/* --- 4. Filtro (Barra de Pesquisa + Selects) --- */}
|
||||
<div className="flex flex-col md:flex-row items-start md:items-center gap-3 bg-white p-4 rounded-lg border border-gray-200">
|
||||
|
||||
{/* Select de Filtro por Papel - Ajustado para resetar a página */}
|
||||
{/* Barra de Pesquisa */}
|
||||
<div className="relative w-full md:flex-1">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
|
||||
<Input
|
||||
placeholder="Buscar por nome, e-mail ou telefone..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => {
|
||||
setSearchTerm(e.target.value);
|
||||
setCurrentPage(1); // Reseta a paginação ao pesquisar
|
||||
}}
|
||||
className="pl-10 w-full bg-gray-50 border-gray-200 focus:bg-white transition-colors"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-3 w-full md:w-auto">
|
||||
{/* Select de Filtro por Papel */}
|
||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
||||
<span className="text-sm font-medium text-foreground whitespace-nowrap">
|
||||
Filtrar por papel
|
||||
</span>
|
||||
<Select
|
||||
onValueChange={(value) => {
|
||||
setSelectedRole(value);
|
||||
@ -195,8 +219,8 @@ export default function UsersPage() {
|
||||
}}
|
||||
value={selectedRole}>
|
||||
|
||||
<SelectTrigger className="w-full sm:w-[180px]"> {/* w-full para mobile, w-[180px] para sm+ */}
|
||||
<SelectValue placeholder="Filtrar por papel" />
|
||||
<SelectTrigger className="w-full sm:w-[150px]">
|
||||
<SelectValue placeholder="Papel" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todos</SelectItem>
|
||||
@ -211,29 +235,28 @@ export default function UsersPage() {
|
||||
|
||||
{/* Select de Itens por Página */}
|
||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
||||
<span className="text-sm font-medium text-foreground whitespace-nowrap">
|
||||
Itens por página
|
||||
</span>
|
||||
<Select
|
||||
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 className="w-full sm:w-[80px]">
|
||||
<SelectValue placeholder="10" />
|
||||
</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>
|
||||
<SelectItem value="5">5</SelectItem>
|
||||
<SelectItem value="10">10</SelectItem>
|
||||
<SelectItem value="20">20</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<Button variant="outline" className="ml-auto w-full md:w-auto">
|
||||
|
||||
<Button variant="outline" className="ml-auto w-full md:w-auto hidden lg:flex">
|
||||
<Filter className="w-4 h-4 mr-2" />
|
||||
Filtro avançado
|
||||
Filtros
|
||||
</Button>
|
||||
</div>
|
||||
{/* Fim do Filtro e Itens por Página */}
|
||||
</div>
|
||||
{/* Fim do Filtro */}
|
||||
|
||||
{/* Tabela/Lista */}
|
||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-x-auto">
|
||||
@ -254,11 +277,21 @@ export default function UsersPage() {
|
||||
<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>
|
||||
<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">
|
||||
@ -299,7 +332,10 @@ export default function UsersPage() {
|
||||
<div className="text-sm font-medium text-gray-900 truncate">
|
||||
{u.full_name || "—"}
|
||||
</div>
|
||||
<div className="text-sm text-gray-500 capitalize">
|
||||
<div className="text-xs text-gray-500 truncate">
|
||||
{u.email}
|
||||
</div>
|
||||
<div className="text-sm text-gray-500 capitalize mt-1">
|
||||
{u.role || "—"}
|
||||
</div>
|
||||
</div>
|
||||
@ -320,7 +356,6 @@ export default function UsersPage() {
|
||||
{/* 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}
|
||||
@ -335,8 +370,9 @@ export default function UsersPage() {
|
||||
<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"
|
||||
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"
|
||||
}`}
|
||||
>
|
||||
@ -352,7 +388,6 @@ export default function UsersPage() {
|
||||
>
|
||||
{"Próximo >"}
|
||||
</button>
|
||||
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
@ -360,7 +395,10 @@ export default function UsersPage() {
|
||||
</div>
|
||||
|
||||
{/* Modal de Detalhes */}
|
||||
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
||||
<AlertDialog
|
||||
open={detailsDialogOpen}
|
||||
onOpenChange={setDetailsDialogOpen}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="text-2xl">
|
||||
@ -388,19 +426,25 @@ export default function UsersPage() {
|
||||
<strong>Telefone:</strong> {userDetails.profile.phone}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Roles:</strong>{" "}
|
||||
{userDetails.roles?.join(", ")}
|
||||
<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]) => (
|
||||
{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>
|
||||
{k}:{" "}
|
||||
<span
|
||||
className={`font-semibold ${
|
||||
v ? "text-green-600" : "text-red-600"
|
||||
}`}
|
||||
>
|
||||
{v ? "Sim" : "Não"}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
)
|
||||
)}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
169
app/page.tsx
169
app/page.tsx
@ -3,50 +3,49 @@
|
||||
import Link from "next/link";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useState } from "react";
|
||||
import { Stethoscope, Baby, Microscope } from "lucide-react";
|
||||
|
||||
export default function InicialPage() {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col bg-background">
|
||||
{/* Barra superior de informações */}
|
||||
<div className="bg-primary text-primary-foreground text-sm py-2 px-4 md:px-6 flex justify-between items-center">
|
||||
<div className="min-h-screen flex flex-col bg-white font-sans scroll-smooth text-[#1E2A78]">
|
||||
{/* Barra superior */}
|
||||
<div className="bg-[#1E2A78] text-white text-sm py-2 px-4 md:px-6 flex justify-between items-center">
|
||||
<span className="hidden sm:inline">Horário: 08h00 - 21h00</span>
|
||||
<span>Email: contato@mediconnect.com</span>
|
||||
<span className="hover:underline cursor-pointer transition">
|
||||
Email: contato@mediconnect.com
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Header principal - Com Logo REAL */}
|
||||
<header className="bg-card shadow-md py-4 px-4 md:px-6 flex justify-between items-center relative">
|
||||
{/* Agrupamento do Logo e Nome do Site */}
|
||||
<a href="#home" className="flex items-center space-x-1 cursor-pointer">
|
||||
{/* 1. IMAGEM/LOGO REAL: Referenciando o arquivo placeholder-logo.png na pasta public */}
|
||||
{/* Header */}
|
||||
<header className="bg-white shadow-md py-4 px-4 md:px-6 flex justify-between items-center relative sticky top-0 z-50 backdrop-blur-md">
|
||||
<a href="#home" className="flex items-center space-x-2 cursor-pointer">
|
||||
<img
|
||||
src="/android-chrome-512x512.png" // O caminho se inicia a partir da pasta 'public'
|
||||
src="/android-chrome-512x512.png"
|
||||
alt="Logo MediConnect"
|
||||
className="w-14 h-14 object-contain" // ALTERADO: Aumentado para w-14 h-14
|
||||
className="w-20 h-20 object-contain transition-transform hover:scale-105"
|
||||
/>
|
||||
|
||||
{/* 2. NOME DO SITE */}
|
||||
<h1 className="text-2xl font-bold text-primary">MedConnect</h1>
|
||||
<h1 className="text-2xl font-extrabold text-[#1E2A78] tracking-tight">
|
||||
MedConnect
|
||||
</h1>
|
||||
</a>
|
||||
|
||||
{/* Botão do menu hambúrguer para telas menores */}
|
||||
{/* Menu Mobile */}
|
||||
<div className="md:hidden flex items-center space-x-4">
|
||||
{/* O botão de login agora estará sempre aqui, fora do menu */}
|
||||
<Link href="/login">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="rounded-full px-4 py-2 text-sm border-2 transition cursor-pointer"
|
||||
className="rounded-full px-4 py-2 text-sm border-2 border-[#007BFF] text-[#007BFF] hover:bg-[#007BFF] hover:text-white transition"
|
||||
>
|
||||
Login
|
||||
</Button>
|
||||
</Link>
|
||||
<button
|
||||
onClick={() => setIsMenuOpen(!isMenuOpen)}
|
||||
className="text-primary-foreground focus:outline-none"
|
||||
className="text-[#1E2A78] focus:outline-none"
|
||||
>
|
||||
<svg
|
||||
className="w-6 h-6 text-primary"
|
||||
className="w-6 h-6"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
@ -71,114 +70,140 @@ export default function InicialPage() {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Navegação principal */}
|
||||
{/* Navegação */}
|
||||
<nav
|
||||
className={`${
|
||||
isMenuOpen ? "block" : "hidden"
|
||||
} absolute top-[76px] left-0 w-full bg-card shadow-md py-4 md:relative md:top-auto md:left-auto md:w-auto md:block md:bg-transparent md:shadow-none z-10`}
|
||||
} absolute top-[76px] left-0 w-full bg-white shadow-md py-4 md:relative md:top-auto md:left-auto md:w-auto md:block md:bg-transparent md:shadow-none transition-all duration-300 z-10`}
|
||||
>
|
||||
<div className="flex flex-col md:flex-row space-y-4 md:space-y-0 md:space-x-6 text-muted-foreground font-medium items-center">
|
||||
<Link href="#home" className="hover:text-primary">
|
||||
<div className="flex flex-col md:flex-row space-y-4 md:space-y-0 md:space-x-8 text-gray-600 font-medium items-center">
|
||||
<Link href="#home" className="hover:text-[#007BFF] transition">
|
||||
Home
|
||||
</Link>
|
||||
<a href="#about" className="hover:text-primary">
|
||||
<a href="#about" className="hover:text-[#007BFF] transition">
|
||||
Sobre
|
||||
</a>
|
||||
<a href="#departments" className="hover:text-primary">
|
||||
<a href="#departments" className="hover:text-[#007BFF] transition">
|
||||
Departamentos
|
||||
</a>
|
||||
<a href="#doctors" className="hover:text-primary">
|
||||
<a href="#doctors" className="hover:text-[#007BFF] transition">
|
||||
Médicos
|
||||
</a>
|
||||
<a href="#contact" className="hover:text-primary">
|
||||
<a href="#contact" className="hover:text-[#007BFF] transition">
|
||||
Contato
|
||||
</a>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
{/* Botão de Login para telas maiores (md e acima) */}
|
||||
{/* Login Desktop */}
|
||||
<div className="hidden md:flex space-x-4">
|
||||
<Link href="/login">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="rounded-full px-6 py-2 border-2 transition cursor-pointer"
|
||||
className="rounded-full px-6 py-2 border-2 border-[#007BFF] text-[#007BFF] hover:bg-[#007BFF] hover:text-white transition cursor-pointer"
|
||||
>
|
||||
Login
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Seção principal de destaque */}
|
||||
<section className="flex flex-col md:flex-row items-center justify-between px-6 md:px-10 lg:px-20 py-16 bg-background text-center md:text-left">
|
||||
{/* Hero Section */}
|
||||
<section className="flex flex-col md:flex-row items-center justify-between px-6 md:px-10 lg:px-20 py-20 bg-gradient-to-r from-[#1E2A78] via-[#007BFF] to-[#00BFFF] text-white">
|
||||
<div className="max-w-lg mx-auto md:mx-0">
|
||||
<h2 className="text-muted-foreground uppercase text-sm">
|
||||
<h2 className="uppercase text-sm tracking-widest opacity-80">
|
||||
Bem-vindo à Saúde Digital
|
||||
</h2>
|
||||
<h1 className="text-3xl sm:text-4xl lg:text-5xl font-extrabold text-foreground leading-tight mt-2">
|
||||
<h1 className="text-4xl sm:text-5xl lg:text-6xl font-extrabold leading-tight mt-2 drop-shadow-lg">
|
||||
Soluções Médicas <br /> & Cuidados com a Saúde
|
||||
</h1>
|
||||
<p className="text-muted-foreground mt-4 text-sm sm:text-base">
|
||||
<p className="mt-4 text-base leading-relaxed opacity-90">
|
||||
Excelência em saúde há mais de 25 anos. Atendimento médico com
|
||||
qualidade, segurança e carinho.
|
||||
</p>
|
||||
<div className="mt-6 flex flex-col sm:flex-row space-y-4 sm:space-y-0 sm:space-x-4 justify-center md:justify-start">
|
||||
<Button>Nossos Serviços</Button>
|
||||
<Button variant="secondary">Saiba Mais</Button>
|
||||
<div className="mt-8 flex flex-col sm:flex-row space-y-4 sm:space-y-0 sm:space-x-4 justify-center md:justify-start">
|
||||
<Button className="px-8 py-3 text-base font-semibold bg-white text-[#1E2A78] hover:bg-[#EAF4FF] transition-all shadow-md">
|
||||
Nossos Serviços
|
||||
</Button>
|
||||
<Button className="px-8 py-3 text-base font-semibold bg-white text-[#1E2A78] hover:bg-[#EAF4FF] transition-all shadow-md">
|
||||
Saiba Mais
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-10 md:mt-0 flex justify-center">
|
||||
<img
|
||||
src="https://t4.ftcdn.net/jpg/03/20/52/31/360_F_320523164_tx7Rdd7I2XDTvvKfz2oRuRpKOPE5z0ni.jpg"
|
||||
alt="Médico"
|
||||
className="w-60 sm:w-80 lg:w-96 h-auto object-cover rounded-lg shadow-lg"
|
||||
className="w-72 sm:w-96 lg:w-[28rem] h-auto object-cover rounded-2xl shadow-xl "
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Seção de serviços */}
|
||||
<section className="py-16 px-6 md:px-10 lg:px-20 bg-card">
|
||||
<h2 className="text-center text-2xl sm:text-3xl font-bold text-foreground">
|
||||
{/* Serviços */}
|
||||
<section
|
||||
id="departments"
|
||||
className="py-20 px-6 md:px-10 lg:px-20 bg-[#F8FBFF]"
|
||||
>
|
||||
<h2 className="text-center text-3xl sm:text-4xl font-extrabold text-[#1E2A78]">
|
||||
Cuidados completos para a sua saúde
|
||||
</h2>
|
||||
<p className="text-center text-muted-foreground mt-2 text-sm sm:text-base">
|
||||
<p className="text-center text-gray-600 mt-3 text-base">
|
||||
Serviços médicos que oferecemos
|
||||
</p>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 mt-10 max-w-5xl mx-auto">
|
||||
<div className="p-6 bg-background rounded-xl shadow hover:shadow-lg transition">
|
||||
<h3 className="text-xl font-semibold text-primary">
|
||||
Clínica Geral
|
||||
</h3>
|
||||
<p className="text-muted-foreground mt-2 text-sm">
|
||||
Seu primeiro passo para o cuidado. Atendimento focado na prevenção
|
||||
e no diagnóstico inicial.
|
||||
</p>
|
||||
<Button className="mt-4 w-full">Agendar</Button>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-10 mt-12 max-w-6xl mx-auto">
|
||||
{/* Card */}
|
||||
{[
|
||||
{
|
||||
title: "Clínica Geral",
|
||||
desc: "Seu primeiro passo para o cuidado. Atendimento focado na prevenção e no diagnóstico inicial.",
|
||||
Icon: Stethoscope,
|
||||
},
|
||||
{
|
||||
title: "Pediatria",
|
||||
desc: "Cuidado gentil e especializado para garantir a saúde e o desenvolvimento de crianças e adolescentes.",
|
||||
Icon: Baby,
|
||||
},
|
||||
{
|
||||
title: "Exames",
|
||||
desc: "Resultados rápidos e precisos em exames laboratoriais e de imagem essenciais para seu diagnóstico.",
|
||||
Icon: Microscope,
|
||||
},
|
||||
].map(({ title, desc, Icon }, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="p-8 bg-white rounded-2xl shadow-md hover:shadow-xl transition-all duration-300 border border-[#E0E9FF] group"
|
||||
>
|
||||
<div className="flex items-center space-x-3">
|
||||
<Icon className="text-[#007BFF] w-6 h-6 group-hover:scale-110 transition-transform" />
|
||||
<h3 className="text-xl font-semibold">{title}</h3>
|
||||
</div>
|
||||
<div className="p-6 bg-background rounded-xl shadow hover:shadow-lg transition">
|
||||
<h3 className="text-xl font-semibold text-primary">Pediatria</h3>
|
||||
<p className="text-muted-foreground mt-2 text-sm">
|
||||
Cuidado gentil e especializado para garantir a saúde e o
|
||||
desenvolvimento de crianças e adolescentes.
|
||||
<p className="text-gray-600 mt-3 text-sm leading-relaxed">
|
||||
{desc}
|
||||
</p>
|
||||
<Button className="mt-4 w-full">Agendar</Button>
|
||||
</div>
|
||||
<div className="p-6 bg-background rounded-xl shadow hover:shadow-lg transition">
|
||||
<h3 className="text-xl font-semibold text-primary">Exames</h3>
|
||||
<p className="text-muted-foreground mt-2 text-sm">
|
||||
Resultados rápidos e precisos em exames laboratoriais e de imagem
|
||||
essenciais para seu diagnóstico.
|
||||
</p>
|
||||
<Button className="mt-4 w-full">Agendar</Button>
|
||||
<Button className="mt-6 w-full bg-[#007BFF] hover:bg-[#005FCC] text-white transition">
|
||||
Agendar
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Footer */}
|
||||
<footer className="bg-primary text-primary-foreground py-6 text-center text-sm">
|
||||
<p>© 2025 MediConnect</p>
|
||||
<footer className="bg-[#1E2A78] text-white py-8 text-center text-sm">
|
||||
<div className="space-y-2">
|
||||
<p>© 2025 MediConnect — Todos os direitos reservados</p>
|
||||
<div className="flex justify-center space-x-6 opacity-80">
|
||||
<a href="#about" className="hover:text-[#00BFFF] transition">
|
||||
Sobre
|
||||
</a>
|
||||
<a href="#departments" className="hover:text-[#00BFFF] transition">
|
||||
Serviços
|
||||
</a>
|
||||
<a href="#contact" className="hover:text-[#00BFFF] transition">
|
||||
Contato
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,8 +1,14 @@
|
||||
import { Card, CardContent, CardDescription, 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"
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
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() {
|
||||
return (
|
||||
@ -10,13 +16,17 @@ export default function PatientDashboard() {
|
||||
<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>
|
||||
<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>
|
||||
<CardTitle className="text-sm font-medium">
|
||||
Próxima Consulta
|
||||
</CardTitle>
|
||||
<Calendar className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
@ -27,12 +37,16 @@ export default function PatientDashboard() {
|
||||
|
||||
<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>
|
||||
<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">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>
|
||||
</Card>
|
||||
|
||||
@ -52,23 +66,31 @@ export default function PatientDashboard() {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Ações Rápidas</CardTitle>
|
||||
<CardDescription>Acesse rapidamente as principais funcionalidades</CardDescription>
|
||||
<CardDescription>
|
||||
Acesse rapidamente as principais funcionalidades
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<Link href="/patient/schedule">
|
||||
<Button className="w-full justify-start">
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
<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="/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" />
|
||||
Ver Minhas Consultas
|
||||
</Button>
|
||||
</Link>
|
||||
<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" />
|
||||
Atualizar Dados
|
||||
</Button>
|
||||
@ -109,5 +131,5 @@ export default function PatientDashboard() {
|
||||
</div>
|
||||
</div>
|
||||
</Sidebar>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@ -31,8 +31,12 @@ interface PatientProfileData {
|
||||
}
|
||||
|
||||
export default function PatientProfile() {
|
||||
const { user, isLoading: isAuthLoading } = useAuthLayout({ requiredRole: ["paciente", "admin", "medico", "gestor", "secretaria"] });
|
||||
const [patientData, setPatientData] = useState<PatientProfileData | null>(null);
|
||||
const { user, isLoading: isAuthLoading } = useAuthLayout({
|
||||
requiredRole: ["paciente", "admin", "medico", "gestor", "secretaria"],
|
||||
});
|
||||
const [patientData, setPatientData] = useState<PatientProfileData | null>(
|
||||
null
|
||||
);
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
@ -56,14 +60,21 @@ export default function PatientProfile() {
|
||||
});
|
||||
} 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" });
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: "Não foi possível carregar seus dados completos.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
fetchPatientDetails();
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
const handleInputChange = (field: keyof PatientProfileData, value: string) => {
|
||||
const handleInputChange = (
|
||||
field: keyof PatientProfileData,
|
||||
value: string
|
||||
) => {
|
||||
setPatientData((prev) => (prev ? { ...prev, [field]: value } : null));
|
||||
};
|
||||
|
||||
@ -82,11 +93,18 @@ export default function PatientProfile() {
|
||||
city: patientData.city,
|
||||
};
|
||||
await patientsService.update(user.id, patientPayload);
|
||||
toast({ title: "Sucesso!", description: "Seus dados foram atualizados." });
|
||||
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" });
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: "Não foi possível salvar suas alterações.",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
@ -96,7 +114,9 @@ export default function PatientProfile() {
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
|
||||
const handleAvatarUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const handleAvatarUpload = async (
|
||||
event: React.ChangeEvent<HTMLInputElement>
|
||||
) => {
|
||||
const file = event.target.files?.[0];
|
||||
if (!file || !user) return;
|
||||
|
||||
@ -108,15 +128,26 @@ export default function PatientProfile() {
|
||||
|
||||
try {
|
||||
await api.storage.upload("avatars", filePath, file);
|
||||
await api.patch(`/rest/v1/profiles?id=eq.${user.id}`, { avatar_url: filePath });
|
||||
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));
|
||||
setPatientData((prev) =>
|
||||
prev ? { ...prev, avatarFullUrl: newFullUrl } : null
|
||||
);
|
||||
|
||||
toast({ title: "Sucesso!", description: "Sua foto de perfil foi atualizada." });
|
||||
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" });
|
||||
toast({
|
||||
title: "Erro de Upload",
|
||||
description: "Não foi possível enviar sua foto.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@ -136,8 +167,16 @@ export default function PatientProfile() {
|
||||
<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
|
||||
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>
|
||||
|
||||
@ -154,16 +193,36 @@ export default function PatientProfile() {
|
||||
<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} />
|
||||
<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} />
|
||||
<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} />
|
||||
<Input
|
||||
id="birthDate"
|
||||
type="date"
|
||||
value={patientData.birthDate}
|
||||
onChange={(e) =>
|
||||
handleInputChange("birthDate", e.target.value)
|
||||
}
|
||||
disabled={!isEditing}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@ -178,31 +237,69 @@ export default function PatientProfile() {
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<Input id="email" type="email" value={patientData.email} disabled />
|
||||
<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} />
|
||||
<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} />
|
||||
<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} />
|
||||
<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} />
|
||||
<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} />
|
||||
<Input
|
||||
id="city"
|
||||
value={patientData.city}
|
||||
onChange={(e) =>
|
||||
handleInputChange("city", e.target.value)
|
||||
}
|
||||
disabled={!isEditing}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
@ -217,7 +314,10 @@ export default function PatientProfile() {
|
||||
<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}>
|
||||
<Avatar
|
||||
className="w-16 h-16 cursor-pointer"
|
||||
onClick={handleAvatarClick}
|
||||
>
|
||||
<AvatarImage src={patientData.avatarFullUrl} />
|
||||
<AvatarFallback className="text-2xl">
|
||||
{patientData.name
|
||||
@ -226,10 +326,19 @@ export default function PatientProfile() {
|
||||
.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}>
|
||||
<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" />
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
onChange={handleAvatarUpload}
|
||||
className="hidden"
|
||||
accept="image/png, image/jpeg"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">{patientData.name}</p>
|
||||
@ -247,7 +356,14 @@ export default function PatientProfile() {
|
||||
</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>
|
||||
<span>
|
||||
{patientData.birthDate
|
||||
? new Date(patientData.birthDate).toLocaleDateString(
|
||||
"pt-BR",
|
||||
{ timeZone: "UTC" }
|
||||
)
|
||||
: "Não informado"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import type React from "react"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import Link from "next/link"
|
||||
@ -9,24 +8,24 @@ import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { Eye, EyeOff, ArrowLeft } from "lucide-react"
|
||||
import { ArrowLeft, Loader2 } from "lucide-react"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { usersService } from "@/services/usersApi.mjs" // Mantém a importação
|
||||
import { isValidCPF } from "@/lib/utils"
|
||||
|
||||
export default function PatientRegister() {
|
||||
const [showPassword, setShowPassword] = useState(false)
|
||||
const [showConfirmPassword, setShowConfirmPassword] = useState(false)
|
||||
// REMOVIDO: Estados para 'showPassword' e 'showConfirmPassword'
|
||||
const [formData, setFormData] = useState({
|
||||
name: "",
|
||||
email: "",
|
||||
password: "",
|
||||
confirmPassword: "",
|
||||
phone: "",
|
||||
cpf: "",
|
||||
birthDate: "",
|
||||
address: "",
|
||||
// REMOVIDO: Campos 'password' e 'confirmPassword'
|
||||
})
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
|
||||
const handleInputChange = (field: string, value: string) => {
|
||||
setFormData((prev) => ({
|
||||
@ -37,22 +36,52 @@ export default function PatientRegister() {
|
||||
|
||||
const handleRegister = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setIsLoading(true)
|
||||
|
||||
if (formData.password !== formData.confirmPassword) {
|
||||
alert("As senhas não coincidem!")
|
||||
// --- VALIDAÇÃO DE CPF ---
|
||||
if (!isValidCPF(formData.cpf)) {
|
||||
toast({
|
||||
title: "CPF Inválido",
|
||||
description: "O CPF informado não é válido. Verifique os dígitos.",
|
||||
variant: "destructive",
|
||||
})
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
setIsLoading(true)
|
||||
// --- LÓGICA DE REGISTRO COM ENDPOINT PÚBLICO ---
|
||||
try {
|
||||
// ALTERADO: Payload ajustado para o endpoint 'register-patient'
|
||||
const payload = {
|
||||
email: formData.email.trim().toLowerCase(),
|
||||
full_name: formData.name,
|
||||
phone_mobile: formData.phone, // O endpoint espera 'phone_mobile'
|
||||
cpf: formData.cpf.replace(/\D/g, ''),
|
||||
birth_date: formData.birthDate,
|
||||
}
|
||||
|
||||
// Simulação de registro - em produção, conectar com API real
|
||||
setTimeout(() => {
|
||||
// Salvar dados do usuário no localStorage para simulação
|
||||
const { confirmPassword, ...userData } = formData
|
||||
localStorage.setItem("patientData", JSON.stringify(userData))
|
||||
router.push("/patient/dashboard")
|
||||
// ALTERADO: Chamada para a nova função de serviço
|
||||
await usersService.registerPatient(payload)
|
||||
|
||||
// ALTERADO: Mensagem de sucesso para refletir o fluxo de confirmação por e-mail
|
||||
toast({
|
||||
title: "Cadastro enviado com sucesso!",
|
||||
description: "Enviamos um link de confirmação para o seu e-mail. Por favor, verifique sua caixa de entrada para ativar sua conta.",
|
||||
})
|
||||
|
||||
// Redireciona para a página de login
|
||||
router.push("/login")
|
||||
|
||||
} catch (error: any) {
|
||||
console.error("Erro no registro:", error)
|
||||
toast({
|
||||
title: "Erro ao Criar Conta",
|
||||
description: error.message || "Não foi possível concluir o cadastro. Verifique seus dados e tente novamente.",
|
||||
variant: "destructive",
|
||||
})
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}, 1000)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
@ -67,136 +96,85 @@ export default function PatientRegister() {
|
||||
|
||||
<Card>
|
||||
<CardHeader className="text-center">
|
||||
<CardTitle className="text-2xl">Cadastro de Paciente</CardTitle>
|
||||
<CardDescription>Preencha seus dados para criar sua conta</CardDescription>
|
||||
<CardTitle className="text-2xl">Crie sua Conta de Paciente</CardTitle>
|
||||
<CardDescription>Preencha seus dados para acessar o portal MedConnect</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleRegister} className="space-y-4">
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">Nome Completo</Label>
|
||||
<Label htmlFor="name">Nome Completo *</Label>
|
||||
<Input
|
||||
id="name"
|
||||
value={formData.name}
|
||||
onChange={(e) => handleInputChange("name", e.target.value)}
|
||||
required
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="cpf">CPF</Label>
|
||||
<Label htmlFor="cpf">CPF *</Label>
|
||||
<Input
|
||||
id="cpf"
|
||||
value={formData.cpf}
|
||||
onChange={(e) => handleInputChange("cpf", e.target.value)}
|
||||
placeholder="000.000.000-00"
|
||||
required
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<Label htmlFor="email">Email *</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={formData.email}
|
||||
onChange={(e) => handleInputChange("email", e.target.value)}
|
||||
required
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="phone">Telefone</Label>
|
||||
<Label htmlFor="phone">Telefone *</Label>
|
||||
<Input
|
||||
id="phone"
|
||||
value={formData.phone}
|
||||
onChange={(e) => handleInputChange("phone", e.target.value)}
|
||||
placeholder="(11) 99999-9999"
|
||||
required
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="birthDate">Data de Nascimento</Label>
|
||||
<Label htmlFor="birthDate">Data de Nascimento *</Label>
|
||||
<Input
|
||||
id="birthDate"
|
||||
type="date"
|
||||
value={formData.birthDate}
|
||||
onChange={(e) => handleInputChange("birthDate", e.target.value)}
|
||||
required
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="address">Endereço</Label>
|
||||
<Textarea
|
||||
id="address"
|
||||
value={formData.address}
|
||||
onChange={(e) => handleInputChange("address", e.target.value)}
|
||||
placeholder="Rua, número, bairro, cidade, estado"
|
||||
rows={3}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Senha</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="password"
|
||||
type={showPassword ? "text" : "password"}
|
||||
value={formData.password}
|
||||
onChange={(e) => handleInputChange("password", e.target.value)}
|
||||
required
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
>
|
||||
{showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="confirmPassword">Confirmar Senha</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="confirmPassword"
|
||||
type={showConfirmPassword ? "text" : "password"}
|
||||
value={formData.confirmPassword}
|
||||
onChange={(e) => handleInputChange("confirmPassword", e.target.value)}
|
||||
required
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
|
||||
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
|
||||
>
|
||||
{showConfirmPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/* REMOVIDO: Seção de senha e confirmação de senha */}
|
||||
|
||||
<Button type="submit" className="w-full" disabled={isLoading}>
|
||||
{isLoading ? "Criando conta..." : "Criar Conta"}
|
||||
{isLoading ? <><Loader2 className="mr-2 h-4 w-4 animate-spin" /> Criando conta...</> : "Criar Conta"}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<div className="mt-6 text-center">
|
||||
<p className="text-sm text-gray-600">
|
||||
Já tem uma conta?{" "}
|
||||
<Link href="/patient/login" className="text-blue-600 hover:underline">
|
||||
<Link href="/login" className="text-blue-600 hover:underline">
|
||||
Faça login aqui
|
||||
</Link>
|
||||
</p>
|
||||
|
||||
@ -1,159 +1,67 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect } from "react"
|
||||
import { useState, useEffect, useMemo } from "react"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"
|
||||
import { toast } from "@/hooks/use-toast"
|
||||
import { FileText, Download, Eye, Calendar, User, X } from "lucide-react"
|
||||
import { FileText, Download, Eye, Calendar, User, X, Loader2 } from "lucide-react"
|
||||
import Sidebar from "@/components/Sidebar"
|
||||
import { useAuthLayout } from "@/hooks/useAuthLayout"
|
||||
import { reportsApi } from "@/services/reportsApi.mjs"
|
||||
|
||||
interface Report {
|
||||
id: string
|
||||
title: string
|
||||
doctor: string
|
||||
date: string
|
||||
type: string
|
||||
status: "disponivel" | "pendente"
|
||||
description: string
|
||||
content: {
|
||||
patientInfo: {
|
||||
name: string
|
||||
age: number
|
||||
gender: string
|
||||
id: string
|
||||
}
|
||||
examDetails: {
|
||||
requestingDoctor: string
|
||||
examDate: string
|
||||
reportDate: string
|
||||
technique: string
|
||||
}
|
||||
findings: string
|
||||
conclusion: string
|
||||
recommendations?: string
|
||||
}
|
||||
id: string;
|
||||
order_number: string;
|
||||
patient_id: string;
|
||||
status: string;
|
||||
exam: string;
|
||||
requested_by: string;
|
||||
cid_code: string;
|
||||
diagnosis: string;
|
||||
conclusion: string;
|
||||
content_html: string;
|
||||
content_json: any;
|
||||
hide_date: boolean;
|
||||
hide_signature: boolean;
|
||||
due_at: string;
|
||||
created_by: string;
|
||||
updated_by: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export default function ReportsPage() {
|
||||
const [reports, setReports] = useState<Report[]>([])
|
||||
const [selectedReport, setSelectedReport] = useState<Report | null>(null)
|
||||
const [isViewModalOpen, setIsViewModalOpen] = useState(false)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const requiredRole = useMemo(() => ["paciente"], []);
|
||||
const { user, isLoading: isAuthLoading } = useAuthLayout({ requiredRole });
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
const mockReports: Report[] = [
|
||||
{
|
||||
id: "1",
|
||||
title: "Exame de Sangue - Hemograma Completo",
|
||||
doctor: "Dr. João Silva",
|
||||
date: "2024-01-15",
|
||||
type: "Exame Laboratorial",
|
||||
status: "disponivel",
|
||||
description: "Hemograma completo com contagem de células sanguíneas",
|
||||
content: {
|
||||
patientInfo: {
|
||||
name: "Maria Silva Santos",
|
||||
age: 35,
|
||||
gender: "Feminino",
|
||||
id: "123.456.789-00",
|
||||
},
|
||||
examDetails: {
|
||||
requestingDoctor: "Dr. João Silva - CRM 12345",
|
||||
examDate: "15/01/2024",
|
||||
reportDate: "15/01/2024",
|
||||
technique: "Análise automatizada com confirmação microscópica",
|
||||
},
|
||||
findings:
|
||||
"Hemácias: 4.5 milhões/mm³ (VR: 4.0-5.2)\nHemoglobina: 13.2 g/dL (VR: 12.0-15.5)\nHematócrito: 40% (VR: 36-46)\nLeucócitos: 7.200/mm³ (VR: 4.000-11.000)\nPlaquetas: 280.000/mm³ (VR: 150.000-450.000)\n\nFórmula leucocitária:\n- Neutrófilos: 65% (VR: 50-70%)\n- Linfócitos: 28% (VR: 20-40%)\n- Monócitos: 5% (VR: 2-8%)\n- Eosinófilos: 2% (VR: 1-4%)",
|
||||
conclusion:
|
||||
"Hemograma dentro dos parâmetros normais. Não foram observadas alterações significativas na série vermelha, branca ou plaquetária.",
|
||||
recommendations: "Manter acompanhamento médico regular. Repetir exame conforme orientação médica.",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
title: "Radiografia do Tórax",
|
||||
doctor: "Dra. Maria Santos",
|
||||
date: "2024-01-10",
|
||||
type: "Exame de Imagem",
|
||||
status: "disponivel",
|
||||
description: "Radiografia PA e perfil do tórax",
|
||||
content: {
|
||||
patientInfo: {
|
||||
name: "Maria Silva Santos",
|
||||
age: 35,
|
||||
gender: "Feminino",
|
||||
id: "123.456.789-00",
|
||||
},
|
||||
examDetails: {
|
||||
requestingDoctor: "Dra. Maria Santos - CRM 67890",
|
||||
examDate: "10/01/2024",
|
||||
reportDate: "10/01/2024",
|
||||
technique: "Radiografia digital PA e perfil",
|
||||
},
|
||||
findings:
|
||||
"Campos pulmonares livres, sem sinais de consolidação ou derrame pleural. Silhueta cardíaca dentro dos limites normais. Estruturas ósseas íntegras. Diafragmas em posição normal.",
|
||||
conclusion: "Radiografia de tórax sem alterações patológicas evidentes.",
|
||||
recommendations: "Correlacionar com quadro clínico. Acompanhamento conforme indicação médica.",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "3",
|
||||
title: "Eletrocardiograma",
|
||||
doctor: "Dr. Carlos Oliveira",
|
||||
date: "2024-01-08",
|
||||
type: "Exame Cardiológico",
|
||||
status: "pendente",
|
||||
description: "ECG de repouso para avaliação cardíaca",
|
||||
content: {
|
||||
patientInfo: {
|
||||
name: "Maria Silva Santos",
|
||||
age: 35,
|
||||
gender: "Feminino",
|
||||
id: "123.456.789-00",
|
||||
},
|
||||
examDetails: {
|
||||
requestingDoctor: "Dr. Carlos Oliveira - CRM 54321",
|
||||
examDate: "08/01/2024",
|
||||
reportDate: "",
|
||||
technique: "ECG de repouso",
|
||||
},
|
||||
findings: "",
|
||||
conclusion: "",
|
||||
recommendations: "",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "4",
|
||||
title: "Ultrassom Abdominal",
|
||||
doctor: "Dra. Ana Costa",
|
||||
date: "2024-01-05",
|
||||
type: "Exame de Imagem",
|
||||
status: "disponivel",
|
||||
description: "Ultrassonografia do abdome total",
|
||||
content: {
|
||||
patientInfo: {
|
||||
name: "Maria Silva Santos",
|
||||
age: 35,
|
||||
gender: "Feminino",
|
||||
id: "123.456.789-00",
|
||||
},
|
||||
examDetails: {
|
||||
requestingDoctor: "Dra. Ana Costa - CRM 98765",
|
||||
examDate: "05/01/2024",
|
||||
reportDate: "05/01/2024",
|
||||
technique: "Ultrassom convencional",
|
||||
},
|
||||
findings:
|
||||
"Viscerais bem posicionadas. Rim direito e esquerdo com contornos normais. Vesícula com volume dentro do normal.",
|
||||
conclusion: "Ultrassom abdominal sem alterações patológicas evidentes.",
|
||||
recommendations: "Acompanhamento conforme indicação médica.",
|
||||
},
|
||||
},
|
||||
]
|
||||
setReports(mockReports)
|
||||
}, [])
|
||||
if (user) {
|
||||
const fetchReports = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const fetchedReports = await reportsApi.getReports(user.id);
|
||||
setReports(fetchedReports);
|
||||
} catch (error) {
|
||||
console.error("Erro ao buscar laudos:", error)
|
||||
toast({
|
||||
title: "Erro ao buscar laudos",
|
||||
description: "Não foi possível carregar os laudos. Tente novamente.",
|
||||
variant: "destructive",
|
||||
})
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
fetchReports()
|
||||
}
|
||||
}, [user?.id])
|
||||
|
||||
const handleViewReport = (reportId: string) => {
|
||||
const report = reports.find((r) => r.id === reportId)
|
||||
@ -168,100 +76,23 @@ export default function ReportsPage() {
|
||||
if (!report) return
|
||||
|
||||
try {
|
||||
// Simular loading
|
||||
toast({
|
||||
title: "Preparando download...",
|
||||
description: "Gerando PDF do laudo médico",
|
||||
})
|
||||
|
||||
// Criar conteúdo HTML do laudo para conversão em PDF
|
||||
const htmlContent = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Laudo Médico - ${report.title}</title>
|
||||
<style>
|
||||
body { font-family: Arial, sans-serif; margin: 40px; line-height: 1.6; }
|
||||
.header { text-align: center; border-bottom: 2px solid #333; padding-bottom: 20px; margin-bottom: 30px; }
|
||||
.section { margin-bottom: 25px; }
|
||||
.section-title { font-size: 16px; font-weight: bold; color: #333; margin-bottom: 10px; border-bottom: 1px solid #ccc; padding-bottom: 5px; }
|
||||
.info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px; }
|
||||
.info-item { margin-bottom: 8px; }
|
||||
.label { font-weight: bold; color: #555; }
|
||||
.content { white-space: pre-line; }
|
||||
.footer { margin-top: 40px; text-align: center; font-size: 12px; color: #666; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="header">
|
||||
<h1>LAUDO MÉDICO</h1>
|
||||
<h2>${report.title}</h2>
|
||||
<p><strong>Tipo:</strong> ${report.type}</p>
|
||||
</div>
|
||||
const htmlContent = report.content_html;
|
||||
|
||||
<div class="section">
|
||||
<div class="section-title">DADOS DO PACIENTE</div>
|
||||
<div class="info-grid">
|
||||
<div class="info-item"><span class="label">Nome:</span> ${report.content.patientInfo.name}</div>
|
||||
<div class="info-item"><span class="label">Idade:</span> ${report.content.patientInfo.age} anos</div>
|
||||
<div class="info-item"><span class="label">Sexo:</span> ${report.content.patientInfo.gender}</div>
|
||||
<div class="info-item"><span class="label">CPF:</span> ${report.content.patientInfo.id}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<div class="section-title">DETALHES DO EXAME</div>
|
||||
<div class="info-grid">
|
||||
<div class="info-item"><span class="label">Médico Solicitante:</span> ${report.content.examDetails.requestingDoctor}</div>
|
||||
<div class="info-item"><span class="label">Data do Exame:</span> ${report.content.examDetails.examDate}</div>
|
||||
<div class="info-item"><span class="label">Data do Laudo:</span> ${report.content.examDetails.reportDate}</div>
|
||||
<div class="info-item"><span class="label">Técnica:</span> ${report.content.examDetails.technique}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<div class="section-title">ACHADOS</div>
|
||||
<div class="content">${report.content.findings}</div>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<div class="section-title">CONCLUSÃO</div>
|
||||
<div class="content">${report.content.conclusion}</div>
|
||||
</div>
|
||||
|
||||
${
|
||||
report.content.recommendations
|
||||
? `
|
||||
<div class="section">
|
||||
<div class="section-title">RECOMENDAÇÕES</div>
|
||||
<div class="content">${report.content.recommendations}</div>
|
||||
</div>
|
||||
`
|
||||
: ""
|
||||
}
|
||||
|
||||
<div class="footer">
|
||||
<p>Documento gerado em ${new Date().toLocaleDateString("pt-BR")} às ${new Date().toLocaleTimeString("pt-BR")}</p>
|
||||
<p>Este é um documento médico oficial. Mantenha-o em local seguro.</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`
|
||||
|
||||
// Criar blob com o conteúdo HTML
|
||||
const blob = new Blob([htmlContent], { type: "text/html" })
|
||||
const url = URL.createObjectURL(blob)
|
||||
|
||||
// Criar link temporário para download
|
||||
const link = document.createElement("a")
|
||||
link.href = url
|
||||
link.download = `laudo-${report.title.replace(/[^a-zA-Z0-9]/g, "-").toLowerCase()}-${report.date}.html`
|
||||
link.download = `laudo-${report.order_number}.html`
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
|
||||
// Limpar URL temporária
|
||||
URL.revokeObjectURL(url)
|
||||
|
||||
toast({
|
||||
@ -283,8 +114,18 @@ export default function ReportsPage() {
|
||||
setSelectedReport(null)
|
||||
}
|
||||
|
||||
const availableReports = reports.filter((report) => report.status === "disponivel")
|
||||
const pendingReports = reports.filter((report) => report.status === "pendente")
|
||||
const availableReports = reports.filter((report) => report.status.toLowerCase() === "draft")
|
||||
const pendingReports = reports.filter((report) => report.status.toLowerCase() !== "draft")
|
||||
|
||||
if (isLoading || isAuthLoading) {
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="flex justify-center items-center h-full">
|
||||
<Loader2 className="h-8 w-8 animate-spin" />
|
||||
</div>
|
||||
</Sidebar>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Sidebar>
|
||||
@ -333,25 +174,25 @@ export default function ReportsPage() {
|
||||
<CardHeader>
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="space-y-1">
|
||||
<CardTitle className="text-lg">{report.title}</CardTitle>
|
||||
<CardTitle className="text-lg">{report.exam}</CardTitle>
|
||||
<CardDescription className="flex items-center gap-4">
|
||||
<span className="flex items-center gap-1">
|
||||
<User className="h-4 w-4" />
|
||||
{report.doctor}
|
||||
{report.requested_by}
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<Calendar className="h-4 w-4" />
|
||||
{new Date(report.date).toLocaleDateString("pt-BR")}
|
||||
{new Date(report.created_at).toLocaleDateString("pt-BR")}
|
||||
</span>
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Badge variant="secondary" className="bg-green-100 text-green-800">
|
||||
{report.type}
|
||||
Finalizado
|
||||
</Badge>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-gray-600 mb-4">{report.description}</p>
|
||||
<p className="text-gray-600 mb-4">{report.diagnosis}</p>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
@ -369,7 +210,7 @@ export default function ReportsPage() {
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<Download className="h-4 w-4" />
|
||||
Baixar PDF
|
||||
Baixar
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
@ -388,25 +229,25 @@ export default function ReportsPage() {
|
||||
<CardHeader>
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="space-y-1">
|
||||
<CardTitle className="text-lg">{report.title}</CardTitle>
|
||||
<CardTitle className="text-lg">{report.exam}</CardTitle>
|
||||
<CardDescription className="flex items-center gap-4">
|
||||
<span className="flex items-center gap-1">
|
||||
<User className="h-4 w-4" />
|
||||
{report.doctor}
|
||||
{report.requested_by}
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<Calendar className="h-4 w-4" />
|
||||
{new Date(report.date).toLocaleDateString("pt-BR")}
|
||||
{new Date(report.created_at).toLocaleDateString("pt-BR")}
|
||||
</span>
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Badge variant="secondary" className="bg-yellow-100 text-yellow-800">
|
||||
Pendente
|
||||
{report.status}
|
||||
</Badge>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-gray-600 mb-4">{report.description}</p>
|
||||
<p className="text-gray-600 mb-4">{report.diagnosis}</p>
|
||||
<p className="text-sm text-yellow-600 font-medium">
|
||||
Laudo em processamento. Você será notificado quando estiver disponível.
|
||||
</p>
|
||||
@ -417,7 +258,7 @@ export default function ReportsPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{reports.length === 0 && (
|
||||
{reports.length === 0 && !isLoading && (
|
||||
<Card className="text-center py-12">
|
||||
<CardContent>
|
||||
<FileText className="h-12 w-12 text-gray-400 mx-auto mb-4" />
|
||||
@ -432,9 +273,9 @@ export default function ReportsPage() {
|
||||
<DialogHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<DialogTitle className="text-xl font-bold">{selectedReport?.title}</DialogTitle>
|
||||
<DialogTitle className="text-xl font-bold">{selectedReport?.exam}</DialogTitle>
|
||||
<DialogDescription className="mt-1">
|
||||
{selectedReport?.type} - {selectedReport?.doctor}
|
||||
{selectedReport?.order_number}
|
||||
</DialogDescription>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" onClick={handleCloseModal} className="h-8 w-8 p-0">
|
||||
@ -444,94 +285,7 @@ export default function ReportsPage() {
|
||||
</DialogHeader>
|
||||
|
||||
{selectedReport && (
|
||||
<div className="space-y-6 mt-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Dados do Paciente</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-500">Nome</p>
|
||||
<p className="text-sm">{selectedReport.content.patientInfo.name}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-500">Idade</p>
|
||||
<p className="text-sm">{selectedReport.content.patientInfo.age} anos</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-500">Sexo</p>
|
||||
<p className="text-sm">{selectedReport.content.patientInfo.gender}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-500">CPF</p>
|
||||
<p className="text-sm">{selectedReport.content.patientInfo.id}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Detalhes do Exame</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-500">Médico Solicitante</p>
|
||||
<p className="text-sm">{selectedReport.content.examDetails.requestingDoctor}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-500">Data do Exame</p>
|
||||
<p className="text-sm">{selectedReport.content.examDetails.examDate}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-500">Data do Laudo</p>
|
||||
<p className="text-sm">{selectedReport.content.examDetails.reportDate}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-500">Técnica</p>
|
||||
<p className="text-sm">{selectedReport.content.examDetails.technique}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Achados</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="whitespace-pre-line text-sm leading-relaxed">{selectedReport.content.findings}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Conclusão</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm leading-relaxed">{selectedReport.content.conclusion}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{selectedReport.content.recommendations && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Recomendações</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm leading-relaxed">{selectedReport.content.recommendations}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<div className="flex gap-3 pt-4 border-t">
|
||||
<Button onClick={() => handleDownloadReport(selectedReport.id)} className="flex items-center gap-2">
|
||||
<Download className="h-4 w-4" />
|
||||
Baixar PDF
|
||||
</Button>
|
||||
<Button variant="outline" onClick={handleCloseModal}>
|
||||
Fechar
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-6 mt-4" dangerouslySetInnerHTML={{ __html: selectedReport.content_html }} />
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
@ -1,11 +1,25 @@
|
||||
"use client";
|
||||
|
||||
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 { Badge } from "@/components/ui/badge";
|
||||
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 Link from "next/link";
|
||||
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
||||
@ -34,7 +48,7 @@ export default function SecretaryAppointments() {
|
||||
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 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
|
||||
@ -48,8 +62,13 @@ export default function SecretaryAppointments() {
|
||||
|
||||
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" },
|
||||
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);
|
||||
@ -71,21 +90,32 @@ export default function SecretaryAppointments() {
|
||||
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' }),
|
||||
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 confirmEdit = async () => {
|
||||
if (!selectedAppointment || !editFormData.date || !editFormData.time || !editFormData.status) {
|
||||
if (
|
||||
!selectedAppointment ||
|
||||
!editFormData.date ||
|
||||
!editFormData.time ||
|
||||
!editFormData.status
|
||||
) {
|
||||
toast.error("Todos os campos são obrigatórios para a edição.");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const newScheduledAt = new Date(`${editFormData.date}T${editFormData.time}:00Z`).toISOString();
|
||||
const newScheduledAt = new Date(
|
||||
`${editFormData.date}T${editFormData.time}:00Z`
|
||||
).toISOString();
|
||||
const updatePayload = {
|
||||
scheduled_at: newScheduledAt,
|
||||
status: editFormData.status,
|
||||
@ -99,7 +129,6 @@ export default function SecretaryAppointments() {
|
||||
|
||||
setEditModal(false);
|
||||
toast.success("Consulta atualizada com sucesso!");
|
||||
|
||||
} catch (error) {
|
||||
console.error("Erro ao atualizar consulta:", error);
|
||||
toast.error("Não foi possível atualizar a consulta.");
|
||||
@ -116,7 +145,9 @@ export default function SecretaryAppointments() {
|
||||
if (!selectedAppointment) return;
|
||||
try {
|
||||
await appointmentsService.delete(selectedAppointment.id);
|
||||
setAppointments((prev) => prev.filter((apt) => apt.id !== selectedAppointment.id));
|
||||
setAppointments((prev) =>
|
||||
prev.filter((apt) => apt.id !== selectedAppointment.id)
|
||||
);
|
||||
setDeleteModal(false);
|
||||
toast.success("Consulta deletada com sucesso!");
|
||||
} catch (error) {
|
||||
@ -127,41 +158,89 @@ export default function SecretaryAppointments() {
|
||||
|
||||
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>;
|
||||
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"];
|
||||
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>
|
||||
<h1 className="text-3xl font-bold text-gray-900">Consultas Agendadas</h1>
|
||||
<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><Calendar className="mr-2 h-4 w-4" /> Agendar Nova Consulta</Button>
|
||||
<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>
|
||||
|
||||
<div className="grid gap-6">
|
||||
{isLoading ? <p>Carregando consultas...</p> : appointments.length > 0 ? (
|
||||
{isLoading ? (
|
||||
<p>Carregando consultas...</p>
|
||||
) : appointments.length > 0 ? (
|
||||
appointments.map((appointment) => (
|
||||
<Card key={appointment.id}>
|
||||
<CardHeader>
|
||||
<div className="flex justify-between items-start">
|
||||
<div>
|
||||
<CardTitle className="text-lg">{appointment.doctor.full_name}</CardTitle>
|
||||
<CardDescription>{appointment.doctor.specialty}</CardDescription>
|
||||
<CardTitle className="text-lg">
|
||||
{appointment.doctor.full_name}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{appointment.doctor.specialty}
|
||||
</CardDescription>
|
||||
</div>
|
||||
{getStatusBadge(appointment.status)}
|
||||
</div>
|
||||
@ -175,11 +254,21 @@ export default function SecretaryAppointments() {
|
||||
</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" })}
|
||||
{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" })}
|
||||
{new Date(appointment.scheduled_at).toLocaleTimeString(
|
||||
"pt-BR",
|
||||
{
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
timeZone: "UTC",
|
||||
}
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
@ -201,7 +290,7 @@ export default function SecretaryAppointments() {
|
||||
</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
|
||||
Cancelar
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
@ -1,6 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import { Card, CardContent, CardDescription,
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
@ -102,7 +105,9 @@ export default function SecretaryDashboard() {
|
||||
{/* 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>
|
||||
<p className="text-gray-600">
|
||||
Bem-vindo ao seu portal de consultas médicas
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Cards principais */}
|
||||
@ -132,12 +137,13 @@ export default function SecretaryDashboard() {
|
||||
? `Dr(a). ${firstConfirmed.doctor_name}`
|
||||
: "Médico não informado"}{" "}
|
||||
-{" "}
|
||||
{new Date(
|
||||
firstConfirmed.scheduled_at
|
||||
).toLocaleTimeString("pt-BR", {
|
||||
{new Date(firstConfirmed.scheduled_at).toLocaleTimeString(
|
||||
"pt-BR",
|
||||
{
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
})}
|
||||
}
|
||||
)}
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
@ -164,20 +170,22 @@ export default function SecretaryDashboard() {
|
||||
) : nextAgendada ? (
|
||||
<>
|
||||
<div className="text-lg font-bold text-gray-900">
|
||||
{new Date(
|
||||
nextAgendada.scheduled_at
|
||||
).toLocaleDateString("pt-BR", {
|
||||
{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", {
|
||||
{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
|
||||
@ -223,8 +231,8 @@ export default function SecretaryDashboard() {
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<Link href="/secretary/schedule">
|
||||
<Button className="w-full justify-start">
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
<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>
|
||||
@ -253,15 +261,11 @@ export default function SecretaryDashboard() {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Pacientes</CardTitle>
|
||||
<CardDescription>
|
||||
Últimos pacientes cadastrados
|
||||
</CardDescription>
|
||||
<CardDescription>Últimos pacientes cadastrados</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{loadingPatients ? (
|
||||
<p className="text-sm text-gray-500">
|
||||
Carregando pacientes...
|
||||
</p>
|
||||
<p className="text-sm text-gray-500">Carregando pacientes...</p>
|
||||
) : patients.length === 0 ? (
|
||||
<p className="text-sm text-gray-500">
|
||||
Nenhum paciente cadastrado.
|
||||
|
||||
@ -6,7 +6,7 @@ import Link from "next/link";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Plus, Edit, Trash2, Eye, Calendar, Filter, Loader2 } from "lucide-react";
|
||||
import { Plus, Edit, Trash2, Eye, Calendar, Filter, Loader2, MoreVertical } from "lucide-react";
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||
import { patientsService } from "@/services/patientsApi.mjs";
|
||||
import Sidebar from "@/components/Sidebar";
|
||||
@ -76,9 +76,7 @@ export default function PacientesPage() {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[]
|
||||
);
|
||||
}, []);
|
||||
|
||||
// 2. Efeito para aplicar filtros e calcular a lista filtrada (chama-se quando allPatients ou filtros mudam)
|
||||
useEffect(() => {
|
||||
@ -113,7 +111,6 @@ export default function PacientesPage() {
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
|
||||
// --- LÓGICA DE AÇÕES (DELETAR / VER DETALHES) ---
|
||||
|
||||
const openDetailsDialog = async (patientId: string) => {
|
||||
@ -131,9 +128,11 @@ export default function PacientesPage() {
|
||||
try {
|
||||
await patientsService.delete(patientId);
|
||||
// Atualiza a lista completa para refletir a exclusão
|
||||
setAllPatients((prev) => prev.filter((p) => String(p.id) !== String(patientId)));
|
||||
setAllPatients((prev) =>
|
||||
prev.filter((p) => String(p.id) !== String(patientId))
|
||||
);
|
||||
} catch (e: any) {
|
||||
alert(`Erro ao deletar paciente: ${e?.message || 'Erro desconhecido'}`);
|
||||
alert(`Erro ao deletar paciente: ${e?.message || "Erro desconhecido"}`);
|
||||
}
|
||||
setDeleteDialogOpen(false);
|
||||
setPatientToDelete(null);
|
||||
@ -150,12 +149,16 @@ export default function PacientesPage() {
|
||||
{/* Header (Responsividade OK) */}
|
||||
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-xl md:text-2xl font-bold text-foreground">Pacientes</h1>
|
||||
<p className="text-muted-foreground text-sm md:text-base">Gerencie as informações de seus pacientes</p>
|
||||
<h1 className="text-xl md:text-2xl font-bold text-foreground">
|
||||
Pacientes
|
||||
</h1>
|
||||
<p className="text-muted-foreground text-sm md:text-base">
|
||||
Gerencie as informações de seus pacientes
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Link href="/secretary/pacientes/novo" className="w-full md:w-auto">
|
||||
<Button className="w-full bg-green-600 hover:bg-green-700">
|
||||
<Button className="w-full bg-blue-600 hover:bg-blue-700">
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Adicionar
|
||||
</Button>
|
||||
@ -173,15 +176,18 @@ export default function PacientesPage() {
|
||||
placeholder="Buscar por nome ou telefone..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
// w-full no mobile, depois flex-grow para ocupar o espaço disponível
|
||||
className="w-full sm:flex-grow sm:max-w-[300px] p-2 border rounded-md text-sm"
|
||||
className="w-full sm:flex-grow sm:min-w-[150px] p-2 border rounded-md text-sm"
|
||||
/>
|
||||
|
||||
{/* Convênio - Ocupa a largura total em telas pequenas, depois se ajusta */}
|
||||
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[200px]">
|
||||
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">Convênio</span>
|
||||
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">
|
||||
Convênio
|
||||
</span>
|
||||
<Select value={convenioFilter} onValueChange={setConvenioFilter}>
|
||||
<SelectTrigger className="w-full sm:w-40"> {/* w-full para mobile, w-40 para sm+ */}
|
||||
<SelectTrigger className="w-full sm:w-40">
|
||||
{" "}
|
||||
{/* w-full para mobile, w-40 para sm+ */}
|
||||
<SelectValue placeholder="Convênio" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@ -209,79 +215,122 @@ export default function PacientesPage() {
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Aniversariantes - Ocupa 100% no mobile, e se alinha à direita no md+ */}
|
||||
<Button variant="outline" className="w-full md:w-auto md:ml-auto">
|
||||
<Calendar className="w-4 h-4 mr-2" />
|
||||
Aniversariantes
|
||||
</Button>
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
{/* --- SEÇÃO DE TABELA (VISÍVEL EM TELAS MAIORES OU IGUAIS A MD) --- */}
|
||||
{/* Garantir que a tabela se esconda em telas menores e apareça em MD+ */}
|
||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md hidden md:block">
|
||||
<div className="overflow-x-auto"> {/* Permite rolagem horizontal se a tabela for muito larga */}
|
||||
<div className="overflow-x-auto">
|
||||
{" "}
|
||||
{/* Permite rolagem horizontal se a tabela for muito larga */}
|
||||
{error ? (
|
||||
<div className="p-6 text-red-600">{`Erro ao carregar pacientes: ${error}`}</div>
|
||||
) : loading ? (
|
||||
<div className="p-6 text-center text-gray-500 flex items-center justify-center">
|
||||
<Loader2 className="w-6 h-6 mr-2 animate-spin text-green-600" /> Carregando pacientes...
|
||||
<Loader2 className="w-6 h-6 mr-2 animate-spin text-green-600" />{" "}
|
||||
Carregando pacientes...
|
||||
</div>
|
||||
) : (
|
||||
<table className="w-full min-w-[650px]"> {/* min-w para evitar que a tabela se contraia demais */}
|
||||
<table className="w-full min-w-[650px]">
|
||||
{" "}
|
||||
{/* min-w para evitar que a tabela se contraia demais */}
|
||||
<thead className="bg-gray-50 border-b border-gray-200">
|
||||
<tr>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[20%]">Nome</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[20%]">
|
||||
Nome
|
||||
</th>
|
||||
{/* Ajustes de visibilidade de colunas para diferentes breakpoints */}
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">Telefone</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden md:table-cell">Cidade / Estado</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">Convênio</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">Último atendimento</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">Próximo atendimento</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[5%]">Ações</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">
|
||||
Telefone
|
||||
</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden md:table-cell">
|
||||
Cidade / Estado
|
||||
</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">
|
||||
Convênio
|
||||
</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">
|
||||
Último atendimento
|
||||
</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">
|
||||
Próximo atendimento
|
||||
</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[5%]">
|
||||
Ações
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{currentPatients.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={7} className="p-8 text-center text-gray-500">
|
||||
{allPatients.length === 0 ? "Nenhum paciente cadastrado" : "Nenhum paciente encontrado com os filtros aplicados"}
|
||||
{allPatients.length === 0
|
||||
? "Nenhum paciente cadastrado"
|
||||
: "Nenhum paciente encontrado com os filtros aplicados"}
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
currentPatients.map((patient) => (
|
||||
<tr key={patient.id} className="border-b border-gray-100 hover:bg-gray-50">
|
||||
<tr
|
||||
key={patient.id}
|
||||
className="border-b border-gray-100 hover:bg-gray-50"
|
||||
>
|
||||
<td className="p-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
|
||||
<span className="text-green-600 font-medium text-sm">{patient.nome?.charAt(0) || "?"}</span>
|
||||
<div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
|
||||
<span className="text-blue-600 font-medium text-sm">
|
||||
{patient.nome?.charAt(0) || "?"}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<span className="font-medium text-gray-900">
|
||||
{patient.nome}
|
||||
{patient.vip && (
|
||||
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-600 bg-purple-100 rounded-full">VIP</span>
|
||||
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-600 bg-purple-100 rounded-full">
|
||||
VIP
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="p-4 text-gray-600 hidden sm:table-cell">{patient.telefone}</td>
|
||||
<td className="p-4 text-gray-600 hidden sm:table-cell">
|
||||
{patient.telefone}
|
||||
</td>
|
||||
<td className="p-4 text-gray-600 hidden md:table-cell">{`${patient.cidade} / ${patient.estado}`}</td>
|
||||
<td className="p-4 text-gray-600 hidden sm:table-cell">{patient.convenio}</td>
|
||||
<td className="p-4 text-gray-600 hidden lg:table-cell">{patient.ultimoAtendimento}</td>
|
||||
<td className="p-4 text-gray-600 hidden lg:table-cell">{patient.proximoAtendimento}</td>
|
||||
<td className="p-4 text-gray-600 hidden sm:table-cell">
|
||||
{patient.convenio}
|
||||
</td>
|
||||
<td className="p-4 text-gray-600 hidden lg:table-cell">
|
||||
{patient.ultimoAtendimento}
|
||||
</td>
|
||||
<td className="p-4 text-gray-600 hidden lg:table-cell">
|
||||
{patient.proximoAtendimento}
|
||||
</td>
|
||||
|
||||
<td className="p-4">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<div className="text-blue-600 cursor-pointer">Ações</div>
|
||||
<div className="text-blue-600 cursor-pointer">
|
||||
Ações
|
||||
</div>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => openDetailsDialog(String(patient.id))}>
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
openDetailsDialog(String(patient.id))
|
||||
}
|
||||
>
|
||||
<Eye className="w-4 h-4 mr-2" />
|
||||
Ver detalhes
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/secretary/pacientes/${patient.id}/editar`} className="flex items-center w-full">
|
||||
<Link
|
||||
href={`/secretary/pacientes/${patient.id}/editar`}
|
||||
className="flex items-center w-full"
|
||||
>
|
||||
<Edit className="w-4 h-4 mr-2" />
|
||||
Editar
|
||||
</Link>
|
||||
@ -291,7 +340,12 @@ export default function PacientesPage() {
|
||||
<Calendar className="w-4 h-4 mr-2" />
|
||||
Marcar consulta
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(String(patient.id))}>
|
||||
<DropdownMenuItem
|
||||
className="text-red-600"
|
||||
onClick={() =>
|
||||
openDeleteDialog(String(patient.id))
|
||||
}
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
Excluir
|
||||
</DropdownMenuItem>
|
||||
@ -314,32 +368,50 @@ export default function PacientesPage() {
|
||||
<div className="p-6 text-red-600">{`Erro ao carregar pacientes: ${error}`}</div>
|
||||
) : loading ? (
|
||||
<div className="p-6 text-center text-gray-500 flex items-center justify-center">
|
||||
<Loader2 className="w-6 h-6 mr-2 animate-spin text-green-600" /> Carregando pacientes...
|
||||
<Loader2 className="w-6 h-6 mr-2 animate-spin text-green-600" />{" "}
|
||||
Carregando pacientes...
|
||||
</div>
|
||||
) : filteredPatients.length === 0 ? (
|
||||
<div className="p-8 text-center text-gray-500">
|
||||
{allPatients.length === 0 ? "Nenhum paciente cadastrado" : "Nenhum paciente encontrado com os filtros aplicados"}
|
||||
{allPatients.length === 0
|
||||
? "Nenhum paciente cadastrado"
|
||||
: "Nenhum paciente encontrado com os filtros aplicados"}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{currentPatients.map((patient) => (
|
||||
<div key={patient.id} className="bg-gray-50 rounded-lg p-4 flex flex-col sm:flex-row justify-between items-start sm:items-center border border-gray-200">
|
||||
<div
|
||||
key={patient.id}
|
||||
className="bg-gray-50 rounded-lg p-4 flex flex-col sm:flex-row justify-between items-start sm:items-center border border-gray-200"
|
||||
>
|
||||
<div className="flex-grow mb-2 sm:mb-0">
|
||||
<div className="font-semibold text-lg text-gray-900 flex items-center">
|
||||
{patient.nome}
|
||||
{patient.vip && (
|
||||
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-600 bg-purple-100 rounded-full">VIP</span>
|
||||
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-600 bg-purple-100 rounded-full">
|
||||
VIP
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-sm text-gray-600">Telefone: {patient.telefone}</div>
|
||||
<div className="text-sm text-gray-600">Convênio: {patient.convenio}</div>
|
||||
<div className="text-sm text-gray-600">
|
||||
Telefone: {patient.telefone}
|
||||
</div>
|
||||
<div className="text-sm text-gray-600">
|
||||
Convênio: {patient.convenio}
|
||||
</div>
|
||||
</div>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<div className="w-full"><Button variant="outline" className="w-full">Ações</Button></div>
|
||||
<div className="w-full">
|
||||
<Button variant="outline" className="w-full">
|
||||
Ações
|
||||
</Button>
|
||||
</div>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => openDetailsDialog(String(patient.id))}>
|
||||
<DropdownMenuItem
|
||||
onClick={() => openDetailsDialog(String(patient.id))}
|
||||
>
|
||||
<Eye className="w-4 h-4 mr-2" />
|
||||
Ver detalhes
|
||||
</DropdownMenuItem>
|
||||
@ -422,7 +494,10 @@ export default function PacientesPage() {
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
||||
<AlertDialog
|
||||
open={detailsDialogOpen}
|
||||
onOpenChange={setDetailsDialogOpen}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Detalhes do Paciente</AlertDialogTitle>
|
||||
|
||||
@ -40,7 +40,12 @@ export function LoginForm({ children }: LoginFormProps) {
|
||||
*/
|
||||
const handleRoleSelection = (selectedDashboardRole: string, user: any) => {
|
||||
if (!user) {
|
||||
toast({ title: "Erro de Sessão", description: "Não foi possível encontrar os dados do usuário. Tente novamente.", variant: "destructive" });
|
||||
toast({
|
||||
title: "Erro de Sessão",
|
||||
description:
|
||||
"Não foi possível encontrar os dados do usuário. Tente novamente.",
|
||||
variant: "destructive",
|
||||
});
|
||||
setUserRoles([]);
|
||||
return;
|
||||
}
|
||||
@ -48,23 +53,40 @@ export function LoginForm({ children }: LoginFormProps) {
|
||||
const roleInLowerCase = selectedDashboardRole.toLowerCase();
|
||||
console.log("Salvando no localStorage com o perfil:", roleInLowerCase);
|
||||
|
||||
const completeUserInfo = { ...user, user_metadata: { ...user.user_metadata, role: roleInLowerCase } };
|
||||
const completeUserInfo = {
|
||||
...user,
|
||||
user_metadata: { ...user.user_metadata, role: roleInLowerCase },
|
||||
};
|
||||
localStorage.setItem("user_info", JSON.stringify(completeUserInfo));
|
||||
|
||||
let redirectPath = "";
|
||||
switch (selectedDashboardRole) {
|
||||
case "gestor": redirectPath = "/manager/dashboard"; break;
|
||||
case "admin": redirectPath = "/manager/dashboard"; break;
|
||||
case "medico": redirectPath = "/doctor/dashboard"; break;
|
||||
case "secretaria": redirectPath = "/secretary/dashboard"; break;
|
||||
case "paciente": redirectPath = "/patient/dashboard"; break;
|
||||
case "gestor":
|
||||
redirectPath = "/manager/dashboard";
|
||||
break;
|
||||
case "admin":
|
||||
redirectPath = "/manager/dashboard";
|
||||
break;
|
||||
case "medico":
|
||||
redirectPath = "/doctor/dashboard";
|
||||
break;
|
||||
case "secretaria":
|
||||
redirectPath = "/secretary/dashboard";
|
||||
break;
|
||||
case "paciente":
|
||||
redirectPath = "/patient/dashboard";
|
||||
break;
|
||||
}
|
||||
|
||||
if (redirectPath) {
|
||||
toast({ title: `Entrando como ${selectedDashboardRole}...` });
|
||||
router.push(redirectPath);
|
||||
} else {
|
||||
toast({ title: "Erro", description: "Perfil selecionado inválido.", variant: "destructive" });
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: "Perfil selecionado inválido.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@ -81,23 +103,29 @@ export function LoginForm({ children }: LoginFormProps) {
|
||||
throw new Error("Resposta de autenticação inválida.");
|
||||
}
|
||||
|
||||
const rolesData = await api.get(`/rest/v1/user_roles?user_id=eq.${user.id}&select=role`);
|
||||
const rolesData = await api.get(
|
||||
`/rest/v1/user_roles?user_id=eq.${user.id}&select=role`
|
||||
);
|
||||
|
||||
const me = await usersService.getMeSimple()
|
||||
console.log(me.roles)
|
||||
const me = await usersService.getMeSimple();
|
||||
console.log(me.roles);
|
||||
|
||||
if (!me.roles || me.roles.length === 0) {
|
||||
throw new Error("Nenhum perfil de acesso foi encontrado para este usuário.");
|
||||
throw new Error(
|
||||
"Nenhum perfil de acesso foi encontrado para este usuário."
|
||||
);
|
||||
}
|
||||
|
||||
handleRoleSelection(me.roles[0], user);
|
||||
|
||||
} catch (error) {
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("user_info");
|
||||
toast({
|
||||
title: "Erro no Login",
|
||||
description: error instanceof Error ? error.message : "Ocorreu um erro inesperado.",
|
||||
description:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Ocorreu um erro inesperado.",
|
||||
variant: "destructive",
|
||||
});
|
||||
setIsLoading(false);
|
||||
@ -105,7 +133,8 @@ export function LoginForm({ children }: LoginFormProps) {
|
||||
};
|
||||
|
||||
// Estado para guardar os botões de seleção de perfil
|
||||
const [roleSelectionUI, setRoleSelectionUI] = useState<React.ReactNode | null>(null);
|
||||
const [roleSelectionUI, setRoleSelectionUI] =
|
||||
useState<React.ReactNode | null>(null);
|
||||
|
||||
return (
|
||||
<Card className="w-full bg-transparent border-0 shadow-none">
|
||||
@ -116,30 +145,78 @@ export function LoginForm({ children }: LoginFormProps) {
|
||||
<Label htmlFor="email">E-mail</Label>
|
||||
<div className="relative">
|
||||
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground w-5 h-5" />
|
||||
<Input id="email" type="email" placeholder="seu.email@exemplo.com" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} className="pl-10 h-11" required disabled={isLoading} autoComplete="username" />
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="seu.email@exemplo.com"
|
||||
value={form.email}
|
||||
onChange={(e) => setForm({ ...form, email: e.target.value })}
|
||||
className="pl-10 h-11 focus-visible:ring-blue-600 focus-visible:ring-2"
|
||||
required
|
||||
disabled={isLoading}
|
||||
autoComplete="username"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Senha</Label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground w-5 h-5" />
|
||||
<Input id="password" type={showPassword ? "text" : "password"} placeholder="Digite sua senha" value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} className="pl-10 pr-12 h-11" required disabled={isLoading} autoComplete="current-password" />
|
||||
<button type="button" onClick={() => setShowPassword(!showPassword)} className="absolute right-2 top-1/2 -translate-y-1/2 h-8 w-8 p-0 text-muted-foreground hover:text-foreground" disabled={isLoading}>
|
||||
{showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
|
||||
<Input
|
||||
id="password"
|
||||
type={showPassword ? "text" : "password"}
|
||||
placeholder="Digite sua senha"
|
||||
value={form.password}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, password: e.target.value })
|
||||
}
|
||||
className="pl-10 pr-12 h-11 focus-visible:ring-blue-600 focus-visible:ring-2"
|
||||
required
|
||||
disabled={isLoading}
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 h-8 w-8 p-0 text-muted-foreground hover:text-foreground"
|
||||
disabled={isLoading}
|
||||
>
|
||||
{showPassword ? (
|
||||
<EyeOff className="w-5 h-5" />
|
||||
) : (
|
||||
<Eye className="w-5 h-5" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<Button type="submit" className="w-full h-11 text-base font-semibold" disabled={isLoading}>
|
||||
{isLoading ? <Loader2 className="w-5 h-5 animate-spin" /> : "Entrar"}
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full h-11 bg-blue-600 hover:bg-blue-700 text-white"
|
||||
disabled={isLoading}
|
||||
>
|
||||
{isLoading ? (
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
) : (
|
||||
"Entrar"
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
) : (
|
||||
<div className="space-y-4 animate-in fade-in-50">
|
||||
<h3 className="text-lg font-medium text-center text-foreground">Você tem múltiplos perfis</h3>
|
||||
<p className="text-sm text-muted-foreground text-center">Selecione com qual perfil deseja entrar:</p>
|
||||
<h3 className="text-lg font-medium text-center text-foreground">
|
||||
Você tem múltiplos perfis
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground text-center">
|
||||
Selecione com qual perfil deseja entrar:
|
||||
</p>
|
||||
<div className="flex flex-col space-y-3 pt-2">
|
||||
{userRoles.map((role) => (
|
||||
<Button key={role} variant="outline" className="h-11 text-base" onClick={() => handleRoleSelection(role, authenticatedUser)}>
|
||||
<Button
|
||||
key={role}
|
||||
variant="outline"
|
||||
className="h-11 text-base"
|
||||
onClick={() => handleRoleSelection(role, authenticatedUser)}
|
||||
>
|
||||
Entrar como: {role.charAt(0).toUpperCase() + role.slice(1)}
|
||||
</Button>
|
||||
))}
|
||||
|
||||
@ -5,13 +5,10 @@ import type React from "react";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useRouter, usePathname } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import Cookies from "js-cookie"; // Mantido apenas para a limpeza de segurança no logout
|
||||
import Cookies from "js-cookie";
|
||||
import { api } from "@/services/api.mjs";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@ -20,18 +17,14 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
|
||||
import {
|
||||
Search,
|
||||
Bell,
|
||||
Calendar,
|
||||
User,
|
||||
LogOut,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Home,
|
||||
CalendarCheck2,
|
||||
ClipboardPlus,
|
||||
SquareUserRound,
|
||||
CalendarClock,
|
||||
Users,
|
||||
SquareUser,
|
||||
@ -39,6 +32,7 @@ import {
|
||||
Stethoscope,
|
||||
ClipboardMinus,
|
||||
} from "lucide-react";
|
||||
|
||||
import SidebarUserSection from "@/components/ui/userToolTip";
|
||||
|
||||
interface UserData {
|
||||
@ -83,7 +77,6 @@ export default function Sidebar({ children }: SidebarProps) {
|
||||
|
||||
useEffect(() => {
|
||||
const userInfoString = localStorage.getItem("user_info");
|
||||
// --- ALTERAÇÃO 1: Buscando o token no localStorage ---
|
||||
const token = localStorage.getItem("token");
|
||||
|
||||
if (userInfoString && token) {
|
||||
@ -113,7 +106,6 @@ export default function Sidebar({ children }: SidebarProps) {
|
||||
});
|
||||
setRole(userInfo.user_metadata?.role);
|
||||
} else {
|
||||
// O redirecionamento para /login já estava correto. Ótimo!
|
||||
router.push("/login");
|
||||
}
|
||||
}, [router]);
|
||||
@ -133,21 +125,17 @@ export default function Sidebar({ children }: SidebarProps) {
|
||||
|
||||
const handleLogout = () => setShowLogoutDialog(true);
|
||||
|
||||
// --- ALTERAÇÃO 2: A função de logout agora é MUITO mais simples ---
|
||||
const confirmLogout = async () => {
|
||||
try {
|
||||
// Chama a função centralizada para fazer o logout no servidor
|
||||
await api.logout();
|
||||
} catch (error) {
|
||||
// O erro já é logado dentro da função api.logout, não precisamos fazer nada aqui
|
||||
} finally {
|
||||
// A responsabilidade do componente é apenas limpar o estado local e redirecionar
|
||||
localStorage.removeItem("user_info");
|
||||
localStorage.removeItem("token");
|
||||
Cookies.remove("access_token"); // Limpeza de segurança
|
||||
Cookies.remove("access_token");
|
||||
|
||||
setShowLogoutDialog(false);
|
||||
router.push("/"); // Redireciona para a home
|
||||
router.push("/");
|
||||
}
|
||||
};
|
||||
|
||||
@ -202,35 +190,25 @@ export default function Sidebar({ children }: SidebarProps) {
|
||||
|
||||
const managerItems: MenuItem[] = [
|
||||
{ href: "/manager/dashboard", icon: Home, label: "Dashboard" },
|
||||
{ href: "#", icon: ClipboardMinus, label: "Relatórios gerenciais" },
|
||||
{ href: "/manager/usuario", icon: Users, label: "Gestão de Usuários" },
|
||||
{ href: "/manager/home", icon: Stethoscope, label: "Gestão de Médicos" },
|
||||
{ href: "/manager/pacientes", icon: Users, label: "Gestão de Pacientes" },
|
||||
{ href: "/doctor/consultas", icon: CalendarCheck2, label: "Consultas" }, //adicionar botão de voltar pra pagina anterior
|
||||
{ href: "/secretary/appointments", icon: CalendarCheck2, label: "Consultas" },
|
||||
{ href: "/manager/disponibilidade", icon: ClipboardList, label: "Disponibilidade" },
|
||||
];
|
||||
|
||||
let menuItems: MenuItem[];
|
||||
switch (role) {
|
||||
case "gestor":
|
||||
menuItems = managerItems;
|
||||
break;
|
||||
case "admin":
|
||||
menuItems = managerItems;
|
||||
break;
|
||||
return managerItems;
|
||||
case "medico":
|
||||
menuItems = doctorItems;
|
||||
break;
|
||||
return doctorItems;
|
||||
case "secretaria":
|
||||
menuItems = secretaryItems;
|
||||
break;
|
||||
return secretaryItems;
|
||||
case "paciente":
|
||||
menuItems = patientItems;
|
||||
break;
|
||||
default:
|
||||
menuItems = patientItems;
|
||||
break;
|
||||
return patientItems;
|
||||
}
|
||||
return menuItems;
|
||||
};
|
||||
|
||||
const menuItems = SetMenuItems(role);
|
||||
@ -246,48 +224,59 @@ export default function Sidebar({ children }: SidebarProps) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 flex">
|
||||
<div
|
||||
className={`bg-white border-r border-gray-200 transition-all duration-300 fixed top-0 h-screen flex flex-col z-30 ${
|
||||
sidebarCollapsed ? "w-16" : "w-64"
|
||||
}`}
|
||||
className={`fixed top-0 h-screen flex flex-col z-30 transition-all duration-300
|
||||
${sidebarCollapsed ? "w-16" : "w-64"}
|
||||
bg-[#123965] text-white`}
|
||||
>
|
||||
<div className="p-4 border-b border-gray-200 flex items-center justify-between">
|
||||
{/* TOPO */}
|
||||
<div className="p-4 border-b border-white/10 flex items-center justify-between">
|
||||
{!sidebarCollapsed && (
|
||||
<div className="flex items-center gap-2">
|
||||
{/* 🛑 SUBSTITUIÇÃO: Usando a tag <img> com o caminho da logo */}
|
||||
<div className="bg-white p-1 rounded-lg">
|
||||
<img
|
||||
src="/Logo MedConnect.png" // Use o arquivo da logo (ou /android-chrome-512x512.png)
|
||||
alt="Logo MediConnect"
|
||||
className="w-12 h-12 object-contain" // Define o tamanho para w-8 h-8 (32px)
|
||||
src="/Logo MedConnect.png"
|
||||
alt="Logo MedConnect"
|
||||
className="w-12 h-12 object-contain"
|
||||
/>
|
||||
<span className="font-semibold text-gray-900">MedConnect</span>
|
||||
</div>
|
||||
|
||||
<span className="font-semibold text-white text-lg">
|
||||
MedConnect
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
|
||||
className="p-1"
|
||||
className="p-1 text-white hover:bg-white/10 cursor-pointer"
|
||||
>
|
||||
{sidebarCollapsed ? (
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
<ChevronRight className="w-5 h-5" />
|
||||
) : (
|
||||
<ChevronLeft className="w-4 h-4" />
|
||||
<ChevronLeft className="w-5 h-5" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<nav className="flex-1 p-2 overflow-y-auto">
|
||||
{/* MENU */}
|
||||
<nav className="flex-1 p-3 overflow-y-auto">
|
||||
{menuItems.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const isActive = pathname === item.href;
|
||||
|
||||
return (
|
||||
<Link key={item.label} href={item.href}>
|
||||
<div
|
||||
className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${
|
||||
className={`
|
||||
flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors
|
||||
${
|
||||
isActive
|
||||
? "bg-blue-50 text-blue-600 border-r-2 border-blue-600"
|
||||
: "text-gray-600 hover:bg-gray-50"
|
||||
}`}
|
||||
? "bg-white/20 text-white font-semibold"
|
||||
: "text-white/80 hover:bg-white/10 hover:text-white"
|
||||
}
|
||||
`}
|
||||
>
|
||||
<Icon className="w-5 h-5 flex-shrink-0" />
|
||||
{!sidebarCollapsed && (
|
||||
@ -298,30 +287,31 @@ export default function Sidebar({ children }: SidebarProps) {
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
|
||||
{/* PERFIL ORIGINAL + NOME BRANCO */}
|
||||
<div className="mt-auto p-3 border-t border-white/10">
|
||||
<SidebarUserSection
|
||||
userData={userData}
|
||||
sidebarCollapsed={false}
|
||||
sidebarCollapsed={sidebarCollapsed}
|
||||
handleLogout={handleLogout}
|
||||
isActive={role === "paciente" ? false : true}
|
||||
></SidebarUserSection>
|
||||
isActive={role !== "paciente"}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={`flex-1 flex flex-col transition-all duration-300 w-full ${
|
||||
className={`flex-1 flex flex-col transition-all duration-300 ${
|
||||
sidebarCollapsed ? "ml-16" : "ml-64"
|
||||
}`}
|
||||
>
|
||||
<header className="bg-gray-50 px-4 md:px-6 py-4 flex items-center justify-between"></header>
|
||||
<main className="flex-1 p-4 md:p-6">{children}</main>
|
||||
</div>
|
||||
|
||||
<Dialog open={showLogoutDialog} onOpenChange={setShowLogoutDialog}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Confirmar Saída</DialogTitle>
|
||||
<DialogDescription>
|
||||
Deseja realmente sair do sistema? Você precisará fazer login
|
||||
novamente para acessar sua conta.
|
||||
novamente.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter className="flex gap-2">
|
||||
@ -335,6 +325,7 @@ export default function Sidebar({ children }: SidebarProps) {
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@ -9,25 +9,50 @@ import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Calendar as CalendarShadcn } from "@/components/ui/calendar";
|
||||
import { format, addDays } from "date-fns";
|
||||
import { User, StickyNote, Calendar } from "lucide-react";
|
||||
import {smsService } from "@/services/Sms.mjs"
|
||||
import { User, StickyNote, Check, ChevronsUpDown } from "lucide-react";
|
||||
import { smsService } from "@/services/Sms.mjs";
|
||||
import { toast } from "@/hooks/use-toast";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
// Componentes do Combobox (Barra de Pesquisa)
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
} from "@/components/ui/command";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
|
||||
export default function ScheduleForm() {
|
||||
// Estado do usuário e role
|
||||
const [role, setRole] = useState<string>("paciente");
|
||||
const [userId, setUserId] = useState<string | null>(null);
|
||||
const [role, setRole] = useState<string>("paciente")
|
||||
const [userId, setUserId] = useState<string | null>(null)
|
||||
|
||||
// Listas e seleções
|
||||
const [patients, setPatients] = useState<any[]>([]);
|
||||
const [selectedPatient, setSelectedPatient] = useState("");
|
||||
const [openPatientCombobox, setOpenPatientCombobox] = useState(false);
|
||||
|
||||
const [doctors, setDoctors] = useState<any[]>([]);
|
||||
const [selectedDoctor, setSelectedDoctor] = useState("");
|
||||
const [openDoctorCombobox, setOpenDoctorCombobox] = useState(false); // Novo estado para médico
|
||||
|
||||
const [selectedDate, setSelectedDate] = useState("");
|
||||
const [selectedTime, setSelectedTime] = useState("");
|
||||
const [notes, setNotes] = useState("");
|
||||
@ -36,192 +61,186 @@ export default function ScheduleForm() {
|
||||
const [loadingSlots, setLoadingSlots] = useState(false);
|
||||
|
||||
// Outras configs
|
||||
const [tipoConsulta] = useState("presencial");
|
||||
const [duracao] = useState("30");
|
||||
const [disponibilidades, setDisponibilidades] = useState<any[]>([]);
|
||||
const [availabilityCounts, setAvailabilityCounts] = useState<Record<string, number>>({});
|
||||
const [tooltip, setTooltip] = useState<{ x: number; y: number; text: string } | null>(null);
|
||||
const calendarRef = useRef<HTMLDivElement | null>(null);
|
||||
const [tipoConsulta] = useState("presencial")
|
||||
const [duracao] = useState("30")
|
||||
const [disponibilidades, setDisponibilidades] = useState<any[]>([])
|
||||
const [availabilityCounts, setAvailabilityCounts] = useState<Record<string, number>>({})
|
||||
const [tooltip, setTooltip] = useState<{ x: number; y: number; text: string } | null>(null)
|
||||
const calendarRef = useRef<HTMLDivElement | null>(null)
|
||||
|
||||
// Funções auxiliares
|
||||
const getWeekdayNumber = (weekday: string) =>
|
||||
["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
|
||||
.indexOf(weekday.toLowerCase()) + 1;
|
||||
["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"].indexOf(weekday.toLowerCase()) + 1
|
||||
|
||||
const getBrazilDate = (date: Date) =>
|
||||
new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), 12, 0, 0));
|
||||
new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), 12, 0, 0))
|
||||
|
||||
// 🔹 Buscar dados do usuário e role
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
;(async () => {
|
||||
try {
|
||||
const me = await usersService.getMe();
|
||||
const currentRole = me?.roles?.[0] || "paciente";
|
||||
setRole(currentRole);
|
||||
setUserId(me?.user?.id || null);
|
||||
const me = await usersService.getMe()
|
||||
const currentRole = me?.roles?.[0] || "paciente"
|
||||
setRole(currentRole)
|
||||
setUserId(me?.user?.id || null)
|
||||
|
||||
if (["secretaria", "gestor", "admin"].includes(currentRole)) {
|
||||
const pats = await patientsService.list();
|
||||
setPatients(pats || []);
|
||||
const pats = await patientsService.list()
|
||||
setPatients(pats || [])
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Erro ao carregar usuário:", err);
|
||||
console.error("Erro ao carregar usuário:", err)
|
||||
}
|
||||
})();
|
||||
}, []);
|
||||
})()
|
||||
}, [])
|
||||
|
||||
// 🔹 Buscar médicos
|
||||
const fetchDoctors = useCallback(async () => {
|
||||
setLoadingDoctors(true);
|
||||
setLoadingDoctors(true)
|
||||
try {
|
||||
const data = await doctorsService.list();
|
||||
setDoctors(data || []);
|
||||
const data = await doctorsService.list()
|
||||
setDoctors(data || [])
|
||||
} catch (err) {
|
||||
console.error("Erro ao buscar médicos:", err);
|
||||
toast({ title: "Erro", description: "Não foi possível carregar médicos." });
|
||||
console.error("Erro ao buscar médicos:", err)
|
||||
toast({ title: "Erro", description: "Não foi possível carregar médicos." })
|
||||
} finally {
|
||||
setLoadingDoctors(false);
|
||||
setLoadingDoctors(false)
|
||||
}
|
||||
}, []);
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
fetchDoctors();
|
||||
}, [fetchDoctors]);
|
||||
fetchDoctors()
|
||||
}, [fetchDoctors])
|
||||
|
||||
// 🔹 Buscar disponibilidades
|
||||
const loadDoctorDisponibilidades = useCallback(async (doctorId?: string) => {
|
||||
if (!doctorId) return;
|
||||
if (!doctorId) return
|
||||
try {
|
||||
const disp = await AvailabilityService.listById(doctorId);
|
||||
setDisponibilidades(disp || []);
|
||||
await computeAvailabilityCountsPreview(doctorId, disp || []);
|
||||
const disp = await AvailabilityService.listById(doctorId)
|
||||
setDisponibilidades(disp || [])
|
||||
await computeAvailabilityCountsPreview(doctorId, disp || [])
|
||||
} catch (err) {
|
||||
console.error("Erro ao buscar disponibilidades:", err);
|
||||
setDisponibilidades([]);
|
||||
console.error("Erro ao buscar disponibilidades:", err)
|
||||
setDisponibilidades([])
|
||||
}
|
||||
}, []);
|
||||
}, [])
|
||||
|
||||
const computeAvailabilityCountsPreview = async (doctorId: string, dispList: any[]) => {
|
||||
const computeAvailabilityCountsPreview = async (
|
||||
doctorId: string,
|
||||
dispList: any[]
|
||||
) => {
|
||||
try {
|
||||
const today = new Date();
|
||||
const start = format(today, "yyyy-MM-dd");
|
||||
const endDate = addDays(today, 90);
|
||||
const end = format(endDate, "yyyy-MM-dd");
|
||||
const today = new Date()
|
||||
const start = format(today, "yyyy-MM-dd")
|
||||
const endDate = addDays(today, 90)
|
||||
const end = format(endDate, "yyyy-MM-dd")
|
||||
|
||||
const appointments = await appointmentsService.search_appointment(
|
||||
`doctor_id=eq.${doctorId}&scheduled_at=gte.${start}T00:00:00Z&scheduled_at=lt.${end}T23:59:59Z`
|
||||
);
|
||||
`doctor_id=eq.${doctorId}&scheduled_at=gte.${start}T00:00:00Z&scheduled_at=lt.${end}T23:59:59Z`,
|
||||
)
|
||||
|
||||
const apptsByDate: Record<string, number> = {};
|
||||
(appointments || []).forEach((a: any) => {
|
||||
const d = String(a.scheduled_at).split("T")[0];
|
||||
apptsByDate[d] = (apptsByDate[d] || 0) + 1;
|
||||
});
|
||||
const apptsByDate: Record<string, number> = {}
|
||||
;(appointments || []).forEach((a: any) => {
|
||||
const d = String(a.scheduled_at).split("T")[0]
|
||||
apptsByDate[d] = (apptsByDate[d] || 0) + 1
|
||||
})
|
||||
|
||||
const counts: Record<string, number> = {};
|
||||
const counts: Record<string, number> = {}
|
||||
for (let i = 0; i <= 90; i++) {
|
||||
const d = addDays(today, i);
|
||||
const key = format(d, "yyyy-MM-dd");
|
||||
const dayOfWeek = d.getDay() === 0 ? 7 : d.getDay();
|
||||
const dailyDisp = dispList.filter((p) => getWeekdayNumber(p.weekday) === dayOfWeek);
|
||||
const d = addDays(today, i)
|
||||
const key = format(d, "yyyy-MM-dd")
|
||||
const dayOfWeek = d.getDay() === 0 ? 7 : d.getDay()
|
||||
const dailyDisp = dispList.filter((p) => getWeekdayNumber(p.weekday) === dayOfWeek)
|
||||
if (dailyDisp.length === 0) {
|
||||
counts[key] = 0;
|
||||
continue;
|
||||
counts[key] = 0
|
||||
continue
|
||||
}
|
||||
let possible = 0;
|
||||
let possible = 0
|
||||
dailyDisp.forEach((p) => {
|
||||
const [sh, sm] = p.start_time.split(":").map(Number);
|
||||
const [eh, em] = p.end_time.split(":").map(Number);
|
||||
const startMin = sh * 60 + sm;
|
||||
const endMin = eh * 60 + em;
|
||||
const slot = p.slot_minutes || 30;
|
||||
if (endMin >= startMin) possible += Math.floor((endMin - startMin) / slot) + 1;
|
||||
});
|
||||
const occupied = apptsByDate[key] || 0;
|
||||
counts[key] = Math.max(0, possible - occupied);
|
||||
const [sh, sm] = p.start_time.split(":").map(Number)
|
||||
const [eh, em] = p.end_time.split(":").map(Number)
|
||||
const startMin = sh * 60 + sm
|
||||
const endMin = eh * 60 + em
|
||||
const slot = p.slot_minutes || 30
|
||||
if (endMin >= startMin) possible += Math.floor((endMin - startMin) / slot) + 1
|
||||
})
|
||||
const occupied = apptsByDate[key] || 0
|
||||
counts[key] = Math.max(0, possible - occupied)
|
||||
}
|
||||
setAvailabilityCounts(counts);
|
||||
setAvailabilityCounts(counts)
|
||||
} catch (err) {
|
||||
console.error("Erro ao calcular contagens:", err);
|
||||
setAvailabilityCounts({});
|
||||
console.error("Erro ao calcular contagens:", err)
|
||||
setAvailabilityCounts({})
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 🔹 Quando médico muda
|
||||
useEffect(() => {
|
||||
if (selectedDoctor) {
|
||||
loadDoctorDisponibilidades(selectedDoctor);
|
||||
loadDoctorDisponibilidades(selectedDoctor)
|
||||
} else {
|
||||
setDisponibilidades([]);
|
||||
setAvailabilityCounts({});
|
||||
setDisponibilidades([])
|
||||
setAvailabilityCounts({})
|
||||
}
|
||||
setSelectedDate("");
|
||||
setSelectedTime("");
|
||||
setAvailableTimes([]);
|
||||
}, [selectedDoctor, loadDoctorDisponibilidades]);
|
||||
setSelectedDate("")
|
||||
setSelectedTime("")
|
||||
setAvailableTimes([])
|
||||
}, [selectedDoctor, loadDoctorDisponibilidades])
|
||||
|
||||
// 🔹 Buscar horários disponíveis
|
||||
const fetchAvailableSlots = useCallback(async (doctorId: string, date: string) => {
|
||||
if (!doctorId || !date) return;
|
||||
setLoadingSlots(true);
|
||||
setAvailableTimes([]);
|
||||
if (!doctorId || !date) return
|
||||
setLoadingSlots(true)
|
||||
setAvailableTimes([])
|
||||
try {
|
||||
const disponibilidades = await AvailabilityService.listById(doctorId);
|
||||
const disponibilidades = await AvailabilityService.listById(doctorId)
|
||||
const consultas = await appointmentsService.search_appointment(
|
||||
`doctor_id=eq.${doctorId}&scheduled_at=gte.${date}T00:00:00Z&scheduled_at=lt.${date}T23:59:59Z`
|
||||
);
|
||||
const diaJS = new Date(date).getDay();
|
||||
const diaAPI = diaJS === 0 ? 7 : diaJS;
|
||||
const disponibilidadeDia = disponibilidades.find(
|
||||
(d: any) => getWeekdayNumber(d.weekday) === diaAPI
|
||||
);
|
||||
`doctor_id=eq.${doctorId}&scheduled_at=gte.${date}T00:00:00Z&scheduled_at=lt.${date}T23:59:59Z`,
|
||||
)
|
||||
const diaJS = new Date(date).getDay()
|
||||
const diaAPI = diaJS === 0 ? 7 : diaJS
|
||||
const disponibilidadeDia = disponibilidades.find((d: any) => getWeekdayNumber(d.weekday) === diaAPI)
|
||||
if (!disponibilidadeDia) {
|
||||
toast({ title: "Nenhuma disponibilidade", description: "Nenhum horário para este dia." });
|
||||
return setAvailableTimes([]);
|
||||
toast({ title: "Nenhuma disponibilidade", description: "Nenhum horário para este dia." })
|
||||
return setAvailableTimes([])
|
||||
}
|
||||
const [startHour, startMin] = disponibilidadeDia.start_time.split(":").map(Number);
|
||||
const [endHour, endMin] = disponibilidadeDia.end_time.split(":").map(Number);
|
||||
const slot = disponibilidadeDia.slot_minutes || 30;
|
||||
const horariosGerados: string[] = [];
|
||||
let atual = new Date(date);
|
||||
atual.setHours(startHour, startMin, 0, 0);
|
||||
const end = new Date(date);
|
||||
end.setHours(endHour, endMin, 0, 0);
|
||||
const [startHour, startMin] = disponibilidadeDia.start_time.split(":").map(Number)
|
||||
const [endHour, endMin] = disponibilidadeDia.end_time.split(":").map(Number)
|
||||
const slot = disponibilidadeDia.slot_minutes || 30
|
||||
const horariosGerados: string[] = []
|
||||
let atual = new Date(date)
|
||||
atual.setHours(startHour, startMin, 0, 0)
|
||||
const end = new Date(date)
|
||||
end.setHours(endHour, endMin, 0, 0)
|
||||
while (atual <= end) {
|
||||
horariosGerados.push(atual.toTimeString().slice(0, 5));
|
||||
atual = new Date(atual.getTime() + slot * 60000);
|
||||
horariosGerados.push(atual.toTimeString().slice(0, 5))
|
||||
atual = new Date(atual.getTime() + slot * 60000)
|
||||
}
|
||||
const ocupados = (consultas || []).map((c: any) =>
|
||||
String(c.scheduled_at).split("T")[1]?.slice(0, 5)
|
||||
);
|
||||
const livres = horariosGerados.filter((h) => !ocupados.includes(h));
|
||||
setAvailableTimes(livres);
|
||||
const ocupados = (consultas || []).map((c: any) => String(c.scheduled_at).split("T")[1]?.slice(0, 5))
|
||||
const livres = horariosGerados.filter((h) => !ocupados.includes(h))
|
||||
setAvailableTimes(livres)
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
toast({ title: "Erro", description: "Falha ao carregar horários." });
|
||||
console.error(err)
|
||||
toast({ title: "Erro", description: "Falha ao carregar horários." })
|
||||
} finally {
|
||||
setLoadingSlots(false);
|
||||
setLoadingSlots(false)
|
||||
}
|
||||
}, []);
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedDoctor && selectedDate) fetchAvailableSlots(selectedDoctor, selectedDate);
|
||||
}, [selectedDoctor, selectedDate, fetchAvailableSlots]);
|
||||
if (selectedDoctor && selectedDate) fetchAvailableSlots(selectedDoctor, selectedDate)
|
||||
}, [selectedDoctor, selectedDate, fetchAvailableSlots])
|
||||
|
||||
// 🔹 Submeter agendamento
|
||||
// 🔹 Submeter agendamento
|
||||
// 🔹 Submeter agendamento
|
||||
// 🔹 Submeter agendamento
|
||||
// 🔹 Submeter agendamento
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
e.preventDefault()
|
||||
|
||||
const isSecretaryLike = ["secretaria", "admin", "gestor"].includes(role);
|
||||
const patientId = isSecretaryLike ? selectedPatient : userId;
|
||||
const isSecretaryLike = ["secretaria", "admin", "gestor"].includes(role)
|
||||
const patientId = isSecretaryLike ? selectedPatient : userId
|
||||
|
||||
if (!patientId || !selectedDoctor || !selectedDate || !selectedTime) {
|
||||
toast({ title: "Campos obrigatórios", description: "Preencha todos os campos." });
|
||||
return;
|
||||
toast({ title: "Campos obrigatórios", description: "Preencha todos os campos." })
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
@ -232,9 +251,8 @@ const handleSubmit = async (e: React.FormEvent) => {
|
||||
duration_minutes: Number(duracao),
|
||||
notes,
|
||||
appointment_type: tipoConsulta,
|
||||
};
|
||||
}
|
||||
|
||||
// ✅ mantém o fluxo original de criação (funcional)
|
||||
await appointmentsService.create(body);
|
||||
|
||||
const dateFormatted = selectedDate.split("-").reverse().join("/");
|
||||
@ -246,53 +264,42 @@ const handleSubmit = async (e: React.FormEvent) => {
|
||||
}.`,
|
||||
});
|
||||
|
||||
let phoneNumber = "+5511999999999"; // fallback
|
||||
let phoneNumber = "+5511999999999";
|
||||
|
||||
try {
|
||||
if (isSecretaryLike) {
|
||||
// Secretária/admin → telefone do paciente selecionado
|
||||
const patient = patients.find((p: any) => p.id === patientId);
|
||||
|
||||
// Pacientes criados no sistema podem ter phone ou phone_mobile
|
||||
const rawPhone = patient?.phone || patient?.phone_mobile || null;
|
||||
|
||||
if (rawPhone) phoneNumber = rawPhone;
|
||||
const patient = patients.find((p: any) => p.id === patientId)
|
||||
const rawPhone = patient?.phone || patient?.phone_mobile || null
|
||||
if (rawPhone) phoneNumber = rawPhone
|
||||
} else {
|
||||
// Paciente → telefone vem do perfil do próprio usuário logado
|
||||
const me = await usersService.getMe();
|
||||
|
||||
|
||||
const me = await usersService.getMe()
|
||||
const rawPhone =
|
||||
me?.profile?.phone ||
|
||||
(typeof me?.profile === "object" && "phone_mobile" in me.profile ? (me.profile as any).phone_mobile : null) ||
|
||||
(typeof me?.profile === "object" && "phone_mobile" in me.profile
|
||||
? (me.profile as any).phone_mobile
|
||||
: null) ||
|
||||
(typeof me === "object" && "user_metadata" in me ? (me as any).user_metadata?.phone : null) ||
|
||||
null;
|
||||
|
||||
if (rawPhone) phoneNumber = rawPhone;
|
||||
null
|
||||
if (rawPhone) phoneNumber = rawPhone
|
||||
}
|
||||
|
||||
// 🔹 Normaliza para formato internacional (+55)
|
||||
if (phoneNumber) {
|
||||
phoneNumber = phoneNumber.replace(/\D/g, "");
|
||||
if (!phoneNumber.startsWith("55")) phoneNumber = `55${phoneNumber}`;
|
||||
phoneNumber = `+${phoneNumber}`;
|
||||
phoneNumber = phoneNumber.replace(/\D/g, "")
|
||||
if (!phoneNumber.startsWith("55")) phoneNumber = `55${phoneNumber}`
|
||||
phoneNumber = `+${phoneNumber}`
|
||||
}
|
||||
|
||||
console.log("📞 Telefone usado:", phoneNumber);
|
||||
console.log("📞 Telefone usado:", phoneNumber)
|
||||
} catch (err) {
|
||||
console.warn("⚠️ Não foi possível obter telefone do paciente:", err);
|
||||
console.warn("⚠️ Não foi possível obter telefone do paciente:", err)
|
||||
}
|
||||
|
||||
|
||||
// 💬 envia o SMS de confirmação
|
||||
// 💬 Envia o SMS de lembrete (sem mostrar nada ao paciente)
|
||||
// 💬 Envia o SMS de lembrete (somente loga no console, não mostra no sistema)
|
||||
try {
|
||||
const smsRes = await smsService.sendSms({
|
||||
phone_number: phoneNumber,
|
||||
message: `Lembrete: sua consulta é em ${dateFormatted} às ${selectedTime} na Clínica MediConnect.`,
|
||||
patient_id: patientId,
|
||||
});
|
||||
})
|
||||
|
||||
if (smsRes?.success) {
|
||||
console.log("✅ SMS enviado com sucesso:", smsRes.message_sid);
|
||||
@ -303,9 +310,6 @@ try {
|
||||
console.error("❌ Erro ao enviar SMS:", smsErr);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
// 🧹 limpa os campos
|
||||
setSelectedDoctor("");
|
||||
setSelectedDate("");
|
||||
@ -318,75 +322,83 @@ try {
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// 🔹 Tooltip no calendário
|
||||
useEffect(() => {
|
||||
const cont = calendarRef.current;
|
||||
if (!cont) return;
|
||||
const cont = calendarRef.current
|
||||
if (!cont) return
|
||||
const onMove = (ev: MouseEvent) => {
|
||||
const target = ev.target as HTMLElement | null;
|
||||
const btn = target?.closest("button");
|
||||
if (!btn) return setTooltip(null);
|
||||
const aria = btn.getAttribute("aria-label") || btn.textContent || "";
|
||||
const parsed = new Date(aria);
|
||||
if (isNaN(parsed.getTime())) return setTooltip(null);
|
||||
const key = format(getBrazilDate(parsed), "yyyy-MM-dd");
|
||||
const count = availabilityCounts[key] ?? 0;
|
||||
const target = ev.target as HTMLElement | null
|
||||
const btn = target?.closest("button")
|
||||
if (!btn) return setTooltip(null)
|
||||
const aria = btn.getAttribute("aria-label") || btn.textContent || ""
|
||||
const parsed = new Date(aria)
|
||||
if (isNaN(parsed.getTime())) return setTooltip(null)
|
||||
const key = format(getBrazilDate(parsed), "yyyy-MM-dd")
|
||||
const count = availabilityCounts[key] ?? 0
|
||||
setTooltip({
|
||||
x: ev.pageX + 10,
|
||||
y: ev.pageY + 10,
|
||||
text: `${count} horário${count !== 1 ? "s" : ""} disponíveis`,
|
||||
});
|
||||
};
|
||||
const onLeave = () => setTooltip(null);
|
||||
cont.addEventListener("mousemove", onMove);
|
||||
cont.addEventListener("mouseleave", onLeave);
|
||||
})
|
||||
}
|
||||
const onLeave = () => setTooltip(null)
|
||||
cont.addEventListener("mousemove", onMove)
|
||||
cont.addEventListener("mouseleave", onLeave)
|
||||
return () => {
|
||||
cont.removeEventListener("mousemove", onMove);
|
||||
cont.removeEventListener("mouseleave", onLeave);
|
||||
};
|
||||
}, [availabilityCounts]);
|
||||
cont.removeEventListener("mousemove", onMove)
|
||||
cont.removeEventListener("mouseleave", onLeave)
|
||||
}
|
||||
}, [availabilityCounts])
|
||||
|
||||
return (
|
||||
<div className="max-w-6xl mx-auto space-y-4 px-4">
|
||||
<h1 className="text-2xl font-semibold">Agendar Consulta</h1>
|
||||
<div className="py-3 px-2">
|
||||
<div className="max-w-7xl mx-auto space-y-3">
|
||||
<div className="space-y-1">
|
||||
<h1 className="text-3xl font-bold text-slate-900">Agendar Consulta</h1>
|
||||
<p className="text-slate-600">Selecione o médico, data e horário para sua consulta</p>
|
||||
</div>
|
||||
|
||||
<Card className="border rounded-xl shadow-sm">
|
||||
<CardHeader>
|
||||
<CardTitle>Dados da Consulta</CardTitle>
|
||||
<div className="grid lg:grid-cols-[1fr,380px] gap-4">
|
||||
{/* Coluna do Formulário */}
|
||||
<form onSubmit={handleSubmit} className="space-y-3">
|
||||
<Card className="border shadow-sm">
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-lg">Informações Básicas</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<div className="space-y-3">
|
||||
{/* Se secretária/gestor/admin → mostrar campo Paciente */}
|
||||
<CardContent className="space-y-3">
|
||||
{["secretaria", "gestor", "admin"].includes(role) && (
|
||||
<div>
|
||||
<Label>Paciente</Label>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="patient-select" className="text-sm font-medium">
|
||||
Paciente
|
||||
</Label>
|
||||
<Select value={selectedPatient} onValueChange={setSelectedPatient}>
|
||||
<SelectTrigger>
|
||||
<SelectTrigger id="patient-select">
|
||||
<SelectValue placeholder="Selecione o paciente" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{patients.map((p) => (
|
||||
<SelectItem key={p.id} value={p.id}>{p.full_name}</SelectItem>
|
||||
<SelectItem key={p.id} value={p.id}>
|
||||
{p.full_name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<Label>Médico</Label>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="doctor-select" className="text-sm font-medium">
|
||||
Médico
|
||||
</Label>
|
||||
<Select value={selectedDoctor} onValueChange={setSelectedDoctor}>
|
||||
<SelectTrigger>
|
||||
<SelectTrigger id="doctor-select">
|
||||
<SelectValue placeholder="Selecione o médico" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{loadingDoctors ? (
|
||||
<SelectItem value="loading" disabled>Carregando...</SelectItem>
|
||||
<SelectItem value="loading" disabled>
|
||||
Carregando...
|
||||
</SelectItem>
|
||||
) : (
|
||||
doctors.map((d) => (
|
||||
<SelectItem key={d.id} value={d.id}>
|
||||
@ -397,112 +409,152 @@ try {
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div>
|
||||
<Label>Data</Label>
|
||||
<div ref={calendarRef} className="rounded-lg border p-2">
|
||||
<Card className="border shadow-sm">
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-lg">Selecione a Data</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div ref={calendarRef} className="flex justify-center">
|
||||
<CalendarShadcn
|
||||
mode="single"
|
||||
disabled={!selectedDoctor}
|
||||
selected={selectedDate ? new Date(selectedDate + "T12:00:00") : undefined}
|
||||
selected={
|
||||
selectedDate
|
||||
? new Date(selectedDate + "T12:00:00")
|
||||
: undefined
|
||||
}
|
||||
onSelect={(date) => {
|
||||
if (!date) return;
|
||||
const formatted = format(new Date(date.getTime() + 12 * 60 * 60 * 1000), "yyyy-MM-dd");
|
||||
setSelectedDate(formatted);
|
||||
if (!date) return
|
||||
const formatted = format(new Date(date.getTime() + 12 * 60 * 60 * 1000), "yyyy-MM-dd")
|
||||
setSelectedDate(formatted)
|
||||
}}
|
||||
className="rounded-md"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div>
|
||||
<Label>Observações</Label>
|
||||
<Card className="border shadow-sm">
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-lg">Observações (Opcional)</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Textarea
|
||||
placeholder="Instruções para o médico..."
|
||||
placeholder="Adicione instruções ou informações importantes para o médico..."
|
||||
value={notes}
|
||||
onChange={(e) => setNotes(e.target.value)}
|
||||
className="mt-2"
|
||||
rows={4}
|
||||
className="resize-none"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</form>
|
||||
|
||||
<div className="space-y-3">
|
||||
<Card className="shadow-md rounded-xl bg-blue-50 border border-blue-200">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-blue-700">Resumo</CardTitle>
|
||||
<Card className="border-2 border-blue-200 shadow-lg bg-gradient-to-br from-blue-50 to-white sticky top-6">
|
||||
<CardHeader className="pb-3 border-b border-blue-100">
|
||||
<CardTitle className="text-blue-900 flex items-center gap-2">
|
||||
<User className="h-5 w-5" />
|
||||
Resumo da Consulta
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 text-gray-900 text-sm">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<User className="h-4 w-4 text-blue-600" />
|
||||
<div className="text-xs">
|
||||
{selectedDoctor
|
||||
? doctors.find((d) => d.id === selectedDoctor)?.full_name
|
||||
: "Médico"}
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">
|
||||
{tipoConsulta} • {duracao} min
|
||||
<CardContent className="pt-3 space-y-3">
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs font-medium text-slate-600">Médico</p>
|
||||
<p className="text-sm font-semibold text-slate-900">
|
||||
{selectedDoctor ? doctors.find((d) => d.id === selectedDoctor)?.full_name : "Não selecionado"}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs font-medium text-slate-600">Data</p>
|
||||
<p className="text-sm font-semibold text-slate-900">
|
||||
{selectedDate ? format(new Date(selectedDate + "T12:00:00"), "dd/MM/yyyy") : "Não selecionada"}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Horário</Label>
|
||||
<Select onValueChange={setSelectedTime} disabled={loadingSlots || availableTimes.length === 0}>
|
||||
<SelectTrigger>
|
||||
<Label htmlFor="time-select" className="text-xs font-medium text-slate-600">
|
||||
Horário
|
||||
</Label>
|
||||
<Select
|
||||
value={selectedTime}
|
||||
onValueChange={setSelectedTime}
|
||||
disabled={loadingSlots || availableTimes.length === 0}
|
||||
>
|
||||
<SelectTrigger id="time-select" className="bg-white">
|
||||
<SelectValue
|
||||
placeholder={
|
||||
loadingSlots
|
||||
? "Carregando horários..."
|
||||
? "Carregando..."
|
||||
: availableTimes.length === 0
|
||||
? "Nenhum horário disponível"
|
||||
: "Selecione o horário"
|
||||
? "Nenhum horário"
|
||||
: "Escolha o horário"
|
||||
}
|
||||
/>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{availableTimes.map((h) => (
|
||||
<SelectItem key={h} value={h}>{h}</SelectItem>
|
||||
<SelectItem key={h} value={h}>
|
||||
{h}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="pt-3 border-t border-blue-100 space-y-2">
|
||||
<div className="flex justify-between text-xs">
|
||||
<span className="text-slate-600">Tipo:</span>
|
||||
<span className="font-medium text-slate-900 capitalize">{tipoConsulta}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-xs">
|
||||
<span className="text-slate-600">Duração:</span>
|
||||
<span className="font-medium text-slate-900">{duracao} minutos</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{notes && (
|
||||
<div className="flex items-start gap-2 text-sm">
|
||||
<StickyNote className="h-4 w-4" />
|
||||
<div className="italic text-gray-700">{notes}</div>
|
||||
<div className="pt-3 border-t border-blue-100">
|
||||
<div className="flex items-start gap-2">
|
||||
<StickyNote className="h-4 w-4 text-blue-600 mt-0.5 flex-shrink-0" />
|
||||
<p className="text-xs italic text-slate-700 line-clamp-3">{notes}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<div className="pt-2 space-y-2">
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full md:w-auto px-4 py-1.5 text-sm bg-blue-600 text-white hover:bg-blue-700"
|
||||
onClick={handleSubmit}
|
||||
className="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium shadow-md"
|
||||
disabled={!selectedDoctor || !selectedDate || !selectedTime}
|
||||
>
|
||||
Agendar
|
||||
Confirmar Agendamento
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setSelectedDoctor("");
|
||||
setSelectedDate("");
|
||||
setSelectedTime("");
|
||||
setNotes("");
|
||||
setSelectedPatient("");
|
||||
setSelectedDoctor("")
|
||||
setSelectedDate("")
|
||||
setSelectedTime("")
|
||||
setNotes("")
|
||||
setSelectedPatient("")
|
||||
}}
|
||||
className="px-3"
|
||||
className="w-full"
|
||||
>
|
||||
Limpar
|
||||
Limpar Formulário
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{tooltip && (
|
||||
<div
|
||||
@ -513,14 +565,16 @@ try {
|
||||
zIndex: 60,
|
||||
background: "rgba(0,0,0,0.85)",
|
||||
color: "white",
|
||||
padding: "6px 8px",
|
||||
padding: "6px 10px",
|
||||
borderRadius: 6,
|
||||
fontSize: 12,
|
||||
fontWeight: 500,
|
||||
pointerEvents: "none",
|
||||
}}
|
||||
>
|
||||
{tooltip.text}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
105
components/ui/WeeklyScheduleCard.tsx
Normal file
105
components/ui/WeeklyScheduleCard.tsx
Normal file
@ -0,0 +1,105 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card";
|
||||
import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
||||
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||
|
||||
type Availability = {
|
||||
id: string;
|
||||
doctor_id: string;
|
||||
weekday: string;
|
||||
start_time: string;
|
||||
end_time: string;
|
||||
slot_minutes: number;
|
||||
appointment_type: string;
|
||||
active: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
created_by: string;
|
||||
updated_by: string | null;
|
||||
};
|
||||
|
||||
interface WeeklyScheduleProps {
|
||||
doctorId?: string;
|
||||
}
|
||||
|
||||
export default function WeeklyScheduleCard({ doctorId }: WeeklyScheduleProps) {
|
||||
const [schedule, setSchedule] = useState<Record<string, { start: string; end: string }[]>>({});
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const weekdaysPT: Record<string, string> = {
|
||||
sunday: "Domingo",
|
||||
monday: "Segunda",
|
||||
tuesday: "Terça",
|
||||
wednesday: "Quarta",
|
||||
thursday: "Quinta",
|
||||
friday: "Sexta",
|
||||
saturday: "Sábado",
|
||||
};
|
||||
|
||||
const formatTime = (time?: string | null) => time?.split(":")?.slice(0, 2).join(":") ?? "";
|
||||
|
||||
function formatAvailability(data: Availability[]) {
|
||||
const grouped = data.reduce((acc: any, item) => {
|
||||
const { weekday, start_time, end_time } = item;
|
||||
|
||||
if (!acc[weekday]) acc[weekday] = [];
|
||||
|
||||
acc[weekday].push({ start: start_time, end: end_time });
|
||||
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
return grouped;
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const fetchSchedule = async () => {
|
||||
try {
|
||||
const availabilityList = await AvailabilityService.list();
|
||||
|
||||
const filtered = availabilityList.filter((a: Availability) => a.doctor_id == doctorId);
|
||||
|
||||
const formatted = formatAvailability(filtered);
|
||||
setSchedule(formatted);
|
||||
} catch (err) {
|
||||
console.error("Erro ao carregar horários:", err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchSchedule();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="space-y-4 grid md:grid-cols-7 gap-2">
|
||||
{loading ? (
|
||||
<p className="text-sm text-gray-500 col-span-7 text-center">Carregando...</p>
|
||||
) : (
|
||||
["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "Saturday"].map((day) => {
|
||||
const times = schedule[day] || [];
|
||||
return (
|
||||
<div key={day} className="space-y-4">
|
||||
<div className="flex flex-col items-center justify-between p-3 bg-blue-50 rounded-lg">
|
||||
<p className="font-medium capitalize">{weekdaysPT[day]}</p>
|
||||
<div className="text-center">
|
||||
{times.length > 0 ? (
|
||||
times.map((t, i) => (
|
||||
<p key={i} className="text-sm text-gray-600">
|
||||
{formatTime(t.start)} <br /> {formatTime(t.end)}
|
||||
</p>
|
||||
))
|
||||
) : (
|
||||
<p className="text-sm text-gray-400 italic">Sem horário</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -41,8 +41,10 @@ export interface ButtonProps
|
||||
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
({ className, variant, size, asChild = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : 'button'
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
ref={ref}
|
||||
{...props}
|
||||
|
||||
115
components/ui/filter-bar.tsx
Normal file
115
components/ui/filter-bar.tsx
Normal file
@ -0,0 +1,115 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import { Search, Filter, X } from "lucide-react";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
|
||||
export interface FilterOption {
|
||||
label: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
export interface FilterConfig {
|
||||
key: string; // O nome do estado que vai guardar esse valor (ex: 'specialty')
|
||||
label: string; // O placeholder do select (ex: 'Especialidade')
|
||||
options: FilterOption[] | string[]; // Opções do dropdown
|
||||
}
|
||||
|
||||
interface FilterBarProps {
|
||||
onSearch: (term: string) => void;
|
||||
searchTerm: string;
|
||||
searchPlaceholder?: string;
|
||||
filters?: FilterConfig[];
|
||||
activeFilters: Record<string, string>;
|
||||
onFilterChange: (key: string, value: string) => void;
|
||||
onClearFilters?: () => void;
|
||||
className?: string;
|
||||
children?: React.ReactNode; // Para botões extras (ex: "Novo Médico", paginação)
|
||||
}
|
||||
|
||||
export function FilterBar({
|
||||
onSearch,
|
||||
searchTerm,
|
||||
searchPlaceholder = "Pesquisar...",
|
||||
filters = [],
|
||||
activeFilters,
|
||||
onFilterChange,
|
||||
onClearFilters,
|
||||
children,
|
||||
className,
|
||||
}: FilterBarProps) {
|
||||
|
||||
// Verifica se tem algum filtro ativo para mostrar o botão de limpar
|
||||
const hasActiveFilters =
|
||||
searchTerm !== "" ||
|
||||
Object.values(activeFilters).some(val => val !== "all" && val !== "");
|
||||
|
||||
return (
|
||||
<div className={`flex flex-col md:flex-row items-start md:items-center gap-3 bg-white p-4 rounded-lg border border-gray-200 ${className}`}>
|
||||
|
||||
{/* Barra de Pesquisa */}
|
||||
<div className="relative w-full md:flex-1">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
|
||||
<Input
|
||||
placeholder={searchPlaceholder}
|
||||
value={searchTerm}
|
||||
onChange={(e) => onSearch(e.target.value)}
|
||||
className="pl-10 w-full bg-gray-50 border-gray-200 focus:bg-white transition-colors"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Filtros Dinâmicos (Selects) */}
|
||||
<div className="flex flex-wrap items-center gap-3 w-full md:w-auto">
|
||||
{filters.map((filter) => (
|
||||
<div key={filter.key} className="w-full sm:w-auto">
|
||||
<Select
|
||||
value={activeFilters[filter.key] || "all"}
|
||||
onValueChange={(value) => onFilterChange(filter.key, value)}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-[180px]">
|
||||
<SelectValue placeholder={filter.label} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todos: {filter.label}</SelectItem>
|
||||
{filter.options.map((opt) => {
|
||||
// Suporta tanto array de strings quanto array de objetos {label, value}
|
||||
const value = typeof opt === 'string' ? opt : opt.value;
|
||||
const label = typeof opt === 'string' ? opt : opt.label;
|
||||
return (
|
||||
<SelectItem key={value} value={value}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
);
|
||||
})}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Botão de Limpar Filtros */}
|
||||
{hasActiveFilters && onClearFilters && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={onClearFilters}
|
||||
className="text-gray-500 hover:text-red-600"
|
||||
title="Limpar filtros"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Botões Extras (ex: Novo Médico, Paginação) passados como children */}
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,94 +1,145 @@
|
||||
'use client'
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter, DialogClose
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
interface Paciente {
|
||||
id: string;
|
||||
nome: string;
|
||||
telefone: string;
|
||||
cidade: string;
|
||||
estado: string;
|
||||
email?: string;
|
||||
birth_date?: string;
|
||||
cpf?: string;
|
||||
blood_type?: string;
|
||||
weight_kg?: number;
|
||||
height_m?: number;
|
||||
street?: string;
|
||||
number?: string;
|
||||
complement?: string;
|
||||
neighborhood?: string;
|
||||
cep?: string;
|
||||
[key: string]: any; // Para permitir outras propriedades se necessário
|
||||
}
|
||||
|
||||
interface PatientDetailsModalProps {
|
||||
patient: Paciente | null;
|
||||
isOpen: boolean;
|
||||
patient: any;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function PatientDetailsModal({ patient, isOpen, onClose }: PatientDetailsModalProps) {
|
||||
export function PatientDetailsModal({
|
||||
patient,
|
||||
isOpen,
|
||||
onClose,
|
||||
}: PatientDetailsModalProps) {
|
||||
if (!patient) return null;
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
<DialogContent className="sm:max-w-[600px]">
|
||||
<DialogContent className="max-w-[95%] sm:max-w-lg max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Detalhes do Paciente</DialogTitle>
|
||||
<DialogDescription>Informações detalhadas sobre o paciente.</DialogDescription>
|
||||
<DialogTitle className="text-xl font-bold">Detalhes do Paciente</DialogTitle>
|
||||
<DialogDescription>
|
||||
Informações detalhadas sobre o paciente.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
|
||||
<div className="space-y-4 py-2">
|
||||
{/* Grid Principal */}
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
<div>
|
||||
<p className="font-semibold">Nome Completo</p>
|
||||
<p>{patient.nome}</p>
|
||||
<p className="font-semibold text-gray-900">Nome Completo</p>
|
||||
<p className="text-gray-700">{patient.nome}</p>
|
||||
</div>
|
||||
|
||||
{/* CORREÇÃO AQUI: Adicionado 'break-all' para quebrar o email */}
|
||||
<div>
|
||||
<p className="font-semibold text-gray-900">Email</p>
|
||||
<p className="text-gray-700 break-all">{patient.email || "N/A"}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="font-semibold text-gray-900">Telefone</p>
|
||||
<p className="text-gray-700">{patient.telefone}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="font-semibold text-gray-900">Data de Nascimento</p>
|
||||
<p className="text-gray-700">{patient.birth_date || "N/A"}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="font-semibold text-gray-900">CPF</p>
|
||||
<p className="text-gray-700">{patient.cpf || "N/A"}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="font-semibold text-gray-900">Tipo Sanguíneo</p>
|
||||
<p className="text-gray-700">{patient.blood_type || "N/A"}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="font-semibold text-gray-900">Peso (kg)</p>
|
||||
<p className="text-gray-700">{patient.weight_kg || "0"}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="font-semibold text-gray-900">Altura (m)</p>
|
||||
<p className="text-gray-700">{patient.height_m || "0"}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<hr className="border-gray-200" />
|
||||
|
||||
{/* Seção de Endereço */}
|
||||
<div>
|
||||
<h4 className="font-semibold mb-3 text-gray-900">Endereço</h4>
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
<div>
|
||||
<p className="font-semibold text-gray-900">Rua</p>
|
||||
<p className="text-gray-700">
|
||||
{patient.street && patient.street !== "N/A"
|
||||
? `${patient.street}, ${patient.number || ""}`
|
||||
: "N/A"}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Email</p>
|
||||
<p>{patient.email}</p>
|
||||
<p className="font-semibold text-gray-900">Complemento</p>
|
||||
<p className="text-gray-700">{patient.complement || "N/A"}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Telefone</p>
|
||||
<p>{patient.telefone}</p>
|
||||
<p className="font-semibold text-gray-900">Bairro</p>
|
||||
<p className="text-gray-700">{patient.neighborhood || "N/A"}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Data de Nascimento</p>
|
||||
<p>{patient.birth_date}</p>
|
||||
<p className="font-semibold text-gray-900">Cidade</p>
|
||||
<p className="text-gray-700">{patient.cidade || "N/A"}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">CPF</p>
|
||||
<p>{patient.cpf}</p>
|
||||
<p className="font-semibold text-gray-900">Estado</p>
|
||||
<p className="text-gray-700">{patient.estado || "N/A"}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Tipo Sanguíneo</p>
|
||||
<p>{patient.blood_type}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Peso (kg)</p>
|
||||
<p>{patient.weight_kg}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Altura (m)</p>
|
||||
<p>{patient.height_m}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-t pt-4 mt-4">
|
||||
<h3 className="font-semibold mb-2">Endereço</h3>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<p className="font-semibold">Rua</p>
|
||||
<p>{`${patient.street}, ${patient.number}`}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Complemento</p>
|
||||
<p>{patient.complement}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Bairro</p>
|
||||
<p>{patient.neighborhood}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Cidade</p>
|
||||
<p>{patient.cidade}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Estado</p>
|
||||
<p>{patient.estado}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">CEP</p>
|
||||
<p>{patient.cep}</p>
|
||||
<p className="font-semibold text-gray-900">CEP</p>
|
||||
<p className="text-gray-700">{patient.cep || "N/A"}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<button type="button" className="px-4 py-2 bg-gray-200 rounded-md">Fechar</button>
|
||||
</DialogClose>
|
||||
<Button variant="secondary" onClick={onClose} className="w-full sm:w-auto">
|
||||
Fechar
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
@ -2,7 +2,14 @@
|
||||
|
||||
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CalendarCheck2, CalendarClock, ClipboardPlus, Home, LogOut, SquareUser } from "lucide-react";
|
||||
import {
|
||||
CalendarCheck2,
|
||||
CalendarClock,
|
||||
ClipboardPlus,
|
||||
Home,
|
||||
LogOut,
|
||||
SquareUser,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
Popover,
|
||||
PopoverTrigger,
|
||||
@ -36,11 +43,19 @@ export default function SidebarUserSection({
|
||||
}: Props) {
|
||||
const pathname = usePathname();
|
||||
const menuItems: any[] = [
|
||||
{ href: "/patient/schedule", icon: CalendarClock, label: "Agendar Consulta" },
|
||||
{ href: "/patient/appointments", icon: CalendarCheck2, label: "Minhas Consultas" },
|
||||
{
|
||||
href: "/patient/schedule",
|
||||
icon: CalendarClock,
|
||||
label: "Agendar Consulta",
|
||||
},
|
||||
{
|
||||
href: "/patient/appointments",
|
||||
icon: CalendarCheck2,
|
||||
label: "Minhas Consultas",
|
||||
},
|
||||
{ href: "/patient/reports", icon: ClipboardPlus, label: "Meus Laudos" },
|
||||
{ href: "/patient/profile", icon: SquareUser, label: "Meus Dados" },
|
||||
]
|
||||
];
|
||||
return (
|
||||
<div className="border-t p-4 mt-auto">
|
||||
{/* POPUP DE INFORMAÇÕES DO USUÁRIO */}
|
||||
@ -48,10 +63,9 @@ export default function SidebarUserSection({
|
||||
<PopoverTrigger asChild>
|
||||
<div
|
||||
className={`flex items-center space-x-3 mb-4 p-2 rounded-md transition-colors ${
|
||||
isActive
|
||||
? "cursor-pointer hover:bg-gray-100"
|
||||
: "cursor-default pointer-events-none"
|
||||
}`}>
|
||||
isActive ? "cursor-pointer" : "cursor-default pointer-events-none"
|
||||
}`}
|
||||
>
|
||||
<Avatar>
|
||||
<AvatarImage src="/placeholder.svg?height=40&width=40" />
|
||||
<AvatarFallback>
|
||||
@ -64,10 +78,10 @@ export default function SidebarUserSection({
|
||||
|
||||
{!sidebarCollapsed && (
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium text-gray-900 truncate">
|
||||
<p className="text-sm font-medium text-white truncate">
|
||||
{userData.user_metadata.full_name}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 truncate">
|
||||
<p className="text-xs text-white truncate">
|
||||
{userData.app_metadata.user_role}
|
||||
</p>
|
||||
</div>
|
||||
@ -105,21 +119,25 @@ export default function SidebarUserSection({
|
||||
</nav>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
{/* Botão de sair */}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className={
|
||||
sidebarCollapsed
|
||||
? "w-full bg-transparent flex justify-center items-center p-2"
|
||||
: "w-full bg-transparent"
|
||||
? "w-full bg-white text-black flex justify-center items-center p-2 hover:bg-gray-200"
|
||||
: "w-full bg-white text-black hover:bg-gray-200 cursor-pointer"
|
||||
}
|
||||
onClick={handleLogout}
|
||||
>
|
||||
<LogOut className={sidebarCollapsed ? "h-5 w-5" : "mr-2 h-4 w-4"} />
|
||||
{sidebarCollapsed && "Sair"}
|
||||
<LogOut
|
||||
className={
|
||||
sidebarCollapsed ? "h-5 w-5 text-black" : "mr-2 h-4 w-4 text-black"
|
||||
}
|
||||
/>
|
||||
{!sidebarCollapsed && "Sair"}
|
||||
</Button>
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
94
lib/normalization.ts
Normal file
94
lib/normalization.ts
Normal file
@ -0,0 +1,94 @@
|
||||
// lib/normalization.ts
|
||||
|
||||
/**
|
||||
* Mapa de normalização.
|
||||
* A chave é o termo "sujo" (em minúsculo) e o valor é o termo "Canônico" (Bonito).
|
||||
*/
|
||||
const SPECIALTY_MAPPING: Record<string, string> = {
|
||||
// --- Cardiologia ---
|
||||
"cardiologista": "Cardiologia",
|
||||
"cardio": "Cardiologia",
|
||||
"cardiologia": "Cardiologia",
|
||||
|
||||
// --- Dermatologia ---
|
||||
"dermatologista": "Dermatologia",
|
||||
"dermato": "Dermatologia",
|
||||
"dermatologia": "Dermatologia",
|
||||
|
||||
// --- Ortopedia ---
|
||||
"ortopedista": "Ortopedia",
|
||||
"ortopedia": "Ortopedia",
|
||||
|
||||
// --- Ginecologia ---
|
||||
"ginecologista": "Ginecologia",
|
||||
"ginecologia": "Ginecologia",
|
||||
"ginecologistaa": "Ginecologia", // Erro de digitação comum
|
||||
"gineco": "Ginecologia",
|
||||
|
||||
// --- Pediatria ---
|
||||
"pediatra": "Pediatria",
|
||||
"pediatria": "Pediatria",
|
||||
|
||||
// --- Clínica Geral (Onde estava o erro) ---
|
||||
"clinico geral": "Clínica Geral",
|
||||
"clínico geral": "Clínica Geral",
|
||||
"clinica geral": "Clínica Geral",
|
||||
"clínica geral": "Clínica Geral", // <--- ADICIONADO
|
||||
"geral": "Clínica Geral",
|
||||
"medico geral": "Clínica Geral",
|
||||
"médico geral": "Clínica Geral",
|
||||
|
||||
// --- Neurologia ---
|
||||
"neurologista": "Neurologia",
|
||||
"neurologia": "Neurologia",
|
||||
"neuro": "Neurologia",
|
||||
"neurocirurgiao": "Neurocirurgia",
|
||||
"neurocirurgião": "Neurocirurgia",
|
||||
|
||||
// --- Limpeza de Lixo / Outros ---
|
||||
"asdw": "Outros",
|
||||
"teste": "Outros",
|
||||
"n/a": "Não Informado", // <--- Transforma o "N/A" da imagem
|
||||
"na": "Não Informado",
|
||||
};
|
||||
|
||||
/**
|
||||
* Recebe uma especialidade suja e retorna a versão limpa.
|
||||
*/
|
||||
export function normalizeSpecialty(raw: string | null | undefined): string {
|
||||
if (!raw) return "Não Informado";
|
||||
|
||||
// Remove espaços extras e joga para minúsculo
|
||||
const lower = raw.trim().toLowerCase();
|
||||
|
||||
// Se for uma string vazia ou traço
|
||||
if (lower === "" || lower === "-") return "Não Informado";
|
||||
|
||||
// Verifica no mapa
|
||||
if (SPECIALTY_MAPPING[lower]) {
|
||||
return SPECIALTY_MAPPING[lower];
|
||||
}
|
||||
|
||||
// Fallback: Capitaliza a primeira letra de cada palavra
|
||||
// Ex: "cirurgia plastica" -> "Cirurgia Plastica"
|
||||
return lower.replace(/\b\w/g, (l) => l.toUpperCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* Extrai uma lista única de especialidades normalizadas.
|
||||
*/
|
||||
export function getUniqueSpecialties(items: any[]): string[] {
|
||||
const specialties = new Set<string>();
|
||||
|
||||
items.forEach(item => {
|
||||
// Normaliza antes de adicionar ao Set
|
||||
const normalized = normalizeSpecialty(item.specialty);
|
||||
|
||||
// Só adiciona se não for "Não Informado" ou "Outros" (Opcional: remova o if se quiser mostrar tudo)
|
||||
if (normalized && normalized !== "Não Informado") {
|
||||
specialties.add(normalized);
|
||||
}
|
||||
});
|
||||
|
||||
return Array.from(specialties).sort();
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 45 KiB After Width: | Height: | Size: 30 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 48 KiB After Width: | Height: | Size: 33 KiB |
@ -9,7 +9,7 @@ export const reportsApi = {
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch reports:", error);
|
||||
return [];
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
getReportById: async (reportId) => {
|
||||
|
||||
@ -21,6 +21,14 @@ export const usersService = {
|
||||
return await api.post(`/functions/v1/create-user-with-password`, data);
|
||||
},
|
||||
|
||||
// --- NOVA FUNÇÃO ADICIONADA AQUI ---
|
||||
// Esta função chama o endpoint público de registro de paciente.
|
||||
async registerPatient(data) {
|
||||
// POR QUÊ? Este endpoint é público e não requer token JWT, resolvendo o erro 401.
|
||||
return await api.post("/functions/v1/register-patient", data);
|
||||
},
|
||||
// --- FIM DA NOVA FUNÇÃO ---
|
||||
|
||||
async getMeSimple() {
|
||||
return await api.post(`/functions/v1/user-info`);
|
||||
},
|
||||
@ -35,8 +43,7 @@ export const usersService = {
|
||||
isManager: role?.role === "gestor",
|
||||
isDoctor: role?.role === "medico",
|
||||
isSecretary: role?.role === "secretaria",
|
||||
isAdminOrManager:
|
||||
role?.role === "admin" || role?.role === "gestor" ? true : false,
|
||||
isAdminOrManager: role?.role === "admin" || role?.role === "gestor" ? true : false,
|
||||
};
|
||||
|
||||
return {
|
||||
@ -64,30 +71,23 @@ export const usersService = {
|
||||
async resetPassword(email) {
|
||||
if (!email) throw new Error("Email é obrigatório para resetar a senha.");
|
||||
|
||||
|
||||
try {
|
||||
const res = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_SUPABASE_URL}/auth/v1/recover`,
|
||||
{
|
||||
const res = await fetch(`${process.env.NEXT_PUBLIC_SUPABASE_URL}/auth/v1/recover`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
apikey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
|
||||
},
|
||||
body: JSON.stringify({ email }),
|
||||
}
|
||||
);
|
||||
|
||||
});
|
||||
|
||||
const data = await res.json().catch(() => ({}));
|
||||
|
||||
|
||||
if (!res.ok) {
|
||||
console.error("Erro no resetPassword:", res.status, data);
|
||||
throw new Error(`Erro ${res.status}: ${data.message || "Falha ao resetar senha."}`);
|
||||
}
|
||||
|
||||
|
||||
console.log("✅ Reset de senha:", data);
|
||||
return data;
|
||||
} catch (err) {
|
||||
@ -95,6 +95,4 @@ export const usersService = {
|
||||
throw new Error(err.message || "Erro inesperado na recuperação de senha.");
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
};
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user