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(); var cotizacionPArgentino = {}; 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; } crearNotaPedidoService.getParametros().then(function (res) { var parametros = JSON.parse(res.data[0].jsonText); if ($localStorage.notaPedido) { $timeout(function () { getLSNotaPedido(); }); } else { for (var property in parametros) { $scope.notaPedido[property] = parametros[property]; $scope.inicial[property] = parametros[property]; } setearNotaPedido($scope.notaPedido); } }); init(); } function init() { $scope.$broadcast('cleanCabecera'); $scope.notaPedido = { id: 0, cliente: {}, proveedor: {}, domicilio: { dom: '' }, vendedor: {}, fechaCarga: new Date(), cotizacion: {}, articulosNotaPedido: [], notaPedidoPlazo: [], notaPedidoPuntoDescarga: [] }; $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.vendedor = $scope.notaPedido.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, idListaPrecio: $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.length > 0) { 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; config(); }, function (error) { focaModalService.alert('Hubo un error al crear la nota de pedido'); focaBotoneraLateralService.endGuardar(); $scope.saveLoading = false; console.info(error); }); }; $scope.setTempCantidadArticulo = function (articulo) { articulo.tmpCantidad = articulo.cantidad; }; $scope.setTempPrecioArticulo = function (articulo) { articulo.tmpPrecio = articulo.precio; }; $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(function(notaPedido) { notaPedido.articulosNotaPedido.forEach(function (articulo) { articulo.precio = (articulo.precio / notaPedido.cotizacion.VENDEDOR).toFixed(4); }); setearNotaPedido(notaPedido); }); }; $scope.seleccionarProductos = function () { if ($scope.idLista === undefined) { focaModalService.alert('Primero seleccione una lista de precio y condición'); return; } else if (!validarNotaRemitada()) { 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.descripcionLarga, 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, ivaUnitario: producto.IMPIVA, impuestoInternoUnitario: producto.ImpInt, impuestoInterno1Unitario: producto.ImpInt2, impuestoInterno2Unitario: producto.ImpInt3, precioLista: producto.precio, combustible: 1, facturado: 0, idArticulo: producto.id, tasaIva: producto.tasaIVA }; newArt.exentoUnitario = newArt.ivaUnitario ? 0 : producto.neto; newArt.netoUnitario = newArt.ivaUnitario ? producto.neto : 0; $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) { puntoDescarga.forEach(function (punto) { $scope.notaPedido.notaPedidoPuntoDescarga.push( { puntoDescarga: punto } ); }); $scope.$broadcast('addCabecera', { label: 'Puntos de descarga:', valor: getCabeceraPuntoDescarga(puntoDescarga) }); }, function () { $scope.abrirModalDomicilios($scope.cliente); } ); } }; $scope.seleccionarDomicilioDeEntrega = function () { if (!$scope.notaPedido.cliente.COD) { focaModalService.alert('Seleccione un Cliente'); return; } else { $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; } $filter('filter')($scope.botonera, { label: 'Proveedor' })[0].checked = true; }, 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 () { if (validarNotaRemitada()) { var modalInstance = $uibModal.open( { ariaLabelledBy: 'Busqueda de Cliente', templateUrl: 'foca-busqueda-cliente-modal.html', controller: 'focaBusquedaClienteModalController', resolve: { vendedor: function () { return { id: $scope.idVendedor} }, cobrador: function () { return null; } }, size: 'lg' } ); modalInstance.result.then( function (cliente) { cliente.mod = cliente.mod; $scope.abrirModalDomicilios(cliente); $scope.cliente = cliente; }, function () { } ); } }; $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, VEN: cliente.ven }; crearNotaPedidoService.getVendedorById($scope.notaPedido.cliente.VEN) .then(function (res) { if (res.data !== '') { $scope.notaPedido.vendedor = res.data; $scope.$broadcast('addCabecera', { label: 'Vendedor:', valor: $filter('rellenarDigitos') ($scope.notaPedido.vendedor.NUM, 3) + ' - ' + $scope.notaPedido.vendedor.NOM }); } var domicilioStamp = domicilio.Calle + ' ' + domicilio.Numero + ', ' + domicilio.Localidad + ', ' + domicilio.Provincia; $scope.notaPedido.domicilioStamp = domicilioStamp; $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(); } // Seteo checked en botonera $filter('filter')($scope.botonera, { label: 'Cliente' })[0].checked = true; $filter('filter')($scope.botonera, { label: 'Domicilio de Entrega' })[0].checked = true; }) .catch(function (e) { console.log(e); }); }, 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 (!validarNotaRemitada()) { return; } 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; }, idCliente: function () { return $scope.notaPedido.cliente.COD } } } ); 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.listaPrecio.ID; $scope.notaPedido.cliente.MOD = precioCondicion.listaPrecio.ID; $scope.idLista = parseInt(precioCondicion.listaPrecio.ID) ? parseInt(precioCondicion.listaPrecio.ID) : -1; for (var i = 0; i < precioCondicion.plazoPago.length; i++) { plazosConcat += precioCondicion.plazoPago[i].dias + ', '; } plazosConcat = plazosConcat.substring(0, plazosConcat.length - 2); cabecera = $filter('rellenarDigitos')($scope.idLista, 4) + ' - ' + precioCondicion.listaPrecio.DES + ' ' + 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 }); $filter('filter')($scope.botonera, { label: 'Precios y Condiciones' })[0].checked = true; }) .catch(function (e) { console.log(e); }) } }; $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) { if (moneda.ID !== 1) { $scope.abrirModalCotizacion(moneda); return; } crearNotaPedidoService.getCotizacionByIdMoneda(1) .then(function (res) { cotizacionPArgentino = res.data[0].cotizaciones[0]; cotizacionPArgentino.moneda = moneda; actualizarCabeceraMoneda(cotizacionPArgentino); $scope.notaPedido.cotizacion = cotizacionPArgentino; }); } ); } }; $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) { cotizacion.moneda = moneda; actualizarCabeceraMoneda(cotizacion); $scope.notaPedido.cotizacion = cotizacion; $filter('filter')($scope.botonera, { label: 'Moneda' })[0].checked = true; }, function () { } ); }; function actualizarCabeceraMoneda(cotizacion) { $scope.notaPedido.articulosNotaPedido.forEach(function (art) { art.precio = (art.precio * $scope.notaPedido.cotizacion.VENDEDOR).toFixed(4); art.precio = (art.precio / cotizacion.VENDEDOR).toFixed(4); }); if (cotizacion.moneda.DETALLE === 'PESOS ARGENTINOS') { $scope.$broadcast('removeCabecera', 'Moneda:'); $scope.$broadcast('removeCabecera', 'Fecha cotizacion:'); $scope.$broadcast('removeCabecera', 'Cotizacion:'); } else { $scope.$broadcast('addCabecera', { label: 'Moneda:', valor: cotizacion.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') }); } } $scope.agregarATabla = function (key) { if (key === 13) { if (!$scope.articuloACargar.cantidad || !$scope.articuloACargar.precio) { 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) { if (validarNotaRemitada()) { $scope.notaPedido.articulosNotaPedido.splice(key, 1); } }; $scope.editarArticulo = function (key, articulo, bandera) { if (key === 13) { var valorAEditar = bandera === 'precio' ? articulo.precio : articulo.cantidad; var tempValor = bandera === 'precio' ? articulo.tmpPrecio : articulo.tmpCantidad; if (tempValor === '') { focaModalService.alert('Los valores deben ser al menos 1'); return; } else if (tempValor === '0') { focaModalService.alert('Esta ingresando un producto con valor 0'); } else if (valorAEditar < 0) { focaModalService.alert('Los valores no pueden ser negativos'); return; } articulo[bandera] = parseFloat(tempValor); $scope.getTotal(); var propiedad = 'edit' + bandera.charAt(0).toUpperCase() + bandera.slice(1); articulo[propiedad] = 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); }; // TODO: quitar watch usar función de articulos pedido cuando se haga $scope.$watch('notaPedido.articulosNotaPedido', function () { if ($scope.notaPedido.articulosNotaPedido.length) { $filter('filter')($scope.botonera, { label: 'Productos' })[0].checked = true; } else { $filter('filter')($scope.botonera, { label: 'Productos' })[0].checked = false; } }, true); function setearNotaPedido(notaPedido) { //añado cabeceras $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.cotizacion.moneda) { $filter('filter')($scope.botonera, { label: 'Moneda' })[0].checked = true; } 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 }); $filter('filter')($scope.botonera, { label: 'Cliente' })[0].checked = true; } if (notaPedido.proveedor.COD) { cabeceras.push({ label: 'Proveedor:', valor: $filter('rellenarDigitos')(notaPedido.proveedor.COD, 5) + ' - ' + notaPedido.proveedor.NOM }); $filter('filter')($scope.botonera, { label: 'Proveedor' })[0].checked = true; } if (notaPedido.notaPedidoPlazo.length) { cabeceras.push({ label: 'Precios y condiciones:', valor: valorPrecioCondicion() + ' ' + notaPedidoBusinessService .plazoToString(notaPedido.notaPedidoPlazo) }); $filter('filter')($scope.botonera, { label: 'Precios y condiciones' })[0].checked = true; } 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 if (notaPedido.idPrecioCondicion) { $scope.idLista = -1; } $scope.puntoVenta = $filter('rellenarDigitos')( notaPedido.sucursal, 4 ); $scope.comprobante = $filter('rellenarDigitos')( notaPedido.numeroNotaPedido, 8 ); if (notaPedido.notaPedidoPuntoDescarga.length) { var puntos = []; notaPedido.notaPedidoPuntoDescarga.forEach(function (notaPedidoPuntoDescarga) { 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() { $scope.notaPedido.domicilioStamp = ''; $scope.notaPedido.notaPedidoPuntoDescarga = []; $scope.notaPedido.domicilio = { dom: '' }; $scope.notaPedido.cliente = {}; $scope.$broadcast('removeCabecera', 'Cliente:'); $scope.$broadcast('removeCabecera', 'Domicilio:'); $scope.$broadcast('removeCabecera', 'Puntos de descarga:'); $filter('filter')($scope.botonera, { label: 'Cliente' })[0].checked = false; } } ]);