diff --git a/server.js b/server.js index 96a7768..ba81824 100644 --- a/server.js +++ b/server.js @@ -3,7 +3,7 @@ import cors from "cors"; import bcrypt from "bcryptjs"; import jwt from "jsonwebtoken"; import pg from "pg"; -import crypto from "crypto"; // <--- AÑADE ESTA LÍNEA EXACTAMENTE ASÍ +import crypto from "crypto"; // <--- IMPORTACIÓN CORREGIDA const { Pool } = pg; const app = express(); @@ -319,16 +319,54 @@ async function ensureInstance(instanceName) { return { baseUrl, headers }; } -// RUTAS AUTH +// ========================================== +// 🚀 RUTAS PÚBLICAS (MÓVIL OPERARIO) +// ========================================== + +app.get("/public/assignment/:token", async (req, res) => { + try { + const { token } = req.params; + const q = await pool.query(` + SELECT ap.*, s.raw_data, u.full_name as worker_name + FROM assignment_pings ap + JOIN scraped_services s ON ap.scraped_id = s.id + JOIN users u ON ap.user_id = u.id + WHERE ap.token = $1 AND ap.status = 'pending' AND ap.expires_at > NOW() + `, [token]); + if (q.rowCount === 0) return res.status(404).json({ ok: false, error: "Enlace caducado" }); + res.json({ ok: true, service: q.rows[0].raw_data, worker: q.rows[0].worker_name }); + } catch (e) { res.status(500).json({ ok: false }); } +}); + +app.post("/public/assignment/respond", async (req, res) => { + const client = await pool.connect(); + try { + const { token, action } = req.body; + await client.query('BEGIN'); + const q = await client.query("SELECT * FROM assignment_pings WHERE token = $1 AND status = 'pending' AND expires_at > NOW()", [token]); + if (q.rowCount === 0) throw new Error("Acción caducada"); + const ping = q.rows[0]; + if (action === 'accept') { + await client.query("UPDATE assignment_pings SET status = 'accepted' WHERE id = $1", [ping.id]); + await client.query("UPDATE scraped_services SET status = 'imported', automation_status = 'completed' WHERE id = $1", [ping.scraped_id]); + } else { + await client.query("UPDATE assignment_pings SET status = 'rejected', expires_at = NOW() WHERE id = $1", [ping.id]); + } + await client.query('COMMIT'); + res.json({ ok: true }); + } catch (e) { await client.query('ROLLBACK'); res.status(400).json({ ok: false }); } finally { client.release(); } +}); + +// ========================================== +// 🔐 RUTAS AUTH Y PRIVADAS ( CRM ORIGINAL ) +// ========================================== + app.post("/auth/register", async (req, res) => { const client = await pool.connect(); try { const { fullName, phone, address, dni, email, password } = req.body; const p = normalizePhone(phone); if (!fullName || !p || !email || !password) return res.status(400).json({ ok: false }); const passwordHash = await bcrypt.hash(password, 10); await client.query('BEGIN'); const insert = await client.query("INSERT INTO users (full_name, phone, address, dni, email, password_hash, role, owner_id, plan_tier) VALUES ($1, $2, $3, $4, $5, $6, 'admin', NULL, 'free') RETURNING id", [fullName, p, address, dni, email, passwordHash]); const userId = insert.rows[0].id; const code = genCode6(); const codeHash = await bcrypt.hash(code, 10); const expiresAt = new Date(Date.now() + 10 * 60 * 1000); await client.query("INSERT INTO login_codes (user_id, phone, code_hash, expires_at) VALUES ($1, $2, $3, $4)", [userId, p, codeHash, expiresAt]); await sendWhatsAppCode(p, code); await client.query('COMMIT'); res.json({ ok: true, phone: p }); } catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false }); } finally { client.release(); } }); app.post("/auth/verify", async (req, res) => { try { const { phone, code } = req.body; const p = normalizePhone(phone); const q = await pool.query(`SELECT lc.*, u.id as uid, u.email, u.role, u.owner_id FROM login_codes lc JOIN users u ON lc.user_id = u.id WHERE lc.phone=$1 AND lc.consumed_at IS NULL AND lc.expires_at > NOW() ORDER BY lc.created_at DESC LIMIT 1`, [p]); if (q.rowCount === 0) return res.status(400).json({ ok: false }); const row = q.rows[0]; if (!(await bcrypt.compare(String(code), row.code_hash))) return res.status(400).json({ ok: false }); await pool.query("UPDATE login_codes SET consumed_at=NOW() WHERE id=$1", [row.id]); await pool.query("UPDATE users SET is_verified=TRUE WHERE id=$1", [row.uid]); res.json({ ok: true, token: signToken({ id: row.uid, email: row.email, phone: p, role: row.role, owner_id: row.owner_id }) }); } catch (e) { res.status(500).json({ ok: false }); } }); app.post("/auth/login", async (req, res) => { try { const { email, password } = req.body; const q = await pool.query("SELECT * FROM users WHERE email=$1", [email]); if (q.rowCount === 0) return res.status(401).json({ ok: false }); let user = null; for (const u of q.rows) { if (await bcrypt.compare(password, u.password_hash)) { user = u; break; } } if (!user) return res.status(401).json({ ok: false }); res.json({ ok: true, token: signToken(user) }); } catch(e) { res.status(500).json({ ok: false }); } }); -// ========================================== -// 🚀 GESTIÓN WHATSAPP (CON RESTRICCIÓN DE PLAN) -// ========================================== app.get("/whatsapp/status", authMiddleware, (req, res, next) => requirePlan(req, res, next, 'whatsapp_enabled'), async (req, res) => { try { const instanceName = `cliente_${req.user.accountId}`; @@ -346,9 +384,6 @@ app.get("/whatsapp/status", authMiddleware, (req, res, next) => requirePlan(req, } catch (e) { res.status(500).json({ ok: false, error: e.message }); } }); -// ========================================== -// 🤖 GESTIÓN DE PROVEEDORES Y ROBOTS -// ========================================== app.get("/providers/credentials", authMiddleware, async (req, res) => { try { const q = await pool.query("SELECT provider, username, last_sync, status FROM provider_credentials WHERE owner_id=$1", [req.user.accountId]); @@ -382,7 +417,6 @@ app.get("/providers/scraped", authMiddleware, async (req, res) => { } }); -// RUTA AUTOMATIZAR (INICIAR RUEDA) app.post("/providers/automate/:id", authMiddleware, async (req, res) => { try { const { id } = req.params; @@ -403,7 +437,7 @@ app.post("/providers/automate/:id", authMiddleware, async (req, res) => { await pool.query("UPDATE scraped_services SET automation_status = 'in_progress' WHERE id = $1", [id]); const worker = workersQ.rows[Math.floor(Math.random() * workersQ.rows.length)]; - const token = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); + const token = crypto.randomBytes(16).toString('hex'); const expiresAt = new Date(Date.now() + 5 * 60 * 1000); await pool.query(`INSERT INTO assignment_pings (scraped_id, user_id, token, expires_at) VALUES ($1, $2, $3, $4)`, [id, worker.id, token, expiresAt]); @@ -415,54 +449,6 @@ app.post("/providers/automate/:id", authMiddleware, async (req, res) => { } catch (e) { res.status(500).json({ ok: false, error: e.message }); } }); -// Endpoint público para aceptar.html -// 1. Endpoint para que el móvil del operario vea los datos del servicio -app.get("/public/assignment/:token", async (req, res) => { - try { - const { token } = req.params; - const q = await pool.query(` - SELECT ap.*, s.raw_data, u.full_name as worker_name - FROM assignment_pings ap - JOIN scraped_services s ON ap.scraped_id = s.id - JOIN users u ON ap.user_id = u.id - WHERE ap.token = $1 AND ap.status = 'pending' AND ap.expires_at > NOW() - `, [token]); - - if (q.rowCount === 0) return res.status(404).json({ ok: false, error: "Enlace caducado o ya aceptado" }); - - res.json({ ok: true, service: q.rows[0].raw_data, worker: q.rows[0].worker_name }); - } catch (e) { res.status(500).json({ ok: false }); } -}); - -// 2. Endpoint para procesar el botón de "Aceptar" del móvil -app.post("/public/assignment/respond", async (req, res) => { - const client = await pool.connect(); - try { - const { token, action } = req.body; - await client.query('BEGIN'); - - const q = await client.query("SELECT * FROM assignment_pings WHERE token = $1 AND status = 'pending' AND expires_at > NOW()", [token]); - if (q.rowCount === 0) throw new Error("Turno expirado o ya procesado"); - - const ping = q.rows[0]; - - if (action === 'accept') { - // Marcamos como aceptado - await client.query("UPDATE assignment_pings SET status = 'accepted' WHERE id = $1", [ping.id]); - // Importante: Marcamos el original como completado para que desaparezca de la cola - await client.query("UPDATE scraped_services SET status = 'imported', automation_status = 'completed' WHERE id = $1", [ping.scraped_id]); - - // Aquí llamarías a tu función de crear servicio oficial (POST /services) - } else { - // Si rechaza, forzamos expiración para que el reloj salte al siguiente - await client.query("UPDATE assignment_pings SET status = 'rejected', expires_at = NOW() WHERE id = $1", [ping.id]); - } - - await client.query('COMMIT'); - res.json({ ok: true }); - } catch (e) { await client.query('ROLLBACK'); res.status(400).json({ ok: false, error: e.message }); } finally { client.release(); } -}); - app.post("/providers/import/:id", authMiddleware, async (req, res) => { const client = await pool.connect(); try { @@ -515,7 +501,6 @@ app.put('/providers/scraped/:id', authMiddleware, async (req, res) => { } catch (error) { res.status(500).json({ error: 'Error' }); } }); -// MAPEADOR Y DISCOVERY app.get("/discovery/keys/:provider", authMiddleware, async (req, res) => { try { const { provider } = req.params; @@ -549,7 +534,6 @@ app.post("/discovery/save", authMiddleware, async (req, res) => { } catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false }); } finally { client.release(); } }); -// CLIENTES app.get("/clients", authMiddleware, async (req, res) => { try { const { search } = req.query; @@ -589,12 +573,10 @@ app.put("/clients/:id", authMiddleware, async (req, res) => { } catch (e) { res.status(500).json({ ok: false }); } }); -// ESTADOS app.get("/statuses", authMiddleware, async (req, res) => { try { let q = await pool.query("SELECT * FROM service_statuses WHERE owner_id=$1 ORDER BY id ASC", [req.user.accountId]); if (q.rowCount === 0) { const defaults = [{name:'Pendiente',c:'gray',d:true,f:false},{name:'En Proceso',c:'blue',d:false,f:false},{name:'Terminado',c:'green',d:false,f:true},{name:'Cancelado',c:'red',d:false,f:true}]; for (const s of defaults) await pool.query("INSERT INTO service_statuses (owner_id,name,color,is_default,is_final) VALUES ($1,$2,$3,$4,$5)", [req.user.accountId,s.name,s.c,s.d,s.f]); q = await pool.query("SELECT * FROM service_statuses WHERE owner_id=$1 ORDER BY id ASC", [req.user.accountId]); } res.json({ ok: true, statuses: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } }); app.post("/statuses", authMiddleware, async (req, res) => { try { const { name, color } = req.body; await pool.query("INSERT INTO service_statuses (owner_id, name, color) VALUES ($1, $2, $3)", [req.user.accountId, name, color || 'gray']); res.json({ ok: true }); } catch(e) { res.status(500).json({ ok: false }); } }); app.delete("/statuses/:id", authMiddleware, async (req, res) => { const client = await pool.connect(); try { const statusId = req.params.id; const check = await client.query("SELECT COUNT(*) FROM services WHERE status_id = $1 AND owner_id = $2", [statusId, req.user.accountId]); if (parseInt(check.rows[0].count) > 0) return res.status(400).json({ ok: false, error: "En uso" }); await client.query("DELETE FROM service_statuses WHERE id=$1 AND owner_id=$2", [statusId, req.user.accountId]); res.json({ ok: true }); } catch(e) { res.status(500).json({ ok: false }); } finally { client.release(); } }); -// EMPRESAS, ZONAS Y OPERARIOS app.get("/clients/search", authMiddleware, async (req, res) => { try { const { phone } = req.query; const p = normalizePhone(phone); if(!p) return res.json({ok:true,client:null}); const q = await pool.query("SELECT * FROM clients WHERE phone=$1 AND owner_id=$2 LIMIT 1", [p, req.user.accountId]); res.json({ ok: true, client: q.rows[0] || null }); } catch (e) { res.status(500).json({ ok: false }); } }); app.get("/companies", authMiddleware, async (req, res) => { try { const q = await pool.query("SELECT * FROM companies WHERE owner_id=$1 ORDER BY name ASC", [req.user.accountId]); res.json({ ok: true, companies: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } }); app.post("/companies", authMiddleware, async (req, res) => { try { const { name } = req.body; await pool.query("INSERT INTO companies (name, owner_id) VALUES ($1, $2)", [name, req.user.accountId]); res.json({ ok: true }); } catch (e) { res.status(500).json({ ok: false }); } }); @@ -606,7 +588,6 @@ app.delete("/zones/:id", authMiddleware, async (req, res) => { try { await pool. app.get("/zones/:id/operators", authMiddleware, async (req, res) => { try { const q = await pool.query("SELECT user_id FROM user_zones WHERE zone_id=$1", [req.params.id]); res.json({ ok: true, assignedIds: q.rows.map(r=>r.user_id) }); } catch (e) { res.status(500).json({ ok: false }); } }); app.post("/zones/:id/assign", authMiddleware, async (req, res) => { const client = await pool.connect(); try { const { operator_ids } = req.body; await client.query('BEGIN'); await client.query("DELETE FROM user_zones WHERE zone_id=$1", [req.params.id]); if(operator_ids) for(const uid of operator_ids) await client.query("INSERT INTO user_zones (user_id, zone_id) VALUES ($1, $2)", [uid, req.params.id]); await client.query('COMMIT'); res.json({ok:true}); } catch(e){ await client.query('ROLLBACK'); res.status(500).json({ok:false}); } finally { client.release(); } }); -// GEOGRAFÍA Y USUARIOS ADMIN app.get("/api/geo/municipios/:provincia", authMiddleware, async (req, res) => { try { let { provincia } = req.params; const provClean = provincia.toUpperCase().normalize("NFD").replace(/[\u0300-\u036f]/g, ""); const q = await pool.query("SELECT municipio, codigo_postal FROM master_geo_es WHERE provincia = $1 ORDER BY municipio ASC", [provClean]); res.json({ ok: true, municipios: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } }); app.patch("/admin/users/:id/status", authMiddleware, async (req, res) => { try { const { status } = req.body; await pool.query("UPDATE users SET status = $1 WHERE id = $2 AND owner_id = $3", [status, req.params.id, req.user.accountId]); res.json({ ok: true }); } catch (e) { res.status(500).json({ ok: false }); } }); app.get("/admin/users", authMiddleware, async (req, res) => { try { const q = await pool.query(`SELECT u.id, u.full_name, u.email, u.phone, u.role, u.zones, u.status, COALESCE(json_agg(g.id) FILTER (WHERE g.id IS NOT NULL), '[]') as guilds FROM users u LEFT JOIN user_guilds ug ON u.id=ug.user_id LEFT JOIN guilds g ON ug.guild_id=g.id WHERE u.owner_id=$1 GROUP BY u.id ORDER BY u.id DESC`, [req.user.accountId]); res.json({ ok: true, users: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } }); @@ -614,14 +595,12 @@ app.post("/admin/users", authMiddleware, async (req, res) => { const client = aw app.put("/admin/users/:id", authMiddleware, async (req, res) => { const client = await pool.connect(); try { const userId = req.params.id; const { fullName, email, phone, role, guilds, password, zones } = req.body; const p = normalizePhone(phone); await client.query('BEGIN'); if(password) { const hash = await bcrypt.hash(password, 10); await client.query("UPDATE users SET full_name=$1, email=$2, phone=$3, role=$4, password_hash=$5, zones=$6 WHERE id=$7", [fullName, email, p, role, hash, JSON.stringify(zones || []), userId]); } else { await client.query("UPDATE users SET full_name=$1, email=$2, phone=$3, role=$4, zones=$5 WHERE id=$6", [fullName, email, p, role, JSON.stringify(zones || []), userId]); } if (guilds && Array.isArray(guilds)) { await client.query("DELETE FROM user_guilds WHERE user_id=$1", [userId]); for (const gid of guilds) await client.query("INSERT INTO user_guilds (user_id, guild_id) VALUES ($1, $2)", [userId, gid]); } await client.query('COMMIT'); res.json({ ok: true }); } catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false }); } finally { client.release(); } }); app.delete("/admin/users/:id", authMiddleware, async (req, res) => { try { await pool.query("DELETE FROM users WHERE id=$1 AND owner_id=$2", [req.params.id, req.user.accountId]); res.json({ ok: true }); } catch (e) { res.status(500).json({ ok: false }); } }); -// CONFIGURACIÓN EMPRESA Y GREMIOS (EXTRA) app.get("/config/company", authMiddleware, async (req, res) => { try { const q = await pool.query("SELECT company_slug, full_name, plan_tier FROM users WHERE id=$1", [req.user.accountId]); res.json({ ok: true, slug: q.rows[0]?.company_slug, name: q.rows[0]?.full_name, plan: q.rows[0]?.plan_tier }); } catch (e) { res.status(500).json({ ok: false }); } }); app.post("/config/company", authMiddleware, async (req, res) => { const client = await pool.connect(); try { const { slug } = req.body; if (!slug || slug.length < 3) return res.status(400).json({ ok: false, error: "Mínimo 3 caracteres" }); const cleanSlug = slug.toLowerCase().replace(/[^a-z0-9-]/g, ""); if (cleanSlug !== slug) return res.status(400).json({ ok: false, error: "Carácteres inválidos" }); const check = await client.query("SELECT id FROM users WHERE company_slug=$1 AND id != $2", [cleanSlug, req.user.accountId]); if (check.rowCount > 0) return res.status(400).json({ ok: false, error: "Nombre en uso" }); await client.query("UPDATE users SET company_slug=$1 WHERE id=$2", [cleanSlug, req.user.accountId]); res.json({ ok: true, fullUrl: `https://${cleanSlug}.integrarepara.es` }); } catch (e) { res.status(500).json({ ok: false }); } finally { client.release(); } }); app.get("/guilds", authMiddleware, async (req, res) => { try { const q = await pool.query("SELECT * FROM guilds WHERE owner_id=$1 ORDER BY name ASC", [req.user.accountId]); res.json({ ok: true, guilds: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } }); app.post("/guilds", authMiddleware, async (req, res) => { try { const { name } = req.body; await pool.query("INSERT INTO guilds (name, owner_id) VALUES ($1, $2)", [name, req.user.accountId]); res.json({ ok: true }); } catch (e) { res.status(500).json({ ok: false }); } }); app.delete("/guilds/:id", authMiddleware, async (req, res) => { try { await pool.query("DELETE FROM guilds WHERE id=$1 AND owner_id=$2", [req.params.id, req.user.accountId]); res.json({ ok: true }); } catch (e) { res.status(500).json({ ok: false }); } }); -// GESTIÓN DE SERVICIOS OFICIALES app.get("/services", authMiddleware, async (req, res) => { try { const q = await pool.query(`SELECT s.*, st.name as status_name, st.color as status_color, c.name as company_name, g.name as guild_name, u.full_name as assigned_name FROM services s LEFT JOIN service_statuses st ON s.status_id = st.id LEFT JOIN companies c ON s.company_id = c.id LEFT JOIN guilds g ON s.guild_id = g.id LEFT JOIN users u ON s.assigned_to = u.id WHERE s.owner_id=$1 ORDER BY s.created_at DESC`, [req.user.accountId]); res.json({ ok: true, services: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } }); app.get("/services/:id", authMiddleware, async (req, res) => { try { const q = await pool.query(`SELECT * FROM services WHERE id=$1 AND owner_id=$2`, [req.params.id, req.user.accountId]); res.json({ ok: true, service: q.rows[0] }); } catch (e) { res.status(500).json({ ok: false }); } }); app.get("/services/:id/logs", authMiddleware, async (req, res) => { try { const q = await pool.query(`SELECT l.*, u.full_name as user_name, s2.name as new_status, s2.color as new_color FROM service_logs l LEFT JOIN users u ON l.user_id=u.id LEFT JOIN service_statuses s2 ON l.new_status_id=s2.id WHERE l.service_id=$1 ORDER BY l.created_at DESC`, [req.params.id]); res.json({ ok: true, logs: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } }); @@ -656,7 +635,7 @@ setInterval(async () => { if (nextWorkerQ.rowCount > 0) { const nextW = nextWorkerQ.rows[0]; - const newToken = Math.random().toString(36).substring(2, 15); + const newToken = crypto.randomBytes(16).toString('hex'); const expiresAt = new Date(Date.now() + 5 * 60 * 1000); await pool.query(`INSERT INTO assignment_pings (scraped_id, user_id, token, expires_at) VALUES ($1, $2, $3, $4)`, [ping.scraped_id, nextW.id, newToken, expiresAt]); await sendWhatsAppAuto(nextW.phone, `🛠️ *SERVICIO DISPONIBLE*\nEl anterior compañero no respondió. Es tu turno:\n🔗 https://integrarepara.es/aceptar.html?t=${newToken}`);