From 490e240aef36ad572e7f891327022c13338e71e1 Mon Sep 17 00:00:00 2001 From: marsalva Date: Sat, 28 Feb 2026 21:34:18 +0000 Subject: [PATCH] Actualizar server.js --- server.js | 41 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/server.js b/server.js index f37252c..72ed178 100644 --- a/server.js +++ b/server.js @@ -1149,8 +1149,47 @@ app.put('/providers/scraped/:id', authMiddleware, async (req, res) => { return res.json({ ok: true }); } + // ESCUDO ANTI-ARCHIVO Y LOG AUTOMÁTICO if (status === 'archived') { - await pool.query(`UPDATE scraped_services SET status = 'archived', automation_status = 'manual' WHERE id = $2 AND owner_id = $3`, [id, req.user.accountId]); + const checkQ = await pool.query(` + SELECT raw_data, assigned_to, + (SELECT is_final FROM service_statuses WHERE id::text = raw_data->>'status_operativo') as is_final + FROM scraped_services WHERE id = $1 AND owner_id = $2 + `, [id, req.user.accountId]); + + if (checkQ.rowCount > 0) { + const row = checkQ.rows[0]; + const isFinal = row.is_final === true; + const hasWorker = row.assigned_to !== null; + let raw = row.raw_data || {}; + + // SI tiene trabajador asignado Y NO está en un estado final operativo (Finalizado/Anulado) + if (hasWorker && !isFinal) { + + // Solo guardamos el aviso si no lo habíamos guardado ya antes (para no inundar el log) + if (!raw.cerrado_proveedor) { + raw.cerrado_proveedor = true; + await pool.query(`UPDATE scraped_services SET raw_data = $1 WHERE id = $2 AND owner_id = $3`, [JSON.stringify(raw), id, req.user.accountId]); + + // GUARDAMOS EN EL LOG (Trazabilidad) + await pool.query( + "INSERT INTO scraped_service_logs (scraped_id, user_name, action, details) VALUES ($1, $2, $3, $4)", + [id, 'Sistema (Robot)', 'Intento de Cierre', 'La compañía ha cerrado el aviso en su portal, pero se mantiene vivo en IntegraRepara hasta que el técnico lo finalice.'] + ); + } + return res.json({ ok: true, note: "Protegido de archivo automático" }); + } + } + + // Si no tiene trabajador, o el técnico YA lo había finalizado, lo archivamos sin problema + await pool.query(`UPDATE scraped_services SET status = 'archived', automation_status = 'manual' WHERE id = $1 AND owner_id = $2`, [id, req.user.accountId]); + + // GUARDAMOS EN EL LOG + await pool.query( + "INSERT INTO scraped_service_logs (scraped_id, user_name, action, details) VALUES ($1, $2, $3, $4)", + [id, 'Sistema', 'Archivado', 'El expediente se ha cerrado definitivamente y movido al histórico.'] + ); + return res.json({ ok: true }); }