Actualizar server.js

This commit is contained in:
2026-03-28 20:36:43 +00:00
parent b95c1a7797
commit 3fe6fc5bc9

View File

@@ -412,21 +412,27 @@ async function autoUpdateDB() {
} catch (e) { console.error("❌ Error DB:", e); } finally { client.release(); }
}
// HELPERS
// ==========================================
// 📞 HELPERS (UNIFICACIÓN TOTAL DE TELÉFONOS)
// ==========================================
// HELPERS
// 1. Extrae SIEMPRE exactamente 9 dígitos (Formato Nacional: 600123456)
function extractValidPhone(rawPhone) {
if (!rawPhone) return "";
let str = String(rawPhone).toUpperCase();
str = str.replace(/(^\+34|^0034)/, ""); // Quita prefijo inicial si lo hay
str = str.replace(/[\s\-\.]/g, ""); // Quita espacios, guiones y puntos
const match = str.match(/[6789]\d{8}/); // Busca el primer número de 9 cifras que empiece por 6,7,8,9
if (match) return match[0];
const digits = str.replace(/\D/g, ""); // Si falla, coge los primeros 9 números que pille
return digits.length >= 9 ? digits.substring(0, 9) : digits;
let str = String(rawPhone).replace(/\D/g, ""); // Borra todo lo que no sea número (espacios, letras, +, -)
if (str.startsWith("0034")) str = str.slice(4);
if (str.startsWith("34") && str.length >= 11) str = str.slice(2);
const match = str.match(/[6789]\d{8}/);
return match ? match[0] : (str.length >= 9 ? str.slice(-9) : str);
}
// 2. Normaliza SIEMPRE a Formato Internacional para la Base de Datos (+34600123456)
function normalizePhone(phone) {
const clean = extractValidPhone(phone);
return clean ? "+34" + clean : "";
}
function normalizePhone(phone) { let p = String(phone || "").trim().replace(/\s+/g, "").replace(/-/g, ""); if (!p) return ""; if (!p.startsWith("+") && /^[6789]\d{8}/.test(p)) return "+34" + p; return p; }
function signToken(user) { const accountId = user.owner_id || user.id; return jwt.sign({ sub: user.id, email: user.email, phone: user.phone, role: user.role || 'operario', accountId }, JWT_SECRET, { expiresIn: "30d" }); }
function authMiddleware(req, res, next) { const h = req.headers.authorization || ""; const token = h.startsWith("Bearer ") ? h.slice(7) : ""; if (!token) return res.status(401).json({ ok: false, error: "No token" }); try { req.user = jwt.verify(token, JWT_SECRET); next(); } catch { return res.status(401).json({ ok: false, error: "Token inválido" }); } }
function genCode6() { return String(Math.floor(100000 + Math.random() * 900000)); }