Skip to main content

Overview

The cost calculation system automatically computes the total inspection cost based on vehicle motorization types. Each engine type has a different inspection rate, reflecting the varying complexity and time requirements for different propulsion systems.
The system uses differential pricing based on motorization technology, with electric vehicles receiving the lowest rates and diesel vehicles the highest.

Pricing Structure

The current ITV inspection rates are defined in the calcularYMostrarTotal() function (script.js:268):

Diesel

€50 per vehicleHighest rate due to emissions testing complexity

Gasoline

€45 per vehicleStandard combustion engine inspection

Hybrid

€35 per vehicleReduced rate for eco-friendly technology

Electric

€30 per vehicleLowest rate - minimal emissions inspection needed

Core Function: calcularYMostrarTotal()

The main calculation function (script.js:268) handles all pricing logic:
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>
    `;
}

Calculation Process

The cost calculation follows a systematic workflow:
1

Define Rate Table

Tariff structure is established with rates for each motorization type (Diesel: €50, Gasoline: €45, Hybrid: €35, Electric: €30).
2

Count Vehicles by Type

The system iterates through vehiculosData array and counts vehicles by motorization type.
3

Calculate Subtotals

Individual costs are calculated by multiplying vehicle count by respective rate.
4

Generate Total

All subtotals are summed to produce the final amount.
5

Display Breakdown

Results are rendered with itemized breakdown and grand total.

Data Source

Vehicle Data Array

The calculation function relies on the vehiculosData global array, which is populated by procesarDatosVehiculos() (script.js:189):
script.js:189-204
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
        });
    }
}
Each vehicle object in vehiculosData contains: vehicle number, motorization type, ITV status, and observations.

Visual Representation

Itemized Breakdown

The calculation displays a detailed cost breakdown with visual styling (styles.css:666-673):
styles.css:666-673
.desglose-item {
    padding: 0.5rem;
    margin: 0.25rem 0;
    background: rgba(16, 185, 129, 0.1);
    border-radius: 0.375rem;
    font-size: 0.95rem;
    font-weight: 600;
}

Icon Mapping

The obtenerEmojiMotorizacion() helper function (script.js:326) provides visual indicators:
script.js:326-334
function obtenerEmojiMotorizacion(tipo) {
    const emojis = {
        "Diesel": "🛢️",
        "Gasolina": "⛽",
        "Hibrido": "🔋",
        "Electrico": "⚡"
    };
    return emojis[tipo] || "🚗";
}
The default 🚗 emoji serves as a fallback for any unexpected motorization types.

Example Calculations

Here are some real-world calculation scenarios:
Input:
  • 1 Diesel vehicle
Calculation:
Diesel: 1 × €50 = €50
Total: €50
Display:
🛢️ 1 Diesel: 50€
💰 Total: 50€
Input:
  • 2 Diesel vehicles
  • 1 Gasoline vehicle
  • 1 Hybrid vehicle
  • 1 Electric vehicle
Calculation:
Diesel:    2 × €50 = €100
Gasolina:  1 × €45 = €45
Hibrido:   1 × €35 = €35
Electrico: 1 × €30 = €30
Total: €210
Display:
🛢️ 2 Diesel: 100€
⛽ 1 Gasolina: 45€
🔋 1 Hibrido: 35€
⚡ 1 Electrico: 30€
💰 Total: 210€
Input:
  • 10 Electric vehicles
Calculation:
Electrico: 10 × €30 = €300
Total: €300
Display:
⚡ 10 Electrico: 300€
💰 Total: 300€

Integration with Results Display

The cost calculation is called as part of the main calculation workflow in calcular() (script.js:119):
script.js:119-148
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.");
    }
}
The calculation function is only executed after successful validation. If validation fails, the process stops and no cost is calculated.

Display Container

Results are rendered in the total section of index.html (index.html:76-84):
index.html:76-84
<!-- Tarjeta con el total a pagar -->
<div class="info-card">
    <div class="total">
        <h3>💰 Total a Pagar</h3>
        <div class="total-amount">
            <span id="total">€0</span>
        </div>
    </div>
</div>

Styling Details

The total amount display has distinctive styling (styles.css:361-374):
styles.css:361-374
.total-amount {
    text-align: center;
    padding: 1.5rem;
    background: linear-gradient(135deg, #ecfdf5 0%, #d1fae5 100%);
    border-radius: 0.5rem;
    border: 2px solid #10b981;
}

.total-amount span {
    font-size: 2rem;
    font-weight: 800;
    color: #10b981;
    text-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

Performance Considerations

Efficient Iteration

Single pass through vehicle data using forEach() for counting

Conditional Rendering

Only motorization types with vehicles are displayed in the breakdown

Template Strings

HTML generation uses efficient template literals

No External Dependencies

Pure JavaScript calculation with no library dependencies

Customization Options

The rate structure can be easily modified by updating the tarifas object:
// Example: Updated rates
const tarifas = {
    "Diesel": 55,      // Increased from 50
    "Gasolina": 50,    // Increased from 45
    "Hibrido": 40,     // Increased from 35
    "Electrico": 35    // Increased from 30
};
Rate changes take effect immediately without requiring changes to other parts of the system.

Error Handling

The calculation is wrapped in a try-catch block (script.js:144-147) to handle unexpected errors:
script.js:144-147
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.");
}

Next Steps

Results Display

See how calculated costs are presented to users

Data Validation

Learn about the validation that precedes calculation

Build docs developers (and LLMs) love