diff --git a/src/PagesMedico/DoctorAgendamentoManager.jsx b/src/PagesMedico/DoctorAgendamentoManager.jsx
index 4d521a6..7f0d77e 100644
--- a/src/PagesMedico/DoctorAgendamentoManager.jsx
+++ b/src/PagesMedico/DoctorAgendamentoManager.jsx
@@ -2,38 +2,43 @@ import React, { useState, useMemo, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import API_KEY from '../components/utils/apiKeys.js';
import AgendamentoCadastroManager from '../pages/AgendamentoCadastroManager.jsx';
-import { GetPatientByID } from '../components/utils/Functions-Endpoints/Patient.js';
-import { GetAllDoctors, GetDoctorByID } from '../components/utils/Functions-Endpoints/Doctor.js';
+// Removidos imports não utilizados no novo fluxo
+import { GetAllDoctors } from '../components/utils/Functions-Endpoints/Doctor.js';
import { useAuth } from '../components/utils/AuthProvider.js';
import dayjs from 'dayjs';
import 'dayjs/locale/pt-br';
import isBetween from 'dayjs/plugin/isBetween';
import localeData from 'dayjs/plugin/localeData';
-import { Search, ChevronLeft, ChevronRight, Edit, Trash2, CheckCircle } from 'lucide-react';
+import { Search, ChevronLeft, ChevronRight, Edit, Trash2, CheckCircle } from 'lucide-react';
import "../pages/style/Agendamento.css";
import '../pages/style/FilaEspera.css';
-import Spinner from '../components/Spinner.jsx';
+import Spinner from '../components/Spinner.jsx';
+
dayjs.locale('pt-br');
dayjs.extend(isBetween);
dayjs.extend(localeData);
-const Agendamento = ({ setDictInfo }) => {
+
+const Agendamento = () => {
const navigate = useNavigate();
+ const { getAuthorizationHeader, user } = useAuth();
+ const authHeader = getAuthorizationHeader();
+
+ // ID do médico que você quer visualizar
+ const ID_MEDICO_ESPECIFICO = "078d2a67-b4c1-43c8-ae32-c1e75bb5b3df";
+
const [listaTodosAgendamentos, setListaTodosAgendamentos] = useState([]);
const [selectedID, setSelectedId] = useState('0');
const [filaEsperaData, setFilaEsperaData] = useState([]);
const [FiladeEspera, setFiladeEspera] = useState(false);
const [PageNovaConsulta, setPageConsulta] = useState(false);
- const [searchTerm, setSearchTerm] = useState('');
- const { getAuthorizationHeader } = useAuth();
const [DictAgendamentosOrganizados, setAgendamentosOrganizados] = useState({});
const [showDeleteModal, setShowDeleteModal] = useState(false);
const [ListaDeMedicos, setListaDeMedicos] = useState([]);
const [FiltredTodosMedicos, setFiltredTodosMedicos] = useState([]);
const [searchTermDoctor, setSearchTermDoctor] = useState('');
const [MedicoFiltrado, setMedicoFiltrado] = useState({ id: "vazio" });
- const [cacheAgendamentos, setCacheAgendamentos] = useState([]);
const [motivoCancelamento, setMotivoCancelamento] = useState("");
const [showSpinner, setShowSpinner] = useState(true);
const [waitlistSearch, setWaitlistSearch] = useState('');
@@ -41,38 +46,49 @@ const Agendamento = ({ setDictInfo }) => {
const [waitSortDir, setWaitSortDir] = useState('asc');
const [waitPage, setWaitPage] = useState(1);
const [waitPerPage, setWaitPerPage] = useState(10);
- const authHeader = getAuthorizationHeader();
- const cacheMedicos = useMemo(() => ({}), []);
- const cachePacientes = useMemo(() => ({}), []);
+ const [cacheMedicos, setCacheMedicos] = useState({});
+ const [cachePacientes, setCachePacientes] = useState({});
const [currentDate, setCurrentDate] = useState(dayjs());
const [selectedDay, setSelectedDay] = useState(dayjs());
const [agendamentoParaEdicao, setAgendamentoParaEdicao] = useState(null);
-
const [quickJump, setQuickJump] = useState({
month: currentDate.month(),
year: currentDate.year()
});
+ // ✨ ALTERAÇÃO PRINCIPAL: A busca agora filtra pelo ID do médico direto na API
const fetchAppointments = useCallback(async () => {
- const myHeaders = new Headers(); myHeaders.append("Authorization", authHeader); myHeaders.append("apikey", API_KEY);
+ if (!authHeader) return;
+ setShowSpinner(true);
+ const myHeaders = new Headers();
+ myHeaders.append("Authorization", authHeader);
+ myHeaders.append("apikey", API_KEY);
const requestOptions = { method: 'GET', headers: myHeaders, redirect: 'follow' };
+
+ // A URL agora contém o filtro para o ID do médico específico
+ const apiUrl = `https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/appointments?doctor_id=eq.${ID_MEDICO_ESPECIFICO}&select=*`;
+
try {
- const res = await fetch("https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/appointments?select=*", requestOptions);
+ const res = await fetch(apiUrl, requestOptions);
const data = await res.json();
- setListaTodosAgendamentos(data);
+ setListaTodosAgendamentos(data || []);
} catch (err) {
console.error('Erro ao buscar agendamentos', err);
+ setListaTodosAgendamentos([]);
} finally {
- if (!listaTodosAgendamentos.length) {
- setShowSpinner(false);
- }
+ setShowSpinner(false);
}
- }, [authHeader, listaTodosAgendamentos.length]);
+ }, [authHeader, ID_MEDICO_ESPECIFICO]);
+
const updateAppointmentStatus = useCallback(async (id, updates) => {
- const myHeaders = new Headers(); myHeaders.append("Authorization", authHeader); myHeaders.append("apikey", API_KEY); myHeaders.append("Content-Type", "application/json"); myHeaders.append("Prefer", "return=representation");
+ setShowSpinner(true);
+ const myHeaders = new Headers();
+ myHeaders.append("Authorization", authHeader);
+ myHeaders.append("apikey", API_KEY);
+ myHeaders.append("Content-Type", "application/json");
+ myHeaders.append("Prefer", "return=representation");
const requestOptions = { method: 'PATCH', headers: myHeaders, body: JSON.stringify(updates) };
-
try {
const response = await fetch(`https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/appointments?id=eq.${id}`, requestOptions);
if (response.ok) {
@@ -85,14 +101,14 @@ const Agendamento = ({ setDictInfo }) => {
} catch (error) {
console.error('Erro de rede/servidor:', error);
return false;
+ } finally {
+ setShowSpinner(false);
}
}, [authHeader, fetchAppointments]);
+
const deleteConsulta = useCallback(async (id) => {
- setShowSpinner(true);
-
const success = await updateAppointmentStatus(id, { status: "cancelled", cancellation_reason: motivoCancelamento, updated_at: new Date().toISOString() });
- setShowSpinner(false);
if (success) {
setShowDeleteModal(false);
setMotivoCancelamento("");
@@ -102,12 +118,9 @@ const Agendamento = ({ setDictInfo }) => {
}
}, [motivoCancelamento, updateAppointmentStatus]);
-
+
const confirmConsulta = useCallback(async (id) => {
- setShowSpinner(true);
-
const success = await updateAppointmentStatus(id, { status: "agendado", cancellation_reason: null, updated_at: new Date().toISOString() });
- setShowSpinner(false);
if (success) {
setSelectedId('0');
} else {
@@ -115,87 +128,125 @@ const Agendamento = ({ setDictInfo }) => {
}
}, [updateAppointmentStatus]);
- const handleEditConsulta = (agendamento) => {
- setAgendamentoParaEdicao(agendamento);
- setPageConsulta(true);
- };
-
- const handleQuickJumpChange = (type, value) => {
- setQuickJump(prev => ({ ...prev, [type]: Number(value) }));
- };
-
- const applyQuickJump = () => {
- let newDate = dayjs().year(quickJump.year).month(quickJump.month).date(1);
- setCurrentDate(newDate);
- setSelectedDay(newDate);
- };
+ useEffect(() => {
+ if(authHeader) {
+ fetchAppointments();
+ // A busca de todos os médicos pode continuar caso a secretária precise ver a lista
+ if (user?.role !== 'doctor') {
+ GetAllDoctors(authHeader).then(docs => {
+ if (docs) {
+ setListaDeMedicos(docs.map(d => ({ nomeMedico: d.full_name, idMedico: d.id })));
+ }
+ });
+ }
+ }
+ }, [authHeader, fetchAppointments, user?.role]);
useEffect(() => {
- setQuickJump({
- month: currentDate.month(),
- year: currentDate.year()
- });
- }, [currentDate]);
+ const processData = async () => {
+ // Como os dados já vêm filtrados da API, não precisamos mais da verificação de 'user' aqui
+ if (!listaTodosAgendamentos.length) {
+ setAgendamentosOrganizados({});
+ setFilaEsperaData([]);
+ return;
+ }
- useEffect(() => {
- if (!listaTodosAgendamentos.length && !showSpinner) { return; }
- setShowSpinner(true);
+ setShowSpinner(true);
+
+ // ✨ SIMPLIFICAÇÃO: Não é mais necessário filtrar por `user.role`,
+ // pois a API já retornou apenas os agendamentos do médico desejado.
+ const appointmentsToShow = listaTodosAgendamentos;
+
+ const patientIdsToFetch = new Set();
+ const doctorIdsToFetch = new Set();
+
+ appointmentsToShow.forEach(ag => {
+ if (ag.patient_id && !cachePacientes[ag.patient_id]) {
+ patientIdsToFetch.add(ag.patient_id);
+ }
+ if (ag.doctor_id && !cacheMedicos[ag.doctor_id]) {
+ doctorIdsToFetch.add(ag.doctor_id);
+ }
+ });
+
+ const fetchPromises = [];
+
+ if (patientIdsToFetch.size > 0) {
+ const query = `id=in.(${Array.from(patientIdsToFetch).join(',')})`;
+ fetchPromises.push(
+ fetch(`https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/patients?${query}&select=*`, {
+ headers: { apikey: API_KEY, Authorization: authHeader }
+ }).then(res => res.json())
+ );
+ } else {
+ fetchPromises.push(Promise.resolve(null)); // Mantém a ordem do Promise.all
+ }
+
+ if (doctorIdsToFetch.size > 0) {
+ const query = `id=in.(${Array.from(doctorIdsToFetch).join(',')})`;
+ fetchPromises.push(
+ fetch(`https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/doctors?${query}&select=id,full_name`, {
+ headers: { apikey: API_KEY, Authorization: authHeader }
+ }).then(res => res.json())
+ );
+ } else {
+ fetchPromises.push(Promise.resolve(null));
+ }
+
+ const [newPatients, newDoctors] = await Promise.all(fetchPromises);
+
+ const updatedPatientCache = { ...cachePacientes };
+ if (newPatients) newPatients.forEach(p => updatedPatientCache[p.id] = p);
+
+ const updatedDoctorCache = { ...cacheMedicos };
+ if (newDoctors) newDoctors.forEach(d => updatedDoctorCache[d.id] = d);
+
+ setCachePacientes(updatedPatientCache);
+ setCacheMedicos(updatedDoctorCache);
- const fetchDados = async () => {
const newDict = {};
const newFila = [];
- for (const agendamento of listaTodosAgendamentos) {
- if (!agendamento.doctor_id || !agendamento.patient_id) continue;
+ for (const agendamento of appointmentsToShow) {
+ const medico = updatedDoctorCache[agendamento.doctor_id];
+ const paciente = updatedPatientCache[agendamento.patient_id];
- if (!cacheMedicos[agendamento.doctor_id]) {
- const doctorData = await GetDoctorByID(agendamento.doctor_id, authHeader);
- cacheMedicos[agendamento.doctor_id] = doctorData[0];
- }
- if (!cachePacientes[agendamento.patient_id]) {
- const patientData = await GetPatientByID(agendamento.patient_id, authHeader);
- cachePacientes[agendamento.patient_id] = patientData[0];
- }
+ if (!medico || !paciente) continue;
- const medico = cacheMedicos[agendamento.doctor_id];
- const paciente = cachePacientes[agendamento.patient_id];
const agendamentoMelhorado = {
...agendamento,
- medico_nome: medico?.full_name,
- paciente_nome: paciente?.full_name,
- paciente_cpf: paciente?.cpf
+ medico_nome: medico.full_name || 'N/A',
+ paciente_nome: paciente.full_name || 'N/A',
+ paciente_cpf: paciente.cpf || 'N/A'
};
if (agendamento.status === "requested") {
- newFila.push({
- agendamento: agendamentoMelhorado,
- Infos: agendamentoMelhorado
- });
+ newFila.push({ agendamento: agendamentoMelhorado, Infos: agendamentoMelhorado });
} else {
const DiaAgendamento = dayjs(agendamento.scheduled_at).format("YYYY-MM-DD");
- if (newDict[DiaAgendamento]) {
- newDict[DiaAgendamento].push(agendamentoMelhorado);
- } else {
- newDict[DiaAgendamento] = [agendamentoMelhorado];
- }
+ if (!newDict[DiaAgendamento]) newDict[DiaAgendamento] = [];
+ newDict[DiaAgendamento].push(agendamentoMelhorado);
}
}
for (const key in newDict) {
- newDict[key].sort((a, b) => a.scheduled_at.localeCompare(b.scheduled_at));
+ newDict[key].sort((a, b) => new Date(a.scheduled_at) - new Date(b.scheduled_at));
}
setAgendamentosOrganizados(newDict);
setFilaEsperaData(newFila);
setShowSpinner(false);
};
- fetchDados();
- }, [listaTodosAgendamentos, authHeader, cacheMedicos, cachePacientes, showSpinner]);
- useEffect(() => {
- fetchAppointments();
- GetAllDoctors(authHeader).then(docs => setListaDeMedicos(docs.map(d => ({ nomeMedico: d.full_name, idMedico: d.id }))));
- }, [authHeader, fetchAppointments]);
+ processData();
+ }, [listaTodosAgendamentos, authHeader]); // Removido 'user' das dependências pois não é mais usado aqui
+
+ // O restante do código permanece o mesmo...
+
+ const handleEditConsulta = (agendamento) => {
+ setAgendamentoParaEdicao(agendamento);
+ setPageConsulta(true);
+ };
const handleSearchMedicos = (term) => {
setSearchTermDoctor(term);
@@ -209,54 +260,7 @@ const Agendamento = ({ setDictInfo }) => {
setMedicoFiltrado({ id: "vazio" });
}
};
-
- const filaEsperaFiltrada = useMemo(() => {
- if (!waitlistSearch.trim()) return filaEsperaData;
- const term = waitlistSearch.toLowerCase();
- return filaEsperaData.filter(item =>
- (item?.Infos?.paciente_nome?.toLowerCase() || '').includes(term) ||
- (item?.Infos?.paciente_cpf?.toLowerCase() || '').includes(term) ||
- (item?.Infos?.medico_nome?.toLowerCase() || '').includes(term)
- );
- }, [waitlistSearch, filaEsperaData]);
-
- const applySortingWaitlist = useCallback((arr) => {
- if (!Array.isArray(arr) || !waitSortKey) return arr;
- const copy = [...arr];
- if (waitSortKey === 'paciente') {
- copy.sort((a, b) => (a?.Infos?.paciente_nome || '').localeCompare((b?.Infos?.paciente_nome || '')));
- } else if (waitSortKey === 'medico') {
- copy.sort((a, b) => (a?.Infos?.medico_nome || '').localeCompare((b?.Infos?.medico_nome || '')));
- } else if (waitSortKey === 'data') {
- copy.sort((a, b) => new Date(a?.agendamento?.scheduled_at || 0) - new Date(b?.agendamento?.scheduled_at || 0));
- }
- if (waitSortDir === 'desc') copy.reverse();
- return copy;
- }, [waitSortKey, waitSortDir]);
-
- const filaEsperaOrdenada = useMemo(() => applySortingWaitlist(filaEsperaFiltrada), [filaEsperaFiltrada, applySortingWaitlist]);
-
- const waitTotalPages = Math.ceil(filaEsperaOrdenada.length / waitPerPage) || 1;
- const waitIndiceInicial = (waitPage - 1) * waitPerPage;
- const waitIndiceFinal = waitIndiceInicial + waitPerPage;
- const filaEsperaPaginada = filaEsperaOrdenada.slice(waitIndiceInicial, waitIndiceFinal);
-
- const gerarNumerosWaitPages = () => {
- const paginas = [];
- const paginasParaMostrar = 5;
- let inicio = Math.max(1, waitPage - Math.floor(paginasParaMostrar / 2));
- let fim = Math.min(waitTotalPages, inicio + paginasParaMostrar - 1);
- inicio = Math.max(1, fim - paginasParaMostrar + 1);
- for (let i = inicio; i <= fim; i++) {
- paginas.push(i);
- }
- return paginas;
- };
-
- useEffect(() => {
- setWaitPage(1);
- }, [waitlistSearch, waitSortKey, waitSortDir]);
-
+
const generateDateGrid = () => {
const grid = [];
const startOfMonth = currentDate.startOf('month');
@@ -271,26 +275,91 @@ const Agendamento = ({ setDictInfo }) => {
const dateGrid = useMemo(() => generateDateGrid(), [currentDate]);
const weekDays = ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'];
const handleDateClick = (day) => setSelectedDay(day);
- const DeleteModal = () => (
-
-
-
-
-
Confirmação de Cancelamento
-
-
-
-
Qual o motivo do cancelamento?
-
-
-
-
-
-
+const DeleteModal = () => (
+
+
+
+
+
Confirmação de Cancelamento
+
+
+
+
Qual o motivo do cancelamento? (Opcional)
+
+
+
+
+ {/* ✨ Botão sempre ativo ✨ */}
+
- );
+
+);
+
+
+ useEffect(() => {
+ setQuickJump({
+ month: currentDate.month(),
+ year: currentDate.year()
+ });
+ }, [currentDate]);
+
+ const filaEsperaFiltrada = useMemo(() => {
+ if (!waitlistSearch.trim()) return filaEsperaData;
+ const term = waitlistSearch.toLowerCase();
+ return filaEsperaData.filter(item =>
+ (item?.Infos?.paciente_nome?.toLowerCase() || '').includes(term) ||
+ (item?.Infos?.paciente_cpf?.toLowerCase() || '').includes(term) ||
+ (item?.Infos?.medico_nome?.toLowerCase() || '').includes(term)
+ );
+ }, [waitlistSearch, filaEsperaData]);
+
+ const applySortingWaitlist = useCallback((arr) => {
+ if (!Array.isArray(arr) || !waitSortKey) return arr;
+ const copy = [...arr];
+ const key = waitSortKey;
+ const dir = waitSortDir === 'asc' ? 1 : -1;
+ copy.sort((a, b) => {
+ const valA = key === 'data' ? new Date(a.agendamento.scheduled_at) : (a.Infos?.[`${key}_nome`] || '');
+ const valB = key === 'data' ? new Date(b.agendamento.scheduled_at) : (b.Infos?.[`${key}_nome`] || '');
+ if (valA < valB) return -1 * dir;
+ if (valA > valB) return 1 * dir;
+ return 0;
+ });
+ return copy;
+ }, [waitSortKey, waitSortDir]);
+
+ const filaEsperaOrdenada = useMemo(() => applySortingWaitlist(filaEsperaFiltrada), [filaEsperaFiltrada, applySortingWaitlist]);
+ const waitTotalPages = Math.ceil(filaEsperaOrdenada.length / waitPerPage) || 1;
+ const waitIndiceInicial = (waitPage - 1) * waitPerPage;
+ const waitIndiceFinal = waitIndiceInicial + waitPerPage;
+ const filaEsperaPaginada = filaEsperaOrdenada.slice(waitIndiceInicial, waitIndiceFinal);
+
+ const gerarNumerosWaitPages = () => {
+ const paginas = [];
+ const paginasParaMostrar = 5;
+ let inicio = Math.max(1, waitPage - Math.floor(paginasParaMostrar / 2));
+ let fim = Math.min(waitTotalPages, inicio + paginasParaMostrar - 1);
+ inicio = Math.max(1, fim - paginasParaMostrar + 1);
+ for (let i = inicio; i <= fim; i++) paginas.push(i);
+ return paginas;
+ };
+
+ useEffect(() => { setWaitPage(1); }, [waitlistSearch, waitSortKey, waitSortDir]);
+
+ const handleQuickJumpChange = (type, value) => {
+ setQuickJump(prev => ({ ...prev, [type]: Number(value) }));
+ };
+
+ const applyQuickJump = () => {
+ let newDate = dayjs().year(quickJump.year).month(quickJump.month).date(1);
+ setCurrentDate(newDate);
+ setSelectedDay(newDate);
+ };
+
return (
Agendar nova consulta
@@ -309,47 +378,49 @@ const Agendamento = ({ setDictInfo }) => {
{!PageNovaConsulta ? (
-
-
-
-
-
-
handleSearchMedicos(e.target.value)} />
+ {user?.role !== 'doctor' && (
+
+
+
+
+ {searchTermDoctor && FiltredTodosMedicos.length > 0 && (
+
+ {FiltredTodosMedicos.map((medico) => (
+
{
+ setSearchTermDoctor(medico.nomeMedico);
+ setFiltredTodosMedicos([]);
+ setMedicoFiltrado({ id: medico.idMedico });
+ }}
+ >
+
{medico.nomeMedico}
+
+ ))}
+
+ )}
- {searchTermDoctor && FiltredTodosMedicos.length > 0 && (
-
- {FiltredTodosMedicos.map((medico) => (
-
{
- setSearchTermDoctor(medico.nomeMedico);
- setFiltredTodosMedicos([]);
- setMedicoFiltrado(medico);
- }}
- >
-
{medico.nomeMedico}
-
- ))}
-
- )}
-
+ )}
-
-
+
+
- {FiladeEspera === false ? (
+ {!FiladeEspera ? (
{selectedDay.format('MMM')}{selectedDay.format('DD')}
{selectedDay.format('dddd')}
{selectedDay.format('D [de] MMMM [de] YYYY')}
Consultas para {selectedDay.format('DD/MM')}
- {showSpinner ? : (DictAgendamentosOrganizados[selectedDay.format('YYYY-MM-DD')]?.length > 0) ? (
+ {showSpinner ? : (DictAgendamentosOrganizados[selectedDay.format('YYYY-MM-DD')]?.filter(app => MedicoFiltrado.id === "vazio" || app.doctor_id === MedicoFiltrado.id).length > 0) ? (
DictAgendamentosOrganizados[selectedDay.format('YYYY-MM-DD')]
.filter(app => MedicoFiltrado.id === "vazio" || app.doctor_id === MedicoFiltrado.id)
.map(app => (
@@ -377,7 +448,8 @@ const Agendamento = ({ setDictInfo }) => {
)}
- ))) : (
Nenhuma consulta agendada.
)}
+ ))
+ ) : (
Nenhuma consulta agendada.
)}
@@ -418,14 +490,12 @@ const Agendamento = ({ setDictInfo }) => {
-
-
{weekDays.map(day =>
{day}
)}
{dateGrid.map((day, index) => {
@@ -445,10 +515,6 @@ const Agendamento = ({ setDictInfo }) => {
) : (
- {}
-
- {}
-
@@ -460,30 +526,25 @@ const Agendamento = ({ setDictInfo }) => {
Ordenar por:
- {(() => {
- const sortValue = waitSortKey ? `${waitSortKey}-${waitSortDir}` : '';
- return (
-
- );
- })()}
+
@@ -571,7 +632,6 @@ const Agendamento = ({ setDictInfo }) => {
-
)}
@@ -580,12 +640,15 @@ const Agendamento = ({ setDictInfo }) => {
{
+ setPageConsulta(false);
+ fetchAppointments();
+ }}
/>
)}
{showDeleteModal && }
- {}
- )
+ );
}
-export default Agendamento;
\ No newline at end of file
+export default Agendamento;
diff --git a/src/PagesPaciente/ConsultasPaciente.jsx b/src/PagesPaciente/ConsultasPaciente.jsx
index 5922997..24a4811 100644
--- a/src/PagesPaciente/ConsultasPaciente.jsx
+++ b/src/PagesPaciente/ConsultasPaciente.jsx
@@ -2,8 +2,6 @@ import React, { useState, useMemo, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import API_KEY from '../components/utils/apiKeys.js';
import AgendamentoCadastroManager from '../pages/AgendamentoCadastroManager.jsx';
-import { GetPatientByID } from '../components/utils/Functions-Endpoints/Patient.js';
-import { GetAllDoctors, GetDoctorByID } from '../components/utils/Functions-Endpoints/Doctor.js';
import { useAuth } from '../components/utils/AuthProvider.js';
import dayjs from 'dayjs';
import 'dayjs/locale/pt-br';
@@ -14,233 +12,289 @@ import "../pages/style/Agendamento.css";
import '../pages/style/FilaEspera.css';
import Spinner from '../components/Spinner.jsx';
+
dayjs.locale('pt-br');
dayjs.extend(isBetween);
dayjs.extend(localeData);
+
const Agendamento = ({ setDictInfo }) => {
const navigate = useNavigate();
- const [listaTodosAgendamentos, setListaTodosAgendamentos] = useState([]);
- const [selectedID, setSelectedId] = useState('0');
- const [filaEsperaData, setFilaEsperaData] = useState([]);
+ const { getAuthorizationHeader, user } = useAuth();
+
+
+
+ const [isLoading, setIsLoading] = useState(true);
+ const [DictAgendamentosOrganizados, setDictAgendamentosOrganizados] = useState({});
+
+
+ const [filaEsperaData, setFilaDeEsperaData] = useState([]);
+
const [FiladeEspera, setFiladeEspera] = useState(false);
const [PageNovaConsulta, setPageConsulta] = useState(false);
- const { getAuthorizationHeader } = useAuth();
- const [DictAgendamentosOrganizados, setAgendamentosOrganizados] = useState({});
- const [ListaDeMedicos, setListaDeMedicos] = useState([]);
- const [showSpinner, setShowSpinner] = useState(true);
- const [waitlistSearch, setWaitlistSearch] = useState('');
- const [waitSortKey, setWaitSortKey] = useState(null);
- const [waitSortDir, setWaitSortDir] = useState('asc');
- const [waitPage, setWaitPage] = useState(1);
- const [waitPerPage, setWaitPerPage] = useState(10);
- const authHeader = getAuthorizationHeader();
- const cacheMedicos = useMemo(() => ({}), []);
- const cachePacientes = useMemo(() => ({}), []);
+
+
const [currentDate, setCurrentDate] = useState(dayjs());
const [selectedDay, setSelectedDay] = useState(dayjs());
-
const [quickJump, setQuickJump] = useState({
month: currentDate.month(),
year: currentDate.year()
});
- const fetchAppointments = async () => {
- const myHeaders = new Headers(); myHeaders.append("Authorization", authHeader); myHeaders.append("apikey", API_KEY);
- const requestOptions = { method: 'GET', headers: myHeaders, redirect: 'follow' };
- try {
- const res = await fetch("https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/appointments?select=*", requestOptions);
- const data = await res.json();
- setListaTodosAgendamentos(data);
- } catch (err) {
- console.error('Erro ao buscar agendamentos', err);
- }
- };
+
+
+ const [isCancelModalOpen, setIsCancelModalOpen] = useState(false);
+ const [appointmentToCancel, setAppointmentToCancel] = useState(null);
+ const [cancellationReason, setCancellationReason] = useState('');
+
+ const authHeader = useMemo(() => getAuthorizationHeader(), [getAuthorizationHeader]);
+
+
+
+ useEffect(() => {
+ const carregarDados = async () => {
+
+ const patientId = user?.patient_id || "6e7f8829-0574-42df-9290-8dbb70f75ada";
+
+ if (!authHeader) {
+ console.warn("Header de autorização não disponível.");
+ setIsLoading(false);
+ return;
+ }
+
+
+ setIsLoading(true);
+ try {
+
+ const myHeaders = new Headers({ "Authorization": authHeader, "apikey": API_KEY });
+ const requestOptions = { method: 'GET', headers: myHeaders };
+ const response = await fetch(`https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/appointments?select=*,doctors(full_name)&patient_id=eq.${patientId}`, requestOptions);
+
+ if (!response.ok) throw new Error(`Erro na requisição: ${response.statusText}`);
+
+ const consultasBrutas = await response.json() || [];
+
+
+
+ const newDict = {};
+ const newFila = [];
+
+
+ for (const agendamento of consultasBrutas) {
+ const agendamentoMelhorado = {
+ ...agendamento,
+ medico_nome: agendamento.doctors?.full_name || 'Médico não informado'
+ };
+
+ if (agendamento.status === "requested") {
+ newFila.push({ agendamento: agendamentoMelhorado, Infos: agendamentoMelhorado });
+ } else {
+ const diaAgendamento = dayjs(agendamento.scheduled_at).format("YYYY-MM-DD");
+ if (newDict[diaAgendamento]) {
+ newDict[diaAgendamento].push(agendamentoMelhorado);
+ } else {
+ newDict[diaAgendamento] = [agendamentoMelhorado];
+ }
+ }
+ }
+
+ for (const key in newDict) {
+ newDict[key].sort((a, b) => a.scheduled_at.localeCompare(b.scheduled_at));
+ }
+
+ setDictAgendamentosOrganizados(newDict);
+ setFilaDeEsperaData(newFila);
+
+
+ } catch (err) {
+ console.error('Falha ao buscar ou processar agendamentos:', err);
+ setDictAgendamentosOrganizados({});
+ setFilaDeEsperaData([]);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+
+ carregarDados();
+ }, [authHeader, user]);
+
const updateAppointmentStatus = async (id, updates) => {
- const myHeaders = new Headers(); myHeaders.append("Authorization", authHeader); myHeaders.append("apikey", API_KEY); myHeaders.append("Content-Type", "application/json"); myHeaders.append("Prefer", "return=representation");
+ const myHeaders = new Headers({
+ "Authorization": authHeader, "apikey": API_KEY, "Content-Type": "application/json"
+ });
const requestOptions = { method: 'PATCH', headers: myHeaders, body: JSON.stringify(updates) };
try {
const response = await fetch(`https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/appointments?id=eq.${id}`, requestOptions);
- if (response.ok) {
- await fetchAppointments();
- return true;
- } else {
- console.error('Erro ao atualizar agendamento:', await response.text());
- return false;
- }
+ if (!response.ok) throw new Error('Falha ao atualizar o status.');
+ return true;
} catch (error) {
console.error('Erro de rede/servidor:', error);
return false;
}
};
- const deleteConsulta = async (id) => {
- const confirmation = window.confirm("Tem certeza que deseja CANCELAR este agendamento? Esta ação é irreversível.");
- if (!confirmation) return;
-
- setShowSpinner(true);
- const success = await updateAppointmentStatus(id, { status: "cancelled", cancellation_reason: "Cancelado pela Secretaria", updated_at: new Date().toISOString() });
- setShowSpinner(false);
- if (success) {
- alert("Consulta cancelada com sucesso!");
- } else {
- alert("Falha ao cancelar a consulta.");
- }
- };
- const confirmConsulta = async (id) => {
- const confirmation = window.confirm("Tem certeza que deseja CONFIRMAR/REVERTER o cancelamento deste agendamento para 'agendado'?");
- if (!confirmation) return;
- setShowSpinner(true);
- const success = await updateAppointmentStatus(id, { status: "agendado", cancellation_reason: null, updated_at: new Date().toISOString() });
- setShowSpinner(false);
- if (success) {
- alert("Agendamento confirmado/revertido para 'agendado' com sucesso!");
- } else {
- alert("Falha ao reverter o cancelamento.");
- }
- };
-
- const handleQuickJumpChange = (type, value) => {
- setQuickJump(prev => ({ ...prev, [type]: Number(value) }));
- };
-
- useEffect(() => {
- setQuickJump({
- month: currentDate.month(),
- year: currentDate.year()
- });
- }, [currentDate]);
-
- const applyQuickJump = () => {
- let newDate = dayjs().year(quickJump.year).month(quickJump.month).date(1);
- setCurrentDate(newDate);
- setSelectedDay(newDate);
- };
-
- useEffect(() => {
- if (!listaTodosAgendamentos.length) { setShowSpinner(false); return; }
- setShowSpinner(true);
- const fetchDados = async () => {
- const newDict = {}; const newFila = [];
- for (const agendamento of listaTodosAgendamentos) {
- if (!agendamento.doctor_id || !agendamento.patient_id) continue;
- if (!cacheMedicos[agendamento.doctor_id]) { cacheMedicos[agendamento.doctor_id] = (await GetDoctorByID(agendamento.doctor_id, authHeader))[0]; }
- if (!cachePacientes[agendamento.patient_id]) { cachePacientes[agendamento.patient_id] = (await GetPatientByID(agendamento.patient_id, authHeader))[0]; }
- const medico = cacheMedicos[agendamento.doctor_id];
- const paciente = cachePacientes[agendamento.patient_id];
-
- const agendamentoMelhorado = { ...agendamento, medico_nome: medico?.full_name, paciente_nome: paciente?.full_name, paciente_cpf: paciente?.cpf };
-
- if (agendamento.status === "requested") {
- newFila.push({ agendamento: agendamentoMelhorado, Infos: agendamentoMelhorado });
- }
- else {
- const DiaAgendamento = dayjs(agendamento.scheduled_at).format("YYYY-MM-DD");
- if (newDict[DiaAgendamento]) {
- newDict[DiaAgendamento].push(agendamentoMelhorado);
- }
- else {
- newDict[DiaAgendamento] = [agendamentoMelhorado];
- }
- }
- }
- for (const key in newDict) { newDict[key].sort((a, b) => a.scheduled_at.localeCompare(b.scheduled_at)); }
-
- setAgendamentosOrganizados(newDict);
- setFilaEsperaData(newFila);
- setShowSpinner(false);
- };
- fetchDados();
- }, [listaTodosAgendamentos, authHeader, cacheMedicos, cachePacientes]);
-
- useEffect(() => {
- fetchAppointments();
- GetAllDoctors(authHeader).then(docs => setListaDeMedicos(docs.map(d => ({ nomeMedico: d.full_name, idMedico: d.id }))));
- }, [authHeader]);
-
- const filaEsperaFiltrada = useMemo(() => {
- if (!waitlistSearch.trim()) return filaEsperaData;
- const term = waitlistSearch.toLowerCase();
- return filaEsperaData.filter(item => (item?.Infos?.paciente_nome?.toLowerCase() || '').includes(term) || (item?.Infos?.paciente_cpf?.toLowerCase() || '').includes(term) || (item?.Infos?.nome_medico?.toLowerCase() || '').includes(term));
- }, [waitlistSearch, filaEsperaData]);
- const applySortingWaitlist = (arr) => {
- if (!Array.isArray(arr) || !waitSortKey) return arr;
- const copy = [...arr];
- if (waitSortKey === 'paciente') { copy.sort((a, b) => (a?.Infos?.paciente_nome || '').localeCompare((b?.Infos?.paciente_nome || ''))); }
- else if (waitSortKey === 'medico') { copy.sort((a, b) => (a?.Infos?.nome_medico || '').localeCompare((b?.Infos?.nome_medico || ''))); }
- else if (waitSortKey === 'data') { copy.sort((a, b) => new Date(a?.agendamento?.scheduled_at || 0) - new Date(b?.agendamento?.scheduled_at || 0)); }
- if (waitSortDir === 'desc') copy.reverse();
- return copy;
+
+ const handleCancelClick = (appointmentId) => {
+ setAppointmentToCancel(appointmentId);
+ setCancellationReason('');
+ setIsCancelModalOpen(true);
};
- const filaEsperaOrdenada = applySortingWaitlist(filaEsperaFiltrada);
- const waitTotalPages = Math.ceil(filaEsperaOrdenada.length / waitPerPage) || 1;
- const waitIndiceInicial = (waitPage - 1) * waitPerPage;
- const waitIndiceFinal = waitIndiceInicial + waitPerPage;
- const filaEsperaPaginada = filaEsperaOrdenada.slice(waitIndiceInicial, waitIndiceFinal);
- const gerarNumerosWaitPages = () => {
- const paginas = []; const paginasParaMostrar = 5;
- let inicio = Math.max(1, waitPage - Math.floor(paginasParaMostrar / 2));
- let fim = Math.min(waitTotalPages, inicio + paginasParaMostrar - 1);
- inicio = Math.max(1, fim - paginasParaMostrar + 1);
- for (let i = inicio; i <= fim; i++) { paginas.push(i); }
- return paginas;
- };
- useEffect(() => { setWaitPage(1); }, [waitlistSearch, waitSortKey, waitSortDir]);
- // Funções do Calendário
- const generateDateGrid = () => {
- const grid = []; const startOfMonth = currentDate.startOf('month');
- let currentDay = startOfMonth.subtract(startOfMonth.day(), 'day');
- for (let i = 0; i < 42; i++) { grid.push(currentDay); currentDay = currentDay.add(1, 'day'); }
- return grid;
+
+
+ const executeCancellation = async () => {
+ if (!appointmentToCancel) return;
+
+ setIsLoading(true);
+
+
+ const motivo = cancellationReason.trim() || "Cancelado pelo paciente (motivo não especificado)";
+
+ const success = await updateAppointmentStatus(appointmentToCancel, {
+ status: "cancelled",
+ cancellation_reason: motivo,
+ updated_at: new Date().toISOString()
+ });
+
+
+ setIsCancelModalOpen(false);
+ setAppointmentToCancel(null);
+ setCancellationReason('');
+
+
+ if (success) {
+ alert("Solicitação cancelada com sucesso!");
+
+ setDictAgendamentosOrganizados(prev => {
+ const newDict = { ...prev };
+ for (const date in newDict) {
+ newDict[date] = newDict[date].filter(app => app.id !== appointmentToCancel);
+ }
+ return newDict;
+ });
+ setFilaDeEsperaData(prev => prev.filter(item => item.agendamento.id !== appointmentToCancel));
+ } else {
+ alert("Falha ao cancelar a solicitação.");
+ }
+ setIsLoading(false);
};
- const dateGrid = useMemo(() => generateDateGrid(), [currentDate]);
+
+
+ const handleQuickJumpChange = (type, value) => setQuickJump(prev => ({ ...prev, [type]: Number(value) }));
+ const applyQuickJump = () => {
+ const newDate = dayjs().year(quickJump.year).month(quickJump.month).date(1);
+ setCurrentDate(newDate);
+ setSelectedDay(newDate);
+ };
+ const dateGrid = useMemo(() => {
+ const grid = [];
+ const startOfMonth = currentDate.startOf('month');
+ let currentDay = startOfMonth.subtract(startOfMonth.day(), 'day');
+ for (let i = 0; i < 42; i++) {
+ grid.push(currentDay);
+ currentDay = currentDay.add(1, 'day');
+ }
+ return grid;
+ }, [currentDate]);
const weekDays = ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'];
const handleDateClick = (day) => setSelectedDay(day);
+ const activeButtonStyle = {
+ backgroundColor: '#1B2A41',
+ color: 'white',
+ padding: '6px 12px',
+ fontSize: '0.875rem',
+ borderRadius: '8px',
+ border: '1px solid white',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ cursor: 'pointer'
+ };
+
+ const inactiveButtonStyle = {
+ backgroundColor: '#1B2A41',
+ color: 'white',
+ padding: '6px 12px',
+ fontSize: '0.875rem',
+ borderRadius: '8px',
+ border: '1px solid #1B2A41',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ cursor: 'pointer'
+ };
+
+
+
+ if (isLoading) {
+ return (
+
+
+
+ );
+ }
+
+
return (
Minhas consultas
- {}
+
+
- {}
{!PageNovaConsulta ? (
- {FiladeEspera === false ? (
+ {!FiladeEspera ? (
+
- {}
{selectedDay.format('MMM')}{selectedDay.format('DD')}
{selectedDay.format('dddd')}
{selectedDay.format('D [de] MMMM [de] YYYY')}
Consultas para {selectedDay.format('DD/MM')}
- {showSpinner ?
: (DictAgendamentosOrganizados[selectedDay.format('YYYY-MM-DD')]?.length > 0) ? (DictAgendamentosOrganizados[selectedDay.format('YYYY-MM-DD')].map(app => (
-
-
{dayjs(app.scheduled_at).format('HH:mm')}
-
{app.paciente_nome}Dr(a). {app.medico_nome}
- {}
-
- ))) : (
Nenhuma consulta agendada.
)}
+ {(DictAgendamentosOrganizados[selectedDay.format('YYYY-MM-DD')]?.length > 0) ? (
+ DictAgendamentosOrganizados[selectedDay.format('YYYY-MM-DD')].map(app => (
+
+
{dayjs(app.scheduled_at).format('HH:mm')}
+
+ Consulta com Dr(a). {app.medico_nome}
+
+
+ {app.status !== 'cancelled' && dayjs(app.scheduled_at).isAfter(dayjs()) && (
+
+ )}
+
+
+ ))
+ ) : (
Nenhuma consulta agendada para esta data.
)}
- {}
Realizado
Confirmado
Agendado
Cancelado
@@ -249,41 +303,21 @@ const Agendamento = ({ setDictInfo }) => {
{currentDate.format('MMMM [de] YYYY')}
-
-
-
-
-
+
+
+
-
{weekDays.map(day =>
{day}
)}
{dateGrid.map((day, index) => {
@@ -292,11 +326,7 @@ const Agendamento = ({ setDictInfo }) => {
return (
handleDateClick(day)}>
{day.format('D')}
- {appointmentsOnDay.length > 0 &&
-
- {appointmentsOnDay.length}
-
- }
+ {appointmentsOnDay.length > 0 &&
{appointmentsOnDay.length}
}
);
})}
@@ -305,51 +335,45 @@ const Agendamento = ({ setDictInfo }) => {
) : (
-
+
-
Fila de Espera
+
Minhas Solicitações em Fila de Espera
-
-
Filtros
-
setWaitlistSearch(e.target.value)} />Digite o nome do paciente, CPF ou nome do médico
-
-
- Ordenar por:
- {(() => { const sortValue = waitSortKey ? `${waitSortKey}-${waitSortDir}` : ''; return ( { const v = e.target.value; if (!v) { setWaitSortKey(null); setWaitSortDir('asc'); return; } const [k, d] = v.split('-'); setWaitSortKey(k); setWaitSortDir(d); }}>
-
- );})()}
-
-
-
{filaEsperaFiltrada.length} DE {filaEsperaData.length} SOLICITAÇÕES ENCONTRADAS
-
-
- | Nome do Paciente | CPF | Médico Solicitado | Data da Solicitação | Ações |
+
+
+
+ | Médico Solicitado |
+ Data da Solicitação |
+ Ações |
+
+
- {filaEsperaPaginada.length > 0 ? (filaEsperaPaginada.map((item, index) => (
- | {item?.Infos?.paciente_nome} | {item?.Infos?.paciente_cpf} | {item?.Infos?.nome_medico} | {dayjs(item.agendamento.scheduled_at).format('DD/MM/YYYY')} |
-
- {}
-
- |
+ {filaEsperaData.length > 0 ? (filaEsperaData.map((item) => (
+
+ | Dr(a). {item.Infos?.medico_nome} |
+ {dayjs(item.agendamento.created_at).format('DD/MM/YYYY HH:mm')} |
+
+
+ |
- ))) : ({showSpinner ? : (<> Nenhuma solicitação encontrada. >)} |
)}
+ ))) : (
+
+ |
+ Nenhuma solicitação na fila de espera.
+ |
+
+ )}
- {filaEsperaFiltrada.length > 0 && (
-
Itens por página: { setWaitPerPage(Number(e.target.value)); setWaitPage(1); }}>
-
Página {waitPage} de {waitTotalPages} • Mostrando {waitIndiceInicial + 1}-{Math.min(waitIndiceFinal, filaEsperaFiltrada.length)} de {filaEsperaFiltrada.length}
-
)}
-
+
)}
@@ -357,8 +381,49 @@ const Agendamento = ({ setDictInfo }) => {
) : (
)}
+
+
+ {}
+ {isCancelModalOpen && (
+
+
+
+
Confirmação de Cancelamento
+
+
+
+
Qual o motivo do cancelamento?
+
+
+
+
+
+
+
+
+ )}
+ {}
)
}
-export default Agendamento;
\ No newline at end of file
+
+export default Agendamento;
diff --git a/src/pages/Agendamento.jsx b/src/pages/Agendamento.jsx
index dd01ddd..d959cb7 100644
--- a/src/pages/Agendamento.jsx
+++ b/src/pages/Agendamento.jsx
@@ -12,16 +12,18 @@ import { useAuth } from '../components/utils/AuthProvider.js';
import dayjs from 'dayjs';
import 'dayjs/locale/pt-br';
import isBetween from 'dayjs/plugin/isBetween';
-import localeData from 'dayjs/plugin/localeData';
-import { Search, ChevronLeft, ChevronRight, Edit, Trash2 } from 'lucide-react';
-import CalendarComponent from '../components/AgendarConsulta/CalendarComponent.jsx';
+import localeData from 'dayjs/plugin/localeData';
+import { Search, ChevronLeft, ChevronRight, Edit, Trash2 } from 'lucide-react';
+import CalendarComponent from '../components/AgendarConsulta/CalendarComponent.jsx';
import "./style/Agendamento.css";
import './style/FilaEspera.css';
import Spinner from '../components/Spinner.jsx';
+
dayjs.locale('pt-br');
dayjs.extend(isBetween);
-dayjs.extend(localeData);
+dayjs.extend(localeData);
+
const Agendamento = ({ setDictInfo }) => {
const navigate = useNavigate();
@@ -39,7 +41,7 @@ const Agendamento = ({ setDictInfo }) => {
const [searchTermDoctor, setSearchTermDoctor] = useState('');
const [MedicoFiltrado, setMedicoFiltrado] = useState({ id: "vazio" });
const [cacheAgendamentos, setCacheAgendamentos] = useState([]);
- const [appointmentToEdit, setAppointmentToEdit] = useState(null);
+ const [appointmentToEdit, setAppointmentToEdit] = useState(null);
const [showConfirmModal, setShowConfirmModal] = useState(false);
const [motivoCancelamento, setMotivoCancelamento] = useState("");
const [showSpinner, setShowSpinner] = useState(true);
@@ -54,13 +56,14 @@ const Agendamento = ({ setDictInfo }) => {
const [currentDate, setCurrentDate] = useState(dayjs());
const [selectedDay, setSelectedDay] = useState(dayjs());
- const [editingAppointmentId, setEditingAppointmentId] = useState(null);
+ const [editingAppointmentId, setEditingAppointmentId] = useState(null);
- const [quickJump, setQuickJump] = useState({
- month: currentDate.month(),
- year: currentDate.year()
+ const [quickJump, setQuickJump] = useState({
+ month: currentDate.month(),
+ year: currentDate.year()
});
+
const fetchAppointments = async () => {
const myHeaders = new Headers(); myHeaders.append("Authorization", authHeader); myHeaders.append("apikey", API_KEY);
const requestOptions = { method: 'GET', headers: myHeaders, redirect: 'follow' };
@@ -73,6 +76,7 @@ const Agendamento = ({ setDictInfo }) => {
}
};
+
const updateAppointmentStatus = async (id, updates) => {
const myHeaders = new Headers(); myHeaders.append("Authorization", authHeader); myHeaders.append("apikey", API_KEY); myHeaders.append("Content-Type", "application/json"); myHeaders.append("Prefer", "return=representation");
const requestOptions = { method: 'PATCH', headers: myHeaders, body: JSON.stringify(updates) };
@@ -80,7 +84,7 @@ const Agendamento = ({ setDictInfo }) => {
try {
const response = await fetch(`https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/appointments?id=eq.${id}`, requestOptions);
if (response.ok) {
- await fetchAppointments();
+ await fetchAppointments();
return true;
} else {
console.error('Erro ao atualizar agendamento:', await response.text());
@@ -92,6 +96,7 @@ const Agendamento = ({ setDictInfo }) => {
}
};
+
const deleteConsulta = async (id) => {
setShowSpinner(true);
const success = await updateAppointmentStatus(id, { status: "cancelled", cancellation_reason: motivoCancelamento, updated_at: new Date().toISOString() });
@@ -117,10 +122,12 @@ const Agendamento = ({ setDictInfo }) => {
}
};
+
const handleQuickJumpChange = (type, value) => {
setQuickJump(prev => ({ ...prev, [type]: Number(value) }));
};
+
useEffect(() => {
setQuickJump({
month: currentDate.month(),
@@ -128,12 +135,14 @@ const Agendamento = ({ setDictInfo }) => {
});
}, [currentDate]);
+
const applyQuickJump = () => {
let newDate = dayjs().year(quickJump.year).month(quickJump.month).date(1);
setCurrentDate(newDate);
- setSelectedDay(newDate);
+ setSelectedDay(newDate);
};
+
useEffect(() => {
if (!listaTodosAgendamentos.length) { setShowSpinner(false); return; }
setShowSpinner(true);
@@ -145,12 +154,12 @@ const Agendamento = ({ setDictInfo }) => {
if (!cachePacientes[agendamento.patient_id]) { cachePacientes[agendamento.patient_id] = (await GetPatientByID(agendamento.patient_id, authHeader))[0]; }
const medico = cacheMedicos[agendamento.doctor_id];
const paciente = cachePacientes[agendamento.patient_id];
-
- const agendamentoMelhorado = {
- ...agendamento,
- medico_nome: medico?.full_name,
- paciente_nome: paciente?.full_name,
- paciente_cpf: paciente?.cpf
+
+ const agendamentoMelhorado = {
+ ...agendamento,
+ medico_nome: medico?.full_name,
+ paciente_nome: paciente?.full_name,
+ paciente_cpf: paciente?.cpf
};
if (agendamento.status === "requested") { newFila.push({ agendamento: agendamentoMelhorado, Infos: agendamentoMelhorado }); }
@@ -168,12 +177,15 @@ const Agendamento = ({ setDictInfo }) => {
fetchDados();
}, [listaTodosAgendamentos, authHeader, cacheMedicos, cachePacientes]);
+
useEffect(() => {
- fetchAppointments();
+ fetchAppointments();
GetAllDoctors(authHeader).then(docs => setListaDeMedicos(docs.map(d => ({ nomeMedico: d.full_name, idMedico: d.id }))));
}, [authHeader]);
- const handleSearchMedicos = (term) => { };
+
+ const handleSearchMedicos = (term) => { };
+
const filaEsperaFiltrada = useMemo(() => {
if (!waitlistSearch.trim()) return filaEsperaData;
@@ -205,6 +217,7 @@ const Agendamento = ({ setDictInfo }) => {
};
useEffect(() => { setWaitPage(1); }, [waitlistSearch, waitSortKey, waitSortDir]);
+
const generateDateGrid = () => {
const grid = []; const startOfMonth = currentDate.startOf('month');
let currentDay = startOfMonth.subtract(startOfMonth.day(), 'day');
@@ -215,6 +228,7 @@ const Agendamento = ({ setDictInfo }) => {
const weekDays = ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'];
const handleDateClick = (day) => setSelectedDay(day);
+
const DeleteModal = () => (
@@ -229,12 +243,13 @@ const Agendamento = ({ setDictInfo }) => {
-
+
- );
+ );
+
const ConfirmEditModal = () => (
@@ -255,7 +270,8 @@ const Agendamento = ({ setDictInfo }) => {
- );
+ );
+
return (
@@ -263,9 +279,9 @@ const Agendamento = ({ setDictInfo }) => {
Agendar nova consulta
{/* LIMPA O OBJETO DE EDIÇÃO AO CLICAR EM "ADICIONAR" */}
-
) : (
-
)}
{showDeleteModal && }
@@ -442,5 +458,6 @@ const Agendamento = ({ setDictInfo }) => {
)
}
-
-export default Agendamento;
\ No newline at end of file
+
+export default Agendamento;
+
\ No newline at end of file
diff --git a/src/pages/style/FilaEspera.css b/src/pages/style/FilaEspera.css
index 358a21f..eb2777d 100644
--- a/src/pages/style/FilaEspera.css
+++ b/src/pages/style/FilaEspera.css
@@ -322,4 +322,4 @@ html[data-bs-theme="dark"] .busca-fila-espera {
html[data-bs-theme="dark"] .busca-fila-espera:focus {
border-color: #5980fd !important;
-}
\ No newline at end of file
+}