feat(export): generar reportes nativos en Excel XLSX con acentos limpios y columnas perfectas

This commit is contained in:
unknown
2026-10-08 13:16:33 -06:00
parent 5a0683d199
commit abee440e12
7 changed files with 201 additions and 59 deletions
+105 -1
View File
@@ -19,7 +19,8 @@
"puppeteer-core": "^25.12.0",
"qrcode": "^1.5.4",
"synckit": "^0.11.13",
"web-push": "^3.6.7"
"web-push": "^3.6.7",
"xlsx": "^0.18.5"
}
},
"node_modules/@pkgr/core": {
@@ -263,6 +264,15 @@
"node": ">= 0.6"
}
},
"node_modules/adler-32": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/adler-32/-/adler-32-1.3.1.tgz",
"integrity": "sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/agent-base": {
"version": "7.1.4",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
@@ -416,6 +426,19 @@
"node": ">=6"
}
},
"node_modules/cfb": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/cfb/-/cfb-1.2.2.tgz",
"integrity": "sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==",
"license": "Apache-2.0",
"dependencies": {
"adler-32": "~1.3.0",
"crc-32": "~1.2.0"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/chromium-bidi": {
"version": "17.0.2",
"resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-17.0.2.tgz",
@@ -443,6 +466,15 @@
"wrap-ansi": "^6.2.0"
}
},
"node_modules/codepage": {
"version": "1.15.0",
"resolved": "https://registry.npmjs.org/codepage/-/codepage-1.15.0.tgz",
"integrity": "sha512-3g6NUTPd/YtuuGrhMnOMRjFc+LJw/bnMp3+0r/Wcz3IXUuCosKRJvMphm5+Q+bvTVGcJJuRvVLuYba+WojaFaA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
@@ -524,6 +556,18 @@
"url": "https://opencollective.com/express"
}
},
"node_modules/crc-32": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz",
"integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==",
"license": "Apache-2.0",
"bin": {
"crc32": "bin/crc32.njs"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
@@ -850,6 +894,15 @@
"node": ">= 0.6"
}
},
"node_modules/frac": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/frac/-/frac-1.1.2.tgz",
"integrity": "sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/fresh": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",
@@ -2050,6 +2103,18 @@
"node": ">= 10.x"
}
},
"node_modules/ssf": {
"version": "0.11.2",
"resolved": "https://registry.npmjs.org/ssf/-/ssf-0.11.2.tgz",
"integrity": "sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==",
"license": "Apache-2.0",
"dependencies": {
"frac": "~1.1.2"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/statuses": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
@@ -2235,6 +2300,24 @@
"integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==",
"license": "ISC"
},
"node_modules/wmf": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wmf/-/wmf-1.0.2.tgz",
"integrity": "sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/word": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/word/-/word-0.3.0.tgz",
"integrity": "sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/wrap-ansi": {
"version": "6.2.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz",
@@ -2276,6 +2359,27 @@
}
}
},
"node_modules/xlsx": {
"version": "0.18.5",
"resolved": "https://registry.npmjs.org/xlsx/-/xlsx-0.18.5.tgz",
"integrity": "sha512-dmg3LCjBPHZnQp5/F/+nnTa+miPJxUXB6vtk42YjBBKayDNagxGEeIdWApkYPOf3Z3pm3k62Knjzp7lMeTEtFQ==",
"license": "Apache-2.0",
"dependencies": {
"adler-32": "~1.3.0",
"cfb": "~1.2.1",
"codepage": "~1.15.0",
"crc-32": "~1.2.1",
"ssf": "~0.11.2",
"wmf": "~1.0.1",
"word": "~0.3.0"
},
"bin": {
"xlsx": "bin/xlsx.njs"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/xtend": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
+2 -1
View File
@@ -31,6 +31,7 @@
"puppeteer-core": "^25.12.0",
"qrcode": "^1.5.4",
"synckit": "^0.11.13",
"web-push": "^3.6.7"
"web-push": "^3.6.7",
"xlsx": "^0.18.5"
}
}
+3 -3
View File
@@ -12,7 +12,7 @@
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="SiboPay">
<meta name="mobile-web-app-capable" content="yes">
<link rel="stylesheet" href="/css/styles.css?v=13.5">
<link rel="stylesheet" href="/css/styles.css?v=13.6">
<link rel="stylesheet" href="/css/desktop.css?v=2.2">
<style>
/* Transiciones suaves */
@@ -3365,10 +3365,10 @@
</button>
</nav>
<script src="/js/dialogs.js?v=13.5"></script>
<script src="/js/dialogs.js?v=13.6"></script>
<script src="/js/sounds.js?v=9.6"></script>
<script src="/js/jsQR.js"></script>
<script src="/js/food-icons.js?v=1.1"></script>
<script src="/js/app.js?v=13.5"></script>
<script src="/js/app.js?v=13.6"></script>
</body>
</html>
+10 -14
View File
@@ -4697,7 +4697,8 @@ async function guardarHorariosEscolares() {
}
function descargarReporteRecargasExcel(descargarTodo = false) {
let url = '/api/admin/export/recargas.csv';
let url = '/api/admin/export/recargas.xlsx';
let dateTag = new Date().toISOString().slice(0, 10);
if (!descargarTodo) {
const desde = document.getElementById('inputExportRecargasDesde')?.value || '';
const hasta = document.getElementById('inputExportRecargasHasta')?.value || '';
@@ -4708,17 +4709,12 @@ function descargarReporteRecargasExcel(descargarTodo = false) {
if (hasta) params.append('hasta', hasta);
if (estado && estado !== 'todos') params.append('estado', estado);
if (desde) dateTag = `${desde}_a_${hasta || desde}`;
const qs = params.toString();
if (qs) url += '?' + qs;
}
const link = document.createElement('a');
link.href = url;
link.target = '_blank';
link.download = '';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
descargarArchivoDirecto(url, `recargas_sinpe_sibopay_${dateTag}.xlsx`);
}
async function loadAdminData() {
@@ -8051,7 +8047,7 @@ async function descargarArchivoDirecto(url, defaultFilename) {
const blobUrl = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = blobUrl;
link.download = defaultFilename || 'reporte.csv';
link.download = defaultFilename || 'reporte.xlsx';
document.body.appendChild(link);
link.click();
setTimeout(() => {
@@ -8062,7 +8058,7 @@ async function descargarArchivoDirecto(url, defaultFilename) {
console.error('Error al descargar archivo blob, usando fallback directo:', err);
const link = document.createElement('a');
link.href = url;
link.download = defaultFilename || 'reporte.csv';
link.download = defaultFilename || 'reporte.xlsx';
link.target = '_blank';
document.body.appendChild(link);
link.click();
@@ -8326,8 +8322,8 @@ async function exportarVentasCsv() {
}
try {
const escuelaId = (currentUser && currentUser.escuela_id) || '';
const url = `/api/admin/export/ventas.csv${escuelaId ? '?escuela_id=' + escuelaId : ''}`;
await descargarArchivoDirecto(url, `ventas_sibopay_${new Date().toISOString().slice(0, 10)}.csv`);
const url = `/api/admin/export/ventas.xlsx${escuelaId ? '?escuela_id=' + escuelaId : ''}`;
await descargarArchivoDirecto(url, `ventas_sibopay_${new Date().toISOString().slice(0, 10)}.xlsx`);
} catch (err) {
alert('Error al exportar ventas: ' + err.message);
} finally {
@@ -8348,8 +8344,8 @@ async function exportarEstudiantesCsv() {
}
try {
const escuelaId = (currentUser && currentUser.escuela_id) || '';
const url = `/api/admin/export/estudiantes.csv${escuelaId ? '?escuela_id=' + escuelaId : ''}`;
await descargarArchivoDirecto(url, `estudiantes_sibopay_${new Date().toISOString().slice(0, 10)}.csv`);
const url = `/api/admin/export/estudiantes.xlsx${escuelaId ? '?escuela_id=' + escuelaId : ''}`;
await descargarArchivoDirecto(url, `estudiantes_saldos_sibopay_${new Date().toISOString().slice(0, 10)}.xlsx`);
} catch (err) {
alert('Error al exportar estudiantes: ' + err.message);
} finally {
+3 -3
View File
@@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SiboPay POS - Terminal de Mostrador y Despacho</title>
<link rel="icon" type="image/png" href="/img/sibopay-emblem.png">
<link rel="stylesheet" href="/css/styles.css?v=13.5">
<link rel="stylesheet" href="/css/styles.css?v=13.6">
<style>
/* Estilos específicos de terminal de alta velocidad */
.student-badge-scanned {
@@ -673,10 +673,10 @@
</div>
</div>
<script src="/js/dialogs.js?v=13.5"></script>
<script src="/js/dialogs.js?v=13.6"></script>
<script src="/js/sounds.js?v=8.6"></script>
<script src="/js/jsQR.js"></script>
<script src="/js/food-icons.js?v=1.1"></script>
<script src="/js/pos.js?v=13.5"></script>
<script src="/js/pos.js?v=13.6"></script>
</body>
</html>
+2 -2
View File
@@ -1,5 +1,5 @@
// SiboPay PWA Service Worker v13.5 - Corrección apertura y trazabilidad modal rechazo SINPE
const CACHE_NAME = 'sibopay-v13.5';
// SiboPay PWA Service Worker v13.6 - Exportación nativa Excel XLSX con acentos limpios
const CACHE_NAME = 'sibopay-v13.6';
const STATIC_ASSETS = [
'/',
'/index.html',
+76 -35
View File
@@ -1827,6 +1827,32 @@ app.post('/api/admin/movimientos/:id/revertir', (req, res) => {
// ==========================================
// EXPORTACIÓN A EXCEL / CSV (ADMIN SODA)
// ==========================================
let XLSX = null;
try {
XLSX = require('xlsx');
} catch (e) {
console.warn('Módulo XLSX no disponible, usando fallback CSV:', e.message);
}
function generarExcelWorkbook(sheetName, headers, rows) {
if (!XLSX) return null;
const wb = XLSX.utils.book_new();
const ws = XLSX.utils.aoa_to_sheet([headers, ...rows]);
// Auto-ajuste de anchos de columna para que el texto nunca salga cortado
ws['!cols'] = headers.map((h, i) => {
let maxLen = String(h || '').length;
for (let r = 0; r < Math.min(rows.length, 500); r++) {
const val = rows[r] && rows[r][i] !== undefined && rows[r][i] !== null ? String(rows[r][i]) : '';
if (val.length > maxLen) maxLen = val.length;
}
return { wch: Math.min(Math.max(maxLen + 3, 14), 45) };
});
XLSX.utils.book_append_sheet(wb, ws, sheetName.substring(0, 31));
return XLSX.write(wb, { type: 'buffer', bookType: 'xlsx' });
}
function arrayToCsv(headers, rows) {
const escapeCell = (cell) => {
if (cell === null || cell === undefined) return '';
@@ -1838,12 +1864,36 @@ function arrayToCsv(headers, rows) {
};
const headerLine = headers.map(escapeCell).join(';');
const rowLines = rows.map(r => r.map(escapeCell).join(';'));
// \uFEFF es el BOM UTF-8 y sep=;\r\n indica a Microsoft Excel el separador exacto de columnas
return '\uFEFFsep=;\r\n' + [headerLine, ...rowLines].join('\r\n');
// UTF-8 BOM puro (\uFEFF) sin "sep=;" (el sep=; provocaba que Excel cambiara la codificación a ANSI y rompiera los acentos)
return '\uFEFF' + [headerLine, ...rowLines].join('\r\n');
}
// Exportar Ventas a CSV
app.get('/api/admin/export/ventas.csv', (req, res) => {
function responderExportacion(res, req, { sheetName, filenameBase, headers, rows }) {
const isCsvRequested = req.path.endsWith('.csv');
// Si no se pide explícitamente .csv y XLSX está disponible, generar archivo nativo .xlsx
if (!isCsvRequested && XLSX) {
try {
const buf = generarExcelWorkbook(sheetName, headers, rows);
if (buf) {
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader('Content-Disposition', `attachment; filename="${filenameBase}.xlsx"`);
return res.send(buf);
}
} catch (err) {
console.error('Error generando XLSX, recurriendo a CSV:', err);
}
}
// Fallback a CSV limpio
const csvOutput = arrayToCsv(headers, rows);
res.setHeader('Content-Type', 'text/csv; charset=utf-8');
res.setHeader('Content-Disposition', `attachment; filename="${filenameBase}.csv"`);
return res.send(csvOutput);
}
// Exportar Ventas a Excel / CSV
app.get(['/api/admin/export/ventas.xlsx', '/api/admin/export/ventas.csv'], (req, res) => {
try {
const escuelaId = req.query.escuela_id ? parseInt(req.query.escuela_id, 10) : null;
let query = `
@@ -1857,12 +1907,12 @@ app.get('/api/admin/export/ventas.csv', (req, res) => {
query += ` WHERE e.escuela_id = ? `;
params.push(escuelaId);
}
query += ` ORDER BY o.id DESC LIMIT 2000`;
query += ` ORDER BY o.id DESC LIMIT 3000`;
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 rows = ordenes.map(o => {
const fechaFmt = o.creado_en ? new Date(o.creado_en).toLocaleString('es-CR') : '';
return [
fechaFmt,
@@ -1871,23 +1921,20 @@ app.get('/api/admin/export/ventas.csv', (req, res) => {
o.codigo_estudiante,
o.tipo_orden === 'preorden' ? 'Pre-orden' : 'Mostrador',
o.momento_entrega || 'Inmediato',
o.total_colones,
Number(o.total_colones || 0),
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);
const filenameBase = `ventas_sibopay_${new Date().toISOString().slice(0, 10)}`;
responderExportacion(res, req, { sheetName: 'Ventas', filenameBase, headers, rows });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Exportar Saldos de Estudiantes a CSV
app.get('/api/admin/export/estudiantes.csv', (req, res) => {
// Exportar Saldos de Estudiantes a Excel / CSV
app.get(['/api/admin/export/estudiantes.xlsx', '/api/admin/export/estudiantes.csv'], (req, res) => {
try {
const escuelaId = req.query.escuela_id ? parseInt(req.query.escuela_id, 10) : null;
let query = `
@@ -1904,16 +1951,16 @@ app.get('/api/admin/export/estudiantes.csv', (req, res) => {
}
query += ` ORDER BY e.nombre_completo ASC`;
const rows = db.prepare(query).all(...params);
const rowsDb = 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 => [
const rows = rowsDb.map(r => [
r.codigo_estudiante,
r.nombre_completo,
r.grado || '',
r.seccion || '',
r.saldo_colones || 0,
r.limite_diario_colones || 3000,
Number(r.saldo_colones || 0),
Number(r.limite_diario_colones || 3000),
r.alergias || 'Ninguna conocida',
r.bloquear_chucherias ? 'SÍ (Veto Activo)' : 'NO',
r.padre_nombre || '',
@@ -1922,18 +1969,15 @@ app.get('/api/admin/export/estudiantes.csv', (req, res) => {
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);
const filenameBase = `estudiantes_saldos_sibopay_${new Date().toISOString().slice(0, 10)}`;
responderExportacion(res, req, { sheetName: 'Saldos Estudiantes', filenameBase, headers, rows });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Exportar Recargas y Depósitos SINPE a CSV / Excel
app.get('/api/admin/export/recargas.csv', (req, res) => {
// Exportar Recargas y Depósitos SINPE a Excel / CSV
app.get(['/api/admin/export/recargas.xlsx', '/api/admin/export/recargas.csv'], (req, res) => {
try {
const escuelaId = req.query.escuela_id ? parseInt(req.query.escuela_id, 10) : null;
const { desde, hasta, estado } = req.query;
@@ -1992,12 +2036,12 @@ app.get('/api/admin/export/recargas.csv', (req, res) => {
'Notas'
];
const csvData = recargas.map(r => {
const rows = recargas.map(r => {
const fechaFmt = r.creado_en ? new Date(r.creado_en).toLocaleString('es-CR') : '';
const gradoSeccion = [r.grado, r.seccion].filter(Boolean).join(' - ') || 'N/A';
let estLabel = r.estado;
if (r.estado === 'aprobado') estLabel = 'Aprobada / Acreditada';
else if (r.estado === 'rechazado') estLabel = 'Rechazada';
if (r.estado === 'aprobada' || r.estado === 'aprobado') estLabel = 'Aprobada / Acreditada';
else if (r.estado === 'rechazada' || r.estado === 'rechazado') estLabel = 'Rechazada';
else if (r.estado === 'pendiente') estLabel = 'Pendiente de Verificación';
return [
@@ -2010,19 +2054,16 @@ app.get('/api/admin/export/recargas.csv', (req, res) => {
gradoSeccion,
r.padre_nombre || 'Padre de Familia',
r.padre_telefono || '',
r.monto_colones || 0,
Number(r.monto_colones || 0),
estLabel,
r.aprobado_por_nombre || (r.estado === 'aprobado' ? 'Sistema / Cajero' : ''),
r.aprobado_por_nombre || ((r.estado === 'aprobada' || r.estado === 'aprobado') ? 'Sistema / Cajero' : ''),
r.notas || ''
];
});
const csvOutput = arrayToCsv(headers, csvData);
const dateTag = desde ? `${desde}_a_${hasta || desde}` : new Date().toISOString().slice(0, 10);
const filename = `recargas_sinpe_sibopay_${dateTag}.csv`;
res.setHeader('Content-Type', 'text/csv; charset=utf-8');
res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
res.send(csvOutput);
const filenameBase = `recargas_sinpe_sibopay_${dateTag}`;
responderExportacion(res, req, { sheetName: 'Recargas SINPE', filenameBase, headers, rows });
} catch (err) {
res.status(500).json({ error: err.message });
}