diff --git a/.gitignore b/.gitignore index f1aab67..53a81ed 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,7 @@ node_modules/ *.db !schema.sql .env +*.db-shm +*.db-wal +*.db +cloudflared.exe diff --git a/public/index.html b/public/index.html index bca0a86..e860336 100644 --- a/public/index.html +++ b/public/index.html @@ -61,10 +61,16 @@ - +
+ + +
@@ -224,6 +230,15 @@ + +
+
+ 🤝 RecreoTransfer entre Compas + Permitir transferir saldo a compañeros de clase +
+ +
+

Consumos Recientes

@@ -232,6 +247,84 @@
+ + + diff --git a/public/js/app.js b/public/js/app.js index 305463e..d8c0ebf 100644 --- a/public/js/app.js +++ b/public/js/app.js @@ -16,6 +16,7 @@ document.addEventListener('DOMContentLoaded', async () => { } await loadInitialData(); + initStudentSSE(); }); async function loadInitialData() { @@ -106,6 +107,12 @@ function updateStudentUI() { // Panel de Padres sliders y valores document.getElementById('lblParentDailyLimit').textContent = `₡${currentStudent.limite_diario_colones.toLocaleString('es-CR')}`; document.getElementById('rangeDailyLimit').value = currentStudent.limite_diario_colones; + + const chkTransfer = document.getElementById('chkParentAllowTransfer'); + if (chkTransfer) { + chkTransfer.checked = currentStudent.permitir_transferencias !== 0; + } + renderParentHistory(); } @@ -116,18 +123,22 @@ function setAppMode(mode, playSound = true) { document.getElementById('btnModeKids').classList.remove('active'); document.getElementById('btnModeTeens').classList.remove('active'); + const transferBtnText = document.getElementById('transferBtnText'); + if (mode === 'kids') { document.body.classList.add('mode-kids'); document.getElementById('btnModeKids').classList.add('active'); document.getElementById('balanceLabel').textContent = '💰 Mis Colones para el Recreo'; document.getElementById('kidsCoinIcon').style.display = 'inline-block'; - document.getElementById('qrBtnText').textContent = 'Tocar para mi QR 📱'; + document.getElementById('qrBtnText').textContent = 'Mi QR 📱'; + if (transferBtnText) transferBtnText.textContent = 'Pasar Plata 🤝'; } else { document.body.classList.add('mode-teens'); document.getElementById('btnModeTeens').classList.add('active'); document.getElementById('balanceLabel').textContent = 'SALDO DISPONIBLE'; document.getElementById('kidsCoinIcon').style.display = 'none'; - document.getElementById('qrBtnText').textContent = 'QR de Pago'; + document.getElementById('qrBtnText').textContent = 'Mi QR'; + if (transferBtnText) transferBtnText.textContent = 'Transferir ⚡'; } if (playSound && window.sounds) { @@ -447,3 +458,224 @@ function renderParentHistory() { `; }).join(''); } + +// ========================================== +// RECREOTRANSFER: PASAR PLATA A UN COMPAÑERO (OPCIÓN 2: ESCANEAR AL AMIGO) +// ========================================== + +let selectedTransferTarget = null; +let currentTransferAmount = 500; +let transferVideoStream = null; +let isTransferScanning = false; + +function openTransferModal() { + if (!currentStudent) return; + + if (currentStudent.permitir_transferencias === 0) { + if (window.sounds) window.sounds.playError(); + return alert('⚠️ Tus padres tienen desactivadas las transferencias entre compañeros en tu perfil.'); + } + + if (window.sounds) window.sounds.playCoin(); + document.getElementById('modalTransfer').style.display = 'flex'; + resetTransferScan(); + renderQuickTransferFriends(); + startTransferCamera(); +} + +function closeTransferModal(e) { + if (e && e.target !== e.currentTarget) return; + stopTransferCamera(); + document.getElementById('modalTransfer').style.display = 'none'; +} + +function renderQuickTransferFriends() { + const container = document.getElementById('quickTransferFriends'); + const others = students.filter(s => s.id !== currentStudent.id); + + container.innerHTML = others.map(s => ` + + `).join(''); +} + +function selectTransferTargetById(studentId) { + const target = students.find(s => s.id === studentId); + if (!target) return; + onTransferTargetIdentified(target); +} + +function onTransferTargetIdentified(target) { + selectedTransferTarget = target; + stopTransferCamera(); + + if (window.sounds) window.sounds.playScanChirp(); + + document.getElementById('transferTargetAvatar').src = target.foto_url; + document.getElementById('transferTargetName').textContent = target.nombre_completo; + document.getElementById('transferTargetGrade').textContent = `${target.grado} • Sección ${target.seccion} • Cód: ${target.codigo_estudiante}`; + + // Resetear montos y PIN + setTransferAmount(500, document.getElementById('btnTransfer500')); + document.getElementById('inputTransferCustomAmount').value = ''; + document.getElementById('inputTransferMotivo').value = ''; + document.getElementById('inputTransferPin').value = ''; + + document.getElementById('transferStepScan').style.display = 'none'; + document.getElementById('transferStepConfirm').style.display = 'block'; +} + +function resetTransferScan() { + selectedTransferTarget = null; + document.getElementById('transferStepConfirm').style.display = 'none'; + document.getElementById('transferStepScan').style.display = 'block'; + startTransferCamera(); +} + +function setTransferAmount(val, btn) { + currentTransferAmount = val; + document.querySelectorAll('#transferStepConfirm .mode-btn').forEach(b => b.classList.remove('active')); + if (btn) btn.classList.add('active'); + document.getElementById('inputTransferCustomAmount').value = ''; + if (window.sounds) window.sounds.playCoin(); +} + +async function startTransferCamera() { + const video = document.getElementById('transferVideo'); + if (!video) return; + + if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { + try { + transferVideoStream = await navigator.mediaDevices.getUserMedia({ + video: { facingMode: 'environment', width: { ideal: 480 } } + }); + video.srcObject = transferVideoStream; + isTransferScanning = true; + scanQrFromCamera(video); + } catch (err) { + console.log('Cámara de transferencia no disponible:', err); + } + } +} + +function stopTransferCamera() { + isTransferScanning = false; + if (transferVideoStream) { + transferVideoStream.getTracks().forEach(t => t.stop()); + transferVideoStream = null; + } +} + +function scanQrFromCamera(video) { + if ('BarcodeDetector' in window) { + const detector = new window.BarcodeDetector({ formats: ['qr_code'] }); + const interval = setInterval(async () => { + if (!isTransferScanning || selectedTransferTarget !== null) { + clearInterval(interval); + return; + } + try { + const barcodes = await detector.detect(video); + if (barcodes.length > 0) { + const rawValue = barcodes[0].rawValue; + const res = await fetch(`/api/estudiantes/qr/${encodeURIComponent(rawValue)}`); + if (res.ok) { + const found = await res.json(); + if (found.id !== currentStudent.id) { + clearInterval(interval); + onTransferTargetIdentified(found); + } + } + } + } catch (e) {} + }, 400); + } +} + +async function executeP2PTransfer() { + if (!currentStudent || !selectedTransferTarget) return; + + let monto = currentTransferAmount; + const custom = parseInt(document.getElementById('inputTransferCustomAmount').value, 10); + if (custom && custom > 0) { + monto = custom; + } + + const pin = document.getElementById('inputTransferPin').value.trim(); + if (!pin) { + if (window.sounds) window.sounds.playError(); + return alert('⚠️ Por favor ingresa tu PIN de seguridad (por defecto 1234).'); + } + + const motivo = document.getElementById('inputTransferMotivo').value.trim(); + + const btn = document.getElementById('btnConfirmTransfer'); + btn.disabled = true; + btn.textContent = 'Transfiriendo saldo...'; + + try { + const res = await fetch('/api/transferencias', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + emisor_id: currentStudent.id, + receptor_id: selectedTransferTarget.id, + monto, + pin, + motivo + }) + }); + + const data = await res.json(); + if (!res.ok) { + if (window.sounds) window.sounds.playError(); + throw new Error(data.error); + } + + if (window.sounds) window.sounds.playSuccess(); + + alert(`🎉 ¡TRANSFERENCIA EXITOSA!\nLe pasaste ₡${data.monto.toLocaleString('es-CR')} a ${data.receptor.nombre}.\nTu nuevo saldo es ₡${data.emisor.saldo_nuevo.toLocaleString('es-CR')}.`); + + closeTransferModal(); + await selectStudent(currentStudent.id); + } catch (err) { + alert(`❌ Fallo en la transferencia: ${err.message}`); + } finally { + btn.disabled = false; + btn.innerHTML = '💸 Enviar Dinero al Instante'; + } +} + +// Toggle Parental para permitir/bloquear transferencias +async function onToggleAllowTransfer(checked) { + if (!currentStudent) return; + try { + await fetch(`/api/estudiantes/${currentStudent.id}/limite`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ permitir_transferencias: checked ? 1 : 0 }) + }); + currentStudent.permitir_transferencias = checked ? 1 : 0; + if (window.sounds) window.sounds.playCoin(); + } catch (e) { + console.error('Error actualizando permiso de transferencias:', e); + } +} + +// SSE en tiempo real para estudiantes (notificación si le pasan plata) +function initStudentSSE() { + const sse = new EventSource('/api/events'); + + sse.addEventListener('transferencia_realizada', (e) => { + try { + const data = JSON.parse(e.data); + if (currentStudent && data.receptor.id === currentStudent.id) { + if (window.sounds) window.sounds.playCoin(); + alert(`🔔 ¡Te pasaron plata!\n${data.emisor.nombre} te transfirió ₡${data.monto.toLocaleString('es-CR')}.\nMotivo: ${data.motivo}`); + selectStudent(currentStudent.id); + } + } catch (err) {} + }); +} diff --git a/public/qr-phone.png b/public/qr-phone.png new file mode 100644 index 0000000..fa9d721 Binary files /dev/null and b/public/qr-phone.png differ diff --git a/server/db.js b/server/db.js index d65785e..db30f21 100644 --- a/server/db.js +++ b/server/db.js @@ -41,6 +41,7 @@ function initDatabase() { bloquear_chucherias INTEGER DEFAULT 0, padre_nombre TEXT, padre_telefono TEXT, + permitir_transferencias INTEGER DEFAULT 1, activo INTEGER DEFAULT 1, creado_en DATETIME DEFAULT CURRENT_TIMESTAMP ); @@ -110,6 +111,14 @@ function initDatabase() { `; db.exec(schema); + + // Migración segura para permitir_transferencias en bases de datos existentes + try { + db.exec('ALTER TABLE estudiantes ADD COLUMN permitir_transferencias INTEGER DEFAULT 1'); + } catch (e) { + // Ya existe la columna + } + seedInitialData(); } @@ -449,10 +458,109 @@ function crearOrdenCompleta({ estudianteId, tipoOrden, momentoEntrega, notas, it return transaction(); } +/** + * Realiza una transferencia P2P directa entre estudiantes (Opción 2: Escaneando al compañero) + * Transacción atómica ACID que verifica saldo, permisos parentales y PIN. + */ +function transferenciaP2PTransaction({ emisorId, qrReceptor, receptorId, monto, pin, motivo }) { + const transaction = db.transaction(() => { + // 1. Obtener emisor + const emisor = db.prepare('SELECT * FROM estudiantes WHERE id = ?').get(emisorId); + if (!emisor) throw new Error('Estudiante emisor no encontrado'); + if (!emisor.activo) throw new Error('Tu cuenta se encuentra inactiva'); + if (emisor.permitir_transferencias === 0) { + throw new Error('Tus padres tienen desactivadas las transferencias entre compañeros en tu perfil'); + } + + // 2. Validar PIN de seguridad del emisor + if (pin && emisor.pin_seguridad && String(emisor.pin_seguridad) !== String(pin).trim()) { + throw new Error('PIN de seguridad incorrecto'); + } + + // 3. Obtener receptor (por ID o por escaneo de QR/código de carné) + let receptor = null; + if (receptorId) { + receptor = db.prepare('SELECT * FROM estudiantes WHERE id = ?').get(receptorId); + } else if (qrReceptor) { + receptor = db.prepare('SELECT * FROM estudiantes WHERE qr_token = ? OR codigo_estudiante = ?').get(qrReceptor, qrReceptor); + } + + if (!receptor) { + throw new Error('Código QR no corresponde a ningún estudiante registrado'); + } + if (!receptor.activo) { + throw new Error(`La cuenta de ${receptor.nombre_completo} se encuentra inactiva`); + } + if (emisor.id === receptor.id) { + throw new Error('No puedes transferirte saldo a ti mismo'); + } + + // 4. Validar monto + const montoColones = parseInt(monto, 10); + if (isNaN(montoColones) || montoColones <= 0) { + throw new Error('El monto a transferir debe ser mayor a ₡0'); + } + if (montoColones > 3000) { + throw new Error('Por seguridad escolar, el tope máximo por transferencia es de ₡3.000'); + } + if (emisor.saldo_colones < montoColones) { + throw new Error(`Saldo insuficiente. Tienes ₡${emisor.saldo_colones.toLocaleString('es-CR')} y deseas transferir ₡${montoColones.toLocaleString('es-CR')}`); + } + + // 5. Actualizar saldos atómicamente + const nuevoSaldoEmisor = emisor.saldo_colones - montoColones; + const nuevoSaldoReceptor = receptor.saldo_colones + montoColones; + + db.prepare('UPDATE estudiantes SET saldo_colones = ? WHERE id = ?').run(nuevoSaldoEmisor, emisor.id); + db.prepare('UPDATE estudiantes SET saldo_colones = ? WHERE id = ?').run(nuevoSaldoReceptor, receptor.id); + + // 6. Registrar en el historial y auditoría de ambos + const motivoTexto = motivo && motivo.trim() ? ` (${motivo.trim()})` : ''; + const descEmisor = `Pase a ${receptor.nombre_completo}${motivoTexto}`; + const descReceptor = `Pase de ${emisor.nombre_completo}${motivoTexto}`; + + db.prepare(` + INSERT INTO transacciones_saldo + (estudiante_id, tipo, monto_colones, saldo_previo, saldo_posterior, descripcion) + VALUES (?, 'transferencia_enviada', ?, ?, ?, ?) + `).run(emisor.id, -montoColones, emisor.saldo_colones, nuevoSaldoEmisor, descEmisor); + + db.prepare(` + INSERT INTO transacciones_saldo + (estudiante_id, tipo, monto_colones, saldo_previo, saldo_posterior, descripcion) + VALUES (?, 'transferencia_recibida', ?, ?, ?, ?) + `).run(receptor.id, montoColones, receptor.saldo_colones, nuevoSaldoReceptor, descReceptor); + + return { + exito: true, + monto: montoColones, + motivo: motivo || 'Pase entre compas', + emisor: { + id: emisor.id, + nombre: emisor.nombre_completo, + saldo_anterior: emisor.saldo_colones, + saldo_nuevo: nuevoSaldoEmisor + }, + receptor: { + id: receptor.id, + nombre: receptor.nombre_completo, + grado: receptor.grado, + seccion: receptor.seccion, + foto_url: receptor.foto_url, + saldo_anterior: receptor.saldo_colones, + saldo_nuevo: nuevoSaldoReceptor + } + }; + }); + + return transaction(); +} + module.exports = { db, initDatabase, debitoCompraTransaction, recargaSaldoTransaction, - crearOrdenCompleta + crearOrdenCompleta, + transferenciaP2PTransaction }; diff --git a/server/server.js b/server/server.js index a06562f..8c9b0b5 100644 --- a/server/server.js +++ b/server/server.js @@ -2,7 +2,7 @@ const express = require('express'); const cors = require('cors'); const path = require('path'); const QRCode = require('qrcode'); -const { db, initDatabase, debitoCompraTransaction, recargaSaldoTransaction, crearOrdenCompleta } = require('./db'); +const { db, initDatabase, debitoCompraTransaction, recargaSaldoTransaction, crearOrdenCompleta, transferenciaP2PTransaction } = require('./db'); const app = express(); const PORT = process.env.PORT || 3030; @@ -187,19 +187,20 @@ app.post('/api/estudiantes/:id/recarga', (req, res) => { } }); -// Actualizar configuración parental (Límite diario y restricciones) +// Actualizar configuración parental (Límite diario, restricciones y transferencias P2P) app.put('/api/estudiantes/:id/limite', (req, res) => { try { - const { limite_diario_colones, alergias, bloquear_chucherias } = req.body; + const { limite_diario_colones, alergias, bloquear_chucherias, permitir_transferencias } = req.body; const estId = req.params.id; db.prepare(` UPDATE estudiantes SET limite_diario_colones = COALESCE(?, limite_diario_colones), alergias = COALESCE(?, alergias), - bloquear_chucherias = COALESCE(?, bloquear_chucherias) + bloquear_chucherias = COALESCE(?, bloquear_chucherias), + permitir_transferencias = COALESCE(?, permitir_transferencias) WHERE id = ? - `).run(limite_diario_colones, alergias, bloquear_chucherias, estId); + `).run(limite_diario_colones, alergias, bloquear_chucherias, permitir_transferencias, estId); const actualizado = db.prepare('SELECT * FROM estudiantes WHERE id = ?').get(estId); res.json(actualizado); @@ -208,6 +209,30 @@ app.put('/api/estudiantes/:id/limite', (req, res) => { } }); +// Transferencia P2P entre estudiantes (Opción 2: Escaneo directo del compañero) +app.post('/api/transferencias', (req, res) => { + try { + const { emisor_id, qr_receptor, receptor_id, monto, pin, motivo } = req.body; + if (!emisor_id) return res.status(400).json({ error: 'Emisor no especificado' }); + + const resultado = transferenciaP2PTransaction({ + emisorId: parseInt(emisor_id, 10), + qrReceptor: qr_receptor, + receptorId: receptor_id ? parseInt(receptor_id, 10) : null, + monto: parseInt(monto, 10), + pin, + motivo + }); + + // Notificar en tiempo real por SSE + broadcastEvent('transferencia_realizada', resultado); + + res.json(resultado); + } catch (error) { + res.status(400).json({ error: error.message }); + } +}); + // ========================================== // 2. PRODUCTOS Y MENÚ // ==========================================