diff --git a/modules/turnero/views/recepcion.php b/modules/turnero/views/recepcion.php index 29d4ecc..1440c17 100644 --- a/modules/turnero/views/recepcion.php +++ b/modules/turnero/views/recepcion.php @@ -419,9 +419,14 @@ document.addEventListener('DOMContentLoaded', function() {
- +
+ + +
@@ -566,6 +571,165 @@ document.addEventListener('DOMContentLoaded', function() { + + +
@@ -902,8 +1066,8 @@ async function buscarPaciente() { const lista = document.getElementById('lista-pacientes-res'); const datos = json.data || json.registros || []; if (!datos.length) { - lista.innerHTML = `
Sin resultados. - Crear nuevo
`; + lista.innerHTML = `
Sin resultados. + Crear nuevo
`; return; } lista.innerHTML = datos.map(p => ` @@ -959,15 +1123,9 @@ function desvincularPaciente() { document.getElementById('inp-buscar-pac').value = ''; } -function abrirNuevoPaciente(nombre) { - const ventana = window.open('lab_pacientes.php?nuevo=1&nombre=' + encodeURIComponent(nombre), '_blank'); - // Detectar cuando se cierra la ventana y refrescar la búsqueda - const chequeo = setInterval(() => { - if (ventana.closed) { - clearInterval(chequeo); - setTimeout(() => buscarPaciente(), 500); // Buscar nuevamente después de cerrar - } - }, 500); +function cambiarPaciente() { + desvincularPaciente(); + setTimeout(() => document.getElementById('inp-buscar-pac').focus(), 80); } // ── Historial del paciente ────────────────────────────────────── @@ -1648,6 +1806,204 @@ function mostrarLlamando(codigo) { _iniciar(); })(DESK_ID, DESK_NOMBRE, 'recepcion', 'desk_id'); +// ── Modal paciente (crear / ver / editar) ──────────────────── +const _mpacModal = () => bootstrap.Modal.getOrCreateInstance(document.getElementById('modalPacienteRec')); + +function mpacAvatar(nombre) { + const parts = nombre.trim().split(/\s+/).filter(Boolean); + document.getElementById('mpac-avatar').textContent = parts.length >= 2 + ? (parts[0][0] + parts[1][0]).toUpperCase() + : (parts[0]?.[0] || '?').toUpperCase(); +} + +async function abrirModalPaciente(id, nombrePrefill) { + // Reset form + document.getElementById('form-paciente-rec').reset(); + document.getElementById('mpac-id').value = ''; + document.getElementById('mpac-avatar').textContent = '?'; + document.getElementById('mpac-wa-badge').innerHTML = ''; + document.getElementById('mpac-user-id').value = ''; + document.getElementById('mpac-ciudad').value = 'Cúcuta'; + + if (id) { + document.getElementById('mpac-titulo').textContent = 'Cargando…'; + document.getElementById('mpac-subtitulo').textContent = ''; + _mpacModal().show(); + try { + const r = await fetch(`${API_PAC}?id=${id}`); + const d = await r.json(); + const p = (d.data || d.registros || [])[0]; + if (!p) { mostrarError('No se pudo cargar el paciente.'); return; } + mpacRellenar(p); + } catch (_) { mostrarError('Error al cargar paciente.'); } + } else { + document.getElementById('mpac-titulo').textContent = 'Nuevo Paciente'; + document.getElementById('mpac-subtitulo').textContent = 'Completa los datos del paciente'; + if (nombrePrefill) { + document.getElementById('mpac-nombre').value = nombrePrefill; + mpacAvatar(nombrePrefill); + } + _mpacModal().show(); + setTimeout(() => document.getElementById('mpac-nombre').focus(), 300); + } +} + +function mpacRellenar(p) { + document.getElementById('mpac-id').value = p.id; + document.getElementById('mpac-nombre').value = p.nombre_completo || ''; + document.getElementById('mpac-doc').value = p.numero_documento || ''; + document.getElementById('mpac-tipo-doc').value = p.tipo_documento || 'CC'; + document.getElementById('mpac-fnac').value = (p.fecha_nacimiento || '').slice(0, 10); + document.getElementById('mpac-email').value = p.email || ''; + document.getElementById('mpac-genero').value = p.genero || ''; + document.getElementById('mpac-eps').value = p.eps || ''; + document.getElementById('mpac-ciudad').value = p.ciudad || 'Cúcuta'; + document.getElementById('mpac-barrio').value = p.barrio || ''; + document.getElementById('mpac-dir').value = p.direccion || ''; + document.getElementById('mpac-notas').value = p.notas_admin || ''; + + // Teléfono con prefijo + let tel = p.telefono || ''; + const prefijos = ['57','58','1']; + let prefijo = '57'; + for (const pf of prefijos) { + if (tel.startsWith(pf) && tel.length > pf.length) { + prefijo = pf; tel = tel.slice(pf.length); break; + } + } + document.getElementById('mpac-tel-prefijo').value = prefijo; + document.getElementById('mpac-tel').value = tel; + + mpacAvatar(p.nombre_completo || ''); + document.getElementById('mpac-titulo').textContent = 'Editar Paciente'; + document.getElementById('mpac-subtitulo').textContent = p.nombre_completo || ''; +} + +async function mpacVerificarWA() { + const prefijo = document.getElementById('mpac-tel-prefijo').value || '57'; + let tel = (document.getElementById('mpac-tel').value || '').replace(/[^0-9]/g, ''); + if (tel.length === 10) tel = prefijo + tel; + const badge = document.getElementById('mpac-wa-badge'); + if (!tel || tel.length < 10) { badge.innerHTML = ''; return; } + badge.innerHTML = 'Verificando…'; + try { + const r = await fetch(`api/lab/check_whatsapp.php?phone=${encodeURIComponent(tel)}`); + const d = await r.json(); + if (d.ok && d.found) { + badge.innerHTML = 'Registrado en WhatsApp'; + document.getElementById('mpac-user-id').value = d.user_id; + } else { + badge.innerHTML = 'Sin WhatsApp registrado'; + document.getElementById('mpac-user-id').value = ''; + } + } catch(_) { badge.innerHTML = ''; } +} + +async function mpacGuardar() { + const nombre = document.getElementById('mpac-nombre').value.trim(); + if (!nombre) { mostrarError('El nombre es obligatorio.'); return; } + if (!/^[\p{L}\s'\-\.]+$/u.test(nombre)) { + mostrarError('El nombre solo debe contener letras, tildes y espacios.'); return; + } + if (nombre.split(/\s+/).filter(Boolean).length < 2) { + mostrarError('Ingresa nombre y apellido (mínimo 2 palabras).'); return; + } + + const tipoDoc = document.getElementById('mpac-tipo-doc').value; + const docVal = document.getElementById('mpac-doc').value.trim(); + if (docVal && ['CC','TI','RC','CE'].includes(tipoDoc)) { + const digits = docVal.replace(/[^0-9]/g, ''); + if (digits.length < 4 || digits.length > 12) { + mostrarError('El documento debe tener entre 4 y 12 dígitos.'); return; + } + } + + const emailVal = document.getElementById('mpac-email').value.trim(); + if (emailVal && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailVal)) { + mostrarError('El correo electrónico no es válido.'); return; + } + + const prefijo = document.getElementById('mpac-tel-prefijo').value || '57'; + let tel = document.getElementById('mpac-tel').value.replace(/[^0-9]/g, ''); + if (tel.length === 10) tel = prefijo + tel; + if (tel && prefijo === '57') { + const sinPref = tel.replace(/^57/, ''); + if (!/^3\d{9}$/.test(sinPref)) { + mostrarError('El celular colombiano debe comenzar por 3 y tener 10 dígitos.'); return; + } + } + + const id = document.getElementById('mpac-id').value; + const datos = { + nombre_completo: nombre, + tipo_documento: tipoDoc, + numero_documento: docVal || null, + fecha_nacimiento: document.getElementById('mpac-fnac').value || null, + telefono: tel || null, + email: emailVal || null, + genero: document.getElementById('mpac-genero').value || null, + eps: document.getElementById('mpac-eps').value.trim() || null, + ciudad: document.getElementById('mpac-ciudad').value.trim() || null, + barrio: document.getElementById('mpac-barrio').value.trim() || null, + direccion: document.getElementById('mpac-dir').value.trim() || null, + notas_admin: document.getElementById('mpac-notas').value.trim() || null, + user_id: document.getElementById('mpac-user-id').value || null, + }; + if (id) datos.id = parseInt(id); + + const btn = document.getElementById('mpac-btn-guardar'); + btn.disabled = true; + btn.innerHTML = 'Guardando…'; + + try { + const r = await fetch('api/lab/save_paciente.php', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(datos), + }); + const d = await r.json(); + + if (!d.success && !d.ok) { + mostrarError(d.error || 'Error al guardar el paciente.'); + return; + } + + _mpacModal().hide(); + mostrarToast(d.message || 'Paciente guardado.', 'success'); + + if (id) { + // Edición: actualizar datos en pantalla si es el paciente activo + if (pacienteActivo && pacienteActivo.id == id) { + pacienteActivo.nombre_completo = nombre; + pacienteActivo.numero_documento = docVal; + pacienteActivo.tipo_documento = tipoDoc; + pacienteActivo.telefono = tel; + document.getElementById('lbl-pac-nombre').textContent = + (pacienteActivo.full_name || nombre).trim(); + document.getElementById('lbl-pac-doc').textContent = + tipoDoc + ' ' + (docVal || ''); + document.getElementById('lbl-pac-cel').textContent = tel || ''; + } + } else { + // Creación: vincular al turno automáticamente + const nuevoPac = { + id: d.id || d.data?.id, + nombre_completo: nombre, + full_name: nombre, + tipo_documento: tipoDoc, + numero_documento: docVal, + telefono: tel, + }; + seleccionarPaciente(nuevoPac); + } + } catch (err) { + mostrarError('Error de red: ' + err.message); + } finally { + btn.disabled = false; + btn.innerHTML = 'Guardar paciente'; + } +} + // ── Toast ──────────────────────────────────────────────────── let toastTimer = null; function mostrarToast(msg, type = 'info', duration = 2500) {