WhatsApp libre al cliente y pausa de la IA por expediente (para Claude) #4
125
server.js
125
server.js
@@ -5845,89 +5845,95 @@ app.post("/services/:id/chat", authMiddleware, async (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
// 📲 WHATSAPP LIBRE AL CLIENTE (PANEL / ASISTENTE CLAUDE)
|
// 🤖 CLAUDE: ENVIAR WHATSAPP AL CLIENTE DE UN EXPEDIENTE
|
||||||
// ==========================================
|
// ==========================================
|
||||||
// Envía un texto al móvil del cliente por la instancia de WhatsApp de la cuenta,
|
// Lo usa el conector de IA (herramienta enviar_whatsapp). Envía el texto tal cual,
|
||||||
// lo guarda en el chat como mensaje humano (activa el escudo humano de 120 min) y,
|
// lo guarda en el chat como "Marsalva (Claude)" y pausa la IA de esa conversación
|
||||||
// por defecto, pausa la IA del expediente igual que el emoji 🔴.
|
// durante pause_minutes (30 por defecto). La pausa se quita sola al vencer.
|
||||||
|
const CLAUDE_SENDER_NAME = "Marsalva (Claude)";
|
||||||
|
|
||||||
app.post("/services/:id/whatsapp", authMiddleware, async (req, res) => {
|
app.post("/services/:id/whatsapp", authMiddleware, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const role = String(req.user.role || "").trim().toLowerCase();
|
if (req.user.role === 'operario' || req.user.role === 'operario_cerrado') {
|
||||||
if (!["admin", "superadmin"].includes(role)) {
|
return res.status(403).json({ ok: false, error: "Solo administración puede enviar desde aquí" });
|
||||||
return res.status(403).json({ ok: false, error: "Solo un administrador puede escribir al cliente" });
|
|
||||||
}
|
}
|
||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
const texto = (req.body?.message || "").toString().trim();
|
const message = (req.body?.message ?? "").toString().trim();
|
||||||
if (!texto) return res.status(400).json({ ok: false, error: "El mensaje está vacío" });
|
if (!message) return res.status(400).json({ ok: false, error: "El mensaje está vacío" });
|
||||||
if (texto.length > 4000) return res.status(400).json({ ok: false, error: "Mensaje demasiado largo" });
|
if (message.length > 4000) return res.status(400).json({ ok: false, error: "Mensaje demasiado largo" });
|
||||||
const pausar = !(req.body?.pause_ia === false || req.body?.pause_ia === "false");
|
|
||||||
|
|
||||||
const svcQ = await pool.query("SELECT id, service_ref, raw_data FROM scraped_services WHERE id=$1 AND owner_id=$2", [id, req.user.accountId]);
|
let pauseMin = parseInt(req.body?.pause_minutes ?? 30, 10);
|
||||||
|
if (!Number.isFinite(pauseMin)) pauseMin = 30;
|
||||||
|
pauseMin = Math.min(Math.max(pauseMin, 0), 720);
|
||||||
|
|
||||||
|
const svcQ = await pool.query("SELECT raw_data FROM scraped_services WHERE id=$1 AND owner_id=$2", [id, req.user.accountId]);
|
||||||
if (svcQ.rowCount === 0) return res.status(404).json({ ok: false, error: "Servicio no encontrado" });
|
if (svcQ.rowCount === 0) return res.status(404).json({ ok: false, error: "Servicio no encontrado" });
|
||||||
const raw = svcQ.rows[0].raw_data || {};
|
const raw = svcQ.rows[0].raw_data || {};
|
||||||
const movil = extractBestMobile(raw);
|
|
||||||
if (!/^[67]\d{8}$/.test(movil || "")) {
|
|
||||||
return res.status(400).json({ ok: false, error: "El expediente no tiene un móvil válido" });
|
|
||||||
}
|
|
||||||
|
|
||||||
const enviado = await sendWhatsAppAuto("34" + movil, texto, "cliente_" + req.user.accountId, false);
|
const nueve = req.body?.phone ? extractValidPhone(String(req.body.phone)) : extractBestMobile(raw);
|
||||||
if (!enviado) return res.status(502).json({ ok: false, error: "WhatsApp no ha podido enviar el mensaje" });
|
if (!/^[67]\d{8}$/.test(nueve || "")) return res.status(400).json({ ok: false, error: "El expediente no tiene un móvil válido" });
|
||||||
|
const destino = "34" + nueve;
|
||||||
|
|
||||||
if (pausar) {
|
// Pausamos ANTES de enviar, para que la IA no conteste a la vez que nosotros
|
||||||
await pool.query("UPDATE scraped_services SET raw_data = COALESCE(raw_data, '{}'::jsonb) || '{\"ia_paused\": true}'::jsonb WHERE id = $1", [id]);
|
let hasta = null;
|
||||||
|
if (pauseMin > 0) {
|
||||||
|
hasta = new Date(Date.now() + pauseMin * 60000).toISOString();
|
||||||
await pool.query(
|
await pool.query(
|
||||||
"INSERT INTO service_communications (scraped_id, owner_id, sender_name, sender_role, message, is_internal) VALUES ($1, $2, 'Sistema', 'system', $3, true)",
|
"UPDATE scraped_services SET raw_data = COALESCE(raw_data, '{}'::jsonb) || jsonb_build_object('ia_paused_until', $2::text) WHERE id=$1 AND owner_id=$3",
|
||||||
[id, req.user.accountId, "🔴 IA pausada al escribir al cliente desde el panel/asistente."]
|
[id, hasta, req.user.accountId]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const userQ = await pool.query("SELECT full_name FROM users WHERE id=$1", [req.user.sub]);
|
const enviado = await sendWhatsAppAuto(destino, message, `cliente_${req.user.accountId}`, false);
|
||||||
const senderName = userQ.rows[0]?.full_name || "Admin";
|
if (!enviado) return res.status(502).json({ ok: false, error: "No se pudo enviar el WhatsApp (revisa la conexión con Evolution)" });
|
||||||
|
|
||||||
const insertQ = await pool.query(
|
const insertQ = await pool.query(
|
||||||
"INSERT INTO service_communications (scraped_id, owner_id, sender_id, sender_name, sender_role, message, is_internal) VALUES ($1, $2, $3, $4, $5, $6, false) RETURNING id, sender_id, sender_name, sender_role, message, is_internal, created_at",
|
`INSERT INTO service_communications (scraped_id, owner_id, sender_id, sender_name, sender_role, message, is_internal)
|
||||||
[id, req.user.accountId, req.user.sub, senderName, role, texto]
|
VALUES ($1, $2, $3, $4, 'admin', $5, false)
|
||||||
|
RETURNING id, sender_name, message, created_at`,
|
||||||
|
[id, req.user.accountId, req.user.sub, CLAUDE_SENDER_NAME, message]
|
||||||
);
|
);
|
||||||
await pool.query(
|
await pool.query(
|
||||||
"INSERT INTO scraped_service_logs (scraped_id, user_name, action, details) VALUES ($1, $2, $3, $4)",
|
"INSERT INTO scraped_service_logs (scraped_id, user_name, action, details) VALUES ($1, $2, $3, $4)",
|
||||||
[id, senderName, "WhatsApp enviado al cliente", "Al " + movil + ": " + texto.slice(0, 500)]
|
[id, CLAUDE_SENDER_NAME, "WhatsApp enviado al cliente", "Al " + nueve + ": " + message.slice(0, 500)]
|
||||||
).catch(e => console.error("⚠️ Log WhatsApp manual:", e.message));
|
).catch(e => console.error("⚠️ Log WhatsApp de Claude:", e.message));
|
||||||
|
|
||||||
res.json({ ok: true, phone: movil, ia_paused: pausar, message: insertQ.rows[0] });
|
console.log(`🤖 [CLAUDE WA] Enviado a ${destino} (servicio ${id}). IA pausada hasta ${hasta || 'sin pausa'}`);
|
||||||
|
res.json({ ok: true, sent_to: destino, ia_paused_until: hasta, message: insertQ.rows[0] });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("❌ Error enviando WhatsApp manual:", e.message);
|
console.error("Error enviando WhatsApp de Claude:", e);
|
||||||
res.status(500).json({ ok: false, error: "Error interno" });
|
res.status(500).json({ ok: false });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// 🔴/🟢 PAUSAR O REACTIVAR LA IA DE UN EXPEDIENTE DESDE EL PANEL / ASISTENTE
|
// 🟢 Quitar la pausa temporal de la IA (no toca la pausa manual con 🔴)
|
||||||
app.post("/services/:id/ia", authMiddleware, async (req, res) => {
|
app.post("/services/:id/ia/resume", authMiddleware, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const role = String(req.user.role || "").trim().toLowerCase();
|
if (req.user.role === 'operario' || req.user.role === 'operario_cerrado') {
|
||||||
if (!["admin", "superadmin"].includes(role)) {
|
return res.status(403).json({ ok: false, error: "Solo administración" });
|
||||||
return res.status(403).json({ ok: false, error: "Solo un administrador puede cambiar la IA" });
|
|
||||||
}
|
}
|
||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
const paused = req.body?.paused === true || req.body?.paused === "true";
|
const q = await pool.query(
|
||||||
const svcQ = await pool.query("SELECT id FROM scraped_services WHERE id=$1 AND owner_id=$2", [id, req.user.accountId]);
|
`UPDATE scraped_services SET raw_data = COALESCE(raw_data, '{}'::jsonb) - 'ia_paused_until'
|
||||||
if (svcQ.rowCount === 0) return res.status(404).json({ ok: false, error: "Servicio no encontrado" });
|
WHERE id=$1 AND owner_id=$2
|
||||||
|
RETURNING LOWER(COALESCE(raw_data->>'ia_paused', 'false')) IN ('true', 't', '1') AS pausa_manual`,
|
||||||
if (paused) {
|
[id, req.user.accountId]
|
||||||
await pool.query("UPDATE scraped_services SET raw_data = COALESCE(raw_data, '{}'::jsonb) || '{\"ia_paused\": true}'::jsonb WHERE id = $1", [id]);
|
|
||||||
} else {
|
|
||||||
await pool.query("UPDATE scraped_services SET raw_data = raw_data - 'ia_paused' WHERE id = $1", [id]);
|
|
||||||
}
|
|
||||||
await pool.query(
|
|
||||||
"INSERT INTO service_communications (scraped_id, owner_id, sender_name, sender_role, message, is_internal) VALUES ($1, $2, 'Sistema', 'system', $3, true)",
|
|
||||||
[id, req.user.accountId, paused ? "🔴 IA pausada desde el panel/asistente." : "🟢 IA reactivada desde el panel/asistente."]
|
|
||||||
);
|
);
|
||||||
res.json({ ok: true, ia_paused: paused });
|
if (q.rowCount === 0) return res.status(404).json({ ok: false, error: "Servicio no encontrado" });
|
||||||
|
|
||||||
|
await pool.query(
|
||||||
|
`INSERT INTO service_communications (scraped_id, owner_id, sender_name, sender_role, message, is_internal)
|
||||||
|
VALUES ($1, $2, 'Sistema', 'system', $3, true)`,
|
||||||
|
[id, req.user.accountId, "🟢 IA reactivada al terminar la conversación de Claude."]
|
||||||
|
);
|
||||||
|
|
||||||
|
res.json({ ok: true, manual_pause_still_active: q.rows[0].pausa_manual === true });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("❌ Error cambiando estado de la IA:", e.message);
|
console.error("Error reactivando IA:", e);
|
||||||
res.status(500).json({ ok: false, error: "Error interno" });
|
res.status(500).json({ ok: false });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
// 🧾 PARTES DE TRABAJO (texto con IA + firma + PDF + envío WhatsApp)
|
// 🧾 PARTES DE TRABAJO (texto con IA + firma + PDF + envío WhatsApp)
|
||||||
// ==========================================
|
// ==========================================
|
||||||
@@ -6069,12 +6075,25 @@ async function procesarTurnoIA({ ownerId, service, mensajeTexto, telefonoCliente
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ⏸️ Pausa temporal (p. ej. cuando Claude escribe al cliente): se quita sola al vencer
|
||||||
|
try {
|
||||||
|
const pausaQ = await pool.query("SELECT raw_data->>'ia_paused_until' AS hasta FROM scraped_services WHERE id = $1", [service.id]);
|
||||||
|
const hasta = pausaQ.rows[0]?.hasta ? new Date(pausaQ.rows[0].hasta) : null;
|
||||||
|
if (hasta && !isNaN(hasta.getTime()) && hasta.getTime() > Date.now()) {
|
||||||
|
console.log(`⏸️ [IA EN PAUSA] ${service.service_ref} hasta ${hasta.toISOString()}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (ePausa) {
|
||||||
|
console.error("Error comprobando pausa temporal de IA:", ePausa.message);
|
||||||
|
}
|
||||||
|
|
||||||
// 🛡️ Escudo humano: si alguien habló hace menos de 120 min, la IA se calla
|
// 🛡️ Escudo humano: si alguien habló hace menos de 120 min, la IA se calla
|
||||||
const checkHumanQ = await pool.query(`
|
const checkHumanQ = await pool.query(`
|
||||||
SELECT sender_role, created_at
|
SELECT sender_role, created_at
|
||||||
FROM service_communications
|
FROM service_communications
|
||||||
WHERE scraped_id = $1
|
WHERE scraped_id = $1
|
||||||
AND sender_role IN ('admin', 'superadmin', 'operario')
|
AND sender_role IN ('admin', 'superadmin', 'operario')
|
||||||
|
AND COALESCE(sender_name, '') <> 'Marsalva (Claude)'
|
||||||
ORDER BY created_at DESC
|
ORDER BY created_at DESC
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
`, [service.id]);
|
`, [service.id]);
|
||||||
@@ -6533,7 +6552,7 @@ app.post("/webhook/evolution", async (req, res) => {
|
|||||||
try {
|
try {
|
||||||
await pool.query(`
|
await pool.query(`
|
||||||
UPDATE scraped_services
|
UPDATE scraped_services
|
||||||
SET raw_data = raw_data - 'ia_paused'
|
SET raw_data = raw_data - 'ia_paused' - 'ia_paused_until'
|
||||||
WHERE id = $1
|
WHERE id = $1
|
||||||
`, [service.id]);
|
`, [service.id]);
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user