feat: configuracion de horarios escolares admin, reporte excel recargas sinpe y remocion enlaces footer
This commit is contained in:
+75
-6
@@ -118,9 +118,15 @@ function initDatabase() {
|
||||
nombre_sinpe VARCHAR(150) DEFAULT 'Soda Central',
|
||||
concesionario VARCHAR(150),
|
||||
activo BOOLEAN DEFAULT TRUE,
|
||||
hora_recreo_1 VARCHAR(20) DEFAULT '09:30',
|
||||
hora_almuerzo VARCHAR(20) DEFAULT '11:45',
|
||||
hora_recreo_2 VARCHAR(20) DEFAULT '13:45',
|
||||
creado_en TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
`);
|
||||
try { db.exec("ALTER TABLE escuelas ADD COLUMN IF NOT EXISTS hora_recreo_1 VARCHAR(20) DEFAULT '09:30';"); } catch (_) {}
|
||||
try { db.exec("ALTER TABLE escuelas ADD COLUMN IF NOT EXISTS hora_almuerzo VARCHAR(20) DEFAULT '11:45';"); } catch (_) {}
|
||||
try { db.exec("ALTER TABLE escuelas ADD COLUMN IF NOT EXISTS hora_recreo_2 VARCHAR(20) DEFAULT '13:45';"); } catch (_) {}
|
||||
} catch (e) {}
|
||||
|
||||
try {
|
||||
@@ -312,6 +318,9 @@ function initDatabase() {
|
||||
try { db.exec('ALTER TABLE usuarios ADD COLUMN activo INTEGER DEFAULT 1'); } catch (e) {}
|
||||
try { db.exec('UPDATE usuarios SET activo = 1 WHERE activo IS NULL'); } catch (e) {}
|
||||
try { db.exec("UPDATE ordenes SET estado = 'cancelado' WHERE estado = 'expirado'"); } catch (e) {}
|
||||
try { db.exec("ALTER TABLE escuelas ADD COLUMN hora_recreo_1 TEXT DEFAULT '09:30'"); } catch (e) {}
|
||||
try { db.exec("ALTER TABLE escuelas ADD COLUMN hora_almuerzo TEXT DEFAULT '11:45'"); } catch (e) {}
|
||||
try { db.exec("ALTER TABLE escuelas ADD COLUMN hora_recreo_2 TEXT DEFAULT '13:45'"); } catch (e) {}
|
||||
|
||||
// 8. Relación N:M Padres - Estudiantes
|
||||
try {
|
||||
@@ -812,16 +821,73 @@ function recargaSaldoTransaction({ estudianteId, monto, comprobanteSinpe, descri
|
||||
return transaction();
|
||||
}
|
||||
|
||||
function formatTime12h(timeStr) {
|
||||
if (!timeStr) return '';
|
||||
const parts = String(timeStr).split(':');
|
||||
let h = parseInt(parts[0], 10);
|
||||
const m = parts[1] || '00';
|
||||
if (isNaN(h)) return timeStr;
|
||||
const ampm = h >= 12 ? 'PM' : 'AM';
|
||||
h = h % 12;
|
||||
if (h === 0) h = 12;
|
||||
return `${h}:${m} ${ampm}`;
|
||||
}
|
||||
|
||||
function obtenerHorariosEscuela(escuelaId = 1) {
|
||||
try {
|
||||
const row = db.prepare('SELECT id, codigo, nombre, hora_recreo_1, hora_almuerzo, hora_recreo_2 FROM escuelas WHERE id = ?').get(escuelaId || 1);
|
||||
if (row) {
|
||||
return {
|
||||
id: row.id,
|
||||
nombre: row.nombre,
|
||||
hora_recreo_1: row.hora_recreo_1 || '09:30',
|
||||
hora_almuerzo: row.hora_almuerzo || '11:45',
|
||||
hora_recreo_2: row.hora_recreo_2 || '13:45',
|
||||
hora_recreo_1_fmt: formatTime12h(row.hora_recreo_1 || '09:30'),
|
||||
hora_almuerzo_fmt: formatTime12h(row.hora_almuerzo || '11:45'),
|
||||
hora_recreo_2_fmt: formatTime12h(row.hora_recreo_2 || '13:45')
|
||||
};
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error obteniendo horarios escuela:', e);
|
||||
}
|
||||
return {
|
||||
id: 1,
|
||||
nombre: 'Soda Escolar Central',
|
||||
hora_recreo_1: '09:30',
|
||||
hora_almuerzo: '11:45',
|
||||
hora_recreo_2: '13:45',
|
||||
hora_recreo_1_fmt: '9:30 AM',
|
||||
hora_almuerzo_fmt: '11:45 AM',
|
||||
hora_recreo_2_fmt: '1:45 PM'
|
||||
};
|
||||
}
|
||||
|
||||
function actualizarHorariosEscuela(escuelaId = 1, { hora_recreo_1, hora_almuerzo, hora_recreo_2 }) {
|
||||
const r1 = hora_recreo_1 || '09:30';
|
||||
const alm = hora_almuerzo || '11:45';
|
||||
const r2 = hora_recreo_2 || '13:45';
|
||||
|
||||
db.prepare(`
|
||||
UPDATE escuelas
|
||||
SET hora_recreo_1 = ?, hora_almuerzo = ?, hora_recreo_2 = ?
|
||||
WHERE id = ?
|
||||
`).run(r1, alm, r2, escuelaId || 1);
|
||||
|
||||
return obtenerHorariosEscuela(escuelaId || 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Traduce y estandariza el código o texto de momento de entrega a una etiqueta humana amigable
|
||||
*/
|
||||
function formatMomentoLabel(momento) {
|
||||
function formatMomentoLabel(momento, escuelaId = 1) {
|
||||
const m = String(momento || '').toLowerCase().trim();
|
||||
if (m === 'recreo_1' || m.includes('1er') || m.includes('9:30')) return '1er Recreo (9:30 AM)';
|
||||
if (m === 'almuerzo' || m.includes('almuerzo') || m.includes('11:45')) return 'Almuerzo (11:45 AM)';
|
||||
if (m === 'recreo_2' || m.includes('2do') || m.includes('1:45')) return '2do Recreo (1:45 PM)';
|
||||
const horarios = obtenerHorariosEscuela(escuelaId);
|
||||
if (m === 'recreo_1' || m.includes('1er') || m.includes('9:30')) return `1er Recreo (${horarios.hora_recreo_1_fmt})`;
|
||||
if (m === 'almuerzo' || m.includes('almuerzo') || m.includes('11:45')) return `Almuerzo (${horarios.hora_almuerzo_fmt})`;
|
||||
if (m === 'recreo_2' || m.includes('2do') || m.includes('1:45')) return `2do Recreo (${horarios.hora_recreo_2_fmt})`;
|
||||
if (m === 'inmediato' || m.includes('inmediato')) return 'Entrega Inmediata';
|
||||
return momento || '1er Recreo (9:30 AM)';
|
||||
return momento || `1er Recreo (${horarios.hora_recreo_1_fmt})`;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1807,5 +1873,8 @@ module.exports = {
|
||||
expirarPreordenesVencidas,
|
||||
cancelarPreorden,
|
||||
despacharPreordenTransaction,
|
||||
enriquecerEstudianteFinanzas
|
||||
enriquecerEstudianteFinanzas,
|
||||
obtenerHorariosEscuela,
|
||||
actualizarHorariosEscuela,
|
||||
formatTime12h
|
||||
};
|
||||
|
||||
+135
-1
@@ -32,7 +32,10 @@ const {
|
||||
expirarPreordenesVencidas,
|
||||
cancelarPreorden,
|
||||
despacharPreordenTransaction,
|
||||
enriquecerEstudianteFinanzas
|
||||
enriquecerEstudianteFinanzas,
|
||||
obtenerHorariosEscuela,
|
||||
actualizarHorariosEscuela,
|
||||
formatTime12h
|
||||
} = require('./db');
|
||||
const { checkSinpeEmailsOnce, simularSinpeEmail } = require('./sinpeImapService');
|
||||
const { normalizarCodigoDetalle, parseSinpeEmail } = require('./sinpeParser');
|
||||
@@ -1928,6 +1931,137 @@ app.get('/api/admin/export/estudiantes.csv', (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Exportar Recargas y Depósitos SINPE a CSV / Excel
|
||||
app.get('/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;
|
||||
|
||||
let query = `
|
||||
SELECT s.id, s.creado_en, s.comprobante_sinpe, s.codigo_detalle, s.monto_colones, s.estado, s.notas,
|
||||
e.codigo_estudiante, e.nombre_completo as estudiante_nombre, e.grado, e.seccion,
|
||||
COALESCE(u.nombre, e.padre_nombre) as padre_nombre,
|
||||
COALESCE(u.telefono, e.padre_telefono) as padre_telefono,
|
||||
u_aprob.nombre as aprobado_por_nombre
|
||||
FROM solicitudes_recarga_sinpe s
|
||||
JOIN estudiantes e ON s.estudiante_id = e.id
|
||||
LEFT JOIN usuarios u ON s.padre_usuario_id = u.id
|
||||
LEFT JOIN usuarios u_aprob ON s.aprobado_por_usuario_id = u_aprob.id
|
||||
WHERE 1=1
|
||||
`;
|
||||
const params = [];
|
||||
|
||||
if (escuelaId) {
|
||||
query += ` AND (s.escuela_id = ? OR s.escuela_id IS NULL) `;
|
||||
params.push(escuelaId);
|
||||
}
|
||||
|
||||
if (desde && desde.trim()) {
|
||||
query += ` AND s.creado_en >= ? `;
|
||||
params.push(`${desde.trim()} 00:00:00`);
|
||||
}
|
||||
|
||||
if (hasta && hasta.trim()) {
|
||||
query += ` AND s.creado_en <= ? `;
|
||||
params.push(`${hasta.trim()} 23:59:59`);
|
||||
}
|
||||
|
||||
if (estado && estado.trim() && estado.trim() !== 'todos') {
|
||||
query += ` AND s.estado = ? `;
|
||||
params.push(estado.trim());
|
||||
}
|
||||
|
||||
query += ` ORDER BY s.id DESC LIMIT 5000`;
|
||||
|
||||
const recargas = db.prepare(query).all(...params);
|
||||
|
||||
const headers = [
|
||||
'ID Solicitud',
|
||||
'Fecha y Hora',
|
||||
'Comprobante SINPE',
|
||||
'Código Verificación',
|
||||
'Estudiante',
|
||||
'Carné Estudiante',
|
||||
'Grado y Sección',
|
||||
'Padre / Tutor',
|
||||
'Teléfono Padre',
|
||||
'Monto (CRC)',
|
||||
'Estado',
|
||||
'Verificado Por',
|
||||
'Notas'
|
||||
];
|
||||
|
||||
const csvData = 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';
|
||||
else if (r.estado === 'pendiente') estLabel = 'Pendiente de Verificación';
|
||||
|
||||
return [
|
||||
r.id,
|
||||
fechaFmt,
|
||||
r.comprobante_sinpe || '',
|
||||
r.codigo_detalle || '',
|
||||
r.estudiante_nombre || '',
|
||||
r.codigo_estudiante || '',
|
||||
gradoSeccion,
|
||||
r.padre_nombre || 'Padre de Familia',
|
||||
r.padre_telefono || '',
|
||||
r.monto_colones || 0,
|
||||
estLabel,
|
||||
r.aprobado_por_nombre || (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);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Obtener Horarios de Recreos y Almuerzo de la Escuela
|
||||
app.get('/api/escuela/horarios', (req, res) => {
|
||||
try {
|
||||
const escuelaId = req.query.escuela_id ? parseInt(req.query.escuela_id, 10) : 1;
|
||||
const horarios = obtenerHorariosEscuela(escuelaId);
|
||||
res.json({ success: true, horarios });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Modificar Horarios de Recreos y Almuerzo de la Escuela (Admin)
|
||||
app.put('/api/admin/escuela/horarios', (req, res) => {
|
||||
try {
|
||||
const { escuela_id, hora_recreo_1, hora_almuerzo, hora_recreo_2 } = req.body;
|
||||
const escuelaId = escuela_id ? parseInt(escuela_id, 10) : 1;
|
||||
const actualizados = actualizarHorariosEscuela(escuelaId, {
|
||||
hora_recreo_1,
|
||||
hora_almuerzo,
|
||||
hora_recreo_2
|
||||
});
|
||||
|
||||
// Notificar en tiempo real por SSE
|
||||
broadcastEvent('horarios_actualizados', actualizados);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Horarios escolares actualizados correctamente',
|
||||
horarios: actualizados
|
||||
});
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// ==========================================
|
||||
// 1. ESTUDIANTES Y QR
|
||||
// ==========================================
|
||||
|
||||
Reference in New Issue
Block a user