All files / routes vehiculos.service.js

89.37% Statements 185/207
73.33% Branches 11/15
100% Functions 6/6
89.37% Lines 185/207

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 2091x 1x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x               2x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x       2x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x             2x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x             2x 1x 1x 1x    
// AISLANDO LAS FUNCIONALIDADES DE VEHICULOS
 
async function crearVehiculo(pool, idEmpresa, { placa, tipo, color, modelo }) {
  //Verificar si la placa ya existe
  const [existente] = await pool.query(
    'SELECT id_vehiculo FROM vehiculos WHERE placa = ? AND id_empresa = ?',
    [placa, idEmpresa]
  );
 
  if (existente.length > 0) {
    return {
      success: false,
      status: 400,
      message: 'Ya existe un vehículo con esta placa'
    };
  }
 
  //Insertar nuevo vehículo
  const [result] = await pool.query(
    `INSERT INTO vehiculos (id_empresa, placa, tipo, color, modelo)
     VALUES (?, ?, ?, ?, ?)`,
    [idEmpresa, placa, tipo, color, modelo]
  );
 
  return {
    success: true,
    status: 201,
    message: 'Vehículo registrado exitosamente',
    id: result.insertId
  };
}
 
async function obtenerVehiculoEspecifico(pool, idVehiculo, idEmpresa) {
  const [vehiculos] = await pool.query(
    'SELECT * FROM vehiculos WHERE id_vehiculo = ? AND id_empresa = ?',
    [idVehiculo, idEmpresa]
  );
 
  if (vehiculos.length === 0) {
    return {
      success: false,
      message: 'Vehículo no encontrado',
      data: null
    };
  }
 
  return {
    success: true,
    message: 'Vehículo encontrado',
    data: vehiculos[0]
  };
}
 
 
 
async function actualizarVehiculo(pool, idVehiculo, idEmpresa, datos) {
  const { placa, tipo, color, modelo } = datos;
 
  try {
    //Verificar si existe otro vehículo con la misma placa
    const [existente] = await pool.query(
      'SELECT id_vehiculo FROM vehiculos WHERE placa = ? AND id_empresa = ? AND id_vehiculo != ?',
      [placa, idEmpresa, idVehiculo]
    );
 
    if (existente.length > 0) {
      return {
        success: false,
        code: 400,
        message: 'Ya existe otro vehículo con esta placa'
      };
    }
 
    //Ejecutar la actualización
    await pool.query(
      `UPDATE vehiculos 
       SET placa = ?, tipo = ?, color = ?, modelo = ?
       WHERE id_vehiculo = ? AND id_empresa = ?`,
      [placa, tipo, color, modelo, idVehiculo, idEmpresa]
    );
 
    return {
      success: true,
      code: 200,
      message: 'Vehículo actualizado exitosamente'
    };
  } catch (error) {
    console.error('Error al actualizar vehículo:', error);
    return {
      success: false,
      code: 500,
      message: 'Error al actualizar el vehículo'
    };
  }
}
 
 
async function obtenerVehiculos(pool, idEmpresa) {
  try {
    const [vehiculos] = await pool.query(
      `SELECT v.*, 
              CASE 
                  WHEN EXISTS (
                      SELECT 1 
                      FROM movimientos m 
                      WHERE m.id_vehiculo = v.id_vehiculo 
                      AND m.fecha_salida IS NULL
                  ) THEN 'activo'
                  ELSE 'inactivo'
              END as estado
       FROM vehiculos v
       WHERE v.id_empresa = ?
       ORDER BY v.fecha_registro DESC`,
      [idEmpresa]
    );
 
    return { success: true, data: vehiculos };
  } catch (error) {
    console.error('Error al obtener vehículos:', error);
    return { success: false, message: 'Error al obtener los vehículos' };
  }
}
 
 
 
async function obtenerHistorialVehiculo(pool, idVehiculo) {
  try {
    const [rows] = await pool.query(
      `SELECT 
          m.id_movimiento,
          m.fecha_entrada,
          m.fecha_salida,
          m.total_a_pagar,
          m.estado,
          t.tipo_vehiculo,
          COALESCE(SUM(p.monto), 0) AS total_pagado,
          COUNT(p.id_pago) AS pagos
       FROM movimientos m
       JOIN tarifas t ON t.id_tarifa = m.id_tarifa
       LEFT JOIN pagos p ON p.id_movimiento = m.id_movimiento
       WHERE m.id_vehiculo = ?
       GROUP BY m.id_movimiento, m.fecha_entrada, m.fecha_salida, 
                m.total_a_pagar, m.estado, t.tipo_vehiculo
       ORDER BY m.fecha_entrada DESC`,
      [idVehiculo]
    );
 
    if (!rows || rows.length === 0) {
      return {
        success: false,
        message: 'No hay historial para este vehículo',
        data: [],
      };
    }
 
    return {
      success: true,
      message: 'Historial obtenido correctamente',
      data: rows,
    };
  } catch (error) {
    console.error('Error al obtener historial:', error);
    return {
      success: false,
      message: 'Error al obtener historial',
    };
  }
}
 
 
 
async function eliminarVehiculo(pool, idVehiculo, idEmpresa) {
  try {
    //Verificar si tiene movimientos activos
    const [movimientos] = await pool.query(
      'SELECT id_movimiento FROM movimientos WHERE id_vehiculo = ? AND fecha_salida IS NULL',
      [idVehiculo]
    );
 
    if (movimientos.length > 0) {
      return {
        success: false,
        message: 'No se puede eliminar un vehículo con movimientos activos',
      };
    }
 
    //Eliminar el vehículo
    await pool.query(
      'DELETE FROM vehiculos WHERE id_vehiculo = ? AND id_empresa = ?',
      [idVehiculo, idEmpresa]
    );
 
    return {
      success: true,
      message: 'Vehículo eliminado exitosamente',
    };
  } catch (error) {
    console.error('Error al eliminar vehículo:', error);
    return {
      success: false,
      message: 'Error al eliminar el vehículo',
    };
  }
}
 
module.exports = {crearVehiculo, obtenerVehiculoEspecifico, actualizarVehiculo, 
    obtenerVehiculos, obtenerHistorialVehiculo, eliminarVehiculo};