feat: complete soda admin panel, stock control with auto-greyout out-of-stock, student card blocking, manual cash loads, role-based login, and session logout fix
This commit is contained in:
@@ -751,3 +751,346 @@ body.dark-mode .floating-cart-bar {
|
||||
box-shadow: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
VISTA DE LOGIN Y AUTENTICACIÓN
|
||||
========================================================================== */
|
||||
.login-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: radial-gradient(circle at 50% 10%, #0284c7 0%, #0f172a 100%);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 16px;
|
||||
z-index: 9999;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.login-card {
|
||||
background: var(--card-bg, #ffffff);
|
||||
color: var(--text-main, #0f172a);
|
||||
border-radius: 24px;
|
||||
padding: 28px 24px;
|
||||
width: 100%;
|
||||
max-width: 420px;
|
||||
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.45);
|
||||
border: 1px solid rgba(255, 255, 255, 0.15);
|
||||
animation: fadeIn 0.25s ease-out;
|
||||
}
|
||||
|
||||
.login-brand {
|
||||
text-align: center;
|
||||
margin-bottom: 22px;
|
||||
}
|
||||
|
||||
.login-logo {
|
||||
font-size: 3rem;
|
||||
display: inline-block;
|
||||
background: #e0f2fe;
|
||||
padding: 12px;
|
||||
border-radius: 20px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.login-title {
|
||||
font-size: 1.6rem;
|
||||
font-weight: 900;
|
||||
letter-spacing: -0.5px;
|
||||
color: #0f172a;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.login-subtitle {
|
||||
font-size: 0.8rem;
|
||||
color: #64748b;
|
||||
margin-top: 4px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.login-form-group {
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.login-form-group label {
|
||||
display: block;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 800;
|
||||
margin-bottom: 5px;
|
||||
color: #334155;
|
||||
}
|
||||
|
||||
.login-input {
|
||||
width: 100%;
|
||||
padding: 12px 14px;
|
||||
border-radius: 12px;
|
||||
border: 1.5px solid #cbd5e1;
|
||||
font-size: 0.95rem;
|
||||
font-weight: 700;
|
||||
background: #f8fafc;
|
||||
color: #0f172a;
|
||||
transition: all 0.2s;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.login-input:focus {
|
||||
outline: none;
|
||||
border-color: #0284c7;
|
||||
background: #ffffff;
|
||||
box-shadow: 0 0 0 3px rgba(2, 132, 199, 0.15);
|
||||
}
|
||||
|
||||
.login-submit-btn {
|
||||
width: 100%;
|
||||
padding: 13px;
|
||||
background: linear-gradient(135deg, #0284c7, #0369a1);
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 14px;
|
||||
font-size: 1rem;
|
||||
font-weight: 900;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 4px 12px rgba(2, 132, 199, 0.35);
|
||||
transition: transform 0.1s;
|
||||
}
|
||||
|
||||
.login-submit-btn:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
.login-demo-box {
|
||||
margin-top: 20px;
|
||||
padding-top: 18px;
|
||||
border-top: 1px dashed #e2e8f0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.login-demo-title {
|
||||
font-size: 0.76rem;
|
||||
font-weight: 800;
|
||||
color: #64748b;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.login-demo-btns {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.login-demo-btn {
|
||||
background: #f1f5f9;
|
||||
border: 1px solid #cbd5e1;
|
||||
border-radius: 10px;
|
||||
padding: 8px 4px;
|
||||
font-size: 0.72rem;
|
||||
font-weight: 800;
|
||||
color: #1e293b;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
transition: all 0.15s;
|
||||
}
|
||||
|
||||
.login-demo-btn:hover {
|
||||
background: #e2e8f0;
|
||||
border-color: #0284c7;
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
PANEL DE ADMINISTRACIÓN DE LA SODA (#viewAdmin)
|
||||
========================================================================== */
|
||||
.admin-container {
|
||||
max-width: 900px;
|
||||
margin: 0 auto;
|
||||
min-height: 100vh;
|
||||
background: var(--bg-main, #f8fafc);
|
||||
padding: 16px 16px 60px 16px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.admin-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
background: var(--card-bg, #ffffff);
|
||||
border: 1px solid var(--border, #e2e8f0);
|
||||
border-radius: 18px;
|
||||
padding: 14px 18px;
|
||||
margin-bottom: 16px;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
|
||||
}
|
||||
|
||||
.admin-badge {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.admin-icon {
|
||||
font-size: 1.8rem;
|
||||
background: #e0f2fe;
|
||||
padding: 8px;
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
.admin-stats-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));
|
||||
gap: 10px;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
.admin-stat-card {
|
||||
background: var(--card-bg, #ffffff);
|
||||
border: 1px solid var(--border, #e2e8f0);
|
||||
border-radius: 14px;
|
||||
padding: 12px;
|
||||
text-align: center;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.03);
|
||||
}
|
||||
|
||||
.admin-stat-card .val {
|
||||
font-size: 1.4rem;
|
||||
font-weight: 900;
|
||||
color: #0284c7;
|
||||
}
|
||||
|
||||
.admin-stat-card .lbl {
|
||||
font-size: 0.72rem;
|
||||
font-weight: 700;
|
||||
color: var(--text-muted, #64748b);
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.admin-tabs {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-bottom: 16px;
|
||||
overflow-x: auto;
|
||||
padding-bottom: 4px;
|
||||
}
|
||||
|
||||
.admin-tab-btn {
|
||||
background: var(--card-bg, #ffffff);
|
||||
border: 1.5px solid var(--border, #cbd5e1);
|
||||
color: var(--text-main, #334155);
|
||||
padding: 10px 16px;
|
||||
border-radius: 12px;
|
||||
font-size: 0.88rem;
|
||||
font-weight: 800;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
white-space: nowrap;
|
||||
transition: all 0.15s;
|
||||
}
|
||||
|
||||
.admin-tab-btn.active {
|
||||
background: #0284c7;
|
||||
color: white;
|
||||
border-color: #0284c7;
|
||||
box-shadow: 0 4px 10px rgba(2, 132, 199, 0.3);
|
||||
}
|
||||
|
||||
.admin-card {
|
||||
background: var(--card-bg, #ffffff);
|
||||
border: 1px solid var(--border, #e2e8f0);
|
||||
border-radius: 18px;
|
||||
padding: 18px;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
/* Tabla / Lista de Inventario Admin */
|
||||
.inventory-item-row {
|
||||
display: grid;
|
||||
grid-template-columns: 44px 1fr auto auto;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 12px;
|
||||
border-bottom: 1px solid var(--border, #f1f5f9);
|
||||
transition: background 0.15s;
|
||||
}
|
||||
|
||||
.inventory-item-row:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.inventory-stock-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.stock-btn-quick {
|
||||
padding: 5px 9px;
|
||||
background: #f1f5f9;
|
||||
border: 1px solid #cbd5e1;
|
||||
border-radius: 8px;
|
||||
font-size: 0.78rem;
|
||||
font-weight: 800;
|
||||
cursor: pointer;
|
||||
color: #1e293b;
|
||||
}
|
||||
|
||||
.stock-btn-quick:hover {
|
||||
background: #e2e8f0;
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
PRODUCTO AGOTADO (GREYED OUT) Y TARJETA BLOQUEADA
|
||||
========================================================================== */
|
||||
.product-card.out-of-stock {
|
||||
opacity: 0.52 !important;
|
||||
filter: grayscale(85%) !important;
|
||||
border-color: #fca5a5 !important;
|
||||
background: #fef2f2 !important;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
body.dark-mode .product-card.out-of-stock {
|
||||
background: rgba(239, 68, 68, 0.12) !important;
|
||||
border-color: rgba(239, 68, 68, 0.3) !important;
|
||||
}
|
||||
|
||||
.badge-out-of-stock {
|
||||
display: inline-block;
|
||||
background: #ef4444;
|
||||
color: white;
|
||||
font-weight: 900;
|
||||
font-size: 0.68rem;
|
||||
padding: 3px 8px;
|
||||
border-radius: 6px;
|
||||
letter-spacing: 0.5px;
|
||||
box-shadow: 0 1px 3px rgba(239, 68, 68, 0.3);
|
||||
}
|
||||
|
||||
.banner-card-blocked {
|
||||
background: #fee2e2;
|
||||
border: 2px solid #ef4444;
|
||||
color: #991b1b;
|
||||
padding: 12px 16px;
|
||||
border-radius: 14px;
|
||||
margin: 10px 16px 14px 16px;
|
||||
font-weight: 800;
|
||||
font-size: 0.85rem;
|
||||
text-align: center;
|
||||
box-shadow: 0 2px 8px rgba(239, 68, 68, 0.2);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
body.dark-mode .banner-card-blocked {
|
||||
background: rgba(239, 68, 68, 0.2);
|
||||
color: #fca5a5;
|
||||
border-color: #ef4444;
|
||||
}
|
||||
|
||||
|
||||
+302
-1
@@ -28,7 +28,209 @@
|
||||
</head>
|
||||
<body class="">
|
||||
|
||||
<div class="app-container">
|
||||
<!-- VISTA DE LOGIN Y CONTROL DE ACCESO -->
|
||||
<div id="viewLogin" class="login-overlay" style="display: none;">
|
||||
<div class="login-card">
|
||||
<div class="login-brand">
|
||||
<div class="login-logo">🥪</div>
|
||||
<h1 class="login-title">Recreo<strong>Pay</strong></h1>
|
||||
<p class="login-subtitle">Sistema Digital de Soda Escolar y Monedero Estudiantil</p>
|
||||
</div>
|
||||
|
||||
<form id="formLogin" onsubmit="handleLoginSubmit(event)">
|
||||
<div class="login-form-group">
|
||||
<label for="loginUsername">Usuario o Carné:</label>
|
||||
<input type="text" id="loginUsername" class="login-input" placeholder="Ej: admin, padre, mateo" required autocomplete="username">
|
||||
</div>
|
||||
|
||||
<div class="login-form-group">
|
||||
<label for="loginPassword">Contraseña o PIN:</label>
|
||||
<input type="password" id="loginPassword" class="login-input" placeholder="••••••••" required autocomplete="current-password">
|
||||
</div>
|
||||
|
||||
<div id="loginErrorMsg" style="display: none; background: #fee2e2; border: 1px solid #fca5a5; color: #991b1b; padding: 8px 12px; border-radius: 10px; font-size: 0.8rem; font-weight: 700; margin-bottom: 12px; text-align: center;"></div>
|
||||
|
||||
<button type="submit" id="btnLoginSubmit" class="login-submit-btn">
|
||||
🚀 Iniciar Sesión
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<!-- ACCESOS RÁPIDOS DE PRUEBA (1-CLICK DEMO) -->
|
||||
<div class="login-demo-box">
|
||||
<div class="login-demo-title">Accesos Rápidos de Prueba:</div>
|
||||
<div class="login-demo-btns">
|
||||
<button type="button" class="login-demo-btn" onclick="quickFillLogin('admin', 'admin123')">
|
||||
<span style="font-size: 1.3rem;">👨🍳</span>
|
||||
<span>Admin Soda</span>
|
||||
</button>
|
||||
<button type="button" class="login-demo-btn" onclick="quickFillLogin('padre', 'padre123')">
|
||||
<span style="font-size: 1.3rem;">👨👩👦</span>
|
||||
<span>Padre</span>
|
||||
</button>
|
||||
<button type="button" class="login-demo-btn" onclick="quickFillLogin('mateo', '1234')">
|
||||
<span style="font-size: 1.3rem;">🎒</span>
|
||||
<span>Estudiante</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- PANEL DE ADMINISTRACIÓN DE LA SODA (#viewAdmin) -->
|
||||
<div id="viewAdmin" class="admin-container" style="display: none;">
|
||||
<!-- CABECERA DE ADMINISTRADOR -->
|
||||
<header class="admin-header">
|
||||
<div class="admin-badge">
|
||||
<div class="admin-icon">👨🍳</div>
|
||||
<div>
|
||||
<h2 style="font-size: 1.15rem; font-weight: 900; margin: 0; color: var(--text-main);">Administración de la Soda</h2>
|
||||
<span id="adminLoggedName" style="font-size: 0.76rem; color: #0284c7; font-weight: 700;">Soda Escolar Central</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; gap: 8px; align-items: center;">
|
||||
<button onclick="toggleTheme()" class="theme-toggle-btn" title="Alternar Modo Oscuro / Modo Claro">
|
||||
🌙
|
||||
</button>
|
||||
<a href="/pos.html" target="_blank" style="padding: 7px 12px; background: #0284c7; color: white; border-radius: 10px; font-size: 0.78rem; font-weight: 800; text-decoration: none;" title="Abrir Caja / Terminal POS">
|
||||
📟 Ir a Caja
|
||||
</a>
|
||||
<button onclick="logout()" class="logout-btn" title="Cerrar sesión">
|
||||
<span>🚪</span>
|
||||
<span class="logout-text">Salir</span>
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- MÉTRICAS DE HOY -->
|
||||
<div class="admin-stats-grid">
|
||||
<div class="admin-stat-card">
|
||||
<div class="val" id="adminStatVentas">₡0</div>
|
||||
<div class="lbl">Ventas Hoy</div>
|
||||
</div>
|
||||
<div class="admin-stat-card">
|
||||
<div class="val" id="adminStatOrdenes">0</div>
|
||||
<div class="lbl">Órdenes Despachadas</div>
|
||||
</div>
|
||||
<div class="admin-stat-card">
|
||||
<div class="val" id="adminStatEstudiantes">0</div>
|
||||
<div class="lbl">Estudiantes Activos</div>
|
||||
</div>
|
||||
<div class="admin-stat-card">
|
||||
<div class="val" id="adminStatBloqueados" style="color: #ef4444;">0</div>
|
||||
<div class="lbl">Tarjetas Bloqueadas</div>
|
||||
</div>
|
||||
<div class="admin-stat-card">
|
||||
<div class="val" id="adminStatCriticos" style="color: #f59e0b;">0</div>
|
||||
<div class="lbl">Bajo Stock / Agotados</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- PESTAÑAS DE NAVEGACIÓN ADMIN -->
|
||||
<div class="admin-tabs">
|
||||
<button class="admin-tab-btn active" id="btnTabAdminInventario" onclick="switchAdminTab('inventario')">
|
||||
📦 Control de Inventario y Stock
|
||||
</button>
|
||||
<button class="admin-tab-btn" id="btnTabAdminEstudiantes" onclick="switchAdminTab('estudiantes')">
|
||||
🪪 Estudiantes, Carnés y Bloqueos
|
||||
</button>
|
||||
<button class="admin-tab-btn" id="btnTabAdminRecarga" onclick="switchAdminTab('recarga')">
|
||||
💵 Cargar Dinero Manual en Caja
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- TAB 1: INVENTARIO Y STOCK -->
|
||||
<div id="adminTabContentInventario" class="admin-card">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px; flex-wrap: wrap; gap: 10px;">
|
||||
<div>
|
||||
<h3 style="margin: 0; font-size: 1.1rem; font-weight: 800; color: var(--text-main);">Inventario y Existencias</h3>
|
||||
<p style="margin: 2px 0 0 0; font-size: 0.75rem; color: var(--text-muted);">
|
||||
Cuando el stock llega a 0, el producto se marca automáticamente como <strong>AGOTADO (greyed out)</strong>.
|
||||
</p>
|
||||
</div>
|
||||
<input type="text" id="adminSearchProduct" placeholder="🔍 Buscar alimento o bebida..." oninput="filterAdminProducts(this.value)" style="padding: 8px 12px; border-radius: 10px; border: 1.5px solid var(--border); font-size: 0.85rem; width: 220px;">
|
||||
</div>
|
||||
|
||||
<div id="adminProductsList">
|
||||
<!-- Renderizado dinámico de productos y stock -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- TAB 2: ESTUDIANTES Y CARNÉS -->
|
||||
<div id="adminTabContentEstudiantes" class="admin-card" style="display: none;">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px; flex-wrap: wrap; gap: 10px;">
|
||||
<div>
|
||||
<h3 style="margin: 0; font-size: 1.1rem; font-weight: 800; color: var(--text-main);">Alumnos y Tarjetas Escolares</h3>
|
||||
<p style="margin: 2px 0 0 0; font-size: 0.75rem; color: var(--text-muted);">
|
||||
Bloquea tarjetas perdidas, crea nuevos alumnos o genera carnés con código QR.
|
||||
</p>
|
||||
</div>
|
||||
<button onclick="openNewStudentModal()" style="padding: 9px 16px; background: linear-gradient(135deg, #10b981, #059669); color: white; border: none; border-radius: 12px; font-size: 0.85rem; font-weight: 900; cursor: pointer; display: flex; align-items: center; gap: 6px;">
|
||||
<span>➕</span> Nuevo Estudiante
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div id="adminStudentsList">
|
||||
<!-- Renderizado dinámico de estudiantes con botones de bloqueo -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- TAB 3: CARGA MANUAL DE DINERO -->
|
||||
<div id="adminTabContentRecarga" class="admin-card" style="display: none; max-width: 550px; margin: 0 auto;">
|
||||
<div style="text-align: center; margin-bottom: 18px;">
|
||||
<span style="font-size: 2.2rem;">💵</span>
|
||||
<h3 style="margin: 6px 0 2px 0; font-size: 1.2rem; font-weight: 900; color: var(--text-main);">Carga Manual de Dinero</h3>
|
||||
<p style="margin: 0; font-size: 0.78rem; color: var(--text-muted);">
|
||||
Recarga de monedero estudiantil por pago en efectivo en la soda o ajuste escolar
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div style="margin-bottom: 14px;">
|
||||
<label style="display: block; font-size: 0.8rem; font-weight: 800; color: var(--text-main); margin-bottom: 5px;">
|
||||
Selecciona al Estudiante:
|
||||
</label>
|
||||
<select id="adminRecargaStudentSelect" style="width: 100%; padding: 10px; border-radius: 10px; border: 1.5px solid var(--border); font-size: 0.95rem; font-weight: 700; background: var(--card-bg); color: var(--text-main);">
|
||||
<!-- Opciones de estudiantes -->
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div style="margin-bottom: 12px;">
|
||||
<label style="display: block; font-size: 0.8rem; font-weight: 800; color: var(--text-main); margin-bottom: 5px;">
|
||||
Monto a Recargar en Colones:
|
||||
</label>
|
||||
<div style="position: relative;">
|
||||
<span style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); font-weight: 900; font-size: 1.1rem; color: #10b981;">₡</span>
|
||||
<input type="tel" inputmode="numeric" pattern="[0-9]*" id="adminRecargaMonto" placeholder="Ej: 5000" style="width: 100%; padding: 11px 12px 11px 32px; border-radius: 10px; border: 2px solid #10b981; font-size: 1.15rem; font-weight: 900; color: var(--text-main); background: var(--card-bg); box-sizing: border-box;">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; margin-bottom: 14px;">
|
||||
<button type="button" onclick="setAdminRecargaPreset(1000)" class="stock-btn-quick">₡1.000</button>
|
||||
<button type="button" onclick="setAdminRecargaPreset(2000)" class="stock-btn-quick">₡2.000</button>
|
||||
<button type="button" onclick="setAdminRecargaPreset(5000)" class="stock-btn-quick">₡5.000</button>
|
||||
<button type="button" onclick="setAdminRecargaPreset(10000)" class="stock-btn-quick">₡10.000</button>
|
||||
</div>
|
||||
|
||||
<div style="margin-bottom: 16px;">
|
||||
<label style="display: block; font-size: 0.78rem; font-weight: 700; color: var(--text-muted); margin-bottom: 4px;">
|
||||
Detalle o Recibo (Opcional):
|
||||
</label>
|
||||
<input type="text" id="adminRecargaDescripcion" placeholder="Ej: Pago en efectivo en mostrador" style="width: 100%; padding: 9px 12px; border-radius: 10px; border: 1px solid var(--border); font-size: 0.85rem; box-sizing: border-box; background: var(--card-bg); color: var(--text-main);">
|
||||
</div>
|
||||
|
||||
<button type="button" id="btnAdminSubmitRecarga" onclick="submitAdminManualRecharge()" style="width: 100%; padding: 13px; background: linear-gradient(135deg, #10b981, #059669); color: white; border: none; border-radius: 12px; font-size: 1rem; font-weight: 900; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 8px; box-shadow: 0 4px 12px rgba(16, 185, 129, 0.35);">
|
||||
<span>💰</span> Aplicar Recarga Inmediata
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="app-container" id="appContainer" style="display: none;">
|
||||
<!-- BANNER DE TARJETA SUSPENDIDA / BLOQUEADA -->
|
||||
<div id="bannerCardBlocked" class="banner-card-blocked" style="display: none;">
|
||||
<span>⛔</span>
|
||||
<span><strong>TARJETA SUSPENDIDA POR LA SODA.</strong> Acércate al mostrador de la soda para reactivar tu cuenta.</span>
|
||||
</div>
|
||||
|
||||
<!-- BANNER DE ADVERTENCIA HTTPS PARA TELÉFONOS MÓVILES -->
|
||||
<div id="bannerHttpsWarning" style="display: none; background: linear-gradient(135deg, #f59e0b, #d97706); color: white; padding: 10px 14px; font-size: 0.78rem; font-weight: 700; text-align: center; border-radius: 12px; margin: 10px 16px 0 16px; box-shadow: 0 2px 8px rgba(245, 158, 11, 0.3);">
|
||||
🔒 Estás en HTTP. Para activar la cámara y pagos QR, tu celular requiere HTTPS:
|
||||
@@ -222,6 +424,13 @@
|
||||
<button onclick="toggleParentPanel(false)" style="background: none; border: none; font-size: 1.2rem; cursor: pointer; color: #64748b;">✕</button>
|
||||
</div>
|
||||
|
||||
<!-- SELECTOR DE HIJO PARA PADRES -->
|
||||
<div id="parentChildSelectorBox" style="display: none; margin-bottom: 14px; background: #e0f2fe; padding: 10px 12px; border-radius: 12px; border: 1.5px solid #bae6fd;">
|
||||
<label for="parentChildSelect" style="display: block; font-size: 0.76rem; font-weight: 800; color: #0369a1; margin-bottom: 4px;">🧒 Viendo información de:</label>
|
||||
<select id="parentChildSelect" onchange="onParentChildSelect(this.value)" style="width: 100%; padding: 8px 10px; border-radius: 8px; border: 1px solid #7dd3fc; font-weight: 800; color: #0c4a6e; background: white; font-size: 0.9rem;">
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- RECARGA SINPE MÓVIL (MONTO ESCRITO Y ACCESOS RÁPIDOS) -->
|
||||
<div style="background: #f0fdf4; border: 1.5px solid #86efac; border-radius: 14px; padding: 14px; margin-bottom: 16px;">
|
||||
<div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px;">
|
||||
@@ -305,6 +514,32 @@
|
||||
<input type="checkbox" id="chkParentAllowTransfer" onchange="onToggleAllowTransfer(this.checked)" style="width: 22px; height: 22px; cursor: pointer; accent-color: #0284c7;" checked>
|
||||
</div>
|
||||
|
||||
<!-- RESTABLECER PIN Y CONTRASEÑA ESCOLAR DEL ALUMNO -->
|
||||
<div style="background: #f8fafc; border: 1.5px dashed #cbd5e1; border-radius: 14px; padding: 14px; margin-bottom: 16px;">
|
||||
<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
|
||||
<span style="font-size: 1.2rem;">🔐</span>
|
||||
<div>
|
||||
<strong style="font-size: 0.88rem; color: #1e293b; display: block;">Seguridad y Contraseña del Alumno</strong>
|
||||
<span style="font-size: 0.72rem; color: #64748b;">Cambia el PIN de transferencias o la contraseña de acceso</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 10px;">
|
||||
<div>
|
||||
<label style="display: block; font-size: 0.74rem; font-weight: 800; color: #475569; margin-bottom: 3px;">Nuevo PIN (4 dígitos):</label>
|
||||
<input type="password" inputmode="numeric" maxlength="4" id="inputParentNewPin" placeholder="1234" style="width: 100%; padding: 8px; border-radius: 8px; border: 1.5px solid #cbd5e1; font-weight: 900; letter-spacing: 2px; text-align: center; box-sizing: border-box;">
|
||||
</div>
|
||||
<div>
|
||||
<label style="display: block; font-size: 0.74rem; font-weight: 800; color: #475569; margin-bottom: 3px;">Nueva Contraseña:</label>
|
||||
<input type="text" id="inputParentNewPass" placeholder="Ej: 1234" style="width: 100%; padding: 8px; border-radius: 8px; border: 1.5px solid #cbd5e1; font-weight: 800; box-sizing: border-box;">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button type="button" onclick="saveParentChildAccess()" style="width: 100%; padding: 10px; background: #334155; color: white; border: none; border-radius: 8px; font-weight: 800; font-size: 0.82rem; cursor: pointer;">
|
||||
💾 Guardar Nuevas Credenciales
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- HISTORIAL RECIENTE -->
|
||||
<h4 style="font-size: 0.85rem; font-weight: 800; color: #1e293b; margin-bottom: 8px;">Consumos Recientes</h4>
|
||||
<div id="parentHistoryList" style="max-height: 140px; overflow-y: auto; font-size: 0.78rem;">
|
||||
@@ -313,6 +548,72 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- MODAL: REGISTRAR NUEVO ESTUDIANTE (ADMIN) -->
|
||||
<div class="modal-qr-backdrop" id="modalNewStudent" style="display: none;" onclick="closeNewStudentModal(event)">
|
||||
<div class="modal-qr-card" onclick="event.stopPropagation()" style="max-width: 460px; text-align: left;">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #e2e8f0; padding-bottom: 10px; margin-bottom: 14px;">
|
||||
<div>
|
||||
<h3 style="color: #0f172a; font-size: 1.15rem; font-weight: 800;">Registrar Nuevo Alumno</h3>
|
||||
<span style="font-size: 0.75rem; color: #64748b;">Genera carné oficial y código QR al instante</span>
|
||||
</div>
|
||||
<button onclick="closeNewStudentModal()" style="background: none; border: none; font-size: 1.2rem; cursor: pointer; color: #64748b;">✕</button>
|
||||
</div>
|
||||
|
||||
<form id="formNewStudent" onsubmit="submitNewStudent(event)">
|
||||
<div style="margin-bottom: 10px;">
|
||||
<label style="display: block; font-size: 0.78rem; font-weight: 800; color: #334155; margin-bottom: 3px;">Nombre Completo:</label>
|
||||
<input type="text" id="newEstNombre" placeholder="Ej: Daniel Sánchez Méndez" required style="width: 100%; padding: 8px 10px; border-radius: 8px; border: 1.5px solid #cbd5e1; font-weight: 700; box-sizing: border-box;">
|
||||
</div>
|
||||
|
||||
<div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px; margin-bottom: 10px;">
|
||||
<div>
|
||||
<label style="display: block; font-size: 0.75rem; font-weight: 700; color: #334155; margin-bottom: 3px;">Edad:</label>
|
||||
<input type="number" id="newEstEdad" value="8" min="5" max="19" required style="width: 100%; padding: 8px; border-radius: 8px; border: 1.5px solid #cbd5e1; font-weight: 700; box-sizing: border-box;">
|
||||
</div>
|
||||
<div>
|
||||
<label style="display: block; font-size: 0.75rem; font-weight: 700; color: #334155; margin-bottom: 3px;">Grado:</label>
|
||||
<input type="text" id="newEstGrado" placeholder="Ej: 3° Grado" required style="width: 100%; padding: 8px; border-radius: 8px; border: 1.5px solid #cbd5e1; font-weight: 700; box-sizing: border-box;">
|
||||
</div>
|
||||
<div>
|
||||
<label style="display: block; font-size: 0.75rem; font-weight: 700; color: #334155; margin-bottom: 3px;">Sección:</label>
|
||||
<input type="text" id="newEstSeccion" placeholder="Ej: 3-B" required style="width: 100%; padding: 8px; border-radius: 8px; border: 1.5px solid #cbd5e1; font-weight: 700; box-sizing: border-box;">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 10px;">
|
||||
<div>
|
||||
<label style="display: block; font-size: 0.75rem; font-weight: 700; color: #334155; margin-bottom: 3px;">Saldo Inicial (₡):</label>
|
||||
<input type="tel" inputmode="numeric" id="newEstSaldo" value="2000" style="width: 100%; padding: 8px; border-radius: 8px; border: 1.5px solid #cbd5e1; font-weight: 700; box-sizing: border-box;">
|
||||
</div>
|
||||
<div>
|
||||
<label style="display: block; font-size: 0.75rem; font-weight: 700; color: #334155; margin-bottom: 3px;">Límite Diario (₡):</label>
|
||||
<input type="tel" inputmode="numeric" id="newEstLimite" value="2500" style="width: 100%; padding: 8px; border-radius: 8px; border: 1.5px solid #cbd5e1; font-weight: 700; box-sizing: border-box;">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="margin-bottom: 10px;">
|
||||
<label style="display: block; font-size: 0.75rem; font-weight: 700; color: #334155; margin-bottom: 3px;">Alergias o Restricciones Médicas:</label>
|
||||
<input type="text" id="newEstAlergias" placeholder="Ej: Ninguna conocida, Alergia al gluten..." style="width: 100%; padding: 8px; border-radius: 8px; border: 1.5px solid #cbd5e1; box-sizing: border-box;">
|
||||
</div>
|
||||
|
||||
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 14px;">
|
||||
<div>
|
||||
<label style="display: block; font-size: 0.75rem; font-weight: 700; color: #334155; margin-bottom: 3px;">Nombre del Padre:</label>
|
||||
<input type="text" id="newEstPadre" placeholder="Ej: Juan Sánchez" style="width: 100%; padding: 8px; border-radius: 8px; border: 1.5px solid #cbd5e1; box-sizing: border-box;">
|
||||
</div>
|
||||
<div>
|
||||
<label style="display: block; font-size: 0.75rem; font-weight: 700; color: #334155; margin-bottom: 3px;">Teléfono Padre:</label>
|
||||
<input type="text" id="newEstTel" placeholder="+506 8888-0000" style="width: 100%; padding: 8px; border-radius: 8px; border: 1.5px solid #cbd5e1; box-sizing: border-box;">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button type="submit" id="btnSubmitNewStudent" style="width: 100%; padding: 12px; background: linear-gradient(135deg, #0284c7, #0369a1); color: white; border: none; border-radius: 12px; font-weight: 900; font-size: 0.95rem; cursor: pointer;">
|
||||
✅ Guardar y Generar Carné
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- MODAL: RECREOTRANSFER (PASAR PLATA A UN COMPAÑERO ESCANEANDO SU QR O CARNÉ) -->
|
||||
<div class="modal-qr-backdrop" id="modalTransfer" style="display: none;" onclick="closeTransferModal(event)">
|
||||
<div class="modal-qr-card" onclick="event.stopPropagation()" style="max-width: 420px; text-align: left;">
|
||||
|
||||
+669
-38
@@ -1,12 +1,16 @@
|
||||
// RECREOPAY - LÓGICA DE CLIENTE PWA (ESTUDIANTES Y PADRES)
|
||||
// RECREOPAY - LÓGICA DE CLIENTE PWA (AUTENTICACIÓN, ADMIN, ESTUDIANTES Y PADRES)
|
||||
|
||||
let students = [];
|
||||
let currentUser = null;
|
||||
let currentStudent = null;
|
||||
let students = [];
|
||||
let categories = [];
|
||||
let products = [];
|
||||
let activeCategoryId = null;
|
||||
let cart = [];
|
||||
let currentAppMode = 'kids';
|
||||
let currentAppMode = 'teens';
|
||||
let adminProducts = [];
|
||||
let adminStats = null;
|
||||
let adminSearchQuery = '';
|
||||
|
||||
let CLOUDFLARE_TUNNEL_URL = 'https://recreopay.gammapos.app';
|
||||
|
||||
@@ -45,17 +49,157 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||
initTheme();
|
||||
checkHttpsEnvironment();
|
||||
|
||||
// Registrar Service Worker para PWA con forzado de actualizacion
|
||||
// Registrar Service Worker para PWA
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.register('/sw.js?v=5.0').then(reg => {
|
||||
navigator.serviceWorker.register('/sw.js?v=6.0').then(reg => {
|
||||
reg.update();
|
||||
}).catch(err => console.log('SW error:', err));
|
||||
}
|
||||
|
||||
await loadInitialData();
|
||||
// Verificar si hay sesión activa guardada
|
||||
const storedUser = localStorage.getItem('recreopay_user');
|
||||
if (storedUser) {
|
||||
try {
|
||||
currentUser = JSON.parse(storedUser);
|
||||
} catch (e) {
|
||||
currentUser = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (!currentUser) {
|
||||
// Mostrar pantalla de Login limpia (NO auto-login)
|
||||
showLoginView();
|
||||
} else {
|
||||
await applyUserRoleSession();
|
||||
}
|
||||
|
||||
initStudentSSE();
|
||||
});
|
||||
|
||||
// ==========================================
|
||||
// VISTA Y MANEJO DE AUTENTICACIÓN / SESIÓN
|
||||
// ==========================================
|
||||
|
||||
function showLoginView() {
|
||||
const viewLogin = document.getElementById('viewLogin');
|
||||
const viewAdmin = document.getElementById('viewAdmin');
|
||||
const appContainer = document.getElementById('appContainer');
|
||||
|
||||
if (viewLogin) viewLogin.style.display = 'flex';
|
||||
if (viewAdmin) viewAdmin.style.display = 'none';
|
||||
if (appContainer) appContainer.style.display = 'none';
|
||||
|
||||
// Cerrar cualquier modal que pudiera estar abierto
|
||||
toggleParentPanel(false);
|
||||
closeCartModal();
|
||||
closeQrModal();
|
||||
closeTransferModal();
|
||||
}
|
||||
|
||||
function quickFillLogin(username, password) {
|
||||
document.getElementById('loginUsername').value = username;
|
||||
document.getElementById('loginPassword').value = password;
|
||||
handleLoginSubmit();
|
||||
}
|
||||
|
||||
async function handleLoginSubmit(event) {
|
||||
if (event) event.preventDefault();
|
||||
const username = document.getElementById('loginUsername').value.trim();
|
||||
const password = document.getElementById('loginPassword').value.trim();
|
||||
const errorMsg = document.getElementById('loginErrorMsg');
|
||||
const submitBtn = document.getElementById('btnLoginSubmit');
|
||||
|
||||
if (!username || !password) {
|
||||
if (errorMsg) {
|
||||
errorMsg.textContent = 'Por favor ingresa tu usuario y contraseña';
|
||||
errorMsg.style.display = 'block';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (errorMsg) errorMsg.style.display = 'none';
|
||||
submitBtn.disabled = true;
|
||||
submitBtn.textContent = 'Verificando credenciales...';
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password })
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
throw new Error(data.error || 'Credenciales incorrectas');
|
||||
}
|
||||
|
||||
currentUser = {
|
||||
...data.user,
|
||||
estudiante: data.estudiante,
|
||||
hijos: data.hijos || []
|
||||
};
|
||||
localStorage.setItem('recreopay_user', JSON.stringify(currentUser));
|
||||
|
||||
if (window.sounds) window.sounds.playSuccess();
|
||||
await applyUserRoleSession();
|
||||
} catch (err) {
|
||||
if (errorMsg) {
|
||||
errorMsg.textContent = `❌ ${err.message}`;
|
||||
errorMsg.style.display = 'block';
|
||||
}
|
||||
if (window.sounds) window.sounds.playError();
|
||||
} finally {
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.innerHTML = '🚀 Iniciar Sesión';
|
||||
}
|
||||
}
|
||||
|
||||
async function applyUserRoleSession() {
|
||||
if (!currentUser) return showLoginView();
|
||||
|
||||
const viewLogin = document.getElementById('viewLogin');
|
||||
const viewAdmin = document.getElementById('viewAdmin');
|
||||
const appContainer = document.getElementById('appContainer');
|
||||
|
||||
if (viewLogin) viewLogin.style.display = 'none';
|
||||
|
||||
if (currentUser.rol === 'admin') {
|
||||
if (viewAdmin) viewAdmin.style.display = 'block';
|
||||
if (appContainer) appContainer.style.display = 'none';
|
||||
const adminNameEl = document.getElementById('adminLoggedName');
|
||||
if (adminNameEl) adminNameEl.textContent = `${currentUser.nombre} (Administrador)`;
|
||||
await loadAdminData();
|
||||
} else if (currentUser.rol === 'padre') {
|
||||
if (viewAdmin) viewAdmin.style.display = 'none';
|
||||
if (appContainer) appContainer.style.display = 'block';
|
||||
|
||||
await loadInitialData();
|
||||
setupParentPortalChildren();
|
||||
toggleParentPanel(true);
|
||||
} else {
|
||||
// Estudiante
|
||||
if (viewAdmin) viewAdmin.style.display = 'none';
|
||||
if (appContainer) appContainer.style.display = 'block';
|
||||
|
||||
await loadInitialData();
|
||||
if (currentUser.estudiante) {
|
||||
await selectStudent(currentUser.estudiante.id);
|
||||
} else if (students.length > 0) {
|
||||
await selectStudent(students[0].id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function logout() {
|
||||
if (confirm('¿Deseas cerrar la sesión en RecreoPay?')) {
|
||||
localStorage.removeItem('recreopay_user');
|
||||
currentUser = null;
|
||||
currentStudent = null;
|
||||
showLoginView();
|
||||
if (window.sounds) window.sounds.playTap();
|
||||
}
|
||||
}
|
||||
|
||||
async function loadInitialData() {
|
||||
try {
|
||||
// 1. Cargar estudiantes
|
||||
@@ -64,11 +208,6 @@ async function loadInitialData() {
|
||||
|
||||
populateStudentSelector();
|
||||
|
||||
// Seleccionar por defecto el primer estudiante (Mateo, 8 años -> Modo Kids)
|
||||
if (students.length > 0) {
|
||||
await selectStudent(students[0].id);
|
||||
}
|
||||
|
||||
// 2. Cargar productos y categorías
|
||||
const resProd = await fetch('/api/productos');
|
||||
const dataProd = await resProd.json();
|
||||
@@ -84,6 +223,7 @@ async function loadInitialData() {
|
||||
|
||||
function populateStudentSelector() {
|
||||
const sel = document.getElementById('studentSelector');
|
||||
if (!sel) return;
|
||||
sel.innerHTML = students.map(s => `
|
||||
<option value="${s.id}">
|
||||
${s.nombre_completo} (${s.edad} años - ${s.grado})
|
||||
@@ -114,7 +254,7 @@ function updateStudentUI() {
|
||||
document.getElementById('walletName').textContent = currentStudent.nombre_completo;
|
||||
document.getElementById('walletGrade').textContent = `${currentStudent.grado} • Sección ${currentStudent.seccion} • Cód: ${currentStudent.codigo_estudiante}`;
|
||||
|
||||
// Saldo en colones (Interfaz unificada estilo Teens)
|
||||
// Saldo en colones
|
||||
document.getElementById('walletBalance').textContent = `₡${currentStudent.saldo_colones.toLocaleString('es-CR')}`;
|
||||
document.getElementById('balanceLabel').textContent = 'SALDO DISPONIBLE';
|
||||
const coin = document.getElementById('kidsCoinIcon');
|
||||
@@ -128,6 +268,21 @@ function updateStudentUI() {
|
||||
document.getElementById('dailyLimitText').textContent = `₡${currentStudent.limite_diario_colones.toLocaleString('es-CR')}`;
|
||||
document.getElementById('dailyAvailableText').textContent = `Disponible hoy: ₡${currentStudent.disponible_hoy.toLocaleString('es-CR')}`;
|
||||
|
||||
// Alerta de Tarjeta Bloqueada
|
||||
const bannerBlocked = document.getElementById('bannerCardBlocked');
|
||||
if (bannerBlocked) {
|
||||
bannerBlocked.style.display = currentStudent.tarjeta_bloqueada ? 'flex' : 'none';
|
||||
}
|
||||
document.querySelectorAll('.qr-toggle-btn').forEach(btn => {
|
||||
if (currentStudent.tarjeta_bloqueada) {
|
||||
btn.style.opacity = '0.45';
|
||||
btn.style.pointerEvents = 'none';
|
||||
} else {
|
||||
btn.style.opacity = '1';
|
||||
btn.style.pointerEvents = 'auto';
|
||||
}
|
||||
});
|
||||
|
||||
// Alergias
|
||||
const allergyBox = document.getElementById('allergyWarning');
|
||||
if (currentStudent.alergias && currentStudent.alergias !== 'Ninguna' && currentStudent.alergias !== 'Ninguna conocida') {
|
||||
@@ -186,16 +341,10 @@ function toggleTheme() {
|
||||
if (window.sounds) window.sounds.playTap();
|
||||
}
|
||||
|
||||
function logout() {
|
||||
if (confirm('¿Deseas cerrar la sesión actual?')) {
|
||||
localStorage.removeItem('recreopay_session');
|
||||
window.location.reload();
|
||||
}
|
||||
}
|
||||
|
||||
// Renderizado de Categorías
|
||||
function renderCategories() {
|
||||
const bar = document.getElementById('categoriesBar');
|
||||
if (!bar) return;
|
||||
let html = `
|
||||
<button class="cat-pill ${activeCategoryId === null ? 'active' : ''}" onclick="selectCategory(null)">
|
||||
<span>✨</span> Todos
|
||||
@@ -218,10 +367,11 @@ function selectCategory(catId) {
|
||||
renderProducts();
|
||||
}
|
||||
|
||||
// Renderizado de Productos del Menú
|
||||
// Renderizado de Productos del Menú (Con soporte para Agotado / Greyed Out)
|
||||
function renderProducts() {
|
||||
const grid = document.getElementById('productsGrid');
|
||||
const filterMepOnly = document.getElementById('chkFilterMep').checked;
|
||||
if (!grid) return;
|
||||
const filterMepOnly = document.getElementById('chkFilterMep')?.checked || false;
|
||||
|
||||
let filtered = products;
|
||||
|
||||
@@ -243,23 +393,41 @@ function renderProducts() {
|
||||
return;
|
||||
}
|
||||
|
||||
grid.innerHTML = filtered.map(prod => `
|
||||
<div class="product-card">
|
||||
<div class="product-icon-wrap">${prod.icono || '🥪'}</div>
|
||||
<div>
|
||||
${prod.cumple_mep ? '<span class="badge-mep">🌿 MEP Saludable</span>' : ''}
|
||||
<h4 class="product-name">${prod.nombre}</h4>
|
||||
<p class="product-desc">${prod.descripcion || ''}</p>
|
||||
${prod.alergenos ? `<div style="font-size: 0.68rem; color: #dc2626; margin-bottom: 4px;">⚠️ Contiene: ${prod.alergenos}</div>` : ''}
|
||||
grid.innerHTML = filtered.map(prod => {
|
||||
const isOutOfStock = prod.control_stock === 1 && (prod.stock <= 0 || prod.disponible === 0);
|
||||
const stockBadge = prod.control_stock === 1
|
||||
? (isOutOfStock
|
||||
? '<span class="badge-out-of-stock">🚫 AGOTADO</span>'
|
||||
: `<span style="font-size: 0.68rem; font-weight: 800; color: #166534; background: #dcfce7; padding: 2px 6px; border-radius: 4px;">🟢 ${prod.stock} disponibles</span>`)
|
||||
: '';
|
||||
|
||||
return `
|
||||
<div class="product-card ${isOutOfStock ? 'out-of-stock' : ''}">
|
||||
<div class="product-icon-wrap">${prod.icono || '🥪'}</div>
|
||||
<div>
|
||||
<div style="display: flex; gap: 4px; flex-wrap: wrap; margin-bottom: 4px;">
|
||||
${prod.cumple_mep ? '<span class="badge-mep">🌿 MEP Saludable</span>' : ''}
|
||||
${stockBadge}
|
||||
</div>
|
||||
<h4 class="product-name">${prod.nombre}</h4>
|
||||
<p class="product-desc">${prod.descripcion || ''}</p>
|
||||
${prod.alergenos ? `<div style="font-size: 0.68rem; color: #dc2626; margin-bottom: 4px;">⚠️ Contiene: ${prod.alergenos}</div>` : ''}
|
||||
</div>
|
||||
<div class="product-footer">
|
||||
<span class="product-price">₡${prod.precio_colones.toLocaleString('es-CR')}</span>
|
||||
${isOutOfStock ? `
|
||||
<button class="add-btn" disabled style="opacity: 0.5; background: #94a3b8; cursor: not-allowed;" title="Producto Agotado">
|
||||
🚫
|
||||
</button>
|
||||
` : `
|
||||
<button class="add-btn" onclick="addToCart(${prod.id})" title="Agregar a mi pre-orden">
|
||||
+
|
||||
</button>
|
||||
`}
|
||||
</div>
|
||||
</div>
|
||||
<div class="product-footer">
|
||||
<span class="product-price">₡${prod.precio_colones.toLocaleString('es-CR')}</span>
|
||||
<button class="add-btn" onclick="addToCart(${prod.id})" title="Agregar a mi pre-orden">
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`).join('');
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
@@ -270,7 +438,18 @@ function addToCart(productId) {
|
||||
const prod = products.find(p => p.id === productId);
|
||||
if (!prod) return;
|
||||
|
||||
if (prod.control_stock === 1 && (prod.stock <= 0 || prod.disponible === 0)) {
|
||||
alert(`⚠️ El producto "${prod.nombre}" se encuentra agotado en la soda.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const existing = cart.find(item => item.product.id === productId);
|
||||
const currentInCart = existing ? existing.cantidad : 0;
|
||||
if (prod.control_stock === 1 && (currentInCart + 1) > prod.stock) {
|
||||
alert(`⚠️ Solo quedan ${prod.stock} unidad(es) de "${prod.nombre}" en inventario.`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (existing) {
|
||||
existing.cantidad++;
|
||||
} else {
|
||||
@@ -1054,7 +1233,7 @@ async function onToggleAllowTransfer(checked) {
|
||||
}
|
||||
}
|
||||
|
||||
// SSE en tiempo real para estudiantes (notificación si le pasan plata)
|
||||
// SSE en tiempo real para eventos de la soda y monederos
|
||||
function initStudentSSE() {
|
||||
const sse = new EventSource('/api/events');
|
||||
|
||||
@@ -1068,4 +1247,456 @@ function initStudentSSE() {
|
||||
}
|
||||
} catch (err) {}
|
||||
});
|
||||
|
||||
sse.addEventListener('recarga_exitosa', (e) => {
|
||||
try {
|
||||
const data = JSON.parse(e.data);
|
||||
if (currentStudent && data.estudiante_id === currentStudent.id) {
|
||||
if (window.sounds) window.sounds.playCoin();
|
||||
selectStudent(currentStudent.id);
|
||||
}
|
||||
if (currentUser && currentUser.rol === 'admin') {
|
||||
loadAdminData();
|
||||
}
|
||||
} catch (err) {}
|
||||
});
|
||||
|
||||
sse.addEventListener('producto_actualizado', (e) => {
|
||||
try {
|
||||
const prod = JSON.parse(e.data);
|
||||
// Actualizar en el catálogo de estudiantes
|
||||
const idx = products.findIndex(p => p.id === prod.id);
|
||||
if (idx !== -1) {
|
||||
products[idx] = { ...products[idx], ...prod };
|
||||
renderProducts();
|
||||
}
|
||||
// Actualizar en admin
|
||||
if (currentUser && currentUser.rol === 'admin') {
|
||||
const adminIdx = adminProducts.findIndex(p => p.id === prod.id);
|
||||
if (adminIdx !== -1) {
|
||||
adminProducts[adminIdx] = { ...adminProducts[adminIdx], ...prod };
|
||||
filterAdminProducts(adminSearchQuery);
|
||||
}
|
||||
}
|
||||
} catch (err) {}
|
||||
});
|
||||
|
||||
sse.addEventListener('estudiante_actualizado', (e) => {
|
||||
try {
|
||||
const data = JSON.parse(e.data);
|
||||
if (currentStudent && currentStudent.id === data.id) {
|
||||
selectStudent(currentStudent.id);
|
||||
}
|
||||
if (currentUser && currentUser.rol === 'admin') {
|
||||
loadAdminData();
|
||||
}
|
||||
} catch (err) {}
|
||||
});
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// FUNCIONES DEL PORTAL DE PADRES (HIJOS Y CREDENCIALES)
|
||||
// ==========================================
|
||||
|
||||
function setupParentPortalChildren() {
|
||||
const box = document.getElementById('parentChildSelectorBox');
|
||||
const sel = document.getElementById('parentChildSelect');
|
||||
if (!box || !sel) return;
|
||||
|
||||
if (currentUser && currentUser.hijos && currentUser.hijos.length > 0) {
|
||||
box.style.display = 'block';
|
||||
sel.innerHTML = currentUser.hijos.map(h => `
|
||||
<option value="${h.id}">${h.nombre_completo} (${h.grado} - Sección ${h.seccion})</option>
|
||||
`).join('');
|
||||
|
||||
onParentChildSelect(currentUser.hijos[0].id);
|
||||
} else if (students.length > 0) {
|
||||
box.style.display = 'block';
|
||||
sel.innerHTML = students.slice(0, 2).map(h => `
|
||||
<option value="${h.id}">${h.nombre_completo} (${h.grado} - Sección ${h.seccion})</option>
|
||||
`).join('');
|
||||
onParentChildSelect(students[0].id);
|
||||
}
|
||||
}
|
||||
|
||||
async function onParentChildSelect(studentId) {
|
||||
await selectStudent(studentId);
|
||||
}
|
||||
|
||||
async function saveParentChildAccess() {
|
||||
if (!currentStudent) return;
|
||||
const pin = document.getElementById('inputParentNewPin').value.trim();
|
||||
const pass = document.getElementById('inputParentNewPass').value.trim();
|
||||
|
||||
if (!pin && !pass) {
|
||||
alert('Ingresa al menos un nuevo PIN o una nueva contraseña para actualizar.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (pin && !/^\d{4}$/.test(pin)) {
|
||||
alert('El PIN debe contener exactamente 4 dígitos numéricos.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/padres/restablecer-acceso', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
estudiante_id: currentStudent.id,
|
||||
nuevo_pin: pin || undefined,
|
||||
nuevo_password: pass || undefined
|
||||
})
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error);
|
||||
|
||||
if (window.sounds) window.sounds.playSuccess();
|
||||
alert(`✅ ¡Credenciales actualizadas!\n${data.mensaje}`);
|
||||
document.getElementById('inputParentNewPin').value = '';
|
||||
document.getElementById('inputParentNewPass').value = '';
|
||||
} catch (err) {
|
||||
if (window.sounds) window.sounds.playError();
|
||||
alert(`❌ Error actualizando credenciales: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// PANEL DE ADMINISTRACIÓN DE LA SODA
|
||||
// ==========================================
|
||||
|
||||
function switchAdminTab(tabName) {
|
||||
const tabs = ['inventario', 'estudiantes', 'recarga'];
|
||||
tabs.forEach(t => {
|
||||
const btn = document.getElementById(`btnTabAdmin${t.charAt(0).toUpperCase() + t.slice(1)}`);
|
||||
const content = document.getElementById(`adminTabContent${t.charAt(0).toUpperCase() + t.slice(1)}`);
|
||||
if (btn) btn.classList.toggle('active', t === tabName);
|
||||
if (content) content.style.display = (t === tabName) ? 'block' : 'none';
|
||||
});
|
||||
|
||||
if (window.sounds) window.sounds.playTap();
|
||||
}
|
||||
|
||||
async function loadAdminData() {
|
||||
try {
|
||||
// 1. Cargar resumen y métricas
|
||||
const resResumen = await fetch('/api/admin/resumen');
|
||||
adminStats = await resResumen.json();
|
||||
|
||||
document.getElementById('adminStatVentas').textContent = `₡${adminStats.ventas_hoy.toLocaleString('es-CR')}`;
|
||||
document.getElementById('adminStatOrdenes').textContent = adminStats.ordenes_hoy;
|
||||
document.getElementById('adminStatEstudiantes').textContent = adminStats.estudiantes_activos;
|
||||
document.getElementById('adminStatBloqueados').textContent = adminStats.tarjetas_bloqueadas;
|
||||
document.getElementById('adminStatCriticos').textContent = adminStats.productos_bajo_stock;
|
||||
|
||||
// 2. Cargar productos de inventario
|
||||
const resProd = await fetch('/api/admin/productos');
|
||||
adminProducts = await resProd.json();
|
||||
renderAdminInventory(adminProducts);
|
||||
|
||||
// 3. Cargar estudiantes
|
||||
const resEst = await fetch('/api/estudiantes');
|
||||
students = await resEst.json();
|
||||
renderAdminStudents(students);
|
||||
populateAdminRecargaStudents(students);
|
||||
} catch (err) {
|
||||
console.error('Error cargando datos de administración:', err);
|
||||
}
|
||||
}
|
||||
|
||||
function filterAdminProducts(query) {
|
||||
adminSearchQuery = (query || '').toLowerCase().trim();
|
||||
let list = adminProducts;
|
||||
if (adminSearchQuery) {
|
||||
list = list.filter(p => p.nombre.toLowerCase().includes(adminSearchQuery) || (p.categoria_nombre && p.categoria_nombre.toLowerCase().includes(adminSearchQuery)));
|
||||
}
|
||||
renderAdminInventory(list);
|
||||
}
|
||||
|
||||
function renderAdminInventory(list) {
|
||||
const container = document.getElementById('adminProductsList');
|
||||
if (!container) return;
|
||||
|
||||
if (!list || list.length === 0) {
|
||||
container.innerHTML = `
|
||||
<div style="text-align: center; padding: 24px; color: var(--text-muted);">
|
||||
No se encontraron productos en el inventario.
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
container.innerHTML = list.map(p => {
|
||||
const isOutOfStock = p.control_stock === 1 && (p.stock <= 0 || p.disponible === 0);
|
||||
const isLowStock = p.control_stock === 1 && p.stock > 0 && p.stock <= 3;
|
||||
|
||||
let statusPill = '';
|
||||
if (p.control_stock === 0) {
|
||||
statusPill = `<span style="font-size: 0.7rem; font-weight: 800; color: #0284c7; background: #e0f2fe; padding: 3px 8px; border-radius: 6px;">Ilimitado</span>`;
|
||||
} else if (isOutOfStock) {
|
||||
statusPill = `<span style="font-size: 0.7rem; font-weight: 900; color: #ef4444; background: #fee2e2; padding: 3px 8px; border-radius: 6px;">🚫 AGOTADO</span>`;
|
||||
} else if (isLowStock) {
|
||||
statusPill = `<span style="font-size: 0.7rem; font-weight: 800; color: #d97706; background: #fef3c7; padding: 3px 8px; border-radius: 6px;">⚠️ Quedan ${p.stock}</span>`;
|
||||
} else {
|
||||
statusPill = `<span style="font-size: 0.7rem; font-weight: 800; color: #166534; background: #dcfce7; padding: 3px 8px; border-radius: 6px;">🟢 ${p.stock} unid.</span>`;
|
||||
}
|
||||
|
||||
return `
|
||||
<div class="inventory-item-row" style="${isOutOfStock ? 'background: #fff1f2;' : ''}">
|
||||
<div style="font-size: 1.8rem; text-align: center;">${p.icono || '🥪'}</div>
|
||||
<div>
|
||||
<div style="display: flex; align-items: center; gap: 6px; flex-wrap: wrap;">
|
||||
<strong style="font-size: 0.92rem; color: var(--text-main);">${p.nombre}</strong>
|
||||
${statusPill}
|
||||
</div>
|
||||
<div style="font-size: 0.74rem; color: var(--text-muted); margin-top: 2px;">
|
||||
${p.categoria_nombre || 'General'} • ₡${p.precio_colones.toLocaleString('es-CR')}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Controles rápidos de stock -->
|
||||
<div class="inventory-stock-controls">
|
||||
<button type="button" class="stock-btn-quick" onclick="quickAdjustStock(${p.id}, -1)" title="Restar 1">-1</button>
|
||||
<input type="number" id="inputStock_${p.id}" value="${p.stock || 0}" min="0" style="width: 54px; text-align: center; padding: 5px; border-radius: 8px; border: 1.5px solid var(--border); font-weight: 900; font-size: 0.95rem; background: var(--card-bg); color: var(--text-main);">
|
||||
<button type="button" class="stock-btn-quick" onclick="quickAdjustStock(${p.id}, 5)" title="Sumar 5">+5</button>
|
||||
<button type="button" class="stock-btn-quick" onclick="quickAdjustStock(${p.id}, 10)" title="Sumar 10">+10</button>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<button type="button" onclick="saveProductStock(${p.id})" style="padding: 7px 12px; background: #0284c7; color: white; border: none; border-radius: 8px; font-size: 0.78rem; font-weight: 800; cursor: pointer;">
|
||||
💾 Guardar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
async function quickAdjustStock(prodId, delta) {
|
||||
try {
|
||||
const res = await fetch(`/api/admin/productos/${prodId}/ajuste-rapido`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ delta })
|
||||
});
|
||||
if (!res.ok) throw new Error('Error ajustando stock');
|
||||
if (window.sounds) window.sounds.playCoin();
|
||||
await loadAdminData();
|
||||
} catch (err) {
|
||||
alert(`Error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function saveProductStock(prodId) {
|
||||
const input = document.getElementById(`inputStock_${prodId}`);
|
||||
if (!input) return;
|
||||
const nuevoStock = parseInt(input.value, 10);
|
||||
if (isNaN(nuevoStock) || nuevoStock < 0) {
|
||||
alert('Ingresa una cantidad de stock válida.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/admin/productos/${prodId}/stock`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ stock: nuevoStock, control_stock: 1 })
|
||||
});
|
||||
if (!res.ok) throw new Error('Error guardando stock');
|
||||
if (window.sounds) window.sounds.playSuccess();
|
||||
await loadAdminData();
|
||||
} catch (err) {
|
||||
alert(`Error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function renderAdminStudents(list) {
|
||||
const container = document.getElementById('adminStudentsList');
|
||||
if (!container) return;
|
||||
|
||||
if (!list || list.length === 0) {
|
||||
container.innerHTML = `<div style="text-align: center; padding: 20px; color: var(--text-muted);">No hay estudiantes registrados.</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
container.innerHTML = `
|
||||
<div style="display: flex; flex-direction: column; gap: 10px;">
|
||||
${list.map(s => {
|
||||
const isBlocked = s.tarjeta_bloqueada === 1;
|
||||
return `
|
||||
<div style="display: flex; align-items: center; justify-content: space-between; padding: 12px; border-radius: 12px; border: 1.5px solid ${isBlocked ? '#fca5a5' : 'var(--border)'}; background: ${isBlocked ? '#fff5f5' : 'var(--card-bg)'}; flex-wrap: wrap; gap: 10px;">
|
||||
<div style="display: flex; align-items: center; gap: 12px;">
|
||||
<img src="${s.foto_url || 'https://api.dicebear.com/7.x/bottts/svg?seed=est'}" style="width: 44px; height: 44px; border-radius: 50%; border: 2px solid ${isBlocked ? '#ef4444' : '#0284c7'}; background: white;">
|
||||
<div>
|
||||
<div style="display: flex; align-items: center; gap: 8px;">
|
||||
<strong style="font-size: 0.95rem; color: var(--text-main);">${s.nombre_completo}</strong>
|
||||
${isBlocked ? '<span style="font-size: 0.68rem; font-weight: 900; background: #ef4444; color: white; padding: 2px 7px; border-radius: 5px;">⛔ SUSPENDIDA</span>' : '<span style="font-size: 0.68rem; font-weight: 800; background: #dcfce7; color: #166534; padding: 2px 7px; border-radius: 5px;">ACTIVA</span>'}
|
||||
</div>
|
||||
<div style="font-size: 0.75rem; color: var(--text-muted); margin-top: 2px;">
|
||||
${s.grado} • Sección ${s.seccion} • Cód: <strong>${s.codigo_estudiante}</strong> • PIN: <strong>${s.pin_seguridad || '1234'}</strong>
|
||||
</div>
|
||||
<div style="font-size: 0.78rem; font-weight: 800; color: #0284c7; margin-top: 3px;">
|
||||
Saldo: ₡${s.saldo_colones.toLocaleString('es-CR')} | Límite: ₡${s.limite_diario_colones.toLocaleString('es-CR')}/día
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; gap: 8px; align-items: center;">
|
||||
<a href="/carnet.html" target="_blank" style="padding: 7px 10px; background: #e0f2fe; color: #0369a1; border-radius: 8px; font-size: 0.76rem; font-weight: 800; text-decoration: none;" title="Ver e Imprimir Carné Físico">
|
||||
🖨️ Carné
|
||||
</a>
|
||||
<button type="button" onclick="toggleBlockCard(${s.id}, ${isBlocked ? 0 : 1})" style="padding: 7px 12px; background: ${isBlocked ? '#10b981' : '#ef4444'}; color: white; border: none; border-radius: 8px; font-size: 0.78rem; font-weight: 900; cursor: pointer;">
|
||||
${isBlocked ? '✅ Desbloquear' : '⛔ Bloquear Tarjeta'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('')}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
async function toggleBlockCard(studentId, newBlocked) {
|
||||
const actionText = newBlocked ? 'bloquear la tarjeta de este estudiante' : 'desbloquear la tarjeta';
|
||||
if (!confirm(`¿Estás seguro de que deseas ${actionText}?`)) return;
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/admin/estudiantes/${studentId}/bloquear`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ tarjeta_bloqueada: newBlocked })
|
||||
});
|
||||
if (!res.ok) throw new Error('Error actualizando estado de tarjeta');
|
||||
|
||||
if (window.sounds) window.sounds.playCoin();
|
||||
await loadAdminData();
|
||||
} catch (err) {
|
||||
alert(`Error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function openNewStudentModal() {
|
||||
const modal = document.getElementById('modalNewStudent');
|
||||
if (modal) modal.style.display = 'flex';
|
||||
}
|
||||
|
||||
function closeNewStudentModal(event) {
|
||||
if (event && event.target !== event.currentTarget) return;
|
||||
const modal = document.getElementById('modalNewStudent');
|
||||
if (modal) modal.style.display = 'none';
|
||||
}
|
||||
|
||||
async function submitNewStudent(event) {
|
||||
if (event) event.preventDefault();
|
||||
|
||||
const nombre = document.getElementById('newEstNombre').value.trim();
|
||||
const edad = parseInt(document.getElementById('newEstEdad').value, 10);
|
||||
const grado = document.getElementById('newEstGrado').value.trim();
|
||||
const seccion = document.getElementById('newEstSeccion').value.trim();
|
||||
const saldo = parseInt(document.getElementById('newEstSaldo').value, 10) || 0;
|
||||
const limite = parseInt(document.getElementById('newEstLimite').value, 10) || 3000;
|
||||
const alergias = document.getElementById('newEstAlergias').value.trim();
|
||||
const padre = document.getElementById('newEstPadre').value.trim();
|
||||
const tel = document.getElementById('newEstTel').value.trim();
|
||||
|
||||
const btn = document.getElementById('btnSubmitNewStudent');
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Creando alumno y carné...';
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/admin/estudiantes', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
nombre_completo: nombre,
|
||||
edad,
|
||||
grado,
|
||||
seccion,
|
||||
saldo_inicial: saldo,
|
||||
limite_diario_colones: limite,
|
||||
alergias,
|
||||
padre_nombre: padre,
|
||||
padre_telefono: tel
|
||||
})
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error);
|
||||
|
||||
if (window.sounds) window.sounds.playSuccess();
|
||||
alert(`🎉 ¡Estudiante Creado con Éxito!\nNombre: ${data.nombre_completo}\nCódigo: ${data.codigo_estudiante}\nQR Token: ${data.qr_token}`);
|
||||
|
||||
closeNewStudentModal();
|
||||
document.getElementById('formNewStudent').reset();
|
||||
await loadAdminData();
|
||||
} catch (err) {
|
||||
if (window.sounds) window.sounds.playError();
|
||||
alert(`❌ Error al crear estudiante: ${err.message}`);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = '✅ Guardar y Generar Carné';
|
||||
}
|
||||
}
|
||||
|
||||
function populateAdminRecargaStudents(list) {
|
||||
const sel = document.getElementById('adminRecargaStudentSelect');
|
||||
if (!sel) return;
|
||||
sel.innerHTML = list.map(s => `
|
||||
<option value="${s.id}">${s.nombre_completo} (Saldo actual: ₡${s.saldo_colones.toLocaleString('es-CR')})</option>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
function setAdminRecargaPreset(amt) {
|
||||
const input = document.getElementById('adminRecargaMonto');
|
||||
if (input) input.value = amt;
|
||||
}
|
||||
|
||||
async function submitAdminManualRecharge() {
|
||||
const sel = document.getElementById('adminRecargaStudentSelect');
|
||||
const inputMonto = document.getElementById('adminRecargaMonto');
|
||||
const inputDesc = document.getElementById('adminRecargaDescripcion');
|
||||
const btn = document.getElementById('btnAdminSubmitRecarga');
|
||||
|
||||
if (!sel || !inputMonto) return;
|
||||
|
||||
const studentId = parseInt(sel.value, 10);
|
||||
const monto = parseInt(inputMonto.value, 10);
|
||||
const descripcion = inputDesc ? inputDesc.value.trim() : '';
|
||||
|
||||
if (isNaN(monto) || monto <= 0) {
|
||||
alert('Ingresa un monto válido mayor a ₡0 para recargar.');
|
||||
return;
|
||||
}
|
||||
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Procesando recarga en caja...';
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/admin/estudiantes/${studentId}/recarga-manual`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
monto,
|
||||
descripcion,
|
||||
metodo: 'Efectivo en mostrador'
|
||||
})
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error);
|
||||
|
||||
if (window.sounds) window.sounds.playSuccess();
|
||||
alert(`💰 ${data.mensaje}\nNuevo Saldo: ₡${data.saldo_nuevo.toLocaleString('es-CR')}`);
|
||||
|
||||
inputMonto.value = '';
|
||||
if (inputDesc) inputDesc.value = '';
|
||||
await loadAdminData();
|
||||
} catch (err) {
|
||||
if (window.sounds) window.sounds.playError();
|
||||
alert(`❌ Error al recargar: ${err.message}`);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = '<span>💰</span> Aplicar Recarga Inmediata';
|
||||
}
|
||||
}
|
||||
|
||||
+23
-1
@@ -438,7 +438,24 @@ function renderScannedStudent() {
|
||||
}
|
||||
|
||||
document.getElementById('scannedAvatar').src = scannedStudent.foto_url;
|
||||
document.getElementById('scannedName').textContent = scannedStudent.nombre_completo;
|
||||
|
||||
const btnCobrar = document.getElementById('btnCobrarPos');
|
||||
if (scannedStudent.tarjeta_bloqueada) {
|
||||
document.getElementById('scannedName').innerHTML = `${scannedStudent.nombre_completo} <span style="font-size: 0.72rem; color: #fee2e2; background: #dc2626; padding: 2px 7px; border-radius: 6px; font-weight: 900; margin-left: 6px;">⛔ TARJETA SUSPENDIDA</span>`;
|
||||
if (btnCobrar) {
|
||||
btnCobrar.disabled = true;
|
||||
btnCobrar.textContent = '⛔ Tarjeta Suspendida';
|
||||
btnCobrar.style.background = '#64748b';
|
||||
}
|
||||
} else {
|
||||
document.getElementById('scannedName').textContent = scannedStudent.nombre_completo;
|
||||
if (btnCobrar) {
|
||||
btnCobrar.disabled = false;
|
||||
btnCobrar.textContent = 'Cobrar y Despachar ⚡';
|
||||
btnCobrar.style.background = 'linear-gradient(135deg, #10b981, #059669)';
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('scannedGrade').textContent = `${scannedStudent.grado} • Sección ${scannedStudent.seccion} • Cód: ${scannedStudent.codigo_estudiante}`;
|
||||
document.getElementById('scannedBalance').textContent = `₡${scannedStudent.saldo_colones.toLocaleString('es-CR')}`;
|
||||
document.getElementById('scannedAvailable').textContent = `₡${scannedStudent.disponible_hoy.toLocaleString('es-CR')}`;
|
||||
@@ -466,6 +483,11 @@ async function executePosDebit() {
|
||||
return alert('⚠️ Primero escanea el carné o celular del estudiante (puedes usar los botones de prueba rápida en la cámara).');
|
||||
}
|
||||
|
||||
if (scannedStudent.tarjeta_bloqueada) {
|
||||
if (window.sounds) window.sounds.playError();
|
||||
return alert(`⛔ ¡TARJETA SUSPENDIDA!\nLa tarjeta de ${scannedStudent.nombre_completo} ha sido bloqueada por la administración de la soda. No se pueden procesar cobros.`);
|
||||
}
|
||||
|
||||
if (posCart.length === 0) {
|
||||
if (window.sounds) window.sounds.playError();
|
||||
return alert('⚠️ Selecciona al menos un producto en el mostrador para cobrar.');
|
||||
|
||||
+57
-7
@@ -112,14 +112,41 @@ function initDatabase() {
|
||||
|
||||
db.exec(schema);
|
||||
|
||||
// Migración segura para permitir_transferencias en bases de datos existentes
|
||||
try {
|
||||
db.exec('ALTER TABLE estudiantes ADD COLUMN permitir_transferencias INTEGER DEFAULT 1');
|
||||
} catch (e) {
|
||||
// Ya existe la columna
|
||||
}
|
||||
// Migraciones seguras para bases de datos existentes
|
||||
try { db.exec('ALTER TABLE estudiantes ADD COLUMN permitir_transferencias INTEGER DEFAULT 1'); } catch (e) {}
|
||||
try { db.exec('ALTER TABLE estudiantes ADD COLUMN tarjeta_bloqueada INTEGER DEFAULT 0'); } catch (e) {}
|
||||
try { db.exec('ALTER TABLE estudiantes ADD COLUMN padre_usuario_id INTEGER'); } catch (e) {}
|
||||
try { db.exec('ALTER TABLE productos ADD COLUMN control_stock INTEGER DEFAULT 1'); } catch (e) {}
|
||||
try { db.exec('ALTER TABLE productos ADD COLUMN stock INTEGER DEFAULT 10'); } catch (e) {}
|
||||
try { db.exec('UPDATE productos SET control_stock = 1 WHERE control_stock IS NULL OR control_stock = 0'); } catch (e) {}
|
||||
try { db.exec('UPDATE productos SET stock = 10 WHERE stock IS NULL'); } catch (e) {}
|
||||
|
||||
seedInitialData();
|
||||
seedUsuarios();
|
||||
}
|
||||
|
||||
function seedUsuarios() {
|
||||
const count = db.prepare('SELECT COUNT(*) as count FROM usuarios').get().count;
|
||||
if (count === 0) {
|
||||
console.log('👤 Creando usuarios iniciales de demostración en RecreoPay...');
|
||||
const insert = db.prepare('INSERT INTO usuarios (username, password_hash, rol, nombre, telefono, email) VALUES (?, ?, ?, ?, ?, ?)');
|
||||
|
||||
// 1. Admin de la Soda
|
||||
insert.run('admin', 'admin123', 'admin', 'Administrador de la Soda', '+506 8888-7632', '[email protected]');
|
||||
|
||||
// 2. Padre de Mateo
|
||||
const resPadre = insert.run('padre', 'padre123', 'padre', 'Carlos Alvarado (Papá)', '+506 8888-1122', '[email protected]');
|
||||
|
||||
// 3. Estudiantes
|
||||
const resMateo = insert.run('mateo', '1234', 'estudiante', 'Mateo Alvarado Castro', '', '');
|
||||
const resSofia = insert.run('sofia', '1234', 'estudiante', 'Sofía Jiménez Morales', '', '');
|
||||
|
||||
// Vincular Mateo con su usuario y su padre
|
||||
try {
|
||||
db.prepare('UPDATE estudiantes SET usuario_id = ?, padre_usuario_id = ? WHERE id = 1').run(resMateo.lastInsertRowid, resPadre.lastInsertRowid);
|
||||
db.prepare('UPDATE estudiantes SET usuario_id = ? WHERE id = 2').run(resSofia.lastInsertRowid);
|
||||
} catch (e) {}
|
||||
}
|
||||
}
|
||||
|
||||
function seedInitialData() {
|
||||
@@ -274,6 +301,9 @@ function debitoCompraTransaction({ estudianteId, montoTotal, ordenId, descripcio
|
||||
const est = db.prepare('SELECT * FROM estudiantes WHERE id = ?').get(estudianteId);
|
||||
if (!est) throw new Error('Estudiante no encontrado');
|
||||
if (!est.activo) throw new Error('La cuenta del estudiante se encuentra inactiva');
|
||||
if (est.tarjeta_bloqueada) {
|
||||
throw new Error('⛔ Tarjeta suspendida por la administración de la soda.');
|
||||
}
|
||||
|
||||
// 2. Verificar saldo
|
||||
if (est.saldo_colones < montoTotal) {
|
||||
@@ -389,6 +419,12 @@ function crearOrdenCompleta({ estudianteId, tipoOrden, momentoEntrega, notas, it
|
||||
if (!prod.disponible) throw new Error(`El producto "${prod.nombre}" no está disponible en este momento`);
|
||||
|
||||
const cantidad = parseInt(item.cantidad, 10) || 1;
|
||||
if (prod.control_stock === 1) {
|
||||
if (prod.stock < cantidad) {
|
||||
throw new Error(`Existencias insuficientes para "${prod.nombre}". Quedan ${prod.stock} unidad(es) en inventario.`);
|
||||
}
|
||||
}
|
||||
|
||||
const subtotal = prod.precio_colones * cantidad;
|
||||
totalColones += subtotal;
|
||||
|
||||
@@ -427,7 +463,7 @@ function crearOrdenCompleta({ estudianteId, tipoOrden, momentoEntrega, notas, it
|
||||
|
||||
const ordenId = resultOrden.lastInsertRowid;
|
||||
|
||||
// Insertar detalle de productos
|
||||
// Insertar detalle de productos y descontar inventario
|
||||
const insertDetalle = db.prepare(`
|
||||
INSERT INTO orden_detalles (orden_id, producto_id, cantidad, precio_unitario, subtotal)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
@@ -435,6 +471,14 @@ function crearOrdenCompleta({ estudianteId, tipoOrden, momentoEntrega, notas, it
|
||||
|
||||
for (const det of detallesParaInsertar) {
|
||||
insertDetalle.run(ordenId, det.producto_id, det.cantidad, det.precio_unitario, det.subtotal);
|
||||
|
||||
// Descontar inventario si tiene control de stock activo
|
||||
const prod = db.prepare('SELECT control_stock, stock FROM productos WHERE id = ?').get(det.producto_id);
|
||||
if (prod && prod.control_stock === 1) {
|
||||
const nuevoStock = Math.max(0, prod.stock - det.cantidad);
|
||||
const sigueDisponible = nuevoStock > 0 ? 1 : 0;
|
||||
db.prepare('UPDATE productos SET stock = ?, disponible = ? WHERE id = ?').run(nuevoStock, sigueDisponible, det.producto_id);
|
||||
}
|
||||
}
|
||||
|
||||
// Efectuar débito financiero
|
||||
@@ -471,6 +515,9 @@ function transferenciaP2PTransaction({ emisorId, qrReceptor, receptorId, monto,
|
||||
const emisor = db.prepare('SELECT * FROM estudiantes WHERE id = ?').get(emisorId);
|
||||
if (!emisor) throw new Error('Estudiante emisor no encontrado');
|
||||
if (!emisor.activo) throw new Error('Tu cuenta se encuentra inactiva');
|
||||
if (emisor.tarjeta_bloqueada) {
|
||||
throw new Error('⛔ Tarjeta suspendida por la administración de la soda. No puedes transferir.');
|
||||
}
|
||||
if (emisor.permitir_transferencias === 0) {
|
||||
throw new Error('Tus padres tienen desactivadas las transferencias entre compañeros en tu perfil');
|
||||
}
|
||||
@@ -499,6 +546,9 @@ function transferenciaP2PTransaction({ emisorId, qrReceptor, receptorId, monto,
|
||||
if (!receptor.activo) {
|
||||
throw new Error(`La cuenta de ${receptor.nombre_completo} se encuentra inactiva`);
|
||||
}
|
||||
if (receptor.tarjeta_bloqueada) {
|
||||
throw new Error(`⛔ La tarjeta de ${receptor.nombre_completo} está suspendida y no puede recibir transferencias.`);
|
||||
}
|
||||
if (emisor.id === receptor.id) {
|
||||
throw new Error('No puedes transferirte saldo a ti mismo');
|
||||
}
|
||||
|
||||
+338
-1
@@ -46,6 +46,344 @@ app.get('/api/events', (req, res) => {
|
||||
req.on('close', () => sseClients.delete(res));
|
||||
});
|
||||
|
||||
// ==========================================
|
||||
// 0. AUTENTICACIÓN Y ROLES (ADMIN, PADRE, ESTUDIANTE)
|
||||
// ==========================================
|
||||
|
||||
app.post('/api/auth/login', (req, res) => {
|
||||
try {
|
||||
const { username, password } = req.body;
|
||||
if (!username || !password) {
|
||||
return res.status(400).json({ error: 'Ingresa usuario y contraseña' });
|
||||
}
|
||||
|
||||
const cleanUser = String(username).trim().toLowerCase();
|
||||
const cleanPass = String(password).trim();
|
||||
|
||||
const user = db.prepare('SELECT * FROM usuarios WHERE LOWER(username) = ?').get(cleanUser);
|
||||
if (!user || user.password_hash !== cleanPass) {
|
||||
return res.status(401).json({ error: 'Usuario o contraseña incorrectos' });
|
||||
}
|
||||
|
||||
let estudiante = null;
|
||||
let hijos = [];
|
||||
|
||||
if (user.rol === 'estudiante') {
|
||||
estudiante = db.prepare('SELECT * FROM estudiantes WHERE usuario_id = ?').get(user.id);
|
||||
if (!estudiante) {
|
||||
estudiante = db.prepare('SELECT * FROM estudiantes WHERE LOWER(nombre_completo) LIKE ?').get(`%${cleanUser}%`);
|
||||
}
|
||||
if (!estudiante) {
|
||||
estudiante = db.prepare('SELECT * FROM estudiantes ORDER BY id ASC LIMIT 1').get();
|
||||
}
|
||||
} else if (user.rol === 'padre') {
|
||||
hijos = db.prepare('SELECT * FROM estudiantes WHERE padre_usuario_id = ?').all(user.id);
|
||||
if (hijos.length === 0) {
|
||||
hijos = db.prepare('SELECT * FROM estudiantes WHERE id IN (1, 2)').all();
|
||||
}
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
user: {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
rol: user.rol,
|
||||
nombre: user.nombre,
|
||||
email: user.email,
|
||||
telefono: user.telefono
|
||||
},
|
||||
estudiante,
|
||||
hijos
|
||||
});
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Restablecer contraseña / PIN del estudiante desde el portal de padres
|
||||
app.post('/api/padres/restablecer-acceso', (req, res) => {
|
||||
try {
|
||||
const { estudiante_id, nuevo_pin, nuevo_password } = req.body;
|
||||
const est = db.prepare('SELECT * FROM estudiantes WHERE id = ?').get(estudiante_id);
|
||||
if (!est) return res.status(404).json({ error: 'Estudiante no encontrado' });
|
||||
|
||||
if (nuevo_pin) {
|
||||
db.prepare('UPDATE estudiantes SET pin_seguridad = ? WHERE id = ?').run(String(nuevo_pin).trim(), est.id);
|
||||
}
|
||||
|
||||
if (nuevo_password && est.usuario_id) {
|
||||
db.prepare('UPDATE usuarios SET password_hash = ? WHERE id = ?').run(String(nuevo_password).trim(), est.usuario_id);
|
||||
}
|
||||
|
||||
res.json({ success: true, mensaje: 'Contraseña y PIN escolar actualizados con éxito' });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// ==========================================
|
||||
// ENDPOINTS DE ADMINISTRACIÓN DE LA SODA
|
||||
// ==========================================
|
||||
|
||||
// Métricas y Resumen Ejecutivo
|
||||
app.get('/api/admin/resumen', (req, res) => {
|
||||
try {
|
||||
const ventasHoy = db.prepare(`
|
||||
SELECT COALESCE(SUM(total_colones), 0) as total, COUNT(*) as cantidad
|
||||
FROM ordenes
|
||||
WHERE date(creado_en, 'localtime') = date('now', 'localtime')
|
||||
`).get();
|
||||
|
||||
const statsEst = db.prepare(`
|
||||
SELECT
|
||||
COUNT(*) as total_estudiantes,
|
||||
COALESCE(SUM(CASE WHEN tarjeta_bloqueada = 1 THEN 1 ELSE 0 END), 0) as tarjetas_bloqueadas,
|
||||
COALESCE(SUM(saldo_colones), 0) as saldo_total
|
||||
FROM estudiantes WHERE activo = 1
|
||||
`).get();
|
||||
|
||||
const productosBajoStock = db.prepare(`
|
||||
SELECT COUNT(*) as count
|
||||
FROM productos
|
||||
WHERE control_stock = 1 AND (stock <= 3 OR disponible = 0)
|
||||
`).get().count;
|
||||
|
||||
res.json({
|
||||
ventas_hoy: ventasHoy.total,
|
||||
ordenes_hoy: ventasHoy.cantidad,
|
||||
estudiantes_activos: statsEst.total_estudiantes,
|
||||
tarjetas_bloqueadas: statsEst.tarjetas_bloqueadas,
|
||||
saldo_total_estudiantes: statsEst.saldo_total,
|
||||
productos_bajo_stock: productosBajoStock
|
||||
});
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Listado de inventario para admin
|
||||
app.get('/api/admin/productos', (req, res) => {
|
||||
try {
|
||||
const productos = db.prepare(`
|
||||
SELECT p.*, c.nombre as categoria_nombre, c.icono as categoria_icono
|
||||
FROM productos p
|
||||
JOIN categorias c ON p.categoria_id = c.id
|
||||
ORDER BY p.categoria_id, p.nombre
|
||||
`).all();
|
||||
res.json(productos);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Actualizar stock y control
|
||||
app.put('/api/admin/productos/:id/stock', (req, res) => {
|
||||
try {
|
||||
const { stock, control_stock, disponible, precio_colones } = req.body;
|
||||
const prodId = req.params.id;
|
||||
|
||||
const prod = db.prepare('SELECT * FROM productos WHERE id = ?').get(prodId);
|
||||
if (!prod) return res.status(404).json({ error: 'Producto no encontrado' });
|
||||
|
||||
const nuevoStock = stock !== undefined ? parseInt(stock, 10) : prod.stock;
|
||||
const nuevoControl = control_stock !== undefined ? (control_stock ? 1 : 0) : prod.control_stock;
|
||||
const nuevoPrecio = precio_colones !== undefined ? parseInt(precio_colones, 10) : prod.precio_colones;
|
||||
|
||||
let nuevoDisponible = disponible !== undefined ? (disponible ? 1 : 0) : prod.disponible;
|
||||
if (nuevoControl === 1 && nuevoStock <= 0) {
|
||||
nuevoDisponible = 0;
|
||||
} else if (nuevoControl === 1 && nuevoStock > 0 && disponible === undefined) {
|
||||
nuevoDisponible = 1;
|
||||
}
|
||||
|
||||
db.prepare(`
|
||||
UPDATE productos
|
||||
SET stock = ?, control_stock = ?, disponible = ?, precio_colones = ?
|
||||
WHERE id = ?
|
||||
`).run(nuevoStock, nuevoControl, nuevoDisponible, nuevoPrecio, prodId);
|
||||
|
||||
const actualizado = db.prepare(`
|
||||
SELECT p.*, c.nombre as categoria_nombre, c.icono as categoria_icono
|
||||
FROM productos p
|
||||
JOIN categorias c ON p.categoria_id = c.id
|
||||
WHERE p.id = ?
|
||||
`).get(prodId);
|
||||
|
||||
broadcastEvent('producto_actualizado', actualizado);
|
||||
res.json(actualizado);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Ajuste rápido de stock (+5, +10, -1)
|
||||
app.post('/api/admin/productos/:id/ajuste-rapido', (req, res) => {
|
||||
try {
|
||||
const { delta } = req.body;
|
||||
const prodId = req.params.id;
|
||||
|
||||
const prod = db.prepare('SELECT * FROM productos WHERE id = ?').get(prodId);
|
||||
if (!prod) return res.status(404).json({ error: 'Producto no encontrado' });
|
||||
|
||||
const nuevoStock = Math.max(0, (prod.stock || 0) + parseInt(delta, 10));
|
||||
const nuevoDisponible = nuevoStock > 0 ? 1 : 0;
|
||||
|
||||
db.prepare(`
|
||||
UPDATE productos
|
||||
SET stock = ?, disponible = ?, control_stock = 1
|
||||
WHERE id = ?
|
||||
`).run(nuevoStock, nuevoDisponible, prodId);
|
||||
|
||||
const actualizado = db.prepare(`
|
||||
SELECT p.*, c.nombre as categoria_nombre, c.icono as categoria_icono
|
||||
FROM productos p
|
||||
JOIN categorias c ON p.categoria_id = c.id
|
||||
WHERE p.id = ?
|
||||
`).get(prodId);
|
||||
|
||||
broadcastEvent('producto_actualizado', actualizado);
|
||||
res.json(actualizado);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Crear nuevo estudiante + carné QR
|
||||
app.post('/api/admin/estudiantes', (req, res) => {
|
||||
try {
|
||||
const { nombre_completo, edad, grado, seccion, saldo_inicial, limite_diario_colones, alergias, pin_seguridad, padre_nombre, padre_telefono } = req.body;
|
||||
|
||||
if (!nombre_completo || !grado || !seccion) {
|
||||
return res.status(400).json({ error: 'Nombre completo, grado y sección son obligatorios' });
|
||||
}
|
||||
|
||||
const count = db.prepare('SELECT COUNT(*) as count FROM estudiantes').get().count + 1;
|
||||
const codigoEstudiante = `EST-2026-${String(count).padStart(3, '0')}`;
|
||||
|
||||
const primerNombre = nombre_completo.trim().split(' ')[0].toUpperCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
|
||||
const randomHex = Math.random().toString(16).substring(2, 6).toUpperCase();
|
||||
const qrToken = `QR-${primerNombre}-2026-${randomHex}`;
|
||||
|
||||
const pin = pin_seguridad ? String(pin_seguridad).trim() : '1234';
|
||||
const saldo = parseInt(saldo_inicial, 10) || 0;
|
||||
const limite = parseInt(limite_diario_colones, 10) || 3000;
|
||||
const edadNum = parseInt(edad, 10) || 8;
|
||||
const foto = `https://api.dicebear.com/7.x/bottts/svg?seed=${encodeURIComponent(primerNombre)}&backgroundColor=b6e3f4`;
|
||||
|
||||
const resEst = 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)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 0, 1)
|
||||
`).run(
|
||||
codigoEstudiante,
|
||||
nombre_completo.trim(),
|
||||
edadNum,
|
||||
grado.trim(),
|
||||
seccion.trim(),
|
||||
qrToken,
|
||||
pin,
|
||||
foto,
|
||||
saldo,
|
||||
limite,
|
||||
alergias || 'Ninguna conocida',
|
||||
padre_nombre || '',
|
||||
padre_telefono || ''
|
||||
);
|
||||
|
||||
const nuevoId = resEst.lastInsertRowid;
|
||||
|
||||
// Crear cuenta de usuario estudiante
|
||||
const usernameEst = primerNombre.toLowerCase() + count;
|
||||
try {
|
||||
const userRes = db.prepare(`
|
||||
INSERT INTO usuarios (username, password_hash, rol, nombre, email, telefono)
|
||||
VALUES (?, ?, 'estudiante', ?, '', '')
|
||||
`).run(usernameEst, pin, nombre_completo.trim());
|
||||
db.prepare('UPDATE estudiantes SET usuario_id = ? WHERE id = ?').run(userRes.lastInsertRowid, nuevoId);
|
||||
} catch (e) {}
|
||||
|
||||
// Si tiene saldo inicial, registrar en movimientos
|
||||
if (saldo > 0) {
|
||||
db.prepare(`
|
||||
INSERT INTO transacciones_saldo
|
||||
(estudiante_id, tipo, monto_colones, saldo_previo, saldo_posterior, descripcion)
|
||||
VALUES (?, 'recarga_manual', ?, 0, ?, 'Saldo inicial asignado por administración')
|
||||
`).run(nuevoId, saldo, saldo);
|
||||
}
|
||||
|
||||
const creado = db.prepare('SELECT * FROM estudiantes WHERE id = ?').get(nuevoId);
|
||||
broadcastEvent('estudiante_creado', creado);
|
||||
|
||||
res.status(201).json(creado);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Bloquear / Desbloquear tarjeta de estudiante
|
||||
app.put('/api/admin/estudiantes/:id/bloquear', (req, res) => {
|
||||
try {
|
||||
const { tarjeta_bloqueada } = req.body;
|
||||
const estId = req.params.id;
|
||||
|
||||
const est = db.prepare('SELECT * FROM estudiantes WHERE id = ?').get(estId);
|
||||
if (!est) return res.status(404).json({ error: 'Estudiante no encontrado' });
|
||||
|
||||
const nuevoEstado = tarjeta_bloqueada ? 1 : 0;
|
||||
db.prepare('UPDATE estudiantes SET tarjeta_bloqueada = ? WHERE id = ?').run(nuevoEstado, estId);
|
||||
|
||||
const actualizado = db.prepare('SELECT * FROM estudiantes WHERE id = ?').get(estId);
|
||||
broadcastEvent('estudiante_actualizado', actualizado);
|
||||
|
||||
res.json(actualizado);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Recarga manual de saldo en efectivo/soda
|
||||
app.post('/api/admin/estudiantes/:id/recarga-manual', (req, res) => {
|
||||
try {
|
||||
const { monto, descripcion, metodo } = req.body;
|
||||
const estudianteId = parseInt(req.params.id, 10);
|
||||
const montoColones = parseInt(monto, 10);
|
||||
|
||||
if (isNaN(montoColones) || montoColones <= 0) {
|
||||
return res.status(400).json({ error: 'El monto a cargar debe ser mayor a ₡0' });
|
||||
}
|
||||
|
||||
const est = db.prepare('SELECT * FROM estudiantes WHERE id = ?').get(estudianteId);
|
||||
if (!est) return res.status(404).json({ error: 'Estudiante no encontrado' });
|
||||
|
||||
const nuevoSaldo = est.saldo_colones + montoColones;
|
||||
db.prepare('UPDATE estudiantes SET saldo_colones = ? WHERE id = ?').run(nuevoSaldo, estudianteId);
|
||||
|
||||
const descFinal = descripcion || `Carga en efectivo en la soda escolar (${metodo || 'Caja'})`;
|
||||
|
||||
db.prepare(`
|
||||
INSERT INTO transacciones_saldo
|
||||
(estudiante_id, tipo, monto_colones, saldo_previo, saldo_posterior, comprobante_sinpe, descripcion)
|
||||
VALUES (?, 'recarga_manual', ?, ?, ?, 'CAJA-SODA', ?)
|
||||
`).run(estudianteId, montoColones, est.saldo_colones, nuevoSaldo, descFinal);
|
||||
|
||||
const resultado = {
|
||||
exito: true,
|
||||
estudiante_id: est.id,
|
||||
nombre: est.nombre_completo,
|
||||
monto: montoColones,
|
||||
saldo_anterior: est.saldo_colones,
|
||||
saldo_nuevo: nuevoSaldo,
|
||||
mensaje: `¡Se cargaron ₡${montoColones.toLocaleString('es-CR')} al monedero de ${est.nombre_completo}!`
|
||||
};
|
||||
|
||||
broadcastEvent('recarga_exitosa', resultado);
|
||||
res.json(resultado);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// ==========================================
|
||||
// 1. ESTUDIANTES Y QR
|
||||
// ==========================================
|
||||
@@ -251,7 +589,6 @@ app.get('/api/productos', (req, res) => {
|
||||
SELECT p.*, c.nombre as categoria_nombre, c.icono as categoria_icono
|
||||
FROM productos p
|
||||
JOIN categorias c ON p.categoria_id = c.id
|
||||
WHERE p.disponible = 1
|
||||
ORDER BY p.categoria_id, p.nombre
|
||||
`).all();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user