feat: escalabilidad de codigos a 5 digitos y soporte de prefijos multi-negocio

This commit is contained in:
unknown
2026-10-05 01:26:59 -06:00
parent 0840bf0217
commit cfc81a7e2d
3 changed files with 36 additions and 12 deletions
+12 -2
View File
@@ -947,8 +947,18 @@
<form id="formNewStudent" onsubmit="submitNewStudent(event)">
<div style="margin-bottom: 10px;">
<label style="display: block; font-size: 0.78rem; font-weight: 800; color: #334155; margin-bottom: 3px;">Nombre Completo:</label>
<input type="text" id="newEstNombre" placeholder="Ej: Daniel Sánchez Méndez" required style="width: 100%; padding: 8px 10px; border-radius: 8px; border: 1.5px solid #cbd5e1; font-weight: 700; box-sizing: border-box;">
<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);">
<option value="EST">🎒 Estudiante / Alumno (Escuela o Colegio)</option>
<option value="EMP">💼 Colaborador / Empleado (Empresa o Comedor)</option>
<option value="EVT">🎟️ Asistente / Pulsera (Evento o Feria)</option>
<option value="SOC">🏅 Socio / Miembro (Club o Gimnasio)</option>
</select>
</div>
<div style="margin-bottom: 10px;">
<label style="display: block; font-size: 0.78rem; font-weight: 800; color: var(--text-main); margin-bottom: 3px;">Nombre Completo *:</label>
<input type="text" id="newEstNombre" placeholder="Ej: Daniel Sánchez Méndez" required style="width: 100%; padding: 8px 10px; border-radius: 8px; border: 1.5px solid var(--border); font-weight: 700; box-sizing: border-box; background: var(--card-bg); color: var(--text-main);">
</div>
<div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px; margin-bottom: 10px;">
+6 -2
View File
@@ -2716,9 +2716,12 @@ async function submitNewStudent(event) {
const padre = document.getElementById('newEstPadre').value.trim();
const tel = document.getElementById('newEstTel').value.trim();
const tipoEl = document.getElementById('newEstTipo');
const prefijo = tipoEl ? tipoEl.value : 'EST';
const btn = document.getElementById('btnSubmitNewStudent');
btn.disabled = true;
btn.textContent = 'Creando alumno y carné...';
btn.textContent = 'Creando usuario y carné...';
try {
const res = await fetch('/api/admin/estudiantes', {
@@ -2733,7 +2736,8 @@ async function submitNewStudent(event) {
limite_diario_colones: limite,
alergias,
padre_nombre: padre,
padre_telefono: tel
padre_telefono: tel,
prefijo
})
});
+18 -8
View File
@@ -709,21 +709,31 @@ app.delete('/api/admin/personal/:id', (req, res) => {
}
});
// Crear nuevo estudiante + carné QR
// Crear nuevo estudiante / usuario + carné QR (escalable a 5 dígitos y prefijos multi-negocio)
app.post('/api/admin/estudiantes', (req, res) => {
try {
const { nombre_completo, edad, grado, seccion, saldo_inicial, limite_diario_colones, alergias, pin_seguridad, padre_nombre, padre_telefono } = req.body;
const {
nombre_completo, edad, grado, seccion, saldo_inicial,
limite_diario_colones, alergias, pin_seguridad, padre_nombre,
padre_telefono, prefijo, tipo_entidad
} = req.body;
if (!nombre_completo || !grado || !seccion) {
return res.status(400).json({ error: 'Nombre completo, grado y sección son obligatorios' });
}
const count = db.prepare('SELECT COUNT(*) as count FROM estudiantes').get().count + 1;
const codigoEstudiante = `EST-2026-${String(count).padStart(3, '0')}`;
// 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;
// Prefijo configurable para expansión a otros negocios (EST, EMP, EVT, SOC, PASS)
const cleanPrefix = (prefijo || tipo_entidad || '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')}`;
const primerNombre = nombre_completo.trim().split(' ')[0].toUpperCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
const randomHex = Math.random().toString(16).substring(2, 6).toUpperCase();
const qrToken = `QR-${primerNombre}-2026-${randomHex}`;
const qrToken = `QR-${cleanPrefix}-${primerNombre}-${year}-${String(nextSeq).padStart(5, '0')}-${randomHex}`;
const pin = pin_seguridad ? String(pin_seguridad).trim() : '1234';
const saldo = parseInt(saldo_inicial, 10) || 0;
@@ -754,11 +764,11 @@ app.post('/api/admin/estudiantes', (req, res) => {
const nuevoId = resEst.lastInsertRowid;
// Crear cuenta de usuario estudiante
const usernameEst = primerNombre.toLowerCase() + count;
const usernameEst = primerNombre.toLowerCase() + nextSeq;
try {
const userRes = db.prepare(`
INSERT INTO usuarios (username, password_hash, rol, nombre, email, telefono)
VALUES (?, ?, 'estudiante', ?, '', '')
INSERT INTO usuarios (username, password_hash, rol, nombre, email, telefono, activo)
VALUES (?, ?, 'estudiante', ?, '', '', 1)
`).run(usernameEst, pin, nombre_completo.trim());
db.prepare('UPDATE estudiantes SET usuario_id = ? WHERE id = ?').run(userRes.lastInsertRowid, nuevoId);
} catch (e) {}