1 Commits

2 changed files with 16 additions and 453 deletions

View File

@@ -20,8 +20,7 @@
"pg": "^8.11.3", "pg": "^8.11.3",
"stripe": "^14.20.0", "stripe": "^14.20.0",
"playwright": "^1.42.1", "playwright": "^1.42.1",
"openai": "^4.28.0", "openai": "^4.28.0"
"express-rate-limit": "^7.4.0"
}, },
"engines": { "engines": {

456
server.js
View File

@@ -7,11 +7,9 @@ import pg from "pg";
import crypto from "crypto"; import crypto from "crypto";
import OpenAI from "openai"; import OpenAI from "openai";
import Stripe from "stripe"; import Stripe from "stripe";
import rateLimit from "express-rate-limit";
const { Pool } = pg; const { Pool } = pg;
const app = express(); const app = express();
app.set("trust proxy", 1); // Necesario para express-rate-limit detrás del proxy de Coolify
// 🛑 SEMÁFORO IA: Guarda los IDs de los servicios que están siendo procesados // 🛑 SEMÁFORO IA: Guarda los IDs de los servicios que están siendo procesados
@@ -1060,6 +1058,8 @@ ALTER TABLE protection_subscriptions ALTER COLUMN status SET DEFAULT 'pendiente_
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='scraped_services' AND column_name='automation_status') THEN ALTER TABLE scraped_services ADD COLUMN automation_status TEXT DEFAULT 'manual'; END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='scraped_services' AND column_name='automation_status') THEN ALTER TABLE scraped_services ADD COLUMN automation_status TEXT DEFAULT 'manual'; END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='scraped_services' AND column_name='closed_at') THEN ALTER TABLE scraped_services ADD COLUMN closed_at TIMESTAMP; END IF;
-- AÑADIDO: Token mágico para el Portal del Cliente -- AÑADIDO: Token mágico para el Portal del Cliente
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='clients' AND column_name='portal_token') THEN IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='clients' AND column_name='portal_token') THEN
ALTER TABLE clients ADD COLUMN portal_token TEXT UNIQUE; ALTER TABLE clients ADD COLUMN portal_token TEXT UNIQUE;
@@ -3850,8 +3850,8 @@ app.put('/providers/scraped/:id', authMiddleware, async (req, res) => {
const mainStatus = isFinal ? 'archived' : 'imported'; const mainStatus = isFinal ? 'archived' : 'imported';
await pool.query( await pool.query(
`UPDATE scraped_services SET raw_data = $1, assigned_to = $2, is_urgent = $3, status = $6 WHERE id = $4 AND owner_id = $5`, `UPDATE scraped_services SET raw_data = $1, assigned_to = $2, is_urgent = $3, status = $6, closed_at = CASE WHEN $7 THEN COALESCE(closed_at, NOW()) ELSE NULL END WHERE id = $4 AND owner_id = $5`,
[JSON.stringify(updatedRawData), finalAssignedTo, isUrgentFinal, id, req.user.accountId, mainStatus] [JSON.stringify(updatedRawData), finalAssignedTo, isUrgentFinal, id, req.user.accountId, mainStatus, isFinal]
); );
// BANDERAS INTELIGENTES // BANDERAS INTELIGENTES
@@ -4780,12 +4780,15 @@ function calculateScore(services) {
let scoreCierre = 0; let scoreCierre = 0;
if (closedLast30Days.length > 0) { if (closedLast30Days.length > 0) {
let totalDaysToClose = 0; let totalDaysToClose = 0;
let closedWithTimestamp = 0;
closedLast30Days.forEach(s => { closedLast30Days.forEach(s => {
if (!s.closed_at) return; // 🟢 FIX: sin fecha real de cierre (servicio cerrado antes de esta corrección), no lo contamos
const created = new Date(s.created_at); const created = new Date(s.created_at);
const closed = new Date(); // Estimamos el cierre en el ciclo actual const closed = new Date(s.closed_at); // 🟢 FIX: usamos la fecha real de cierre, no "ahora"
totalDaysToClose += Math.max(1, (closed - created) / (1000 * 60 * 60 * 24)); totalDaysToClose += Math.max(1, (closed - created) / (1000 * 60 * 60 * 24));
closedWithTimestamp++;
}); });
const avgCloseDays = totalDaysToClose / closedLast30Days.length; const avgCloseDays = closedWithTimestamp > 0 ? (totalDaysToClose / closedWithTimestamp) : 999;
if (avgCloseDays <= 2) scoreCierre = 30; if (avgCloseDays <= 2) scoreCierre = 30;
else if (avgCloseDays >= 14) scoreCierre = 0; else if (avgCloseDays >= 14) scoreCierre = 0;
@@ -4865,7 +4868,7 @@ app.get("/ranking", authMiddleware, async (req, res) => {
try { try {
// CORRECCIÓN: Hemos quitado "updated_at" de aquí para evitar que la base de datos se queje // CORRECCIÓN: Hemos quitado "updated_at" de aquí para evitar que la base de datos se queje
const q = await pool.query(` const q = await pool.query(`
SELECT id, created_at, raw_data, SELECT id, created_at, closed_at, raw_data,
(SELECT is_final FROM service_statuses WHERE id::text = raw_data->>'status_operativo') as is_final (SELECT is_final FROM service_statuses WHERE id::text = raw_data->>'status_operativo') as is_final
FROM scraped_services FROM scraped_services
WHERE assigned_to = $1 WHERE assigned_to = $1
@@ -7154,444 +7157,5 @@ setInterval(async () => {
} }
}, 60000); // Se ejecuta en bucle cada 60.000 milisegundos (1 minuto) }, 60000); // Se ejecuta en bucle cada 60.000 milisegundos (1 minuto)
// ============================================
// 💡 COMPARADOR DE FACTURAS DE LUZ (marsalva.es)
// ============================================
// Fase 1: el cliente sube su factura, nosotros extraemos los datos con IA,
// recalculamos con nuestras propias fórmulas (la IA NUNCA calcula importes),
// comparamos contra nuestras tarifas propias y avisamos a Marco por WhatsApp.
// El archivo subido nunca se guarda en disco: se procesa en memoria y se descarta.
pool.query(`
CREATE TABLE IF NOT EXISTS energy_tariffs (
id SERIAL PRIMARY KEY,
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
tipo TEXT DEFAULT 'propia', -- 'propia' | 'repsol' | 'mercado'
nombre TEXT NOT NULL,
comercializadora TEXT,
precio_potencia_p1 NUMERIC NOT NULL DEFAULT 0, -- €/kW·día
precio_potencia_p2 NUMERIC NOT NULL DEFAULT 0, -- €/kW·día
precio_energia_punta NUMERIC NOT NULL DEFAULT 0, -- €/kWh
precio_energia_llano NUMERIC NOT NULL DEFAULT 0, -- €/kWh (si no hay periodos, usar el mismo valor en los 3)
precio_energia_valle NUMERIC NOT NULL DEFAULT 0, -- €/kWh
descuento_pct NUMERIC NOT NULL DEFAULT 0, -- % único combinado sobre la energía
bono_social_dia NUMERIC NOT NULL DEFAULT 0,
alquiler_contador_dia NUMERIC NOT NULL DEFAULT 0,
notas TEXT,
activa BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS energy_settings (
owner_id INT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
iee_pct NUMERIC NOT NULL DEFAULT 5.1126963,
iva_pct NUMERIC NOT NULL DEFAULT 21,
openai_model TEXT,
cnmc_enabled BOOLEAN DEFAULT TRUE,
admin_whatsapp TEXT,
updated_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS energy_quote_leads (
id SERIAL PRIMARY KEY,
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
email TEXT NOT NULL,
telefono TEXT NOT NULL,
codigo_postal TEXT,
rgpd_aceptado BOOLEAN NOT NULL DEFAULT FALSE,
rgpd_fecha TIMESTAMP,
factura_json JSONB, -- datos extraídos por la IA (sin PII: sin nombre/DNI/dirección/IBAN/CUPS)
total_real NUMERIC,
total_recalculado NUMERIC,
diferencia NUMERIC,
revisar_manualmente BOOLEAN DEFAULT FALSE,
mejor_tarifa_id INT REFERENCES energy_tariffs(id),
ahorro_estimado_factura NUMERIC,
ahorro_estimado_anual NUMERIC,
comparativa_json JSONB, -- resultado completo contra todas las tarifas activas
mercado_cnmc_json JSONB, -- snapshot informativo del comparador oficial (puede ser null)
estado TEXT DEFAULT 'nuevo', -- nuevo | revisado | contactado | descartado
notificado_whatsapp BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT NOW()
);
`).catch((e) => console.error("❌ Error creando tablas de energy-quote:", e.message));
// --- Límite de peticiones por IP para el endpoint público (anti-abuso) ---
const energyQuoteLimiter = rateLimit({
windowMs: 60 * 60 * 1000, // 1 hora
max: 5,
standardHeaders: true,
legacyHeaders: false,
message: { ok: false, error: "Demasiadas solicitudes. Inténtalo de nuevo en un rato." },
});
const ENERGY_ALLOWED_MIME = new Set(["application/pdf", "image/jpeg", "image/jpg", "image/png"]);
const ENERGY_MAX_FILE_BYTES = 6 * 1024 * 1024; // 6MB (con base64 ~8MB, dentro del límite de express.json de 10mb)
// --- Motor de cálculo (TODO lo monetario lo hace nuestro código, nunca la IA) ---
// NOTA sobre "descuentos": el enunciado original decía "Base IEE = potencia + energía
// − descuentos + bono social", pero "energía" ya lleva el descuento restado una vez
// (Energía = kWh × precio − descuentos). Validado numéricamente contra la factura de
// referencia de Endesa (10%+10% = 20% combinado, aplicado UNA sola vez sobre la energía
// bruta): el resultado cuadra con el total real dentro de ±0,05€. Restarlo una segunda
// vez en la Base IEE se desvía más de 0,75€ del total real, así que NO se resta dos veces.
function calcularFactura(perfil, precios, ieePct = 5.1126963, ivaPct = 21) {
const dias = Number(perfil.diasFacturados) || 0;
const p1 = Number(perfil.potenciaP1Kw) || 0;
const p2 = Number(perfil.potenciaP2Kw) || 0;
const kwhPunta = Number(perfil.kwhPunta) || 0;
const kwhLlano = Number(perfil.kwhLlano) || 0;
const kwhValle = Number(perfil.kwhValle) || 0;
const potencia = p1 * (Number(precios.precioPotenciaP1) || 0) * dias
+ p2 * (Number(precios.precioPotenciaP2) || 0) * dias;
const energiaBruta = kwhPunta * (Number(precios.precioEnergiaPunta) || 0)
+ kwhLlano * (Number(precios.precioEnergiaLlano) || 0)
+ kwhValle * (Number(precios.precioEnergiaValle) || 0);
const descuentoPct = Number(precios.descuentoPct) || 0;
const descuento = energiaBruta * (descuentoPct / 100);
const energia = energiaBruta - descuento;
const bonoSocial = dias * (Number(precios.bonoSocialDia) || 0);
const baseIEE = potencia + energia + bonoSocial;
const iee = baseIEE * (Number(ieePct) / 100);
const alquilerContador = dias * (Number(precios.alquilerContadorDia) || 0);
const baseIva = baseIEE + iee + alquilerContador;
const iva = baseIva * (Number(ivaPct) / 100);
const total = baseIva + iva;
const round2 = (n) => Math.round(n * 100) / 100;
return {
potencia: round2(potencia),
energiaBruta: round2(energiaBruta),
descuento: round2(descuento),
energia: round2(energia),
bonoSocial: round2(bonoSocial),
baseIEE: round2(baseIEE),
iee: round2(iee),
alquilerContador: round2(alquilerContador),
iva: round2(iva),
total: round2(total),
};
}
// --- Consulta best-effort al comparador oficial del CNMC (informativa, nunca bloqueante) ---
async function consultarOfertasCNMC(perfil, codigoPostal) {
try {
const dias = Number(perfil.diasFacturados) || 30;
const kwhPunta = Number(perfil.kwhPunta) || 0;
const kwhLlano = Number(perfil.kwhLlano) || 0;
const kwhValle = Number(perfil.kwhValle) || 0;
const kwhTotal = kwhPunta + kwhLlano + kwhValle;
const anual = (n) => Math.round((n / dias) * 365);
const p1 = Number(perfil.potenciaP1Kw) || 0;
const p2 = Number(perfil.potenciaP2Kw) || 0;
const ahora = Date.now();
const unAnioMs = 365 * 24 * 60 * 60 * 1000;
const params = new URLSearchParams({
tipoSuministro: "E",
codigoPostal: String(codigoPostal || ""),
potencia: String(Math.max(p1, p2)),
potenciaPrimeraFranja: String(p1),
potenciaSegundaFranja: String(p2),
consumoAnualE: String(anual(kwhTotal)),
consumoPrimeraFranja: String(anual(kwhPunta)),
consumoSegundaFranja: String(anual(kwhLlano)),
consumoTerceraFranja: String(anual(kwhValle)),
tarifa: "4",
serviciosAdicionales: "2",
permanencia: "2",
vivienda: "true",
factura: "true",
revisionPrecios: "2",
dateInicio: String(ahora),
dateFin: String(ahora + unAnioMs),
perfilConsumo: "13",
cups: "0000",
autoconsumo: "false",
});
const url = `https://comparador.cnmc.gob.es/api/publico/ofertas/electricidad?${params.toString()}`;
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 4000);
const resp = await fetch(url, { signal: controller.signal });
clearTimeout(timeout);
if (!resp.ok) return null;
const data = await resp.json();
const ofertas = Array.isArray(data.resultadoComparador) ? data.resultadoComparador : [];
return ofertas
.slice()
.sort((a, b) => (a.importePrimerAnio || 0) - (b.importePrimerAnio || 0))
.slice(0, 5)
.map((o) => ({
comercializadora: o.comercializadora,
oferta: o.oferta,
importePrimerAnio: o.importePrimerAnio,
importeSegundoAnio: o.importeSegundoAnio,
verde: !!o.verde,
penalizacion: !!o.penalizacion,
}));
} catch (e) {
console.warn("⚠️ CNMC no disponible (no bloqueante):", e.message);
return null;
}
}
// --- Extracción de la factura con OpenAI (visión). NUNCA extrae nombre/DNI/dirección/IBAN/CUPS ---
async function extraerFacturaConIA(archivoBase64, archivoMime) {
const systemPrompt = `Eres un extractor de datos de facturas eléctricas españolas. Responde SOLO un JSON con
estas claves exactas (usa null si un dato no aparece; no inventes ni deduzcas nada):
comercializadora, tarifa_acceso, dias_facturados, potencia_p1_kw, potencia_p2_kw,
precio_potencia_p1, precio_potencia_p2, kwh_punta, kwh_llano, kwh_valle, precio_energia_punta,
precio_energia_llano, precio_energia_valle, descuento_pct, descuento_aplica_a,
alquiler_contador_dia, bono_social_dia, total_factura, permanencia, permanencia_fecha_fin.
IMPORTANTE: NUNCA extraigas ni menciones nombre, DNI, dirección, IBAN ni CUPS, aunque aparezcan
en la factura. No incluyas esas claves en el JSON bajo ningún concepto.`;
const modelo = process.env.OPENAI_MODEL_FACTURAS || process.env.OPENAI_MODEL || "gpt-4o-mini";
const dataUrl = `data:${archivoMime};base64,${archivoBase64}`;
const esPdf = archivoMime === "application/pdf";
const userContent = esPdf
? [
{ type: "text", text: "Extrae los datos de esta factura (PDF) según las instrucciones." },
{ type: "file", file: { filename: "factura.pdf", file_data: dataUrl } },
]
: [
{ type: "text", text: "Extrae los datos de esta factura (foto) según las instrucciones." },
{ type: "image_url", image_url: { url: dataUrl } },
];
const completion = await openai.chat.completions.create({
model: modelo,
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: userContent },
],
response_format: { type: "json_object" },
temperature: 0,
});
try {
return JSON.parse(completion.choices?.[0]?.message?.content || "{}");
} catch {
return {};
}
}
// --- Endpoint público: el cliente sube su factura desde marsalva.es (Portal con iframe) ---
app.post("/public/energy-quote", energyQuoteLimiter, async (req, res) => {
try {
const { email, telefono, codigoPostal, rgpdAceptado, honeypot, archivoBase64, archivoMime } = req.body || {};
// Honeypot: si un bot rellena este campo oculto, respondemos "éxito" genérico sin procesar nada.
if (honeypot) {
return res.json({ ok: true, message: "Hemos recibido tu factura, te enviamos el estudio en menos de 24h." });
}
if (!email || !telefono || !rgpdAceptado) {
return res.status(400).json({ ok: false, error: "Faltan datos obligatorios o no se aceptó la política de privacidad." });
}
if (!archivoBase64 || !archivoMime || !ENERGY_ALLOWED_MIME.has(archivoMime)) {
return res.status(400).json({ ok: false, error: "Formato de archivo no soportado (solo PDF, JPG o PNG)." });
}
const tamanoBytes = Buffer.byteLength(archivoBase64, "base64");
if (tamanoBytes > ENERGY_MAX_FILE_BYTES) {
return res.status(400).json({ ok: false, error: "El archivo es demasiado grande (máximo 6MB)." });
}
const ownerId = Number(process.env.ENERGY_QUOTE_OWNER_ID);
if (!ownerId) {
console.error("❌ ENERGY_QUOTE_OWNER_ID no configurado: el comparador de luz no puede guardar leads.");
return res.status(503).json({ ok: false, error: "Comparador no disponible temporalmente." });
}
// 1) Extraer con IA (el archivo solo vive en esta variable, nunca se escribe a disco)
let extraido = await extraerFacturaConIA(archivoBase64, archivoMime);
// Por si la IA ignora la instrucción: nos aseguramos de no guardar nunca estos campos.
delete extraido.nombre; delete extraido.dni; delete extraido.direccion; delete extraido.iban; delete extraido.cups;
const settingsQ = await pool.query("SELECT * FROM energy_settings WHERE owner_id=$1", [ownerId]);
const settings = settingsQ.rows[0] || {};
const ieePct = settings.iee_pct ?? 5.1126963;
const ivaPct = settings.iva_pct ?? 21;
const perfil = {
diasFacturados: extraido.dias_facturados,
potenciaP1Kw: extraido.potencia_p1_kw,
potenciaP2Kw: extraido.potencia_p2_kw,
kwhPunta: extraido.kwh_punta,
kwhLlano: extraido.kwh_llano,
kwhValle: extraido.kwh_valle,
};
// 2) Recalcular la factura actual con sus propios precios extraídos, y reconciliar (±1€)
const preciosActuales = {
precioPotenciaP1: extraido.precio_potencia_p1,
precioPotenciaP2: extraido.precio_potencia_p2,
precioEnergiaPunta: extraido.precio_energia_punta,
precioEnergiaLlano: extraido.precio_energia_llano,
precioEnergiaValle: extraido.precio_energia_valle,
descuentoPct: extraido.descuento_pct,
bonoSocialDia: extraido.bono_social_dia,
alquilerContadorDia: extraido.alquiler_contador_dia,
};
const recalculado = calcularFactura(perfil, preciosActuales, ieePct, ivaPct);
const totalReal = Number(extraido.total_factura) || null;
const diferencia = totalReal != null ? Math.round((recalculado.total - totalReal) * 100) / 100 : null;
const revisarManualmente = totalReal == null || Math.abs(diferencia) > 1;
// 3) Comparar contra todas las tarifas activas (propias + Repsol + mercado que haya cargado a mano)
const tarifasQ = await pool.query("SELECT * FROM energy_tariffs WHERE owner_id=$1 AND activa=TRUE", [ownerId]);
const comparativa = tarifasQ.rows.map((tarifa) => {
const calculo = calcularFactura(perfil, {
precioPotenciaP1: tarifa.precio_potencia_p1,
precioPotenciaP2: tarifa.precio_potencia_p2,
precioEnergiaPunta: tarifa.precio_energia_punta,
precioEnergiaLlano: tarifa.precio_energia_llano,
precioEnergiaValle: tarifa.precio_energia_valle,
descuentoPct: tarifa.descuento_pct,
bonoSocialDia: tarifa.bono_social_dia,
alquilerContadorDia: tarifa.alquiler_contador_dia,
}, ieePct, ivaPct);
const base = totalReal != null ? totalReal : recalculado.total;
const ahorroFactura = Math.round((base - calculo.total) * 100) / 100;
const dias = Number(perfil.diasFacturados) || 30;
const ahorroAnual = Math.round((ahorroFactura / dias) * 365 * 100) / 100;
return { tarifaId: tarifa.id, nombre: tarifa.nombre, tipo: tarifa.tipo, comercializadora: tarifa.comercializadora, total: calculo.total, ahorroFactura, ahorroAnual };
}).sort((a, b) => b.ahorroFactura - a.ahorroFactura);
const mejor = comparativa[0] || null;
// 4) Mercado oficial (CNMC) - informativo, nunca bloquea el estudio si falla
const mercadoCnmc = settings.cnmc_enabled === false ? null : await consultarOfertasCNMC(perfil, codigoPostal);
// 5) Guardar el lead
const leadQ = await pool.query(
`INSERT INTO energy_quote_leads
(owner_id, email, telefono, codigo_postal, rgpd_aceptado, rgpd_fecha, factura_json, total_real,
total_recalculado, diferencia, revisar_manualmente, mejor_tarifa_id, ahorro_estimado_factura,
ahorro_estimado_anual, comparativa_json, mercado_cnmc_json)
VALUES ($1,$2,$3,$4,$5,NOW(),$6,$7,$8,$9,$10,$11,$12,$13,$14,$15)
RETURNING id`,
[ownerId, email, telefono, codigoPostal || null, true, JSON.stringify(extraido), totalReal,
recalculado.total, diferencia, revisarManualmente, mejor?.tarifaId || null, mejor?.ahorroFactura || null,
mejor?.ahorroAnual || null, JSON.stringify(comparativa), mercadoCnmc ? JSON.stringify(mercadoCnmc) : null]
);
// 6) Avisar a Marco por WhatsApp (reutilizando la integración Evolution ya existente)
const adminPhoneRaw = settings.admin_whatsapp || process.env.ENERGY_ADMIN_WHATSAPP || "";
const adminPhone = adminPhoneRaw.replace("+", "");
if (adminPhone && process.env.EVOLUTION_INSTANCE) {
const aviso = revisarManualmente
? `⚠️ Nuevo lead comparador de luz (REVISAR MANUALMENTE)\nEmail: ${email}\nTel: ${telefono}\nLa factura no cuadra con el recálculo (dif: ${diferencia ?? "N/D"}€).`
: `💡 Nuevo lead comparador de luz\nEmail: ${email}\nTel: ${telefono}\nMejor tarifa: ${mejor?.nombre || "N/D"} (ahorro ${mejor?.ahorroFactura ?? "N/D"}€/factura, ${mejor?.ahorroAnual ?? "N/D"}€/año)`;
sendWhatsAppAuto(adminPhone, aviso, process.env.EVOLUTION_INSTANCE, false).catch(console.error);
}
res.json({ ok: true, message: "Hemos recibido tu factura, te enviamos el estudio en menos de 24h.", leadId: leadQ.rows[0].id });
} catch (e) {
console.error("❌ Error en /public/energy-quote:", e.message);
res.status(500).json({ ok: false, error: "No hemos podido procesar tu factura. Inténtalo de nuevo." });
}
});
// --- Panel admin: tarifas propias/Repsol/mercado ---
app.get("/energy-tariffs", authMiddleware, async (req, res) => {
try {
const q = await pool.query("SELECT * FROM energy_tariffs WHERE owner_id=$1 ORDER BY tipo ASC, nombre ASC", [req.user.accountId]);
res.json({ ok: true, tarifas: q.rows });
} catch (e) { res.status(500).json({ ok: false }); }
});
app.post("/energy-tariffs", authMiddleware, async (req, res) => {
try {
const b = req.body || {};
const q = await pool.query(
`INSERT INTO energy_tariffs
(owner_id, tipo, nombre, comercializadora, precio_potencia_p1, precio_potencia_p2,
precio_energia_punta, precio_energia_llano, precio_energia_valle, descuento_pct,
bono_social_dia, alquiler_contador_dia, notas, activa)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14) RETURNING id`,
[req.user.accountId, b.tipo || "propia", b.nombre, b.comercializadora || null,
b.precioPotenciaP1 || 0, b.precioPotenciaP2 || 0, b.precioEnergiaPunta || 0,
b.precioEnergiaLlano || 0, b.precioEnergiaValle || 0, b.descuentoPct || 0,
b.bonoSocialDia || 0, b.alquilerContadorDia || 0, b.notas || null, b.activa !== false]
);
res.json({ ok: true, id: q.rows[0].id });
} catch (e) { res.status(500).json({ ok: false }); }
});
app.put("/energy-tariffs/:id", authMiddleware, async (req, res) => {
try {
const b = req.body || {};
await pool.query(
`UPDATE energy_tariffs SET tipo=$1, nombre=$2, comercializadora=$3, precio_potencia_p1=$4,
precio_potencia_p2=$5, precio_energia_punta=$6, precio_energia_llano=$7, precio_energia_valle=$8,
descuento_pct=$9, bono_social_dia=$10, alquiler_contador_dia=$11, notas=$12, activa=$13, updated_at=NOW()
WHERE id=$14 AND owner_id=$15`,
[b.tipo || "propia", b.nombre, b.comercializadora || null, b.precioPotenciaP1 || 0, b.precioPotenciaP2 || 0,
b.precioEnergiaPunta || 0, b.precioEnergiaLlano || 0, b.precioEnergiaValle || 0, b.descuentoPct || 0,
b.bonoSocialDia || 0, b.alquilerContadorDia || 0, b.notas || null, b.activa !== false,
req.params.id, req.user.accountId]
);
res.json({ ok: true });
} catch (e) { res.status(500).json({ ok: false }); }
});
app.delete("/energy-tariffs/:id", authMiddleware, async (req, res) => {
try {
await pool.query("DELETE FROM energy_tariffs 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 }); }
});
// --- Panel admin: leads del comparador ---
app.get("/energy-leads", authMiddleware, async (req, res) => {
try {
const q = await pool.query("SELECT * FROM energy_quote_leads WHERE owner_id=$1 ORDER BY created_at DESC LIMIT 200", [req.user.accountId]);
res.json({ ok: true, leads: q.rows });
} catch (e) { res.status(500).json({ ok: false }); }
});
app.patch("/energy-leads/:id", authMiddleware, async (req, res) => {
try {
const { estado } = req.body || {};
await pool.query("UPDATE energy_quote_leads SET estado=$1 WHERE id=$2 AND owner_id=$3", [estado, req.params.id, req.user.accountId]);
res.json({ ok: true });
} catch (e) { res.status(500).json({ ok: false }); }
});
// --- Panel admin: ajustes (IEE, IVA, modelo IA, WhatsApp de aviso, activar/desactivar CNMC) ---
app.get("/energy-settings", authMiddleware, async (req, res) => {
try {
const q = await pool.query("SELECT * FROM energy_settings WHERE owner_id=$1", [req.user.accountId]);
res.json({ ok: true, settings: q.rows[0] || null });
} catch (e) { res.status(500).json({ ok: false }); }
});
app.put("/energy-settings", authMiddleware, async (req, res) => {
try {
const b = req.body || {};
await pool.query(
`INSERT INTO energy_settings (owner_id, iee_pct, iva_pct, openai_model, cnmc_enabled, admin_whatsapp, updated_at)
VALUES ($1,$2,$3,$4,$5,$6,NOW())
ON CONFLICT (owner_id) DO UPDATE SET iee_pct=$2, iva_pct=$3, openai_model=$4, cnmc_enabled=$5, admin_whatsapp=$6, updated_at=NOW()`,
[req.user.accountId, b.ieePct ?? 5.1126963, b.ivaPct ?? 21, b.openaiModel || null, b.cnmcEnabled !== false, b.adminWhatsapp || null]
);
res.json({ ok: true });
} catch (e) { res.status(500).json({ ok: false }); }
});
const port = process.env.PORT || 3000; const port = process.env.PORT || 3000;
autoUpdateDB().then(() => { app.listen(port, "0.0.0.0", () => console.log(`🚀 Server OK en puerto ${port}`)); }); autoUpdateDB().then(() => { app.listen(port, "0.0.0.0", () => console.log(`🚀 Server OK en puerto ${port}`)); });