import express from "express"; import cors from "cors"; import bcrypt from "bcryptjs"; import jwt from "jsonwebtoken"; import pg from "pg"; import crypto from "crypto"; const { Pool } = pg; const app = express(); app.use(cors()); app.use(express.json()); // VARIABLES DE ENTORNO const { DATABASE_URL, JWT_SECRET, EVOLUTION_BASE_URL, EVOLUTION_API_KEY, EVOLUTION_INSTANCE, } = process.env; // --- DIAGNÓSTICO DE INICIO --- console.log("------------------------------------------------"); console.log("🚀 VERSIÓN REFORZADA - CRM + PANEL OPERATIVO"); console.log("------------------------------------------------"); if (!DATABASE_URL || !JWT_SECRET) process.exit(1); const pool = new Pool({ connectionString: DATABASE_URL, ssl: false }); // ========================================== // 💰 CONFIGURACIÓN DE PLANES (SAAS) // ========================================== const PLAN_LIMITS = { 'free': { name: 'Básico Gratuito', whatsapp_enabled: false, templates_enabled: false, automation_enabled: false }, 'standard': { name: 'Estándar', whatsapp_enabled: true, templates_enabled: true, automation_enabled: false }, 'pro': { name: 'Profesional', whatsapp_enabled: true, templates_enabled: true, automation_enabled: true } }; // ========================================== // 🧠 AUTO-ACTUALIZACIÓN DB // ========================================== async function autoUpdateDB() { const client = await pool.connect(); try { console.log("🔄 Verificando estructura DB..."); await client.query(` -- USUARIOS CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, full_name TEXT NOT NULL, phone TEXT NOT NULL, email TEXT NOT NULL, dni TEXT, address TEXT, password_hash TEXT NOT NULL, is_verified BOOLEAN DEFAULT FALSE, owner_id INT, role TEXT DEFAULT 'operario', company_slug TEXT UNIQUE, plan_tier TEXT DEFAULT 'free', subscription_status TEXT DEFAULT 'active', paid_providers_count INT DEFAULT 0, zones JSONB DEFAULT '[]', status TEXT DEFAULT 'active', created_at TIMESTAMP DEFAULT NOW() ); CREATE TABLE IF NOT EXISTS login_codes ( id SERIAL PRIMARY KEY, user_id INT REFERENCES users(id) ON DELETE CASCADE, phone TEXT NOT NULL, code_hash TEXT NOT NULL, purpose TEXT DEFAULT 'register_verify', consumed_at TIMESTAMP, expires_at TIMESTAMP NOT NULL, created_at TIMESTAMP DEFAULT NOW() ); -- CONFIGURACIÓN NEGOCIO CREATE TABLE IF NOT EXISTS guilds ( id SERIAL PRIMARY KEY, owner_id INT REFERENCES users(id) ON DELETE CASCADE, name TEXT NOT NULL, created_at TIMESTAMP DEFAULT NOW() ); CREATE TABLE IF NOT EXISTS user_guilds ( user_id INT REFERENCES users(id) ON DELETE CASCADE, guild_id INT REFERENCES guilds(id) ON DELETE CASCADE, PRIMARY KEY (user_id, guild_id) ); CREATE TABLE IF NOT EXISTS companies ( id SERIAL PRIMARY KEY, owner_id INT REFERENCES users(id) ON DELETE CASCADE, name TEXT NOT NULL, cif TEXT, email TEXT, phone TEXT, address TEXT, created_at TIMESTAMP DEFAULT NOW() ); -- CLIENTES (CRM) CREATE TABLE IF NOT EXISTS clients ( id SERIAL PRIMARY KEY, owner_id INT REFERENCES users(id) ON DELETE CASCADE, full_name TEXT NOT NULL, phone TEXT NOT NULL, email TEXT, addresses JSONB DEFAULT '[]', notes TEXT, created_at TIMESTAMP DEFAULT NOW() ); -- ESTADOS Y PLANTILLAS CREATE TABLE IF NOT EXISTS service_statuses ( id SERIAL PRIMARY KEY, owner_id INT REFERENCES users(id) ON DELETE CASCADE, name TEXT NOT NULL, color TEXT DEFAULT 'gray', is_default BOOLEAN DEFAULT FALSE, is_final BOOLEAN DEFAULT FALSE, created_at TIMESTAMP DEFAULT NOW() ); CREATE TABLE IF NOT EXISTS message_templates ( id SERIAL PRIMARY KEY, owner_id INT REFERENCES users(id) ON DELETE CASCADE, type TEXT NOT NULL, content TEXT, created_at TIMESTAMP DEFAULT NOW(), UNIQUE(owner_id, type) ); -- ZONAS CREATE TABLE IF NOT EXISTS zones ( id SERIAL PRIMARY KEY, name TEXT NOT NULL, owner_id INT, created_at TIMESTAMP DEFAULT NOW() ); CREATE TABLE IF NOT EXISTS user_zones ( user_id INT REFERENCES users(id) ON DELETE CASCADE, zone_id INT REFERENCES zones(id) ON DELETE CASCADE, PRIMARY KEY (user_id, zone_id) ); -- 🤖 ROBOTS / PROVEEDORES CREATE TABLE IF NOT EXISTS provider_credentials ( id SERIAL PRIMARY KEY, owner_id INT REFERENCES users(id) ON DELETE CASCADE, provider TEXT NOT NULL, username TEXT NOT NULL, password_hash TEXT NOT NULL, last_sync TIMESTAMP, status TEXT DEFAULT 'active', UNIQUE(owner_id, provider) ); CREATE TABLE IF NOT EXISTS scraped_services ( id SERIAL PRIMARY KEY, owner_id INT REFERENCES users(id) ON DELETE CASCADE, provider TEXT NOT NULL, 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 CREATE TABLE IF NOT EXISTS variable_mappings ( id SERIAL PRIMARY KEY, owner_id INT REFERENCES users(id) ON DELETE CASCADE, provider TEXT NOT NULL, original_key TEXT NOT NULL, target_key TEXT, is_ignored BOOLEAN DEFAULT FALSE, created_at TIMESTAMP DEFAULT NOW(), UNIQUE(owner_id, provider, original_key) ); -- SERVICIOS (PRINCIPAL) CREATE TABLE IF NOT EXISTS services ( id SERIAL PRIMARY KEY, owner_id INT REFERENCES users(id) ON DELETE CASCADE, client_id INT REFERENCES clients(id) ON DELETE SET NULL, status_id INT REFERENCES service_statuses(id) ON DELETE SET NULL, guild_id INT REFERENCES guilds(id) ON DELETE SET NULL, assigned_to INT REFERENCES users(id) ON DELETE SET NULL, title TEXT, description TEXT, contact_phone TEXT, contact_name TEXT, address TEXT, email TEXT, scheduled_date DATE DEFAULT CURRENT_DATE, scheduled_time TIME DEFAULT CURRENT_TIME, duration_minutes INT DEFAULT 30, is_urgent BOOLEAN DEFAULT FALSE, is_company BOOLEAN DEFAULT FALSE, company_id INT REFERENCES companies(id) ON DELETE SET NULL, company_ref TEXT, internal_notes TEXT, client_notes TEXT, import_source TEXT, provider_data JSONB DEFAULT '{}', closed_at TIMESTAMP, created_at TIMESTAMP DEFAULT NOW() ); CREATE TABLE IF NOT EXISTS service_logs ( id SERIAL PRIMARY KEY, service_id INT REFERENCES services(id) ON DELETE CASCADE, user_id INT REFERENCES users(id) ON DELETE SET NULL, old_status_id INT REFERENCES service_statuses(id), new_status_id INT REFERENCES service_statuses(id), comment TEXT, 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 (SIN ROMPER NADA, SÓLO AÑADE) await client.query(` DO $$ BEGIN -- Añadimos columna física para el operario en scraped_services si no existe IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='scraped_services' AND column_name='assigned_to') THEN ALTER TABLE scraped_services ADD COLUMN assigned_to INT REFERENCES users(id); END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='client_id') THEN ALTER TABLE services ADD COLUMN client_id INT REFERENCES clients(id) ON DELETE SET NULL; END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='status_id') THEN ALTER TABLE services ADD COLUMN status_id INT REFERENCES service_statuses(id) ON DELETE SET NULL; END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='users' AND column_name='plan_tier') THEN ALTER TABLE users ADD COLUMN plan_tier TEXT DEFAULT 'free'; END IF; 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; END $$; `); console.log("✅ DB Sincronizada."); } catch (e) { console.error("❌ Error DB:", e); } finally { client.release(); } } // HELPERS function normalizePhone(phone) { let p = String(phone || "").trim().replace(/\s+/g, "").replace(/-/g, ""); if (!p) return ""; if (!p.startsWith("+") && /^[6789]\d{8}/.test(p)) return "+34" + p; return p; } function signToken(user) { const accountId = user.owner_id || user.id; return jwt.sign({ sub: user.id, email: user.email, phone: user.phone, role: user.role || 'operario', accountId }, JWT_SECRET, { expiresIn: "30d" }); } function authMiddleware(req, res, next) { const h = req.headers.authorization || ""; const token = h.startsWith("Bearer ") ? h.slice(7) : ""; if (!token) return res.status(401).json({ ok: false, error: "No token" }); try { req.user = jwt.verify(token, JWT_SECRET); next(); } catch { return res.status(401).json({ ok: false, error: "Token inválido" }); } } function genCode6() { return String(Math.floor(100000 + Math.random() * 900000)); } // --- WHATSAPP UTILS --- async function sendWhatsAppCode(phone, code) { if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY || !EVOLUTION_INSTANCE) return; try { await fetch(`${EVOLUTION_BASE_URL.replace(/\/$/, "")}/message/sendText/${EVOLUTION_INSTANCE}`, { method: "POST", headers: { "Content-Type": "application/json", "apikey": EVOLUTION_API_KEY }, body: JSON.stringify({ number: phone.replace("+", ""), text: `🔐 Código: *${code}*` }) }); } catch (e) {} } async function sendWhatsAppAuto(phone, text) { if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY || !EVOLUTION_INSTANCE) return; try { await fetch(`${EVOLUTION_BASE_URL.replace(/\/$/, "")}/message/sendText/${EVOLUTION_INSTANCE}`, { method: "POST", headers: { "Content-Type": "application/json", "apikey": EVOLUTION_API_KEY }, body: JSON.stringify({ number: phone.replace("+", ""), text }) }); } catch (e) {} } async function ensureInstance(instanceName) { if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY) throw new Error("Faltan variables EVOLUTION"); const baseUrl = EVOLUTION_BASE_URL.replace(/\/$/, ""); const headers = { "Content-Type": "application/json", "apikey": EVOLUTION_API_KEY.trim() }; const checkRes = await fetch(`${baseUrl}/instance/connectionState/${instanceName}`, { headers }); if (checkRes.status === 404) { await fetch(`${baseUrl}/instance/create`, { method: 'POST', headers, body: JSON.stringify({ instanceName: instanceName, qrcode: true, integration: "WHATSAPP-BAILEYS" }) }); } return { baseUrl, headers }; } // ========================================== // 🚀 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]); // REFORZADO: Guardamos el ID del operario en la columna asignada y en el JSON await client.query(` UPDATE scraped_services SET status = 'imported', automation_status = 'completed', assigned_to = $1, raw_data = raw_data || jsonb_build_object('assigned_to', $1) WHERE id = $2 `, [ping.user_id, 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 PANEL OPERATIVO (NUEVAS / REVISADAS) // ========================================== app.get("/services/active", authMiddleware, async (req, res) => { try { const q = await pool.query(` SELECT s.*, u.full_name as assigned_name, CASE WHEN (s.raw_data->>'scheduled_date') IS NULL OR (s.raw_data->>'scheduled_date') = '' THEN 'asignado_operario' ELSE 'citado' END as estado_operativo FROM scraped_services s LEFT JOIN users u ON s.assigned_to = u.id -- JOIN FISICO PARA VELOCIDAD WHERE s.owner_id = $1 AND (s.automation_status = 'completed' OR s.status = 'imported') AND s.status != 'archived' 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.put("/services/set-appointment/:id", authMiddleware, async (req, res) => { try { const { id } = req.params; const { date, time, status_operativo } = req.body; await pool.query(` UPDATE scraped_services SET raw_data = raw_data || jsonb_build_object('scheduled_date', $1, 'scheduled_time', $2, 'status_operativo', $3) WHERE id = $4 AND owner_id = $5 `, [date, time, status_operativo, id, req.user.accountId]); res.json({ ok: true }); } catch (e) { res.status(500).json({ ok: false }); } }); app.post("/services/manual-high", authMiddleware, async (req, res) => { try { const { phone, name, address, description, guild_id, assigned_to, mode } = req.body; const serviceRef = "MAN-" + Date.now().toString().slice(-6); const rawData = { "Nombre Cliente": name, "Teléfono": phone, "Dirección": address, "Descripción": description, "guild_id": guild_id }; await pool.query(` INSERT INTO scraped_services (owner_id, provider, service_ref, raw_data, status, automation_status, assigned_to) VALUES ($1, 'MANUAL', $2, $3, 'pending', $4, $5) `, [req.user.accountId, serviceRef, JSON.stringify(rawData), mode === 'auto' ? 'manual' : 'completed', mode === 'manual' ? assigned_to : null]); res.json({ ok: true }); } catch (e) { res.status(500).json({ ok: false }); } }); // ========================================== // 🔐 RUTAS CRM (COMPLETAS DE TU ARCHIVO 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 }); } }); app.get("/providers/scraped", authMiddleware, async (req, res) => { try { const q = await pool.query(` SELECT s.*, ap.expires_at as token_expires_at, u.full_name as current_worker_name, (SELECT json_agg(json_build_object('name', u2.full_name, 'phone', u2.phone)) FROM assignment_pings ap2 JOIN users u2 ON ap2.user_id = u2.id WHERE ap2.scraped_id = s.id AND ap2.status IN ('expired', 'rejected')) as attempted_workers_data FROM scraped_services s LEFT JOIN assignment_pings ap ON s.id = ap.scraped_id AND ap.status = 'pending' LEFT JOIN users u ON ap.user_id = 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.put('/providers/scraped/:id', authMiddleware, async (req, res) => { const { id } = req.params; const { automation_status, name, phone, address, status } = req.body; try { if (automation_status) { await pool.query(`UPDATE scraped_services SET automation_status = $1 WHERE id = $2`, [automation_status, id]); return res.json({ ok: true }); } if (status === 'archived') { await pool.query(`UPDATE scraped_services SET status = 'archived' WHERE id = $1`, [id]); return res.json({ ok: true }); } const current = await pool.query('SELECT raw_data FROM scraped_services WHERE id = $1', [id]); const updated = { ...current.rows[0].raw_data, "Nombre Cliente": name, "Teléfono": phone, "Dirección": address }; await pool.query(`UPDATE scraped_services SET raw_data = $1, status = 'pending' WHERE id = $2`, [JSON.stringify(updated), id]); res.json({ ok: true }); } catch (error) { res.status(500).json({ error: 'Error' }); } }); 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.get("/operators", authMiddleware, async (req, res) => { try { const { guild_id } = req.query; let sql = "SELECT id, full_name FROM users WHERE owner_id=$1 AND role='operario' AND status='active'"; const params = [req.user.accountId]; if(guild_id) { sql += " AND id IN (SELECT user_id FROM user_guilds WHERE guild_id=$2)"; params.push(guild_id); } const q = await pool.query(sql + " ORDER BY full_name ASC", params); res.json({ ok: true, operators: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } }); // [Aquí seguirían todas tus rutas de CRM: clients, companies, zones, geo, logs, etc. Mantén tus bloques de código originales ahí] // ========================================== // 🕒 RELOJ DEL SISTEMA (RUEDA WHATSAPP) // ========================================== setInterval(async () => { try { const expiredPings = await pool.query(` SELECT ap.id, ap.scraped_id, s.owner_id FROM assignment_pings ap JOIN scraped_services s ON ap.scraped_id = s.id WHERE ap.status = 'pending' AND ap.expires_at < NOW() AND s.automation_status = 'in_progress' `); for (const ping of expiredPings.rows) { await pool.query("UPDATE assignment_pings SET status = 'expired' WHERE id = $1", [ping.id]); const nextW = await pool.query(`SELECT id, phone FROM users WHERE owner_id=$1 AND status='active' AND id NOT IN (SELECT user_id FROM assignment_pings WHERE scraped_id=$2) LIMIT 1`, [ping.owner_id, ping.scraped_id]); if (nextW.rowCount > 0) { const token = crypto.randomBytes(16).toString('hex'); await pool.query(`INSERT INTO assignment_pings (scraped_id, user_id, token, expires_at) VALUES ($1, $2, $3, NOW() + INTERVAL '5 min')`, [ping.scraped_id, nextW.rows[0].id, token]); await sendWhatsAppAuto(nextW.rows[0].phone, `🛠️ NUEVO TURNO: https://integrarepara.es/aceptar.html?t=${token}`); } else { await pool.query("UPDATE scraped_services SET automation_status = 'failed' WHERE id = $1", [ping.scraped_id]); } } } catch (e) {} }, 60000); const port = process.env.PORT || 3000; autoUpdateDB().then(() => { app.listen(port, "0.0.0.0", () => console.log(`🚀 Server OK en puerto ${port}`)); });