From 375cba86eb6931b8927a02fbfc539f0ceb73a162 Mon Sep 17 00:00:00 2001 From: Lizandro Guarnizo <77708265+lizandrogd@users.noreply.github.com> Date: Thu, 11 Jun 2026 23:11:32 -0500 Subject: [PATCH] up --- ...60611_turnero_consentimiento_principal.sql | 10 -- modules/turnero/api/create_turno.php | 95 ++++++++----------- modules/turnero/api/send_consentimiento.php | 22 ----- modules/turnero/api/set_principal_consent.php | 45 --------- modules/turnero/views/configuracion.php | 58 +---------- modules/turnero/views/display_global.php | 2 +- modules/turnero/views/recepcion.php | 17 +--- 7 files changed, 44 insertions(+), 205 deletions(-) delete mode 100644 migrations/20260611_turnero_consentimiento_principal.sql delete mode 100644 modules/turnero/api/set_principal_consent.php diff --git a/migrations/20260611_turnero_consentimiento_principal.sql b/migrations/20260611_turnero_consentimiento_principal.sql deleted file mode 100644 index d046b2e..0000000 --- a/migrations/20260611_turnero_consentimiento_principal.sql +++ /dev/null @@ -1,10 +0,0 @@ --- ============================================================ --- Migration: 20260611_turnero_consentimiento_principal --- Añade flag is_principal a lab_formularios para marcar --- el consentimiento principal de recepción (no ligado a exámenes). --- ============================================================ - -ALTER TABLE lab_formularios - ADD COLUMN is_principal TINYINT(1) NOT NULL DEFAULT 0 - COMMENT '1 = consentimiento principal de recepción, se auto-crea al tomar turno' - AFTER tipo; diff --git a/modules/turnero/api/create_turno.php b/modules/turnero/api/create_turno.php index 6556b5c..a0b2e4b 100644 --- a/modules/turnero/api/create_turno.php +++ b/modules/turnero/api/create_turno.php @@ -98,67 +98,48 @@ try { notificarSSE($sesionId); - // ── Auto-crear consentimiento principal + enviar WhatsApp ── - try { - $stmtPc = $pdo->prepare( - "SELECT id, nombre FROM lab_formularios WHERE is_principal = 1 AND tipo = 'consentimiento' AND is_active = 1 LIMIT 1" - ); - $stmtPc->execute(); - $principalForm = $stmtPc->fetch(PDO::FETCH_ASSOC); - if ($principalForm) { - $tokenPrincipal = 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) + // ── Enviar notificación WhatsApp con la plantilla configurada ── + if ($pacienteTel) { + try { + $stmtCfg = $pdo->prepare( + "SELECT clave, valor FROM lab_config WHERE clave IN ('turnero_wa_template','turnero_wa_lang')" ); - $stmtIns = $pdo->prepare( - "INSERT IGNORE INTO turnero_consentimientos (turno_id, formulario_id, token, estado) - VALUES (?, ?, ?, 'pendiente')" - ); - $stmtIns->execute([$turnoId, (int)$principalForm['id'], $tokenPrincipal]); + $stmtCfg->execute(); + $cfgWA = $stmtCfg->fetchAll(PDO::FETCH_KEY_PAIR); + $waTemplate = $cfgWA['turnero_wa_template'] ?? 'consentimiento_turno'; + $waLang = $cfgWA['turnero_wa_lang'] ?? 'es_CO'; + } catch (\Throwable $e) { + $waTemplate = 'consentimiento_turno'; + $waLang = 'es_CO'; + } - // Enviar WhatsApp si tenemos celular - if ($pacienteTel) { - $cel = preg_replace('/[\s\-\.]/', '', $pacienteTel); - if (!str_starts_with($cel, '+')) { - $cel = '+57' . ltrim($cel, '0'); - } - $enlaceFirma = (defined('BASE_URL') ? rtrim(BASE_URL, '/') : '') - . '/ver_formulario_enviado.php?token=' . urlencode($tokenPrincipal); - $nombrePacWA = $pacienteNombre ?: 'Paciente'; - require_once __DIR__ . '/../../../services/WhatsAppService.php'; - try { - $wa = new WhatsAppService(); - $wa->sendTemplateMessage( - $cel, - 'consentimiento_turno', - 'es', - [ - htmlspecialchars($nombrePacWA, ENT_QUOTES), - htmlspecialchars($principalForm['nombre'], ENT_QUOTES), - $codigo, - ], - [$enlaceFirma] - ); - } catch (\Throwable $eTmpl) { - try { - $mensajeTexto = "Hola {$nombrePacWA}, le informamos que para su turno *{$codigo}* " - . "debe firmar el siguiente consentimiento informado:\n\n" - . "*{$principalForm['nombre']}*\n\n" - . "Puede firmarlo en el siguiente enlace:\n{$enlaceFirma}\n\n" - . "Si ya firmó este documento presencial, ignore este mensaje."; - $wa->sendTextMessage($cel, $mensajeTexto); - } catch (\Throwable $eTxt) { - // Silenciar error de WhatsApp, el turno ya se creó - } - } + $cel = preg_replace('/[\s\-\.]/', '', $pacienteTel); + if (!str_starts_with($cel, '+')) { + $cel = '+57' . ltrim($cel, '0'); + } + $nombrePacWA = $pacienteNombre ?: 'Paciente'; + require_once __DIR__ . '/../../../services/WhatsAppService.php'; + try { + $wa = new WhatsAppService(); + $wa->sendTemplateMessage( + $cel, + $waTemplate, + $waLang, + [ + htmlspecialchars($nombrePacWA, ENT_QUOTES), + $codigo, + '', + ], + [] + ); + } catch (\Throwable $eTmpl) { + try { + $mensajeTexto = "Hola {$nombrePacWA}, su turno *{$codigo}* ha sido registrado en {$codigo}. Preséntese al laboratorio."; + $wa->sendTextMessage($cel, $mensajeTexto); + } catch (\Throwable $eTxt) { + // Silenciar } } - } catch (\Throwable $e) { - // Silenciar error — el turno ya se creó exitosamente } // Contar posición en la cola diff --git a/modules/turnero/api/send_consentimiento.php b/modules/turnero/api/send_consentimiento.php index cdc2b49..d3bd0b0 100644 --- a/modules/turnero/api/send_consentimiento.php +++ b/modules/turnero/api/send_consentimiento.php @@ -117,28 +117,6 @@ if ($lugarIdSol > 0) { } } -// 3c. Consentimiento principal de recepción (is_principal) -$principalRow = null; -try { - $stmtPc = $pdo->prepare( - "SELECT id AS formulario_id, nombre AS formulario_nombre - FROM lab_formularios - WHERE is_principal = 1 AND tipo = 'consentimiento' AND is_active = 1 - LIMIT 1" - ); - $stmtPc->execute(); - $principalRow = $stmtPc->fetch(PDO::FETCH_ASSOC); -} catch (\Throwable $e) {} -if ($principalRow) { - $yaExiste = false; - foreach ($formulariosRequeridos as $fr) { - if ((int)$fr['formulario_id'] === (int)$principalRow['formulario_id']) { $yaExiste = true; break; } - } - if (!$yaExiste) { - $formulariosRequeridos[] = $principalRow; - } -} - if (empty($formulariosRequeridos)) { jsonOk(['consentimientos' => [], 'mensaje' => 'Ningún examen ni servicio requiere consentimiento.']); } diff --git a/modules/turnero/api/set_principal_consent.php b/modules/turnero/api/set_principal_consent.php deleted file mode 100644 index 944b2be..0000000 --- a/modules/turnero/api/set_principal_consent.php +++ /dev/null @@ -1,45 +0,0 @@ -prepare( - "SELECT id FROM lab_formularios WHERE id = ? AND tipo = 'consentimiento' AND is_active = 1" - ); - $stmt->execute([$formularioId]); - if (!$stmt->fetch()) { - jsonError('Formulario no encontrado o no es un consentimiento activo.', 404); - } -} - -$pdo->beginTransaction(); -try { - // Quitar principal de todos - $pdo->exec("UPDATE lab_formularios SET is_principal = 0 WHERE is_principal = 1"); - // Marcar el nuevo principal (si aplica) - if ($formularioId) { - $stmt = $pdo->prepare("UPDATE lab_formularios SET is_principal = 1 WHERE id = ?"); - $stmt->execute([$formularioId]); - } - $pdo->commit(); - jsonOk([ - 'formulario_id' => $formularioId, - ], $formularioId ? 'Consentimiento principal actualizado' : 'Consentimiento principal desmarcado'); -} catch (\Throwable $e) { - $pdo->rollBack(); - jsonError('Error al actualizar: ' . $e->getMessage(), 500); -} diff --git a/modules/turnero/views/configuracion.php b/modules/turnero/views/configuracion.php index 9fb984a..0b3ae1f 100644 --- a/modules/turnero/views/configuracion.php +++ b/modules/turnero/views/configuracion.php @@ -58,7 +58,7 @@ try { try { $formulariosCons = $pdo->query( - "SELECT id, nombre, COALESCE(is_principal,0) AS is_principal FROM lab_formularios WHERE is_active=1 ORDER BY nombre ASC" + "SELECT id, nombre FROM lab_formularios WHERE is_active=1 ORDER BY nombre ASC" )->fetchAll(PDO::FETCH_ASSOC); } catch (\Throwable $e) { $_loadErrors[] = 'lab_formularios: ' . $e->getMessage(); } @@ -491,37 +491,16 @@ $tab = $_GET['tab'] ?? 'lugares';

Vista inversa: por consentimiento

- -
- - Marque un consentimiento como principal (el que se firma en recepción para pasar a toma de muestras). - Se auto-creará cuando el paciente tome turno en el kiosko y se enviará por WhatsApp automáticamente. -
- - -
- - - Principal - - - - - - +
- + Sin exámenes vinculados' : implode(', ', array_map(fn($e)=>''.$e['codigo'].'', $exsVinculados)) @@ -529,11 +508,6 @@ $tab = $_GET['tab'] ?? 'lugares';
- -
- Ningún consentimiento marcado como principal. -
-
@@ -1149,32 +1123,6 @@ async function borrarTvVideo() { } catch(e) { toast('Error de conexión', 'error'); } } -// ── Consentimiento principal ────────────────────────────────── -async function marcarPrincipalConsent(formularioId) { - try { - const res = await fetch(API + 'set_principal_consent.php', { - method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ formulario_id: formularioId }) - }); - const json = await res.json(); - if (!json.ok) { toast(json.error || 'Error', 'error'); return; } - toast('Consentimiento principal actualizado'); - setTimeout(() => location.reload(), 400); - } catch (e) { toast('Error de conexión', 'error'); } -} -async function quitarPrincipalConsent() { - try { - const res = await fetch(API + 'set_principal_consent.php', { - method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ formulario_id: null }) - }); - const json = await res.json(); - if (!json.ok) { toast(json.error || 'Error', 'error'); return; } - toast('Consentimiento principal desmarcado'); - setTimeout(() => location.reload(), 400); - } catch (e) { toast('Error de conexión', 'error'); } -} - async function guardarWhatsApp() { const template = document.getElementById('wa-template')?.value.trim(); const lang = document.getElementById('wa-lang')?.value.trim(); diff --git a/modules/turnero/views/display_global.php b/modules/turnero/views/display_global.php index 091c9ad..8118a53 100644 --- a/modules/turnero/views/display_global.php +++ b/modules/turnero/views/display_global.php @@ -108,7 +108,7 @@ $_hasVideo = (bool)$_tvVideo; position: relative; } .pg-body.has-video { - grid-template-columns: 240px 1fr 240px; + grid-template-columns: 380px 1fr 380px; } diff --git a/modules/turnero/views/recepcion.php b/modules/turnero/views/recepcion.php index e72092b..51962c0 100644 --- a/modules/turnero/views/recepcion.php +++ b/modules/turnero/views/recepcion.php @@ -594,21 +594,8 @@ function abrirFicha(turno) { .catch(() => {}); } - // Cargar consentimientos anticipados (principal y otros ya creados) - cargarConsentimientosTurno(turno.id); -} - -async function cargarConsentimientosTurno(turnoId) { - try { - const res = await fetch(`${API}get_consentimientos.php?turno_id=${turnoId}`); - const json = await res.json(); - if (json.ok && json.consentimientos?.length) { - consentimientos = json.consentimientos; - renderConsentimientos(consentimientos); - document.getElementById('sec-consentimientos').style.display = ''; - document.getElementById('btn-reenviar-consent').classList.remove('d-none'); - } - } catch (_) {} + // Buscar consentimientos si ya tiene solicitud + verificarSolicitudExistente(turno.id); } async function verificarSolicitudExistente(turnoId) {