Merge branch 'Stage' of https://github.com/m1guelmcf/MedConnect into Disponibilidade
This commit is contained in:
commit
063bdf4ef7
@ -21,6 +21,8 @@ import { Eye, Edit, Calendar, Trash2 } from "lucide-react";
|
|||||||
import { AvailabilityEditModal } from "@/components/ui/availability-edit-modal";
|
import { AvailabilityEditModal } from "@/components/ui/availability-edit-modal";
|
||||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||||
|
|
||||||
|
// ... (Interfaces de tipo omitidas para brevidade, pois não foram alteradas)
|
||||||
|
|
||||||
interface UserPermissions {
|
interface UserPermissions {
|
||||||
isAdmin: boolean;
|
isAdmin: boolean;
|
||||||
isManager: boolean;
|
isManager: boolean;
|
||||||
@ -335,43 +337,45 @@ export default function AvailabilityPage() {
|
|||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Dados </h2>
|
<h2 className="text-lg font-semibold text-gray-900 mb-6">Dados </h2>
|
||||||
|
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="grid md:grid-cols-3 gap-4">
|
{/* **AJUSTE DE RESPONSIVIDADE: DIAS DA SEMANA** */}
|
||||||
<div>
|
<div>
|
||||||
<Label className="text-sm font-medium text-gray-700">Dia Da Semana</Label>
|
<Label className="text-sm font-medium text-gray-700">Dia Da Semana</Label>
|
||||||
<div className="flex gap-4 mt-2 flex-nowrap">
|
{/* O antigo 'flex gap-4 mt-2 flex-nowrap' foi substituído por um grid responsivo: */}
|
||||||
<label className="flex items-center gap-2">
|
<div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-7 gap-x-4 gap-y-2 mt-2">
|
||||||
|
<label className="flex items-center gap-1">
|
||||||
<input type="radio" name="weekday" value="monday" className="text-blue-600" />
|
<input type="radio" name="weekday" value="monday" className="text-blue-600" />
|
||||||
<span className="whitespace-nowrap text-sm">Segunda-Feira</span>
|
<span className="whitespace-nowrap text-sm">Segunda</span>
|
||||||
</label>
|
</label>
|
||||||
<label className="flex items-center gap-2">
|
<label className="flex items-center gap-1">
|
||||||
<input type="radio" name="weekday" value="tuesday" className="text-blue-600" />
|
<input type="radio" name="weekday" value="tuesday" className="text-blue-600" />
|
||||||
<span className="whitespace-nowrap text-sm">Terça-Feira</span>
|
<span className="whitespace-nowrap text-sm">Terça</span>
|
||||||
</label>
|
</label>
|
||||||
<label className="flex items-center gap-2">
|
<label className="flex items-center gap-1">
|
||||||
<input type="radio" name="weekday" value="wednesday" className="text-blue-600" />
|
<input type="radio" name="weekday" value="wednesday" className="text-blue-600" />
|
||||||
<span className="whitespace-nowrap text-sm">Quarta-Feira</span>
|
<span className="whitespace-nowrap text-sm">Quarta</span>
|
||||||
</label>
|
</label>
|
||||||
<label className="flex items-center gap-2">
|
<label className="flex items-center gap-1">
|
||||||
<input type="radio" name="weekday" value="thursday" className="text-blue-600" />
|
<input type="radio" name="weekday" value="thursday" className="text-blue-600" />
|
||||||
<span className="whitespace-nowrap text-sm">Quinta-Feira</span>
|
<span className="whitespace-nowrap text-sm">Quinta</span>
|
||||||
</label>
|
</label>
|
||||||
<label className="flex items-center gap-2">
|
<label className="flex items-center gap-1">
|
||||||
<input type="radio" name="weekday" value="friday" className="text-blue-600" />
|
<input type="radio" name="weekday" value="friday" className="text-blue-600" />
|
||||||
<span className="whitespace-nowrap text-sm">Sexta-Feira</span>
|
<span className="whitespace-nowrap text-sm">Sexta</span>
|
||||||
</label>
|
</label>
|
||||||
<label className="flex items-center gap-2">
|
<label className="flex items-center gap-1">
|
||||||
<input type="radio" name="weekday" value="saturday" className="text-blue-600" />
|
<input type="radio" name="weekday" value="saturday" className="text-blue-600" />
|
||||||
<span className="whitespace-nowrap text-sm">Sábado</span>
|
<span className="whitespace-nowrap text-sm">Sábado</span>
|
||||||
</label>
|
</label>
|
||||||
<label className="flex items-center gap-2">
|
<label className="flex items-center gap-1">
|
||||||
<input type="radio" name="weekday" value="sunday" className="text-blue-600" />
|
<input type="radio" name="weekday" value="sunday" className="text-blue-600" />
|
||||||
<span className="whitespace-nowrap text-sm">Domingo</span>
|
<span className="whitespace-nowrap text-sm">Domingo</span>
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-5 gap-6">
|
{/* **AJUSTE DE RESPONSIVIDADE: HORÁRIO E DURAÇÃO** */}
|
||||||
|
{/* Ajustado para 1 coluna em móvel, 2 em tablet e 5 em desktop (mantendo o que já existia com ajustes) */}
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-6">
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="horarioEntrada" className="text-sm font-medium text-gray-700">
|
<Label htmlFor="horarioEntrada" className="text-sm font-medium text-gray-700">
|
||||||
Horario De Entrada
|
Horario De Entrada
|
||||||
@ -390,6 +394,7 @@ export default function AvailabilityPage() {
|
|||||||
</Label>
|
</Label>
|
||||||
<Input type="number" id="duracaoConsulta" name="duracaoConsulta" required className="mt-1" />
|
<Input type="number" id="duracaoConsulta" name="duracaoConsulta" required className="mt-1" />
|
||||||
</div>
|
</div>
|
||||||
|
{/* O Select de modalidade fica fora deste grid para ocupar uma linha inteira em telas menores, como no original, garantindo clareza */}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
@ -409,53 +414,56 @@ export default function AvailabilityPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex justify-between gap-4">
|
{/* **AJUSTE DE RESPONSIVIDADE: BOTÕES DE AÇÃO** */}
|
||||||
<Link href="/doctor/disponibilidade/excecoes">
|
{/* Alinha à direita em telas maiores e empilha (com o botão primário no final) em telas menores */}
|
||||||
<Button variant="default">Adicionar Exceção</Button>
|
<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>
|
</Link>
|
||||||
<div>
|
<div className="flex gap-4 w-full sm:w-auto">
|
||||||
<Link href="/doctor/dashboard">
|
<Link href="/doctor/dashboard" className="w-full sm:w-auto">
|
||||||
<Button variant="outline">Cancelar</Button>
|
<Button variant="outline" className="w-full sm:w-auto">Cancelar</Button>
|
||||||
</Link>
|
</Link>
|
||||||
<Button type="submit" className="bg-green-600 hover:bg-green-700">
|
<Button type="submit" className="bg-green-600 hover:bg-green-700 w-full sm:w-auto">
|
||||||
Salvar Disponibilidade
|
Salvar Disponibilidade
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
|
{/* **AJUSTE DE RESPONSIVIDADE: CARD DE HORÁRIO SEMANAL** */}
|
||||||
<div>
|
<div>
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Horário Semanal</CardTitle>
|
<CardTitle>Horário Semanal</CardTitle>
|
||||||
<CardDescription>Confira ou altere a sua disponibilidade da semana</CardDescription>
|
<CardDescription>Confira ou altere a sua disponibilidade da semana</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-4 grid md:grid-cols-7 gap-2">
|
{/* 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) => {
|
{["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"].map((day) => {
|
||||||
const times = schedule[day] || [];
|
const times = schedule[day] || [];
|
||||||
return (
|
return (
|
||||||
<div key={day} className="space-y-4">
|
<div key={day} className="space-y-4">
|
||||||
<div className="flex flex-col items-center justify-between p-3 bg-blue-50 rounded-lg">
|
<div className="flex flex-col items-center justify-between p-3 bg-blue-50 rounded-lg h-full">
|
||||||
<div>
|
<p className="font-medium capitalize text-center mb-2">{weekdaysPT[day]}</p>
|
||||||
<p className="font-medium capitalize">{weekdaysPT[day]}</p>
|
<div className="text-center w-full">
|
||||||
</div>
|
|
||||||
<div className="text-center">
|
|
||||||
{times.length > 0 ? (
|
{times.length > 0 ? (
|
||||||
times.map((t, i) => (
|
times.map((t, i) => (
|
||||||
<div key={i}>
|
<div key={i}>
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<p className="text-sm text-gray-600 hover:text-accent-foreground hover:bg-gray-200">
|
<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)} <br /> {formatTime(t.end)}
|
{formatTime(t.start)} - {formatTime(t.end)}
|
||||||
</p>
|
</p>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
<DropdownMenuItem onClick={() => handleOpenModal(t, day)}>
|
<DropdownMenuItem onClick={() => handleOpenModal(t, day)}>
|
||||||
<Eye className="w-4 h-4 mr-2" />
|
<Edit className="w-4 h-4 mr-2" />
|
||||||
Editar
|
Editar
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
onClick={() => openDeleteDialog(t, day)}
|
onClick={() => openDeleteDialog(t, day)}
|
||||||
className="text-red-600">
|
className="text-red-600 focus:bg-red-50 focus:text-red-600">
|
||||||
<Trash2 className="w-4 h-4 mr-2" />
|
<Trash2 className="w-4 h-4 mr-2" />
|
||||||
Excluir
|
Excluir
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
@ -474,6 +482,8 @@ export default function AvailabilityPage() {
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</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}>
|
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||||
<AlertDialogContent>
|
<AlertDialogContent>
|
||||||
<AlertDialogHeader>
|
<AlertDialogHeader>
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
|
// app/doctor/pacientes/page.tsx (assumindo a localização)
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState, useCallback } from "react";
|
||||||
import DoctorLayout from "@/components/doctor-layout";
|
import DoctorLayout from "@/components/doctor-layout";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import {
|
import {
|
||||||
@ -9,9 +10,17 @@ import {
|
|||||||
DropdownMenuItem,
|
DropdownMenuItem,
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from "@/components/ui/dropdown-menu";
|
} 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 { api } from "@/services/api.mjs";
|
||||||
import { PatientDetailsModal } from "@/components/ui/patient-details-modal";
|
import { PatientDetailsModal } from "@/components/ui/patient-details-modal";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
|
||||||
interface Paciente {
|
interface Paciente {
|
||||||
id: string;
|
id: string;
|
||||||
@ -41,6 +50,60 @@ export default function PacientesPage() {
|
|||||||
const [selectedPatient, setSelectedPatient] = useState<Paciente | null>(null);
|
const [selectedPatient, setSelectedPatient] = useState<Paciente | null>(null);
|
||||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||||
|
|
||||||
|
// --- Lógica de Paginação INÍCIO ---
|
||||||
|
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) => {
|
const handleOpenModal = (patient: Paciente) => {
|
||||||
setSelectedPatient(patient);
|
setSelectedPatient(patient);
|
||||||
setIsModalOpen(true);
|
setIsModalOpen(true);
|
||||||
@ -51,92 +114,132 @@ export default function PacientesPage() {
|
|||||||
setIsModalOpen(false);
|
setIsModalOpen(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
const formatDate = (dateString: string) => {
|
const formatDate = (dateString: string | null | undefined) => {
|
||||||
if (!dateString) return "";
|
if (!dateString) return "N/A";
|
||||||
|
try {
|
||||||
const date = new Date(dateString);
|
const date = new Date(dateString);
|
||||||
return new Intl.DateTimeFormat('pt-BR').format(date);
|
return new Intl.DateTimeFormat("pt-BR").format(date);
|
||||||
|
} catch (e) {
|
||||||
|
return dateString; // Retorna o string original se o formato for inválido
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const [itemsPerPage, setItemsPerPage] = useState(5);
|
const fetchPacientes = useCallback(async () => {
|
||||||
const [currentPage, setCurrentPage] = useState(1);
|
|
||||||
|
|
||||||
const indexOfLastItem = currentPage * itemsPerPage;
|
|
||||||
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
|
|
||||||
const currentItems = pacientes.slice(indexOfFirstItem, indexOfLastItem);
|
|
||||||
|
|
||||||
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
async function fetchPacientes() {
|
|
||||||
try {
|
try {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
const json = await api.get("/rest/v1/patients");
|
const json = await api.get("/rest/v1/patients");
|
||||||
const items = Array.isArray(json) ? json : (Array.isArray(json?.data) ? json.data : []);
|
const items = Array.isArray(json)
|
||||||
|
? json
|
||||||
|
: Array.isArray(json?.data)
|
||||||
|
? json.data
|
||||||
|
: [];
|
||||||
|
|
||||||
const mapped = items.map((p: any) => ({
|
const mapped: Paciente[] = items.map((p: any) => ({
|
||||||
id: String(p.id ?? ""),
|
id: String(p.id ?? ""),
|
||||||
nome: p.full_name ?? "",
|
nome: p.full_name ?? "—",
|
||||||
telefone: p.phone_mobile ?? "",
|
telefone: p.phone_mobile ?? "N/A",
|
||||||
cidade: p.city ?? "",
|
cidade: p.city ?? "N/A",
|
||||||
estado: p.state ?? "",
|
estado: p.state ?? "N/A",
|
||||||
ultimoAtendimento: formatDate(p.created_at) ?? "",
|
ultimoAtendimento: formatDate(p.created_at),
|
||||||
proximoAtendimento: "",
|
proximoAtendimento: "N/A", // Necessita de lógica de agendamento real
|
||||||
email: p.email ?? "",
|
email: p.email ?? "N/A",
|
||||||
birth_date: p.birth_date ?? "",
|
birth_date: p.birth_date ?? "N/A",
|
||||||
cpf: p.cpf ?? "",
|
cpf: p.cpf ?? "N/A",
|
||||||
blood_type: p.blood_type ?? "",
|
blood_type: p.blood_type ?? "N/A",
|
||||||
weight_kg: p.weight_kg ?? 0,
|
weight_kg: p.weight_kg ?? 0,
|
||||||
height_m: p.height_m ?? 0,
|
height_m: p.height_m ?? 0,
|
||||||
street: p.street ?? "",
|
street: p.street ?? "N/A",
|
||||||
number: p.number ?? "",
|
number: p.number ?? "N/A",
|
||||||
complement: p.complement ?? "",
|
complement: p.complement ?? "N/A",
|
||||||
neighborhood: p.neighborhood ?? "",
|
neighborhood: p.neighborhood ?? "N/A",
|
||||||
cep: p.cep ?? "",
|
cep: p.cep ?? "N/A",
|
||||||
}));
|
}));
|
||||||
|
|
||||||
setPacientes(mapped);
|
setPacientes(mapped);
|
||||||
|
setCurrentPage(1); // Resetar a página ao carregar novos dados
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
|
console.error("Erro ao carregar pacientes:", e);
|
||||||
setError(e?.message || "Erro ao carregar pacientes");
|
setError(e?.message || "Erro ao carregar pacientes");
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
fetchPacientes();
|
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchPacientes();
|
||||||
|
}, [fetchPacientes]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DoctorLayout>
|
<DoctorLayout>
|
||||||
<div className="space-y-6">
|
<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>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-foreground">Pacientes</h1>
|
<h1 className="text-2xl font-bold text-foreground">Pacientes</h1>
|
||||||
<p className="text-muted-foreground">Lista de pacientes vinculados</p>
|
<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-green-600 hover:bg-green-700">
|
||||||
|
Novo Paciente
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
</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">
|
<div className="overflow-x-auto">
|
||||||
<table className="w-full">
|
<table className="min-w-[600px] w-full">
|
||||||
<thead className="bg-muted border-b border-border">
|
<thead className="bg-muted border-b border-border">
|
||||||
<tr>
|
<tr>
|
||||||
<th className="text-left p-4 font-medium text-foreground">Nome</th>
|
<th className="text-left p-3 sm:p-4 font-medium text-foreground">Nome</th>
|
||||||
<th className="text-left p-4 font-medium text-foreground">Telefone</th>
|
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden md:table-cell">
|
||||||
<th className="text-left p-4 font-medium text-foreground">Cidade</th>
|
Telefone
|
||||||
<th className="text-left p-4 font-medium text-foreground">Estado</th>
|
</th>
|
||||||
<th className="text-left p-4 font-medium text-foreground">Último atendimento</th>
|
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden lg:table-cell">
|
||||||
<th className="text-left p-4 font-medium text-foreground">Próximo atendimento</th>
|
Cidade
|
||||||
<th className="text-left p-4 font-medium text-foreground">Ações</th>
|
</th>
|
||||||
|
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden lg:table-cell">
|
||||||
|
Estado
|
||||||
|
</th>
|
||||||
|
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden xl:table-cell">
|
||||||
|
Último atendimento
|
||||||
|
</th>
|
||||||
|
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden xl:table-cell">
|
||||||
|
Próximo atendimento
|
||||||
|
</th>
|
||||||
|
<th className="text-left p-3 sm:p-4 font-medium text-foreground">Ações</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<tr>
|
<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...
|
Carregando pacientes...
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
) : error ? (
|
) : error ? (
|
||||||
<tr>
|
<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>
|
</tr>
|
||||||
) : pacientes.length === 0 ? (
|
) : pacientes.length === 0 ? (
|
||||||
<tr>
|
<tr>
|
||||||
@ -146,17 +249,32 @@ export default function PacientesPage() {
|
|||||||
</tr>
|
</tr>
|
||||||
) : (
|
) : (
|
||||||
currentItems.map((p) => (
|
currentItems.map((p) => (
|
||||||
<tr key={p.id} className="border-b border-border hover:bg-accent">
|
<tr
|
||||||
<td className="p-4">{p.nome}</td>
|
key={p.id}
|
||||||
<td className="p-4 text-muted-foreground">{p.telefone}</td>
|
className="border-b border-border hover:bg-accent/40 transition-colors"
|
||||||
<td className="p-4 text-muted-foreground">{p.cidade}</td>
|
>
|
||||||
<td className="p-4 text-muted-foreground">{p.estado}</td>
|
<td className="p-3 sm:p-4">{p.nome}</td>
|
||||||
<td className="p-4 text-muted-foreground">{p.ultimoAtendimento}</td>
|
<td className="p-3 sm:p-4 text-muted-foreground hidden md:table-cell">
|
||||||
<td className="p-4 text-muted-foreground">{p.proximoAtendimento}</td>
|
{p.telefone}
|
||||||
<td className="p-4">
|
</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>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<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>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
<DropdownMenuItem onClick={() => handleOpenModal(p)}>
|
<DropdownMenuItem onClick={() => handleOpenModal(p)}>
|
||||||
@ -164,7 +282,7 @@ export default function PacientesPage() {
|
|||||||
Ver detalhes
|
Ver detalhes
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem asChild>
|
<DropdownMenuItem asChild>
|
||||||
<Link href={`/doctor/medicos/${p.id}/laudos`}>
|
<Link href={`/doctor/pacientes/${p.id}/laudos`}>
|
||||||
<Edit className="w-4 h-4 mr-2" />
|
<Edit className="w-4 h-4 mr-2" />
|
||||||
Laudos
|
Laudos
|
||||||
</Link>
|
</Link>
|
||||||
@ -175,11 +293,14 @@ export default function PacientesPage() {
|
|||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
const newPacientes = pacientes.filter((pac) => pac.id !== p.id)
|
// Simulação de exclusão (A exclusão real deve ser feita via API)
|
||||||
setPacientes(newPacientes)
|
const newPacientes = pacientes.filter((pac) => pac.id !== p.id);
|
||||||
alert(`Paciente ID: ${p.id} excluído`)
|
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" />
|
<Trash2 className="w-4 h-4 mr-2" />
|
||||||
Excluir
|
Excluir
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
@ -192,19 +313,51 @@ export default function PacientesPage() {
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</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
|
<button
|
||||||
key={i}
|
onClick={goToPrevPage}
|
||||||
onClick={() => paginate(i + 1)}
|
disabled={currentPage === 1}
|
||||||
className={`px-4 py-2 rounded-md ${currentPage === i + 1 ? 'bg-primary text-primary-foreground' : 'bg-secondary text-secondary-foreground'}`}
|
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>
|
||||||
|
|
||||||
|
{/* Números das Páginas */}
|
||||||
|
{visiblePageNumbers.map((number) => (
|
||||||
|
<button
|
||||||
|
key={number}
|
||||||
|
onClick={() => paginate(number)}
|
||||||
|
className={`px-4 py-2 rounded-md font-medium transition-colors text-sm border border-border ${
|
||||||
|
currentPage === number
|
||||||
|
? "bg-green-600 text-primary-foreground shadow-md border-green-600"
|
||||||
|
: "bg-secondary text-secondary-foreground hover:bg-secondary/80"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{number}
|
||||||
</button>
|
</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>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
<PatientDetailsModal
|
<PatientDetailsModal
|
||||||
patient={selectedPatient}
|
patient={selectedPatient}
|
||||||
isOpen={isModalOpen}
|
isOpen={isModalOpen}
|
||||||
|
|||||||
@ -1,534 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import { useState } from "react"
|
|
||||||
import { useRouter } from "next/navigation"
|
|
||||||
import Link from "next/link"
|
|
||||||
import { Button } from "@/components/ui/button"
|
|
||||||
import { Input } from "@/components/ui/input"
|
|
||||||
import { Label } from "@/components/ui/label"
|
|
||||||
import { Textarea } from "@/components/ui/textarea"
|
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
|
||||||
import { Checkbox } from "@/components/ui/checkbox"
|
|
||||||
import { Upload, X, ChevronDown, Save, Loader2 } from "lucide-react"
|
|
||||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
|
|
||||||
import ManagerLayout from "@/components/manager-layout"
|
|
||||||
import { doctorsService } from "services/doctorsApi.mjs";
|
|
||||||
|
|
||||||
|
|
||||||
const UF_LIST = ["AC", "AL", "AP", "AM", "BA", "CE", "DF", "ES", "GO", "MA", "MT", "MS", "MG", "PA", "PB", "PR", "PE", "PI", "RJ", "RN", "RS", "RO", "RR", "SC", "SP", "SE", "TO"];
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
interface DoctorFormData {
|
|
||||||
|
|
||||||
nomeCompleto: string;
|
|
||||||
crm: string;
|
|
||||||
crmEstado: string;
|
|
||||||
cpf: string;
|
|
||||||
email: string;
|
|
||||||
especialidade: string;
|
|
||||||
telefoneCelular: string;
|
|
||||||
telefone2: string;
|
|
||||||
cep: string;
|
|
||||||
endereco: string;
|
|
||||||
numero: string;
|
|
||||||
complemento: string;
|
|
||||||
bairro: string;
|
|
||||||
cidade: string;
|
|
||||||
estado: string;
|
|
||||||
dataNascimento: string;
|
|
||||||
rg: string;
|
|
||||||
ativo: boolean;
|
|
||||||
observacoes: string;
|
|
||||||
anexos: { id: number, name: string }[];
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
const apiMap: { [K in keyof DoctorFormData]: string | null } = {
|
|
||||||
nomeCompleto: 'full_name',
|
|
||||||
crm: 'crm',
|
|
||||||
crmEstado: 'crm_uf',
|
|
||||||
cpf: 'cpf',
|
|
||||||
email: 'email',
|
|
||||||
|
|
||||||
especialidade: 'specialty',
|
|
||||||
telefoneCelular: 'phone_mobile',
|
|
||||||
telefone2: 'phone2',
|
|
||||||
cep: 'cep',
|
|
||||||
endereco: 'street',
|
|
||||||
numero: 'number',
|
|
||||||
complemento: 'complement',
|
|
||||||
bairro: 'neighborhood',
|
|
||||||
cidade: 'city',
|
|
||||||
estado: 'state',
|
|
||||||
dataNascimento: 'birth_date',
|
|
||||||
rg: 'rg',
|
|
||||||
ativo: 'active',
|
|
||||||
|
|
||||||
observacoes: null,
|
|
||||||
anexos: null,
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
const defaultFormData: DoctorFormData = {
|
|
||||||
nomeCompleto: '', crm: '', crmEstado: '', cpf: '', email: '',
|
|
||||||
especialidade: '', telefoneCelular: '', telefone2: '', cep: '',
|
|
||||||
endereco: '', numero: '', complemento: '', bairro: '', cidade: '', estado: '',
|
|
||||||
dataNascimento: '', rg: '', ativo: true,
|
|
||||||
observacoes: '', anexos: [],
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const cleanNumber = (value: string): string => value.replace(/\D/g, '');
|
|
||||||
|
|
||||||
const formatCPF = (value: string): string => {
|
|
||||||
const cleaned = cleanNumber(value).substring(0, 11);
|
|
||||||
return cleaned.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4');
|
|
||||||
};
|
|
||||||
|
|
||||||
const formatCEP = (value: string): string => {
|
|
||||||
const cleaned = cleanNumber(value).substring(0, 8);
|
|
||||||
return cleaned.replace(/(\d{5})(\d{3})/, '$1-$2');
|
|
||||||
};
|
|
||||||
|
|
||||||
const formatPhoneMobile = (value: string): string => {
|
|
||||||
const cleaned = cleanNumber(value).substring(0, 11);
|
|
||||||
if (cleaned.length > 10) {
|
|
||||||
return cleaned.replace(/(\d{2})(\d{5})(\d{4})/, '($1) $2-$3');
|
|
||||||
}
|
|
||||||
return cleaned.replace(/(\d{2})(\d{4})(\d{4})/, '($1) $2-$3');
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export default function NovoMedicoPage() {
|
|
||||||
const router = useRouter();
|
|
||||||
const [formData, setFormData] = useState<DoctorFormData>(defaultFormData);
|
|
||||||
const [isSaving, setIsSaving] = useState(false);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
const [anexosOpen, setAnexosOpen] = useState(false);
|
|
||||||
|
|
||||||
|
|
||||||
const handleInputChange = (key: keyof DoctorFormData, value: string | boolean | { id: number, name: string }[]) => {
|
|
||||||
|
|
||||||
|
|
||||||
if (typeof value === 'string') {
|
|
||||||
let maskedValue = value;
|
|
||||||
if (key === 'cpf') maskedValue = formatCPF(value);
|
|
||||||
if (key === 'cep') maskedValue = formatCEP(value);
|
|
||||||
if (key === 'telefoneCelular' || key === 'telefone2') maskedValue = formatPhoneMobile(value);
|
|
||||||
|
|
||||||
setFormData((prev) => ({ ...prev, [key]: maskedValue }));
|
|
||||||
} else {
|
|
||||||
setFormData((prev) => ({ ...prev, [key]: value }));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
const adicionarAnexo = () => {
|
|
||||||
const newId = Date.now();
|
|
||||||
handleInputChange('anexos', [...formData.anexos, { id: newId, name: `Documento ${formData.anexos.length + 1}` }]);
|
|
||||||
}
|
|
||||||
|
|
||||||
const removerAnexo = (id: number) => {
|
|
||||||
handleInputChange('anexos', formData.anexos.filter((anexo) => anexo.id !== id));
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
const requiredFields = [
|
|
||||||
{ key: 'nomeCompleto', name: 'Nome Completo' },
|
|
||||||
{ key: 'crm', name: 'CRM' },
|
|
||||||
{ key: 'crmEstado', name: 'UF do CRM' },
|
|
||||||
{ key: 'cpf', name: 'CPF' },
|
|
||||||
{ key: 'email', name: 'E-mail' },
|
|
||||||
] as const;
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
setError(null);
|
|
||||||
setIsSaving(true);
|
|
||||||
|
|
||||||
|
|
||||||
for (const field of requiredFields) {
|
|
||||||
let valueToCheck = formData[field.key];
|
|
||||||
|
|
||||||
|
|
||||||
if (!valueToCheck || String(valueToCheck).trim() === '') {
|
|
||||||
setError(`O campo obrigatório "${field.name}" deve ser preenchido.`);
|
|
||||||
setIsSaving(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const finalPayload: { [key: string]: any } = {};
|
|
||||||
const formKeys = Object.keys(formData) as Array<keyof DoctorFormData>;
|
|
||||||
|
|
||||||
|
|
||||||
formKeys.forEach((key) => {
|
|
||||||
const apiFieldName = apiMap[key];
|
|
||||||
|
|
||||||
if (!apiFieldName) return;
|
|
||||||
|
|
||||||
let value = formData[key];
|
|
||||||
|
|
||||||
if (typeof value === 'string') {
|
|
||||||
let trimmedValue = value.trim();
|
|
||||||
|
|
||||||
|
|
||||||
const isOptional = !requiredFields.some(f => f.key === key);
|
|
||||||
|
|
||||||
if (isOptional && trimmedValue === '') {
|
|
||||||
finalPayload[apiFieldName] = null;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
if (key === 'crmEstado' || key === 'estado') {
|
|
||||||
trimmedValue = trimmedValue.toUpperCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
value = trimmedValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
finalPayload[apiFieldName] = value;
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
try {
|
|
||||||
|
|
||||||
const response = await doctorsService.create(finalPayload);
|
|
||||||
router.push("/manager/home");
|
|
||||||
} catch (e: any) {
|
|
||||||
console.error("Erro ao salvar o médico:", e);
|
|
||||||
|
|
||||||
let detailedError = `Erro na requisição. Verifique se o **CRM** ou **CPF** já existem ou se as **Máscaras/Datas** estão incorretas.`;
|
|
||||||
|
|
||||||
|
|
||||||
if (e.message && e.message.includes("duplicate key value violates unique constraint")) {
|
|
||||||
|
|
||||||
detailedError = "O CPF ou CRM informado já está cadastrado no sistema. Por favor, verifique os dados de identificação.";
|
|
||||||
} else if (e.message && e.message.includes("Detalhes:")) {
|
|
||||||
|
|
||||||
detailedError = e.message.split("Detalhes:")[1].trim();
|
|
||||||
} else if (e.message) {
|
|
||||||
detailedError = e.message;
|
|
||||||
}
|
|
||||||
|
|
||||||
setError(`Erro ao cadastrar. Detalhes: ${detailedError}`);
|
|
||||||
} finally {
|
|
||||||
setIsSaving(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ManagerLayout>
|
|
||||||
<div className="w-full space-y-6 p-4 md:p-8">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<h1 className="text-2xl font-bold text-gray-900">Novo Médico</h1>
|
|
||||||
<p className="text-sm text-gray-500">
|
|
||||||
Preencha os dados do novo médico para cadastro.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<Link href="/manager/home">
|
|
||||||
<Button variant="outline">Cancelar</Button>
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<form onSubmit={handleSubmit} className="space-y-6">
|
|
||||||
|
|
||||||
{error && (
|
|
||||||
<div className="p-3 bg-red-100 text-red-700 rounded-lg border border-red-300">
|
|
||||||
<p className="font-medium">Erro no Cadastro:</p>
|
|
||||||
<p className="text-sm">{error}</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
|
|
||||||
<div className="space-y-4">
|
|
||||||
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">
|
|
||||||
Dados Principais e Pessoais
|
|
||||||
</h2>
|
|
||||||
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-4 gap-4">
|
|
||||||
<div className="space-y-2 col-span-2">
|
|
||||||
<Label htmlFor="nomeCompleto">Nome Completo *</Label>
|
|
||||||
<Input
|
|
||||||
id="nomeCompleto"
|
|
||||||
value={formData.nomeCompleto}
|
|
||||||
onChange={(e) => handleInputChange("nomeCompleto", e.target.value)}
|
|
||||||
placeholder="Nome do Médico"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2 col-span-1">
|
|
||||||
<Label htmlFor="crm">CRM *</Label>
|
|
||||||
<Input
|
|
||||||
id="crm"
|
|
||||||
value={formData.crm}
|
|
||||||
onChange={(e) => handleInputChange("crm", e.target.value)}
|
|
||||||
placeholder="Ex: 123456"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2 col-span-1">
|
|
||||||
<Label htmlFor="crmEstado">UF do CRM *</Label>
|
|
||||||
<Select value={formData.crmEstado} onValueChange={(v) => handleInputChange("crmEstado", v)}>
|
|
||||||
<SelectTrigger id="crmEstado">
|
|
||||||
<SelectValue placeholder="UF" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
{UF_LIST.map(uf => (
|
|
||||||
<SelectItem key={uf} value={uf}>{uf}</SelectItem>
|
|
||||||
))}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-3 gap-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="especialidade">Especialidade</Label>
|
|
||||||
<Input
|
|
||||||
id="especialidade"
|
|
||||||
value={formData.especialidade}
|
|
||||||
onChange={(e) => handleInputChange("especialidade", e.target.value)}
|
|
||||||
placeholder="Ex: Cardiologia"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="cpf">CPF *</Label>
|
|
||||||
<Input
|
|
||||||
id="cpf"
|
|
||||||
value={formData.cpf}
|
|
||||||
onChange={(e) => handleInputChange("cpf", e.target.value)}
|
|
||||||
placeholder="000.000.000-00"
|
|
||||||
maxLength={14}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="rg">RG</Label>
|
|
||||||
<Input
|
|
||||||
id="rg"
|
|
||||||
value={formData.rg}
|
|
||||||
onChange={(e) => handleInputChange("rg", e.target.value)}
|
|
||||||
placeholder="00.000.000-0"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-3 gap-4">
|
|
||||||
<div className="space-y-2 col-span-2">
|
|
||||||
<Label htmlFor="email">E-mail *</Label>
|
|
||||||
<Input
|
|
||||||
id="email"
|
|
||||||
type="email"
|
|
||||||
value={formData.email}
|
|
||||||
onChange={(e) => handleInputChange("email", e.target.value)}
|
|
||||||
placeholder="exemplo@dominio.com"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2 col-span-1">
|
|
||||||
<Label htmlFor="dataNascimento">Data de Nascimento</Label>
|
|
||||||
<Input
|
|
||||||
id="dataNascimento"
|
|
||||||
type="date"
|
|
||||||
value={formData.dataNascimento}
|
|
||||||
onChange={(e) => handleInputChange("dataNascimento", e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
|
|
||||||
<div className="space-y-4">
|
|
||||||
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">
|
|
||||||
Contato e Endereço
|
|
||||||
</h2>
|
|
||||||
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-3 gap-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="telefoneCelular">Telefone Celular</Label>
|
|
||||||
<Input
|
|
||||||
id="telefoneCelular"
|
|
||||||
value={formData.telefoneCelular}
|
|
||||||
onChange={(e) => handleInputChange("telefoneCelular", e.target.value)}
|
|
||||||
placeholder="(00) 00000-0000"
|
|
||||||
maxLength={15}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="telefone2">Telefone Adicional</Label>
|
|
||||||
<Input
|
|
||||||
id="telefone2"
|
|
||||||
value={formData.telefone2}
|
|
||||||
onChange={(e) => handleInputChange("telefone2", e.target.value)}
|
|
||||||
placeholder="(00) 00000-0000"
|
|
||||||
maxLength={15}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2 flex items-end justify-center pb-1">
|
|
||||||
<div className="flex items-center space-x-2">
|
|
||||||
<Checkbox
|
|
||||||
id="ativo"
|
|
||||||
checked={formData.ativo}
|
|
||||||
onCheckedChange={(checked) => handleInputChange("ativo", checked === true)}
|
|
||||||
/>
|
|
||||||
<Label htmlFor="ativo">Médico Ativo</Label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-4 gap-4">
|
|
||||||
<div className="space-y-2 col-span-1">
|
|
||||||
<Label htmlFor="cep">CEP</Label>
|
|
||||||
<Input
|
|
||||||
id="cep"
|
|
||||||
value={formData.cep}
|
|
||||||
onChange={(e) => handleInputChange("cep", e.target.value)}
|
|
||||||
placeholder="00000-000"
|
|
||||||
maxLength={9}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2 col-span-3">
|
|
||||||
<Label htmlFor="endereco">Rua</Label>
|
|
||||||
<Input
|
|
||||||
id="endereco"
|
|
||||||
value={formData.endereco}
|
|
||||||
onChange={(e) => handleInputChange("endereco", e.target.value)}
|
|
||||||
placeholder="Rua, Avenida, etc."
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="grid md:grid-cols-4 gap-4">
|
|
||||||
<div className="space-y-2 col-span-1">
|
|
||||||
<Label htmlFor="numero">Número</Label>
|
|
||||||
<Input
|
|
||||||
id="numero"
|
|
||||||
value={formData.numero}
|
|
||||||
onChange={(e) => handleInputChange("numero", e.target.value)}
|
|
||||||
placeholder="123"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2 col-span-3">
|
|
||||||
<Label htmlFor="complemento">Complemento</Label>
|
|
||||||
<Input
|
|
||||||
id="complemento"
|
|
||||||
value={formData.complemento}
|
|
||||||
onChange={(e) => handleInputChange("complemento", e.target.value)}
|
|
||||||
placeholder="Apto, Bloco, etc."
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="grid md:grid-cols-4 gap-4">
|
|
||||||
<div className="space-y-2 col-span-2">
|
|
||||||
<Label htmlFor="bairro">Bairro</Label>
|
|
||||||
<Input
|
|
||||||
id="bairro"
|
|
||||||
value={formData.bairro}
|
|
||||||
onChange={(e) => handleInputChange("bairro", e.target.value)}
|
|
||||||
placeholder="Bairro"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2 col-span-1">
|
|
||||||
<Label htmlFor="estado">Estado</Label>
|
|
||||||
<Input
|
|
||||||
id="estado"
|
|
||||||
value={formData.estado}
|
|
||||||
onChange={(e) => handleInputChange("estado", e.target.value)}
|
|
||||||
placeholder="SP"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2 col-span-1">
|
|
||||||
<Label htmlFor="cidade">Cidade</Label>
|
|
||||||
<Input
|
|
||||||
id="cidade"
|
|
||||||
value={formData.cidade}
|
|
||||||
onChange={(e) => handleInputChange("cidade", e.target.value)}
|
|
||||||
placeholder="São Paulo"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
|
|
||||||
<div className="space-y-4">
|
|
||||||
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">
|
|
||||||
Outras Informações (Internas)
|
|
||||||
</h2>
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="observacoes">Observações (Apenas internas)</Label>
|
|
||||||
<Textarea
|
|
||||||
id="observacoes"
|
|
||||||
value={formData.observacoes}
|
|
||||||
onChange={(e) => handleInputChange("observacoes", e.target.value)}
|
|
||||||
placeholder="Notas internas sobre o médico..."
|
|
||||||
className="min-h-[100px]"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-4">
|
|
||||||
<Collapsible open={anexosOpen} onOpenChange={setAnexosOpen}>
|
|
||||||
<CollapsibleTrigger asChild>
|
|
||||||
<div className="flex justify-between items-center cursor-pointer pb-2 border-b">
|
|
||||||
<h2 className="text-md font-semibold text-gray-800">Anexos ({formData.anexos.length})</h2>
|
|
||||||
<ChevronDown className={`w-5 h-5 transition-transform ${anexosOpen ? 'rotate-180' : 'rotate-0'}`} />
|
|
||||||
</div>
|
|
||||||
</CollapsibleTrigger>
|
|
||||||
<CollapsibleContent className="space-y-4 pt-2">
|
|
||||||
<Button type="button" onClick={adicionarAnexo} variant="outline" className="w-full">
|
|
||||||
<Upload className="w-4 h-4 mr-2" />
|
|
||||||
Adicionar Documento
|
|
||||||
</Button>
|
|
||||||
{formData.anexos.map((anexo) => (
|
|
||||||
<div key={anexo.id} className="flex items-center justify-between p-3 bg-gray-50 border rounded-lg">
|
|
||||||
<span className="text-sm text-gray-700">{anexo.name}</span>
|
|
||||||
<Button type="button" variant="ghost" size="icon" onClick={() => removerAnexo(anexo.id)}>
|
|
||||||
<X className="w-4 h-4 text-red-500" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</CollapsibleContent>
|
|
||||||
</Collapsible>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
|
|
||||||
<div className="flex justify-end gap-4 pb-8 pt-4">
|
|
||||||
<Link href="/manager/home">
|
|
||||||
<Button type="button" variant="outline" disabled={isSaving}>
|
|
||||||
Cancelar
|
|
||||||
</Button>
|
|
||||||
</Link>
|
|
||||||
<Button
|
|
||||||
type="submit"
|
|
||||||
className="bg-green-600 hover:bg-green-700"
|
|
||||||
disabled={isSaving}
|
|
||||||
>
|
|
||||||
{isSaving ? (
|
|
||||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
|
||||||
) : (
|
|
||||||
<Save className="w-4 h-4 mr-2" />
|
|
||||||
)}
|
|
||||||
{isSaving ? "Salvando..." : "Salvar Médico"}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</ManagerLayout>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -1,13 +1,13 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import React, { useEffect, useState, useCallback } from "react"
|
import React, { useEffect, useState, useCallback, useMemo } from "react"
|
||||||
import ManagerLayout from "@/components/manager-layout";
|
import ManagerLayout from "@/components/manager-layout";
|
||||||
import Link from "next/link"
|
import Link from "next/link"
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button"
|
||||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||||
import { Plus, Edit, Trash2, Eye, Calendar, Filter, MoreVertical, Loader2 } from "lucide-react"
|
import { Plus, Edit, Trash2, Eye, Calendar, Filter, Loader2 } from "lucide-react"
|
||||||
import {
|
import {
|
||||||
AlertDialog,
|
AlertDialog,
|
||||||
AlertDialogAction,
|
AlertDialogAction,
|
||||||
@ -30,7 +30,7 @@ interface Doctor {
|
|||||||
phone_mobile: string | null;
|
phone_mobile: string | null;
|
||||||
city: string | null;
|
city: string | null;
|
||||||
state: string | null;
|
state: string | null;
|
||||||
|
status?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -38,7 +38,6 @@ interface DoctorDetails {
|
|||||||
nome: string;
|
nome: string;
|
||||||
crm: string;
|
crm: string;
|
||||||
especialidade: string;
|
especialidade: string;
|
||||||
|
|
||||||
contato: {
|
contato: {
|
||||||
celular?: string;
|
celular?: string;
|
||||||
telefone1?: string;
|
telefone1?: string;
|
||||||
@ -58,7 +57,6 @@ interface DoctorDetails {
|
|||||||
export default function DoctorsPage() {
|
export default function DoctorsPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
|
|
||||||
const [doctors, setDoctors] = useState<Doctor[]>([]);
|
const [doctors, setDoctors] = useState<Doctor[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
@ -67,16 +65,25 @@ export default function DoctorsPage() {
|
|||||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||||
const [doctorToDeleteId, setDoctorToDeleteId] = useState<number | null>(null);
|
const [doctorToDeleteId, setDoctorToDeleteId] = useState<number | null>(null);
|
||||||
|
|
||||||
|
// --- Estados para Filtros ---
|
||||||
|
const [specialtyFilter, setSpecialtyFilter] = useState("all");
|
||||||
|
const [statusFilter, setStatusFilter] = useState("all");
|
||||||
|
|
||||||
|
// --- Estados para Paginação ---
|
||||||
|
const [itemsPerPage, setItemsPerPage] = useState(10);
|
||||||
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
|
|
||||||
const fetchDoctors = useCallback(async () => {
|
const fetchDoctors = useCallback(async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
|
|
||||||
const data: Doctor[] = await doctorsService.list();
|
const data: Doctor[] = await doctorsService.list();
|
||||||
setDoctors(data || []);
|
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) {
|
} catch (e: any) {
|
||||||
console.error("Erro ao carregar lista de médicos:", e);
|
console.error("Erro ao carregar lista de médicos:", e);
|
||||||
setError("Não foi possível carregar a lista de médicos. Verifique a conexão com a API.");
|
setError("Não foi possível carregar a lista de médicos. Verifique a conexão com a API.");
|
||||||
@ -94,23 +101,15 @@ export default function DoctorsPage() {
|
|||||||
|
|
||||||
const openDetailsDialog = async (doctor: Doctor) => {
|
const openDetailsDialog = async (doctor: Doctor) => {
|
||||||
setDetailsDialogOpen(true);
|
setDetailsDialogOpen(true);
|
||||||
|
|
||||||
setDoctorDetails({
|
setDoctorDetails({
|
||||||
nome: doctor.full_name,
|
nome: doctor.full_name,
|
||||||
crm: doctor.crm,
|
crm: doctor.crm,
|
||||||
especialidade: doctor.specialty,
|
especialidade: doctor.specialty,
|
||||||
contato: {
|
contato: { celular: doctor.phone_mobile ?? undefined },
|
||||||
celular: doctor.phone_mobile ?? undefined,
|
endereco: { cidade: doctor.city ?? undefined, estado: doctor.state ?? undefined },
|
||||||
telefone1: undefined
|
status: doctor.status || "Ativo",
|
||||||
},
|
|
||||||
endereco: {
|
|
||||||
cidade: doctor.city ?? undefined,
|
|
||||||
estado: doctor.state ?? undefined,
|
|
||||||
},
|
|
||||||
|
|
||||||
convenio: "Particular",
|
convenio: "Particular",
|
||||||
vip: false,
|
vip: false,
|
||||||
status: "Ativo",
|
|
||||||
ultimo_atendimento: "N/A",
|
ultimo_atendimento: "N/A",
|
||||||
proximo_atendimento: "N/A",
|
proximo_atendimento: "N/A",
|
||||||
});
|
});
|
||||||
@ -119,19 +118,14 @@ export default function DoctorsPage() {
|
|||||||
|
|
||||||
const handleDelete = async () => {
|
const handleDelete = async () => {
|
||||||
if (doctorToDeleteId === null) return;
|
if (doctorToDeleteId === null) return;
|
||||||
|
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
await doctorsService.delete(doctorToDeleteId);
|
await doctorsService.delete(doctorToDeleteId);
|
||||||
|
|
||||||
console.log(`Médico com ID ${doctorToDeleteId} excluído com sucesso!`);
|
|
||||||
|
|
||||||
setDeleteDialogOpen(false);
|
setDeleteDialogOpen(false);
|
||||||
setDoctorToDeleteId(null);
|
setDoctorToDeleteId(null);
|
||||||
await fetchDoctors();
|
await fetchDoctors();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("Erro ao excluir:", e);
|
console.error("Erro ao excluir:", e);
|
||||||
|
|
||||||
alert("Erro ao excluir médico.");
|
alert("Erro ao excluir médico.");
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
@ -143,55 +137,133 @@ export default function DoctorsPage() {
|
|||||||
setDeleteDialogOpen(true);
|
setDeleteDialogOpen(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const uniqueSpecialties = useMemo(() => {
|
||||||
|
const specialties = doctors.map(doctor => doctor.specialty).filter(Boolean);
|
||||||
|
return [...new Set(specialties)];
|
||||||
|
}, [doctors]);
|
||||||
|
|
||||||
const handleEdit = (doctorId: number) => {
|
const filteredDoctors = doctors.filter(doctor => {
|
||||||
|
const specialtyMatch = specialtyFilter === "all" || doctor.specialty === specialtyFilter;
|
||||||
|
const statusMatch = statusFilter === "all" || doctor.status === statusFilter;
|
||||||
|
return specialtyMatch && statusMatch;
|
||||||
|
});
|
||||||
|
|
||||||
router.push(`/manager/home/${doctorId}/editar`);
|
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[] = [];
|
||||||
|
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);
|
||||||
|
|
||||||
|
const handleItemsPerPageChange = (value: string) => {
|
||||||
|
setItemsPerPage(Number(value));
|
||||||
|
setCurrentPage(1);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ManagerLayout>
|
<ManagerLayout>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6 px-2 sm:px-4 md:px-6">
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
|
{/* Cabeçalho */}
|
||||||
|
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-gray-900">Médicos Cadastrados</h1>
|
<h1 className="text-2xl font-bold text-gray-900">Médicos Cadastrados</h1>
|
||||||
<p className="text-sm text-gray-500">Gerencie todos os profissionais de saúde.</p>
|
<p className="text-sm text-gray-500">Gerencie todos os profissionais de saúde.</p>
|
||||||
</div>
|
</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>
|
||||||
|
|
||||||
|
|
||||||
<div className="flex items-center space-x-4 bg-white p-4 rounded-lg border border-gray-200">
|
{/* Filtros e Itens por Página */}
|
||||||
<Filter className="w-5 h-5 text-gray-400" />
|
<div className="flex flex-wrap items-center gap-3 bg-white p-3 sm:p-4 rounded-lg border border-gray-200">
|
||||||
<Select>
|
<div className="flex items-center gap-2 w-full md:w-auto">
|
||||||
<SelectTrigger className="w-[180px]">
|
<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" />
|
<SelectValue placeholder="Especialidade" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="cardiologia">Cardiologia</SelectItem>
|
<SelectItem value="all">Todas</SelectItem>
|
||||||
<SelectItem value="dermatologia">Dermatologia</SelectItem>
|
{uniqueSpecialties.map(specialty => (
|
||||||
<SelectItem value="pediatria">Pediatria</SelectItem>
|
<SelectItem key={specialty} value={specialty}>{specialty}</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>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</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 */}
|
||||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-hidden">
|
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-hidden">
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="p-8 text-center text-gray-500">
|
<div className="p-8 text-center text-gray-500">
|
||||||
@ -199,68 +271,67 @@ export default function DoctorsPage() {
|
|||||||
Carregando médicos...
|
Carregando médicos...
|
||||||
</div>
|
</div>
|
||||||
) : error ? (
|
) : error ? (
|
||||||
<div className="p-8 text-center text-red-600">
|
<div className="p-8 text-center text-red-600">{error}</div>
|
||||||
{error}
|
) : filteredDoctors.length === 0 ? (
|
||||||
</div>
|
|
||||||
) : doctors.length === 0 ? (
|
|
||||||
<div className="p-8 text-center text-gray-500">
|
<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>.
|
{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>
|
||||||
) : (
|
) : (
|
||||||
<div className="overflow-x-auto">
|
<div className="overflow-x-auto">
|
||||||
<table className="min-w-full divide-y divide-gray-200">
|
<table className="w-full min-w-[600px]">
|
||||||
<thead className="bg-gray-50">
|
<thead className="bg-gray-50 border-b border-gray-200">
|
||||||
<tr>
|
<tr>
|
||||||
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Nome</th>
|
<th className="text-left p-2 md:p-4 font-medium text-gray-700">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 className="text-left p-2 md:p-4 font-medium text-gray-700">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 className="text-left p-2 md:p-4 font-medium text-gray-700">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 className="text-left p-2 md:p-4 font-medium text-gray-700">Status</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 className="text-left p-2 md:p-4 font-medium text-gray-700">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>
|
<th className="text-right p-4 font-medium text-gray-700">Ações</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody className="bg-white divide-y divide-gray-200">
|
<tbody className="bg-white divide-y divide-gray-200">
|
||||||
{doctors.map((doctor) => (
|
{currentItems.map((doctor) => (
|
||||||
<tr key={doctor.id} className="hover:bg-gray-50">
|
<tr key={doctor.id} className="hover:bg-gray-50 transition">
|
||||||
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{doctor.full_name}</td>
|
<td className="px-4 py-3 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-4 py-3 text-gray-500 hidden sm:table-cell">{doctor.crm}</td>
|
||||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{doctor.specialty}</td>
|
<td className="px-4 py-3 text-gray-500 hidden md:table-cell">{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-4 py-3 text-gray-500 hidden lg:table-cell">{doctor.status || "N/A"}</td>
|
||||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
|
<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"}
|
{(doctor.city || doctor.state)
|
||||||
|
? `${doctor.city || ""}${doctor.city && doctor.state ? '/' : ''}${doctor.state || ""}`
|
||||||
|
: "N/A"}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
|
<td className="px-4 py-3 text-right">
|
||||||
|
{/* ===== INÍCIO DA ALTERAÇÃO ===== */}
|
||||||
<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>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<Button variant="ghost" className="h-8 w-8 p-0" title="Mais Ações">
|
<div className="text-blue-600 cursor-pointer inline-block">Ações</div>
|
||||||
<span className="sr-only">Mais Ações</span>
|
|
||||||
<MoreVertical className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end">
|
<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>
|
<DropdownMenuItem>
|
||||||
<Calendar className="mr-2 h-4 w-4" />
|
<Calendar className="mr-2 h-4 w-4" />
|
||||||
Agendar Consulta
|
Marcar consulta
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(doctor.id)}>
|
||||||
|
<Trash2 className="mr-2 h-4 w-4" />
|
||||||
|
Excluir
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
</div>
|
{/* ===== FIM DA ALTERAÇÃO ===== */}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
@ -270,7 +341,41 @@ export default function DoctorsPage() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Paginação */}
|
||||||
|
{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">
|
||||||
|
<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>
|
||||||
|
|
||||||
|
{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>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<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>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Dialogs de Exclusão e Detalhes */}
|
||||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||||
<AlertDialogContent>
|
<AlertDialogContent>
|
||||||
<AlertDialogHeader>
|
<AlertDialogHeader>
|
||||||
@ -282,25 +387,22 @@ export default function DoctorsPage() {
|
|||||||
<AlertDialogFooter>
|
<AlertDialogFooter>
|
||||||
<AlertDialogCancel disabled={loading}>Cancelar</AlertDialogCancel>
|
<AlertDialogCancel disabled={loading}>Cancelar</AlertDialogCancel>
|
||||||
<AlertDialogAction onClick={handleDelete} className="bg-red-600 hover:bg-red-700" disabled={loading}>
|
<AlertDialogAction onClick={handleDelete} className="bg-red-600 hover:bg-red-700" disabled={loading}>
|
||||||
{loading ? (
|
{loading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null}
|
||||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
|
||||||
) : null}
|
|
||||||
Excluir
|
Excluir
|
||||||
</AlertDialogAction>
|
</AlertDialogAction>
|
||||||
</AlertDialogFooter>
|
</AlertDialogFooter>
|
||||||
</AlertDialogContent>
|
</AlertDialogContent>
|
||||||
</AlertDialog>
|
</AlertDialog>
|
||||||
|
|
||||||
|
|
||||||
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
||||||
<AlertDialogContent>
|
<AlertDialogContent className="max-w-[95%] sm:max-w-lg">
|
||||||
<AlertDialogHeader>
|
<AlertDialogHeader>
|
||||||
<AlertDialogTitle className="text-2xl">{doctorDetails?.nome}</AlertDialogTitle>
|
<AlertDialogTitle className="text-2xl">{doctorDetails?.nome}</AlertDialogTitle>
|
||||||
<AlertDialogDescription className="text-left text-gray-700">
|
<AlertDialogDescription className="text-left text-gray-700">
|
||||||
{doctorDetails && (
|
{doctorDetails && (
|
||||||
<div className="space-y-3 text-left">
|
<div className="space-y-3 text-left">
|
||||||
<h3 className="font-semibold mt-2">Informações Principais</h3>
|
<h3 className="font-semibold mt-2">Informações Principais</h3>
|
||||||
<div className="grid grid-cols-2 gap-y-1 gap-x-4 text-sm">
|
<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>CRM:</strong> {doctorDetails.crm}</div>
|
||||||
<div><strong>Especialidade:</strong> {doctorDetails.especialidade}</div>
|
<div><strong>Especialidade:</strong> {doctorDetails.especialidade}</div>
|
||||||
<div><strong>Celular:</strong> {doctorDetails.contato.celular || 'N/A'}</div>
|
<div><strong>Celular:</strong> {doctorDetails.contato.celular || 'N/A'}</div>
|
||||||
@ -308,7 +410,7 @@ export default function DoctorsPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<h3 className="font-semibold mt-4">Atendimento e Convênio</h3>
|
<h3 className="font-semibold mt-4">Atendimento e Convênio</h3>
|
||||||
<div className="grid grid-cols-2 gap-y-1 gap-x-4 text-sm">
|
<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>Convênio:</strong> {doctorDetails.convenio || 'N/A'}</div>
|
||||||
<div><strong>VIP:</strong> {doctorDetails.vip ? "Sim" : "Não"}</div>
|
<div><strong>VIP:</strong> {doctorDetails.vip ? "Sim" : "Não"}</div>
|
||||||
<div><strong>Status:</strong> {doctorDetails.status || 'N/A'}</div>
|
<div><strong>Status:</strong> {doctorDetails.status || 'N/A'}</div>
|
||||||
|
|||||||
@ -1,676 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import type React from "react";
|
|
||||||
|
|
||||||
import { useState } from "react";
|
|
||||||
import Link from "next/link";
|
|
||||||
import { useRouter } from "next/navigation";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { Input } from "@/components/ui/input";
|
|
||||||
import { Label } from "@/components/ui/label";
|
|
||||||
import { Textarea } from "@/components/ui/textarea";
|
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
|
||||||
import { Checkbox } from "@/components/ui/checkbox";
|
|
||||||
import { Upload, Plus, X, ChevronDown } from "lucide-react";
|
|
||||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
|
|
||||||
import { useToast } from "@/hooks/use-toast";
|
|
||||||
import SecretaryLayout from "@/components/secretary-layout";
|
|
||||||
import { patientsService } from "@/services/patientsApi.mjs";
|
|
||||||
|
|
||||||
export default function NovoPacientePage() {
|
|
||||||
const [anexosOpen, setAnexosOpen] = useState(false);
|
|
||||||
const [anexos, setAnexos] = useState<string[]>([]);
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
|
||||||
const router = useRouter();
|
|
||||||
const { toast } = useToast();
|
|
||||||
|
|
||||||
const adicionarAnexo = () => {
|
|
||||||
setAnexos([...anexos, `Documento ${anexos.length + 1}`]);
|
|
||||||
};
|
|
||||||
|
|
||||||
const removerAnexo = (index: number) => {
|
|
||||||
setAnexos(anexos.filter((_, i) => i !== index));
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
const cleanNumber = (value: string): string => value.replace(/\D/g, '');
|
|
||||||
|
|
||||||
const formatCPF = (value: string): string => {
|
|
||||||
const cleaned = cleanNumber(value).substring(0, 11);
|
|
||||||
return cleaned.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4');
|
|
||||||
};
|
|
||||||
|
|
||||||
const formatCEP = (value: string): string => {
|
|
||||||
const cleaned = cleanNumber(value).substring(0, 8);
|
|
||||||
return cleaned.replace(/(\d{5})(\d{3})/, '$1-$2');
|
|
||||||
};
|
|
||||||
|
|
||||||
const formatPhoneMobile = (value: string): string => {
|
|
||||||
const cleaned = cleanNumber(value).substring(0, 11);
|
|
||||||
if (cleaned.length > 10) {
|
|
||||||
return cleaned.replace(/(\d{2})(\d{5})(\d{4})/, '+55 ($1) $2-$3');
|
|
||||||
}
|
|
||||||
return cleaned.replace(/(\d{2})(\d{4})(\d{4})/, '+55 ($1) $2-$3');
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
|
||||||
e.preventDefault();
|
|
||||||
if (isLoading) return;
|
|
||||||
setIsLoading(true);
|
|
||||||
const form = e.currentTarget;
|
|
||||||
const formData = new FormData(form);
|
|
||||||
|
|
||||||
const apiPayload = {
|
|
||||||
full_name: (formData.get("nome") as string) || "", // obrigatório
|
|
||||||
social_name: (formData.get("nomeSocial") as string) || undefined,
|
|
||||||
cpf: (formatCPF(formData.get("cpf") as string)) || "", // obrigatório
|
|
||||||
email: (formData.get("email") as string) || "", // obrigatório
|
|
||||||
phone_mobile: (formatPhoneMobile(formData.get("celular") as string)) || "", // obrigatório
|
|
||||||
birth_date: formData.get("dataNascimento") ? new Date(formData.get("dataNascimento") as string) : undefined,
|
|
||||||
sex: (formData.get("sexo") as string) || undefined,
|
|
||||||
blood_type: (formData.get("tipoSanguineo") as string) || undefined,
|
|
||||||
weight_kg: formData.get("peso") ? parseFloat(formData.get("peso") as string) : undefined,
|
|
||||||
height_m: formData.get("altura") ? parseFloat(formData.get("altura") as string) : undefined,
|
|
||||||
cep: (formatCEP(formData.get("cep") as string)) || undefined,
|
|
||||||
street: (formData.get("endereco") as string) || undefined,
|
|
||||||
number: (formData.get("numero") as string) || undefined,
|
|
||||||
complement: (formData.get("complemento") as string) || undefined,
|
|
||||||
neighborhood: (formData.get("bairro") as string) || undefined,
|
|
||||||
city: (formData.get("cidade") as string) || undefined,
|
|
||||||
state: (formData.get("estado") as string) || undefined,
|
|
||||||
};
|
|
||||||
|
|
||||||
console.log(apiPayload.email)
|
|
||||||
console.log(apiPayload.cep)
|
|
||||||
console.log(apiPayload.phone_mobile)
|
|
||||||
|
|
||||||
const errors: string[] = [];
|
|
||||||
const fullName = apiPayload.full_name?.trim() || "";
|
|
||||||
if (!fullName || fullName.length < 2 || fullName.length > 255) {
|
|
||||||
errors.push("Nome deve ter entre 2 e 255 caracteres.");
|
|
||||||
}
|
|
||||||
|
|
||||||
const cpf = apiPayload.cpf || "";
|
|
||||||
if (!/^\d{3}\.\d{3}\.\d{3}-\d{2}$/.test(cpf)) {
|
|
||||||
errors.push("CPF deve estar no formato XXX.XXX.XXX-XX.");
|
|
||||||
}
|
|
||||||
|
|
||||||
const sex = apiPayload.sex;
|
|
||||||
const allowedSex = ["Masculino", "Feminino", "outro"];
|
|
||||||
if (!sex || !allowedSex.includes(sex)) {
|
|
||||||
errors.push("Sexo é obrigatório e deve ser masculino, feminino ou outro.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!apiPayload.birth_date) {
|
|
||||||
errors.push("Data de nascimento é obrigatória.");
|
|
||||||
}
|
|
||||||
|
|
||||||
const phoneMobile = apiPayload.phone_mobile || "";
|
|
||||||
if (phoneMobile && !/^\+55 \(\d{2}\) \d{4,5}-\d{4}$/.test(phoneMobile)) {
|
|
||||||
errors.push("Celular deve estar no formato +55 (XX) XXXXX-XXXX.");
|
|
||||||
}
|
|
||||||
|
|
||||||
const cep = apiPayload.cep || "";
|
|
||||||
if (cep && !/^\d{5}-\d{3}$/.test(cep)) {
|
|
||||||
errors.push("CEP deve estar no formato XXXXX-XXX.");
|
|
||||||
}
|
|
||||||
|
|
||||||
const state = apiPayload.state || "";
|
|
||||||
if (state && state.length !== 2) {
|
|
||||||
errors.push("Estado (UF) deve ter 2 caracteres.");
|
|
||||||
}
|
|
||||||
if (errors.length) {
|
|
||||||
toast({ title: "Corrija os campos", description: errors[0] });
|
|
||||||
console.log("campos errados")
|
|
||||||
setIsLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const res = await patientsService.create(apiPayload);
|
|
||||||
console.log(res)
|
|
||||||
|
|
||||||
let message = "Paciente cadastrado com sucesso";
|
|
||||||
try {
|
|
||||||
if (!res[0].id) {
|
|
||||||
throw new Error(`${res.error} ${res.message}`|| "A API retornou erro");
|
|
||||||
} else {
|
|
||||||
console.log(message)
|
|
||||||
}
|
|
||||||
} catch {}
|
|
||||||
|
|
||||||
toast({
|
|
||||||
title: "Sucesso",
|
|
||||||
description: message,
|
|
||||||
});
|
|
||||||
router.push("/manager/pacientes");
|
|
||||||
} catch (err: any) {
|
|
||||||
toast({
|
|
||||||
title: "Erro",
|
|
||||||
description: err?.message || "Não foi possível cadastrar o paciente",
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<SecretaryLayout>
|
|
||||||
<div className="space-y-6">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<h1 className="text-2xl font-bold text-gray-900">Novo Paciente</h1>
|
|
||||||
<p className="text-gray-600">Cadastre um novo paciente no sistema</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<form className="space-y-6" onSubmit={handleSubmit}>
|
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Dados Pessoais</h2>
|
|
||||||
|
|
||||||
<div className="space-y-6">
|
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
<div className="w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center">
|
|
||||||
<Upload className="w-8 h-8 text-gray-400" />
|
|
||||||
</div>
|
|
||||||
<Button variant="outline" type="button" size="sm">
|
|
||||||
<Upload className="w-4 h-4 mr-2" />
|
|
||||||
Carregar Foto
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="nome" className="text-sm font-medium text-gray-700">
|
|
||||||
Nome *
|
|
||||||
</Label>
|
|
||||||
<Input id="nome" name="nome" placeholder="Nome completo" required className="mt-1" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="nomeSocial" className="text-sm font-medium text-gray-700">
|
|
||||||
Nome Social
|
|
||||||
</Label>
|
|
||||||
<Input id="nomeSocial" name="nomeSocial" placeholder="Nome social ou apelido" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-3 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="cpf" className="text-sm font-medium text-gray-700">
|
|
||||||
CPF *
|
|
||||||
</Label>
|
|
||||||
<Input id="cpf" name="cpf" placeholder="000.000.000-00" required className="mt-1" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="rg" className="text-sm font-medium text-gray-700">
|
|
||||||
RG
|
|
||||||
</Label>
|
|
||||||
<Input id="rg" name="rg" placeholder="00.000.000-0" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="outrosDocumentos" className="text-sm font-medium text-gray-700">
|
|
||||||
Outros Documentos
|
|
||||||
</Label>
|
|
||||||
<Select name="outrosDocumentos">
|
|
||||||
<SelectTrigger className="mt-1">
|
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="cnh">CNH</SelectItem>
|
|
||||||
<SelectItem value="passaporte">Passaporte</SelectItem>
|
|
||||||
<SelectItem value="carteira-trabalho">Carteira de Trabalho</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-3 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label className="text-sm font-medium text-gray-700">Sexo *</Label>
|
|
||||||
<div className="flex gap-4 mt-2">
|
|
||||||
<label className="flex items-center gap-2">
|
|
||||||
<input type="radio" name="sexo" value="Masculino" className="text-blue-600" required/>
|
|
||||||
<span className="text-sm">Masculino</span>
|
|
||||||
</label>
|
|
||||||
<label className="flex items-center gap-2">
|
|
||||||
<input type="radio" name="sexo" value="Feminino" className="text-blue-600" required/>
|
|
||||||
<span className="text-sm">Feminino</span>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="dataNascimento" className="text-sm font-medium text-gray-700">
|
|
||||||
Data de Nascimento *
|
|
||||||
</Label>
|
|
||||||
<Input id="dataNascimento" name="dataNascimento" type="date" className="mt-1" required/>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="estadoCivil" className="text-sm font-medium text-gray-700">
|
|
||||||
Estado Civil
|
|
||||||
</Label>
|
|
||||||
<Select name="estadoCivil">
|
|
||||||
<SelectTrigger className="mt-1">
|
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="solteiro">Solteiro(a)</SelectItem>
|
|
||||||
<SelectItem value="casado">Casado(a)</SelectItem>
|
|
||||||
<SelectItem value="divorciado">Divorciado(a)</SelectItem>
|
|
||||||
<SelectItem value="viuvo">Viúvo(a)</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="etnia" className="text-sm font-medium text-gray-700">
|
|
||||||
Etnia
|
|
||||||
</Label>
|
|
||||||
<Select name="etnia">
|
|
||||||
<SelectTrigger className="mt-1">
|
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="branca">Branca</SelectItem>
|
|
||||||
<SelectItem value="preta">Preta</SelectItem>
|
|
||||||
<SelectItem value="parda">Parda</SelectItem>
|
|
||||||
<SelectItem value="amarela">Amarela</SelectItem>
|
|
||||||
<SelectItem value="indigena">Indígena</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="raca" className="text-sm font-medium text-gray-700">
|
|
||||||
Raça
|
|
||||||
</Label>
|
|
||||||
<Select name="raca">
|
|
||||||
<SelectTrigger className="mt-1">
|
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="branca">Branca</SelectItem>
|
|
||||||
<SelectItem value="preta">Preta</SelectItem>
|
|
||||||
<SelectItem value="parda">Parda</SelectItem>
|
|
||||||
<SelectItem value="amarela">Amarela</SelectItem>
|
|
||||||
<SelectItem value="indigena">Indígena</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="naturalidade" className="text-sm font-medium text-gray-700">
|
|
||||||
Naturalidade
|
|
||||||
</Label>
|
|
||||||
<Select name="naturalidade">
|
|
||||||
<SelectTrigger className="mt-1">
|
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="aracaju">Aracaju</SelectItem>
|
|
||||||
<SelectItem value="salvador">Salvador</SelectItem>
|
|
||||||
<SelectItem value="recife">Recife</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="nacionalidade" className="text-sm font-medium text-gray-700">
|
|
||||||
Nacionalidade
|
|
||||||
</Label>
|
|
||||||
<Select name="nacionalidade">
|
|
||||||
<SelectTrigger className="mt-1">
|
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="brasileira">Brasileira</SelectItem>
|
|
||||||
<SelectItem value="estrangeira">Estrangeira</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="profissao" className="text-sm font-medium text-gray-700">
|
|
||||||
Profissão
|
|
||||||
</Label>
|
|
||||||
<Input id="profissao" name="profissao" placeholder="Profissão" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="nomeMae" className="text-sm font-medium text-gray-700">
|
|
||||||
Nome da Mãe
|
|
||||||
</Label>
|
|
||||||
<Input id="nomeMae" name="nomeMae" placeholder="Nome da mãe" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="profissaoMae" className="text-sm font-medium text-gray-700">
|
|
||||||
Profissão da Mãe
|
|
||||||
</Label>
|
|
||||||
<Input id="profissaoMae" name="profissaoMae" placeholder="Profissão da mãe" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="nomePai" className="text-sm font-medium text-gray-700">
|
|
||||||
Nome do Pai
|
|
||||||
</Label>
|
|
||||||
<Input id="nomePai" name="nomePai" placeholder="Nome do pai" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="profissaoPai" className="text-sm font-medium text-gray-700">
|
|
||||||
Profissão do Pai
|
|
||||||
</Label>
|
|
||||||
<Input id="profissaoPai" name="profissaoPai" placeholder="Profissão do pai" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="nomeResponsavel" className="text-sm font-medium text-gray-700">
|
|
||||||
Nome do Responsável
|
|
||||||
</Label>
|
|
||||||
<Input id="nomeResponsavel" name="nomeResponsavel" placeholder="Nome do responsável" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="cpfResponsavel" className="text-sm font-medium text-gray-700">
|
|
||||||
CPF do Responsável
|
|
||||||
</Label>
|
|
||||||
<Input id="cpfResponsavel" name="cpfResponsavel" placeholder="000.000.000-00" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="nomeEsposo" className="text-sm font-medium text-gray-700">
|
|
||||||
Nome do Esposo(a)
|
|
||||||
</Label>
|
|
||||||
<Input id="nomeEsposo" name="nomeEsposo" placeholder="Nome do esposo(a)" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center space-x-2">
|
|
||||||
<Checkbox id="rnGuia" name="rnGuia" />
|
|
||||||
<Label htmlFor="rnGuia" className="text-sm text-gray-700">
|
|
||||||
RN na Guia do convênio
|
|
||||||
</Label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="codigoLegado" className="text-sm font-medium text-gray-700">
|
|
||||||
Código Legado
|
|
||||||
</Label>
|
|
||||||
<Input id="codigoLegado" name="codigoLegado" placeholder="Código do sistema anterior" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="observacoes" className="text-sm font-medium text-gray-700">
|
|
||||||
Observações
|
|
||||||
</Label>
|
|
||||||
<Textarea id="observacoes" name="observacoes" placeholder="Observações gerais sobre o paciente" className="min-h-[100px] mt-1" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Collapsible open={anexosOpen} onOpenChange={setAnexosOpen}>
|
|
||||||
<CollapsibleTrigger asChild>
|
|
||||||
<Button variant="ghost" type="button" className="w-full justify-between p-0 h-auto text-left">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<div className="w-4 h-4 bg-gray-400 rounded-sm flex items-center justify-center">
|
|
||||||
<span className="text-white text-xs">📎</span>
|
|
||||||
</div>
|
|
||||||
<span className="text-sm font-medium text-gray-700">Anexos do paciente</span>
|
|
||||||
</div>
|
|
||||||
<ChevronDown className={`w-4 h-4 transition-transform ${anexosOpen ? "rotate-180" : ""}`} />
|
|
||||||
</Button>
|
|
||||||
</CollapsibleTrigger>
|
|
||||||
<CollapsibleContent className="space-y-4 mt-4">
|
|
||||||
{anexos.map((anexo, index) => (
|
|
||||||
<div key={index} className="flex items-center justify-between p-3 border rounded-lg bg-gray-50">
|
|
||||||
<span className="text-sm">{anexo}</span>
|
|
||||||
<Button variant="ghost" size="sm" onClick={() => removerAnexo(index)} type="button">
|
|
||||||
<X className="w-4 h-4" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
<Button variant="outline" onClick={adicionarAnexo} type="button" size="sm">
|
|
||||||
<Plus className="w-4 h-4 mr-2" />
|
|
||||||
Adicionar Anexo
|
|
||||||
</Button>
|
|
||||||
</CollapsibleContent>
|
|
||||||
</Collapsible>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Contato</h2>
|
|
||||||
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="grid md:grid-cols-3 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="email" className="text-sm font-medium text-gray-700">
|
|
||||||
E-mail *
|
|
||||||
</Label>
|
|
||||||
<Input id="email" name="email" type="email" placeholder="email@exemplo.com" className="mt-1" required/>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="celular" className="text-sm font-medium text-gray-700">
|
|
||||||
Celular *
|
|
||||||
</Label>
|
|
||||||
<div className="flex mt-1">
|
|
||||||
<Select>
|
|
||||||
<SelectTrigger className="w-20 rounded-r-none">
|
|
||||||
<SelectValue placeholder="+55" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="+55">+55</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
<Input id="celular" name="celular" placeholder="(XX) XXXXX-XXXX" className="rounded-l-none" required/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="telefone1" className="text-sm font-medium text-gray-700">
|
|
||||||
Telefone 1
|
|
||||||
</Label>
|
|
||||||
<Input id="telefone1" name="telefone1" placeholder="(XX) XXXX-XXXX" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="telefone2" className="text-sm font-medium text-gray-700">
|
|
||||||
Telefone 2
|
|
||||||
</Label>
|
|
||||||
<Input id="telefone2" name="telefone2" placeholder="(XX) XXXX-XXXX" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Endereço</h2>
|
|
||||||
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="cep" className="text-sm font-medium text-gray-700">
|
|
||||||
CEP
|
|
||||||
</Label>
|
|
||||||
<Input id="cep" name="cep" placeholder="00000-000" className="mt-1 max-w-xs" />
|
|
||||||
</div>
|
|
||||||
<div className="grid md:grid-cols-3 gap-4">
|
|
||||||
<div className="md:col-span-2">
|
|
||||||
<Label htmlFor="endereco" className="text-sm font-medium text-gray-700">
|
|
||||||
Endereço
|
|
||||||
</Label>
|
|
||||||
<Input id="endereco" name="endereco" placeholder="Rua, Avenida..." className="mt-1" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="numero" className="text-sm font-medium text-gray-700">
|
|
||||||
Número
|
|
||||||
</Label>
|
|
||||||
<Input id="numero" name="numero" placeholder="123" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="complemento" className="text-sm font-medium text-gray-700">
|
|
||||||
Complemento
|
|
||||||
</Label>
|
|
||||||
<Input id="complemento" name="complemento" placeholder="Apto, Bloco..." className="mt-1" />
|
|
||||||
</div>
|
|
||||||
<div className="grid md:grid-cols-3 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="bairro" className="text-sm font-medium text-gray-700">
|
|
||||||
Bairro
|
|
||||||
</Label>
|
|
||||||
<Input id="bairro" name="bairro" placeholder="Bairro" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="cidade" className="text-sm font-medium text-gray-700">
|
|
||||||
Cidade
|
|
||||||
</Label>
|
|
||||||
<Input id="cidade" name="cidade" placeholder="Cidade" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="estado" className="text-sm font-medium text-gray-700">
|
|
||||||
Estado
|
|
||||||
</Label>
|
|
||||||
<Select name="estado">
|
|
||||||
<SelectTrigger className="mt-1">
|
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="SE">Sergipe</SelectItem>
|
|
||||||
<SelectItem value="BA">Bahia</SelectItem>
|
|
||||||
<SelectItem value="AL">Alagoas</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Informações Médicas</h2>
|
|
||||||
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="grid md:grid-cols-4 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="tipoSanguineo" className="text-sm font-medium text-gray-700">
|
|
||||||
Tipo Sanguíneo
|
|
||||||
</Label>
|
|
||||||
<Select name="tipoSanguineo">
|
|
||||||
<SelectTrigger className="mt-1">
|
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="A+">A+</SelectItem>
|
|
||||||
<SelectItem value="A-">A-</SelectItem>
|
|
||||||
<SelectItem value="B+">B+</SelectItem>
|
|
||||||
<SelectItem value="B-">B-</SelectItem>
|
|
||||||
<SelectItem value="AB+">AB+</SelectItem>
|
|
||||||
<SelectItem value="AB-">AB-</SelectItem>
|
|
||||||
<SelectItem value="O+">O+</SelectItem>
|
|
||||||
<SelectItem value="O-">O-</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="peso" className="text-sm font-medium text-gray-700">
|
|
||||||
Peso
|
|
||||||
</Label>
|
|
||||||
<div className="relative mt-1">
|
|
||||||
<Input id="peso" name="peso" type="number" placeholder="70" />
|
|
||||||
<span className="absolute right-3 top-1/2 transform -translate-y-1/2 text-sm text-gray-500">kg</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="altura" className="text-sm font-medium text-gray-700">
|
|
||||||
Altura
|
|
||||||
</Label>
|
|
||||||
<div className="relative mt-1">
|
|
||||||
<Input id="altura" name="altura" type="number" step="0.01" placeholder="1.70" />
|
|
||||||
<span className="absolute right-3 top-1/2 transform -translate-y-1/2 text-sm text-gray-500">m</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="imc" className="text-sm font-medium text-gray-700">
|
|
||||||
IMC
|
|
||||||
</Label>
|
|
||||||
<div className="relative mt-1">
|
|
||||||
<Input id="imc" name="imc" placeholder="Calculado automaticamente" disabled />
|
|
||||||
<span className="absolute right-3 top-1/2 transform -translate-y-1/2 text-sm text-gray-500">kg/m²</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="alergias" className="text-sm font-medium text-gray-700">
|
|
||||||
Alergias
|
|
||||||
</Label>
|
|
||||||
<Textarea id="alergias" name="alergias" placeholder="Ex: AAS, Dipirona, etc." className="min-h-[80px] mt-1" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Informações de Convênio</h2>
|
|
||||||
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="convenio" className="text-sm font-medium text-gray-700">
|
|
||||||
Convênio
|
|
||||||
</Label>
|
|
||||||
<Select name="convenio">
|
|
||||||
<SelectTrigger className="mt-1">
|
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="particular">Particular</SelectItem>
|
|
||||||
<SelectItem value="sus">SUS</SelectItem>
|
|
||||||
<SelectItem value="unimed">Unimed</SelectItem>
|
|
||||||
<SelectItem value="bradesco">Bradesco Saúde</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="plano" className="text-sm font-medium text-gray-700">
|
|
||||||
Plano
|
|
||||||
</Label>
|
|
||||||
<Input id="plano" name="plano" placeholder="Nome do plano" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="numeroMatricula" className="text-sm font-medium text-gray-700">
|
|
||||||
Nº de Matrícula
|
|
||||||
</Label>
|
|
||||||
<Input id="numeroMatricula" name="numeroMatricula" placeholder="Número da matrícula" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="validadeCarteira" className="text-sm font-medium text-gray-700">
|
|
||||||
Validade da Carteira
|
|
||||||
</Label>
|
|
||||||
<Input id="validadeCarteira" name="validadeCarteira" type="date" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center space-x-2">
|
|
||||||
<Checkbox id="validadeIndeterminada" name="validadeIndeterminada" />
|
|
||||||
<Label htmlFor="validadeIndeterminada" className="text-sm text-gray-700">
|
|
||||||
Validade Indeterminada
|
|
||||||
</Label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex justify-end gap-4">
|
|
||||||
<Link href="/manager/pacientes">
|
|
||||||
<Button variant="outline" type="button">
|
|
||||||
Cancelar
|
|
||||||
</Button>
|
|
||||||
</Link>
|
|
||||||
<Button type="submit" className="bg-blue-600 hover:bg-blue-700" disabled={isLoading}>
|
|
||||||
{isLoading ? "Salvando..." : "Salvar Paciente"}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</SecretaryLayout>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -1,132 +1,139 @@
|
|||||||
|
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, useEffect, useRef, useCallback } from "react";
|
import { useState, useEffect, useCallback } from "react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||||
DropdownMenu,
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
DropdownMenuContent,
|
import { Plus, Edit, Trash2, Eye, Calendar, Filter, Loader2 } from "lucide-react";
|
||||||
DropdownMenuItem,
|
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||||
DropdownMenuTrigger,
|
|
||||||
} from "@/components/ui/dropdown-menu";
|
|
||||||
import {
|
|
||||||
Select,
|
|
||||||
SelectContent,
|
|
||||||
SelectItem,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from "@/components/ui/select";
|
|
||||||
import { Plus, Edit, Trash2, Eye, Calendar, Filter } from "lucide-react";
|
|
||||||
import {
|
|
||||||
AlertDialog,
|
|
||||||
AlertDialogAction,
|
|
||||||
AlertDialogCancel,
|
|
||||||
AlertDialogContent,
|
|
||||||
AlertDialogDescription,
|
|
||||||
AlertDialogFooter,
|
|
||||||
AlertDialogHeader,
|
|
||||||
AlertDialogTitle,
|
|
||||||
} from "@/components/ui/alert-dialog";
|
|
||||||
import ManagerLayout from "@/components/manager-layout";
|
|
||||||
import { patientsService } from "@/services/patientsApi.mjs";
|
import { patientsService } from "@/services/patientsApi.mjs";
|
||||||
|
import ManagerLayout from "@/components/manager-layout";
|
||||||
|
|
||||||
|
// Defina o tamanho da página.
|
||||||
|
const PAGE_SIZE = 5;
|
||||||
|
|
||||||
export default function PacientesPage() {
|
export default function PacientesPage() {
|
||||||
|
// --- ESTADOS DE DADOS E GERAL ---
|
||||||
const [searchTerm, setSearchTerm] = useState("");
|
const [searchTerm, setSearchTerm] = useState("");
|
||||||
const [convenioFilter, setConvenioFilter] = useState("all");
|
const [convenioFilter, setConvenioFilter] = useState("all");
|
||||||
const [vipFilter, setVipFilter] = useState("all");
|
const [vipFilter, setVipFilter] = useState("all");
|
||||||
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);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// --- ESTADOS DE PAGINAÇÃO ---
|
||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
const [hasNext, setHasNext] = useState(true);
|
|
||||||
const [isFetching, setIsFetching] = useState(false);
|
// CÁLCULO DA PAGINAÇÃO
|
||||||
const observerRef = useRef<HTMLDivElement | null>(null);
|
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 [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||||
const [patientToDelete, setPatientToDelete] = useState<string | null>(null);
|
const [patientToDelete, setPatientToDelete] = useState<string | null>(null);
|
||||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
||||||
const [patientDetails, setPatientDetails] = useState<any | null>(null);
|
const [patientDetails, setPatientDetails] = useState<any | null>(null);
|
||||||
|
|
||||||
|
// --- FUNÇÕES DE LÓGICA ---
|
||||||
|
|
||||||
|
// 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) => {
|
const openDetailsDialog = async (patientId: string) => {
|
||||||
setDetailsDialogOpen(true);
|
setDetailsDialogOpen(true);
|
||||||
setPatientDetails(null);
|
setPatientDetails(null);
|
||||||
try {
|
try {
|
||||||
const res = await patientsService.getById(patientId);
|
const res = await patientsService.getById(patientId);
|
||||||
setPatientDetails(res[0]);
|
setPatientDetails(Array.isArray(res) ? res[0] : res); // Supondo que retorne um array com um item
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
setPatientDetails({ error: e?.message || "Erro ao buscar detalhes" });
|
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) => {
|
const handleDeletePatient = async (patientId: string) => {
|
||||||
// Remove from current list (client-side deletion)
|
|
||||||
try {
|
try {
|
||||||
const res = await patientsService.delete(patientId);
|
await patientsService.delete(patientId);
|
||||||
|
// Atualiza a lista completa para refletir a exclusão
|
||||||
if (res) {
|
setAllPatients((prev) => prev.filter((p) => String(p.id) !== String(patientId)));
|
||||||
alert(`${res.error} ${res.message}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
setPatients((prev) =>
|
|
||||||
prev.filter((p) => String(p.id) !== String(patientId))
|
|
||||||
);
|
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
setError(e?.message || "Erro ao deletar paciente");
|
alert(`Erro ao deletar paciente: ${e?.message || 'Erro desconhecido'}`);
|
||||||
}
|
}
|
||||||
setDeleteDialogOpen(false);
|
setDeleteDialogOpen(false);
|
||||||
setPatientToDelete(null);
|
setPatientToDelete(null);
|
||||||
@ -137,66 +144,53 @@ export default function PacientesPage() {
|
|||||||
setDeleteDialogOpen(true);
|
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 (
|
return (
|
||||||
<ManagerLayout>
|
<ManagerLayout>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6 px-2 sm:px-4 md:px-8">
|
||||||
|
{/* Header (Responsividade OK) */}
|
||||||
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-xl md:text-2xl font-bold text-foreground">
|
<h1 className="text-xl md:text-2xl font-bold text-foreground">Pacientes</h1>
|
||||||
Pacientes
|
<p className="text-muted-foreground text-sm md:text-base">Gerencie as informações de seus pacientes</p>
|
||||||
</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="/manager/pacientes/novo">
|
|
||||||
<Button className="w-full md:w-auto">
|
|
||||||
<Plus className="w-4 h-4 mr-2" />
|
|
||||||
Adicionar
|
|
||||||
</Button>
|
|
||||||
</Link>
|
|
||||||
</div>
|
</div>
|
||||||
</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 (Responsividade APLICADA) */}
|
||||||
{/* Convênio */}
|
<div className="flex flex-wrap items-center gap-4 bg-card p-4 rounded-lg border border-border">
|
||||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
<Filter className="w-5 h-5 text-gray-400" />
|
||||||
<span className="text-sm font-medium text-foreground">
|
|
||||||
Convênio
|
{/* Busca - Ocupa 100% no mobile, depois cresce */}
|
||||||
</span>
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Buscar por nome ou telefone..."
|
||||||
|
value={searchTerm}
|
||||||
|
onChange={(e) => setSearchTerm(e.target.value)}
|
||||||
|
className="w-full sm:flex-grow sm:min-w-[150px] p-2 border rounded-md text-sm"
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Convênio - Ocupa metade da linha no mobile */}
|
||||||
|
<div className="flex items-center gap-2 w-[calc(50%-8px)] sm:w-auto sm:flex-grow sm:max-w-[200px]">
|
||||||
|
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">Convênio</span>
|
||||||
<Select value={convenioFilter} onValueChange={setConvenioFilter}>
|
<Select value={convenioFilter} onValueChange={setConvenioFilter}>
|
||||||
<SelectTrigger className="w-full md:w-40">
|
<SelectTrigger className="w-full sm:w-40">
|
||||||
<SelectValue placeholder="Selecione o Convênio" />
|
<SelectValue placeholder="Convênio" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="all">Todos</SelectItem>
|
<SelectItem value="all">Todos</SelectItem>
|
||||||
<SelectItem value="Particular">Particular</SelectItem>
|
<SelectItem value="Particular">Particular</SelectItem>
|
||||||
<SelectItem value="SUS">SUS</SelectItem>
|
<SelectItem value="SUS">SUS</SelectItem>
|
||||||
<SelectItem value="Unimed">Unimed</SelectItem>
|
<SelectItem value="Unimed">Unimed</SelectItem>
|
||||||
|
{/* Adicione outros convênios conforme necessário */}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
{/* VIP - Ocupa a outra metade da linha no mobile */}
|
||||||
<span className="text-sm font-medium text-foreground">VIP</span>
|
<div className="flex items-center gap-2 w-[calc(50%-8px)] 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}>
|
<Select value={vipFilter} onValueChange={setVipFilter}>
|
||||||
<SelectTrigger className="w-full md:w-32">
|
<SelectTrigger className="w-full sm:w-32">
|
||||||
<SelectValue placeholder="Selecione" />
|
<SelectValue placeholder="VIP" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="all">Todos</SelectItem>
|
<SelectItem value="all">Todos</SelectItem>
|
||||||
@ -205,129 +199,94 @@ export default function PacientesPage() {
|
|||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</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>
|
|
||||||
|
|
||||||
<Button variant="outline" className="ml-auto w-full md:w-auto">
|
{/* Aniversariantes - Vai para a linha de baixo no mobile, ocupando 100% */}
|
||||||
<Filter className="w-4 h-4 mr-2" />
|
<Button variant="outline" className="w-full md:w-auto md:ml-auto">
|
||||||
Filtro avançado
|
<Calendar className="w-4 h-4 mr-2" />
|
||||||
|
Aniversariantes
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="bg-white rounded-lg border border-gray-200">
|
{/* Tabela (Responsividade APLICADA) */}
|
||||||
|
<div className="bg-white rounded-lg border border-gray-200 shadow-md">
|
||||||
<div className="overflow-x-auto">
|
<div className="overflow-x-auto">
|
||||||
{error ? (
|
{error ? (
|
||||||
<div className="p-6 text-red-600">{`Erro ao carregar pacientes: ${error}`}</div>
|
<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]">
|
// min-w ajustado para responsividade
|
||||||
|
<table className="w-full min-w-[650px] md:min-w-[900px]">
|
||||||
<thead className="bg-gray-50 border-b border-gray-200">
|
<thead className="bg-gray-50 border-b border-gray-200">
|
||||||
<tr>
|
<tr>
|
||||||
<th className="text-left p-2 md:p-4 font-medium text-gray-700">
|
<th className="text-left p-4 font-medium text-gray-700 w-[20%]">Nome</th>
|
||||||
Nome
|
{/* Coluna oculta em telas muito pequenas */}
|
||||||
</th>
|
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">Telefone</th>
|
||||||
<th className="text-left p-2 md:p-4 font-medium text-gray-700">
|
{/* Coluna oculta em telas pequenas e muito pequenas */}
|
||||||
Telefone
|
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden md:table-cell">Cidade / Estado</th>
|
||||||
</th>
|
{/* Coluna oculta em telas muito pequenas */}
|
||||||
<th className="text-left p-2 md:p-4 font-medium text-gray-700">
|
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">Convênio</th>
|
||||||
Cidade
|
{/* Colunas ocultas em telas médias, pequenas e muito pequenas */}
|
||||||
</th>
|
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">Último atendimento</th>
|
||||||
<th className="text-left p-2 md:p-4 font-medium text-gray-700">
|
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">Próximo atendimento</th>
|
||||||
Estado
|
<th className="text-left p-4 font-medium text-gray-700 w-[5%]">Ações</th>
|
||||||
</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>
|
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{filteredPatients.length === 0 ? (
|
{currentPatients.length === 0 ? (
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan={7} className="p-8 text-center text-gray-500">
|
<td colSpan={7} className="p-8 text-center text-gray-500">
|
||||||
{patients.length === 0
|
{allPatients.length === 0 ? "Nenhum paciente cadastrado" : "Nenhum paciente encontrado com os filtros aplicados"}
|
||||||
? "Nenhum paciente cadastrado"
|
|
||||||
: "Nenhum paciente encontrado com os filtros aplicados"}
|
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
) : (
|
) : (
|
||||||
filteredPatients.map((patient) => (
|
currentPatients.map((patient) => (
|
||||||
<tr
|
<tr key={patient.id} className="border-b border-gray-100 hover:bg-gray-50">
|
||||||
key={patient.id}
|
|
||||||
className="border-b border-gray-100 hover:bg-gray-50"
|
|
||||||
>
|
|
||||||
<td className="p-4">
|
<td className="p-4">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<div className="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center">
|
<div className="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
|
||||||
<span className="text-gray-600 font-medium text-sm">
|
<span className="text-green-600 font-medium text-sm">{patient.nome?.charAt(0) || "?"}</span>
|
||||||
{patient.nome?.charAt(0) || "?"}
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
<span className="font-medium text-gray-900">
|
<span className="font-medium text-gray-900">
|
||||||
{patient.nome}
|
{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>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td className="p-4 text-gray-600">
|
{/* Aplicação das classes de visibilidade */}
|
||||||
{patient.telefone}
|
<td className="p-4 text-gray-600 hidden sm:table-cell">{patient.telefone}</td>
|
||||||
</td>
|
<td className="p-4 text-gray-600 hidden md:table-cell">{`${patient.cidade} / ${patient.estado}`}</td>
|
||||||
<td className="p-4 text-gray-600">{patient.cidade}</td>
|
<td className="p-4 text-gray-600 hidden sm:table-cell">{patient.convenio}</td>
|
||||||
<td className="p-4 text-gray-600">{patient.estado}</td>
|
<td className="p-4 text-gray-600 hidden lg:table-cell">{patient.ultimoAtendimento}</td>
|
||||||
<td className="p-4 text-gray-600">
|
<td className="p-4 text-gray-600 hidden lg:table-cell">{patient.proximoAtendimento}</td>
|
||||||
{patient.ultimoAtendimento}
|
|
||||||
</td>
|
|
||||||
<td className="p-4 text-gray-600">
|
|
||||||
{patient.proximoAtendimento}
|
|
||||||
</td>
|
|
||||||
<td className="p-4">
|
<td className="p-4">
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<div className="text-blue-600">Ações</div>
|
<div className="text-blue-600 cursor-pointer">Ações</div>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem onClick={() => openDetailsDialog(String(patient.id))}>
|
||||||
onClick={() =>
|
|
||||||
openDetailsDialog(String(patient.id))
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<Eye className="w-4 h-4 mr-2" />
|
<Eye className="w-4 h-4 mr-2" />
|
||||||
Ver detalhes
|
Ver detalhes
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
|
||||||
<DropdownMenuItem asChild>
|
<DropdownMenuItem asChild>
|
||||||
<Link
|
<Link href={`/secretary/pacientes/${patient.id}/editar`} className="flex items-center w-full">
|
||||||
href={`/manager/pacientes/${patient.id}/editar`}
|
|
||||||
>
|
|
||||||
<Edit className="w-4 h-4 mr-2" />
|
<Edit className="w-4 h-4 mr-2" />
|
||||||
Editar
|
Editar
|
||||||
</Link>
|
</Link>
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
|
||||||
<DropdownMenuItem>
|
<DropdownMenuItem>
|
||||||
<Calendar className="w-4 h-4 mr-2" />
|
<Calendar className="w-4 h-4 mr-2" />
|
||||||
Marcar consulta
|
Marcar consulta
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(String(patient.id))}>
|
||||||
className="text-red-600"
|
|
||||||
onClick={() =>
|
|
||||||
openDeleteDialog(String(patient.id))
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<Trash2 className="w-4 h-4 mr-2" />
|
<Trash2 className="w-4 h-4 mr-2" />
|
||||||
Excluir
|
Excluir
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
@ -340,118 +299,146 @@ export default function PacientesPage() {
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
)}
|
)}
|
||||||
<div ref={observerRef} style={{ height: 1 }} />
|
</div>
|
||||||
{isFetching && (
|
|
||||||
<div className="p-4 text-center text-gray-500">
|
{/* Paginação */}
|
||||||
Carregando mais pacientes...
|
{totalPages > 1 && !loading && (
|
||||||
|
<div className="flex flex-col sm:flex-row items-center justify-center p-4 border-t border-gray-200">
|
||||||
|
{/* Renderização dos botões de número de página (Limitando a 5) */}
|
||||||
|
<div className="flex space-x-2"> {/* Increased space-x for more separation */}
|
||||||
|
{/* Botão Anterior */}
|
||||||
|
<Button
|
||||||
|
onClick={() => setPage((prev) => Math.max(1, prev - 1))}
|
||||||
|
disabled={page === 1}
|
||||||
|
variant="outline"
|
||||||
|
size="lg" // Changed to "lg" for larger buttons
|
||||||
|
>
|
||||||
|
< Anterior
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
{Array.from({ length: totalPages }, (_, index) => index + 1)
|
||||||
|
.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="lg" // Changed to "lg" for larger buttons
|
||||||
|
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="lg" // Changed to "lg" for larger buttons
|
||||||
|
>
|
||||||
|
Próximo >
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
|
{/* AlertDialogs (Permanecem os mesmos) */}
|
||||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||||
|
{/* ... (AlertDialog de Exclusão) ... */}
|
||||||
<AlertDialogContent>
|
<AlertDialogContent>
|
||||||
<AlertDialogHeader>
|
<AlertDialogHeader>
|
||||||
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
|
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
|
||||||
<AlertDialogDescription>
|
<AlertDialogDescription>Tem certeza que deseja excluir este paciente? Esta ação não pode ser desfeita.</AlertDialogDescription>
|
||||||
Tem certeza que deseja excluir este paciente? Esta ação não pode
|
|
||||||
ser desfeita.
|
|
||||||
</AlertDialogDescription>
|
|
||||||
</AlertDialogHeader>
|
</AlertDialogHeader>
|
||||||
<AlertDialogFooter>
|
<AlertDialogFooter>
|
||||||
<AlertDialogCancel>Cancelar</AlertDialogCancel>
|
<AlertDialogCancel>Cancelar</AlertDialogCancel>
|
||||||
<AlertDialogAction
|
<AlertDialogAction onClick={() => patientToDelete && handleDeletePatient(patientToDelete)} className="bg-red-600 hover:bg-red-700">
|
||||||
onClick={() =>
|
|
||||||
patientToDelete && handleDeletePatient(patientToDelete)
|
|
||||||
}
|
|
||||||
className="bg-red-600 hover:bg-red-700"
|
|
||||||
>
|
|
||||||
Excluir
|
Excluir
|
||||||
</AlertDialogAction>
|
</AlertDialogAction>
|
||||||
</AlertDialogFooter>
|
</AlertDialogFooter>
|
||||||
</AlertDialogContent>
|
</AlertDialogContent>
|
||||||
</AlertDialog>
|
</AlertDialog>
|
||||||
|
|
||||||
{/* Modal de detalhes do paciente */}
|
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
||||||
<AlertDialog
|
{/* ... (AlertDialog de Detalhes) ... */}
|
||||||
open={detailsDialogOpen}
|
|
||||||
onOpenChange={setDetailsDialogOpen}
|
|
||||||
>
|
|
||||||
<AlertDialogContent>
|
<AlertDialogContent>
|
||||||
<AlertDialogHeader>
|
<AlertDialogHeader>
|
||||||
<AlertDialogTitle>Detalhes do Paciente</AlertDialogTitle>
|
<AlertDialogTitle>Detalhes do Paciente</AlertDialogTitle>
|
||||||
<AlertDialogDescription>
|
<AlertDialogDescription>
|
||||||
{patientDetails === null ? (
|
{patientDetails === null ? (
|
||||||
<div className="text-gray-500">Carregando...</div>
|
<div className="text-gray-500">
|
||||||
|
<Loader2 className="w-6 h-6 animate-spin mx-auto text-green-600 my-4" />
|
||||||
|
Carregando...
|
||||||
|
</div>
|
||||||
) : patientDetails?.error ? (
|
) : patientDetails?.error ? (
|
||||||
<div className="text-red-600">{patientDetails.error}</div>
|
<div className="text-red-600 p-4">{patientDetails.error}</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-2 text-left">
|
<div className="grid gap-4 py-4">
|
||||||
<p>
|
<div className="grid grid-cols-2 gap-4">
|
||||||
<strong>Nome:</strong> {patientDetails.full_name}
|
<div>
|
||||||
</p>
|
<p className="font-semibold">Nome Completo</p>
|
||||||
<p>
|
<p>{patientDetails.full_name}</p>
|
||||||
<strong>CPF:</strong> {patientDetails.cpf}
|
</div>
|
||||||
</p>
|
<div>
|
||||||
<p>
|
<p className="font-semibold">Email</p>
|
||||||
<strong>Email:</strong> {patientDetails.email}
|
<p>{patientDetails.email}</p>
|
||||||
</p>
|
</div>
|
||||||
<p>
|
<div>
|
||||||
<strong>Telefone:</strong>{" "}
|
<p className="font-semibold">Telefone</p>
|
||||||
{patientDetails.phone_mobile ??
|
<p>{patientDetails.phone_mobile}</p>
|
||||||
patientDetails.phone1 ??
|
</div>
|
||||||
patientDetails.phone2 ??
|
<div>
|
||||||
"-"}
|
<p className="font-semibold">Data de Nascimento</p>
|
||||||
</p>
|
<p>{patientDetails.birth_date}</p>
|
||||||
<p>
|
</div>
|
||||||
<strong>Nome social:</strong>{" "}
|
<div>
|
||||||
{patientDetails.social_name ?? "-"}
|
<p className="font-semibold">CPF</p>
|
||||||
</p>
|
<p>{patientDetails.cpf}</p>
|
||||||
<p>
|
</div>
|
||||||
<strong>Sexo:</strong> {patientDetails.sex ?? "-"}
|
<div>
|
||||||
</p>
|
<p className="font-semibold">Tipo Sanguíneo</p>
|
||||||
<p>
|
<p>{patientDetails.blood_type}</p>
|
||||||
<strong>Tipo sanguíneo:</strong>{" "}
|
</div>
|
||||||
{patientDetails.blood_type ?? "-"}
|
<div>
|
||||||
</p>
|
<p className="font-semibold">Peso (kg)</p>
|
||||||
<p>
|
<p>{patientDetails.weight_kg}</p>
|
||||||
<strong>Peso:</strong> {patientDetails.weight_kg ?? "-"}
|
</div>
|
||||||
{patientDetails.weight_kg ? "kg" : ""}
|
<div>
|
||||||
</p>
|
<p className="font-semibold">Altura (m)</p>
|
||||||
<p>
|
<p>{patientDetails.height_m}</p>
|
||||||
<strong>Altura:</strong> {patientDetails.height_m ?? "-"}
|
</div>
|
||||||
{patientDetails.height_m ? "m" : ""}
|
</div>
|
||||||
</p>
|
<div className="border-t pt-4 mt-4">
|
||||||
<p>
|
<h3 className="font-semibold mb-2">Endereço</h3>
|
||||||
<strong>IMC:</strong> {patientDetails.bmi ?? "-"}
|
<div className="grid grid-cols-2 gap-4">
|
||||||
</p>
|
<div>
|
||||||
<p>
|
<p className="font-semibold">Rua</p>
|
||||||
<strong>Endereço:</strong> {patientDetails.street ?? "-"}
|
<p>{`${patientDetails.street}, ${patientDetails.number}`}</p>
|
||||||
</p>
|
</div>
|
||||||
<p>
|
<div>
|
||||||
<strong>Bairro:</strong>{" "}
|
<p className="font-semibold">Complemento</p>
|
||||||
{patientDetails.neighborhood ?? "-"}
|
<p>{patientDetails.complement}</p>
|
||||||
</p>
|
</div>
|
||||||
<p>
|
<div>
|
||||||
<strong>Cidade:</strong> {patientDetails.city ?? "-"}
|
<p className="font-semibold">Bairro</p>
|
||||||
</p>
|
<p>{patientDetails.neighborhood}</p>
|
||||||
<p>
|
</div>
|
||||||
<strong>Estado:</strong> {patientDetails.state ?? "-"}
|
<div>
|
||||||
</p>
|
<p className="font-semibold">Cidade</p>
|
||||||
<p>
|
<p>{patientDetails.cidade}</p>
|
||||||
<strong>CEP:</strong> {patientDetails.cep ?? "-"}
|
</div>
|
||||||
</p>
|
<div>
|
||||||
<p>
|
<p className="font-semibold">Estado</p>
|
||||||
<strong>Criado em:</strong>{" "}
|
<p>{patientDetails.estado}</p>
|
||||||
{patientDetails.created_at ?? "-"}
|
</div>
|
||||||
</p>
|
<div>
|
||||||
<p>
|
<p className="font-semibold">CEP</p>
|
||||||
<strong>Atualizado em:</strong>{" "}
|
<p>{patientDetails.cep}</p>
|
||||||
{patientDetails.updated_at ?? "-"}
|
</div>
|
||||||
</p>
|
</div>
|
||||||
<p>
|
</div>
|
||||||
<strong>Id:</strong> {patientDetails.id ?? "-"}
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</AlertDialogDescription>
|
</AlertDialogDescription>
|
||||||
|
|||||||
@ -1,3 +1,5 @@
|
|||||||
|
// /app/manager/usuario/novo/page.tsx
|
||||||
|
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
@ -9,7 +11,8 @@ import { Label } from "@/components/ui/label";
|
|||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
import { Save, Loader2, Pause } from "lucide-react";
|
import { Save, Loader2, Pause } from "lucide-react";
|
||||||
import ManagerLayout from "@/components/manager-layout";
|
import ManagerLayout from "@/components/manager-layout";
|
||||||
import { usersService } from "services/usersApi.mjs";
|
import { usersService } from "@/services/usersApi.mjs";
|
||||||
|
import { doctorsService } from "@/services/doctorsApi.mjs"; // Importação adicionada
|
||||||
import { login } from "services/api.mjs";
|
import { login } from "services/api.mjs";
|
||||||
|
|
||||||
interface UserFormData {
|
interface UserFormData {
|
||||||
@ -20,6 +23,10 @@ interface UserFormData {
|
|||||||
senha: string;
|
senha: string;
|
||||||
confirmarSenha: string;
|
confirmarSenha: string;
|
||||||
cpf: string;
|
cpf: string;
|
||||||
|
// Novos campos para Médico
|
||||||
|
crm: string;
|
||||||
|
crm_uf: string;
|
||||||
|
specialty: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const defaultFormData: UserFormData = {
|
const defaultFormData: UserFormData = {
|
||||||
@ -30,6 +37,10 @@ const defaultFormData: UserFormData = {
|
|||||||
senha: "",
|
senha: "",
|
||||||
confirmarSenha: "",
|
confirmarSenha: "",
|
||||||
cpf: "",
|
cpf: "",
|
||||||
|
// Valores iniciais para campos de Médico
|
||||||
|
crm: "",
|
||||||
|
crm_uf: "",
|
||||||
|
specialty: "",
|
||||||
};
|
};
|
||||||
|
|
||||||
const cleanNumber = (value: string): string => value.replace(/\D/g, "");
|
const cleanNumber = (value: string): string => value.replace(/\D/g, "");
|
||||||
@ -47,7 +58,13 @@ export default function NovoUsuarioPage() {
|
|||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
const handleInputChange = (key: keyof UserFormData, value: string) => {
|
const handleInputChange = (key: keyof UserFormData, value: string) => {
|
||||||
const updatedValue = key === "telefone" ? formatPhone(value) : value;
|
let updatedValue = value;
|
||||||
|
if (key === "telefone") {
|
||||||
|
updatedValue = formatPhone(value);
|
||||||
|
} else if (key === "crm_uf") {
|
||||||
|
// Converte UF para maiúsculas
|
||||||
|
updatedValue = value.toUpperCase();
|
||||||
|
}
|
||||||
setFormData((prev) => ({ ...prev, [key]: updatedValue }));
|
setFormData((prev) => ({ ...prev, [key]: updatedValue }));
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -65,22 +82,56 @@ export default function NovoUsuarioPage() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Validação adicional para Médico
|
||||||
|
if (formData.papel === "medico") {
|
||||||
|
if (!formData.crm || !formData.crm_uf) {
|
||||||
|
setError("Para a função 'Médico', o CRM e a UF do CRM são obrigatórios.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
setIsSaving(true);
|
setIsSaving(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const payload = {
|
if (formData.papel === "medico") {
|
||||||
full_name: formData.nomeCompleto,
|
// Lógica para criação de Médico
|
||||||
|
const doctorPayload = {
|
||||||
email: formData.email.trim().toLowerCase(),
|
email: formData.email.trim().toLowerCase(),
|
||||||
phone: formData.telefone || null,
|
full_name: formData.nomeCompleto,
|
||||||
role: formData.papel,
|
|
||||||
password: formData.senha,
|
|
||||||
cpf: formData.cpf,
|
cpf: formData.cpf,
|
||||||
|
crm: formData.crm,
|
||||||
|
crm_uf: formData.crm_uf,
|
||||||
|
specialty: formData.specialty || null,
|
||||||
|
phone_mobile: formData.telefone || null, // Usando phone_mobile conforme o schema
|
||||||
};
|
};
|
||||||
|
|
||||||
console.log("📤 Enviando payload:");
|
console.log("📤 Enviando payload para Médico:");
|
||||||
console.log(payload);
|
console.log(doctorPayload);
|
||||||
|
|
||||||
await usersService.create_user(payload);
|
// Chamada ao endpoint específico para criação de médico
|
||||||
|
await doctorsService.create(doctorPayload);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
// Lógica para criação de Outras Roles
|
||||||
|
const isPatient = formData.papel === "paciente";
|
||||||
|
|
||||||
|
const userPayload = {
|
||||||
|
email: formData.email.trim().toLowerCase(),
|
||||||
|
password: formData.senha,
|
||||||
|
full_name: formData.nomeCompleto,
|
||||||
|
phone: formData.telefone || null,
|
||||||
|
role: formData.papel,
|
||||||
|
cpf: formData.cpf,
|
||||||
|
create_patient_record: isPatient, // true se a role for 'paciente'
|
||||||
|
phone_mobile: isPatient ? formData.telefone || null : undefined, // Enviar phone_mobile se for paciente
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log("📤 Enviando payload para Usuário Comum:");
|
||||||
|
console.log(userPayload);
|
||||||
|
|
||||||
|
// Chamada ao endpoint padrão para criação de usuário
|
||||||
|
await usersService.create_user(userPayload);
|
||||||
|
}
|
||||||
|
|
||||||
router.push("/manager/usuario");
|
router.push("/manager/usuario");
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
@ -91,6 +142,8 @@ export default function NovoUsuarioPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const isMedico = formData.papel === "medico";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ManagerLayout>
|
<ManagerLayout>
|
||||||
<div className="w-full h-full p-4 md:p-8 flex justify-center items-start">
|
<div className="w-full h-full p-4 md:p-8 flex justify-center items-start">
|
||||||
@ -140,6 +193,27 @@ export default function NovoUsuarioPage() {
|
|||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Campos Condicionais para Médico */}
|
||||||
|
{isMedico && (
|
||||||
|
<>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="crm">CRM *</Label>
|
||||||
|
<Input id="crm" value={formData.crm} onChange={(e) => handleInputChange("crm", e.target.value)} placeholder="Número do CRM" required />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="crm_uf">UF do CRM *</Label>
|
||||||
|
<Input id="crm_uf" value={formData.crm_uf} onChange={(e) => handleInputChange("crm_uf", e.target.value)} placeholder="Ex: SP" maxLength={2} required />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2 md:col-span-2">
|
||||||
|
<Label htmlFor="specialty">Especialidade (opcional)</Label>
|
||||||
|
<Input id="specialty" value={formData.specialty} onChange={(e) => handleInputChange("specialty", e.target.value)} placeholder="Ex: Cardiologia" />
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{/* Fim dos Campos Condicionais */}
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="senha">Senha *</Label>
|
<Label htmlFor="senha">Senha *</Label>
|
||||||
<Input id="senha" type="password" value={formData.senha} onChange={(e) => handleInputChange("senha", e.target.value)} placeholder="Mínimo 8 caracteres" minLength={8} required />
|
<Input id="senha" type="password" value={formData.senha} onChange={(e) => handleInputChange("senha", e.target.value)} placeholder="Mínimo 8 caracteres" minLength={8} required />
|
||||||
|
|||||||
@ -46,20 +46,34 @@ export default function UsersPage() {
|
|||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
||||||
const [userDetails, setUserDetails] = useState<UserInfoResponse | null>(null);
|
const [userDetails, setUserDetails] = useState<UserInfoResponse | null>(
|
||||||
const [selectedRole, setSelectedRole] = useState<string>("");
|
null
|
||||||
|
);
|
||||||
|
// Ajuste 1: Definir 'all' como valor inicial para garantir que todos os usuários sejam exibidos por padrão.
|
||||||
|
const [selectedRole, setSelectedRole] = useState<string>("all");
|
||||||
|
|
||||||
|
// --- Lógica de Paginação INÍCIO ---
|
||||||
|
const [itemsPerPage, setItemsPerPage] = useState(10);
|
||||||
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
|
|
||||||
|
// Lógica 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 () => {
|
const fetchUsers = useCallback(async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
// 1) pega roles
|
|
||||||
const rolesData: any[] = await usersService.list_roles();
|
const rolesData: any[] = await usersService.list_roles();
|
||||||
// Garante que rolesData é array
|
|
||||||
const rolesArray = Array.isArray(rolesData) ? rolesData : [];
|
const rolesArray = Array.isArray(rolesData) ? rolesData : [];
|
||||||
|
|
||||||
// 2) pega todos os profiles de uma vez (para evitar muitos requests)
|
const profilesData: any[] = await api.get(
|
||||||
const profilesData: any[] = await api.get(`/rest/v1/profiles?select=id,full_name,email,phone`);
|
`/rest/v1/profiles?select=id,full_name,email,phone`
|
||||||
|
);
|
||||||
|
|
||||||
const profilesById = new Map<string, any>();
|
const profilesById = new Map<string, any>();
|
||||||
if (Array.isArray(profilesData)) {
|
if (Array.isArray(profilesData)) {
|
||||||
for (const p of profilesData) {
|
for (const p of profilesData) {
|
||||||
@ -67,7 +81,6 @@ export default function UsersPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3) mapear roles -> flat users, usando ID específico de cada item
|
|
||||||
const mapped: FlatUser[] = rolesArray.map((roleItem) => {
|
const mapped: FlatUser[] = rolesArray.map((roleItem) => {
|
||||||
const uid = roleItem.user_id;
|
const uid = roleItem.user_id;
|
||||||
const profile = profilesById.get(uid);
|
const profile = profilesById.get(uid);
|
||||||
@ -82,6 +95,7 @@ export default function UsersPage() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
setUsers(mapped);
|
setUsers(mapped);
|
||||||
|
setCurrentPage(1); // Resetar a página após carregar
|
||||||
console.log("[fetchUsers] mapped count:", mapped.length);
|
console.log("[fetchUsers] mapped count:", mapped.length);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
console.error("Erro ao buscar usuários:", err);
|
console.error("Erro ao buscar usuários:", err);
|
||||||
@ -95,7 +109,7 @@ export default function UsersPage() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const init = async () => {
|
const init = async () => {
|
||||||
try {
|
try {
|
||||||
await login(); // garante token
|
await login();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.warn("login falhou no init:", e);
|
console.warn("login falhou no init:", e);
|
||||||
}
|
}
|
||||||
@ -115,7 +129,6 @@ export default function UsersPage() {
|
|||||||
setUserDetails(data);
|
setUserDetails(data);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
console.error("Erro ao carregar detalhes:", err);
|
console.error("Erro ao carregar detalhes:", err);
|
||||||
// fallback com dados já conhecidos
|
|
||||||
setUserDetails({
|
setUserDetails({
|
||||||
user: { id: flatUser.user_id, email: flatUser.email },
|
user: { id: flatUser.user_id, email: flatUser.email },
|
||||||
profile: { full_name: flatUser.full_name, phone: flatUser.phone },
|
profile: { full_name: flatUser.full_name, phone: flatUser.phone },
|
||||||
@ -125,27 +138,91 @@ export default function UsersPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 1. Filtragem
|
||||||
const filteredUsers =
|
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 (
|
return (
|
||||||
<ManagerLayout>
|
<ManagerLayout>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6 px-2 sm:px-4 md:px-8">
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-gray-900">Usuários</h1>
|
<h1 className="text-2xl font-bold text-gray-900">Usuários</h1>
|
||||||
<p className="text-sm text-gray-500">Gerencie usuários.</p>
|
<p className="text-sm text-gray-500">Gerencie usuários.</p>
|
||||||
</div>
|
</div>
|
||||||
<Link href="/manager/usuario/novo">
|
<Link href="/manager/usuario/novo" className="w-full sm:w-auto">
|
||||||
<Button className="bg-green-600 hover:bg-green-700">
|
<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
|
<Plus className="w-4 h-4 mr-2" /> Novo Usuário
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</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 */}
|
||||||
<Filter className="w-5 h-5 text-gray-400" />
|
<div className="flex flex-wrap items-center gap-3 bg-white p-4 rounded-lg border border-gray-200">
|
||||||
<Select onValueChange={setSelectedRole} value={selectedRole}>
|
|
||||||
|
{/* 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">
|
||||||
|
Filtrar por papel
|
||||||
|
</span>
|
||||||
|
<Select
|
||||||
|
onValueChange={(value) => {
|
||||||
|
setSelectedRole(value);
|
||||||
|
setCurrentPage(1); // Resetar para a primeira página ao mudar o filtro
|
||||||
|
}}
|
||||||
|
value={selectedRole}>
|
||||||
|
|
||||||
<SelectTrigger className="w-[180px]">
|
<SelectTrigger className="w-[180px]">
|
||||||
<SelectValue placeholder="Filtrar por papel" />
|
<SelectValue placeholder="Filtrar por papel" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
@ -160,7 +237,34 @@ export default function UsersPage() {
|
|||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-hidden">
|
{/* 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">
|
||||||
|
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>
|
||||||
|
{/* Fim do Filtro e Itens por Página */}
|
||||||
|
|
||||||
|
{/* Tabela */}
|
||||||
|
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-x-auto">
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="p-8 text-center text-gray-500">
|
<div className="p-8 text-center text-gray-500">
|
||||||
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
|
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
|
||||||
@ -170,12 +274,12 @@ export default function UsersPage() {
|
|||||||
<div className="p-8 text-center text-red-600">{error}</div>
|
<div className="p-8 text-center text-red-600">{error}</div>
|
||||||
) : filteredUsers.length === 0 ? (
|
) : filteredUsers.length === 0 ? (
|
||||||
<div className="p-8 text-center text-gray-500">
|
<div className="p-8 text-center text-gray-500">
|
||||||
Nenhum usuário encontrado.
|
Nenhum usuário encontrado com os filtros aplicados.
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="overflow-x-auto">
|
<>
|
||||||
<table className="min-w-full divide-y divide-gray-200">
|
<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>
|
<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">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">Nome</th>
|
||||||
@ -186,15 +290,34 @@ export default function UsersPage() {
|
|||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody className="bg-white divide-y divide-gray-200">
|
<tbody className="bg-white divide-y divide-gray-200">
|
||||||
{filteredUsers.map((u) => (
|
{/* Usando currentItems para a paginação */}
|
||||||
<tr key={u.id} className="hover:bg-gray-50">
|
{currentItems.map((u) => (
|
||||||
<td className="px-6 py-4 text-sm text-gray-500">{u.id}</td>
|
<tr
|
||||||
<td className="px-6 py-4 text-sm text-gray-900">{u.full_name}</td>
|
key={u.id}
|
||||||
<td className="px-6 py-4 text-sm text-gray-500">{u.email}</td>
|
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">{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-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">
|
<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" />
|
<Eye className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</td>
|
</td>
|
||||||
@ -202,14 +325,57 @@ export default function UsersPage() {
|
|||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
|
|
||||||
|
{/* 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>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{/* Fim da Paginação ATUALIZADA */}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Modal de Detalhes */}
|
||||||
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
||||||
<AlertDialogContent>
|
<AlertDialogContent>
|
||||||
<AlertDialogHeader>
|
<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>
|
<AlertDialogDescription>
|
||||||
{!userDetails ? (
|
{!userDetails ? (
|
||||||
<div className="p-4 text-center text-gray-500">
|
<div className="p-4 text-center text-gray-500">
|
||||||
@ -218,15 +384,34 @@ export default function UsersPage() {
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-3 pt-2 text-left text-gray-700">
|
<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>
|
<div>
|
||||||
<strong>Permissões:</strong>
|
<strong>ID:</strong> {userDetails.user.id}
|
||||||
<ul className="list-disc list-inside">
|
</div>
|
||||||
{Object.entries(userDetails.permissions || {}).map(([k,v]) => <li key={k}>{k}: {v ? "Sim" : "Não"}</li>)}
|
<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>
|
||||||
|
{/* Melhoria na visualização das permissões no modal */}
|
||||||
|
<div className="pt-2">
|
||||||
|
<strong className="block mb-1">Permissões:</strong>
|
||||||
|
<ul className="list-disc list-inside space-y-0.5 text-sm">
|
||||||
|
{Object.entries(
|
||||||
|
userDetails.permissions || {}
|
||||||
|
).map(([k, v]) => (
|
||||||
|
<li key={k}>
|
||||||
|
{k}: <span className={`font-semibold ${v ? 'text-green-600' : 'text-red-600'}`}>{v ? "Sim" : "Não"}</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -131,8 +131,12 @@ export default function PatientAppointmentsPage() {
|
|||||||
return (
|
return (
|
||||||
<PatientLayout>
|
<PatientLayout>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<h1 className="text-3xl font-bold text-gray-900">Minhas Consultas</h1>
|
<div className="flex justify-between items-center">
|
||||||
<p className="text-gray-600">Veja, reagende ou cancele suas consultas</p>
|
<div>
|
||||||
|
<h1 className="text-3xl font-bold text-foreground">Minhas Consultas</h1>
|
||||||
|
<p className="text-muted-foreground">Veja, reagende ou cancele suas consultas</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="grid gap-6">
|
<div className="grid gap-6">
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
|
|||||||
@ -1,676 +1,172 @@
|
|||||||
|
// Caminho: app/(manager)/usuario/novo/page.tsx
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import type React from "react";
|
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import Link from "next/link";
|
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
|
import Link from "next/link";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import { Textarea } from "@/components/ui/textarea";
|
// O Select foi removido pois não é mais necessário
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
import { Save, Loader2 } from "lucide-react";
|
||||||
import { Checkbox } from "@/components/ui/checkbox";
|
import ManagerLayout from "@/components/manager-layout";
|
||||||
import { Upload, Plus, X, ChevronDown } from "lucide-react";
|
// Os imports originais foram mantidos, como solicitado
|
||||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
|
import { usersService } from "services/usersApi.mjs";
|
||||||
import { useToast } from "@/hooks/use-toast";
|
import { doctorsService } from "services/doctorsApi.mjs";
|
||||||
import SecretaryLayout from "@/components/secretary-layout";
|
import { login } from "services/api.mjs";
|
||||||
import { patientsService } from "@/services/patientsApi.mjs";
|
|
||||||
|
|
||||||
export default function NovoPacientePage() {
|
// Interface simplificada para refletir apenas os campos necessários
|
||||||
const [anexosOpen, setAnexosOpen] = useState(false);
|
interface UserFormData {
|
||||||
const [anexos, setAnexos] = useState<string[]>([]);
|
email: string;
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
nomeCompleto: string;
|
||||||
|
telefone: string;
|
||||||
|
senha: string;
|
||||||
|
confirmarSenha: string;
|
||||||
|
cpf: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const defaultFormData: UserFormData = {
|
||||||
|
email: "",
|
||||||
|
nomeCompleto: "",
|
||||||
|
telefone: "",
|
||||||
|
senha: "",
|
||||||
|
confirmarSenha: "",
|
||||||
|
cpf: "",
|
||||||
|
};
|
||||||
|
|
||||||
|
const cleanNumber = (value: string): string => value.replace(/\D/g, "");
|
||||||
|
const formatPhone = (value: string): string => {
|
||||||
|
const cleaned = cleanNumber(value).substring(0, 11);
|
||||||
|
if (cleaned.length === 11) return cleaned.replace(/(\d{2})(\d{5})(\d{4})/, "($1) $2-$3");
|
||||||
|
if (cleaned.length === 10) return cleaned.replace(/(\d{2})(\d{4})(\d{4})/, "($1) $2-$3");
|
||||||
|
return cleaned;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function NovoUsuarioPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { toast } = useToast();
|
const [formData, setFormData] = useState<UserFormData>(defaultFormData);
|
||||||
|
const [isSaving, setIsSaving] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
const adicionarAnexo = () => {
|
const handleInputChange = (key: keyof UserFormData, value: string) => {
|
||||||
setAnexos([...anexos, `Documento ${anexos.length + 1}`]);
|
const updatedValue = key === "telefone" ? formatPhone(value) : value;
|
||||||
|
setFormData((prev) => ({ ...prev, [key]: updatedValue }));
|
||||||
};
|
};
|
||||||
|
|
||||||
const removerAnexo = (index: number) => {
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
setAnexos(anexos.filter((_, i) => i !== index));
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
const cleanNumber = (value: string): string => value.replace(/\D/g, '');
|
|
||||||
|
|
||||||
const formatCPF = (value: string): string => {
|
|
||||||
const cleaned = cleanNumber(value).substring(0, 11);
|
|
||||||
return cleaned.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4');
|
|
||||||
};
|
|
||||||
|
|
||||||
const formatCEP = (value: string): string => {
|
|
||||||
const cleaned = cleanNumber(value).substring(0, 8);
|
|
||||||
return cleaned.replace(/(\d{5})(\d{3})/, '$1-$2');
|
|
||||||
};
|
|
||||||
|
|
||||||
const formatPhoneMobile = (value: string): string => {
|
|
||||||
const cleaned = cleanNumber(value).substring(0, 11);
|
|
||||||
if (cleaned.length > 10) {
|
|
||||||
return cleaned.replace(/(\d{2})(\d{5})(\d{4})/, '+55 ($1) $2-$3');
|
|
||||||
}
|
|
||||||
return cleaned.replace(/(\d{2})(\d{4})(\d{4})/, '+55 ($1) $2-$3');
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (isLoading) return;
|
setError(null);
|
||||||
setIsLoading(true);
|
|
||||||
const form = e.currentTarget;
|
|
||||||
const formData = new FormData(form);
|
|
||||||
|
|
||||||
const apiPayload = {
|
// Validação simplificada
|
||||||
full_name: (formData.get("nome") as string) || "", // obrigatório
|
if (!formData.email || !formData.nomeCompleto || !formData.senha || !formData.confirmarSenha || !formData.cpf) {
|
||||||
social_name: (formData.get("nomeSocial") as string) || undefined,
|
setError("Por favor, preencha todos os campos obrigatórios.");
|
||||||
cpf: (formatCPF(formData.get("cpf") as string)) || "", // obrigatório
|
|
||||||
email: (formData.get("email") as string) || "", // obrigatório
|
|
||||||
phone_mobile: (formatPhoneMobile(formData.get("celular") as string)) || "", // obrigatório
|
|
||||||
birth_date: formData.get("dataNascimento") ? new Date(formData.get("dataNascimento") as string) : undefined,
|
|
||||||
sex: (formData.get("sexo") as string) || undefined,
|
|
||||||
blood_type: (formData.get("tipoSanguineo") as string) || undefined,
|
|
||||||
weight_kg: formData.get("peso") ? parseFloat(formData.get("peso") as string) : undefined,
|
|
||||||
height_m: formData.get("altura") ? parseFloat(formData.get("altura") as string) : undefined,
|
|
||||||
cep: (formatCEP(formData.get("cep") as string)) || undefined,
|
|
||||||
street: (formData.get("endereco") as string) || undefined,
|
|
||||||
number: (formData.get("numero") as string) || undefined,
|
|
||||||
complement: (formData.get("complemento") as string) || undefined,
|
|
||||||
neighborhood: (formData.get("bairro") as string) || undefined,
|
|
||||||
city: (formData.get("cidade") as string) || undefined,
|
|
||||||
state: (formData.get("estado") as string) || undefined,
|
|
||||||
};
|
|
||||||
|
|
||||||
console.log(apiPayload.email)
|
|
||||||
console.log(apiPayload.cep)
|
|
||||||
console.log(apiPayload.phone_mobile)
|
|
||||||
|
|
||||||
const errors: string[] = [];
|
|
||||||
const fullName = apiPayload.full_name?.trim() || "";
|
|
||||||
if (!fullName || fullName.length < 2 || fullName.length > 255) {
|
|
||||||
errors.push("Nome deve ter entre 2 e 255 caracteres.");
|
|
||||||
}
|
|
||||||
|
|
||||||
const cpf = apiPayload.cpf || "";
|
|
||||||
if (!/^\d{3}\.\d{3}\.\d{3}-\d{2}$/.test(cpf)) {
|
|
||||||
errors.push("CPF deve estar no formato XXX.XXX.XXX-XX.");
|
|
||||||
}
|
|
||||||
|
|
||||||
const sex = apiPayload.sex;
|
|
||||||
const allowedSex = ["Masculino", "Feminino", "outro"];
|
|
||||||
if (!sex || !allowedSex.includes(sex)) {
|
|
||||||
errors.push("Sexo é obrigatório e deve ser masculino, feminino ou outro.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!apiPayload.birth_date) {
|
|
||||||
errors.push("Data de nascimento é obrigatória.");
|
|
||||||
}
|
|
||||||
|
|
||||||
const phoneMobile = apiPayload.phone_mobile || "";
|
|
||||||
if (phoneMobile && !/^\+55 \(\d{2}\) \d{4,5}-\d{4}$/.test(phoneMobile)) {
|
|
||||||
errors.push("Celular deve estar no formato +55 (XX) XXXXX-XXXX.");
|
|
||||||
}
|
|
||||||
|
|
||||||
const cep = apiPayload.cep || "";
|
|
||||||
if (cep && !/^\d{5}-\d{3}$/.test(cep)) {
|
|
||||||
errors.push("CEP deve estar no formato XXXXX-XXX.");
|
|
||||||
}
|
|
||||||
|
|
||||||
const state = apiPayload.state || "";
|
|
||||||
if (state && state.length !== 2) {
|
|
||||||
errors.push("Estado (UF) deve ter 2 caracteres.");
|
|
||||||
}
|
|
||||||
if (errors.length) {
|
|
||||||
toast({ title: "Corrija os campos", description: errors[0] });
|
|
||||||
console.log("campos errados")
|
|
||||||
setIsLoading(false);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
if (formData.senha !== formData.confirmarSenha) {
|
||||||
const res = await patientsService.create(apiPayload);
|
setError("A Senha e a Confirmação de Senha não coincidem.");
|
||||||
console.log(res)
|
return;
|
||||||
|
|
||||||
let message = "Paciente cadastrado com sucesso";
|
|
||||||
try {
|
|
||||||
if (!res[0].id) {
|
|
||||||
throw new Error(`${res.error} ${res.message}`|| "A API retornou erro");
|
|
||||||
} else {
|
|
||||||
console.log(message)
|
|
||||||
}
|
}
|
||||||
} catch {}
|
|
||||||
|
|
||||||
toast({
|
setIsSaving(true);
|
||||||
title: "Sucesso",
|
|
||||||
description: message,
|
try {
|
||||||
});
|
// Payload agora é fixo para a role 'paciente'
|
||||||
router.push("/secretary/pacientes");
|
const payload = {
|
||||||
} catch (err: any) {
|
full_name: formData.nomeCompleto,
|
||||||
toast({
|
email: formData.email.trim().toLowerCase(),
|
||||||
title: "Erro",
|
phone: formData.telefone || null,
|
||||||
description: err?.message || "Não foi possível cadastrar o paciente",
|
role: "paciente", // Role fixada
|
||||||
});
|
password: formData.senha,
|
||||||
|
cpf: formData.cpf,
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log("📤 Enviando payload para criação de Usuário (Paciente):");
|
||||||
|
console.log(payload);
|
||||||
|
|
||||||
|
// A chamada original à API foi mantida
|
||||||
|
await usersService.create_user(payload);
|
||||||
|
|
||||||
|
router.push("/manager/usuario");
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Erro ao criar usuário:", e);
|
||||||
|
setError(e?.message || "Não foi possível criar o usuário. Verifique os dados e tente novamente.");
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoading(false);
|
setIsSaving(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SecretaryLayout>
|
<ManagerLayout>
|
||||||
<div className="space-y-6">
|
<div className="w-full h-full p-4 md:p-8 flex justify-center items-start">
|
||||||
<div className="flex items-center justify-between">
|
<div className="w-full max-w-screen-lg space-y-8">
|
||||||
|
<div className="flex items-center justify-between border-b pb-4">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-gray-900">Novo Paciente</h1>
|
<h1 className="text-3xl font-extrabold text-gray-900">Novo Usuário</h1>
|
||||||
<p className="text-gray-600">Cadastre um novo paciente no sistema</p>
|
<p className="text-md text-gray-500">Preencha os dados para cadastrar um novo usuário no sistema.</p>
|
||||||
|
</div>
|
||||||
|
<Link href="/manager/usuario">
|
||||||
|
<Button variant="outline">Cancelar</Button>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-6 bg-white p-6 md:p-10 border rounded-xl shadow-lg">
|
||||||
|
{error && (
|
||||||
|
<div className="p-4 bg-red-50 text-red-700 rounded-lg border border-red-300">
|
||||||
|
<p className="font-semibold">Erro no Cadastro:</p>
|
||||||
|
<p className="text-sm break-words">{error}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||||
|
<div className="space-y-2 md:col-span-2">
|
||||||
|
<Label htmlFor="nomeCompleto">Nome Completo *</Label>
|
||||||
|
<Input id="nomeCompleto" value={formData.nomeCompleto} onChange={(e) => handleInputChange("nomeCompleto", e.target.value)} placeholder="Nome e Sobrenome" required />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="email">E-mail *</Label>
|
||||||
|
<Input id="email" type="email" value={formData.email} onChange={(e) => handleInputChange("email", e.target.value)} placeholder="exemplo@dominio.com" required />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* O seletor de Papel (Função) foi removido */}
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="senha">Senha *</Label>
|
||||||
|
<Input id="senha" type="password" value={formData.senha} onChange={(e) => handleInputChange("senha", e.target.value)} placeholder="Mínimo 8 caracteres" minLength={8} required />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="confirmarSenha">Confirmar Senha *</Label>
|
||||||
|
<Input id="confirmarSenha" type="password" value={formData.confirmarSenha} onChange={(e) => handleInputChange("confirmarSenha", e.target.value)} placeholder="Repita a senha" required />
|
||||||
|
{formData.senha && formData.confirmarSenha && formData.senha !== formData.confirmarSenha && <p className="text-xs text-red-500">As senhas não coincidem.</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="telefone">Telefone</Label>
|
||||||
|
<Input id="telefone" value={formData.telefone} onChange={(e) => handleInputChange("telefone", e.target.value)} placeholder="(00) 00000-0000" maxLength={15} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<form className="space-y-6" onSubmit={handleSubmit}>
|
<div className="space-y-2">
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
<Label htmlFor="cpf">Cpf *</Label>
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Dados Pessoais</h2>
|
<Input id="cpf" value={formData.cpf} onChange={(e) => handleInputChange("cpf", e.target.value)} placeholder="xxx.xxx.xxx-xx" required />
|
||||||
|
|
||||||
<div className="space-y-6">
|
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
<div className="w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center">
|
|
||||||
<Upload className="w-8 h-8 text-gray-400" />
|
|
||||||
</div>
|
|
||||||
<Button variant="outline" type="button" size="sm">
|
|
||||||
<Upload className="w-4 h-4 mr-2" />
|
|
||||||
Carregar Foto
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
<div className="flex justify-end gap-4 pt-6 border-t mt-6">
|
||||||
<div>
|
<Link href="/manager/usuario">
|
||||||
<Label htmlFor="nome" className="text-sm font-medium text-gray-700">
|
<Button type="button" variant="outline" disabled={isSaving}>
|
||||||
Nome *
|
|
||||||
</Label>
|
|
||||||
<Input id="nome" name="nome" placeholder="Nome completo" required className="mt-1" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="nomeSocial" className="text-sm font-medium text-gray-700">
|
|
||||||
Nome Social
|
|
||||||
</Label>
|
|
||||||
<Input id="nomeSocial" name="nomeSocial" placeholder="Nome social ou apelido" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-3 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="cpf" className="text-sm font-medium text-gray-700">
|
|
||||||
CPF *
|
|
||||||
</Label>
|
|
||||||
<Input id="cpf" name="cpf" placeholder="000.000.000-00" required className="mt-1" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="rg" className="text-sm font-medium text-gray-700">
|
|
||||||
RG
|
|
||||||
</Label>
|
|
||||||
<Input id="rg" name="rg" placeholder="00.000.000-0" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="outrosDocumentos" className="text-sm font-medium text-gray-700">
|
|
||||||
Outros Documentos
|
|
||||||
</Label>
|
|
||||||
<Select name="outrosDocumentos">
|
|
||||||
<SelectTrigger className="mt-1">
|
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="cnh">CNH</SelectItem>
|
|
||||||
<SelectItem value="passaporte">Passaporte</SelectItem>
|
|
||||||
<SelectItem value="carteira-trabalho">Carteira de Trabalho</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-3 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label className="text-sm font-medium text-gray-700">Sexo *</Label>
|
|
||||||
<div className="flex gap-4 mt-2">
|
|
||||||
<label className="flex items-center gap-2">
|
|
||||||
<input type="radio" name="sexo" value="Masculino" className="text-blue-600" required/>
|
|
||||||
<span className="text-sm">Masculino</span>
|
|
||||||
</label>
|
|
||||||
<label className="flex items-center gap-2">
|
|
||||||
<input type="radio" name="sexo" value="Feminino" className="text-blue-600" required/>
|
|
||||||
<span className="text-sm">Feminino</span>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="dataNascimento" className="text-sm font-medium text-gray-700">
|
|
||||||
Data de Nascimento *
|
|
||||||
</Label>
|
|
||||||
<Input id="dataNascimento" name="dataNascimento" type="date" className="mt-1" required/>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="estadoCivil" className="text-sm font-medium text-gray-700">
|
|
||||||
Estado Civil
|
|
||||||
</Label>
|
|
||||||
<Select name="estadoCivil">
|
|
||||||
<SelectTrigger className="mt-1">
|
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="solteiro">Solteiro(a)</SelectItem>
|
|
||||||
<SelectItem value="casado">Casado(a)</SelectItem>
|
|
||||||
<SelectItem value="divorciado">Divorciado(a)</SelectItem>
|
|
||||||
<SelectItem value="viuvo">Viúvo(a)</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="etnia" className="text-sm font-medium text-gray-700">
|
|
||||||
Etnia
|
|
||||||
</Label>
|
|
||||||
<Select name="etnia">
|
|
||||||
<SelectTrigger className="mt-1">
|
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="branca">Branca</SelectItem>
|
|
||||||
<SelectItem value="preta">Preta</SelectItem>
|
|
||||||
<SelectItem value="parda">Parda</SelectItem>
|
|
||||||
<SelectItem value="amarela">Amarela</SelectItem>
|
|
||||||
<SelectItem value="indigena">Indígena</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="raca" className="text-sm font-medium text-gray-700">
|
|
||||||
Raça
|
|
||||||
</Label>
|
|
||||||
<Select name="raca">
|
|
||||||
<SelectTrigger className="mt-1">
|
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="branca">Branca</SelectItem>
|
|
||||||
<SelectItem value="preta">Preta</SelectItem>
|
|
||||||
<SelectItem value="parda">Parda</SelectItem>
|
|
||||||
<SelectItem value="amarela">Amarela</SelectItem>
|
|
||||||
<SelectItem value="indigena">Indígena</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="naturalidade" className="text-sm font-medium text-gray-700">
|
|
||||||
Naturalidade
|
|
||||||
</Label>
|
|
||||||
<Select name="naturalidade">
|
|
||||||
<SelectTrigger className="mt-1">
|
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="aracaju">Aracaju</SelectItem>
|
|
||||||
<SelectItem value="salvador">Salvador</SelectItem>
|
|
||||||
<SelectItem value="recife">Recife</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="nacionalidade" className="text-sm font-medium text-gray-700">
|
|
||||||
Nacionalidade
|
|
||||||
</Label>
|
|
||||||
<Select name="nacionalidade">
|
|
||||||
<SelectTrigger className="mt-1">
|
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="brasileira">Brasileira</SelectItem>
|
|
||||||
<SelectItem value="estrangeira">Estrangeira</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="profissao" className="text-sm font-medium text-gray-700">
|
|
||||||
Profissão
|
|
||||||
</Label>
|
|
||||||
<Input id="profissao" name="profissao" placeholder="Profissão" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="nomeMae" className="text-sm font-medium text-gray-700">
|
|
||||||
Nome da Mãe
|
|
||||||
</Label>
|
|
||||||
<Input id="nomeMae" name="nomeMae" placeholder="Nome da mãe" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="profissaoMae" className="text-sm font-medium text-gray-700">
|
|
||||||
Profissão da Mãe
|
|
||||||
</Label>
|
|
||||||
<Input id="profissaoMae" name="profissaoMae" placeholder="Profissão da mãe" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="nomePai" className="text-sm font-medium text-gray-700">
|
|
||||||
Nome do Pai
|
|
||||||
</Label>
|
|
||||||
<Input id="nomePai" name="nomePai" placeholder="Nome do pai" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="profissaoPai" className="text-sm font-medium text-gray-700">
|
|
||||||
Profissão do Pai
|
|
||||||
</Label>
|
|
||||||
<Input id="profissaoPai" name="profissaoPai" placeholder="Profissão do pai" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="nomeResponsavel" className="text-sm font-medium text-gray-700">
|
|
||||||
Nome do Responsável
|
|
||||||
</Label>
|
|
||||||
<Input id="nomeResponsavel" name="nomeResponsavel" placeholder="Nome do responsável" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="cpfResponsavel" className="text-sm font-medium text-gray-700">
|
|
||||||
CPF do Responsável
|
|
||||||
</Label>
|
|
||||||
<Input id="cpfResponsavel" name="cpfResponsavel" placeholder="000.000.000-00" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="nomeEsposo" className="text-sm font-medium text-gray-700">
|
|
||||||
Nome do Esposo(a)
|
|
||||||
</Label>
|
|
||||||
<Input id="nomeEsposo" name="nomeEsposo" placeholder="Nome do esposo(a)" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center space-x-2">
|
|
||||||
<Checkbox id="rnGuia" name="rnGuia" />
|
|
||||||
<Label htmlFor="rnGuia" className="text-sm text-gray-700">
|
|
||||||
RN na Guia do convênio
|
|
||||||
</Label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="codigoLegado" className="text-sm font-medium text-gray-700">
|
|
||||||
Código Legado
|
|
||||||
</Label>
|
|
||||||
<Input id="codigoLegado" name="codigoLegado" placeholder="Código do sistema anterior" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="observacoes" className="text-sm font-medium text-gray-700">
|
|
||||||
Observações
|
|
||||||
</Label>
|
|
||||||
<Textarea id="observacoes" name="observacoes" placeholder="Observações gerais sobre o paciente" className="min-h-[100px] mt-1" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Collapsible open={anexosOpen} onOpenChange={setAnexosOpen}>
|
|
||||||
<CollapsibleTrigger asChild>
|
|
||||||
<Button variant="ghost" type="button" className="w-full justify-between p-0 h-auto text-left">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<div className="w-4 h-4 bg-gray-400 rounded-sm flex items-center justify-center">
|
|
||||||
<span className="text-white text-xs">📎</span>
|
|
||||||
</div>
|
|
||||||
<span className="text-sm font-medium text-gray-700">Anexos do paciente</span>
|
|
||||||
</div>
|
|
||||||
<ChevronDown className={`w-4 h-4 transition-transform ${anexosOpen ? "rotate-180" : ""}`} />
|
|
||||||
</Button>
|
|
||||||
</CollapsibleTrigger>
|
|
||||||
<CollapsibleContent className="space-y-4 mt-4">
|
|
||||||
{anexos.map((anexo, index) => (
|
|
||||||
<div key={index} className="flex items-center justify-between p-3 border rounded-lg bg-gray-50">
|
|
||||||
<span className="text-sm">{anexo}</span>
|
|
||||||
<Button variant="ghost" size="sm" onClick={() => removerAnexo(index)} type="button">
|
|
||||||
<X className="w-4 h-4" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
<Button variant="outline" onClick={adicionarAnexo} type="button" size="sm">
|
|
||||||
<Plus className="w-4 h-4 mr-2" />
|
|
||||||
Adicionar Anexo
|
|
||||||
</Button>
|
|
||||||
</CollapsibleContent>
|
|
||||||
</Collapsible>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Contato</h2>
|
|
||||||
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="grid md:grid-cols-3 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="email" className="text-sm font-medium text-gray-700">
|
|
||||||
E-mail *
|
|
||||||
</Label>
|
|
||||||
<Input id="email" name="email" type="email" placeholder="email@exemplo.com" className="mt-1" required/>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="celular" className="text-sm font-medium text-gray-700">
|
|
||||||
Celular *
|
|
||||||
</Label>
|
|
||||||
<div className="flex mt-1">
|
|
||||||
<Select>
|
|
||||||
<SelectTrigger className="w-20 rounded-r-none">
|
|
||||||
<SelectValue placeholder="+55" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="+55">+55</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
<Input id="celular" name="celular" placeholder="(XX) XXXXX-XXXX" className="rounded-l-none" required/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="telefone1" className="text-sm font-medium text-gray-700">
|
|
||||||
Telefone 1
|
|
||||||
</Label>
|
|
||||||
<Input id="telefone1" name="telefone1" placeholder="(XX) XXXX-XXXX" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="telefone2" className="text-sm font-medium text-gray-700">
|
|
||||||
Telefone 2
|
|
||||||
</Label>
|
|
||||||
<Input id="telefone2" name="telefone2" placeholder="(XX) XXXX-XXXX" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Endereço</h2>
|
|
||||||
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="cep" className="text-sm font-medium text-gray-700">
|
|
||||||
CEP
|
|
||||||
</Label>
|
|
||||||
<Input id="cep" name="cep" placeholder="00000-000" className="mt-1 max-w-xs" />
|
|
||||||
</div>
|
|
||||||
<div className="grid md:grid-cols-3 gap-4">
|
|
||||||
<div className="md:col-span-2">
|
|
||||||
<Label htmlFor="endereco" className="text-sm font-medium text-gray-700">
|
|
||||||
Endereço
|
|
||||||
</Label>
|
|
||||||
<Input id="endereco" name="endereco" placeholder="Rua, Avenida..." className="mt-1" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="numero" className="text-sm font-medium text-gray-700">
|
|
||||||
Número
|
|
||||||
</Label>
|
|
||||||
<Input id="numero" name="numero" placeholder="123" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="complemento" className="text-sm font-medium text-gray-700">
|
|
||||||
Complemento
|
|
||||||
</Label>
|
|
||||||
<Input id="complemento" name="complemento" placeholder="Apto, Bloco..." className="mt-1" />
|
|
||||||
</div>
|
|
||||||
<div className="grid md:grid-cols-3 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="bairro" className="text-sm font-medium text-gray-700">
|
|
||||||
Bairro
|
|
||||||
</Label>
|
|
||||||
<Input id="bairro" name="bairro" placeholder="Bairro" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="cidade" className="text-sm font-medium text-gray-700">
|
|
||||||
Cidade
|
|
||||||
</Label>
|
|
||||||
<Input id="cidade" name="cidade" placeholder="Cidade" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="estado" className="text-sm font-medium text-gray-700">
|
|
||||||
Estado
|
|
||||||
</Label>
|
|
||||||
<Select name="estado">
|
|
||||||
<SelectTrigger className="mt-1">
|
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="SE">Sergipe</SelectItem>
|
|
||||||
<SelectItem value="BA">Bahia</SelectItem>
|
|
||||||
<SelectItem value="AL">Alagoas</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Informações Médicas</h2>
|
|
||||||
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="grid md:grid-cols-4 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="tipoSanguineo" className="text-sm font-medium text-gray-700">
|
|
||||||
Tipo Sanguíneo
|
|
||||||
</Label>
|
|
||||||
<Select name="tipoSanguineo">
|
|
||||||
<SelectTrigger className="mt-1">
|
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="A+">A+</SelectItem>
|
|
||||||
<SelectItem value="A-">A-</SelectItem>
|
|
||||||
<SelectItem value="B+">B+</SelectItem>
|
|
||||||
<SelectItem value="B-">B-</SelectItem>
|
|
||||||
<SelectItem value="AB+">AB+</SelectItem>
|
|
||||||
<SelectItem value="AB-">AB-</SelectItem>
|
|
||||||
<SelectItem value="O+">O+</SelectItem>
|
|
||||||
<SelectItem value="O-">O-</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="peso" className="text-sm font-medium text-gray-700">
|
|
||||||
Peso
|
|
||||||
</Label>
|
|
||||||
<div className="relative mt-1">
|
|
||||||
<Input id="peso" name="peso" type="number" placeholder="70" />
|
|
||||||
<span className="absolute right-3 top-1/2 transform -translate-y-1/2 text-sm text-gray-500">kg</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="altura" className="text-sm font-medium text-gray-700">
|
|
||||||
Altura
|
|
||||||
</Label>
|
|
||||||
<div className="relative mt-1">
|
|
||||||
<Input id="altura" name="altura" type="number" step="0.01" placeholder="1.70" />
|
|
||||||
<span className="absolute right-3 top-1/2 transform -translate-y-1/2 text-sm text-gray-500">m</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="imc" className="text-sm font-medium text-gray-700">
|
|
||||||
IMC
|
|
||||||
</Label>
|
|
||||||
<div className="relative mt-1">
|
|
||||||
<Input id="imc" name="imc" placeholder="Calculado automaticamente" disabled />
|
|
||||||
<span className="absolute right-3 top-1/2 transform -translate-y-1/2 text-sm text-gray-500">kg/m²</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="alergias" className="text-sm font-medium text-gray-700">
|
|
||||||
Alergias
|
|
||||||
</Label>
|
|
||||||
<Textarea id="alergias" name="alergias" placeholder="Ex: AAS, Dipirona, etc." className="min-h-[80px] mt-1" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
|
||||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Informações de Convênio</h2>
|
|
||||||
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="convenio" className="text-sm font-medium text-gray-700">
|
|
||||||
Convênio
|
|
||||||
</Label>
|
|
||||||
<Select name="convenio">
|
|
||||||
<SelectTrigger className="mt-1">
|
|
||||||
<SelectValue placeholder="Selecione" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="particular">Particular</SelectItem>
|
|
||||||
<SelectItem value="sus">SUS</SelectItem>
|
|
||||||
<SelectItem value="unimed">Unimed</SelectItem>
|
|
||||||
<SelectItem value="bradesco">Bradesco Saúde</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="plano" className="text-sm font-medium text-gray-700">
|
|
||||||
Plano
|
|
||||||
</Label>
|
|
||||||
<Input id="plano" name="plano" placeholder="Nome do plano" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="numeroMatricula" className="text-sm font-medium text-gray-700">
|
|
||||||
Nº de Matrícula
|
|
||||||
</Label>
|
|
||||||
<Input id="numeroMatricula" name="numeroMatricula" placeholder="Número da matrícula" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="validadeCarteira" className="text-sm font-medium text-gray-700">
|
|
||||||
Validade da Carteira
|
|
||||||
</Label>
|
|
||||||
<Input id="validadeCarteira" name="validadeCarteira" type="date" className="mt-1" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center space-x-2">
|
|
||||||
<Checkbox id="validadeIndeterminada" name="validadeIndeterminada" />
|
|
||||||
<Label htmlFor="validadeIndeterminada" className="text-sm text-gray-700">
|
|
||||||
Validade Indeterminada
|
|
||||||
</Label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex justify-end gap-4">
|
|
||||||
<Link href="/secretary/pacientes">
|
|
||||||
<Button variant="outline" type="button">
|
|
||||||
Cancelar
|
Cancelar
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
<Button type="submit" className="bg-blue-600 hover:bg-blue-700" disabled={isLoading}>
|
<Button type="submit" className="bg-green-600 hover:bg-green-700" disabled={isSaving}>
|
||||||
{isLoading ? "Salvando..." : "Salvar Paciente"}
|
{isSaving ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Save className="w-4 h-4 mr-2" />}
|
||||||
|
{isSaving ? "Salvando..." : "Salvar Usuário"}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</SecretaryLayout>
|
</div>
|
||||||
|
</ManagerLayout>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -1,132 +1,139 @@
|
|||||||
|
// app/secretary/pacientes/page.tsx
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, useEffect, useRef, useCallback } from "react";
|
import { useState, useEffect, useCallback } from "react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||||
DropdownMenu,
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
DropdownMenuContent,
|
import { Plus, Edit, Trash2, Eye, Calendar, Filter, Loader2 } from "lucide-react";
|
||||||
DropdownMenuItem,
|
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||||
DropdownMenuTrigger,
|
|
||||||
} from "@/components/ui/dropdown-menu";
|
|
||||||
import {
|
|
||||||
Select,
|
|
||||||
SelectContent,
|
|
||||||
SelectItem,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from "@/components/ui/select";
|
|
||||||
import { Plus, Edit, Trash2, Eye, Calendar, Filter } from "lucide-react";
|
|
||||||
import {
|
|
||||||
AlertDialog,
|
|
||||||
AlertDialogAction,
|
|
||||||
AlertDialogCancel,
|
|
||||||
AlertDialogContent,
|
|
||||||
AlertDialogDescription,
|
|
||||||
AlertDialogFooter,
|
|
||||||
AlertDialogHeader,
|
|
||||||
AlertDialogTitle,
|
|
||||||
} from "@/components/ui/alert-dialog";
|
|
||||||
import SecretaryLayout from "@/components/secretary-layout";
|
import SecretaryLayout from "@/components/secretary-layout";
|
||||||
import { patientsService } from "@/services/patientsApi.mjs";
|
import { patientsService } from "@/services/patientsApi.mjs";
|
||||||
|
|
||||||
|
// Defina o tamanho da página.
|
||||||
|
const PAGE_SIZE = 5;
|
||||||
|
|
||||||
export default function PacientesPage() {
|
export default function PacientesPage() {
|
||||||
|
// --- ESTADOS DE DADOS E GERAL ---
|
||||||
const [searchTerm, setSearchTerm] = useState("");
|
const [searchTerm, setSearchTerm] = useState("");
|
||||||
const [convenioFilter, setConvenioFilter] = useState("all");
|
const [convenioFilter, setConvenioFilter] = useState("all");
|
||||||
const [vipFilter, setVipFilter] = useState("all");
|
const [vipFilter, setVipFilter] = useState("all");
|
||||||
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);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// --- ESTADOS DE PAGINAÇÃO ---
|
||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
const [hasNext, setHasNext] = useState(true);
|
|
||||||
const [isFetching, setIsFetching] = useState(false);
|
// CÁLCULO DA PAGINAÇÃO
|
||||||
const observerRef = useRef<HTMLDivElement | null>(null);
|
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 [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||||
const [patientToDelete, setPatientToDelete] = useState<string | null>(null);
|
const [patientToDelete, setPatientToDelete] = useState<string | null>(null);
|
||||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
||||||
const [patientDetails, setPatientDetails] = useState<any | null>(null);
|
const [patientDetails, setPatientDetails] = useState<any | null>(null);
|
||||||
|
|
||||||
|
// --- FUNÇÕES DE LÓGICA ---
|
||||||
|
|
||||||
|
// 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) => {
|
const openDetailsDialog = async (patientId: string) => {
|
||||||
setDetailsDialogOpen(true);
|
setDetailsDialogOpen(true);
|
||||||
setPatientDetails(null);
|
setPatientDetails(null);
|
||||||
try {
|
try {
|
||||||
const res = await patientsService.getById(patientId);
|
const res = await patientsService.getById(patientId);
|
||||||
setPatientDetails(res[0]);
|
setPatientDetails(Array.isArray(res) ? res[0] : res); // Supondo que retorne um array com um item
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
setPatientDetails({ error: e?.message || "Erro ao buscar detalhes" });
|
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) => {
|
const handleDeletePatient = async (patientId: string) => {
|
||||||
// Remove from current list (client-side deletion)
|
|
||||||
try {
|
try {
|
||||||
const res = await patientsService.delete(patientId);
|
await patientsService.delete(patientId);
|
||||||
|
// Atualiza a lista completa para refletir a exclusão
|
||||||
if (res) {
|
setAllPatients((prev) => prev.filter((p) => String(p.id) !== String(patientId)));
|
||||||
alert(`${res.error} ${res.message}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
setPatients((prev) =>
|
|
||||||
prev.filter((p) => String(p.id) !== String(patientId))
|
|
||||||
);
|
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
setError(e?.message || "Erro ao deletar paciente");
|
alert(`Erro ao deletar paciente: ${e?.message || 'Erro desconhecido'}`);
|
||||||
}
|
}
|
||||||
setDeleteDialogOpen(false);
|
setDeleteDialogOpen(false);
|
||||||
setPatientToDelete(null);
|
setPatientToDelete(null);
|
||||||
@ -137,35 +144,18 @@ export default function PacientesPage() {
|
|||||||
setDeleteDialogOpen(true);
|
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 (
|
return (
|
||||||
<SecretaryLayout>
|
<SecretaryLayout>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6 px-2 sm:px-4 md:px-8">
|
||||||
|
{/* Header (Responsividade OK) */}
|
||||||
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-xl md:text-2xl font-bold text-foreground">
|
<h1 className="text-xl md:text-2xl font-bold text-foreground">Pacientes</h1>
|
||||||
Pacientes
|
<p className="text-muted-foreground text-sm md:text-base">Gerencie as informações de seus pacientes</p>
|
||||||
</h1>
|
|
||||||
<p className="text-muted-foreground text-sm md:text-base">
|
|
||||||
Gerencie as informações de seus pacientes
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<Link href="/secretary/pacientes/novo">
|
<Link href="/secretary/pacientes/novo" className="w-full md:w-auto">
|
||||||
<Button 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" />
|
<Plus className="w-4 h-4 mr-2" />
|
||||||
Adicionar
|
Adicionar
|
||||||
</Button>
|
</Button>
|
||||||
@ -173,30 +163,42 @@ export default function PacientesPage() {
|
|||||||
</div>
|
</div>
|
||||||
</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 (Responsividade APLICADA) */}
|
||||||
{/* Convênio */}
|
<div className="flex flex-wrap items-center gap-4 bg-card p-4 rounded-lg border border-border">
|
||||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
<Filter className="w-5 h-5 text-gray-400" />
|
||||||
<span className="text-sm font-medium text-foreground">
|
|
||||||
Convênio
|
{/* Busca - Ocupa 100% no mobile, depois cresce */}
|
||||||
</span>
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Buscar por nome ou telefone..."
|
||||||
|
value={searchTerm}
|
||||||
|
onChange={(e) => setSearchTerm(e.target.value)}
|
||||||
|
className="w-full sm:flex-grow sm:min-w-[150px] p-2 border rounded-md text-sm"
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Convênio - Ocupa metade da linha no mobile */}
|
||||||
|
<div className="flex items-center gap-2 w-[calc(50%-8px)] sm:w-auto sm:flex-grow sm:max-w-[200px]">
|
||||||
|
<span className="text-sm font-medium text-foreground whitespace-nowrap hidden md:block">Convênio</span>
|
||||||
<Select value={convenioFilter} onValueChange={setConvenioFilter}>
|
<Select value={convenioFilter} onValueChange={setConvenioFilter}>
|
||||||
<SelectTrigger className="w-full md:w-40">
|
<SelectTrigger className="w-full sm:w-40">
|
||||||
<SelectValue placeholder="Selecione o Convênio" />
|
<SelectValue placeholder="Convênio" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="all">Todos</SelectItem>
|
<SelectItem value="all">Todos</SelectItem>
|
||||||
<SelectItem value="Particular">Particular</SelectItem>
|
<SelectItem value="Particular">Particular</SelectItem>
|
||||||
<SelectItem value="SUS">SUS</SelectItem>
|
<SelectItem value="SUS">SUS</SelectItem>
|
||||||
<SelectItem value="Unimed">Unimed</SelectItem>
|
<SelectItem value="Unimed">Unimed</SelectItem>
|
||||||
|
{/* Adicione outros convênios conforme necessário */}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-2 w-full md:w-auto">
|
{/* VIP - Ocupa a outra metade da linha no mobile */}
|
||||||
<span className="text-sm font-medium text-foreground">VIP</span>
|
<div className="flex items-center gap-2 w-[calc(50%-8px)] 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}>
|
<Select value={vipFilter} onValueChange={setVipFilter}>
|
||||||
<SelectTrigger className="w-full md:w-32">
|
<SelectTrigger className="w-full sm:w-32">
|
||||||
<SelectValue placeholder="Selecione" />
|
<SelectValue placeholder="VIP" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="all">Todos</SelectItem>
|
<SelectItem value="all">Todos</SelectItem>
|
||||||
@ -205,129 +207,94 @@ export default function PacientesPage() {
|
|||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</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>
|
|
||||||
|
|
||||||
<Button variant="outline" className="ml-auto w-full md:w-auto">
|
{/* Aniversariantes - Vai para a linha de baixo no mobile, ocupando 100% */}
|
||||||
<Filter className="w-4 h-4 mr-2" />
|
<Button variant="outline" className="w-full md:w-auto md:ml-auto">
|
||||||
Filtro avançado
|
<Calendar className="w-4 h-4 mr-2" />
|
||||||
|
Aniversariantes
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="bg-white rounded-lg border border-gray-200">
|
{/* Tabela (Responsividade APLICADA) */}
|
||||||
|
<div className="bg-white rounded-lg border border-gray-200 shadow-md">
|
||||||
<div className="overflow-x-auto">
|
<div className="overflow-x-auto">
|
||||||
{error ? (
|
{error ? (
|
||||||
<div className="p-6 text-red-600">{`Erro ao carregar pacientes: ${error}`}</div>
|
<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]">
|
// min-w ajustado para responsividade
|
||||||
|
<table className="w-full min-w-[650px] md:min-w-[900px]">
|
||||||
<thead className="bg-gray-50 border-b border-gray-200">
|
<thead className="bg-gray-50 border-b border-gray-200">
|
||||||
<tr>
|
<tr>
|
||||||
<th className="text-left p-2 md:p-4 font-medium text-gray-700">
|
<th className="text-left p-4 font-medium text-gray-700 w-[20%]">Nome</th>
|
||||||
Nome
|
{/* Coluna oculta em telas muito pequenas */}
|
||||||
</th>
|
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">Telefone</th>
|
||||||
<th className="text-left p-2 md:p-4 font-medium text-gray-700">
|
{/* Coluna oculta em telas pequenas e muito pequenas */}
|
||||||
Telefone
|
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden md:table-cell">Cidade / Estado</th>
|
||||||
</th>
|
{/* Coluna oculta em telas muito pequenas */}
|
||||||
<th className="text-left p-2 md:p-4 font-medium text-gray-700">
|
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden sm:table-cell">Convênio</th>
|
||||||
Cidade
|
{/* Colunas ocultas em telas médias, pequenas e muito pequenas */}
|
||||||
</th>
|
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">Último atendimento</th>
|
||||||
<th className="text-left p-2 md:p-4 font-medium text-gray-700">
|
<th className="text-left p-4 font-medium text-gray-700 w-[15%] hidden lg:table-cell">Próximo atendimento</th>
|
||||||
Estado
|
<th className="text-left p-4 font-medium text-gray-700 w-[5%]">Ações</th>
|
||||||
</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>
|
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{filteredPatients.length === 0 ? (
|
{currentPatients.length === 0 ? (
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan={7} className="p-8 text-center text-gray-500">
|
<td colSpan={7} className="p-8 text-center text-gray-500">
|
||||||
{patients.length === 0
|
{allPatients.length === 0 ? "Nenhum paciente cadastrado" : "Nenhum paciente encontrado com os filtros aplicados"}
|
||||||
? "Nenhum paciente cadastrado"
|
|
||||||
: "Nenhum paciente encontrado com os filtros aplicados"}
|
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
) : (
|
) : (
|
||||||
filteredPatients.map((patient) => (
|
currentPatients.map((patient) => (
|
||||||
<tr
|
<tr key={patient.id} className="border-b border-gray-100 hover:bg-gray-50">
|
||||||
key={patient.id}
|
|
||||||
className="border-b border-gray-100 hover:bg-gray-50"
|
|
||||||
>
|
|
||||||
<td className="p-4">
|
<td className="p-4">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<div className="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center">
|
<div className="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
|
||||||
<span className="text-gray-600 font-medium text-sm">
|
<span className="text-green-600 font-medium text-sm">{patient.nome?.charAt(0) || "?"}</span>
|
||||||
{patient.nome?.charAt(0) || "?"}
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
<span className="font-medium text-gray-900">
|
<span className="font-medium text-gray-900">
|
||||||
{patient.nome}
|
{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>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td className="p-4 text-gray-600">
|
{/* Aplicação das classes de visibilidade */}
|
||||||
{patient.telefone}
|
<td className="p-4 text-gray-600 hidden sm:table-cell">{patient.telefone}</td>
|
||||||
</td>
|
<td className="p-4 text-gray-600 hidden md:table-cell">{`${patient.cidade} / ${patient.estado}`}</td>
|
||||||
<td className="p-4 text-gray-600">{patient.cidade}</td>
|
<td className="p-4 text-gray-600 hidden sm:table-cell">{patient.convenio}</td>
|
||||||
<td className="p-4 text-gray-600">{patient.estado}</td>
|
<td className="p-4 text-gray-600 hidden lg:table-cell">{patient.ultimoAtendimento}</td>
|
||||||
<td className="p-4 text-gray-600">
|
<td className="p-4 text-gray-600 hidden lg:table-cell">{patient.proximoAtendimento}</td>
|
||||||
{patient.ultimoAtendimento}
|
|
||||||
</td>
|
|
||||||
<td className="p-4 text-gray-600">
|
|
||||||
{patient.proximoAtendimento}
|
|
||||||
</td>
|
|
||||||
<td className="p-4">
|
<td className="p-4">
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<div className="text-blue-600">Ações</div>
|
<div className="text-blue-600 cursor-pointer">Ações</div>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem onClick={() => openDetailsDialog(String(patient.id))}>
|
||||||
onClick={() =>
|
|
||||||
openDetailsDialog(String(patient.id))
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<Eye className="w-4 h-4 mr-2" />
|
<Eye className="w-4 h-4 mr-2" />
|
||||||
Ver detalhes
|
Ver detalhes
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
|
||||||
<DropdownMenuItem asChild>
|
<DropdownMenuItem asChild>
|
||||||
<Link
|
<Link href={`/secretary/pacientes/${patient.id}/editar`} className="flex items-center w-full">
|
||||||
href={`/secretary/pacientes/${patient.id}/editar`}
|
|
||||||
>
|
|
||||||
<Edit className="w-4 h-4 mr-2" />
|
<Edit className="w-4 h-4 mr-2" />
|
||||||
Editar
|
Editar
|
||||||
</Link>
|
</Link>
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
|
||||||
<DropdownMenuItem>
|
<DropdownMenuItem>
|
||||||
<Calendar className="w-4 h-4 mr-2" />
|
<Calendar className="w-4 h-4 mr-2" />
|
||||||
Marcar consulta
|
Marcar consulta
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(String(patient.id))}>
|
||||||
className="text-red-600"
|
|
||||||
onClick={() =>
|
|
||||||
openDeleteDialog(String(patient.id))
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<Trash2 className="w-4 h-4 mr-2" />
|
<Trash2 className="w-4 h-4 mr-2" />
|
||||||
Excluir
|
Excluir
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
@ -340,118 +307,146 @@ export default function PacientesPage() {
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
)}
|
)}
|
||||||
<div ref={observerRef} style={{ height: 1 }} />
|
</div>
|
||||||
{isFetching && (
|
|
||||||
<div className="p-4 text-center text-gray-500">
|
{/* Paginação */}
|
||||||
Carregando mais pacientes...
|
{totalPages > 1 && !loading && (
|
||||||
|
<div className="flex flex-col sm:flex-row items-center justify-center p-4 border-t border-gray-200">
|
||||||
|
{/* Renderização dos botões de número de página (Limitando a 5) */}
|
||||||
|
<div className="flex space-x-2"> {/* Increased space-x for more separation */}
|
||||||
|
{/* Botão Anterior */}
|
||||||
|
<Button
|
||||||
|
onClick={() => setPage((prev) => Math.max(1, prev - 1))}
|
||||||
|
disabled={page === 1}
|
||||||
|
variant="outline"
|
||||||
|
size="lg" // Changed to "lg" for larger buttons
|
||||||
|
>
|
||||||
|
< Anterior
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
{Array.from({ length: totalPages }, (_, index) => index + 1)
|
||||||
|
.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="lg" // Changed to "lg" for larger buttons
|
||||||
|
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="lg" // Changed to "lg" for larger buttons
|
||||||
|
>
|
||||||
|
Próximo >
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
|
{/* AlertDialogs (Permanecem os mesmos) */}
|
||||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||||
|
{/* ... (AlertDialog de Exclusão) ... */}
|
||||||
<AlertDialogContent>
|
<AlertDialogContent>
|
||||||
<AlertDialogHeader>
|
<AlertDialogHeader>
|
||||||
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
|
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
|
||||||
<AlertDialogDescription>
|
<AlertDialogDescription>Tem certeza que deseja excluir este paciente? Esta ação não pode ser desfeita.</AlertDialogDescription>
|
||||||
Tem certeza que deseja excluir este paciente? Esta ação não pode
|
|
||||||
ser desfeita.
|
|
||||||
</AlertDialogDescription>
|
|
||||||
</AlertDialogHeader>
|
</AlertDialogHeader>
|
||||||
<AlertDialogFooter>
|
<AlertDialogFooter>
|
||||||
<AlertDialogCancel>Cancelar</AlertDialogCancel>
|
<AlertDialogCancel>Cancelar</AlertDialogCancel>
|
||||||
<AlertDialogAction
|
<AlertDialogAction onClick={() => patientToDelete && handleDeletePatient(patientToDelete)} className="bg-red-600 hover:bg-red-700">
|
||||||
onClick={() =>
|
|
||||||
patientToDelete && handleDeletePatient(patientToDelete)
|
|
||||||
}
|
|
||||||
className="bg-red-600 hover:bg-red-700"
|
|
||||||
>
|
|
||||||
Excluir
|
Excluir
|
||||||
</AlertDialogAction>
|
</AlertDialogAction>
|
||||||
</AlertDialogFooter>
|
</AlertDialogFooter>
|
||||||
</AlertDialogContent>
|
</AlertDialogContent>
|
||||||
</AlertDialog>
|
</AlertDialog>
|
||||||
|
|
||||||
{/* Modal de detalhes do paciente */}
|
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
||||||
<AlertDialog
|
{/* ... (AlertDialog de Detalhes) ... */}
|
||||||
open={detailsDialogOpen}
|
|
||||||
onOpenChange={setDetailsDialogOpen}
|
|
||||||
>
|
|
||||||
<AlertDialogContent>
|
<AlertDialogContent>
|
||||||
<AlertDialogHeader>
|
<AlertDialogHeader>
|
||||||
<AlertDialogTitle>Detalhes do Paciente</AlertDialogTitle>
|
<AlertDialogTitle>Detalhes do Paciente</AlertDialogTitle>
|
||||||
<AlertDialogDescription>
|
<AlertDialogDescription>
|
||||||
{patientDetails === null ? (
|
{patientDetails === null ? (
|
||||||
<div className="text-gray-500">Carregando...</div>
|
<div className="text-gray-500">
|
||||||
|
<Loader2 className="w-6 h-6 animate-spin mx-auto text-green-600 my-4" />
|
||||||
|
Carregando...
|
||||||
|
</div>
|
||||||
) : patientDetails?.error ? (
|
) : patientDetails?.error ? (
|
||||||
<div className="text-red-600">{patientDetails.error}</div>
|
<div className="text-red-600 p-4">{patientDetails.error}</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-2 text-left">
|
<div className="grid gap-4 py-4">
|
||||||
<p>
|
<div className="grid grid-cols-2 gap-4">
|
||||||
<strong>Nome:</strong> {patientDetails.full_name}
|
<div>
|
||||||
</p>
|
<p className="font-semibold">Nome Completo</p>
|
||||||
<p>
|
<p>{patientDetails.full_name}</p>
|
||||||
<strong>CPF:</strong> {patientDetails.cpf}
|
</div>
|
||||||
</p>
|
<div>
|
||||||
<p>
|
<p className="font-semibold">Email</p>
|
||||||
<strong>Email:</strong> {patientDetails.email}
|
<p>{patientDetails.email}</p>
|
||||||
</p>
|
</div>
|
||||||
<p>
|
<div>
|
||||||
<strong>Telefone:</strong>{" "}
|
<p className="font-semibold">Telefone</p>
|
||||||
{patientDetails.phone_mobile ??
|
<p>{patientDetails.phone_mobile}</p>
|
||||||
patientDetails.phone1 ??
|
</div>
|
||||||
patientDetails.phone2 ??
|
<div>
|
||||||
"-"}
|
<p className="font-semibold">Data de Nascimento</p>
|
||||||
</p>
|
<p>{patientDetails.birth_date}</p>
|
||||||
<p>
|
</div>
|
||||||
<strong>Nome social:</strong>{" "}
|
<div>
|
||||||
{patientDetails.social_name ?? "-"}
|
<p className="font-semibold">CPF</p>
|
||||||
</p>
|
<p>{patientDetails.cpf}</p>
|
||||||
<p>
|
</div>
|
||||||
<strong>Sexo:</strong> {patientDetails.sex ?? "-"}
|
<div>
|
||||||
</p>
|
<p className="font-semibold">Tipo Sanguíneo</p>
|
||||||
<p>
|
<p>{patientDetails.blood_type}</p>
|
||||||
<strong>Tipo sanguíneo:</strong>{" "}
|
</div>
|
||||||
{patientDetails.blood_type ?? "-"}
|
<div>
|
||||||
</p>
|
<p className="font-semibold">Peso (kg)</p>
|
||||||
<p>
|
<p>{patientDetails.weight_kg}</p>
|
||||||
<strong>Peso:</strong> {patientDetails.weight_kg ?? "-"}
|
</div>
|
||||||
{patientDetails.weight_kg ? "kg" : ""}
|
<div>
|
||||||
</p>
|
<p className="font-semibold">Altura (m)</p>
|
||||||
<p>
|
<p>{patientDetails.height_m}</p>
|
||||||
<strong>Altura:</strong> {patientDetails.height_m ?? "-"}
|
</div>
|
||||||
{patientDetails.height_m ? "m" : ""}
|
</div>
|
||||||
</p>
|
<div className="border-t pt-4 mt-4">
|
||||||
<p>
|
<h3 className="font-semibold mb-2">Endereço</h3>
|
||||||
<strong>IMC:</strong> {patientDetails.bmi ?? "-"}
|
<div className="grid grid-cols-2 gap-4">
|
||||||
</p>
|
<div>
|
||||||
<p>
|
<p className="font-semibold">Rua</p>
|
||||||
<strong>Endereço:</strong> {patientDetails.street ?? "-"}
|
<p>{`${patientDetails.street}, ${patientDetails.number}`}</p>
|
||||||
</p>
|
</div>
|
||||||
<p>
|
<div>
|
||||||
<strong>Bairro:</strong>{" "}
|
<p className="font-semibold">Complemento</p>
|
||||||
{patientDetails.neighborhood ?? "-"}
|
<p>{patientDetails.complement}</p>
|
||||||
</p>
|
</div>
|
||||||
<p>
|
<div>
|
||||||
<strong>Cidade:</strong> {patientDetails.city ?? "-"}
|
<p className="font-semibold">Bairro</p>
|
||||||
</p>
|
<p>{patientDetails.neighborhood}</p>
|
||||||
<p>
|
</div>
|
||||||
<strong>Estado:</strong> {patientDetails.state ?? "-"}
|
<div>
|
||||||
</p>
|
<p className="font-semibold">Cidade</p>
|
||||||
<p>
|
<p>{patientDetails.cidade}</p>
|
||||||
<strong>CEP:</strong> {patientDetails.cep ?? "-"}
|
</div>
|
||||||
</p>
|
<div>
|
||||||
<p>
|
<p className="font-semibold">Estado</p>
|
||||||
<strong>Criado em:</strong>{" "}
|
<p>{patientDetails.estado}</p>
|
||||||
{patientDetails.created_at ?? "-"}
|
</div>
|
||||||
</p>
|
<div>
|
||||||
<p>
|
<p className="font-semibold">CEP</p>
|
||||||
<strong>Atualizado em:</strong>{" "}
|
<p>{patientDetails.cep}</p>
|
||||||
{patientDetails.updated_at ?? "-"}
|
</div>
|
||||||
</p>
|
</div>
|
||||||
<p>
|
</div>
|
||||||
<strong>Id:</strong> {patientDetails.id ?? "-"}
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</AlertDialogDescription>
|
</AlertDialogDescription>
|
||||||
|
|||||||
@ -147,7 +147,12 @@ export default function DoctorLayout({ children }: PatientLayoutProps) {
|
|||||||
label: "Consultas",
|
label: "Consultas",
|
||||||
// Botão para página de consultas marcadas do médico atual
|
// Botão para página de consultas marcadas do médico atual
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
href: "/doctor/medicos/editorlaudo",
|
||||||
|
icon: Clock,
|
||||||
|
label: "Editor de Laudo",
|
||||||
|
// Botão para página do editor de laudo
|
||||||
|
},
|
||||||
{
|
{
|
||||||
href: "/doctor/medicos",
|
href: "/doctor/medicos",
|
||||||
icon: User,
|
icon: User,
|
||||||
|
|||||||
@ -3,7 +3,10 @@ import { api } from "./api.mjs";
|
|||||||
export const doctorsService = {
|
export const doctorsService = {
|
||||||
list: () => api.get("/rest/v1/doctors"),
|
list: () => api.get("/rest/v1/doctors"),
|
||||||
getById: (id) => api.get(`/rest/v1/doctors?id=eq.${id}`).then(data => data[0]),
|
getById: (id) => api.get(`/rest/v1/doctors?id=eq.${id}`).then(data => data[0]),
|
||||||
create: (data) => api.post("/functions/v1/create-doctor", data),
|
async create(data) {
|
||||||
|
// Esta é a função usada no page.tsx para criar médicos
|
||||||
|
return await api.post("/functions/v1/create-doctor", data);
|
||||||
|
},
|
||||||
update: (id, data) => api.patch(`/rest/v1/doctors?id=eq.${id}`, data),
|
update: (id, data) => api.patch(`/rest/v1/doctors?id=eq.${id}`, data),
|
||||||
delete: (id) => api.delete(`/rest/v1/doctors?id=eq.${id}`),
|
delete: (id) => api.delete(`/rest/v1/doctors?id=eq.${id}`),
|
||||||
};
|
};
|
||||||
@ -1,5 +1,3 @@
|
|||||||
// SUBSTITUA O OBJETO INTEIRO EM services/usersApi.mjs
|
|
||||||
|
|
||||||
import { api } from "./api.mjs";
|
import { api } from "./api.mjs";
|
||||||
|
|
||||||
export const usersService = {
|
export const usersService = {
|
||||||
@ -19,6 +17,7 @@ export const usersService = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
async create_user(data) {
|
async create_user(data) {
|
||||||
|
// Esta é a função usada no page.tsx para criar usuários que não são médicos
|
||||||
return await api.post(`/functions/v1/create-user-with-password`, data);
|
return await api.post(`/functions/v1/create-user-with-password`, data);
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user