Skip to main content

Overview

The export functions API provides capabilities to export results as JSON, print formatted reports, reset the application, and manage action buttons.

exportarResultados()

Exports all client and vehicle data as a JSON file for download. Source: script.js:529-548

Parameters

This function takes no parameters. It uses global variables obtenerDatosCliente() and vehiculosData.

Returns

void - Does not return a value

Side Effects

  • Creates a JSON blob with all application data
  • Triggers browser download
  • Filename format: ITV_{apellidos}_{timestamp}.json
  • Includes current date and time in Spanish locale

Export Data Structure

{
    cliente: {
        nombre: string,
        apellidos: string,
        razonSocial: string,
        nAutos: number
    },
    vehiculos: [
        {
            numero: number,
            motorizacion: string,
            estadoITV: string,
            observaciones: string
        }
    ],
    fecha: string,  // Format: "DD/MM/YYYY"
    hora: string    // Format: "HH:MM:SS"
}

Example Implementation

function exportarResultados() {
    const datosExportacion = {
        cliente: obtenerDatosCliente(),
        vehiculos: vehiculosData,
        fecha: new Date().toLocaleDateString('es-ES'),
        hora: new Date().toLocaleTimeString('es-ES')
    };

    const jsonStr = JSON.stringify(datosExportacion, null, 2);
    const blob = new Blob([jsonStr], { type: 'application/json' });
    const url = URL.createObjectURL(blob);

    const a = document.createElement('a');
    a.href = url;
    a.download = `ITV_${datosExportacion.cliente.apellidos}_${Date.now()}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}

Example Export File

{
  "cliente": {
    "nombre": "Juan",
    "apellidos": "GarcΓ­a",
    "razonSocial": "GarcΓ­a Automotive SL",
    "nAutos": 3
  },
  "vehiculos": [
    {
      "numero": 1,
      "motorizacion": "Diesel",
      "estadoITV": "Aprobo",
      "observaciones": "VehΓ­culo en buen estado"
    },
    {
      "numero": 2,
      "motorizacion": "Electrico",
      "estadoITV": "Aprobo",
      "observaciones": ""
    },
    {
      "numero": 3,
      "motorizacion": "Hibrido",
      "estadoITV": "NoAprobo",
      "observaciones": "Requiere revisiΓ³n de frenos"
    }
  ],
  "fecha": "07/03/2026",
  "hora": "14:23:45"
}
The JSON is formatted with 2-space indentation for readability. The timestamp in the filename ensures unique file names for multiple exports.

imprimirResultados()

Generates a print-friendly version of the results and triggers the browser print dialog. Source: script.js:551-573

Parameters

This function takes no parameters.

Returns

void - Does not return a value

Process Flow

  1. Saves current page HTML
  2. Extracts results and client information sections
  3. Replaces page content with print-formatted version
  4. Triggers browser print dialog
  5. Restores original page content
  6. Reinitializes event listeners
The function automatically restores the original page state after printing, ensuring users can continue working without refreshing.

Example Implementation

function imprimirResultados() {
    const contenidoOriginal = document.body.innerHTML;
    const resultados = document.getElementById("muestra").outerHTML;
    const informacionCliente = document.getElementById("informacion").outerHTML;

    document.body.innerHTML = `
        <div style="padding: 20px; font-family: Arial, sans-serif;">
            <h1 style="text-align: center; color: #2563eb;">
                Concesionario de Coches - Resultados ITV
            </h1>
            <hr style="margin: 20px 0;">
            ${informacionCliente}
            ${resultados}
            <div style="margin-top: 30px; text-align: center; 
                        font-size: 12px; color: #666;">
                Impreso el ${new Date().toLocaleDateString('es-ES')} 
                a las ${new Date().toLocaleTimeString('es-ES')}
            </div>
        </div>
    `;

    window.print();
    document.body.innerHTML = contenidoOriginal;

    // Reinicializar eventos despuΓ©s de restaurar el contenido
    inicializarEventos();
}
  • Header: β€œConcesionario de Coches - Resultados ITV” in blue
  • Content: Client information and full results
  • Footer: Timestamp of when the report was printed
  • Styling: Clean, professional Arial font with proper spacing

reiniciarFormulario()

Resets the entire application to its initial state with user confirmation. Source: script.js:522-526

Parameters

This function takes no parameters.

Returns

void - Does not return a value

Side Effects

  • Shows browser confirmation dialog
  • Reloads the entire page if confirmed
  • Preserves all data if cancelled

Example Implementation

function reiniciarFormulario() {
    if (confirm("ΒΏEstΓ‘ seguro que desea reiniciar el formulario? Se perderΓ‘n todos los datos ingresados.")) {
        location.reload();
    }
}

Usage

<button onclick="reiniciarFormulario()">πŸ”„ Nuevo Formulario</button>
This action is destructive and cannot be undone. Always prompts for user confirmation before proceeding.

agregarBotonesAccion()

Adds export, print, and reset action buttons to the results section. Source: script.js:578-605

Parameters

This function takes no parameters.

Returns

void - Does not return a value

Side Effects

  • Checks if action buttons already exist (prevents duplicates)
  • Appends button container to #muestra element
  • Injects secondary button styles if not present

Buttons Created

  1. πŸ–¨οΈ Imprimir - Calls imprimirResultados()
  2. πŸ“₯ Exportar JSON - Calls exportarResultados()
  3. πŸ”„ Nuevo Formulario - Calls reiniciarFormulario()

Example Implementation

function agregarBotonesAccion() {
    const muestra = document.getElementById("muestra");

    if (!document.getElementById("botones-accion")) {
        const botonesHTML = `
            <div id="botones-accion" class="info-card full-width">
                <div style="padding: 1.5rem; text-align: center;">
                    <h3>πŸ“‹ Acciones Disponibles</h3>
                    <div style="display: flex; gap: 1rem; 
                                justify-content: center; flex-wrap: wrap; 
                                margin-top: 1rem;">
                        <button onclick="imprimirResultados()" 
                                class="btn-secondary">
                            πŸ–¨οΈ Imprimir
                        </button>
                        <button onclick="exportarResultados()" 
                                class="btn-secondary">
                            πŸ“₯ Exportar JSON
                        </button>
                        <button onclick="reiniciarFormulario()" 
                                class="btn-secondary">
                            πŸ”„ Nuevo Formulario
                        </button>
                    </div>
                </div>
            </div>
        `;
        muestra.innerHTML += botonesHTML;

        // Agregar estilos para los botones secundarios
        agregarEstilosBotonSecundario();
    }
}
This function is automatically called 500ms after results are displayed to ensure smooth UI transitions.

agregarEstilosBotonSecundario()

Injects CSS styles for secondary action buttons if not already present. Source: script.js:610-688

Parameters

This function takes no parameters.

Returns

void - Does not return a value

Styles Applied

Button Styles (.btn-secondary)

  • Gradient background: light gray to slate
  • Blue border and text
  • Rounded corners (0.5rem)
  • Hover effect: purple gradient with lift animation
  • Responsive padding and sizing

Vehicle Status Styles

  • .estado-vehiculo.aprobado: Green background and border
  • .estado-vehiculo.no-aprobado: Red background and border

Other Styles

  • .observacion-vehiculo: Light blue background for observations
  • .desglose-item: Green background for cost breakdown items
  • .total-final: Purple gradient background for total cost

Example Implementation

function agregarEstilosBotonSecundario() {
    if (!document.querySelector("#btn-secondary-styles")) {
        const estilos = document.createElement("style");
        estilos.id = "btn-secondary-styles";
        estilos.textContent = `
            .btn-secondary {
                padding: 0.75rem 1.5rem;
                background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
                color: #2563eb;
                border: 2px solid #2563eb;
                border-radius: 0.5rem;
                font-weight: 600;
                cursor: pointer;
                transition: all 0.3s ease;
                box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
                font-size: 0.9rem;
                text-transform: uppercase;
                letter-spacing: 0.05em;
            }
            .btn-secondary:hover {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                transform: translateY(-2px);
                box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1);
            }
            /* Additional styles... */
        `;
        document.head.appendChild(estilos);
    }
}

Workflow Integration

Typical User Flow

  1. User fills out client information
  2. User fills out vehicle forms
  3. User clicks β€œCalcular Resultados” β†’ calcularYMostrar()
  4. Results are displayed with action buttons β†’ agregarBotonesAccion()
  5. User can:
    • Print results β†’ imprimirResultados()
    • Export to JSON β†’ exportarResultados()
    • Start over β†’ reiniciarFormulario()

Function Call Chain

calcularYMostrar()
  └─> calcular()
  └─> ocultarCaja()
  └─> setTimeout(() => agregarBotonesAccion(), 500)
        └─> agregarEstilosBotonSecundario()

File Naming Conventions

JSON Export

Format: ITV_{apellidos}_{timestamp}.json Examples:
  • ITV_Garcia_1709820225000.json
  • ITV_Rodriguez_1709820330500.json
The timestamp ensures unique filenames even when exporting multiple times in quick succession.

Browser Compatibility

Required APIs

  • Blob - For JSON file creation
  • URL.createObjectURL() - For download links
  • window.print() - For print functionality
  • location.reload() - For form reset
  • document.createElement() - For dynamic DOM manipulation

Supported Features

  • Download attribute on anchor elements
  • Modern ES6+ JavaScript syntax
  • DOM manipulation
  • Spanish locale date/time formatting

Build docs developers (and LLMs) love