feat: transferencias P2P entre estudiantes mediante escaneo de QR y carnet (RecreoTransfer)
This commit is contained in:
@@ -4,3 +4,7 @@ node_modules/
|
||||
*.db
|
||||
!schema.sql
|
||||
.env
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
*.db
|
||||
cloudflared.exe
|
||||
|
||||
+94
-1
@@ -61,10 +61,16 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; gap: 6px; flex-wrap: wrap; justify-content: flex-end;">
|
||||
<button class="qr-toggle-btn" onclick="openQrModal()">
|
||||
<span>📱</span>
|
||||
<span id="qrBtnText">Ver mi QR</span>
|
||||
<span id="qrBtnText">Mi QR</span>
|
||||
</button>
|
||||
<button class="qr-toggle-btn" style="background: rgba(16, 185, 129, 0.25); border-color: rgba(52, 211, 153, 0.4);" onclick="openTransferModal()">
|
||||
<span>🤝</span>
|
||||
<span id="transferBtnText">Pasar Plata</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -224,6 +230,15 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- CONTROL PARENTAL: PERMITIR O BLOQUEAR TRANSFERENCIAS ENTRE COMPAÑEROS -->
|
||||
<div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 12px; padding: 12px 14px; margin-bottom: 16px; display: flex; justify-content: space-between; align-items: center;">
|
||||
<div>
|
||||
<strong style="font-size: 0.85rem; color: #1e293b; display: block;">🤝 RecreoTransfer entre Compas</strong>
|
||||
<span style="font-size: 0.72rem; color: #64748b;">Permitir transferir saldo a compañeros de clase</span>
|
||||
</div>
|
||||
<input type="checkbox" id="chkParentAllowTransfer" onchange="onToggleAllowTransfer(this.checked)" style="width: 22px; height: 22px; cursor: pointer; accent-color: #0284c7;" checked>
|
||||
</div>
|
||||
|
||||
<!-- HISTORIAL RECIENTE -->
|
||||
<h4 style="font-size: 0.85rem; font-weight: 800; color: #1e293b; margin-bottom: 8px;">Consumos Recientes</h4>
|
||||
<div id="parentHistoryList" style="max-height: 140px; overflow-y: auto; font-size: 0.78rem;">
|
||||
@@ -232,6 +247,84 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- MODAL: RECREOTRANSFER (PASAR PLATA A UN COMPAÑERO ESCANEANDO SU QR O CARNÉ) -->
|
||||
<div class="modal-qr-backdrop" id="modalTransfer" style="display: none;" onclick="closeTransferModal(event)">
|
||||
<div class="modal-qr-card" onclick="event.stopPropagation()" style="max-width: 420px; text-align: left;">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #e2e8f0; padding-bottom: 10px; margin-bottom: 12px;">
|
||||
<div>
|
||||
<h3 style="color: #0f172a; font-size: 1.15rem; font-weight: 800;">🤝 Pasar Plata a un Compa</h3>
|
||||
<span style="font-size: 0.75rem; color: #64748b;">Escanea el carné o celular de tu amigo</span>
|
||||
</div>
|
||||
<button onclick="closeTransferModal()" style="background: none; border: none; font-size: 1.2rem; cursor: pointer; color: #64748b;">✕</button>
|
||||
</div>
|
||||
|
||||
<!-- PASO 1: ESCANEAR CÁMARA O ELEGIR COMPAÑERO DE PRUEBA -->
|
||||
<div id="transferStepScan">
|
||||
<div style="position: relative; border-radius: 12px; overflow: hidden; background: #000; height: 160px; margin-bottom: 12px;">
|
||||
<video id="transferVideo" style="width: 100%; height: 100%; object-fit: cover;" autoplay playsinline muted></video>
|
||||
<div class="laser-scan-line"></div>
|
||||
<div style="position: absolute; bottom: 8px; left: 0; right: 0; text-align: center; color: white; font-size: 0.72rem; text-shadow: 0 1px 3px black;">
|
||||
Apunta al QR del carné o celular de tu amigo
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="text-align: center; margin-bottom: 12px;">
|
||||
<span style="font-size: 0.74rem; color: #64748b; font-weight: 700;">O selecciona a un compañero para transferirle:</span>
|
||||
<div id="quickTransferFriends" style="display: flex; gap: 6px; flex-wrap: wrap; justify-content: center; margin-top: 8px;">
|
||||
<!-- Se llena dinámicamente con los otros estudiantes -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- PASO 2: CONFIRMAR COMPAÑERO Y MONTO -->
|
||||
<div id="transferStepConfirm" style="display: none;">
|
||||
<!-- Tarjeta del receptor -->
|
||||
<div style="background: #f0fdf4; border: 1.5px solid #86efac; border-radius: 14px; padding: 12px; display: flex; align-items: center; gap: 12px; margin-bottom: 14px;">
|
||||
<img id="transferTargetAvatar" src="" style="width: 48px; height: 48px; border-radius: 50%; border: 2px solid #10b981; background: white;">
|
||||
<div style="flex: 1;">
|
||||
<div style="font-size: 0.7rem; color: #15803d; font-weight: 800; text-transform: uppercase;">Vas a transferir a:</div>
|
||||
<h4 id="transferTargetName" style="font-size: 1rem; font-weight: 900; color: #0f172a; line-height: 1.2;">Nombre</h4>
|
||||
<span id="transferTargetGrade" style="font-size: 0.75rem; color: #64748b;">Grado y Sección</span>
|
||||
</div>
|
||||
<button onclick="resetTransferScan()" style="background: #e2e8f0; border: none; padding: 4px 8px; border-radius: 6px; font-size: 0.75rem; font-weight: 700; cursor: pointer;">Cambiar</button>
|
||||
</div>
|
||||
|
||||
<!-- MONTO A PASAR -->
|
||||
<label style="display: block; font-size: 0.82rem; font-weight: 800; color: #1e293b; margin-bottom: 6px;">
|
||||
¿Cuánto le vas a pasar?
|
||||
</label>
|
||||
<div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; margin-bottom: 10px;">
|
||||
<button type="button" class="mode-btn active" id="btnTransfer500" onclick="setTransferAmount(500, this)" style="padding: 8px; text-align: center; justify-content: center; font-size: 0.85rem;">₡500</button>
|
||||
<button type="button" class="mode-btn" id="btnTransfer1000" onclick="setTransferAmount(1000, this)" style="padding: 8px; text-align: center; justify-content: center; font-size: 0.85rem;">₡1.000</button>
|
||||
<button type="button" class="mode-btn" id="btnTransfer1500" onclick="setTransferAmount(1500, this)" style="padding: 8px; text-align: center; justify-content: center; font-size: 0.85rem;">₡1.500</button>
|
||||
</div>
|
||||
|
||||
<div style="margin-bottom: 12px;">
|
||||
<input type="number" id="inputTransferCustomAmount" placeholder="Otro monto (ej. 750)" style="width: 100%; padding: 10px; border-radius: 10px; border: 1px solid #cbd5e1; font-size: 1rem; font-weight: 800; color: #0284c7;">
|
||||
</div>
|
||||
|
||||
<!-- MOTIVO OPCIONAL -->
|
||||
<div style="margin-bottom: 12px;">
|
||||
<label style="display: block; font-size: 0.75rem; font-weight: 700; color: #64748b; margin-bottom: 4px;">Motivo (Opcional):</label>
|
||||
<input type="text" id="inputTransferMotivo" placeholder="Ej: Mitad de la empanada, fresco..." style="width: 100%; padding: 8px 10px; border-radius: 8px; border: 1px solid #cbd5e1; font-size: 0.85rem;">
|
||||
</div>
|
||||
|
||||
<!-- PIN DE SEGURIDAD -->
|
||||
<div style="background: #f8fafc; border: 1px dashed #cbd5e1; border-radius: 10px; padding: 10px 12px; margin-bottom: 14px;">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
|
||||
<label style="font-size: 0.78rem; font-weight: 800; color: #0f172a;">🔐 Digita tu PIN de 4 dígitos:</label>
|
||||
<span style="font-size: 0.7rem; color: #64748b;">(PIN por defecto: 1234)</span>
|
||||
</div>
|
||||
<input type="password" id="inputTransferPin" maxlength="4" placeholder="••••" style="width: 100%; text-align: center; font-size: 1.4rem; letter-spacing: 6px; padding: 8px; border-radius: 8px; border: 1px solid #cbd5e1; font-weight: 900;">
|
||||
</div>
|
||||
|
||||
<button id="btnConfirmTransfer" onclick="executeP2PTransfer()" style="width: 100%; padding: 14px; background: linear-gradient(135deg, #10b981, #059669); color: white; border: none; border-radius: 14px; font-weight: 900; font-size: 1.05rem; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 8px; box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);">
|
||||
<span>💸</span> Enviar Dinero al Instante
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/js/sounds.js"></script>
|
||||
<script src="/js/app.js"></script>
|
||||
</body>
|
||||
|
||||
+234
-2
@@ -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 => `
|
||||
<button type="button" onclick="selectTransferTargetById(${s.id})" style="display: flex; align-items: center; gap: 4px; padding: 4px 8px; background: #f1f5f9; border: 1px solid #cbd5e1; border-radius: 8px; font-size: 0.72rem; font-weight: 700; cursor: pointer; color: #1e293b;">
|
||||
<img src="${s.foto_url}" style="width: 20px; height: 20px; border-radius: 50%;">
|
||||
<span>${s.nombre_completo.split(' ')[0]} (${s.grado.split(' ')[0]})</span>
|
||||
</button>
|
||||
`).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 = '<span>💸</span> 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) {}
|
||||
});
|
||||
}
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.6 KiB |
+109
-1
@@ -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
|
||||
};
|
||||
|
||||
+30
-5
@@ -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Ú
|
||||
// ==========================================
|
||||
|
||||
Reference in New Issue
Block a user