forked from RiseUP/riseup-squad23
285 lines
12 KiB
JavaScript
285 lines
12 KiB
JavaScript
import React, { useState, useEffect, useCallback, useMemo } from 'react';
|
|
import dayjs from 'dayjs';
|
|
import 'dayjs/locale/pt-br';
|
|
import weekday from 'dayjs/plugin/weekday';
|
|
import FormCriarExcecao from '../components/FormCriarExcecao';
|
|
import "../components/AgendarConsulta/style/formagendamentos.css";
|
|
import "./style/Agendamento.css";
|
|
import './style/FilaEspera.css';
|
|
import { useAuth } from '../components/utils/AuthProvider';
|
|
import API_KEY from '../components/utils/apiKeys';
|
|
|
|
dayjs.extend(weekday);
|
|
dayjs.locale('pt-br');
|
|
|
|
const ENDPOINT_BASE = "https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/doctor_exceptions";
|
|
|
|
const getDateRange = (date, view) => {
|
|
const startDayjs = dayjs(date);
|
|
let fromDate, toDate, titleRange;
|
|
|
|
if (view === 'diario') {
|
|
fromDate = startDayjs.format('YYYY-MM-DD');
|
|
toDate = startDayjs.format('YYYY-MM-DD');
|
|
titleRange = startDayjs.format('DD/MM/YYYY');
|
|
} else if (view === 'semanal') {
|
|
// Padrão Dayjs: Sunday=0, Monday=1.
|
|
// startOf('week') pode ser Domingo ou Segunda, dependendo do locale.
|
|
// Se precisar forçar a Segunda-feira:
|
|
let weekStart = startDayjs.startOf('week');
|
|
if (weekStart.day() !== 1) { // Se não for segunda-feira (1), ajusta
|
|
weekStart = startDayjs.weekday(1); // Vai para a segunda-feira desta semana
|
|
}
|
|
|
|
const weekEnd = weekStart.add(6, 'day');
|
|
|
|
fromDate = weekStart.format('YYYY-MM-DD');
|
|
toDate = weekEnd.format('YYYY-MM-DD');
|
|
titleRange = `Semana de ${weekStart.format('DD/MM')} a ${weekEnd.format('DD/MM')}`;
|
|
|
|
} else if (view === 'mensal') {
|
|
const monthStart = startDayjs.startOf('month');
|
|
const monthEnd = startDayjs.endOf('month');
|
|
|
|
fromDate = monthStart.format('YYYY-MM-DD');
|
|
toDate = monthEnd.format('YYYY-MM-DD');
|
|
titleRange = startDayjs.format('MMMM/YYYY').toUpperCase();
|
|
}
|
|
|
|
return { fromDate, toDate, titleRange };
|
|
};
|
|
|
|
const ExcecoesDisponibilidade = () => {
|
|
|
|
const { getAuthorizationHeader } = useAuth();
|
|
const [pageNovaExcecao, setPageNovaExcecao] = useState(false);
|
|
const [excecoes, setExcecoes] = useState([]);
|
|
const [loading, setLoading] = useState(false);
|
|
|
|
const [filtroMedicoId, setFiltroMedicoId] = useState('');
|
|
const [filtroData, setFiltroData] = useState(dayjs().format('YYYY-MM-DD'));
|
|
|
|
const [visualizacao, setVisualizacao] = useState('diario');
|
|
|
|
const resolveAuthHeader = () => {
|
|
try {
|
|
const h = getAuthorizationHeader();
|
|
return h || '';
|
|
} catch {
|
|
return '';
|
|
}
|
|
}
|
|
|
|
const fetchExcecoes = useCallback(async (fromDate, toDate, doctorId) => {
|
|
|
|
setLoading(true);
|
|
|
|
let url = `${ENDPOINT_BASE}?select=*`;
|
|
|
|
if (doctorId) {
|
|
url += `&doctor_id=eq.${doctorId}`;
|
|
}
|
|
|
|
url += `&date=gte.${fromDate}&date=lte.${toDate}`;
|
|
|
|
const myHeaders = new Headers();
|
|
const authHeader = resolveAuthHeader();
|
|
if (authHeader) myHeaders.append("Authorization", authHeader);
|
|
myHeaders.append("Content-Type", "application/json");
|
|
if (API_KEY) myHeaders.append("apikey", API_KEY);
|
|
|
|
try {
|
|
const requestOptions = {
|
|
method: 'GET',
|
|
headers: myHeaders,
|
|
redirect: 'follow'
|
|
};
|
|
|
|
const response = await fetch(url, requestOptions);
|
|
const result = await response.json();
|
|
|
|
if (response.ok && Array.isArray(result)) {
|
|
setExcecoes(result);
|
|
} else {
|
|
setExcecoes([]);
|
|
console.error("Erro ao listar exceções (Status:", response.status, "):", result);
|
|
alert(`Erro ao carregar lista de exceções. Status: ${response.status}. Detalhes: ${result.message || JSON.stringify(result)}`);
|
|
}
|
|
} catch (error) {
|
|
console.error('Erro na requisição de listagem de exceções:', error);
|
|
setExcecoes([]);
|
|
alert("Erro de comunicação com o servidor ao listar exceções.");
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, [getAuthorizationHeader]);
|
|
|
|
const { fromDate, toDate, titleRange } = useMemo(() =>
|
|
getDateRange(filtroData, visualizacao),
|
|
[filtroData, visualizacao]
|
|
);
|
|
|
|
useEffect(() => {
|
|
fetchExcecoes(fromDate, toDate, filtroMedicoId);
|
|
}, [fetchExcecoes, filtroMedicoId, fromDate, toDate]);
|
|
|
|
const deleteExcecao = async (id) => {
|
|
if (!window.confirm("Confirma exclusão desta exceção?")) return;
|
|
const myHeaders = new Headers();
|
|
const authHeader = resolveAuthHeader();
|
|
if (authHeader) myHeaders.append("Authorization", authHeader);
|
|
if (API_KEY) myHeaders.append("apikey", API_KEY);
|
|
myHeaders.append("Content-Type", "application/json");
|
|
|
|
try {
|
|
const res = await fetch(`${ENDPOINT_BASE}?id=eq.${id}`, {
|
|
method: 'DELETE',
|
|
headers: myHeaders,
|
|
redirect: 'follow'
|
|
});
|
|
if (res.ok) {
|
|
setExcecoes(prev => prev.filter(x => x.id !== id));
|
|
} else {
|
|
const text = await res.text();
|
|
console.error('Erro ao deletar exceção', res.status, text);
|
|
alert(`Erro ao excluir exceção. Status: ${res.status}. ${text}`);
|
|
}
|
|
} catch (err) {
|
|
console.error('Erro na requisição de exclusão:', err);
|
|
alert('Erro ao excluir exceção.');
|
|
}
|
|
}
|
|
|
|
const handleCancelForm = (recarregar = false) => {
|
|
setPageNovaExcecao(false);
|
|
if (recarregar) {
|
|
fetchExcecoes(fromDate, toDate, filtroMedicoId);
|
|
}
|
|
}
|
|
|
|
if (pageNovaExcecao) {
|
|
return <FormCriarExcecao onCancel={handleCancelForm} doctorID={filtroMedicoId} />;
|
|
}
|
|
|
|
return (
|
|
<div>
|
|
{/* Título e Botão de Criação */}
|
|
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '15px' }}>
|
|
<h1>Gerenciar Exceções de Disponibilidade</h1>
|
|
<button
|
|
className="btn-primary"
|
|
onClick={() => setPageNovaExcecao(true)}
|
|
style={{ padding: '10px 20px', fontSize: '14px', whiteSpace: 'nowrap' }}
|
|
>
|
|
+ Criar Nova Exceção
|
|
</button>
|
|
</div>
|
|
|
|
<div className='atendimento-eprocura'>
|
|
|
|
{/* Filtros de Médico e Data */}
|
|
<div className='busca-atendimento'>
|
|
<div>
|
|
<i className="fa-solid fa-user-doctor"></i>
|
|
<input
|
|
type="text"
|
|
placeholder="Filtrar por ID do Médico..."
|
|
value={filtroMedicoId}
|
|
onChange={(e) => setFiltroMedicoId(e.target.value)}
|
|
/>
|
|
</div>
|
|
<div>
|
|
<i className="fa-solid fa-calendar"></i>
|
|
<input
|
|
type="date"
|
|
value={filtroData}
|
|
onChange={(e) => setFiltroData(e.target.value)}
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Botões de Visualização (Dia/Semana/Mês) */}
|
|
<div className='container-btns-agenda-fila_esepera'>
|
|
<button
|
|
className={`btn-agenda ${visualizacao === "diario" ? "opc-agenda-ativo" : ""}`}
|
|
onClick={() => setVisualizacao('diario')}
|
|
>
|
|
Dia
|
|
</button>
|
|
<button
|
|
className={`btn-fila-espera ${visualizacao === "semanal" ? "opc-filaespera-ativo" : ""}`}
|
|
onClick={() => setVisualizacao('semanal')}
|
|
>
|
|
Semana
|
|
</button>
|
|
<button
|
|
className={`btn-fila-espera ${visualizacao === "mensal" ? "opc-filaespera-ativo" : ""}`}
|
|
onClick={() => setVisualizacao('mensal')}
|
|
>
|
|
Mês
|
|
</button>
|
|
</div>
|
|
|
|
{/* Tabela de Exceções (Título usa o titleRange calculado) */}
|
|
<section className='calendario-ou-filaespera'>
|
|
<div className="fila-container">
|
|
<h2 className="fila-titulo">Exceções em {titleRange} ({excecoes.length})</h2>
|
|
{loading ? (
|
|
<p>Carregando exceções...</p>
|
|
) : excecoes.length === 0 ? (
|
|
<p>Nenhuma exceção encontrada para os filtros aplicados.</p>
|
|
) : (
|
|
<table className="fila-tabela">
|
|
<thead>
|
|
<tr>
|
|
<th>Médico (ID)</th>
|
|
<th>Data</th>
|
|
<th>Início</th>
|
|
<th>Término</th>
|
|
<th>Motivo</th>
|
|
<th>Criado por</th>
|
|
<th>Ações</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{excecoes.map((exc) => (
|
|
<tr key={exc.id}>
|
|
<td><p>{exc.doctor_id}</p></td>
|
|
<td>{dayjs(exc.date).format('DD/MM/YYYY')}</td>
|
|
<td>{exc.start_time ? dayjs(exc.start_time, 'HH:mm:ss').format('HH:mm') : '—'}</td>
|
|
<td>{exc.end_time ? dayjs(exc.end_time, 'HH:mm:ss').format('HH:mm') : '—'}</td>
|
|
<td><p>{exc.reason}</p></td>
|
|
<td>{exc.created_by || '—'}</td>
|
|
<td>
|
|
<div className="d-flex gap-2">
|
|
<button
|
|
className="btn btn-sm btn-edit"
|
|
onClick={() => {
|
|
setFiltroMedicoId(exc.doctor_id || '');
|
|
setPageNovaExcecao(true);
|
|
}}
|
|
>
|
|
<i className="bi bi-pencil me-1"></i> Editar
|
|
</button>
|
|
|
|
<button
|
|
className="btn btn-sm btn-delete"
|
|
onClick={() => deleteExcecao(exc.id)}
|
|
>
|
|
<i className="bi bi-trash me-1"></i> Excluir
|
|
</button>
|
|
</div>
|
|
</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
)}
|
|
</div>
|
|
</section>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export default ExcecoesDisponibilidade; |