feat: exportacion excel admin, carga masiva estudiantes dev, ticket termico pos, backups bd y sw v12

This commit is contained in:
unknown
2026-10-07 15:41:07 -06:00
parent e00f8fffb4
commit ae5377f0e6
6 changed files with 1024 additions and 10 deletions
+136
View File
@@ -256,6 +256,10 @@
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 21h18"/><path d="M5 21V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16"/><path d="M9 21v-4a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v4"/><line x1="9" y1="9" x2="9" y2="9.01"/><line x1="15" y1="9" x2="15" y2="9.01"/></svg> <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 21h18"/><path d="M5 21V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16"/><path d="M9 21v-4a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v4"/><line x1="9" y1="9" x2="9" y2="9.01"/><line x1="15" y1="9" x2="15" y2="9.01"/></svg>
<span>Escuelas & Sedes</span> <span>Escuelas & Sedes</span>
</button> </button>
<button class="dev-tab-btn" id="btnDevTabImportacion" onclick="switchDevTab('importacion')" style="display: inline-flex; align-items: center; gap: 8px;">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
<span>Carga Masiva (Excel/CSV)</span>
</button>
</nav> </nav>
<!-- 1. PESTAÑA: USUARIOS Y ADMINISTRADORES --> <!-- 1. PESTAÑA: USUARIOS Y ADMINISTRADORES -->
@@ -438,6 +442,46 @@
<div id="devStatsContainer" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 16px; margin-bottom: 24px;"> <div id="devStatsContainer" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 16px; margin-bottom: 24px;">
<!-- Inyectado dinámicamente --> <!-- Inyectado dinámicamente -->
</div> </div>
<!-- SECCIÓN: COPIAS DE SEGURIDAD (BACKUPS) AUTOMÁTICAS -->
<div class="dev-card" style="background: var(--card-bg); border: 1.5px solid var(--border); border-radius: 18px; padding: 22px; margin-top: 20px;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; flex-wrap: wrap; gap: 10px;">
<div style="display: flex; align-items: center; gap: 10px;">
<div style="width: 38px; height: 38px; border-radius: 10px; background: #f0fdf4; color: #166534; border: 1px solid #bbf7d0; display: flex; align-items: center; justify-content: center; font-size: 1.25rem;">
💾
</div>
<div>
<h3 style="margin: 0; font-size: 1.08rem; font-weight: 900; color: var(--text-main);">Copias de Seguridad del Sistema (Backups)</h3>
<span style="font-size: 0.76rem; color: var(--text-muted);">Respaldos automáticos diarios y descargas manuales</span>
</div>
</div>
<button type="button" onclick="ejecutarBackupManualDev()" id="btnDevCrearBackup" class="dev-action-btn dev-action-btn-primary" style="padding: 9px 18px; font-size: 0.84rem; display: inline-flex; align-items: center; gap: 6px;">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.3" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
<span>Crear Respaldo Ahora</span>
</button>
</div>
<div id="devBackupsStatusMsg" style="display: none; padding: 10px 14px; border-radius: 10px; margin-bottom: 14px; font-size: 0.82rem; font-weight: 700;"></div>
<div style="overflow-x: auto;">
<table class="dev-table" style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">
<thead>
<tr style="border-bottom: 1.5px solid var(--border); text-align: left; color: var(--text-muted);">
<th style="padding: 10px 12px;">Archivo de Respaldo</th>
<th style="padding: 10px 12px;">Motor BD</th>
<th style="padding: 10px 12px;">Fecha y Hora</th>
<th style="padding: 10px 12px;">Tamaño</th>
<th style="padding: 10px 12px; text-align: right;">Acción</th>
</tr>
</thead>
<tbody id="devBackupsTableBody">
<tr>
<td colspan="5" style="text-align: center; padding: 18px; color: var(--text-muted);">Cargando copias de seguridad...</td>
</tr>
</tbody>
</table>
</div>
</div>
</div> </div>
<!-- 4. PESTAÑA: ESCUELAS & SEDES (MULTI-TENANT) --> <!-- 4. PESTAÑA: ESCUELAS & SEDES (MULTI-TENANT) -->
@@ -463,6 +507,90 @@
<!-- Inyectado dinámicamente --> <!-- Inyectado dinámicamente -->
</div> </div>
</div> </div>
<!-- 5. PESTAÑA: CARGA MASIVA DE ESTUDIANTES (DEVELOPER) -->
<div id="devTabContentImportacion" class="dev-tab-content" style="display: none;">
<div class="dev-card" style="background: var(--card-bg); border: 1.5px solid var(--border); border-radius: 18px; padding: 24px; margin-bottom: 20px;">
<div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 18px; flex-wrap: wrap; gap: 12px;">
<div>
<h3 style="margin: 0; font-size: 1.2rem; font-weight: 900; color: var(--text-main); display: flex; align-items: center; gap: 8px;">
<span>👥 Carga Masiva de Estudiantes vía Excel / CSV</span>
</h3>
<p style="margin: 4px 0 0 0; font-size: 0.82rem; color: var(--text-muted); line-height: 1.4;">
Importa decenas o cientos de estudiantes en segundos. Puedes subir un archivo <code>.csv</code> o pegar las celdas directamente copiadas desde Microsoft Excel o Google Sheets.
</p>
</div>
<button type="button" onclick="descargarPlantillaCsvEstudiantes()" class="dev-action-btn" style="padding: 8px 14px; font-size: 0.80rem; display: inline-flex; align-items: center; gap: 6px;">
<span>📥 Descargar Plantilla Ejemplo (.CSV)</span>
</button>
</div>
<!-- Paso 1: Seleccionar Escuela Destino -->
<div style="margin-bottom: 18px; background: #f8fafc; border: 1.5px solid var(--border); padding: 16px; border-radius: 14px;">
<label style="font-size: 0.84rem; font-weight: 800; color: var(--text-main); display: block; margin-bottom: 6px;">
1. Selecciona la Escuela / Sede de Destino: *
</label>
<select id="devImportEscuelaSelect" style="width: 100%; max-width: 420px; padding: 10px 14px; border-radius: 10px; border: 1.5px solid var(--border); background: var(--card-bg); color: var(--text-main); font-weight: 700; font-size: 0.90rem;">
<!-- Cargado dinámicamente -->
</select>
</div>
<!-- Paso 2: Pegar o Subir Datos -->
<div style="margin-bottom: 18px;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
<label style="font-size: 0.84rem; font-weight: 800; color: var(--text-main); display: block;">
2. Pega aquí los datos desde Excel o escribe en formato CSV:
</label>
<span style="font-size: 0.74rem; color: var(--text-muted);">Columnas: <strong>Nombre, Grado, Sección, Saldo (opcional), Alergias (opcional), Tel. Padre (opcional)</strong></span>
</div>
<textarea id="devImportTextarea" rows="7" placeholder="Ejemplo pegado desde Excel:&#10;Santiago Morales Castro&#9;5to&#9;5-B&#9;2500&#9;Lactosa&#9;8888-1234&#10;Valeria Solano Gómez&#9;3ro&#9;3-A&#9;5000&#9;Ninguna&#9;8765-4321&#10;Mateo Alvarado Pérez&#9;2do&#9;2-A&#9;0&#9;Maní&#9;8333-2211" style="width: 100%; padding: 12px 14px; border-radius: 12px; border: 1.5px solid var(--border); background: var(--card-bg); color: var(--text-main); font-family: monospace; font-size: 0.84rem; line-height: 1.45; box-sizing: border-box;"></textarea>
<div style="display: flex; justify-content: space-between; align-items: center; margin-top: 10px; flex-wrap: wrap; gap: 10px;">
<div style="display: flex; align-items: center; gap: 8px;">
<span style="font-size: 0.78rem; font-weight: 700; color: var(--text-muted);">O selecciona archivo CSV:</span>
<input type="file" id="devImportFileInput" accept=".csv,.txt" onchange="handleDevImportFile(event)" style="font-size: 0.78rem;">
</div>
<button type="button" onclick="analizarDatosImportacionDev()" class="dev-action-btn dev-action-btn-primary" style="padding: 10px 20px; font-size: 0.88rem; display: inline-flex; align-items: center; gap: 6px;">
<span>🔍 Previsualizar y Validar</span>
</button>
</div>
</div>
<!-- Paso 3: Previsualización de Datos -->
<div id="devImportPreviewBox" style="display: none; border-top: 1.5px dashed var(--border); padding-top: 18px; margin-top: 18px;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; flex-wrap: wrap; gap: 8px;">
<div style="display: flex; align-items: center; gap: 10px;">
<span id="devImportPreviewCount" style="background: #e0f2fe; color: #0284c7; padding: 4px 10px; border-radius: 8px; font-weight: 800; font-size: 0.80rem;">0 Alumnos Detectados</span>
<span style="font-size: 0.78rem; color: var(--text-muted);">Revisa la lista antes de guardar</span>
</div>
<button type="button" onclick="ejecutarImportacionMasivaDev()" id="btnDevEjecutarImport" class="dev-action-btn dev-action-btn-primary" style="background: linear-gradient(135deg, #16a34a, #15803d); border-color: #16a34a; padding: 10px 22px; font-size: 0.90rem; font-weight: 800;">
<span>⚡ Confirmar e Importar Todos los Estudiantes</span>
</button>
</div>
<div style="overflow-x: auto; max-height: 380px; overflow-y: auto; border: 1px solid var(--border); border-radius: 12px;">
<table class="dev-table" style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">
<thead style="position: sticky; top: 0; background: var(--card-bg); z-index: 2;">
<tr style="border-bottom: 1.5px solid var(--border); text-align: left; color: var(--text-muted);">
<th style="padding: 8px 10px;">#</th>
<th style="padding: 8px 10px;">Nombre Completo</th>
<th style="padding: 8px 10px;">Grado/Sección</th>
<th style="padding: 8px 10px;">Saldo Inicial</th>
<th style="padding: 8px 10px;">Alergias</th>
<th style="padding: 8px 10px;">Teléfono Padre</th>
<th style="padding: 8px 10px;">Código Asignado</th>
</tr>
</thead>
<tbody id="devImportPreviewTbody">
<!-- Filas inyectadas -->
</tbody>
</table>
</div>
</div>
<div id="devImportResultMsg" style="display: none; margin-top: 16px; padding: 14px; border-radius: 12px; font-size: 0.84rem; line-height: 1.45;"></div>
</div>
</div>
</div> </div>
<!-- PANEL DE ADMINISTRACIÓN DE LA SODA (#viewAdmin) --> <!-- PANEL DE ADMINISTRACIÓN DE LA SODA (#viewAdmin) -->
@@ -507,6 +635,14 @@
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="20" height="14" x="2" y="3" rx="2"/><line x1="8" x2="16" y1="21" y2="21"/><line x1="12" x2="12" y1="17" y2="21"/></svg> <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="20" height="14" x="2" y="3" rx="2"/><line x1="8" x2="16" y1="21" y2="21"/><line x1="12" x2="12" y1="17" y2="21"/></svg>
<span class="admin-btn-text">Terminal POS</span> <span class="admin-btn-text">Terminal POS</span>
</a> </a>
<button type="button" onclick="exportarVentasCsv()" class="btn-saas btn-saas-outline" style="height: 34px; border-color: #10b981; color: #166534;" title="Descargar histórico de ventas a archivo Excel / CSV">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
<span class="admin-btn-text">📊 Ventas Excel</span>
</button>
<button type="button" onclick="exportarEstudiantesCsv()" class="btn-saas btn-saas-outline" style="height: 34px; border-color: #0284c7; color: #0284c7;" title="Descargar listado de saldos de alumnos a Excel / CSV">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
<span class="admin-btn-text">📋 Saldos Excel</span>
</button>
</div> </div>
</header> </header>
+308
View File
@@ -517,12 +517,19 @@ function switchDevTab(tab) {
if (btn) btn.classList.add('active'); if (btn) btn.classList.add('active');
if (content) content.style.display = 'block'; if (content) content.style.display = 'block';
loadDevStats(); loadDevStats();
cargarBackupsDev();
} else if (tab === 'escuelas') { } else if (tab === 'escuelas') {
const btn = document.getElementById('btnDevTabEscuelas'); const btn = document.getElementById('btnDevTabEscuelas');
const content = document.getElementById('devTabContentEscuelas'); const content = document.getElementById('devTabContentEscuelas');
if (btn) btn.classList.add('active'); if (btn) btn.classList.add('active');
if (content) content.style.display = 'block'; if (content) content.style.display = 'block';
loadDevEscuelas(); 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 = `<tr><td colspan="5" style="text-align: center; padding: 18px; color: var(--text-muted);">No hay respaldos generados aún. Haz clic en "Crear Respaldo Ahora".</td></tr>`;
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 `
<tr style="border-bottom: 1px solid var(--border);">
<td style="padding: 10px 12px; font-weight: 800; color: var(--text-main); font-family: monospace;">
💾 ${escapeHtml(b.filename)}
</td>
<td style="padding: 10px 12px;">
<span style="font-size: 0.70rem; font-weight: 800; padding: 2px 7px; border-radius: 6px; background: rgba(2, 132, 199, 0.1); color: ${badgeColor};">
${escapeHtml(b.tipo)}
</span>
</td>
<td style="padding: 10px 12px; color: var(--text-muted); font-size: 0.78rem;">
${fechaFmt}
</td>
<td style="padding: 10px 12px; font-weight: 800; color: #16a34a;">
${escapeHtml(b.sizeFmt)}
</td>
<td style="padding: 10px 12px; text-align: right;">
<button type="button" onclick="descargarBackupDev('${encodeURIComponent(b.filename)}')" class="dev-action-btn" style="padding: 5px 12px; font-size: 0.76rem; display: inline-flex; align-items: center; gap: 4px;">
<span>⬇️ Descargar</span>
</button>
</td>
</tr>
`;
}).join('');
} catch (err) {
tbody.innerHTML = `<tr><td colspan="5" style="text-align: center; padding: 18px; color: #dc2626;">Error al cargar lista de respaldos: ${escapeHtml(err.message)}</td></tr>`;
}
}
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 = `<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.3" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg> <span>Crear Respaldo Ahora</span>`;
}
}
}
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 => `
<option value="${e.id}">${escapeHtml(e.nombre)} (${escapeHtml(e.codigo)})</option>
`).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) => `
<tr style="border-bottom: 1px solid var(--border);">
<td style="padding: 6px 10px; color: var(--text-muted);">${idx + 1}</td>
<td style="padding: 6px 10px; font-weight: 800; color: var(--text-main);">${escapeHtml(st.nombre_completo)}</td>
<td style="padding: 6px 10px;">${escapeHtml(st.grado)} - ${escapeHtml(st.seccion)}</td>
<td style="padding: 6px 10px; color: #16a34a; font-weight: 700;">₡${st.saldo_inicial.toLocaleString('es-CR')}</td>
<td style="padding: 6px 10px; color: ${st.alergias !== 'Ninguna conocida' ? '#e11d48' : 'var(--text-muted)'}; font-size: 0.76rem;">${escapeHtml(st.alergias)}</td>
<td style="padding: 6px 10px; font-family: monospace;">${escapeHtml(st.padre_telefono || '-')}</td>
<td style="padding: 6px 10px; color: #0284c7; font-size: 0.76rem; font-weight: 700;">(Auto-generado)</td>
</tr>
`).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 = `
<strong>${data.mensaje}</strong>
<div style="font-size: 0.78rem; margin-top: 6px;">Total procesados: ${data.totalProcesados} · Insertados con éxito: ${data.insertados} · Omitidos: ${data.omitidos}</div>
${data.errores && data.errores.length > 0 ? `<div style="color: #dc2626; font-size: 0.74rem; margin-top: 4px;">Avisos: ${data.errores.join(' | ')}</div>` : ''}
`;
}
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 = `<strong>Error durante la importación:</strong> ${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');
}
+140 -2
View File
@@ -127,6 +127,15 @@ document.addEventListener('DOMContentLoaded', async () => {
}; };
window.addEventListener('click', promptOnFirstInteraction, { once: true }); window.addEventListener('click', promptOnFirstInteraction, { once: true });
window.addEventListener('touchstart', 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 // Cargar catálogo de productos
@@ -1212,14 +1221,42 @@ async function handlePistolBarcodeScan(rawToken) {
window.sounds.playCoin(); 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 // Limpiar carrito de mostrador
clearPosCart(); clearPosCart();
clearScannedStudent(); 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(() => { pistolaAutoCloseTimer = setTimeout(() => {
closePistolaModal(); closePistolaModal();
}, 2500); }, closeDelay);
} catch (err) { } catch (err) {
if (window.sounds) window.sounds.playError(); if (window.sounds) window.sounds.playError();
@@ -2189,4 +2226,105 @@ function copyPistolaUrl() {
} }
window.copyPistolaUrl = copyPistolaUrl; window.copyPistolaUrl = copyPistolaUrl;
// ==========================================
// IMPRESIÓN DE COMANDA / TICKET TÉRMICO (58mm / 80mm)
// ==========================================
function escapeHtml(str) {
if (!str) return '';
return String(str)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
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 `
<tr>
<td style="padding: 2px 4px 2px 0; vertical-align: top; width: 26px; font-weight: bold;">${cant}x</td>
<td style="padding: 2px 4px; vertical-align: top; word-break: break-word;">${escapeHtml(it.nombre)}</td>
<td style="padding: 2px 0 2px 4px; vertical-align: top; text-align: right; white-space: nowrap; font-weight: bold;">₡${Number(subt).toLocaleString('es-CR')}</td>
</tr>
`;
}).join('');
container.innerHTML = `
<div style="text-align: center; font-family: 'Courier New', Courier, monospace; font-size: 12px; line-height: 1.25; color: #000; width: 100%; max-width: 80mm; margin: 0 auto; box-sizing: border-box;">
<div style="font-size: 15px; font-weight: 900; letter-spacing: 0.5px; margin-bottom: 2px;">SIBOPAY</div>
<div style="font-size: 11px; font-weight: bold; text-transform: uppercase; margin-bottom: 4px;">SODA ESCOLAR • COMPROBANTE</div>
<div style="border-top: 1px dashed #000; margin: 5px 0;"></div>
<div style="text-align: left; font-size: 11px; line-height: 1.35;">
<div><strong>Fecha:</strong> ${fechaFmt}</div>
<div><strong>Ticket:</strong> #${escapeHtml(ord.orderCode)}</div>
<div><strong>Estudiante:</strong> ${escapeHtml(ord.student?.nombre_completo || 'Cliente')}</div>
${ord.student?.grado ? `<div><strong>Grado:</strong> ${escapeHtml(ord.student.grado)}</div>` : ''}
</div>
<div style="border-top: 1px dashed #000; margin: 5px 0;"></div>
<table style="width: 100%; font-size: 11px; border-collapse: collapse; text-align: left; margin: 4px 0;">
<thead>
<tr style="border-bottom: 1px dashed #000;">
<th style="padding-bottom: 3px; font-weight: bold;">Cant.</th>
<th style="padding-bottom: 3px; font-weight: bold;">Detalle</th>
<th style="text-align: right; padding-bottom: 3px; font-weight: bold;">Total</th>
</tr>
</thead>
<tbody>
${itemsRows}
</tbody>
</table>
<div style="border-top: 1px dashed #000; margin: 5px 0;"></div>
<div style="display: flex; justify-content: space-between; font-size: 14px; font-weight: 900; margin: 4px 0;">
<span>TOTAL COBRADO:</span>
<span>₡${Number(ord.total || 0).toLocaleString('es-CR')}</span>
</div>
<div style="display: flex; justify-content: space-between; font-size: 11px; margin: 2px 0;">
<span>Saldo Disponible:</span>
<span style="font-weight: bold;">₡${Number(ord.nuevoSaldo || 0).toLocaleString('es-CR')}</span>
</div>
<div style="border-top: 1px dashed #000; margin: 6px 0;"></div>
<div style="text-align: center; font-size: 10px; margin-top: 6px; line-height: 1.3;">
¡Gracias por su compra!<br>
Monedero Escolar SiboPay
</div>
</div>
`;
window.print();
}
window.imprimirTicketTermico = imprimirTicketTermico;
+45 -1
View File
@@ -38,6 +38,36 @@
from { transform: rotate(0deg); } from { transform: rotate(0deg); }
to { transform: rotate(360deg); } 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;
}
}
</style> </style>
<script> <script>
function posLogout() { function posLogout() {
@@ -116,6 +146,10 @@
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg> <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>
<span>Admin</span> <span>Admin</span>
</a> </a>
<label style="display: inline-flex; align-items: center; gap: 6px; font-size: 0.74rem; font-weight: 700; color: #475569; background: #ffffff; padding: 4px 10px; border-radius: 8px; border: 1.5px solid #cbd5e1; cursor: pointer; user-select: none;" title="Imprimir comanda o ticket térmico automáticamente al finalizar cada cobro">
<input type="checkbox" id="chkPosAutoPrint" style="cursor: pointer; width: 14px; height: 14px;">
<span>🖨️ Auto-imprimir ticket</span>
</label>
</div> </div>
</div> </div>
@@ -438,6 +472,11 @@
<strong id="pistolaSuccessBalance" style="color: #16a34a; font-size: 0.95rem;">-</strong> <strong id="pistolaSuccessBalance" style="color: #16a34a; font-size: 0.95rem;">-</strong>
</div> </div>
</div> </div>
<div style="display: flex; gap: 8px; margin-bottom: 10px;">
<button type="button" onclick="imprimirTicketTermico()" class="btn-saas btn-saas-outline" style="flex: 1; height: 40px; font-size: 0.86rem; font-weight: 800; display: inline-flex; align-items: center; justify-content: center; gap: 6px; color: #0284c7; border-color: #bae6fd; background: #f0f9ff;" title="Imprimir ticket para impresora térmica de 58mm o 80mm">
<span>🖨️ Imprimir Ticket Térmico</span>
</button>
</div>
<button type="button" onclick="closePistolaModal()" class="btn-saas btn-saas-primary" style="width: 100%; height: 42px; background: #16a34a; border-color: #16a34a; font-size: 0.92rem; font-weight: 800;"> <button type="button" onclick="closePistolaModal()" class="btn-saas btn-saas-primary" style="width: 100%; height: 42px; background: #16a34a; border-color: #16a34a; font-size: 0.92rem; font-weight: 800;">
Listo / Siguiente Alumno (Enter) ➔ Listo / Siguiente Alumno (Enter) ➔
</button> </button>
@@ -499,6 +538,8 @@
</div> </div>
</form> </form>
</div> </div>
</div>
<!-- MODAL: VINCULAR TELÉFONO COMO PISTOLA QR INALÁMBRICA --> <!-- MODAL: VINCULAR TELÉFONO COMO PISTOLA QR INALÁMBRICA -->
<div class="modal-qr-backdrop" id="modalPhonePairing" style="display: none;" onclick="closePhonePairingModal(event)"> <div class="modal-qr-backdrop" id="modalPhonePairing" style="display: none;" onclick="closePhonePairingModal(event)">
<div class="modal-qr-card" onclick="event.stopPropagation()" style="max-width: 440px; text-align: center; border-radius: 20px; padding: 22px;"> <div class="modal-qr-card" onclick="event.stopPropagation()" style="max-width: 440px; text-align: center; border-radius: 20px; padding: 22px;">
@@ -527,9 +568,12 @@
</div> </div>
</div> </div>
<!-- CONTENEDOR DE TICKET TÉRMICO OCULTO EN PANTALLA (VISIBLE EN IMPRESIÓN 58mm / 80mm) -->
<div id="posThermalReceipt" style="display: none;"></div>
<script src="/js/sounds.js?v=8.6"></script> <script src="/js/sounds.js?v=8.6"></script>
<script src="/js/jsQR.js"></script> <script src="/js/jsQR.js"></script>
<script src="/js/food-icons.js?v=1.1"></script> <script src="/js/food-icons.js?v=1.1"></script>
<script src="/js/pos.js?v=10.4"></script> <script src="/js/pos.js?v=12.0"></script>
</body> </body>
</html> </html>
+10 -7
View File
@@ -1,5 +1,5 @@
// RecreoPay PWA Service Worker v9.5 - Soporte Pistola Móvil Remota // SiboPay PWA Service Worker v12.0 - Alta Velocidad & Despacho
const CACHE_NAME = 'recreopay-v9.5'; const CACHE_NAME = 'sibopay-v12.0';
const STATIC_ASSETS = [ const STATIC_ASSETS = [
'/', '/',
'/index.html', '/index.html',
@@ -12,8 +12,11 @@ const STATIC_ASSETS = [
'/js/app.js', '/js/app.js',
'/js/pos.js', '/js/pos.js',
'/js/sounds.js', '/js/sounds.js',
'/js/food-icons.js',
'/icons/icon-192.png', '/icons/icon-192.png',
'/icons/icon-512.png' '/icons/icon-512.png',
'/img/sibopay-emblem.png',
'/apple-touch-icon.png'
]; ];
self.addEventListener('install', (event) => { self.addEventListener('install', (event) => {
@@ -85,18 +88,18 @@ self.addEventListener('push', (event) => {
try { try {
data = event.data.json(); data = event.data.json();
} catch (e) { } 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 = { 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', icon: data.icon || '/icons/icon-192.png',
badge: data.badge || '/icons/icon-192.png', badge: data.badge || '/icons/icon-192.png',
vibrate: [250, 100, 250, 100, 250], vibrate: [250, 100, 250, 100, 250],
data: data.data || { url: '/pos.html?tab=sinpe' }, data: data.data || { url: '/pos.html?tab=sinpe' },
tag: data.tag || `recreopay-push-${Date.now()}`, tag: data.tag || `sibopay-push-${Date.now()}`,
renotify: true, renotify: true,
requireInteraction: true requireInteraction: true
}; };
+385
View File
@@ -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) // Crear nuevo estudiante / usuario + carné QR (escalable a 5 dígitos y prefijos multi-negocio)
app.post('/api/admin/estudiantes', (req, res) => { app.post('/api/admin/estudiantes', (req, res) => {
try { 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 // 1. ESTUDIANTES Y QR
// ========================================== // ==========================================