diff --git a/server.js b/server.js index b1ae848..2ba16ad 100644 --- a/server.js +++ b/server.js @@ -3956,7 +3956,7 @@ app.post("/webhook/evolution", async (req, res) => { s.raw_data->>'requested_time' as cita_pendiente_hora, s.raw_data->>'Compañía' as compania, COALESCE(s.raw_data->>'Descripción', s.raw_data->>'DESCRIPCION') as averia, - s.raw_data->>'ia_paused' as ia_paused -- 🚨 NUEVO: Miramos si tiene el semáforo rojo + s.raw_data->>'ia_paused' as ia_paused -- 🚨 BÚSQUEDA DEL SEMÁFORO ROJO FROM scraped_services s LEFT JOIN users u ON s.assigned_to = u.id LEFT JOIN service_statuses st ON (s.raw_data->>'status_operativo')::text = st.id::text @@ -3973,25 +3973,31 @@ app.post("/webhook/evolution", async (req, res) => { if (data.data.key.fromMe) { const msgCmd = mensajeTexto.trim(); - // 🔴 COMANDO MÁGICO 1: PAUSAR LA IA (Mandar solo el emoji 🔴) - if (msgCmd === '🔴') { - await pool.query(`UPDATE scraped_services SET raw_data = jsonb_set(COALESCE(raw_data, '{}'::jsonb), '{ia_paused}', 'true') WHERE id = $1`, [service.id]); - await pool.query(`INSERT INTO service_communications (scraped_id, owner_id, sender_name, sender_role, message, is_internal) VALUES ($1, $2, $3, $4, $5, true)`, [service.id, ownerId, "Sistema", "admin", "🔴 IA Pausada manualmente con Emoji."]); - console.log(`🔴 [IA PAUSADA] Semáforo rojo activado para exp ${service.service_ref}`); + // 🔴 COMANDO MÁGICO 1: PAUSAR LA IA (Resistente a emojis de iPhone) + if (msgCmd.includes('🔴')) { + try { + await pool.query(`UPDATE scraped_services SET raw_data = COALESCE(raw_data, '{}'::jsonb) || '{"ia_paused": true}'::jsonb WHERE id = $1`, [service.id]); + await pool.query(`INSERT INTO service_communications (scraped_id, owner_id, sender_name, sender_role, message, is_internal) VALUES ($1, $2, $3, $4, $5, true)`, [service.id, ownerId, "Sistema", "admin", "🔴 IA Pausada manualmente con Emoji."]); + console.log(`🔴 [IA PAUSADA] Semáforo rojo activado para exp ${service.service_ref}`); + } catch(err) { console.error("Error pausando IA:", err); } return; } - // 🟢 COMANDO MÁGICO 2: ACTIVAR LA IA (Mandar solo el emoji 🟢) - if (msgCmd === '🟢') { - await pool.query(`UPDATE scraped_services SET raw_data = raw_data - 'ia_paused' WHERE id = $1`, [service.id]); - await pool.query(`INSERT INTO service_communications (scraped_id, owner_id, sender_name, sender_role, message, is_internal) VALUES ($1, $2, $3, $4, $5, true)`, [service.id, ownerId, "Sistema", "admin", "🟢 IA Reactivada manualmente con Emoji."]); - console.log(`🟢 [IA ACTIVADA] Semáforo verde activado para exp ${service.service_ref}`); + // 🟢 COMANDO MÁGICO 2: ACTIVAR LA IA + if (msgCmd.includes('🟢')) { + try { + await pool.query(`UPDATE scraped_services SET raw_data = raw_data - 'ia_paused' WHERE id = $1`, [service.id]); + await pool.query(`INSERT INTO service_communications (scraped_id, owner_id, sender_name, sender_role, message, is_internal) VALUES ($1, $2, $3, $4, $5, true)`, [service.id, ownerId, "Sistema", "admin", "🟢 IA Reactivada manualmente con Emoji."]); + console.log(`🟢 [IA ACTIVADA] Semáforo verde activado para exp ${service.service_ref}`); + } catch(err) { console.error("Error activando IA:", err); } return; } // Guardado normal si es un texto tuyo hablando con el cliente - await pool.query(`INSERT INTO service_communications (scraped_id, owner_id, sender_name, sender_role, message) VALUES ($1, $2, $3, $4, $5)`, - [service.id, ownerId, "Técnico (WhatsApp)", "operario", mensajeTexto]); + try { + await pool.query(`INSERT INTO service_communications (scraped_id, owner_id, sender_name, sender_role, message) VALUES ($1, $2, $3, $4, $5)`, + [service.id, ownerId, "Técnico (WhatsApp)", "operario", mensajeTexto]); + } catch(err) { console.error("Error guardando mensaje de admin:", err); } return; } @@ -4000,12 +4006,12 @@ app.post("/webhook/evolution", async (req, res) => { try { // 🛑 COMPROBAR SI LA HEMOS PAUSADO CON EL SEMÁFORO ROJO - if (service.ia_paused === 'true') { + if (service.ia_paused === 'true' || service.ia_paused === true) { console.log(`🤫 [IA MUTEADA] El cliente ha hablado, pero la IA está en semáforo rojo para ${service.service_ref}`); return; } - // 🛡️ VERIFICAR INTERVENCIÓN HUMANA (Y ACTIVAMOS LAS 2 HORAS DE ESPERA) + // 🛡️ VERIFICAR INTERVENCIÓN HUMANA Y APLICAR 2 HORAS DE SILENCIO (120 min) const checkHumanQ = await pool.query(` SELECT sender_role, created_at FROM service_communications WHERE scraped_id = $1 ORDER BY created_at DESC LIMIT 1 @@ -4015,7 +4021,7 @@ app.post("/webhook/evolution", async (req, res) => { const lastMsg = checkHumanQ.rows[0]; const diffMinutos = (new Date() - new Date(lastMsg.created_at)) / (1000 * 60); - // 🛑 ESCUDO ACTIVADO: Si un humano ha hablado hace menos de 120 minutos, la IA se calla + // 🛑 ESCUDO ACTIVADO if (['admin', 'superadmin', 'operario'].includes(lastMsg.sender_role) && diffMinutos < 120) { console.log(`🛡️ [ESCUDO IA] Silenciando a la IA porque un humano habló hace ${Math.round(diffMinutos)} minutos.`); return;