controller.js 44.6 KB
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 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
angular.module('focaCrearNotaPedido') .controller('notaPedidoCtrl',
    [
        '$scope',
        '$uibModal',
        '$location',
        '$filter',
        '$timeout',
        'crearNotaPedidoService',
        'focaBotoneraLateralService',
        'focaModalService',
        'notaPedidoBusinessService',
        '$rootScope',
        'focaSeguimientoService',
        'APP',
        'focaLoginService',
        '$localStorage',
        function(
            $scope, $uibModal, $location, $filter, $timeout, crearNotaPedidoService,
            focaBotoneraLateralService, focaModalService, notaPedidoBusinessService,
            $rootScope, focaSeguimientoService, APP, focaLoginService, $localStorage)
        {
            config();

            function config() {
                // PARAMETROS INICIALES PARA FUNCIONAMIENTO DEL PROGRAMA
                $scope.tmpCantidad = Number;
                $scope.tmpPrecio = Number;
                $scope.notaPedido = {};
                $scope.isNumber = angular.isNumber;
                $scope.datepickerAbierto = false;
                $scope.show = false;
                $scope.cargando = true;
                $scope.botonera = crearNotaPedidoService.getBotonera();
                $scope.puntoVenta = $filter('rellenarDigitos')(0, 4);
                $scope.comprobante = $filter('rellenarDigitos')(0, 8);
                $scope.dateOptions = {
                    maxDate: new Date(),
                    minDate: new Date(2010, 0, 1)
                };

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

                // SETEA BOTONERA DE FACTURADOR TENIENDO EN CUENTA SI ESTA SETEADO EL VENDEDOR
                if (APP === 'distribuidor') {
                    $scope.idVendedor = focaLoginService.getLoginData().vendedorCobrador;
                }

                //Trabajo con la cotización más reciente, por eso uso siempre la primera '[0]'
                crearNotaPedidoService.getCotizacionByIdMoneda(1).then(function(res) {
                    var monedaPorDefecto = res.data[0];
                    $scope.notaPedido.cotizacion = Object.assign(
                        {moneda: monedaPorDefecto},
                        monedaPorDefecto.cotizaciones[0]
                    );
                    $scope.inicial.cotizacion = $scope.notaPedido.cotizacion;
                    $timeout(function() {getLSNotaPedido();});
                });

                init();
                
            }

            function init() {
                $scope.$broadcast('cleanCabecera');

                $scope.notaPedido = {
                    id: 0,
                    cliente: {},
                    proveedor: {},
                    domicilio: {dom: ''},
                    vendedor: {},
                    fechaCarga: new Date(),
                    cotizacion: {},
                    articulosNotaPedido: [],
                    notaPedidoPlazo: [],
                    notaPedidoPuntoDescarga: {
                        puntoDescarga: {}   
                    }
                };
                $scope.idLista = undefined;

                crearNotaPedidoService.getNumeroNotaPedido().then(
                    function(res) {
                        $scope.puntoVenta = $filter('rellenarDigitos')(
                            res.data.sucursal, 4
                        );
                        
                        $scope.comprobante = $filter('rellenarDigitos')(
                            res.data.numeroNotaPedido, 8
                        );
                    },
                    function(err) {
                        focaModalService.alert('La terminal no esta configurada correctamente');
                        console.info(err);
                    }
                );

                if (APP === 'distribuidor') {
                    crearNotaPedidoService.getVendedorById($scope.idVendedor).then(
                        function(res) {
                            var vendedor = res.data;
                            $scope.$broadcast('addCabecera', {
                                label: 'Vendedor:',
                                valor: $filter('rellenarDigitos')(vendedor.NUM, 3) + ' - ' +
                                    vendedor.NOM
                            });

                            $scope.notaPedido.vendedor = vendedor;
                        }
                    );
                }

                $scope.inicial = angular.copy($scope.notaPedido);
            }

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

            $scope.crearNotaPedido = function() {
                if (!$scope.notaPedido.cliente.COD ) {
                    focaModalService.alert('Ingrese Cliente');
                    return;
                } else if ($scope.notaPedido.idRemito === -1) {
                    focaBotoneraLateralService.alert('No se puede modificar esta nota de pedido');
                    return;
                } else if (!$scope.notaPedido.proveedor.COD) {
                    focaModalService.alert('Ingrese Proveedor');
                    return;
                } else if (!$scope.notaPedido.cotizacion.ID) {
                    focaModalService.alert('Ingrese Cotización');
                    return;
                } else if (!$scope.notaPedido.cotizacion.moneda.ID) {
                    focaModalService.alert('Ingrese Moneda');
                    return;
                } else if (!$scope.notaPedido.notaPedidoPlazo) {
                    focaModalService.alert('Ingrese Precios y Condiciones');
                    return;
                } else if (
                    $scope.notaPedido.flete === undefined || $scope.notaPedido.flete === null)
                {
                    focaModalService.alert('Ingrese Flete');
                    return;
                } else if (!$scope.notaPedido.domicilioStamp) {//TODO validar domicilio correcto
                    focaModalService.alert('Ingrese Domicilio');
                    return;
                } else if ($scope.notaPedido.articulosNotaPedido.length === 0) {
                    focaModalService.alert('Debe cargar al menos un articulo');
                    return;
                }
                focaBotoneraLateralService.startGuardar();
                    $scope.saveLoading = true;
                    var notaPedido = {
                        id: $scope.notaPedido.id,
                        fechaCarga: new Date($scope.notaPedido.fechaCarga)
                            .toISOString().slice(0, 19).replace('T', ' '),
                        idVendedor: $scope.notaPedido.vendedor.id,
                        idCliente: $scope.notaPedido.cliente.COD,
                        nombreCliente: $scope.notaPedido.cliente.NOM,
                        cuitCliente: $scope.notaPedido.cliente.CUIT,
                        idProveedor: $scope.notaPedido.proveedor.COD,
                        idDomicilio: $scope.notaPedido.domicilio.id,
                        idCotizacion: $scope.notaPedido.cotizacion.ID,
                        idPrecioCondicion: $scope.notaPedido.idPrecioCondicion,
                        cotizacion: $scope.notaPedido.cotizacion.VENDEDOR,
                        flete: $scope.notaPedido.flete,
                        fob: $scope.notaPedido.fob,
                        bomba: $scope.notaPedido.bomba,
                        kilometros: $scope.notaPedido.kilometros,
                        domicilioStamp: $scope.notaPedido.domicilioStamp,
                        observaciones: $scope.notaPedido.observaciones,
                        estado: 0,
                        total: $scope.getTotal()
                    };
                crearNotaPedidoService.crearNotaPedido(notaPedido).then(
                    function(data) {
                        // Al guardar los datos de la nota de pedido logueamos la
                        // actividad para su seguimiento.
                        //TODO: GUARDAR POSISIONAMIENTO AL EDITAR?
                        focaSeguimientoService.guardarPosicion(
                            'Nota de pedido',
                            data.data.id,
                            ''
                        );
                        notaPedidoBusinessService.addArticulos(
                            $scope.notaPedido.articulosNotaPedido,
                            data.data.id, $scope.notaPedido.cotizacion.VENDEDOR);

                        if ($scope.notaPedido.notaPedidoPuntoDescarga) {
                            notaPedidoBusinessService.addPuntosDescarga(data.data.id,
                                $scope.notaPedido.notaPedidoPuntoDescarga);
                        }

                        var plazos = $scope.notaPedido.notaPedidoPlazo;
                        var plazosACrear = [];
                        plazos.forEach(function(plazo) {
                            plazosACrear.push({
                                idNotaPedido: data.data.id,
                                dias: plazo.dias
                            });
                        });

                        if (plazosACrear.length) {
                            crearNotaPedidoService.crearPlazosParaNotaPedido(plazosACrear);
                        }

                        notaPedidoBusinessService.addEstado(data.data.id,
                            $scope.notaPedido.vendedor.id);

                        focaBotoneraLateralService.endGuardar(true);
                        $scope.saveLoading = false;

                        init();
                    }, function(error) {
                        focaModalService.alert('Hubo un error al crear la nota de pedido');
                        focaBotoneraLateralService.endGuardar();
                        $scope.saveLoading = false;
                        console.info(error);
                    });
            };

            $scope.seleccionarNotaPedido = function() {
                var modalInstance = $uibModal.open(
                    {
                        ariaLabelledBy: 'Busqueda de Nota de Pedido',
                        templateUrl: 'foca-modal-nota-pedido.html',
                        controller: 'focaModalNotaPedidoController',
                        size: 'lg',
                        resolve: {
                            usadoPor: function() {return 'notaPedido';},
                            idVendedor: function() {
                                if (APP === 'distribuidor')
                                    return $scope.notaPedido.vendedor.id;
                                else
                                    return null;
                            }
                        }
                    }
                );
                modalInstance.result.then(setearNotaPedido);
            };

            $scope.seleccionarProductos = function() {
                if ($scope.idLista === undefined) {
                    focaModalService.alert(
                        'Primero seleccione una lista de precio y condicion');
                    return;
                }
                var modalInstance = $uibModal.open(
                    {
                        ariaLabelledBy: 'Busqueda de Productos',
                        templateUrl: 'modal-busqueda-productos.html',
                        controller: 'modalBusquedaProductosCtrl',
                        resolve: {
                            parametroProducto: {
                                idLista: $scope.idLista,
                                cotizacion: $scope.notaPedido.cotizacion.VENDEDOR,
                                simbolo: $scope.notaPedido.cotizacion.moneda.SIMBOLO
                            }
                        },
                        size: 'lg'
                    }
                );
                modalInstance.result.then(
                    function(producto) {
                        var newArt =
                        {
                            id: 0,
                            codigo: producto.codigo,
                            sector: producto.sector,
                            sectorCodigo: producto.sector + '-' + producto.codigo,
                            descripcion: producto.descripcion,
                            item: $scope.notaPedido.articulosNotaPedido.length + 1,
                            nombre: producto.descripcion,
                            precio: parseFloat(producto.precio.toFixed(4)),
                            costoUnitario: producto.costo,
                            editCantidad: false,
                            editPrecio: false,
                            rubro: producto.CodRub,
                            exentoUnitario: producto.precio,
                            ivaUnitario: producto.IMPIVA,
                            impuestoInternoUnitario: producto.ImpInt,
                            impuestoInterno1Unitario: producto.ImpInt2,
                            impuestoInterno2Unitario: producto.ImpInt3, 
                            precioLista: producto.precio,
                            combustible: 1,
                            facturado: 0,
                            idArticulo: producto.id
                        };
                        $scope.articuloACargar = newArt;
                        $scope.cargando = false;
                    }, function() {
                        // funcion ejecutada cuando se cancela el modal
                    }
                );
            };

            $scope.seleccionarPuntosDeDescarga = function() {
                if (!$scope.notaPedido.cliente.COD || !$scope.notaPedido.domicilio.id) {
                    focaModalService.alert('Primero seleccione un cliente y un domicilio');
                    return;
                } else {
                    var modalInstance = $uibModal.open(
                        {
                            ariaLabelledBy: 'Búsqueda de Puntos de descarga',
                            templateUrl: 'modal-punto-descarga.html',
                            controller: 'focaModalPuntoDescargaController',
                            size: 'lg',
                            resolve: {
                                filters: {
                                    idDomicilio: $scope.notaPedido.domicilio.id,
                                    idCliente: $scope.notaPedido.cliente.COD,
                                    articulos: $scope.notaPedido.articulosNotaPedido,
                                    puntoDescarga: $scope.notaPedido.notaPedidoPuntoDescarga,
                                    domicilio: $scope.notaPedido.domicilio
                                }
                            }
                        }
                    );
                    modalInstance.result.then(
                        function(puntoDescarga) {
                            $scope.notaPedido.notaPedidoPuntoDescarga = puntoDescarga;

                            $scope.$broadcast('addCabecera', {
                                label: 'Puntos de descarga:',
                                valor: getCabeceraPuntoDescarga(puntoDescarga)
                            });
                        }, function() {
                            $scope.abrirModalDomicilios($scope.cliente);
                        }
                    );
                }
            };

            $scope.seleccionarProveedor = function() {
                $scope.abrirModalProveedores(function() {
                    if (validarNotaRemitada()) {
                        var modalInstance = $uibModal.open(
                            {
                                ariaLabelledBy: 'Busqueda de Flete',
                                templateUrl: 'modal-flete.html',
                                controller: 'focaModalFleteController',
                                size: 'lg',
                                resolve: {
                                    parametrosFlete:
                                        function() {
                                            return {
                                                flete: $scope.notaPedido.fob ? 'FOB' :
                                                    ( $scope.notaPedido.flete ? '1' :
                                                    ($scope.notaPedido.flete === undefined ?
                                                        null : '0')),
                                                bomba: $scope.notaPedido.bomba ? '1' :
                                                    ($scope.notaPedido.bomba === undefined ?
                                                        null : '0'),
                                                kilometros: $scope.notaPedido.kilometros
                                            };
                                        }
                                }
                            }
                        );
                        modalInstance.result.then(
                            function(datos) {
                                $scope.notaPedido.flete = datos.flete;
                                $scope.notaPedido.fob = datos.FOB;
                                $scope.notaPedido.bomba = datos.bomba;
                                $scope.notaPedido.kilometros = datos.kilometros;
                                $scope.$broadcast('addCabecera', {
                                    label: 'Flete:',
                                    valor: datos.FOB ? 'FOB' : (datos.flete ? 'Si' : 'No')
                                });
                                if (datos.flete) {
                                    $scope.$broadcast('addCabecera', {
                                        label: 'Bomba:',
                                        valor: datos.bomba ? 'Si' : 'No'
                                    });
                                    $scope.$broadcast('addCabecera', {
                                        label: 'Kilometros:',
                                        valor: datos.kilometros
                                    });
                                } else {
                                    $scope.$broadcast('removeCabecera', 'Bomba:');
                                    $scope.$broadcast('removeCabecera', 'Kilometros:');
                                    $scope.notaPedido.bomba = false;
                                    $scope.notaPedido.kilometros = null;
                                }
                            }, function() {
                                $scope.seleccionarTransportista();
                            }
                        );
                    }
                });
            };

            $scope.seleccionarVendedor = function(callback, ocultarVendedor) {
                if (APP === 'distribuidor' || ocultarVendedor) {
                    callback();
                    return;
                }

                if (validarNotaRemitada()) {
                    var parametrosModal = {
                        titulo: 'Búsqueda vendedores',
                        query: '/vendedor',
                        columnas: [
                            {
                                propiedad: 'NUM',
                                nombre: 'Código',
                                filtro: {
                                    nombre: 'rellenarDigitos',
                                    parametro: 3
                                }
                            },
                            {
                                propiedad: 'NOM',
                                nombre: 'Nombre'
                            }
                        ],
                        size: 'md'
                    };
                    focaModalService.modal(parametrosModal).then(
                        function(vendedor) {
                            $scope.$broadcast('addCabecera', {
                                label: 'Vendedor:',
                                valor: $filter('rellenarDigitos')(vendedor.NUM, 3) + ' - ' +
                                    vendedor.NOM
                            });
                            $scope.notaPedido.vendedor = vendedor;
                            deleteCliente();
                            callback();
                        }, function() {}
                    );
                }
            };

            $scope.seleccionarCliente = function(ocultarVendedor) {
                $scope.seleccionarVendedor(function() {
                    if (validarNotaRemitada()) {
                        var modalInstance = $uibModal.open(
                            {
                                ariaLabelledBy: 'Busqueda de Cliente',
                                templateUrl: 'foca-busqueda-cliente-modal.html',
                                controller: 'focaBusquedaClienteModalController',
                                resolve: {
                                    vendedor: function() { return $scope.notaPedido.vendedor; },
                                    cobrador: function() { return null; }
                                },
                                size: 'lg'
                            }
                        );
                        modalInstance.result.then(
                            function(cliente) {
                                $scope.abrirModalDomicilios(cliente);
                                $scope.cliente = cliente;
                            }, function() {
                                if (APP !== 'distribuidor') $scope.seleccionarCliente();
                            }
                        );
                    }
                }, ocultarVendedor);
            };

            $scope.abrirModalProveedores = function(callback) {
                if (validarNotaRemitada()) {
                    var parametrosModal = {
                        titulo: 'Búsqueda de Proveedor',
                        query: '/proveedor',
                        columnas: [
                            {
                                nombre: 'Código',
                                propiedad: 'COD',
                                filtro: {
                                    nombre: 'rellenarDigitos',
                                    parametro: 5
                                }
                            },
                            {
                                nombre: 'Nombre',
                                propiedad: 'NOM'
                            },
                            {
                                nombre: 'CUIT',
                                propiedad: 'CUIT'
                            }
                        ],
                        tipo: 'POST',
                        json: {razonCuitCod: ''}
                    };
                    focaModalService.modal(parametrosModal).then(
                        function(proveedor) {
                            $scope.notaPedido.proveedor = proveedor;
                            $scope.$broadcast('addCabecera', {
                                label: 'Proveedor:',
                                valor: $filter('rellenarDigitos')(proveedor.COD, 5) + ' - ' +
                                    proveedor.NOM
                            });
                            callback();
                        }, function() {

                        }
                    );
                }
            };

            $scope.abrirModalDomicilios = function(cliente) {
                var modalInstanceDomicilio = $uibModal.open(
                    {
                        ariaLabelledBy: 'Busqueda de Domicilios',
                        templateUrl: 'modal-domicilio.html',
                        controller: 'focaModalDomicilioController',
                        resolve: { 
                            idCliente: function() { return cliente.cod; },
                            esNuevo: function() { return cliente.esNuevo; }
                        },
                        size: 'lg',
                    }
                );
                modalInstanceDomicilio.result.then(
                    function(domicilio) {
                        $scope.notaPedido.domicilio = domicilio;
                        $scope.notaPedido.cliente = {
                            COD: cliente.cod,
                            CUIT: cliente.cuit,
                            NOM: cliente.nom,
                            MOD: cliente.mod
                        };
                        var domicilioStamp = 
                            domicilio.Calle + ' ' + domicilio.Numero + ', ' + 
                            domicilio.Localidad + ', ' + domicilio.Provincia;
                        $scope.notaPedido.domicilioStamp = domicilioStamp;

                        $scope.notaPedido.notaPedidoPuntoDescarga = domicilio.puntoDescarga;

                        $scope.$broadcast('addCabecera', {
                            label: 'Cliente:',
                            valor: $filter('rellenarDigitos')(cliente.cod, 5) + ' - ' + cliente.nom
                        });
                        $scope.$broadcast('addCabecera', {
                            label: 'Domicilio:',
                            valor: domicilioStamp
                        });
                        if (domicilio.verPuntos) {
                            delete $scope.notaPedido.domicilio.verPuntos;
                            $scope.seleccionarPuntosDeDescarga();
                        } else {
                            crearNotaPedidoService
                                .getPuntosDescargaByClienDom(domicilio.id, cliente.cod)
                                .then(function(res) {
                                    if (res.data.length) $scope.seleccionarPuntosDeDescarga();
                                });
                        }
                    }, function() {
                        $scope.seleccionarCliente(true);
                        return;
                    }
                );
            };

            $scope.getTotal = function() {
                var total = 0;
                if ($scope.notaPedido.articulosNotaPedido) {
                    var arrayTempArticulos = $scope.notaPedido.articulosNotaPedido;
                    for (var i = 0; i < arrayTempArticulos.length; i++) {
                        total += arrayTempArticulos[i].precio * arrayTempArticulos[i].cantidad;
                    }
                }
                return parseFloat(total.toFixed(2));
            };

            $scope.getSubTotal = function() {
                if ($scope.articuloACargar) {
                    return $scope.articuloACargar.precio * $scope.articuloACargar.cantidad;
                }
            };

            $scope.seleccionarPreciosYCondiciones = function() {
                if (!$scope.notaPedido.cliente.COD) {
                    focaModalService.alert('Primero seleccione un cliente');
                    return;
                }
                if ($scope.notaPedido.articulosNotaPedido.length !== 0) {
                        focaModalService.confirm('Se perderan los productos ingresados').then(function(data) {
                            if (data) {
                                abrirModal();
                            }
                        });
                } else if (validarNotaRemitada()) {
                    abrirModal();
                }
                function abrirModal() {
                    var modalInstance = $uibModal.open(
                        {
                            ariaLabelledBy: 'Busqueda de Precio Condición',
                            templateUrl: 'modal-precio-condicion.html',
                            controller: 'focaModalPrecioCondicionController',
                            size: 'lg',
                            resolve: {
                                idListaPrecio: function() {
                                    return $scope.notaPedido.cliente.MOD || null;
                                }
                            }
                        }
                    );

                    modalInstance.result.then(
                        function(precioCondicion) {
                            var cabecera = '';
                            var plazosConcat = '';
                            if (!Array.isArray(precioCondicion)) {
                                $scope.notaPedido.notaPedidoPlazo = precioCondicion.plazoPago;
                                $scope.notaPedido.precioCondicion = precioCondicion;
                                $scope.notaPedido.idPrecioCondicion = precioCondicion.id;
                                $scope.idLista = precioCondicion.idListaPrecio;
                                for (var i = 0; i < precioCondicion.plazoPago.length; i++) {
                                    plazosConcat += precioCondicion.plazoPago[i].dias + ' ';
                                }
                                cabecera = $filter('rellenarDigitos')(precioCondicion.id, 4) +
                                    ' - ' + precioCondicion.nombre + ' ' + plazosConcat.trim();
                            } else { //Cuando se ingresan los plazos manualmente
                                $scope.notaPedido.idPrecioCondicion = 0;
                                //-1, el modal productos busca todos los productos
                                $scope.idLista = -1; 
                                $scope.notaPedido.notaPedidoPlazo = precioCondicion;
                                for (var j = 0; j < precioCondicion.length; j++) {
                                    plazosConcat += precioCondicion[j].dias + ' ';
                                }
                                cabecera = 'Ingreso manual ' + plazosConcat.trim();
                            }
                            $scope.notaPedido.articulosNotaPedido = [];
                            $scope.$broadcast('addCabecera', {
                                label: 'Precios y condiciones:',
                                valor: cabecera
                            });
                        }, function() {

                        }
                    );
                }
            };

            $scope.seleccionarMoneda = function() {
                if (validarNotaRemitada()) {
                    var parametrosModal = {
                        titulo: 'Búsqueda de monedas',
                        query: '/moneda',
                        columnas: [
                            {
                                propiedad: 'DETALLE',
                                nombre: 'Nombre'
                            },
                            {
                                propiedad: 'SIMBOLO',
                                nombre: 'Símbolo'
                            }
                        ],
                        size: 'md'
                    };
                    focaModalService.modal(parametrosModal).then(
                        function(moneda) {
                            $scope.abrirModalCotizacion(moneda);
                        }, function() {

                        }
                    );
                }
            };

            $scope.seleccionarObservaciones = function() {
                var observacion = {
                    titulo: 'Ingrese Observaciones',
                    value: $scope.notaPedido.observaciones,
                    maxlength: 155,
                    textarea: true
                };

                focaModalService
                    .prompt(observacion)
                    .then(function(observaciones) {
                        $scope.notaPedido.observaciones = observaciones;
                    });
            };

            $scope.abrirModalCotizacion = 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) {
                        var articulosTablaTemp = $scope.notaPedido.articulosNotaPedido || [];
                        for (var i = 0; i < articulosTablaTemp.length; i++) {
                            articulosTablaTemp[i].precio = articulosTablaTemp[i].precio *
                                $scope.notaPedido.cotizacion.VENDEDOR;
                            articulosTablaTemp[i].precio = articulosTablaTemp[i].precio /
                                cotizacion.VENDEDOR;
                        }
                        $scope.notaPedido.articulosNotaPedido = articulosTablaTemp;
                        $scope.notaPedido.cotizacion = cotizacion;
                        $scope.notaPedido.cotizacion.moneda = moneda;
                        if (moneda.DETALLE === 'PESOS ARGENTINOS') {
                            $scope.$broadcast('removeCabecera', 'Moneda:');
                            $scope.$broadcast('removeCabecera', 'Fecha cotizacion:');
                            $scope.$broadcast('removeCabecera', 'Cotizacion:');
                        } else {
                            $scope.$broadcast('addCabecera', {
                                label: 'Moneda:',
                                valor: moneda.DETALLE
                            });
                            $scope.$broadcast('addCabecera', {
                                label: 'Fecha cotizacion:',
                                valor: $filter('date')(cotizacion.FECHA, 'dd/MM/yyyy')
                            });
                            $scope.$broadcast('addCabecera', {
                                label: 'Cotizacion:',
                                valor: $filter('number')(cotizacion.VENDEDOR, '2')
                            });
                        }
                    }, function() {

                    }
                );
            };

            $scope.agregarATabla = function(key) {
                if (key === 13) {
                    if ($scope.articuloACargar.cantidad === undefined ||
                        $scope.articuloACargar.cantidad === 0 ||
                        $scope.articuloACargar.cantidad === null ) {
                            focaModalService.alert('El valor debe ser al menos 1');
                            return;
                    }
                    delete $scope.articuloACargar.sectorCodigo;
                    $scope.notaPedido.articulosNotaPedido.push($scope.articuloACargar);
                    $scope.cargando = true;
                }
            };

            $scope.quitarArticulo = function(key) {
                $scope.notaPedido.articulosNotaPedido.splice(key, 1);
            };

            $scope.editarArticulo = function(key, articulo, tmpCantidad, tmpPrecio) {             
                if (key === 13) {
                    if (!articulo.cantidad || !articulo.precio) {
                        focaModalService.alert('Los valores deben ser al menos 1');
                        return;
                    } else if (articulo.cantidad < 0 || articulo.precio < 0) {
                        focaModalService.alert('Los valores no pueden ser negativos');
                        return;
                    }
                    articulo.cantidad = tmpCantidad;
                    articulo.precio = tmpPrecio;
                    $scope.getTotal();
                    articulo.editCantidad = articulo.editPrecio = false;
                }
            };
            
            $scope.cancelarEditar = function(articulo) {
                $scope.tmpCantidad = articulo.cantidad;
                $scope.tmpPrecio = articulo.precio;                
                articulo.editCantidad = articulo.editPrecio = false;                
            };            

            $scope.cambioEdit = function(articulo, propiedad) {
                if (propiedad === 'cantidad') {
                    articulo.editCantidad = true;
                } else if (propiedad === 'precio') {
                    articulo.editPrecio = true;
                }
            };

            $scope.resetFilter = function() {
                $scope.articuloACargar = {};
                $scope.cargando = true;
            };
            //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);
            };

            function setearNotaPedido(notaPedido) {
                //añado cabeceras

                if (validarNotaRemitada()) {
                    $scope.validar = true;
                } else {
                    $scope.validar = false;
                }

                $scope.notaPedido = notaPedido;
                if (!$scope.notaPedido.domicilio) {
                    $scope.notaPedido.domicilio = {
                        id: $scope.notaPedido.idDomicilio
                    };
                }
                $scope.$broadcast('removeCabecera', 'Bomba:');
                $scope.$broadcast('removeCabecera', 'Kilometros:');
                $scope.$broadcast('cleanCabecera');

                var cabeceras = [];

                if (notaPedido.cotizacion.moneda.CODIGO_AFIP !== 'PES') {
                    cabeceras.push({
                        label: 'Moneda:',
                        valor: notaPedido.cotizacion.moneda.DETALLE
                    });
                    cabeceras.push({
                        label: 'Fecha cotizacion:',
                        valor: $filter('date')(notaPedido.cotizacion.FECHA,
                            'dd/MM/yyyy')
                    });
                    cabeceras.push({
                        label: 'Cotizacion:',
                        valor: $filter('number')(notaPedido.cotizacion.VENDEDOR,
                            '2')
                    });
                }

                if (notaPedido.vendedor.NUM) {
                    cabeceras.push({
                        label: 'Vendedor:',
                        valor: $filter('rellenarDigitos')(notaPedido.vendedor.NUM, 3) +
                            ' - ' + notaPedido.vendedor.NOM
                    });
                }

                if (notaPedido.cliente.COD) {
                    cabeceras.push({
                        label: 'Cliente:',
                        valor: notaPedido.cliente.NOM
                    });
                    cabeceras.push({
                        label: 'Domicilio:',
                        valor: notaPedido.domicilioStamp
                    });
                }

                if (notaPedido.proveedor.COD) {
                    cabeceras.push({
                        label: 'Proveedor:',
                        valor: $filter('rellenarDigitos')(notaPedido.proveedor.COD, 5) +
                            ' - ' + notaPedido.proveedor.NOM
                    });
                }

                if (notaPedido.notaPedidoPlazo.length) {
                    cabeceras.push({
                        label: 'Precios y condiciones:',
                        valor: valorPrecioCondicion() + ' ' +
                            notaPedidoBusinessService
                                .plazoToString(notaPedido.notaPedidoPlazo)
                    });
                }

                if (notaPedido.flete !== undefined) {
                    cabeceras.push({
                        label: 'Flete:',
                        valor: notaPedido.fob === 1 ? 'FOB' : (
                            notaPedido.flete === 1 ? 'Si' : 'No')
                    });
                }

                function valorPrecioCondicion() {
                    if (notaPedido.idPrecioCondicion > 0) {
                        return notaPedido.precioCondicion.nombre;
                    } else {
                        return 'Ingreso Manual';
                    }
                }

                if (notaPedido.flete === 1) {
                    var cabeceraBomba = {
                        label: 'Bomba:',
                        valor: notaPedido.bomba === 1 ? 'Si' : 'No'
                    };
                    if (notaPedido.kilometros) {
                        var cabeceraKilometros = {
                            label: 'Kilometros:',
                            valor: notaPedido.kilometros
                        };
                        cabeceras.push(cabeceraKilometros);
                    }
                    cabeceras.push(cabeceraBomba);
                }

                if (notaPedido.idPrecioCondicion > 0) {
                    $scope.idLista = notaPedido.precioCondicion.idListaPrecio;
                } else {
                    $scope.idLista = -1;
                }

                $scope.puntoVenta = $filter('rellenarDigitos')(
                    notaPedido.sucursal, 4
                );

                $scope.comprobante = $filter('rellenarDigitos')(
                    notaPedido.numeroNotaPedido, 8
                );

                if (notaPedido.notaPedidoPuntoDescarga) {                    
                    var puntos = [];
                    notaPedido.notaPedidoPuntoDescarga.forEach(function(notaPedidoPuntoDescarga, idx, arr) {
                        puntos.push(notaPedidoPuntoDescarga.puntoDescarga);
                    });
                    cabeceras.push({
                        label: 'Puntos de descarga: ',
                        valor: $filter('rellenarDigitos')(getCabeceraPuntoDescarga(puntos))
                    });
                }

                addArrayCabecera(cabeceras);
            }

            function getCabeceraPuntoDescarga(puntoDescarga){
                var puntosStamp = '';
                puntoDescarga.forEach(function(punto, idx, arr) {
                    puntosStamp += punto.descripcion;
                    if ((idx + 1) !== arr.length) puntosStamp += ', ';
                });
                return puntosStamp;
            }

            function addArrayCabecera(array) {
                for (var i = 0; i < array.length; i++) {
                    $scope.$broadcast('addCabecera', {
                        label: array[i].label,
                        valor: array[i].valor
                    });
                }
            }

            function validarNotaRemitada() {
                if (!$scope.notaPedido.idRemito) {
                    return true;
                } else {
                    focaModalService.alert('No se puede editar una nota de pedido remitada');
                    return false;
                }
            }

            function salir() {
                var confirmacion = false;

                if (!angular.equals($scope.notaPedido, $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('/');
                }
            }

            function getLSNotaPedido() {
                var notaPedido = JSON.parse($localStorage.notaPedido || null);
                if (notaPedido) {
                    delete $localStorage.notaPedido;
                    setearNotaPedido(notaPedido);
                }
            }

            function deleteCliente() {
                delete $scope.notaPedido.domicilioStamp;
                delete $scope.notaPedido.notaPedidoPuntoDescarga;
                $scope.notaPedido.domicilio = {dom: ''};
                $scope.notaPedido.cliente = {};
                $scope.$broadcast('removeCabecera', 'Cliente:');
                $scope.$broadcast('removeCabecera', 'Domicilio:');
                $scope.$broadcast('removeCabecera', 'Puntos de descarga:');
            }
        }
    ]);