Actualizar robot.js
This commit is contained in:
717
robot.js
717
robot.js
@@ -1,245 +1,540 @@
|
||||
import { chromium } from 'playwright';
|
||||
import pg from 'pg';
|
||||
import express from "express";
|
||||
import cors from "cors";
|
||||
import bcrypt from "bcryptjs";
|
||||
import jwt from "jsonwebtoken";
|
||||
import pg from "pg";
|
||||
|
||||
// En Coolify las variables se inyectan solas
|
||||
const { DATABASE_URL } = process.env;
|
||||
const { Pool } = pg;
|
||||
const app = express();
|
||||
|
||||
if (!DATABASE_URL) {
|
||||
console.error("❌ Error: No hay DATABASE_URL definida.");
|
||||
process.exit(1);
|
||||
}
|
||||
app.use(cors());
|
||||
app.use(express.json());
|
||||
|
||||
const pool = new pg.Pool({ connectionString: DATABASE_URL, ssl: false });
|
||||
// VARIABLES DE ENTORNO
|
||||
const {
|
||||
DATABASE_URL,
|
||||
JWT_SECRET,
|
||||
EVOLUTION_BASE_URL,
|
||||
EVOLUTION_API_KEY,
|
||||
EVOLUTION_INSTANCE,
|
||||
} = process.env;
|
||||
|
||||
// CONFIGURACIÓN
|
||||
const HEADLESS = true; // En servidor SIEMPRE true
|
||||
// --- DIAGNÓSTICO DE INICIO ---
|
||||
console.log("------------------------------------------------");
|
||||
console.log("🔧 INICIANDO SERVIDOR INTEGRA REPARA (FULL + MAPPER)");
|
||||
console.log("------------------------------------------------");
|
||||
if (!DATABASE_URL) console.error("❌ FALTA: DATABASE_URL");
|
||||
if (!JWT_SECRET) console.error("❌ FALTA: JWT_SECRET");
|
||||
|
||||
async function main() {
|
||||
console.log("🤖 INICIANDO ROBOT UNIFICADO (MEJORADO)...");
|
||||
if (!EVOLUTION_BASE_URL) console.error("⚠️ AVISO: Falta EVOLUTION_BASE_URL");
|
||||
else console.log("✅ Evolution URL:", EVOLUTION_BASE_URL);
|
||||
|
||||
while (true) {
|
||||
if (!EVOLUTION_INSTANCE) console.error("⚠️ AVISO: Falta EVOLUTION_INSTANCE");
|
||||
else console.log("✅ Instancia Notificaciones:", EVOLUTION_INSTANCE);
|
||||
|
||||
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 {
|
||||
// 1. Obtener credenciales activas
|
||||
const res = await client.query("SELECT * FROM provider_credentials WHERE status = 'active'");
|
||||
const credentials = res.rows;
|
||||
console.log("🔄 Verificando estructura DB...");
|
||||
|
||||
console.log(`📋 Procesando ${credentials.length} cuentas de proveedores...`);
|
||||
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,
|
||||
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()
|
||||
);
|
||||
|
||||
for (const cred of credentials) {
|
||||
let password = "";
|
||||
-- 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',
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
UNIQUE(owner_id, provider, service_ref)
|
||||
);
|
||||
|
||||
-- 🗺️ TABLA DE MAPEO DE VARIABLES (NUEVO)
|
||||
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()
|
||||
);
|
||||
`);
|
||||
|
||||
// PARCHE DE ACTUALIZACIÓN
|
||||
await client.query(`
|
||||
DO $$ BEGIN
|
||||
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='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='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;
|
||||
|
||||
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 $$;
|
||||
`);
|
||||
|
||||
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)); }
|
||||
|
||||
// 🛡️ MIDDLEWARE DE PLANES
|
||||
async function requirePlan(req, res, next, feature) {
|
||||
try {
|
||||
password = Buffer.from(cred.password_hash, 'base64').toString('utf-8');
|
||||
} catch (e) {
|
||||
console.error(`Error decodificando pass para usuario ${cred.owner_id}`);
|
||||
continue;
|
||||
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" }); }
|
||||
}
|
||||
|
||||
console.log(`\n🔄 Sincronizando ${cred.provider.toUpperCase()} para usuario ID ${cred.owner_id}...`);
|
||||
|
||||
if (cred.provider === 'multiasistencia') {
|
||||
await runMultiasistencia(cred.owner_id, cred.username, password);
|
||||
} else if (cred.provider === 'homeserve') {
|
||||
await runHomeserve(cred.owner_id, cred.username, password);
|
||||
}
|
||||
|
||||
// Actualizar timestamp
|
||||
await client.query("UPDATE provider_credentials SET last_sync = NOW() WHERE id = $1", [cred.id]);
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
console.error("❌ Error en ciclo principal:", e);
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
|
||||
// ESPERA DE 15 MINUTOS
|
||||
console.log("\n💤 Durmiendo 15 minutos...");
|
||||
await new Promise(r => setTimeout(r, 15 * 60 * 1000));
|
||||
}
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// 🛠️ ROBOT MULTIASISTENCIA (CORREGIDO)
|
||||
// ==========================================
|
||||
async function runMultiasistencia(ownerId, user, pass) {
|
||||
const browser = await chromium.launch({ headless: HEADLESS, args: ['--no-sandbox'] });
|
||||
const context = await browser.newContext();
|
||||
const page = await context.newPage();
|
||||
|
||||
// --- WHATSAPP UTILS ---
|
||||
async function sendWhatsAppCode(phone, code) {
|
||||
if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY || !EVOLUTION_INSTANCE) { console.error("❌ Faltan datos WhatsApp"); return; }
|
||||
try {
|
||||
console.log("🌍 [Multi] Conectando...");
|
||||
await page.goto('https://web.multiasistencia.com/w3multi/acceso.php', { timeout: 60000 });
|
||||
|
||||
// Login
|
||||
const userInput = await page.$('input[name="usuario"]') || await page.$('input[type="text"]');
|
||||
if(userInput) {
|
||||
await userInput.fill(user);
|
||||
await page.fill('input[type="password"]', pass);
|
||||
await page.click('input[type="submit"]');
|
||||
await page.waitForTimeout(4000);
|
||||
}
|
||||
|
||||
// Ir a listado
|
||||
await page.goto('https://web.multiasistencia.com/w3multi/frepasos_new.php?refresh=1', { waitUntil: 'domcontentloaded' });
|
||||
|
||||
// Sacar expedientes
|
||||
const expedientes = await page.evaluate(() => {
|
||||
const links = Array.from(document.querySelectorAll('a[href*="reparacion="]'));
|
||||
return Array.from(new Set(links.map(a => a.href.match(/reparacion=(\d+)/)?.[1]).filter(Boolean)));
|
||||
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}*` })
|
||||
});
|
||||
|
||||
console.log(`🔍 [Multi] ${expedientes.length} expedientes encontrados.`);
|
||||
|
||||
for (const ref of expedientes) {
|
||||
await page.goto(`https://web.multiasistencia.com/w3multi/repasos1.php?reparacion=${ref}`, { waitUntil: 'domcontentloaded' });
|
||||
|
||||
// --- NUEVA LÓGICA DE EXTRACCIÓN POR CELDAS ---
|
||||
const data = await page.evaluate(() => {
|
||||
|
||||
// Función auxiliar para buscar en celdas vecinas
|
||||
const findValueByHeader = (keywords) => {
|
||||
const cells = Array.from(document.querySelectorAll('td, th'));
|
||||
for (const cell of cells) {
|
||||
const text = (cell.innerText || "").toUpperCase().trim();
|
||||
// Si la celda contiene una de las palabras clave
|
||||
if (keywords.some(k => text.includes(k.toUpperCase()))) {
|
||||
// Devolvemos el texto de la celda SIGUIENTE
|
||||
const nextCell = cell.nextElementSibling;
|
||||
if (nextCell) return nextCell.innerText.trim();
|
||||
}
|
||||
}
|
||||
return "";
|
||||
};
|
||||
|
||||
// Función auxiliar para descripción (busca bloques de texto grandes)
|
||||
const findDescription = () => {
|
||||
// Intento 1: Buscar celda "Descripción"
|
||||
let desc = findValueByHeader(['Descripción', 'Daños', 'Solicitud']);
|
||||
if(desc) return desc;
|
||||
|
||||
// Intento 2: Buscar en el cuerpo general si falla la tabla
|
||||
const body = document.body.innerText;
|
||||
const match = body.match(/Descripción\s*[:\-]?\s*([^\n]+)/i);
|
||||
return match ? match[1].trim() : "";
|
||||
} catch (e) { console.error("Error envío WA:", e.message); }
|
||||
}
|
||||
|
||||
// Extracción más precisa
|
||||
let address = findValueByHeader(['Dirección', 'Domicilio', 'Riesgo']);
|
||||
let pob = findValueByHeader(['Población', 'Localidad']);
|
||||
let cp = findValueByHeader(['C.P.', 'Postal']);
|
||||
|
||||
// Limpieza de dirección (quitar "Baremo" si se cuela)
|
||||
if (address.includes("Baremo")) address = address.split("Baremo")[0].trim();
|
||||
|
||||
// Unir dirección completa
|
||||
let fullAddress = address;
|
||||
if (pob) fullAddress += `, ${pob}`;
|
||||
if (cp) fullAddress += ` (${cp})`;
|
||||
|
||||
return {
|
||||
clientName: findValueByHeader(['Nombre Cliente', 'Asegurado']) || "Desconocido",
|
||||
address: fullAddress || "Sin dirección detectada",
|
||||
phone: (document.body.innerText.match(/[6789]\d{8}/) || [])[0] || "",
|
||||
description: findDescription()
|
||||
};
|
||||
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 (data.clientName) {
|
||||
// Solo guardamos si tenemos al menos un nombre
|
||||
await saveServiceToDB(ownerId, 'multiasistencia', ref, data);
|
||||
}
|
||||
return { baseUrl, headers };
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
console.error("❌ [Multi] Error:", e.message);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
}
|
||||
// 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, 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 }); } });
|
||||
|
||||
// ==========================================
|
||||
// 🛠️ ROBOT HOMESERVE (MANTENIDO)
|
||||
// 🚀 GESTIÓN WHATSAPP (CON RESTRICCIÓN DE PLAN)
|
||||
// ==========================================
|
||||
async function runHomeserve(ownerId, user, pass) {
|
||||
const browser = await chromium.launch({ headless: HEADLESS, args: ['--no-sandbox'] });
|
||||
const page = await browser.newPage();
|
||||
|
||||
app.get("/whatsapp/status", authMiddleware, (req, res, next) => requirePlan(req, res, next, 'whatsapp_enabled'), async (req, res) => {
|
||||
try {
|
||||
console.log("🌍 [HomeServe] Conectando...");
|
||||
await page.goto('https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=PROF_PASS', { timeout: 60000 });
|
||||
|
||||
if (await page.isVisible('input[name="CODIGO"]')) {
|
||||
await page.fill('input[name="CODIGO"]', user);
|
||||
await page.fill('input[type="password"]', pass);
|
||||
await page.keyboard.press('Enter');
|
||||
await page.waitForTimeout(5000);
|
||||
const instanceName = `cliente_${req.user.accountId}`;
|
||||
const { baseUrl, headers } = await ensureInstance(instanceName);
|
||||
const stateRes = await fetch(`${baseUrl}/instance/connectionState/${instanceName}`, { headers });
|
||||
const stateData = await stateRes.json();
|
||||
const state = stateData.instance?.state || "close";
|
||||
let qr = null;
|
||||
if (state !== "open") {
|
||||
const qrRes = await fetch(`${baseUrl}/instance/connect/${instanceName}`, { headers });
|
||||
const qrData = await qrRes.json();
|
||||
qr = qrData.code || qrData.base64;
|
||||
}
|
||||
|
||||
await page.goto('https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=lista_servicios_total');
|
||||
|
||||
const refs = await page.evaluate(() => {
|
||||
const filas = Array.from(document.querySelectorAll('table tr'));
|
||||
return filas.map(tr => tr.querySelector('td')?.innerText.trim()).filter(t => /^\d{4,}$/.test(t));
|
||||
res.json({ ok: true, state, qr, instanceName });
|
||||
} catch (e) { res.status(500).json({ ok: false, error: e.message }); }
|
||||
});
|
||||
|
||||
console.log(`🔍 [HomeServe] ${refs.length} expedientes encontrados.`);
|
||||
|
||||
for (const ref of refs) {
|
||||
// ==========================================
|
||||
// 🤖 GESTIÓN DE PROVEEDORES Y ROBOTS
|
||||
// ==========================================
|
||||
app.get("/providers/credentials", authMiddleware, async (req, res) => {
|
||||
try {
|
||||
await page.goto('https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=lista_servicios_total');
|
||||
await page.click(`text="${ref}"`, { timeout: 5000 });
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
const data = await page.evaluate(() => {
|
||||
const rows = Array.from(document.querySelectorAll('tr'));
|
||||
const d = {};
|
||||
rows.forEach(r => {
|
||||
const cells = r.querySelectorAll('td');
|
||||
if(cells.length > 1) {
|
||||
const k = cells[0].innerText.toUpperCase();
|
||||
const v = cells[1].innerText;
|
||||
if(k.includes("CLIENTE")) d.clientName = v;
|
||||
if(k.includes("DOMICILIO")) d.address = v;
|
||||
if(k.includes("POBLACION")) d.address += ", " + v;
|
||||
if(k.includes("TELEFONOS")) d.phone = v;
|
||||
if(k.includes("COMENTARIOS") || k.includes("AVERIA")) d.description = v;
|
||||
}
|
||||
});
|
||||
return d;
|
||||
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 }); }
|
||||
});
|
||||
|
||||
if (data.clientName) {
|
||||
await saveServiceToDB(ownerId, 'homeserve', ref, data);
|
||||
}
|
||||
|
||||
} catch (e) { console.error(`Error leyendo ${ref}: ${e.message}`); }
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
console.error("❌ [HomeServe] Error:", e.message);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// 💾 GUARDADO EN BASE DE DATOS
|
||||
// ==========================================
|
||||
async function saveServiceToDB(ownerId, provider, ref, data) {
|
||||
// Verificar si ya existe en servicios reales (para no duplicar trabajo)
|
||||
const exists = await pool.query("SELECT id FROM services WHERE company_ref = $1 AND owner_id = $2", [ref, ownerId]);
|
||||
if (exists.rowCount > 0) return;
|
||||
|
||||
// Verificar si ya existe en buzón, si existe ACTUALIZAMOS los datos (por si hemos mejorado el scraping)
|
||||
console.log(`💾 Guardando/Actualizando: ${ref} (${data.address})`);
|
||||
|
||||
app.post("/providers/credentials", authMiddleware, async (req, res) => {
|
||||
try {
|
||||
const { provider, username, password } = req.body;
|
||||
const passwordSafe = Buffer.from(password).toString('base64');
|
||||
await pool.query(`
|
||||
INSERT INTO scraped_services (owner_id, provider, service_ref, raw_data, status)
|
||||
VALUES ($1, $2, $3, $4, 'pending')
|
||||
ON CONFLICT (owner_id, provider, service_ref)
|
||||
DO UPDATE SET raw_data = EXCLUDED.raw_data, created_at = NOW()
|
||||
`, [ownerId, provider, ref, JSON.stringify(data)]);
|
||||
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.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;
|
||||
}
|
||||
|
||||
main();
|
||||
// 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(); }
|
||||
});
|
||||
|
||||
// ==========================================
|
||||
// 🗺️ MAPEADOR DE VARIABLES (DISCOVERY) - NUEVO
|
||||
// ==========================================
|
||||
app.get("/discovery/keys/:provider", authMiddleware, async (req, res) => {
|
||||
try {
|
||||
const { provider } = req.params;
|
||||
const rawServices = await pool.query("SELECT raw_data FROM scraped_services WHERE owner_id=$1 AND provider=$2", [req.user.accountId, provider]);
|
||||
const mappings = await pool.query("SELECT original_key, target_key, is_ignored FROM variable_mappings WHERE owner_id=$1 AND provider=$2", [req.user.accountId, provider]);
|
||||
const mapDict = {};
|
||||
mappings.rows.forEach(m => mapDict[m.original_key] = m);
|
||||
|
||||
const discoverySet = new Set();
|
||||
const samples = {};
|
||||
|
||||
rawServices.rows.forEach(row => {
|
||||
const data = row.raw_data;
|
||||
if (data && typeof data === 'object') {
|
||||
Object.keys(data).forEach(k => {
|
||||
discoverySet.add(k);
|
||||
if (!samples[k] && data[k]) samples[k] = data[k];
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const result = Array.from(discoverySet).map(key => ({
|
||||
original: key,
|
||||
sample: samples[key] || "(Vacío)",
|
||||
mappedTo: mapDict[key]?.target_key || "",
|
||||
ignored: mapDict[key]?.is_ignored || false
|
||||
})).sort((a, b) => a.original.localeCompare(b.original));
|
||||
|
||||
res.json({ ok: true, keys: result });
|
||||
} catch (e) { res.status(500).json({ ok: false, error: e.message }); }
|
||||
});
|
||||
|
||||
app.post("/discovery/save", authMiddleware, async (req, res) => {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
const { provider, mappings } = req.body;
|
||||
await client.query('BEGIN');
|
||||
for (const m of mappings) {
|
||||
await client.query(`
|
||||
INSERT INTO variable_mappings (owner_id, provider, original_key, target_key, is_ignored)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (owner_id, provider, original_key)
|
||||
DO UPDATE SET target_key = EXCLUDED.target_key, is_ignored = EXCLUDED.is_ignored
|
||||
`, [req.user.accountId, provider, m.original, m.target, m.ignored]);
|
||||
}
|
||||
await client.query('COMMIT');
|
||||
res.json({ ok: true });
|
||||
} catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false, error: e.message }); } finally { client.release(); }
|
||||
});
|
||||
|
||||
// =========================
|
||||
// 👥 GESTIÓN DE CLIENTES
|
||||
// =========================
|
||||
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 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)`; 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 }); }
|
||||
});
|
||||
|
||||
app.get("/clients/:id/details", authMiddleware, async (req, res) => {
|
||||
try {
|
||||
const clientId = req.params.id;
|
||||
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 });
|
||||
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 }); }
|
||||
});
|
||||
|
||||
app.post("/clients", authMiddleware, async (req, res) => {
|
||||
try {
|
||||
const { full_name, phone, email, address, notes } = req.body;
|
||||
const p = normalizePhone(phone);
|
||||
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 }); }
|
||||
});
|
||||
|
||||
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]);
|
||||
res.json({ ok: true });
|
||||
} catch (e) { res.status(500).json({ ok: false }); }
|
||||
});
|
||||
|
||||
// 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
|
||||
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 }); } });
|
||||
app.delete("/companies/:id", authMiddleware, async (req, res) => { try { await pool.query("DELETE FROM companies 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 }); } });
|
||||
app.get("/operators", authMiddleware, async (req, res) => { try { const q = await pool.query("SELECT id, full_name FROM users WHERE owner_id=$1 AND role='operario' ORDER BY full_name ASC", [req.user.accountId]); res.json({ ok: true, operators: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||||
app.get("/zones", authMiddleware, async (req, res) => { try { const q = await pool.query("SELECT * FROM zones WHERE owner_id=$1 ORDER BY name ASC", [req.user.accountId]); res.json({ ok: true, zones: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||||
app.post("/zones", authMiddleware, async (req, res) => { try { const { name } = req.body; await pool.query("INSERT INTO zones (name, owner_id) VALUES ($1, $2)", [name, req.user.accountId]); res.json({ ok: true }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||||
app.delete("/zones/:id", authMiddleware, async (req, res) => { try { await pool.query("DELETE FROM zones 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 }); } });
|
||||
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(); } });
|
||||
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 }); } });
|
||||
app.put("/services/:id/status", authMiddleware, async (req, res) => { const client = await pool.connect(); try { const { status_id, comment } = req.body; await client.query('BEGIN'); const curr = await client.query("SELECT status_id FROM services WHERE id=$1", [req.params.id]); const old = curr.rows[0].status_id; await client.query("UPDATE services SET status_id=$1 WHERE id=$2", [status_id, req.params.id]); await client.query("INSERT INTO service_logs (service_id, user_id, old_status_id, new_status_id, comment) VALUES ($1, $2, $3, $4, $5)", [req.params.id, req.user.sub, old, status_id, comment]); await client.query('COMMIT'); res.json({ ok: true }); } catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false }); } finally { client.release(); } });
|
||||
app.post("/services", authMiddleware, async (req, res) => { const client = await pool.connect(); try { const { phone, name, address, email, description, scheduled_date, scheduled_time, duration, is_urgent, is_company, company_id, company_ref, internal_notes, client_notes, status_id, guild_id, assigned_to } = req.body; const p = normalizePhone(phone); await client.query('BEGIN'); let finalStatus = status_id; if (!finalStatus) { const def = await client.query("SELECT id FROM service_statuses WHERE owner_id=$1 AND is_default=TRUE LIMIT 1", [req.user.accountId]); finalStatus = def.rows[0]?.id; } let clientId; const cCheck = await client.query("SELECT id, addresses FROM clients WHERE phone=$1 AND owner_id=$2", [p, req.user.accountId]); if (cCheck.rowCount > 0) { clientId = cCheck.rows[0].id; let addrs = cCheck.rows[0].addresses || []; if(!addrs.includes(address)) { addrs.push(address); await client.query("UPDATE clients SET addresses=$1 WHERE id=$2", [JSON.stringify(addrs), clientId]); } } else { const newC = await client.query("INSERT INTO clients (owner_id, full_name, phone, email, addresses) VALUES ($1, $2, $3, $4, $5) RETURNING id", [req.user.accountId, name, p, email, JSON.stringify([address])]); clientId = newC.rows[0].id; } const insert = await client.query(`INSERT INTO services (owner_id, client_id, status_id, contact_phone, contact_name, address, email, description, scheduled_date, scheduled_time, duration_minutes, is_urgent, is_company, company_id, company_ref, internal_notes, client_notes, title, guild_id, assigned_to) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20) RETURNING id`, [req.user.accountId, clientId, finalStatus, p, name, address, email, description, scheduled_date || 'NOW()', scheduled_time || 'NOW()', (duration || 30), (is_urgent || false), (is_company || false), (company_id || null), company_ref, internal_notes, client_notes, name + " - Svc", (guild_id || null), (assigned_to || null)]); await client.query("INSERT INTO service_logs (service_id, user_id, new_status_id, comment) VALUES ($1, $2, $3, 'Servicio Creado')", [insert.rows[0].id, req.user.sub, finalStatus]); 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(); } });
|
||||
app.put("/services/:id", authMiddleware, async (req, res) => { const client = await pool.connect(); try { const { name, address, email, description, scheduled_date, scheduled_time, duration, is_urgent, is_company, company_id, company_ref, internal_notes, client_notes, guild_id, assigned_to } = req.body; await client.query('BEGIN'); await client.query(`UPDATE services SET contact_name=$1, address=$2, email=$3, description=$4, scheduled_date=$5, scheduled_time=$6, duration_minutes=$7, is_urgent=$8, is_company=$9, company_id=$10, company_ref=$11, internal_notes=$12, client_notes=$13, guild_id=$14, assigned_to=$15 WHERE id=$16 AND owner_id=$17`, [name, address, email, description, scheduled_date, scheduled_time, (duration || 30), (is_urgent || false), (is_company || false), (company_id || null), company_ref, internal_notes, client_notes, (guild_id || null), (assigned_to || null), req.params.id, req.user.accountId]); await client.query("INSERT INTO service_logs (service_id, user_id, new_status_id, comment) VALUES ($1, $2, (SELECT status_id FROM services WHERE id=$1), 'Datos editados')", [req.params.id, req.user.sub]); 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("/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 }); } });
|
||||
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 }); } });
|
||||
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, 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 } = 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) VALUES ($1, $2, $3, $4, $5, TRUE, $6) RETURNING id", [fullName, email, hash, role || 'operario', p, req.user.accountId]); 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 } = 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}`)); });
|
||||
Reference in New Issue
Block a user