diff --git a/server.js b/server.js index d24e490..adac134 100644 --- a/server.js +++ b/server.js @@ -620,44 +620,35 @@ app.post("/whatsapp/settings", authMiddleware, async (req, res) => { async function triggerWhatsAppEvent(ownerId, serviceId, eventType) { try { - // 1. Miramos si la empresa tiene el botón encendido const userQ = await pool.query("SELECT wa_settings FROM users WHERE id=$1", [ownerId]); const settings = userQ.rows[0]?.wa_settings || {}; - - // TRUCO: Si es Modificación, usamos el valor del botón "Cambio de Cita" (wa_evt_date) const checkSwitch = eventType === 'wa_evt_update' ? 'wa_evt_date' : eventType; - if (!settings[checkSwitch]) return; // Si el botón está apagado, salimos + if (!settings[checkSwitch]) return false; // Botón apagado = No enviado - // 2. Buscamos qué plantilla corresponde a este evento - const tplTypeMap = { - 'wa_evt_welcome': 'welcome', - 'wa_evt_assigned': 'assigned', // <--- Añadida línea reparada - 'wa_evt_date': 'appointment', - 'wa_evt_update': 'update', - 'wa_evt_onway': 'on_way', - 'wa_evt_survey': 'survey' -}; + const tplTypeMap = { + 'wa_evt_welcome': 'welcome', + 'wa_evt_assigned': 'assigned', + 'wa_evt_date': 'appointment', + 'wa_evt_update': 'update', + 'wa_evt_onway': 'on_way', + 'wa_evt_survey': 'survey' + }; const tplQ = await pool.query("SELECT content FROM message_templates WHERE owner_id=$1 AND type=$2", [ownerId, tplTypeMap[eventType]]); - if (tplQ.rowCount === 0 || !tplQ.rows[0].content) return; + if (tplQ.rowCount === 0 || !tplQ.rows[0].content) return false; let text = tplQ.rows[0].content; - // 3. Extraemos los datos del expediente const svcQ = await pool.query("SELECT * FROM scraped_services WHERE id=$1", [serviceId]); - if (svcQ.rowCount === 0) return; + 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; + if (!phone) return false; // Sin teléfono = No enviado - // 4. Buscamos el token del portal cliente const phoneClean = phone.replace('+34', '').trim(); const clientQ = await pool.query("SELECT portal_token FROM clients WHERE phone LIKE $1 AND owner_id=$2 LIMIT 1", [`%${phoneClean}%`, ownerId]); const token = clientQ.rowCount > 0 ? clientQ.rows[0].portal_token : "ERROR"; - const linkMagico = `https://portal.integrarepara.es/?token=${token}&service=${serviceId}`; // <--- Fix Enlace Directo + const linkMagico = `https://portal.integrarepara.es/?token=${token}&service=${serviceId}`; - // ========================================== - // 🔄 5. TRADUCTOR DE FECHAS AL FORMATO ESPAÑOL + DÍA - // ========================================== let fechaLimpia = raw["scheduled_date"] || "la fecha acordada"; if (fechaLimpia.includes("-")) { const partes = fechaLimpia.split("-"); @@ -668,7 +659,6 @@ async function triggerWhatsAppEvent(ownerId, serviceId, eventType) { } } - // 6. Reemplazamos las variables text = text.replace(/{{NOMBRE}}/g, raw["Nombre Cliente"] || raw["CLIENTE"] || "Cliente"); text = text.replace(/{{DIRECCION}}/g, raw["Dirección"] || raw["DOMICILIO"] || "su domicilio"); text = text.replace(/{{FECHA}}/g, fechaLimpia); @@ -677,11 +667,11 @@ async function triggerWhatsAppEvent(ownerId, serviceId, eventType) { text = text.replace(/{{REFERENCIA}}/g, s.service_ref || ""); text = text.replace(/{{ENLACE}}/g, linkMagico); - // 7. Disparamos el mensaje const useDelay = settings.wa_delay_enabled !== false; - await sendWhatsAppAuto(phone, text, `cliente_${ownerId}`, useDelay); + // RETORNAMOS EL ÉXITO O FRACASO DEL ENVÍO + return await sendWhatsAppAuto(phone, text, `cliente_${ownerId}`, useDelay); - } catch (e) { console.error("Error Motor WA:", e.message); } + } catch (e) { console.error("Error Motor WA:", e.message); return false; } } app.get("/providers/credentials", authMiddleware, async (req, res) => {