Merge branch 'Stage' of https://github.com/m1guelmcf/MedConnect into consulta-ordem
This commit is contained in:
commit
83e0814293
@ -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";
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -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}
|
||||||
|
|||||||
@ -29,6 +29,7 @@ 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 Availability = {
|
type Availability = {
|
||||||
id: string;
|
id: string;
|
||||||
@ -165,20 +166,17 @@ export default function PatientDashboard() {
|
|||||||
);
|
);
|
||||||
setAvailability(filteredAvail);
|
setAvailability(filteredAvail);
|
||||||
|
|
||||||
// Busca exceções
|
// Busca exceções
|
||||||
const exceptionsList = await exceptionsService.list();
|
const exceptionsList = await exceptionsService.list();
|
||||||
const filteredExc = exceptionsList.filter(
|
const filteredExc = exceptionsList.filter((exc: { doctor_id: string }) => exc.doctor_id === doctor?.id);
|
||||||
(exc: { doctor_id: string }) => exc.doctor_id === doctor?.id
|
setExceptions(filteredExc);
|
||||||
);
|
} catch (e: any) {
|
||||||
console.log(exceptionsList);
|
alert(`${e?.error} ${e?.message}`);
|
||||||
setExceptions(filteredExc);
|
}
|
||||||
} catch (e: any) {
|
};
|
||||||
alert(`${e?.error} ${e?.message}`);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
fetchData();
|
fetchData();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// Função auxiliar para filtrar o id do doctor correspondente ao user logado
|
// 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[]) {
|
||||||
@ -320,82 +318,42 @@ export default function PatientDashboard() {
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Próximas Consultas</CardTitle>
|
<CardTitle>Próximas Consultas</CardTitle>
|
||||||
<CardDescription>Suas consultas agendadas</CardDescription>
|
<CardDescription>Suas consultas agendadas</CardDescription>
|
||||||
</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-blue-50 rounded-lg">
|
||||||
<div>
|
<div>
|
||||||
<p className="font-medium">Dr. João Santos</p>
|
<p className="font-medium">Dr. João Santos</p>
|
||||||
<p className="text-sm text-gray-600">Cardiologia</p>
|
<p className="text-sm text-gray-600">Cardiologia</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-right">
|
<div className="text-right">
|
||||||
<p className="font-medium">02 out</p>
|
<p className="font-medium">02 out</p>
|
||||||
<p className="text-sm text-gray-600">14:30</p>
|
<p className="text-sm text-gray-600">14:30</p>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<div className="grid md:grid-cols-1 gap-6">
|
||||||
</CardContent>
|
<Card>
|
||||||
</Card>
|
<CardHeader>
|
||||||
</div>
|
<CardTitle>Horário Semanal</CardTitle>
|
||||||
<div className="grid md:grid-cols-1 gap-6">
|
<CardDescription>Confira rapidamente a sua disponibilidade da semana</CardDescription>
|
||||||
<Card>
|
</CardHeader>
|
||||||
<CardHeader>
|
<CardContent>{loggedDoctor && <WeeklyScheduleCard doctorId={loggedDoctor.id} />}</CardContent>
|
||||||
<CardTitle>Horário Semanal</CardTitle>
|
</Card>
|
||||||
<CardDescription>
|
</div>
|
||||||
Confira rapidamente a sua disponibilidade da semana
|
<div className="grid md:grid-cols-1 gap-6">
|
||||||
</CardDescription>
|
<Card>
|
||||||
</CardHeader>
|
<CardHeader>
|
||||||
<CardContent className="space-y-4 grid md:grid-cols-7 gap-2">
|
<CardTitle>Exceções</CardTitle>
|
||||||
{[
|
<CardDescription>Bloqueios e liberações eventuais de agenda</CardDescription>
|
||||||
"sunday",
|
</CardHeader>
|
||||||
"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>
|
|
||||||
</div>
|
|
||||||
<div className="grid md:grid-cols-1 gap-6">
|
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle>Exceções</CardTitle>
|
|
||||||
<CardDescription>
|
|
||||||
Bloqueios e liberações eventuais de agenda
|
|
||||||
</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
|
|
||||||
<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 ? (
|
||||||
@ -411,75 +369,47 @@ export default function PatientDashboard() {
|
|||||||
const startTime = formatTime(ex.start_time);
|
const startTime = formatTime(ex.start_time);
|
||||||
const endTime = formatTime(ex.end_time);
|
const endTime = formatTime(ex.end_time);
|
||||||
|
|
||||||
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-blue-50 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-gray-600">{startTime && endTime ? `${startTime} - ${endTime}` : "Dia todo"}</p>
|
||||||
{startTime && endTime
|
</div>
|
||||||
? `${startTime} - ${endTime}`
|
<div className="text-center mt-2">
|
||||||
: "Dia todo"}
|
<p className={`text-sm font-medium ${ex.kind === "bloqueio" ? "text-red-600" : "text-green-600"}`}>{ex.kind === "bloqueio" ? "Bloqueio" : "Liberação"}</p>
|
||||||
</p>
|
<p className="text-xs text-gray-500 italic">{ex.reason || "Sem motivo especificado"}</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-center mt-2">
|
<div>
|
||||||
<p
|
<Button className="text-red-600" variant="outline" onClick={() => openDeleteDialog(String(ex.id))}>
|
||||||
className={`text-sm font-medium ${
|
<Trash2></Trash2>
|
||||||
ex.kind === "bloqueio"
|
</Button>
|
||||||
? "text-red-600"
|
</div>
|
||||||
: "text-green-600"
|
</div>
|
||||||
}`}
|
</div>
|
||||||
>
|
);
|
||||||
{ex.kind === "bloqueio" ? "Bloqueio" : "Liberação"}
|
})
|
||||||
</p>
|
) : (
|
||||||
<p className="text-xs text-gray-500 italic">
|
<p className="text-sm text-gray-400 italic col-span-7 text-center">Nenhuma exceção registrada.</p>
|
||||||
{ex.reason || "Sem motivo especificado"}
|
)}
|
||||||
</p>
|
</CardContent>
|
||||||
</div>
|
</Card>
|
||||||
<div>
|
</div>
|
||||||
<Button
|
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||||
className="text-red-600"
|
<AlertDialogContent>
|
||||||
variant="outline"
|
<AlertDialogHeader>
|
||||||
onClick={() => openDeleteDialog(String(ex.id))}
|
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
|
||||||
>
|
<AlertDialogDescription>Tem certeza que deseja excluir esta exceção? Esta ação não pode ser desfeita.</AlertDialogDescription>
|
||||||
<Trash2></Trash2>
|
</AlertDialogHeader>
|
||||||
</Button>
|
<AlertDialogFooter>
|
||||||
</div>
|
<AlertDialogCancel>Cancelar</AlertDialogCancel>
|
||||||
</div>
|
<AlertDialogAction onClick={() => exceptionToDelete && handleDeleteException(exceptionToDelete)} className="bg-red-600 hover:bg-red-700">
|
||||||
</div>
|
Excluir
|
||||||
);
|
</AlertDialogAction>
|
||||||
})
|
</AlertDialogFooter>
|
||||||
) : (
|
</AlertDialogContent>
|
||||||
<p className="text-sm text-gray-400 italic col-span-7 text-center">
|
</AlertDialog>
|
||||||
Nenhuma exceção registrada.
|
</div>
|
||||||
</p>
|
</Sidebar>
|
||||||
)}
|
);
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
|
||||||
<AlertDialogContent>
|
|
||||||
<AlertDialogHeader>
|
|
||||||
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
|
|
||||||
<AlertDialogDescription>
|
|
||||||
Tem certeza que deseja excluir esta exceção? Esta ação não pode
|
|
||||||
ser desfeita.
|
|
||||||
</AlertDialogDescription>
|
|
||||||
</AlertDialogHeader>
|
|
||||||
<AlertDialogFooter>
|
|
||||||
<AlertDialogCancel>Cancelar</AlertDialogCancel>
|
|
||||||
<AlertDialogAction
|
|
||||||
onClick={() =>
|
|
||||||
exceptionToDelete && handleDeleteException(exceptionToDelete)
|
|
||||||
}
|
|
||||||
className="bg-red-600 hover:bg-red-700"
|
|
||||||
>
|
|
||||||
Excluir
|
|
||||||
</AlertDialogAction>
|
|
||||||
</AlertDialogFooter>
|
|
||||||
</AlertDialogContent>
|
|
||||||
</AlertDialog>
|
|
||||||
</div>
|
|
||||||
</Sidebar>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -218,36 +218,36 @@ export default function AvailabilityPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Mapa de tradução
|
// Mapa de tradução
|
||||||
const weekdaysPT: Record<string, string> = {
|
const weekdaysPT: Record<string, string> = {
|
||||||
sunday: "Domingo",
|
sunday: "Domingo",
|
||||||
monday: "Segunda",
|
monday: "Segunda",
|
||||||
tuesday: "Terça",
|
tuesday: "Terça",
|
||||||
wednesday: "Quarta",
|
wednesday: "Quarta",
|
||||||
thursday: "Quinta",
|
thursday: "Quinta",
|
||||||
friday: "Sexta",
|
friday: "Sexta",
|
||||||
saturday: "Sábado",
|
saturday: "Sábado",
|
||||||
};
|
};
|
||||||
const fetchData = async () => {
|
const fetchData = async () => {
|
||||||
try {
|
try {
|
||||||
const loggedUser = await usersService.getMe();
|
const loggedUser = await usersService.getMe();
|
||||||
const doctorList = await doctorsService.list();
|
const doctorList = await doctorsService.list();
|
||||||
setUserData(loggedUser);
|
setUserData(loggedUser);
|
||||||
const doctor = findDoctorById(loggedUser.user.id, doctorList);
|
const doctor = findDoctorById(loggedUser.user.id, doctorList);
|
||||||
setDoctorId(doctor?.id);
|
setDoctorId(doctor?.id);
|
||||||
console.log(doctor);
|
console.log(doctor);
|
||||||
// Busca disponibilidade
|
// Busca disponibilidade
|
||||||
const availabilityList = await AvailabilityService.list();
|
const availabilityList = await AvailabilityService.list();
|
||||||
|
|
||||||
// Filtra já com a variável local
|
// Filtra já com a variável local
|
||||||
const filteredAvail = availabilityList.filter(
|
const filteredAvail = availabilityList.filter(
|
||||||
(disp: { doctor_id: string }) => disp.doctor_id === doctor?.id
|
(disp: { doctor_id: string }) => disp.doctor_id === doctor?.id
|
||||||
);
|
);
|
||||||
setAvailability(filteredAvail);
|
setAvailability(filteredAvail);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
alert(`${e?.error} ${e?.message}`);
|
alert(`${e?.error} ${e?.message}`);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchData();
|
fetchData();
|
||||||
@ -320,20 +320,21 @@ export default function AvailabilityPage() {
|
|||||||
}
|
}
|
||||||
} catch {}
|
} catch {}
|
||||||
|
|
||||||
toast({
|
toast({
|
||||||
title: "Sucesso",
|
title: "Sucesso",
|
||||||
description: message,
|
description: message,
|
||||||
});
|
});
|
||||||
router.push("#"); // adicionar página para listar a disponibilidade
|
router.push("#"); // adicionar página para listar a disponibilidade
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
toast({
|
toast({
|
||||||
title: "Erro",
|
title: "Erro",
|
||||||
description: err?.message || "Não foi possível criar a disponibilidade",
|
description: err?.message || "Não foi possível criar a disponibilidade",
|
||||||
});
|
});
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoading(false);
|
fetchData()
|
||||||
}
|
setIsLoading(false);
|
||||||
};
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const openDeleteDialog = (
|
const openDeleteDialog = (
|
||||||
schedule: { start: string; end: string },
|
schedule: { start: string; end: string },
|
||||||
@ -343,38 +344,35 @@ export default function AvailabilityPage() {
|
|||||||
setDeleteDialogOpen(true);
|
setDeleteDialogOpen(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDeleteAvailability = async (AvailabilityId: string) => {
|
const handleDeleteAvailability = async (AvailabilityId: string) => {
|
||||||
try {
|
try {
|
||||||
const res = await AvailabilityService.delete(AvailabilityId);
|
const res = await AvailabilityService.delete(AvailabilityId);
|
||||||
|
|
||||||
let message = "Disponibilidade deletada com sucesso";
|
let message = "Disponibilidade deletada com sucesso";
|
||||||
try {
|
try {
|
||||||
if (res) {
|
if (res) {
|
||||||
throw new Error(
|
throw new Error(`${res.error} ${res.message}` || "A API retornou erro");
|
||||||
`${res.error} ${res.message}` || "A API retornou erro"
|
} else {
|
||||||
);
|
console.log(message);
|
||||||
} else {
|
}
|
||||||
console.log(message);
|
} catch {}
|
||||||
}
|
|
||||||
} catch {}
|
toast({
|
||||||
|
title: "Sucesso",
|
||||||
toast({
|
description: message,
|
||||||
title: "Sucesso",
|
});
|
||||||
description: message,
|
|
||||||
});
|
setAvailability((prev: Availability[]) => prev.filter((p) => String(p.id) !== String(AvailabilityId)));
|
||||||
|
} catch (e: any) {
|
||||||
setAvailability((prev: Availability[]) =>
|
toast({
|
||||||
prev.filter((p) => String(p.id) !== String(AvailabilityId))
|
title: "Erro",
|
||||||
);
|
description: e?.message || "Não foi possível deletar a disponibilidade",
|
||||||
} catch (e: any) {
|
});
|
||||||
toast({
|
}
|
||||||
title: "Erro",
|
fetchData()
|
||||||
description: e?.message || "Não foi possível deletar a disponibilidade",
|
setDeleteDialogOpen(false);
|
||||||
});
|
setSelectedAvailability(null);
|
||||||
}
|
};
|
||||||
setDeleteDialogOpen(false);
|
|
||||||
setSelectedAvailability(null);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Sidebar>
|
<Sidebar>
|
||||||
@ -542,142 +540,99 @@ export default function AvailabilityPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* **AJUSTE DE RESPONSIVIDADE: BOTÕES DE AÇÃO** */}
|
{/* **AJUSTE DE RESPONSIVIDADE: BOTÕES DE AÇÃO** */}
|
||||||
{/* Alinha à direita em telas maiores e empilha (com o botão primário no final) em telas menores */}
|
{/* Alinha à direita em telas maiores e empilha (com o botão primário no final) em telas menores */}
|
||||||
{/* Alteração aqui: Adicionado w-full aos Links e Buttons para ocuparem a largura total em telas pequenas */}
|
{/* Alteração aqui: Adicionado w-full aos Links e Buttons para ocuparem a largura total em telas pequenas */}
|
||||||
<div className="flex flex-col-reverse sm:flex-row sm:justify-between gap-4">
|
<div className="flex flex-col-reverse sm:flex-row sm:justify-between gap-4">
|
||||||
<Link
|
<Link href="/doctor/disponibilidade/excecoes" className="w-full sm:w-auto">
|
||||||
href="/doctor/disponibilidade/excecoes"
|
<Button variant="default" className="w-full sm:w-auto">Adicionar Exceção</Button>
|
||||||
className="w-full sm:w-auto"
|
</Link>
|
||||||
>
|
<div className="flex flex-col sm:flex-row gap-4 w-full sm:w-auto"> {/* Ajustado para empilhar os botões Cancelar e Salvar em telas pequenas */}
|
||||||
<Button
|
<Link href="/doctor/dashboard" className="w-full sm:w-auto">
|
||||||
variant="default"
|
<Button variant="outline" className="w-full sm:w-auto">Cancelar</Button>
|
||||||
className="w-full sm:w-auto bg-blue-600 hover:bg-blue-700 text-white cursor-pointer"
|
</Link>
|
||||||
>
|
<Button type="submit" className="bg-green-600 hover:bg-green-700 w-full sm:w-auto">
|
||||||
Adicionar Exceção
|
Salvar Disponibilidade
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</div>
|
||||||
<div className="flex flex-col sm:flex-row gap-4 w-full sm:w-auto">
|
|
||||||
{" "}
|
|
||||||
{/* Ajustado para empilhar os botões Cancelar e Salvar em telas pequenas */}
|
|
||||||
<Link href="/doctor/dashboard" className="w-full sm:w-auto">
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
className="w-full sm:w-auto cursor-pointer"
|
|
||||||
>
|
|
||||||
Cancelar
|
|
||||||
</Button>
|
|
||||||
</Link>
|
|
||||||
<Button
|
|
||||||
type="submit"
|
|
||||||
className="bg-blue-600 hover:bg-blue-700 w-full sm:w-auto cursor-pointer"
|
|
||||||
>
|
|
||||||
Salvar Disponibilidade
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
{/* **AJUSTE DE RESPONSIVIDADE: CARD DE HORÁRIO SEMANAL** */}
|
|
||||||
<div>
|
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle>Horário Semanal</CardTitle>
|
|
||||||
<CardDescription>
|
|
||||||
Confira ou altere a sua disponibilidade da semana
|
|
||||||
</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
{/* Define um grid responsivo para os dias da semana (1 coluna em móvel, 2 em pequeno, 3 em médio e 7 em telas grandes) */}
|
|
||||||
<CardContent className="space-y-4 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-7 gap-2">
|
|
||||||
{[
|
|
||||||
"sunday",
|
|
||||||
"monday",
|
|
||||||
"tuesday",
|
|
||||||
"wednesday",
|
|
||||||
"thursday",
|
|
||||||
"friday",
|
|
||||||
"saturday",
|
|
||||||
].map((day) => {
|
|
||||||
const times = schedule[day] || [];
|
|
||||||
return (
|
|
||||||
<div key={day} className="space-y-4">
|
|
||||||
<div className="flex flex-col items-center justify-between p-3 bg-blue-50 rounded-lg h-full">
|
|
||||||
<p className="font-medium capitalize text-center mb-2">
|
|
||||||
{weekdaysPT[day]}
|
|
||||||
</p>
|
|
||||||
<div className="text-center w-full">
|
|
||||||
{times.length > 0 ? (
|
|
||||||
times.map((t, i) => (
|
|
||||||
<div key={i}>
|
|
||||||
<DropdownMenu>
|
|
||||||
<DropdownMenuTrigger asChild>
|
|
||||||
<p className="text-sm text-gray-600 cursor-pointer p-1 rounded hover:text-accent-foreground hover:bg-gray-200 transition-colors duration-150">
|
|
||||||
{formatTime(t.start)} - {formatTime(t.end)}
|
|
||||||
</p>
|
|
||||||
</DropdownMenuTrigger>
|
|
||||||
<DropdownMenuContent align="end">
|
|
||||||
<DropdownMenuItem
|
|
||||||
onClick={() => handleOpenModal(t, day)}
|
|
||||||
>
|
|
||||||
<Edit className="w-4 h-4 mr-2" />
|
|
||||||
Editar
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuItem
|
|
||||||
onClick={() => openDeleteDialog(t, day)}
|
|
||||||
className="text-red-600 focus:bg-red-50 focus:text-red-600"
|
|
||||||
>
|
|
||||||
<Trash2 className="w-4 h-4 mr-2" />
|
|
||||||
Excluir
|
|
||||||
</DropdownMenuItem>
|
|
||||||
</DropdownMenuContent>
|
|
||||||
</DropdownMenu>
|
|
||||||
</div>
|
|
||||||
))
|
|
||||||
) : (
|
|
||||||
<p className="text-sm text-gray-400 italic">
|
|
||||||
Sem horário
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</form>
|
||||||
);
|
|
||||||
})}
|
{/* **AJUSTE DE RESPONSIVIDADE: CARD DE HORÁRIO SEMANAL** */}
|
||||||
</CardContent>
|
<div>
|
||||||
</Card>
|
<Card>
|
||||||
</div>
|
<CardHeader>
|
||||||
|
<CardTitle>Horário Semanal</CardTitle>
|
||||||
{/* AlertDialog e Modal de Edição (não precisam de grandes ajustes de layout, apenas garantindo que os componentes sejam responsivos internamente) */}
|
<CardDescription>Confira ou altere a sua disponibilidade da semana</CardDescription>
|
||||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
</CardHeader>
|
||||||
<AlertDialogContent>
|
{/* Define um grid responsivo para os dias da semana (1 coluna em móvel, 2 em pequeno, 3 em médio e 7 em telas grandes) */}
|
||||||
<AlertDialogHeader>
|
<CardContent className="space-y-4 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-7 gap-2">
|
||||||
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
|
{["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"].map((day) => {
|
||||||
<AlertDialogDescription>
|
const times = schedule[day] || [];
|
||||||
Tem certeza que deseja excluir esta disponibilidade? Esta ação
|
return (
|
||||||
não pode ser desfeita.
|
<div key={day} className="space-y-4">
|
||||||
</AlertDialogDescription>
|
<div className="flex flex-col items-center justify-between p-3 bg-blue-50 rounded-lg h-full">
|
||||||
</AlertDialogHeader>
|
<p className="font-medium capitalize text-center mb-2">{weekdaysPT[day]}</p>
|
||||||
<AlertDialogFooter>
|
<div className="text-center w-full">
|
||||||
<AlertDialogCancel>Cancelar</AlertDialogCancel>
|
{times.length > 0 ? (
|
||||||
<AlertDialogAction
|
times.map((t, i) => (
|
||||||
onClick={() =>
|
<div key={i}>
|
||||||
selectedAvailability &&
|
<DropdownMenu>
|
||||||
handleDeleteAvailability(selectedAvailability.id)
|
<DropdownMenuTrigger asChild>
|
||||||
}
|
<p className="text-sm text-gray-600 cursor-pointer rounded hover:text-accent-foreground hover:bg-gray-200 transition-colors duration-150">
|
||||||
className="bg-red-600 hover:bg-red-700"
|
{formatTime(t.start)} - {formatTime(t.end)}
|
||||||
>
|
</p>
|
||||||
Excluir
|
</DropdownMenuTrigger>
|
||||||
</AlertDialogAction>
|
<DropdownMenuContent align="end">
|
||||||
</AlertDialogFooter>
|
<DropdownMenuItem onClick={() => handleOpenModal(t, day)}>
|
||||||
</AlertDialogContent>
|
<Edit className="w-4 h-4 mr-2" />
|
||||||
</AlertDialog>
|
Editar
|
||||||
</div>
|
</DropdownMenuItem>
|
||||||
<AvailabilityEditModal
|
<DropdownMenuItem
|
||||||
availability={selectedAvailability}
|
onClick={() => openDeleteDialog(t, day)}
|
||||||
isOpen={isModalOpen}
|
className="text-red-600 focus:bg-red-50 focus:text-red-600">
|
||||||
onClose={handleCloseModal}
|
<Trash2 className="w-4 h-4 mr-2" />
|
||||||
onSubmit={handleEdit}
|
Excluir
|
||||||
/>
|
</DropdownMenuItem>
|
||||||
</Sidebar>
|
</DropdownMenuContent>
|
||||||
);
|
</DropdownMenu>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<p className="text-sm text-gray-400 italic">Sem horário</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* AlertDialog e Modal de Edição (não precisam de grandes ajustes de layout, apenas garantindo que os componentes sejam responsivos internamente) */}
|
||||||
|
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>Tem certeza que deseja excluir esta disponibilidade? Esta ação não pode ser desfeita.</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>Cancelar</AlertDialogCancel>
|
||||||
|
<AlertDialogAction onClick={() => selectedAvailability && handleDeleteAvailability(selectedAvailability.id)} className="bg-red-600 hover:bg-red-700">
|
||||||
|
Excluir
|
||||||
|
</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
</div>
|
||||||
|
<AvailabilityEditModal
|
||||||
|
availability={selectedAvailability}
|
||||||
|
isOpen={isModalOpen}
|
||||||
|
onClose={handleCloseModal}
|
||||||
|
onSubmit={handleEdit}
|
||||||
|
/>
|
||||||
|
|
||||||
|
</Sidebar>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
185
app/manager/disponibilidade/page.tsx
Normal file
185
app/manager/disponibilidade/page.tsx
Normal file
@ -0,0 +1,185 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
import WeeklyScheduleCard from "@/components/ui/WeeklyScheduleCard";
|
||||||
|
|
||||||
|
import { useEffect, useState, useMemo } from "react";
|
||||||
|
|
||||||
|
import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
||||||
|
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Filter } from "lucide-react";
|
||||||
|
|
||||||
|
type Doctor = {
|
||||||
|
id: string;
|
||||||
|
full_name: string;
|
||||||
|
specialty: string;
|
||||||
|
active: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Availability = {
|
||||||
|
id: string;
|
||||||
|
doctor_id: string;
|
||||||
|
weekday: string;
|
||||||
|
start_time: string;
|
||||||
|
end_time: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function AllAvailabilities() {
|
||||||
|
const [availabilities, setAvailabilities] = useState<Availability[] | null>(null);
|
||||||
|
const [doctors, setDoctors] = useState<Doctor[] | null>(null);
|
||||||
|
|
||||||
|
// 🔎 Filtros
|
||||||
|
const [search, setSearch] = useState("");
|
||||||
|
const [specialty, setSpecialty] = useState("all");
|
||||||
|
|
||||||
|
// 🔄 Paginação
|
||||||
|
const ITEMS_PER_PAGE = 6;
|
||||||
|
const [page, setPage] = useState(1);
|
||||||
|
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchData = async () => {
|
||||||
|
try {
|
||||||
|
const doctorsList = await doctorsService.list();
|
||||||
|
setDoctors(doctorsList);
|
||||||
|
|
||||||
|
const availabilityList = await AvailabilityService.list();
|
||||||
|
setAvailabilities(availabilityList);
|
||||||
|
} catch (e: any) {
|
||||||
|
alert(`${e?.error} ${e?.message}`);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchData();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// 🎯 Obter todas as especialidades existentes
|
||||||
|
const specialties = useMemo(() => {
|
||||||
|
if (!doctors) return [];
|
||||||
|
const unique = Array.from(new Set(doctors.map((d) => d.specialty)));
|
||||||
|
return unique;
|
||||||
|
}, [doctors]);
|
||||||
|
|
||||||
|
// 🔍 Filtrar médicos por especialidade + nome
|
||||||
|
const filteredDoctors = useMemo(() => {
|
||||||
|
if (!doctors) return [];
|
||||||
|
|
||||||
|
return doctors.filter((doctor) => (specialty === "all" ? true : doctor.specialty === specialty)).filter((doctor) => doctor.full_name.toLowerCase().includes(search.toLowerCase()));
|
||||||
|
}, [doctors, search, specialty]);
|
||||||
|
|
||||||
|
// 📄 Paginação (após filtros!)
|
||||||
|
const totalPages = Math.ceil(filteredDoctors.length / ITEMS_PER_PAGE);
|
||||||
|
const paginatedDoctors = filteredDoctors.slice((page - 1) * ITEMS_PER_PAGE, page * ITEMS_PER_PAGE);
|
||||||
|
|
||||||
|
const goNext = () => setPage((p) => Math.min(p + 1, totalPages));
|
||||||
|
const goPrev = () => setPage((p) => Math.max(p - 1, 1));
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<Sidebar>
|
||||||
|
<div className="p-6 text-gray-500">Carregando dados...</div>
|
||||||
|
</Sidebar>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!doctors || !availabilities) {
|
||||||
|
return (
|
||||||
|
<Sidebar>
|
||||||
|
<div className="p-6 text-red-600 font-medium">Não foi possível carregar médicos ou disponibilidades.</div>
|
||||||
|
</Sidebar>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Sidebar>
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-bold text-gray-900">Disponibilidade dos Médicos</h1>
|
||||||
|
<p className="text-gray-600">Visualize a agenda semanal individual de cada médico.</p>
|
||||||
|
</div>
|
||||||
|
<Card>
|
||||||
|
<CardContent>
|
||||||
|
{/* 🔎 Filtros */}
|
||||||
|
<div className="flex flex-col md:flex-row gap-4 items-center">
|
||||||
|
{/* Filtro por nome */}
|
||||||
|
<Filter className="w-4 h-4 mr-2" />
|
||||||
|
<Input
|
||||||
|
placeholder="Buscar por nome do médico..."
|
||||||
|
value={search}
|
||||||
|
onChange={(e) => {
|
||||||
|
setSearch(e.target.value);
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
className="w-full md:w-1/3"
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Filtro por especialidade */}
|
||||||
|
<Select
|
||||||
|
onValueChange={(value) => {
|
||||||
|
setSpecialty(value);
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
defaultValue="all"
|
||||||
|
>
|
||||||
|
<SelectTrigger className="w-full md:w-64">
|
||||||
|
<SelectValue placeholder="Especialidade" />
|
||||||
|
</SelectTrigger>
|
||||||
|
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="all">Todas as especialidades</SelectItem>
|
||||||
|
{specialties.map((sp) => (
|
||||||
|
<SelectItem key={sp} value={sp}>
|
||||||
|
{sp}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
{/* GRID de cards */}
|
||||||
|
<div className="grid md:grid-cols-1 lg:grid-cols-1 gap-6">
|
||||||
|
{paginatedDoctors.map((doctor) => {
|
||||||
|
const doctorAvailabilities = availabilities.filter((a) => a.doctor_id === doctor.id);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card key={doctor.id}>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-xl font-semibold">{doctor.full_name}</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
|
<CardContent>
|
||||||
|
<WeeklyScheduleCard doctorId={doctor.id} />
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 📄 Paginação */}
|
||||||
|
{totalPages > 1 && (
|
||||||
|
<div className="flex justify-center items-center gap-4 pt-4">
|
||||||
|
<Button variant="outline" onClick={goPrev} disabled={page === 1}>
|
||||||
|
Anterior
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<span className="text-gray-700 font-medium">
|
||||||
|
Página {page} de {totalPages}
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<Button variant="outline" onClick={goNext} disabled={page === totalPages}>
|
||||||
|
Próxima
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Sidebar>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -4,34 +4,19 @@ 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 {
|
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||||
DropdownMenu,
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
DropdownMenuContent,
|
import { Edit, Trash2, Eye, Calendar, Loader2 } from "lucide-react";
|
||||||
DropdownMenuItem,
|
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||||
DropdownMenuTrigger,
|
|
||||||
} from "@/components/ui/dropdown-menu";
|
|
||||||
import {
|
|
||||||
Select,
|
|
||||||
SelectContent,
|
|
||||||
SelectItem,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from "@/components/ui/select";
|
|
||||||
import { Edit, Trash2, Eye, Calendar, Filter, Loader2 } from "lucide-react";
|
|
||||||
import {
|
|
||||||
AlertDialog,
|
|
||||||
AlertDialogAction,
|
|
||||||
AlertDialogCancel,
|
|
||||||
AlertDialogContent,
|
|
||||||
AlertDialogDescription,
|
|
||||||
AlertDialogFooter,
|
|
||||||
AlertDialogHeader,
|
|
||||||
AlertDialogTitle,
|
|
||||||
} from "@/components/ui/alert-dialog";
|
|
||||||
|
|
||||||
import { doctorsService } from "services/doctorsApi.mjs";
|
// Imports dos Serviços
|
||||||
|
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;
|
||||||
full_name: string;
|
full_name: string;
|
||||||
@ -66,119 +51,111 @@ interface DoctorDetails {
|
|||||||
export default function DoctorsPage() {
|
export default function DoctorsPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
const [doctors, setDoctors] = useState<Doctor[]>([]);
|
// --- Estados de Dados ---
|
||||||
const [loading, setLoading] = useState(true);
|
const [doctors, setDoctors] = useState<Doctor[]>([]);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [loading, setLoading] = useState(true);
|
||||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [doctorDetails, setDoctorDetails] = useState<DoctorDetails | null>(
|
|
||||||
null
|
|
||||||
);
|
|
||||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
|
||||||
const [doctorToDeleteId, setDoctorToDeleteId] = useState<number | null>(null);
|
|
||||||
|
|
||||||
// --- Estados para Filtros ---
|
// --- Estados de Modais ---
|
||||||
const [specialtyFilter, setSpecialtyFilter] = useState("all");
|
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
||||||
const [statusFilter, setStatusFilter] = useState("all");
|
const [doctorDetails, setDoctorDetails] = useState<DoctorDetails | null>(null);
|
||||||
|
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||||
|
const [doctorToDeleteId, setDoctorToDeleteId] = useState<number | null>(null);
|
||||||
|
|
||||||
// --- Estados para Paginação ---
|
// --- Estados de Filtro e Busca ---
|
||||||
const [itemsPerPage, setItemsPerPage] = useState(10);
|
const [searchTerm, setSearchTerm] = useState("");
|
||||||
const [currentPage, setCurrentPage] = useState(1);
|
const [filters, setFilters] = useState({
|
||||||
|
specialty: "all",
|
||||||
|
status: "all"
|
||||||
|
});
|
||||||
|
|
||||||
const fetchDoctors = useCallback(async () => {
|
// --- Estados de Paginação ---
|
||||||
setLoading(true);
|
const [itemsPerPage, setItemsPerPage] = useState(10);
|
||||||
setError(null);
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
try {
|
|
||||||
const data: Doctor[] = await doctorsService.list();
|
// 1. Buscar Médicos na API
|
||||||
const dataWithStatus = data.map((doc, index) => ({
|
const fetchDoctors = useCallback(async () => {
|
||||||
...doc,
|
setLoading(true);
|
||||||
status:
|
setError(null);
|
||||||
index % 3 === 0 ? "Inativo" : index % 2 === 0 ? "Férias" : "Ativo",
|
try {
|
||||||
}));
|
const data: Doctor[] = await doctorsService.list();
|
||||||
setDoctors(dataWithStatus || []);
|
// Mockando status para visualização (conforme original)
|
||||||
setCurrentPage(1);
|
const dataWithStatus = data.map((doc, index) => ({
|
||||||
} catch (e: any) {
|
...doc,
|
||||||
console.error("Erro ao carregar lista de médicos:", e);
|
status: index % 3 === 0 ? "Inativo" : index % 2 === 0 ? "Férias" : "Ativo",
|
||||||
setError(
|
}));
|
||||||
"Não foi possível carregar a lista de médicos. Verifique a conexão com a API."
|
setDoctors(dataWithStatus || []);
|
||||||
);
|
// Não resetamos a página aqui para manter a navegação fluida se apenas recarregar dados
|
||||||
setDoctors([]);
|
} catch (e: any) {
|
||||||
} finally {
|
console.error("Erro ao carregar lista de médicos:", e);
|
||||||
setLoading(false);
|
setError("Não foi possível carregar a lista de médicos. Verifique a conexão com a API.");
|
||||||
}
|
setDoctors([]);
|
||||||
}, []);
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchDoctors();
|
fetchDoctors();
|
||||||
}, [fetchDoctors]);
|
}, [fetchDoctors]);
|
||||||
|
|
||||||
const openDetailsDialog = async (doctor: Doctor) => {
|
// 2. Gerar lista única de especialidades (Normalizada)
|
||||||
setDetailsDialogOpen(true);
|
const uniqueSpecialties = useMemo(() => {
|
||||||
setDoctorDetails({
|
return getUniqueSpecialties(doctors);
|
||||||
nome: doctor.full_name,
|
}, [doctors]);
|
||||||
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 () => {
|
// 3. Lógica de Filtragem Centralizada
|
||||||
if (doctorToDeleteId === null) return;
|
const filteredDoctors = useMemo(() => {
|
||||||
setLoading(true);
|
return doctors.filter((doctor) => {
|
||||||
try {
|
// Normaliza a especialidade do médico atual para comparar
|
||||||
await doctorsService.delete(doctorToDeleteId);
|
const normalizedDocSpecialty = normalizeSpecialty(doctor.specialty);
|
||||||
setDeleteDialogOpen(false);
|
|
||||||
setDoctorToDeleteId(null);
|
// Filtros exatos
|
||||||
await fetchDoctors();
|
const specialtyMatch = filters.specialty === "all" || normalizedDocSpecialty === filters.specialty;
|
||||||
} catch (e) {
|
const statusMatch = filters.status === "all" || doctor.status === filters.status;
|
||||||
console.error("Erro ao excluir:", e);
|
|
||||||
alert("Erro ao excluir médico.");
|
// Busca textual (Nome, Telefone, CRM)
|
||||||
} finally {
|
const searchLower = searchTerm.toLowerCase();
|
||||||
setLoading(false);
|
const nameMatch = doctor.full_name?.toLowerCase().includes(searchLower);
|
||||||
}
|
const phoneMatch = doctor.phone_mobile?.includes(searchLower);
|
||||||
};
|
const crmMatch = doctor.crm?.toLowerCase().includes(searchLower);
|
||||||
|
|
||||||
const openDeleteDialog = (doctorId: number) => {
|
return specialtyMatch && statusMatch && (searchTerm === "" || nameMatch || phoneMatch || crmMatch);
|
||||||
setDoctorToDeleteId(doctorId);
|
});
|
||||||
setDeleteDialogOpen(true);
|
}, [doctors, filters, searchTerm]);
|
||||||
};
|
|
||||||
|
|
||||||
const uniqueSpecialties = useMemo(() => {
|
// --- Handlers de Controle (Com Reset de Paginação) ---
|
||||||
const specialties = doctors
|
|
||||||
.map((doctor) => doctor.specialty)
|
|
||||||
.filter(Boolean);
|
|
||||||
return [...new Set(specialties)];
|
|
||||||
}, [doctors]);
|
|
||||||
|
|
||||||
const filteredDoctors = doctors.filter((doctor) => {
|
const handleSearch = (term: string) => {
|
||||||
const specialtyMatch =
|
setSearchTerm(term);
|
||||||
specialtyFilter === "all" || doctor.specialty === specialtyFilter;
|
setCurrentPage(1); // Correção: Reseta para página 1 ao buscar
|
||||||
const statusMatch =
|
};
|
||||||
statusFilter === "all" || doctor.status === statusFilter;
|
|
||||||
return specialtyMatch && statusMatch;
|
|
||||||
});
|
|
||||||
|
|
||||||
const totalPages = Math.ceil(filteredDoctors.length / itemsPerPage);
|
const handleFilterChange = (key: string, value: string) => {
|
||||||
const indexOfLastItem = currentPage * itemsPerPage;
|
setFilters(prev => ({ ...prev, [key]: value }));
|
||||||
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
setCurrentPage(1); // Correção: Reseta para página 1 ao filtrar
|
||||||
const currentItems = filteredDoctors.slice(indexOfFirstItem, indexOfLastItem);
|
};
|
||||||
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
|
|
||||||
|
|
||||||
const goToPrevPage = () => {
|
const handleClearFilters = () => {
|
||||||
setCurrentPage((prev) => Math.max(1, prev - 1));
|
setSearchTerm("");
|
||||||
};
|
setFilters({ specialty: "all", status: "all" });
|
||||||
|
setCurrentPage(1); // Correção: Reseta para página 1 ao limpar
|
||||||
|
};
|
||||||
|
|
||||||
const goToNextPage = () => {
|
const handleItemsPerPageChange = (value: string) => {
|
||||||
setCurrentPage((prev) => Math.min(totalPages, prev + 1));
|
setItemsPerPage(Number(value));
|
||||||
};
|
setCurrentPage(1);
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- Lógica de Paginação ---
|
||||||
|
const totalPages = Math.ceil(filteredDoctors.length / itemsPerPage);
|
||||||
|
const indexOfLastItem = currentPage * itemsPerPage;
|
||||||
|
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
||||||
|
const currentItems = filteredDoctors.slice(indexOfFirstItem, indexOfLastItem);
|
||||||
|
|
||||||
|
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
|
||||||
|
const goToPrevPage = () => setCurrentPage((prev) => Math.max(1, prev - 1));
|
||||||
|
const goToNextPage = () => setCurrentPage((prev) => Math.min(totalPages, prev + 1));
|
||||||
|
|
||||||
const getVisiblePageNumbers = (totalPages: number, currentPage: number) => {
|
const getVisiblePageNumbers = (totalPages: number, currentPage: number) => {
|
||||||
const pages: number[] = [];
|
const pages: number[] = [];
|
||||||
@ -204,10 +181,43 @@ 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 (
|
||||||
<Sidebar>
|
<Sidebar>
|
||||||
@ -224,257 +234,192 @@ export default function DoctorsPage() {
|
|||||||
</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">
|
onSearch={handleSearch}
|
||||||
Especialidade
|
activeFilters={filters}
|
||||||
</span>
|
onFilterChange={handleFilterChange}
|
||||||
<Select value={specialtyFilter} onValueChange={setSpecialtyFilter}>
|
onClearFilters={handleClearFilters}
|
||||||
<SelectTrigger className="w-[160px] sm:w-[180px]">
|
searchPlaceholder="Buscar por nome, CRM ou telefone..."
|
||||||
<SelectValue placeholder="Especialidade" />
|
filters={[
|
||||||
</SelectTrigger>
|
{
|
||||||
<SelectContent>
|
key: "specialty",
|
||||||
<SelectItem value="all">Todas</SelectItem>
|
label: "Especialidade",
|
||||||
{uniqueSpecialties.map((specialty) => (
|
options: uniqueSpecialties
|
||||||
<SelectItem key={specialty} value={specialty}>
|
},
|
||||||
{specialty}
|
{
|
||||||
</SelectItem>
|
key: "status",
|
||||||
))}
|
label: "Status",
|
||||||
</SelectContent>
|
options: ["Ativo", "Férias", "Inativo"]
|
||||||
</Select>
|
}
|
||||||
</div>
|
]}
|
||||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
|
||||||
<span className="text-sm font-medium text-foreground">Status</span>
|
|
||||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
|
||||||
<SelectTrigger className="w-[160px] sm:w-[180px]">
|
|
||||||
<SelectValue placeholder="Status" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="all">Todos</SelectItem>
|
|
||||||
<SelectItem value="Ativo">Ativo</SelectItem>
|
|
||||||
<SelectItem value="Férias">Férias</SelectItem>
|
|
||||||
<SelectItem value="Inativo">Inativo</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
|
||||||
<span className="text-sm font-medium text-foreground">
|
|
||||||
Itens por página
|
|
||||||
</span>
|
|
||||||
<Select
|
|
||||||
onValueChange={handleItemsPerPageChange}
|
|
||||||
defaultValue={String(itemsPerPage)}
|
|
||||||
>
|
|
||||||
<SelectTrigger className="w-[140px]">
|
|
||||||
<SelectValue placeholder="Itens por pág." />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="5">5 por página</SelectItem>
|
|
||||||
<SelectItem value="10">10 por página</SelectItem>
|
|
||||||
<SelectItem value="20">20 por página</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
<Button variant="outline" className="ml-auto w-full md:w-auto">
|
|
||||||
<Filter className="w-4 h-4 mr-2" />
|
|
||||||
Filtro avançado
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Tabela de Médicos (Visível em Telas Médias e Maiores) */}
|
|
||||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-hidden hidden md:block">
|
|
||||||
{loading ? (
|
|
||||||
<div className="p-8 text-center text-gray-500">
|
|
||||||
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
|
|
||||||
Carregando médicos...
|
|
||||||
</div>
|
|
||||||
) : error ? (
|
|
||||||
<div className="p-8 text-center text-red-600">{error}</div>
|
|
||||||
) : filteredDoctors.length === 0 ? (
|
|
||||||
<div className="p-8 text-center text-gray-500">
|
|
||||||
{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 encontrado com os filtros aplicados."
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="overflow-x-auto">
|
|
||||||
<table className="w-full min-w-[600px]">
|
|
||||||
<thead className="bg-gray-50 border-b border-gray-200">
|
|
||||||
<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-gray-700">
|
|
||||||
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-gray-700 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-right p-4 font-medium text-gray-700">
|
|
||||||
Ações
|
|
||||||
</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody className="bg-white divide-y divide-gray-200">
|
|
||||||
{currentItems.map((doctor) => (
|
|
||||||
<tr key={doctor.id} className="hover:bg-gray-50 transition">
|
|
||||||
<td className="px-4 py-3 font-medium text-gray-900">
|
|
||||||
{doctor.full_name}
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-gray-500 hidden sm:table-cell">
|
|
||||||
{doctor.crm}
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-gray-500 hidden md:table-cell">
|
|
||||||
{doctor.specialty}
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-gray-500 hidden lg:table-cell">
|
|
||||||
{doctor.status || "N/A"}
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-gray-500 hidden xl:table-cell">
|
|
||||||
{doctor.city || doctor.state
|
|
||||||
? `${doctor.city || ""}${
|
|
||||||
doctor.city && doctor.state ? "/" : ""
|
|
||||||
}${doctor.state || ""}`
|
|
||||||
: "N/A"}
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-right">
|
|
||||||
<DropdownMenu>
|
|
||||||
<DropdownMenuTrigger asChild>
|
|
||||||
<div className="text-blue-600 cursor-pointer inline-block">
|
|
||||||
Ações
|
|
||||||
</div>
|
|
||||||
</DropdownMenuTrigger>
|
|
||||||
<DropdownMenuContent align="end">
|
|
||||||
<DropdownMenuItem
|
|
||||||
onClick={() => openDetailsDialog(doctor)}
|
|
||||||
>
|
|
||||||
<Eye className="mr-2 h-4 w-4" />
|
|
||||||
Ver detalhes
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuItem asChild>
|
|
||||||
<Link href={`/manager/home/${doctor.id}/editar`}>
|
|
||||||
<Edit className="mr-2 h-4 w-4" />
|
|
||||||
Editar
|
|
||||||
</Link>
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuItem>
|
|
||||||
<Calendar className="mr-2 h-4 w-4" />
|
|
||||||
Marcar consulta
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuItem
|
|
||||||
className="text-red-600"
|
|
||||||
onClick={() => openDeleteDialog(doctor.id)}
|
|
||||||
>
|
|
||||||
<Trash2 className="mr-2 h-4 w-4" />
|
|
||||||
Excluir
|
|
||||||
</DropdownMenuItem>
|
|
||||||
</DropdownMenuContent>
|
|
||||||
</DropdownMenu>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
))}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Cards de Médicos (Visível Apenas em Telas Pequenas) */}
|
|
||||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md p-4 block md:hidden">
|
|
||||||
{loading ? (
|
|
||||||
<div className="p-8 text-center text-gray-500">
|
|
||||||
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
|
|
||||||
Carregando médicos...
|
|
||||||
</div>
|
|
||||||
) : error ? (
|
|
||||||
<div className="p-8 text-center text-red-600">{error}</div>
|
|
||||||
) : filteredDoctors.length === 0 ? (
|
|
||||||
<div className="p-8 text-center text-gray-500">
|
|
||||||
{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 encontrado com os filtros aplicados."
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="space-y-4">
|
|
||||||
{currentItems.map((doctor) => (
|
|
||||||
<div
|
|
||||||
key={doctor.id}
|
|
||||||
className="bg-white-50 rounded-lg p-4 flex justify-between items-center border border-white-200"
|
|
||||||
>
|
>
|
||||||
<div>
|
{/* Seletor de Itens por Página (Filho do FilterBar) */}
|
||||||
<div className="font-semibold text-gray-900">
|
<div className="hidden lg:block">
|
||||||
{doctor.full_name}
|
<Select onValueChange={handleItemsPerPageChange} defaultValue={String(itemsPerPage)}>
|
||||||
|
<SelectTrigger className="w-[70px]">
|
||||||
|
<SelectValue placeholder="10" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="5">5</SelectItem>
|
||||||
|
<SelectItem value="10">10</SelectItem>
|
||||||
|
<SelectItem value="20">20</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-sm text-gray-600">
|
</FilterBar>
|
||||||
{doctor.specialty}
|
|
||||||
</div>
|
{/* Tabela de Médicos */}
|
||||||
</div>
|
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-hidden hidden md:block">
|
||||||
<DropdownMenu>
|
{loading ? (
|
||||||
<DropdownMenuTrigger asChild>
|
<div className="p-8 text-center text-gray-500">
|
||||||
<div className="text-blue-600 cursor-pointer inline-block">
|
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
|
||||||
Ações
|
Carregando médicos...
|
||||||
</div>
|
</div>
|
||||||
</DropdownMenuTrigger>
|
) : error ? (
|
||||||
<DropdownMenuContent align="end">
|
<div className="p-8 text-center text-red-600">{error}</div>
|
||||||
<DropdownMenuItem
|
) : filteredDoctors.length === 0 ? (
|
||||||
onClick={() => openDetailsDialog(doctor)}
|
<div className="p-8 text-center text-gray-500">
|
||||||
>
|
{doctors.length === 0
|
||||||
<Eye className="mr-2 h-4 w-4" />
|
? <>Nenhum médico cadastrado. <Link href="/manager/home/novo" className="text-green-600 hover:underline">Adicione um novo</Link>.</>
|
||||||
Ver detalhes
|
: "Nenhum médico encontrado com os filtros aplicados."
|
||||||
</DropdownMenuItem>
|
}
|
||||||
<DropdownMenuItem asChild>
|
</div>
|
||||||
<Link href={`/manager/home/${doctor.id}/editar`}>
|
) : (
|
||||||
<Edit className="mr-2 h-4 w-4" />
|
<div className="overflow-x-auto">
|
||||||
Editar
|
<table className="w-full min-w-[600px]">
|
||||||
</Link>
|
<thead className="bg-gray-50 border-b border-gray-200">
|
||||||
</DropdownMenuItem>
|
<tr>
|
||||||
<DropdownMenuItem>
|
<th className="text-left p-2 md:p-4 font-medium text-gray-700">Nome</th>
|
||||||
<Calendar className="mr-2 h-4 w-4" />
|
<th className="text-left p-2 md:p-4 font-medium text-gray-700">CRM</th>
|
||||||
Marcar consulta
|
<th className="text-left p-2 md:p-4 font-medium text-gray-700">Especialidade</th>
|
||||||
</DropdownMenuItem>
|
<th className="text-left p-2 md:p-4 font-medium text-gray-700 hidden lg:table-cell">Status</th>
|
||||||
<DropdownMenuItem
|
<th className="text-left p-2 md:p-4 font-medium text-gray-700 hidden xl:table-cell">Cidade/Estado</th>
|
||||||
className="text-red-600"
|
<th className="text-right p-4 font-medium text-gray-700">Ações</th>
|
||||||
onClick={() => openDeleteDialog(doctor.id)}
|
</tr>
|
||||||
>
|
</thead>
|
||||||
<Trash2 className="mr-2 h-4 w-4" />
|
<tbody className="bg-white divide-y divide-gray-200">
|
||||||
Excluir
|
{currentItems.map((doctor) => (
|
||||||
</DropdownMenuItem>
|
<tr key={doctor.id} className="hover:bg-gray-50 transition">
|
||||||
</DropdownMenuContent>
|
<td className="px-4 py-3 font-medium text-gray-900">
|
||||||
</DropdownMenu>
|
{doctor.full_name}
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-gray-500 hidden sm:table-cell">{doctor.crm}</td>
|
||||||
|
<td className="px-4 py-3 text-gray-500 hidden md:table-cell">
|
||||||
|
{/* Exibe Especialidade Normalizada */}
|
||||||
|
{normalizeSpecialty(doctor.specialty)}
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-gray-500 hidden lg:table-cell">
|
||||||
|
<span className={`px-2 py-1 rounded-full text-xs ${
|
||||||
|
doctor.status === 'Ativo' ? 'bg-green-100 text-green-800' :
|
||||||
|
doctor.status === 'Inativo' ? 'bg-red-100 text-red-800' : 'bg-yellow-100 text-yellow-800'
|
||||||
|
}`}>
|
||||||
|
{doctor.status || "N/A"}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-gray-500 hidden xl:table-cell">
|
||||||
|
{(doctor.city || doctor.state)
|
||||||
|
? `${doctor.city || ""}${doctor.city && doctor.state ? '/' : ''}${doctor.state || ""}`
|
||||||
|
: "N/A"}
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-right">
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<div className="text-blue-600 cursor-pointer inline-block hover:underline">Ações</div>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end">
|
||||||
|
<DropdownMenuItem onClick={() => openDetailsDialog(doctor)}>
|
||||||
|
<Eye className="mr-2 h-4 w-4" />
|
||||||
|
Ver detalhes
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem asChild>
|
||||||
|
<Link href={`/manager/home/${doctor.id}/editar`}>
|
||||||
|
<Edit className="mr-2 h-4 w-4" />
|
||||||
|
Editar
|
||||||
|
</Link>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem>
|
||||||
|
<Calendar className="mr-2 h-4 w-4" />
|
||||||
|
Marcar consulta
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(doctor.id)}>
|
||||||
|
<Trash2 className="mr-2 h-4 w-4" />
|
||||||
|
Excluir
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Cards de Médicos (Mobile) */}
|
||||||
|
<div className="bg-white rounded-lg border border-gray-200 shadow-md p-4 block md:hidden">
|
||||||
|
{loading ? (
|
||||||
|
<div className="p-8 text-center text-gray-500">
|
||||||
|
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
|
||||||
|
Carregando médicos...
|
||||||
|
</div>
|
||||||
|
) : error ? (
|
||||||
|
<div className="p-8 text-center text-red-600">{error}</div>
|
||||||
|
) : filteredDoctors.length === 0 ? (
|
||||||
|
<div className="p-8 text-center text-gray-500">
|
||||||
|
{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 encontrado com os filtros aplicados."
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{currentItems.map((doctor) => (
|
||||||
|
<div key={doctor.id} className="bg-gray-50 rounded-lg p-4 flex justify-between items-center border border-gray-100">
|
||||||
|
<div>
|
||||||
|
<div className="font-semibold text-gray-900">{doctor.full_name}</div>
|
||||||
|
<div className="text-xs text-gray-500 mb-1">{doctor.phone_mobile}</div>
|
||||||
|
<div className="text-sm text-gray-600">{normalizeSpecialty(doctor.specialty)}</div>
|
||||||
|
<div className="text-xs mt-1">
|
||||||
|
<span className={`px-2 py-0.5 rounded-full text-xs ${
|
||||||
|
doctor.status === 'Ativo' ? 'bg-green-100 text-green-800' :
|
||||||
|
doctor.status === 'Inativo' ? 'bg-red-100 text-red-800' : 'bg-yellow-100 text-yellow-800'
|
||||||
|
}`}>
|
||||||
|
{doctor.status || "N/A"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
|
||||||
|
<span className="sr-only">Abrir menu</span>
|
||||||
|
<div className="font-bold text-gray-500">...</div>
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end">
|
||||||
|
<DropdownMenuItem onClick={() => openDetailsDialog(doctor)}>
|
||||||
|
<Eye className="mr-2 h-4 w-4" />
|
||||||
|
Ver detalhes
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem asChild>
|
||||||
|
<Link href={`/manager/home/${doctor.id}/editar`}>
|
||||||
|
<Edit className="mr-2 h-4 w-4" />
|
||||||
|
Editar
|
||||||
|
</Link>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(doctor.id)}>
|
||||||
|
<Trash2 className="mr-2 h-4 w-4" />
|
||||||
|
Excluir
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Paginação */}
|
{/* Paginação */}
|
||||||
{totalPages > 1 && (
|
{totalPages > 1 && (
|
||||||
@ -511,31 +456,22 @@ export default function DoctorsPage() {
|
|||||||
</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>
|
||||||
<AlertDialogTitle>Confirma a exclusão?</AlertDialogTitle>
|
<AlertDialogTitle>Confirma a exclusão?</AlertDialogTitle>
|
||||||
<AlertDialogDescription>
|
<AlertDialogDescription>Esta ação é irreversível e excluirá permanentemente o registro deste médico.</AlertDialogDescription>
|
||||||
Esta ação é irreversível e excluirá permanentemente o registro
|
</AlertDialogHeader>
|
||||||
deste médico.
|
<AlertDialogFooter>
|
||||||
</AlertDialogDescription>
|
<AlertDialogCancel disabled={loading}>Cancelar</AlertDialogCancel>
|
||||||
</AlertDialogHeader>
|
<AlertDialogAction onClick={handleDelete} className="bg-red-600 hover:bg-red-700" disabled={loading}>
|
||||||
<AlertDialogFooter>
|
{loading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null}
|
||||||
<AlertDialogCancel disabled={loading}>Cancelar</AlertDialogCancel>
|
Excluir
|
||||||
<AlertDialogAction
|
</AlertDialogAction>
|
||||||
onClick={handleDelete}
|
</AlertDialogFooter>
|
||||||
className="bg-red-600 hover:bg-red-700"
|
</AlertDialogContent>
|
||||||
disabled={loading}
|
</AlertDialog>
|
||||||
>
|
|
||||||
{loading ? (
|
|
||||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
|
||||||
) : null}
|
|
||||||
Excluir
|
|
||||||
</AlertDialogAction>
|
|
||||||
</AlertDialogFooter>
|
|
||||||
</AlertDialogContent>
|
|
||||||
</AlertDialog>
|
|
||||||
|
|
||||||
<AlertDialog
|
<AlertDialog
|
||||||
open={detailsDialogOpen}
|
open={detailsDialogOpen}
|
||||||
|
|||||||
@ -3,23 +3,10 @@
|
|||||||
import React, { useEffect, useState, useCallback } from "react";
|
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 {
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
Select,
|
import { Input } from "@/components/ui/input"; // <--- 1. Importação Adicionada
|
||||||
SelectContent,
|
import { Plus, Eye, Filter, Loader2, Search } from "lucide-react"; // <--- 1. Ícone Search Adicionado
|
||||||
SelectItem,
|
import { AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from "@/components/ui/select";
|
|
||||||
import { Plus, Eye, Filter, Loader2 } from "lucide-react";
|
|
||||||
import {
|
|
||||||
AlertDialog,
|
|
||||||
AlertDialogCancel,
|
|
||||||
AlertDialogContent,
|
|
||||||
AlertDialogDescription,
|
|
||||||
AlertDialogFooter,
|
|
||||||
AlertDialogHeader,
|
|
||||||
AlertDialogTitle,
|
|
||||||
} from "@/components/ui/alert-dialog";
|
|
||||||
import { 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";
|
||||||
import Sidebar from "@/components/Sidebar";
|
import Sidebar from "@/components/Sidebar";
|
||||||
@ -41,12 +28,15 @@ interface UserInfoResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function UsersPage() {
|
export default function UsersPage() {
|
||||||
const [users, setUsers] = useState<FlatUser[]>([]);
|
const [users, setUsers] = useState<FlatUser[]>([]);
|
||||||
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>(null);
|
const [userDetails, setUserDetails] = useState<UserInfoResponse | null>(null);
|
||||||
const [selectedRole, setSelectedRole] = useState<string>("all");
|
|
||||||
|
// --- Estados de Filtro ---
|
||||||
|
const [searchTerm, setSearchTerm] = useState(""); // <--- 2. Estado da busca
|
||||||
|
const [selectedRole, setSelectedRole] = useState<string>("all");
|
||||||
|
|
||||||
// --- Lógica de Paginação INÍCIO ---
|
// --- Lógica de Paginação INÍCIO ---
|
||||||
const [itemsPerPage, setItemsPerPage] = useState(10);
|
const [itemsPerPage, setItemsPerPage] = useState(10);
|
||||||
@ -130,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;
|
||||||
@ -191,63 +192,71 @@ export default function UsersPage() {
|
|||||||
</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-white p-4 rounded-lg border border-gray-200">
|
||||||
{/* Select de Filtro por Papel - Ajustado para resetar a página */}
|
|
||||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
|
||||||
<span className="text-sm font-medium text-foreground whitespace-nowrap">
|
|
||||||
Filtrar por papel
|
|
||||||
</span>
|
|
||||||
<Select
|
|
||||||
onValueChange={(value) => {
|
|
||||||
setSelectedRole(value);
|
|
||||||
setCurrentPage(1);
|
|
||||||
}}
|
|
||||||
value={selectedRole}
|
|
||||||
>
|
|
||||||
<SelectTrigger className="w-full sm:w-[180px]">
|
|
||||||
{" "}
|
|
||||||
{/* w-full para mobile, w-[180px] para sm+ */}
|
|
||||||
<SelectValue placeholder="Filtrar por papel" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="all">Todos</SelectItem>
|
|
||||||
<SelectItem value="admin">Admin</SelectItem>
|
|
||||||
<SelectItem value="gestor">Gestor</SelectItem>
|
|
||||||
<SelectItem value="medico">Médico</SelectItem>
|
|
||||||
<SelectItem value="secretaria">Secretária</SelectItem>
|
|
||||||
<SelectItem value="user">Usuário</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Select de Itens por Página */}
|
{/* Barra de Pesquisa */}
|
||||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
<div className="relative w-full md:flex-1">
|
||||||
<span className="text-sm font-medium text-foreground whitespace-nowrap">
|
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
|
||||||
Itens por página
|
<Input
|
||||||
</span>
|
placeholder="Buscar por nome, e-mail ou telefone..."
|
||||||
<Select
|
value={searchTerm}
|
||||||
onValueChange={handleItemsPerPageChange}
|
onChange={(e) => {
|
||||||
defaultValue={String(itemsPerPage)}
|
setSearchTerm(e.target.value);
|
||||||
>
|
setCurrentPage(1); // Reseta a paginação ao pesquisar
|
||||||
<SelectTrigger className="w-full sm:w-[140px]">
|
}}
|
||||||
{" "}
|
className="pl-10 w-full bg-gray-50 border-gray-200 focus:bg-white transition-colors"
|
||||||
{/* w-full para mobile, w-[140px] para sm+ */}
|
/>
|
||||||
<SelectValue placeholder="Itens por pág." />
|
</div>
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
<div className="flex flex-wrap items-center gap-3 w-full md:w-auto">
|
||||||
<SelectItem value="5">5 por página</SelectItem>
|
{/* Select de Filtro por Papel */}
|
||||||
<SelectItem value="10">10 por página</SelectItem>
|
<div className="flex items-center gap-2 w-full md:w-auto">
|
||||||
<SelectItem value="20">20 por página</SelectItem>
|
<Select
|
||||||
</SelectContent>
|
onValueChange={(value) => {
|
||||||
</Select>
|
setSelectedRole(value);
|
||||||
</div>
|
setCurrentPage(1);
|
||||||
<Button variant="outline" className="ml-auto w-full md:w-auto">
|
}}
|
||||||
<Filter className="w-4 h-4 mr-2" />
|
value={selectedRole}>
|
||||||
Filtro avançado
|
|
||||||
</Button>
|
<SelectTrigger className="w-full sm:w-[150px]">
|
||||||
</div>
|
<SelectValue placeholder="Papel" />
|
||||||
{/* Fim do Filtro e Itens por Página */}
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="all">Todos</SelectItem>
|
||||||
|
<SelectItem value="admin">Admin</SelectItem>
|
||||||
|
<SelectItem value="gestor">Gestor</SelectItem>
|
||||||
|
<SelectItem value="medico">Médico</SelectItem>
|
||||||
|
<SelectItem value="secretaria">Secretária</SelectItem>
|
||||||
|
<SelectItem value="user">Usuário</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Select de Itens por Página */}
|
||||||
|
<div className="flex items-center gap-2 w-full md:w-auto">
|
||||||
|
<Select
|
||||||
|
onValueChange={handleItemsPerPageChange}
|
||||||
|
defaultValue={String(itemsPerPage)}
|
||||||
|
>
|
||||||
|
<SelectTrigger className="w-full sm:w-[80px]">
|
||||||
|
<SelectValue placeholder="10" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="5">5</SelectItem>
|
||||||
|
<SelectItem value="10">10</SelectItem>
|
||||||
|
<SelectItem value="20">20</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button variant="outline" className="ml-auto w-full md:w-auto hidden lg:flex">
|
||||||
|
<Filter className="w-4 h-4 mr-2" />
|
||||||
|
Filtros
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</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-white rounded-lg border border-gray-200 shadow-md overflow-x-auto">
|
||||||
@ -315,34 +324,34 @@ export default function UsersPage() {
|
|||||||
</tbody>
|
</tbody>
|
||||||
</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 divide-gray-200">
|
||||||
{currentItems.map((u) => (
|
{currentItems.map((u) => (
|
||||||
<div
|
<div key={u.id} className="flex items-center justify-between p-4 hover:bg-gray-50">
|
||||||
key={u.id}
|
<div className="flex-1 min-w-0">
|
||||||
className="flex items-center justify-between p-4 hover:bg-gray-50"
|
<div className="text-sm font-medium text-gray-900 truncate">
|
||||||
>
|
{u.full_name || "—"}
|
||||||
<div className="flex-1 min-w-0">
|
</div>
|
||||||
<div className="text-sm font-medium text-gray-900 truncate">
|
<div className="text-xs text-gray-500 truncate">
|
||||||
{u.full_name || "—"}
|
{u.email}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-sm text-gray-500 capitalize">
|
<div className="text-sm text-gray-500 capitalize mt-1">
|
||||||
{u.role || "—"}
|
{u.role || "—"}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="ml-4 flex-shrink-0">
|
<div className="ml-4 flex-shrink-0">
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="icon"
|
size="icon"
|
||||||
onClick={() => openDetailsDialog(u)}
|
onClick={() => openDetailsDialog(u)}
|
||||||
title="Visualizar"
|
title="Visualizar"
|
||||||
>
|
>
|
||||||
<Eye className="h-4 w-4" />
|
<Eye className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Paginação */}
|
{/* Paginação */}
|
||||||
{totalPages > 1 && (
|
{totalPages > 1 && (
|
||||||
|
|||||||
@ -227,31 +227,24 @@ export default function PacientesPage() {
|
|||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 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">
|
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">VIP</span>
|
||||||
VIP
|
<Select value={vipFilter} onValueChange={setVipFilter}>
|
||||||
</span>
|
<SelectTrigger className="w-full sm:w-32"> {/* w-full para mobile, w-32 para sm+ */}
|
||||||
<Select value={vipFilter} onValueChange={setVipFilter}>
|
<SelectValue placeholder="VIP" />
|
||||||
<SelectTrigger className="w-full sm:w-32">
|
</SelectTrigger>
|
||||||
{" "}
|
<SelectContent>
|
||||||
{/* w-full para mobile, w-32 para sm+ */}
|
<SelectItem value="all">Todos</SelectItem>
|
||||||
<SelectValue placeholder="VIP" />
|
<SelectItem value="vip">VIP</SelectItem>
|
||||||
</SelectTrigger>
|
<SelectItem value="regular">Regular</SelectItem>
|
||||||
<SelectContent>
|
</SelectContent>
|
||||||
<SelectItem value="all">Todos</SelectItem>
|
</Select>
|
||||||
<SelectItem value="vip">VIP</SelectItem>
|
</div>
|
||||||
<SelectItem value="regular">Regular</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</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>
|
|
||||||
|
|
||||||
{/* --- 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+ */}
|
||||||
|
|||||||
@ -188,18 +188,14 @@ 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: "/secretary/appointments", icon: CalendarCheck2, label: "Consultas" },
|
||||||
{
|
{ href: "/manager/disponibilidade", icon: ClipboardList, label: "Disponibilidade" },
|
||||||
href: "/secretary/appointments",
|
];
|
||||||
icon: CalendarCheck2,
|
|
||||||
label: "Consultas",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
switch (role) {
|
switch (role) {
|
||||||
case "gestor":
|
case "gestor":
|
||||||
|
|||||||
@ -19,9 +19,25 @@ import {
|
|||||||
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, 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";
|
||||||
|
|
||||||
|
// Componentes do Combobox (Barra de Pesquisa)
|
||||||
|
import {
|
||||||
|
Command,
|
||||||
|
CommandEmpty,
|
||||||
|
CommandGroup,
|
||||||
|
CommandInput,
|
||||||
|
CommandItem,
|
||||||
|
CommandList,
|
||||||
|
} from "@/components/ui/command";
|
||||||
|
import {
|
||||||
|
Popover,
|
||||||
|
PopoverContent,
|
||||||
|
PopoverTrigger,
|
||||||
|
} from "@/components/ui/popover";
|
||||||
|
|
||||||
export default function ScheduleForm() {
|
export default function ScheduleForm() {
|
||||||
// Estado do usuário e role
|
// Estado do usuário e role
|
||||||
@ -31,8 +47,12 @@ export default function ScheduleForm() {
|
|||||||
// Listas e seleções
|
// Listas e seleções
|
||||||
const [patients, setPatients] = useState<any[]>([]);
|
const [patients, setPatients] = useState<any[]>([]);
|
||||||
const [selectedPatient, setSelectedPatient] = useState("");
|
const [selectedPatient, setSelectedPatient] = useState("");
|
||||||
|
const [openPatientCombobox, setOpenPatientCombobox] = useState(false);
|
||||||
|
|
||||||
const [doctors, setDoctors] = useState<any[]>([]);
|
const [doctors, setDoctors] = useState<any[]>([]);
|
||||||
const [selectedDoctor, setSelectedDoctor] = useState("");
|
const [selectedDoctor, setSelectedDoctor] = useState("");
|
||||||
|
const [openDoctorCombobox, setOpenDoctorCombobox] = useState(false); // Novo estado para médico
|
||||||
|
|
||||||
const [selectedDate, setSelectedDate] = useState("");
|
const [selectedDate, setSelectedDate] = useState("");
|
||||||
const [selectedTime, setSelectedTime] = useState("");
|
const [selectedTime, setSelectedTime] = useState("");
|
||||||
const [notes, setNotes] = useState("");
|
const [notes, setNotes] = useState("");
|
||||||
@ -249,10 +269,7 @@ export default function ScheduleForm() {
|
|||||||
}, [selectedDoctor, selectedDate, fetchAvailableSlots]);
|
}, [selectedDoctor, selectedDate, fetchAvailableSlots]);
|
||||||
|
|
||||||
// 🔹 Submeter agendamento
|
// 🔹 Submeter agendamento
|
||||||
// 🔹 Submeter agendamento
|
|
||||||
// 🔹 Submeter agendamento
|
|
||||||
// 🔹 Submeter agendamento
|
|
||||||
// 🔹 Submeter agendamento
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|
||||||
@ -260,10 +277,7 @@ export default function ScheduleForm() {
|
|||||||
const patientId = isSecretaryLike ? selectedPatient : userId;
|
const patientId = isSecretaryLike ? selectedPatient : userId;
|
||||||
|
|
||||||
if (!patientId || !selectedDoctor || !selectedDate || !selectedTime) {
|
if (!patientId || !selectedDoctor || !selectedDate || !selectedTime) {
|
||||||
toast({
|
toast({ title: "Campos obrigatórios", description: "Preencha todos os campos." });
|
||||||
title: "Campos obrigatórios",
|
|
||||||
description: "Preencha todos os campos.",
|
|
||||||
});
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -277,7 +291,6 @@ export default function ScheduleForm() {
|
|||||||
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("/");
|
||||||
@ -289,31 +302,20 @@ export default function ScheduleForm() {
|
|||||||
}.`,
|
}.`,
|
||||||
});
|
});
|
||||||
|
|
||||||
let phoneNumber = "+5511999999999"; // fallback
|
let phoneNumber = "+5511999999999";
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (isSecretaryLike) {
|
if (isSecretaryLike) {
|
||||||
// Secretária/admin → telefone do paciente selecionado
|
|
||||||
const patient = patients.find((p: any) => p.id === patientId);
|
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;
|
const rawPhone = patient?.phone || patient?.phone_mobile || null;
|
||||||
|
|
||||||
if (rawPhone) phoneNumber = rawPhone;
|
if (rawPhone) phoneNumber = rawPhone;
|
||||||
} else {
|
} else {
|
||||||
// Paciente → telefone vem do perfil do próprio usuário logado
|
|
||||||
const me = await usersService.getMe();
|
const me = await usersService.getMe();
|
||||||
|
|
||||||
const rawPhone =
|
const rawPhone =
|
||||||
me?.profile?.phone ||
|
me?.profile?.phone ||
|
||||||
(typeof me?.profile === "object" && "phone_mobile" in me.profile
|
(typeof me?.profile === "object" && "phone_mobile" in me.profile ? (me.profile as any).phone_mobile : null) ||
|
||||||
? (me.profile as any).phone_mobile
|
(typeof me === "object" && "user_metadata" in me ? (me as any).user_metadata?.phone : null) ||
|
||||||
: null) ||
|
|
||||||
(typeof me === "object" && "user_metadata" in me
|
|
||||||
? (me as any).user_metadata?.phone
|
|
||||||
: null) ||
|
|
||||||
null;
|
null;
|
||||||
|
|
||||||
if (rawPhone) phoneNumber = rawPhone;
|
if (rawPhone) phoneNumber = rawPhone;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -397,63 +399,114 @@ export default function ScheduleForm() {
|
|||||||
<CardTitle>Dados da Consulta</CardTitle>
|
<CardTitle>Dados da Consulta</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<form
|
<form onSubmit={handleSubmit} className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||||
onSubmit={handleSubmit}
|
<div className="space-y-4"> {/* Ajuste: maior espaçamento vertical geral */}
|
||||||
className="grid grid-cols-1 lg:grid-cols-2 gap-6"
|
|
||||||
>
|
{/* Se secretária/gestor/admin → COMBOBOX de Paciente */}
|
||||||
<div className="space-y-3">
|
|
||||||
{/* Se secretária/gestor/admin → mostrar campo Paciente */}
|
|
||||||
{["secretaria", "gestor", "admin"].includes(role) && (
|
{["secretaria", "gestor", "admin"].includes(role) && (
|
||||||
<div>
|
<div className="flex flex-col gap-2"> {/* Ajuste: gap entre Label e Input */}
|
||||||
<Label>Paciente</Label>
|
<Label>Paciente</Label>
|
||||||
<Select
|
<Popover open={openPatientCombobox} onOpenChange={setOpenPatientCombobox}>
|
||||||
value={selectedPatient}
|
<PopoverTrigger asChild>
|
||||||
onValueChange={setSelectedPatient}
|
<Button
|
||||||
>
|
variant="outline"
|
||||||
<SelectTrigger>
|
role="combobox"
|
||||||
<SelectValue placeholder="Selecione o paciente" />
|
aria-expanded={openPatientCombobox}
|
||||||
</SelectTrigger>
|
className="w-full justify-between"
|
||||||
<SelectContent>
|
>
|
||||||
{patients.map((p) => (
|
{selectedPatient
|
||||||
<SelectItem key={p.id} value={p.id}>
|
? patients.find((p) => p.id === selectedPatient)?.full_name
|
||||||
{p.full_name}
|
: "Selecione o paciente..."}
|
||||||
</SelectItem>
|
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||||
))}
|
</Button>
|
||||||
</SelectContent>
|
</PopoverTrigger>
|
||||||
</Select>
|
<PopoverContent className="w-[350px] p-0">
|
||||||
|
<Command>
|
||||||
|
<CommandInput placeholder="Buscar paciente..." />
|
||||||
|
<CommandList>
|
||||||
|
<CommandEmpty>Nenhum paciente encontrado.</CommandEmpty>
|
||||||
|
<CommandGroup>
|
||||||
|
{patients.map((patient) => (
|
||||||
|
<CommandItem
|
||||||
|
key={patient.id}
|
||||||
|
value={patient.full_name}
|
||||||
|
onSelect={() => {
|
||||||
|
setSelectedPatient(patient.id === selectedPatient ? "" : patient.id);
|
||||||
|
setOpenPatientCombobox(false);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Check
|
||||||
|
className={cn(
|
||||||
|
"mr-2 h-4 w-4",
|
||||||
|
selectedPatient === patient.id ? "opacity-100" : "opacity-0"
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
{patient.full_name}
|
||||||
|
</CommandItem>
|
||||||
|
))}
|
||||||
|
</CommandGroup>
|
||||||
|
</CommandList>
|
||||||
|
</Command>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div>
|
{/* COMBOBOX de Médico (Nova funcionalidade) */}
|
||||||
|
<div className="flex flex-col gap-2"> {/* Ajuste: gap entre Label e Input */}
|
||||||
<Label>Médico</Label>
|
<Label>Médico</Label>
|
||||||
<Select
|
<Popover open={openDoctorCombobox} onOpenChange={setOpenDoctorCombobox}>
|
||||||
value={selectedDoctor}
|
<PopoverTrigger asChild>
|
||||||
onValueChange={setSelectedDoctor}
|
<Button
|
||||||
>
|
variant="outline"
|
||||||
<SelectTrigger>
|
role="combobox"
|
||||||
<SelectValue placeholder="Selecione o médico" />
|
aria-expanded={openDoctorCombobox}
|
||||||
</SelectTrigger>
|
className="w-full justify-between"
|
||||||
<SelectContent>
|
disabled={loadingDoctors}
|
||||||
{loadingDoctors ? (
|
>
|
||||||
<SelectItem value="loading" disabled>
|
{loadingDoctors
|
||||||
Carregando...
|
? "Carregando médicos..."
|
||||||
</SelectItem>
|
: selectedDoctor
|
||||||
) : (
|
? doctors.find((d) => d.id === selectedDoctor)?.full_name
|
||||||
[...doctors]
|
: "Selecione o médico..."}
|
||||||
.sort((a, b) =>
|
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||||
String(a.full_name).localeCompare(String(b.full_name))
|
</Button>
|
||||||
)
|
</PopoverTrigger>
|
||||||
.map((d) => (
|
<PopoverContent className="w-[350px] p-0">
|
||||||
<SelectItem key={d.id} value={d.id}>
|
<Command>
|
||||||
{d.full_name} — {d.specialty}
|
<CommandInput placeholder="Buscar médico..." />
|
||||||
</SelectItem>
|
<CommandList>
|
||||||
))
|
<CommandEmpty>Nenhum médico encontrado.</CommandEmpty>
|
||||||
)}
|
<CommandGroup>
|
||||||
</SelectContent>
|
{doctors.map((doctor) => (
|
||||||
</Select>
|
<CommandItem
|
||||||
|
key={doctor.id}
|
||||||
|
value={doctor.full_name}
|
||||||
|
onSelect={() => {
|
||||||
|
setSelectedDoctor(doctor.id === selectedDoctor ? "" : doctor.id);
|
||||||
|
setOpenDoctorCombobox(false);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Check
|
||||||
|
className={cn(
|
||||||
|
"mr-2 h-4 w-4",
|
||||||
|
selectedDoctor === doctor.id ? "opacity-100" : "opacity-0"
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<div className="flex flex-col">
|
||||||
|
<span>{doctor.full_name}</span>
|
||||||
|
<span className="text-xs text-muted-foreground">{doctor.specialty}</span>
|
||||||
|
</div>
|
||||||
|
</CommandItem>
|
||||||
|
))}
|
||||||
|
</CommandGroup>
|
||||||
|
</CommandList>
|
||||||
|
</Command>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div className="flex flex-col gap-2">
|
||||||
<Label>Data</Label>
|
<Label>Data</Label>
|
||||||
<div ref={calendarRef} className="rounded-lg border p-2">
|
<div ref={calendarRef} className="rounded-lg border p-2">
|
||||||
<CalendarShadcn
|
<CalendarShadcn
|
||||||
@ -476,18 +529,18 @@ export default function ScheduleForm() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div className="flex flex-col gap-2">
|
||||||
<Label>Observações</Label>
|
<Label>Observações</Label>
|
||||||
<Textarea
|
<Textarea
|
||||||
placeholder="Instruções para o médico..."
|
placeholder="Instruções para o médico..."
|
||||||
value={notes}
|
value={notes}
|
||||||
onChange={(e) => setNotes(e.target.value)}
|
onChange={(e) => setNotes(e.target.value)}
|
||||||
className="mt-2"
|
className="mt-1"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-3">
|
<div className="space-y-4"> {/* Ajuste: Espaçamento no lado direito também */}
|
||||||
<Card className="shadow-md rounded-xl bg-blue-50 border border-blue-200">
|
<Card className="shadow-md rounded-xl bg-blue-50 border border-blue-200">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="text-blue-700">Resumo</CardTitle>
|
<CardTitle className="text-blue-700">Resumo</CardTitle>
|
||||||
@ -591,4 +644,4 @@ export default function ScheduleForm() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
105
components/ui/WeeklyScheduleCard.tsx
Normal file
105
components/ui/WeeklyScheduleCard.tsx
Normal file
@ -0,0 +1,105 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card";
|
||||||
|
import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
||||||
|
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||||
|
|
||||||
|
type Availability = {
|
||||||
|
id: string;
|
||||||
|
doctor_id: string;
|
||||||
|
weekday: string;
|
||||||
|
start_time: string;
|
||||||
|
end_time: string;
|
||||||
|
slot_minutes: number;
|
||||||
|
appointment_type: string;
|
||||||
|
active: boolean;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
created_by: string;
|
||||||
|
updated_by: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
interface WeeklyScheduleProps {
|
||||||
|
doctorId?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function WeeklyScheduleCard({ doctorId }: WeeklyScheduleProps) {
|
||||||
|
const [schedule, setSchedule] = useState<Record<string, { start: string; end: string }[]>>({});
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
|
const weekdaysPT: Record<string, string> = {
|
||||||
|
sunday: "Domingo",
|
||||||
|
monday: "Segunda",
|
||||||
|
tuesday: "Terça",
|
||||||
|
wednesday: "Quarta",
|
||||||
|
thursday: "Quinta",
|
||||||
|
friday: "Sexta",
|
||||||
|
saturday: "Sábado",
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatTime = (time?: string | null) => time?.split(":")?.slice(0, 2).join(":") ?? "";
|
||||||
|
|
||||||
|
function formatAvailability(data: Availability[]) {
|
||||||
|
const grouped = data.reduce((acc: any, item) => {
|
||||||
|
const { weekday, start_time, end_time } = item;
|
||||||
|
|
||||||
|
if (!acc[weekday]) acc[weekday] = [];
|
||||||
|
|
||||||
|
acc[weekday].push({ start: start_time, end: end_time });
|
||||||
|
|
||||||
|
return acc;
|
||||||
|
}, {});
|
||||||
|
|
||||||
|
return grouped;
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchSchedule = async () => {
|
||||||
|
try {
|
||||||
|
const availabilityList = await AvailabilityService.list();
|
||||||
|
|
||||||
|
const filtered = availabilityList.filter((a: Availability) => a.doctor_id == doctorId);
|
||||||
|
|
||||||
|
const formatted = formatAvailability(filtered);
|
||||||
|
setSchedule(formatted);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Erro ao carregar horários:", err);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchSchedule();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4 grid md:grid-cols-7 gap-2">
|
||||||
|
{loading ? (
|
||||||
|
<p className="text-sm text-gray-500 col-span-7 text-center">Carregando...</p>
|
||||||
|
) : (
|
||||||
|
["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "Saturday"].map((day) => {
|
||||||
|
const times = schedule[day] || [];
|
||||||
|
return (
|
||||||
|
<div key={day} className="space-y-4">
|
||||||
|
<div className="flex flex-col items-center justify-between p-3 bg-blue-50 rounded-lg">
|
||||||
|
<p className="font-medium capitalize">{weekdaysPT[day]}</p>
|
||||||
|
<div className="text-center">
|
||||||
|
{times.length > 0 ? (
|
||||||
|
times.map((t, i) => (
|
||||||
|
<p key={i} className="text-sm text-gray-600">
|
||||||
|
{formatTime(t.start)} <br /> {formatTime(t.end)}
|
||||||
|
</p>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<p className="text-sm text-gray-400 italic">Sem horário</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
115
components/ui/filter-bar.tsx
Normal file
115
components/ui/filter-bar.tsx
Normal file
@ -0,0 +1,115 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import React from "react";
|
||||||
|
import { Search, Filter, X } from "lucide-react";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
|
||||||
|
export interface FilterOption {
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FilterConfig {
|
||||||
|
key: string; // O nome do estado que vai guardar esse valor (ex: 'specialty')
|
||||||
|
label: string; // O placeholder do select (ex: 'Especialidade')
|
||||||
|
options: FilterOption[] | string[]; // Opções do dropdown
|
||||||
|
}
|
||||||
|
|
||||||
|
interface FilterBarProps {
|
||||||
|
onSearch: (term: string) => void;
|
||||||
|
searchTerm: string;
|
||||||
|
searchPlaceholder?: string;
|
||||||
|
filters?: FilterConfig[];
|
||||||
|
activeFilters: Record<string, string>;
|
||||||
|
onFilterChange: (key: string, value: string) => void;
|
||||||
|
onClearFilters?: () => void;
|
||||||
|
className?: string;
|
||||||
|
children?: React.ReactNode; // Para botões extras (ex: "Novo Médico", paginação)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function FilterBar({
|
||||||
|
onSearch,
|
||||||
|
searchTerm,
|
||||||
|
searchPlaceholder = "Pesquisar...",
|
||||||
|
filters = [],
|
||||||
|
activeFilters,
|
||||||
|
onFilterChange,
|
||||||
|
onClearFilters,
|
||||||
|
children,
|
||||||
|
className,
|
||||||
|
}: FilterBarProps) {
|
||||||
|
|
||||||
|
// Verifica se tem algum filtro ativo para mostrar o botão de limpar
|
||||||
|
const hasActiveFilters =
|
||||||
|
searchTerm !== "" ||
|
||||||
|
Object.values(activeFilters).some(val => val !== "all" && val !== "");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={`flex flex-col md:flex-row items-start md:items-center gap-3 bg-white p-4 rounded-lg border border-gray-200 ${className}`}>
|
||||||
|
|
||||||
|
{/* Barra de Pesquisa */}
|
||||||
|
<div className="relative w-full md:flex-1">
|
||||||
|
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
|
||||||
|
<Input
|
||||||
|
placeholder={searchPlaceholder}
|
||||||
|
value={searchTerm}
|
||||||
|
onChange={(e) => onSearch(e.target.value)}
|
||||||
|
className="pl-10 w-full bg-gray-50 border-gray-200 focus:bg-white transition-colors"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Filtros Dinâmicos (Selects) */}
|
||||||
|
<div className="flex flex-wrap items-center gap-3 w-full md:w-auto">
|
||||||
|
{filters.map((filter) => (
|
||||||
|
<div key={filter.key} className="w-full sm:w-auto">
|
||||||
|
<Select
|
||||||
|
value={activeFilters[filter.key] || "all"}
|
||||||
|
onValueChange={(value) => onFilterChange(filter.key, value)}
|
||||||
|
>
|
||||||
|
<SelectTrigger className="w-full sm:w-[180px]">
|
||||||
|
<SelectValue placeholder={filter.label} />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="all">Todos: {filter.label}</SelectItem>
|
||||||
|
{filter.options.map((opt) => {
|
||||||
|
// Suporta tanto array de strings quanto array de objetos {label, value}
|
||||||
|
const value = typeof opt === 'string' ? opt : opt.value;
|
||||||
|
const label = typeof opt === 'string' ? opt : opt.label;
|
||||||
|
return (
|
||||||
|
<SelectItem key={value} value={value}>
|
||||||
|
{label}
|
||||||
|
</SelectItem>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{/* Botão de Limpar Filtros */}
|
||||||
|
{hasActiveFilters && onClearFilters && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={onClearFilters}
|
||||||
|
className="text-gray-500 hover:text-red-600"
|
||||||
|
title="Limpar filtros"
|
||||||
|
>
|
||||||
|
<X className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Botões Extras (ex: Novo Médico, Paginação) passados como children */}
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -1,96 +1,147 @@
|
|||||||
'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">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>Detalhes do Paciente</DialogTitle>
|
<DialogTitle className="text-xl font-bold">Detalhes do Paciente</DialogTitle>
|
||||||
<DialogDescription>Informações detalhadas sobre o paciente.</DialogDescription>
|
<DialogDescription>
|
||||||
|
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-gray-900">Nome Completo</p>
|
||||||
<p>{patient.nome}</p>
|
<p className="text-gray-700">{patient.nome}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* CORREÇÃO AQUI: Adicionado 'break-all' para quebrar o email */}
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Email</p>
|
<p className="font-semibold text-gray-900">Email</p>
|
||||||
<p>{patient.email}</p>
|
<p className="text-gray-700 break-all">{patient.email || "N/A"}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Telefone</p>
|
<p className="font-semibold text-gray-900">Telefone</p>
|
||||||
<p>{patient.telefone}</p>
|
<p className="text-gray-700">{patient.telefone}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Data de Nascimento</p>
|
<p className="font-semibold text-gray-900">Data de Nascimento</p>
|
||||||
<p>{patient.birth_date}</p>
|
<p className="text-gray-700">{patient.birth_date || "N/A"}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">CPF</p>
|
<p className="font-semibold text-gray-900">CPF</p>
|
||||||
<p>{patient.cpf}</p>
|
<p className="text-gray-700">{patient.cpf || "N/A"}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Tipo Sanguíneo</p>
|
<p className="font-semibold text-gray-900">Tipo Sanguíneo</p>
|
||||||
<p>{patient.blood_type}</p>
|
<p className="text-gray-700">{patient.blood_type || "N/A"}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Peso (kg)</p>
|
<p className="font-semibold text-gray-900">Peso (kg)</p>
|
||||||
<p>{patient.weight_kg}</p>
|
<p className="text-gray-700">{patient.weight_kg || "0"}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Altura (m)</p>
|
<p className="font-semibold text-gray-900">Altura (m)</p>
|
||||||
<p>{patient.height_m}</p>
|
<p className="text-gray-700">{patient.height_m || "0"}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="border-t pt-4 mt-4">
|
|
||||||
<h3 className="font-semibold mb-2">Endereço</h3>
|
<hr className="border-gray-200" />
|
||||||
<div className="grid grid-cols-2 gap-4">
|
|
||||||
|
{/* Seção de Endereço */}
|
||||||
|
<div>
|
||||||
|
<h4 className="font-semibold mb-3 text-gray-900">Endereço</h4>
|
||||||
|
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Rua</p>
|
<p className="font-semibold text-gray-900">Rua</p>
|
||||||
<p>{`${patient.street}, ${patient.number}`}</p>
|
<p className="text-gray-700">
|
||||||
|
{patient.street && patient.street !== "N/A"
|
||||||
|
? `${patient.street}, ${patient.number || ""}`
|
||||||
|
: "N/A"}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Complemento</p>
|
<p className="font-semibold text-gray-900">Complemento</p>
|
||||||
<p>{patient.complement}</p>
|
<p className="text-gray-700">{patient.complement || "N/A"}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Bairro</p>
|
<p className="font-semibold text-gray-900">Bairro</p>
|
||||||
<p>{patient.neighborhood}</p>
|
<p className="text-gray-700">{patient.neighborhood || "N/A"}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Cidade</p>
|
<p className="font-semibold text-gray-900">Cidade</p>
|
||||||
<p>{patient.cidade}</p>
|
<p className="text-gray-700">{patient.cidade || "N/A"}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">Estado</p>
|
<p className="font-semibold text-gray-900">Estado</p>
|
||||||
<p>{patient.estado}</p>
|
<p className="text-gray-700">{patient.estado || "N/A"}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">CEP</p>
|
<p className="font-semibold text-gray-900">CEP</p>
|
||||||
<p>{patient.cep}</p>
|
<p className="text-gray-700">{patient.cep || "N/A"}</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>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
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();
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user