diff --git a/public/css/styles.css b/public/css/styles.css index b5ce656..8c82089 100644 --- a/public/css/styles.css +++ b/public/css/styles.css @@ -6481,3 +6481,11 @@ body.dark-mode .danger-zone-box { color: #fda4af; } +/* Kardex Developer Responsive */ +@media (max-width: 860px) { + #devKardexMainGrid { + grid-template-columns: 1fr !important; + } +} + + diff --git a/public/index.html b/public/index.html index dec343b..a6adc6e 100644 --- a/public/index.html +++ b/public/index.html @@ -252,6 +252,10 @@ 🔍 Buscador SINPE Móvil + @@ -763,6 +767,151 @@ + + + @@ -4628,10 +4777,10 @@ - - + + - - + + diff --git a/public/js/app.js b/public/js/app.js index bd410cb..b596b90 100644 --- a/public/js/app.js +++ b/public/js/app.js @@ -622,6 +622,12 @@ function switchDevTab(tab) { if (btn) btn.classList.add('active'); if (content) content.style.display = 'block'; loadDevSinpeUniversal(); + } else if (tab === 'kardex') { + const btn = document.getElementById('btnDevTabKardex'); + const content = document.getElementById('devTabContentKardex'); + if (btn) btn.classList.add('active'); + if (content) content.style.display = 'block'; + inicializarDevKardex(); } } @@ -10831,4 +10837,491 @@ function copiarAlPortapapelesTexto(texto, btnEl) { } window.copiarAlPortapapelesTexto = copiarAlPortapapelesTexto; +// ======================================================== +// KARDEX & AUDITORÍA 360° DE ESTUDIANTES (DEVELOPER MASTER) +// ======================================================== + +let currentKardexEstudianteId = null; +let currentKardexData = null; +let currentKardexSubTab = 'compras'; +let devKardexEstudiantesList = []; + +/** + * Inicializar la pestaña de Kardex en el Panel Developer + */ +async function inicializarDevKardex() { + await poblarEscuelasKardexDev(); + await recargarListaKardexDev(); +} +window.inicializarDevKardex = inicializarDevKardex; + +async function poblarEscuelasKardexDev() { + const select = document.getElementById('devKardexEscuelaFilter'); + if (!select) return; + + const currentVal = select.value; + select.innerHTML = ''; + + try { + const res = await fetch('/api/developer/escuelas'); + if (res.ok) { + const escuelas = await res.json(); + if (Array.isArray(escuelas)) { + escuelas.forEach(esc => { + const opt = document.createElement('option'); + opt.value = esc.id; + opt.textContent = `${esc.nombre} (${esc.codigo || 'SEDE'})`; + select.appendChild(opt); + }); + } + } + } catch (e) { + console.warn('No se pudieron cargar escuelas para filtro de kardex:', e); + } + + if (currentVal) select.value = currentVal; +} + +async function recargarListaKardexDev() { + const studentListEl = document.getElementById('devKardexStudentList'); + if (studentListEl) { + studentListEl.innerHTML = '
⏳ Cargando alumnos...
'; + } + + try { + const res = await fetch('/api/developer/estudiantes/buscar'); + if (res.ok) { + const data = await res.json(); + if (Array.isArray(data)) { + devKardexEstudiantesList = data; + } + } + } catch (err) { + console.error('Error cargando estudiantes para kardex dev:', err); + } + + buscarEstudiantesKardexDev(); +} +window.recargarListaKardexDev = recargarListaKardexDev; + +/** + * Filtrar estudiantes por texto y escuela en tiempo real + */ +function buscarEstudiantesKardexDev() { + const searchInput = document.getElementById('devKardexSearchInput'); + const escuelaSelect = document.getElementById('devKardexEscuelaFilter'); + const studentListEl = document.getElementById('devKardexStudentList'); + const countBadge = document.getElementById('devKardexResultCountBadge'); + + if (!studentListEl) return; + + const normalizeStr = str => (str || '') + .normalize("NFD") + .replace(/[\u0300-\u036f]/g, "") + .toLowerCase() + .trim(); + + const query = normalizeStr(searchInput?.value || ''); + const escuelaId = escuelaSelect?.value || 'todas'; + + const filtered = devKardexEstudiantesList.filter(e => { + // Filtro por escuela + if (escuelaId !== 'todas' && String(e.escuela_id) !== String(escuelaId)) { + return false; + } + if (!query) return true; + return normalizeStr(e.nombre_completo).includes(query) || + normalizeStr(e.codigo_estudiante).includes(query) || + normalizeStr(e.padre_nombre).includes(query) || + normalizeStr(e.padre_telefono).includes(query) || + normalizeStr(e.grado).includes(query) || + normalizeStr(e.seccion).includes(query) || + normalizeStr(e.escuela_nombre).includes(query); + }); + + if (countBadge) { + countBadge.textContent = `${filtered.length} estudiante(s)`; + } + + if (filtered.length === 0) { + studentListEl.innerHTML = ` +
+ 🔍 No se encontraron alumnos con los criterios seleccionados. +
+ `; + return; + } + + studentListEl.innerHTML = filtered.map(e => { + const isSelected = String(e.id) === String(currentKardexEstudianteId); + const parts = (e.nombre_completo || 'ES').trim().split(/\s+/); + const initials = parts.length >= 2 ? (parts[0][0] + parts[1][0]).toUpperCase() : parts[0].substring(0, 2).toUpperCase(); + const saldo = Number(e.saldo_colones || 0).toLocaleString('es-CR'); + const escBadge = e.escuela_nombre ? `${escapeHtml(e.escuela_nombre)}` : ''; + + return ` +
+
+
+ ${initials} +
+
+
+ ${escapeHtml(e.nombre_completo)} +
+
+ ${e.codigo_estudiante || ''} + ${e.grado || ''} ${e.seccion ? '· ' + e.seccion : ''} + ${escBadge} +
+
+
+
+
₡${saldo}
+ Saldo +
+
+ `; + }).join(''); + + // Si no hay estudiante seleccionado o el seleccionado ya no está en la lista filtrada, seleccionar el primero + const isSelectedInList = filtered.some(e => String(e.id) === String(currentKardexEstudianteId)); + if (!isSelectedInList && filtered.length > 0) { + seleccionarEstudianteKardexDev(filtered[0].id); + } +} +window.buscarEstudiantesKardexDev = buscarEstudiantesKardexDev; + +/** + * Seleccionar un estudiante y cargar su Kardex 360° + */ +async function seleccionarEstudianteKardexDev(studentId) { + currentKardexEstudianteId = studentId; + await cargarKardexEstudianteDev(studentId); + buscarEstudiantesKardexDev(); +} +window.seleccionarEstudianteKardexDev = seleccionarEstudianteKardexDev; + +/** + * Consultar datos del endpoint y poblar la vista + */ +async function cargarKardexEstudianteDev(studentId) { + const placeholder = document.getElementById('devKardexPlaceholder'); + const studentView = document.getElementById('devKardexStudentView'); + + if (placeholder) placeholder.style.display = 'none'; + if (studentView) studentView.style.display = 'block'; + + try { + const res = await fetch(`/api/developer/estudiantes/${studentId}/kardex`); + if (!res.ok) throw new Error('No se pudo obtener el kardex del estudiante'); + const data = await res.json(); + currentKardexData = data; + + const est = data.estudiante || {}; + const totales = data.totales || {}; + + // 1. Cabecera Ficha Técnica + const avatar = document.getElementById('devKardexAvatar'); + const carnet = document.getElementById('devKardexBadgeCarnet'); + const escuela = document.getElementById('devKardexBadgeEscuela'); + const nombre = document.getElementById('devKardexNombre'); + const gradoSeccion = document.getElementById('devKardexGradoSeccion'); + const padreInfo = document.getElementById('devKardexPadreInfo'); + + const parts = (est.nombre_completo || 'ES').trim().split(/\s+/); + const initials = parts.length >= 2 ? (parts[0][0] + parts[1][0]).toUpperCase() : parts[0].substring(0, 2).toUpperCase(); + if (avatar) avatar.textContent = initials; + + if (carnet) carnet.textContent = est.codigo_estudiante || `ID #${est.id}`; + if (escuela) escuela.textContent = est.escuela_nombre || 'Sede'; + if (nombre) nombre.textContent = est.nombre_completo; + if (gradoSeccion) gradoSeccion.textContent = `${est.grado || 'Estudiante'} ${est.seccion ? '· Sección ' + est.seccion : ''}`; + + if (padreInfo) { + const tel = est.padre_telefono ? ` · Tel: ${est.padre_telefono}` : ''; + padreInfo.textContent = `Encargado: ${est.padre_nombre || 'N/A'}${tel}`; + } + + // 2. KPIs + const kpiSaldo = document.getElementById('devKardexKpiSaldoActual'); + const kpiRecargas = document.getElementById('devKardexKpiTotalRecargas'); + const kpiCantRecargas = document.getElementById('devKardexKpiCantRecargas'); + const kpiCompras = document.getElementById('devKardexKpiTotalCompras'); + const kpiCantCompras = document.getElementById('devKardexKpiCantCompras'); + const kpiLimite = document.getElementById('devKardexKpiLimiteDiario'); + + if (kpiSaldo) kpiSaldo.textContent = `₡${Number(totales.saldo_actual || 0).toLocaleString('es-CR')}`; + if (kpiRecargas) kpiRecargas.textContent = `₡${Number(totales.total_recargas || 0).toLocaleString('es-CR')}`; + if (kpiCantRecargas) kpiCantRecargas.textContent = `${totales.cant_recargas || 0} recargas`; + if (kpiCompras) kpiCompras.textContent = `₡${Number(totales.total_compras || 0).toLocaleString('es-CR')}`; + if (kpiCantCompras) kpiCantCompras.textContent = `${totales.cant_compras || 0} compras`; + if (kpiLimite) kpiLimite.textContent = `₡${Number(est.limite_diario_colones || 0).toLocaleString('es-CR')}`; + + // 3. Contadores en pestañas + const badgeCompras = document.getElementById('devKardexBadgeTabComprasCount'); + const badgeRecargas = document.getElementById('devKardexBadgeTabRecargasCount'); + const badgeMov = document.getElementById('devKardexBadgeTabMovimientosCount'); + + if (badgeCompras) badgeCompras.textContent = data.compras ? data.compras.length : 0; + if (badgeRecargas) badgeRecargas.textContent = data.recargas ? data.recargas.length : 0; + if (badgeMov) badgeMov.textContent = data.movimientos ? data.movimientos.length : 0; + + // 4. Renderizar la subvista activa + renderizarSubVistaKardexDev(currentKardexSubTab); + } catch (err) { + console.error('Error cargando kardex del estudiante:', err); + if (studentView) { + studentView.innerHTML = ` +
+ ⚠️ Error al consultar el Kardex del estudiante: ${err.message} +
+ `; + } + } +} +window.cargarKardexEstudianteDev = cargarKardexEstudianteDev; + +/** + * Cambiar entre sub-pestañas: 'compras', 'recargas', 'movimientos' + */ +function cambiarSubTabKardexDev(subTab) { + currentKardexSubTab = subTab; + + const btnCompras = document.getElementById('btnDevKardexTabCompras'); + const btnRecargas = document.getElementById('btnDevKardexTabRecargas'); + const btnMov = document.getElementById('btnDevKardexTabMovimientos'); + + const viewCompras = document.getElementById('devKardexSubViewCompras'); + const viewRecargas = document.getElementById('devKardexSubViewRecargas'); + const viewMov = document.getElementById('devKardexSubViewMovimientos'); + + // Clases botones + if (btnCompras) { + btnCompras.className = `dev-action-btn ${subTab === 'compras' ? 'dev-action-btn-primary' : 'dev-action-btn-outline'}`; + } + if (btnRecargas) { + btnRecargas.className = `dev-action-btn ${subTab === 'recargas' ? 'dev-action-btn-primary' : 'dev-action-btn-outline'}`; + } + if (btnMov) { + btnMov.className = `dev-action-btn ${subTab === 'movimientos' ? 'dev-action-btn-primary' : 'dev-action-btn-outline'}`; + } + + // Visibilidad vistas + if (viewCompras) viewCompras.style.display = subTab === 'compras' ? 'block' : 'none'; + if (viewRecargas) viewRecargas.style.display = subTab === 'recargas' ? 'block' : 'none'; + if (viewMov) viewMov.style.display = subTab === 'movimientos' ? 'block' : 'none'; + + renderizarSubVistaKardexDev(subTab); +} +window.cambiarSubTabKardexDev = cambiarSubTabKardexDev; + +/** + * Renderizar la sub-vista seleccionada con datos + */ +function renderizarSubVistaKardexDev(subTab) { + if (!currentKardexData) return; + + if (subTab === 'compras') { + const container = document.getElementById('devKardexSubViewCompras'); + if (!container) return; + + const compras = currentKardexData.compras || []; + if (compras.length === 0) { + container.innerHTML = ` +
+ 🛒 Este estudiante aún no registra compras de soda ni meriendas. +
+ `; + return; + } + + container.innerHTML = ` +
+ ${compras.map(o => { + const fecha = o.creado_en ? new Date(o.creado_en).toLocaleString('es-CR', { month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit' }) : 'Fecha N/A'; + const items = Array.isArray(o.items) ? o.items : []; + const isCancelado = o.estado === 'cancelado'; + const total = Number(o.total_colones || 0).toLocaleString('es-CR'); + + let estadoBadge = `✓ ${o.estado || 'Entregado'}`; + if (isCancelado) { + estadoBadge = `✕ Cancelado`; + } else if (o.estado === 'pendiente' || o.estado === 'en_preparacion') { + estadoBadge = `⏳ ${o.estado}`; + } + + return ` +
+
+
+
+ #${o.codigo_orden || 'ORD-' + o.id} + ${estadoBadge} + ${o.tipo_orden === 'preorden' ? 'Preorden Recreo' : 'Caja Mostrador'} +
+
+ 📅 ${fecha} ${o.momento_entrega_label ? `· ⏰ ${o.momento_entrega_label}` : ''} +
+
+
+
+ ₡${total} +
+ Total de la compra +
+
+ + +
+
+ Productos Adquiridos: +
+
+ ${items.map(it => ` +
+
+ ${it.icono || '🥪'} + ${it.cantidad}x ${escapeHtml(it.nombre || 'Producto')} +
+ + ₡${Number(it.precio_unitario || 0).toLocaleString('es-CR')} c/u = ₡${Number(it.subtotal || 0).toLocaleString('es-CR')} + +
+ `).join('')} +
+
+
+ `; + }).join('')} +
+ `; + } else if (subTab === 'recargas') { + const container = document.getElementById('devKardexSubViewRecargas'); + if (!container) return; + + const recargas = currentKardexData.recargas || []; + if (recargas.length === 0) { + container.innerHTML = ` +
+ ⚡ Este estudiante aún no registra recargas de saldo. +
+ `; + return; + } + + container.innerHTML = ` +
+ ${recargas.map(r => { + const fecha = r.fecha ? new Date(r.fecha).toLocaleString('es-CR', { month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit' }) : 'Fecha N/A'; + const isSinpe = r.tipo === 'recarga_sinpe'; + const monto = Number(r.monto_colones || 0).toLocaleString('es-CR'); + const saldoPrev = Number(r.saldo_previo || 0).toLocaleString('es-CR'); + const saldoPost = Number(r.saldo_posterior || 0).toLocaleString('es-CR'); + + return ` +
+
+
+
+ + ${isSinpe ? '📲 Recarga SINPE Móvil' : '💵 Recarga en Caja'} + + ${r.comprobante_sinpe ? `Ref #${r.comprobante_sinpe}` : ''} +
+
+ 📅 ${fecha} +
+
+ ${escapeHtml(r.descripcion || 'Recarga de monedero')} +
+
+
+
+ +₡${monto} +
+ Acreditado a cuenta +
+
+ + +
+ Saldo antes: ₡${saldoPrev} + ➔ + Saldo resultante: ₡${saldoPost} +
+
+ `; + }).join('')} +
+ `; + } else if (subTab === 'movimientos') { + const container = document.getElementById('devKardexSubViewMovimientos'); + if (!container) return; + + const movimientos = currentKardexData.movimientos || []; + if (movimientos.length === 0) { + container.innerHTML = ` +
+ 📊 Este estudiante aún no registra movimientos en el sistema. +
+ `; + return; + } + + container.innerHTML = ` +
+ + + + + + + + + + + + + ${movimientos.map(m => { + const fecha = m.fecha ? new Date(m.fecha).toLocaleString('es-CR', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }) : ''; + const esIngreso = Number(m.monto_colones) > 0; + const montoSigno = esIngreso ? `+₡${Number(m.monto_colones).toLocaleString('es-CR')}` : `-₡${Math.abs(Number(m.monto_colones)).toLocaleString('es-CR')}`; + const montoColor = esIngreso ? '#10b981' : '#ef4444'; + + return ` + + + + + + + + + `; + }).join('')} + +
Fecha / HoraTipoDescripción & ReferenciaSaldo PrevioMovimientoSaldo Posterior
${fecha} + + ${m.tipo} + + +
${escapeHtml(m.descripcion || '')}
+ ${m.comprobante_sinpe ? `Ref #${m.comprobante_sinpe}` : ''} + ${m.codigo_orden ? `#${m.codigo_orden}` : ''} +
₡${Number(m.saldo_previo || 0).toLocaleString('es-CR')}${montoSigno}₡${Number(m.saldo_posterior || 0).toLocaleString('es-CR')}
+
+ `; + } +} + +function abrirCarnetEstudianteDesdeDev() { + if (currentKardexData && currentKardexData.estudiante && currentKardexData.estudiante.codigo_estudiante) { + window.open(`/carnet.html?carnet=${encodeURIComponent(currentKardexData.estudiante.codigo_estudiante)}`, '_blank'); + } else { + alert('No hay código de carné disponible para este estudiante.'); + } +} +window.abrirCarnetEstudianteDesdeDev = abrirCarnetEstudianteDesdeDev; + diff --git a/public/sw.js b/public/sw.js index cbc961c..1c6b4b1 100644 --- a/public/sw.js +++ b/public/sw.js @@ -1,5 +1,5 @@ -// SiboPay PWA Service Worker v19.2 - Ultra Fast Startup & Stale-While-Revalidate -const CACHE_NAME = 'sibopay-v19.2'; +// SiboPay PWA Service Worker v19.3 - Ultra Fast Startup & Stale-While-Revalidate +const CACHE_NAME = 'sibopay-v19.3'; const STATIC_ASSETS = [ '/', '/index.html', @@ -8,13 +8,13 @@ const STATIC_ASSETS = [ '/pistola.html', '/carnet.html', '/manifest.json', - '/css/styles.css?v=19.1', + '/css/styles.css?v=19.3', '/css/desktop.css?v=2.2', - '/js/dialogs.js?v=19.2', - '/js/app.js?v=19.2', + '/js/dialogs.js?v=19.3', + '/js/app.js?v=19.3', '/js/pos.js', - '/js/sounds.js?v=19.2', - '/js/food-icons.js?v=19.2', + '/js/sounds.js?v=19.3', + '/js/food-icons.js?v=19.3', '/icons/icon-192.png', '/icons/icon-512.png', '/img/sibopay-emblem.png', diff --git a/server/server.js b/server/server.js index f88b945..a0038d0 100644 --- a/server/server.js +++ b/server/server.js @@ -2457,6 +2457,83 @@ app.get(['/api/admin/estudiantes', '/api/developer/estudiantes/buscar'], (req, r } }); +// 0.1 Kardex 360° Integral de Estudiante (Developer) +app.get('/api/developer/estudiantes/:id/kardex', (req, res) => { + try { + const estId = parseInt(req.params.id, 10); + const est = db.prepare(` + SELECT e.*, esc.nombre as escuela_nombre, esc.codigo as escuela_codigo + FROM estudiantes e + LEFT JOIN escuelas esc ON esc.id = e.escuela_id + WHERE e.id = ? + `).get(estId); + + if (!est) return res.status(404).json({ error: 'Estudiante no encontrado' }); + + // 1. Movimientos contables (Kardex completo de transacciones_saldo) + const movimientos = db.prepare(` + SELECT ts.*, o.codigo_orden + FROM transacciones_saldo ts + LEFT JOIN ordenes o ON ts.orden_id = o.id + WHERE ts.estudiante_id = ? + ORDER BY ts.fecha DESC, ts.id DESC + LIMIT 200 + `).all(estId); + + // 2. Compras en soda (con desglose de productos) + const ordenesRaw = db.prepare(` + SELECT o.*, + (SELECT json_group_array(json_object('producto_id', d.producto_id, 'nombre', COALESCE(d.nombre_producto, p.nombre), 'icono', COALESCE(p.icono, '🥪'), 'cantidad', d.cantidad, 'precio_unitario', d.precio_unitario, 'subtotal', d.subtotal)) + FROM orden_detalles d LEFT JOIN productos p ON d.producto_id = p.id WHERE d.orden_id = o.id) as items_json + FROM ordenes o + WHERE o.estudiante_id = ? + ORDER BY o.creado_en DESC, o.id DESC + LIMIT 100 + `).all(estId); + + const compras = ordenesRaw.map(o => ({ + ...o, + momento_entrega_label: formatMomentoLabel(o.momento_entrega, o.escuela_id || est.escuela_id || 1), + items: Array.isArray(o.items_json) + ? o.items_json + : (typeof o.items_json === 'string' ? JSON.parse(o.items_json || '[]') : []) + })); + + // 3. Recargas específicas + const recargas = movimientos.filter(m => m.tipo && (m.tipo.startsWith('recarga') || m.tipo === 'recarga_sinpe' || m.tipo === 'recarga_manual')); + + // 4. Totales / KPIs históricos + const totalRecargasRow = db.prepare(` + SELECT COALESCE(SUM(monto_colones), 0) as total, COUNT(*) as cant + FROM transacciones_saldo + WHERE estudiante_id = ? AND tipo IN ('recarga_sinpe', 'recarga_manual') AND monto_colones > 0 AND (revertida IS NULL OR revertida = 0) + `).get(estId) || { total: 0, cant: 0 }; + + const totalComprasRow = db.prepare(` + SELECT COALESCE(SUM(ABS(monto_colones)), 0) as total, COUNT(*) as cant + FROM transacciones_saldo + WHERE estudiante_id = ? AND monto_colones < 0 AND (revertida IS NULL OR revertida = 0) + `).get(estId) || { total: 0, cant: 0 }; + + res.json({ + estudiante: est, + totales: { + saldo_actual: est.saldo_colones || 0, + total_recargas: Number(totalRecargasRow.total || 0), + cant_recargas: Number(totalRecargasRow.cant || 0), + total_compras: Number(totalComprasRow.total || 0), + cant_compras: Number(totalComprasRow.cant || 0) + }, + compras, + recargas, + movimientos + }); + } catch (error) { + console.error('Error en /api/developer/estudiantes/:id/kardex:', error); + res.status(500).json({ error: error.message }); + } +}); + // 1. Buscador universal multicriterio app.get('/api/developer/sinpe/buscar', (req, res) => { try {