dev 8 months ago
parent b546074199
commit 6fac2f097e

@ -11,270 +11,287 @@
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,
nombreGrupo: string;
nombre: string;
precio?: number | null | string;
consultar: boolean;
warning: boolean;
warningMessage?: string;
}
interface ViewOptions {
options: Option[];
total : number | null;
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 };
}
const stepTimeout = 1000;
const logoProject = dataConfig.sources.logos + dataConfig.logos.project;
const logoCompany = dataConfig.sources.logos + dataConfig.logos.company;
// ============================================================================
// ESTADO
// ============================================================================
const TIPOLOGIAS = ['A1', 'P1', 'P2'];
const STEP_TIMEOUT = 1000;
let downloadState: DownloadState = $state('idle');
let isVisible = $state(false);
let message = $state('');
const views = appState.getAllViews();
const tipologias = ['A1', 'P1', 'P2'];
const logoProject = dataConfig.sources.logos + dataConfig.logos.project;
const logoCompany = dataConfig.sources.logos + dataConfig.logos.company;
// ============================================================================
// HANDLERS
// ============================================================================
// Abrir el modal con el selector
function openSelector() {
isVisible = true;
downloadState = 'idle';
}
// Cancelar y cerrar
function handleCancel() {
isVisible = false;
downloadState = 'idle';
}
// Generar PDF con la tipología seleccionada
async function handleTipologiaSelected(tipologia: string) {
downloadState = 'creating';
try {
const pdfDoc = new jsPDF({
const pdfDoc = createPDFDocument();
const config = getPDFConfig(pdfDoc);
registerFonts(pdfDoc);
await generatePDFContent(pdfDoc, config, tipologia);
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);
}
}
// ============================================================================
// CREACIÓN DE PDF
// ============================================================================
function createPDFDocument(): jsPDF {
return new jsPDF({
orientation: 'landscape',
unit: 'mm',
format: 'A4',
});
}
const pageWidth = pdfDoc.internal.pageSize.getWidth();
const pageHeight = pdfDoc.internal.pageSize.getHeight();
const margin = 15;
// === Registrar fuentes ===
const tf = projectFonts['Didot'];
pdfDoc.addFileToVFS(tf.filename, tf.base64);
pdfDoc.addFont(tf.filename, tf.name, tf.style);
const pf = projectFonts['proxima_nova_regular'];
pdfDoc.addFileToVFS(pf.filename, pf.base64);
pdfDoc.addFont(pf.filename, pf.name, pf.style);
const pb = projectFonts['proxima_nova_bold'];
pdfDoc.addFileToVFS(pb.filename, pb.base64);
pdfDoc.addFont(pb.filename, pb.name, pb.style);
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,
}
};
}
const pl = projectFonts['proxima_nova_light'];
pdfDoc.addFileToVFS(pl.filename, pl.base64);
pdfDoc.addFont(pl.filename, pl.name, pl.style);
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) {
addCoverPage(pdfDoc, config, tipologia);
addPresentationPage(pdfDoc, config);
addViewPages(pdfDoc, config);
addFinalPage(pdfDoc, config);
}
// Calcular tamaño de imagen
const imgPixelWidth = 1500;
const imgPixelHeight = 1500;
const pageRatio = pageWidth / pageHeight;
const imgRatio = imgPixelWidth / imgPixelHeight;
// ============================================================================
// PÁGINAS DEL PDF
// ============================================================================
function addCoverPage(pdfDoc: jsPDF, config: PDFConfig, tipologia: string) {
const coverImage = dataPdfImages['pdf_openbox_ini'];
if (!coverImage) return;
// === Portada ===
const ini = dataPdfImages['pdf_openbox_ini'];
if (ini) {
const iniFormat = ini.includes('jpeg') ? 'JPEG' : 'PNG';
pdfDoc.addImage(ini, iniFormat, 0, 0, pageWidth, pageHeight, '', 'FAST');
const format = coverImage.includes('jpeg') ? 'JPEG' : 'PNG';
pdfDoc.addImage(coverImage, format, 0, 0, config.pageWidth, config.pageHeight, '', 'FAST');
// Tipo de vivienda (USAR LA TIPOLOGÍA SELECCIONADA)
pdfDoc.setFontSize(20);
pdfDoc.setFont(pb.name, "normal");
pdfDoc.setFont(config.fonts.bold, "normal");
pdfDoc.text(tipologia.toUpperCase(), 265, 119);
pdfDoc.addPage();
}
// == Presentacion ===
// Configuración grid 3x2
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;
const squareSize = (pageWidth - margin * 2 - spacing * (cols - 1)) / cols;
const base64 = dataPdfImages['pdf_openbox_pre'];
if (base64) {
const preFormat = base64.includes('jpeg') ? 'JPEG' : 'PNG';
pdfDoc.addImage(base64, 'JPEG', margin, startY, squareSize, squareSize, '', 'FAST');
// 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');
}
// Colocar las minuaturas de las 5 vistas en el documento
// Primera fila (2 vistas)
views.slice(0, 2).forEach((view, i) => {
const base64 = images[getViewImage(view.id)];
if (!base64) {
return;
}
const columnIndex = i + 1; // empieza en columna 1 (segunda visualmente)
const x = margin + columnIndex * (squareSize + spacing);
pdfDoc.addImage(base64, 'JPEG', x, startY, squareSize, squareSize, '', 'FAST');
})
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 vi = images[getViewImage(view.id)];
if (!vi) {
return;
}
const x = margin + i * (squareSize + spacing);
pdfDoc.addImage(vi, 'JPEG', x, startY, squareSize, squareSize, '', 'FAST');
})
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();
// === Páginas de vistas ===
views.forEach((view, index) => {
const base64 = images[getViewImage(view.id)];
if (!base64) {
return;
}
let renderWidth: number;
let renderHeight: number;
if (imgRatio > pageRatio) {
renderHeight = pageHeight - 2 * margin;
renderWidth = renderHeight * imgRatio;
} else {
renderHeight = pageHeight - 2 * margin;
renderWidth = renderHeight * imgRatio;
}
const x = margin; const y = (pageHeight - renderHeight) / 2;
pdfDoc.addImage(base64, 'JPEG', x, y, renderWidth, renderHeight, '', 'FAST');
function addViewPages(pdfDoc: jsPDF, config: PDFConfig) {
const imageRatio = 1; // 1500x1500
const pageRatio = config.pageWidth / config.pageHeight;
views.forEach((view, index) => {
const viewImage = images[getViewImage(view.id)];
if (!viewImage) return;
// Posiciones del rectángulo
const rectX = renderWidth + margin + 10;
const rectY = margin + 90;
const rectWidth = pageWidth - rectX - margin;
const rectHeight = pageHeight - rectY - margin;
// 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;
/*
// color
pdfDoc.setFillColor(237, 237, 226);
pdfDoc.rect(rectX, rectY, rectWidth, rectHeight, "F");
// 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;
/*
pdfDoc.setFillColor(241, 242, 14);
pdfDoc.rect(rectX, rectY-20, rectWidth, 20, "F");
*/
addViewContent(pdfDoc, config, view, textStartX, textMaxWidth);
// === TEXTOS ===
let textStartX = margin + renderWidth + 10;
let cursorY = margin + 5;
// 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) {
let cursorY = config.margin + 5;
// === Título ===
// Título de la vista
pdfDoc.setFontSize(18);
pdfDoc.setFont(pf.name, "normal");
pdfDoc.text((view.name).toUpperCase(), textStartX, cursorY);
pdfDoc.setFont(config.fonts.regular, "normal");
pdfDoc.setTextColor(30, 30, 30);
pdfDoc.text(view.name.toUpperCase(), x, cursorY);
// === Descripción ===
pdfDoc.setFont(pl.name, "normal");
// Descripción
if (view.text) {
cursorY += 8;
cursorY = addTextBlock(pdfDoc, view.text, textStartX, cursorY, pageWidth - textStartX - margin, pl.name, 12, 5);
cursorY = addMultilineText(pdfDoc, view.text, x, cursorY, maxWidth, config.fonts.light, 12, 5);
}
// === AÑADIR INFORMACIÓN DE OPCIONES ===
const vo = getViewOptions(view)
if (vo.options.length > 0) {
const tx = textStartX;
const ty = 100;
const textBoxMaxWidth = rectWidth - 3;
// === Título ===
pdfDoc.setFontSize(14);
pdfDoc.setFont(pf.name, "normal");
pdfDoc.text(('ACABADOS SELECCIONADOS').toUpperCase(), tx, ty);
let ty2 = ty + 10;
vo.options.forEach((option) => {
ty2 = cursorY = addOptionBlock(
pdfDoc,
option.nombreGrupo, // Nombre del grupo
option.nombre, // Nombre de la opción
option.consultar ? 'consultar' : (option.precio !== undefined ? option.precio : null),
tx,
ty2,
textBoxMaxWidth,
pf.name, // Font grupo (regular)
9, // Size grupo (pequeño)
pb.name, // Font opción (bold)
11, // Size opción (grande)
pf.name, // Font precio (regular)
11, // Size precio (mediano)
(option.warning || option.consultar) ? advertenciaIconB64 : '',
6,
option.warningMessage
);
})
}
// Nueva página excepto en la última
if (index < views.length - 1) pdfDoc.addPage();
});
// === Página final ===
pdfDoc.addPage();
const fin = dataPdfImages['pdf_openbox_fin'];
if (fin) {
const finFormat = fin.includes('jpeg') ? 'JPEG' : 'PNG';
pdfDoc.addImage(fin, finFormat, 0, 0, pageWidth, pageHeight, '', 'FAST');
// Opciones
const viewOptions = getViewOptions(view);
if (viewOptions.options.length > 0) {
cursorY = 100;
addOptionsSection(pdfDoc, config, viewOptions, x, cursorY, maxWidth);
}
}
downloadState = 'downloading';
// Guardar con nombre que incluye la tipología
pdfDoc.save(`mi_OPENBOX_${tipologia}.pdf`);
function addOptionsSection(pdfDoc: jsPDF, config: PDFConfig, viewOptions: ViewOptions, x: number, y: number, maxWidth: number) {
let cursorY = y;
downloadState = 'success';
// 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: 9 },
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);
});
}
// Cerrar modal después de 2 segundos
setTimeout(() => {
isVisible = false;
downloadState = 'idle';
}, 2000);
function addFinalPage(pdfDoc: jsPDF, config: PDFConfig) {
pdfDoc.addPage();
const finalImage = dataPdfImages['pdf_openbox_fin'];
if (!finalImage) return;
} catch (err: any) {
downloadState = 'error';
message = err?.message || 'Error desconocido al generar el PDF';
console.error(err);
}
const format = finalImage.includes('jpeg') ? 'JPEG' : 'PNG';
pdfDoc.addImage(finalImage, format, 0, 0, config.pageWidth, config.pageHeight, '', 'FAST');
}
// ============================================================================
// UTILIDADES DE TEXTO
// ============================================================================
// === Función auxiliar para texto multilínea ===
function addTextBlock(
function addMultilineText(
pdfDoc: jsPDF,
text: string | string[] | null | undefined,
x: number,
@ -283,9 +300,10 @@
font: string,
fontSize: number,
lineHeight: number
) {
): number {
if (!text) return yStart;
let safeText: string = Array.isArray(text) ? text.join("\n") : String(text);
const safeText = Array.isArray(text) ? text.join("\n") : String(text);
if (safeText.trim().length === 0) return yStart;
pdfDoc.setFont(font, "normal");
@ -294,201 +312,208 @@
const paragraphs = safeText.split(/\r?\n/);
let cursorY = yStart;
for (let p = 0; p < paragraphs.length; p++) {
const paragraph = paragraphs[p].trim();
if (!paragraph) {
paragraphs.forEach(paragraph => {
const trimmed = paragraph.trim();
if (!trimmed) {
cursorY += lineHeight;
continue;
}
const lines = pdfDoc.splitTextToSize(paragraph, maxWidth);
for (let i = 0; i < lines.length; i++) {
pdfDoc.text(lines[i], x, cursorY + i * lineHeight);
}
cursorY += lines.length * lineHeight + lineHeight;
}
return cursorY;
}
function getViewOptions(view: View): ViewOptions {
const options: Option[] = [];
let hasWarning = false;
let hasConsult = false;
let total = 0;
if (view.options.length > 0) {
// Obtener opciones de la vista
view.options.forEach((group) => {
const currentOptionId = appState.getCurrentOption(view.id, group.id);
const optionValue = currentOptionId ? appState.getOptionValue(currentOptionId) : null;
const optionRef = group.values.find(v => v.id === currentOptionId);
const requiresConsult = currentOptionId ? appState.requiresConsultation(view.id, group.id, currentOptionId) : {required: false};
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 = total + (optionRef?.amount ?? 0);
return;
}
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.required ? requiresConsult.message : undefined
const lines = pdfDoc.splitTextToSize(trimmed, maxWidth);
lines.forEach((line: string) => {
pdfDoc.text(line, x, cursorY);
cursorY += lineHeight;
});
cursorY += lineHeight; // Espacio entre párrafos
});
}
return {
total,
options,
hasWarning,
hasConsult,
}
return cursorY;
}
// ============================================================================
// RENDERIZADO DE OPCIONES
// ============================================================================
// === Nueva función para bloques de opciones (3 líneas: grupo, opción, precio) ===
function addOptionBlock(
function renderOption(
pdfDoc: jsPDF,
nombreGrupo: string,
nombreOpcion: string,
precio: number | null | string,
option: Option,
x: number,
y: number,
maxWidth: number,
groupFont: string,
groupSize: number,
optionFont: string,
optionSize: number,
priceFont: string,
priceSize: number,
icon: string | null = null,
iconSize: number = 3,
warningMessage?: string,
styles: TextStyles,
icon: string | null = null
): number {
let cursorY = y;
// Icono (si existe)
/*
if (icon) {
pdfDoc.addImage(icon, 'PNG', x, cursorY - iconSize + 1, iconSize, iconSize);
}
// Línea 1: Nombre del grupo
cursorY = renderGroupName(pdfDoc, option.nombreGrupo, x, cursorY, styles.group);
*/
// Línea 2: Nombre de la opción + icono
cursorY = renderOptionName(pdfDoc, option.nombre, x, cursorY, maxWidth, styles.option, icon);
// LÍNEA 1: Nombre del grupo (pequeño, uppercase, gris)
pdfDoc.setFont(groupFont, "normal");
pdfDoc.setFontSize(groupSize);
pdfDoc.setTextColor(120, 120, 120);
pdfDoc.text(nombreGrupo.toUpperCase(), x, cursorY);
cursorY += groupSize * 0.5;
// Línea 3: Precio
cursorY = renderPrice(pdfDoc, option, x, cursorY, maxWidth, styles.price);
// LÍNEA 2: Nombre de la opción (más grande, bold, negro)
/*
pdfDoc.setFont(optionFont, "normal");
pdfDoc.setFontSize(optionSize);
pdfDoc.setTextColor(30, 30, 30);
// Línea 4: Warning (si existe)
if (option.warningMessage) {
cursorY = renderWarning(pdfDoc, option.warningMessage, x, cursorY, maxWidth, styles.group.font);
}
// Dividir en múltiples líneas si es necesario
const optionLines = pdfDoc.splitTextToSize(nombreOpcion, maxWidth - (icon ? iconSize + 2 : 0));
optionLines.forEach((line: string) => {
pdfDoc.text(line, x + (icon ? iconSize + 2 : 0), cursorY);
cursorY += optionSize * 0.45;
});
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;
// LÍNEA 2: Nombre de la opción (más grande, bold, negro) + ICONO A LA DERECHA
pdfDoc.setFont(optionFont, "normal");
pdfDoc.setFontSize(optionSize);
pdfDoc.setFont(style.font, "normal");
pdfDoc.setFontSize(style.size);
pdfDoc.setTextColor(30, 30, 30);
// Dividir en múltiples líneas si es necesario
const optionLines = pdfDoc.splitTextToSize(nombreOpcion, maxWidth);
const iconYPosition = cursorY; // Guardar posición Y para el icono
const lines = pdfDoc.splitTextToSize(optionName, maxWidth);
const iconYPosition = y;
optionLines.forEach((line: string) => {
let cursorY = y;
lines.forEach((line: string) => {
pdfDoc.text(line, x, cursorY);
cursorY += optionSize * 0.45;
cursorY += style.size * 0.45;
});
// Icono a la derecha, alineado con la primera línea de la opción
// Icono alineado a la derecha
if (icon) {
const iconX = x + maxWidth - iconSize;
pdfDoc.addImage(icon, 'PNG', iconX, iconYPosition - iconSize + 1, iconSize, iconSize);
const iconX = x + maxWidth - ICON_SIZE;
pdfDoc.addImage(icon, 'PNG', iconX, iconYPosition - ICON_SIZE + 1, ICON_SIZE, ICON_SIZE);
}
// LÍNEA 3: Precio (si existe)
// LÍNEA 3: Precio (si existe) - ALINEADO A LA DERECHA
if (precio !== null && precio !== undefined) {
pdfDoc.setFont(priceFont, "normal");
pdfDoc.setFontSize(priceSize);
return cursorY;
}
let priceText: string;
let priceColor: { r: number, g: number, b: number };
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) {
priceText = '+ ' + formatPrice(precio);
priceColor = {r: 46, g: 125, b: 50}; // Verde
return {
text: '+ ' + formatPrice(precio),
color: { r: 46, g: 125, b: 50 } // Verde
};
} else if (precio === 'consultar' || typeof precio === 'string') {
priceText = 'CONSULTAR';
priceColor = {r: 255, g: 140, b: 0}; // Naranja
return {
text: 'CONSULTAR',
color: { r: 255, g: 140, b: 0 } // Naranja
};
} else {
priceText = 'Sin coste adicional';
priceColor = {r: 120, g: 120, b: 120}; // Gris
return {
text: 'Sin coste adicional',
color: { r: 120, g: 120, b: 120 } // Gris
};
}
// Calcular ancho del texto del precio
const priceWidth = pdfDoc.getTextWidth(priceText);
// Posición alineada a la derecha
const priceX = x + maxWidth - priceWidth;
pdfDoc.setTextColor(priceColor.r, priceColor.g, priceColor.b);
pdfDoc.text(priceText, priceX, cursorY);
cursorY += priceSize * 0.45;
}
// LÍNEA 4 (OPCIONAL): Mensaje de advertencia si existe
if (warningMessage && warningMessage.trim()) {
cursorY += 1; // Pequeño espacio antes del mensaje
pdfDoc.setFont(groupFont, "normal");
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(8);
pdfDoc.setTextColor(200, 100, 0); // Color naranja/amarillo para advertencia
pdfDoc.setTextColor(200, 100, 0);
// Dividir el mensaje en múltiples líneas si es necesario
const warnLines = pdfDoc.splitTextToSize(warningMessage, maxWidth - 5);
warnLines.forEach((line: string) => {
const lines = pdfDoc.splitTextToSize(message, maxWidth - 5);
lines.forEach((line: string) => {
pdfDoc.text('⚠️ ' + line, x, cursorY);
cursorY += 3;
});
pdfDoc.setTextColor(0, 0, 0); // Reset
return cursorY;
}
// ============================================================================
// EXTRACCIÓN DE DATOS
// ============================================================================
// Espacio entre opciones
cursorY += 4;
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;
// Reset
pdfDoc.setTextColor(0, 0, 0);
const optionValue = appState.getOptionValue(currentOptionId);
const optionRef = group.values.find(v => v.id === currentOptionId);
const requiresConsult = appState.requiresConsultation(view.id, group.id, currentOptionId);
return cursorY;
}
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"
@ -501,9 +526,9 @@
{isVisible}
{message}
{downloadState}
{tipologias}
logoCompany={logoCompany}
logoProject={logoProject}
tipologias={TIPOLOGIAS}
{logoCompany}
{logoProject}
text="Descarga tu Selección"
onTipologiaSelected={handleTipologiaSelected}
onCancel={handleCancel}

Loading…
Cancel
Save

Powered by TurnKey Linux.