Añade generación y envío por WhatsApp del PDF detallado de la comparativa de luz (logo Marsalva + Repsol)
This commit is contained in:
283
server.js
283
server.js
@@ -8,8 +8,14 @@ import crypto from "crypto";
|
||||
import OpenAI from "openai";
|
||||
import Stripe from "stripe";
|
||||
import rateLimit from "express-rate-limit";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
import { PDFDocument, StandardFonts, rgb } from "pdf-lib";
|
||||
|
||||
const { Pool } = pg;
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
const app = express();
|
||||
app.set("trust proxy", 1); // Necesario para express-rate-limit detrás del proxy de Coolify
|
||||
|
||||
@@ -1025,6 +1031,14 @@ ALTER TABLE protection_subscriptions ALTER COLUMN status SET DEFAULT 'pendiente_
|
||||
ALTER TABLE users ADD COLUMN portal_settings JSONB DEFAULT '{"m_start":"09:00", "m_end":"14:00", "a_start":"16:00", "a_end":"19:00"}';
|
||||
END IF;
|
||||
|
||||
// AÑADIDO: Guarda si ya se envió el PDF de la comparativa de luz al cliente
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='energy_quote_leads' AND column_name='pdf_enviado') THEN
|
||||
ALTER TABLE energy_quote_leads ADD COLUMN pdf_enviado BOOLEAN DEFAULT FALSE;
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='energy_quote_leads' AND column_name='pdf_enviado_at') THEN
|
||||
ALTER TABLE energy_quote_leads ADD COLUMN pdf_enviado_at TIMESTAMP;
|
||||
END IF;
|
||||
|
||||
-- AÑADIDO: Columna física de operario para el panel operativo
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='scraped_services' AND column_name='assigned_to') THEN
|
||||
ALTER TABLE scraped_services ADD COLUMN assigned_to INT REFERENCES users(id);
|
||||
@@ -7573,6 +7587,275 @@ app.patch("/energy-leads/:id", authMiddleware, async (req, res) => {
|
||||
} catch (e) { res.status(500).json({ ok: false }); }
|
||||
});
|
||||
|
||||
|
||||
// =====================================================================
|
||||
// Comparador de luz: generación del PDF detallado de la comparativa
|
||||
// (con logo de Marsalva y, si la mejor tarifa es de Repsol, su logo)
|
||||
// y envío por WhatsApp al cliente desde el panel de leads.
|
||||
// =====================================================================
|
||||
|
||||
const MARSALVA_LOGO_PATH = path.join(__dirname, "assets", "logos", "marsalva.png");
|
||||
const REPSOL_LOGO_PATH = path.join(__dirname, "assets", "logos", "repsol.png");
|
||||
|
||||
const PDF_COLOR_DARK = rgb(0x0f / 255, 0x17 / 255, 0x2a / 255);
|
||||
const PDF_COLOR_GRAY = rgb(0x64 / 255, 0x74 / 255, 0x8b / 255);
|
||||
const PDF_COLOR_LIGHT_GRAY = rgb(0xe2 / 255, 0xe8 / 255, 0xf0 / 255);
|
||||
const PDF_COLOR_GREEN = rgb(0x05 / 255, 0x96 / 255, 0x69 / 255);
|
||||
const PDF_COLOR_GREEN_BG = rgb(0xec / 255, 0xfd / 255, 0xf5 / 255);
|
||||
const PDF_COLOR_AMBER = rgb(0xb4 / 255, 0x53 / 255, 0x09 / 255);
|
||||
const PDF_COLOR_AMBER_BG = rgb(0xff / 255, 0xfb / 255, 0xeb / 255);
|
||||
|
||||
function pdfFmtEuro(n) {
|
||||
if (n === null || n === undefined || n === "") return "—";
|
||||
return Number(n).toLocaleString("es-ES", { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + " €";
|
||||
}
|
||||
function pdfFmtVal(v) {
|
||||
if (v === null || v === undefined || v === "") return "—";
|
||||
return String(v);
|
||||
}
|
||||
|
||||
async function embedLogoIfExists(pdfDoc, logoPath) {
|
||||
try {
|
||||
if (!logoPath || !fs.existsSync(logoPath)) return null;
|
||||
const bytes = fs.readFileSync(logoPath);
|
||||
if (logoPath.toLowerCase().endsWith(".jpg") || logoPath.toLowerCase().endsWith(".jpeg")) {
|
||||
return await pdfDoc.embedJpg(bytes);
|
||||
}
|
||||
return await pdfDoc.embedPng(bytes);
|
||||
} catch (e) {
|
||||
console.error("No se pudo incrustar el logo", logoPath, e.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function generarPdfComparativaLuz(lead) {
|
||||
const fj = lead.factura_json || {};
|
||||
const comparativa = Array.isArray(lead.comparativa_json) ? lead.comparativa_json : [];
|
||||
const mejor = comparativa[0] || null;
|
||||
|
||||
const pdfDoc = await PDFDocument.create();
|
||||
const PAGE_W = 595.28, PAGE_H = 841.89; // A4
|
||||
const MARGIN = 42;
|
||||
let page = pdfDoc.addPage([PAGE_W, PAGE_H]);
|
||||
const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
|
||||
const fontBold = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
|
||||
|
||||
const marsalvaLogo = await embedLogoIfExists(pdfDoc, MARSALVA_LOGO_PATH);
|
||||
const repsolLogo = await embedLogoIfExists(pdfDoc, REPSOL_LOGO_PATH);
|
||||
|
||||
let y = PAGE_H - MARGIN;
|
||||
|
||||
function ensureSpace(h) {
|
||||
if (y - h < MARGIN + 30) {
|
||||
page = pdfDoc.addPage([PAGE_W, PAGE_H]);
|
||||
y = PAGE_H - MARGIN;
|
||||
}
|
||||
}
|
||||
|
||||
function drawText(text, x, yy, opts) {
|
||||
opts = opts || {};
|
||||
const size = opts.size || 10;
|
||||
const bold = !!opts.bold;
|
||||
const color = opts.color || PDF_COLOR_DARK;
|
||||
const align = opts.align || "left";
|
||||
const maxWidth = opts.maxWidth != null ? opts.maxWidth : null;
|
||||
const f = bold ? fontBold : font;
|
||||
let drawX = x;
|
||||
if (align === "right" && maxWidth != null) {
|
||||
const w = f.widthOfTextAtSize(text, size);
|
||||
drawX = x + maxWidth - w;
|
||||
}
|
||||
page.drawText(text, { x: drawX, y: yy, size, font: f, color });
|
||||
}
|
||||
|
||||
function wrapText(text, maxWidth, size, f) {
|
||||
const words = String(text).split(" ");
|
||||
const lines = [];
|
||||
let current = "";
|
||||
for (const w of words) {
|
||||
const test = current ? current + " " + w : w;
|
||||
if (f.widthOfTextAtSize(test, size) > maxWidth && current) {
|
||||
lines.push(current);
|
||||
current = w;
|
||||
} else {
|
||||
current = test;
|
||||
}
|
||||
}
|
||||
if (current) lines.push(current);
|
||||
return lines;
|
||||
}
|
||||
|
||||
// ---------- CABECERA ----------
|
||||
const headerH = 54;
|
||||
if (marsalvaLogo) {
|
||||
const scale = headerH / marsalvaLogo.height;
|
||||
const w = marsalvaLogo.width * scale;
|
||||
page.drawImage(marsalvaLogo, { x: MARGIN, y: y - headerH, width: w, height: headerH });
|
||||
} else {
|
||||
drawText("MARSALVA", MARGIN, y - 24, { size: 18, bold: true });
|
||||
}
|
||||
y -= headerH + 14;
|
||||
|
||||
page.drawLine({ start: { x: MARGIN, y }, end: { x: PAGE_W - MARGIN, y }, thickness: 1, color: PDF_COLOR_LIGHT_GRAY });
|
||||
y -= 24;
|
||||
|
||||
drawText("Estudio comparativo de tu factura de luz", MARGIN, y, { size: 16, bold: true });
|
||||
y -= 16;
|
||||
const fecha = new Date().toLocaleDateString("es-ES", { day: "2-digit", month: "long", year: "numeric" });
|
||||
drawText(`Fecha del estudio: ${fecha}`, MARGIN, y, { size: 9, color: PDF_COLOR_GRAY });
|
||||
y -= 28;
|
||||
|
||||
// ---------- RESUMEN DESTACADO DE AHORRO ----------
|
||||
const ahorroFactura = lead.ahorro_estimado_factura;
|
||||
const ahorroAnual = lead.ahorro_estimado_anual;
|
||||
const tieneAhorro = mejor && Number(ahorroFactura) > 0;
|
||||
|
||||
const boxH = 70;
|
||||
ensureSpace(boxH + 10);
|
||||
page.drawRectangle({
|
||||
x: MARGIN, y: y - boxH, width: PAGE_W - MARGIN * 2, height: boxH,
|
||||
color: tieneAhorro ? PDF_COLOR_GREEN_BG : PDF_COLOR_AMBER_BG,
|
||||
borderColor: tieneAhorro ? PDF_COLOR_GREEN : PDF_COLOR_AMBER,
|
||||
borderWidth: 1,
|
||||
});
|
||||
if (tieneAhorro) {
|
||||
drawText(`Mejor opción encontrada: ${mejor.nombre}`, MARGIN + 16, y - 24, { size: 12, bold: true, color: PDF_COLOR_GREEN });
|
||||
drawText(`Ahorro estimado: ${pdfFmtEuro(ahorroFactura)} en esta factura • ${pdfFmtEuro(ahorroAnual)} al año`, MARGIN + 16, y - 42, { size: 10.5, color: PDF_COLOR_DARK });
|
||||
if (repsolLogo && /repsol/i.test(mejor.nombre || "")) {
|
||||
const rh = 28;
|
||||
const rw = repsolLogo.width * (rh / repsolLogo.height);
|
||||
page.drawImage(repsolLogo, { x: PAGE_W - MARGIN - 16 - rw, y: y - boxH / 2 - rh / 2, width: rw, height: rh });
|
||||
}
|
||||
drawText("Estudio orientativo según los datos de tu factura y las tarifas publicadas a fecha de hoy.", MARGIN + 16, y - 58, { size: 7.5, color: PDF_COLOR_GRAY });
|
||||
} else {
|
||||
drawText("Con los datos de tu factura actual, hoy no encontramos una tarifa que te suponga un ahorro claro.", MARGIN + 16, y - 24, { size: 10.5, bold: true, color: PDF_COLOR_AMBER });
|
||||
drawText("Aun así, aquí tienes el detalle completo de la comparativa realizada.", MARGIN + 16, y - 42, { size: 9.5, color: PDF_COLOR_DARK });
|
||||
}
|
||||
y -= boxH + 26;
|
||||
|
||||
// ---------- TABLA: TU FACTURA ACTUAL ----------
|
||||
ensureSpace(30);
|
||||
drawText("Tu factura actual", MARGIN, y, { size: 12.5, bold: true });
|
||||
y -= 18;
|
||||
|
||||
const filasFactura = [
|
||||
["Comercializadora", pdfFmtVal(fj.comercializadora)],
|
||||
["Tarifa de acceso", pdfFmtVal(fj.tarifa_acceso)],
|
||||
["Días facturados", pdfFmtVal(fj.dias_facturados)],
|
||||
["Potencia contratada P1 / P2 (kW)", `${pdfFmtVal(fj.potencia_p1_kw)} / ${pdfFmtVal(fj.potencia_p2_kw)}`],
|
||||
["Consumo punta / llano / valle (kWh)", `${pdfFmtVal(fj.kwh_punta)} / ${pdfFmtVal(fj.kwh_llano)} / ${pdfFmtVal(fj.kwh_valle)}`],
|
||||
["Precio energía punta / llano / valle (€/kWh)", `${pdfFmtVal(fj.precio_energia_punta)} / ${pdfFmtVal(fj.precio_energia_llano)} / ${pdfFmtVal(fj.precio_energia_valle)}`],
|
||||
["Descuento aplicado", `${fj.descuento_pct ?? 0}%${fj.descuento_aplica_a ? " (" + fj.descuento_aplica_a + ")" : ""}`],
|
||||
["Permanencia", fj.permanencia ? `${fj.permanencia}${fj.permanencia_fecha_fin ? " hasta " + fj.permanencia_fecha_fin : ""}` : "Sin permanencia"],
|
||||
["Total de la factura", pdfFmtEuro(lead.total_real)],
|
||||
];
|
||||
|
||||
const rowH = 18;
|
||||
for (const fila of filasFactura) {
|
||||
const label = fila[0], value = fila[1];
|
||||
ensureSpace(rowH);
|
||||
drawText(label, MARGIN, y, { size: 9, color: PDF_COLOR_GRAY });
|
||||
drawText(value, MARGIN, y, { size: 9, bold: true, color: PDF_COLOR_DARK, align: "right", maxWidth: PAGE_W - MARGIN * 2 });
|
||||
y -= rowH;
|
||||
page.drawLine({ start: { x: MARGIN, y: y + 5 }, end: { x: PAGE_W - MARGIN, y: y + 5 }, thickness: 0.5, color: PDF_COLOR_LIGHT_GRAY });
|
||||
}
|
||||
y -= 16;
|
||||
|
||||
// ---------- TABLA: COMPARATIVA DE TARIFAS ----------
|
||||
ensureSpace(30);
|
||||
drawText("Comparativa con tarifas disponibles", MARGIN, y, { size: 12.5, bold: true });
|
||||
y -= 20;
|
||||
|
||||
if (comparativa.length === 0) {
|
||||
drawText("No había tarifas activas para comparar en el momento del estudio.", MARGIN, y, { size: 9.5, color: PDF_COLOR_GRAY });
|
||||
y -= 20;
|
||||
} else {
|
||||
const colTarifaW = 205, colTotalW = 95, colAhorroFW = 100, colAhorroAW = 101;
|
||||
ensureSpace(20);
|
||||
drawText("Tarifa", MARGIN, y, { size: 8.5, bold: true, color: PDF_COLOR_GRAY });
|
||||
drawText("Total/factura", MARGIN + colTarifaW, y, { size: 8.5, bold: true, color: PDF_COLOR_GRAY, align: "right", maxWidth: colTotalW });
|
||||
drawText("Ahorro/factura", MARGIN + colTarifaW + colTotalW, y, { size: 8.5, bold: true, color: PDF_COLOR_GRAY, align: "right", maxWidth: colAhorroFW });
|
||||
drawText("Ahorro/año", MARGIN + colTarifaW + colTotalW + colAhorroFW, y, { size: 8.5, bold: true, color: PDF_COLOR_GRAY, align: "right", maxWidth: colAhorroAW });
|
||||
y -= 14;
|
||||
page.drawLine({ start: { x: MARGIN, y: y + 6 }, end: { x: PAGE_W - MARGIN, y: y + 6 }, thickness: 0.75, color: PDF_COLOR_DARK });
|
||||
y -= 6;
|
||||
|
||||
comparativa.slice(0, 8).forEach((c, i) => {
|
||||
ensureSpace(20);
|
||||
const isWinner = i === 0;
|
||||
if (isWinner) {
|
||||
page.drawRectangle({ x: MARGIN - 4, y: y - 5, width: PAGE_W - MARGIN * 2 + 8, height: 17, color: PDF_COLOR_GREEN_BG });
|
||||
}
|
||||
const prefijo = isWinner ? "MEJOR: " : "";
|
||||
let nombre = prefijo + (c.nombre || "—");
|
||||
const fUsada = isWinner ? fontBold : font;
|
||||
const maxW = colTarifaW - 4;
|
||||
if (fUsada.widthOfTextAtSize(nombre, 9) > maxW) {
|
||||
while (nombre.length > prefijo.length + 1 && fUsada.widthOfTextAtSize(nombre + "…", 9) > maxW) {
|
||||
nombre = nombre.slice(0, -1);
|
||||
}
|
||||
nombre += "…";
|
||||
}
|
||||
drawText(nombre, MARGIN, y, { size: 9, bold: isWinner, color: isWinner ? PDF_COLOR_GREEN : PDF_COLOR_DARK });
|
||||
drawText(pdfFmtEuro(c.total), MARGIN + colTarifaW, y, { size: 9, bold: isWinner, color: isWinner ? PDF_COLOR_GREEN : PDF_COLOR_DARK, align: "right", maxWidth: colTotalW });
|
||||
const signoF = Number(c.ahorroFactura) >= 0 ? "+" : "";
|
||||
const signoA = Number(c.ahorroAnual) >= 0 ? "+" : "";
|
||||
drawText(`${signoF}${pdfFmtEuro(c.ahorroFactura)}`, MARGIN + colTarifaW + colTotalW, y, { size: 9, bold: isWinner, color: isWinner ? PDF_COLOR_GREEN : PDF_COLOR_DARK, align: "right", maxWidth: colAhorroFW });
|
||||
drawText(`${signoA}${pdfFmtEuro(c.ahorroAnual)}`, MARGIN + colTarifaW + colTotalW + colAhorroFW, y, { size: 9, bold: isWinner, color: isWinner ? PDF_COLOR_GREEN : PDF_COLOR_DARK, align: "right", maxWidth: colAhorroAW });
|
||||
y -= 19;
|
||||
});
|
||||
y -= 10;
|
||||
}
|
||||
|
||||
// ---------- PIE ----------
|
||||
ensureSpace(60);
|
||||
page.drawLine({ start: { x: MARGIN, y }, end: { x: PAGE_W - MARGIN, y }, thickness: 1, color: PDF_COLOR_LIGHT_GRAY });
|
||||
y -= 16;
|
||||
const disclaimer = "Este estudio se ha generado de forma automática a partir de los datos extraídos de tu factura y de las tarifas publicadas por las compañías comparadas en la fecha indicada. Los importes son orientativos y pueden variar según condiciones particulares del contrato final.";
|
||||
const discLines = wrapText(disclaimer, PAGE_W - MARGIN * 2, 7.5, font);
|
||||
discLines.forEach((line) => {
|
||||
drawText(line, MARGIN, y, { size: 7.5, color: PDF_COLOR_GRAY });
|
||||
y -= 10;
|
||||
});
|
||||
|
||||
const bytes = await pdfDoc.save();
|
||||
return Buffer.from(bytes);
|
||||
}
|
||||
|
||||
// --- Genera el PDF de la comparativa de un lead y lo envía por WhatsApp al cliente ---
|
||||
app.post("/energy-leads/:id/send-pdf", authMiddleware, async (req, res) => {
|
||||
try {
|
||||
const ownerId = req.user.accountId;
|
||||
const q = await pool.query("SELECT * FROM energy_quote_leads WHERE id=$1 AND owner_id=$2", [req.params.id, ownerId]);
|
||||
const lead = q.rows[0];
|
||||
if (!lead) return res.status(404).json({ ok: false, detail: "Lead no encontrado" });
|
||||
if (!lead.telefono) return res.status(400).json({ ok: false, detail: "El lead no tiene teléfono guardado" });
|
||||
|
||||
const pdfBuffer = await generarPdfComparativaLuz(lead);
|
||||
const base64Pdf = pdfBuffer.toString("base64");
|
||||
|
||||
const mejor = Array.isArray(lead.comparativa_json) ? lead.comparativa_json[0] : null;
|
||||
const tieneAhorro = mejor && Number(lead.ahorro_estimado_factura) > 0;
|
||||
const caption = tieneAhorro
|
||||
? `Aquí tienes tu estudio comparativo de la factura de luz. Con ${mejor.nombre} podrías ahorrar ${Number(lead.ahorro_estimado_factura).toFixed(2)}€ en esta factura y ${Number(lead.ahorro_estimado_anual || 0).toFixed(2)}€ al año.`
|
||||
: "Aquí tienes tu estudio comparativo de la factura de luz.";
|
||||
|
||||
const instanciaEvolution = `cliente_${ownerId}`;
|
||||
const resultado = await sendWhatsAppMedia(lead.telefono, base64Pdf, "estudio-comparativa-luz.pdf", caption, instanciaEvolution);
|
||||
|
||||
if (!resultado || !resultado.ok) {
|
||||
return res.status(502).json({ ok: false, detail: (resultado && resultado.detail) || "No se pudo enviar el PDF por WhatsApp" });
|
||||
}
|
||||
|
||||
await pool.query("UPDATE energy_quote_leads SET pdf_enviado=true, pdf_enviado_at=NOW() WHERE id=$1 AND owner_id=$2", [req.params.id, ownerId]);
|
||||
|
||||
res.json({ ok: true });
|
||||
} catch (e) {
|
||||
console.error("Error enviando PDF de comparativa de luz:", e);
|
||||
res.status(500).json({ ok: false, detail: "Error generando o enviando el PDF" });
|
||||
}
|
||||
});
|
||||
|
||||
// --- Panel admin: ajustes (IEE, IVA, modelo IA, WhatsApp de aviso, activar/desactivar CNMC) ---
|
||||
app.get("/energy-settings", authMiddleware, async (req, res) => {
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user