diff --git a/public/css/styles.css b/public/css/styles.css index 6999ae7..1b140cc 100644 --- a/public/css/styles.css +++ b/public/css/styles.css @@ -3596,6 +3596,27 @@ body.dark-mode .admin-student-row.is-blocked { } } +/* Botón de transferir en gris claro / gray out cuando los padres lo desactivan */ +.qr-toggle-btn.transfer-btn-disabled { + background: rgba(241, 245, 249, 0.85) !important; + color: #94a3b8 !important; + border-color: #cbd5e1 !important; + box-shadow: none !important; + opacity: 0.65 !important; + filter: grayscale(1) !important; + cursor: pointer !important; +} +.qr-toggle-btn.transfer-btn-disabled svg { + stroke: #94a3b8 !important; +} +.pwa-nav-item.transfer-nav-disabled { + opacity: 0.45 !important; + filter: grayscale(1) !important; + color: #94a3b8 !important; +} +.pwa-nav-item.transfer-nav-disabled svg { + stroke: #94a3b8 !important; +} diff --git a/public/index.html b/public/index.html index 7eddf0c..2d12b67 100644 --- a/public/index.html +++ b/public/index.html @@ -787,25 +787,34 @@ Inmediato - -
- ₡ - +
+
+ +
+ ₡ + +
+
+
+ + +
-
- - - - -
- - + + +
@@ -991,7 +1000,7 @@ Mi QR - @@ -1144,23 +1153,26 @@ Acreditación Inmediata - -
- ₡ - -
- -
- - - - +
+
+ +
+ ₡ + +
+
+
+ + +
diff --git a/public/js/app.js b/public/js/app.js index 978ae07..d6fe9df 100644 --- a/public/js/app.js +++ b/public/js/app.js @@ -555,6 +555,26 @@ function updateStudentUI() { } }); + // Gray-out del botón Transferir cuando los padres lo desactivan + const btnCardTransfer = document.getElementById('btnCardTransfer'); + const pwaNavTransfer = document.getElementById('pwaNavTransfer'); + const transferenciasHabilitadas = currentStudent.permitir_transferencias !== 0; + + if (btnCardTransfer) { + if (!transferenciasHabilitadas) { + btnCardTransfer.classList.add('transfer-btn-disabled'); + } else { + btnCardTransfer.classList.remove('transfer-btn-disabled'); + } + } + if (pwaNavTransfer) { + if (!transferenciasHabilitadas) { + pwaNavTransfer.classList.add('transfer-nav-disabled'); + } else { + pwaNavTransfer.classList.remove('transfer-nav-disabled'); + } + } + // Alergias const allergyBox = document.getElementById('allergyWarning'); if (currentStudent.alergias && currentStudent.alergias !== 'Ninguna' && currentStudent.alergias !== 'Ninguna conocida') { @@ -929,37 +949,38 @@ async function quickSinpeRecharge(monto) { } async function customSinpeRecharge() { - const input = document.getElementById('inputCustomSinpe'); - const val = parseInt(input.value, 10); - if (!val || val <= 0) return alert('Por favor escribe un monto válido a recargar en colones.'); - await doSinpeRecharge(val); - input.value = ''; -} - -async function doSinpeRecharge(monto) { if (!currentStudent) return; - const comprobante = `SINPE-${Math.floor(100000 + Math.random() * 900000)}`; + const inputMonto = document.getElementById('inputCustomSinpe'); + const inputComp = document.getElementById('inputCustomSinpeComprobante'); + const val = parseInt(inputMonto ? inputMonto.value : 0, 10); + const comp = inputComp ? inputComp.value.trim() : ''; + + if (!val || val <= 0) return alert('Por favor escribe un monto válido a recargar en colones.'); + if (!comp) return alert('Por favor escribe el número de comprobante SINPE.'); try { - const res = await fetch(`/api/estudiantes/${currentStudent.id}/recarga`, { + const res = await fetch('/api/sinpe/solicitar', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ - monto, - comprobante, - descripcion: `Recarga SINPE Móvil desde portal de padres` + estudiante_id: currentStudent.id, + padre_usuario_id: currentUser && currentUser.rol === 'padre' ? currentUser.id : null, + monto: val, + comprobante: comp, + notas: `Portal Parental Móvil para ${currentStudent.nombre_completo}` }) }); - const data = await res.json(); if (!res.ok) throw new Error(data.error); if (window.sounds) window.sounds.playSuccess(); - alert(`¡Recarga SINPE exitosa!\nSe acreditaron ₡${monto.toLocaleString('es-CR')} al monedero de ${currentStudent.nombre_completo}.\nComprobante: ${comprobante}`); + alert(`¡Solicitud de Recarga Enviada!\n\nMonto: ₡${val.toLocaleString('es-CR')}\nComprobante: #${comp}\n\nLa soda verificará el depósito y el saldo se acreditará automáticamente.`); - await selectStudent(currentStudent.id); + if (inputMonto) inputMonto.value = ''; + if (inputComp) inputComp.value = ''; } catch (err) { - alert(`Error en recarga: ${err.message}`); + if (window.sounds) window.sounds.playError(); + alert(`Error al enviar solicitud SINPE: ${err.message}`); } } @@ -1541,6 +1562,7 @@ async function onToggleAllowTransfer(checked) { body: JSON.stringify({ permitir_transferencias: checked ? 1 : 0 }) }); currentStudent.permitir_transferencias = checked ? 1 : 0; + updateStudentUI(); if (window.sounds) window.sounds.playCoin(); } catch (e) { console.error('Error actualizando permiso de transferencias:', e); @@ -1660,6 +1682,17 @@ function initStudentSSE() { } catch (err) {} }); + sse.addEventListener('solicitud_sinpe_procesada', (e) => { + try { + if (currentUser && currentUser.rol === 'padre') { + if (currentParentChild) { + loadParentSinpeRequests(currentParentChild.id); + } + loadParentDashboard(); + } + } catch (err) {} + }); + sse.addEventListener('transferencia_realizada', (e) => { try { const data = JSON.parse(e.data); @@ -1978,6 +2011,7 @@ function renderActiveChildDetails(child) { if (chkTransfer) chkTransfer.checked = child.permitir_transferencias !== 0; loadActiveChildHistory(child.id); + loadParentSinpeRequests(child.id); } async function loadActiveChildHistory(studentId) { @@ -2015,49 +2049,119 @@ async function loadActiveChildHistory(studentId) { } } -function setParentSinpePreset(amt) { - const input = document.getElementById('inputParentSinpeMonto'); - if (input) input.value = amt; - if (window.sounds) window.sounds.playTap(); -} - async function executeParentSinpeRecharge() { if (!currentParentChild) { alert('Selecciona primero al estudiante a quien deseas recargarle.'); return; } - const input = document.getElementById('inputParentSinpeMonto'); - const monto = parseInt(input ? input.value : 0, 10); + const inputMonto = document.getElementById('inputParentSinpeMonto'); + const inputComp = document.getElementById('inputParentSinpeComprobante'); + const btn = document.getElementById('btnParentValidarSinpe'); + + const monto = parseInt(inputMonto ? inputMonto.value : 0, 10); + const comprobante = inputComp ? inputComp.value.trim() : ''; if (isNaN(monto) || monto <= 0) { alert('Ingresa un monto válido mayor a ₡0 para recargar.'); + if (inputMonto) inputMonto.focus(); + return; + } + if (!comprobante) { + alert('Por favor ingresa el número de comprobante de la transferencia SINPE Móvil.'); + if (inputComp) inputComp.focus(); return; } try { - const res = await fetch(`/api/estudiantes/${currentParentChild.id}/recarga`, { + if (btn) { + btn.disabled = true; + btn.innerHTML = 'Verificando...'; + } + + const res = await fetch('/api/sinpe/solicitar', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ + estudiante_id: currentParentChild.id, + padre_usuario_id: currentUser ? currentUser.id : null, monto, - comprobante: 'SINPE-PADRE', - descripcion: `Recarga SINPE Móvil por Padre/Madre para ${currentParentChild.nombre_completo}` + comprobante, + notas: `Portal de Padres - ${currentUser ? currentUser.nombre : 'Encargado'}` }) }); const data = await res.json(); if (!res.ok) throw new Error(data.error); if (window.sounds) window.sounds.playCoin(); - alert(`¡Recarga Exitosa!\nSe agregaron ₡${monto.toLocaleString('es-CR')} al monedero de ${currentParentChild.nombre_completo}.\nNuevo Saldo: ₡${data.saldo_nuevo.toLocaleString('es-CR')}`); + alert(`¡Solicitud de Recarga Enviada!\n\nMonto: ₡${monto.toLocaleString('es-CR')}\nComprobante: #${comprobante}\n\nLa soda verificará el depósito y el saldo se acreditará automáticamente.`); - if (input) input.value = ''; - await loadParentDashboard(); + if (inputMonto) inputMonto.value = ''; + if (inputComp) inputComp.value = ''; + + await loadParentSinpeRequests(currentParentChild.id); } catch (err) { if (window.sounds) window.sounds.playError(); - alert(`Error al procesar recarga SINPE: ${err.message}`); + alert(`Error al enviar solicitud SINPE: ${err.message}`); + } finally { + if (btn) { + btn.disabled = false; + btn.innerHTML = `Validar SINPE`; + } } } +async function loadParentSinpeRequests(studentId) { + const box = document.getElementById('parentSinpePendingBox'); + const list = document.getElementById('parentSinpePendingList'); + if (!box || !list) return; + + try { + const res = await fetch(`/api/sinpe/solicitudes/estudiante/${studentId}`); + const data = await res.json(); + if (!res.ok) throw new Error(data.error); + + const solicitudes = data.solicitudes || []; + if (solicitudes.length === 0) { + box.style.display = 'none'; + list.innerHTML = ''; + return; + } + + box.style.display = 'block'; + list.innerHTML = solicitudes.slice(0, 5).map(s => { + const fecha = new Date(s.creado_en).toLocaleString('es-CR', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }); + let badgeStyle = ''; + let badgeText = ''; + + if (s.estado === 'pendiente') { + badgeStyle = 'background: #fef3c7; color: #b45309; border: 1px solid #fde68a;'; + badgeText = '⏳ Por Verificar'; + } else if (s.estado === 'aprobada') { + badgeStyle = 'background: #dcfce7; color: #15803d; border: 1px solid #bbf7d0;'; + badgeText = '✅ Acreditado'; + } else { + badgeStyle = 'background: #fee2e2; color: #b91c1c; border: 1px solid #fecaca;'; + badgeText = '❌ Rechazado'; + } + + return ` +
+
+
₡${s.monto_colones.toLocaleString('es-CR')} (Comp: #${s.comprobante_sinpe})
+
${fecha}
+
+
+ ${badgeText} +
+
+ `; + }).join(''); + } catch (err) { + console.error('Error cargando solicitudes SINPE:', err); + } +} + + function setParentLimitPreset(amt) { const input = document.getElementById('inputParentCustomLimit'); const range = document.getElementById('rangeParentLimit'); @@ -2117,6 +2221,10 @@ async function onToggleParentTransfer(checked) { if (!res.ok) throw new Error(data.error); currentParentChild.permitir_transferencias = checked ? 1 : 0; + if (currentStudent && currentStudent.id === currentParentChild.id) { + currentStudent.permitir_transferencias = checked ? 1 : 0; + updateStudentUI(); + } if (window.sounds) window.sounds.playTap(); } catch (err) { alert(`No se pudo actualizar permiso de transferencia: ${err.message}`); diff --git a/public/js/pos.js b/public/js/pos.js index 47a8ba4..e3ee3ad 100644 --- a/public/js/pos.js +++ b/public/js/pos.js @@ -78,6 +78,7 @@ document.addEventListener('DOMContentLoaded', async () => { checkPosHttpsEnvironment(); await loadCatalog(); await loadPreOrders(); + await loadSinpeRequests(); // La cámara se activa bajo demanda al cobrar o identificar, NO al entrar initSSE(); initPistolScanner(); @@ -1150,12 +1151,18 @@ function switchPosTab(tab) { currentTab = tab; document.getElementById('tabBtnMostrador').classList.toggle('active', tab === 'mostrador'); document.getElementById('tabBtnPreordenes').classList.toggle('active', tab === 'preordenes'); + const tabSinpe = document.getElementById('tabBtnSinpe'); + if (tabSinpe) tabSinpe.classList.toggle('active', tab === 'sinpe'); document.getElementById('viewPosMostrador').style.display = tab === 'mostrador' ? 'block' : 'none'; document.getElementById('viewPosPreordenes').style.display = tab === 'preordenes' ? 'block' : 'none'; + const viewSinpe = document.getElementById('viewPosSinpe'); + if (viewSinpe) viewSinpe.style.display = tab === 'sinpe' ? 'block' : 'none'; if (tab === 'preordenes') { loadPreOrders(); + } else if (tab === 'sinpe') { + loadSinpeRequests(); } } @@ -1337,4 +1344,152 @@ function initSSE() { } } catch (err) {} }); + + sseSource.addEventListener('solicitud_sinpe_nueva', (e) => { + if (window.sounds) window.sounds.playCoin(); + loadSinpeRequests(); + }); + + sseSource.addEventListener('solicitud_sinpe_procesada', () => { + loadSinpeRequests(); + }); } + +// ========================================== +// RECARGAS SINPE EN POS +// ========================================== + +async function loadSinpeRequests() { + const list = document.getElementById('sinpeRequestsList'); + const badge = document.getElementById('badgeSinpeCount'); + if (!list) return; + + try { + const res = await fetch('/api/sinpe/solicitudes?estado=pendiente'); + const data = await res.json(); + if (!res.ok) throw new Error(data.error); + + const solicitudes = data.solicitudes || []; + + if (badge) { + if (solicitudes.length > 0) { + badge.textContent = solicitudes.length; + badge.style.display = 'inline-block'; + } else { + badge.style.display = 'none'; + } + } + + if (solicitudes.length === 0) { + list.innerHTML = ` +
+
✨
+ No hay recargas SINPE pendientes +

Todas las recargas reportadas por los padres han sido procesadas.

+
+ `; + return; + } + + list.innerHTML = solicitudes.map(s => { + const fecha = new Date(s.creado_en).toLocaleString('es-CR', { + day: '2-digit', + month: 'short', + hour: '2-digit', + minute: '2-digit' + }); + + return ` +
+
+ Foto +
+
${s.estudiante_nombre}
+
+ ${s.estudiante_grado || ''} ${s.estudiante_seccion ? '• Sec. ' + s.estudiante_seccion : ''} + Saldo actual: ₡${(s.estudiante_saldo || 0).toLocaleString('es-CR')} +
+
+ Reportado: ${fecha} +
+
+
+ +
+
+ +₡${s.monto_colones.toLocaleString('es-CR')} +
+
+ Comp: #${s.comprobante_sinpe} +
+
+ +
+ + +
+
+ `; + }).join(''); + } catch (err) { + console.error('Error cargando solicitudes SINPE:', err); + } +} + +async function procesarSinpePos(solicitudId, accion) { + if (accion === 'aprobar') { + const ok = confirm('¿Confirmas que verificaste el comprobante y el dinero ya ingresó a la cuenta bancaria de la soda?'); + if (!ok) return; + + try { + const res = await fetch('/api/sinpe/procesar', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + solicitud_id: solicitudId, + accion: 'aprobar', + usuario_id: null + }) + }); + const data = await res.json(); + if (!res.ok) throw new Error(data.error); + + if (window.sounds) window.sounds.playCoin(); + alert(`¡Recarga Aprobada!\nSe acreditaron ₡${data.resultado.monto.toLocaleString('es-CR')} al estudiante ${data.resultado.estudiante_nombre}.\nNuevo saldo: ₡${data.resultado.saldo_nuevo.toLocaleString('es-CR')}.`); + loadSinpeRequests(); + } catch (err) { + if (window.sounds) window.sounds.playError(); + alert(`Error al aprobar recarga: ${err.message}`); + } + } else if (accion === 'rechazar') { + const motivo = prompt('Motivo del rechazo de la recarga:', 'Comprobante no coincide o fondos no recibidos'); + if (motivo === null) return; // cancelado por usuario + + try { + const res = await fetch('/api/sinpe/procesar', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + solicitud_id: solicitudId, + accion: 'rechazar', + motivo: motivo || 'Rechazado por la soda', + usuario_id: null + }) + }); + const data = await res.json(); + if (!res.ok) throw new Error(data.error); + + alert('La solicitud de recarga ha sido rechazada.'); + loadSinpeRequests(); + } catch (err) { + alert(`Error al rechazar recarga: ${err.message}`); + } + } +} + diff --git a/public/pos.html b/public/pos.html index 88395d9..8cf01a2 100644 --- a/public/pos.html +++ b/public/pos.html @@ -97,6 +97,9 @@ + @@ -171,6 +174,29 @@ + + +