controller.js 13.1 KB
angular.module('focaCrearCobranza') .controller('cobranzaController',
    [
        '$scope',
        '$uibModal',
        '$location',
        '$filter',
        'focaCrearCobranzaService',
        'focaModalService',
        function($scope, $uibModal, $location, $filter, focaCrearCobranzaService, focaModalService)
        {
            $scope.botonera = [
                {texto: 'Cliente', accion: function() {$scope.seleccionarCliente();}},
                {texto: 'Cobrador', accion: function() {$scope.seleccionarCobrador();}},
                {texto: 'Deuda', accion: function() {$scope.swichDeuda();}},
                {texto: 'Cobros', accion: function() {$scope.swichCobro();}},
                {texto: 'Moneda', accion: function() {$scope.seleccionarMoneda();}},
                {texto: '', accion: function() {}},
                {texto: '', accion: function() {}},
                {texto: '', accion: function() {}}
            ];
            $scope.datepickerAbierto = false;
            $scope.cobroDeuda = true;
            $scope.show = false;
            $scope.cargando = true;
            $scope.dateOptions = {
                maxDate: new Date(),
                minDate: new Date(2010, 0, 1)
            };

            $scope.cobranza = {
                fecha: new Date()
            };

            $scope.cabecera = [];
            $scope.showCabecera = true;

            $scope.now = new Date();
            $scope.puntoVenta = '0000';
            $scope.comprobante = '00000000';
            $scope.facturaTabla = [];
            $scope.cobrosTabla = [];

            var monedaPorDefecto;
            //Trabajo con la cotización más reciente, por eso uso siempre la primera '[0]'
            focaCrearCobranzaService.getCotizacionByIdMoneda(1).then(function(res) {
                monedaPorDefecto = res.data[0];
                addCabecera('Moneda:', monedaPorDefecto.DETALLE);
                addCabecera('Fecha cotizacion:',
                    new Date(monedaPorDefecto.cotizaciones[0].FECHA).toLocaleDateString());
                addCabecera('Cotizacion:', monedaPorDefecto.cotizaciones[0].VENDEDOR);
                $scope.cobranza.moneda = monedaPorDefecto;
                $scope.cobranza.cotizacion = monedaPorDefecto.cotizaciones[0];
            });

            focaCrearCobranzaService.getNumeroRecibo().then(
                function(res) {
                    $scope.puntoVenta = $scope.rellenar(res.data.sucursal, 4);
                    $scope.comprobante = $scope.rellenar(res.data.numeroRecibo, 8);
                },
                function(err) {
                    focaModalService.alert('La terminal no esta configurada correctamente');
                    console.info(err);
                }
            );
            $scope.crearCobranza = function() {
                if(!$scope.cobranza.cliente) {
                    focaModalService.alert('Ingrese Cliente');
                    return;
                }
                if($scope.facturaTabla.length < 1) {
                    focaModalService.alert('Ingrese al menos una factura');
                    return;
                }
                if($scope.getTotalCobrado() - $scope.getTotalDeuda() !== 0) {
                    focaModalService.alert('La diferencia debe ser ' +
                        $scope.cobranza.moneda.SIMBOLO + '0,00');
                    return;
                }
                //TODO: Guarda cobranza
                // var date = new Date();
                // var cobranza = {
                // };
            };

            $scope.swichCobro = function() {
                $scope.cobroDeuda = false;
            };

            $scope.swichDeuda = function() {
                $scope.cobroDeuda = true;
            };

            $scope.seleccionarCliente = function() {

                var modalInstance = $uibModal.open(
                    {
                        ariaLabelledBy: 'Busqueda de Cliente',
                        templateUrl: 'foca-busqueda-cliente-modal.html',
                        controller: 'focaBusquedaClienteModalController',
                        size: 'lg'
                    }
                );
                modalInstance.result.then(
                    function(cliente) {
                        addCabecera('Cliente:', cliente.nom);
                        $scope.cobranza.cliente = {
                            COD: cliente.cod,
                            CUIT: cliente.cuit,
                            NOM: cliente.nom
                        };
                    }, function() {

                    }
                );
            };

            $scope.seleccionarFactura = function() {
                if(!$scope.cobranza.cliente) {
                    focaModalService.alert('Seleccione primero un cliente');
                    return;
                }
                var modalInstance = $uibModal.open(
                    {
                        ariaLabelledBy: 'Busqueda de Facturas',
                        templateUrl: 'foca-modal-factura.html',
                        controller: 'focaModalFacturaController',
                        size: 'lg',
                        resolve: {
                            parametrosFactura: {
                                cliente: $scope.cobranza.cliente.COD,
                                simbolo: $scope.cobranza.moneda.SIMBOLO,
                                cotizacion: $scope.cobranza.cotizacion.VENDEDOR
                            }
                        }
                    }
                );
                modalInstance.result.then(
                    function(facturas) {
                        $scope.facturaTabla = $scope.facturaTabla.concat(facturas);
                    }, function() {

                    }
                );
            };

            $scope.seleccionarCheque = function() {
                var modalInstance = $uibModal.open(
                    {
                        ariaLabelledBy: 'Carga de cheques',
                        templateUrl: 'modal-cheque.html',
                        controller: 'focaModalChequeController',
                        size: 'lg'
                    }
                );
                modalInstance.result.then(
                    function(cheque) {
                        var cobro = {
                            tipo: 'Ch' + '(' + cheque.numero + ')' + ' ' + cheque.banco,
                            fecha: cheque.fechaPresentacion,
                            importe: cheque.importe * $scope.cobranza.cotizacion.VENDEDOR
                        };
                        $scope.cobrosTabla.push(cobro);
                    }, function() {

                    }
                );
            };
            
            $scope.seleccionarEfectivo = function() {
                var modalInstance = $uibModal.open(
                    {
                        ariaLabelledBy: 'Carga de cheques',
                        templateUrl: 'modal-efectivo.html',
                        controller: 'focaModalEfectivoController',
                        size: 'sm'
                    }
                );
                modalInstance.result.then(
                    function(efectivo) {
                        var cobro = {
                            tipo: 'Efectivo',
                            fecha: new Date(),
                            importe: efectivo * $scope.cobranza.cotizacion.VENDEDOR
                        };
                        $scope.cobrosTabla.push(cobro);
                    }, function() {

                    }
                );
            };

            $scope.seleccionarMoneda = function() {
                var modalInstance = $uibModal.open(
                    {
                        ariaLabelledBy: 'Busqueda de Moneda',
                        templateUrl: 'modal-moneda.html',
                        controller: 'focaModalMonedaController',
                        size: 'lg'
                    }
                );
                modalInstance.result.then(
                    function(moneda) {
                        $scope.seleccionarCotizacion(moneda);
                    }, function() {

                    }
                );
            };
            
            $scope.seleccionarCobrador = function() {
                var modalInstance = $uibModal.open(
                    {
                        ariaLabelledBy: 'Busqueda de Cobradores',
                        templateUrl: 'modal-cobradores.html',
                        controller: 'focaModalCobradoresController',
                        size: 'lg'
                    }
                );
                modalInstance.result.then(
                    function(cobrador) {
                        addCabecera('Cobrador:', cobrador.nombre);
                        $scope.cobranza.cobrador = cobrador;
                    }, function() {

                    }
                );
            };

            $scope.seleccionarCotizacion = function(moneda) {
                var modalInstance = $uibModal.open(
                    {
                        ariaLabelledBy: 'Busqueda de Cotización',
                        templateUrl: 'modal-cotizacion.html',
                        controller: 'focaModalCotizacionController',
                        size: 'lg',
                        resolve: {idMoneda: function() {return moneda.ID;}}
                    }
                );
                modalInstance.result.then(
                    function(cotizacion) {
                        $scope.cobranza.moneda = moneda;
                        $scope.cobranza.cotizacion = cotizacion;
                        addCabecera('Moneda:', moneda.DETALLE);
                        addCabecera(
                            'Fecha cotizacion:',
                            $filter('date')(cotizacion.FECHA, 'dd/MM/yyyy')
                        );
                        addCabecera('Cotizacion:', cotizacion.VENDEDOR);
                    }, function() {

                    }
                );
            };
            
            $scope.agregarCobro = function(key) {
                if(key === 13) {
                    var cobro = {
                        cobro: 'Efectivo',
                        fecha: new Date(),
                        importe: $scope.cobroEfectivo
                    };
                    $scope.cobrosTabla.push(cobro);
                }
            };

            $scope.getTotalDeuda = function() {
                var total = 0;
                for (var i = 0; i < $scope.facturaTabla.length; i++) {
                    total += $scope.facturaTabla[i].IPA;
                }
                return parseFloat(total.toFixed(2));
            };

            $scope.getTotalCobrado = function() {
                var total = 0;
                for (var i = 0; i < $scope.cobrosTabla.length; i++) {
                    total += $scope.cobrosTabla[i].importe;
                }
                return parseFloat(total.toFixed(2));
            };

            $scope.getSubTotal = function() {
                if($scope.articuloACargar) {
                    return $scope.articuloACargar.precio * $scope.articuloACargar.cantidad;
                }
            };
            //Recibe aviso si el teclado está en uso
            // $rootScope.$on('usarTeclado', function(event, data) {
                // if(data) {
                    // $scope.mostrarTeclado = true;
                    // return;
                // }
                // $scope.mostrarTeclado = false;
            // })
            $scope.selectFocus = function($event) {
                //Si el teclado esta en uso no selecciona el valor
                // if($scope.mostrarTeclado) {
                    // return;
                // }
                $event.target.select();
            };

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

            $scope.parsearATexto = function(articulo) {
                articulo.cantidad = parseFloat(articulo.cantidad);
                articulo.precio = parseFloat(articulo.precio);
            };

            $scope.rellenar = function(relleno, longitud) {
                relleno = '' + relleno;
                while (relleno.length < longitud) {
                    relleno = '0' + relleno;
                }

                return relleno;
            };

            $scope.quitarFactura = function(key) {
                $scope.facturaTabla.splice(key, 1);
            };

            $scope.quitarCobro = function(key) {
                $scope.cobrosTabla.splice(key, 1);
            };

            function addCabecera(label, valor) {
                var propiedad = $filter('filter')($scope.cabecera, {label: label}, true);
                if(propiedad.length === 1) {
                    propiedad[0].valor = valor;
                } else {
                    $scope.cabecera.push({label: label, valor: valor});
                }
            }
            // TODO: descomentar cuando se use
            /*function removeCabecera(label) {
                var propiedad = $filter('filter')($scope.cabecera, {label: label}, true);
                if(propiedad.length === 1){
                    $scope.cabecera.splice($scope.cabecera.indexOf(propiedad[0]), 1);
                }
            }*/
        }
    ]);