WhatsApp libre al cliente y pausa de la IA por expediente (para Claude) #4

Merged
marsalva merged 4 commits from feature/whatsapp-claude into main 2026-11-25 15:11:41 +00:00
Showing only changes of commit c94ab7e054 - Show all commits

View File

@@ -5844,6 +5844,90 @@ app.post("/services/:id/chat", authMiddleware, async (req, res) => {
} }
}); });
// ==========================================
// 📲 WHATSAPP LIBRE AL CLIENTE (PANEL / ASISTENTE CLAUDE)
// ==========================================
// Envía un texto al móvil del cliente por la instancia de WhatsApp de la cuenta,
// lo guarda en el chat como mensaje humano (activa el escudo humano de 120 min) y,
// por defecto, pausa la IA del expediente igual que el emoji 🔴.
app.post("/services/:id/whatsapp", authMiddleware, async (req, res) => {
try {
const role = String(req.user.role || "").trim().toLowerCase();
if (!["admin", "superadmin"].includes(role)) {
return res.status(403).json({ ok: false, error: "Solo un administrador puede escribir al cliente" });
}
const { id } = req.params;
const texto = (req.body?.message || "").toString().trim();
if (!texto) 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" });
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]);
if (svcQ.rowCount === 0) return res.status(404).json({ ok: false, error: "Servicio no encontrado" });
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);
if (!enviado) return res.status(502).json({ ok: false, error: "WhatsApp no ha podido enviar el mensaje" });
if (pausar) {
await pool.query("UPDATE scraped_services SET raw_data = COALESCE(raw_data, '{}'::jsonb) || '{\"ia_paused\": true}'::jsonb 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, "🔴 IA pausada al escribir al cliente desde el panel/asistente."]
);
}
const userQ = await pool.query("SELECT full_name FROM users WHERE id=$1", [req.user.sub]);
const senderName = userQ.rows[0]?.full_name || "Admin";
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",
[id, req.user.accountId, req.user.sub, senderName, role, texto]
);
await pool.query(
"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)]
).catch(e => console.error("⚠️ Log WhatsApp manual:", e.message));
res.json({ ok: true, phone: movil, ia_paused: pausar, message: insertQ.rows[0] });
} catch (e) {
console.error("❌ Error enviando WhatsApp manual:", e.message);
res.status(500).json({ ok: false, error: "Error interno" });
}
});
// 🔴/🟢 PAUSAR O REACTIVAR LA IA DE UN EXPEDIENTE DESDE EL PANEL / ASISTENTE
app.post("/services/:id/ia", authMiddleware, async (req, res) => {
try {
const role = String(req.user.role || "").trim().toLowerCase();
if (!["admin", "superadmin"].includes(role)) {
return res.status(403).json({ ok: false, error: "Solo un administrador puede cambiar la IA" });
}
const { id } = req.params;
const paused = req.body?.paused === true || req.body?.paused === "true";
const svcQ = await pool.query("SELECT id 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 (paused) {
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 });
} catch (e) {
console.error("❌ Error cambiando estado de la IA:", e.message);
res.status(500).json({ ok: false, error: "Error interno" });
}
});
// ========================================== // ==========================================
// 🧾 PARTES DE TRABAJO (texto con IA + firma + PDF + envío WhatsApp) // 🧾 PARTES DE TRABAJO (texto con IA + firma + PDF + envío WhatsApp)
// ========================================== // ==========================================