Actualizar server.js

This commit is contained in:
2026-03-16 22:00:53 +00:00
parent bcf5f07f51
commit 9f9bc27060

View File

@@ -3714,7 +3714,8 @@ app.post("/services/:id/chat", authMiddleware, async (req, res) => {
app.post("/webhook/evolution", async (req, res) => {
try {
const data = req.body;
if (data.event !== "messages.upsert" || data.data.key.fromMe) return res.sendStatus(200);
// 🚨 CAMBIO 1: Quitamos el 'fromMe' de aquí arriba para que el servidor escuche TUS mensajes
if (data.event !== "messages.upsert") return res.sendStatus(200);
const remoteJid = data.data.key.remoteJid;
const telefonoCliente = remoteJid.split("@")[0];
@@ -3731,7 +3732,6 @@ app.post("/webhook/evolution", async (req, res) => {
const ownerId = instanceName.split("_")[1];
const cleanPhone = telefonoCliente.slice(-9);
// 🔍 BUSCAMOS EL EXPEDIENTE ACTIVO MÁS RECIENTE (Ignorando finalizados/anulados)
// 🔍 BUSCAMOS EL EXPEDIENTE ACTIVO MÁS RECIENTE (Ignorando finalizados/anulados)
const svcQ = await pool.query(`
SELECT s.id, s.service_ref, s.assigned_to, u.full_name as worker_name, s.is_urgent,
@@ -3756,6 +3756,15 @@ app.post("/webhook/evolution", async (req, res) => {
if (svcQ.rowCount > 0) {
const service = svcQ.rows[0];
// 🚨 CAMBIO 2: EL NUEVO ESCUDO HUMANO 🚨
// Si detecta que el mensaje lo has mandado TÚ desde tu móvil de empresa
if (data.data.key.fromMe) {
// Lo guarda en la base de datos para que quede constancia y la IA sepa que estás al mando
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; // Cortamos la ejecución. ¡ChatGPT no dirá ni mu!
}
// 🛑 SEMÁFORO ANTI-METRALLETA
if (candadosIA.has(service.id)) {
return;
@@ -3772,6 +3781,7 @@ 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);
// Como tu mensaje se guardó como 'operario', aquí saltará esta regla y detendrá a la IA durante 120 min
if (['admin', 'superadmin', 'operario'].includes(lastMsg.sender_role) && diffMinutos < 120) return;
}