angular.module('focaCrearNotaPedido') .controller('notaPedidoCtrl', [ '$scope', '$uibModal', '$location', '$filter', 'crearNotaPedidoService', 'focaModalService', 'notaPedidoBusinessService', '$rootScope', 'focaSeguimientoService', function( $scope, $uibModal, $location, $filter, crearNotaPedidoService, focaModalService, notaPedidoBusinessService, $rootScope, focaSeguimientoService) { $scope.botonera = crearNotaPedidoService.getBotonera(); $scope.isNumber = angular.isNumber; $scope.datepickerAbierto = false; $scope.show = false; $scope.cargando = true; $scope.dateOptions = { maxDate: new Date(), minDate: new Date(2010, 0, 1) }; $scope.notaPedido = { id: 0, vendedor: {}, cliente: {}, proveedor: {}, domicilio: {dom: ''}, moneda: {}, cotizacion: {} }; var monedaPorDefecto; //Trabajo con la cotización más reciente, por eso uso siempre la primera '[0]' crearNotaPedidoService.getCotizacionByIdMoneda(1).then(function(res) { monedaPorDefecto = res.data[0]; $scope.notaPedido.moneda = monedaPorDefecto; $scope.notaPedido.cotizacion = monedaPorDefecto.cotizaciones[0]; }); $scope.cabecera = []; $scope.showCabecera = true; $scope.now = new Date(); $scope.puntoVenta = '0000'; $scope.comprobante = '00000000'; $scope.articulosTabla = []; $scope.idLista = undefined; crearNotaPedidoService.getPrecioCondicion().then( function(res) { $scope.precioCondiciones = res.data; } ); crearNotaPedidoService.getNumeroNotaPedido().then( function(res) { $scope.puntoVenta = rellenar(res.data.sucursal, 4); $scope.comprobante = rellenar(res.data.numeroNotaPedido, 8); }, function(err) { focaModalService.alert('La terminal no esta configurada correctamente'); console.info(err); } ); $scope.crearNotaPedido = function() { if(!$scope.notaPedido.vendedor.CodVen) { focaModalService.alert('Ingrese Vendedor'); return; } else if(!$scope.notaPedido.cliente.COD) { focaModalService.alert('Ingrese Cliente'); return; } else if(!$scope.notaPedido.proveedor.COD) { focaModalService.alert('Ingrese Proveedor'); return; } else if(!$scope.notaPedido.moneda.ID) { focaModalService.alert('Ingrese Moneda'); return; } else if(!$scope.notaPedido.cotizacion.ID) { focaModalService.alert('Ingrese Cotización'); return; } else if(!$scope.plazosPagos) { 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.articulosTabla.length === 0) { focaModalService.alert('Debe cargar al menos un articulo'); return; } $scope.saveLoading = true; var notaPedido = { id: $scope.notaPedido.id, fechaCarga: $scope.now.toISOString().slice(0, 19).replace('T', ' '), idVendedor: $scope.notaPedido.vendedor.CodVen, 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,TODO GUARDAR 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, 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( data.data.id, 'Nota de pedido', 'Nº: ' + $filter('comprobante')([ $scope.puntoVenta, $scope.comprobante ]) + '
' + 'Vendedor: ' + $scope.notaPedido.vendedor.NomVen + '
' + 'Total: ' + $filter('currency')($scope.getTotal()) ); notaPedidoBusinessService.addArticulos($scope.articulosTabla, data.data.id, $scope.notaPedido.cotizacion.VENDEDOR); var plazos = $scope.plazosPagos; for(var j = 0; j < plazos.length; j++) { var json = { idPedido: data.data.id, dias: plazos[j].dias }; crearNotaPedidoService.crearPlazosParaNotaPedido(json); } notaPedidoBusinessService.addEstado(data.data.id, $scope.notaPedido.vendedor.CodVen); focaModalService.alert('Nota pedido creada'); $scope.saveLoading = false; $scope.cabecera = []; addCabecera('Moneda:', $scope.notaPedido.moneda.DETALLE); addCabecera( 'Fecha cotizacion:', $filter('date')($scope.notaPedido.cotizacion.FECHA, 'dd/MM/yyyy') ); addCabecera('Cotizacion:', $scope.notaPedido.cotizacion.VENDEDOR); crearNotaPedidoService.getNumeroNotaPedido().then( function(res) { $scope.puntoVenta = rellenar(res.data.sucursal, 4); $scope.comprobante = rellenar(res.data.numeroNotaPedido, 8); }, function(err) { focaModalService.alert( 'La terminal no esta configurada correctamente'); console.info(err); } ); $scope.notaPedido.vendedor = {}; $scope.notaPedido.cliente = {}; $scope.notaPedido.proveedor = {}; $scope.notaPedido.domicilio = {}; $scope.notaPedido.flete = null; $scope.notaPedido.fob = null; $scope.notaPedido.bomba = null; $scope.notaPedido.kilometros = null; $scope.articulosTabla = []; }, function(error) { focaModalService.alert('Hubo un error al crear la nota de pedido'); $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';}} } ); modalInstance.result.then( function(notaPedido) { $scope.now = new Date(notaPedido.fechaCarga); //añado cabeceras $scope.notaPedido.id = notaPedido.id; removeCabecera('Bomba:'); removeCabecera('Kilometros:'); var cabeceras = [ { label: 'Moneda:', valor: notaPedido.cotizacion.moneda.DETALLE }, { label: 'Fecha cotizacion:', valor: $filter('date')(notaPedido.cotizacion.FECHA, 'dd/MM/yyyy') }, { label: 'Cotizacion:', valor: notaPedido.cotizacion.VENDEDOR }, { label: 'Cliente:', valor: notaPedido.cliente.NOM }, { label: 'Domicilio:', valor: notaPedido.domicilioStamp }, { label: 'Vendedor:', valor: notaPedido.vendedor.NomVen }, { label: 'Proveedor:', valor: notaPedido.proveedor.NOM }, { label: 'Precio condicion:', valor: valorPrecioCondicion() + ' ' + notaPedidoBusinessService .plazoToString(notaPedido.notaPedidoPlazo) }, { 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); } $scope.articulosTabla = notaPedido.articulosNotaPedido; notaPedidoBusinessService.calcularArticulos($scope.articulosTabla, notaPedido.cotizacion.VENDEDOR); if(notaPedido.idPrecioCondicion > 0) { $scope.idLista = notaPedido.precioCondicion.idListaPrecio; } else { $scope.idLista = -1; } $scope.puntoVenta = rellenar(notaPedido.sucursal, 4); $scope.comprobante = rellenar(notaPedido.numeroNotaPedido, 8); $scope.notaPedido = notaPedido; $scope.notaPedido.moneda = notaPedido.cotizacion.moneda; $scope.plazosPagos = notaPedido.notaPedidoPlazo; addArrayCabecera(cabeceras); }, function() { // funcion ejecutada cuando se cancela el modal } ); }; $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.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.articulosTabla.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 }; $scope.articuloACargar = newArt; $scope.cargando = false; }, function() { // funcion ejecutada cuando se cancela el modal } ); }; $scope.seleccionarVendedor = function() { if(validarNotaRemitada()) { var modalInstance = $uibModal.open( { ariaLabelledBy: 'Busqueda de Vendedores', templateUrl: 'modal-vendedores.html', controller: 'modalVendedoresCtrl', size: 'lg' } ); modalInstance.result.then( function(vendedor) { addCabecera('Vendedor:', vendedor.NomVen); $scope.notaPedido.vendedor = vendedor; }, function() { } ); } }; $scope.seleccionarProveedor = function() { if(validarNotaRemitada()) { var modalInstance = $uibModal.open( { ariaLabelledBy: 'Busqueda de Proveedor', templateUrl: 'modal-proveedor.html', controller: 'focaModalProveedorCtrl', size: 'lg', resolve: { transportista: function() { return false; } } } ); modalInstance.result.then( function(proveedor) { $scope.notaPedido.proveedor = proveedor; addCabecera('Proveedor:', proveedor.NOM); }, function() { } ); } }; $scope.seleccionarCliente = function() { if(validarNotaRemitada()) { var modalInstance = $uibModal.open( { ariaLabelledBy: 'Busqueda de Cliente', templateUrl: 'foca-busqueda-cliente-modal.html', controller: 'focaBusquedaClienteModalController', size: 'lg' } ); modalInstance.result.then( function(cliente) { $scope.abrirModalDomicilios(cliente); }, 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; }}, size: 'lg', } ); modalInstanceDomicilio.result.then( function(domicilio) { $scope.notaPedido.domicilio = domicilio; $scope.notaPedido.cliente = { COD: cliente.cod, CUIT: cliente.cuit, NOM: cliente.nom }; addCabecera('Cliente:', cliente.nom); var domicilioStamp = domicilio.Calle + ' ' + domicilio.Numero + ', ' + domicilio.Localidad + ', ' + domicilio.Provincia; $scope.notaPedido.domicilioStamp = domicilioStamp; addCabecera('Domicilio:', domicilioStamp); }, function() { $scope.seleccionarCliente(); return; } ); }; $scope.getTotal = function() { var total = 0; var arrayTempArticulos = $scope.articulosTabla; 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()) { var modalInstance = $uibModal.open( { ariaLabelledBy: 'Busqueda de Precio Condición', templateUrl: 'modal-precio-condicion.html', controller: 'focaModalPrecioCondicionController', size: 'lg' } ); modalInstance.result.then( function(precioCondicion) { var cabecera = ''; var plazosConcat = ''; if(!Array.isArray(precioCondicion)) { $scope.notaPedido.idPrecioCondicion = precioCondicion.id; $scope.plazosPagos = precioCondicion.plazoPago; $scope.idLista = precioCondicion.idListaPrecio; for(var i = 0; i < precioCondicion.plazoPago.length; i++) { plazosConcat += precioCondicion.plazoPago[i].dias + ' '; } cabecera = precioCondicion.nombre + ' ' + plazosConcat.trim(); } else { //Cuando se ingresan los plazos manualmente $scope.notaPedido.idPrecioCondicion = 0; $scope.idLista = -1; //-1, el modal productos busca todos los productos $scope.plazosPagos = precioCondicion; for(var j = 0; j < precioCondicion.length; j++) { plazosConcat += precioCondicion[j].dias + ' '; } cabecera = 'Ingreso manual ' + plazosConcat.trim(); } $scope.articulosTabla = []; addCabecera('Precios y condiciones:', cabecera); }, function() { } ); } }; $scope.seleccionarFlete = 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; addCabecera('Flete:', datos.FOB ? 'FOB' : (datos.flete ? 'Si' : 'No')); if(datos.flete) { addCabecera('Bomba:', datos.bomba ? 'Si' : 'No'); addCabecera('Kilometros:', datos.kilometros); } else { removeCabecera('Bomba:'); removeCabecera('Kilometros:'); $scope.notaPedido.bomba = false; $scope.notaPedido.kilometros = null; } }, function() { } ); } }; $scope.seleccionarMoneda = function() { if(validarNotaRemitada()) { var modalInstance = $uibModal.open( { ariaLabelledBy: 'Busqueda de Moneda', templateUrl: 'modal-moneda.html', controller: 'focaModalMonedaController', size: 'lg' } ); modalInstance.result.then( function(moneda) { $scope.abrirModalCotizacion(moneda); }, function() { } ); } }; $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.articulosTabla; 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.articulosTabla = articulosTablaTemp; $scope.notaPedido.moneda = moneda; $scope.notaPedido.cotizacion = cotizacion; if(moneda.DETALLE == "PESOS ARGENTINOS"){ removeCabecera('Moneda:'); removeCabecera('Fecha cotizacion:'); removeCabecera('Cotizacion:'); }else{ addCabecera('Moneda:', moneda.DETALLE); addCabecera( 'Fecha cotizacion:', $filter('date')(cotizacion.FECHA, 'dd/MM/yyyy') ); addCabecera('Cotizacion:', cotizacion.VENDEDOR); } }, 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.articulosTabla.push($scope.articuloACargar); $scope.cargando = true; } }; $scope.quitarArticulo = function(key) { $scope.articulosTabla.splice(key, 1); }; $scope.editarArticulo = function(key, articulo) { if(key === 13) { if(articulo.cantidad === null || articulo.cantidad === 0 || articulo.cantidad === undefined) { focaModalService.alert('El valor debe ser al menos 1'); return; } articulo.editCantidad = false; 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 addArrayCabecera(array) { for(var i = 0; i < array.length; i++) { addCabecera(array[i].label, array[i].valor); } } 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}); } } 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); } } function rellenar(relleno, longitud) { relleno = '' + relleno; while (relleno.length < longitud) { relleno = '0' + relleno; } return relleno; } function validarNotaRemitada() { if(!$scope.notaPedido.idRemito) { return true; }else{ focaModalService.alert('No se puede editar una nota de pedido remitada'); return false; } } } ]);