Actualizar server.js

This commit is contained in:
2026-02-12 22:46:00 +00:00
parent c7d42a2460
commit 25b49e136c

381
server.js
View File

@@ -16,38 +16,36 @@ const {
JWT_SECRET,
EVOLUTION_BASE_URL,
EVOLUTION_API_KEY,
EVOLUTION_INSTANCE, // <--- ¡FALTABA ESTO! (La instancia que envía los códigos)
EVOLUTION_INSTANCE, // <--- Instancia Maestra para SMS/Registro
} = process.env;
// --- DIAGNÓSTICO DE INICIO ---
console.log("------------------------------------------------");
console.log("🔧 INICIANDO SERVIDOR INTEGRA REPARA");
console.log("🔧 INICIANDO SERVIDOR INTEGRA REPARA (FULL)");
console.log("------------------------------------------------");
if (!DATABASE_URL) console.error("❌ FALTA: DATABASE_URL");
if (!JWT_SECRET) console.error("❌ FALTA: JWT_SECRET");
if (!EVOLUTION_BASE_URL) {
console.error("⚠️ AVISO: No has puesto EVOLUTION_BASE_URL");
} else {
console.log("✅ Evolution URL:", EVOLUTION_BASE_URL);
}
if (!EVOLUTION_BASE_URL) console.error("⚠️ AVISO: Falta EVOLUTION_BASE_URL");
else console.log("✅ Evolution URL:", EVOLUTION_BASE_URL);
if (!EVOLUTION_INSTANCE) {
console.error("⚠️ AVISO: No has puesto EVOLUTION_INSTANCE (No se enviarán códigos de registro)");
} else {
console.log("✅ Instancia de Notificaciones:", EVOLUTION_INSTANCE);
}
if (!EVOLUTION_INSTANCE) console.error("⚠️ AVISO: Falta EVOLUTION_INSTANCE (No saldrán códigos de registro)");
else console.log("✅ Instancia Notificaciones:", EVOLUTION_INSTANCE);
console.log("------------------------------------------------");
if (!DATABASE_URL || !JWT_SECRET) {
process.exit(1);
}
if (!DATABASE_URL || !JWT_SECRET) process.exit(1);
const pool = new Pool({
connectionString: DATABASE_URL,
ssl: false
});
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
@@ -58,6 +56,7 @@ async function autoUpdateDB() {
console.log("🔄 Verificando estructura DB...");
await client.query(`
-- USUARIOS
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
full_name TEXT NOT NULL,
@@ -69,6 +68,10 @@ async function autoUpdateDB() {
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,
created_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS login_codes (
@@ -81,6 +84,8 @@ async function autoUpdateDB() {
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,
@@ -102,6 +107,8 @@ async function autoUpdateDB() {
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,
@@ -112,6 +119,8 @@ async function autoUpdateDB() {
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,
@@ -129,6 +138,8 @@ async function autoUpdateDB() {
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE(owner_id, type)
);
-- ZONAS
CREATE TABLE IF NOT EXISTS zones (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
@@ -140,6 +151,30 @@ async function autoUpdateDB() {
zone_id INT REFERENCES zones(id) ON DELETE CASCADE,
PRIMARY KEY (user_id, zone_id)
);
-- 🤖 ROBOTS / PROVEEDORES (NUEVO)
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, -- DATOS CRUDOS DEL ROBOT
status TEXT DEFAULT 'pending',
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE(owner_id, provider, service_ref)
);
-- SERVICIOS (PRINCIPAL)
CREATE TABLE IF NOT EXISTS services (
id SERIAL PRIMARY KEY,
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
@@ -162,6 +197,8 @@ async function autoUpdateDB() {
company_ref TEXT,
internal_notes TEXT,
client_notes TEXT,
import_source TEXT, -- 'homeserve', 'multiasistencia', 'manual'
provider_data JSONB DEFAULT '{}', -- 📥 AQUÍ SE GUARDAN TODOS LOS DATOS EXTRA
closed_at TIMESTAMP,
created_at TIMESTAMP DEFAULT NOW()
);
@@ -176,29 +213,23 @@ async function autoUpdateDB() {
);
`);
// PARCHE DE COLUMNAS
// PARCHE DE ACTUALIZACIÓN
await client.query(`
DO $$ BEGIN
-- Asegurar columnas básicas
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='services' AND column_name='guild_id') THEN ALTER TABLE services ADD COLUMN guild_id INT REFERENCES guilds(id) ON DELETE SET NULL; END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='assigned_to') THEN ALTER TABLE services ADD COLUMN assigned_to INT REFERENCES users(id) ON DELETE SET NULL; END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='contact_phone') THEN ALTER TABLE services ADD COLUMN contact_phone TEXT; END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='contact_name') THEN ALTER TABLE services ADD COLUMN contact_name TEXT; END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='address') THEN ALTER TABLE services ADD COLUMN address TEXT; END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='email') THEN ALTER TABLE services ADD COLUMN email TEXT; END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='title') THEN ALTER TABLE services ADD COLUMN title TEXT; END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='description') THEN ALTER TABLE services ADD COLUMN description TEXT; END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='scheduled_date') THEN ALTER TABLE services ADD COLUMN scheduled_date DATE DEFAULT CURRENT_DATE; END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='scheduled_time') THEN ALTER TABLE services ADD COLUMN scheduled_time TIME DEFAULT CURRENT_TIME; END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='duration_minutes') THEN ALTER TABLE services ADD COLUMN duration_minutes INT DEFAULT 30; END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='is_urgent') THEN ALTER TABLE services ADD COLUMN is_urgent BOOLEAN DEFAULT FALSE; END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='company_id') THEN ALTER TABLE services ADD COLUMN company_id INT REFERENCES companies(id) ON DELETE SET NULL; END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='is_company') THEN ALTER TABLE services ADD COLUMN is_company BOOLEAN DEFAULT FALSE; END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='company_ref') THEN ALTER TABLE services ADD COLUMN company_ref TEXT; END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='internal_notes') THEN ALTER TABLE services ADD COLUMN internal_notes TEXT; END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='client_notes') THEN ALTER TABLE services ADD COLUMN client_notes TEXT; END IF;
-- Columnas SaaS
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='users' AND column_name='company_slug') THEN ALTER TABLE users ADD COLUMN company_slug TEXT UNIQUE; END IF;
-- Columnas DATA IMPORT (NUEVO)
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;
BEGIN ALTER TABLE users DROP CONSTRAINT IF EXISTS users_phone_key; EXCEPTION WHEN OTHERS THEN NULL; END;
BEGIN ALTER TABLE users DROP CONSTRAINT IF EXISTS users_email_key; EXCEPTION WHEN OTHERS THEN NULL; END;
END $$;
@@ -210,95 +241,57 @@ async function autoUpdateDB() {
// 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 genCode6() { return String(Math.floor(100000 + Math.random() * 900000)); }
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)); }
// --- FUNCIÓN DE ENVÍO DE CÓDIGO (REGISTRO) ---
async function sendWhatsAppCode(phone, code) {
if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY || !EVOLUTION_INSTANCE) {
console.error("❌ ERROR: Faltan variables para enviar WhatsApp (URL, APIKEY o INSTANCE)");
return;
}
// Aseguramos que la URL no tenga barra al final y añadimos la instancia
const url = `${EVOLUTION_BASE_URL.replace(/\/$/, "")}/message/sendText/${EVOLUTION_INSTANCE}`;
const number = phone.replace("+", ""); // Quitar el + para la API
console.log(`📤 Enviando código a ${number} desde instancia ${EVOLUTION_INSTANCE}...`);
// 🛡️ MIDDLEWARE DE PLANES
async function requirePlan(req, res, next, feature) {
try {
const res = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"apikey": EVOLUTION_API_KEY
},
body: JSON.stringify({
number: number,
text: `🔐 Código de verificación IntegraRepara: *${code}*`
})
});
if (!res.ok) {
const err = await res.text();
console.error("❌ Error enviando WhatsApp:", res.status, err);
} else {
console.log("✅ WhatsApp enviado correctamente.");
}
} catch (e) {
console.error("❌ Excepción enviando WhatsApp:", e.message);
}
const q = await pool.query("SELECT plan_tier, subscription_status FROM users WHERE id=$1", [req.user.accountId]);
const userPlan = q.rows[0]?.plan_tier || 'free';
const limits = PLAN_LIMITS[userPlan];
if (!limits || !limits[feature]) return res.status(403).json({ ok: false, error: `Función solo para plan ${feature === 'automation_enabled' ? 'PRO' : 'ESTÁNDAR'}` });
next();
} catch (e) { res.status(500).json({ ok: false, error: "Error plan" }); }
}
// --- AUTOMATIZACIÓN DE INSTANCIAS (CLIENTES) ---
async function ensureInstance(instanceName) {
if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY) throw new Error("Faltan variables EVOLUTION en el servidor");
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) {
console.log(`🚀 Creando instancia automática: ${instanceName}`);
const createRes = await fetch(`${baseUrl}/instance/create`, {
method: 'POST',
headers,
body: JSON.stringify({
instanceName: instanceName,
qrcode: true,
integration: "WHATSAPP-BAILEYS"
})
// --- WHATSAPP UTILS ---
async function sendWhatsAppCode(phone, code) {
if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY || !EVOLUTION_INSTANCE) { console.error("Faltan datos WhatsApp"); 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) { console.error("Error envío WA:", e.message); }
}
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" })
});
if (!createRes.ok) {
const errText = await createRes.text();
if (createRes.status === 401) throw new Error("API KEY INCORRECTA");
throw new Error(`Error creando instancia: ${errText}`);
}
} else if (checkRes.status === 401) {
throw new Error("API KEY INCORRECTA");
}
return { baseUrl, headers };
}
// RUTAS AUTH
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) VALUES ($1, $2, $3, $4, $5, $6, 'admin', NULL) 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]);
// ENVÍO DE WHATSAPP
await sendWhatsAppCode(p, code);
await client.query('COMMIT'); res.json({ ok: true, phone: p }); } catch (e) { await client.query('ROLLBACK'); console.error(e); res.status(500).json({ ok: false }); } finally { client.release(); } });
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); // Enviar código
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 (AUTOMÁTICA)
// 🚀 GESTIÓN WHATSAPP (CON RESTRICCIÓN DE PLAN)
// ==========================================
app.get("/whatsapp/status", authMiddleware, async (req, res) => {
app.get("/whatsapp/status", authMiddleware, (req, res, next) => requirePlan(req, res, next, 'whatsapp_enabled'), async (req, res) => {
try {
const instanceName = `cliente_${req.user.accountId}`;
const { baseUrl, headers } = await ensureInstance(instanceName);
@@ -312,126 +305,146 @@ app.get("/whatsapp/status", authMiddleware, async (req, res) => {
qr = qrData.code || qrData.base64;
}
res.json({ ok: true, state, qr, instanceName });
} catch (e) {
console.error("Error WhatsApp EndPoint:", e.message);
res.status(500).json({ ok: false, error: e.message });
}
} catch (e) { res.status(500).json({ ok: false, error: e.message }); }
});
// GESTIÓN DE ESTADOS
app.get("/statuses", authMiddleware, async (req, res) => {
// ==========================================
// 🤖 GESTIÓN DE PROVEEDORES (ROBOTS)
// ==========================================
app.get("/providers/credentials", 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 });
const q = await pool.query("SELECT provider, username, last_sync, status FROM provider_credentials WHERE owner_id=$1", [req.user.accountId]);
res.json({ ok: true, credentials: q.rows });
} catch (e) { res.status(500).json({ ok: false }); }
});
app.post("/statuses", authMiddleware, async (req, res) => {
app.post("/providers/credentials", authMiddleware, async (req, res) => {
try {
const { name, color } = req.body;
if(!name) return res.status(400).json({ok:false, error: "Nombre requerido"});
await pool.query("INSERT INTO service_statuses (owner_id, name, color) VALUES ($1, $2, $3)", [req.user.accountId, name, color || 'gray']);
const { provider, username, password } = req.body;
const passwordSafe = Buffer.from(password).toString('base64');
await pool.query(`
INSERT INTO provider_credentials (owner_id, provider, username, password_hash)
VALUES ($1, $2, $3, $4)
ON CONFLICT (owner_id, provider) DO UPDATE SET username = EXCLUDED.username, password_hash = EXCLUDED.password_hash, status = 'active'
`, [req.user.accountId, provider, username, passwordSafe]);
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 accountId = req.user.accountId;
const check = await client.query("SELECT COUNT(*) FROM services WHERE status_id = $1 AND owner_id = $2", [statusId, 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, accountId]);
res.json({ ok: true });
} catch(e) { res.status(500).json({ ok: false }); } finally { client.release(); }
} catch (e) { res.status(500).json({ ok: false }); }
});
// GESTIÓN DE PLANTILLAS
app.get("/templates", authMiddleware, async (req, res) => { try { const q = await pool.query("SELECT * FROM message_templates WHERE owner_id=$1", [req.user.accountId]); res.json({ ok: true, templates: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } });
app.post("/templates", authMiddleware, async (req, res) => { try { const { type, content } = req.body; await pool.query(`INSERT INTO message_templates (owner_id, type, content) VALUES ($1, $2, $3) ON CONFLICT (owner_id, type) DO UPDATE SET content = EXCLUDED.content`, [req.user.accountId, type, content]); res.json({ ok: true }); } catch (e) { res.status(500).json({ ok: false }); } });
app.get("/providers/scraped", authMiddleware, async (req, res) => {
try {
const q = await pool.query("SELECT * FROM scraped_services WHERE owner_id=$1 AND status='pending' ORDER BY created_at DESC", [req.user.accountId]);
res.json({ ok: true, services: q.rows });
} catch (e) { res.status(500).json({ ok: false }); }
});
// 📥 IMPORTACIÓN INTELIGENTE (LA CLAVE)
app.post("/providers/import/:id", authMiddleware, async (req, res) => {
const client = await pool.connect();
try {
const scrapedId = req.params.id;
await client.query('BEGIN');
// 1. Obtener datos RAW
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 raw = scrapedQ.rows[0].raw_data;
const provider = scrapedQ.rows[0].provider;
const ref = scrapedQ.rows[0].service_ref;
// 2. Buscar/Crear Cliente
const phoneClean = normalizePhone(raw.phone || "");
let clientId = null;
if (phoneClean) {
const cCheck = await client.query("SELECT id FROM clients WHERE phone=$1 AND owner_id=$2", [phoneClean, req.user.accountId]);
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, raw.clientName || "Cliente Robot", phoneClean || "", JSON.stringify([raw.address || ""])]);
clientId = newC.rows[0].id;
}
// 3. Buscar/Crear Compañía
let companyId = null;
const companyName = provider.charAt(0).toUpperCase() + provider.slice(1);
const compCheck = await client.query("SELECT id FROM companies WHERE name ILIKE $1 AND owner_id=$2", [companyName, req.user.accountId]);
if (compCheck.rowCount > 0) companyId = compCheck.rows[0].id;
else {
const newComp = await client.query("INSERT INTO companies (owner_id, name) VALUES ($1, $2) RETURNING id", [req.user.accountId, companyName]);
companyId = newComp.rows[0].id;
}
// 4. Insertar Servicio (CON PROVIDER_DATA)
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, company_id, status_id, company_ref, title, description, address, contact_phone, contact_name,
is_company, import_source, provider_data
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) RETURNING id
`, [
req.user.accountId, clientId, companyId, statusQ.rows[0]?.id, ref,
`${companyName} - ${ref}`, raw.description || "Sin descripción", raw.address, phoneClean, raw.clientName,
true, provider, JSON.stringify(raw)
]);
await client.query("UPDATE scraped_services SET status='imported' WHERE id=$1", [scrapedId]);
await client.query("INSERT INTO service_logs (service_id, user_id, new_status_id, comment) VALUES ($1, $2, $3, 'Importado por Robot')", [insertSvc.rows[0].id, req.user.sub, statusQ.rows[0]?.id]);
await client.query('COMMIT');
res.json({ ok: true });
} catch (e) { await client.query('ROLLBACK'); console.error(e); res.status(500).json({ ok: false, error: e.message }); } finally { client.release(); }
});
// =========================
// 👥 GESTIÓN DE CLIENTES (CRM)
// =========================
// 1. Obtener lista de clientes con contador de servicios
app.get("/clients", authMiddleware, async (req, res) => {
try {
const { search } = req.query;
let query = `
SELECT c.*,
(SELECT COUNT(*) FROM services s WHERE s.client_id = c.id) as service_count,
(SELECT MAX(created_at) FROM services s WHERE s.client_id = c.id) as last_service
FROM clients c
WHERE c.owner_id = $1
`;
let query = `SELECT c.*, (SELECT COUNT(*) FROM services s WHERE s.client_id = c.id) as service_count FROM clients c WHERE c.owner_id = $1`;
const params = [req.user.accountId];
if (search) {
query += ` AND (c.full_name ILIKE $2 OR c.phone ILIKE $2 OR c.email ILIKE $2)`;
params.push(`%${search}%`);
}
query += ` ORDER BY c.created_at DESC LIMIT 50`; // Limitamos a 50 para no saturar
if (search) { query += ` AND (c.full_name ILIKE $2 OR c.phone ILIKE $2)`; params.push(`%${search}%`); }
query += ` ORDER BY c.created_at DESC LIMIT 50`;
const q = await pool.query(query, params);
res.json({ ok: true, clients: q.rows });
} catch (e) { res.status(500).json({ ok: false, error: e.message }); }
} catch (e) { res.status(500).json({ ok: false }); }
});
// 2. Obtener un cliente DETALLADO (con direcciones y servicios)
app.get("/clients/:id/details", authMiddleware, async (req, res) => {
try {
const clientId = req.params.id;
// Datos del cliente
const clientQ = await pool.query("SELECT * FROM clients WHERE id=$1 AND owner_id=$2", [clientId, req.user.accountId]);
if (clientQ.rowCount === 0) return res.status(404).json({ ok: false });
// Historial de servicios
const servicesQ = await pool.query(`
SELECT s.*, st.name as status_name, st.color as status_color, u.full_name as assigned_name
FROM services s
LEFT JOIN service_statuses st ON s.status_id = st.id
LEFT JOIN users u ON s.assigned_to = u.id
WHERE s.client_id = $1 ORDER BY s.created_at DESC
`, [clientId]);
const servicesQ = await pool.query(`SELECT s.*, st.name as status_name, st.color as status_color, u.full_name as assigned_name FROM services s LEFT JOIN service_statuses st ON s.status_id = st.id LEFT JOIN users u ON s.assigned_to = u.id WHERE s.client_id = $1 ORDER BY s.created_at DESC`, [clientId]);
res.json({ ok: true, client: clientQ.rows[0], services: servicesQ.rows });
} catch (e) { res.status(500).json({ ok: false }); }
});
// 3. Crear cliente manual (sin crear servicio)
app.post("/clients", authMiddleware, async (req, res) => {
try {
const { full_name, phone, email, address, notes } = req.body;
const p = normalizePhone(phone);
const addrs = address ? JSON.stringify([address]) : '[]';
const q = await pool.query(
"INSERT INTO clients (owner_id, full_name, phone, email, addresses, notes) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id",
[req.user.accountId, full_name, p, email, addrs, notes]
);
const q = await pool.query("INSERT INTO clients (owner_id, full_name, phone, email, addresses, notes) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id", [req.user.accountId, full_name, p, email, JSON.stringify([address]), notes]);
res.json({ ok: true, id: q.rows[0].id });
} catch (e) { res.status(500).json({ ok: false }); }
});
// 4. Actualizar notas o datos del cliente
app.put("/clients/:id", authMiddleware, async (req, res) => {
try {
const { full_name, email, notes, addresses } = req.body;
await pool.query(
"UPDATE clients SET full_name=$1, email=$2, notes=$3, addresses=$4 WHERE id=$5 AND owner_id=$6",
[full_name, email, notes, JSON.stringify(addresses), req.params.id, req.user.accountId]
);
await pool.query("UPDATE clients SET full_name=$1, email=$2, notes=$3, addresses=$4 WHERE id=$5 AND owner_id=$6", [full_name, email, notes, JSON.stringify(addresses), req.params.id, req.user.accountId]);
res.json({ ok: true });
} catch (e) { res.status(500).json({ ok: false }); }
});
// RESTO DE RUTAS CRUD...
// GESTIÓN DE ESTADOS Y SERVICIOS BÁSICOS
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(); } });
// RESTO DE ENDPOINTS (CLIENTES, ZONAS, ETC.) MANTENIDOS
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 }); } });
@@ -457,5 +470,9 @@ 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 } = 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 WHERE id=$6", [fullName, email, p, role, hash, userId]); } else { await client.query("UPDATE users SET full_name=$1, email=$2, phone=$3, role=$4 WHERE id=$5", [fullName, email, p, role, 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 }); } });
// GESTIÓN DE SUBDOMINIO (EMPRESA)
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(); } });
const port = process.env.PORT || 3000;
autoUpdateDB().then(() => { app.listen(port, "0.0.0.0", () => console.log(`🚀 Server OK en puerto ${port}`)); });