You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
949 lines
32 KiB
949 lines
32 KiB
<script lang="ts">
|
|
import { dataConfig } from "../data/DataConfig.js";
|
|
import type { DownloadState } from "../data/DownloadTypes";
|
|
import PoDownload from "../cmps/PoDownload.svelte";
|
|
import { projectFonts } from "../data/DataFonts";
|
|
import { dataPdfImages } from "../data/DataPdfImagesB64";
|
|
import { images } from "../data/DataImagesB64";
|
|
import { jsPDF } from "jspdf";
|
|
import { appState, getViewImage } from "../data/AppState.svelte";
|
|
import { formatPrice } from "../utils/formats";
|
|
import type { View } from "../data/DataConfigTypes";
|
|
import { advertenciaIconB64 } from "../data/DataIconsB64"
|
|
|
|
// ============================================================================
|
|
// TIPOS
|
|
// ============================================================================
|
|
|
|
interface Option {
|
|
nombreGrupo: string;
|
|
nombre: string;
|
|
precio?: number | null | string;
|
|
consultar: boolean;
|
|
warning: boolean;
|
|
warningMessage?: string;
|
|
}
|
|
|
|
interface ViewOptions {
|
|
options: Option[];
|
|
total: number;
|
|
hasWarning: boolean;
|
|
hasConsult: boolean;
|
|
}
|
|
|
|
interface PDFConfig {
|
|
pageWidth: number;
|
|
pageHeight: number;
|
|
margin: number;
|
|
fonts: {
|
|
title: string;
|
|
regular: string;
|
|
bold: string;
|
|
light: string;
|
|
};
|
|
}
|
|
|
|
interface TextStyles {
|
|
group: { font: string; size: number };
|
|
option: { font: string; size: number };
|
|
price: { font: string; size: number };
|
|
}
|
|
|
|
// ============================================================================
|
|
// ESTADO
|
|
// ============================================================================
|
|
|
|
const TIPOLOGIAS = ['P2D','P3D','P4D','B2D', 'B3D', 'B4D','A4D'];
|
|
const tiposInfo : Record<string,string> = {
|
|
'P2D' :'Vivienda de 2 Dormitorios',
|
|
'P3D' :'Vivienda de 3 Dormitorios',
|
|
'P4D' :'Vivienda de 4 Dormitorios',
|
|
'B2D' :'Planta Baja de 2 Dormitorios',
|
|
'B3D' :'Planta Baja de 3 Dormitorios',
|
|
'B4D' :'Planta Baja de 4 Dormitorios',
|
|
'A4D' :'Ático de 4 Dormitorios',
|
|
}
|
|
|
|
|
|
let downloadState: DownloadState = $state('idle');
|
|
let isVisible = $state(false);
|
|
let message = $state('');
|
|
|
|
const views = appState.getAllViews();
|
|
const logoProject = dataConfig.sources.logos + dataConfig.logos.project;
|
|
const logoCompany = dataConfig.sources.logos + dataConfig.logos.company;
|
|
|
|
// ============================================================================
|
|
// HANDLERS
|
|
// ============================================================================
|
|
|
|
function openSelector() {
|
|
isVisible = true;
|
|
downloadState = 'idle';
|
|
}
|
|
|
|
function handleCancel() {
|
|
isVisible = false;
|
|
downloadState = 'idle';
|
|
}
|
|
|
|
async function handleTipologiaSelected(tipologia: string) {
|
|
downloadState = 'creating';
|
|
|
|
try {
|
|
const pdfDoc = createPDFDocument();
|
|
const config = getPDFConfig(pdfDoc);
|
|
|
|
// ✅ PRECALCULAR TODAS LAS OPCIONES UNA SOLA VEZ
|
|
|
|
const allViewOptions = precalculateAllOptions(tipologia);
|
|
|
|
registerFonts(pdfDoc);
|
|
await generatePDFContent(pdfDoc, config, tipologia, allViewOptions);
|
|
|
|
downloadState = 'downloading';
|
|
pdfDoc.save(`OPENBOX_${tipologia}_${Date.now()}.pdf`);
|
|
downloadState = 'success';
|
|
|
|
setTimeout(() => {
|
|
isVisible = false;
|
|
downloadState = 'idle';
|
|
}, 2000);
|
|
|
|
} catch (err: any) {
|
|
downloadState = 'error';
|
|
message = err?.message || 'Error desconocido al generar el PDF';
|
|
console.error('PDF Generation Error:', err);
|
|
}
|
|
}
|
|
|
|
// ============================================================================
|
|
// PRECÁLCULO DE OPCIONES (una sola vez)
|
|
// ============================================================================
|
|
|
|
interface AllViewOptions {
|
|
general: Option[];
|
|
views: Map<string, ViewOptions>;
|
|
totalGeneral: number;
|
|
}
|
|
|
|
function precalculateAllOptions(tipologia: string): AllViewOptions {
|
|
const generalOptions = getGeneralOptions(tiposInfo[tipologia]);
|
|
const viewOptionsMap = new Map<string, ViewOptions>();
|
|
let totalGeneral = 0;
|
|
|
|
views.forEach((view) => {
|
|
const viewOptions = getViewOptions(view);
|
|
viewOptionsMap.set(view.id, viewOptions);
|
|
totalGeneral += viewOptions.total;
|
|
});
|
|
|
|
return {
|
|
general: generalOptions,
|
|
views: viewOptionsMap,
|
|
totalGeneral
|
|
};
|
|
}
|
|
|
|
// ============================================================================
|
|
// CREACIÓN DE PDF
|
|
// ============================================================================
|
|
|
|
function createPDFDocument(): jsPDF {
|
|
return new jsPDF({
|
|
orientation: 'landscape',
|
|
unit: 'mm',
|
|
format: 'A4',
|
|
});
|
|
}
|
|
|
|
function getPDFConfig(pdfDoc: jsPDF): PDFConfig {
|
|
return {
|
|
pageWidth: pdfDoc.internal.pageSize.getWidth(),
|
|
pageHeight: pdfDoc.internal.pageSize.getHeight(),
|
|
margin: 15,
|
|
fonts: {
|
|
title: projectFonts['Didot'].name,
|
|
regular: projectFonts['proxima_nova_regular'].name,
|
|
bold: projectFonts['proxima_nova_bold'].name,
|
|
light: projectFonts['proxima_nova_light'].name,
|
|
}
|
|
};
|
|
}
|
|
|
|
function registerFonts(pdfDoc: jsPDF) {
|
|
const fontsToRegister = [
|
|
projectFonts['Didot'],
|
|
projectFonts['proxima_nova_regular'],
|
|
projectFonts['proxima_nova_bold'],
|
|
projectFonts['proxima_nova_light']
|
|
];
|
|
|
|
fontsToRegister.forEach(font => {
|
|
pdfDoc.addFileToVFS(font.filename, font.base64);
|
|
pdfDoc.addFont(font.filename, font.name, font.style);
|
|
});
|
|
}
|
|
|
|
async function generatePDFContent(pdfDoc: jsPDF, config: PDFConfig, tipologia: string, allOptions: AllViewOptions) {
|
|
addCoverPage(pdfDoc, config, tipologia);
|
|
addPresentationPage(pdfDoc, config);
|
|
addViewPages(pdfDoc, config, allOptions);
|
|
addSummaryPage(pdfDoc, config, allOptions);
|
|
addFinalPage(pdfDoc, config);
|
|
}
|
|
|
|
// ============================================================================
|
|
// PÁGINAS DEL PDF
|
|
// ============================================================================
|
|
|
|
function addCoverPage(pdfDoc: jsPDF, config: PDFConfig, tipologia: string) {
|
|
const coverImage = dataPdfImages['pdf_openbox_ini'];
|
|
if (!coverImage) return;
|
|
|
|
const format = coverImage.includes('jpeg') ? 'JPEG' : 'PNG';
|
|
pdfDoc.addImage(coverImage, format, 0, 0, config.pageWidth, config.pageHeight, '', 'FAST');
|
|
|
|
pdfDoc.setFontSize(20);
|
|
pdfDoc.setFont(config.fonts.bold, "normal");
|
|
pdfDoc.text(tipologia.toUpperCase(), 265, 119);
|
|
|
|
pdfDoc.addPage();
|
|
}
|
|
|
|
function addPresentationPage(pdfDoc: jsPDF, config: PDFConfig) {
|
|
const cols = 3;
|
|
const spacing = 10;
|
|
const squareSize = (config.pageWidth - config.margin * 2 - spacing * (cols - 1)) / cols;
|
|
let startY = 15;
|
|
|
|
// Imagen de presentación
|
|
const preImage = dataPdfImages['pdf_openbox_pre'];
|
|
if (preImage) {
|
|
const format = preImage.includes('jpeg') ? 'JPEG' : 'PNG';
|
|
pdfDoc.addImage(preImage, format, config.margin, startY, squareSize, squareSize, '', 'FAST');
|
|
}
|
|
|
|
// Primera fila (2 vistas)
|
|
views.slice(0, 2).forEach((view, i) => {
|
|
const image = images[getViewImage(view.id)];
|
|
if (!image) return;
|
|
const x = config.margin + (i + 1) * (squareSize + spacing);
|
|
pdfDoc.addImage(image, 'JPEG', x, startY, squareSize, squareSize, '', 'FAST');
|
|
});
|
|
|
|
startY += squareSize + 14;
|
|
|
|
// Segunda fila (3 vistas)
|
|
views.slice(2, 5).forEach((view, i) => {
|
|
const image = images[getViewImage(view.id)];
|
|
if (!image) return;
|
|
const x = config.margin + i * (squareSize + spacing);
|
|
pdfDoc.addImage(image, 'JPEG', x, startY, squareSize, squareSize, '', 'FAST');
|
|
});
|
|
|
|
pdfDoc.addPage();
|
|
}
|
|
|
|
function addViewPages(pdfDoc: jsPDF, config: PDFConfig, allOptions: AllViewOptions) {
|
|
const imageRatio = 1; // 1500x1500
|
|
//const pageRatio = config.pageWidth / config.pageHeight;
|
|
|
|
views.forEach((view, index) => {
|
|
const viewImage = images[getViewImage(view.id)];
|
|
if (!viewImage) return;
|
|
|
|
// Calcular dimensiones de imagen
|
|
const renderHeight = config.pageHeight - 2 * config.margin;
|
|
const renderWidth = renderHeight * imageRatio;
|
|
const x = config.margin;
|
|
const y = (config.pageHeight - renderHeight) / 2;
|
|
|
|
// Añadir imagen
|
|
pdfDoc.addImage(viewImage, 'JPEG', x, y, renderWidth, renderHeight, '', 'FAST');
|
|
|
|
// Añadir contenido de texto
|
|
const textStartX = config.margin + renderWidth + 10;
|
|
const textMaxWidth = config.pageWidth - textStartX - config.margin;
|
|
|
|
const viewOptions = allOptions.views.get(view.id);
|
|
if (viewOptions) {
|
|
addViewContent(pdfDoc, config, view, textStartX, textMaxWidth, viewOptions);
|
|
}
|
|
|
|
// Nueva página (excepto la última)
|
|
if (index < views.length - 1) pdfDoc.addPage();
|
|
});
|
|
}
|
|
|
|
function addViewContent(pdfDoc: jsPDF, config: PDFConfig, view: View, x: number, maxWidth: number, viewOptions: ViewOptions) {
|
|
let cursorY = config.margin + 5;
|
|
|
|
// Título de la vista
|
|
pdfDoc.setFontSize(18);
|
|
pdfDoc.setFont(config.fonts.regular, "normal");
|
|
pdfDoc.setTextColor(30, 30, 30);
|
|
pdfDoc.text(view.name.toUpperCase(), x, cursorY);
|
|
|
|
// Descripción
|
|
if (view.text) {
|
|
cursorY += 8;
|
|
cursorY = addMultilineText(pdfDoc, view.text, x, cursorY, maxWidth, config.fonts.light, 12, 5);
|
|
}
|
|
|
|
// Opciones (usar las precalculadas)
|
|
if (viewOptions.options.length > 0) {
|
|
cursorY = 100;
|
|
addOptionsSection(pdfDoc, config, viewOptions, x, cursorY, maxWidth);
|
|
}
|
|
}
|
|
|
|
function addOptionsSection(pdfDoc: jsPDF, config: PDFConfig, viewOptions: ViewOptions, x: number, y: number, maxWidth: number) {
|
|
let cursorY = y;
|
|
|
|
// Título de sección
|
|
pdfDoc.setFontSize(14);
|
|
pdfDoc.setFont(config.fonts.regular, "normal");
|
|
pdfDoc.setTextColor(30, 30, 30);
|
|
pdfDoc.text('ACABADOS SELECCIONADOS', x, cursorY);
|
|
cursorY += 10;
|
|
|
|
// Estilos de texto
|
|
const styles: TextStyles = {
|
|
group: { font: config.fonts.regular, size: 11 },
|
|
option: { font: config.fonts.bold, size: 11 },
|
|
price: { font: config.fonts.regular, size: 11 }
|
|
};
|
|
|
|
// Listar opciones
|
|
viewOptions.options.forEach((option) => {
|
|
const icon = (option.warning || option.consultar) ? advertenciaIconB64 : null;
|
|
cursorY = renderOption(pdfDoc, option, x, cursorY, maxWidth, styles, icon);
|
|
});
|
|
}
|
|
|
|
|
|
function addSummaryPage(pdfDoc: jsPDF, config: PDFConfig, allOptions: AllViewOptions) {
|
|
pdfDoc.addPage();
|
|
|
|
const COLS = 5;
|
|
const MARGIN = 10;
|
|
const COL_WIDTH = (config.pageWidth - 2 * MARGIN) / COLS;
|
|
const THUMB_SIZE = COL_WIDTH - 4;
|
|
const ICON_SIZE = 3;
|
|
//const ROW_SPACING = 10;
|
|
|
|
let startY = MARGIN+10;
|
|
|
|
// ===== TÍTULO DE LA PÁGINA =====
|
|
pdfDoc.setFontSize(16);
|
|
pdfDoc.setFont(config.fonts.bold, "normal");
|
|
pdfDoc.setTextColor(80, 80, 80);
|
|
pdfDoc.text('Resumen de la configuración seleccionada'.toUpperCase(), config.pageWidth / 2, startY, { align: 'center' });
|
|
startY += 12;
|
|
|
|
// ===== FILA 1: 5 VISTAS =====
|
|
const row1Y = startY-5;
|
|
views.slice(0, 5).forEach((view, index) => {
|
|
const x = MARGIN + index * COL_WIDTH;
|
|
const viewOptions = allOptions.views.get(view.id);
|
|
if (viewOptions) {
|
|
renderViewColumnWithHeader(pdfDoc, config, view, viewOptions, x, row1Y, COL_WIDTH, THUMB_SIZE, ICON_SIZE);
|
|
}
|
|
});
|
|
|
|
// ===== FILA 2: GENERALES (izq) + ESPACIO + TOTAL (der) =====
|
|
const row2Y = row1Y + 120;
|
|
|
|
// Columna 1: Acabados Generales (izquierda)
|
|
//const generalX = MARGIN;
|
|
//renderGeneralColumnWithHeader(pdfDoc, config, allOptions.general, generalX, row2Y, COL_WIDTH, THUMB_SIZE, ICON_SIZE);
|
|
renderGeneralColumnWithHeader(pdfDoc, config, allOptions.general, MARGIN, row2Y, COL_WIDTH, THUMB_SIZE, ICON_SIZE);
|
|
|
|
// Columnas 2-4: Vacías (espacio)
|
|
renderFirmaColumnWithHeader (pdfDoc, config, 70, row2Y, 130)
|
|
|
|
|
|
|
|
// Columna 5: Total (derecha)
|
|
const totalX = MARGIN + 4 * COL_WIDTH;
|
|
renderTotalColumnWithHeader(pdfDoc, config, allOptions, totalX-20, row2Y, COL_WIDTH+16);
|
|
}
|
|
|
|
|
|
|
|
function renderViewColumnWithHeader(
|
|
pdfDoc: jsPDF,
|
|
config: PDFConfig,
|
|
view: View,
|
|
viewOptions: ViewOptions,
|
|
x: number,
|
|
y: number,
|
|
colWidth: number,
|
|
thumbSize: number,
|
|
iconSize: number
|
|
) {
|
|
let cursorY = y+3;
|
|
|
|
// Header de columna
|
|
pdfDoc.setFillColor(46, 125, 50);
|
|
pdfDoc.rect(x+2, cursorY - 5, thumbSize, 8, 'F');
|
|
|
|
pdfDoc.setFontSize(8);
|
|
pdfDoc.setFont(config.fonts.bold, "normal");
|
|
pdfDoc.setTextColor(255, 255, 255);
|
|
const titleLines = pdfDoc.splitTextToSize(view.name.toUpperCase(), colWidth - 4);
|
|
titleLines.forEach((line: string, i: number) => {
|
|
pdfDoc.text(line, x + colWidth / 2, cursorY + i * 3, { align: 'center' });
|
|
});
|
|
|
|
cursorY += 3;
|
|
|
|
// Thumbnail de la vista
|
|
const viewImage = images[getViewImage(view.id)];
|
|
if (viewImage) {
|
|
pdfDoc.addImage(viewImage, 'JPEG', x + 2, cursorY, thumbSize, thumbSize, '', 'FAST');
|
|
}
|
|
cursorY += thumbSize + 5;
|
|
|
|
// ✅ USAR OPCIONES PRECALCULADAS
|
|
viewOptions.options.forEach((option) => {
|
|
cursorY = renderCompactOption(pdfDoc, config, option, x + 2, cursorY, colWidth - 4, iconSize);
|
|
});
|
|
|
|
// Total de la vista
|
|
if (viewOptions.total > 0) {
|
|
cursorY += 3;
|
|
|
|
pdfDoc.setDrawColor(200, 200, 200);
|
|
pdfDoc.setLineWidth(0.3);
|
|
pdfDoc.line(x + 2, cursorY, x + colWidth - 2, cursorY);
|
|
cursorY += 4;
|
|
|
|
pdfDoc.setFontSize(9);
|
|
pdfDoc.setFont(config.fonts.bold, "normal");
|
|
pdfDoc.setTextColor(46, 125, 50);
|
|
pdfDoc.text('TOTAL', x + 2, cursorY);
|
|
pdfDoc.text(formatPrice(viewOptions.total), x + colWidth - 4, cursorY, { align: 'right' });
|
|
|
|
pdfDoc.setLineWidth(0.2);
|
|
pdfDoc.setTextColor(0, 0, 0);
|
|
}
|
|
}
|
|
|
|
|
|
function renderFirmaColumnWithHeader(
|
|
pdfDoc: jsPDF,
|
|
config: PDFConfig,
|
|
x: number,
|
|
y: number,
|
|
colWidth: number,
|
|
) {
|
|
let cursorY = y;
|
|
|
|
// Header de columna
|
|
pdfDoc.setFillColor(157, 186, 113);
|
|
pdfDoc.rect(x+2, cursorY - 5, colWidth, 50, 'S');
|
|
|
|
pdfDoc.setFontSize(12);
|
|
pdfDoc.setFont(config.fonts.bold, "normal");
|
|
pdfDoc.setTextColor(80,80,80);
|
|
const titleLines = pdfDoc.splitTextToSize('FIRMA CLIENTE', colWidth - 4);
|
|
titleLines.forEach((line: string, i: number) => {
|
|
pdfDoc.text(line, x + colWidth / 2, cursorY + i * 3, { align: 'center' });
|
|
});
|
|
|
|
|
|
}
|
|
|
|
|
|
function renderGeneralColumnWithHeader(
|
|
pdfDoc: jsPDF,
|
|
config: PDFConfig,
|
|
generalOptions: Option[],
|
|
x: number,
|
|
y: number,
|
|
colWidth: number,
|
|
thumbSize: number,
|
|
iconSize: number
|
|
) {
|
|
let cursorY = y;
|
|
|
|
// Header de columna
|
|
pdfDoc.setFillColor(157, 186, 113);
|
|
pdfDoc.rect(x+2, cursorY - 5, thumbSize, 8, 'F');
|
|
|
|
pdfDoc.setFontSize(8);
|
|
pdfDoc.setFont(config.fonts.bold, "normal");
|
|
pdfDoc.setTextColor(80,80,80);
|
|
const titleLines = pdfDoc.splitTextToSize('ACABADOS GENERALES', colWidth - 4);
|
|
titleLines.forEach((line: string, i: number) => {
|
|
pdfDoc.text(line, x + colWidth / 2, cursorY + i * 3, { align: 'center' });
|
|
});
|
|
|
|
cursorY += 10;
|
|
|
|
// Icono o placeholder
|
|
/*
|
|
pdfDoc.setFillColor(157, 186, 113);
|
|
pdfDoc.rect(x + 2, cursorY, thumbSize, thumbSize, 'F');
|
|
|
|
pdfDoc.setFontSize(24);
|
|
pdfDoc.setTextColor(80, 80, 80);
|
|
pdfDoc.text('🏠', x + colWidth / 2, cursorY + thumbSize / 2 + 4, { align: 'center' });
|
|
|
|
cursorY += thumbSize + 5;
|
|
|
|
*/
|
|
|
|
// ✅ USAR OPCIONES PRECALCULADAS
|
|
generalOptions.forEach((option) => {
|
|
cursorY = renderCompactOption(pdfDoc, config, option, x + 2, cursorY, thumbSize, iconSize);
|
|
});
|
|
}
|
|
|
|
function renderTotalColumnWithHeader(
|
|
pdfDoc: jsPDF,
|
|
config: PDFConfig,
|
|
allOptions: AllViewOptions,
|
|
x: number,
|
|
y: number,
|
|
colWidth: number
|
|
) {
|
|
let cursorY = y;
|
|
|
|
// Header de columna
|
|
pdfDoc.setFillColor(47,101,53);
|
|
pdfDoc.rect(x, cursorY - 5, colWidth, 8, 'F');
|
|
|
|
pdfDoc.setFontSize(10);
|
|
pdfDoc.setFont(config.fonts.bold, "normal");
|
|
pdfDoc.setTextColor(255, 255, 255);
|
|
pdfDoc.text('TOTALES ESTANCIAS', x + colWidth / 2, cursorY, { align: 'center' });
|
|
|
|
cursorY += 15;
|
|
|
|
// ✅ USAR TOTALES PRECALCULADOS
|
|
const viewTotals: { view: string; total: number }[] = [];
|
|
views.forEach((view) => {
|
|
const vo = allOptions.views.get(view.id);
|
|
if (vo && vo.total > 0) {
|
|
viewTotals.push({ view: view.name.toUpperCase(), total: vo.total });
|
|
}
|
|
});
|
|
|
|
// Subtotales por vista
|
|
pdfDoc.setFontSize(10);
|
|
pdfDoc.setFont(config.fonts.regular, "normal");
|
|
pdfDoc.setTextColor(80, 80, 80);
|
|
|
|
viewTotals.forEach((item) => {
|
|
const nameLines = pdfDoc.splitTextToSize(item.view, colWidth * 0.6);
|
|
nameLines.forEach((line: string, i: number) => {
|
|
pdfDoc.text(line, x + 2, cursorY + i * 3);
|
|
});
|
|
|
|
pdfDoc.setFont(config.fonts.bold, "normal");
|
|
pdfDoc.text(formatPrice(item.total), x + colWidth - 4, cursorY, { align: 'right' });
|
|
pdfDoc.setFont(config.fonts.regular, "normal");
|
|
|
|
cursorY += Math.max(nameLines.length * 3, 6) + 1;
|
|
});
|
|
|
|
// Línea separadora
|
|
cursorY += 5;
|
|
/*
|
|
pdfDoc.setDrawColor(46, 125, 50);
|
|
pdfDoc.setLineWidth(0.5);
|
|
pdfDoc.line(x + 2, cursorY, x + colWidth - 2, cursorY);
|
|
cursorY += 6;
|
|
*/
|
|
|
|
// Total general
|
|
pdfDoc.setFillColor(240, 240, 240);
|
|
pdfDoc.rect(x + 1, cursorY - 4, colWidth - 2, 10, 'F');
|
|
|
|
pdfDoc.setFontSize(10);
|
|
pdfDoc.setFont(config.fonts.bold, "normal");
|
|
pdfDoc.setTextColor(25, 25, 25);
|
|
pdfDoc.text('TOTAL', x + 4, cursorY + 2);
|
|
pdfDoc.setFontSize(12);
|
|
pdfDoc.text(formatPrice(allOptions.totalGeneral), x + colWidth - 4, cursorY + 2, { align: 'right' });
|
|
|
|
pdfDoc.setLineWidth(0.2);
|
|
pdfDoc.setTextColor(0, 0, 0);
|
|
}
|
|
|
|
|
|
function renderCompactOption(
|
|
pdfDoc: jsPDF,
|
|
config: PDFConfig,
|
|
option: Option,
|
|
x: number,
|
|
y: number,
|
|
maxWidth: number,
|
|
iconSize: number
|
|
): number {
|
|
let cursorY = y;
|
|
const iconMargin = 1;
|
|
const iconSpace = (option.warning || option.consultar) ? iconSize + iconMargin : 0;
|
|
|
|
// Calcular precio para ponerlo en la línea del grupo
|
|
const precio = option.consultar ? 'consultar' : option.precio;
|
|
let priceText = '';
|
|
let priceColor = { r: 0, g: 0, b: 0 };
|
|
|
|
if (precio !== null && precio !== undefined) {
|
|
const priceDisplay = getPriceDisplay(precio);
|
|
priceText = priceDisplay.text;
|
|
priceColor = priceDisplay.color;
|
|
}
|
|
|
|
// Calcular ancho del precio
|
|
pdfDoc.setFont(config.fonts.regular, "normal");
|
|
pdfDoc.setFontSize(6);
|
|
const priceWidth = priceText ? pdfDoc.getTextWidth(priceText) + 2 : 0;
|
|
|
|
// LÍNEA 1: Grupo (izquierda) + Precio (derecha)
|
|
pdfDoc.setFont(config.fonts.regular, "normal");
|
|
pdfDoc.setFontSize(6);
|
|
pdfDoc.setTextColor(120, 120, 120);
|
|
|
|
// Calcular espacio disponible para el grupo
|
|
const availableGroupWidth = maxWidth - priceWidth;
|
|
const groupLines = pdfDoc.splitTextToSize(option.nombreGrupo.toUpperCase(), availableGroupWidth);
|
|
|
|
// Primera línea del grupo
|
|
if (groupLines.length > 0) {
|
|
pdfDoc.text(groupLines[0], x, cursorY);
|
|
|
|
// Precio a la derecha en la misma línea
|
|
if (priceText) {
|
|
pdfDoc.setTextColor(priceColor.r, priceColor.g, priceColor.b);
|
|
pdfDoc.text(priceText, x + maxWidth, cursorY, { align: 'right' });
|
|
pdfDoc.setTextColor(120, 120, 120);
|
|
}
|
|
|
|
cursorY += 2.5;
|
|
}
|
|
|
|
// Resto de líneas del grupo (si hay más)
|
|
for (let i = 1; i < groupLines.length; i++) {
|
|
pdfDoc.text(groupLines[i], x, cursorY);
|
|
cursorY += 2.5;
|
|
}
|
|
|
|
// Icono al inicio de la línea del nombre (si existe)
|
|
if ((option.warning || option.consultar) && advertenciaIconB64) {
|
|
pdfDoc.addImage(advertenciaIconB64, 'PNG', x, cursorY - iconSize + 1, iconSize, iconSize);
|
|
}
|
|
|
|
// LÍNEA 2: Nombre de la opción (bold, negro)
|
|
pdfDoc.setFont(config.fonts.bold, "normal");
|
|
pdfDoc.setFontSize(7);
|
|
pdfDoc.setTextColor(30, 30, 30);
|
|
|
|
const optionLines = pdfDoc.splitTextToSize(option.nombre, maxWidth - iconSpace);
|
|
|
|
optionLines.forEach((line: string) => {
|
|
pdfDoc.text(line, x + iconSpace, cursorY);
|
|
cursorY += 3;
|
|
});
|
|
|
|
cursorY += 2; // Espacio entre opciones
|
|
pdfDoc.setTextColor(0, 0, 0);
|
|
return cursorY;
|
|
}
|
|
|
|
|
|
|
|
function getGeneralOptions(tipologia: string): Option[] {
|
|
const options: Option[] = [];
|
|
|
|
options.push({
|
|
nombreGrupo: 'TIPO DE VIVIENDA',
|
|
nombre: tipologia,
|
|
consultar: false,
|
|
precio: null,
|
|
warning: false,
|
|
});
|
|
|
|
Object.entries(dataConfig.options.general).forEach(([groupId, group]) => {
|
|
const currentOptionId = appState.getCurrentOption('general', groupId);
|
|
if (!currentOptionId) return;
|
|
|
|
const optionValue = appState.getOptionValue(currentOptionId);
|
|
const optionRef = group.values.find(v => v.id === currentOptionId);
|
|
const requiresConsult = appState.requiresConsultation('general', groupId, currentOptionId);
|
|
|
|
const hasPrice = optionRef?.amount && typeof optionRef.amount === 'number' && optionRef.amount > 0;
|
|
const isConsultar = optionRef?.amount === 'consultar';
|
|
|
|
options.push({
|
|
nombreGrupo: group.name || groupId,
|
|
nombre: optionValue?.name || currentOptionId || 'No seleccionado',
|
|
precio: hasPrice ? optionRef.amount : null,
|
|
consultar: isConsultar,
|
|
warning: requiresConsult.required,
|
|
warningMessage: requiresConsult.message
|
|
});
|
|
});
|
|
|
|
return options;
|
|
}
|
|
|
|
function addFinalPage(pdfDoc: jsPDF, config: PDFConfig) {
|
|
pdfDoc.addPage();
|
|
const finalImage = dataPdfImages['pdf_openbox_fin'];
|
|
if (!finalImage) return;
|
|
|
|
const format = finalImage.includes('jpeg') ? 'JPEG' : 'PNG';
|
|
pdfDoc.addImage(finalImage, format, 0, 0, config.pageWidth, config.pageHeight, '', 'FAST');
|
|
}
|
|
|
|
// ============================================================================
|
|
// UTILIDADES DE TEXTO
|
|
// ============================================================================
|
|
|
|
function addMultilineText(
|
|
pdfDoc: jsPDF,
|
|
text: string | string[] | null | undefined,
|
|
x: number,
|
|
yStart: number,
|
|
maxWidth: number,
|
|
font: string,
|
|
fontSize: number,
|
|
lineHeight: number
|
|
): number {
|
|
if (!text) return yStart;
|
|
|
|
const safeText = Array.isArray(text) ? text.join("\n") : String(text);
|
|
if (safeText.trim().length === 0) return yStart;
|
|
|
|
pdfDoc.setFont(font, "normal");
|
|
pdfDoc.setFontSize(fontSize);
|
|
|
|
const paragraphs = safeText.split(/\r?\n/);
|
|
let cursorY = yStart;
|
|
|
|
paragraphs.forEach(paragraph => {
|
|
const trimmed = paragraph.trim();
|
|
if (!trimmed) {
|
|
cursorY += lineHeight;
|
|
return;
|
|
}
|
|
|
|
const lines = pdfDoc.splitTextToSize(trimmed, maxWidth);
|
|
lines.forEach((line: string) => {
|
|
pdfDoc.text(line, x, cursorY);
|
|
cursorY += lineHeight;
|
|
});
|
|
cursorY += lineHeight; // Espacio entre párrafos
|
|
});
|
|
|
|
return cursorY;
|
|
}
|
|
|
|
// ============================================================================
|
|
// RENDERIZADO DE OPCIONES
|
|
// ============================================================================
|
|
|
|
function renderOption(
|
|
pdfDoc: jsPDF,
|
|
option: Option,
|
|
x: number,
|
|
y: number,
|
|
maxWidth: number,
|
|
styles: TextStyles,
|
|
icon: string | null = null
|
|
): number {
|
|
let cursorY = y;
|
|
|
|
// Línea 1: Nombre del grupo
|
|
const cY = cursorY;
|
|
cursorY = renderGroupName(pdfDoc, option.nombreGrupo, x, cursorY, styles.group);
|
|
renderPrice(pdfDoc, option, x, cY, maxWidth, styles.price);
|
|
|
|
// Línea 2: Nombre de la opción + icono
|
|
cursorY = renderOptionName(pdfDoc, option.nombre, x, cursorY, maxWidth, styles.option, icon);
|
|
|
|
// Línea 3: Warning (si existe)
|
|
if (option.warningMessage) {
|
|
cursorY = renderWarning(pdfDoc, option.warningMessage, x, cursorY, maxWidth, styles.group.font);
|
|
}
|
|
|
|
return cursorY + 4; // Espacio entre opciones
|
|
}
|
|
|
|
function renderGroupName(pdfDoc: jsPDF, groupName: string, x: number, y: number, style: { font: string; size: number }): number {
|
|
pdfDoc.setFont(style.font, "normal");
|
|
pdfDoc.setFontSize(style.size);
|
|
pdfDoc.setTextColor(120, 120, 120);
|
|
pdfDoc.text(groupName.toUpperCase(), x, y);
|
|
return y + style.size * 0.5;
|
|
}
|
|
|
|
function renderOptionName(
|
|
pdfDoc: jsPDF,
|
|
optionName: string,
|
|
x: number,
|
|
y: number,
|
|
maxWidth: number,
|
|
style: { font: string; size: number },
|
|
icon: string | null
|
|
): number {
|
|
const ICON_SIZE = 6;
|
|
|
|
pdfDoc.setFont(style.font, "normal");
|
|
pdfDoc.setFontSize(style.size);
|
|
pdfDoc.setTextColor(30, 30, 30);
|
|
|
|
const lines = pdfDoc.splitTextToSize(optionName, maxWidth);
|
|
const iconYPosition = y;
|
|
|
|
let cursorY = y;
|
|
lines.forEach((line: string) => {
|
|
pdfDoc.text(line, x, cursorY);
|
|
cursorY += style.size * 0.45;
|
|
});
|
|
|
|
// Icono alineado a la derecha
|
|
if (icon) {
|
|
const iconX = x + maxWidth - ICON_SIZE;
|
|
pdfDoc.addImage(icon, 'PNG', iconX, iconYPosition - ICON_SIZE + 1, ICON_SIZE, ICON_SIZE);
|
|
}
|
|
|
|
return cursorY;
|
|
}
|
|
|
|
function renderPrice(
|
|
pdfDoc: jsPDF,
|
|
option: Option,
|
|
x: number,
|
|
y: number,
|
|
maxWidth: number,
|
|
style: { font: string; size: number }
|
|
): number {
|
|
const precio = option.consultar ? 'consultar' : option.precio;
|
|
if (precio === null || precio === undefined) return y;
|
|
|
|
pdfDoc.setFont(style.font, "normal");
|
|
pdfDoc.setFontSize(style.size);
|
|
|
|
const { text, color } = getPriceDisplay(precio);
|
|
const priceWidth = pdfDoc.getTextWidth(text);
|
|
const priceX = x + maxWidth - priceWidth;
|
|
|
|
pdfDoc.setTextColor(color.r, color.g, color.b);
|
|
pdfDoc.text(text, priceX, y);
|
|
pdfDoc.setTextColor(0, 0, 0); // Reset
|
|
|
|
return y + style.size * 0.45;
|
|
}
|
|
|
|
function getPriceDisplay(precio: number | string): { text: string; color: { r: number; g: number; b: number } } {
|
|
if (typeof precio === 'number' && precio > 0) {
|
|
return {
|
|
text: '+ ' + formatPrice(precio),
|
|
color: { r: 46, g: 125, b: 50 } // Verde
|
|
};
|
|
} else if (precio === 'consultar' || typeof precio === 'string') {
|
|
return {
|
|
text: 'CONSULTAR',
|
|
color: { r: 255, g: 140, b: 0 } // Naranja
|
|
};
|
|
} else {
|
|
return {
|
|
text: 'Sin coste adicional',
|
|
color: { r: 120, g: 120, b: 120 } // Gris
|
|
};
|
|
}
|
|
}
|
|
|
|
function renderWarning(
|
|
pdfDoc: jsPDF,
|
|
message: string,
|
|
x: number,
|
|
y: number,
|
|
maxWidth: number,
|
|
font: string
|
|
): number {
|
|
let cursorY = y + 1;
|
|
|
|
pdfDoc.setFont(font, "normal");
|
|
pdfDoc.setFontSize(10);
|
|
pdfDoc.setTextColor(200, 100, 0);
|
|
|
|
const lines = pdfDoc.splitTextToSize(message, maxWidth - 5);
|
|
lines.forEach((line: string) => {
|
|
pdfDoc.text(line, x, cursorY);
|
|
cursorY += 4;
|
|
});
|
|
|
|
pdfDoc.setTextColor(0, 0, 0); // Reset
|
|
return cursorY;
|
|
}
|
|
|
|
// ============================================================================
|
|
// EXTRACCIÓN DE DATOS
|
|
// ============================================================================
|
|
|
|
function getViewOptions(view: View): ViewOptions {
|
|
const options: Option[] = [];
|
|
let hasWarning = false;
|
|
let hasConsult = false;
|
|
let total = 0;
|
|
|
|
view.options.forEach((group) => {
|
|
const currentOptionId = appState.getCurrentOption(view.id, group.id);
|
|
if (!currentOptionId) return;
|
|
|
|
const optionValue = appState.getOptionValue(currentOptionId);
|
|
const optionRef = group.values.find(v => v.id === currentOptionId);
|
|
const requiresConsult = appState.requiresConsultation(view.id, group.id, currentOptionId);
|
|
|
|
const hasPrice = optionRef?.amount && typeof optionRef.amount === 'number' && optionRef.amount > 0;
|
|
const isConsultar = optionRef?.amount === 'consultar';
|
|
|
|
if (requiresConsult.required) hasWarning = true;
|
|
if (isConsultar) hasConsult = true;
|
|
if (hasPrice) total += (optionRef.amount as number);
|
|
|
|
options.push({
|
|
nombreGrupo: group.name || group.id,
|
|
nombre: optionValue?.name || currentOptionId || 'No seleccionado',
|
|
precio: hasPrice ? optionRef.amount : null,
|
|
consultar: isConsultar,
|
|
warning: requiresConsult.required,
|
|
warningMessage: requiresConsult.message
|
|
});
|
|
});
|
|
|
|
return { options, total, hasWarning, hasConsult };
|
|
}
|
|
</script>
|
|
|
|
<!-- ============================================================================ -->
|
|
<!-- UI -->
|
|
<!-- ============================================================================ -->
|
|
|
|
<button
|
|
type="button"
|
|
class="px-3 lg:px-4 py-2 rounded-md text-base font-medium transition-colors duration-200 text-white bg-green-900 hover:bg-green-700 cursor-pointer"
|
|
onclick={openSelector}
|
|
>
|
|
Descargar Selección
|
|
</button>
|
|
|
|
<PoDownload
|
|
{isVisible}
|
|
{message}
|
|
{downloadState}
|
|
tipologias={TIPOLOGIAS}
|
|
tiposTextos={Object.values(tiposInfo)}
|
|
{logoCompany}
|
|
{logoProject}
|
|
text="Descarga tu Selección"
|
|
onTipologiaSelected={handleTipologiaSelected}
|
|
onCancel={handleCancel}
|
|
/> |