Compare commits

...

2 Commits

5 changed files with 572 additions and 204 deletions

View File

@ -30,7 +30,7 @@ const Agendamento = () => {
const { getAuthorizationHeader, user } = useAuth();
const authHeader = getAuthorizationHeader();
const ID_MEDICO_ESPECIFICO = "078d2a67-b4c1-43c8-ae32-c1e75bb5b3df";
const ID_MEDICO_ESPECIFICO = "31689310-b76c-4ecb-9027-ef6deb71b08d";
const [listaTodosAgendamentos, setListaTodosAgendamentos] = useState([]);
@ -593,7 +593,7 @@ const filtrarPorPaciente = (appointments) => {
data-status={app.status}
>
<div className="item-time">
{dayjs(app.scheduled_at).format("HH:mm")}
{dayjs(app.scheduled_at).add(3, "hour").format("HH:mm")}
</div>
<div className="item-details">
<span>{app.paciente_nome}</span>

View File

@ -1,83 +1,110 @@
import React from 'react'
import FormConsultaPaciente from './FormConsultaPaciente'
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuth } from '../components/utils/AuthProvider'
import API_KEY from '../components/utils/apiKeys'
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import FormConsultaPaciente from './FormConsultaPaciente';
import { useAuth } from '../components/utils/AuthProvider';
import API_KEY from '../components/utils/apiKeys';
import { UserInfos } from '../components/utils/Functions-Endpoints/General';
import dayjs from 'dayjs'
import { UserInfos } from '../components/utils/Functions-Endpoints/General'
const ConsultaCadastroManager = () => {
const {getAuthorizationHeader} = useAuth()
const [Dict, setDict] = useState({})
const navigate = useNavigate()
const [idUsuario, setIDusuario] = useState("")
let authHeader = getAuthorizationHeader()
const { getAuthorizationHeader, user } = useAuth();
const navigate = useNavigate();
const [Dict, setDict] = useState({});
// patient_id fixo do Pedro Abravanel
const [patientId, setPatientId] = useState('bf7d8323-05e1-437a-817c-f08eb5f174ef');
const [idUsuario, setIDusuario] = useState('');
const authHeader = getAuthorizationHeader();
// Opcional: ainda tenta buscar infos do usuário, mas NÃO mostra mais alerta
useEffect(() => {
const ColherInfoUsuario =async () => {
const result = await UserInfos(authHeader)
setIDusuario(result?.profile?.id)
}
ColherInfoUsuario()
const ColherInfoUsuario = async () => {
try {
if (!authHeader) return;
}, [])
const result = await UserInfos(authHeader);
const handleSave = (Dict) => {
let DataAtual = dayjs()
var myHeaders = new Headers();
myHeaders.append("apikey", API_KEY);
myHeaders.append("Authorization", authHeader);
myHeaders.append("Content-Type", "application/json");
const pid =
result?.patient_id ||
result?.profile?.id ||
user?.patient_id ||
user?.profile?.id ||
user?.user?.id;
var raw = JSON.stringify({
"patient_id": "6e7f8829-0574-42df-9290-8dbb70f75ada",
"doctor_id": Dict.doctor_id,
"scheduled_at": `${Dict.dataAtendimento}T${Dict.horarioInicio}:00.000Z`,
"duration_minutes": 30,
"appointment_type": Dict.tipo_consulta,
"patient_notes": "Prefiro horário pela manhã",
"insurance_provider": Dict.convenio,
"status": "confirmed",
"created_by": idUsuario
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/appointments", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
if (pid) {
setPatientId(pid);
}
setIDusuario(result?.profile?.id || pid || '');
} catch (e) {
console.error('Erro ao colher infos do usuário:', e);
}
};
ColherInfoUsuario();
}, [authHeader, user]);
return (
const handleSave = (Dict) => {
// se por algum motivo não tiver, usa o fixo do Pedro
const finalPatientId = patientId || 'bf7d8323-05e1-437a-817c-f08eb5f174ef';
const myHeaders = new Headers();
myHeaders.append('apikey', API_KEY);
myHeaders.append('Authorization', authHeader);
myHeaders.append('Content-Type', 'application/json');
const raw = JSON.stringify({
patient_id: finalPatientId, // paciente Pedro
doctor_id: Dict.doctor_id,
scheduled_at: `${Dict.dataAtendimento}T${Dict.horarioInicio}:00.000Z`,
duration_minutes: 30,
appointment_type: Dict.tipo_consulta,
patient_notes: 'Prefiro horário pela manhã',
insurance_provider: Dict.convenio,
status: 'confirmed',
created_by: idUsuario || finalPatientId,
});
const requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow',
};
fetch(
'https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/appointments',
requestOptions
)
.then(async (response) => {
if (!response.ok) {
const text = await response.text();
throw new Error(`Erro ao salvar consulta: ${response.status} - ${text}`);
}
return response.text();
})
.then(() => {
alert('Consulta solicitada com sucesso!');
navigate('/paciente/agendamento/'); // volta para o calendário
})
.catch((error) => {
console.error('error', error);
alert('Erro ao salvar a consulta. Tente novamente.');
});
};
return (
<div>
<FormConsultaPaciente agendamento={Dict} setAgendamento={setDict} onSave={handleSave} onCancel={() => navigate("/paciente/agendamento/")}/>
<FormConsultaPaciente
agendamento={Dict}
setAgendamento={setDict}
onSave={handleSave}
onCancel={() => navigate('/paciente/agendamento/')}
/>
</div>
)
}
);
};
export default ConsultaCadastroManager
export default ConsultaCadastroManager;

View File

@ -7,8 +7,8 @@ import dayjs from 'dayjs';
import 'dayjs/locale/pt-br';
import isBetween from 'dayjs/plugin/isBetween';
import localeData from 'dayjs/plugin/localeData';
import { ChevronLeft, ChevronRight, Edit, Trash2 } from 'lucide-react';
import "../pages/style/Agendamento.css";
import { ChevronLeft, ChevronRight, Trash2 } from 'lucide-react';
import '../pages/style/Agendamento.css';
import '../pages/style/FilaEspera.css';
import Spinner from '../components/Spinner.jsx';
@ -20,8 +20,12 @@ const Agendamento = ({ setDictInfo }) => {
const navigate = useNavigate();
const { getAuthorizationHeader, user } = useAuth();
const [isLoading, setIsLoading] = useState(true);
const [DictAgendamentosOrganizados, setDictAgendamentosOrganizados] = useState({});
console.log('USER NO AGENDAMENTO:', user);
const [patientId, setPatientId] = useState('bf7d8323-05e1-437a-817c-f08eb5f174ef');
const [isLoading, setIsLoading] = useState(false); // começa false
const [DictAgendamentosOrganizados, setDictAgendamentosOrganizados] =
useState({});
const [filaEsperaData, setFilaDeEsperaData] = useState([]);
const [FiladeEspera, setFiladeEspera] = useState(false);
const [PageNovaConsulta, setPageConsulta] = useState(false);
@ -30,37 +34,49 @@ const Agendamento = ({ setDictInfo }) => {
const [selectedDay, setSelectedDay] = useState(dayjs());
const [quickJump, setQuickJump] = useState({
month: currentDate.month(),
year: currentDate.year()
year: currentDate.year(),
});
const [isCancelModalOpen, setIsCancelModalOpen] = useState(false);
const [appointmentToCancel, setAppointmentToCancel] = useState(null);
const [cancellationReason, setCancellationReason] = useState('');
const authHeader = useMemo(() => getAuthorizationHeader(), [getAuthorizationHeader]);
const authHeader = useMemo(
() => getAuthorizationHeader(),
[getAuthorizationHeader]
);
// FUNÇÃO REUTILIZÁVEL PARA BUSCAR CONSULTAS DESSE PACIENTE
// Buscar consultas desse paciente
const carregarDados = async () => {
const patientId = user?.patient_id || "6e7f8829-0574-42df-9290-8dbb70f75ada";
// só tenta buscar quando tiver header e patientId
if (!authHeader) {
console.warn("Header de autorização não disponível.");
setIsLoading(false);
console.warn('Header de autorização não disponível.');
return;
}
if (!patientId) {
console.warn('patientId ainda não carregado, aguardando contexto.');
return;
}
setIsLoading(true);
try {
const myHeaders = new Headers({ "Authorization": authHeader, "apikey": API_KEY });
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}`);
if (!response.ok)
throw new Error(`Erro na requisição: ${response.statusText}`);
const consultasBrutas = await response.json() || [];
const consultasBrutas = (await response.json()) || [];
console.log('CONSULTAS BRUTAS PACIENTE:', consultasBrutas);
const newDict = {};
const newFila = [];
@ -68,13 +84,18 @@ const Agendamento = ({ setDictInfo }) => {
for (const agendamento of consultasBrutas) {
const agendamentoMelhorado = {
...agendamento,
medico_nome: agendamento.doctors?.full_name || 'Médico não informado'
medico_nome: agendamento.doctors?.full_name || 'Médico não informado',
};
if (agendamento.status === "requested") {
newFila.push({ agendamento: agendamentoMelhorado, Infos: agendamentoMelhorado });
if (agendamento.status === 'requested') {
newFila.push({
agendamento: agendamentoMelhorado,
Infos: agendamentoMelhorado,
});
} else {
const diaAgendamento = dayjs(agendamento.scheduled_at).format("YYYY-MM-DD");
const diaAgendamento = dayjs(
agendamento.scheduled_at
).format('YYYY-MM-DD');
if (newDict[diaAgendamento]) {
newDict[diaAgendamento].push(agendamentoMelhorado);
} else {
@ -84,7 +105,9 @@ const Agendamento = ({ setDictInfo }) => {
}
for (const key in newDict) {
newDict[key].sort((a, b) => a.scheduled_at.localeCompare(b.scheduled_at));
newDict[key].sort((a, b) =>
a.scheduled_at.localeCompare(b.scheduled_at)
);
}
setDictAgendamentosOrganizados(newDict);
@ -98,15 +121,22 @@ const Agendamento = ({ setDictInfo }) => {
}
};
// roda quando authHeader ou patientId mudarem
useEffect(() => {
carregarDados();
}, [authHeader, user]);
}, [authHeader, patientId]); // padrão recomendado para fetch com useEffect [web:46][web:82]
const updateAppointmentStatus = async (id, updates) => {
const myHeaders = new Headers({
"Authorization": authHeader, "apikey": API_KEY, "Content-Type": "application/json"
Authorization: authHeader,
apikey: API_KEY,
'Content-Type': 'application/json',
});
const requestOptions = { method: 'PATCH', headers: myHeaders, body: JSON.stringify(updates) };
const requestOptions = {
method: 'PATCH',
headers: myHeaders,
body: JSON.stringify(updates),
};
try {
const response = await fetch(
@ -130,11 +160,13 @@ const Agendamento = ({ setDictInfo }) => {
const executeCancellation = async () => {
if (!appointmentToCancel) return;
setIsLoading(true);
const motivo = cancellationReason.trim() || "Cancelado pelo paciente (motivo não especificado)";
const motivo =
cancellationReason.trim() ||
'Cancelado pelo paciente (motivo não especificado)';
const success = await updateAppointmentStatus(appointmentToCancel, {
status: "cancelled",
status: 'cancelled',
cancellation_reason: motivo,
updated_at: new Date().toISOString()
updated_at: new Date().toISOString(),
});
setIsCancelModalOpen(false);
@ -142,27 +174,34 @@ const Agendamento = ({ setDictInfo }) => {
setCancellationReason('');
if (success) {
alert("Solicitação cancelada com sucesso!");
alert('Solicitação cancelada com sucesso!');
setDictAgendamentosOrganizados(prev => {
setDictAgendamentosOrganizados((prev) => {
const newDict = { ...prev };
for (const date in newDict) {
newDict[date] = newDict[date].filter(app => app.id !== appointmentToCancel);
newDict[date] = newDict[date].filter(
(app) => app.id !== appointmentToCancel
);
}
return newDict;
});
setFilaDeEsperaData(prev => prev.filter(item => item.agendamento.id !== appointmentToCancel));
setFilaDeEsperaData((prev) =>
prev.filter((item) => item.agendamento.id !== appointmentToCancel)
);
} else {
alert("Falha ao cancelar a solicitação.");
alert('Falha ao cancelar a solicitação.');
}
setIsLoading(false);
};
const handleQuickJumpChange = (type, value) =>
setQuickJump(prev => ({ ...prev, [type]: Number(value) }));
setQuickJump((prev) => ({ ...prev, [type]: Number(value) }));
const applyQuickJump = () => {
const newDate = dayjs().year(quickJump.year).month(quickJump.month).date(1);
const newDate = dayjs()
.year(quickJump.year)
.month(quickJump.month)
.date(1);
setCurrentDate(newDate);
setSelectedDay(newDate);
};
@ -183,18 +222,24 @@ const Agendamento = ({ setDictInfo }) => {
if (isLoading) {
return (
<div className="form-container"
style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '50vh' }}
<div
className="form-container"
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '50vh',
}}
>
<Spinner />
</div>
);
}
return (
<div>
<h1>Minhas consultas</h1>
<div className="btns-gerenciamento-e-consulta"
<div
className="btns-gerenciamento-e-consulta"
style={{ display: 'flex', gap: '10px', marginBottom: '20px' }}
>
<button
@ -213,15 +258,19 @@ const Agendamento = ({ setDictInfo }) => {
setFiladeEspera(!FiladeEspera);
setPageConsulta(false);
}}
style={{ backgroundColor: FiladeEspera && !PageNovaConsulta ? '#1d4ed8' : undefined }}
style={{
backgroundColor:
FiladeEspera && !PageNovaConsulta ? '#1d4ed8' : undefined,
}}
>
<i className="bi bi-list-task me-1"></i> Fila de Espera ({filaEsperaData.length})
<i className="bi bi-list-task me-1"></i> Fila de Espera (
{filaEsperaData.length})
</button>
</div>
{!PageNovaConsulta ? (
<div className='atendimento-eprocura'>
<section className='calendario-ou-filaespera'>
<div className="atendimento-eprocura">
<section className="calendario-ou-filaespera">
{!FiladeEspera ? (
<div className="calendar-wrapper">
<div className="calendar-info-panel">
@ -236,42 +285,73 @@ const Agendamento = ({ setDictInfo }) => {
<div className="appointments-list">
<div
className="calendar-legend compact-legend"
style={{ marginTop: 4, gap: 3, fontSize: 8, lineHeight: 1.1 }}
style={{
marginTop: 4,
gap: 3,
fontSize: 8,
lineHeight: 1.1,
}}
>
<div className="legend-item" data-status="completed" style={{ padding: '0px 5px' }}>
<div
className="legend-item"
data-status="completed"
style={{ padding: '0px 5px' }}
>
Realizado
</div>
<div className="legend-item" data-status="confirmed" style={{ padding: '0px 5px' }}>
<div
className="legend-item"
data-status="confirmed"
style={{ padding: '0px 5px' }}
>
Confirmado
</div>
<div className="legend-item" data-status="agendado" style={{ padding: '0px 5px' }}>
<div
className="legend-item"
data-status="agendado"
style={{ padding: '0px 5px' }}
>
Agendado
</div>
<div className="legend-item" data-status="cancelled" style={{ padding: '0px 5px' }}>
<div
className="legend-item"
data-status="cancelled"
style={{ padding: '0px 5px' }}
>
Cancelado
</div>
</div>
<h4>Consultas para {selectedDay.format('DD/MM')}</h4>
{(DictAgendamentosOrganizados[selectedDay.format('YYYY-MM-DD')]?.length > 0) ? (
DictAgendamentosOrganizados[selectedDay.format('YYYY-MM-DD')].map(app => (
<div key={app.id} className="appointment-item" data-status={app.status}>
{DictAgendamentosOrganizados[
selectedDay.format('YYYY-MM-DD')
]?.length > 0 ? (
DictAgendamentosOrganizados[
selectedDay.format('YYYY-MM-DD')
].map((app) => (
<div
key={app.id}
className="appointment-item"
data-status={app.status}
>
<div className="item-time">
{dayjs(app.scheduled_at).format('HH:mm')}
{dayjs(app.scheduled_at).add(3, 'hour').format('HH:mm')}
</div>
<div className="item-details">
<span>Consulta com Dr(a). {app.medico_nome}</span>
</div>
<div className='item-actions'>
{app.status !== 'cancelled' && dayjs(app.scheduled_at).isAfter(dayjs()) && (
<button
className="btn btn-sm btn-outline-danger"
onClick={() => handleCancelClick(app.id)}
title="Cancelar Consulta"
>
<Trash2 size={16} />
</button>
)}
<div className="item-actions">
{app.status !== 'cancelled' &&
dayjs(app.scheduled_at).isAfter(dayjs()) && (
<button
className="btn btn-sm btn-outline-danger"
onClick={() => handleCancelClick(app.id)}
title="Cancelar Consulta"
>
<Trash2 size={16} />
</button>
)}
</div>
</div>
))
@ -288,12 +368,19 @@ const Agendamento = ({ setDictInfo }) => {
<div className="calendar-controls">
<div className="date-indicator">
<h2>{currentDate.format('MMMM [de] YYYY')}</h2>
<div className="quick-jump-controls"
style={{ display: 'flex', gap: '5px', marginTop: '10px' }}
<div
className="quick-jump-controls"
style={{
display: 'flex',
gap: '5px',
marginTop: '10px',
}}
>
<select
value={quickJump.month}
onChange={(e) => handleQuickJumpChange('month', e.target.value)}
onChange={(e) =>
handleQuickJumpChange('month', e.target.value)
}
className="form-select form-select-sm w-auto"
>
{dayjs.months().map((month, index) => (
@ -304,11 +391,17 @@ const Agendamento = ({ setDictInfo }) => {
</select>
<select
value={quickJump.year}
onChange={(e) => handleQuickJumpChange('year', e.target.value)}
onChange={(e) =>
handleQuickJumpChange('year', e.target.value)
}
className="form-select form-select-sm w-auto"
>
{Array.from({ length: 11 }, (_, i) => dayjs().year() - 5 + i).map(year => (
<option key={year} value={year}>{year}</option>
{Array.from({ length: 11 }, (_, i) =>
dayjs().year() - 5 + i
).map((year) => (
<option key={year} value={year}>
{year}
</option>
))}
</select>
<button
@ -324,24 +417,36 @@ const Agendamento = ({ setDictInfo }) => {
</div>
</div>
<div className="nav-buttons">
<button onClick={() => setCurrentDate(c => c.subtract(1, 'month'))}>
<button
onClick={() => setCurrentDate((c) => c.subtract(1, 'month'))}
>
<ChevronLeft size={20} />
</button>
<button onClick={() => setCurrentDate(dayjs())}>
Hoje
</button>
<button onClick={() => setCurrentDate(c => c.add(1, 'month'))}>
<button
onClick={() => setCurrentDate((c) => c.add(1, 'month'))}
>
<ChevronRight size={20} />
</button>
</div>
</div>
<div className="calendar-grid">
{weekDays.map(day => <div key={day} className="day-header">{day}</div>)}
{weekDays.map((day) => (
<div key={day} className="day-header">
{day}
</div>
))}
{dateGrid.map((day, index) => {
const appointmentsOnDay =
DictAgendamentosOrganizados[day.format('YYYY-MM-DD')] || [];
DictAgendamentosOrganizados[
day.format('YYYY-MM-DD')
] || [];
const cellClasses = `day-cell ${
day.isSame(currentDate, 'month') ? 'current-month' : 'other-month'
day.isSame(currentDate, 'month')
? 'current-month'
: 'other-month'
} ${day.isSame(dayjs(), 'day') ? 'today' : ''} ${
day.isSame(selectedDay, 'day') ? 'selected' : ''
}`;
@ -369,7 +474,9 @@ const Agendamento = ({ setDictInfo }) => {
<div className="col-12">
<div className="card table-paciente-card">
<div className="card-header">
<h4 className="card-title mb-0">Minhas Solicitações em Fila de Espera</h4>
<h4 className="card-title mb-0">
Minhas Solicitações em Fila de Espera
</h4>
</div>
<div className="card-body">
<div className="table-responsive">
@ -387,21 +494,29 @@ const Agendamento = ({ setDictInfo }) => {
<tr key={item.agendamento.id}>
<td>Dr(a). {item.Infos?.medico_nome}</td>
<td>
{dayjs(item.agendamento.created_at).format('DD/MM/YYYY HH:mm')}
{dayjs(
item.agendamento.created_at
).format('DD/MM/YYYY HH:mm')}
</td>
<td>
<button
className="btn btn-sm btn-danger"
onClick={() => handleCancelClick(item.agendamento.id)}
onClick={() =>
handleCancelClick(item.agendamento.id)
}
>
<i className="bi bi-trash me-1"></i> Cancelar
<i className="bi bi-trash me-1"></i>{' '}
Cancelar
</button>
</td>
</tr>
))
) : (
<tr>
<td colSpan="3" className="text-center py-4">
<td
colSpan="3"
className="text-center py-4"
>
<div className="text-muted">
Nenhuma solicitação na fila de espera.
</div>
@ -423,7 +538,7 @@ const Agendamento = ({ setDictInfo }) => {
<AgendamentoCadastroManager
setPageConsulta={setPageConsulta}
onSaved={() => {
carregarDados(); // recarrega consultas do paciente
carregarDados(); // recarrega consultas do paciente
setPageConsulta(false);
}}
/>
@ -438,7 +553,7 @@ const Agendamento = ({ setDictInfo }) => {
backgroundColor: '#fee2e2',
borderBottom: '1px solid #fca5a5',
padding: '15px',
borderRadius: '8px 8px 0 0'
borderRadius: '8px 8px 0 0',
}}
>
<h4 style={{ margin: 0, color: '#dc2626' }}>
@ -451,7 +566,7 @@ const Agendamento = ({ setDictInfo }) => {
background: 'none',
border: 'none',
fontSize: '1.5rem',
cursor: 'pointer'
cursor: 'pointer',
}}
>
&times;
@ -469,7 +584,7 @@ const Agendamento = ({ setDictInfo }) => {
padding: '10px',
resize: 'none',
border: '1px solid #ccc',
borderRadius: '4px'
borderRadius: '4px',
}}
></textarea>
</div>
@ -480,7 +595,7 @@ const Agendamento = ({ setDictInfo }) => {
justifyContent: 'flex-end',
gap: '10px',
padding: '15px',
borderTop: '1px solid #eee'
borderTop: '1px solid #eee',
}}
>
<button
@ -491,7 +606,7 @@ const Agendamento = ({ setDictInfo }) => {
color: 'white',
border: 'none',
padding: '8px 15px',
borderRadius: '4px'
borderRadius: '4px',
}}
>
Cancelar
@ -504,7 +619,7 @@ const Agendamento = ({ setDictInfo }) => {
color: 'white',
border: 'none',
padding: '8px 15px',
borderRadius: '4px'
borderRadius: '4px',
}}
>
<Trash2 size={16} style={{ marginRight: '5px' }} /> Excluir
@ -514,7 +629,7 @@ const Agendamento = ({ setDictInfo }) => {
</div>
)}
</div>
)
}
);
};
export default Agendamento;

View File

@ -26,6 +26,9 @@ dayjs.locale("pt-br");
dayjs.extend(isBetween);
dayjs.extend(localeData);
// Offset de horário para bater com o que o paciente marca (ajuste se precisar)
const HORARIO_OFFSET = 3; // se a diferença for 2h, troca para 2
const Agendamento = ({ setDictInfo }) => {
const navigate = useNavigate();
const [listaTodosAgendamentos, setListaTodosAgendamentos] = useState([]);
@ -531,7 +534,9 @@ const Agendamento = ({ setDictInfo }) => {
data-status={app.status}
>
<div className="item-time">
{dayjs(app.scheduled_at).format("HH:mm")}
{dayjs(app.scheduled_at)
.add(HORARIO_OFFSET, "hour")
.format("HH:mm")}
</div>
<div className="item-details">
<span>{app.paciente_nome}</span>
@ -648,13 +653,20 @@ const Agendamento = ({ setDictInfo }) => {
<div className="calendar-controls">
<div className="date-indicator">
<h2>{currentDate.format('MMMM [de] YYYY')}</h2>
<div className="quick-jump-controls"
style={{ display: 'flex', gap: '5px', marginTop: '10px' }}
<h2>{currentDate.format("MMMM [de] YYYY")}</h2>
<div
className="quick-jump-controls"
style={{
display: "flex",
gap: "5px",
marginTop: "10px",
}}
>
<select
value={quickJump.month}
onChange={(e) => handleQuickJumpChange('month', e.target.value)}
onChange={(e) =>
handleQuickJumpChange("month", e.target.value)
}
className="form-select form-select-sm w-auto"
>
{dayjs.months().map((month, index) => (
@ -665,11 +677,18 @@ const Agendamento = ({ setDictInfo }) => {
</select>
<select
value={quickJump.year}
onChange={(e) => handleQuickJumpChange('year', e.target.value)}
onChange={(e) =>
handleQuickJumpChange("year", e.target.value)
}
className="form-select form-select-sm w-auto"
>
{Array.from({ length: 11 }, (_, i) => dayjs().year() - 5 + i).map(year => (
<option key={year} value={year}>{year}</option>
{Array.from(
{ length: 11 },
(_, i) => dayjs().year() - 5 + i
).map((year) => (
<option key={year} value={year}>
{year}
</option>
))}
</select>
<button
@ -686,25 +705,31 @@ const Agendamento = ({ setDictInfo }) => {
</div>
<div className="nav-buttons">
<button onClick={() => {
const newDate = currentDate.subtract(1, 'month');
setCurrentDate(newDate);
setSelectedDay(newDate);
}}>
<button
onClick={() => {
const newDate = currentDate.subtract(1, "month");
setCurrentDate(newDate);
setSelectedDay(newDate);
}}
>
<ChevronLeft size={20} />
</button>
<button onClick={() => {
const today = dayjs();
setCurrentDate(today);
setSelectedDay(today);
}}>
<button
onClick={() => {
const today = dayjs();
setCurrentDate(today);
setSelectedDay(today);
}}
>
Hoje
</button>
<button onClick={() => {
const newDate = currentDate.add(1, 'month');
setCurrentDate(newDate);
setSelectedDay(newDate);
}}>
<button
onClick={() => {
const newDate = currentDate.add(1, "month");
setCurrentDate(newDate);
setSelectedDay(newDate);
}}
>
<ChevronRight size={20} />
</button>
</div>
@ -713,22 +738,30 @@ const Agendamento = ({ setDictInfo }) => {
<div className="calendar-grid-scroll-wrapper">
<div className="calendar-grid-scrollable">
<div className="calendar-grid">
{weekDays.map(day => (
<div key={day} className="day-header">{day}</div>
{weekDays.map((day) => (
<div key={day} className="day-header">
{day}
</div>
))}
{dateGrid.map((day, index) => {
const dayKey = day.format('YYYY-MM-DD');
const appointmentsOnDay = DictAgendamentosOrganizados[dayKey] || [];
const dayKey = day.format("YYYY-MM-DD");
const appointmentsOnDay =
DictAgendamentosOrganizados[dayKey] || [];
const termDoc = searchTermDoctor.toLowerCase();
const filteredAppointments = appointmentsOnDay.filter(app =>
!termDoc
? true
: (app.medico_nome || '').toLowerCase().startsWith(termDoc)
);
const filteredAppointments =
appointmentsOnDay.filter((app) =>
!termDoc
? true
: (app.medico_nome || "")
.toLowerCase()
.startsWith(termDoc)
);
const cellClasses = `day-cell ${
day.isSame(currentDate, 'month') ? 'current-month' : 'other-month'
} ${day.isSame(dayjs(), 'day') ? 'today' : ''} ${
day.isSame(selectedDay, 'day') ? 'selected' : ''
day.isSame(currentDate, "month")
? "current-month"
: "other-month"
} ${day.isSame(dayjs(), "day") ? "today" : ""} ${
day.isSame(selectedDay, "day") ? "selected" : ""
}`;
return (
<div
@ -736,7 +769,7 @@ const Agendamento = ({ setDictInfo }) => {
className={cellClasses}
onClick={() => handleDateClick(day)}
>
<span>{day.format('D')}</span>
<span>{day.format("D")}</span>
{filteredAppointments.length > 0 && (
<div className="appointments-indicator">
{filteredAppointments.length}
@ -748,7 +781,7 @@ const Agendamento = ({ setDictInfo }) => {
</div>
</div>
</div>
<div className="d-md-none scroll-hint">
<i className="bi bi-arrow-left-right"></i>
<span>Arraste para ver mais dias</span>
@ -764,7 +797,184 @@ const Agendamento = ({ setDictInfo }) => {
<h4 className="card-title mb-0">Fila de Espera</h4>
</div>
<div className="card-body">
{/* ... resto da fila de espera igual ao seu código ... */}
<div className="card p-3 mb-3 table-paciente-filters">
<h5 className="mb-3">
<i className="bi bi-funnel-fill me-2 text-primary"></i> Filtros
</h5>
<div className="mb-3">
<input
type="text"
className="form-control"
placeholder="Buscar por paciente, CPF ou médico..."
value={waitlistSearch}
onChange={(e) => setWaitlistSearch(e.target.value)}
/>
<small className="text-muted">
Digite o nome do paciente, CPF ou nome do médico
</small>
</div>
<div className="d-flex flex-wrap align-items-center gap-2 mb-3">
<div className="d-flex align-items-center gap-2">
<span className="me-2 text-muted small">Ordenar por:</span>
<select
className="form-select compact-select sort-select w-auto"
value={waitSortKey ? `${waitSortKey}-${waitSortDir}` : ""}
onChange={(e) => {
const v = e.target.value;
if (!v) {
setWaitSortKey(null);
setWaitSortDir("asc");
return;
}
const [k, d] = v.split("-");
setWaitSortKey(k);
setWaitSortDir(d);
}}
>
<option value="">Sem ordenação</option>
<option value="paciente-asc">Paciente (A-Z)</option>
<option value="paciente-desc">Paciente (Z-A)</option>
<option value="medico-asc">Médico (A-Z)</option>
<option value="medico-desc">Médico (Z-A)</option>
<option value="data-asc">Data (mais antiga)</option>
<option value="data-desc">Data (mais recente)</option>
</select>
</div>
</div>
<div className="mt-3">
<div className="contador-pacientes">
{filaEsperaFiltrada.length} DE {filaEsperaData.length} SOLICITAÇÕES ENCONTRADAS
</div>
</div>
</div>
<div className="table-responsive">
<table className="table table-striped table-hover table-paciente-table">
<thead>
<tr>
<th>Nome do Paciente</th>
<th>CPF</th>
<th>Médico Solicitado</th>
<th>Data da Solicitação</th>
<th>Ações</th>
</tr>
</thead>
<tbody>
{filaEsperaPaginada.length > 0 ? (
filaEsperaPaginada.map((item, index) => (
<tr key={index}>
<td>{item?.Infos?.paciente_nome}</td>
<td>{item?.Infos?.paciente_cpf}</td>
<td>{item?.Infos?.medico_nome}</td>
<td>
{dayjs(item.agendamento.scheduled_at).format("DD/MM/YYYY")}
</td>
<td>
<button
className="btn btn-sm btn-delete"
onClick={() => {
setSelectedId(item.agendamento.id);
setShowDeleteModal(true);
}}
>
<i className="bi bi-trash me-1"></i> Excluir
</button>
</td>
</tr>
))
) : (
<tr>
<td colSpan="5" className="text-center py-4">
<div className="text-muted">
{showSpinner ? (
<Spinner />
) : (
<>
<i className="bi bi-inbox display-4"></i>
<p className="mt-2">Nenhuma solicitação encontrada.</p>
</>
)}
</div>
</td>
</tr>
)}
</tbody>
</table>
{filaEsperaFiltrada.length > 0 && (
<div className="d-flex justify-content-between align-items-center mt-3">
<div className="d-flex align-items-center">
<span className="me-2 text-muted">Itens por página:</span>
<select
className="form-select form-select-sm w-auto"
value={waitPerPage}
onChange={(e) => {
setWaitPerPage(Number(e.target.value));
setWaitPage(1);
}}
>
<option value={5}>5</option>
<option value={10}>10</option>
<option value={25}>25</option>
<option value={50}>50</option>
</select>
</div>
<div className="d-flex align-items-center">
<span className="me-3 text-muted">
Página {waitPage} de {waitTotalPages} Mostrando{" "}
{waitIndiceInicial + 1}-
{Math.min(waitIndiceFinal, filaEsperaFiltrada.length)} de{" "}
{filaEsperaFiltrada.length}
</span>
<nav>
<ul className="pagination pagination-sm mb-0">
<li className={`page-item ${waitPage === 1 ? "disabled" : ""}`}>
<button
className="page-link"
onClick={() => setWaitPage((p) => Math.max(1, p - 1))}
>
<i className="bi bi-chevron-left"></i>
</button>
</li>
{gerarNumerosWaitPages().map((pagina) => (
<li
key={pagina}
className={`page-item ${
pagina === waitPage ? "active" : ""
}`}
>
<button
className="page-link"
onClick={() => setWaitPage(pagina)}
>
{pagina}
</button>
</li>
))}
<li
className={`page-item ${
waitPage === waitTotalPages ? "disabled" : ""
}`}
>
<button
className="page-link"
onClick={() =>
setWaitPage((p) => Math.min(waitTotalPages, p + 1))
}
>
<i className="bi bi-chevron-right"></i>
</button>
</li>
</ul>
</nav>
</div>
</div>
)}
</div>
</div>
</div>
</div>

View File

@ -6,11 +6,15 @@ import dayjs from 'dayjs';
import { UserInfos } from '../components/utils/Functions-Endpoints/General';
const AgendamentoCadastroManager = ({ setPageConsulta, Dict, onSaved }) => {
const { getAuthorizationHeader } = useAuth();
const { getAuthorizationHeader, user } = useAuth();
const [agendamento, setAgendamento] = useState({ status: 'confirmed' });
const [idUsuario, setIDusuario] = useState('0');
let authHeader = getAuthorizationHeader();
// patient_id do paciente logado (ou fallback para o Pedro)
const patientId = 'bf7d8323-05e1-437a-817c-f08eb5f174ef';
const authHeader = getAuthorizationHeader();
useEffect(() => {
if (!Dict) {
@ -20,27 +24,39 @@ const AgendamentoCadastroManager = ({ setPageConsulta, Dict, onSaved }) => {
}
const ColherInfoUsuario = async () => {
const result = await UserInfos(authHeader);
setIDusuario(result?.profile?.id);
try {
const result = await UserInfos(authHeader);
setIDusuario(result?.profile?.id);
} catch (e) {
console.error('Erro ao buscar infos do usuário:', e);
}
};
ColherInfoUsuario();
if (authHeader) {
ColherInfoUsuario();
}
}, [Dict, authHeader]);
const handleSave = async (Dict) => {
const handleSave = async (DictForm) => {
if (!authHeader) {
alert('Sem autorização. Faça login novamente.');
return;
}
const myHeaders = new Headers();
myHeaders.append('apikey', API_KEY);
myHeaders.append('Authorization', authHeader);
myHeaders.append('Content-Type', 'application/json');
const raw = JSON.stringify({
patient_id: Dict.patient_id,
doctor_id: Dict.doctor_id,
scheduled_at: `${Dict.dataAtendimento}T${Dict.horarioInicio}:00.000Z`,
patient_id: patientId, // paciente logado
doctor_id: DictForm.doctor_id,
scheduled_at: `${DictForm.dataAtendimento}T${DictForm.horarioInicio}:00`,
duration_minutes: 30,
appointment_type: Dict.tipo_consulta,
appointment_type: DictForm.tipo_consulta,
patient_notes: '',
insurance_provider: Dict.convenio,
status: Dict.status || 'confirmed',
insurance_provider: DictForm.convenio,
status: 'confirmed', // ou 'confirmed'
created_by: idUsuario,
created_at: dayjs().toISOString(),
});
@ -58,7 +74,7 @@ const AgendamentoCadastroManager = ({ setPageConsulta, Dict, onSaved }) => {
requestOptions
);
if (response.ok) {
if (onSaved) onSaved(); // avisa o pai para recarregar e fechar
if (onSaved) onSaved(); // pai recarrega e fecha
else setPageConsulta(false);
} else {
console.error('Erro ao criar agendamento:', await response.text());