Compare commits
75 Commits
fcbcb9988f
...
979bb0db7f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
979bb0db7f | ||
| 113504d6cc | |||
|
|
adcf76b6ff | ||
|
|
cdac2dc69d | ||
|
|
097222df79 | ||
| 4412ae8848 | |||
|
|
894b866d44 | ||
|
|
ad078dcb4e | ||
| ce45c7187a | |||
| aa409fde0f | |||
| 43e69d3cc1 | |||
| ebd40eecc2 | |||
| 24179c550e | |||
| a078204276 | |||
| 5a3ea1bb75 | |||
| c04b0989d2 | |||
| 998947eda6 | |||
| 2672d96b1a | |||
| 5b8ee4e9f5 | |||
| d24bf41818 | |||
|
|
531ae3d529 | ||
|
|
7de65147c1 | ||
|
|
732c3a4b02 | ||
|
|
ae5654a055 | ||
|
|
ed862da502 | ||
| 8b4f2a737d | |||
| 569d912981 | |||
|
|
d699b1ab69 | ||
| 1cd659b2b7 | |||
| 634542dff7 | |||
|
|
248e90595e | ||
| 054e4fddda | |||
| 619c4eba77 | |||
|
|
98f14efe00 | ||
| 9fd9c05040 | |||
|
|
1c922b4ac1 | ||
|
|
7ab488b346 | ||
| dbc5a64ccd | |||
| 8a63219cf6 | |||
|
|
883411b8a3 | ||
| 71963064e0 | |||
| 25000e3cfb | |||
|
|
2e0ce5fa89 | ||
| 5de7d4b471 | |||
| 83e0814293 | |||
| dd26f3b660 | |||
|
|
4a1a91e8aa | ||
| 4957c9c55a | |||
|
|
9fb2ff1c4d | ||
| 00e8b4310e | |||
|
|
bfad3eeac4 | ||
| 1d978cfaef | |||
|
|
861fdd2cc7 | ||
| c41d561dd6 | |||
| 83bdaed7aa | |||
| adfeb3097f | |||
| ddc4443114 | |||
|
|
f848ca7376 | ||
| 74a7fa91de | |||
| 945ec9d7e7 | |||
| b9f8efb039 | |||
| d9f361defb | |||
| 12aa0e34e1 | |||
| 6e62797526 | |||
| abd1333f11 | |||
| cfc6a105b5 | |||
| da35ebbff5 | |||
|
|
01aecc4485 | ||
|
|
b9b49cba42 | ||
|
|
361a651412 | ||
| c9aed9d4a4 | |||
| cbcb7b54fd | |||
|
|
e31d7f7046 | ||
| 7c45ea583f | |||
|
|
c0f635d908 |
@ -19,20 +19,25 @@ interface AccessibilityContextProps {
|
|||||||
const AccessibilityContext = createContext<AccessibilityContextProps | undefined>(undefined);
|
const AccessibilityContext = createContext<AccessibilityContextProps | undefined>(undefined);
|
||||||
|
|
||||||
export const AccessibilityProvider = ({ children }: { children: ReactNode }) => {
|
export const AccessibilityProvider = ({ children }: { children: ReactNode }) => {
|
||||||
const [theme, setThemeState] = useState<Theme>('light');
|
const [theme, setThemeState] = useState<Theme>(() => {
|
||||||
const [contrast, setContrastState] = useState<Contrast>('normal');
|
if (typeof window !== 'undefined') {
|
||||||
const [fontSize, setFontSize] = useState<number>(16);
|
return (localStorage.getItem('accessibility-theme') as Theme) || 'light';
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const storedTheme = (localStorage.getItem('accessibility-theme') as Theme) || 'light';
|
|
||||||
const storedContrast = (localStorage.getItem('accessibility-contrast') as Contrast) || 'normal';
|
|
||||||
const storedSize = localStorage.getItem('accessibility-font-size');
|
|
||||||
setThemeState(storedTheme);
|
|
||||||
setContrastState(storedContrast);
|
|
||||||
if (storedSize) {
|
|
||||||
setFontSize(parseFloat(storedSize));
|
|
||||||
}
|
}
|
||||||
}, []);
|
return 'light';
|
||||||
|
});
|
||||||
|
const [contrast, setContrastState] = useState<Contrast>(() => {
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
return (localStorage.getItem('accessibility-contrast') as Contrast) || 'normal';
|
||||||
|
}
|
||||||
|
return 'normal';
|
||||||
|
});
|
||||||
|
const [fontSize, setFontSize] = useState<number>(() => {
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
const storedSize = localStorage.getItem('accessibility-font-size');
|
||||||
|
return storedSize ? parseFloat(storedSize) : 16;
|
||||||
|
}
|
||||||
|
return 16;
|
||||||
|
});
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const root = document.documentElement;
|
const root = document.documentElement;
|
||||||
|
|||||||
@ -31,7 +31,7 @@ interface EnrichedAppointment {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function DoctorAppointmentsPage() {
|
export default function DoctorAppointmentsPage() {
|
||||||
const { user, isLoading: isAuthLoading } = useAuthLayout({ requiredRole: 'medico' });
|
const { user, isLoading: isAuthLoading } = useAuthLayout({ requiredRole: "medico" });
|
||||||
|
|
||||||
const [allAppointments, setAllAppointments] = useState<EnrichedAppointment[]>([]);
|
const [allAppointments, setAllAppointments] = useState<EnrichedAppointment[]>([]);
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
@ -111,13 +111,22 @@ export default function DoctorAppointmentsPage() {
|
|||||||
return format(date, "EEEE, dd 'de' MMMM", { locale: ptBR });
|
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']) => {
|
const getStatusVariant = (status: EnrichedAppointment['status']) => {
|
||||||
switch (status) {
|
switch (status) {
|
||||||
case "confirmed": case "checked_in": return "default";
|
case "confirmed": case "checked_in": return "text-foreground bg-blue-100 hover:bg-blue-150";
|
||||||
case "completed": return "secondary";
|
case "completed": return "text-foreground bg-green-100 hover:bg-green-150";
|
||||||
case "cancelled": case "no_show": return "destructive";
|
case "cancelled": case "no_show": return "text-foreground bg-red-200 hover:bg-red-250";
|
||||||
case "requested": return "outline";
|
case "requested": return "text-foreground bg-yellow-100 hover:bg-yellow-150";
|
||||||
default: return "outline";
|
default: return "border-gray bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90";
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -153,7 +162,7 @@ export default function DoctorAppointmentsPage() {
|
|||||||
<Card>
|
<Card>
|
||||||
<CardHeader><CardTitle className="flex items-center"><CalendarIcon className="mr-2 h-5 w-5" />Filtrar por Data</CardTitle><CardDescription>Selecione um dia para ver os detalhes.</CardDescription></CardHeader>
|
<CardHeader><CardTitle className="flex items-center"><CalendarIcon className="mr-2 h-5 w-5" />Filtrar por Data</CardTitle><CardDescription>Selecione um dia para ver os detalhes.</CardDescription></CardHeader>
|
||||||
<CardContent className="flex justify-center p-2">
|
<CardContent className="flex justify-center p-2">
|
||||||
<CalendarShadcn mode="single" selected={selectedDate} onSelect={setSelectedDate} modifiers={{ booked: bookedDays }} modifiersClassNames={{ booked: "bg-primary/20" }} className="rounded-md border p-2" locale={ptBR}/>
|
<CalendarShadcn mode="single" selected={selectedDate} onSelect={setSelectedDate} modifiers={{ booked: bookedDays }} modifiersClassNames={{ booked: "bg-primary/20" }} className="rounded-md border p-2" locale={ptBR} />
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
@ -191,7 +200,7 @@ export default function DoctorAppointmentsPage() {
|
|||||||
|
|
||||||
{/* Coluna 2: Status e Telefone */}
|
{/* Coluna 2: Status e Telefone */}
|
||||||
<div className="col-span-1 flex flex-col items-center gap-2">
|
<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">
|
<div className="flex items-center text-sm text-muted-foreground">
|
||||||
<Phone className="mr-2 h-4 w-4" />
|
<Phone className="mr-2 h-4 w-4" />
|
||||||
{appointment.patientPhone}
|
{appointment.patientPhone}
|
||||||
|
|||||||
@ -1,19 +1,54 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
import {
|
||||||
|
Card,
|
||||||
|
CardContent,
|
||||||
|
CardDescription,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from "@/components/ui/card";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Calendar, Clock, User, Trash2 } from "lucide-react";
|
import { Calendar, Clock, User, Trash2 } from "lucide-react";
|
||||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
import {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogAction,
|
||||||
|
AlertDialogCancel,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogTitle,
|
||||||
|
} from "@/components/ui/alert-dialog";
|
||||||
|
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState, useMemo } from "react"; // Adicionado useMemo
|
||||||
import { toast } from "@/hooks/use-toast";
|
import { toast } from "@/hooks/use-toast";
|
||||||
|
|
||||||
|
import { useAuthLayout } from "@/hooks/useAuthLayout";
|
||||||
|
import { patientsService } from "@/services/patientsApi.mjs";
|
||||||
|
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
||||||
|
import { format, parseISO, isAfter, isSameMonth, startOfToday } from "date-fns";
|
||||||
|
import { ptBR } from "date-fns/locale";
|
||||||
|
|
||||||
import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
||||||
import { exceptionsService } from "@/services/exceptionApi.mjs";
|
import { exceptionsService } from "@/services/exceptionApi.mjs";
|
||||||
import { doctorsService } from "@/services/doctorsApi.mjs";
|
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||||
import { usersService } from "@/services/usersApi.mjs";
|
import { usersService } from "@/services/usersApi.mjs";
|
||||||
import Sidebar from "@/components/Sidebar";
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
import WeeklyScheduleCard from "@/components/ui/WeeklyScheduleCard";
|
||||||
|
|
||||||
|
|
||||||
|
type Appointment = {
|
||||||
|
id: string;
|
||||||
|
doctor_id: string;
|
||||||
|
patient_id: string;
|
||||||
|
scheduled_at: string;
|
||||||
|
status: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type EnrichedAppointment = Appointment & {
|
||||||
|
patientName: string;
|
||||||
|
};
|
||||||
|
|
||||||
type Availability = {
|
type Availability = {
|
||||||
id: string;
|
id: string;
|
||||||
@ -61,7 +96,7 @@ type Doctor = {
|
|||||||
updated_by: string | null;
|
updated_by: string | null;
|
||||||
max_days_in_advance: number;
|
max_days_in_advance: number;
|
||||||
rating: number | null;
|
rating: number | null;
|
||||||
}
|
};
|
||||||
|
|
||||||
interface UserPermissions {
|
interface UserPermissions {
|
||||||
isAdmin: boolean;
|
isAdmin: boolean;
|
||||||
@ -94,19 +129,30 @@ interface UserData {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface Exception {
|
interface Exception {
|
||||||
id: string; // id da exceção
|
id: string;
|
||||||
doctor_id: string;
|
doctor_id: string;
|
||||||
date: string; // formato YYYY-MM-DD
|
date: string;
|
||||||
start_time: string | null; // null = dia inteiro
|
start_time: string | null;
|
||||||
end_time: string | null; // null = dia inteiro
|
end_time: string | null;
|
||||||
kind: "bloqueio" | "disponibilidade"; // tipos conhecidos
|
kind: "bloqueio" | "disponibilidade";
|
||||||
reason: string | null; // pode ser null
|
reason: string | null;
|
||||||
created_at: string; // timestamp ISO
|
created_at: string;
|
||||||
created_by: string;
|
created_by: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function PatientDashboard() {
|
type Patient = {
|
||||||
const [loggedDoctor, setLoggedDoctor] = useState<Doctor>();
|
id: string;
|
||||||
|
full_name: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function DoctorDashboard() {
|
||||||
|
// --- CORREÇÃO CRÍTICA DO LOOP ---
|
||||||
|
// Usamos useMemo para garantir que o array de roles seja uma referência estável
|
||||||
|
// e não dispare o useEffect do useAuthLayout infinitamente.
|
||||||
|
const requiredRoles = useMemo(() => ['medico'], []);
|
||||||
|
const { user } = useAuthLayout({ requiredRole: requiredRoles });
|
||||||
|
|
||||||
|
const [loggedDoctor, setLoggedDoctor] = useState<Doctor | null>(null);
|
||||||
const [userData, setUserData] = useState<UserData>();
|
const [userData, setUserData] = useState<UserData>();
|
||||||
const [availability, setAvailability] = useState<any | null>(null);
|
const [availability, setAvailability] = useState<any | null>(null);
|
||||||
const [exceptions, setExceptions] = useState<Exception[]>([]);
|
const [exceptions, setExceptions] = useState<Exception[]>([]);
|
||||||
@ -116,52 +162,65 @@ export default function PatientDashboard() {
|
|||||||
const [exceptionToDelete, setExceptionToDelete] = useState<string | null>(null);
|
const [exceptionToDelete, setExceptionToDelete] = useState<string | null>(null);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
// Mapa de tradução
|
const [nextAppointment, setNextAppointment] = useState<EnrichedAppointment | null>(null);
|
||||||
const weekdaysPT: Record<string, string> = {
|
const [monthlyCount, setMonthlyCount] = useState<number>(0);
|
||||||
sunday: "Domingo",
|
|
||||||
monday: "Segunda",
|
const weekdaysPT: Record<string, string> = { sunday: "Domingo", monday: "Segunda", tuesday: "Terça", wednesday: "Quarta", thursday: "Quinta", friday: "Sexta", saturday: "Sábado" };
|
||||||
tuesday: "Terça",
|
|
||||||
wednesday: "Quarta",
|
|
||||||
thursday: "Quinta",
|
|
||||||
friday: "Sexta",
|
|
||||||
saturday: "Sábado",
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchData = async () => {
|
const fetchData = async () => {
|
||||||
|
if (!user?.id) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const doctorsList: Doctor[] = await doctorsService.list();
|
const doctorsList: Doctor[] = await doctorsService.list();
|
||||||
const doctor = doctorsList[0];
|
const currentDoctor = doctorsList.find(doc => doc.user_id === user.id);
|
||||||
|
|
||||||
// Salva no estado
|
if (!currentDoctor) {
|
||||||
setLoggedDoctor(doctor);
|
setError("Perfil de médico não encontrado para este usuário.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLoggedDoctor(currentDoctor);
|
||||||
|
|
||||||
// Busca disponibilidade
|
const [appointmentsList, patientsList, availabilityList, exceptionsList] = await Promise.all([
|
||||||
const availabilityList = await AvailabilityService.list();
|
appointmentsService.list(),
|
||||||
|
patientsService.list(),
|
||||||
|
AvailabilityService.list(),
|
||||||
|
exceptionsService.list()
|
||||||
|
]);
|
||||||
|
|
||||||
// Filtra já com a variável local
|
const patientsMap = new Map(patientsList.map((p: Patient) => [p.id, p.full_name]));
|
||||||
const filteredAvail = availabilityList.filter(
|
|
||||||
(disp: { doctor_id: string }) => disp.doctor_id === doctor?.id
|
const doctorAppointments = appointmentsList
|
||||||
|
.filter((apt: Appointment) => apt.doctor_id === currentDoctor.id)
|
||||||
|
.map((apt: Appointment): EnrichedAppointment => ({
|
||||||
|
...apt,
|
||||||
|
patientName: String(patientsMap.get(apt.patient_id) || "Paciente Desconhecido"),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const today = startOfToday();
|
||||||
|
const upcomingAppointments = doctorAppointments
|
||||||
|
.filter(apt => isAfter(parseISO(apt.scheduled_at), today))
|
||||||
|
.sort((a, b) => new Date(a.scheduled_at).getTime() - new Date(b.scheduled_at).getTime());
|
||||||
|
setNextAppointment(upcomingAppointments[0] || null);
|
||||||
|
|
||||||
|
const activeStatuses = ['confirmed', 'requested', 'checked_in'];
|
||||||
|
const currentMonthAppointments = doctorAppointments.filter(apt =>
|
||||||
|
isSameMonth(parseISO(apt.scheduled_at), new Date()) && activeStatuses.includes(apt.status)
|
||||||
);
|
);
|
||||||
setAvailability(filteredAvail);
|
setMonthlyCount(currentMonthAppointments.length);
|
||||||
|
|
||||||
// Busca exceções
|
setAvailability(availabilityList.filter((d: any) => d.doctor_id === currentDoctor.id));
|
||||||
const exceptionsList = await exceptionsService.list();
|
setExceptions(exceptionsList.filter((e: any) => e.doctor_id === currentDoctor.id));
|
||||||
const filteredExc = exceptionsList.filter(
|
|
||||||
(exc: { doctor_id: string }) => exc.doctor_id === doctor?.id
|
|
||||||
);
|
|
||||||
console.log(exceptionsList)
|
|
||||||
setExceptions(filteredExc);
|
|
||||||
|
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
alert(`${e?.error} ${e?.message}`);
|
setError(e?.message || "Erro ao buscar dados do dashboard");
|
||||||
|
console.error("Erro no dashboard:", e);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
fetchData();
|
fetchData();
|
||||||
}, []);
|
}, [user?.id]);
|
||||||
|
|
||||||
// Função auxiliar para filtrar o id do doctor correspondente ao user logado
|
|
||||||
function findDoctorById(id: string, doctors: Doctor[]) {
|
function findDoctorById(id: string, doctors: Doctor[]) {
|
||||||
return doctors.find((doctor) => doctor.user_id === id);
|
return doctors.find((doctor) => doctor.user_id === id);
|
||||||
}
|
}
|
||||||
@ -173,53 +232,25 @@ export default function PatientDashboard() {
|
|||||||
|
|
||||||
const handleDeleteException = async (ExceptionId: string) => {
|
const handleDeleteException = async (ExceptionId: string) => {
|
||||||
try {
|
try {
|
||||||
alert(ExceptionId)
|
|
||||||
const res = await exceptionsService.delete(ExceptionId);
|
const res = await exceptionsService.delete(ExceptionId);
|
||||||
|
if (res && res.error) { throw new Error(res.message || "A API retornou um erro"); }
|
||||||
let message = "Exceção deletada com sucesso";
|
toast({ title: "Sucesso", description: "Exceção deletada com sucesso" });
|
||||||
try {
|
|
||||||
if (res) {
|
|
||||||
throw new Error(`${res.error} ${res.message}` || "A API retornou erro");
|
|
||||||
} else {
|
|
||||||
console.log(message);
|
|
||||||
}
|
|
||||||
} catch {}
|
|
||||||
|
|
||||||
toast({
|
|
||||||
title: "Sucesso",
|
|
||||||
description: message,
|
|
||||||
});
|
|
||||||
|
|
||||||
setExceptions((prev: Exception[]) => prev.filter((p) => String(p.id) !== String(ExceptionId)));
|
setExceptions((prev: Exception[]) => prev.filter((p) => String(p.id) !== String(ExceptionId)));
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
toast({
|
toast({ title: "Erro", description: e?.message || "Não foi possível deletar a exceção" });
|
||||||
title: "Erro",
|
|
||||||
description: e?.message || "Não foi possível deletar a exceção",
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
setDeleteDialogOpen(false);
|
setDeleteDialogOpen(false);
|
||||||
setExceptionToDelete(null);
|
setExceptionToDelete(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
function formatAvailability(data: Availability[]) {
|
function formatAvailability(data: Availability[]) {
|
||||||
// Agrupar os horários por dia da semana
|
if (!data) return {};
|
||||||
const schedule = data.reduce((acc: any, item) => {
|
const schedule = data.reduce((acc: any, item) => {
|
||||||
const { weekday, start_time, end_time } = item;
|
const { weekday, start_time, end_time } = item;
|
||||||
|
if (!acc[weekday]) acc[weekday] = [];
|
||||||
// Se o dia ainda não existe, cria o array
|
acc[weekday].push({ start: start_time, end: end_time });
|
||||||
if (!acc[weekday]) {
|
|
||||||
acc[weekday] = [];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Adiciona o horário do dia
|
|
||||||
acc[weekday].push({
|
|
||||||
start: start_time,
|
|
||||||
end: end_time,
|
|
||||||
});
|
|
||||||
|
|
||||||
return acc;
|
return acc;
|
||||||
}, {} as Record<string, { start: string; end: string }[]>);
|
}, {} as Record<string, { start: string; end: string }[]>);
|
||||||
|
|
||||||
return schedule;
|
return schedule;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -234,8 +265,10 @@ export default function PatientDashboard() {
|
|||||||
<Sidebar>
|
<Sidebar>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
|
<h1 className="text-3xl font-bold">Dashboard</h1>
|
||||||
<p className="text-gray-600">Bem-vindo ao seu portal de consultas médicas</p>
|
<p className="text-muted-foreground">
|
||||||
|
Bem-vindo ao seu portal de consultas médicas
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||||
@ -245,8 +278,21 @@ export default function PatientDashboard() {
|
|||||||
<Calendar className="h-4 w-4 text-muted-foreground" />
|
<Calendar className="h-4 w-4 text-muted-foreground" />
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div className="text-2xl font-bold">02 out</div>
|
{nextAppointment ? (
|
||||||
<p className="text-xs text-muted-foreground">Dr. Silva - 14:30</p>
|
<>
|
||||||
|
<p className="text-2xl font-bold capitalize">
|
||||||
|
{nextAppointment.patientName} - {format(parseISO(nextAppointment.scheduled_at), "HH:mm")}
|
||||||
|
</p>
|
||||||
|
<div className="text-x text-muted-foreground">
|
||||||
|
{format(parseISO(nextAppointment.scheduled_at), "dd MMM", { locale: ptBR })}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="text-2xl font-bold">Nenhuma</div>
|
||||||
|
<p className="text-xs text-muted-foreground">Sem próximas consultas</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
@ -256,8 +302,8 @@ export default function PatientDashboard() {
|
|||||||
<Clock className="h-4 w-4 text-muted-foreground" />
|
<Clock className="h-4 w-4 text-muted-foreground" />
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div className="text-2xl font-bold">4</div>
|
<div className="text-2xl font-bold">{monthlyCount}</div>
|
||||||
<p className="text-xs text-muted-foreground">4 agendadas</p>
|
<p className="text-xs text-muted-foreground">{monthlyCount === 1 ? '1 agendada' : `${monthlyCount} agendadas`}</p>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
@ -280,7 +326,7 @@ export default function PatientDashboard() {
|
|||||||
<CardDescription>Acesse rapidamente as principais funcionalidades</CardDescription>
|
<CardDescription>Acesse rapidamente as principais funcionalidades</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-4">
|
<CardContent className="space-y-4">
|
||||||
<Link href="/doctor/medicos/consultas">
|
<Link href="/doctor/consultas">
|
||||||
<Button className="w-full justify-start">
|
<Button className="w-full justify-start">
|
||||||
<Calendar className="mr-2 h-4 w-4" />
|
<Calendar className="mr-2 h-4 w-4" />
|
||||||
Ver Minhas Consultas
|
Ver Minhas Consultas
|
||||||
@ -289,26 +335,7 @@ export default function PatientDashboard() {
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle>Próximas Consultas</CardTitle>
|
|
||||||
<CardDescription>Suas consultas agendadas</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="flex items-center justify-between p-3 bg-blue-50 rounded-lg">
|
|
||||||
<div>
|
|
||||||
<p className="font-medium">Dr. João Santos</p>
|
|
||||||
<p className="text-sm text-gray-600">Cardiologia</p>
|
|
||||||
</div>
|
|
||||||
<div className="text-right">
|
|
||||||
<p className="font-medium">02 out</p>
|
|
||||||
<p className="text-sm text-gray-600">14:30</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
</div>
|
||||||
<div className="grid md:grid-cols-1 gap-6">
|
<div className="grid md:grid-cols-1 gap-6">
|
||||||
<Card>
|
<Card>
|
||||||
@ -316,31 +343,7 @@ export default function PatientDashboard() {
|
|||||||
<CardTitle>Horário Semanal</CardTitle>
|
<CardTitle>Horário Semanal</CardTitle>
|
||||||
<CardDescription>Confira rapidamente a sua disponibilidade da semana</CardDescription>
|
<CardDescription>Confira rapidamente a sua disponibilidade da semana</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-4 grid md:grid-cols-7 gap-2">
|
<CardContent>{loggedDoctor && <WeeklyScheduleCard doctorId={loggedDoctor.id} />}</CardContent>
|
||||||
{["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"].map((day) => {
|
|
||||||
const times = schedule[day] || [];
|
|
||||||
return (
|
|
||||||
<div key={day} className="space-y-4">
|
|
||||||
<div className="flex flex-col items-center justify-between p-3 bg-blue-50 rounded-lg">
|
|
||||||
<div>
|
|
||||||
<p className="font-medium capitalize">{weekdaysPT[day]}</p>
|
|
||||||
</div>
|
|
||||||
<div className="text-center">
|
|
||||||
{times.length > 0 ? (
|
|
||||||
times.map((t, i) => (
|
|
||||||
<p key={i} className="text-sm text-gray-600">
|
|
||||||
{formatTime(t.start)} <br /> {formatTime(t.end)}
|
|
||||||
</p>
|
|
||||||
))
|
|
||||||
) : (
|
|
||||||
<p className="text-sm text-gray-400 italic">Sem horário</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
<div className="grid md:grid-cols-1 gap-6">
|
<div className="grid md:grid-cols-1 gap-6">
|
||||||
@ -353,7 +356,6 @@ export default function PatientDashboard() {
|
|||||||
<CardContent className="space-y-4 grid md:grid-cols-7 gap-2">
|
<CardContent className="space-y-4 grid md:grid-cols-7 gap-2">
|
||||||
{exceptions && exceptions.length > 0 ? (
|
{exceptions && exceptions.length > 0 ? (
|
||||||
exceptions.map((ex: Exception) => {
|
exceptions.map((ex: Exception) => {
|
||||||
// Formata data e hora
|
|
||||||
const date = new Date(ex.date).toLocaleDateString("pt-BR", {
|
const date = new Date(ex.date).toLocaleDateString("pt-BR", {
|
||||||
weekday: "long",
|
weekday: "long",
|
||||||
day: "2-digit",
|
day: "2-digit",
|
||||||
@ -366,21 +368,21 @@ export default function PatientDashboard() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div key={ex.id} className="space-y-4">
|
<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="flex flex-col items-center justify-between p-3 bg-primary/10 rounded-lg shadow-sm">
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<p className="font-semibold capitalize">{date}</p>
|
<p className="font-semibold capitalize">{date}</p>
|
||||||
<p className="text-sm text-gray-600">
|
<p className="text-sm text-muted-foreground">
|
||||||
{startTime && endTime
|
{startTime && endTime
|
||||||
? `${startTime} - ${endTime}`
|
? `${startTime} - ${endTime}`
|
||||||
: "Dia todo"}
|
: "Dia todo"}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-center mt-2">
|
<div className="text-center mt-2">
|
||||||
<p className={`text-sm font-medium ${ex.kind === "bloqueio" ? "text-red-600" : "text-green-600"}`}>{ex.kind === "bloqueio" ? "Bloqueio" : "Liberação"}</p>
|
<p className={`text-sm font-medium ${ex.kind === "bloqueio" ? "text-destructive" : "text-primary"}`}>{ex.kind === "bloqueio" ? "Bloqueio" : "Liberação"}</p>
|
||||||
<p className="text-xs text-gray-500 italic">{ex.reason || "Sem motivo especificado"}</p>
|
<p className="text-xs text-muted-foreground italic">{ex.reason || "Sem motivo especificado"}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<Button className="text-red-600" variant="outline" onClick={() => openDeleteDialog(String(ex.id))}>
|
<Button className="text-destructive" variant="outline" onClick={() => openDeleteDialog(String(ex.id))}>
|
||||||
<Trash2></Trash2>
|
<Trash2></Trash2>
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
@ -389,7 +391,7 @@ export default function PatientDashboard() {
|
|||||||
);
|
);
|
||||||
})
|
})
|
||||||
) : (
|
) : (
|
||||||
<p className="text-sm text-gray-400 italic col-span-7 text-center">Nenhuma exceção registrada.</p>
|
<p className="text-sm text-muted-foreground italic col-span-7 text-center">Nenhuma exceção registrada.</p>
|
||||||
)}
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
@ -402,7 +404,7 @@ export default function PatientDashboard() {
|
|||||||
</AlertDialogHeader>
|
</AlertDialogHeader>
|
||||||
<AlertDialogFooter>
|
<AlertDialogFooter>
|
||||||
<AlertDialogCancel>Cancelar</AlertDialogCancel>
|
<AlertDialogCancel>Cancelar</AlertDialogCancel>
|
||||||
<AlertDialogAction onClick={() => exceptionToDelete && handleDeleteException(exceptionToDelete)} className="bg-red-600 hover:bg-red-700">
|
<AlertDialogAction onClick={() => exceptionToDelete && handleDeleteException(exceptionToDelete)} className="bg-destructive hover:bg-destructive/90">
|
||||||
Excluir
|
Excluir
|
||||||
</AlertDialogAction>
|
</AlertDialogAction>
|
||||||
</AlertDialogFooter>
|
</AlertDialogFooter>
|
||||||
|
|||||||
@ -149,12 +149,12 @@ export default function ExceptionPage() {
|
|||||||
<Sidebar>
|
<Sidebar>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-bold text-gray-900">Adicione exceções</h1>
|
<h1 className="text-3xl font-bold text-foreground">Adicione exceções</h1>
|
||||||
<p className="text-gray-600">Altere a disponibilidade em casos especiais para o Dr. João Silva</p>
|
<p className="text-muted-foreground">Altere a disponibilidade em casos especiais para o Dr. João Silva</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex justify-between items-center">
|
<div className="flex justify-between items-center">
|
||||||
<h2 className="text-xl font-semibold">Consultas para: {displayDate}</h2>
|
<h2 className="text-xl font-semibold text-foreground">Consultas para: {displayDate}</h2>
|
||||||
<Button disabled={isLoading} variant="outline" size="sm">
|
<Button disabled={isLoading} variant="outline" size="sm">
|
||||||
<RefreshCw className={`mr-2 h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
|
<RefreshCw className={`mr-2 h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
|
||||||
Atualizar Agenda
|
Atualizar Agenda
|
||||||
@ -171,7 +171,7 @@ export default function ExceptionPage() {
|
|||||||
<CalendarIcon className="mr-2 h-5 w-5" />
|
<CalendarIcon className="mr-2 h-5 w-5" />
|
||||||
Calendário
|
Calendário
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
<p className="text-sm text-gray-500">Selecione a data desejada.</p>
|
<p className="text-sm text-muted-foreground">Selecione a data desejada.</p>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="flex justify-center p-2">
|
<CardContent className="flex justify-center p-2">
|
||||||
<Calendar
|
<Calendar
|
||||||
@ -194,23 +194,23 @@ export default function ExceptionPage() {
|
|||||||
{/* COLUNA 2: FORM PARA ADICIONAR EXCEÇÃO */}
|
{/* COLUNA 2: FORM PARA ADICIONAR EXCEÇÃO */}
|
||||||
<div className="lg:col-span-2 space-y-4">
|
<div className="lg:col-span-2 space-y-4">
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<p className="text-center text-lg text-gray-500">Carregando a agenda...</p>
|
<p className="text-center text-lg text-muted-foreground">Carregando a agenda...</p>
|
||||||
) : !selectedCalendarDate ? (
|
) : !selectedCalendarDate ? (
|
||||||
<p className="text-center text-lg text-gray-500">Selecione uma data.</p>
|
<p className="text-center text-lg text-muted-foreground">Selecione uma data.</p>
|
||||||
) : (
|
) : (
|
||||||
<form className="space-y-6" onSubmit={handleSubmit}>
|
<form className="space-y-6" onSubmit={handleSubmit}>
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
<div className="bg-card rounded-lg border border-border p-6">
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Dados </h2>
|
<h2 className="text-lg font-semibold text-foreground mb-6">Dados </h2>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="grid md:grid-cols-5 gap-6">
|
<div className="grid md:grid-cols-5 gap-6">
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="horarioEntrada" className="text-sm font-medium text-gray-700">
|
<Label htmlFor="horarioEntrada" className="text-sm font-medium text-foreground">
|
||||||
Horario De Entrada
|
Horario De Entrada
|
||||||
</Label>
|
</Label>
|
||||||
<Input type="time" id="horarioEntrada" name="horarioEntrada" className="mt-1" />
|
<Input type="time" id="horarioEntrada" name="horarioEntrada" className="mt-1" />
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="horarioSaida" className="text-sm font-medium text-gray-700">
|
<Label htmlFor="horarioSaida" className="text-sm font-medium text-foreground">
|
||||||
Horario De Saida
|
Horario De Saida
|
||||||
</Label>
|
</Label>
|
||||||
<Input type="time" id="horarioSaida" name="horarioSaida" className="mt-1" />
|
<Input type="time" id="horarioSaida" name="horarioSaida" className="mt-1" />
|
||||||
@ -218,7 +218,7 @@ export default function ExceptionPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="tipo" className="text-sm font-medium text-gray-700">
|
<Label htmlFor="tipo" className="text-sm font-medium text-foreground">
|
||||||
Tipo
|
Tipo
|
||||||
</Label>
|
</Label>
|
||||||
<Select onValueChange={(value) => setTipo(value)} value={tipo}>
|
<Select onValueChange={(value) => setTipo(value)} value={tipo}>
|
||||||
@ -232,7 +232,7 @@ export default function ExceptionPage() {
|
|||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="reason" className="text-sm font-medium text-gray-700">
|
<Label htmlFor="reason" className="text-sm font-medium text-foreground">
|
||||||
Motivo
|
Motivo
|
||||||
</Label>
|
</Label>
|
||||||
<Input type="textarea" id="reason" name="reason" required className="mt-1" />
|
<Input type="textarea" id="reason" name="reason" required className="mt-1" />
|
||||||
@ -244,7 +244,7 @@ export default function ExceptionPage() {
|
|||||||
<Link href="/doctor/disponibilidade">
|
<Link href="/doctor/disponibilidade">
|
||||||
<Button variant="outline">Cancelar</Button>
|
<Button variant="outline">Cancelar</Button>
|
||||||
</Link>
|
</Link>
|
||||||
<Button type="submit" className="bg-green-600 hover:bg-green-700">
|
<Button type="submit" className="bg-green-600 hover:bg-green-700 text-white">
|
||||||
Salvar Exceção
|
Salvar Exceção
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -6,7 +6,13 @@ import Link from "next/link";
|
|||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Label } from "@/components/ui/label";
|
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 { AvailabilityService } from "@/services/availabilityApi.mjs";
|
||||||
import { usersService } from "@/services/usersApi.mjs";
|
import { usersService } from "@/services/usersApi.mjs";
|
||||||
@ -14,11 +20,31 @@ import { doctorsService } from "@/services/doctorsApi.mjs";
|
|||||||
|
|
||||||
import { toast } from "@/hooks/use-toast";
|
import { toast } from "@/hooks/use-toast";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card";
|
import {
|
||||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
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 { Edit, Trash2 } from "lucide-react";
|
||||||
import { AvailabilityEditModal } from "@/components/ui/availability-edit-modal";
|
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";
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
// ... (Interfaces de tipo omitidas para brevidade, pois não foram alteradas)
|
// ... (Interfaces de tipo omitidas para brevidade, pois não foram alteradas)
|
||||||
@ -80,7 +106,7 @@ type Doctor = {
|
|||||||
updated_by: string | null;
|
updated_by: string | null;
|
||||||
max_days_in_advance: number;
|
max_days_in_advance: number;
|
||||||
rating: number | null;
|
rating: number | null;
|
||||||
}
|
};
|
||||||
|
|
||||||
type Availability = {
|
type Availability = {
|
||||||
id: string;
|
id: string;
|
||||||
@ -101,27 +127,38 @@ export default function AvailabilityPage() {
|
|||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [schedule, setSchedule] = useState<Record<string, { start: string; end: string }[]>>({});
|
const [schedule, setSchedule] = useState<
|
||||||
const formatTime = (time?: string | null) => time?.split(":")?.slice(0, 2).join(":") ?? "";
|
Record<string, { start: string; end: string }[]>
|
||||||
|
>({});
|
||||||
|
const formatTime = (time?: string | null) =>
|
||||||
|
time?.split(":")?.slice(0, 2).join(":") ?? "";
|
||||||
const [userData, setUserData] = useState<UserData>();
|
const [userData, setUserData] = useState<UserData>();
|
||||||
const [availability, setAvailability] = useState<any | null>(null);
|
const [availability, setAvailability] = useState<any | null>(null);
|
||||||
const [doctorId, setDoctorId] = useState<string>();
|
const [doctorId, setDoctorId] = useState<string>();
|
||||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||||
const [modalidadeConsulta, setModalidadeConsulta] = useState<string>("");
|
const [modalidadeConsulta, setModalidadeConsulta] = useState<string>("");
|
||||||
const [selectedAvailability, setSelectedAvailability] = useState<Availability | null>(null);
|
const [selectedAvailability, setSelectedAvailability] =
|
||||||
|
useState<Availability | null>(null);
|
||||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||||
|
|
||||||
const selectAvailability = (schedule: { start: string; end: string;}, day: string) => {
|
const selectAvailability = (
|
||||||
const selected = availability.filter((a: Availability) =>
|
schedule: { start: string; end: string },
|
||||||
|
day: string
|
||||||
|
) => {
|
||||||
|
const selected = availability.filter(
|
||||||
|
(a: Availability) =>
|
||||||
a.start_time === schedule.start &&
|
a.start_time === schedule.start &&
|
||||||
a.end_time === schedule.end &&
|
a.end_time === schedule.end &&
|
||||||
a.weekday === day
|
a.weekday === day
|
||||||
);
|
);
|
||||||
setSelectedAvailability(selected[0]);
|
setSelectedAvailability(selected[0]);
|
||||||
}
|
};
|
||||||
|
|
||||||
const handleOpenModal = (schedule: { start: string; end: string;}, day: string) => {
|
const handleOpenModal = (
|
||||||
selectAvailability(schedule, day)
|
schedule: { start: string; end: string },
|
||||||
|
day: string
|
||||||
|
) => {
|
||||||
|
selectAvailability(schedule, day);
|
||||||
setIsModalOpen(true);
|
setIsModalOpen(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -130,7 +167,13 @@ export default function AvailabilityPage() {
|
|||||||
setIsModalOpen(false);
|
setIsModalOpen(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleEdit = async (formData:{ start_time: "", end_time: "", slot_minutes: "", appointment_type: "", id:""}) => {
|
const handleEdit = async (formData: {
|
||||||
|
start_time: "";
|
||||||
|
end_time: "";
|
||||||
|
slot_minutes: "";
|
||||||
|
appointment_type: "";
|
||||||
|
id: "";
|
||||||
|
}) => {
|
||||||
if (isLoading) return;
|
if (isLoading) return;
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
|
|
||||||
@ -149,7 +192,9 @@ export default function AvailabilityPage() {
|
|||||||
let message = "disponibilidade editada com sucesso";
|
let message = "disponibilidade editada com sucesso";
|
||||||
try {
|
try {
|
||||||
if (!res[0].id) {
|
if (!res[0].id) {
|
||||||
throw new Error(`${res.error} ${res.message}` || "A API retornou erro");
|
throw new Error(
|
||||||
|
`${res.error} ${res.message}` || "A API retornou erro"
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
console.log(message);
|
console.log(message);
|
||||||
}
|
}
|
||||||
@ -159,16 +204,17 @@ export default function AvailabilityPage() {
|
|||||||
title: "Sucesso",
|
title: "Sucesso",
|
||||||
description: message,
|
description: message,
|
||||||
});
|
});
|
||||||
router.push("#")
|
router.push("#");
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
toast({
|
toast({
|
||||||
title: "Erro",
|
title: "Erro",
|
||||||
description: err?.message || "Não foi possível editar a disponibilidade",
|
description:
|
||||||
|
err?.message || "Não foi possível editar a disponibilidade",
|
||||||
});
|
});
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
handleCloseModal();
|
handleCloseModal();
|
||||||
fetchData()
|
fetchData();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -212,7 +258,6 @@ export default function AvailabilityPage() {
|
|||||||
return doctors.find((doctor) => doctor.user_id === id);
|
return doctors.find((doctor) => doctor.user_id === id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
function formatAvailability(data: Availability[]) {
|
function formatAvailability(data: Availability[]) {
|
||||||
// Agrupar os horários por dia da semana
|
// Agrupar os horários por dia da semana
|
||||||
const schedule = data.reduce((acc: any, item) => {
|
const schedule = data.reduce((acc: any, item) => {
|
||||||
@ -267,7 +312,9 @@ export default function AvailabilityPage() {
|
|||||||
let message = "disponibilidade cadastrada com sucesso";
|
let message = "disponibilidade cadastrada com sucesso";
|
||||||
try {
|
try {
|
||||||
if (!res[0].id) {
|
if (!res[0].id) {
|
||||||
throw new Error(`${res.error} ${res.message}` || "A API retornou erro");
|
throw new Error(
|
||||||
|
`${res.error} ${res.message}` || "A API retornou erro"
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
console.log(message);
|
console.log(message);
|
||||||
}
|
}
|
||||||
@ -284,12 +331,16 @@ export default function AvailabilityPage() {
|
|||||||
description: err?.message || "Não foi possível criar a disponibilidade",
|
description: err?.message || "Não foi possível criar a disponibilidade",
|
||||||
});
|
});
|
||||||
} finally {
|
} finally {
|
||||||
|
fetchData()
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const openDeleteDialog = (schedule: { start: string; end: string;}, day: string) => {
|
const openDeleteDialog = (
|
||||||
selectAvailability(schedule, day)
|
schedule: { start: string; end: string },
|
||||||
|
day: string
|
||||||
|
) => {
|
||||||
|
selectAvailability(schedule, day);
|
||||||
setDeleteDialogOpen(true);
|
setDeleteDialogOpen(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -318,6 +369,7 @@ export default function AvailabilityPage() {
|
|||||||
description: e?.message || "Não foi possível deletar a disponibilidade",
|
description: e?.message || "Não foi possível deletar a disponibilidade",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
fetchData()
|
||||||
setDeleteDialogOpen(false);
|
setDeleteDialogOpen(false);
|
||||||
setSelectedAvailability(null);
|
setSelectedAvailability(null);
|
||||||
};
|
};
|
||||||
@ -327,47 +379,88 @@ export default function AvailabilityPage() {
|
|||||||
<div className="space-y-6 flex-1 overflow-y-auto p-6">
|
<div className="space-y-6 flex-1 overflow-y-auto p-6">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-gray-900">Definir Disponibilidade</h1>
|
<h1 className="text-2xl font-bold">
|
||||||
<p className="text-gray-600">Defina sua disponibilidade para consultas </p>
|
Definir Disponibilidade
|
||||||
|
</h1>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
Defina sua disponibilidade para consultas{" "}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<form className="space-y-6" onSubmit={handleSubmit}>
|
<form className="space-y-6" onSubmit={handleSubmit}>
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
<div className="bg-card rounded-lg border p-6">
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Dados </h2>
|
<h2 className="text-lg font-semibold mb-6">Dados </h2>
|
||||||
|
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
{/* **AJUSTE DE RESPONSIVIDADE: DIAS DA SEMANA** */}
|
{/* **AJUSTE DE RESPONSIVIDADE: DIAS DA SEMANA** */}
|
||||||
<div>
|
<div>
|
||||||
<Label className="text-sm font-medium text-gray-700">Dia Da Semana</Label>
|
<Label className="text-sm font-medium">
|
||||||
|
Dia Da Semana
|
||||||
|
</Label>
|
||||||
{/* O antigo 'flex gap-4 mt-2 flex-nowrap' foi substituído por um grid responsivo: */}
|
{/* 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">
|
<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">
|
<label className="flex items-center gap-1">
|
||||||
<input type="radio" name="weekday" value="monday" className="text-blue-600" />
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="weekday"
|
||||||
|
value="monday"
|
||||||
|
className="text-primary"
|
||||||
|
/>
|
||||||
<span className="whitespace-nowrap text-sm">Segunda</span>
|
<span className="whitespace-nowrap text-sm">Segunda</span>
|
||||||
</label>
|
</label>
|
||||||
<label className="flex items-center gap-1">
|
<label className="flex items-center gap-1">
|
||||||
<input type="radio" name="weekday" value="tuesday" className="text-blue-600" />
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="weekday"
|
||||||
|
value="tuesday"
|
||||||
|
className="text-primary"
|
||||||
|
/>
|
||||||
<span className="whitespace-nowrap text-sm">Terça</span>
|
<span className="whitespace-nowrap text-sm">Terça</span>
|
||||||
</label>
|
</label>
|
||||||
<label className="flex items-center gap-1">
|
<label className="flex items-center gap-1">
|
||||||
<input type="radio" name="weekday" value="wednesday" className="text-blue-600" />
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="weekday"
|
||||||
|
value="wednesday"
|
||||||
|
className="text-primary"
|
||||||
|
/>
|
||||||
<span className="whitespace-nowrap text-sm">Quarta</span>
|
<span className="whitespace-nowrap text-sm">Quarta</span>
|
||||||
</label>
|
</label>
|
||||||
<label className="flex items-center gap-1">
|
<label className="flex items-center gap-1">
|
||||||
<input type="radio" name="weekday" value="thursday" className="text-blue-600" />
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="weekday"
|
||||||
|
value="thursday"
|
||||||
|
className="text-primary"
|
||||||
|
/>
|
||||||
<span className="whitespace-nowrap text-sm">Quinta</span>
|
<span className="whitespace-nowrap text-sm">Quinta</span>
|
||||||
</label>
|
</label>
|
||||||
<label className="flex items-center gap-1">
|
<label className="flex items-center gap-1">
|
||||||
<input type="radio" name="weekday" value="friday" className="text-blue-600" />
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="weekday"
|
||||||
|
value="friday"
|
||||||
|
className="text-primary"
|
||||||
|
/>
|
||||||
<span className="whitespace-nowrap text-sm">Sexta</span>
|
<span className="whitespace-nowrap text-sm">Sexta</span>
|
||||||
</label>
|
</label>
|
||||||
<label className="flex items-center gap-1">
|
<label className="flex items-center gap-1">
|
||||||
<input type="radio" name="weekday" value="saturday" className="text-blue-600" />
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="weekday"
|
||||||
|
value="saturday"
|
||||||
|
className="text-primary"
|
||||||
|
/>
|
||||||
<span className="whitespace-nowrap text-sm">Sábado</span>
|
<span className="whitespace-nowrap text-sm">Sábado</span>
|
||||||
</label>
|
</label>
|
||||||
<label className="flex items-center gap-1">
|
<label className="flex items-center gap-1">
|
||||||
<input type="radio" name="weekday" value="sunday" className="text-blue-600" />
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="weekday"
|
||||||
|
value="sunday"
|
||||||
|
className="text-primary"
|
||||||
|
/>
|
||||||
<span className="whitespace-nowrap text-sm">Domingo</span>
|
<span className="whitespace-nowrap text-sm">Domingo</span>
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
@ -377,31 +470,64 @@ export default function AvailabilityPage() {
|
|||||||
{/* Ajustado para 1 coluna em móvel, 2 em tablet e 5 em desktop (mantendo o que já existia com ajustes) */}
|
{/* 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 className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-6">
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="horarioEntrada" className="text-sm font-medium text-gray-700">
|
<Label
|
||||||
|
htmlFor="horarioEntrada"
|
||||||
|
className="text-sm font-medium"
|
||||||
|
>
|
||||||
Horario De Entrada
|
Horario De Entrada
|
||||||
</Label>
|
</Label>
|
||||||
<Input type="time" id="horarioEntrada" name="horarioEntrada" required className="mt-1" />
|
<Input
|
||||||
|
type="time"
|
||||||
|
id="horarioEntrada"
|
||||||
|
name="horarioEntrada"
|
||||||
|
required
|
||||||
|
className="mt-1"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="horarioSaida" className="text-sm font-medium text-gray-700">
|
<Label
|
||||||
|
htmlFor="horarioSaida"
|
||||||
|
className="text-sm font-medium"
|
||||||
|
>
|
||||||
Horario De Saida
|
Horario De Saida
|
||||||
</Label>
|
</Label>
|
||||||
<Input type="time" id="horarioSaida" name="horarioSaida" required className="mt-1" />
|
<Input
|
||||||
|
type="time"
|
||||||
|
id="horarioSaida"
|
||||||
|
name="horarioSaida"
|
||||||
|
required
|
||||||
|
className="mt-1"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="duracaoConsulta" className="text-sm font-medium text-gray-700">
|
<Label
|
||||||
Duração Da Consulta (min)
|
htmlFor="duracaoConsulta"
|
||||||
|
className="text-sm font-medium whitespace-nowrap"
|
||||||
|
>
|
||||||
|
Duração da Consulta(min)
|
||||||
</Label>
|
</Label>
|
||||||
<Input type="number" id="duracaoConsulta" name="duracaoConsulta" required className="mt-1" />
|
<Input
|
||||||
|
type="number"
|
||||||
|
id="duracaoConsulta"
|
||||||
|
name="duracaoConsulta"
|
||||||
|
required
|
||||||
|
className="mt-1"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
{/* O Select de modalidade fica fora deste grid para ocupar uma linha inteira em telas menores, como no original, garantindo clareza */}
|
{/* O Select de modalidade fica fora deste grid para ocupar uma linha inteira em telas menores, como no original, garantindo clareza */}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="modalidadeConsulta" className="text-sm font-medium text-gray-700">
|
<Label
|
||||||
|
htmlFor="modalidadeConsulta"
|
||||||
|
className="text-sm font-medium"
|
||||||
|
>
|
||||||
Modalidade De Consulta
|
Modalidade De Consulta
|
||||||
</Label>
|
</Label>
|
||||||
<Select onValueChange={(value) => setModalidadeConsulta(value)} value={modalidadeConsulta}>
|
<Select
|
||||||
|
onValueChange={(value) => setModalidadeConsulta(value)}
|
||||||
|
value={modalidadeConsulta}
|
||||||
|
>
|
||||||
<SelectTrigger className="mt-1">
|
<SelectTrigger className="mt-1">
|
||||||
<SelectValue placeholder="Selecione" />
|
<SelectValue placeholder="Selecione" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
@ -425,7 +551,7 @@ export default function AvailabilityPage() {
|
|||||||
<Link href="/doctor/dashboard" className="w-full sm:w-auto">
|
<Link href="/doctor/dashboard" className="w-full sm:w-auto">
|
||||||
<Button variant="outline" className="w-full sm:w-auto">Cancelar</Button>
|
<Button variant="outline" className="w-full sm:w-auto">Cancelar</Button>
|
||||||
</Link>
|
</Link>
|
||||||
<Button type="submit" className="bg-green-600 hover:bg-green-700 w-full sm:w-auto">
|
<Button type="submit" className="bg-primary hover:bg-primary/90 w-full sm:w-auto">
|
||||||
Salvar Disponibilidade
|
Salvar Disponibilidade
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
@ -445,15 +571,15 @@ export default function AvailabilityPage() {
|
|||||||
const times = schedule[day] || [];
|
const times = schedule[day] || [];
|
||||||
return (
|
return (
|
||||||
<div key={day} className="space-y-4">
|
<div key={day} className="space-y-4">
|
||||||
<div className="flex flex-col items-center justify-between p-3 bg-blue-50 rounded-lg h-full">
|
<div className="flex flex-col items-center justify-start p-3 bg-primary/10 rounded-lg min-h-[76px] ">
|
||||||
<p className="font-medium capitalize text-center mb-2">{weekdaysPT[day]}</p>
|
<p className="font-medium capitalize text-center ">{weekdaysPT[day]}</p>
|
||||||
<div className="text-center w-full">
|
<div className="text-center w-full mt-2">
|
||||||
{times.length > 0 ? (
|
{times.length > 0 ? (
|
||||||
times.map((t, i) => (
|
times.map((t, i) => (
|
||||||
<div key={i}>
|
<div key={i}>
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<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-muted-foreground cursor-pointer rounded hover:text-accent-foreground hover:bg-muted transition-colors duration-150">
|
||||||
{formatTime(t.start)} - {formatTime(t.end)}
|
{formatTime(t.start)} - {formatTime(t.end)}
|
||||||
</p>
|
</p>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
@ -464,7 +590,7 @@ export default function AvailabilityPage() {
|
|||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
onClick={() => openDeleteDialog(t, day)}
|
onClick={() => openDeleteDialog(t, day)}
|
||||||
className="text-red-600 focus:bg-red-50 focus:text-red-600">
|
className="text-destructive focus:bg-destructive/10 focus:text-destructive">
|
||||||
<Trash2 className="w-4 h-4 mr-2" />
|
<Trash2 className="w-4 h-4 mr-2" />
|
||||||
Excluir
|
Excluir
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
@ -473,7 +599,7 @@ export default function AvailabilityPage() {
|
|||||||
</div>
|
</div>
|
||||||
))
|
))
|
||||||
) : (
|
) : (
|
||||||
<p className="text-sm text-gray-400 italic">Sem horário</p>
|
<p className="text-sm text-muted-foreground italic">Sem horário</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -493,7 +619,7 @@ export default function AvailabilityPage() {
|
|||||||
</AlertDialogHeader>
|
</AlertDialogHeader>
|
||||||
<AlertDialogFooter>
|
<AlertDialogFooter>
|
||||||
<AlertDialogCancel>Cancelar</AlertDialogCancel>
|
<AlertDialogCancel>Cancelar</AlertDialogCancel>
|
||||||
<AlertDialogAction onClick={() => selectedAvailability && handleDeleteAvailability(selectedAvailability.id)} className="bg-red-600 hover:bg-red-700">
|
<AlertDialogAction onClick={() => selectedAvailability && handleDeleteAvailability(selectedAvailability.id)} className="bg-destructive hover:bg-destructive/90">
|
||||||
Excluir
|
Excluir
|
||||||
</AlertDialogAction>
|
</AlertDialogAction>
|
||||||
</AlertDialogFooter>
|
</AlertDialogFooter>
|
||||||
|
|||||||
@ -144,10 +144,6 @@ export default function EditarLaudoPage() {
|
|||||||
<CardContent>
|
<CardContent>
|
||||||
<form onSubmit={handleSubmit} className="space-y-6">
|
<form onSubmit={handleSubmit} className="space-y-6">
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="order_number">Nº do Pedido</Label>
|
|
||||||
<Input id="order_number" value={formData.order_number || ''} onChange={handleInputChange} />
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="exam">Exame</Label>
|
<Label htmlFor="exam">Exame</Label>
|
||||||
<Input id="exam" value={formData.exam || ''} onChange={handleInputChange} />
|
<Input id="exam" value={formData.exam || ''} onChange={handleInputChange} />
|
||||||
|
|||||||
@ -1,5 +1,4 @@
|
|||||||
|
"use client";
|
||||||
"use client";
|
|
||||||
|
|
||||||
import { useParams, useRouter } from "next/navigation";
|
import { useParams, useRouter } from "next/navigation";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
@ -106,10 +105,6 @@ export default function NovoLaudoPage() {
|
|||||||
<CardContent>
|
<CardContent>
|
||||||
<form onSubmit={handleSubmit} className="space-y-6">
|
<form onSubmit={handleSubmit} className="space-y-6">
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="order_number">Nº do Pedido</Label>
|
|
||||||
<Input id="order_number" value={formData.order_number} onChange={handleInputChange} />
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="exam">Exame</Label>
|
<Label htmlFor="exam">Exame</Label>
|
||||||
<Input id="exam" value={formData.exam} onChange={handleInputChange} />
|
<Input id="exam" value={formData.exam} onChange={handleInputChange} />
|
||||||
|
|||||||
@ -2,11 +2,23 @@
|
|||||||
|
|
||||||
import { useEffect, useState, useCallback } from "react";
|
import { useEffect, useState, useCallback } from "react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
import {
|
||||||
import { Eye, Edit, Calendar, Trash2, Loader2 } from "lucide-react";
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from "@/components/ui/dropdown-menu";
|
||||||
|
import { Eye, Edit, Calendar, Trash2, Loader2, MoreVertical, Filter } from "lucide-react";
|
||||||
import { api } from "@/services/api.mjs";
|
import { api } from "@/services/api.mjs";
|
||||||
import { PatientDetailsModal } from "@/components/ui/patient-details-modal";
|
import { PatientDetailsModal } from "@/components/ui/patient-details-modal";
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import Sidebar from "@/components/Sidebar";
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
@ -29,6 +41,9 @@ interface Paciente {
|
|||||||
complement?: string;
|
complement?: string;
|
||||||
neighborhood?: string;
|
neighborhood?: string;
|
||||||
cep?: string;
|
cep?: string;
|
||||||
|
// NOVOS CAMPOS PARA O FILTRO
|
||||||
|
convenio?: string;
|
||||||
|
vip?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function PacientesPage() {
|
export default function PacientesPage() {
|
||||||
@ -38,19 +53,44 @@ export default function PacientesPage() {
|
|||||||
const [selectedPatient, setSelectedPatient] = useState<Paciente | null>(null);
|
const [selectedPatient, setSelectedPatient] = useState<Paciente | null>(null);
|
||||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||||
|
|
||||||
// --- Lógica de Paginação INÍCIO ---
|
// --- ESTADOS DOS FILTROS ---
|
||||||
const [itemsPerPage, setItemsPerPage] = useState(5);
|
const [searchTerm, setSearchTerm] = useState("");
|
||||||
|
const [convenioFilter, setConvenioFilter] = useState("todos");
|
||||||
|
const [vipFilter, setVipFilter] = useState("todos");
|
||||||
|
|
||||||
|
// --- Lógica de Filtragem ---
|
||||||
|
const filteredPacientes = pacientes.filter((p) => {
|
||||||
|
// 1. Filtro de Texto (Nome ou Telefone)
|
||||||
|
const searchLower = searchTerm.toLowerCase();
|
||||||
|
const matchesSearch = p.nome?.toLowerCase().includes(searchLower) || p.telefone?.includes(searchLower);
|
||||||
|
|
||||||
|
// 2. Filtro de Convênio
|
||||||
|
// Se for "todos", passa. Se não, verifica se o convênio do paciente é igual ao selecionado.
|
||||||
|
const matchesConvenio = convenioFilter === "todos" || (p.convenio?.toLowerCase() === convenioFilter);
|
||||||
|
|
||||||
|
// 3. Filtro VIP
|
||||||
|
// Se for "todos", passa. Se não, verifica se o status VIP é igual ao selecionado.
|
||||||
|
const matchesVip = vipFilter === "todos" || (p.vip?.toLowerCase() === vipFilter);
|
||||||
|
|
||||||
|
return matchesSearch && matchesConvenio && matchesVip;
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Lógica de Paginação ---
|
||||||
|
const [itemsPerPage, setItemsPerPage] = useState(10);
|
||||||
const [currentPage, setCurrentPage] = useState(1);
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
|
|
||||||
const totalPages = Math.ceil(pacientes.length / itemsPerPage);
|
// Resetar página quando qualquer filtro mudar
|
||||||
|
useEffect(() => {
|
||||||
|
setCurrentPage(1);
|
||||||
|
}, [searchTerm, convenioFilter, vipFilter, itemsPerPage]);
|
||||||
|
|
||||||
|
const totalPages = Math.ceil(filteredPacientes.length / itemsPerPage);
|
||||||
const indexOfLastItem = currentPage * itemsPerPage;
|
const indexOfLastItem = currentPage * itemsPerPage;
|
||||||
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
||||||
const currentItems = pacientes.slice(indexOfFirstItem, indexOfLastItem);
|
const currentItems = filteredPacientes.slice(indexOfFirstItem, indexOfLastItem);
|
||||||
|
|
||||||
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
|
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
|
||||||
|
|
||||||
// Funções de Navegação
|
|
||||||
const goToPrevPage = () => {
|
const goToPrevPage = () => {
|
||||||
setCurrentPage((prev) => Math.max(1, prev - 1));
|
setCurrentPage((prev) => Math.max(1, prev - 1));
|
||||||
};
|
};
|
||||||
@ -59,7 +99,6 @@ export default function PacientesPage() {
|
|||||||
setCurrentPage((prev) => Math.min(totalPages, prev + 1));
|
setCurrentPage((prev) => Math.min(totalPages, prev + 1));
|
||||||
};
|
};
|
||||||
|
|
||||||
// Lógica para gerar os números das páginas visíveis (máximo de 5)
|
|
||||||
const getVisiblePageNumbers = (totalPages: number, currentPage: number) => {
|
const getVisiblePageNumbers = (totalPages: number, currentPage: number) => {
|
||||||
const pages: number[] = [];
|
const pages: number[] = [];
|
||||||
const maxVisiblePages = 5;
|
const maxVisiblePages = 5;
|
||||||
@ -84,13 +123,10 @@ export default function PacientesPage() {
|
|||||||
|
|
||||||
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) => {
|
const handleItemsPerPageChange = (value: string) => {
|
||||||
setItemsPerPage(Number(value));
|
setItemsPerPage(Number(value));
|
||||||
setCurrentPage(1);
|
setCurrentPage(1);
|
||||||
};
|
};
|
||||||
// --- Lógica de Paginação FIM ---
|
|
||||||
|
|
||||||
|
|
||||||
const handleOpenModal = (patient: Paciente) => {
|
const handleOpenModal = (patient: Paciente) => {
|
||||||
setSelectedPatient(patient);
|
setSelectedPatient(patient);
|
||||||
@ -108,7 +144,7 @@ export default function PacientesPage() {
|
|||||||
const date = new Date(dateString);
|
const date = new Date(dateString);
|
||||||
return new Intl.DateTimeFormat("pt-BR").format(date);
|
return new Intl.DateTimeFormat("pt-BR").format(date);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return dateString; // Retorna o string original se o formato for inválido
|
return dateString;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -130,7 +166,7 @@ export default function PacientesPage() {
|
|||||||
cidade: p.city ?? "N/A",
|
cidade: p.city ?? "N/A",
|
||||||
estado: p.state ?? "N/A",
|
estado: p.state ?? "N/A",
|
||||||
ultimoAtendimento: formatDate(p.created_at),
|
ultimoAtendimento: formatDate(p.created_at),
|
||||||
proximoAtendimento: "N/A", // Necessita de lógica de agendamento real
|
proximoAtendimento: "N/A",
|
||||||
email: p.email ?? "N/A",
|
email: p.email ?? "N/A",
|
||||||
birth_date: p.birth_date ?? "N/A",
|
birth_date: p.birth_date ?? "N/A",
|
||||||
cpf: p.cpf ?? "N/A",
|
cpf: p.cpf ?? "N/A",
|
||||||
@ -142,10 +178,14 @@ export default function PacientesPage() {
|
|||||||
complement: p.complement ?? "N/A",
|
complement: p.complement ?? "N/A",
|
||||||
neighborhood: p.neighborhood ?? "N/A",
|
neighborhood: p.neighborhood ?? "N/A",
|
||||||
cep: p.cep ?? "N/A",
|
cep: p.cep ?? "N/A",
|
||||||
|
|
||||||
|
// ⚠️ ATENÇÃO: Verifique o nome real desses campos na sua API
|
||||||
|
// Se a API não retorna, estou colocando valores padrão para teste
|
||||||
|
convenio: p.insurance_plan || p.convenio || "Unimed", // Exemplo: mapeie o campo correto
|
||||||
|
vip: p.is_vip ? "Sim" : "Não", // Exemplo: se for booleano converta para string
|
||||||
}));
|
}));
|
||||||
|
|
||||||
setPacientes(mapped);
|
setPacientes(mapped);
|
||||||
setCurrentPage(1); // Resetar a página ao carregar novos dados
|
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
console.error("Erro ao carregar pacientes:", e);
|
console.error("Erro ao carregar pacientes:", e);
|
||||||
setError(e?.message || "Erro ao carregar pacientes");
|
setError(e?.message || "Erro ao carregar pacientes");
|
||||||
@ -161,23 +201,73 @@ export default function PacientesPage() {
|
|||||||
return (
|
return (
|
||||||
<Sidebar>
|
<Sidebar>
|
||||||
<div className="space-y-6 px-2 sm:px-4 md:px-6">
|
<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">
|
||||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3"> {/* Ajustado para flex-col em telas pequenas */}
|
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-foreground">Pacientes</h1>
|
<h1 className="text-2xl font-bold text-foreground">Pacientes</h1>
|
||||||
<p className="text-muted-foreground text-sm sm:text-base">
|
<p className="text-muted-foreground text-sm sm:text-base">
|
||||||
Lista de pacientes vinculados
|
Lista de pacientes vinculados
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
{/* Controles de filtro e novo paciente */}
|
</div>
|
||||||
{/* 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">
|
{/* --- BARRA DE PESQUISA COM FILTROS ATIVOS --- */}
|
||||||
|
<div className="flex flex-col md:flex-row gap-4 items-center p-2 border border-border rounded-lg bg-card shadow-sm">
|
||||||
|
|
||||||
|
{/* Input de Busca */}
|
||||||
|
<div className="flex items-center gap-3 flex-1 w-full px-2">
|
||||||
|
<Filter className="w-5 h-5 text-muted-foreground flex-shrink-0" />
|
||||||
|
<Input
|
||||||
|
type="text"
|
||||||
|
placeholder="Buscar por nome ou telefone..."
|
||||||
|
value={searchTerm}
|
||||||
|
onChange={(e) => setSearchTerm(e.target.value)}
|
||||||
|
className="border-0 focus-visible:ring-0 shadow-none bg-transparent px-0 h-auto text-base placeholder:text-muted-foreground"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Filtros e Paginação */}
|
||||||
|
<div className="flex flex-wrap items-center gap-4 w-full md:w-auto px-2 border-t md:border-t-0 md:border-l border-border pt-2 md:pt-0 justify-end">
|
||||||
|
|
||||||
|
{/* FILTRO CONVÊNIO */}
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-sm font-medium whitespace-nowrap text-muted-foreground hidden lg:inline">Convênio</span>
|
||||||
|
<Select value={convenioFilter} onValueChange={setConvenioFilter}>
|
||||||
|
<SelectTrigger className="w-[100px] h-8 border-border bg-transparent focus:ring-0">
|
||||||
|
<SelectValue placeholder="Todos" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="todos">Todos</SelectItem>
|
||||||
|
{/* Certifique-se que o 'value' aqui seja minúsculo para bater com a lógica do filtro */}
|
||||||
|
<SelectItem value="unimed">Unimed</SelectItem>
|
||||||
|
<SelectItem value="bradesco">Bradesco</SelectItem>
|
||||||
|
<SelectItem value="particular">Particular</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* FILTRO VIP */}
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-sm font-medium whitespace-nowrap text-muted-foreground hidden lg:inline">VIP</span>
|
||||||
|
<Select value={vipFilter} onValueChange={setVipFilter}>
|
||||||
|
<SelectTrigger className="w-[90px] h-8 border-border bg-transparent focus:ring-0">
|
||||||
|
<SelectValue placeholder="Todos" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="todos">Todos</SelectItem>
|
||||||
|
<SelectItem value="sim">Sim</SelectItem>
|
||||||
|
<SelectItem value="não">Não</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* PAGINAÇÃO */}
|
||||||
|
<div className="flex items-center gap-2 pl-2 md:border-l border-border">
|
||||||
<Select
|
<Select
|
||||||
onValueChange={handleItemsPerPageChange}
|
onValueChange={handleItemsPerPageChange}
|
||||||
defaultValue={String(itemsPerPage)}
|
defaultValue={String(itemsPerPage)}
|
||||||
>
|
>
|
||||||
<SelectTrigger className="w-full sm:w-[140px]">
|
<SelectTrigger className="w-[130px] h-8 border-border bg-transparent focus:ring-0">
|
||||||
<SelectValue placeholder="Itens por pág." />
|
<SelectValue placeholder="Paginação" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="5">5 por página</SelectItem>
|
<SelectItem value="5">5 por página</SelectItem>
|
||||||
@ -185,37 +275,23 @@ export default function PacientesPage() {
|
|||||||
<SelectItem value="20">20 por página</SelectItem>
|
<SelectItem value="20">20 por página</SelectItem>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
<Link href="/doctor/pacientes/novo" className="w-full sm:w-auto">
|
</div>
|
||||||
<Button variant="default" className="bg-green-600 hover:bg-green-700 w-full sm:w-auto">
|
|
||||||
Novo Paciente
|
|
||||||
</Button>
|
|
||||||
</Link>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Tabela de Dados */}
|
||||||
<div className="bg-card rounded-lg border border-border overflow-hidden shadow-md">
|
<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">
|
||||||
<div className="overflow-x-auto hidden md:block"> {/* Esconde em telas pequenas */}
|
|
||||||
<table className="min-w-[600px] w-full">
|
<table className="min-w-[600px] w-full">
|
||||||
<thead className="bg-muted border-b border-border">
|
<thead className="bg-muted border-b border-border">
|
||||||
<tr>
|
<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">Nome</th>
|
||||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground">
|
<th className="text-left p-3 sm:p-4 font-medium text-foreground">Telefone</th>
|
||||||
Telefone
|
{/* Coluna Convênio visível para teste */}
|
||||||
</th>
|
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden lg:table-cell">Convênio</th>
|
||||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden lg:table-cell">
|
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden lg:table-cell">VIP</th>
|
||||||
Cidade
|
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden xl:table-cell">Último atendimento</th>
|
||||||
</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>
|
<th className="text-left p-3 sm:p-4 font-medium text-foreground">Ações</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
@ -231,40 +307,27 @@ export default function PacientesPage() {
|
|||||||
<tr>
|
<tr>
|
||||||
<td colSpan={7} className="p-6 text-red-600 text-center">{`Erro: ${error}`}</td>
|
<td colSpan={7} className="p-6 text-red-600 text-center">{`Erro: ${error}`}</td>
|
||||||
</tr>
|
</tr>
|
||||||
) : pacientes.length === 0 ? (
|
) : filteredPacientes.length === 0 ? (
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan={7} className="p-8 text-center text-muted-foreground">
|
<td colSpan={7} className="p-8 text-center text-muted-foreground">
|
||||||
Nenhum paciente encontrado
|
Nenhum paciente encontrado com esses filtros.
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
) : (
|
) : (
|
||||||
currentItems.map((p) => (
|
currentItems.map((p) => (
|
||||||
<tr
|
<tr key={p.id} className="border-b border-border hover:bg-accent/40 transition-colors">
|
||||||
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">{p.nome}</td>
|
||||||
<td className="p-3 sm:p-4 text-muted-foreground">
|
<td className="p-3 sm:p-4 text-muted-foreground">{p.telefone}</td>
|
||||||
{p.telefone}
|
<td className="p-3 sm:p-4 text-muted-foreground hidden lg:table-cell">{p.convenio}</td>
|
||||||
</td>
|
<td className="p-3 sm:p-4 text-muted-foreground hidden lg:table-cell">{p.vip}</td>
|
||||||
<td className="p-3 sm:p-4 text-muted-foreground hidden lg:table-cell">
|
<td className="p-3 sm:p-4 text-muted-foreground hidden xl:table-cell">{p.ultimoAtendimento}</td>
|
||||||
{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">
|
<td className="p-3 sm:p-4">
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<button className="text-primary hover:underline text-sm sm:text-base">
|
<Button variant="ghost" className="h-8 w-8 p-0">
|
||||||
Ações
|
<span className="sr-only">Abrir menu</span>
|
||||||
</button>
|
<MoreVertical className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
<DropdownMenuItem onClick={() => handleOpenModal(p)}>
|
<DropdownMenuItem onClick={() => handleOpenModal(p)}>
|
||||||
@ -272,26 +335,11 @@ export default function PacientesPage() {
|
|||||||
Ver detalhes
|
Ver detalhes
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem asChild>
|
<DropdownMenuItem asChild>
|
||||||
<Link href={`/doctor/pacientes/${p.id}/laudos`}>
|
<Link href={`/doctor/medicos/${p.id}/laudos`}>
|
||||||
<Edit className="w-4 h-4 mr-2" />
|
<Edit className="w-4 h-4 mr-2" />
|
||||||
Laudos
|
Laudos
|
||||||
</Link>
|
</Link>
|
||||||
</DropdownMenuItem>
|
</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>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
</td>
|
</td>
|
||||||
@ -302,29 +350,26 @@ export default function PacientesPage() {
|
|||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Layout em Cards/Lista para Telas Pequenas */}
|
{/* Cards para Mobile */}
|
||||||
<div className="md:hidden divide-y divide-border"> {/* Visível apenas em telas pequenas */}
|
<div className="md:hidden divide-y divide-border">
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="p-6 text-muted-foreground text-center">
|
<div className="p-6 text-muted-foreground text-center">
|
||||||
<Loader2 className="w-6 h-6 animate-spin mx-auto text-primary" />
|
<Loader2 className="w-6 h-6 animate-spin mx-auto text-primary" />
|
||||||
Carregando pacientes...
|
Carregando...
|
||||||
</div>
|
</div>
|
||||||
) : error ? (
|
) : filteredPacientes.length === 0 ? (
|
||||||
<div className="p-6 text-red-600 text-center">{`Erro: ${error}`}</div>
|
|
||||||
) : pacientes.length === 0 ? (
|
|
||||||
<div className="p-8 text-center text-muted-foreground">
|
<div className="p-8 text-center text-muted-foreground">
|
||||||
Nenhum paciente encontrado
|
Nenhum paciente encontrado.
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
currentItems.map((p) => (
|
currentItems.map((p) => (
|
||||||
<div key={p.id} className="flex items-center justify-between p-4 hover:bg-accent/40 transition-colors">
|
<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="flex-1 min-w-0 pr-4">
|
||||||
<div className="text-base font-semibold text-foreground break-words"> {/* Aumentado a fonte e break-words para evitar corte do nome */}
|
<div className="text-base font-semibold text-foreground break-words">
|
||||||
{p.nome || "—"}
|
{p.nome || "—"}
|
||||||
</div>
|
</div>
|
||||||
{/* Removido o 'truncate' e adicionado 'break-words' no telefone */}
|
<div className="text-sm text-muted-foreground">
|
||||||
<div className="text-sm text-muted-foreground break-words">
|
{p.telefone} | {p.convenio} | VIP: {p.vip}
|
||||||
Telefone: **{p.telefone || "N/A"}**
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="ml-4 flex-shrink-0">
|
<div className="ml-4 flex-shrink-0">
|
||||||
@ -345,21 +390,6 @@ export default function PacientesPage() {
|
|||||||
Laudos
|
Laudos
|
||||||
</Link>
|
</Link>
|
||||||
</DropdownMenuItem>
|
</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>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
</div>
|
</div>
|
||||||
@ -368,12 +398,9 @@ export default function PacientesPage() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
{/* Paginação */}
|
{/* Paginação */}
|
||||||
{totalPages > 1 && (
|
{totalPages > 1 && (
|
||||||
<div className="flex flex-wrap justify-center items-center gap-2 border-t border-border p-4 bg-muted/40">
|
<div className="flex flex-wrap justify-center items-center gap-2 border-t border-border p-4 bg-muted/40">
|
||||||
|
|
||||||
{/* Botão Anterior */}
|
|
||||||
<button
|
<button
|
||||||
onClick={goToPrevPage}
|
onClick={goToPrevPage}
|
||||||
disabled={currentPage === 1}
|
disabled={currentPage === 1}
|
||||||
@ -382,14 +409,13 @@ export default function PacientesPage() {
|
|||||||
{"< Anterior"}
|
{"< Anterior"}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{/* Números das Páginas */}
|
|
||||||
{visiblePageNumbers.map((number) => (
|
{visiblePageNumbers.map((number) => (
|
||||||
<button
|
<button
|
||||||
key={number}
|
key={number}
|
||||||
onClick={() => paginate(number)}
|
onClick={() => paginate(number)}
|
||||||
className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border border-border ${
|
className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border border-border ${
|
||||||
currentPage === number
|
currentPage === number
|
||||||
? "bg-green-600 text-primary-foreground shadow-md border-green-600"
|
? "bg-blue-600 text-primary-foreground shadow-md border-blue-600"
|
||||||
: "bg-secondary text-secondary-foreground hover:bg-secondary/80"
|
: "bg-secondary text-secondary-foreground hover:bg-secondary/80"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
@ -397,7 +423,6 @@ export default function PacientesPage() {
|
|||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
|
|
||||||
{/* Botão Próximo */}
|
|
||||||
<button
|
<button
|
||||||
onClick={goToNextPage}
|
onClick={goToNextPage}
|
||||||
disabled={currentPage === totalPages}
|
disabled={currentPage === totalPages}
|
||||||
@ -405,7 +430,6 @@ export default function PacientesPage() {
|
|||||||
>
|
>
|
||||||
{"Próximo >"}
|
{"Próximo >"}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -1,8 +1,6 @@
|
|||||||
@import 'tailwindcss';
|
@import "tailwindcss";
|
||||||
@import 'tw-animate-css';
|
@import "tw-animate-css";
|
||||||
|
|
||||||
@custom-variant dark (&:is(.dark *));
|
@custom-variant dark (&:is(.dark *));
|
||||||
|
|
||||||
:root {
|
:root {
|
||||||
--background: oklch(1 0 0);
|
--background: oklch(1 0 0);
|
||||||
--foreground: oklch(0.145 0 0);
|
--foreground: oklch(0.145 0 0);
|
||||||
@ -18,8 +16,8 @@
|
|||||||
--muted-foreground: oklch(0.556 0 0);
|
--muted-foreground: oklch(0.556 0 0);
|
||||||
--accent: oklch(0.97 0 0);
|
--accent: oklch(0.97 0 0);
|
||||||
--accent-foreground: oklch(0.205 0 0);
|
--accent-foreground: oklch(0.205 0 0);
|
||||||
--destructive: oklch(0.577 0.245 27.325);
|
--destructive: oklch(0.637 0.237 25.331);
|
||||||
--destructive-foreground: oklch(0.577 0.245 27.325);
|
--destructive-foreground: oklch(0.985 0 0);
|
||||||
--border: oklch(0.922 0 0);
|
--border: oklch(0.922 0 0);
|
||||||
--input: oklch(0.922 0 0);
|
--input: oklch(0.922 0 0);
|
||||||
--ring: oklch(0.708 0 0);
|
--ring: oklch(0.708 0 0);
|
||||||
@ -54,8 +52,8 @@
|
|||||||
--muted-foreground: oklch(0.708 0 0);
|
--muted-foreground: oklch(0.708 0 0);
|
||||||
--accent: oklch(0.269 0 0);
|
--accent: oklch(0.269 0 0);
|
||||||
--accent-foreground: oklch(0.985 0 0);
|
--accent-foreground: oklch(0.985 0 0);
|
||||||
--destructive: oklch(0.396 0.141 25.723);
|
--destructive: oklch(0.7 0.25 25);
|
||||||
--destructive-foreground: oklch(0.637 0.237 25.331);
|
--destructive-foreground: oklch(0.985 0 0);
|
||||||
--border: oklch(0.269 0 0);
|
--border: oklch(0.269 0 0);
|
||||||
--input: oklch(0.269 0 0);
|
--input: oklch(0.269 0 0);
|
||||||
--ring: oklch(0.439 0 0);
|
--ring: oklch(0.439 0 0);
|
||||||
@ -89,7 +87,7 @@
|
|||||||
--muted-foreground: oklch(1 0.5 100);
|
--muted-foreground: oklch(1 0.5 100);
|
||||||
--accent: oklch(0 0 0);
|
--accent: oklch(0 0 0);
|
||||||
--accent-foreground: oklch(1 0.5 100);
|
--accent-foreground: oklch(1 0.5 100);
|
||||||
--destructive: oklch(0.5 0.3 30);
|
--destructive: oklch(0.8 0.5 25);
|
||||||
--destructive-foreground: oklch(0 0 0);
|
--destructive-foreground: oklch(0 0 0);
|
||||||
--border: oklch(1 0.5 100);
|
--border: oklch(1 0.5 100);
|
||||||
--input: oklch(0 0 0);
|
--input: oklch(0 0 0);
|
||||||
|
|||||||
@ -4,11 +4,7 @@ import { GeistMono } from "geist/font/mono";
|
|||||||
import { Analytics } from "@vercel/analytics/next";
|
import { Analytics } from "@vercel/analytics/next";
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
import { Toaster } from "@/components/ui/toaster";
|
import { Toaster } from "@/components/ui/toaster";
|
||||||
// [PASSO 1.2] - Importando o nosso provider
|
import { Providers } from "./providers";
|
||||||
import { AppointmentsProvider } from "./context/AppointmentsContext";
|
|
||||||
import { AccessibilityProvider } from "./context/AccessibilityContext";
|
|
||||||
import { AccessibilityModal } from "@/components/accessibility-modal";
|
|
||||||
import { ThemeInitializer } from "@/components/theme-initializer";
|
|
||||||
|
|
||||||
export default function RootLayout({
|
export default function RootLayout({
|
||||||
children,
|
children,
|
||||||
@ -18,12 +14,7 @@ export default function RootLayout({
|
|||||||
return (
|
return (
|
||||||
<html lang="en" suppressHydrationWarning>
|
<html lang="en" suppressHydrationWarning>
|
||||||
<body className={`font-sans ${GeistSans.variable} ${GeistMono.variable}`}>
|
<body className={`font-sans ${GeistSans.variable} ${GeistMono.variable}`}>
|
||||||
{/* [PASSO 1.2] - Envolvendo a aplicação com o provider */}
|
<Providers>{children}</Providers>
|
||||||
<ThemeInitializer />
|
|
||||||
<AccessibilityProvider>
|
|
||||||
<AppointmentsProvider>{children}</AppointmentsProvider>
|
|
||||||
<AccessibilityModal />
|
|
||||||
</AccessibilityProvider>
|
|
||||||
<Analytics />
|
<Analytics />
|
||||||
<Toaster />
|
<Toaster />
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@ -97,7 +97,7 @@ export default function LoginPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* O contêiner principal que agora terá a sombra e o estilo de card */}
|
{/* O contêiner principal que agora terá a sombra e o estilo de card */}
|
||||||
<div className="w-full max-w-md bg-card p-10 rounded-2xl shadow-xl">
|
<div className="w-full max-w-md bg-card p-10 rounded-2xl shadow-xl border-2 border-border mt-8">
|
||||||
{/* NOVO: Bloco da Logo e Nome (Painel Esquerdo) */}
|
{/* NOVO: Bloco da Logo e Nome (Painel Esquerdo) */}
|
||||||
<div className="flex items-center justify-center space-x-3 mb-8">
|
<div className="flex items-center justify-center space-x-3 mb-8">
|
||||||
<img
|
<img
|
||||||
@ -138,7 +138,7 @@ export default function LoginPage() {
|
|||||||
Não tem uma conta de paciente?{" "}
|
Não tem uma conta de paciente?{" "}
|
||||||
</span>
|
</span>
|
||||||
<Link href="/patient/register">
|
<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
|
Crie uma agora
|
||||||
</span>
|
</span>
|
||||||
</Link>
|
</Link>
|
||||||
@ -155,6 +155,7 @@ export default function LoginPage() {
|
|||||||
fill
|
fill
|
||||||
style={{ objectFit: "cover" }}
|
style={{ objectFit: "cover" }}
|
||||||
priority
|
priority
|
||||||
|
className="dark:opacity-80"
|
||||||
/>
|
/>
|
||||||
{/* Camada de sobreposição para escurecer a imagem e destacar o texto */}
|
{/* Camada de sobreposição para escurecer a imagem e destacar o texto */}
|
||||||
<div className="absolute inset-0 bg-primary/80 flex flex-col items-start justify-end p-12 text-left">
|
<div className="absolute inset-0 bg-primary/80 flex flex-col items-start justify-end p-12 text-left">
|
||||||
@ -232,18 +233,21 @@ export default function LoginPage() {
|
|||||||
|
|
||||||
{/* Botões */}
|
{/* Botões */}
|
||||||
<div className="flex gap-3 pt-2">
|
<div className="flex gap-3 pt-2">
|
||||||
|
{/* Botão Cancelar – Azul contornado */}
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
onClick={closeModal}
|
onClick={closeModal}
|
||||||
disabled={isLoading}
|
disabled={isLoading}
|
||||||
className="flex-1"
|
className="flex-1 bg-blue-600 hover:bg-blue-700 text-white"
|
||||||
>
|
>
|
||||||
Cancelar
|
Cancelar
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
|
{/* Botão Resetar Senha – Azul sólido */}
|
||||||
<Button
|
<Button
|
||||||
onClick={handleResetPassword}
|
onClick={handleResetPassword}
|
||||||
disabled={isLoading}
|
disabled={isLoading}
|
||||||
className="flex-1"
|
className="flex-1 bg-blue-600 hover:bg-blue-700 text-white"
|
||||||
>
|
>
|
||||||
{isLoading ? "Enviando..." : "Resetar Senha"}
|
{isLoading ? "Enviando..." : "Resetar Senha"}
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@ -1,13 +1,20 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
import {
|
||||||
|
Card,
|
||||||
|
CardContent,
|
||||||
|
CardDescription,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from "@/components/ui/card";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Calendar, Clock, Plus, User } from "lucide-react";
|
import { Clock, Plus, User } from "lucide-react"; // Removi 'Calendar' que não estava sendo usado
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import React, { useState, useEffect } from "react";
|
import React, { useState, useEffect } from "react";
|
||||||
import { usersService } from "services/usersApi.mjs";
|
import { usersService } from "services/usersApi.mjs";
|
||||||
import { doctorsService } from "services/doctorsApi.mjs";
|
import { doctorsService } from "services/doctorsApi.mjs";
|
||||||
import Sidebar from "@/components/Sidebar";
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
import { api } from "services/api.mjs"; // <-- ADICIONEI ESTE IMPORT
|
||||||
|
|
||||||
export default function ManagerDashboard() {
|
export default function ManagerDashboard() {
|
||||||
// 🔹 Estados para usuários
|
// 🔹 Estados para usuários
|
||||||
@ -18,16 +25,44 @@ export default function ManagerDashboard() {
|
|||||||
const [doctors, setDoctors] = useState<any[]>([]);
|
const [doctors, setDoctors] = useState<any[]>([]);
|
||||||
const [loadingDoctors, setLoadingDoctors] = useState(true);
|
const [loadingDoctors, setLoadingDoctors] = useState(true);
|
||||||
|
|
||||||
// 🔹 Buscar primeiro usuário
|
// 🔹 Buscar primeiro usuário (LÓGICA ATUALIZADA)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
async function fetchFirstUser() {
|
async function fetchFirstUser() {
|
||||||
|
setLoadingUser(true); // Garante que o estado de loading inicie como true
|
||||||
try {
|
try {
|
||||||
const data = await usersService.list_roles();
|
// 1. Busca a lista de usuários com seus cargos (roles)
|
||||||
if (Array.isArray(data) && data.length > 0) {
|
const rolesData = await usersService.list_roles();
|
||||||
setFirstUser(data[0]);
|
|
||||||
|
// 2. Verifica se a lista não está vazia
|
||||||
|
if (Array.isArray(rolesData) && rolesData.length > 0) {
|
||||||
|
const firstUserRole = rolesData[0];
|
||||||
|
const firstUserId = firstUserRole.user_id;
|
||||||
|
|
||||||
|
if (!firstUserId) {
|
||||||
|
throw new Error("O primeiro usuário da lista não possui um ID válido.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Usa o ID para buscar o perfil (com nome e email) do usuário
|
||||||
|
const profileData = await api.get(
|
||||||
|
`/rest/v1/profiles?select=full_name,email&id=eq.${firstUserId}`
|
||||||
|
);
|
||||||
|
|
||||||
|
// 4. Verifica se o perfil foi encontrado
|
||||||
|
if (Array.isArray(profileData) && profileData.length > 0) {
|
||||||
|
const userProfile = profileData[0];
|
||||||
|
// 5. Combina os dados do cargo e do perfil e atualiza o estado
|
||||||
|
setFirstUser({
|
||||||
|
...firstUserRole,
|
||||||
|
...userProfile
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// Se não encontrar o perfil, exibe os dados que temos
|
||||||
|
setFirstUser(firstUserRole);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Erro ao carregar usuário:", error);
|
console.error("Erro ao carregar usuário:", error);
|
||||||
|
setFirstUser(null); // Limpa o usuário em caso de erro
|
||||||
} finally {
|
} finally {
|
||||||
setLoadingUser(false);
|
setLoadingUser(false);
|
||||||
}
|
}
|
||||||
@ -59,42 +94,42 @@ export default function ManagerDashboard() {
|
|||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
{/* Cabeçalho */}
|
{/* Cabeçalho */}
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
|
<h1 className="text-3xl font-bold">Dashboard</h1>
|
||||||
<p className="text-gray-600">Bem-vindo ao seu portal de consultas médicas</p>
|
<p className="text-muted-foreground">
|
||||||
|
Bem-vindo ao seu portal de consultas médicas
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Cards principais */}
|
{/* Cards principais */}
|
||||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||||
{/* Card 1 */}
|
|
||||||
<Card>
|
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
|
||||||
<CardTitle className="text-sm font-medium">Relatórios gerenciais</CardTitle>
|
|
||||||
<Calendar className="h-4 w-4 text-muted-foreground" />
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<div className="text-2xl font-bold">0</div>
|
|
||||||
<p className="text-xs text-muted-foreground">Relatórios disponíveis</p>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* Card 2 — Gestão de usuários */}
|
{/* Card 2 — Gestão de usuários */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||||
<CardTitle className="text-sm font-medium">Gestão de usuários</CardTitle>
|
<CardTitle className="text-sm font-medium">
|
||||||
|
Gestão de usuários
|
||||||
|
</CardTitle>
|
||||||
<Clock className="h-4 w-4 text-muted-foreground" />
|
<Clock className="h-4 w-4 text-muted-foreground" />
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
{loadingUser ? (
|
{loadingUser ? (
|
||||||
<div className="text-gray-500 text-sm">Carregando usuário...</div>
|
<div className="text-muted-foreground text-sm">
|
||||||
|
Carregando usuário...
|
||||||
|
</div>
|
||||||
) : firstUser ? (
|
) : firstUser ? (
|
||||||
<>
|
<>
|
||||||
<div className="text-2xl font-bold">{firstUser.full_name || "Sem nome"}</div>
|
<div className="text-2xl font-bold">
|
||||||
|
{firstUser.full_name || "Sem nome"}
|
||||||
|
</div>
|
||||||
<p className="text-xs text-muted-foreground">
|
<p className="text-xs text-muted-foreground">
|
||||||
{firstUser.email || "Sem e-mail cadastrado"}
|
{firstUser.email || "Sem e-mail cadastrado"}
|
||||||
</p>
|
</p>
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<div className="text-sm text-gray-500">Nenhum usuário encontrado</div>
|
<div className="text-sm text-muted-foreground">
|
||||||
|
Nenhum usuário encontrado
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
@ -118,7 +153,9 @@ export default function ManagerDashboard() {
|
|||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Ações Rápidas</CardTitle>
|
<CardTitle>Ações Rápidas</CardTitle>
|
||||||
<CardDescription>Acesse rapidamente as principais funcionalidades</CardDescription>
|
<CardDescription>
|
||||||
|
Acesse rapidamente as principais funcionalidades
|
||||||
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-4">
|
<CardContent className="space-y-4">
|
||||||
<Link href="/manager/home">
|
<Link href="/manager/home">
|
||||||
@ -128,19 +165,28 @@ export default function ManagerDashboard() {
|
|||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
<Link href="/manager/usuario">
|
<Link href="/manager/usuario">
|
||||||
<Button variant="outline" className="w-full justify-start bg-transparent">
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="w-full justify-start"
|
||||||
|
>
|
||||||
<User className="mr-2 h-4 w-4" />
|
<User className="mr-2 h-4 w-4" />
|
||||||
Usuários Cadastrados
|
Usuários Cadastrados
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
<Link href="/manager/home/novo">
|
<Link href="/manager/home/novo">
|
||||||
<Button variant="outline" className="w-full justify-start bg-transparent">
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="w-full justify-start"
|
||||||
|
>
|
||||||
<Plus className="mr-2 h-4 w-4" />
|
<Plus className="mr-2 h-4 w-4" />
|
||||||
Adicionar Novo Médico
|
Adicionar Novo Médico
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
<Link href="/manager/usuario/novo">
|
<Link href="/manager/usuario/novo">
|
||||||
<Button variant="outline" className="w-full justify-start bg-transparent">
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="w-full justify-start"
|
||||||
|
>
|
||||||
<Plus className="mr-2 h-4 w-4" />
|
<Plus className="mr-2 h-4 w-4" />
|
||||||
Criar novo Usuário
|
Criar novo Usuário
|
||||||
</Button>
|
</Button>
|
||||||
@ -152,28 +198,34 @@ export default function ManagerDashboard() {
|
|||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Gestão de Médicos</CardTitle>
|
<CardTitle>Gestão de Médicos</CardTitle>
|
||||||
<CardDescription>Médicos cadastrados recentemente</CardDescription>
|
<CardDescription>
|
||||||
|
Médicos cadastrados recentemente
|
||||||
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
{loadingDoctors ? (
|
{loadingDoctors ? (
|
||||||
<p className="text-sm text-gray-500">Carregando médicos...</p>
|
<p className="text-sm text-muted-foreground">Carregando médicos...</p>
|
||||||
) : doctors.length === 0 ? (
|
) : doctors.length === 0 ? (
|
||||||
<p className="text-sm text-gray-500">Nenhum médico cadastrado.</p>
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Nenhum médico cadastrado.
|
||||||
|
</p>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
{doctors.map((doc, index) => (
|
{doctors.map((doc, index) => (
|
||||||
<div
|
<div
|
||||||
key={index}
|
key={index}
|
||||||
className="flex items-center justify-between p-3 bg-green-50 rounded-lg border border-green-100"
|
className="flex items-center justify-between p-3 bg-secondary rounded-lg border"
|
||||||
>
|
>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-medium">{doc.full_name || "Sem nome"}</p>
|
<p className="font-medium">
|
||||||
<p className="text-sm text-gray-600">
|
{doc.full_name || "Sem nome"}
|
||||||
|
</p>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
{doc.specialty || "Sem especialidade"}
|
{doc.specialty || "Sem especialidade"}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-right">
|
<div className="text-right">
|
||||||
<p className="font-medium text-green-700">
|
<p className="font-medium text-primary">
|
||||||
{doc.active ? "Ativo" : "Inativo"}
|
{doc.active ? "Ativo" : "Inativo"}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
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-muted-foreground">Carregando dados...</div>
|
||||||
|
</Sidebar>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!doctors || !availabilities) {
|
||||||
|
return (
|
||||||
|
<Sidebar>
|
||||||
|
<div className="p-6 text-destructive 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">Disponibilidade dos Médicos</h1>
|
||||||
|
<p className="text-muted-foreground">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-muted-foreground font-medium">
|
||||||
|
Página {page} de {totalPages}
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<Button variant="outline" onClick={goNext} disabled={page === totalPages}>
|
||||||
|
Próxima
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Sidebar>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -209,8 +209,8 @@ export default function EditarMedicoPage() {
|
|||||||
return (
|
return (
|
||||||
<Sidebar>
|
<Sidebar>
|
||||||
<div className="flex justify-center items-center h-full w-full py-16">
|
<div className="flex justify-center items-center h-full w-full py-16">
|
||||||
<Loader2 className="w-8 h-8 animate-spin text-green-600" />
|
<Loader2 className="w-8 h-8 animate-spin text-primary" />
|
||||||
<p className="ml-2 text-gray-600">Carregando dados do médico...</p>
|
<p className="ml-2 text-muted-foreground">Carregando dados do médico...</p>
|
||||||
</div>
|
</div>
|
||||||
</Sidebar>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
@ -221,11 +221,11 @@ export default function EditarMedicoPage() {
|
|||||||
<div className="w-full space-y-6 p-4 md:p-8">
|
<div className="w-full space-y-6 p-4 md:p-8">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-gray-900">
|
<h1 className="text-2xl font-bold text-foreground">
|
||||||
Editar Médico: <span className="text-green-600">{formData.nomeCompleto}</span>
|
Editar Médico: <span className="text-primary">{formData.nomeCompleto}</span>
|
||||||
</h1>
|
</h1>
|
||||||
<p className="text-sm text-gray-500">
|
<p className="text-sm text-muted-foreground">
|
||||||
Atualize as informações do médico (ID: {id}).
|
Atualize as informações do médico
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<Link href="/manager/home">
|
<Link href="/manager/home">
|
||||||
@ -239,19 +239,19 @@ export default function EditarMedicoPage() {
|
|||||||
<form onSubmit={handleSubmit} className="space-y-6">
|
<form onSubmit={handleSubmit} className="space-y-6">
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
<div className="p-3 bg-red-100 text-red-700 rounded-lg border border-red-300">
|
<div className="p-3 rounded-lg border bg-destructive/10 text-destructive border-destructive/30">
|
||||||
<p className="font-medium">Erro na Atualização:</p>
|
<p className="font-medium">Erro na Atualização:</p>
|
||||||
<p className="text-sm">{error}</p>
|
<p className="text-sm">{error}</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="space-y-4 p-4 border rounded-xl shadow-sm bg-white">
|
<div className="space-y-4 p-4 rounded-xl border border-border shadow-sm bg-card">
|
||||||
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">
|
<h2 className="text-lg font-semibold text-foreground border-b border-border pb-2">
|
||||||
Dados Principais e Pessoais
|
Dados Principais e Pessoais
|
||||||
</h2>
|
</h2>
|
||||||
<div className="grid md:grid-cols-4 gap-4">
|
<div className="grid md:grid-cols-4 gap-4">
|
||||||
<div className="space-y-2 col-span-2">
|
<div className="space-y-2 col-span-2">
|
||||||
<Label htmlFor="nomeCompleto">Nome Completo (full_name)</Label>
|
<Label htmlFor="nomeCompleto">Nome Completo</Label>
|
||||||
<Input
|
<Input
|
||||||
id="nomeCompleto"
|
id="nomeCompleto"
|
||||||
value={formData.nomeCompleto}
|
value={formData.nomeCompleto}
|
||||||
@ -269,7 +269,7 @@ export default function EditarMedicoPage() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2 col-span-1">
|
<div className="space-y-2 col-span-1">
|
||||||
<Label htmlFor="crmEstado">UF do CRM (crm_uf)</Label>
|
<Label htmlFor="crmEstado">UF do CRM</Label>
|
||||||
<Select value={formData.crmEstado} onValueChange={(v) => handleInputChange("crmEstado", v)}>
|
<Select value={formData.crmEstado} onValueChange={(v) => handleInputChange("crmEstado", v)}>
|
||||||
<SelectTrigger id="crmEstado">
|
<SelectTrigger id="crmEstado">
|
||||||
<SelectValue placeholder="UF" />
|
<SelectValue placeholder="UF" />
|
||||||
@ -286,7 +286,7 @@ export default function EditarMedicoPage() {
|
|||||||
|
|
||||||
<div className="grid md:grid-cols-3 gap-4">
|
<div className="grid md:grid-cols-3 gap-4">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="especialidade">Especialidade (specialty)</Label>
|
<Label htmlFor="especialidade">Especialidade</Label>
|
||||||
<Input
|
<Input
|
||||||
id="especialidade"
|
id="especialidade"
|
||||||
value={formData.especialidade}
|
value={formData.especialidade}
|
||||||
@ -327,7 +327,7 @@ export default function EditarMedicoPage() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2 col-span-1">
|
<div className="space-y-2 col-span-1">
|
||||||
<Label htmlFor="dataNascimento">Data de Nascimento (birth_date)</Label>
|
<Label htmlFor="dataNascimento">Data de Nascimento</Label>
|
||||||
<Input
|
<Input
|
||||||
id="dataNascimento"
|
id="dataNascimento"
|
||||||
type="date"
|
type="date"
|
||||||
@ -342,20 +342,20 @@ export default function EditarMedicoPage() {
|
|||||||
checked={formData.ativo}
|
checked={formData.ativo}
|
||||||
onCheckedChange={(checked) => handleInputChange("ativo", checked === true)}
|
onCheckedChange={(checked) => handleInputChange("ativo", checked === true)}
|
||||||
/>
|
/>
|
||||||
<Label htmlFor="ativo">Médico Ativo (active)</Label>
|
<Label htmlFor="ativo">Médico Ativo</Label>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-4 p-4 border rounded-xl shadow-sm bg-white">
|
<div className="space-y-4 p-4 rounded-xl border border-border shadow-sm bg-card">
|
||||||
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">
|
<h2 className="text-lg font-semibold text-foreground border-b border-border pb-2">
|
||||||
Contato e Endereço
|
Contato e Endereço
|
||||||
</h2>
|
</h2>
|
||||||
|
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
<div className="grid md:grid-cols-2 gap-4">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="telefoneCelular">Telefone Celular (phone_mobile)</Label>
|
<Label htmlFor="telefoneCelular">Telefone Celular</Label>
|
||||||
<Input
|
<Input
|
||||||
id="telefoneCelular"
|
id="telefoneCelular"
|
||||||
value={formData.telefoneCelular}
|
value={formData.telefoneCelular}
|
||||||
@ -365,7 +365,7 @@ export default function EditarMedicoPage() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="telefone2">Telefone Adicional (phone2)</Label>
|
<Label htmlFor="telefone2">Telefone Adicional</Label>
|
||||||
<Input
|
<Input
|
||||||
id="telefone2"
|
id="telefone2"
|
||||||
value={formData.telefone2}
|
value={formData.telefone2}
|
||||||
@ -389,7 +389,7 @@ export default function EditarMedicoPage() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2 col-span-3">
|
<div className="space-y-2 col-span-3">
|
||||||
<Label htmlFor="endereco">Logradouro (street)</Label>
|
<Label htmlFor="endereco">Logradouro</Label>
|
||||||
<Input
|
<Input
|
||||||
id="endereco"
|
id="endereco"
|
||||||
value={formData.endereco}
|
value={formData.endereco}
|
||||||
@ -440,7 +440,7 @@ export default function EditarMedicoPage() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2 col-span-1">
|
<div className="space-y-2 col-span-1">
|
||||||
<Label htmlFor="estado">Estado (state)</Label>
|
<Label htmlFor="estado">Estado</Label>
|
||||||
<Input
|
<Input
|
||||||
id="estado"
|
id="estado"
|
||||||
value={formData.estado}
|
value={formData.estado}
|
||||||
@ -452,8 +452,8 @@ export default function EditarMedicoPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
<div className="space-y-4 p-4 border rounded-xl shadow-sm bg-white">
|
<div className="space-y-4 p-4 rounded-xl border border-border shadow-sm bg-card">
|
||||||
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">
|
<h2 className="text-lg font-semibold text-foreground border-b border-border pb-2">
|
||||||
Observações (Apenas internas)
|
Observações (Apenas internas)
|
||||||
</h2>
|
</h2>
|
||||||
<Textarea
|
<Textarea
|
||||||
@ -474,7 +474,7 @@ export default function EditarMedicoPage() {
|
|||||||
</Link>
|
</Link>
|
||||||
<Button
|
<Button
|
||||||
type="submit"
|
type="submit"
|
||||||
className="bg-green-600 hover:bg-green-700"
|
className="bg-primary hover:bg-primary/90"
|
||||||
disabled={isSaving}
|
disabled={isSaving}
|
||||||
>
|
>
|
||||||
{isSaving ? (
|
{isSaving ? (
|
||||||
|
|||||||
@ -1,17 +1,20 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import React, { useEffect, useState, useCallback, useMemo } from "react"
|
import React, { useEffect, useState, useCallback, useMemo } from "react";
|
||||||
import Link from "next/link"
|
import Link from "next/link";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button"
|
||||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||||
import { Edit, Trash2, Eye, Calendar, Filter, Loader2 } from "lucide-react"
|
import { Edit, Trash2, Eye, Calendar, Filter, Loader2, MoreVertical } from "lucide-react"
|
||||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog"
|
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog"
|
||||||
|
|
||||||
import { doctorsService } from "services/doctorsApi.mjs";
|
import { doctorsService } from "services/doctorsApi.mjs";
|
||||||
import Sidebar from "@/components/Sidebar";
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
|
// --- NOVOS IMPORTS (Certifique-se que criou os arquivos no passo anterior) ---
|
||||||
|
import { FilterBar } from "@/components/ui/filter-bar";
|
||||||
|
import { normalizeSpecialty, getUniqueSpecialties } from "@/lib/normalization";
|
||||||
|
|
||||||
interface Doctor {
|
interface Doctor {
|
||||||
id: number;
|
id: number;
|
||||||
@ -47,33 +50,41 @@ interface DoctorDetails {
|
|||||||
export default function DoctorsPage() {
|
export default function DoctorsPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
|
// --- Estados de Dados ---
|
||||||
const [doctors, setDoctors] = useState<Doctor[]>([]);
|
const [doctors, setDoctors] = useState<Doctor[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// --- Estados de Modais ---
|
||||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
||||||
const [doctorDetails, setDoctorDetails] = useState<DoctorDetails | null>(null);
|
const [doctorDetails, setDoctorDetails] = useState<DoctorDetails | null>(null);
|
||||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||||
const [doctorToDeleteId, setDoctorToDeleteId] = useState<number | null>(null);
|
const [doctorToDeleteId, setDoctorToDeleteId] = useState<number | null>(null);
|
||||||
|
|
||||||
// --- Estados para Filtros ---
|
// --- Estados de Filtro e Busca ---
|
||||||
const [specialtyFilter, setSpecialtyFilter] = useState("all");
|
const [searchTerm, setSearchTerm] = useState("");
|
||||||
const [statusFilter, setStatusFilter] = useState("all");
|
const [filters, setFilters] = useState({
|
||||||
|
specialty: "all",
|
||||||
|
status: "all"
|
||||||
|
});
|
||||||
|
|
||||||
// --- Estados para Paginação ---
|
// --- Estados de Paginação ---
|
||||||
const [itemsPerPage, setItemsPerPage] = useState(10);
|
const [itemsPerPage, setItemsPerPage] = useState(10);
|
||||||
const [currentPage, setCurrentPage] = useState(1);
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
|
|
||||||
|
// 1. Buscar Médicos na API
|
||||||
const fetchDoctors = useCallback(async () => {
|
const fetchDoctors = useCallback(async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const data: Doctor[] = await doctorsService.list();
|
const data: Doctor[] = await doctorsService.list();
|
||||||
|
// Mockando status para visualização (conforme original)
|
||||||
const dataWithStatus = data.map((doc, index) => ({
|
const dataWithStatus = data.map((doc, index) => ({
|
||||||
...doc,
|
...doc,
|
||||||
status: index % 3 === 0 ? "Inativo" : index % 2 === 0 ? "Férias" : "Ativo",
|
status: index % 3 === 0 ? "Inativo" : index % 2 === 0 ? "Férias" : "Ativo",
|
||||||
}));
|
}));
|
||||||
setDoctors(dataWithStatus || []);
|
setDoctors(dataWithStatus || []);
|
||||||
setCurrentPage(1);
|
// Não resetamos a página aqui para manter a navegação fluida se apenas recarregar dados
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
console.error("Erro ao carregar lista de médicos:", e);
|
console.error("Erro ao carregar lista de médicos:", e);
|
||||||
setError("Não foi possível carregar a lista de médicos. Verifique a conexão com a API.");
|
setError("Não foi possível carregar a lista de médicos. Verifique a conexão com a API.");
|
||||||
@ -87,67 +98,63 @@ export default function DoctorsPage() {
|
|||||||
fetchDoctors();
|
fetchDoctors();
|
||||||
}, [fetchDoctors]);
|
}, [fetchDoctors]);
|
||||||
|
|
||||||
const openDetailsDialog = async (doctor: Doctor) => {
|
// 2. Gerar lista única de especialidades (Normalizada)
|
||||||
setDetailsDialogOpen(true);
|
|
||||||
setDoctorDetails({
|
|
||||||
nome: doctor.full_name,
|
|
||||||
crm: doctor.crm,
|
|
||||||
especialidade: doctor.specialty,
|
|
||||||
contato: { celular: doctor.phone_mobile ?? undefined },
|
|
||||||
endereco: { cidade: doctor.city ?? undefined, estado: doctor.state ?? undefined },
|
|
||||||
status: doctor.status || "Ativo",
|
|
||||||
convenio: "Particular",
|
|
||||||
vip: false,
|
|
||||||
ultimo_atendimento: "N/A",
|
|
||||||
proximo_atendimento: "N/A",
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleDelete = async () => {
|
|
||||||
if (doctorToDeleteId === null) return;
|
|
||||||
setLoading(true);
|
|
||||||
try {
|
|
||||||
await doctorsService.delete(doctorToDeleteId);
|
|
||||||
setDeleteDialogOpen(false);
|
|
||||||
setDoctorToDeleteId(null);
|
|
||||||
await fetchDoctors();
|
|
||||||
} catch (e) {
|
|
||||||
console.error("Erro ao excluir:", e);
|
|
||||||
alert("Erro ao excluir médico.");
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const openDeleteDialog = (doctorId: number) => {
|
|
||||||
setDoctorToDeleteId(doctorId);
|
|
||||||
setDeleteDialogOpen(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
const uniqueSpecialties = useMemo(() => {
|
const uniqueSpecialties = useMemo(() => {
|
||||||
const specialties = doctors.map((doctor) => doctor.specialty).filter(Boolean);
|
return getUniqueSpecialties(doctors);
|
||||||
return [...new Set(specialties)];
|
|
||||||
}, [doctors]);
|
}, [doctors]);
|
||||||
|
|
||||||
const filteredDoctors = doctors.filter((doctor) => {
|
// 3. Lógica de Filtragem Centralizada
|
||||||
const specialtyMatch = specialtyFilter === "all" || doctor.specialty === specialtyFilter;
|
const filteredDoctors = useMemo(() => {
|
||||||
const statusMatch = statusFilter === "all" || doctor.status === statusFilter;
|
return doctors.filter((doctor) => {
|
||||||
return specialtyMatch && statusMatch;
|
// Normaliza a especialidade do médico atual para comparar
|
||||||
});
|
const normalizedDocSpecialty = normalizeSpecialty(doctor.specialty);
|
||||||
|
|
||||||
|
// Filtros exatos
|
||||||
|
const specialtyMatch = filters.specialty === "all" || normalizedDocSpecialty === filters.specialty;
|
||||||
|
const statusMatch = filters.status === "all" || doctor.status === filters.status;
|
||||||
|
|
||||||
|
// Busca textual (Nome, Telefone, CRM)
|
||||||
|
const searchLower = searchTerm.toLowerCase();
|
||||||
|
const nameMatch = doctor.full_name?.toLowerCase().includes(searchLower);
|
||||||
|
const phoneMatch = doctor.phone_mobile?.includes(searchLower);
|
||||||
|
const crmMatch = doctor.crm?.toLowerCase().includes(searchLower);
|
||||||
|
|
||||||
|
return specialtyMatch && statusMatch && (searchTerm === "" || nameMatch || phoneMatch || crmMatch);
|
||||||
|
});
|
||||||
|
}, [doctors, filters, searchTerm]);
|
||||||
|
|
||||||
|
// --- Handlers de Controle (Com Reset de Paginação) ---
|
||||||
|
|
||||||
|
const handleSearch = (term: string) => {
|
||||||
|
setSearchTerm(term);
|
||||||
|
setCurrentPage(1); // Correção: Reseta para página 1 ao buscar
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFilterChange = (key: string, value: string) => {
|
||||||
|
setFilters(prev => ({ ...prev, [key]: value }));
|
||||||
|
setCurrentPage(1); // Correção: Reseta para página 1 ao filtrar
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleClearFilters = () => {
|
||||||
|
setSearchTerm("");
|
||||||
|
setFilters({ specialty: "all", status: "all" });
|
||||||
|
setCurrentPage(1); // Correção: Reseta para página 1 ao limpar
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleItemsPerPageChange = (value: string) => {
|
||||||
|
setItemsPerPage(Number(value));
|
||||||
|
setCurrentPage(1);
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- Lógica de Paginação ---
|
||||||
const totalPages = Math.ceil(filteredDoctors.length / itemsPerPage);
|
const totalPages = Math.ceil(filteredDoctors.length / itemsPerPage);
|
||||||
const indexOfLastItem = currentPage * itemsPerPage;
|
const indexOfLastItem = currentPage * itemsPerPage;
|
||||||
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
||||||
const currentItems = filteredDoctors.slice(indexOfFirstItem, indexOfLastItem);
|
const currentItems = filteredDoctors.slice(indexOfFirstItem, indexOfLastItem);
|
||||||
|
|
||||||
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
|
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
|
||||||
|
const goToPrevPage = () => setCurrentPage((prev) => Math.max(1, prev - 1));
|
||||||
const goToPrevPage = () => {
|
const goToNextPage = () => setCurrentPage((prev) => Math.min(totalPages, prev + 1));
|
||||||
setCurrentPage((prev) => Math.max(1, prev - 1));
|
|
||||||
};
|
|
||||||
|
|
||||||
const goToNextPage = () => {
|
|
||||||
setCurrentPage((prev) => Math.min(totalPages, prev + 1));
|
|
||||||
};
|
|
||||||
|
|
||||||
const getVisiblePageNumbers = (totalPages: number, currentPage: number) => {
|
const getVisiblePageNumbers = (totalPages: number, currentPage: number) => {
|
||||||
const pages: number[] = [];
|
const pages: number[] = [];
|
||||||
@ -173,9 +180,42 @@ export default function DoctorsPage() {
|
|||||||
|
|
||||||
const visiblePageNumbers = getVisiblePageNumbers(totalPages, currentPage);
|
const visiblePageNumbers = getVisiblePageNumbers(totalPages, currentPage);
|
||||||
|
|
||||||
const handleItemsPerPageChange = (value: string) => {
|
// --- Handlers de Ações (Detalhes e Delete) ---
|
||||||
setItemsPerPage(Number(value));
|
const openDetailsDialog = (doctor: Doctor) => {
|
||||||
setCurrentPage(1);
|
setDetailsDialogOpen(true);
|
||||||
|
setDoctorDetails({
|
||||||
|
nome: doctor.full_name,
|
||||||
|
crm: doctor.crm,
|
||||||
|
especialidade: normalizeSpecialty(doctor.specialty), // Exibe normalizado
|
||||||
|
contato: { celular: doctor.phone_mobile ?? undefined },
|
||||||
|
endereco: { cidade: doctor.city ?? undefined, estado: doctor.state ?? undefined },
|
||||||
|
status: doctor.status || "Ativo",
|
||||||
|
convenio: "Particular",
|
||||||
|
vip: false,
|
||||||
|
ultimo_atendimento: "N/A",
|
||||||
|
proximo_atendimento: "N/A",
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const openDeleteDialog = (doctorId: number) => {
|
||||||
|
setDoctorToDeleteId(doctorId);
|
||||||
|
setDeleteDialogOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDelete = async () => {
|
||||||
|
if (doctorToDeleteId === null) return;
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
await doctorsService.delete(doctorToDeleteId);
|
||||||
|
setDeleteDialogOpen(false);
|
||||||
|
setDoctorToDeleteId(null);
|
||||||
|
await fetchDoctors();
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Erro ao excluir:", e);
|
||||||
|
alert("Erro ao excluir médico.");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@ -184,99 +224,100 @@ export default function DoctorsPage() {
|
|||||||
{/* Cabeçalho */}
|
{/* Cabeçalho */}
|
||||||
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
|
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-gray-900">Médicos Cadastrados</h1>
|
<h1 className="text-2xl font-bold">
|
||||||
<p className="text-sm text-gray-500">Gerencie todos os profissionais de saúde.</p>
|
Médicos Cadastrados
|
||||||
|
</h1>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Gerencie todos os profissionais de saúde.
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Filtros e Itens por Página */}
|
{/* --- NOVO COMPONENTE DE FILTRO --- */}
|
||||||
<div className="flex flex-wrap items-center gap-3 bg-white p-3 sm:p-4 rounded-lg border border-gray-200">
|
<FilterBar
|
||||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
searchTerm={searchTerm}
|
||||||
<span className="text-sm font-medium text-foreground">Especialidade</span>
|
onSearch={handleSearch}
|
||||||
<Select value={specialtyFilter} onValueChange={setSpecialtyFilter}>
|
activeFilters={filters}
|
||||||
<SelectTrigger className="w-[160px] sm:w-[180px]">
|
onFilterChange={handleFilterChange}
|
||||||
<SelectValue placeholder="Especialidade" />
|
onClearFilters={handleClearFilters}
|
||||||
</SelectTrigger>
|
searchPlaceholder="Buscar por nome, CRM ou telefone..."
|
||||||
<SelectContent>
|
filters={[
|
||||||
<SelectItem value="all">Todas</SelectItem>
|
{
|
||||||
{uniqueSpecialties.map((specialty) => (
|
key: "specialty",
|
||||||
<SelectItem key={specialty} value={specialty}>
|
label: "Especialidade",
|
||||||
{specialty}
|
options: uniqueSpecialties
|
||||||
</SelectItem>
|
},
|
||||||
))}
|
{
|
||||||
</SelectContent>
|
key: "status",
|
||||||
</Select>
|
label: "Status",
|
||||||
</div>
|
options: ["Ativo", "Férias", "Inativo"]
|
||||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
}
|
||||||
<span className="text-sm font-medium text-foreground">Status</span>
|
]}
|
||||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
>
|
||||||
<SelectTrigger className="w-[160px] sm:w-[180px]">
|
{/* Seletor de Itens por Página (Filho do FilterBar) */}
|
||||||
<SelectValue placeholder="Status" />
|
<div className="hidden lg:block">
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="all">Todos</SelectItem>
|
|
||||||
<SelectItem value="Ativo">Ativo</SelectItem>
|
|
||||||
<SelectItem value="Férias">Férias</SelectItem>
|
|
||||||
<SelectItem value="Inativo">Inativo</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
|
||||||
<span className="text-sm font-medium text-foreground">Itens por página</span>
|
|
||||||
<Select onValueChange={handleItemsPerPageChange} defaultValue={String(itemsPerPage)}>
|
<Select onValueChange={handleItemsPerPageChange} defaultValue={String(itemsPerPage)}>
|
||||||
<SelectTrigger className="w-[140px]">
|
<SelectTrigger className="w-[70px]">
|
||||||
<SelectValue placeholder="Itens por pág." />
|
<SelectValue placeholder="10" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="5">5 por página</SelectItem>
|
<SelectItem value="5">5</SelectItem>
|
||||||
<SelectItem value="10">10 por página</SelectItem>
|
<SelectItem value="10">10</SelectItem>
|
||||||
<SelectItem value="20">20 por página</SelectItem>
|
<SelectItem value="20">20</SelectItem>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
<Button variant="outline" className="ml-auto w-full md:w-auto">
|
</FilterBar>
|
||||||
<Filter className="w-4 h-4 mr-2" />
|
|
||||||
Filtro avançado
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Tabela de Médicos (Visível em Telas Médias e Maiores) */}
|
{/* Tabela de Médicos */}
|
||||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-hidden hidden md:block">
|
<div className="bg-card rounded-lg border shadow-md overflow-hidden hidden md:block">
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="p-8 text-center text-gray-500">
|
<div className="p-8 text-center text-muted-foreground">
|
||||||
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
|
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-primary" />
|
||||||
Carregando médicos...
|
Carregando médicos...
|
||||||
</div>
|
</div>
|
||||||
) : error ? (
|
) : error ? (
|
||||||
<div className="p-8 text-center text-red-600">{error}</div>
|
<div className="p-8 text-center text-destructive">{error}</div>
|
||||||
) : filteredDoctors.length === 0 ? (
|
) : filteredDoctors.length === 0 ? (
|
||||||
<div className="p-8 text-center text-gray-500">
|
<div className="p-8 text-center text-muted-foreground">
|
||||||
{doctors.length === 0
|
{doctors.length === 0
|
||||||
? <>Nenhum médico cadastrado. <Link href="/manager/home/novo" className="text-green-600 hover:underline">Adicione um novo</Link>.</>
|
? <>Nenhum médico cadastrado. <Link href="/manager/home/novo" className="text-primary hover:underline">Adicione um novo</Link>.</>
|
||||||
: "Nenhum médico encontrado com os filtros aplicados."
|
: "Nenhum médico encontrado com os filtros aplicados."
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="overflow-x-auto">
|
<div className="overflow-x-auto">
|
||||||
<table className="w-full min-w-[600px]">
|
<table className="w-full min-w-[600px]">
|
||||||
<thead className="bg-gray-50 border-b border-gray-200">
|
<thead className="bg-muted border-b">
|
||||||
<tr>
|
<tr>
|
||||||
<th className="text-left p-2 md:p-4 font-medium text-gray-700">Nome</th>
|
<th className="text-left p-2 md:p-4 font-medium text-muted-foreground">Nome</th>
|
||||||
<th className="text-left p-2 md:p-4 font-medium text-gray-700">CRM</th>
|
<th className="text-left p-2 md:p-4 font-medium text-muted-foreground">CRM</th>
|
||||||
<th className="text-left p-2 md:p-4 font-medium text-gray-700">Especialidade</th>
|
<th className="text-left p-2 md:p-4 font-medium text-muted-foreground">Especialidade</th>
|
||||||
<th className="text-left p-2 md:p-4 font-medium text-gray-700 hidden lg:table-cell">Status</th>
|
<th className="text-left p-2 md:p-4 font-medium text-muted-foreground hidden lg:table-cell">Status</th>
|
||||||
<th className="text-left p-2 md:p-4 font-medium text-gray-700 hidden xl:table-cell">Cidade/Estado</th>
|
<th className="text-left p-2 md:p-4 font-medium text-muted-foreground hidden xl:table-cell">Cidade/Estado</th>
|
||||||
<th className="text-right p-4 font-medium text-gray-700">Ações</th>
|
<th className="text-right p-4 font-medium text-muted-foreground">Ações</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody className="bg-white divide-y divide-gray-200">
|
<tbody className="bg-card divide-y">
|
||||||
{currentItems.map((doctor) => (
|
{currentItems.map((doctor) => (
|
||||||
<tr key={doctor.id} className="hover:bg-gray-50 transition">
|
<tr key={doctor.id} className="hover:bg-muted transition">
|
||||||
<td className="px-4 py-3 font-medium text-gray-900">{doctor.full_name}</td>
|
<td className="px-4 py-3 font-medium">
|
||||||
<td className="px-4 py-3 text-gray-500 hidden sm:table-cell">{doctor.crm}</td>
|
{doctor.full_name}
|
||||||
<td className="px-4 py-3 text-gray-500 hidden md:table-cell">{doctor.specialty}</td>
|
</td>
|
||||||
<td className="px-4 py-3 text-gray-500 hidden lg:table-cell">{doctor.status || "N/A"}</td>
|
<td className="px-4 py-3 text-muted-foreground hidden sm:table-cell">{doctor.crm}</td>
|
||||||
<td className="px-4 py-3 text-gray-500 hidden xl:table-cell">
|
<td className="px-4 py-3 text-muted-foreground hidden md:table-cell">
|
||||||
|
{/* Exibe Especialidade Normalizada */}
|
||||||
|
{normalizeSpecialty(doctor.specialty)}
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-muted-foreground hidden lg:table-cell">
|
||||||
|
<span className={`px-2 py-1 rounded-full text-xs ${
|
||||||
|
doctor.status === 'Ativo' ? 'bg-primary/10 text-primary' :
|
||||||
|
doctor.status === 'Inativo' ? 'bg-destructive/10 text-destructive' : 'bg-yellow-400/10 text-yellow-400'
|
||||||
|
}`}>
|
||||||
|
{doctor.status || "N/A"}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-muted-foreground hidden xl:table-cell">
|
||||||
{(doctor.city || doctor.state)
|
{(doctor.city || doctor.state)
|
||||||
? `${doctor.city || ""}${doctor.city && doctor.state ? '/' : ''}${doctor.state || ""}`
|
? `${doctor.city || ""}${doctor.city && doctor.state ? '/' : ''}${doctor.state || ""}`
|
||||||
: "N/A"}
|
: "N/A"}
|
||||||
@ -284,7 +325,10 @@ export default function DoctorsPage() {
|
|||||||
<td className="px-4 py-3 text-right">
|
<td className="px-4 py-3 text-right">
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<div className="text-blue-600 cursor-pointer inline-block">Ações</div>
|
<Button variant="ghost" className="h-8 w-8 p-0">
|
||||||
|
<span className="sr-only">Abrir menu</span>
|
||||||
|
<MoreVertical className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
<DropdownMenuItem onClick={() => openDetailsDialog(doctor)}>
|
<DropdownMenuItem onClick={() => openDetailsDialog(doctor)}>
|
||||||
@ -301,7 +345,7 @@ export default function DoctorsPage() {
|
|||||||
<Calendar className="mr-2 h-4 w-4" />
|
<Calendar className="mr-2 h-4 w-4" />
|
||||||
Marcar consulta
|
Marcar consulta
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(doctor.id)}>
|
<DropdownMenuItem className="text-destructive" onClick={() => openDeleteDialog(doctor.id)}>
|
||||||
<Trash2 className="mr-2 h-4 w-4" />
|
<Trash2 className="mr-2 h-4 w-4" />
|
||||||
Excluir
|
Excluir
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
@ -316,33 +360,45 @@ export default function DoctorsPage() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Cards de Médicos (Visível Apenas em Telas Pequenas) */}
|
{/* Cards de Médicos (Mobile) */}
|
||||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md p-4 block md:hidden">
|
<div className="bg-card rounded-lg border shadow-md p-4 block md:hidden">
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="p-8 text-center text-gray-500">
|
<div className="p-8 text-center text-muted-foreground">
|
||||||
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
|
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-primary" />
|
||||||
Carregando médicos...
|
Carregando médicos...
|
||||||
</div>
|
</div>
|
||||||
) : error ? (
|
) : error ? (
|
||||||
<div className="p-8 text-center text-red-600">{error}</div>
|
<div className="p-8 text-center text-destructive">{error}</div>
|
||||||
) : filteredDoctors.length === 0 ? (
|
) : filteredDoctors.length === 0 ? (
|
||||||
<div className="p-8 text-center text-gray-500">
|
<div className="p-8 text-center text-muted-foreground">
|
||||||
{doctors.length === 0
|
{doctors.length === 0
|
||||||
? <>Nenhum médico cadastrado. <Link href="/manager/home/novo" className="text-green-600 hover:underline">Adicione um novo</Link>.</>
|
? <>Nenhum médico cadastrado. <Link href="/manager/home/novo" className="text-primary hover:underline">Adicione um novo</Link>.</>
|
||||||
: "Nenhum médico encontrado com os filtros aplicados."
|
: "Nenhum médico encontrado com os filtros aplicados."
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
{currentItems.map((doctor) => (
|
{currentItems.map((doctor) => (
|
||||||
<div key={doctor.id} className="bg-white-50 rounded-lg p-4 flex justify-between items-center border border-white-200">
|
<div key={doctor.id} className="bg-muted rounded-lg p-4 flex justify-between items-center border">
|
||||||
<div>
|
<div>
|
||||||
<div className="font-semibold text-gray-900">{doctor.full_name}</div>
|
<div className="font-semibold">{doctor.full_name}</div>
|
||||||
<div className="text-sm text-gray-600">{doctor.specialty}</div>
|
<div className="text-xs text-muted-foreground mb-1">{doctor.phone_mobile}</div>
|
||||||
|
<div className="text-sm text-muted-foreground">{normalizeSpecialty(doctor.specialty)}</div>
|
||||||
|
<div className="text-xs mt-1">
|
||||||
|
<span className={`px-2 py-0.5 rounded-full text-xs ${
|
||||||
|
doctor.status === 'Ativo' ? 'bg-primary/10 text-primary' :
|
||||||
|
doctor.status === 'Inativo' ? 'bg-destructive/10 text-destructive' : 'bg-yellow-400/10 text-yellow-400'
|
||||||
|
}`}>
|
||||||
|
{doctor.status || "N/A"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<div className="text-blue-600 cursor-pointer inline-block">Ações</div>
|
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
|
||||||
|
<span className="sr-only">Abrir menu</span>
|
||||||
|
<div className="font-bold text-muted-foreground">...</div>
|
||||||
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
<DropdownMenuItem onClick={() => openDetailsDialog(doctor)}>
|
<DropdownMenuItem onClick={() => openDetailsDialog(doctor)}>
|
||||||
@ -355,11 +411,7 @@ export default function DoctorsPage() {
|
|||||||
Editar
|
Editar
|
||||||
</Link>
|
</Link>
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem>
|
<DropdownMenuItem className="text-destructive" onClick={() => openDeleteDialog(doctor.id)}>
|
||||||
<Calendar className="mr-2 h-4 w-4" />
|
|
||||||
Marcar consulta
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(doctor.id)}>
|
|
||||||
<Trash2 className="mr-2 h-4 w-4" />
|
<Trash2 className="mr-2 h-4 w-4" />
|
||||||
Excluir
|
Excluir
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
@ -373,11 +425,11 @@ export default function DoctorsPage() {
|
|||||||
|
|
||||||
{/* Paginação */}
|
{/* Paginação */}
|
||||||
{totalPages > 1 && (
|
{totalPages > 1 && (
|
||||||
<div className="flex flex-wrap justify-center items-center gap-2 mt-4 p-4 bg-white rounded-lg border border-gray-200 shadow-md">
|
<div className="flex flex-wrap justify-center items-center gap-2 mt-4 p-4 bg-card rounded-lg border shadow-md">
|
||||||
<button
|
<button
|
||||||
onClick={goToPrevPage}
|
onClick={goToPrevPage}
|
||||||
disabled={currentPage === 1}
|
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"
|
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-muted text-muted-foreground hover:bg-muted/90 disabled:opacity-50 disabled:cursor-not-allowed border"
|
||||||
>
|
>
|
||||||
{"< Anterior"}
|
{"< Anterior"}
|
||||||
</button>
|
</button>
|
||||||
@ -386,10 +438,10 @@ export default function DoctorsPage() {
|
|||||||
<button
|
<button
|
||||||
key={number}
|
key={number}
|
||||||
onClick={() => paginate(number)}
|
onClick={() => paginate(number)}
|
||||||
className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border border-gray-300 ${
|
className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border ${
|
||||||
currentPage === number
|
currentPage === number
|
||||||
? "bg-green-600 text-white shadow-md border-green-600"
|
? "bg-primary text-primary-foreground shadow-md border-primary"
|
||||||
: "bg-gray-100 text-gray-700 hover:bg-gray-200"
|
: "bg-muted text-muted-foreground hover:bg-muted/90"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{number}
|
{number}
|
||||||
@ -399,14 +451,14 @@ export default function DoctorsPage() {
|
|||||||
<button
|
<button
|
||||||
onClick={goToNextPage}
|
onClick={goToNextPage}
|
||||||
disabled={currentPage === totalPages}
|
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"
|
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-muted text-muted-foreground hover:bg-muted/90 disabled:opacity-50 disabled:cursor-not-allowed border"
|
||||||
>
|
>
|
||||||
{"Próximo >"}
|
{"Próximo >"}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Dialogs de Exclusão e Detalhes */}
|
{/* Dialogs (Exclusão e Detalhes) */}
|
||||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||||
<AlertDialogContent>
|
<AlertDialogContent>
|
||||||
<AlertDialogHeader>
|
<AlertDialogHeader>
|
||||||
@ -415,7 +467,7 @@ export default function DoctorsPage() {
|
|||||||
</AlertDialogHeader>
|
</AlertDialogHeader>
|
||||||
<AlertDialogFooter>
|
<AlertDialogFooter>
|
||||||
<AlertDialogCancel disabled={loading}>Cancelar</AlertDialogCancel>
|
<AlertDialogCancel disabled={loading}>Cancelar</AlertDialogCancel>
|
||||||
<AlertDialogAction onClick={handleDelete} className="bg-red-600 hover:bg-red-700" disabled={loading}>
|
<AlertDialogAction onClick={handleDelete} className="bg-destructive hover:bg-destructive/90" disabled={loading}>
|
||||||
{loading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null}
|
{loading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null}
|
||||||
Excluir
|
Excluir
|
||||||
</AlertDialogAction>
|
</AlertDialogAction>
|
||||||
@ -423,50 +475,70 @@ export default function DoctorsPage() {
|
|||||||
</AlertDialogContent>
|
</AlertDialogContent>
|
||||||
</AlertDialog>
|
</AlertDialog>
|
||||||
|
|
||||||
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
<AlertDialog
|
||||||
|
open={detailsDialogOpen}
|
||||||
|
onOpenChange={setDetailsDialogOpen}
|
||||||
|
>
|
||||||
<AlertDialogContent className="max-w-[95%] sm:max-w-lg">
|
<AlertDialogContent className="max-w-[95%] sm:max-w-lg">
|
||||||
<AlertDialogHeader>
|
<AlertDialogHeader>
|
||||||
<AlertDialogTitle className="text-2xl">{doctorDetails?.nome}</AlertDialogTitle>
|
<AlertDialogTitle className="text-2xl">
|
||||||
<AlertDialogDescription className="text-left text-gray-700">
|
{doctorDetails?.nome}
|
||||||
|
</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription className="text-left text-muted-foreground">
|
||||||
{doctorDetails && (
|
{doctorDetails && (
|
||||||
<div className="space-y-3 text-left">
|
<div className="space-y-3 text-left">
|
||||||
<h3 className="font-semibold mt-2">Informações Principais</h3>
|
<h3 className="font-semibold mt-2">
|
||||||
|
Informações Principais
|
||||||
|
</h3>
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-y-2 gap-x-4 text-sm">
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-y-2 gap-x-4 text-sm">
|
||||||
<div>
|
<div>
|
||||||
<strong>CRM:</strong> {doctorDetails.crm}
|
<strong>CRM:</strong> {doctorDetails.crm}
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<strong>Especialidade:</strong> {doctorDetails.especialidade}
|
<strong>Especialidade:</strong>{" "}
|
||||||
|
{doctorDetails.especialidade}
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<strong>Celular:</strong> {doctorDetails.contato.celular || "N/A"}
|
<strong>Celular:</strong>{" "}
|
||||||
|
{doctorDetails.contato.celular || "N/A"}
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<strong>Localização:</strong> {`${doctorDetails.endereco.cidade || "N/A"}/${doctorDetails.endereco.estado || "N/A"}`}
|
<strong>Localização:</strong>{" "}
|
||||||
|
{`${doctorDetails.endereco.cidade || "N/A"}/${
|
||||||
|
doctorDetails.endereco.estado || "N/A"
|
||||||
|
}`}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<h3 className="font-semibold mt-4">Atendimento e Convênio</h3>
|
<h3 className="font-semibold mt-4">
|
||||||
|
Atendimento e Convênio
|
||||||
|
</h3>
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-y-2 gap-x-4 text-sm">
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-y-2 gap-x-4 text-sm">
|
||||||
<div>
|
<div>
|
||||||
<strong>Convênio:</strong> {doctorDetails.convenio || "N/A"}
|
<strong>Convênio:</strong>{" "}
|
||||||
|
{doctorDetails.convenio || "N/A"}
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<strong>VIP:</strong> {doctorDetails.vip ? "Sim" : "Não"}
|
<strong>VIP:</strong>{" "}
|
||||||
|
{doctorDetails.vip ? "Sim" : "Não"}
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<strong>Status:</strong> {doctorDetails.status || "N/A"}
|
<strong>Status:</strong> {doctorDetails.status || "N/A"}
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<strong>Último atendimento:</strong> {doctorDetails.ultimo_atendimento || "N/A"}
|
<strong>Último atendimento:</strong>{" "}
|
||||||
|
{doctorDetails.ultimo_atendimento || "N/A"}
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<strong>Próximo atendimento:</strong> {doctorDetails.proximo_atendimento || "N/A"}
|
<strong>Próximo atendimento:</strong>{" "}
|
||||||
|
{doctorDetails.proximo_atendimento || "N/A"}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{doctorDetails === null && !loading && <div className="text-red-600">Detalhes não disponíveis.</div>}
|
{doctorDetails === null && !loading && (
|
||||||
|
<div className="text-destructive">Detalhes não disponíveis.</div>
|
||||||
|
)}
|
||||||
</AlertDialogDescription>
|
</AlertDialogDescription>
|
||||||
</AlertDialogHeader>
|
</AlertDialogHeader>
|
||||||
<AlertDialogFooter>
|
<AlertDialogFooter>
|
||||||
|
|||||||
@ -8,7 +8,7 @@ export default function ManagerLoginPage() {
|
|||||||
// O ideal no futuro é deletar esta página e redirecionar os usuários.
|
// O ideal no futuro é deletar esta página e redirecionar os usuários.
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-blue-50 flex items-center justify-center p-4">
|
<div className="min-h-screen bg-background flex items-center justify-center p-4">
|
||||||
<div className="w-full max-w-md text-center">
|
<div className="w-full max-w-md text-center">
|
||||||
<h1 className="text-3xl font-bold text-foreground mb-2">Área do Gestor</h1>
|
<h1 className="text-3xl font-bold text-foreground mb-2">Área do Gestor</h1>
|
||||||
<p className="text-muted-foreground mb-8">Acesse o sistema médico</p>
|
<p className="text-muted-foreground mb-8">Acesse o sistema médico</p>
|
||||||
|
|||||||
@ -31,34 +31,35 @@ export default function EditarPacientePage() {
|
|||||||
const [isUploadingAnexo, setIsUploadingAnexo] = useState(false);
|
const [isUploadingAnexo, setIsUploadingAnexo] = useState(false);
|
||||||
const anexoInputRef = useRef<HTMLInputElement | null>(null);
|
const anexoInputRef = useRef<HTMLInputElement | null>(null);
|
||||||
|
|
||||||
|
// Tipagem completa do formulário
|
||||||
type FormData = {
|
type FormData = {
|
||||||
nome: string; // full_name
|
nome: string;
|
||||||
cpf: string;
|
cpf: string;
|
||||||
dataNascimento: string; // birth_date
|
dataNascimento: string;
|
||||||
sexo: string; // sex
|
sexo: string;
|
||||||
id?: string;
|
id?: string;
|
||||||
nomeSocial?: string; // social_name
|
nomeSocial?: string;
|
||||||
rg?: string;
|
rg?: string;
|
||||||
documentType?: string; // document_type
|
documentType?: string;
|
||||||
documentNumber?: string; // document_number
|
documentNumber?: string;
|
||||||
ethnicity?: string;
|
ethnicity?: string;
|
||||||
race?: string;
|
race?: string;
|
||||||
naturality?: string;
|
naturality?: string;
|
||||||
nationality?: string;
|
nationality?: string;
|
||||||
profession?: string;
|
profession?: string;
|
||||||
maritalStatus?: string; // marital_status
|
maritalStatus?: string;
|
||||||
motherName?: string; // mother_name
|
motherName?: string;
|
||||||
motherProfession?: string; // mother_profession
|
motherProfession?: string;
|
||||||
fatherName?: string; // father_name
|
fatherName?: string;
|
||||||
fatherProfession?: string; // father_profession
|
fatherProfession?: string;
|
||||||
guardianName?: string; // guardian_name
|
guardianName?: string;
|
||||||
guardianCpf?: string; // guardian_cpf
|
guardianCpf?: string;
|
||||||
spouseName?: string; // spouse_name
|
spouseName?: string;
|
||||||
rnInInsurance?: boolean; // rn_in_insurance
|
rnInInsurance?: boolean;
|
||||||
legacyCode?: string; // legacy_code
|
legacyCode?: string;
|
||||||
notes?: string;
|
notes?: string;
|
||||||
email?: string;
|
email?: string;
|
||||||
phoneMobile?: string; // phone_mobile
|
phoneMobile?: string;
|
||||||
phone1?: string;
|
phone1?: string;
|
||||||
phone2?: string;
|
phone2?: string;
|
||||||
cep?: string;
|
cep?: string;
|
||||||
@ -82,7 +83,6 @@ export default function EditarPacientePage() {
|
|||||||
bloodType?: string;
|
bloodType?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
const [formData, setFormData] = useState<FormData>({
|
const [formData, setFormData] = useState<FormData>({
|
||||||
nome: "",
|
nome: "",
|
||||||
cpf: "",
|
cpf: "",
|
||||||
@ -141,7 +141,6 @@ export default function EditarPacientePage() {
|
|||||||
async function fetchPatient() {
|
async function fetchPatient() {
|
||||||
try {
|
try {
|
||||||
const res = await patientsService.getById(patientId);
|
const res = await patientsService.getById(patientId);
|
||||||
// Map API snake_case/nested to local camelCase form
|
|
||||||
setFormData({
|
setFormData({
|
||||||
id: res[0]?.id ?? "",
|
id: res[0]?.id ?? "",
|
||||||
nome: res[0]?.full_name ?? "",
|
nome: res[0]?.full_name ?? "",
|
||||||
@ -206,7 +205,6 @@ export default function EditarPacientePage() {
|
|||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
// Build API payload (snake_case)
|
|
||||||
const payload = {
|
const payload = {
|
||||||
full_name: formData.nome || null,
|
full_name: formData.nome || null,
|
||||||
cpf: formData.cpf || null,
|
cpf: formData.cpf || null,
|
||||||
@ -247,39 +245,42 @@ export default function EditarPacientePage() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Sidebar>
|
<Sidebar>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6 px-2 sm:px-4 pb-20">
|
||||||
<div className="flex items-center gap-4">
|
{/* --- HEADER RESPONSIVO --- */}
|
||||||
|
<div className="flex flex-col xl:flex-row gap-6 xl:items-start xl:justify-between">
|
||||||
|
<div className="flex flex-col sm:flex-row sm:items-center gap-4">
|
||||||
<Link href="/manager/pacientes">
|
<Link href="/manager/pacientes">
|
||||||
<Button variant="ghost" size="sm">
|
<Button variant="ghost" size="sm" className="-ml-2">
|
||||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||||
Voltar
|
Voltar
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-gray-900">Editar Paciente</h1>
|
<h1 className="text-xl sm:text-2xl font-bold text-foreground">Editar Paciente</h1>
|
||||||
<p className="text-gray-600">Atualize as informações do paciente</p>
|
<p className="text-sm text-muted-foreground">Atualize as informações do paciente</p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Anexos Section */}
|
{/* Anexos Section */}
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
<div className="w-full xl:w-auto xl:min-w-[400px] bg-card rounded-lg border border-border p-4 sm:p-6">
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Anexos</h2>
|
<h2 className="text-lg font-semibold text-foreground mb-4 sm:mb-6">Anexos</h2>
|
||||||
<div className="flex items-center gap-3 mb-4">
|
<div className="flex items-center gap-3 mb-4">
|
||||||
<input ref={anexoInputRef} type="file" className="hidden" />
|
<input ref={anexoInputRef} type="file" className="hidden" />
|
||||||
<Button type="button" variant="outline" disabled={isUploadingAnexo}>
|
<Button type="button" variant="outline" size="sm" disabled={isUploadingAnexo} className="w-full sm:w-auto">
|
||||||
<Paperclip className="w-4 h-4 mr-2" /> {isUploadingAnexo ? "Enviando..." : "Adicionar anexo"}
|
<Paperclip className="w-4 h-4 mr-2" /> {isUploadingAnexo ? "Enviando..." : "Adicionar anexo"}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
{anexos.length === 0 ? (
|
{anexos.length === 0 ? (
|
||||||
<p className="text-sm text-gray-500">Nenhum anexo encontrado.</p>
|
<p className="text-sm text-muted-foreground">Nenhum anexo encontrado.</p>
|
||||||
) : (
|
) : (
|
||||||
<ul className="divide-y">
|
<ul className="divide-y divide-border">
|
||||||
{anexos.map((a) => (
|
{anexos.map((a) => (
|
||||||
<li key={a.id} className="flex items-center justify-between py-2">
|
<li key={a.id} className="flex items-center justify-between py-2">
|
||||||
<div className="flex items-center gap-2 min-w-0">
|
<div className="flex items-center gap-2 min-w-0">
|
||||||
<Paperclip className="w-4 h-4 text-gray-500 shrink-0" />
|
<Paperclip className="w-4 h-4 text-muted-foreground shrink-0" />
|
||||||
<span className="text-sm text-gray-800 truncate">{a.nome || a.filename || `Anexo ${a.id}`}</span>
|
<span className="text-sm text-foreground truncate">{a.nome || a.filename || `Anexo ${a.id}`}</span>
|
||||||
</div>
|
</div>
|
||||||
<Button type="button" variant="ghost" className="text-red-600">
|
<Button type="button" variant="ghost" size="sm" className="text-destructive">
|
||||||
<Trash2 className="w-4 h-4 mr-1" /> Remover
|
<Trash2 className="w-4 h-4 mr-1" /> Remover
|
||||||
</Button>
|
</Button>
|
||||||
</li>
|
</li>
|
||||||
@ -289,36 +290,38 @@ export default function EditarPacientePage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<form onSubmit={handleSubmit} className="space-y-8">
|
<form onSubmit={handleSubmit} className="space-y-6 sm:space-y-8">
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
{/* --- DADOS PESSOAIS --- */}
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Dados Pessoais</h2>
|
<div className="bg-card rounded-lg border border-border p-4 sm:p-6">
|
||||||
|
<h2 className="text-lg font-semibold text-foreground mb-4 sm:mb-6">Dados Pessoais</h2>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6">
|
||||||
{/* Photo upload */}
|
{/* Photo upload Responsivo */}
|
||||||
<div className="space-y-2">
|
<div className="space-y-2 col-span-1 md:col-span-2 lg:col-span-3">
|
||||||
<Label>Foto do paciente</Label>
|
<Label>Foto do paciente</Label>
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex flex-col sm:flex-row items-start sm:items-center gap-4">
|
||||||
<div className="w-20 h-20 rounded-full bg-gray-100 overflow-hidden flex items-center justify-center">
|
<div className="w-20 h-20 rounded-full bg-muted overflow-hidden flex items-center justify-center shrink-0 border">
|
||||||
{photoUrl ? (
|
{photoUrl ? (
|
||||||
// eslint-disable-next-line @next/next/no-img-element
|
// eslint-disable-next-line @next/next/no-img-element
|
||||||
<img src={photoUrl} alt="Foto do paciente" className="w-full h-full object-cover" />
|
<img src={photoUrl} alt="Foto do paciente" className="w-full h-full object-cover" />
|
||||||
) : (
|
) : (
|
||||||
<span className="text-gray-400 text-sm">Sem foto</span>
|
<span className="text-muted-foreground text-xs text-center px-2">Sem foto</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex gap-2">
|
<div className="flex flex-wrap gap-2 w-full">
|
||||||
<input ref={fileInputRef} type="file" accept="image/*" className="hidden" />
|
<input ref={fileInputRef} type="file" accept="image/*" className="hidden" />
|
||||||
<Button type="button" variant="outline" disabled={isUploadingPhoto}>
|
<Button type="button" variant="outline" size="sm" disabled={isUploadingPhoto} className="flex-1 sm:flex-none">
|
||||||
{isUploadingPhoto ? "Enviando..." : "Enviar foto"}
|
{isUploadingPhoto ? "Enviando..." : "Enviar foto"}
|
||||||
</Button>
|
</Button>
|
||||||
{photoUrl && (
|
{photoUrl && (
|
||||||
<Button type="button" variant="ghost" disabled={isUploadingPhoto}>
|
<Button type="button" variant="ghost" size="sm" disabled={isUploadingPhoto} className="flex-1 sm:flex-none">
|
||||||
Remover
|
Remover
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="nome">Nome *</Label>
|
<Label htmlFor="nome">Nome *</Label>
|
||||||
<Input id="nome" value={formData.nome} onChange={(e) => handleInputChange("nome", e.target.value)} required />
|
<Input id="nome" value={formData.nome} onChange={(e) => handleInputChange("nome", e.target.value)} required />
|
||||||
@ -336,13 +339,13 @@ export default function EditarPacientePage() {
|
|||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label>Sexo *</Label>
|
<Label>Sexo *</Label>
|
||||||
<div className="flex gap-4">
|
<div className="flex flex-wrap gap-4 pt-2">
|
||||||
<div className="flex items-center space-x-2">
|
<div className="flex items-center space-x-2">
|
||||||
<input type="radio" id="Masculino" name="sexo" value="Masculino" checked={formData.sexo === "Masculino"} onChange={(e) => handleInputChange("sexo", e.target.value)} className="w-4 h-4 text-blue-600" />
|
<input type="radio" id="Masculino" name="sexo" value="Masculino" checked={formData.sexo === "Masculino"} onChange={(e) => handleInputChange("sexo", e.target.value)} className="w-4 h-4 text-primary" />
|
||||||
<Label htmlFor="Masculino">Masculino</Label>
|
<Label htmlFor="Masculino">Masculino</Label>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center space-x-2">
|
<div className="flex items-center space-x-2">
|
||||||
<input type="radio" id="Feminino" name="sexo" value="Feminino" checked={formData.sexo === "Feminino"} onChange={(e) => handleInputChange("sexo", e.target.value)} className="w-4 h-4 text-blue-600" />
|
<input type="radio" id="Feminino" name="sexo" value="Feminino" checked={formData.sexo === "Feminino"} onChange={(e) => handleInputChange("sexo", e.target.value)} className="w-4 h-4 text-primary" />
|
||||||
<Label htmlFor="Feminino">Feminino</Label>
|
<Label htmlFor="Feminino">Feminino</Label>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -353,12 +356,11 @@ export default function EditarPacientePage() {
|
|||||||
<Input id="dataNascimento" type="date" value={formData.dataNascimento} onChange={(e) => handleInputChange("dataNascimento", e.target.value)} required />
|
<Input id="dataNascimento" type="date" value={formData.dataNascimento} onChange={(e) => handleInputChange("dataNascimento", e.target.value)} required />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Demais campos de select e input */}
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="etnia">Etnia</Label>
|
<Label htmlFor="etnia">Etnia</Label>
|
||||||
<Select value={formData.ethnicity} onValueChange={(value) => handleInputChange("ethnicity", value)}>
|
<Select value={formData.ethnicity} onValueChange={(value) => handleInputChange("ethnicity", value)}>
|
||||||
<SelectTrigger>
|
<SelectTrigger><SelectValue placeholder="Selecione" /></SelectTrigger>
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="branca">Branca</SelectItem>
|
<SelectItem value="branca">Branca</SelectItem>
|
||||||
<SelectItem value="preta">Preta</SelectItem>
|
<SelectItem value="preta">Preta</SelectItem>
|
||||||
@ -372,9 +374,7 @@ export default function EditarPacientePage() {
|
|||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="raca">Raça</Label>
|
<Label htmlFor="raca">Raça</Label>
|
||||||
<Select value={formData.race} onValueChange={(value) => handleInputChange("race", value)}>
|
<Select value={formData.race} onValueChange={(value) => handleInputChange("race", value)}>
|
||||||
<SelectTrigger>
|
<SelectTrigger><SelectValue placeholder="Selecione" /></SelectTrigger>
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="caucasiana">Caucasiana</SelectItem>
|
<SelectItem value="caucasiana">Caucasiana</SelectItem>
|
||||||
<SelectItem value="negroide">Negroide</SelectItem>
|
<SelectItem value="negroide">Negroide</SelectItem>
|
||||||
@ -391,9 +391,7 @@ export default function EditarPacientePage() {
|
|||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="nacionalidade">Nacionalidade</Label>
|
<Label htmlFor="nacionalidade">Nacionalidade</Label>
|
||||||
<Select value={formData.nationality} onValueChange={(value) => handleInputChange("nationality", value)}>
|
<Select value={formData.nationality} onValueChange={(value) => handleInputChange("nationality", value)}>
|
||||||
<SelectTrigger>
|
<SelectTrigger><SelectValue placeholder="Selecione" /></SelectTrigger>
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="brasileira">Brasileira</SelectItem>
|
<SelectItem value="brasileira">Brasileira</SelectItem>
|
||||||
<SelectItem value="estrangeira">Estrangeira</SelectItem>
|
<SelectItem value="estrangeira">Estrangeira</SelectItem>
|
||||||
@ -409,9 +407,7 @@ export default function EditarPacientePage() {
|
|||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="estadoCivil">Estado civil</Label>
|
<Label htmlFor="estadoCivil">Estado civil</Label>
|
||||||
<Select value={formData.maritalStatus} onValueChange={(value) => handleInputChange("maritalStatus", value)}>
|
<Select value={formData.maritalStatus} onValueChange={(value) => handleInputChange("maritalStatus", value)}>
|
||||||
<SelectTrigger>
|
<SelectTrigger><SelectValue placeholder="Selecione" /></SelectTrigger>
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="solteiro">Solteiro(a)</SelectItem>
|
<SelectItem value="solteiro">Solteiro(a)</SelectItem>
|
||||||
<SelectItem value="casado">Casado(a)</SelectItem>
|
<SelectItem value="casado">Casado(a)</SelectItem>
|
||||||
@ -470,26 +466,22 @@ export default function EditarPacientePage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Contact Section */}
|
{/* --- CONTATO --- */}
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
<div className="bg-card rounded-lg border border-border p-4 sm:p-6">
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Contato</h2>
|
<h2 className="text-lg font-semibold text-foreground mb-4 sm:mb-6">Contato</h2>
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6">
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="email">E-mail *</Label>
|
<Label htmlFor="email">E-mail *</Label>
|
||||||
<Input id="email" type="email" value={formData.email} onChange={(e) => handleInputChange("email", e.target.value)} required/>
|
<Input id="email" type="email" value={formData.email} onChange={(e) => handleInputChange("email", e.target.value)} required/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="celular">Celular *</Label>
|
<Label htmlFor="celular">Celular *</Label>
|
||||||
<Input id="celular" value={formData.phoneMobile} onChange={(e) => handleInputChange("phoneMobile", e.target.value)} placeholder="(00) 00000-0000" required/>
|
<Input id="celular" value={formData.phoneMobile} onChange={(e) => handleInputChange("phoneMobile", e.target.value)} placeholder="(00) 00000-0000" required/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="telefone1">Telefone 1</Label>
|
<Label htmlFor="telefone1">Telefone 1</Label>
|
||||||
<Input id="telefone1" value={formData.phone1} onChange={(e) => handleInputChange("phone1", e.target.value)} placeholder="(00) 0000-0000" />
|
<Input id="telefone1" value={formData.phone1} onChange={(e) => handleInputChange("phone1", e.target.value)} placeholder="(00) 0000-0000" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="telefone2">Telefone 2</Label>
|
<Label htmlFor="telefone2">Telefone 2</Label>
|
||||||
<Input id="telefone2" value={formData.phone2} onChange={(e) => handleInputChange("phone2", e.target.value)} placeholder="(00) 0000-0000" />
|
<Input id="telefone2" value={formData.phone2} onChange={(e) => handleInputChange("phone2", e.target.value)} placeholder="(00) 0000-0000" />
|
||||||
@ -497,47 +489,38 @@ export default function EditarPacientePage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Address Section */}
|
{/* --- ENDEREÇO --- */}
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
<div className="bg-card rounded-lg border border-border p-4 sm:p-6">
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Endereço</h2>
|
<h2 className="text-lg font-semibold text-foreground mb-4 sm:mb-6">Endereço</h2>
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6">
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="cep">CEP</Label>
|
<Label htmlFor="cep">CEP</Label>
|
||||||
<Input id="cep" value={formData.cep} onChange={(e) => handleInputChange("cep", e.target.value)} placeholder="00000-000" />
|
<Input id="cep" value={formData.cep} onChange={(e) => handleInputChange("cep", e.target.value)} placeholder="00000-000" />
|
||||||
</div>
|
</div>
|
||||||
|
<div className="space-y-2 md:col-span-2 lg:col-span-2">
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="endereco">Endereço</Label>
|
<Label htmlFor="endereco">Endereço</Label>
|
||||||
<Input id="endereco" value={formData.street} onChange={(e) => handleInputChange("street", e.target.value)} />
|
<Input id="endereco" value={formData.street} onChange={(e) => handleInputChange("street", e.target.value)} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="numero">Número</Label>
|
<Label htmlFor="numero">Número</Label>
|
||||||
<Input id="numero" value={formData.number} onChange={(e) => handleInputChange("number", e.target.value)} />
|
<Input id="numero" value={formData.number} onChange={(e) => handleInputChange("number", e.target.value)} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="complemento">Complemento</Label>
|
<Label htmlFor="complemento">Complemento</Label>
|
||||||
<Input id="complemento" value={formData.complement} onChange={(e) => handleInputChange("complement", e.target.value)} />
|
<Input id="complemento" value={formData.complement} onChange={(e) => handleInputChange("complement", e.target.value)} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="bairro">Bairro</Label>
|
<Label htmlFor="bairro">Bairro</Label>
|
||||||
<Input id="bairro" value={formData.neighborhood} onChange={(e) => handleInputChange("neighborhood", e.target.value)} />
|
<Input id="bairro" value={formData.neighborhood} onChange={(e) => handleInputChange("neighborhood", e.target.value)} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="cidade">Cidade</Label>
|
<Label htmlFor="cidade">Cidade</Label>
|
||||||
<Input id="cidade" value={formData.city} onChange={(e) => handleInputChange("city", e.target.value)} />
|
<Input id="cidade" value={formData.city} onChange={(e) => handleInputChange("city", e.target.value)} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="estado">Estado</Label>
|
<Label htmlFor="estado">Estado</Label>
|
||||||
<Select value={formData.state} onValueChange={(value) => handleInputChange("state", value)}>
|
<Select value={formData.state} onValueChange={(value) => handleInputChange("state", value)}>
|
||||||
<SelectTrigger>
|
<SelectTrigger><SelectValue placeholder="Selecione" /></SelectTrigger>
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="AC">Acre</SelectItem>
|
<SelectItem value="AC">Acre</SelectItem>
|
||||||
<SelectItem value="AL">Alagoas</SelectItem>
|
<SelectItem value="AL">Alagoas</SelectItem>
|
||||||
@ -572,17 +555,14 @@ export default function EditarPacientePage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Medical Information Section */}
|
{/* --- INFORMAÇÕES MÉDICAS --- */}
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
<div className="bg-card rounded-lg border border-border p-4 sm:p-6">
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Informações Médicas</h2>
|
<h2 className="text-lg font-semibold text-foreground mb-4 sm:mb-6">Informações Médicas</h2>
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6">
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="tipoSanguineo">Tipo Sanguíneo</Label>
|
<Label htmlFor="tipoSanguineo">Tipo Sanguíneo</Label>
|
||||||
<Select value={formData.bloodType} onValueChange={(value) => handleInputChange("bloodType", value)}>
|
<Select value={formData.bloodType} onValueChange={(value) => handleInputChange("bloodType", value)}>
|
||||||
<SelectTrigger>
|
<SelectTrigger><SelectValue placeholder="Selecione" /></SelectTrigger>
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="A+">A+</SelectItem>
|
<SelectItem value="A+">A+</SelectItem>
|
||||||
<SelectItem value="A-">A-</SelectItem>
|
<SelectItem value="A-">A-</SelectItem>
|
||||||
@ -595,40 +575,33 @@ export default function EditarPacientePage() {
|
|||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="peso">Peso (kg)</Label>
|
<Label htmlFor="peso">Peso (kg)</Label>
|
||||||
<Input id="peso" type="number" value={formData.weightKg} onChange={(e) => handleInputChange("weightKg", e.target.value)} placeholder="0.0" />
|
<Input id="peso" type="number" value={formData.weightKg} onChange={(e) => handleInputChange("weightKg", e.target.value)} placeholder="0.0" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="altura">Altura (m)</Label>
|
<Label htmlFor="altura">Altura (m)</Label>
|
||||||
<Input id="altura" type="number" step="0.01" value={formData.heightM} onChange={(e) => handleInputChange("heightM", e.target.value)} placeholder="0.00" />
|
<Input id="altura" type="number" step="0.01" value={formData.heightM} onChange={(e) => handleInputChange("heightM", e.target.value)} placeholder="0.00" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label>IMC</Label>
|
<Label>IMC</Label>
|
||||||
<Input value={formData.weightKg && formData.heightM ? (Number.parseFloat(formData.weightKg) / Number.parseFloat(formData.heightM) ** 2).toFixed(2) : ""} disabled placeholder="Calculado automaticamente" />
|
<Input value={formData.weightKg && formData.heightM ? (Number.parseFloat(formData.weightKg) / Number.parseFloat(formData.heightM) ** 2).toFixed(2) : ""} disabled placeholder="Calculado automaticamente" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mt-6">
|
<div className="mt-6">
|
||||||
<Label htmlFor="alergias">Alergias</Label>
|
<Label htmlFor="alergias">Alergias</Label>
|
||||||
<Textarea id="alergias" onChange={(e) => handleInputChange("alergias", e.target.value)} placeholder="Ex: AAS, Dipirona, etc." className="mt-2" />
|
<Textarea id="alergias" onChange={(e) => handleInputChange("alergias", e.target.value)} placeholder="Ex: AAS, Dipirona, etc." className="mt-2" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Insurance Information Section */}
|
{/* --- CONVÊNIO --- */}
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
<div className="bg-card rounded-lg border border-border p-4 sm:p-6">
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Informações de convênio</h2>
|
<h2 className="text-lg font-semibold text-foreground mb-4 sm:mb-6">Informações de convênio</h2>
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6">
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="convenio">Convênio</Label>
|
<Label htmlFor="convenio">Convênio</Label>
|
||||||
<Select onValueChange={(value) => handleInputChange("convenio", value)}>
|
<Select onValueChange={(value) => handleInputChange("convenio", value)}>
|
||||||
<SelectTrigger>
|
<SelectTrigger><SelectValue placeholder="Selecione" /></SelectTrigger>
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="Particular">Particular</SelectItem>
|
<SelectItem value="Particular">Particular</SelectItem>
|
||||||
<SelectItem value="SUS">SUS</SelectItem>
|
<SelectItem value="SUS">SUS</SelectItem>
|
||||||
@ -638,23 +611,19 @@ export default function EditarPacientePage() {
|
|||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="plano">Plano</Label>
|
<Label htmlFor="plano">Plano</Label>
|
||||||
<Input id="plano" onChange={(e) => handleInputChange("plano", e.target.value)} />
|
<Input id="plano" onChange={(e) => handleInputChange("plano", e.target.value)} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="numeroMatricula">Nº de matrícula</Label>
|
<Label htmlFor="numeroMatricula">Nº de matrícula</Label>
|
||||||
<Input id="numeroMatricula" onChange={(e) => handleInputChange("numeroMatricula", e.target.value)} />
|
<Input id="numeroMatricula" onChange={(e) => handleInputChange("numeroMatricula", e.target.value)} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="validadeCarteira">Validade da Carteira</Label>
|
<Label htmlFor="validadeCarteira">Validade da Carteira</Label>
|
||||||
<Input id="validadeCarteira" type="date" onChange={(e) => handleInputChange("validadeCarteira", e.target.value)} disabled={validadeIndeterminada} />
|
<Input id="validadeCarteira" type="date" onChange={(e) => handleInputChange("validadeCarteira", e.target.value)} disabled={validadeIndeterminada} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mt-4">
|
<div className="mt-4">
|
||||||
<div className="flex items-center space-x-2">
|
<div className="flex items-center space-x-2">
|
||||||
<Checkbox id="validadeIndeterminada" checked={validadeIndeterminada} onCheckedChange={(checked) => setValidadeIndeterminada(checked === true)} />
|
<Checkbox id="validadeIndeterminada" checked={validadeIndeterminada} onCheckedChange={(checked) => setValidadeIndeterminada(checked === true)} />
|
||||||
@ -663,13 +632,14 @@ export default function EditarPacientePage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex justify-end gap-4">
|
{/* --- BOTÕES DE AÇÃO --- */}
|
||||||
<Link href="/manager/pacientes">
|
<div className="flex flex-col-reverse sm:flex-row justify-end gap-4 pt-4">
|
||||||
<Button type="button" variant="outline">
|
<Link href="/manager/pacientes" className="w-full sm:w-auto">
|
||||||
|
<Button type="button" variant="outline" className="w-full">
|
||||||
Cancelar
|
Cancelar
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
<Button type="submit" className="bg-blue-600 hover:bg-blue-700">
|
<Button type="submit" className="bg-primary hover:bg-primary/90 w-full sm:w-auto">
|
||||||
<Save className="w-4 h-4 mr-2" />
|
<Save className="w-4 h-4 mr-2" />
|
||||||
Salvar Alterações
|
Salvar Alterações
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@ -5,69 +5,79 @@ import Link from "next/link";
|
|||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
import { Edit, Trash2, Eye, Calendar, Filter, Loader2 } from "lucide-react";
|
import { Edit, Trash2, Eye, Calendar, Filter, Loader2, MoreVertical, Phone, MapPin, Activity, ChevronLeft, ChevronRight } 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 { patientsService } from "@/services/patientsApi.mjs";
|
import { patientsService } from "@/services/patientsApi.mjs";
|
||||||
import Sidebar from "@/components/Sidebar";
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
// Defina o tamanho da página.
|
|
||||||
const PAGE_SIZE = 5;
|
|
||||||
|
|
||||||
export default function PacientesPage() {
|
export default function PacientesPage() {
|
||||||
// --- ESTADOS DE DADOS E GERAL ---
|
// --- ESTADOS ---
|
||||||
const [searchTerm, setSearchTerm] = useState("");
|
const [searchTerm, setSearchTerm] = useState("");
|
||||||
const [convenioFilter, setConvenioFilter] = useState("all");
|
const [convenioFilter, setConvenioFilter] = useState("all");
|
||||||
const [vipFilter, setVipFilter] = useState("all");
|
const [vipFilter, setVipFilter] = useState("all");
|
||||||
|
|
||||||
// Lista completa, carregada da API uma única vez
|
|
||||||
const [allPatients, setAllPatients] = useState<any[]>([]);
|
const [allPatients, setAllPatients] = useState<any[]>([]);
|
||||||
// Lista após a aplicação dos filtros (base para a paginação)
|
|
||||||
const [filteredPatients, setFilteredPatients] = useState<any[]>([]);
|
const [filteredPatients, setFilteredPatients] = useState<any[]>([]);
|
||||||
|
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
// --- ESTADOS DE PAGINAÇÃO ---
|
// --- PAGINAÇÃO ---
|
||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
|
const [pageSize, setPageSize] = useState(10);
|
||||||
|
|
||||||
|
const totalPages = Math.ceil(filteredPatients.length / pageSize);
|
||||||
|
const startIndex = (page - 1) * pageSize;
|
||||||
|
const endIndex = startIndex + pageSize;
|
||||||
|
|
||||||
// CÁLCULO DA PAGINAÇÃO
|
|
||||||
const totalPages = Math.ceil(filteredPatients.length / PAGE_SIZE);
|
|
||||||
const startIndex = (page - 1) * PAGE_SIZE;
|
|
||||||
const endIndex = startIndex + PAGE_SIZE;
|
|
||||||
// Pacientes a serem exibidos na tabela (aplicando a paginação)
|
|
||||||
const currentPatients = filteredPatients.slice(startIndex, endIndex);
|
const currentPatients = filteredPatients.slice(startIndex, endIndex);
|
||||||
|
|
||||||
// --- ESTADOS DE DIALOGS ---
|
// --- DIALOGS ---
|
||||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||||
const [patientToDelete, setPatientToDelete] = useState<string | null>(null);
|
const [patientToDelete, setPatientToDelete] = useState<string | null>(null);
|
||||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
||||||
const [patientDetails, setPatientDetails] = useState<any | null>(null);
|
const [patientDetails, setPatientDetails] = useState<any | null>(null);
|
||||||
|
|
||||||
// --- FUNÇÕES DE LÓGICA ---
|
// --- LÓGICA DE NÚMEROS DA PAGINAÇÃO (LIMITADO A 3) ---
|
||||||
|
const getPageNumbers = () => {
|
||||||
|
const maxVisible = 3;
|
||||||
|
|
||||||
// 1. Função para carregar TODOS os pacientes da API
|
if (totalPages <= maxVisible) {
|
||||||
const fetchAllPacientes = useCallback(
|
return Array.from({ length: totalPages }, (_, i) => i + 1);
|
||||||
async () => {
|
}
|
||||||
|
|
||||||
|
let start = Math.max(1, page - 1);
|
||||||
|
let end = Math.min(totalPages, start + maxVisible - 1);
|
||||||
|
|
||||||
|
if (end === totalPages) {
|
||||||
|
start = Math.max(1, end - maxVisible + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const pages = [];
|
||||||
|
for (let i = start; i <= end; i++) {
|
||||||
|
pages.push(i);
|
||||||
|
}
|
||||||
|
return pages;
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- FETCH DADOS ---
|
||||||
|
const fetchAllPacientes = useCallback(async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
// Como o backend retorna um array, chamamos sem paginação
|
|
||||||
const res = await patientsService.list();
|
const res = await patientsService.list();
|
||||||
|
|
||||||
const mapped = res.map((p: any) => ({
|
const mapped = res.map((p: any) => ({
|
||||||
id: String(p.id ?? ""),
|
id: String(p.id ?? ""),
|
||||||
nome: p.full_name ?? "—",
|
nome: p.full_name ?? "—",
|
||||||
telefone: p.phone_mobile ?? p.phone1 ?? "—",
|
telefone: p.phone_mobile ?? p.phone1 ?? "—",
|
||||||
cidade: p.city ?? "—",
|
cidade: p.city ?? "—",
|
||||||
estado: p.state ?? "—",
|
estado: p.state ?? "—",
|
||||||
// Formate as datas se necessário, aqui usamos como string
|
|
||||||
ultimoAtendimento: p.last_visit_at?.split('T')[0] ?? "—",
|
ultimoAtendimento: p.last_visit_at?.split('T')[0] ?? "—",
|
||||||
proximoAtendimento: p.next_appointment_at?.split('T')[0] ?? "—",
|
proximoAtendimento: p.next_appointment_at?.split('T')[0] ?? "—",
|
||||||
vip: Boolean(p.vip ?? false),
|
vip: Boolean(p.vip ?? false),
|
||||||
convenio: p.convenio ?? "Particular", // Define um valor padrão
|
convenio: p.convenio ?? "Particular",
|
||||||
status: p.status ?? undefined,
|
status: p.status ?? undefined,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
setAllPatients(mapped);
|
setAllPatients(mapped);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
@ -75,52 +85,30 @@ export default function PacientesPage() {
|
|||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
},
|
}, []);
|
||||||
[]
|
|
||||||
);
|
|
||||||
|
|
||||||
// 2. Efeito para aplicar filtros e calcular a lista filtrada (chama-se quando allPatients ou filtros mudam)
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const filtered = allPatients.filter((patient) => {
|
const filtered = allPatients.filter((patient) => {
|
||||||
// Filtro por termo de busca (Nome ou Telefone)
|
const matchesSearch = patient.nome?.toLowerCase().includes(searchTerm.toLowerCase()) || patient.telefone?.includes(searchTerm);
|
||||||
const matchesSearch =
|
const matchesConvenio = convenioFilter === "all" || patient.convenio === convenioFilter;
|
||||||
patient.nome?.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
const matchesVip = vipFilter === "all" || (vipFilter === "vip" && patient.vip) || (vipFilter === "regular" && !patient.vip);
|
||||||
patient.telefone?.includes(searchTerm);
|
|
||||||
|
|
||||||
// Filtro por Convênio
|
|
||||||
const matchesConvenio =
|
|
||||||
convenioFilter === "all" ||
|
|
||||||
patient.convenio === convenioFilter;
|
|
||||||
|
|
||||||
// Filtro por VIP
|
|
||||||
const matchesVip =
|
|
||||||
vipFilter === "all" ||
|
|
||||||
(vipFilter === "vip" && patient.vip) ||
|
|
||||||
(vipFilter === "regular" && !patient.vip);
|
|
||||||
|
|
||||||
return matchesSearch && matchesConvenio && matchesVip;
|
return matchesSearch && matchesConvenio && matchesVip;
|
||||||
});
|
});
|
||||||
|
|
||||||
setFilteredPatients(filtered);
|
setFilteredPatients(filtered);
|
||||||
// Garante que a página atual seja válida após a filtragem
|
|
||||||
setPage(1);
|
setPage(1);
|
||||||
}, [allPatients, searchTerm, convenioFilter, vipFilter]);
|
}, [allPatients, searchTerm, convenioFilter, vipFilter]);
|
||||||
|
|
||||||
// 3. Efeito inicial para buscar os pacientes
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchAllPacientes();
|
fetchAllPacientes();
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// --- AÇÕES ---
|
||||||
// --- LÓGICA DE AÇÕES (DELETAR / VER DETALHES) ---
|
|
||||||
|
|
||||||
const openDetailsDialog = async (patientId: string) => {
|
const openDetailsDialog = async (patientId: string) => {
|
||||||
setDetailsDialogOpen(true);
|
setDetailsDialogOpen(true);
|
||||||
setPatientDetails(null);
|
setPatientDetails(null);
|
||||||
try {
|
try {
|
||||||
const res = await patientsService.getById(patientId);
|
const res = await patientsService.getById(patientId);
|
||||||
setPatientDetails(Array.isArray(res) ? res[0] : res); // Supondo que retorne um array com um item
|
setPatientDetails(Array.isArray(res) ? res[0] : res);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
setPatientDetails({ error: e?.message || "Erro ao buscar detalhes" });
|
setPatientDetails({ error: e?.message || "Erro ao buscar detalhes" });
|
||||||
}
|
}
|
||||||
@ -129,375 +117,219 @@ export default function PacientesPage() {
|
|||||||
const handleDeletePatient = async (patientId: string) => {
|
const handleDeletePatient = async (patientId: string) => {
|
||||||
try {
|
try {
|
||||||
await patientsService.delete(patientId);
|
await patientsService.delete(patientId);
|
||||||
// Atualiza a lista completa para refletir a exclusão
|
|
||||||
setAllPatients((prev) => prev.filter((p) => String(p.id) !== String(patientId)));
|
setAllPatients((prev) => prev.filter((p) => String(p.id) !== String(patientId)));
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
alert(`Erro ao deletar paciente: ${e?.message || 'Erro desconhecido'}`);
|
alert(`Erro ao deletar paciente: ${e?.message || "Erro desconhecido"}`);
|
||||||
}
|
}
|
||||||
setDeleteDialogOpen(false);
|
setDeleteDialogOpen(false);
|
||||||
setPatientToDelete(null);
|
setPatientToDelete(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
const openDeleteDialog = (patientId: string) => {
|
const ActionMenu = ({ patientId }: { patientId: string }) => (
|
||||||
setPatientToDelete(patientId);
|
<DropdownMenu>
|
||||||
setDeleteDialogOpen(true);
|
<DropdownMenuTrigger asChild>
|
||||||
};
|
<div className="cursor-pointer p-2 hover:bg-muted rounded-full">
|
||||||
|
<MoreVertical className="h-4 w-4" />
|
||||||
|
</div>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end">
|
||||||
|
<DropdownMenuItem onClick={() => openDetailsDialog(String(patientId))}>
|
||||||
|
<Eye className="w-4 h-4 mr-2" /> Ver detalhes
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem asChild>
|
||||||
|
<Link href={`/manager/pacientes/${patientId}/editar`} className="flex items-center w-full">
|
||||||
|
<Edit className="w-4 h-4 mr-2" /> Editar
|
||||||
|
</Link>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem>
|
||||||
|
<Calendar className="w-4 h-4 mr-2" /> Marcar consulta
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem className="text-destructive" onClick={() => { setPatientToDelete(patientId); setDeleteDialogOpen(true); }}>
|
||||||
|
<Trash2 className="w-4 h-4 mr-2" /> Excluir
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Sidebar>
|
<Sidebar>
|
||||||
<div className="space-y-6 px-2 sm:px-4 md:px-8">
|
<div className="space-y-6 px-2 sm:px-4 md:px-8 pb-20">
|
||||||
{/* Header (Responsividade OK) */}
|
{/* Header */}
|
||||||
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-xl md:text-2xl font-bold text-foreground">Pacientes</h1>
|
<h1 className="text-xl md:text-2xl font-bold">Pacientes</h1>
|
||||||
<p className="text-muted-foreground text-sm md:text-base">Gerencie as informações de seus pacientes</p>
|
<p className="text-muted-foreground text-sm md:text-base">Gerencie as informações de seus pacientes</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Bloco de Filtros (Responsividade APLICADA) */}
|
{/* Filtros */}
|
||||||
{/* Adicionado flex-wrap para permitir que os itens quebrem para a linha de baixo */}
|
<div className="flex flex-wrap items-center gap-4 bg-card p-4 rounded-lg border">
|
||||||
<div className="flex flex-wrap items-center gap-4 bg-card p-4 rounded-lg border border-border">
|
<Filter className="w-5 h-5 text-muted-foreground" />
|
||||||
<Filter className="w-5 h-5 text-gray-400" />
|
<input type="text" placeholder="Buscar por nome ou telefone..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} className="w-full sm:flex-grow sm:max-w-[300px] p-2 border rounded-md text-sm" />
|
||||||
|
|
||||||
{/* Busca - Ocupa 100% no mobile, depois cresce */}
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
placeholder="Buscar por nome ou telefone..."
|
|
||||||
value={searchTerm}
|
|
||||||
onChange={(e) => setSearchTerm(e.target.value)}
|
|
||||||
// w-full no mobile, depois flex-grow para ocupar o espaço disponível
|
|
||||||
className="w-full sm:flex-grow sm:max-w-[300px] p-2 border rounded-md text-sm"
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* Convênio - Ocupa a largura total em telas pequenas, depois se ajusta */}
|
|
||||||
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[200px]">
|
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[200px]">
|
||||||
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">Convênio</span>
|
<span className="text-sm font-medium whitespace-nowrap hidden md:block">Convênio</span>
|
||||||
<Select value={convenioFilter} onValueChange={setConvenioFilter}>
|
<Select value={convenioFilter} onValueChange={setConvenioFilter}>
|
||||||
<SelectTrigger className="w-full sm:w-40"> {/* w-full para mobile, w-40 para sm+ */}
|
<SelectTrigger className="w-full sm:w-40"><SelectValue placeholder="Convênio" /></SelectTrigger>
|
||||||
<SelectValue placeholder="Convênio" />
|
<SelectContent><SelectItem value="all">Todos</SelectItem><SelectItem value="Particular">Particular</SelectItem><SelectItem value="SUS">SUS</SelectItem><SelectItem value="Unimed">Unimed</SelectItem></SelectContent>
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="all">Todos</SelectItem>
|
|
||||||
<SelectItem value="Particular">Particular</SelectItem>
|
|
||||||
<SelectItem value="SUS">SUS</SelectItem>
|
|
||||||
<SelectItem value="Unimed">Unimed</SelectItem>
|
|
||||||
{/* Adicione outros convênios conforme necessário */}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* VIP - Ocupa a largura total em telas pequenas, depois se ajusta */}
|
|
||||||
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[150px]">
|
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[150px]">
|
||||||
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">VIP</span>
|
<span className="text-sm font-medium whitespace-nowrap hidden md:block">VIP</span>
|
||||||
<Select value={vipFilter} onValueChange={setVipFilter}>
|
<Select value={vipFilter} onValueChange={setVipFilter}>
|
||||||
<SelectTrigger className="w-full sm:w-32"> {/* w-full para mobile, w-32 para sm+ */}
|
<SelectTrigger className="w-full sm:w-32"><SelectValue placeholder="VIP" /></SelectTrigger>
|
||||||
<SelectValue placeholder="VIP" />
|
<SelectContent><SelectItem value="all">Todos</SelectItem><SelectItem value="vip">VIP</SelectItem><SelectItem value="regular">Regular</SelectItem></SelectContent>
|
||||||
</SelectTrigger>
|
</Select>
|
||||||
<SelectContent>
|
</div>
|
||||||
<SelectItem value="all">Todos</SelectItem>
|
<div className="flex items-center gap-2 w-full sm:w-auto ml-auto sm:ml-0">
|
||||||
<SelectItem value="vip">VIP</SelectItem>
|
<Select value={String(pageSize)} onValueChange={(value) => { setPageSize(Number(value)); setPage(1); }}>
|
||||||
<SelectItem value="regular">Regular</SelectItem>
|
<SelectTrigger className="w-full sm:w-[70px]"><SelectValue placeholder="10" /></SelectTrigger>
|
||||||
</SelectContent>
|
<SelectContent><SelectItem value="5">5</SelectItem><SelectItem value="10">10</SelectItem><SelectItem value="20">20</SelectItem></SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Aniversariantes - Ocupa 100% no mobile, e se alinha à direita no md+ */}
|
|
||||||
<Button variant="outline" className="w-full md:w-auto md:ml-auto">
|
|
||||||
<Calendar className="w-4 h-4 mr-2" />
|
|
||||||
Aniversariantes
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* --- SEÇÃO DE TABELA (VISÍVEL EM TELAS MAIORES OU IGUAIS A MD) --- */}
|
{/* Loading / Erro / Conteúdo */}
|
||||||
{/* Garantir que a tabela se esconda em telas menores e apareça em MD+ */}
|
|
||||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md hidden md:block">
|
|
||||||
<div className="overflow-x-auto"> {/* Permite rolagem horizontal se a tabela for muito larga */}
|
|
||||||
{error ? (
|
{error ? (
|
||||||
<div className="p-6 text-red-600">{`Erro ao carregar pacientes: ${error}`}</div>
|
<div className="p-6 text-destructive bg-card border rounded-lg">{`Erro: ${error}`}</div>
|
||||||
) : loading ? (
|
) : loading ? (
|
||||||
<div className="p-6 text-center text-gray-500 flex items-center justify-center">
|
<div className="p-6 text-center text-muted-foreground flex items-center justify-center bg-card border rounded-lg"><Loader2 className="w-6 h-6 mr-2 animate-spin text-primary" /> Carregando...</div>
|
||||||
<Loader2 className="w-6 h-6 mr-2 animate-spin text-green-600" /> Carregando pacientes...
|
|
||||||
</div>
|
|
||||||
) : (
|
) : (
|
||||||
<table className="w-full min-w-[650px]"> {/* min-w para evitar que a tabela se contraia demais */}
|
<>
|
||||||
<thead className="bg-gray-50 border-b border-gray-200">
|
{/* LISTA MOBILE */}
|
||||||
|
<div className="grid grid-cols-1 gap-4 md:hidden">
|
||||||
|
{currentPatients.length === 0 ? (
|
||||||
|
<div className="p-8 text-center text-muted-foreground bg-card rounded-lg border">Nenhum paciente encontrado.</div>
|
||||||
|
) : (
|
||||||
|
currentPatients.map((patient) => (
|
||||||
|
<div key={patient.id} className="bg-card p-4 rounded-lg border shadow-sm flex flex-col gap-3 relative">
|
||||||
|
<div className="flex justify-between items-start">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="w-10 h-10 bg-primary/10 rounded-full flex items-center justify-center"><span className="text-primary font-bold text-sm">{patient.nome?.charAt(0) || "?"}</span></div>
|
||||||
|
<div>
|
||||||
|
<div className="font-semibold flex items-center gap-2">{patient.nome}{patient.vip && <span className="px-1.5 py-0.5 text-[10px] font-bold rounded-full text-purple-600 bg-purple-100 uppercase">VIP</span>}</div>
|
||||||
|
<div className="text-xs text-muted-foreground">{patient.convenio}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<ActionMenu patientId={String(patient.id)} />
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-2 gap-2 text-sm text-muted-foreground mt-2 pt-2 border-t">
|
||||||
|
<div className="flex items-center gap-2"><Phone className="w-3 h-3" /> {patient.telefone}</div>
|
||||||
|
<div className="flex items-center gap-2"><MapPin className="w-3 h-3" /> {patient.cidade}</div>
|
||||||
|
<div className="flex items-center gap-2 col-span-2"><Activity className="w-3 h-3" /> Última: {patient.ultimoAtendimento}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* TABELA DESKTOP */}
|
||||||
|
<div className="bg-card rounded-lg border shadow-md hidden md:block">
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="w-full min-w-[650px]">
|
||||||
|
<thead className="bg-muted border-b">
|
||||||
<tr>
|
<tr>
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[20%]">Nome</th>
|
<th className="text-left p-4 font-medium text-muted-foreground w-[20%]">Nome</th>
|
||||||
{/* Ajustes de visibilidade de colunas para diferentes breakpoints */}
|
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden sm:table-cell">Telefone</th>
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">Telefone</th>
|
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden md:table-cell">Cidade / Estado</th>
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden md:table-cell">Cidade / Estado</th>
|
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden sm:table-cell">Convênio</th>
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">Convênio</th>
|
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden lg:table-cell">Último atendimento</th>
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">Último atendimento</th>
|
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden lg:table-cell">Próximo atendimento</th>
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">Próximo atendimento</th>
|
<th className="text-left p-4 font-medium text-muted-foreground w-[5%]">Ações</th>
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[5%]">Ações</th>
|
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{currentPatients.length === 0 ? (
|
{currentPatients.length === 0 ? (
|
||||||
<tr>
|
<tr><td colSpan={7} className="p-8 text-center text-muted-foreground">Nenhum paciente encontrado</td></tr>
|
||||||
<td colSpan={7} className="p-8 text-center text-gray-500">
|
|
||||||
{allPatients.length === 0 ? "Nenhum paciente cadastrado" : "Nenhum paciente encontrado com os filtros aplicados"}
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
) : (
|
) : (
|
||||||
currentPatients.map((patient) => (
|
currentPatients.map((patient) => (
|
||||||
<tr key={patient.id} className="border-b border-gray-100 hover:bg-gray-50">
|
<tr key={patient.id} className="border-b hover:bg-muted">
|
||||||
<td className="p-4">
|
<td className="p-4">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<div className="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
|
<div className="w-8 h-8 bg-primary/10 rounded-full flex items-center justify-center"><span className="text-primary font-medium text-sm">{patient.nome?.charAt(0) || "?"}</span></div>
|
||||||
<span className="text-green-600 font-medium text-sm">{patient.nome?.charAt(0) || "?"}</span>
|
<span className="font-medium">{patient.nome}{patient.vip && <span className="ml-2 px-2 py-0.5 text-xs font-semibold rounded-full text-purple-400 bg-purple-400/15">VIP</span>}</span>
|
||||||
</div>
|
|
||||||
<span className="font-medium text-gray-900">
|
|
||||||
{patient.nome}
|
|
||||||
{patient.vip && (
|
|
||||||
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-600 bg-purple-100 rounded-full">VIP</span>
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td className="p-4 text-gray-600 hidden sm:table-cell">{patient.telefone}</td>
|
<td className="p-4 text-muted-foreground hidden sm:table-cell">{patient.telefone}</td>
|
||||||
<td className="p-4 text-gray-600 hidden md:table-cell">{`${patient.cidade} / ${patient.estado}`}</td>
|
<td className="p-4 text-muted-foreground hidden md:table-cell">{`${patient.cidade} / ${patient.estado}`}</td>
|
||||||
<td className="p-4 text-gray-600 hidden sm:table-cell">{patient.convenio}</td>
|
<td className="p-4 text-muted-foreground hidden sm:table-cell">{patient.convenio}</td>
|
||||||
<td className="p-4 text-gray-600 hidden lg:table-cell">{patient.ultimoAtendimento}</td>
|
<td className="p-4 text-muted-foreground hidden lg:table-cell">{patient.ultimoAtendimento}</td>
|
||||||
<td className="p-4 text-gray-600 hidden lg:table-cell">{patient.proximoAtendimento}</td>
|
<td className="p-4 text-muted-foreground hidden lg:table-cell">{patient.proximoAtendimento}</td>
|
||||||
|
<td className="p-4"><ActionMenu patientId={String(patient.id)} /></td>
|
||||||
<td className="p-4">
|
|
||||||
<DropdownMenu>
|
|
||||||
<DropdownMenuTrigger asChild>
|
|
||||||
<div className="text-blue-600 cursor-pointer">Ações</div>
|
|
||||||
</DropdownMenuTrigger>
|
|
||||||
<DropdownMenuContent align="end">
|
|
||||||
<DropdownMenuItem onClick={() => openDetailsDialog(String(patient.id))}>
|
|
||||||
<Eye className="w-4 h-4 mr-2" />
|
|
||||||
Ver detalhes
|
|
||||||
</DropdownMenuItem>
|
|
||||||
|
|
||||||
<DropdownMenuItem asChild>
|
|
||||||
<Link href={`/secretary/pacientes/${patient.id}/editar`} className="flex items-center w-full">
|
|
||||||
<Edit className="w-4 h-4 mr-2" />
|
|
||||||
Editar
|
|
||||||
</Link>
|
|
||||||
</DropdownMenuItem>
|
|
||||||
|
|
||||||
<DropdownMenuItem>
|
|
||||||
<Calendar className="w-4 h-4 mr-2" />
|
|
||||||
Marcar consulta
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(String(patient.id))}>
|
|
||||||
<Trash2 className="w-4 h-4 mr-2" />
|
|
||||||
Excluir
|
|
||||||
</DropdownMenuItem>
|
|
||||||
</DropdownMenuContent>
|
|
||||||
</DropdownMenu>
|
|
||||||
</td>
|
|
||||||
</tr>
|
</tr>
|
||||||
))
|
))
|
||||||
)}
|
)}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* --- SEÇÃO DE CARDS (VISÍVEL APENAS EM TELAS MENORES QUE MD) --- */}
|
{/* --- RODAPÉ DE PAGINAÇÃO --- */}
|
||||||
{/* Garantir que os cards apareçam em telas menores e se escondam em MD+ */}
|
|
||||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md p-4 block md:hidden">
|
|
||||||
{error ? (
|
|
||||||
<div className="p-6 text-red-600">{`Erro ao carregar pacientes: ${error}`}</div>
|
|
||||||
) : loading ? (
|
|
||||||
<div className="p-6 text-center text-gray-500 flex items-center justify-center">
|
|
||||||
<Loader2 className="w-6 h-6 mr-2 animate-spin text-green-600" /> Carregando pacientes...
|
|
||||||
</div>
|
|
||||||
) : filteredPatients.length === 0 ? (
|
|
||||||
<div className="p-8 text-center text-gray-500">
|
|
||||||
{allPatients.length === 0 ? "Nenhum paciente cadastrado" : "Nenhum paciente encontrado com os filtros aplicados"}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="space-y-4">
|
|
||||||
{currentPatients.map((patient) => (
|
|
||||||
<div key={patient.id} className="bg-gray-50 rounded-lg p-4 flex flex-col sm:flex-row justify-between items-start sm:items-center border border-gray-200">
|
|
||||||
<div className="flex-grow mb-2 sm:mb-0">
|
|
||||||
<div className="font-semibold text-lg text-gray-900 flex items-center">
|
|
||||||
{patient.nome}
|
|
||||||
{patient.vip && (
|
|
||||||
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-600 bg-purple-100 rounded-full">VIP</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="text-sm text-gray-600">Telefone: {patient.telefone}</div>
|
|
||||||
<div className="text-sm text-gray-600">Convênio: {patient.convenio}</div>
|
|
||||||
</div>
|
|
||||||
<DropdownMenu>
|
|
||||||
<DropdownMenuTrigger asChild>
|
|
||||||
<div className="w-full"><Button variant="outline" className="w-full">Ações</Button></div>
|
|
||||||
</DropdownMenuTrigger>
|
|
||||||
<DropdownMenuContent align="end">
|
|
||||||
<DropdownMenuItem onClick={() => openDetailsDialog(String(patient.id))}>
|
|
||||||
<Eye className="w-4 h-4 mr-2" />
|
|
||||||
Ver detalhes
|
|
||||||
</DropdownMenuItem>
|
|
||||||
|
|
||||||
<DropdownMenuItem asChild>
|
|
||||||
<Link href={`/secretary/pacientes/${patient.id}/editar`} className="flex items-center w-full">
|
|
||||||
<Edit className="w-4 h-4 mr-2" />
|
|
||||||
Editar
|
|
||||||
</Link>
|
|
||||||
</DropdownMenuItem>
|
|
||||||
|
|
||||||
<DropdownMenuItem>
|
|
||||||
<Calendar className="w-4 h-4 mr-2" />
|
|
||||||
Marcar consulta
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(String(patient.id))}>
|
|
||||||
<Trash2 className="w-4 h-4 mr-2" />
|
|
||||||
Excluir
|
|
||||||
</DropdownMenuItem>
|
|
||||||
</DropdownMenuContent>
|
|
||||||
</DropdownMenu>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Paginação */}
|
|
||||||
{totalPages > 1 && !loading && (
|
{totalPages > 1 && !loading && (
|
||||||
<div className="flex flex-col sm:flex-row items-center justify-center p-4 border-t border-gray-200">
|
<div className="py-4 px-2 border-t border-border">
|
||||||
<div className="flex space-x-2 flex-wrap justify-center"> {/* Adicionado flex-wrap e justify-center para botões da paginação */}
|
|
||||||
<Button
|
{/* 1. PAGINAÇÃO MOBILE (Simples) */}
|
||||||
onClick={() => setPage((prev) => Math.max(1, prev - 1))}
|
<div className="flex items-center justify-between md:hidden gap-2">
|
||||||
disabled={page === 1}
|
<Button onClick={() => setPage((prev) => Math.max(1, prev - 1))} disabled={page === 1} variant="outline" size="sm" className="min-w-[90px]">
|
||||||
variant="outline"
|
<ChevronLeft className="w-4 h-4 mr-1" /> Anterior
|
||||||
size="lg"
|
</Button>
|
||||||
>
|
<span className="text-sm font-medium text-muted-foreground">{page} de {totalPages}</span>
|
||||||
|
<Button onClick={() => setPage((prev) => Math.min(totalPages, prev + 1))} disabled={page === totalPages} variant="outline" size="sm" className="min-w-[90px]">
|
||||||
|
Próximo <ChevronRight className="w-4 h-4 ml-1" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 2. PAGINAÇÃO DESKTOP (Numerada Limitada) */}
|
||||||
|
<div className="hidden md:flex items-center justify-center gap-2">
|
||||||
|
<Button onClick={() => setPage((prev) => Math.max(1, prev - 1))} disabled={page === 1} variant="outline" className="px-4">
|
||||||
< Anterior
|
< Anterior
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
{Array.from({ length: totalPages }, (_, index) => index + 1)
|
{getPageNumbers().map((pageNum) => (
|
||||||
.slice(Math.max(0, page - 3), Math.min(totalPages, page + 2))
|
|
||||||
.map((pageNumber) => (
|
|
||||||
<Button
|
<Button
|
||||||
key={pageNumber}
|
key={pageNum}
|
||||||
onClick={() => setPage(pageNumber)}
|
onClick={() => setPage(pageNum)}
|
||||||
variant={pageNumber === page ? "default" : "outline"}
|
/* CORREÇÃO AQUI: Removemos as classes manuais e usamos apenas o variant */
|
||||||
size="lg"
|
variant={pageNum === page ? "default" : "outline"}
|
||||||
className={pageNumber === page ? "bg-green-600 hover:bg-green-700 text-white" : "text-gray-700"}
|
className="w-10 h-10 p-0"
|
||||||
>
|
>
|
||||||
{pageNumber}
|
{pageNum}
|
||||||
</Button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
|
|
||||||
<Button
|
<Button onClick={() => setPage((prev) => Math.min(totalPages, prev + 1))} disabled={page === totalPages} variant="outline" className="px-4">
|
||||||
onClick={() => setPage((prev) => Math.min(totalPages, prev + 1))}
|
|
||||||
disabled={page === totalPages}
|
|
||||||
variant="outline"
|
|
||||||
size="lg"
|
|
||||||
>
|
|
||||||
Próximo >
|
Próximo >
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* AlertDialogs (Permanecem os mesmos) */}
|
{/* Dialogs */}
|
||||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||||
<AlertDialogContent>
|
<AlertDialogContent>
|
||||||
<AlertDialogHeader>
|
<AlertDialogHeader><AlertDialogTitle>Confirmar exclusão</AlertDialogTitle><AlertDialogDescription>Tem certeza que deseja excluir este paciente?</AlertDialogDescription></AlertDialogHeader>
|
||||||
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
|
<AlertDialogFooter><AlertDialogCancel>Cancelar</AlertDialogCancel><AlertDialogAction onClick={() => patientToDelete && handleDeletePatient(patientToDelete)} className="bg-destructive hover:bg-destructive/90">Excluir</AlertDialogAction></AlertDialogFooter>
|
||||||
<AlertDialogDescription>Tem certeza que deseja excluir este paciente? Esta ação não pode ser desfeita.</AlertDialogDescription>
|
|
||||||
</AlertDialogHeader>
|
|
||||||
<AlertDialogFooter>
|
|
||||||
<AlertDialogCancel>Cancelar</AlertDialogCancel>
|
|
||||||
<AlertDialogAction onClick={() => patientToDelete && handleDeletePatient(patientToDelete)} className="bg-red-600 hover:bg-red-700">
|
|
||||||
Excluir
|
|
||||||
</AlertDialogAction>
|
|
||||||
</AlertDialogFooter>
|
|
||||||
</AlertDialogContent>
|
</AlertDialogContent>
|
||||||
</AlertDialog>
|
</AlertDialog>
|
||||||
|
|
||||||
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
||||||
<AlertDialogContent>
|
<AlertDialogContent className="max-h-[90vh] overflow-y-auto">
|
||||||
<AlertDialogHeader>
|
<AlertDialogHeader><AlertDialogTitle>Detalhes do Paciente</AlertDialogTitle></AlertDialogHeader>
|
||||||
<AlertDialogTitle>Detalhes do Paciente</AlertDialogTitle>
|
|
||||||
<AlertDialogDescription>
|
<AlertDialogDescription>
|
||||||
{patientDetails === null ? (
|
{patientDetails ? (!patientDetails.error ? (
|
||||||
<div className="text-gray-500">
|
<div className="grid gap-4 py-4 text-left">
|
||||||
<Loader2 className="w-6 h-6 animate-spin mx-auto text-green-600 my-4" />
|
|
||||||
Carregando...
|
|
||||||
</div>
|
|
||||||
) : patientDetails?.error ? (
|
|
||||||
<div className="text-red-600 p-4">{patientDetails.error}</div>
|
|
||||||
) : (
|
|
||||||
<div className="grid gap-4 py-4">
|
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||||
<div>
|
<div><p className="font-semibold text-xs text-muted-foreground">NOME</p><p>{patientDetails.full_name}</p></div>
|
||||||
<p className="font-semibold">Nome Completo</p>
|
<div><p className="font-semibold text-xs text-muted-foreground">EMAIL</p><p className="break-all">{patientDetails.email}</p></div>
|
||||||
<p>{patientDetails.full_name}</p>
|
<div><p className="font-semibold text-xs text-muted-foreground">TELEFONE</p><p>{patientDetails.phone_mobile}</p></div>
|
||||||
|
<div><p className="font-semibold text-xs text-muted-foreground">DATA NASC.</p><p>{patientDetails.birth_date}</p></div>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div className="border-t pt-4"><p className="font-semibold text-primary mb-2">Endereço</p><p>{patientDetails.street}, {patientDetails.number}</p><p>{patientDetails.cidade}/{patientDetails.estado}</p></div>
|
||||||
<p className="font-semibold">Email</p>
|
|
||||||
<p>{patientDetails.email}</p>
|
|
||||||
</div>
|
</div>
|
||||||
<div>
|
) : <p className="text-destructive">{patientDetails.error}</p>) : <Loader2 className="w-6 h-6 animate-spin mx-auto text-primary" />}
|
||||||
<p className="font-semibold">Telefone</p>
|
|
||||||
<p>{patientDetails.phone_mobile}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Data de Nascimento</p>
|
|
||||||
<p>{patientDetails.birth_date}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">CPF</p>
|
|
||||||
<p>{patientDetails.cpf}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Tipo Sanguíneo</p>
|
|
||||||
<p>{patientDetails.blood_type}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Peso (kg)</p>
|
|
||||||
<p>{patientDetails.weight_kg}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Altura (m)</p>
|
|
||||||
<p>{patientDetails.height_m}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="border-t pt-4 mt-4">
|
|
||||||
<h3 className="font-semibold mb-2">Endereço</h3>
|
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Rua</p>
|
|
||||||
<p>{`${patientDetails.street}, ${patientDetails.number}`}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Complemento</p>
|
|
||||||
<p>{patientDetails.complement}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Bairro</p>
|
|
||||||
<p>{patientDetails.neighborhood}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Cidade</p>
|
|
||||||
<p>{patientDetails.cidade}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Estado</p>
|
|
||||||
<p>{patientDetails.estado}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">CEP</p>
|
|
||||||
<p>{patientDetails.cep}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</AlertDialogDescription>
|
</AlertDialogDescription>
|
||||||
</AlertDialogHeader>
|
<AlertDialogFooter><AlertDialogCancel>Fechar</AlertDialogCancel></AlertDialogFooter>
|
||||||
<AlertDialogFooter>
|
|
||||||
<AlertDialogCancel>Fechar</AlertDialogCancel>
|
|
||||||
</AlertDialogFooter>
|
|
||||||
</AlertDialogContent>
|
</AlertDialogContent>
|
||||||
</AlertDialog>
|
</AlertDialog>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -157,8 +157,8 @@ export default function EditarUsuarioPage() {
|
|||||||
return (
|
return (
|
||||||
<Sidebar>
|
<Sidebar>
|
||||||
<div className="flex justify-center items-center h-full w-full py-16">
|
<div className="flex justify-center items-center h-full w-full py-16">
|
||||||
<Loader2 className="w-8 h-8 animate-spin text-green-600" />
|
<Loader2 className="w-8 h-8 animate-spin text-primary" />
|
||||||
<p className="ml-2 text-gray-600">Carregando dados do usuário...</p>
|
<p className="ml-2 text-muted-foreground">Carregando dados do usuário...</p>
|
||||||
</div>
|
</div>
|
||||||
</Sidebar>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
@ -169,10 +169,10 @@ export default function EditarUsuarioPage() {
|
|||||||
<div className="w-full max-w-2xl mx-auto space-y-6 p-4 md:p-8">
|
<div className="w-full max-w-2xl mx-auto space-y-6 p-4 md:p-8">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-gray-900">
|
<h1 className="text-2xl font-bold text-foreground">
|
||||||
Editar Usuário: <span className="text-green-600">{formData.nomeCompleto}</span>
|
Editar Usuário: <span className="text-primary">{formData.nomeCompleto}</span>
|
||||||
</h1>
|
</h1>
|
||||||
<p className="text-sm text-gray-500">
|
<p className="text-sm text-muted-foreground">
|
||||||
Atualize as informações do usuário (ID: {id}).
|
Atualize as informações do usuário (ID: {id}).
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@ -184,9 +184,9 @@ export default function EditarUsuarioPage() {
|
|||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<form onSubmit={handleSubmit} className="space-y-8 bg-white p-8 border rounded-lg shadow-sm">
|
<form onSubmit={handleSubmit} className="space-y-8 bg-card p-8 border border-border rounded-lg shadow-sm">
|
||||||
{error && (
|
{error && (
|
||||||
<div className="p-3 bg-red-100 text-red-700 rounded-lg border border-red-300">
|
<div className="p-3 rounded-lg border bg-destructive/10 text-destructive border-destructive/30">
|
||||||
<p className="font-medium">Erro na Atualização:</p>
|
<p className="font-medium">Erro na Atualização:</p>
|
||||||
<p className="text-sm">{error}</p>
|
<p className="text-sm">{error}</p>
|
||||||
</div>
|
</div>
|
||||||
@ -261,7 +261,7 @@ export default function EditarUsuarioPage() {
|
|||||||
</Link>
|
</Link>
|
||||||
<Button
|
<Button
|
||||||
type="submit"
|
type="submit"
|
||||||
className="bg-green-600 hover:bg-green-700"
|
className="bg-primary hover:bg-primary/90"
|
||||||
disabled={isSaving}
|
disabled={isSaving}
|
||||||
>
|
>
|
||||||
{isSaving ? (
|
{isSaving ? (
|
||||||
|
|||||||
@ -140,17 +140,17 @@ export default function NovoUsuarioPage() {
|
|||||||
<div className="w-full max-w-screen-lg space-y-8">
|
<div className="w-full max-w-screen-lg space-y-8">
|
||||||
<div className="flex items-center justify-between border-b pb-4">
|
<div className="flex items-center justify-between border-b pb-4">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-extrabold text-gray-900">Novo Usuário</h1>
|
<h1 className="text-3xl font-extrabold">Novo Usuário</h1>
|
||||||
<p className="text-md text-gray-500">Preencha os dados para cadastrar um novo usuário no sistema.</p>
|
<p className="text-md text-muted-foreground">Preencha os dados para cadastrar um novo usuário no sistema.</p>
|
||||||
</div>
|
</div>
|
||||||
<Link href="/manager/usuario">
|
<Link href="/manager/usuario">
|
||||||
<Button variant="outline">Cancelar</Button>
|
<Button variant="outline">Cancelar</Button>
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<form onSubmit={handleSubmit} className="space-y-6 bg-white p-6 md:p-10 border rounded-xl shadow-lg">
|
<form onSubmit={handleSubmit} className="space-y-6 bg-card p-6 md:p-10 border rounded-xl shadow-lg">
|
||||||
{error && (
|
{error && (
|
||||||
<div className="p-4 bg-red-50 text-red-700 rounded-lg border border-red-300">
|
<div className="p-4 bg-destructive/10 text-destructive rounded-lg border border-destructive">
|
||||||
<p className="font-semibold">Erro no Cadastro:</p>
|
<p className="font-semibold">Erro no Cadastro:</p>
|
||||||
<p className="text-sm break-words">{error}</p>
|
<p className="text-sm break-words">{error}</p>
|
||||||
</div>
|
</div>
|
||||||
@ -208,7 +208,7 @@ export default function NovoUsuarioPage() {
|
|||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="confirmarSenha">Confirmar Senha *</Label>
|
<Label htmlFor="confirmarSenha">Confirmar Senha *</Label>
|
||||||
<Input id="confirmarSenha" type="password" value={formData.confirmarSenha} onChange={(e) => handleInputChange("confirmarSenha", e.target.value)} placeholder="Repita a senha" required />
|
<Input id="confirmarSenha" type="password" value={formData.confirmarSenha} onChange={(e) => handleInputChange("confirmarSenha", e.target.value)} placeholder="Repita a senha" required />
|
||||||
{formData.senha && formData.confirmarSenha && formData.senha !== formData.confirmarSenha && <p className="text-xs text-red-500">As senhas não coincidem.</p>}
|
{formData.senha && formData.confirmarSenha && formData.senha !== formData.confirmarSenha && <p className="text-xs text-destructive">As senhas não coincidem.</p>}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
@ -228,7 +228,7 @@ export default function NovoUsuarioPage() {
|
|||||||
Cancelar
|
Cancelar
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
<Button type="submit" className="bg-green-600 hover:bg-green-700" disabled={isSaving}>
|
<Button type="submit" className="bg-primary hover:bg-primary/90" disabled={isSaving}>
|
||||||
{isSaving ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Save className="w-4 h-4 mr-2" />}
|
{isSaving ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Save className="w-4 h-4 mr-2" />}
|
||||||
{isSaving ? "Salvando..." : "Salvar Usuário"}
|
{isSaving ? "Salvando..." : "Salvar Usuário"}
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@ -4,7 +4,8 @@ import React, { useEffect, useState, useCallback } from "react";
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
import { Plus, Eye, Filter, Loader2 } from "lucide-react";
|
import { Input } from "@/components/ui/input"; // <--- 1. Importação Adicionada
|
||||||
|
import { Plus, Eye, Filter, Loader2, Search } from "lucide-react"; // <--- 1. Ícone Search Adicionado
|
||||||
import { AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
import { AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||||
import { api, login } from "services/api.mjs";
|
import { api, login } from "services/api.mjs";
|
||||||
import { usersService } from "services/usersApi.mjs";
|
import { usersService } from "services/usersApi.mjs";
|
||||||
@ -31,9 +32,10 @@ export default function UsersPage() {
|
|||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
||||||
const [userDetails, setUserDetails] = useState<UserInfoResponse | null>(
|
const [userDetails, setUserDetails] = useState<UserInfoResponse | null>(null);
|
||||||
null
|
|
||||||
);
|
// --- Estados de Filtro ---
|
||||||
|
const [searchTerm, setSearchTerm] = useState(""); // <--- 2. Estado da busca
|
||||||
const [selectedRole, setSelectedRole] = useState<string>("all");
|
const [selectedRole, setSelectedRole] = useState<string>("all");
|
||||||
|
|
||||||
// --- Lógica de Paginação INÍCIO ---
|
// --- Lógica de Paginação INÍCIO ---
|
||||||
@ -118,10 +120,21 @@ export default function UsersPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const filteredUsers =
|
// --- 3. Lógica de Filtragem Atualizada ---
|
||||||
selectedRole && selectedRole !== "all"
|
const filteredUsers = users.filter((u) => {
|
||||||
? users.filter((u) => u.role === selectedRole)
|
// Filtro por Papel (Role)
|
||||||
: users;
|
const roleMatch = selectedRole === "all" || u.role === selectedRole;
|
||||||
|
|
||||||
|
// Filtro da Barra de Pesquisa (Nome, Email ou Telefone)
|
||||||
|
const searchLower = searchTerm.toLowerCase();
|
||||||
|
const nameMatch = u.full_name?.toLowerCase().includes(searchLower);
|
||||||
|
const emailMatch = u.email?.toLowerCase().includes(searchLower);
|
||||||
|
const phoneMatch = u.phone?.includes(searchLower);
|
||||||
|
|
||||||
|
const searchMatch = !searchTerm || nameMatch || emailMatch || phoneMatch;
|
||||||
|
|
||||||
|
return roleMatch && searchMatch;
|
||||||
|
});
|
||||||
|
|
||||||
const indexOfLastItem = currentPage * itemsPerPage;
|
const indexOfLastItem = currentPage * itemsPerPage;
|
||||||
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
||||||
@ -166,28 +179,39 @@ export default function UsersPage() {
|
|||||||
return (
|
return (
|
||||||
<Sidebar>
|
<Sidebar>
|
||||||
<div className="space-y-6 px-2 sm:px-4 md:px-8">
|
<div className="space-y-6 px-2 sm:px-4 md:px-8">
|
||||||
|
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-gray-900">Usuários</h1>
|
<h1 className="text-2xl font-bold">Usuários</h1>
|
||||||
<p className="text-sm text-gray-500">Gerencie usuários.</p>
|
<p className="text-sm text-muted-foreground">Gerencie usuários.</p>
|
||||||
</div>
|
</div>
|
||||||
<Link href="/manager/usuario/novo" className="w-full sm:w-auto">
|
<Link href="/manager/usuario/novo" className="w-full sm:w-auto">
|
||||||
<Button className="w-full sm:w-auto bg-green-600 hover:bg-green-700">
|
<Button className="w-full sm:w-auto">
|
||||||
<Plus className="w-4 h-4 mr-2" /> Novo Usuário
|
<Plus className="w-4 h-4 mr-2" /> Novo Usuário
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Filtro e Itens por Página */}
|
{/* --- 4. Filtro (Barra de Pesquisa + Selects) --- */}
|
||||||
<div className="flex flex-wrap items-center gap-3 bg-white p-4 rounded-lg border border-gray-200">
|
<div className="flex flex-col md:flex-row items-start md:items-center gap-3 bg-card p-4 rounded-lg border">
|
||||||
|
|
||||||
{/* Select de Filtro por Papel - Ajustado para resetar a página */}
|
{/* Barra de Pesquisa */}
|
||||||
|
<div className="relative w-full md:flex-1">
|
||||||
|
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||||
|
<Input
|
||||||
|
placeholder="Buscar por nome, e-mail ou telefone..."
|
||||||
|
value={searchTerm}
|
||||||
|
onChange={(e) => {
|
||||||
|
setSearchTerm(e.target.value);
|
||||||
|
setCurrentPage(1); // Reseta a paginação ao pesquisar
|
||||||
|
}}
|
||||||
|
className="pl-10 w-full bg-muted border-border focus:bg-card transition-colors"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap items-center gap-3 w-full md:w-auto">
|
||||||
|
{/* Select de Filtro por Papel */}
|
||||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
<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
|
<Select
|
||||||
onValueChange={(value) => {
|
onValueChange={(value) => {
|
||||||
setSelectedRole(value);
|
setSelectedRole(value);
|
||||||
@ -195,8 +219,8 @@ export default function UsersPage() {
|
|||||||
}}
|
}}
|
||||||
value={selectedRole}>
|
value={selectedRole}>
|
||||||
|
|
||||||
<SelectTrigger className="w-full sm:w-[180px]"> {/* w-full para mobile, w-[180px] para sm+ */}
|
<SelectTrigger className="w-full sm:w-[150px]">
|
||||||
<SelectValue placeholder="Filtrar por papel" />
|
<SelectValue placeholder="Papel" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="all">Todos</SelectItem>
|
<SelectItem value="all">Todos</SelectItem>
|
||||||
@ -211,69 +235,78 @@ export default function UsersPage() {
|
|||||||
|
|
||||||
{/* Select de Itens por Página */}
|
{/* Select de Itens por Página */}
|
||||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
<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
|
<Select
|
||||||
onValueChange={handleItemsPerPageChange}
|
onValueChange={handleItemsPerPageChange}
|
||||||
defaultValue={String(itemsPerPage)}
|
defaultValue={String(itemsPerPage)}
|
||||||
>
|
>
|
||||||
<SelectTrigger className="w-full sm:w-[140px]"> {/* w-full para mobile, w-[140px] para sm+ */}
|
<SelectTrigger className="w-full sm:w-[80px]">
|
||||||
<SelectValue placeholder="Itens por pág." />
|
<SelectValue placeholder="10" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="5">5 por página</SelectItem>
|
<SelectItem value="5">5</SelectItem>
|
||||||
<SelectItem value="10">10 por página</SelectItem>
|
<SelectItem value="10">10</SelectItem>
|
||||||
<SelectItem value="20">20 por página</SelectItem>
|
<SelectItem value="20">20</SelectItem>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
<Button variant="outline" className="ml-auto w-full md:w-auto">
|
|
||||||
|
<Button variant="outline" className="ml-auto w-full md:w-auto hidden lg:flex">
|
||||||
<Filter className="w-4 h-4 mr-2" />
|
<Filter className="w-4 h-4 mr-2" />
|
||||||
Filtro avançado
|
Filtros
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
{/* Fim do Filtro e Itens por Página */}
|
</div>
|
||||||
|
{/* Fim do Filtro */}
|
||||||
|
|
||||||
{/* Tabela/Lista */}
|
{/* Tabela/Lista */}
|
||||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-x-auto">
|
<div className="bg-card rounded-lg border shadow-md overflow-x-auto">
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="p-8 text-center text-gray-500">
|
<div className="p-8 text-center text-muted-foreground">
|
||||||
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
|
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-primary" />
|
||||||
Carregando usuários...
|
Carregando usuários...
|
||||||
</div>
|
</div>
|
||||||
) : error ? (
|
) : error ? (
|
||||||
<div className="p-8 text-center text-red-600">{error}</div>
|
<div className="p-8 text-center text-destructive">{error}</div>
|
||||||
) : filteredUsers.length === 0 ? (
|
) : filteredUsers.length === 0 ? (
|
||||||
<div className="p-8 text-center text-gray-500">
|
<div className="p-8 text-center text-muted-foreground">
|
||||||
Nenhum usuário encontrado com os filtros aplicados.
|
Nenhum usuário encontrado com os filtros aplicados.
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
{/* Tabela para Telas Médias e Grandes */}
|
{/* Tabela para Telas Médias e Grandes */}
|
||||||
<table className="min-w-full divide-y divide-gray-200 hidden md:table">
|
<table className="min-w-full divide-y hidden md:table">
|
||||||
<thead className="bg-gray-50">
|
<thead className="bg-muted">
|
||||||
<tr>
|
<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-muted-foreground uppercase">
|
||||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">E-mail</th>
|
Nome
|
||||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Telefone</th>
|
</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-left text-xs font-medium text-muted-foreground uppercase">
|
||||||
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">Ações</th>
|
E-mail
|
||||||
|
</th>
|
||||||
|
<th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
|
||||||
|
Telefone
|
||||||
|
</th>
|
||||||
|
<th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
|
||||||
|
Cargo
|
||||||
|
</th>
|
||||||
|
<th className="px-6 py-3 text-right text-xs font-medium text-muted-foreground uppercase">
|
||||||
|
Ações
|
||||||
|
</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody className="bg-white divide-y divide-gray-200">
|
<tbody className="bg-card divide-y">
|
||||||
{currentItems.map((u) => (
|
{currentItems.map((u) => (
|
||||||
<tr key={u.id} className="hover:bg-gray-50">
|
<tr key={u.id} className="hover:bg-muted">
|
||||||
<td className="px-6 py-4 text-sm text-gray-900">
|
<td className="px-6 py-4 text-sm">
|
||||||
{u.full_name}
|
{u.full_name}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 text-sm text-gray-500 break-all">
|
<td className="px-6 py-4 text-sm text-muted-foreground break-all">
|
||||||
{u.email}
|
{u.email}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 text-sm text-gray-500">
|
<td className="px-6 py-4 text-sm text-muted-foreground">
|
||||||
{u.phone}
|
{u.phone}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 text-sm text-gray-500 capitalize">
|
<td className="px-6 py-4 text-sm text-muted-foreground capitalize">
|
||||||
{u.role}
|
{u.role}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 text-right">
|
<td className="px-6 py-4 text-right">
|
||||||
@ -292,14 +325,17 @@ export default function UsersPage() {
|
|||||||
</table>
|
</table>
|
||||||
|
|
||||||
{/* Layout em Cards/Lista para Telas Pequenas */}
|
{/* Layout em Cards/Lista para Telas Pequenas */}
|
||||||
<div className="md:hidden divide-y divide-gray-200">
|
<div className="md:hidden divide-y">
|
||||||
{currentItems.map((u) => (
|
{currentItems.map((u) => (
|
||||||
<div key={u.id} className="flex items-center justify-between p-4 hover:bg-gray-50">
|
<div key={u.id} className="flex items-center justify-between p-4 hover:bg-muted">
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<div className="text-sm font-medium text-gray-900 truncate">
|
<div className="text-sm font-medium truncate">
|
||||||
{u.full_name || "—"}
|
{u.full_name || "—"}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-sm text-gray-500 capitalize">
|
<div className="text-xs text-muted-foreground truncate">
|
||||||
|
{u.email}
|
||||||
|
</div>
|
||||||
|
<div className="text-sm text-muted-foreground capitalize mt-1">
|
||||||
{u.role || "—"}
|
{u.role || "—"}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -319,13 +355,12 @@ export default function UsersPage() {
|
|||||||
|
|
||||||
{/* Paginação */}
|
{/* Paginação */}
|
||||||
{totalPages > 1 && (
|
{totalPages > 1 && (
|
||||||
<div className="flex flex-wrap justify-center items-center gap-2 mt-4 p-4 border-t border-gray-200">
|
<div className="flex flex-wrap justify-center items-center gap-2 mt-4 p-4 border-t">
|
||||||
|
|
||||||
{/* Botão Anterior */}
|
{/* Botão Anterior */}
|
||||||
<button
|
<button
|
||||||
onClick={goToPrevPage}
|
onClick={goToPrevPage}
|
||||||
disabled={currentPage === 1}
|
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"
|
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-muted text-muted-foreground hover:bg-muted/90 disabled:opacity-50 disabled:cursor-not-allowed border"
|
||||||
>
|
>
|
||||||
{"< Anterior"}
|
{"< Anterior"}
|
||||||
</button>
|
</button>
|
||||||
@ -335,9 +370,10 @@ export default function UsersPage() {
|
|||||||
<button
|
<button
|
||||||
key={number}
|
key={number}
|
||||||
onClick={() => paginate(number)}
|
onClick={() => paginate(number)}
|
||||||
className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border border-gray-300 ${currentPage === number
|
className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border ${
|
||||||
? "bg-green-600 text-white shadow-md border-green-600"
|
currentPage === number
|
||||||
: "bg-gray-100 text-gray-700 hover:bg-gray-200"
|
? "bg-primary text-primary-foreground shadow-md border-primary"
|
||||||
|
: "bg-muted text-muted-foreground hover:bg-muted/90"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{number}
|
{number}
|
||||||
@ -348,11 +384,10 @@ export default function UsersPage() {
|
|||||||
<button
|
<button
|
||||||
onClick={goToNextPage}
|
onClick={goToNextPage}
|
||||||
disabled={currentPage === totalPages}
|
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"
|
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-muted text-muted-foreground hover:bg-muted/90 disabled:opacity-50 disabled:cursor-not-allowed border"
|
||||||
>
|
>
|
||||||
{"Próximo >"}
|
{"Próximo >"}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
@ -360,7 +395,10 @@ export default function UsersPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Modal de Detalhes */}
|
{/* Modal de Detalhes */}
|
||||||
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
<AlertDialog
|
||||||
|
open={detailsDialogOpen}
|
||||||
|
onOpenChange={setDetailsDialogOpen}
|
||||||
|
>
|
||||||
<AlertDialogContent>
|
<AlertDialogContent>
|
||||||
<AlertDialogHeader>
|
<AlertDialogHeader>
|
||||||
<AlertDialogTitle className="text-2xl">
|
<AlertDialogTitle className="text-2xl">
|
||||||
@ -368,12 +406,12 @@ export default function UsersPage() {
|
|||||||
</AlertDialogTitle>
|
</AlertDialogTitle>
|
||||||
<AlertDialogDescription>
|
<AlertDialogDescription>
|
||||||
{!userDetails ? (
|
{!userDetails ? (
|
||||||
<div className="p-4 text-center text-gray-500">
|
<div className="p-4 text-center text-muted-foreground">
|
||||||
<Loader2 className="w-6 h-6 animate-spin mx-auto mb-3 text-green-600" />
|
<Loader2 className="w-6 h-6 animate-spin mx-auto mb-3 text-primary" />
|
||||||
Buscando dados completos...
|
Buscando dados completos...
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-3 pt-2 text-left text-gray-700">
|
<div className="space-y-3 pt-2 text-left text-muted-foreground">
|
||||||
<div>
|
<div>
|
||||||
<strong>ID:</strong> {userDetails.user.id}
|
<strong>ID:</strong> {userDetails.user.id}
|
||||||
</div>
|
</div>
|
||||||
@ -388,19 +426,25 @@ export default function UsersPage() {
|
|||||||
<strong>Telefone:</strong> {userDetails.profile.phone}
|
<strong>Telefone:</strong> {userDetails.profile.phone}
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<strong>Roles:</strong>{" "}
|
<strong>Roles:</strong> {userDetails.roles?.join(", ")}
|
||||||
{userDetails.roles?.join(", ")}
|
|
||||||
</div>
|
</div>
|
||||||
<div className="pt-2">
|
<div className="pt-2">
|
||||||
<strong className="block mb-1">Permissões:</strong>
|
<strong className="block mb-1">Permissões:</strong>
|
||||||
<ul className="list-disc list-inside space-y-0.5 text-sm">
|
<ul className="list-disc list-inside space-y-0.5 text-sm">
|
||||||
{Object.entries(
|
{Object.entries(userDetails.permissions || {}).map(
|
||||||
userDetails.permissions || {}
|
([k, v]) => (
|
||||||
).map(([k, v]) => (
|
|
||||||
<li key={k}>
|
<li key={k}>
|
||||||
{k}: <span className={`font-semibold ${v ? 'text-green-600' : 'text-red-600'}`}>{v ? "Sim" : "Não"}</span>
|
{k}:{" "}
|
||||||
|
<span
|
||||||
|
className={`font-semibold ${
|
||||||
|
v ? "text-primary" : "text-destructive"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{v ? "Sim" : "Não"}
|
||||||
|
</span>
|
||||||
</li>
|
</li>
|
||||||
))}
|
)
|
||||||
|
)}
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
173
app/page.tsx
173
app/page.tsx
@ -3,50 +3,55 @@
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
|
import { Stethoscope, Baby, Microscope } from "lucide-react";
|
||||||
|
import { useAccessibility } from "./context/AccessibilityContext";
|
||||||
|
|
||||||
export default function InicialPage() {
|
export default function InicialPage() {
|
||||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||||
|
const { contrast } = useAccessibility();
|
||||||
|
|
||||||
|
const heroClass = contrast === "high"
|
||||||
|
? "px-6 md:px-10 lg:px-20 py-20 bg-background text-foreground border-y-2 border-primary"
|
||||||
|
: "px-6 md:px-10 lg:px-20 py-20 bg-gradient-to-r from-[#1E2A78] via-[#007BFF] to-[#00BFFF] text-white";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen flex flex-col bg-background">
|
<div className="min-h-screen flex flex-col bg-background font-sans scroll-smooth text-foreground">
|
||||||
{/* Barra superior de informações */}
|
{/* Barra superior */}
|
||||||
<div className="bg-primary text-primary-foreground text-sm py-2 px-4 md:px-6 flex justify-between items-center">
|
<div className="bg-primary text-primary-foreground 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 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>
|
</div>
|
||||||
|
{/* Header */}
|
||||||
{/* Header principal - Com Logo REAL */}
|
<header className="bg-muted text-foreground shadow-md py-4 px-4 md:px-6 flex justify-between items-center relative sticky top-0 z-50 backdrop-blur-md">
|
||||||
<header className="bg-card shadow-md py-4 px-4 md:px-6 flex justify-between items-center relative">
|
<a href="#home" className="flex items-center space-x-2 cursor-pointer">
|
||||||
{/* 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 */}
|
|
||||||
<img
|
<img
|
||||||
src="/android-chrome-512x512.png" // O caminho se inicia a partir da pasta 'public'
|
src="/android-chrome-512x512.png"
|
||||||
alt="Logo MediConnect"
|
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"
|
||||||
/>
|
/>
|
||||||
|
<h1 className="text-2xl font-extrabold text-foreground tracking-tight">
|
||||||
{/* 2. NOME DO SITE */}
|
MedConnect
|
||||||
<h1 className="text-2xl font-bold text-primary">MediConnect</h1>
|
</h1>
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
{/* Botão do menu hambúrguer para telas menores */}
|
{/* Menu Mobile */}
|
||||||
<div className="md:hidden flex items-center space-x-4">
|
<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">
|
<Link href="/login">
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
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-primary text-primary hover:bg-primary hover:text-primary-foreground transition"
|
||||||
>
|
>
|
||||||
Login
|
Login
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
<button
|
<button
|
||||||
onClick={() => setIsMenuOpen(!isMenuOpen)}
|
onClick={() => setIsMenuOpen(!isMenuOpen)}
|
||||||
className="text-primary-foreground focus:outline-none"
|
className="text-[#1E2A78] focus:outline-none"
|
||||||
>
|
>
|
||||||
<svg
|
<svg
|
||||||
className="w-6 h-6 text-primary"
|
className="w-6 h-6"
|
||||||
fill="none"
|
fill="none"
|
||||||
stroke="currentColor"
|
stroke="currentColor"
|
||||||
viewBox="0 0 24 24"
|
viewBox="0 0 24 24"
|
||||||
@ -71,114 +76,140 @@ export default function InicialPage() {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Navegação principal */}
|
{/* Navegação */}
|
||||||
<nav
|
<nav
|
||||||
className={`${
|
className={`${
|
||||||
isMenuOpen ? "block" : "hidden"
|
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">
|
<div className="flex flex-col md:flex-row space-y-4 md:space-y-0 md:space-x-8 text-foreground font-medium items-center">
|
||||||
<Link href="#home" className="hover:text-primary">
|
<Link href="#home" className="hover:text-primary transition">
|
||||||
Home
|
Home
|
||||||
</Link>
|
</Link>
|
||||||
<a href="#about" className="hover:text-primary">
|
<a href="#about" className="hover:text-primary transition">
|
||||||
Sobre
|
Sobre
|
||||||
</a>
|
</a>
|
||||||
<a href="#departments" className="hover:text-primary">
|
<a href="#departments" className="hover:text-primary transition">
|
||||||
Departamentos
|
Departamentos
|
||||||
</a>
|
</a>
|
||||||
<a href="#doctors" className="hover:text-primary">
|
<a href="#doctors" className="hover:text-primary transition">
|
||||||
Médicos
|
Médicos
|
||||||
</a>
|
</a>
|
||||||
<a href="#contact" className="hover:text-primary">
|
<a href="#contact" className="hover:text-primary transition">
|
||||||
Contato
|
Contato
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
{/* Botão de Login para telas maiores (md e acima) */}
|
{/* Login Desktop */}
|
||||||
<div className="hidden md:flex space-x-4">
|
<div className="hidden md:flex space-x-4">
|
||||||
<Link href="/login">
|
<Link href="/login">
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
className="rounded-full px-6 py-2 border-2 transition cursor-pointer"
|
className="rounded-full px-6 py-2 border-2 border-primary text-primary hover:bg-primary hover:text-primary-foreground transition cursor-pointer"
|
||||||
>
|
>
|
||||||
Login
|
Login
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
{/* Hero Section */}
|
||||||
{/* Seção principal de destaque */}
|
<section className={`flex flex-col md:flex-row items-center justify-between ${heroClass}`}>
|
||||||
<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">
|
|
||||||
<div className="max-w-lg mx-auto md:mx-0">
|
<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
|
Bem-vindo à Saúde Digital
|
||||||
</h2>
|
</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
|
Soluções Médicas <br /> & Cuidados com a Saúde
|
||||||
</h1>
|
</h1>
|
||||||
<p className="text-muted-foreground mt-4 text-sm sm:text-base">
|
<p className="mt-4 text-base leading-relaxed opacity-90 text-foreground">
|
||||||
Excelência em saúde há mais de 25 anos. Atendimento médico com
|
Excelência em saúde há mais de 25 anos. Atendimento médico com
|
||||||
qualidade, segurança e carinho.
|
qualidade, segurança e carinho.
|
||||||
</p>
|
</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">
|
<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>Nossos Serviços</Button>
|
<Button className="px-8 py-3 text-base font-semibold bg-card text-card-foreground hover:bg-muted transition-all shadow-md">
|
||||||
<Button variant="secondary">Saiba Mais</Button>
|
Nossos Serviços
|
||||||
|
</Button>
|
||||||
|
<Button className="px-8 py-3 text-base font-semibold bg-card text-card-foreground hover:bg-muted transition-all shadow-md">
|
||||||
|
Saiba Mais
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-10 md:mt-0 flex justify-center">
|
<div className="mt-10 md:mt-0 flex justify-center">
|
||||||
<img
|
<img
|
||||||
src="https://t4.ftcdn.net/jpg/03/20/52/31/360_F_320523164_tx7Rdd7I2XDTvvKfz2oRuRpKOPE5z0ni.jpg"
|
src="https://t4.ftcdn.net/jpg/03/20/52/31/360_F_320523164_tx7Rdd7I2XDTvvKfz2oRuRpKOPE5z0ni.jpg"
|
||||||
alt="Médico"
|
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>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
{/* Serviços */}
|
||||||
{/* Seção de serviços */}
|
<section
|
||||||
<section className="py-16 px-6 md:px-10 lg:px-20 bg-card">
|
id="departments"
|
||||||
<h2 className="text-center text-2xl sm:text-3xl font-bold text-foreground">
|
className="py-20 px-6 md:px-10 lg:px-20 bg-secondary"
|
||||||
|
>
|
||||||
|
<h2 className="text-center text-3xl sm:text-4xl font-extrabold text-foreground">
|
||||||
Cuidados completos para a sua saúde
|
Cuidados completos para a sua saúde
|
||||||
</h2>
|
</h2>
|
||||||
<p className="text-center text-muted-foreground mt-2 text-sm sm:text-base">
|
<p className="text-center text-muted-foreground mt-3 text-base">
|
||||||
Serviços médicos que oferecemos
|
Serviços médicos que oferecemos
|
||||||
</p>
|
</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="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-10 mt-12 max-w-6xl mx-auto">
|
||||||
<div className="p-6 bg-background rounded-xl shadow hover:shadow-lg transition">
|
{/* Card */}
|
||||||
<h3 className="text-xl font-semibold text-primary">
|
{[
|
||||||
Clínica Geral
|
{
|
||||||
</h3>
|
title: "Clínica Geral",
|
||||||
<p className="text-muted-foreground mt-2 text-sm">
|
desc: "Seu primeiro passo para o cuidado. Atendimento focado na prevenção e no diagnóstico inicial.",
|
||||||
Seu primeiro passo para o cuidado. Atendimento focado na prevenção
|
Icon: Stethoscope,
|
||||||
e no diagnóstico inicial.
|
},
|
||||||
</p>
|
{
|
||||||
<Button className="mt-4 w-full">Agendar</Button>
|
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-card rounded-2xl shadow-md hover:shadow-xl transition-all duration-300 border border-border group"
|
||||||
|
>
|
||||||
|
<div className="flex items-center space-x-3">
|
||||||
|
<Icon className="text-primary w-6 h-6 group-hover:scale-110 transition-transform" />
|
||||||
|
<h3 className="text-xl font-semibold">{title}</h3>
|
||||||
</div>
|
</div>
|
||||||
<div className="p-6 bg-background rounded-xl shadow hover:shadow-lg transition">
|
<p className="text-muted-foreground mt-3 text-sm leading-relaxed">
|
||||||
<h3 className="text-xl font-semibold text-primary">Pediatria</h3>
|
{desc}
|
||||||
<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>
|
</p>
|
||||||
<Button className="mt-4 w-full">Agendar</Button>
|
<Button className="mt-6 w-full bg-primary hover:opacity-90 text-primary-foreground transition">
|
||||||
</div>
|
Agendar
|
||||||
<div className="p-6 bg-background rounded-xl shadow hover:shadow-lg transition">
|
</Button>
|
||||||
<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>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
{/* Footer */}
|
{/* Footer */}
|
||||||
<footer className="bg-primary text-primary-foreground py-6 text-center text-sm">
|
<footer className="bg-primary text-primary-foreground py-8 text-center text-sm border-t-2 border-primary-foreground/20">
|
||||||
<p>© 2025 MediConnect</p>
|
<div className="space-y-2">
|
||||||
|
<p>© 2025 MediConnect — Todos os direitos reservados</p>
|
||||||
|
<div className="flex justify-center space-x-6 opacity-90">
|
||||||
|
<a href="#about" className="hover:opacity-70 transition">
|
||||||
|
Sobre
|
||||||
|
</a>
|
||||||
|
<a href="#departments" className="hover:opacity-70 transition">
|
||||||
|
Serviços
|
||||||
|
</a>
|
||||||
|
<a href="#contact" className="hover:opacity-70 transition">
|
||||||
|
Contato
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,93 +1,83 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
|
import {
|
||||||
|
Card,
|
||||||
|
CardContent,
|
||||||
|
CardDescription,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from "@/components/ui/card";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Calendar, Clock, CalendarDays, X } from "lucide-react";
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import {
|
||||||
|
Calendar,
|
||||||
|
Clock,
|
||||||
|
MapPin,
|
||||||
|
Phone,
|
||||||
|
User,
|
||||||
|
X,
|
||||||
|
AlertCircle,
|
||||||
|
} from "lucide-react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
|
||||||
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
||||||
import { usersService } from "@/services/usersApi.mjs";
|
import { usersService } from "@/services/usersApi.mjs";
|
||||||
|
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||||
import Sidebar from "@/components/Sidebar";
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
// Tipagem correta para o usuário
|
|
||||||
interface UserProfile {
|
|
||||||
id: string;
|
|
||||||
full_name: string;
|
|
||||||
email: string;
|
|
||||||
phone?: string;
|
|
||||||
avatar_url?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface User {
|
|
||||||
user: {
|
|
||||||
id: string;
|
|
||||||
email: string;
|
|
||||||
};
|
|
||||||
profile: UserProfile;
|
|
||||||
roles: string[];
|
|
||||||
permissions?: any;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Appointment {
|
|
||||||
id: string;
|
|
||||||
doctor_id: string;
|
|
||||||
scheduled_at: string;
|
|
||||||
status: string;
|
|
||||||
doctorName?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function PatientAppointmentsPage() {
|
export default function PatientAppointmentsPage() {
|
||||||
const [appointments, setAppointments] = useState<Appointment[]>([]);
|
const [appointments, setAppointments] = useState<any[]>([]);
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
const [userData, setUserData] = useState<User | null>(null);
|
|
||||||
|
|
||||||
// --- Busca o usuário logado ---
|
// Estados para cancelamento
|
||||||
const fetchUser = async () => {
|
const [cancelModal, setCancelModal] = useState(false);
|
||||||
try {
|
const [selectedAppointment, setSelectedAppointment] = useState<any>(null);
|
||||||
const user: User = await usersService.getMe();
|
|
||||||
if (!user.roles.includes("patient") && !user.roles.includes("user")) {
|
|
||||||
toast.error("Apenas pacientes podem visualizar suas consultas.");
|
|
||||||
setIsLoading(false);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
setUserData(user);
|
|
||||||
return user;
|
|
||||||
} catch (err) {
|
|
||||||
console.error("Erro ao buscar usuário logado:", err);
|
|
||||||
toast.error("Não foi possível identificar o usuário logado.");
|
|
||||||
setIsLoading(false);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// --- Busca consultas do paciente ---
|
const fetchData = async () => {
|
||||||
const fetchAppointments = async (patientId: string) => {
|
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
try {
|
try {
|
||||||
const queryParams = `patient_id=eq.${patientId}&order=scheduled_at.desc`;
|
// 1. Obter usuário logado
|
||||||
const appointmentsList: Appointment[] = await appointmentsService.search_appointment(queryParams);
|
const user = await usersService.getMe();
|
||||||
|
if (!user || !user.user?.id) {
|
||||||
// Buscar nome do médico para cada consulta
|
toast.error("Usuário não identificado.");
|
||||||
const appointmentsWithDoctor = await Promise.all(
|
return;
|
||||||
appointmentsList.map(async (apt) => {
|
|
||||||
let doctorName = apt.doctor_id;
|
|
||||||
if (apt.doctor_id) {
|
|
||||||
try {
|
|
||||||
const doctorInfo = await usersService.full_data(apt.doctor_id);
|
|
||||||
doctorName = doctorInfo?.profile?.full_name || apt.doctor_id;
|
|
||||||
} catch (err) {
|
|
||||||
console.error("Erro ao buscar nome do médico:", err);
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
return { ...apt, doctorName };
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
setAppointments(appointmentsWithDoctor);
|
// 2. Buscar médicos e agendamentos em paralelo
|
||||||
} catch (err) {
|
// Filtra apenas agendamentos deste paciente
|
||||||
console.error("Erro ao carregar consultas:", err);
|
const queryParams = `patient_id=eq.${"user.user.id"}&order=scheduled_at.desc`;
|
||||||
|
console.log("id do paciente:", user.profile.id);
|
||||||
|
const [appointmentList, doctorList] = await Promise.all([
|
||||||
|
appointmentsService.search_appointment(queryParams),
|
||||||
|
doctorsService.list(),
|
||||||
|
]);
|
||||||
|
console.log("Agendamentos obtidos:", appointmentList);
|
||||||
|
console.log("Médicos obtidos:", doctorList);
|
||||||
|
// 3. Mapear médicos para acesso rápido
|
||||||
|
const doctorMap = new Map(doctorList.map((d: any) => [d.id, d]));
|
||||||
|
|
||||||
|
// 4. Enriquecer os agendamentos com dados do médico
|
||||||
|
const enrichedAppointments = appointmentList.map((apt: any) => ({
|
||||||
|
...apt,
|
||||||
|
doctor: doctorMap.get(apt.doctor_id) || {
|
||||||
|
full_name: "Médico não encontrado",
|
||||||
|
specialty: "Clínico Geral",
|
||||||
|
location: "Consultório",
|
||||||
|
phone: "N/A"
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
console.log("Agendamentos enriquecidos:", enrichedAppointments);
|
||||||
|
setAppointments(enrichedAppointments);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Erro ao buscar dados:", error);
|
||||||
toast.error("Não foi possível carregar suas consultas.");
|
toast.error("Não foi possível carregar suas consultas.");
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
@ -95,96 +85,187 @@ export default function PatientAppointmentsPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
(async () => {
|
fetchData();
|
||||||
const user = await fetchUser();
|
|
||||||
if (user?.user.id) {
|
|
||||||
await fetchAppointments(user.user.id);
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const getStatusBadge = (status: string) => {
|
// --- LÓGICA DE CANCELAMENTO ---
|
||||||
switch (status) {
|
const handleCancelClick = (appointment: any) => {
|
||||||
case "requested":
|
setSelectedAppointment(appointment);
|
||||||
return <Badge className="bg-yellow-100 text-yellow-800">Solicitada</Badge>;
|
setCancelModal(true);
|
||||||
case "confirmed":
|
};
|
||||||
return <Badge className="bg-blue-100 text-blue-800">Confirmada</Badge>;
|
|
||||||
case "checked_in":
|
const confirmCancel = async () => {
|
||||||
return <Badge className="bg-indigo-100 text-indigo-800">Check-in</Badge>;
|
if (!selectedAppointment) return;
|
||||||
case "completed":
|
try {
|
||||||
return <Badge className="bg-green-100 text-green-800">Realizada</Badge>;
|
// Opção A: Deletar o registro (como no código da secretária)
|
||||||
case "cancelled":
|
await appointmentsService.delete(selectedAppointment.id);
|
||||||
return <Badge className="bg-red-100 text-red-800">Cancelada</Badge>;
|
|
||||||
default:
|
// Opção B: Se preferir apenas mudar o status, descomente abaixo e comente a linha acima:
|
||||||
return <Badge variant="secondary">{status}</Badge>;
|
// await appointmentsService.update(selectedAppointment.id, { status: 'cancelled' });
|
||||||
|
|
||||||
|
setAppointments((prev) =>
|
||||||
|
prev.filter((apt) => apt.id !== selectedAppointment.id)
|
||||||
|
);
|
||||||
|
setCancelModal(false);
|
||||||
|
toast.success("Consulta cancelada com sucesso.");
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Erro ao cancelar consulta:", error);
|
||||||
|
toast.error("Não foi possível cancelar a consulta.");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleReschedule = (apt: Appointment) => {
|
|
||||||
toast.info(`Funcionalidade de reagendamento da consulta ${apt.id} ainda não implementada`);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCancel = (apt: Appointment) => {
|
|
||||||
toast.info(`Funcionalidade de cancelamento da consulta ${apt.id} ainda não implementada`);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Sidebar>
|
<Sidebar>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="flex justify-between items-center">
|
<div className="flex justify-between items-center">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-bold text-foreground">Minhas Consultas</h1>
|
<h1 className="text-3xl font-bold">Minhas Consultas</h1>
|
||||||
<p className="text-muted-foreground">Veja, reagende ou cancele suas consultas</p>
|
<p className="text-muted-foreground">
|
||||||
|
Acompanhe seu histórico e próximos agendamentos
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid gap-6">
|
<div className="grid gap-6">
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<p>Carregando consultas...</p>
|
<p>Carregando consultas...</p>
|
||||||
) : appointments.length === 0 ? (
|
) : appointments.length > 0 ? (
|
||||||
<p className="text-gray-600">Você ainda não possui consultas agendadas.</p>
|
appointments.map((appointment) => (
|
||||||
) : (
|
<Card key={appointment.id}>
|
||||||
appointments.map((apt) => (
|
<CardHeader>
|
||||||
<Card key={apt.id}>
|
<div className="flex justify-between items-start">
|
||||||
<CardHeader className="flex justify-between items-start">
|
|
||||||
<div>
|
<div>
|
||||||
<CardTitle className="text-lg">{apt.doctorName}</CardTitle>
|
<CardTitle className="text-lg">
|
||||||
<CardDescription>Especialidade: N/A</CardDescription>
|
{appointment.doctor.full_name}
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
{appointment.doctor.specialty}
|
||||||
|
</CardDescription>
|
||||||
|
</div>
|
||||||
|
{getStatusBadge(appointment.status)}
|
||||||
</div>
|
</div>
|
||||||
{getStatusBadge(apt.status)}
|
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="grid md:grid-cols-2 gap-3 text-sm text-gray-700">
|
<CardContent>
|
||||||
<div className="space-y-2">
|
<div className="grid md:grid-cols-2 gap-4">
|
||||||
<div className="flex items-center">
|
{/* Coluna 1: Data e Hora */}
|
||||||
<Calendar className="mr-2 h-4 w-4 text-gray-500" />
|
<div className="space-y-3">
|
||||||
{new Date(apt.scheduled_at).toLocaleDateString("pt-BR")}
|
<div className="flex items-center text-sm text-foreground font-medium">
|
||||||
|
<User className="mr-2 h-4 w-4 text-muted-foreground" />
|
||||||
|
Dr(a). {appointment.doctor.full_name.split(' ')[0]}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center">
|
<div className="flex items-center text-sm text-muted-foreground">
|
||||||
<Clock className="mr-2 h-4 w-4 text-gray-500" />
|
<Calendar className="mr-2 h-4 w-4" />
|
||||||
{new Date(apt.scheduled_at).toLocaleTimeString("pt-BR", {
|
{new Date(appointment.scheduled_at).toLocaleDateString(
|
||||||
hour: "2-digit",
|
"pt-BR",
|
||||||
minute: "2-digit",
|
{ timeZone: "UTC" }
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="flex gap-2 mt-4 pt-4 border-t">
|
|
||||||
{apt.status !== "cancelled" && (
|
|
||||||
<>
|
|
||||||
<Button variant="outline" size="sm" onClick={() => handleReschedule(apt)}>
|
|
||||||
<CalendarDays className="mr-2 h-4 w-4" /> Reagendar
|
|
||||||
</Button>
|
|
||||||
<Button variant="destructive" size="sm" onClick={() => handleCancel(apt)}>
|
|
||||||
<X className="mr-2 h-4 w-4" /> Cancelar
|
|
||||||
</Button>
|
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
<div className="flex items-center text-sm text-muted-foreground">
|
||||||
|
<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>
|
||||||
|
|
||||||
|
{/* Coluna 2: Localização e Contato */}
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="flex items-center text-sm text-muted-foreground">
|
||||||
|
<MapPin className="mr-2 h-4 w-4" />
|
||||||
|
{appointment.doctor.location || "Local a definir"}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center text-sm text-muted-foreground">
|
||||||
|
<Phone className="mr-2 h-4 w-4" />
|
||||||
|
{appointment.doctor.phone || "Contato não disponível"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Ações */}
|
||||||
|
{["requested", "confirmed"].includes(appointment.status) && (
|
||||||
|
<div className="flex gap-2 mt-4 pt-4 border-t justify-end">
|
||||||
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
size="sm"
|
||||||
|
className="bg-transparent text-destructive hover:bg-destructive/10 border border-destructive/20"
|
||||||
|
onClick={() => handleCancelClick(appointment)}
|
||||||
|
>
|
||||||
|
<X className="mr-2 h-4 w-4" />
|
||||||
|
Cancelar Consulta
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
))
|
))
|
||||||
|
) : (
|
||||||
|
<div className="text-center py-10 border rounded-lg bg-muted/20">
|
||||||
|
<Calendar className="mx-auto h-10 w-10 text-muted-foreground mb-4" />
|
||||||
|
<p className="text-muted-foreground">Você ainda não possui consultas agendadas.</p>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Modal de Confirmação de Cancelamento */}
|
||||||
|
<Dialog open={cancelModal} onOpenChange={setCancelModal}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="flex items-center gap-2">
|
||||||
|
<AlertCircle className="h-5 w-5 text-destructive" />
|
||||||
|
Cancelar Consulta
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Tem certeza que deseja cancelar sua consulta com{" "}
|
||||||
|
<strong>{selectedAppointment?.doctor?.full_name}</strong> no dia{" "}
|
||||||
|
{selectedAppointment &&
|
||||||
|
new Date(selectedAppointment.scheduled_at).toLocaleDateString(
|
||||||
|
"pt-BR", { timeZone: "UTC" }
|
||||||
|
)}
|
||||||
|
? Esta ação não pode ser desfeita.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={() => setCancelModal(false)}>
|
||||||
|
Voltar
|
||||||
|
</Button>
|
||||||
|
<Button variant="destructive" onClick={confirmCancel}>
|
||||||
|
Confirmar Cancelamento
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
</Sidebar>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Helper para Badges (Mantido consistente com o código da secretária)
|
||||||
|
const getStatusBadge = (status: string) => {
|
||||||
|
switch (status) {
|
||||||
|
case "requested":
|
||||||
|
return (
|
||||||
|
<Badge className="bg-yellow-400/10 text-yellow-600 hover:bg-yellow-400/20 border-yellow-400/20">Solicitada</Badge>
|
||||||
|
);
|
||||||
|
case "confirmed":
|
||||||
|
return <Badge className="bg-primary/10 text-primary hover:bg-primary/20 border-primary/20">Confirmada</Badge>;
|
||||||
|
case "checked_in":
|
||||||
|
return (
|
||||||
|
<Badge className="bg-indigo-400/10 text-indigo-600 hover:bg-indigo-400/20 border-indigo-400/20">Check-in</Badge>
|
||||||
|
);
|
||||||
|
case "completed":
|
||||||
|
return <Badge className="bg-green-400/10 text-green-600 hover:bg-green-400/20 border-green-400/20">Realizada</Badge>;
|
||||||
|
case "cancelled":
|
||||||
|
return <Badge className="bg-destructive/10 text-destructive hover:bg-destructive/20 border-destructive/20">Cancelada</Badge>;
|
||||||
|
case "no_show":
|
||||||
|
return (
|
||||||
|
<Badge className="bg-muted text-foreground border-muted-foreground/20">Não Compareceu</Badge>
|
||||||
|
);
|
||||||
|
default:
|
||||||
|
return <Badge variant="secondary">{status}</Badge>;
|
||||||
|
}
|
||||||
|
};
|
||||||
@ -1,22 +1,32 @@
|
|||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
import {
|
||||||
import { Button } from "@/components/ui/button"
|
Card,
|
||||||
import { Calendar, Clock, User, Plus } from "lucide-react"
|
CardContent,
|
||||||
import Link from "next/link"
|
CardDescription,
|
||||||
import Sidebar from "@/components/Sidebar"
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from "@/components/ui/card";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Calendar, Clock, User, Plus } from "lucide-react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
|
||||||
export default function PatientDashboard() {
|
export default function PatientDashboard() {
|
||||||
return (
|
return (
|
||||||
<Sidebar>
|
<Sidebar>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
|
<h1 className="text-3xl font-bold text-foreground">Dashboard</h1>
|
||||||
<p className="text-gray-600">Bem-vindo ao seu portal de consultas médicas</p>
|
<p className="text-muted-foreground">
|
||||||
|
Bem-vindo ao seu portal de consultas médicas
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||||
<CardTitle className="text-sm font-medium">Próxima Consulta</CardTitle>
|
<CardTitle className="text-sm font-medium">
|
||||||
|
Próxima Consulta
|
||||||
|
</CardTitle>
|
||||||
<Calendar className="h-4 w-4 text-muted-foreground" />
|
<Calendar className="h-4 w-4 text-muted-foreground" />
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
@ -27,12 +37,16 @@ export default function PatientDashboard() {
|
|||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||||
<CardTitle className="text-sm font-medium">Consultas Este Mês</CardTitle>
|
<CardTitle className="text-sm font-medium">
|
||||||
|
Consultas Este Mês
|
||||||
|
</CardTitle>
|
||||||
<Clock className="h-4 w-4 text-muted-foreground" />
|
<Clock className="h-4 w-4 text-muted-foreground" />
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div className="text-2xl font-bold">3</div>
|
<div className="text-2xl font-bold">3</div>
|
||||||
<p className="text-xs text-muted-foreground">2 realizadas, 1 agendada</p>
|
<p className="text-xs text-muted-foreground">
|
||||||
|
2 realizadas, 1 agendada
|
||||||
|
</p>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
@ -52,23 +66,31 @@ export default function PatientDashboard() {
|
|||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Ações Rápidas</CardTitle>
|
<CardTitle>Ações Rápidas</CardTitle>
|
||||||
<CardDescription>Acesse rapidamente as principais funcionalidades</CardDescription>
|
<CardDescription>
|
||||||
|
Acesse rapidamente as principais funcionalidades
|
||||||
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-4">
|
<CardContent className="space-y-4">
|
||||||
<Link href="/patient/schedule">
|
<Link href="/patient/schedule">
|
||||||
<Button className="w-full justify-start">
|
<Button className="w-full justify-start">
|
||||||
<Plus className="mr-2 h-4 w-4" />
|
<User className="mr-2 h-4 w-4" />
|
||||||
Agendar Nova Consulta
|
Agendar Nova Consulta
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
<Link href="/patient/appointments">
|
<Link href="/patient/appointments">
|
||||||
<Button variant="outline" className="w-full justify-start bg-transparent">
|
<Button
|
||||||
|
variant="secondary"
|
||||||
|
className="w-full justify-start"
|
||||||
|
>
|
||||||
<Calendar className="mr-2 h-4 w-4" />
|
<Calendar className="mr-2 h-4 w-4" />
|
||||||
Ver Minhas Consultas
|
Ver Minhas Consultas
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
<Link href="/patient/profile">
|
<Link href="/patient/profile">
|
||||||
<Button variant="outline" className="w-full justify-start bg-transparent">
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="w-full justify-start"
|
||||||
|
>
|
||||||
<User className="mr-2 h-4 w-4" />
|
<User className="mr-2 h-4 w-4" />
|
||||||
Atualizar Dados
|
Atualizar Dados
|
||||||
</Button>
|
</Button>
|
||||||
@ -83,24 +105,24 @@ export default function PatientDashboard() {
|
|||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div className="flex items-center justify-between p-3 bg-blue-50 rounded-lg">
|
<div className="flex items-center justify-between p-3 bg-muted rounded-lg">
|
||||||
<div>
|
<div>
|
||||||
<p className="font-medium">Dr. Silva</p>
|
<p className="font-medium">Dr. Silva</p>
|
||||||
<p className="text-sm text-gray-600">Cardiologia</p>
|
<p className="text-sm text-muted-foreground">Cardiologia</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-right">
|
<div className="text-right">
|
||||||
<p className="font-medium">15 Jan</p>
|
<p className="font-medium">15 Jan</p>
|
||||||
<p className="text-sm text-gray-600">14:30</p>
|
<p className="text-sm text-muted-foreground">14:30</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center justify-between p-3 bg-green-50 rounded-lg">
|
<div className="flex items-center justify-between p-3 bg-muted rounded-lg">
|
||||||
<div>
|
<div>
|
||||||
<p className="font-medium">Dra. Santos</p>
|
<p className="font-medium">Dra. Santos</p>
|
||||||
<p className="text-sm text-gray-600">Dermatologia</p>
|
<p className="text-sm text-muted-foreground">Dermatologia</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-right">
|
<div className="text-right">
|
||||||
<p className="font-medium">22 Jan</p>
|
<p className="font-medium">22 Jan</p>
|
||||||
<p className="text-sm text-gray-600">10:00</p>
|
<p className="text-sm text-muted-foreground">10:00</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -109,5 +131,5 @@ export default function PatientDashboard() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</Sidebar>
|
</Sidebar>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,18 +1,17 @@
|
|||||||
// ARQUIVO COMPLETO PARA: app/patient/profile/page.tsx
|
// Caminho: app/patient/profile/page.tsx
|
||||||
|
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, useEffect, useRef } from "react";
|
import { useState, useEffect, useRef } from "react";
|
||||||
import Sidebar from "@/components/Sidebar";
|
import Sidebar from "@/components/Sidebar";
|
||||||
import { useAuthLayout } from "@/hooks/useAuthLayout";
|
import { useAuthLayout } from "@/hooks/useAuthLayout";
|
||||||
import { patientsService } from "@/services/patientsApi.mjs";
|
import { patientsService } from "@/services/patientsApi.mjs";
|
||||||
|
import { usersService } from "@/services/usersApi.mjs"; // Adicionado import
|
||||||
import { api } from "@/services/api.mjs";
|
import { api } from "@/services/api.mjs";
|
||||||
|
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import { Textarea } from "@/components/ui/textarea";
|
|
||||||
import { User, Mail, Phone, Calendar, Upload } from "lucide-react";
|
import { User, Mail, Phone, Calendar, Upload } from "lucide-react";
|
||||||
import { toast } from "@/hooks/use-toast";
|
import { toast } from "@/hooks/use-toast";
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||||
@ -31,17 +30,48 @@ interface PatientProfileData {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function PatientProfile() {
|
export default function PatientProfile() {
|
||||||
const { user, isLoading: isAuthLoading } = useAuthLayout({ requiredRole: ["paciente", "admin", "medico", "gestor", "secretaria"] });
|
const { user, isLoading: isAuthLoading } = useAuthLayout({
|
||||||
|
requiredRole: ["paciente", "admin", "medico", "gestor", "secretaria"],
|
||||||
|
});
|
||||||
|
|
||||||
const [patientData, setPatientData] = useState<PatientProfileData | null>(null);
|
const [patientData, setPatientData] = useState<PatientProfileData | null>(null);
|
||||||
const [isEditing, setIsEditing] = useState(false);
|
const [isEditing, setIsEditing] = useState(false);
|
||||||
const [isSaving, setIsSaving] = useState(false);
|
const [isSaving, setIsSaving] = useState(false);
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
const getInitials = (name: string) => {
|
||||||
|
if (!name) return "U";
|
||||||
|
return name
|
||||||
|
.split(" ")
|
||||||
|
.map((n) => n[0])
|
||||||
|
.slice(0, 2)
|
||||||
|
.join("")
|
||||||
|
.toUpperCase();
|
||||||
|
};
|
||||||
|
|
||||||
|
// Função auxiliar para construir URL do avatar
|
||||||
|
const buildAvatarUrl = (path: string | null | undefined) => {
|
||||||
|
if (!path) return undefined;
|
||||||
|
const baseUrl = "https://yuanqfswhberkoevtmfr.supabase.co";
|
||||||
|
const cleanPath = path.startsWith('/') ? path.slice(1) : path;
|
||||||
|
const separator = cleanPath.includes('?') ? '&' : '?';
|
||||||
|
return `${baseUrl}/storage/v1/object/avatars/${cleanPath}${separator}t=${new Date().getTime()}`;
|
||||||
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (user?.id) {
|
if (user?.id) {
|
||||||
const fetchPatientDetails = async () => {
|
const loadData = async () => {
|
||||||
try {
|
try {
|
||||||
|
// 1. Busca dados médicos (Tabela Patients)
|
||||||
const patientDetails = await patientsService.getById(user.id);
|
const patientDetails = await patientsService.getById(user.id);
|
||||||
|
|
||||||
|
// 2. Busca dados de sistema frescos (Tabela Profiles via getMe)
|
||||||
|
// Isso garante que pegamos o avatar real do banco, não do cache local
|
||||||
|
const userSystemData = await usersService.getMe();
|
||||||
|
|
||||||
|
const freshAvatarPath = userSystemData?.profile?.avatar_url;
|
||||||
|
const freshAvatarUrl = buildAvatarUrl(freshAvatarPath);
|
||||||
|
|
||||||
setPatientData({
|
setPatientData({
|
||||||
name: patientDetails.full_name || user.name,
|
name: patientDetails.full_name || user.name,
|
||||||
email: user.email,
|
email: user.email,
|
||||||
@ -52,21 +82,49 @@ export default function PatientProfile() {
|
|||||||
street: patientDetails.street || "",
|
street: patientDetails.street || "",
|
||||||
number: patientDetails.number || "",
|
number: patientDetails.number || "",
|
||||||
city: patientDetails.city || "",
|
city: patientDetails.city || "",
|
||||||
avatarFullUrl: user.avatarFullUrl,
|
avatarFullUrl: freshAvatarUrl, // Usa a URL fresca do banco
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Erro ao buscar detalhes do paciente:", error);
|
console.error("Erro ao buscar detalhes:", error);
|
||||||
toast({ title: "Erro", description: "Não foi possível carregar seus dados completos.", variant: "destructive" });
|
toast({
|
||||||
|
title: "Erro",
|
||||||
|
description: "Não foi possível carregar seus dados completos.",
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
fetchPatientDetails();
|
loadData();
|
||||||
}
|
}
|
||||||
}, [user]);
|
}, [user?.id, user?.email, user?.name]); // Removi user.avatarFullUrl para não depender do cache
|
||||||
|
|
||||||
const handleInputChange = (field: keyof PatientProfileData, value: string) => {
|
const handleInputChange = (
|
||||||
|
field: keyof PatientProfileData,
|
||||||
|
value: string
|
||||||
|
) => {
|
||||||
setPatientData((prev) => (prev ? { ...prev, [field]: value } : null));
|
setPatientData((prev) => (prev ? { ...prev, [field]: value } : null));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const updateLocalSession = (updates: { full_name?: string; avatar_url?: string }) => {
|
||||||
|
try {
|
||||||
|
const storedUserString = localStorage.getItem("user_info");
|
||||||
|
if (storedUserString) {
|
||||||
|
const storedUser = JSON.parse(storedUserString);
|
||||||
|
|
||||||
|
if (!storedUser.user_metadata) storedUser.user_metadata = {};
|
||||||
|
if (updates.full_name) storedUser.user_metadata.full_name = updates.full_name;
|
||||||
|
if (updates.avatar_url) storedUser.user_metadata.avatar_url = updates.avatar_url;
|
||||||
|
|
||||||
|
if (!storedUser.profile) storedUser.profile = {};
|
||||||
|
if (updates.full_name) storedUser.profile.full_name = updates.full_name;
|
||||||
|
if (updates.avatar_url) storedUser.profile.avatar_url = updates.avatar_url;
|
||||||
|
|
||||||
|
localStorage.setItem("user_info", JSON.stringify(storedUser));
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Erro ao atualizar sessão local:", e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const handleSave = async () => {
|
const handleSave = async () => {
|
||||||
if (!patientData || !user) return;
|
if (!patientData || !user) return;
|
||||||
setIsSaving(true);
|
setIsSaving(true);
|
||||||
@ -81,12 +139,29 @@ export default function PatientProfile() {
|
|||||||
number: patientData.number,
|
number: patientData.number,
|
||||||
city: patientData.city,
|
city: patientData.city,
|
||||||
};
|
};
|
||||||
|
|
||||||
await patientsService.update(user.id, patientPayload);
|
await patientsService.update(user.id, patientPayload);
|
||||||
toast({ title: "Sucesso!", description: "Seus dados foram atualizados." });
|
await api.patch(`/rest/v1/profiles?id=eq.${user.id}`, {
|
||||||
|
full_name: patientData.name,
|
||||||
|
});
|
||||||
|
|
||||||
|
updateLocalSession({ full_name: patientData.name });
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: "Sucesso!",
|
||||||
|
description: "Seus dados foram atualizados. A página será recarregada.",
|
||||||
|
});
|
||||||
|
|
||||||
setIsEditing(false);
|
setIsEditing(false);
|
||||||
|
setTimeout(() => window.location.reload(), 1000);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Erro ao salvar dados:", error);
|
console.error("Erro ao salvar dados:", error);
|
||||||
toast({ title: "Erro", description: "Não foi possível salvar suas alterações.", variant: "destructive" });
|
toast({
|
||||||
|
title: "Erro",
|
||||||
|
description: "Não foi possível salvar suas alterações.",
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
} finally {
|
} finally {
|
||||||
setIsSaving(false);
|
setIsSaving(false);
|
||||||
}
|
}
|
||||||
@ -96,34 +171,52 @@ export default function PatientProfile() {
|
|||||||
fileInputRef.current?.click();
|
fileInputRef.current?.click();
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleAvatarUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
|
const handleAvatarUpload = async (
|
||||||
|
event: React.ChangeEvent<HTMLInputElement>
|
||||||
|
) => {
|
||||||
const file = event.target.files?.[0];
|
const file = event.target.files?.[0];
|
||||||
if (!file || !user) return;
|
if (!file || !user) return;
|
||||||
|
|
||||||
const fileExt = file.name.split(".").pop();
|
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}`;
|
const filePath = `${user.id}/avatar.${fileExt}`;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await api.storage.upload("avatars", filePath, file);
|
await api.storage.upload("avatars", filePath, file);
|
||||||
await api.patch(`/rest/v1/profiles?id=eq.${user.id}`, { avatar_url: filePath });
|
await api.patch(`/rest/v1/profiles?id=eq.${user.id}`, {
|
||||||
|
avatar_url: filePath,
|
||||||
|
});
|
||||||
|
|
||||||
const newFullUrl = `https://yuanqfswhberkoevtmfr.supabase.co/storage/v1/object/public/avatars/${filePath}?t=${new Date().getTime()}`;
|
const newFullUrl = buildAvatarUrl(filePath);
|
||||||
setPatientData((prev) => (prev ? { ...prev, avatarFullUrl: newFullUrl } : null));
|
|
||||||
|
setPatientData((prev) =>
|
||||||
|
prev ? { ...prev, avatarFullUrl: newFullUrl } : null
|
||||||
|
);
|
||||||
|
|
||||||
|
updateLocalSession({ avatar_url: filePath });
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: "Sucesso!",
|
||||||
|
description: "Sua foto de perfil foi atualizada.",
|
||||||
|
});
|
||||||
|
|
||||||
|
setTimeout(() => window.location.reload(), 1000);
|
||||||
|
|
||||||
toast({ title: "Sucesso!", description: "Sua foto de perfil foi atualizada." });
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Erro no upload do avatar:", error);
|
console.error("Erro no upload do avatar:", error);
|
||||||
toast({ title: "Erro de Upload", description: "Não foi possível enviar sua foto.", variant: "destructive" });
|
toast({
|
||||||
|
title: "Erro de Upload",
|
||||||
|
description: "Não foi possível enviar sua foto.",
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (isAuthLoading || !patientData) {
|
if (isAuthLoading || !patientData) {
|
||||||
return (
|
return (
|
||||||
<Sidebar>
|
<Sidebar>
|
||||||
<div>Carregando seus dados...</div>
|
<div className="flex items-center justify-center h-full">
|
||||||
|
<p className="text-muted-foreground">Carregando seus dados...</p>
|
||||||
|
</div>
|
||||||
</Sidebar>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -133,11 +226,19 @@ export default function PatientProfile() {
|
|||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="flex justify-between items-center">
|
<div className="flex justify-between items-center">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-bold text-gray-900">Meus Dados</h1>
|
<h1 className="text-3xl font-bold text-foreground">Meus Dados</h1>
|
||||||
<p className="text-gray-600">Gerencie suas informações pessoais</p>
|
<p className="text-muted-foreground">Gerencie suas informações pessoais</p>
|
||||||
</div>
|
</div>
|
||||||
<Button onClick={() => (isEditing ? handleSave() : setIsEditing(true))} disabled={isSaving}>
|
<Button
|
||||||
{isEditing ? (isSaving ? "Salvando..." : "Salvar Alterações") : "Editar Dados"}
|
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>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@ -154,16 +255,36 @@ export default function PatientProfile() {
|
|||||||
<div className="grid md:grid-cols-2 gap-4">
|
<div className="grid md:grid-cols-2 gap-4">
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="name">Nome Completo</Label>
|
<Label htmlFor="name">Nome Completo</Label>
|
||||||
<Input id="name" value={patientData.name} onChange={(e) => handleInputChange("name", e.target.value)} disabled={!isEditing} />
|
<Input
|
||||||
|
id="name"
|
||||||
|
value={patientData.name}
|
||||||
|
onChange={(e) =>
|
||||||
|
handleInputChange("name", e.target.value)
|
||||||
|
}
|
||||||
|
disabled={!isEditing}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="cpf">CPF</Label>
|
<Label htmlFor="cpf">CPF</Label>
|
||||||
<Input id="cpf" value={patientData.cpf} onChange={(e) => handleInputChange("cpf", e.target.value)} disabled={!isEditing} />
|
<Input
|
||||||
|
id="cpf"
|
||||||
|
value={patientData.cpf}
|
||||||
|
onChange={(e) => handleInputChange("cpf", e.target.value)}
|
||||||
|
disabled={!isEditing}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="birthDate">Data de Nascimento</Label>
|
<Label htmlFor="birthDate">Data de Nascimento</Label>
|
||||||
<Input id="birthDate" type="date" value={patientData.birthDate} onChange={(e) => handleInputChange("birthDate", e.target.value)} disabled={!isEditing} />
|
<Input
|
||||||
|
id="birthDate"
|
||||||
|
type="date"
|
||||||
|
value={patientData.birthDate}
|
||||||
|
onChange={(e) =>
|
||||||
|
handleInputChange("birthDate", e.target.value)
|
||||||
|
}
|
||||||
|
disabled={!isEditing}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
@ -178,31 +299,69 @@ export default function PatientProfile() {
|
|||||||
<div className="grid md:grid-cols-2 gap-4">
|
<div className="grid md:grid-cols-2 gap-4">
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="email">Email</Label>
|
<Label htmlFor="email">Email</Label>
|
||||||
<Input id="email" type="email" value={patientData.email} disabled />
|
<Input
|
||||||
|
id="email"
|
||||||
|
type="email"
|
||||||
|
value={patientData.email}
|
||||||
|
disabled
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="phone">Telefone</Label>
|
<Label htmlFor="phone">Telefone</Label>
|
||||||
<Input id="phone" value={patientData.phone} onChange={(e) => handleInputChange("phone", e.target.value)} disabled={!isEditing} />
|
<Input
|
||||||
|
id="phone"
|
||||||
|
value={patientData.phone}
|
||||||
|
onChange={(e) =>
|
||||||
|
handleInputChange("phone", e.target.value)
|
||||||
|
}
|
||||||
|
disabled={!isEditing}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="grid md:grid-cols-3 gap-4">
|
<div className="grid md:grid-cols-3 gap-4">
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="cep">CEP</Label>
|
<Label htmlFor="cep">CEP</Label>
|
||||||
<Input id="cep" value={patientData.cep} onChange={(e) => handleInputChange("cep", e.target.value)} disabled={!isEditing} />
|
<Input
|
||||||
|
id="cep"
|
||||||
|
value={patientData.cep}
|
||||||
|
onChange={(e) => handleInputChange("cep", e.target.value)}
|
||||||
|
disabled={!isEditing}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="md:col-span-2">
|
<div className="md:col-span-2">
|
||||||
<Label htmlFor="street">Rua / Logradouro</Label>
|
<Label htmlFor="street">Rua / Logradouro</Label>
|
||||||
<Input id="street" value={patientData.street} onChange={(e) => handleInputChange("street", e.target.value)} disabled={!isEditing} />
|
<Input
|
||||||
|
id="street"
|
||||||
|
value={patientData.street}
|
||||||
|
onChange={(e) =>
|
||||||
|
handleInputChange("street", e.target.value)
|
||||||
|
}
|
||||||
|
disabled={!isEditing}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
<div className="grid md:grid-cols-2 gap-4">
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="number">Número</Label>
|
<Label htmlFor="number">Número</Label>
|
||||||
<Input id="number" value={patientData.number} onChange={(e) => handleInputChange("number", e.target.value)} disabled={!isEditing} />
|
<Input
|
||||||
|
id="number"
|
||||||
|
value={patientData.number}
|
||||||
|
onChange={(e) =>
|
||||||
|
handleInputChange("number", e.target.value)
|
||||||
|
}
|
||||||
|
disabled={!isEditing}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="city">Cidade</Label>
|
<Label htmlFor="city">Cidade</Label>
|
||||||
<Input id="city" value={patientData.city} onChange={(e) => handleInputChange("city", e.target.value)} disabled={!isEditing} />
|
<Input
|
||||||
|
id="city"
|
||||||
|
value={patientData.city}
|
||||||
|
onChange={(e) =>
|
||||||
|
handleInputChange("city", e.target.value)
|
||||||
|
}
|
||||||
|
disabled={!isEditing}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
@ -216,38 +375,55 @@ export default function PatientProfile() {
|
|||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-4">
|
<CardContent className="space-y-4">
|
||||||
<div className="flex items-center space-x-3">
|
<div className="flex items-center space-x-3">
|
||||||
<div className="relative">
|
<div className="relative group">
|
||||||
<Avatar className="w-16 h-16 cursor-pointer" onClick={handleAvatarClick}>
|
<Avatar
|
||||||
<AvatarImage src={patientData.avatarFullUrl} />
|
className="w-16 h-16 cursor-pointer border-2 border-transparent group-hover:border-blue-500 transition-all"
|
||||||
<AvatarFallback className="text-2xl">
|
onClick={handleAvatarClick}
|
||||||
{patientData.name
|
>
|
||||||
.split(" ")
|
<AvatarImage src={patientData.avatarFullUrl} className="object-cover" />
|
||||||
.map((n) => n[0])
|
<AvatarFallback className="text-2xl bg-gray-200 text-gray-700 font-bold">
|
||||||
.join("")}
|
{getInitials(patientData.name)}
|
||||||
</AvatarFallback>
|
</AvatarFallback>
|
||||||
</Avatar>
|
</Avatar>
|
||||||
<div className="absolute bottom-0 right-0 bg-primary text-primary-foreground rounded-full p-1 cursor-pointer hover:bg-primary/80" onClick={handleAvatarClick}>
|
<div
|
||||||
|
className="absolute bottom-0 right-0 bg-blue-600 text-white rounded-full p-1.5 cursor-pointer hover:bg-blue-700 shadow-md transition-colors"
|
||||||
|
onClick={handleAvatarClick}
|
||||||
|
title="Alterar foto"
|
||||||
|
>
|
||||||
<Upload className="w-3 h-3" />
|
<Upload className="w-3 h-3" />
|
||||||
</div>
|
</div>
|
||||||
<input type="file" ref={fileInputRef} onChange={handleAvatarUpload} className="hidden" accept="image/png, image/jpeg" />
|
<input
|
||||||
|
type="file"
|
||||||
|
ref={fileInputRef}
|
||||||
|
onChange={handleAvatarUpload}
|
||||||
|
className="hidden"
|
||||||
|
accept="image/png, image/jpeg, image/jpg"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-medium">{patientData.name}</p>
|
<p className="font-medium text-lg">{patientData.name}</p>
|
||||||
<p className="text-sm text-gray-500">Paciente</p>
|
<p className="text-sm text-gray-500">Paciente</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-3 pt-4 border-t">
|
<div className="space-y-3 pt-4 border-t">
|
||||||
<div className="flex items-center text-sm">
|
<div className="flex items-center text-sm">
|
||||||
<Mail className="mr-2 h-4 w-4 text-gray-500" />
|
<Mail className="mr-2 h-4 w-4 text-muted-foreground" />
|
||||||
<span className="truncate">{patientData.email}</span>
|
<span className="truncate">{patientData.email}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center text-sm">
|
<div className="flex items-center text-sm">
|
||||||
<Phone className="mr-2 h-4 w-4 text-gray-500" />
|
<Phone className="mr-2 h-4 w-4 text-muted-foreground" />
|
||||||
<span>{patientData.phone || "Não informado"}</span>
|
<span>{patientData.phone || "Não informado"}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center text-sm">
|
<div className="flex items-center text-sm">
|
||||||
<Calendar className="mr-2 h-4 w-4 text-gray-500" />
|
<Calendar className="mr-2 h-4 w-4 text-muted-foreground" />
|
||||||
<span>{patientData.birthDate ? new Date(patientData.birthDate).toLocaleDateString("pt-BR", { timeZone: "UTC" }) : "Não informado"}</span>
|
<span>
|
||||||
|
{patientData.birthDate
|
||||||
|
? new Date(patientData.birthDate).toLocaleDateString(
|
||||||
|
"pt-BR",
|
||||||
|
{ timeZone: "UTC" }
|
||||||
|
)
|
||||||
|
: "Não informado"}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
|
|||||||
@ -1,7 +1,6 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import type React from "react"
|
import type React from "react"
|
||||||
|
|
||||||
import { useState } from "react"
|
import { useState } from "react"
|
||||||
import { useRouter } from "next/navigation"
|
import { useRouter } from "next/navigation"
|
||||||
import Link from "next/link"
|
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 { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||||
import { Input } from "@/components/ui/input"
|
import { Input } from "@/components/ui/input"
|
||||||
import { Label } from "@/components/ui/label"
|
import { Label } from "@/components/ui/label"
|
||||||
import { Textarea } from "@/components/ui/textarea"
|
import { ArrowLeft, Loader2 } from "lucide-react"
|
||||||
import { Eye, EyeOff, ArrowLeft } 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() {
|
export default function PatientRegister() {
|
||||||
const [showPassword, setShowPassword] = useState(false)
|
// REMOVIDO: Estados para 'showPassword' e 'showConfirmPassword'
|
||||||
const [showConfirmPassword, setShowConfirmPassword] = useState(false)
|
|
||||||
const [formData, setFormData] = useState({
|
const [formData, setFormData] = useState({
|
||||||
name: "",
|
name: "",
|
||||||
email: "",
|
email: "",
|
||||||
password: "",
|
|
||||||
confirmPassword: "",
|
|
||||||
phone: "",
|
phone: "",
|
||||||
cpf: "",
|
cpf: "",
|
||||||
birthDate: "",
|
birthDate: "",
|
||||||
address: "",
|
// REMOVIDO: Campos 'password' e 'confirmPassword'
|
||||||
})
|
})
|
||||||
const [isLoading, setIsLoading] = useState(false)
|
const [isLoading, setIsLoading] = useState(false)
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
const { toast } = useToast()
|
||||||
|
|
||||||
const handleInputChange = (field: string, value: string) => {
|
const handleInputChange = (field: string, value: string) => {
|
||||||
setFormData((prev) => ({
|
setFormData((prev) => ({
|
||||||
@ -37,166 +36,144 @@ export default function PatientRegister() {
|
|||||||
|
|
||||||
const handleRegister = async (e: React.FormEvent) => {
|
const handleRegister = async (e: React.FormEvent) => {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
|
setIsLoading(true)
|
||||||
|
|
||||||
if (formData.password !== formData.confirmPassword) {
|
// --- VALIDAÇÃO DE CPF ---
|
||||||
alert("As senhas não coincidem!")
|
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
|
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
|
// ALTERADO: Chamada para a nova função de serviço
|
||||||
setTimeout(() => {
|
await usersService.registerPatient(payload)
|
||||||
// Salvar dados do usuário no localStorage para simulação
|
|
||||||
const { confirmPassword, ...userData } = formData
|
// ALTERADO: Mensagem de sucesso para refletir o fluxo de confirmação por e-mail
|
||||||
localStorage.setItem("patientData", JSON.stringify(userData))
|
toast({
|
||||||
router.push("/patient/dashboard")
|
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)
|
setIsLoading(false)
|
||||||
}, 1000)
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 py-8 px-4">
|
<div className="min-h-screen bg-background py-8 px-4">
|
||||||
<div className="max-w-2xl mx-auto">
|
<div className="max-w-2xl mx-auto">
|
||||||
<div className="mb-6">
|
<div className="mb-6">
|
||||||
<Link href="/" className="inline-flex items-center text-blue-600 hover:text-blue-800">
|
<Link href="/" className="inline-flex items-center text-primary hover:text-primary/90">
|
||||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||||
Voltar ao início
|
Voltar ao início
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader className="text-center">
|
<CardHeader className="text-center">
|
||||||
<CardTitle className="text-2xl">Cadastro de Paciente</CardTitle>
|
<CardTitle className="text-2xl text-foreground">Crie sua Conta de Paciente</CardTitle>
|
||||||
<CardDescription>Preencha seus dados para criar sua conta</CardDescription>
|
<CardDescription className="text-muted-foreground">Preencha seus dados para acessar o portal MedConnect</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<form onSubmit={handleRegister} className="space-y-4">
|
<form onSubmit={handleRegister} className="space-y-4">
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
<div className="grid md:grid-cols-2 gap-4">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="name">Nome Completo</Label>
|
<Label htmlFor="name">Nome Completo *</Label>
|
||||||
<Input
|
<Input
|
||||||
id="name"
|
id="name"
|
||||||
value={formData.name}
|
value={formData.name}
|
||||||
onChange={(e) => handleInputChange("name", e.target.value)}
|
onChange={(e) => handleInputChange("name", e.target.value)}
|
||||||
required
|
required
|
||||||
|
disabled={isLoading}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="cpf">CPF</Label>
|
<Label htmlFor="cpf">CPF *</Label>
|
||||||
<Input
|
<Input
|
||||||
id="cpf"
|
id="cpf"
|
||||||
value={formData.cpf}
|
value={formData.cpf}
|
||||||
onChange={(e) => handleInputChange("cpf", e.target.value)}
|
onChange={(e) => handleInputChange("cpf", e.target.value)}
|
||||||
placeholder="000.000.000-00"
|
placeholder="000.000.000-00"
|
||||||
required
|
required
|
||||||
|
disabled={isLoading}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
<div className="grid md:grid-cols-2 gap-4">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="email">Email</Label>
|
<Label htmlFor="email">Email *</Label>
|
||||||
<Input
|
<Input
|
||||||
id="email"
|
id="email"
|
||||||
type="email"
|
type="email"
|
||||||
value={formData.email}
|
value={formData.email}
|
||||||
onChange={(e) => handleInputChange("email", e.target.value)}
|
onChange={(e) => handleInputChange("email", e.target.value)}
|
||||||
required
|
required
|
||||||
|
disabled={isLoading}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="phone">Telefone</Label>
|
<Label htmlFor="phone">Telefone *</Label>
|
||||||
<Input
|
<Input
|
||||||
id="phone"
|
id="phone"
|
||||||
value={formData.phone}
|
value={formData.phone}
|
||||||
onChange={(e) => handleInputChange("phone", e.target.value)}
|
onChange={(e) => handleInputChange("phone", e.target.value)}
|
||||||
placeholder="(11) 99999-9999"
|
placeholder="(11) 99999-9999"
|
||||||
required
|
required
|
||||||
|
disabled={isLoading}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="birthDate">Data de Nascimento</Label>
|
<Label htmlFor="birthDate">Data de Nascimento *</Label>
|
||||||
<Input
|
<Input
|
||||||
id="birthDate"
|
id="birthDate"
|
||||||
type="date"
|
type="date"
|
||||||
value={formData.birthDate}
|
value={formData.birthDate}
|
||||||
onChange={(e) => handleInputChange("birthDate", e.target.value)}
|
onChange={(e) => handleInputChange("birthDate", e.target.value)}
|
||||||
required
|
required
|
||||||
|
disabled={isLoading}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
{/* REMOVIDO: Seção de senha e confirmação de senha */}
|
||||||
<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>
|
|
||||||
|
|
||||||
<Button type="submit" className="w-full" disabled={isLoading}>
|
<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>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<div className="mt-6 text-center">
|
<div className="mt-6 text-center">
|
||||||
<p className="text-sm text-gray-600">
|
<p className="text-sm">
|
||||||
Já tem uma conta?{" "}
|
<span className="text-muted-foreground">Já tem uma conta?</span>{" "}
|
||||||
<Link href="/patient/login" className="text-blue-600 hover:underline">
|
<Link href="/login" className="text-primary hover:underline font-medium">
|
||||||
Faça login aqui
|
Faça login aqui
|
||||||
</Link>
|
</Link>
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@ -1,159 +1,68 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useState, useEffect } from "react"
|
import { useState, useEffect, useMemo } from "react"
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||||
import { Badge } from "@/components/ui/badge"
|
import { Badge } from "@/components/ui/badge"
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button"
|
||||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"
|
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"
|
||||||
import { toast } from "@/hooks/use-toast"
|
import { toast } from "@/hooks/use-toast"
|
||||||
import { FileText, Download, Eye, Calendar, User, X } from "lucide-react"
|
import { FileText, Download, Eye, Calendar, User, X, Loader2 } from "lucide-react"
|
||||||
import Sidebar from "@/components/Sidebar"
|
import Sidebar from "@/components/Sidebar"
|
||||||
|
import { useAuthLayout } from "@/hooks/useAuthLayout"
|
||||||
|
import { reportsApi } from "@/services/reportsApi.mjs"
|
||||||
|
|
||||||
interface Report {
|
interface Report {
|
||||||
id: string
|
id: string;
|
||||||
title: string
|
order_number: string;
|
||||||
doctor: string
|
patient_id: string;
|
||||||
date: string
|
status: string;
|
||||||
type: string
|
exam: string;
|
||||||
status: "disponivel" | "pendente"
|
requested_by: string;
|
||||||
description: string
|
cid_code: string;
|
||||||
content: {
|
diagnosis: string;
|
||||||
patientInfo: {
|
conclusion: string;
|
||||||
name: string
|
content_html: string;
|
||||||
age: number
|
content_json: any;
|
||||||
gender: string
|
hide_date: boolean;
|
||||||
id: string
|
hide_signature: boolean;
|
||||||
}
|
due_at: string;
|
||||||
examDetails: {
|
created_by: string;
|
||||||
requestingDoctor: string
|
updated_by: string;
|
||||||
examDate: string
|
created_at: string;
|
||||||
reportDate: string
|
updated_at: string;
|
||||||
technique: string
|
|
||||||
}
|
|
||||||
findings: string
|
|
||||||
conclusion: string
|
|
||||||
recommendations?: string
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function ReportsPage() {
|
export default function ReportsPage() {
|
||||||
const [reports, setReports] = useState<Report[]>([])
|
const [reports, setReports] = useState<Report[]>([])
|
||||||
const [selectedReport, setSelectedReport] = useState<Report | null>(null)
|
const [selectedReport, setSelectedReport] = useState<Report | null>(null)
|
||||||
const [isViewModalOpen, setIsViewModalOpen] = useState(false)
|
const [isViewModalOpen, setIsViewModalOpen] = useState(false)
|
||||||
|
const [isLoading, setIsLoading] = useState(true)
|
||||||
|
const { user, isLoading: isAuthLoading } = useAuthLayout({
|
||||||
|
requiredRole: ["paciente", "admin", "medico", "gestor", "secretaria"],
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const mockReports: Report[] = [
|
if (user) {
|
||||||
{
|
const fetchReports = async () => {
|
||||||
id: "1",
|
try {
|
||||||
title: "Exame de Sangue - Hemograma Completo",
|
setIsLoading(true);
|
||||||
doctor: "Dr. João Silva",
|
const fetchedReports = await reportsApi.getReports(user.id);
|
||||||
date: "2024-01-15",
|
setReports(fetchedReports);
|
||||||
type: "Exame Laboratorial",
|
} catch (error) {
|
||||||
status: "disponivel",
|
console.error("Erro ao buscar laudos:", error)
|
||||||
description: "Hemograma completo com contagem de células sanguíneas",
|
toast({
|
||||||
content: {
|
title: "Erro ao buscar laudos",
|
||||||
patientInfo: {
|
description: "Não foi possível carregar os laudos. Tente novamente.",
|
||||||
name: "Maria Silva Santos",
|
variant: "destructive",
|
||||||
age: 35,
|
})
|
||||||
gender: "Feminino",
|
} finally {
|
||||||
id: "123.456.789-00",
|
setIsLoading(false);
|
||||||
},
|
}
|
||||||
examDetails: {
|
}
|
||||||
requestingDoctor: "Dr. João Silva - CRM 12345",
|
fetchReports()
|
||||||
examDate: "15/01/2024",
|
}
|
||||||
reportDate: "15/01/2024",
|
}, [user?.id])
|
||||||
technique: "Análise automatizada com confirmação microscópica",
|
|
||||||
},
|
|
||||||
findings:
|
|
||||||
"Hemácias: 4.5 milhões/mm³ (VR: 4.0-5.2)\nHemoglobina: 13.2 g/dL (VR: 12.0-15.5)\nHematócrito: 40% (VR: 36-46)\nLeucócitos: 7.200/mm³ (VR: 4.000-11.000)\nPlaquetas: 280.000/mm³ (VR: 150.000-450.000)\n\nFórmula leucocitária:\n- Neutrófilos: 65% (VR: 50-70%)\n- Linfócitos: 28% (VR: 20-40%)\n- Monócitos: 5% (VR: 2-8%)\n- Eosinófilos: 2% (VR: 1-4%)",
|
|
||||||
conclusion:
|
|
||||||
"Hemograma dentro dos parâmetros normais. Não foram observadas alterações significativas na série vermelha, branca ou plaquetária.",
|
|
||||||
recommendations: "Manter acompanhamento médico regular. Repetir exame conforme orientação médica.",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "2",
|
|
||||||
title: "Radiografia do Tórax",
|
|
||||||
doctor: "Dra. Maria Santos",
|
|
||||||
date: "2024-01-10",
|
|
||||||
type: "Exame de Imagem",
|
|
||||||
status: "disponivel",
|
|
||||||
description: "Radiografia PA e perfil do tórax",
|
|
||||||
content: {
|
|
||||||
patientInfo: {
|
|
||||||
name: "Maria Silva Santos",
|
|
||||||
age: 35,
|
|
||||||
gender: "Feminino",
|
|
||||||
id: "123.456.789-00",
|
|
||||||
},
|
|
||||||
examDetails: {
|
|
||||||
requestingDoctor: "Dra. Maria Santos - CRM 67890",
|
|
||||||
examDate: "10/01/2024",
|
|
||||||
reportDate: "10/01/2024",
|
|
||||||
technique: "Radiografia digital PA e perfil",
|
|
||||||
},
|
|
||||||
findings:
|
|
||||||
"Campos pulmonares livres, sem sinais de consolidação ou derrame pleural. Silhueta cardíaca dentro dos limites normais. Estruturas ósseas íntegras. Diafragmas em posição normal.",
|
|
||||||
conclusion: "Radiografia de tórax sem alterações patológicas evidentes.",
|
|
||||||
recommendations: "Correlacionar com quadro clínico. Acompanhamento conforme indicação médica.",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "3",
|
|
||||||
title: "Eletrocardiograma",
|
|
||||||
doctor: "Dr. Carlos Oliveira",
|
|
||||||
date: "2024-01-08",
|
|
||||||
type: "Exame Cardiológico",
|
|
||||||
status: "pendente",
|
|
||||||
description: "ECG de repouso para avaliação cardíaca",
|
|
||||||
content: {
|
|
||||||
patientInfo: {
|
|
||||||
name: "Maria Silva Santos",
|
|
||||||
age: 35,
|
|
||||||
gender: "Feminino",
|
|
||||||
id: "123.456.789-00",
|
|
||||||
},
|
|
||||||
examDetails: {
|
|
||||||
requestingDoctor: "Dr. Carlos Oliveira - CRM 54321",
|
|
||||||
examDate: "08/01/2024",
|
|
||||||
reportDate: "",
|
|
||||||
technique: "ECG de repouso",
|
|
||||||
},
|
|
||||||
findings: "",
|
|
||||||
conclusion: "",
|
|
||||||
recommendations: "",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "4",
|
|
||||||
title: "Ultrassom Abdominal",
|
|
||||||
doctor: "Dra. Ana Costa",
|
|
||||||
date: "2024-01-05",
|
|
||||||
type: "Exame de Imagem",
|
|
||||||
status: "disponivel",
|
|
||||||
description: "Ultrassonografia do abdome total",
|
|
||||||
content: {
|
|
||||||
patientInfo: {
|
|
||||||
name: "Maria Silva Santos",
|
|
||||||
age: 35,
|
|
||||||
gender: "Feminino",
|
|
||||||
id: "123.456.789-00",
|
|
||||||
},
|
|
||||||
examDetails: {
|
|
||||||
requestingDoctor: "Dra. Ana Costa - CRM 98765",
|
|
||||||
examDate: "05/01/2024",
|
|
||||||
reportDate: "05/01/2024",
|
|
||||||
technique: "Ultrassom convencional",
|
|
||||||
},
|
|
||||||
findings:
|
|
||||||
"Viscerais bem posicionadas. Rim direito e esquerdo com contornos normais. Vesícula com volume dentro do normal.",
|
|
||||||
conclusion: "Ultrassom abdominal sem alterações patológicas evidentes.",
|
|
||||||
recommendations: "Acompanhamento conforme indicação médica.",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]
|
|
||||||
setReports(mockReports)
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
const handleViewReport = (reportId: string) => {
|
const handleViewReport = (reportId: string) => {
|
||||||
const report = reports.find((r) => r.id === reportId)
|
const report = reports.find((r) => r.id === reportId)
|
||||||
@ -168,100 +77,23 @@ export default function ReportsPage() {
|
|||||||
if (!report) return
|
if (!report) return
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Simular loading
|
|
||||||
toast({
|
toast({
|
||||||
title: "Preparando download...",
|
title: "Preparando download...",
|
||||||
description: "Gerando PDF do laudo médico",
|
description: "Gerando PDF do laudo médico",
|
||||||
})
|
})
|
||||||
|
|
||||||
// Criar conteúdo HTML do laudo para conversão em PDF
|
const htmlContent = report.content_html;
|
||||||
const htmlContent = `
|
|
||||||
<!DOCTYPE html>
|
|
||||||
<html>
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8">
|
|
||||||
<title>Laudo Médico - ${report.title}</title>
|
|
||||||
<style>
|
|
||||||
body { font-family: Arial, sans-serif; margin: 40px; line-height: 1.6; }
|
|
||||||
.header { text-align: center; border-bottom: 2px solid #333; padding-bottom: 20px; margin-bottom: 30px; }
|
|
||||||
.section { margin-bottom: 25px; }
|
|
||||||
.section-title { font-size: 16px; font-weight: bold; color: #333; margin-bottom: 10px; border-bottom: 1px solid #ccc; padding-bottom: 5px; }
|
|
||||||
.info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px; }
|
|
||||||
.info-item { margin-bottom: 8px; }
|
|
||||||
.label { font-weight: bold; color: #555; }
|
|
||||||
.content { white-space: pre-line; }
|
|
||||||
.footer { margin-top: 40px; text-align: center; font-size: 12px; color: #666; }
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<div class="header">
|
|
||||||
<h1>LAUDO MÉDICO</h1>
|
|
||||||
<h2>${report.title}</h2>
|
|
||||||
<p><strong>Tipo:</strong> ${report.type}</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="section">
|
|
||||||
<div class="section-title">DADOS DO PACIENTE</div>
|
|
||||||
<div class="info-grid">
|
|
||||||
<div class="info-item"><span class="label">Nome:</span> ${report.content.patientInfo.name}</div>
|
|
||||||
<div class="info-item"><span class="label">Idade:</span> ${report.content.patientInfo.age} anos</div>
|
|
||||||
<div class="info-item"><span class="label">Sexo:</span> ${report.content.patientInfo.gender}</div>
|
|
||||||
<div class="info-item"><span class="label">CPF:</span> ${report.content.patientInfo.id}</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="section">
|
|
||||||
<div class="section-title">DETALHES DO EXAME</div>
|
|
||||||
<div class="info-grid">
|
|
||||||
<div class="info-item"><span class="label">Médico Solicitante:</span> ${report.content.examDetails.requestingDoctor}</div>
|
|
||||||
<div class="info-item"><span class="label">Data do Exame:</span> ${report.content.examDetails.examDate}</div>
|
|
||||||
<div class="info-item"><span class="label">Data do Laudo:</span> ${report.content.examDetails.reportDate}</div>
|
|
||||||
<div class="info-item"><span class="label">Técnica:</span> ${report.content.examDetails.technique}</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="section">
|
|
||||||
<div class="section-title">ACHADOS</div>
|
|
||||||
<div class="content">${report.content.findings}</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="section">
|
|
||||||
<div class="section-title">CONCLUSÃO</div>
|
|
||||||
<div class="content">${report.content.conclusion}</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
${
|
|
||||||
report.content.recommendations
|
|
||||||
? `
|
|
||||||
<div class="section">
|
|
||||||
<div class="section-title">RECOMENDAÇÕES</div>
|
|
||||||
<div class="content">${report.content.recommendations}</div>
|
|
||||||
</div>
|
|
||||||
`
|
|
||||||
: ""
|
|
||||||
}
|
|
||||||
|
|
||||||
<div class="footer">
|
|
||||||
<p>Documento gerado em ${new Date().toLocaleDateString("pt-BR")} às ${new Date().toLocaleTimeString("pt-BR")}</p>
|
|
||||||
<p>Este é um documento médico oficial. Mantenha-o em local seguro.</p>
|
|
||||||
</div>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
`
|
|
||||||
|
|
||||||
// Criar blob com o conteúdo HTML
|
|
||||||
const blob = new Blob([htmlContent], { type: "text/html" })
|
const blob = new Blob([htmlContent], { type: "text/html" })
|
||||||
const url = URL.createObjectURL(blob)
|
const url = URL.createObjectURL(blob)
|
||||||
|
|
||||||
// Criar link temporário para download
|
|
||||||
const link = document.createElement("a")
|
const link = document.createElement("a")
|
||||||
link.href = url
|
link.href = url
|
||||||
link.download = `laudo-${report.title.replace(/[^a-zA-Z0-9]/g, "-").toLowerCase()}-${report.date}.html`
|
link.download = `laudo-${report.order_number}.html`
|
||||||
document.body.appendChild(link)
|
document.body.appendChild(link)
|
||||||
link.click()
|
link.click()
|
||||||
document.body.removeChild(link)
|
document.body.removeChild(link)
|
||||||
|
|
||||||
// Limpar URL temporária
|
|
||||||
URL.revokeObjectURL(url)
|
URL.revokeObjectURL(url)
|
||||||
|
|
||||||
toast({
|
toast({
|
||||||
@ -283,15 +115,25 @@ export default function ReportsPage() {
|
|||||||
setSelectedReport(null)
|
setSelectedReport(null)
|
||||||
}
|
}
|
||||||
|
|
||||||
const availableReports = reports.filter((report) => report.status === "disponivel")
|
const availableReports = reports.filter((report) => report.status.toLowerCase() === "draft")
|
||||||
const pendingReports = reports.filter((report) => report.status === "pendente")
|
const pendingReports = reports.filter((report) => report.status.toLowerCase() !== "draft")
|
||||||
|
|
||||||
|
if (isLoading || isAuthLoading) {
|
||||||
|
return (
|
||||||
|
<Sidebar>
|
||||||
|
<div className="flex justify-center items-center h-full">
|
||||||
|
<Loader2 className="h-8 w-8 animate-spin" />
|
||||||
|
</div>
|
||||||
|
</Sidebar>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Sidebar>
|
<Sidebar>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-bold text-gray-900">Meus Laudos</h1>
|
<h1 className="text-3xl font-bold text-foreground">Meus Laudos</h1>
|
||||||
<p className="text-gray-600 mt-2">Visualize e baixe seus laudos médicos e resultados de exames</p>
|
<p className="text-muted-foreground mt-2">Visualize e baixe seus laudos médicos e resultados de exames</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||||
@ -326,32 +168,32 @@ export default function ReportsPage() {
|
|||||||
|
|
||||||
{availableReports.length > 0 && (
|
{availableReports.length > 0 && (
|
||||||
<div>
|
<div>
|
||||||
<h2 className="text-xl font-semibold text-gray-900 mb-4">Laudos Disponíveis</h2>
|
<h2 className="text-xl font-semibold text-foreground mb-4">Laudos Disponíveis</h2>
|
||||||
<div className="grid gap-4">
|
<div className="grid gap-4">
|
||||||
{availableReports.map((report) => (
|
{availableReports.map((report) => (
|
||||||
<Card key={report.id} className="hover:shadow-md transition-shadow">
|
<Card key={report.id} className="hover:shadow-md transition-shadow">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<div className="flex items-start justify-between">
|
<div className="flex items-start justify-between">
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
<CardTitle className="text-lg">{report.title}</CardTitle>
|
<CardTitle className="text-lg">{report.exam}</CardTitle>
|
||||||
<CardDescription className="flex items-center gap-4">
|
<CardDescription className="flex items-center gap-4">
|
||||||
<span className="flex items-center gap-1">
|
<span className="flex items-center gap-1">
|
||||||
<User className="h-4 w-4" />
|
<User className="h-4 w-4" />
|
||||||
{report.doctor}
|
{report.requested_by}
|
||||||
</span>
|
</span>
|
||||||
<span className="flex items-center gap-1">
|
<span className="flex items-center gap-1">
|
||||||
<Calendar className="h-4 w-4" />
|
<Calendar className="h-4 w-4" />
|
||||||
{new Date(report.date).toLocaleDateString("pt-BR")}
|
{new Date(report.created_at).toLocaleDateString("pt-BR")}
|
||||||
</span>
|
</span>
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</div>
|
</div>
|
||||||
<Badge variant="secondary" className="bg-green-100 text-green-800">
|
<Badge variant="secondary" className="bg-green-100 text-green-800">
|
||||||
{report.type}
|
Finalizado
|
||||||
</Badge>
|
</Badge>
|
||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<p className="text-gray-600 mb-4">{report.description}</p>
|
<p className="text-muted-foreground mb-4">{report.diagnosis}</p>
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
@ -369,7 +211,7 @@ export default function ReportsPage() {
|
|||||||
className="flex items-center gap-2"
|
className="flex items-center gap-2"
|
||||||
>
|
>
|
||||||
<Download className="h-4 w-4" />
|
<Download className="h-4 w-4" />
|
||||||
Baixar PDF
|
Baixar
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
@ -381,33 +223,33 @@ export default function ReportsPage() {
|
|||||||
|
|
||||||
{pendingReports.length > 0 && (
|
{pendingReports.length > 0 && (
|
||||||
<div>
|
<div>
|
||||||
<h2 className="text-xl font-semibold text-gray-900 mb-4">Laudos Pendentes</h2>
|
<h2 className="text-xl font-semibold text-foreground mb-4">Laudos Pendentes</h2>
|
||||||
<div className="grid gap-4">
|
<div className="grid gap-4">
|
||||||
{pendingReports.map((report) => (
|
{pendingReports.map((report) => (
|
||||||
<Card key={report.id} className="opacity-75">
|
<Card key={report.id} className="opacity-75">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<div className="flex items-start justify-between">
|
<div className="flex items-start justify-between">
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
<CardTitle className="text-lg">{report.title}</CardTitle>
|
<CardTitle className="text-lg">{report.exam}</CardTitle>
|
||||||
<CardDescription className="flex items-center gap-4">
|
<CardDescription className="flex items-center gap-4">
|
||||||
<span className="flex items-center gap-1">
|
<span className="flex items-center gap-1">
|
||||||
<User className="h-4 w-4" />
|
<User className="h-4 w-4" />
|
||||||
{report.doctor}
|
{report.requested_by}
|
||||||
</span>
|
</span>
|
||||||
<span className="flex items-center gap-1">
|
<span className="flex items-center gap-1">
|
||||||
<Calendar className="h-4 w-4" />
|
<Calendar className="h-4 w-4" />
|
||||||
{new Date(report.date).toLocaleDateString("pt-BR")}
|
{new Date(report.created_at).toLocaleDateString("pt-BR")}
|
||||||
</span>
|
</span>
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</div>
|
</div>
|
||||||
<Badge variant="secondary" className="bg-yellow-100 text-yellow-800">
|
<Badge variant="secondary" className="bg-yellow-100 text-yellow-800">
|
||||||
Pendente
|
{report.status}
|
||||||
</Badge>
|
</Badge>
|
||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<p className="text-gray-600 mb-4">{report.description}</p>
|
<p className="text-muted-foreground mb-4">{report.diagnosis}</p>
|
||||||
<p className="text-sm text-yellow-600 font-medium">
|
<p className="text-sm text-yellow-600 dark:text-yellow-500 font-medium">
|
||||||
Laudo em processamento. Você será notificado quando estiver disponível.
|
Laudo em processamento. Você será notificado quando estiver disponível.
|
||||||
</p>
|
</p>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
@ -417,12 +259,12 @@ export default function ReportsPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{reports.length === 0 && (
|
{reports.length === 0 && !isLoading && (
|
||||||
<Card className="text-center py-12">
|
<Card className="text-center py-12">
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<FileText className="h-12 w-12 text-gray-400 mx-auto mb-4" />
|
<FileText className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
|
||||||
<h3 className="text-lg font-medium text-gray-900 mb-2">Nenhum laudo encontrado</h3>
|
<h3 className="text-lg font-medium text-foreground mb-2">Nenhum laudo encontrado</h3>
|
||||||
<p className="text-gray-600">Seus laudos médicos aparecerão aqui após a realização de exames.</p>
|
<p className="text-muted-foreground">Seus laudos médicos aparecerão aqui após a realização de exames.</p>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
)}
|
)}
|
||||||
@ -432,9 +274,9 @@ export default function ReportsPage() {
|
|||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
<DialogTitle className="text-xl font-bold">{selectedReport?.title}</DialogTitle>
|
<DialogTitle className="text-xl font-bold">{selectedReport?.exam}</DialogTitle>
|
||||||
<DialogDescription className="mt-1">
|
<DialogDescription className="mt-1">
|
||||||
{selectedReport?.type} - {selectedReport?.doctor}
|
{selectedReport?.order_number}
|
||||||
</DialogDescription>
|
</DialogDescription>
|
||||||
</div>
|
</div>
|
||||||
<Button variant="ghost" size="sm" onClick={handleCloseModal} className="h-8 w-8 p-0">
|
<Button variant="ghost" size="sm" onClick={handleCloseModal} className="h-8 w-8 p-0">
|
||||||
@ -444,94 +286,7 @@ export default function ReportsPage() {
|
|||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
|
|
||||||
{selectedReport && (
|
{selectedReport && (
|
||||||
<div className="space-y-6 mt-4">
|
<div className="space-y-6 mt-4" dangerouslySetInnerHTML={{ __html: selectedReport.content_html }} />
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle className="text-lg">Dados do Paciente</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="grid grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<p className="text-sm font-medium text-gray-500">Nome</p>
|
|
||||||
<p className="text-sm">{selectedReport.content.patientInfo.name}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="text-sm font-medium text-gray-500">Idade</p>
|
|
||||||
<p className="text-sm">{selectedReport.content.patientInfo.age} anos</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="text-sm font-medium text-gray-500">Sexo</p>
|
|
||||||
<p className="text-sm">{selectedReport.content.patientInfo.gender}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="text-sm font-medium text-gray-500">CPF</p>
|
|
||||||
<p className="text-sm">{selectedReport.content.patientInfo.id}</p>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle className="text-lg">Detalhes do Exame</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="grid grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<p className="text-sm font-medium text-gray-500">Médico Solicitante</p>
|
|
||||||
<p className="text-sm">{selectedReport.content.examDetails.requestingDoctor}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="text-sm font-medium text-gray-500">Data do Exame</p>
|
|
||||||
<p className="text-sm">{selectedReport.content.examDetails.examDate}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="text-sm font-medium text-gray-500">Data do Laudo</p>
|
|
||||||
<p className="text-sm">{selectedReport.content.examDetails.reportDate}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="text-sm font-medium text-gray-500">Técnica</p>
|
|
||||||
<p className="text-sm">{selectedReport.content.examDetails.technique}</p>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle className="text-lg">Achados</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<div className="whitespace-pre-line text-sm leading-relaxed">{selectedReport.content.findings}</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle className="text-lg">Conclusão</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<p className="text-sm leading-relaxed">{selectedReport.content.conclusion}</p>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{selectedReport.content.recommendations && (
|
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle className="text-lg">Recomendações</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<p className="text-sm leading-relaxed">{selectedReport.content.recommendations}</p>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="flex gap-3 pt-4 border-t">
|
|
||||||
<Button onClick={() => handleDownloadReport(selectedReport.id)} className="flex items-center gap-2">
|
|
||||||
<Download className="h-4 w-4" />
|
|
||||||
Baixar PDF
|
|
||||||
</Button>
|
|
||||||
<Button variant="outline" onClick={handleCloseModal}>
|
|
||||||
Fechar
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|||||||
18
app/providers.tsx
Normal file
18
app/providers.tsx
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { AccessibilityProvider } from "./context/AccessibilityContext";
|
||||||
|
import { AppointmentsProvider } from "./context/AppointmentsContext";
|
||||||
|
import { AccessibilityModal } from "@/components/accessibility-modal";
|
||||||
|
import { ThemeInitializer } from "@/components/theme-initializer";
|
||||||
|
|
||||||
|
export function Providers({ children }: { children: React.ReactNode }) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<ThemeInitializer />
|
||||||
|
<AccessibilityProvider>
|
||||||
|
<AppointmentsProvider>{children}</AppointmentsProvider>
|
||||||
|
<AccessibilityModal />
|
||||||
|
</AccessibilityProvider>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -1,11 +1,34 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect, useMemo } from "react";
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
import {
|
||||||
|
Card,
|
||||||
|
CardContent,
|
||||||
|
CardDescription,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from "@/components/ui/card";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Dialog } from "@/components/ui/dialog";
|
import { Dialog } from "@/components/ui/dialog";
|
||||||
import { Calendar, Clock, MapPin, Phone, User, Trash2, Pencil } from "lucide-react";
|
import { Input } from "@/components/ui/input"; // Importei o Input
|
||||||
|
import { Calendar as CalendarShadcn } from "@/components/ui/calendar";
|
||||||
|
import { Separator } from "@/components/ui/separator";
|
||||||
|
import {
|
||||||
|
Calendar as CalendarIcon,
|
||||||
|
Clock,
|
||||||
|
MapPin,
|
||||||
|
Phone,
|
||||||
|
User,
|
||||||
|
Trash2,
|
||||||
|
Pencil,
|
||||||
|
List,
|
||||||
|
RefreshCw,
|
||||||
|
Loader2,
|
||||||
|
Search, // Importei o ícone de busca
|
||||||
|
} from "lucide-react";
|
||||||
|
import { format, parseISO, isValid, isToday, isTomorrow } from "date-fns";
|
||||||
|
import { ptBR } from "date-fns/locale";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
||||||
@ -22,6 +45,9 @@ export default function SecretaryAppointments() {
|
|||||||
const [deleteModal, setDeleteModal] = useState(false);
|
const [deleteModal, setDeleteModal] = useState(false);
|
||||||
const [editModal, setEditModal] = useState(false);
|
const [editModal, setEditModal] = useState(false);
|
||||||
|
|
||||||
|
// Estado da Busca
|
||||||
|
const [searchTerm, setSearchTerm] = useState("");
|
||||||
|
|
||||||
// Estado para o formulário de edição
|
// Estado para o formulário de edição
|
||||||
const [editFormData, setEditFormData] = useState({
|
const [editFormData, setEditFormData] = useState({
|
||||||
date: "",
|
date: "",
|
||||||
@ -29,15 +55,15 @@ export default function SecretaryAppointments() {
|
|||||||
status: "",
|
status: "",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Estado de data selecionada
|
||||||
|
const [selectedDate, setSelectedDate] = useState<Date | undefined>(new Date());
|
||||||
|
|
||||||
const fetchData = async () => {
|
const fetchData = async () => {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
try {
|
try {
|
||||||
// 1. DEFINIR O PARÂMETRO DE ORDENAÇÃO
|
const queryParams = "order=scheduled_at.asc";
|
||||||
// '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([
|
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),
|
appointmentsService.search_appointment(queryParams),
|
||||||
patientsService.list(),
|
patientsService.list(),
|
||||||
doctorsService.list(),
|
doctorsService.list(),
|
||||||
@ -48,8 +74,13 @@ export default function SecretaryAppointments() {
|
|||||||
|
|
||||||
const enrichedAppointments = appointmentList.map((apt: any) => ({
|
const enrichedAppointments = appointmentList.map((apt: any) => ({
|
||||||
...apt,
|
...apt,
|
||||||
patient: patientMap.get(apt.patient_id) || { full_name: "Paciente não encontrado" },
|
patient: patientMap.get(apt.patient_id) || {
|
||||||
doctor: doctorMap.get(apt.doctor_id) || { full_name: "Médico não encontrado", specialty: "N/A" },
|
full_name: "Paciente não encontrado",
|
||||||
|
},
|
||||||
|
doctor: doctorMap.get(apt.doctor_id) || {
|
||||||
|
full_name: "Médico não encontrado",
|
||||||
|
specialty: "N/A",
|
||||||
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
setAppointments(enrichedAppointments);
|
setAppointments(enrichedAppointments);
|
||||||
@ -63,50 +94,112 @@ export default function SecretaryAppointments() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchData();
|
fetchData();
|
||||||
}, []); // Array vazio garante que a busca ocorra apenas uma vez, no carregamento da página.
|
}, []);
|
||||||
|
|
||||||
// --- LÓGICA DE EDIÇÃO ---
|
// --- Filtragem e Agrupamento ---
|
||||||
|
const groupedAppointments = useMemo(() => {
|
||||||
|
let filteredList = appointments;
|
||||||
|
|
||||||
|
// 1. Filtro de Texto (Nome do Paciente ou Médico)
|
||||||
|
if (searchTerm) {
|
||||||
|
const lowerTerm = searchTerm.toLowerCase();
|
||||||
|
filteredList = filteredList.filter(
|
||||||
|
(apt) =>
|
||||||
|
apt.patient.full_name.toLowerCase().includes(lowerTerm) ||
|
||||||
|
apt.doctor.full_name.toLowerCase().includes(lowerTerm)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Filtro de Data (se selecionada)
|
||||||
|
if (selectedDate) {
|
||||||
|
filteredList = filteredList.filter((apt) => {
|
||||||
|
if (!apt.scheduled_at) return false;
|
||||||
|
const iso = apt.scheduled_at.toString();
|
||||||
|
return iso.startsWith(format(selectedDate, "yyyy-MM-dd"));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Agrupamento por dia
|
||||||
|
return filteredList.reduce((acc: Record<string, any[]>, apt: any) => {
|
||||||
|
if (!apt.scheduled_at) return acc;
|
||||||
|
const dateObj = new Date(apt.scheduled_at);
|
||||||
|
if (!isValid(dateObj)) return acc;
|
||||||
|
const key = format(dateObj, "yyyy-MM-dd");
|
||||||
|
if (!acc[key]) acc[key] = [];
|
||||||
|
acc[key].push(apt);
|
||||||
|
return acc;
|
||||||
|
}, {});
|
||||||
|
}, [appointments, selectedDate, searchTerm]);
|
||||||
|
|
||||||
|
// Dias que têm consulta (para destacar no calendário)
|
||||||
|
const bookedDays = useMemo(
|
||||||
|
() =>
|
||||||
|
appointments
|
||||||
|
.map((apt) =>
|
||||||
|
apt.scheduled_at ? new Date(apt.scheduled_at) : null
|
||||||
|
)
|
||||||
|
.filter((d): d is Date => d !== null && isValid(d)),
|
||||||
|
[appointments]
|
||||||
|
);
|
||||||
|
|
||||||
|
const formatDisplayDate = (dateString: string) => {
|
||||||
|
const date = parseISO(dateString);
|
||||||
|
if (isToday(date)) {
|
||||||
|
return `Hoje, ${format(date, "dd 'de' MMMM", { locale: ptBR })}`;
|
||||||
|
}
|
||||||
|
if (isTomorrow(date)) {
|
||||||
|
return `Amanhã, ${format(date, "dd 'de' MMMM", { locale: ptBR })}`;
|
||||||
|
}
|
||||||
|
return format(date, "EEEE, dd 'de' MMMM", { locale: ptBR });
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- LÓGICA DE EDIÇÃO E DELEÇÃO ---
|
||||||
const handleEdit = (appointment: any) => {
|
const handleEdit = (appointment: any) => {
|
||||||
setSelectedAppointment(appointment);
|
setSelectedAppointment(appointment);
|
||||||
const appointmentDate = new Date(appointment.scheduled_at);
|
const appointmentDate = new Date(appointment.scheduled_at);
|
||||||
|
|
||||||
setEditFormData({
|
setEditFormData({
|
||||||
date: appointmentDate.toISOString().split('T')[0],
|
date: appointmentDate.toISOString().split("T")[0],
|
||||||
time: appointmentDate.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit', timeZone: 'UTC' }),
|
time: appointmentDate.toLocaleTimeString("pt-BR", {
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
timeZone: "UTC",
|
||||||
|
}),
|
||||||
status: appointment.status,
|
status: appointment.status,
|
||||||
});
|
});
|
||||||
setEditModal(true);
|
setEditModal(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
const confirmEdit = async () => {
|
const confirmEdit = async () => {
|
||||||
if (!selectedAppointment || !editFormData.date || !editFormData.time || !editFormData.status) {
|
if (
|
||||||
|
!selectedAppointment ||
|
||||||
|
!editFormData.date ||
|
||||||
|
!editFormData.time ||
|
||||||
|
!editFormData.status
|
||||||
|
) {
|
||||||
toast.error("Todos os campos são obrigatórios para a edição.");
|
toast.error("Todos os campos são obrigatórios para a edição.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const newScheduledAt = new Date(`${editFormData.date}T${editFormData.time}:00Z`).toISOString();
|
const newScheduledAt = new Date(
|
||||||
|
`${editFormData.date}T${editFormData.time}:00Z`
|
||||||
|
).toISOString();
|
||||||
const updatePayload = {
|
const updatePayload = {
|
||||||
scheduled_at: newScheduledAt,
|
scheduled_at: newScheduledAt,
|
||||||
status: editFormData.status,
|
status: editFormData.status,
|
||||||
};
|
};
|
||||||
|
|
||||||
await appointmentsService.update(selectedAppointment.id, updatePayload);
|
await appointmentsService.update(selectedAppointment.id, updatePayload);
|
||||||
|
await fetchData();
|
||||||
// 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);
|
setEditModal(false);
|
||||||
toast.success("Consulta atualizada com sucesso!");
|
toast.success("Consulta atualizada com sucesso!");
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Erro ao atualizar consulta:", error);
|
console.error("Erro ao atualizar consulta:", error);
|
||||||
toast.error("Não foi possível atualizar a consulta.");
|
toast.error("Não foi possível atualizar a consulta.");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- LÓGICA DE DELEÇÃO ---
|
|
||||||
const handleDelete = (appointment: any) => {
|
const handleDelete = (appointment: any) => {
|
||||||
setSelectedAppointment(appointment);
|
setSelectedAppointment(appointment);
|
||||||
setDeleteModal(true);
|
setDeleteModal(true);
|
||||||
@ -116,7 +209,9 @@ export default function SecretaryAppointments() {
|
|||||||
if (!selectedAppointment) return;
|
if (!selectedAppointment) return;
|
||||||
try {
|
try {
|
||||||
await appointmentsService.delete(selectedAppointment.id);
|
await appointmentsService.delete(selectedAppointment.id);
|
||||||
setAppointments((prev) => prev.filter((apt) => apt.id !== selectedAppointment.id));
|
setAppointments((prev) =>
|
||||||
|
prev.filter((apt) => apt.id !== selectedAppointment.id)
|
||||||
|
);
|
||||||
setDeleteModal(false);
|
setDeleteModal(false);
|
||||||
toast.success("Consulta deletada com sucesso!");
|
toast.success("Consulta deletada com sucesso!");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@ -125,103 +220,249 @@ export default function SecretaryAppointments() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const getStatusBadge = (status: string) => {
|
|
||||||
switch (status) {
|
|
||||||
case "requested": return <Badge className="bg-yellow-100 text-yellow-800">Solicitada</Badge>;
|
|
||||||
case "confirmed": return <Badge className="bg-blue-100 text-blue-800">Confirmada</Badge>;
|
|
||||||
case "checked_in": return <Badge className="bg-indigo-100 text-indigo-800">Check-in</Badge>;
|
|
||||||
case "completed": return <Badge className="bg-green-100 text-green-800">Realizada</Badge>;
|
|
||||||
case "cancelled": return <Badge className="bg-red-100 text-red-800">Cancelada</Badge>;
|
|
||||||
case "no_show": return <Badge className="bg-gray-100 text-gray-800">Não Compareceu</Badge>;
|
|
||||||
default: return <Badge variant="secondary">{status}</Badge>;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
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 (
|
return (
|
||||||
<Sidebar>
|
<Sidebar>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="flex justify-between items-center">
|
{/* Cabeçalho principal */}
|
||||||
|
<div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-bold text-gray-900">Consultas Agendadas</h1>
|
<h1 className="text-3xl font-bold text-foreground">
|
||||||
<p className="text-gray-600">Gerencie as consultas dos pacientes</p>
|
Agenda Médica
|
||||||
|
</h1>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
Consultas para os pacientes
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<Link href="/secretary/schedule">
|
<Link href="/secretary/schedule">
|
||||||
<Button><Calendar className="mr-2 h-4 w-4" /> Agendar Nova Consulta</Button>
|
<Button className="bg-primary hover:bg-primary/90 text-primary-foreground">
|
||||||
|
<CalendarIcon className="mr-2 h-4 w-4" />
|
||||||
|
Agendar Nova Consulta
|
||||||
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid gap-6">
|
{/* Barra de Filtros e Ações */}
|
||||||
{isLoading ? <p>Carregando consultas...</p> : appointments.length > 0 ? (
|
<div className="flex flex-col md:flex-row justify-between items-center gap-4">
|
||||||
appointments.map((appointment) => (
|
<h2 className="text-xl font-semibold capitalize whitespace-nowrap">
|
||||||
<Card key={appointment.id}>
|
{selectedDate
|
||||||
<CardHeader>
|
? `Agenda de ${format(selectedDate, "dd/MM/yyyy")}`
|
||||||
<div className="flex justify-between items-start">
|
: "Todas as Consultas"}
|
||||||
<div>
|
</h2>
|
||||||
<CardTitle className="text-lg">{appointment.doctor.full_name}</CardTitle>
|
|
||||||
<CardDescription>{appointment.doctor.specialty}</CardDescription>
|
<div className="flex flex-col md:flex-row items-center gap-3 w-full md:w-auto">
|
||||||
|
{/* BARRA DE PESQUISA ADICIONADA AQUI */}
|
||||||
|
<div className="relative w-full md:w-72">
|
||||||
|
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||||
|
<Input
|
||||||
|
type="search"
|
||||||
|
placeholder="Buscar paciente ou médico..."
|
||||||
|
className="pl-9 w-full"
|
||||||
|
value={searchTerm}
|
||||||
|
onChange={(e) => setSearchTerm(e.target.value)}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
{getStatusBadge(appointment.status)}
|
|
||||||
</div>
|
<div className="flex gap-2 w-full md:w-auto">
|
||||||
</CardHeader>
|
<Button
|
||||||
<CardContent>
|
onClick={() => {
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
setSelectedDate(undefined);
|
||||||
<div className="space-y-3">
|
setSearchTerm("");
|
||||||
<div className="flex items-center text-sm text-gray-800 font-medium">
|
}}
|
||||||
<User className="mr-2 h-4 w-4 text-gray-600" />
|
variant="ghost"
|
||||||
{appointment.patient.full_name}
|
size="sm"
|
||||||
</div>
|
className="flex-1 md:flex-none"
|
||||||
<div className="flex items-center text-sm text-gray-600">
|
>
|
||||||
<Calendar className="mr-2 h-4 w-4" />
|
<List className="mr-2 h-4 w-4" />
|
||||||
{new Date(appointment.scheduled_at).toLocaleDateString("pt-BR", { timeZone: "UTC" })}
|
Mostrar Todas
|
||||||
</div>
|
</Button>
|
||||||
<div className="flex items-center text-sm text-gray-600">
|
<Button
|
||||||
<Clock className="mr-2 h-4 w-4" />
|
onClick={() => fetchData()}
|
||||||
{new Date(appointment.scheduled_at).toLocaleTimeString("pt-BR", { hour: '2-digit', minute: '2-digit', timeZone: "UTC" })}
|
disabled={isLoading}
|
||||||
</div>
|
variant="outline"
|
||||||
</div>
|
size="sm"
|
||||||
<div className="space-y-3">
|
className="flex-1 md:flex-none"
|
||||||
<div className="flex items-center text-sm text-gray-600">
|
>
|
||||||
<MapPin className="mr-2 h-4 w-4" />
|
<RefreshCw
|
||||||
{appointment.doctor.location || "Local a definir"}
|
className={`mr-2 h-4 w-4 ${isLoading ? "animate-spin" : ""}`}
|
||||||
</div>
|
/>
|
||||||
<div className="flex items-center text-sm text-gray-600">
|
Atualizar
|
||||||
<Phone className="mr-2 h-4 w-4" />
|
</Button>
|
||||||
{appointment.doctor.phone || "N/A"}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex gap-2 mt-4 pt-4 border-t">
|
{/* Grid com calendário + lista */}
|
||||||
<Button variant="outline" size="sm" onClick={() => handleEdit(appointment)}>
|
<div className="grid lg:grid-cols-3 gap-6">
|
||||||
|
{/* Coluna esquerda: calendário */}
|
||||||
|
<div className="lg:col-span-1">
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="flex items-center">
|
||||||
|
<CalendarIcon className="mr-2 h-5 w-5" />
|
||||||
|
Filtrar por Data
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Selecione um dia para ver os detalhes.
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="flex justify-center p-2">
|
||||||
|
<CalendarShadcn
|
||||||
|
mode="single"
|
||||||
|
selected={selectedDate}
|
||||||
|
onSelect={setSelectedDate}
|
||||||
|
modifiers={{ booked: bookedDays }}
|
||||||
|
modifiersClassNames={{ booked: "bg-primary/20" }}
|
||||||
|
className="rounded-md border p-2"
|
||||||
|
locale={ptBR}
|
||||||
|
/>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Coluna direita: lista de consultas */}
|
||||||
|
<div className="lg:col-span-2 space-y-6">
|
||||||
|
{isLoading ? (
|
||||||
|
<div className="flex justify-center items-center h-48">
|
||||||
|
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
||||||
|
</div>
|
||||||
|
) : Object.keys(groupedAppointments).length === 0 ? (
|
||||||
|
<Card className="flex flex-col items-center justify-center h-48 text-center">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Nenhuma consulta encontrada</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
{searchTerm
|
||||||
|
? "Nenhum resultado para a busca."
|
||||||
|
: selectedDate
|
||||||
|
? "Não há agendamentos para esta data."
|
||||||
|
: "Não há consultas agendadas."}
|
||||||
|
</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
) : (
|
||||||
|
Object.entries(groupedAppointments).map(
|
||||||
|
([date, appointmentsForDay]) => (
|
||||||
|
<div key={date}>
|
||||||
|
<h3 className="text-lg font-semibold text-foreground mb-3 capitalize">
|
||||||
|
{formatDisplayDate(date)}
|
||||||
|
</h3>
|
||||||
|
<div className="space-y-4">
|
||||||
|
{appointmentsForDay.map((appointment: any) => {
|
||||||
|
const scheduledAtDate = new Date(
|
||||||
|
appointment.scheduled_at
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card
|
||||||
|
key={appointment.id}
|
||||||
|
className="shadow-sm hover:shadow-md transition-shadow"
|
||||||
|
>
|
||||||
|
<CardContent className="p-4 grid grid-cols-1 md:grid-cols-3 items-center gap-4">
|
||||||
|
{/* Coluna 1: Paciente + hora */}
|
||||||
|
<div className="col-span-1 flex flex-col gap-2">
|
||||||
|
<div className="font-semibold flex items-center text-foreground">
|
||||||
|
<User className="mr-2 h-4 w-4 text-primary" />
|
||||||
|
{appointment.patient.full_name}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center text-sm text-muted-foreground">
|
||||||
|
<Clock className="mr-2 h-4 w-4" />
|
||||||
|
{isValid(scheduledAtDate)
|
||||||
|
? format(scheduledAtDate, "HH:mm")
|
||||||
|
: "--:--"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Coluna 2: Médico / local / telefone */}
|
||||||
|
<div className="col-span-1 flex flex-col gap-2">
|
||||||
|
<div className="flex items-center text-sm text-muted-foreground">
|
||||||
|
<User className="mr-2 h-4 w-4" />
|
||||||
|
{appointment.doctor.full_name}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center text-sm text-muted-foreground">
|
||||||
|
<MapPin className="mr-2 h-4 w-4" />
|
||||||
|
{appointment.doctor.location ||
|
||||||
|
"Local a definir"}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center text-sm text-muted-foreground">
|
||||||
|
<Phone className="mr-2 h-4 w-4" />
|
||||||
|
{appointment.doctor.phone || "N/A"}
|
||||||
|
</div>
|
||||||
|
<div>{getStatusBadge(appointment.status)}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Coluna 3: Ações */}
|
||||||
|
<div className="col-span-1 flex justify-start md:justify-end">
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => handleEdit(appointment)}
|
||||||
|
>
|
||||||
<Pencil className="mr-2 h-4 w-4" />
|
<Pencil className="mr-2 h-4 w-4" />
|
||||||
Editar
|
Editar
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="outline" size="sm" className="text-red-600 hover:text-red-700 hover:bg-red-50 bg-transparent" onClick={() => handleDelete(appointment)}>
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => handleDelete(appointment)}
|
||||||
|
>
|
||||||
<Trash2 className="mr-2 h-4 w-4" />
|
<Trash2 className="mr-2 h-4 w-4" />
|
||||||
Deletar
|
Cancelar
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
))
|
);
|
||||||
) : (
|
})}
|
||||||
<p>Nenhuma consulta encontrada.</p>
|
</div>
|
||||||
|
<Separator className="my-6" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
)
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* MODAL DE EDIÇÃO */}
|
{/* MODAL DE EDIÇÃO */}
|
||||||
<Dialog open={editModal} onOpenChange={setEditModal}>
|
<Dialog open={editModal} onOpenChange={setEditModal}>
|
||||||
{/* ... (código do modal de edição) ... */}
|
{/* Modal de edição permanece o mesmo, adicione o DialogContent se precisar */}
|
||||||
|
{/* Aqui estou assumindo que você tem o conteúdo do Dialog no seu código original ou em outro lugar, pois ele não estava completo no snippet anterior */}
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|
||||||
{/* Modal de Deleção */}
|
{/* Modal de Deleção */}
|
||||||
<Dialog open={deleteModal} onOpenChange={setDeleteModal}>
|
<Dialog open={deleteModal} onOpenChange={setDeleteModal}>
|
||||||
{/* ... (código do modal de deleção) ... */}
|
{/* Modal de deleção permanece o mesmo */}
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
</div>
|
||||||
</Sidebar>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const getStatusBadge = (status: string) => {
|
||||||
|
switch (status) {
|
||||||
|
case "requested":
|
||||||
|
return (
|
||||||
|
<Badge className="bg-yellow-400/10 text-yellow-400">Solicitada</Badge>
|
||||||
|
);
|
||||||
|
case "confirmed":
|
||||||
|
return <Badge className="bg-primary/10 text-primary">Confirmada</Badge>;
|
||||||
|
case "checked_in":
|
||||||
|
return (
|
||||||
|
<Badge className="bg-indigo-400/10 text-indigo-400">Check-in</Badge>
|
||||||
|
);
|
||||||
|
case "completed":
|
||||||
|
return <Badge className="bg-green-400/10 text-green-400">Realizada</Badge>;
|
||||||
|
case "cancelled":
|
||||||
|
return (
|
||||||
|
<Badge className="bg-destructive/10 text-destructive">Cancelada</Badge>
|
||||||
|
);
|
||||||
|
case "no_show":
|
||||||
|
return (
|
||||||
|
<Badge className="bg-muted text-foreground">Não Compareceu</Badge>
|
||||||
|
);
|
||||||
|
default:
|
||||||
|
return <Badge variant="secondary">{status}</Badge>;
|
||||||
|
}
|
||||||
|
};
|
||||||
@ -1,6 +1,9 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { Card, CardContent, CardDescription,
|
import {
|
||||||
|
Card,
|
||||||
|
CardContent,
|
||||||
|
CardDescription,
|
||||||
CardHeader,
|
CardHeader,
|
||||||
CardTitle,
|
CardTitle,
|
||||||
} from "@/components/ui/card";
|
} from "@/components/ui/card";
|
||||||
@ -101,8 +104,10 @@ export default function SecretaryDashboard() {
|
|||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
{/* Cabeçalho */}
|
{/* Cabeçalho */}
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
|
<h1 className="text-3xl font-bold">Dashboard</h1>
|
||||||
<p className="text-gray-600">Bem-vindo ao seu portal de consultas médicas</p>
|
<p className="text-muted-foreground">
|
||||||
|
Bem-vindo ao seu portal de consultas médicas
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Cards principais */}
|
{/* Cards principais */}
|
||||||
@ -117,7 +122,7 @@ export default function SecretaryDashboard() {
|
|||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
{loadingAppointments ? (
|
{loadingAppointments ? (
|
||||||
<div className="text-gray-500 text-sm">
|
<div className="text-muted-foreground text-sm">
|
||||||
Carregando próxima consulta...
|
Carregando próxima consulta...
|
||||||
</div>
|
</div>
|
||||||
) : firstConfirmed ? (
|
) : firstConfirmed ? (
|
||||||
@ -132,16 +137,17 @@ export default function SecretaryDashboard() {
|
|||||||
? `Dr(a). ${firstConfirmed.doctor_name}`
|
? `Dr(a). ${firstConfirmed.doctor_name}`
|
||||||
: "Médico não informado"}{" "}
|
: "Médico não informado"}{" "}
|
||||||
-{" "}
|
-{" "}
|
||||||
{new Date(
|
{new Date(firstConfirmed.scheduled_at).toLocaleTimeString(
|
||||||
firstConfirmed.scheduled_at
|
"pt-BR",
|
||||||
).toLocaleTimeString("pt-BR", {
|
{
|
||||||
hour: "2-digit",
|
hour: "2-digit",
|
||||||
minute: "2-digit",
|
minute: "2-digit",
|
||||||
})}
|
}
|
||||||
|
)}
|
||||||
</p>
|
</p>
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<div className="text-sm text-gray-500">
|
<div className="text-sm text-muted-foreground">
|
||||||
Nenhuma consulta confirmada encontrada
|
Nenhuma consulta confirmada encontrada
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@ -158,26 +164,28 @@ export default function SecretaryDashboard() {
|
|||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
{loadingAppointments ? (
|
{loadingAppointments ? (
|
||||||
<div className="text-gray-500 text-sm">
|
<div className="text-muted-foreground text-sm">
|
||||||
Carregando consultas...
|
Carregando consultas...
|
||||||
</div>
|
</div>
|
||||||
) : nextAgendada ? (
|
) : nextAgendada ? (
|
||||||
<>
|
<>
|
||||||
<div className="text-lg font-bold text-gray-900">
|
<div className="text-lg font-bold">
|
||||||
{new Date(
|
{new Date(nextAgendada.scheduled_at).toLocaleDateString(
|
||||||
nextAgendada.scheduled_at
|
"pt-BR",
|
||||||
).toLocaleDateString("pt-BR", {
|
{
|
||||||
day: "2-digit",
|
day: "2-digit",
|
||||||
month: "2-digit",
|
month: "2-digit",
|
||||||
year: "numeric",
|
year: "numeric",
|
||||||
})}{" "}
|
}
|
||||||
|
)}{" "}
|
||||||
às{" "}
|
às{" "}
|
||||||
{new Date(
|
{new Date(nextAgendada.scheduled_at).toLocaleTimeString(
|
||||||
nextAgendada.scheduled_at
|
"pt-BR",
|
||||||
).toLocaleTimeString("pt-BR", {
|
{
|
||||||
hour: "2-digit",
|
hour: "2-digit",
|
||||||
minute: "2-digit",
|
minute: "2-digit",
|
||||||
})}
|
}
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-muted-foreground">
|
<p className="text-xs text-muted-foreground">
|
||||||
{nextAgendada.doctor_name
|
{nextAgendada.doctor_name
|
||||||
@ -191,7 +199,7 @@ export default function SecretaryDashboard() {
|
|||||||
</p>
|
</p>
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<div className="text-sm text-gray-500">
|
<div className="text-sm text-muted-foreground">
|
||||||
Nenhuma consulta agendada neste mês
|
Nenhuma consulta agendada neste mês
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@ -223,8 +231,8 @@ export default function SecretaryDashboard() {
|
|||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-4">
|
<CardContent className="space-y-4">
|
||||||
<Link href="/secretary/schedule">
|
<Link href="/secretary/schedule">
|
||||||
<Button className="w-full justify-start">
|
<Button className="w-full justify-start bg-primary text-primary-foreground hover:bg-primary/90">
|
||||||
<Plus className="mr-2 h-4 w-4" />
|
<User className="mr-2 h-4 w-4" />
|
||||||
Agendar Nova Consulta
|
Agendar Nova Consulta
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
@ -253,17 +261,13 @@ export default function SecretaryDashboard() {
|
|||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Pacientes</CardTitle>
|
<CardTitle>Pacientes</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>Últimos pacientes cadastrados</CardDescription>
|
||||||
Últimos pacientes cadastrados
|
|
||||||
</CardDescription>
|
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
{loadingPatients ? (
|
{loadingPatients ? (
|
||||||
<p className="text-sm text-gray-500">
|
<p className="text-sm text-muted-foreground">Carregando pacientes...</p>
|
||||||
Carregando pacientes...
|
|
||||||
</p>
|
|
||||||
) : patients.length === 0 ? (
|
) : patients.length === 0 ? (
|
||||||
<p className="text-sm text-gray-500">
|
<p className="text-sm text-muted-foreground">
|
||||||
Nenhum paciente cadastrado.
|
Nenhum paciente cadastrado.
|
||||||
</p>
|
</p>
|
||||||
) : (
|
) : (
|
||||||
@ -271,20 +275,20 @@ export default function SecretaryDashboard() {
|
|||||||
{patients.map((patient, index) => (
|
{patients.map((patient, index) => (
|
||||||
<div
|
<div
|
||||||
key={index}
|
key={index}
|
||||||
className="flex items-center justify-between p-3 bg-blue-50 rounded-lg border border-blue-100"
|
className="flex items-center justify-between p-3 bg-primary/10 rounded-lg border border-primary/20"
|
||||||
>
|
>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-medium text-gray-900">
|
<p className="font-medium text-foreground">
|
||||||
{patient.full_name || "Sem nome"}
|
{patient.full_name || "Sem nome"}
|
||||||
</p>
|
</p>
|
||||||
<p className="text-sm text-gray-600">
|
<p className="text-sm text-muted-foreground">
|
||||||
{patient.phone_mobile ||
|
{patient.phone_mobile ||
|
||||||
patient.phone1 ||
|
patient.phone1 ||
|
||||||
"Sem telefone"}
|
"Sem telefone"}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-right">
|
<div className="text-right">
|
||||||
<p className="font-medium text-blue-700">
|
<p className="font-medium text-primary">
|
||||||
{patient.convenio || "Particular"}
|
{patient.convenio || "Particular"}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -265,7 +265,7 @@ export default function EditarPacientePage() {
|
|||||||
return (
|
return (
|
||||||
<Sidebar>
|
<Sidebar>
|
||||||
{/* O espaçamento foi reduzido aqui: de `p-4 sm:p-6 lg:p-8` para `p-2 sm:p-4 lg:p-6` */}
|
{/* O espaçamento foi reduzido aqui: de `p-4 sm:p-6 lg:p-8` para `p-2 sm:p-4 lg:p-6` */}
|
||||||
<div className="space-y-6 p-2 sm:p-4 lg:p-6 max-w-10xl mx-auto"> {/* Alterado padding responsivo */}
|
<div className="space-y-6 p-2 sm:p-4 lg:p-6 max-w-10xl mx-auto">{/* Alterado padding responsivo */}
|
||||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
|
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex items-center gap-4">
|
||||||
<Link href="/secretary/pacientes">
|
<Link href="/secretary/pacientes">
|
||||||
@ -275,31 +275,29 @@ export default function EditarPacientePage() {
|
|||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-gray-900">Editar Paciente</h1>
|
<h1 className="text-2xl font-bold">Editar Paciente</h1>
|
||||||
<p className="text-gray-600">Atualize as informações do paciente</p>
|
<p className="text-muted-foreground">Atualize as informações do paciente</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{/* Espaço reservado para anexos ou ações futuras */}
|
||||||
{/* Anexos Section - Movido para fora do cabeçalho para melhor organização e responsividade */}
|
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<form onSubmit={handleSubmit} className="space-y-8">
|
<form onSubmit={handleSubmit} className="space-y-8">
|
||||||
{/* Dados Pessoais Section */}
|
{/* Dados Pessoais Section */}
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
<div className="bg-card rounded-lg border p-6">
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Dados Pessoais</h2>
|
<h2 className="text-lg font-semibold mb-6">Dados Pessoais</h2>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||||
{/* Photo upload */}
|
{/* Photo upload */}
|
||||||
<div className="space-y-2 col-span-1 md:col-span-2 lg:col-span-1">
|
<div className="space-y-2 col-span-1 md:col-span-2 lg:col-span-1">
|
||||||
<Label>Foto do paciente</Label>
|
<Label>Foto do paciente</Label>
|
||||||
<div className="flex flex-col sm:flex-row items-center gap-4">
|
<div className="flex flex-col sm:flex-row items-center gap-4">
|
||||||
<div className="w-20 h-20 rounded-full bg-gray-100 overflow-hidden flex items-center justify-center">
|
<div className="w-20 h-20 rounded-full bg-muted overflow-hidden flex items-center justify-center">
|
||||||
{photoUrl ? (
|
{photoUrl ? (
|
||||||
// eslint-disable-next-line @next/next/no-img-element
|
// eslint-disable-next-line @next/next/no-img-element
|
||||||
<img src={photoUrl} alt="Foto do paciente" className="w-full h-full object-cover" />
|
<img src={photoUrl} alt="Foto do paciente" className="w-full h-full object-cover" />
|
||||||
) : (
|
) : (
|
||||||
<span className="text-gray-400 text-sm text-center">Sem foto</span>
|
<span className="text-muted-foreground text-sm text-center">Sem foto</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col sm:flex-row gap-2 mt-2 sm:mt-0">
|
<div className="flex flex-col sm:flex-row gap-2 mt-2 sm:mt-0">
|
||||||
@ -334,11 +332,11 @@ export default function EditarPacientePage() {
|
|||||||
<Label>Sexo *</Label>
|
<Label>Sexo *</Label>
|
||||||
<div className="flex flex-col sm:flex-row gap-4">
|
<div className="flex flex-col sm:flex-row gap-4">
|
||||||
<div className="flex items-center space-x-2">
|
<div className="flex items-center space-x-2">
|
||||||
<input type="radio" id="Masculino" name="sexo" value="Masculino" checked={formData.sexo === "Masculino"} onChange={(e) => handleInputChange("sexo", e.target.value)} className="w-4 h-4 text-blue-600" />
|
<input type="radio" id="Masculino" name="sexo" value="Masculino" checked={formData.sexo === "Masculino"} onChange={(e) => handleInputChange("sexo", e.target.value)} className="w-4 h-4 text-primary" />
|
||||||
<Label htmlFor="Masculino">Masculino</Label>
|
<Label htmlFor="Masculino">Masculino</Label>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center space-x-2">
|
<div className="flex items-center space-x-2">
|
||||||
<input type="radio" id="Feminino" name="sexo" value="Feminino" checked={formData.sexo === "Feminino"} onChange={(e) => handleInputChange("sexo", e.target.value)} className="w-4 h-4 text-blue-600" />
|
<input type="radio" id="Feminino" name="sexo" value="Feminino" checked={formData.sexo === "Feminino"} onChange={(e) => handleInputChange("sexo", e.target.value)} className="w-4 h-4 text-primary" />
|
||||||
<Label htmlFor="Feminino">Feminino</Label>
|
<Label htmlFor="Feminino">Feminino</Label>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -467,8 +465,8 @@ export default function EditarPacientePage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Contact Section */}
|
{/* Contact Section */}
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
<div className="bg-card rounded-lg border p-6">
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Contato</h2>
|
<h2 className="text-lg font-semibold mb-6">Contato</h2>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
@ -494,8 +492,8 @@ export default function EditarPacientePage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Address Section */}
|
{/* Address Section */}
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
<div className="bg-card rounded-lg border p-6">
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Endereço</h2>
|
<h2 className="text-lg font-semibold mb-6">Endereço</h2>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
@ -569,8 +567,8 @@ export default function EditarPacientePage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Medical Information Section */}
|
{/* Medical Information Section */}
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
<div className="bg-card rounded-lg border p-6">
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Informações Médicas</h2>
|
<h2 className="text-lg font-semibold mb-6">Informações Médicas</h2>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
@ -615,8 +613,8 @@ export default function EditarPacientePage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Insurance Information Section */}
|
{/* Insurance Information Section */}
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
<div className="bg-card rounded-lg border p-6">
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Informações de convênio</h2>
|
<h2 className="text-lg font-semibold mb-6">Informações de convênio</h2>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
@ -665,7 +663,7 @@ export default function EditarPacientePage() {
|
|||||||
Cancelar
|
Cancelar
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
<Button type="submit" className="bg-blue-600 hover:bg-blue-700 w-full sm:w-auto">
|
<Button type="submit" className="bg-primary hover:bg-primary/90 w-full sm:w-auto">
|
||||||
<Save className="w-4 h-4 mr-2" />
|
<Save className="w-4 h-4 mr-2" />
|
||||||
Salvar Alterações
|
Salvar Alterações
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@ -85,7 +85,7 @@ export default function NovoUsuarioPage() {
|
|||||||
router.push("/manager/usuario");
|
router.push("/manager/usuario");
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
console.error("Erro ao criar usuário:", e);
|
console.error("Erro ao criar usuário:", e);
|
||||||
setError(e?.message || "Não foi possível criar o usuário. Verifique os dados e tente novamente.");
|
setError(e?.message || "Não foi possível criar o paciente. Verifique os dados e tente novamente.");
|
||||||
} finally {
|
} finally {
|
||||||
setIsSaving(false);
|
setIsSaving(false);
|
||||||
}
|
}
|
||||||
@ -100,10 +100,10 @@ export default function NovoUsuarioPage() {
|
|||||||
{/* Cabeçalho da página */}
|
{/* Cabeçalho da página */}
|
||||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between border-b pb-4 gap-4"> {/* Ajustado para empilhar em telas pequenas */}
|
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between border-b pb-4 gap-4"> {/* Ajustado para empilhar em telas pequenas */}
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl sm:text-3xl font-extrabold text-gray-900">Novo Usuário</h1> {/* Tamanho de texto responsivo */}
|
<h1 className="text-2xl sm:text-3xl font-extrabold text-gray-900">Novo Paciente</h1> {/* Tamanho de texto responsivo */}
|
||||||
<p className="text-sm sm:text-md text-gray-500">Preencha os dados para cadastrar um novo usuário no sistema.</p> {/* Tamanho de texto responsivo */}
|
<p className="text-sm sm:text-md text-gray-500">Preencha os dados para cadastrar um novo paciente no sistema.</p> {/* Tamanho de texto responsivo */}
|
||||||
</div>
|
</div>
|
||||||
<Link href="/manager/usuario">
|
<Link href="/secretary/pacientes">
|
||||||
<Button variant="outline" className="w-full sm:w-auto">Cancelar</Button> {/* Botão ocupa largura total em telas pequenas */}
|
<Button variant="outline" className="w-full sm:w-auto">Cancelar</Button> {/* Botão ocupa largura total em telas pequenas */}
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
@ -153,15 +153,19 @@ export default function NovoUsuarioPage() {
|
|||||||
|
|
||||||
{/* Botões de ação */}
|
{/* Botões de ação */}
|
||||||
<div className="flex flex-col sm:flex-row justify-end gap-4 pt-6 border-t mt-6"> {/* Botões empilhados em telas pequenas */}
|
<div className="flex flex-col sm:flex-row justify-end gap-4 pt-6 border-t mt-6"> {/* Botões empilhados em telas pequenas */}
|
||||||
<Link href="/manager/usuario">
|
<Link href="/secretary/pacientes">
|
||||||
<Button type="button" variant="outline" disabled={isSaving} className="w-full sm:w-auto">
|
<Button type="button" variant="outline" disabled={isSaving} className="w-full sm:w-auto">
|
||||||
Cancelar
|
Cancelar
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
|
<Link href="/secretary/pacientes">
|
||||||
<Button type="submit" className="bg-green-600 hover:bg-green-700 w-full sm:w-auto" disabled={isSaving}>
|
<Button type="submit" className="bg-green-600 hover:bg-green-700 w-full sm:w-auto" disabled={isSaving}>
|
||||||
|
|
||||||
{isSaving ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Save className="w-4 h-4 mr-2" />}
|
{isSaving ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Save className="w-4 h-4 mr-2" />}
|
||||||
{isSaving ? "Salvando..." : "Salvar Usuário"}
|
{isSaving ? "Salvando..." : "Salvar Paciente"}
|
||||||
|
|
||||||
</Button>
|
</Button>
|
||||||
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -6,7 +6,7 @@ import Link from "next/link";
|
|||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
import { Plus, Edit, Trash2, Eye, Calendar, Filter, Loader2 } from "lucide-react";
|
import { Plus, Edit, Trash2, Eye, Calendar, Filter, Loader2, MoreVertical } from "lucide-react";
|
||||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||||
import { patientsService } from "@/services/patientsApi.mjs";
|
import { patientsService } from "@/services/patientsApi.mjs";
|
||||||
import Sidebar from "@/components/Sidebar";
|
import Sidebar from "@/components/Sidebar";
|
||||||
@ -76,9 +76,7 @@ export default function PacientesPage() {
|
|||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
},
|
}, []);
|
||||||
[]
|
|
||||||
);
|
|
||||||
|
|
||||||
// 2. Efeito para aplicar filtros e calcular a lista filtrada (chama-se quando allPatients ou filtros mudam)
|
// 2. Efeito para aplicar filtros e calcular a lista filtrada (chama-se quando allPatients ou filtros mudam)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@ -113,7 +111,6 @@ export default function PacientesPage() {
|
|||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
|
||||||
// --- LÓGICA DE AÇÕES (DELETAR / VER DETALHES) ---
|
// --- LÓGICA DE AÇÕES (DELETAR / VER DETALHES) ---
|
||||||
|
|
||||||
const openDetailsDialog = async (patientId: string) => {
|
const openDetailsDialog = async (patientId: string) => {
|
||||||
@ -131,9 +128,11 @@ export default function PacientesPage() {
|
|||||||
try {
|
try {
|
||||||
await patientsService.delete(patientId);
|
await patientsService.delete(patientId);
|
||||||
// Atualiza a lista completa para refletir a exclusão
|
// Atualiza a lista completa para refletir a exclusão
|
||||||
setAllPatients((prev) => prev.filter((p) => String(p.id) !== String(patientId)));
|
setAllPatients((prev) =>
|
||||||
|
prev.filter((p) => String(p.id) !== String(patientId))
|
||||||
|
);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
alert(`Erro ao deletar paciente: ${e?.message || 'Erro desconhecido'}`);
|
alert(`Erro ao deletar paciente: ${e?.message || "Erro desconhecido"}`);
|
||||||
}
|
}
|
||||||
setDeleteDialogOpen(false);
|
setDeleteDialogOpen(false);
|
||||||
setPatientToDelete(null);
|
setPatientToDelete(null);
|
||||||
@ -150,12 +149,16 @@ export default function PacientesPage() {
|
|||||||
{/* Header (Responsividade OK) */}
|
{/* Header (Responsividade OK) */}
|
||||||
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-xl md:text-2xl font-bold text-foreground">Pacientes</h1>
|
<h1 className="text-xl md:text-2xl font-bold">
|
||||||
<p className="text-muted-foreground text-sm md:text-base">Gerencie as informações de seus pacientes</p>
|
Pacientes
|
||||||
|
</h1>
|
||||||
|
<p className="text-muted-foreground text-sm md:text-base">
|
||||||
|
Gerencie as informações de seus pacientes
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<Link href="/secretary/pacientes/novo" className="w-full md:w-auto">
|
<Link href="/secretary/pacientes/novo" className="w-full md:w-auto">
|
||||||
<Button className="w-full bg-green-600 hover:bg-green-700">
|
<Button className="w-full bg-primary hover:bg-primary/90">
|
||||||
<Plus className="w-4 h-4 mr-2" />
|
<Plus className="w-4 h-4 mr-2" />
|
||||||
Adicionar
|
Adicionar
|
||||||
</Button>
|
</Button>
|
||||||
@ -164,8 +167,8 @@ export default function PacientesPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Bloco de Filtros (Responsividade APLICADA) */}
|
{/* Bloco de Filtros (Responsividade APLICADA) */}
|
||||||
<div className="flex flex-wrap items-center gap-4 bg-card p-4 rounded-lg border border-border">
|
<div className="flex flex-wrap items-center gap-4 bg-card p-4 rounded-lg border">
|
||||||
<Filter className="w-5 h-5 text-gray-400" />
|
<Filter className="w-5 h-5 text-muted-foreground" />
|
||||||
|
|
||||||
{/* Busca - Ocupa 100% no mobile, depois cresce */}
|
{/* Busca - Ocupa 100% no mobile, depois cresce */}
|
||||||
<input
|
<input
|
||||||
@ -173,15 +176,18 @@ export default function PacientesPage() {
|
|||||||
placeholder="Buscar por nome ou telefone..."
|
placeholder="Buscar por nome ou telefone..."
|
||||||
value={searchTerm}
|
value={searchTerm}
|
||||||
onChange={(e) => setSearchTerm(e.target.value)}
|
onChange={(e) => setSearchTerm(e.target.value)}
|
||||||
// w-full no mobile, depois flex-grow para ocupar o espaço disponível
|
className="w-full sm:flex-grow sm:min-w-[150px] p-2 border rounded-md text-sm"
|
||||||
className="w-full sm:flex-grow sm:max-w-[300px] p-2 border rounded-md text-sm"
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Convênio - Ocupa a largura total em telas pequenas, depois se ajusta */}
|
{/* Convênio - Ocupa a largura total em telas pequenas, depois se ajusta */}
|
||||||
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[200px]">
|
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[200px]">
|
||||||
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">Convênio</span>
|
<span className="text-sm font-medium whitespace-nowrap hidden md:block">
|
||||||
|
Convênio
|
||||||
|
</span>
|
||||||
<Select value={convenioFilter} onValueChange={setConvenioFilter}>
|
<Select value={convenioFilter} onValueChange={setConvenioFilter}>
|
||||||
<SelectTrigger className="w-full sm:w-40"> {/* w-full para mobile, w-40 para sm+ */}
|
<SelectTrigger className="w-full sm:w-40">
|
||||||
|
{" "}
|
||||||
|
{/* w-full para mobile, w-40 para sm+ */}
|
||||||
<SelectValue placeholder="Convênio" />
|
<SelectValue placeholder="Convênio" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
@ -196,7 +202,7 @@ export default function PacientesPage() {
|
|||||||
|
|
||||||
{/* VIP - Ocupa a largura total em telas pequenas, depois se ajusta */}
|
{/* VIP - Ocupa a largura total em telas pequenas, depois se ajusta */}
|
||||||
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[150px]">
|
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[150px]">
|
||||||
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">VIP</span>
|
<span className="text-sm font-medium whitespace-nowrap hidden md:block">VIP</span>
|
||||||
<Select value={vipFilter} onValueChange={setVipFilter}>
|
<Select value={vipFilter} onValueChange={setVipFilter}>
|
||||||
<SelectTrigger className="w-full sm:w-32"> {/* w-full para mobile, w-32 para sm+ */}
|
<SelectTrigger className="w-full sm:w-32"> {/* w-full para mobile, w-32 para sm+ */}
|
||||||
<SelectValue placeholder="VIP" />
|
<SelectValue placeholder="VIP" />
|
||||||
@ -209,79 +215,123 @@ export default function PacientesPage() {
|
|||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Aniversariantes - Ocupa 100% no mobile, e se alinha à direita no md+ */}
|
|
||||||
<Button variant="outline" className="w-full md:w-auto md:ml-auto">
|
|
||||||
<Calendar className="w-4 h-4 mr-2" />
|
|
||||||
Aniversariantes
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* --- SEÇÃO DE TABELA (VISÍVEL EM TELAS MAIORES OU IGUAIS A MD) --- */}
|
{/* --- SEÇÃO DE TABELA (VISÍVEL EM TELAS MAIORES OU IGUAIS A MD) --- */}
|
||||||
{/* Garantir que a tabela se esconda em telas menores e apareça em MD+ */}
|
{/* Garantir que a tabela se esconda em telas menores e apareça em MD+ */}
|
||||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md hidden md:block">
|
<div className="bg-card rounded-lg border shadow-md hidden md:block">
|
||||||
<div className="overflow-x-auto"> {/* Permite rolagem horizontal se a tabela for muito larga */}
|
<div className="overflow-x-auto">
|
||||||
|
{" "}
|
||||||
|
{/* Permite rolagem horizontal se a tabela for muito larga */}
|
||||||
{error ? (
|
{error ? (
|
||||||
<div className="p-6 text-red-600">{`Erro ao carregar pacientes: ${error}`}</div>
|
<div className="p-6 text-destructive">{`Erro ao carregar pacientes: ${error}`}</div>
|
||||||
) : loading ? (
|
) : loading ? (
|
||||||
<div className="p-6 text-center text-gray-500 flex items-center justify-center">
|
<div className="p-6 text-center text-muted-foreground flex items-center justify-center">
|
||||||
<Loader2 className="w-6 h-6 mr-2 animate-spin text-green-600" /> Carregando pacientes...
|
<Loader2 className="w-6 h-6 mr-2 animate-spin text-primary" />{" "}
|
||||||
|
Carregando pacientes...
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<table className="w-full min-w-[650px]"> {/* min-w para evitar que a tabela se contraia demais */}
|
<table className="w-full min-w-[650px]">
|
||||||
<thead className="bg-gray-50 border-b border-gray-200">
|
{" "}
|
||||||
|
{/* min-w para evitar que a tabela se contraia demais */}
|
||||||
|
<thead className="bg-muted border-b">
|
||||||
<tr>
|
<tr>
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[20%]">Nome</th>
|
<th className="text-left p-4 font-medium text-muted-foreground w-[20%]">
|
||||||
|
Nome
|
||||||
|
</th>
|
||||||
{/* Ajustes de visibilidade de colunas para diferentes breakpoints */}
|
{/* Ajustes de visibilidade de colunas para diferentes breakpoints */}
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">Telefone</th>
|
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden sm:table-cell">
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden md:table-cell">Cidade / Estado</th>
|
Telefone
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">Convênio</th>
|
</th>
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">Último atendimento</th>
|
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden md:table-cell">
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">Próximo atendimento</th>
|
Cidade / Estado
|
||||||
<th className="text-left p-4 font-medium text-gray-700 w-[5%]">Ações</th>
|
</th>
|
||||||
|
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden sm:table-cell">
|
||||||
|
Convênio
|
||||||
|
</th>
|
||||||
|
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden lg:table-cell">
|
||||||
|
Último atendimento
|
||||||
|
</th>
|
||||||
|
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden lg:table-cell">
|
||||||
|
Próximo atendimento
|
||||||
|
</th>
|
||||||
|
<th className="text-left p-4 font-medium text-muted-foreground w-[5%]">
|
||||||
|
Ações
|
||||||
|
</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{currentPatients.length === 0 ? (
|
{currentPatients.length === 0 ? (
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan={7} className="p-8 text-center text-gray-500">
|
<td colSpan={7} className="p-8 text-center text-muted-foreground">
|
||||||
{allPatients.length === 0 ? "Nenhum paciente cadastrado" : "Nenhum paciente encontrado com os filtros aplicados"}
|
{allPatients.length === 0
|
||||||
|
? "Nenhum paciente cadastrado"
|
||||||
|
: "Nenhum paciente encontrado com os filtros aplicados"}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
) : (
|
) : (
|
||||||
currentPatients.map((patient) => (
|
currentPatients.map((patient) => (
|
||||||
<tr key={patient.id} className="border-b border-gray-100 hover:bg-gray-50">
|
<tr
|
||||||
|
key={patient.id}
|
||||||
|
className="border-b hover:bg-muted"
|
||||||
|
>
|
||||||
<td className="p-4">
|
<td className="p-4">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<div className="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
|
<div className="w-8 h-8 bg-primary/10 rounded-full flex items-center justify-center">
|
||||||
<span className="text-green-600 font-medium text-sm">{patient.nome?.charAt(0) || "?"}</span>
|
<span className="text-primary font-medium text-sm">
|
||||||
|
{patient.nome?.charAt(0) || "?"}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<span className="font-medium text-gray-900">
|
|
||||||
|
<span className="font-medium">
|
||||||
{patient.nome}
|
{patient.nome}
|
||||||
{patient.vip && (
|
{patient.vip && (
|
||||||
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-600 bg-purple-100 rounded-full">VIP</span>
|
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-500 bg-purple-500/10 rounded-full">
|
||||||
|
VIP
|
||||||
|
</span>
|
||||||
)}
|
)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td className="p-4 text-gray-600 hidden sm:table-cell">{patient.telefone}</td>
|
<td className="p-4 text-muted-foreground hidden sm:table-cell">
|
||||||
<td className="p-4 text-gray-600 hidden md:table-cell">{`${patient.cidade} / ${patient.estado}`}</td>
|
{patient.telefone}
|
||||||
<td className="p-4 text-gray-600 hidden sm:table-cell">{patient.convenio}</td>
|
</td>
|
||||||
<td className="p-4 text-gray-600 hidden lg:table-cell">{patient.ultimoAtendimento}</td>
|
<td className="p-4 text-muted-foreground hidden md:table-cell">{`${patient.cidade} / ${patient.estado}`}</td>
|
||||||
<td className="p-4 text-gray-600 hidden lg:table-cell">{patient.proximoAtendimento}</td>
|
<td className="p-4 text-muted-foreground hidden sm:table-cell">
|
||||||
|
{patient.convenio}
|
||||||
|
</td>
|
||||||
|
<td className="p-4 text-muted-foreground hidden lg:table-cell">
|
||||||
|
{patient.ultimoAtendimento}
|
||||||
|
</td>
|
||||||
|
<td className="p-4 text-muted-foreground hidden lg:table-cell">
|
||||||
|
{patient.proximoAtendimento}
|
||||||
|
</td>
|
||||||
|
|
||||||
<td className="p-4">
|
<td className="p-4">
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<div className="text-blue-600 cursor-pointer">Ações</div>
|
<Button variant="ghost" className="h-8 w-8 p-0">
|
||||||
|
<span className="sr-only">Abrir menu</span>
|
||||||
|
<MoreVertical className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
<DropdownMenuItem onClick={() => openDetailsDialog(String(patient.id))}>
|
<DropdownMenuItem
|
||||||
|
onClick={() =>
|
||||||
|
openDetailsDialog(String(patient.id))
|
||||||
|
}
|
||||||
|
>
|
||||||
<Eye className="w-4 h-4 mr-2" />
|
<Eye className="w-4 h-4 mr-2" />
|
||||||
Ver detalhes
|
Ver detalhes
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
|
||||||
<DropdownMenuItem asChild>
|
<DropdownMenuItem asChild>
|
||||||
<Link href={`/secretary/pacientes/${patient.id}/editar`} className="flex items-center w-full">
|
<Link
|
||||||
|
href={`/secretary/pacientes/${patient.id}/editar`}
|
||||||
|
className="flex items-center w-full"
|
||||||
|
>
|
||||||
<Edit className="w-4 h-4 mr-2" />
|
<Edit className="w-4 h-4 mr-2" />
|
||||||
Editar
|
Editar
|
||||||
</Link>
|
</Link>
|
||||||
@ -291,7 +341,12 @@ export default function PacientesPage() {
|
|||||||
<Calendar className="w-4 h-4 mr-2" />
|
<Calendar className="w-4 h-4 mr-2" />
|
||||||
Marcar consulta
|
Marcar consulta
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(String(patient.id))}>
|
<DropdownMenuItem
|
||||||
|
className="text-destructive"
|
||||||
|
onClick={() =>
|
||||||
|
openDeleteDialog(String(patient.id))
|
||||||
|
}
|
||||||
|
>
|
||||||
<Trash2 className="w-4 h-4 mr-2" />
|
<Trash2 className="w-4 h-4 mr-2" />
|
||||||
Excluir
|
Excluir
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
@ -309,37 +364,55 @@ export default function PacientesPage() {
|
|||||||
|
|
||||||
{/* --- SEÇÃO DE CARDS (VISÍVEL APENAS EM TELAS MENORES QUE MD) --- */}
|
{/* --- SEÇÃO DE CARDS (VISÍVEL APENAS EM TELAS MENORES QUE MD) --- */}
|
||||||
{/* Garantir que os cards apareçam em telas menores e se escondam em MD+ */}
|
{/* Garantir que os cards apareçam em telas menores e se escondam em MD+ */}
|
||||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md p-4 block md:hidden">
|
<div className="bg-card rounded-lg border shadow-md p-4 block md:hidden">
|
||||||
{error ? (
|
{error ? (
|
||||||
<div className="p-6 text-red-600">{`Erro ao carregar pacientes: ${error}`}</div>
|
<div className="p-6 text-destructive">{`Erro ao carregar pacientes: ${error}`}</div>
|
||||||
) : loading ? (
|
) : loading ? (
|
||||||
<div className="p-6 text-center text-gray-500 flex items-center justify-center">
|
<div className="p-6 text-center text-muted-foreground flex items-center justify-center">
|
||||||
<Loader2 className="w-6 h-6 mr-2 animate-spin text-green-600" /> Carregando pacientes...
|
<Loader2 className="w-6 h-6 mr-2 animate-spin text-primary" />{" "}
|
||||||
|
Carregando pacientes...
|
||||||
</div>
|
</div>
|
||||||
) : filteredPatients.length === 0 ? (
|
) : filteredPatients.length === 0 ? (
|
||||||
<div className="p-8 text-center text-gray-500">
|
<div className="p-8 text-center text-muted-foreground">
|
||||||
{allPatients.length === 0 ? "Nenhum paciente cadastrado" : "Nenhum paciente encontrado com os filtros aplicados"}
|
{allPatients.length === 0
|
||||||
|
? "Nenhum paciente cadastrado"
|
||||||
|
: "Nenhum paciente encontrado com os filtros aplicados"}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
{currentPatients.map((patient) => (
|
{currentPatients.map((patient) => (
|
||||||
<div key={patient.id} className="bg-gray-50 rounded-lg p-4 flex flex-col sm:flex-row justify-between items-start sm:items-center border border-gray-200">
|
<div
|
||||||
|
key={patient.id}
|
||||||
|
className="bg-muted rounded-lg p-4 flex flex-col sm:flex-row justify-between items-start sm:items-center border"
|
||||||
|
>
|
||||||
<div className="flex-grow mb-2 sm:mb-0">
|
<div className="flex-grow mb-2 sm:mb-0">
|
||||||
<div className="font-semibold text-lg text-gray-900 flex items-center">
|
<div className="font-semibold text-lg flex items-center">
|
||||||
{patient.nome}
|
{patient.nome}
|
||||||
{patient.vip && (
|
{patient.vip && (
|
||||||
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-600 bg-purple-100 rounded-full">VIP</span>
|
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-500 bg-purple-500/10 rounded-full">
|
||||||
|
VIP
|
||||||
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-sm text-gray-600">Telefone: {patient.telefone}</div>
|
<div className="text-sm text-muted-foreground">
|
||||||
<div className="text-sm text-gray-600">Convênio: {patient.convenio}</div>
|
Telefone: {patient.telefone}
|
||||||
|
</div>
|
||||||
|
<div className="text-sm text-muted-foreground">
|
||||||
|
Convênio: {patient.convenio}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<div className="w-full"><Button variant="outline" className="w-full">Ações</Button></div>
|
<div className="w-full">
|
||||||
|
<Button variant="outline" className="w-full">
|
||||||
|
Ações
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
<DropdownMenuItem onClick={() => openDetailsDialog(String(patient.id))}>
|
<DropdownMenuItem
|
||||||
|
onClick={() => openDetailsDialog(String(patient.id))}
|
||||||
|
>
|
||||||
<Eye className="w-4 h-4 mr-2" />
|
<Eye className="w-4 h-4 mr-2" />
|
||||||
Ver detalhes
|
Ver detalhes
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
@ -355,7 +428,7 @@ export default function PacientesPage() {
|
|||||||
<Calendar className="w-4 h-4 mr-2" />
|
<Calendar className="w-4 h-4 mr-2" />
|
||||||
Marcar consulta
|
Marcar consulta
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(String(patient.id))}>
|
<DropdownMenuItem className="text-destructive" onClick={() => openDeleteDialog(String(patient.id))}>
|
||||||
<Trash2 className="w-4 h-4 mr-2" />
|
<Trash2 className="w-4 h-4 mr-2" />
|
||||||
Excluir
|
Excluir
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
@ -369,7 +442,7 @@ export default function PacientesPage() {
|
|||||||
|
|
||||||
{/* Paginação */}
|
{/* Paginação */}
|
||||||
{totalPages > 1 && !loading && (
|
{totalPages > 1 && !loading && (
|
||||||
<div className="flex flex-col sm:flex-row items-center justify-center p-4 border-t border-gray-200">
|
<div className="flex flex-col sm:flex-row items-center justify-center p-4 border-t">
|
||||||
<div className="flex space-x-2 flex-wrap justify-center"> {/* Adicionado flex-wrap e justify-center para botões da paginação */}
|
<div className="flex space-x-2 flex-wrap justify-center"> {/* Adicionado flex-wrap e justify-center para botões da paginação */}
|
||||||
<Button
|
<Button
|
||||||
onClick={() => setPage((prev) => Math.max(1, prev - 1))}
|
onClick={() => setPage((prev) => Math.max(1, prev - 1))}
|
||||||
@ -388,7 +461,7 @@ export default function PacientesPage() {
|
|||||||
onClick={() => setPage(pageNumber)}
|
onClick={() => setPage(pageNumber)}
|
||||||
variant={pageNumber === page ? "default" : "outline"}
|
variant={pageNumber === page ? "default" : "outline"}
|
||||||
size="lg"
|
size="lg"
|
||||||
className={pageNumber === page ? "bg-green-600 hover:bg-green-700 text-white" : "text-gray-700"}
|
className={pageNumber === page ? "bg-primary hover:bg-primary/90 text-primary-foreground" : "text-muted-foreground"}
|
||||||
>
|
>
|
||||||
{pageNumber}
|
{pageNumber}
|
||||||
</Button>
|
</Button>
|
||||||
@ -415,25 +488,28 @@ export default function PacientesPage() {
|
|||||||
</AlertDialogHeader>
|
</AlertDialogHeader>
|
||||||
<AlertDialogFooter>
|
<AlertDialogFooter>
|
||||||
<AlertDialogCancel>Cancelar</AlertDialogCancel>
|
<AlertDialogCancel>Cancelar</AlertDialogCancel>
|
||||||
<AlertDialogAction onClick={() => patientToDelete && handleDeletePatient(patientToDelete)} className="bg-red-600 hover:bg-red-700">
|
<AlertDialogAction onClick={() => patientToDelete && handleDeletePatient(patientToDelete)} className="bg-destructive hover:bg-destructive/90">
|
||||||
Excluir
|
Excluir
|
||||||
</AlertDialogAction>
|
</AlertDialogAction>
|
||||||
</AlertDialogFooter>
|
</AlertDialogFooter>
|
||||||
</AlertDialogContent>
|
</AlertDialogContent>
|
||||||
</AlertDialog>
|
</AlertDialog>
|
||||||
|
|
||||||
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
<AlertDialog
|
||||||
|
open={detailsDialogOpen}
|
||||||
|
onOpenChange={setDetailsDialogOpen}
|
||||||
|
>
|
||||||
<AlertDialogContent>
|
<AlertDialogContent>
|
||||||
<AlertDialogHeader>
|
<AlertDialogHeader>
|
||||||
<AlertDialogTitle>Detalhes do Paciente</AlertDialogTitle>
|
<AlertDialogTitle>Detalhes do Paciente</AlertDialogTitle>
|
||||||
<AlertDialogDescription>
|
<AlertDialogDescription>
|
||||||
{patientDetails === null ? (
|
{patientDetails === null ? (
|
||||||
<div className="text-gray-500">
|
<div className="text-muted-foreground">
|
||||||
<Loader2 className="w-6 h-6 animate-spin mx-auto text-green-600 my-4" />
|
<Loader2 className="w-6 h-6 animate-spin mx-auto text-primary my-4" />
|
||||||
Carregando...
|
Carregando...
|
||||||
</div>
|
</div>
|
||||||
) : patientDetails?.error ? (
|
) : patientDetails?.error ? (
|
||||||
<div className="text-red-600 p-4">{patientDetails.error}</div>
|
<div className="text-destructive p-4">{patientDetails.error}</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="grid gap-4 py-4">
|
<div className="grid gap-4 py-4">
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||||
|
|||||||
@ -40,7 +40,12 @@ export function LoginForm({ children }: LoginFormProps) {
|
|||||||
*/
|
*/
|
||||||
const handleRoleSelection = (selectedDashboardRole: string, user: any) => {
|
const handleRoleSelection = (selectedDashboardRole: string, user: any) => {
|
||||||
if (!user) {
|
if (!user) {
|
||||||
toast({ title: "Erro de Sessão", description: "Não foi possível encontrar os dados do usuário. Tente novamente.", variant: "destructive" });
|
toast({
|
||||||
|
title: "Erro de Sessão",
|
||||||
|
description:
|
||||||
|
"Não foi possível encontrar os dados do usuário. Tente novamente.",
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
setUserRoles([]);
|
setUserRoles([]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -48,23 +53,40 @@ export function LoginForm({ children }: LoginFormProps) {
|
|||||||
const roleInLowerCase = selectedDashboardRole.toLowerCase();
|
const roleInLowerCase = selectedDashboardRole.toLowerCase();
|
||||||
console.log("Salvando no localStorage com o perfil:", roleInLowerCase);
|
console.log("Salvando no localStorage com o perfil:", roleInLowerCase);
|
||||||
|
|
||||||
const completeUserInfo = { ...user, user_metadata: { ...user.user_metadata, role: roleInLowerCase } };
|
const completeUserInfo = {
|
||||||
|
...user,
|
||||||
|
user_metadata: { ...user.user_metadata, role: roleInLowerCase },
|
||||||
|
};
|
||||||
localStorage.setItem("user_info", JSON.stringify(completeUserInfo));
|
localStorage.setItem("user_info", JSON.stringify(completeUserInfo));
|
||||||
|
|
||||||
let redirectPath = "";
|
let redirectPath = "";
|
||||||
switch (selectedDashboardRole) {
|
switch (selectedDashboardRole) {
|
||||||
case "gestor": redirectPath = "/manager/dashboard"; break;
|
case "gestor":
|
||||||
case "admin": redirectPath = "/manager/dashboard"; break;
|
redirectPath = "/manager/dashboard";
|
||||||
case "medico": redirectPath = "/doctor/dashboard"; break;
|
break;
|
||||||
case "secretaria": redirectPath = "/secretary/dashboard"; break;
|
case "admin":
|
||||||
case "paciente": redirectPath = "/patient/dashboard"; break;
|
redirectPath = "/manager/dashboard";
|
||||||
|
break;
|
||||||
|
case "medico":
|
||||||
|
redirectPath = "/doctor/dashboard";
|
||||||
|
break;
|
||||||
|
case "secretaria":
|
||||||
|
redirectPath = "/secretary/dashboard";
|
||||||
|
break;
|
||||||
|
case "paciente":
|
||||||
|
redirectPath = "/patient/dashboard";
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (redirectPath) {
|
if (redirectPath) {
|
||||||
toast({ title: `Entrando como ${selectedDashboardRole}...` });
|
toast({ title: `Entrando como ${selectedDashboardRole}...` });
|
||||||
router.push(redirectPath);
|
router.push(redirectPath);
|
||||||
} else {
|
} else {
|
||||||
toast({ title: "Erro", description: "Perfil selecionado inválido.", variant: "destructive" });
|
toast({
|
||||||
|
title: "Erro",
|
||||||
|
description: "Perfil selecionado inválido.",
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -81,23 +103,29 @@ export function LoginForm({ children }: LoginFormProps) {
|
|||||||
throw new Error("Resposta de autenticação inválida.");
|
throw new Error("Resposta de autenticação inválida.");
|
||||||
}
|
}
|
||||||
|
|
||||||
const rolesData = await api.get(`/rest/v1/user_roles?user_id=eq.${user.id}&select=role`);
|
const rolesData = await api.get(
|
||||||
|
`/rest/v1/user_roles?user_id=eq.${user.id}&select=role`
|
||||||
|
);
|
||||||
|
|
||||||
const me = await usersService.getMeSimple()
|
const me = await usersService.getMeSimple();
|
||||||
console.log(me.roles)
|
console.log(me.roles);
|
||||||
|
|
||||||
if (!me.roles || me.roles.length === 0) {
|
if (!me.roles || me.roles.length === 0) {
|
||||||
throw new Error("Nenhum perfil de acesso foi encontrado para este usuário.");
|
throw new Error(
|
||||||
|
"Nenhum perfil de acesso foi encontrado para este usuário."
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
handleRoleSelection(me.roles[0], user);
|
handleRoleSelection(me.roles[0], user);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
localStorage.removeItem("token");
|
localStorage.removeItem("token");
|
||||||
localStorage.removeItem("user_info");
|
localStorage.removeItem("user_info");
|
||||||
toast({
|
toast({
|
||||||
title: "Erro no Login",
|
title: "Erro no Login",
|
||||||
description: error instanceof Error ? error.message : "Ocorreu um erro inesperado.",
|
description:
|
||||||
|
error instanceof Error
|
||||||
|
? error.message
|
||||||
|
: "Ocorreu um erro inesperado.",
|
||||||
variant: "destructive",
|
variant: "destructive",
|
||||||
});
|
});
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
@ -105,7 +133,8 @@ export function LoginForm({ children }: LoginFormProps) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Estado para guardar os botões de seleção de perfil
|
// Estado para guardar os botões de seleção de perfil
|
||||||
const [roleSelectionUI, setRoleSelectionUI] = useState<React.ReactNode | null>(null);
|
const [roleSelectionUI, setRoleSelectionUI] =
|
||||||
|
useState<React.ReactNode | null>(null);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card className="w-full bg-transparent border-0 shadow-none">
|
<Card className="w-full bg-transparent border-0 shadow-none">
|
||||||
@ -116,30 +145,78 @@ export function LoginForm({ children }: LoginFormProps) {
|
|||||||
<Label htmlFor="email">E-mail</Label>
|
<Label htmlFor="email">E-mail</Label>
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground w-5 h-5" />
|
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground w-5 h-5" />
|
||||||
<Input id="email" type="email" placeholder="seu.email@exemplo.com" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} className="pl-10 h-11" required disabled={isLoading} autoComplete="username" />
|
<Input
|
||||||
|
id="email"
|
||||||
|
type="email"
|
||||||
|
placeholder="seu.email@exemplo.com"
|
||||||
|
value={form.email}
|
||||||
|
onChange={(e) => setForm({ ...form, email: e.target.value })}
|
||||||
|
className="pl-10 h-11 focus-visible:ring-blue-600 focus-visible:ring-2"
|
||||||
|
required
|
||||||
|
disabled={isLoading}
|
||||||
|
autoComplete="username"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="password">Senha</Label>
|
<Label htmlFor="password">Senha</Label>
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground w-5 h-5" />
|
<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" />
|
<Input
|
||||||
<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}>
|
id="password"
|
||||||
{showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
|
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>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<Button type="submit" className="w-full h-11 text-base font-semibold" disabled={isLoading}>
|
<Button
|
||||||
{isLoading ? <Loader2 className="w-5 h-5 animate-spin" /> : "Entrar"}
|
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>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-4 animate-in fade-in-50">
|
<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>
|
<h3 className="text-lg font-medium text-center text-foreground">
|
||||||
<p className="text-sm text-muted-foreground text-center">Selecione com qual perfil deseja entrar:</p>
|
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">
|
<div className="flex flex-col space-y-3 pt-2">
|
||||||
{userRoles.map((role) => (
|
{userRoles.map((role) => (
|
||||||
<Button key={role} variant="outline" className="h-11 text-base" onClick={() => handleRoleSelection(role, authenticatedUser)}>
|
<Button
|
||||||
|
key={role}
|
||||||
|
variant="outline"
|
||||||
|
className="h-11 text-base"
|
||||||
|
onClick={() => handleRoleSelection(role, authenticatedUser)}
|
||||||
|
>
|
||||||
Entrar como: {role.charAt(0).toUpperCase() + role.slice(1)}
|
Entrar como: {role.charAt(0).toUpperCase() + role.slice(1)}
|
||||||
</Button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@ -1,17 +1,15 @@
|
|||||||
// Caminho: [seu-caminho]/ManagerLayout.tsx
|
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import type React from "react";
|
import type React from "react";
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import { useRouter, usePathname } from "next/navigation";
|
import { useRouter, usePathname } from "next/navigation";
|
||||||
import Link from "next/link";
|
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 { api } from "@/services/api.mjs";
|
||||||
|
import { usersService } from "@/services/usersApi.mjs"; // Importando usersService
|
||||||
|
import { useAccessibility } from "@/app/context/AccessibilityContext";
|
||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
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 {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
DialogContent,
|
DialogContent,
|
||||||
@ -20,25 +18,21 @@ import {
|
|||||||
DialogHeader,
|
DialogHeader,
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from "@/components/ui/dialog";
|
} from "@/components/ui/dialog";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
Search,
|
|
||||||
Bell,
|
|
||||||
Calendar,
|
|
||||||
User,
|
|
||||||
LogOut,
|
LogOut,
|
||||||
ChevronLeft,
|
ChevronLeft,
|
||||||
ChevronRight,
|
ChevronRight,
|
||||||
Home,
|
Home,
|
||||||
CalendarCheck2,
|
CalendarCheck2,
|
||||||
ClipboardPlus,
|
ClipboardPlus,
|
||||||
SquareUserRound,
|
|
||||||
CalendarClock,
|
CalendarClock,
|
||||||
Users,
|
Users,
|
||||||
SquareUser,
|
SquareUser,
|
||||||
ClipboardList,
|
ClipboardList,
|
||||||
Stethoscope,
|
Stethoscope,
|
||||||
ClipboardMinus,
|
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
|
|
||||||
import SidebarUserSection from "@/components/ui/userToolTip";
|
import SidebarUserSection from "@/components/ui/userToolTip";
|
||||||
|
|
||||||
interface UserData {
|
interface UserData {
|
||||||
@ -53,6 +47,7 @@ interface UserData {
|
|||||||
full_name: string;
|
full_name: string;
|
||||||
phone_mobile: string;
|
phone_mobile: string;
|
||||||
role: string;
|
role: string;
|
||||||
|
avatar_url?: string;
|
||||||
};
|
};
|
||||||
identities: {
|
identities: {
|
||||||
identity_id: string;
|
identity_id: string;
|
||||||
@ -78,17 +73,36 @@ export default function Sidebar({ children }: SidebarProps) {
|
|||||||
const [role, setRole] = useState<string>();
|
const [role, setRole] = useState<string>();
|
||||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
|
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
|
||||||
const [showLogoutDialog, setShowLogoutDialog] = useState(false);
|
const [showLogoutDialog, setShowLogoutDialog] = useState(false);
|
||||||
|
const [avatarFullUrl, setAvatarFullUrl] = useState<string | undefined>(undefined);
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
|
|
||||||
|
// Função auxiliar para construir URL
|
||||||
|
const buildAvatarUrl = (path: string) => {
|
||||||
|
if (!path) return undefined;
|
||||||
|
const baseUrl = "https://yuanqfswhberkoevtmfr.supabase.co";
|
||||||
|
const cleanPath = path.startsWith('/') ? path.slice(1) : path;
|
||||||
|
const separator = cleanPath.includes('?') ? '&' : '?';
|
||||||
|
return `${baseUrl}/storage/v1/object/avatars/${cleanPath}${separator}t=${new Date().getTime()}`;
|
||||||
|
};
|
||||||
|
const { theme, contrast } = useAccessibility();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const userInfoString = localStorage.getItem("user_info");
|
const userInfoString = localStorage.getItem("user_info");
|
||||||
// --- ALTERAÇÃO 1: Buscando o token no localStorage ---
|
|
||||||
const token = localStorage.getItem("token");
|
const token = localStorage.getItem("token");
|
||||||
|
|
||||||
if (userInfoString && token) {
|
if (userInfoString && token) {
|
||||||
|
try {
|
||||||
const userInfo = JSON.parse(userInfoString);
|
const userInfo = JSON.parse(userInfoString);
|
||||||
|
|
||||||
|
// 1. Tenta pegar o avatar do cache local
|
||||||
|
let rawAvatarPath =
|
||||||
|
userInfo.profile?.avatar_url ||
|
||||||
|
userInfo.user_metadata?.avatar_url ||
|
||||||
|
userInfo.app_metadata?.avatar_url ||
|
||||||
|
"";
|
||||||
|
|
||||||
|
// Configura estado inicial com o que tem no cache
|
||||||
setUserData({
|
setUserData({
|
||||||
id: userInfo.id ?? "",
|
id: userInfo.id ?? "",
|
||||||
email: userInfo.email ?? "",
|
email: userInfo.email ?? "",
|
||||||
@ -98,22 +112,63 @@ export default function Sidebar({ children }: SidebarProps) {
|
|||||||
user_metadata: {
|
user_metadata: {
|
||||||
cpf: userInfo.user_metadata?.cpf ?? "",
|
cpf: userInfo.user_metadata?.cpf ?? "",
|
||||||
email_verified: userInfo.user_metadata?.email_verified ?? false,
|
email_verified: userInfo.user_metadata?.email_verified ?? false,
|
||||||
full_name: userInfo.user_metadata?.full_name ?? "",
|
full_name: userInfo.user_metadata?.full_name || userInfo.profile?.full_name || "Usuário",
|
||||||
phone_mobile: userInfo.user_metadata?.phone_mobile ?? "",
|
phone_mobile: userInfo.user_metadata?.phone_mobile ?? "",
|
||||||
role: userInfo.user_metadata?.role ?? "",
|
role: userInfo.user_metadata?.role ?? "",
|
||||||
|
avatar_url: rawAvatarPath,
|
||||||
},
|
},
|
||||||
identities:
|
identities: userInfo.identities ?? [],
|
||||||
userInfo.identities?.map((identity: any) => ({
|
|
||||||
identity_id: identity.identity_id ?? "",
|
|
||||||
id: identity.id ?? "",
|
|
||||||
user_id: identity.user_id ?? "",
|
|
||||||
provider: identity.provider ?? "",
|
|
||||||
})) ?? [],
|
|
||||||
is_anonymous: userInfo.is_anonymous ?? false,
|
is_anonymous: userInfo.is_anonymous ?? false,
|
||||||
});
|
});
|
||||||
|
|
||||||
setRole(userInfo.user_metadata?.role);
|
setRole(userInfo.user_metadata?.role);
|
||||||
|
|
||||||
|
if (rawAvatarPath) {
|
||||||
|
setAvatarFullUrl(buildAvatarUrl(rawAvatarPath));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. AUTO-REPARO: Se não tiver avatar ou profile no cache, busca na API e atualiza
|
||||||
|
if (!rawAvatarPath || !userInfo.profile) {
|
||||||
|
console.log("[Sidebar] Cache incompleto. Buscando dados frescos...");
|
||||||
|
usersService.getMe().then((freshData) => {
|
||||||
|
if (freshData && freshData.profile) {
|
||||||
|
const freshAvatar = freshData.profile.avatar_url;
|
||||||
|
|
||||||
|
// Atualiza o objeto local
|
||||||
|
const updatedUserInfo = {
|
||||||
|
...userInfo,
|
||||||
|
profile: freshData.profile, // Injeta o profile completo
|
||||||
|
user_metadata: {
|
||||||
|
...userInfo.user_metadata,
|
||||||
|
avatar_url: freshAvatar || userInfo.user_metadata.avatar_url
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Salva no localStorage para a próxima vez
|
||||||
|
localStorage.setItem("user_info", JSON.stringify(updatedUserInfo));
|
||||||
|
console.log("[Sidebar] LocalStorage sincronizado com sucesso.");
|
||||||
|
|
||||||
|
// Atualiza visualmente se achou um avatar novo
|
||||||
|
if (freshAvatar && freshAvatar !== rawAvatarPath) {
|
||||||
|
setAvatarFullUrl(buildAvatarUrl(freshAvatar));
|
||||||
|
// Atualiza o userData também para refletir no tooltip
|
||||||
|
setUserData(prev => prev ? ({
|
||||||
|
...prev,
|
||||||
|
user_metadata: {
|
||||||
|
...prev.user_metadata,
|
||||||
|
avatar_url: freshAvatar
|
||||||
|
}
|
||||||
|
}) : undefined);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}).catch(err => console.error("[Sidebar] Falha no auto-reparo:", err));
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Erro ao processar dados do usuário na Sidebar:", e);
|
||||||
|
}
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
// O redirecionamento para /login já estava correto. Ótimo!
|
|
||||||
router.push("/login");
|
router.push("/login");
|
||||||
}
|
}
|
||||||
}, [router]);
|
}, [router]);
|
||||||
@ -133,21 +188,18 @@ export default function Sidebar({ children }: SidebarProps) {
|
|||||||
|
|
||||||
const handleLogout = () => setShowLogoutDialog(true);
|
const handleLogout = () => setShowLogoutDialog(true);
|
||||||
|
|
||||||
// --- ALTERAÇÃO 2: A função de logout agora é MUITO mais simples ---
|
|
||||||
const confirmLogout = async () => {
|
const confirmLogout = async () => {
|
||||||
try {
|
try {
|
||||||
// Chama a função centralizada para fazer o logout no servidor
|
|
||||||
await api.logout();
|
await api.logout();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// O erro já é logado dentro da função api.logout, não precisamos fazer nada aqui
|
console.error("Erro ao fazer logout", error);
|
||||||
} finally {
|
} finally {
|
||||||
// A responsabilidade do componente é apenas limpar o estado local e redirecionar
|
|
||||||
localStorage.removeItem("user_info");
|
localStorage.removeItem("user_info");
|
||||||
localStorage.removeItem("token");
|
localStorage.removeItem("token");
|
||||||
Cookies.remove("access_token"); // Limpeza de segurança
|
Cookies.remove("access_token");
|
||||||
|
|
||||||
setShowLogoutDialog(false);
|
setShowLogoutDialog(false);
|
||||||
router.push("/"); // Redireciona para a home
|
router.push("/");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -202,38 +254,29 @@ export default function Sidebar({ children }: SidebarProps) {
|
|||||||
|
|
||||||
const managerItems: MenuItem[] = [
|
const managerItems: MenuItem[] = [
|
||||||
{ href: "/manager/dashboard", icon: Home, label: "Dashboard" },
|
{ href: "/manager/dashboard", icon: Home, label: "Dashboard" },
|
||||||
{ href: "#", icon: ClipboardMinus, label: "Relatórios gerenciais" },
|
|
||||||
{ href: "/manager/usuario", icon: Users, label: "Gestão de Usuários" },
|
{ href: "/manager/usuario", icon: Users, label: "Gestão de Usuários" },
|
||||||
{ href: "/manager/home", icon: Stethoscope, label: "Gestão de Médicos" },
|
{ href: "/manager/home", icon: Stethoscope, label: "Gestão de Médicos" },
|
||||||
{ href: "/manager/pacientes", icon: Users, label: "Gestão de Pacientes" },
|
{ href: "/manager/pacientes", icon: Users, label: "Gestão de Pacientes" },
|
||||||
{ href: "/doctor/consultas", icon: CalendarCheck2, label: "Consultas" }, //adicionar botão de voltar pra pagina anterior
|
{ href: "/secretary/appointments", icon: CalendarCheck2, label: "Consultas" },
|
||||||
|
{ href: "/manager/disponibilidade", icon: ClipboardList, label: "Disponibilidade" },
|
||||||
];
|
];
|
||||||
|
|
||||||
let menuItems: MenuItem[];
|
|
||||||
switch (role) {
|
switch (role) {
|
||||||
case "gestor":
|
case "gestor":
|
||||||
menuItems = managerItems;
|
|
||||||
break;
|
|
||||||
case "admin":
|
case "admin":
|
||||||
menuItems = managerItems;
|
return managerItems;
|
||||||
break;
|
|
||||||
case "medico":
|
case "medico":
|
||||||
menuItems = doctorItems;
|
return doctorItems;
|
||||||
break;
|
|
||||||
case "secretaria":
|
case "secretaria":
|
||||||
menuItems = secretaryItems;
|
return secretaryItems;
|
||||||
break;
|
|
||||||
case "paciente":
|
case "paciente":
|
||||||
menuItems = patientItems;
|
|
||||||
break;
|
|
||||||
default:
|
default:
|
||||||
menuItems = patientItems;
|
return patientItems;
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
return menuItems;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const menuItems = SetMenuItems(role);
|
const menuItems = SetMenuItems(role);
|
||||||
|
const isDefaultMode = theme === "light" && contrast === "normal";
|
||||||
|
|
||||||
if (!userData) {
|
if (!userData) {
|
||||||
return (
|
return (
|
||||||
@ -244,50 +287,61 @@ export default function Sidebar({ children }: SidebarProps) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-50 flex">
|
<div className="min-h-screen bg-background flex">
|
||||||
<div
|
<div
|
||||||
className={`bg-white border-r border-gray-200 transition-all duration-300 fixed top-0 h-screen flex flex-col z-30 ${
|
className={`fixed top-0 h-screen flex flex-col z-30 transition-all duration-300
|
||||||
sidebarCollapsed ? "w-16" : "w-64"
|
${sidebarCollapsed ? "w-16" : "w-64"}
|
||||||
}`}
|
${isDefaultMode ? "bg-[#123965] text-white" : "bg-sidebar text-sidebar-foreground"}`}
|
||||||
>
|
>
|
||||||
<div className="p-4 border-b border-gray-200 flex items-center justify-between">
|
{/* TOPO */}
|
||||||
|
<div className={`p-4 border-b ${isDefaultMode ? "border-white/10" : "border-sidebar-border"} flex items-center justify-between`}>
|
||||||
{!sidebarCollapsed && (
|
{!sidebarCollapsed && (
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
{/* 🛑 SUBSTITUIÇÃO: Usando a tag <img> com o caminho da logo */}
|
<div className="bg-background p-1 rounded-lg">
|
||||||
<img
|
<img
|
||||||
src="/Logo MedConnect.png" // Use o arquivo da logo (ou /android-chrome-512x512.png)
|
src="/Logo MedConnect.png"
|
||||||
alt="Logo MediConnect"
|
alt="Logo MedConnect"
|
||||||
className="w-12 h-12 object-contain" // Define o tamanho para w-8 h-8 (32px)
|
className="w-12 h-12 object-contain"
|
||||||
/>
|
/>
|
||||||
<span className="font-semibold text-gray-900">MedConnect</span>
|
</div>
|
||||||
|
|
||||||
|
<span className="font-semibold text-lg">
|
||||||
|
MedConnect
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
|
onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
|
||||||
className="p-1"
|
className={`p-1 ${isDefaultMode ? "text-white hover:bg-white/10" : "hover:bg-sidebar-accent"} cursor-pointer`}
|
||||||
>
|
>
|
||||||
{sidebarCollapsed ? (
|
{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>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<nav className="flex-1 p-2 overflow-y-auto">
|
{/* MENU */}
|
||||||
|
<nav className="flex-1 px-3 py-6 overflow-y-auto flex flex-col gap-2">
|
||||||
{menuItems.map((item) => {
|
{menuItems.map((item) => {
|
||||||
const Icon = item.icon;
|
const Icon = item.icon;
|
||||||
const isActive = pathname === item.href;
|
const isActive = pathname === item.href;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Link key={item.label} href={item.href}>
|
<Link key={item.label} href={item.href}>
|
||||||
<div
|
<div
|
||||||
className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${
|
className={`
|
||||||
|
flex items-center gap-3 px-3 py-2 rounded-lg transition-colors
|
||||||
|
${
|
||||||
isActive
|
isActive
|
||||||
? "bg-blue-50 text-blue-600 border-r-2 border-blue-600"
|
? `${isDefaultMode ? "bg-white/20 text-white font-semibold" : "bg-sidebar-primary text-sidebar-primary-foreground font-semibold"}`
|
||||||
: "text-gray-600 hover:bg-gray-50"
|
: `${isDefaultMode ? "text-white/80 hover:bg-white/10 hover:text-white" : "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"}`
|
||||||
}`}
|
}
|
||||||
|
`}
|
||||||
>
|
>
|
||||||
<Icon className="w-5 h-5 flex-shrink-0" />
|
<Icon className="w-5 h-5 flex-shrink-0" />
|
||||||
{!sidebarCollapsed && (
|
{!sidebarCollapsed && (
|
||||||
@ -298,30 +352,38 @@ export default function Sidebar({ children }: SidebarProps) {
|
|||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
|
{/* PERFIL ORIGINAL + NOME BRANCO - CORREÇÃO DE ALINHAMENTO AQUI */}
|
||||||
|
<div
|
||||||
|
className={`
|
||||||
|
mt-auto p-3 border-t
|
||||||
|
${isDefaultMode ? "border-white/10" : "border-sidebar-border"}
|
||||||
|
flex flex-col
|
||||||
|
${sidebarCollapsed ? "items-center justify-center" : "items-stretch"}
|
||||||
|
`}
|
||||||
|
>
|
||||||
<SidebarUserSection
|
<SidebarUserSection
|
||||||
userData={userData}
|
userData={userData}
|
||||||
sidebarCollapsed={false}
|
sidebarCollapsed={sidebarCollapsed}
|
||||||
handleLogout={handleLogout}
|
handleLogout={handleLogout}
|
||||||
isActive={role === "paciente" ? false : true}
|
isActive={role !== "paciente"}
|
||||||
></SidebarUserSection>
|
avatarUrl={avatarFullUrl}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
</div>
|
</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"
|
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>
|
<main className="flex-1 p-4 md:p-6">{children}</main>
|
||||||
</div>
|
|
||||||
|
|
||||||
<Dialog open={showLogoutDialog} onOpenChange={setShowLogoutDialog}>
|
<Dialog open={showLogoutDialog} onOpenChange={setShowLogoutDialog}>
|
||||||
<DialogContent className="sm:max-w-md">
|
<DialogContent className="sm:max-w-md">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>Confirmar Saída</DialogTitle>
|
<DialogTitle>Confirmar Saída</DialogTitle>
|
||||||
<DialogDescription>
|
<DialogDescription>
|
||||||
Deseja realmente sair do sistema? Você precisará fazer login
|
Deseja realmente sair do sistema? Você precisará fazer login
|
||||||
novamente para acessar sua conta.
|
novamente.
|
||||||
</DialogDescription>
|
</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
<DialogFooter className="flex gap-2">
|
<DialogFooter className="flex gap-2">
|
||||||
@ -336,5 +398,6 @@ export default function Sidebar({ children }: SidebarProps) {
|
|||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -9,25 +9,52 @@ import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
|||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
import { Textarea } from "@/components/ui/textarea";
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
import { Calendar as CalendarShadcn } from "@/components/ui/calendar";
|
import { Calendar as CalendarShadcn } from "@/components/ui/calendar";
|
||||||
import { format, addDays } from "date-fns";
|
import { format, addDays } from "date-fns";
|
||||||
import { User, StickyNote, Calendar } from "lucide-react";
|
import { User, StickyNote, CalendarDays, Stethoscope, Check, ChevronsUpDown } from "lucide-react";
|
||||||
import {smsService } from "@/services/Sms.mjs"
|
import { smsService } from "@/services/Sms.mjs";
|
||||||
import { toast } from "@/hooks/use-toast";
|
import { toast } from "@/hooks/use-toast";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
// --- Importações do Combobox ---
|
||||||
|
import {
|
||||||
|
Command,
|
||||||
|
CommandEmpty,
|
||||||
|
CommandGroup,
|
||||||
|
CommandInput,
|
||||||
|
CommandItem,
|
||||||
|
CommandList,
|
||||||
|
} from "@/components/ui/command";
|
||||||
|
import {
|
||||||
|
Popover,
|
||||||
|
PopoverContent,
|
||||||
|
PopoverTrigger,
|
||||||
|
} from "@/components/ui/popover";
|
||||||
|
|
||||||
export default function ScheduleForm() {
|
export default function ScheduleForm() {
|
||||||
// Estado do usuário e role
|
// --- ESTADOS ---
|
||||||
const [role, setRole] = useState<string>("paciente");
|
const [role, setRole] = useState<string>("paciente");
|
||||||
const [userId, setUserId] = useState<string | null>(null);
|
const [userId, setUserId] = useState<string | null>(null);
|
||||||
|
|
||||||
// Listas e seleções
|
// Estados de Paciente
|
||||||
const [patients, setPatients] = useState<any[]>([]);
|
const [patients, setPatients] = useState<any[]>([]);
|
||||||
const [selectedPatient, setSelectedPatient] = useState("");
|
const [selectedPatient, setSelectedPatient] = useState("");
|
||||||
|
const [openPatientCombobox, setOpenPatientCombobox] = useState(false);
|
||||||
|
|
||||||
|
// Estados de Médico
|
||||||
const [doctors, setDoctors] = useState<any[]>([]);
|
const [doctors, setDoctors] = useState<any[]>([]);
|
||||||
const [selectedDoctor, setSelectedDoctor] = useState("");
|
const [selectedDoctor, setSelectedDoctor] = useState("");
|
||||||
|
const [openDoctorCombobox, setOpenDoctorCombobox] = useState(false);
|
||||||
|
|
||||||
|
// Estados de Agendamento
|
||||||
const [selectedDate, setSelectedDate] = useState("");
|
const [selectedDate, setSelectedDate] = useState("");
|
||||||
const [selectedTime, setSelectedTime] = useState("");
|
const [selectedTime, setSelectedTime] = useState("");
|
||||||
const [notes, setNotes] = useState("");
|
const [notes, setNotes] = useState("");
|
||||||
@ -35,23 +62,23 @@ export default function ScheduleForm() {
|
|||||||
const [loadingDoctors, setLoadingDoctors] = useState(true);
|
const [loadingDoctors, setLoadingDoctors] = useState(true);
|
||||||
const [loadingSlots, setLoadingSlots] = useState(false);
|
const [loadingSlots, setLoadingSlots] = useState(false);
|
||||||
|
|
||||||
// Outras configs
|
// Configurações
|
||||||
const [tipoConsulta] = useState("presencial");
|
const [tipoConsulta] = useState("presencial");
|
||||||
const [duracao] = useState("30");
|
const [duracao] = useState("30");
|
||||||
const [disponibilidades, setDisponibilidades] = useState<any[]>([]);
|
const [disponibilidades, setDisponibilidades] = useState<any[]>([]);
|
||||||
const [availabilityCounts, setAvailabilityCounts] = useState<Record<string, number>>({});
|
const [availabilityCounts, setAvailabilityCounts] = useState<Record<string, number>>({});
|
||||||
const [tooltip, setTooltip] = useState<{ x: number; y: number; text: string } | null>(null);
|
const [tooltip, setTooltip] = useState<{ x: number; y: number; text: string } | null>(null);
|
||||||
|
|
||||||
const calendarRef = useRef<HTMLDivElement | null>(null);
|
const calendarRef = useRef<HTMLDivElement | null>(null);
|
||||||
|
|
||||||
// Funções auxiliares
|
// --- HELPER FUNCTIONS ---
|
||||||
const getWeekdayNumber = (weekday: string) =>
|
const getWeekdayNumber = (weekday: string) =>
|
||||||
["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
|
["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"].indexOf(weekday.toLowerCase()) + 1;
|
||||||
.indexOf(weekday.toLowerCase()) + 1;
|
|
||||||
|
|
||||||
const getBrazilDate = (date: Date) =>
|
const getBrazilDate = (date: Date) =>
|
||||||
new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), 12, 0, 0));
|
new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), 12, 0, 0));
|
||||||
|
|
||||||
// 🔹 Buscar dados do usuário e role
|
// --- EFFECTS ---
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
(async () => {
|
(async () => {
|
||||||
try {
|
try {
|
||||||
@ -70,7 +97,6 @@ export default function ScheduleForm() {
|
|||||||
})();
|
})();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// 🔹 Buscar médicos
|
|
||||||
const fetchDoctors = useCallback(async () => {
|
const fetchDoctors = useCallback(async () => {
|
||||||
setLoadingDoctors(true);
|
setLoadingDoctors(true);
|
||||||
try {
|
try {
|
||||||
@ -88,7 +114,6 @@ export default function ScheduleForm() {
|
|||||||
fetchDoctors();
|
fetchDoctors();
|
||||||
}, [fetchDoctors]);
|
}, [fetchDoctors]);
|
||||||
|
|
||||||
// 🔹 Buscar disponibilidades
|
|
||||||
const loadDoctorDisponibilidades = useCallback(async (doctorId?: string) => {
|
const loadDoctorDisponibilidades = useCallback(async (doctorId?: string) => {
|
||||||
if (!doctorId) return;
|
if (!doctorId) return;
|
||||||
try {
|
try {
|
||||||
@ -147,7 +172,6 @@ export default function ScheduleForm() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 🔹 Quando médico muda
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (selectedDoctor) {
|
if (selectedDoctor) {
|
||||||
loadDoctorDisponibilidades(selectedDoctor);
|
loadDoctorDisponibilidades(selectedDoctor);
|
||||||
@ -160,7 +184,6 @@ export default function ScheduleForm() {
|
|||||||
setAvailableTimes([]);
|
setAvailableTimes([]);
|
||||||
}, [selectedDoctor, loadDoctorDisponibilidades]);
|
}, [selectedDoctor, loadDoctorDisponibilidades]);
|
||||||
|
|
||||||
// 🔹 Buscar horários disponíveis
|
|
||||||
const fetchAvailableSlots = useCallback(async (doctorId: string, date: string) => {
|
const fetchAvailableSlots = useCallback(async (doctorId: string, date: string) => {
|
||||||
if (!doctorId || !date) return;
|
if (!doctorId || !date) return;
|
||||||
setLoadingSlots(true);
|
setLoadingSlots(true);
|
||||||
@ -172,9 +195,7 @@ export default function ScheduleForm() {
|
|||||||
);
|
);
|
||||||
const diaJS = new Date(date).getDay();
|
const diaJS = new Date(date).getDay();
|
||||||
const diaAPI = diaJS === 0 ? 7 : diaJS;
|
const diaAPI = diaJS === 0 ? 7 : diaJS;
|
||||||
const disponibilidadeDia = disponibilidades.find(
|
const disponibilidadeDia = disponibilidades.find((d: any) => getWeekdayNumber(d.weekday) === diaAPI);
|
||||||
(d: any) => getWeekdayNumber(d.weekday) === diaAPI
|
|
||||||
);
|
|
||||||
if (!disponibilidadeDia) {
|
if (!disponibilidadeDia) {
|
||||||
toast({ title: "Nenhuma disponibilidade", description: "Nenhum horário para este dia." });
|
toast({ title: "Nenhuma disponibilidade", description: "Nenhum horário para este dia." });
|
||||||
return setAvailableTimes([]);
|
return setAvailableTimes([]);
|
||||||
@ -191,9 +212,7 @@ export default function ScheduleForm() {
|
|||||||
horariosGerados.push(atual.toTimeString().slice(0, 5));
|
horariosGerados.push(atual.toTimeString().slice(0, 5));
|
||||||
atual = new Date(atual.getTime() + slot * 60000);
|
atual = new Date(atual.getTime() + slot * 60000);
|
||||||
}
|
}
|
||||||
const ocupados = (consultas || []).map((c: any) =>
|
const ocupados = (consultas || []).map((c: any) => String(c.scheduled_at).split("T")[1]?.slice(0, 5));
|
||||||
String(c.scheduled_at).split("T")[1]?.slice(0, 5)
|
|
||||||
);
|
|
||||||
const livres = horariosGerados.filter((h) => !ocupados.includes(h));
|
const livres = horariosGerados.filter((h) => !ocupados.includes(h));
|
||||||
setAvailableTimes(livres);
|
setAvailableTimes(livres);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@ -208,14 +227,9 @@ export default function ScheduleForm() {
|
|||||||
if (selectedDoctor && selectedDate) fetchAvailableSlots(selectedDoctor, selectedDate);
|
if (selectedDoctor && selectedDate) fetchAvailableSlots(selectedDoctor, selectedDate);
|
||||||
}, [selectedDoctor, selectedDate, fetchAvailableSlots]);
|
}, [selectedDoctor, selectedDate, fetchAvailableSlots]);
|
||||||
|
|
||||||
// 🔹 Submeter agendamento
|
// --- SUBMIT ---
|
||||||
// 🔹 Submeter agendamento
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
// 🔹 Submeter agendamento
|
|
||||||
// 🔹 Submeter agendamento
|
|
||||||
// 🔹 Submeter agendamento
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|
||||||
const isSecretaryLike = ["secretaria", "admin", "gestor"].includes(role);
|
const isSecretaryLike = ["secretaria", "admin", "gestor"].includes(role);
|
||||||
const patientId = isSecretaryLike ? selectedPatient : userId;
|
const patientId = isSecretaryLike ? selectedPatient : userId;
|
||||||
|
|
||||||
@ -234,79 +248,14 @@ const handleSubmit = async (e: React.FormEvent) => {
|
|||||||
appointment_type: tipoConsulta,
|
appointment_type: tipoConsulta,
|
||||||
};
|
};
|
||||||
|
|
||||||
// ✅ mantém o fluxo original de criação (funcional)
|
|
||||||
await appointmentsService.create(body);
|
await appointmentsService.create(body);
|
||||||
|
|
||||||
const dateFormatted = selectedDate.split("-").reverse().join("/");
|
const dateFormatted = selectedDate.split("-").reverse().join("/");
|
||||||
|
|
||||||
toast({
|
toast({
|
||||||
title: "Consulta agendada!",
|
title: "Consulta agendada!",
|
||||||
description: `Consulta marcada para ${dateFormatted} às ${selectedTime} com o(a) médico(a) ${
|
description: `Consulta marcada para ${dateFormatted} às ${selectedTime}.`,
|
||||||
doctors.find((d) => d.id === selectedDoctor)?.full_name || ""
|
|
||||||
}.`,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
let phoneNumber = "+5511999999999"; // fallback
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (isSecretaryLike) {
|
|
||||||
// Secretária/admin → telefone do paciente selecionado
|
|
||||||
const patient = patients.find((p: any) => p.id === patientId);
|
|
||||||
|
|
||||||
// Pacientes criados no sistema podem ter phone ou phone_mobile
|
|
||||||
const rawPhone = patient?.phone || patient?.phone_mobile || null;
|
|
||||||
|
|
||||||
if (rawPhone) phoneNumber = rawPhone;
|
|
||||||
} else {
|
|
||||||
// Paciente → telefone vem do perfil do próprio usuário logado
|
|
||||||
const me = await usersService.getMe();
|
|
||||||
|
|
||||||
|
|
||||||
const rawPhone =
|
|
||||||
me?.profile?.phone ||
|
|
||||||
(typeof me?.profile === "object" && "phone_mobile" in me.profile ? (me.profile as any).phone_mobile : null) ||
|
|
||||||
(typeof me === "object" && "user_metadata" in me ? (me as any).user_metadata?.phone : null) ||
|
|
||||||
null;
|
|
||||||
|
|
||||||
if (rawPhone) phoneNumber = rawPhone;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 🔹 Normaliza para formato internacional (+55)
|
|
||||||
if (phoneNumber) {
|
|
||||||
phoneNumber = phoneNumber.replace(/\D/g, "");
|
|
||||||
if (!phoneNumber.startsWith("55")) phoneNumber = `55${phoneNumber}`;
|
|
||||||
phoneNumber = `+${phoneNumber}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log("📞 Telefone usado:", phoneNumber);
|
|
||||||
} catch (err) {
|
|
||||||
console.warn("⚠️ Não foi possível obter telefone do paciente:", err);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// 💬 envia o SMS de confirmação
|
|
||||||
// 💬 Envia o SMS de lembrete (sem mostrar nada ao paciente)
|
|
||||||
// 💬 Envia o SMS de lembrete (somente loga no console, não mostra no sistema)
|
|
||||||
try {
|
|
||||||
const smsRes = await smsService.sendSms({
|
|
||||||
phone_number: phoneNumber,
|
|
||||||
message: `Lembrete: sua consulta é em ${dateFormatted} às ${selectedTime} na Clínica MediConnect.`,
|
|
||||||
patient_id: patientId,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (smsRes?.success) {
|
|
||||||
console.log("✅ SMS enviado com sucesso:", smsRes.message_sid);
|
|
||||||
} else {
|
|
||||||
console.warn("⚠️ Falha no envio do SMS:", smsRes);
|
|
||||||
}
|
|
||||||
} catch (smsErr) {
|
|
||||||
console.error("❌ Erro ao enviar SMS:", smsErr);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// 🧹 limpa os campos
|
|
||||||
setSelectedDoctor("");
|
setSelectedDoctor("");
|
||||||
setSelectedDate("");
|
setSelectedDate("");
|
||||||
setSelectedTime("");
|
setSelectedTime("");
|
||||||
@ -316,13 +265,9 @@ try {
|
|||||||
console.error("❌ Erro ao agendar consulta:", err);
|
console.error("❌ Erro ao agendar consulta:", err);
|
||||||
toast({ title: "Erro", description: "Falha ao agendar consulta." });
|
toast({ title: "Erro", description: "Falha ao agendar consulta." });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// --- TOOLTIP ---
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// 🔹 Tooltip no calendário
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const cont = calendarRef.current;
|
const cont = calendarRef.current;
|
||||||
if (!cont) return;
|
if (!cont) return;
|
||||||
@ -351,56 +296,174 @@ try {
|
|||||||
}, [availabilityCounts]);
|
}, [availabilityCounts]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="max-w-6xl mx-auto space-y-4 px-4">
|
<div className="w-full min-h-screen p-4 md:p-6 lg:p-8">
|
||||||
<h1 className="text-2xl font-semibold">Agendar Consulta</h1>
|
<div className="max-w-7xl mx-auto space-y-6">
|
||||||
|
<div className="space-y-1">
|
||||||
|
<h1 className="text-2xl md:text-3xl font-bold text-foreground">
|
||||||
|
Agendar Consulta
|
||||||
|
</h1>
|
||||||
|
<p className="text-muted-foreground text-sm md:text-base">
|
||||||
|
Preencha os dados abaixo para marcar seu horário.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
<Card className="border rounded-xl shadow-sm">
|
<div className="grid grid-cols-1 xl:grid-cols-[1fr_350px] gap-6">
|
||||||
<CardHeader>
|
|
||||||
<CardTitle>Dados da Consulta</CardTitle>
|
{/* == ESQUERDA == */}
|
||||||
|
<div className="space-y-6">
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 items-start">
|
||||||
|
|
||||||
|
{/* BLOCO 1: SELEÇÃO */}
|
||||||
|
<Card className="h-full border shadow-sm">
|
||||||
|
<CardHeader className="pb-3 border-b bg-muted/20">
|
||||||
|
<CardTitle className="text-base flex items-center gap-2">
|
||||||
|
<Stethoscope className="w-4 h-4 text-primary" />
|
||||||
|
Dados da Consulta
|
||||||
|
</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent className="space-y-5 pt-5">
|
||||||
<form onSubmit={handleSubmit} className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
|
||||||
<div className="space-y-3">
|
{/* COMBOBOX DE PACIENTE */}
|
||||||
{/* Se secretária/gestor/admin → mostrar campo Paciente */}
|
|
||||||
{["secretaria", "gestor", "admin"].includes(role) && (
|
{["secretaria", "gestor", "admin"].includes(role) && (
|
||||||
<div>
|
<div className="space-y-2">
|
||||||
<Label>Paciente</Label>
|
<Label className="text-sm font-medium">Selecione o Paciente</Label>
|
||||||
<Select value={selectedPatient} onValueChange={setSelectedPatient}>
|
|
||||||
<SelectTrigger>
|
<Popover open={openPatientCombobox} onOpenChange={setOpenPatientCombobox}>
|
||||||
<SelectValue placeholder="Selecione o paciente" />
|
<PopoverTrigger asChild>
|
||||||
</SelectTrigger>
|
<Button
|
||||||
<SelectContent>
|
variant="outline"
|
||||||
|
role="combobox"
|
||||||
|
aria-expanded={openPatientCombobox}
|
||||||
|
className="w-full justify-between"
|
||||||
|
>
|
||||||
|
{selectedPatient
|
||||||
|
? patients.find((p) => p.id === selectedPatient)?.full_name
|
||||||
|
: "Buscar paciente..."}
|
||||||
|
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||||
|
</Button>
|
||||||
|
</PopoverTrigger>
|
||||||
|
|
||||||
|
{/* AQUI: align="start" e w igual ao trigger garantem que não invada a lateral */}
|
||||||
|
<PopoverContent
|
||||||
|
className="w-[--radix-popover-trigger-width] min-w-0 p-0"
|
||||||
|
align="start"
|
||||||
|
side="bottom"
|
||||||
|
>
|
||||||
|
<Command>
|
||||||
|
<CommandInput placeholder="Procurar paciente..." />
|
||||||
|
|
||||||
|
{/* AQUI: max-h-[130px] no mobile deixa a lista bem compacta */}
|
||||||
|
<CommandList className="max-h-[130px] md:max-h-[300px] overflow-y-auto">
|
||||||
|
<CommandEmpty>Nenhum paciente encontrado.</CommandEmpty>
|
||||||
|
<CommandGroup>
|
||||||
{patients.map((p) => (
|
{patients.map((p) => (
|
||||||
<SelectItem key={p.id} value={p.id}>{p.full_name}</SelectItem>
|
<CommandItem
|
||||||
|
key={p.id}
|
||||||
|
value={p.full_name}
|
||||||
|
onSelect={() => {
|
||||||
|
setSelectedPatient(p.id === selectedPatient ? "" : p.id);
|
||||||
|
setOpenPatientCombobox(false);
|
||||||
|
}}
|
||||||
|
className="text-xs md:text-sm py-1.5 md:py-2"
|
||||||
|
>
|
||||||
|
<Check
|
||||||
|
className={cn(
|
||||||
|
"mr-2 h-3 w-3 md:h-4 md:w-4",
|
||||||
|
selectedPatient === p.id ? "opacity-100" : "opacity-0"
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<span className="truncate">{p.full_name}</span>
|
||||||
|
</CommandItem>
|
||||||
))}
|
))}
|
||||||
</SelectContent>
|
</CommandGroup>
|
||||||
</Select>
|
</CommandList>
|
||||||
|
</Command>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div>
|
{/* COMBOBOX DE MÉDICO */}
|
||||||
<Label>Médico</Label>
|
<div className="space-y-2">
|
||||||
<Select value={selectedDoctor} onValueChange={setSelectedDoctor}>
|
<Label className="text-sm font-medium">Selecione o Médico</Label>
|
||||||
<SelectTrigger>
|
|
||||||
<SelectValue placeholder="Selecione o médico" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
{loadingDoctors ? (
|
|
||||||
<SelectItem value="loading" disabled>Carregando...</SelectItem>
|
|
||||||
) : (
|
|
||||||
doctors.map((d) => (
|
|
||||||
<SelectItem key={d.id} value={d.id}>
|
|
||||||
{d.full_name} — {d.specialty}
|
|
||||||
</SelectItem>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
<Popover open={openDoctorCombobox} onOpenChange={setOpenDoctorCombobox}>
|
||||||
<Label>Data</Label>
|
<PopoverTrigger asChild>
|
||||||
<div ref={calendarRef} className="rounded-lg border p-2">
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
role="combobox"
|
||||||
|
aria-expanded={openDoctorCombobox}
|
||||||
|
className="w-full justify-between"
|
||||||
|
disabled={loadingDoctors}
|
||||||
|
>
|
||||||
|
{loadingDoctors ? "Carregando..." : (
|
||||||
|
selectedDoctor
|
||||||
|
? doctors.find((doctor) => doctor.id === selectedDoctor)?.full_name
|
||||||
|
: "Buscar médico..."
|
||||||
|
)}
|
||||||
|
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||||
|
</Button>
|
||||||
|
</PopoverTrigger>
|
||||||
|
|
||||||
|
{/* AQUI: Configurações de largura e posicionamento corrigidos */}
|
||||||
|
<PopoverContent
|
||||||
|
className="w-[--radix-popover-trigger-width] min-w-0 p-0"
|
||||||
|
align="start"
|
||||||
|
side="bottom"
|
||||||
|
>
|
||||||
|
<Command>
|
||||||
|
<CommandInput placeholder="Procurar médico..." />
|
||||||
|
|
||||||
|
{/* AQUI: Altura reduzida no mobile */}
|
||||||
|
<CommandList className="max-h-[130px] md:max-h-[300px] overflow-y-auto">
|
||||||
|
<CommandEmpty>Nenhum médico encontrado.</CommandEmpty>
|
||||||
|
<CommandGroup>
|
||||||
|
{doctors.map((doctor) => (
|
||||||
|
<CommandItem
|
||||||
|
key={doctor.id}
|
||||||
|
value={doctor.full_name}
|
||||||
|
onSelect={() => {
|
||||||
|
setSelectedDoctor(doctor.id === selectedDoctor ? "" : doctor.id);
|
||||||
|
setOpenDoctorCombobox(false);
|
||||||
|
}}
|
||||||
|
className="text-xs md:text-sm py-1.5 md:py-2"
|
||||||
|
>
|
||||||
|
<Check
|
||||||
|
className={cn(
|
||||||
|
"mr-2 h-3 w-3 md:h-4 md:w-4",
|
||||||
|
selectedDoctor === doctor.id ? "opacity-100" : "opacity-0"
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<div className="flex flex-col truncate">
|
||||||
|
<span className="truncate font-medium">{doctor.full_name}</span>
|
||||||
|
<span className="text-[10px] md:text-xs text-muted-foreground truncate">{doctor.specialty}</span>
|
||||||
|
</div>
|
||||||
|
</CommandItem>
|
||||||
|
))}
|
||||||
|
</CommandGroup>
|
||||||
|
</CommandList>
|
||||||
|
</Command>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
|
||||||
|
<p className="text-xs text-muted-foreground mt-1">
|
||||||
|
Digite para filtrar por nome.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* BLOCO 2: CALENDÁRIO */}
|
||||||
|
<Card className="h-full border shadow-sm flex flex-col">
|
||||||
|
<CardHeader className="pb-3 border-b bg-muted/20">
|
||||||
|
<CardTitle className="text-base flex items-center gap-2">
|
||||||
|
<CalendarDays className="w-4 h-4 text-primary" />
|
||||||
|
Data Disponível
|
||||||
|
</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="flex-1 flex items-center justify-center pt-4 pb-4">
|
||||||
|
<div ref={calendarRef} className="flex justify-center w-full overflow-x-auto">
|
||||||
<CalendarShadcn
|
<CalendarShadcn
|
||||||
mode="single"
|
mode="single"
|
||||||
disabled={!selectedDoctor}
|
disabled={!selectedDoctor}
|
||||||
@ -410,52 +473,73 @@ try {
|
|||||||
const formatted = format(new Date(date.getTime() + 12 * 60 * 60 * 1000), "yyyy-MM-dd");
|
const formatted = format(new Date(date.getTime() + 12 * 60 * 60 * 1000), "yyyy-MM-dd");
|
||||||
setSelectedDate(formatted);
|
setSelectedDate(formatted);
|
||||||
}}
|
}}
|
||||||
|
className="rounded-md border p-3 w-fit"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
{/* BLOCO 3: OBSERVAÇÕES */}
|
||||||
<Label>Observações</Label>
|
<Card className="border shadow-sm">
|
||||||
|
<CardHeader className="pb-3 border-b bg-muted/20">
|
||||||
|
<CardTitle className="text-base flex items-center gap-2">
|
||||||
|
<StickyNote className="w-4 h-4 text-primary" />
|
||||||
|
Observações (Opcional)
|
||||||
|
</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="pt-4">
|
||||||
<Textarea
|
<Textarea
|
||||||
placeholder="Instruções para o médico..."
|
placeholder="Instruções especiais, sintomas ou motivos da consulta..."
|
||||||
value={notes}
|
value={notes}
|
||||||
onChange={(e) => setNotes(e.target.value)}
|
onChange={(e) => setNotes(e.target.value)}
|
||||||
className="mt-2"
|
rows={3}
|
||||||
|
className="resize-none w-full"
|
||||||
/>
|
/>
|
||||||
</div>
|
</CardContent>
|
||||||
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-3">
|
{/* == DIREITA == */}
|
||||||
<Card className="shadow-md rounded-xl bg-blue-50 border border-blue-200">
|
<div className="w-full">
|
||||||
<CardHeader>
|
<div className="xl:sticky xl:top-6">
|
||||||
<CardTitle className="text-blue-700">Resumo</CardTitle>
|
<Card className="border-2 border-primary shadow-lg h-full flex flex-col">
|
||||||
|
<CardHeader className="pb-4 border-b border-primary/20 bg-primary/5">
|
||||||
|
<CardTitle className="text-primary flex items-center gap-2 text-lg">
|
||||||
|
<User className="h-5 w-5" />
|
||||||
|
Resumo da Consulta
|
||||||
|
</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-2 text-gray-900 text-sm">
|
<CardContent className="pt-6 space-y-5 flex-1">
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div className="flex items-center gap-2">
|
<div className="grid grid-cols-2 gap-4 xl:grid-cols-1">
|
||||||
<User className="h-4 w-4 text-blue-600" />
|
<div className="space-y-1">
|
||||||
<div className="text-xs">
|
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Médico</p>
|
||||||
{selectedDoctor
|
<p className="text-sm font-semibold text-foreground break-words">
|
||||||
? doctors.find((d) => d.id === selectedDoctor)?.full_name
|
{selectedDoctor ? doctors.find((d) => d.id === selectedDoctor)?.full_name : "—"}
|
||||||
: "Médico"}
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<div className="space-y-1">
|
||||||
<div className="text-xs text-gray-600">
|
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Data</p>
|
||||||
{tipoConsulta} • {duracao} min
|
<p className="text-sm font-semibold text-foreground">
|
||||||
|
{selectedDate ? format(new Date(selectedDate + "T12:00:00"), "dd/MM/yyyy") : "—"}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2 pt-2">
|
||||||
<Label>Horário</Label>
|
<Label htmlFor="time-select" className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
|
||||||
<Select onValueChange={setSelectedTime} disabled={loadingSlots || availableTimes.length === 0}>
|
Horário da Sessão
|
||||||
<SelectTrigger>
|
</Label>
|
||||||
|
<Select
|
||||||
|
value={selectedTime}
|
||||||
|
onValueChange={setSelectedTime}
|
||||||
|
disabled={loadingSlots || availableTimes.length === 0}
|
||||||
|
>
|
||||||
|
<SelectTrigger id="time-select" className="bg-white w-full border-primary/30 focus:ring-primary">
|
||||||
<SelectValue
|
<SelectValue
|
||||||
placeholder={
|
placeholder={
|
||||||
loadingSlots
|
loadingSlots ? "Carregando..." : availableTimes.length === 0 ? "Selecione uma data" : "Escolha o horário"
|
||||||
? "Carregando horários..."
|
|
||||||
: availableTimes.length === 0
|
|
||||||
? "Nenhum horário disponível"
|
|
||||||
: "Selecione o horário"
|
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
@ -467,26 +551,29 @@ try {
|
|||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{notes && (
|
<div className="pt-4 border-t border-dashed space-y-2">
|
||||||
<div className="flex items-start gap-2 text-sm">
|
<div className="flex justify-between text-sm">
|
||||||
<StickyNote className="h-4 w-4" />
|
<span className="text-muted-foreground">Tipo:</span>
|
||||||
<div className="italic text-gray-700">{notes}</div>
|
<span className="font-medium capitalize">{tipoConsulta}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-between text-sm">
|
||||||
|
<span className="text-muted-foreground">Duração estimada:</span>
|
||||||
|
<span className="font-medium">{duracao} min</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<div className="flex gap-2">
|
<div className="pt-4 space-y-3 mt-auto">
|
||||||
<Button
|
<Button
|
||||||
type="submit"
|
type="submit"
|
||||||
className="w-full md:w-auto px-4 py-1.5 text-sm bg-blue-600 text-white hover:bg-blue-700"
|
onClick={handleSubmit}
|
||||||
|
className="w-full bg-primary hover:bg-primary/90 text-primary-foreground font-semibold shadow-md py-6 h-auto text-base transition-all"
|
||||||
disabled={!selectedDoctor || !selectedDate || !selectedTime}
|
disabled={!selectedDoctor || !selectedDate || !selectedTime}
|
||||||
>
|
>
|
||||||
Agendar
|
Confirmar Agendamento
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
variant="outline"
|
variant="ghost"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setSelectedDoctor("");
|
setSelectedDoctor("");
|
||||||
setSelectedDate("");
|
setSelectedDate("");
|
||||||
@ -494,15 +581,18 @@ try {
|
|||||||
setNotes("");
|
setNotes("");
|
||||||
setSelectedPatient("");
|
setSelectedPatient("");
|
||||||
}}
|
}}
|
||||||
className="px-3"
|
className="w-full text-muted-foreground hover:text-destructive"
|
||||||
>
|
>
|
||||||
Limpar
|
Limpar Formulário
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
{tooltip && (
|
{tooltip && (
|
||||||
<div
|
<div
|
||||||
@ -513,9 +603,11 @@ try {
|
|||||||
zIndex: 60,
|
zIndex: 60,
|
||||||
background: "rgba(0,0,0,0.85)",
|
background: "rgba(0,0,0,0.85)",
|
||||||
color: "white",
|
color: "white",
|
||||||
padding: "6px 8px",
|
padding: "6px 10px",
|
||||||
borderRadius: 6,
|
borderRadius: 6,
|
||||||
fontSize: 12,
|
fontSize: 12,
|
||||||
|
fontWeight: 500,
|
||||||
|
pointerEvents: "none",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{tooltip.text}
|
{tooltip.text}
|
||||||
|
|||||||
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-muted-foreground 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-primary/10 rounded-lg">
|
||||||
|
<p className="font-medium capitalize text-foreground">{weekdaysPT[day]}</p>
|
||||||
|
<div className="text-center">
|
||||||
|
{times.length > 0 ? (
|
||||||
|
times.map((t, i) => (
|
||||||
|
<p key={i} className="text-sm text-muted-foreground">
|
||||||
|
{formatTime(t.start)} <br /> {formatTime(t.end)}
|
||||||
|
</p>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<p className="text-sm text-muted-foreground italic">Sem horário</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -41,8 +41,10 @@ export interface ButtonProps
|
|||||||
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||||
({ className, variant, size, asChild = false, ...props }, ref) => {
|
({ className, variant, size, asChild = false, ...props }, ref) => {
|
||||||
const Comp = asChild ? Slot : 'button'
|
const Comp = asChild ? Slot : 'button'
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Comp
|
<Comp
|
||||||
|
data-slot="button"
|
||||||
className={cn(buttonVariants({ variant, size, className }))}
|
className={cn(buttonVariants({ variant, size, className }))}
|
||||||
ref={ref}
|
ref={ref}
|
||||||
{...props}
|
{...props}
|
||||||
|
|||||||
115
components/ui/filter-bar.tsx
Normal file
115
components/ui/filter-bar.tsx
Normal file
@ -0,0 +1,115 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import React from "react";
|
||||||
|
import { Search, Filter, X } from "lucide-react";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
|
||||||
|
export interface FilterOption {
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FilterConfig {
|
||||||
|
key: string; // O nome do estado que vai guardar esse valor (ex: 'specialty')
|
||||||
|
label: string; // O placeholder do select (ex: 'Especialidade')
|
||||||
|
options: FilterOption[] | string[]; // Opções do dropdown
|
||||||
|
}
|
||||||
|
|
||||||
|
interface FilterBarProps {
|
||||||
|
onSearch: (term: string) => void;
|
||||||
|
searchTerm: string;
|
||||||
|
searchPlaceholder?: string;
|
||||||
|
filters?: FilterConfig[];
|
||||||
|
activeFilters: Record<string, string>;
|
||||||
|
onFilterChange: (key: string, value: string) => void;
|
||||||
|
onClearFilters?: () => void;
|
||||||
|
className?: string;
|
||||||
|
children?: React.ReactNode; // Para botões extras (ex: "Novo Médico", paginação)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function FilterBar({
|
||||||
|
onSearch,
|
||||||
|
searchTerm,
|
||||||
|
searchPlaceholder = "Pesquisar...",
|
||||||
|
filters = [],
|
||||||
|
activeFilters,
|
||||||
|
onFilterChange,
|
||||||
|
onClearFilters,
|
||||||
|
children,
|
||||||
|
className,
|
||||||
|
}: FilterBarProps) {
|
||||||
|
|
||||||
|
// Verifica se tem algum filtro ativo para mostrar o botão de limpar
|
||||||
|
const hasActiveFilters =
|
||||||
|
searchTerm !== "" ||
|
||||||
|
Object.values(activeFilters).some(val => val !== "all" && val !== "");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={`flex flex-col md:flex-row items-start md:items-center gap-3 bg-card p-4 rounded-lg border ${className}`}>
|
||||||
|
|
||||||
|
{/* Barra de Pesquisa */}
|
||||||
|
<div className="relative w-full md:flex-1">
|
||||||
|
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||||
|
<Input
|
||||||
|
placeholder={searchPlaceholder}
|
||||||
|
value={searchTerm}
|
||||||
|
onChange={(e) => onSearch(e.target.value)}
|
||||||
|
className="pl-10 w-full bg-muted border-border focus:bg-card transition-colors"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Filtros Dinâmicos (Selects) */}
|
||||||
|
<div className="flex flex-wrap items-center gap-3 w-full md:w-auto">
|
||||||
|
{filters.map((filter) => (
|
||||||
|
<div key={filter.key} className="w-full sm:w-auto">
|
||||||
|
<Select
|
||||||
|
value={activeFilters[filter.key] || "all"}
|
||||||
|
onValueChange={(value) => onFilterChange(filter.key, value)}
|
||||||
|
>
|
||||||
|
<SelectTrigger className="w-full sm:w-[180px]">
|
||||||
|
<SelectValue placeholder={filter.label} />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="all">Todos: {filter.label}</SelectItem>
|
||||||
|
{filter.options.map((opt) => {
|
||||||
|
// Suporta tanto array de strings quanto array de objetos {label, value}
|
||||||
|
const value = typeof opt === 'string' ? opt : opt.value;
|
||||||
|
const label = typeof opt === 'string' ? opt : opt.label;
|
||||||
|
return (
|
||||||
|
<SelectItem key={value} value={value}>
|
||||||
|
{label}
|
||||||
|
</SelectItem>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{/* Botão de Limpar Filtros */}
|
||||||
|
{hasActiveFilters && onClearFilters && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={onClearFilters}
|
||||||
|
className="text-muted-foreground hover:text-destructive"
|
||||||
|
title="Limpar filtros"
|
||||||
|
>
|
||||||
|
<X className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Botões Extras (ex: Novo Médico, Paginação) passados como children */}
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -1,94 +1,145 @@
|
|||||||
'use client'
|
"use client";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter, DialogClose
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
} from "@/components/ui/dialog";
|
} from "@/components/ui/dialog";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
|
||||||
|
interface Paciente {
|
||||||
|
id: string;
|
||||||
|
nome: string;
|
||||||
|
telefone: string;
|
||||||
|
cidade: string;
|
||||||
|
estado: string;
|
||||||
|
email?: string;
|
||||||
|
birth_date?: string;
|
||||||
|
cpf?: string;
|
||||||
|
blood_type?: string;
|
||||||
|
weight_kg?: number;
|
||||||
|
height_m?: number;
|
||||||
|
street?: string;
|
||||||
|
number?: string;
|
||||||
|
complement?: string;
|
||||||
|
neighborhood?: string;
|
||||||
|
cep?: string;
|
||||||
|
[key: string]: any; // Para permitir outras propriedades se necessário
|
||||||
|
}
|
||||||
|
|
||||||
interface PatientDetailsModalProps {
|
interface PatientDetailsModalProps {
|
||||||
|
patient: Paciente | null;
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
patient: any;
|
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function PatientDetailsModal({ patient, isOpen, onClose }: PatientDetailsModalProps) {
|
export function PatientDetailsModal({
|
||||||
|
patient,
|
||||||
|
isOpen,
|
||||||
|
onClose,
|
||||||
|
}: PatientDetailsModalProps) {
|
||||||
if (!patient) return null;
|
if (!patient) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||||
<DialogContent className="sm:max-w-[600px]">
|
<DialogContent className="max-w-[95%] sm:max-w-lg max-h-[90vh] overflow-y-auto bg-card text-card-foreground border border-border">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>Detalhes do Paciente</DialogTitle>
|
<DialogTitle className="text-xl font-bold text-foreground">Detalhes do Paciente</DialogTitle>
|
||||||
<DialogDescription>Informações detalhadas sobre o paciente.</DialogDescription>
|
<DialogDescription className="text-muted-foreground">
|
||||||
|
Informações detalhadas sobre o paciente.
|
||||||
|
</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
<div className="grid gap-4 py-4">
|
|
||||||
<div className="grid grid-cols-2 gap-4">
|
<div className="space-y-4 py-2">
|
||||||
|
{/* Grid Principal */}
|
||||||
|
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Nome Completo</p>
|
<p className="font-semibold text-foreground">Nome Completo</p>
|
||||||
<p>{patient.nome}</p>
|
<p className="text-muted-foreground">{patient.nome}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* CORREÇÃO AQUI: Adicionado 'break-all' para quebrar o email */}
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold text-foreground">Email</p>
|
||||||
|
<p className="text-muted-foreground break-all">{patient.email || "N/A"}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold text-foreground">Telefone</p>
|
||||||
|
<p className="text-muted-foreground">{patient.telefone}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold text-foreground">Data de Nascimento</p>
|
||||||
|
<p className="text-muted-foreground">{patient.birth_date || "N/A"}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold text-foreground">CPF</p>
|
||||||
|
<p className="text-muted-foreground">{patient.cpf || "N/A"}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold text-foreground">Tipo Sanguíneo</p>
|
||||||
|
<p className="text-muted-foreground">{patient.blood_type || "N/A"}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold text-foreground">Peso (kg)</p>
|
||||||
|
<p className="text-muted-foreground">{patient.weight_kg || "0"}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold text-foreground">Altura (m)</p>
|
||||||
|
<p className="text-muted-foreground">{patient.height_m || "0"}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<hr className="border-border" />
|
||||||
|
|
||||||
|
{/* Seção de Endereço */}
|
||||||
|
<div>
|
||||||
|
<h4 className="font-semibold mb-3 text-foreground">Endereço</h4>
|
||||||
|
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold text-foreground">Rua</p>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
{patient.street && patient.street !== "N/A"
|
||||||
|
? `${patient.street}, ${patient.number || ""}`
|
||||||
|
: "N/A"}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Email</p>
|
<p className="font-semibold text-foreground">Complemento</p>
|
||||||
<p>{patient.email}</p>
|
<p className="text-muted-foreground">{patient.complement || "N/A"}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Telefone</p>
|
<p className="font-semibold text-foreground">Bairro</p>
|
||||||
<p>{patient.telefone}</p>
|
<p className="text-muted-foreground">{patient.neighborhood || "N/A"}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Data de Nascimento</p>
|
<p className="font-semibold text-foreground">Cidade</p>
|
||||||
<p>{patient.birth_date}</p>
|
<p className="text-muted-foreground">{patient.cidade || "N/A"}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">CPF</p>
|
<p className="font-semibold text-foreground">Estado</p>
|
||||||
<p>{patient.cpf}</p>
|
<p className="text-muted-foreground">{patient.estado || "N/A"}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Tipo Sanguíneo</p>
|
<p className="font-semibold text-foreground">CEP</p>
|
||||||
<p>{patient.blood_type}</p>
|
<p className="text-muted-foreground">{patient.cep || "N/A"}</p>
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Peso (kg)</p>
|
|
||||||
<p>{patient.weight_kg}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Altura (m)</p>
|
|
||||||
<p>{patient.height_m}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="border-t pt-4 mt-4">
|
|
||||||
<h3 className="font-semibold mb-2">Endereço</h3>
|
|
||||||
<div className="grid grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Rua</p>
|
|
||||||
<p>{`${patient.street}, ${patient.number}`}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Complemento</p>
|
|
||||||
<p>{patient.complement}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Bairro</p>
|
|
||||||
<p>{patient.neighborhood}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Cidade</p>
|
|
||||||
<p>{patient.cidade}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">Estado</p>
|
|
||||||
<p>{patient.estado}</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold">CEP</p>
|
|
||||||
<p>{patient.cep}</p>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
<DialogClose asChild>
|
<Button variant="secondary" onClick={onClose} className="w-full sm:w-auto">
|
||||||
<button type="button" className="px-4 py-2 bg-gray-200 rounded-md">Fechar</button>
|
Fechar
|
||||||
</DialogClose>
|
</Button>
|
||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|||||||
@ -2,7 +2,14 @@
|
|||||||
|
|
||||||
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
|
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
|
||||||
import { Button } from "@/components/ui/button";
|
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 {
|
import {
|
||||||
Popover,
|
Popover,
|
||||||
PopoverTrigger,
|
PopoverTrigger,
|
||||||
@ -26,6 +33,7 @@ interface Props {
|
|||||||
sidebarCollapsed: boolean;
|
sidebarCollapsed: boolean;
|
||||||
handleLogout: () => void;
|
handleLogout: () => void;
|
||||||
isActive: boolean;
|
isActive: boolean;
|
||||||
|
avatarUrl?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function SidebarUserSection({
|
export default function SidebarUserSection({
|
||||||
@ -33,14 +41,35 @@ export default function SidebarUserSection({
|
|||||||
sidebarCollapsed,
|
sidebarCollapsed,
|
||||||
handleLogout,
|
handleLogout,
|
||||||
isActive,
|
isActive,
|
||||||
|
avatarUrl,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
const menuItems: any[] = [
|
const menuItems: any[] = [
|
||||||
{ href: "/patient/schedule", icon: CalendarClock, label: "Agendar Consulta" },
|
{
|
||||||
{ href: "/patient/appointments", icon: CalendarCheck2, label: "Minhas Consultas" },
|
href: "/patient/schedule",
|
||||||
|
icon: CalendarClock,
|
||||||
|
label: "Agendar Consulta",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: "/patient/appointments",
|
||||||
|
icon: CalendarCheck2,
|
||||||
|
label: "Minhas Consultas",
|
||||||
|
},
|
||||||
{ href: "/patient/reports", icon: ClipboardPlus, label: "Meus Laudos" },
|
{ href: "/patient/reports", icon: ClipboardPlus, label: "Meus Laudos" },
|
||||||
{ href: "/patient/profile", icon: SquareUser, label: "Meus Dados" },
|
{ href: "/patient/profile", icon: SquareUser, label: "Meus Dados" },
|
||||||
]
|
];
|
||||||
|
|
||||||
|
// Função auxiliar para obter iniciais
|
||||||
|
const getInitials = (name: string) => {
|
||||||
|
if (!name) return "U";
|
||||||
|
return name
|
||||||
|
.split(" ")
|
||||||
|
.map((n) => n[0])
|
||||||
|
.slice(0, 2)
|
||||||
|
.join("")
|
||||||
|
.toUpperCase();
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="border-t p-4 mt-auto">
|
<div className="border-t p-4 mt-auto">
|
||||||
{/* POPUP DE INFORMAÇÕES DO USUÁRIO */}
|
{/* POPUP DE INFORMAÇÕES DO USUÁRIO */}
|
||||||
@ -48,26 +77,26 @@ export default function SidebarUserSection({
|
|||||||
<PopoverTrigger asChild>
|
<PopoverTrigger asChild>
|
||||||
<div
|
<div
|
||||||
className={`flex items-center space-x-3 mb-4 p-2 rounded-md transition-colors ${
|
className={`flex items-center space-x-3 mb-4 p-2 rounded-md transition-colors ${
|
||||||
isActive
|
isActive ? "cursor-pointer" : "cursor-default pointer-events-none"
|
||||||
? "cursor-pointer hover:bg-gray-100"
|
}`}
|
||||||
: "cursor-default pointer-events-none"
|
>
|
||||||
}`}>
|
|
||||||
<Avatar>
|
<Avatar>
|
||||||
<AvatarImage src="/placeholder.svg?height=40&width=40" />
|
<AvatarImage
|
||||||
<AvatarFallback>
|
src={avatarUrl}
|
||||||
{userData.user_metadata.full_name
|
alt={userData.user_metadata.full_name}
|
||||||
.split(" ")
|
className="object-cover"
|
||||||
.map((n) => n[0])
|
/>
|
||||||
.join("")}
|
<AvatarFallback className="text-black bg-gray-200 font-semibold">
|
||||||
|
{getInitials(userData.user_metadata.full_name)}
|
||||||
</AvatarFallback>
|
</AvatarFallback>
|
||||||
</Avatar>
|
</Avatar>
|
||||||
|
|
||||||
{!sidebarCollapsed && (
|
{!sidebarCollapsed && (
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<p className="text-sm font-medium text-gray-900 truncate">
|
<p className="text-sm font-medium text-white truncate">
|
||||||
{userData.user_metadata.full_name}
|
{userData.user_metadata.full_name}
|
||||||
</p>
|
</p>
|
||||||
<p className="text-xs text-gray-500 truncate">
|
<p className="text-xs text-white truncate">
|
||||||
{userData.app_metadata.user_role}
|
{userData.app_metadata.user_role}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@ -79,7 +108,7 @@ export default function SidebarUserSection({
|
|||||||
<PopoverContent
|
<PopoverContent
|
||||||
align="center"
|
align="center"
|
||||||
side="top"
|
side="top"
|
||||||
className="w-64 p-4 shadow-lg border bg-white"
|
className="w-64 p-4 shadow-2xl border-2 border-primary/20 bg-card text-card-foreground ring-1 ring-primary/10"
|
||||||
>
|
>
|
||||||
<nav>
|
<nav>
|
||||||
{menuItems.map((item) => {
|
{menuItems.map((item) => {
|
||||||
@ -90,8 +119,8 @@ export default function SidebarUserSection({
|
|||||||
<div
|
<div
|
||||||
className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${
|
className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${
|
||||||
isActive
|
isActive
|
||||||
? "bg-blue-50 text-blue-600 border-r-2 border-blue-600"
|
? "bg-primary/10 text-primary border-r-2 border-primary"
|
||||||
: "text-gray-600 hover:bg-gray-50"
|
: "text-foreground hover:bg-muted"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<Icon className="w-5 h-5 flex-shrink-0" />
|
<Icon className="w-5 h-5 flex-shrink-0" />
|
||||||
@ -105,21 +134,25 @@ export default function SidebarUserSection({
|
|||||||
</nav>
|
</nav>
|
||||||
</PopoverContent>
|
</PopoverContent>
|
||||||
</Popover>
|
</Popover>
|
||||||
|
|
||||||
{/* Botão de sair */}
|
{/* Botão de sair */}
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
className={
|
className={
|
||||||
sidebarCollapsed
|
sidebarCollapsed
|
||||||
? "w-full bg-transparent flex justify-center items-center p-2"
|
? "w-full bg-card text-foreground border-2 border-border flex justify-center items-center p-2 hover:bg-muted"
|
||||||
: "w-full bg-transparent"
|
: "w-full bg-card text-foreground border-2 border-border hover:bg-muted cursor-pointer"
|
||||||
}
|
}
|
||||||
onClick={handleLogout}
|
onClick={handleLogout}
|
||||||
>
|
>
|
||||||
<LogOut className={sidebarCollapsed ? "h-5 w-5" : "mr-2 h-4 w-4"} />
|
<LogOut
|
||||||
{sidebarCollapsed && "Sair"}
|
className={
|
||||||
|
sidebarCollapsed ? "h-5 w-5" : "mr-2 h-4 w-4"
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{!sidebarCollapsed && "Sair"}
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -18,7 +18,9 @@ interface UseAuthLayoutOptions {
|
|||||||
requiredRole?: string[];
|
requiredRole?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useAuthLayout({ requiredRole }: UseAuthLayoutOptions = {}) {
|
export function useAuthLayout(
|
||||||
|
{ requiredRole }: UseAuthLayoutOptions = {}
|
||||||
|
) {
|
||||||
const [user, setUser] = useState<UserLayoutData | null>(null);
|
const [user, setUser] = useState<UserLayoutData | null>(null);
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@ -28,8 +30,16 @@ export function useAuthLayout({ requiredRole }: UseAuthLayoutOptions = {}) {
|
|||||||
try {
|
try {
|
||||||
const fullUserData = await usersService.getMe();
|
const fullUserData = await usersService.getMe();
|
||||||
|
|
||||||
if (!fullUserData.roles.some((role) => requiredRole?.includes(role))) {
|
// só verifica papel se requiredRole existir
|
||||||
console.error(`Acesso negado. Requer perfil '${requiredRole}', mas o usuário tem '${fullUserData.roles.join(", ")}'.`);
|
if (
|
||||||
|
requiredRole &&
|
||||||
|
!fullUserData.roles.some((role: string) =>
|
||||||
|
requiredRole.includes(role)
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
console.error(
|
||||||
|
`Acesso negado. Requer perfil '${requiredRole}', mas o usuário tem '${fullUserData.roles.join(", ")}'.`
|
||||||
|
);
|
||||||
toast({
|
toast({
|
||||||
title: "Acesso Negado",
|
title: "Acesso Negado",
|
||||||
description: "Você não tem permissão para acessar esta página.",
|
description: "Você não tem permissão para acessar esta página.",
|
||||||
@ -40,10 +50,9 @@ export function useAuthLayout({ requiredRole }: UseAuthLayoutOptions = {}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const avatarPath = fullUserData.profile.avatar_url;
|
const avatarPath = fullUserData.profile.avatar_url;
|
||||||
|
const avatarFullUrl = avatarPath
|
||||||
// *** A CORREÇÃO ESTÁ AQUI ***
|
? `https://yuanqfswhberkoevtmfr.supabase.co/storage/v1/object/public/avatars/${avatarPath}`
|
||||||
// Adicionamos o nome do bucket 'avatars' na URL final.
|
: undefined;
|
||||||
const avatarFullUrl = avatarPath ? `https://yuanqfswhberkoevtmfr.supabase.co/storage/v1/object/public/avatars/${avatarPath}` : undefined;
|
|
||||||
|
|
||||||
setUser({
|
setUser({
|
||||||
id: fullUserData.user.id,
|
id: fullUserData.user.id,
|
||||||
@ -51,7 +60,7 @@ export function useAuthLayout({ requiredRole }: UseAuthLayoutOptions = {}) {
|
|||||||
email: fullUserData.user.email,
|
email: fullUserData.user.email,
|
||||||
roles: fullUserData.roles,
|
roles: fullUserData.roles,
|
||||||
avatar_url: avatarPath,
|
avatar_url: avatarPath,
|
||||||
avatarFullUrl: avatarFullUrl,
|
avatarFullUrl,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Falha na autenticação do layout:", error);
|
console.error("Falha na autenticação do layout:", error);
|
||||||
@ -62,7 +71,7 @@ export function useAuthLayout({ requiredRole }: UseAuthLayoutOptions = {}) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
fetchUserData();
|
fetchUserData();
|
||||||
}, [router, requiredRole]);
|
}, [router]); // não depende mais de requiredRole
|
||||||
|
|
||||||
return { user, isLoading };
|
return { user, isLoading };
|
||||||
}
|
}
|
||||||
|
|||||||
94
lib/normalization.ts
Normal file
94
lib/normalization.ts
Normal file
@ -0,0 +1,94 @@
|
|||||||
|
// lib/normalization.ts
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mapa de normalização.
|
||||||
|
* A chave é o termo "sujo" (em minúsculo) e o valor é o termo "Canônico" (Bonito).
|
||||||
|
*/
|
||||||
|
const SPECIALTY_MAPPING: Record<string, string> = {
|
||||||
|
// --- Cardiologia ---
|
||||||
|
"cardiologista": "Cardiologia",
|
||||||
|
"cardio": "Cardiologia",
|
||||||
|
"cardiologia": "Cardiologia",
|
||||||
|
|
||||||
|
// --- Dermatologia ---
|
||||||
|
"dermatologista": "Dermatologia",
|
||||||
|
"dermato": "Dermatologia",
|
||||||
|
"dermatologia": "Dermatologia",
|
||||||
|
|
||||||
|
// --- Ortopedia ---
|
||||||
|
"ortopedista": "Ortopedia",
|
||||||
|
"ortopedia": "Ortopedia",
|
||||||
|
|
||||||
|
// --- Ginecologia ---
|
||||||
|
"ginecologista": "Ginecologia",
|
||||||
|
"ginecologia": "Ginecologia",
|
||||||
|
"ginecologistaa": "Ginecologia", // Erro de digitação comum
|
||||||
|
"gineco": "Ginecologia",
|
||||||
|
|
||||||
|
// --- Pediatria ---
|
||||||
|
"pediatra": "Pediatria",
|
||||||
|
"pediatria": "Pediatria",
|
||||||
|
|
||||||
|
// --- Clínica Geral (Onde estava o erro) ---
|
||||||
|
"clinico geral": "Clínica Geral",
|
||||||
|
"clínico geral": "Clínica Geral",
|
||||||
|
"clinica geral": "Clínica Geral",
|
||||||
|
"clínica geral": "Clínica Geral", // <--- ADICIONADO
|
||||||
|
"geral": "Clínica Geral",
|
||||||
|
"medico geral": "Clínica Geral",
|
||||||
|
"médico geral": "Clínica Geral",
|
||||||
|
|
||||||
|
// --- Neurologia ---
|
||||||
|
"neurologista": "Neurologia",
|
||||||
|
"neurologia": "Neurologia",
|
||||||
|
"neuro": "Neurologia",
|
||||||
|
"neurocirurgiao": "Neurocirurgia",
|
||||||
|
"neurocirurgião": "Neurocirurgia",
|
||||||
|
|
||||||
|
// --- Limpeza de Lixo / Outros ---
|
||||||
|
"asdw": "Outros",
|
||||||
|
"teste": "Outros",
|
||||||
|
"n/a": "Não Informado", // <--- Transforma o "N/A" da imagem
|
||||||
|
"na": "Não Informado",
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Recebe uma especialidade suja e retorna a versão limpa.
|
||||||
|
*/
|
||||||
|
export function normalizeSpecialty(raw: string | null | undefined): string {
|
||||||
|
if (!raw) return "Não Informado";
|
||||||
|
|
||||||
|
// Remove espaços extras e joga para minúsculo
|
||||||
|
const lower = raw.trim().toLowerCase();
|
||||||
|
|
||||||
|
// Se for uma string vazia ou traço
|
||||||
|
if (lower === "" || lower === "-") return "Não Informado";
|
||||||
|
|
||||||
|
// Verifica no mapa
|
||||||
|
if (SPECIALTY_MAPPING[lower]) {
|
||||||
|
return SPECIALTY_MAPPING[lower];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback: Capitaliza a primeira letra de cada palavra
|
||||||
|
// Ex: "cirurgia plastica" -> "Cirurgia Plastica"
|
||||||
|
return lower.replace(/\b\w/g, (l) => l.toUpperCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extrai uma lista única de especialidades normalizadas.
|
||||||
|
*/
|
||||||
|
export function getUniqueSpecialties(items: any[]): string[] {
|
||||||
|
const specialties = new Set<string>();
|
||||||
|
|
||||||
|
items.forEach(item => {
|
||||||
|
// Normaliza antes de adicionar ao Set
|
||||||
|
const normalized = normalizeSpecialty(item.specialty);
|
||||||
|
|
||||||
|
// Só adiciona se não for "Não Informado" ou "Outros" (Opcional: remova o if se quiser mostrar tudo)
|
||||||
|
if (normalized && normalized !== "Não Informado") {
|
||||||
|
specialties.add(normalized);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return Array.from(specialties).sort();
|
||||||
|
}
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 45 KiB After Width: | Height: | Size: 30 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 48 KiB After Width: | Height: | Size: 33 KiB |
@ -2,7 +2,11 @@ import { api } from "./api.mjs";
|
|||||||
|
|
||||||
export const patientsService = {
|
export const patientsService = {
|
||||||
list: () => api.get("/rest/v1/patients"),
|
list: () => api.get("/rest/v1/patients"),
|
||||||
getById: (id) => api.get(`/rest/v1/patients?id=eq.${id}`),
|
getById: (id) => {
|
||||||
|
console.log("getById chamado", id);
|
||||||
|
return api.get(`/rest/v1/patients?id=eq.${id}`);
|
||||||
|
},
|
||||||
|
|
||||||
create: (data) => api.post("/rest/v1/patients", data),
|
create: (data) => api.post("/rest/v1/patients", data),
|
||||||
update: (id, data) => api.patch(`/rest/v1/patients?id=eq.${id}`, data),
|
update: (id, data) => api.patch(`/rest/v1/patients?id=eq.${id}`, data),
|
||||||
delete: (id) => api.delete(`/rest/v1/patients?id=eq.${id}`),
|
delete: (id) => api.delete(`/rest/v1/patients?id=eq.${id}`),
|
||||||
|
|||||||
@ -9,7 +9,7 @@ export const reportsApi = {
|
|||||||
return data;
|
return data;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to fetch reports:", error);
|
console.error("Failed to fetch reports:", error);
|
||||||
return [];
|
throw error;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
getReportById: async (reportId) => {
|
getReportById: async (reportId) => {
|
||||||
|
|||||||
@ -3,6 +3,7 @@ import { api } from "./api.mjs";
|
|||||||
export const usersService = {
|
export const usersService = {
|
||||||
// Função getMe corrigida para chamar a si mesma pelo nome
|
// Função getMe corrigida para chamar a si mesma pelo nome
|
||||||
async getMe() {
|
async getMe() {
|
||||||
|
console.log("getMe chamado");
|
||||||
const sessionData = await api.getSession();
|
const sessionData = await api.getSession();
|
||||||
if (!sessionData?.id) {
|
if (!sessionData?.id) {
|
||||||
console.error("Sessão não encontrada ou usuário sem ID.", sessionData);
|
console.error("Sessão não encontrada ou usuário sem ID.", sessionData);
|
||||||
@ -21,6 +22,14 @@ export const usersService = {
|
|||||||
return await api.post(`/functions/v1/create-user-with-password`, data);
|
return await api.post(`/functions/v1/create-user-with-password`, data);
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// --- NOVA FUNÇÃO ADICIONADA AQUI ---
|
||||||
|
// Esta função chama o endpoint público de registro de paciente.
|
||||||
|
async registerPatient(data) {
|
||||||
|
// POR QUÊ? Este endpoint é público e não requer token JWT, resolvendo o erro 401.
|
||||||
|
return await api.post("/functions/v1/register-patient", data);
|
||||||
|
},
|
||||||
|
// --- FIM DA NOVA FUNÇÃO ---
|
||||||
|
|
||||||
async getMeSimple() {
|
async getMeSimple() {
|
||||||
return await api.post(`/functions/v1/user-info`);
|
return await api.post(`/functions/v1/user-info`);
|
||||||
},
|
},
|
||||||
@ -35,8 +44,7 @@ export const usersService = {
|
|||||||
isManager: role?.role === "gestor",
|
isManager: role?.role === "gestor",
|
||||||
isDoctor: role?.role === "medico",
|
isDoctor: role?.role === "medico",
|
||||||
isSecretary: role?.role === "secretaria",
|
isSecretary: role?.role === "secretaria",
|
||||||
isAdminOrManager:
|
isAdminOrManager: role?.role === "admin" || role?.role === "gestor" ? true : false,
|
||||||
role?.role === "admin" || role?.role === "gestor" ? true : false,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@ -64,37 +72,28 @@ export const usersService = {
|
|||||||
async resetPassword(email) {
|
async resetPassword(email) {
|
||||||
if (!email) throw new Error("Email é obrigatório para resetar a senha.");
|
if (!email) throw new Error("Email é obrigatório para resetar a senha.");
|
||||||
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(
|
const res = await fetch(`${process.env.NEXT_PUBLIC_SUPABASE_URL}/auth/v1/recover`, {
|
||||||
`${process.env.NEXT_PUBLIC_SUPABASE_URL}/auth/v1/recover`,
|
|
||||||
{
|
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
apikey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
|
apikey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
|
||||||
},
|
},
|
||||||
body: JSON.stringify({ email }),
|
body: JSON.stringify({ email }),
|
||||||
}
|
});
|
||||||
);
|
|
||||||
|
|
||||||
|
|
||||||
const data = await res.json().catch(() => ({}));
|
const data = await res.json().catch(() => ({}));
|
||||||
|
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
console.error("Erro no resetPassword:", res.status, data);
|
console.error("Erro no resetPassword:", res.status, data);
|
||||||
throw new Error(`Erro ${res.status}: ${data.message || "Falha ao resetar senha."}`);
|
throw new Error(`Erro ${res.status}: ${data.message || "Falha ao resetar senha."}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
console.log("✅ Reset de senha:", data);
|
console.log("✅ Reset de senha:", data);
|
||||||
return data;
|
return data;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("❌ Erro na chamada resetPassword:", err);
|
console.error("❌ Erro na chamada resetPassword:", err);
|
||||||
throw new Error(err.message || "Erro inesperado na recuperação de senha.");
|
throw new Error(err.message || "Erro inesperado na recuperação de senha.");
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user