angular.module('focaCrearFactura').controller('facturaController', [ '$scope', '$uibModal', '$location', '$filter', 'crearFacturaService', '$timeout', 'focaModalService', 'crearRemitoService', '$rootScope', 'focaBotoneraLateralService', '$localStorage', 'APP', function ( $scope, $uibModal, $location, $filter, crearFacturaService, $timeout, focaModalService, crearRemitoService, $rootScope, focaBotoneraLateralService, $localStorage, APP) { config(); function config() { $scope.tmpCantidad = Number; $scope.tmpPrecio = Number; $scope.botonera = crearFacturaService.getBotonera(); $scope.botoneraProductos = []; $scope.isNumber = angular.isNumber; $scope.datepickerAbierto = false; $scope.show = false; $scope.cargando = true; $scope.now = new Date(); $scope.puntoVenta = rellenar(0, 4); $scope.comprobante = rellenar(0, 8); $scope.dateOptions = { maxDate: new Date(), minDate: new Date(2010, 0, 1) }; $scope.cabeceras = []; crearFacturaService.getParametros().then(function (res) { var parametros = JSON.parse(res.data[0].jsonText); if ($localStorage.factura) { $timeout(function () { getLSFactura(); }); } else { for (var property in parametros) { $scope.factura[property] = parametros[property]; $scope.inicial[property] = parametros[property]; } setearFactura($scope.factura); } }); //SETEO BOTONERA LATERAL $timeout(function () { focaBotoneraLateralService.showSalir(false); focaBotoneraLateralService.showPausar(true); focaBotoneraLateralService.showGuardar(true, $scope.seleccionarFormaDePago); focaBotoneraLateralService.addCustomButton('Salir', salir); }); init(); } function init() { $scope.$broadcast('cleanCabecera'); $scope.factura = { id: 0, estado: 0, vendedor: {}, cliente: {}, proveedor: {}, domicilio: { dom: '' }, moneda: {}, cotizacion: $scope.cotizacionPorDefecto || {}, articulosFactura: [], despachos: [] }; $scope.factura.articulosFactura = []; $scope.idLista = undefined; crearRemitoService.getNumeroRemito().then( function (res) { $scope.puntoVenta = rellenar(res.data.sucursal, 4); $scope.comprobante = rellenar(res.data.numeroRemito, 8); }, function (err) { focaModalService.alert('La terminal no esta configurada correctamente'); console.info(err); } ); $scope.inicial = angular.copy($scope.factura); } $scope.$watch('factura', function (newValue) { focaBotoneraLateralService.setPausarData({ label: 'factura', val: newValue }); }, true); $scope.seleccionarFormaDePago = function () { if (!validarGuardar()) return; var modalInstance = $uibModal.open( { templateUrl: 'modal-forma-pago.html', controller: 'focaModalFormaPagoController', resolve: { filters: function () { return null; }, }, size: 'lg', } ); modalInstance.result .then(function (data) { console.log(data); $scope.crearFactura(); }) .catch(function (e) { console.error(e); }); }; $scope.crearFactura = function () { var save = { factura: { BONIF: 0, CLI: $scope.factura.cliente.cod, CUI: $scope.factura.cliente.cuit, CTA: $scope.factura.cliente.cod, DC1: '', DC2: '', DE1: '', DOM: $scope.factura.cliente.DOM, FACAUT: 0, DTO: 0, FEC: $filter('date')($scope.now, 'yyyy-MM-dd HH:mm:ss'), FEC_ANT: '19000101', FPA: 0, // 0 <- Múltiple formas de pago, 2 cta corriente IDEXCEPCION: 0, IDLP: $scope.factura.cliente.mod.trim() || 0, IDPERSONERIA: 0, IMI: 0, // TODO IMI2: 0, // TODO IMI3: 0, // TODO IMP_LEY: 0, IRI: 0, // TODO IRS: 0, LEG: '', LUG: $scope.factura.vendedor.LugVen, MK_M: 0, NEE: 0, // TODO NET: 0, // TODO NFI: '', NNP: 0, NOM: $scope.factura.cliente.nom, OPE: $scope.factura.vendedor.CodVen, PAG: $scope.getTotal(), PER: 0, PER_IVA: 0, PLA: $scope.factura.vendedor.NplVen, PRO: '', REC_ANT: 0, SUC: parseInt($scope.puntoVenta), TCA: 1, TCO: 'FT', TFI: '', TIP: $scope.factura.cliente.tipoFactura, TIV: 0, // TODO TOT: $scope.getTotal(), TUR: 0, // TODO VEN: $scope.factura.vendedor.CodVen, VTO_CLI: '', ZON: 1, // TODO OBSERVACIONES: $scope.factura.observaciones }, cuerpo: $scope.articulosFiltro(), despachos: $scope.factura.despachos }; crearFacturaService.guardarFactura(save).then(function (res) { focaBotoneraLateralService.endGuardar(true); focaModalService.alert('Comprobante guardado con éxito'); config(); }).catch(function (err) { focaModalService.alert('Hubo un error al guardar la factura'); console.log(err); }); }; $scope.seleccionarCliente = function () { var modalInstance = $uibModal.open( { ariaLabelledBy: 'Busqueda de Cliente', templateUrl: 'foca-busqueda-cliente-modal.html', controller: 'focaBusquedaClienteModalController', resolve: { vendedor: function () { return null; }, cobrador: function () { return null; } }, size: 'lg' } ); modalInstance.result.then( function (cliente) { var modalInstance = $uibModal.open( { templateUrl: 'modal-estado-cuenta.html', controller: 'focaModalEstadoCuentaController', size: 'lg', resolve: { parametros: function () { return { idCliente: cliente.cod }; }, } } ); modalInstance.result .then(function (data) { $scope.factura.cliente = cliente; $scope.$broadcast('addCabecera', { label: 'Cliente:', valor: $filter('rellenarDigitos')(cliente.cod, 3) + ' - ' + cliente.nom }); $filter('filter')($scope.botonera, { label: 'Cliente' })[0].checked = true; $scope.$broadcast('addCabecera', { label: 'Tipo de pago: ', valor: data }); }) .catch(function () { $scope.seleccionarCliente(); }); }, function () { } ); }; $scope.seleccionarVendedor = function () { var parametrosModal = { titulo: 'Búsqueda vendedores', query: '/vendedor-playa', columnas: [ { propiedad: 'CodVen', nombre: 'Código', filtro: { nombre: 'rellenarDigitos', parametro: 3 } }, { propiedad: 'NomVen', nombre: 'Nombre' } ], size: 'md' }; focaModalService.modal(parametrosModal).then( function (vendedor) { indicarPassword(vendedor) .then(function () { validarPlanillaVendedor(vendedor) .then(function () { $filter('filter')($scope.botonera, { label: 'Vendedor' })[0].checked = true; $scope.$broadcast('addCabecera', { label: 'Vendedor:', valor: $filter('rellenarDigitos')(vendedor.CodVen, 3) + ' - ' + vendedor.NomVen }); $scope.factura.vendedor = vendedor; getProductosByPlanilla(vendedor.NplVen); }) .catch($scope.seleccionarVendedor); }) .catch(function (err) { console.log(err); }); }, function () { } ); }; $scope.seleccionarMoneda = function () { 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; } crearRemitoService.getCotizacionByIdMoneda(1) .then(function (res) { var cotizacionPArgentino = res.data[0].cotizaciones[0]; cotizacionPArgentino.moneda = moneda; actualizarCabeceraMoneda(cotizacionPArgentino); $scope.remito.cotizacion = cotizacionPArgentino; }); }, 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) { cotizacion.moneda = moneda; actualizarCabeceraMoneda(cotizacion); $scope.factura.cotizacion = cotizacion; }, function () { } ); }; $scope.seleccionarObservaciones = function () { var observacion = { titulo: 'Ingrese Observaciones', value: $scope.factura.observaciones, maxlength: 155, textarea: true }; focaModalService .prompt(observacion) .then(function (observaciones) { $scope.factura.observaciones = observaciones; }); }; $scope.articulosFiltro = function () { return $scope.factura.articulosFactura.filter(function (articulo) { return !articulo.desactivado; }); }; $scope.getTotal = function () { var total = 0; $scope.articulosFiltro().forEach(function (articulo) { total += articulo.PUN * articulo.CAN; }); return parseFloat(total.toFixed(2)); }; $scope.quitarDespacho = function (articulo, index) { crearFacturaService .setearDespachoDesocupado({ surtidor: $scope.factura.despachos[index].SUR, producto: $scope.factura.despachos[index].PRO, carga: $scope.factura.despachos[index].CAR, planilla: $scope.factura.despachos[index].PLA }) .then(function () { articulo.desactivado = true; $scope.factura.despachos.splice(index, 1); }) .catch(function () { focaModalService.alert('Hubo un error al desasociar este despacho'); }); }; function getProductosByPlanilla(numeroPlanilla) { crearFacturaService.getProductosByPlanilla(numeroPlanilla).then(function (res) { $scope.botoneraProductos.length = 0; res.data.forEach(function (producto) { $scope.botoneraProductos.push({ label: producto.DetArt, image: 'buscarProductos.png' }); crearFuncionesProductos(producto); }); $scope.botoneraProductos.push({ label: 'Busqueda Productos', image: 'buscarProductos.png' }); }); } $scope.seleccionarBusquedaProductos = function () { var modalInstance = $uibModal.open( { ariaLabelledBy: 'Busqueda de Productos', templateUrl: 'modal-busqueda-productos.html', controller: 'modalBusquedaProductosCtrl', resolve: { parametroProducto: { idLista: null, cotizacion: $scope.factura.cotizacion.VENDEDOR, simbolo: $scope.factura.cotizacion.moneda.SIMBOLO, buscarTodos: true } }, size: 'lg' } ); modalInstance.result .then(function (producto) { console.log(producto); var articulo = { TIP: $scope.factura.cliente.tipoFactura, TCO: 'FT', SUC: parseInt($scope.puntoVenta), ORD: $scope.articulosFiltro().length + 1, SEC: producto.sector, ART: producto.codigo, RUB: producto.CodRub, DES: producto.descripcionLarga, PUN: producto.precio, // TODO IVA: producto.IMPIVA, // TODO NET: 0, // TODO NEX: 0, // TODO IMI: producto.ImpInt, // TODO IMI2: producto.ImpInt2, // TODO IMI3: producto.ImpInt3, // TODO PUT: producto.PreNet, // TODO SUR: 0, PLA: $scope.factura.vendedor.NplVen, LUG: $scope.factura.vendedor.LugVen, LEG: $scope.factura.vendedor.CodVen, TUR: $scope.factura.vendedor.TurVen, ORDEN_PRECOMPRA: '', ESC: producto.tipoFactura === 'L' ? 1 : 0, CMF: 0, PTA: 0, IVS: 0, TIVA: 0, CON: 0, SINO: '', ORD_TRA: 0, IMP_DESP: 0, PCD: 0, RTO: '' }; // crearFacturaService.setearDespachoOcupado({ // surtidor: articulo.SUR, // producto: articulo.PRO, // carga: articulo.CAR // }) // .then(function () { $scope.factura.articulosFactura.push(articulo); $scope.cambioEdit(articulo, 'cantidad'); // }) // .catch(function (err) { // focaModalService.alert('El despacho esta en uso'); // }); }) .catch(function (e) { console.log(e); }); }; function crearFuncionesProductos(producto) { $scope[nombreFuncion(producto.DetArt)] = function () { if (angular.equals($scope.factura.cliente, {})) { focaModalService.alert('Seleccione cliente'); return; } var modalInstance = $uibModal.open( { templateUrl: 'modal-combustibles.html', controller: 'focaModalCombustiblesController', resolve: { parametros: function () { return { despachos: producto.despachos, nombreProducto: producto.DetArt }; } }, size: 'md' } ); modalInstance.result.then(function (despacho) { var articulo = { TIP: $scope.factura.cliente.tipoFactura, TCO: 'FT', SUC: parseInt($scope.puntoVenta), ORD: $scope.articulosFiltro().length + 1, SEC: despacho.SEC, ART: despacho.PRO, RUB: producto.CodRub, DES: producto.DetArt, CAN: despacho.LTS, PUN: producto.PreVen, // TODO IVA: producto.IMPIVA, // TODO NET: 0, // TODO NEX: 0, // TODO IMI: producto.ImpInt, // TODO IMI2: producto.ImpInt2, // TODO IMI3: producto.ImpInt3, // TODO PUT: producto.PreNet, // TODO SUR: despacho.SUR, PLA: despacho.PLA, LUG: despacho.LUG, LEG: $scope.factura.vendedor.CodVen, TUR: $scope.factura.vendedor.TurVen, ORDEN_PRECOMPRA: '', ESC: producto.tipoFactura === 'L' ? 1 : 0, CMF: 0, PTA: 0, IVS: 0, TIVA: 0, CON: 0, SINO: '', ORD_TRA: 0, IMP_DESP: 0, PCD: 0, RTO: '' }; crearFacturaService.setearDespachoOcupado({ surtidor: despacho.SUR, producto: despacho.PRO, carga: despacho.CAR }) .then(function () { $scope.factura.articulosFactura.push(articulo); $scope.factura.despachos.push(despacho); }) .catch(function (err) { focaModalService.alert('El despacho esta en uso'); }); }) .catch(function (err) { console.log(err); }); }; } function nombreFuncion(string) { var texto = 'seleccionar'; var arr = string.split(' '); arr.forEach(function (palabra) { palabra = palabra.charAt(0).toUpperCase() + palabra.slice(1); texto += palabra; }); return texto; } function indicarPassword(vendedor) { return new Promise(function (resolve, reject) { focaModalService .prompt({ titulo: 'Indique Contraseña', value: '' }) .then(function (contraseña) { if (contraseña !== vendedor.ClaVen.trim()) { focaModalService.alert('Clave incorrecta').then(function () { indicarPassword(vendedor); }); } else { resolve(); } }) .catch(reject); }); } function validarPlanillaVendedor(vendedor) { return new Promise(function (resolve, reject) { crearFacturaService .validarPlanillaVendedor(vendedor.CodVen.trim()) .then(function (res) { if (!res.data.length) { focaModalService .alert('No se encontró planilla abierta para el vendedor') .then(reject); } else { resolve(); } }) .catch(reject); }); } function rellenar(relleno, longitud) { relleno = '' + relleno; while (relleno.length < longitud) { relleno = '0' + relleno; } return relleno; } function salir() { var confirmacion = false; if (!angular.equals($scope.factura, $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 setearFactura(factura) { $scope.$broadcast('cleanCabecera'); $scope.cabeceras = []; if (factura.cotizacion && factura.cotizacion.moneda.CODIGO_AFIP !== 'PES') { $scope.cabeceras.push({ label: 'Moneda:', valor: factura.cotizacion.moneda.DETALLE }); $scope.cabeceras.push({ label: 'Fecha cotizacion:', valor: $filter('date')(factura.cotizacion.FECHA, 'dd/MM/yyyy') }); $scope.cabeceras.push({ label: 'Cotizacion:', valor: $filter('number')(factura.cotizacion.VENDEDOR, '2') }); } if (factura.cotizacion && factura.cotizacion.moneda) { $filter('filter')($scope.botonera, { label: 'Moneda' })[0].checked = true; } if (factura.cliente && factura.cliente.cod) { $scope.cabeceras.push({ label: 'Cliente:', valor: $filter('rellenarDigitos')(factura.cliente.cod, 3) + ' - ' + factura.cliente.nom }); $filter('filter')($scope.botonera, { label: 'Cliente' })[0].checked = true; } $scope.puntoVenta = rellenar(factura.sucursal, 4); $scope.comprobante = rellenar(factura.numerofactura, 8); $scope.factura = factura; addArrayCabecera($scope.cabeceras); } function getLSFactura() { var factura = JSON.parse($localStorage.factura || null); if (factura) { setearFactura(factura); delete $localStorage.factura; } } function addArrayCabecera(array) { for (var i = 0; i < array.length; i++) { $scope.$broadcast('addCabecera', { label: array[i].label, valor: array[i].valor }); } } $scope.cambioEdit = function (articulo, propiedad) { if (propiedad === 'cantidad') { articulo.editCantidad = true; } }; $scope.editarArticulo = function (key, articulo, tmpCantidad) { if (key === 13) { if (!articulo.cantidad && !tmpCantidad) { focaModalService.alert('Los valores deben ser al menos 1'); return; } else if (tmpCantidad === '0') { focaModalService.alert('Esta ingresando un producto con valor 0'); } else if (articulo.cantidad < 0) { focaModalService.alert('Los valores no pueden ser negativos'); return; } articulo.CAN = parseInt(tmpCantidad); $scope.getTotal(); articulo.editCantidad = false; } }; $scope.cancelarEditar = function (articulo) { $scope.tmpCantidad = articulo.CAN; articulo.editCantidad = false; }; function actualizarCabeceraMoneda(cotizacion) { $scope.factura.articulosFactura.forEach(function (art) { art.PUN = (art.PUN * $scope.factura.cotizacion.VENDEDOR).toFixed(4); art.PUN = (art.PUN / 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') }); } } function validarGuardar() { if (angular.equals({}, $scope.factura.vendedor)) { focaModalService.alert('Seleccione Vendedor'); return false; } else if (angular.equals({}, $scope.factura.cliente)) { focaModalService.alert('Seleccione Cliente'); return false; } else if (!$scope.articulosFiltro().length) { focaModalService.alert('Seleccione al menos un Articulo'); return false; } return true; } } ]);