feat(developer): add individual student registration with school selector in developer suite

This commit is contained in:
unknown
2026-10-08 18:24:52 -06:00
parent 87c5baa263
commit 7c62608519
3 changed files with 118 additions and 12 deletions
+32 -5
View File
@@ -263,10 +263,16 @@
<option value="estudiante">Estudiantes</option>
</select>
</div>
<button onclick="openModalDevUser()" class="dev-action-btn dev-action-btn-primary" style="padding: 10px 18px; font-size: 0.88rem; display: inline-flex; align-items: center; gap: 6px;">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><line x1="19" x2="19" y1="8" y2="14"/><line x1="22" x2="16" y1="11" y2="11"/></svg>
<span>Crear Nuevo Usuario / Admin</span>
</button>
<div style="display: flex; gap: 8px; flex-wrap: wrap;">
<button type="button" onclick="openNewStudentModalFromDev()" class="dev-action-btn" style="padding: 10px 18px; font-size: 0.88rem; display: inline-flex; align-items: center; gap: 6px; background: linear-gradient(135deg, #0284c7, #0369a1); color: #ffffff; border: none; font-weight: 800; border-radius: 10px; box-shadow: 0 2px 6px rgba(2,132,199,0.3); cursor: pointer;">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 10v6M2 10l10-5 10 5-10 5z"/><path d="M6 12v5c3 3 9 3 12 0v-5"/></svg>
<span>🎓 + Registrar Estudiante</span>
</button>
<button onclick="openModalDevUser()" class="dev-action-btn dev-action-btn-primary" style="padding: 10px 18px; font-size: 0.88rem; display: inline-flex; align-items: center; gap: 6px;">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><line x1="19" x2="19" y1="8" y2="14"/><line x1="22" x2="16" y1="11" y2="11"/></svg>
<span>Crear Usuario / Admin</span>
</button>
</div>
</div>
<!-- Resumen rápido de usuarios -->
@@ -2550,6 +2556,14 @@
</div>
<form id="formNewStudent" onsubmit="submitNewStudent(event)">
<!-- Selector de Escuela Destino (Visible en Modo Developer) -->
<div id="newEstEscuelaContainer" style="display: none; margin-bottom: 12px; background: #f0fdf4; border: 1.5px solid #86efac; border-radius: 10px; padding: 10px;">
<label style="display: block; font-size: 0.78rem; font-weight: 800; color: #166534; margin-bottom: 4px;">🏫 Escuela / Institución Destino *:</label>
<select id="newEstEscuelaSelect" style="width: 100%; padding: 8px 10px; border-radius: 8px; border: 1.5px solid #86efac; font-weight: 800; box-sizing: border-box; background: #ffffff; color: #0f172a;">
<!-- Opciones cargadas dinámicamente -->
</select>
<small style="display: block; font-size: 0.70rem; color: #15803d; margin-top: 3px;">El estudiante se registrará en esta sede y heredará su código institucional.</small>
</div>
<div style="margin-bottom: 10px;">
<label style="display: block; font-size: 0.78rem; font-weight: 800; color: var(--text-main); margin-bottom: 3px;">Tipo de Perfil / Negocio:</label>
<select id="newEstTipo" style="width: 100%; padding: 8px 10px; border-radius: 8px; border: 1.5px solid var(--border); font-weight: 800; box-sizing: border-box; background: var(--card-bg); color: var(--text-main);">
@@ -3088,7 +3102,7 @@
</div>
<div>
<label style="font-size: 0.8rem; font-weight: 800; color: var(--text-main); display: block; margin-bottom: 4px;">Rol en el Sistema:</label>
<select id="devInputRol" required style="width: 100%; padding: 9px 12px; border-radius: 10px; border: 1.5px solid var(--border); background: var(--bg-main); color: var(--text-main); font-weight: 700; box-sizing: border-box;">
<select id="devInputRol" required onchange="handleDevUserRoleChange()" style="width: 100%; padding: 9px 12px; border-radius: 10px; border: 1.5px solid var(--border); background: var(--bg-main); color: var(--text-main); font-weight: 700; box-sizing: border-box;">
<option value="admin">Administrador (Soda/Escuela)</option>
<option value="developer">Developer Master</option>
<option value="cajero">Cajero POS</option>
@@ -3099,6 +3113,19 @@
</div>
</div>
<!-- Banner de sugerencia si seleccionan Estudiante -->
<div id="devStudentRoleTip" style="display: none; background: #f0fdf4; border: 1.5px solid #86efac; border-radius: 10px; padding: 10px 14px; margin-bottom: 12px;">
<div style="display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap;">
<div style="font-size: 0.76rem; color: #166534; line-height: 1.35;">
🎓 <strong>¿Deseas generar carné oficial y código QR automático?</strong><br>
Este formulario solo crea credenciales de login. Para crear el estudiante completo con carné, QR y saldo:
</div>
<button type="button" onclick="closeModalDevUser(); openNewStudentModalFromDev();" class="dev-action-btn" style="padding: 6px 12px; font-size: 0.76rem; background: #0284c7; color: white; border: none; font-weight: 800; border-radius: 8px; cursor: pointer;">
Abrir Registro Oficial 🎓
</button>
</div>
</div>
<div style="margin-bottom: 12px;">
<label style="font-size: 0.8rem; font-weight: 800; color: var(--text-main); display: block; margin-bottom: 4px;">Nombre Completo:</label>
<input type="text" id="devInputNombre" required placeholder="ej: Juan Pérez Rojas" style="width: 100%; padding: 9px 12px; border-radius: 10px; border: 1.5px solid var(--border); background: var(--bg-main); color: var(--text-main); font-weight: 700; box-sizing: border-box;">
+74 -3
View File
@@ -5460,14 +5460,55 @@ async function toggleBlockCard(studentId, newBlocked) {
}
function openNewStudentModal() {
window.newStudentFromDev = false;
const escContainer = document.getElementById('newEstEscuelaContainer');
if (escContainer) escContainer.style.display = 'none';
const title = document.getElementById('modalNewStudentTitle');
if (title) title.textContent = 'Registrar Nuevo Alumno';
const modal = document.getElementById('modalNewStudent');
if (modal) modal.style.display = 'flex';
}
async function openNewStudentModalFromDev() {
window.newStudentFromDev = true;
const escContainer = document.getElementById('newEstEscuelaContainer');
if (escContainer) escContainer.style.display = 'block';
const title = document.getElementById('modalNewStudentTitle');
if (title) title.textContent = 'Registrar Nuevo Alumno (Developer)';
const escSelect = document.getElementById('newEstEscuelaSelect');
if (escSelect) {
escSelect.innerHTML = '<option value="">Cargando escuelas...</option>';
try {
const res = await fetch('/api/developer/escuelas');
if (res.ok) {
const escuelas = await res.json();
if (Array.isArray(escuelas) && escuelas.length > 0) {
escSelect.innerHTML = escuelas.map(e => `
<option value="${e.id}">${escapeHtml(e.nombre)} (${escapeHtml(e.codigo || 'Sede')})</option>
`).join('');
} else {
escSelect.innerHTML = '<option value="1">Soda Escolar Central (ESC01)</option>';
}
} else {
escSelect.innerHTML = '<option value="1">Soda Escolar Central (ESC01)</option>';
}
} catch (err) {
console.error('Error cargando escuelas en modal:', err);
escSelect.innerHTML = '<option value="1">Soda Escolar Central (ESC01)</option>';
}
}
const modal = document.getElementById('modalNewStudent');
if (modal) modal.style.display = 'flex';
}
window.openNewStudentModalFromDev = openNewStudentModalFromDev;
function closeNewStudentModal(event) {
if (event && event.target !== event.currentTarget) return;
const modal = document.getElementById('modalNewStudent');
if (modal) modal.style.display = 'none';
window.newStudentFromDev = false;
}
async function submitNewStudent(event) {
@@ -5491,7 +5532,15 @@ async function submitNewStudent(event) {
btn.textContent = 'Creando usuario y carné...';
try {
const escId = (currentUser && currentUser.escuela_id) || 1;
let escId = (currentUser && currentUser.escuela_id) || 1;
const escContainer = document.getElementById('newEstEscuelaContainer');
const escSelect = document.getElementById('newEstEscuelaSelect');
if (window.newStudentFromDev || (escContainer && escContainer.style.display !== 'none')) {
if (escSelect && escSelect.value) {
escId = parseInt(escSelect.value, 10);
}
}
const res = await fetch('/api/admin/estudiantes', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@@ -5514,11 +5563,18 @@ async function submitNewStudent(event) {
if (!res.ok) throw new Error(data.error);
if (window.sounds) window.sounds.playSuccess();
alert(`¡Estudiante Creado con Éxito!\nNombre: ${data.nombre_completo}\nCódigo: ${data.codigo_estudiante}\nQR Token: ${data.qr_token}`);
const credsMsg = data.username_creado ? `\n\nCredenciales de Acceso:\nUsuario: ${data.username_creado}\nPIN temporal: ${data.pin_creado || '1234'}` : '';
alert(`¡Estudiante Creado con Éxito!\n\nNombre: ${data.nombre_completo}\nCódigo Estudiante: ${data.codigo_estudiante}\nQR Token: ${data.qr_token}${credsMsg}`);
closeNewStudentModal();
document.getElementById('formNewStudent').reset();
await loadAdminData();
// Actualizar vistas correspondientes
if (window.newStudentFromDev || (currentUser && currentUser.rol === 'developer')) {
if (typeof loadDevUsuarios === 'function') await loadDevUsuarios();
if (typeof loadDeveloperDashboard === 'function') await loadDeveloperDashboard();
}
if (typeof loadAdminData === 'function') await loadAdminData();
} catch (err) {
if (window.sounds) window.sounds.playError();
alert(`Error al crear estudiante: ${err.message}`);
@@ -7690,6 +7746,7 @@ function renderDevUsuarios(users) {
<td style="padding: 10px 14px; font-weight: 800; color: var(--text-main);">
${escapeHtml(u.username)}
${extraInfo}
${u.escuela_nombre ? `<div style="font-size: 0.68rem; color: #0284c7; background: #e0f2fe; border: 1px solid #bae6fd; display: inline-flex; align-items: center; gap: 3px; padding: 1px 6px; border-radius: 4px; margin-top: 3px; font-weight: 700;">🏫 ${escapeHtml(u.escuela_nombre)}</div>` : ''}
</td>
<td style="padding: 10px 14px; color: var(--text-main); font-weight: 600;">${escapeHtml(u.nombre || '-')}</td>
<td style="padding: 10px 14px;">${roleBadge}</td>
@@ -7719,6 +7776,15 @@ function renderDevUsuarios(users) {
}).join('');
}
function handleDevUserRoleChange() {
const rolInput = document.getElementById('devInputRol');
const tip = document.getElementById('devStudentRoleTip');
if (rolInput && tip) {
tip.style.display = (rolInput.value === 'estudiante') ? 'block' : 'none';
}
}
window.handleDevUserRoleChange = handleDevUserRoleChange;
function openModalDevUser(userId = null) {
const modal = document.getElementById('modalDevUser');
const title = document.getElementById('modalDevUserTitle');
@@ -7730,6 +7796,7 @@ function openModalDevUser(userId = null) {
const pwdHelp = document.getElementById('devPasswordHelp');
const telInput = document.getElementById('devInputTelefono');
const emailInput = document.getElementById('devInputEmail');
const tip = document.getElementById('devStudentRoleTip');
if (userId) {
const user = devAllUsers.find(u => u.id === userId);
@@ -7744,6 +7811,7 @@ function openModalDevUser(userId = null) {
if (pwdHelp) pwdHelp.style.display = 'block';
telInput.value = user.telefono || '';
emailInput.value = user.email || '';
if (tip) tip.style.display = (user.rol === 'estudiante') ? 'block' : 'none';
} else {
title.textContent = 'Crear Nuevo Usuario / Admin';
idInput.value = '';
@@ -7755,6 +7823,7 @@ function openModalDevUser(userId = null) {
if (pwdHelp) pwdHelp.style.display = 'none';
telInput.value = '';
emailInput.value = '';
if (tip) tip.style.display = 'none';
}
modal.style.display = 'flex';
@@ -7764,6 +7833,8 @@ function closeModalDevUser(event) {
if (event && event.target !== event.currentTarget) return;
const modal = document.getElementById('modalDevUser');
if (modal) modal.style.display = 'none';
const tip = document.getElementById('devStudentRoleTip');
if (tip) tip.style.display = 'none';
}
async function saveDevUser(e) {
+12 -4
View File
@@ -1522,6 +1522,8 @@ app.get('/api/developer/usuarios', (req, res) => {
SELECT u.id, u.username, u.password_hash, u.rol, u.nombre, u.telefono, u.email, u.activo, u.creado_en, u.escuela_id,
esc.nombre as escuela_nombre, esc.codigo as escuela_codigo,
(SELECT COUNT(*) FROM estudiantes e WHERE e.usuario_id = u.id) as es_estudiante,
(SELECT e.codigo_estudiante FROM estudiantes e WHERE e.usuario_id = u.id LIMIT 1) as estudiante_codigo,
(SELECT e.grado FROM estudiantes e WHERE e.usuario_id = u.id LIMIT 1) as estudiante_grado,
(SELECT COUNT(*) FROM padres_estudiantes pe WHERE pe.padre_usuario_id = u.id) as hijos_vinculados
FROM usuarios u
LEFT JOIN escuelas esc ON u.escuela_id = esc.id
@@ -2246,7 +2248,7 @@ app.post('/api/admin/estudiantes', (req, res) => {
// Correlativo seguro basado en el último ID registrado (evita colisiones por borrado)
const maxRow = db.prepare('SELECT COALESCE(MAX(id), 0) + 1 as nextId FROM estudiantes').get();
const nextSeq = maxRow ? maxRow.nextId : 1;
const nextSeq = maxRow ? (maxRow.nextId || maxRow.nextid || 1) : 1;
// Resolver escuela y prefijo institucional
let escuelaId = req.body.escuela_id ? parseInt(req.body.escuela_id, 10) : 1;
@@ -2256,8 +2258,14 @@ app.post('/api/admin/estudiantes', (req, res) => {
if (escRow && escRow.codigo) schoolPrefix = escRow.codigo;
} catch (e) {}
// Prefijo institucional configurable (ej: SJT, LCR, EST)
const cleanPrefix = (prefijo || tipo_entidad || schoolPrefix).toUpperCase().trim().replace(/[^A-Z0-9]/g, '').substring(0, 6) || 'EST';
// Prefijo institucional configurable (ej: SJT, ESC01, o prefijos de perfil EMP, EVT, SOC)
let finalPrefix = schoolPrefix;
if (prefijo && prefijo !== 'EST') {
finalPrefix = prefijo;
} else if (tipo_entidad && tipo_entidad !== 'EST') {
finalPrefix = tipo_entidad;
}
const cleanPrefix = (finalPrefix || schoolPrefix || 'EST').toUpperCase().trim().replace(/[^A-Z0-9]/g, '').substring(0, 6) || 'EST';
const year = new Date().getFullYear();
const codigoEstudiante = `${cleanPrefix}-${year}-${String(nextSeq).padStart(5, '0')}`;
@@ -2316,7 +2324,7 @@ app.post('/api/admin/estudiantes', (req, res) => {
const creado = db.prepare('SELECT * FROM estudiantes WHERE id = ?').get(nuevoId);
broadcastEvent('estudiante_creado', creado);
res.status(201).json(creado);
res.status(201).json({ ...creado, username_creado: usernameEst, pin_creado: pin });
} catch (err) {
res.status(500).json({ error: err.message });
}