Actualizar server.js
This commit is contained in:
39
server.js
39
server.js
@@ -2839,6 +2839,7 @@ app.get("/services/:id/chat", authMiddleware, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// 2. Enviar un nuevo mensaje (Oficina u Operario) CON AVISO WHATSAPP Y TRAZABILIDAD
|
||||
app.post("/services/:id/chat", authMiddleware, async (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
@@ -2853,6 +2854,7 @@ app.post("/services/:id/chat", authMiddleware, async (req, res) => {
|
||||
const senderName = userQ.rows[0]?.full_name || "Usuario";
|
||||
const senderRole = userQ.rows[0]?.role || "operario";
|
||||
|
||||
// 1. Guardar el mensaje en la base de datos (Chat)
|
||||
await pool.query(`
|
||||
INSERT INTO service_communications
|
||||
(scraped_id, owner_id, sender_id, sender_name, sender_role, message, is_internal)
|
||||
@@ -2860,9 +2862,42 @@ app.post("/services/:id/chat", authMiddleware, async (req, res) => {
|
||||
`, [id, req.user.accountId, req.user.sub, senderName, senderRole, message.trim(), finalIsInternal]);
|
||||
|
||||
res.json({ ok: true });
|
||||
|
||||
// 2. Lógica de Notificación y Trazabilidad
|
||||
if (!isOperario && !finalIsInternal) {
|
||||
const svcQ = await pool.query("SELECT assigned_to, service_ref FROM scraped_services WHERE id=$1", [id]);
|
||||
|
||||
if (svcQ.rowCount > 0 && svcQ.rows[0].assigned_to) {
|
||||
const workerId = svcQ.rows[0].assigned_to;
|
||||
const ref = svcQ.rows[0].service_ref || id;
|
||||
|
||||
const wQ = await pool.query("SELECT phone, full_name FROM users WHERE id=$1", [workerId]);
|
||||
|
||||
if (wQ.rowCount > 0 && wQ.rows[0].phone) {
|
||||
const workerPhone = wQ.rows[0].phone;
|
||||
const workerName = wQ.rows[0].full_name;
|
||||
|
||||
const msgWa = `💬 *NUEVO MENSAJE DE LA OFICINA*\nExpediente: *#${ref}*\n\n"${message.trim()}"\n\n_Entra en tu App para contestar._`;
|
||||
|
||||
// A) Disparar el WhatsApp
|
||||
const waExito = await sendWhatsAppAuto(workerPhone, msgWa, `cliente_${req.user.accountId}`, false);
|
||||
|
||||
// B) 🟢 DEJAR HUELLA EN EL LOG (Trazabilidad)
|
||||
const logDetalle = waExito
|
||||
? `Aviso enviado por WhatsApp a ${workerName} (${workerPhone}).`
|
||||
: `Intento de aviso por WhatsApp a ${workerName} fallido (revisar conexión Evolution).`;
|
||||
|
||||
await pool.query(
|
||||
"INSERT INTO scraped_service_logs (scraped_id, user_name, action, details) VALUES ($1, $2, $3, $4)",
|
||||
[id, "Sistema (Chat)", "Notificación Enviada", logDetalle]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
console.error("Error enviando mensaje:", e);
|
||||
res.status(500).json({ ok: false });
|
||||
console.error("Error enviando mensaje y log:", e);
|
||||
if (!res.headersSent) res.status(500).json({ ok: false });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user