diff --git a/public/index.html b/public/index.html index 271c23a..5a67d46 100644 --- a/public/index.html +++ b/public/index.html @@ -256,6 +256,10 @@ Escuelas & Sedes + @@ -438,6 +442,46 @@
+ + +
+
+
+
+ 💾 +
+
+

Copias de Seguridad del Sistema (Backups)

+ Respaldos automáticos diarios y descargas manuales +
+
+ +
+ + + +
+ + + + + + + + + + + + + + + +
Archivo de RespaldoMotor BDFecha y HoraTamañoAcción
Cargando copias de seguridad...
+
+
@@ -463,6 +507,90 @@ + + + @@ -507,6 +635,14 @@ Terminal POS + + diff --git a/public/js/app.js b/public/js/app.js index e2a9061..fa87099 100644 --- a/public/js/app.js +++ b/public/js/app.js @@ -517,12 +517,19 @@ function switchDevTab(tab) { if (btn) btn.classList.add('active'); if (content) content.style.display = 'block'; loadDevStats(); + cargarBackupsDev(); } else if (tab === 'escuelas') { const btn = document.getElementById('btnDevTabEscuelas'); const content = document.getElementById('devTabContentEscuelas'); if (btn) btn.classList.add('active'); if (content) content.style.display = 'block'; loadDevEscuelas(); + } else if (tab === 'importacion') { + const btn = document.getElementById('btnDevTabImportacion'); + const content = document.getElementById('devTabContentImportacion'); + if (btn) btn.classList.add('active'); + if (content) content.style.display = 'block'; + cargarEscuelasSelectImportacion(); } } @@ -7586,5 +7593,306 @@ async function toggleDevEscuelaEstado(id, nuevoEstado) { } } +// ========================================== +// GESTIÓN DE COPIAS DE SEGURIDAD (DEVELOPER) +// ========================================== +async function cargarBackupsDev() { + const tbody = document.getElementById('devBackupsTableBody'); + if (!tbody) return; + + try { + const res = await fetch('/api/developer/backups'); + const data = await res.json(); + const backups = data.backups || []; + + if (backups.length === 0) { + tbody.innerHTML = `No hay respaldos generados aún. Haz clic en "Crear Respaldo Ahora".`; + return; + } + + tbody.innerHTML = backups.map(b => { + const fechaFmt = b.fecha ? new Date(b.fecha).toLocaleString('es-CR') : '-'; + const badgeColor = b.tipo === 'PostgreSQL' ? '#0284c7' : '#16a34a'; + return ` + + + 💾 ${escapeHtml(b.filename)} + + + + ${escapeHtml(b.tipo)} + + + + ${fechaFmt} + + + ${escapeHtml(b.sizeFmt)} + + + + + + `; + }).join(''); + } catch (err) { + tbody.innerHTML = `Error al cargar lista de respaldos: ${escapeHtml(err.message)}`; + } +} + +async function ejecutarBackupManualDev() { + const btn = document.getElementById('btnDevCrearBackup'); + const msg = document.getElementById('devBackupsStatusMsg'); + if (btn) { + btn.disabled = true; + btn.innerHTML = '⏳ Generando Respaldo...'; + } + if (msg) msg.style.display = 'none'; + + try { + const res = await fetch('/api/developer/backups/crear', { method: 'POST' }); + const data = await res.json(); + if (!res.ok) throw new Error(data.error || 'Error generando respaldo'); + + if (window.sounds) window.sounds.playSuccess(); + if (msg) { + msg.style.display = 'block'; + msg.style.background = '#f0fdf4'; + msg.style.border = '1px solid #bbf7d0'; + msg.style.color = '#166534'; + msg.textContent = `✅ ${data.mensaje}`; + } + cargarBackupsDev(); + } catch (err) { + if (window.sounds) window.sounds.playError(); + if (msg) { + msg.style.display = 'block'; + msg.style.background = '#fef2f2'; + msg.style.border = '1px solid #fecaca'; + msg.style.color = '#991b1b'; + msg.textContent = `❌ ${err.message}`; + } + } finally { + if (btn) { + btn.disabled = false; + btn.innerHTML = ` Crear Respaldo Ahora`; + } + } +} + +function descargarBackupDev(filename) { + window.location.href = `/api/developer/backups/descargar/${filename}`; +} + +// ========================================== +// CARGA MASIVA DE ESTUDIANTES (DEVELOPER) +// ========================================== +let parsedStudentsToImport = []; + +async function cargarEscuelasSelectImportacion() { + const select = document.getElementById('devImportEscuelaSelect'); + if (!select) return; + + try { + const res = await fetch('/api/developer/escuelas'); + const escuelas = await res.json(); + select.innerHTML = escuelas.map(e => ` + + `).join(''); + } catch (err) { + console.error('Error cargando escuelas para importación:', err); + } +} + +function descargarPlantillaCsvEstudiantes() { + const headers = ['Nombre Completo', 'Grado', 'Seccion', 'Saldo Inicial', 'Alergias', 'Telefono Padre']; + const sampleRows = [ + ['Santiago Morales Castro', '5to', '5-B', '3000', 'Lactosa', '8888-1234'], + ['Valeria Solano Gómez', '3ro', '3-A', '5000', 'Ninguna', '8765-4321'], + ['Mateo Alvarado Pérez', '2do', '2-A', '0', 'Maní', '8333-2211'] + ]; + const csvContent = '\uFEFF' + [headers.join(','), ...sampleRows.map(r => r.map(c => `"${c}"`).join(','))].join('\r\n'); + const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = 'plantilla_estudiantes_sibopay.csv'; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); +} + +function handleDevImportFile(event) { + const file = event.target.files && event.target.files[0]; + if (!file) return; + + const reader = new FileReader(); + reader.onload = function(e) { + const content = e.target.result; + const txt = document.getElementById('devImportTextarea'); + if (txt) { + txt.value = content; + analizarDatosImportacionDev(); + } + }; + reader.readAsText(file); +} + +function analizarDatosImportacionDev() { + const textarea = document.getElementById('devImportTextarea'); + const previewBox = document.getElementById('devImportPreviewBox'); + const tbody = document.getElementById('devImportPreviewTbody'); + const countBadge = document.getElementById('devImportPreviewCount'); + const resultMsg = document.getElementById('devImportResultMsg'); + if (resultMsg) resultMsg.style.display = 'none'; + + if (!textarea || !textarea.value.trim()) { + alert('Por favor, pega datos de Excel o escribe el listado de alumnos.'); + return; + } + + const rawLines = textarea.value.trim().split(/\r?\n/); + parsedStudentsToImport = []; + + for (let i = 0; i < rawLines.length; i++) { + const line = rawLines[i].trim(); + if (!line) continue; + + let delimiter = '\t'; + if (line.includes('\t')) delimiter = '\t'; + else if (line.includes(',')) delimiter = ','; + else if (line.includes(';')) delimiter = ';'; + + const cols = line.split(delimiter).map(c => c.trim().replace(/^["']|["']$/g, '')); + if (cols.length === 0 || !cols[0]) continue; + + const firstColLower = cols[0].toLowerCase(); + if (i === 0 && (firstColLower.includes('nombre') || firstColLower.includes('alumno') || firstColLower.includes('estudiante'))) { + continue; + } + + const nombre = cols[0]; + const grado = cols[1] || 'General'; + const seccion = cols[2] || 'A'; + const saldo = parseInt(cols[3] || 0, 10) || 0; + const alergias = cols[4] || 'Ninguna conocida'; + const tel = cols[5] || ''; + + parsedStudentsToImport.push({ + nombre_completo: nombre, + grado: grado, + seccion: seccion, + saldo_inicial: saldo, + alergias: alergias, + padre_telefono: tel + }); + } + + if (parsedStudentsToImport.length === 0) { + alert('No se detectaron alumnos válidos en el texto ingresado.'); + return; + } + + if (countBadge) countBadge.textContent = `${parsedStudentsToImport.length} Alumnos Detectados`; + if (tbody) { + tbody.innerHTML = parsedStudentsToImport.map((st, idx) => ` + + ${idx + 1} + ${escapeHtml(st.nombre_completo)} + ${escapeHtml(st.grado)} - ${escapeHtml(st.seccion)} + ₡${st.saldo_inicial.toLocaleString('es-CR')} + ${escapeHtml(st.alergias)} + ${escapeHtml(st.padre_telefono || '-')} + (Auto-generado) + + `).join(''); + } + + if (previewBox) previewBox.style.display = 'block'; +} + +async function ejecutarImportacionMasivaDev() { + if (!parsedStudentsToImport || parsedStudentsToImport.length === 0) { + alert('Primero analiza y previsualiza los estudiantes a importar.'); + return; + } + + const select = document.getElementById('devImportEscuelaSelect'); + const escuelaId = select ? parseInt(select.value, 10) : 1; + const btn = document.getElementById('btnDevEjecutarImport'); + const resultMsg = document.getElementById('devImportResultMsg'); + + if (btn) { + btn.disabled = true; + btn.textContent = '⏳ Importando en la Base de Datos...'; + } + + try { + const res = await fetch('/api/developer/estudiantes/importar-masivo', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + escuela_id: escuelaId, + estudiantes: parsedStudentsToImport + }) + }); + + const data = await res.json(); + if (!res.ok) throw new Error(data.error || 'Error al procesar la importación.'); + + if (window.sounds) { + window.sounds.playSuccess(); + window.sounds.playCoin(); + } + + if (resultMsg) { + resultMsg.style.display = 'block'; + resultMsg.style.background = '#f0fdf4'; + resultMsg.style.border = '1.5px solid #86efac'; + resultMsg.style.color = '#166534'; + resultMsg.innerHTML = ` + ${data.mensaje} +
Total procesados: ${data.totalProcesados} · Insertados con éxito: ${data.insertados} · Omitidos: ${data.omitidos}
+ ${data.errores && data.errores.length > 0 ? `
Avisos: ${data.errores.join(' | ')}
` : ''} + `; + } + + document.getElementById('devImportPreviewBox').style.display = 'none'; + document.getElementById('devImportTextarea').value = ''; + parsedStudentsToImport = []; + + } catch (err) { + if (window.sounds) window.sounds.playError(); + if (resultMsg) { + resultMsg.style.display = 'block'; + resultMsg.style.background = '#fef2f2'; + resultMsg.style.border = '1.5px solid #fecaca'; + resultMsg.style.color = '#991b1b'; + resultMsg.innerHTML = `Error durante la importación: ${err.message}`; + } + } finally { + if (btn) { + btn.disabled = false; + btn.textContent = '⚡ Confirmar e Importar Todos los Estudiantes'; + } + } +} + +// ========================================== +// EXPORTACIÓN A EXCEL / CSV (ADMIN SODA) +// ========================================== +function exportarVentasCsv() { + const escuelaId = (window.currentAdminUser && window.currentAdminUser.escuela_id) || ''; + window.open(`/api/admin/export/ventas.csv${escuelaId ? '?escuela_id=' + escuelaId : ''}`, '_blank'); +} + +function exportarEstudiantesCsv() { + const escuelaId = (window.currentAdminUser && window.currentAdminUser.escuela_id) || ''; + window.open(`/api/admin/export/estudiantes.csv${escuelaId ? '?escuela_id=' + escuelaId : ''}`, '_blank'); +} + diff --git a/public/js/pos.js b/public/js/pos.js index ed196e0..fdbab44 100644 --- a/public/js/pos.js +++ b/public/js/pos.js @@ -127,6 +127,15 @@ document.addEventListener('DOMContentLoaded', async () => { }; window.addEventListener('click', promptOnFirstInteraction, { once: true }); window.addEventListener('touchstart', promptOnFirstInteraction, { once: true }); + + // Inicializar preferencia de auto-impresión de ticket térmico + const chkAutoPrint = document.getElementById('chkPosAutoPrint'); + if (chkAutoPrint) { + chkAutoPrint.checked = localStorage.getItem('sibopay_pos_autoprint') === '1'; + chkAutoPrint.addEventListener('change', () => { + localStorage.setItem('sibopay_pos_autoprint', chkAutoPrint.checked ? '1' : '0'); + }); + } }); // Cargar catálogo de productos @@ -1212,14 +1221,42 @@ async function handlePistolBarcodeScan(rawToken) { window.sounds.playCoin(); } + // Guardar para impresión de comanda / ticket térmico + window.lastCompletedOrder = { + orderCode: dataCobro.codigo_orden || ('ORD-' + Date.now().toString().slice(-4)), + student: { + nombre_completo: student.nombre_completo, + codigo_estudiante: student.codigo_estudiante, + grado: student.grado || student.grado_seccion || '' + }, + items: posCart.map(i => ({ + nombre: i.product?.nombre || 'Producto', + cantidad: i.cantidad || 1, + precio: i.product?.precio || 0, + subtotal: (i.product?.precio || 0) * (i.cantidad || 1) + })), + total: totalCompra, + nuevoSaldo: nuevoSaldo, + fecha: new Date() + }; + + // Auto-imprimir ticket si está activada la casilla + const autoPrintActive = !!document.getElementById('chkPosAutoPrint')?.checked; + if (autoPrintActive) { + setTimeout(() => { + imprimirTicketTermico(); + }, 350); + } + // Limpiar carrito de mostrador clearPosCart(); clearScannedStudent(); - // Auto-cerrar el modal en 2.5 segundos para quedar listo para el siguiente alumno + // Auto-cerrar el modal (dar más tiempo si se imprime para no interrumpir el diálogo) + const closeDelay = autoPrintActive ? 6000 : 2500; pistolaAutoCloseTimer = setTimeout(() => { closePistolaModal(); - }, 2500); + }, closeDelay); } catch (err) { if (window.sounds) window.sounds.playError(); @@ -2189,4 +2226,105 @@ function copyPistolaUrl() { } window.copyPistolaUrl = copyPistolaUrl; +// ========================================== +// IMPRESIÓN DE COMANDA / TICKET TÉRMICO (58mm / 80mm) +// ========================================== +function escapeHtml(str) { + if (!str) return ''; + return String(str) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +function imprimirTicketTermico(orderData) { + const ord = orderData || window.lastCompletedOrder; + if (!ord) { + alert('No hay ninguna venta o comanda reciente para imprimir.'); + return; + } + + // Si el modal está abierto con auto-cierre, pausar o extender el temporizador + if (typeof pistolaAutoCloseTimer !== 'undefined' && pistolaAutoCloseTimer) { + clearTimeout(pistolaAutoCloseTimer); + pistolaAutoCloseTimer = setTimeout(() => { + if (typeof closePistolaModal === 'function') closePistolaModal(); + }, 6000); + } + + const container = document.getElementById('posThermalReceipt'); + if (!container) return; + + const fechaFmt = (ord.fecha ? new Date(ord.fecha) : new Date()).toLocaleString('es-CR', { + day: '2-digit', month: '2-digit', year: 'numeric', + hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true + }); + + const itemsRows = (ord.items || []).map(it => { + const cant = it.cantidad || 1; + const subt = (it.subtotal != null ? it.subtotal : ((it.precio || 0) * cant)); + return ` + + ${cant}x + ${escapeHtml(it.nombre)} + ₡${Number(subt).toLocaleString('es-CR')} + + `; + }).join(''); + + container.innerHTML = ` +
+
SIBOPAY
+
SODA ESCOLAR • COMPROBANTE
+
+ +
+
Fecha: ${fechaFmt}
+
Ticket: #${escapeHtml(ord.orderCode)}
+
Estudiante: ${escapeHtml(ord.student?.nombre_completo || 'Cliente')}
+ ${ord.student?.grado ? `
Grado: ${escapeHtml(ord.student.grado)}
` : ''} +
+ +
+ + + + + + + + + + + ${itemsRows} + +
Cant.DetalleTotal
+ +
+ +
+ TOTAL COBRADO: + ₡${Number(ord.total || 0).toLocaleString('es-CR')} +
+ +
+ Saldo Disponible: + ₡${Number(ord.nuevoSaldo || 0).toLocaleString('es-CR')} +
+ +
+
+ ¡Gracias por su compra!
+ Monedero Escolar SiboPay +
+
+ `; + + window.print(); +} +window.imprimirTicketTermico = imprimirTicketTermico; + + diff --git a/public/pos.html b/public/pos.html index aee4559..e2a84c3 100644 --- a/public/pos.html +++ b/public/pos.html @@ -38,6 +38,36 @@ from { transform: rotate(0deg); } to { transform: rotate(360deg); } } + + /* Formateo de impresión para Comanda / Ticket Térmico (58mm / 80mm) */ + @media print { + body * { + visibility: hidden !important; + } + #posThermalReceipt, #posThermalReceipt * { + visibility: visible !important; + } + #posThermalReceipt { + position: fixed !important; + left: 0 !important; + top: 0 !important; + width: 100% !important; + max-width: 80mm !important; + margin: 0 !important; + padding: 4mm 2mm !important; + font-family: 'Courier New', Courier, monospace !important; + font-size: 12px !important; + line-height: 1.3 !important; + color: #000000 !important; + background: #ffffff !important; + display: block !important; + z-index: 999999 !important; + } + @page { + margin: 0; + size: auto; + } + } - + diff --git a/public/sw.js b/public/sw.js index ce616ed..5a45c20 100644 --- a/public/sw.js +++ b/public/sw.js @@ -1,5 +1,5 @@ -// RecreoPay PWA Service Worker v9.5 - Soporte Pistola Móvil Remota -const CACHE_NAME = 'recreopay-v9.5'; +// SiboPay PWA Service Worker v12.0 - Alta Velocidad & Despacho +const CACHE_NAME = 'sibopay-v12.0'; const STATIC_ASSETS = [ '/', '/index.html', @@ -12,8 +12,11 @@ const STATIC_ASSETS = [ '/js/app.js', '/js/pos.js', '/js/sounds.js', + '/js/food-icons.js', '/icons/icon-192.png', - '/icons/icon-512.png' + '/icons/icon-512.png', + '/img/sibopay-emblem.png', + '/apple-touch-icon.png' ]; self.addEventListener('install', (event) => { @@ -85,18 +88,18 @@ self.addEventListener('push', (event) => { try { data = event.data.json(); } catch (e) { - data = { title: '🔔 RecreoPay', body: event.data.text() }; + data = { title: '🔔 SiboPay', body: event.data.text() }; } } - const title = data.title || '🔔 RecreoPay'; + const title = data.title || '🔔 SiboPay'; const options = { - body: data.body || 'Tienes una nueva notificación de RecreoPay', + body: data.body || 'Tienes una nueva notificación de SiboPay', icon: data.icon || '/icons/icon-192.png', badge: data.badge || '/icons/icon-192.png', vibrate: [250, 100, 250, 100, 250], data: data.data || { url: '/pos.html?tab=sinpe' }, - tag: data.tag || `recreopay-push-${Date.now()}`, + tag: data.tag || `sibopay-push-${Date.now()}`, renotify: true, requireInteraction: true }; diff --git a/server/server.js b/server/server.js index a34bc34..7d1c894 100644 --- a/server/server.js +++ b/server/server.js @@ -1342,6 +1342,284 @@ app.put('/api/developer/escuelas/:id/estado', (req, res) => { } }); +// ========================================== +// MÓDULO DE COPIAS DE SEGURIDAD (BACKUPS) +// ========================================== +const backupsDir = path.join(__dirname, 'backups'); +if (!fs.existsSync(backupsDir)) { + try { fs.mkdirSync(backupsDir, { recursive: true }); } catch (e) {} +} + +function rotarBackups() { + try { + const files = fs.readdirSync(backupsDir) + .filter(f => f.startsWith('sibopay_')) + .map(f => { + const p = path.join(backupsDir, f); + return { name: f, path: p, time: fs.statSync(p).mtimeMs }; + }) + .sort((a, b) => b.time - a.time); + if (files.length > 20) { + for (const oldFile of files.slice(20)) { + try { fs.unlinkSync(oldFile.path); } catch (e) {} + } + } + } catch (e) {} +} + +async function ejecutarBackupBaseDatos() { + const isPg = Boolean(process.env.DATABASE_URL); + const now = new Date(); + const pad = (n) => String(n).padStart(2, '0'); + const timestamp = `${now.getFullYear()}-${pad(now.getMonth()+1)}-${pad(now.getDate())}_${pad(now.getHours())}-${pad(now.getMinutes())}-${pad(now.getSeconds())}`; + + if (isPg) { + const filename = `sibopay_pg_${timestamp}.sql`; + const targetPath = path.join(backupsDir, filename); + const dbUrl = process.env.DATABASE_URL; + const parsed = new URL(dbUrl); + const user = parsed.username || 'postgres'; + const password = parsed.password || ''; + const host = parsed.hostname || '127.0.0.1'; + const port = parsed.port || '5432'; + const dbname = parsed.pathname ? parsed.pathname.replace(/^\//, '') : 'recreopay_db'; + + return new Promise((resolve, reject) => { + const { exec } = require('child_process'); + const cmd = `PGPASSWORD="${password}" pg_dump -h ${host} -p ${port} -U ${user} -d ${dbname} --clean > "${targetPath}"`; + exec(cmd, (err, stdout, stderr) => { + if (err) return reject(new Error('Fallo al ejecutar pg_dump: ' + (stderr || err.message))); + const stat = fs.statSync(targetPath); + rotarBackups(); + resolve({ + filename, + sizeBytes: stat.size, + sizeFmt: (stat.size / 1024).toFixed(1) + ' KB', + fecha: now.toISOString(), + tipo: 'PostgreSQL' + }); + }); + }); + } else { + const filename = `sibopay_sqlite_${timestamp}.db`; + const targetPath = path.join(backupsDir, filename); + const sqliteSource = path.join(__dirname, 'recreopay.db'); + if (fs.existsSync(sqliteSource)) { + fs.copyFileSync(sqliteSource, targetPath); + } + const stat = fs.existsSync(targetPath) ? fs.statSync(targetPath) : { size: 0 }; + rotarBackups(); + return { + filename, + sizeBytes: stat.size, + sizeFmt: (stat.size / 1024).toFixed(1) + ' KB', + fecha: now.toISOString(), + tipo: 'SQLite' + }; + } +} + +// Programar backup automático cada 24 horas (iniciado tras 5 minutos de uptime) +setTimeout(() => { + ejecutarBackupBaseDatos().catch(() => {}); + setInterval(() => { + ejecutarBackupBaseDatos().catch(() => {}); + }, 24 * 60 * 60 * 1000); +}, 5 * 60 * 1000); + +// Endpoint: Listar backups existentes (Developer) +app.get('/api/developer/backups', (req, res) => { + try { + if (!fs.existsSync(backupsDir)) { + return res.json({ backups: [] }); + } + const files = fs.readdirSync(backupsDir) + .filter(f => f.startsWith('sibopay_')) + .map(f => { + const p = path.join(backupsDir, f); + const stat = fs.statSync(p); + return { + filename: f, + sizeBytes: stat.size, + sizeFmt: (stat.size / 1024).toFixed(1) + ' KB', + fecha: stat.mtime.toISOString(), + tipo: f.includes('_pg_') ? 'PostgreSQL' : 'SQLite' + }; + }) + .sort((a, b) => new Date(b.fecha) - new Date(a.fecha)); + + res.json({ backups: files }); + } catch (err) { + res.status(500).json({ error: err.message }); + } +}); + +// Endpoint: Crear backup manual inmediato (Developer) +app.post('/api/developer/backups/crear', async (req, res) => { + try { + const backupInfo = await ejecutarBackupBaseDatos(); + res.json({ + exito: true, + mensaje: `Respaldo "${backupInfo.filename}" generado exitosamente (${backupInfo.sizeFmt}).`, + backup: backupInfo + }); + } catch (err) { + res.status(500).json({ error: err.message }); + } +}); + +// Endpoint: Descargar archivo de backup (Developer) +app.get('/api/developer/backups/descargar/:filename', (req, res) => { + try { + const safeFilename = path.basename(req.params.filename); + const targetPath = path.join(backupsDir, safeFilename); + if (!fs.existsSync(targetPath)) { + return res.status(404).send('Archivo de respaldo no encontrado.'); + } + res.download(targetPath, safeFilename); + } catch (err) { + res.status(500).send(err.message); + } +}); + +// ========================================== +// CARGA MASIVA DE ESTUDIANTES (DEVELOPER) +// ========================================== +app.post('/api/developer/estudiantes/importar-masivo', (req, res) => { + try { + const { escuela_id, estudiantes } = req.body; + if (!escuela_id) { + return res.status(400).json({ error: 'Debes seleccionar la escuela de destino.' }); + } + if (!Array.isArray(estudiantes) || estudiantes.length === 0) { + return res.status(400).json({ error: 'No se recibieron estudiantes para importar.' }); + } + + const escuela = db.prepare('SELECT id, codigo, nombre FROM escuelas WHERE id = ?').get(escuela_id); + if (!escuela) { + return res.status(404).json({ error: 'La escuela seleccionada no existe.' }); + } + + const schoolPrefix = (escuela.codigo || 'EST').toUpperCase().trim().replace(/[^A-Z0-9]/g, ''); + const year = new Date().getFullYear(); + + const maxRow = db.prepare('SELECT MAX(id) as maxId FROM estudiantes').get(); + let currentSeq = (maxRow && maxRow.maxId ? maxRow.maxId : 0) + 1; + + let insertados = 0; + let omitidos = 0; + const errores = []; + const resultados = []; + + const insertEstStmt = db.prepare(` + INSERT INTO estudiantes ( + codigo_estudiante, nombre_completo, edad, grado, seccion, + qr_token, pin_seguridad, foto_url, saldo_colones, limite_diario_colones, + alergias, padre_nombre, padre_telefono, permitir_transferencias, + tarjeta_bloqueada, activo, escuela_id + ) VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, 1, 0, 1, ?) + `); + + const insertTxStmt = db.prepare(` + INSERT INTO transacciones_saldo ( + estudiante_id, tipo, monto_colones, saldo_anterior, saldo_nuevo, descripcion + ) VALUES (?, 'recarga_manual', ?, 0, ?, 'Saldo inicial asignado por importación masiva') + `); + + const insertUserStmt = db.prepare(` + INSERT INTO usuarios (username, password_hash, rol, nombre, activo, escuela_id) + VALUES (?, ?, 'estudiante', ?, 1, ?) + `); + + const processImport = db.transaction(() => { + for (let i = 0; i < estudiantes.length; i++) { + const item = estudiantes[i]; + const rawNombre = item.nombre_completo || item.nombre || ''; + const cleanNombre = String(rawNombre).trim(); + + if (!cleanNombre) { + omitidos++; + errores.push(`Fila ${i + 1}: Nombre vacío.`); + continue; + } + + const grado = String(item.grado || item.nivel || 'Primaria').trim(); + const seccion = String(item.seccion || item.grupo || 'A').trim(); + const saldoInicial = Math.max(0, parseInt(item.saldo_inicial || item.saldo || 0, 10)); + const limiteDiario = Math.max(500, parseInt(item.limite_diario || 3000, 10)); + const alergias = String(item.alergias || 'Ninguna conocida').trim(); + const padreNombre = String(item.padre_nombre || item.encargado || '').trim(); + const padreTelefono = String(item.padre_telefono || item.telefono || '').trim(); + const edad = parseInt(item.edad || 10, 10); + const pin = String(item.pin || '1234').trim(); + + let codigoEstudiante = item.codigo ? String(item.codigo).trim().toUpperCase() : null; + if (codigoEstudiante) { + const existe = db.prepare('SELECT id FROM estudiantes WHERE codigo_estudiante = ?').get(codigoEstudiante); + if (existe) { + omitidos++; + errores.push(`Fila ${i + 1} ("${cleanNombre}"): El código "${codigoEstudiante}" ya está registrado.`); + continue; + } + } else { + codigoEstudiante = `${schoolPrefix}-${year}-${String(currentSeq).padStart(5, '0')}`; + } + + const primerNombre = cleanNombre.split(' ')[0].toUpperCase().normalize("NFD").replace(/[\u0300-\u036f]/g, ""); + const randomHex = Math.random().toString(16).substring(2, 6).toUpperCase(); + const qrToken = `QR-${schoolPrefix}-${primerNombre}-${year}-${String(currentSeq).padStart(5, '0')}-${randomHex}`; + + const resEst = insertEstStmt.run( + codigoEstudiante, + cleanNombre, + edad, + grado, + seccion, + qrToken, + pin, + saldoInicial, + limiteDiario, + alergias, + padreNombre, + padreTelefono, + escuela_id + ); + + const newEstId = resEst.lastInsertRowid || resEst.id; + + if (saldoInicial > 0) { + insertTxStmt.run(newEstId, saldoInicial, saldoInicial); + } + + const usernameEst = primerNombre.toLowerCase() + currentSeq; + try { + const resUser = insertUserStmt.run(usernameEst, pin, cleanNombre, escuela_id); + const userId = resUser.lastInsertRowid || resUser.id; + db.prepare('UPDATE estudiantes SET usuario_id = ? WHERE id = ?').run(userId, newEstId); + } catch (e) {} + + currentSeq++; + insertados++; + resultados.push({ id: newEstId, codigo: codigoEstudiante, nombre: cleanNombre }); + } + }); + + processImport(); + + res.json({ + exito: true, + totalProcesados: estudiantes.length, + insertados, + omitidos, + errores, + estudiantes: resultados.slice(0, 100), + mensaje: `¡Importación completada! Se crearon ${insertados} estudiante(s) con éxito en "${escuela.nombre}".` + }); + } catch (err) { + res.status(500).json({ error: err.message }); + } +}); + // Crear nuevo estudiante / usuario + carné QR (escalable a 5 dígitos y prefijos multi-negocio) app.post('/api/admin/estudiantes', (req, res) => { try { @@ -1567,6 +1845,113 @@ app.post('/api/admin/movimientos/:id/revertir', (req, res) => { } }); +// ========================================== +// EXPORTACIÓN A EXCEL / CSV (ADMIN SODA) +// ========================================== +function arrayToCsv(headers, rows) { + const escapeCell = (cell) => { + if (cell === null || cell === undefined) return ''; + const str = String(cell); + if (str.includes(',') || str.includes('"') || str.includes('\n') || str.includes('\r')) { + return `"${str.replace(/"/g, '""')}"`; + } + return str; + }; + const headerLine = headers.map(escapeCell).join(','); + const rowLines = rows.map(r => r.map(escapeCell).join(',')); + return '\uFEFF' + [headerLine, ...rowLines].join('\r\n'); +} + +// Exportar Ventas a CSV +app.get('/api/admin/export/ventas.csv', (req, res) => { + try { + const escuelaId = req.query.escuela_id ? parseInt(req.query.escuela_id, 10) : null; + let query = ` + SELECT o.id, o.codigo_orden, o.tipo_orden, o.momento_entrega, o.total_colones, o.estado, o.creado_en, + e.nombre_completo as estudiante_nombre, e.codigo_estudiante + FROM ordenes o + JOIN estudiantes e ON o.estudiante_id = e.id + `; + const params = []; + if (escuelaId) { + query += ` WHERE e.escuela_id = ? `; + params.push(escuelaId); + } + query += ` ORDER BY o.id DESC LIMIT 2000`; + + const ordenes = db.prepare(query).all(...params); + + const headers = ['Fecha y Hora', 'Código Orden', 'Estudiante', 'Código Est.', 'Tipo Orden', 'Horario Entrega', 'Total (CRC)', 'Estado']; + const csvData = ordenes.map(o => { + const fechaFmt = o.creado_en ? new Date(o.creado_en).toLocaleString('es-CR') : ''; + return [ + fechaFmt, + o.codigo_orden, + o.estudiante_nombre, + o.codigo_estudiante, + o.tipo_orden === 'preorden' ? 'Pre-orden' : 'Mostrador', + o.momento_entrega || 'Inmediato', + o.total_colones, + o.estado + ]; + }); + + const csvOutput = arrayToCsv(headers, csvData); + const filename = `ventas_sibopay_${new Date().toISOString().slice(0, 10)}.csv`; + res.setHeader('Content-Type', 'text/csv; charset=utf-8'); + res.setHeader('Content-Disposition', `attachment; filename="${filename}"`); + res.send(csvOutput); + } catch (err) { + res.status(500).json({ error: err.message }); + } +}); + +// Exportar Saldos de Estudiantes a CSV +app.get('/api/admin/export/estudiantes.csv', (req, res) => { + try { + const escuelaId = req.query.escuela_id ? parseInt(req.query.escuela_id, 10) : null; + let query = ` + SELECT e.codigo_estudiante, e.nombre_completo, e.grado, e.seccion, + e.saldo_colones, e.limite_diario_colones, e.alergias, e.bloquear_chucherias, + e.padre_nombre, e.padre_telefono, e.activo, esc.nombre as escuela_nombre + FROM estudiantes e + LEFT JOIN escuelas esc ON e.escuela_id = esc.id + `; + const params = []; + if (escuelaId) { + query += ` WHERE e.escuela_id = ? `; + params.push(escuelaId); + } + query += ` ORDER BY e.nombre_completo ASC`; + + const rows = db.prepare(query).all(...params); + const headers = ['Código Estudiante', 'Nombre Completo', 'Grado', 'Sección', 'Saldo Actual (CRC)', 'Límite Diario (CRC)', 'Alergias / Salud', 'Veto Chatarra', 'Encargado / Padre', 'Teléfono Padre', 'Sede Escolar', 'Estado']; + + const csvData = rows.map(r => [ + r.codigo_estudiante, + r.nombre_completo, + r.grado || '', + r.seccion || '', + r.saldo_colones || 0, + r.limite_diario_colones || 3000, + r.alergias || 'Ninguna conocida', + r.bloquear_chucherias ? 'SÍ (Veto Activo)' : 'NO', + r.padre_nombre || '', + r.padre_telefono || '', + r.escuela_nombre || 'Sede Central', + r.activo ? 'Activo' : 'Bloqueado' + ]); + + const csvOutput = arrayToCsv(headers, csvData); + const filename = `estudiantes_saldos_sibopay_${new Date().toISOString().slice(0, 10)}.csv`; + res.setHeader('Content-Type', 'text/csv; charset=utf-8'); + res.setHeader('Content-Disposition', `attachment; filename="${filename}"`); + res.send(csvOutput); + } catch (err) { + res.status(500).json({ error: err.message }); + } +}); + // ========================================== // 1. ESTUDIANTES Y QR // ==========================================