From a407061a22cdc782e2cb80d6be739a1a9614d70c Mon Sep 17 00:00:00 2001 From: marsalva Date: Sun, 15 Feb 2026 19:24:32 +0000 Subject: [PATCH] Actualizar server.js --- server.js | 268 +++++++++++++++++++++--------------------------------- 1 file changed, 104 insertions(+), 164 deletions(-) diff --git a/server.js b/server.js index 9b25698..92f7dac 100644 --- a/server.js +++ b/server.js @@ -21,7 +21,7 @@ const { // --- DIAGNÓSTICO DE INICIO --- console.log("------------------------------------------------"); -console.log("🚀 VERSIÓN NUEVA CARGADA - CON MAPEADOR REAL"); +console.log("🚀 VERSIÓN COMPLETA - CON AUTOMATISMOS REALES"); console.log("------------------------------------------------"); if (!DATABASE_URL) console.error("❌ FALTA: DATABASE_URL"); if (!JWT_SECRET) console.error("❌ FALTA: JWT_SECRET"); @@ -172,11 +172,12 @@ async function autoUpdateDB() { service_ref TEXT NOT NULL, raw_data JSONB, status TEXT DEFAULT 'pending', + automation_status TEXT DEFAULT 'manual', created_at TIMESTAMP DEFAULT NOW(), UNIQUE(owner_id, provider, service_ref) ); - -- 🗺️ TABLA DE MAPEO DE VARIABLES (NUEVO) + -- 🗺️ TABLA DE MAPEO DE VARIABLES CREATE TABLE IF NOT EXISTS variable_mappings ( id SERIAL PRIMARY KEY, owner_id INT REFERENCES users(id) ON DELETE CASCADE, @@ -226,18 +227,17 @@ async function autoUpdateDB() { created_at TIMESTAMP DEFAULT NOW() ); - // Dentro de autoUpdateDB en server.js -await client.query(` - CREATE TABLE IF NOT EXISTS assignment_pings ( - id SERIAL PRIMARY KEY, - scraped_id INT NOT NULL, -- Aseguramos que el nombre sea exacto - user_id INT REFERENCES users(id) ON DELETE CASCADE, - token TEXT UNIQUE NOT NULL, - status TEXT DEFAULT 'pending', - expires_at TIMESTAMP NOT NULL, - created_at TIMESTAMP DEFAULT NOW() - ); - + -- TABLA PARA ASIGNACIÓN AUTOMÁTICA + CREATE TABLE IF NOT EXISTS assignment_pings ( + id SERIAL PRIMARY KEY, + scraped_id INT NOT NULL, + user_id INT REFERENCES users(id) ON DELETE CASCADE, + token TEXT UNIQUE NOT NULL, + status TEXT DEFAULT 'pending', + expires_at TIMESTAMP NOT NULL, + created_at TIMESTAMP DEFAULT NOW() + ); + `); // PARCHE DE ACTUALIZACIÓN await client.query(` @@ -255,7 +255,6 @@ await client.query(` IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='provider_data') THEN ALTER TABLE services ADD COLUMN provider_data JSONB DEFAULT '{}'; END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='import_source') THEN ALTER TABLE services ADD COLUMN import_source TEXT; END IF; - -- NUEVO: Estado de automatismo [AÑADIDO] IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='scraped_services' AND column_name='automation_status') THEN ALTER TABLE scraped_services ADD COLUMN automation_status TEXT DEFAULT 'manual'; END IF; BEGIN ALTER TABLE users DROP CONSTRAINT IF EXISTS users_phone_key; EXCEPTION WHEN OTHERS THEN NULL; END; @@ -295,7 +294,6 @@ async function sendWhatsAppCode(phone, code) { } catch (e) { console.error("Error envío WA:", e.message); } } -// NUEVA FUNCIÓN PARA MENSAJES DE AUTOMATISMOS [AÑADIDO] async function sendWhatsAppAuto(phone, text) { if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY || !EVOLUTION_INSTANCE) return; try { @@ -383,39 +381,94 @@ 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; + const { guild_id, cp } = req.body; + + if (!guild_id || !cp) return res.status(400).json({ ok: false, error: "Faltan datos (Gremio o CP)" }); + + const workersQ = await pool.query(` + 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::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" }); + + 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 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]); + + const link = `https://integrarepara.es/aceptar.html?t=${token}`; + await sendWhatsAppAuto(worker.phone, `🛠️ *NUEVO SERVICIO*\nCP: ${cp}\n🔗 ${link}`); + + res.json({ ok: true, message: "Automatismo iniciado con " + worker.full_name }); + } catch (e) { res.status(500).json({ ok: false, error: e.message }); } +}); + +// Endpoint público para aceptar.html +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 }); } +}); + +// Endpoint público para respuesta +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]); + // (La lógica de traspaso real a 'services' iría aquí, reutilizando handleFinalImport) + } 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(); } +}); + app.post("/providers/import/:id", authMiddleware, async (req, res) => { const client = await pool.connect(); try { const scrapedId = req.params.id; await client.query('BEGIN'); - - const scrapedQ = await client.query( - "SELECT * FROM scraped_services WHERE id=$1 AND owner_id=$2", - [scrapedId, req.user.accountId] - ); - if (scrapedQ.rowCount === 0) return res.status(404).json({ ok: false, error: "No encontrado" }); - + const scrapedQ = await client.query("SELECT * FROM scraped_services WHERE id=$1 AND owner_id=$2", [scrapedId, req.user.accountId]); + if (scrapedQ.rowCount === 0) return res.status(404).json({ ok: false }); const raw = scrapedQ.rows[0].raw_data; const provider = scrapedQ.rows[0].provider; const ref = scrapedQ.rows[0].service_ref; - - const mappingQ = await client.query( - "SELECT original_key, target_key FROM variable_mappings WHERE owner_id=$1 AND provider=$2 AND is_ignored=FALSE", - [req.user.accountId, provider] - ); - + const mappingQ = await client.query("SELECT original_key, target_key FROM variable_mappings WHERE owner_id=$1 AND provider=$2 AND is_ignored=FALSE", [req.user.accountId, provider]); const cleanData = {}; - mappingQ.rows.forEach(m => { - if (raw[m.original_key]) { - cleanData[m.target_key] = raw[m.original_key]; - } - }); - + mappingQ.rows.forEach(m => { if (raw[m.original_key]) cleanData[m.target_key] = raw[m.original_key]; }); const phone = cleanData.phone || cleanData.phone2 || ""; const name = cleanData.clientName || "Cliente Importado"; const address = cleanData.address || ""; const cpExpediente = cleanData.cp || ""; - const phoneClean = normalizePhone(phone); let clientId = null; if (phoneClean) { @@ -423,119 +476,22 @@ app.post("/providers/import/:id", authMiddleware, async (req, res) => { if (cCheck.rowCount > 0) clientId = cCheck.rows[0].id; } if (!clientId) { - const newC = await client.query( - "INSERT INTO clients (owner_id, full_name, phone, addresses) VALUES ($1, $2, $3, $4) RETURNING id", - [req.user.accountId, name, phoneClean, JSON.stringify([address])] - ); + const newC = await client.query("INSERT INTO clients (owner_id, full_name, phone, addresses) VALUES ($1, $2, $3, $4) RETURNING id", [req.user.accountId, name, phoneClean, JSON.stringify([address])]); clientId = newC.rows[0].id; } - let autoAssignedTo = null; if (cpExpediente) { - const workerQ = await client.query(` - SELECT id FROM users - WHERE owner_id = $1 - AND role = 'operario' - AND status = 'active' - AND zones @> $2::jsonb - LIMIT 1 - `, [req.user.accountId, JSON.stringify([{ cps: cpExpediente.toString() }])]); - - if (workerQ.rowCount > 0) { - autoAssignedTo = workerQ.rows[0].id; - } + const workerQ = await client.query(`SELECT id FROM users WHERE owner_id = $1 AND role = 'operario' AND status = 'active' AND zones @> $2::jsonb LIMIT 1`, [req.user.accountId, JSON.stringify([{ cps: cpExpediente.toString() }])]); + if (workerQ.rowCount > 0) autoAssignedTo = workerQ.rows[0].id; } - const statusQ = await client.query("SELECT id FROM service_statuses WHERE owner_id=$1 AND is_default=TRUE LIMIT 1", [req.user.accountId]); - - const insertSvc = await client.query(` - INSERT INTO services ( - owner_id, client_id, status_id, company_ref, title, description, address, contact_phone, contact_name, - is_company, import_source, provider_data, scheduled_date, assigned_to - ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14) RETURNING id - `, [ - req.user.accountId, - clientId, - statusQ.rows[0]?.id, - ref, - `${provider.toUpperCase()} - ${ref}`, - cleanData.descripcion || "Sin descripción", - address, - phoneClean, - name, - true, - provider, - JSON.stringify(cleanData), - cleanData.fecha_cita || 'NOW()', - autoAssignedTo - ]); - + const insertSvc = await client.query(`INSERT INTO services (owner_id, client_id, status_id, company_ref, title, description, address, contact_phone, contact_name, is_company, import_source, provider_data, scheduled_date, assigned_to) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14) RETURNING id`, [req.user.accountId, clientId, statusQ.rows[0]?.id, ref, `${provider.toUpperCase()} - ${ref}`, cleanData.descripcion || "Sin descripción", address, phoneClean, name, true, provider, JSON.stringify(cleanData), cleanData.fecha_cita || 'NOW()', autoAssignedTo]); await client.query("UPDATE scraped_services SET status='imported' WHERE id=$1", [scrapedId]); - await client.query('COMMIT'); res.json({ ok: true, serviceId: insertSvc.rows[0].id, assigned: !!autoAssignedTo }); - } catch (e) { - await client.query('ROLLBACK'); - console.error(e); - res.status(500).json({ ok: false, error: e.message }); - } finally { - client.release(); - } + } catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false }); } finally { client.release(); } }); -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 - 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::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 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) + 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]); - - // 5. Envío de WhatsApp - const link = `https://tuweb.com/aceptar.html?t=${token}`; - 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 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 app.put('/providers/scraped/:id', authMiddleware, async (req, res) => { const { id } = req.params; const { name, phone, address, cp, description, guild_id, assigned_to, internal_notes, client_notes, is_urgent } = req.body; @@ -548,7 +504,7 @@ app.put('/providers/scraped/:id', authMiddleware, async (req, res) => { } catch (error) { res.status(500).json({ error: 'Error' }); } }); -// MAPEADOR +// MAPEADOR Y DISCOVERY app.get("/discovery/keys/:provider", authMiddleware, async (req, res) => { try { const { provider } = req.params; @@ -627,7 +583,7 @@ app.get("/statuses", authMiddleware, async (req, res) => { try { let q = await p 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(); } }); -// RESTO +// 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 }); } }); @@ -639,38 +595,22 @@ 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(); } }); -// GEO -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 }); } -}); - -// STATUS USUARIO -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 }); } -}); - +// 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 }); } }); app.post("/admin/users", authMiddleware, async (req, res) => { const client = await pool.connect(); try { const { fullName, email, password, role, guilds, phone, zones } = req.body; if (!email || !password || !fullName || !phone) return res.status(400).json({ ok: false }); const p = normalizePhone(phone); const hash = await bcrypt.hash(password, 10); const check = await client.query("SELECT id FROM users WHERE (phone=$1 OR email=$2) AND owner_id=$3", [p, email, req.user.accountId]); if (check.rowCount > 0) return res.status(400).json({ ok: false, error: "Duplicado" }); await client.query('BEGIN'); const insert = await client.query("INSERT INTO users (full_name, email, password_hash, role, phone, is_verified, owner_id, zones, status) VALUES ($1, $2, $3, $4, $5, TRUE, $6, $7, 'active') RETURNING id", [fullName, email, hash, role || 'operario', p, req.user.accountId, JSON.stringify(zones || [])]); const uid = insert.rows[0].id; if (guilds) for (const gid of guilds) await client.query("INSERT INTO user_guilds (user_id, guild_id) VALUES ($1, $2)", [uid, 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.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 }); } }); -// CONFIG +// 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(); } }); - -// SERVICIOS 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 }); } }); @@ -680,7 +620,7 @@ app.put("/services/:id", authMiddleware, async (req, res) => { const client = aw app.delete("/services/:id", authMiddleware, async (req, res) => { try { await pool.query("DELETE FROM services 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 }); } }); // ========================================== -// 🕒 EL RELOJ DEL SISTEMA (Ejecutar cada minuto) [AÑADIDO] +// 🕒 EL RELOJ DEL SISTEMA (Ejecutar cada minuto) // ========================================== setInterval(async () => { try { @@ -708,7 +648,7 @@ setInterval(async () => { const newToken = Math.random().toString(36).substring(2, 15); 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://tuweb.com/aceptar.html?t=${newToken}`); + await sendWhatsAppAuto(nextW.phone, `🛠️ *SERVICIO DISPONIBLE*\nEl anterior compañero no respondió. Es tu turno:\n🔗 https://integrarepara.es/aceptar.html?t=${newToken}`); } else { await pool.query("UPDATE scraped_services SET automation_status = 'failed' WHERE id = $1", [ping.scraped_id]); }