diff --git a/server.js b/server.js index a6a8492..61915a1 100644 --- a/server.js +++ b/server.js @@ -1224,27 +1224,40 @@ app.post("/agenda/requests/:id/approve", authMiddleware, async (req, res) => { delete updatedRaw.requested_date; delete updatedRaw.requested_time; + // 1. Guardamos en Base de Datos await pool.query("UPDATE scraped_services SET raw_data=$1 WHERE id=$2", [JSON.stringify(updatedRaw), id]); console.log(`🤖 [PORTAL-CITA] Cita aprobada para ${reqDate}. Disparando eventos...`); - // Disparamos WhatsApp oficial de cita confirmada - await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_date'); - - // 🚀 DISPARAR ROBOTS SEGÚN PROVEEDOR - const checkProv = await pool.query("SELECT provider FROM scraped_services WHERE id=$1", [id]); - const providerName = checkProv.rows[0]?.provider; - - if (providerName === 'homeserve') { - console.log(`✅ [PORTAL-CITA] Disparando robot HS: CITA (${reqDate})`); - triggerHomeServeRobot(req.user.accountId, id, 'date').catch(console.error); - } else if (providerName === 'multiasistencia') { - console.log(`✅ [PORTAL-CITA] Disparando robot MULTI: CITA (${reqDate})`); - triggerMultiRobot(req.user.accountId, id, 'date').catch(console.error); - } - + // 🚀 2. RESPONDEMOS AL NAVEGADOR INMEDIATAMENTE (La ventana se cierra al instante) res.json({ok: true}); - } catch (e) { res.status(500).json({ok: false}); } + + // 👻 3. TAREAS EN SEGUNDO PLANO (El WA tarda 10 segs, pero el usuario ya no espera) + (async () => { + try { + // Disparamos WhatsApp oficial de cita confirmada + await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_date'); + + // Disparamos ROBOTS SEGÚN PROVEEDOR + const checkProv = await pool.query("SELECT provider FROM scraped_services WHERE id=$1", [id]); + const providerName = checkProv.rows[0]?.provider; + + if (providerName === 'homeserve') { + console.log(`✅ [PORTAL-CITA] Disparando robot HS: CITA (${reqDate})`); + triggerHomeServeRobot(req.user.accountId, id, 'date').catch(console.error); + } else if (providerName === 'multiasistencia') { + console.log(`✅ [PORTAL-CITA] Disparando robot MULTI: CITA (${reqDate})`); + triggerMultiRobot(req.user.accountId, id, 'date').catch(console.error); + } + } catch (errBckg) { + console.error("Error en tareas de fondo de aprobar cita:", errBckg); + } + })(); + + } catch (e) { + console.error("Error al aprobar cita:", e); + if (!res.headersSent) res.status(500).json({ok: false}); + } }); // 5. RECHAZAR CITA