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() {
|
||||
const { user, isLoading: isAuthLoading } = useAuthLayout({ requiredRole: 'medico' });
|
||||
const { user, isLoading: isAuthLoading } = useAuthLayout({ requiredRole: "medico" });
|
||||
|
||||
const [allAppointments, setAllAppointments] = useState<EnrichedAppointment[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
@ -111,13 +111,22 @@ export default function DoctorAppointmentsPage() {
|
||||
return format(date, "EEEE, dd 'de' MMMM", { locale: ptBR });
|
||||
};
|
||||
|
||||
const statusPT: Record<string, string> = {
|
||||
confirmed: "Confirmada",
|
||||
completed: "Concluída",
|
||||
cancelled: "Cancelada",
|
||||
requested: "Solicitada",
|
||||
no_show: "oculta",
|
||||
checked_in: "Aguardando",
|
||||
};
|
||||
|
||||
const getStatusVariant = (status: EnrichedAppointment['status']) => {
|
||||
switch (status) {
|
||||
case "confirmed": case "checked_in": return "default";
|
||||
case "completed": return "secondary";
|
||||
case "cancelled": case "no_show": return "destructive";
|
||||
case "requested": return "outline";
|
||||
default: return "outline";
|
||||
case "confirmed": case "checked_in": return "text-foreground bg-blue-100 hover:bg-blue-150";
|
||||
case "completed": return "text-foreground bg-green-100 hover:bg-green-150";
|
||||
case "cancelled": case "no_show": return "text-foreground bg-red-200 hover:bg-red-250";
|
||||
case "requested": return "text-foreground bg-yellow-100 hover:bg-yellow-150";
|
||||
default: return "border-gray bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90";
|
||||
}
|
||||
};
|
||||
|
||||
@ -191,7 +200,7 @@ export default function DoctorAppointmentsPage() {
|
||||
|
||||
{/* Coluna 2: Status e Telefone */}
|
||||
<div className="col-span-1 flex flex-col items-center gap-2">
|
||||
<Badge variant={getStatusVariant(appointment.status)} className="capitalize text-xs">{appointment.status.replace('_', ' ')}</Badge>
|
||||
<Badge variant="outline" className={getStatusVariant(appointment.status)}>{statusPT[appointment.status].replace('_', ' ')}</Badge>
|
||||
<div className="flex items-center text-sm text-muted-foreground">
|
||||
<Phone className="mr-2 h-4 w-4" />
|
||||
{appointment.patientPhone}
|
||||
|
||||
@ -29,6 +29,7 @@ import { exceptionsService } from "@/services/exceptionApi.mjs";
|
||||
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||
import { usersService } from "@/services/usersApi.mjs";
|
||||
import Sidebar from "@/components/Sidebar";
|
||||
import WeeklyScheduleCard from "@/components/ui/WeeklyScheduleCard";
|
||||
|
||||
type Availability = {
|
||||
id: string;
|
||||
@ -165,20 +166,17 @@ export default function PatientDashboard() {
|
||||
);
|
||||
setAvailability(filteredAvail);
|
||||
|
||||
// Busca exceções
|
||||
const exceptionsList = await exceptionsService.list();
|
||||
const filteredExc = exceptionsList.filter(
|
||||
(exc: { doctor_id: string }) => exc.doctor_id === doctor?.id
|
||||
);
|
||||
console.log(exceptionsList);
|
||||
setExceptions(filteredExc);
|
||||
} catch (e: any) {
|
||||
alert(`${e?.error} ${e?.message}`);
|
||||
}
|
||||
};
|
||||
// Busca exceções
|
||||
const exceptionsList = await exceptionsService.list();
|
||||
const filteredExc = exceptionsList.filter((exc: { doctor_id: string }) => exc.doctor_id === doctor?.id);
|
||||
setExceptions(filteredExc);
|
||||
} catch (e: any) {
|
||||
alert(`${e?.error} ${e?.message}`);
|
||||
}
|
||||
};
|
||||
|
||||
fetchData();
|
||||
}, []);
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
// Função auxiliar para filtrar o id do doctor correspondente ao user logado
|
||||
function findDoctorById(id: string, doctors: Doctor[]) {
|
||||
@ -320,82 +318,42 @@ export default function PatientDashboard() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Próximas Consultas</CardTitle>
|
||||
<CardDescription>Suas consultas agendadas</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between p-3 bg-blue-50 rounded-lg">
|
||||
<div>
|
||||
<p className="font-medium">Dr. João Santos</p>
|
||||
<p className="text-sm text-gray-600">Cardiologia</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="font-medium">02 out</p>
|
||||
<p className="text-sm text-gray-600">14:30</p>
|
||||
</div>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Próximas Consultas</CardTitle>
|
||||
<CardDescription>Suas consultas agendadas</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between p-3 bg-blue-50 rounded-lg">
|
||||
<div>
|
||||
<p className="font-medium">Dr. João Santos</p>
|
||||
<p className="text-sm text-gray-600">Cardiologia</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="font-medium">02 out</p>
|
||||
<p className="text-sm text-gray-600">14:30</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-1 gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Horário Semanal</CardTitle>
|
||||
<CardDescription>
|
||||
Confira rapidamente a sua disponibilidade da semana
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4 grid md:grid-cols-7 gap-2">
|
||||
{[
|
||||
"sunday",
|
||||
"monday",
|
||||
"tuesday",
|
||||
"wednesday",
|
||||
"thursday",
|
||||
"friday",
|
||||
"saturday",
|
||||
].map((day) => {
|
||||
const times = schedule[day] || [];
|
||||
return (
|
||||
<div key={day} className="space-y-4">
|
||||
<div className="flex flex-col items-center justify-between p-3 bg-blue-50 rounded-lg">
|
||||
<div>
|
||||
<p className="font-medium capitalize">
|
||||
{weekdaysPT[day]}
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
{times.length > 0 ? (
|
||||
times.map((t, i) => (
|
||||
<p key={i} className="text-sm text-gray-600">
|
||||
{formatTime(t.start)} <br /> {formatTime(t.end)}
|
||||
</p>
|
||||
))
|
||||
) : (
|
||||
<p className="text-sm text-gray-400 italic">
|
||||
Sem horário
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</CardContent>
|
||||
</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>
|
||||
<div className="grid md:grid-cols-1 gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Horário Semanal</CardTitle>
|
||||
<CardDescription>Confira rapidamente a sua disponibilidade da semana</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>{loggedDoctor && <WeeklyScheduleCard doctorId={loggedDoctor.id} />}</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">
|
||||
{exceptions && exceptions.length > 0 ? (
|
||||
@ -411,75 +369,47 @@ export default function PatientDashboard() {
|
||||
const startTime = formatTime(ex.start_time);
|
||||
const endTime = formatTime(ex.end_time);
|
||||
|
||||
return (
|
||||
<div key={ex.id} className="space-y-4">
|
||||
<div className="flex flex-col items-center justify-between p-3 bg-blue-50 rounded-lg shadow-sm">
|
||||
<div className="text-center">
|
||||
<p className="font-semibold capitalize">{date}</p>
|
||||
<p className="text-sm text-gray-600">
|
||||
{startTime && endTime
|
||||
? `${startTime} - ${endTime}`
|
||||
: "Dia todo"}
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-center mt-2">
|
||||
<p
|
||||
className={`text-sm font-medium ${
|
||||
ex.kind === "bloqueio"
|
||||
? "text-red-600"
|
||||
: "text-green-600"
|
||||
}`}
|
||||
>
|
||||
{ex.kind === "bloqueio" ? "Bloqueio" : "Liberação"}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 italic">
|
||||
{ex.reason || "Sem motivo especificado"}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<Button
|
||||
className="text-red-600"
|
||||
variant="outline"
|
||||
onClick={() => openDeleteDialog(String(ex.id))}
|
||||
>
|
||||
<Trash2></Trash2>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<p className="text-sm text-gray-400 italic col-span-7 text-center">
|
||||
Nenhuma exceção registrada.
|
||||
</p>
|
||||
)}
|
||||
</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>
|
||||
);
|
||||
return (
|
||||
<div key={ex.id} className="space-y-4">
|
||||
<div className="flex flex-col items-center justify-between p-3 bg-blue-50 rounded-lg shadow-sm">
|
||||
<div className="text-center">
|
||||
<p className="font-semibold capitalize">{date}</p>
|
||||
<p className="text-sm text-gray-600">{startTime && endTime ? `${startTime} - ${endTime}` : "Dia todo"}</p>
|
||||
</div>
|
||||
<div className="text-center mt-2">
|
||||
<p className={`text-sm font-medium ${ex.kind === "bloqueio" ? "text-red-600" : "text-green-600"}`}>{ex.kind === "bloqueio" ? "Bloqueio" : "Liberação"}</p>
|
||||
<p className="text-xs text-gray-500 italic">{ex.reason || "Sem motivo especificado"}</p>
|
||||
</div>
|
||||
<div>
|
||||
<Button className="text-red-600" variant="outline" onClick={() => openDeleteDialog(String(ex.id))}>
|
||||
<Trash2></Trash2>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<p className="text-sm text-gray-400 italic col-span-7 text-center">Nenhuma exceção registrada.</p>
|
||||
)}
|
||||
</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
|
||||
const weekdaysPT: Record<string, string> = {
|
||||
sunday: "Domingo",
|
||||
monday: "Segunda",
|
||||
tuesday: "Terça",
|
||||
wednesday: "Quarta",
|
||||
thursday: "Quinta",
|
||||
friday: "Sexta",
|
||||
saturday: "Sábado",
|
||||
};
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
const loggedUser = await usersService.getMe();
|
||||
const doctorList = await doctorsService.list();
|
||||
setUserData(loggedUser);
|
||||
const doctor = findDoctorById(loggedUser.user.id, doctorList);
|
||||
setDoctorId(doctor?.id);
|
||||
console.log(doctor);
|
||||
// Busca disponibilidade
|
||||
const availabilityList = await AvailabilityService.list();
|
||||
|
||||
// Filtra já com a variável local
|
||||
const filteredAvail = availabilityList.filter(
|
||||
(disp: { doctor_id: string }) => disp.doctor_id === doctor?.id
|
||||
);
|
||||
setAvailability(filteredAvail);
|
||||
} catch (e: any) {
|
||||
alert(`${e?.error} ${e?.message}`);
|
||||
}
|
||||
};
|
||||
// Mapa de tradução
|
||||
const weekdaysPT: Record<string, string> = {
|
||||
sunday: "Domingo",
|
||||
monday: "Segunda",
|
||||
tuesday: "Terça",
|
||||
wednesday: "Quarta",
|
||||
thursday: "Quinta",
|
||||
friday: "Sexta",
|
||||
saturday: "Sábado",
|
||||
};
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
const loggedUser = await usersService.getMe();
|
||||
const doctorList = await doctorsService.list();
|
||||
setUserData(loggedUser);
|
||||
const doctor = findDoctorById(loggedUser.user.id, doctorList);
|
||||
setDoctorId(doctor?.id);
|
||||
console.log(doctor);
|
||||
// Busca disponibilidade
|
||||
const availabilityList = await AvailabilityService.list();
|
||||
|
||||
// Filtra já com a variável local
|
||||
const filteredAvail = availabilityList.filter(
|
||||
(disp: { doctor_id: string }) => disp.doctor_id === doctor?.id
|
||||
);
|
||||
setAvailability(filteredAvail);
|
||||
} catch (e: any) {
|
||||
alert(`${e?.error} ${e?.message}`);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
@ -320,20 +320,21 @@ export default function AvailabilityPage() {
|
||||
}
|
||||
} catch {}
|
||||
|
||||
toast({
|
||||
title: "Sucesso",
|
||||
description: message,
|
||||
});
|
||||
router.push("#"); // adicionar página para listar a disponibilidade
|
||||
} catch (err: any) {
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: err?.message || "Não foi possível criar a disponibilidade",
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
toast({
|
||||
title: "Sucesso",
|
||||
description: message,
|
||||
});
|
||||
router.push("#"); // adicionar página para listar a disponibilidade
|
||||
} catch (err: any) {
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: err?.message || "Não foi possível criar a disponibilidade",
|
||||
});
|
||||
} finally {
|
||||
fetchData()
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const openDeleteDialog = (
|
||||
schedule: { start: string; end: string },
|
||||
@ -343,38 +344,35 @@ export default function AvailabilityPage() {
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleDeleteAvailability = async (AvailabilityId: string) => {
|
||||
try {
|
||||
const res = await AvailabilityService.delete(AvailabilityId);
|
||||
|
||||
let message = "Disponibilidade deletada com sucesso";
|
||||
try {
|
||||
if (res) {
|
||||
throw new Error(
|
||||
`${res.error} ${res.message}` || "A API retornou erro"
|
||||
);
|
||||
} else {
|
||||
console.log(message);
|
||||
}
|
||||
} catch {}
|
||||
|
||||
toast({
|
||||
title: "Sucesso",
|
||||
description: message,
|
||||
});
|
||||
|
||||
setAvailability((prev: Availability[]) =>
|
||||
prev.filter((p) => String(p.id) !== String(AvailabilityId))
|
||||
);
|
||||
} catch (e: any) {
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: e?.message || "Não foi possível deletar a disponibilidade",
|
||||
});
|
||||
}
|
||||
setDeleteDialogOpen(false);
|
||||
setSelectedAvailability(null);
|
||||
};
|
||||
const handleDeleteAvailability = async (AvailabilityId: string) => {
|
||||
try {
|
||||
const res = await AvailabilityService.delete(AvailabilityId);
|
||||
|
||||
let message = "Disponibilidade deletada com sucesso";
|
||||
try {
|
||||
if (res) {
|
||||
throw new Error(`${res.error} ${res.message}` || "A API retornou erro");
|
||||
} else {
|
||||
console.log(message);
|
||||
}
|
||||
} catch {}
|
||||
|
||||
toast({
|
||||
title: "Sucesso",
|
||||
description: message,
|
||||
});
|
||||
|
||||
setAvailability((prev: Availability[]) => prev.filter((p) => String(p.id) !== String(AvailabilityId)));
|
||||
} catch (e: any) {
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: e?.message || "Não foi possível deletar a disponibilidade",
|
||||
});
|
||||
}
|
||||
fetchData()
|
||||
setDeleteDialogOpen(false);
|
||||
setSelectedAvailability(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<Sidebar>
|
||||
@ -542,142 +540,99 @@ export default function AvailabilityPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* **AJUSTE DE RESPONSIVIDADE: BOTÕES DE AÇÃO** */}
|
||||
{/* Alinha à direita em telas maiores e empilha (com o botão primário no final) em telas menores */}
|
||||
{/* 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">
|
||||
<Link
|
||||
href="/doctor/disponibilidade/excecoes"
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
<Button
|
||||
variant="default"
|
||||
className="w-full sm:w-auto bg-blue-600 hover:bg-blue-700 text-white cursor-pointer"
|
||||
>
|
||||
Adicionar Exceção
|
||||
</Button>
|
||||
</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 */}
|
||||
<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>
|
||||
{/* **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 */}
|
||||
{/* 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">
|
||||
<Link href="/doctor/disponibilidade/excecoes" className="w-full sm:w-auto">
|
||||
<Button variant="default" className="w-full sm:w-auto">Adicionar Exceção</Button>
|
||||
</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 */}
|
||||
<Link href="/doctor/dashboard" className="w-full sm:w-auto">
|
||||
<Button variant="outline" className="w-full sm:w-auto">Cancelar</Button>
|
||||
</Link>
|
||||
<Button type="submit" className="bg-green-600 hover:bg-green-700 w-full sm:w-auto">
|
||||
Salvar Disponibilidade
|
||||
</Button>
|
||||
</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>
|
||||
);
|
||||
</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 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>
|
||||
);
|
||||
})}
|
||||
</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 { useRouter } from "next/navigation";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
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 { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Edit, Trash2, Eye, Calendar, 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";
|
||||
|
||||
// --- 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 {
|
||||
id: number;
|
||||
full_name: string;
|
||||
@ -66,119 +51,111 @@ interface DoctorDetails {
|
||||
export default function DoctorsPage() {
|
||||
const router = useRouter();
|
||||
|
||||
const [doctors, setDoctors] = useState<Doctor[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
||||
const [doctorDetails, setDoctorDetails] = useState<DoctorDetails | null>(
|
||||
null
|
||||
);
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [doctorToDeleteId, setDoctorToDeleteId] = useState<number | null>(null);
|
||||
// --- Estados de Dados ---
|
||||
const [doctors, setDoctors] = useState<Doctor[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// --- Estados para Filtros ---
|
||||
const [specialtyFilter, setSpecialtyFilter] = useState("all");
|
||||
const [statusFilter, setStatusFilter] = useState("all");
|
||||
// --- Estados de Modais ---
|
||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
||||
const [doctorDetails, setDoctorDetails] = useState<DoctorDetails | null>(null);
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [doctorToDeleteId, setDoctorToDeleteId] = useState<number | null>(null);
|
||||
|
||||
// --- Estados para Paginação ---
|
||||
const [itemsPerPage, setItemsPerPage] = useState(10);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
// --- Estados de Filtro e Busca ---
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
const [filters, setFilters] = useState({
|
||||
specialty: "all",
|
||||
status: "all"
|
||||
});
|
||||
|
||||
const fetchDoctors = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data: Doctor[] = await doctorsService.list();
|
||||
const dataWithStatus = data.map((doc, index) => ({
|
||||
...doc,
|
||||
status:
|
||||
index % 3 === 0 ? "Inativo" : index % 2 === 0 ? "Férias" : "Ativo",
|
||||
}));
|
||||
setDoctors(dataWithStatus || []);
|
||||
setCurrentPage(1);
|
||||
} catch (e: any) {
|
||||
console.error("Erro ao carregar lista de médicos:", e);
|
||||
setError(
|
||||
"Não foi possível carregar a lista de médicos. Verifique a conexão com a API."
|
||||
);
|
||||
setDoctors([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
// --- Estados de Paginação ---
|
||||
const [itemsPerPage, setItemsPerPage] = useState(10);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
|
||||
// 1. Buscar Médicos na API
|
||||
const fetchDoctors = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data: Doctor[] = await doctorsService.list();
|
||||
// Mockando status para visualização (conforme original)
|
||||
const dataWithStatus = data.map((doc, index) => ({
|
||||
...doc,
|
||||
status: index % 3 === 0 ? "Inativo" : index % 2 === 0 ? "Férias" : "Ativo",
|
||||
}));
|
||||
setDoctors(dataWithStatus || []);
|
||||
// Não resetamos a página aqui para manter a navegação fluida se apenas recarregar dados
|
||||
} catch (e: any) {
|
||||
console.error("Erro ao carregar lista de médicos:", e);
|
||||
setError("Não foi possível carregar a lista de médicos. Verifique a conexão com a API.");
|
||||
setDoctors([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchDoctors();
|
||||
}, [fetchDoctors]);
|
||||
|
||||
const openDetailsDialog = async (doctor: Doctor) => {
|
||||
setDetailsDialogOpen(true);
|
||||
setDoctorDetails({
|
||||
nome: doctor.full_name,
|
||||
crm: doctor.crm,
|
||||
especialidade: doctor.specialty,
|
||||
contato: { celular: doctor.phone_mobile ?? undefined },
|
||||
endereco: {
|
||||
cidade: doctor.city ?? undefined,
|
||||
estado: doctor.state ?? undefined,
|
||||
},
|
||||
status: doctor.status || "Ativo",
|
||||
convenio: "Particular",
|
||||
vip: false,
|
||||
ultimo_atendimento: "N/A",
|
||||
proximo_atendimento: "N/A",
|
||||
});
|
||||
};
|
||||
// 2. Gerar lista única de especialidades (Normalizada)
|
||||
const uniqueSpecialties = useMemo(() => {
|
||||
return getUniqueSpecialties(doctors);
|
||||
}, [doctors]);
|
||||
|
||||
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);
|
||||
}
|
||||
};
|
||||
// 3. Lógica de Filtragem Centralizada
|
||||
const filteredDoctors = useMemo(() => {
|
||||
return doctors.filter((doctor) => {
|
||||
// Normaliza a especialidade do médico atual para comparar
|
||||
const normalizedDocSpecialty = normalizeSpecialty(doctor.specialty);
|
||||
|
||||
// Filtros exatos
|
||||
const specialtyMatch = filters.specialty === "all" || normalizedDocSpecialty === filters.specialty;
|
||||
const statusMatch = filters.status === "all" || doctor.status === filters.status;
|
||||
|
||||
// Busca textual (Nome, Telefone, CRM)
|
||||
const searchLower = searchTerm.toLowerCase();
|
||||
const nameMatch = doctor.full_name?.toLowerCase().includes(searchLower);
|
||||
const phoneMatch = doctor.phone_mobile?.includes(searchLower);
|
||||
const crmMatch = doctor.crm?.toLowerCase().includes(searchLower);
|
||||
|
||||
const openDeleteDialog = (doctorId: number) => {
|
||||
setDoctorToDeleteId(doctorId);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
return specialtyMatch && statusMatch && (searchTerm === "" || nameMatch || phoneMatch || crmMatch);
|
||||
});
|
||||
}, [doctors, filters, searchTerm]);
|
||||
|
||||
const uniqueSpecialties = useMemo(() => {
|
||||
const specialties = doctors
|
||||
.map((doctor) => doctor.specialty)
|
||||
.filter(Boolean);
|
||||
return [...new Set(specialties)];
|
||||
}, [doctors]);
|
||||
// --- Handlers de Controle (Com Reset de Paginação) ---
|
||||
|
||||
const filteredDoctors = doctors.filter((doctor) => {
|
||||
const specialtyMatch =
|
||||
specialtyFilter === "all" || doctor.specialty === specialtyFilter;
|
||||
const statusMatch =
|
||||
statusFilter === "all" || doctor.status === statusFilter;
|
||||
return specialtyMatch && statusMatch;
|
||||
});
|
||||
const handleSearch = (term: string) => {
|
||||
setSearchTerm(term);
|
||||
setCurrentPage(1); // Correção: Reseta para página 1 ao buscar
|
||||
};
|
||||
|
||||
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 handleFilterChange = (key: string, value: string) => {
|
||||
setFilters(prev => ({ ...prev, [key]: value }));
|
||||
setCurrentPage(1); // Correção: Reseta para página 1 ao filtrar
|
||||
};
|
||||
|
||||
const goToPrevPage = () => {
|
||||
setCurrentPage((prev) => Math.max(1, prev - 1));
|
||||
};
|
||||
const handleClearFilters = () => {
|
||||
setSearchTerm("");
|
||||
setFilters({ specialty: "all", status: "all" });
|
||||
setCurrentPage(1); // Correção: Reseta para página 1 ao limpar
|
||||
};
|
||||
|
||||
const goToNextPage = () => {
|
||||
setCurrentPage((prev) => Math.min(totalPages, prev + 1));
|
||||
};
|
||||
const handleItemsPerPageChange = (value: string) => {
|
||||
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 pages: number[] = [];
|
||||
@ -204,10 +181,43 @@ export default function DoctorsPage() {
|
||||
|
||||
const visiblePageNumbers = getVisiblePageNumbers(totalPages, currentPage);
|
||||
|
||||
const handleItemsPerPageChange = (value: string) => {
|
||||
setItemsPerPage(Number(value));
|
||||
setCurrentPage(1);
|
||||
};
|
||||
// --- Handlers de Ações (Detalhes e Delete) ---
|
||||
const openDetailsDialog = (doctor: Doctor) => {
|
||||
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 (
|
||||
<Sidebar>
|
||||
@ -224,257 +234,192 @@ export default function DoctorsPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filtros e Itens por Página */}
|
||||
<div className="flex flex-wrap items-center gap-3 bg-white p-3 sm:p-4 rounded-lg border border-gray-200">
|
||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
||||
<span className="text-sm font-medium text-foreground">
|
||||
Especialidade
|
||||
</span>
|
||||
<Select value={specialtyFilter} onValueChange={setSpecialtyFilter}>
|
||||
<SelectTrigger className="w-[160px] sm:w-[180px]">
|
||||
<SelectValue placeholder="Especialidade" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todas</SelectItem>
|
||||
{uniqueSpecialties.map((specialty) => (
|
||||
<SelectItem key={specialty} value={specialty}>
|
||||
{specialty}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</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"
|
||||
{/* --- NOVO COMPONENTE DE FILTRO --- */}
|
||||
<FilterBar
|
||||
searchTerm={searchTerm}
|
||||
onSearch={handleSearch}
|
||||
activeFilters={filters}
|
||||
onFilterChange={handleFilterChange}
|
||||
onClearFilters={handleClearFilters}
|
||||
searchPlaceholder="Buscar por nome, CRM ou telefone..."
|
||||
filters={[
|
||||
{
|
||||
key: "specialty",
|
||||
label: "Especialidade",
|
||||
options: uniqueSpecialties
|
||||
},
|
||||
{
|
||||
key: "status",
|
||||
label: "Status",
|
||||
options: ["Ativo", "Férias", "Inativo"]
|
||||
}
|
||||
]}
|
||||
>
|
||||
<div>
|
||||
<div className="font-semibold text-gray-900">
|
||||
{doctor.full_name}
|
||||
{/* Seletor de Itens por Página (Filho do FilterBar) */}
|
||||
<div className="hidden lg:block">
|
||||
<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 className="text-sm text-gray-600">
|
||||
{doctor.specialty}
|
||||
</div>
|
||||
</div>
|
||||
<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>
|
||||
</FilterBar>
|
||||
|
||||
{/* Tabela de Médicos */}
|
||||
<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">
|
||||
{/* 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>
|
||||
|
||||
{/* Paginação */}
|
||||
{totalPages > 1 && (
|
||||
@ -511,31 +456,22 @@ export default function DoctorsPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Dialogs de Exclusão e Detalhes */}
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Confirma a exclusão?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Esta ação é irreversível e excluirá permanentemente o registro
|
||||
deste médico.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={loading}>Cancelar</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleDelete}
|
||||
className="bg-red-600 hover:bg-red-700"
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? (
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
) : null}
|
||||
Excluir
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
{/* Dialogs (Exclusão e Detalhes) */}
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Confirma a exclusão?</AlertDialogTitle>
|
||||
<AlertDialogDescription>Esta ação é irreversível e excluirá permanentemente o registro deste médico.</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={loading}>Cancelar</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleDelete} className="bg-red-600 hover:bg-red-700" disabled={loading}>
|
||||
{loading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null}
|
||||
Excluir
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
<AlertDialog
|
||||
open={detailsDialogOpen}
|
||||
|
||||
@ -3,23 +3,10 @@
|
||||
import React, { useEffect, useState, useCallback } from "react";
|
||||
import Link from "next/link";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Plus, Eye, Filter, Loader2 } from "lucide-react";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Input } from "@/components/ui/input"; // <--- 1. Importação Adicionada
|
||||
import { Plus, Eye, Filter, Loader2, Search } from "lucide-react"; // <--- 1. Ícone Search Adicionado
|
||||
import { AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||
import { api, login } from "services/api.mjs";
|
||||
import { usersService } from "services/usersApi.mjs";
|
||||
import Sidebar from "@/components/Sidebar";
|
||||
@ -41,12 +28,15 @@ interface UserInfoResponse {
|
||||
}
|
||||
|
||||
export default function UsersPage() {
|
||||
const [users, setUsers] = useState<FlatUser[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
||||
const [userDetails, setUserDetails] = useState<UserInfoResponse | null>(null);
|
||||
const [selectedRole, setSelectedRole] = useState<string>("all");
|
||||
const [users, setUsers] = useState<FlatUser[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
||||
const [userDetails, setUserDetails] = useState<UserInfoResponse | null>(null);
|
||||
|
||||
// --- Estados de Filtro ---
|
||||
const [searchTerm, setSearchTerm] = useState(""); // <--- 2. Estado da busca
|
||||
const [selectedRole, setSelectedRole] = useState<string>("all");
|
||||
|
||||
// --- Lógica de Paginação INÍCIO ---
|
||||
const [itemsPerPage, setItemsPerPage] = useState(10);
|
||||
@ -130,10 +120,21 @@ export default function UsersPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const filteredUsers =
|
||||
selectedRole && selectedRole !== "all"
|
||||
? users.filter((u) => u.role === selectedRole)
|
||||
: users;
|
||||
// --- 3. Lógica de Filtragem Atualizada ---
|
||||
const filteredUsers = users.filter((u) => {
|
||||
// Filtro por Papel (Role)
|
||||
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 indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
||||
@ -191,63 +192,71 @@ export default function UsersPage() {
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* Filtro e Itens por Página */}
|
||||
<div className="flex flex-wrap items-center gap-3 bg-white p-4 rounded-lg border border-gray-200">
|
||||
{/* Select de Filtro por Papel - Ajustado para resetar a página */}
|
||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
||||
<span className="text-sm font-medium text-foreground whitespace-nowrap">
|
||||
Filtrar por papel
|
||||
</span>
|
||||
<Select
|
||||
onValueChange={(value) => {
|
||||
setSelectedRole(value);
|
||||
setCurrentPage(1);
|
||||
}}
|
||||
value={selectedRole}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-[180px]">
|
||||
{" "}
|
||||
{/* w-full para mobile, w-[180px] para sm+ */}
|
||||
<SelectValue placeholder="Filtrar por papel" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todos</SelectItem>
|
||||
<SelectItem value="admin">Admin</SelectItem>
|
||||
<SelectItem value="gestor">Gestor</SelectItem>
|
||||
<SelectItem value="medico">Médico</SelectItem>
|
||||
<SelectItem value="secretaria">Secretária</SelectItem>
|
||||
<SelectItem value="user">Usuário</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
{/* --- 4. Filtro (Barra de Pesquisa + Selects) --- */}
|
||||
<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 Itens por Página */}
|
||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
||||
<span className="text-sm font-medium text-foreground whitespace-nowrap">
|
||||
Itens por página
|
||||
</span>
|
||||
<Select
|
||||
onValueChange={handleItemsPerPageChange}
|
||||
defaultValue={String(itemsPerPage)}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-[140px]">
|
||||
{" "}
|
||||
{/* w-full para mobile, w-[140px] para sm+ */}
|
||||
<SelectValue placeholder="Itens por pág." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="5">5 por página</SelectItem>
|
||||
<SelectItem value="10">10 por página</SelectItem>
|
||||
<SelectItem value="20">20 por página</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<Button variant="outline" className="ml-auto w-full md:w-auto">
|
||||
<Filter className="w-4 h-4 mr-2" />
|
||||
Filtro avançado
|
||||
</Button>
|
||||
</div>
|
||||
{/* Fim do Filtro e Itens por Página */}
|
||||
{/* 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="Buscar por nome, e-mail ou telefone..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => {
|
||||
setSearchTerm(e.target.value);
|
||||
setCurrentPage(1); // Reseta a paginação ao pesquisar
|
||||
}}
|
||||
className="pl-10 w-full bg-gray-50 border-gray-200 focus:bg-white transition-colors"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-3 w-full md:w-auto">
|
||||
{/* Select de Filtro por Papel */}
|
||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
||||
<Select
|
||||
onValueChange={(value) => {
|
||||
setSelectedRole(value);
|
||||
setCurrentPage(1);
|
||||
}}
|
||||
value={selectedRole}>
|
||||
|
||||
<SelectTrigger className="w-full sm:w-[150px]">
|
||||
<SelectValue placeholder="Papel" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todos</SelectItem>
|
||||
<SelectItem value="admin">Admin</SelectItem>
|
||||
<SelectItem value="gestor">Gestor</SelectItem>
|
||||
<SelectItem value="medico">Médico</SelectItem>
|
||||
<SelectItem value="secretaria">Secretária</SelectItem>
|
||||
<SelectItem value="user">Usuário</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Select de Itens por Página */}
|
||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
||||
<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 */}
|
||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-x-auto">
|
||||
@ -315,34 +324,34 @@ export default function UsersPage() {
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
{/* Layout em Cards/Lista para Telas Pequenas */}
|
||||
<div className="md:hidden divide-y divide-gray-200">
|
||||
{currentItems.map((u) => (
|
||||
<div
|
||||
key={u.id}
|
||||
className="flex items-center justify-between p-4 hover:bg-gray-50"
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm font-medium text-gray-900 truncate">
|
||||
{u.full_name || "—"}
|
||||
</div>
|
||||
<div className="text-sm text-gray-500 capitalize">
|
||||
{u.role || "—"}
|
||||
</div>
|
||||
</div>
|
||||
<div className="ml-4 flex-shrink-0">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => openDetailsDialog(u)}
|
||||
title="Visualizar"
|
||||
>
|
||||
<Eye className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{/* Layout em Cards/Lista para Telas Pequenas */}
|
||||
<div className="md:hidden divide-y divide-gray-200">
|
||||
{currentItems.map((u) => (
|
||||
<div key={u.id} className="flex items-center justify-between p-4 hover:bg-gray-50">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm font-medium text-gray-900 truncate">
|
||||
{u.full_name || "—"}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 truncate">
|
||||
{u.email}
|
||||
</div>
|
||||
<div className="text-sm text-gray-500 capitalize mt-1">
|
||||
{u.role || "—"}
|
||||
</div>
|
||||
</div>
|
||||
<div className="ml-4 flex-shrink-0">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => openDetailsDialog(u)}
|
||||
title="Visualizar"
|
||||
>
|
||||
<Eye className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Paginação */}
|
||||
{totalPages > 1 && (
|
||||
|
||||
@ -227,31 +227,24 @@ export default function PacientesPage() {
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* VIP - Ocupa a largura total em telas pequenas, depois se ajusta */}
|
||||
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[150px]">
|
||||
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">
|
||||
VIP
|
||||
</span>
|
||||
<Select value={vipFilter} onValueChange={setVipFilter}>
|
||||
<SelectTrigger className="w-full sm:w-32">
|
||||
{" "}
|
||||
{/* w-full para mobile, w-32 para sm+ */}
|
||||
<SelectValue placeholder="VIP" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todos</SelectItem>
|
||||
<SelectItem value="vip">VIP</SelectItem>
|
||||
<SelectItem value="regular">Regular</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* 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>
|
||||
{/* VIP - Ocupa a largura total em telas pequenas, depois se ajusta */}
|
||||
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[150px]">
|
||||
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">VIP</span>
|
||||
<Select value={vipFilter} onValueChange={setVipFilter}>
|
||||
<SelectTrigger className="w-full sm:w-32"> {/* w-full para mobile, w-32 para sm+ */}
|
||||
<SelectValue placeholder="VIP" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todos</SelectItem>
|
||||
<SelectItem value="vip">VIP</SelectItem>
|
||||
<SelectItem value="regular">Regular</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
{/* --- SEÇÃO DE TABELA (VISÍVEL EM TELAS MAIORES OU IGUAIS A MD) --- */}
|
||||
{/* Garantir que a tabela se esconda em telas menores e apareça em MD+ */}
|
||||
|
||||
@ -188,18 +188,14 @@ export default function Sidebar({ children }: SidebarProps) {
|
||||
},
|
||||
];
|
||||
|
||||
const managerItems: MenuItem[] = [
|
||||
{ href: "/manager/dashboard", icon: Home, label: "Dashboard" },
|
||||
{ href: "#", icon: ClipboardMinus, label: "Relatórios gerenciais" },
|
||||
{ href: "/manager/usuario", icon: Users, label: "Gestão de Usuários" },
|
||||
{ href: "/manager/home", icon: Stethoscope, label: "Gestão de Médicos" },
|
||||
{ href: "/manager/pacientes", icon: Users, label: "Gestão de Pacientes" },
|
||||
{
|
||||
href: "/secretary/appointments",
|
||||
icon: CalendarCheck2,
|
||||
label: "Consultas",
|
||||
},
|
||||
];
|
||||
const managerItems: MenuItem[] = [
|
||||
{ href: "/manager/dashboard", icon: Home, label: "Dashboard" },
|
||||
{ href: "/manager/usuario", icon: Users, label: "Gestão de Usuários" },
|
||||
{ href: "/manager/home", icon: Stethoscope, label: "Gestão de Médicos" },
|
||||
{ href: "/manager/pacientes", icon: Users, label: "Gestão de Pacientes" },
|
||||
{ href: "/secretary/appointments", icon: CalendarCheck2, label: "Consultas" },
|
||||
{ href: "/manager/disponibilidade", icon: ClipboardList, label: "Disponibilidade" },
|
||||
];
|
||||
|
||||
switch (role) {
|
||||
case "gestor":
|
||||
|
||||
@ -19,9 +19,25 @@ import {
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Calendar as CalendarShadcn } from "@/components/ui/calendar";
|
||||
import { format, addDays } from "date-fns";
|
||||
import { User, StickyNote, Calendar } from "lucide-react";
|
||||
import { smsService } from "@/services/Sms.mjs";
|
||||
import { User, StickyNote, Check, ChevronsUpDown } from "lucide-react";
|
||||
import { smsService } from "@/services/Sms.mjs";;
|
||||
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() {
|
||||
// Estado do usuário e role
|
||||
@ -31,8 +47,12 @@ export default function ScheduleForm() {
|
||||
// Listas e seleções
|
||||
const [patients, setPatients] = useState<any[]>([]);
|
||||
const [selectedPatient, setSelectedPatient] = useState("");
|
||||
const [openPatientCombobox, setOpenPatientCombobox] = useState(false);
|
||||
|
||||
const [doctors, setDoctors] = useState<any[]>([]);
|
||||
const [selectedDoctor, setSelectedDoctor] = useState("");
|
||||
const [openDoctorCombobox, setOpenDoctorCombobox] = useState(false); // Novo estado para médico
|
||||
|
||||
const [selectedDate, setSelectedDate] = useState("");
|
||||
const [selectedTime, setSelectedTime] = useState("");
|
||||
const [notes, setNotes] = useState("");
|
||||
@ -249,10 +269,7 @@ export default function ScheduleForm() {
|
||||
}, [selectedDoctor, selectedDate, fetchAvailableSlots]);
|
||||
|
||||
// 🔹 Submeter agendamento
|
||||
// 🔹 Submeter agendamento
|
||||
// 🔹 Submeter agendamento
|
||||
// 🔹 Submeter agendamento
|
||||
// 🔹 Submeter agendamento
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
@ -260,10 +277,7 @@ export default function ScheduleForm() {
|
||||
const patientId = isSecretaryLike ? selectedPatient : userId;
|
||||
|
||||
if (!patientId || !selectedDoctor || !selectedDate || !selectedTime) {
|
||||
toast({
|
||||
title: "Campos obrigatórios",
|
||||
description: "Preencha todos os campos.",
|
||||
});
|
||||
toast({ title: "Campos obrigatórios", description: "Preencha todos os campos." });
|
||||
return;
|
||||
}
|
||||
|
||||
@ -277,7 +291,6 @@ export default function ScheduleForm() {
|
||||
appointment_type: tipoConsulta,
|
||||
};
|
||||
|
||||
// ✅ mantém o fluxo original de criação (funcional)
|
||||
await appointmentsService.create(body);
|
||||
|
||||
const dateFormatted = selectedDate.split("-").reverse().join("/");
|
||||
@ -289,31 +302,20 @@ export default function ScheduleForm() {
|
||||
}.`,
|
||||
});
|
||||
|
||||
let phoneNumber = "+5511999999999"; // fallback
|
||||
let phoneNumber = "+5511999999999";
|
||||
|
||||
try {
|
||||
if (isSecretaryLike) {
|
||||
// Secretária/admin → telefone do paciente selecionado
|
||||
const patient = patients.find((p: any) => p.id === patientId);
|
||||
|
||||
// Pacientes criados no sistema podem ter phone ou phone_mobile
|
||||
const rawPhone = patient?.phone || patient?.phone_mobile || null;
|
||||
|
||||
if (rawPhone) phoneNumber = rawPhone;
|
||||
} else {
|
||||
// Paciente → telefone vem do perfil do próprio usuário logado
|
||||
const me = await usersService.getMe();
|
||||
|
||||
const rawPhone =
|
||||
me?.profile?.phone ||
|
||||
(typeof me?.profile === "object" && "phone_mobile" in me.profile
|
||||
? (me.profile as any).phone_mobile
|
||||
: null) ||
|
||||
(typeof me === "object" && "user_metadata" in me
|
||||
? (me as any).user_metadata?.phone
|
||||
: null) ||
|
||||
(typeof me?.profile === "object" && "phone_mobile" in me.profile ? (me.profile as any).phone_mobile : null) ||
|
||||
(typeof me === "object" && "user_metadata" in me ? (me as any).user_metadata?.phone : null) ||
|
||||
null;
|
||||
|
||||
if (rawPhone) phoneNumber = rawPhone;
|
||||
}
|
||||
|
||||
@ -397,63 +399,114 @@ export default function ScheduleForm() {
|
||||
<CardTitle>Dados da Consulta</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form
|
||||
onSubmit={handleSubmit}
|
||||
className="grid grid-cols-1 lg:grid-cols-2 gap-6"
|
||||
>
|
||||
<div className="space-y-3">
|
||||
{/* Se secretária/gestor/admin → mostrar campo Paciente */}
|
||||
<form onSubmit={handleSubmit} className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<div className="space-y-4"> {/* Ajuste: maior espaçamento vertical geral */}
|
||||
|
||||
{/* Se secretária/gestor/admin → COMBOBOX de Paciente */}
|
||||
{["secretaria", "gestor", "admin"].includes(role) && (
|
||||
<div>
|
||||
<div className="flex flex-col gap-2"> {/* Ajuste: gap entre Label e Input */}
|
||||
<Label>Paciente</Label>
|
||||
<Select
|
||||
value={selectedPatient}
|
||||
onValueChange={setSelectedPatient}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Selecione o paciente" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{patients.map((p) => (
|
||||
<SelectItem key={p.id} value={p.id}>
|
||||
{p.full_name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Popover open={openPatientCombobox} onOpenChange={setOpenPatientCombobox}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
aria-expanded={openPatientCombobox}
|
||||
className="w-full justify-between"
|
||||
>
|
||||
{selectedPatient
|
||||
? patients.find((p) => p.id === selectedPatient)?.full_name
|
||||
: "Selecione o paciente..."}
|
||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<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>
|
||||
{/* COMBOBOX de Médico (Nova funcionalidade) */}
|
||||
<div className="flex flex-col gap-2"> {/* Ajuste: gap entre Label e Input */}
|
||||
<Label>Médico</Label>
|
||||
<Select
|
||||
value={selectedDoctor}
|
||||
onValueChange={setSelectedDoctor}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Selecione o médico" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{loadingDoctors ? (
|
||||
<SelectItem value="loading" disabled>
|
||||
Carregando...
|
||||
</SelectItem>
|
||||
) : (
|
||||
[...doctors]
|
||||
.sort((a, b) =>
|
||||
String(a.full_name).localeCompare(String(b.full_name))
|
||||
)
|
||||
.map((d) => (
|
||||
<SelectItem key={d.id} value={d.id}>
|
||||
{d.full_name} — {d.specialty}
|
||||
</SelectItem>
|
||||
))
|
||||
)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Popover open={openDoctorCombobox} onOpenChange={setOpenDoctorCombobox}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
aria-expanded={openDoctorCombobox}
|
||||
className="w-full justify-between"
|
||||
disabled={loadingDoctors}
|
||||
>
|
||||
{loadingDoctors
|
||||
? "Carregando médicos..."
|
||||
: selectedDoctor
|
||||
? doctors.find((d) => d.id === selectedDoctor)?.full_name
|
||||
: "Selecione o médico..."}
|
||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-[350px] p-0">
|
||||
<Command>
|
||||
<CommandInput placeholder="Buscar médico..." />
|
||||
<CommandList>
|
||||
<CommandEmpty>Nenhum médico encontrado.</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{doctors.map((doctor) => (
|
||||
<CommandItem
|
||||
key={doctor.id}
|
||||
value={doctor.full_name}
|
||||
onSelect={() => {
|
||||
setSelectedDoctor(doctor.id === selectedDoctor ? "" : doctor.id);
|
||||
setOpenDoctorCombobox(false);
|
||||
}}
|
||||
>
|
||||
<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 className="flex flex-col gap-2">
|
||||
<Label>Data</Label>
|
||||
<div ref={calendarRef} className="rounded-lg border p-2">
|
||||
<CalendarShadcn
|
||||
@ -476,18 +529,18 @@ export default function ScheduleForm() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>Observações</Label>
|
||||
<Textarea
|
||||
placeholder="Instruções para o médico..."
|
||||
value={notes}
|
||||
onChange={(e) => setNotes(e.target.value)}
|
||||
className="mt-2"
|
||||
className="mt-1"
|
||||
/>
|
||||
</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">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-blue-700">Resumo</CardTitle>
|
||||
@ -591,4 +644,4 @@ export default function ScheduleForm() {
|
||||
)}
|
||||
</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 {
|
||||
Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter, DialogClose
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} 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 {
|
||||
patient: Paciente | null;
|
||||
isOpen: boolean;
|
||||
patient: any;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function PatientDetailsModal({ patient, isOpen, onClose }: PatientDetailsModalProps) {
|
||||
export function PatientDetailsModal({
|
||||
patient,
|
||||
isOpen,
|
||||
onClose,
|
||||
}: PatientDetailsModalProps) {
|
||||
if (!patient) return null;
|
||||
|
||||
return (
|
||||
<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>
|
||||
<DialogTitle>Detalhes do Paciente</DialogTitle>
|
||||
<DialogDescription>Informações detalhadas sobre o paciente.</DialogDescription>
|
||||
<DialogTitle className="text-xl font-bold">Detalhes do Paciente</DialogTitle>
|
||||
<DialogDescription>
|
||||
Informações detalhadas sobre o paciente.
|
||||
</DialogDescription>
|
||||
</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>
|
||||
<p className="font-semibold">Nome Completo</p>
|
||||
<p>{patient.nome}</p>
|
||||
<p className="font-semibold text-gray-900">Nome Completo</p>
|
||||
<p className="text-gray-700">{patient.nome}</p>
|
||||
</div>
|
||||
|
||||
{/* CORREÇÃO AQUI: Adicionado 'break-all' para quebrar o email */}
|
||||
<div>
|
||||
<p className="font-semibold">Email</p>
|
||||
<p>{patient.email}</p>
|
||||
<p className="font-semibold text-gray-900">Email</p>
|
||||
<p className="text-gray-700 break-all">{patient.email || "N/A"}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="font-semibold">Telefone</p>
|
||||
<p>{patient.telefone}</p>
|
||||
<p className="font-semibold text-gray-900">Telefone</p>
|
||||
<p className="text-gray-700">{patient.telefone}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="font-semibold">Data de Nascimento</p>
|
||||
<p>{patient.birth_date}</p>
|
||||
<p className="font-semibold text-gray-900">Data de Nascimento</p>
|
||||
<p className="text-gray-700">{patient.birth_date || "N/A"}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="font-semibold">CPF</p>
|
||||
<p>{patient.cpf}</p>
|
||||
<p className="font-semibold text-gray-900">CPF</p>
|
||||
<p className="text-gray-700">{patient.cpf || "N/A"}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="font-semibold">Tipo Sanguíneo</p>
|
||||
<p>{patient.blood_type}</p>
|
||||
<p className="font-semibold text-gray-900">Tipo Sanguíneo</p>
|
||||
<p className="text-gray-700">{patient.blood_type || "N/A"}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="font-semibold">Peso (kg)</p>
|
||||
<p>{patient.weight_kg}</p>
|
||||
<p className="font-semibold text-gray-900">Peso (kg)</p>
|
||||
<p className="text-gray-700">{patient.weight_kg || "0"}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="font-semibold">Altura (m)</p>
|
||||
<p>{patient.height_m}</p>
|
||||
<p className="font-semibold text-gray-900">Altura (m)</p>
|
||||
<p className="text-gray-700">{patient.height_m || "0"}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-t pt-4 mt-4">
|
||||
<h3 className="font-semibold mb-2">Endereço</h3>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
|
||||
<hr className="border-gray-200" />
|
||||
|
||||
{/* 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>
|
||||
<p className="font-semibold">Rua</p>
|
||||
<p>{`${patient.street}, ${patient.number}`}</p>
|
||||
<p className="font-semibold text-gray-900">Rua</p>
|
||||
<p className="text-gray-700">
|
||||
{patient.street && patient.street !== "N/A"
|
||||
? `${patient.street}, ${patient.number || ""}`
|
||||
: "N/A"}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Complemento</p>
|
||||
<p>{patient.complement}</p>
|
||||
<p className="font-semibold text-gray-900">Complemento</p>
|
||||
<p className="text-gray-700">{patient.complement || "N/A"}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Bairro</p>
|
||||
<p>{patient.neighborhood}</p>
|
||||
<p className="font-semibold text-gray-900">Bairro</p>
|
||||
<p className="text-gray-700">{patient.neighborhood || "N/A"}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Cidade</p>
|
||||
<p>{patient.cidade}</p>
|
||||
<p className="font-semibold text-gray-900">Cidade</p>
|
||||
<p className="text-gray-700">{patient.cidade || "N/A"}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Estado</p>
|
||||
<p>{patient.estado}</p>
|
||||
<p className="font-semibold text-gray-900">Estado</p>
|
||||
<p className="text-gray-700">{patient.estado || "N/A"}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">CEP</p>
|
||||
<p>{patient.cep}</p>
|
||||
<p className="font-semibold text-gray-900">CEP</p>
|
||||
<p className="text-gray-700">{patient.cep || "N/A"}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<button type="button" className="px-4 py-2 bg-gray-200 rounded-md">Fechar</button>
|
||||
</DialogClose>
|
||||
<Button variant="secondary" onClick={onClose} className="w-full sm:w-auto">
|
||||
Fechar
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</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