Actualizar server.js

This commit is contained in:
2026-03-04 21:10:38 +00:00
parent 6569464979
commit dfb1474787

View File

@@ -889,7 +889,7 @@ async function sendWhatsAppAuto(phone, message, instanceName, useDelay = false)
}
// ==========================================
// 🔔 DISPARADOR DE EVENTOS DE WHATSAPP
// 🔔 DISPARADOR DE EVENTOS DE WHATSAPP (CON MODO SEGURO)
// ==========================================
async function triggerWhatsAppEvent(ownerId, serviceId, eventType) {
try {
@@ -914,23 +914,27 @@ async function triggerWhatsAppEvent(ownerId, serviceId, eventType) {
if (svcQ.rowCount === 0) return false;
const s = svcQ.rows[0];
const raw = s.raw_data || {};
const phone = raw["Teléfono"] || raw["TELEFONO"] || "";
if (!phone) return false; // Sin teléfono = No enviado
// 1. EXTRAER TELÉFONO DEL CLIENTE LIMPIO
let rawPhone = raw["Teléfono"] || raw["TELEFONO"] || raw["TELEFONOS"] || "";
let cleanPhoneToMatch = String(rawPhone).replace(/\D/g, "");
if (cleanPhoneToMatch.length > 9) cleanPhoneToMatch = cleanPhoneToMatch.slice(-9);
if (cleanPhoneToMatch.length < 9) return false; // Si no hay teléfono válido, cancelamos
// 4. Buscamos el token del portal cliente (o lo creamos si no existe)
const phoneClean = phone.replace('+34', '').trim();
const finalPhoneToSend = "34" + cleanPhoneToMatch;
// 2. Buscamos el token del portal cliente (o lo creamos si no existe)
let token = "ERROR";
const clientQ = await pool.query("SELECT portal_token FROM clients WHERE phone LIKE $1 AND owner_id=$2 LIMIT 1", [`%${phoneClean}%`, ownerId]);
const clientQ = await pool.query("SELECT portal_token FROM clients WHERE phone LIKE $1 AND owner_id=$2 LIMIT 1", [`%${cleanPhoneToMatch}%`, ownerId]);
if (clientQ.rowCount > 0) {
token = clientQ.rows[0].portal_token;
} else {
// El cliente no existe en la agenda aún. Lo creamos al vuelo.
const cName = raw["Nombre Cliente"] || raw["CLIENTE"] || "Asegurado";
const cAddr = raw["Dirección"] || raw["DOMICILIO"] || "";
const insertC = await pool.query(
"INSERT INTO clients (owner_id, full_name, phone, addresses) VALUES ($1, $2, $3, $4) RETURNING portal_token",
[ownerId, cName, phone, JSON.stringify([cAddr])]
[ownerId, cName, finalPhoneToSend, JSON.stringify([cAddr])]
);
token = insertC.rows[0].portal_token;
}
@@ -956,9 +960,22 @@ async function triggerWhatsAppEvent(ownerId, serviceId, eventType) {
text = text.replace(/{{ENLACE}}/g, linkMagico);
const useDelay = settings.wa_delay_enabled !== false;
const instanceName = `cliente_${ownerId}`;
// RETORNAMOS EL ÉXITO O FRACASO DEL ENVÍO
return await sendWhatsAppAuto(phone, text, `cliente_${ownerId}`, useDelay);
// ====================================================
// 🛑 MODO PRUEBAS (Desvía los mensajes a tu móvil)
// ====================================================
const MODO_PRUEBAS = true; // Cambia esto a 'false' para enviar a clientes reales
const MI_TELEFONO = "34667248132"; // <--- TU NÚMERO DE MÓVIL YA CONFIGURADO
if (MODO_PRUEBAS) {
console.log(`🛡️ [MODO PRUEBAS] Enviando WA al admin (${MI_TELEFONO}) en lugar de al cliente (${finalPhoneToSend})`);
const textoPrueba = `*(SIMULACIÓN PARA CLIENTE: ${finalPhoneToSend})*\n\n` + text;
return await sendWhatsAppAuto(MI_TELEFONO, textoPrueba, instanceName, useDelay);
} else {
console.log(`[WA] Enviando mensaje real al cliente: ${finalPhoneToSend}`);
return await sendWhatsAppAuto(finalPhoneToSend, text, instanceName, useDelay);
}
} catch (e) {
console.error("Error Motor WA:", e.message);