controller.js 10.9 KB
angular.module('focaLogisticaPedidoRuta').controller('focaLogisticaPedidoRutaController', [
  '$scope', 'focaLogisticaPedidoRutaService', '$location', '$uibModal', '$filter',
  'focaModalService', 'focaBotoneraLateralService', '$interval',
  function ($scope, focaLogisticaPedidoRutaService, $location, $uibModal, $filter,
    focaModalService, focaBotoneraLateralService, $interval
  ) {
    $scope.actividad = 'Logistica';
    //Datos Pantalla
    $scope.titulo = 'Logistica de Pedidos';

    var transportista = { label: 'Vehículo', image: 'abmChofer.png' };
    var fecha = { label: 'Fecha Reparto', image: 'FechaEntrega.png' };
    $scope.botonera = [fecha, transportista];
    var cabecera = '';
    $scope.now = new Date();
    $scope.idVendedor = 0;
    $scope.marcadores = [];
    $scope.vehiculos = [];
    getSeguimiento();
    $scope.arrastrando = false;
    $scope.general = function () {
      $scope.idVendedor = 0;
      getSeguimiento();
    };

    setearFecha(new Date());

    //SETEO BOTONERA LATERAL
    focaBotoneraLateralService.showSalir(true);
    focaBotoneraLateralService.showPausar(false);
    focaBotoneraLateralService.showGuardar(false);

    $scope.general = function () {
      $scope.idVendedor = 0;
      getSeguimiento();
      $scope.$broadcast('removeCabecera', cabecera);
      $scope.$broadcast('addCabecera', {
        label: 'General',
        valor: ''
      });
    };

    $scope.cargar = function (idVehiculo, punto) {
      if (!eligioFecha()) return;
      var idRemito;
      if (punto === -1) {
        idRemito = -1;
      } else {
        idRemito = JSON.parse(punto).notaPedido.remito.id;
      }

      $uibModal.open(
        {
          ariaLabelledBy: 'Busqueda de Vehiculo',
          templateUrl: 'foca-detalle-vehiculo.html',
          controller: 'focaDetalleVehiculo',
          size: 'lg',
          resolve: {
            idVehiculo: function () { return idVehiculo; },
            idRemito: function () { return idRemito; },
            fechaReparto: function () { return $scope.fechaReparto; },
            orden: function () { return null; }
          }
        }
      );
    };

    $scope.quitarVehiculo = function (vehiculo) {
      if (!eligioFecha() || vehiculoEnUso(vehiculo)) return;
      focaModalService.confirm('Esta seguro que desea eliminar el vehículo ' +
        vehiculo.codigo + ' de ' + vehiculo.transportista.NOM + '?').then(function () {
          eliminarVehiculo(vehiculo);
        });
    };

    $scope.hacerHojaRuta = function (vehiculo, cerrar) {
      if (!eligioFecha() || vehiculoEnUso(vehiculo)) return;
      var modalInstance = $uibModal.open(
        {
          ariaLabelledBy: 'Creación hoja ruta',
          templateUrl: 'foca-modal-cerrar-vehiculo.html',
          controller: 'focaModalCerrarVehiculo',
          size: 'lg',
          resolve: {
            idVehiculo: function () { return vehiculo.id; },
            fechaReparto: function () { return $scope.fechaReparto; },
            cerrar: function () { return cerrar; }
          }
        }
      );
      modalInstance.result
        .then(function () { }, function () { });
    };

    $scope.arrastra = function () {
      $scope.arrastrando = true;
      $scope.$digest();
    };

    $scope.noArrastra = function () {
      $scope.arrastrando = false;
      $scope.$digest();
    };

    $scope.individual = function () {
      $scope.idVendedor = -1;
    };

    $scope.mostrarDetalle = function () {
      $scope.detalle = true;
    };

    $scope.salir = function () {
      $location.path('/');
    };

    $scope.search = function () {
      getSeguimiento();
    };

    $scope.fecha = function () {
      getSeguimiento();
    };

    $scope.seleccionarVehiculo = function () {
      var parametrosModal = {
        titulo: 'Búsqueda de Transportista',
        query: '/transportista',
        columnas: [
          {
            nombre: 'Código',
            propiedad: 'COD'
          },
          {
            nombre: 'Nombre',
            propiedad: 'NOM'
          },
          {
            nombre: 'CUIT',
            propiedad: 'CUIT'
          }
        ]
      };
      focaModalService.modal(parametrosModal)
        .then(function (transportista) {
          $scope.selectVehiculo(transportista.COD, transportista.NOM);
        });
    };

    $scope.seleccionarRemito = function () {
      var modalInstance = $uibModal.open(
        {
          ariaLabelledBy: 'Busqueda de Remito',
          templateUrl: 'foca-modal-remito.html',
          controller: 'focaModalRemitoController',
          size: 'lg',
          resolve: { usadoPor: function () { return 'remito'; } }
        }
      );
      modalInstance.result
        .then(function (remito) {
          $scope.remito = remito;
          $scope.remito.numero = $filter('rellenarDigitos')(remito.lugar, 4) + '-' +
            $filter('rellenarDigitos')(remito.numeroRemito, 6);
          $scope.cliente = remito.cliente.NOM;
        }, function () { });
    };

    $scope.selectVehiculo = function (idTransportista, nombreTransportista) {
      var parametrosModal = {
        columnas: [
          {
            propiedad: 'codigo',
            nombre: 'Código'
          },
          {
            propiedad: 'tractor',
            nombre: 'tractor'
          },
          {
            propiedad: 'semi',
            nombre: 'Semi'
          },
          {
            propiedad: 'capacidadTotalCisternas',
            nombre: 'Capacidad'
          }
        ],
        query: '/vehiculo/transportista/' + idTransportista,
        titulo: 'Búsqueda de vehiculos',
        subTitulo: idTransportista + '-' + nombreTransportista
      };
      focaModalService.modal(parametrosModal)
        .then(
          function (vehiculo) {
            var existe = $filter('filter')($scope.vehiculos, { id: vehiculo.id });
            if (existe.length) {
              focaModalService.alert('El vehiculo ya ha sido cargado');
              return;
            }
            if (!vehiculo.cisternas.length) {
              focaModalService.alert('El vehiculo no tiene cisternas');
              return;
            }
            $scope.vehiculos.push(vehiculo);
          }, function () { });
    };

    $scope.seleccionarFechaReparto = function () {
      focaModalService.modalFecha('Fecha de reparto')
        .then(function (fecha) {
          setearFecha(fecha);
        });
    };

    function actualizarMarcadores(filtros) {
      var marcadores = [];
      if (filtros.cliente && filtros.remito === undefined) {

        $scope.marcadores.forEach(function (marcador) {
          if (marcador.notaPedido.cliente.NOM === filtros.cliente) {
            marcadores.push(marcador);
          }
        });

        if (marcadores.length === 0) {
          focaModalService.alert('No se encontraron coincidencias en la busqueda')
            .then(function (data) {
              if (data) $scope.marcadoresFiltro = marcadores;
            });
          $scope.$broadcast('cleanCabecera');
          setearFecha(new Date());
          return;
        } else {
          $scope.marcadoresFiltro = marcadores;
          $scope.$broadcast('addCabecera', {
            label: 'Cliente:',
            valor: filtros.cliente
          });
        }
      } else {
        $scope.marcadores.forEach(function (marcador) {
          if (filtros.remito.id === marcador.notaPedido.remito.id) marcadores.push(marcador);
        });
        if (marcadores.length === 0) {
          focaModalService.alert('No se encontraron coincidencias en la busqueda')
            .then(function (data) {
              if (data) $scope.marcadoresFiltro = marcadores;
            });
          $scope.$broadcast('cleanCabecera');
          setearFecha(new Date());
          return;
        } else {
          $scope.marcadoresFiltro = marcadores;
          $scope.$broadcast('addCabecera', {
            label: 'Cliente:',
            valor: filtros.cliente
          });
        }
      }
    }

    function setearFecha(fecha) {
      $scope.fechaReparto = fecha;
      focaLogisticaPedidoRutaService.setFechaReparto(fecha);
      focaLogisticaPedidoRutaService.getUnidadesByFecha(fecha).then(function (res) {
        $scope.vehiculos = res.data;
        $scope.$broadcast('addCabecera', {
          label: 'Fecha:',
          valor: fecha.toLocaleDateString()
        });
      });
    }

    function getSeguimiento() {
      var desde = new Date('1900/01/01');
      var hasta = new Date('2099/01/01');
      if ($scope.fechaDesde) {
        var fechaDesde = $scope.fechaDesde;
        desde = new Date(new Date(fechaDesde.setHours(0)).setMinutes(0));
        desde = new Date(desde);
      }
      if ($scope.fechaHasta) {
        var fechaHasta = $scope.fechaHasta;
        hasta = new Date(new Date(fechaHasta.setHours(0)).setMinutes(0));
        hasta = hasta.setDate(hasta.getDate() + 1);
        hasta = new Date(hasta);
      }
      var datos = {
        actividad: $scope.actividad,
        idUsuario: $scope.idVendedor,
        fechaDesde: desde,
        fechaHasta: hasta,
        asignacion: $scope.filtroEstado ? true : ($scope.filtroEstado !== undefined ?
          false : undefined)
      };

      $scope.datosBuscados = {
        actividad: $scope.actividad,
        individual: $scope.idVendedor ? true : false
      };

      focaLogisticaPedidoRutaService.obtenerActividad(datos).then(function (datos) {
        if (!angular.equals($scope.marcadores, datos.data)) {
          $scope.marcadores = datos.data;
          $scope.marcadoresFiltro = $scope.marcadores;
        }
      });
    }

    function eliminarVehiculo(vehiculo) {
      focaLogisticaPedidoRutaService.getRemitosByIdVehiculo(vehiculo.id).then(function (res) {
        if (!res.data.length) {
          $scope.vehiculos.splice($scope.vehiculos.indexOf(vehiculo), 1);
        } else {
          focaModalService.alert('No ha sido posible eliminar el vehiculo porque ' +
            'tiene remitos asociados').then(function () {
              $scope.hacerHojaRuta(vehiculo, true);
            });
        }
      });
    }

    function eligioFecha() {
      if (!$scope.fechaReparto) {
        focaModalService.alert('Primero seleccione fecha de reparto');
        return false;
      }
      return true;
    }

    function vehiculoEnUso(vehiculo) {
      var idUsuario = focaLogisticaPedidoRutaService.idUsuario;
      for (var i = 0; i < vehiculo.cisternas.length; i++) {
        for (var j = 0; j < vehiculo.cisternas[i].cisternasCarga.length; j++) {
          var cisternaCarga = vehiculo.cisternas[i].cisternasCarga[j];
          if (cisternaCarga.fechaReparto.substring(0, 10) === $scope.fechaReparto
            .toISOString().substring(0, 10) && cisternaCarga.idUsuarioProceso &&
            cisternaCarga.idUsuarioProceso !== idUsuario) {
            focaModalService.alert('El vehículo está siendo usado por otro usuario');
            return true;
          }
        }
      }
      return false;
    }
    // $interval(function() {
    //     getSeguimiento();
    // }, 5000);
  }
]);