feat(padres): agregar dashboard ejecutivo familiar con metricas de saldo, compras y recargas, filtro de hijos y exportacion Excel
This commit is contained in:
+138
-10
@@ -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.9">
|
||||
<link rel="stylesheet" href="/css/styles.css?v=14.0">
|
||||
<link rel="stylesheet" href="/css/desktop.css?v=2.2">
|
||||
<style>
|
||||
/* Transiciones suaves */
|
||||
@@ -630,14 +630,6 @@
|
||||
<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>
|
||||
</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>
|
||||
</header>
|
||||
|
||||
@@ -1377,6 +1369,15 @@
|
||||
</div>
|
||||
<span class="parent-nav-arrow" style="color: #16a34a;">›</span>
|
||||
</div>
|
||||
|
||||
<div class="parent-nav-box" data-view="dashboard" onclick="openParentSubView('dashboard')">
|
||||
<div class="parent-nav-box-icon" style="background: rgba(2, 132, 199, 0.12); color: #0284c7;">📊</div>
|
||||
<div class="parent-nav-box-text">
|
||||
<strong style="color: #0284c7;">Dashboard Ejecutivo</strong>
|
||||
<span>Saldos, compras y recargas</span>
|
||||
</div>
|
||||
<span class="parent-nav-arrow" style="color: #0284c7;">›</span>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- COLUMNA DERECHA: ESCENARIO DE CONTENIDO ACTIVO -->
|
||||
@@ -1951,6 +1952,133 @@
|
||||
<span>Guardar Nuevas Credenciales</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- SUBVISTA: DASHBOARD EJECUTIVO FAMILIAR -->
|
||||
<div id="parentSubViewDashboard" class="parent-subview" style="display: none;">
|
||||
<div class="parent-subview-header">
|
||||
<button type="button" onclick="closeParentSubView()" class="parent-subview-back-btn">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg>
|
||||
<span>Volver</span>
|
||||
</button>
|
||||
<div style="display: flex; align-items: center; gap: 8px;">
|
||||
<span style="font-size: 1.1rem;">📊</span>
|
||||
<strong style="font-size: 0.92rem; color: var(--text-main);">Dashboard Ejecutivo Familiar</strong>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="parent-card" style="background: var(--card-bg, #ffffff); border: 1px solid var(--border, #e2e8f0); border-radius: 18px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.03);">
|
||||
<!-- BARRA DE CONTROLES: FILTRO DE HIJO, PERÍODO Y ACTUALIZAR -->
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 12px; margin-bottom: 16px; padding-bottom: 14px; border-bottom: 1px solid var(--border, #e2e8f0);">
|
||||
<div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
|
||||
<div>
|
||||
<label for="parentDashChildFilter" style="display: block; font-size: 0.72rem; font-weight: 800; color: var(--text-muted); text-transform: uppercase; margin-bottom: 3px;">Estudiante:</label>
|
||||
<select id="parentDashChildFilter" onchange="cambiarHijoDashboardPadres(this.value)" style="padding: 6px 12px; border-radius: 9px; border: 1.5px solid var(--border); background: var(--bg-main); color: var(--text-main); font-size: 0.82rem; font-weight: 800; outline: none; cursor: pointer;">
|
||||
<option value="todos">👨👩👧👦 Todos mis hijos (Consolidado)</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label style="display: block; font-size: 0.72rem; font-weight: 800; color: var(--text-muted); text-transform: uppercase; margin-bottom: 3px;">Período:</label>
|
||||
<div class="admin-dash-period-pills" id="parentDashPeriodPills">
|
||||
<button type="button" class="admin-dash-pill-btn active" data-periodo="mes" onclick="cambiarPeriodoDashboardPadres('mes')">Este Mes</button>
|
||||
<button type="button" class="admin-dash-pill-btn" data-periodo="30dias" onclick="cambiarPeriodoDashboardPadres('30dias')">30 Días</button>
|
||||
<button type="button" class="admin-dash-pill-btn" data-periodo="hoy" onclick="cambiarPeriodoDashboardPadres('hoy')">Hoy</button>
|
||||
<button type="button" class="admin-dash-pill-btn" data-periodo="todo" onclick="cambiarPeriodoDashboardPadres('todo')">Histórico</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button type="button" onclick="cargarDashboardPadres()" class="btn-saas btn-saas-outline" style="height: 32px; padding: 0 10px; font-size: 0.76rem;" title="Recargar datos">
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"/><path d="M16 21h5v-5"/></svg>
|
||||
<span>Actualizar</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- CUADRÍCULA DE 4 TARJETAS KPI EJECUTIVAS -->
|
||||
<div class="admin-dash-grid" style="margin-bottom: 18px;">
|
||||
<!-- KPI 1: SALDO DISPONIBLE -->
|
||||
<div class="admin-dash-kpi-card kpi-blue">
|
||||
<div class="admin-dash-kpi-header">
|
||||
<span class="admin-dash-kpi-title">Saldo Disponible</span>
|
||||
<div class="admin-dash-kpi-icon">💳</div>
|
||||
</div>
|
||||
<div class="admin-dash-kpi-val" id="parentDashKpiSaldo">₡0</div>
|
||||
<div class="admin-dash-kpi-meta">
|
||||
<span id="parentDashKpiSaldoMeta">Retenido preórdenes: <strong>₡0</strong></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- KPI 2: TOTAL RECARGADO -->
|
||||
<div class="admin-dash-kpi-card kpi-purple">
|
||||
<div class="admin-dash-kpi-header">
|
||||
<span class="admin-dash-kpi-title">Recargas del Período</span>
|
||||
<div class="admin-dash-kpi-icon">📥</div>
|
||||
</div>
|
||||
<div class="admin-dash-kpi-val" id="parentDashKpiRecargas">₡0</div>
|
||||
<div class="admin-dash-kpi-meta">
|
||||
<span id="parentDashKpiRecargasMeta">SINPE Móvil: <strong>₡0 (0 recargas)</strong></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- KPI 3: CONSUMO / COMPRAS -->
|
||||
<div class="admin-dash-kpi-card kpi-green">
|
||||
<div class="admin-dash-kpi-header">
|
||||
<span class="admin-dash-kpi-title">Compras en la Soda</span>
|
||||
<div class="admin-dash-kpi-icon">🥪</div>
|
||||
</div>
|
||||
<div class="admin-dash-kpi-val" id="parentDashKpiCompras">₡0</div>
|
||||
<div class="admin-dash-kpi-meta">
|
||||
<span id="parentDashKpiComprasMeta">0 compras despachadas</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- KPI 4: PROMEDIO POR COMPRA -->
|
||||
<div class="admin-dash-kpi-card kpi-amber">
|
||||
<div class="admin-dash-kpi-header">
|
||||
<span class="admin-dash-kpi-title">Promedio de Compra</span>
|
||||
<div class="admin-dash-kpi-icon">📊</div>
|
||||
</div>
|
||||
<div class="admin-dash-kpi-val" id="parentDashKpiTicket">₡0</div>
|
||||
<div class="admin-dash-kpi-meta">
|
||||
<span id="parentDashKpiTicketMeta">Ticket promedio por orden</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- SECCIÓN 2 COLUMNAS: TOP PRODUCTOS CONSUMIDOS Y MOVIMIENTOS RECIENTES -->
|
||||
<div class="admin-dash-split" style="margin-bottom: 18px;">
|
||||
<!-- COLUMNA 1: TOP MERIENDAS CONSUMIDAS -->
|
||||
<div class="admin-dash-section">
|
||||
<div class="admin-dash-section-title">
|
||||
<span>🏆 Meriendas Más Consumidas</span>
|
||||
<span style="font-size: 0.72rem; color: var(--text-muted); font-weight: 600;">Unidades & Monto</span>
|
||||
</div>
|
||||
<div id="parentDashTopProductosList" style="display: flex; flex-direction: column; gap: 10px;">
|
||||
<!-- Dinámico -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- COLUMNA 2: ÚLTIMOS MOVIMIENTOS -->
|
||||
<div class="admin-dash-section">
|
||||
<div class="admin-dash-section-title">
|
||||
<span>📜 Movimientos Recientes</span>
|
||||
<span style="font-size: 0.72rem; color: var(--text-muted); font-weight: 600;">Compras & Recargas</span>
|
||||
</div>
|
||||
<div id="parentDashMovimientosList" style="display: flex; flex-direction: column; gap: 8px; max-height: 280px; overflow-y: auto;">
|
||||
<!-- Dinámico -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- BOTÓN EXPORTAR EXCEL ESTADO DE CUENTA -->
|
||||
<div style="display: flex; justify-content: flex-end; padding-top: 12px; border-top: 1px solid var(--border, #e2e8f0);">
|
||||
<button type="button" onclick="descargarEstadoCuentaPadresExcel()" class="btn-saas btn-saas-outline" style="height: 36px; border-color: #10b981; color: #166534; font-size: 0.82rem; font-weight: 800;">
|
||||
<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="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>Descargar Estado de Cuenta (Excel XLSX)</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
@@ -3585,6 +3713,6 @@
|
||||
<script src="/js/sounds.js?v=13.8"></script>
|
||||
<script src="/js/jsQR.js"></script>
|
||||
<script src="/js/food-icons.js?v=1.1"></script>
|
||||
<script src="/js/app.js?v=13.9"></script>
|
||||
<script src="/js/app.js?v=14.0"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+180
-1
@@ -2942,7 +2942,8 @@ function openParentSubView(viewKey, shouldScroll = true) {
|
||||
'parentSubViewAlergias',
|
||||
'parentSubViewLimites',
|
||||
'parentSubViewHistorial',
|
||||
'parentSubViewCredenciales'
|
||||
'parentSubViewCredenciales',
|
||||
'parentSubViewDashboard'
|
||||
];
|
||||
subViews.forEach(id => {
|
||||
const el = document.getElementById(id);
|
||||
@@ -2966,6 +2967,7 @@ function openParentSubView(viewKey, shouldScroll = true) {
|
||||
else if (viewKey === 'historial') targetId = 'parentSubViewHistorial';
|
||||
else if (viewKey === 'credenciales') targetId = 'parentSubViewCredenciales';
|
||||
else if (viewKey === 'preordenes' || viewKey === 'menu') targetId = 'parentSubViewMenu';
|
||||
else if (viewKey === 'dashboard') targetId = 'parentSubViewDashboard';
|
||||
else if (viewKey === 'resumen') targetId = 'parentSubViewResumen';
|
||||
|
||||
const targetEl = document.getElementById(targetId);
|
||||
@@ -2986,6 +2988,8 @@ function openParentSubView(viewKey, shouldScroll = true) {
|
||||
|
||||
if (viewKey === 'preordenes' || viewKey === 'menu') {
|
||||
renderParentCatalog();
|
||||
} else if (viewKey === 'dashboard') {
|
||||
cargarDashboardPadres();
|
||||
} else if (viewKey === 'sinpe' && currentParentChild) {
|
||||
if (typeof ensureParentSinpeSession === 'function') {
|
||||
ensureParentSinpeSession(currentParentChild);
|
||||
@@ -3006,6 +3010,181 @@ function openParentSubView(viewKey, shouldScroll = true) {
|
||||
if (window.sounds) window.sounds.playTap();
|
||||
}
|
||||
|
||||
// Variables y Funciones del Dashboard Ejecutivo de Padres
|
||||
let parentDashPeriodoActual = 'mes';
|
||||
let parentDashHijoActual = 'todos';
|
||||
|
||||
function poblarSelectorHijosDashboardPadres() {
|
||||
const select = document.getElementById('parentDashChildFilter');
|
||||
if (!select) return;
|
||||
const hijos = (currentUser && currentUser.hijos) ? currentUser.hijos : [];
|
||||
|
||||
let html = `<option value="todos">👨👩👧👦 Todos mis hijos (Consolidado)</option>`;
|
||||
hijos.forEach(h => {
|
||||
html += `<option value="${h.id}">${escapeHtml(h.nombre_completo)} (${escapeHtml(h.grado || 'Estudiante')})</option>`;
|
||||
});
|
||||
select.innerHTML = html;
|
||||
select.value = parentDashHijoActual;
|
||||
}
|
||||
|
||||
async function cambiarPeriodoDashboardPadres(periodo) {
|
||||
parentDashPeriodoActual = periodo;
|
||||
const container = document.getElementById('parentDashPeriodPills');
|
||||
if (container) {
|
||||
const buttons = container.querySelectorAll('.admin-dash-pill-btn');
|
||||
buttons.forEach(btn => {
|
||||
btn.classList.toggle('active', btn.dataset.periodo === periodo);
|
||||
});
|
||||
}
|
||||
await cargarDashboardPadres();
|
||||
}
|
||||
|
||||
async function cambiarHijoDashboardPadres(estudianteId) {
|
||||
parentDashHijoActual = estudianteId;
|
||||
await cargarDashboardPadres();
|
||||
}
|
||||
|
||||
async function cargarDashboardPadres() {
|
||||
if (!currentUser || currentUser.rol !== 'padre') return;
|
||||
|
||||
poblarSelectorHijosDashboardPadres();
|
||||
|
||||
try {
|
||||
let url = `/api/padres/dashboard?padre_usuario_id=${currentUser.id}&periodo=${encodeURIComponent(parentDashPeriodoActual)}`;
|
||||
if (parentDashHijoActual && parentDashHijoActual !== 'todos') {
|
||||
url += `&estudiante_id=${encodeURIComponent(parentDashHijoActual)}`;
|
||||
}
|
||||
|
||||
const res = await fetch(url);
|
||||
if (!res.ok) throw new Error('Error al cargar datos del dashboard de padres');
|
||||
const data = await res.json();
|
||||
const resumen = data.resumen || {};
|
||||
|
||||
// 1. KPI Saldo
|
||||
const elSaldo = document.getElementById('parentDashKpiSaldo');
|
||||
if (elSaldo) elSaldo.textContent = `₡${(resumen.saldo_disponible || 0).toLocaleString('es-CR')}`;
|
||||
|
||||
const elSaldoMeta = document.getElementById('parentDashKpiSaldoMeta');
|
||||
if (elSaldoMeta) {
|
||||
if ((resumen.saldo_retenido || 0) > 0) {
|
||||
elSaldoMeta.innerHTML = `Retenido preórdenes: <strong style="color: #f59e0b;">₡${(resumen.saldo_retenido || 0).toLocaleString('es-CR')}</strong> • Total: ₡${(resumen.saldo_total || 0).toLocaleString('es-CR')}`;
|
||||
} else {
|
||||
elSaldoMeta.innerHTML = `Saldo total en monederos: <strong>₡${(resumen.saldo_total || 0).toLocaleString('es-CR')}</strong>`;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. KPI Recargas
|
||||
const elRecargas = document.getElementById('parentDashKpiRecargas');
|
||||
if (elRecargas) elRecargas.textContent = `₡${(resumen.total_recargas || 0).toLocaleString('es-CR')}`;
|
||||
|
||||
const elRecargasMeta = document.getElementById('parentDashKpiRecargasMeta');
|
||||
if (elRecargasMeta) {
|
||||
elRecargasMeta.innerHTML = `SINPE Móvil: <strong>₡${(resumen.recargas_sinpe || 0).toLocaleString('es-CR')}</strong> (${resumen.cant_recargas || 0} recargas)`;
|
||||
}
|
||||
|
||||
// 3. KPI Compras
|
||||
const elCompras = document.getElementById('parentDashKpiCompras');
|
||||
if (elCompras) elCompras.textContent = `₡${(resumen.total_compras || 0).toLocaleString('es-CR')}`;
|
||||
|
||||
const elComprasMeta = document.getElementById('parentDashKpiComprasMeta');
|
||||
if (elComprasMeta) {
|
||||
elComprasMeta.textContent = `${resumen.cant_compras || 0} compras despachadas`;
|
||||
}
|
||||
|
||||
// 4. KPI Promedio
|
||||
const elTicket = document.getElementById('parentDashKpiTicket');
|
||||
if (elTicket) elTicket.textContent = `₡${(resumen.ticket_promedio || 0).toLocaleString('es-CR')}`;
|
||||
|
||||
const elTicketMeta = document.getElementById('parentDashKpiTicketMeta');
|
||||
if (elTicketMeta) {
|
||||
elTicketMeta.textContent = `Promedio de consumo por orden`;
|
||||
}
|
||||
|
||||
// 5. Top Productos Consumidos
|
||||
const contTop = document.getElementById('parentDashTopProductosList');
|
||||
if (contTop) {
|
||||
const top = data.top_productos || [];
|
||||
if (top.length === 0) {
|
||||
contTop.innerHTML = `
|
||||
<div style="text-align: center; padding: 20px 10px; color: var(--text-muted); font-size: 0.8rem;">
|
||||
No hay compras registradas en este período.
|
||||
</div>
|
||||
`;
|
||||
} else {
|
||||
const maxCant = Math.max(...top.map(t => t.cantidad_total || 1));
|
||||
const medallas = ['🥇', '🥈', '🥉', '4º', '5º'];
|
||||
contTop.innerHTML = top.map((p, idx) => {
|
||||
const pct = Math.round(((p.cantidad_total || 0) / maxCant) * 100);
|
||||
return `
|
||||
<div style="display: flex; flex-direction: column; gap: 4px; padding: 6px 0; border-bottom: 1px dashed var(--border, #e2e8f0);">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; font-size: 0.82rem;">
|
||||
<span style="display: flex; align-items: center; gap: 6px; min-width: 0;">
|
||||
<span style="font-size: 0.85rem; font-weight: 800; width: 22px;">${medallas[idx] || (idx + 1)}</span>
|
||||
<strong style="color: var(--text-main); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${escapeHtml(p.nombre_producto)}</strong>
|
||||
</span>
|
||||
<span style="text-align: right; flex-shrink: 0; font-weight: 800; color: #0284c7;">
|
||||
₡${(p.total_colones || 0).toLocaleString('es-CR')}
|
||||
<span style="font-size: 0.72rem; color: var(--text-muted); font-weight: 600; display: block;">${p.cantidad_total} uds</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="admin-dash-bar-track" style="height: 5px;">
|
||||
<div class="admin-dash-bar-fill" style="width: ${pct}%; background: linear-gradient(90deg, #34d399, #10b981);"></div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Últimos Movimientos
|
||||
const contMov = document.getElementById('parentDashMovimientosList');
|
||||
if (contMov) {
|
||||
const movs = data.movimientos || [];
|
||||
if (movs.length === 0) {
|
||||
contMov.innerHTML = `
|
||||
<div style="text-align: center; padding: 20px 10px; color: var(--text-muted); font-size: 0.8rem;">
|
||||
Sin movimientos registrados para el período seleccionado.
|
||||
</div>
|
||||
`;
|
||||
} else {
|
||||
contMov.innerHTML = movs.map(m => {
|
||||
const esIngreso = Number(m.monto_colones || 0) > 0;
|
||||
const colorMonto = esIngreso ? '#16a34a' : '#0f172a';
|
||||
const signo = esIngreso ? '+' : '';
|
||||
const fechaFmt = m.fecha ? new Date(m.fecha).toLocaleString('es-CR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' }) : '';
|
||||
return `
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; padding: 8px 10px; background: var(--bg-main, #f8fafc); border-radius: 10px; font-size: 0.8rem; border: 1px solid var(--border, #e2e8f0);">
|
||||
<div style="min-width: 0;">
|
||||
<div style="font-weight: 800; color: var(--text-main); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
|
||||
${escapeHtml(m.descripcion || m.tipo)}
|
||||
</div>
|
||||
<div style="font-size: 0.70rem; color: var(--text-muted); margin-top: 1px;">
|
||||
<span>${escapeHtml(m.estudiante_nombre)}</span> • <span>${fechaFmt}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div style="text-align: right; flex-shrink: 0; font-weight: 900; color: ${colorMonto}; margin-left: 10px;">
|
||||
${signo}₡${Math.abs(Number(m.monto_colones || 0)).toLocaleString('es-CR')}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error al cargar dashboard de padres:', err);
|
||||
}
|
||||
}
|
||||
|
||||
function descargarEstadoCuentaPadresExcel() {
|
||||
if (!currentUser || currentUser.rol !== 'padre') return;
|
||||
let url = `/api/padres/export/estado-cuenta.xlsx?padre_usuario_id=${currentUser.id}&periodo=${encodeURIComponent(parentDashPeriodoActual)}`;
|
||||
if (parentDashHijoActual && parentDashHijoActual !== 'todos') {
|
||||
url += `&estudiante_id=${encodeURIComponent(parentDashHijoActual)}`;
|
||||
}
|
||||
const dateTag = new Date().toISOString().slice(0, 10);
|
||||
descargarArchivoDirecto(url, `estado_cuenta_familiar_${dateTag}.xlsx`);
|
||||
}
|
||||
|
||||
function closeParentSubView(shouldScroll = true) {
|
||||
const isDesktop = window.innerWidth >= 860;
|
||||
if (isDesktop) {
|
||||
|
||||
+2
-2
@@ -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.9">
|
||||
<link rel="stylesheet" href="/css/styles.css?v=14.0">
|
||||
<style>
|
||||
/* Estilos específicos de terminal de alta velocidad */
|
||||
.student-badge-scanned {
|
||||
@@ -677,6 +677,6 @@
|
||||
<script src="/js/sounds.js?v=13.8"></script>
|
||||
<script src="/js/jsQR.js"></script>
|
||||
<script src="/js/food-icons.js?v=1.1"></script>
|
||||
<script src="/js/pos.js?v=13.9"></script>
|
||||
<script src="/js/pos.js?v=14.0"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
// SiboPay PWA Service Worker v13.9 - Dashboard Ejecutivo de Soda
|
||||
const CACHE_NAME = 'sibopay-v13.9';
|
||||
// SiboPay PWA Service Worker v14.0 - Dashboard Ejecutivo de Padres
|
||||
const CACHE_NAME = 'sibopay-v14.0';
|
||||
const STATIC_ASSETS = [
|
||||
'/',
|
||||
'/index.html',
|
||||
|
||||
@@ -473,6 +473,300 @@ app.post('/api/padres/restablecer-acceso', (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Dashboard Ejecutivo del Portal de Padres
|
||||
app.get('/api/padres/dashboard', (req, res) => {
|
||||
try {
|
||||
const padreUsuarioId = req.query.padre_usuario_id ? parseInt(req.query.padre_usuario_id, 10) : null;
|
||||
if (!padreUsuarioId) return res.status(400).json({ error: 'Falta padre_usuario_id' });
|
||||
|
||||
// 1. Obtener hijos vinculados a este padre
|
||||
let hijos = db.prepare(`
|
||||
SELECT e.id, e.nombre_completo, e.grado, e.seccion, e.codigo_estudiante, e.codigo_carnet, e.saldo_colones, e.foto_url
|
||||
FROM estudiantes e
|
||||
JOIN padres_estudiantes pe ON e.id = pe.estudiante_id
|
||||
WHERE pe.padre_usuario_id = ? AND e.activo = 1
|
||||
ORDER BY e.nombre_completo ASC
|
||||
`).all(padreUsuarioId);
|
||||
|
||||
if (hijos.length === 0) {
|
||||
hijos = db.prepare(`
|
||||
SELECT e.id, e.nombre_completo, e.grado, e.seccion, e.codigo_estudiante, e.codigo_carnet, e.saldo_colones, e.foto_url
|
||||
FROM estudiantes e
|
||||
WHERE e.padre_usuario_id = ? AND e.activo = 1
|
||||
ORDER BY e.nombre_completo ASC
|
||||
`).all(padreUsuarioId);
|
||||
}
|
||||
|
||||
if (hijos.length === 0) {
|
||||
return res.json({
|
||||
periodo: req.query.periodo || 'mes',
|
||||
hijos: [],
|
||||
resumen: {
|
||||
saldo_total: 0,
|
||||
saldo_disponible: 0,
|
||||
saldo_retenido: 0,
|
||||
total_recargas: 0,
|
||||
recargas_sinpe: 0,
|
||||
recargas_efectivo: 0,
|
||||
cant_recargas: 0,
|
||||
total_compras: 0,
|
||||
cant_compras: 0,
|
||||
ticket_promedio: 0
|
||||
},
|
||||
top_productos: [],
|
||||
movimientos: []
|
||||
});
|
||||
}
|
||||
|
||||
// 2. Filtrar por hijo si se especifica
|
||||
const estudianteIdQuery = req.query.estudiante_id;
|
||||
let targetIds = hijos.map(h => h.id);
|
||||
if (estudianteIdQuery && estudianteIdQuery !== 'todos') {
|
||||
const parsedId = parseInt(estudianteIdQuery, 10);
|
||||
if (targetIds.includes(parsedId)) {
|
||||
targetIds = [parsedId];
|
||||
}
|
||||
}
|
||||
const inPlaceholders = targetIds.map(() => '?').join(',');
|
||||
|
||||
// 3. Manejo de período
|
||||
const periodo = req.query.periodo || 'mes';
|
||||
const ahora = new Date();
|
||||
const fHoy = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Costa_Rica' }).format(ahora);
|
||||
let fechaInicio = fHoy;
|
||||
let fechaFin = fHoy;
|
||||
let usarFiltroFechas = true;
|
||||
|
||||
if (periodo === 'hoy') {
|
||||
fechaInicio = fHoy;
|
||||
fechaFin = fHoy;
|
||||
} else if (periodo === '30dias') {
|
||||
const d30 = new Date();
|
||||
d30.setDate(d30.getDate() - 29);
|
||||
fechaInicio = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Costa_Rica' }).format(d30);
|
||||
fechaFin = fHoy;
|
||||
} else if (periodo === 'mes') {
|
||||
fechaInicio = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Costa_Rica' }).format(new Date(ahora.getFullYear(), ahora.getMonth(), 1));
|
||||
fechaFin = fHoy;
|
||||
} else if (periodo === 'todo') {
|
||||
usarFiltroFechas = false;
|
||||
}
|
||||
|
||||
// 4. Saldo actual y retenido en preórdenes
|
||||
const saldosRow = db.prepare(`
|
||||
SELECT COALESCE(SUM(saldo_colones), 0) as total
|
||||
FROM estudiantes
|
||||
WHERE id IN (${inPlaceholders})
|
||||
`).get(...targetIds);
|
||||
const saldoTotal = saldosRow ? saldosRow.total : 0;
|
||||
|
||||
const retenidoRow = db.prepare(`
|
||||
SELECT COALESCE(SUM(total_colones), 0) as total
|
||||
FROM ordenes
|
||||
WHERE estudiante_id IN (${inPlaceholders}) AND tipo_orden = 'preorden' AND estado IN ('pendiente', 'en_preparacion', 'listo')
|
||||
`).get(...targetIds);
|
||||
const saldoRetenido = retenidoRow ? retenidoRow.total : 0;
|
||||
const saldoDisponible = Math.max(0, saldoTotal - saldoRetenido);
|
||||
|
||||
// 5. Recargas del período
|
||||
let sqlRecargas = `
|
||||
SELECT
|
||||
COALESCE(SUM(monto_colones), 0) as total_recargas,
|
||||
COALESCE(SUM(CASE WHEN tipo = 'recarga_sinpe' THEN monto_colones ELSE 0 END), 0) as recargas_sinpe,
|
||||
COALESCE(SUM(CASE WHEN tipo = 'recarga_manual' THEN monto_colones ELSE 0 END), 0) as recargas_efectivo,
|
||||
COUNT(*) as cant_recargas
|
||||
FROM transacciones_saldo
|
||||
WHERE estudiante_id IN (${inPlaceholders})
|
||||
AND tipo IN ('recarga_sinpe', 'recarga_manual')
|
||||
AND monto_colones > 0
|
||||
AND (revertida IS NULL OR revertida = 0)
|
||||
`;
|
||||
const paramsRecargas = [...targetIds];
|
||||
if (usarFiltroFechas) {
|
||||
sqlRecargas += ` AND date(fecha, 'localtime') >= ? AND date(fecha, 'localtime') <= ?`;
|
||||
paramsRecargas.push(fechaInicio, fechaFin);
|
||||
}
|
||||
const recargasRow = db.prepare(sqlRecargas).get(...paramsRecargas) || {};
|
||||
|
||||
// 6. Compras / Consumo del período
|
||||
let sqlCompras = `
|
||||
SELECT
|
||||
COALESCE(SUM(total_colones), 0) as total_compras,
|
||||
COUNT(*) as cant_compras,
|
||||
ROUND(COALESCE(AVG(total_colones), 0)) as ticket_promedio
|
||||
FROM ordenes
|
||||
WHERE estudiante_id IN (${inPlaceholders}) AND estado != 'cancelado'
|
||||
`;
|
||||
const paramsCompras = [...targetIds];
|
||||
if (usarFiltroFechas) {
|
||||
sqlCompras += ` AND date(creado_en, 'localtime') >= ? AND date(creado_en, 'localtime') <= ?`;
|
||||
paramsCompras.push(fechaInicio, fechaFin);
|
||||
}
|
||||
const comprasRow = db.prepare(sqlCompras).get(...paramsCompras) || {};
|
||||
|
||||
// 7. Top 5 Productos Consumidos
|
||||
let sqlTop = `
|
||||
SELECT
|
||||
od.nombre_producto,
|
||||
COALESCE(SUM(od.cantidad), 0) as cantidad_total,
|
||||
COALESCE(SUM(od.subtotal), 0) as total_colones
|
||||
FROM orden_detalles od
|
||||
JOIN ordenes o ON od.orden_id = o.id
|
||||
WHERE o.estudiante_id IN (${inPlaceholders}) AND o.estado != 'cancelado'
|
||||
`;
|
||||
const paramsTop = [...targetIds];
|
||||
if (usarFiltroFechas) {
|
||||
sqlTop += ` AND date(o.creado_en, 'localtime') >= ? AND date(o.creado_en, 'localtime') <= ?`;
|
||||
paramsTop.push(fechaInicio, fechaFin);
|
||||
}
|
||||
sqlTop += ` GROUP BY od.nombre_producto ORDER BY cantidad_total DESC, total_colones DESC LIMIT 5`;
|
||||
const topProductos = db.prepare(sqlTop).all(...paramsTop);
|
||||
|
||||
// 8. Movimientos recientes (hasta 12)
|
||||
let sqlMov = `
|
||||
SELECT
|
||||
ts.id, ts.estudiante_id, e.nombre_completo as estudiante_nombre,
|
||||
ts.tipo, ts.monto_colones, ts.descripcion, ts.fecha
|
||||
FROM transacciones_saldo ts
|
||||
JOIN estudiantes e ON ts.estudiante_id = e.id
|
||||
WHERE ts.estudiante_id IN (${inPlaceholders})
|
||||
`;
|
||||
const paramsMov = [...targetIds];
|
||||
if (usarFiltroFechas) {
|
||||
sqlMov += ` AND date(ts.fecha, 'localtime') >= ? AND date(ts.fecha, 'localtime') <= ?`;
|
||||
paramsMov.push(fechaInicio, fechaFin);
|
||||
}
|
||||
sqlMov += ` ORDER BY ts.fecha DESC, ts.id DESC LIMIT 12`;
|
||||
const movimientos = db.prepare(sqlMov).all(...paramsMov);
|
||||
|
||||
res.json({
|
||||
periodo,
|
||||
fecha_inicio: fechaInicio,
|
||||
fecha_fin: fechaFin,
|
||||
hijos,
|
||||
resumen: {
|
||||
saldo_total: saldoTotal,
|
||||
saldo_disponible: saldoDisponible,
|
||||
saldo_retenido: saldoRetenido,
|
||||
total_recargas: recargasRow.total_recargas || 0,
|
||||
recargas_sinpe: recargasRow.recargas_sinpe || 0,
|
||||
recargas_efectivo: recargasRow.recargas_efectivo || 0,
|
||||
cant_recargas: recargasRow.cant_recargas || 0,
|
||||
total_compras: comprasRow.total_compras || 0,
|
||||
cant_compras: comprasRow.cant_compras || 0,
|
||||
ticket_promedio: comprasRow.ticket_promedio || 0
|
||||
},
|
||||
top_productos: topProductos,
|
||||
movimientos
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Error en /api/padres/dashboard:', err);
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Exportar Estado de Cuenta Familiar a Excel
|
||||
app.get(['/api/padres/export/estado-cuenta.xlsx', '/api/padres/export/estado-cuenta.csv'], (req, res) => {
|
||||
try {
|
||||
const padreUsuarioId = req.query.padre_usuario_id ? parseInt(req.query.padre_usuario_id, 10) : null;
|
||||
if (!padreUsuarioId) return res.status(400).json({ error: 'Falta padre_usuario_id' });
|
||||
|
||||
let hijos = db.prepare(`
|
||||
SELECT e.id, e.nombre_completo, e.grado, e.seccion, e.codigo_estudiante
|
||||
FROM estudiantes e
|
||||
JOIN padres_estudiantes pe ON e.id = pe.estudiante_id
|
||||
WHERE pe.padre_usuario_id = ? AND e.activo = 1
|
||||
`).all(padreUsuarioId);
|
||||
|
||||
if (hijos.length === 0) {
|
||||
hijos = db.prepare(`
|
||||
SELECT e.id, e.nombre_completo, e.grado, e.seccion, e.codigo_estudiante
|
||||
FROM estudiantes e
|
||||
WHERE e.padre_usuario_id = ? AND e.activo = 1
|
||||
`).all(padreUsuarioId);
|
||||
}
|
||||
|
||||
if (hijos.length === 0) return res.status(404).json({ error: 'No hay estudiantes vinculados' });
|
||||
|
||||
const estudianteIdQuery = req.query.estudiante_id;
|
||||
let targetIds = hijos.map(h => h.id);
|
||||
if (estudianteIdQuery && estudianteIdQuery !== 'todos') {
|
||||
const parsedId = parseInt(estudianteIdQuery, 10);
|
||||
if (targetIds.includes(parsedId)) targetIds = [parsedId];
|
||||
}
|
||||
const inPlaceholders = targetIds.map(() => '?').join(',');
|
||||
|
||||
const periodo = req.query.periodo || 'mes';
|
||||
const ahora = new Date();
|
||||
const fHoy = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Costa_Rica' }).format(ahora);
|
||||
let fechaInicio = fHoy;
|
||||
let fechaFin = fHoy;
|
||||
let usarFiltroFechas = true;
|
||||
|
||||
if (periodo === 'hoy') {
|
||||
fechaInicio = fHoy;
|
||||
fechaFin = fHoy;
|
||||
} else if (periodo === '30dias') {
|
||||
const d30 = new Date();
|
||||
d30.setDate(d30.getDate() - 29);
|
||||
fechaInicio = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Costa_Rica' }).format(d30);
|
||||
fechaFin = fHoy;
|
||||
} else if (periodo === 'mes') {
|
||||
fechaInicio = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Costa_Rica' }).format(new Date(ahora.getFullYear(), ahora.getMonth(), 1));
|
||||
fechaFin = fHoy;
|
||||
} else if (periodo === 'todo') {
|
||||
usarFiltroFechas = false;
|
||||
}
|
||||
|
||||
let sqlMov = `
|
||||
SELECT
|
||||
ts.id, ts.fecha, e.nombre_completo as estudiante_nombre, e.codigo_estudiante,
|
||||
ts.tipo, ts.descripcion, ts.monto_colones, ts.saldo_posterior
|
||||
FROM transacciones_saldo ts
|
||||
JOIN estudiantes e ON ts.estudiante_id = e.id
|
||||
WHERE ts.estudiante_id IN (${inPlaceholders})
|
||||
`;
|
||||
const paramsMov = [...targetIds];
|
||||
if (usarFiltroFechas) {
|
||||
sqlMov += ` AND date(ts.fecha, 'localtime') >= ? AND date(ts.fecha, 'localtime') <= ?`;
|
||||
paramsMov.push(fechaInicio, fechaFin);
|
||||
}
|
||||
sqlMov += ` ORDER BY ts.fecha DESC, ts.id DESC LIMIT 1000`;
|
||||
const transacciones = db.prepare(sqlMov).all(...paramsMov);
|
||||
|
||||
const tipoEtiquetas = {
|
||||
'recarga_sinpe': 'Recarga SINPE Móvil',
|
||||
'recarga_manual': 'Recarga en Caja',
|
||||
'compra_mostrador': 'Compra Mostrador',
|
||||
'preorden': 'Compra Pre-orden',
|
||||
'reversion_recarga': 'Reversión Recarga',
|
||||
'transferencia_enviada': 'Transferencia Enviada',
|
||||
'transferencia_recibida': 'Transferencia Recibida'
|
||||
};
|
||||
|
||||
const headers = ['Fecha y Hora', 'Estudiante', 'Código Est.', 'Tipo de Movimiento', 'Descripción', 'Monto (CRC)', 'Saldo Posterior (CRC)'];
|
||||
const rows = transacciones.map(t => {
|
||||
const fechaFmt = t.fecha ? new Date(t.fecha).toLocaleString('es-CR') : '';
|
||||
const tipoTxt = tipoEtiquetas[t.tipo] || t.tipo;
|
||||
return [
|
||||
fechaFmt,
|
||||
t.estudiante_nombre,
|
||||
t.codigo_estudiante,
|
||||
tipoTxt,
|
||||
t.descripcion || '',
|
||||
Number(t.monto_colones || 0),
|
||||
Number(t.saldo_posterior || 0)
|
||||
];
|
||||
});
|
||||
|
||||
const filenameBase = `estado_cuenta_familiar_${new Date().toISOString().slice(0, 10)}`;
|
||||
responderExportacion(res, req, { sheetName: 'Estado de Cuenta', filenameBase, headers, rows });
|
||||
} catch (err) {
|
||||
console.error('Error al exportar estado de cuenta:', err);
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// ==========================================
|
||||
// ENDPOINTS DE ADMINISTRACIÓN DE LA SODA
|
||||
// ==========================================
|
||||
|
||||
Reference in New Issue
Block a user