Actualizar server.js

This commit is contained in:
2026-03-26 08:19:05 +00:00
parent e6dbb9aaec
commit 329bc52865

View File

@@ -3955,7 +3955,8 @@ app.post("/webhook/evolution", async (req, res) => {
s.raw_data->>'requested_date' as cita_pendiente_fecha,
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
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
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
@@ -3970,6 +3971,25 @@ app.post("/webhook/evolution", async (req, res) => {
const service = svcQ.rows[0];
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}`);
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}`);
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]);
return;
@@ -3979,7 +3999,13 @@ app.post("/webhook/evolution", async (req, res) => {
candadosIA.add(service.id);
try {
// 🛡️ VERIFICAR INTERVENCIÓN HUMANA
// 🛑 COMPROBAR SI LA HEMOS PAUSADO CON EL SEMÁFORO ROJO
if (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)
const checkHumanQ = await pool.query(`
SELECT sender_role, created_at FROM service_communications
WHERE scraped_id = $1 ORDER BY created_at DESC LIMIT 1
@@ -3988,8 +4014,12 @@ app.post("/webhook/evolution", async (req, res) => {
if (checkHumanQ.rowCount > 0) {
const lastMsg = checkHumanQ.rows[0];
const diffMinutos = (new Date() - new Date(lastMsg.created_at)) / (1000 * 60);
// PUESTO A 0 PARA PRUEBAS: CÁMBIALO A 120 CUANDO TERMINES
if (['admin', 'superadmin', 'operario'].includes(lastMsg.sender_role) && diffMinutos < 0) return;
// 🛑 ESCUDO ACTIVADO: Si un humano ha hablado hace menos de 120 minutos, la IA se calla
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;
}
}
// 🧠 LLAMADA A LA IA