diff --git a/server.js b/server.js index dfb7d8d..3a4faf1 100644 --- a/server.js +++ b/server.js @@ -5704,7 +5704,8 @@ app.put("/budgets/:id", authMiddleware, async (req, res) => { app.patch("/budgets/:id/status", authMiddleware, async (req, res) => { try { - await pool.query("UPDATE budgets SET status=$1 WHERE id=$2 AND owner_id=$3", [req.body.status, req.params.id, req.user.accountId]); + const upd = await pool.query("UPDATE budgets SET status=$1 WHERE id=$2 AND owner_id=$3", [req.body.status, req.params.id, req.user.accountId]); + if (upd.rowCount > 0) await sincronizarExpedientePresupuesto(req.params.id, req.user.accountId, req.body.status, "Panel"); res.json({ ok: true }); } catch(e) { res.status(500).json({ok: false}); } }); @@ -6512,6 +6513,60 @@ app.post("/webhook/evolution", async (req, res) => { } }); +// ========================================== +// 🗄️ ARCHIVO AUTOMÁTICO DEL EXPEDIENTE DE UN PRESUPUESTO +// ========================================== +// Cuando el cliente RECHAZA un presupuesto, su expediente propio (service_ref "PRE-") se archiva +// en estado Anulado y se le quita el modo presupuesto, para que no quede abierto ni el asistente de +// WhatsApp lo siga tratando como pendiente. Si más tarde se ACEPTA, se reabre (solo si lo archivó esto). +// Nunca toca servicios de compañías (HomeServe, Multi...): solo el expediente PRE- del presupuesto. +async function sincronizarExpedientePresupuesto(budgetId, ownerId, nuevoEstado, origen = "Sistema") { + try { + if (!budgetId || !ownerId) return; + if (nuevoEstado !== "rejected" && nuevoEstado !== "accepted") return; + const sq = await pool.query( + "SELECT id, status, raw_data FROM scraped_services WHERE owner_id = $1 AND service_ref = $2 ORDER BY id DESC LIMIT 1", + [ownerId, `PRE-${budgetId}`] + ); + if (sq.rowCount === 0) return; + const exp = sq.rows[0]; + const raw = exp.raw_data || {}; + + if (nuevoEstado === "rejected") { + if (exp.status === "archived") return; + const stQ = await pool.query( + "SELECT id FROM service_statuses WHERE owner_id = $1 AND LOWER(TRIM(name)) = 'anulado' ORDER BY id LIMIT 1", + [ownerId] + ); + raw.budget_mode = false; + raw.archived_at = new Date().toISOString(); + raw.archivado_por_rechazo = true; + raw.estado_operativo_previo = raw.status_operativo ?? null; + if (stQ.rowCount > 0) raw.status_operativo = stQ.rows[0].id; + await pool.query("UPDATE scraped_services SET status = 'archived', raw_data = $1 WHERE id = $2", [JSON.stringify(raw), exp.id]); + await pool.query( + "INSERT INTO scraped_service_logs (scraped_id, user_name, action, details) VALUES ($1, $2, $3, $4)", + [exp.id, origen, "Presupuesto Rechazado", `El cliente ha rechazado el presupuesto PRE-${budgetId}. Expediente archivado automáticamente.`] + ).catch(() => {}); + console.log(`🗄️ [PRESUPUESTOS] PRE-${budgetId} rechazado → expediente ${exp.id} archivado`); + } else if (exp.status === "archived" && raw.archivado_por_rechazo) { + delete raw.archived_at; + delete raw.archivado_por_rechazo; + raw.status_operativo = raw.estado_operativo_previo ?? ""; + delete raw.estado_operativo_previo; + raw.budget_mode = true; + await pool.query("UPDATE scraped_services SET status = 'pending', raw_data = $1 WHERE id = $2", [JSON.stringify(raw), exp.id]); + await pool.query( + "INSERT INTO scraped_service_logs (scraped_id, user_name, action, details) VALUES ($1, $2, $3, $4)", + [exp.id, origen, "Presupuesto Aceptado", `El presupuesto PRE-${budgetId} se ha aceptado tras haberse rechazado. Expediente reabierto.`] + ).catch(() => {}); + console.log(`♻️ [PRESUPUESTOS] PRE-${budgetId} aceptado → expediente ${exp.id} reabierto`); + } + } catch (e) { + console.error("⚠️ Error sincronizando expediente del presupuesto:", e.message); + } +} + // ========================================== // ✍️ 5. RUTA PARA ACEPTAR/RECHAZAR Y FIRMAR PRESUPUESTOS // ========================================== @@ -6531,6 +6586,8 @@ app.post("/public/portal/:token/budget/:id/respond", async (req, res) => { "UPDATE budgets SET status = $1, signature = $2 WHERE id = $3 AND owner_id = $4", [newStatus, signature || null, id, ownerId] ); + // 🗄️ Rechazado → archivar su expediente PRE-xxx. Aceptado → reabrirlo si se había archivado por rechazo. + await sincronizarExpedientePresupuesto(id, ownerId, newStatus, "Cliente (portal)"); const ownerData = await pool.query("SELECT phone FROM users WHERE id = $1", [ownerId]); const bQ = await pool.query("SELECT client_name, total FROM budgets WHERE id = $1", [id]);