Actualizar server.js

This commit is contained in:
2026-03-04 22:46:41 +00:00
parent 9d7166e81e
commit f00b854959

View File

@@ -1368,6 +1368,7 @@ app.get("/services/active", authMiddleware, async (req, res) => {
// AÑADIDO: Ruta para fijar la cita o el estado operativo (CORREGIDA PARA NO PERDER LA FECHA) // AÑADIDO: Ruta para fijar la cita o el estado operativo (CORREGIDA PARA NO PERDER LA FECHA)
// AÑADIDO: Ruta para fijar la cita o el estado operativo (CORREGIDA PARA NO PERDER LA FECHA Y ENVIAR BIEN EL WHATSAPP) // AÑADIDO: Ruta para fijar la cita o el estado operativo (CORREGIDA PARA NO PERDER LA FECHA Y ENVIAR BIEN EL WHATSAPP)
// AÑADIDO: Ruta para fijar la cita o el estado operativo (CON ENVÍO WA EN SEGUNDO PLANO)
app.put("/services/set-appointment/:id", authMiddleware, async (req, res) => { app.put("/services/set-appointment/:id", authMiddleware, async (req, res) => {
try { try {
const { id } = req.params; const { id } = req.params;
@@ -1398,7 +1399,7 @@ app.put("/services/set-appointment/:id", authMiddleware, async (req, res) => {
newTime = ""; newTime = "";
} }
// 1. PRIMERO GUARDAMOS EN BASE DE DATOS (Para que los motores puedan leer la info real) // 1. GUARDAMOS EN BBDD RÁPIDAMENTE
const updatedRawData = { const updatedRawData = {
...rawActual, ...rawActual,
...extra, ...extra,
@@ -1411,7 +1412,17 @@ app.put("/services/set-appointment/:id", authMiddleware, async (req, res) => {
[JSON.stringify(updatedRawData), finalAssignedTo, id, req.user.accountId] [JSON.stringify(updatedRawData), finalAssignedTo, id, req.user.accountId]
); );
// 2. DESPUÉS LANZAMOS LOS EVENTOS (Con la BBDD ya actualizada) // --- INICIO TRAZABILIDAD ---
let logDetalle = `Estado modificado a: ${stName.toUpperCase() || 'MODIFICADO'}.`;
if (newDate) logDetalle += ` Cita para el ${newDate} a las ${newTime}.`;
await registrarMovimiento(id, req.user.sub, "Actualización desde App", logDetalle);
// 🚀 RESPONDEMOS AL NAVEGADOR INMEDIATAMENTE (La ventana se cierra al instante)
res.json({ ok: true });
// 2. MAGIA: TAREAS EN SEGUNDO PLANO (El WhatsApp tarda lo que tenga que tardar, sin bloquear)
(async () => {
try {
if (stName.includes('asignado')) { if (stName.includes('asignado')) {
const waEnviadoExito = await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_assigned'); const waEnviadoExito = await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_assigned');
if (waEnviadoExito) { if (waEnviadoExito) {
@@ -1436,10 +1447,8 @@ app.put("/services/set-appointment/:id", authMiddleware, async (req, res) => {
sendWhatsAppAuto(w.phone, msg, `cliente_${req.user.accountId}`, false).catch(console.error); sendWhatsAppAuto(w.phone, msg, `cliente_${req.user.accountId}`, false).catch(console.error);
} }
} }
// Limpieza de datos si se desasigna
updatedRawData.assigned_to = null; updatedRawData.assigned_to = null;
updatedRawData.assigned_to_name = null; updatedRawData.assigned_to_name = null;
finalAssignedTo = null;
await pool.query('UPDATE scraped_services SET raw_data = $1, assigned_to = null WHERE id = $2 AND owner_id = $3', [JSON.stringify(updatedRawData), id, req.user.accountId]); await pool.query('UPDATE scraped_services SET raw_data = $1, assigned_to = null WHERE id = $2 AND owner_id = $3', [JSON.stringify(updatedRawData), id, req.user.accountId]);
} }
else if (stName.includes('citado') && newDate !== "" && date !== undefined) { else if (stName.includes('citado') && newDate !== "" && date !== undefined) {
@@ -1449,21 +1458,19 @@ app.put("/services/set-appointment/:id", authMiddleware, async (req, res) => {
} else if (stName.includes('camino')) { } else if (stName.includes('camino')) {
await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_onway'); await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_onway');
} else if (stName.includes('finalizado') || stName.includes('terminado')) { } else if (stName.includes('finalizado') || stName.includes('terminado')) {
if (!skip_survey) { // Solo lo mandamos si el operario no dijo que NO if (!skip_survey) {
await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_survey'); await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_survey');
} }
} }
} catch (errBckg) {
console.error("Error en tareas de fondo:", errBckg);
}
})(); // El paréntesis final ejecuta esto en las sombras
// --- INICIO TRAZABILIDAD ---
let logDetalle = `Estado modificado a: ${stName.toUpperCase() || 'MODIFICADO'}.`;
if (newDate) logDetalle += ` Cita para el ${newDate} a las ${newTime}.`;
await registrarMovimiento(id, req.user.sub, "Actualización desde App", logDetalle);
// --- FIN TRAZABILIDAD ---
res.json({ ok: true });
} catch (e) { } catch (e) {
console.error("Error agendando cita:", e); console.error("Error agendando cita:", e);
res.status(500).json({ ok: false }); // Solo enviamos error si no hemos respondido ya
if (!res.headersSent) res.status(500).json({ ok: false });
} }
}); });