From 670b9ebc23df66ff1de39065020414b7c590c02c Mon Sep 17 00:00:00 2001 From: marsalva Date: Sun, 15 Feb 2026 19:07:06 +0000 Subject: [PATCH] Actualizar server.js --- server.js | 47 ++++++++++++++++++++++++++++++++++++----------- 1 file changed, 36 insertions(+), 11 deletions(-) diff --git a/server.js b/server.js index 34eb82b..ff99278 100644 --- a/server.js +++ b/server.js @@ -482,31 +482,56 @@ app.post("/providers/import/:id", authMiddleware, async (req, res) => { } }); -// NUEVA RUTA PARA INICIAR AUTOMATISMO [AÑADIDO] app.post("/providers/automate/:id", authMiddleware, async (req, res) => { try { const { id } = req.params; const { guild_id, cp } = req.body; + + // 1. Verificación de datos de entrada + if (!guild_id || !cp) { + return res.status(400).json({ ok: false, error: "Faltan datos (Gremio o CP)" }); + } + + // 2. Buscamos operarios: Corregimos la consulta para ser más robusta const workersQ = await pool.query(` - SELECT u.id, u.full_name, u.phone FROM users u + SELECT u.id, u.full_name, u.phone + FROM users u JOIN user_guilds ug ON u.id = ug.user_id - WHERE u.owner_id = $1 AND u.role = 'operario' AND u.status = 'active' - AND ug.guild_id = $2 AND u.zones @> $3::jsonb + WHERE u.owner_id = $1 + AND u.role = 'operario' + AND u.status = 'active' + AND ug.guild_id = $2 + AND u.zones::jsonb @> $3::jsonb `, [req.user.accountId, guild_id, JSON.stringify([{ cps: cp.toString() }])]); - if (workersQ.rowCount === 0) return res.status(404).json({ ok: false, error: "No hay operarios disponibles" }); + if (workersQ.rowCount === 0) { + return res.status(404).json({ ok: false, error: "No hay operarios ACTIVOS que cubran este CP y Gremio" }); + } + // 3. Marcamos el expediente como 'en proceso' await pool.query("UPDATE scraped_services SET automation_status = 'in_progress' WHERE id = $1", [id]); + + // 4. Elegimos uno al azar y generamos token const worker = workersQ.rows[Math.floor(Math.random() * workersQ.rows.length)]; - const token = Math.random().toString(36).substring(2, 15); - const expiresAt = new Date(Date.now() + 5 * 60 * 1000); + const token = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); + const expiresAt = new Date(Date.now() + 5 * 60 * 1000); // 5 minutos - await pool.query(`INSERT INTO assignment_pings (scraped_id, user_id, token, expires_at) VALUES ($1, $2, $3, $4)`, [id, worker.id, token, expiresAt]); + await pool.query(` + INSERT INTO assignment_pings (scraped_id, user_id, token, expires_at) + VALUES ($1, $2, $3, $4) + `, [id, worker.id, token, expiresAt]); + + // 5. Envío de WhatsApp const link = `https://tuweb.com/aceptar.html?t=${token}`; - await sendWhatsAppAuto(worker.phone, `🛠️ *NUEVO SERVICIO*\nCP: ${cp}\n🔗 ${link}`); + const mensaje = `🛠️ *NUEVO SERVICIO DISPONIBLE*\n📍 CP: ${cp}\n📋 Tienes 5 minutos para revisar y aceptar:\n\n🔗 ${link}`; + + await sendWhatsAppAuto(worker.phone, mensaje); - res.json({ ok: true, message: "Automatismo iniciado" }); - } catch (e) { res.status(500).json({ ok: false }); } + res.json({ ok: true, message: "Automatismo iniciado con " + worker.full_name }); + } catch (e) { + console.error("❌ Error en Automate:", e.message); + res.status(500).json({ ok: false, error: "Error interno: " + e.message }); + } }); // RUTA PARA GUARDAR GREMIO Y OPERARIO