This commit is contained in:
Lizandro Guarnizo
2026-06-16 11:07:24 -05:00
parent 6a8a8e0826
commit ea40cf8dae
2 changed files with 52 additions and 11 deletions
+2 -2
View File
@@ -121,8 +121,8 @@ try {
// Crear o recuperar estado de cada consentimiento requerido
$stmtCreateConsent = $pdo->prepare(
"INSERT IGNORE INTO turnero_consentimientos (turno_id, formulario_id, estado, creado_at)
VALUES (?, ?, 'pendiente', NOW())"
"INSERT IGNORE INTO turnero_consentimientos (turno_id, formulario_id, token, estado)
VALUES (?, ?, UUID(), 'pendiente')"
);
foreach ($consentimientosRequeridos as &$c) {
$stmtCreateConsent->execute([$turnoId, $c['formulario_id']]);
+50 -9
View File
@@ -443,6 +443,8 @@ const API_PAC = '<?= BASE_URL ?>api/lab/get_pacientes.php';
const DESK_ID = <?= $deskId ?: 'null' ?>;
// ── Arranque ──────────────────────────────────────────────────
let pollingConsentimientosId = null;
document.addEventListener('DOMContentLoaded', () => {
cargarCola();
pollingColaId = setInterval(cargarCola, 3000);
@@ -452,28 +454,45 @@ document.addEventListener('DOMContentLoaded', () => {
.addEventListener('change', onLugarChange);
// Refrescar consentimientos al volver a la pestaña (firma en otra pestaña)
document.addEventListener('visibilitychange', () => {
if (!document.hidden && turnoActivo) refrescarConsentimientos(turnoActivo.id);
if (!document.hidden && turnoActivo) refrescarConsentimientosLugar();
});
});
// ── Formularios del lugar ────────────────────────────────────
// ── Polling automático de consentimientos cuando hay uno abierto ──
async function refrescarConsentimientosLugar() {
if (!turnoActivo) return;
try {
const res = await fetch(`${API}get_consentimientos.php?turno_id=${turnoActivo.id}`);
const json = await res.json();
if (json.ok && json.consentimientos) {
consentimientos = json.consentimientos;
renderConsentimientos(consentimientos);
}
} catch (_) {}
}
// ── Formularios del lugar (aparecen al seleccionar lugar) ────
async function onLugarChange() {
const sec = document.getElementById('sec-consentimientos');
const lista = document.getElementById('lista-consentimientos');
const lugarId = parseInt(document.getElementById('sel-lugar').value);
if (!lugarId || !pacienteActivo) { sec.style.display = 'none'; return; }
if (!lugarId) { sec.style.display = 'none'; return; }
try {
const res = await fetch(`${API}get_lugar_formularios.php?lugar_id=${lugarId}`);
const json = await res.json();
if (!json.ok || !json.data?.formularios?.length) { sec.style.display = 'none'; return; }
if (!json.ok || !json.data?.formularios?.length) {
sec.style.display = 'none';
return;
}
lista.innerHTML = json.data.formularios.map(f => {
const nom = escHtml(f.nombre);
const disabled = !turnoActivo ? 'disabled title="Llama el turno primero"' : '';
return `<div class="consent-item pendiente">
<i class="fas fa-file-signature"></i>
<span class="c-nom">${nom}</span>
<div class="consent-acciones">
<button class="btn btn-outline-primary"
<button class="btn btn-outline-primary" ${disabled}
onclick="abrirFormularioLugar(${f.id}, '${nom.replace(/'/g, "\\'")}')"
title="Abrir formulario en nueva pestaña">
<i class="fas fa-external-link-alt"></i> Firmar
@@ -757,6 +776,13 @@ async function guardarSolicitud() {
const lugarId = parseInt(document.getElementById('sel-lugar').value);
if (!lugarId) { mostrarError('Seleccione el lugar destino.'); return; }
// ✅ VALIDACIÓN: verificar que los consentimientos del lugar estén firmados
const consentPendientes = Array.from(document.querySelectorAll('.consent-item.pendiente, .consent-item.enviado, .consent-item.visto')).length;
if (consentPendientes > 0) {
mostrarError('⚠️ El paciente debe firmar los consentimientos del lugar antes de guardar la solicitud.');
return;
}
const examIds = Array.from(document.querySelectorAll('.exam-chk:checked')).map(c => parseInt(c.value));
if (!examIds.length) { mostrarError('Seleccione al menos un examen.'); return; }
@@ -786,10 +812,19 @@ async function guardarSolicitud() {
btn.innerHTML = '<i class="fas fa-check me-1"></i>Guardado';
// Mostrar consentimientos (siempre — son todos los formularios del lab)
renderConsentimientos(consentimientos);
document.getElementById('sec-consentimientos').style.display = '';
document.getElementById('btn-enviar-consent').classList.remove('d-none');
// Detener polling de consentimientos (ya se guardó)
if (pollingConsentimientosId) {
clearInterval(pollingConsentimientosId);
pollingConsentimientosId = null;
}
// No mostrar consentimientos post-guardado aquí (ya vienen de create_solicitud)
// Solo renderizar si vienen nuevos
if (consentimientos && consentimientos.length > 0) {
renderConsentimientos(consentimientos);
document.getElementById('sec-consentimientos').style.display = '';
document.getElementById('btn-enviar-consent').classList.remove('d-none');
}
document.getElementById('btn-pasar-lugar').classList.remove('d-none');
document.getElementById('btn-guardar').classList.add('d-none');
@@ -861,6 +896,12 @@ async function firmarConsentimiento(formularioId, nombre) {
const json = await res.json();
if (json.ok && json.data?.url) {
window.open(json.data.url, '_blank');
// Iniciar polling automático para detectar firma
if (!pollingConsentimientosId) {
pollingConsentimientosId = setInterval(() => {
refrescarConsentimientosLugar();
}, 3000);
}
} else {
mostrarError(json.error || 'No se pudo crear el token de firma');
}