Compare commits
3 Commits
main
...
responsivi
| Author | SHA1 | Date | |
|---|---|---|---|
| 63baee72f9 | |||
| ea48af4161 | |||
| a6b116fb57 |
@ -94,43 +94,44 @@ export default function AvailabilityPage() {
|
||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Dados </h2>
|
||||
|
||||
<div className="space-y-6">
|
||||
<div className="grid md:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<Label className="text-sm font-medium text-gray-700">Dia Da Semana</Label>
|
||||
<div className="flex gap-4 mt-2 flex-nowrap">
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="radio" name="weekday" value="monday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Segunda-Feira</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="radio" name="weekday" value="tuesday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Terça-Feira</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="radio" name="weekday" value="wednesday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Quarta-Feira</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="radio" name="weekday" value="thursday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Quinta-Feira</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="radio" name="weekday" value="friday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Sexta-Feira</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="radio" name="weekday" value="saturday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Sabado</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="radio" name="weekday" value="sunday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Domingo</span>
|
||||
</label>
|
||||
</div>
|
||||
{/* Ajuste de responsividade: removemos o grid para os dias da semana e focamos no div interno */}
|
||||
<div>
|
||||
<Label className="text-sm font-medium text-gray-700">Dia Da Semana</Label>
|
||||
{/* NOVO: Grid responsivo para os radio buttons dos dias da semana */}
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 md:grid-cols-7 gap-x-2 gap-y-1 mt-2">
|
||||
<label className="flex items-center gap-1">
|
||||
<input type="radio" name="weekday" value="monday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Segunda</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1">
|
||||
<input type="radio" name="weekday" value="tuesday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Terça</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1">
|
||||
<input type="radio" name="weekday" value="wednesday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Quarta</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1">
|
||||
<input type="radio" name="weekday" value="thursday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Quinta</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1">
|
||||
<input type="radio" name="weekday" value="friday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Sexta</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1">
|
||||
<input type="radio" name="weekday" value="saturday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Sábado</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1">
|
||||
<input type="radio" name="weekday" value="sunday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Domingo</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-5 gap-6">
|
||||
{/* NOVO: Grid responsivo para os campos de horário e duração */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-6">
|
||||
<div>
|
||||
<Label htmlFor="horarioEntrada" className="text-sm font-medium text-gray-700">
|
||||
Horario De Entrada
|
||||
@ -149,6 +150,7 @@ export default function AvailabilityPage() {
|
||||
</Label>
|
||||
<Input type="number" id="duracaoConsulta" name="duracaoConsulta" required className="mt-1" />
|
||||
</div>
|
||||
{/* A modalidade de consulta agora vai ocupar o espaço restante na linha ou ficar embaixo, dependendo do grid */}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
@ -168,14 +170,15 @@ export default function AvailabilityPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-4">
|
||||
{/* NOVO: Ajuste de responsividade para os botões */}
|
||||
<div className="flex flex-col-reverse sm:flex-row sm:justify-end gap-4">
|
||||
<Link href="/doctor/disponibilidade/excecoes">
|
||||
<Button variant="outline">Adicionar Exceção</Button>
|
||||
<Button variant="outline" className="w-full sm:w-auto">Adicionar Exceção</Button>
|
||||
</Link>
|
||||
<Link href="/doctor/dashboard">
|
||||
<Button variant="outline">Cancelar</Button>
|
||||
<Button variant="outline" className="w-full sm:w-auto">Cancelar</Button>
|
||||
</Link>
|
||||
<Button type="submit" className="bg-green-600 hover:bg-green-700">
|
||||
<Button type="submit" className="bg-green-600 hover:bg-green-700 w-full sm:w-auto">
|
||||
Salvar Disponibilidade
|
||||
</Button>
|
||||
</div>
|
||||
@ -183,4 +186,4 @@ export default function AvailabilityPage() {
|
||||
</div>
|
||||
</DoctorLayout>
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,7 @@
|
||||
// app/doctor/pacientes/page.tsx (assumindo a localização)
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useState, useCallback } from "react";
|
||||
import DoctorLayout from "@/components/doctor-layout";
|
||||
import Link from "next/link";
|
||||
import {
|
||||
@ -9,9 +10,17 @@ import {
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { Eye, Edit, Calendar, Trash2 } from "lucide-react";
|
||||
import { Eye, Edit, Calendar, Trash2, Loader2 } from "lucide-react";
|
||||
import { api } from "@/services/api.mjs";
|
||||
import { PatientDetailsModal } from "@/components/ui/patient-details-modal";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
interface Paciente {
|
||||
id: string;
|
||||
@ -41,6 +50,60 @@ export default function PacientesPage() {
|
||||
const [selectedPatient, setSelectedPatient] = useState<Paciente | null>(null);
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
|
||||
// --- Lógica de Paginação INÍCIO ---
|
||||
const [itemsPerPage, setItemsPerPage] = useState(5);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
|
||||
const totalPages = Math.ceil(pacientes.length / itemsPerPage);
|
||||
|
||||
const indexOfLastItem = currentPage * itemsPerPage;
|
||||
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
||||
const currentItems = pacientes.slice(indexOfFirstItem, indexOfLastItem);
|
||||
|
||||
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
|
||||
|
||||
// Funções de Navegação
|
||||
const goToPrevPage = () => {
|
||||
setCurrentPage((prev) => Math.max(1, prev - 1));
|
||||
};
|
||||
|
||||
const goToNextPage = () => {
|
||||
setCurrentPage((prev) => Math.min(totalPages, prev + 1));
|
||||
};
|
||||
|
||||
// Lógica para gerar os números das páginas visíveis (máximo de 5)
|
||||
const getVisiblePageNumbers = (totalPages: number, currentPage: number) => {
|
||||
const pages: number[] = [];
|
||||
const maxVisiblePages = 5;
|
||||
const halfRange = Math.floor(maxVisiblePages / 2);
|
||||
let startPage = Math.max(1, currentPage - halfRange);
|
||||
let endPage = Math.min(totalPages, currentPage + halfRange);
|
||||
|
||||
if (endPage - startPage + 1 < maxVisiblePages) {
|
||||
if (endPage === totalPages) {
|
||||
startPage = Math.max(1, totalPages - maxVisiblePages + 1);
|
||||
}
|
||||
if (startPage === 1) {
|
||||
endPage = Math.min(totalPages, maxVisiblePages);
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = startPage; i <= endPage; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
return pages;
|
||||
};
|
||||
|
||||
const visiblePageNumbers = getVisiblePageNumbers(totalPages, currentPage);
|
||||
|
||||
// Lógica para mudar itens por página, resetando para a página 1
|
||||
const handleItemsPerPageChange = (value: string) => {
|
||||
setItemsPerPage(Number(value));
|
||||
setCurrentPage(1);
|
||||
};
|
||||
// --- Lógica de Paginação FIM ---
|
||||
|
||||
|
||||
const handleOpenModal = (patient: Paciente) => {
|
||||
setSelectedPatient(patient);
|
||||
setIsModalOpen(true);
|
||||
@ -51,92 +114,132 @@ export default function PacientesPage() {
|
||||
setIsModalOpen(false);
|
||||
};
|
||||
|
||||
const formatDate = (dateString: string) => {
|
||||
if (!dateString) return "";
|
||||
const date = new Date(dateString);
|
||||
return new Intl.DateTimeFormat('pt-BR').format(date);
|
||||
const formatDate = (dateString: string | null | undefined) => {
|
||||
if (!dateString) return "N/A";
|
||||
try {
|
||||
const date = new Date(dateString);
|
||||
return new Intl.DateTimeFormat("pt-BR").format(date);
|
||||
} catch (e) {
|
||||
return dateString; // Retorna o string original se o formato for inválido
|
||||
}
|
||||
};
|
||||
|
||||
const [itemsPerPage, setItemsPerPage] = useState(5);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const fetchPacientes = useCallback(async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const json = await api.get("/rest/v1/patients");
|
||||
const items = Array.isArray(json)
|
||||
? json
|
||||
: Array.isArray(json?.data)
|
||||
? json.data
|
||||
: [];
|
||||
|
||||
const indexOfLastItem = currentPage * itemsPerPage;
|
||||
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
||||
const currentItems = pacientes.slice(indexOfFirstItem, indexOfLastItem);
|
||||
const mapped: Paciente[] = items.map((p: any) => ({
|
||||
id: String(p.id ?? ""),
|
||||
nome: p.full_name ?? "—",
|
||||
telefone: p.phone_mobile ?? "N/A",
|
||||
cidade: p.city ?? "N/A",
|
||||
estado: p.state ?? "N/A",
|
||||
ultimoAtendimento: formatDate(p.created_at),
|
||||
proximoAtendimento: "N/A", // Necessita de lógica de agendamento real
|
||||
email: p.email ?? "N/A",
|
||||
birth_date: p.birth_date ?? "N/A",
|
||||
cpf: p.cpf ?? "N/A",
|
||||
blood_type: p.blood_type ?? "N/A",
|
||||
weight_kg: p.weight_kg ?? 0,
|
||||
height_m: p.height_m ?? 0,
|
||||
street: p.street ?? "N/A",
|
||||
number: p.number ?? "N/A",
|
||||
complement: p.complement ?? "N/A",
|
||||
neighborhood: p.neighborhood ?? "N/A",
|
||||
cep: p.cep ?? "N/A",
|
||||
}));
|
||||
|
||||
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
|
||||
setPacientes(mapped);
|
||||
setCurrentPage(1); // Resetar a página ao carregar novos dados
|
||||
} catch (e: any) {
|
||||
console.error("Erro ao carregar pacientes:", e);
|
||||
setError(e?.message || "Erro ao carregar pacientes");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchPacientes() {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const json = await api.get("/rest/v1/patients");
|
||||
const items = Array.isArray(json) ? json : (Array.isArray(json?.data) ? json.data : []);
|
||||
|
||||
const mapped = items.map((p: any) => ({
|
||||
id: String(p.id ?? ""),
|
||||
nome: p.full_name ?? "",
|
||||
telefone: p.phone_mobile ?? "",
|
||||
cidade: p.city ?? "",
|
||||
estado: p.state ?? "",
|
||||
ultimoAtendimento: formatDate(p.created_at) ?? "",
|
||||
proximoAtendimento: "",
|
||||
email: p.email ?? "",
|
||||
birth_date: p.birth_date ?? "",
|
||||
cpf: p.cpf ?? "",
|
||||
blood_type: p.blood_type ?? "",
|
||||
weight_kg: p.weight_kg ?? 0,
|
||||
height_m: p.height_m ?? 0,
|
||||
street: p.street ?? "",
|
||||
number: p.number ?? "",
|
||||
complement: p.complement ?? "",
|
||||
neighborhood: p.neighborhood ?? "",
|
||||
cep: p.cep ?? "",
|
||||
}));
|
||||
|
||||
setPacientes(mapped);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Erro ao carregar pacientes");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
fetchPacientes();
|
||||
}, []);
|
||||
}, [fetchPacientes]);
|
||||
|
||||
return (
|
||||
<DoctorLayout>
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-foreground">Pacientes</h1>
|
||||
<p className="text-muted-foreground">Lista de pacientes vinculados</p>
|
||||
<div className="space-y-6 px-2 sm:px-4 md:px-6">
|
||||
{/* Cabeçalho */}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-foreground">Pacientes</h1>
|
||||
<p className="text-muted-foreground text-sm sm:text-base">
|
||||
Lista de pacientes vinculados
|
||||
</p>
|
||||
</div>
|
||||
{/* Adicione um seletor de itens por página ao lado de um botão de 'Novo Paciente' se aplicável */}
|
||||
<div className="flex gap-3">
|
||||
<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>
|
||||
<Link href="/doctor/pacientes/novo">
|
||||
<Button variant="default" className="bg-primary hover:bg-primary/90">
|
||||
Novo Paciente
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-card rounded-lg border border-border">
|
||||
|
||||
<div className="bg-card rounded-lg border border-border overflow-hidden shadow-md">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full">
|
||||
<table className="min-w-[600px] w-full">
|
||||
<thead className="bg-muted border-b border-border">
|
||||
<tr>
|
||||
<th className="text-left p-4 font-medium text-foreground">Nome</th>
|
||||
<th className="text-left p-4 font-medium text-foreground">Telefone</th>
|
||||
<th className="text-left p-4 font-medium text-foreground">Cidade</th>
|
||||
<th className="text-left p-4 font-medium text-foreground">Estado</th>
|
||||
<th className="text-left p-4 font-medium text-foreground">Último atendimento</th>
|
||||
<th className="text-left p-4 font-medium text-foreground">Próximo atendimento</th>
|
||||
<th className="text-left p-4 font-medium text-foreground">Ações</th>
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground">Nome</th>
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden md:table-cell">
|
||||
Telefone
|
||||
</th>
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden lg:table-cell">
|
||||
Cidade
|
||||
</th>
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden lg:table-cell">
|
||||
Estado
|
||||
</th>
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden xl:table-cell">
|
||||
Último atendimento
|
||||
</th>
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden xl:table-cell">
|
||||
Próximo atendimento
|
||||
</th>
|
||||
<th className="text-left p-3 sm:p-4 font-medium text-foreground">Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{loading ? (
|
||||
<tr>
|
||||
<td colSpan={7} className="p-6 text-muted-foreground">
|
||||
<td colSpan={7} className="p-6 text-muted-foreground text-center">
|
||||
<Loader2 className="w-6 h-6 animate-spin mx-auto text-primary" />
|
||||
Carregando pacientes...
|
||||
</td>
|
||||
</tr>
|
||||
) : error ? (
|
||||
<tr>
|
||||
<td colSpan={7} className="p-6 text-red-600">{`Erro: ${error}`}</td>
|
||||
<td colSpan={7} className="p-6 text-red-600 text-center">{`Erro: ${error}`}</td>
|
||||
</tr>
|
||||
) : pacientes.length === 0 ? (
|
||||
<tr>
|
||||
@ -146,17 +249,32 @@ export default function PacientesPage() {
|
||||
</tr>
|
||||
) : (
|
||||
currentItems.map((p) => (
|
||||
<tr key={p.id} className="border-b border-border hover:bg-accent">
|
||||
<td className="p-4">{p.nome}</td>
|
||||
<td className="p-4 text-muted-foreground">{p.telefone}</td>
|
||||
<td className="p-4 text-muted-foreground">{p.cidade}</td>
|
||||
<td className="p-4 text-muted-foreground">{p.estado}</td>
|
||||
<td className="p-4 text-muted-foreground">{p.ultimoAtendimento}</td>
|
||||
<td className="p-4 text-muted-foreground">{p.proximoAtendimento}</td>
|
||||
<td className="p-4">
|
||||
<tr
|
||||
key={p.id}
|
||||
className="border-b border-border hover:bg-accent/40 transition-colors"
|
||||
>
|
||||
<td className="p-3 sm:p-4">{p.nome}</td>
|
||||
<td className="p-3 sm:p-4 text-muted-foreground hidden md:table-cell">
|
||||
{p.telefone}
|
||||
</td>
|
||||
<td className="p-3 sm:p-4 text-muted-foreground hidden lg:table-cell">
|
||||
{p.cidade}
|
||||
</td>
|
||||
<td className="p-3 sm:p-4 text-muted-foreground hidden lg:table-cell">
|
||||
{p.estado}
|
||||
</td>
|
||||
<td className="p-3 sm:p-4 text-muted-foreground hidden xl:table-cell">
|
||||
{p.ultimoAtendimento}
|
||||
</td>
|
||||
<td className="p-3 sm:p-4 text-muted-foreground hidden xl:table-cell">
|
||||
{p.proximoAtendimento}
|
||||
</td>
|
||||
<td className="p-3 sm:p-4">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="text-primary hover:underline">Ações</button>
|
||||
<button className="text-primary hover:underline text-sm sm:text-base">
|
||||
Ações
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => handleOpenModal(p)}>
|
||||
@ -164,7 +282,7 @@ export default function PacientesPage() {
|
||||
Ver detalhes
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/doctor/medicos/${p.id}/laudos`}>
|
||||
<Link href={`/doctor/pacientes/${p.id}/laudos`}>
|
||||
<Edit className="w-4 h-4 mr-2" />
|
||||
Laudos
|
||||
</Link>
|
||||
@ -175,11 +293,14 @@ export default function PacientesPage() {
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
const newPacientes = pacientes.filter((pac) => pac.id !== p.id)
|
||||
setPacientes(newPacientes)
|
||||
alert(`Paciente ID: ${p.id} excluído`)
|
||||
// Simulação de exclusão (A exclusão real deve ser feita via API)
|
||||
const newPacientes = pacientes.filter((pac) => pac.id !== p.id);
|
||||
setPacientes(newPacientes);
|
||||
alert(`Paciente ID: ${p.id} excluído`);
|
||||
// Necessário chamar a API de exclusão aqui
|
||||
}}
|
||||
className="text-red-600">
|
||||
className="text-red-600 focus:bg-red-50 focus:text-red-600"
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
Excluir
|
||||
</DropdownMenuItem>
|
||||
@ -192,19 +313,51 @@ export default function PacientesPage() {
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div className="flex justify-center space-x-2 mt-4 p-4">
|
||||
{Array.from({ length: Math.ceil(pacientes.length / itemsPerPage) }, (_, i) => (
|
||||
|
||||
{/* Paginação ATUALIZADA */}
|
||||
{totalPages > 1 && (
|
||||
<div className="flex flex-wrap justify-center items-center gap-2 border-t border-border p-4 bg-muted/40">
|
||||
|
||||
{/* Botão Anterior */}
|
||||
<button
|
||||
key={i}
|
||||
onClick={() => paginate(i + 1)}
|
||||
className={`px-4 py-2 rounded-md ${currentPage === i + 1 ? 'bg-primary text-primary-foreground' : 'bg-secondary text-secondary-foreground'}`}
|
||||
onClick={goToPrevPage}
|
||||
disabled={currentPage === 1}
|
||||
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-secondary text-secondary-foreground hover:bg-secondary/80 disabled:opacity-50 disabled:cursor-not-allowed border border-border"
|
||||
>
|
||||
{i + 1}
|
||||
{"< Anterior"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Números das Páginas */}
|
||||
{visiblePageNumbers.map((number) => (
|
||||
<button
|
||||
key={number}
|
||||
onClick={() => paginate(number)}
|
||||
className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border border-border ${
|
||||
currentPage === number
|
||||
? "bg-primary text-primary-foreground shadow-md border-primary"
|
||||
: "bg-secondary text-secondary-foreground hover:bg-secondary/80"
|
||||
}`}
|
||||
>
|
||||
{number}
|
||||
</button>
|
||||
))}
|
||||
|
||||
{/* Botão Próximo */}
|
||||
<button
|
||||
onClick={goToNextPage}
|
||||
disabled={currentPage === totalPages}
|
||||
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-secondary text-secondary-foreground hover:bg-secondary/80 disabled:opacity-50 disabled:cursor-not-allowed border border-border"
|
||||
>
|
||||
{"Próximo >"}
|
||||
</button>
|
||||
|
||||
</div>
|
||||
)}
|
||||
{/* Fim da Paginação ATUALIZADA */}
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<PatientDetailsModal
|
||||
patient={selectedPatient}
|
||||
isOpen={isModalOpen}
|
||||
|
||||
@ -1,13 +1,34 @@
|
||||
// app/manager/home/page.tsx (ou doctors/page.tsx, dependendo da sua rota)
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState, useCallback } from "react"
|
||||
import React, { useEffect, useState, useCallback } from "react";
|
||||
import ManagerLayout from "@/components/manager-layout";
|
||||
import Link from "next/link"
|
||||
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 { Plus, Edit, Trash2, Eye, Calendar, Filter, MoreVertical, Loader2 } from "lucide-react"
|
||||
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 {
|
||||
Plus,
|
||||
Edit,
|
||||
Trash2,
|
||||
Eye,
|
||||
Calendar,
|
||||
Filter,
|
||||
MoreVertical,
|
||||
Loader2,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
@ -17,36 +38,25 @@ import {
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { doctorsService } from "services/doctorsApi.mjs";
|
||||
|
||||
|
||||
interface Doctor {
|
||||
id: number;
|
||||
full_name: string;
|
||||
specialty: string;
|
||||
crm: string;
|
||||
phone_mobile: string | null;
|
||||
city: string | null;
|
||||
state: string | null;
|
||||
|
||||
id: number;
|
||||
full_name: string;
|
||||
specialty: string;
|
||||
crm: string;
|
||||
phone_mobile: string | null;
|
||||
city: string | null;
|
||||
state: string | null;
|
||||
}
|
||||
|
||||
|
||||
interface DoctorDetails {
|
||||
nome: string;
|
||||
crm: string;
|
||||
especialidade: string;
|
||||
|
||||
contato: {
|
||||
celular?: string;
|
||||
telefone1?: string;
|
||||
}
|
||||
endereco: {
|
||||
cidade?: string;
|
||||
estado?: string;
|
||||
}
|
||||
contato: { celular?: string; telefone1?: string };
|
||||
endereco: { cidade?: string; estado?: string };
|
||||
convenio?: string;
|
||||
vip?: boolean;
|
||||
status?: string;
|
||||
@ -58,80 +68,124 @@ 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 [doctorDetails, setDoctorDetails] = useState<DoctorDetails | null>(
|
||||
null
|
||||
);
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [doctorToDeleteId, setDoctorToDeleteId] = useState<number | null>(null);
|
||||
|
||||
|
||||
|
||||
// --- Lógica de Paginação ---
|
||||
const [itemsPerPage, setItemsPerPage] = useState(10);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
|
||||
// 1. Definição do total de páginas
|
||||
const totalPages = Math.ceil(doctors.length / itemsPerPage);
|
||||
|
||||
// 2. Cálculo dos itens a serem exibidos na página atual
|
||||
const indexOfLastItem = currentPage * itemsPerPage;
|
||||
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
||||
const currentItems = doctors.slice(indexOfFirstItem, indexOfLastItem);
|
||||
|
||||
// 3. Função para mudar de página
|
||||
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
|
||||
|
||||
// 4. Funções para Navegação ADICIONADAS
|
||||
const goToPrevPage = () => {
|
||||
setCurrentPage((prev) => Math.max(1, prev - 1));
|
||||
};
|
||||
|
||||
const goToNextPage = () => {
|
||||
setCurrentPage((prev) => Math.min(totalPages, prev + 1));
|
||||
};
|
||||
|
||||
// 5. Lógica para gerar os números das páginas visíveis (máximo de 5)
|
||||
const getVisiblePageNumbers = (totalPages: number, currentPage: number) => {
|
||||
const pages: number[] = [];
|
||||
const maxVisiblePages = 5;
|
||||
const halfRange = Math.floor(maxVisiblePages / 2);
|
||||
let startPage = Math.max(1, currentPage - halfRange);
|
||||
let endPage = Math.min(totalPages, currentPage + halfRange);
|
||||
|
||||
if (endPage - startPage + 1 < maxVisiblePages) {
|
||||
if (endPage === totalPages) {
|
||||
startPage = Math.max(1, totalPages - maxVisiblePages + 1);
|
||||
}
|
||||
if (startPage === 1) {
|
||||
endPage = Math.min(totalPages, maxVisiblePages);
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = startPage; i <= endPage; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
return pages;
|
||||
};
|
||||
|
||||
const visiblePageNumbers = getVisiblePageNumbers(totalPages, currentPage);
|
||||
// Fim da lógica de números de página visíveis
|
||||
|
||||
// Lógica para mudar itens por página, resetando para a página 1
|
||||
const handleItemsPerPageChange = (value: string) => {
|
||||
setItemsPerPage(Number(value));
|
||||
setCurrentPage(1); // Resetar para a primeira página
|
||||
};
|
||||
// --- Fim da Lógica de Paginação ---
|
||||
|
||||
const fetchDoctors = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
|
||||
const data: Doctor[] = await doctorsService.list();
|
||||
setDoctors(data || []);
|
||||
setDoctors(data || []);
|
||||
setCurrentPage(1); // Resetar para a primeira página ao carregar novos 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.");
|
||||
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,
|
||||
telefone1: undefined
|
||||
},
|
||||
endereco: {
|
||||
cidade: doctor.city ?? undefined,
|
||||
estado: doctor.state ?? undefined,
|
||||
},
|
||||
|
||||
convenio: "Particular",
|
||||
vip: false,
|
||||
status: "Ativo",
|
||||
ultimo_atendimento: "N/A",
|
||||
proximo_atendimento: "N/A",
|
||||
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,
|
||||
},
|
||||
convenio: "Particular",
|
||||
vip: false,
|
||||
status: "Ativo",
|
||||
ultimo_atendimento: "N/A",
|
||||
proximo_atendimento: "N/A",
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (doctorToDeleteId === null) return;
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
await doctorsService.delete(doctorToDeleteId);
|
||||
|
||||
console.log(`Médico com ID ${doctorToDeleteId} excluído com sucesso!`);
|
||||
|
||||
setDeleteDialogOpen(false);
|
||||
setDoctorToDeleteId(null);
|
||||
await fetchDoctors();
|
||||
await fetchDoctors();
|
||||
} catch (e) {
|
||||
console.error("Erro ao excluir:", e);
|
||||
|
||||
alert("Erro ao excluir médico.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
@ -142,192 +196,325 @@ export default function DoctorsPage() {
|
||||
setDoctorToDeleteId(doctorId);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
|
||||
const handleEdit = (doctorId: number) => {
|
||||
|
||||
router.push(`/manager/home/${doctorId}/editar`);
|
||||
};
|
||||
|
||||
|
||||
return (
|
||||
<ManagerLayout>
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Médicos Cadastrados</h1>
|
||||
<p className="text-sm text-gray-500">Gerencie todos os profissionais de saúde.</p>
|
||||
<div className="space-y-6 px-2 sm:px-4 md:px-6">
|
||||
{/* Cabeçalho */}
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">
|
||||
Médicos Cadastrados
|
||||
</h1>
|
||||
<p className="text-sm text-gray-500">
|
||||
Gerencie todos os profissionais de saúde.
|
||||
</p>
|
||||
</div>
|
||||
<Link href="/manager/home/novo" className="w-full sm:w-auto">
|
||||
<Button className="w-full sm:w-auto bg-green-600 hover:bg-green-700">
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Adicionar Novo
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
<Link href="/manager/home/novo">
|
||||
<Button className="bg-green-600 hover:bg-green-700">
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Adicionar Novo
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="flex items-center space-x-4 bg-white p-4 rounded-lg border border-gray-200">
|
||||
<Filter className="w-5 h-5 text-gray-400" />
|
||||
<Select>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue placeholder="Especialidade" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="cardiologia">Cardiologia</SelectItem>
|
||||
<SelectItem value="dermatologia">Dermatologia</SelectItem>
|
||||
<SelectItem value="pediatria">Pediatria</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue placeholder="Status" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="ativo">Ativo</SelectItem>
|
||||
<SelectItem value="ferias">Férias</SelectItem>
|
||||
<SelectItem value="inativo">Inativo</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</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">
|
||||
<Filter className="w-5 h-5 text-gray-400" />
|
||||
<Select>
|
||||
<SelectTrigger className="w-[160px] sm:w-[180px]">
|
||||
<SelectValue placeholder="Especialidade" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="cardiologia">Cardiologia</SelectItem>
|
||||
<SelectItem value="dermatologia">Dermatologia</SelectItem>
|
||||
<SelectItem value="pediatria">Pediatria</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select>
|
||||
<SelectTrigger className="w-[160px] sm:w-[180px]">
|
||||
<SelectValue placeholder="Status" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="ativo">Ativo</SelectItem>
|
||||
<SelectItem value="ferias">Férias</SelectItem>
|
||||
<SelectItem value="inativo">Inativo</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{/* Select de Itens por Página */}
|
||||
<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>
|
||||
|
||||
|
||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-hidden">
|
||||
{loading ? (
|
||||
{/* Tabela */}
|
||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-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...
|
||||
<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>
|
||||
) : doctors.length === 0 ? (
|
||||
) : error ? (
|
||||
<div className="p-8 text-center text-red-600">{error}</div>
|
||||
) : doctors.length === 0 ? (
|
||||
<div className="p-8 text-center text-gray-500">
|
||||
Nenhum médico cadastrado. <Link href="/manager/home/novo" className="text-green-600 hover:underline">Adicione um novo</Link>.
|
||||
Nenhum médico cadastrado.{" "}
|
||||
<Link
|
||||
href="/manager/home/novo"
|
||||
className="text-green-600 hover:underline"
|
||||
>
|
||||
Adicione um novo
|
||||
</Link>
|
||||
.
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Nome</th>
|
||||
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">CRM</th>
|
||||
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Especialidade</th>
|
||||
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Celular</th>
|
||||
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Cidade/Estado</th>
|
||||
<th scope="col" className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{doctors.map((doctor) => (
|
||||
<tr key={doctor.id} className="hover:bg-gray-50">
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{doctor.full_name}</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{doctor.crm}</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{doctor.specialty}</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{doctor.phone_mobile || "N/A"}</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
|
||||
{(doctor.city || doctor.state) ? `${doctor.city || ''}${doctor.city && doctor.state ? '/' : ''}${doctor.state || ''}` : "N/A"}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
|
||||
|
||||
<div className="flex justify-end space-x-1">
|
||||
|
||||
<Button variant="outline" size="icon" onClick={() => openDetailsDialog(doctor)} title="Visualizar Detalhes">
|
||||
<Eye className="h-4 w-4" />
|
||||
</Button>
|
||||
|
||||
<Button variant="outline" size="icon" onClick={() => handleEdit(doctor.id)} title="Editar">
|
||||
<Edit className="h-4 w-4 text-blue-600" />
|
||||
</Button>
|
||||
|
||||
<Button variant="outline" size="icon" onClick={() => openDeleteDialog(doctor.id)} title="Excluir">
|
||||
<Trash2 className="h-4 w-4 text-red-600" />
|
||||
</Button>
|
||||
|
||||
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" className="h-8 w-8 p-0" title="Mais Ações">
|
||||
<span className="sr-only">Mais Ações</span>
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem>
|
||||
<Calendar className="mr-2 h-4 w-4" />
|
||||
Agendar Consulta
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</td>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-[700px] w-full divide-y divide-gray-200 text-sm sm:text-base">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th className="px-4 py-3 text-left font-medium text-gray-500 uppercase tracking-wider">
|
||||
Nome
|
||||
</th>
|
||||
<th className="px-4 py-3 text-left font-medium text-gray-500 uppercase tracking-wider hidden sm:table-cell">
|
||||
CRM
|
||||
</th>
|
||||
<th className="px-4 py-3 text-left font-medium text-gray-500 uppercase tracking-wider hidden md:table-cell">
|
||||
Especialidade
|
||||
</th>
|
||||
<th className="px-4 py-3 text-left font-medium text-gray-500 uppercase tracking-wider hidden lg:table-cell">
|
||||
Celular
|
||||
</th>
|
||||
<th className="px-4 py-3 text-left font-medium text-gray-500 uppercase tracking-wider hidden xl:table-cell">
|
||||
Cidade/Estado
|
||||
</th>
|
||||
<th className="px-4 py-3 text-right font-medium text-gray-500 uppercase tracking-wider">
|
||||
Ações
|
||||
</th>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</thead>
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{/* Usando currentItems para a paginação */}
|
||||
{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.phone_mobile || "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">
|
||||
<div className="flex justify-end gap-2 flex-wrap sm:flex-nowrap">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => openDetailsDialog(doctor)}
|
||||
title="Visualizar Detalhes"
|
||||
>
|
||||
<Eye className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => handleEdit(doctor.id)}
|
||||
title="Editar"
|
||||
>
|
||||
<Edit className="h-4 w-4 text-blue-600" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => openDeleteDialog(doctor.id)}
|
||||
title="Excluir"
|
||||
>
|
||||
<Trash2 className="h-4 w-4 text-red-600" />
|
||||
</Button>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="h-8 w-8 p-0"
|
||||
title="Mais Ações"
|
||||
>
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem>
|
||||
<Calendar className="mr-2 h-4 w-4" />
|
||||
Agendar Consulta
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Paginação ATUALIZADA */}
|
||||
{totalPages > 1 && (
|
||||
<div className="flex flex-wrap justify-center items-center gap-2 mt-4 p-4 bg-white rounded-lg border border-gray-200 shadow-md">
|
||||
|
||||
{/* Botão Anterior */}
|
||||
<button
|
||||
onClick={goToPrevPage}
|
||||
disabled={currentPage === 1}
|
||||
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300"
|
||||
>
|
||||
{"< Anterior"}
|
||||
</button>
|
||||
|
||||
{/* Números das Páginas */}
|
||||
{visiblePageNumbers.map((number) => (
|
||||
<button
|
||||
key={number}
|
||||
onClick={() => paginate(number)}
|
||||
className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border border-gray-300 ${
|
||||
currentPage === number
|
||||
? "bg-green-600 text-white shadow-md border-green-600"
|
||||
: "bg-gray-100 text-gray-700 hover:bg-gray-200"
|
||||
}`}
|
||||
>
|
||||
{number}
|
||||
</button>
|
||||
))}
|
||||
|
||||
{/* Botão Próximo */}
|
||||
<button
|
||||
onClick={goToNextPage}
|
||||
disabled={currentPage === totalPages}
|
||||
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300"
|
||||
>
|
||||
{"Próximo >"}
|
||||
</button>
|
||||
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
|
||||
<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} onOpenChange={setDetailsDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="text-2xl">{doctorDetails?.nome}</AlertDialogTitle>
|
||||
<AlertDialogDescription className="text-left text-gray-700">
|
||||
{doctorDetails && (
|
||||
<div className="space-y-3 text-left">
|
||||
<h3 className="font-semibold mt-2">Informações Principais</h3>
|
||||
<div className="grid grid-cols-2 gap-y-1 gap-x-4 text-sm">
|
||||
<div><strong>CRM:</strong> {doctorDetails.crm}</div>
|
||||
<div><strong>Especialidade:</strong> {doctorDetails.especialidade}</div>
|
||||
<div><strong>Celular:</strong> {doctorDetails.contato.celular || 'N/A'}</div>
|
||||
<div><strong>Localização:</strong> {`${doctorDetails.endereco.cidade || 'N/A'}/${doctorDetails.endereco.estado || 'N/A'}`}</div>
|
||||
{/* Dialogs */}
|
||||
<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" />
|
||||
)}
|
||||
Excluir
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
||||
<AlertDialogContent className="max-w-[95%] sm:max-w-lg">
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="text-2xl">
|
||||
{doctorDetails?.nome}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription className="text-left text-gray-700">
|
||||
{doctorDetails && (
|
||||
<div className="space-y-3 text-left">
|
||||
<h3 className="font-semibold mt-2">
|
||||
Informações Principais
|
||||
</h3>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-y-2 gap-x-4 text-sm">
|
||||
<div>
|
||||
<strong>CRM:</strong> {doctorDetails.crm}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Especialidade:</strong>{" "}
|
||||
{doctorDetails.especialidade}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Celular:</strong>{" "}
|
||||
{doctorDetails.contato.celular || "N/A"}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Localização:</strong>{" "}
|
||||
{`${doctorDetails.endereco.cidade || "N/A"}/${
|
||||
doctorDetails.endereco.estado || "N/A"
|
||||
}`}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3 className="font-semibold mt-4">
|
||||
Atendimento e Convênio
|
||||
</h3>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-y-2 gap-x-4 text-sm">
|
||||
<div>
|
||||
<strong>Convênio:</strong>{" "}
|
||||
{doctorDetails.convenio || "N/A"}
|
||||
</div>
|
||||
<div>
|
||||
<strong>VIP:</strong>{" "}
|
||||
{doctorDetails.vip ? "Sim" : "Não"}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Status:</strong>{" "}
|
||||
{doctorDetails.status || "N/A"}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Último atendimento:</strong>{" "}
|
||||
{doctorDetails.ultimo_atendimento || "N/A"}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Próximo atendimento:</strong>{" "}
|
||||
{doctorDetails.proximo_atendimento || "N/A"}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3 className="font-semibold mt-4">Atendimento e Convênio</h3>
|
||||
<div className="grid grid-cols-2 gap-y-1 gap-x-4 text-sm">
|
||||
<div><strong>Convênio:</strong> {doctorDetails.convenio || 'N/A'}</div>
|
||||
<div><strong>VIP:</strong> {doctorDetails.vip ? "Sim" : "Não"}</div>
|
||||
<div><strong>Status:</strong> {doctorDetails.status || 'N/A'}</div>
|
||||
<div><strong>Último atendimento:</strong> {doctorDetails.ultimo_atendimento || 'N/A'}</div>
|
||||
<div><strong>Próximo atendimento:</strong> {doctorDetails.proximo_atendimento || 'N/A'}</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{doctorDetails === null && !loading && (
|
||||
<div className="text-red-600">Detalhes não disponíveis.</div>
|
||||
)}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Fechar</AlertDialogCancel>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
)}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Fechar</AlertDialogCancel>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</ManagerLayout>
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -46,20 +46,33 @@ export default function UsersPage() {
|
||||
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 [userDetails, setUserDetails] = useState<UserInfoResponse | null>(
|
||||
null
|
||||
);
|
||||
const [selectedRole, setSelectedRole] = useState<string>("");
|
||||
|
||||
// --- Lógica de Paginação INÍCIO ---
|
||||
const [itemsPerPage, setItemsPerPage] = useState(10);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
|
||||
// Lógica para mudar itens por página, resetando para a página 1
|
||||
const handleItemsPerPageChange = (value: string) => {
|
||||
setItemsPerPage(Number(value));
|
||||
setCurrentPage(1); // Resetar para a primeira página
|
||||
};
|
||||
// --- Lógica de Paginação FIM ---
|
||||
|
||||
const fetchUsers = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
// 1) pega roles
|
||||
const rolesData: any[] = await usersService.list_roles();
|
||||
// Garante que rolesData é array
|
||||
const rolesArray = Array.isArray(rolesData) ? rolesData : [];
|
||||
|
||||
// 2) pega todos os profiles de uma vez (para evitar muitos requests)
|
||||
const profilesData: any[] = await api.get(`/rest/v1/profiles?select=id,full_name,email,phone`);
|
||||
const profilesData: any[] = await api.get(
|
||||
`/rest/v1/profiles?select=id,full_name,email,phone`
|
||||
);
|
||||
|
||||
const profilesById = new Map<string, any>();
|
||||
if (Array.isArray(profilesData)) {
|
||||
for (const p of profilesData) {
|
||||
@ -67,7 +80,6 @@ export default function UsersPage() {
|
||||
}
|
||||
}
|
||||
|
||||
// 3) mapear roles -> flat users, usando ID específico de cada item
|
||||
const mapped: FlatUser[] = rolesArray.map((roleItem) => {
|
||||
const uid = roleItem.user_id;
|
||||
const profile = profilesById.get(uid);
|
||||
@ -82,6 +94,7 @@ export default function UsersPage() {
|
||||
});
|
||||
|
||||
setUsers(mapped);
|
||||
setCurrentPage(1); // Resetar a página após carregar
|
||||
console.log("[fetchUsers] mapped count:", mapped.length);
|
||||
} catch (err: any) {
|
||||
console.error("Erro ao buscar usuários:", err);
|
||||
@ -95,7 +108,7 @@ export default function UsersPage() {
|
||||
useEffect(() => {
|
||||
const init = async () => {
|
||||
try {
|
||||
await login(); // garante token
|
||||
await login();
|
||||
} catch (e) {
|
||||
console.warn("login falhou no init:", e);
|
||||
}
|
||||
@ -115,7 +128,6 @@ export default function UsersPage() {
|
||||
setUserDetails(data);
|
||||
} catch (err: any) {
|
||||
console.error("Erro ao carregar detalhes:", err);
|
||||
// fallback com dados já conhecidos
|
||||
setUserDetails({
|
||||
user: { id: flatUser.user_id, email: flatUser.email },
|
||||
profile: { full_name: flatUser.full_name, phone: flatUser.phone },
|
||||
@ -125,26 +137,79 @@ export default function UsersPage() {
|
||||
}
|
||||
};
|
||||
|
||||
// 1. Filtragem
|
||||
const filteredUsers =
|
||||
selectedRole && selectedRole !== "all" ? users.filter((u) => u.role === selectedRole) : users;
|
||||
selectedRole && selectedRole !== "all"
|
||||
? users.filter((u) => u.role === selectedRole)
|
||||
: users;
|
||||
|
||||
// 2. Paginação (aplicada sobre a lista filtrada)
|
||||
const indexOfLastItem = currentPage * itemsPerPage;
|
||||
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
||||
const currentItems = filteredUsers.slice(indexOfFirstItem, indexOfLastItem);
|
||||
|
||||
// Função para mudar de página
|
||||
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
|
||||
|
||||
const totalPages = Math.ceil(filteredUsers.length / itemsPerPage);
|
||||
|
||||
// --- Funções e Lógica de Navegação ADICIONADAS ---
|
||||
const goToPrevPage = () => {
|
||||
setCurrentPage((prev) => Math.max(1, prev - 1));
|
||||
};
|
||||
|
||||
const goToNextPage = () => {
|
||||
setCurrentPage((prev) => Math.min(totalPages, prev + 1));
|
||||
};
|
||||
|
||||
// Lógica para gerar os números das páginas visíveis
|
||||
const getVisiblePageNumbers = (totalPages: number, currentPage: number) => {
|
||||
const pages: number[] = [];
|
||||
const maxVisiblePages = 5; // Número máximo de botões de página a serem exibidos (ex: 2, 3, 4, 5, 6)
|
||||
const halfRange = Math.floor(maxVisiblePages / 2);
|
||||
let startPage = Math.max(1, currentPage - halfRange);
|
||||
let endPage = Math.min(totalPages, currentPage + halfRange);
|
||||
|
||||
// Ajusta para manter o número fixo de botões quando nos limites
|
||||
if (endPage - startPage + 1 < maxVisiblePages) {
|
||||
if (endPage === totalPages) {
|
||||
startPage = Math.max(1, totalPages - maxVisiblePages + 1);
|
||||
}
|
||||
if (startPage === 1) {
|
||||
endPage = Math.min(totalPages, maxVisiblePages);
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = startPage; i <= endPage; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
return pages;
|
||||
};
|
||||
|
||||
const visiblePageNumbers = getVisiblePageNumbers(totalPages, currentPage);
|
||||
// --- Fim das Funções e Lógica de Navegação ADICIONADAS ---
|
||||
|
||||
|
||||
return (
|
||||
<ManagerLayout>
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-6 px-2 sm:px-4 md:px-8">
|
||||
{/* Header */}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Usuários</h1>
|
||||
<p className="text-sm text-gray-500">Gerencie usuários.</p>
|
||||
</div>
|
||||
<Link href="/manager/usuario/novo">
|
||||
<Button className="bg-green-600 hover:bg-green-700">
|
||||
<Link href="/manager/usuario/novo" className="w-full sm:w-auto">
|
||||
<Button className="w-full sm:w-auto bg-green-600 hover:bg-green-700">
|
||||
<Plus className="w-4 h-4 mr-2" /> Novo Usuário
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-4 bg-white p-4 rounded-lg border border-gray-200">
|
||||
{/* 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">
|
||||
<Filter className="w-5 h-5 text-gray-400" />
|
||||
{/* Select de Filtro por Papel */}
|
||||
<Select onValueChange={setSelectedRole} value={selectedRole}>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue placeholder="Filtrar por papel" />
|
||||
@ -158,9 +223,25 @@ export default function UsersPage() {
|
||||
<SelectItem value="user">Usuário</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{/* Select de Itens por Página */}
|
||||
<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>
|
||||
{/* Fim do Filtro e Itens por Página */}
|
||||
|
||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-hidden">
|
||||
{/* Tabela */}
|
||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-x-auto">
|
||||
{loading ? (
|
||||
<div className="p-8 text-center text-gray-500">
|
||||
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
|
||||
@ -170,31 +251,62 @@ export default function UsersPage() {
|
||||
<div className="p-8 text-center text-red-600">{error}</div>
|
||||
) : filteredUsers.length === 0 ? (
|
||||
<div className="p-8 text-center text-gray-500">
|
||||
Nenhum usuário encontrado.
|
||||
Nenhum usuário encontrado com os filtros aplicados.
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<>
|
||||
<table className="min-w-full divide-y divide-gray-200">
|
||||
<thead className="bg-gray-50">
|
||||
<thead className="bg-gray-50 hidden md:table-header-group">
|
||||
<tr>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">ID</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Nome</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">E-mail</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Telefone</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Cargo</th>
|
||||
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">Ações</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
|
||||
ID
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
|
||||
Nome
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
|
||||
E-mail
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
|
||||
Telefone
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
|
||||
Cargo
|
||||
</th>
|
||||
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">
|
||||
Ações
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{filteredUsers.map((u) => (
|
||||
<tr key={u.id} className="hover:bg-gray-50">
|
||||
<td className="px-6 py-4 text-sm text-gray-500">{u.id}</td>
|
||||
<td className="px-6 py-4 text-sm text-gray-900">{u.full_name}</td>
|
||||
<td className="px-6 py-4 text-sm text-gray-500">{u.email}</td>
|
||||
<td className="px-6 py-4 text-sm text-gray-500">{u.phone}</td>
|
||||
<td className="px-6 py-4 text-sm text-gray-500 capitalize">{u.role}</td>
|
||||
{/* Usando currentItems para a paginação */}
|
||||
{currentItems.map((u) => (
|
||||
<tr
|
||||
key={u.id}
|
||||
className="flex flex-col md:table-row md:flex-row border-b md:border-0 hover:bg-gray-50"
|
||||
>
|
||||
<td className="px-6 py-4 text-sm text-gray-500 break-all md:whitespace-nowrap">
|
||||
{u.id}
|
||||
</td>
|
||||
<td className="px-6 py-4 text-sm text-gray-900">
|
||||
{u.full_name}
|
||||
</td>
|
||||
<td className="px-6 py-4 text-sm text-gray-500 break-all">
|
||||
{u.email}
|
||||
</td>
|
||||
<td className="px-6 py-4 text-sm text-gray-500">
|
||||
{u.phone}
|
||||
</td>
|
||||
<td className="px-6 py-4 text-sm text-gray-500 capitalize">
|
||||
{u.role}
|
||||
</td>
|
||||
<td className="px-6 py-4 text-right">
|
||||
<Button variant="outline" size="icon" onClick={() => openDetailsDialog(u)} title="Visualizar">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => openDetailsDialog(u)}
|
||||
title="Visualizar"
|
||||
>
|
||||
<Eye className="h-4 w-4" />
|
||||
</Button>
|
||||
</td>
|
||||
@ -202,14 +314,58 @@ export default function UsersPage() {
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Paginação ATUALIZADA */}
|
||||
{totalPages > 1 && (
|
||||
<div className="flex flex-wrap justify-center items-center gap-2 mt-4 p-4 border-t border-gray-200">
|
||||
|
||||
{/* Botão Anterior */}
|
||||
<button
|
||||
onClick={goToPrevPage}
|
||||
disabled={currentPage === 1}
|
||||
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300"
|
||||
>
|
||||
{"< Anterior"}
|
||||
</button>
|
||||
|
||||
{/* Números das Páginas */}
|
||||
{visiblePageNumbers.map((number) => (
|
||||
<button
|
||||
key={number}
|
||||
onClick={() => paginate(number)}
|
||||
className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border border-gray-300 ${
|
||||
currentPage === number
|
||||
? "bg-green-600 text-white shadow-md border-green-600"
|
||||
: "bg-gray-100 text-gray-700 hover:bg-gray-200"
|
||||
}`}
|
||||
>
|
||||
{number}
|
||||
</button>
|
||||
))}
|
||||
|
||||
{/* Botão Próximo */}
|
||||
<button
|
||||
onClick={goToNextPage}
|
||||
disabled={currentPage === totalPages}
|
||||
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300"
|
||||
>
|
||||
{"Próximo >"}
|
||||
</button>
|
||||
|
||||
</div>
|
||||
)}
|
||||
{/* Fim da Paginação ATUALIZADA */}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Modal de Detalhes */}
|
||||
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="text-2xl">{userDetails?.profile?.full_name || "Detalhes do Usuário"}</AlertDialogTitle>
|
||||
<AlertDialogTitle className="text-2xl">
|
||||
{userDetails?.profile?.full_name || "Detalhes do Usuário"}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{!userDetails ? (
|
||||
<div className="p-4 text-center text-gray-500">
|
||||
@ -218,15 +374,33 @@ export default function UsersPage() {
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3 pt-2 text-left text-gray-700">
|
||||
<div><strong>ID:</strong> {userDetails.user.id}</div>
|
||||
<div><strong>E-mail:</strong> {userDetails.user.email}</div>
|
||||
<div><strong>Nome completo:</strong> {userDetails.profile.full_name}</div>
|
||||
<div><strong>Telefone:</strong> {userDetails.profile.phone}</div>
|
||||
<div><strong>Roles:</strong> {userDetails.roles?.join(", ")}</div>
|
||||
<div>
|
||||
<strong>ID:</strong> {userDetails.user.id}
|
||||
</div>
|
||||
<div>
|
||||
<strong>E-mail:</strong> {userDetails.user.email}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Nome completo:</strong>{" "}
|
||||
{userDetails.profile.full_name}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Telefone:</strong> {userDetails.profile.phone}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Roles:</strong>{" "}
|
||||
{userDetails.roles?.join(", ")}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Permissões:</strong>
|
||||
<ul className="list-disc list-inside">
|
||||
{Object.entries(userDetails.permissions || {}).map(([k,v]) => <li key={k}>{k}: {v ? "Sim" : "Não"}</li>)}
|
||||
{Object.entries(
|
||||
userDetails.permissions || {}
|
||||
).map(([k, v]) => (
|
||||
<li key={k}>
|
||||
{k}: {v ? "Sim" : "Não"}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
@ -241,4 +415,4 @@ export default function UsersPage() {
|
||||
</div>
|
||||
</ManagerLayout>
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -1,108 +1,139 @@
|
||||
// app/secretary/pacientes/page.tsx
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useRef, useCallback } from "react";
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import Link from "next/link";
|
||||
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 { Plus, Edit, Trash2, Eye, Calendar, Filter } from "lucide-react";
|
||||
import { Plus, Edit, Trash2, Eye, Calendar, Filter, Loader2 } from "lucide-react";
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||
import SecretaryLayout from "@/components/secretary-layout";
|
||||
import { patientsService } from "@/services/patientsApi.mjs";
|
||||
|
||||
// Defina o tamanho da página.
|
||||
const PAGE_SIZE = 5;
|
||||
|
||||
export default function PacientesPage() {
|
||||
// --- ESTADOS DE DADOS E GERAL ---
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
const [convenioFilter, setConvenioFilter] = useState("all");
|
||||
const [vipFilter, setVipFilter] = useState("all");
|
||||
const [patients, setPatients] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
// Lista completa, carregada da API uma única vez
|
||||
const [allPatients, setAllPatients] = useState<any[]>([]);
|
||||
// Lista após a aplicação dos filtros (base para a paginação)
|
||||
const [filteredPatients, setFilteredPatients] = useState<any[]>([]);
|
||||
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// --- ESTADOS DE PAGINAÇÃO ---
|
||||
const [page, setPage] = useState(1);
|
||||
const [hasNext, setHasNext] = useState(true);
|
||||
const [isFetching, setIsFetching] = useState(false);
|
||||
const observerRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
// CÁLCULO DA PAGINAÇÃO
|
||||
const totalPages = Math.ceil(filteredPatients.length / PAGE_SIZE);
|
||||
const startIndex = (page - 1) * PAGE_SIZE;
|
||||
const endIndex = startIndex + PAGE_SIZE;
|
||||
// Pacientes a serem exibidos na tabela (aplicando a paginação)
|
||||
const currentPatients = filteredPatients.slice(startIndex, endIndex);
|
||||
|
||||
// --- ESTADOS DE DIALOGS ---
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [patientToDelete, setPatientToDelete] = useState<string | null>(null);
|
||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
||||
const [patientDetails, setPatientDetails] = useState<any | null>(null);
|
||||
|
||||
// --- FUNÇÕES DE LÓGICA ---
|
||||
|
||||
// 1. Função para carregar TODOS os pacientes da API
|
||||
const fetchAllPacientes = useCallback(
|
||||
async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
// Como o backend retorna um array, chamamos sem paginação
|
||||
const res = await patientsService.list();
|
||||
|
||||
const mapped = res.map((p: any) => ({
|
||||
id: String(p.id ?? ""),
|
||||
nome: p.full_name ?? "—",
|
||||
telefone: p.phone_mobile ?? p.phone1 ?? "—",
|
||||
cidade: p.city ?? "—",
|
||||
estado: p.state ?? "—",
|
||||
// Formate as datas se necessário, aqui usamos como string
|
||||
ultimoAtendimento: p.last_visit_at?.split('T')[0] ?? "—",
|
||||
proximoAtendimento: p.next_appointment_at?.split('T')[0] ?? "—",
|
||||
vip: Boolean(p.vip ?? false),
|
||||
convenio: p.convenio ?? "Particular", // Define um valor padrão
|
||||
status: p.status ?? undefined,
|
||||
}));
|
||||
|
||||
setAllPatients(mapped);
|
||||
} catch (e: any) {
|
||||
console.error(e);
|
||||
setError(e?.message || "Erro ao buscar pacientes");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
// 2. Efeito para aplicar filtros e calcular a lista filtrada (chama-se quando allPatients ou filtros mudam)
|
||||
useEffect(() => {
|
||||
const filtered = allPatients.filter((patient) => {
|
||||
// Filtro por termo de busca (Nome ou Telefone)
|
||||
const matchesSearch =
|
||||
patient.nome?.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
patient.telefone?.includes(searchTerm);
|
||||
|
||||
// Filtro por Convênio
|
||||
const matchesConvenio =
|
||||
convenioFilter === "all" ||
|
||||
patient.convenio === convenioFilter;
|
||||
|
||||
// Filtro por VIP
|
||||
const matchesVip =
|
||||
vipFilter === "all" ||
|
||||
(vipFilter === "vip" && patient.vip) ||
|
||||
(vipFilter === "regular" && !patient.vip);
|
||||
|
||||
return matchesSearch && matchesConvenio && matchesVip;
|
||||
});
|
||||
|
||||
setFilteredPatients(filtered);
|
||||
// Garante que a página atual seja válida após a filtragem
|
||||
setPage(1);
|
||||
}, [allPatients, searchTerm, convenioFilter, vipFilter]);
|
||||
|
||||
// 3. Efeito inicial para buscar os pacientes
|
||||
useEffect(() => {
|
||||
fetchAllPacientes();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
|
||||
// --- LÓGICA DE AÇÕES (DELETAR / VER DETALHES) ---
|
||||
|
||||
const openDetailsDialog = async (patientId: string) => {
|
||||
setDetailsDialogOpen(true);
|
||||
setPatientDetails(null);
|
||||
try {
|
||||
const res = await patientsService.getById(patientId);
|
||||
setPatientDetails(res[0]);
|
||||
setPatientDetails(Array.isArray(res) ? res[0] : res); // Supondo que retorne um array com um item
|
||||
} catch (e: any) {
|
||||
setPatientDetails({ error: e?.message || "Erro ao buscar detalhes" });
|
||||
}
|
||||
};
|
||||
|
||||
const fetchPacientes = useCallback(
|
||||
async (pageToFetch: number) => {
|
||||
if (isFetching || !hasNext) return;
|
||||
setIsFetching(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await patientsService.list();
|
||||
const mapped = res.map((p: any) => ({
|
||||
id: String(p.id ?? ""),
|
||||
nome: p.full_name ?? "",
|
||||
telefone: p.phone_mobile ?? p.phone1 ?? "",
|
||||
cidade: p.city ?? "",
|
||||
estado: p.state ?? "",
|
||||
ultimoAtendimento: p.last_visit_at ?? "",
|
||||
proximoAtendimento: p.next_appointment_at ?? "",
|
||||
vip: Boolean(p.vip ?? false),
|
||||
convenio: p.convenio ?? "", // se não existir, fica vazio
|
||||
status: p.status ?? undefined,
|
||||
}));
|
||||
|
||||
setPatients((prev) => {
|
||||
const all = [...prev, ...mapped];
|
||||
const unique = Array.from(new Map(all.map((p) => [p.id, p])).values());
|
||||
return unique;
|
||||
});
|
||||
|
||||
if (!mapped.id) setHasNext(false); // parar carregamento
|
||||
else setPage((prev) => prev + 1);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Erro ao buscar pacientes");
|
||||
} finally {
|
||||
setIsFetching(false);
|
||||
}
|
||||
},
|
||||
[isFetching, hasNext]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
fetchPacientes(page);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!observerRef.current || !hasNext) return;
|
||||
const observer = new window.IntersectionObserver((entries) => {
|
||||
if (entries[0].isIntersecting && !isFetching && hasNext) {
|
||||
fetchPacientes(page);
|
||||
}
|
||||
});
|
||||
observer.observe(observerRef.current);
|
||||
return () => {
|
||||
if (observerRef.current) observer.unobserve(observerRef.current);
|
||||
};
|
||||
}, [fetchPacientes, page, hasNext, isFetching]);
|
||||
|
||||
const handleDeletePatient = async (patientId: string) => {
|
||||
// Remove from current list (client-side deletion)
|
||||
try {
|
||||
const res = await patientsService.delete(patientId);
|
||||
|
||||
if (res) {
|
||||
alert(`${res.error} ${res.message}`);
|
||||
}
|
||||
|
||||
setPatients((prev) => prev.filter((p) => String(p.id) !== String(patientId)));
|
||||
await patientsService.delete(patientId);
|
||||
// Atualiza a lista completa para refletir a exclusão
|
||||
setAllPatients((prev) => prev.filter((p) => String(p.id) !== String(patientId)));
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Erro ao deletar paciente");
|
||||
alert(`Erro ao deletar paciente: ${e?.message || 'Erro desconhecido'}`);
|
||||
}
|
||||
setDeleteDialogOpen(false);
|
||||
setPatientToDelete(null);
|
||||
@ -113,25 +144,18 @@ export default function PacientesPage() {
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
const filteredPatients = patients.filter((patient) => {
|
||||
const matchesSearch = patient.nome?.toLowerCase().includes(searchTerm.toLowerCase()) || patient.telefone?.includes(searchTerm);
|
||||
const matchesConvenio = convenioFilter === "all" || (patient.convenio ?? "") === convenioFilter;
|
||||
const matchesVip = vipFilter === "all" || (vipFilter === "vip" && patient.vip) || (vipFilter === "regular" && !patient.vip);
|
||||
|
||||
return matchesSearch && matchesConvenio && matchesVip;
|
||||
});
|
||||
|
||||
return (
|
||||
<SecretaryLayout>
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-6 px-2 sm:px-4 md:px-8">
|
||||
{/* Header */}
|
||||
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-xl md:text-2xl font-bold text-foreground">Pacientes</h1>
|
||||
<p className="text-muted-foreground text-sm md:text-base">Gerencie as informações de seus pacientes</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Link href="/secretary/pacientes/novo">
|
||||
<Button className="w-full md:w-auto">
|
||||
<Link href="/secretary/pacientes/novo" className="w-full md:w-auto">
|
||||
<Button className="w-full bg-green-600 hover:bg-green-700">
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Adicionar
|
||||
</Button>
|
||||
@ -139,28 +163,41 @@ export default function PacientesPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col md:flex-row flex-wrap gap-4 bg-card p-4 rounded-lg border border-border">
|
||||
{/* Bloco de Filtros */}
|
||||
<div className="flex flex-wrap items-center gap-4 bg-card p-4 rounded-lg border border-border">
|
||||
<Filter className="w-5 h-5 text-gray-400" />
|
||||
{/* Busca */}
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Buscar por nome ou telefone..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="flex-grow min-w-[150px] p-2 border rounded-md text-sm"
|
||||
/>
|
||||
|
||||
{/* Convênio */}
|
||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
||||
<span className="text-sm font-medium text-foreground">Convênio</span>
|
||||
<div className="flex items-center gap-2 w-full sm:w-auto flex-grow max-w-[200px]">
|
||||
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden sm:block">Convênio</span>
|
||||
<Select value={convenioFilter} onValueChange={setConvenioFilter}>
|
||||
<SelectTrigger className="w-full md:w-40">
|
||||
<SelectValue placeholder="Selecione o Convênio" />
|
||||
<SelectTrigger className="w-full sm:w-40">
|
||||
<SelectValue placeholder="Convênio" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todos</SelectItem>
|
||||
<SelectItem value="Particular">Particular</SelectItem>
|
||||
<SelectItem value="SUS">SUS</SelectItem>
|
||||
<SelectItem value="Unimed">Unimed</SelectItem>
|
||||
{/* Adicione outros convênios conforme necessário */}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
||||
<span className="text-sm font-medium text-foreground">VIP</span>
|
||||
{/* VIP */}
|
||||
<div className="flex items-center gap-2 w-full sm:w-auto flex-grow max-w-[150px]">
|
||||
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden sm:block">VIP</span>
|
||||
<Select value={vipFilter} onValueChange={setVipFilter}>
|
||||
<SelectTrigger className="w-full md:w-32">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
<SelectTrigger className="w-full sm:w-32">
|
||||
<SelectValue placeholder="VIP" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todos</SelectItem>
|
||||
@ -169,132 +206,155 @@ export default function PacientesPage() {
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
||||
<span className="text-sm font-medium text-foreground">Aniversariantes</span>
|
||||
<Select>
|
||||
<SelectTrigger className="w-full md:w-32">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="today">Hoje</SelectItem>
|
||||
<SelectItem value="week">Esta semana</SelectItem>
|
||||
<SelectItem value="month">Este mês</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium text-foreground">VIP</span>
|
||||
<Select value={vipFilter} onValueChange={setVipFilter}>
|
||||
<SelectTrigger className="w-32">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todos</SelectItem>
|
||||
<SelectItem value="vip">VIP</SelectItem>
|
||||
<SelectItem value="regular">Regular</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium text-foreground">Aniversariantes</span>
|
||||
<Select>
|
||||
<SelectTrigger className="w-32">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="today">Hoje</SelectItem>
|
||||
<SelectItem value="week">Esta semana</SelectItem>
|
||||
<SelectItem value="month">Este mês</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
|
||||
{/* Aniversariantes (mantido como placeholder) */}
|
||||
<Button variant="outline" className="ml-auto w-full md:w-auto">
|
||||
<Filter className="w-4 h-4 mr-2" />
|
||||
Filtro avançado
|
||||
<Calendar className="w-4 h-4 mr-2" />
|
||||
Aniversariantes
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-lg border border-gray-200">
|
||||
{/* Tabela */}
|
||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md">
|
||||
<div className="overflow-x-auto">
|
||||
{error ? (
|
||||
<div className="p-6 text-red-600">{`Erro ao carregar pacientes: ${error}`}</div>
|
||||
) : loading ? (
|
||||
<div className="p-6 text-center text-gray-500 flex items-center justify-center">
|
||||
<Loader2 className="w-6 h-6 mr-2 animate-spin text-green-600" /> Carregando pacientes...
|
||||
</div>
|
||||
) : (
|
||||
<table className="w-full min-w-[600px]">
|
||||
<table className="w-full min-w-[900px]">
|
||||
<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">Telefone</th>
|
||||
<th className="text-left p-2 md:p-4 font-medium text-gray-700">Cidade</th>
|
||||
<th className="text-left p-2 md:p-4 font-medium text-gray-700">Estado</th>
|
||||
<th className="text-left p-2 md:p-4 font-medium text-gray-700">Último atendimento</th>
|
||||
<th className="text-left p-2 md:p-4 font-medium text-gray-700">Próximo atendimento</th>
|
||||
<th className="text-left p-2 md:p-4 font-medium text-gray-700">Ações</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[20%]">Nome</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%]">Telefone</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%]">Cidade / Estado</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%]">Convênio</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%]">Último atendimento</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[15%]">Próximo atendimento</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700 w-[5%]">Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filteredPatients.length === 0 ? (
|
||||
{currentPatients.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={7} className="p-8 text-center text-gray-500">
|
||||
{patients.length === 0 ? "Nenhum paciente cadastrado" : "Nenhum paciente encontrado com os filtros aplicados"}
|
||||
{allPatients.length === 0 ? "Nenhum paciente cadastrado" : "Nenhum paciente encontrado com os filtros aplicados"}
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
filteredPatients.map((patient) => (
|
||||
currentPatients.map((patient) => (
|
||||
<tr key={patient.id} className="border-b border-gray-100 hover:bg-gray-50">
|
||||
<td className="p-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center">
|
||||
<span className="text-gray-600 font-medium text-sm">{patient.nome?.charAt(0) || "?"}</span>
|
||||
<div className="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
|
||||
<span className="text-green-600 font-medium text-sm">{patient.nome?.charAt(0) || "?"}</span>
|
||||
</div>
|
||||
<span className="font-medium text-gray-900">{patient.nome}</span>
|
||||
<span className="font-medium text-gray-900">
|
||||
{patient.nome}
|
||||
{patient.vip && (
|
||||
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-600 bg-purple-100 rounded-full">VIP</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="p-4 text-gray-600">{patient.telefone}</td>
|
||||
<td className="p-4 text-gray-600">{patient.cidade}</td>
|
||||
<td className="p-4 text-gray-600">{patient.estado}</td>
|
||||
<td className="p-4 text-gray-600">{`${patient.cidade} / ${patient.estado}`}</td>
|
||||
<td className="p-4 text-gray-600">{patient.convenio}</td>
|
||||
<td className="p-4 text-gray-600">{patient.ultimoAtendimento}</td>
|
||||
<td className="p-4 text-gray-600">{patient.proximoAtendimento}</td>
|
||||
|
||||
{/* --- COLUNA AÇÕES CORRIGIDA --- */}
|
||||
<td className="p-4">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<div className="text-blue-600">Ações</div>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => openDetailsDialog(String(patient.id))}>
|
||||
<Eye className="w-4 h-4 mr-2" />
|
||||
Ver detalhes
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/secretary/pacientes/${patient.id}/editar`}>
|
||||
<Edit className="w-4 h-4 mr-2" />
|
||||
Editar
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem>
|
||||
<Calendar className="w-4 h-4 mr-2" />
|
||||
Marcar consulta
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(String(patient.id))}>
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
Excluir
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<div className="text-blue-600 cursor-pointer">Ações</div>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => openDetailsDialog(String(patient.id))}>
|
||||
<Eye className="w-4 h-4 mr-2" />
|
||||
Ver detalhes
|
||||
</DropdownMenuItem>
|
||||
|
||||
{/* O Trecho CORRIGIDO ABAIXO */}
|
||||
<DropdownMenuItem asChild>
|
||||
{/* O Link deve ter o estilo de um DropdownMenuItem, e englobar todo o conteúdo (ícone + texto) */}
|
||||
<Link href={`/secretary/pacientes/${patient.id}/editar`} className="flex items-center w-full">
|
||||
<Edit className="w-4 h-4 mr-2" />
|
||||
Editar
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem>
|
||||
<Calendar className="w-4 h-4 mr-2" />
|
||||
Marcar consulta
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(String(patient.id))}>
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
Excluir
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</td>
|
||||
{/* --- FIM DA COLUNA AÇÕES CORRIGIDA --- */}
|
||||
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
<div ref={observerRef} style={{ height: 1 }} />
|
||||
{isFetching && <div className="p-4 text-center text-gray-500">Carregando mais pacientes...</div>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* --- PAGINAÇÃO --- */}
|
||||
{totalPages > 1 && !loading && (
|
||||
<div className="flex flex-wrap items-center justify-between p-4 border-t border-gray-200">
|
||||
|
||||
{/* Botões de Navegação */}
|
||||
<div className="flex space-x-1">
|
||||
{/* Botão Anterior */}
|
||||
<Button
|
||||
onClick={() => setPage((prev) => Math.max(1, prev - 1))}
|
||||
disabled={page === 1}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
>
|
||||
< Anterior
|
||||
</Button>
|
||||
|
||||
{/* Renderização dos botões de número de página (Limitando a 5) */}
|
||||
{Array.from({ length: totalPages }, (_, index) => index + 1)
|
||||
// Limita a exibição dos botões para 5 (janela de visualização)
|
||||
.slice(Math.max(0, page - 3), Math.min(totalPages, page + 2))
|
||||
.map((pageNumber) => (
|
||||
<Button
|
||||
key={pageNumber}
|
||||
onClick={() => setPage(pageNumber)}
|
||||
variant={pageNumber === page ? "default" : "outline"}
|
||||
size="sm"
|
||||
className={pageNumber === page ? "bg-green-600 hover:bg-green-700 text-white" : "text-gray-700"}
|
||||
>
|
||||
{pageNumber}
|
||||
</Button>
|
||||
))}
|
||||
|
||||
{/* Botão Próximo */}
|
||||
<Button
|
||||
onClick={() => setPage((prev) => Math.min(totalPages, prev + 1))}
|
||||
disabled={page === totalPages}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
>
|
||||
Próximo >
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{/* --- FIM DA PAGINAÇÃO --- */}
|
||||
</div>
|
||||
|
||||
{/* AlertDialogs (Mantidos) */}
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
@ -310,75 +370,84 @@ export default function PacientesPage() {
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{/* Modal de detalhes do paciente */}
|
||||
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Detalhes do Paciente</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{patientDetails === null ? (
|
||||
<div className="text-gray-500">Carregando...</div>
|
||||
) : patientDetails?.error ? (
|
||||
<div className="text-red-600">{patientDetails.error}</div>
|
||||
) : (
|
||||
<div className="space-y-2 text-left">
|
||||
<p>
|
||||
<strong>Nome:</strong> {patientDetails.full_name}
|
||||
</p>
|
||||
<p>
|
||||
<strong>CPF:</strong> {patientDetails.cpf}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Email:</strong> {patientDetails.email}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Telefone:</strong> {patientDetails.phone_mobile ?? patientDetails.phone1 ?? patientDetails.phone2 ?? "-"}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Nome social:</strong> {patientDetails.social_name ?? "-"}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Sexo:</strong> {patientDetails.sex ?? "-"}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Tipo sanguíneo:</strong> {patientDetails.blood_type ?? "-"}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Peso:</strong> {patientDetails.weight_kg ?? "-"}
|
||||
{patientDetails.weight_kg ? "kg" : ""}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Altura:</strong> {patientDetails.height_m ?? "-"}
|
||||
{patientDetails.height_m ? "m" : ""}
|
||||
</p>
|
||||
<p>
|
||||
<strong>IMC:</strong> {patientDetails.bmi ?? "-"}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Endereço:</strong> {patientDetails.street ?? "-"}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Bairro:</strong> {patientDetails.neighborhood ?? "-"}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Cidade:</strong> {patientDetails.city ?? "-"}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Estado:</strong> {patientDetails.state ?? "-"}
|
||||
</p>
|
||||
<p>
|
||||
<strong>CEP:</strong> {patientDetails.cep ?? "-"}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Criado em:</strong> {patientDetails.created_at ?? "-"}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Atualizado em:</strong> {patientDetails.updated_at ?? "-"}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Id:</strong> {patientDetails.id ?? "-"}
|
||||
</p>
|
||||
<div className="text-gray-500">
|
||||
<Loader2 className="w-6 h-6 animate-spin mx-auto text-green-600 my-4" />
|
||||
Carregando...
|
||||
</div>
|
||||
) : patientDetails?.error ? (
|
||||
<div className="text-red-600 p-4">{patientDetails.error}</div>
|
||||
) : (
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<p className="font-semibold">Nome Completo</p>
|
||||
<p>{patientDetails.full_name}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Email</p>
|
||||
<p>{patientDetails.email}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Telefone</p>
|
||||
<p>{patientDetails.phone_mobile}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Data de Nascimento</p>
|
||||
<p>{patientDetails.birth_date}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">CPF</p>
|
||||
<p>{patientDetails.cpf}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Tipo Sanguíneo</p>
|
||||
<p>{patientDetails.blood_type}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Peso (kg)</p>
|
||||
<p>{patientDetails.weight_kg}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Altura (m)</p>
|
||||
<p>{patientDetails.height_m}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-t pt-4 mt-4">
|
||||
<h3 className="font-semibold mb-2">Endereço</h3>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<p className="font-semibold">Rua</p>
|
||||
<p>{`${patientDetails.street}, ${patientDetails.number}`}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Complemento</p>
|
||||
<p>{patientDetails.complement}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Bairro</p>
|
||||
<p>{patientDetails.neighborhood}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Cidade</p>
|
||||
<p>{patientDetails.cidade}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">Estado</p>
|
||||
<p>{patientDetails.estado}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold">CEP</p>
|
||||
<p>{patientDetails.cep}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
@ -390,4 +459,4 @@ export default function PacientesPage() {
|
||||
</div>
|
||||
</SecretaryLayout>
|
||||
);
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user