diff --git a/server.js b/server.js index 749bee3..8e1d2db 100644 --- a/server.js +++ b/server.js @@ -973,11 +973,11 @@ app.get("/services/active", authMiddleware, async (req, res) => { } catch (e) { res.status(500).json({ ok: false }); } }); -// AÑADIDO: Ruta para fijar la cita o el estado operativo (REGLA ESTRICTA) app.put("/services/set-appointment/:id", authMiddleware, async (req, res) => { try { const { id } = req.params; - let { date, time, status_operativo, ...extra } = req.body; // let en status_operativo para poder cambiarlo + // OJO: status_operativo con 'let' para que la IA pueda cambiarlo + let { date, time, status_operativo, ...extra } = req.body; const current = await pool.query('SELECT raw_data FROM scraped_services WHERE id = $1 AND owner_id = $2', [id, req.user.accountId]); if (current.rowCount === 0) return res.status(404).json({ ok: false, error: 'No encontrado' }); @@ -986,31 +986,34 @@ app.put("/services/set-appointment/:id", authMiddleware, async (req, res) => { const oldTime = current.rows[0].raw_data.scheduled_time || ""; const newDate = date || ""; const newTime = time || ""; - + const statusQ = await pool.query("SELECT name FROM service_statuses WHERE id=$1", [status_operativo]); const stName = statusQ.rows[0]?.name.toLowerCase() || ""; - // --- REGLA: ASIGNADO -> WA -> ESPERANDO AL CLIENTE --- + // --- REGLA ESTRICTA: ASIGNADO -> WA -> ESPERANDO AL CLIENTE --- if (stName.includes('asignado')) { const waEnviadoExito = await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_assigned'); if (waEnviadoExito) { - // Si el WA se envía correctamente, forzamos el estado a "Esperando al Cliente" + // Si el WA se envía correctamente, forzamos el salto a "Esperando al Cliente" const estadoEsperando = await pool.query("SELECT id FROM service_statuses WHERE owner_id=$1 AND name='Esperando al Cliente' LIMIT 1", [req.user.accountId]); - if(estadoEsperando.rowCount > 0) status_operativo = estadoEsperando.rows[0].id; + if (estadoEsperando.rowCount > 0) { + status_operativo = estadoEsperando.rows[0].id; + } } } else if (stName.includes('citado') && newDate !== "") { - if (oldDate === "") triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_date'); - else if (oldDate !== newDate || oldTime !== newTime) triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_update'); + if (oldDate === "") await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_date'); + else if (oldDate !== newDate || oldTime !== newTime) await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_update'); } else if (stName.includes('camino')) { - 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')) { - triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_survey'); + await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_survey'); } - // Guardamos el estado definitivo (sea el que arrastró, o el forzado a "Esperando") + // Finalmente, guardamos (con el estado original, o con el estado "Esperando" si el WA llegó) const updatedRawData = { ...current.rows[0].raw_data, ...extra, "scheduled_date": newDate, "scheduled_time": newTime, "status_operativo": status_operativo }; - await pool.query('UPDATE scraped_services SET raw_data = $1 WHERE id = $2 AND owner_id = $3', [JSON.stringify(updatedRawData), id, req.user.accountId]); + await pool.query('UPDATE scraped_services SET raw_data = $1 WHERE id = $2 AND owner_id = $3', [JSON.stringify(updatedRawData), id, req.user.accountId]); + res.json({ ok: true }); } catch (e) { console.error("Error agendando cita:", e);