Merge branch 'Stage' of https://github.com/m1guelmcf/MedConnect into ajustes-agendamentio
This commit is contained in:
commit
4957c9c55a
@ -31,7 +31,7 @@ interface EnrichedAppointment {
|
||||
}
|
||||
|
||||
export default function DoctorAppointmentsPage() {
|
||||
const { user, isLoading: isAuthLoading } = useAuthLayout({ requiredRole: 'medico' });
|
||||
const { user, isLoading: isAuthLoading } = useAuthLayout({ requiredRole: "medico" });
|
||||
|
||||
const [allAppointments, setAllAppointments] = useState<EnrichedAppointment[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
@ -111,13 +111,22 @@ export default function DoctorAppointmentsPage() {
|
||||
return format(date, "EEEE, dd 'de' MMMM", { locale: ptBR });
|
||||
};
|
||||
|
||||
const statusPT: Record<string, string> = {
|
||||
confirmed: "Confirmada",
|
||||
completed: "Concluída",
|
||||
cancelled: "Cancelada",
|
||||
requested: "Solicitada",
|
||||
no_show: "oculta",
|
||||
checked_in: "Aguardando",
|
||||
};
|
||||
|
||||
const getStatusVariant = (status: EnrichedAppointment['status']) => {
|
||||
switch (status) {
|
||||
case "confirmed": case "checked_in": return "default";
|
||||
case "completed": return "secondary";
|
||||
case "cancelled": case "no_show": return "destructive";
|
||||
case "requested": return "outline";
|
||||
default: return "outline";
|
||||
case "confirmed": case "checked_in": return "text-foreground bg-blue-100 hover:bg-blue-150";
|
||||
case "completed": return "text-foreground bg-green-100 hover:bg-green-150";
|
||||
case "cancelled": case "no_show": return "text-foreground bg-red-200 hover:bg-red-250";
|
||||
case "requested": return "text-foreground bg-yellow-100 hover:bg-yellow-150";
|
||||
default: return "border-gray bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90";
|
||||
}
|
||||
};
|
||||
|
||||
@ -191,7 +200,7 @@ export default function DoctorAppointmentsPage() {
|
||||
|
||||
{/* Coluna 2: Status e Telefone */}
|
||||
<div className="col-span-1 flex flex-col items-center gap-2">
|
||||
<Badge variant={getStatusVariant(appointment.status)} className="capitalize text-xs">{appointment.status.replace('_', ' ')}</Badge>
|
||||
<Badge variant="outline" className={getStatusVariant(appointment.status)}>{statusPT[appointment.status].replace('_', ' ')}</Badge>
|
||||
<div className="flex items-center text-sm text-muted-foreground">
|
||||
<Phone className="mr-2 h-4 w-4" />
|
||||
{appointment.patientPhone}
|
||||
|
||||
@ -1,9 +1,24 @@
|
||||
"use client";
|
||||
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Calendar, Clock, User, Trash2 } from "lucide-react";
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useEffect, useState } from "react";
|
||||
@ -14,24 +29,25 @@ import { exceptionsService } from "@/services/exceptionApi.mjs";
|
||||
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||
import { usersService } from "@/services/usersApi.mjs";
|
||||
import Sidebar from "@/components/Sidebar";
|
||||
import WeeklyScheduleCard from "@/components/ui/WeeklyScheduleCard";
|
||||
|
||||
type Availability = {
|
||||
id: string;
|
||||
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;
|
||||
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;
|
||||
weekday: object;
|
||||
};
|
||||
|
||||
type Doctor = {
|
||||
@ -61,36 +77,36 @@ type Doctor = {
|
||||
updated_by: string | null;
|
||||
max_days_in_advance: number;
|
||||
rating: number | null;
|
||||
}
|
||||
};
|
||||
|
||||
interface UserPermissions {
|
||||
isAdmin: boolean;
|
||||
isManager: boolean;
|
||||
isDoctor: boolean;
|
||||
isSecretary: boolean;
|
||||
isAdminOrManager: boolean;
|
||||
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;
|
||||
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 {
|
||||
@ -98,7 +114,7 @@ interface Exception {
|
||||
doctor_id: string;
|
||||
date: string; // formato YYYY-MM-DD
|
||||
start_time: string | null; // null = dia inteiro
|
||||
end_time: string | null; // null = dia inteiro
|
||||
end_time: string | null; // null = dia inteiro
|
||||
kind: "bloqueio" | "disponibilidade"; // tipos conhecidos
|
||||
reason: string | null; // pode ser null
|
||||
created_at: string; // timestamp ISO
|
||||
@ -106,188 +122,201 @@ 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);
|
||||
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);
|
||||
|
||||
// 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",
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
const doctorsList: Doctor[] = await doctorsService.list();
|
||||
const doctor = doctorsList[0];
|
||||
|
||||
// Salva no estado
|
||||
setLoggedDoctor(doctor);
|
||||
|
||||
// Busca disponibilidade
|
||||
const availabilityList = await AvailabilityService.list();
|
||||
|
||||
// Filtra já com a variável local
|
||||
const filteredAvail = availabilityList.filter(
|
||||
(disp: { doctor_id: string }) => disp.doctor_id === doctor?.id
|
||||
);
|
||||
setAvailability(filteredAvail);
|
||||
|
||||
// Busca exceções
|
||||
const exceptionsList = await exceptionsService.list();
|
||||
const filteredExc = exceptionsList.filter(
|
||||
(exc: { doctor_id: string }) => exc.doctor_id === doctor?.id
|
||||
);
|
||||
console.log(exceptionsList)
|
||||
setExceptions(filteredExc);
|
||||
|
||||
} catch (e: any) {
|
||||
alert(`${e?.error} ${e?.message}`);
|
||||
}
|
||||
// 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",
|
||||
};
|
||||
|
||||
fetchData();
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
const doctorsList: Doctor[] = await doctorsService.list();
|
||||
const doctor = doctorsList[0];
|
||||
|
||||
// Função auxiliar para filtrar o id do doctor correspondente ao user logado
|
||||
function findDoctorById(id: string, doctors: Doctor[]) {
|
||||
return doctors.find((doctor) => doctor.user_id === id);
|
||||
}
|
||||
|
||||
const openDeleteDialog = (exceptionId: string) => {
|
||||
setExceptionToDelete(exceptionId);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
// Salva no estado
|
||||
setLoggedDoctor(doctor);
|
||||
|
||||
const handleDeleteException = async (ExceptionId: string) => {
|
||||
try {
|
||||
alert(ExceptionId)
|
||||
const res = await exceptionsService.delete(ExceptionId);
|
||||
// Busca disponibilidade
|
||||
const availabilityList = await AvailabilityService.list();
|
||||
|
||||
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 {}
|
||||
// Filtra já com a variável local
|
||||
const filteredAvail = availabilityList.filter(
|
||||
(disp: { doctor_id: string }) => disp.doctor_id === doctor?.id
|
||||
);
|
||||
setAvailability(filteredAvail);
|
||||
|
||||
toast({
|
||||
title: "Sucesso",
|
||||
description: message,
|
||||
});
|
||||
|
||||
setExceptions((prev: Exception[]) => prev.filter((p) => String(p.id) !== String(ExceptionId)));
|
||||
} catch (e: any) {
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: e?.message || "Não foi possível deletar a exceção",
|
||||
});
|
||||
}
|
||||
setDeleteDialogOpen(false);
|
||||
setExceptionToDelete(null);
|
||||
};
|
||||
|
||||
function formatAvailability(data: Availability[]) {
|
||||
// Agrupar os horários por dia da semana
|
||||
const schedule = data.reduce((acc: any, item) => {
|
||||
const { weekday, start_time, end_time } = item;
|
||||
|
||||
// Se o dia ainda não existe, cria o array
|
||||
if (!acc[weekday]) {
|
||||
acc[weekday] = [];
|
||||
// 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}`);
|
||||
}
|
||||
};
|
||||
|
||||
// Adiciona o horário do dia
|
||||
acc[weekday].push({
|
||||
start: start_time,
|
||||
end: end_time,
|
||||
});
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
return acc;
|
||||
}, {} as Record<string, { start: string; end: string }[]>);
|
||||
// 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);
|
||||
}
|
||||
|
||||
return schedule;
|
||||
}
|
||||
const openDeleteDialog = (exceptionId: string) => {
|
||||
setExceptionToDelete(exceptionId);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (availability) {
|
||||
const formatted = formatAvailability(availability);
|
||||
setSchedule(formatted);
|
||||
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);
|
||||
}
|
||||
}, [availability]);
|
||||
} catch {}
|
||||
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
|
||||
<p className="text-gray-600">Bem-vindo ao seu portal de consultas médicas</p>
|
||||
</div>
|
||||
toast({
|
||||
title: "Sucesso",
|
||||
description: message,
|
||||
});
|
||||
|
||||
<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>
|
||||
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);
|
||||
};
|
||||
|
||||
<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>
|
||||
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;
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Perfil</CardTitle>
|
||||
<User className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">100%</div>
|
||||
<p className="text-xs text-muted-foreground">Dados completos</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
// Se o dia ainda não existe, cria o array
|
||||
if (!acc[weekday]) {
|
||||
acc[weekday] = [];
|
||||
}
|
||||
|
||||
<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>
|
||||
// Adiciona o horário do dia
|
||||
acc[weekday].push({
|
||||
start: start_time,
|
||||
end: end_time,
|
||||
});
|
||||
|
||||
return acc;
|
||||
}, {} as Record<string, { start: string; end: string }[]>);
|
||||
|
||||
return schedule;
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (availability) {
|
||||
const formatted = formatAvailability(availability);
|
||||
setSchedule(formatted);
|
||||
}
|
||||
}, [availability]);
|
||||
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
|
||||
<p className="text-gray-600">
|
||||
Bem-vindo ao seu portal de consultas médicas
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">
|
||||
Próxima Consulta
|
||||
</CardTitle>
|
||||
<Calendar className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">02 out</div>
|
||||
<p className="text-xs text-muted-foreground">Dr. Silva - 14:30</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">
|
||||
Consultas Este Mês
|
||||
</CardTitle>
|
||||
<Clock className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">4</div>
|
||||
<p className="text-xs text-muted-foreground">4 agendadas</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Perfil</CardTitle>
|
||||
<User className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">100%</div>
|
||||
<p className="text-xs text-muted-foreground">Dados completos</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Ações Rápidas</CardTitle>
|
||||
<CardDescription>
|
||||
Acesse rapidamente as principais funcionalidades
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<Link href="/doctor/medicos/consultas">
|
||||
<Button className="bg-blue-600 hover:bg-blue-700 text-white cursor-pointer">
|
||||
<Calendar className="mr-2 h-4 w-4 text-white" />
|
||||
Ver Minhas Consultas
|
||||
</Button>
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
@ -316,31 +345,7 @@ export default function PatientDashboard() {
|
||||
<CardTitle>Horário Semanal</CardTitle>
|
||||
<CardDescription>Confira rapidamente a sua disponibilidade da semana</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4 grid md:grid-cols-7 gap-2">
|
||||
{["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"].map((day) => {
|
||||
const times = schedule[day] || [];
|
||||
return (
|
||||
<div key={day} className="space-y-4">
|
||||
<div className="flex flex-col items-center justify-between p-3 bg-blue-50 rounded-lg">
|
||||
<div>
|
||||
<p className="font-medium capitalize">{weekdaysPT[day]}</p>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
{times.length > 0 ? (
|
||||
times.map((t, i) => (
|
||||
<p key={i} className="text-sm text-gray-600">
|
||||
{formatTime(t.start)} <br /> {formatTime(t.end)}
|
||||
</p>
|
||||
))
|
||||
) : (
|
||||
<p className="text-sm text-gray-400 italic">Sem horário</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</CardContent>
|
||||
<CardContent>{loggedDoctor && <WeeklyScheduleCard doctorId={loggedDoctor.id} />}</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-1 gap-6">
|
||||
@ -350,30 +355,26 @@ 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) => {
|
||||
// Formata data e hora
|
||||
const date = new Date(ex.date).toLocaleDateString("pt-BR", {
|
||||
weekday: "long",
|
||||
day: "2-digit",
|
||||
month: "long",
|
||||
timeZone: "UTC",
|
||||
});
|
||||
|
||||
const startTime = formatTime(ex.start_time);
|
||||
const endTime = formatTime(ex.end_time);
|
||||
const startTime = formatTime(ex.start_time);
|
||||
const endTime = formatTime(ex.end_time);
|
||||
|
||||
return (
|
||||
<div key={ex.id} className="space-y-4">
|
||||
<div className="flex flex-col items-center justify-between p-3 bg-blue-50 rounded-lg shadow-sm">
|
||||
<div className="text-center">
|
||||
<p className="font-semibold capitalize">{date}</p>
|
||||
<p className="text-sm text-gray-600">
|
||||
{startTime && endTime
|
||||
? `${startTime} - ${endTime}`
|
||||
: "Dia todo"}
|
||||
</p>
|
||||
<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>
|
||||
|
||||
@ -6,7 +6,13 @@ import Link from "next/link";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
|
||||
import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
||||
import { usersService } from "@/services/usersApi.mjs";
|
||||
@ -14,163 +20,203 @@ import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||
|
||||
import { toast } from "@/hooks/use-toast";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card";
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||
import {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
} from "@/components/ui/card";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { Edit, Trash2 } from "lucide-react";
|
||||
import { AvailabilityEditModal } from "@/components/ui/availability-edit-modal";
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import Sidebar from "@/components/Sidebar";
|
||||
|
||||
// ... (Interfaces de tipo omitidas para brevidade, pois não foram alteradas)
|
||||
|
||||
interface UserPermissions {
|
||||
isAdmin: boolean;
|
||||
isManager: boolean;
|
||||
isDoctor: boolean;
|
||||
isSecretary: boolean;
|
||||
isAdminOrManager: boolean;
|
||||
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;
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
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;
|
||||
};
|
||||
|
||||
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;
|
||||
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;
|
||||
};
|
||||
|
||||
export default function AvailabilityPage() {
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const router = useRouter();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [schedule, setSchedule] = useState<Record<string, { start: string; end: string }[]>>({});
|
||||
const formatTime = (time?: string | null) => time?.split(":")?.slice(0, 2).join(":") ?? "";
|
||||
const [userData, setUserData] = useState<UserData>();
|
||||
const [availability, setAvailability] = useState<any | null>(null);
|
||||
const [doctorId, setDoctorId] = useState<string>();
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [modalidadeConsulta, setModalidadeConsulta] = useState<string>("");
|
||||
const [selectedAvailability, setSelectedAvailability] = useState<Availability | null>(null);
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
|
||||
const selectAvailability = (schedule: { start: string; end: string;}, day: string) => {
|
||||
const selected = availability.filter((a: Availability) =>
|
||||
a.start_time === schedule.start &&
|
||||
a.end_time === schedule.end &&
|
||||
a.weekday === day
|
||||
);
|
||||
setSelectedAvailability(selected[0]);
|
||||
}
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const router = useRouter();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [schedule, setSchedule] = useState<
|
||||
Record<string, { start: string; end: string }[]>
|
||||
>({});
|
||||
const formatTime = (time?: string | null) =>
|
||||
time?.split(":")?.slice(0, 2).join(":") ?? "";
|
||||
const [userData, setUserData] = useState<UserData>();
|
||||
const [availability, setAvailability] = useState<any | null>(null);
|
||||
const [doctorId, setDoctorId] = useState<string>();
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [modalidadeConsulta, setModalidadeConsulta] = useState<string>("");
|
||||
const [selectedAvailability, setSelectedAvailability] =
|
||||
useState<Availability | null>(null);
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
|
||||
const handleOpenModal = (schedule: { start: string; end: string;}, day: string) => {
|
||||
selectAvailability(schedule, day)
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
const handleCloseModal = () => {
|
||||
setSelectedAvailability(null);
|
||||
setIsModalOpen(false);
|
||||
const selectAvailability = (
|
||||
schedule: { start: string; end: string },
|
||||
day: string
|
||||
) => {
|
||||
const selected = availability.filter(
|
||||
(a: Availability) =>
|
||||
a.start_time === schedule.start &&
|
||||
a.end_time === schedule.end &&
|
||||
a.weekday === day
|
||||
);
|
||||
setSelectedAvailability(selected[0]);
|
||||
};
|
||||
|
||||
const handleOpenModal = (
|
||||
schedule: { start: string; end: string },
|
||||
day: string
|
||||
) => {
|
||||
selectAvailability(schedule, day);
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
const handleCloseModal = () => {
|
||||
setSelectedAvailability(null);
|
||||
setIsModalOpen(false);
|
||||
};
|
||||
|
||||
const handleEdit = async (formData: {
|
||||
start_time: "";
|
||||
end_time: "";
|
||||
slot_minutes: "";
|
||||
appointment_type: "";
|
||||
id: "";
|
||||
}) => {
|
||||
if (isLoading) return;
|
||||
setIsLoading(true);
|
||||
|
||||
const apiPayload = {
|
||||
start_time: formData.start_time,
|
||||
end_time: formData.end_time,
|
||||
slot_minutes: formData.slot_minutes,
|
||||
appointment_type: formData.appointment_type,
|
||||
};
|
||||
console.log(apiPayload);
|
||||
|
||||
const handleEdit = async (formData:{ start_time: "", end_time: "", slot_minutes: "", appointment_type: "", id:""}) => {
|
||||
if (isLoading) return;
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const res = await AvailabilityService.update(formData.id, apiPayload);
|
||||
console.log(res);
|
||||
|
||||
const apiPayload = {
|
||||
start_time: formData.start_time,
|
||||
end_time: formData.end_time,
|
||||
slot_minutes: formData.slot_minutes,
|
||||
appointment_type: formData.appointment_type,
|
||||
};
|
||||
console.log(apiPayload);
|
||||
|
||||
try {
|
||||
const res = await AvailabilityService.update(formData.id, apiPayload);
|
||||
console.log(res);
|
||||
|
||||
let message = "disponibilidade editada com sucesso";
|
||||
try {
|
||||
if (!res[0].id) {
|
||||
throw new Error(`${res.error} ${res.message}` || "A API retornou erro");
|
||||
} else {
|
||||
console.log(message);
|
||||
}
|
||||
} catch {}
|
||||
|
||||
toast({
|
||||
title: "Sucesso",
|
||||
description: message,
|
||||
});
|
||||
router.push("#")
|
||||
} catch (err: any) {
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: err?.message || "Não foi possível editar a disponibilidade",
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
handleCloseModal();
|
||||
fetchData()
|
||||
let message = "disponibilidade editada com sucesso";
|
||||
try {
|
||||
if (!res[0].id) {
|
||||
throw new Error(
|
||||
`${res.error} ${res.message}` || "A API retornou erro"
|
||||
);
|
||||
} else {
|
||||
console.log(message);
|
||||
}
|
||||
};
|
||||
} catch {}
|
||||
|
||||
toast({
|
||||
title: "Sucesso",
|
||||
description: message,
|
||||
});
|
||||
router.push("#");
|
||||
} catch (err: any) {
|
||||
toast({
|
||||
title: "Erro",
|
||||
description:
|
||||
err?.message || "Não foi possível editar a disponibilidade",
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
handleCloseModal();
|
||||
fetchData();
|
||||
}
|
||||
};
|
||||
|
||||
// Mapa de tradução
|
||||
const weekdaysPT: Record<string, string> = {
|
||||
@ -183,95 +229,96 @@ export default function AvailabilityPage() {
|
||||
saturday: "Sábado",
|
||||
};
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
const loggedUser = await usersService.getMe();
|
||||
const doctorList = await doctorsService.list();
|
||||
setUserData(loggedUser);
|
||||
const doctor = findDoctorById(loggedUser.user.id, doctorList);
|
||||
setDoctorId(doctor?.id);
|
||||
console.log(doctor);
|
||||
// Busca disponibilidade
|
||||
const availabilityList = await AvailabilityService.list();
|
||||
|
||||
// Filtra já com a variável local
|
||||
const filteredAvail = availabilityList.filter(
|
||||
(disp: { doctor_id: string }) => disp.doctor_id === doctor?.id
|
||||
);
|
||||
setAvailability(filteredAvail);
|
||||
} catch (e: any) {
|
||||
alert(`${e?.error} ${e?.message}`);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
// Função auxiliar para filtrar o id do doctor correspondente ao user logado
|
||||
function findDoctorById(id: string, doctors: Doctor[]) {
|
||||
return doctors.find((doctor) => doctor.user_id === id);
|
||||
}
|
||||
|
||||
|
||||
function formatAvailability(data: Availability[]) {
|
||||
// Agrupar os horários por dia da semana
|
||||
const schedule = data.reduce((acc: any, item) => {
|
||||
const { weekday, start_time, end_time } = item;
|
||||
|
||||
// Se o dia ainda não existe, cria o array
|
||||
if (!acc[weekday]) {
|
||||
acc[weekday] = [];
|
||||
}
|
||||
|
||||
// Adiciona o horário do dia
|
||||
acc[weekday].push({
|
||||
start: start_time,
|
||||
end: end_time,
|
||||
});
|
||||
|
||||
return acc;
|
||||
}, {} as Record<string, { start: string; end: string }[]>);
|
||||
|
||||
return schedule;
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (availability) {
|
||||
const formatted = formatAvailability(availability);
|
||||
setSchedule(formatted);
|
||||
}
|
||||
}, [availability]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
if (isLoading) return;
|
||||
setIsLoading(true);
|
||||
const form = e.currentTarget;
|
||||
const formData = new FormData(form);
|
||||
|
||||
const apiPayload = {
|
||||
doctor_id: doctorId,
|
||||
weekday: (formData.get("weekday") as string) || undefined,
|
||||
start_time: (formData.get("horarioEntrada") as string) || undefined,
|
||||
end_time: (formData.get("horarioSaida") as string) || undefined,
|
||||
slot_minutes: Number(formData.get("duracaoConsulta")) || undefined,
|
||||
appointment_type: modalidadeConsulta || undefined,
|
||||
active: true,
|
||||
};
|
||||
console.log(apiPayload);
|
||||
|
||||
try {
|
||||
const res = await AvailabilityService.create(apiPayload);
|
||||
console.log(res);
|
||||
const loggedUser = await usersService.getMe();
|
||||
const doctorList = await doctorsService.list();
|
||||
setUserData(loggedUser);
|
||||
const doctor = findDoctorById(loggedUser.user.id, doctorList);
|
||||
setDoctorId(doctor?.id);
|
||||
console.log(doctor);
|
||||
// Busca disponibilidade
|
||||
const availabilityList = await AvailabilityService.list();
|
||||
|
||||
// Filtra já com a variável local
|
||||
const filteredAvail = availabilityList.filter(
|
||||
(disp: { doctor_id: string }) => disp.doctor_id === doctor?.id
|
||||
);
|
||||
setAvailability(filteredAvail);
|
||||
} catch (e: any) {
|
||||
alert(`${e?.error} ${e?.message}`);
|
||||
}
|
||||
};
|
||||
|
||||
let message = "disponibilidade cadastrada com sucesso";
|
||||
try {
|
||||
if (!res[0].id) {
|
||||
throw new Error(`${res.error} ${res.message}` || "A API retornou erro");
|
||||
} else {
|
||||
console.log(message);
|
||||
}
|
||||
} catch {}
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
// Função auxiliar para filtrar o id do doctor correspondente ao user logado
|
||||
function findDoctorById(id: string, doctors: Doctor[]) {
|
||||
return doctors.find((doctor) => doctor.user_id === id);
|
||||
}
|
||||
|
||||
function formatAvailability(data: Availability[]) {
|
||||
// Agrupar os horários por dia da semana
|
||||
const schedule = data.reduce((acc: any, item) => {
|
||||
const { weekday, start_time, end_time } = item;
|
||||
|
||||
// Se o dia ainda não existe, cria o array
|
||||
if (!acc[weekday]) {
|
||||
acc[weekday] = [];
|
||||
}
|
||||
|
||||
// Adiciona o horário do dia
|
||||
acc[weekday].push({
|
||||
start: start_time,
|
||||
end: end_time,
|
||||
});
|
||||
|
||||
return acc;
|
||||
}, {} as Record<string, { start: string; end: string }[]>);
|
||||
|
||||
return schedule;
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (availability) {
|
||||
const formatted = formatAvailability(availability);
|
||||
setSchedule(formatted);
|
||||
}
|
||||
}, [availability]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
if (isLoading) return;
|
||||
setIsLoading(true);
|
||||
const form = e.currentTarget;
|
||||
const formData = new FormData(form);
|
||||
|
||||
const apiPayload = {
|
||||
doctor_id: doctorId,
|
||||
weekday: (formData.get("weekday") as string) || undefined,
|
||||
start_time: (formData.get("horarioEntrada") as string) || undefined,
|
||||
end_time: (formData.get("horarioSaida") as string) || undefined,
|
||||
slot_minutes: Number(formData.get("duracaoConsulta")) || undefined,
|
||||
appointment_type: modalidadeConsulta || undefined,
|
||||
active: true,
|
||||
};
|
||||
console.log(apiPayload);
|
||||
|
||||
try {
|
||||
const res = await AvailabilityService.create(apiPayload);
|
||||
console.log(res);
|
||||
|
||||
let message = "disponibilidade cadastrada com sucesso";
|
||||
try {
|
||||
if (!res[0].id) {
|
||||
throw new Error(
|
||||
`${res.error} ${res.message}` || "A API retornou erro"
|
||||
);
|
||||
} else {
|
||||
console.log(message);
|
||||
}
|
||||
} catch {}
|
||||
|
||||
toast({
|
||||
title: "Sucesso",
|
||||
@ -284,14 +331,18 @@ export default function AvailabilityPage() {
|
||||
description: err?.message || "Não foi possível criar a disponibilidade",
|
||||
});
|
||||
} finally {
|
||||
fetchData()
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const openDeleteDialog = (schedule: { start: string; end: string;}, day: string) => {
|
||||
selectAvailability(schedule, day)
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
const openDeleteDialog = (
|
||||
schedule: { start: string; end: string },
|
||||
day: string
|
||||
) => {
|
||||
selectAvailability(schedule, day);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleDeleteAvailability = async (AvailabilityId: string) => {
|
||||
try {
|
||||
@ -318,101 +369,176 @@ export default function AvailabilityPage() {
|
||||
description: e?.message || "Não foi possível deletar a disponibilidade",
|
||||
});
|
||||
}
|
||||
fetchData()
|
||||
setDeleteDialogOpen(false);
|
||||
setSelectedAvailability(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="space-y-6 flex-1 overflow-y-auto p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Definir Disponibilidade</h1>
|
||||
<p className="text-gray-600">Defina sua disponibilidade para consultas </p>
|
||||
</div>
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="space-y-6 flex-1 overflow-y-auto p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">
|
||||
Definir Disponibilidade
|
||||
</h1>
|
||||
<p className="text-gray-600">
|
||||
Defina sua disponibilidade para consultas{" "}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form className="space-y-6" onSubmit={handleSubmit}>
|
||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Dados </h2>
|
||||
|
||||
<div className="space-y-6">
|
||||
{/* **AJUSTE DE RESPONSIVIDADE: DIAS DA SEMANA** */}
|
||||
<div>
|
||||
<Label className="text-sm font-medium text-gray-700">
|
||||
Dia Da Semana
|
||||
</Label>
|
||||
{/* O antigo 'flex gap-4 mt-2 flex-nowrap' foi substituído por um grid responsivo: */}
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-7 gap-x-4 gap-y-2 mt-2">
|
||||
<label className="flex items-center gap-1">
|
||||
<input
|
||||
type="radio"
|
||||
name="weekday"
|
||||
value="monday"
|
||||
className="text-blue-600"
|
||||
/>
|
||||
<span className="whitespace-nowrap text-sm">Segunda</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1">
|
||||
<input
|
||||
type="radio"
|
||||
name="weekday"
|
||||
value="tuesday"
|
||||
className="text-blue-600"
|
||||
/>
|
||||
<span className="whitespace-nowrap text-sm">Terça</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1">
|
||||
<input
|
||||
type="radio"
|
||||
name="weekday"
|
||||
value="wednesday"
|
||||
className="text-blue-600"
|
||||
/>
|
||||
<span className="whitespace-nowrap text-sm">Quarta</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1">
|
||||
<input
|
||||
type="radio"
|
||||
name="weekday"
|
||||
value="thursday"
|
||||
className="text-blue-600"
|
||||
/>
|
||||
<span className="whitespace-nowrap text-sm">Quinta</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1">
|
||||
<input
|
||||
type="radio"
|
||||
name="weekday"
|
||||
value="friday"
|
||||
className="text-blue-600"
|
||||
/>
|
||||
<span className="whitespace-nowrap text-sm">Sexta</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1">
|
||||
<input
|
||||
type="radio"
|
||||
name="weekday"
|
||||
value="saturday"
|
||||
className="text-blue-600"
|
||||
/>
|
||||
<span className="whitespace-nowrap text-sm">Sábado</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1">
|
||||
<input
|
||||
type="radio"
|
||||
name="weekday"
|
||||
value="sunday"
|
||||
className="text-blue-600"
|
||||
/>
|
||||
<span className="whitespace-nowrap text-sm">Domingo</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form className="space-y-6" onSubmit={handleSubmit}>
|
||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Dados </h2>
|
||||
{/* **AJUSTE DE RESPONSIVIDADE: HORÁRIO E DURAÇÃO** */}
|
||||
{/* Ajustado para 1 coluna em móvel, 2 em tablet e 5 em desktop (mantendo o que já existia com ajustes) */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-6">
|
||||
<div>
|
||||
<Label
|
||||
htmlFor="horarioEntrada"
|
||||
className="text-sm font-medium text-gray-700"
|
||||
>
|
||||
Horario De Entrada
|
||||
</Label>
|
||||
<Input
|
||||
type="time"
|
||||
id="horarioEntrada"
|
||||
name="horarioEntrada"
|
||||
required
|
||||
className="mt-1"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label
|
||||
htmlFor="horarioSaida"
|
||||
className="text-sm font-medium text-gray-700"
|
||||
>
|
||||
Horario De Saida
|
||||
</Label>
|
||||
<Input
|
||||
type="time"
|
||||
id="horarioSaida"
|
||||
name="horarioSaida"
|
||||
required
|
||||
className="mt-1"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label
|
||||
htmlFor="duracaoConsulta"
|
||||
className="text-sm font-medium text-gray-700"
|
||||
>
|
||||
Duração Da Consulta (min)
|
||||
</Label>
|
||||
<Input
|
||||
type="number"
|
||||
id="duracaoConsulta"
|
||||
name="duracaoConsulta"
|
||||
required
|
||||
className="mt-1"
|
||||
/>
|
||||
</div>
|
||||
{/* O Select de modalidade fica fora deste grid para ocupar uma linha inteira em telas menores, como no original, garantindo clareza */}
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
{/* **AJUSTE DE RESPONSIVIDADE: DIAS DA SEMANA** */}
|
||||
<div>
|
||||
<Label className="text-sm font-medium text-gray-700">Dia Da Semana</Label>
|
||||
{/* O antigo 'flex gap-4 mt-2 flex-nowrap' foi substituído por um grid responsivo: */}
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-7 gap-x-4 gap-y-2 mt-2">
|
||||
<label className="flex items-center gap-1">
|
||||
<input type="radio" name="weekday" value="monday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Segunda</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1">
|
||||
<input type="radio" name="weekday" value="tuesday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Terça</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1">
|
||||
<input type="radio" name="weekday" value="wednesday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Quarta</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1">
|
||||
<input type="radio" name="weekday" value="thursday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Quinta</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1">
|
||||
<input type="radio" name="weekday" value="friday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Sexta</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1">
|
||||
<input type="radio" name="weekday" value="saturday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Sábado</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1">
|
||||
<input type="radio" name="weekday" value="sunday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Domingo</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* **AJUSTE DE RESPONSIVIDADE: HORÁRIO E DURAÇÃO** */}
|
||||
{/* Ajustado para 1 coluna em móvel, 2 em tablet e 5 em desktop (mantendo o que já existia com ajustes) */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-6">
|
||||
<div>
|
||||
<Label htmlFor="horarioEntrada" className="text-sm font-medium text-gray-700">
|
||||
Horario De Entrada
|
||||
</Label>
|
||||
<Input type="time" id="horarioEntrada" name="horarioEntrada" required className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="horarioSaida" className="text-sm font-medium text-gray-700">
|
||||
Horario De Saida
|
||||
</Label>
|
||||
<Input type="time" id="horarioSaida" name="horarioSaida" required className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="duracaoConsulta" className="text-sm font-medium text-gray-700">
|
||||
Duração Da Consulta (min)
|
||||
</Label>
|
||||
<Input type="number" id="duracaoConsulta" name="duracaoConsulta" required className="mt-1" />
|
||||
</div>
|
||||
{/* O Select de modalidade fica fora deste grid para ocupar uma linha inteira em telas menores, como no original, garantindo clareza */}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="modalidadeConsulta" className="text-sm font-medium text-gray-700">
|
||||
Modalidade De Consulta
|
||||
</Label>
|
||||
<Select onValueChange={(value) => setModalidadeConsulta(value)} value={modalidadeConsulta}>
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="presencial">Presencial </SelectItem>
|
||||
<SelectItem value="telemedicina">Telemedicina</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Label
|
||||
htmlFor="modalidadeConsulta"
|
||||
className="text-sm font-medium text-gray-700"
|
||||
>
|
||||
Modalidade De Consulta
|
||||
</Label>
|
||||
<Select
|
||||
onValueChange={(value) => setModalidadeConsulta(value)}
|
||||
value={modalidadeConsulta}
|
||||
>
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="presencial">Presencial </SelectItem>
|
||||
<SelectItem value="telemedicina">Telemedicina</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* **AJUSTE DE RESPONSIVIDADE: BOTÕES DE AÇÃO** */}
|
||||
{/* Alinha à direita em telas maiores e empilha (com o botão primário no final) em telas menores */}
|
||||
@ -453,7 +579,7 @@ export default function AvailabilityPage() {
|
||||
<div key={i}>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<p className="text-sm text-gray-600 cursor-pointer p-1 rounded hover:text-accent-foreground hover:bg-gray-200 transition-colors duration-150">
|
||||
<p className="text-sm text-gray-600 cursor-pointer rounded hover:text-accent-foreground hover:bg-gray-200 transition-colors duration-150">
|
||||
{formatTime(t.start)} - {formatTime(t.end)}
|
||||
</p>
|
||||
</DropdownMenuTrigger>
|
||||
@ -509,4 +635,4 @@ export default function AvailabilityPage() {
|
||||
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,414 +2,463 @@
|
||||
|
||||
import { useEffect, useState, useCallback } from "react";
|
||||
import Link from "next/link";
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { Eye, Edit, Calendar, Trash2, Loader2 } from "lucide-react";
|
||||
import { api } from "@/services/api.mjs";
|
||||
import { PatientDetailsModal } from "@/components/ui/patient-details-modal";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import Sidebar from "@/components/Sidebar";
|
||||
|
||||
interface Paciente {
|
||||
id: string;
|
||||
nome: string;
|
||||
telefone: string;
|
||||
cidade: string;
|
||||
estado: string;
|
||||
ultimoAtendimento?: string;
|
||||
proximoAtendimento?: string;
|
||||
email?: string;
|
||||
birth_date?: string;
|
||||
cpf?: string;
|
||||
blood_type?: string;
|
||||
weight_kg?: number;
|
||||
height_m?: number;
|
||||
street?: string;
|
||||
number?: string;
|
||||
complement?: string;
|
||||
neighborhood?: string;
|
||||
cep?: string;
|
||||
id: string;
|
||||
nome: string;
|
||||
telefone: string;
|
||||
cidade: string;
|
||||
estado: string;
|
||||
ultimoAtendimento?: string;
|
||||
proximoAtendimento?: string;
|
||||
email?: string;
|
||||
birth_date?: string;
|
||||
cpf?: string;
|
||||
blood_type?: string;
|
||||
weight_kg?: number;
|
||||
height_m?: number;
|
||||
street?: string;
|
||||
number?: string;
|
||||
complement?: string;
|
||||
neighborhood?: string;
|
||||
cep?: string;
|
||||
}
|
||||
|
||||
export default function PacientesPage() {
|
||||
const [pacientes, setPacientes] = useState<Paciente[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [selectedPatient, setSelectedPatient] = useState<Paciente | null>(null);
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [pacientes, setPacientes] = useState<Paciente[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [selectedPatient, setSelectedPatient] = useState<Paciente | null>(null);
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
|
||||
// --- Lógica de Paginação INÍCIO ---
|
||||
const [itemsPerPage, setItemsPerPage] = useState(5);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
// --- Lógica de Paginação INÍCIO ---
|
||||
const [itemsPerPage, setItemsPerPage] = useState(5);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
|
||||
const totalPages = Math.ceil(pacientes.length / itemsPerPage);
|
||||
const totalPages = Math.ceil(pacientes.length / itemsPerPage);
|
||||
|
||||
const indexOfLastItem = currentPage * itemsPerPage;
|
||||
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
||||
const currentItems = pacientes.slice(indexOfFirstItem, indexOfLastItem);
|
||||
const indexOfLastItem = currentPage * itemsPerPage;
|
||||
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
||||
const currentItems = pacientes.slice(indexOfFirstItem, indexOfLastItem);
|
||||
|
||||
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
|
||||
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
|
||||
|
||||
// Funções de Navegação
|
||||
const goToPrevPage = () => {
|
||||
setCurrentPage((prev) => Math.max(1, prev - 1));
|
||||
};
|
||||
// Funções de Navegação
|
||||
const goToPrevPage = () => {
|
||||
setCurrentPage((prev) => Math.max(1, prev - 1));
|
||||
};
|
||||
|
||||
const goToNextPage = () => {
|
||||
setCurrentPage((prev) => Math.min(totalPages, prev + 1));
|
||||
};
|
||||
const goToNextPage = () => {
|
||||
setCurrentPage((prev) => Math.min(totalPages, prev + 1));
|
||||
};
|
||||
|
||||
// Lógica para gerar os números das páginas visíveis (máximo de 5)
|
||||
const getVisiblePageNumbers = (totalPages: number, currentPage: number) => {
|
||||
const pages: number[] = [];
|
||||
const maxVisiblePages = 5;
|
||||
const halfRange = Math.floor(maxVisiblePages / 2);
|
||||
let startPage = Math.max(1, currentPage - halfRange);
|
||||
let endPage = Math.min(totalPages, currentPage + halfRange);
|
||||
// Lógica para gerar os números das páginas visíveis (máximo de 5)
|
||||
const getVisiblePageNumbers = (totalPages: number, currentPage: number) => {
|
||||
const pages: number[] = [];
|
||||
const maxVisiblePages = 5;
|
||||
const halfRange = Math.floor(maxVisiblePages / 2);
|
||||
let startPage = Math.max(1, currentPage - halfRange);
|
||||
let endPage = Math.min(totalPages, currentPage + halfRange);
|
||||
|
||||
if (endPage - startPage + 1 < maxVisiblePages) {
|
||||
if (endPage === totalPages) {
|
||||
startPage = Math.max(1, totalPages - maxVisiblePages + 1);
|
||||
}
|
||||
if (startPage === 1) {
|
||||
endPage = Math.min(totalPages, maxVisiblePages);
|
||||
}
|
||||
}
|
||||
if (endPage - startPage + 1 < maxVisiblePages) {
|
||||
if (endPage === totalPages) {
|
||||
startPage = Math.max(1, totalPages - maxVisiblePages + 1);
|
||||
}
|
||||
if (startPage === 1) {
|
||||
endPage = Math.min(totalPages, maxVisiblePages);
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = startPage; i <= endPage; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
return pages;
|
||||
};
|
||||
for (let i = startPage; i <= endPage; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
return pages;
|
||||
};
|
||||
|
||||
const visiblePageNumbers = getVisiblePageNumbers(totalPages, currentPage);
|
||||
const visiblePageNumbers = getVisiblePageNumbers(totalPages, currentPage);
|
||||
|
||||
// Lógica para mudar itens por página, resetando para a página 1
|
||||
const handleItemsPerPageChange = (value: string) => {
|
||||
setItemsPerPage(Number(value));
|
||||
setCurrentPage(1);
|
||||
};
|
||||
// --- Lógica de Paginação FIM ---
|
||||
// Lógica para mudar itens por página, resetando para a página 1
|
||||
const handleItemsPerPageChange = (value: string) => {
|
||||
setItemsPerPage(Number(value));
|
||||
setCurrentPage(1);
|
||||
};
|
||||
// --- Lógica de Paginação FIM ---
|
||||
|
||||
const handleOpenModal = (patient: Paciente) => {
|
||||
setSelectedPatient(patient);
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
const handleOpenModal = (patient: Paciente) => {
|
||||
setSelectedPatient(patient);
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
const handleCloseModal = () => {
|
||||
setSelectedPatient(null);
|
||||
setIsModalOpen(false);
|
||||
};
|
||||
|
||||
const handleCloseModal = () => {
|
||||
setSelectedPatient(null);
|
||||
setIsModalOpen(false);
|
||||
};
|
||||
const formatDate = (dateString: string | null | undefined) => {
|
||||
if (!dateString) return "N/A";
|
||||
try {
|
||||
const date = new Date(dateString);
|
||||
return new Intl.DateTimeFormat("pt-BR").format(date);
|
||||
} catch (e) {
|
||||
return dateString; // Retorna o string original se o formato for inválido
|
||||
}
|
||||
};
|
||||
|
||||
const formatDate = (dateString: string | null | undefined) => {
|
||||
if (!dateString) return "N/A";
|
||||
try {
|
||||
const date = new Date(dateString);
|
||||
return new Intl.DateTimeFormat("pt-BR").format(date);
|
||||
} catch (e) {
|
||||
return dateString; // Retorna o string original se o formato for inválido
|
||||
}
|
||||
};
|
||||
const fetchPacientes = useCallback(async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const json = await api.get("/rest/v1/patients");
|
||||
const items = Array.isArray(json)
|
||||
? json
|
||||
: Array.isArray(json?.data)
|
||||
? json.data
|
||||
: [];
|
||||
|
||||
const fetchPacientes = useCallback(async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const json = await api.get("/rest/v1/patients");
|
||||
const items = Array.isArray(json)
|
||||
? json
|
||||
: Array.isArray(json?.data)
|
||||
? json.data
|
||||
: [];
|
||||
const mapped: Paciente[] = items.map((p: any) => ({
|
||||
id: String(p.id ?? ""),
|
||||
nome: p.full_name ?? "—",
|
||||
telefone: p.phone_mobile ?? "N/A",
|
||||
cidade: p.city ?? "N/A",
|
||||
estado: p.state ?? "N/A",
|
||||
ultimoAtendimento: formatDate(p.created_at),
|
||||
proximoAtendimento: "N/A", // Necessita de lógica de agendamento real
|
||||
email: p.email ?? "N/A",
|
||||
birth_date: p.birth_date ?? "N/A",
|
||||
cpf: p.cpf ?? "N/A",
|
||||
blood_type: p.blood_type ?? "N/A",
|
||||
weight_kg: p.weight_kg ?? 0,
|
||||
height_m: p.height_m ?? 0,
|
||||
street: p.street ?? "N/A",
|
||||
number: p.number ?? "N/A",
|
||||
complement: p.complement ?? "N/A",
|
||||
neighborhood: p.neighborhood ?? "N/A",
|
||||
cep: p.cep ?? "N/A",
|
||||
}));
|
||||
|
||||
const mapped: Paciente[] = items.map((p: any) => ({
|
||||
id: String(p.id ?? ""),
|
||||
nome: p.full_name ?? "—",
|
||||
telefone: p.phone_mobile ?? "N/A",
|
||||
cidade: p.city ?? "N/A",
|
||||
estado: p.state ?? "N/A",
|
||||
ultimoAtendimento: formatDate(p.created_at),
|
||||
proximoAtendimento: "N/A", // Necessita de lógica de agendamento real
|
||||
email: p.email ?? "N/A",
|
||||
birth_date: p.birth_date ?? "N/A",
|
||||
cpf: p.cpf ?? "N/A",
|
||||
blood_type: p.blood_type ?? "N/A",
|
||||
weight_kg: p.weight_kg ?? 0,
|
||||
height_m: p.height_m ?? 0,
|
||||
street: p.street ?? "N/A",
|
||||
number: p.number ?? "N/A",
|
||||
complement: p.complement ?? "N/A",
|
||||
neighborhood: p.neighborhood ?? "N/A",
|
||||
cep: p.cep ?? "N/A",
|
||||
}));
|
||||
setPacientes(mapped);
|
||||
setCurrentPage(1); // Resetar a página ao carregar novos dados
|
||||
} catch (e: any) {
|
||||
console.error("Erro ao carregar pacientes:", e);
|
||||
setError(e?.message || "Erro ao carregar pacientes");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
setPacientes(mapped);
|
||||
setCurrentPage(1); // Resetar a página ao carregar novos dados
|
||||
} catch (e: any) {
|
||||
console.error("Erro ao carregar pacientes:", e);
|
||||
setError(e?.message || "Erro ao carregar pacientes");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
fetchPacientes();
|
||||
}, [fetchPacientes]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchPacientes();
|
||||
}, [fetchPacientes]);
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="space-y-6 px-2 sm:px-4 md:px-6">
|
||||
{/* Cabeçalho */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
|
||||
{" "}
|
||||
{/* Ajustado para flex-col em telas pequenas */}
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-foreground">Pacientes</h1>
|
||||
<p className="text-muted-foreground text-sm sm:text-base">
|
||||
Lista de pacientes vinculados
|
||||
</p>
|
||||
</div>
|
||||
{/* Controles de filtro e novo paciente */}
|
||||
{/* Alterado para que o Select e o Link ocupem a largura total em telas pequenas e fiquem lado a lado em telas maiores */}
|
||||
<div className="flex flex-wrap gap-3 mt-4 sm:mt-0 w-full sm:w-auto justify-start sm:justify-end">
|
||||
<Select
|
||||
onValueChange={handleItemsPerPageChange}
|
||||
defaultValue={String(itemsPerPage)}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-[140px]">
|
||||
<SelectValue placeholder="Itens por pág." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="5">5 por página</SelectItem>
|
||||
<SelectItem value="10">10 por página</SelectItem>
|
||||
<SelectItem value="20">20 por página</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Link href="/doctor/pacientes/novo" className="w-full sm:w-auto">
|
||||
<Button
|
||||
variant="default"
|
||||
className="bg-blue-600 hover:bg-blue-700 w-full sm:w-auto"
|
||||
>
|
||||
Novo Paciente
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="space-y-6 px-2 sm:px-4 md:px-6">
|
||||
{/* Cabeçalho */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3"> {/* Ajustado para flex-col em telas pequenas */}
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-foreground">Pacientes</h1>
|
||||
<p className="text-muted-foreground text-sm sm:text-base">
|
||||
Lista de pacientes vinculados
|
||||
</p>
|
||||
<div className="bg-card rounded-lg border border-border overflow-hidden shadow-md">
|
||||
{/* Tabela para Telas Médias e Grandes */}
|
||||
<div className="overflow-x-auto hidden md:block">
|
||||
{" "}
|
||||
{/* Esconde em telas pequenas */}
|
||||
<table className="min-w-[600px] w-full">
|
||||
<thead className="bg-muted border-b border-border">
|
||||
<tr>
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground">
|
||||
Nome
|
||||
</th>
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground">
|
||||
Telefone
|
||||
</th>
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden lg:table-cell">
|
||||
Cidade
|
||||
</th>
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden lg:table-cell">
|
||||
Estado
|
||||
</th>
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden xl:table-cell">
|
||||
Último atendimento
|
||||
</th>
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden xl:table-cell">
|
||||
Próximo atendimento
|
||||
</th>
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground">
|
||||
Ações
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{loading ? (
|
||||
<tr>
|
||||
<td
|
||||
colSpan={7}
|
||||
className="p-6 text-muted-foreground text-center"
|
||||
>
|
||||
<Loader2 className="w-6 h-6 animate-spin mx-auto text-primary" />
|
||||
Carregando pacientes...
|
||||
</td>
|
||||
</tr>
|
||||
) : error ? (
|
||||
<tr>
|
||||
<td
|
||||
colSpan={7}
|
||||
className="p-6 text-red-600 text-center"
|
||||
>{`Erro: ${error}`}</td>
|
||||
</tr>
|
||||
) : pacientes.length === 0 ? (
|
||||
<tr>
|
||||
<td
|
||||
colSpan={7}
|
||||
className="p-8 text-center text-muted-foreground"
|
||||
>
|
||||
Nenhum paciente encontrado
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
currentItems.map((p) => (
|
||||
<tr
|
||||
key={p.id}
|
||||
className="border-b border-border hover:bg-accent/40 transition-colors"
|
||||
>
|
||||
<td className="p-3 sm:p-4">{p.nome}</td>
|
||||
<td className="p-3 sm:p-4 text-muted-foreground">
|
||||
{p.telefone}
|
||||
</td>
|
||||
<td className="p-3 sm:p-4 text-muted-foreground hidden lg:table-cell">
|
||||
{p.cidade}
|
||||
</td>
|
||||
<td className="p-3 sm:p-4 text-muted-foreground hidden lg:table-cell">
|
||||
{p.estado}
|
||||
</td>
|
||||
<td className="p-3 sm:p-4 text-muted-foreground hidden xl:table-cell">
|
||||
{p.ultimoAtendimento}
|
||||
</td>
|
||||
<td className="p-3 sm:p-4 text-muted-foreground hidden xl:table-cell">
|
||||
{p.proximoAtendimento}
|
||||
</td>
|
||||
<td className="p-3 sm:p-4">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="text-primary hover:underline text-sm sm:text-base">
|
||||
Ações
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleOpenModal(p)}
|
||||
>
|
||||
<Eye className="w-4 h-4 mr-2" />
|
||||
Ver detalhes
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/doctor/pacientes/${p.id}/laudos`}>
|
||||
<Edit className="w-4 h-4 mr-2" />
|
||||
Laudos
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
alert(`Agenda para paciente ID: ${p.id}`)
|
||||
}
|
||||
>
|
||||
<Calendar className="w-4 h-4 mr-2" />
|
||||
Ver agenda
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
const newPacientes = pacientes.filter(
|
||||
(pac) => pac.id !== p.id
|
||||
);
|
||||
setPacientes(newPacientes);
|
||||
alert(`Paciente ID: ${p.id} excluído`);
|
||||
}}
|
||||
className="text-red-600 focus:bg-red-50 focus:text-red-600"
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
Excluir
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Layout em Cards/Lista para Telas Pequenas */}
|
||||
<div className="md:hidden divide-y divide-border">
|
||||
{" "}
|
||||
{/* Visível apenas em telas pequenas */}
|
||||
{loading ? (
|
||||
<div className="p-6 text-muted-foreground text-center">
|
||||
<Loader2 className="w-6 h-6 animate-spin mx-auto text-primary" />
|
||||
Carregando pacientes...
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="p-6 text-red-600 text-center">{`Erro: ${error}`}</div>
|
||||
) : pacientes.length === 0 ? (
|
||||
<div className="p-8 text-center text-muted-foreground">
|
||||
Nenhum paciente encontrado
|
||||
</div>
|
||||
) : (
|
||||
currentItems.map((p) => (
|
||||
<div
|
||||
key={p.id}
|
||||
className="flex items-center justify-between p-4 hover:bg-accent/40 transition-colors"
|
||||
>
|
||||
<div className="flex-1 min-w-0 pr-4">
|
||||
{" "}
|
||||
{/* Adicionado padding à direita */}
|
||||
<div className="text-base font-semibold text-foreground break-words">
|
||||
{" "}
|
||||
{/* Aumentado a fonte e break-words para evitar corte do nome */}
|
||||
{p.nome || "—"}
|
||||
</div>
|
||||
{/* Controles de filtro e novo paciente */}
|
||||
{/* Alterado para que o Select e o Link ocupem a largura total em telas pequenas e fiquem lado a lado em telas maiores */}
|
||||
<div className="flex flex-wrap gap-3 mt-4 sm:mt-0 w-full sm:w-auto justify-start sm:justify-end">
|
||||
<Select
|
||||
onValueChange={handleItemsPerPageChange}
|
||||
defaultValue={String(itemsPerPage)}
|
||||
{/* Removido o 'truncate' e adicionado 'break-words' no telefone */}
|
||||
<div className="text-sm text-muted-foreground break-words">
|
||||
Telefone: **{p.telefone || "N/A"}**
|
||||
</div>
|
||||
</div>
|
||||
<div className="ml-4 flex-shrink-0">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="icon">
|
||||
<Eye className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => handleOpenModal(p)}>
|
||||
<Eye className="w-4 h-4 mr-2" />
|
||||
Ver detalhes
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/doctor/pacientes/${p.id}/laudos`}>
|
||||
<Edit className="w-4 h-4 mr-2" />
|
||||
Laudos
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
alert(`Agenda para paciente ID: ${p.id}`)
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-[140px]">
|
||||
<SelectValue placeholder="Itens por pág." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="5">5 por página</SelectItem>
|
||||
<SelectItem value="10">10 por página</SelectItem>
|
||||
<SelectItem value="20">20 por página</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Link href="/doctor/pacientes/novo" className="w-full sm:w-auto">
|
||||
<Button variant="default" className="bg-green-600 hover:bg-green-700 w-full sm:w-auto">
|
||||
Novo Paciente
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
<Calendar className="w-4 h-4 mr-2" />
|
||||
Ver agenda
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
const newPacientes = pacientes.filter(
|
||||
(pac) => pac.id !== p.id
|
||||
);
|
||||
setPacientes(newPacientes);
|
||||
alert(`Paciente ID: ${p.id} excluído`);
|
||||
}}
|
||||
className="text-red-600 focus:bg-red-50 focus:text-red-600"
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
Excluir
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Paginação */}
|
||||
{totalPages > 1 && (
|
||||
<div className="flex flex-wrap justify-center items-center gap-2 border-t border-border p-4 bg-muted/40">
|
||||
{/* Botão Anterior */}
|
||||
<button
|
||||
onClick={goToPrevPage}
|
||||
disabled={currentPage === 1}
|
||||
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-secondary text-secondary-foreground hover:bg-secondary/80 disabled:opacity-50 disabled:cursor-not-allowed border border-border"
|
||||
>
|
||||
{"< Anterior"}
|
||||
</button>
|
||||
|
||||
<div className="bg-card rounded-lg border border-border overflow-hidden shadow-md">
|
||||
{/* Tabela para Telas Médias e Grandes */}
|
||||
<div className="overflow-x-auto hidden md:block"> {/* Esconde em telas pequenas */}
|
||||
<table className="min-w-[600px] w-full">
|
||||
<thead className="bg-muted border-b border-border">
|
||||
<tr>
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground">Nome</th>
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground">
|
||||
Telefone
|
||||
</th>
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden lg:table-cell">
|
||||
Cidade
|
||||
</th>
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden lg:table-cell">
|
||||
Estado
|
||||
</th>
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden xl:table-cell">
|
||||
Último atendimento
|
||||
</th>
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden xl:table-cell">
|
||||
Próximo atendimento
|
||||
</th>
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground">Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{loading ? (
|
||||
<tr>
|
||||
<td colSpan={7} className="p-6 text-muted-foreground text-center">
|
||||
<Loader2 className="w-6 h-6 animate-spin mx-auto text-primary" />
|
||||
Carregando pacientes...
|
||||
</td>
|
||||
</tr>
|
||||
) : error ? (
|
||||
<tr>
|
||||
<td colSpan={7} className="p-6 text-red-600 text-center">{`Erro: ${error}`}</td>
|
||||
</tr>
|
||||
) : pacientes.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={7} className="p-8 text-center text-muted-foreground">
|
||||
Nenhum paciente encontrado
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
currentItems.map((p) => (
|
||||
<tr
|
||||
key={p.id}
|
||||
className="border-b border-border hover:bg-accent/40 transition-colors"
|
||||
>
|
||||
<td className="p-3 sm:p-4">{p.nome}</td>
|
||||
<td className="p-3 sm:p-4 text-muted-foreground">
|
||||
{p.telefone}
|
||||
</td>
|
||||
<td className="p-3 sm:p-4 text-muted-foreground hidden lg:table-cell">
|
||||
{p.cidade}
|
||||
</td>
|
||||
<td className="p-3 sm:p-4 text-muted-foreground hidden lg:table-cell">
|
||||
{p.estado}
|
||||
</td>
|
||||
<td className="p-3 sm:p-4 text-muted-foreground hidden xl:table-cell">
|
||||
{p.ultimoAtendimento}
|
||||
</td>
|
||||
<td className="p-3 sm:p-4 text-muted-foreground hidden xl:table-cell">
|
||||
{p.proximoAtendimento}
|
||||
</td>
|
||||
<td className="p-3 sm:p-4">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="text-primary hover:underline text-sm sm:text-base">
|
||||
Ações
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => handleOpenModal(p)}>
|
||||
<Eye className="w-4 h-4 mr-2" />
|
||||
Ver detalhes
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/doctor/pacientes/${p.id}/laudos`}>
|
||||
<Edit className="w-4 h-4 mr-2" />
|
||||
Laudos
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => alert(`Agenda para paciente ID: ${p.id}`)}>
|
||||
<Calendar className="w-4 h-4 mr-2" />
|
||||
Ver agenda
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
const newPacientes = pacientes.filter((pac) => pac.id !== p.id);
|
||||
setPacientes(newPacientes);
|
||||
alert(`Paciente ID: ${p.id} excluído`);
|
||||
}}
|
||||
className="text-red-600 focus:bg-red-50 focus:text-red-600"
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
Excluir
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{/* Números das Páginas */}
|
||||
{visiblePageNumbers.map((number) => (
|
||||
<button
|
||||
key={number}
|
||||
onClick={() => paginate(number)}
|
||||
className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border border-border ${
|
||||
currentPage === number
|
||||
? "bg-blue-600 text-primary-foreground shadow-md border-blue-600"
|
||||
: "bg-secondary text-secondary-foreground hover:bg-secondary/80"
|
||||
}`}
|
||||
>
|
||||
{number}
|
||||
</button>
|
||||
))}
|
||||
|
||||
{/* Layout em Cards/Lista para Telas Pequenas */}
|
||||
<div className="md:hidden divide-y divide-border"> {/* Visível apenas em telas pequenas */}
|
||||
{loading ? (
|
||||
<div className="p-6 text-muted-foreground text-center">
|
||||
<Loader2 className="w-6 h-6 animate-spin mx-auto text-primary" />
|
||||
Carregando pacientes...
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="p-6 text-red-600 text-center">{`Erro: ${error}`}</div>
|
||||
) : pacientes.length === 0 ? (
|
||||
<div className="p-8 text-center text-muted-foreground">
|
||||
Nenhum paciente encontrado
|
||||
</div>
|
||||
) : (
|
||||
currentItems.map((p) => (
|
||||
<div key={p.id} className="flex items-center justify-between p-4 hover:bg-accent/40 transition-colors">
|
||||
<div className="flex-1 min-w-0 pr-4"> {/* Adicionado padding à direita */}
|
||||
<div className="text-base font-semibold text-foreground break-words"> {/* Aumentado a fonte e break-words para evitar corte do nome */}
|
||||
{p.nome || "—"}
|
||||
</div>
|
||||
{/* Removido o 'truncate' e adicionado 'break-words' no telefone */}
|
||||
<div className="text-sm text-muted-foreground break-words">
|
||||
Telefone: **{p.telefone || "N/A"}**
|
||||
</div>
|
||||
</div>
|
||||
<div className="ml-4 flex-shrink-0">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="icon">
|
||||
<Eye className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => handleOpenModal(p)}>
|
||||
<Eye className="w-4 h-4 mr-2" />
|
||||
Ver detalhes
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/doctor/pacientes/${p.id}/laudos`}>
|
||||
<Edit className="w-4 h-4 mr-2" />
|
||||
Laudos
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => alert(`Agenda para paciente ID: ${p.id}`)}>
|
||||
<Calendar className="w-4 h-4 mr-2" />
|
||||
Ver agenda
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
const newPacientes = pacientes.filter((pac) => pac.id !== p.id);
|
||||
setPacientes(newPacientes);
|
||||
alert(`Paciente ID: ${p.id} excluído`);
|
||||
}}
|
||||
className="text-red-600 focus:bg-red-50 focus:text-red-600"
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
Excluir
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
|
||||
{/* Paginação */}
|
||||
{totalPages > 1 && (
|
||||
<div className="flex flex-wrap justify-center items-center gap-2 border-t border-border p-4 bg-muted/40">
|
||||
|
||||
{/* Botão Anterior */}
|
||||
<button
|
||||
onClick={goToPrevPage}
|
||||
disabled={currentPage === 1}
|
||||
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-secondary text-secondary-foreground hover:bg-secondary/80 disabled:opacity-50 disabled:cursor-not-allowed border border-border"
|
||||
>
|
||||
{"< Anterior"}
|
||||
</button>
|
||||
|
||||
{/* Números das Páginas */}
|
||||
{visiblePageNumbers.map((number) => (
|
||||
<button
|
||||
key={number}
|
||||
onClick={() => paginate(number)}
|
||||
className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border border-border ${
|
||||
currentPage === number
|
||||
? "bg-green-600 text-primary-foreground shadow-md border-green-600"
|
||||
: "bg-secondary text-secondary-foreground hover:bg-secondary/80"
|
||||
}`}
|
||||
>
|
||||
{number}
|
||||
</button>
|
||||
))}
|
||||
|
||||
{/* Botão Próximo */}
|
||||
<button
|
||||
onClick={goToNextPage}
|
||||
disabled={currentPage === totalPages}
|
||||
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-secondary text-secondary-foreground hover:bg-secondary/80 disabled:opacity-50 disabled:cursor-not-allowed border border-border"
|
||||
>
|
||||
{"Próximo >"}
|
||||
</button>
|
||||
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{/* Botão Próximo */}
|
||||
<button
|
||||
onClick={goToNextPage}
|
||||
disabled={currentPage === totalPages}
|
||||
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-secondary text-secondary-foreground hover:bg-secondary/80 disabled:opacity-50 disabled:cursor-not-allowed border border-border"
|
||||
>
|
||||
{"Próximo >"}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<PatientDetailsModal
|
||||
patient={selectedPatient}
|
||||
@ -418,4 +467,4 @@ export default function PacientesPage() {
|
||||
/>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -138,7 +138,7 @@ export default function LoginPage() {
|
||||
Não tem uma conta de paciente?{" "}
|
||||
</span>
|
||||
<Link href="/patient/register">
|
||||
<span className="font-semibold text-primary hover:underline cursor-pointer">
|
||||
<span className="font-semibold text-blue-600 hover:text-blue-700 hover:underline cursor-pointer">
|
||||
Crie uma agora
|
||||
</span>
|
||||
</Link>
|
||||
@ -232,18 +232,21 @@ export default function LoginPage() {
|
||||
|
||||
{/* Botões */}
|
||||
<div className="flex gap-3 pt-2">
|
||||
{/* Botão Cancelar – Azul contornado */}
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={closeModal}
|
||||
disabled={isLoading}
|
||||
className="flex-1"
|
||||
className="flex-1 bg-blue-600 hover:bg-blue-700 text-white"
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
|
||||
{/* Botão Resetar Senha – Azul sólido */}
|
||||
<Button
|
||||
onClick={handleResetPassword}
|
||||
disabled={isLoading}
|
||||
className="flex-1"
|
||||
className="flex-1 bg-blue-600 hover:bg-blue-700 text-white"
|
||||
>
|
||||
{isLoading ? "Enviando..." : "Resetar Senha"}
|
||||
</Button>
|
||||
|
||||
@ -1,6 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Calendar, Clock, Plus, User } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
@ -10,181 +16,212 @@ import { doctorsService } from "services/doctorsApi.mjs";
|
||||
import Sidebar from "@/components/Sidebar";
|
||||
|
||||
export default function ManagerDashboard() {
|
||||
// 🔹 Estados para usuários
|
||||
const [firstUser, setFirstUser] = useState<any>(null);
|
||||
const [loadingUser, setLoadingUser] = useState(true);
|
||||
// 🔹 Estados para usuários
|
||||
const [firstUser, setFirstUser] = useState<any>(null);
|
||||
const [loadingUser, setLoadingUser] = useState(true);
|
||||
|
||||
// 🔹 Estados para médicos
|
||||
const [doctors, setDoctors] = useState<any[]>([]);
|
||||
const [loadingDoctors, setLoadingDoctors] = useState(true);
|
||||
// 🔹 Estados para médicos
|
||||
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]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Erro ao carregar usuário:", error);
|
||||
} finally {
|
||||
setLoadingUser(false);
|
||||
}
|
||||
// 🔹 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]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Erro ao carregar usuário:", error);
|
||||
} finally {
|
||||
setLoadingUser(false);
|
||||
}
|
||||
}
|
||||
|
||||
fetchFirstUser();
|
||||
}, []);
|
||||
fetchFirstUser();
|
||||
}, []);
|
||||
|
||||
// 🔹 Buscar 3 primeiros médicos
|
||||
useEffect(() => {
|
||||
async function fetchDoctors() {
|
||||
try {
|
||||
const data = await doctorsService.list(); // ajuste se seu service tiver outro método
|
||||
if (Array.isArray(data)) {
|
||||
setDoctors(data.slice(0, 3)); // pega os 3 primeiros
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Erro ao carregar médicos:", error);
|
||||
} finally {
|
||||
setLoadingDoctors(false);
|
||||
}
|
||||
// 🔹 Buscar 3 primeiros médicos
|
||||
useEffect(() => {
|
||||
async function fetchDoctors() {
|
||||
try {
|
||||
const data = await doctorsService.list(); // ajuste se seu service tiver outro método
|
||||
if (Array.isArray(data)) {
|
||||
setDoctors(data.slice(0, 3)); // pega os 3 primeiros
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Erro ao carregar médicos:", error);
|
||||
} finally {
|
||||
setLoadingDoctors(false);
|
||||
}
|
||||
}
|
||||
|
||||
fetchDoctors();
|
||||
}, []);
|
||||
fetchDoctors();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="space-y-6">
|
||||
{/* Cabeçalho */}
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
|
||||
<p className="text-gray-600">Bem-vindo ao seu portal de consultas médicas</p>
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="space-y-6">
|
||||
{/* Cabeçalho */}
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
|
||||
<p className="text-gray-600">
|
||||
Bem-vindo ao seu portal de consultas médicas
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Cards principais */}
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{/* Card 1 */}
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">
|
||||
Relatórios gerenciais
|
||||
</CardTitle>
|
||||
<Calendar className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">0</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Relatórios disponíveis
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Card 2 — Gestão de usuários */}
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">
|
||||
Gestão de usuários
|
||||
</CardTitle>
|
||||
<Clock className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{loadingUser ? (
|
||||
<div className="text-gray-500 text-sm">
|
||||
Carregando usuário...
|
||||
</div>
|
||||
|
||||
{/* Cards principais */}
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{/* Card 1 */}
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Relatórios gerenciais</CardTitle>
|
||||
<Calendar className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">0</div>
|
||||
<p className="text-xs text-muted-foreground">Relatórios disponíveis</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Card 2 — Gestão de usuários */}
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Gestão de usuários</CardTitle>
|
||||
<Clock className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{loadingUser ? (
|
||||
<div className="text-gray-500 text-sm">Carregando usuário...</div>
|
||||
) : firstUser ? (
|
||||
<>
|
||||
<div className="text-2xl font-bold">{firstUser.full_name || "Sem nome"}</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{firstUser.email || "Sem e-mail cadastrado"}
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<div className="text-sm text-gray-500">Nenhum usuário encontrado</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Card 3 — Perfil */}
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Perfil</CardTitle>
|
||||
<User className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">100%</div>
|
||||
<p className="text-xs text-muted-foreground">Dados completos</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : firstUser ? (
|
||||
<>
|
||||
<div className="text-2xl font-bold">
|
||||
{firstUser.full_name || "Sem nome"}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{firstUser.email || "Sem e-mail cadastrado"}
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<div className="text-sm text-gray-500">
|
||||
Nenhum usuário encontrado
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Cards secundários */}
|
||||
<div className="grid md:grid-cols-2 gap-6">
|
||||
{/* Card — Ações rápidas */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Ações Rápidas</CardTitle>
|
||||
<CardDescription>Acesse rapidamente as principais funcionalidades</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<Link href="/manager/home">
|
||||
<Button className="w-full justify-start">
|
||||
<User className="mr-2 h-4 w-4" />
|
||||
Gestão de Médicos
|
||||
</Button>
|
||||
</Link>
|
||||
<Link href="/manager/usuario">
|
||||
<Button variant="outline" className="w-full justify-start bg-transparent">
|
||||
<User className="mr-2 h-4 w-4" />
|
||||
Usuários Cadastrados
|
||||
</Button>
|
||||
</Link>
|
||||
<Link href="/manager/home/novo">
|
||||
<Button variant="outline" className="w-full justify-start bg-transparent">
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Adicionar Novo Médico
|
||||
</Button>
|
||||
</Link>
|
||||
<Link href="/manager/usuario/novo">
|
||||
<Button variant="outline" className="w-full justify-start bg-transparent">
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Criar novo Usuário
|
||||
</Button>
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{/* Card 3 — Perfil */}
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Perfil</CardTitle>
|
||||
<User className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">100%</div>
|
||||
<p className="text-xs text-muted-foreground">Dados completos</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Card — Gestão de Médicos */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Gestão de Médicos</CardTitle>
|
||||
<CardDescription>Médicos cadastrados recentemente</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{loadingDoctors ? (
|
||||
<p className="text-sm text-gray-500">Carregando médicos...</p>
|
||||
) : doctors.length === 0 ? (
|
||||
<p className="text-sm text-gray-500">Nenhum médico cadastrado.</p>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{doctors.map((doc, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-center justify-between p-3 bg-green-50 rounded-lg border border-green-100"
|
||||
>
|
||||
<div>
|
||||
<p className="font-medium">{doc.full_name || "Sem nome"}</p>
|
||||
<p className="text-sm text-gray-600">
|
||||
{doc.specialty || "Sem especialidade"}
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="font-medium text-green-700">
|
||||
{doc.active ? "Ativo" : "Inativo"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
{/* Cards secundários */}
|
||||
<div className="grid md:grid-cols-2 gap-6">
|
||||
{/* Card — Ações rápidas */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Ações Rápidas</CardTitle>
|
||||
<CardDescription>
|
||||
Acesse rapidamente as principais funcionalidades
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<Link href="/manager/home">
|
||||
<Button className="w-full justify-start bg-blue-600 text-white hover:bg-blue-700">
|
||||
<User className="mr-2 h-4 w-4 text-white" />
|
||||
Gestão de Médicos
|
||||
</Button>
|
||||
</Link>
|
||||
<Link href="/manager/usuario">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full justify-start bg-transparent"
|
||||
>
|
||||
<User className="mr-2 h-4 w-4" />
|
||||
Usuários Cadastrados
|
||||
</Button>
|
||||
</Link>
|
||||
<Link href="/manager/home/novo">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full justify-start bg-transparent"
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Adicionar Novo Médico
|
||||
</Button>
|
||||
</Link>
|
||||
<Link href="/manager/usuario/novo">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full justify-start bg-transparent"
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Criar novo Usuário
|
||||
</Button>
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Card — Gestão de Médicos */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Gestão de Médicos</CardTitle>
|
||||
<CardDescription>
|
||||
Médicos cadastrados recentemente
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{loadingDoctors ? (
|
||||
<p className="text-sm text-gray-500">Carregando médicos...</p>
|
||||
) : doctors.length === 0 ? (
|
||||
<p className="text-sm text-gray-500">
|
||||
Nenhum médico cadastrado.
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{doctors.map((doc, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-center justify-between p-3 bg-green-50 rounded-lg border border-green-100"
|
||||
>
|
||||
<div>
|
||||
<p className="font-medium">
|
||||
{doc.full_name || "Sem nome"}
|
||||
</p>
|
||||
<p className="text-sm text-gray-600">
|
||||
{doc.specialty || "Sem especialidade"}
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="font-medium text-green-700">
|
||||
{doc.active ? "Ativo" : "Inativo"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</Sidebar>
|
||||
);
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
|
||||
185
app/manager/disponibilidade/page.tsx
Normal file
185
app/manager/disponibilidade/page.tsx
Normal file
@ -0,0 +1,185 @@
|
||||
"use client";
|
||||
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import Sidebar from "@/components/Sidebar";
|
||||
import WeeklyScheduleCard from "@/components/ui/WeeklyScheduleCard";
|
||||
|
||||
import { useEffect, useState, useMemo } from "react";
|
||||
|
||||
import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
||||
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Filter } from "lucide-react";
|
||||
|
||||
type Doctor = {
|
||||
id: string;
|
||||
full_name: string;
|
||||
specialty: string;
|
||||
active: boolean;
|
||||
};
|
||||
|
||||
type Availability = {
|
||||
id: string;
|
||||
doctor_id: string;
|
||||
weekday: string;
|
||||
start_time: string;
|
||||
end_time: string;
|
||||
};
|
||||
|
||||
export default function AllAvailabilities() {
|
||||
const [availabilities, setAvailabilities] = useState<Availability[] | null>(null);
|
||||
const [doctors, setDoctors] = useState<Doctor[] | null>(null);
|
||||
|
||||
// 🔎 Filtros
|
||||
const [search, setSearch] = useState("");
|
||||
const [specialty, setSpecialty] = useState("all");
|
||||
|
||||
// 🔄 Paginação
|
||||
const ITEMS_PER_PAGE = 6;
|
||||
const [page, setPage] = useState(1);
|
||||
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
const doctorsList = await doctorsService.list();
|
||||
setDoctors(doctorsList);
|
||||
|
||||
const availabilityList = await AvailabilityService.list();
|
||||
setAvailabilities(availabilityList);
|
||||
} catch (e: any) {
|
||||
alert(`${e?.error} ${e?.message}`);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
// 🎯 Obter todas as especialidades existentes
|
||||
const specialties = useMemo(() => {
|
||||
if (!doctors) return [];
|
||||
const unique = Array.from(new Set(doctors.map((d) => d.specialty)));
|
||||
return unique;
|
||||
}, [doctors]);
|
||||
|
||||
// 🔍 Filtrar médicos por especialidade + nome
|
||||
const filteredDoctors = useMemo(() => {
|
||||
if (!doctors) return [];
|
||||
|
||||
return doctors.filter((doctor) => (specialty === "all" ? true : doctor.specialty === specialty)).filter((doctor) => doctor.full_name.toLowerCase().includes(search.toLowerCase()));
|
||||
}, [doctors, search, specialty]);
|
||||
|
||||
// 📄 Paginação (após filtros!)
|
||||
const totalPages = Math.ceil(filteredDoctors.length / ITEMS_PER_PAGE);
|
||||
const paginatedDoctors = filteredDoctors.slice((page - 1) * ITEMS_PER_PAGE, page * ITEMS_PER_PAGE);
|
||||
|
||||
const goNext = () => setPage((p) => Math.min(p + 1, totalPages));
|
||||
const goPrev = () => setPage((p) => Math.max(p - 1, 1));
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="p-6 text-gray-500">Carregando dados...</div>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
|
||||
if (!doctors || !availabilities) {
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="p-6 text-red-600 font-medium">Não foi possível carregar médicos ou disponibilidades.</div>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">Disponibilidade dos Médicos</h1>
|
||||
<p className="text-gray-600">Visualize a agenda semanal individual de cada médico.</p>
|
||||
</div>
|
||||
<Card>
|
||||
<CardContent>
|
||||
{/* 🔎 Filtros */}
|
||||
<div className="flex flex-col md:flex-row gap-4 items-center">
|
||||
{/* Filtro por nome */}
|
||||
<Filter className="w-4 h-4 mr-2" />
|
||||
<Input
|
||||
placeholder="Buscar por nome do médico..."
|
||||
value={search}
|
||||
onChange={(e) => {
|
||||
setSearch(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
className="w-full md:w-1/3"
|
||||
/>
|
||||
|
||||
{/* Filtro por especialidade */}
|
||||
<Select
|
||||
onValueChange={(value) => {
|
||||
setSpecialty(value);
|
||||
setPage(1);
|
||||
}}
|
||||
defaultValue="all"
|
||||
>
|
||||
<SelectTrigger className="w-full md:w-64">
|
||||
<SelectValue placeholder="Especialidade" />
|
||||
</SelectTrigger>
|
||||
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todas as especialidades</SelectItem>
|
||||
{specialties.map((sp) => (
|
||||
<SelectItem key={sp} value={sp}>
|
||||
{sp}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{/* GRID de cards */}
|
||||
<div className="grid md:grid-cols-1 lg:grid-cols-1 gap-6">
|
||||
{paginatedDoctors.map((doctor) => {
|
||||
const doctorAvailabilities = availabilities.filter((a) => a.doctor_id === doctor.id);
|
||||
|
||||
return (
|
||||
<Card key={doctor.id}>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-xl font-semibold">{doctor.full_name}</CardTitle>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent>
|
||||
<WeeklyScheduleCard doctorId={doctor.id} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* 📄 Paginação */}
|
||||
{totalPages > 1 && (
|
||||
<div className="flex justify-center items-center gap-4 pt-4">
|
||||
<Button variant="outline" onClick={goPrev} disabled={page === 1}>
|
||||
Anterior
|
||||
</Button>
|
||||
|
||||
<span className="text-gray-700 font-medium">
|
||||
Página {page} de {totalPages}
|
||||
</span>
|
||||
|
||||
<Button variant="outline" onClick={goNext} disabled={page === totalPages}>
|
||||
Próxima
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -3,416 +3,451 @@
|
||||
import React, { useEffect, useState, useCallback } from "react";
|
||||
import Link from "next/link";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Plus, Eye, Filter, Loader2 } from "lucide-react";
|
||||
import { AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { api, login } from "services/api.mjs";
|
||||
import { usersService } from "services/usersApi.mjs";
|
||||
import Sidebar from "@/components/Sidebar";
|
||||
|
||||
interface FlatUser {
|
||||
id: string;
|
||||
user_id: string;
|
||||
full_name?: string;
|
||||
email: string;
|
||||
phone?: string | null;
|
||||
role: string;
|
||||
id: string;
|
||||
user_id: string;
|
||||
full_name?: string;
|
||||
email: string;
|
||||
phone?: string | null;
|
||||
role: string;
|
||||
}
|
||||
|
||||
interface UserInfoResponse {
|
||||
user: any;
|
||||
profile: any;
|
||||
roles: string[];
|
||||
permissions: Record<string, boolean>;
|
||||
user: any;
|
||||
profile: any;
|
||||
roles: string[];
|
||||
permissions: Record<string, boolean>;
|
||||
}
|
||||
|
||||
export default function UsersPage() {
|
||||
const [users, setUsers] = useState<FlatUser[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
||||
const [userDetails, setUserDetails] = useState<UserInfoResponse | null>(
|
||||
null
|
||||
);
|
||||
const [selectedRole, setSelectedRole] = useState<string>("all");
|
||||
const [users, setUsers] = useState<FlatUser[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
||||
const [userDetails, setUserDetails] = useState<UserInfoResponse | null>(null);
|
||||
const [selectedRole, setSelectedRole] = useState<string>("all");
|
||||
|
||||
// --- Lógica de Paginação INÍCIO ---
|
||||
const [itemsPerPage, setItemsPerPage] = useState(10);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
// --- Lógica de Paginação INÍCIO ---
|
||||
const [itemsPerPage, setItemsPerPage] = useState(10);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
|
||||
const handleItemsPerPageChange = (value: string) => {
|
||||
setItemsPerPage(Number(value));
|
||||
setCurrentPage(1);
|
||||
};
|
||||
// --- Lógica de Paginação FIM ---
|
||||
const handleItemsPerPageChange = (value: string) => {
|
||||
setItemsPerPage(Number(value));
|
||||
setCurrentPage(1);
|
||||
};
|
||||
// --- Lógica de Paginação FIM ---
|
||||
|
||||
const fetchUsers = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const rolesData: any[] = await usersService.list_roles();
|
||||
const rolesArray = Array.isArray(rolesData) ? rolesData : [];
|
||||
const fetchUsers = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const rolesData: any[] = await usersService.list_roles();
|
||||
const rolesArray = Array.isArray(rolesData) ? rolesData : [];
|
||||
|
||||
const profilesData: any[] = await api.get(
|
||||
`/rest/v1/profiles?select=id,full_name,email,phone`
|
||||
);
|
||||
const profilesData: any[] = await api.get(
|
||||
`/rest/v1/profiles?select=id,full_name,email,phone`
|
||||
);
|
||||
|
||||
const profilesById = new Map<string, any>();
|
||||
if (Array.isArray(profilesData)) {
|
||||
for (const p of profilesData) {
|
||||
if (p?.id) profilesById.set(p.id, p);
|
||||
}
|
||||
}
|
||||
|
||||
const mapped: FlatUser[] = rolesArray.map((roleItem) => {
|
||||
const uid = roleItem.user_id;
|
||||
const profile = profilesById.get(uid);
|
||||
return {
|
||||
id: uid,
|
||||
user_id: uid,
|
||||
full_name: profile?.full_name ?? "—",
|
||||
email: profile?.email ?? "—",
|
||||
phone: profile?.phone ?? "—",
|
||||
role: roleItem.role ?? "—",
|
||||
};
|
||||
});
|
||||
|
||||
setUsers(mapped);
|
||||
setCurrentPage(1);
|
||||
} catch (err: any) {
|
||||
console.error("Erro ao buscar usuários:", err);
|
||||
setError("Não foi possível carregar os usuários. Veja console.");
|
||||
setUsers([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
const profilesById = new Map<string, any>();
|
||||
if (Array.isArray(profilesData)) {
|
||||
for (const p of profilesData) {
|
||||
if (p?.id) profilesById.set(p.id, p);
|
||||
}
|
||||
}, []);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const init = async () => {
|
||||
try {
|
||||
await login();
|
||||
} catch (e) {
|
||||
console.warn("login falhou no init:", e);
|
||||
}
|
||||
await fetchUsers();
|
||||
const mapped: FlatUser[] = rolesArray.map((roleItem) => {
|
||||
const uid = roleItem.user_id;
|
||||
const profile = profilesById.get(uid);
|
||||
return {
|
||||
id: uid,
|
||||
user_id: uid,
|
||||
full_name: profile?.full_name ?? "—",
|
||||
email: profile?.email ?? "—",
|
||||
phone: profile?.phone ?? "—",
|
||||
role: roleItem.role ?? "—",
|
||||
};
|
||||
init();
|
||||
}, [fetchUsers]);
|
||||
});
|
||||
|
||||
const openDetailsDialog = async (flatUser: FlatUser) => {
|
||||
setDetailsDialogOpen(true);
|
||||
setUserDetails(null);
|
||||
setUsers(mapped);
|
||||
setCurrentPage(1);
|
||||
} catch (err: any) {
|
||||
console.error("Erro ao buscar usuários:", err);
|
||||
setError("Não foi possível carregar os usuários. Veja console.");
|
||||
setUsers([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
try {
|
||||
const data = await usersService.full_data(flatUser.user_id);
|
||||
setUserDetails(data);
|
||||
} catch (err: any) {
|
||||
console.error("Erro ao carregar detalhes:", err);
|
||||
setUserDetails({
|
||||
user: { id: flatUser.user_id, email: flatUser.email },
|
||||
profile: { full_name: flatUser.full_name, phone: flatUser.phone },
|
||||
roles: [flatUser.role],
|
||||
permissions: {},
|
||||
});
|
||||
}
|
||||
useEffect(() => {
|
||||
const init = async () => {
|
||||
try {
|
||||
await login();
|
||||
} catch (e) {
|
||||
console.warn("login falhou no init:", e);
|
||||
}
|
||||
await fetchUsers();
|
||||
};
|
||||
init();
|
||||
}, [fetchUsers]);
|
||||
|
||||
const filteredUsers =
|
||||
selectedRole && selectedRole !== "all"
|
||||
? users.filter((u) => u.role === selectedRole)
|
||||
: users;
|
||||
const openDetailsDialog = async (flatUser: FlatUser) => {
|
||||
setDetailsDialogOpen(true);
|
||||
setUserDetails(null);
|
||||
|
||||
const indexOfLastItem = currentPage * itemsPerPage;
|
||||
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
||||
const currentItems = filteredUsers.slice(indexOfFirstItem, indexOfLastItem);
|
||||
try {
|
||||
const data = await usersService.full_data(flatUser.user_id);
|
||||
setUserDetails(data);
|
||||
} catch (err: any) {
|
||||
console.error("Erro ao carregar detalhes:", err);
|
||||
setUserDetails({
|
||||
user: { id: flatUser.user_id, email: flatUser.email },
|
||||
profile: { full_name: flatUser.full_name, phone: flatUser.phone },
|
||||
roles: [flatUser.role],
|
||||
permissions: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
|
||||
const filteredUsers =
|
||||
selectedRole && selectedRole !== "all"
|
||||
? users.filter((u) => u.role === selectedRole)
|
||||
: users;
|
||||
|
||||
const totalPages = Math.ceil(filteredUsers.length / itemsPerPage);
|
||||
const indexOfLastItem = currentPage * itemsPerPage;
|
||||
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
||||
const currentItems = filteredUsers.slice(indexOfFirstItem, indexOfLastItem);
|
||||
|
||||
const goToPrevPage = () => {
|
||||
setCurrentPage((prev) => Math.max(1, prev - 1));
|
||||
};
|
||||
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
|
||||
|
||||
const goToNextPage = () => {
|
||||
setCurrentPage((prev) => Math.min(totalPages, prev + 1));
|
||||
};
|
||||
const totalPages = Math.ceil(filteredUsers.length / itemsPerPage);
|
||||
|
||||
const getVisiblePageNumbers = (totalPages: number, currentPage: number) => {
|
||||
const pages: number[] = [];
|
||||
const maxVisiblePages = 5;
|
||||
const halfRange = Math.floor(maxVisiblePages / 2);
|
||||
let startPage = Math.max(1, currentPage - halfRange);
|
||||
let endPage = Math.min(totalPages, currentPage + halfRange);
|
||||
const goToPrevPage = () => {
|
||||
setCurrentPage((prev) => Math.max(1, prev - 1));
|
||||
};
|
||||
|
||||
if (endPage - startPage + 1 < maxVisiblePages) {
|
||||
if (endPage === totalPages) {
|
||||
startPage = Math.max(1, totalPages - maxVisiblePages + 1);
|
||||
}
|
||||
if (startPage === 1) {
|
||||
endPage = Math.min(totalPages, maxVisiblePages);
|
||||
}
|
||||
}
|
||||
const goToNextPage = () => {
|
||||
setCurrentPage((prev) => Math.min(totalPages, prev + 1));
|
||||
};
|
||||
|
||||
for (let i = startPage; i <= endPage; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
return pages;
|
||||
};
|
||||
const getVisiblePageNumbers = (totalPages: number, currentPage: number) => {
|
||||
const pages: number[] = [];
|
||||
const maxVisiblePages = 5;
|
||||
const halfRange = Math.floor(maxVisiblePages / 2);
|
||||
let startPage = Math.max(1, currentPage - halfRange);
|
||||
let endPage = Math.min(totalPages, currentPage + halfRange);
|
||||
|
||||
const visiblePageNumbers = getVisiblePageNumbers(totalPages, currentPage);
|
||||
if (endPage - startPage + 1 < maxVisiblePages) {
|
||||
if (endPage === totalPages) {
|
||||
startPage = Math.max(1, totalPages - maxVisiblePages + 1);
|
||||
}
|
||||
if (startPage === 1) {
|
||||
endPage = Math.min(totalPages, maxVisiblePages);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="space-y-6 px-2 sm:px-4 md:px-8">
|
||||
for (let i = startPage; i <= endPage; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
return pages;
|
||||
};
|
||||
|
||||
{/* Header */}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Usuários</h1>
|
||||
<p className="text-sm text-gray-500">Gerencie usuários.</p>
|
||||
</div>
|
||||
<Link href="/manager/usuario/novo" className="w-full sm:w-auto">
|
||||
<Button className="w-full sm:w-auto bg-green-600 hover:bg-green-700">
|
||||
<Plus className="w-4 h-4 mr-2" /> Novo Usuário
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
const visiblePageNumbers = getVisiblePageNumbers(totalPages, currentPage);
|
||||
|
||||
{/* Filtro e Itens por Página */}
|
||||
<div className="flex flex-wrap items-center gap-3 bg-white p-4 rounded-lg border border-gray-200">
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="space-y-6 px-2 sm:px-4 md:px-8">
|
||||
{/* Header */}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Usuários</h1>
|
||||
<p className="text-sm text-gray-500">Gerencie usuários.</p>
|
||||
</div>
|
||||
<Link href="/manager/usuario/novo" className="w-full sm:w-auto">
|
||||
<Button className="w-full sm:w-auto bg-blue-600 hover:bg-blue-700">
|
||||
<Plus className="w-4 h-4 mr-2" /> Novo Usuário
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* Select de Filtro por Papel - Ajustado para resetar a página */}
|
||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
||||
<span className="text-sm font-medium text-foreground whitespace-nowrap">
|
||||
Filtrar por papel
|
||||
</span>
|
||||
<Select
|
||||
onValueChange={(value) => {
|
||||
setSelectedRole(value);
|
||||
setCurrentPage(1);
|
||||
}}
|
||||
value={selectedRole}>
|
||||
{/* Filtro e Itens por Página */}
|
||||
<div className="flex flex-wrap items-center gap-3 bg-white p-4 rounded-lg border border-gray-200">
|
||||
{/* Select de Filtro por Papel - Ajustado para resetar a página */}
|
||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
||||
<span className="text-sm font-medium text-foreground whitespace-nowrap">
|
||||
Filtrar por papel
|
||||
</span>
|
||||
<Select
|
||||
onValueChange={(value) => {
|
||||
setSelectedRole(value);
|
||||
setCurrentPage(1);
|
||||
}}
|
||||
value={selectedRole}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-[180px]">
|
||||
{" "}
|
||||
{/* w-full para mobile, w-[180px] para sm+ */}
|
||||
<SelectValue placeholder="Filtrar por papel" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todos</SelectItem>
|
||||
<SelectItem value="admin">Admin</SelectItem>
|
||||
<SelectItem value="gestor">Gestor</SelectItem>
|
||||
<SelectItem value="medico">Médico</SelectItem>
|
||||
<SelectItem value="secretaria">Secretária</SelectItem>
|
||||
<SelectItem value="user">Usuário</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<SelectTrigger className="w-full sm:w-[180px]"> {/* w-full para mobile, w-[180px] para sm+ */}
|
||||
<SelectValue placeholder="Filtrar por papel" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todos</SelectItem>
|
||||
<SelectItem value="admin">Admin</SelectItem>
|
||||
<SelectItem value="gestor">Gestor</SelectItem>
|
||||
<SelectItem value="medico">Médico</SelectItem>
|
||||
<SelectItem value="secretaria">Secretária</SelectItem>
|
||||
<SelectItem value="user">Usuário</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
{/* Select de Itens por Página */}
|
||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
||||
<span className="text-sm font-medium text-foreground whitespace-nowrap">
|
||||
Itens por página
|
||||
</span>
|
||||
<Select
|
||||
onValueChange={handleItemsPerPageChange}
|
||||
defaultValue={String(itemsPerPage)}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-[140px]">
|
||||
{" "}
|
||||
{/* w-full para mobile, w-[140px] para sm+ */}
|
||||
<SelectValue placeholder="Itens por pág." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="5">5 por página</SelectItem>
|
||||
<SelectItem value="10">10 por página</SelectItem>
|
||||
<SelectItem value="20">20 por página</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<Button variant="outline" className="ml-auto w-full md:w-auto">
|
||||
<Filter className="w-4 h-4 mr-2" />
|
||||
Filtro avançado
|
||||
</Button>
|
||||
</div>
|
||||
{/* Fim do Filtro e Itens por Página */}
|
||||
|
||||
{/* Select de Itens por Página */}
|
||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
||||
<span className="text-sm font-medium text-foreground whitespace-nowrap">
|
||||
Itens por página
|
||||
</span>
|
||||
<Select
|
||||
onValueChange={handleItemsPerPageChange}
|
||||
defaultValue={String(itemsPerPage)}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-[140px]"> {/* w-full para mobile, w-[140px] para sm+ */}
|
||||
<SelectValue placeholder="Itens por pág." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="5">5 por página</SelectItem>
|
||||
<SelectItem value="10">10 por página</SelectItem>
|
||||
<SelectItem value="20">20 por página</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<Button variant="outline" className="ml-auto w-full md:w-auto">
|
||||
<Filter className="w-4 h-4 mr-2" />
|
||||
Filtro avançado
|
||||
</Button>
|
||||
</div>
|
||||
{/* Fim do Filtro e Itens por Página */}
|
||||
|
||||
{/* Tabela/Lista */}
|
||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-x-auto">
|
||||
{loading ? (
|
||||
<div className="p-8 text-center text-gray-500">
|
||||
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
|
||||
Carregando usuários...
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="p-8 text-center text-red-600">{error}</div>
|
||||
) : filteredUsers.length === 0 ? (
|
||||
<div className="p-8 text-center text-gray-500">
|
||||
Nenhum usuário encontrado com os filtros aplicados.
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Tabela para Telas Médias e Grandes */}
|
||||
<table className="min-w-full divide-y divide-gray-200 hidden md:table">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Nome</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">E-mail</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Telefone</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Cargo</th>
|
||||
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{currentItems.map((u) => (
|
||||
<tr key={u.id} className="hover:bg-gray-50">
|
||||
<td className="px-6 py-4 text-sm text-gray-900">
|
||||
{u.full_name}
|
||||
</td>
|
||||
<td className="px-6 py-4 text-sm text-gray-500 break-all">
|
||||
{u.email}
|
||||
</td>
|
||||
<td className="px-6 py-4 text-sm text-gray-500">
|
||||
{u.phone}
|
||||
</td>
|
||||
<td className="px-6 py-4 text-sm text-gray-500 capitalize">
|
||||
{u.role}
|
||||
</td>
|
||||
<td className="px-6 py-4 text-right">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => openDetailsDialog(u)}
|
||||
title="Visualizar"
|
||||
>
|
||||
<Eye className="h-4 w-4" />
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
{/* Layout em Cards/Lista para Telas Pequenas */}
|
||||
<div className="md:hidden divide-y divide-gray-200">
|
||||
{currentItems.map((u) => (
|
||||
<div key={u.id} className="flex items-center justify-between p-4 hover:bg-gray-50">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm font-medium text-gray-900 truncate">
|
||||
{u.full_name || "—"}
|
||||
</div>
|
||||
<div className="text-sm text-gray-500 capitalize">
|
||||
{u.role || "—"}
|
||||
</div>
|
||||
</div>
|
||||
<div className="ml-4 flex-shrink-0">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => openDetailsDialog(u)}
|
||||
title="Visualizar"
|
||||
>
|
||||
<Eye className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Paginação */}
|
||||
{totalPages > 1 && (
|
||||
<div className="flex flex-wrap justify-center items-center gap-2 mt-4 p-4 border-t border-gray-200">
|
||||
|
||||
{/* Botão Anterior */}
|
||||
<button
|
||||
onClick={goToPrevPage}
|
||||
disabled={currentPage === 1}
|
||||
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300"
|
||||
>
|
||||
{"< Anterior"}
|
||||
</button>
|
||||
|
||||
{/* Números das Páginas */}
|
||||
{visiblePageNumbers.map((number) => (
|
||||
<button
|
||||
key={number}
|
||||
onClick={() => paginate(number)}
|
||||
className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border border-gray-300 ${currentPage === number
|
||||
? "bg-green-600 text-white shadow-md border-green-600"
|
||||
: "bg-gray-100 text-gray-700 hover:bg-gray-200"
|
||||
}`}
|
||||
>
|
||||
{number}
|
||||
</button>
|
||||
))}
|
||||
|
||||
{/* Botão Próximo */}
|
||||
<button
|
||||
onClick={goToNextPage}
|
||||
disabled={currentPage === totalPages}
|
||||
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300"
|
||||
>
|
||||
{"Próximo >"}
|
||||
</button>
|
||||
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Modal de Detalhes */}
|
||||
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="text-2xl">
|
||||
{userDetails?.profile?.full_name || "Detalhes do Usuário"}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{!userDetails ? (
|
||||
<div className="p-4 text-center text-gray-500">
|
||||
<Loader2 className="w-6 h-6 animate-spin mx-auto mb-3 text-green-600" />
|
||||
Buscando dados completos...
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3 pt-2 text-left text-gray-700">
|
||||
<div>
|
||||
<strong>ID:</strong> {userDetails.user.id}
|
||||
</div>
|
||||
<div>
|
||||
<strong>E-mail:</strong> {userDetails.user.email}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Nome completo:</strong>{" "}
|
||||
{userDetails.profile.full_name}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Telefone:</strong> {userDetails.profile.phone}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Roles:</strong>{" "}
|
||||
{userDetails.roles?.join(", ")}
|
||||
</div>
|
||||
<div className="pt-2">
|
||||
<strong className="block mb-1">Permissões:</strong>
|
||||
<ul className="list-disc list-inside space-y-0.5 text-sm">
|
||||
{Object.entries(
|
||||
userDetails.permissions || {}
|
||||
).map(([k, v]) => (
|
||||
<li key={k}>
|
||||
{k}: <span className={`font-semibold ${v ? 'text-green-600' : 'text-red-600'}`}>{v ? "Sim" : "Não"}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Fechar</AlertDialogCancel>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
{/* Tabela/Lista */}
|
||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-x-auto">
|
||||
{loading ? (
|
||||
<div className="p-8 text-center text-gray-500">
|
||||
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
|
||||
Carregando usuários...
|
||||
</div>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
) : error ? (
|
||||
<div className="p-8 text-center text-red-600">{error}</div>
|
||||
) : filteredUsers.length === 0 ? (
|
||||
<div className="p-8 text-center text-gray-500">
|
||||
Nenhum usuário encontrado com os filtros aplicados.
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Tabela para Telas Médias e Grandes */}
|
||||
<table className="min-w-full divide-y divide-gray-200 hidden md:table">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
|
||||
Nome
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
|
||||
E-mail
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
|
||||
Telefone
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
|
||||
Cargo
|
||||
</th>
|
||||
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">
|
||||
Ações
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{currentItems.map((u) => (
|
||||
<tr key={u.id} className="hover:bg-gray-50">
|
||||
<td className="px-6 py-4 text-sm text-gray-900">
|
||||
{u.full_name}
|
||||
</td>
|
||||
<td className="px-6 py-4 text-sm text-gray-500 break-all">
|
||||
{u.email}
|
||||
</td>
|
||||
<td className="px-6 py-4 text-sm text-gray-500">
|
||||
{u.phone}
|
||||
</td>
|
||||
<td className="px-6 py-4 text-sm text-gray-500 capitalize">
|
||||
{u.role}
|
||||
</td>
|
||||
<td className="px-6 py-4 text-right">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => openDetailsDialog(u)}
|
||||
title="Visualizar"
|
||||
>
|
||||
<Eye className="h-4 w-4" />
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
{/* Layout em Cards/Lista para Telas Pequenas */}
|
||||
<div className="md:hidden divide-y divide-gray-200">
|
||||
{currentItems.map((u) => (
|
||||
<div
|
||||
key={u.id}
|
||||
className="flex items-center justify-between p-4 hover:bg-gray-50"
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm font-medium text-gray-900 truncate">
|
||||
{u.full_name || "—"}
|
||||
</div>
|
||||
<div className="text-sm text-gray-500 capitalize">
|
||||
{u.role || "—"}
|
||||
</div>
|
||||
</div>
|
||||
<div className="ml-4 flex-shrink-0">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => openDetailsDialog(u)}
|
||||
title="Visualizar"
|
||||
>
|
||||
<Eye className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Paginação */}
|
||||
{totalPages > 1 && (
|
||||
<div className="flex flex-wrap justify-center items-center gap-2 mt-4 p-4 border-t border-gray-200">
|
||||
{/* Botão Anterior */}
|
||||
<button
|
||||
onClick={goToPrevPage}
|
||||
disabled={currentPage === 1}
|
||||
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300"
|
||||
>
|
||||
{"< Anterior"}
|
||||
</button>
|
||||
|
||||
{/* Números das Páginas */}
|
||||
{visiblePageNumbers.map((number) => (
|
||||
<button
|
||||
key={number}
|
||||
onClick={() => paginate(number)}
|
||||
className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border border-gray-300 ${
|
||||
currentPage === number
|
||||
? "bg-blue-600 text-white shadow-md border-blue-600"
|
||||
: "bg-gray-100 text-gray-700 hover:bg-gray-200"
|
||||
}`}
|
||||
>
|
||||
{number}
|
||||
</button>
|
||||
))}
|
||||
|
||||
{/* Botão Próximo */}
|
||||
<button
|
||||
onClick={goToNextPage}
|
||||
disabled={currentPage === totalPages}
|
||||
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300"
|
||||
>
|
||||
{"Próximo >"}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Modal de Detalhes */}
|
||||
<AlertDialog
|
||||
open={detailsDialogOpen}
|
||||
onOpenChange={setDetailsDialogOpen}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="text-2xl">
|
||||
{userDetails?.profile?.full_name || "Detalhes do Usuário"}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{!userDetails ? (
|
||||
<div className="p-4 text-center text-gray-500">
|
||||
<Loader2 className="w-6 h-6 animate-spin mx-auto mb-3 text-green-600" />
|
||||
Buscando dados completos...
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3 pt-2 text-left text-gray-700">
|
||||
<div>
|
||||
<strong>ID:</strong> {userDetails.user.id}
|
||||
</div>
|
||||
<div>
|
||||
<strong>E-mail:</strong> {userDetails.user.email}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Nome completo:</strong>{" "}
|
||||
{userDetails.profile.full_name}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Telefone:</strong> {userDetails.profile.phone}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Roles:</strong> {userDetails.roles?.join(", ")}
|
||||
</div>
|
||||
<div className="pt-2">
|
||||
<strong className="block mb-1">Permissões:</strong>
|
||||
<ul className="list-disc list-inside space-y-0.5 text-sm">
|
||||
{Object.entries(userDetails.permissions || {}).map(
|
||||
([k, v]) => (
|
||||
<li key={k}>
|
||||
{k}:{" "}
|
||||
<span
|
||||
className={`font-semibold ${
|
||||
v ? "text-green-600" : "text-red-600"
|
||||
}`}
|
||||
>
|
||||
{v ? "Sim" : "Não"}
|
||||
</span>
|
||||
</li>
|
||||
)
|
||||
)}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Fechar</AlertDialogCancel>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
|
||||
175
app/page.tsx
175
app/page.tsx
@ -3,50 +3,49 @@
|
||||
import Link from "next/link";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useState } from "react";
|
||||
import { Stethoscope, Baby, Microscope } from "lucide-react";
|
||||
|
||||
export default function InicialPage() {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col bg-background">
|
||||
{/* Barra superior de informações */}
|
||||
<div className="bg-primary text-primary-foreground text-sm py-2 px-4 md:px-6 flex justify-between items-center">
|
||||
<div className="min-h-screen flex flex-col bg-white font-sans scroll-smooth text-[#1E2A78]">
|
||||
{/* Barra superior */}
|
||||
<div className="bg-[#1E2A78] text-white text-sm py-2 px-4 md:px-6 flex justify-between items-center">
|
||||
<span className="hidden sm:inline">Horário: 08h00 - 21h00</span>
|
||||
<span>Email: contato@mediconnect.com</span>
|
||||
<span className="hover:underline cursor-pointer transition">
|
||||
Email: contato@mediconnect.com
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Header principal - Com Logo REAL */}
|
||||
<header className="bg-card shadow-md py-4 px-4 md:px-6 flex justify-between items-center relative">
|
||||
{/* Agrupamento do Logo e Nome do Site */}
|
||||
<a href="#home" className="flex items-center space-x-1 cursor-pointer">
|
||||
{/* 1. IMAGEM/LOGO REAL: Referenciando o arquivo placeholder-logo.png na pasta public */}
|
||||
{/* Header */}
|
||||
<header className="bg-white shadow-md py-4 px-4 md:px-6 flex justify-between items-center relative sticky top-0 z-50 backdrop-blur-md">
|
||||
<a href="#home" className="flex items-center space-x-2 cursor-pointer">
|
||||
<img
|
||||
src="/android-chrome-512x512.png" // O caminho se inicia a partir da pasta 'public'
|
||||
src="/android-chrome-512x512.png"
|
||||
alt="Logo MediConnect"
|
||||
className="w-14 h-14 object-contain" // ALTERADO: Aumentado para w-14 h-14
|
||||
className="w-20 h-20 object-contain transition-transform hover:scale-105"
|
||||
/>
|
||||
|
||||
{/* 2. NOME DO SITE */}
|
||||
<h1 className="text-2xl font-bold text-primary">MedConnect</h1>
|
||||
<h1 className="text-2xl font-extrabold text-[#1E2A78] tracking-tight">
|
||||
MedConnect
|
||||
</h1>
|
||||
</a>
|
||||
|
||||
{/* Botão do menu hambúrguer para telas menores */}
|
||||
{/* Menu Mobile */}
|
||||
<div className="md:hidden flex items-center space-x-4">
|
||||
{/* O botão de login agora estará sempre aqui, fora do menu */}
|
||||
<Link href="/login">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="rounded-full px-4 py-2 text-sm border-2 transition cursor-pointer"
|
||||
className="rounded-full px-4 py-2 text-sm border-2 border-[#007BFF] text-[#007BFF] hover:bg-[#007BFF] hover:text-white transition"
|
||||
>
|
||||
Login
|
||||
</Button>
|
||||
</Link>
|
||||
<button
|
||||
onClick={() => setIsMenuOpen(!isMenuOpen)}
|
||||
className="text-primary-foreground focus:outline-none"
|
||||
className="text-[#1E2A78] focus:outline-none"
|
||||
>
|
||||
<svg
|
||||
className="w-6 h-6 text-primary"
|
||||
className="w-6 h-6"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
@ -71,114 +70,140 @@ export default function InicialPage() {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Navegação principal */}
|
||||
{/* Navegação */}
|
||||
<nav
|
||||
className={`${
|
||||
isMenuOpen ? "block" : "hidden"
|
||||
} absolute top-[76px] left-0 w-full bg-card shadow-md py-4 md:relative md:top-auto md:left-auto md:w-auto md:block md:bg-transparent md:shadow-none z-10`}
|
||||
} absolute top-[76px] left-0 w-full bg-white shadow-md py-4 md:relative md:top-auto md:left-auto md:w-auto md:block md:bg-transparent md:shadow-none transition-all duration-300 z-10`}
|
||||
>
|
||||
<div className="flex flex-col md:flex-row space-y-4 md:space-y-0 md:space-x-6 text-muted-foreground font-medium items-center">
|
||||
<Link href="#home" className="hover:text-primary">
|
||||
<div className="flex flex-col md:flex-row space-y-4 md:space-y-0 md:space-x-8 text-gray-600 font-medium items-center">
|
||||
<Link href="#home" className="hover:text-[#007BFF] transition">
|
||||
Home
|
||||
</Link>
|
||||
<a href="#about" className="hover:text-primary">
|
||||
<a href="#about" className="hover:text-[#007BFF] transition">
|
||||
Sobre
|
||||
</a>
|
||||
<a href="#departments" className="hover:text-primary">
|
||||
<a href="#departments" className="hover:text-[#007BFF] transition">
|
||||
Departamentos
|
||||
</a>
|
||||
<a href="#doctors" className="hover:text-primary">
|
||||
<a href="#doctors" className="hover:text-[#007BFF] transition">
|
||||
Médicos
|
||||
</a>
|
||||
<a href="#contact" className="hover:text-primary">
|
||||
<a href="#contact" className="hover:text-[#007BFF] transition">
|
||||
Contato
|
||||
</a>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
{/* Botão de Login para telas maiores (md e acima) */}
|
||||
{/* Login Desktop */}
|
||||
<div className="hidden md:flex space-x-4">
|
||||
<Link href="/login">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="rounded-full px-6 py-2 border-2 transition cursor-pointer"
|
||||
className="rounded-full px-6 py-2 border-2 border-[#007BFF] text-[#007BFF] hover:bg-[#007BFF] hover:text-white transition"
|
||||
>
|
||||
Login
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Seção principal de destaque */}
|
||||
<section className="flex flex-col md:flex-row items-center justify-between px-6 md:px-10 lg:px-20 py-16 bg-background text-center md:text-left">
|
||||
{/* Hero Section */}
|
||||
<section className="flex flex-col md:flex-row items-center justify-between px-6 md:px-10 lg:px-20 py-20 bg-gradient-to-r from-[#1E2A78] via-[#007BFF] to-[#00BFFF] text-white">
|
||||
<div className="max-w-lg mx-auto md:mx-0">
|
||||
<h2 className="text-muted-foreground uppercase text-sm">
|
||||
<h2 className="uppercase text-sm tracking-widest opacity-80">
|
||||
Bem-vindo à Saúde Digital
|
||||
</h2>
|
||||
<h1 className="text-3xl sm:text-4xl lg:text-5xl font-extrabold text-foreground leading-tight mt-2">
|
||||
<h1 className="text-4xl sm:text-5xl lg:text-6xl font-extrabold leading-tight mt-2 drop-shadow-lg">
|
||||
Soluções Médicas <br /> & Cuidados com a Saúde
|
||||
</h1>
|
||||
<p className="text-muted-foreground mt-4 text-sm sm:text-base">
|
||||
<p className="mt-4 text-base leading-relaxed opacity-90">
|
||||
Excelência em saúde há mais de 25 anos. Atendimento médico com
|
||||
qualidade, segurança e carinho.
|
||||
</p>
|
||||
<div className="mt-6 flex flex-col sm:flex-row space-y-4 sm:space-y-0 sm:space-x-4 justify-center md:justify-start">
|
||||
<Button>Nossos Serviços</Button>
|
||||
<Button variant="secondary">Saiba Mais</Button>
|
||||
<div className="mt-8 flex flex-col sm:flex-row space-y-4 sm:space-y-0 sm:space-x-4 justify-center md:justify-start">
|
||||
<Button className="px-8 py-3 text-base font-semibold bg-white text-[#1E2A78] hover:bg-[#EAF4FF] transition-all shadow-md">
|
||||
Nossos Serviços
|
||||
</Button>
|
||||
<Button className="px-8 py-3 text-base font-semibold bg-white text-[#1E2A78] hover:bg-[#EAF4FF] transition-all shadow-md">
|
||||
Saiba Mais
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-10 md:mt-0 flex justify-center">
|
||||
<img
|
||||
src="https://t4.ftcdn.net/jpg/03/20/52/31/360_F_320523164_tx7Rdd7I2XDTvvKfz2oRuRpKOPE5z0ni.jpg"
|
||||
alt="Médico"
|
||||
className="w-60 sm:w-80 lg:w-96 h-auto object-cover rounded-lg shadow-lg"
|
||||
className="w-72 sm:w-96 lg:w-[28rem] h-auto object-cover rounded-2xl shadow-xl "
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Seção de serviços */}
|
||||
<section className="py-16 px-6 md:px-10 lg:px-20 bg-card">
|
||||
<h2 className="text-center text-2xl sm:text-3xl font-bold text-foreground">
|
||||
{/* Serviços */}
|
||||
<section
|
||||
id="departments"
|
||||
className="py-20 px-6 md:px-10 lg:px-20 bg-[#F8FBFF]"
|
||||
>
|
||||
<h2 className="text-center text-3xl sm:text-4xl font-extrabold text-[#1E2A78]">
|
||||
Cuidados completos para a sua saúde
|
||||
</h2>
|
||||
<p className="text-center text-muted-foreground mt-2 text-sm sm:text-base">
|
||||
<p className="text-center text-gray-600 mt-3 text-base">
|
||||
Serviços médicos que oferecemos
|
||||
</p>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 mt-10 max-w-5xl mx-auto">
|
||||
<div className="p-6 bg-background rounded-xl shadow hover:shadow-lg transition">
|
||||
<h3 className="text-xl font-semibold text-primary">
|
||||
Clínica Geral
|
||||
</h3>
|
||||
<p className="text-muted-foreground mt-2 text-sm">
|
||||
Seu primeiro passo para o cuidado. Atendimento focado na prevenção
|
||||
e no diagnóstico inicial.
|
||||
</p>
|
||||
<Button className="mt-4 w-full">Agendar</Button>
|
||||
</div>
|
||||
<div className="p-6 bg-background rounded-xl shadow hover:shadow-lg transition">
|
||||
<h3 className="text-xl font-semibold text-primary">Pediatria</h3>
|
||||
<p className="text-muted-foreground mt-2 text-sm">
|
||||
Cuidado gentil e especializado para garantir a saúde e o
|
||||
desenvolvimento de crianças e adolescentes.
|
||||
</p>
|
||||
<Button className="mt-4 w-full">Agendar</Button>
|
||||
</div>
|
||||
<div className="p-6 bg-background rounded-xl shadow hover:shadow-lg transition">
|
||||
<h3 className="text-xl font-semibold text-primary">Exames</h3>
|
||||
<p className="text-muted-foreground mt-2 text-sm">
|
||||
Resultados rápidos e precisos em exames laboratoriais e de imagem
|
||||
essenciais para seu diagnóstico.
|
||||
</p>
|
||||
<Button className="mt-4 w-full">Agendar</Button>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-10 mt-12 max-w-6xl mx-auto">
|
||||
{/* Card */}
|
||||
{[
|
||||
{
|
||||
title: "Clínica Geral",
|
||||
desc: "Seu primeiro passo para o cuidado. Atendimento focado na prevenção e no diagnóstico inicial.",
|
||||
Icon: Stethoscope,
|
||||
},
|
||||
{
|
||||
title: "Pediatria",
|
||||
desc: "Cuidado gentil e especializado para garantir a saúde e o desenvolvimento de crianças e adolescentes.",
|
||||
Icon: Baby,
|
||||
},
|
||||
{
|
||||
title: "Exames",
|
||||
desc: "Resultados rápidos e precisos em exames laboratoriais e de imagem essenciais para seu diagnóstico.",
|
||||
Icon: Microscope,
|
||||
},
|
||||
].map(({ title, desc, Icon }, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="p-8 bg-white rounded-2xl shadow-md hover:shadow-xl transition-all duration-300 border border-[#E0E9FF] group"
|
||||
>
|
||||
<div className="flex items-center space-x-3">
|
||||
<Icon className="text-[#007BFF] w-6 h-6 group-hover:scale-110 transition-transform" />
|
||||
<h3 className="text-xl font-semibold">{title}</h3>
|
||||
</div>
|
||||
<p className="text-gray-600 mt-3 text-sm leading-relaxed">
|
||||
{desc}
|
||||
</p>
|
||||
<Button className="mt-6 w-full bg-[#007BFF] hover:bg-[#005FCC] text-white transition">
|
||||
Agendar
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Footer */}
|
||||
<footer className="bg-primary text-primary-foreground py-6 text-center text-sm">
|
||||
<p>© 2025 MediConnect</p>
|
||||
<footer className="bg-[#1E2A78] text-white py-8 text-center text-sm">
|
||||
<div className="space-y-2">
|
||||
<p>© 2025 MediConnect — Todos os direitos reservados</p>
|
||||
<div className="flex justify-center space-x-6 opacity-80">
|
||||
<a href="#about" className="hover:text-[#00BFFF] transition">
|
||||
Sobre
|
||||
</a>
|
||||
<a href="#departments" className="hover:text-[#00BFFF] transition">
|
||||
Serviços
|
||||
</a>
|
||||
<a href="#contact" className="hover:text-[#00BFFF] transition">
|
||||
Contato
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,8 +1,14 @@
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Calendar, Clock, User, Plus } from "lucide-react"
|
||||
import Link from "next/link"
|
||||
import Sidebar from "@/components/Sidebar"
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Calendar, Clock, User, Plus } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import Sidebar from "@/components/Sidebar";
|
||||
|
||||
export default function PatientDashboard() {
|
||||
return (
|
||||
@ -10,13 +16,17 @@ export default function PatientDashboard() {
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
|
||||
<p className="text-gray-600">Bem-vindo ao seu portal de consultas médicas</p>
|
||||
<p className="text-gray-600">
|
||||
Bem-vindo ao seu portal de consultas médicas
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Próxima Consulta</CardTitle>
|
||||
<CardTitle className="text-sm font-medium">
|
||||
Próxima Consulta
|
||||
</CardTitle>
|
||||
<Calendar className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
@ -27,12 +37,16 @@ export default function PatientDashboard() {
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Consultas Este Mês</CardTitle>
|
||||
<CardTitle className="text-sm font-medium">
|
||||
Consultas Este Mês
|
||||
</CardTitle>
|
||||
<Clock className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">3</div>
|
||||
<p className="text-xs text-muted-foreground">2 realizadas, 1 agendada</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
2 realizadas, 1 agendada
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@ -52,23 +66,31 @@ export default function PatientDashboard() {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Ações Rápidas</CardTitle>
|
||||
<CardDescription>Acesse rapidamente as principais funcionalidades</CardDescription>
|
||||
<CardDescription>
|
||||
Acesse rapidamente as principais funcionalidades
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<Link href="/patient/schedule">
|
||||
<Button className="w-full justify-start">
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
<Button className="w-full justify-start bg-blue-600 text-white hover:bg-blue-700">
|
||||
<User className="mr-2 h-4 w-4 text-white" />
|
||||
Agendar Nova Consulta
|
||||
</Button>
|
||||
</Link>
|
||||
<Link href="/patient/appointments">
|
||||
<Button variant="outline" className="w-full justify-start bg-transparent">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full justify-start bg-transparent"
|
||||
>
|
||||
<Calendar className="mr-2 h-4 w-4" />
|
||||
Ver Minhas Consultas
|
||||
</Button>
|
||||
</Link>
|
||||
<Link href="/patient/profile">
|
||||
<Button variant="outline" className="w-full justify-start bg-transparent">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full justify-start bg-transparent"
|
||||
>
|
||||
<User className="mr-2 h-4 w-4" />
|
||||
Atualizar Dados
|
||||
</Button>
|
||||
@ -109,5 +131,5 @@ export default function PatientDashboard() {
|
||||
</div>
|
||||
</div>
|
||||
</Sidebar>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@ -18,243 +18,359 @@ import { toast } from "@/hooks/use-toast";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
|
||||
interface PatientProfileData {
|
||||
name: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
cpf: string;
|
||||
birthDate: string;
|
||||
cep: string;
|
||||
street: string;
|
||||
number: string;
|
||||
city: string;
|
||||
avatarFullUrl?: string;
|
||||
name: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
cpf: string;
|
||||
birthDate: string;
|
||||
cep: string;
|
||||
street: string;
|
||||
number: string;
|
||||
city: string;
|
||||
avatarFullUrl?: string;
|
||||
}
|
||||
|
||||
export default function PatientProfile() {
|
||||
const { user, isLoading: isAuthLoading } = useAuthLayout({ requiredRole: ["paciente", "admin", "medico", "gestor", "secretaria"] });
|
||||
const [patientData, setPatientData] = useState<PatientProfileData | null>(null);
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const { user, isLoading: isAuthLoading } = useAuthLayout({
|
||||
requiredRole: ["paciente", "admin", "medico", "gestor", "secretaria"],
|
||||
});
|
||||
const [patientData, setPatientData] = useState<PatientProfileData | null>(
|
||||
null
|
||||
);
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (user?.id) {
|
||||
const fetchPatientDetails = async () => {
|
||||
try {
|
||||
const patientDetails = await patientsService.getById(user.id);
|
||||
setPatientData({
|
||||
name: patientDetails.full_name || user.name,
|
||||
email: user.email,
|
||||
phone: patientDetails.phone_mobile || "",
|
||||
cpf: patientDetails.cpf || "",
|
||||
birthDate: patientDetails.birth_date || "",
|
||||
cep: patientDetails.cep || "",
|
||||
street: patientDetails.street || "",
|
||||
number: patientDetails.number || "",
|
||||
city: patientDetails.city || "",
|
||||
avatarFullUrl: user.avatarFullUrl,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Erro ao buscar detalhes do paciente:", error);
|
||||
toast({ title: "Erro", description: "Não foi possível carregar seus dados completos.", variant: "destructive" });
|
||||
}
|
||||
};
|
||||
fetchPatientDetails();
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
const handleInputChange = (field: keyof PatientProfileData, value: string) => {
|
||||
setPatientData((prev) => (prev ? { ...prev, [field]: value } : null));
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!patientData || !user) return;
|
||||
setIsSaving(true);
|
||||
useEffect(() => {
|
||||
if (user?.id) {
|
||||
const fetchPatientDetails = async () => {
|
||||
try {
|
||||
const patientPayload = {
|
||||
full_name: patientData.name,
|
||||
cpf: patientData.cpf,
|
||||
birth_date: patientData.birthDate,
|
||||
phone_mobile: patientData.phone,
|
||||
cep: patientData.cep,
|
||||
street: patientData.street,
|
||||
number: patientData.number,
|
||||
city: patientData.city,
|
||||
};
|
||||
await patientsService.update(user.id, patientPayload);
|
||||
toast({ title: "Sucesso!", description: "Seus dados foram atualizados." });
|
||||
setIsEditing(false);
|
||||
const patientDetails = await patientsService.getById(user.id);
|
||||
setPatientData({
|
||||
name: patientDetails.full_name || user.name,
|
||||
email: user.email,
|
||||
phone: patientDetails.phone_mobile || "",
|
||||
cpf: patientDetails.cpf || "",
|
||||
birthDate: patientDetails.birth_date || "",
|
||||
cep: patientDetails.cep || "",
|
||||
street: patientDetails.street || "",
|
||||
number: patientDetails.number || "",
|
||||
city: patientDetails.city || "",
|
||||
avatarFullUrl: user.avatarFullUrl,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Erro ao salvar dados:", error);
|
||||
toast({ title: "Erro", description: "Não foi possível salvar suas alterações.", variant: "destructive" });
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
console.error("Erro ao buscar detalhes do paciente:", error);
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: "Não foi possível carregar seus dados completos.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleAvatarClick = () => {
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
|
||||
const handleAvatarUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
if (!file || !user) return;
|
||||
|
||||
const fileExt = file.name.split(".").pop();
|
||||
|
||||
// *** A CORREÇÃO ESTÁ AQUI ***
|
||||
// O caminho salvo no banco de dados não deve conter o nome do bucket.
|
||||
const filePath = `${user.id}/avatar.${fileExt}`;
|
||||
|
||||
try {
|
||||
await api.storage.upload("avatars", filePath, file);
|
||||
await api.patch(`/rest/v1/profiles?id=eq.${user.id}`, { avatar_url: filePath });
|
||||
|
||||
const newFullUrl = `https://yuanqfswhberkoevtmfr.supabase.co/storage/v1/object/public/avatars/${filePath}?t=${new Date().getTime()}`;
|
||||
setPatientData((prev) => (prev ? { ...prev, avatarFullUrl: newFullUrl } : null));
|
||||
|
||||
toast({ title: "Sucesso!", description: "Sua foto de perfil foi atualizada." });
|
||||
} catch (error) {
|
||||
console.error("Erro no upload do avatar:", error);
|
||||
toast({ title: "Erro de Upload", description: "Não foi possível enviar sua foto.", variant: "destructive" });
|
||||
}
|
||||
};
|
||||
|
||||
if (isAuthLoading || !patientData) {
|
||||
return (
|
||||
<Sidebar>
|
||||
<div>Carregando seus dados...</div>
|
||||
</Sidebar>
|
||||
);
|
||||
};
|
||||
fetchPatientDetails();
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
const handleInputChange = (
|
||||
field: keyof PatientProfileData,
|
||||
value: string
|
||||
) => {
|
||||
setPatientData((prev) => (prev ? { ...prev, [field]: value } : null));
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!patientData || !user) return;
|
||||
setIsSaving(true);
|
||||
try {
|
||||
const patientPayload = {
|
||||
full_name: patientData.name,
|
||||
cpf: patientData.cpf,
|
||||
birth_date: patientData.birthDate,
|
||||
phone_mobile: patientData.phone,
|
||||
cep: patientData.cep,
|
||||
street: patientData.street,
|
||||
number: patientData.number,
|
||||
city: patientData.city,
|
||||
};
|
||||
await patientsService.update(user.id, patientPayload);
|
||||
toast({
|
||||
title: "Sucesso!",
|
||||
description: "Seus dados foram atualizados.",
|
||||
});
|
||||
setIsEditing(false);
|
||||
} catch (error) {
|
||||
console.error("Erro ao salvar dados:", error);
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: "Não foi possível salvar suas alterações.",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAvatarClick = () => {
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
|
||||
const handleAvatarUpload = async (
|
||||
event: React.ChangeEvent<HTMLInputElement>
|
||||
) => {
|
||||
const file = event.target.files?.[0];
|
||||
if (!file || !user) return;
|
||||
|
||||
const fileExt = file.name.split(".").pop();
|
||||
|
||||
// *** A CORREÇÃO ESTÁ AQUI ***
|
||||
// O caminho salvo no banco de dados não deve conter o nome do bucket.
|
||||
const filePath = `${user.id}/avatar.${fileExt}`;
|
||||
|
||||
try {
|
||||
await api.storage.upload("avatars", filePath, file);
|
||||
await api.patch(`/rest/v1/profiles?id=eq.${user.id}`, {
|
||||
avatar_url: filePath,
|
||||
});
|
||||
|
||||
const newFullUrl = `https://yuanqfswhberkoevtmfr.supabase.co/storage/v1/object/public/avatars/${filePath}?t=${new Date().getTime()}`;
|
||||
setPatientData((prev) =>
|
||||
prev ? { ...prev, avatarFullUrl: newFullUrl } : null
|
||||
);
|
||||
|
||||
toast({
|
||||
title: "Sucesso!",
|
||||
description: "Sua foto de perfil foi atualizada.",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Erro no upload do avatar:", error);
|
||||
toast({
|
||||
title: "Erro de Upload",
|
||||
description: "Não foi possível enviar sua foto.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (isAuthLoading || !patientData) {
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">Meus Dados</h1>
|
||||
<p className="text-gray-600">Gerencie suas informações pessoais</p>
|
||||
</div>
|
||||
<Button onClick={() => (isEditing ? handleSave() : setIsEditing(true))} disabled={isSaving}>
|
||||
{isEditing ? (isSaving ? "Salvando..." : "Salvar Alterações") : "Editar Dados"}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid lg:grid-cols-3 gap-6">
|
||||
<div className="lg:col-span-2 space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center">
|
||||
<User className="mr-2 h-5 w-5" />
|
||||
Informações Pessoais
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="name">Nome Completo</Label>
|
||||
<Input id="name" value={patientData.name} onChange={(e) => handleInputChange("name", e.target.value)} disabled={!isEditing} />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="cpf">CPF</Label>
|
||||
<Input id="cpf" value={patientData.cpf} onChange={(e) => handleInputChange("cpf", e.target.value)} disabled={!isEditing} />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="birthDate">Data de Nascimento</Label>
|
||||
<Input id="birthDate" type="date" value={patientData.birthDate} onChange={(e) => handleInputChange("birthDate", e.target.value)} disabled={!isEditing} />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center">
|
||||
<Mail className="mr-2 h-5 w-5" />
|
||||
Contato e Endereço
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<Input id="email" type="email" value={patientData.email} disabled />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="phone">Telefone</Label>
|
||||
<Input id="phone" value={patientData.phone} onChange={(e) => handleInputChange("phone", e.target.value)} disabled={!isEditing} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="cep">CEP</Label>
|
||||
<Input id="cep" value={patientData.cep} onChange={(e) => handleInputChange("cep", e.target.value)} disabled={!isEditing} />
|
||||
</div>
|
||||
<div className="md:col-span-2">
|
||||
<Label htmlFor="street">Rua / Logradouro</Label>
|
||||
<Input id="street" value={patientData.street} onChange={(e) => handleInputChange("street", e.target.value)} disabled={!isEditing} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="number">Número</Label>
|
||||
<Input id="number" value={patientData.number} onChange={(e) => handleInputChange("number", e.target.value)} disabled={!isEditing} />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="city">Cidade</Label>
|
||||
<Input id="city" value={patientData.city} onChange={(e) => handleInputChange("city", e.target.value)} disabled={!isEditing} />
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Resumo do Perfil</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="relative">
|
||||
<Avatar className="w-16 h-16 cursor-pointer" onClick={handleAvatarClick}>
|
||||
<AvatarImage src={patientData.avatarFullUrl} />
|
||||
<AvatarFallback className="text-2xl">
|
||||
{patientData.name
|
||||
.split(" ")
|
||||
.map((n) => n[0])
|
||||
.join("")}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="absolute bottom-0 right-0 bg-primary text-primary-foreground rounded-full p-1 cursor-pointer hover:bg-primary/80" onClick={handleAvatarClick}>
|
||||
<Upload className="w-3 h-3" />
|
||||
</div>
|
||||
<input type="file" ref={fileInputRef} onChange={handleAvatarUpload} className="hidden" accept="image/png, image/jpeg" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">{patientData.name}</p>
|
||||
<p className="text-sm text-gray-500">Paciente</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-3 pt-4 border-t">
|
||||
<div className="flex items-center text-sm">
|
||||
<Mail className="mr-2 h-4 w-4 text-gray-500" />
|
||||
<span className="truncate">{patientData.email}</span>
|
||||
</div>
|
||||
<div className="flex items-center text-sm">
|
||||
<Phone className="mr-2 h-4 w-4 text-gray-500" />
|
||||
<span>{patientData.phone || "Não informado"}</span>
|
||||
</div>
|
||||
<div className="flex items-center text-sm">
|
||||
<Calendar className="mr-2 h-4 w-4 text-gray-500" />
|
||||
<span>{patientData.birthDate ? new Date(patientData.birthDate).toLocaleDateString("pt-BR", { timeZone: "UTC" }) : "Não informado"}</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Sidebar>
|
||||
<Sidebar>
|
||||
<div>Carregando seus dados...</div>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">Meus Dados</h1>
|
||||
<p className="text-gray-600">Gerencie suas informações pessoais</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => (isEditing ? handleSave() : setIsEditing(true))}
|
||||
disabled={isSaving}
|
||||
className="bg-blue-600 hover:bg-blue-700 text-white"
|
||||
>
|
||||
{isEditing
|
||||
? isSaving
|
||||
? "Salvando..."
|
||||
: "Salvar Alterações"
|
||||
: "Editar Dados"}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid lg:grid-cols-3 gap-6">
|
||||
<div className="lg:col-span-2 space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center">
|
||||
<User className="mr-2 h-5 w-5" />
|
||||
Informações Pessoais
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="name">Nome Completo</Label>
|
||||
<Input
|
||||
id="name"
|
||||
value={patientData.name}
|
||||
onChange={(e) =>
|
||||
handleInputChange("name", e.target.value)
|
||||
}
|
||||
disabled={!isEditing}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="cpf">CPF</Label>
|
||||
<Input
|
||||
id="cpf"
|
||||
value={patientData.cpf}
|
||||
onChange={(e) => handleInputChange("cpf", e.target.value)}
|
||||
disabled={!isEditing}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="birthDate">Data de Nascimento</Label>
|
||||
<Input
|
||||
id="birthDate"
|
||||
type="date"
|
||||
value={patientData.birthDate}
|
||||
onChange={(e) =>
|
||||
handleInputChange("birthDate", e.target.value)
|
||||
}
|
||||
disabled={!isEditing}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center">
|
||||
<Mail className="mr-2 h-5 w-5" />
|
||||
Contato e Endereço
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={patientData.email}
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="phone">Telefone</Label>
|
||||
<Input
|
||||
id="phone"
|
||||
value={patientData.phone}
|
||||
onChange={(e) =>
|
||||
handleInputChange("phone", e.target.value)
|
||||
}
|
||||
disabled={!isEditing}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="cep">CEP</Label>
|
||||
<Input
|
||||
id="cep"
|
||||
value={patientData.cep}
|
||||
onChange={(e) => handleInputChange("cep", e.target.value)}
|
||||
disabled={!isEditing}
|
||||
/>
|
||||
</div>
|
||||
<div className="md:col-span-2">
|
||||
<Label htmlFor="street">Rua / Logradouro</Label>
|
||||
<Input
|
||||
id="street"
|
||||
value={patientData.street}
|
||||
onChange={(e) =>
|
||||
handleInputChange("street", e.target.value)
|
||||
}
|
||||
disabled={!isEditing}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="number">Número</Label>
|
||||
<Input
|
||||
id="number"
|
||||
value={patientData.number}
|
||||
onChange={(e) =>
|
||||
handleInputChange("number", e.target.value)
|
||||
}
|
||||
disabled={!isEditing}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="city">Cidade</Label>
|
||||
<Input
|
||||
id="city"
|
||||
value={patientData.city}
|
||||
onChange={(e) =>
|
||||
handleInputChange("city", e.target.value)
|
||||
}
|
||||
disabled={!isEditing}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Resumo do Perfil</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="relative">
|
||||
<Avatar
|
||||
className="w-16 h-16 cursor-pointer"
|
||||
onClick={handleAvatarClick}
|
||||
>
|
||||
<AvatarImage src={patientData.avatarFullUrl} />
|
||||
<AvatarFallback className="text-2xl">
|
||||
{patientData.name
|
||||
.split(" ")
|
||||
.map((n) => n[0])
|
||||
.join("")}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div
|
||||
className="absolute bottom-0 right-0 bg-primary text-primary-foreground rounded-full p-1 cursor-pointer hover:bg-primary/80"
|
||||
onClick={handleAvatarClick}
|
||||
>
|
||||
<Upload className="w-3 h-3" />
|
||||
</div>
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
onChange={handleAvatarUpload}
|
||||
className="hidden"
|
||||
accept="image/png, image/jpeg"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">{patientData.name}</p>
|
||||
<p className="text-sm text-gray-500">Paciente</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-3 pt-4 border-t">
|
||||
<div className="flex items-center text-sm">
|
||||
<Mail className="mr-2 h-4 w-4 text-gray-500" />
|
||||
<span className="truncate">{patientData.email}</span>
|
||||
</div>
|
||||
<div className="flex items-center text-sm">
|
||||
<Phone className="mr-2 h-4 w-4 text-gray-500" />
|
||||
<span>{patientData.phone || "Não informado"}</span>
|
||||
</div>
|
||||
<div className="flex items-center text-sm">
|
||||
<Calendar className="mr-2 h-4 w-4 text-gray-500" />
|
||||
<span>
|
||||
{patientData.birthDate
|
||||
? new Date(patientData.birthDate).toLocaleDateString(
|
||||
"pt-BR",
|
||||
{ timeZone: "UTC" }
|
||||
)
|
||||
: "Não informado"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import type React from "react"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import Link from "next/link"
|
||||
@ -9,24 +8,24 @@ import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { Eye, EyeOff, ArrowLeft } from "lucide-react"
|
||||
import { ArrowLeft, Loader2 } from "lucide-react"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { usersService } from "@/services/usersApi.mjs" // Mantém a importação
|
||||
import { isValidCPF } from "@/lib/utils"
|
||||
|
||||
export default function PatientRegister() {
|
||||
const [showPassword, setShowPassword] = useState(false)
|
||||
const [showConfirmPassword, setShowConfirmPassword] = useState(false)
|
||||
// REMOVIDO: Estados para 'showPassword' e 'showConfirmPassword'
|
||||
const [formData, setFormData] = useState({
|
||||
name: "",
|
||||
email: "",
|
||||
password: "",
|
||||
confirmPassword: "",
|
||||
phone: "",
|
||||
cpf: "",
|
||||
birthDate: "",
|
||||
address: "",
|
||||
// REMOVIDO: Campos 'password' e 'confirmPassword'
|
||||
})
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
|
||||
const handleInputChange = (field: string, value: string) => {
|
||||
setFormData((prev) => ({
|
||||
@ -37,22 +36,52 @@ export default function PatientRegister() {
|
||||
|
||||
const handleRegister = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setIsLoading(true)
|
||||
|
||||
if (formData.password !== formData.confirmPassword) {
|
||||
alert("As senhas não coincidem!")
|
||||
// --- VALIDAÇÃO DE CPF ---
|
||||
if (!isValidCPF(formData.cpf)) {
|
||||
toast({
|
||||
title: "CPF Inválido",
|
||||
description: "O CPF informado não é válido. Verifique os dígitos.",
|
||||
variant: "destructive",
|
||||
})
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
setIsLoading(true)
|
||||
// --- LÓGICA DE REGISTRO COM ENDPOINT PÚBLICO ---
|
||||
try {
|
||||
// ALTERADO: Payload ajustado para o endpoint 'register-patient'
|
||||
const payload = {
|
||||
email: formData.email.trim().toLowerCase(),
|
||||
full_name: formData.name,
|
||||
phone_mobile: formData.phone, // O endpoint espera 'phone_mobile'
|
||||
cpf: formData.cpf.replace(/\D/g, ''),
|
||||
birth_date: formData.birthDate,
|
||||
}
|
||||
|
||||
// Simulação de registro - em produção, conectar com API real
|
||||
setTimeout(() => {
|
||||
// Salvar dados do usuário no localStorage para simulação
|
||||
const { confirmPassword, ...userData } = formData
|
||||
localStorage.setItem("patientData", JSON.stringify(userData))
|
||||
router.push("/patient/dashboard")
|
||||
// ALTERADO: Chamada para a nova função de serviço
|
||||
await usersService.registerPatient(payload)
|
||||
|
||||
// ALTERADO: Mensagem de sucesso para refletir o fluxo de confirmação por e-mail
|
||||
toast({
|
||||
title: "Cadastro enviado com sucesso!",
|
||||
description: "Enviamos um link de confirmação para o seu e-mail. Por favor, verifique sua caixa de entrada para ativar sua conta.",
|
||||
})
|
||||
|
||||
// Redireciona para a página de login
|
||||
router.push("/login")
|
||||
|
||||
} catch (error: any) {
|
||||
console.error("Erro no registro:", error)
|
||||
toast({
|
||||
title: "Erro ao Criar Conta",
|
||||
description: error.message || "Não foi possível concluir o cadastro. Verifique seus dados e tente novamente.",
|
||||
variant: "destructive",
|
||||
})
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}, 1000)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
@ -67,136 +96,85 @@ export default function PatientRegister() {
|
||||
|
||||
<Card>
|
||||
<CardHeader className="text-center">
|
||||
<CardTitle className="text-2xl">Cadastro de Paciente</CardTitle>
|
||||
<CardDescription>Preencha seus dados para criar sua conta</CardDescription>
|
||||
<CardTitle className="text-2xl">Crie sua Conta de Paciente</CardTitle>
|
||||
<CardDescription>Preencha seus dados para acessar o portal MedConnect</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleRegister} className="space-y-4">
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">Nome Completo</Label>
|
||||
<Label htmlFor="name">Nome Completo *</Label>
|
||||
<Input
|
||||
id="name"
|
||||
value={formData.name}
|
||||
onChange={(e) => handleInputChange("name", e.target.value)}
|
||||
required
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="cpf">CPF</Label>
|
||||
<Label htmlFor="cpf">CPF *</Label>
|
||||
<Input
|
||||
id="cpf"
|
||||
value={formData.cpf}
|
||||
onChange={(e) => handleInputChange("cpf", e.target.value)}
|
||||
placeholder="000.000.000-00"
|
||||
required
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<Label htmlFor="email">Email *</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={formData.email}
|
||||
onChange={(e) => handleInputChange("email", e.target.value)}
|
||||
required
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="phone">Telefone</Label>
|
||||
<Label htmlFor="phone">Telefone *</Label>
|
||||
<Input
|
||||
id="phone"
|
||||
value={formData.phone}
|
||||
onChange={(e) => handleInputChange("phone", e.target.value)}
|
||||
placeholder="(11) 99999-9999"
|
||||
required
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="birthDate">Data de Nascimento</Label>
|
||||
<Label htmlFor="birthDate">Data de Nascimento *</Label>
|
||||
<Input
|
||||
id="birthDate"
|
||||
type="date"
|
||||
value={formData.birthDate}
|
||||
onChange={(e) => handleInputChange("birthDate", e.target.value)}
|
||||
required
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="address">Endereço</Label>
|
||||
<Textarea
|
||||
id="address"
|
||||
value={formData.address}
|
||||
onChange={(e) => handleInputChange("address", e.target.value)}
|
||||
placeholder="Rua, número, bairro, cidade, estado"
|
||||
rows={3}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Senha</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="password"
|
||||
type={showPassword ? "text" : "password"}
|
||||
value={formData.password}
|
||||
onChange={(e) => handleInputChange("password", e.target.value)}
|
||||
required
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
>
|
||||
{showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="confirmPassword">Confirmar Senha</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="confirmPassword"
|
||||
type={showConfirmPassword ? "text" : "password"}
|
||||
value={formData.confirmPassword}
|
||||
onChange={(e) => handleInputChange("confirmPassword", e.target.value)}
|
||||
required
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
|
||||
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
|
||||
>
|
||||
{showConfirmPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/* REMOVIDO: Seção de senha e confirmação de senha */}
|
||||
|
||||
<Button type="submit" className="w-full" disabled={isLoading}>
|
||||
{isLoading ? "Criando conta..." : "Criar Conta"}
|
||||
{isLoading ? <><Loader2 className="mr-2 h-4 w-4 animate-spin" /> Criando conta...</> : "Criar Conta"}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<div className="mt-6 text-center">
|
||||
<p className="text-sm text-gray-600">
|
||||
Já tem uma conta?{" "}
|
||||
<Link href="/patient/login" className="text-blue-600 hover:underline">
|
||||
<Link href="/login" className="text-blue-600 hover:underline">
|
||||
Faça login aqui
|
||||
</Link>
|
||||
</p>
|
||||
@ -206,4 +184,4 @@ export default function PatientRegister() {
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
@ -1,11 +1,25 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Dialog } from "@/components/ui/dialog";
|
||||
import { Calendar, Clock, MapPin, Phone, User, Trash2, Pencil } from "lucide-react";
|
||||
import {
|
||||
Calendar,
|
||||
Clock,
|
||||
MapPin,
|
||||
Phone,
|
||||
User,
|
||||
Trash2,
|
||||
Pencil,
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import Link from "next/link";
|
||||
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
||||
@ -14,214 +28,298 @@ import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||
import Sidebar from "@/components/Sidebar";
|
||||
|
||||
export default function SecretaryAppointments() {
|
||||
const [appointments, setAppointments] = useState<any[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [selectedAppointment, setSelectedAppointment] = useState<any>(null);
|
||||
const [appointments, setAppointments] = useState<any[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [selectedAppointment, setSelectedAppointment] = useState<any>(null);
|
||||
|
||||
// Estados dos Modais
|
||||
const [deleteModal, setDeleteModal] = useState(false);
|
||||
const [editModal, setEditModal] = useState(false);
|
||||
// Estados dos Modais
|
||||
const [deleteModal, setDeleteModal] = useState(false);
|
||||
const [editModal, setEditModal] = useState(false);
|
||||
|
||||
// Estado para o formulário de edição
|
||||
const [editFormData, setEditFormData] = useState({
|
||||
date: "",
|
||||
time: "",
|
||||
status: "",
|
||||
// Estado para o formulário de edição
|
||||
const [editFormData, setEditFormData] = useState({
|
||||
date: "",
|
||||
time: "",
|
||||
status: "",
|
||||
});
|
||||
|
||||
const fetchData = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
// 1. DEFINIR O PARÂMETRO DE ORDENAÇÃO
|
||||
// 'scheduled_at.desc' ordena pela data do agendamento, em ordem descendente (mais recentes primeiro).
|
||||
const queryParams = "order=scheduled_at.desc";
|
||||
|
||||
const [appointmentList, patientList, doctorList] = await Promise.all([
|
||||
// 2. USAR A FUNÇÃO DE BUSCA COM O PARÂMETRO DE ORDENAÇÃO
|
||||
appointmentsService.search_appointment(queryParams),
|
||||
patientsService.list(),
|
||||
doctorsService.list(),
|
||||
]);
|
||||
|
||||
const patientMap = new Map(patientList.map((p: any) => [p.id, p]));
|
||||
const doctorMap = new Map(doctorList.map((d: any) => [d.id, d]));
|
||||
|
||||
const enrichedAppointments = appointmentList.map((apt: any) => ({
|
||||
...apt,
|
||||
patient: patientMap.get(apt.patient_id) || {
|
||||
full_name: "Paciente não encontrado",
|
||||
},
|
||||
doctor: doctorMap.get(apt.doctor_id) || {
|
||||
full_name: "Médico não encontrado",
|
||||
specialty: "N/A",
|
||||
},
|
||||
}));
|
||||
|
||||
setAppointments(enrichedAppointments);
|
||||
} catch (error) {
|
||||
console.error("Falha ao buscar agendamentos:", error);
|
||||
toast.error("Não foi possível carregar a lista de agendamentos.");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, []); // Array vazio garante que a busca ocorra apenas uma vez, no carregamento da página.
|
||||
|
||||
// --- LÓGICA DE EDIÇÃO ---
|
||||
const handleEdit = (appointment: any) => {
|
||||
setSelectedAppointment(appointment);
|
||||
const appointmentDate = new Date(appointment.scheduled_at);
|
||||
|
||||
setEditFormData({
|
||||
date: appointmentDate.toISOString().split("T")[0],
|
||||
time: appointmentDate.toLocaleTimeString("pt-BR", {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
timeZone: "UTC",
|
||||
}),
|
||||
status: appointment.status,
|
||||
});
|
||||
setEditModal(true);
|
||||
};
|
||||
|
||||
const fetchData = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
// 1. DEFINIR O PARÂMETRO DE ORDENAÇÃO
|
||||
// 'scheduled_at.desc' ordena pela data do agendamento, em ordem descendente (mais recentes primeiro).
|
||||
const queryParams = 'order=scheduled_at.desc';
|
||||
const confirmEdit = async () => {
|
||||
if (
|
||||
!selectedAppointment ||
|
||||
!editFormData.date ||
|
||||
!editFormData.time ||
|
||||
!editFormData.status
|
||||
) {
|
||||
toast.error("Todos os campos são obrigatórios para a edição.");
|
||||
return;
|
||||
}
|
||||
|
||||
const [appointmentList, patientList, doctorList] = await Promise.all([
|
||||
// 2. USAR A FUNÇÃO DE BUSCA COM O PARÂMETRO DE ORDENAÇÃO
|
||||
appointmentsService.search_appointment(queryParams),
|
||||
patientsService.list(),
|
||||
doctorsService.list(),
|
||||
]);
|
||||
try {
|
||||
const newScheduledAt = new Date(
|
||||
`${editFormData.date}T${editFormData.time}:00Z`
|
||||
).toISOString();
|
||||
const updatePayload = {
|
||||
scheduled_at: newScheduledAt,
|
||||
status: editFormData.status,
|
||||
};
|
||||
|
||||
const patientMap = new Map(patientList.map((p: any) => [p.id, p]));
|
||||
const doctorMap = new Map(doctorList.map((d: any) => [d.id, d]));
|
||||
await appointmentsService.update(selectedAppointment.id, updatePayload);
|
||||
|
||||
const enrichedAppointments = appointmentList.map((apt: any) => ({
|
||||
...apt,
|
||||
patient: patientMap.get(apt.patient_id) || { full_name: "Paciente não encontrado" },
|
||||
doctor: doctorMap.get(apt.doctor_id) || { full_name: "Médico não encontrado", specialty: "N/A" },
|
||||
}));
|
||||
// 3. RECARREGAR OS DADOS APÓS A EDIÇÃO
|
||||
// Isso garante que a lista permaneça ordenada corretamente se a data for alterada.
|
||||
fetchData();
|
||||
|
||||
setAppointments(enrichedAppointments);
|
||||
} catch (error) {
|
||||
console.error("Falha ao buscar agendamentos:", error);
|
||||
toast.error("Não foi possível carregar a lista de agendamentos.");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
setEditModal(false);
|
||||
toast.success("Consulta atualizada com sucesso!");
|
||||
} catch (error) {
|
||||
console.error("Erro ao atualizar consulta:", error);
|
||||
toast.error("Não foi possível atualizar a consulta.");
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, []); // Array vazio garante que a busca ocorra apenas uma vez, no carregamento da página.
|
||||
// --- LÓGICA DE DELEÇÃO ---
|
||||
const handleDelete = (appointment: any) => {
|
||||
setSelectedAppointment(appointment);
|
||||
setDeleteModal(true);
|
||||
};
|
||||
|
||||
// --- LÓGICA DE EDIÇÃO ---
|
||||
const handleEdit = (appointment: any) => {
|
||||
setSelectedAppointment(appointment);
|
||||
const appointmentDate = new Date(appointment.scheduled_at);
|
||||
const confirmDelete = async () => {
|
||||
if (!selectedAppointment) return;
|
||||
try {
|
||||
await appointmentsService.delete(selectedAppointment.id);
|
||||
setAppointments((prev) =>
|
||||
prev.filter((apt) => apt.id !== selectedAppointment.id)
|
||||
);
|
||||
setDeleteModal(false);
|
||||
toast.success("Consulta deletada com sucesso!");
|
||||
} catch (error) {
|
||||
console.error("Erro ao deletar consulta:", error);
|
||||
toast.error("Não foi possível deletar a consulta.");
|
||||
}
|
||||
};
|
||||
|
||||
setEditFormData({
|
||||
date: appointmentDate.toISOString().split('T')[0],
|
||||
time: appointmentDate.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit', timeZone: 'UTC' }),
|
||||
status: appointment.status,
|
||||
});
|
||||
setEditModal(true);
|
||||
};
|
||||
const getStatusBadge = (status: string) => {
|
||||
switch (status) {
|
||||
case "requested":
|
||||
return (
|
||||
<Badge className="bg-yellow-100 text-yellow-800">Solicitada</Badge>
|
||||
);
|
||||
case "confirmed":
|
||||
return <Badge className="bg-blue-100 text-blue-800">Confirmada</Badge>;
|
||||
case "checked_in":
|
||||
return (
|
||||
<Badge className="bg-indigo-100 text-indigo-800">Check-in</Badge>
|
||||
);
|
||||
case "completed":
|
||||
return <Badge className="bg-green-100 text-green-800">Realizada</Badge>;
|
||||
case "cancelled":
|
||||
return <Badge className="bg-red-100 text-red-800">Cancelada</Badge>;
|
||||
case "no_show":
|
||||
return (
|
||||
<Badge className="bg-gray-100 text-gray-800">Não Compareceu</Badge>
|
||||
);
|
||||
default:
|
||||
return <Badge variant="secondary">{status}</Badge>;
|
||||
}
|
||||
};
|
||||
|
||||
const confirmEdit = async () => {
|
||||
if (!selectedAppointment || !editFormData.date || !editFormData.time || !editFormData.status) {
|
||||
toast.error("Todos os campos são obrigatórios para a edição.");
|
||||
return;
|
||||
}
|
||||
const timeSlots = [
|
||||
"08:00",
|
||||
"08:30",
|
||||
"09:00",
|
||||
"09:30",
|
||||
"10:00",
|
||||
"10:30",
|
||||
"11:00",
|
||||
"11:30",
|
||||
"14:00",
|
||||
"14:30",
|
||||
"15:00",
|
||||
"15:30",
|
||||
"16:00",
|
||||
"16:30",
|
||||
"17:00",
|
||||
"17:30",
|
||||
];
|
||||
const appointmentStatuses = [
|
||||
"requested",
|
||||
"confirmed",
|
||||
"checked_in",
|
||||
"completed",
|
||||
"cancelled",
|
||||
"no_show",
|
||||
];
|
||||
|
||||
try {
|
||||
const newScheduledAt = new Date(`${editFormData.date}T${editFormData.time}:00Z`).toISOString();
|
||||
const updatePayload = {
|
||||
scheduled_at: newScheduledAt,
|
||||
status: editFormData.status,
|
||||
};
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">
|
||||
Consultas Agendadas
|
||||
</h1>
|
||||
<p className="text-gray-600">Gerencie as consultas dos pacientes</p>
|
||||
</div>
|
||||
<Link href="/secretary/schedule">
|
||||
<Button className="bg-blue-600 hover:bg-blue-700 text-white">
|
||||
<Calendar className="mr-2 h-4 w-4 text-white" />
|
||||
Agendar Nova Consulta
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
await appointmentsService.update(selectedAppointment.id, updatePayload);
|
||||
|
||||
// 3. RECARREGAR OS DADOS APÓS A EDIÇÃO
|
||||
// Isso garante que a lista permaneça ordenada corretamente se a data for alterada.
|
||||
fetchData();
|
||||
|
||||
setEditModal(false);
|
||||
toast.success("Consulta atualizada com sucesso!");
|
||||
|
||||
} catch (error) {
|
||||
console.error("Erro ao atualizar consulta:", error);
|
||||
toast.error("Não foi possível atualizar a consulta.");
|
||||
}
|
||||
};
|
||||
|
||||
// --- LÓGICA DE DELEÇÃO ---
|
||||
const handleDelete = (appointment: any) => {
|
||||
setSelectedAppointment(appointment);
|
||||
setDeleteModal(true);
|
||||
};
|
||||
|
||||
const confirmDelete = async () => {
|
||||
if (!selectedAppointment) return;
|
||||
try {
|
||||
await appointmentsService.delete(selectedAppointment.id);
|
||||
setAppointments((prev) => prev.filter((apt) => apt.id !== selectedAppointment.id));
|
||||
setDeleteModal(false);
|
||||
toast.success("Consulta deletada com sucesso!");
|
||||
} catch (error) {
|
||||
console.error("Erro ao deletar consulta:", error);
|
||||
toast.error("Não foi possível deletar a consulta.");
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusBadge = (status: string) => {
|
||||
switch (status) {
|
||||
case "requested": return <Badge className="bg-yellow-100 text-yellow-800">Solicitada</Badge>;
|
||||
case "confirmed": return <Badge className="bg-blue-100 text-blue-800">Confirmada</Badge>;
|
||||
case "checked_in": return <Badge className="bg-indigo-100 text-indigo-800">Check-in</Badge>;
|
||||
case "completed": return <Badge className="bg-green-100 text-green-800">Realizada</Badge>;
|
||||
case "cancelled": return <Badge className="bg-red-100 text-red-800">Cancelada</Badge>;
|
||||
case "no_show": return <Badge className="bg-gray-100 text-gray-800">Não Compareceu</Badge>;
|
||||
default: return <Badge variant="secondary">{status}</Badge>;
|
||||
}
|
||||
};
|
||||
|
||||
const timeSlots = ["08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30"];
|
||||
const appointmentStatuses = ["requested", "confirmed", "checked_in", "completed", "cancelled", "no_show"];
|
||||
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="grid gap-6">
|
||||
{isLoading ? (
|
||||
<p>Carregando consultas...</p>
|
||||
) : appointments.length > 0 ? (
|
||||
appointments.map((appointment) => (
|
||||
<Card key={appointment.id}>
|
||||
<CardHeader>
|
||||
<div className="flex justify-between items-start">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">Consultas Agendadas</h1>
|
||||
<p className="text-gray-600">Gerencie as consultas dos pacientes</p>
|
||||
<CardTitle className="text-lg">
|
||||
{appointment.doctor.full_name}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{appointment.doctor.specialty}
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Link href="/secretary/schedule">
|
||||
<Button><Calendar className="mr-2 h-4 w-4" /> Agendar Nova Consulta</Button>
|
||||
</Link>
|
||||
</div>
|
||||
{getStatusBadge(appointment.status)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center text-sm text-gray-800 font-medium">
|
||||
<User className="mr-2 h-4 w-4 text-gray-600" />
|
||||
{appointment.patient.full_name}
|
||||
</div>
|
||||
<div className="flex items-center text-sm text-gray-600">
|
||||
<Calendar className="mr-2 h-4 w-4" />
|
||||
{new Date(appointment.scheduled_at).toLocaleDateString(
|
||||
"pt-BR",
|
||||
{ timeZone: "UTC" }
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center text-sm text-gray-600">
|
||||
<Clock className="mr-2 h-4 w-4" />
|
||||
{new Date(appointment.scheduled_at).toLocaleTimeString(
|
||||
"pt-BR",
|
||||
{
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
timeZone: "UTC",
|
||||
}
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center text-sm text-gray-600">
|
||||
<MapPin className="mr-2 h-4 w-4" />
|
||||
{appointment.doctor.location || "Local a definir"}
|
||||
</div>
|
||||
<div className="flex items-center text-sm text-gray-600">
|
||||
<Phone className="mr-2 h-4 w-4" />
|
||||
{appointment.doctor.phone || "N/A"}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6">
|
||||
{isLoading ? <p>Carregando consultas...</p> : appointments.length > 0 ? (
|
||||
appointments.map((appointment) => (
|
||||
<Card key={appointment.id}>
|
||||
<CardHeader>
|
||||
<div className="flex justify-between items-start">
|
||||
<div>
|
||||
<CardTitle className="text-lg">{appointment.doctor.full_name}</CardTitle>
|
||||
<CardDescription>{appointment.doctor.specialty}</CardDescription>
|
||||
</div>
|
||||
{getStatusBadge(appointment.status)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center text-sm text-gray-800 font-medium">
|
||||
<User className="mr-2 h-4 w-4 text-gray-600" />
|
||||
{appointment.patient.full_name}
|
||||
</div>
|
||||
<div className="flex items-center text-sm text-gray-600">
|
||||
<Calendar className="mr-2 h-4 w-4" />
|
||||
{new Date(appointment.scheduled_at).toLocaleDateString("pt-BR", { timeZone: "UTC" })}
|
||||
</div>
|
||||
<div className="flex items-center text-sm text-gray-600">
|
||||
<Clock className="mr-2 h-4 w-4" />
|
||||
{new Date(appointment.scheduled_at).toLocaleTimeString("pt-BR", { hour: '2-digit', minute: '2-digit', timeZone: "UTC" })}
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center text-sm text-gray-600">
|
||||
<MapPin className="mr-2 h-4 w-4" />
|
||||
{appointment.doctor.location || "Local a definir"}
|
||||
</div>
|
||||
<div className="flex items-center text-sm text-gray-600">
|
||||
<Phone className="mr-2 h-4 w-4" />
|
||||
{appointment.doctor.phone || "N/A"}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2 mt-4 pt-4 border-t">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleEdit(appointment)}
|
||||
>
|
||||
<Pencil className="mr-2 h-4 w-4" />
|
||||
Editar
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-red-600 hover:text-red-700 hover:bg-red-50 bg-transparent"
|
||||
onClick={() => handleDelete(appointment)}
|
||||
>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Deletar
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))
|
||||
) : (
|
||||
<p>Nenhuma consulta encontrada.</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 mt-4 pt-4 border-t">
|
||||
<Button variant="outline" size="sm" onClick={() => handleEdit(appointment)}>
|
||||
<Pencil className="mr-2 h-4 w-4" />
|
||||
Editar
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" className="text-red-600 hover:text-red-700 hover:bg-red-50 bg-transparent" onClick={() => handleDelete(appointment)}>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Deletar
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))
|
||||
) : (
|
||||
<p>Nenhuma consulta encontrada.</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{/* MODAL DE EDIÇÃO */}
|
||||
<Dialog open={editModal} onOpenChange={setEditModal}>
|
||||
{/* ... (código do modal de edição) ... */}
|
||||
</Dialog>
|
||||
|
||||
{/* MODAL DE EDIÇÃO */}
|
||||
<Dialog open={editModal} onOpenChange={setEditModal}>
|
||||
{/* ... (código do modal de edição) ... */}
|
||||
</Dialog>
|
||||
|
||||
{/* Modal de Deleção */}
|
||||
<Dialog open={deleteModal} onOpenChange={setDeleteModal}>
|
||||
{/* ... (código do modal de deleção) ... */}
|
||||
</Dialog>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
{/* Modal de Deleção */}
|
||||
<Dialog open={deleteModal} onOpenChange={setDeleteModal}>
|
||||
{/* ... (código do modal de deleção) ... */}
|
||||
</Dialog>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,8 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import { Card, CardContent, CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Calendar, Clock, User, Plus } from "lucide-react";
|
||||
@ -13,289 +16,290 @@ import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
||||
import Sidebar from "@/components/Sidebar";
|
||||
|
||||
export default function SecretaryDashboard() {
|
||||
// Estados
|
||||
const [patients, setPatients] = useState<any[]>([]);
|
||||
const [loadingPatients, setLoadingPatients] = useState(true);
|
||||
// Estados
|
||||
const [patients, setPatients] = useState<any[]>([]);
|
||||
const [loadingPatients, setLoadingPatients] = useState(true);
|
||||
|
||||
const [firstConfirmed, setFirstConfirmed] = useState<any>(null);
|
||||
const [nextAgendada, setNextAgendada] = useState<any>(null);
|
||||
const [loadingAppointments, setLoadingAppointments] = useState(true);
|
||||
const [firstConfirmed, setFirstConfirmed] = useState<any>(null);
|
||||
const [nextAgendada, setNextAgendada] = useState<any>(null);
|
||||
const [loadingAppointments, setLoadingAppointments] = useState(true);
|
||||
|
||||
// 🔹 Buscar pacientes
|
||||
useEffect(() => {
|
||||
async function fetchPatients() {
|
||||
try {
|
||||
const data = await patientsService.list();
|
||||
if (Array.isArray(data)) {
|
||||
setPatients(data.slice(0, 3));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Erro ao carregar pacientes:", error);
|
||||
} finally {
|
||||
setLoadingPatients(false);
|
||||
}
|
||||
// 🔹 Buscar pacientes
|
||||
useEffect(() => {
|
||||
async function fetchPatients() {
|
||||
try {
|
||||
const data = await patientsService.list();
|
||||
if (Array.isArray(data)) {
|
||||
setPatients(data.slice(0, 3));
|
||||
}
|
||||
fetchPatients();
|
||||
}, []);
|
||||
} catch (error) {
|
||||
console.error("Erro ao carregar pacientes:", error);
|
||||
} finally {
|
||||
setLoadingPatients(false);
|
||||
}
|
||||
}
|
||||
fetchPatients();
|
||||
}, []);
|
||||
|
||||
// 🔹 Buscar consultas (confirmadas + 1ª do mês)
|
||||
useEffect(() => {
|
||||
async function fetchAppointments() {
|
||||
try {
|
||||
const hoje = new Date();
|
||||
const inicioMes = new Date(hoje.getFullYear(), hoje.getMonth(), 1);
|
||||
const fimMes = new Date(hoje.getFullYear(), hoje.getMonth() + 1, 0);
|
||||
// 🔹 Buscar consultas (confirmadas + 1ª do mês)
|
||||
useEffect(() => {
|
||||
async function fetchAppointments() {
|
||||
try {
|
||||
const hoje = new Date();
|
||||
const inicioMes = new Date(hoje.getFullYear(), hoje.getMonth(), 1);
|
||||
const fimMes = new Date(hoje.getFullYear(), hoje.getMonth() + 1, 0);
|
||||
|
||||
// Mesmo parâmetro de ordenação da página /secretary/appointments
|
||||
const queryParams = "order=scheduled_at.desc";
|
||||
const data = await appointmentsService.search_appointment(queryParams);
|
||||
// Mesmo parâmetro de ordenação da página /secretary/appointments
|
||||
const queryParams = "order=scheduled_at.desc";
|
||||
const data = await appointmentsService.search_appointment(queryParams);
|
||||
|
||||
if (!Array.isArray(data) || data.length === 0) {
|
||||
setFirstConfirmed(null);
|
||||
setNextAgendada(null);
|
||||
return;
|
||||
}
|
||||
|
||||
// 🩵 1️⃣ Consultas confirmadas (para o card “Próxima Consulta Confirmada”)
|
||||
const confirmadas = data.filter((apt: any) => {
|
||||
const dataConsulta = new Date(apt.scheduled_at || apt.date);
|
||||
return apt.status === "confirmed" && dataConsulta >= hoje;
|
||||
});
|
||||
|
||||
confirmadas.sort(
|
||||
(a: any, b: any) =>
|
||||
new Date(a.scheduled_at || a.date).getTime() -
|
||||
new Date(b.scheduled_at || b.date).getTime()
|
||||
);
|
||||
|
||||
setFirstConfirmed(confirmadas[0] || null);
|
||||
|
||||
// 💙 2️⃣ Consultas deste mês — pegar sempre a 1ª (mais próxima)
|
||||
const consultasMes = data.filter((apt: any) => {
|
||||
const dataConsulta = new Date(apt.scheduled_at);
|
||||
return dataConsulta >= inicioMes && dataConsulta <= fimMes;
|
||||
});
|
||||
|
||||
if (consultasMes.length > 0) {
|
||||
consultasMes.sort(
|
||||
(a: any, b: any) =>
|
||||
new Date(a.scheduled_at).getTime() -
|
||||
new Date(b.scheduled_at).getTime()
|
||||
);
|
||||
setNextAgendada(consultasMes[0]);
|
||||
} else {
|
||||
setNextAgendada(null);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Erro ao carregar consultas:", error);
|
||||
} finally {
|
||||
setLoadingAppointments(false);
|
||||
}
|
||||
if (!Array.isArray(data) || data.length === 0) {
|
||||
setFirstConfirmed(null);
|
||||
setNextAgendada(null);
|
||||
return;
|
||||
}
|
||||
|
||||
fetchAppointments();
|
||||
}, []);
|
||||
// 🩵 1️⃣ Consultas confirmadas (para o card “Próxima Consulta Confirmada”)
|
||||
const confirmadas = data.filter((apt: any) => {
|
||||
const dataConsulta = new Date(apt.scheduled_at || apt.date);
|
||||
return apt.status === "confirmed" && dataConsulta >= hoje;
|
||||
});
|
||||
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="space-y-6">
|
||||
{/* Cabeçalho */}
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
|
||||
<p className="text-gray-600">Bem-vindo ao seu portal de consultas médicas</p>
|
||||
confirmadas.sort(
|
||||
(a: any, b: any) =>
|
||||
new Date(a.scheduled_at || a.date).getTime() -
|
||||
new Date(b.scheduled_at || b.date).getTime()
|
||||
);
|
||||
|
||||
setFirstConfirmed(confirmadas[0] || null);
|
||||
|
||||
// 💙 2️⃣ Consultas deste mês — pegar sempre a 1ª (mais próxima)
|
||||
const consultasMes = data.filter((apt: any) => {
|
||||
const dataConsulta = new Date(apt.scheduled_at);
|
||||
return dataConsulta >= inicioMes && dataConsulta <= fimMes;
|
||||
});
|
||||
|
||||
if (consultasMes.length > 0) {
|
||||
consultasMes.sort(
|
||||
(a: any, b: any) =>
|
||||
new Date(a.scheduled_at).getTime() -
|
||||
new Date(b.scheduled_at).getTime()
|
||||
);
|
||||
setNextAgendada(consultasMes[0]);
|
||||
} else {
|
||||
setNextAgendada(null);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Erro ao carregar consultas:", error);
|
||||
} finally {
|
||||
setLoadingAppointments(false);
|
||||
}
|
||||
}
|
||||
|
||||
fetchAppointments();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Sidebar>
|
||||
<div className="space-y-6">
|
||||
{/* Cabeçalho */}
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
|
||||
<p className="text-gray-600">
|
||||
Bem-vindo ao seu portal de consultas médicas
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Cards principais */}
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{/* Próxima Consulta Confirmada */}
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">
|
||||
Próxima Consulta Confirmada
|
||||
</CardTitle>
|
||||
<Calendar className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{loadingAppointments ? (
|
||||
<div className="text-gray-500 text-sm">
|
||||
Carregando próxima consulta...
|
||||
</div>
|
||||
|
||||
{/* Cards principais */}
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{/* Próxima Consulta Confirmada */}
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">
|
||||
Próxima Consulta Confirmada
|
||||
</CardTitle>
|
||||
<Calendar className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{loadingAppointments ? (
|
||||
<div className="text-gray-500 text-sm">
|
||||
Carregando próxima consulta...
|
||||
</div>
|
||||
) : firstConfirmed ? (
|
||||
<>
|
||||
<div className="text-2xl font-bold">
|
||||
{new Date(
|
||||
firstConfirmed.scheduled_at || firstConfirmed.date
|
||||
).toLocaleDateString("pt-BR")}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{firstConfirmed.doctor_name
|
||||
? `Dr(a). ${firstConfirmed.doctor_name}`
|
||||
: "Médico não informado"}{" "}
|
||||
-{" "}
|
||||
{new Date(
|
||||
firstConfirmed.scheduled_at
|
||||
).toLocaleTimeString("pt-BR", {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
})}
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<div className="text-sm text-gray-500">
|
||||
Nenhuma consulta confirmada encontrada
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Consultas Este Mês */}
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">
|
||||
Consultas Este Mês
|
||||
</CardTitle>
|
||||
<Clock className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{loadingAppointments ? (
|
||||
<div className="text-gray-500 text-sm">
|
||||
Carregando consultas...
|
||||
</div>
|
||||
) : nextAgendada ? (
|
||||
<>
|
||||
<div className="text-lg font-bold text-gray-900">
|
||||
{new Date(
|
||||
nextAgendada.scheduled_at
|
||||
).toLocaleDateString("pt-BR", {
|
||||
day: "2-digit",
|
||||
month: "2-digit",
|
||||
year: "numeric",
|
||||
})}{" "}
|
||||
às{" "}
|
||||
{new Date(
|
||||
nextAgendada.scheduled_at
|
||||
).toLocaleTimeString("pt-BR", {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
})}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{nextAgendada.doctor_name
|
||||
? `Dr(a). ${nextAgendada.doctor_name}`
|
||||
: "Médico não informado"}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{nextAgendada.patient_name
|
||||
? `Paciente: ${nextAgendada.patient_name}`
|
||||
: ""}
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<div className="text-sm text-gray-500">
|
||||
Nenhuma consulta agendada neste mês
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Perfil */}
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Perfil</CardTitle>
|
||||
<User className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">100%</div>
|
||||
<p className="text-xs text-muted-foreground">Dados completos</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : firstConfirmed ? (
|
||||
<>
|
||||
<div className="text-2xl font-bold">
|
||||
{new Date(
|
||||
firstConfirmed.scheduled_at || firstConfirmed.date
|
||||
).toLocaleDateString("pt-BR")}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{firstConfirmed.doctor_name
|
||||
? `Dr(a). ${firstConfirmed.doctor_name}`
|
||||
: "Médico não informado"}{" "}
|
||||
-{" "}
|
||||
{new Date(firstConfirmed.scheduled_at).toLocaleTimeString(
|
||||
"pt-BR",
|
||||
{
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
}
|
||||
)}
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<div className="text-sm text-gray-500">
|
||||
Nenhuma consulta confirmada encontrada
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Cards Secundários */}
|
||||
<div className="grid md:grid-cols-2 gap-6">
|
||||
{/* Ações rápidas */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Ações Rápidas</CardTitle>
|
||||
<CardDescription>
|
||||
Acesse rapidamente as principais funcionalidades
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<Link href="/secretary/schedule">
|
||||
<Button className="w-full justify-start">
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Agendar Nova Consulta
|
||||
</Button>
|
||||
</Link>
|
||||
<Link href="/secretary/appointments">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full justify-start bg-transparent"
|
||||
>
|
||||
<Calendar className="mr-2 h-4 w-4" />
|
||||
Ver Consultas
|
||||
</Button>
|
||||
</Link>
|
||||
<Link href="/secretary/pacientes">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full justify-start bg-transparent"
|
||||
>
|
||||
<User className="mr-2 h-4 w-4" />
|
||||
Gerenciar Pacientes
|
||||
</Button>
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Pacientes */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Pacientes</CardTitle>
|
||||
<CardDescription>
|
||||
Últimos pacientes cadastrados
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{loadingPatients ? (
|
||||
<p className="text-sm text-gray-500">
|
||||
Carregando pacientes...
|
||||
</p>
|
||||
) : patients.length === 0 ? (
|
||||
<p className="text-sm text-gray-500">
|
||||
Nenhum paciente cadastrado.
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{patients.map((patient, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-center justify-between p-3 bg-blue-50 rounded-lg border border-blue-100"
|
||||
>
|
||||
<div>
|
||||
<p className="font-medium text-gray-900">
|
||||
{patient.full_name || "Sem nome"}
|
||||
</p>
|
||||
<p className="text-sm text-gray-600">
|
||||
{patient.phone_mobile ||
|
||||
patient.phone1 ||
|
||||
"Sem telefone"}
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="font-medium text-blue-700">
|
||||
{patient.convenio || "Particular"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
{/* Consultas Este Mês */}
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">
|
||||
Consultas Este Mês
|
||||
</CardTitle>
|
||||
<Clock className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{loadingAppointments ? (
|
||||
<div className="text-gray-500 text-sm">
|
||||
Carregando consultas...
|
||||
</div>
|
||||
</div>
|
||||
</Sidebar>
|
||||
);
|
||||
) : nextAgendada ? (
|
||||
<>
|
||||
<div className="text-lg font-bold text-gray-900">
|
||||
{new Date(nextAgendada.scheduled_at).toLocaleDateString(
|
||||
"pt-BR",
|
||||
{
|
||||
day: "2-digit",
|
||||
month: "2-digit",
|
||||
year: "numeric",
|
||||
}
|
||||
)}{" "}
|
||||
às{" "}
|
||||
{new Date(nextAgendada.scheduled_at).toLocaleTimeString(
|
||||
"pt-BR",
|
||||
{
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
}
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{nextAgendada.doctor_name
|
||||
? `Dr(a). ${nextAgendada.doctor_name}`
|
||||
: "Médico não informado"}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{nextAgendada.patient_name
|
||||
? `Paciente: ${nextAgendada.patient_name}`
|
||||
: ""}
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<div className="text-sm text-gray-500">
|
||||
Nenhuma consulta agendada neste mês
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Perfil */}
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Perfil</CardTitle>
|
||||
<User className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">100%</div>
|
||||
<p className="text-xs text-muted-foreground">Dados completos</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Cards Secundários */}
|
||||
<div className="grid md:grid-cols-2 gap-6">
|
||||
{/* Ações rápidas */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Ações Rápidas</CardTitle>
|
||||
<CardDescription>
|
||||
Acesse rapidamente as principais funcionalidades
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<Link href="/secretary/schedule">
|
||||
<Button className="w-full justify-start bg-blue-600 text-white hover:bg-blue-700">
|
||||
<User className="mr-2 h-4 w-4 text-white" />
|
||||
Agendar Nova Consulta
|
||||
</Button>
|
||||
</Link>
|
||||
<Link href="/secretary/appointments">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full justify-start bg-transparent"
|
||||
>
|
||||
<Calendar className="mr-2 h-4 w-4" />
|
||||
Ver Consultas
|
||||
</Button>
|
||||
</Link>
|
||||
<Link href="/secretary/pacientes">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full justify-start bg-transparent"
|
||||
>
|
||||
<User className="mr-2 h-4 w-4" />
|
||||
Gerenciar Pacientes
|
||||
</Button>
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Pacientes */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Pacientes</CardTitle>
|
||||
<CardDescription>Últimos pacientes cadastrados</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{loadingPatients ? (
|
||||
<p className="text-sm text-gray-500">Carregando pacientes...</p>
|
||||
) : patients.length === 0 ? (
|
||||
<p className="text-sm text-gray-500">
|
||||
Nenhum paciente cadastrado.
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{patients.map((patient, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-center justify-between p-3 bg-blue-50 rounded-lg border border-blue-100"
|
||||
>
|
||||
<div>
|
||||
<p className="font-medium text-gray-900">
|
||||
{patient.full_name || "Sem nome"}
|
||||
</p>
|
||||
<p className="text-sm text-gray-600">
|
||||
{patient.phone_mobile ||
|
||||
patient.phone1 ||
|
||||
"Sem telefone"}
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="font-medium text-blue-700">
|
||||
{patient.convenio || "Particular"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -16,138 +16,215 @@ import { Eye, EyeOff, Mail, Lock, Loader2 } from "lucide-react";
|
||||
import { usersService } from "@/services/usersApi.mjs";
|
||||
|
||||
interface LoginFormProps {
|
||||
children?: React.ReactNode;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
interface FormState {
|
||||
email: string;
|
||||
password: string;
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export function LoginForm({ children }: LoginFormProps) {
|
||||
const [form, setForm] = useState<FormState>({ email: "", password: "" });
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const router = useRouter();
|
||||
const { toast } = useToast();
|
||||
const [form, setForm] = useState<FormState>({ email: "", password: "" });
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const router = useRouter();
|
||||
const { toast } = useToast();
|
||||
|
||||
const [userRoles, setUserRoles] = useState<string[]>([]);
|
||||
const [authenticatedUser, setAuthenticatedUser] = useState<any>(null);
|
||||
const [userRoles, setUserRoles] = useState<string[]>([]);
|
||||
const [authenticatedUser, setAuthenticatedUser] = useState<any>(null);
|
||||
|
||||
/**
|
||||
* --- NOVA FUNÇÃO ---
|
||||
* Finaliza o login com o perfil de dashboard escolhido e redireciona.
|
||||
*/
|
||||
const handleRoleSelection = (selectedDashboardRole: string, user: any) => {
|
||||
if (!user) {
|
||||
toast({ title: "Erro de Sessão", description: "Não foi possível encontrar os dados do usuário. Tente novamente.", variant: "destructive" });
|
||||
setUserRoles([]);
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* --- NOVA FUNÇÃO ---
|
||||
* Finaliza o login com o perfil de dashboard escolhido e redireciona.
|
||||
*/
|
||||
const handleRoleSelection = (selectedDashboardRole: string, user: any) => {
|
||||
if (!user) {
|
||||
toast({
|
||||
title: "Erro de Sessão",
|
||||
description:
|
||||
"Não foi possível encontrar os dados do usuário. Tente novamente.",
|
||||
variant: "destructive",
|
||||
});
|
||||
setUserRoles([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const roleInLowerCase = selectedDashboardRole.toLowerCase();
|
||||
console.log("Salvando no localStorage com o perfil:", roleInLowerCase);
|
||||
const roleInLowerCase = selectedDashboardRole.toLowerCase();
|
||||
console.log("Salvando no localStorage com o perfil:", roleInLowerCase);
|
||||
|
||||
const completeUserInfo = { ...user, user_metadata: { ...user.user_metadata, role: roleInLowerCase } };
|
||||
localStorage.setItem("user_info", JSON.stringify(completeUserInfo));
|
||||
|
||||
let redirectPath = "";
|
||||
switch (selectedDashboardRole) {
|
||||
case "gestor": redirectPath = "/manager/dashboard"; break;
|
||||
case "admin": redirectPath = "/manager/dashboard"; break;
|
||||
case "medico": redirectPath = "/doctor/dashboard"; break;
|
||||
case "secretaria": redirectPath = "/secretary/dashboard"; break;
|
||||
case "paciente": redirectPath = "/patient/dashboard"; break;
|
||||
}
|
||||
|
||||
if (redirectPath) {
|
||||
toast({ title: `Entrando como ${selectedDashboardRole}...` });
|
||||
router.push(redirectPath);
|
||||
} else {
|
||||
toast({ title: "Erro", description: "Perfil selecionado inválido.", variant: "destructive" });
|
||||
}
|
||||
const completeUserInfo = {
|
||||
...user,
|
||||
user_metadata: { ...user.user_metadata, role: roleInLowerCase },
|
||||
};
|
||||
localStorage.setItem("user_info", JSON.stringify(completeUserInfo));
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setIsLoading(true);
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("user_info");
|
||||
let redirectPath = "";
|
||||
switch (selectedDashboardRole) {
|
||||
case "gestor":
|
||||
redirectPath = "/manager/dashboard";
|
||||
break;
|
||||
case "admin":
|
||||
redirectPath = "/manager/dashboard";
|
||||
break;
|
||||
case "medico":
|
||||
redirectPath = "/doctor/dashboard";
|
||||
break;
|
||||
case "secretaria":
|
||||
redirectPath = "/secretary/dashboard";
|
||||
break;
|
||||
case "paciente":
|
||||
redirectPath = "/patient/dashboard";
|
||||
break;
|
||||
}
|
||||
|
||||
try {
|
||||
const authData = await login(form.email, form.password);
|
||||
const user = authData.user;
|
||||
if (!user || !user.id) {
|
||||
throw new Error("Resposta de autenticação inválida.");
|
||||
}
|
||||
if (redirectPath) {
|
||||
toast({ title: `Entrando como ${selectedDashboardRole}...` });
|
||||
router.push(redirectPath);
|
||||
} else {
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: "Perfil selecionado inválido.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const rolesData = await api.get(`/rest/v1/user_roles?user_id=eq.${user.id}&select=role`);
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setIsLoading(true);
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("user_info");
|
||||
|
||||
const me = await usersService.getMeSimple()
|
||||
console.log(me.roles)
|
||||
try {
|
||||
const authData = await login(form.email, form.password);
|
||||
const user = authData.user;
|
||||
if (!user || !user.id) {
|
||||
throw new Error("Resposta de autenticação inválida.");
|
||||
}
|
||||
|
||||
if (!me.roles || me.roles.length === 0) {
|
||||
throw new Error("Nenhum perfil de acesso foi encontrado para este usuário.");
|
||||
}
|
||||
const rolesData = await api.get(
|
||||
`/rest/v1/user_roles?user_id=eq.${user.id}&select=role`
|
||||
);
|
||||
|
||||
handleRoleSelection(me.roles[0], user);
|
||||
const me = await usersService.getMeSimple();
|
||||
console.log(me.roles);
|
||||
|
||||
} catch (error) {
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("user_info");
|
||||
toast({
|
||||
title: "Erro no Login",
|
||||
description: error instanceof Error ? error.message : "Ocorreu um erro inesperado.",
|
||||
variant: "destructive",
|
||||
});
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
if (!me.roles || me.roles.length === 0) {
|
||||
throw new Error(
|
||||
"Nenhum perfil de acesso foi encontrado para este usuário."
|
||||
);
|
||||
}
|
||||
|
||||
// Estado para guardar os botões de seleção de perfil
|
||||
const [roleSelectionUI, setRoleSelectionUI] = useState<React.ReactNode | null>(null);
|
||||
handleRoleSelection(me.roles[0], user);
|
||||
} catch (error) {
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("user_info");
|
||||
toast({
|
||||
title: "Erro no Login",
|
||||
description:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Ocorreu um erro inesperado.",
|
||||
variant: "destructive",
|
||||
});
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="w-full bg-transparent border-0 shadow-none">
|
||||
<CardContent className="p-0">
|
||||
{!roleSelectionUI ? (
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">E-mail</Label>
|
||||
<div className="relative">
|
||||
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground w-5 h-5" />
|
||||
<Input id="email" type="email" placeholder="seu.email@exemplo.com" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} className="pl-10 h-11" required disabled={isLoading} autoComplete="username" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Senha</Label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground w-5 h-5" />
|
||||
<Input id="password" type={showPassword ? "text" : "password"} placeholder="Digite sua senha" value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} className="pl-10 pr-12 h-11" required disabled={isLoading} autoComplete="current-password" />
|
||||
<button type="button" onClick={() => setShowPassword(!showPassword)} className="absolute right-2 top-1/2 -translate-y-1/2 h-8 w-8 p-0 text-muted-foreground hover:text-foreground" disabled={isLoading}>
|
||||
{showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<Button type="submit" className="w-full h-11 text-base font-semibold" disabled={isLoading}>
|
||||
{isLoading ? <Loader2 className="w-5 h-5 animate-spin" /> : "Entrar"}
|
||||
</Button>
|
||||
</form>
|
||||
) : (
|
||||
<div className="space-y-4 animate-in fade-in-50">
|
||||
<h3 className="text-lg font-medium text-center text-foreground">Você tem múltiplos perfis</h3>
|
||||
<p className="text-sm text-muted-foreground text-center">Selecione com qual perfil deseja entrar:</p>
|
||||
<div className="flex flex-col space-y-3 pt-2">
|
||||
{userRoles.map((role) => (
|
||||
<Button key={role} variant="outline" className="h-11 text-base" onClick={() => handleRoleSelection(role, authenticatedUser)}>
|
||||
Entrar como: {role.charAt(0).toUpperCase() + role.slice(1)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{children}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
// Estado para guardar os botões de seleção de perfil
|
||||
const [roleSelectionUI, setRoleSelectionUI] =
|
||||
useState<React.ReactNode | null>(null);
|
||||
|
||||
return (
|
||||
<Card className="w-full bg-transparent border-0 shadow-none">
|
||||
<CardContent className="p-0">
|
||||
{!roleSelectionUI ? (
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">E-mail</Label>
|
||||
<div className="relative">
|
||||
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground w-5 h-5" />
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="seu.email@exemplo.com"
|
||||
value={form.email}
|
||||
onChange={(e) => setForm({ ...form, email: e.target.value })}
|
||||
className="pl-10 h-11 focus-visible:ring-blue-600 focus-visible:ring-2"
|
||||
required
|
||||
disabled={isLoading}
|
||||
autoComplete="username"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Senha</Label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground w-5 h-5" />
|
||||
<Input
|
||||
id="password"
|
||||
type={showPassword ? "text" : "password"}
|
||||
placeholder="Digite sua senha"
|
||||
value={form.password}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, password: e.target.value })
|
||||
}
|
||||
className="pl-10 pr-12 h-11 focus-visible:ring-blue-600 focus-visible:ring-2"
|
||||
required
|
||||
disabled={isLoading}
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 h-8 w-8 p-0 text-muted-foreground hover:text-foreground"
|
||||
disabled={isLoading}
|
||||
>
|
||||
{showPassword ? (
|
||||
<EyeOff className="w-5 h-5" />
|
||||
) : (
|
||||
<Eye className="w-5 h-5" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full h-11 bg-blue-600 hover:bg-blue-700 text-white"
|
||||
disabled={isLoading}
|
||||
>
|
||||
{isLoading ? (
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
) : (
|
||||
"Entrar"
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
) : (
|
||||
<div className="space-y-4 animate-in fade-in-50">
|
||||
<h3 className="text-lg font-medium text-center text-foreground">
|
||||
Você tem múltiplos perfis
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground text-center">
|
||||
Selecione com qual perfil deseja entrar:
|
||||
</p>
|
||||
<div className="flex flex-col space-y-3 pt-2">
|
||||
{userRoles.map((role) => (
|
||||
<Button
|
||||
key={role}
|
||||
variant="outline"
|
||||
className="h-11 text-base"
|
||||
onClick={() => handleRoleSelection(role, authenticatedUser)}
|
||||
>
|
||||
Entrar como: {role.charAt(0).toUpperCase() + role.slice(1)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{children}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
@ -5,13 +5,10 @@ import type React from "react";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useRouter, usePathname } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import Cookies from "js-cookie"; // Mantido apenas para a limpeza de segurança no logout
|
||||
import Cookies from "js-cookie";
|
||||
import { api } from "@/services/api.mjs";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@ -20,18 +17,14 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
|
||||
import {
|
||||
Search,
|
||||
Bell,
|
||||
Calendar,
|
||||
User,
|
||||
LogOut,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Home,
|
||||
CalendarCheck2,
|
||||
ClipboardPlus,
|
||||
SquareUserRound,
|
||||
CalendarClock,
|
||||
Users,
|
||||
SquareUser,
|
||||
@ -39,6 +32,7 @@ import {
|
||||
Stethoscope,
|
||||
ClipboardMinus,
|
||||
} from "lucide-react";
|
||||
|
||||
import SidebarUserSection from "@/components/ui/userToolTip";
|
||||
|
||||
interface UserData {
|
||||
@ -83,7 +77,6 @@ export default function Sidebar({ children }: SidebarProps) {
|
||||
|
||||
useEffect(() => {
|
||||
const userInfoString = localStorage.getItem("user_info");
|
||||
// --- ALTERAÇÃO 1: Buscando o token no localStorage ---
|
||||
const token = localStorage.getItem("token");
|
||||
|
||||
if (userInfoString && token) {
|
||||
@ -113,7 +106,6 @@ export default function Sidebar({ children }: SidebarProps) {
|
||||
});
|
||||
setRole(userInfo.user_metadata?.role);
|
||||
} else {
|
||||
// O redirecionamento para /login já estava correto. Ótimo!
|
||||
router.push("/login");
|
||||
}
|
||||
}, [router]);
|
||||
@ -133,21 +125,17 @@ export default function Sidebar({ children }: SidebarProps) {
|
||||
|
||||
const handleLogout = () => setShowLogoutDialog(true);
|
||||
|
||||
// --- ALTERAÇÃO 2: A função de logout agora é MUITO mais simples ---
|
||||
const confirmLogout = async () => {
|
||||
try {
|
||||
// Chama a função centralizada para fazer o logout no servidor
|
||||
await api.logout();
|
||||
} catch (error) {
|
||||
// O erro já é logado dentro da função api.logout, não precisamos fazer nada aqui
|
||||
} finally {
|
||||
// A responsabilidade do componente é apenas limpar o estado local e redirecionar
|
||||
localStorage.removeItem("user_info");
|
||||
localStorage.removeItem("token");
|
||||
Cookies.remove("access_token"); // Limpeza de segurança
|
||||
Cookies.remove("access_token");
|
||||
|
||||
setShowLogoutDialog(false);
|
||||
router.push("/"); // Redireciona para a home
|
||||
router.push("/");
|
||||
}
|
||||
};
|
||||
|
||||
@ -200,37 +188,27 @@ export default function Sidebar({ children }: SidebarProps) {
|
||||
},
|
||||
];
|
||||
|
||||
const managerItems: MenuItem[] = [
|
||||
{ href: "/manager/dashboard", icon: Home, label: "Dashboard" },
|
||||
{ href: "#", icon: ClipboardMinus, label: "Relatórios gerenciais" },
|
||||
{ href: "/manager/usuario", icon: Users, label: "Gestão de Usuários" },
|
||||
{ href: "/manager/home", icon: Stethoscope, label: "Gestão de Médicos" },
|
||||
{ href: "/manager/pacientes", icon: Users, label: "Gestão de Pacientes" },
|
||||
{ href: "/doctor/consultas", icon: CalendarCheck2, label: "Consultas" }, //adicionar botão de voltar pra pagina anterior
|
||||
];
|
||||
const managerItems: MenuItem[] = [
|
||||
{ href: "/manager/dashboard", icon: Home, label: "Dashboard" },
|
||||
{ href: "/manager/usuario", icon: Users, label: "Gestão de Usuários" },
|
||||
{ href: "/manager/home", icon: Stethoscope, label: "Gestão de Médicos" },
|
||||
{ href: "/manager/pacientes", icon: Users, label: "Gestão de Pacientes" },
|
||||
{ href: "/secretary/appointments", icon: CalendarCheck2, label: "Consultas" },
|
||||
{ href: "/manager/disponibilidade", icon: ClipboardList, label: "Disponibilidade" },
|
||||
];
|
||||
|
||||
let menuItems: MenuItem[];
|
||||
switch (role) {
|
||||
case "gestor":
|
||||
menuItems = managerItems;
|
||||
break;
|
||||
case "admin":
|
||||
menuItems = managerItems;
|
||||
break;
|
||||
return managerItems;
|
||||
case "medico":
|
||||
menuItems = doctorItems;
|
||||
break;
|
||||
return doctorItems;
|
||||
case "secretaria":
|
||||
menuItems = secretaryItems;
|
||||
break;
|
||||
return secretaryItems;
|
||||
case "paciente":
|
||||
menuItems = patientItems;
|
||||
break;
|
||||
default:
|
||||
menuItems = patientItems;
|
||||
break;
|
||||
return patientItems;
|
||||
}
|
||||
return menuItems;
|
||||
};
|
||||
|
||||
const menuItems = SetMenuItems(role);
|
||||
@ -246,48 +224,59 @@ export default function Sidebar({ children }: SidebarProps) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 flex">
|
||||
<div
|
||||
className={`bg-white border-r border-gray-200 transition-all duration-300 fixed top-0 h-screen flex flex-col z-30 ${
|
||||
sidebarCollapsed ? "w-16" : "w-64"
|
||||
}`}
|
||||
className={`fixed top-0 h-screen flex flex-col z-30 transition-all duration-300
|
||||
${sidebarCollapsed ? "w-16" : "w-64"}
|
||||
bg-[#123965] text-white`}
|
||||
>
|
||||
<div className="p-4 border-b border-gray-200 flex items-center justify-between">
|
||||
{/* TOPO */}
|
||||
<div className="p-4 border-b border-white/10 flex items-center justify-between">
|
||||
{!sidebarCollapsed && (
|
||||
<div className="flex items-center gap-2">
|
||||
{/* 🛑 SUBSTITUIÇÃO: Usando a tag <img> com o caminho da logo */}
|
||||
<img
|
||||
src="/Logo MedConnect.png" // Use o arquivo da logo (ou /android-chrome-512x512.png)
|
||||
alt="Logo MediConnect"
|
||||
className="w-12 h-12 object-contain" // Define o tamanho para w-8 h-8 (32px)
|
||||
/>
|
||||
<span className="font-semibold text-gray-900">MedConnect</span>
|
||||
<div className="bg-white p-1 rounded-lg">
|
||||
<img
|
||||
src="/Logo MedConnect.png"
|
||||
alt="Logo MedConnect"
|
||||
className="w-12 h-12 object-contain"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<span className="font-semibold text-white text-lg">
|
||||
MedConnect
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
|
||||
className="p-1"
|
||||
className="p-1 text-white hover:bg-white/10 cursor-pointer"
|
||||
>
|
||||
{sidebarCollapsed ? (
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
<ChevronRight className="w-5 h-5" />
|
||||
) : (
|
||||
<ChevronLeft className="w-4 h-4" />
|
||||
<ChevronLeft className="w-5 h-5" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<nav className="flex-1 p-2 overflow-y-auto">
|
||||
{/* MENU */}
|
||||
<nav className="flex-1 p-3 overflow-y-auto">
|
||||
{menuItems.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const isActive = pathname === item.href;
|
||||
|
||||
return (
|
||||
<Link key={item.label} href={item.href}>
|
||||
<div
|
||||
className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${
|
||||
isActive
|
||||
? "bg-blue-50 text-blue-600 border-r-2 border-blue-600"
|
||||
: "text-gray-600 hover:bg-gray-50"
|
||||
}`}
|
||||
className={`
|
||||
flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors
|
||||
${
|
||||
isActive
|
||||
? "bg-white/20 text-white font-semibold"
|
||||
: "text-white/80 hover:bg-white/10 hover:text-white"
|
||||
}
|
||||
`}
|
||||
>
|
||||
<Icon className="w-5 h-5 flex-shrink-0" />
|
||||
{!sidebarCollapsed && (
|
||||
@ -298,30 +287,31 @@ export default function Sidebar({ children }: SidebarProps) {
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
<SidebarUserSection
|
||||
userData={userData}
|
||||
sidebarCollapsed={false}
|
||||
handleLogout={handleLogout}
|
||||
isActive={role === "paciente" ? false : true}
|
||||
></SidebarUserSection>
|
||||
</div>
|
||||
|
||||
{/* PERFIL ORIGINAL + NOME BRANCO */}
|
||||
<div className="mt-auto p-3 border-t border-white/10">
|
||||
<SidebarUserSection
|
||||
userData={userData}
|
||||
sidebarCollapsed={sidebarCollapsed}
|
||||
handleLogout={handleLogout}
|
||||
isActive={role !== "paciente"}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className={`flex-1 flex flex-col transition-all duration-300 w-full ${
|
||||
className={`flex-1 flex flex-col transition-all duration-300 ${
|
||||
sidebarCollapsed ? "ml-16" : "ml-64"
|
||||
}`}
|
||||
>
|
||||
<header className="bg-gray-50 px-4 md:px-6 py-4 flex items-center justify-between"></header>
|
||||
<main className="flex-1 p-4 md:p-6">{children}</main>
|
||||
</div>
|
||||
|
||||
<Dialog open={showLogoutDialog} onOpenChange={setShowLogoutDialog}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Confirmar Saída</DialogTitle>
|
||||
<DialogDescription>
|
||||
Deseja realmente sair do sistema? Você precisará fazer login
|
||||
novamente para acessar sua conta.
|
||||
novamente.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter className="flex gap-2">
|
||||
@ -335,6 +325,7 @@ export default function Sidebar({ children }: SidebarProps) {
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
105
components/ui/WeeklyScheduleCard.tsx
Normal file
105
components/ui/WeeklyScheduleCard.tsx
Normal file
@ -0,0 +1,105 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card";
|
||||
import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
||||
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||
|
||||
type Availability = {
|
||||
id: string;
|
||||
doctor_id: string;
|
||||
weekday: string;
|
||||
start_time: string;
|
||||
end_time: string;
|
||||
slot_minutes: number;
|
||||
appointment_type: string;
|
||||
active: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
created_by: string;
|
||||
updated_by: string | null;
|
||||
};
|
||||
|
||||
interface WeeklyScheduleProps {
|
||||
doctorId?: string;
|
||||
}
|
||||
|
||||
export default function WeeklyScheduleCard({ doctorId }: WeeklyScheduleProps) {
|
||||
const [schedule, setSchedule] = useState<Record<string, { start: string; end: string }[]>>({});
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const weekdaysPT: Record<string, string> = {
|
||||
sunday: "Domingo",
|
||||
monday: "Segunda",
|
||||
tuesday: "Terça",
|
||||
wednesday: "Quarta",
|
||||
thursday: "Quinta",
|
||||
friday: "Sexta",
|
||||
saturday: "Sábado",
|
||||
};
|
||||
|
||||
const formatTime = (time?: string | null) => time?.split(":")?.slice(0, 2).join(":") ?? "";
|
||||
|
||||
function formatAvailability(data: Availability[]) {
|
||||
const grouped = data.reduce((acc: any, item) => {
|
||||
const { weekday, start_time, end_time } = item;
|
||||
|
||||
if (!acc[weekday]) acc[weekday] = [];
|
||||
|
||||
acc[weekday].push({ start: start_time, end: end_time });
|
||||
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
return grouped;
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const fetchSchedule = async () => {
|
||||
try {
|
||||
const availabilityList = await AvailabilityService.list();
|
||||
|
||||
const filtered = availabilityList.filter((a: Availability) => a.doctor_id == doctorId);
|
||||
|
||||
const formatted = formatAvailability(filtered);
|
||||
setSchedule(formatted);
|
||||
} catch (err) {
|
||||
console.error("Erro ao carregar horários:", err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchSchedule();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="space-y-4 grid md:grid-cols-7 gap-2">
|
||||
{loading ? (
|
||||
<p className="text-sm text-gray-500 col-span-7 text-center">Carregando...</p>
|
||||
) : (
|
||||
["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "Saturday"].map((day) => {
|
||||
const times = schedule[day] || [];
|
||||
return (
|
||||
<div key={day} className="space-y-4">
|
||||
<div className="flex flex-col items-center justify-between p-3 bg-blue-50 rounded-lg">
|
||||
<p className="font-medium capitalize">{weekdaysPT[day]}</p>
|
||||
<div className="text-center">
|
||||
{times.length > 0 ? (
|
||||
times.map((t, i) => (
|
||||
<p key={i} className="text-sm text-gray-600">
|
||||
{formatTime(t.start)} <br /> {formatTime(t.end)}
|
||||
</p>
|
||||
))
|
||||
) : (
|
||||
<p className="text-sm text-gray-400 italic">Sem horário</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -2,7 +2,14 @@
|
||||
|
||||
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CalendarCheck2, CalendarClock, ClipboardPlus, Home, LogOut, SquareUser } from "lucide-react";
|
||||
import {
|
||||
CalendarCheck2,
|
||||
CalendarClock,
|
||||
ClipboardPlus,
|
||||
Home,
|
||||
LogOut,
|
||||
SquareUser,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
Popover,
|
||||
PopoverTrigger,
|
||||
@ -34,45 +41,52 @@ export default function SidebarUserSection({
|
||||
handleLogout,
|
||||
isActive,
|
||||
}: Props) {
|
||||
const pathname = usePathname();
|
||||
const menuItems: any[] = [
|
||||
{ href: "/patient/schedule", icon: CalendarClock, label: "Agendar Consulta" },
|
||||
{ href: "/patient/appointments", icon: CalendarCheck2, label: "Minhas Consultas" },
|
||||
{ href: "/patient/reports", icon: ClipboardPlus, label: "Meus Laudos" },
|
||||
{ href: "/patient/profile", icon: SquareUser, label: "Meus Dados" },
|
||||
]
|
||||
const pathname = usePathname();
|
||||
const menuItems: any[] = [
|
||||
{
|
||||
href: "/patient/schedule",
|
||||
icon: CalendarClock,
|
||||
label: "Agendar Consulta",
|
||||
},
|
||||
{
|
||||
href: "/patient/appointments",
|
||||
icon: CalendarCheck2,
|
||||
label: "Minhas Consultas",
|
||||
},
|
||||
{ href: "/patient/reports", icon: ClipboardPlus, label: "Meus Laudos" },
|
||||
{ href: "/patient/profile", icon: SquareUser, label: "Meus Dados" },
|
||||
];
|
||||
return (
|
||||
<div className="border-t p-4 mt-auto">
|
||||
{/* POPUP DE INFORMAÇÕES DO USUÁRIO */}
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<div
|
||||
className={`flex items-center space-x-3 mb-4 p-2 rounded-md transition-colors ${
|
||||
isActive
|
||||
? "cursor-pointer hover:bg-gray-100"
|
||||
: "cursor-default pointer-events-none"
|
||||
}`}>
|
||||
<Avatar>
|
||||
<AvatarImage src="/placeholder.svg?height=40&width=40" />
|
||||
<AvatarFallback>
|
||||
{userData.user_metadata.full_name
|
||||
.split(" ")
|
||||
.map((n) => n[0])
|
||||
.join("")}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div
|
||||
className={`flex items-center space-x-3 mb-4 p-2 rounded-md transition-colors ${
|
||||
isActive ? "cursor-pointer" : "cursor-default pointer-events-none"
|
||||
}`}
|
||||
>
|
||||
<Avatar>
|
||||
<AvatarImage src="/placeholder.svg?height=40&width=40" />
|
||||
<AvatarFallback>
|
||||
{userData.user_metadata.full_name
|
||||
.split(" ")
|
||||
.map((n) => n[0])
|
||||
.join("")}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
|
||||
{!sidebarCollapsed && (
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium text-gray-900 truncate">
|
||||
{userData.user_metadata.full_name}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 truncate">
|
||||
{userData.app_metadata.user_role}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{!sidebarCollapsed && (
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium text-white truncate">
|
||||
{userData.user_metadata.full_name}
|
||||
</p>
|
||||
<p className="text-xs text-white truncate">
|
||||
{userData.app_metadata.user_role}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</PopoverTrigger>
|
||||
|
||||
{/* Card flutuante */}
|
||||
@ -83,43 +97,47 @@ export default function SidebarUserSection({
|
||||
>
|
||||
<nav>
|
||||
{menuItems.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const isActive = pathname === item.href;
|
||||
return (
|
||||
<Link key={item.label} href={item.href}>
|
||||
<div
|
||||
className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${
|
||||
isActive
|
||||
? "bg-blue-50 text-blue-600 border-r-2 border-blue-600"
|
||||
: "text-gray-600 hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
<Icon className="w-5 h-5 flex-shrink-0" />
|
||||
{!sidebarCollapsed && (
|
||||
<span className="font-medium">{item.label}</span>
|
||||
)}
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
const Icon = item.icon;
|
||||
const isActive = pathname === item.href;
|
||||
return (
|
||||
<Link key={item.label} href={item.href}>
|
||||
<div
|
||||
className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${
|
||||
isActive
|
||||
? "bg-blue-50 text-blue-600 border-r-2 border-blue-600"
|
||||
: "text-gray-600 hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
<Icon className="w-5 h-5 flex-shrink-0" />
|
||||
{!sidebarCollapsed && (
|
||||
<span className="font-medium">{item.label}</span>
|
||||
)}
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
{/* Botão de sair */}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className={
|
||||
sidebarCollapsed
|
||||
? "w-full bg-transparent flex justify-center items-center p-2"
|
||||
: "w-full bg-transparent"
|
||||
? "w-full bg-white text-black flex justify-center items-center p-2 hover:bg-gray-200"
|
||||
: "w-full bg-white text-black hover:bg-gray-200 cursor-pointer"
|
||||
}
|
||||
onClick={handleLogout}
|
||||
>
|
||||
<LogOut className={sidebarCollapsed ? "h-5 w-5" : "mr-2 h-4 w-4"} />
|
||||
{sidebarCollapsed && "Sair"}
|
||||
<LogOut
|
||||
className={
|
||||
sidebarCollapsed ? "h-5 w-5 text-black" : "mr-2 h-4 w-4 text-black"
|
||||
}
|
||||
/>
|
||||
{!sidebarCollapsed && "Sair"}
|
||||
</Button>
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 45 KiB After Width: | Height: | Size: 30 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 48 KiB After Width: | Height: | Size: 33 KiB |
@ -1,100 +1,98 @@
|
||||
import { api } from "./api.mjs";
|
||||
|
||||
export const usersService = {
|
||||
// Função getMe corrigida para chamar a si mesma pelo nome
|
||||
async getMe() {
|
||||
const sessionData = await api.getSession();
|
||||
if (!sessionData?.id) {
|
||||
console.error("Sessão não encontrada ou usuário sem ID.", sessionData);
|
||||
throw new Error("Usuário não autenticado.");
|
||||
}
|
||||
// Chamando a outra função do serviço pelo nome explícito
|
||||
return usersService.full_data(sessionData.id);
|
||||
},
|
||||
// Função getMe corrigida para chamar a si mesma pelo nome
|
||||
async getMe() {
|
||||
const sessionData = await api.getSession();
|
||||
if (!sessionData?.id) {
|
||||
console.error("Sessão não encontrada ou usuário sem ID.", sessionData);
|
||||
throw new Error("Usuário não autenticado.");
|
||||
}
|
||||
// Chamando a outra função do serviço pelo nome explícito
|
||||
return usersService.full_data(sessionData.id);
|
||||
},
|
||||
|
||||
async list_roles() {
|
||||
return await api.get(`/rest/v1/user_roles?select=id,user_id,role,created_at`);
|
||||
},
|
||||
async list_roles() {
|
||||
return await api.get(`/rest/v1/user_roles?select=id,user_id,role,created_at`);
|
||||
},
|
||||
|
||||
async create_user(data) {
|
||||
// Esta é a função usada no page.tsx para criar usuários que não são médicos
|
||||
return await api.post(`/functions/v1/create-user-with-password`, data);
|
||||
},
|
||||
async create_user(data) {
|
||||
// Esta é a função usada no page.tsx para criar usuários que não são médicos
|
||||
return await api.post(`/functions/v1/create-user-with-password`, data);
|
||||
},
|
||||
|
||||
async getMeSimple() {
|
||||
return await api.post(`/functions/v1/user-info`);
|
||||
},
|
||||
// --- NOVA FUNÇÃO ADICIONADA AQUI ---
|
||||
// Esta função chama o endpoint público de registro de paciente.
|
||||
async registerPatient(data) {
|
||||
// POR QUÊ? Este endpoint é público e não requer token JWT, resolvendo o erro 401.
|
||||
return await api.post("/functions/v1/register-patient", data);
|
||||
},
|
||||
// --- FIM DA NOVA FUNÇÃO ---
|
||||
|
||||
async full_data(user_id) {
|
||||
if (!user_id) throw new Error("user_id é obrigatório");
|
||||
async getMeSimple() {
|
||||
return await api.post(`/functions/v1/user-info`);
|
||||
},
|
||||
|
||||
const [profile] = await api.get(`/rest/v1/profiles?id=eq.${user_id}`);
|
||||
const [role] = await api.get(`/rest/v1/user_roles?user_id=eq.${user_id}`);
|
||||
const permissions = {
|
||||
isAdmin: role?.role === "admin",
|
||||
isManager: role?.role === "gestor",
|
||||
isDoctor: role?.role === "medico",
|
||||
isSecretary: role?.role === "secretaria",
|
||||
isAdminOrManager:
|
||||
role?.role === "admin" || role?.role === "gestor" ? true : false,
|
||||
};
|
||||
async full_data(user_id) {
|
||||
if (!user_id) throw new Error("user_id é obrigatório");
|
||||
|
||||
return {
|
||||
user: {
|
||||
id: user_id,
|
||||
email: profile?.email ?? "—",
|
||||
email_confirmed_at: null,
|
||||
created_at: profile?.created_at ?? "—",
|
||||
last_sign_in_at: null,
|
||||
},
|
||||
profile: {
|
||||
id: profile?.id ?? user_id,
|
||||
full_name: profile?.full_name ?? "—",
|
||||
email: profile?.email ?? "—",
|
||||
phone: profile?.phone ?? "—",
|
||||
avatar_url: profile?.avatar_url ?? null,
|
||||
disabled: profile?.disabled ?? false,
|
||||
created_at: profile?.created_at ?? null,
|
||||
updated_at: profile?.updated_at ?? null,
|
||||
},
|
||||
roles: [role?.role ?? "—"],
|
||||
permissions,
|
||||
};
|
||||
},
|
||||
async resetPassword(email) {
|
||||
if (!email) throw new Error("Email é obrigatório para resetar a senha.");
|
||||
const [profile] = await api.get(`/rest/v1/profiles?id=eq.${user_id}`);
|
||||
const [role] = await api.get(`/rest/v1/user_roles?user_id=eq.${user_id}`);
|
||||
const permissions = {
|
||||
isAdmin: role?.role === "admin",
|
||||
isManager: role?.role === "gestor",
|
||||
isDoctor: role?.role === "medico",
|
||||
isSecretary: role?.role === "secretaria",
|
||||
isAdminOrManager: role?.role === "admin" || role?.role === "gestor" ? true : false,
|
||||
};
|
||||
|
||||
return {
|
||||
user: {
|
||||
id: user_id,
|
||||
email: profile?.email ?? "—",
|
||||
email_confirmed_at: null,
|
||||
created_at: profile?.created_at ?? "—",
|
||||
last_sign_in_at: null,
|
||||
},
|
||||
profile: {
|
||||
id: profile?.id ?? user_id,
|
||||
full_name: profile?.full_name ?? "—",
|
||||
email: profile?.email ?? "—",
|
||||
phone: profile?.phone ?? "—",
|
||||
avatar_url: profile?.avatar_url ?? null,
|
||||
disabled: profile?.disabled ?? false,
|
||||
created_at: profile?.created_at ?? null,
|
||||
updated_at: profile?.updated_at ?? null,
|
||||
},
|
||||
roles: [role?.role ?? "—"],
|
||||
permissions,
|
||||
};
|
||||
},
|
||||
async resetPassword(email) {
|
||||
if (!email) throw new Error("Email é obrigatório para resetar a senha.");
|
||||
|
||||
try {
|
||||
const res = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_SUPABASE_URL}/auth/v1/recover`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
apikey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
|
||||
},
|
||||
body: JSON.stringify({ email }),
|
||||
}
|
||||
);
|
||||
try {
|
||||
const res = await fetch(`${process.env.NEXT_PUBLIC_SUPABASE_URL}/auth/v1/recover`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
apikey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
|
||||
},
|
||||
body: JSON.stringify({ email }),
|
||||
});
|
||||
|
||||
const data = await res.json().catch(() => ({}));
|
||||
|
||||
const data = await res.json().catch(() => ({}));
|
||||
|
||||
|
||||
if (!res.ok) {
|
||||
console.error("Erro no resetPassword:", res.status, data);
|
||||
throw new Error(`Erro ${res.status}: ${data.message || "Falha ao resetar senha."}`);
|
||||
}
|
||||
|
||||
|
||||
console.log("✅ Reset de senha:", data);
|
||||
return data;
|
||||
} catch (err) {
|
||||
console.error("❌ Erro na chamada resetPassword:", err);
|
||||
throw new Error(err.message || "Erro inesperado na recuperação de senha.");
|
||||
}
|
||||
},
|
||||
|
||||
if (!res.ok) {
|
||||
console.error("Erro no resetPassword:", res.status, data);
|
||||
throw new Error(`Erro ${res.status}: ${data.message || "Falha ao resetar senha."}`);
|
||||
}
|
||||
|
||||
console.log("✅ Reset de senha:", data);
|
||||
return data;
|
||||
} catch (err) {
|
||||
console.error("❌ Erro na chamada resetPassword:", err);
|
||||
throw new Error(err.message || "Erro inesperado na recuperação de senha.");
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user