angular.module('focaCrearHojaRuta').controller('hojaRutaCtrl', [ '$scope', '$uibModal', '$location', '$filter', '$timeout', 'focaCrearHojaRutaService', 'focaModalService', 'focaBotoneraLateralService', 'focaLoginService', '$localStorage', 'hojaRutaBusinessService', '$cookies', function ($scope, $uibModal, $location, $filter, $timeout, focaCrearHojaRutaService, focaModalService, focaBotoneraLateralService, focaLoginSrv, $localStorage, hojaRutaBusinessService, $cookies) { config(); function config() { $scope.botoneraPrincipal = focaCrearHojaRutaService.getBotones(); $scope.botonera = []; $scope.datepickerAbierto = false; $scope.show = false; $scope.cisternaCargas = []; $scope.cargando = true; $scope.articulos = []; $scope.remito = { id: '', numeroRemito: '' }; $scope.now = new Date(); $scope.puntoVenta = $filter('rellenarDigitos')(0, 4); $scope.comprobante = $filter('rellenarDigitos')(0, 8); //SETEO BOTONERA LATERAL $timeout(function () { focaBotoneraLateralService.showSalir(false); focaBotoneraLateralService.showPausar(true); focaBotoneraLateralService.showGuardar(true, $scope.crearHojaRuta); focaBotoneraLateralService.addCustomButton('Salir', salir); }); focaCrearHojaRutaService.getParametros().then(function (res) { var parametros = JSON.parse(res.data[0].jsonText); if ($localStorage.hojaRuta) { $timeout(function () { getLSHojaRuta(); }); } else { for (var property in parametros) { $scope.hojaRuta[property] = parametros[property]; $scope.inicial[property] = parametros[property]; } //Setear Hoja de Ruta //setearHojaRuta($scope.hojaRuta); } }); init(); } function init() { $scope.$broadcast('cleanCabecera'); $scope.hojaRuta = { fecha: new Date(), litros: 0, chofer: {}, vehiculo: { capacidad: 0 }, transportista: {}, remitosTabla: [] }; $scope.idLista = undefined; focaCrearHojaRutaService.getNumeroHojaRuta().then( function (res) { $scope.puntoVenta = $filter('rellenarDigitos')(res.data.sucursal, 4); $scope.comprobante = $filter('rellenarDigitos')(res.data.numeroHojaRuta, 8); }, function (err) { focaModalService.alert('La terminal no esta configurada correctamente'); console.info(err); } ); setearFecha(new Date()); $scope.inicial = angular.copy($scope.hojaRuta); } // $scope.$watch('hojaRuta', function(newValue) { // // Seteo checked en remitos // if ($scope.hojaRuta.remitosTabla.length) { // $filter('filter')($scope.botonera, { // label: 'Remitos', // })[0].checked = true; // } else { // $filter('filter')($scope.botonera, { // label: 'Remitos', // })[0].checked = false; // } // focaBotoneraLateralService.setPausarData({ // label: 'hojaRuta', // val: newValue // }); // }, true); $scope.seleccionarRemitoAbierto = function () { $scope.remitoAbierto = true; $scope.cargaRemito = false; $scope.precargado = false; var isBotoneraDirty = $scope.botonera.find(function (boton) { return boton.checked; }); config(); if (isBotoneraDirty) { $scope.$broadcast('cleanCabecera'); focaModalService.confirm('Se perderan los cambios') .then(function () { limpiarBotonera($scope.botonera); limpiarBotonera($scope.botoneraPrincipal); $filter('filter')($scope.botoneraPrincipal, { label: 'Remito Abierto', })[0].checked = true; $scope.botonera = focaCrearHojaRutaService.getBotonFecha(); }); } else { $scope.$broadcast('cleanCabecera'); limpiarBotonera($scope.botoneraPrincipal); $filter('filter')($scope.botoneraPrincipal, { label: 'Remito Abierto', })[0].checked = true; $scope.botonera = focaCrearHojaRutaService.getBotonFecha(); } $scope.botonera = focaCrearHojaRutaService.getRemitoAbierto(); }; $scope.seleccionarCargarRemitos = function () { $scope.cargaRemito = true; $scope.remitoAbierto = false; $scope.precargado = false; var isBotoneraDirty = $scope.botonera.find(function (boton) { return boton.checked; }); config(); if (isBotoneraDirty) { $scope.$broadcast('cleanCabecera'); focaModalService.confirm('Se perderan los cambios') .then(function () { limpiarBotonera($scope.botonera); limpiarBotonera($scope.botoneraPrincipal); $scope.preCargados = false; $filter('filter')($scope.botoneraPrincipal, { label: 'Cargar Remitos', })[0].checked = true; $scope.botonera = focaCrearHojaRutaService.getBotonFecha(); }); } else { $scope.$broadcast('cleanCabecera'); limpiarBotonera($scope.botoneraPrincipal); $filter('filter')($scope.botoneraPrincipal, { label: 'Cargar Remitos', })[0].checked = true; $scope.botonera = focaCrearHojaRutaService.getBotonFecha(); } $scope.precargado = false; }; $scope.seleccionarPrecargados = function () { $scope.precargado = true; $scope.cargaRemito = false; $scope.remitoAbierto = false; var isBotoneraDirty = $scope.botonera.find(function (boton) { return boton.checked; }); config(); if (isBotoneraDirty) { focaModalService.confirm('Se perderan los cambios') .then(function () { $scope.$broadcast('cleanCabecera'); limpiarBotonera($scope.botonera); limpiarBotonera($scope.botoneraPrincipal); $filter('filter')($scope.botoneraPrincipal, { label: 'Precargado', })[0].checked = true; $scope.botonera = focaCrearHojaRutaService.getBotonFecha(); }); } else { $scope.$broadcast('cleanCabecera'); limpiarBotonera($scope.botoneraPrincipal); $filter('filter')($scope.botoneraPrincipal, { label: 'Precargado', })[0].checked = true; $scope.botonera = focaCrearHojaRutaService.getBotonFecha(); } }; $scope.quitarArticulo = function (key ,articulo) { $scope.articulos.splice(key, 1); }; function validarHojaRuta() { if ($scope.precargado) { if (!$scope.hojaRuta.chofer.id) { focaModalService.alert('Ingrese Chofer'); return false; } if (!$scope.hojaRuta.vehiculo.id) { focaModalService.alert('Ingrese Vehiculo'); return false; } if (!$scope.hojaRuta.transportista.COD) { focaModalService.alert('Ingrese Transportista'); return false; } if (!$scope.hojaRuta.datosExtra) { focaModalService.alert('Ingrese Datos extra'); return false; } } else if ($scope.cargaRemito) { if (!$scope.hojaRuta.remitosTabla.length) { focaModalService.alert('Ingrese Remitos'); return false; } else if (!$scope.hojaRuta.chofer.id) { focaModalService.alert('Ingrese Chofer'); return false; } if (!$scope.hojaRuta.vehiculo.id) { focaModalService.alert('Ingrese Vehiculo'); return false; } if (!$scope.hojaRuta.transportista.COD) { focaModalService.alert('Ingrese Transportista'); return false; } if (!$scope.hojaRuta.datosExtra) { focaModalService.alert('Ingrese Datos extra'); return false; } } else if ($scope.remitoAbierto) { if (!$scope.hojaRuta.transportista.COD) { focaModalService.alert('Ingrese Transportista'); return false; } else if (!$scope.hojaRuta.vehiculo.id) { focaModalService.alert('Ingrese Vehiculo'); return false; } else if (!$scope.hojaRuta.chofer.id) { focaModalService.alert('Ingrese Chofer'); return false; } else if (!$scope.hojaRuta.proveedor.COD) { focaModalService.alert('Ingrese Proveedor'); return false; } else if (!$scope.hojaRuta.cliente.COD) { focaModalService.alert('Ingrese un Cliente'); return; } } return true; } function getImporte(propiedad) { var importe = 0; $scope.articulos.forEach(function (articulo) { if (articulo[propiedad]) { importe += articulo[propiedad] * articulo.cantidad; } return; }); return importe; } function guardarRemitoAbierto() { //guardar nuevo objeto (?) var date = new Date(); if ($scope.hojaRuta !== null) { console.log('DATOS---: ', $scope.hojaRuta); focaBotoneraLateralService.startGuardar(); var save = { remito: { id: 0, fechaRemito: $scope.now.toISOString().slice(0, 19).replace('T', ' '), idCliente: $scope.hojaRuta.cliente.COD, nombreCliente: $scope.hojaRuta.cliente.NOM, cuitCliente: $scope.hojaRuta.cliente.CUIT, idVendedor: $cookies.get('vendedorCobrador'), idProveedor: $scope.hojaRuta.proveedor.COD, idDomicilio: $scope.hojaRuta.idDomicilio || $scope.hojaRuta.domicilio.id, idCotizacion: $scope.hojaRuta.cotizacion.ID, domicilioStamp: $scope.hojaRuta.domicilioStamp, observaciones: $scope.hojaRuta.observaciones, idListaPrecio: $scope.hojaRuta.cliente.MOD.trim(), total: getImporte('total') || 0, descuento: 0,//TODO, importeNeto: getImporte('netoUnitario') || 0, //TODO: arreglar, importeExento: getImporte('exentoUnitario'), importeIva: getImporte('ivaUnitario') || 0, //TODO: arreglar importeIvaServicios: 0,//TODO importeImpuestoInterno: getImporte('impuestoInternoUnitario'), importeImpuestoInterno1: getImporte('impuestoInterno1Unitario'), importeImpuestoInterno2: getImporte('impuestoInterno2Unitario'), percepcion: 0,//TODO percepcionIva: 0,//TODO redondeo: 0,//TODO anulado: false, planilla: $filter('date')($scope.now, 'ddMMyyyy'), lugar: parseInt($scope.puntoVenta), cuentaMadre: 0,//TODO cuentaContable: 0,//TODO asiento: 0,//TODO e_hd: '',//TODO c_hd: '', numeroLiquidoProducto: 0,//TODO estado: 0, destinoVenta: 0,//TODO operacionTipo: 0, //TODO }, notaPedido: { id: 0 } }; focaCrearHojaRutaService.crearRemito(save).then( function (data) { focaBotoneraLateralService.endGuardar(true); $scope.saveLoading = false; $scope.remito.id = data.data.id; focaCrearHojaRutaService.guardarCisternas({ cisternaCargas: $scope.cisternaCargas, cisternaMovimientos: $scope.cisternaMovimientos, fechaReparto: $scope.hojaRuta.fechaReparto, idVehiculo: $scope.hojaRuta.vehiculo.id }, data.data.id); $scope.remito.numeroRemito = data.data.numero; // if ($scope.remito.remitoPuntoDescarga.length > 0) { // remitoBusinessService.addPuntosDescarga(data.data.id, // $scope.remito.remitoPuntoDescarga); // } hojaRutaBusinessService.addArticulos($scope.articulosRecibidos, data.data.id, $scope.hojaRuta.cotizacion.VENDEDOR); guardarHojaRuta(data.data.id); }, function (error) { focaModalService.alert(error.data || 'Hubo un error al crear el remito'); focaBotoneraLateralService.endGuardar(); $scope.saveLoading = false; console.info(error); } ); function guardarHojaRuta(idRemito) { var save2 = { hojaRuta: { id: 0, fechaCreacion: new Date(date.getTime()).toISOString().slice(0, 19) .replace('T', ' '), idTransportista: $scope.hojaRuta.transportista.COD, idChofer: $scope.hojaRuta.chofer.id, idVehiculo: $scope.hojaRuta.vehiculo.id, proveedor: $scope.hojaRuta.proveedor.id, fechaReparto: new Date($scope.hojaRuta.fechaReparto).toISOString().substring(0, 10), estado: 0, abierta: 1 }, remitos: [{id: idRemito}] } save2.hojaRuta = angular.extend({}, save2.hojaRuta, $scope.hojaRuta.datosExtra); focaCrearHojaRutaService.crearHojaRuta(save2).then( function (data) { focaModalService.alert( 'Hoja ruta creada Nº: ' + $filter('rellenarDigitos')(data.data.sucursal, 4) + '-' + $filter('rellenarDigitos')(data.data.numeroHojaRuta, 8) ); config(); }, function (error) { focaModalService.alert('Hubo un error al crear la hoja de ruta'); console.info(error); } ); } } } $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) { $scope.abrirModalDomicilios(cliente); $scope.cliente = cliente; }, function () { } ); }; $scope.abrirModalDomicilios = function (cliente) { var modalInstanceDomicilio = $uibModal.open( { ariaLabelledBy: 'Busqueda de Domicilios', templateUrl: 'modal-domicilio.html', controller: 'focaModalDomicilioController', size: 'lg', resolve: { idCliente: function () { return cliente.cod; }, esNuevo: function () { return cliente.esNuevo; } } } ); modalInstanceDomicilio.result.then( function (domicilio) { $scope.hojaRuta.domicilio = domicilio; $scope.hojaRuta.cliente = { COD: cliente.cod, CUIT: cliente.cuit, NOM: cliente.nom, MAIL: cliente.mail, MOD: cliente.mod, IVA: cliente.iva, VEN: cliente.ven }; focaCrearHojaRutaService.getVendedorById($scope.hojaRuta.cliente.VEN) .then(function (res) { if (res.data !== '') { $scope.hojaRuta.vendedor = res.data; $scope.$broadcast('addCabecera', { label: 'Vendedor:', valor: $filter('rellenarDigitos')($scope.hojaRuta.vendedor .NUM, 3) +' - ' + $scope.hojaRuta.vendedor.NOM }); } var domicilioStamp = domicilio.Calle + ' ' + domicilio.Numero + ', ' + domicilio.Localidad + ', ' + domicilio.Provincia; $scope.hojaRuta.domicilioStamp = domicilioStamp; $scope.$broadcast('addCabecera', { label: 'Cliente:', valor: $filter('rellenarDigitos')(cliente.cod, 3) + ' - ' + cliente.nom }); $scope.$broadcast('addCabecera', { label: 'Domicilio:', valor: domicilioStamp }); if (domicilio.verPuntos) { delete $scope.hojaRuta.domicilio.verPuntos; $scope.seleccionarPuntosDeDescarga(); } else { focaCrearHojaRutaService .getPuntosDescargaByClienDom(domicilio.id, cliente.cod) .then(function (res) { if (res.data.length) { $scope.seleccionarPuntosDeDescarga(); } }); } $filter('filter')($scope.botonera, { label: 'Cliente', })[0].checked = true; }) .catch(function (e) { console.log(e); }); }, function () { $scope.seleccionarCliente(true); return; } ); }; $scope.seleccionarPuntosDeDescarga = function () { if (!$scope.hojaRuta.cliente.COD || !$scope.hojaRuta.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.remito.domicilio.id, idCliente: $scope.remito.cliente.COD, articulos: $scope.remito.articulosRemito, puntosDescarga: $scope.remito.remitoPuntoDescarga, domicilio: $scope.remito.domicilio } } } ); modalInstance.result.then( function(puntosDescarga) { puntosDescarga.forEach(function(punto) { $scope.hojaRuta.remitoPuntoDescarga.push( { puntoDescarga: punto } ); }); $scope.$broadcast('addCabecera', { label: 'Puntos de descarga:', valor: getCabeceraPuntoDescarga(puntosDescarga) }); }, function () { $scope.abrirModalDomicilios($scope.cliente); } ); } }; function getCabeceraPuntoDescarga(puntosDescarga) { var puntosStamp = ''; puntosDescarga.forEach(function (punto, idx, arr) { puntosStamp += punto.descripcion; if ((idx + 1) !== arr.length) puntosStamp += ', '; }); return puntosStamp; } $scope.crearHojaRuta = function () { var continuar = validarHojaRuta(); if (!continuar) { return; } else if ($scope.remitoAbierto) { guardarRemitoAbierto(); return; } var date = new Date(); var save = { hojaRuta: { id: 0, fechaCreacion: new Date(date.getTime()).toISOString().slice(0, 19) .replace('T', ' '), idTransportista: $scope.hojaRuta.transportista.COD, idChofer: $scope.hojaRuta.chofer.id, idVehiculo: $scope.hojaRuta.vehiculo.id, tarifaFlete: $scope.hojaRuta.tarifario, fechaReparto: new Date($scope.hojaRuta.fechaReparto).toISOString().substring(0, 10), estado: 0 }, remitos: $scope.hojaRuta.remitosTabla }; save.hojaRuta = angular.extend({}, save.hojaRuta, $scope.hojaRuta.datosExtra); focaCrearHojaRutaService.crearHojaRuta(save).then( function (data) { focaModalService.alert( 'Hoja ruta creada Nº: ' + $filter('rellenarDigitos')(data.data.sucursal, 4) + '-' + $filter('rellenarDigitos')(data.data.numeroHojaRuta, 8) ); config(); }, function (error) { focaModalService.alert('Hubo un error al crear la hoja de ruta'); console.info(error); } ); }; $scope.seleccionarProveedor = function () { 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) { $filter('filter')($scope.botonera, { label: 'Proveedor', })[0].checked = true; $scope.$broadcast('addCabecera', { label: 'Proveedor:', valor: proveedor.COD + ' - ' + proveedor.NOM }); $scope.hojaRuta.proveedor = proveedor; }, function () { } ); }; $scope.seleccionarTransportista = function () { if (eligioPreConfirmado()) return; var parametrosModal = { titulo: 'Búsqueda de transportista', query: '/transportista', columnas: [ { nombre: 'Código', propiedad: 'COD' }, { nombre: 'Nombre', propiedad: 'NOM' }, { nombre: 'CUIT', propiedad: 'CUIT' } ] }; focaModalService.modal(parametrosModal).then( function (proveedor) { $scope.hojaRuta.transportista = proveedor; $scope.$broadcast('addCabecera', { label: 'Transportista:', valor: $filter('rellenarDigitos')(proveedor.COD, 5) + ' - ' + proveedor.NOM }); $filter('filter')($scope.botonera, { label: 'Transportista', })[0].checked = true; }, function () { } ); }; $scope.seleccionarChofer = function () { var parametrosModal = { titulo: 'Búsqueda de Chofer', query: '/chofer', columnas: [ { propiedad: 'id', nombre: 'Código', filtro: { nombre: 'rellenarDigitos', parametro: 3 } }, { propiedad: 'nombre', nombre: 'Nombre' }, { propiedad: 'dni', nombre: 'DNI' }, { propiedad: 'telefono', nombre: 'Teléfono' } ] }; focaModalService.modal(parametrosModal).then( function (chofer) { $scope.hojaRuta.chofer = chofer; $scope.$broadcast('addCabecera', { label: 'Chofer:', valor: $filter('rellenarDigitos')(chofer.id, 3) + ' - ' + chofer.nombre }); $filter('filter')($scope.botonera, { label: 'Chofer', })[0].checked = true; $scope.mostrarDetalle($scope.hojaRuta); }, function () { // funcion ejecutada cuando se cancela el modal } ); }; $scope.seleccionarVehiculo = function () { if (!eligioFecha() || eligioPreConfirmado()) return; modalVehiculos(); }; $scope.seleccionarTarifario = function () { focaModalService .prompt({ titulo: 'Tarifa flete', value: $scope.hojaRuta.tarifario }) .then(function (costo) { if (isNaN(costo)) { focaModalService .alert('Ingrese un valor válido') .then(function () { $scope.seleccionarTarifario(); }); return; } $scope.hojaRuta.tarifario = costo; $scope.$broadcast('addCabecera', { label: 'Tarifario:', valor: costo }); $filter('filter')($scope.botonera, { label: 'Tarifario', })[0].checked = true; }); }; $scope.seleccionarRemitos = function () { if (eligioPreConfirmado() || !eligioFecha() || !eligioVehiculo()) return; var modalInstance = $uibModal.open( { ariaLabelledBy: 'Busqueda de Remito', templateUrl: 'foca-modal-remito.html', controller: 'focaModalRemitoController', size: 'lg', resolve: { usadoPor: function () { return 'hojaRuta'; } } } ); modalInstance.result.then( function (remito) { // TODO: borrar cuando no se use definitivamente // for (var i = $scope.hojaRuta.remitosTabla.length - 1; i >= 0; i--) { // if ($scope.hojaRuta.remitosTabla[i].id === remito.id) { // focaModalService.alert('Remito ya incluido'); // return; // } // } // var litros = 0; // for (var j = remito.articulosRemito.length - 1; j >= 0; j--) { // litros = litros + parseFloat(remito.articulosRemito[j].cantidad); // } // if ($scope.hojaRuta.litros >= $scope.hojaRuta.vehiculo.capacidad) { // focaModalService.alert( // 'Debe ingresar toda la información para el transporte' // ); // return; // } //if($scope.hojaRuta.litros + litros >= $scope.hojaRuta.vehiculo.capacidad) // { // var litrostotales = litros; // litros = $scope.hojaRuta.vehiculo.capacidad - $scope.hojaRuta.litros; // focaModalService.alert( // 'La carga excede la capacidad disponible del vehiculo. ' + // 'Excedente no cargado: ' + (litrostotales - litros) + ' litros' // ); // } // remito.litros = litros; // $scope.hojaRuta.litros = $scope.hojaRuta.litros + litros; $scope.cargarCisterna(remito.id).then(function () { $scope.hojaRuta.remitosTabla.push(remito); $filter('filter')($scope.botonera, { label: 'Remitos', })[0].checked = true; }, function (error) { error.then($scope.seleccionarRemitos); }); }, function () { // funcion ejecutada cuando se cancela el modal } ); }; $scope.seleccionarVehiculosPrecargados = function () { if (!eligioFecha()) return; modalVehiculos(true); }; $scope.cargarCisterna = function (idRemito) { if (!eligioFecha() || !$scope.hojaRuta.vehiculo.id) return; var modalInstance = $uibModal.open( { ariaLabelledBy: 'Busqueda de Vehiculo', templateUrl: 'foca-detalle-vehiculo.html', controller: 'focaDetalleVehiculo', size: 'lg', resolve: { idVehiculo: function () { return $scope.hojaRuta.vehiculo.id; }, idRemito: function () { return idRemito; }, fechaReparto: function () { return $scope.hojaRuta.fechaReparto; } } } ); return modalInstance.result; }; $scope.seleccionarFechaEntrega = function () { var confirmacion = false; if (!angular.equals($scope.hojaRuta, $scope.inicial)) { confirmacion = true; } if (confirmacion) { focaModalService .confirm('Si cambia la fecha se perderán los datos actuales') .then(function (data) { if (data) { $scope.hojaRuta.vehiculo.id = undefined; $scope.hojaRuta.tarifario = null; $scope.hojaRuta.transportista = {}; $scope.hojaRuta.chofer = {}; $scope.hojaRuta.datosExtra = undefined; elegirFecha(); } }, function () { return; }); } else { elegirFecha(); } }; function setearFecha(fecha) { $timeout(function () { $scope.$broadcast('addCabecera', { label: 'Fecha de entrega: ', valor: fecha.toLocaleDateString() }); $scope.hojaRuta.fechaReparto = fecha; $scope.inicial.fechaReparto = fecha; }); } $scope.seleccionarDatosExtra = function () { var datosHojaRuta = $scope.hojaRuta.datosExtra; var modalInstance = $uibModal.open( { templateUrl: 'foca-modal-datos-hoja-ruta.html', controller: 'focaModalDatosHojaRutaCtrl', size: 'lg', resolve: { parametrosDatos: function () { return { datosHojaRuta: datosHojaRuta }; } } } ); return modalInstance.result.then(function (datosExtra) { $filter('filter')($scope.botonera, { label: 'Datos extra', })[0].checked = true; $scope.hojaRuta.datosExtra = datosExtra; }, function () { //se ejecuta cuando se cancela el modal }); }; $scope.desasociarRemito = function (key, idRemito) { var idsRemito = [idRemito]; focaModalService.confirm('¿Está seguro que desea desasociar este remito del' + ' vehículo?').then(function () { focaCrearHojaRutaService.desasociarRemitos(idsRemito, $scope.hojaRuta.vehiculo.id, $scope.hojaRuta.remitosTabla.length <= 1) .then(function () { $scope.hojaRuta.remitosTabla.splice(key, 1); focaModalService.alert('Remito desasociado con éxito'); }); }); }; $scope.verProductosRemito = function (idRemito) { var parametrosModal = { titulo: 'Articulos remito', query: '/articulos/remito/' + idRemito, soloMostrar: true, columnas: [ { nombre: 'Código', propiedad: 'codigo' }, { nombre: 'Descripción', propiedad: 'descripcion' }, { nombre: 'Cantidad', propiedad: 'cantidad' } ] }; focaModalService.modal(parametrosModal).then(); }; $scope.mostrarDetalle = function (hojasRutas) { var modalInstance =$uibModal.open( { ariaLabelledBy: '', templateUrl: 'modal-detalle-carga.html', controller: 'focaModalDetalleController', resolve: { hojasRutas: function () { return hojasRutas; } }, size: 'lg', backdrop: false } ); return modalInstance.result.then(function (res) { res.cisternas.forEach( function (cisterna) { $scope.cisternaCargas.push(cisterna.cisternaCarga); }); $scope.cisternaMovimientos = res.movimientos; $scope.articulosRecibidos = res.articulos; $scope.articulos = res.articulos; }, function () { //se ejecuta cuando se cancela el modal }); }; function elegirFecha() { var fechaEntrega = { titulo: 'Fecha de entrega', minDate: new Date() }; focaModalService.modalFecha(fechaEntrega).then(function (fecha) { $scope.hojaRuta.fechaReparto = fecha; $scope.$broadcast('addCabecera', { label: 'Fecha de entrega: ', valor: fecha.toLocaleDateString() }); //habilitar los otros botones var temp = []; if ($scope.botonera.length > 1) { limpiarBotonera($scope.botonera); } else if ($scope.precargado) { temp = focaCrearHojaRutaService.getBotoneraPrecargado(); modalVehiculos(true); } else if ($scope.cargaRemito && $scope.precargado === false) { temp = focaCrearHojaRutaService.getBotoneraCargarRemito(); } else { temp = focaCrearHojaRutaService.getBotoneraCargarRemito(); modalVehiculos(true); } temp.forEach(function (e) { $scope.botonera.push(e); }); $filter('filter')($scope.botonera, { label: 'Fecha Entrega', })[0].checked = true; }); } function eligioPreConfirmado() { if ($scope.eligioPreConfirmado) { focaModalService.alert('No puede elegir si eligió un vehiculo pre cargado'); return true; } return false; } function eligioFecha() { if (!$scope.hojaRuta.fechaReparto) { focaModalService.alert('Primero seleccione fecha de reparto'); return false; } return true; } function eligioVehiculo() { if (!$scope.hojaRuta.vehiculo.id) { focaModalService.alert('Primero seleccione vehiculo'); return false; } return true; } function modalVehiculos(preCargados) { var parametrosModal = {}; if (preCargados) { parametrosModal.query = '/vehiculo/obtener/pre-confirmados/' + new Date($scope.hojaRuta.fechaReparto).toISOString().substring(0, 10); parametrosModal.titulo = 'Búsqueda de vehiculos precargados'; } else { parametrosModal.query = '/vehiculo'; parametrosModal.titulo = 'Búsqueda de vehículos'; } parametrosModal.columnas = [ { propiedad: 'codigo', nombre: 'Código' }, { propiedad: 'tractor', nombre: 'tractor' }, { propiedad: 'semi', nombre: 'Semi' } ]; focaModalService.modal(parametrosModal).then(function (vehiculo) { if (!preCargados && vehiculoEnUso(vehiculo)) return; $scope.hojaRuta.vehiculo = vehiculo; $scope.hojaRuta.transportista = vehiculo.transportista; // mostrarDetalle(vehiculo); if (preCargados) { $scope.eligioPreConfirmado = true; $scope.hojaRuta.vehiculo = vehiculo; $scope.$broadcast('addCabecera', { label: 'Transportista:', valor: $filter('rellenarDigitos')(vehiculo.transportista.COD, 5) + ' - ' + vehiculo.transportista.NOM }); focaCrearHojaRutaService .getRemitosByIdVehiculo(vehiculo.id, $scope.hojaRuta.fechaReparto) .then(function (res) { $filter('filter')($scope.botonera, { label: 'Transportista', })[0].checked = true; $filter('filter')($scope.botonera, { label: 'Vehiculo', })[0].checked = true; $scope.hojaRuta.remitosTabla = res.data; }); } else { focaCrearHojaRutaService .getRemitosByIdVehiculo(vehiculo.id, $scope.hojaRuta.fechaReparto, true) .then(function (res) { $filter('filter')($scope.botonera, { label: 'Vehiculo', })[0].checked = true; $scope.hojaRuta.remitosTabla = res.data; }); } $scope.$broadcast('addCabecera', { label: 'Tractor:', valor: vehiculo.tractor }); $scope.$broadcast('addCabecera', { label: 'Semi:', valor: vehiculo.semi }); $scope.$broadcast('addCabecera', { label: 'Capacidad:', valor: vehiculo.capacidad }); }); } function vehiculoEnUso(vehiculo) { var idUsuario = focaLoginSrv.getLoginData().vendedorCobrador; for (var i = 0; i < vehiculo.cisternas.length; i++) { for (var j = 0; j < vehiculo.cisternas[i].cisternasCarga.length; j++) { var cisternaCarga = vehiculo.cisternas[i].cisternasCarga[j]; if (cisternaCarga.fechaReparto.substring(0, 10) === new Date($scope.hojaRuta.fechaReparto).toISOString().substring(0, 10) && cisternaCarga.idUsuarioProceso && cisternaCarga.idUsuarioProceso !== idUsuario) { focaModalService.alert('El vehículo está siendo usado por otro' + ' usuario'); return true; } } } return false; } function salir() { var confirmacion = false; if (!angular.equals($scope.hojaRuta, $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 limpiarBotonera(botonera) { botonera.forEach(function (boton) { boton.checked = false; }); } function setearHojaRuta(hojaRuta) { $scope.$broadcast('cleanCabecera'); var cabeceras = []; if (hojaRuta.fechaReparto) { cabeceras.push({ label: 'Fecha de entrega:', valor: $filter('date')(hojaRuta.fechaReparto, 'dd/MM/yyyy') }); $filter('filter')($scope.botonera, { label: 'Fecha Entrega' })[0].checked = true; } if (hojaRuta.transportista.COD) { cabeceras.push({ label: 'Transportista:', valor: $filter('rellenarDigitos')(hojaRuta.transportista.COD, 5) + ' - ' + hojaRuta.transportista.NOM }); $filter('filter')($scope.botonera, { label: 'Transportista' })[0].checked = true; } if (hojaRuta.chofer.id) { cabeceras.push({ label: 'Chofer:', valor: $filter('rellenarDigitos')(hojaRuta.chofer.id, 3) + ' - ' + hojaRuta.chofer.nombre }); $filter('filter')($scope.botonera, { label: 'Chofer' })[0].checked = true; } if (hojaRuta.vehiculo.id) { cabeceras.push({ label: 'Tractor:', valor: hojaRuta.vehiculo.tractor }); cabeceras.push({ label: 'Semi:', valor: hojaRuta.vehiculo.semi }); cabeceras.push({ label: 'Capacidad:', valor: hojaRuta.vehiculo.capacidad }); $filter('filter')($scope.botonera, { label: 'Vehiculo' })[0].checked = true; } if (hojaRuta.tarifario) { cabeceras.push({ label: 'Tarifario:', valor: hojaRuta.tarifario }); $filter('filter')($scope.botonera, { label: 'Tarifario' })[0].checked = true; } addArrayCabecera(cabeceras); $scope.hojaRuta = hojaRuta; } function getLSHojaRuta() { var hojaRuta = JSON.parse($localStorage.hojaRuta || null); if (hojaRuta) { setearHojaRuta(hojaRuta); delete $localStorage.hojaRuta; } } function addArrayCabecera(array) { for (var i = 0; i < array.length; i++) { $scope.$broadcast('addCabecera', { label: array[i].label, valor: array[i].valor }); } } } ]);