Actualizar server.js

This commit is contained in:
2026-02-12 08:04:37 +00:00
parent 514bf8cf43
commit 8d20ffc41c

View File

@@ -14,12 +14,30 @@ app.use(express.json());
const {
DATABASE_URL,
JWT_SECRET,
EVOLUTION_BASE_URL, // Ej: https://api.midominio.com
EVOLUTION_API_KEY, // Tu Global API Key
EVOLUTION_BASE_URL,
EVOLUTION_API_KEY,
} = process.env;
// --- DIAGNÓSTICO DE INICIO ---
console.log("------------------------------------------------");
console.log("🔧 INICIANDO SERVIDOR INTEGRA REPARA");
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 (WhatsApp no funcionará)");
} else {
console.log("✅ Evolution URL detectada:", EVOLUTION_BASE_URL);
}
if (!EVOLUTION_API_KEY) {
console.error("⚠️ AVISO: No has puesto EVOLUTION_API_KEY (WhatsApp no funcionará)");
} else {
// Mostramos solo los primeros 4 caracteres por seguridad
console.log("✅ Evolution API Key detectada:", EVOLUTION_API_KEY.substring(0, 4) + "...");
}
console.log("------------------------------------------------");
if (!DATABASE_URL || !JWT_SECRET) {
console.error("❌ ERROR FATAL: Faltan variables de entorno básicas (DB/JWT)");
process.exit(1);
}
@@ -198,7 +216,10 @@ 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 };
const headers = {
"Content-Type": "application/json",
"apikey": EVOLUTION_API_KEY.trim() // Trim por si se copió con espacios
};
// 1. Verificar si existe (intentando pedir estado)
const checkRes = await fetch(`${baseUrl}/instance/connectionState/${instanceName}`, { headers });
@@ -215,11 +236,21 @@ async function ensureInstance(instanceName) {
integration: "WHATSAPP-BAILEYS"
})
});
if (!createRes.ok) {
const err = await createRes.text();
throw new Error("Error creando instancia: " + err);
// Si falla, leemos el error para mostrarlo en el log
const errText = await createRes.text();
console.error("❌ Error Evolution API al crear:", createRes.status, errText);
if (createRes.status === 401) {
throw new Error("API KEY INCORRECTA: Revisa EVOLUTION_API_KEY en las variables de entorno.");
}
throw new Error(`Error creando instancia: ${errText}`);
}
} else if (checkRes.status === 401) {
throw new Error("API KEY INCORRECTA: Revisa EVOLUTION_API_KEY en las variables de entorno.");
}
return { baseUrl, headers };
}
@@ -252,7 +283,7 @@ app.get("/whatsapp/status", authMiddleware, async (req, res) => {
res.json({ ok: true, state, qr, instanceName });
} catch (e) {
console.error("Error WhatsApp:", e);
console.error("Error WhatsApp EndPoint:", e.message);
res.status(500).json({ ok: false, error: e.message });
}
});
@@ -292,7 +323,7 @@ app.delete("/statuses/:id", authMiddleware, async (req, res) => {
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 }); } });
// RESTO DE RUTAS (CLIENTES, ZONAS, SERVICIOS...) - Minimizadas para no ocupar espacio pero funcionales
// RESTO DE RUTAS CRUD...
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 }); } });