forked from RiseUP/riseup-squad21
Atualiza cards com dados de APIs e corrige contagens
This commit is contained in:
parent
01aecc4485
commit
ddc4443114
@ -31,7 +31,7 @@ interface EnrichedAppointment {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function DoctorAppointmentsPage() {
|
export default function DoctorAppointmentsPage() {
|
||||||
const { user, isLoading: isAuthLoading } = useAuthLayout({ requiredRole: 'medico' });
|
const { user, isLoading: isAuthLoading } = useAuthLayout({ requiredRole: ['medico'] });
|
||||||
|
|
||||||
const [allAppointments, setAllAppointments] = useState<EnrichedAppointment[]>([]);
|
const [allAppointments, setAllAppointments] = useState<EnrichedAppointment[]>([]);
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
@ -153,7 +153,7 @@ export default function DoctorAppointmentsPage() {
|
|||||||
<Card>
|
<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>
|
<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">
|
<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>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -9,104 +9,42 @@ import Link from "next/link";
|
|||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { toast } from "@/hooks/use-toast";
|
import { toast } from "@/hooks/use-toast";
|
||||||
|
|
||||||
|
// --- IMPORTS ADICIONADOS PARA A CORREÇÃO ---
|
||||||
|
import { useAuthLayout } from "@/hooks/useAuthLayout";
|
||||||
|
import { patientsService } from "@/services/patientsApi.mjs";
|
||||||
|
// --- FIM DOS IMPORTS ADICIONADOS ---
|
||||||
|
|
||||||
|
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
||||||
|
import { format, parseISO, isAfter, isSameMonth, startOfToday } from "date-fns";
|
||||||
|
import { ptBR } from "date-fns/locale";
|
||||||
|
|
||||||
import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
||||||
import { exceptionsService } from "@/services/exceptionApi.mjs";
|
import { exceptionsService } from "@/services/exceptionApi.mjs";
|
||||||
import { doctorsService } from "@/services/doctorsApi.mjs";
|
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||||
import { usersService } from "@/services/usersApi.mjs";
|
import { usersService } from "@/services/usersApi.mjs";
|
||||||
import Sidebar from "@/components/Sidebar";
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
type Availability = {
|
// (As interfaces permanecem as mesmas)
|
||||||
|
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; };
|
||||||
|
type Schedule = { weekday: object; };
|
||||||
|
type Doctor = { id: string; user_id: string | null; crm: string; crm_uf: string; specialty: string; full_name: string; cpf: string; email: string; phone_mobile: string | null; phone2: string | null; cep: string | null; street: string | null; number: string | null; complement: string | null; neighborhood: string | null; city: string | null; state: string | null; birth_date: string | null; rg: string | null; active: boolean; created_at: string; updated_at: string; created_by: string; updated_by: string | null; max_days_in_advance: number; rating: number | null; }
|
||||||
|
interface UserPermissions { isAdmin: boolean; isManager: boolean; isDoctor: boolean; isSecretary: boolean; isAdminOrManager: boolean; }
|
||||||
|
interface UserData { user: { id: string; email: string; email_confirmed_at: string | null; created_at: string | null; last_sign_in_at: string | null; }; profile: { id: string; full_name: string; email: string; phone: string; avatar_url: string | null; disabled: boolean; created_at: string | null; updated_at: string | null; }; roles: string[]; permissions: UserPermissions; }
|
||||||
|
interface Exception { id: string; doctor_id: string; date: string; start_time: string | null; end_time: string | null; kind: "bloqueio" | "disponibilidade"; reason: string | null; created_at: string; created_by: string; }
|
||||||
|
|
||||||
|
// --- NOVA INTERFACE PARA A CONSULTA COM NOME DO PACIENTE ---
|
||||||
|
interface EnrichedAppointment {
|
||||||
id: string;
|
id: string;
|
||||||
doctor_id: string;
|
patientName: string;
|
||||||
weekday: string;
|
scheduled_at: string;
|
||||||
start_time: string;
|
[key: string]: any;
|
||||||
end_time: string;
|
|
||||||
slot_minutes: number;
|
|
||||||
appointment_type: string;
|
|
||||||
active: boolean;
|
|
||||||
created_at: string;
|
|
||||||
updated_at: string;
|
|
||||||
created_by: string;
|
|
||||||
updated_by: string | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
type Schedule = {
|
|
||||||
weekday: object;
|
|
||||||
};
|
|
||||||
|
|
||||||
type Doctor = {
|
|
||||||
id: string;
|
|
||||||
user_id: string | null;
|
|
||||||
crm: string;
|
|
||||||
crm_uf: string;
|
|
||||||
specialty: string;
|
|
||||||
full_name: string;
|
|
||||||
cpf: string;
|
|
||||||
email: string;
|
|
||||||
phone_mobile: string | null;
|
|
||||||
phone2: string | null;
|
|
||||||
cep: string | null;
|
|
||||||
street: string | null;
|
|
||||||
number: string | null;
|
|
||||||
complement: string | null;
|
|
||||||
neighborhood: string | null;
|
|
||||||
city: string | null;
|
|
||||||
state: string | null;
|
|
||||||
birth_date: string | null;
|
|
||||||
rg: string | null;
|
|
||||||
active: boolean;
|
|
||||||
created_at: string;
|
|
||||||
updated_at: string;
|
|
||||||
created_by: string;
|
|
||||||
updated_by: string | null;
|
|
||||||
max_days_in_advance: number;
|
|
||||||
rating: number | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface UserPermissions {
|
|
||||||
isAdmin: boolean;
|
|
||||||
isManager: boolean;
|
|
||||||
isDoctor: boolean;
|
|
||||||
isSecretary: boolean;
|
|
||||||
isAdminOrManager: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface UserData {
|
|
||||||
user: {
|
|
||||||
id: string;
|
|
||||||
email: string;
|
|
||||||
email_confirmed_at: string | null;
|
|
||||||
created_at: string | null;
|
|
||||||
last_sign_in_at: string | null;
|
|
||||||
};
|
|
||||||
profile: {
|
|
||||||
id: string;
|
|
||||||
full_name: string;
|
|
||||||
email: string;
|
|
||||||
phone: string;
|
|
||||||
avatar_url: string | null;
|
|
||||||
disabled: boolean;
|
|
||||||
created_at: string | null;
|
|
||||||
updated_at: string | null;
|
|
||||||
};
|
|
||||||
roles: string[];
|
|
||||||
permissions: UserPermissions;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Exception {
|
|
||||||
id: string; // id da exceção
|
|
||||||
doctor_id: string;
|
|
||||||
date: string; // formato YYYY-MM-DD
|
|
||||||
start_time: string | null; // null = dia inteiro
|
|
||||||
end_time: string | null; // null = dia inteiro
|
|
||||||
kind: "bloqueio" | "disponibilidade"; // tipos conhecidos
|
|
||||||
reason: string | null; // pode ser null
|
|
||||||
created_at: string; // timestamp ISO
|
|
||||||
created_by: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function PatientDashboard() {
|
export default function PatientDashboard() {
|
||||||
const [loggedDoctor, setLoggedDoctor] = useState<Doctor>();
|
// --- USA O HOOK DE AUTENTICAÇÃO PARA PEGAR O USUÁRIO LOGADO ---
|
||||||
|
const { user } = useAuthLayout({ requiredRole: ['medico'] });
|
||||||
|
|
||||||
|
const [loggedDoctor, setLoggedDoctor] = useState<Doctor | null>(null);
|
||||||
const [userData, setUserData] = useState<UserData>();
|
const [userData, setUserData] = useState<UserData>();
|
||||||
const [availability, setAvailability] = useState<any | null>(null);
|
const [availability, setAvailability] = useState<any | null>(null);
|
||||||
const [exceptions, setExceptions] = useState<Exception[]>([]);
|
const [exceptions, setExceptions] = useState<Exception[]>([]);
|
||||||
@ -116,52 +54,75 @@ export default function PatientDashboard() {
|
|||||||
const [exceptionToDelete, setExceptionToDelete] = useState<string | null>(null);
|
const [exceptionToDelete, setExceptionToDelete] = useState<string | null>(null);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
// Mapa de tradução
|
// --- ESTADOS PARA OS CARDS ATUALIZADOS ---
|
||||||
const weekdaysPT: Record<string, string> = {
|
const [nextAppointment, setNextAppointment] = useState<EnrichedAppointment | null>(null);
|
||||||
sunday: "Domingo",
|
const [monthlyCount, setMonthlyCount] = useState<number>(0);
|
||||||
monday: "Segunda",
|
|
||||||
tuesday: "Terça",
|
|
||||||
wednesday: "Quarta",
|
|
||||||
thursday: "Quinta",
|
|
||||||
friday: "Sexta",
|
|
||||||
saturday: "Sábado",
|
|
||||||
};
|
|
||||||
|
|
||||||
|
const weekdaysPT: Record<string, string> = { sunday: "Domingo", monday: "Segunda", tuesday: "Terça", wednesday: "Quarta", thursday: "Quinta", friday: "Sexta", saturday: "Sábado" };
|
||||||
|
|
||||||
|
// ▼▼▼ LÓGICA DE BUSCA CORRIGIDA E ATUALIZADA ▼▼▼
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchData = async () => {
|
const fetchData = async () => {
|
||||||
|
if (!user?.id) return; // Aguarda o usuário ser carregado
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// Encontra o perfil de médico correspondente ao usuário logado
|
||||||
const doctorsList: Doctor[] = await doctorsService.list();
|
const doctorsList: Doctor[] = await doctorsService.list();
|
||||||
const doctor = doctorsList[0];
|
const currentDoctor = doctorsList.find(doc => doc.user_id === user.id);
|
||||||
|
|
||||||
// Salva no estado
|
if (!currentDoctor) {
|
||||||
setLoggedDoctor(doctor);
|
setError("Perfil de médico não encontrado para este usuário.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLoggedDoctor(currentDoctor);
|
||||||
|
|
||||||
// Busca disponibilidade
|
// Busca todos os dados necessários em paralelo
|
||||||
const availabilityList = await AvailabilityService.list();
|
const [appointmentsList, patientsList, availabilityList, exceptionsList] = await Promise.all([
|
||||||
|
appointmentsService.list(),
|
||||||
|
patientsService.list(),
|
||||||
|
AvailabilityService.list(),
|
||||||
|
exceptionsService.list()
|
||||||
|
]);
|
||||||
|
|
||||||
// Filtra já com a variável local
|
// Mapeia pacientes por ID para consulta rápida
|
||||||
const filteredAvail = availabilityList.filter(
|
const patientsMap = new Map(patientsList.map((p: any) => [p.id, p.full_name]));
|
||||||
(disp: { doctor_id: string }) => disp.doctor_id === doctor?.id
|
|
||||||
|
// 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
|
// Busca e filtra o restante dos dados
|
||||||
const exceptionsList = await exceptionsService.list();
|
setAvailability(availabilityList.filter((d: any) => d.doctor_id === currentDoctor.id));
|
||||||
const filteredExc = exceptionsList.filter(
|
setExceptions(exceptionsList.filter((e: any) => e.doctor_id === currentDoctor.id));
|
||||||
(exc: { doctor_id: string }) => exc.doctor_id === doctor?.id
|
|
||||||
);
|
|
||||||
console.log(exceptionsList)
|
|
||||||
setExceptions(filteredExc);
|
|
||||||
|
|
||||||
} catch (e: any) {
|
} 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[]) {
|
function findDoctorById(id: string, doctors: Doctor[]) {
|
||||||
return doctors.find((doctor) => doctor.user_id === id);
|
return doctors.find((doctor) => doctor.user_id === id);
|
||||||
}
|
}
|
||||||
@ -173,53 +134,25 @@ export default function PatientDashboard() {
|
|||||||
|
|
||||||
const handleDeleteException = async (ExceptionId: string) => {
|
const handleDeleteException = async (ExceptionId: string) => {
|
||||||
try {
|
try {
|
||||||
alert(ExceptionId)
|
|
||||||
const res = await exceptionsService.delete(ExceptionId);
|
const res = await exceptionsService.delete(ExceptionId);
|
||||||
|
if (res && res.error) { throw new Error(res.message || "A API retornou um erro"); }
|
||||||
let message = "Exceção deletada com sucesso";
|
toast({ title: "Sucesso", description: "Exceção deletada com sucesso" });
|
||||||
try {
|
|
||||||
if (res) {
|
|
||||||
throw new Error(`${res.error} ${res.message}` || "A API retornou erro");
|
|
||||||
} else {
|
|
||||||
console.log(message);
|
|
||||||
}
|
|
||||||
} catch {}
|
|
||||||
|
|
||||||
toast({
|
|
||||||
title: "Sucesso",
|
|
||||||
description: message,
|
|
||||||
});
|
|
||||||
|
|
||||||
setExceptions((prev: Exception[]) => prev.filter((p) => String(p.id) !== String(ExceptionId)));
|
setExceptions((prev: Exception[]) => prev.filter((p) => String(p.id) !== String(ExceptionId)));
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
toast({
|
toast({ title: "Erro", description: e?.message || "Não foi possível deletar a exceção" });
|
||||||
title: "Erro",
|
|
||||||
description: e?.message || "Não foi possível deletar a exceção",
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
setDeleteDialogOpen(false);
|
setDeleteDialogOpen(false);
|
||||||
setExceptionToDelete(null);
|
setExceptionToDelete(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
function formatAvailability(data: Availability[]) {
|
function formatAvailability(data: Availability[]) {
|
||||||
// Agrupar os horários por dia da semana
|
if (!data) return {};
|
||||||
const schedule = data.reduce((acc: any, item) => {
|
const schedule = data.reduce((acc: any, item) => {
|
||||||
const { weekday, start_time, end_time } = item;
|
const { weekday, start_time, end_time } = item;
|
||||||
|
if (!acc[weekday]) acc[weekday] = [];
|
||||||
// Se o dia ainda não existe, cria o array
|
acc[weekday].push({ start: start_time, end: end_time });
|
||||||
if (!acc[weekday]) {
|
|
||||||
acc[weekday] = [];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Adiciona o horário do dia
|
|
||||||
acc[weekday].push({
|
|
||||||
start: start_time,
|
|
||||||
end: end_time,
|
|
||||||
});
|
|
||||||
|
|
||||||
return acc;
|
return acc;
|
||||||
}, {} as Record<string, { start: string; end: string }[]>);
|
}, {} as Record<string, { start: string; end: string }[]>);
|
||||||
|
|
||||||
return schedule;
|
return schedule;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -239,27 +172,44 @@ export default function PatientDashboard() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||||
|
{/* ▼▼▼ CARD "PRÓXIMA CONSULTA" CORRIGIDO PARA MOSTRAR NOME DO PACIENTE ▼▼▼ */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||||
<CardTitle className="text-sm font-medium">Próxima Consulta</CardTitle>
|
<CardTitle className="text-sm font-medium">Próxima Consulta</CardTitle>
|
||||||
<Calendar className="h-4 w-4 text-muted-foreground" />
|
<Calendar className="h-4 w-4 text-muted-foreground" />
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div className="text-2xl font-bold">02 out</div>
|
{nextAppointment ? (
|
||||||
<p className="text-xs text-muted-foreground">Dr. Silva - 14:30</p>
|
<>
|
||||||
|
<div className="text-2xl font-bold capitalize">
|
||||||
|
{format(parseISO(nextAppointment.scheduled_at), "dd MMM", { locale: ptBR })}
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{nextAppointment.patientName} - {format(parseISO(nextAppointment.scheduled_at), "HH:mm")}
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="text-2xl font-bold">Nenhuma</div>
|
||||||
|
<p className="text-xs text-muted-foreground">Sem próximas consultas</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
{/* ▲▲▲ FIM DO CARD ATUALIZADO ▲▲▲ */}
|
||||||
|
|
||||||
|
{/* ▼▼▼ CARD "CONSULTAS ESTE MÊS" CORRIGIDO PARA CONTAGEM CORRETA ▼▼▼ */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||||
<CardTitle className="text-sm font-medium">Consultas Este Mês</CardTitle>
|
<CardTitle className="text-sm font-medium">Consultas Este Mês</CardTitle>
|
||||||
<Clock className="h-4 w-4 text-muted-foreground" />
|
<Clock className="h-4 w-4 text-muted-foreground" />
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div className="text-2xl font-bold">4</div>
|
<div className="text-2xl font-bold">{monthlyCount}</div>
|
||||||
<p className="text-xs text-muted-foreground">4 agendadas</p>
|
<p className="text-xs text-muted-foreground">{monthlyCount === 1 ? '1 agendada' : `${monthlyCount} agendadas`}</p>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
{/* ▲▲▲ FIM DO CARD ATUALIZADO ▲▲▲ */}
|
||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||||
@ -273,6 +223,7 @@ export default function PatientDashboard() {
|
|||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* O restante do código permanece o mesmo */}
|
||||||
<div className="grid md:grid-cols-2 gap-6">
|
<div className="grid md:grid-cols-2 gap-6">
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
@ -353,7 +304,6 @@ export default function PatientDashboard() {
|
|||||||
<CardContent className="space-y-4 grid md:grid-cols-7 gap-2">
|
<CardContent className="space-y-4 grid md:grid-cols-7 gap-2">
|
||||||
{exceptions && exceptions.length > 0 ? (
|
{exceptions && exceptions.length > 0 ? (
|
||||||
exceptions.map((ex: Exception) => {
|
exceptions.map((ex: Exception) => {
|
||||||
// Formata data e hora
|
|
||||||
const date = new Date(ex.date).toLocaleDateString("pt-BR", {
|
const date = new Date(ex.date).toLocaleDateString("pt-BR", {
|
||||||
weekday: "long",
|
weekday: "long",
|
||||||
day: "2-digit",
|
day: "2-digit",
|
||||||
|
|||||||
@ -2,12 +2,13 @@
|
|||||||
|
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Calendar, Clock, Plus, User } from "lucide-react";
|
import { Clock, Plus, User } from "lucide-react"; // Removi 'Calendar' que não estava sendo usado
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import React, { useState, useEffect } from "react";
|
import React, { useState, useEffect } from "react";
|
||||||
import { usersService } from "services/usersApi.mjs";
|
import { usersService } from "services/usersApi.mjs";
|
||||||
import { doctorsService } from "services/doctorsApi.mjs";
|
import { doctorsService } from "services/doctorsApi.mjs";
|
||||||
import Sidebar from "@/components/Sidebar";
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
import { api } from "services/api.mjs"; // <-- ADICIONEI ESTE IMPORT
|
||||||
|
|
||||||
export default function ManagerDashboard() {
|
export default function ManagerDashboard() {
|
||||||
// 🔹 Estados para usuários
|
// 🔹 Estados para usuários
|
||||||
@ -18,16 +19,44 @@ export default function ManagerDashboard() {
|
|||||||
const [doctors, setDoctors] = useState<any[]>([]);
|
const [doctors, setDoctors] = useState<any[]>([]);
|
||||||
const [loadingDoctors, setLoadingDoctors] = useState(true);
|
const [loadingDoctors, setLoadingDoctors] = useState(true);
|
||||||
|
|
||||||
// 🔹 Buscar primeiro usuário
|
// 🔹 Buscar primeiro usuário (LÓGICA ATUALIZADA)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
async function fetchFirstUser() {
|
async function fetchFirstUser() {
|
||||||
|
setLoadingUser(true); // Garante que o estado de loading inicie como true
|
||||||
try {
|
try {
|
||||||
const data = await usersService.list_roles();
|
// 1. Busca a lista de usuários com seus cargos (roles)
|
||||||
if (Array.isArray(data) && data.length > 0) {
|
const rolesData = await usersService.list_roles();
|
||||||
setFirstUser(data[0]);
|
|
||||||
|
// 2. Verifica se a lista não está vazia
|
||||||
|
if (Array.isArray(rolesData) && rolesData.length > 0) {
|
||||||
|
const firstUserRole = rolesData[0];
|
||||||
|
const firstUserId = firstUserRole.user_id;
|
||||||
|
|
||||||
|
if (!firstUserId) {
|
||||||
|
throw new Error("O primeiro usuário da lista não possui um ID válido.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Usa o ID para buscar o perfil (com nome e email) do usuário
|
||||||
|
const profileData = await api.get(
|
||||||
|
`/rest/v1/profiles?select=full_name,email&id=eq.${firstUserId}`
|
||||||
|
);
|
||||||
|
|
||||||
|
// 4. Verifica se o perfil foi encontrado
|
||||||
|
if (Array.isArray(profileData) && profileData.length > 0) {
|
||||||
|
const userProfile = profileData[0];
|
||||||
|
// 5. Combina os dados do cargo e do perfil e atualiza o estado
|
||||||
|
setFirstUser({
|
||||||
|
...firstUserRole,
|
||||||
|
...userProfile
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// Se não encontrar o perfil, exibe os dados que temos
|
||||||
|
setFirstUser(firstUserRole);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Erro ao carregar usuário:", error);
|
console.error("Erro ao carregar usuário:", error);
|
||||||
|
setFirstUser(null); // Limpa o usuário em caso de erro
|
||||||
} finally {
|
} finally {
|
||||||
setLoadingUser(false);
|
setLoadingUser(false);
|
||||||
}
|
}
|
||||||
@ -65,17 +94,7 @@ export default function ManagerDashboard() {
|
|||||||
|
|
||||||
{/* Cards principais */}
|
{/* Cards principais */}
|
||||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||||
{/* Card 1 */}
|
|
||||||
<Card>
|
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
|
||||||
<CardTitle className="text-sm font-medium">Relatórios gerenciais</CardTitle>
|
|
||||||
<Calendar className="h-4 w-4 text-muted-foreground" />
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<div className="text-2xl font-bold">0</div>
|
|
||||||
<p className="text-xs text-muted-foreground">Relatórios disponíveis</p>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* Card 2 — Gestão de usuários */}
|
{/* Card 2 — Gestão de usuários */}
|
||||||
<Card>
|
<Card>
|
||||||
|
|||||||
@ -225,7 +225,7 @@ export default function EditarMedicoPage() {
|
|||||||
Editar Médico: <span className="text-green-600">{formData.nomeCompleto}</span>
|
Editar Médico: <span className="text-green-600">{formData.nomeCompleto}</span>
|
||||||
</h1>
|
</h1>
|
||||||
<p className="text-sm text-gray-500">
|
<p className="text-sm text-gray-500">
|
||||||
Atualize as informações do médico (ID: {id}).
|
Atualize as informações do médico
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<Link href="/manager/home">
|
<Link href="/manager/home">
|
||||||
|
|||||||
@ -62,7 +62,7 @@ export default function PacientesPage() {
|
|||||||
estado: p.state ?? "—",
|
estado: p.state ?? "—",
|
||||||
// Formate as datas se necessário, aqui usamos como string
|
// Formate as datas se necessário, aqui usamos como string
|
||||||
ultimoAtendimento: p.last_visit_at?.split('T')[0] ?? "—",
|
ultimoAtendimento: p.last_visit_at?.split('T')[0] ?? "—",
|
||||||
proximoAtendimento: p.next_appointment_at?.split('T')[0] ?? "—",
|
proximoAtendimento: p.next_appointment_at ? p.next_appointment_at.split('T')[0].split('-').reverse().join('-') : "—",
|
||||||
vip: Boolean(p.vip ?? false),
|
vip: Boolean(p.vip ?? false),
|
||||||
convenio: p.convenio ?? "Particular", // Define um valor padrão
|
convenio: p.convenio ?? "Particular", // Define um valor padrão
|
||||||
status: p.status ?? undefined,
|
status: p.status ?? undefined,
|
||||||
|
|||||||
@ -174,7 +174,6 @@ export default function Sidebar({ children }: SidebarProps) {
|
|||||||
|
|
||||||
const managerItems: MenuItem[] = [
|
const managerItems: MenuItem[] = [
|
||||||
{ href: "/manager/dashboard", icon: Home, label: "Dashboard" },
|
{ 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/usuario", icon: Users, label: "Gestão de Usuários" },
|
||||||
{ href: "/manager/home", icon: Stethoscope, label: "Gestão de Médicos" },
|
{ href: "/manager/home", icon: Stethoscope, label: "Gestão de Médicos" },
|
||||||
{ href: "/manager/pacientes", icon: Users, label: "Gestão de Pacientes" },
|
{ href: "/manager/pacientes", icon: Users, label: "Gestão de Pacientes" },
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user