Compare commits

...

No commits in common. "main" and "b3a50ba57365b8fafe7a29e57422b810274cb1df" have entirely different histories.

233 changed files with 49250 additions and 25046 deletions

27
.gitignore vendored
View File

@ -1,27 +0,0 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
# next.js
/.next/
/out/
# production
/build
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

View File

@ -1,2 +0,0 @@
{
}

View File

@ -1,2 +0,0 @@
# riseup-squad21

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 828 B

View File

@ -0,0 +1 @@
<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" width="50px" height="50px"> <path d="M47.16,21.221l-5.91-0.966c-0.346-1.186-0.819-2.326-1.411-3.405l3.45-4.917c0.279-0.397,0.231-0.938-0.112-1.282 l-3.889-3.887c-0.347-0.346-0.893-0.391-1.291-0.104l-4.843,3.481c-1.089-0.602-2.239-1.08-3.432-1.427l-1.031-5.886 C28.607,2.35,28.192,2,27.706,2h-5.5c-0.49,0-0.908,0.355-0.987,0.839l-0.956,5.854c-1.2,0.345-2.352,0.818-3.437,1.412l-4.83-3.45 c-0.399-0.285-0.942-0.239-1.289,0.106L6.82,10.648c-0.343,0.343-0.391,0.883-0.112,1.28l3.399,4.863 c-0.605,1.095-1.087,2.254-1.438,3.46l-5.831,0.971c-0.482,0.08-0.836,0.498-0.836,0.986v5.5c0,0.485,0.348,0.9,0.825,0.985 l5.831,1.034c0.349,1.203,0.831,2.362,1.438,3.46l-3.441,4.813c-0.284,0.397-0.239,0.942,0.106,1.289l3.888,3.891 c0.343,0.343,0.884,0.391,1.281,0.112l4.87-3.411c1.093,0.601,2.248,1.078,3.445,1.424l0.976,5.861C21.3,47.647,21.717,48,22.206,48 h5.5c0.485,0,0.9-0.348,0.984-0.825l1.045-5.89c1.199-0.353,2.348-0.833,3.43-1.435l4.905,3.441 c0.398,0.281,0.938,0.232,1.282-0.111l3.888-3.891c0.346-0.347,0.391-0.894,0.104-1.292l-3.498-4.857 c0.593-1.08,1.064-2.222,1.407-3.408l5.918-1.039c0.479-0.084,0.827-0.5,0.827-0.985v-5.5C47.999,21.718,47.644,21.3,47.16,21.221z M25,32c-3.866,0-7-3.134-7-7c0-3.866,3.134-7,7-7s7,3.134,7,7C32,28.866,28.866,32,25,32z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" width="50px" height="50px"><path d="M 30.398438 2 L 7 2 L 7 48 L 43 48 L 43 14.601563 Z M 15 28 L 31 28 L 31 30 L 15 30 Z M 35 36 L 15 36 L 15 34 L 35 34 Z M 35 24 L 15 24 L 15 22 L 35 22 Z M 30 15 L 30 4.398438 L 40.601563 15 Z"/></svg>

After

Width:  |  Height:  |  Size: 298 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1008 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 848 B

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" width="50px" height="50px"><path d="M 21 3 C 11.601563 3 4 10.601563 4 20 C 4 29.398438 11.601563 37 21 37 C 24.355469 37 27.460938 36.015625 30.09375 34.34375 L 42.375 46.625 L 46.625 42.375 L 34.5 30.28125 C 36.679688 27.421875 38 23.878906 38 20 C 38 10.601563 30.398438 3 21 3 Z M 21 7 C 28.199219 7 34 12.800781 34 20 C 34 27.199219 28.199219 33 21 33 C 13.800781 33 8 27.199219 8 20 C 8 12.800781 13.800781 7 21 7 Z"/></svg>

After

Width:  |  Height:  |  Size: 491 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 516 B

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,444 @@
/* --- Estilos Gerais e Reset --- */
* {
padding: 0px;
margin: 0px;
border: none;
box-sizing: border-box; /* Essencial para um bom layout */
}
.flex {
display: flex;
}
body {
font-family: sans-serif;
background-color: #f3f0f0;
}
/* --- Estilos do Header/Navegação (mantido e levemente ajustado) --- */
.nav {
display: flex;
justify-content: space-between;
background-color: #eaeaea;
align-items: center;
padding: 20px;
}
/* ==========================================================================
BARRA DE BUSCA
========================================================================== */
.div-search {
display: flex; /* Essencial para que a propriedade 'order' funcione */
align-items: center;
border: 1.5px solid #ccc;
border-radius: 6px;
background-color: #fff;
overflow: hidden;
margin-top: 2rem;
margin-bottom: 1rem;
}
/* Efeito de foco no contêiner inteiro */
.div-search:focus-within {
border-color: rgb(44, 185, 228);
box-shadow: 0 0 0 2px rgba(44, 185, 228, 0.2);
}
/* --- 2. Reordenando os Itens Visualmente --- */
.search-input { order: 1; } /* Primeiro item */
.search-button { order: 2; } /* Segundo item (a lupa) */
.filter-select { order: 3; } /* Terceiro e último item (Geral) */
/* --- 3. Estilo dos Itens Individuais na Nova Ordem --- */
/* Campo "Buscar paciente" */
.search-input {
height: 38px;
flex-grow: 1; /* Ocupa o máximo de espaço */
padding: 0 12px;
border: none;
outline: none;
font-size: 14px;
background: transparent;
}
/* Botão da Lupa */
.search-button {
display: flex;
align-items: center;
justify-content: center;
height: 38px;
padding: 0 12px;
background: transparent;
cursor: pointer;
border: none; /* Sem borda, para se juntar ao input */
outline: none;
}
.search-button img {
width: 20px;
height: 20px;
opacity: 0.7;
}
/* Seletor "Geral" */
.filter-select {
height: 38px;
padding: 0 12px;
background: transparent;
border: none;
border-left: 1.5px solid #ccc; /* A única linha divisória */
color: #555;
font-size: 14px;
cursor: pointer;
outline: none;
}
/* ==========================================================================
ÍCONES DO CABEÇALHO - ESTILO APRIMORADO
========================================================================== */
/* --- 1. O contêiner da lista de ícones --- */
.icon-lista {
display: flex;
list-style: none;
gap: 7px; /* Reduzi um pouco o espaço para ficar mais coeso */
align-items: center; /* Alinha todos os ícones verticalmente */
}
/* --- 2. PADRONIZAÇÃO dos links (a) e botões (button) --- */
.icon-lista li a,
.icon-lista li button {
display: flex; /* Garante que o contêiner se ajuste à imagem */
align-items: center;
justify-content: center;
background: none; /* Remove qualquer fundo padrão */
border: none; /* Remove qualquer borda padrão */
padding: 0; /* Remove qualquer padding padrão */
cursor: pointer;
opacity: 0.7; /* Deixa os ícones um pouco mais suaves */
transition: opacity 0.2s ease, transform 0.2s ease; /* Animação suave */
}
/* --- 3. EFEITO HOVER para dar feedback ao usuário --- */
.icon-lista li a:hover,
.icon-lista li button:hover {
opacity: 1; /* Opacidade total no hover */
transform: scale(1.1); /* Leve aumento de tamanho */
}
/* --- 4. O TAMANHO REAL da imagem do ícone --- */
.icon-lista li img {
width: 18px; /* << AUMENTADO O TAMANHO AQUI */
height: 18px; /* << AUMENTADO O TAMANHO AQUI */
display: block;
}
/* A regra #music não é mais necessária, pois já foi padronizada acima */
#music {
background: none;
cursor: pointer;
}
/* ==========================================================================
SIDEBAR E LAYOUT PRINCIPAL - REVISÃO FINAL
========================================================================== */
/* --- Container principal da sidebar para flexbox --- */
.div-sidebar {
height: 100vh;
display: flex;
flex-direction: column;
justify-content: space-between; /* Este é crucial para empurrar o perfil para baixo */
align-items: center; /* Centraliza o conteúdo da sidebar se ela for estreita */
width: 100%; /* Garante que div-sidebar ocupe a largura total de .sidebar */
}
/* --- Estilos de Base da Sidebar --- */
.sidebar {
background-color: #ffffff;
box-shadow: 5px 0 15px rgba(0, 0, 0, 0.1);
height: 100vh;
position: fixed;
top: 0;
left: 0;
z-index: 1000;
transition: width 0.3s ease, transform 0.3s ease;
}
/* --- Logo na Sidebar --- */
.logo1 {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
padding: 1.5rem 0; /* Espaçamento vertical generoso */
border-bottom: 1px solid #eee; /* Linha divisória */
}
#logo-med {
width: 80px; /* << MAIOR AINDA! */
height: auto;
transition: transform 0.3s ease, filter 0.3s ease;
cursor: pointer;
}
#logo-med:hover {
transform: scale(1.1);
filter: drop-shadow(0 0 10px rgba(44, 185, 228, 0.7)); /* Destaque mais forte */
}
/* --- Itens de Navegação --- */
.sidebar ul {
list-style: none;
padding: 0;
margin: 0;
width: 100%; /* Garante que a lista preencha a largura disponível */
}
.sidebar li {
width: 100%; /* Garante que cada item da lista preencha a largura */
}
.sidebar a {
display: flex;
align-items: center;
color: rgb(12, 54, 70);
text-decoration: none;
padding: 1rem 1.5rem;
white-space: nowrap;
border-left: 4px solid transparent;
transition: background-color 0.2s ease, border-left 0.2s ease, color 0.2s ease;
}
.sidebar a:hover,
.sidebar a.active { /* Estilo para hover e item ativo */
background-color: #eef5fa; /* Fundo suave */
border-left-color: rgb(44, 185, 228); /* Borda azul destacada */
color: rgb(44, 185, 228); /* Texto azul para item ativo */
font-weight: 600; /* Negrito para destacar */
}
.icon-sidebar {
width: 22px; /* Tamanho do ícone */
height: 22px;
flex-shrink: 0;
margin-right: 15px; /* Espaço entre ícone e texto */
}
/* --- Perfil do Médico (Dr. Rafael) --- */
.perfil-medico-sidebar {
text-align: center;
padding: 1rem;
border-top: 1px solid #eee;
width: 100%;
}
.perfil-medico-sidebar h3 {
font-size: 1rem;
margin-bottom: 0.25rem;
color: #333;
}
.perfil-medico-sidebar p {
font-size: 0.8rem;
color: #6c757d;
}
/* --- Conteúdo Principal --- */
.section-main {
background-color: #f3f0f0;
transition: margin-left 0.3s ease;
/* padding: 0px; */
width: 100%; /* Garante que ocupe o espaço restante */
height: 100%;
}
/* --- Botão Hambúrguer e Overlay (escondidos por padrão no desktop) --- */
.hamburger-btn,
.overlay {
display: none;
}
/* ==========================================================================
MEDIA QUERIES - RESPONSIVIDADE
========================================================================== */
/* --- LAYOUT DESKTOP (Telas a partir de 1025px) --- */
@media (min-width: 1025px) {
.sidebar {
width: 200px; /* Largura expandida */
}
.section-main {
margin-left: 200px; /* Empurra o conteúdo */
}
}
/* --- LAYOUT TABLET (Telas de 769px a 1024px) - CORRIGIDO --- */
@media (min-width: 769px) and (max-width: 1024px) {
.sidebar {
width: 150px; /* << MUDANÇA: Mantém a largura expandida, igual ao desktop */
}
/* As regras abaixo garantem que o conteúdo da sidebar (ícones, texto)
se comporte como no desktop, mesmo que alguma outra regra os altere. */
.sidebar a {
justify-content: flex-start; /* Alinha o conteúdo à esquerda */
padding: 1rem 1.5rem; /* Restaura o espaçamento interno */
}
.icon-sidebar {
margin-right: 15px; /* Devolve o espaço entre o ícone e o texto */
}
/* AQUI ESTÁ A CORREÇÃO PRINCIPAL:
Garantimos que o texto e o perfil fiquem visíveis. */
.sidebar a span,
.perfil-medico-sidebar {
display: block; /* Garante que eles sejam visíveis */
}
#logo-med {
width: 80px; /* Restaura o tamanho original do logo */
}
.section-main {
margin-left: 150px; /* << MUDANÇA: Empurra o conteúdo pela distância correta */
}
.search-input {
width: 30vw; /* Mantém o ajuste da barra de busca para tablets */
}
}
/* --- LAYOUT MOBILE (Telas até 768px) - CORRIGIDO E FINALIZADO --- */
@media (max-width: 768px) {
.nav {
/* Adicionado flexbox para o alinhamento vertical dos itens */
display: flex;
align-items: center;
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 999;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.13);
padding: 0 15px 0 60px;
height: 65px;
}
.div-search {
flex-grow: 1;
margin-right: 15px;
}
.search-input {
width: 100%;
}
/* <<< MUDANÇA DRÁSTICA #1: ÍCONES DA DIREITA BEM MENORES */
/* --- CORREÇÃO FINAL: FORÇAR A DIMINUIÇÃO DOS ÍCONES DA DIREITA --- */
.user-actions i,
.user-actions svg {
font-size: 2px !important; /* Força um tamanho visivelmente menor */
height: 2px !important; /* Garante a altura para qualquer tipo de ícone */
width: 2px !important; /* Garante a largura para qualquer tipo de ícone */
}
.sidebar {
width: 280px;
transform: translateX(-100%);
/* <<< MUDANÇA #2: A ESTRUTURA QUE FEZ O PERFIL FUNCIONAR */
height: 100vh; /* Ocupa a altura toda da tela */
display: flex;
flex-direction: column; /* Organiza os itens em coluna */
}
.sidebar.active {
transform: translateX(0);
}
.sidebar a {
justify-content: flex-start;
}
.icon-sidebar {
margin-right: 15px;
}
.sidebar a span {
display: block;
}
/* <<< MUDANÇA #3: O ESTILO DO PERFIL QUE VOCÊ APROVOU */
.perfil-medico-sidebar {
margin-top: auto; /* Joga o perfil para a base do menu */
text-align: left;
padding: 20px 15px; /* Espaçamento interno */
border-top: 2px solid #007bff; /* A linha azul que você gostou */
}
#logo-med {
width: 100px;
padding: 0.1rem 15px; /* Adiciona padding para alinhar com os outros itens */
}
.section-main {
margin-left: 0;
padding-top: 80px;
}
/* O seu código do botão hambúrguer e overlay permanece intacto */
.hamburger-btn {
display: flex;
position: fixed;
top: 24px;
left: 20px;
z-index: 1002;
flex-direction: column;
justify-content: space-around;
width: 30px;
height: 25px;
background: transparent;
cursor: pointer;
}
.hamburger-btn span {
width: 100%; height: 3px; background-color: #333;
border-radius: 3px; transition: all 0.3s ease;
}
.hamburger-btn.active span:nth-child(1) { transform: rotate(45deg) translate(5px, 5px); }
.hamburger-btn.active span:nth-child(2) { opacity: 0; }
.hamburger-btn.active span:nth-child(3) { transform: rotate(-45deg) translate(7px, -6px); }
.overlay {
position: fixed; top: 0; left: 0; width: 100%; height: 100%;
background-color: rgba(0, 0, 0, 0.5); z-index: 999;
opacity: 0; visibility: hidden;
transition: opacity 0.3s ease, visibility 0.3s ease;
}
.overlay.active {
display: block; opacity: 1; visibility: visible;
}
}
/* --- Estilos para foco e acessibilidade --- */
.hamburger-btn:focus-visible { /* Usar focus-visible para melhor UX */
outline: 2px solid #007bff;
outline-offset: 2px;
}
.sidebar ul li a:focus-visible,
.icon-lista li a:focus-visible {
outline: 2px solid #007bff;
outline-offset: 2px;
border-radius: 4px;
}

View File

@ -0,0 +1,565 @@
* {
padding: 0px;
margin: 0px;
border: none;
}
.flex {
display: flex;
}
body {
font-family: sans-serif;
background-color: #f3f0f0;
}
.icon-sidebar {
width: 17px;
padding: 10px 15px;
}
#music {
background: none;
}
.sidebar {
padding-top: 1rem;
padding: 1rem 0.5rem 0px 0.5rem;
display: flex;
flex-wrap: wrap;
flex-direction: column;
justify-content: start;
align-items: center;
max-width: 12vw;
max-height: 100vh;
height: 100%;
background-color: white;
width: 100%;
box-shadow: 9px 0px 15px rgba(0, 0, 0, 0.3);
}
.main-contain {
margin: 1rem 4rem;
}
.perfil-medico-sidebar {
display: flex;
flex-direction: column;
width: 100%;
text-align: center;
height: 200px;
}
.perfil-medico-sidebar p {
font-size: 12px;
}
.div-sidebar {
height: 100vh;
display: flex;
flex-direction: column;
/* align-items: flex-end; */
justify-content: space-between;
}
.sidebar a {
display: flex;
align-items: center;
text-decoration: none;
color: rgb(12, 54, 70);
flex-wrap: wrap;
}
.sidebar ul li {
text-align: center;
list-style: none;
border: 2px solid transparent;
border-radius: 3%;
padding: 0.7rem 0.8rem;
}
.sidebar ul li:hover {
border: 2px solid rgb(44, 185, 228);
background-color: rgb(44, 185, 228);
}
.sidebar * {
max-width: 100%;
}
.icon-lista {
display: flex;
list-style: none;
gap: 30px;
padding: 15px;
}
.icon-lista li a img,
img {
width: 22px;
/* background-color: #fff; */
padding: 5px;
}
.div-search {
display: flex;
align-items: center;
position: relative;
}
.div-search:hover {
border: 1.5px solid darkgray;
border-radius: 5px;
}
.section-main {
max-width: 88vw;
margin-left: 10rem;
width: 100%;
background-color: #f3f0f0;
}
.search-input {
height: 38px;
width: 20vw;
padding-left: 10px;
margin-left: 2rem;
border-radius: 5px;
border: 1.5px solid #ccc;
}
.search-button {
position: absolute;
right: 15px;
top: 37%;
transform: translateY(-50%);
background: none;
border: none;
cursor: pointer;
width: 22px;
height: 22px;
}
.nav {
display: flex;
justify-content: space-between;
background-color: #eaeaea;
align-items: center;
padding: 20px;
}
#logo-med {
width: 30px;
margin-bottom: 1rem;
}
/*Interface Hamburguer*/
.hamburger-btn {
display: none;
flex-direction: column;
justify-content: space-around;
width: 30px;
height: 30px;
background: transparent;
border: none;
cursor: pointer;
padding: 0;
position: fixed;
top: 20px;
left: 20px;
z-index: 1001;
}
.hamburger-btn span {
width: 25px;
height: 3px;
background: #333;
border-radius: 3px;
transition: 0.3s;
}
.hamburger-btn.active span:nth-child(1) {
transform: rotate(-45deg) translate(-5px, 6px);
}
.hamburger-btn.active span:nth-child(2) {
opacity: 0;
}
.hamburger-btn.active span:nth-child(3) {
transform: rotate(45deg) translate(-5px, -6px);
}
/* Overlay para fechar menu ao clicar fora */
.overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 998;
}
.overlay.active {
display: block;
}
/* Media queries melhoradas para responsividade */
@media (max-width: 768px) {
.hamburger-btn {
display: flex;
flex-direction: column;
justify-content: space-around;
width: 30px;
height: 22px; /* Ajuste altura */
background: transparent;
cursor: pointer;
padding: 0;
position: fixed; /* Fixo para estar sempre visível */
top: 24px;
left: 20px;
z-index: 1002; /* Acima de tudo */
}
.hamburger-btn span {
width: 30px;
height: 3px;
background: #333;
border-radius: 3px;
transition: all 0.3s ease-in-out;
}
/* Animação do botão para "X" */
.hamburger-btn.active span:nth-child(1) {
transform: rotate(45deg) translate(7px, 7px);
}
.hamburger-btn.active span:nth-child(2) {
opacity: 0;
}
.hamburger-btn.active span:nth-child(3) {
transform: rotate(-45deg) translate(7px, -7px);
}
/* Sidebar no Mobile */
.sidebar {
position: fixed;
left: 0;
top: 0;
height: 100vh;
width: 280px; /* Largura fixa no mobile */
min-width: 0;
padding: 80px 20px 20px;
box-shadow: 5px 0 15px rgba(0, 0, 0, 0.2);
/* A MÁGICA ACONTECE AQUI */
transform: translateX(-100%); /* Esconde a sidebar fora da tela */
transition: transform 0.3s ease-in-out; /* Animação suave */
z-index: 1001; /* Acima do overlay */
overflow-y: auto; /* Permite rolar se o menu for grande */
}
.sidebar.active {
transform: translateX(0); /* Mostra a sidebar */
}
/* Ajustes no layout interno da sidebar mobile */
.sidebar a {
flex-direction: row; /* Ícone e texto lado a lado */
justify-content: flex-start;
padding: 12px 15px;
}
.icon-sidebar {
margin-right: 15px; /* Espaço entre ícone e texto */
margin-bottom: 0;
}
.sidebar p {
font-size: 16px;
}
#logo-med {
width: 50px;
}
/* Conteúdo Principal no Mobile */
.section-main {
width: 100%;
margin-left: 0; /* Remove a margem do desktop */
padding-top: 85px; /* MUITO IMPORTANTE: Espaço para o .nav fixo */
}
.nav {
position: fixed; /* Fixa o cabeçalho no topo */
top: 0;
left: 0;
width: 100%;
z-index: 999; /* Abaixo da sidebar */
padding: 15px 20px;
}
.div-search {
width: 100%;
margin-left: 50px; /* Espaço para o botão hambúrguer */
}
.search-input {
width: 100%;
}
/* Overlay (fundo escuro) */
.overlay {
display: block;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 1000;
opacity: 0;
visibility: hidden; /* Esconde e impede cliques */
transition: opacity 0.3s ease-in-out, visibility 0.3s ease-in-out;
}
}
/* Media query para tablets */
@media (max-width: 1024px) and (min-width: 769px) {
.sidebar {
max-width: 12vw;
padding: 0.3rem;
}
.sidebar a {
flex-wrap: wrap;
justify-content: center;
flex-direction: column;
}
.search-input {
width: 35vw;
min-width: 250px;
margin-left: 2rem;
}
.icon-lista {
gap: 25px;
}
}
/* Media query melhorada para telas muito pequenas */
@media (max-width: 480px) {
.hamburger-btn {
top: 15px;
left: 15px;
}
.sidebar {
/* display: none; */
height: 90vh;
}
.div-sidebar {
max-height: 100%;
width: 90%;
/* background-color: black; */
}
.abas {
max-height: 100%;
overflow-y: auto;
width: 100%;
overflow-x: hidden;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.sidebar.active {
display: flex;
position: fixed;
top: 0;
left: 0;
flex-direction: column;
max-width: 300px;
width: 300px;
height: 100%;
max-height: 100vh;
padding: 60px 15px 15px 15px;
box-shadow: 5px 0px 15px rgba(0, 0, 0, 0.3);
z-index: 999;
background-color: white;
overflow-y: scroll;
}
/* Removendo padding-top desnecessário */
.nav {
padding: 15px;
flex-direction: column;
align-items: stretch;
margin-top: 0;
width: 100%;
}
.div-search {
margin-bottom: 10px;
width: 90%;
margin-left: 1rem;
}
.search-input {
width: 100%;
min-width: auto;
}
.icon-lista {
justify-content: center;
gap: 20px;
padding: 10px;
}
}
/* Adicionando estilos para melhor acessibilidade */
@media (prefers-reduced-motion: reduce) {
.hamburger-btn span,
.sidebar,
.overlay {
transition: none;
}
}
/* Estilos para foco e acessibilidade */
.hamburger-btn:focus {
outline: 2px solid #007bff;
outline-offset: 2px;
}
.sidebar ul li a:focus,
.icon-lista li a:focus {
outline: 2px solid #007bff;
outline-offset: 2px;
border-radius: 4px;
}
/* Adicionando media query para desktop - sidebar sempre visível */
@media (min-width: 769px) {
.sidebar {
display: flex;
position: fixed;
left: auto;
transform: none;
transition: none;
}
.sidebar a {
justify-content: center;
flex-direction: column;
}
.perfil-medico-sidebar {
padding-bottom: 1rem;
}
.search-input {
width: 35vw;
}
.hamburger-btn {
display: none;
}
.overlay {
display: none !important;
}
/* Section main volta ao layout original no desktop */
.section-main {
max-width: 88vw;
width: 100%;
margin-left: 12rem;
}
}
.logo1 {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
}
@media (max-width: 768px) {
.hamburger-btn {
display: flex;
}
.sidebar {
max-width: 280px;
width: 75%;
padding-top: 80px;
transform: translateX(-100%);
transition: transform 0.3s ease-in-out;
z-index: 1001;
}
.sidebar.active {
transform: translateX(0);
}
.sidebar a {
flex-direction: row;
justify-content: flex-start;
text-align: left;
}
.icon-sidebar {
margin-right: 15px;
margin-bottom: 0;
}
.perfil-medico-sidebar {
text-align: left;
padding-left: 10px;
}
#logo-med {
margin-bottom: 1.5rem;
}
.section-main {
margin-left: 0;
padding-top: 80px;
}
.nav {
position: fixed;
top: 0;
width: 100%;
z-index: 998;
padding: 15px 20px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.div-search {
margin-left: 50px;
}
.search-input {
width: 100%;
}
}
/* Telas muito pequenas */
@media (max-width: 480px) {
.nav {
flex-direction: column;
align-items: stretch;
gap: 10px;
padding: 15px;
}
/* ALTERAÇÃO: Aumenta o padding para o nav que agora é mais alto */
.section-main {
padding-top: 130px;
}
.div-search {
margin-left: 0;
width: 100%;
}
}

View File

@ -0,0 +1,111 @@
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Crud + Layout</title>
<link rel="stylesheet" href="global.css" />
<!-- css da página -->
<link rel="stylesheet" href="#" />
</head>
<body>
<main>
<!-- Overlay só aparece em mobile quando menu está ativo -->
<div class="overlay" id="overlay"></div>
<div class="flex">
<!-- Botão hambúrguer só aparece em mobile -->
<button class="hamburger-btn" id="hamburger-btn" aria-label="Abrir menu de navegação" aria-expanded="false">
<span></span>
<span></span>
<span></span>
</button>
<!-- Sidebar agora se comporta diferente em desktop vs mobile -->
<section class="sidebar" id="sidebar" role="navigation" aria-label="Menu principal">
<div class="div-sidebar">
<div class="abas">
<a href="#" aria-label="Página inicial" class="logo1">
<img src="https://images.vexels.com/media/users/3/142777/isolated/preview/84711206e52e0d4ff6c793cb476ea264-logotipo-medico-da-estrela-do-heartbeat.png" alt="Logo médico" id="logo-med" />
</a>
<ul>
<li>
<a href="pages/pacientes/paciente.html" aria-label="Pacientes">
<img src="/clinicApp/assets/layoutIcons/icons8-estetoscópio-50.png" alt="Pacientes" class="icon-sidebar" />
<p>Pacientes</p>
</a>
</li>
<li>
<a href="pages/dashboard/dashboard.html" aria-label="Pacientes">
<img src="/clinicApp/assets/layoutIcons/icons8-estetoscópio-50.png" alt="Pacientes" class="icon-sidebar" />
<p>Dashboard</p>
</a>
</li>
<li>
<a href="pages/agendamento/agendamento.html" aria-label="Cadastro de usuários">
<img src="/clinicApp/assets/layoutIcons/icons8-grupo-de-usuário-homem-homem-50.png" alt="Cadastro" class="icon-sidebar" />
<p>Médicos</p>
</a>
</li>
<li>
<a href="pages/laudo/laudoMedico.html" aria-label="Documentos">
<img src="/clinicApp/assets/layoutIcons/icons8-document.svg" alt="Documentos" class="icon-sidebar" />
<p>Laúdos</p>
</a>
</li>
<li>
<a href="#" aria-label="Documentos">
<img src="assets/layoutIcons/icons8-document.svg" alt="Documentos" class="icon-sidebar" />
<p>Agenda</p>
</a>
</li>
<li>
<a href="#" aria-label="Configurações">
<img src="assets/layoutIcons/icons8-configurações.svg" alt="Configurações" class="icon-sidebar" />
<p>Settings</p>
</a>
</li>
</ul>
</div>
<div class="perfil-medico-sidebar">
<h3>Dr. Rafael Andrade</h3>
<p>Núcleo de Especialidades</p>
</div>
</div>
</section>
<section class="section-main">
<nav class="nav" role="banner">
<div class="div-search">
<input type="text" class="search-input" placeholder="Buscar paciente" aria-label="Campo de busca" />
<button class="search-button" aria-label="Buscar">
<img src="assets/layoutIcons/icons8-pesquisar.svg" alt="Buscar" />
</button>
</div>
<div>
<ul class="icon-lista">
<li>
<a href="#" aria-label="Ajuda"><img src="assets/layoutIcons/icons8-ajuda-50.png" alt="Ajuda" /></a>
</li>
<li>
<button id="music" aria-label="Notificações"><img src="assets/layoutIcons/botao-ativar-notificacoes.png" alt="Notificações" /></button>
</li>
<!--button ta gerando um fundo branco, botei ID pra retirar o background-->
<li>
<a href="#" aria-label="Perfil do usuário"><img src="assets/layoutIcons/icons8-usuário-50.png" alt="Usuário" /></a>
</li>
</ul>
</div>
</nav>
<div class="main-contain">
<h1>Gerenciador</h1>
</div>
</section>
</div>
</main>
<script src="scriptGlobal.js"></script>
</body>
</html>

View File

@ -0,0 +1,949 @@
:root {
--bg-main: #f3f0f0;
--bg-nav: #fafafa;
--bg-modal: #fff;
--sombra-modal: 0 4px 15px rgba(0, 0, 0, 0.3);
--sombra-sidebar: 15px 0px 15px rgba(0, 0, 0, 0.3);
--cor-cinza-claro: #f1f1f1;
--cor-cinza-medio: #ccc;
--cor-cinza-escuro: #666;
--cor-tabela-header: #f3f0f0;
--cor-principal: rgb(38, 137, 255);
--cor-hover-principal: rgb(30, 110, 204);
--cor-borda-input-foco: #2e7d32;
--cor-fundo-botao-salvar: #2e7d32;
--cor-hover-salvar: #256628;
}
* {
padding: 0;
margin: 0;
border: none;
box-sizing: border-box;
}
body,
html {
font-family: Arial, sans-serif;
}
.flex {
display: flex;
}
.sidebar {
padding-top: 1.25rem;
display: flex;
flex-direction: column;
align-items: center;
width: 5vw;
height: 100vh;
background-color: white;
box-shadow: var(--sombra-sidebar);
}
.sidebar ul {
list-style: none;
text-align: center;
}
.sidebar ul li {
padding: 10px 0;
}
.icon-sidebar {
width: 17px;
padding: 10px 13px 5px 13px;
transition: background-color 0.2s;
}
.icon-sidebar:hover {
background-color: var(--cor-cinza-claro);
}
.section-main {
width: 95vw;
background-color: var(--bg-main);
}
.nav {
display: flex;
justify-content: space-between;
align-items: center;
background-color: var(--bg-nav);
padding: 20px;
}
.div-search {
display: flex;
align-items: center;
position: relative;
border-radius: 5px;
transition: border 0.2s;
}
.div-search:hover {
border: 1.5px solid darkgray;
}
.search-input {
height: 38px;
width: 20vw;
padding-left: 10px;
border-radius: 5px;
border: 1.5px solid var(--cor-cinza-medio);
}
.search-button {
position: absolute;
right: 15px;
top: 50%;
transform: translateY(-50%);
background: none;
cursor: pointer;
width: 22px;
height: 22px;
}
.icon-lista {
display: flex;
list-style: none;
gap: 30px;
padding: 15px;
}
.icon-lista li a img,
img {
width: 22px;
padding: 5px;
}
.btn-add,
.btn {
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.2s;
}
.btn-add {
margin: 20px;
background-color: var(--cor-principal);
color: #fff;
}
.btn-add:hover {
background-color: var(--cor-hover-principal);
}
.modal {
display: none;
position: fixed;
z-index: 1000;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.6);
justify-content: center;
align-items: center;
animation: fadeIn 0.3s ease;
}
.modal-content {
background: var(--bg-modal);
padding: 20px;
border-radius: 12px;
width: 800px;
max-height: 90vh;
overflow-y: auto;
box-shadow: var(--sombra-modal);
position: relative;
}
.modal-content h2 {
margin-bottom: 15px;
font-size: 20px;
color: #333;
border-bottom: 1px solid #eee;
padding-bottom: 8px;
}
.close {
position: absolute;
top: 10px;
right: 15px;
font-size: 20px;
cursor: pointer;
color: var(--cor-cinza-escuro);
}
.form-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 15px;
margin-bottom: 15px;
}
.form-group {
display: flex;
flex-direction: column;
}
.form-group label {
font-weight: 600;
font-size: 13px;
margin-bottom: 4px;
color: #444;
}
.form-group input,
.form-group select {
padding: 8px;
height: 32px;
border-radius: 6px;
border: 1px solid var(--cor-cinza-medio);
font-size: 14px;
outline: none;
width: 100%;
}
.form-group input:focus,
.form-group select:focus {
border-color: var(--cor-borda-input-foco);
box-shadow: 0 0 5px rgba(46, 125, 50, 0.3);
}
.radio-group {
display: flex;
gap: 10px;
align-items: center;
}
.form-check-group {
display: flex;
align-items: center;
gap: 8px;
margin-top: 5px;
padding: 0;
font-size: 14px;
color: #444;
min-width: unset;
max-width: fit-content;
.modal-actions {
margin-top: 20px;
display: flex;
justify-content: flex-end;
gap: 10px;
}
.btn-save {
background: var(--cor-fundo-botao-salvar);
color: #fff;
font-size: 14px;
padding: 8px 15px;
}
.btn-cancel {
background: var(--cor-cinza-medio);
color: #333;
font-size: 14px;
padding: 8px 15px;
}
.btn-save:hover {
background: var(--cor-hover-salvar);
}
.btn-cancel:hover {
background: #b3b3b3;
}
.btn-edit,
.btn-delete {
padding: 5px 10px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 14px;
background-color: lightgrey;
color: #000;
transition: background-color 0.2s;
}
.btn-edit:hover,
.btn-delete:hover {
background-color: #d3d3d3;
}
/* Tabela de pacientes */
.paciente-table {
width: 95%; /* Use a largura da tela disponível */
margin: 20px auto;
border-collapse: collapse;
background-color: var(--bg-modal);
border-radius: 10px;
overflow: hidden;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.paciente-table th,
.paciente-table td {
padding: 12px 15px; /* Aumentei o padding para dar mais espaço */
text-align: left;
border-bottom: 1px solid #ddd;
font-size: 15px; /* Ajustei o tamanho da fonte */
white-space: nowrap; /* Impede que o texto quebre para a próxima linha */
overflow: hidden;
text-overflow: ellipsis; /* Adiciona "..." se o texto for muito longo */
}
.paciente-table th {
background-color: var(--cor-tabela-header);
font-weight: bold;
color: #555;
text-transform: uppercase; /* Transforma o texto do cabeçalho em maiúsculas */
}
/* Deixa a tabela responsiva para dispositivos menores */
@media (max-width: 768px) {
.paciente-table {
display: block;
overflow-x: auto; /* Adiciona uma barra de rolagem horizontal */
white-space: nowrap;
}
.paciente-table thead,
.paciente-table tbody,
.paciente-table th,
.paciente-table td,
.paciente-table tr {
display: block;
}
.paciente-table tr {
margin-bottom: 15px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.paciente-table td {
border-bottom: 1px solid #eee;
position: relative;
padding-left: 50%;
text-align: right;
}
.paciente-table td::before {
content: attr(data-label);
position: absolute;
left: 0;
width: 50%;
padding-left: 15px;
font-weight: bold;
text-align: left;
}
}
@keyframes fadeIn {
from {
opacity: 0;
transform: scale(0.95);
}
to {
opacity: 1;
transform: scale(1);
}
}
}
/* Container de formulário para a nova página - AGORA OCUPARÁ A LARGURA TOTAL */
.full-page-form-container {
width: 95%;
margin: 20px auto;
padding: 30px;
background-color: var(--bg-modal);
border-radius: 10px;
box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
box-sizing: border-box;
}
/* Divisores de Seção (Endereço, etc) */
.section-divider {
font-size: 1.2em;
font-weight: bold;
color: #444;
margin: 35px 0 20px;
border-bottom: 1px solid #ccc;
padding-bottom: 8px;
}
/* Ajustes para a grade */
.form-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 20px 30px;
}
.form-grid .span-2 {
grid-column: span 2;
}
/* Estilos de input e select uniformes */
.form-group input,
.form-group select {
padding: 10px;
height: 40px;
border-radius: 8px;
border: 1px solid var(--cor-cinza-medio);
font-size: 16px;
outline: none;
width: 100%;
}
.form-group input:focus,
.form-group select:focus {
border-color: var(--cor-borda-input-foco);
box-shadow: 0 0 5px rgba(46, 125, 50, 0.3);
}
/* Campos de largura total */
.form-group.full-width {
grid-column: 1 / -1;
}
/* Estilo para a área de texto de Observações */
textarea {
resize: vertical;
width: 100%;
min-height: 100px;
padding: 10px;
border-radius: 8px;
border: 1px solid var(--cor-cinza-medio);
font-size: 16px;
outline: none;
box-sizing: border-box;
}
textarea:focus {
border-color: var(--cor-borda-input-foco);
box-shadow: 0 0 5px rgba(46, 125, 50, 0.3);
}
/* Estilo para o campo de upload de arquivo */
.form-group input[type="file"] {
background-color: var(--cor-cinza-claro);
border: 1px dashed var(--cor-cinza-medio);
padding: 10px;
height: auto;
cursor: pointer;
}
/* Outros estilos, como h2, labels, buttons etc., que já estão na sua folha de estilo */
.form-card h2 {
margin-bottom: 25px;
font-size: 24px;
color: #333;
border-bottom: 1px solid #eee;
padding-bottom: 15px;
}
.form-group label {
font-weight: 600;
font-size: 14px;
margin-bottom: 6px;
color: #444;
}
.form-actions {
margin-top: 40px;
display: flex;
justify-content: flex-end;
gap: 20px;
}
.form-actions .btn {
text-decoration: none;
color: #fff;
padding: 12px 22px;
border-radius: 8px;
font-size: 16px;
cursor: pointer;
transition: background-color 0.2s;
}
.form-actions .btn-save {
background: var(--cor-fundo-botao-salvar);
}
.form-actions .btn-cancel {
background: #ccc;
color: #333;
}
.form-actions .btn-save:hover {
background: #256628;
}
.form-actions .btn-cancel:hover {
background: #b3b3b3;
}
/* Estilos gerais do corpo para melhor visualização */
body {
font-family: Arial, sans-serif;
background-color: #f0f2f5;
margin: 0;
padding: 0;
}
/* Container principal para centralizar o conteúdo */
.flex {
display: flex;
min-height: 100vh;
}
/* Estilos para a seção principal, para ocupar o espaço restante */
.section-main {
flex-grow: 1; /* Ocupa todo o espaço restante */
padding: 20px;
background-color: #f8f9fa;
}
/* Estilos para o botão de adicionar paciente */
.btn-add {
display: inline-block;
padding: 10px 20px;
background-color: #007bff;
color: white;
text-decoration: none;
border-radius: 5px;
margin-bottom: 20px;
transition: background-color 0.3s ease;
}
.btn-add:hover {
background-color: #0056b3;
}
/* Estilos da tabela de pacientes */
.paciente-table {
width: 100%;
border-collapse: collapse;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
background-color: white;
border-radius: 8px;
overflow: hidden;
}
.paciente-table th,
.paciente-table td {
padding: 12px 15px;
text-align: left;
border-bottom: 1px solid #ddd;
}
.paciente-table thead th {
background-color: #e9ecef;
font-weight: bold;
color: #495057;
text-transform: uppercase;
font-size: 14px;
}
/* Estilizando as linhas da tabela */
.paciente-table tbody tr:hover {
background-color: #f1f1f1;
}
/* Estilos para os botões de ação na tabela */
.btn-edit,
.btn-delete {
padding: 6px 10px;
border: none;
border-radius: 4px;
color: white;
cursor: pointer;
font-size: 12px;
transition: background-color 0.3s ease;
}
.btn-edit {
background-color: #28a745;
}
.btn-edit:hover {
background-color: #218838;
}
.btn-delete {
background-color: #dc3545;
}
.btn-delete:hover {
background-color: #c82333;
}
/* Estilos para dispositivos móveis (responsividade) */
@media (max-width: 768px) {
.paciente-table,
.paciente-table tbody,
.paciente-table tr,
.paciente-table td {
display: block;
width: 100%;
}
.paciente-table thead {
display: none; /* Esconde o cabeçalho em telas pequenas */
}
.paciente-table tr {
margin-bottom: 15px;
border: 1px solid #ddd;
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.paciente-table td {
text-align: right;
padding-left: 50%; /* Espaço para o rótulo */
position: relative;
}
.paciente-table td::before {
content: attr(data-label);
position: absolute;
left: 10px;
width: 45%;
text-align: left;
font-weight: bold;
color: #555;
}
}
/* Estilos Gerais para o Corpo da Página */
body {
margin: 0;
font-family: Arial, sans-serif;
background-color: #f0f2f5;
}
/* Container Flex principal (sidebar + conteúdo) */
.flex-container {
display: flex;
min-height: 100vh;
}
/* Estilo da Sidebar */
.sidebar {
width: 80px;
background-color: #fff;
padding: 10px 0;
box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
display: flex;
flex-direction: column;
align-items: center;
}
.sidebar ul {
list-style: none;
padding: 0;
margin: 0;
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
}
.sidebar li {
margin-bottom: 20px;
}
.sidebar a {
display: block;
padding: 10px;
border-radius: 5px;
transition: background-color 0.3s ease;
}
.sidebar a:hover {
background-color: #e0e0e0;
}
.sidebar img {
width: 30px;
height: 30px;
display: block;
margin: 0 auto;
}
#logo-med {
width: 45px;
height: 45px;
margin-bottom: 30px;
}
/* Área de Conteúdo Principal (que contém o Header e o main-content) */
.content-area {
flex-grow: 1;
display: flex;
flex-direction: column;
}
/* Estilo do Header */
.header {
background-color: #fff;
padding: 10px 20px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
display: flex;
justify-content: space-between;
align-items: center;
height: 60px;
}
.search-bar {
display: flex;
align-items: center;
border: 1px solid #ccc;
border-radius: 20px;
padding: 5px 10px;
background-color: #f8f8f8;
}
.search-bar input {
border: none;
outline: none;
padding: 5px;
background-color: transparent;
width: 200px;
}
.search-bar button {
background: none;
border: none;
cursor: pointer;
padding: 0 5px;
}
.search-bar button img {
width: 20px;
height: 20px;
}
.header-icons img {
width: 24px;
height: 24px;
margin-left: 20px;
cursor: pointer;
}
/* Estilos para o Conteúdo Principal (abaixo do header) */
.main-content {
flex-grow: 1;
padding: 20px;
overflow-y: auto;
}
/* Estilos para o botão "Cadastrar Paciente" */
.btn-add {
display: inline-block;
background-color: #007bff;
color: #fff;
padding: 10px 15px;
border-radius: 5px;
text-decoration: none;
font-weight: bold;
margin-bottom: 20px;
transition: background-color 0.3s ease;
}
.btn-add:hover {
background-color: #0056b3;
}
/* Estilos da Tabela */
.table-container {
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.paciente-table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
.paciente-table thead th {
background-color: #f2f2f2;
padding: 12px 15px;
text-align: left;
border-bottom: 2px solid #ddd;
}
.paciente-table tbody td {
padding: 10px 15px;
border-bottom: 1px solid #eee;
}
.paciente-table tbody tr:hover {
background-color: #f9f9f9;
}
.btn {
padding: 8px 12px;
border: none;
border-radius: 4px;
cursor: pointer;
margin-right: 5px;
transition: background-color 0.3s ease;
}
/* As cores dos botões de ação foram mantidas como estavam na sua versão anterior */
.btn-edit {
background-color: #08c547;
color: white;
}
.btn-edit:hover {
background-color: #087904;
}
.btn-delete {
background-color: #dc3545;
color: #fff;
}
.btn-delete:hover {
background-color: #b31a29;
}
/* Estilos para a página de cadastro */
.section-cadastro {
background-color: #fff;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
max-width: 600px;
margin: 20px auto;
}
.section-cadastro h2 {
text-align: center;
color: #333;
margin-bottom: 25px;
}
.section-cadastro form label {
display: block;
margin-bottom: 8px;
font-weight: bold;
color: #555;
}
.section-cadastro form input[type="text"],
.section-cadastro form input[type="tel"] {
width: calc(100% - 20px);
padding: 10px;
margin-bottom: 20px;
border: 1px solid #ddd;
border-radius: 4px;
box-sizing: border-box;
}
.section-cadastro form button {
width: 100%;
padding: 12px;
background-color: #28a745;
color: white;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.section-cadastro form button:hover {
background-color: #218838;
}
.btn-back {
display: inline-block;
margin-bottom: 20px;
color: #007bff;
text-decoration: none;
font-weight: bold;
font-size: 16px;
}
.btn-back:hover {
text-decoration: underline;
}
/* Media Queries para Responsividade */
@media (max-width: 768px) {
.sidebar {
width: 60px;
}
.sidebar img {
width: 24px;
height: 24px;
}
#logo-med {
width: 40px;
height: 40px;
}
.header {
flex-direction: column;
height: auto;
padding: 10px;
}
.search-bar {
width: 90%;
margin-bottom: 10px;
}
.header-icons {
margin-top: 10px;
}
.header-icons img {
margin: 0 10px;
}
.paciente-table thead {
display: none;
}
.paciente-table tbody tr {
display: block;
margin-bottom: 10px;
border: 1px solid #ddd;
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}
.paciente-table tbody td {
display: block;
text-align: right;
padding-left: 50%;
position: relative;
font-size: 14px;
}
.paciente-table tbody td::before {
content: attr(data-label);
position: absolute;
left: 15px;
width: 45%;
text-align: left;
font-weight: bold;
}
}

View File

@ -0,0 +1,214 @@
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cadastro de Médico</title>
<link rel="stylesheet" href="./addMedico.css">
<link rel="stylesheet" href="/Squad-21/clinicApp/global.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300" rel="stylesheet">
<link rel="stylesheet" href="/Squad-21/clinicApp/assets/style/bootstrap.css">
</head>
<body>
<main>
<div class="flex">
<section class="section-main">
<nav class="nav">
</nav>
<div class="full-page-form-container">
<div class="form-card">
<h2>Dados do Paciente</h2>
<form id="cadastro-form">
<div class="form-grid">
<div class="form-group"><label for="nome">Nome *</label><input type="text" id="nome"
required></div>
<div class="form-group"><label for="nomeSocial">Nome Social</label><input type="text"
id="nomeSocial"></div>
<div class="form-group">
<label for="cpf">CPF *</label>
<input type="text" id="cpf" placeholder="000.000.000-00" required>
</div>
<div class="form-group">
<label for="cpf">CRM *</label>
<input type="text" id="cpf" placeholder="000.000.000-00" required>
</div>
<div class="form-group">
<label for="outrosDocs">Outros documentos de identidade</label>
<select id="outrosDocs">
<option value="">Selecione</option>
<option value="Passaporte">Passaporte</option>
<option value="CNH">CNH</option>
</select>
</div>
<div class="form-group"><label for="numDoc">Número do documento</label><input
type="text" id="numDoc" placeholder="Número do documento"></div>
<div class="form-group">
<label for="sexo">Sexo *</label>
<select id="sexo" name="sexo" required>
<option value="">Selecione</option>
<option value="Masculino">Masculino</option>
<option value="Feminino">Feminino</option>
<option value="Feminino">Prefiro Não Informar</option>
</select>
</div>
<div class="form-group"><label for="dataNascimento">Data de Nascimento *</label><input
type="date" id="dataNascimento" required></div>
<div class="form-group">
<label for="etnia">Etnia</label>
<select id="etnia">
<option value="">Selecione</option>
<option value="branca">Branca</option>
<option value="preta">Preta</option>
<option value="parda">Parda</option>
<option value="amarela">Amarela</option>
<option value="indigena">Indígena</option>
</select>
</div>
<div class="form-group">
<label for="raca">Raça</label>
<select id="raca">
<option value="">Selecione</option>
<option value="branca">Branca</option>
<option value="preta">Preta</option>
<option value="parda">Parda</option>
<option value="amarela">Amarela</option>
<option value="indigena">Indígena</option>
</select>
</div>
<div class="form-group">
<label for="naturalidade">Naturalidade</label>
<input type="text" id="naturalidade">
</div>
<div class="form-group">
<label for="nacionalidade">Nacionalidade</label>
<input type="text" id="nacionalidade">
</div>
<div class="form-group"><label for="profissao">Profissão</label><input type="text"
id="profissao"></div>
<div class="form-group">
<label for="estadoCivil">Estado Civil</label>
<select id="estadoCivil">
<option value="">Selecione</option>
<option value="solteiro">Solteiro(a)</option>
<option value="casado">Casado(a)</option>
<option value="divorciado">Divorciado(a)</option>
<option value="viuvo">Viúvo(a)</option>
<option value="separado">Separado(a)</option>
</select>
</div>
<div class="form-group">
<label for="nomeMae">Nome da mãe</label>
<input type="text" id="nomeMae">
</div>
<div class="form-group">
<label for="nomePai">Nome do pai</label>
<input type="text" id="nomePai">
</div>
<div class="form-group">
<label for="nomeEsposo">Nome do(a) esposo(a)</label>
<input type="text" id="nomeEsposo">
</div>
</div>
<div class="section-divider">Endereço</div>
<div class="form-grid">
<div class="form-group">
<label for="cep">CEP *</label>
<input type="text" id="cep" required placeholder="00000-000">
</div>
<div class="form-group span-2">
<label for="endereco">Endereço</label>
<input type="text" id="endereco">
</div>
<div class="form-group">
<label for="numero">Número</label>
<input type="text" id="numero">
</div>
<div class="form-group">
<label for="complemento">Complemento</label>
<input type="text" id="complemento">
</div>
<div class="form-group">
<label for="bairro">Bairro</label>
<input type="text" id="bairro">
</div>
<div class="form-group">
<label for="cidade">Cidade</label>
<input type="text" id="cidade">
</div>
<div class="form-group">
<label for="estado">Estado
<label>
<select id="estado">
<option value="">Selecione</option>
<option value="AC">Acre</option>
<option value="AL">Alagoas</option>
<option value="AP">Amapá</option>
<option value="AM">Amazonas</option>
<option value="BA">Bahia</option>
<option value="CE">Ceará</option>
<option value="DF">Distrito Federal</option>
<option value="ES">Espírito Santo</option>
<option value="GO">Goiás</option>
<option value="MA">Maranhão</option>
<option value="MT">Mato Grosso</option>
<option value="MS">Mato Grosso do Sul</option>
<option value="MG">Minas Gerais</option>
<option value="PA">Pará</option>
<option value="PB">Paraíba</option>
<option value="PR">Paraná</option>
<option value="PE">Pernambuco</option>
<option value="PI">Piauí</option>
<option value="RJ">Rio de Janeiro</option>
<option value="RN">Rio Grande do Norte</option>
<option value="RS">Rio Grande do Sul</option>
<option value="RO">Rondônia</option>
<option value="RR">Roraima</option>
<option value="SC">Santa Catarina</option>
<option value="SP">São Paulo</option>
<option value="SE">Sergipe</option>
<option value="TO">Tocantins</option>
</select>
</div>
</div>
<div class="section-divider">Contato</div>
<div class="form-grid">
<div class="form-group">
<label for="email">E-mail *</label>
<input type="email" id="email" required placeholder="email@hotmail.com">
</div>
<div class="form-group">
<label for="celular">Celular *</label>
<input type="text" id="celular" placeholder="(00) 00000-0000" required>
</div>
<div class="form-group">
<label for="telefone1">Telefone</label>
<input type="text" id="telefone1" placeholder="(00) 0000-0000">
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-save">Salvar</button>
<a href="../crud-medico.html" class="btn btn-cancel">Voltar</a>
</div>
</form>
</div>
</div>
</section>
</div>
</main>
<script src="https://cdn.jsdelivr.net/npm/inputmask@5.0.9/dist/inputmask.min.js"></script>
<script defer src="/Squad-21/clinicApp/pages-visao-clinica/medicos/addMedico/addMedico.js"></script>
</body>
</html>

View File

@ -0,0 +1,118 @@
document.addEventListener("DOMContentLoaded", () => {
const form = document.getElementById("cadastro-form");
// Pega o ID do paciente da URL. Se não houver, 'editId' será null.
const urlParams = new URLSearchParams(window.location.search);
const editId = urlParams.get("id");
function desativarFormulario() {
// Desativa todos os inputs, selects e textareas
form.querySelectorAll("input, select, textarea").forEach((el) => {
el.disabled = true;
});
// Remove o botão de submit
const submitBtn = form.querySelector('[type="submit"]');
if (submitBtn) {
submitBtn.remove();
}
}
// Exemplo: se a URL tiver ?mode=detalhes
if (window.location.search.includes("mode=detalhes")) {
desativarFormulario();
}
if (form) {
// Carrega a lista de pacientes
let medicos = JSON.parse(localStorage.getItem("medicos")) || [];
let medicoParaEditar = null;
// Se houver um ID de edição na URL, encontra o medico correspondente
if (editId) {
medicoParaEditar = medicos.find((p) => p.id == editId);
if (medicoParaEditar) {
// Preenche o formulário com os dados do medico para edição
document.getElementById("nome").value = medicoParaEditar.nome;
document.getElementById("celular").value = medicoParaEditar.celular;
document.getElementById("cidade").value = medicoParaEditar.cidade;
document.getElementById("estado").value = medicoParaEditar.estado;
document.getElementById("nomeSocial").value = medicoParaEditar.nomeSocial;
document.getElementById("cpf").value = medicoParaEditar.cpf;
document.getElementById("outrosDocs").value = medicoParaEditar.outrosDocs;
document.getElementById("numDoc").value = medicoParaEditar.numDoc;
document.getElementById("sexo").value = medicoParaEditar.sexo;
document.getElementById("dataNascimento").value = medicoParaEditar.dataNascimento;
document.getElementById("cep").value = medicoParaEditar.cep;
document.getElementById("etnia").value = medicoParaEditar.etnia;
document.getElementById("raca").value = medicoParaEditar.raca;
document.getElementById("nacionalidade").value = medicoParaEditar.nacionalidade;
document.getElementById("estadoCivil").value = medicoParaEditar.estadoCivil;
document.getElementById("nomeMae").value = medicoParaEditar.nomeMae;
document.getElementById("nomePai").value = medicoParaEditar.nomePai;
document.getElementById("nomeEsposo").value = medicoParaEditar.nomeEsposo;
document.getElementById("endereco").value = medicoParaEditar.endereco;
document.getElementById("numero").value = medicoParaEditar.numero;
document.getElementById("complemento").value = medicoParaEditar.complemento;
document.getElementById("bairro").value = medicoParaEditar.bairro;
document.getElementById("email").value = medicoParaEditar.email;
document.getElementById("telefone1").value = medicoParaEditar.telefone1;
}
}
const cpf = document.getElementById("cpf");
const telefone = document.getElementById("telefone1");
const celular = document.getElementById("celular");
// Aplique as máscaras
new Inputmask("999.999.999-99").mask(cpf);
new Inputmask("(99) 99999-9999").mask(celular);
new Inputmask("(99) 9999-9999").mask(telefone);
form.addEventListener("submit", (e) => {
e.preventDefault();
// Coletando os dados do formulário
const medicoNovoOuAtualizado = {
nome: document.getElementById("nome").value,
celular: document.getElementById("celular").value,
cidade: document.getElementById("cidade").value,
estado: document.getElementById("estado").value,
nomeSocial: document.getElementById("nomeSocial").value,
cpf: document.getElementById("cpf").value.replace(/[.\-]/g, ""),
outrosDocs: document.getElementById("outrosDocs").value,
numDoc: document.getElementById("numDoc").value,
sexo: document.getElementById("sexo").value,
dataNascimento: document.getElementById("dataNascimento").value,
etnia: document.getElementById("etnia").value,
raca: document.getElementById("raca").value,
nacionalidade: document.getElementById("nacionalidade").value,
estadoCivil: document.getElementById("estadoCivil").value,
nomeMae: document.getElementById("nomeMae").value,
nomePai: document.getElementById("nomePai").value,
nomeEsposo: document.getElementById("nomeEsposo").value,
endereco: document.getElementById("endereco").value,
numero: document.getElementById("numero").value,
complemento: document.getElementById("complemento").value,
bairro: document.getElementById("bairro").value,
email: document.getElementById("email").value,
telefone1: document.getElementById("telefone1").value,
};
if (medicoParaEditar) {
// Se for um medico para editar, atualiza os dados dele
Object.assign(medicoParaEditar, medicoNovoOuAtualizado);
} else {
// Se for um novo medico, cria um ID único e o adiciona à lista
medicoNovoOuAtualizado.id = Date.now();
medicos.push(medicoNovoOuAtualizado);
}
// Salva a lista atualizada de volta no localStorage
localStorage.setItem("medicos", JSON.stringify(medicos));
// Redireciona para a página de listagem
window.location.href = "../crud-medico.html";
});
}
});

View File

@ -0,0 +1,450 @@
/* Estilos para o container principal do CRUD */
.crud-wrapper {
display: flex;
gap: 30px;
align-items: flex-start;
margin-top: 20px;
}
.crud-header h1 {
font-weight: 600;
color: #333;
}
.crud-header p {
color: #666;
font-size: 1rem;
}
/* Estilos do Formulário */
.form-container {
background-color: #ffffff;
padding: 25px;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
flex: 1;
min-width: 300px;
}
.form-container h2 {
margin-bottom: 20px;
font-weight: 500;
font-size: 1.2rem;
color: #007bff;
border-bottom: 1px solid #dee2e6;
padding-bottom: 10px;
}
.input-group {
margin-bottom: 15px;
}
.input-group label {
display: block;
margin-bottom: 5px;
font-weight: 500;
font-size: 14px;
}
.input-group input,
.input-group select {
width: 100%;
padding: 10px;
border-radius: 5px;
border: 1px solid #ccc;
font-family: 'Poppins', sans-serif;
font-size: 0.95rem;
transition: all 0.2s ease-in-out;
}
.input-group input:focus,
.input-group select:focus {
outline: none;
border-color: #007bff;
box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.2);
}
.button-group {
display: flex;
gap: 10px;
margin-top: 20px;
}
.button-group button {
padding: 10px 15px;
border: none;
border-radius: 5px;
cursor: pointer;
font-family: 'Poppins', sans-serif;
font-size: 1rem;
font-weight: 500;
transition: all 0.2s;
flex: 1;
}
.btn-primary {
background-color: #007bff;
color: white;
}
.btn-primary:hover {
background-color: #0056b3;
transform: translateY(-2px);
}
.btn-secondary {
background-color: #6c757d;
color: white;
}
.btn-secondary:hover {
background-color: #5a6268;
}
/* Estilos da Tabela */
.table-container {
background-color: #ffffff;
padding: 25px;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
flex: 2;
}
.table-container h2 {
margin-bottom: 20px;
font-weight: 500;
}
.table-wrapper {
overflow-x: auto;
/* Garante que a tabela seja rolável em telas pequenas */
}
table {
width: 100%;
border-collapse: collapse;
}
th,
td {
padding: 12px 15px;
text-align: left;
border-bottom: 1px solid #dee2e6;
vertical-align: middle;
}
thead th {
background-color: #f8f9fa;
font-weight: 600;
}
tbody tr:hover {
background-color: #f1f3f5;
}
td .btn-action {
padding: 6px 10px;
font-size: 14px;
margin-right: 5px;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: opacity 0.2s;
}
td .btn-action:hover {
opacity: 0.85;
}
.btn-edit {
background-color: #28a745;
}
.btn-delete {
background-color: #dc3545;
color: #fff;
}
.btn-delete:hover {
background-color: #c82333;
}
.btn-edit:hover {
background-color: #218838;
}
/* Responsividade para o conteúdo do CRUD */
@media (max-width: 992px) {
.crud-wrapper {
flex-direction: column;
}
}
/* força exibição do btn-primary caso haja override */
.btn-primary {
display: inline-block !important;
}
/* espaçamento e alinhamento dos botões */
.button-group {
margin-top: 1.5rem;
display: flex;
justify-content: flex-end;
gap: 1rem;
}
body {
background-color: #f8f9fa;
}
.crud-header {
padding: 2rem 1rem;
margin: 1rem;
background: linear-gradient(135deg, #0d6efd, #6610f2);
color: rgb(251, 250, 250);
border-radius: 0.5rem;
margin-bottom: 2rem;
}
.crud-header h1 {
font-size: 2rem;
color: white;
}
.crud-header p {
font-size: 1.1rem;
color: #e0e0e0;
}
.filtros {
display: flex;
align-items: center;
justify-content: start;
margin-bottom: 1rem;
}
.btn-add {
margin-bottom: 1rem;
}
.table-container {
overflow-x: auto;
}
table {
min-width: 600px;
}
.main-button button {
font-size: 17px;
background: none;
margin-right: 30px;
margin-top: 10px;
border: none;
color: #243b51;
padding: 20px 10px;
border-bottom: 2px solid transparent;
transition: 0.6s;
}
.main-button-border:hover {
/*estilo no mouseenter*/
border: none;
margin-right: 30px;
margin-top: 10px;
padding: 20px 10px;
background: none;
border-bottom: 2px solid blue;
color: blue;
}
.btn-add {
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.2s;
margin: 20px 0px;
background-color: rgb(38, 137, 255);
color: #fff;
text-decoration: none;
}
.btn-add:hover {
background-color: rgb(30, 110, 204);
}
.filter-select {
padding: 8px;
margin-left: 8px;
border: 1px solid #ccc;
border-radius: 5px;
background-color: white;
font-size: 14px;
cursor: pointer;
}
.conteudo {
margin-left: 30px;
background-color: #fafafa;
padding: 25px;
border-radius: 7px;
}
/* Tabela */
#pacientes-tabela {
margin-top: 1.5rem;
width: 100%;
border-collapse: collapse;
border: 1px solid #ddd;
background-color: white;
font-size: 14px;
border-radius: 8px;
overflow: hidden;
}
#pacientes-tabela thead {
background-color: #e9ecef;
}
#pacientes-tabela thead th {
padding: 12px;
border-bottom: 1px solid #ccc;
text-align: left;
font-weight: bold;
}
#pacientes-tabela tbody td {
padding: 10px;
border-bottom: 1px solid #eee;
}
#pacientes-tabela tbody tr:hover {
background-color: #f1f1f1;
}
#pacientes-tabela tbody td button {
padding: 6px 10px;
font-size: 14px;
background-color: #6c757d;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
#pacientes-tabela tbody td button:hover {
background-color: #5a6268;
}
/* Media queries melhoradas para responsividade */
@media (max-width: 768px) {
/* Melhor organização do conteúdo principal em mobile */
.section-main-text {
padding: 20px;
padding-bottom: 0px;
margin-top: 10rem;
}
.section-main-text h1 {
font-size: 28px;
margin-bottom: 10px;
}
.section-main-text p {
font-size: 16px;
}
.main-button {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.main-button button {
margin-right: 0;
margin-top: 5px;
padding: 15px 8px;
font-size: 15px;
}
.conteudo {
margin: 20px;
padding: 20px;
}
/* Formulário responsivo */
#formLaudo {
flex-direction: column;
gap: 15px;
}
#formLaudo fieldset {
width: 100%;
}
#formLaudo button[type="submit"] {
width: 100%;
padding: 12px;
font-size: 16px;
}
/* Tabela responsiva com scroll horizontal */
.table-container {
overflow-x: auto;
margin-top: 20px;
}
#pacientes-tabela {
min-width: 600px;
font-size: 12px;
}
#pacientes-tabela thead th,
#pacientes-tabela tbody td {
padding: 8px;
white-space: nowrap;
}
}
/* Media query para tablets */
@media (max-width: 1024px) and (min-width: 769px) {
.section-main-text h1 {
font-size: 32px;
}
.conteudo {
margin: 25px;
}
}
/* Media query melhorada para telas muito pequenas */
@media (max-width: 480px) {
.section-main-text {
padding: 15px;
}
.section-main-text h1 {
font-size: 24px;
}
.section-main-text p {
font-size: 14px;
}
.conteudo {
margin: 15px;
padding: 15px;
}
#pacientes-tabela {
font-size: 11px;
}
#pacientes-tabela thead th,
#pacientes-tabela tbody td {
padding: 6px;
}
}

View File

@ -0,0 +1,164 @@
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Gestão de Médicos</title>
<link rel="stylesheet" href="/Squad-21/clinicApp/global.css" />
<link rel="stylesheet" href="./crud-medico.css" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/Squad-21/clinicApp/assets/style/bootstrap.css">
</head>
<body>
<main>
<div class="overlay" id="overlay"></div>
<div class="flex">
<button class="hamburger-btn" id="hamburger-btn" aria-label="Abrir menu de navegação" aria-expanded="false">
<span></span>
<span></span>
<span></span>
</button>
<section class="sidebar" id="sidebar" role="navigation" aria-label="Menu principal">
<div class="div-sidebar">
<div class="abas">
<a href="#" aria-label="Página inicial" class="logo1">
<img src="https://images.vexels.com/media/users/3/142777/isolated/preview/84711206e52e0d4ff6c793cb476ea264-logotipo-medico-da-estrela-do-heartbeat.png"
alt="Logo médico" id="logo-med" />
</a>
<ul>
<li>
<a href="#" aria-label="Pacientes">
<img src="/Squad-21/clinicApp/assets/layoutIcons/icons8-estetoscópio-50.png"
alt="Pacientes" class="icon-sidebar" />
<p>Pacientes</p>
</a>
</li>
<li>
<a href="#" aria-label="Dashboard">
<img src="/Squad-21/clinicApp/assets/layoutIcons/icons8-document.svg"
alt="Dashboard" class="icon-sidebar" />
<p>Dashboard</p>
</a>
</li>
<li class="active-item"> <a href="#" aria-label="Médicos">
<img src="/Squad-21/clinicApp/assets/layoutIcons/icons8-estetoscópio-50.png"
alt="Médicos" class="icon-sidebar" />
<p>Médicos</p>
</a>
</li>
<li>
<a href="#" aria-label="Laudos">
<img src="https://i.imgur.com/Y8bXQ1E.png" alt="Laudos" class="icon-sidebar" />
<p>Laudos</p>
</a>
</li>
<li>
<a href="#" aria-label="Agenda">
<img src="https://i.imgur.com/Q3T6sN0.png" alt="Agenda" class="icon-sidebar" />
<p>Agenda</p>
</a>
</li>
<li>
<a href="#" aria-label="Configurações">
<img src="/Squad-21/clinicApp/assets/layoutIcons/icons8-configurações.svg"
alt="Configurações" class="icon-sidebar" />
<p>Settings</p>
</a>
</li>
</ul>
</div>
<div class="perfil-medico-sidebar">
<h3>Dr. Rafael Andrade</h3>
<p>Núcleo de Especialidades</p>
</div>
</div>
</section>
<section class="section-main">
<nav class="nav" role="banner">
<!-- <div class="div-search">
<input type="text" class="search-input" placeholder="Buscar médico..."
aria-label="Campo de busca" />
<button class="search-button" aria-label="Buscar">
<img src="/Squad-21/clinicApp/assets/layoutIcons/icons8-pesquisar.svg" alt="Buscar" />
</button>
</div> -->
<div>
<ul class="icon-lista">
<li>
<a href="#" aria-label="Ajuda"><img src="https://i.imgur.com/o2ba23i.png"
alt="Ajuda" /></a>
</li>
<li>
<button id="music" aria-label="Notificações"><img src="https://i.imgur.com/1BTRaKI.png"
alt="Notificações" /></button>
</li>
<li>
<a href="#" aria-label="Perfil do usuário"><img src="https://i.imgur.com/so83EaA.png"
alt="Usuário" /></a>
</li>
</ul>
</div>
</nav>
<div class="main-contain">
<div class="crud-header">
<h1>Gestão de Médicos</h1>
<p>Adicione, visualize e gerencie os médicos da clínica.</p>
</div>
<div class="conteudo">
<a href="/Squad-21/clinicApp/pages-visao-clinica/medicos/addMedico/addMedico.html" id="btn-add2"
class="btn-add"> + Cadastrar Médico </a>
<div class="filtros">
<div class="div-search">
<input type="text" id="search-input" class="search-input" placeholder="Buscar médico..."
aria-label="Campo de busca" />
<button id="search-button" class="search-button" aria-label="Buscar">
<img src="../../assets/layoutIcons/icons8-pesquisar.svg" alt="Buscar" />
</button>
</div>
<select id="filter-type" class="filter-select">
<option value="geral">Geral</option>
<option value="nome">Nome</option>
<option value="telefone">Celular</option>
<option value="cpf">CPF</option>
<option value="status">Status</option>
<option value="email">Email</option>
</select>
</div>
<!-- Container para scroll horizontal da tabela -->
<div class="table-container">
<table id="medicos-tabela">
<thead>
<tr>
<th>Nome</th>
<th>Telefone</th>
<th>CPF</th>
<th>Status</th>
<th>Ação</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</section>
</div>
</main>
<script src="/Squad-21/clinicApp/scriptGlobal.js"></script>
<script src="./crud-medico.js"></script>
</body>
</html>

View File

@ -0,0 +1,329 @@
// document.addEventListener("DOMContentLoaded", () => {
// const tabelaMedicos = document.getElementById("medicos-tabela");
// const tbody = tabelaMedicos?.querySelector("tbody");
// const searchInput = document.getElementById("search-input");
// const filterType = document.getElementById("filter-type");
// const searchButton = document.getElementById("search-button");
// let pageAtual = 1;
// const itensPorPagina = 10;
// let carregando = false;
// let buscaAtiva = false;
// let termoBusca = "";
// let tipoBusca = "geral";
// const renderizarLote = (medicos) => {
// medicos.forEach((medico) => {
// const row = document.createElement("tr");
// row.innerHTML = `
// <td>${medico.nome || "-"}</td>
// <td>${medico.telefone || "-"}</td>
// <td>${medico.cpf || "-"}</td>
// <td>${medico.status || "-"}</td>
// <td>
// <button class="btn btn-edit" data-id="${medico.id}">Editar</button>
// <button class="btn btn-detail" data-id="${medico.id}">Detalhes</button>
// <button class="btn btn-delete" data-id="${medico.id}">Excluir</button>
// </td>
// `;
// tbody.appendChild(row);
// });
// adicionarEventos();
// };
// const carregarMedicosDaAPI = async () => {
// if (carregando) return;
// carregando = true;
// try {
// const response = await fetch(`https://mock.apidog.com/m1/1053378-0-default/pacientes?page=${pageAtual}&limit=${itensPorPagina}`);
// const json = await response.json();
// const novosMedicos = Array.isArray(json.data) ? json.data : [];
// console.log(novosMedicos)
// if (buscaAtiva && termoBusca.trim()) {
// const termo = termoBusca.toLowerCase();
// const filtrados = novosMedicos.filter((medico) => {
// if (tipoBusca === "geral") {
// return (
// (medico.nome || "").toLowerCase().includes(termo) ||
// (medico.telefone || "").toLowerCase().includes(termo) ||
// (medico.status || "").toLowerCase().includes(termo) ||
// (medico.email || "").toLowerCase().includes(termo) ||
// (medico.cpf || "").toLowerCase().includes(termo)
// );
// } else {
// return (medico[tipoBusca] || "").toLowerCase().includes(termo);
// }
// });
// renderizarLote(filtrados);
// } else {
// renderizarLote(novosMedicos);
// }
// pageAtual++;
// } catch (error) {
// console.error("Erro ao carregar médicos da API:", error);
// } finally {
// carregando = false;
// }
// };
// const aplicarFiltro = () => {
// tbody.innerHTML = "";
// pageAtual = 1;
// buscaAtiva = true;
// termoBusca = searchInput.value;
// tipoBusca = filterType.value;
// carregarMedicosDaAPI();
// };
// const adicionarEventos = () => {
// document.querySelectorAll(".btn-edit").forEach((btn) => {
// btn.addEventListener("click", (e) => {
// const id = e.target.dataset.id;
// window.location.href = `addMedico/addMedico.html?id=${id}`;
// });
// });
// document.querySelectorAll(".btn-detail").forEach((btn) => {
// btn.addEventListener("click", (e) => {
// const id = e.target.dataset.id;
// window.location.href = `addMedico/addMedico.html?mode=detalhes&id=${id}`;
// });
// });
// document.querySelectorAll(".btn-delete").forEach((btn) => {
// btn.addEventListener("click", async (e) => {
// const id = e.target.dataset.id;
// const confirmar = confirm("Tem certeza que deseja excluir este médico?");
// if (!confirmar) return;
// try {
// const response = await fetch(`https://mock.apidog.com/m1/1053378-0-default/pacientes/${id}`, {
// method: "DELETE"
// });
// if (response.ok) {
// e.target.closest("tr").remove();
// alert("Médico excluído com sucesso.");
// } else {
// alert("Erro ao excluir médico.");
// }
// } catch (error) {
// console.error("Erro na exclusão:", error);
// alert("Erro ao excluir médico.");
// }
// });
// });
// };
// window.addEventListener("scroll", () => {
// const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
// if (scrollTop + clientHeight >= scrollHeight - 5) {
// carregarMedicosDaAPI();
// }
// });
// searchButton.addEventListener("click", aplicarFiltro);
// searchInput.addEventListener("keyup", (e) => {
// if (e.key === "Enter") aplicarFiltro();
// });
// carregarMedicosDaAPI();
// });
document.addEventListener("DOMContentLoaded", () => {
const tabelaMedicos = document.getElementById("medicos-tabela");
const tbody = tabelaMedicos?.querySelector("tbody");
const searchInput = document.getElementById("search-input");
const filterType = document.getElementById("filter-type");
const searchButton = document.getElementById("search-button");
const token = "<token>"; // 🔐 Substitua pelo seu token real
let pageAtual = 1;
const itensPorPagina = 10;
let carregando = false;
let buscaAtiva = false;
let termoBusca = "";
let tipoBusca = "geral";
const renderizarLote = (medicos) => {
medicos.forEach((medico) => {
const row = document.createElement("tr");
row.innerHTML = `
<td>${medico.nome || "-"}</td>
<td>${medico.telefone || "-"}</td>
<td>${medico.cpf || "-"}</td>
<td>${medico.status || "-"}</td>
<td>
<button class="btn btn-edit" data-id="${medico.id}">Editar</button>
<button class="btn btn-detail" data-id="${medico.id}">Detalhes</button>
<button class="btn btn-delete" data-id="${medico.id}">Excluir</button>
</td>
`;
tbody.appendChild(row);
});
adicionarEventos();
};
const carregarMedicosDaAPI = async () => {
if (carregando) return;
carregando = true;
try {
const response = await fetch(`https://mock.apidog.com/m1/1053378-0-default/pacientes?page=${pageAtual}&limit=${itensPorPagina}`);
const json = await response.json();
const novosMedicos = Array.isArray(json.data) ? json.data : [];
if (buscaAtiva && termoBusca.trim()) {
const termo = termoBusca.toLowerCase();
const filtrados = novosMedicos.filter((medico) => {
if (tipoBusca === "geral") {
return (
(medico.nome || "").toLowerCase().includes(termo) ||
(medico.telefone || "").toLowerCase().includes(termo) ||
(medico.status || "").toLowerCase().includes(termo) ||
(medico.email || "").toLowerCase().includes(termo) ||
(medico.cpf || "").toLowerCase().includes(termo)
);
} else {
return (medico[tipoBusca] || "").toLowerCase().includes(termo);
}
});
renderizarLote(filtrados);
} else {
renderizarLote(novosMedicos);
}
pageAtual++;
} catch (error) {
console.error("Erro ao carregar médicos da API:", error);
} finally {
carregando = false;
}
};
const aplicarFiltro = () => {
tbody.innerHTML = "";
pageAtual = 1;
buscaAtiva = true;
termoBusca = searchInput.value;
tipoBusca = filterType.value;
carregarMedicosDaAPI();
};
// const adicionarEventos = () => {
// document.querySelectorAll(".btn-edit").forEach((btn) => {
// btn.addEventListener("click", (e) => {
// const id = e.target.dataset.id;
// window.location.href = `addMedico/addMedico.html?id=${id}`;
// });
// });
// document.querySelectorAll(".btn-detail").forEach((btn) => {
// btn.addEventListener("click", (e) => {
// const id = e.target.dataset.id;
// window.location.href = `addMedico/addMedico.html?mode=detalhes&id=${id}`;
// });
// });
// document.querySelectorAll(".btn-delete").forEach((btn) => {
// btn.addEventListener("click", async (e) => {
// const id = e.target.dataset.id;
// const confirmar = confirm("Tem certeza que deseja excluir este médico?");
// if (!confirmar) return;
// const myHeaders = new Headers();
// myHeaders.append("Authorization", `Bearer ${token}`);
// const requestOptions = {
// method: "DELETE",
// headers: myHeaders,
// redirect: "follow"
// };
// try {
// const response = await fetch(`https://mock.apidog.com/m1/1053378-0-default/pacientes/${id}`, requestOptions);
// if (response.ok) {
// e.target.closest("tr").remove();
// alert("Médico excluído com sucesso.");
// } else {
// alert("Erro ao excluir médico. Código: " + response.status);
// }
// } catch (error) {
// console.error("Erro na exclusão:", error);
// alert("Erro ao excluir médico.");
// }
// });
// });
// };
const adicionarEventos = () => {
tbody.addEventListener("click", async (e) => {
const btn = e.target;
const id = btn.dataset.id;
if (btn.classList.contains("btn-edit")) {
window.location.href = `addMedico/addMedico.html?id=${id}`;
}
if (btn.classList.contains("btn-detail")) {
window.location.href = `addMedico/addMedico.html?mode=detalhes&id=${id}`;
}
if (btn.classList.contains("btn-delete")) {
if (btn.disabled) return; // evita múltiplos cliques
const confirmar = confirm("Tem certeza que deseja excluir este médico?");
if (!confirmar) return;
btn.disabled = true;
btn.textContent = "Excluindo...";
const myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer <token>");
const requestOptions = {
method: "DELETE",
headers: myHeaders,
redirect: "follow"
};
try {
const response = await fetch(`https://mock.apidog.com/m1/1053378-0-default/pacientes/${id}`, requestOptions);
if (response.ok) {
btn.closest("tr").remove();
alert("Médico excluído com sucesso.");
} else {
alert("Erro ao excluir médico. Código: " + response.status);
}
} catch (error) {
console.error("Erro na exclusão:", error);
alert("Erro ao excluir médico.");
} finally {
btn.disabled = false;
btn.textContent = "Excluir";
}
}
});
};
window.addEventListener("scroll", () => {
const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
if (scrollTop + clientHeight >= scrollHeight - 5) {
carregarMedicosDaAPI();
}
});
searchButton.addEventListener("click", aplicarFiltro);
searchInput.addEventListener("keyup", (e) => {
if (e.key === "Enter") aplicarFiltro();
});
carregarMedicosDaAPI();
});

View File

@ -0,0 +1,117 @@
/* Container geral */
.crud-wrapper {
display: flex;
gap: 2rem;
flex-wrap: wrap;
}
/* Formulário */
.form-container {
flex: 1;
min-width: 280px;
background: #fff;
padding: 1.5rem;
border-radius: 8px;
box-shadow: var(--shadow);
}
.form-container h2 {
margin-bottom: 1rem;
color: var(--primary);
}
.input-group {
margin-bottom: 1rem;
}
.input-group label {
display: block;
margin-bottom: .3rem;
font-weight: 500;
}
.input-group input,
.input-group select {
width: 100%;
padding: .6rem;
border: 1px solid var(--gray-light);
border-radius: 4px;
}
/* Botões */
.button-group {
display: flex;
gap: 1rem;
}
.btn-primary {
background: var(--primary);
color: #fff;
border: none;
padding: .6rem 1.2rem;
border-radius: 4px;
cursor: pointer;
}
.btn-secondary {
background: var(--gray-light);
color: var(--text);
border: none;
padding: .6rem 1.2rem;
border-radius: 4px;
cursor: pointer;
}
/* Tabela */
.table-container {
flex: 2;
min-width: 320px;
background: #fff;
padding: 1.5rem;
border-radius: 8px;
box-shadow: var(--shadow);
}
.table-wrapper {
overflow-x: auto;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: .8rem;
text-align: left;
border-bottom: 1px solid var(--gray-light);
}
th {
background: var(--gray-bg);
}
.acoes button {
margin-right: .4rem;
padding: .3rem .6rem;
border: none;
border-radius: 4px;
cursor: pointer;
}
.acoes button:first-child {
background: var(--warning);
color: #fff;
}
.acoes button:last-child {
background: var(--danger);
color: #fff;
}
/* Responsividade */
@media(max-width: 768px) {
.crud-wrapper {
flex-direction: column;
}
}

View File

@ -0,0 +1,225 @@
// document.addEventListener('DOMContentLoaded', () => {
// const medicoForm = document.getElementById('medicoForm');
// const medicoIdInput = document.getElementById('medicoId');
// const nomeInput = document.getElementById('nome');
// const crmInput = document.getElementById('crm');
// const especialidadeInput = document.getElementById('especialidade');
// const telefoneInput = document.getElementById('telefone');
// const emailInput = document.getElementById('email');
// const statusInput = document.getElementById('status');
// const cancelarBtn = document.getElementById('cancelarBtn');
// const medicosTabelaBody = document.getElementById('medicosTabelaBody');
// let medicos = JSON.parse(localStorage.getItem('medicos')) || [];
// const salvarMedicos = () => {
// localStorage.setItem('medicos', JSON.stringify(medicos));
// };
// const renderizarTabela = () => {
// medicosTabelaBody.innerHTML = '';
// if (medicos.length === 0) {
// medicosTabelaBody.innerHTML = '<tr><td colspan="5" style="text-align:center;">Nenhum médico cadastrado.</td></tr>';
// return;
// }
// medicos.forEach(medico => {
// const tr = document.createElement('tr');
// tr.innerHTML = `
// <td>${medico.nome}</td>
// <td>${medico.crm}</td>
// <td>${medico.especialidade}</td>
// <td>${medico.status}</td>
// <td>
// <button class="btn-action btn-edit" data-crm="${medico.crm}">Editar</button>
// <button class="btn-action btn-delete" data-crm="${medico.crm}">Excluir</button>
// </td>
// `;
// medicosTabelaBody.appendChild(tr);
// });
// };
// const resetarFormulario = () => {
// medicoForm.reset();
// medicoIdInput.value = '';
// crmInput.disabled = false;
// cancelarBtn.style.display = 'none';
// };
// medicoForm.addEventListener('submit', (e) => {
// e.preventDefault();
// const id = medicoIdInput.value;
// const medico = {
// nome: nomeInput.value.trim(),
// crm: crmInput.value.trim(),
// especialidade: especialidadeInput.value,
// telefone: telefoneInput.value.trim(),
// email: emailInput.value.trim(),
// status: statusInput.value,
// };
// if (id) {
// const index = medicos.findIndex(m => m.crm === id);
// if (index !== -1) {
// medicos[index] = medico;
// }
// } else {
// if (medicos.some(m => m.crm === medico.crm)) {
// alert('CRM já cadastrado!');
// return;
// }
// medicos.push(medico);
// }
// salvarMedicos();
// renderizarTabela();
// resetarFormulario();
// });
// medicosTabelaBody.addEventListener('click', (e) => {
// const target = e.target;
// const crm = target.getAttribute('data-crm');
// if (target.classList.contains('btn-edit')) {
// const medicoParaEditar = medicos.find(m => m.crm === crm);
// if (medicoParaEditar) {
// medicoIdInput.value = medicoParaEditar.crm;
// nomeInput.value = medicoParaEditar.nome;
// crmInput.value = medicoParaEditar.crm;
// crmInput.disabled = true;
// especialidadeInput.value = medicoParaEditar.especialidade;
// telefoneInput.value = medicoParaEditar.telefone;
// emailInput.value = medicoParaEditar.email;
// statusInput.value = medicoParaEditar.status;
// cancelarBtn.style.display = 'inline-block';
// window.scrollTo(0, 0);
// }
// }
// if (target.classList.contains('btn-delete')) {
// if (confirm(`Tem certeza que deseja excluir o médico com CRM ${crm}?`)) {
// medicos = medicos.filter(m => m.crm !== crm);
// salvarMedicos();
// renderizarTabela();
// }
// }
// });
// cancelarBtn.addEventListener('click', () => {
// resetarFormulario();
// });
// renderizarTabela();
// });
// Seletores
// const form = document.getElementById('medicoForm');
// const tabelaBody = document.getElementById('medicosTabelaBody');
// const cancelarBtn = document.getElementById('cancelarBtn');
// const searchInput = document.querySelector('.search-input');
// let medicos = [];
// // Carrega dados do localStorage ao iniciar
// document.addEventListener('DOMContentLoaded', () => {
// const stored = localStorage.getItem('medicos');
// medicos = stored ? JSON.parse(stored) : [];
// renderMedicos(medicos);
// });
// // Função para renderizar lista de médicos
// function renderMedicos(lista) {
// tabelaBody.innerHTML = '';
// lista.forEach(m => {
// const tr = document.createElement('tr');
// tr.innerHTML = `
// <td>${m.nome}</td>
// <td>${m.crm}</td>
// <td>${m.especialidade}</td>
// <td>${m.status}</td>
// <td class="acoes">
// <button onclick="editarMedico('${m.id}')">Editar</button>
// <button onclick="excluirMedico('${m.id}')">Excluir</button>
// </td>`;
// tabelaBody.appendChild(tr);
// });
// }
// // Salva no localStorage
// function salvarLocalStorage() {
// localStorage.setItem('medicos', JSON.stringify(medicos));
// }
// // Trata submissão do formulário
// form.addEventListener('submit', e => {
// e.preventDefault();
// const idField = document.getElementById('medicoId');
// const nome = document.getElementById('nome').value.trim();
// const crm = document.getElementById('crm').value.trim();
// const especialidade = document.getElementById('especialidade').value;
// const telefone = document.getElementById('telefone').value.trim();
// const email = document.getElementById('email').value.trim();
// const status = document.getElementById('status').value;
// // Validação mínima
// if (!nome || !crm || !especialidade) return;
// if (idField.value) {
// // Edição
// const idx = medicos.findIndex(m => m.id === idField.value);
// medicos[idx] = { id: idField.value, nome, crm, especialidade, telefone, email, status };
// } else {
// // Criação
// const novoMedico = {
// id: Date.now().toString(),
// nome, crm, especialidade, telefone, email, status
// };
// medicos.push(novoMedico);
// }
// salvarLocalStorage();
// renderMedicos(medicos);
// form.reset();
// idField.value = '';
// cancelarBtn.style.display = 'none';
// });
// // Função para iniciar edição
// window.editarMedico = function(id) {
// const m = medicos.find(m => m.id === id);
// document.getElementById('medicoId').value = m.id;
// document.getElementById('nome').value = m.nome;
// document.getElementById('crm').value = m.crm;
// document.getElementById('especialidade').value = m.especialidade;
// document.getElementById('telefone').value = m.telefone;
// document.getElementById('email').value = m.email;
// document.getElementById('status').value = m.status;
// cancelarBtn.style.display = 'inline-block';
// };
// // Função para excluir médico
// window.excluirMedico = function(id) {
// if (!confirm('Tem certeza que deseja excluir este médico?')) return;
// medicos = medicos.filter(m => m.id !== id);
// salvarLocalStorage();
// renderMedicos(medicos);
// };
// // Cancelar edição
// cancelarBtn.addEventListener('click', () => {
// form.reset();
// document.getElementById('medicoId').value = '';
// cancelarBtn.style.display = 'none';
// });
// // Filtro de busca
// searchInput.addEventListener('input', () => {
// const termo = searchInput.value.toLowerCase();
// const filtrados = medicos.filter(m =>
// m.nome.toLowerCase().includes(termo) ||
// m.crm.toLowerCase().includes(termo)
// );
// renderMedicos(filtrados);
// });

View File

@ -0,0 +1,86 @@
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Crud + Layout</title>
<link rel="stylesheet" href="../../global.css" />
<!-- css da página -->
<link rel="stylesheet" href="#" />
</head>
<body>
<main>
<!-- Overlay só aparece em mobile quando menu está ativo -->
<div class="overlay" id="overlay"></div>
<div class="flex">
<!-- Botão hambúrguer só aparece em mobile -->
<button class="hamburger-btn" id="hamburger-btn" aria-label="Abrir menu de navegação" aria-expanded="false">
<span></span>
<span></span>
<span></span>
</button>
<!-- Sidebar agora se comporta diferente em desktop vs mobile -->
<section class="sidebar" id="sidebar" role="navigation" aria-label="Menu principal">
<ul>
<li>
<a href="#" aria-label="Página inicial">
<img src="https://images.vexels.com/media/users/3/142777/isolated/preview/84711206e52e0d4ff6c793cb476ea264-logotipo-medico-da-estrela-do-heartbeat.png" alt="Logo médico" id="logo-med" />
</a>
</li>
<li>
<a href="#" aria-label="Pacientes">
<img src="../../assets/layoutIcons/icons8-estetoscópio-50.png" alt="Pacientes" class="icon-sidebar" />
</a>
</li>
<li>
<a href="#" aria-label="Cadastro de usuários">
<img src="../../assets/layoutIcons/icons8-grupo-de-usuário-homem-homem-50.png" alt="Cadastro" class="icon-sidebar" />
</a>
</li>
<li>
<a href="#" aria-label="Documentos">
<img src="../../assets/layoutIcons/icons8-document.svg" alt="Documentos" class="icon-sidebar" />
</a>
</li>
<li>
<a href="#" aria-label="Configurações">
<img src="../../assets/layoutIcons/icons8-configurações.svg" alt="Configurações" class="icon-sidebar" />
</a>
</li>
</ul>
</section>
<!-- Seção principal sem padding-top desnecessário -->
<section class="section-main">
<nav class="nav" role="banner">
<div class="div-search">
<input type="text" class="search-input" placeholder="Buscar paciente" aria-label="Campo de busca" />
<button class="search-button" aria-label="Buscar">
<img src="../../assets/layoutIcons/icons8-pesquisar.svg" alt="Buscar" />
</button>
</div>
<div>
<ul class="icon-lista">
<li>
<a href="#" aria-label="Ajuda"><img src="../../assets/layoutIcons/icons8-ajuda-50.png" alt="Ajuda" /></a>
</li>
<li>
<button aria-label="Notificações"><img src="../../assets/layoutIcons/botao-ativar-notificacoes.png" alt="Notificações" /></button>
</li>
<li>
<a href="#" aria-label="Perfil do usuário"><img src="../../assets/layoutIcons/icons8-usuário-50.png" alt="Usuário" /></a>
</li>
</ul>
</div>
</nav>
</section>
</div>
</main>
<!-- script da página -->
<script src="#"></script>
<script src="../../scriptGlobal.js"></script>
</body>
</html>

View File

@ -0,0 +1,86 @@
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Crud + Layout</title>
<link rel="stylesheet" href="../../global.css" />
<!-- css da página -->
<link rel="stylesheet" href="#" />
</head>
<body>
<main>
<!-- Overlay só aparece em mobile quando menu está ativo -->
<div class="overlay" id="overlay"></div>
<div class="flex">
<!-- Botão hambúrguer só aparece em mobile -->
<button class="hamburger-btn" id="hamburger-btn" aria-label="Abrir menu de navegação" aria-expanded="false">
<span></span>
<span></span>
<span></span>
</button>
<!-- Sidebar agora se comporta diferente em desktop vs mobile -->
<section class="sidebar" id="sidebar" role="navigation" aria-label="Menu principal">
<ul>
<li>
<a href="../../pages/home/home.html" aria-label="Página inicial">
<img src="https://images.vexels.com/media/users/3/142777/isolated/preview/84711206e52e0d4ff6c793cb476ea264-logotipo-medico-da-estrela-do-heartbeat.png" alt="Logo médico" id="logo-med" />
</a>
</li>
<li>
<a href="../../pages/pacientes/paciente.html" aria-label="Pacientes">
<img src="../../assets/layoutIcons/icons8-estetoscópio-50.png" alt="Pacientes" class="icon-sidebar" />
</a>
</li>
<li>
<a href="../../pages/agendamento/agendamento.html" aria-label="Cadastro de usuários">
<img src="../../assets/layoutIcons/icons8-grupo-de-usuário-homem-homem-50.png" alt="Cadastro" class="icon-sidebar" />
</a>
</li>
<li>
<a href="../../pages/laudo/laudoMedico.html" aria-label="Documentos">
<img src="../../assets/layoutIcons/icons8-document.svg" alt="Documentos" class="icon-sidebar" />
</a>
</li>
<li>
<a href="#" aria-label="Configurações">
<img src="../../assets/layoutIcons/icons8-configurações.svg" alt="Configurações" class="icon-sidebar" />
</a>
</li>
</ul>
</section>
<!-- Seção principal sem padding-top desnecessário -->
<section class="section-main">
<nav class="nav" role="banner">
<div class="div-search">
<input type="text" class="search-input" placeholder="Buscar paciente" aria-label="Campo de busca" />
<button class="search-button" aria-label="Buscar">
<img src="../../assets/layoutIcons/icons8-pesquisar.svg" alt="Buscar" />
</button>
</div>
<div>
<ul class="icon-lista">
<li>
<a href="#" aria-label="Ajuda"><img src="../../assets/layoutIcons/icons8-ajuda-50.png" alt="Ajuda" /></a>
</li>
<li>
<button aria-label="Notificações"><img src="../../assets/layoutIcons/botao-ativar-notificacoes.png" alt="Notificações" /></button>
</li>
<li>
<a href="#" aria-label="Perfil do usuário"><img src="../../assets/layoutIcons/icons8-usuário-50.png" alt="Usuário" /></a>
</li>
</ul>
</div>
</nav>
</section>
</div>
</main>
<!-- script da página -->
<script src="#"></script>
<script src="../../scriptGlobal.js"></script>
</body>
</html>

View File

View File

@ -0,0 +1,86 @@
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Crud + Layout</title>
<link rel="stylesheet" href="../../global.css" />
<!-- css da página -->
<link rel="stylesheet" href="#" />
</head>
<body>
<main>
<!-- Overlay só aparece em mobile quando menu está ativo -->
<div class="overlay" id="overlay"></div>
<div class="flex">
<!-- Botão hambúrguer só aparece em mobile -->
<button class="hamburger-btn" id="hamburger-btn" aria-label="Abrir menu de navegação" aria-expanded="false">
<span></span>
<span></span>
<span></span>
</button>
<!-- Sidebar agora se comporta diferente em desktop vs mobile -->
<section class="sidebar" id="sidebar" role="navigation" aria-label="Menu principal">
<ul>
<li>
<a href="../../pages/home/home.html" aria-label="Página inicial">
<img src="https://images.vexels.com/media/users/3/142777/isolated/preview/84711206e52e0d4ff6c793cb476ea264-logotipo-medico-da-estrela-do-heartbeat.png" alt="Logo médico" id="logo-med" />
</a>
</li>
<li>
<a href="../../pages/pacientes/paciente.html" aria-label="Pacientes">
<img src="../../assets/layoutIcons/icons8-estetoscópio-50.png" alt="Pacientes" class="icon-sidebar" />
</a>
</li>
<li>
<a href="#" aria-label="Cadastro de usuários">
<img src="../../assets/layoutIcons/icons8-grupo-de-usuário-homem-homem-50.png" alt="Cadastro" class="icon-sidebar" />
</a>
</li>
<li>
<a href="../../pages/laudo/laudoMedico.html" aria-label="Documentos">
<img src="../../assets/layoutIcons/icons8-document.svg" alt="Documentos" class="icon-sidebar" />
</a>
</li>
<li>
<a href="#" aria-label="Configurações">
<img src="../../assets/layoutIcons/icons8-configurações.svg" alt="Configurações" class="icon-sidebar" />
</a>
</li>
</ul>
</section>
<!-- Seção principal sem padding-top desnecessário -->
<section class="section-main">
<nav class="nav" role="banner">
<div class="div-search">
<input type="text" class="search-input" placeholder="Buscar paciente" aria-label="Campo de busca" />
<button class="search-button" aria-label="Buscar">
<img src="../../assets/layoutIcons/icons8-pesquisar.svg" alt="Buscar" />
</button>
</div>
<div>
<ul class="icon-lista">
<li>
<a href="#" aria-label="Ajuda"><img src="../../assets/layoutIcons/icons8-ajuda-50.png" alt="Ajuda" /></a>
</li>
<li>
<button aria-label="Notificações"><img src="../../assets/layoutIcons/botao-ativar-notificacoes.png" alt="Notificações" /></button>
</li>
<li>
<a href="#" aria-label="Perfil do usuário"><img src="../../assets/layoutIcons/icons8-usuário-50.png" alt="Usuário" /></a>
</li>
</ul>
</div>
</nav>
</section>
</div>
</main>
<!-- script da página -->
<script src="#"></script>
<script src="../../scriptGlobal.js"></script>
</body>
</html>

View File

View File

@ -0,0 +1,260 @@
fieldset {
display: flex;
flex-direction: column;
justify-content: space-between;
}
fieldset label {
font-family: "Times New Roman", Times, serif;
}
fieldset input {
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 14px;
margin-top: 5px;
font-family: sans-serif;
}
#form-tittle {
width: 93%;
display: grid;
grid-template-columns: repeat(6, 1fr);
margin-bottom: 10px;
padding-right: 25px;
}
#form-tittle label {
text-align: left;
font-weight: bold;
color: #243b51;
}
.section-main-text {
padding: 30px;
padding-bottom: 0px;
}
.section-main-text h1 {
margin-bottom: 15px;
font-size: 35px;
font-family: Cambria, Cochin, Georgia, Times, "Times New Roman", serif;
}
.section-main-text p {
font-size: 20px;
}
.main-button button {
font-size: 17px;
background: none;
margin-right: 30px;
margin-top: 10px;
border: none;
color: #243b51;
padding: 20px 10px;
border-bottom: 2px solid transparent;
transition: 0.6s;
}
.main-button-border:hover {
/*estilo no mouseenter*/
border: none;
margin-right: 30px;
margin-top: 10px;
padding: 20px 10px;
background: none;
border-bottom: 2px solid blue;
color: blue;
}
.conteudo {
margin-left: 30px;
background-color: #fafafa;
padding: 25px;
border-radius: 7px;
}
/*formulário */
#formLaudo {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-bottom: 20px;
background-color: #f8f9fa;
padding: 15px;
border-radius: 8px;
border: 1px solid #ddd;
justify-content: space-between;
}
#formLaudo button[type="submit"] {
background-color: #007bff;
color: white;
padding: 10px 16px;
border: none;
border-radius: 4px;
cursor: pointer;
font-weight: bold;
transition: background-color 0.2s ease;
}
#formLaudo button[type="submit"]:hover {
background-color: #0056b3;
}
/* Tabela */
#laudoTable {
width: 100%;
border-collapse: collapse;
border: 1px solid #ddd;
background-color: white;
font-size: 14px;
border-radius: 8px;
overflow: hidden;
}
#laudoTable thead {
background-color: #e9ecef;
}
#laudoTable thead th {
padding: 12px;
border-bottom: 1px solid #ccc;
text-align: left;
font-weight: bold;
}
#laudoTable tbody td {
padding: 10px;
border-bottom: 1px solid #eee;
}
#laudoTable tbody tr:hover {
background-color: #f1f1f1;
}
#laudoTable tbody td button {
padding: 6px 10px;
font-size: 14px;
background-color: #6c757d;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
#laudoTable tbody td button:hover {
background-color: #5a6268;
}
/* Media queries melhoradas para responsividade */
@media (max-width: 768px) {
/* Melhor organização do conteúdo principal em mobile */
.section-main-text {
padding: 20px;
padding-bottom: 0px;
margin-top: 10rem;
}
.section-main-text h1 {
font-size: 28px;
margin-bottom: 10px;
}
.section-main-text p {
font-size: 16px;
}
.main-button {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.main-button button {
margin-right: 0;
margin-top: 5px;
padding: 15px 8px;
font-size: 15px;
}
.conteudo {
margin: 20px;
padding: 20px;
}
/* Formulário responsivo */
#formLaudo {
flex-direction: column;
gap: 15px;
}
#formLaudo fieldset {
width: 100%;
}
#formLaudo button[type="submit"] {
width: 100%;
padding: 12px;
font-size: 16px;
}
/* Tabela responsiva com scroll horizontal */
.table-container {
overflow-x: auto;
margin-top: 20px;
}
#laudoTable {
min-width: 600px;
font-size: 12px;
}
#laudoTable thead th,
#laudoTable tbody td {
padding: 8px;
white-space: nowrap;
}
}
/* Media query para tablets */
@media (max-width: 1024px) and (min-width: 769px) {
.section-main-text h1 {
font-size: 32px;
}
.conteudo {
margin: 25px;
}
}
/* Media query melhorada para telas muito pequenas */
@media (max-width: 480px) {
.section-main-text {
padding: 15px;
}
.section-main-text h1 {
font-size: 24px;
}
.section-main-text p {
font-size: 14px;
}
.conteudo {
margin: 15px;
padding: 15px;
}
#laudoTable {
font-size: 11px;
}
#laudoTable thead th,
#laudoTable tbody td {
padding: 6px;
}
}

View File

@ -0,0 +1,53 @@
const form = document.getElementById("formLaudo");
const tbody = document.querySelector("#laudoTable tbody");
const button = document.querySelectorAll(".button");
// Função para adicionar linha
function adicionarLinhaNaTabela(item) {
const tr = document.createElement("tr");
tr.innerHTML = `
<td>${item.pedido}</td>
<td>${item.data}</td>
<td>${item.prazo}</td>
<td>${item.paciente}</td>
<td>${item.solicitante}</td>
<td>${item.classificacao}</td>
<td><button>...</button></td>
`;
tbody.appendChild(tr);
}
// Carregar dados salvos
function carregarDadosSalvos() {
const dados = JSON.parse(localStorage.getItem("laudos")) || [];
dados.forEach(adicionarLinhaNaTabela);
}
// Salvar novo item
function salvarItem(item) {
const dados = JSON.parse(localStorage.getItem("laudos")) || [];
dados.push(item);
localStorage.setItem("laudos", JSON.stringify(dados));
}
// Evento de envio do formulário
form.addEventListener("submit", (e) => {
e.preventDefault();
const item = {
pedido: document.getElementById("pedido").value,
data: document.getElementById("data").value,
prazo: document.getElementById("prazo").value,
paciente: document.getElementById("paciente").value,
solicitante: document.getElementById("solicitante").value,
classificacao: document.getElementById("classificacao").value,
acao: "...",
};
adicionarLinhaNaTabela(item);
salvarItem(item);
form.reset();
});
// Carregar ao abrir
window.addEventListener("DOMContentLoaded", carregarDadosSalvos);

View File

@ -0,0 +1,121 @@
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Crud + Layout</title>
<link rel="stylesheet" href="/Squad-21/clinicApp/global.css" />
<link rel="stylesheet" href="./laudo.css" />
</head>
<body>
<main>
<!-- Overlay só aparece em mobile quando menu está ativo -->
<div class="overlay" id="overlay"></div>
<div class="flex">
<!-- Botão hambúrguer só aparece em mobile -->
<button class="hamburger-btn" id="hamburger-btn" aria-label="Abrir menu de navegação" aria-expanded="false">
<span></span>
<span></span>
<span></span>
</button>
<!-- Sidebar agora se comporta diferente em desktop vs mobile -->
<section class="sidebar" id="sidebar" role="navigation" aria-label="Menu principal">
<ul>
<li>
<a href="../../pages/home/home.html" aria-label="Página inicial">
<img src="https://images.vexels.com/media/users/3/142777/isolated/preview/84711206e52e0d4ff6c793cb476ea264-logotipo-medico-da-estrela-do-heartbeat.png"
alt="Logo médico" id="logo-med" />
</a>
</li>
<li>
<a href="../../pages/pacientes/paciente.html" aria-label="Pacientes">
<img src="../../assets/layoutIcons/icons8-estetoscópio-50.png" alt="Pacientes"
class="icon-sidebar" />
</a>
</li>
<li>
<a href="#" aria-label="Cadastro de usuários">
<img src="../../assets/layoutIcons/icons8-grupo-de-usuário-homem-homem-50.png"
alt="Cadastro" class="icon-sidebar" />
</a>
</li>
<li>
<a href="../../pages/laudo/laudoMedico.html" aria-label="Documentos">
<img src="../../assets/layoutIcons/icons8-document.svg" alt="Documentos"
class="icon-sidebar" />
</a>
</li>
<li>
<a href="#" aria-label="Configurações">
<img src="../../assets/layoutIcons/icons8-configurações.svg" alt="Configurações"
class="icon-sidebar" />
</a>
</li>
</ul>
</section>
<!-- Seção principal sem padding-top desnecessário -->
<section class="section-main">
<nav class="nav" role="banner">
<div class="div-search">
<input type="text" class="search-input" placeholder="Buscar paciente"
aria-label="Campo de busca" />
<button class="search-button" aria-label="Buscar">
<img src="../../assets/layoutIcons/icons8-pesquisar.svg" alt="Buscar" />
</button>
</div>
<div>
<ul class="icon-lista">
<li>
<a href="#" aria-label="Ajuda"><img
src="/clinicApp/assets/layoutIcons/icons8-ajuda-50.png" alt="Ajuda" /></a>
</li>
<li>
<button aria-label="Notificações"><img
src="/clinicApp/assets/layoutIcons/botao-ativar-notificacoes.png"
alt="Notificações" /></button>
</li>
<li>
<a href="#" aria-label="Perfil do usuário"><img
src="/clinicApp/assets/layoutIcons/icons8-usuário-50.png" alt="Usuário" /></a>
</li>
</ul>
</div>
</nav>
<div class="section-main-text">
<h1>Laudo Médico</h1>
<p>Nesta seção você pode gerenciar todos os laudos gerados através da integração.</p>
<!-- <div class="main-button">
<button class="button main-button-border">A descrever</button>
<button class="button main-button-border">Liberado</button>
<button class="button main-button-border">Entregue</button>
</div> -->
<div id="editor" style="border:1px solid #ccc; padding:1rem; border-radius:8px;"></div>
</div>
<div class="conteudo">
</div>
</section>
</div>
</main>
<script src="laudo.js"></script>
<script src="../../scriptGlobal.js"></script>
<!-- TipTap Editor -->
<script type="module">
import { Editor } from 'https://esm.sh/@tiptap/core'
import StarterKit from 'https://esm.sh/@tiptap/starter-kit'
const editor = new Editor({
element: document.querySelector('#editor'),
extensions: [StarterKit],
content: '<p>Olá, mundo!</p>',
})
</script>
</body>
</html>

View File

View File

View File

@ -0,0 +1,949 @@
:root {
--bg-main: #f3f0f0;
--bg-nav: #fafafa;
--bg-modal: #fff;
--sombra-modal: 0 4px 15px rgba(0, 0, 0, 0.3);
--sombra-sidebar: 15px 0px 15px rgba(0, 0, 0, 0.3);
--cor-cinza-claro: #f1f1f1;
--cor-cinza-medio: #ccc;
--cor-cinza-escuro: #666;
--cor-tabela-header: #f3f0f0;
--cor-principal: rgb(38, 137, 255);
--cor-hover-principal: rgb(30, 110, 204);
--cor-borda-input-foco: #2e7d32;
--cor-fundo-botao-salvar: #2e7d32;
--cor-hover-salvar: #256628;
}
* {
padding: 0;
margin: 0;
border: none;
box-sizing: border-box;
}
body,
html {
font-family: Arial, sans-serif;
}
.flex {
display: flex;
}
.sidebar {
padding-top: 1.25rem;
display: flex;
flex-direction: column;
align-items: center;
width: 5vw;
height: 100vh;
background-color: white;
box-shadow: var(--sombra-sidebar);
}
.sidebar ul {
list-style: none;
text-align: center;
}
.sidebar ul li {
padding: 10px 0;
}
.icon-sidebar {
width: 17px;
padding: 10px 13px 5px 13px;
transition: background-color 0.2s;
}
.icon-sidebar:hover {
background-color: var(--cor-cinza-claro);
}
.section-main {
width: 95vw;
background-color: var(--bg-main);
}
.nav {
display: flex;
justify-content: space-between;
align-items: center;
background-color: var(--bg-nav);
padding: 20px;
}
.div-search {
display: flex;
align-items: center;
position: relative;
border-radius: 5px;
transition: border 0.2s;
}
.div-search:hover {
border: 1.5px solid darkgray;
}
.search-input {
height: 38px;
width: 20vw;
padding-left: 10px;
border-radius: 5px;
border: 1.5px solid var(--cor-cinza-medio);
}
.search-button {
position: absolute;
right: 15px;
top: 50%;
transform: translateY(-50%);
background: none;
cursor: pointer;
width: 22px;
height: 22px;
}
.icon-lista {
display: flex;
list-style: none;
gap: 30px;
padding: 15px;
}
.icon-lista li a img,
img {
width: 22px;
padding: 5px;
}
.btn-add,
.btn {
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.2s;
}
.btn-add {
margin: 20px;
background-color: var(--cor-principal);
color: #fff;
}
.btn-add:hover {
background-color: var(--cor-hover-principal);
}
.modal {
display: none;
position: fixed;
z-index: 1000;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.6);
justify-content: center;
align-items: center;
animation: fadeIn 0.3s ease;
}
.modal-content {
background: var(--bg-modal);
padding: 20px;
border-radius: 12px;
width: 800px;
max-height: 90vh;
overflow-y: auto;
box-shadow: var(--sombra-modal);
position: relative;
}
.modal-content h2 {
margin-bottom: 15px;
font-size: 20px;
color: #333;
border-bottom: 1px solid #eee;
padding-bottom: 8px;
}
.close {
position: absolute;
top: 10px;
right: 15px;
font-size: 20px;
cursor: pointer;
color: var(--cor-cinza-escuro);
}
.form-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 15px;
margin-bottom: 15px;
}
.form-group {
display: flex;
flex-direction: column;
}
.form-group label {
font-weight: 600;
font-size: 13px;
margin-bottom: 4px;
color: #444;
}
.form-group input,
.form-group select {
padding: 8px;
height: 32px;
border-radius: 6px;
border: 1px solid var(--cor-cinza-medio);
font-size: 14px;
outline: none;
width: 100%;
}
.form-group input:focus,
.form-group select:focus {
border-color: var(--cor-borda-input-foco);
box-shadow: 0 0 5px rgba(46, 125, 50, 0.3);
}
.radio-group {
display: flex;
gap: 10px;
align-items: center;
}
.form-check-group {
display: flex;
align-items: center;
gap: 8px;
margin-top: 5px;
padding: 0;
font-size: 14px;
color: #444;
min-width: unset;
max-width: fit-content;
.modal-actions {
margin-top: 20px;
display: flex;
justify-content: flex-end;
gap: 10px;
}
.btn-save {
background: var(--cor-fundo-botao-salvar);
color: #fff;
font-size: 14px;
padding: 8px 15px;
}
.btn-cancel {
background: var(--cor-cinza-medio);
color: #333;
font-size: 14px;
padding: 8px 15px;
}
.btn-save:hover {
background: var(--cor-hover-salvar);
}
.btn-cancel:hover {
background: #b3b3b3;
}
.btn-edit,
.btn-delete {
padding: 5px 10px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 14px;
background-color: lightgrey;
color: #000;
transition: background-color 0.2s;
}
.btn-edit:hover,
.btn-delete:hover {
background-color: #d3d3d3;
}
/* Tabela de pacientes */
.paciente-table {
width: 95%; /* Use a largura da tela disponível */
margin: 20px auto;
border-collapse: collapse;
background-color: var(--bg-modal);
border-radius: 10px;
overflow: hidden;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.paciente-table th,
.paciente-table td {
padding: 12px 15px; /* Aumentei o padding para dar mais espaço */
text-align: left;
border-bottom: 1px solid #ddd;
font-size: 15px; /* Ajustei o tamanho da fonte */
white-space: nowrap; /* Impede que o texto quebre para a próxima linha */
overflow: hidden;
text-overflow: ellipsis; /* Adiciona "..." se o texto for muito longo */
}
.paciente-table th {
background-color: var(--cor-tabela-header);
font-weight: bold;
color: #555;
text-transform: uppercase; /* Transforma o texto do cabeçalho em maiúsculas */
}
/* Deixa a tabela responsiva para dispositivos menores */
@media (max-width: 768px) {
.paciente-table {
display: block;
overflow-x: auto; /* Adiciona uma barra de rolagem horizontal */
white-space: nowrap;
}
.paciente-table thead,
.paciente-table tbody,
.paciente-table th,
.paciente-table td,
.paciente-table tr {
display: block;
}
.paciente-table tr {
margin-bottom: 15px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.paciente-table td {
border-bottom: 1px solid #eee;
position: relative;
padding-left: 50%;
text-align: right;
}
.paciente-table td::before {
content: attr(data-label);
position: absolute;
left: 0;
width: 50%;
padding-left: 15px;
font-weight: bold;
text-align: left;
}
}
@keyframes fadeIn {
from {
opacity: 0;
transform: scale(0.95);
}
to {
opacity: 1;
transform: scale(1);
}
}
}
/* Container de formulário para a nova página - AGORA OCUPARÁ A LARGURA TOTAL */
.full-page-form-container {
width: 95%;
margin: 20px auto;
padding: 30px;
background-color: var(--bg-modal);
border-radius: 10px;
box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
box-sizing: border-box;
}
/* Divisores de Seção (Endereço, etc) */
.section-divider {
font-size: 1.2em;
font-weight: bold;
color: #444;
margin: 35px 0 20px;
border-bottom: 1px solid #ccc;
padding-bottom: 8px;
}
/* Ajustes para a grade */
.form-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 20px 30px;
}
.form-grid .span-2 {
grid-column: span 2;
}
/* Estilos de input e select uniformes */
.form-group input,
.form-group select {
padding: 10px;
height: 40px;
border-radius: 8px;
border: 1px solid var(--cor-cinza-medio);
font-size: 16px;
outline: none;
width: 100%;
}
.form-group input:focus,
.form-group select:focus {
border-color: var(--cor-borda-input-foco);
box-shadow: 0 0 5px rgba(46, 125, 50, 0.3);
}
/* Campos de largura total */
.form-group.full-width {
grid-column: 1 / -1;
}
/* Estilo para a área de texto de Observações */
textarea {
resize: vertical;
width: 100%;
min-height: 100px;
padding: 10px;
border-radius: 8px;
border: 1px solid var(--cor-cinza-medio);
font-size: 16px;
outline: none;
box-sizing: border-box;
}
textarea:focus {
border-color: var(--cor-borda-input-foco);
box-shadow: 0 0 5px rgba(46, 125, 50, 0.3);
}
/* Estilo para o campo de upload de arquivo */
.form-group input[type="file"] {
background-color: var(--cor-cinza-claro);
border: 1px dashed var(--cor-cinza-medio);
padding: 10px;
height: auto;
cursor: pointer;
}
/* Outros estilos, como h2, labels, buttons etc., que já estão na sua folha de estilo */
.form-card h2 {
margin-bottom: 25px;
font-size: 24px;
color: #333;
border-bottom: 1px solid #eee;
padding-bottom: 15px;
}
.form-group label {
font-weight: 600;
font-size: 14px;
margin-bottom: 6px;
color: #444;
}
.form-actions {
margin-top: 40px;
display: flex;
justify-content: flex-end;
gap: 20px;
}
.form-actions .btn {
text-decoration: none;
color: #fff;
padding: 12px 22px;
border-radius: 8px;
font-size: 16px;
cursor: pointer;
transition: background-color 0.2s;
}
.form-actions .btn-save {
background: var(--cor-fundo-botao-salvar);
}
.form-actions .btn-cancel {
background: #ccc;
color: #333;
}
.form-actions .btn-save:hover {
background: #256628;
}
.form-actions .btn-cancel:hover {
background: #b3b3b3;
}
/* Estilos gerais do corpo para melhor visualização */
body {
font-family: Arial, sans-serif;
background-color: #f0f2f5;
margin: 0;
padding: 0;
}
/* Container principal para centralizar o conteúdo */
.flex {
display: flex;
min-height: 100vh;
}
/* Estilos para a seção principal, para ocupar o espaço restante */
.section-main {
flex-grow: 1; /* Ocupa todo o espaço restante */
padding: 20px;
background-color: #f8f9fa;
}
/* Estilos para o botão de adicionar paciente */
.btn-add {
display: inline-block;
padding: 10px 20px;
background-color: #007bff;
color: white;
text-decoration: none;
border-radius: 5px;
margin-bottom: 20px;
transition: background-color 0.3s ease;
}
.btn-add:hover {
background-color: #0056b3;
}
/* Estilos da tabela de pacientes */
.paciente-table {
width: 100%;
border-collapse: collapse;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
background-color: white;
border-radius: 8px;
overflow: hidden;
}
.paciente-table th,
.paciente-table td {
padding: 12px 15px;
text-align: left;
border-bottom: 1px solid #ddd;
}
.paciente-table thead th {
background-color: #e9ecef;
font-weight: bold;
color: #495057;
text-transform: uppercase;
font-size: 14px;
}
/* Estilizando as linhas da tabela */
.paciente-table tbody tr:hover {
background-color: #f1f1f1;
}
/* Estilos para os botões de ação na tabela */
.btn-edit,
.btn-delete {
padding: 6px 10px;
border: none;
border-radius: 4px;
color: white;
cursor: pointer;
font-size: 12px;
transition: background-color 0.3s ease;
}
.btn-edit {
background-color: #28a745;
}
.btn-edit:hover {
background-color: #218838;
}
.btn-delete {
background-color: #dc3545;
}
.btn-delete:hover {
background-color: #c82333;
}
/* Estilos para dispositivos móveis (responsividade) */
@media (max-width: 768px) {
.paciente-table,
.paciente-table tbody,
.paciente-table tr,
.paciente-table td {
display: block;
width: 100%;
}
.paciente-table thead {
display: none; /* Esconde o cabeçalho em telas pequenas */
}
.paciente-table tr {
margin-bottom: 15px;
border: 1px solid #ddd;
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.paciente-table td {
text-align: right;
padding-left: 50%; /* Espaço para o rótulo */
position: relative;
}
.paciente-table td::before {
content: attr(data-label);
position: absolute;
left: 10px;
width: 45%;
text-align: left;
font-weight: bold;
color: #555;
}
}
/* Estilos Gerais para o Corpo da Página */
body {
margin: 0;
font-family: Arial, sans-serif;
background-color: #f0f2f5;
}
/* Container Flex principal (sidebar + conteúdo) */
.flex-container {
display: flex;
min-height: 100vh;
}
/* Estilo da Sidebar */
.sidebar {
width: 80px;
background-color: #fff;
padding: 10px 0;
box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
display: flex;
flex-direction: column;
align-items: center;
}
.sidebar ul {
list-style: none;
padding: 0;
margin: 0;
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
}
.sidebar li {
margin-bottom: 20px;
}
.sidebar a {
display: block;
padding: 10px;
border-radius: 5px;
transition: background-color 0.3s ease;
}
.sidebar a:hover {
background-color: #e0e0e0;
}
.sidebar img {
width: 30px;
height: 30px;
display: block;
margin: 0 auto;
}
#logo-med {
width: 45px;
height: 45px;
margin-bottom: 30px;
}
/* Área de Conteúdo Principal (que contém o Header e o main-content) */
.content-area {
flex-grow: 1;
display: flex;
flex-direction: column;
}
/* Estilo do Header */
.header {
background-color: #fff;
padding: 10px 20px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
display: flex;
justify-content: space-between;
align-items: center;
height: 60px;
}
.search-bar {
display: flex;
align-items: center;
border: 1px solid #ccc;
border-radius: 20px;
padding: 5px 10px;
background-color: #f8f8f8;
}
.search-bar input {
border: none;
outline: none;
padding: 5px;
background-color: transparent;
width: 200px;
}
.search-bar button {
background: none;
border: none;
cursor: pointer;
padding: 0 5px;
}
.search-bar button img {
width: 20px;
height: 20px;
}
.header-icons img {
width: 24px;
height: 24px;
margin-left: 20px;
cursor: pointer;
}
/* Estilos para o Conteúdo Principal (abaixo do header) */
.main-content {
flex-grow: 1;
padding: 20px;
overflow-y: auto;
}
/* Estilos para o botão "Cadastrar Paciente" */
.btn-add {
display: inline-block;
background-color: #007bff;
color: #fff;
padding: 10px 15px;
border-radius: 5px;
text-decoration: none;
font-weight: bold;
margin-bottom: 20px;
transition: background-color 0.3s ease;
}
.btn-add:hover {
background-color: #0056b3;
}
/* Estilos da Tabela */
.table-container {
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.paciente-table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
.paciente-table thead th {
background-color: #f2f2f2;
padding: 12px 15px;
text-align: left;
border-bottom: 2px solid #ddd;
}
.paciente-table tbody td {
padding: 10px 15px;
border-bottom: 1px solid #eee;
}
.paciente-table tbody tr:hover {
background-color: #f9f9f9;
}
.btn {
padding: 8px 12px;
border: none;
border-radius: 4px;
cursor: pointer;
margin-right: 5px;
transition: background-color 0.3s ease;
}
/* As cores dos botões de ação foram mantidas como estavam na sua versão anterior */
.btn-edit {
background-color: #08c547;
color: white;
}
.btn-edit:hover {
background-color: #087904;
}
.btn-delete {
background-color: #dc3545;
color: #fff;
}
.btn-delete:hover {
background-color: #b31a29;
}
/* Estilos para a página de cadastro */
.section-cadastro {
background-color: #fff;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
max-width: 600px;
margin: 20px auto;
}
.section-cadastro h2 {
text-align: center;
color: #333;
margin-bottom: 25px;
}
.section-cadastro form label {
display: block;
margin-bottom: 8px;
font-weight: bold;
color: #555;
}
.section-cadastro form input[type="text"],
.section-cadastro form input[type="tel"] {
width: calc(100% - 20px);
padding: 10px;
margin-bottom: 20px;
border: 1px solid #ddd;
border-radius: 4px;
box-sizing: border-box;
}
.section-cadastro form button {
width: 100%;
padding: 12px;
background-color: #28a745;
color: white;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.section-cadastro form button:hover {
background-color: #218838;
}
.btn-back {
display: inline-block;
margin-bottom: 20px;
color: #007bff;
text-decoration: none;
font-weight: bold;
font-size: 16px;
}
.btn-back:hover {
text-decoration: underline;
}
/* Media Queries para Responsividade */
@media (max-width: 768px) {
.sidebar {
width: 60px;
}
.sidebar img {
width: 24px;
height: 24px;
}
#logo-med {
width: 40px;
height: 40px;
}
.header {
flex-direction: column;
height: auto;
padding: 10px;
}
.search-bar {
width: 90%;
margin-bottom: 10px;
}
.header-icons {
margin-top: 10px;
}
.header-icons img {
margin: 0 10px;
}
.paciente-table thead {
display: none;
}
.paciente-table tbody tr {
display: block;
margin-bottom: 10px;
border: 1px solid #ddd;
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}
.paciente-table tbody td {
display: block;
text-align: right;
padding-left: 50%;
position: relative;
font-size: 14px;
}
.paciente-table tbody td::before {
content: attr(data-label);
position: absolute;
left: 15px;
width: 45%;
text-align: left;
font-weight: bold;
}
}

View File

@ -0,0 +1,232 @@
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cadastro de Paciente</title>
<link rel="stylesheet" href="addPacient.css">
<script src="https://cdn.jsdelivr.net/npm/inputmask@5.0.9/dist/inputmask.min.js"></script>
<script defer src="addPaciente.js"></script>
</head>
<body>
<main>
<div class="flex">
<section class="section-main">
<nav class="nav">
</nav>
<div class="full-page-form-container">
<div class="form-card">
<h2>Dados do Paciente</h2>
<form id="cadastro-form">
<div class="form-grid">
<div class="form-group"><label for="nome">Nome *</label><input type="text" id="nome"
required></div>
<div class="form-group"><label for="nomeSocial">Nome Social</label><input type="text"
id="nomeSocial"></div>
<div class="form-group"><label for="cpf">CPF</label><input type="text" id="cpf" placeholder="000.000.000-00" required></div>
<div class="form-group"><label for="rg">RG</label><input type="text" id="rg"></div>
<div class="form-group">
<label for="outrosDocs">Outros documentos de identidade</label>
<select id="outrosDocs">
<option value="">Selecione</option>
<option value="Passaporte">Passaporte</option>
<option value="CNH">CNH</option>
</select>
</div>
<div class="form-group"><label for="numDoc">Número do documento</label><input
type="text" id="numDoc" placeholder="Número do documento"></div>
<div class="form-group">
<label for="sexo">Sexo</label>
<select id="sexo" name="sexo">
<option value="">Selecione</option>
<option value="Masculino">Masculino</option>
<option value="Feminino">Feminino</option>
</select>
</div>
<div class="form-group"><label for="dataNascimento">Data de Nascimento *</label><input
type="date" id="dataNascimento" required></div>
<div class="form-group">
<label for="etnia">Etnia</label>
<select id="etnia">
<option value="">Selecione</option>
<option value="branca">Branca</option>
<option value="preta">Preta</option>
<option value="parda">Parda</option>
<option value="amarela">Amarela</option>
<option value="indigena">Indígena</option>
</select>
</div>
<div class="form-group">
<label for="raca">Raça</label>
<select id="raca">
<option value="">Selecione</option>
<option value="branca">Branca</option>
<option value="preta">Preta</option>
<option value="parda">Parda</option>
<option value="amarela">Amarela</option>
<option value="indigena">Indígena</option>
</select>
</div>
<div class="form-group"><label for="naturalidade">Naturalidade</label><input type="text"
id="naturalidade"></div>
<div class="form-group">
<label for="nacionalidade">Nacionalidade</label>
<input type="text"
id="nacionalidade">
</div>
<div class="form-group"><label for="profissao">Profissão</label><input type="text"
id="profissao"></div>
<div class="form-group">
<label for="estadoCivil">Estado Civil</label>
<select id="estadoCivil">
<option value="">Selecione</option>
<option value="solteiro">Solteiro(a)</option>
<option value="casado">Casado(a)</option>
<option value="divorciado">Divorciado(a)</option>
<option value="viuvo">Viúvo(a)</option>
<option value="separado">Separado(a)</option>
</select>
</div>
<div class="form-group"><label for="nomeMae">Nome da mãe</label><input type="text"
id="nomeMae"></div>
<div class="form-group"><label for="profissaoMae">Profissão da mãe</label><input
type="text" id="profissaoMae"></div>
<div class="form-group"><label for="nomePai">Nome do pai</label><input type="text"
id="nomePai"></div>
<div class="form-group"><label for="profissaoPai">Profissão do pai</label><input
type="text" id="profissaoPai"></div>
<div class="form-group"><label for="nomeResponsavel">Nome do responsável</label><input
type="text" id="nomeResponsavel"></div>
<div class="form-group"><label for="cpfResponsavel">CPF do responsável</label><input
type="text" id="cpfResponsavel"></div>
<div class="form-group"><label for="nomeEsposo">Nome do esposo(a)</label><input
type="text" id="nomeEsposo"></div>
</div>
<div class="section-divider">Endereço</div>
<div class="form-grid">
<div class="form-group"><label for="cep">CEP</label><input type="text" id="cep"></div>
<div class="form-group span-2"><label for="endereco">Endereço</label><input type="text"
id="endereco"></div>
<div class="form-group"><label for="numero">Número</label><input type="text"
id="numero"></div>
<div class="form-group"><label for="complemento">Complemento</label><input type="text"
id="complemento"></div>
<div class="form-group"><label for="bairro">Bairro</label><input type="text"
id="bairro"></div>
<div class="form-group"><label for="cidade">Cidade</label><input type="text"
id="cidade"></div>
<div class="form-group">
<label for="estado">Estado
<label>
<select id="estado">
<option value="">Selecione</option>
<option value="AC">Acre</option>
<option value="AL">Alagoas</option>
<option value="AP">Amapá</option>
<option value="AM">Amazonas</option>
<option value="BA">Bahia</option>
<option value="CE">Ceará</option>
<option value="DF">Distrito Federal</option>
<option value="ES">Espírito Santo</option>
<option value="GO">Goiás</option>
<option value="MA">Maranhão</option>
<option value="MT">Mato Grosso</option>
<option value="MS">Mato Grosso do Sul</option>
<option value="MG">Minas Gerais</option>
<option value="PA">Pará</option>
<option value="PB">Paraíba</option>
<option value="PR">Paraná</option>
<option value="PE">Pernambuco</option>
<option value="PI">Piauí</option>
<option value="RJ">Rio de Janeiro</option>
<option value="RN">Rio Grande do Norte</option>
<option value="RS">Rio Grande do Sul</option>
<option value="RO">Rondônia</option>
<option value="RR">Roraima</option>
<option value="SC">Santa Catarina</option>
<option value="SP">São Paulo</option>
<option value="SE">Sergipe</option>
<option value="TO">Tocantins</option>
</select>
</div>
</div>
<div class="section-divider">Contato</div>
<div class="form-grid">
<div class="form-group"><label for="email">E-mail</label><input type="email" id="email">
</div>
<div class="form-group"><label for="celular">Celular</label><input type="text"
id="celular" placeholder="(00) 00000-0000"></div>
<div class="form-group"><label for="telefone1">Telefone</label><input type="text"
id="telefone1" placeholder="(00) 0000-0000"></div>
</div>
<div class="section-divider">Informações Médicas</div>
<div class="form-grid">
<div class="form-group">
<label for="tipoSanguineo">Tipo Sanguíneo</label>
<select id="tipoSanguineo">
<option value="">Selecione</option>
<option value="A+">A+</option>
<option value="A-">A-</option>
<option value="B+">B+</option>
<option value="B-">B-</option>
<option value="AB+">AB+</option>
<option value="AB-">AB-</option>
<option value="O+">O+</option>
<option value="O-">O-</option>
</select>
</div>
<div class="form-group"><label for="peso">Peso</label><input type="number" id="peso"
placeholder="kg"></div>
<div class="form-group"><label for="altura">Altura</label><input type="number"
id="altura" placeholder="m"></div>
<div class="form-group full-width"><label for="alergias">Alergias</label><input
type="text" id="alergias" placeholder="Ex: AAS, Dipirona, etc"></div>
</div>
<div class="section-divider">Informações de convênio</div>
<div class="form-grid">
<div class="form-group">
<label for="convenio">Convênio</label>
<input type="text" id="convenio" name="convenio">
</div>
<div class="form-group"><label for="plano">Plano</label><input type="text" id="plano">
</div>
<div class="form-group"><label for="matricula">Nº de matrícula</label><input type="text"
id="matricula"></div>
<div class="form-group"><label for="validadeCarteira">Validade da Carteira</label><input
type="date" id="validadeCarteira"></div>
</div>
<div class="form-check-group">
<input type="checkbox" id="validadeIndeterminada">
<label for="validadeIndeterminada">Validade Indeterminada</label>
</div>
<div class="section-divider">Outras Informações</div>
<div class="form-grid">
<div class="form-group"><label for="codigoLegado">Código legado</label><input
type="text" id="codigoLegado"></div>
<div class="form-group full-width"><label for="observacoes">Observações</label><textarea
id="observacoes" rows="4"></textarea></div>
<div class="form-group full-width"><label for="anexos">Anexos do paciente</label><input
type="file" id="anexos"></div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-save">Salvar</button>
<a href="../paciente.html" class="btn btn-cancel">Cancelar</a>
</div>
</form>
</div>
</div>
</section>
</div>
</main>
</body>
</html>

View File

@ -0,0 +1,151 @@
document.addEventListener("DOMContentLoaded", () => {
const form = document.getElementById("cadastro-form");
// Pega o ID do paciente da URL. Se não houver, 'editId' será null.
const urlParams = new URLSearchParams(window.location.search);
const editId = urlParams.get("id");
function desativarFormulario() {
// Desativa todos os inputs, selects e textareas
form.querySelectorAll("input, select, textarea").forEach((el) => {
el.disabled = true;
});
// Remove o botão de submit
const submitBtn = form.querySelector('[type="submit"]');
if (submitBtn) {
submitBtn.remove();
}
}
// Exemplo: se a URL tiver ?mode=detalhes
if (window.location.search.includes("mode=detalhes")) {
desativarFormulario();
}
if (form) {
// Carrega a lista de pacientes
let pacientes = JSON.parse(localStorage.getItem("pacientes")) || [];
let pacienteParaEditar = null;
// Se houver um ID de edição na URL, encontra o paciente correspondente
if (editId) {
pacienteParaEditar = pacientes.find((p) => p.id == editId);
if (pacienteParaEditar) {
// Preenche o formulário com os dados do paciente para edição
document.getElementById("nome").value = pacienteParaEditar.nome;
document.getElementById("celular").value = pacienteParaEditar.celular;
document.getElementById("cidade").value = pacienteParaEditar.cidade;
document.getElementById("estado").value = pacienteParaEditar.estado;
document.getElementById("nomeSocial").value = pacienteParaEditar.nomeSocial;
document.getElementById("cpf").value = pacienteParaEditar.cpf;
document.getElementById("rg").value = pacienteParaEditar.rg;
document.getElementById("outrosDocs").value = pacienteParaEditar.outrosDocs;
document.getElementById("numDoc").value = pacienteParaEditar.numDoc;
document.getElementById("sexo").value = pacienteParaEditar.sexo;
document.getElementById("dataNascimento").value = pacienteParaEditar.dataNascimento;
document.getElementById("etnia").value = pacienteParaEditar.etnia;
document.getElementById("raca").value = pacienteParaEditar.raca;
document.getElementById("nacionalidade").value = pacienteParaEditar.nacionalidade;
document.getElementById("estadoCivil").value = pacienteParaEditar.estadoCivil;
document.getElementById("nomeMae").value = pacienteParaEditar.nomeMae;
document.getElementById("profissaoMae").value = pacienteParaEditar.profissaoMae;
document.getElementById("nomePai").value = pacienteParaEditar.nomePai;
document.getElementById("profissaoPai").value = pacienteParaEditar.profissaoPai;
document.getElementById("nomeResponsavel").value = pacienteParaEditar.nomeResponsavel;
document.getElementById("cpfResponsavel").value = pacienteParaEditar.cpfResponsavel;
document.getElementById("nomeEsposo").value = pacienteParaEditar.nomeEsposo;
document.getElementById("endereco").value = pacienteParaEditar.endereco;
document.getElementById("numero").value = pacienteParaEditar.numero;
document.getElementById("complemento").value = pacienteParaEditar.complemento;
document.getElementById("bairro").value = pacienteParaEditar.bairro;
document.getElementById("email").value = pacienteParaEditar.email;
document.getElementById("telefone1").value = pacienteParaEditar.telefone1;
document.getElementById("tipoSanguineo").value = pacienteParaEditar.tipoSanguineo;
document.getElementById("peso").value = pacienteParaEditar.peso;
document.getElementById("altura").value = pacienteParaEditar.altura;
document.getElementById("alergias").value = pacienteParaEditar.alergias;
document.getElementById("convenio").value = pacienteParaEditar.convenio;
document.getElementById("plano").value = pacienteParaEditar.plano;
document.getElementById("matricula").value = pacienteParaEditar.matricula;
document.getElementById("validadeCarteira").value = pacienteParaEditar.validadeCarteira;
document.getElementById("validadeIndeterminada").value = pacienteParaEditar.validadeIndeterminada;
document.getElementById("codigoLegado").value = pacienteParaEditar.codigoLegado;
document.getElementById("observacoes").value = pacienteParaEditar.observacoes;
document.getElementById("anexos").value = pacienteParaEditar.anexos;
}
}
const cpf = document.getElementById("cpf");
const telefone = document.getElementById("telefone1");
const celular = document.getElementById("celular");
// Aplique as máscaras
new Inputmask("999.999.999-99").mask(cpf);
new Inputmask("(99) 99999-9999").mask(celular);
new Inputmask("(99) 9999-9999").mask(telefone);
form.addEventListener("submit", (e) => {
e.preventDefault();
// Coletando os dados do formulário
const pacienteNovoOuAtualizado = {
nome: document.getElementById("nome").value,
celular: document.getElementById("celular").value,
cidade: document.getElementById("cidade").value,
estado: document.getElementById("estado").value,
nomeSocial: document.getElementById("nomeSocial").value,
cpf: document.getElementById("cpf").value.replace(/[.\-]/g, ""),
rg: document.getElementById("rg").value,
outrosDocs: document.getElementById("outrosDocs").value,
numDoc: document.getElementById("numDoc").value,
sexo: document.getElementById("sexo").value,
dataNascimento: document.getElementById("dataNascimento").value,
etnia: document.getElementById("etnia").value,
raca: document.getElementById("raca").value,
nacionalidade: document.getElementById("nacionalidade").value,
estadoCivil: document.getElementById("estadoCivil").value,
nomeMae: document.getElementById("nomeMae").value,
profissaoMae: document.getElementById("profissaoMae").value,
nomePai: document.getElementById("nomePai").value,
profissaoPai: document.getElementById("profissaoPai").value,
nomeResponsavel: document.getElementById("nomeResponsavel").value,
cpfResponsavel: document.getElementById("cpfResponsavel").value,
nomeEsposo: document.getElementById("nomeEsposo").value,
endereco: document.getElementById("endereco").value,
numero: document.getElementById("numero").value,
complemento: document.getElementById("complemento").value,
bairro: document.getElementById("bairro").value,
email: document.getElementById("email").value,
celular: document.getElementById("celular").value,
telefone1: document.getElementById("telefone1").value,
tipoSanguineo: document.getElementById("tipoSanguineo").value,
peso: document.getElementById("peso").value,
altura: document.getElementById("altura").value,
alergias: document.getElementById("alergias").value,
convenio: document.getElementById("convenio").value,
plano: document.getElementById("plano").value,
matricula: document.getElementById("matricula").value,
validadeCarteira: document.getElementById("validadeCarteira").value,
validadeIndeterminada: document.getElementById("validadeIndeterminada").value,
codigoLegado: document.getElementById("codigoLegado").value,
observacoes: document.getElementById("observacoes").value,
anexos: document.getElementById("anexos").value,
};
if (pacienteParaEditar) {
// Se for um paciente para editar, atualiza os dados dele
Object.assign(pacienteParaEditar, pacienteNovoOuAtualizado);
} else {
// Se for um novo paciente, cria um ID único e o adiciona à lista
pacienteNovoOuAtualizado.id = Date.now();
pacientes.push(pacienteNovoOuAtualizado);
}
// Salva a lista atualizada de volta no localStorage
localStorage.setItem("pacientes", JSON.stringify(pacientes));
// Redireciona para a página de listagem
window.location.href = "../paciente.html";
});
}
});

View File

@ -0,0 +1,211 @@
.main-button button {
font-size: 17px;
background: none;
margin-right: 30px;
margin-top: 10px;
border: none;
color: #243b51;
padding: 20px 10px;
border-bottom: 2px solid transparent;
transition: 0.6s;
}
.main-button-border:hover {
/*estilo no mouseenter*/
border: none;
margin-right: 30px;
margin-top: 10px;
padding: 20px 10px;
background: none;
border-bottom: 2px solid blue;
color: blue;
}
.btn-add {
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.2s;
margin: 20px 0px;
background-color: rgb(38, 137, 255);
color: #fff;
text-decoration: none;
}
.btn-add:hover {
background-color: rgb(30, 110, 204);
}
.filter-select {
padding: 8px;
margin-left: 8px;
border: 1px solid #ccc;
border-radius: 5px;
background-color: white;
font-size: 14px;
cursor: pointer;
}
.conteudo {
margin-left: 30px;
background-color: #fafafa;
padding: 25px;
border-radius: 7px;
}
/* Tabela */
#pacientes-tabela {
margin-top: 1.5rem;
width: 100%;
border-collapse: collapse;
border: 1px solid #ddd;
background-color: white;
font-size: 14px;
border-radius: 8px;
overflow: hidden;
}
#pacientes-tabela thead {
background-color: #e9ecef;
}
#pacientes-tabela thead th {
padding: 12px;
border-bottom: 1px solid #ccc;
text-align: left;
font-weight: bold;
}
#pacientes-tabela tbody td {
padding: 10px;
border-bottom: 1px solid #eee;
}
#pacientes-tabela tbody tr:hover {
background-color: #f1f1f1;
}
#pacientes-tabela tbody td button {
padding: 6px 10px;
font-size: 14px;
background-color: #6c757d;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
#pacientes-tabela tbody td button:hover {
background-color: #5a6268;
}
/* Media queries melhoradas para responsividade */
@media (max-width: 768px) {
/* Melhor organização do conteúdo principal em mobile */
.section-main-text {
padding: 20px;
padding-bottom: 0px;
margin-top: 10rem;
}
.section-main-text h1 {
font-size: 28px;
margin-bottom: 10px;
}
.section-main-text p {
font-size: 16px;
}
.main-button {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.main-button button {
margin-right: 0;
margin-top: 5px;
padding: 15px 8px;
font-size: 15px;
}
.conteudo {
margin: 20px;
padding: 20px;
}
/* Formulário responsivo */
#formLaudo {
flex-direction: column;
gap: 15px;
}
#formLaudo fieldset {
width: 100%;
}
#formLaudo button[type="submit"] {
width: 100%;
padding: 12px;
font-size: 16px;
}
/* Tabela responsiva com scroll horizontal */
.table-container {
overflow-x: auto;
margin-top: 20px;
}
#pacientes-tabela {
min-width: 600px;
font-size: 12px;
}
#pacientes-tabela thead th,
#pacientes-tabela tbody td {
padding: 8px;
white-space: nowrap;
}
}
/* Media query para tablets */
@media (max-width: 1024px) and (min-width: 769px) {
.section-main-text h1 {
font-size: 32px;
}
.conteudo {
margin: 25px;
}
}
/* Media query melhorada para telas muito pequenas */
@media (max-width: 480px) {
.section-main-text {
padding: 15px;
}
.section-main-text h1 {
font-size: 24px;
}
.section-main-text p {
font-size: 14px;
}
.conteudo {
margin: 15px;
padding: 15px;
}
#pacientes-tabela {
font-size: 11px;
}
#pacientes-tabela thead th,
#pacientes-tabela tbody td {
padding: 6px;
}
}

View File

@ -0,0 +1,141 @@
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Crud + Layout</title>
<link rel="stylesheet" href="../../global.css" />
<!-- css da página -->
<link rel="stylesheet" href="paciente.css" />
</head>
<body>
<main>
<!-- Overlay só aparece em mobile quando menu está ativo -->
<div class="overlay" id="overlay"></div>
<div class="flex">
<!-- Botão hambúrguer só aparece em mobile -->
<button class="hamburger-btn" id="hamburger-btn" aria-label="Abrir menu de navegação" aria-expanded="false">
<span></span>
<span></span>
<span></span>
</button>
<!-- Sidebar agora se comporta diferente em desktop vs mobile -->
<section class="sidebar" id="sidebar" role="navigation" aria-label="Menu principal">
<div class="div-sidebar">
<div class="abas">
<div class="logo1">
<a href="#" aria-label="Página inicial">
<img src="https://images.vexels.com/media/users/3/142777/isolated/preview/84711206e52e0d4ff6c793cb476ea264-logotipo-medico-da-estrela-do-heartbeat.png" alt="Logo médico" id="logo-med" />
</a>
</div>
<ul>
<li>
<a href="#" aria-label="Pacientes">
<img src="../../assets/layoutIcons/icons8-estetoscópio-50.png" alt="Pacientes" class="icon-sidebar" />
<p>Pacientes</p>
</a>
</li>
<li>
<a href="#" aria-label="Pacientes">
<img src="../../assets/layoutIcons/icons8-estetoscópio-50.png" alt="Pacientes" class="icon-sidebar" />
<p>Dashboard</p>
</a>
</li>
<li>
<a href="#" aria-label="Cadastro de usuários">
<img src="../../assets/layoutIcons/icons8-grupo-de-usuário-homem-homem-50.png" alt="Cadastro" class="icon-sidebar" />
<p>Médicos</p>
</a>
</li>
<li>
<a href="../../pages/laudo/laudoMedico.html" aria-label="Documentos">
<img src="../../assets/layoutIcons/icons8-document.svg" alt="Documentos" class="icon-sidebar" />
<p>Laúdos</p>
</a>
</li>
<li>
<a href="#" aria-label="Documentos">
<img src="../../assets/layoutIcons/icons8-document.svg" alt="Documentos" class="icon-sidebar" />
<p>Agenda</p>
</a>
</li>
<li>
<a href="#" aria-label="Configurações">
<img src="../../assets/layoutIcons/icons8-configurações.svg" alt="Configurações" class="icon-sidebar" />
<p>Settings</p>
</a>
</li>
</ul>
</div>
<div class="perfil-medico-sidebar">
<h3>Dr. Rafael Andrade</h3>
<p>Núcleo de Especialidades</p>
</div>
</div>
</section>
<section class="section-main">
<nav class="nav" role="banner">
<div class="div-search">
<input type="text" id="search-input" class="search-input" placeholder="Buscar paciente" aria-label="Campo de busca" />
<select id="filter-type" class="filter-select" aria-label="Selecionar filtro">
<option value="geral">Geral</option>
<option value="nome">Nome</option>
<option value="celular">Telefone</option>
<option value="cidade">Cidade</option>
<option value="estado">Estado</option>
<option value="convenio">Convênio</option>
<option value="cpf">CPF</option>
</select>
<button id="search-button" class="search-button" aria-label="Buscar">
<img src="../../assets/layoutIcons/icons8-pesquisar.svg" alt="Buscar" />
</button>
</div>
<div>
<ul class="icon-lista">
<li>
<a href="#" aria-label="Ajuda"><img src="../../assets/layoutIcons/icons8-ajuda-50.png" alt="Ajuda" /></a>
</li>
<li>
<button id="music" aria-label="Notificações"><img src="../../assets/layoutIcons/botao-ativar-notificacoes.png" alt="Notificações" /></button>
</li>
<!--button ta gerando um fundo branco, botei ID pra retirar o background-->
<li>
<a href="#" aria-label="Perfil do usuário"><img src="../../assets/layoutIcons/icons8-usuário-50.png" alt="Usuário" /></a>
</li>
</ul>
</div>
</nav>
<div class="conteudo">
<h1>Gerenciamento de Pacientes</h1>
<br /><br />
<a href="addPaciente/addPacient.html" id="btn-add" class="btn-add"> + Cadastrar Paciente </a>
<!-- Container para scroll horizontal da tabela -->
<div class="table-container">
<table id="pacientes-tabela">
<thead>
<tr>
<th>Nome</th>
<th>Telefone</th>
<th>Cidade</th>
<th>Estado</th>
<th>Ação</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</section>
</div>
</main>
<script src="/Squad-21/clinicApp/scriptGlobal.js"></script>
<script src="./paciente.js"></script>
</body>
</html>

View File

@ -0,0 +1,142 @@
document.addEventListener("DOMContentLoaded", () => {
const tabelaPacientes = document.getElementById("pacientes-tabela");
let pacientes = JSON.parse(localStorage.getItem("pacientes")) || [];
const atualizarLista = () => {
if (!tabelaPacientes) return;
const tbody = tabelaPacientes.querySelector("tbody");
tbody.innerHTML = "";
pacientes.forEach((paciente, index) => {
const row = document.createElement("tr");
row.innerHTML = `
<td data-label="Nome">${paciente.nome}</td>
<td data-label="Telefone ou Celular">${paciente.celular || "-"}</td>
<td data-label="Cidade">${paciente.cidade || "-"}</td>
<td data-label="Estado">${paciente.estado || "-"}</td>
<td data-label="Ações">
<button class="btn btn-edit" data-id="${paciente.id}">Editar</button>
<button class="btn btn-delete" data-index="${index}">Excluir</button>
<button class="btn btn-detail" data-id="${paciente.id}">Detalhes</button>
</td>
`;
tbody.appendChild(row);
});
// Adiciona event listeners para os botões "Editar"
document.querySelectorAll(".btn-edit").forEach((btn) => {
btn.addEventListener("click", (e) => {
const id = e.target.dataset.id;
window.location.href = `addPaciente/addPacient.html?id=${id}`;
});
});
// Adiciona event listeners para os botões "Excluir"
document.querySelectorAll(".btn-delete").forEach((btn) => {
btn.addEventListener("click", (e) => {
const index = e.target.dataset.index;
if (confirm("Tem certeza que deseja excluir este paciente?")) {
pacientes.splice(index, 1);
localStorage.setItem("pacientes", JSON.stringify(pacientes));
atualizarLista();
}
});
});
document.querySelectorAll(".btn-detail").forEach((btn) => {
btn.addEventListener("click", (e) => {
const id = e.target.dataset.id;
window.location.href = `addPaciente/addPacient.html?mode=detalhes&id=${id}`;
});
});
};
atualizarLista();
});
document.addEventListener("DOMContentLoaded", () => {
const tabelaPacientes = document.getElementById("pacientes-tabela");
const searchInput = document.getElementById("search-input");
const filterType = document.getElementById("filter-type");
const searchButton = document.getElementById("search-button");
let pacientes = JSON.parse(localStorage.getItem("pacientes")) || [];
const atualizarLista = (filtro = "", tipo = "geral") => {
if (!tabelaPacientes) return;
const tbody = tabelaPacientes.querySelector("tbody");
tbody.innerHTML = "";
pacientes
.filter((paciente) => {
if (!filtro) return true;
const termo = filtro.toLowerCase();
if (tipo === "geral") {
// Busca em todos os campos
return (paciente.nome || "").toLowerCase().includes(termo) || (paciente.celular || "").toLowerCase().includes(termo) || (paciente.cidade || "").toLowerCase().includes(termo) || (paciente.estado || "").toLowerCase().includes(termo) || (paciente.convenio || "").toLowerCase().includes(termo) || (paciente.cpf || "").toLowerCase().includes(termo);
} else {
// Busca apenas no campo escolhido
const valorCampo = (paciente[tipo] || "").toString().toLowerCase();
return valorCampo.includes(termo);
}
})
.forEach((paciente, index) => {
const row = document.createElement("tr");
row.innerHTML = `
<td data-label="Nome">${paciente.nome}</td>
<td data-label="Telefone ou Celular">${paciente.celular || "-"}</td>
<td data-label="Cidade">${paciente.cidade || "-"}</td>
<td data-label="Estado">${paciente.estado || "-"}</td>
<td data-label="Ações">
<button class="btn btn-edit" data-id="${paciente.id}">Editar</button>
<button class="btn btn-delete" data-index="${index}">Excluir</button>
<button class="btn btn-detail" data-id="${paciente.id}">Detalhes</button>
</td>
`;
tbody.appendChild(row);
});
// Botões Editar
document.querySelectorAll(".btn-edit").forEach((btn) => {
btn.addEventListener("click", (e) => {
const id = e.target.dataset.id;
window.location.href = `addPaciente/addPacient.html?id=${id}`;
});
});
// Botões Excluir
document.querySelectorAll(".btn-delete").forEach((btn) => {
btn.addEventListener("click", (e) => {
const index = e.target.dataset.index;
if (confirm("Tem certeza que deseja excluir este paciente?")) {
pacientes.splice(index, 1);
localStorage.setItem("pacientes", JSON.stringify(pacientes));
atualizarLista();
}
});
});
document.querySelectorAll(".btn-detail").forEach((btn) => {
btn.addEventListener("click", (e) => {
const id = e.target.dataset.id;
window.location.href = `addPaciente/addPacient.html?mode=detalhes&id=${id}`;
});
});
};
// Clique no botão de busca
searchButton.addEventListener("click", () => {
atualizarLista(searchInput.value, filterType.value);
});
// Enter no campo de busca
searchInput.addEventListener("keyup", (e) => {
if (e.key === "Enter") {
atualizarLista(searchInput.value, filterType.value);
}
});
atualizarLista();
});

View File

@ -0,0 +1,58 @@
const hamburgerBtn = document.getElementById("hamburger-btn");
const sidebar = document.getElementById("sidebar");
const overlay = document.getElementById("overlay");
function toggleMenu() {
const isActive = sidebar.classList.contains("active");
if (isActive) {
closeMenu();
} else {
openMenu();
}
}
function openMenu() {
sidebar.classList.add("active");
hamburgerBtn.classList.add("active");
overlay.classList.add("active");
hamburgerBtn.setAttribute("aria-expanded", "true");
hamburgerBtn.setAttribute("aria-label", "Fechar menu de navegação");
// Previne scroll do body quando menu está aberto
document.body.style.overflow = "hidden";
}
function closeMenu() {
sidebar.classList.remove("active");
hamburgerBtn.classList.remove("active");
overlay.classList.remove("active");
hamburgerBtn.setAttribute("aria-expanded", "false");
hamburgerBtn.setAttribute("aria-label", "Abrir menu de navegação");
// Restaura scroll do body
document.body.style.overflow = "";
}
// Event listeners para o menu hambúrguer
hamburgerBtn.addEventListener("click", toggleMenu);
overlay.addEventListener("click", closeMenu);
document.addEventListener("keydown", (e) => {
if (e.key === "Escape" && sidebar.classList.contains("active")) {
closeMenu();
}
});
sidebar.addEventListener("click", (e) => {
if (e.target.tagName === "A" && window.innerWidth <= 768) {
closeMenu();
}
});
window.addEventListener("resize", () => {
if (window.innerWidth > 768 && sidebar.classList.contains("active")) {
closeMenu();
}
});

View File

@ -1,160 +0,0 @@
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Calendar, Clock, User, Shield, Stethoscope, Receipt, IdCard } from "lucide-react"
export default function HomePage() {
return (
<div className="min-h-screen bg-background">
<div className="container mx-auto px-4 py-16">
<div className="text-center mb-12">
<h1 className="text-4xl font-bold text-foreground mb-4">Central de Operações <br>
</br>
MediConnect
</h1>
<p className="text-xl text-muted-foreground max-w-2xl mx-auto">
Gerencie suas consultas médicas de forma simples e eficiente
</p>
</div>
<div className="grid md:grid-cols-3 gap-8 max-w-6xl mx-auto">
<Card className="hover:shadow-lg transition-shadow flex flex-col h-full">
<CardHeader className="text-center flex-shrink-0">
<User className="w-12 h-12 text-blue-600 mx-auto mb-4" />
<CardTitle>Área do Paciente</CardTitle>
<CardDescription>Tenha o controle total da sua saúde: agende, consulte o histórico e informações pessoais</CardDescription>
</CardHeader>
<CardContent className="space-y-4 flex-grow flex flex-col">
<div className="space-y-3 flex-grow">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Calendar className="w-4 h-4" />
<span>Agendar consultas</span>
</div>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Clock className="w-4 h-4" />
<span>Ver histórico de consultas</span>
</div>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<User className="w-4 h-4" />
<span>Gerenciar dados pessoais</span>
</div>
</div>
<Link href="/patient/login" className="block mt-auto">
<Button className="w-full">Entrar como Paciente</Button>
</Link>
</CardContent>
</Card>
<Card className="hover:shadow-lg transition-shadow flex flex-col h-full">
<CardHeader className="text-center flex-shrink-0">
<Shield className="w-12 h-12 text-purple-600 mx-auto mb-4" />
<CardTitle>Área da Secretária</CardTitle>
<CardDescription>Otimize o fluxo de trabalho e mantenha a agenda sempre organizada</CardDescription>
</CardHeader>
<CardContent className="space-y-4 flex-grow flex flex-col">
<div className="space-y-3 flex-grow">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Calendar className="w-4 h-4" />
<span>Gerenciar consultas</span>
</div>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<User className="w-4 h-4" />
<span>Cadastrar pacientes</span>
</div>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Clock className="w-4 h-4" />
<span>Controlar agenda</span>
</div>
</div>
<Link href="/secretary/login" className="block mt-auto">
<Button className="w-full bg-purple-600 text-white hover:bg-purple-700 dark:bg-purple-500 dark:hover:bg-purple-600 dark:text-white">Entrar como Secretária</Button>
</Link>
</CardContent>
</Card>
<Card className="hover:shadow-lg transition-shadow flex flex-col h-full">
<CardHeader className="text-center flex-shrink-0">
<Stethoscope className="w-12 h-12 text-green-600 mx-auto mb-4" />
<CardTitle>Área Médica</CardTitle>
<CardDescription>Visualize sua agenda, laudos de pacientes e histórico para um diagnóstico preciso</CardDescription>
</CardHeader>
<CardContent className="space-y-4 flex-grow flex flex-col">
<div className="space-y-3 flex-grow">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Calendar className="w-4 h-4" />
<span>Gerenciar agenda</span>
</div>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<User className="w-4 h-4" />
<span>Ver pacientes</span>
</div>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Clock className="w-4 h-4" />
<span>Histórico de atendimentos</span>
</div>
</div>
<Link href="/doctor/login" className="block mt-auto">
<Button className="w-full bg-green-600 text-white hover:bg-green-700 dark:bg-green-500 dark:hover:bg-green-600 dark:text-white">Entrar como Médico</Button>
</Link>
</CardContent>
</Card>
<Card className="hover:shadow-lg transition-shadow flex flex-col h-full">
<CardHeader className="text-center flex-shrink-0">
<IdCard className="w-12 h-12 text-blue-600 mx-auto mb-4" />
<CardTitle>Área do Gestor</CardTitle>
<CardDescription>Configure o sistema, gerencie usuários e controle a operação da clínica</CardDescription>
</CardHeader>
<CardContent className="space-y-4 flex-grow flex flex-col">
<div className="space-y-3 flex-grow">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Calendar className="w-4 h-4" />
<span>Relatórios gerenciais</span>
</div>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<User className="w-4 h-4" />
<span>Configurações do sistema</span>
</div>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Clock className="w-4 h-4" />
<span>Gestão de usuários</span>
</div>
</div>
<Link href="/manager/login" className="block mt-auto">
<Button className="w-full bg-blue-600 text-white hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-600 dark:text-white">Entrar como Gestor</Button>
</Link>
</CardContent>
</Card>
<Card className="hover:shadow-lg transition-shadow flex flex-col h-full">
<CardHeader className="text-center flex-shrink-0">
<Receipt className="w-12 h-12 text-orange-600 mx-auto mb-4" />
<CardTitle>Área de Finanças</CardTitle>
<CardDescription>Controle o faturamento, pagamentos e a saúde financeira da clínica</CardDescription>
</CardHeader>
<CardContent className="space-y-4 flex-grow flex flex-col">
<div className="space-y-3 flex-grow">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Calendar className="w-4 h-4" />
<span>Relatórios financeiros</span>
</div>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<User className="w-4 h-4" />
<span>Faturamento</span>
</div>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Clock className="w-4 h-4" />
<span>Controle de pagamentos</span>
</div>
</div>
<Link href="finance/login" className="block mt-auto">
<Button className="w-full bg-orange-600 text-white hover:bg-orange-700 dark:bg-orange-500 dark:hover:bg-orange-600 dark:text-white">Entrar como Financeiro</Button>
</Link>
</CardContent>
</Card>
</div>
</div>
</div>
)
}

View File

@ -1,105 +0,0 @@
"use client";
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
type Theme = 'light' | 'dark';
type Contrast = 'normal' | 'high';
interface AccessibilityContextProps {
theme: Theme;
setTheme: (theme: Theme) => void;
contrast: Contrast;
setContrast: (contrast: Contrast) => void;
fontSize: number;
increaseFontSize: () => void;
decreaseFontSize: () => void;
resetFontSize: () => void;
}
const AccessibilityContext = createContext<AccessibilityContextProps | undefined>(undefined);
export const AccessibilityProvider = ({ children }: { children: ReactNode }) => {
const [theme, setThemeState] = useState<Theme>(() => {
if (typeof window !== 'undefined') {
return (localStorage.getItem('accessibility-theme') as Theme) || 'light';
}
return 'light';
});
const [contrast, setContrastState] = useState<Contrast>(() => {
if (typeof window !== 'undefined') {
return (localStorage.getItem('accessibility-contrast') as Contrast) || 'normal';
}
return 'normal';
});
const [fontSize, setFontSize] = useState<number>(() => {
if (typeof window !== 'undefined') {
const storedSize = localStorage.getItem('accessibility-font-size');
return storedSize ? parseFloat(storedSize) : 16;
}
return 16;
});
useEffect(() => {
const root = document.documentElement;
// Theme
root.classList.remove('light', 'dark');
root.classList.add(theme);
localStorage.setItem('accessibility-theme', theme);
// Contrast
root.classList.remove('normal-contrast', 'high-contrast');
root.classList.add(contrast === 'high' ? 'high-contrast' : 'normal-contrast');
localStorage.setItem('accessibility-contrast', contrast);
// Font Size
root.style.fontSize = `${fontSize}px`;
localStorage.setItem('accessibility-font-size', fontSize.toString());
}, [theme, contrast, fontSize]);
const setTheme = (newTheme: Theme) => {
setThemeState(newTheme);
};
const setContrast = (newContrast: Contrast) => {
setContrastState(newContrast);
};
const increaseFontSize = () => {
setFontSize(prev => Math.min(prev + 2, 24)); // Cap at 24px
};
const decreaseFontSize = () => {
setFontSize(prev => Math.max(prev - 2, 12)); // Cap at 12px
};
const resetFontSize = () => {
setFontSize(16);
};
return (
<AccessibilityContext.Provider
value={{
theme,
setTheme,
contrast,
setContrast,
fontSize,
increaseFontSize,
decreaseFontSize,
resetFontSize,
}}
>
{children}
</AccessibilityContext.Provider>
);
};
export const useAccessibility = () => {
const context = useContext(AccessibilityContext);
if (context === undefined) {
throw new Error('useAccessibility must be used within an AccessibilityProvider');
}
return context;
};

View File

@ -1,112 +0,0 @@
"use client";
import React, { createContext, useContext, useState, ReactNode } from 'react';
// A interface Appointment permanece a mesma
export interface Appointment {
id: string;
doctorName: string;
specialty: string;
date: string;
time: string;
location: string;
phone: string;
status: 'Agendada' | 'Realizada' | 'Cancelada';
observations?: string;
}
export interface AppointmentsContextType {
appointments: Appointment[];
addAppointment: (appointmentData: Omit<Appointment, 'id' | 'status'>) => void;
updateAppointment: (appointmentId: string, updatedData: Partial<Omit<Appointment, 'id'>>) => void;
// [NOVA FUNÇÃO] Adicionando a assinatura da função de exclusão ao nosso contrato
deleteAppointment: (appointmentId: string) => void;
}
const AppointmentsContext = createContext<AppointmentsContextType | undefined>(undefined);
// Os dados iniciais permanecem os mesmos
const initialAppointments: Appointment[] = [
{
id: '1',
doctorName: "Dr. João Silva",
specialty: "Cardiologia",
date: "2024-08-15",
time: "14:30",
status: "Agendada",
location: "Consultório A - 2º andar",
phone: "(11) 3333-4444",
observations: "Paciente relata dor no peito.",
},
{
id: '2',
doctorName: "Dra. Maria Santos",
specialty: "Dermatologia",
date: "2024-09-10",
time: "10:00",
status: "Agendada",
location: "Consultório B - 1º andar",
phone: "(11) 3333-5555",
},
{
id: '3',
doctorName: "Dr. Pedro Costa",
specialty: "Ortopedia",
date: "2024-07-08",
time: "16:00",
status: "Realizada",
location: "Consultório C - 3º andar",
phone: "(11) 3333-6666",
},
];
export function AppointmentsProvider({ children }: { children: ReactNode }) {
const [appointments, setAppointments] = useState<Appointment[]>(initialAppointments);
const addAppointment = (appointmentData: Omit<Appointment, 'id' | 'status'>) => {
const newAppointment: Appointment = {
id: Date.now().toString(),
status: 'Agendada',
...appointmentData,
};
setAppointments((prev) => [...prev, newAppointment]);
};
const updateAppointment = (appointmentId: string, updatedData: Partial<Omit<Appointment, 'id'>>) => {
setAppointments((prev) =>
prev.map((apt) =>
apt.id === appointmentId ? { ...apt, ...updatedData } : apt
)
);
};
// [NOVA FUNÇÃO] Implementando a lógica de exclusão real
const deleteAppointment = (appointmentId: string) => {
setAppointments((prev) =>
// O método 'filter' cria um novo array com todos os itens
// EXCETO aquele cujo ID corresponde ao que queremos excluir.
prev.filter((apt) => apt.id !== appointmentId)
);
};
const value = {
appointments,
addAppointment,
updateAppointment,
deleteAppointment, // Disponibilizando a nova função para os componentes
};
return (
<AppointmentsContext.Provider value={value}>
{children}
</AppointmentsContext.Provider>
);
}
export function useAppointments() {
const context = useContext(AppointmentsContext);
if (context === undefined) {
throw new Error('useAppointments deve ser usado dentro de um AppointmentsProvider');
}
return context;
}

View File

@ -1,238 +0,0 @@
// ARQUIVO COMPLETO COM A INTERFACE CORRIGIDA: app/doctor/consultas/page.tsx
"use client";
import type React from "react";
import { useState, useEffect, useMemo } from "react";
import { useAuthLayout } from "@/hooks/useAuthLayout";
import { appointmentsService } from "@/services/appointmentsApi.mjs";
import { patientsService } from "@/services/patientsApi.mjs";
import { doctorsService } from "@/services/doctorsApi.mjs";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Calendar as CalendarShadcn } from "@/components/ui/calendar";
import { Separator } from "@/components/ui/separator";
import { Clock, Calendar as CalendarIcon, User, X, RefreshCw, Loader2, MapPin, Phone, List } from "lucide-react";
import { format, isFuture, parseISO, isValid, isToday, isTomorrow } from "date-fns";
import { ptBR } from "date-fns/locale";
import { toast } from "sonner";
import Sidebar from "@/components/Sidebar";
// Interfaces (sem alteração)
interface EnrichedAppointment {
id: string;
patientName: string;
patientPhone: string;
scheduled_at: string;
status: "requested" | "confirmed" | "completed" | "cancelled" | "checked_in" | "no_show";
location: string;
}
export default function DoctorAppointmentsPage() {
const { user, isLoading: isAuthLoading } = useAuthLayout({ requiredRole: "medico" });
const [allAppointments, setAllAppointments] = useState<EnrichedAppointment[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [selectedDate, setSelectedDate] = useState<Date | undefined>(new Date());
const fetchAppointments = async (authUserId: string) => {
setIsLoading(true);
try {
const allDoctors = await doctorsService.list();
const currentDoctor = allDoctors.find((doc: any) => doc.user_id === authUserId);
if (!currentDoctor) {
toast.error("Perfil de médico não encontrado para este usuário.");
return setIsLoading(false);
}
const doctorId = currentDoctor.id;
const [appointmentsList, patientsList] = await Promise.all([
appointmentsService.search_appointment(`doctor_id=eq.${doctorId}&order=scheduled_at.asc`),
patientsService.list()
]);
const patientsMap = new Map<string, { name: string; phone: string }>(
patientsList.map((p: any) => [p.id, { name: p.full_name, phone: p.phone_mobile }])
);
const enrichedAppointments = appointmentsList.map((apt: any) => ({
id: apt.id,
patientName: patientsMap.get(apt.patient_id)?.name || "Paciente Desconhecido",
patientPhone: patientsMap.get(apt.patient_id)?.phone || "N/A",
scheduled_at: apt.scheduled_at,
status: apt.status,
location: "Consultório Principal",
}));
setAllAppointments(enrichedAppointments);
} catch (error) {
console.error("Erro ao carregar a agenda:", error);
toast.error("Não foi possível carregar sua agenda.");
} finally {
setIsLoading(false);
}
};
useEffect(() => {
if (user?.id) {
fetchAppointments(user.id);
}
}, [user]);
const groupedAppointments = useMemo(() => {
const appointmentsToDisplay = selectedDate
? allAppointments.filter(app => app.scheduled_at && app.scheduled_at.startsWith(format(selectedDate, "yyyy-MM-dd")))
: allAppointments.filter(app => {
if (!app.scheduled_at) return false;
const dateObj = parseISO(app.scheduled_at);
return isValid(dateObj) && isFuture(dateObj);
});
return appointmentsToDisplay.reduce((acc, appointment) => {
const dateKey = format(parseISO(appointment.scheduled_at), "yyyy-MM-dd");
if (!acc[dateKey]) acc[dateKey] = [];
acc[dateKey].push(appointment);
return acc;
}, {} as Record<string, EnrichedAppointment[]>);
}, [allAppointments, selectedDate]);
const bookedDays = useMemo(() => {
return allAppointments
.map(app => app.scheduled_at ? new Date(app.scheduled_at) : null)
.filter((date): date is Date => date !== null);
}, [allAppointments]);
const formatDisplayDate = (dateString: string) => {
const date = parseISO(dateString);
if (isToday(date)) return `Hoje, ${format(date, "dd 'de' MMMM", { locale: ptBR })}`;
if (isTomorrow(date)) return `Amanhã, ${format(date, "dd 'de' MMMM", { locale: ptBR })}`;
return format(date, "EEEE, dd 'de' MMMM", { locale: ptBR });
};
const statusPT: Record<string, string> = {
confirmed: "Confirmada",
completed: "Concluída",
cancelled: "Cancelada",
requested: "Solicitada",
no_show: "oculta",
checked_in: "Aguardando",
};
const getStatusVariant = (status: EnrichedAppointment['status']) => {
switch (status) {
case "confirmed": case "checked_in": return "text-foreground bg-blue-100 hover:bg-blue-150";
case "completed": return "text-foreground bg-green-100 hover:bg-green-150";
case "cancelled": case "no_show": return "text-foreground bg-red-200 hover:bg-red-250";
case "requested": return "text-foreground bg-yellow-100 hover:bg-yellow-150";
default: return "border-gray bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90";
}
};
const handleCancel = async (id: string) => {
// ... (função sem alteração)
};
const handleReSchedule = (id: string) => {
// ... (função sem alteração)
};
if (isAuthLoading) {
return <Sidebar><div>Carregando...</div></Sidebar>;
}
return (
<Sidebar>
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold text-foreground">Agenda Médica</h1>
<p className="text-muted-foreground">Consultas para {user?.name || "você"}</p>
</div>
<div className="flex justify-between items-center">
<h2 className="text-xl font-semibold capitalize">
{selectedDate ? `Agenda de ${format(selectedDate, "dd/MM/yyyy")}` : "Próximas Consultas"}
</h2>
<div className="flex gap-2">
<Button onClick={() => setSelectedDate(undefined)} variant="ghost" size="sm"><List className="mr-2 h-4 w-4" />Mostrar Todas</Button>
<Button onClick={() => user?.id && fetchAppointments(user.id)} disabled={isLoading} variant="outline" size="sm"><RefreshCw className={`mr-2 h-4 w-4 ${isLoading ? 'animate-spin' : ''}`} />Atualizar</Button>
</div>
</div>
<div className="grid lg:grid-cols-3 gap-6">
<div className="lg:col-span-1">
<Card>
<CardHeader><CardTitle className="flex items-center"><CalendarIcon className="mr-2 h-5 w-5" />Filtrar por Data</CardTitle><CardDescription>Selecione um dia para ver os detalhes.</CardDescription></CardHeader>
<CardContent className="flex justify-center p-2">
<CalendarShadcn mode="single" selected={selectedDate} onSelect={setSelectedDate} modifiers={{ booked: bookedDays }} modifiersClassNames={{ booked: "bg-primary/20" }} className="rounded-md border p-2" locale={ptBR} />
</CardContent>
</Card>
</div>
<div className="lg:col-span-2 space-y-6">
{isLoading ? (
<div className="flex justify-center items-center h-48"><Loader2 className="h-8 w-8 animate-spin text-primary" /></div>
) : Object.keys(groupedAppointments).length === 0 ? (
<Card className="flex flex-col items-center justify-center h-48 text-center">
<CardHeader><CardTitle>Nenhuma consulta encontrada</CardTitle></CardHeader>
<CardContent><p className="text-muted-foreground">{selectedDate ? "Não há agendamentos para esta data." : "Não há próximas consultas agendadas."}</p></CardContent>
</Card>
) : (
Object.entries(groupedAppointments).map(([date, appointmentsForDay]) => (
<div key={date}>
<h3 className="text-lg font-semibold text-foreground mb-3 capitalize">{formatDisplayDate(date)}</h3>
<div className="space-y-4">
{appointmentsForDay.map((appointment) => {
const showActions = appointment.status === "requested" || appointment.status === "confirmed";
const scheduledAtDate = parseISO(appointment.scheduled_at);
return (
// *** INÍCIO DA MUDANÇA NO CARD ***
<Card key={appointment.id} className="shadow-sm hover:shadow-md transition-shadow">
<CardContent className="p-4 grid grid-cols-3 items-center gap-4">
{/* Coluna 1: Nome e Hora */}
<div className="col-span-1 flex flex-col gap-2">
<div className="font-semibold flex items-center text-foreground">
<User className="mr-2 h-4 w-4 text-primary" />
{appointment.patientName}
</div>
<div className="flex items-center text-sm text-muted-foreground">
<Clock className="mr-2 h-4 w-4" />
{format(scheduledAtDate, "HH:mm")}
</div>
</div>
{/* Coluna 2: Status e Telefone */}
<div className="col-span-1 flex flex-col items-center gap-2">
<Badge variant="outline" className={getStatusVariant(appointment.status)}>{statusPT[appointment.status].replace('_', ' ')}</Badge>
<div className="flex items-center text-sm text-muted-foreground">
<Phone className="mr-2 h-4 w-4" />
{appointment.patientPhone}
</div>
</div>
{/* Coluna 3: Ações */}
<div className="col-span-1 flex justify-end">
{showActions && (
<div className="flex flex-col sm:flex-row gap-2">
<Button variant="outline" size="sm" onClick={() => handleReSchedule(appointment.id)}>
<RefreshCw className="mr-1.5 h-4 w-4" />Reagendar
</Button>
<Button variant="destructive" size="sm" onClick={() => handleCancel(appointment.id)}>
<X className="mr-1.5 h-4 w-4" />Cancelar
</Button>
</div>
)}
</div>
</CardContent>
</Card>
// *** FIM DA MUDANÇA NO CARD ***
);
})}
</div>
<Separator className="my-6" />
</div>
))
)}
</div>
</div>
</div>
</Sidebar>
);
}

View File

@ -1,416 +0,0 @@
"use client";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Calendar, Clock, User, Trash2 } from "lucide-react";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import Link from "next/link";
import { useEffect, useState, useMemo } from "react"; // Adicionado useMemo
import { toast } from "@/hooks/use-toast";
import { useAuthLayout } from "@/hooks/useAuthLayout";
import { patientsService } from "@/services/patientsApi.mjs";
import { appointmentsService } from "@/services/appointmentsApi.mjs";
import { format, parseISO, isAfter, isSameMonth, startOfToday } from "date-fns";
import { ptBR } from "date-fns/locale";
import { AvailabilityService } from "@/services/availabilityApi.mjs";
import { exceptionsService } from "@/services/exceptionApi.mjs";
import { doctorsService } from "@/services/doctorsApi.mjs";
import { usersService } from "@/services/usersApi.mjs";
import Sidebar from "@/components/Sidebar";
import WeeklyScheduleCard from "@/components/ui/WeeklyScheduleCard";
type Appointment = {
id: string;
doctor_id: string;
patient_id: string;
scheduled_at: string;
status: string;
};
type EnrichedAppointment = Appointment & {
patientName: string;
};
type Availability = {
id: string;
doctor_id: string;
weekday: string;
start_time: string;
end_time: string;
slot_minutes: number;
appointment_type: string;
active: boolean;
created_at: string;
updated_at: string;
created_by: string;
updated_by: string | null;
};
type Schedule = {
weekday: object;
};
type Doctor = {
id: string;
user_id: string | null;
crm: string;
crm_uf: string;
specialty: string;
full_name: string;
cpf: string;
email: string;
phone_mobile: string | null;
phone2: string | null;
cep: string | null;
street: string | null;
number: string | null;
complement: string | null;
neighborhood: string | null;
city: string | null;
state: string | null;
birth_date: string | null;
rg: string | null;
active: boolean;
created_at: string;
updated_at: string;
created_by: string;
updated_by: string | null;
max_days_in_advance: number;
rating: number | null;
};
interface UserPermissions {
isAdmin: boolean;
isManager: boolean;
isDoctor: boolean;
isSecretary: boolean;
isAdminOrManager: boolean;
}
interface UserData {
user: {
id: string;
email: string;
email_confirmed_at: string | null;
created_at: string | null;
last_sign_in_at: string | null;
};
profile: {
id: string;
full_name: string;
email: string;
phone: string;
avatar_url: string | null;
disabled: boolean;
created_at: string | null;
updated_at: string | null;
};
roles: string[];
permissions: UserPermissions;
}
interface Exception {
id: string;
doctor_id: string;
date: string;
start_time: string | null;
end_time: string | null;
kind: "bloqueio" | "disponibilidade";
reason: string | null;
created_at: string;
created_by: string;
}
type Patient = {
id: string;
full_name: string;
};
export default function DoctorDashboard() {
// --- CORREÇÃO CRÍTICA DO LOOP ---
// Usamos useMemo para garantir que o array de roles seja uma referência estável
// e não dispare o useEffect do useAuthLayout infinitamente.
const requiredRoles = useMemo(() => ['medico'], []);
const { user } = useAuthLayout({ requiredRole: requiredRoles });
const [loggedDoctor, setLoggedDoctor] = useState<Doctor | null>(null);
const [userData, setUserData] = useState<UserData>();
const [availability, setAvailability] = useState<any | null>(null);
const [exceptions, setExceptions] = useState<Exception[]>([]);
const [schedule, setSchedule] = useState<Record<string, { start: string; end: string }[]>>({});
const formatTime = (time?: string | null) => time?.split(":")?.slice(0, 2).join(":") ?? "";
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [exceptionToDelete, setExceptionToDelete] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [nextAppointment, setNextAppointment] = useState<EnrichedAppointment | null>(null);
const [monthlyCount, setMonthlyCount] = useState<number>(0);
const weekdaysPT: Record<string, string> = { sunday: "Domingo", monday: "Segunda", tuesday: "Terça", wednesday: "Quarta", thursday: "Quinta", friday: "Sexta", saturday: "Sábado" };
useEffect(() => {
const fetchData = async () => {
if (!user?.id) return;
try {
const doctorsList: Doctor[] = await doctorsService.list();
const currentDoctor = doctorsList.find(doc => doc.user_id === user.id);
if (!currentDoctor) {
setError("Perfil de médico não encontrado para este usuário.");
return;
}
setLoggedDoctor(currentDoctor);
const [appointmentsList, patientsList, availabilityList, exceptionsList] = await Promise.all([
appointmentsService.list(),
patientsService.list(),
AvailabilityService.list(),
exceptionsService.list()
]);
const patientsMap = new Map(patientsList.map((p: Patient) => [p.id, p.full_name]));
const doctorAppointments = appointmentsList
.filter((apt: Appointment) => apt.doctor_id === currentDoctor.id)
.map((apt: Appointment): EnrichedAppointment => ({
...apt,
patientName: String(patientsMap.get(apt.patient_id) || "Paciente Desconhecido"),
}));
const today = startOfToday();
const upcomingAppointments = doctorAppointments
.filter(apt => isAfter(parseISO(apt.scheduled_at), today))
.sort((a, b) => new Date(a.scheduled_at).getTime() - new Date(b.scheduled_at).getTime());
setNextAppointment(upcomingAppointments[0] || null);
const activeStatuses = ['confirmed', 'requested', 'checked_in'];
const currentMonthAppointments = doctorAppointments.filter(apt =>
isSameMonth(parseISO(apt.scheduled_at), new Date()) && activeStatuses.includes(apt.status)
);
setMonthlyCount(currentMonthAppointments.length);
setAvailability(availabilityList.filter((d: any) => d.doctor_id === currentDoctor.id));
setExceptions(exceptionsList.filter((e: any) => e.doctor_id === currentDoctor.id));
} catch (e: any) {
setError(e?.message || "Erro ao buscar dados do dashboard");
console.error("Erro no dashboard:", e);
}
};
fetchData();
}, [user?.id]);
function findDoctorById(id: string, doctors: Doctor[]) {
return doctors.find((doctor) => doctor.user_id === id);
}
const openDeleteDialog = (exceptionId: string) => {
setExceptionToDelete(exceptionId);
setDeleteDialogOpen(true);
};
const handleDeleteException = async (ExceptionId: string) => {
try {
const res = await exceptionsService.delete(ExceptionId);
if (res && res.error) { throw new Error(res.message || "A API retornou um erro"); }
toast({ title: "Sucesso", description: "Exceção deletada com sucesso" });
setExceptions((prev: Exception[]) => prev.filter((p) => String(p.id) !== String(ExceptionId)));
} catch (e: any) {
toast({ title: "Erro", description: e?.message || "Não foi possível deletar a exceção" });
}
setDeleteDialogOpen(false);
setExceptionToDelete(null);
};
function formatAvailability(data: Availability[]) {
if (!data) return {};
const schedule = data.reduce((acc: any, item) => {
const { weekday, start_time, end_time } = item;
if (!acc[weekday]) acc[weekday] = [];
acc[weekday].push({ start: start_time, end: end_time });
return acc;
}, {} as Record<string, { start: string; end: string }[]>);
return schedule;
}
useEffect(() => {
if (availability) {
const formatted = formatAvailability(availability);
setSchedule(formatted);
}
}, [availability]);
return (
<Sidebar>
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold">Dashboard</h1>
<p className="text-muted-foreground">
Bem-vindo ao seu portal de consultas médicas
</p>
</div>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Próxima Consulta</CardTitle>
<Calendar className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
{nextAppointment ? (
<>
<p className="text-2xl font-bold capitalize">
{nextAppointment.patientName} - {format(parseISO(nextAppointment.scheduled_at), "HH:mm")}
</p>
<div className="text-x text-muted-foreground">
{format(parseISO(nextAppointment.scheduled_at), "dd MMM", { locale: ptBR })}
</div>
</>
) : (
<>
<div className="text-2xl font-bold">Nenhuma</div>
<p className="text-xs text-muted-foreground">Sem próximas consultas</p>
</>
)}
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Consultas Este Mês</CardTitle>
<Clock className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{monthlyCount}</div>
<p className="text-xs text-muted-foreground">{monthlyCount === 1 ? '1 agendada' : `${monthlyCount} agendadas`}</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Perfil</CardTitle>
<User className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">100%</div>
<p className="text-xs text-muted-foreground">Dados completos</p>
</CardContent>
</Card>
</div>
<div className="grid md:grid-cols-2 gap-6">
<Card>
<CardHeader>
<CardTitle>Ações Rápidas</CardTitle>
<CardDescription>Acesse rapidamente as principais funcionalidades</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<Link href="/doctor/consultas">
<Button className="w-full justify-start">
<Calendar className="mr-2 h-4 w-4" />
Ver Minhas Consultas
</Button>
</Link>
</CardContent>
</Card>
</div>
<div className="grid md:grid-cols-1 gap-6">
<Card>
<CardHeader>
<CardTitle>Horário Semanal</CardTitle>
<CardDescription>Confira rapidamente a sua disponibilidade da semana</CardDescription>
</CardHeader>
<CardContent>{loggedDoctor && <WeeklyScheduleCard doctorId={loggedDoctor.id} />}</CardContent>
</Card>
</div>
<div className="grid md:grid-cols-1 gap-6">
<Card>
<CardHeader>
<CardTitle>Exceções</CardTitle>
<CardDescription>Bloqueios e liberações eventuais de agenda</CardDescription>
</CardHeader>
<CardContent className="space-y-4 grid md:grid-cols-7 gap-2">
{exceptions && exceptions.length > 0 ? (
exceptions.map((ex: Exception) => {
const date = new Date(ex.date).toLocaleDateString("pt-BR", {
weekday: "long",
day: "2-digit",
month: "long",
timeZone: "UTC"
});
const startTime = formatTime(ex.start_time);
const endTime = formatTime(ex.end_time);
return (
<div key={ex.id} className="space-y-4">
<div className="flex flex-col items-center justify-between p-3 bg-primary/10 rounded-lg shadow-sm">
<div className="text-center">
<p className="font-semibold capitalize">{date}</p>
<p className="text-sm text-muted-foreground">
{startTime && endTime
? `${startTime} - ${endTime}`
: "Dia todo"}
</p>
</div>
<div className="text-center mt-2">
<p className={`text-sm font-medium ${ex.kind === "bloqueio" ? "text-destructive" : "text-primary"}`}>{ex.kind === "bloqueio" ? "Bloqueio" : "Liberação"}</p>
<p className="text-xs text-muted-foreground italic">{ex.reason || "Sem motivo especificado"}</p>
</div>
<div>
<Button className="text-destructive" variant="outline" onClick={() => openDeleteDialog(String(ex.id))}>
<Trash2></Trash2>
</Button>
</div>
</div>
</div>
);
})
) : (
<p className="text-sm text-muted-foreground italic col-span-7 text-center">Nenhuma exceção registrada.</p>
)}
</CardContent>
</Card>
</div>
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
<AlertDialogDescription>Tem certeza que deseja excluir esta exceção? Esta ação não pode ser desfeita.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancelar</AlertDialogCancel>
<AlertDialogAction onClick={() => exceptionToDelete && handleDeleteException(exceptionToDelete)} className="bg-destructive hover:bg-destructive/90">
Excluir
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</Sidebar>
);
}

View File

@ -1,258 +0,0 @@
"use client";
import type React from "react";
import Link from "next/link";
import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Calendar as CalendarIcon, RefreshCw } from "lucide-react";
import { useRouter } from "next/navigation";
import { toast } from "@/hooks/use-toast";
import { exceptionsService } from "@/services/exceptionApi.mjs";
// IMPORTAR O COMPONENTE CALENDÁRIO DA SHADCN
import { Calendar } from "@/components/ui/calendar";
import { format } from "date-fns"; // Usaremos o date-fns para formatação e comparação de datas
import { doctorsService } from "@/services/doctorsApi.mjs";
import Sidebar from "@/components/Sidebar";
type Doctor = {
id: string;
user_id: string | null;
crm: string;
crm_uf: string;
specialty: string;
full_name: string;
cpf: string;
email: string;
phone_mobile: string | null;
phone2: string | null;
cep: string | null;
street: string | null;
number: string | null;
complement: string | null;
neighborhood: string | null;
city: string | null;
state: string | null;
birth_date: string | null;
rg: string | null;
active: boolean;
created_at: string;
updated_at: string;
created_by: string;
updated_by: string | null;
max_days_in_advance: number;
rating: number | null;
}
// --- TIPAGEM DA CONSULTA SALVA NO LOCALSTORAGE ---
interface LocalStorageAppointment {
id: number;
patientName: string;
doctor: string;
specialty: string;
date: string; // Data no formato YYYY-MM-DD
time: string; // Hora no formato HH:MM
status: "agendada" | "confirmada" | "cancelada" | "realizada";
location: string;
phone: string;
}
// Função auxiliar para comparar se duas datas (Date objects) são o mesmo dia
const isSameDay = (date1: Date, date2: Date) => {
return date1.getFullYear() === date2.getFullYear() && date1.getMonth() === date2.getMonth() && date1.getDate() === date2.getDate();
};
// --- COMPONENTE PRINCIPAL ---
export default function ExceptionPage() {
const [allAppointments, setAllAppointments] = useState<LocalStorageAppointment[]>([]);
const router = useRouter();
const [filteredAppointments, setFilteredAppointments] = useState<LocalStorageAppointment[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [loggedDoctor, setLoggedDoctor] = useState<Doctor>();
const [tipo, setTipo] = useState<string>("");
useEffect(() => {
const fetchData = async () => {
try {
const doctorsList: Doctor[] = await doctorsService.list();
const doctor = doctorsList[0];
// Salva no estado
setLoggedDoctor(doctor);
} catch (e: any) {
alert(`${e?.error} ${e?.message}`);
}
};
fetchData();
}, []);
// NOVO ESTADO 1: Armazena os dias com consultas (para o calendário)
const [bookedDays, setBookedDays] = useState<Date[]>([]);
// NOVO ESTADO 2: Armazena a data selecionada no calendário
const [selectedCalendarDate, setSelectedCalendarDate] = useState<Date | undefined>(new Date());
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 = {
doctor_id: loggedDoctor?.id,
created_by: loggedDoctor?.user_id,
date: selectedCalendarDate ? format(selectedCalendarDate, "yyyy-MM-dd") : "",
start_time: ((formData.get("horarioEntrada")?formData.get("horarioEntrada") + ":00":null) as string) || null,
end_time: ((formData.get("horarioSaida")?formData.get("horarioSaida") + ":00":null) as string) || null,
kind: tipo || undefined,
reason: formData.get("reason"),
};
console.log(apiPayload);
try {
const res = await exceptionsService.create(apiPayload);
console.log(res);
let message = "Exceção cadastrada 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("/doctor/dashboard"); // adicionar página para listar a disponibilidade
} catch (err: any) {
toast({
title: "Erro",
description: err?.message || "Não foi possível cadastrar a exceção",
});
} finally {
setIsLoading(false);
}
};
const displayDate = selectedCalendarDate ? new Date(selectedCalendarDate).toLocaleDateString("pt-BR", { weekday: "long", day: "2-digit", month: "long" }) : "Selecione uma data";
return (
<Sidebar>
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold text-foreground">Adicione exceções</h1>
<p className="text-muted-foreground">Altere a disponibilidade em casos especiais para o Dr. João Silva</p>
</div>
<div className="flex justify-between items-center">
<h2 className="text-xl font-semibold text-foreground">Consultas para: {displayDate}</h2>
<Button disabled={isLoading} variant="outline" size="sm">
<RefreshCw className={`mr-2 h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
Atualizar Agenda
</Button>
</div>
{/* NOVO LAYOUT DE DUAS COLUNAS */}
<div className="grid lg:grid-cols-3 gap-6">
{/* COLUNA 1: CALENDÁRIO */}
<div className="lg:col-span-1">
<Card>
<CardHeader>
<CardTitle className="flex items-center">
<CalendarIcon className="mr-2 h-5 w-5" />
Calendário
</CardTitle>
<p className="text-sm text-muted-foreground">Selecione a data desejada.</p>
</CardHeader>
<CardContent className="flex justify-center p-2">
<Calendar
mode="single"
selected={selectedCalendarDate}
onSelect={setSelectedCalendarDate}
autoFocus
// A CHAVE DO HIGHLIGHT: Passa o array de datas agendadas
modifiers={{ booked: bookedDays }}
// Define o estilo CSS para o modificador 'booked'
modifiersClassNames={{
booked: "bg-blue-600 text-white aria-selected:!bg-blue-700 hover:!bg-blue-700/90",
}}
className="rounded-md border p-2"
/>
</CardContent>
</Card>
</div>
{/* COLUNA 2: FORM PARA ADICIONAR EXCEÇÃO */}
<div className="lg:col-span-2 space-y-4">
{isLoading ? (
<p className="text-center text-lg text-muted-foreground">Carregando a agenda...</p>
) : !selectedCalendarDate ? (
<p className="text-center text-lg text-muted-foreground">Selecione uma data.</p>
) : (
<form className="space-y-6" onSubmit={handleSubmit}>
<div className="bg-card rounded-lg border border-border p-6">
<h2 className="text-lg font-semibold text-foreground mb-6">Dados </h2>
<div className="space-y-6">
<div className="grid md:grid-cols-5 gap-6">
<div>
<Label htmlFor="horarioEntrada" className="text-sm font-medium text-foreground">
Horario De Entrada
</Label>
<Input type="time" id="horarioEntrada" name="horarioEntrada" className="mt-1" />
</div>
<div>
<Label htmlFor="horarioSaida" className="text-sm font-medium text-foreground">
Horario De Saida
</Label>
<Input type="time" id="horarioSaida" name="horarioSaida" className="mt-1" />
</div>
</div>
<div>
<Label htmlFor="tipo" className="text-sm font-medium text-foreground">
Tipo
</Label>
<Select onValueChange={(value) => setTipo(value)} value={tipo}>
<SelectTrigger className="mt-1">
<SelectValue placeholder="Selecione" />
</SelectTrigger>
<SelectContent>
<SelectItem value="bloqueio">Bloqueio </SelectItem>
<SelectItem value="disponibilidade_extra">Disponibilidade extra</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label htmlFor="reason" className="text-sm font-medium text-foreground">
Motivo
</Label>
<Input type="textarea" id="reason" name="reason" required className="mt-1" />
</div>
</div>
</div>
<div className="flex justify-end gap-4">
<Link href="/doctor/disponibilidade">
<Button variant="outline">Cancelar</Button>
</Link>
<Button type="submit" className="bg-green-600 hover:bg-green-700 text-white">
Salvar Exceção
</Button>
</div>
</form>
)}
</div>
</div>
</div>
</Sidebar>
);
}

View File

@ -1,638 +0,0 @@
"use client";
import { useState, useEffect } from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { AvailabilityService } from "@/services/availabilityApi.mjs";
import { usersService } from "@/services/usersApi.mjs";
import { doctorsService } from "@/services/doctorsApi.mjs";
import { toast } from "@/hooks/use-toast";
import { useRouter } from "next/navigation";
import {
Card,
CardHeader,
CardTitle,
CardDescription,
CardContent,
} from "@/components/ui/card";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Edit, Trash2 } from "lucide-react";
import { AvailabilityEditModal } from "@/components/ui/availability-edit-modal";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import Sidebar from "@/components/Sidebar";
// ... (Interfaces de tipo omitidas para brevidade, pois não foram alteradas)
interface UserPermissions {
isAdmin: boolean;
isManager: boolean;
isDoctor: boolean;
isSecretary: boolean;
isAdminOrManager: boolean;
}
interface UserData {
user: {
id: string;
email: string;
email_confirmed_at: string | null;
created_at: string | null;
last_sign_in_at: string | null;
};
profile: {
id: string;
full_name: string;
email: string;
phone: string;
avatar_url: string | null;
disabled: boolean;
created_at: string | null;
updated_at: string | null;
};
roles: string[];
permissions: UserPermissions;
}
type Doctor = {
id: string;
user_id: string | null;
crm: string;
crm_uf: string;
specialty: string;
full_name: string;
cpf: string;
email: string;
phone_mobile: string | null;
phone2: string | null;
cep: string | null;
street: string | null;
number: string | null;
complement: string | null;
neighborhood: string | null;
city: string | null;
state: string | null;
birth_date: string | null;
rg: string | null;
active: boolean;
created_at: string;
updated_at: string;
created_by: string;
updated_by: string | null;
max_days_in_advance: number;
rating: number | null;
};
type Availability = {
id: string;
doctor_id: string;
weekday: string;
start_time: string;
end_time: string;
slot_minutes: number;
appointment_type: string;
active: boolean;
created_at: string;
updated_at: string;
created_by: string;
updated_by: string | null;
};
export default function AvailabilityPage() {
const [error, setError] = useState<string | null>(null);
const router = useRouter();
const [isLoading, setIsLoading] = useState(false);
const [schedule, setSchedule] = useState<
Record<string, { start: string; end: string }[]>
>({});
const formatTime = (time?: string | null) =>
time?.split(":")?.slice(0, 2).join(":") ?? "";
const [userData, setUserData] = useState<UserData>();
const [availability, setAvailability] = useState<any | null>(null);
const [doctorId, setDoctorId] = useState<string>();
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [modalidadeConsulta, setModalidadeConsulta] = useState<string>("");
const [selectedAvailability, setSelectedAvailability] =
useState<Availability | null>(null);
const [isModalOpen, setIsModalOpen] = useState(false);
const selectAvailability = (
schedule: { start: string; end: string },
day: string
) => {
const selected = availability.filter(
(a: Availability) =>
a.start_time === schedule.start &&
a.end_time === schedule.end &&
a.weekday === day
);
setSelectedAvailability(selected[0]);
};
const handleOpenModal = (
schedule: { start: string; end: string },
day: string
) => {
selectAvailability(schedule, day);
setIsModalOpen(true);
};
const handleCloseModal = () => {
setSelectedAvailability(null);
setIsModalOpen(false);
};
const handleEdit = async (formData: {
start_time: "";
end_time: "";
slot_minutes: "";
appointment_type: "";
id: "";
}) => {
if (isLoading) return;
setIsLoading(true);
const apiPayload = {
start_time: formData.start_time,
end_time: formData.end_time,
slot_minutes: formData.slot_minutes,
appointment_type: formData.appointment_type,
};
console.log(apiPayload);
try {
const res = await AvailabilityService.update(formData.id, apiPayload);
console.log(res);
let message = "disponibilidade editada 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("#");
} catch (err: any) {
toast({
title: "Erro",
description:
err?.message || "Não foi possível editar a disponibilidade",
});
} finally {
setIsLoading(false);
handleCloseModal();
fetchData();
}
};
// Mapa de tradução
const weekdaysPT: Record<string, string> = {
sunday: "Domingo",
monday: "Segunda",
tuesday: "Terça",
wednesday: "Quarta",
thursday: "Quinta",
friday: "Sexta",
saturday: "Sábado",
};
const fetchData = async () => {
try {
const loggedUser = await usersService.getMe();
const doctorList = await doctorsService.list();
setUserData(loggedUser);
const doctor = findDoctorById(loggedUser.user.id, doctorList);
setDoctorId(doctor?.id);
console.log(doctor);
// Busca disponibilidade
const availabilityList = await AvailabilityService.list();
// Filtra já com a variável local
const filteredAvail = availabilityList.filter(
(disp: { doctor_id: string }) => disp.doctor_id === doctor?.id
);
setAvailability(filteredAvail);
} catch (e: any) {
alert(`${e?.error} ${e?.message}`);
}
};
useEffect(() => {
fetchData();
}, []);
// Função auxiliar para filtrar o id do doctor correspondente ao user logado
function findDoctorById(id: string, doctors: Doctor[]) {
return doctors.find((doctor) => doctor.user_id === id);
}
function formatAvailability(data: Availability[]) {
// Agrupar os horários por dia da semana
const schedule = data.reduce((acc: any, item) => {
const { weekday, start_time, end_time } = item;
// Se o dia ainda não existe, cria o array
if (!acc[weekday]) {
acc[weekday] = [];
}
// Adiciona o horário do dia
acc[weekday].push({
start: start_time,
end: end_time,
});
return acc;
}, {} as Record<string, { start: string; end: string }[]>);
return schedule;
}
useEffect(() => {
if (availability) {
const formatted = formatAvailability(availability);
setSchedule(formatted);
}
}, [availability]);
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 = {
doctor_id: doctorId,
weekday: (formData.get("weekday") as string) || undefined,
start_time: (formData.get("horarioEntrada") as string) || undefined,
end_time: (formData.get("horarioSaida") as string) || undefined,
slot_minutes: Number(formData.get("duracaoConsulta")) || undefined,
appointment_type: modalidadeConsulta || undefined,
active: true,
};
console.log(apiPayload);
try {
const res = await AvailabilityService.create(apiPayload);
console.log(res);
let message = "disponibilidade cadastrada 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("#"); // adicionar página para listar a disponibilidade
} catch (err: any) {
toast({
title: "Erro",
description: err?.message || "Não foi possível criar a disponibilidade",
});
} finally {
fetchData()
setIsLoading(false);
}
};
const openDeleteDialog = (
schedule: { start: string; end: string },
day: string
) => {
selectAvailability(schedule, day);
setDeleteDialogOpen(true);
};
const handleDeleteAvailability = async (AvailabilityId: string) => {
try {
const res = await AvailabilityService.delete(AvailabilityId);
let message = "Disponibilidade deletada com sucesso";
try {
if (res) {
throw new Error(`${res.error} ${res.message}` || "A API retornou erro");
} else {
console.log(message);
}
} catch {}
toast({
title: "Sucesso",
description: message,
});
setAvailability((prev: Availability[]) => prev.filter((p) => String(p.id) !== String(AvailabilityId)));
} catch (e: any) {
toast({
title: "Erro",
description: e?.message || "Não foi possível deletar a disponibilidade",
});
}
fetchData()
setDeleteDialogOpen(false);
setSelectedAvailability(null);
};
return (
<Sidebar>
<div className="space-y-6 flex-1 overflow-y-auto p-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold">
Definir Disponibilidade
</h1>
<p className="text-muted-foreground">
Defina sua disponibilidade para consultas{" "}
</p>
</div>
</div>
<form className="space-y-6" onSubmit={handleSubmit}>
<div className="bg-card rounded-lg border p-6">
<h2 className="text-lg font-semibold mb-6">Dados </h2>
<div className="space-y-6">
{/* **AJUSTE DE RESPONSIVIDADE: DIAS DA SEMANA** */}
<div>
<Label className="text-sm font-medium">
Dia Da Semana
</Label>
{/* O antigo 'flex gap-4 mt-2 flex-nowrap' foi substituído por um grid responsivo: */}
<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-primary"
/>
<span className="whitespace-nowrap text-sm">Segunda</span>
</label>
<label className="flex items-center gap-1">
<input
type="radio"
name="weekday"
value="tuesday"
className="text-primary"
/>
<span className="whitespace-nowrap text-sm">Terça</span>
</label>
<label className="flex items-center gap-1">
<input
type="radio"
name="weekday"
value="wednesday"
className="text-primary"
/>
<span className="whitespace-nowrap text-sm">Quarta</span>
</label>
<label className="flex items-center gap-1">
<input
type="radio"
name="weekday"
value="thursday"
className="text-primary"
/>
<span className="whitespace-nowrap text-sm">Quinta</span>
</label>
<label className="flex items-center gap-1">
<input
type="radio"
name="weekday"
value="friday"
className="text-primary"
/>
<span className="whitespace-nowrap text-sm">Sexta</span>
</label>
<label className="flex items-center gap-1">
<input
type="radio"
name="weekday"
value="saturday"
className="text-primary"
/>
<span className="whitespace-nowrap text-sm">Sábado</span>
</label>
<label className="flex items-center gap-1">
<input
type="radio"
name="weekday"
value="sunday"
className="text-primary"
/>
<span className="whitespace-nowrap text-sm">Domingo</span>
</label>
</div>
</div>
{/* **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>
<Label
htmlFor="horarioEntrada"
className="text-sm font-medium"
>
Horario De Entrada
</Label>
<Input
type="time"
id="horarioEntrada"
name="horarioEntrada"
required
className="mt-1"
/>
</div>
<div>
<Label
htmlFor="horarioSaida"
className="text-sm font-medium"
>
Horario De Saida
</Label>
<Input
type="time"
id="horarioSaida"
name="horarioSaida"
required
className="mt-1"
/>
</div>
<div>
<Label
htmlFor="duracaoConsulta"
className="text-sm font-medium whitespace-nowrap"
>
Duração da Consulta(min)
</Label>
<Input
type="number"
id="duracaoConsulta"
name="duracaoConsulta"
required
className="mt-1"
/>
</div>
{/* O Select de modalidade fica fora deste grid para ocupar uma linha inteira em telas menores, como no original, garantindo clareza */}
</div>
<div>
<Label
htmlFor="modalidadeConsulta"
className="text-sm font-medium"
>
Modalidade De Consulta
</Label>
<Select
onValueChange={(value) => setModalidadeConsulta(value)}
value={modalidadeConsulta}
>
<SelectTrigger className="mt-1">
<SelectValue placeholder="Selecione" />
</SelectTrigger>
<SelectContent>
<SelectItem value="presencial">Presencial </SelectItem>
<SelectItem value="telemedicina">Telemedicina</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</div>
{/* **AJUSTE DE RESPONSIVIDADE: BOTÕES DE AÇÃO** */}
{/* Alinha à direita em telas maiores e empilha (com o botão primário no final) em telas menores */}
{/* Alteração aqui: Adicionado w-full aos Links e Buttons para ocuparem a largura total em telas pequenas */}
<div className="flex flex-col-reverse sm:flex-row sm:justify-between gap-4">
<Link href="/doctor/disponibilidade/excecoes" className="w-full sm:w-auto">
<Button variant="default" className="w-full sm:w-auto">Adicionar Exceção</Button>
</Link>
<div className="flex flex-col sm:flex-row gap-4 w-full sm:w-auto"> {/* Ajustado para empilhar os botões Cancelar e Salvar em telas pequenas */}
<Link href="/doctor/dashboard" className="w-full sm:w-auto">
<Button variant="outline" className="w-full sm:w-auto">Cancelar</Button>
</Link>
<Button type="submit" className="bg-primary hover:bg-primary/90 w-full sm:w-auto">
Salvar Disponibilidade
</Button>
</div>
</div>
</form>
{/* **AJUSTE DE RESPONSIVIDADE: CARD DE HORÁRIO SEMANAL** */}
<div>
<Card>
<CardHeader>
<CardTitle>Horário Semanal</CardTitle>
<CardDescription>Confira ou altere a sua disponibilidade da semana</CardDescription>
</CardHeader>
{/* Define um grid responsivo para os dias da semana (1 coluna em móvel, 2 em pequeno, 3 em médio e 7 em telas grandes) */}
<CardContent className="space-y-4 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-7 gap-2">
{["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"].map((day) => {
const times = schedule[day] || [];
return (
<div key={day} className="space-y-4">
<div className="flex flex-col items-center justify-start p-3 bg-primary/10 rounded-lg min-h-[76px] ">
<p className="font-medium capitalize text-center ">{weekdaysPT[day]}</p>
<div className="text-center w-full mt-2">
{times.length > 0 ? (
times.map((t, i) => (
<div key={i}>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<p className="text-sm text-muted-foreground cursor-pointer rounded hover:text-accent-foreground hover:bg-muted transition-colors duration-150">
{formatTime(t.start)} - {formatTime(t.end)}
</p>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => handleOpenModal(t, day)}>
<Edit className="w-4 h-4 mr-2" />
Editar
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => openDeleteDialog(t, day)}
className="text-destructive focus:bg-destructive/10 focus:text-destructive">
<Trash2 className="w-4 h-4 mr-2" />
Excluir
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
))
) : (
<p className="text-sm text-muted-foreground italic">Sem horário</p>
)}
</div>
</div>
</div>
);
})}
</CardContent>
</Card>
</div>
{/* AlertDialog e Modal de Edição (não precisam de grandes ajustes de layout, apenas garantindo que os componentes sejam responsivos internamente) */}
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
<AlertDialogDescription>Tem certeza que deseja excluir esta disponibilidade? Esta ação não pode ser desfeita.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancelar</AlertDialogCancel>
<AlertDialogAction onClick={() => selectedAvailability && handleDeleteAvailability(selectedAvailability.id)} className="bg-destructive hover:bg-destructive/90">
Excluir
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
<AvailabilityEditModal
availability={selectedAvailability}
isOpen={isModalOpen}
onClose={handleCloseModal}
onSubmit={handleEdit}
/>
</Sidebar>
);
}

View File

@ -1,31 +0,0 @@
// Caminho: app/(doctor)/login/page.tsx
import { LoginForm } from "@/components/LoginForm";
import Link from "next/link"; // Adicionado para o link de "Voltar"
export default function DoctorLoginPage() {
// NOTA: Esta página se tornou obsoleta com a criação do /login central.
// O ideal no futuro é deletar esta página e redirecionar os usuários.
return (
<div className="min-h-screen bg-gradient-to-br from-green-50 via-white to-green-50 flex items-center justify-center p-4">
<div className="w-full max-w-md text-center">
<h1 className="text-3xl font-bold text-foreground mb-2">Área do Médico</h1>
<p className="text-muted-foreground mb-8">Acesse o sistema médico</p>
{/* --- ALTERAÇÃO PRINCIPAL AQUI --- */}
{/* Chamando o LoginForm unificado sem props desnecessárias */}
<LoginForm>
{/* Adicionamos um link de "Voltar" como filho (children) */}
<div className="mt-6 text-center text-sm">
<Link href="/">
<span className="font-semibold text-primary hover:underline cursor-pointer">
Voltar à página inicial
</span>
</Link>
</div>
</LoginForm>
</div>
</div>
);
}

View File

@ -1,517 +0,0 @@
"use client";
import type React from "react";
import { useState, useEffect } from "react";
import { useRouter, useParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { ArrowLeft, Save } from "lucide-react";
import Link from "next/link";
import Sidebar from "@/components/Sidebar";
// Mock data - in a real app, this would come from an API
const mockDoctors = [
{
id: 1,
nome: "Dr. Carlos Silva",
cpf: "123.456.789-00",
rg: "12.345.678-9",
sexo: "masculino",
dataNascimento: "1980-05-15",
etnia: "branca",
raca: "caucasiana",
naturalidade: "Aracaju",
nacionalidade: "brasileira",
profissao: "Médico",
estadoCivil: "casado",
nomeMae: "Ana Silva",
nomePai: "José Silva",
nomeEsposo: "Maria Silva",
crm: "CRM/SE 12345",
especialidade: "Cardiologia",
email: "carlos@email.com",
celular: "(79) 99999-1234",
telefone1: "(79) 3214-5678",
telefone2: "",
cep: "49000-000",
endereco: "Rua dos Médicos, 123",
numero: "123",
complemento: "Sala 101",
bairro: "Centro",
cidade: "Aracaju",
estado: "SE",
tipoSanguineo: "A+",
peso: "80",
altura: "1.80",
alergias: "Nenhuma alergia conhecida",
convenio: "Particular",
plano: "Premium",
numeroMatricula: "123456789",
validadeCarteira: "2025-12-31",
observacoes: "Médico experiente",
},
];
export default function EditarMedicoPage() {
const router = useRouter();
const params = useParams();
const doctorId = Number.parseInt(params.id as string);
const [formData, setFormData] = useState({
nome: "",
cpf: "",
rg: "",
sexo: "",
dataNascimento: "",
etnia: "",
raca: "",
naturalidade: "",
nacionalidade: "",
profissao: "",
estadoCivil: "",
nomeMae: "",
nomePai: "",
nomeEsposo: "",
crm: "",
especialidade: "",
email: "",
celular: "",
telefone1: "",
telefone2: "",
cep: "",
endereco: "",
numero: "",
complemento: "",
bairro: "",
cidade: "",
estado: "",
tipoSanguineo: "",
peso: "",
altura: "",
alergias: "",
convenio: "",
plano: "",
numeroMatricula: "",
validadeCarteira: "",
observacoes: "",
});
const [isGuiaConvenio, setIsGuiaConvenio] = useState(false);
const [validadeIndeterminada, setValidadeIndeterminada] = useState(false);
useEffect(() => {
// Load doctor data
const doctor = mockDoctors.find((d) => d.id === doctorId);
if (doctor) {
setFormData(doctor);
}
}, [doctorId]);
const handleInputChange = (field: string, value: string) => {
setFormData((prev) => ({ ...prev, [field]: value }));
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
console.log("[v0] Updating doctor:", formData);
// Here you would typically send the data to your API
router.push("/medicos");
};
return (
<Sidebar>
<div className="space-y-6">
<div className="flex items-center gap-4">
<Link href="/medicos">
<Button variant="ghost" size="sm">
<ArrowLeft className="w-4 h-4 mr-2" />
Voltar
</Button>
</Link>
<div>
<h1 className="text-2xl font-bold text-gray-900">Editar Médico</h1>
<p className="text-gray-600">Atualize as informações do médico</p>
</div>
</div>
<form onSubmit={handleSubmit} className="space-y-8">
<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="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<div className="space-y-2">
<Label htmlFor="nome">Nome *</Label>
<Input id="nome" value={formData.nome} onChange={(e) => handleInputChange("nome", e.target.value)} required />
</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" 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 className="space-y-2">
<Label>Sexo *</Label>
<div className="flex gap-4">
<div className="flex items-center space-x-2">
<input type="radio" id="masculino" name="sexo" value="masculino" checked={formData.sexo === "masculino"} onChange={(e) => handleInputChange("sexo", e.target.value)} className="w-4 h-4 text-blue-600" />
<Label htmlFor="masculino">Masculino</Label>
</div>
<div className="flex items-center space-x-2">
<input type="radio" id="feminino" name="sexo" value="feminino" checked={formData.sexo === "feminino"} onChange={(e) => handleInputChange("sexo", e.target.value)} className="w-4 h-4 text-blue-600" />
<Label htmlFor="feminino">Feminino</Label>
</div>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="dataNascimento">Data de nascimento *</Label>
<Input id="dataNascimento" type="date" value={formData.dataNascimento} onChange={(e) => handleInputChange("dataNascimento", e.target.value)} required />
</div>
<div className="space-y-2">
<Label htmlFor="etnia">Etnia</Label>
<Select value={formData.etnia} onValueChange={(value) => handleInputChange("etnia", value)}>
<SelectTrigger>
<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 className="space-y-2">
<Label htmlFor="raca">Raça</Label>
<Select value={formData.raca} onValueChange={(value) => handleInputChange("raca", value)}>
<SelectTrigger>
<SelectValue placeholder="Selecione" />
</SelectTrigger>
<SelectContent>
<SelectItem value="caucasiana">Caucasiana</SelectItem>
<SelectItem value="negroide">Negroide</SelectItem>
<SelectItem value="mongoloide">Mongoloide</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="naturalidade">Naturalidade</Label>
<Input id="naturalidade" value={formData.naturalidade} onChange={(e) => handleInputChange("naturalidade", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="nacionalidade">Nacionalidade</Label>
<Select value={formData.nacionalidade} onValueChange={(value) => handleInputChange("nacionalidade", value)}>
<SelectTrigger>
<SelectValue placeholder="Selecione" />
</SelectTrigger>
<SelectContent>
<SelectItem value="brasileira">Brasileira</SelectItem>
<SelectItem value="estrangeira">Estrangeira</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="profissao">Profissão</Label>
<Input id="profissao" value={formData.profissao} onChange={(e) => handleInputChange("profissao", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="estadoCivil">Estado civil</Label>
<Select value={formData.estadoCivil} onValueChange={(value) => handleInputChange("estadoCivil", value)}>
<SelectTrigger>
<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 className="space-y-2">
<Label htmlFor="nomeMae">Nome da mãe</Label>
<Input id="nomeMae" value={formData.nomeMae} onChange={(e) => handleInputChange("nomeMae", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="nomePai">Nome do pai</Label>
<Input id="nomePai" value={formData.nomePai} onChange={(e) => handleInputChange("nomePai", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="nomeEsposo">Nome do esposo(a)</Label>
<Input id="nomeEsposo" value={formData.nomeEsposo} onChange={(e) => handleInputChange("nomeEsposo", e.target.value)} />
</div>
</div>
<div className="mt-6">
<div className="flex items-center space-x-2">
<Checkbox id="guiaConvenio" checked={isGuiaConvenio} onCheckedChange={(checked) => setIsGuiaConvenio(checked === true)} />
<Label htmlFor="guiaConvenio">RN na Guia do convênio</Label>
</div>
</div>
<div className="mt-6">
<Label htmlFor="observacoes">Observações</Label>
<Textarea id="observacoes" value={formData.observacoes} onChange={(e) => handleInputChange("observacoes", e.target.value)} placeholder="Digite observações sobre o médico..." className="mt-2" />
</div>
</div>
{/* Professional Information Section */}
<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 Profissionais</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="space-y-2">
<Label htmlFor="crm">CRM *</Label>
<Input id="crm" value={formData.crm} onChange={(e) => handleInputChange("crm", e.target.value)} placeholder="CRM/UF 12345" required />
</div>
<div className="space-y-2">
<Label htmlFor="especialidade">Especialidade *</Label>
<Select value={formData.especialidade} onValueChange={(value) => handleInputChange("especialidade", value)}>
<SelectTrigger>
<SelectValue placeholder="Selecione a especialidade" />
</SelectTrigger>
<SelectContent>
<SelectItem value="Cardiologia">Cardiologia</SelectItem>
<SelectItem value="Pediatria">Pediatria</SelectItem>
<SelectItem value="Ortopedia">Ortopedia</SelectItem>
<SelectItem value="Neurologia">Neurologia</SelectItem>
<SelectItem value="Ginecologia">Ginecologia</SelectItem>
<SelectItem value="Dermatologia">Dermatologia</SelectItem>
<SelectItem value="Psiquiatria">Psiquiatria</SelectItem>
<SelectItem value="Oftalmologia">Oftalmologia</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</div>
{/* Contact Section */}
<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="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<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)} />
</div>
<div className="space-y-2">
<Label htmlFor="celular">Celular</Label>
<Input id="celular" value={formData.celular} onChange={(e) => handleInputChange("celular", e.target.value)} placeholder="(00) 00000-0000" />
</div>
<div className="space-y-2">
<Label htmlFor="telefone1">Telefone 1</Label>
<Input id="telefone1" value={formData.telefone1} onChange={(e) => handleInputChange("telefone1", e.target.value)} placeholder="(00) 0000-0000" />
</div>
<div className="space-y-2">
<Label htmlFor="telefone2">Telefone 2</Label>
<Input id="telefone2" value={formData.telefone2} onChange={(e) => handleInputChange("telefone2", e.target.value)} placeholder="(00) 0000-0000" />
</div>
</div>
</div>
{/* Address Section */}
<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="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<div className="space-y-2">
<Label htmlFor="cep">CEP</Label>
<Input id="cep" value={formData.cep} onChange={(e) => handleInputChange("cep", e.target.value)} placeholder="00000-000" />
</div>
<div className="space-y-2">
<Label htmlFor="endereco">Endereço</Label>
<Input id="endereco" value={formData.endereco} onChange={(e) => handleInputChange("endereco", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="numero">Número</Label>
<Input id="numero" value={formData.numero} onChange={(e) => handleInputChange("numero", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="complemento">Complemento</Label>
<Input id="complemento" value={formData.complemento} onChange={(e) => handleInputChange("complemento", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="bairro">Bairro</Label>
<Input id="bairro" value={formData.bairro} onChange={(e) => handleInputChange("bairro", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="cidade">Cidade</Label>
<Input id="cidade" value={formData.cidade} onChange={(e) => handleInputChange("cidade", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="estado">Estado</Label>
<Select value={formData.estado} onValueChange={(value) => handleInputChange("estado", value)}>
<SelectTrigger>
<SelectValue placeholder="Selecione" />
</SelectTrigger>
<SelectContent>
<SelectItem value="AC">Acre</SelectItem>
<SelectItem value="AL">Alagoas</SelectItem>
<SelectItem value="AP">Amapá</SelectItem>
<SelectItem value="AM">Amazonas</SelectItem>
<SelectItem value="BA">Bahia</SelectItem>
<SelectItem value="CE">Ceará</SelectItem>
<SelectItem value="DF">Distrito Federal</SelectItem>
<SelectItem value="ES">Espírito Santo</SelectItem>
<SelectItem value="GO">Goiás</SelectItem>
<SelectItem value="MA">Maranhão</SelectItem>
<SelectItem value="MT">Mato Grosso</SelectItem>
<SelectItem value="MS">Mato Grosso do Sul</SelectItem>
<SelectItem value="MG">Minas Gerais</SelectItem>
<SelectItem value="PA">Pará</SelectItem>
<SelectItem value="PB">Paraíba</SelectItem>
<SelectItem value="PR">Paraná</SelectItem>
<SelectItem value="PE">Pernambuco</SelectItem>
<SelectItem value="PI">Piauí</SelectItem>
<SelectItem value="RJ">Rio de Janeiro</SelectItem>
<SelectItem value="RN">Rio Grande do Norte</SelectItem>
<SelectItem value="RS">Rio Grande do Sul</SelectItem>
<SelectItem value="RO">Rondônia</SelectItem>
<SelectItem value="RR">Roraima</SelectItem>
<SelectItem value="SC">Santa Catarina</SelectItem>
<SelectItem value="SP">São Paulo</SelectItem>
<SelectItem value="SE">Sergipe</SelectItem>
<SelectItem value="TO">Tocantins</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</div>
{/* Medical Information Section */}
<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="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<div className="space-y-2">
<Label htmlFor="tipoSanguineo">Tipo Sanguíneo</Label>
<Select value={formData.tipoSanguineo} onValueChange={(value) => handleInputChange("tipoSanguineo", value)}>
<SelectTrigger>
<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 className="space-y-2">
<Label htmlFor="peso">Peso (kg)</Label>
<Input id="peso" type="number" value={formData.peso} onChange={(e) => handleInputChange("peso", e.target.value)} placeholder="0.0" />
</div>
<div className="space-y-2">
<Label htmlFor="altura">Altura (m)</Label>
<Input id="altura" type="number" step="0.01" value={formData.altura} onChange={(e) => handleInputChange("altura", e.target.value)} placeholder="0.00" />
</div>
<div className="space-y-2">
<Label>IMC</Label>
<Input value={formData.peso && formData.altura ? (Number.parseFloat(formData.peso) / Number.parseFloat(formData.altura) ** 2).toFixed(2) : ""} disabled placeholder="Calculado automaticamente" />
</div>
</div>
<div className="mt-6">
<Label htmlFor="alergias">Alergias</Label>
<Textarea id="alergias" value={formData.alergias} onChange={(e) => handleInputChange("alergias", e.target.value)} placeholder="Ex: AAS, Dipirona, etc." className="mt-2" />
</div>
</div>
{/* Insurance Information Section */}
<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="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<div className="space-y-2">
<Label htmlFor="convenio">Convênio</Label>
<Select value={formData.convenio} onValueChange={(value) => handleInputChange("convenio", value)}>
<SelectTrigger>
<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>
<SelectItem value="Amil">Amil</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="plano">Plano</Label>
<Input id="plano" value={formData.plano} onChange={(e) => handleInputChange("plano", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="numeroMatricula"> de matrícula</Label>
<Input id="numeroMatricula" value={formData.numeroMatricula} onChange={(e) => handleInputChange("numeroMatricula", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="validadeCarteira">Validade da Carteira</Label>
<Input id="validadeCarteira" type="date" value={formData.validadeCarteira} onChange={(e) => handleInputChange("validadeCarteira", e.target.value)} disabled={validadeIndeterminada} />
</div>
</div>
<div className="mt-4">
<div className="flex items-center space-x-2">
<Checkbox id="validadeIndeterminada" checked={validadeIndeterminada} onCheckedChange={(checked) => setValidadeIndeterminada(checked === true)} />
<Label htmlFor="validadeIndeterminada">Validade Indeterminada</Label>
</div>
</div>
</div>
<div className="flex justify-end gap-4">
<Link href="/medicos">
<Button type="button" variant="outline">
Cancelar
</Button>
</Link>
<Button type="submit" className="bg-green-600 hover:bg-green-700">
<Save className="w-4 h-4 mr-2" />
Salvar Alterações
</Button>
</div>
</form>
</div>
</Sidebar>
);
}

View File

@ -1,233 +0,0 @@
"use client";
import { useParams, useRouter } from "next/navigation";
import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog";
import { Calendar } from "@/components/ui/calendar";
import { CalendarIcon } from "lucide-react";
import { format } from "date-fns";
import TiptapEditor from "@/components/ui/tiptap-editor";
import { Skeleton } from "@/components/ui/skeleton";
import { reportsApi } from "@/services/reportsApi.mjs";
import Sidebar from "@/components/Sidebar";
export default function EditarLaudoPage() {
const router = useRouter();
const params = useParams();
const patientId = params.id as string;
const laudoId = params.laudoId as string;
const [formData, setFormData] = useState<any>({});
const [loading, setLoading] = useState(true);
const [isSubmitting, setIsSubmitting] = useState(false);
const [isDatePickerOpen, setIsDatePickerOpen] = useState(false);
useEffect(() => {
if (laudoId) {
setLoading(true);
reportsApi.getReportById(laudoId)
.then((data: any) => {
console.log("Fetched report data:", data);
// The API now returns an array, get the first element
const reportData = Array.isArray(data) && data.length > 0 ? data[0] : null;
if (reportData) {
setFormData({
...reportData,
due_at: reportData.due_at ? new Date(reportData.due_at) : null,
});
}
})
.catch(error => {
console.error("Failed to fetch report details:", error);
// Here you could add a toast notification to inform the user
})
.finally(() => {
setLoading(false);
});
} else {
// If there's no laudoId, we shouldn't be in a loading state.
setLoading(false);
}
}, [laudoId]);
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const { id, value } = e.target;
setFormData((prev: any) => ({ ...prev, [id]: value }));
};
const handleSelectChange = (id: string, value: string) => {
setFormData((prev: any) => ({ ...prev, [id]: value }));
};
const handleCheckboxChange = (id: string, checked: boolean) => {
setFormData((prev: any) => ({ ...prev, [id]: checked }));
};
const handleDateChange = (date: Date | undefined) => {
console.log("Date selected:", date);
if (date) {
setFormData((prev: any) => ({ ...prev, due_at: date }));
}
};
const handleDateSelect = (date: Date | undefined) => {
handleDateChange(date);
setIsDatePickerOpen(false); // Close the dialog after selection
};
const handleEditorChange = (html: string, json: object) => {
setFormData((prev: any) => ({
...prev,
content_html: html,
content_json: json
}));
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsSubmitting(true);
try {
const { id, patient_id, created_at, updated_at, created_by, updated_by, ...updateData } = formData;
await reportsApi.updateReport(laudoId, updateData);
// toast({ title: "Laudo atualizado com sucesso!" });
router.push(`/doctor/medicos/${patientId}/laudos`);
} catch (error) {
console.error("Failed to update laudo", error);
// toast({ title: "Erro ao atualizar laudo", variant: "destructive" });
} finally {
setIsSubmitting(false);
}
};
if (loading) {
return (
<Sidebar>
<div className="container mx-auto p-4">
<Card>
<CardHeader>
<Skeleton className="h-8 w-1/4" />
</CardHeader>
<CardContent className="space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="space-y-2"><Skeleton className="h-4 w-1/6" /><Skeleton className="h-10 w-full" /></div>
<div className="space-y-2"><Skeleton className="h-4 w-1/6" /><Skeleton className="h-10 w-full" /></div>
<div className="space-y-2"><Skeleton className="h-4 w-1/6" /><Skeleton className="h-10 w-full" /></div>
<div className="space-y-2"><Skeleton className="h-4 w-1/6" /><Skeleton className="h-10 w-full" /></div>
</div>
<div className="space-y-2"><Skeleton className="h-4 w-1/6" /><Skeleton className="h-24 w-full" /></div>
<div className="space-y-2"><Skeleton className="h-4 w-1/6" /><Skeleton className="h-40 w-full" /></div>
<div className="flex justify-end space-x-2">
<Skeleton className="h-10 w-24" />
<Skeleton className="h-10 w-24" />
</div>
</CardContent>
</Card>
</div>
</Sidebar>
)
}
return (
<Sidebar>
<div className="container mx-auto p-4">
<Card>
<CardHeader>
<CardTitle>Editar Laudo - {formData.order_number}</CardTitle>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="space-y-2">
<Label htmlFor="exam">Exame</Label>
<Input id="exam" value={formData.exam || ''} onChange={handleInputChange} />
</div>
<div className="space-y-2">
<Label htmlFor="diagnosis">Diagnóstico</Label>
<Input id="diagnosis" value={formData.diagnosis || ''} onChange={handleInputChange} />
</div>
<div className="space-y-2">
<Label htmlFor="cid_code">Código CID</Label>
<Input id="cid_code" value={formData.cid_code || ''} onChange={handleInputChange} />
</div>
<div className="space-y-2">
<Label htmlFor="requested_by">Solicitado Por</Label>
<Input id="requested_by" value={formData.requested_by || ''} onChange={handleInputChange} />
</div>
<div className="space-y-2">
<Label htmlFor="status">Status</Label>
<Select onValueChange={(value) => handleSelectChange("status", value)} value={formData.status}>
<SelectTrigger>
<SelectValue placeholder="Selecione o status" />
</SelectTrigger>
<SelectContent>
<SelectItem value="draft">Rascunho</SelectItem>
<SelectItem value="final">Finalizado</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="due_at">Data de Vencimento</Label>
<Dialog open={isDatePickerOpen} onOpenChange={setIsDatePickerOpen}>
<DialogTrigger asChild>
<Button variant={"outline"} className="w-full justify-start text-left font-normal">
<CalendarIcon className="mr-2 h-4 w-4" />
{formData.due_at ? format(new Date(formData.due_at), "PPP") : <span>Escolha uma data</span>}
</Button>
</DialogTrigger>
<DialogContent className="w-auto p-0">
<Calendar
mode="single"
selected={formData.due_at ? new Date(formData.due_at) : undefined}
onSelect={handleDateSelect}
initialFocus
/>
</DialogContent>
</Dialog>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="conclusion">Conclusão</Label>
<Textarea id="conclusion" value={formData.conclusion || ''} onChange={handleInputChange} />
</div>
<div className="space-y-2">
<Label>Conteúdo do Laudo</Label>
<div className="rounded-md border border-input">
<TiptapEditor content={formData.content_html || ''} onChange={handleEditorChange} />
</div>
</div>
<div className="flex items-center space-x-4">
<div className="flex items-center space-x-2">
<Checkbox id="hide_date" checked={formData.hide_date} onCheckedChange={(checked) => handleCheckboxChange("hide_date", !!checked)} />
<Label htmlFor="hide_date">Ocultar Data</Label>
</div>
<div className="flex items-center space-x-2">
<Checkbox id="hide_signature" checked={formData.hide_signature} onCheckedChange={(checked) => handleCheckboxChange("hide_signature", !!checked)} />
<Label htmlFor="hide_signature">Ocultar Assinatura</Label>
</div>
</div>
<div className="flex justify-end space-x-2">
<Button type="button" variant="outline" onClick={() => router.back()} disabled={isSubmitting}>
Cancelar
</Button>
<Button type="submit" disabled={isSubmitting}>
{isSubmitting ? "Salvando..." : "Salvar Alterações"}
</Button>
</div>
</form>
</CardContent>
</Card>
</div>
</Sidebar>
);
}

View File

@ -1,189 +0,0 @@
"use client";
import { useParams, useRouter } from "next/navigation";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Calendar } from "@/components/ui/calendar";
import { CalendarIcon } from "lucide-react";
import { format } from "date-fns";
import TiptapEditor from "@/components/ui/tiptap-editor";
import { reportsApi } from "@/services/reportsApi.mjs";
import Sidebar from "@/components/Sidebar";
export default function NovoLaudoPage() {
const router = useRouter();
const params = useParams();
const patientId = params.id as string;
const [formData, setFormData] = useState({
order_number: "",
exam: "",
diagnosis: "",
conclusion: "",
cid_code: "",
content_html: "",
content_json: {}, // Added for the JSON content from the editor
status: "draft",
requested_by: "",
due_at: new Date(),
hide_date: false,
hide_signature: false,
});
const [isSubmitting, setIsSubmitting] = useState(false);
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const { id, value } = e.target;
setFormData(prev => ({ ...prev, [id]: value }));
};
const handleSelectChange = (id: string, value: string) => {
setFormData(prev => ({ ...prev, [id]: value }));
};
const handleCheckboxChange = (id: string, checked: boolean) => {
setFormData(prev => ({ ...prev, [id]: checked }));
};
const handleDateChange = (date: Date | undefined) => {
if (date) {
setFormData(prev => ({ ...prev, due_at: date }));
}
};
// Updated to handle both HTML and JSON from the editor
const handleEditorChange = (html: string, json: object) => {
setFormData(prev => ({
...prev,
content_html: html,
content_json: json
}));
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsSubmitting(true);
try {
const laudoData = {
...formData,
patient_id: patientId,
due_at: formData.due_at.toISOString(), // Ensure date is in ISO format for the API
};
await reportsApi.createReport(laudoData);
// You can use a toast notification here for better user feedback
// toast({ title: "Laudo criado com sucesso!" });
router.push(`/doctor/medicos/${patientId}/laudos`);
} catch (error: any) {
console.error("Failed to create laudo", error);
// You can use a toast notification for errors
// toast({ title: "Erro ao criar laudo", description: error.message, variant: "destructive" });
} finally {
setIsSubmitting(false);
}
};
return (
<Sidebar>
<div className="container mx-auto p-4">
<Card>
<CardHeader>
<CardTitle>Criar Novo Laudo</CardTitle>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="space-y-2">
<Label htmlFor="exam">Exame</Label>
<Input id="exam" value={formData.exam} onChange={handleInputChange} />
</div>
<div className="space-y-2">
<Label htmlFor="diagnosis">Diagnóstico</Label>
<Input id="diagnosis" value={formData.diagnosis} onChange={handleInputChange} />
</div>
<div className="space-y-2">
<Label htmlFor="cid_code">Código CID</Label>
<Input id="cid_code" value={formData.cid_code} onChange={handleInputChange} />
</div>
<div className="space-y-2">
<Label htmlFor="requested_by">Solicitado Por</Label>
<Input id="requested_by" value={formData.requested_by} onChange={handleInputChange} />
</div>
<div className="space-y-2">
<Label htmlFor="status">Status</Label>
<Select onValueChange={(value) => handleSelectChange("status", value)} defaultValue={formData.status}>
<SelectTrigger>
<SelectValue placeholder="Selecione o status" />
</SelectTrigger>
<SelectContent>
<SelectItem value="draft">Rascunho</SelectItem>
<SelectItem value="final">Finalizado</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="due_at">Data de Vencimento</Label>
<Popover>
<PopoverTrigger asChild>
<Button variant={"outline"} className="w-full justify-start text-left font-normal">
<CalendarIcon className="mr-2 h-4 w-4" />
{formData.due_at ? format(formData.due_at, "PPP") : <span>Escolha uma data</span>}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0">
<Calendar mode="single" selected={formData.due_at} onSelect={handleDateChange} initialFocus />
</PopoverContent>
</Popover>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="conclusion">Conclusão</Label>
<Textarea id="conclusion" value={formData.conclusion} onChange={handleInputChange} />
</div>
<div className="space-y-2">
<Label>Conteúdo do Laudo</Label>
<div className="rounded-md border border-input">
<TiptapEditor content={formData.content_html} onChange={handleEditorChange} />
</div>
</div>
<div className="flex items-center space-x-4">
<div className="flex items-center space-x-2">
<Checkbox id="hide_date" checked={formData.hide_date} onCheckedChange={(checked) => handleCheckboxChange("hide_date", !!checked)} />
<Label htmlFor="hide_date">Ocultar Data</Label>
</div>
<div className="flex items-center space-x-2">
<Checkbox id="hide_signature" checked={formData.hide_signature} onCheckedChange={(checked) => handleCheckboxChange("hide_signature", !!checked)} />
<Label htmlFor="hide_signature">Ocultar Assinatura</Label>
</div>
</div>
<div className="flex justify-end space-x-2">
<Button type="button" variant="outline" onClick={() => router.back()} disabled={isSubmitting}>
Cancelar
</Button>
<Button type="submit" disabled={isSubmitting}>
{isSubmitting ? "Salvando..." : "Salvar Laudo"}
</Button>
</div>
</form>
</CardContent>
</Card>
</div>
</Sidebar>
);
}

View File

@ -1,128 +0,0 @@
'use client';
import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { api } from '@/services/api.mjs';
import { reportsApi } from '@/services/reportsApi.mjs';
import Sidebar from '@/components/Sidebar';
export default function LaudosPage() {
const [patient, setPatient] = useState(null);
const [laudos, setLaudos] = useState([]);
const [loading, setLoading] = useState(true);
const params = useParams();
const patientId = params.id as string;
const [currentPage, setCurrentPage] = useState(1);
const [itemsPerPage] = useState(5);
useEffect(() => {
if (patientId) {
const fetchPatientAndLaudos = async () => {
setLoading(true);
try {
const patientData = await api.get(`/rest/v1/patients?id=eq.${patientId}&select=*`).then(r => r?.[0]);
setPatient(patientData);
const laudosData = await reportsApi.getReports(patientId);
setLaudos(laudosData);
} catch (error) {
console.error("Failed to fetch data:", error);
} finally {
setLoading(false);
}
};
fetchPatientAndLaudos();
}
}, [patientId]);
const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = laudos.slice(indexOfFirstItem, indexOfLastItem);
const totalPages = Math.ceil(laudos.length / itemsPerPage);
const paginate = (pageNumber) => setCurrentPage(pageNumber);
return (
<Sidebar>
<div className="container mx-auto p-4">
{loading ? (
<p>Carregando...</p>
) : (
<>
{patient && (
<Card className="mb-4">
<CardHeader>
<CardTitle>Informações do Paciente</CardTitle>
</CardHeader>
<CardContent>
<p><strong>Nome:</strong> {patient.full_name}</p>
<p><strong>Email:</strong> {patient.email}</p>
<p><strong>Telefone:</strong> {patient.phone_mobile}</p>
</CardContent>
</Card>
)}
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle>Laudos do Paciente</CardTitle>
<Link href={`/doctor/medicos/${patientId}/laudos/novo`}>
<Button>Criar Novo Laudo</Button>
</Link>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead> do Pedido</TableHead>
<TableHead>Exame</TableHead>
<TableHead>Diagnóstico</TableHead>
<TableHead>Status</TableHead>
<TableHead>Data de Criação</TableHead>
<TableHead>Ações</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{currentItems.length > 0 ? (
currentItems.map((laudo) => (
<TableRow key={laudo.id}>
<TableCell>{laudo.order_number}</TableCell>
<TableCell>{laudo.exam}</TableCell>
<TableCell>{laudo.diagnosis}</TableCell>
<TableCell>{laudo.status}</TableCell>
<TableCell>{new Date(laudo.created_at).toLocaleDateString()}</TableCell>
<TableCell>
<Link href={`/doctor/medicos/${patientId}/laudos/${laudo.id}/editar`}>
<Button variant="outline" size="sm">Editar</Button>
</Link>
</TableCell>
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={6} className="text-center">Nenhum laudo encontrado.</TableCell>
</TableRow>
)}
</TableBody>
</Table>
{totalPages > 1 && (
<div className="flex justify-center space-x-2 mt-4 p-4">
{Array.from({ length: totalPages }, (_, i) => (
<Button key={i} onClick={() => paginate(i + 1)} variant={currentPage === i + 1 ? 'default' : 'outline'}>
{i + 1}
</Button>
))}
</div>
)}
</CardContent>
</Card>
</>
)}
</div>
</Sidebar>
);
}

View File

@ -1,3 +0,0 @@
export default function Loading() {
return null
}

View File

@ -1,471 +0,0 @@
"use client";
import { useState } from "react";
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 { Upload, Plus, X, ChevronDown } from "lucide-react";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import Sidebar from "@/components/Sidebar";
export default function NovoMedicoPage() {
const [anexosOpen, setAnexosOpen] = useState(false);
const [anexos, setAnexos] = useState<string[]>([]);
const adicionarAnexo = () => {
setAnexos([...anexos, `Documento ${anexos.length + 1}`]);
};
const removerAnexo = (index: number) => {
setAnexos(anexos.filter((_, i) => i !== index));
};
return (
<Sidebar>
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-gray-900">Novo Médico</h1>
<p className="text-gray-600">Cadastre um novo médico no sistema</p>
</div>
</div>
<form className="space-y-6">
<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">
{/* Foto */}
<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" 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" 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" 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" placeholder="00.000.000-0" className="mt-1" />
</div>
<div>
<Label htmlFor="crm" className="text-sm font-medium text-gray-700">
CRM *
</Label>
<Input id="crm" placeholder="CRM/UF 12345" required className="mt-1" />
</div>
</div>
<div>
<Label htmlFor="outrosDocumentos" className="text-sm font-medium text-gray-700">
Outros Documentos
</Label>
<Select>
<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 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" />
<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" />
<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" type="date" className="mt-1" />
</div>
<div>
<Label htmlFor="estadoCivil" className="text-sm font-medium text-gray-700">
Estado Civil
</Label>
<Select>
<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>
<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>
<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>
<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>
<SelectTrigger className="mt-1">
<SelectValue placeholder="Selecione" />
</SelectTrigger>
<SelectContent>
<SelectItem value="brasileira">Brasileira</SelectItem>
<SelectItem value="estrangeira">Estrangeira</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="grid md:grid-cols-2 gap-4">
<div>
<Label htmlFor="profissao" className="text-sm font-medium text-gray-700">
Profissão
</Label>
<Input id="profissao" placeholder="Médico" className="mt-1" />
</div>
<div>
<Label htmlFor="especialidade" className="text-sm font-medium text-gray-700">
Especialidade *
</Label>
<Select>
<SelectTrigger className="mt-1">
<SelectValue placeholder="Selecione" />
</SelectTrigger>
<SelectContent>
<SelectItem value="cardiologia">Cardiologia</SelectItem>
<SelectItem value="pediatria">Pediatria</SelectItem>
<SelectItem value="ortopedia">Ortopedia</SelectItem>
<SelectItem value="ginecologia">Ginecologia</SelectItem>
<SelectItem value="neurologia">Neurologia</SelectItem>
<SelectItem value="dermatologia">Dermatologia</SelectItem>
</SelectContent>
</Select>
</div>
</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" placeholder="Nome da mãe" className="mt-1" />
</div>
<div>
<Label htmlFor="nomePai" className="text-sm font-medium text-gray-700">
Nome do Pai
</Label>
<Input id="nomePai" placeholder="Nome do pai" 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" placeholder="Nome do esposo(a)" className="mt-1" />
</div>
<div>
<Label htmlFor="codigoLegado" className="text-sm font-medium text-gray-700">
Código Legado
</Label>
<Input id="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" placeholder="Observações gerais sobre o médico" 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 médico</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" type="email" placeholder="email@exemplo.com" className="mt-1" />
</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 placeholder="(XX) XXXXX-XXXX" className="rounded-l-none" />
</div>
</div>
<div>
<Label htmlFor="telefone1" className="text-sm font-medium text-gray-700">
Telefone 1
</Label>
<Input id="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" 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" 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" 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" placeholder="123" className="mt-1" />
</div>
</div>
<div>
<Label htmlFor="complemento" className="text-sm font-medium text-gray-700">
Complemento
</Label>
<Input id="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" placeholder="Bairro" className="mt-1" />
</div>
<div>
<Label htmlFor="cidade" className="text-sm font-medium text-gray-700">
Cidade
</Label>
<Input id="cidade" placeholder="Cidade" className="mt-1" />
</div>
<div>
<Label htmlFor="estado" className="text-sm font-medium text-gray-700">
Estado
</Label>
<Select>
<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 Profissionais</h2>
<div className="space-y-4">
<div className="grid md:grid-cols-2 gap-4">
<div>
<Label htmlFor="numeroConselho" className="text-sm font-medium text-gray-700">
Número do Conselho
</Label>
<Input id="numeroConselho" placeholder="Número do CRM" className="mt-1" />
</div>
<div>
<Label htmlFor="ufConselho" className="text-sm font-medium text-gray-700">
UF do Conselho
</Label>
<Select>
<SelectTrigger className="mt-1">
<SelectValue placeholder="Selecione" />
</SelectTrigger>
<SelectContent>
<SelectItem value="SE">SE</SelectItem>
<SelectItem value="BA">BA</SelectItem>
<SelectItem value="AL">AL</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="grid md:grid-cols-2 gap-4">
<div>
<Label htmlFor="dataFormatura" className="text-sm font-medium text-gray-700">
Data de Formatura
</Label>
<Input id="dataFormatura" type="date" className="mt-1" />
</div>
<div>
<Label htmlFor="instituicaoFormacao" className="text-sm font-medium text-gray-700">
Instituição de Formação
</Label>
<Input id="instituicaoFormacao" placeholder="Nome da universidade" className="mt-1" />
</div>
</div>
<div>
<Label htmlFor="especialidades" className="text-sm font-medium text-gray-700">
Especialidades Adicionais
</Label>
<Textarea id="especialidades" placeholder="Liste outras especialidades ou subespecialidades..." className="min-h-[80px] mt-1" />
</div>
</div>
</div>
<div className="flex justify-end gap-4">
<Link href="/doctor/medicos">
<Button variant="outline">Cancelar</Button>
</Link>
<Button type="submit" className="bg-green-600 hover:bg-green-700">
Salvar Médico
</Button>
</div>
</form>
</div>
</Sidebar>
);
}

View File

@ -1,445 +0,0 @@
"use client";
import { useEffect, useState, useCallback } from "react";
import Link from "next/link";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Eye, Edit, Calendar, Trash2, Loader2, MoreVertical, Filter } from "lucide-react";
import { api } from "@/services/api.mjs";
import { PatientDetailsModal } from "@/components/ui/patient-details-modal";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import Sidebar from "@/components/Sidebar";
interface Paciente {
id: string;
nome: string;
telefone: string;
cidade: string;
estado: string;
ultimoAtendimento?: string;
proximoAtendimento?: string;
email?: string;
birth_date?: string;
cpf?: string;
blood_type?: string;
weight_kg?: number;
height_m?: number;
street?: string;
number?: string;
complement?: string;
neighborhood?: string;
cep?: string;
// NOVOS CAMPOS PARA O FILTRO
convenio?: string;
vip?: string;
}
export default function PacientesPage() {
const [pacientes, setPacientes] = useState<Paciente[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [selectedPatient, setSelectedPatient] = useState<Paciente | null>(null);
const [isModalOpen, setIsModalOpen] = useState(false);
// --- ESTADOS DOS FILTROS ---
const [searchTerm, setSearchTerm] = useState("");
const [convenioFilter, setConvenioFilter] = useState("todos");
const [vipFilter, setVipFilter] = useState("todos");
// --- Lógica de Filtragem ---
const filteredPacientes = pacientes.filter((p) => {
// 1. Filtro de Texto (Nome ou Telefone)
const searchLower = searchTerm.toLowerCase();
const matchesSearch = p.nome?.toLowerCase().includes(searchLower) || p.telefone?.includes(searchLower);
// 2. Filtro de Convênio
// Se for "todos", passa. Se não, verifica se o convênio do paciente é igual ao selecionado.
const matchesConvenio = convenioFilter === "todos" || (p.convenio?.toLowerCase() === convenioFilter);
// 3. Filtro VIP
// Se for "todos", passa. Se não, verifica se o status VIP é igual ao selecionado.
const matchesVip = vipFilter === "todos" || (p.vip?.toLowerCase() === vipFilter);
return matchesSearch && matchesConvenio && matchesVip;
});
// --- Lógica de Paginação ---
const [itemsPerPage, setItemsPerPage] = useState(10);
const [currentPage, setCurrentPage] = useState(1);
// Resetar página quando qualquer filtro mudar
useEffect(() => {
setCurrentPage(1);
}, [searchTerm, convenioFilter, vipFilter, itemsPerPage]);
const totalPages = Math.ceil(filteredPacientes.length / itemsPerPage);
const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = filteredPacientes.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);
};
const handleOpenModal = (patient: Paciente) => {
setSelectedPatient(patient);
setIsModalOpen(true);
};
const handleCloseModal = () => {
setSelectedPatient(null);
setIsModalOpen(false);
};
const formatDate = (dateString: string | null | undefined) => {
if (!dateString) return "N/A";
try {
const date = new Date(dateString);
return new Intl.DateTimeFormat("pt-BR").format(date);
} catch (e) {
return dateString;
}
};
const fetchPacientes = useCallback(async () => {
try {
setLoading(true);
setError(null);
const json = await api.get("/rest/v1/patients");
const items = Array.isArray(json)
? json
: Array.isArray(json?.data)
? json.data
: [];
const mapped: Paciente[] = items.map((p: any) => ({
id: String(p.id ?? ""),
nome: p.full_name ?? "—",
telefone: p.phone_mobile ?? "N/A",
cidade: p.city ?? "N/A",
estado: p.state ?? "N/A",
ultimoAtendimento: formatDate(p.created_at),
proximoAtendimento: "N/A",
email: p.email ?? "N/A",
birth_date: p.birth_date ?? "N/A",
cpf: p.cpf ?? "N/A",
blood_type: p.blood_type ?? "N/A",
weight_kg: p.weight_kg ?? 0,
height_m: p.height_m ?? 0,
street: p.street ?? "N/A",
number: p.number ?? "N/A",
complement: p.complement ?? "N/A",
neighborhood: p.neighborhood ?? "N/A",
cep: p.cep ?? "N/A",
// ⚠️ ATENÇÃO: Verifique o nome real desses campos na sua API
// Se a API não retorna, estou colocando valores padrão para teste
convenio: p.insurance_plan || p.convenio || "Unimed", // Exemplo: mapeie o campo correto
vip: p.is_vip ? "Sim" : "Não", // Exemplo: se for booleano converta para string
}));
setPacientes(mapped);
} catch (e: any) {
console.error("Erro ao carregar pacientes:", e);
setError(e?.message || "Erro ao carregar pacientes");
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchPacientes();
}, [fetchPacientes]);
return (
<Sidebar>
<div className="space-y-6 px-2 sm:px-4 md:px-6">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
<div>
<h1 className="text-2xl font-bold text-foreground">Pacientes</h1>
<p className="text-muted-foreground text-sm sm:text-base">
Lista de pacientes vinculados
</p>
</div>
</div>
{/* --- BARRA DE PESQUISA COM FILTROS ATIVOS --- */}
<div className="flex flex-col md:flex-row gap-4 items-center p-2 border border-border rounded-lg bg-card shadow-sm">
{/* Input de Busca */}
<div className="flex items-center gap-3 flex-1 w-full px-2">
<Filter className="w-5 h-5 text-muted-foreground flex-shrink-0" />
<Input
type="text"
placeholder="Buscar por nome ou telefone..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="border-0 focus-visible:ring-0 shadow-none bg-transparent px-0 h-auto text-base placeholder:text-muted-foreground"
/>
</div>
{/* Filtros e Paginação */}
<div className="flex flex-wrap items-center gap-4 w-full md:w-auto px-2 border-t md:border-t-0 md:border-l border-border pt-2 md:pt-0 justify-end">
{/* FILTRO CONVÊNIO */}
<div className="flex items-center gap-2">
<span className="text-sm font-medium whitespace-nowrap text-muted-foreground hidden lg:inline">Convênio</span>
<Select value={convenioFilter} onValueChange={setConvenioFilter}>
<SelectTrigger className="w-[100px] h-8 border-border bg-transparent focus:ring-0">
<SelectValue placeholder="Todos" />
</SelectTrigger>
<SelectContent>
<SelectItem value="todos">Todos</SelectItem>
{/* Certifique-se que o 'value' aqui seja minúsculo para bater com a lógica do filtro */}
<SelectItem value="unimed">Unimed</SelectItem>
<SelectItem value="bradesco">Bradesco</SelectItem>
<SelectItem value="particular">Particular</SelectItem>
</SelectContent>
</Select>
</div>
{/* FILTRO VIP */}
<div className="flex items-center gap-2">
<span className="text-sm font-medium whitespace-nowrap text-muted-foreground hidden lg:inline">VIP</span>
<Select value={vipFilter} onValueChange={setVipFilter}>
<SelectTrigger className="w-[90px] h-8 border-border bg-transparent focus:ring-0">
<SelectValue placeholder="Todos" />
</SelectTrigger>
<SelectContent>
<SelectItem value="todos">Todos</SelectItem>
<SelectItem value="sim">Sim</SelectItem>
<SelectItem value="não">Não</SelectItem>
</SelectContent>
</Select>
</div>
{/* PAGINAÇÃO */}
<div className="flex items-center gap-2 pl-2 md:border-l border-border">
<Select
onValueChange={handleItemsPerPageChange}
defaultValue={String(itemsPerPage)}
>
<SelectTrigger className="w-[130px] h-8 border-border bg-transparent focus:ring-0">
<SelectValue placeholder="Paginação" />
</SelectTrigger>
<SelectContent>
<SelectItem value="5">5 por página</SelectItem>
<SelectItem value="10">10 por página</SelectItem>
<SelectItem value="20">20 por página</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</div>
{/* Tabela de Dados */}
<div className="bg-card rounded-lg border border-border overflow-hidden shadow-md">
<div className="overflow-x-auto hidden md:block">
<table className="min-w-[600px] w-full">
<thead className="bg-muted border-b border-border">
<tr>
<th className="text-left p-3 sm:p-4 font-medium text-foreground">Nome</th>
<th className="text-left p-3 sm:p-4 font-medium text-foreground">Telefone</th>
{/* Coluna Convênio visível para teste */}
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden lg:table-cell">Convênio</th>
<th className="text-left p-3 sm:p-4 font-medium text-foreground hidden lg:table-cell">VIP</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">Ações</th>
</tr>
</thead>
<tbody>
{loading ? (
<tr>
<td colSpan={7} className="p-6 text-muted-foreground text-center">
<Loader2 className="w-6 h-6 animate-spin mx-auto text-primary" />
Carregando pacientes...
</td>
</tr>
) : error ? (
<tr>
<td colSpan={7} className="p-6 text-red-600 text-center">{`Erro: ${error}`}</td>
</tr>
) : filteredPacientes.length === 0 ? (
<tr>
<td colSpan={7} className="p-8 text-center text-muted-foreground">
Nenhum paciente encontrado com esses filtros.
</td>
</tr>
) : (
currentItems.map((p) => (
<tr key={p.id} className="border-b border-border hover:bg-accent/40 transition-colors">
<td className="p-3 sm:p-4">{p.nome}</td>
<td className="p-3 sm:p-4 text-muted-foreground">{p.telefone}</td>
<td className="p-3 sm:p-4 text-muted-foreground hidden lg:table-cell">{p.convenio}</td>
<td className="p-3 sm:p-4 text-muted-foreground hidden lg:table-cell">{p.vip}</td>
<td className="p-3 sm:p-4 text-muted-foreground hidden xl:table-cell">{p.ultimoAtendimento}</td>
<td className="p-3 sm:p-4">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0">
<span className="sr-only">Abrir menu</span>
<MoreVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => handleOpenModal(p)}>
<Eye className="w-4 h-4 mr-2" />
Ver detalhes
</DropdownMenuItem>
<DropdownMenuItem asChild>
<Link href={`/doctor/medicos/${p.id}/laudos`}>
<Edit className="w-4 h-4 mr-2" />
Laudos
</Link>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
{/* Cards para Mobile */}
<div className="md:hidden divide-y divide-border">
{loading ? (
<div className="p-6 text-muted-foreground text-center">
<Loader2 className="w-6 h-6 animate-spin mx-auto text-primary" />
Carregando...
</div>
) : filteredPacientes.length === 0 ? (
<div className="p-8 text-center text-muted-foreground">
Nenhum paciente encontrado.
</div>
) : (
currentItems.map((p) => (
<div key={p.id} className="flex items-center justify-between p-4 hover:bg-accent/40 transition-colors">
<div className="flex-1 min-w-0 pr-4">
<div className="text-base font-semibold text-foreground break-words">
{p.nome || "—"}
</div>
<div className="text-sm text-muted-foreground">
{p.telefone} | {p.convenio} | VIP: {p.vip}
</div>
</div>
<div className="ml-4 flex-shrink-0">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="icon">
<Eye className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => handleOpenModal(p)}>
<Eye className="w-4 h-4 mr-2" />
Ver detalhes
</DropdownMenuItem>
<DropdownMenuItem asChild>
<Link href={`/doctor/pacientes/${p.id}/laudos`}>
<Edit className="w-4 h-4 mr-2" />
Laudos
</Link>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
))
)}
</div>
{/* Paginação */}
{totalPages > 1 && (
<div className="flex flex-wrap justify-center items-center gap-2 border-t border-border p-4 bg-muted/40">
<button
onClick={goToPrevPage}
disabled={currentPage === 1}
className="flex items-center px-4 py-2 rounded-md font-medium transition-colors text-sm bg-secondary text-secondary-foreground hover:bg-secondary/80 disabled:opacity-50 disabled:cursor-not-allowed border border-border"
>
{"< 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-border ${
currentPage === number
? "bg-blue-600 text-primary-foreground shadow-md border-blue-600"
: "bg-secondary text-secondary-foreground hover:bg-secondary/80"
}`}
>
{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-secondary text-secondary-foreground hover:bg-secondary/80 disabled:opacity-50 disabled:cursor-not-allowed border border-border"
>
{"Próximo >"}
</button>
</div>
)}
</div>
</div>
<PatientDetailsModal
patient={selectedPatient}
isOpen={isModalOpen}
onClose={handleCloseModal}
/>
</Sidebar>
);
}

View File

@ -1,23 +0,0 @@
"use client";
import { useEffect, useState } from "react";
import Sidebar from "@/components/Sidebar";
interface Paciente {
id: string;
nome: string;
telefone: string;
cidade: string;
estado: string;
ultimoAtendimento?: string;
proximoAtendimento?: string;
}
export default function PacientesPage() {
return (
<Sidebar>
<div></div>
</Sidebar>
);
}

View File

@ -1,31 +0,0 @@
// Caminho: app/(finance)/login/page.tsx
import { LoginForm } from "@/components/LoginForm";
import Link from "next/link"; // Adicionado para o link de "Voltar"
export default function FinanceLoginPage() {
// NOTA: Esta página se tornou obsoleta com a criação do /login central.
// O ideal no futuro é deletar esta página e redirecionar os usuários.
return (
<div className="min-h-screen bg-gradient-to-br from-orange-50 via-white to-orange-50 flex items-center justify-center p-4">
<div className="w-full max-w-md text-center">
<h1 className="text-3xl font-bold text-foreground mb-2">Área Financeira</h1>
<p className="text-muted-foreground mb-8">Acesse o sistema de faturamento</p>
{/* --- ALTERAÇÃO PRINCIPAL AQUI --- */}
{/* Chamando o LoginForm unificado sem props desnecessárias */}
<LoginForm>
{/* Adicionamos um link de "Voltar" como filho (children) */}
<div className="mt-6 text-center text-sm">
<Link href="/">
<span className="font-semibold text-primary hover:underline cursor-pointer">
Voltar à página inicial
</span>
</Link>
</div>
</LoginForm>
</div>
</div>
);
}

View File

@ -1,154 +0,0 @@
@import "tailwindcss";
@import "tw-animate-css";
@custom-variant dark (&:is(.dark *));
:root {
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.637 0.237 25.331);
--destructive-foreground: oklch(0.985 0 0);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--radius: 0.625rem;
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.145 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.145 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.985 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.7 0.25 25);
--destructive-foreground: oklch(0.985 0 0);
--border: oklch(0.269 0 0);
--input: oklch(0.269 0 0);
--ring: oklch(0.439 0 0);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(0.269 0 0);
--sidebar-ring: oklch(0.439 0 0);
}
.high-contrast {
--background: oklch(0 0 0);
--foreground: oklch(1 0.5 100);
--card: oklch(0 0 0);
--card-foreground: oklch(1 0.5 100);
--popover: oklch(0 0 0);
--popover-foreground: oklch(1 0.5 100);
--primary: oklch(1 0.5 100);
--primary-foreground: oklch(0 0 0);
--secondary: oklch(0 0 0);
--secondary-foreground: oklch(1 0.5 100);
--muted: oklch(0 0 0);
--muted-foreground: oklch(1 0.5 100);
--accent: oklch(0 0 0);
--accent-foreground: oklch(1 0.5 100);
--destructive: oklch(0.8 0.5 25);
--destructive-foreground: oklch(0 0 0);
--border: oklch(1 0.5 100);
--input: oklch(0 0 0);
--ring: oklch(1 0.5 100);
--sidebar: oklch(0 0 0);
--sidebar-foreground: oklch(1 0.5 100);
--sidebar-primary: oklch(1 0.5 100);
--sidebar-primary-foreground: oklch(0 0 0);
--sidebar-accent: oklch(0 0 0);
--sidebar-accent-foreground: oklch(1 0.5 100);
--sidebar-border: oklch(1 0.5 100);
--sidebar-ring: oklch(1 0.5 100);
}
@theme inline {
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--color-chart-1: var(--chart-1);
--color-chart-2: var(--chart-2);
--color-chart-3: var(--chart-3);
--color-chart-4: var(--chart-4);
--color-chart-5: var(--chart-5);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
transition: background-color 0.3s, color 0.3s;
}
}

View File

@ -1,23 +0,0 @@
import type { Metadata } from "next";
import { GeistSans } from "geist/font/sans";
import { GeistMono } from "geist/font/mono";
import { Analytics } from "@vercel/analytics/next";
import "./globals.css";
import { Toaster } from "@/components/ui/toaster";
import { Providers } from "./providers";
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en" suppressHydrationWarning>
<body className={`font-sans ${GeistSans.variable} ${GeistMono.variable}`}>
<Providers>{children}</Providers>
<Analytics />
<Toaster />
</body>
</html>
);
}

View File

@ -1,261 +0,0 @@
// Caminho: app/login/page.tsx
"use client";
import { usersService } from "@/services/usersApi.mjs";
import { LoginForm } from "@/components/LoginForm";
import Link from "next/link";
import Image from "next/image";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ArrowLeft, X } from "lucide-react";
import { useState } from "react";
import RenderFromTemplateContext from "next/dist/client/components/render-from-template-context";
export default function LoginPage() {
const [isModalOpen, setIsModalOpen] = useState(false);
const [email, setEmail] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [message, setMessage] = useState<{
type: "success" | "error";
text: string;
} | null>(null);
const handleOpenModal = () => {
// Tenta pegar o email do input do formulário de login
const emailInput = document.querySelector(
'input[type="email"]'
) as HTMLInputElement;
if (emailInput?.value) {
setEmail(emailInput.value);
}
setIsModalOpen(true);
};
const handleResetPassword = async () => {
if (!email.trim()) {
setMessage({
type: "error",
text: "Por favor, insira um e-mail válido.",
});
return;
}
setIsLoading(true);
setMessage(null);
try {
// Chama o método que já faz o fetch corretamente
const data = await usersService.resetPassword(email);
console.log("Resposta resetPassword:", data);
setMessage({
type: "success",
text: "E-mail de recuperação enviado! Verifique sua caixa de entrada.",
});
setTimeout(() => {
setIsModalOpen(false);
setMessage(null);
setEmail("");
}, 2000);
} catch (error) {
console.error("Erro no reset de senha:", error);
setMessage({
type: "error",
text:
error instanceof Error
? error.message
: "Erro ao enviar e-mail. Tente novamente.",
});
} finally {
setIsLoading(false);
}
};
const closeModal = () => {
setIsModalOpen(false);
setMessage(null);
setEmail("");
};
return (
<>
<div className="min-h-screen grid grid-cols-1 lg:grid-cols-2">
{/* PAINEL ESQUERDO: O Formulário */}
<div className="relative flex flex-col items-center justify-center p-8 bg-background">
{/* Link para Voltar */}
<div className="absolute top-8 left-8">
<Link
href="/"
className="inline-flex items-center text-muted-foreground hover:text-primary transition-colors font-medium"
>
<ArrowLeft className="w-4 h-4 mr-2" />
Voltar à página inicial
</Link>
</div>
{/* O contêiner principal que agora terá a sombra e o estilo de card */}
<div className="w-full max-w-md bg-card p-10 rounded-2xl shadow-xl border-2 border-border mt-8">
{/* NOVO: Bloco da Logo e Nome (Painel Esquerdo) */}
<div className="flex items-center justify-center space-x-3 mb-8">
<img
src="/Logo MedConnect.png" // Caminho da sua logo
alt="Logo MediConnect"
className="w-16 h-16 object-contain" // Mesmo tamanho que usamos na página inicial
/>
<span className="text-3xl font-extrabold text-primary">
MedConnect
</span>
</div>
{/* FIM: Bloco da Logo e Nome */}
<div className="text-center mb-8">
{/* Título de boas-vindas movido para baixo da logo */}
<h1 className="text-3xl font-bold text-foreground">
Acesse sua conta
</h1>
<p className="text-muted-foreground mt-2">
Bem-vindo(a) de volta ao MedConnect!
</p>
</div>
<LoginForm>
{/* Children para o LoginForm */}
<div className="mt-4 text-center text-sm">
<button
onClick={handleOpenModal}
className="text-muted-foreground hover:text-primary cursor-pointer underline bg-transparent border-none"
>
Esqueceu sua senha?
</button>
</div>
</LoginForm>
<div className="mt-6 text-center text-sm">
<span className="text-muted-foreground">
Não tem uma conta de paciente?{" "}
</span>
<Link href="/patient/register">
<span className="font-semibold text-blue-600 hover:text-blue-700 hover:underline cursor-pointer">
Crie uma agora
</span>
</Link>
</div>
</div>
</div>
{/* PAINEL DIREITO: A Imagem e Branding */}
<div className="hidden lg:block relative">
{/* Usamos o componente <Image> para otimização e performance */}
<Image
src="https://images.unsplash.com/photo-1576091160550-2173dba999ef?q=80&w=2070"
alt="Médica utilizando um tablet na clínica MedConnect"
fill
style={{ objectFit: "cover" }}
priority
className="dark:opacity-80"
/>
{/* Camada de sobreposição para escurecer a imagem e destacar o texto */}
<div className="absolute inset-0 bg-primary/80 flex flex-col items-start justify-end p-12 text-left">
{/* BLOCO DE NOME ADICIONADO */}
<div className="mb-6 border-l-4 border-primary-foreground pl-4">
<h1 className="text-5xl font-extrabold text-primary-foreground tracking-wider">
MedConnect
</h1>
</div>
<h2 className="text-4xl font-bold text-primary-foreground leading-tight">
Tecnologia e Cuidado a Serviço da Sua Saúde.
</h2>
<p className="mt-4 text-lg text-primary-foreground/80">
Acesse seu portal para uma experiência de saúde integrada, segura
e eficiente.
</p>
</div>
</div>
</div>
{/* Modal de Recuperação de Senha */}
{isModalOpen && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
<div className="relative w-full max-w-md bg-card p-8 rounded-2xl shadow-2xl mx-4">
{/* Botão de fechar */}
<button
onClick={closeModal}
className="absolute top-4 right-4 text-muted-foreground hover:text-foreground transition-colors"
>
<X className="w-5 h-5" />
</button>
{/* Cabeçalho */}
<div className="mb-6">
<h2 className="text-2xl font-bold text-foreground">
Recuperar Senha
</h2>
<p className="text-muted-foreground mt-2">
Insira seu e-mail e enviaremos um link para redefinir sua senha.
</p>
</div>
{/* Input de e-mail */}
<div className="space-y-4">
<div>
<label
htmlFor="email"
className="block text-sm font-medium text-foreground mb-2"
>
E-mail
</label>
<Input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="seu@email.com"
disabled={isLoading}
className="w-full"
/>
</div>
{/* Mensagem de feedback */}
{message && (
<div
className={`p-3 rounded-lg text-sm ${
message.type === "success"
? "bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300"
: "bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300"
}`}
>
{message.text}
</div>
)}
{/* Botões */}
<div className="flex gap-3 pt-2">
{/* Botão Cancelar Azul contornado */}
<Button
variant="outline"
onClick={closeModal}
disabled={isLoading}
className="flex-1 bg-blue-600 hover:bg-blue-700 text-white"
>
Cancelar
</Button>
{/* Botão Resetar Senha Azul sólido */}
<Button
onClick={handleResetPassword}
disabled={isLoading}
className="flex-1 bg-blue-600 hover:bg-blue-700 text-white"
>
{isLoading ? "Enviando..." : "Resetar Senha"}
</Button>
</div>
</div>
</div>
</div>
)}
</>
);
}

View File

@ -1,242 +0,0 @@
"use client";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Clock, Plus, User } from "lucide-react"; // Removi 'Calendar' que não estava sendo usado
import Link from "next/link";
import React, { useState, useEffect } from "react";
import { usersService } from "services/usersApi.mjs";
import { doctorsService } from "services/doctorsApi.mjs";
import Sidebar from "@/components/Sidebar";
import { api } from "services/api.mjs"; // <-- ADICIONEI ESTE IMPORT
export default function ManagerDashboard() {
// 🔹 Estados para usuários
const [firstUser, setFirstUser] = useState<any>(null);
const [loadingUser, setLoadingUser] = useState(true);
// 🔹 Estados para médicos
const [doctors, setDoctors] = useState<any[]>([]);
const [loadingDoctors, setLoadingDoctors] = useState(true);
// 🔹 Buscar primeiro usuário (LÓGICA ATUALIZADA)
useEffect(() => {
async function fetchFirstUser() {
setLoadingUser(true); // Garante que o estado de loading inicie como true
try {
// 1. Busca a lista de usuários com seus cargos (roles)
const rolesData = await usersService.list_roles();
// 2. Verifica se a lista não está vazia
if (Array.isArray(rolesData) && rolesData.length > 0) {
const firstUserRole = rolesData[0];
const firstUserId = firstUserRole.user_id;
if (!firstUserId) {
throw new Error("O primeiro usuário da lista não possui um ID válido.");
}
// 3. Usa o ID para buscar o perfil (com nome e email) do usuário
const profileData = await api.get(
`/rest/v1/profiles?select=full_name,email&id=eq.${firstUserId}`
);
// 4. Verifica se o perfil foi encontrado
if (Array.isArray(profileData) && profileData.length > 0) {
const userProfile = profileData[0];
// 5. Combina os dados do cargo e do perfil e atualiza o estado
setFirstUser({
...firstUserRole,
...userProfile
});
} else {
// Se não encontrar o perfil, exibe os dados que temos
setFirstUser(firstUserRole);
}
}
} catch (error) {
console.error("Erro ao carregar usuário:", error);
setFirstUser(null); // Limpa o usuário em caso de erro
} finally {
setLoadingUser(false);
}
}
fetchFirstUser();
}, []);
// 🔹 Buscar 3 primeiros médicos
useEffect(() => {
async function fetchDoctors() {
try {
const data = await doctorsService.list(); // ajuste se seu service tiver outro método
if (Array.isArray(data)) {
setDoctors(data.slice(0, 3)); // pega os 3 primeiros
}
} catch (error) {
console.error("Erro ao carregar médicos:", error);
} finally {
setLoadingDoctors(false);
}
}
fetchDoctors();
}, []);
return (
<Sidebar>
<div className="space-y-6">
{/* Cabeçalho */}
<div>
<h1 className="text-3xl font-bold">Dashboard</h1>
<p className="text-muted-foreground">
Bem-vindo ao seu portal de consultas médicas
</p>
</div>
{/* Cards principais */}
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{/* Card 2 — Gestão de usuários */}
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Gestão de usuários
</CardTitle>
<Clock className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
{loadingUser ? (
<div className="text-muted-foreground text-sm">
Carregando usuário...
</div>
) : firstUser ? (
<>
<div className="text-2xl font-bold">
{firstUser.full_name || "Sem nome"}
</div>
<p className="text-xs text-muted-foreground">
{firstUser.email || "Sem e-mail cadastrado"}
</p>
</>
) : (
<div className="text-sm text-muted-foreground">
Nenhum usuário encontrado
</div>
)}
</CardContent>
</Card>
{/* Card 3 — Perfil */}
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Perfil</CardTitle>
<User className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">100%</div>
<p className="text-xs text-muted-foreground">Dados completos</p>
</CardContent>
</Card>
</div>
{/* Cards secundários */}
<div className="grid md:grid-cols-2 gap-6">
{/* Card — Ações rápidas */}
<Card>
<CardHeader>
<CardTitle>Ações Rápidas</CardTitle>
<CardDescription>
Acesse rapidamente as principais funcionalidades
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<Link href="/manager/home">
<Button className="w-full justify-start">
<User className="mr-2 h-4 w-4" />
Gestão de Médicos
</Button>
</Link>
<Link href="/manager/usuario">
<Button
variant="outline"
className="w-full justify-start"
>
<User className="mr-2 h-4 w-4" />
Usuários Cadastrados
</Button>
</Link>
<Link href="/manager/home/novo">
<Button
variant="outline"
className="w-full justify-start"
>
<Plus className="mr-2 h-4 w-4" />
Adicionar Novo Médico
</Button>
</Link>
<Link href="/manager/usuario/novo">
<Button
variant="outline"
className="w-full justify-start"
>
<Plus className="mr-2 h-4 w-4" />
Criar novo Usuário
</Button>
</Link>
</CardContent>
</Card>
{/* Card — Gestão de Médicos */}
<Card>
<CardHeader>
<CardTitle>Gestão de Médicos</CardTitle>
<CardDescription>
Médicos cadastrados recentemente
</CardDescription>
</CardHeader>
<CardContent>
{loadingDoctors ? (
<p className="text-sm text-muted-foreground">Carregando médicos...</p>
) : doctors.length === 0 ? (
<p className="text-sm text-muted-foreground">
Nenhum médico cadastrado.
</p>
) : (
<div className="space-y-4">
{doctors.map((doc, index) => (
<div
key={index}
className="flex items-center justify-between p-3 bg-secondary rounded-lg border"
>
<div>
<p className="font-medium">
{doc.full_name || "Sem nome"}
</p>
<p className="text-sm text-muted-foreground">
{doc.specialty || "Sem especialidade"}
</p>
</div>
<div className="text-right">
<p className="font-medium text-primary">
{doc.active ? "Ativo" : "Inativo"}
</p>
</div>
</div>
))}
</div>
)}
</CardContent>
</Card>
</div>
</div>
</Sidebar>
);
}

View File

@ -1,185 +0,0 @@
"use client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import Sidebar from "@/components/Sidebar";
import WeeklyScheduleCard from "@/components/ui/WeeklyScheduleCard";
import { useEffect, useState, useMemo } from "react";
import { AvailabilityService } from "@/services/availabilityApi.mjs";
import { doctorsService } from "@/services/doctorsApi.mjs";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { Filter } from "lucide-react";
type Doctor = {
id: string;
full_name: string;
specialty: string;
active: boolean;
};
type Availability = {
id: string;
doctor_id: string;
weekday: string;
start_time: string;
end_time: string;
};
export default function AllAvailabilities() {
const [availabilities, setAvailabilities] = useState<Availability[] | null>(null);
const [doctors, setDoctors] = useState<Doctor[] | null>(null);
// 🔎 Filtros
const [search, setSearch] = useState("");
const [specialty, setSpecialty] = useState("all");
// 🔄 Paginação
const ITEMS_PER_PAGE = 6;
const [page, setPage] = useState(1);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
try {
const doctorsList = await doctorsService.list();
setDoctors(doctorsList);
const availabilityList = await AvailabilityService.list();
setAvailabilities(availabilityList);
} catch (e: any) {
alert(`${e?.error} ${e?.message}`);
} finally {
setLoading(false);
}
};
fetchData();
}, []);
// 🎯 Obter todas as especialidades existentes
const specialties = useMemo(() => {
if (!doctors) return [];
const unique = Array.from(new Set(doctors.map((d) => d.specialty)));
return unique;
}, [doctors]);
// 🔍 Filtrar médicos por especialidade + nome
const filteredDoctors = useMemo(() => {
if (!doctors) return [];
return doctors.filter((doctor) => (specialty === "all" ? true : doctor.specialty === specialty)).filter((doctor) => doctor.full_name.toLowerCase().includes(search.toLowerCase()));
}, [doctors, search, specialty]);
// 📄 Paginação (após filtros!)
const totalPages = Math.ceil(filteredDoctors.length / ITEMS_PER_PAGE);
const paginatedDoctors = filteredDoctors.slice((page - 1) * ITEMS_PER_PAGE, page * ITEMS_PER_PAGE);
const goNext = () => setPage((p) => Math.min(p + 1, totalPages));
const goPrev = () => setPage((p) => Math.max(p - 1, 1));
if (loading) {
return (
<Sidebar>
<div className="p-6 text-muted-foreground">Carregando dados...</div>
</Sidebar>
);
}
if (!doctors || !availabilities) {
return (
<Sidebar>
<div className="p-6 text-destructive font-medium">Não foi possível carregar médicos ou disponibilidades.</div>
</Sidebar>
);
}
return (
<Sidebar>
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold">Disponibilidade dos Médicos</h1>
<p className="text-muted-foreground">Visualize a agenda semanal individual de cada médico.</p>
</div>
<Card>
<CardContent>
{/* 🔎 Filtros */}
<div className="flex flex-col md:flex-row gap-4 items-center">
{/* Filtro por nome */}
<Filter className="w-4 h-4 mr-2" />
<Input
placeholder="Buscar por nome do médico..."
value={search}
onChange={(e) => {
setSearch(e.target.value);
setPage(1);
}}
className="w-full md:w-1/3"
/>
{/* Filtro por especialidade */}
<Select
onValueChange={(value) => {
setSpecialty(value);
setPage(1);
}}
defaultValue="all"
>
<SelectTrigger className="w-full md:w-64">
<SelectValue placeholder="Especialidade" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Todas as especialidades</SelectItem>
{specialties.map((sp) => (
<SelectItem key={sp} value={sp}>
{sp}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</CardContent>
</Card>
{/* GRID de cards */}
<div className="grid md:grid-cols-1 lg:grid-cols-1 gap-6">
{paginatedDoctors.map((doctor) => {
const doctorAvailabilities = availabilities.filter((a) => a.doctor_id === doctor.id);
return (
<Card key={doctor.id}>
<CardHeader>
<CardTitle className="text-xl font-semibold">{doctor.full_name}</CardTitle>
</CardHeader>
<CardContent>
<WeeklyScheduleCard doctorId={doctor.id} />
</CardContent>
</Card>
);
})}
</div>
{/* 📄 Paginação */}
{totalPages > 1 && (
<div className="flex justify-center items-center gap-4 pt-4">
<Button variant="outline" onClick={goPrev} disabled={page === 1}>
Anterior
</Button>
<span className="text-muted-foreground font-medium">
Página {page} de {totalPages}
</span>
<Button variant="outline" onClick={goNext} disabled={page === totalPages}>
Próxima
</Button>
</div>
)}
</div>
</Sidebar>
);
}

View File

@ -1,492 +0,0 @@
"use client"
import { useState, useEffect, useCallback } from "react"
import { useRouter, useParams } 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 { Save, Loader2, ArrowLeft } from "lucide-react"
import Sidebar from "@/components/Sidebar"
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;
especialidade: string;
cpf: string;
email: string;
dataNascimento: string;
rg: string;
telefoneCelular: string;
telefone2: string;
cep: string;
endereco: string;
numero: string;
complemento: string;
bairro: string;
cidade: string;
estado: string;
ativo: boolean;
observacoes: string;
}
const apiMap: { [K in keyof DoctorFormData]: string | null } = {
nomeCompleto: 'full_name', crm: 'crm', crmEstado: 'crm_uf', especialidade: 'specialty',
cpf: 'cpf', email: 'email', dataNascimento: 'birth_date', rg: 'rg',
telefoneCelular: 'phone_mobile', telefone2: 'phone2', cep: 'cep',
endereco: 'street', numero: 'number', complemento: 'complement',
bairro: 'neighborhood', cidade: 'city', estado: 'state', ativo: 'active',
observacoes: null,
};
const defaultFormData: DoctorFormData = {
nomeCompleto: '', crm: '', crmEstado: '', especialidade: '', cpf: '', email: '',
dataNascimento: '', rg: '', telefoneCelular: '', telefone2: '', cep: '',
endereco: '', numero: '', complemento: '', bairro: '', cidade: '', estado: '',
ativo: true, observacoes: '',
};
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 EditarMedicoPage() {
const router = useRouter();
const params = useParams();
const id = Array.isArray(params.id) ? params.id[0] : params.id;
const [formData, setFormData] = useState<DoctorFormData>(defaultFormData);
const [loading, setLoading] = useState(true);
const [isSaving, setIsSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const apiToFormMap: { [key: string]: keyof DoctorFormData } = {
'full_name': 'nomeCompleto', 'crm': 'crm', 'crm_uf': 'crmEstado', 'specialty': 'especialidade',
'cpf': 'cpf', 'email': 'email', 'birth_date': 'dataNascimento', 'rg': 'rg',
'phone_mobile': 'telefoneCelular', 'phone2': 'telefone2', 'cep': 'cep',
'street': 'endereco', 'number': 'numero', 'complement': 'complemento',
'neighborhood': 'bairro', 'city': 'cidade', 'state': 'estado', 'active': 'ativo'
};
useEffect(() => {
if (!id) return;
const fetchDoctor = async () => {
try {
const data = await doctorsService.getById(id);
if (!data) {
setError("Médico não encontrado.");
setLoading(false);
return;
}
const initialData: Partial<DoctorFormData> = {};
Object.keys(data).forEach(key => {
const formKey = apiToFormMap[key];
if (formKey) {
let value = data[key] === null ? '' : data[key];
if (formKey === 'ativo') {
value = !!value;
} else if (typeof value !== 'boolean') {
value = String(value);
}
initialData[formKey] = value as any;
}
});
initialData.observacoes = "Observação carregada do sistema (exemplo de campo interno)";
setFormData(prev => ({ ...prev, ...initialData }));
} catch (e) {
console.error("Erro ao carregar dados:", e);
setError("Não foi possível carregar os dados do médico.");
} finally {
setLoading(false);
}
};
fetchDoctor();
}, [id]);
const handleInputChange = (key: keyof DoctorFormData, value: string | boolean) => {
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 handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setIsSaving(true);
if (!id) {
setError("ID do médico ausente.");
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();
if (trimmedValue === '') {
finalPayload[apiFieldName] = null;
return;
}
if (key === 'crmEstado' || key === 'estado') {
trimmedValue = trimmedValue.toUpperCase();
}
value = trimmedValue;
}
finalPayload[apiFieldName] = value;
});
delete finalPayload.user_id;
try {
await doctorsService.update(id, finalPayload);
router.push("/manager/home");
} catch (e: any) {
console.error("Erro ao salvar o médico:", e);
let detailedError = "Erro ao atualizar. Verifique os dados e tente novamente.";
if (e.message && e.message.includes("duplicate key value violates unique constraint")) {
detailedError = "O CPF ou CRM informado já está cadastrado em outro registro.";
} 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 atualizar. Detalhes: ${detailedError}`);
} finally {
setIsSaving(false);
}
};
if (loading) {
return (
<Sidebar>
<div className="flex justify-center items-center h-full w-full py-16">
<Loader2 className="w-8 h-8 animate-spin text-primary" />
<p className="ml-2 text-muted-foreground">Carregando dados do médico...</p>
</div>
</Sidebar>
);
}
return (
<Sidebar>
<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-foreground">
Editar Médico: <span className="text-primary">{formData.nomeCompleto}</span>
</h1>
<p className="text-sm text-muted-foreground">
Atualize as informações do médico
</p>
</div>
<Link href="/manager/home">
<Button variant="outline">
<ArrowLeft className="w-4 h-4 mr-2" />
Voltar
</Button>
</Link>
</div>
<form onSubmit={handleSubmit} className="space-y-6">
{error && (
<div className="p-3 rounded-lg border bg-destructive/10 text-destructive border-destructive/30">
<p className="font-medium">Erro na Atualização:</p>
<p className="text-sm">{error}</p>
</div>
)}
<div className="space-y-4 p-4 rounded-xl border border-border shadow-sm bg-card">
<h2 className="text-lg font-semibold text-foreground border-b border-border 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"
/>
</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"
/>
</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}
/>
</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-4 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"
/>
</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 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>
<div className="space-y-4 p-4 rounded-xl border border-border shadow-sm bg-card">
<h2 className="text-lg font-semibold text-foreground border-b border-border pb-2">
Contato e Endereço
</h2>
<div className="grid md:grid-cols-2 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>
<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">Logradouro</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="cidade">Cidade</Label>
<Input
id="cidade"
value={formData.cidade}
onChange={(e) => handleInputChange("cidade", e.target.value)}
placeholder="São Paulo"
/>
</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>
</div>
<div className="space-y-4 p-4 rounded-xl border border-border shadow-sm bg-card">
<h2 className="text-lg font-semibold text-foreground border-b border-border pb-2">
Observações (Apenas internas)
</h2>
<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="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-primary hover:bg-primary/90"
disabled={isSaving}
>
{isSaving ? (
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
) : (
<Save className="w-4 h-4 mr-2" />
)}
{isSaving ? "Salvando..." : "Salvar Alterações"}
</Button>
</div>
</form>
</div>
</Sidebar>
);
}

View File

@ -1,552 +0,0 @@
"use client";
import React, { useEffect, useState, useCallback, useMemo } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Edit, Trash2, Eye, Calendar, Filter, Loader2, MoreVertical } from "lucide-react"
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog"
import { doctorsService } from "services/doctorsApi.mjs";
import Sidebar from "@/components/Sidebar";
// --- NOVOS IMPORTS (Certifique-se que criou os arquivos no passo anterior) ---
import { FilterBar } from "@/components/ui/filter-bar";
import { normalizeSpecialty, getUniqueSpecialties } from "@/lib/normalization";
interface Doctor {
id: number;
full_name: string;
specialty: string;
crm: string;
phone_mobile: string | null;
city: string | null;
state: string | null;
status?: string;
}
interface DoctorDetails {
nome: string;
crm: string;
especialidade: string;
contato: {
celular?: string;
telefone1?: string;
};
endereco: {
cidade?: string;
estado?: string;
};
convenio?: string;
vip?: boolean;
status?: string;
ultimo_atendimento?: string;
proximo_atendimento?: string;
error?: string;
}
export default function DoctorsPage() {
const router = useRouter();
// --- Estados de Dados ---
const [doctors, setDoctors] = useState<Doctor[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// --- Estados de Modais ---
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
const [doctorDetails, setDoctorDetails] = useState<DoctorDetails | null>(null);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [doctorToDeleteId, setDoctorToDeleteId] = useState<number | null>(null);
// --- Estados de Filtro e Busca ---
const [searchTerm, setSearchTerm] = useState("");
const [filters, setFilters] = useState({
specialty: "all",
status: "all"
});
// --- Estados de Paginação ---
const [itemsPerPage, setItemsPerPage] = useState(10);
const [currentPage, setCurrentPage] = useState(1);
// 1. Buscar Médicos na API
const fetchDoctors = useCallback(async () => {
setLoading(true);
setError(null);
try {
const data: Doctor[] = await doctorsService.list();
// Mockando status para visualização (conforme original)
const dataWithStatus = data.map((doc, index) => ({
...doc,
status: index % 3 === 0 ? "Inativo" : index % 2 === 0 ? "Férias" : "Ativo",
}));
setDoctors(dataWithStatus || []);
// Não resetamos a página aqui para manter a navegação fluida se apenas recarregar dados
} catch (e: any) {
console.error("Erro ao carregar lista de médicos:", e);
setError("Não foi possível carregar a lista de médicos. Verifique a conexão com a API.");
setDoctors([]);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchDoctors();
}, [fetchDoctors]);
// 2. Gerar lista única de especialidades (Normalizada)
const uniqueSpecialties = useMemo(() => {
return getUniqueSpecialties(doctors);
}, [doctors]);
// 3. Lógica de Filtragem Centralizada
const filteredDoctors = useMemo(() => {
return doctors.filter((doctor) => {
// Normaliza a especialidade do médico atual para comparar
const normalizedDocSpecialty = normalizeSpecialty(doctor.specialty);
// Filtros exatos
const specialtyMatch = filters.specialty === "all" || normalizedDocSpecialty === filters.specialty;
const statusMatch = filters.status === "all" || doctor.status === filters.status;
// Busca textual (Nome, Telefone, CRM)
const searchLower = searchTerm.toLowerCase();
const nameMatch = doctor.full_name?.toLowerCase().includes(searchLower);
const phoneMatch = doctor.phone_mobile?.includes(searchLower);
const crmMatch = doctor.crm?.toLowerCase().includes(searchLower);
return specialtyMatch && statusMatch && (searchTerm === "" || nameMatch || phoneMatch || crmMatch);
});
}, [doctors, filters, searchTerm]);
// --- Handlers de Controle (Com Reset de Paginação) ---
const handleSearch = (term: string) => {
setSearchTerm(term);
setCurrentPage(1); // Correção: Reseta para página 1 ao buscar
};
const handleFilterChange = (key: string, value: string) => {
setFilters(prev => ({ ...prev, [key]: value }));
setCurrentPage(1); // Correção: Reseta para página 1 ao filtrar
};
const handleClearFilters = () => {
setSearchTerm("");
setFilters({ specialty: "all", status: "all" });
setCurrentPage(1); // Correção: Reseta para página 1 ao limpar
};
const handleItemsPerPageChange = (value: string) => {
setItemsPerPage(Number(value));
setCurrentPage(1);
};
// --- Lógica de Paginação ---
const totalPages = Math.ceil(filteredDoctors.length / itemsPerPage);
const 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);
// --- Handlers de Ações (Detalhes e Delete) ---
const openDetailsDialog = (doctor: Doctor) => {
setDetailsDialogOpen(true);
setDoctorDetails({
nome: doctor.full_name,
crm: doctor.crm,
especialidade: normalizeSpecialty(doctor.specialty), // Exibe normalizado
contato: { celular: doctor.phone_mobile ?? undefined },
endereco: { cidade: doctor.city ?? undefined, estado: doctor.state ?? undefined },
status: doctor.status || "Ativo",
convenio: "Particular",
vip: false,
ultimo_atendimento: "N/A",
proximo_atendimento: "N/A",
});
};
const openDeleteDialog = (doctorId: number) => {
setDoctorToDeleteId(doctorId);
setDeleteDialogOpen(true);
};
const handleDelete = async () => {
if (doctorToDeleteId === null) return;
setLoading(true);
try {
await doctorsService.delete(doctorToDeleteId);
setDeleteDialogOpen(false);
setDoctorToDeleteId(null);
await fetchDoctors();
} catch (e) {
console.error("Erro ao excluir:", e);
alert("Erro ao excluir médico.");
} finally {
setLoading(false);
}
};
return (
<Sidebar>
<div className="space-y-6 px-2 sm:px-4 md:px-6">
{/* Cabeçalho */}
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
<div>
<h1 className="text-2xl font-bold">
Médicos Cadastrados
</h1>
<p className="text-sm text-muted-foreground">
Gerencie todos os profissionais de saúde.
</p>
</div>
</div>
{/* --- NOVO COMPONENTE DE FILTRO --- */}
<FilterBar
searchTerm={searchTerm}
onSearch={handleSearch}
activeFilters={filters}
onFilterChange={handleFilterChange}
onClearFilters={handleClearFilters}
searchPlaceholder="Buscar por nome, CRM ou telefone..."
filters={[
{
key: "specialty",
label: "Especialidade",
options: uniqueSpecialties
},
{
key: "status",
label: "Status",
options: ["Ativo", "Férias", "Inativo"]
}
]}
>
{/* Seletor de Itens por Página (Filho do FilterBar) */}
<div className="hidden lg:block">
<Select onValueChange={handleItemsPerPageChange} defaultValue={String(itemsPerPage)}>
<SelectTrigger className="w-[70px]">
<SelectValue placeholder="10" />
</SelectTrigger>
<SelectContent>
<SelectItem value="5">5</SelectItem>
<SelectItem value="10">10</SelectItem>
<SelectItem value="20">20</SelectItem>
</SelectContent>
</Select>
</div>
</FilterBar>
{/* Tabela de Médicos */}
<div className="bg-card rounded-lg border shadow-md overflow-hidden hidden md:block">
{loading ? (
<div className="p-8 text-center text-muted-foreground">
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-primary" />
Carregando médicos...
</div>
) : error ? (
<div className="p-8 text-center text-destructive">{error}</div>
) : filteredDoctors.length === 0 ? (
<div className="p-8 text-center text-muted-foreground">
{doctors.length === 0
? <>Nenhum médico cadastrado. <Link href="/manager/home/novo" className="text-primary hover:underline">Adicione um novo</Link>.</>
: "Nenhum médico encontrado com os filtros aplicados."
}
</div>
) : (
<div className="overflow-x-auto">
<table className="w-full min-w-[600px]">
<thead className="bg-muted border-b">
<tr>
<th className="text-left p-2 md:p-4 font-medium text-muted-foreground">Nome</th>
<th className="text-left p-2 md:p-4 font-medium text-muted-foreground">CRM</th>
<th className="text-left p-2 md:p-4 font-medium text-muted-foreground">Especialidade</th>
<th className="text-left p-2 md:p-4 font-medium text-muted-foreground hidden lg:table-cell">Status</th>
<th className="text-left p-2 md:p-4 font-medium text-muted-foreground hidden xl:table-cell">Cidade/Estado</th>
<th className="text-right p-4 font-medium text-muted-foreground">Ações</th>
</tr>
</thead>
<tbody className="bg-card divide-y">
{currentItems.map((doctor) => (
<tr key={doctor.id} className="hover:bg-muted transition">
<td className="px-4 py-3 font-medium">
{doctor.full_name}
</td>
<td className="px-4 py-3 text-muted-foreground hidden sm:table-cell">{doctor.crm}</td>
<td className="px-4 py-3 text-muted-foreground hidden md:table-cell">
{/* Exibe Especialidade Normalizada */}
{normalizeSpecialty(doctor.specialty)}
</td>
<td className="px-4 py-3 text-muted-foreground hidden lg:table-cell">
<span className={`px-2 py-1 rounded-full text-xs ${
doctor.status === 'Ativo' ? 'bg-primary/10 text-primary' :
doctor.status === 'Inativo' ? 'bg-destructive/10 text-destructive' : 'bg-yellow-400/10 text-yellow-400'
}`}>
{doctor.status || "N/A"}
</span>
</td>
<td className="px-4 py-3 text-muted-foreground hidden xl:table-cell">
{(doctor.city || doctor.state)
? `${doctor.city || ""}${doctor.city && doctor.state ? '/' : ''}${doctor.state || ""}`
: "N/A"}
</td>
<td className="px-4 py-3 text-right">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0">
<span className="sr-only">Abrir menu</span>
<MoreVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => openDetailsDialog(doctor)}>
<Eye className="mr-2 h-4 w-4" />
Ver detalhes
</DropdownMenuItem>
<DropdownMenuItem asChild>
<Link href={`/manager/home/${doctor.id}/editar`}>
<Edit className="mr-2 h-4 w-4" />
Editar
</Link>
</DropdownMenuItem>
<DropdownMenuItem>
<Calendar className="mr-2 h-4 w-4" />
Marcar consulta
</DropdownMenuItem>
<DropdownMenuItem className="text-destructive" onClick={() => openDeleteDialog(doctor.id)}>
<Trash2 className="mr-2 h-4 w-4" />
Excluir
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
{/* Cards de Médicos (Mobile) */}
<div className="bg-card rounded-lg border shadow-md p-4 block md:hidden">
{loading ? (
<div className="p-8 text-center text-muted-foreground">
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-primary" />
Carregando médicos...
</div>
) : error ? (
<div className="p-8 text-center text-destructive">{error}</div>
) : filteredDoctors.length === 0 ? (
<div className="p-8 text-center text-muted-foreground">
{doctors.length === 0
? <>Nenhum médico cadastrado. <Link href="/manager/home/novo" className="text-primary hover:underline">Adicione um novo</Link>.</>
: "Nenhum médico encontrado com os filtros aplicados."
}
</div>
) : (
<div className="space-y-4">
{currentItems.map((doctor) => (
<div key={doctor.id} className="bg-muted rounded-lg p-4 flex justify-between items-center border">
<div>
<div className="font-semibold">{doctor.full_name}</div>
<div className="text-xs text-muted-foreground mb-1">{doctor.phone_mobile}</div>
<div className="text-sm text-muted-foreground">{normalizeSpecialty(doctor.specialty)}</div>
<div className="text-xs mt-1">
<span className={`px-2 py-0.5 rounded-full text-xs ${
doctor.status === 'Ativo' ? 'bg-primary/10 text-primary' :
doctor.status === 'Inativo' ? 'bg-destructive/10 text-destructive' : 'bg-yellow-400/10 text-yellow-400'
}`}>
{doctor.status || "N/A"}
</span>
</div>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
<span className="sr-only">Abrir menu</span>
<div className="font-bold text-muted-foreground">...</div>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => openDetailsDialog(doctor)}>
<Eye className="mr-2 h-4 w-4" />
Ver detalhes
</DropdownMenuItem>
<DropdownMenuItem asChild>
<Link href={`/manager/home/${doctor.id}/editar`}>
<Edit className="mr-2 h-4 w-4" />
Editar
</Link>
</DropdownMenuItem>
<DropdownMenuItem className="text-destructive" onClick={() => openDeleteDialog(doctor.id)}>
<Trash2 className="mr-2 h-4 w-4" />
Excluir
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
))}
</div>
)}
</div>
{/* Paginação */}
{totalPages > 1 && (
<div className="flex flex-wrap justify-center items-center gap-2 mt-4 p-4 bg-card rounded-lg border 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-muted text-muted-foreground hover:bg-muted/90 disabled:opacity-50 disabled:cursor-not-allowed border"
>
{"< 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 ${
currentPage === number
? "bg-primary text-primary-foreground shadow-md border-primary"
: "bg-muted text-muted-foreground hover:bg-muted/90"
}`}
>
{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-muted text-muted-foreground hover:bg-muted/90 disabled:opacity-50 disabled:cursor-not-allowed border"
>
{"Próximo >"}
</button>
</div>
)}
{/* Dialogs (Exclusão e Detalhes) */}
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Confirma a exclusão?</AlertDialogTitle>
<AlertDialogDescription>Esta ação é irreversível e excluirá permanentemente o registro deste médico.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={loading}>Cancelar</AlertDialogCancel>
<AlertDialogAction onClick={handleDelete} className="bg-destructive hover:bg-destructive/90" disabled={loading}>
{loading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null}
Excluir
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<AlertDialog
open={detailsDialogOpen}
onOpenChange={setDetailsDialogOpen}
>
<AlertDialogContent className="max-w-[95%] sm:max-w-lg">
<AlertDialogHeader>
<AlertDialogTitle className="text-2xl">
{doctorDetails?.nome}
</AlertDialogTitle>
<AlertDialogDescription className="text-left text-muted-foreground">
{doctorDetails && (
<div className="space-y-3 text-left">
<h3 className="font-semibold mt-2">
Informações Principais
</h3>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-y-2 gap-x-4 text-sm">
<div>
<strong>CRM:</strong> {doctorDetails.crm}
</div>
<div>
<strong>Especialidade:</strong>{" "}
{doctorDetails.especialidade}
</div>
<div>
<strong>Celular:</strong>{" "}
{doctorDetails.contato.celular || "N/A"}
</div>
<div>
<strong>Localização:</strong>{" "}
{`${doctorDetails.endereco.cidade || "N/A"}/${
doctorDetails.endereco.estado || "N/A"
}`}
</div>
</div>
<h3 className="font-semibold mt-4">
Atendimento e Convênio
</h3>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-y-2 gap-x-4 text-sm">
<div>
<strong>Convênio:</strong>{" "}
{doctorDetails.convenio || "N/A"}
</div>
<div>
<strong>VIP:</strong>{" "}
{doctorDetails.vip ? "Sim" : "Não"}
</div>
<div>
<strong>Status:</strong> {doctorDetails.status || "N/A"}
</div>
<div>
<strong>Último atendimento:</strong>{" "}
{doctorDetails.ultimo_atendimento || "N/A"}
</div>
<div>
<strong>Próximo atendimento:</strong>{" "}
{doctorDetails.proximo_atendimento || "N/A"}
</div>
</div>
</div>
)}
{doctorDetails === null && !loading && (
<div className="text-destructive">Detalhes não disponíveis.</div>
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Fechar</AlertDialogCancel>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</Sidebar>
);
}

View File

@ -1,31 +0,0 @@
// Caminho: app/(manager)/login/page.tsx
import { LoginForm } from "@/components/LoginForm";
import Link from "next/link"; // Adicionado para o link de "Voltar"
export default function ManagerLoginPage() {
// NOTA: Esta página se tornou obsoleta com a criação do /login central.
// O ideal no futuro é deletar esta página e redirecionar os usuários.
return (
<div className="min-h-screen bg-background flex items-center justify-center p-4">
<div className="w-full max-w-md text-center">
<h1 className="text-3xl font-bold text-foreground mb-2">Área do Gestor</h1>
<p className="text-muted-foreground mb-8">Acesse o sistema médico</p>
{/* --- ALTERAÇÃO PRINCIPAL AQUI --- */}
{/* Chamando o LoginForm unificado sem props desnecessárias */}
<LoginForm>
{/* Adicionamos um link de "Voltar" como filho (children) */}
<div className="mt-6 text-center text-sm">
<Link href="/">
<span className="font-semibold text-primary hover:underline cursor-pointer">
Voltar à página inicial
</span>
</Link>
</div>
</LoginForm>
</div>
</div>
);
}

View File

@ -1,651 +0,0 @@
"use client";
import type React from "react";
import { useState, useEffect, useRef } from "react";
import { useRouter, useParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { ArrowLeft, Save, Trash2, Paperclip, Upload } from "lucide-react";
import Link from "next/link";
import { useToast } from "@/hooks/use-toast";
import { patientsService } from "@/services/patientsApi.mjs";
import Sidebar from "@/components/Sidebar";
export default function EditarPacientePage() {
const router = useRouter();
const params = useParams();
const patientId = params.id;
const { toast } = useToast();
// Photo upload state
const fileInputRef = useRef<HTMLInputElement | null>(null);
const [isUploadingPhoto, setIsUploadingPhoto] = useState(false);
const [photoUrl, setPhotoUrl] = useState<string | null>(null);
// Anexos state
const [anexos, setAnexos] = useState<any[]>([]);
const [isUploadingAnexo, setIsUploadingAnexo] = useState(false);
const anexoInputRef = useRef<HTMLInputElement | null>(null);
// Tipagem completa do formulário
type FormData = {
nome: string;
cpf: string;
dataNascimento: string;
sexo: string;
id?: string;
nomeSocial?: string;
rg?: string;
documentType?: string;
documentNumber?: string;
ethnicity?: string;
race?: string;
naturality?: string;
nationality?: string;
profession?: string;
maritalStatus?: string;
motherName?: string;
motherProfession?: string;
fatherName?: string;
fatherProfession?: string;
guardianName?: string;
guardianCpf?: string;
spouseName?: string;
rnInInsurance?: boolean;
legacyCode?: string;
notes?: string;
email?: string;
phoneMobile?: string;
phone1?: string;
phone2?: string;
cep?: string;
street?: string;
number?: string;
complement?: string;
neighborhood?: string;
city?: string;
state?: string;
reference?: string;
vip?: boolean;
lastVisitAt?: string;
nextAppointmentAt?: string;
createdAt?: string;
updatedAt?: string;
createdBy?: string;
updatedBy?: string;
weightKg?: string;
heightM?: string;
bmi?: string;
bloodType?: string;
};
const [formData, setFormData] = useState<FormData>({
nome: "",
cpf: "",
dataNascimento: "",
sexo: "",
id: "",
nomeSocial: "",
rg: "",
documentType: "",
documentNumber: "",
ethnicity: "",
race: "",
naturality: "",
nationality: "",
profession: "",
maritalStatus: "",
motherName: "",
motherProfession: "",
fatherName: "",
fatherProfession: "",
guardianName: "",
guardianCpf: "",
spouseName: "",
rnInInsurance: false,
legacyCode: "",
notes: "",
email: "",
phoneMobile: "",
phone1: "",
phone2: "",
cep: "",
street: "",
number: "",
complement: "",
neighborhood: "",
city: "",
state: "",
reference: "",
vip: false,
lastVisitAt: "",
nextAppointmentAt: "",
createdAt: "",
updatedAt: "",
createdBy: "",
updatedBy: "",
weightKg: "",
heightM: "",
bmi: "",
bloodType: "",
});
const [isGuiaConvenio, setIsGuiaConvenio] = useState(false);
const [validadeIndeterminada, setValidadeIndeterminada] = useState(false);
useEffect(() => {
async function fetchPatient() {
try {
const res = await patientsService.getById(patientId);
setFormData({
id: res[0]?.id ?? "",
nome: res[0]?.full_name ?? "",
nomeSocial: res[0]?.social_name ?? "",
cpf: res[0]?.cpf ?? "",
rg: res[0]?.rg ?? "",
documentType: res[0]?.document_type ?? "",
documentNumber: res[0]?.document_number ?? "",
sexo: res[0]?.sex ?? "",
dataNascimento: res[0]?.birth_date ?? "",
ethnicity: res[0]?.ethnicity ?? "",
race: res[0]?.race ?? "",
naturality: res[0]?.naturality ?? "",
nationality: res[0]?.nationality ?? "",
profession: res[0]?.profession ?? "",
maritalStatus: res[0]?.marital_status ?? "",
motherName: res[0]?.mother_name ?? "",
motherProfession: res[0]?.mother_profession ?? "",
fatherName: res[0]?.father_name ?? "",
fatherProfession: res[0]?.father_profession ?? "",
guardianName: res[0]?.guardian_name ?? "",
guardianCpf: res[0]?.guardian_cpf ?? "",
spouseName: res[0]?.spouse_name ?? "",
rnInInsurance: res[0]?.rn_in_insurance ?? false,
legacyCode: res[0]?.legacy_code ?? "",
notes: res[0]?.notes ?? "",
email: res[0]?.email ?? "",
phoneMobile: res[0]?.phone_mobile ?? "",
phone1: res[0]?.phone1 ?? "",
phone2: res[0]?.phone2 ?? "",
cep: res[0]?.cep ?? "",
street: res[0]?.street ?? "",
number: res[0]?.number ?? "",
complement: res[0]?.complement ?? "",
neighborhood: res[0]?.neighborhood ?? "",
city: res[0]?.city ?? "",
state: res[0]?.state ?? "",
reference: res[0]?.reference ?? "",
vip: res[0]?.vip ?? false,
lastVisitAt: res[0]?.last_visit_at ?? "",
nextAppointmentAt: res[0]?.next_appointment_at ?? "",
createdAt: res[0]?.created_at ?? "",
updatedAt: res[0]?.updated_at ?? "",
createdBy: res[0]?.created_by ?? "",
updatedBy: res[0]?.updated_by ?? "",
weightKg: res[0]?.weight_kg ? String(res[0].weight_kg) : "",
heightM: res[0]?.height_m ? String(res[0].height_m) : "",
bmi: res[0]?.bmi ? String(res[0].bmi) : "",
bloodType: res[0]?.blood_type ?? "",
});
} catch (e: any) {
toast({ title: "Erro", description: e?.message || "Falha ao carregar paciente" });
}
}
fetchPatient();
}, [patientId, toast]);
const handleInputChange = (field: string, value: string) => {
setFormData((prev) => ({ ...prev, [field]: value }));
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const payload = {
full_name: formData.nome || null,
cpf: formData.cpf || null,
email: formData.email || null,
phone_mobile: formData.phoneMobile || null,
birth_date: formData.dataNascimento || null,
social_name: formData.nomeSocial || null,
sex: formData.sexo || null,
blood_type: formData.bloodType || null,
weight_kg: formData.weightKg ? Number(formData.weightKg) : null,
height_m: formData.heightM ? Number(formData.heightM) : null,
street: formData.street || null,
number: formData.number || null,
complement: formData.complement || null,
neighborhood: formData.neighborhood || null,
city: formData.city || null,
state: formData.state || null,
cep: formData.cep || null,
};
try {
await patientsService.update(patientId, payload);
toast({
title: "Sucesso",
description: "Paciente atualizado com sucesso",
variant: "default"
});
router.push("/manager/pacientes");
} catch (err: any) {
console.error("Erro ao atualizar paciente:", err);
toast({
title: "Erro",
description: err?.message || "Não foi possível atualizar o paciente",
variant: "destructive"
});
}
};
return (
<Sidebar>
<div className="space-y-6 px-2 sm:px-4 pb-20">
{/* --- HEADER RESPONSIVO --- */}
<div className="flex flex-col xl:flex-row gap-6 xl:items-start xl:justify-between">
<div className="flex flex-col sm:flex-row sm:items-center gap-4">
<Link href="/manager/pacientes">
<Button variant="ghost" size="sm" className="-ml-2">
<ArrowLeft className="w-4 h-4 mr-2" />
Voltar
</Button>
</Link>
<div>
<h1 className="text-xl sm:text-2xl font-bold text-foreground">Editar Paciente</h1>
<p className="text-sm text-muted-foreground">Atualize as informações do paciente</p>
</div>
</div>
{/* Anexos Section */}
<div className="w-full xl:w-auto xl:min-w-[400px] bg-card rounded-lg border border-border p-4 sm:p-6">
<h2 className="text-lg font-semibold text-foreground mb-4 sm:mb-6">Anexos</h2>
<div className="flex items-center gap-3 mb-4">
<input ref={anexoInputRef} type="file" className="hidden" />
<Button type="button" variant="outline" size="sm" disabled={isUploadingAnexo} className="w-full sm:w-auto">
<Paperclip className="w-4 h-4 mr-2" /> {isUploadingAnexo ? "Enviando..." : "Adicionar anexo"}
</Button>
</div>
{anexos.length === 0 ? (
<p className="text-sm text-muted-foreground">Nenhum anexo encontrado.</p>
) : (
<ul className="divide-y divide-border">
{anexos.map((a) => (
<li key={a.id} className="flex items-center justify-between py-2">
<div className="flex items-center gap-2 min-w-0">
<Paperclip className="w-4 h-4 text-muted-foreground shrink-0" />
<span className="text-sm text-foreground truncate">{a.nome || a.filename || `Anexo ${a.id}`}</span>
</div>
<Button type="button" variant="ghost" size="sm" className="text-destructive">
<Trash2 className="w-4 h-4 mr-1" /> Remover
</Button>
</li>
))}
</ul>
)}
</div>
</div>
<form onSubmit={handleSubmit} className="space-y-6 sm:space-y-8">
{/* --- DADOS PESSOAIS --- */}
<div className="bg-card rounded-lg border border-border p-4 sm:p-6">
<h2 className="text-lg font-semibold text-foreground mb-4 sm:mb-6">Dados Pessoais</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6">
{/* Photo upload Responsivo */}
<div className="space-y-2 col-span-1 md:col-span-2 lg:col-span-3">
<Label>Foto do paciente</Label>
<div className="flex flex-col sm:flex-row items-start sm:items-center gap-4">
<div className="w-20 h-20 rounded-full bg-muted overflow-hidden flex items-center justify-center shrink-0 border">
{photoUrl ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={photoUrl} alt="Foto do paciente" className="w-full h-full object-cover" />
) : (
<span className="text-muted-foreground text-xs text-center px-2">Sem foto</span>
)}
</div>
<div className="flex flex-wrap gap-2 w-full">
<input ref={fileInputRef} type="file" accept="image/*" className="hidden" />
<Button type="button" variant="outline" size="sm" disabled={isUploadingPhoto} className="flex-1 sm:flex-none">
{isUploadingPhoto ? "Enviando..." : "Enviar foto"}
</Button>
{photoUrl && (
<Button type="button" variant="ghost" size="sm" disabled={isUploadingPhoto} className="flex-1 sm:flex-none">
Remover
</Button>
)}
</div>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="nome">Nome *</Label>
<Input id="nome" value={formData.nome} onChange={(e) => handleInputChange("nome", e.target.value)} required />
</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" 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 className="space-y-2">
<Label>Sexo *</Label>
<div className="flex flex-wrap gap-4 pt-2">
<div className="flex items-center space-x-2">
<input type="radio" id="Masculino" name="sexo" value="Masculino" checked={formData.sexo === "Masculino"} onChange={(e) => handleInputChange("sexo", e.target.value)} className="w-4 h-4 text-primary" />
<Label htmlFor="Masculino">Masculino</Label>
</div>
<div className="flex items-center space-x-2">
<input type="radio" id="Feminino" name="sexo" value="Feminino" checked={formData.sexo === "Feminino"} onChange={(e) => handleInputChange("sexo", e.target.value)} className="w-4 h-4 text-primary" />
<Label htmlFor="Feminino">Feminino</Label>
</div>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="dataNascimento">Data de nascimento *</Label>
<Input id="dataNascimento" type="date" value={formData.dataNascimento} onChange={(e) => handleInputChange("dataNascimento", e.target.value)} required />
</div>
{/* Demais campos de select e input */}
<div className="space-y-2">
<Label htmlFor="etnia">Etnia</Label>
<Select value={formData.ethnicity} onValueChange={(value) => handleInputChange("ethnicity", value)}>
<SelectTrigger><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 className="space-y-2">
<Label htmlFor="raca">Raça</Label>
<Select value={formData.race} onValueChange={(value) => handleInputChange("race", value)}>
<SelectTrigger><SelectValue placeholder="Selecione" /></SelectTrigger>
<SelectContent>
<SelectItem value="caucasiana">Caucasiana</SelectItem>
<SelectItem value="negroide">Negroide</SelectItem>
<SelectItem value="mongoloide">Mongoloide</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="naturalidade">Naturalidade</Label>
<Input id="naturalidade" value={formData.naturality} onChange={(e) => handleInputChange("naturality", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="nacionalidade">Nacionalidade</Label>
<Select value={formData.nationality} onValueChange={(value) => handleInputChange("nationality", value)}>
<SelectTrigger><SelectValue placeholder="Selecione" /></SelectTrigger>
<SelectContent>
<SelectItem value="brasileira">Brasileira</SelectItem>
<SelectItem value="estrangeira">Estrangeira</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="profissao">Profissão</Label>
<Input id="profissao" value={formData.profession} onChange={(e) => handleInputChange("profession", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="estadoCivil">Estado civil</Label>
<Select value={formData.maritalStatus} onValueChange={(value) => handleInputChange("maritalStatus", value)}>
<SelectTrigger><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 className="space-y-2">
<Label htmlFor="nomeMae">Nome da mãe</Label>
<Input id="nomeMae" value={formData.motherName} onChange={(e) => handleInputChange("motherName", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="profissaoMae">Profissão da mãe</Label>
<Input id="profissaoMae" value={formData.motherProfession} onChange={(e) => handleInputChange("motherProfession", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="nomePai">Nome do pai</Label>
<Input id="nomePai" value={formData.fatherName} onChange={(e) => handleInputChange("fatherName", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="profissaoPai">Profissão do pai</Label>
<Input id="profissaoPai" value={formData.fatherProfession} onChange={(e) => handleInputChange("fatherProfession", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="nomeResponsavel">Nome do responsável</Label>
<Input id="nomeResponsavel" value={formData.guardianName} onChange={(e) => handleInputChange("guardianName", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="cpfResponsavel">CPF do responsável</Label>
<Input id="cpfResponsavel" value={formData.guardianCpf} onChange={(e) => handleInputChange("guardianCpf", e.target.value)} placeholder="000.000.000-00" />
</div>
<div className="space-y-2">
<Label htmlFor="nomeEsposo">Nome do esposo(a)</Label>
<Input id="nomeEsposo" value={formData.spouseName} onChange={(e) => handleInputChange("spouseName", e.target.value)} />
</div>
</div>
<div className="mt-6">
<div className="flex items-center space-x-2">
<Checkbox id="guiaConvenio" checked={isGuiaConvenio} onCheckedChange={(checked) => setIsGuiaConvenio(checked === true)} />
<Label htmlFor="guiaConvenio">RN na Guia do convênio</Label>
</div>
</div>
<div className="mt-6">
<Label htmlFor="observacoes">Observações</Label>
<Textarea id="observacoes" value={formData.notes} onChange={(e) => handleInputChange("notes", e.target.value)} placeholder="Digite observações sobre o paciente..." className="mt-2" />
</div>
</div>
{/* --- CONTATO --- */}
<div className="bg-card rounded-lg border border-border p-4 sm:p-6">
<h2 className="text-lg font-semibold text-foreground mb-4 sm:mb-6">Contato</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6">
<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)} required/>
</div>
<div className="space-y-2">
<Label htmlFor="celular">Celular *</Label>
<Input id="celular" value={formData.phoneMobile} onChange={(e) => handleInputChange("phoneMobile", e.target.value)} placeholder="(00) 00000-0000" required/>
</div>
<div className="space-y-2">
<Label htmlFor="telefone1">Telefone 1</Label>
<Input id="telefone1" value={formData.phone1} onChange={(e) => handleInputChange("phone1", e.target.value)} placeholder="(00) 0000-0000" />
</div>
<div className="space-y-2">
<Label htmlFor="telefone2">Telefone 2</Label>
<Input id="telefone2" value={formData.phone2} onChange={(e) => handleInputChange("phone2", e.target.value)} placeholder="(00) 0000-0000" />
</div>
</div>
</div>
{/* --- ENDEREÇO --- */}
<div className="bg-card rounded-lg border border-border p-4 sm:p-6">
<h2 className="text-lg font-semibold text-foreground mb-4 sm:mb-6">Endereço</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6">
<div className="space-y-2">
<Label htmlFor="cep">CEP</Label>
<Input id="cep" value={formData.cep} onChange={(e) => handleInputChange("cep", e.target.value)} placeholder="00000-000" />
</div>
<div className="space-y-2 md:col-span-2 lg:col-span-2">
<Label htmlFor="endereco">Endereço</Label>
<Input id="endereco" value={formData.street} onChange={(e) => handleInputChange("street", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="numero">Número</Label>
<Input id="numero" value={formData.number} onChange={(e) => handleInputChange("number", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="complemento">Complemento</Label>
<Input id="complemento" value={formData.complement} onChange={(e) => handleInputChange("complement", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="bairro">Bairro</Label>
<Input id="bairro" value={formData.neighborhood} onChange={(e) => handleInputChange("neighborhood", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="cidade">Cidade</Label>
<Input id="cidade" value={formData.city} onChange={(e) => handleInputChange("city", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="estado">Estado</Label>
<Select value={formData.state} onValueChange={(value) => handleInputChange("state", value)}>
<SelectTrigger><SelectValue placeholder="Selecione" /></SelectTrigger>
<SelectContent>
<SelectItem value="AC">Acre</SelectItem>
<SelectItem value="AL">Alagoas</SelectItem>
<SelectItem value="AP">Amapá</SelectItem>
<SelectItem value="AM">Amazonas</SelectItem>
<SelectItem value="BA">Bahia</SelectItem>
<SelectItem value="CE">Ceará</SelectItem>
<SelectItem value="DF">Distrito Federal</SelectItem>
<SelectItem value="ES">Espírito Santo</SelectItem>
<SelectItem value="GO">Goiás</SelectItem>
<SelectItem value="MA">Maranhão</SelectItem>
<SelectItem value="MT">Mato Grosso</SelectItem>
<SelectItem value="MS">Mato Grosso do Sul</SelectItem>
<SelectItem value="MG">Minas Gerais</SelectItem>
<SelectItem value="PA">Pará</SelectItem>
<SelectItem value="PB">Paraíba</SelectItem>
<SelectItem value="PR">Paraná</SelectItem>
<SelectItem value="PE">Pernambuco</SelectItem>
<SelectItem value="PI">Piauí</SelectItem>
<SelectItem value="RJ">Rio de Janeiro</SelectItem>
<SelectItem value="RN">Rio Grande do Norte</SelectItem>
<SelectItem value="RS">Rio Grande do Sul</SelectItem>
<SelectItem value="RO">Rondônia</SelectItem>
<SelectItem value="RR">Roraima</SelectItem>
<SelectItem value="SC">Santa Catarina</SelectItem>
<SelectItem value="SP">São Paulo</SelectItem>
<SelectItem value="SE">Sergipe</SelectItem>
<SelectItem value="TO">Tocantins</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</div>
{/* --- INFORMAÇÕES MÉDICAS --- */}
<div className="bg-card rounded-lg border border-border p-4 sm:p-6">
<h2 className="text-lg font-semibold text-foreground mb-4 sm:mb-6">Informações Médicas</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6">
<div className="space-y-2">
<Label htmlFor="tipoSanguineo">Tipo Sanguíneo</Label>
<Select value={formData.bloodType} onValueChange={(value) => handleInputChange("bloodType", value)}>
<SelectTrigger><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 className="space-y-2">
<Label htmlFor="peso">Peso (kg)</Label>
<Input id="peso" type="number" value={formData.weightKg} onChange={(e) => handleInputChange("weightKg", e.target.value)} placeholder="0.0" />
</div>
<div className="space-y-2">
<Label htmlFor="altura">Altura (m)</Label>
<Input id="altura" type="number" step="0.01" value={formData.heightM} onChange={(e) => handleInputChange("heightM", e.target.value)} placeholder="0.00" />
</div>
<div className="space-y-2">
<Label>IMC</Label>
<Input value={formData.weightKg && formData.heightM ? (Number.parseFloat(formData.weightKg) / Number.parseFloat(formData.heightM) ** 2).toFixed(2) : ""} disabled placeholder="Calculado automaticamente" />
</div>
</div>
<div className="mt-6">
<Label htmlFor="alergias">Alergias</Label>
<Textarea id="alergias" onChange={(e) => handleInputChange("alergias", e.target.value)} placeholder="Ex: AAS, Dipirona, etc." className="mt-2" />
</div>
</div>
{/* --- CONVÊNIO --- */}
<div className="bg-card rounded-lg border border-border p-4 sm:p-6">
<h2 className="text-lg font-semibold text-foreground mb-4 sm:mb-6">Informações de convênio</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6">
<div className="space-y-2">
<Label htmlFor="convenio">Convênio</Label>
<Select onValueChange={(value) => handleInputChange("convenio", value)}>
<SelectTrigger><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>
<SelectItem value="Amil">Amil</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="plano">Plano</Label>
<Input id="plano" onChange={(e) => handleInputChange("plano", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="numeroMatricula"> de matrícula</Label>
<Input id="numeroMatricula" onChange={(e) => handleInputChange("numeroMatricula", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="validadeCarteira">Validade da Carteira</Label>
<Input id="validadeCarteira" type="date" onChange={(e) => handleInputChange("validadeCarteira", e.target.value)} disabled={validadeIndeterminada} />
</div>
</div>
<div className="mt-4">
<div className="flex items-center space-x-2">
<Checkbox id="validadeIndeterminada" checked={validadeIndeterminada} onCheckedChange={(checked) => setValidadeIndeterminada(checked === true)} />
<Label htmlFor="validadeIndeterminada">Validade Indeterminada</Label>
</div>
</div>
</div>
{/* --- BOTÕES DE AÇÃO --- */}
<div className="flex flex-col-reverse sm:flex-row justify-end gap-4 pt-4">
<Link href="/manager/pacientes" className="w-full sm:w-auto">
<Button type="button" variant="outline" className="w-full">
Cancelar
</Button>
</Link>
<Button type="submit" className="bg-primary hover:bg-primary/90 w-full sm:w-auto">
<Save className="w-4 h-4 mr-2" />
Salvar Alterações
</Button>
</div>
</form>
</div>
</Sidebar>
);
}

View File

@ -1,3 +0,0 @@
export default function Loading() {
return null
}

View File

@ -1,338 +0,0 @@
"use client";
import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Edit, Trash2, Eye, Calendar, Filter, Loader2, MoreVertical, Phone, MapPin, Activity, ChevronLeft, ChevronRight } from "lucide-react";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { patientsService } from "@/services/patientsApi.mjs";
import Sidebar from "@/components/Sidebar";
export default function PacientesPage() {
// --- ESTADOS ---
const [searchTerm, setSearchTerm] = useState("");
const [convenioFilter, setConvenioFilter] = useState("all");
const [vipFilter, setVipFilter] = useState("all");
const [allPatients, setAllPatients] = useState<any[]>([]);
const [filteredPatients, setFilteredPatients] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// --- PAGINAÇÃO ---
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const totalPages = Math.ceil(filteredPatients.length / pageSize);
const startIndex = (page - 1) * pageSize;
const endIndex = startIndex + pageSize;
const currentPatients = filteredPatients.slice(startIndex, endIndex);
// --- DIALOGS ---
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [patientToDelete, setPatientToDelete] = useState<string | null>(null);
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
const [patientDetails, setPatientDetails] = useState<any | null>(null);
// --- LÓGICA DE NÚMEROS DA PAGINAÇÃO (LIMITADO A 3) ---
const getPageNumbers = () => {
const maxVisible = 3;
if (totalPages <= maxVisible) {
return Array.from({ length: totalPages }, (_, i) => i + 1);
}
let start = Math.max(1, page - 1);
let end = Math.min(totalPages, start + maxVisible - 1);
if (end === totalPages) {
start = Math.max(1, end - maxVisible + 1);
}
const pages = [];
for (let i = start; i <= end; i++) {
pages.push(i);
}
return pages;
};
// --- FETCH DADOS ---
const fetchAllPacientes = useCallback(async () => {
setLoading(true);
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?.split('T')[0] ?? "—",
proximoAtendimento: p.next_appointment_at?.split('T')[0] ?? "—",
vip: Boolean(p.vip ?? false),
convenio: p.convenio ?? "Particular",
status: p.status ?? undefined,
}));
setAllPatients(mapped);
} catch (e: any) {
console.error(e);
setError(e?.message || "Erro ao buscar pacientes");
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
const filtered = allPatients.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;
});
setFilteredPatients(filtered);
setPage(1);
}, [allPatients, searchTerm, convenioFilter, vipFilter]);
useEffect(() => {
fetchAllPacientes();
}, []);
// --- AÇÕES ---
const openDetailsDialog = async (patientId: string) => {
setDetailsDialogOpen(true);
setPatientDetails(null);
try {
const res = await patientsService.getById(patientId);
setPatientDetails(Array.isArray(res) ? res[0] : res);
} catch (e: any) {
setPatientDetails({ error: e?.message || "Erro ao buscar detalhes" });
}
};
const handleDeletePatient = async (patientId: string) => {
try {
await patientsService.delete(patientId);
setAllPatients((prev) => prev.filter((p) => String(p.id) !== String(patientId)));
} catch (e: any) {
alert(`Erro ao deletar paciente: ${e?.message || "Erro desconhecido"}`);
}
setDeleteDialogOpen(false);
setPatientToDelete(null);
};
const ActionMenu = ({ patientId }: { patientId: string }) => (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<div className="cursor-pointer p-2 hover:bg-muted rounded-full">
<MoreVertical className="h-4 w-4" />
</div>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => openDetailsDialog(String(patientId))}>
<Eye className="w-4 h-4 mr-2" /> Ver detalhes
</DropdownMenuItem>
<DropdownMenuItem asChild>
<Link href={`/manager/pacientes/${patientId}/editar`} className="flex items-center w-full">
<Edit className="w-4 h-4 mr-2" /> Editar
</Link>
</DropdownMenuItem>
<DropdownMenuItem>
<Calendar className="w-4 h-4 mr-2" /> Marcar consulta
</DropdownMenuItem>
<DropdownMenuItem className="text-destructive" onClick={() => { setPatientToDelete(patientId); setDeleteDialogOpen(true); }}>
<Trash2 className="w-4 h-4 mr-2" /> Excluir
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
return (
<Sidebar>
<div className="space-y-6 px-2 sm:px-4 md:px-8 pb-20">
{/* Header */}
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
<div>
<h1 className="text-xl md:text-2xl font-bold">Pacientes</h1>
<p className="text-muted-foreground text-sm md:text-base">Gerencie as informações de seus pacientes</p>
</div>
</div>
{/* Filtros */}
<div className="flex flex-wrap items-center gap-4 bg-card p-4 rounded-lg border">
<Filter className="w-5 h-5 text-muted-foreground" />
<input type="text" placeholder="Buscar por nome ou telefone..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} className="w-full sm:flex-grow sm:max-w-[300px] p-2 border rounded-md text-sm" />
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[200px]">
<span className="text-sm font-medium whitespace-nowrap hidden md:block">Convênio</span>
<Select value={convenioFilter} onValueChange={setConvenioFilter}>
<SelectTrigger className="w-full sm:w-40"><SelectValue placeholder="Convênio" /></SelectTrigger>
<SelectContent><SelectItem value="all">Todos</SelectItem><SelectItem value="Particular">Particular</SelectItem><SelectItem value="SUS">SUS</SelectItem><SelectItem value="Unimed">Unimed</SelectItem></SelectContent>
</Select>
</div>
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[150px]">
<span className="text-sm font-medium whitespace-nowrap hidden md:block">VIP</span>
<Select value={vipFilter} onValueChange={setVipFilter}>
<SelectTrigger className="w-full sm:w-32"><SelectValue placeholder="VIP" /></SelectTrigger>
<SelectContent><SelectItem value="all">Todos</SelectItem><SelectItem value="vip">VIP</SelectItem><SelectItem value="regular">Regular</SelectItem></SelectContent>
</Select>
</div>
<div className="flex items-center gap-2 w-full sm:w-auto ml-auto sm:ml-0">
<Select value={String(pageSize)} onValueChange={(value) => { setPageSize(Number(value)); setPage(1); }}>
<SelectTrigger className="w-full sm:w-[70px]"><SelectValue placeholder="10" /></SelectTrigger>
<SelectContent><SelectItem value="5">5</SelectItem><SelectItem value="10">10</SelectItem><SelectItem value="20">20</SelectItem></SelectContent>
</Select>
</div>
</div>
{/* Loading / Erro / Conteúdo */}
{error ? (
<div className="p-6 text-destructive bg-card border rounded-lg">{`Erro: ${error}`}</div>
) : loading ? (
<div className="p-6 text-center text-muted-foreground flex items-center justify-center bg-card border rounded-lg"><Loader2 className="w-6 h-6 mr-2 animate-spin text-primary" /> Carregando...</div>
) : (
<>
{/* LISTA MOBILE */}
<div className="grid grid-cols-1 gap-4 md:hidden">
{currentPatients.length === 0 ? (
<div className="p-8 text-center text-muted-foreground bg-card rounded-lg border">Nenhum paciente encontrado.</div>
) : (
currentPatients.map((patient) => (
<div key={patient.id} className="bg-card p-4 rounded-lg border shadow-sm flex flex-col gap-3 relative">
<div className="flex justify-between items-start">
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-primary/10 rounded-full flex items-center justify-center"><span className="text-primary font-bold text-sm">{patient.nome?.charAt(0) || "?"}</span></div>
<div>
<div className="font-semibold flex items-center gap-2">{patient.nome}{patient.vip && <span className="px-1.5 py-0.5 text-[10px] font-bold rounded-full text-purple-600 bg-purple-100 uppercase">VIP</span>}</div>
<div className="text-xs text-muted-foreground">{patient.convenio}</div>
</div>
</div>
<ActionMenu patientId={String(patient.id)} />
</div>
<div className="grid grid-cols-2 gap-2 text-sm text-muted-foreground mt-2 pt-2 border-t">
<div className="flex items-center gap-2"><Phone className="w-3 h-3" /> {patient.telefone}</div>
<div className="flex items-center gap-2"><MapPin className="w-3 h-3" /> {patient.cidade}</div>
<div className="flex items-center gap-2 col-span-2"><Activity className="w-3 h-3" /> Última: {patient.ultimoAtendimento}</div>
</div>
</div>
))
)}
</div>
{/* TABELA DESKTOP */}
<div className="bg-card rounded-lg border shadow-md hidden md:block">
<div className="overflow-x-auto">
<table className="w-full min-w-[650px]">
<thead className="bg-muted border-b">
<tr>
<th className="text-left p-4 font-medium text-muted-foreground w-[20%]">Nome</th>
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden sm:table-cell">Telefone</th>
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden md:table-cell">Cidade / Estado</th>
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden sm:table-cell">Convênio</th>
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden lg:table-cell">Último atendimento</th>
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden lg:table-cell">Próximo atendimento</th>
<th className="text-left p-4 font-medium text-muted-foreground w-[5%]">Ações</th>
</tr>
</thead>
<tbody>
{currentPatients.length === 0 ? (
<tr><td colSpan={7} className="p-8 text-center text-muted-foreground">Nenhum paciente encontrado</td></tr>
) : (
currentPatients.map((patient) => (
<tr key={patient.id} className="border-b hover:bg-muted">
<td className="p-4">
<div className="flex items-center gap-3">
<div className="w-8 h-8 bg-primary/10 rounded-full flex items-center justify-center"><span className="text-primary font-medium text-sm">{patient.nome?.charAt(0) || "?"}</span></div>
<span className="font-medium">{patient.nome}{patient.vip && <span className="ml-2 px-2 py-0.5 text-xs font-semibold rounded-full text-purple-400 bg-purple-400/15">VIP</span>}</span>
</div>
</td>
<td className="p-4 text-muted-foreground hidden sm:table-cell">{patient.telefone}</td>
<td className="p-4 text-muted-foreground hidden md:table-cell">{`${patient.cidade} / ${patient.estado}`}</td>
<td className="p-4 text-muted-foreground hidden sm:table-cell">{patient.convenio}</td>
<td className="p-4 text-muted-foreground hidden lg:table-cell">{patient.ultimoAtendimento}</td>
<td className="p-4 text-muted-foreground hidden lg:table-cell">{patient.proximoAtendimento}</td>
<td className="p-4"><ActionMenu patientId={String(patient.id)} /></td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
</>
)}
{/* --- RODAPÉ DE PAGINAÇÃO --- */}
{totalPages > 1 && !loading && (
<div className="py-4 px-2 border-t border-border">
{/* 1. PAGINAÇÃO MOBILE (Simples) */}
<div className="flex items-center justify-between md:hidden gap-2">
<Button onClick={() => setPage((prev) => Math.max(1, prev - 1))} disabled={page === 1} variant="outline" size="sm" className="min-w-[90px]">
<ChevronLeft className="w-4 h-4 mr-1" /> Anterior
</Button>
<span className="text-sm font-medium text-muted-foreground">{page} de {totalPages}</span>
<Button onClick={() => setPage((prev) => Math.min(totalPages, prev + 1))} disabled={page === totalPages} variant="outline" size="sm" className="min-w-[90px]">
Próximo <ChevronRight className="w-4 h-4 ml-1" />
</Button>
</div>
{/* 2. PAGINAÇÃO DESKTOP (Numerada Limitada) */}
<div className="hidden md:flex items-center justify-center gap-2">
<Button onClick={() => setPage((prev) => Math.max(1, prev - 1))} disabled={page === 1} variant="outline" className="px-4">
&lt; Anterior
</Button>
{getPageNumbers().map((pageNum) => (
<Button
key={pageNum}
onClick={() => setPage(pageNum)}
/* CORREÇÃO AQUI: Removemos as classes manuais e usamos apenas o variant */
variant={pageNum === page ? "default" : "outline"}
className="w-10 h-10 p-0"
>
{pageNum}
</Button>
))}
<Button onClick={() => setPage((prev) => Math.min(totalPages, prev + 1))} disabled={page === totalPages} variant="outline" className="px-4">
Próximo &gt;
</Button>
</div>
</div>
)}
{/* Dialogs */}
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader><AlertDialogTitle>Confirmar exclusão</AlertDialogTitle><AlertDialogDescription>Tem certeza que deseja excluir este paciente?</AlertDialogDescription></AlertDialogHeader>
<AlertDialogFooter><AlertDialogCancel>Cancelar</AlertDialogCancel><AlertDialogAction onClick={() => patientToDelete && handleDeletePatient(patientToDelete)} className="bg-destructive hover:bg-destructive/90">Excluir</AlertDialogAction></AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
<AlertDialogContent className="max-h-[90vh] overflow-y-auto">
<AlertDialogHeader><AlertDialogTitle>Detalhes do Paciente</AlertDialogTitle></AlertDialogHeader>
<AlertDialogDescription>
{patientDetails ? (!patientDetails.error ? (
<div className="grid gap-4 py-4 text-left">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div><p className="font-semibold text-xs text-muted-foreground">NOME</p><p>{patientDetails.full_name}</p></div>
<div><p className="font-semibold text-xs text-muted-foreground">EMAIL</p><p className="break-all">{patientDetails.email}</p></div>
<div><p className="font-semibold text-xs text-muted-foreground">TELEFONE</p><p>{patientDetails.phone_mobile}</p></div>
<div><p className="font-semibold text-xs text-muted-foreground">DATA NASC.</p><p>{patientDetails.birth_date}</p></div>
</div>
<div className="border-t pt-4"><p className="font-semibold text-primary mb-2">Endereço</p><p>{patientDetails.street}, {patientDetails.number}</p><p>{patientDetails.cidade}/{patientDetails.estado}</p></div>
</div>
) : <p className="text-destructive">{patientDetails.error}</p>) : <Loader2 className="w-6 h-6 animate-spin mx-auto text-primary" />}
</AlertDialogDescription>
<AlertDialogFooter><AlertDialogCancel>Fechar</AlertDialogCancel></AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</Sidebar>
);
}

View File

@ -1,279 +0,0 @@
"use client"
import { useState, useEffect } from "react"
import { useRouter, useParams } 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Save, Loader2, ArrowLeft } from "lucide-react"
import Sidebar from "@/components/Sidebar"
// Mock user service for demonstration. Replace with your actual API service.
const usersService = {
getById: async (id: string): Promise<any> => {
console.log(`API Call: Fetching user with ID ${id}`);
await new Promise(resolve => setTimeout(resolve, 500));
// This mock finds a user from a predefined list.
const mockUsers = [
{ id: 1, full_name: 'Alice Admin', email: 'alice.admin@example.com', phone: '(11) 98765-4321', role: 'admin' },
{ id: 2, full_name: 'Bruno Gestor', email: 'bruno.g@example.com', phone: '(21) 91234-5678', role: 'gestor' },
{ id: 3, full_name: 'Dr. Carlos Médico', email: 'carlos.med@example.com', phone: null, role: 'medico' },
{ id: 4, full_name: 'Daniela Secretaria', email: 'daniela.sec@example.com', phone: '(31) 99999-8888', role: 'secretaria' },
{ id: 5, full_name: 'Eduardo Usuário', email: 'edu.user@example.com', phone: '(41) 98888-7777', role: 'user' },
];
const user = mockUsers.find(u => u.id.toString() === id);
if (!user) throw new Error("Usuário não encontrado.");
return user;
},
update: async (id: string, payload: any): Promise<void> => {
console.log(`API Call: Updating user ${id} with payload:`, payload);
await new Promise(resolve => setTimeout(resolve, 1000));
// To simulate an error (e.g., duplicate email), you could throw an error here:
// if (payload.email === 'bruno.g@example.com') throw new Error("Este e-mail já está em uso por outro usuário.");
}
};
// Interface for the user form data
interface UserFormData {
nomeCompleto: string;
email: string;
telefone: string;
papel: string;
password?: string; // Optional for password updates
}
// Default state for the form
const defaultFormData: UserFormData = {
nomeCompleto: '',
email: '',
telefone: '',
papel: '',
password: '',
};
// Helper functions for phone formatting
const cleanNumber = (value: string): string => value.replace(/\D/g, '');
const formatPhone = (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 EditarUsuarioPage() {
const router = useRouter();
const params = useParams();
const id = Array.isArray(params.id) ? params.id[0] : params.id;
const [formData, setFormData] = useState<UserFormData>(defaultFormData);
const [loading, setLoading] = useState(true);
const [isSaving, setIsSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
// Map API field names to our form field names
const apiToFormMap: { [key: string]: keyof UserFormData } = {
'full_name': 'nomeCompleto',
'email': 'email',
'phone': 'telefone',
'role': 'papel'
};
// Fetch user data when the component mounts
useEffect(() => {
if (!id) return;
const fetchUser = async () => {
try {
const data = await usersService.getById(id);
if (!data) {
setError("Usuário não encontrado.");
setLoading(false);
return;
}
const initialData: Partial<UserFormData> = {};
Object.keys(data).forEach(key => {
const formKey = apiToFormMap[key];
if (formKey) {
initialData[formKey] = data[key] === null ? '' : String(data[key]);
}
});
setFormData(prev => ({ ...prev, ...initialData }));
} catch (e: any) {
console.error("Erro ao carregar dados do usuário:", e);
setError(e.message || "Não foi possível carregar os dados do usuário.");
} finally {
setLoading(false);
}
};
fetchUser();
}, [id]);
const handleInputChange = (key: keyof UserFormData, value: string) => {
const updatedValue = key === 'telefone' ? formatPhone(value) : value;
setFormData((prev) => ({ ...prev, [key]: updatedValue }));
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setIsSaving(true);
if (!id) {
setError("ID do usuário ausente.");
setIsSaving(false);
return;
}
// Prepare payload for the API
const payload: { [key: string]: any } = {
full_name: formData.nomeCompleto,
email: formData.email,
phone: formData.telefone.trim() || null,
role: formData.papel,
};
// Only include the password in the payload if it has been changed
if (formData.password && formData.password.trim() !== '') {
payload.password = formData.password;
}
try {
await usersService.update(id, payload);
router.push("/manager/usuario");
} catch (e: any) {
console.error("Erro ao salvar o usuário:", e);
setError(e.message || "Ocorreu um erro inesperado ao atualizar.");
} finally {
setIsSaving(false);
}
};
if (loading) {
return (
<Sidebar>
<div className="flex justify-center items-center h-full w-full py-16">
<Loader2 className="w-8 h-8 animate-spin text-primary" />
<p className="ml-2 text-muted-foreground">Carregando dados do usuário...</p>
</div>
</Sidebar>
);
}
return (
<Sidebar>
<div className="w-full max-w-2xl mx-auto space-y-6 p-4 md:p-8">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-foreground">
Editar Usuário: <span className="text-primary">{formData.nomeCompleto}</span>
</h1>
<p className="text-sm text-muted-foreground">
Atualize as informações do usuário (ID: {id}).
</p>
</div>
<Link href="/manager/usuario">
<Button variant="outline">
<ArrowLeft className="w-4 h-4 mr-2" />
Voltar
</Button>
</Link>
</div>
<form onSubmit={handleSubmit} className="space-y-8 bg-card p-8 border border-border rounded-lg shadow-sm">
{error && (
<div className="p-3 rounded-lg border bg-destructive/10 text-destructive border-destructive/30">
<p className="font-medium">Erro na Atualização:</p>
<p className="text-sm">{error}</p>
</div>
)}
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="nomeCompleto">Nome Completo</Label>
<Input
id="nomeCompleto"
value={formData.nomeCompleto}
onChange={(e) => handleInputChange("nomeCompleto", e.target.value)}
/>
</div>
<div className="grid md:grid-cols-2 gap-4">
<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)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="password">Nova Senha</Label>
<Input
id="password"
type="password"
value={formData.password}
onChange={(e) => handleInputChange("password", e.target.value)}
placeholder="Deixe em branco para não alterar"
/>
</div>
</div>
<div className="grid md:grid-cols-2 gap-4">
<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 className="space-y-2">
<Label htmlFor="papel">Papel (Função)</Label>
<Select value={formData.papel} onValueChange={(v) => handleInputChange("papel", v)}>
<SelectTrigger id="papel">
<SelectValue placeholder="Selecione uma função" />
</SelectTrigger>
<SelectContent>
<SelectItem value="admin">Admin</SelectItem>
<SelectItem value="gestor">Gestor</SelectItem>
<SelectItem value="medico">Médico</SelectItem>
<SelectItem value="secretaria">Secretaria</SelectItem>
<SelectItem value="user">Usuário</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</div>
<div className="flex justify-end gap-4 pt-4">
<Link href="/manager/usuario">
<Button type="button" variant="outline" disabled={isSaving}>
Cancelar
</Button>
</Link>
<Button
type="submit"
className="bg-primary hover:bg-primary/90"
disabled={isSaving}
>
{isSaving ? (
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
) : (
<Save className="w-4 h-4 mr-2" />
)}
{isSaving ? "Salvando..." : "Salvar Alterações"}
</Button>
</div>
</form>
</div>
</Sidebar>
);
}

View File

@ -1,241 +0,0 @@
// ARQUIVO COMPLETO PARA: app/manager/usuario/novo/page.tsx
"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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Save, Loader2 } from "lucide-react";
import { usersService } from "@/services/usersApi.mjs";
import { doctorsService } from "@/services/doctorsApi.mjs";
import { login } from "services/api.mjs";
import { isValidCPF } from "@/lib/utils"; // 1. IMPORTAÇÃO DA FUNÇÃO DE VALIDAÇÃO
import Sidebar from "@/components/Sidebar";
interface UserFormData {
email: string;
nomeCompleto: string;
telefone: string;
papel: string;
senha: string;
confirmarSenha: string;
cpf: string;
crm: string;
crm_uf: string;
specialty: string;
}
const defaultFormData: UserFormData = {
email: "",
nomeCompleto: "",
telefone: "",
papel: "",
senha: "",
confirmarSenha: "",
cpf: "",
crm: "",
crm_uf: "",
specialty: "",
};
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 [formData, setFormData] = useState<UserFormData>(defaultFormData);
const [isSaving, setIsSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleInputChange = (key: keyof UserFormData, value: string) => {
let updatedValue = value;
if (key === "telefone") {
updatedValue = formatPhone(value);
} else if (key === "crm_uf") {
updatedValue = value.toUpperCase();
}
setFormData((prev) => ({ ...prev, [key]: updatedValue }));
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
if (!formData.email || !formData.nomeCompleto || !formData.papel || !formData.senha || !formData.confirmarSenha || !formData.cpf) {
setError("Por favor, preencha todos os campos obrigatórios.");
return;
}
if (formData.senha !== formData.confirmarSenha) {
setError("A Senha e a Confirmação de Senha não coincidem.");
return;
}
// 2. VALIDAÇÃO DO CPF ANTES DO ENVIO
if (!isValidCPF(formData.cpf)) {
setError("O CPF informado é inválido. Por favor, verifique os dígitos.");
return;
}
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);
try {
if (formData.papel === "medico") {
const doctorPayload = {
email: formData.email.trim().toLowerCase(),
full_name: formData.nomeCompleto,
cpf: formData.cpf,
crm: formData.crm,
crm_uf: formData.crm_uf,
specialty: formData.specialty || null,
phone_mobile: formData.telefone || null,
};
await doctorsService.create(doctorPayload);
} else {
const isPatient = formData.papel === "paciente";
const userPayload = {
email: formData.email.trim().toLowerCase(),
password: formData.senha,
full_name: formData.nomeCompleto,
phone: formData.telefone || null,
roles: [formData.papel, "paciente"],
cpf: formData.cpf,
create_patient_record: isPatient,
phone_mobile: isPatient ? formData.telefone || null : undefined,
};
await usersService.create_user(userPayload);
}
router.push("/manager/usuario");
} catch (e: any) {
console.error("Erro ao criar usuário:", e);
// 3. MENSAGEM DE ERRO MELHORADA
const detail = e.message?.split('detail:"')[1]?.split('"')[0] || e.message;
setError(detail.replace(/\\/g, "") || "Não foi possível criar o usuário. Verifique os dados e tente novamente.");
} finally {
setIsSaving(false);
}
};
const isMedico = formData.papel === "medico";
return (
<Sidebar>
<div className="w-full h-full p-4 md:p-8 flex justify-center items-start">
<div className="w-full max-w-screen-lg space-y-8">
<div className="flex items-center justify-between border-b pb-4">
<div>
<h1 className="text-3xl font-extrabold">Novo Usuário</h1>
<p className="text-md text-muted-foreground">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-card p-6 md:p-10 border rounded-xl shadow-lg">
{error && (
<div className="p-4 bg-destructive/10 text-destructive rounded-lg border border-destructive">
<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>
<div className="space-y-2">
<Label htmlFor="papel">Papel (Função) *</Label>
<Select value={formData.papel} onValueChange={(v) => handleInputChange("papel", v)} required>
<SelectTrigger id="papel">
<SelectValue placeholder="Selecione uma função" />
</SelectTrigger>
<SelectContent>
<SelectItem value="admin">Administrador</SelectItem>
<SelectItem value="gestor">Gestor</SelectItem>
<SelectItem value="medico">Médico</SelectItem>
<SelectItem value="secretaria">Secretária</SelectItem>
<SelectItem value="paciente">Usuário</SelectItem>
</SelectContent>
</Select>
</div>
{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>
</>
)}
<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-destructive">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 className="space-y-2">
<Label htmlFor="cpf">Cpf *</Label>
<Input id="cpf" value={formData.cpf} onChange={(e) => handleInputChange("cpf", e.target.value)} placeholder="Apenas números" required />
</div>
<div className="flex justify-end gap-4 pt-6 border-t mt-6">
<Link href="/manager/usuario">
<Button type="button" variant="outline" disabled={isSaving}>
Cancelar
</Button>
</Link>
<Button type="submit" className="bg-primary hover:bg-primary/90" disabled={isSaving}>
{isSaving ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Save className="w-4 h-4 mr-2" />}
{isSaving ? "Salvando..." : "Salvar Usuário"}
</Button>
</div>
</form>
</div>
</div>
</Sidebar>
);
}

View File

@ -1,462 +0,0 @@
"use client";
import React, { useEffect, useState, useCallback } from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Input } from "@/components/ui/input"; // <--- 1. Importação Adicionada
import { Plus, Eye, Filter, Loader2, Search } from "lucide-react"; // <--- 1. Ícone Search Adicionado
import { AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { api, login } from "services/api.mjs";
import { usersService } from "services/usersApi.mjs";
import Sidebar from "@/components/Sidebar";
interface FlatUser {
id: string;
user_id: string;
full_name?: string;
email: string;
phone?: string | null;
role: string;
}
interface UserInfoResponse {
user: any;
profile: any;
roles: string[];
permissions: Record<string, boolean>;
}
export default function UsersPage() {
const [users, setUsers] = useState<FlatUser[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
const [userDetails, setUserDetails] = useState<UserInfoResponse | null>(null);
// --- Estados de Filtro ---
const [searchTerm, setSearchTerm] = useState(""); // <--- 2. Estado da busca
const [selectedRole, setSelectedRole] = useState<string>("all");
// --- Lógica de Paginação INÍCIO ---
const [itemsPerPage, setItemsPerPage] = useState(10);
const [currentPage, setCurrentPage] = useState(1);
const handleItemsPerPageChange = (value: string) => {
setItemsPerPage(Number(value));
setCurrentPage(1);
};
// --- Lógica de Paginação FIM ---
const fetchUsers = useCallback(async () => {
setLoading(true);
setError(null);
try {
const rolesData: any[] = await usersService.list_roles();
const rolesArray = Array.isArray(rolesData) ? rolesData : [];
const profilesData: any[] = await api.get(
`/rest/v1/profiles?select=id,full_name,email,phone`
);
const profilesById = new Map<string, any>();
if (Array.isArray(profilesData)) {
for (const p of profilesData) {
if (p?.id) profilesById.set(p.id, p);
}
}
const mapped: FlatUser[] = rolesArray.map((roleItem) => {
const uid = roleItem.user_id;
const profile = profilesById.get(uid);
return {
id: uid,
user_id: uid,
full_name: profile?.full_name ?? "—",
email: profile?.email ?? "—",
phone: profile?.phone ?? "—",
role: roleItem.role ?? "—",
};
});
setUsers(mapped);
setCurrentPage(1);
} catch (err: any) {
console.error("Erro ao buscar usuários:", err);
setError("Não foi possível carregar os usuários. Veja console.");
setUsers([]);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
const init = async () => {
try {
await login();
} catch (e) {
console.warn("login falhou no init:", e);
}
await fetchUsers();
};
init();
}, [fetchUsers]);
const openDetailsDialog = async (flatUser: FlatUser) => {
setDetailsDialogOpen(true);
setUserDetails(null);
try {
const data = await usersService.full_data(flatUser.user_id);
setUserDetails(data);
} catch (err: any) {
console.error("Erro ao carregar detalhes:", err);
setUserDetails({
user: { id: flatUser.user_id, email: flatUser.email },
profile: { full_name: flatUser.full_name, phone: flatUser.phone },
roles: [flatUser.role],
permissions: {},
});
}
};
// --- 3. Lógica de Filtragem Atualizada ---
const filteredUsers = users.filter((u) => {
// Filtro por Papel (Role)
const roleMatch = selectedRole === "all" || u.role === selectedRole;
// Filtro da Barra de Pesquisa (Nome, Email ou Telefone)
const searchLower = searchTerm.toLowerCase();
const nameMatch = u.full_name?.toLowerCase().includes(searchLower);
const emailMatch = u.email?.toLowerCase().includes(searchLower);
const phoneMatch = u.phone?.includes(searchLower);
const searchMatch = !searchTerm || nameMatch || emailMatch || phoneMatch;
return roleMatch && searchMatch;
});
const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = filteredUsers.slice(indexOfFirstItem, indexOfLastItem);
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
const totalPages = Math.ceil(filteredUsers.length / itemsPerPage);
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);
return (
<Sidebar>
<div className="space-y-6 px-2 sm:px-4 md:px-8">
{/* Header */}
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 className="text-2xl font-bold">Usuários</h1>
<p className="text-sm text-muted-foreground">Gerencie usuários.</p>
</div>
<Link href="/manager/usuario/novo" className="w-full sm:w-auto">
<Button className="w-full sm:w-auto">
<Plus className="w-4 h-4 mr-2" /> Novo Usuário
</Button>
</Link>
</div>
{/* --- 4. Filtro (Barra de Pesquisa + Selects) --- */}
<div className="flex flex-col md:flex-row items-start md:items-center gap-3 bg-card p-4 rounded-lg border">
{/* Barra de Pesquisa */}
<div className="relative w-full md:flex-1">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Buscar por nome, e-mail ou telefone..."
value={searchTerm}
onChange={(e) => {
setSearchTerm(e.target.value);
setCurrentPage(1); // Reseta a paginação ao pesquisar
}}
className="pl-10 w-full bg-muted border-border focus:bg-card transition-colors"
/>
</div>
<div className="flex flex-wrap items-center gap-3 w-full md:w-auto">
{/* Select de Filtro por Papel */}
<div className="flex items-center gap-2 w-full md:w-auto">
<Select
onValueChange={(value) => {
setSelectedRole(value);
setCurrentPage(1);
}}
value={selectedRole}>
<SelectTrigger className="w-full sm:w-[150px]">
<SelectValue placeholder="Papel" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Todos</SelectItem>
<SelectItem value="admin">Admin</SelectItem>
<SelectItem value="gestor">Gestor</SelectItem>
<SelectItem value="medico">Médico</SelectItem>
<SelectItem value="secretaria">Secretária</SelectItem>
<SelectItem value="user">Usuário</SelectItem>
</SelectContent>
</Select>
</div>
{/* Select de Itens por Página */}
<div className="flex items-center gap-2 w-full md:w-auto">
<Select
onValueChange={handleItemsPerPageChange}
defaultValue={String(itemsPerPage)}
>
<SelectTrigger className="w-full sm:w-[80px]">
<SelectValue placeholder="10" />
</SelectTrigger>
<SelectContent>
<SelectItem value="5">5</SelectItem>
<SelectItem value="10">10</SelectItem>
<SelectItem value="20">20</SelectItem>
</SelectContent>
</Select>
</div>
<Button variant="outline" className="ml-auto w-full md:w-auto hidden lg:flex">
<Filter className="w-4 h-4 mr-2" />
Filtros
</Button>
</div>
</div>
{/* Fim do Filtro */}
{/* Tabela/Lista */}
<div className="bg-card rounded-lg border shadow-md overflow-x-auto">
{loading ? (
<div className="p-8 text-center text-muted-foreground">
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-primary" />
Carregando usuários...
</div>
) : error ? (
<div className="p-8 text-center text-destructive">{error}</div>
) : filteredUsers.length === 0 ? (
<div className="p-8 text-center text-muted-foreground">
Nenhum usuário encontrado com os filtros aplicados.
</div>
) : (
<>
{/* Tabela para Telas Médias e Grandes */}
<table className="min-w-full divide-y hidden md:table">
<thead className="bg-muted">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
Nome
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
E-mail
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
Telefone
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
Cargo
</th>
<th className="px-6 py-3 text-right text-xs font-medium text-muted-foreground uppercase">
Ações
</th>
</tr>
</thead>
<tbody className="bg-card divide-y">
{currentItems.map((u) => (
<tr key={u.id} className="hover:bg-muted">
<td className="px-6 py-4 text-sm">
{u.full_name}
</td>
<td className="px-6 py-4 text-sm text-muted-foreground break-all">
{u.email}
</td>
<td className="px-6 py-4 text-sm text-muted-foreground">
{u.phone}
</td>
<td className="px-6 py-4 text-sm text-muted-foreground capitalize">
{u.role}
</td>
<td className="px-6 py-4 text-right">
<Button
variant="outline"
size="icon"
onClick={() => openDetailsDialog(u)}
title="Visualizar"
>
<Eye className="h-4 w-4" />
</Button>
</td>
</tr>
))}
</tbody>
</table>
{/* Layout em Cards/Lista para Telas Pequenas */}
<div className="md:hidden divide-y">
{currentItems.map((u) => (
<div key={u.id} className="flex items-center justify-between p-4 hover:bg-muted">
<div className="flex-1 min-w-0">
<div className="text-sm font-medium truncate">
{u.full_name || "—"}
</div>
<div className="text-xs text-muted-foreground truncate">
{u.email}
</div>
<div className="text-sm text-muted-foreground capitalize mt-1">
{u.role || "—"}
</div>
</div>
<div className="ml-4 flex-shrink-0">
<Button
variant="outline"
size="icon"
onClick={() => openDetailsDialog(u)}
title="Visualizar"
>
<Eye className="h-4 w-4" />
</Button>
</div>
</div>
))}
</div>
{/* Paginação */}
{totalPages > 1 && (
<div className="flex flex-wrap justify-center items-center gap-2 mt-4 p-4 border-t">
{/* 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-muted text-muted-foreground hover:bg-muted/90 disabled:opacity-50 disabled:cursor-not-allowed border"
>
{"< 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 ${
currentPage === number
? "bg-primary text-primary-foreground shadow-md border-primary"
: "bg-muted text-muted-foreground hover:bg-muted/90"
}`}
>
{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-muted text-muted-foreground hover:bg-muted/90 disabled:opacity-50 disabled:cursor-not-allowed border"
>
{"Próximo >"}
</button>
</div>
)}
</>
)}
</div>
{/* Modal de Detalhes */}
<AlertDialog
open={detailsDialogOpen}
onOpenChange={setDetailsDialogOpen}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="text-2xl">
{userDetails?.profile?.full_name || "Detalhes do Usuário"}
</AlertDialogTitle>
<AlertDialogDescription>
{!userDetails ? (
<div className="p-4 text-center text-muted-foreground">
<Loader2 className="w-6 h-6 animate-spin mx-auto mb-3 text-primary" />
Buscando dados completos...
</div>
) : (
<div className="space-y-3 pt-2 text-left text-muted-foreground">
<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 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-primary" : "text-destructive"
}`}
>
{v ? "Sim" : "Não"}
</span>
</li>
)
)}
</ul>
</div>
</div>
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Fechar</AlertDialogCancel>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</Sidebar>
);
}

View File

@ -1,215 +0,0 @@
"use client";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { useState } from "react";
import { Stethoscope, Baby, Microscope } from "lucide-react";
import { useAccessibility } from "./context/AccessibilityContext";
export default function InicialPage() {
const [isMenuOpen, setIsMenuOpen] = useState(false);
const { contrast } = useAccessibility();
const heroClass = contrast === "high"
? "px-6 md:px-10 lg:px-20 py-20 bg-background text-foreground border-y-2 border-primary"
: "px-6 md:px-10 lg:px-20 py-20 bg-gradient-to-r from-[#1E2A78] via-[#007BFF] to-[#00BFFF] text-white";
return (
<div className="min-h-screen flex flex-col bg-background font-sans scroll-smooth text-foreground">
{/* Barra superior */}
<div className="bg-primary text-primary-foreground text-sm py-2 px-4 md:px-6 flex justify-between items-center">
<span className="hidden sm:inline">Horário: 08h00 - 21h00</span>
<span className="hover:underline cursor-pointer transition">
Email: contato@mediconnect.com
</span>
</div>
{/* Header */}
<header className="bg-muted text-foreground shadow-md py-4 px-4 md:px-6 flex justify-between items-center relative sticky top-0 z-50 backdrop-blur-md">
<a href="#home" className="flex items-center space-x-2 cursor-pointer">
<img
src="/android-chrome-512x512.png"
alt="Logo MediConnect"
className="w-20 h-20 object-contain transition-transform hover:scale-105"
/>
<h1 className="text-2xl font-extrabold text-foreground tracking-tight">
MedConnect
</h1>
</a>
{/* Menu Mobile */}
<div className="md:hidden flex items-center space-x-4">
<Link href="/login">
<Button
variant="outline"
className="rounded-full px-4 py-2 text-sm border-2 border-primary text-primary hover:bg-primary hover:text-primary-foreground transition"
>
Login
</Button>
</Link>
<button
onClick={() => setIsMenuOpen(!isMenuOpen)}
className="text-[#1E2A78] focus:outline-none"
>
<svg
className="w-6 h-6"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
{isMenuOpen ? (
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M6 18L18 6M6 6l12 12"
></path>
) : (
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M4 6h16M4 12h16M4 18h16"
></path>
)}
</svg>
</button>
</div>
{/* Navegação */}
<nav
className={`${
isMenuOpen ? "block" : "hidden"
} absolute top-[76px] left-0 w-full bg-white shadow-md py-4 md:relative md:top-auto md:left-auto md:w-auto md:block md:bg-transparent md:shadow-none transition-all duration-300 z-10`}
>
<div className="flex flex-col md:flex-row space-y-4 md:space-y-0 md:space-x-8 text-foreground font-medium items-center">
<Link href="#home" className="hover:text-primary transition">
Home
</Link>
<a href="#about" className="hover:text-primary transition">
Sobre
</a>
<a href="#departments" className="hover:text-primary transition">
Departamentos
</a>
<a href="#doctors" className="hover:text-primary transition">
Médicos
</a>
<a href="#contact" className="hover:text-primary transition">
Contato
</a>
</div>
</nav>
{/* Login Desktop */}
<div className="hidden md:flex space-x-4">
<Link href="/login">
<Button
variant="outline"
className="rounded-full px-6 py-2 border-2 border-primary text-primary hover:bg-primary hover:text-primary-foreground transition cursor-pointer"
>
Login
</Button>
</Link>
</div>
</header>
{/* Hero Section */}
<section className={`flex flex-col md:flex-row items-center justify-between ${heroClass}`}>
<div className="max-w-lg mx-auto md:mx-0">
<h2 className="uppercase text-sm tracking-widest opacity-80">
Bem-vindo à Saúde Digital
</h2>
<h1 className="text-4xl sm:text-5xl lg:text-6xl font-extrabold leading-tight mt-2 drop-shadow-lg">
Soluções Médicas <br /> & Cuidados com a Saúde
</h1>
<p className="mt-4 text-base leading-relaxed opacity-90 text-foreground">
Excelência em saúde mais de 25 anos. Atendimento médico com
qualidade, segurança e carinho.
</p>
<div className="mt-8 flex flex-col sm:flex-row space-y-4 sm:space-y-0 sm:space-x-4 justify-center md:justify-start">
<Button className="px-8 py-3 text-base font-semibold bg-card text-card-foreground hover:bg-muted transition-all shadow-md">
Nossos Serviços
</Button>
<Button className="px-8 py-3 text-base font-semibold bg-card text-card-foreground hover:bg-muted transition-all shadow-md">
Saiba Mais
</Button>
</div>
</div>
<div className="mt-10 md:mt-0 flex justify-center">
<img
src="https://t4.ftcdn.net/jpg/03/20/52/31/360_F_320523164_tx7Rdd7I2XDTvvKfz2oRuRpKOPE5z0ni.jpg"
alt="Médico"
className="w-72 sm:w-96 lg:w-[28rem] h-auto object-cover rounded-2xl shadow-xl "
/>
</div>
</section>
{/* Serviços */}
<section
id="departments"
className="py-20 px-6 md:px-10 lg:px-20 bg-secondary"
>
<h2 className="text-center text-3xl sm:text-4xl font-extrabold text-foreground">
Cuidados completos para a sua saúde
</h2>
<p className="text-center text-muted-foreground mt-3 text-base">
Serviços médicos que oferecemos
</p>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-10 mt-12 max-w-6xl mx-auto">
{/* Card */}
{[
{
title: "Clínica Geral",
desc: "Seu primeiro passo para o cuidado. Atendimento focado na prevenção e no diagnóstico inicial.",
Icon: Stethoscope,
},
{
title: "Pediatria",
desc: "Cuidado gentil e especializado para garantir a saúde e o desenvolvimento de crianças e adolescentes.",
Icon: Baby,
},
{
title: "Exames",
desc: "Resultados rápidos e precisos em exames laboratoriais e de imagem essenciais para seu diagnóstico.",
Icon: Microscope,
},
].map(({ title, desc, Icon }, index) => (
<div
key={index}
className="p-8 bg-card rounded-2xl shadow-md hover:shadow-xl transition-all duration-300 border border-border group"
>
<div className="flex items-center space-x-3">
<Icon className="text-primary w-6 h-6 group-hover:scale-110 transition-transform" />
<h3 className="text-xl font-semibold">{title}</h3>
</div>
<p className="text-muted-foreground mt-3 text-sm leading-relaxed">
{desc}
</p>
<Button className="mt-6 w-full bg-primary hover:opacity-90 text-primary-foreground transition">
Agendar
</Button>
</div>
))}
</div>
</section>
{/* Footer */}
<footer className="bg-primary text-primary-foreground py-8 text-center text-sm border-t-2 border-primary-foreground/20">
<div className="space-y-2">
<p>© 2025 MediConnect Todos os direitos reservados</p>
<div className="flex justify-center space-x-6 opacity-90">
<a href="#about" className="hover:opacity-70 transition">
Sobre
</a>
<a href="#departments" className="hover:opacity-70 transition">
Serviços
</a>
<a href="#contact" className="hover:opacity-70 transition">
Contato
</a>
</div>
</div>
</footer>
   
</div>
);
}

View File

@ -1,271 +0,0 @@
"use client";
import { useState, useEffect } from "react";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
Calendar,
Clock,
MapPin,
Phone,
User,
X,
AlertCircle,
} from "lucide-react";
import { toast } from "sonner";
import { appointmentsService } from "@/services/appointmentsApi.mjs";
import { usersService } from "@/services/usersApi.mjs";
import { doctorsService } from "@/services/doctorsApi.mjs";
import Sidebar from "@/components/Sidebar";
export default function PatientAppointmentsPage() {
const [appointments, setAppointments] = useState<any[]>([]);
const [isLoading, setIsLoading] = useState(true);
// Estados para cancelamento
const [cancelModal, setCancelModal] = useState(false);
const [selectedAppointment, setSelectedAppointment] = useState<any>(null);
const fetchData = async () => {
setIsLoading(true);
try {
// 1. Obter usuário logado
const user = await usersService.getMe();
if (!user || !user.user?.id) {
toast.error("Usuário não identificado.");
return;
}
// 2. Buscar médicos e agendamentos em paralelo
// Filtra apenas agendamentos deste paciente
const queryParams = `patient_id=eq.${"user.user.id"}&order=scheduled_at.desc`;
console.log("id do paciente:", user.profile.id);
const [appointmentList, doctorList] = await Promise.all([
appointmentsService.search_appointment(queryParams),
doctorsService.list(),
]);
console.log("Agendamentos obtidos:", appointmentList);
console.log("Médicos obtidos:", doctorList);
// 3. Mapear médicos para acesso rápido
const doctorMap = new Map(doctorList.map((d: any) => [d.id, d]));
// 4. Enriquecer os agendamentos com dados do médico
const enrichedAppointments = appointmentList.map((apt: any) => ({
...apt,
doctor: doctorMap.get(apt.doctor_id) || {
full_name: "Médico não encontrado",
specialty: "Clínico Geral",
location: "Consultório",
phone: "N/A"
},
}));
console.log("Agendamentos enriquecidos:", enrichedAppointments);
setAppointments(enrichedAppointments);
} catch (error) {
console.error("Erro ao buscar dados:", error);
toast.error("Não foi possível carregar suas consultas.");
} finally {
setIsLoading(false);
}
};
useEffect(() => {
fetchData();
}, []);
// --- LÓGICA DE CANCELAMENTO ---
const handleCancelClick = (appointment: any) => {
setSelectedAppointment(appointment);
setCancelModal(true);
};
const confirmCancel = async () => {
if (!selectedAppointment) return;
try {
// Opção A: Deletar o registro (como no código da secretária)
await appointmentsService.delete(selectedAppointment.id);
// Opção B: Se preferir apenas mudar o status, descomente abaixo e comente a linha acima:
// await appointmentsService.update(selectedAppointment.id, { status: 'cancelled' });
setAppointments((prev) =>
prev.filter((apt) => apt.id !== selectedAppointment.id)
);
setCancelModal(false);
toast.success("Consulta cancelada com sucesso.");
} catch (error) {
console.error("Erro ao cancelar consulta:", error);
toast.error("Não foi possível cancelar a consulta.");
}
};
return (
<Sidebar>
<div className="space-y-6">
<div className="flex justify-between items-center">
<div>
<h1 className="text-3xl font-bold">Minhas Consultas</h1>
<p className="text-muted-foreground">
Acompanhe seu histórico e próximos agendamentos
</p>
</div>
</div>
<div className="grid gap-6">
{isLoading ? (
<p>Carregando consultas...</p>
) : appointments.length > 0 ? (
appointments.map((appointment) => (
<Card key={appointment.id}>
<CardHeader>
<div className="flex justify-between items-start">
<div>
<CardTitle className="text-lg">
{appointment.doctor.full_name}
</CardTitle>
<CardDescription>
{appointment.doctor.specialty}
</CardDescription>
</div>
{getStatusBadge(appointment.status)}
</div>
</CardHeader>
<CardContent>
<div className="grid md:grid-cols-2 gap-4">
{/* Coluna 1: Data e Hora */}
<div className="space-y-3">
<div className="flex items-center text-sm text-foreground font-medium">
<User className="mr-2 h-4 w-4 text-muted-foreground" />
Dr(a). {appointment.doctor.full_name.split(' ')[0]}
</div>
<div className="flex items-center text-sm text-muted-foreground">
<Calendar className="mr-2 h-4 w-4" />
{new Date(appointment.scheduled_at).toLocaleDateString(
"pt-BR",
{ timeZone: "UTC" }
)}
</div>
<div className="flex items-center text-sm text-muted-foreground">
<Clock className="mr-2 h-4 w-4" />
{new Date(appointment.scheduled_at).toLocaleTimeString(
"pt-BR",
{
hour: "2-digit",
minute: "2-digit",
timeZone: "UTC",
}
)}
</div>
</div>
{/* Coluna 2: Localização e Contato */}
<div className="space-y-3">
<div className="flex items-center text-sm text-muted-foreground">
<MapPin className="mr-2 h-4 w-4" />
{appointment.doctor.location || "Local a definir"}
</div>
<div className="flex items-center text-sm text-muted-foreground">
<Phone className="mr-2 h-4 w-4" />
{appointment.doctor.phone || "Contato não disponível"}
</div>
</div>
</div>
{/* Ações */}
{["requested", "confirmed"].includes(appointment.status) && (
<div className="flex gap-2 mt-4 pt-4 border-t justify-end">
<Button
variant="destructive"
size="sm"
className="bg-transparent text-destructive hover:bg-destructive/10 border border-destructive/20"
onClick={() => handleCancelClick(appointment)}
>
<X className="mr-2 h-4 w-4" />
Cancelar Consulta
</Button>
</div>
)}
</CardContent>
</Card>
))
) : (
<div className="text-center py-10 border rounded-lg bg-muted/20">
<Calendar className="mx-auto h-10 w-10 text-muted-foreground mb-4" />
<p className="text-muted-foreground">Você ainda não possui consultas agendadas.</p>
</div>
)}
</div>
</div>
{/* Modal de Confirmação de Cancelamento */}
<Dialog open={cancelModal} onOpenChange={setCancelModal}>
<DialogContent>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<AlertCircle className="h-5 w-5 text-destructive" />
Cancelar Consulta
</DialogTitle>
<DialogDescription>
Tem certeza que deseja cancelar sua consulta com{" "}
<strong>{selectedAppointment?.doctor?.full_name}</strong> no dia{" "}
{selectedAppointment &&
new Date(selectedAppointment.scheduled_at).toLocaleDateString(
"pt-BR", { timeZone: "UTC" }
)}
? Esta ação não pode ser desfeita.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => setCancelModal(false)}>
Voltar
</Button>
<Button variant="destructive" onClick={confirmCancel}>
Confirmar Cancelamento
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</Sidebar>
);
}
// Helper para Badges (Mantido consistente com o código da secretária)
const getStatusBadge = (status: string) => {
switch (status) {
case "requested":
return (
<Badge className="bg-yellow-400/10 text-yellow-600 hover:bg-yellow-400/20 border-yellow-400/20">Solicitada</Badge>
);
case "confirmed":
return <Badge className="bg-primary/10 text-primary hover:bg-primary/20 border-primary/20">Confirmada</Badge>;
case "checked_in":
return (
<Badge className="bg-indigo-400/10 text-indigo-600 hover:bg-indigo-400/20 border-indigo-400/20">Check-in</Badge>
);
case "completed":
return <Badge className="bg-green-400/10 text-green-600 hover:bg-green-400/20 border-green-400/20">Realizada</Badge>;
case "cancelled":
return <Badge className="bg-destructive/10 text-destructive hover:bg-destructive/20 border-destructive/20">Cancelada</Badge>;
case "no_show":
return (
<Badge className="bg-muted text-foreground border-muted-foreground/20">Não Compareceu</Badge>
);
default:
return <Badge variant="secondary">{status}</Badge>;
}
};

View File

@ -1,135 +0,0 @@
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Calendar, Clock, User, Plus } from "lucide-react";
import Link from "next/link";
import Sidebar from "@/components/Sidebar";
export default function PatientDashboard() {
return (
<Sidebar>
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold text-foreground">Dashboard</h1>
<p className="text-muted-foreground">
Bem-vindo ao seu portal de consultas médicas
</p>
</div>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Próxima Consulta
</CardTitle>
<Calendar className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">15 Jan</div>
<p className="text-xs text-muted-foreground">Dr. Silva - 14:30</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Consultas Este Mês
</CardTitle>
<Clock className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">3</div>
<p className="text-xs text-muted-foreground">
2 realizadas, 1 agendada
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Perfil</CardTitle>
<User className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">100%</div>
<p className="text-xs text-muted-foreground">Dados completos</p>
</CardContent>
</Card>
</div>
<div className="grid md:grid-cols-2 gap-6">
<Card>
<CardHeader>
<CardTitle>Ações Rápidas</CardTitle>
<CardDescription>
Acesse rapidamente as principais funcionalidades
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<Link href="/patient/schedule">
<Button className="w-full justify-start">
<User className="mr-2 h-4 w-4" />
Agendar Nova Consulta
</Button>
</Link>
<Link href="/patient/appointments">
<Button
variant="secondary"
className="w-full justify-start"
>
<Calendar className="mr-2 h-4 w-4" />
Ver Minhas Consultas
</Button>
</Link>
<Link href="/patient/profile">
<Button
variant="outline"
className="w-full justify-start"
>
<User className="mr-2 h-4 w-4" />
Atualizar Dados
</Button>
</Link>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Próximas Consultas</CardTitle>
<CardDescription>Suas consultas agendadas</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="flex items-center justify-between p-3 bg-muted rounded-lg">
<div>
<p className="font-medium">Dr. Silva</p>
<p className="text-sm text-muted-foreground">Cardiologia</p>
</div>
<div className="text-right">
<p className="font-medium">15 Jan</p>
<p className="text-sm text-muted-foreground">14:30</p>
</div>
</div>
<div className="flex items-center justify-between p-3 bg-muted rounded-lg">
<div>
<p className="font-medium">Dra. Santos</p>
<p className="text-sm text-muted-foreground">Dermatologia</p>
</div>
<div className="text-right">
<p className="font-medium">22 Jan</p>
<p className="text-sm text-muted-foreground">10:00</p>
</div>
</div>
</div>
</CardContent>
</Card>
</div>
</div>
</Sidebar>
);
}

View File

@ -1,46 +0,0 @@
// Caminho: app/patient/login/page.tsx
import Link from "next/link";
import { LoginForm } from "@/components/LoginForm";
import { Button } from "@/components/ui/button";
import { ArrowLeft } from "lucide-react";
export default function PatientLoginPage() {
// NOTA: Esta página de login específica para pacientes se tornou obsoleta
// com a criação da nossa página de login central em /login.
// Mantemos este arquivo por enquanto para evitar quebrar outras partes do código,
// mas o ideal no futuro seria deletar esta página e redirecionar
// /patient/login para /login.
return (
<div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50 flex flex-col items-center justify-center p-4">
<div className="w-full max-w-md">
<div className="mb-8">
<Link href="/" className="inline-flex items-center text-muted-foreground hover:text-primary transition-colors duration-200 font-medium">
<ArrowLeft className="w-4 h-4 mr-2" />
Voltar ao início
</Link>
</div>
{/* --- ALTERAÇÃO PRINCIPAL AQUI --- */}
{/* Removemos as props desnecessárias (title, description, role, etc.) */}
{/* O novo LoginForm é autônomo e não precisa mais delas. */}
<LoginForm>
{/* Este bloco é passado como 'children' para o LoginForm */}
<div className="mt-6 text-center text-sm">
<span className="text-muted-foreground">Não tem uma conta? </span>
<Link href="/patient/register">
<span className="font-semibold text-primary hover:underline cursor-pointer">
Crie uma agora
</span>
</Link>
</div>
</LoginForm>
<div className="mt-8 text-center">
<p className="text-sm text-muted-foreground">Problemas para acessar? Entre em contato conosco</p>
</div>
</div>
</div>
);
}

View File

@ -1,436 +0,0 @@
// Caminho: app/patient/profile/page.tsx
"use client";
import { useState, useEffect, useRef } from "react";
import Sidebar from "@/components/Sidebar";
import { useAuthLayout } from "@/hooks/useAuthLayout";
import { patientsService } from "@/services/patientsApi.mjs";
import { usersService } from "@/services/usersApi.mjs"; // Adicionado import
import { api } from "@/services/api.mjs";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { User, Mail, Phone, Calendar, Upload } from "lucide-react";
import { toast } from "@/hooks/use-toast";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
interface PatientProfileData {
name: string;
email: string;
phone: string;
cpf: string;
birthDate: string;
cep: string;
street: string;
number: string;
city: string;
avatarFullUrl?: string;
}
export default function PatientProfile() {
const { user, isLoading: isAuthLoading } = useAuthLayout({
requiredRole: ["paciente", "admin", "medico", "gestor", "secretaria"],
});
const [patientData, setPatientData] = useState<PatientProfileData | null>(null);
const [isEditing, setIsEditing] = useState(false);
const [isSaving, setIsSaving] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const getInitials = (name: string) => {
if (!name) return "U";
return name
.split(" ")
.map((n) => n[0])
.slice(0, 2)
.join("")
.toUpperCase();
};
// Função auxiliar para construir URL do avatar
const buildAvatarUrl = (path: string | null | undefined) => {
if (!path) return undefined;
const baseUrl = "https://yuanqfswhberkoevtmfr.supabase.co";
const cleanPath = path.startsWith('/') ? path.slice(1) : path;
const separator = cleanPath.includes('?') ? '&' : '?';
return `${baseUrl}/storage/v1/object/avatars/${cleanPath}${separator}t=${new Date().getTime()}`;
};
useEffect(() => {
if (user?.id) {
const loadData = async () => {
try {
// 1. Busca dados médicos (Tabela Patients)
const patientDetails = await patientsService.getById(user.id);
// 2. Busca dados de sistema frescos (Tabela Profiles via getMe)
// Isso garante que pegamos o avatar real do banco, não do cache local
const userSystemData = await usersService.getMe();
const freshAvatarPath = userSystemData?.profile?.avatar_url;
const freshAvatarUrl = buildAvatarUrl(freshAvatarPath);
setPatientData({
name: patientDetails.full_name || user.name,
email: user.email,
phone: patientDetails.phone_mobile || "",
cpf: patientDetails.cpf || "",
birthDate: patientDetails.birth_date || "",
cep: patientDetails.cep || "",
street: patientDetails.street || "",
number: patientDetails.number || "",
city: patientDetails.city || "",
avatarFullUrl: freshAvatarUrl, // Usa a URL fresca do banco
});
} catch (error) {
console.error("Erro ao buscar detalhes:", error);
toast({
title: "Erro",
description: "Não foi possível carregar seus dados completos.",
variant: "destructive",
});
}
};
loadData();
}
}, [user?.id, user?.email, user?.name]); // Removi user.avatarFullUrl para não depender do cache
const handleInputChange = (
field: keyof PatientProfileData,
value: string
) => {
setPatientData((prev) => (prev ? { ...prev, [field]: value } : null));
};
const updateLocalSession = (updates: { full_name?: string; avatar_url?: string }) => {
try {
const storedUserString = localStorage.getItem("user_info");
if (storedUserString) {
const storedUser = JSON.parse(storedUserString);
if (!storedUser.user_metadata) storedUser.user_metadata = {};
if (updates.full_name) storedUser.user_metadata.full_name = updates.full_name;
if (updates.avatar_url) storedUser.user_metadata.avatar_url = updates.avatar_url;
if (!storedUser.profile) storedUser.profile = {};
if (updates.full_name) storedUser.profile.full_name = updates.full_name;
if (updates.avatar_url) storedUser.profile.avatar_url = updates.avatar_url;
localStorage.setItem("user_info", JSON.stringify(storedUser));
}
} catch (e) {
console.error("Erro ao atualizar sessão local:", e);
}
};
const handleSave = async () => {
if (!patientData || !user) return;
setIsSaving(true);
try {
const patientPayload = {
full_name: patientData.name,
cpf: patientData.cpf,
birth_date: patientData.birthDate,
phone_mobile: patientData.phone,
cep: patientData.cep,
street: patientData.street,
number: patientData.number,
city: patientData.city,
};
await patientsService.update(user.id, patientPayload);
await api.patch(`/rest/v1/profiles?id=eq.${user.id}`, {
full_name: patientData.name,
});
updateLocalSession({ full_name: patientData.name });
toast({
title: "Sucesso!",
description: "Seus dados foram atualizados. A página será recarregada.",
});
setIsEditing(false);
setTimeout(() => window.location.reload(), 1000);
} catch (error) {
console.error("Erro ao salvar dados:", error);
toast({
title: "Erro",
description: "Não foi possível salvar suas alterações.",
variant: "destructive",
});
} finally {
setIsSaving(false);
}
};
const handleAvatarClick = () => {
fileInputRef.current?.click();
};
const handleAvatarUpload = async (
event: React.ChangeEvent<HTMLInputElement>
) => {
const file = event.target.files?.[0];
if (!file || !user) return;
const fileExt = file.name.split(".").pop();
const filePath = `${user.id}/avatar.${fileExt}`;
try {
await api.storage.upload("avatars", filePath, file);
await api.patch(`/rest/v1/profiles?id=eq.${user.id}`, {
avatar_url: filePath,
});
const newFullUrl = buildAvatarUrl(filePath);
setPatientData((prev) =>
prev ? { ...prev, avatarFullUrl: newFullUrl } : null
);
updateLocalSession({ avatar_url: filePath });
toast({
title: "Sucesso!",
description: "Sua foto de perfil foi atualizada.",
});
setTimeout(() => window.location.reload(), 1000);
} catch (error) {
console.error("Erro no upload do avatar:", error);
toast({
title: "Erro de Upload",
description: "Não foi possível enviar sua foto.",
variant: "destructive",
});
}
};
if (isAuthLoading || !patientData) {
return (
<Sidebar>
<div className="flex items-center justify-center h-full">
<p className="text-muted-foreground">Carregando seus dados...</p>
</div>
</Sidebar>
);
}
return (
<Sidebar>
<div className="space-y-6">
<div className="flex justify-between items-center">
<div>
<h1 className="text-3xl font-bold text-foreground">Meus Dados</h1>
<p className="text-muted-foreground">Gerencie suas informações pessoais</p>
</div>
<Button
onClick={() => (isEditing ? handleSave() : setIsEditing(true))}
disabled={isSaving}
className="bg-blue-600 hover:bg-blue-700 text-white"
>
{isEditing
? isSaving
? "Salvando..."
: "Salvar Alterações"
: "Editar Dados"}
</Button>
</div>
<div className="grid lg:grid-cols-3 gap-6">
<div className="lg:col-span-2 space-y-6">
<Card>
<CardHeader>
<CardTitle className="flex items-center">
<User className="mr-2 h-5 w-5" />
Informações Pessoais
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid md:grid-cols-2 gap-4">
<div>
<Label htmlFor="name">Nome Completo</Label>
<Input
id="name"
value={patientData.name}
onChange={(e) =>
handleInputChange("name", e.target.value)
}
disabled={!isEditing}
/>
</div>
<div>
<Label htmlFor="cpf">CPF</Label>
<Input
id="cpf"
value={patientData.cpf}
onChange={(e) => handleInputChange("cpf", e.target.value)}
disabled={!isEditing}
/>
</div>
</div>
<div>
<Label htmlFor="birthDate">Data de Nascimento</Label>
<Input
id="birthDate"
type="date"
value={patientData.birthDate}
onChange={(e) =>
handleInputChange("birthDate", e.target.value)
}
disabled={!isEditing}
/>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="flex items-center">
<Mail className="mr-2 h-5 w-5" />
Contato e Endereço
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid md:grid-cols-2 gap-4">
<div>
<Label htmlFor="email">Email</Label>
<Input
id="email"
type="email"
value={patientData.email}
disabled
/>
</div>
<div>
<Label htmlFor="phone">Telefone</Label>
<Input
id="phone"
value={patientData.phone}
onChange={(e) =>
handleInputChange("phone", e.target.value)
}
disabled={!isEditing}
/>
</div>
</div>
<div className="grid md:grid-cols-3 gap-4">
<div>
<Label htmlFor="cep">CEP</Label>
<Input
id="cep"
value={patientData.cep}
onChange={(e) => handleInputChange("cep", e.target.value)}
disabled={!isEditing}
/>
</div>
<div className="md:col-span-2">
<Label htmlFor="street">Rua / Logradouro</Label>
<Input
id="street"
value={patientData.street}
onChange={(e) =>
handleInputChange("street", e.target.value)
}
disabled={!isEditing}
/>
</div>
</div>
<div className="grid md:grid-cols-2 gap-4">
<div>
<Label htmlFor="number">Número</Label>
<Input
id="number"
value={patientData.number}
onChange={(e) =>
handleInputChange("number", e.target.value)
}
disabled={!isEditing}
/>
</div>
<div>
<Label htmlFor="city">Cidade</Label>
<Input
id="city"
value={patientData.city}
onChange={(e) =>
handleInputChange("city", e.target.value)
}
disabled={!isEditing}
/>
</div>
</div>
</CardContent>
</Card>
</div>
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle>Resumo do Perfil</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center space-x-3">
<div className="relative group">
<Avatar
className="w-16 h-16 cursor-pointer border-2 border-transparent group-hover:border-blue-500 transition-all"
onClick={handleAvatarClick}
>
<AvatarImage src={patientData.avatarFullUrl} className="object-cover" />
<AvatarFallback className="text-2xl bg-gray-200 text-gray-700 font-bold">
{getInitials(patientData.name)}
</AvatarFallback>
</Avatar>
<div
className="absolute bottom-0 right-0 bg-blue-600 text-white rounded-full p-1.5 cursor-pointer hover:bg-blue-700 shadow-md transition-colors"
onClick={handleAvatarClick}
title="Alterar foto"
>
<Upload className="w-3 h-3" />
</div>
<input
type="file"
ref={fileInputRef}
onChange={handleAvatarUpload}
className="hidden"
accept="image/png, image/jpeg, image/jpg"
/>
</div>
<div>
<p className="font-medium text-lg">{patientData.name}</p>
<p className="text-sm text-gray-500">Paciente</p>
</div>
</div>
<div className="space-y-3 pt-4 border-t">
<div className="flex items-center text-sm">
<Mail className="mr-2 h-4 w-4 text-muted-foreground" />
<span className="truncate">{patientData.email}</span>
</div>
<div className="flex items-center text-sm">
<Phone className="mr-2 h-4 w-4 text-muted-foreground" />
<span>{patientData.phone || "Não informado"}</span>
</div>
<div className="flex items-center text-sm">
<Calendar className="mr-2 h-4 w-4 text-muted-foreground" />
<span>
{patientData.birthDate
? new Date(patientData.birthDate).toLocaleDateString(
"pt-BR",
{ timeZone: "UTC" }
)
: "Não informado"}
</span>
</div>
</div>
</CardContent>
</Card>
</div>
</div>
</div>
</Sidebar>
);
}

View File

@ -1,186 +0,0 @@
"use client"
import type React from "react"
import { useState } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { ArrowLeft, Loader2 } from "lucide-react"
import { useToast } from "@/hooks/use-toast"
import { usersService } from "@/services/usersApi.mjs" // Mantém a importação
import { isValidCPF } from "@/lib/utils"
export default function PatientRegister() {
// REMOVIDO: Estados para 'showPassword' e 'showConfirmPassword'
const [formData, setFormData] = useState({
name: "",
email: "",
phone: "",
cpf: "",
birthDate: "",
// REMOVIDO: Campos 'password' e 'confirmPassword'
})
const [isLoading, setIsLoading] = useState(false)
const router = useRouter()
const { toast } = useToast()
const handleInputChange = (field: string, value: string) => {
setFormData((prev) => ({
...prev,
[field]: value,
}))
}
const handleRegister = async (e: React.FormEvent) => {
e.preventDefault()
setIsLoading(true)
// --- VALIDAÇÃO DE CPF ---
if (!isValidCPF(formData.cpf)) {
toast({
title: "CPF Inválido",
description: "O CPF informado não é válido. Verifique os dígitos.",
variant: "destructive",
})
setIsLoading(false)
return
}
// --- LÓGICA DE REGISTRO COM ENDPOINT PÚBLICO ---
try {
// ALTERADO: Payload ajustado para o endpoint 'register-patient'
const payload = {
email: formData.email.trim().toLowerCase(),
full_name: formData.name,
phone_mobile: formData.phone, // O endpoint espera 'phone_mobile'
cpf: formData.cpf.replace(/\D/g, ''),
birth_date: formData.birthDate,
}
// ALTERADO: Chamada para a nova função de serviço
await usersService.registerPatient(payload)
// ALTERADO: Mensagem de sucesso para refletir o fluxo de confirmação por e-mail
toast({
title: "Cadastro enviado com sucesso!",
description: "Enviamos um link de confirmação para o seu e-mail. Por favor, verifique sua caixa de entrada para ativar sua conta.",
})
// Redireciona para a página de login
router.push("/login")
} catch (error: any) {
console.error("Erro no registro:", error)
toast({
title: "Erro ao Criar Conta",
description: error.message || "Não foi possível concluir o cadastro. Verifique seus dados e tente novamente.",
variant: "destructive",
})
} finally {
setIsLoading(false)
}
}
return (
<div className="min-h-screen bg-background py-8 px-4">
<div className="max-w-2xl mx-auto">
<div className="mb-6">
<Link href="/" className="inline-flex items-center text-primary hover:text-primary/90">
<ArrowLeft className="w-4 h-4 mr-2" />
Voltar ao início
</Link>
</div>
<Card>
<CardHeader className="text-center">
<CardTitle className="text-2xl text-foreground">Crie sua Conta de Paciente</CardTitle>
<CardDescription className="text-muted-foreground">Preencha seus dados para acessar o portal MedConnect</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleRegister} className="space-y-4">
<div className="grid md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="name">Nome Completo *</Label>
<Input
id="name"
value={formData.name}
onChange={(e) => handleInputChange("name", e.target.value)}
required
disabled={isLoading}
/>
</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"
required
disabled={isLoading}
/>
</div>
</div>
<div className="grid md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="email">Email *</Label>
<Input
id="email"
type="email"
value={formData.email}
onChange={(e) => handleInputChange("email", e.target.value)}
required
disabled={isLoading}
/>
</div>
<div className="space-y-2">
<Label htmlFor="phone">Telefone *</Label>
<Input
id="phone"
value={formData.phone}
onChange={(e) => handleInputChange("phone", e.target.value)}
placeholder="(11) 99999-9999"
required
disabled={isLoading}
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="birthDate">Data de Nascimento *</Label>
<Input
id="birthDate"
type="date"
value={formData.birthDate}
onChange={(e) => handleInputChange("birthDate", e.target.value)}
required
disabled={isLoading}
/>
</div>
{/* REMOVIDO: Seção de senha e confirmação de senha */}
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? <><Loader2 className="mr-2 h-4 w-4 animate-spin" /> Criando conta...</> : "Criar Conta"}
</Button>
</form>
<div className="mt-6 text-center">
<p className="text-sm">
<span className="text-muted-foreground"> tem uma conta?</span>{" "}
<Link href="/login" className="text-primary hover:underline font-medium">
Faça login aqui
</Link>
</p>
</div>
</CardContent>
</Card>
</div>
</div>
)
}

View File

@ -1,296 +0,0 @@
"use client"
import { useState, useEffect, useMemo } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { toast } from "@/hooks/use-toast"
import { FileText, Download, Eye, Calendar, User, X, Loader2 } from "lucide-react"
import Sidebar from "@/components/Sidebar"
import { useAuthLayout } from "@/hooks/useAuthLayout"
import { reportsApi } from "@/services/reportsApi.mjs"
interface Report {
id: string;
order_number: string;
patient_id: string;
status: string;
exam: string;
requested_by: string;
cid_code: string;
diagnosis: string;
conclusion: string;
content_html: string;
content_json: any;
hide_date: boolean;
hide_signature: boolean;
due_at: string;
created_by: string;
updated_by: string;
created_at: string;
updated_at: string;
}
export default function ReportsPage() {
const [reports, setReports] = useState<Report[]>([])
const [selectedReport, setSelectedReport] = useState<Report | null>(null)
const [isViewModalOpen, setIsViewModalOpen] = useState(false)
const [isLoading, setIsLoading] = useState(true)
const { user, isLoading: isAuthLoading } = useAuthLayout({
requiredRole: ["paciente", "admin", "medico", "gestor", "secretaria"],
  });
useEffect(() => {
if (user) {
const fetchReports = async () => {
try {
setIsLoading(true);
const fetchedReports = await reportsApi.getReports(user.id);
setReports(fetchedReports);
} catch (error) {
console.error("Erro ao buscar laudos:", error)
toast({
title: "Erro ao buscar laudos",
description: "Não foi possível carregar os laudos. Tente novamente.",
variant: "destructive",
})
} finally {
setIsLoading(false);
}
}
fetchReports()
}
}, [user?.id])
const handleViewReport = (reportId: string) => {
const report = reports.find((r) => r.id === reportId)
if (report) {
setSelectedReport(report)
setIsViewModalOpen(true)
}
}
const handleDownloadReport = async (reportId: string) => {
const report = reports.find((r) => r.id === reportId)
if (!report) return
try {
toast({
title: "Preparando download...",
description: "Gerando PDF do laudo médico",
})
const htmlContent = report.content_html;
const blob = new Blob([htmlContent], { type: "text/html" })
const url = URL.createObjectURL(blob)
const link = document.createElement("a")
link.href = url
link.download = `laudo-${report.order_number}.html`
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
URL.revokeObjectURL(url)
toast({
title: "Download concluído!",
description: "O laudo foi baixado com sucesso",
})
} catch (error) {
console.error("Erro ao baixar laudo:", error)
toast({
title: "Erro no download",
description: "Não foi possível baixar o laudo. Tente novamente.",
variant: "destructive",
})
}
}
const handleCloseModal = () => {
setIsViewModalOpen(false)
setSelectedReport(null)
}
const availableReports = reports.filter((report) => report.status.toLowerCase() === "draft")
const pendingReports = reports.filter((report) => report.status.toLowerCase() !== "draft")
if (isLoading || isAuthLoading) {
return (
<Sidebar>
<div className="flex justify-center items-center h-full">
<Loader2 className="h-8 w-8 animate-spin" />
</div>
</Sidebar>
)
}
return (
<Sidebar>
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold text-foreground">Meus Laudos</h1>
<p className="text-muted-foreground mt-2">Visualize e baixe seus laudos médicos e resultados de exames</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Total de Laudos</CardTitle>
<FileText className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{reports.length}</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Disponíveis</CardTitle>
<Eye className="h-4 w-4 text-green-600" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-green-600">{availableReports.length}</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Pendentes</CardTitle>
<Calendar className="h-4 w-4 text-yellow-600" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-yellow-600">{pendingReports.length}</div>
</CardContent>
</Card>
</div>
{availableReports.length > 0 && (
<div>
<h2 className="text-xl font-semibold text-foreground mb-4">Laudos Disponíveis</h2>
<div className="grid gap-4">
{availableReports.map((report) => (
<Card key={report.id} className="hover:shadow-md transition-shadow">
<CardHeader>
<div className="flex items-start justify-between">
<div className="space-y-1">
<CardTitle className="text-lg">{report.exam}</CardTitle>
<CardDescription className="flex items-center gap-4">
<span className="flex items-center gap-1">
<User className="h-4 w-4" />
{report.requested_by}
</span>
<span className="flex items-center gap-1">
<Calendar className="h-4 w-4" />
{new Date(report.created_at).toLocaleDateString("pt-BR")}
</span>
</CardDescription>
</div>
<Badge variant="secondary" className="bg-green-100 text-green-800">
Finalizado
</Badge>
</div>
</CardHeader>
<CardContent>
<p className="text-muted-foreground mb-4">{report.diagnosis}</p>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => handleViewReport(report.id)}
className="flex items-center gap-2"
>
<Eye className="h-4 w-4" />
Visualizar
</Button>
<Button
variant="default"
size="sm"
onClick={() => handleDownloadReport(report.id)}
className="flex items-center gap-2"
>
<Download className="h-4 w-4" />
Baixar
</Button>
</div>
</CardContent>
</Card>
))}
</div>
</div>
)}
{pendingReports.length > 0 && (
<div>
<h2 className="text-xl font-semibold text-foreground mb-4">Laudos Pendentes</h2>
<div className="grid gap-4">
{pendingReports.map((report) => (
<Card key={report.id} className="opacity-75">
<CardHeader>
<div className="flex items-start justify-between">
<div className="space-y-1">
<CardTitle className="text-lg">{report.exam}</CardTitle>
<CardDescription className="flex items-center gap-4">
<span className="flex items-center gap-1">
<User className="h-4 w-4" />
{report.requested_by}
</span>
<span className="flex items-center gap-1">
<Calendar className="h-4 w-4" />
{new Date(report.created_at).toLocaleDateString("pt-BR")}
</span>
</CardDescription>
</div>
<Badge variant="secondary" className="bg-yellow-100 text-yellow-800">
{report.status}
</Badge>
</div>
</CardHeader>
<CardContent>
<p className="text-muted-foreground mb-4">{report.diagnosis}</p>
<p className="text-sm text-yellow-600 dark:text-yellow-500 font-medium">
Laudo em processamento. Você será notificado quando estiver disponível.
</p>
</CardContent>
</Card>
))}
</div>
</div>
)}
{reports.length === 0 && !isLoading && (
<Card className="text-center py-12">
<CardContent>
<FileText className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
<h3 className="text-lg font-medium text-foreground mb-2">Nenhum laudo encontrado</h3>
<p className="text-muted-foreground">Seus laudos médicos aparecerão aqui após a realização de exames.</p>
</CardContent>
</Card>
)}
<Dialog open={isViewModalOpen} onOpenChange={setIsViewModalOpen}>
<DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<div className="flex items-center justify-between">
<div>
<DialogTitle className="text-xl font-bold">{selectedReport?.exam}</DialogTitle>
<DialogDescription className="mt-1">
{selectedReport?.order_number}
</DialogDescription>
</div>
<Button variant="ghost" size="sm" onClick={handleCloseModal} className="h-8 w-8 p-0">
<X className="h-4 w-4" />
</Button>
</div>
</DialogHeader>
{selectedReport && (
<div className="space-y-6 mt-4" dangerouslySetInnerHTML={{ __html: selectedReport.content_html }} />
)}
</DialogContent>
</Dialog>
</div>
</Sidebar>
)
}

View File

@ -1,12 +0,0 @@
// app/patient/appointments/page.tsx
import Sidebar from "@/components/Sidebar";
import ScheduleForm from "@/components/schedule/schedule-form";
export default function PatientAppointments() {
return (
<Sidebar>
<ScheduleForm />
</Sidebar>
);
}

View File

@ -1,18 +0,0 @@
"use client";
import { AccessibilityProvider } from "./context/AccessibilityContext";
import { AppointmentsProvider } from "./context/AppointmentsContext";
import { AccessibilityModal } from "@/components/accessibility-modal";
import { ThemeInitializer } from "@/components/theme-initializer";
export function Providers({ children }: { children: React.ReactNode }) {
return (
<>
<ThemeInitializer />
<AccessibilityProvider>
<AppointmentsProvider>{children}</AppointmentsProvider>
<AccessibilityModal />
</AccessibilityProvider>
</>
);
}

View File

@ -1,468 +0,0 @@
"use client";
import { useState, useEffect, useMemo } from "react";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Dialog } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input"; // Importei o Input
import { Calendar as CalendarShadcn } from "@/components/ui/calendar";
import { Separator } from "@/components/ui/separator";
import {
Calendar as CalendarIcon,
Clock,
MapPin,
Phone,
User,
Trash2,
Pencil,
List,
RefreshCw,
Loader2,
Search, // Importei o ícone de busca
} from "lucide-react";
import { format, parseISO, isValid, isToday, isTomorrow } from "date-fns";
import { ptBR } from "date-fns/locale";
import { toast } from "sonner";
import Link from "next/link";
import { appointmentsService } from "@/services/appointmentsApi.mjs";
import { patientsService } from "@/services/patientsApi.mjs";
import { doctorsService } from "@/services/doctorsApi.mjs";
import Sidebar from "@/components/Sidebar";
export default function SecretaryAppointments() {
const [appointments, setAppointments] = useState<any[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [selectedAppointment, setSelectedAppointment] = useState<any>(null);
// Estados dos Modais
const [deleteModal, setDeleteModal] = useState(false);
const [editModal, setEditModal] = useState(false);
// Estado da Busca
const [searchTerm, setSearchTerm] = useState("");
// Estado para o formulário de edição
const [editFormData, setEditFormData] = useState({
date: "",
time: "",
status: "",
});
// Estado de data selecionada
const [selectedDate, setSelectedDate] = useState<Date | undefined>(new Date());
const fetchData = async () => {
setIsLoading(true);
try {
const queryParams = "order=scheduled_at.asc";
const [appointmentList, patientList, doctorList] = await Promise.all([
appointmentsService.search_appointment(queryParams),
patientsService.list(),
doctorsService.list(),
]);
const patientMap = new Map(patientList.map((p: any) => [p.id, p]));
const doctorMap = new Map(doctorList.map((d: any) => [d.id, d]));
const enrichedAppointments = appointmentList.map((apt: any) => ({
...apt,
patient: patientMap.get(apt.patient_id) || {
full_name: "Paciente não encontrado",
},
doctor: doctorMap.get(apt.doctor_id) || {
full_name: "Médico não encontrado",
specialty: "N/A",
},
}));
setAppointments(enrichedAppointments);
} catch (error) {
console.error("Falha ao buscar agendamentos:", error);
toast.error("Não foi possível carregar a lista de agendamentos.");
} finally {
setIsLoading(false);
}
};
useEffect(() => {
fetchData();
}, []);
// --- Filtragem e Agrupamento ---
const groupedAppointments = useMemo(() => {
let filteredList = appointments;
// 1. Filtro de Texto (Nome do Paciente ou Médico)
if (searchTerm) {
const lowerTerm = searchTerm.toLowerCase();
filteredList = filteredList.filter(
(apt) =>
apt.patient.full_name.toLowerCase().includes(lowerTerm) ||
apt.doctor.full_name.toLowerCase().includes(lowerTerm)
);
}
// 2. Filtro de Data (se selecionada)
if (selectedDate) {
filteredList = filteredList.filter((apt) => {
if (!apt.scheduled_at) return false;
const iso = apt.scheduled_at.toString();
return iso.startsWith(format(selectedDate, "yyyy-MM-dd"));
});
}
// 3. Agrupamento por dia
return filteredList.reduce((acc: Record<string, any[]>, apt: any) => {
if (!apt.scheduled_at) return acc;
const dateObj = new Date(apt.scheduled_at);
if (!isValid(dateObj)) return acc;
const key = format(dateObj, "yyyy-MM-dd");
if (!acc[key]) acc[key] = [];
acc[key].push(apt);
return acc;
}, {});
}, [appointments, selectedDate, searchTerm]);
// Dias que têm consulta (para destacar no calendário)
const bookedDays = useMemo(
() =>
appointments
.map((apt) =>
apt.scheduled_at ? new Date(apt.scheduled_at) : null
)
.filter((d): d is Date => d !== null && isValid(d)),
[appointments]
);
const formatDisplayDate = (dateString: string) => {
const date = parseISO(dateString);
if (isToday(date)) {
return `Hoje, ${format(date, "dd 'de' MMMM", { locale: ptBR })}`;
}
if (isTomorrow(date)) {
return `Amanhã, ${format(date, "dd 'de' MMMM", { locale: ptBR })}`;
}
return format(date, "EEEE, dd 'de' MMMM", { locale: ptBR });
};
// --- LÓGICA DE EDIÇÃO E DELEÇÃO ---
const handleEdit = (appointment: any) => {
setSelectedAppointment(appointment);
const appointmentDate = new Date(appointment.scheduled_at);
setEditFormData({
date: appointmentDate.toISOString().split("T")[0],
time: appointmentDate.toLocaleTimeString("pt-BR", {
hour: "2-digit",
minute: "2-digit",
timeZone: "UTC",
}),
status: appointment.status,
});
setEditModal(true);
};
const confirmEdit = async () => {
if (
!selectedAppointment ||
!editFormData.date ||
!editFormData.time ||
!editFormData.status
) {
toast.error("Todos os campos são obrigatórios para a edição.");
return;
}
try {
const newScheduledAt = new Date(
`${editFormData.date}T${editFormData.time}:00Z`
).toISOString();
const updatePayload = {
scheduled_at: newScheduledAt,
status: editFormData.status,
};
await appointmentsService.update(selectedAppointment.id, updatePayload);
await fetchData();
setEditModal(false);
toast.success("Consulta atualizada com sucesso!");
} catch (error) {
console.error("Erro ao atualizar consulta:", error);
toast.error("Não foi possível atualizar a consulta.");
}
};
const handleDelete = (appointment: any) => {
setSelectedAppointment(appointment);
setDeleteModal(true);
};
const confirmDelete = async () => {
if (!selectedAppointment) return;
try {
await appointmentsService.delete(selectedAppointment.id);
setAppointments((prev) =>
prev.filter((apt) => apt.id !== selectedAppointment.id)
);
setDeleteModal(false);
toast.success("Consulta deletada com sucesso!");
} catch (error) {
console.error("Erro ao deletar consulta:", error);
toast.error("Não foi possível deletar a consulta.");
}
};
return (
<Sidebar>
<div className="space-y-6">
{/* Cabeçalho principal */}
<div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
<div>
<h1 className="text-3xl font-bold text-foreground">
Agenda Médica
</h1>
<p className="text-muted-foreground">
Consultas para os pacientes
</p>
</div>
<Link href="/secretary/schedule">
<Button className="bg-primary hover:bg-primary/90 text-primary-foreground">
<CalendarIcon className="mr-2 h-4 w-4" />
Agendar Nova Consulta
</Button>
</Link>
</div>
{/* Barra de Filtros e Ações */}
<div className="flex flex-col md:flex-row justify-between items-center gap-4">
<h2 className="text-xl font-semibold capitalize whitespace-nowrap">
{selectedDate
? `Agenda de ${format(selectedDate, "dd/MM/yyyy")}`
: "Todas as Consultas"}
</h2>
<div className="flex flex-col md:flex-row items-center gap-3 w-full md:w-auto">
{/* BARRA DE PESQUISA ADICIONADA AQUI */}
<div className="relative w-full md:w-72">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
type="search"
placeholder="Buscar paciente ou médico..."
className="pl-9 w-full"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
<div className="flex gap-2 w-full md:w-auto">
<Button
onClick={() => {
setSelectedDate(undefined);
setSearchTerm("");
}}
variant="ghost"
size="sm"
className="flex-1 md:flex-none"
>
<List className="mr-2 h-4 w-4" />
Mostrar Todas
</Button>
<Button
onClick={() => fetchData()}
disabled={isLoading}
variant="outline"
size="sm"
className="flex-1 md:flex-none"
>
<RefreshCw
className={`mr-2 h-4 w-4 ${isLoading ? "animate-spin" : ""}`}
/>
Atualizar
</Button>
</div>
</div>
</div>
{/* Grid com calendário + lista */}
<div className="grid lg:grid-cols-3 gap-6">
{/* Coluna esquerda: calendário */}
<div className="lg:col-span-1">
<Card>
<CardHeader>
<CardTitle className="flex items-center">
<CalendarIcon className="mr-2 h-5 w-5" />
Filtrar por Data
</CardTitle>
<CardDescription>
Selecione um dia para ver os detalhes.
</CardDescription>
</CardHeader>
<CardContent className="flex justify-center p-2">
<CalendarShadcn
mode="single"
selected={selectedDate}
onSelect={setSelectedDate}
modifiers={{ booked: bookedDays }}
modifiersClassNames={{ booked: "bg-primary/20" }}
className="rounded-md border p-2"
locale={ptBR}
/>
</CardContent>
</Card>
</div>
{/* Coluna direita: lista de consultas */}
<div className="lg:col-span-2 space-y-6">
{isLoading ? (
<div className="flex justify-center items-center h-48">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
</div>
) : Object.keys(groupedAppointments).length === 0 ? (
<Card className="flex flex-col items-center justify-center h-48 text-center">
<CardHeader>
<CardTitle>Nenhuma consulta encontrada</CardTitle>
</CardHeader>
<CardContent>
<p className="text-muted-foreground">
{searchTerm
? "Nenhum resultado para a busca."
: selectedDate
? "Não há agendamentos para esta data."
: "Não há consultas agendadas."}
</p>
</CardContent>
</Card>
) : (
Object.entries(groupedAppointments).map(
([date, appointmentsForDay]) => (
<div key={date}>
<h3 className="text-lg font-semibold text-foreground mb-3 capitalize">
{formatDisplayDate(date)}
</h3>
<div className="space-y-4">
{appointmentsForDay.map((appointment: any) => {
const scheduledAtDate = new Date(
appointment.scheduled_at
);
return (
<Card
key={appointment.id}
className="shadow-sm hover:shadow-md transition-shadow"
>
<CardContent className="p-4 grid grid-cols-1 md:grid-cols-3 items-center gap-4">
{/* Coluna 1: Paciente + hora */}
<div className="col-span-1 flex flex-col gap-2">
<div className="font-semibold flex items-center text-foreground">
<User className="mr-2 h-4 w-4 text-primary" />
{appointment.patient.full_name}
</div>
<div className="flex items-center text-sm text-muted-foreground">
<Clock className="mr-2 h-4 w-4" />
{isValid(scheduledAtDate)
? format(scheduledAtDate, "HH:mm")
: "--:--"}
</div>
</div>
{/* Coluna 2: Médico / local / telefone */}
<div className="col-span-1 flex flex-col gap-2">
<div className="flex items-center text-sm text-muted-foreground">
<User className="mr-2 h-4 w-4" />
{appointment.doctor.full_name}
</div>
<div className="flex items-center text-sm text-muted-foreground">
<MapPin className="mr-2 h-4 w-4" />
{appointment.doctor.location ||
"Local a definir"}
</div>
<div className="flex items-center text-sm text-muted-foreground">
<Phone className="mr-2 h-4 w-4" />
{appointment.doctor.phone || "N/A"}
</div>
<div>{getStatusBadge(appointment.status)}</div>
</div>
{/* Coluna 3: Ações */}
<div className="col-span-1 flex justify-start md:justify-end">
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => handleEdit(appointment)}
>
<Pencil className="mr-2 h-4 w-4" />
Editar
</Button>
<Button
variant="destructive"
size="sm"
onClick={() => handleDelete(appointment)}
>
<Trash2 className="mr-2 h-4 w-4" />
Cancelar
</Button>
</div>
</div>
</CardContent>
</Card>
);
})}
</div>
<Separator className="my-6" />
</div>
)
)
)}
</div>
</div>
{/* MODAL DE EDIÇÃO */}
<Dialog open={editModal} onOpenChange={setEditModal}>
{/* Modal de edição permanece o mesmo, adicione o DialogContent se precisar */}
{/* Aqui estou assumindo que você tem o conteúdo do Dialog no seu código original ou em outro lugar, pois ele não estava completo no snippet anterior */}
</Dialog>
{/* Modal de Deleção */}
<Dialog open={deleteModal} onOpenChange={setDeleteModal}>
{/* Modal de deleção permanece o mesmo */}
</Dialog>
</div>
</Sidebar>
);
}
const getStatusBadge = (status: string) => {
switch (status) {
case "requested":
return (
<Badge className="bg-yellow-400/10 text-yellow-400">Solicitada</Badge>
);
case "confirmed":
return <Badge className="bg-primary/10 text-primary">Confirmada</Badge>;
case "checked_in":
return (
<Badge className="bg-indigo-400/10 text-indigo-400">Check-in</Badge>
);
case "completed":
return <Badge className="bg-green-400/10 text-green-400">Realizada</Badge>;
case "cancelled":
return (
<Badge className="bg-destructive/10 text-destructive">Cancelada</Badge>
);
case "no_show":
return (
<Badge className="bg-muted text-foreground">Não Compareceu</Badge>
);
default:
return <Badge variant="secondary">{status}</Badge>;
}
};

View File

@ -1,305 +0,0 @@
"use client";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Calendar, Clock, User, Plus } from "lucide-react";
import Link from "next/link";
import React, { useState, useEffect } from "react";
import { patientsService } from "@/services/patientsApi.mjs";
import { appointmentsService } from "@/services/appointmentsApi.mjs";
import Sidebar from "@/components/Sidebar";
export default function SecretaryDashboard() {
// Estados
const [patients, setPatients] = useState<any[]>([]);
const [loadingPatients, setLoadingPatients] = useState(true);
const [firstConfirmed, setFirstConfirmed] = useState<any>(null);
const [nextAgendada, setNextAgendada] = useState<any>(null);
const [loadingAppointments, setLoadingAppointments] = useState(true);
// 🔹 Buscar pacientes
useEffect(() => {
async function fetchPatients() {
try {
const data = await patientsService.list();
if (Array.isArray(data)) {
setPatients(data.slice(0, 3));
}
} catch (error) {
console.error("Erro ao carregar pacientes:", error);
} finally {
setLoadingPatients(false);
}
}
fetchPatients();
}, []);
// 🔹 Buscar consultas (confirmadas + 1ª do mês)
useEffect(() => {
async function fetchAppointments() {
try {
const hoje = new Date();
const inicioMes = new Date(hoje.getFullYear(), hoje.getMonth(), 1);
const fimMes = new Date(hoje.getFullYear(), hoje.getMonth() + 1, 0);
// Mesmo parâmetro de ordenação da página /secretary/appointments
const queryParams = "order=scheduled_at.desc";
const data = await appointmentsService.search_appointment(queryParams);
if (!Array.isArray(data) || data.length === 0) {
setFirstConfirmed(null);
setNextAgendada(null);
return;
}
// 🩵 1⃣ Consultas confirmadas (para o card “Próxima Consulta Confirmada”)
const confirmadas = data.filter((apt: any) => {
const dataConsulta = new Date(apt.scheduled_at || apt.date);
return apt.status === "confirmed" && dataConsulta >= hoje;
});
confirmadas.sort(
(a: any, b: any) =>
new Date(a.scheduled_at || a.date).getTime() -
new Date(b.scheduled_at || b.date).getTime()
);
setFirstConfirmed(confirmadas[0] || null);
// 💙 2⃣ Consultas deste mês — pegar sempre a 1ª (mais próxima)
const consultasMes = data.filter((apt: any) => {
const dataConsulta = new Date(apt.scheduled_at);
return dataConsulta >= inicioMes && dataConsulta <= fimMes;
});
if (consultasMes.length > 0) {
consultasMes.sort(
(a: any, b: any) =>
new Date(a.scheduled_at).getTime() -
new Date(b.scheduled_at).getTime()
);
setNextAgendada(consultasMes[0]);
} else {
setNextAgendada(null);
}
} catch (error) {
console.error("Erro ao carregar consultas:", error);
} finally {
setLoadingAppointments(false);
}
}
fetchAppointments();
}, []);
return (
<Sidebar>
<div className="space-y-6">
{/* Cabeçalho */}
<div>
<h1 className="text-3xl font-bold">Dashboard</h1>
<p className="text-muted-foreground">
Bem-vindo ao seu portal de consultas médicas
</p>
</div>
{/* Cards principais */}
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{/* Próxima Consulta Confirmada */}
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Próxima Consulta Confirmada
</CardTitle>
<Calendar className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
{loadingAppointments ? (
<div className="text-muted-foreground text-sm">
Carregando próxima consulta...
</div>
) : firstConfirmed ? (
<>
<div className="text-2xl font-bold">
{new Date(
firstConfirmed.scheduled_at || firstConfirmed.date
).toLocaleDateString("pt-BR")}
</div>
<p className="text-xs text-muted-foreground">
{firstConfirmed.doctor_name
? `Dr(a). ${firstConfirmed.doctor_name}`
: "Médico não informado"}{" "}
-{" "}
{new Date(firstConfirmed.scheduled_at).toLocaleTimeString(
"pt-BR",
{
hour: "2-digit",
minute: "2-digit",
}
)}
</p>
</>
) : (
<div className="text-sm text-muted-foreground">
Nenhuma consulta confirmada encontrada
</div>
)}
</CardContent>
</Card>
{/* Consultas Este Mês */}
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Consultas Este Mês
</CardTitle>
<Clock className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
{loadingAppointments ? (
<div className="text-muted-foreground text-sm">
Carregando consultas...
</div>
) : nextAgendada ? (
<>
<div className="text-lg font-bold">
{new Date(nextAgendada.scheduled_at).toLocaleDateString(
"pt-BR",
{
day: "2-digit",
month: "2-digit",
year: "numeric",
}
)}{" "}
às{" "}
{new Date(nextAgendada.scheduled_at).toLocaleTimeString(
"pt-BR",
{
hour: "2-digit",
minute: "2-digit",
}
)}
</div>
<p className="text-xs text-muted-foreground">
{nextAgendada.doctor_name
? `Dr(a). ${nextAgendada.doctor_name}`
: "Médico não informado"}
</p>
<p className="text-xs text-muted-foreground">
{nextAgendada.patient_name
? `Paciente: ${nextAgendada.patient_name}`
: ""}
</p>
</>
) : (
<div className="text-sm text-muted-foreground">
Nenhuma consulta agendada neste mês
</div>
)}
</CardContent>
</Card>
{/* Perfil */}
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Perfil</CardTitle>
<User className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">100%</div>
<p className="text-xs text-muted-foreground">Dados completos</p>
</CardContent>
</Card>
</div>
{/* Cards Secundários */}
<div className="grid md:grid-cols-2 gap-6">
{/* Ações rápidas */}
<Card>
<CardHeader>
<CardTitle>Ações Rápidas</CardTitle>
<CardDescription>
Acesse rapidamente as principais funcionalidades
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<Link href="/secretary/schedule">
<Button className="w-full justify-start bg-primary text-primary-foreground hover:bg-primary/90">
<User className="mr-2 h-4 w-4" />
Agendar Nova Consulta
</Button>
</Link>
<Link href="/secretary/appointments">
<Button
variant="outline"
className="w-full justify-start bg-transparent"
>
<Calendar className="mr-2 h-4 w-4" />
Ver Consultas
</Button>
</Link>
<Link href="/secretary/pacientes">
<Button
variant="outline"
className="w-full justify-start bg-transparent"
>
<User className="mr-2 h-4 w-4" />
Gerenciar Pacientes
</Button>
</Link>
</CardContent>
</Card>
{/* Pacientes */}
<Card>
<CardHeader>
<CardTitle>Pacientes</CardTitle>
<CardDescription>Últimos pacientes cadastrados</CardDescription>
</CardHeader>
<CardContent>
{loadingPatients ? (
<p className="text-sm text-muted-foreground">Carregando pacientes...</p>
) : patients.length === 0 ? (
<p className="text-sm text-muted-foreground">
Nenhum paciente cadastrado.
</p>
) : (
<div className="space-y-4">
{patients.map((patient, index) => (
<div
key={index}
className="flex items-center justify-between p-3 bg-primary/10 rounded-lg border border-primary/20"
>
<div>
<p className="font-medium text-foreground">
{patient.full_name || "Sem nome"}
</p>
<p className="text-sm text-muted-foreground">
{patient.phone_mobile ||
patient.phone1 ||
"Sem telefone"}
</p>
</div>
<div className="text-right">
<p className="font-medium text-primary">
{patient.convenio || "Particular"}
</p>
</div>
</div>
))}
</div>
)}
</CardContent>
</Card>
</div>
</div>
</Sidebar>
);
}

View File

@ -1,31 +0,0 @@
// Caminho: app/(secretary)/login/page.tsx
import { LoginForm } from "@/components/LoginForm";
import Link from "next/link"; // Adicionado para o link de "Voltar"
export default function SecretaryLoginPage() {
// NOTA: Esta página se tornou obsoleta com a criação do /login central.
// O ideal no futuro é deletar esta página e redirecionar os usuários.
return (
<div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-blue-50 flex items-center justify-center p-4">
<div className="w-full max-w-md text-center">
<h1 className="text-3xl font-bold text-foreground mb-2">Área da Secretária</h1>
<p className="text-muted-foreground mb-8">Acesse o sistema de gerenciamento</p>
{/* --- ALTERAÇÃO PRINCIPAL AQUI --- */}
{/* Chamando o LoginForm unificado sem props desnecessárias */}
<LoginForm>
{/* Adicionamos um link de "Voltar" como filho (children) */}
<div className="mt-6 text-center text-sm">
<Link href="/">
<span className="font-semibold text-primary hover:underline cursor-pointer">
Voltar à página inicial
</span>
</Link>
</div>
</LoginForm>
</div>
</div>
);
}

View File

@ -1,675 +0,0 @@
"use client";
import type React from "react";
import { useState, useEffect, useRef } from "react";
import { useRouter, useParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { ArrowLeft, Save, Trash2, Paperclip, Upload } from "lucide-react";
import Link from "next/link";
import { useToast } from "@/hooks/use-toast";
import { patientsService } from "@/services/patientsApi.mjs";
import Sidebar from "@/components/Sidebar";
export default function EditarPacientePage() {
const router = useRouter();
const params = useParams();
const patientId = params.id;
const { toast } = useToast();
// Photo upload state
const fileInputRef = useRef<HTMLInputElement | null>(null);
const [isUploadingPhoto, setIsUploadingPhoto] = useState(false);
const [photoUrl, setPhotoUrl] = useState<string | null>(null);
// Anexos state
const [anexos, setAnexos] = useState<any[]>([]);
const [isUploadingAnexo, setIsUploadingAnexo] = useState(false);
const anexoInputRef = useRef<HTMLInputElement | null>(null);
type FormData = {
nome: string; // full_name
cpf: string;
dataNascimento: string; // birth_date
sexo: string; // sex
id?: string;
nomeSocial?: string; // social_name
rg?: string;
documentType?: string; // document_type
documentNumber?: string; // document_number
ethnicity?: string;
race?: string;
naturality?: string;
nationality?: string;
profession?: string;
maritalStatus?: string; // marital_status
motherName?: string; // mother_name
motherProfession?: string; // mother_profession
fatherName?: string; // father_name
fatherProfession?: string; // father_profession
guardianName?: string; // guardian_name
guardianCpf?: string; // guardian_cpf
spouseName?: string; // spouse_name
rnInInsurance?: boolean; // rn_in_insurance
legacyCode?: string; // legacy_code
notes?: string;
email?: string;
phoneMobile?: string; // phone_mobile
phone1?: string;
phone2?: string;
cep?: string;
street?: string;
number?: string;
complement?: string;
neighborhood?: string;
city?: string;
state?: string;
reference?: string;
vip?: boolean;
lastVisitAt?: string;
nextAppointmentAt?: string;
createdAt?: string;
updatedAt?: string;
createdBy?: string;
updatedBy?: string;
weightKg?: string;
heightM?: string;
bmi?: string;
bloodType?: string;
// Adicionei os campos do convênio para o tipo FormData
convenio?: string;
plano?: string;
numeroMatricula?: string;
validadeCarteira?: string;
alergias?: string;
};
const [formData, setFormData] = useState<FormData>({
nome: "",
cpf: "",
dataNascimento: "",
sexo: "",
id: "",
nomeSocial: "",
rg: "",
documentType: "",
documentNumber: "",
ethnicity: "",
race: "",
naturality: "",
nationality: "",
profession: "",
maritalStatus: "",
motherName: "",
motherProfession: "",
fatherName: "",
fatherProfession: "",
guardianName: "",
guardianCpf: "",
spouseName: "",
rnInInsurance: false,
legacyCode: "",
notes: "",
email: "",
phoneMobile: "",
phone1: "",
phone2: "",
cep: "",
street: "",
number: "",
complement: "",
neighborhood: "",
city: "",
state: "",
reference: "",
vip: false,
lastVisitAt: "",
nextAppointmentAt: "",
createdAt: "",
updatedAt: "",
createdBy: "",
updatedBy: "",
weightKg: "",
heightM: "",
bmi: "",
bloodType: "",
convenio: "",
plano: "",
numeroMatricula: "",
validadeCarteira: "",
alergias: "",
});
const [isGuiaConvenio, setIsGuiaConvenio] = useState(false);
const [validadeIndeterminada, setValidadeIndeterminada] = useState(false);
useEffect(() => {
async function fetchPatient() {
try {
const res = await patientsService.getById(patientId);
// Map API snake_case/nested to local camelCase form
setFormData({
id: res[0]?.id ?? "",
nome: res[0]?.full_name ?? "",
nomeSocial: res[0]?.social_name ?? "",
cpf: res[0]?.cpf ?? "",
rg: res[0]?.rg ?? "",
documentType: res[0]?.document_type ?? "",
documentNumber: res[0]?.document_number ?? "",
sexo: res[0]?.sex ?? "",
dataNascimento: res[0]?.birth_date ?? "",
ethnicity: res[0]?.ethnicity ?? "",
race: res[0]?.race ?? "",
naturality: res[0]?.naturality ?? "",
nationality: res[0]?.nationality ?? "",
profession: res[0]?.profession ?? "",
maritalStatus: res[0]?.marital_status ?? "",
motherName: res[0]?.mother_name ?? "",
motherProfession: res[0]?.mother_profession ?? "",
fatherName: res[0]?.father_name ?? "",
fatherProfession: res[0]?.father_profession ?? "",
guardianName: res[0]?.guardian_name ?? "",
guardianCpf: res[0]?.guardian_cpf ?? "",
spouseName: res[0]?.spouse_name ?? "",
rnInInsurance: res[0]?.rn_in_insurance ?? false,
legacyCode: res[0]?.legacy_code ?? "",
notes: res[0]?.notes ?? "",
email: res[0]?.email ?? "",
phoneMobile: res[0]?.phone_mobile ?? "",
phone1: res[0]?.phone1 ?? "",
phone2: res[0]?.phone2 ?? "",
cep: res[0]?.cep ?? "",
street: res[0]?.street ?? "",
number: res[0]?.number ?? "",
complement: res[0]?.complement ?? "",
neighborhood: res[0]?.neighborhood ?? "",
city: res[0]?.city ?? "",
state: res[0]?.state ?? "",
reference: res[0]?.reference ?? "",
vip: res[0]?.vip ?? false,
lastVisitAt: res[0]?.last_visit_at ?? "",
nextAppointmentAt: res[0]?.next_appointment_at ?? "",
createdAt: res[0]?.created_at ?? "",
updatedAt: res[0]?.updated_at ?? "",
createdBy: res[0]?.created_by ?? "",
updatedBy: res[0]?.updated_by ?? "",
weightKg: res[0]?.weight_kg ? String(res[0].weight_kg) : "",
heightM: res[0]?.height_m ? String(res[0].height_m) : "",
bmi: res[0]?.bmi ? String(res[0].bmi) : "",
bloodType: res[0]?.blood_type ?? "",
// Os campos de convênio e alergias não vêm da API, então os deixamos vazios ou com valores padrão
convenio: "",
plano: "",
numeroMatricula: "",
validadeCarteira: "",
alergias: "",
});
} catch (e: any) {
toast({ title: "Erro", description: e?.message || "Falha ao carregar paciente" });
}
}
fetchPatient();
}, [patientId, toast]);
const handleInputChange = (field: string, value: string) => {
setFormData((prev) => ({ ...prev, [field]: value }));
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
// Build API payload (snake_case)
const payload = {
full_name: formData.nome || null,
cpf: formData.cpf || null,
email: formData.email || null,
phone_mobile: formData.phoneMobile || null,
birth_date: formData.dataNascimento || null,
social_name: formData.nomeSocial || null,
sex: formData.sexo || null,
blood_type: formData.bloodType || null,
weight_kg: formData.weightKg ? Number(formData.weightKg) : null,
height_m: formData.heightM ? Number(formData.heightM) : null,
street: formData.street || null,
number: formData.number || null,
complement: formData.complement || null,
neighborhood: formData.neighborhood || null,
city: formData.city || null,
state: formData.state || null,
cep: formData.cep || null,
};
try {
await patientsService.update(patientId, payload);
toast({
title: "Sucesso",
description: "Paciente atualizado com sucesso",
variant: "default"
});
router.push("/secretary/pacientes");
} catch (err: any) {
console.error("Erro ao atualizar paciente:", err);
toast({
title: "Erro",
description: err?.message || "Não foi possível atualizar o paciente",
variant: "destructive"
});
}
};
return (
<Sidebar>
{/* O espaçamento foi reduzido aqui: de `p-4 sm:p-6 lg:p-8` para `p-2 sm:p-4 lg:p-6` */}
<div className="space-y-6 p-2 sm:p-4 lg:p-6 max-w-10xl mx-auto">{/* Alterado padding responsivo */}
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div className="flex items-center gap-4">
<Link href="/secretary/pacientes">
<Button variant="ghost" size="sm">
<ArrowLeft className="w-4 h-4 mr-2" />
Voltar
</Button>
</Link>
<div>
<h1 className="text-2xl font-bold">Editar Paciente</h1>
<p className="text-muted-foreground">Atualize as informações do paciente</p>
</div>
</div>
{/* Espaço reservado para anexos ou ações futuras */}
</div>
<form onSubmit={handleSubmit} className="space-y-8">
{/* Dados Pessoais Section */}
<div className="bg-card rounded-lg border p-6">
<h2 className="text-lg font-semibold mb-6">Dados Pessoais</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{/* Photo upload */}
<div className="space-y-2 col-span-1 md:col-span-2 lg:col-span-1">
<Label>Foto do paciente</Label>
<div className="flex flex-col sm:flex-row items-center gap-4">
<div className="w-20 h-20 rounded-full bg-muted overflow-hidden flex items-center justify-center">
{photoUrl ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={photoUrl} alt="Foto do paciente" className="w-full h-full object-cover" />
) : (
<span className="text-muted-foreground text-sm text-center">Sem foto</span>
)}
</div>
<div className="flex flex-col sm:flex-row gap-2 mt-2 sm:mt-0">
<input ref={fileInputRef} type="file" accept="image/*" className="hidden" />
<Button type="button" variant="outline" disabled={isUploadingPhoto}>
{isUploadingPhoto ? "Enviando..." : "Enviar foto"}
</Button>
{photoUrl && (
<Button type="button" variant="ghost" disabled={isUploadingPhoto}>
Remover
</Button>
)}
</div>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="nome">Nome *</Label>
<Input id="nome" value={formData.nome} onChange={(e) => handleInputChange("nome", e.target.value)} required />
</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" 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 className="space-y-2">
<Label>Sexo *</Label>
<div className="flex flex-col sm:flex-row gap-4">
<div className="flex items-center space-x-2">
<input type="radio" id="Masculino" name="sexo" value="Masculino" checked={formData.sexo === "Masculino"} onChange={(e) => handleInputChange("sexo", e.target.value)} className="w-4 h-4 text-primary" />
<Label htmlFor="Masculino">Masculino</Label>
</div>
<div className="flex items-center space-x-2">
<input type="radio" id="Feminino" name="sexo" value="Feminino" checked={formData.sexo === "Feminino"} onChange={(e) => handleInputChange("sexo", e.target.value)} className="w-4 h-4 text-primary" />
<Label htmlFor="Feminino">Feminino</Label>
</div>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="dataNascimento">Data de nascimento *</Label>
<Input id="dataNascimento" type="date" value={formData.dataNascimento} onChange={(e) => handleInputChange("dataNascimento", e.target.value)} required />
</div>
<div className="space-y-2">
<Label htmlFor="etnia">Etnia</Label>
<Select value={formData.ethnicity} onValueChange={(value) => handleInputChange("ethnicity", value)}>
<SelectTrigger>
<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 className="space-y-2">
<Label htmlFor="raca">Raça</Label>
<Select value={formData.race} onValueChange={(value) => handleInputChange("race", value)}>
<SelectTrigger>
<SelectValue placeholder="Selecione" />
</SelectTrigger>
<SelectContent>
<SelectItem value="caucasiana">Caucasiana</SelectItem>
<SelectItem value="negroide">Negroide</SelectItem>
<SelectItem value="mongoloide">Mongoloide</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="naturalidade">Naturalidade</Label>
<Input id="naturalidade" value={formData.naturality} onChange={(e) => handleInputChange("naturality", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="nacionalidade">Nacionalidade</Label>
<Select value={formData.nationality} onValueChange={(value) => handleInputChange("nationality", value)}>
<SelectTrigger>
<SelectValue placeholder="Selecione" />
</SelectTrigger>
<SelectContent>
<SelectItem value="brasileira">Brasileira</SelectItem>
<SelectItem value="estrangeira">Estrangeira</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="profissao">Profissão</Label>
<Input id="profissao" value={formData.profession} onChange={(e) => handleInputChange("profissao", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="estadoCivil">Estado civil</Label>
<Select value={formData.maritalStatus} onValueChange={(value) => handleInputChange("maritalStatus", value)}>
<SelectTrigger>
<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 className="space-y-2">
<Label htmlFor="nomeMae">Nome da mãe</Label>
<Input id="nomeMae" value={formData.motherName} onChange={(e) => handleInputChange("motherName", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="profissaoMae">Profissão da mãe</Label>
<Input id="profissaoMae" value={formData.motherProfession} onChange={(e) => handleInputChange("motherProfession", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="nomePai">Nome do pai</Label>
<Input id="nomePai" value={formData.fatherName} onChange={(e) => handleInputChange("fatherName", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="profissaoPai">Profissão do pai</Label>
<Input id="profissaoPai" value={formData.fatherProfession} onChange={(e) => handleInputChange("fatherProfession", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="nomeResponsavel">Nome do responsável</Label>
<Input id="nomeResponsavel" value={formData.guardianName} onChange={(e) => handleInputChange("guardianName", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="cpfResponsavel">CPF do responsável</Label>
<Input id="cpfResponsavel" value={formData.guardianCpf} onChange={(e) => handleInputChange("guardianCpf", e.target.value)} placeholder="000.000.000-00" />
</div>
<div className="space-y-2">
<Label htmlFor="nomeEsposo">Nome do esposo(a)</Label>
<Input id="nomeEsposo" value={formData.spouseName} onChange={(e) => handleInputChange("spouseName", e.target.value)} />
</div>
</div>
<div className="mt-6">
<div className="flex items-center space-x-2">
<Checkbox id="guiaConvenio" checked={isGuiaConvenio} onCheckedChange={(checked) => setIsGuiaConvenio(checked === true)} />
<Label htmlFor="guiaConvenio">RN na Guia do convênio</Label>
</div>
</div>
<div className="mt-6">
<Label htmlFor="observacoes">Observações</Label>
<Textarea id="observacoes" value={formData.notes} onChange={(e) => handleInputChange("notes", e.target.value)} placeholder="Digite observações sobre o paciente..." className="mt-2" />
</div>
</div>
{/* Contact Section */}
<div className="bg-card rounded-lg border p-6">
<h2 className="text-lg font-semibold mb-6">Contato</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<div className="space-y-2">
<Label htmlFor="email">E-mail *</Label>
<Input id="email" type="email" value={formData.email} onChange={(e) => handleInputChange("email", e.target.value)} required />
</div>
<div className="space-y-2">
<Label htmlFor="celular">Celular *</Label>
<Input id="celular" value={formData.phoneMobile} onChange={(e) => handleInputChange("phoneMobile", e.target.value)} placeholder="(00) 00000-0000" required />
</div>
<div className="space-y-2">
<Label htmlFor="telefone1">Telefone 1</Label>
<Input id="telefone1" value={formData.phone1} onChange={(e) => handleInputChange("phone1", e.target.value)} placeholder="(00) 0000-0000" />
</div>
<div className="space-y-2">
<Label htmlFor="telefone2">Telefone 2</Label>
<Input id="telefone2" value={formData.phone2} onChange={(e) => handleInputChange("phone2", e.target.value)} placeholder="(00) 0000-0000" />
</div>
</div>
</div>
{/* Address Section */}
<div className="bg-card rounded-lg border p-6">
<h2 className="text-lg font-semibold mb-6">Endereço</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<div className="space-y-2">
<Label htmlFor="cep">CEP</Label>
<Input id="cep" value={formData.cep} onChange={(e) => handleInputChange("cep", e.target.value)} placeholder="00000-000" />
</div>
<div className="space-y-2">
<Label htmlFor="endereco">Endereço</Label>
<Input id="endereco" value={formData.street} onChange={(e) => handleInputChange("street", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="numero">Número</Label>
<Input id="numero" value={formData.number} onChange={(e) => handleInputChange("number", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="complemento">Complemento</Label>
<Input id="complemento" value={formData.complement} onChange={(e) => handleInputChange("complement", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="bairro">Bairro</Label>
<Input id="bairro" value={formData.neighborhood} onChange={(e) => handleInputChange("neighborhood", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="cidade">Cidade</Label>
<Input id="cidade" value={formData.city} onChange={(e) => handleInputChange("city", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="estado">Estado</Label>
<Select value={formData.state} onValueChange={(value) => handleInputChange("state", value)}>
<SelectTrigger>
<SelectValue placeholder="Selecione" />
</SelectTrigger>
<SelectContent>
<SelectItem value="AC">Acre</SelectItem>
<SelectItem value="AL">Alagoas</SelectItem>
<SelectItem value="AP">Amapá</SelectItem>
<SelectItem value="AM">Amazonas</SelectItem>
<SelectItem value="BA">Bahia</SelectItem>
<SelectItem value="CE">Ceará</SelectItem>
<SelectItem value="DF">Distrito Federal</SelectItem>
<SelectItem value="ES">Espírito Santo</SelectItem>
<SelectItem value="GO">Goiás</SelectItem>
<SelectItem value="MA">Maranhão</SelectItem>
<SelectItem value="MT">Mato Grosso</SelectItem>
<SelectItem value="MS">Mato Grosso do Sul</SelectItem>
<SelectItem value="MG">Minas Gerais</SelectItem>
<SelectItem value="PA">Pará</SelectItem>
<SelectItem value="PB">Paraíba</SelectItem>
<SelectItem value="PR">Paraná</SelectItem>
<SelectItem value="PE">Pernambuco</SelectItem>
<SelectItem value="PI">Piauí</SelectItem>
<SelectItem value="RJ">Rio de Janeiro</SelectItem>
<SelectItem value="RN">Rio Grande do Norte</SelectItem>
<SelectItem value="RS">Rio Grande do Sul</SelectItem>
<SelectItem value="RO">Rondônia</SelectItem>
<SelectItem value="RR">Roraima</SelectItem>
<SelectItem value="SC">Santa Catarina</SelectItem>
<SelectItem value="SP">São Paulo</SelectItem>
<SelectItem value="SE">Sergipe</SelectItem>
<SelectItem value="TO">Tocantins</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</div>
{/* Medical Information Section */}
<div className="bg-card rounded-lg border p-6">
<h2 className="text-lg font-semibold mb-6">Informações Médicas</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<div className="space-y-2">
<Label htmlFor="tipoSanguineo">Tipo Sanguíneo</Label>
<Select value={formData.bloodType} onValueChange={(value) => handleInputChange("bloodType", value)}>
<SelectTrigger>
<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 className="space-y-2">
<Label htmlFor="peso">Peso (kg)</Label>
<Input id="peso" type="number" value={formData.weightKg} onChange={(e) => handleInputChange("weightKg", e.target.value)} placeholder="0.0" />
</div>
<div className="space-y-2">
<Label htmlFor="altura">Altura (m)</Label>
<Input id="altura" type="number" step="0.01" value={formData.heightM} onChange={(e) => handleInputChange("heightM", e.target.value)} placeholder="0.00" />
</div>
<div className="space-y-2">
<Label>IMC</Label>
<Input value={formData.weightKg && formData.heightM ? (Number.parseFloat(formData.weightKg) / Number.parseFloat(formData.heightM) ** 2).toFixed(2) : ""} disabled placeholder="Calculado automaticamente" />
</div>
</div>
<div className="mt-6">
<Label htmlFor="alergias">Alergias</Label>
<Textarea id="alergias" value={formData.alergias} onChange={(e) => handleInputChange("alergias", e.target.value)} placeholder="Ex: AAS, Dipirona, etc." className="mt-2" />
</div>
</div>
{/* Insurance Information Section */}
<div className="bg-card rounded-lg border p-6">
<h2 className="text-lg font-semibold mb-6">Informações de convênio</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<div className="space-y-2">
<Label htmlFor="convenio">Convênio</Label>
<Select value={formData.convenio} onValueChange={(value) => handleInputChange("convenio", value)}>
<SelectTrigger>
<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>
<SelectItem value="Amil">Amil</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="plano">Plano</Label>
<Input id="plano" value={formData.plano} onChange={(e) => handleInputChange("plano", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="numeroMatricula"> de matrícula</Label>
<Input id="numeroMatricula" value={formData.numeroMatricula} onChange={(e) => handleInputChange("numeroMatricula", e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="validadeCarteira">Validade da Carteira</Label>
<Input id="validadeCarteira" type="date" value={formData.validadeCarteira} onChange={(e) => handleInputChange("validadeCarteira", e.target.value)} disabled={validadeIndeterminada} />
</div>
</div>
<div className="mt-4">
<div className="flex items-center space-x-2">
<Checkbox id="validadeIndeterminada" checked={validadeIndeterminada} onCheckedChange={(checked) => setValidadeIndeterminada(checked === true)} />
<Label htmlFor="validadeIndeterminada">Validade Indeterminada</Label>
</div>
</div>
</div>
<div className="flex flex-col sm:flex-row justify-end gap-4">
<Link href="/secretary/pacientes">
<Button type="button" variant="outline" className="w-full sm:w-auto">
Cancelar
</Button>
</Link>
<Button type="submit" className="bg-primary hover:bg-primary/90 w-full sm:w-auto">
<Save className="w-4 h-4 mr-2" />
Salvar Alterações
</Button>
</div>
</form>
</div>
</Sidebar>
);
}

View File

@ -1,3 +0,0 @@
export default function Loading() {
return null
}

View File

@ -1,175 +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 { Save, Loader2 } from "lucide-react";
import { usersService } from "services/usersApi.mjs";
import Sidebar from "@/components/Sidebar";
// Interface simplificada para refletir apenas os campos necessários
interface UserFormData {
email: string;
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 [formData, setFormData] = useState<UserFormData>(defaultFormData);
const [isSaving, setIsSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleInputChange = (key: keyof UserFormData, value: string) => {
const updatedValue = key === "telefone" ? formatPhone(value) : value;
setFormData((prev) => ({ ...prev, [key]: updatedValue }));
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
// Validação simplificada
if (!formData.email || !formData.nomeCompleto || !formData.senha || !formData.confirmarSenha || !formData.cpf) {
setError("Por favor, preencha todos os campos obrigatórios.");
return;
}
if (formData.senha !== formData.confirmarSenha) {
setError("A Senha e a Confirmação de Senha não coincidem.");
return;
}
setIsSaving(true);
try {
// Payload agora é fixo para a role 'paciente'
const payload = {
full_name: formData.nomeCompleto,
email: formData.email.trim().toLowerCase(),
phone: formData.telefone || null,
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 paciente. Verifique os dados e tente novamente.");
} finally {
setIsSaving(false);
}
};
return (
<Sidebar>
{/* Container principal com padding responsivo e centralização */}
<div className="w-full h-full p-4 md:p-8 lg:p-12 flex justify-center items-start">
{/* Conteúdo do formulário com largura máxima para telas maiores */}
<div className="w-full max-w-screen-md lg:max-w-screen-lg space-y-8">
{/* Cabeçalho da página */}
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between border-b pb-4 gap-4"> {/* Ajustado para empilhar em telas pequenas */}
<div>
<h1 className="text-2xl sm:text-3xl font-extrabold text-gray-900">Novo Paciente</h1> {/* Tamanho de texto responsivo */}
<p className="text-sm sm:text-md text-gray-500">Preencha os dados para cadastrar um novo paciente no sistema.</p> {/* Tamanho de texto responsivo */}
</div>
<Link href="/secretary/pacientes">
<Button variant="outline" className="w-full sm:w-auto">Cancelar</Button> {/* Botão ocupa largura total em telas pequenas */}
</Link>
</div>
{/* Formulário */}
<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>
)}
{/* Campos do formulário em grid responsivo */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="space-y-2 md:col-span-2"> {/* Nome Completo ocupa 2 colunas em telas maiores */}
<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>
<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 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 md:col-span-2"> {/* CPF ocupa 2 colunas em telas maiores */}
<Label htmlFor="cpf">CPF *</Label>
<Input id="cpf" value={formData.cpf} onChange={(e) => handleInputChange("cpf", e.target.value)} placeholder="xxx.xxx.xxx-xx" required />
</div>
</div>
{/* Botões de ação */}
<div className="flex flex-col sm:flex-row justify-end gap-4 pt-6 border-t mt-6"> {/* Botões empilhados em telas pequenas */}
<Link href="/secretary/pacientes">
<Button type="button" variant="outline" disabled={isSaving} className="w-full sm:w-auto">
Cancelar
</Button>
</Link>
<Link href="/secretary/pacientes">
<Button type="submit" className="bg-green-600 hover:bg-green-700 w-full sm:w-auto" disabled={isSaving}>
{isSaving ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Save className="w-4 h-4 mr-2" />}
{isSaving ? "Salvando..." : "Salvar Paciente"}
</Button>
</Link>
</div>
</form>
</div>
</div>
</Sidebar>
);
}

View File

@ -1,590 +0,0 @@
// app/secretary/pacientes/page.tsx
"use client";
import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Plus, Edit, Trash2, Eye, Calendar, Filter, Loader2, MoreVertical } from "lucide-react";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { patientsService } from "@/services/patientsApi.mjs";
import Sidebar from "@/components/Sidebar";
// Defina o tamanho da página.
const PAGE_SIZE = 5;
export default function PacientesPage() {
// --- ESTADOS DE DADOS E GERAL ---
const [searchTerm, setSearchTerm] = useState("");
const [convenioFilter, setConvenioFilter] = useState("all");
const [vipFilter, setVipFilter] = useState("all");
// Lista completa, carregada da API uma única vez
const [allPatients, setAllPatients] = useState<any[]>([]);
// Lista após a aplicação dos filtros (base para a paginação)
const [filteredPatients, setFilteredPatients] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// --- ESTADOS DE PAGINAÇÃO ---
const [page, setPage] = useState(1);
// CÁLCULO DA PAGINAÇÃO
const totalPages = Math.ceil(filteredPatients.length / PAGE_SIZE);
const startIndex = (page - 1) * PAGE_SIZE;
const endIndex = startIndex + PAGE_SIZE;
// Pacientes a serem exibidos na tabela (aplicando a paginação)
const currentPatients = filteredPatients.slice(startIndex, endIndex);
// --- ESTADOS DE DIALOGS ---
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [patientToDelete, setPatientToDelete] = useState<string | null>(null);
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
const [patientDetails, setPatientDetails] = useState<any | null>(null);
// --- FUNÇÕES DE LÓGICA ---
// 1. Função para carregar TODOS os pacientes da API
const fetchAllPacientes = useCallback(
async () => {
setLoading(true);
setError(null);
try {
// Como o backend retorna um array, chamamos sem paginação
const res = await patientsService.list();
const mapped = res.map((p: any) => ({
id: String(p.id ?? ""),
nome: p.full_name ?? "—",
telefone: p.phone_mobile ?? p.phone1 ?? "—",
cidade: p.city ?? "—",
estado: p.state ?? "—",
// Formate as datas se necessário, aqui usamos como string
ultimoAtendimento: p.last_visit_at?.split('T')[0] ?? "—",
proximoAtendimento: p.next_appointment_at?.split('T')[0] ?? "—",
vip: Boolean(p.vip ?? false),
convenio: p.convenio ?? "Particular", // Define um valor padrão
status: p.status ?? undefined,
}));
setAllPatients(mapped);
} catch (e: any) {
console.error(e);
setError(e?.message || "Erro ao buscar pacientes");
} finally {
setLoading(false);
}
}, []);
// 2. Efeito para aplicar filtros e calcular a lista filtrada (chama-se quando allPatients ou filtros mudam)
useEffect(() => {
const filtered = allPatients.filter((patient) => {
// Filtro por termo de busca (Nome ou Telefone)
const matchesSearch =
patient.nome?.toLowerCase().includes(searchTerm.toLowerCase()) ||
patient.telefone?.includes(searchTerm);
// Filtro por Convênio
const matchesConvenio =
convenioFilter === "all" ||
patient.convenio === convenioFilter;
// Filtro por VIP
const matchesVip =
vipFilter === "all" ||
(vipFilter === "vip" && patient.vip) ||
(vipFilter === "regular" && !patient.vip);
return matchesSearch && matchesConvenio && matchesVip;
});
setFilteredPatients(filtered);
// Garante que a página atual seja válida após a filtragem
setPage(1);
}, [allPatients, searchTerm, convenioFilter, vipFilter]);
// 3. Efeito inicial para buscar os pacientes
useEffect(() => {
fetchAllPacientes();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// --- LÓGICA DE AÇÕES (DELETAR / VER DETALHES) ---
const openDetailsDialog = async (patientId: string) => {
setDetailsDialogOpen(true);
setPatientDetails(null);
try {
const res = await patientsService.getById(patientId);
setPatientDetails(Array.isArray(res) ? res[0] : res); // Supondo que retorne um array com um item
} catch (e: any) {
setPatientDetails({ error: e?.message || "Erro ao buscar detalhes" });
}
};
const handleDeletePatient = async (patientId: string) => {
try {
await patientsService.delete(patientId);
// Atualiza a lista completa para refletir a exclusão
setAllPatients((prev) =>
prev.filter((p) => String(p.id) !== String(patientId))
);
} catch (e: any) {
alert(`Erro ao deletar paciente: ${e?.message || "Erro desconhecido"}`);
}
setDeleteDialogOpen(false);
setPatientToDelete(null);
};
const openDeleteDialog = (patientId: string) => {
setPatientToDelete(patientId);
setDeleteDialogOpen(true);
};
return (
<Sidebar>
<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>
<h1 className="text-xl md:text-2xl font-bold">
Pacientes
</h1>
<p className="text-muted-foreground text-sm md:text-base">
Gerencie as informações de seus pacientes
</p>
</div>
<div className="flex gap-2">
<Link href="/secretary/pacientes/novo" className="w-full md:w-auto">
<Button className="w-full bg-primary hover:bg-primary/90">
<Plus className="w-4 h-4 mr-2" />
Adicionar
</Button>
</Link>
</div>
</div>
{/* Bloco de Filtros (Responsividade APLICADA) */}
<div className="flex flex-wrap items-center gap-4 bg-card p-4 rounded-lg border">
<Filter className="w-5 h-5 text-muted-foreground" />
{/* Busca - Ocupa 100% no mobile, depois cresce */}
<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 a largura total em telas pequenas, depois se ajusta */}
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[200px]">
<span className="text-sm font-medium whitespace-nowrap hidden md:block">
Convênio
</span>
<Select value={convenioFilter} onValueChange={setConvenioFilter}>
<SelectTrigger className="w-full sm:w-40">
{" "}
{/* w-full para mobile, w-40 para sm+ */}
<SelectValue placeholder="Convênio" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Todos</SelectItem>
<SelectItem value="Particular">Particular</SelectItem>
<SelectItem value="SUS">SUS</SelectItem>
<SelectItem value="Unimed">Unimed</SelectItem>
{/* Adicione outros convênios conforme necessário */}
</SelectContent>
</Select>
</div>
{/* VIP - Ocupa a largura total em telas pequenas, depois se ajusta */}
<div className="flex items-center gap-2 w-full sm:w-auto sm:flex-grow sm:max-w-[150px]">
<span className="text-sm font-medium whitespace-nowrap hidden md:block">VIP</span>
<Select value={vipFilter} onValueChange={setVipFilter}>
<SelectTrigger className="w-full sm:w-32"> {/* w-full para mobile, w-32 para sm+ */}
<SelectValue placeholder="VIP" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Todos</SelectItem>
<SelectItem value="vip">VIP</SelectItem>
<SelectItem value="regular">Regular</SelectItem>
</SelectContent>
</Select>
</div>
</div>
{/* --- SEÇÃO DE TABELA (VISÍVEL EM TELAS MAIORES OU IGUAIS A MD) --- */}
{/* Garantir que a tabela se esconda em telas menores e apareça em MD+ */}
<div className="bg-card rounded-lg border shadow-md hidden md:block">
<div className="overflow-x-auto">
{" "}
{/* Permite rolagem horizontal se a tabela for muito larga */}
{error ? (
<div className="p-6 text-destructive">{`Erro ao carregar pacientes: ${error}`}</div>
) : loading ? (
<div className="p-6 text-center text-muted-foreground flex items-center justify-center">
<Loader2 className="w-6 h-6 mr-2 animate-spin text-primary" />{" "}
Carregando pacientes...
</div>
) : (
<table className="w-full min-w-[650px]">
{" "}
{/* min-w para evitar que a tabela se contraia demais */}
<thead className="bg-muted border-b">
<tr>
<th className="text-left p-4 font-medium text-muted-foreground w-[20%]">
Nome
</th>
{/* Ajustes de visibilidade de colunas para diferentes breakpoints */}
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden sm:table-cell">
Telefone
</th>
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden md:table-cell">
Cidade / Estado
</th>
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden sm:table-cell">
Convênio
</th>
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden lg:table-cell">
Último atendimento
</th>
<th className="text-left p-4 font-medium text-muted-foreground w-[15%] hidden lg:table-cell">
Próximo atendimento
</th>
<th className="text-left p-4 font-medium text-muted-foreground w-[5%]">
Ações
</th>
</tr>
</thead>
<tbody>
{currentPatients.length === 0 ? (
<tr>
<td colSpan={7} className="p-8 text-center text-muted-foreground">
{allPatients.length === 0
? "Nenhum paciente cadastrado"
: "Nenhum paciente encontrado com os filtros aplicados"}
</td>
</tr>
) : (
currentPatients.map((patient) => (
<tr
key={patient.id}
className="border-b hover:bg-muted"
>
<td className="p-4">
<div className="flex items-center gap-3">
<div className="w-8 h-8 bg-primary/10 rounded-full flex items-center justify-center">
<span className="text-primary font-medium text-sm">
{patient.nome?.charAt(0) || "?"}
</span>
</div>
<span className="font-medium">
{patient.nome}
{patient.vip && (
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-500 bg-purple-500/10 rounded-full">
VIP
</span>
)}
</span>
</div>
</td>
<td className="p-4 text-muted-foreground hidden sm:table-cell">
{patient.telefone}
</td>
<td className="p-4 text-muted-foreground hidden md:table-cell">{`${patient.cidade} / ${patient.estado}`}</td>
<td className="p-4 text-muted-foreground hidden sm:table-cell">
{patient.convenio}
</td>
<td className="p-4 text-muted-foreground hidden lg:table-cell">
{patient.ultimoAtendimento}
</td>
<td className="p-4 text-muted-foreground hidden lg:table-cell">
{patient.proximoAtendimento}
</td>
<td className="p-4">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0">
<span className="sr-only">Abrir menu</span>
<MoreVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={() =>
openDetailsDialog(String(patient.id))
}
>
<Eye className="w-4 h-4 mr-2" />
Ver detalhes
</DropdownMenuItem>
<DropdownMenuItem asChild>
<Link
href={`/secretary/pacientes/${patient.id}/editar`}
className="flex items-center w-full"
>
<Edit className="w-4 h-4 mr-2" />
Editar
</Link>
</DropdownMenuItem>
<DropdownMenuItem>
<Calendar className="w-4 h-4 mr-2" />
Marcar consulta
</DropdownMenuItem>
<DropdownMenuItem
className="text-destructive"
onClick={() =>
openDeleteDialog(String(patient.id))
}
>
<Trash2 className="w-4 h-4 mr-2" />
Excluir
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</td>
</tr>
))
)}
</tbody>
</table>
)}
</div>
</div>
{/* --- SEÇÃO DE CARDS (VISÍVEL APENAS EM TELAS MENORES QUE MD) --- */}
{/* Garantir que os cards apareçam em telas menores e se escondam em MD+ */}
<div className="bg-card rounded-lg border shadow-md p-4 block md:hidden">
{error ? (
<div className="p-6 text-destructive">{`Erro ao carregar pacientes: ${error}`}</div>
) : loading ? (
<div className="p-6 text-center text-muted-foreground flex items-center justify-center">
<Loader2 className="w-6 h-6 mr-2 animate-spin text-primary" />{" "}
Carregando pacientes...
</div>
) : filteredPatients.length === 0 ? (
<div className="p-8 text-center text-muted-foreground">
{allPatients.length === 0
? "Nenhum paciente cadastrado"
: "Nenhum paciente encontrado com os filtros aplicados"}
</div>
) : (
<div className="space-y-4">
{currentPatients.map((patient) => (
<div
key={patient.id}
className="bg-muted rounded-lg p-4 flex flex-col sm:flex-row justify-between items-start sm:items-center border"
>
<div className="flex-grow mb-2 sm:mb-0">
<div className="font-semibold text-lg flex items-center">
{patient.nome}
{patient.vip && (
<span className="ml-2 px-2 py-0.5 text-xs font-semibold text-purple-500 bg-purple-500/10 rounded-full">
VIP
</span>
)}
</div>
<div className="text-sm text-muted-foreground">
Telefone: {patient.telefone}
</div>
<div className="text-sm text-muted-foreground">
Convênio: {patient.convenio}
</div>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<div className="w-full">
<Button variant="outline" className="w-full">
Ações
</Button>
</div>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={() => openDetailsDialog(String(patient.id))}
>
<Eye className="w-4 h-4 mr-2" />
Ver detalhes
</DropdownMenuItem>
<DropdownMenuItem asChild>
<Link href={`/secretary/pacientes/${patient.id}/editar`} className="flex items-center w-full">
<Edit className="w-4 h-4 mr-2" />
Editar
</Link>
</DropdownMenuItem>
<DropdownMenuItem>
<Calendar className="w-4 h-4 mr-2" />
Marcar consulta
</DropdownMenuItem>
<DropdownMenuItem className="text-destructive" onClick={() => openDeleteDialog(String(patient.id))}>
<Trash2 className="w-4 h-4 mr-2" />
Excluir
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
))}
</div>
)}
</div>
{/* Paginação */}
{totalPages > 1 && !loading && (
<div className="flex flex-col sm:flex-row items-center justify-center p-4 border-t">
<div className="flex space-x-2 flex-wrap justify-center"> {/* Adicionado flex-wrap e justify-center para botões da paginação */}
<Button
onClick={() => setPage((prev) => Math.max(1, prev - 1))}
disabled={page === 1}
variant="outline"
size="lg"
>
&lt; 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"
className={pageNumber === page ? "bg-primary hover:bg-primary/90 text-primary-foreground" : "text-muted-foreground"}
>
{pageNumber}
</Button>
))}
<Button
onClick={() => setPage((prev) => Math.min(totalPages, prev + 1))}
disabled={page === totalPages}
variant="outline"
size="lg"
>
Próximo &gt;
</Button>
</div>
</div>
)}
{/* AlertDialogs (Permanecem os mesmos) */}
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
<AlertDialogDescription>Tem certeza que deseja excluir este paciente? Esta ação não pode ser desfeita.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancelar</AlertDialogCancel>
<AlertDialogAction onClick={() => patientToDelete && handleDeletePatient(patientToDelete)} className="bg-destructive hover:bg-destructive/90">
Excluir
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<AlertDialog
open={detailsDialogOpen}
onOpenChange={setDetailsDialogOpen}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Detalhes do Paciente</AlertDialogTitle>
<AlertDialogDescription>
{patientDetails === null ? (
<div className="text-muted-foreground">
<Loader2 className="w-6 h-6 animate-spin mx-auto text-primary my-4" />
Carregando...
</div>
) : patientDetails?.error ? (
<div className="text-destructive p-4">{patientDetails.error}</div>
) : (
<div className="grid gap-4 py-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<p className="font-semibold">Nome Completo</p>
<p>{patientDetails.full_name}</p>
</div>
<div>
<p className="font-semibold">Email</p>
<p>{patientDetails.email}</p>
</div>
<div>
<p className="font-semibold">Telefone</p>
<p>{patientDetails.phone_mobile}</p>
</div>
<div>
<p className="font-semibold">Data de Nascimento</p>
<p>{patientDetails.birth_date}</p>
</div>
<div>
<p className="font-semibold">CPF</p>
<p>{patientDetails.cpf}</p>
</div>
<div>
<p className="font-semibold">Tipo Sanguíneo</p>
<p>{patientDetails.blood_type}</p>
</div>
<div>
<p className="font-semibold">Peso (kg)</p>
<p>{patientDetails.weight_kg}</p>
</div>
<div>
<p className="font-semibold">Altura (m)</p>
<p>{patientDetails.height_m}</p>
</div>
</div>
<div className="border-t pt-4 mt-4">
<h3 className="font-semibold mb-2">Endereço</h3>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<p className="font-semibold">Rua</p>
<p>{`${patientDetails.street}, ${patientDetails.number}`}</p>
</div>
<div>
<p className="font-semibold">Complemento</p>
<p>{patientDetails.complement}</p>
</div>
<div>
<p className="font-semibold">Bairro</p>
<p>{patientDetails.neighborhood}</p>
</div>
<div>
<p className="font-semibold">Cidade</p>
<p>{patientDetails.cidade}</p>
</div>
<div>
<p className="font-semibold">Estado</p>
<p>{patientDetails.estado}</p>
</div>
<div>
<p className="font-semibold">CEP</p>
<p>{patientDetails.cep}</p>
</div>
</div>
</div>
</div>
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Fechar</AlertDialogCancel>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</Sidebar>
);
}

View File

@ -1,11 +0,0 @@
import Sidebar from "@/components/Sidebar";
import ScheduleForm from "@/components/schedule/schedule-form";
export default function SecretaryAppointments() {
return (
<Sidebar>
<ScheduleForm />
</Sidebar>
);
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 828 B

View File

@ -0,0 +1 @@
<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" width="50px" height="50px"> <path d="M47.16,21.221l-5.91-0.966c-0.346-1.186-0.819-2.326-1.411-3.405l3.45-4.917c0.279-0.397,0.231-0.938-0.112-1.282 l-3.889-3.887c-0.347-0.346-0.893-0.391-1.291-0.104l-4.843,3.481c-1.089-0.602-2.239-1.08-3.432-1.427l-1.031-5.886 C28.607,2.35,28.192,2,27.706,2h-5.5c-0.49,0-0.908,0.355-0.987,0.839l-0.956,5.854c-1.2,0.345-2.352,0.818-3.437,1.412l-4.83-3.45 c-0.399-0.285-0.942-0.239-1.289,0.106L6.82,10.648c-0.343,0.343-0.391,0.883-0.112,1.28l3.399,4.863 c-0.605,1.095-1.087,2.254-1.438,3.46l-5.831,0.971c-0.482,0.08-0.836,0.498-0.836,0.986v5.5c0,0.485,0.348,0.9,0.825,0.985 l5.831,1.034c0.349,1.203,0.831,2.362,1.438,3.46l-3.441,4.813c-0.284,0.397-0.239,0.942,0.106,1.289l3.888,3.891 c0.343,0.343,0.884,0.391,1.281,0.112l4.87-3.411c1.093,0.601,2.248,1.078,3.445,1.424l0.976,5.861C21.3,47.647,21.717,48,22.206,48 h5.5c0.485,0,0.9-0.348,0.984-0.825l1.045-5.89c1.199-0.353,2.348-0.833,3.43-1.435l4.905,3.441 c0.398,0.281,0.938,0.232,1.282-0.111l3.888-3.891c0.346-0.347,0.391-0.894,0.104-1.292l-3.498-4.857 c0.593-1.08,1.064-2.222,1.407-3.408l5.918-1.039c0.479-0.084,0.827-0.5,0.827-0.985v-5.5C47.999,21.718,47.644,21.3,47.16,21.221z M25,32c-3.866,0-7-3.134-7-7c0-3.866,3.134-7,7-7s7,3.134,7,7C32,28.866,28.866,32,25,32z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" width="50px" height="50px"><path d="M 30.398438 2 L 7 2 L 7 48 L 43 48 L 43 14.601563 Z M 15 28 L 31 28 L 31 30 L 15 30 Z M 35 36 L 15 36 L 15 34 L 35 34 Z M 35 24 L 15 24 L 15 22 L 35 22 Z M 30 15 L 30 4.398438 L 40.601563 15 Z"/></svg>

After

Width:  |  Height:  |  Size: 298 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1008 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 848 B

Some files were not shown because too many files have changed in this diff Show More