feat: portal dedicado de padres sin modal, registro con vinculacion QR, buscador inteligente y recarga por QR en admin
This commit is contained in:
@@ -1593,3 +1593,243 @@ body.dark-mode .pwa-bottom-nav {
|
|||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ==========================================================================
|
||||||
|
PESTAÑAS DE LOGIN / REGISTRO
|
||||||
|
========================================================================== */
|
||||||
|
.login-tabs {
|
||||||
|
display: flex;
|
||||||
|
background: #f1f5f9;
|
||||||
|
padding: 4px;
|
||||||
|
border-radius: 14px;
|
||||||
|
margin-bottom: 18px;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
body.dark-mode .login-tabs {
|
||||||
|
background: #0f172a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-tab-btn {
|
||||||
|
flex: 1;
|
||||||
|
padding: 9px 8px;
|
||||||
|
border: none;
|
||||||
|
background: transparent;
|
||||||
|
color: #64748b;
|
||||||
|
font-weight: 800;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
border-radius: 10px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-tab-btn.active {
|
||||||
|
background: #ffffff;
|
||||||
|
color: #0284c7;
|
||||||
|
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
|
||||||
|
}
|
||||||
|
|
||||||
|
body.dark-mode .login-tab-btn.active {
|
||||||
|
background: #1e293b;
|
||||||
|
color: #38bdf8;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ==========================================================================
|
||||||
|
PORTAL DEDICADO DE PADRES (#viewPadres)
|
||||||
|
========================================================================== */
|
||||||
|
.parent-container {
|
||||||
|
max-width: 600px;
|
||||||
|
margin: 0 auto;
|
||||||
|
min-height: 100vh;
|
||||||
|
width: 100%;
|
||||||
|
padding: calc(14px + var(--safe-top)) 16px calc(90px + var(--safe-bottom)) 16px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.parent-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 16px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.parent-badge {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.parent-icon {
|
||||||
|
font-size: 1.8rem;
|
||||||
|
background: #f0fdf4;
|
||||||
|
padding: 8px;
|
||||||
|
border-radius: 12px;
|
||||||
|
border: 1px solid #bbf7d0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.parent-header-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.parent-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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Tarjetas de Hijos Vinculados */
|
||||||
|
.parent-children-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
|
||||||
|
gap: 10px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.parent-child-card {
|
||||||
|
border: 2px solid var(--border, #e2e8f0);
|
||||||
|
border-radius: 16px;
|
||||||
|
padding: 12px;
|
||||||
|
background: var(--card-bg, #ffffff);
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
position: relative;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.parent-child-card:hover {
|
||||||
|
transform: translateY(-2px);
|
||||||
|
box-shadow: 0 4px 12px rgba(2, 132, 199, 0.12);
|
||||||
|
}
|
||||||
|
|
||||||
|
.parent-child-card.selected {
|
||||||
|
border-color: #0284c7;
|
||||||
|
background: #f0f9ff;
|
||||||
|
box-shadow: 0 4px 12px rgba(2, 132, 199, 0.18);
|
||||||
|
}
|
||||||
|
|
||||||
|
body.dark-mode .parent-child-card.selected {
|
||||||
|
background: rgba(2, 132, 199, 0.15);
|
||||||
|
border-color: #38bdf8;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Buscador Inteligente en Admin Carga */
|
||||||
|
.admin-search-container {
|
||||||
|
position: relative;
|
||||||
|
margin-bottom: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-search-input-wrap {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-search-input {
|
||||||
|
flex: 1;
|
||||||
|
padding: 11px 14px;
|
||||||
|
border-radius: 12px;
|
||||||
|
border: 1.5px solid var(--border, #cbd5e1);
|
||||||
|
font-size: 0.95rem;
|
||||||
|
font-weight: 700;
|
||||||
|
background: var(--card-bg, #ffffff);
|
||||||
|
color: var(--text-main, #0f172a);
|
||||||
|
outline: none;
|
||||||
|
transition: border 0.15s;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-search-input:focus {
|
||||||
|
border-color: #0284c7;
|
||||||
|
box-shadow: 0 0 0 3px rgba(2, 132, 199, 0.15);
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-scan-btn {
|
||||||
|
padding: 11px 14px;
|
||||||
|
background: linear-gradient(135deg, #0284c7, #0369a1);
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
border-radius: 12px;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
font-weight: 800;
|
||||||
|
cursor: pointer;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
white-space: nowrap;
|
||||||
|
box-shadow: 0 2px 8px rgba(2, 132, 199, 0.3);
|
||||||
|
transition: transform 0.1s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-scan-btn:active {
|
||||||
|
transform: scale(0.97);
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-search-dropdown {
|
||||||
|
position: absolute;
|
||||||
|
top: 100%;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
background: var(--card-bg, #ffffff);
|
||||||
|
border: 1.5px solid #0284c7;
|
||||||
|
border-radius: 14px;
|
||||||
|
max-height: 250px;
|
||||||
|
overflow-y: auto;
|
||||||
|
z-index: 50;
|
||||||
|
box-shadow: 0 12px 28px rgba(0, 0, 0, 0.18);
|
||||||
|
margin-top: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-search-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
border-bottom: 1px solid var(--border, #f1f5f9);
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background 0.15s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-search-item:last-child {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-search-item:hover, .admin-search-item:active {
|
||||||
|
background: #f0f9ff;
|
||||||
|
}
|
||||||
|
|
||||||
|
body.dark-mode .admin-search-item:hover {
|
||||||
|
background: rgba(2, 132, 199, 0.15);
|
||||||
|
}
|
||||||
|
|
||||||
|
.selected-student-banner {
|
||||||
|
background: #f8fafc;
|
||||||
|
border: 2px solid #0284c7;
|
||||||
|
border-radius: 16px;
|
||||||
|
padding: 12px 14px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 10px;
|
||||||
|
box-shadow: 0 2px 8px rgba(2, 132, 199, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
body.dark-mode .selected-student-banner {
|
||||||
|
background: rgba(30, 41, 59, 0.6);
|
||||||
|
border-color: #38bdf8;
|
||||||
|
}
|
||||||
|
|
||||||
|
|||||||
+330
-8
@@ -10,7 +10,7 @@
|
|||||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
||||||
<meta name="apple-mobile-web-app-title" content="RecreoPay">
|
<meta name="apple-mobile-web-app-title" content="RecreoPay">
|
||||||
<meta name="mobile-web-app-capable" content="yes">
|
<meta name="mobile-web-app-capable" content="yes">
|
||||||
<link rel="stylesheet" href="/css/styles.css?v=7.0">
|
<link rel="stylesheet" href="/css/styles.css?v=8.0">
|
||||||
<style>
|
<style>
|
||||||
/* Transiciones suaves */
|
/* Transiciones suaves */
|
||||||
.fade-enter { animation: fadeIn 0.2s ease-in-out; }
|
.fade-enter { animation: fadeIn 0.2s ease-in-out; }
|
||||||
@@ -28,6 +28,17 @@
|
|||||||
<p class="login-subtitle">Sistema Digital de Soda Escolar y Monedero Estudiantil</p>
|
<p class="login-subtitle">Sistema Digital de Soda Escolar y Monedero Estudiantil</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- SELECTOR ENTRE INICIO DE SESIÓN Y REGISTRO -->
|
||||||
|
<div class="login-tabs">
|
||||||
|
<button type="button" class="login-tab-btn active" id="tabBtnLogin" onclick="switchLoginTab('login')">
|
||||||
|
🔑 Iniciar Sesión
|
||||||
|
</button>
|
||||||
|
<button type="button" class="login-tab-btn" id="tabBtnRegister" onclick="switchLoginTab('register')">
|
||||||
|
👨👩👦 Registro de Padres
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- FORMULARIO 1: INICIAR SESIÓN -->
|
||||||
<form id="formLogin" onsubmit="handleLoginSubmit(event)">
|
<form id="formLogin" onsubmit="handleLoginSubmit(event)">
|
||||||
<div class="login-form-group">
|
<div class="login-form-group">
|
||||||
<label for="loginUsername">Usuario o Carné:</label>
|
<label for="loginUsername">Usuario o Carné:</label>
|
||||||
@@ -46,6 +57,35 @@
|
|||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
|
<!-- FORMULARIO 2: REGISTRO DE NUEVOS PADRES -->
|
||||||
|
<form id="formRegisterPadre" onsubmit="handleRegisterPadreSubmit(event)" style="display: none;">
|
||||||
|
<div class="login-form-group">
|
||||||
|
<label for="regNombre">Nombre y Apellidos:</label>
|
||||||
|
<input type="text" id="regNombre" class="login-input" placeholder="Ej: Carlos Alvarado Castro" required autocomplete="name">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="login-form-group">
|
||||||
|
<label for="regTelefono">Teléfono o Celular (para SINPE):</label>
|
||||||
|
<input type="tel" id="regTelefono" class="login-input" placeholder="Ej: 8888-1122" required autocomplete="tel">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="login-form-group">
|
||||||
|
<label for="regUsername">Nombre de Usuario:</label>
|
||||||
|
<input type="text" id="regUsername" class="login-input" placeholder="Ej: carlos_papa" required autocomplete="username">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="login-form-group">
|
||||||
|
<label for="regPassword">Contraseña:</label>
|
||||||
|
<input type="password" id="regPassword" class="login-input" placeholder="Mínimo 4 caracteres" required autocomplete="new-password">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="registerErrorMsg" 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="btnRegisterSubmit" class="login-submit-btn" style="background: linear-gradient(135deg, #10b981, #059669);">
|
||||||
|
✨ Crear Cuenta y Entrar al Panel
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
<!-- ACCESOS RÁPIDOS DE PRUEBA (1-CLICK DEMO) -->
|
<!-- ACCESOS RÁPIDOS DE PRUEBA (1-CLICK DEMO) -->
|
||||||
<div class="login-demo-box">
|
<div class="login-demo-box">
|
||||||
<div class="login-demo-title">Accesos Rápidos de Prueba:</div>
|
<div class="login-demo-title">Accesos Rápidos de Prueba:</div>
|
||||||
@@ -176,14 +216,48 @@
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- BUSCADOR INTELIGENTE Y BOTÓN ESCANEAR QR -->
|
||||||
<div style="margin-bottom: 14px;">
|
<div style="margin-bottom: 14px;">
|
||||||
<label style="display: block; font-size: 0.8rem; font-weight: 800; color: var(--text-main); margin-bottom: 5px;">
|
<label style="display: block; font-size: 0.8rem; font-weight: 800; color: var(--text-main); margin-bottom: 6px;">
|
||||||
Selecciona al Estudiante:
|
Buscar Estudiante por Nombre, Apellidos o Carné:
|
||||||
</label>
|
</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);">
|
<div class="admin-search-container">
|
||||||
<!-- Opciones de estudiantes -->
|
<div class="admin-search-input-wrap">
|
||||||
</select>
|
<div style="position: relative; flex: 1;">
|
||||||
|
<input type="text" id="inputAdminSearchStudent" class="admin-search-input" placeholder="🔍 Escribe para buscar (ej: Mateo, EST-2026, Alvarado)..." oninput="onAdminSearchStudent(this.value)" autocomplete="off">
|
||||||
|
<button type="button" id="btnClearAdminSearch" onclick="clearAdminSearchStudent()" style="display: none; position: absolute; right: 10px; top: 50%; transform: translateY(-50%); background: none; border: none; font-size: 1rem; color: #94a3b8; cursor: pointer;">✕</button>
|
||||||
</div>
|
</div>
|
||||||
|
<button type="button" onclick="openAdminScanQrModal()" class="admin-scan-btn" title="Escanear carné físico o código QR con la cámara">
|
||||||
|
<span>📷</span>
|
||||||
|
<span>Escanear QR</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div id="adminSearchResultsDropdown" class="admin-search-dropdown" style="display: none;"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- FICHA DEL ESTUDIANTE SELECCIONADO -->
|
||||||
|
<div id="adminSelectedStudentBanner" class="selected-student-banner" style="display: none;">
|
||||||
|
<div style="display: flex; align-items: center; gap: 10px; min-width: 0; flex: 1;">
|
||||||
|
<img id="adminSelectedAvatar" src="" style="width: 44px; height: 44px; border-radius: 50%; border: 2px solid #0284c7; background: white; flex-shrink: 0; object-fit: cover;">
|
||||||
|
<div style="min-width: 0;">
|
||||||
|
<div style="display: flex; align-items: center; gap: 6px; flex-wrap: wrap;">
|
||||||
|
<strong id="adminSelectedName" style="font-size: 0.95rem; color: var(--text-main); word-break: break-word;">Selecciona un alumno</strong>
|
||||||
|
<span id="adminSelectedStatusBadge" style="font-size: 0.65rem; font-weight: 800; background: #dcfce7; color: #166534; padding: 2px 6px; border-radius: 4px;">ACTIVA</span>
|
||||||
|
</div>
|
||||||
|
<div id="adminSelectedMeta" style="font-size: 0.74rem; color: var(--text-muted); margin-top: 2px;">
|
||||||
|
Grado y Sección • Cód: EST-2026-000
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div style="text-align: right; flex-shrink: 0;">
|
||||||
|
<div style="font-size: 0.68rem; font-weight: 800; color: var(--text-muted); text-transform: uppercase;">Saldo Actual</div>
|
||||||
|
<div id="adminSelectedBalance" style="font-size: 1.15rem; font-weight: 900; color: #10b981;">₡0</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- SELECT OCULTO PARA COMPATIBILIDAD CON FUNCIONES JS -->
|
||||||
|
<select id="adminRecargaStudentSelect" style="display: none;" onchange="onAdminSelectChange(this.value)"></select>
|
||||||
|
|
||||||
<div style="margin-bottom: 12px;">
|
<div style="margin-bottom: 12px;">
|
||||||
<label style="display: block; font-size: 0.8rem; font-weight: 800; color: var(--text-main); margin-bottom: 5px;">
|
<label style="display: block; font-size: 0.8rem; font-weight: 800; color: var(--text-main); margin-bottom: 5px;">
|
||||||
@@ -215,6 +289,205 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- ========================================== -->
|
||||||
|
<!-- PORTAL COMPLETO DE PADRES (#viewPadres) -->
|
||||||
|
<!-- ========================================== -->
|
||||||
|
<div id="viewPadres" class="parent-container" style="display: none;">
|
||||||
|
<!-- CABECERA DE PADRES -->
|
||||||
|
<header class="parent-header">
|
||||||
|
<div class="parent-badge">
|
||||||
|
<div class="parent-icon">👨👩👦</div>
|
||||||
|
<div>
|
||||||
|
<h2 style="font-size: 1.15rem; font-weight: 900; margin: 0; color: var(--text-main);">Portal de Padres</h2>
|
||||||
|
<span id="parentLoggedName" style="font-size: 0.76rem; color: #10b981; font-weight: 700;">Familia RecreoPay</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="parent-header-actions">
|
||||||
|
<button onclick="toggleTheme()" class="theme-toggle-btn" title="Alternar Modo Oscuro / Modo Claro">
|
||||||
|
🌙
|
||||||
|
</button>
|
||||||
|
<button type="button" onclick="switchToSodaMenuAsParent()" class="mode-btn" style="background: var(--bg-main); border: 1.5px solid var(--border); font-size: 0.78rem; font-weight: 800; border-radius: 10px; padding: 7px 11px; cursor: pointer; color: var(--text-main);" title="Ver menú y pre-ordenar para mi hijo">
|
||||||
|
🥪 Ver Menú
|
||||||
|
</button>
|
||||||
|
<button onclick="logout(true)" class="logout-btn" title="Cerrar sesión">
|
||||||
|
<span>🚪</span>
|
||||||
|
<span class="logout-text">Salir</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<!-- BANNER SI NO HAY HIJOS VINCULADOS -->
|
||||||
|
<div id="parentNoChildrenBanner" class="parent-card" style="display: none; text-align: center; border: 2px dashed #0284c7; background: #f0f9ff;">
|
||||||
|
<span style="font-size: 2.5rem;">🧒</span>
|
||||||
|
<h3 style="font-size: 1.15rem; font-weight: 900; color: #0369a1; margin: 8px 0 4px 0;">¡Bienvenido a RecreoPay!</h3>
|
||||||
|
<p style="font-size: 0.82rem; color: #64748b; margin-bottom: 14px;">
|
||||||
|
Aún no has vinculado ningún estudiante a tu cuenta de padre. Escanea el carné de tu hijo para monitorear su saldo y recargarle al instante.
|
||||||
|
</p>
|
||||||
|
<button type="button" onclick="openScanChildQrModal()" class="login-submit-btn" style="background: linear-gradient(135deg, #0284c7, #0369a1); display: inline-flex; align-items: center; justify-content: center; gap: 8px; width: auto; padding: 12px 24px;">
|
||||||
|
<span>📷</span> Escanear Carné QR de mi Hijo
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- SECCIÓN: MIS HIJOS (TARJETAS VISUALES) -->
|
||||||
|
<div id="parentChildrenSection" style="margin-bottom: 16px;">
|
||||||
|
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
|
||||||
|
<h3 style="font-size: 0.92rem; font-weight: 900; color: var(--text-main); text-transform: uppercase; letter-spacing: 0.5px;">
|
||||||
|
👨👩👦 Mis Hijos
|
||||||
|
</h3>
|
||||||
|
<button type="button" onclick="openScanChildQrModal()" style="background: none; border: none; color: #0284c7; font-size: 0.8rem; font-weight: 800; cursor: pointer; display: flex; align-items: center; gap: 4px;">
|
||||||
|
<span>➕</span> Vincular otro hijo con QR
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Cuadrícula de tarjetas de hijos -->
|
||||||
|
<div id="parentChildrenGrid" class="parent-children-grid">
|
||||||
|
<!-- Renderizado dinámico de tarjetas de hijos -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- SECCIÓN DE GESTIÓN DEL HIJO SELECCIONADO -->
|
||||||
|
<div id="parentSelectedChildContainer" style="display: none;">
|
||||||
|
<!-- FICHA ACTIVA DEL HIJO SELECCIONADO -->
|
||||||
|
<div class="parent-card" style="border: 2px solid #0284c7; background: linear-gradient(135deg, rgba(2, 132, 199, 0.04), rgba(56, 189, 248, 0.08));">
|
||||||
|
<div style="display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 14px;">
|
||||||
|
<div style="display: flex; align-items: center; gap: 12px; min-width: 0;">
|
||||||
|
<img id="parentActiveChildAvatar" src="" style="width: 50px; height: 50px; border-radius: 50%; border: 3px solid #0284c7; background: white; object-fit: cover;">
|
||||||
|
<div style="min-width: 0;">
|
||||||
|
<h3 id="parentActiveChildName" style="font-size: 1.1rem; font-weight: 900; margin: 0; color: var(--text-main); word-break: break-word;">Cargando...</h3>
|
||||||
|
<span id="parentActiveChildMeta" style="font-size: 0.76rem; color: var(--text-muted); font-weight: 600;">Grado • Carné</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div style="text-align: right;">
|
||||||
|
<span style="font-size: 0.7rem; font-weight: 800; color: var(--text-muted); text-transform: uppercase; display: block;">Saldo Disponible</span>
|
||||||
|
<span id="parentActiveChildBalance" style="font-size: 1.35rem; font-weight: 900; color: #0284c7;">₡0</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="display: flex; gap: 8px; flex-wrap: wrap;">
|
||||||
|
<button type="button" onclick="switchToSodaMenuAsParent()" style="flex: 1; padding: 9px; background: #0284c7; color: white; border: none; border-radius: 10px; font-weight: 800; font-size: 0.8rem; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 6px;">
|
||||||
|
<span>🥪</span> Pre-ordenar Merienda
|
||||||
|
</button>
|
||||||
|
<a id="btnParentViewCarnet" href="/carnet.html" target="_blank" style="padding: 9px 12px; background: #f1f5f9; color: #1e293b; border: 1px solid #cbd5e1; border-radius: 10px; font-weight: 800; font-size: 0.8rem; text-decoration: none; display: flex; align-items: center; gap: 4px;">
|
||||||
|
<span>🖨️</span> Ver Carné QR
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- RECARGA SINPE MÓVIL (DIRECTO EN PANTALLA, NO MODAL) -->
|
||||||
|
<div class="parent-card" style="background: #f0fdf4; border: 1.5px solid #86efac;">
|
||||||
|
<div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px;">
|
||||||
|
<div style="display: flex; align-items: center; gap: 10px;">
|
||||||
|
<span style="font-size: 1.6rem;">📱</span>
|
||||||
|
<div>
|
||||||
|
<strong style="color: #166534; font-size: 1rem; display: block;">Recarga por SINPE Móvil</strong>
|
||||||
|
<p style="font-size: 0.74rem; color: #15803d; margin: 0;">Número Soda: <strong>8888-SODA (7632)</strong></p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<span style="font-size: 0.7rem; color: #166534; background: #dcfce7; font-weight: 800; padding: 3px 8px; border-radius: 6px;">Inmediato</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<label style="display: block; font-size: 0.8rem; font-weight: 800; color: #166534; margin-bottom: 4px;">
|
||||||
|
Monto a recargar en colones:
|
||||||
|
</label>
|
||||||
|
<div style="position: relative; margin-bottom: 8px;">
|
||||||
|
<span style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); font-weight: 900; color: #166534; font-size: 1.15rem;">₡</span>
|
||||||
|
<input type="tel" inputmode="numeric" pattern="[0-9]*" id="inputParentSinpeMonto" placeholder="Ej: 3000" style="width: 100%; padding: 11px 12px 11px 32px; border-radius: 10px; border: 1.5px solid #86efac; font-size: 1.2rem; font-weight: 900; color: #166534; background: white; box-sizing: border-box;">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; margin-bottom: 12px;">
|
||||||
|
<button type="button" onclick="setParentSinpePreset(1000)" class="stock-btn-quick" style="border-color: #86efac; color: #166534;">₡1.000</button>
|
||||||
|
<button type="button" onclick="setParentSinpePreset(2000)" class="stock-btn-quick" style="border-color: #86efac; color: #166534;">₡2.000</button>
|
||||||
|
<button type="button" onclick="setParentSinpePreset(5000)" class="stock-btn-quick" style="border-color: #86efac; color: #166534;">₡5.000</button>
|
||||||
|
<button type="button" onclick="setParentSinpePreset(10000)" class="stock-btn-quick" style="border-color: #86efac; color: #166534;">₡10.000</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button type="button" onclick="executeParentSinpeRecharge()" style="width: 100%; padding: 13px; background: linear-gradient(135deg, #16a34a, #15803d); color: white; border: none; border-radius: 12px; font-weight: 900; font-size: 0.95rem; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 8px; box-shadow: 0 4px 10px rgba(22, 163, 74, 0.3);">
|
||||||
|
<span>📲</span> Aplicar Recarga de Saldo
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- CONFIGURACIÓN DE LÍMITE DIARIO -->
|
||||||
|
<div class="parent-card" style="background: #f0f9ff; border: 2px solid #38bdf8;">
|
||||||
|
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
|
||||||
|
<div>
|
||||||
|
<strong style="font-size: 0.95rem; color: #0369a1; display: block;">🛡️ Límite de Gasto Máximo Diario</strong>
|
||||||
|
<span style="font-size: 0.74rem; color: #64748b;">Monto máximo que el estudiante puede gastar por día</span>
|
||||||
|
</div>
|
||||||
|
<span id="lblParentDailyLimitDisplay" style="font-size: 1.1rem; color: #0284c7; font-weight: 900; background: white; border: 1.5px solid #bae6fd; padding: 4px 12px; border-radius: 8px;">₡3.000</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="display: flex; gap: 8px; margin-bottom: 10px;">
|
||||||
|
<div style="position: relative; flex: 1;">
|
||||||
|
<span style="position: absolute; left: 10px; top: 50%; transform: translateY(-50%); font-weight: 900; color: #0284c7; font-size: 1.1rem;">₡</span>
|
||||||
|
<input type="tel" inputmode="numeric" pattern="[0-9]*" id="inputParentCustomLimit" placeholder="Ej: 3000" style="width: 100%; padding: 10px 10px 10px 30px; border-radius: 10px; border: 2px solid #0284c7; font-size: 1.1rem; font-weight: 900; color: #0f172a; background: white; box-sizing: border-box;">
|
||||||
|
</div>
|
||||||
|
<button type="button" onclick="saveParentCustomLimit()" style="padding: 10px 16px; background: linear-gradient(135deg, #0284c7, #0369a1); color: white; border: none; border-radius: 10px; font-weight: 900; font-size: 0.85rem; cursor: pointer; white-space: nowrap; box-shadow: 0 2px 6px rgba(2, 132, 199, 0.35);">
|
||||||
|
💾 Guardar
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 5px; margin-bottom: 10px;">
|
||||||
|
<button type="button" onclick="setParentLimitPreset(1500)" class="stock-btn-quick">₡1.500</button>
|
||||||
|
<button type="button" onclick="setParentLimitPreset(2500)" class="stock-btn-quick">₡2.500</button>
|
||||||
|
<button type="button" onclick="setParentLimitPreset(3500)" class="stock-btn-quick">₡3.500</button>
|
||||||
|
<button type="button" onclick="setParentLimitPreset(5000)" class="stock-btn-quick">₡5.000</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<input type="range" id="rangeParentLimit" min="1000" max="10000" step="500" value="3000" oninput="onParentLimitSliderChange(this.value)" style="width: 100%;">
|
||||||
|
<div style="display: flex; justify-content: space-between; font-size: 0.7rem; color: #64748b; margin-top: 2px;">
|
||||||
|
<span>₡1.000 min</span>
|
||||||
|
<span>₡10.000 max</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- PERMISOS DE TRANSFERENCIA ENTRE COMPAÑEROS -->
|
||||||
|
<div class="parent-card" style="display: flex; justify-content: space-between; align-items: center;">
|
||||||
|
<div>
|
||||||
|
<strong style="font-size: 0.88rem; color: var(--text-main); display: block;">🤝 RecreoTransfer entre Compas</strong>
|
||||||
|
<span style="font-size: 0.74rem; color: var(--text-muted);">Permitir transferir saldo a compañeros de clase</span>
|
||||||
|
</div>
|
||||||
|
<input type="checkbox" id="chkParentAllowTransferDirect" onchange="onToggleParentTransfer(this.checked)" style="width: 24px; height: 24px; cursor: pointer; accent-color: #0284c7;" checked>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- SEGURIDAD Y PIN ESCOLAR -->
|
||||||
|
<div class="parent-card" style="border: 1.5px dashed var(--border);">
|
||||||
|
<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 10px;">
|
||||||
|
<span style="font-size: 1.2rem;">🔐</span>
|
||||||
|
<div>
|
||||||
|
<strong style="font-size: 0.9rem; color: var(--text-main); display: block;">Credenciales del Estudiante</strong>
|
||||||
|
<span style="font-size: 0.74rem; color: var(--text-muted);">Restablece el PIN o la contraseña de acceso escolar</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: var(--text-muted); margin-bottom: 3px;">Nuevo PIN (4 dígitos):</label>
|
||||||
|
<input type="password" inputmode="numeric" maxlength="4" id="inputParentStudentPin" placeholder="1234" style="width: 100%; padding: 9px; border-radius: 8px; border: 1.5px solid var(--border); font-weight: 900; letter-spacing: 2px; text-align: center; box-sizing: border-box; background: var(--card-bg); color: var(--text-main);">
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label style="display: block; font-size: 0.74rem; font-weight: 800; color: var(--text-muted); margin-bottom: 3px;">Nueva Contraseña:</label>
|
||||||
|
<input type="text" id="inputParentStudentPass" placeholder="Ej: 1234" style="width: 100%; padding: 9px; border-radius: 8px; border: 1.5px solid var(--border); font-weight: 800; box-sizing: border-box; background: var(--card-bg); color: var(--text-main);">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button type="button" onclick="saveParentStudentCredentials()" 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 DE COMPRAS RECIENTES -->
|
||||||
|
<div class="parent-card">
|
||||||
|
<h4 style="font-size: 0.9rem; font-weight: 900; color: var(--text-main); margin-bottom: 10px;">
|
||||||
|
📋 Historial de Compras en Soda
|
||||||
|
</h4>
|
||||||
|
<div id="parentStudentHistoryList" style="font-size: 0.8rem; color: var(--text-muted);">
|
||||||
|
Sin compras recientes registradas.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="app-container" id="appContainer" style="display: none;">
|
<div class="app-container" id="appContainer" style="display: none;">
|
||||||
<!-- BANNER DE TARJETA SUSPENDIDA / BLOQUEADA -->
|
<!-- BANNER DE TARJETA SUSPENDIDA / BLOQUEADA -->
|
||||||
<div id="bannerCardBlocked" class="banner-card-blocked" style="display: none;">
|
<div id="bannerCardBlocked" class="banner-card-blocked" style="display: none;">
|
||||||
@@ -729,6 +1002,55 @@
|
|||||||
<span>💸</span> Enviar Dinero al Instante
|
<span>💸</span> Enviar Dinero al Instante
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
<!-- MODAL: ESCANEAR QR PARA VINCULAR HIJO (PORTAL PADRES) -->
|
||||||
|
<div class="modal-qr-backdrop" id="modalScanChildQr" style="display: none;" onclick="closeScanChildQrModal(event)">
|
||||||
|
<div class="modal-qr-card" onclick="event.stopPropagation()" style="max-width: 400px; text-align: center;">
|
||||||
|
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; border-bottom: 1px solid var(--border); padding-bottom: 8px;">
|
||||||
|
<strong style="font-size: 1rem; color: var(--text-main);">📷 Vincular Estudiante con QR</strong>
|
||||||
|
<button type="button" onclick="closeScanChildQrModal()" style="background: none; border: none; font-size: 1.2rem; cursor: pointer; color: var(--text-muted);">✕</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="position: relative; width: 100%; height: 220px; background: #000; border-radius: 14px; overflow: hidden; margin-bottom: 10px;">
|
||||||
|
<video id="videoScanChild" playsinline autoplay muted style="width: 100%; height: 100%; object-fit: cover;"></video>
|
||||||
|
<canvas id="canvasScanChild" style="display: none;"></canvas>
|
||||||
|
<div style="position: absolute; inset: 16px; border: 2px dashed #38bdf8; border-radius: 12px; pointer-events: none;"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p style="font-size: 0.78rem; color: var(--text-muted); margin-bottom: 10px;">
|
||||||
|
Apunta la cámara al carné escolar del estudiante.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div style="border-top: 1px dashed var(--border); padding-top: 10px; margin-top: 10px; text-align: left;">
|
||||||
|
<label for="inputManualStudentCode" style="display: block; font-size: 0.76rem; font-weight: 800; color: var(--text-main); margin-bottom: 4px;">
|
||||||
|
O escribe el código de carné manualmente:
|
||||||
|
</label>
|
||||||
|
<div style="display: flex; gap: 6px;">
|
||||||
|
<input type="text" id="inputManualStudentCode" placeholder="Ej: EST-2026-001 o QR Token" style="flex: 1; padding: 8px 10px; border-radius: 8px; border: 1.5px solid var(--border); font-size: 0.85rem; font-weight: 800; background: var(--card-bg); color: var(--text-main); box-sizing: border-box;">
|
||||||
|
<button type="button" onclick="submitManualStudentLink()" style="padding: 8px 14px; background: #0284c7; color: white; border: none; border-radius: 8px; font-weight: 800; font-size: 0.8rem; cursor: pointer; white-space: nowrap;">
|
||||||
|
Vincular
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- MODAL: ESCANEAR QR PARA RECARGA EN SODA (ADMIN) -->
|
||||||
|
<div class="modal-qr-backdrop" id="modalAdminScanQr" style="display: none;" onclick="closeAdminScanQrModal(event)">
|
||||||
|
<div class="modal-qr-card" onclick="event.stopPropagation()" style="max-width: 400px; text-align: center;">
|
||||||
|
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; border-bottom: 1px solid var(--border); padding-bottom: 8px;">
|
||||||
|
<strong style="font-size: 1rem; color: var(--text-main);">📷 Escanear Carné para Recarga</strong>
|
||||||
|
<button type="button" onclick="closeAdminScanQrModal()" style="background: none; border: none; font-size: 1.2rem; cursor: pointer; color: var(--text-muted);">✕</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="position: relative; width: 100%; height: 220px; background: #000; border-radius: 14px; overflow: hidden; margin-bottom: 10px;">
|
||||||
|
<video id="videoAdminScan" playsinline autoplay muted style="width: 100%; height: 100%; object-fit: cover;"></video>
|
||||||
|
<canvas id="canvasAdminScan" style="display: none;"></canvas>
|
||||||
|
<div style="position: absolute; inset: 16px; border: 2px dashed #10b981; border-radius: 12px; pointer-events: none;"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p style="font-size: 0.78rem; color: var(--text-muted); margin-bottom: 6px;">
|
||||||
|
Escanea el QR del carné del alumno para seleccionarlo al instante.
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -756,8 +1078,8 @@
|
|||||||
</button>
|
</button>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
<script src="/js/sounds.js?v=7.0"></script>
|
<script src="/js/sounds.js?v=8.0"></script>
|
||||||
<script src="/js/jsQR.js"></script>
|
<script src="/js/jsQR.js"></script>
|
||||||
<script src="/js/app.js?v=7.0"></script>
|
<script src="/js/app.js?v=8.0"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+770
-55
@@ -51,7 +51,7 @@ document.addEventListener('DOMContentLoaded', async () => {
|
|||||||
|
|
||||||
// Registrar Service Worker para PWA
|
// Registrar Service Worker para PWA
|
||||||
if ('serviceWorker' in navigator) {
|
if ('serviceWorker' in navigator) {
|
||||||
navigator.serviceWorker.register('/sw.js?v=7.0').then(reg => {
|
navigator.serviceWorker.register('/sw.js?v=8.0').then(reg => {
|
||||||
// Registro limpio sin recargas forzadas
|
// Registro limpio sin recargas forzadas
|
||||||
}).catch(err => console.log('SW error:', err));
|
}).catch(err => console.log('SW error:', err));
|
||||||
}
|
}
|
||||||
@@ -80,24 +80,100 @@ document.addEventListener('DOMContentLoaded', async () => {
|
|||||||
// VISTA Y MANEJO DE AUTENTICACIÓN / SESIÓN
|
// VISTA Y MANEJO DE AUTENTICACIÓN / SESIÓN
|
||||||
// ==========================================
|
// ==========================================
|
||||||
|
|
||||||
|
let currentParentChild = null; // Estudiante activo en el portal de padres
|
||||||
|
let adminSelectedStudent = null; // Estudiante seleccionado para recarga en admin
|
||||||
|
let scanChildStream = null;
|
||||||
|
let scanChildAnimId = null;
|
||||||
|
let scanAdminStream = null;
|
||||||
|
let scanAdminAnimId = null;
|
||||||
|
|
||||||
function showLoginView() {
|
function showLoginView() {
|
||||||
const viewLogin = document.getElementById('viewLogin');
|
const viewLogin = document.getElementById('viewLogin');
|
||||||
const viewAdmin = document.getElementById('viewAdmin');
|
const viewAdmin = document.getElementById('viewAdmin');
|
||||||
|
const viewPadres = document.getElementById('viewPadres');
|
||||||
const appContainer = document.getElementById('appContainer');
|
const appContainer = document.getElementById('appContainer');
|
||||||
const bottomNav = document.getElementById('pwaBottomNav');
|
const bottomNav = document.getElementById('pwaBottomNav');
|
||||||
|
|
||||||
if (viewLogin) viewLogin.style.display = 'flex';
|
if (viewLogin) viewLogin.style.display = 'flex';
|
||||||
if (viewAdmin) viewAdmin.style.display = 'none';
|
if (viewAdmin) viewAdmin.style.display = 'none';
|
||||||
|
if (viewPadres) viewPadres.style.display = 'none';
|
||||||
if (appContainer) appContainer.style.display = 'none';
|
if (appContainer) appContainer.style.display = 'none';
|
||||||
if (bottomNav) bottomNav.style.display = 'none';
|
if (bottomNav) bottomNav.style.display = 'none';
|
||||||
|
|
||||||
// Cerrar cualquier modal que pudiera estar abierto
|
switchLoginTab('login');
|
||||||
|
closeScanChildQrModal();
|
||||||
|
closeAdminScanQrModal();
|
||||||
toggleParentPanel(false);
|
toggleParentPanel(false);
|
||||||
closeCartModal();
|
closeCartModal();
|
||||||
closeQrModal();
|
closeQrModal();
|
||||||
closeTransferModal();
|
closeTransferModal();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function switchLoginTab(tab) {
|
||||||
|
const formLogin = document.getElementById('formLogin');
|
||||||
|
const formRegister = document.getElementById('formRegisterPadre');
|
||||||
|
const tabLogin = document.getElementById('tabBtnLogin');
|
||||||
|
const tabReg = document.getElementById('tabBtnRegister');
|
||||||
|
const demoBox = document.querySelector('.login-demo-box');
|
||||||
|
|
||||||
|
if (tab === 'login') {
|
||||||
|
if (formLogin) formLogin.style.display = 'block';
|
||||||
|
if (formRegister) formRegister.style.display = 'none';
|
||||||
|
if (tabLogin) tabLogin.classList.add('active');
|
||||||
|
if (tabReg) tabReg.classList.remove('active');
|
||||||
|
if (demoBox) demoBox.style.display = 'block';
|
||||||
|
} else {
|
||||||
|
if (formLogin) formLogin.style.display = 'none';
|
||||||
|
if (formRegister) formRegister.style.display = 'block';
|
||||||
|
if (tabLogin) tabLogin.classList.remove('active');
|
||||||
|
if (tabReg) tabReg.classList.add('active');
|
||||||
|
if (demoBox) demoBox.style.display = 'none';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleRegisterPadreSubmit(event) {
|
||||||
|
if (event) event.preventDefault();
|
||||||
|
const nombre = document.getElementById('regNombre').value.trim();
|
||||||
|
const telefono = document.getElementById('regTelefono').value.trim();
|
||||||
|
const username = document.getElementById('regUsername').value.trim();
|
||||||
|
const password = document.getElementById('regPassword').value.trim();
|
||||||
|
const errorMsg = document.getElementById('registerErrorMsg');
|
||||||
|
const btnSubmit = document.getElementById('btnRegisterSubmit');
|
||||||
|
|
||||||
|
if (errorMsg) errorMsg.style.display = 'none';
|
||||||
|
btnSubmit.disabled = true;
|
||||||
|
btnSubmit.textContent = 'Creando cuenta de padre...';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/auth/register-padre', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ nombre, telefono, username, password })
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (!res.ok) throw new Error(data.error || 'Error al registrar la cuenta');
|
||||||
|
|
||||||
|
currentUser = {
|
||||||
|
...data.user,
|
||||||
|
hijos: []
|
||||||
|
};
|
||||||
|
localStorage.setItem('recreopay_user', JSON.stringify(currentUser));
|
||||||
|
|
||||||
|
if (window.sounds) window.sounds.playSuccess();
|
||||||
|
alert(`🎉 ¡Bienvenido(a) a RecreoPay, ${data.user.nombre}! Tu cuenta de padre fue creada exitosamente.`);
|
||||||
|
await applyUserRoleSession();
|
||||||
|
} catch (err) {
|
||||||
|
if (errorMsg) {
|
||||||
|
errorMsg.textContent = `❌ ${err.message}`;
|
||||||
|
errorMsg.style.display = 'block';
|
||||||
|
}
|
||||||
|
if (window.sounds) window.sounds.playError();
|
||||||
|
} finally {
|
||||||
|
btnSubmit.disabled = false;
|
||||||
|
btnSubmit.innerHTML = '✨ Crear Cuenta y Entrar al Panel';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function quickFillLogin(username, password) {
|
function quickFillLogin(username, password) {
|
||||||
document.getElementById('loginUsername').value = username;
|
document.getElementById('loginUsername').value = username;
|
||||||
document.getElementById('loginPassword').value = password;
|
document.getElementById('loginPassword').value = password;
|
||||||
@@ -161,6 +237,7 @@ async function applyUserRoleSession() {
|
|||||||
|
|
||||||
const viewLogin = document.getElementById('viewLogin');
|
const viewLogin = document.getElementById('viewLogin');
|
||||||
const viewAdmin = document.getElementById('viewAdmin');
|
const viewAdmin = document.getElementById('viewAdmin');
|
||||||
|
const viewPadres = document.getElementById('viewPadres');
|
||||||
const appContainer = document.getElementById('appContainer');
|
const appContainer = document.getElementById('appContainer');
|
||||||
const bottomNav = document.getElementById('pwaBottomNav');
|
const bottomNav = document.getElementById('pwaBottomNav');
|
||||||
const navPadres = document.getElementById('pwaNavPadres');
|
const navPadres = document.getElementById('pwaNavPadres');
|
||||||
@@ -169,27 +246,25 @@ async function applyUserRoleSession() {
|
|||||||
|
|
||||||
if (currentUser.rol === 'admin') {
|
if (currentUser.rol === 'admin') {
|
||||||
if (viewAdmin) viewAdmin.style.display = 'block';
|
if (viewAdmin) viewAdmin.style.display = 'block';
|
||||||
|
if (viewPadres) viewPadres.style.display = 'none';
|
||||||
if (appContainer) appContainer.style.display = 'none';
|
if (appContainer) appContainer.style.display = 'none';
|
||||||
if (bottomNav) bottomNav.style.display = 'none';
|
if (bottomNav) bottomNav.style.display = 'none';
|
||||||
const adminNameEl = document.getElementById('adminLoggedName');
|
const adminNameEl = document.getElementById('adminLoggedName');
|
||||||
if (adminNameEl) adminNameEl.textContent = `${currentUser.nombre} (Administrador)`;
|
if (adminNameEl) adminNameEl.textContent = `${currentUser.nombre} (Administrador)`;
|
||||||
await loadAdminData();
|
await loadAdminData();
|
||||||
|
setupAdminSmartSearch();
|
||||||
} else if (currentUser.rol === 'padre') {
|
} else if (currentUser.rol === 'padre') {
|
||||||
if (viewAdmin) viewAdmin.style.display = 'none';
|
if (viewAdmin) viewAdmin.style.display = 'none';
|
||||||
if (appContainer) appContainer.style.display = 'block';
|
if (viewPadres) viewPadres.style.display = 'block'; // PANEL DEDICADO COMPLETO (NO MODAL)
|
||||||
if (bottomNav) bottomNav.style.display = 'flex';
|
if (appContainer) appContainer.style.display = 'none';
|
||||||
if (navPadres) navPadres.style.display = 'flex';
|
if (bottomNav) bottomNav.style.display = 'none';
|
||||||
|
|
||||||
// Mostrar botón de acceso al portal de padres
|
|
||||||
const btnPadres = document.getElementById('btnModePadres');
|
|
||||||
if (btnPadres) btnPadres.style.display = 'inline-block';
|
|
||||||
|
|
||||||
await loadInitialData();
|
await loadInitialData();
|
||||||
setupParentPortalChildren();
|
await loadParentDashboard();
|
||||||
toggleParentPanel(true);
|
|
||||||
} else {
|
} else {
|
||||||
// Estudiante: SEGURIDAD ESTRICTA - Ocultar botón de padres
|
// Estudiante: SEGURIDAD ESTRICTA - Ocultar botón de padres
|
||||||
if (viewAdmin) viewAdmin.style.display = 'none';
|
if (viewAdmin) viewAdmin.style.display = 'none';
|
||||||
|
if (viewPadres) viewPadres.style.display = 'none';
|
||||||
if (appContainer) appContainer.style.display = 'block';
|
if (appContainer) appContainer.style.display = 'block';
|
||||||
if (bottomNav) bottomNav.style.display = 'flex';
|
if (bottomNav) bottomNav.style.display = 'flex';
|
||||||
if (navPadres) navPadres.style.display = 'none'; // Estudiantes no ven pestaña padres
|
if (navPadres) navPadres.style.display = 'none'; // Estudiantes no ven pestaña padres
|
||||||
@@ -211,6 +286,8 @@ function logout(skipConfirm = false) {
|
|||||||
localStorage.removeItem('recreopay_user');
|
localStorage.removeItem('recreopay_user');
|
||||||
currentUser = null;
|
currentUser = null;
|
||||||
currentStudent = null;
|
currentStudent = null;
|
||||||
|
currentParentChild = null;
|
||||||
|
adminSelectedStudent = null;
|
||||||
showLoginView();
|
showLoginView();
|
||||||
if (window.sounds) window.sounds.playTap();
|
if (window.sounds) window.sounds.playTap();
|
||||||
}
|
}
|
||||||
@@ -659,17 +736,19 @@ function closeQrModal(e) {
|
|||||||
// ==========================================
|
// ==========================================
|
||||||
|
|
||||||
function toggleParentPanel(show, e) {
|
function toggleParentPanel(show, e) {
|
||||||
|
if (e && e.target !== e.currentTarget) return;
|
||||||
|
if (currentUser && currentUser.rol === 'padre') {
|
||||||
|
if (show) {
|
||||||
|
returnToParentDashboard();
|
||||||
|
} else {
|
||||||
|
switchToSodaMenuAsParent();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
// SEGURIDAD: Un estudiante no tiene acceso al portal de padres
|
// SEGURIDAD: Un estudiante no tiene acceso al portal de padres
|
||||||
if (currentUser && currentUser.rol === 'estudiante') {
|
|
||||||
const modalPadres = document.getElementById('modalPadres');
|
const modalPadres = document.getElementById('modalPadres');
|
||||||
if (modalPadres) modalPadres.style.display = 'none';
|
if (modalPadres) modalPadres.style.display = 'none';
|
||||||
resetPwaNavActive();
|
resetPwaNavActive();
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (e && e.target !== e.currentTarget) return;
|
|
||||||
const modalPadres = document.getElementById('modalPadres');
|
|
||||||
if (modalPadres) modalPadres.style.display = show ? 'flex' : 'none';
|
|
||||||
if (!show) resetPwaNavActive();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function openDailyLimitEditor() {
|
function openDailyLimitEditor() {
|
||||||
@@ -1369,41 +1448,280 @@ function initStudentSSE() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
// FUNCIONES DEL PORTAL DE PADRES (HIJOS Y CREDENCIALES)
|
// FUNCIONES DEL PORTAL DEDICADO DE PADRES
|
||||||
// ==========================================
|
// ==========================================
|
||||||
|
|
||||||
function setupParentPortalChildren() {
|
async function loadParentDashboard() {
|
||||||
const box = document.getElementById('parentChildSelectorBox');
|
if (!currentUser || currentUser.rol !== 'padre') return;
|
||||||
const sel = document.getElementById('parentChildSelect');
|
|
||||||
if (!box || !sel) return;
|
|
||||||
|
|
||||||
if (currentUser && currentUser.hijos && currentUser.hijos.length > 0) {
|
const parentLoggedName = document.getElementById('parentLoggedName');
|
||||||
box.style.display = 'block';
|
if (parentLoggedName) {
|
||||||
sel.innerHTML = currentUser.hijos.map(h => `
|
parentLoggedName.textContent = currentUser.nombre ? `${currentUser.nombre} (Padre/Madre)` : 'Familia RecreoPay';
|
||||||
<option value="${h.id}">${h.nombre_completo} (${h.grado} - Sección ${h.seccion})</option>
|
}
|
||||||
`).join('');
|
|
||||||
|
|
||||||
onParentChildSelect(currentUser.hijos[0].id);
|
try {
|
||||||
} else if (students.length > 0) {
|
const res = await fetch(`/api/padres/mis-hijos?padre_usuario_id=${currentUser.id}`);
|
||||||
box.style.display = 'block';
|
const data = await res.json();
|
||||||
sel.innerHTML = students.slice(0, 2).map(h => `
|
if (res.ok && data.hijos) {
|
||||||
<option value="${h.id}">${h.nombre_completo} (${h.grado} - Sección ${h.seccion})</option>
|
currentUser.hijos = data.hijos;
|
||||||
`).join('');
|
localStorage.setItem('recreopay_user', JSON.stringify(currentUser));
|
||||||
onParentChildSelect(students[0].id);
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('Error al cargar hijos del padre:', err);
|
||||||
|
}
|
||||||
|
|
||||||
|
renderParentDashboardView();
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderParentDashboardView() {
|
||||||
|
const bannerNoHijos = document.getElementById('parentNoChildrenBanner');
|
||||||
|
const sectionHijos = document.getElementById('parentChildrenSection');
|
||||||
|
const containerActive = document.getElementById('parentSelectedChildContainer');
|
||||||
|
const grid = document.getElementById('parentChildrenGrid');
|
||||||
|
|
||||||
|
const hijos = (currentUser && currentUser.hijos) ? currentUser.hijos : [];
|
||||||
|
|
||||||
|
if (hijos.length === 0) {
|
||||||
|
if (bannerNoHijos) bannerNoHijos.style.display = 'block';
|
||||||
|
if (containerActive) containerActive.style.display = 'none';
|
||||||
|
if (grid) grid.innerHTML = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bannerNoHijos) bannerNoHijos.style.display = 'none';
|
||||||
|
if (containerActive) containerActive.style.display = 'block';
|
||||||
|
|
||||||
|
// Si no hay hijo seleccionado o el seleccionado ya no existe en la lista, seleccionar el primero
|
||||||
|
if (!currentParentChild || !hijos.some(h => h.id === currentParentChild.id)) {
|
||||||
|
currentParentChild = hijos[0];
|
||||||
|
} else {
|
||||||
|
// Actualizar datos del hijo seleccionado desde la lista actualizada
|
||||||
|
currentParentChild = hijos.find(h => h.id === currentParentChild.id) || hijos[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Renderizar tarjetas de hijos en la cuadrícula
|
||||||
|
if (grid) {
|
||||||
|
grid.innerHTML = hijos.map(h => {
|
||||||
|
const isSelected = currentParentChild && currentParentChild.id === h.id;
|
||||||
|
const isBlocked = !!h.tarjeta_bloqueada;
|
||||||
|
return `
|
||||||
|
<div class="parent-child-card ${isSelected ? 'active' : ''}" onclick="selectParentChild(${h.id})">
|
||||||
|
<div style="display: flex; align-items: center; gap: 10px; margin-bottom: 8px;">
|
||||||
|
<img src="${h.foto_url || '/img/avatar_default.png'}" style="width: 42px; height: 42px; border-radius: 50%; border: 2px solid ${isSelected ? '#0284c7' : 'var(--border)'}; object-fit: cover;">
|
||||||
|
<div style="min-width: 0; flex: 1;">
|
||||||
|
<strong style="font-size: 0.9rem; color: var(--text-main); display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
|
||||||
|
${h.nombre_completo}
|
||||||
|
</strong>
|
||||||
|
<span style="font-size: 0.72rem; color: var(--text-muted); font-weight: 600;">
|
||||||
|
${h.grado} - Sec. ${h.seccion}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
${isBlocked ? '<span style="font-size: 0.65rem; background: #fee2e2; color: #dc2626; padding: 2px 6px; border-radius: 4px; font-weight: 800;">BLOQUEADO</span>' : ''}
|
||||||
|
</div>
|
||||||
|
<div style="display: flex; justify-content: space-between; align-items: center; border-top: 1px solid var(--border); padding-top: 6px; margin-top: 4px;">
|
||||||
|
<span style="font-size: 0.72rem; color: var(--text-muted); font-weight: 700;">Saldo:</span>
|
||||||
|
<strong style="font-size: 1.05rem; color: #0284c7; font-weight: 900;">
|
||||||
|
₡${(h.saldo_colones || 0).toLocaleString('es-CR')}
|
||||||
|
</strong>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
renderActiveChildDetails(currentParentChild);
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectParentChild(childId) {
|
||||||
|
const hijos = (currentUser && currentUser.hijos) ? currentUser.hijos : [];
|
||||||
|
const found = hijos.find(h => h.id === childId);
|
||||||
|
if (found) {
|
||||||
|
currentParentChild = found;
|
||||||
|
renderParentDashboardView();
|
||||||
|
if (window.sounds) window.sounds.playTap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onParentChildSelect(studentId) {
|
function renderActiveChildDetails(child) {
|
||||||
await selectStudent(studentId);
|
if (!child) return;
|
||||||
|
|
||||||
|
const avatar = document.getElementById('parentActiveChildAvatar');
|
||||||
|
const name = document.getElementById('parentActiveChildName');
|
||||||
|
const meta = document.getElementById('parentActiveChildMeta');
|
||||||
|
const balance = document.getElementById('parentActiveChildBalance');
|
||||||
|
const linkCarnet = document.getElementById('btnParentViewCarnet');
|
||||||
|
const lblLimit = document.getElementById('lblParentDailyLimitDisplay');
|
||||||
|
const inputCustomLimit = document.getElementById('inputParentCustomLimit');
|
||||||
|
const rangeLimit = document.getElementById('rangeParentLimit');
|
||||||
|
const chkTransfer = document.getElementById('chkParentAllowTransferDirect');
|
||||||
|
|
||||||
|
if (avatar) avatar.src = child.foto_url || '/img/avatar_default.png';
|
||||||
|
if (name) name.textContent = child.nombre_completo;
|
||||||
|
if (meta) meta.textContent = `${child.grado} - Sección ${child.seccion} • Cód: ${child.codigo_estudiante}`;
|
||||||
|
if (balance) balance.textContent = `₡${(child.saldo_colones || 0).toLocaleString('es-CR')}`;
|
||||||
|
if (linkCarnet) linkCarnet.href = `/carnet.html?token=${child.qr_token || ''}&id=${child.id}`;
|
||||||
|
|
||||||
|
const currentLimit = child.limite_diario_colones || 3000;
|
||||||
|
if (lblLimit) lblLimit.textContent = `₡${currentLimit.toLocaleString('es-CR')}`;
|
||||||
|
if (inputCustomLimit) inputCustomLimit.value = currentLimit;
|
||||||
|
if (rangeLimit) rangeLimit.value = currentLimit;
|
||||||
|
if (chkTransfer) chkTransfer.checked = child.permitir_transferencias !== 0;
|
||||||
|
|
||||||
|
loadActiveChildHistory(child.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function saveParentChildAccess() {
|
async function loadActiveChildHistory(studentId) {
|
||||||
if (!currentStudent) return;
|
const container = document.getElementById('parentStudentHistoryList');
|
||||||
const pin = document.getElementById('inputParentNewPin').value.trim();
|
if (!container) return;
|
||||||
const pass = document.getElementById('inputParentNewPass').value.trim();
|
|
||||||
|
container.innerHTML = '<span style="color: var(--text-muted);">Cargando historial de compras...</span>';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/ordenes?estudiante_id=${studentId}`);
|
||||||
|
const ordenes = await res.json();
|
||||||
|
|
||||||
|
if (!Array.isArray(ordenes) || ordenes.length === 0) {
|
||||||
|
container.innerHTML = '<span style="color: var(--text-muted); font-size: 0.8rem;">Sin compras recientes registradas en la soda.</span>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
container.innerHTML = ordenes.slice(0, 10).map(o => {
|
||||||
|
const itemsStr = (o.items && o.items.length > 0)
|
||||||
|
? o.items.map(it => `${it.cantidad}x ${it.nombre}`).join(', ')
|
||||||
|
: 'Compra en mostrador';
|
||||||
|
const fecha = o.creado_en ? new Date(o.creado_en).toLocaleDateString('es-CR', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }) : '';
|
||||||
|
return `
|
||||||
|
<div style="display: flex; justify-content: space-between; align-items: center; padding: 8px 0; border-bottom: 1px dashed var(--border);">
|
||||||
|
<div style="min-width: 0; flex: 1; padding-right: 8px;">
|
||||||
|
<div style="font-weight: 800; color: var(--text-main); font-size: 0.82rem; word-break: break-word;">${itemsStr}</div>
|
||||||
|
<div style="font-size: 0.72rem; color: var(--text-muted); margin-top: 1px;">${fecha} • Estado: <span style="color: #10b981; font-weight: 700;">${o.estado}</span></div>
|
||||||
|
</div>
|
||||||
|
<strong style="color: #0284c7; font-size: 0.88rem; flex-shrink: 0;">-₡${(o.total_colones || 0).toLocaleString('es-CR')}</strong>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}).join('');
|
||||||
|
} catch (err) {
|
||||||
|
container.innerHTML = '<span style="color: #ef4444; font-size: 0.78rem;">No se pudo cargar el historial.</span>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setParentSinpePreset(amt) {
|
||||||
|
const input = document.getElementById('inputParentSinpeMonto');
|
||||||
|
if (input) input.value = amt;
|
||||||
|
if (window.sounds) window.sounds.playTap();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function executeParentSinpeRecharge() {
|
||||||
|
if (!currentParentChild) {
|
||||||
|
alert('Selecciona primero al estudiante a quien deseas recargarle.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const input = document.getElementById('inputParentSinpeMonto');
|
||||||
|
const monto = parseInt(input ? input.value : 0, 10);
|
||||||
|
|
||||||
|
if (isNaN(monto) || monto <= 0) {
|
||||||
|
alert('Ingresa un monto válido mayor a ₡0 para recargar.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/estudiantes/${currentParentChild.id}/recarga`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
monto,
|
||||||
|
comprobante: 'SINPE-PADRE',
|
||||||
|
descripcion: `Recarga SINPE Móvil por Padre/Madre para ${currentParentChild.nombre_completo}`
|
||||||
|
})
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (!res.ok) throw new Error(data.error);
|
||||||
|
|
||||||
|
if (window.sounds) window.sounds.playCoin();
|
||||||
|
alert(`🎉 ¡Recarga Exitosa!\nSe agregaron ₡${monto.toLocaleString('es-CR')} al monedero de ${currentParentChild.nombre_completo}.\nNuevo Saldo: ₡${data.saldo_nuevo.toLocaleString('es-CR')}`);
|
||||||
|
|
||||||
|
if (input) input.value = '';
|
||||||
|
await loadParentDashboard();
|
||||||
|
} catch (err) {
|
||||||
|
if (window.sounds) window.sounds.playError();
|
||||||
|
alert(`❌ Error al procesar recarga SINPE: ${err.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setParentLimitPreset(amt) {
|
||||||
|
const input = document.getElementById('inputParentCustomLimit');
|
||||||
|
const range = document.getElementById('rangeParentLimit');
|
||||||
|
const lbl = document.getElementById('lblParentDailyLimitDisplay');
|
||||||
|
if (input) input.value = amt;
|
||||||
|
if (range) range.value = amt;
|
||||||
|
if (lbl) lbl.textContent = `₡${parseInt(amt, 10).toLocaleString('es-CR')}`;
|
||||||
|
if (window.sounds) window.sounds.playTap();
|
||||||
|
}
|
||||||
|
|
||||||
|
function onParentLimitSliderChange(val) {
|
||||||
|
const input = document.getElementById('inputParentCustomLimit');
|
||||||
|
const lbl = document.getElementById('lblParentDailyLimitDisplay');
|
||||||
|
if (input) input.value = val;
|
||||||
|
if (lbl) lbl.textContent = `₡${parseInt(val, 10).toLocaleString('es-CR')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveParentCustomLimit() {
|
||||||
|
if (!currentParentChild) return;
|
||||||
|
const input = document.getElementById('inputParentCustomLimit');
|
||||||
|
const val = parseInt(input ? input.value : 0, 10);
|
||||||
|
|
||||||
|
if (isNaN(val) || val < 500) {
|
||||||
|
alert('El límite diario debe ser de al menos ₡500.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/estudiantes/${currentParentChild.id}/limite`, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ limite_diario_colones: val })
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (!res.ok) throw new Error(data.error);
|
||||||
|
|
||||||
|
currentParentChild.limite_diario_colones = val;
|
||||||
|
if (window.sounds) window.sounds.playSuccess();
|
||||||
|
alert(`🛡️ Límite diario actualizado a ₡${val.toLocaleString('es-CR')} para ${currentParentChild.nombre_completo}.`);
|
||||||
|
await loadParentDashboard();
|
||||||
|
} catch (err) {
|
||||||
|
if (window.sounds) window.sounds.playError();
|
||||||
|
alert(`❌ Error al guardar límite: ${err.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onToggleParentTransfer(checked) {
|
||||||
|
if (!currentParentChild) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/estudiantes/${currentParentChild.id}/limite`, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ permitir_transferencias: checked ? 1 : 0 })
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (!res.ok) throw new Error(data.error);
|
||||||
|
|
||||||
|
currentParentChild.permitir_transferencias = checked ? 1 : 0;
|
||||||
|
if (window.sounds) window.sounds.playTap();
|
||||||
|
} catch (err) {
|
||||||
|
alert(`❌ No se pudo actualizar permiso de transferencia: ${err.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveParentStudentCredentials() {
|
||||||
|
if (!currentParentChild) return;
|
||||||
|
const pinInput = document.getElementById('inputParentStudentPin');
|
||||||
|
const passInput = document.getElementById('inputParentStudentPass');
|
||||||
|
const pin = pinInput ? pinInput.value.trim() : '';
|
||||||
|
const pass = passInput ? passInput.value.trim() : '';
|
||||||
|
|
||||||
if (!pin && !pass) {
|
if (!pin && !pass) {
|
||||||
alert('Ingresa al menos un nuevo PIN o una nueva contraseña para actualizar.');
|
alert('Ingresa al menos un nuevo PIN o una nueva contraseña.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1417,22 +1735,178 @@ async function saveParentChildAccess() {
|
|||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
estudiante_id: currentStudent.id,
|
estudiante_id: currentParentChild.id,
|
||||||
nuevo_pin: pin || undefined,
|
nuevo_pin: pin || undefined,
|
||||||
nuevo_password: pass || undefined
|
nuevo_password: pass || undefined
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (!res.ok) throw new Error(data.error);
|
if (!res.ok) throw new Error(data.error);
|
||||||
|
|
||||||
if (window.sounds) window.sounds.playSuccess();
|
if (window.sounds) window.sounds.playSuccess();
|
||||||
alert(`✅ ¡Credenciales actualizadas!\n${data.mensaje}`);
|
alert(`✅ ¡Credenciales de acceso escolar actualizadas!\n${data.mensaje}`);
|
||||||
document.getElementById('inputParentNewPin').value = '';
|
if (pinInput) pinInput.value = '';
|
||||||
document.getElementById('inputParentNewPass').value = '';
|
if (passInput) passInput.value = '';
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (window.sounds) window.sounds.playError();
|
if (window.sounds) window.sounds.playError();
|
||||||
alert(`❌ Error actualizando credenciales: ${err.message}`);
|
alert(`❌ Error al actualizar credenciales: ${err.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function switchToSodaMenuAsParent() {
|
||||||
|
if (!currentParentChild && currentUser.hijos && currentUser.hijos.length > 0) {
|
||||||
|
currentParentChild = currentUser.hijos[0];
|
||||||
|
}
|
||||||
|
if (currentParentChild) {
|
||||||
|
selectStudent(currentParentChild.id);
|
||||||
|
}
|
||||||
|
const viewPadres = document.getElementById('viewPadres');
|
||||||
|
const appContainer = document.getElementById('appContainer');
|
||||||
|
const bottomNav = document.getElementById('pwaBottomNav');
|
||||||
|
const btnPadres = document.getElementById('btnModePadres');
|
||||||
|
if (viewPadres) viewPadres.style.display = 'none';
|
||||||
|
if (appContainer) appContainer.style.display = 'block';
|
||||||
|
if (bottomNav) bottomNav.style.display = 'flex';
|
||||||
|
if (btnPadres) {
|
||||||
|
btnPadres.style.display = 'inline-block';
|
||||||
|
btnPadres.innerHTML = '⬅ Portal Padres';
|
||||||
|
btnPadres.onclick = () => returnToParentDashboard();
|
||||||
|
}
|
||||||
|
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||||
|
}
|
||||||
|
|
||||||
|
function returnToParentDashboard() {
|
||||||
|
const viewPadres = document.getElementById('viewPadres');
|
||||||
|
const appContainer = document.getElementById('appContainer');
|
||||||
|
const bottomNav = document.getElementById('pwaBottomNav');
|
||||||
|
if (viewPadres) viewPadres.style.display = 'block';
|
||||||
|
if (appContainer) appContainer.style.display = 'none';
|
||||||
|
if (bottomNav) bottomNav.style.display = 'none';
|
||||||
|
loadParentDashboard();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// ESCANEO QR Y VINCULACIÓN DE ESTUDIANTES PARA PADRES
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
function openScanChildQrModal() {
|
||||||
|
const modal = document.getElementById('modalScanChildQr');
|
||||||
|
if (modal) modal.style.display = 'flex';
|
||||||
|
const input = document.getElementById('inputManualStudentCode');
|
||||||
|
if (input) input.value = '';
|
||||||
|
startScanChildCamera();
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeScanChildQrModal(event) {
|
||||||
|
if (event && event.target && event.target.id !== 'modalScanChildQr') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
stopScanChildCamera();
|
||||||
|
const modal = document.getElementById('modalScanChildQr');
|
||||||
|
if (modal) modal.style.display = 'none';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startScanChildCamera() {
|
||||||
|
stopScanChildCamera();
|
||||||
|
const video = document.getElementById('videoScanChild');
|
||||||
|
const canvas = document.getElementById('canvasScanChild');
|
||||||
|
if (!video || !canvas) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
scanChildStream = await navigator.mediaDevices.getUserMedia({
|
||||||
|
video: { facingMode: 'environment', width: { ideal: 640 }, height: { ideal: 480 } }
|
||||||
|
});
|
||||||
|
video.srcObject = scanChildStream;
|
||||||
|
video.setAttribute('playsinline', true);
|
||||||
|
await video.play();
|
||||||
|
|
||||||
|
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
||||||
|
|
||||||
|
function scanFrame() {
|
||||||
|
if (video.readyState === video.HAVE_ENOUGH_DATA) {
|
||||||
|
canvas.width = video.videoWidth;
|
||||||
|
canvas.height = video.videoHeight;
|
||||||
|
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
|
||||||
|
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
||||||
|
if (window.jsQR) {
|
||||||
|
const code = window.jsQR(imageData.data, imageData.width, imageData.height, {
|
||||||
|
inversionAttempts: 'dontInvert'
|
||||||
|
});
|
||||||
|
if (code && code.data) {
|
||||||
|
handleChildQrDetected(code.data);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
scanChildAnimId = requestAnimationFrame(scanFrame);
|
||||||
|
}
|
||||||
|
scanChildAnimId = requestAnimationFrame(scanFrame);
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('Cámara no disponible para escaneo de carné:', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopScanChildCamera() {
|
||||||
|
if (scanChildAnimId) {
|
||||||
|
cancelAnimationFrame(scanChildAnimId);
|
||||||
|
scanChildAnimId = null;
|
||||||
|
}
|
||||||
|
if (scanChildStream) {
|
||||||
|
scanChildStream.getTracks().forEach(t => t.stop());
|
||||||
|
scanChildStream = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleChildQrDetected(token) {
|
||||||
|
stopScanChildCamera();
|
||||||
|
if (window.sounds) window.sounds.playBeep();
|
||||||
|
await linkStudentToParentAccount(token);
|
||||||
|
}
|
||||||
|
|
||||||
|
function submitManualStudentLink() {
|
||||||
|
const input = document.getElementById('inputManualStudentCode');
|
||||||
|
const val = input ? input.value.trim() : '';
|
||||||
|
if (!val) {
|
||||||
|
alert('Por favor ingresa el carné o token del estudiante.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
linkStudentToParentAccount(val);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function linkStudentToParentAccount(tokenOrCode) {
|
||||||
|
if (!currentUser || !currentUser.id) {
|
||||||
|
alert('Debes iniciar sesión como padre para vincular un estudiante.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/padres/vincular-hijo', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
padre_usuario_id: currentUser.id,
|
||||||
|
qr_token_o_codigo: tokenOrCode
|
||||||
|
})
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (!res.ok) throw new Error(data.error);
|
||||||
|
|
||||||
|
currentUser.hijos = data.hijos;
|
||||||
|
localStorage.setItem('recreopay_user', JSON.stringify(currentUser));
|
||||||
|
currentParentChild = data.estudiante;
|
||||||
|
|
||||||
|
closeScanChildQrModal();
|
||||||
|
if (window.sounds) window.sounds.playSuccess();
|
||||||
|
alert(`🎉 ¡Éxito!\n${data.mensaje}`);
|
||||||
|
renderParentDashboardView();
|
||||||
|
} catch (err) {
|
||||||
|
if (window.sounds) window.sounds.playError();
|
||||||
|
alert(`❌ ${err.message}`);
|
||||||
|
// Reiniciar cámara si el modal sigue abierto
|
||||||
|
const modal = document.getElementById('modalScanChildQr');
|
||||||
|
if (modal && modal.style.display !== 'none') {
|
||||||
|
startScanChildCamera();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1717,17 +2191,246 @@ async function submitNewStudent(event) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// BUSCADOR INTELIGENTE Y RECARGA EN CAJA (ADMIN)
|
||||||
|
// ==========================================
|
||||||
|
|
||||||
|
function setupAdminSmartSearch() {
|
||||||
|
if (students && students.length > 0) {
|
||||||
|
populateAdminRecargaStudents(students);
|
||||||
|
if (!adminSelectedStudent) {
|
||||||
|
selectAdminStudent(students[0].id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function populateAdminRecargaStudents(list) {
|
function populateAdminRecargaStudents(list) {
|
||||||
const sel = document.getElementById('adminRecargaStudentSelect');
|
const sel = document.getElementById('adminRecargaStudentSelect');
|
||||||
if (!sel) return;
|
if (!sel) return;
|
||||||
sel.innerHTML = list.map(s => `
|
sel.innerHTML = (list || []).map(s => `
|
||||||
<option value="${s.id}">${s.nombre_completo} (Saldo actual: ₡${s.saldo_colones.toLocaleString('es-CR')})</option>
|
<option value="${s.id}">${s.nombre_completo} (Saldo actual: ₡${(s.saldo_colones || 0).toLocaleString('es-CR')})</option>
|
||||||
`).join('');
|
`).join('');
|
||||||
|
|
||||||
|
if (list && list.length > 0 && !adminSelectedStudent) {
|
||||||
|
selectAdminStudent(list[0].id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onAdminSearchStudent(query) {
|
||||||
|
const q = (query || '').trim().toLowerCase();
|
||||||
|
const dropdown = document.getElementById('adminSearchResultsDropdown');
|
||||||
|
const btnClear = document.getElementById('btnClearAdminSearch');
|
||||||
|
|
||||||
|
if (btnClear) btnClear.style.display = q.length > 0 ? 'block' : 'none';
|
||||||
|
if (!dropdown) return;
|
||||||
|
|
||||||
|
if (q.length === 0) {
|
||||||
|
dropdown.style.display = 'none';
|
||||||
|
dropdown.innerHTML = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const results = (students || []).filter(s => {
|
||||||
|
const nombre = (s.nombre_completo || '').toLowerCase();
|
||||||
|
const codigo = (s.codigo_estudiante || '').toLowerCase();
|
||||||
|
const grado = `${s.grado || ''} ${s.seccion || ''}`.toLowerCase();
|
||||||
|
return nombre.includes(q) || codigo.includes(q) || grado.includes(q);
|
||||||
|
});
|
||||||
|
|
||||||
|
if (results.length === 0) {
|
||||||
|
dropdown.innerHTML = `
|
||||||
|
<div style="padding: 12px; text-align: center; color: var(--text-muted); font-size: 0.8rem;">
|
||||||
|
No se encontró ningún estudiante con "<strong>${query}</strong>"
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
dropdown.style.display = 'block';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
dropdown.innerHTML = results.map(s => `
|
||||||
|
<div class="admin-search-item" onclick="selectAdminStudent(${s.id})">
|
||||||
|
<img src="${s.foto_url || '/img/avatar_default.png'}" style="width: 36px; height: 36px; border-radius: 50%; object-fit: cover; border: 1.5px solid #0284c7; flex-shrink: 0;">
|
||||||
|
<div style="min-width: 0; flex: 1;">
|
||||||
|
<strong style="font-size: 0.88rem; color: var(--text-main); display: block; word-break: break-word;">${s.nombre_completo}</strong>
|
||||||
|
<span style="font-size: 0.72rem; color: var(--text-muted);">${s.grado} - Sec. ${s.seccion} • Cód: ${s.codigo_estudiante}</span>
|
||||||
|
</div>
|
||||||
|
<div style="text-align: right; flex-shrink: 0;">
|
||||||
|
<span style="font-size: 0.65rem; color: var(--text-muted); display: block; text-transform: uppercase;">Saldo</span>
|
||||||
|
<strong style="font-size: 0.95rem; color: #10b981;">₡${(s.saldo_colones || 0).toLocaleString('es-CR')}</strong>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`).join('');
|
||||||
|
dropdown.style.display = 'block';
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearAdminSearchStudent() {
|
||||||
|
const input = document.getElementById('inputAdminSearchStudent');
|
||||||
|
const btnClear = document.getElementById('btnClearAdminSearch');
|
||||||
|
const dropdown = document.getElementById('adminSearchResultsDropdown');
|
||||||
|
if (input) input.value = '';
|
||||||
|
if (btnClear) btnClear.style.display = 'none';
|
||||||
|
if (dropdown) {
|
||||||
|
dropdown.style.display = 'none';
|
||||||
|
dropdown.innerHTML = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onAdminSelectChange(studentId) {
|
||||||
|
selectAdminStudent(parseInt(studentId, 10));
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectAdminStudent(studentId) {
|
||||||
|
const id = parseInt(studentId, 10);
|
||||||
|
const student = (students || []).find(s => s.id === id);
|
||||||
|
if (!student) return;
|
||||||
|
|
||||||
|
adminSelectedStudent = student;
|
||||||
|
|
||||||
|
const sel = document.getElementById('adminRecargaStudentSelect');
|
||||||
|
if (sel) sel.value = String(student.id);
|
||||||
|
|
||||||
|
const banner = document.getElementById('adminSelectedStudentBanner');
|
||||||
|
const avatar = document.getElementById('adminSelectedAvatar');
|
||||||
|
const name = document.getElementById('adminSelectedName');
|
||||||
|
const statusBadge = document.getElementById('adminSelectedStatusBadge');
|
||||||
|
const meta = document.getElementById('adminSelectedMeta');
|
||||||
|
const balance = document.getElementById('adminSelectedBalance');
|
||||||
|
const searchInput = document.getElementById('inputAdminSearchStudent');
|
||||||
|
const dropdown = document.getElementById('adminSearchResultsDropdown');
|
||||||
|
|
||||||
|
if (banner) banner.style.display = 'flex';
|
||||||
|
if (avatar) avatar.src = student.foto_url || '/img/avatar_default.png';
|
||||||
|
if (name) name.textContent = student.nombre_completo;
|
||||||
|
if (statusBadge) {
|
||||||
|
if (student.tarjeta_bloqueada) {
|
||||||
|
statusBadge.textContent = 'BLOQUEADA';
|
||||||
|
statusBadge.style.background = '#fee2e2';
|
||||||
|
statusBadge.style.color = '#dc2626';
|
||||||
|
} else {
|
||||||
|
statusBadge.textContent = 'ACTIVA';
|
||||||
|
statusBadge.style.background = '#dcfce7';
|
||||||
|
statusBadge.style.color = '#166534';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (meta) meta.textContent = `${student.grado} - Sección ${student.seccion} • Cód: ${student.codigo_estudiante}`;
|
||||||
|
if (balance) balance.textContent = `₡${(student.saldo_colones || 0).toLocaleString('es-CR')}`;
|
||||||
|
|
||||||
|
if (searchInput) searchInput.value = student.nombre_completo;
|
||||||
|
if (dropdown) dropdown.style.display = 'none';
|
||||||
|
|
||||||
|
const montoInput = document.getElementById('adminRecargaMonto');
|
||||||
|
if (montoInput) montoInput.focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ESCANEO QR CON CÁMARA EN MOSTRADOR DE SODA (ADMIN)
|
||||||
|
function openAdminScanQrModal() {
|
||||||
|
const modal = document.getElementById('modalAdminScanQr');
|
||||||
|
if (modal) modal.style.display = 'flex';
|
||||||
|
startScanAdminCamera();
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeAdminScanQrModal(event) {
|
||||||
|
if (event && event.target && event.target.id !== 'modalAdminScanQr') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
stopScanAdminCamera();
|
||||||
|
const modal = document.getElementById('modalAdminScanQr');
|
||||||
|
if (modal) modal.style.display = 'none';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startScanAdminCamera() {
|
||||||
|
stopScanAdminCamera();
|
||||||
|
const video = document.getElementById('videoAdminScan');
|
||||||
|
const canvas = document.getElementById('canvasAdminScan');
|
||||||
|
if (!video || !canvas) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
scanAdminStream = await navigator.mediaDevices.getUserMedia({
|
||||||
|
video: { facingMode: 'environment', width: { ideal: 640 }, height: { ideal: 480 } }
|
||||||
|
});
|
||||||
|
video.srcObject = scanAdminStream;
|
||||||
|
video.setAttribute('playsinline', true);
|
||||||
|
await video.play();
|
||||||
|
|
||||||
|
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
||||||
|
|
||||||
|
function scanFrame() {
|
||||||
|
if (video.readyState === video.HAVE_ENOUGH_DATA) {
|
||||||
|
canvas.width = video.videoWidth;
|
||||||
|
canvas.height = video.videoHeight;
|
||||||
|
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
|
||||||
|
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
||||||
|
if (window.jsQR) {
|
||||||
|
const code = window.jsQR(imageData.data, imageData.width, imageData.height, {
|
||||||
|
inversionAttempts: 'dontInvert'
|
||||||
|
});
|
||||||
|
if (code && code.data) {
|
||||||
|
handleAdminQrDetected(code.data);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
scanAdminAnimId = requestAnimationFrame(scanFrame);
|
||||||
|
}
|
||||||
|
scanAdminAnimId = requestAnimationFrame(scanFrame);
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('Cámara de mostrador no disponible:', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopScanAdminCamera() {
|
||||||
|
if (scanAdminAnimId) {
|
||||||
|
cancelAnimationFrame(scanAdminAnimId);
|
||||||
|
scanAdminAnimId = null;
|
||||||
|
}
|
||||||
|
if (scanAdminStream) {
|
||||||
|
scanAdminStream.getTracks().forEach(t => t.stop());
|
||||||
|
scanAdminStream = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleAdminQrDetected(token) {
|
||||||
|
stopScanAdminCamera();
|
||||||
|
const modal = document.getElementById('modalAdminScanQr');
|
||||||
|
if (modal) modal.style.display = 'none';
|
||||||
|
if (window.sounds) window.sounds.playBeep();
|
||||||
|
|
||||||
|
const clean = String(token).trim().toLowerCase();
|
||||||
|
let student = (students || []).find(s =>
|
||||||
|
(s.qr_token && s.qr_token.toLowerCase() === clean) ||
|
||||||
|
(s.codigo_estudiante && s.codigo_estudiante.toLowerCase() === clean)
|
||||||
|
);
|
||||||
|
|
||||||
|
if (student) {
|
||||||
|
selectAdminStudent(student.id);
|
||||||
|
if (window.sounds) window.sounds.playSuccess();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Si no está en cache local, buscarlo en el servidor
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/estudiantes/qr/${encodeURIComponent(token)}`);
|
||||||
|
const data = await res.json();
|
||||||
|
if (!res.ok) throw new Error(data.error);
|
||||||
|
|
||||||
|
student = data;
|
||||||
|
const idx = (students || []).findIndex(s => s.id === student.id);
|
||||||
|
if (idx >= 0) students[idx] = student;
|
||||||
|
else students.push(student);
|
||||||
|
|
||||||
|
populateAdminRecargaStudents(students);
|
||||||
|
selectAdminStudent(student.id);
|
||||||
|
if (window.sounds) window.sounds.playSuccess();
|
||||||
|
} catch (err) {
|
||||||
|
if (window.sounds) window.sounds.playError();
|
||||||
|
alert(`❌ Estudiante no encontrado por QR: ${err.message}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function setAdminRecargaPreset(amt) {
|
function setAdminRecargaPreset(amt) {
|
||||||
const input = document.getElementById('adminRecargaMonto');
|
const input = document.getElementById('adminRecargaMonto');
|
||||||
if (input) input.value = amt;
|
if (input) input.value = amt;
|
||||||
|
if (window.sounds) window.sounds.playTap();
|
||||||
}
|
}
|
||||||
|
|
||||||
async function submitAdminManualRecharge() {
|
async function submitAdminManualRecharge() {
|
||||||
@@ -1736,12 +2439,15 @@ async function submitAdminManualRecharge() {
|
|||||||
const inputDesc = document.getElementById('adminRecargaDescripcion');
|
const inputDesc = document.getElementById('adminRecargaDescripcion');
|
||||||
const btn = document.getElementById('btnAdminSubmitRecarga');
|
const btn = document.getElementById('btnAdminSubmitRecarga');
|
||||||
|
|
||||||
if (!sel || !inputMonto) return;
|
let studentId = adminSelectedStudent ? adminSelectedStudent.id : (sel ? parseInt(sel.value, 10) : null);
|
||||||
|
const monto = parseInt(inputMonto ? inputMonto.value : 0, 10);
|
||||||
const studentId = parseInt(sel.value, 10);
|
|
||||||
const monto = parseInt(inputMonto.value, 10);
|
|
||||||
const descripcion = inputDesc ? inputDesc.value.trim() : '';
|
const descripcion = inputDesc ? inputDesc.value.trim() : '';
|
||||||
|
|
||||||
|
if (!studentId) {
|
||||||
|
alert('Por favor selecciona un estudiante antes de aplicar la recarga.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (isNaN(monto) || monto <= 0) {
|
if (isNaN(monto) || monto <= 0) {
|
||||||
alert('Ingresa un monto válido mayor a ₡0 para recargar.');
|
alert('Ingresa un monto válido mayor a ₡0 para recargar.');
|
||||||
return;
|
return;
|
||||||
@@ -1756,7 +2462,7 @@ async function submitAdminManualRecharge() {
|
|||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
monto,
|
monto,
|
||||||
descripcion,
|
descripcion: descripcion || 'Pago en efectivo en mostrador de soda',
|
||||||
metodo: 'Efectivo en mostrador'
|
metodo: 'Efectivo en mostrador'
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
@@ -1769,7 +2475,16 @@ async function submitAdminManualRecharge() {
|
|||||||
|
|
||||||
inputMonto.value = '';
|
inputMonto.value = '';
|
||||||
if (inputDesc) inputDesc.value = '';
|
if (inputDesc) inputDesc.value = '';
|
||||||
|
|
||||||
|
// Actualizar datos del estudiante en cache y banner
|
||||||
|
if (adminSelectedStudent && adminSelectedStudent.id === studentId) {
|
||||||
|
adminSelectedStudent.saldo_colones = data.saldo_nuevo;
|
||||||
|
const balanceEl = document.getElementById('adminSelectedBalance');
|
||||||
|
if (balanceEl) balanceEl.textContent = `₡${data.saldo_nuevo.toLocaleString('es-CR')}`;
|
||||||
|
}
|
||||||
|
|
||||||
await loadAdminData();
|
await loadAdminData();
|
||||||
|
populateAdminRecargaStudents(students);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (window.sounds) window.sounds.playError();
|
if (window.sounds) window.sounds.playError();
|
||||||
alert(`❌ Error al recargar: ${err.message}`);
|
alert(`❌ Error al recargar: ${err.message}`);
|
||||||
|
|||||||
+2
-2
@@ -1,5 +1,5 @@
|
|||||||
// RecreoPay PWA Service Worker v7.0 - Alta Estabilidad
|
// RecreoPay PWA Service Worker v8.0 - Portal Padres, Registro QR y Buscador Admin
|
||||||
const CACHE_NAME = 'recreopay-v7.0';
|
const CACHE_NAME = 'recreopay-v8.0';
|
||||||
const STATIC_ASSETS = [
|
const STATIC_ASSETS = [
|
||||||
'/',
|
'/',
|
||||||
'/index.html',
|
'/index.html',
|
||||||
|
|||||||
@@ -121,6 +121,23 @@ function initDatabase() {
|
|||||||
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 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) {}
|
try { db.exec('UPDATE productos SET stock = 10 WHERE stock IS NULL'); } catch (e) {}
|
||||||
|
|
||||||
|
// 8. Relación N:M Padres - Estudiantes
|
||||||
|
try {
|
||||||
|
db.exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS padres_estudiantes (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
padre_usuario_id INTEGER NOT NULL REFERENCES usuarios(id) ON DELETE CASCADE,
|
||||||
|
estudiante_id INTEGER NOT NULL REFERENCES estudiantes(id) ON DELETE CASCADE,
|
||||||
|
creado_en DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
UNIQUE(padre_usuario_id, estudiante_id)
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
db.exec(`
|
||||||
|
INSERT OR IGNORE INTO padres_estudiantes (padre_usuario_id, estudiante_id)
|
||||||
|
SELECT padre_usuario_id, id FROM estudiantes WHERE padre_usuario_id IS NOT NULL;
|
||||||
|
`);
|
||||||
|
} catch (e) {}
|
||||||
|
|
||||||
seedInitialData();
|
seedInitialData();
|
||||||
seedUsuarios();
|
seedUsuarios();
|
||||||
}
|
}
|
||||||
|
|||||||
+144
-4
@@ -77,9 +77,15 @@ app.post('/api/auth/login', (req, res) => {
|
|||||||
estudiante = db.prepare('SELECT * FROM estudiantes ORDER BY id ASC LIMIT 1').get();
|
estudiante = db.prepare('SELECT * FROM estudiantes ORDER BY id ASC LIMIT 1').get();
|
||||||
}
|
}
|
||||||
} else if (user.rol === 'padre') {
|
} else if (user.rol === 'padre') {
|
||||||
hijos = db.prepare('SELECT * FROM estudiantes WHERE padre_usuario_id = ?').all(user.id);
|
hijos = db.prepare(`
|
||||||
|
SELECT e.*
|
||||||
|
FROM estudiantes e
|
||||||
|
JOIN padres_estudiantes pe ON e.id = pe.estudiante_id
|
||||||
|
WHERE pe.padre_usuario_id = ?
|
||||||
|
ORDER BY e.nombre_completo ASC
|
||||||
|
`).all(user.id);
|
||||||
if (hijos.length === 0) {
|
if (hijos.length === 0) {
|
||||||
hijos = db.prepare('SELECT * FROM estudiantes WHERE id IN (1, 2)').all();
|
hijos = db.prepare('SELECT * FROM estudiantes WHERE padre_usuario_id = ?').all(user.id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,6 +107,135 @@ app.post('/api/auth/login', (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Registro de nuevos padres desde la pantalla de bienvenida
|
||||||
|
app.post('/api/auth/register-padre', (req, res) => {
|
||||||
|
try {
|
||||||
|
const { nombre, telefono, email, username, password } = req.body;
|
||||||
|
if (!nombre || !username || !password) {
|
||||||
|
return res.status(400).json({ error: 'Nombre completo, usuario y contraseña son requeridos' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const cleanUser = String(username).trim().toLowerCase();
|
||||||
|
const cleanPass = String(password).trim();
|
||||||
|
const cleanNombre = String(nombre).trim();
|
||||||
|
const cleanTel = telefono ? String(telefono).trim() : '';
|
||||||
|
const cleanEmail = email ? String(email).trim().toLowerCase() : '';
|
||||||
|
|
||||||
|
if (cleanUser.length < 3) {
|
||||||
|
return res.status(400).json({ error: 'El nombre de usuario debe tener al menos 3 caracteres' });
|
||||||
|
}
|
||||||
|
if (cleanPass.length < 4) {
|
||||||
|
return res.status(400).json({ error: 'La contraseña debe tener al menos 4 caracteres' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Comprobar si el usuario ya existe
|
||||||
|
const exists = db.prepare('SELECT id FROM usuarios WHERE LOWER(username) = ?').get(cleanUser);
|
||||||
|
if (exists) {
|
||||||
|
return res.status(400).json({ error: 'Ese nombre de usuario ya está en uso. Por favor elige otro.' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const insert = db.prepare(`
|
||||||
|
INSERT INTO usuarios (username, password_hash, rol, nombre, telefono, email)
|
||||||
|
VALUES (?, ?, 'padre', ?, ?, ?)
|
||||||
|
`);
|
||||||
|
const result = insert.run(cleanUser, cleanPass, cleanNombre, cleanTel, cleanEmail);
|
||||||
|
|
||||||
|
const newUser = {
|
||||||
|
id: result.lastInsertRowid,
|
||||||
|
username: cleanUser,
|
||||||
|
rol: 'padre',
|
||||||
|
nombre: cleanNombre,
|
||||||
|
telefono: cleanTel,
|
||||||
|
email: cleanEmail
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
success: true,
|
||||||
|
user: newUser,
|
||||||
|
hijos: []
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
res.status(500).json({ error: err.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Vincular estudiante a la cuenta de padre mediante QR o código de carné
|
||||||
|
app.post('/api/padres/vincular-hijo', (req, res) => {
|
||||||
|
try {
|
||||||
|
const { padre_usuario_id, qr_token_o_codigo } = req.body;
|
||||||
|
if (!padre_usuario_id || !qr_token_o_codigo) {
|
||||||
|
return res.status(400).json({ error: 'Faltan datos de vinculación (ID de padre o código)' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const cleanQuery = String(qr_token_o_codigo).trim();
|
||||||
|
|
||||||
|
// Buscar al estudiante por qr_token o codigo_estudiante o id
|
||||||
|
const est = db.prepare(`
|
||||||
|
SELECT * FROM estudiantes
|
||||||
|
WHERE qr_token = ? OR codigo_estudiante = ? OR LOWER(codigo_estudiante) = LOWER(?)
|
||||||
|
`).get(cleanQuery, cleanQuery, cleanQuery);
|
||||||
|
|
||||||
|
if (!est) {
|
||||||
|
return res.status(404).json({ error: 'No se encontró ningún estudiante con ese código QR o número de carné. Verifica que el código sea correcto.' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Insertar en tabla padres_estudiantes (permite vinculación múltiple para ambos padres)
|
||||||
|
db.prepare(`
|
||||||
|
INSERT OR IGNORE INTO padres_estudiantes (padre_usuario_id, estudiante_id)
|
||||||
|
VALUES (?, ?)
|
||||||
|
`).run(padre_usuario_id, est.id);
|
||||||
|
|
||||||
|
// Actualizar también campo legacy en caso de ser el primer padre
|
||||||
|
if (!est.padre_usuario_id) {
|
||||||
|
db.prepare('UPDATE estudiantes SET padre_usuario_id = ? WHERE id = ?').run(padre_usuario_id, est.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Devolver lista completa actualizada de hijos del padre
|
||||||
|
const hijos = db.prepare(`
|
||||||
|
SELECT e.*
|
||||||
|
FROM estudiantes e
|
||||||
|
JOIN padres_estudiantes pe ON e.id = pe.estudiante_id
|
||||||
|
WHERE pe.padre_usuario_id = ?
|
||||||
|
ORDER BY e.nombre_completo ASC
|
||||||
|
`).all(padre_usuario_id);
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
success: true,
|
||||||
|
mensaje: `¡Estudiante ${est.nombre_completo} vinculado con éxito!`,
|
||||||
|
estudiante: est,
|
||||||
|
hijos
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
res.status(500).json({ error: err.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Consultar lista en tiempo real de hijos vinculados
|
||||||
|
app.get('/api/padres/mis-hijos', (req, res) => {
|
||||||
|
try {
|
||||||
|
const { padre_usuario_id } = req.query;
|
||||||
|
if (!padre_usuario_id) {
|
||||||
|
return res.status(400).json({ error: 'Falta padre_usuario_id' });
|
||||||
|
}
|
||||||
|
|
||||||
|
let hijos = db.prepare(`
|
||||||
|
SELECT e.*
|
||||||
|
FROM estudiantes e
|
||||||
|
JOIN padres_estudiantes pe ON e.id = pe.estudiante_id
|
||||||
|
WHERE pe.padre_usuario_id = ?
|
||||||
|
ORDER BY e.nombre_completo ASC
|
||||||
|
`).all(padre_usuario_id);
|
||||||
|
|
||||||
|
if (hijos.length === 0) {
|
||||||
|
hijos = db.prepare('SELECT * FROM estudiantes WHERE padre_usuario_id = ?').all(padre_usuario_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json({ success: true, hijos });
|
||||||
|
} catch (err) {
|
||||||
|
res.status(500).json({ error: err.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// Restablecer contraseña / PIN del estudiante desde el portal de padres
|
// Restablecer contraseña / PIN del estudiante desde el portal de padres
|
||||||
app.post('/api/padres/restablecer-acceso', (req, res) => {
|
app.post('/api/padres/restablecer-acceso', (req, res) => {
|
||||||
try {
|
try {
|
||||||
@@ -452,7 +587,8 @@ app.get('/api/estudiantes/:id', (req, res) => {
|
|||||||
app.get('/api/estudiantes/qr/:token', (req, res) => {
|
app.get('/api/estudiantes/qr/:token', (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { token } = req.params;
|
const { token } = req.params;
|
||||||
const est = db.prepare('SELECT * FROM estudiantes WHERE qr_token = ? OR codigo_estudiante = ?').get(token, token);
|
const cleanToken = String(token).trim();
|
||||||
|
const est = db.prepare('SELECT * FROM estudiantes WHERE qr_token = ? OR codigo_estudiante = ? OR LOWER(codigo_estudiante) = LOWER(?)').get(cleanToken, cleanToken, cleanToken);
|
||||||
if (!est) {
|
if (!est) {
|
||||||
return res.status(404).json({ error: 'Código QR no reconocido en la base de datos de la escuela' });
|
return res.status(404).json({ error: 'Código QR no reconocido en la base de datos de la escuela' });
|
||||||
}
|
}
|
||||||
@@ -638,7 +774,7 @@ app.post('/api/ordenes', (req, res) => {
|
|||||||
// Listar órdenes (con filtro por estado o tipo)
|
// Listar órdenes (con filtro por estado o tipo)
|
||||||
app.get('/api/ordenes', (req, res) => {
|
app.get('/api/ordenes', (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { estado, tipo } = req.query;
|
const { estado, tipo, estudiante_id } = req.query;
|
||||||
let query = `
|
let query = `
|
||||||
SELECT o.*, e.nombre_completo as estudiante_nombre, e.grado, e.seccion, e.foto_url,
|
SELECT o.*, e.nombre_completo as estudiante_nombre, e.grado, e.seccion, e.foto_url,
|
||||||
(SELECT json_group_array(json_object('producto_id', p.id, 'nombre', p.nombre, 'icono', p.icono, 'cantidad', d.cantidad, 'precio_unitario', d.precio_unitario, 'subtotal', d.subtotal))
|
(SELECT json_group_array(json_object('producto_id', p.id, 'nombre', p.nombre, 'icono', p.icono, 'cantidad', d.cantidad, 'precio_unitario', d.precio_unitario, 'subtotal', d.subtotal))
|
||||||
@@ -649,6 +785,10 @@ app.get('/api/ordenes', (req, res) => {
|
|||||||
`;
|
`;
|
||||||
const params = [];
|
const params = [];
|
||||||
|
|
||||||
|
if (estudiante_id) {
|
||||||
|
query += ' AND o.estudiante_id = ?';
|
||||||
|
params.push(estudiante_id);
|
||||||
|
}
|
||||||
if (estado) {
|
if (estado) {
|
||||||
query += ' AND o.estado = ?';
|
query += ' AND o.estado = ?';
|
||||||
params.push(estado);
|
params.push(estado);
|
||||||
|
|||||||
Reference in New Issue
Block a user