feat(qr): add 3-second dynamic QR auto-rotation and global settings configuration (v3.8.46)

This commit is contained in:
2026-10-28 08:11:45 -03:00
parent 54c221e20e
commit 2d1fefa856
16 changed files with 600 additions and 64 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "frontend",
"version": "3.8.45",
"version": "3.8.46",
"description": "",
"main": "index.js",
"scripts": {
+3 -3
View File
@@ -86,9 +86,9 @@ const env = nunjucks.configure(path.join(__dirname, '../views'), {
});
// Versiones institucionales del sistema
const APP_VERSION = '3.8.45';
const FRONTEND_VERSION = '3.8.45';
const BACKEND_VERSION = '3.8.45';
const APP_VERSION = '3.8.46';
const FRONTEND_VERSION = '3.8.46';
const BACKEND_VERSION = '3.8.46';
env.addGlobal('app_version', APP_VERSION);
env.addGlobal('frontend_version', FRONTEND_VERSION);
+5
View File
@@ -1794,6 +1794,10 @@ const handleGlobalSettings = async (req, res) => {
}
if (settings) {
settings.ui = settings.ui || { show_role_banner: true };
settings.security_qr = settings.security_qr || {
renewal_interval_seconds: 3,
grace_period_seconds: 60
};
}
try {
@@ -1893,6 +1897,7 @@ router.post('/settings/moodle/test', forwardSettingsAction);
router.post('/settings/moodle/sync', forwardSettingsAction);
router.get('/settings/moodle/stats', forwardSettingsAction);
router.post('/settings/ui', forwardSettingsAction);
router.post('/settings/security-qr', forwardSettingsAction);
router.post('/settings/ai', forwardSettingsAction);
router.post('/settings/ai/test', forwardSettingsAction);
router.post('/settings/reset_system', forwardSettingsAction);
+6 -2
View File
@@ -7,12 +7,14 @@ router.use(requireAuth);
router.get(['/my-card', '/', '/mi-credencial'], async (req, res) => {
let qrToken = '';
let expiresInHours = 72;
let renewalIntervalSeconds = 3;
try {
const resp = await req.apiClient.get('/reception/my-qr-token');
if (resp.data) {
qrToken = resp.data.qr_token || '';
expiresInHours = resp.data.expires_in_hours || 72;
renewalIntervalSeconds = resp.data.renewal_interval_seconds || 3;
}
} catch (err) {
console.warn('QR token generation notice:', err.message);
@@ -22,7 +24,8 @@ router.get(['/my-card', '/', '/mi-credencial'], async (req, res) => {
title: 'Mi Credencial Digital — UniCABA',
user: req.user,
qrToken,
expiresInHours
expiresInHours,
renewalIntervalSeconds
});
});
@@ -41,7 +44,8 @@ router.get('/token', async (req, res) => {
user_name: req.user?.name || '',
user_dni: req.user?.document_number || '',
user_role: (req.user?.role || 'ALUMNO').toUpperCase(),
expires_in_hours: 72
expires_in_hours: 72,
renewal_interval_seconds: 3
});
}
});
@@ -93,6 +93,11 @@
<i class="bi bi-cpu me-2 text-success"></i>Asistente IA &amp; LLM Local
</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" id="tab-security-qr-btn" data-bs-toggle="tab" data-bs-target="#tab-security-qr" type="button" role="tab">
<i class="bi bi-qr-code me-2 text-warning"></i>Credencial QR &amp; Acceso
</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link text-danger" id="tab-maintenance-btn" data-bs-toggle="tab" data-bs-target="#tab-maintenance" type="button" role="tab">
<i class="bi bi-radioactive me-2 text-danger"></i>Mantenimiento &amp; Reinicio
@@ -718,7 +723,92 @@
</div>
<!-- ========================================== -->
<!-- PESTAÑA 6: MANTENIMIENTO & REINICIO -->
<!-- PESTAÑA 6: CREDENCIAL QR & ACCESO (SDD-012)-->
<!-- ========================================== -->
<div class="tab-pane fade" id="tab-security-qr" role="tabpanel">
<div class="row g-4">
<div class="col-lg-8">
<form id="securityQrForm" onsubmit="saveSecurityQrConfig(event)">
<div class="card border shadow-none bg-body-tertiary p-3 mb-4 rounded-3">
<h6 class="fw-bold mb-3 d-flex align-items-center">
<i class="bi bi-shield-lock-fill text-warning me-2"></i>Rotación Dinámica de Código QR Anti-Captura
</h6>
<div class="mb-4">
<label class="form-label small fw-semibold text-body" for="qr_renewal_interval_seconds">
Tiempo de Renovación del Código QR en Pantalla (Segundos)
</label>
<div class="input-group input-group-sm mb-2" style="max-width: 260px;">
<span class="input-group-text"><i class="bi bi-stopwatch"></i></span>
<input type="number" class="form-control font-monospace text-center fw-bold" id="qr_renewal_interval_seconds" name="renewal_interval_seconds"
min="1" max="300" step="1"
value="{{ settings.security_qr.renewal_interval_seconds if (settings and settings.security_qr and settings.security_qr.renewal_interval_seconds) else 3 }}" required>
<span class="input-group-text">segundos</span>
</div>
<div class="d-flex gap-2 flex-wrap mb-2">
<button type="button" class="btn btn-xs btn-outline-secondary py-1 px-2 small" onclick="setQrIntervalPreset(3)">
<i class="bi bi-lightning-charge text-warning me-1"></i>3 seg (Predeterminado)
</button>
<button type="button" class="btn btn-xs btn-outline-secondary py-1 px-2 small" onclick="setQrIntervalPreset(5)">
5 seg
</button>
<button type="button" class="btn btn-xs btn-outline-secondary py-1 px-2 small" onclick="setQrIntervalPreset(10)">
10 seg
</button>
<button type="button" class="btn btn-xs btn-outline-secondary py-1 px-2 small" onclick="setQrIntervalPreset(30)">
30 seg
</button>
</div>
<div class="text-muted small">
Frecuencia con la que la aplicación regenera la imagen del QR y su token criptográfico firmado en el modal del usuario, carnet y perfil.
Un valor de <strong>3 segundos</strong> garantiza máxima seguridad anti-screenshot / anti-captura para evitar que los estudiantes se presten accesos.
</div>
</div>
<hr class="opacity-25 my-3">
<div class="mb-3">
<label class="form-label small fw-semibold text-body" for="qr_token_grace_period_seconds">
Ventana de Gracia / Validez de Lectura del Token (Segundos)
</label>
<div class="input-group input-group-sm mb-2" style="max-width: 260px;">
<span class="input-group-text"><i class="bi bi-hourglass-split"></i></span>
<input type="number" class="form-control font-monospace text-center fw-bold" id="qr_token_grace_period_seconds" name="grace_period_seconds"
min="5" max="3600" step="5"
value="{{ settings.security_qr.grace_period_seconds if (settings and settings.security_qr and settings.security_qr.grace_period_seconds) else 60 }}" required>
<span class="input-group-text">segundos</span>
</div>
<div class="text-muted small">
Tiempo durante el cual el escáner de Recepción aceptará como válido un token QR recién generado (tolerancia a latencia de red, enfoque de cámara y lectura en torniquetes). Se recomienda entre 30 y 120 segundos.
</div>
</div>
</div>
<div class="d-flex justify-content-end">
<button type="submit" class="btn btn-primary btn-sm px-4" id="btnSaveSecurityQr">
<i class="bi bi-check2-circle me-1"></i>Guardar Configuración de Credencial QR
</button>
</div>
</form>
</div>
<!-- Panel de Consejos / UX & Seguridad -->
<div class="col-lg-4">
<div class="card border-0 bg-warning-subtle text-warning-emphasis p-3 rounded-3 mb-3">
<h6 class="fw-bold mb-2"><i class="bi bi-shield-check me-1"></i>Credencial Dinámica Anti-Fraude</h6>
<p class="small mb-2">
Al renovar el código cada 3 segundos, las capturas de pantalla tomadas por alumnos quedan invalidadas en los puntos de acceso físico.
</p>
<p class="small mb-0">
Cada rotación genera un JWT con identificador único (JTI) y marca de tiempo firmada, garantizando trazabilidad y seguridad institucional.
</p>
</div>
</div>
</div>
</div>
<!-- ========================================== -->
<!-- PESTAÑA 7: MANTENIMIENTO & REINICIO -->
<!-- ========================================== -->
<div class="tab-pane fade" id="tab-maintenance" role="tabpanel">
<div class="row g-4">
@@ -1500,6 +1590,57 @@ async function testAiConnection() {
}
}
// -------------------------------------------------------------
// Configuración de Credenciales QR Dinámicas y Rotación (SDD-012)
// -------------------------------------------------------------
function setQrIntervalPreset(sec) {
const input = document.getElementById('qr_renewal_interval_seconds');
if (input) input.value = sec;
}
async function saveSecurityQrConfig(e) {
e.preventDefault();
const btn = document.getElementById('btnSaveSecurityQr');
const renewalInput = document.getElementById('qr_renewal_interval_seconds');
const graceInput = document.getElementById('qr_token_grace_period_seconds');
btn.disabled = true;
btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Guardando...';
const payload = {
renewal_interval_seconds: parseInt(renewalInput.value, 10) || 3,
grace_period_seconds: parseInt(graceInput.value, 10) || 60
};
try {
let res = await fetch('/admin/settings/security-qr', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (!res.ok && res.status === 404) {
res = await fetch('/api/v1/admin/settings/security-qr', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
}
const data = await res.json();
if (res.ok) {
showAlert(data.message || 'Configuración de credenciales QR guardada exitosamente.', 'success');
} else {
showAlert(data.message || 'Error al guardar configuración de QR.', 'danger');
}
} catch (err) {
showAlert('Error de comunicación: ' + err.message, 'danger');
} finally {
btn.disabled = false;
btn.innerHTML = '<i class="bi bi-check2-circle me-1"></i>Guardar Configuración de Credencial QR';
}
}
// -------------------------------------------------------------
// Reinicialización Total del Sistema (Requiere Contraseña Admin)
// -------------------------------------------------------------
+95 -15
View File
@@ -73,8 +73,23 @@
</div>
</div>
</div>
<div class="mt-2 text-muted small" style="font-size: 0.72rem;" id="profileQrValidity">
<i class="bi bi-clock-history me-1"></i>QR Dinámico renovable ({{ expiresInHours or 72 }}hs)
<!-- Barra de Progreso y Cuenta Regresiva de Renovación Dinámica -->
<div class="mt-2 mb-2 px-2" style="max-width: 220px; margin: 0 auto;">
<div class="progress" style="height: 4px; background-color: rgba(180, 62, 142, 0.15); border-radius: 4px;">
<div id="profileQrProgressBar" class="progress-bar" role="progressbar" style="width: 100%; background: linear-gradient(90deg, #4338CA, #B43E8E); transition: width 0.1s linear;"></div>
</div>
<div class="d-flex justify-content-between align-items-center mt-1 text-muted small" style="font-size: 0.70rem;">
<span class="d-flex align-items-center gap-1">
<span class="spinner-grow spinner-grow-sm text-success" style="width: 5px; height: 5px;" role="status"></span>
<span class="text-success fw-semibold">Anti-captura</span>
</span>
<span>Renueva en <strong id="profileQrCountdown" class="font-monospace text-primary">3s</strong></span>
</div>
</div>
<div class="mt-1 text-muted small" style="font-size: 0.72rem;" id="profileQrValidity">
<i class="bi bi-arrow-repeat me-1"></i>Código dinámico con rotación cada 3 seg
</div>
</div>
<div class="col-md-7 col-lg-8">
@@ -307,6 +322,11 @@
<script>
(function() {
var profileQrInstance = null;
var timerId = null;
var renewalInterval = 3; // Segundos (default 3s configurable)
var elapsedMs = 0;
var tickIntervalMs = 100;
var isFetching = false;
var initialToken = "{{ qrToken }}";
var fallbackToken = "UNICABA:USR:{{ user.id }}:DNI:{{ user.document_number or user.email }}";
@@ -329,11 +349,27 @@
}
}
window.refreshProfileQrCode = function() {
var icon = document.getElementById('profileRefreshQrIcon');
function updateProgressUi() {
var progressBar = document.getElementById('profileQrProgressBar');
var countdownEl = document.getElementById('profileQrCountdown');
var totalMs = renewalInterval * 1000;
var remainingMs = Math.max(0, totalMs - elapsedMs);
var pct = Math.max(0, Math.min(100, (remainingMs / totalMs) * 100));
if (progressBar) {
progressBar.style.width = pct + '%';
}
if (countdownEl) {
countdownEl.textContent = (remainingMs / 1000).toFixed(1) + 's';
}
}
function fetchNewToken(showSpinner) {
if (isFetching) return;
isFetching = true;
var container = document.getElementById('profileQrCodeDisplay');
if (icon) icon.classList.add('spin-animation');
if (container) {
if (showSpinner && container && !profileQrInstance) {
container.innerHTML = '<div class="spinner-border text-primary spinner-border-sm" role="status"></div>';
}
@@ -341,31 +377,75 @@
.then(function(res) { return res.json(); })
.then(function(data) {
if (data && data.qr_token) {
if (data.renewal_interval_seconds && data.renewal_interval_seconds > 0) {
renewalInterval = data.renewal_interval_seconds;
}
drawQR(data.qr_token);
if (data.expires_in_hours) {
var valEl = document.getElementById('profileQrValidity');
if (valEl) {
valEl.innerHTML = '<i class="bi bi-clock-history me-1"></i>QR Dinámico renovable (' + data.expires_in_hours + 'hs)';
}
var valEl = document.getElementById('profileQrValidity');
if (valEl) {
valEl.innerHTML = '<i class="bi bi-arrow-repeat me-1"></i>Código dinámico con rotación cada ' + renewalInterval + ' seg';
}
} else {
drawQR(fallbackToken);
}
})
.catch(function(err) {
console.warn('Error refrescando token:', err);
console.warn('Error refrescando token en perfil:', err);
drawQR(fallbackToken);
})
.finally(function() {
if (icon) {
setTimeout(function() { icon.classList.remove('spin-animation'); }, 700);
}
isFetching = false;
elapsedMs = 0;
updateProgressUi();
});
}
function startLoop() {
stopLoop();
elapsedMs = 0;
updateProgressUi();
fetchNewToken(false);
timerId = setInterval(function() {
elapsedMs += tickIntervalMs;
updateProgressUi();
if (elapsedMs >= renewalInterval * 1000) {
elapsedMs = 0;
fetchNewToken(false);
}
}, tickIntervalMs);
}
function stopLoop() {
if (timerId) {
clearInterval(timerId);
timerId = null;
}
}
window.refreshProfileQrCode = function() {
var icon = document.getElementById('profileRefreshQrIcon');
if (icon) icon.classList.add('spin-animation');
elapsedMs = 0;
fetchNewToken(false);
setTimeout(function() {
if (icon) icon.classList.remove('spin-animation');
}, 600);
};
document.addEventListener('DOMContentLoaded', function() {
var tokenToUse = (initialToken && initialToken.length > 10) ? initialToken : fallbackToken;
drawQR(tokenToUse);
startLoop();
document.addEventListener('visibilitychange', function() {
if (document.hidden) {
stopLoop();
} else {
startLoop();
}
});
});
})();
</script>
+116 -11
View File
@@ -53,10 +53,24 @@
</div>
<!-- Código QR Institucional -->
<div class="p-3 bg-white rounded-4 shadow-sm d-inline-block mb-3" style="min-width: 200px; min-height: 200px;">
<div class="p-3 bg-white rounded-4 shadow-sm d-inline-block mb-2" style="min-width: 200px; min-height: 200px;">
<div id="qrcode" class="d-flex justify-content-center align-items-center"></div>
</div>
<!-- Barra de Progreso y Cuenta Regresiva de Renovación Dinámica -->
<div class="mb-3 px-3" style="max-width: 240px; margin: 0 auto;">
<div class="progress" style="height: 4px; background-color: rgba(255, 255, 255, 0.2); border-radius: 4px;">
<div id="cardQrProgressBar" class="progress-bar bg-white" role="progressbar" style="width: 100%; transition: width 0.1s linear;"></div>
</div>
<div class="d-flex justify-content-between align-items-center mt-1 text-white-50 small" style="font-size: 0.70rem;">
<span class="d-flex align-items-center gap-1">
<span class="spinner-grow spinner-grow-sm text-success" style="width: 5px; height: 5px;" role="status"></span>
<span class="text-white fw-semibold">Anti-captura activo</span>
</span>
<span class="text-white">Renueva en <strong id="cardQrCountdown" class="font-monospace text-white">3s</strong></span>
</div>
</div>
<div class="d-flex justify-content-center align-items-center gap-3 text-start small opacity-90 mb-2">
<div>
<span class="d-block text-uppercase" style="font-size: 0.65rem;">Documento</span>
@@ -72,8 +86,8 @@
<!-- Footer de la Credencial -->
<div class="p-3 bg-black bg-opacity-25 border-top border-white border-opacity-10 d-flex align-items-center justify-content-between text-white-50 small">
<span><i class="bi bi-clock-history me-1"></i> QR renovable</span>
<span>Validez: {{ expiresInHours }}hs</span>
<span id="cardRenewalText"><i class="bi bi-arrow-repeat me-1"></i> QR dinámico ({{ renewalIntervalSeconds or 3 }}s)</span>
<span>Validez institucional</span>
</div>
</div>
@@ -104,16 +118,23 @@
<!-- Librería QRCode.js via CDN -->
<script src="https://cdn.jsdelivr.net/npm/qrcodejs@1.0.0/qrcode.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
const qrContainer = document.getElementById('qrcode');
const token = "{{ qrToken }}";
const fallbackText = "UNICABA:USR:{{ user.id }}:DNI:{{ user.document_number or user.email }}";
const textToEncode = token && token.length > 10 ? token : fallbackText;
(function() {
var qrInstance = null;
var timerId = null;
var renewalInterval = parseInt("{{ renewalIntervalSeconds or 3 }}", 10) || 3;
var elapsedMs = 0;
var tickIntervalMs = 100;
var isFetching = false;
var initialToken = "{{ qrToken }}";
var fallbackText = "UNICABA:USR:{{ user.id }}:DNI:{{ user.document_number or user.email }}";
function drawQR(text) {
var qrContainer = document.getElementById('qrcode');
if (!qrContainer) return;
qrContainer.innerHTML = '';
try {
new QRCode(qrContainer, {
text: textToEncode,
qrInstance = new QRCode(qrContainer, {
text: text,
width: 180,
height: 180,
colorDark: "#0F172A",
@@ -124,6 +145,90 @@
console.error('Error generando QR:', e);
qrContainer.innerHTML = '<div class="alert alert-warning p-2 small">Código disponible en modo texto</div>';
}
}
function updateProgressUi() {
var progressBar = document.getElementById('cardQrProgressBar');
var countdownEl = document.getElementById('cardQrCountdown');
var totalMs = renewalInterval * 1000;
var remainingMs = Math.max(0, totalMs - elapsedMs);
var pct = Math.max(0, Math.min(100, (remainingMs / totalMs) * 100));
if (progressBar) {
progressBar.style.width = pct + '%';
}
if (countdownEl) {
countdownEl.textContent = (remainingMs / 1000).toFixed(1) + 's';
}
}
function fetchNewToken() {
if (isFetching) return;
isFetching = true;
fetch('/credential/token')
.then(function(res) { return res.json(); })
.then(function(data) {
if (data && data.qr_token) {
if (data.renewal_interval_seconds && data.renewal_interval_seconds > 0) {
renewalInterval = data.renewal_interval_seconds;
}
drawQR(data.qr_token);
var textEl = document.getElementById('cardRenewalText');
if (textEl) {
textEl.innerHTML = '<i class="bi bi-arrow-repeat me-1"></i> QR dinámico (' + renewalInterval + 's)';
}
} else {
drawQR(fallbackText);
}
})
.catch(function(err) {
console.warn('Error renovando QR de carnet:', err);
drawQR(fallbackText);
})
.finally(function() {
isFetching = false;
elapsedMs = 0;
updateProgressUi();
});
}
function startLoop() {
stopLoop();
elapsedMs = 0;
updateProgressUi();
timerId = setInterval(function() {
elapsedMs += tickIntervalMs;
updateProgressUi();
if (elapsedMs >= renewalInterval * 1000) {
elapsedMs = 0;
fetchNewToken();
}
}, tickIntervalMs);
}
function stopLoop() {
if (timerId) {
clearInterval(timerId);
timerId = null;
}
}
document.addEventListener('DOMContentLoaded', function() {
var textToEncode = (initialToken && initialToken.length > 10) ? initialToken : fallbackText;
drawQR(textToEncode);
startLoop();
document.addEventListener('visibilitychange', function() {
if (document.hidden) {
stopLoop();
} else {
startLoop();
}
});
});
})();
</script>
{% endblock %}
+81 -19
View File
@@ -53,6 +53,20 @@
</div>
</div>
<!-- Barra de Progreso y Cuenta Regresiva de Renovación Dinámica -->
<div class="mt-2 mb-2 px-3" style="max-width: 260px; margin: 0 auto;">
<div class="progress" style="height: 4px; background-color: rgba(180, 62, 142, 0.15); border-radius: 4px;">
<div id="modalQrProgressBar" class="progress-bar" role="progressbar" style="width: 100%; background: linear-gradient(90deg, #4338CA, #B43E8E); transition: width 0.1s linear;"></div>
</div>
<div class="d-flex justify-content-between align-items-center mt-1 text-muted small" style="font-size: 0.72rem;">
<span class="d-flex align-items-center gap-1">
<span class="spinner-grow spinner-grow-sm text-success" style="width: 6px; height: 6px;" role="status"></span>
<span class="text-success fw-semibold">Anti-captura activo</span>
</span>
<span>Renueva en <strong id="modalQrCountdown" class="font-monospace text-primary">3s</strong></span>
</div>
</div>
<!-- Información de Validez y Seguridad -->
<div class="mt-2 mb-3">
<div class="d-inline-flex align-items-center gap-1 text-success small fw-semibold">
@@ -60,7 +74,7 @@
<span>Firma Criptográfica Verificada</span>
</div>
<div class="text-muted small mt-1" style="font-size: 0.73rem;" id="modalQrValidityText">
<i class="bi bi-clock-history me-1"></i>QR Dinámico renovable cada 72hs
<i class="bi bi-arrow-repeat me-1"></i>Código dinámico con rotación cada 3 seg
</div>
</div>
@@ -68,7 +82,7 @@
<div class="d-grid gap-2">
<div class="btn-group">
<button type="button" class="btn btn-outline-secondary btn-sm py-2" onclick="refreshGlobalQrModal()" id="btnRefreshGlobalQr">
<i class="bi bi-arrow-clockwise me-1" id="globalRefreshQrIcon"></i>Actualizar Código QR
<i class="bi bi-arrow-clockwise me-1" id="globalRefreshQrIcon"></i>Rotar Ahora
</button>
<a href="/credential/my-card" class="btn btn-primary btn-sm py-2">
<i class="bi bi-person-badge me-1"></i>Ver Carnet Completo
@@ -93,7 +107,11 @@
<script>
(function() {
let qrModalInstance = null;
let cachedQrToken = null;
let timerId = null;
let renewalInterval = 3; // Segundos (default 3s configurable)
let elapsedMs = 0;
const tickIntervalMs = 100;
let isFetching = false;
function ensureQrLibrary(callback) {
if (typeof QRCode !== 'undefined') {
@@ -132,16 +150,27 @@
}
}
function loadAndRenderQR(forceRefresh) {
var spinner = document.getElementById('globalQrSpinner');
var container = document.getElementById('globalQrModalContainer');
function updateProgressUi() {
var progressBar = document.getElementById('modalQrProgressBar');
var countdownEl = document.getElementById('modalQrCountdown');
var totalMs = renewalInterval * 1000;
var remainingMs = Math.max(0, totalMs - elapsedMs);
var pct = Math.max(0, Math.min(100, (remainingMs / totalMs) * 100));
if (!forceRefresh && cachedQrToken) {
renderModalQR(cachedQrToken);
return;
if (progressBar) {
progressBar.style.width = pct + '%';
}
if (countdownEl) {
countdownEl.textContent = (remainingMs / 1000).toFixed(1) + 's';
}
}
if (container && (!qrModalInstance || forceRefresh)) {
function fetchAndRenderToken(showSpinner) {
if (isFetching) return;
isFetching = true;
var container = document.getElementById('globalQrModalContainer');
if (showSpinner && container && !qrModalInstance) {
container.innerHTML = '<div class="spinner-border text-primary spinner-border-sm" role="status"></div>';
}
@@ -149,15 +178,15 @@
.then(function(res) { return res.json(); })
.then(function(data) {
if (data && data.qr_token) {
cachedQrToken = data.qr_token;
if (data.renewal_interval_seconds && data.renewal_interval_seconds > 0) {
renewalInterval = data.renewal_interval_seconds;
}
ensureQrLibrary(function() {
renderModalQR(data.qr_token);
});
if (data.expires_in_hours) {
var valText = document.getElementById('modalQrValidityText');
if (valText) {
valText.innerHTML = '<i class="bi bi-clock-history me-1"></i>QR Dinámico renovable cada ' + data.expires_in_hours + 'hs';
}
var valText = document.getElementById('modalQrValidityText');
if (valText) {
valText.innerHTML = '<i class="bi bi-arrow-repeat me-1"></i>Código dinámico con rotación cada ' + renewalInterval + ' seg';
}
} else {
throw new Error('Token no disponible');
@@ -169,23 +198,56 @@
ensureQrLibrary(function() {
renderModalQR(fallback);
});
})
.finally(function() {
isFetching = false;
elapsedMs = 0;
updateProgressUi();
});
}
function startAutoRefreshLoop() {
stopAutoRefreshLoop();
elapsedMs = 0;
updateProgressUi();
fetchAndRenderToken(false);
timerId = setInterval(function() {
elapsedMs += tickIntervalMs;
updateProgressUi();
if (elapsedMs >= renewalInterval * 1000) {
elapsedMs = 0;
fetchAndRenderToken(false);
}
}, tickIntervalMs);
}
function stopAutoRefreshLoop() {
if (timerId) {
clearInterval(timerId);
timerId = null;
}
}
window.refreshGlobalQrModal = function() {
var icon = document.getElementById('globalRefreshQrIcon');
if (icon) icon.classList.add('spin-animation');
loadAndRenderQR(true);
elapsedMs = 0;
fetchAndRenderToken(false);
setTimeout(function() {
if (icon) icon.classList.remove('spin-animation');
}, 800);
}, 600);
};
document.addEventListener('DOMContentLoaded', function() {
var modalEl = document.getElementById('userQrCredentialModal');
if (modalEl) {
modalEl.addEventListener('show.bs.modal', function() {
loadAndRenderQR(false);
startAutoRefreshLoop();
});
modalEl.addEventListener('hide.bs.modal', function() {
stopAutoRefreshLoop();
});
}
});