diff --git a/server.js b/server.js index 99231ac..b4f0f7c 100644 --- a/server.js +++ b/server.js @@ -1288,7 +1288,7 @@ app.get("/services/active", authMiddleware, async (req, res) => { } }); -// AÑADIDO: Ruta para fijar la cita o el estado operativo (REGLA ESTRICTA) +// AÑADIDO: Ruta para fijar la cita o el estado operativo (CORREGIDA PARA NO PERDER LA FECHA) app.put("/services/set-appointment/:id", authMiddleware, async (req, res) => { try { const { id } = req.params; @@ -1297,10 +1297,13 @@ app.put("/services/set-appointment/:id", authMiddleware, async (req, res) => { const current = await pool.query('SELECT raw_data, assigned_to 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' }); - const oldDate = current.rows[0].raw_data.scheduled_date || ""; - const oldTime = current.rows[0].raw_data.scheduled_time || ""; - let newDate = date || ""; - let newTime = time || ""; + const rawActual = current.rows[0].raw_data || {}; + + // --- MEJORA: MANTENER FECHA SI NO SE ENVÍA --- + // Si 'date' es undefined (no viene en el JSON), usamos la que ya tiene el servicio. + let newDate = (date !== undefined) ? date : (rawActual.scheduled_date || ""); + let newTime = (time !== undefined) ? time : (rawActual.scheduled_time || ""); + let finalAssignedTo = current.rows[0].assigned_to; if (status_operativo === "") status_operativo = null; @@ -1311,13 +1314,14 @@ app.put("/services/set-appointment/:id", authMiddleware, async (req, res) => { stName = (statusQ.rows[0]?.name || "").toLowerCase(); } - // --- NUEVA REGLA: BORRAR FECHAS SI SE ANULA O RETROCEDE --- + // --- REGLA ESTRICTA: BORRAR FECHAS SOLO SI SE ANULA O RETROCEDE A PENDIENTE --- if (stName.includes('pendiente') || stName.includes('desasignado') || stName.includes('asignado') || stName.includes('anulado') || stName.includes('esperando')) { + // Solo en estos casos reseteamos la fecha a vacío newDate = ""; newTime = ""; } - // --- MOTOR DE EVENTOS Y DESASIGNACIÓN --- + // --- MOTOR DE EVENTOS --- if (stName.includes('asignado')) { const waEnviadoExito = await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_assigned'); if (waEnviadoExito) { @@ -1328,12 +1332,12 @@ app.put("/services/set-appointment/:id", authMiddleware, async (req, res) => { } } else if (stName.includes('pendiente de asignar') || stName.includes('desasignado')) { - const oldWorkerId = finalAssignedTo || current.rows[0].raw_data.assigned_to; + const oldWorkerId = finalAssignedTo || rawActual.assigned_to; if (oldWorkerId) { const workerQ = await pool.query("SELECT full_name, phone FROM users WHERE id=$1", [oldWorkerId]); if (workerQ.rowCount > 0) { const w = workerQ.rows[0]; - const ref = current.rows[0].raw_data.service_ref || current.rows[0].raw_data["Referencia"] || id; + const ref = rawActual.service_ref || rawActual["Referencia"] || id; const msg = `⚠️ *AVISO DE DESASIGNACIÓN*\n\nHola ${w.full_name}, se te ha retirado el expediente *#${ref}*.\n\nYa no tienes que atender este servicio.`; sendWhatsAppAuto(w.phone, msg, `cliente_${req.user.accountId}`, false).catch(console.error); } @@ -1342,18 +1346,28 @@ app.put("/services/set-appointment/:id", authMiddleware, async (req, res) => { extra.assigned_to_name = null; finalAssignedTo = null; } - else if (stName.includes('citado') && newDate !== "") { + else if (stName.includes('citado') && newDate !== "" && date !== undefined) { + // Solo disparamos el WA de cita si realmente estamos enviando una fecha nueva (date !== undefined) + const oldDate = rawActual.scheduled_date || ""; 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 (oldDate !== newDate) await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_update'); } else if (stName.includes('camino')) { await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_onway'); } else if (stName.includes('finalizado') || stName.includes('terminado')) { await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_survey'); } - const updatedRawData = { ...current.rows[0].raw_data, ...extra, "scheduled_date": newDate, "scheduled_time": newTime, "status_operativo": status_operativo }; + const updatedRawData = { + ...rawActual, + ...extra, + "scheduled_date": newDate, + "scheduled_time": newTime, + "status_operativo": status_operativo + }; - await pool.query('UPDATE scraped_services SET raw_data = $1, assigned_to = $2 WHERE id = $3 AND owner_id = $4', [JSON.stringify(updatedRawData), finalAssignedTo, id, req.user.accountId]); + await pool.query('UPDATE scraped_services SET raw_data = $1, assigned_to = $2 WHERE id = $3 AND owner_id = $4', + [JSON.stringify(updatedRawData), finalAssignedTo, id, req.user.accountId] + ); res.json({ ok: true }); } catch (e) {