controller.js 13.9 KB
angular.module('focaOrdenCarga')
    .controller('focaOrdenCargaController', [
        '$scope',
        '$location',
        '$filter',
        '$timeout',
        'focaOrdenCargaService',
        'focaBotoneraLateralService',
        'focaModalService',
        '$uibModal',
        function (
            $scope, $location, $filter, $timeout, focaOrdenCargaService,
            focaBotoneraLateralService, focaModalService, $uibModal) {

            init();

            function init() {
                // PARAMETROS INICIALES PARA FUNCIONAMIENTO DEL PROGRAMA
                $scope.fecha = new Date();
                $scope.isNumber = angular.isNumber;
                $scope.show = false;
                $scope.cargando = true;
                $scope.cabeceras = [];
                $scope.botonera = focaOrdenCargaService.getBotonera();
                $scope.dateOptions = {
                    maxDate: new Date(),
                    minDate: new Date(2010, 0, 1)
                };
                $scope.ordenCarga = {
                    id: 0,
                    cliente: {},
                    proveedor: {},
                    domicilio: { dom: '' },
                    vendedor: {},
                    fechaCarga: new Date(),
                    cotizacion: {},
                    articulosNotaPedido: [],
                    notaPedidoPlazo: [],
                    notaPedidoPuntoDescarga: []
                };
                $scope.hojaRuta = {
                    fecha: new Date(),
                    litros: 0,
                    chofer: {},
                    vehiculo: {
                        capacidad: 0,
                        cisternas: []
                    },
                    transportista: {},
                    remitosTabla: []
                };
            }

            //SETEO BOTONERA LATERAL
            $timeout(function () {
                focaBotoneraLateralService.showSalir(false);
                focaBotoneraLateralService.showPausar(true);
                focaBotoneraLateralService.showGuardar(true, $scope.crearNotaPedido);
                focaBotoneraLateralService.addCustomButton('Salir', salir);
            });

            $scope.seleccionarVehiculo = function () {

                seleccionarTransportista().then(

                    function (transportista) {
                        elegirTransportista(transportista);

                        var parametrosModal = {
                            columnas: [
                                {
                                    propiedad: 'codigo',
                                    nombre: 'Código'
                                },
                                {
                                    propiedad: 'tractor',
                                    nombre: 'tractor'
                                },
                                {
                                    propiedad: 'semi',
                                    nombre: 'Semi'
                                },
                                {
                                    propiedad: 'capacidadTotalCisternas',
                                    nombre: 'Capacidad'
                                },
                                // {
                                //     propiedad: 'cantidad',
                                //     nombre: 'carga'
                                // }
                            ],
                            query: '/vehiculo/transportista/' + transportista.COD,
                            // query: '/cisterna_carga/cisterna/vehiculo/transportista/' + transportista.COD,
                            titulo: 'Búsqueda de vehiculos',
                            subTitulo: transportista.COD + '-' + transportista.NOM
                        };

                        focaModalService.modal(parametrosModal).then(
                            function (vehiculo) {
                                $scope.$broadcast('addCabecera', {
                                    label: 'Vehículo:',
                                    valor: vehiculo.codigo
                                });
                                $scope.hojaRuta.vehiculo = vehiculo;
                                $scope.hojaRuta.transportista = transportista;
                                $scope.hojaRuta.vehiculo.cisternas = vehiculo.cisternas;
                                getEstadosCisternas($scope.hojaRuta.vehiculo.cisternas);
                            }, function () {
                                seleccionarTransportista();
                            });
                    });
            };

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

            $scope.seleccionarFechaDeReparto = function () {
                focaModalService.modalFecha('Fecha').then(function (fecha) {
                    $scope.$broadcast('addCabecera', {
                        label: 'Fecha:',
                        valor: fecha.toLocaleDateString()
                    });

                    $scope.fecha = fecha;
                    if ($scope.hojaRuta.vehiculo.cisternas)
                        getEstadosCisternas($scope.hojaRuta.vehiculo.cisternas);
                });
            };

            $scope.seleccionarHojasDeRuta = function () {
                if (!$scope.hojaRuta.vehiculo.cisternas.length) {
                    focaModalService.alert('Primero seleccione un vehículo con cisternas');
                    return;
                }
                $uibModal.open(
                    {
                        ariaLabelledBy: 'Hojas de Ruta',
                        templateUrl: 'modal-hojas-ruta.html',
                        controller: 'focaOrdenCargaController',
                        size: 'md',
                        resolve: {
                            filters: {
                                cisternas: $scope.hojaRuta.vehiculo.id
                            }
                        }
                    }
                );
                var idVehiculo = $scope.hojaRuta.vehiculo.id
                focaOrdenCargaService.getHojasRuta(idVehiculo)
                    .then(function (res) {
                        console.log(res);
                    })
                    .catch(function (err) {
                        console.error(err)
                    })
            }

            $scope.seleccionarRemitoAbierto = function () {
                if ($scope.hojaRuta.vehiculo.capacidad === 0) {
                    focaModalService.alert('Debe ingresar vehiculo');
                    return;
                } else {
                    mostrarDetalle($scope.hojaRuta);
                }
            };

            $scope.seleccionarChofer = function () {
                var parametrosModal = {
                    titulo: 'Búsqueda de Chofer',
                    query: '/chofer',
                    columnas: [
                        {
                            propiedad: 'id',
                            nombre: 'Código',
                            filtro: {
                                nombre: 'rellenarDigitos',
                                parametro: 3
                            }
                        },
                        {
                            propiedad: 'nombre',
                            nombre: 'Nombre'
                        },
                        {
                            propiedad: 'dni',
                            nombre: 'DNI'
                        },
                        {
                            propiedad: 'telefono',
                            nombre: 'Teléfono'
                        }
                    ]
                };
                focaModalService.modal(parametrosModal).then(
                    function (chofer) {
                        $scope.ordenCarga.chofer = chofer;
                        $scope.$broadcast('addCabecera', {
                            label: 'Chofer:',
                            valor: $filter('rellenarDigitos')(chofer.id, 3) + ' - ' + chofer.nombre
                        });

                        $filter('filter')($scope.botonera, {
                            label: 'Chofer',
                        })[0].checked = true;
                    }, function () {
                        // funcion ejecutada cuando se cancela el modal
                    }
                );
            };

            $scope.seleccionarGraficar = function () {
                if (!$scope.hojaRuta.vehiculo.cisternas.length) {
                    focaModalService.alert('Primero seleccione un vehículo con cisternas');
                    return;
                }
                $uibModal.open(
                    {
                        ariaLabelledBy: 'Grafico de cisternas',
                        templateUrl: 'modal-grafico-cisternas.html',
                        controller: 'focaModalGraficoCisternasController',
                        size: 'md',
                        resolve: {
                            filters: {
                                cisternas: $scope.hojaRuta.vehiculo.cisternas
                            }
                        }
                    }
                );
            };

            function elegirTransportista(transportista) {
                var codigo = ('00000' + transportista.COD).slice(-5);
                $scope.idTransportista = transportista.COD;
                $scope.filtros = transportista.NOM.trim();
                $scope.$broadcast('addCabecera', {
                    label: 'Transportista:',
                    valor: codigo + ' - ' + transportista.NOM
                });
            }

            function getEstadosCisternas(cisternas) {
                cisternas.forEach(function (cisterna) {
                    focaOrdenCargaService
                        .getEstadoCisterna(cisterna.id, $scope.fecha)
                        .then(function (res) {
                            cisterna.estado = res.data;
                        })
                        .catch(function (err) { console.error(err) });
                });
            }

            function mostrarDetalle(hojasRutas) {
                var modalInstance = $uibModal.open(
                    {
                        ariaLabelledBy: '',
                        templateUrl: 'modal-detalle-carga.html',
                        controller: 'focaModalDetalleController',
                        resolve: {
                            parametrosModal: function () {
                                return {
                                    hojasRutas: hojasRutas,
                                    orden: $scope.hojaRuta.orden
                                };
                            }
                        },
                        size: 'lg',
                        backdrop: false
                    }
                );
                return modalInstance.result
                    .then(function (res) {
                        res.cisternas.forEach(function (cisterna) {
                            $scope.cisternaCargas.push(cisterna.cisternaCarga);
                        });
                        $scope.cisternaMovimientos = res.movimientos;
                        $scope.articulosRecibidos = res.articulos;
                        $scope.articulos = res.articulos;
                        $filter('filter')($scope.botonera, {
                            label: 'Detalle de Carga',
                        })[0].checked = true;
                    })
                    .catch(function (e) { console.error(e); });
            };

            function crearOrdenCarga() {
                if (!$scope.hojaRuta.vehiculo) {
                    focaModalService.alert('Ingrese Vehículo');
                    return;
                } else if (!$scope.hojaRuta.chofer) {
                    focaBotoneraLateralService.alert('Ingrese Chofer');
                    return;
                }

                focaBotoneraLateralService.startGuardar();
                $scope.saveLoading = true;

            }

            $scope.$watch('ordenCarga', function (newValue) {
                focaBotoneraLateralService.setPausarData({
                    label: 'ordenCarga',
                    val: newValue
                });
            }, true);

            $scope.$watch('ordenCarga', function (newValue) {
                focaBotoneraLateralService.setPausarData({
                    label: 'ordenCarga',
                    val: newValue
                });
                focaBotoneraLateralService.setRutasPausadas({
                    label: 'rutas',
                    val: 'orden-carga'
                });
            }, true);

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

            function salir() {
                var confirmacion = false;

                if (!angular.equals($scope.ordenCarga, $scope.inicial)) {
                    confirmacion = true;
                }

                if (confirmacion) {
                    focaModalService.confirm(
                        '¿Está seguro de que desea salir? Se perderán todos los datos cargados.'
                    ).then(function (data) {
                        if (data) {
                            $location.path('/');
                        }
                    });
                } else {
                    $location.path('/');
                }
            }
        }]);