From 62c4e7a18cb76debcca5a3c8776d2de2d10b5bb8 Mon Sep 17 00:00:00 2001 From: Lizandro Guarnizo <77708265+lizandrogd@users.noreply.github.com> Date: Tue, 16 Jun 2026 16:05:04 -0500 Subject: [PATCH] up --- modules/turnero/api/get_consentimientos.php | 90 ++++++++++++++++++++- modules/turnero/views/lugar.php | 36 --------- 2 files changed, 89 insertions(+), 37 deletions(-) diff --git a/modules/turnero/api/get_consentimientos.php b/modules/turnero/api/get_consentimientos.php index a04b6c1..37a47d7 100644 --- a/modules/turnero/api/get_consentimientos.php +++ b/modules/turnero/api/get_consentimientos.php @@ -21,7 +21,7 @@ if ($turnoId <= 0) jsonError('turno_id inválido.'); $pdo = db(); // ── Verificar que el turno existe ───────────────────────────── -$stmt = $pdo->prepare("SELECT id, estado FROM turnero_turnos WHERE id = ?"); +$stmt = $pdo->prepare("SELECT id, estado, lugar_destino_id FROM turnero_turnos WHERE id = ?"); $stmt->execute([$turnoId]); $turno = $stmt->fetch(PDO::FETCH_ASSOC); if (!$turno) jsonError('Turno no encontrado.', 404); @@ -90,6 +90,94 @@ if ($incluirSolicitud) { ); $stmt->execute([$solicitud['id']]); $examenes = $stmt->fetchAll(PDO::FETCH_ASSOC); + + // Auto-crear consentimientos requeridos desde DOS fuentes: + // 1. Por examen → exam_tipo_consentimientos + // 2. Por lugar → turnero_lugar_consentimientos + $requeridos = []; + $vistosFIds = []; + + // Fuente 1: examen + if (!empty($examenes)) { + $examIds = array_column($examenes, 'id'); + $ph = implode(',', array_fill(0, count($examIds), '?')); + $stmtE = $pdo->prepare( + "SELECT DISTINCT etc.formulario_id, f.nombre AS formulario_nombre + FROM exam_tipo_consentimientos etc + JOIN lab_formularios f ON f.id = etc.formulario_id + WHERE etc.exam_tipo_id IN ($ph) AND f.is_active = 1" + ); + $stmtE->execute($examIds); + foreach ($stmtE->fetchAll(PDO::FETCH_ASSOC) as $r) { + $fid = (int)$r['formulario_id']; + if (!in_array($fid, $vistosFIds, true)) { + $requeridos[] = $r; + $vistosFIds[] = $fid; + } + } + } + + // Fuente 2: lugar destino del turno + $lugarDestinoId = (int)($turno['lugar_destino_id'] ?? 0); + if ($lugarDestinoId) { + $stmtL = $pdo->prepare( + "SELECT DISTINCT tlc.formulario_id, f.nombre AS formulario_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" + ); + $stmtL->execute([$lugarDestinoId]); + foreach ($stmtL->fetchAll(PDO::FETCH_ASSOC) as $r) { + $fid = (int)$r['formulario_id']; + if (!in_array($fid, $vistosFIds, true)) { + $requeridos[] = $r; + $vistosFIds[] = $fid; + } + } + } + + // Auto-crear los registros que falten + if (!empty($requeridos)) { + $existFormIds = array_map('intval', array_column($consentimientos, 'formulario_id')); + $stmtIns = $pdo->prepare( + "INSERT IGNORE INTO turnero_consentimientos + (turno_id, formulario_id, token, estado) + VALUES (?, ?, ?, 'pendiente')" + ); + $creados = 0; + foreach ($requeridos as $r) { + if (!in_array((int)$r['formulario_id'], $existFormIds, true)) { + $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) + ); + $stmtIns->execute([$turnoId, (int)$r['formulario_id'], $token]); + $creados++; + } + } + + // Re-leer si se crearon nuevos registros + if ($creados > 0) { + $stmtC = $pdo->prepare( + "SELECT tc.id, tc.turno_id, tc.formulario_id, tc.token, + tc.estado, tc.enviado_at, tc.firmado_at, + (tc.firma_profesional_svg IS NOT NULL) AS tiene_firma_profesional, + tc.firmado_profesional_at, + f.nombre AS formulario_nombre + FROM turnero_consentimientos tc + LEFT JOIN lab_formularios f ON f.id = tc.formulario_id + WHERE tc.turno_id = ? + ORDER BY tc.id ASC" + ); + $stmtC->execute([$turnoId]); + $consentimientos = $stmtC->fetchAll(PDO::FETCH_ASSOC); + $respuesta['consentimientos'] = $consentimientos; + } + } } $respuesta['solicitud'] = $solicitud; diff --git a/modules/turnero/views/lugar.php b/modules/turnero/views/lugar.php index f4e7b4a..a7f58bd 100644 --- a/modules/turnero/views/lugar.php +++ b/modules/turnero/views/lugar.php @@ -616,42 +616,6 @@ async function cargarFichaSolicitud(turnoId) { listaEx.innerHTML = 'Sin exámenes registrados'; } - // Auto-crear tokens para formularios del lugar que aún no tengan registro - if (lugarId) { - const resF = await fetch(`${API}get_lugar_formularios.php?lugar_id=${lugarId}`); - const jsonF = await resF.json(); - const forms = (jsonF.ok && jsonF.formularios) ? jsonF.formularios : []; - - const existIds = new Set(consts.map(c => parseInt(c.formulario_id))); - const faltantes = forms.filter(f => !existIds.has(parseInt(f.id))); - - if (faltantes.length > 0) { - await Promise.all(faltantes.map(f => - fetch(API + 'create_consent_token.php', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ turno_id: turnoId, formulario_id: f.id }), - }).catch(() => {}) - )); - // Recargar consents tras la creación - const res2 = await fetch(`${API}get_consentimientos.php?turno_id=${turnoId}`); - const json2 = await res2.json(); - if (json2.ok) consts = json2.consentimientos || []; - - // Si alguno no se pudo crear (sin paciente), mostrarlo igual como pendiente visual - const createdIds = new Set(consts.map(c => parseInt(c.formulario_id))); - faltantes.forEach(f => { - if (!createdIds.has(parseInt(f.id))) { - consts.push({ - id: null, turno_id: turnoId, - formulario_id: f.id, formulario_nombre: f.nombre, - estado: 'pendiente', token: null, - }); - } - }); - } - } - // Consentimientos renderConsentimientos(consts);