Files
Autoparts-DB/pos/static/js/login.js
consultoria-as a386ca5b4a
Some checks failed
CI / lint-and-test (3.11) (push) Has been cancelled
CI / lint-and-test (3.13) (push) Has been cancelled
Mejoras de sesion: estabilizacion, IA, Nexus Yonke y marketplace B2B
- F0 blindaje: Redis/Celery, pg_hba sin trust LAN, secretos a env 600, backups, webhook auth, jobs muertos
- F1 caja: bugs POS, reembolsos al corte, apartados, CFDI, topes de descuento en cotizacion/apartado
- F2/F7 IA de catalogo: autocategorizacion, dedup de SKUs con embeddings, OCR de facturas, descripciones, claves SAT, limpieza de fitment
- F3 IA en el flujo: vision Yonke, preguntas MeLi, venta cruzada, anomalias, sinonimos, busqueda semantica (rerank/embeddings)
- F4/F8 escala y cartera: /metrics+Prometheus+Grafana, pool, score de credito, churn, metricas multi-tenant
- Nexus Yonke (M1-M6): modelo de datos 1-de-1, alta por donador, vitrina publica, MeLi usado, consignacion, garantia por dias, reportes, etiquetas
- Marketplace B2B entre yonkes (catalogo + pedidos cross-tenant)
- Seguridad: auth en /api/admin/* (35 endpoints), alertas por tenant
- Migraciones v4.27/v4.28; timers expire-demos y rollup-metrics
2026-10-12 00:57:31 +00:00

120 lines
4.1 KiB
JavaScript

// /home/Autopartes/pos/static/js/login.js
(function() {
'use strict';
var pin = '';
var dots = document.querySelectorAll('#pinDots .pin-dot');
var errorEl = document.getElementById('loginError');
// Get tenant_id from URL param or localStorage
var tenantId = new URLSearchParams(window.location.search).get('tenant')
|| localStorage.getItem('pos_tenant_id');
// Device ID (persistent)
var deviceId = localStorage.getItem('pos_device_id');
if (!deviceId) {
deviceId = 'dev-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
localStorage.setItem('pos_device_id', deviceId);
}
/**
* Check if a JWT token is expired by decoding its payload.
* Returns true if the token is valid (not expired), false otherwise.
*/
function isTokenValid(token) {
try {
var parts = token.split('.');
if (parts.length !== 3) return false;
// Base64url decode the payload (index 1)
var payload = parts[1].replace(/-/g, '+').replace(/_/g, '/');
var decoded = JSON.parse(atob(payload));
// exp is in seconds, Date.now() is in milliseconds
if (!decoded.exp) return false;
// Add 30-second buffer to avoid edge cases
return (decoded.exp * 1000) > (Date.now() + 30000);
} catch (e) {
return false;
}
}
function updateDots() {
dots.forEach(function(dot, i) {
dot.classList.toggle('filled', i < pin.length);
});
}
window.addDigit = function(d) {
if (pin.length >= 4) return;
pin += d;
updateDots();
errorEl.textContent = '';
if (pin.length === 4) {
submitPin();
}
};
window.clearPin = function() {
pin = '';
updateDots();
errorEl.textContent = '';
};
window.submitPin = function() {
if (pin.length !== 4) return;
errorEl.textContent = '';
fetch('/pos/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
tenant_id: parseInt(tenantId),
pin: pin,
device_id: deviceId
})
})
.then(function(res) { return res.json().then(function(d) { return { ok: res.ok, data: d }; }); })
.then(function(result) {
if (!result.ok) {
errorEl.textContent = result.data.error || 'Error de autenticacion';
clearPin();
return;
}
localStorage.setItem('pos_token', result.data.token);
localStorage.setItem('pos_employee', JSON.stringify(result.data.employee));
localStorage.setItem('pos_tenant_id', tenantId);
document.cookie = 'pos_role=' + (result.data.employee.role || '') + '; path=/pos; SameSite=Lax';
var role = (result.data.employee.role || '').toLowerCase();
if (role === 'workshop' || role === 'mechanic' || role === 'counter') {
window.location.href = '/pos/workshop';
} else if (role === 'driver') {
window.location.href = '/pos/remission-notes';
} else {
window.location.href = '/pos/catalog';
}
})
.catch(function() {
errorEl.textContent = 'Error de conexion';
clearPin();
});
};
// Keyboard support
document.addEventListener('keydown', function(e) {
if (e.key >= '0' && e.key <= '9') addDigit(e.key);
else if (e.key === 'Backspace') clearPin();
else if (e.key === 'Enter') submitPin();
});
// Auto-redirect if already logged in AND token is not expired
var token = localStorage.getItem('pos_token');
if (token && tenantId) {
if (isTokenValid(token)) {
window.location.href = '/pos/catalog';
} else {
// Token expired — clean up and stay on login page
localStorage.removeItem('pos_token');
localStorage.removeItem('pos_employee');
}
}
})();