diff --git a/modules/turnero/api/create_consent_token.php b/modules/turnero/api/create_consent_token.php new file mode 100644 index 0000000..75d40d5 --- /dev/null +++ b/modules/turnero/api/create_consent_token.php @@ -0,0 +1,75 @@ +prepare("SELECT id, sesion_id, paciente_id FROM turnero_turnos WHERE id = ?"); +$stmt->execute([$turnoId]); +$turno = $stmt->fetch(PDO::FETCH_ASSOC); +if (!$turno) jsonError('Turno no encontrado.', 404); + +$pacienteId = $turno['paciente_id']; +if (!$pacienteId) jsonError('El turno no tiene paciente vinculado.'); + +// Verificar que el formulario existe +$stmt = $pdo->prepare("SELECT id, nombre FROM lab_formularios WHERE id = ? AND is_active = 1"); +$stmt->execute([$formularioId]); +$formulario = $stmt->fetch(PDO::FETCH_ASSOC); +if (!$formulario) jsonError('Formulario no encontrado o inactivo.', 404); + +// Buscar si ya existe un token +$stmt = $pdo->prepare( + "SELECT token, estado FROM turnero_consentimientos WHERE turno_id = ? AND formulario_id = ?" +); +$stmt->execute([$turnoId, $formularioId]); +$existente = $stmt->fetch(PDO::FETCH_ASSOC); + +if ($existente) { + if (in_array($existente['estado'], ['firmado', 'rechazado'], true)) { + jsonError('Este consentimiento ya fue ' . $existente['estado'] . '.', 422); + } + $token = $existente['token']; +} else { + // Generar nuevo token + $token = sprintf( + '%04x%04x-%04x-%04x-%04x-%04x%04x%04x', + mt_rand(0, 0xffff), mt_rand(0, 0xffff), + mt_rand(0, 0xffff), + mt_rand(0, 0x0fff) | 0x4000, + mt_rand(0, 0x3fff) | 0x8000, + mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) + ); + + $stmt = $pdo->prepare( + "INSERT INTO turnero_consentimientos (turno_id, formulario_id, token, estado, creado_at) + VALUES (?, ?, ?, 'pendiente', NOW())" + ); + $stmt->execute([$turnoId, $formularioId, $token]); +} + +$url = BASE_URL . 'ver_formulario_enviado.php?token=' . urlencode($token); + +jsonOk([ + 'token' => $token, + 'url' => $url, + 'nombre'=> $formulario['nombre'], +]); diff --git a/modules/turnero/api/get_lugar_formularios.php b/modules/turnero/api/get_lugar_formularios.php new file mode 100644 index 0000000..49dcbe1 --- /dev/null +++ b/modules/turnero/api/get_lugar_formularios.php @@ -0,0 +1,27 @@ +prepare( + "SELECT f.id, f.nombre + FROM turnero_lugar_consentimientos tlc + JOIN lab_formularios f ON f.id = tlc.formulario_id + WHERE tlc.lugar_id = ? + AND f.is_active = 1 + ORDER BY f.nombre ASC" +); +$stmt->execute([$lugarId]); +$formularios = $stmt->fetchAll(PDO::FETCH_ASSOC); + +jsonOk(['formularios' => $formularios]); diff --git a/modules/turnero/views/recepcion.php b/modules/turnero/views/recepcion.php index 067f303..34f2bad 100644 --- a/modules/turnero/views/recepcion.php +++ b/modules/turnero/views/recepcion.php @@ -389,7 +389,7 @@ require_once __DIR__ . '/../../../shared/components/sidebar.php'; -
+ `; + }).join(''); + sec.style.display = ''; + } catch (_) { + sec.style.display = 'none'; + } +} +async function abrirFormularioLugar(formularioId, nombre) { + if (!turnoActivo) return; + // Si ya hay solicitud guardada, usa el consent token + try { + const res = await fetch(API + 'create_consent_token.php', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ turno_id: turnoActivo.id, formulario_id: formularioId }), + }); + const json = await res.json(); + if (json.ok && json.data?.url) { + window.open(json.data.url, '_blank'); + } else { + window.open('lab_formularios.php', '_blank'); + } + } catch (_) { + window.open('lab_formularios.php', '_blank'); + } +} // ── Cola ────────────────────────────────────────────────────── async function cargarCola() { @@ -769,11 +821,11 @@ function renderConsentimientos(lista) { const ya = ['firmado','rechazado'].includes(c.estado); const token = escHtml(c.token || ''); const nom = escHtml(c.formulario_nombre || 'Consentimiento'); - const nomJs = JSON.stringify(c.formulario_nombre || 'Consentimiento'); + const fId = c.formulario_id; // Botón de firma (solo si no está firmado/rechazado) - const btnFirmar = (!ya && c.token) - ? `` : ''; @@ -798,11 +850,23 @@ function renderConsentimientos(lista) { } // ── Firmar en nueva pestaña ────────────────────────────────── -function abrirFirmaPresencialRec(token) { - window.open( - BASE_WA + 'ver_formulario_enviado.php?token=' + encodeURIComponent(token) + '&firmar=1', - '_blank' - ); +async function firmarConsentimiento(formularioId, nombre) { + if (!turnoActivo) { mostrarError('No hay turno activo.'); return; } + try { + const res = await fetch(API + 'create_consent_token.php', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ turno_id: turnoActivo.id, formulario_id: formularioId }), + }); + const json = await res.json(); + if (json.ok && json.data?.url) { + window.open(json.data.url, '_blank'); + } else { + mostrarError(json.error || 'No se pudo crear el token de firma'); + } + } catch (err) { + mostrarError('Error al abrir firma: ' + err.message); + } } function verFirmado(token) { window.open(BASE_WA + 'ver_formulario_enviado.php?token=' + encodeURIComponent(token), '_blank'); diff --git a/ver_formulario_enviado.php b/ver_formulario_enviado.php index 5d4c8b8..4713c8a 100644 --- a/ver_formulario_enviado.php +++ b/ver_formulario_enviado.php @@ -32,14 +32,15 @@ if ($modoTurnero) { tc.enviado_at, tc.firmado_at, tc.ip_firma, tc.ua_firma, tc.firma_svg, f.nombre AS form_nombre, f.categoria, f.descripcion AS form_descripcion, f.esquema, f.doc_encabezado, f.doc_subtitulo, f.doc_logo_base64, f.doc_color, f.doc_pie_pagina, - p.nombre_completo AS paciente_nombre, p.numero_documento, p.tipo_documento, + p.nombre_completo AS paciente_nombre, + p.numero_documento, p.tipo_documento, p.fecha_nacimiento, p.telefono AS paciente_telefono, p.eps, t.sesion_id FROM turnero_consentimientos tc JOIN lab_formularios f ON f.id = tc.formulario_id JOIN turnero_turnos t ON t.id = tc.turno_id - JOIN turnero_solicitudes ts ON ts.turno_id = tc.turno_id - LEFT JOIN lab_pacientes p ON p.id = ts.paciente_id + LEFT JOIN turnero_solicitudes ts ON ts.turno_id = tc.turno_id + LEFT JOIN lab_pacientes p ON p.id = COALESCE(ts.paciente_id, t.paciente_id) WHERE tc.token = ?", [$tokenTurnero] );