Merge pull request #25 from m1guelmcf/retirar-relatorios
Atualiza cards com dados de APIs e corrige contagens
This commit is contained in:
commit
2e0ce5fa89
@ -56,7 +56,7 @@ export default function DoctorAppointmentsPage() {
|
||||
const patientsMap = new Map<string, { name: string; phone: string }>(
|
||||
patientsList.map((p: any) => [p.id, { name: p.full_name, phone: p.phone_mobile }])
|
||||
);
|
||||
|
||||
|
||||
const enrichedAppointments = appointmentsList.map((apt: any) => ({
|
||||
id: apt.id,
|
||||
patientName: patientsMap.get(apt.patient_id)?.name || "Paciente Desconhecido",
|
||||
@ -85,10 +85,10 @@ export default function DoctorAppointmentsPage() {
|
||||
const appointmentsToDisplay = selectedDate
|
||||
? allAppointments.filter(app => app.scheduled_at && app.scheduled_at.startsWith(format(selectedDate, "yyyy-MM-dd")))
|
||||
: allAppointments.filter(app => {
|
||||
if (!app.scheduled_at) return false;
|
||||
const dateObj = parseISO(app.scheduled_at);
|
||||
return isValid(dateObj) && isFuture(dateObj);
|
||||
});
|
||||
if (!app.scheduled_at) return false;
|
||||
const dateObj = parseISO(app.scheduled_at);
|
||||
return isValid(dateObj) && isFuture(dateObj);
|
||||
});
|
||||
|
||||
return appointmentsToDisplay.reduce((acc, appointment) => {
|
||||
const dateKey = format(parseISO(appointment.scheduled_at), "yyyy-MM-dd");
|
||||
@ -162,7 +162,7 @@ export default function DoctorAppointmentsPage() {
|
||||
<Card>
|
||||
<CardHeader><CardTitle className="flex items-center"><CalendarIcon className="mr-2 h-5 w-5" />Filtrar por Data</CardTitle><CardDescription>Selecione um dia para ver os detalhes.</CardDescription></CardHeader>
|
||||
<CardContent className="flex justify-center p-2">
|
||||
<CalendarShadcn mode="single" selected={selectedDate} onSelect={setSelectedDate} modifiers={{ booked: bookedDays }} modifiersClassNames={{ booked: "bg-primary/20" }} className="rounded-md border p-2" locale={ptBR}/>
|
||||
<CalendarShadcn mode="single" selected={selectedDate} onSelect={setSelectedDate} modifiers={{ booked: bookedDays }} modifiersClassNames={{ booked: "bg-primary/20" }} className="rounded-md border p-2" locale={ptBR} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
@ -197,7 +197,7 @@ export default function DoctorAppointmentsPage() {
|
||||
{format(scheduledAtDate, "HH:mm")}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
{/* Coluna 2: Status e Telefone */}
|
||||
<div className="col-span-1 flex flex-col items-center gap-2">
|
||||
<Badge variant="outline" className={getStatusVariant(appointment.status)}>{statusPT[appointment.status].replace('_', ' ')}</Badge>
|
||||
|
||||
@ -24,6 +24,15 @@ 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";
|
||||
@ -122,127 +131,120 @@ interface Exception {
|
||||
}
|
||||
|
||||
export default function PatientDashboard() {
|
||||
const [loggedDoctor, setLoggedDoctor] = useState<Doctor>();
|
||||
const [userData, setUserData] = useState<UserData>();
|
||||
const [availability, setAvailability] = useState<any | null>(null);
|
||||
const [exceptions, setExceptions] = useState<Exception[]>([]);
|
||||
const [schedule, setSchedule] = useState<
|
||||
Record<string, { start: string; end: string }[]>
|
||||
>({});
|
||||
const formatTime = (time?: string | null) =>
|
||||
time?.split(":")?.slice(0, 2).join(":") ?? "";
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [exceptionToDelete, setExceptionToDelete] = useState<string | null>(
|
||||
null
|
||||
);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
// --- USA O HOOK DE AUTENTICAÇÃO PARA PEGAR O USUÁRIO LOGADO ---
|
||||
const { user } = useAuthLayout({ requiredRole: ['medico'] });
|
||||
|
||||
// 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",
|
||||
};
|
||||
const [loggedDoctor, setLoggedDoctor] = useState<Doctor | null>(null);
|
||||
const [userData, setUserData] = useState<UserData>();
|
||||
const [availability, setAvailability] = useState<any | null>(null);
|
||||
const [exceptions, setExceptions] = useState<Exception[]>([]);
|
||||
const [schedule, setSchedule] = useState<Record<string, { start: string; end: string }[]>>({});
|
||||
const formatTime = (time?: string | null) => time?.split(":")?.slice(0, 2).join(":") ?? "";
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [exceptionToDelete, setExceptionToDelete] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
const doctorsList: Doctor[] = await doctorsService.list();
|
||||
const doctor = doctorsList[0];
|
||||
// --- ESTADOS PARA OS CARDS ATUALIZADOS ---
|
||||
const [nextAppointment, setNextAppointment] = useState<EnrichedAppointment | null>(null);
|
||||
const [monthlyCount, setMonthlyCount] = useState<number>(0);
|
||||
|
||||
// Salva no estado
|
||||
setLoggedDoctor(doctor);
|
||||
const weekdaysPT: Record<string, string> = { sunday: "Domingo", monday: "Segunda", tuesday: "Terça", wednesday: "Quarta", thursday: "Quinta", friday: "Sexta", saturday: "Sábado" };
|
||||
|
||||
// Busca disponibilidade
|
||||
const availabilityList = await AvailabilityService.list();
|
||||
// ▼▼▼ LÓGICA DE BUSCA CORRIGIDA E ATUALIZADA ▼▼▼
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
if (!user?.id) return; // Aguarda o usuário ser carregado
|
||||
|
||||
// Filtra já com a variável local
|
||||
const filteredAvail = availabilityList.filter(
|
||||
(disp: { doctor_id: string }) => disp.doctor_id === doctor?.id
|
||||
);
|
||||
setAvailability(filteredAvail);
|
||||
try {
|
||||
// Encontra o perfil de médico correspondente ao usuário logado
|
||||
const doctorsList: Doctor[] = await doctorsService.list();
|
||||
const currentDoctor = doctorsList.find(doc => doc.user_id === user.id);
|
||||
|
||||
if (!currentDoctor) {
|
||||
setError("Perfil de médico não encontrado para este usuário.");
|
||||
return;
|
||||
}
|
||||
setLoggedDoctor(currentDoctor);
|
||||
|
||||
// Busca todos os dados necessários em paralelo
|
||||
const [appointmentsList, patientsList, availabilityList, exceptionsList] = await Promise.all([
|
||||
appointmentsService.list(),
|
||||
patientsService.list(),
|
||||
AvailabilityService.list(),
|
||||
exceptionsService.list()
|
||||
]);
|
||||
|
||||
// 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)
|
||||
);
|
||||
setMonthlyCount(currentMonthAppointments.length);
|
||||
|
||||
// Busca e filtra o restante dos dados
|
||||
setAvailability(availabilityList.filter((d: any) => d.doctor_id === currentDoctor.id));
|
||||
setExceptions(exceptionsList.filter((e: any) => e.doctor_id === currentDoctor.id));
|
||||
|
||||
// Busca exceções
|
||||
const exceptionsList = await exceptionsService.list();
|
||||
const filteredExc = exceptionsList.filter((exc: { doctor_id: string }) => exc.doctor_id === doctor?.id);
|
||||
setExceptions(filteredExc);
|
||||
} catch (e: any) {
|
||||
alert(`${e?.error} ${e?.message}`);
|
||||
setError(e?.message || "Erro ao buscar dados do dashboard");
|
||||
console.error("Erro no dashboard:", e);
|
||||
}
|
||||
};
|
||||
|
||||
fetchData();
|
||||
}, []);
|
||||
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);
|
||||
}
|
||||
|
||||
const openDeleteDialog = (exceptionId: string) => {
|
||||
setExceptionToDelete(exceptionId);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleDeleteException = async (ExceptionId: string) => {
|
||||
try {
|
||||
alert(ExceptionId);
|
||||
const res = await exceptionsService.delete(ExceptionId);
|
||||
|
||||
let message = "Exceção deletada com sucesso";
|
||||
try {
|
||||
if (res) {
|
||||
throw new Error(
|
||||
`${res.error} ${res.message}` || "A API retornou erro"
|
||||
);
|
||||
} else {
|
||||
console.log(message);
|
||||
}
|
||||
} catch {}
|
||||
|
||||
toast({
|
||||
title: "Sucesso",
|
||||
description: message,
|
||||
});
|
||||
|
||||
setExceptions((prev: Exception[]) =>
|
||||
prev.filter((p) => String(p.id) !== String(ExceptionId))
|
||||
);
|
||||
} catch (e: any) {
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: e?.message || "Não foi possível deletar a exceção",
|
||||
});
|
||||
function findDoctorById(id: string, doctors: Doctor[]) {
|
||||
return doctors.find((doctor) => doctor.user_id === id);
|
||||
}
|
||||
setDeleteDialogOpen(false);
|
||||
setExceptionToDelete(null);
|
||||
};
|
||||
|
||||
function formatAvailability(data: Availability[]) {
|
||||
// Agrupar os horários por dia da semana
|
||||
const schedule = data.reduce((acc: any, item) => {
|
||||
const { weekday, start_time, end_time } = item;
|
||||
const openDeleteDialog = (exceptionId: string) => {
|
||||
setExceptionToDelete(exceptionId);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
// Se o dia ainda não existe, cria o array
|
||||
if (!acc[weekday]) {
|
||||
acc[weekday] = [];
|
||||
}
|
||||
const handleDeleteException = async (ExceptionId: string) => {
|
||||
try {
|
||||
const res = await exceptionsService.delete(ExceptionId);
|
||||
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" });
|
||||
}
|
||||
setDeleteDialogOpen(false);
|
||||
setExceptionToDelete(null);
|
||||
};
|
||||
|
||||
// Adiciona o horário do dia
|
||||
acc[weekday].push({
|
||||
start: start_time,
|
||||
end: end_time,
|
||||
});
|
||||
|
||||
return acc;
|
||||
}, {} as Record<string, { start: string; end: string }[]>);
|
||||
|
||||
return schedule;
|
||||
}
|
||||
function formatAvailability(data: Availability[]) {
|
||||
if (!data) return {};
|
||||
const schedule = 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;
|
||||
}, {} as Record<string, { start: string; end: string }[]>);
|
||||
return schedule;
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (availability) {
|
||||
@ -261,32 +263,45 @@ export default function PatientDashboard() {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">
|
||||
Próxima Consulta
|
||||
</CardTitle>
|
||||
<Calendar className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">02 out</div>
|
||||
<p className="text-xs text-muted-foreground">Dr. Silva - 14:30</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<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>
|
||||
{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>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">
|
||||
Consultas Este Mês
|
||||
</CardTitle>
|
||||
<Clock className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">4</div>
|
||||
<p className="text-xs text-muted-foreground">4 agendadas</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{/* ▼▼▼ CARD "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">{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">
|
||||
@ -300,23 +315,22 @@ export default function PatientDashboard() {
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Ações Rápidas</CardTitle>
|
||||
<CardDescription>
|
||||
Acesse rapidamente as principais funcionalidades
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<Link href="/doctor/medicos/consultas">
|
||||
<Button className="bg-blue-600 hover:bg-blue-700 text-white cursor-pointer">
|
||||
<Calendar className="mr-2 h-4 w-4 text-white" />
|
||||
Ver Minhas Consultas
|
||||
</Button>
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{/* O restante do código permanece o mesmo */}
|
||||
<div className="grid md:grid-cols-2 gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Ações Rápidas</CardTitle>
|
||||
<CardDescription>Acesse rapidamente as principais funcionalidades</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<Link href="/doctor/medicos/consultas">
|
||||
<Button className="w-full justify-start">
|
||||
<Calendar className="mr-2 h-4 w-4" />
|
||||
Ver Minhas Consultas
|
||||
</Button>
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
@ -355,16 +369,15 @@ export default function PatientDashboard() {
|
||||
<CardDescription>Bloqueios e liberações eventuais de agenda</CardDescription>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-4 grid md:grid-cols-7 gap-2">
|
||||
{exceptions && exceptions.length > 0 ? (
|
||||
exceptions.map((ex: Exception) => {
|
||||
// Formata data e hora
|
||||
const date = new Date(ex.date).toLocaleDateString("pt-BR", {
|
||||
weekday: "long",
|
||||
day: "2-digit",
|
||||
month: "long",
|
||||
timeZone: "UTC",
|
||||
});
|
||||
<CardContent className="space-y-4 grid md:grid-cols-7 gap-2">
|
||||
{exceptions && exceptions.length > 0 ? (
|
||||
exceptions.map((ex: Exception) => {
|
||||
const date = new Date(ex.date).toLocaleDateString("pt-BR", {
|
||||
weekday: "long",
|
||||
day: "2-digit",
|
||||
month: "long",
|
||||
timeZone: "UTC"
|
||||
});
|
||||
|
||||
const startTime = formatTime(ex.start_time);
|
||||
const endTime = formatTime(ex.end_time);
|
||||
@ -374,7 +387,11 @@ export default function PatientDashboard() {
|
||||
<div className="flex flex-col items-center justify-between p-3 bg-blue-50 rounded-lg shadow-sm">
|
||||
<div className="text-center">
|
||||
<p className="font-semibold capitalize">{date}</p>
|
||||
<p className="text-sm text-gray-600">{startTime && endTime ? `${startTime} - ${endTime}` : "Dia todo"}</p>
|
||||
<p className="text-sm text-gray-600">
|
||||
{startTime && endTime
|
||||
? `${startTime} - ${endTime}`
|
||||
: "Dia todo"}
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-center mt-2">
|
||||
<p className={`text-sm font-medium ${ex.kind === "bloqueio" ? "text-red-600" : "text-green-600"}`}>{ex.kind === "bloqueio" ? "Bloqueio" : "Liberação"}</p>
|
||||
@ -412,4 +429,4 @@ export default function PatientDashboard() {
|
||||
</div>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -8,12 +8,13 @@ import {
|
||||
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
|
||||
@ -24,20 +25,48 @@ export default function ManagerDashboard() {
|
||||
const [doctors, setDoctors] = useState<any[]>([]);
|
||||
const [loadingDoctors, setLoadingDoctors] = useState(true);
|
||||
|
||||
// 🔹 Buscar primeiro usuário
|
||||
useEffect(() => {
|
||||
async function fetchFirstUser() {
|
||||
try {
|
||||
const data = await usersService.list_roles();
|
||||
if (Array.isArray(data) && data.length > 0) {
|
||||
setFirstUser(data[0]);
|
||||
// 🔹 Buscar primeiro usuário (LÓGICA ATUALIZADA)
|
||||
useEffect(() => {
|
||||
async function fetchFirstUser() {
|
||||
setLoadingUser(true); // Garante que o estado de loading inicie como true
|
||||
try {
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Erro ao carregar usuário:", error);
|
||||
} finally {
|
||||
setLoadingUser(false);
|
||||
}
|
||||
}
|
||||
|
||||
fetchFirstUser();
|
||||
}, []);
|
||||
@ -71,23 +100,9 @@ export default function ManagerDashboard() {
|
||||
</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>
|
||||
{/* Cards principais */}
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
|
||||
|
||||
{/* Card 2 — Gestão de usuários */}
|
||||
<Card>
|
||||
@ -224,4 +239,4 @@ export default function ManagerDashboard() {
|
||||
</div>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -9,47 +9,47 @@ import { Label } from "@/components/ui/label"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { Save, Loader2, ArrowLeft } from "lucide-react"
|
||||
import { Save, Loader2, ArrowLeft } from "lucide-react"
|
||||
import Sidebar from "@/components/Sidebar"
|
||||
import { doctorsService } from "services/doctorsApi.mjs";
|
||||
import { doctorsService } from "services/doctorsApi.mjs";
|
||||
|
||||
const UF_LIST = ["AC", "AL", "AP", "AM", "BA", "CE", "DF", "ES", "GO", "MA", "MT", "MS", "MG", "PA", "PB", "PR", "PE", "PI", "RJ", "RN", "RS", "RO", "RR", "SC", "SP", "SE", "TO"];
|
||||
|
||||
interface DoctorFormData {
|
||||
nomeCompleto: string;
|
||||
crm: string;
|
||||
crmEstado: string;
|
||||
especialidade: string;
|
||||
cpf: string;
|
||||
email: string;
|
||||
dataNascimento: string;
|
||||
rg: string;
|
||||
telefoneCelular: string;
|
||||
telefone2: string;
|
||||
cep: string;
|
||||
endereco: string;
|
||||
numero: string;
|
||||
complemento: string;
|
||||
bairro: string;
|
||||
cidade: string;
|
||||
estado: string;
|
||||
ativo: boolean;
|
||||
observacoes: string;
|
||||
nomeCompleto: string;
|
||||
crm: string;
|
||||
crmEstado: string;
|
||||
especialidade: string;
|
||||
cpf: string;
|
||||
email: string;
|
||||
dataNascimento: string;
|
||||
rg: string;
|
||||
telefoneCelular: string;
|
||||
telefone2: string;
|
||||
cep: string;
|
||||
endereco: string;
|
||||
numero: string;
|
||||
complemento: string;
|
||||
bairro: string;
|
||||
cidade: string;
|
||||
estado: string;
|
||||
ativo: boolean;
|
||||
observacoes: string;
|
||||
}
|
||||
const apiMap: { [K in keyof DoctorFormData]: string | null } = {
|
||||
nomeCompleto: 'full_name', crm: 'crm', crmEstado: 'crm_uf', especialidade: 'specialty',
|
||||
cpf: 'cpf', email: 'email', dataNascimento: 'birth_date', rg: 'rg',
|
||||
telefoneCelular: 'phone_mobile', telefone2: 'phone2', cep: 'cep',
|
||||
endereco: 'street', numero: 'number', complemento: 'complement',
|
||||
bairro: 'neighborhood', cidade: 'city', estado: 'state', ativo: 'active',
|
||||
observacoes: null,
|
||||
nomeCompleto: 'full_name', crm: 'crm', crmEstado: 'crm_uf', especialidade: 'specialty',
|
||||
cpf: 'cpf', email: 'email', dataNascimento: 'birth_date', rg: 'rg',
|
||||
telefoneCelular: 'phone_mobile', telefone2: 'phone2', cep: 'cep',
|
||||
endereco: 'street', numero: 'number', complemento: 'complement',
|
||||
bairro: 'neighborhood', cidade: 'city', estado: 'state', ativo: 'active',
|
||||
observacoes: null,
|
||||
};
|
||||
|
||||
const defaultFormData: DoctorFormData = {
|
||||
nomeCompleto: '', crm: '', crmEstado: '', especialidade: '', cpf: '', email: '',
|
||||
dataNascimento: '', rg: '', telefoneCelular: '', telefone2: '', cep: '',
|
||||
endereco: '', numero: '', complemento: '', bairro: '', cidade: '', estado: '',
|
||||
ativo: true, observacoes: '',
|
||||
nomeCompleto: '', crm: '', crmEstado: '', especialidade: '', cpf: '', email: '',
|
||||
dataNascimento: '', rg: '', telefoneCelular: '', telefone2: '', cep: '',
|
||||
endereco: '', numero: '', complemento: '', bairro: '', cidade: '', estado: '',
|
||||
ativo: true, observacoes: '',
|
||||
};
|
||||
|
||||
const cleanNumber = (value: string): string => value.replace(/\D/g, '');
|
||||
@ -73,420 +73,420 @@ const formatPhoneMobile = (value: string): string => {
|
||||
};
|
||||
|
||||
export default function EditarMedicoPage() {
|
||||
const router = useRouter();
|
||||
const params = useParams();
|
||||
const id = Array.isArray(params.id) ? params.id[0] : params.id;
|
||||
const [formData, setFormData] = useState<DoctorFormData>(defaultFormData);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const apiToFormMap: { [key: string]: keyof DoctorFormData } = {
|
||||
'full_name': 'nomeCompleto', 'crm': 'crm', 'crm_uf': 'crmEstado', 'specialty': 'especialidade',
|
||||
'cpf': 'cpf', 'email': 'email', 'birth_date': 'dataNascimento', 'rg': 'rg',
|
||||
'phone_mobile': 'telefoneCelular', 'phone2': 'telefone2', 'cep': 'cep',
|
||||
'street': 'endereco', 'number': 'numero', 'complement': 'complemento',
|
||||
'neighborhood': 'bairro', 'city': 'cidade', 'state': 'estado', 'active': 'ativo'
|
||||
};
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
|
||||
const fetchDoctor = async () => {
|
||||
try {
|
||||
const data = await doctorsService.getById(id);
|
||||
|
||||
if (!data) {
|
||||
setError("Médico não encontrado.");
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const initialData: Partial<DoctorFormData> = {};
|
||||
|
||||
Object.keys(data).forEach(key => {
|
||||
const formKey = apiToFormMap[key];
|
||||
if (formKey) {
|
||||
let value = data[key] === null ? '' : data[key];
|
||||
if (formKey === 'ativo') {
|
||||
value = !!value;
|
||||
} else if (typeof value !== 'boolean') {
|
||||
value = String(value);
|
||||
}
|
||||
initialData[formKey] = value as any;
|
||||
}
|
||||
});
|
||||
initialData.observacoes = "Observação carregada do sistema (exemplo de campo interno)";
|
||||
|
||||
setFormData(prev => ({ ...prev, ...initialData }));
|
||||
} catch (e) {
|
||||
console.error("Erro ao carregar dados:", e);
|
||||
setError("Não foi possível carregar os dados do médico.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
const router = useRouter();
|
||||
const params = useParams();
|
||||
const id = Array.isArray(params.id) ? params.id[0] : params.id;
|
||||
const [formData, setFormData] = useState<DoctorFormData>(defaultFormData);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const apiToFormMap: { [key: string]: keyof DoctorFormData } = {
|
||||
'full_name': 'nomeCompleto', 'crm': 'crm', 'crm_uf': 'crmEstado', 'specialty': 'especialidade',
|
||||
'cpf': 'cpf', 'email': 'email', 'birth_date': 'dataNascimento', 'rg': 'rg',
|
||||
'phone_mobile': 'telefoneCelular', 'phone2': 'telefone2', 'cep': 'cep',
|
||||
'street': 'endereco', 'number': 'numero', 'complement': 'complemento',
|
||||
'neighborhood': 'bairro', 'city': 'cidade', 'state': 'estado', 'active': 'ativo'
|
||||
};
|
||||
fetchDoctor();
|
||||
}, [id]);
|
||||
|
||||
const handleInputChange = (key: keyof DoctorFormData, value: string | boolean) => {
|
||||
|
||||
|
||||
if (typeof value === 'string') {
|
||||
let maskedValue = value;
|
||||
if (key === 'cpf') maskedValue = formatCPF(value);
|
||||
if (key === 'cep') maskedValue = formatCEP(value);
|
||||
if (key === 'telefoneCelular' || key === 'telefone2') maskedValue = formatPhoneMobile(value);
|
||||
|
||||
setFormData((prev) => ({ ...prev, [key]: maskedValue }));
|
||||
} else {
|
||||
setFormData((prev) => ({ ...prev, [key]: value }));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setIsSaving(true);
|
||||
|
||||
if (!id) {
|
||||
setError("ID do médico ausente.");
|
||||
setIsSaving(false);
|
||||
return;
|
||||
}
|
||||
const fetchDoctor = async () => {
|
||||
try {
|
||||
const data = await doctorsService.getById(id);
|
||||
|
||||
const finalPayload: { [key: string]: any } = {};
|
||||
const formKeys = Object.keys(formData) as Array<keyof DoctorFormData>;
|
||||
if (!data) {
|
||||
setError("Médico não encontrado.");
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
formKeys.forEach((key) => {
|
||||
const apiFieldName = apiMap[key];
|
||||
|
||||
if (!apiFieldName) return;
|
||||
const initialData: Partial<DoctorFormData> = {};
|
||||
|
||||
Object.keys(data).forEach(key => {
|
||||
const formKey = apiToFormMap[key];
|
||||
if (formKey) {
|
||||
let value = data[key] === null ? '' : data[key];
|
||||
if (formKey === 'ativo') {
|
||||
value = !!value;
|
||||
} else if (typeof value !== 'boolean') {
|
||||
value = String(value);
|
||||
}
|
||||
initialData[formKey] = value as any;
|
||||
}
|
||||
});
|
||||
initialData.observacoes = "Observação carregada do sistema (exemplo de campo interno)";
|
||||
|
||||
setFormData(prev => ({ ...prev, ...initialData }));
|
||||
} catch (e) {
|
||||
console.error("Erro ao carregar dados:", e);
|
||||
setError("Não foi possível carregar os dados do médico.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
fetchDoctor();
|
||||
}, [id]);
|
||||
|
||||
const handleInputChange = (key: keyof DoctorFormData, value: string | boolean) => {
|
||||
|
||||
let value = formData[key];
|
||||
|
||||
if (typeof value === 'string') {
|
||||
let trimmedValue = value.trim();
|
||||
if (trimmedValue === '') {
|
||||
finalPayload[apiFieldName] = null;
|
||||
return;
|
||||
}
|
||||
if (key === 'crmEstado' || key === 'estado') {
|
||||
trimmedValue = trimmedValue.toUpperCase();
|
||||
}
|
||||
|
||||
value = trimmedValue;
|
||||
}
|
||||
|
||||
finalPayload[apiFieldName] = value;
|
||||
});
|
||||
let maskedValue = value;
|
||||
if (key === 'cpf') maskedValue = formatCPF(value);
|
||||
if (key === 'cep') maskedValue = formatCEP(value);
|
||||
if (key === 'telefoneCelular' || key === 'telefone2') maskedValue = formatPhoneMobile(value);
|
||||
|
||||
delete finalPayload.user_id;
|
||||
try {
|
||||
await doctorsService.update(id, finalPayload);
|
||||
router.push("/manager/home");
|
||||
} catch (e: any) {
|
||||
console.error("Erro ao salvar o médico:", e);
|
||||
let detailedError = "Erro ao atualizar. Verifique os dados e tente novamente.";
|
||||
|
||||
if (e.message && e.message.includes("duplicate key value violates unique constraint")) {
|
||||
detailedError = "O CPF ou CRM informado já está cadastrado em outro registro.";
|
||||
} else if (e.message && e.message.includes("Detalhes:")) {
|
||||
detailedError = e.message.split("Detalhes:")[1].trim();
|
||||
} else if (e.message) {
|
||||
detailedError = e.message;
|
||||
}
|
||||
|
||||
setError(`Erro ao atualizar. Detalhes: ${detailedError}`);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
setFormData((prev) => ({ ...prev, [key]: maskedValue }));
|
||||
} else {
|
||||
setFormData((prev) => ({ ...prev, [key]: value }));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setIsSaving(true);
|
||||
|
||||
if (!id) {
|
||||
setError("ID do médico ausente.");
|
||||
setIsSaving(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const finalPayload: { [key: string]: any } = {};
|
||||
const formKeys = Object.keys(formData) as Array<keyof DoctorFormData>;
|
||||
|
||||
|
||||
formKeys.forEach((key) => {
|
||||
const apiFieldName = apiMap[key];
|
||||
|
||||
if (!apiFieldName) return;
|
||||
|
||||
let value = formData[key];
|
||||
|
||||
if (typeof value === 'string') {
|
||||
let trimmedValue = value.trim();
|
||||
if (trimmedValue === '') {
|
||||
finalPayload[apiFieldName] = null;
|
||||
return;
|
||||
}
|
||||
if (key === 'crmEstado' || key === 'estado') {
|
||||
trimmedValue = trimmedValue.toUpperCase();
|
||||
}
|
||||
|
||||
value = trimmedValue;
|
||||
}
|
||||
|
||||
finalPayload[apiFieldName] = value;
|
||||
});
|
||||
|
||||
delete finalPayload.user_id;
|
||||
try {
|
||||
await doctorsService.update(id, finalPayload);
|
||||
router.push("/manager/home");
|
||||
} catch (e: any) {
|
||||
console.error("Erro ao salvar o médico:", e);
|
||||
let detailedError = "Erro ao atualizar. Verifique os dados e tente novamente.";
|
||||
|
||||
if (e.message && e.message.includes("duplicate key value violates unique constraint")) {
|
||||
detailedError = "O CPF ou CRM informado já está cadastrado em outro registro.";
|
||||
} else if (e.message && e.message.includes("Detalhes:")) {
|
||||
detailedError = e.message.split("Detalhes:")[1].trim();
|
||||
} else if (e.message) {
|
||||
detailedError = e.message;
|
||||
}
|
||||
|
||||
setError(`Erro ao atualizar. Detalhes: ${detailedError}`);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
if (loading) {
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="flex justify-center items-center h-full w-full py-16">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-green-600" />
|
||||
<p className="ml-2 text-gray-600">Carregando dados do médico...</p>
|
||||
</div>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
};
|
||||
if (loading) {
|
||||
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="flex justify-center items-center h-full w-full py-16">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-green-600" />
|
||||
<p className="ml-2 text-gray-600">Carregando dados do médico...</p>
|
||||
<div className="w-full space-y-6 p-4 md:p-8">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">
|
||||
Editar Médico: <span className="text-green-600">{formData.nomeCompleto}</span>
|
||||
</h1>
|
||||
<p className="text-sm text-gray-500">
|
||||
Atualize as informações do médico
|
||||
</p>
|
||||
</div>
|
||||
<Link href="/manager/home">
|
||||
<Button variant="outline">
|
||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||
Voltar
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
|
||||
{error && (
|
||||
<div className="p-3 bg-red-100 text-red-700 rounded-lg border border-red-300">
|
||||
<p className="font-medium">Erro na Atualização:</p>
|
||||
<p className="text-sm">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-4 p-4 border rounded-xl shadow-sm bg-white">
|
||||
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">
|
||||
Dados Principais e Pessoais
|
||||
</h2>
|
||||
<div className="grid md:grid-cols-4 gap-4">
|
||||
<div className="space-y-2 col-span-2">
|
||||
<Label htmlFor="nomeCompleto">Nome Completo (full_name)</Label>
|
||||
<Input
|
||||
id="nomeCompleto"
|
||||
value={formData.nomeCompleto}
|
||||
onChange={(e) => handleInputChange("nomeCompleto", e.target.value)}
|
||||
placeholder="Nome do Médico"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 col-span-1">
|
||||
<Label htmlFor="crm">CRM</Label>
|
||||
<Input
|
||||
id="crm"
|
||||
value={formData.crm}
|
||||
onChange={(e) => handleInputChange("crm", e.target.value)}
|
||||
placeholder="Ex: 123456"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 col-span-1">
|
||||
<Label htmlFor="crmEstado">UF do CRM (crm_uf)</Label>
|
||||
<Select value={formData.crmEstado} onValueChange={(v) => handleInputChange("crmEstado", v)}>
|
||||
<SelectTrigger id="crmEstado">
|
||||
<SelectValue placeholder="UF" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{UF_LIST.map(uf => (
|
||||
<SelectItem key={uf} value={uf}>{uf}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="grid md:grid-cols-3 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="especialidade">Especialidade (specialty)</Label>
|
||||
<Input
|
||||
id="especialidade"
|
||||
value={formData.especialidade}
|
||||
onChange={(e) => handleInputChange("especialidade", e.target.value)}
|
||||
placeholder="Ex: Cardiologia"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="cpf">CPF</Label>
|
||||
<Input
|
||||
id="cpf"
|
||||
value={formData.cpf}
|
||||
onChange={(e) => handleInputChange("cpf", e.target.value)}
|
||||
placeholder="000.000.000-00"
|
||||
maxLength={14}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="rg">RG</Label>
|
||||
<Input
|
||||
id="rg"
|
||||
value={formData.rg}
|
||||
onChange={(e) => handleInputChange("rg", e.target.value)}
|
||||
placeholder="00.000.000-0"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-4 gap-4">
|
||||
<div className="space-y-2 col-span-2">
|
||||
<Label htmlFor="email">E-mail</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={formData.email}
|
||||
onChange={(e) => handleInputChange("email", e.target.value)}
|
||||
placeholder="exemplo@dominio.com"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 col-span-1">
|
||||
<Label htmlFor="dataNascimento">Data de Nascimento (birth_date)</Label>
|
||||
<Input
|
||||
id="dataNascimento"
|
||||
type="date"
|
||||
value={formData.dataNascimento}
|
||||
onChange={(e) => handleInputChange("dataNascimento", e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 flex items-end justify-center pb-1">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="ativo"
|
||||
checked={formData.ativo}
|
||||
onCheckedChange={(checked) => handleInputChange("ativo", checked === true)}
|
||||
/>
|
||||
<Label htmlFor="ativo">Médico Ativo (active)</Label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 p-4 border rounded-xl shadow-sm bg-white">
|
||||
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">
|
||||
Contato e Endereço
|
||||
</h2>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="telefoneCelular">Telefone Celular (phone_mobile)</Label>
|
||||
<Input
|
||||
id="telefoneCelular"
|
||||
value={formData.telefoneCelular}
|
||||
onChange={(e) => handleInputChange("telefoneCelular", e.target.value)}
|
||||
placeholder="(00) 00000-0000"
|
||||
maxLength={15}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="telefone2">Telefone Adicional (phone2)</Label>
|
||||
<Input
|
||||
id="telefone2"
|
||||
value={formData.telefone2}
|
||||
onChange={(e) => handleInputChange("telefone2", e.target.value)}
|
||||
placeholder="(00) 00000-0000"
|
||||
maxLength={15}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="grid md:grid-cols-4 gap-4">
|
||||
<div className="space-y-2 col-span-1">
|
||||
<Label htmlFor="cep">CEP</Label>
|
||||
<Input
|
||||
id="cep"
|
||||
value={formData.cep}
|
||||
onChange={(e) => handleInputChange("cep", e.target.value)}
|
||||
placeholder="00000-000"
|
||||
maxLength={9}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 col-span-3">
|
||||
<Label htmlFor="endereco">Logradouro (street)</Label>
|
||||
<Input
|
||||
id="endereco"
|
||||
value={formData.endereco}
|
||||
onChange={(e) => handleInputChange("endereco", e.target.value)}
|
||||
placeholder="Rua, Avenida, etc."
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-4 gap-4">
|
||||
<div className="space-y-2 col-span-1">
|
||||
<Label htmlFor="numero">Número</Label>
|
||||
<Input
|
||||
id="numero"
|
||||
value={formData.numero}
|
||||
onChange={(e) => handleInputChange("numero", e.target.value)}
|
||||
placeholder="123"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 col-span-3">
|
||||
<Label htmlFor="complemento">Complemento</Label>
|
||||
<Input
|
||||
id="complemento"
|
||||
value={formData.complemento}
|
||||
onChange={(e) => handleInputChange("complemento", e.target.value)}
|
||||
placeholder="Apto, Bloco, etc."
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-4 gap-4">
|
||||
<div className="space-y-2 col-span-2">
|
||||
<Label htmlFor="bairro">Bairro</Label>
|
||||
<Input
|
||||
id="bairro"
|
||||
value={formData.bairro}
|
||||
onChange={(e) => handleInputChange("bairro", e.target.value)}
|
||||
placeholder="Bairro"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 col-span-1">
|
||||
<Label htmlFor="cidade">Cidade</Label>
|
||||
<Input
|
||||
id="cidade"
|
||||
value={formData.cidade}
|
||||
onChange={(e) => handleInputChange("cidade", e.target.value)}
|
||||
placeholder="São Paulo"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 col-span-1">
|
||||
<Label htmlFor="estado">Estado (state)</Label>
|
||||
<Input
|
||||
id="estado"
|
||||
value={formData.estado}
|
||||
onChange={(e) => handleInputChange("estado", e.target.value)}
|
||||
placeholder="SP"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="space-y-4 p-4 border rounded-xl shadow-sm bg-white">
|
||||
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">
|
||||
Observações (Apenas internas)
|
||||
</h2>
|
||||
<Textarea
|
||||
id="observacoes"
|
||||
value={formData.observacoes}
|
||||
onChange={(e) => handleInputChange("observacoes", e.target.value)}
|
||||
placeholder="Notas internas sobre o médico..."
|
||||
className="min-h-[100px]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="flex justify-end gap-4 pb-8 pt-4">
|
||||
<Link href="/manager/home">
|
||||
<Button type="button" variant="outline" disabled={isSaving}>
|
||||
Cancelar
|
||||
</Button>
|
||||
</Link>
|
||||
<Button
|
||||
type="submit"
|
||||
className="bg-green-600 hover:bg-green-700"
|
||||
disabled={isSaving}
|
||||
>
|
||||
{isSaving ? (
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Save className="w-4 h-4 mr-2" />
|
||||
)}
|
||||
{isSaving ? "Salvando..." : "Salvar Alterações"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="w-full space-y-6 p-4 md:p-8">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">
|
||||
Editar Médico: <span className="text-green-600">{formData.nomeCompleto}</span>
|
||||
</h1>
|
||||
<p className="text-sm text-gray-500">
|
||||
Atualize as informações do médico (ID: {id}).
|
||||
</p>
|
||||
</div>
|
||||
<Link href="/manager/home">
|
||||
<Button variant="outline">
|
||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||
Voltar
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
|
||||
{error && (
|
||||
<div className="p-3 bg-red-100 text-red-700 rounded-lg border border-red-300">
|
||||
<p className="font-medium">Erro na Atualização:</p>
|
||||
<p className="text-sm">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-4 p-4 border rounded-xl shadow-sm bg-white">
|
||||
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">
|
||||
Dados Principais e Pessoais
|
||||
</h2>
|
||||
<div className="grid md:grid-cols-4 gap-4">
|
||||
<div className="space-y-2 col-span-2">
|
||||
<Label htmlFor="nomeCompleto">Nome Completo (full_name)</Label>
|
||||
<Input
|
||||
id="nomeCompleto"
|
||||
value={formData.nomeCompleto}
|
||||
onChange={(e) => handleInputChange("nomeCompleto", e.target.value)}
|
||||
placeholder="Nome do Médico"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 col-span-1">
|
||||
<Label htmlFor="crm">CRM</Label>
|
||||
<Input
|
||||
id="crm"
|
||||
value={formData.crm}
|
||||
onChange={(e) => handleInputChange("crm", e.target.value)}
|
||||
placeholder="Ex: 123456"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 col-span-1">
|
||||
<Label htmlFor="crmEstado">UF do CRM (crm_uf)</Label>
|
||||
<Select value={formData.crmEstado} onValueChange={(v) => handleInputChange("crmEstado", v)}>
|
||||
<SelectTrigger id="crmEstado">
|
||||
<SelectValue placeholder="UF" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{UF_LIST.map(uf => (
|
||||
<SelectItem key={uf} value={uf}>{uf}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="grid md:grid-cols-3 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="especialidade">Especialidade (specialty)</Label>
|
||||
<Input
|
||||
id="especialidade"
|
||||
value={formData.especialidade}
|
||||
onChange={(e) => handleInputChange("especialidade", e.target.value)}
|
||||
placeholder="Ex: Cardiologia"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="cpf">CPF</Label>
|
||||
<Input
|
||||
id="cpf"
|
||||
value={formData.cpf}
|
||||
onChange={(e) => handleInputChange("cpf", e.target.value)}
|
||||
placeholder="000.000.000-00"
|
||||
maxLength={14}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="rg">RG</Label>
|
||||
<Input
|
||||
id="rg"
|
||||
value={formData.rg}
|
||||
onChange={(e) => handleInputChange("rg", e.target.value)}
|
||||
placeholder="00.000.000-0"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-4 gap-4">
|
||||
<div className="space-y-2 col-span-2">
|
||||
<Label htmlFor="email">E-mail</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={formData.email}
|
||||
onChange={(e) => handleInputChange("email", e.target.value)}
|
||||
placeholder="exemplo@dominio.com"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 col-span-1">
|
||||
<Label htmlFor="dataNascimento">Data de Nascimento (birth_date)</Label>
|
||||
<Input
|
||||
id="dataNascimento"
|
||||
type="date"
|
||||
value={formData.dataNascimento}
|
||||
onChange={(e) => handleInputChange("dataNascimento", e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 flex items-end justify-center pb-1">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="ativo"
|
||||
checked={formData.ativo}
|
||||
onCheckedChange={(checked) => handleInputChange("ativo", checked === true)}
|
||||
/>
|
||||
<Label htmlFor="ativo">Médico Ativo (active)</Label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 p-4 border rounded-xl shadow-sm bg-white">
|
||||
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">
|
||||
Contato e Endereço
|
||||
</h2>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="telefoneCelular">Telefone Celular (phone_mobile)</Label>
|
||||
<Input
|
||||
id="telefoneCelular"
|
||||
value={formData.telefoneCelular}
|
||||
onChange={(e) => handleInputChange("telefoneCelular", e.target.value)}
|
||||
placeholder="(00) 00000-0000"
|
||||
maxLength={15}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="telefone2">Telefone Adicional (phone2)</Label>
|
||||
<Input
|
||||
id="telefone2"
|
||||
value={formData.telefone2}
|
||||
onChange={(e) => handleInputChange("telefone2", e.target.value)}
|
||||
placeholder="(00) 00000-0000"
|
||||
maxLength={15}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="grid md:grid-cols-4 gap-4">
|
||||
<div className="space-y-2 col-span-1">
|
||||
<Label htmlFor="cep">CEP</Label>
|
||||
<Input
|
||||
id="cep"
|
||||
value={formData.cep}
|
||||
onChange={(e) => handleInputChange("cep", e.target.value)}
|
||||
placeholder="00000-000"
|
||||
maxLength={9}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 col-span-3">
|
||||
<Label htmlFor="endereco">Logradouro (street)</Label>
|
||||
<Input
|
||||
id="endereco"
|
||||
value={formData.endereco}
|
||||
onChange={(e) => handleInputChange("endereco", e.target.value)}
|
||||
placeholder="Rua, Avenida, etc."
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-4 gap-4">
|
||||
<div className="space-y-2 col-span-1">
|
||||
<Label htmlFor="numero">Número</Label>
|
||||
<Input
|
||||
id="numero"
|
||||
value={formData.numero}
|
||||
onChange={(e) => handleInputChange("numero", e.target.value)}
|
||||
placeholder="123"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 col-span-3">
|
||||
<Label htmlFor="complemento">Complemento</Label>
|
||||
<Input
|
||||
id="complemento"
|
||||
value={formData.complemento}
|
||||
onChange={(e) => handleInputChange("complemento", e.target.value)}
|
||||
placeholder="Apto, Bloco, etc."
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-4 gap-4">
|
||||
<div className="space-y-2 col-span-2">
|
||||
<Label htmlFor="bairro">Bairro</Label>
|
||||
<Input
|
||||
id="bairro"
|
||||
value={formData.bairro}
|
||||
onChange={(e) => handleInputChange("bairro", e.target.value)}
|
||||
placeholder="Bairro"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 col-span-1">
|
||||
<Label htmlFor="cidade">Cidade</Label>
|
||||
<Input
|
||||
id="cidade"
|
||||
value={formData.cidade}
|
||||
onChange={(e) => handleInputChange("cidade", e.target.value)}
|
||||
placeholder="São Paulo"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 col-span-1">
|
||||
<Label htmlFor="estado">Estado (state)</Label>
|
||||
<Input
|
||||
id="estado"
|
||||
value={formData.estado}
|
||||
onChange={(e) => handleInputChange("estado", e.target.value)}
|
||||
placeholder="SP"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="space-y-4 p-4 border rounded-xl shadow-sm bg-white">
|
||||
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">
|
||||
Observações (Apenas internas)
|
||||
</h2>
|
||||
<Textarea
|
||||
id="observacoes"
|
||||
value={formData.observacoes}
|
||||
onChange={(e) => handleInputChange("observacoes", e.target.value)}
|
||||
placeholder="Notas internas sobre o médico..."
|
||||
className="min-h-[100px]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="flex justify-end gap-4 pb-8 pt-4">
|
||||
<Link href="/manager/home">
|
||||
<Button type="button" variant="outline" disabled={isSaving}>
|
||||
Cancelar
|
||||
</Button>
|
||||
</Link>
|
||||
<Button
|
||||
type="submit"
|
||||
className="bg-green-600 hover:bg-green-700"
|
||||
disabled={isSaving}
|
||||
>
|
||||
{isSaving ? (
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Save className="w-4 h-4 mr-2" />
|
||||
)}
|
||||
{isSaving ? "Salvando..." : "Salvar Alterações"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
@ -34,58 +34,59 @@ import Sidebar from "@/components/Sidebar";
|
||||
const PAGE_SIZE = 5;
|
||||
|
||||
export default function PacientesPage() {
|
||||
// --- ESTADOS DE DADOS E GERAL ---
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
const [convenioFilter, setConvenioFilter] = useState("all");
|
||||
const [vipFilter, setVipFilter] = useState("all");
|
||||
// --- ESTADOS DE DADOS E GERAL ---
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
const [convenioFilter, setConvenioFilter] = useState("all");
|
||||
const [vipFilter, setVipFilter] = useState("all");
|
||||
|
||||
// Lista completa, carregada da API uma única vez
|
||||
const [allPatients, setAllPatients] = useState<any[]>([]);
|
||||
// Lista após a aplicação dos filtros (base para a paginação)
|
||||
const [filteredPatients, setFilteredPatients] = useState<any[]>([]);
|
||||
// Lista completa, carregada da API uma única vez
|
||||
const [allPatients, setAllPatients] = useState<any[]>([]);
|
||||
// Lista após a aplicação dos filtros (base para a paginação)
|
||||
const [filteredPatients, setFilteredPatients] = useState<any[]>([]);
|
||||
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// --- ESTADOS DE PAGINAÇÃO ---
|
||||
const [page, setPage] = useState(1);
|
||||
// --- ESTADOS DE PAGINAÇÃO ---
|
||||
const [page, setPage] = useState(1);
|
||||
|
||||
// CÁLCULO DA PAGINAÇÃO
|
||||
const totalPages = Math.ceil(filteredPatients.length / PAGE_SIZE);
|
||||
const startIndex = (page - 1) * PAGE_SIZE;
|
||||
const endIndex = startIndex + PAGE_SIZE;
|
||||
// Pacientes a serem exibidos na tabela (aplicando a paginação)
|
||||
const currentPatients = filteredPatients.slice(startIndex, endIndex);
|
||||
// CÁLCULO DA PAGINAÇÃO
|
||||
const totalPages = Math.ceil(filteredPatients.length / PAGE_SIZE);
|
||||
const startIndex = (page - 1) * PAGE_SIZE;
|
||||
const endIndex = startIndex + PAGE_SIZE;
|
||||
// Pacientes a serem exibidos na tabela (aplicando a paginação)
|
||||
const currentPatients = filteredPatients.slice(startIndex, endIndex);
|
||||
|
||||
// --- ESTADOS DE DIALOGS ---
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [patientToDelete, setPatientToDelete] = useState<string | null>(null);
|
||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
||||
const [patientDetails, setPatientDetails] = useState<any | null>(null);
|
||||
// --- ESTADOS DE DIALOGS ---
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [patientToDelete, setPatientToDelete] = useState<string | null>(null);
|
||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
||||
const [patientDetails, setPatientDetails] = useState<any | null>(null);
|
||||
|
||||
// --- FUNÇÕES DE LÓGICA ---
|
||||
// --- FUNÇÕES DE LÓGICA ---
|
||||
|
||||
// 1. Função para carregar TODOS os pacientes da API
|
||||
const fetchAllPacientes = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
// Como o backend retorna um array, chamamos sem paginação
|
||||
const res = await patientsService.list();
|
||||
// 1. Função para carregar TODOS os pacientes da API
|
||||
const fetchAllPacientes = useCallback(
|
||||
async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
// Como o backend retorna um array, chamamos sem paginação
|
||||
const res = await patientsService.list();
|
||||
|
||||
const mapped = res.map((p: any) => ({
|
||||
id: String(p.id ?? ""),
|
||||
nome: p.full_name ?? "—",
|
||||
telefone: p.phone_mobile ?? p.phone1 ?? "—",
|
||||
cidade: p.city ?? "—",
|
||||
estado: p.state ?? "—",
|
||||
// Formate as datas se necessário, aqui usamos como string
|
||||
ultimoAtendimento: p.last_visit_at?.split("T")[0] ?? "—",
|
||||
proximoAtendimento: p.next_appointment_at?.split("T")[0] ?? "—",
|
||||
vip: Boolean(p.vip ?? false),
|
||||
convenio: p.convenio ?? "Particular", // Define um valor padrão
|
||||
status: p.status ?? undefined,
|
||||
}));
|
||||
const mapped = res.map((p: any) => ({
|
||||
id: String(p.id ?? ""),
|
||||
nome: p.full_name ?? "—",
|
||||
telefone: p.phone_mobile ?? p.phone1 ?? "—",
|
||||
cidade: p.city ?? "—",
|
||||
estado: p.state ?? "—",
|
||||
// Formate as datas se necessário, aqui usamos como string
|
||||
ultimoAtendimento: p.last_visit_at?.split('T')[0] ?? "—",
|
||||
proximoAtendimento: p.next_appointment_at ? p.next_appointment_at.split('T')[0].split('-').reverse().join('-') : "—",
|
||||
vip: Boolean(p.vip ?? false),
|
||||
convenio: p.convenio ?? "Particular", // Define um valor padrão
|
||||
status: p.status ?? undefined,
|
||||
}));
|
||||
|
||||
setAllPatients(mapped);
|
||||
} catch (e: any) {
|
||||
@ -96,31 +97,32 @@ export default function PacientesPage() {
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 2. Efeito para aplicar filtros e calcular a lista filtrada (chama-se quando allPatients ou filtros mudam)
|
||||
useEffect(() => {
|
||||
const filtered = allPatients.filter((patient) => {
|
||||
// Filtro por termo de busca (Nome ou Telefone)
|
||||
const matchesSearch =
|
||||
patient.nome?.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
patient.telefone?.includes(searchTerm);
|
||||
// 2. Efeito para aplicar filtros e calcular a lista filtrada (chama-se quando allPatients ou filtros mudam)
|
||||
useEffect(() => {
|
||||
const filtered = allPatients.filter((patient) => {
|
||||
// Filtro por termo de busca (Nome ou Telefone)
|
||||
const matchesSearch =
|
||||
patient.nome?.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
patient.telefone?.includes(searchTerm);
|
||||
|
||||
// Filtro por Convênio
|
||||
const matchesConvenio =
|
||||
convenioFilter === "all" || patient.convenio === convenioFilter;
|
||||
// Filtro por Convênio
|
||||
const matchesConvenio =
|
||||
convenioFilter === "all" ||
|
||||
patient.convenio === convenioFilter;
|
||||
|
||||
// Filtro por VIP
|
||||
const matchesVip =
|
||||
vipFilter === "all" ||
|
||||
(vipFilter === "vip" && patient.vip) ||
|
||||
(vipFilter === "regular" && !patient.vip);
|
||||
// Filtro por VIP
|
||||
const matchesVip =
|
||||
vipFilter === "all" ||
|
||||
(vipFilter === "vip" && patient.vip) ||
|
||||
(vipFilter === "regular" && !patient.vip);
|
||||
|
||||
return matchesSearch && matchesConvenio && matchesVip;
|
||||
});
|
||||
return matchesSearch && matchesConvenio && matchesVip;
|
||||
});
|
||||
|
||||
setFilteredPatients(filtered);
|
||||
// Garante que a página atual seja válida após a filtragem
|
||||
setPage(1);
|
||||
}, [allPatients, searchTerm, convenioFilter, vipFilter]);
|
||||
setFilteredPatients(filtered);
|
||||
// Garante que a página atual seja válida após a filtragem
|
||||
setPage(1);
|
||||
}, [allPatients, searchTerm, convenioFilter, vipFilter]);
|
||||
|
||||
// 3. Efeito inicial para buscar os pacientes
|
||||
useEffect(() => {
|
||||
@ -128,18 +130,18 @@ export default function PacientesPage() {
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
// --- LÓGICA DE AÇÕES (DELETAR / VER DETALHES) ---
|
||||
// --- LÓGICA DE AÇÕES (DELETAR / VER DETALHES) ---
|
||||
|
||||
const openDetailsDialog = async (patientId: string) => {
|
||||
setDetailsDialogOpen(true);
|
||||
setPatientDetails(null);
|
||||
try {
|
||||
const res = await patientsService.getById(patientId);
|
||||
setPatientDetails(Array.isArray(res) ? res[0] : res); // Supondo que retorne um array com um item
|
||||
} catch (e: any) {
|
||||
setPatientDetails({ error: e?.message || "Erro ao buscar detalhes" });
|
||||
}
|
||||
};
|
||||
const openDetailsDialog = async (patientId: string) => {
|
||||
setDetailsDialogOpen(true);
|
||||
setPatientDetails(null);
|
||||
try {
|
||||
const res = await patientsService.getById(patientId);
|
||||
setPatientDetails(Array.isArray(res) ? res[0] : res); // Supondo que retorne um array com um item
|
||||
} catch (e: any) {
|
||||
setPatientDetails({ error: e?.message || "Erro ao buscar detalhes" });
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeletePatient = async (patientId: string) => {
|
||||
try {
|
||||
@ -175,20 +177,20 @@ export default function PacientesPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Bloco de Filtros (Responsividade APLICADA) */}
|
||||
{/* Adicionado flex-wrap para permitir que os itens quebrem para a linha de baixo */}
|
||||
<div className="flex flex-wrap items-center gap-4 bg-card p-4 rounded-lg border border-border">
|
||||
<Filter className="w-5 h-5 text-gray-400" />
|
||||
{/* Bloco de Filtros (Responsividade APLICADA) */}
|
||||
{/* Adicionado flex-wrap para permitir que os itens quebrem para a linha de baixo */}
|
||||
<div className="flex flex-wrap items-center gap-4 bg-card p-4 rounded-lg border border-border">
|
||||
<Filter className="w-5 h-5 text-gray-400" />
|
||||
|
||||
{/* Busca - Ocupa 100% no mobile, depois cresce */}
|
||||
<input
|
||||
type="text"
|
||||
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"
|
||||
/>
|
||||
{/* Busca - Ocupa 100% no mobile, depois cresce */}
|
||||
<input
|
||||
type="text"
|
||||
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"
|
||||
/>
|
||||
|
||||
{/* 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]">
|
||||
@ -211,138 +213,91 @@ export default function PacientesPage() {
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* VIP - 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-[150px]">
|
||||
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">
|
||||
VIP
|
||||
</span>
|
||||
<Select value={vipFilter} onValueChange={setVipFilter}>
|
||||
<SelectTrigger className="w-full sm:w-32">
|
||||
{" "}
|
||||
{/* w-full para mobile, w-32 para sm+ */}
|
||||
<SelectValue placeholder="VIP" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todos</SelectItem>
|
||||
<SelectItem value="vip">VIP</SelectItem>
|
||||
<SelectItem value="regular">Regular</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
{/* VIP - 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-[150px]">
|
||||
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">VIP</span>
|
||||
<Select value={vipFilter} onValueChange={setVipFilter}>
|
||||
<SelectTrigger className="w-full sm:w-32"> {/* w-full para mobile, w-32 para sm+ */}
|
||||
<SelectValue placeholder="VIP" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todos</SelectItem>
|
||||
<SelectItem value="vip">VIP</SelectItem>
|
||||
<SelectItem value="regular">Regular</SelectItem>
|
||||
</SelectContent>
|
||||
</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>
|
||||
{/* 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 */}
|
||||
{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>
|
||||
) : (
|
||||
<table className="w-full min-w-[650px]">
|
||||
{" "}
|
||||
{/* min-w para evitar que a tabela se contraia demais */}
|
||||
<thead className="bg-gray-50 border-b border-gray-200">
|
||||
<tr>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[20%]">
|
||||
Nome
|
||||
</th>
|
||||
{/* Ajustes de visibilidade de colunas para diferentes breakpoints */}
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">
|
||||
Telefone
|
||||
</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden md:table-cell">
|
||||
Cidade / Estado
|
||||
</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">
|
||||
Convênio
|
||||
</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">
|
||||
Último atendimento
|
||||
</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">
|
||||
Próximo atendimento
|
||||
</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[5%]">
|
||||
Ações
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{currentPatients.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={7} className="p-8 text-center text-gray-500">
|
||||
{allPatients.length === 0
|
||||
? "Nenhum paciente cadastrado"
|
||||
: "Nenhum paciente encontrado com os filtros aplicados"}
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
currentPatients.map((patient) => (
|
||||
<tr
|
||||
key={patient.id}
|
||||
className="border-b border-gray-100 hover:bg-gray-50"
|
||||
>
|
||||
<td className="p-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
|
||||
<span className="text-blue-600 font-medium text-sm">
|
||||
{patient.nome?.charAt(0) || "?"}
|
||||
</span>
|
||||
{/* --- 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 */}
|
||||
{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>
|
||||
) : (
|
||||
<table className="w-full min-w-[650px]"> {/* min-w para evitar que a tabela se contraia demais */}
|
||||
<thead className="bg-gray-50 border-b border-gray-200">
|
||||
<tr>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[20%]">Nome</th>
|
||||
{/* Ajustes de visibilidade de colunas para diferentes breakpoints */}
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">Telefone</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden md:table-cell">Cidade / Estado</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">Convênio</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">Último atendimento</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">Próximo atendimento</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[5%]">Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{currentPatients.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={7} className="p-8 text-center text-gray-500">
|
||||
{allPatients.length === 0 ? "Nenhum paciente cadastrado" : "Nenhum paciente encontrado com os filtros aplicados"}
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
currentPatients.map((patient) => (
|
||||
<tr key={patient.id} className="border-b border-gray-100 hover:bg-gray-50">
|
||||
<td className="p-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
|
||||
<span className="text-green-600 font-medium text-sm">{patient.nome?.charAt(0) || "?"}</span>
|
||||
</div>
|
||||
<span className="font-medium text-gray-900">
|
||||
{patient.nome}
|
||||
{patient.vip && (
|
||||
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-600 bg-purple-100 rounded-full">VIP</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<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>
|
||||
|
||||
<span className="font-medium text-gray-900">
|
||||
{patient.nome}
|
||||
{patient.vip && (
|
||||
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-600 bg-purple-100 rounded-full">
|
||||
VIP
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<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">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<div className="text-blue-600 cursor-pointer">
|
||||
Ações
|
||||
</div>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
openDetailsDialog(String(patient.id))
|
||||
}
|
||||
>
|
||||
<Eye className="w-4 h-4 mr-2" />
|
||||
Ver detalhes
|
||||
</DropdownMenuItem>
|
||||
<td className="p-4">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<div className="text-blue-600 cursor-pointer">Ações</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
|
||||
@ -379,249 +334,208 @@ 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>
|
||||
{/* --- 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 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>
|
||||
<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>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Paginação */}
|
||||
{totalPages > 1 && !loading && (
|
||||
<div className="flex flex-col sm:flex-row items-center justify-center p-4 border-t border-gray-200">
|
||||
<div className="flex space-x-2 flex-wrap justify-center">
|
||||
{" "}
|
||||
{/* Adicionado flex-wrap e justify-center para botões da paginação */}
|
||||
<Button
|
||||
onClick={() => setPage((prev) => Math.max(1, prev - 1))}
|
||||
disabled={page === 1}
|
||||
variant="outline"
|
||||
size="lg"
|
||||
>
|
||||
< Anterior
|
||||
</Button>
|
||||
{Array.from({ length: totalPages }, (_, index) => index + 1)
|
||||
.slice(Math.max(0, page - 3), Math.min(totalPages, page + 2))
|
||||
.map((pageNumber) => (
|
||||
<Button
|
||||
key={pageNumber}
|
||||
onClick={() => setPage(pageNumber)}
|
||||
variant={pageNumber === page ? "default" : "outline"}
|
||||
size="lg"
|
||||
className={
|
||||
pageNumber === page
|
||||
? "bg-blue-600 hover:bg-blue-700 text-white"
|
||||
: "text-gray-700"
|
||||
}
|
||||
>
|
||||
{pageNumber}
|
||||
</Button>
|
||||
))}
|
||||
<Button
|
||||
onClick={() =>
|
||||
setPage((prev) => Math.min(totalPages, prev + 1))
|
||||
}
|
||||
disabled={page === totalPages}
|
||||
variant="outline"
|
||||
size="lg"
|
||||
>
|
||||
Próximo >
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{/* Paginação */}
|
||||
{totalPages > 1 && !loading && (
|
||||
<div className="flex flex-col sm:flex-row items-center justify-center p-4 border-t border-gray-200">
|
||||
<div className="flex space-x-2 flex-wrap justify-center"> {/* Adicionado flex-wrap e justify-center para botões da paginação */}
|
||||
<Button
|
||||
onClick={() => setPage((prev) => Math.max(1, prev - 1))}
|
||||
disabled={page === 1}
|
||||
variant="outline"
|
||||
size="lg"
|
||||
>
|
||||
< Anterior
|
||||
</Button>
|
||||
|
||||
{/* AlertDialogs (Permanecem os mesmos) */}
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Tem certeza que deseja excluir este paciente? Esta ação não pode
|
||||
ser desfeita.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancelar</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() =>
|
||||
patientToDelete && handleDeletePatient(patientToDelete)
|
||||
}
|
||||
className="bg-red-600 hover:bg-red-700"
|
||||
>
|
||||
Excluir
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
{Array.from({ length: totalPages }, (_, index) => index + 1)
|
||||
.slice(Math.max(0, page - 3), Math.min(totalPages, page + 2))
|
||||
.map((pageNumber) => (
|
||||
<Button
|
||||
key={pageNumber}
|
||||
onClick={() => setPage(pageNumber)}
|
||||
variant={pageNumber === page ? "default" : "outline"}
|
||||
size="lg"
|
||||
className={pageNumber === page ? "bg-green-600 hover:bg-green-700 text-white" : "text-gray-700"}
|
||||
>
|
||||
{pageNumber}
|
||||
</Button>
|
||||
))}
|
||||
|
||||
<AlertDialog
|
||||
open={detailsDialogOpen}
|
||||
onOpenChange={setDetailsDialogOpen}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Detalhes do Paciente</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{patientDetails === null ? (
|
||||
<div className="text-gray-500">
|
||||
<Loader2 className="w-6 h-6 animate-spin mx-auto text-green-600 my-4" />
|
||||
Carregando...
|
||||
</div>
|
||||
) : patientDetails?.error ? (
|
||||
<div className="text-red-600 p-4">{patientDetails.error}</div>
|
||||
) : (
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<p className="font-semibold">Nome Completo</p>
|
||||
<p>{patientDetails.full_name}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Email</p>
|
||||
<p>{patientDetails.email}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Telefone</p>
|
||||
<p>{patientDetails.phone_mobile}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Data de Nascimento</p>
|
||||
<p>{patientDetails.birth_date}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">CPF</p>
|
||||
<p>{patientDetails.cpf}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Tipo Sanguíneo</p>
|
||||
<p>{patientDetails.blood_type}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Peso (kg)</p>
|
||||
<p>{patientDetails.weight_kg}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Altura (m)</p>
|
||||
<p>{patientDetails.height_m}</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => setPage((prev) => Math.min(totalPages, prev + 1))}
|
||||
disabled={page === totalPages}
|
||||
variant="outline"
|
||||
size="lg"
|
||||
>
|
||||
Próximo >
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-t pt-4 mt-4">
|
||||
<h3 className="font-semibold mb-2">Endereço</h3>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<p className="font-semibold">Rua</p>
|
||||
<p>{`${patientDetails.street}, ${patientDetails.number}`}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Complemento</p>
|
||||
<p>{patientDetails.complement}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Bairro</p>
|
||||
<p>{patientDetails.neighborhood}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Cidade</p>
|
||||
<p>{patientDetails.cidade}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Estado</p>
|
||||
<p>{patientDetails.estado}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">CEP</p>
|
||||
<p>{patientDetails.cep}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Fechar</AlertDialogCancel>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</Sidebar>
|
||||
);
|
||||
|
||||
{/* AlertDialogs (Permanecem os mesmos) */}
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
|
||||
<AlertDialogDescription>Tem certeza que deseja excluir este paciente? Esta ação não pode ser desfeita.</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancelar</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={() => patientToDelete && handleDeletePatient(patientToDelete)} className="bg-red-600 hover:bg-red-700">
|
||||
Excluir
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Detalhes do Paciente</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{patientDetails === null ? (
|
||||
<div className="text-gray-500">
|
||||
<Loader2 className="w-6 h-6 animate-spin mx-auto text-green-600 my-4" />
|
||||
Carregando...
|
||||
</div>
|
||||
) : patientDetails?.error ? (
|
||||
<div className="text-red-600 p-4">{patientDetails.error}</div>
|
||||
) : (
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<p className="font-semibold">Nome Completo</p>
|
||||
<p>{patientDetails.full_name}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Email</p>
|
||||
<p>{patientDetails.email}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Telefone</p>
|
||||
<p>{patientDetails.phone_mobile}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Data de Nascimento</p>
|
||||
<p>{patientDetails.birth_date}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">CPF</p>
|
||||
<p>{patientDetails.cpf}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Tipo Sanguíneo</p>
|
||||
<p>{patientDetails.blood_type}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Peso (kg)</p>
|
||||
<p>{patientDetails.weight_kg}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Altura (m)</p>
|
||||
<p>{patientDetails.height_m}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-t pt-4 mt-4">
|
||||
<h3 className="font-semibold mb-2">Endereço</h3>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<p className="font-semibold">Rua</p>
|
||||
<p>{`${patientDetails.street}, ${patientDetails.number}`}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Complemento</p>
|
||||
<p>{patientDetails.complement}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Bairro</p>
|
||||
<p>{patientDetails.neighborhood}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Cidade</p>
|
||||
<p>{patientDetails.cidade}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Estado</p>
|
||||
<p>{patientDetails.estado}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">CEP</p>
|
||||
<p>{patientDetails.cep}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Fechar</AlertDialogCancel>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user