Skip to main content

Overview

The calculation engine processes vehicle inspection data, calculates costs based on motorization types, and displays comprehensive results to the user.

calcular()

Main calculation orchestrator that coordinates all data processing and result display. Source: script.js:119-148

Parameters

This function takes no parameters.

Returns

void - Does not return a value

Process Flow

  1. Obtains client data
  2. Validates all vehicle forms
  3. Processes vehicle data
  4. Displays client information
  5. Displays ITV status for each vehicle
  6. Displays vehicle observations
  7. Calculates and displays total cost

Error Handling

The function is wrapped in a try-catch block. Any errors are logged to console and displayed to the user via mostrarError().

Example Implementation

function calcular() {
    try {
        // Obtener datos del cliente
        const datosCliente = obtenerDatosCliente();

        // Validar que todos los vehículos tengan datos completos
        if (!validarFormulariosVehiculos()) {
            return;
        }

        // Procesar datos de vehículos
        procesarDatosVehiculos();

        // Mostrar información del cliente
        mostrarInformacionCliente(datosCliente);

        // Mostrar estados de ITV
        mostrarEstadosITV();

        // Mostrar observaciones
        mostrarObservaciones();

        // Calcular y mostrar total
        calcularYMostrarTotal();

    } catch (error) {
        console.error("Error en el cálculo:", error);
        mostrarError("Ha ocurrido un error al procesar los datos. Por favor, verifique la información ingresada.");
    }
}

obtenerDatosCliente()

Extracts and returns client information from the main form. Source: script.js:154-161

Parameters

This function takes no parameters.

Returns

Object - Client data object with the following structure:
{
    nombre: string,      // Client first name
    apellidos: string,   // Client last name
    razonSocial: string, // Business name
    nAutos: number       // Number of vehicles
}

Example Implementation

function obtenerDatosCliente() {
    return {
        nombre: document.getElementById("nombre").value.trim(),
        apellidos: document.getElementById("apellidos").value.trim(),
        razonSocial: document.getElementById("razonSocial").value.trim(),
        nAutos: numeroAutos
    };
}

Usage

const cliente = obtenerDatosCliente();
console.log(`Processing ${cliente.nAutos} vehicles for ${cliente.nombre} ${cliente.apellidos}`);

procesarDatosVehiculos()

Extracts data from all vehicle forms and stores it in the global vehiculosData array. Source: script.js:189-204

Parameters

This function takes no parameters. It processes forms based on the global numeroAutos variable.

Returns

void - Does not return a value

Side Effects

  • Resets the global vehiculosData array
  • Populates vehiculosData with one object per vehicle

Vehicle Data Structure

Each vehicle object contains:
{
    numero: number,           // Vehicle number (1-indexed)
    motorizacion: string,     // "Diesel" | "Gasolina" | "Hibrido" | "Electrico"
    estadoITV: string,        // "Aprobo" | "NoAprobo"
    observaciones: string     // User observations (trimmed)
}

Example Implementation

function procesarDatosVehiculos() {
    vehiculosData = [];

    for (let i = 1; i <= numeroAutos; i++) {
        const motorizacion = document.querySelector(
            `input[name="motorizacion${i}"]:checked`
        ).value;
        const estadoITV = document.querySelector(
            `input[name="aprobados${i}"]:checked`
        ).value;
        const observaciones = document.getElementById(
            `observaciones${i}`
        ).value.trim();

        vehiculosData.push({
            numero: i,
            motorizacion: motorizacion,
            estadoITV: estadoITV,
            observaciones: observaciones
        });
    }
}
This function assumes that validarFormulariosVehiculos() has already been called and returned true.

calcularYMostrarTotal()

Calculates the total cost based on vehicle motorization types and displays a detailed breakdown. Source: script.js:268-319

Parameters

This function takes no parameters. It uses the global vehiculosData array.

Returns

void - Does not return a value

Pricing Structure

MotorizationCost per Vehicle
Diesel50€
Gasolina45€
Híbrido35€
Eléctrico30€

Calculation Logic

  1. Count vehicles by motorization type
  2. Calculate cost per type (quantity × rate)
  3. Sum all costs for total
  4. Generate detailed breakdown with emojis
  5. Display in the #total container

Example Implementation

function calcularYMostrarTotal() {
    const tarifas = {
        "Diesel": 50,
        "Gasolina": 45,
        "Hibrido": 35,
        "Electrico": 30
    };

    let contadores = {
        "Diesel": 0,
        "Gasolina": 0,
        "Hibrido": 0,
        "Electrico": 0
    };

    // Contar vehículos por tipo de motorización
    vehiculosData.forEach(vehiculo => {
        contadores[vehiculo.motorizacion]++;
    });

    // Calcular costos por tipo
    const costos = {
        diesel: tarifas.Diesel * contadores.Diesel,
        gasolina: tarifas.Gasolina * contadores.Gasolina,
        hibrido: tarifas.Hibrido * contadores.Hibrido,
        electrico: tarifas.Electrico * contadores.Electrico
    };

    const totalGeneral = costos.diesel + costos.gasolina + 
                         costos.hibrido + costos.electrico;

    // Crear desglose detallado
    let desglose = "";
    Object.keys(contadores).forEach(tipo => {
        if (contadores[tipo] > 0) {
            const costo = tarifas[tipo] * contadores[tipo];
            desglose += `
                <div class="desglose-item">
                    ${obtenerEmojiMotorizacion(tipo)} ${contadores[tipo]} ${tipo}: ${costo}
                </div>
            `;
        }
    });

    document.getElementById("total").innerHTML = `
        <div class="total-desglose">
            ${desglose}
            <div class="total-final">
                💰 Total: ${totalGeneral}
            </div>
        </div>
    `;
}

Output Example

For 2 Diesel, 1 Gasolina, and 1 Eléctrico:
🛢️ 2 Diesel: 100€
⛽ 1 Gasolina: 45€
⚡ 1 Electrico: 30€
💰 Total: 175€

obtenerEmojiMotorizacion()

Returns the emoji icon for a given motorization type. Source: script.js:326-334

Parameters

tipo
string
required
The motorization type: “Diesel”, “Gasolina”, “Hibrido”, or “Electrico”

Returns

string - The emoji corresponding to the motorization type, or ”🚗” as default

Emoji Mapping

MotorizationEmoji
Diesel🛢️
Gasolina
Hibrido🔋
Electrico
Default🚗

Example Implementation

function obtenerEmojiMotorizacion(tipo) {
    const emojis = {
        "Diesel": "🛢️",
        "Gasolina": "⛽",
        "Hibrido": "🔋",
        "Electrico": "⚡"
    };
    return emojis[tipo] || "🚗";
}

Usage

const icono = obtenerEmojiMotorizacion("Diesel");  // Returns "🛢️"
const iconoDesconocido = obtenerEmojiMotorizacion("Unknown");  // Returns "🚗"

calcularYMostrar()

Combined function that validates, calculates, hides forms, and displays results. Source: script.js:693-704

Parameters

This function takes no parameters.

Returns

void - Does not return a value

Process Flow

  1. Validates all vehicle forms
  2. Exits early if validation fails
  3. Calls calcular() to process data
  4. Calls ocultarCaja() to hide forms
  5. After 500ms delay, adds action buttons

Example Implementation

function calcularYMostrar() {
    // Validar que todos los vehículos tengan datos completos
    if (!validarFormulariosVehiculos()) {
        return; // Detener la ejecución si hay errores
    }
    
    // Si la validación es exitosa, calcular y mostrar resultados
    calcular();
    ocultarCaja();
    
    setTimeout(() => {
        agregarBotonesAccion();
    }, 500);
}
This is the function called by the “Calcular Resultados” button. It serves as the main entry point for the calculation workflow.

Display Functions

mostrarInformacionCliente()

Source: script.js:210-218 Displays client information in the results section.
datos
Object
required
Client data object returned by obtenerDatosCliente()

mostrarEstadosITV()

Source: script.js:223-239 Displays the ITV approval status for each vehicle with color-coded styling.

mostrarObservaciones()

Source: script.js:244-263 Displays all vehicle observations. Shows “Sin observaciones registradas” if none exist.

Animation Functions

ocultarCaja()

Source: script.js:339-355 Animates the form sections out and triggers result display.

mostrarResultados()

Source: script.js:360-375 Animates the results section in and scrolls to it smoothly.

Build docs developers (and LLMs) love