Actualizar server.js

This commit is contained in:
2026-02-15 19:07:06 +00:00
parent 71d1648d4d
commit 670b9ebc23

View File

@@ -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) => { app.post("/providers/automate/:id", authMiddleware, async (req, res) => {
try { try {
const { id } = req.params; const { id } = req.params;
const { guild_id, cp } = req.body; 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(` 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 JOIN user_guilds ug ON u.id = ug.user_id
WHERE u.owner_id = $1 AND u.role = 'operario' AND u.status = 'active' WHERE u.owner_id = $1
AND ug.guild_id = $2 AND u.zones @> $3::jsonb 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() }])]); `, [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]); 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 worker = workersQ.rows[Math.floor(Math.random() * workersQ.rows.length)];
const token = Math.random().toString(36).substring(2, 15); 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); 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}`; 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" }); res.json({ ok: true, message: "Automatismo iniciado con " + worker.full_name });
} catch (e) { res.status(500).json({ ok: false }); } } 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 // RUTA PARA GUARDAR GREMIO Y OPERARIO