public async void GuardarPosicionVehiculoGPS(EventoLogistico evento)
        {
            RespuestaProcesoEventoLogistico respuesta = new RespuestaProcesoEventoLogistico();

            DataService.AppDataService ds = new DataService.AppDataService(ParametrosSistema.TokenUsuarioActual);
            await ds.RealizarPeticionApi <RespuestaProcesoEventoLogistico>("Evento/GuardarPosicionVehiculoGPS", DataService.TipoPeticionApi.Post, evento);
        }
        public EventoLogistico SeleccionarEventosLogisticoporID(Int64 idEvento)
        {
            EventoLogisticoDAO     eventoDAO = new EventoLogisticoDAO();
            List <EventoLogistico> eventos   = eventoDAO.SeleccionarEventosLogisticoporID(idEvento);
            EventoLogistico        evento    = new EventoLogistico();

            if (eventos != null && eventos.Count > 0)
            {
                evento = eventos[0];
            }

            return(evento);
        }
        public EventoLogistico GuardarEventoLogistico(EventoLogistico evento)
        {
            lock (locker)
            {
                if (evento.IdApp != 0)
                {
                    using (var _db = DependencyService.Get <ISQLite>().GetConnection())
                    {
                        _db.Update(evento);
                    }

                    return(evento);
                }
                else
                {
                    using (var _db = DependencyService.Get <ISQLite>().GetConnection())
                    {
                        evento.IdApp = _db.Insert(evento);
                    }
                    return(evento);
                }
            }
        }
        protected async override void OnAppearing()
        {
            base.OnAppearing();

            activityIndicator.IsRunning = true;
            activityIndicator.IsVisible = true;

            ScrollView scrollView = new ScrollView();

            StackLayout stackPanel = new StackLayout();

            scrollView.Content = stackPanel;
            stackPanel.Padding = new Thickness(10);

            EventoLogisticoBLL eventoLogisticosBLL = new EventoLogisticoBLL();
            EventoLogistico    evento = new EventoLogistico();

            evento = eventoLogisticosBLL.SeleccionarEventosLogisticoporID(_idEvento);

            if (evento != null)
            {
                List <CampoEventoLogistico> camposTipoEvento = await eventoLogisticosBLL.SeleccionarCamposPorEvento(evento.IdTipoEvento, consultaLocal : true);

                if (camposTipoEvento != null)
                {
                    List <TipoEventoLogistico> tiposEventos = await eventoLogisticosBLL.SeleccionarTiposEventoLogistico(consultaLocal : true);

                    TipoEventoLogistico tipoEvento = (from t in tiposEventos
                                                      where t.CodigoEvento == evento.IdTipoEvento
                                                      select t).FirstOrDefault();

                    if (tipoEvento != null)
                    {
                        Label lblNombreEvento = new Label();
                        lblNombreEvento.Text     = tipoEvento.NombreEvento;
                        lblNombreEvento.FontSize = 30;
                        stackPanel.Children.Add(lblNombreEvento);
                    }

                    Label lblTituloFechaEvento = new Label();
                    lblTituloFechaEvento.Text     = "Fecha Evento";
                    lblTituloFechaEvento.FontSize = 25;
                    stackPanel.Children.Add(lblTituloFechaEvento);

                    Label lblFechaEvento = new Label();
                    lblFechaEvento.Text     = evento.FechaEvento.Value.ToString();
                    lblFechaEvento.FontSize = 20;
                    stackPanel.Children.Add(lblFechaEvento);

                    Label lblTituloNumeroManifiesto = new Label();
                    lblTituloNumeroManifiesto.Text     = "Número Manifiesto";
                    lblTituloNumeroManifiesto.FontSize = 25;
                    stackPanel.Children.Add(lblTituloNumeroManifiesto);

                    Label lblNumeroViaje = new Label();
                    lblNumeroViaje.Text     = evento.NumeroManifiesto.ToString();
                    lblNumeroViaje.FontSize = 20;
                    stackPanel.Children.Add(lblNumeroViaje);

                    Label tituloCampo;
                    Label valorCampo;

                    foreach (CampoEventoLogistico campo in camposTipoEvento)
                    {
                        tituloCampo = new Label();
                        valorCampo  = new Label();

                        tituloCampo.Text     = campo.TituloCampoEventoLogistico;
                        tituloCampo.FontSize = 25;

                        valorCampo.Text     = Util.ObtenerValorDinamicamente(evento, campo.NombreCampoEventoLogistico);
                        valorCampo.FontSize = 20;

                        stackPanel.Children.Add(tituloCampo);
                        stackPanel.Children.Add(valorCampo);
                    }
                    if (!string.IsNullOrEmpty(evento.ErrorSincronizacion))
                    {
                        //Label lblTituloError = new Label();
                        //lblTituloError.Text = "Resultado Evento";
                        //stackPanel.Children.Add(lblTituloError);
                        Label lblError = new Label();
                        lblError.Text      = evento.ErrorSincronizacion;
                        lblError.TextColor = Color.Red;
                        stackPanel.Children.Add(lblError);
                    }

                    Content = scrollView;
                }
            }

            activityIndicator.IsRunning = false;
            activityIndicator.IsVisible = false;
        }
Exemplo n.º 5
0
        // ILocationListener is a way for the Service to subscribe for updates
        // from the System location Service

        public void OnLocationChanged(Android.Locations.Location location)
        {
            try {
                if (DependencyService.Get <ICredentialsService>().DoCredentialsExist())
                {
                    //LocationChanged(this, new LocationChangedEventArgs(location));

                    // This should be updating every time we request new location updates
                    // both when teh app is in the background, and in the foreground
                    Log.Debug(logTag, $"Latitude is {location.Latitude}");
                    Log.Debug(logTag, $"Longitude is {location.Longitude}");
                    Log.Debug(logTag, $"Altitude is {location.Altitude}");
                    Log.Debug(logTag, $"Speed is {location.Speed}");
                    Log.Debug(logTag, $"Accuracy is {location.Accuracy}");
                    Log.Debug(logTag, $"Bearing is {location.Bearing}");

                    Transporte viajeActivo = null;

                    Util util    = new Util();
                    bool?tercero = null;
                    if (util.UsuarioTienePermiso("eventoslogisticosterceros"))
                    {
                        tercero = true;
                    }

                    EventoLogisticoBLL eventoBLL = new EventoLogisticoBLL();
                    List <Transporte>  transportesHabilitadosRegistroEventos = new List <Transporte>();



                    Task.Run(async() => {
                        transportesHabilitadosRegistroEventos = await eventoBLL.SeleccionarTransporteHabilitadoRegistroEventos(!await ParametrosSistema.isOnline, tercero);

                        if (transportesHabilitadosRegistroEventos != null && transportesHabilitadosRegistroEventos.Count > 0)
                        {
                            viajeActivo = transportesHabilitadosRegistroEventos[0];
                        }


                        if (viajeActivo != null)
                        {
                            //The Geocoder class retrieves a list of address from Google over the internet
                            Geocoder geocoder = new Geocoder(Android.App.Application.Context);
                            IList <Android.Locations.Address> addressList = null;
                            Android.Locations.Address address             = null;
                            double lat      = 0;
                            double lon      = 0;
                            string _address = string.Empty;

                            try {
                                if (location.Latitude != 0)
                                {
                                    addressList = geocoder.GetFromLocation(location.Latitude, location.Longitude, 1);
                                    address     = addressList.FirstOrDefault();

                                    _address = address.SubThoroughfare + " " + address.Thoroughfare +
                                               ", " + address.Locality + ", " + address.AdminArea + ", " + address.CountryCode;
                                    //_address = address.
                                }

                                lat = location.Latitude;
                                lon = location.Longitude;
                            } catch (Exception ex) {
                            }


                            //Se crea evento logistico para guardar la posicion del gps
                            EventoLogistico evento = new EventoLogistico();

                            //Cero es solo reportar posicion
                            evento.IdTipoEvento             = 44; //Evento reportar posicion
                            evento.Placa                    = viajeActivo.Placa;
                            evento.NumeroManifiesto         = viajeActivo.NumeroTransporte;
                            evento.Latitud                  = (float)lat;
                            evento.Longitud                 = (float)lon;
                            evento.DescripcionPosicion      = _address;
                            evento.FechaEvento              = DateTime.Now;
                            evento.NumeroDocumentoConductor = viajeActivo.NumeroDocConductor.ToString();

                            await eventoBLL.GuardarEventoLogistico(evento);
                        }
                    });



                    //Log.Debug("TAG", "Funciona Inicio " + i + " long " + location.Latitude + " lat " + location.Longitude + " - " + _address);



                    //else {
                    //    //Log.Debug("TAG", "Funciona Inicio Sin viaje activo " + i);
                    //}
                }
            } catch {
            }
        }
        public async Task <RespuestaProcesoEventoLogistico> GuardarEventoLogistico(EventoLogistico evento)
        {
            RespuestaProcesoEventoLogistico respuesta = new RespuestaProcesoEventoLogistico();



            if (await ParametrosSistema.isOnline)
            {
                DataService.AppDataService ds = new DataService.AppDataService(ParametrosSistema.TokenUsuarioActual);
                respuesta = await ds.RealizarPeticionApi <RespuestaProcesoEventoLogistico>("Evento/GuardarEventoLogistico", DataService.TipoPeticionApi.Post, evento);

                evento.ID                  = respuesta.IdEvento;
                evento.Sincronizado        = true;
                evento.FechaSincronizacion = DateTime.Now;
                if (respuesta.ProcesadoCorrectamente == false)
                {
                    evento.Estado = "E";
                    evento.ErrorSincronizacion = respuesta.Respuesta;
                }
                else
                {
                    evento.Estado = "S";
                }
            }
            else
            {
                evento.Sincronizado = false;
                respuesta.ProcesadoCorrectamente = true;
                respuesta.Respuesta = "Se ha guardado el evento en la memoria interna del teléfono.";
            }

            //Se determina si se debe guardar el evento en la base de datos local
            EventoLogisticoDAO eventoDAO = new EventoLogisticoDAO();

            eventoDAO.GuardarEventoLogistico(evento);

            //Si es un evento de activación se debe registrar el manifiesto en el historial de activaciones
            if (evento.IdTipoEvento == (int)TipoEventoLogisticoEnum.ActivarViaje)
            {
                if (respuesta.ProcesadoCorrectamente == true)
                {
                    Transporte transporte = new Transporte();
                    HistorialActivacionManifiesto historial = new HistorialActivacionManifiesto();

                    historial.Sincronizado        = true;
                    historial.FechaSincronizacion = DateTime.Now;
                    historial.Activo            = true;
                    historial.FechaActivacion   = evento.FechaEvento;
                    historial.UsuarioActivacion = ParametrosSistema.UsuarioActual;
                    TransporteBLL transporteBLL = new TransporteBLL();
                    transporte = await transporteBLL.SeleccionarTransporte(evento.NumeroManifiesto);

                    //if (await ParametrosSistema.isOnline)
                    //{
                    //    historial.Sincronizado = true;
                    //    historial.FechaSincronizacion = DateTime.Now;

                    //    TransporteBLL transporteBLL = new TransporteBLL();
                    //    transporte = await transporteBLL.SeleccionarTransporte(evento.NumeroManifiesto);

                    //}
                    //else
                    //{
                    //    historial.Sincronizado = false;
                    //    transporte.NumeroDocConductor = Convert.ToInt32(ParametrosSistema.NumeroIdentificacionUsuarioActual);
                    //    transporte.NumeroTransporte = evento.NumeroManifiesto;
                    //}


                    //se guarda un registro en historial activación viaje
                    if (transporte != null)
                    {
                        historial.Placa = transporte.Placa;
                        historial.NumeroDocConductor = transporte.NumeroDocConductor.ToString();
                        historial.NombreRuta         = transporte.NombreRuta;
                        historial.NumeroManifiesto   = transporte.NumeroTransporte;
                        historial.ClaseTransporte    = transporte.ClaseTransporte;
                    }
                    else
                    {
                        historial.NumeroDocConductor = historial.UsuarioActivacion;
                    }
                    HistorialActivacionManifiestoDAO historialActivacionDAO = new HistorialActivacionManifiestoDAO();

                    //si en la bd local el conductor aun tiene un viaje activo, se elimina
                    HistorialActivacionManifiesto historialAnterior = historialActivacionDAO.SeleccionarHistorialManifiestoActivoPorConductor(evento.NumeroDocumentoConductor);
                    if (historialAnterior != null)
                    {
                        historialActivacionDAO.EliminarHistorialActivacionManifiesto(historialAnterior.NumeroManifiesto);
                    }

                    //se fuarda el registro de activacion viaje
                    historialActivacionDAO.GuardarHistorialActivacionManifiesto(historial);

                    //Se guardan las entregas del transporte
                    if (transporte != null && transporte.Entregas != null && transporte.Entregas.Count > 0)
                    {
                        EntregaBLL entregaBLL = new EntregaBLL();
                        foreach (Entrega entrega in transporte.Entregas)
                        {
                            entregaBLL.GuardarEntrega(entrega);
                        }
                    }
                }
                else if (evento.Sincronizado == true && evento.Estado == "E")
                {
                    //Si el evento se sincronizó pero devolvió error, se elimina el manifiesto del historial de activacion
                    HistorialActivacionManifiestoDAO historialActivacionDAO = new HistorialActivacionManifiestoDAO();
                    historialActivacionDAO.EliminarHistorialActivacionManifiesto(evento.NumeroManifiesto);
                }
            }
            else if (evento.IdTipoEvento == (int)TipoEventoLogisticoEnum.SuspenderViaje)
            {
                HistorialActivacionManifiestoBLL historialBLL = new HistorialActivacionManifiestoBLL();
                historialBLL.EliminarHistorialActivacionManifiesto(evento.NumeroManifiesto);
            }
            else if (evento.IdTipoEvento == (int)TipoEventoLogisticoEnum.ReanudarViaje)
            {
                Transporte transporte = new Transporte();
                HistorialActivacionManifiesto historial = new HistorialActivacionManifiesto();

                historial.Sincronizado        = true;
                historial.FechaSincronizacion = DateTime.Now;
                historial.Activo            = true;
                historial.FechaActivacion   = evento.FechaEvento;
                historial.UsuarioActivacion = ParametrosSistema.UsuarioActual;
                TransporteBLL transporteBLL = new TransporteBLL();
                transporte = await transporteBLL.SeleccionarTransporte(evento.NumeroManifiesto);

                if (transporte != null)
                {
                    historial.Placa = transporte.Placa;
                    historial.NumeroDocConductor = transporte.NumeroDocConductor.ToString();
                    historial.NombreRuta         = transporte.NombreRuta;
                    historial.NumeroManifiesto   = transporte.NumeroTransporte;
                    historial.ClaseTransporte    = transporte.ClaseTransporte;
                }
                else
                {
                    historial.NumeroDocConductor = historial.UsuarioActivacion;
                }
                HistorialActivacionManifiestoDAO historialActivacionDAO = new HistorialActivacionManifiestoDAO();

                //si en la bd local el conductor aun tiene un viaje activo, se elimina
                HistorialActivacionManifiesto historialAnterior = historialActivacionDAO.SeleccionarHistorialManifiestoActivoPorConductor(evento.NumeroDocumentoConductor);
                if (historialAnterior != null)
                {
                    historialActivacionDAO.EliminarHistorialActivacionManifiesto(historialAnterior.NumeroManifiesto);
                }

                //se guarda el registro de reanudación viaje
                historialActivacionDAO.GuardarHistorialActivacionManifiesto(historial);
            }
            else if (evento.IdTipoEvento == (int)TipoEventoLogisticoEnum.FinViaje)
            {
                HistorialActivacionManifiestoDAO historialActivacionDAO = new HistorialActivacionManifiestoDAO();
                var historialActivacion = historialActivacionDAO.SeleccionarHistorialActivacionManifiesto(evento.NumeroManifiesto);
                if (historialActivacion != null)
                {
                    if (evento.Sincronizado == false || respuesta.ProcesadoCorrectamente == true)
                    {
                        //Se debe marcar como finalizado el viaje
                        historialActivacion.Activo              = false;
                        historialActivacion.FechaInactivacion   = evento.FechaEvento;
                        historialActivacion.UsuarioInactivacion = evento.NumeroDocumentoConductor;
                        historialActivacionDAO.GuardarHistorialActivacionManifiesto(historialActivacion);
                    }
                    else if (evento.Sincronizado == true && evento.Estado == "E")
                    {
                        //Si el evento se sincronizó pero devolvió error, se elimina el manifiesto del historial de activacion
                        historialActivacion.Activo              = true;
                        historialActivacion.FechaInactivacion   = null;
                        historialActivacion.UsuarioInactivacion = null;
                        historialActivacionDAO.GuardarHistorialActivacionManifiesto(historialActivacion);
                    }
                }
            }
            return(respuesta);
        }
        private List <TipoEventoLogistico> ValidarEventosLogisticosSucesoresPorUltimoEvento(EventoLogistico ultimoEventoRegistrado, List <EventoLogistico> eventosRegistrados, List <TipoEventoLogistico> tipoEventos, long numeroManifiesto)
        {
            List <TipoEventoLogistico> eventosSucesores = new List <TipoEventoLogistico>();

            //Si el ultimo evento registrado fue activación, valida si es un vacio para mostrar el evento inicio de viaje
            if (ultimoEventoRegistrado.IdTipoEvento == (int)TipoEventoLogisticoEnum.ActivarViaje)
            {
                HistorialActivacionManifiestoDAO historialActivacionDAO = new HistorialActivacionManifiestoDAO();
                HistorialActivacionManifiesto    transporte             = historialActivacionDAO.SeleccionarHistorialActivacionManifiesto(ultimoEventoRegistrado.NumeroManifiesto);
                if (transporte != null)
                {
                    if (transporte.ClaseTransporte == "ZT17" || transporte.ClaseTransporte == "ZT18")
                    {
                        eventosSucesores = tipoEventos.Where(t => t.CodigoEvento == (int)TipoEventoLogisticoEnum.IniciaViaje ||
                                                             t.CodigoEvento == (int)TipoEventoLogisticoEnum.Otro).ToList();
                        return(eventosSucesores);
                    }
                }
            }

            //si tiene inicios de cargue sin fin cargue, muestra solo fin cargue
            if (ultimoEventoRegistrado.IdTipoEvento == (int)TipoEventoLogisticoEnum.IniciaCargue)
            {
                eventosSucesores = tipoEventos.Where(t => t.CodigoEvento == (int)TipoEventoLogisticoEnum.FinCargue ||
                                                     t.CodigoEvento == (int)TipoEventoLogisticoEnum.Otro).ToList();
                return(eventosSucesores);
            }

            //si valida tiene mas entregas pendientes por registrarle datos de cargue
            EntregaDAO     entregaDAO         = new EntregaDAO();
            List <Entrega> entregasManifiesto = entregaDAO.SeleccionarEntregasPorTransporte(numeroManifiesto);

            if (ultimoEventoRegistrado.IdTipoEvento == (int)TipoEventoLogisticoEnum.FinCargue)
            {
                int entregasCargadas = 0;
                foreach (Entrega entrega in entregasManifiesto)
                {
                    var llegadaCargue = (from e in eventosRegistrados
                                         where e.IdTipoEvento == (int)TipoEventoLogisticoEnum.LlegadaCargue
                                         where e.campo1 == entrega.NumeroEntrega.ToString()
                                         select e).ToList();
                    var finCargue = (from e in eventosRegistrados
                                     where e.IdTipoEvento == (int)TipoEventoLogisticoEnum.FinCargue
                                     where e.campo1 == entrega.NumeroEntrega.ToString()
                                     select e).ToList();
                    if (llegadaCargue != null && finCargue != null)
                    {
                        entregasCargadas += 1;
                    }
                }
                if (entregasCargadas < entregasManifiesto.Count)
                {
                    eventosSucesores = tipoEventos.Where(t => t.CodigoEvento == (int)TipoEventoLogisticoEnum.LlegadaCargue ||
                                                         t.CodigoEvento == (int)TipoEventoLogisticoEnum.Otro).ToList();
                    return(eventosSucesores);
                }
            }
            //si tiene inicios de descargue sin fin descargue, muestra solo fin descargue
            if (ultimoEventoRegistrado.IdTipoEvento == (int)TipoEventoLogisticoEnum.IniciaDescargue)
            {
                eventosSucesores = tipoEventos.Where(t => t.CodigoEvento == (int)TipoEventoLogisticoEnum.FinDescargue ||
                                                     t.CodigoEvento == (int)TipoEventoLogisticoEnum.Otro).ToList();
                return(eventosSucesores);
            }
            //si valida tiene mas entregas pendientes por registrarle datos de descargue
            if (ultimoEventoRegistrado.IdTipoEvento == (int)TipoEventoLogisticoEnum.FinDescargue)
            {
                bool existenEntregasSinDescargar = false;


                int entregasDescargadasoDesegachadas = 0;

                foreach (Entrega entrega in entregasManifiesto)
                {
                    var llegadaDescargue = (from e in eventosRegistrados
                                            where e.IdTipoEvento == (int)TipoEventoLogisticoEnum.LlegadaDestino
                                            where e.campo1 == entrega.NumeroEntrega.ToString()
                                            select e).FirstOrDefault();
                    var finDescargue = (from e in eventosRegistrados
                                        where e.IdTipoEvento == (int)TipoEventoLogisticoEnum.FinDescargue
                                        where e.campo1 == entrega.NumeroEntrega.ToString()
                                        select e).FirstOrDefault();

                    if (llegadaDescargue != null && finDescargue != null)
                    {
                        entregasDescargadasoDesegachadas = entregasDescargadasoDesegachadas + 1;
                    }
                    else
                    {
                        var desenganche = (from e in eventosRegistrados
                                           where e.IdTipoEvento == (int)TipoEventoLogisticoEnum.Desenganche
                                           select e).FirstOrDefault();

                        if (desenganche != null)
                        {
                            int remesesasDesengachadas = 0;
                            if (int.TryParse(desenganche.campo1, out remesesasDesengachadas))
                            {
                                entregasDescargadasoDesegachadas = entregasDescargadasoDesegachadas + remesesasDesengachadas;
                            }
                        }
                    }
                }
                if (entregasDescargadasoDesegachadas < entregasManifiesto.Count())
                {
                    existenEntregasSinDescargar = true;
                }

                if (existenEntregasSinDescargar)
                {
                    eventosSucesores = tipoEventos.Where(t => t.CodigoEvento == (int)TipoEventoLogisticoEnum.LlegadaDestino ||
                                                         t.CodigoEvento == (int)TipoEventoLogisticoEnum.Otro).ToList();
                    return(eventosSucesores);
                }
            }
            //si tiene inicios de paradas sin continuacion viaje, muestra solo eventos que puede registrar en esta parado
            if (ultimoEventoRegistrado.IdTipoEvento == (int)TipoEventoLogisticoEnum.ParadaCamino)
            {
                eventosSucesores = tipoEventos.Where(t => t.CodigoEvento == (int)TipoEventoLogisticoEnum.ContinuacionViaje ||
                                                     t.CodigoEvento == (int)TipoEventoLogisticoEnum.Otro).ToList();
                return(eventosSucesores);
            }

            return(eventosSucesores);
        }
        public async Task <List <TipoEventoLogistico> > SeleccionarSiguienteEventoporManifiesto(Int64 numeroManifiesto, bool consultaLocal = false)
        {
            List <TipoEventoLogistico> eventosSucesores = new List <TipoEventoLogistico>();
            Util util = new Util();
            bool?usuarioTipoTercero = null;

            if (util.UsuarioTienePermiso("eventoslogisticosterceros"))
            {
                usuarioTipoTercero = true;
            }

            if (consultaLocal)
            {
                string numeroIdentificacionConductor          = string.Empty;
                List <TipoEventoLogistico> tipoEventos        = new List <TipoEventoLogistico>();
                List <EventoLogistico>     eventosRegistrados = new List <EventoLogistico>();

                EventoLogisticoDAO dao = new EventoLogisticoDAO();
                List <JerarquiaTipoEventoLogistico> jerarquiaTipoEventos = new List <JerarquiaTipoEventoLogistico>();

                EventoLogistico     ultimoEventoRegistrado = null;
                TipoEventoLogistico ultimoTipoEvento       = new TipoEventoLogistico();
                tipoEventos = await this.SeleccionarTiposEventoLogistico(consultaLocal : true, aplicaTerceros : usuarioTipoTercero);

                if ((usuarioTipoTercero.HasValue && !usuarioTipoTercero.Value) || !usuarioTipoTercero.HasValue)
                {
                    //Se consulta si tiene jornada laboral activa
                    var             eventosInicioJornada = dao.SeleccionarEventosLogisticos(numeroManifiesto: null, estado: null, codigoTipoEvento: (int)TipoEventoLogisticoEnum.InicioJornada);
                    var             eventosFinJornada    = dao.SeleccionarEventosLogisticos(numeroManifiesto: null, estado: null, codigoTipoEvento: (int)TipoEventoLogisticoEnum.FinJornada);
                    EventoLogistico ultimoInicioJornada  = null;
                    EventoLogistico ultimoFinJornada     = null;
                    if (eventosInicioJornada != null && eventosInicioJornada.Count > 0)
                    {
                        eventosInicioJornada = eventosInicioJornada.OrderByDescending(e => e.FechaEvento).ToList();
                        ultimoInicioJornada  = eventosInicioJornada.DefaultIfEmpty(null).Where(e => String.IsNullOrEmpty(e.Estado) || e.Estado != "E").FirstOrDefault();
                    }
                    if (eventosFinJornada != null && eventosFinJornada.Count > 0)
                    {
                        eventosFinJornada = eventosFinJornada.OrderByDescending(e => e.FechaEvento).ToList();
                        ultimoFinJornada  = eventosFinJornada.DefaultIfEmpty(null).Where(e => String.IsNullOrEmpty(e.Estado) || e.Estado != "E").FirstOrDefault();
                    }
                    bool existeJornadaLaboral = false;
                    if (ultimoInicioJornada != null)
                    {
                        if (ultimoFinJornada == null)
                        {
                            existeJornadaLaboral = true;
                        }
                        else
                        {
                            //SI existe algún evento de fin jornada registrado, se debe validar que sea anterior al ultimo inicio de jornada
                            if (ultimoFinJornada.FechaEvento < ultimoInicioJornada.FechaEvento)
                            {
                                existeJornadaLaboral = true;
                            }
                        }
                    }

                    if (existeJornadaLaboral == false)
                    {
                        //Si no tiene jornada laboral activa se le muestra únicamente el evento de inicio jornada
                        eventosSucesores = tipoEventos.Where(t => t.CodigoEvento == (int)TipoEventoLogisticoEnum.InicioJornada ||
                                                             t.CodigoEvento == (int)TipoEventoLogisticoEnum.Otro).ToList();
                        return(eventosSucesores);
                    }
                }
                if (numeroManifiesto == 0)
                {
                    eventosSucesores = dao.SeleccionarEventosSucesores(0);
                    if (eventosSucesores != null)
                    {
                        eventosSucesores = eventosSucesores.Where(e => e.TransporteObligatorio == false).ToList();
                    }
                }
                else
                {
                    eventosRegistrados = SeleccionarEventosLogisticos(numeroManifiesto, consultaLocal: true, estado: null);


                    jerarquiaTipoEventos = await SeleccionarJerarquiaTipoEventosLogisticos(consultaLocal : true);

                    if (eventosRegistrados != null && eventosRegistrados.Count > 0)
                    {
                        //Se excluyen los eventos con error
                        eventosRegistrados = eventosRegistrados.Where(e => String.IsNullOrEmpty(e.Estado) || e.Estado != "E").OrderByDescending(e => e.FechaEvento).ToList();

                        ultimoEventoRegistrado = (from e in eventosRegistrados
                                                  select e).FirstOrDefault();
                    }
                    if (ultimoEventoRegistrado != null)
                    {
                        eventosSucesores = ValidarEventosLogisticosSucesoresPorUltimoEvento(ultimoEventoRegistrado, eventosRegistrados, tipoEventos, numeroManifiesto);

                        if (eventosSucesores != null && eventosSucesores.Count > 0)
                        {
                            return(eventosSucesores);
                        }

                        ultimoTipoEvento = (from t in tipoEventos
                                            where t.CodigoEvento == ultimoEventoRegistrado.IdTipoEvento
                                            select t).FirstOrDefault();

                        if (ultimoTipoEvento.EventoTipoOtros && eventosRegistrados.Count == 1)
                        {
                            //Solo se ha registrado un evento y es de tipo "Otros"
                            eventosSucesores = dao.SeleccionarEventosSucesores(0);
                        }
                        else if (ultimoTipoEvento.EventoTipoOtros && eventosRegistrados.Count > 1)
                        {
                            List <EventoLogistico> eventosRegistradosTipoOtros = new List <EventoLogistico>();
                            //Se valida si el anterior evento registrado es de tipo otros con restriccion
                            //7,14,19: Parada, Entrada Taller, Inicio jornada respectivamente
                            eventosRegistradosTipoOtros = (from e in eventosRegistrados
                                                           join t in tipoEventos on e.IdTipoEvento equals t.CodigoEvento
                                                           where t.EventoTipoOtros && ParametrosSistema.EventoTipoOtroconRestriccion.Contains(t.CodigoEvento)
                                                           orderby e.FechaEvento descending
                                                           select e).ToList();
                            if (eventosRegistradosTipoOtros != null && eventosRegistradosTipoOtros.Count > 0)
                            {
                                var grupoEventosRegistradosTipoOtros = eventosRegistradosTipoOtros.GroupBy(e => e.IdTipoEvento);

                                foreach (IGrouping <int, EventoLogistico> grupo in grupoEventosRegistradosTipoOtros)
                                {
                                    int cantidad = grupo.Count();
                                    var eventoTipoRestriccion = (from j in jerarquiaTipoEventos
                                                                 where j.CodigoEventoPredecesor == grupo.Key
                                                                 select j).FirstOrDefault();
                                    if (eventoTipoRestriccion != null)
                                    {
                                        int cantidadeventoTipoRestriccion = (from e in eventosRegistrados
                                                                             where e.IdTipoEvento == eventoTipoRestriccion.CodigoEvento
                                                                             select e).Count();
                                        if (cantidad > cantidadeventoTipoRestriccion)
                                        {
                                            eventosSucesores = dao.SeleccionarEventosSucesores(grupo.Key);
                                        }
                                    }
                                }

                                if (eventosSucesores.Count() == 0)
                                {
                                    //eventosRegistrados = eventosRegistrados.OrderByDescending(x => x.FechaEvento).OrderByDescending(x => x.ID).ToList();
                                    eventosRegistrados     = eventosRegistrados.OrderByDescending(x => x.FechaEvento).ToList();
                                    ultimoEventoRegistrado = null;
                                    ultimoEventoRegistrado = (from e in eventosRegistrados
                                                              join t in tipoEventos on e.IdTipoEvento equals t.CodigoEvento
                                                              where !t.EventoTipoOtros
                                                              select e).FirstOrDefault();
                                    if (ultimoEventoRegistrado != null)
                                    {
                                        eventosSucesores = ValidarEventosLogisticosSucesoresPorUltimoEvento(ultimoEventoRegistrado, eventosRegistrados, tipoEventos, numeroManifiesto);

                                        if (eventosSucesores == null || eventosSucesores.Count == 0)
                                        {
                                            eventosSucesores = dao.SeleccionarEventosSucesores(ultimoEventoRegistrado.IdTipoEvento);
                                        }
                                    }
                                    else
                                    {
                                        eventosSucesores = dao.SeleccionarEventosSucesores(0);
                                    }
                                }
                            }
                            else
                            {
                                eventosRegistrados = eventosRegistrados.OrderByDescending(x => x.FechaEvento).OrderByDescending(x => x.ID).ToList();
                                //Se busca el ultimo evento registrado que no sea de tipo otros
                                ultimoEventoRegistrado = (from e in eventosRegistrados
                                                          join t in tipoEventos on e.IdTipoEvento equals t.CodigoEvento
                                                          where !t.EventoTipoOtros
                                                          select e).FirstOrDefault();
                                if (ultimoEventoRegistrado != null)
                                {
                                    eventosSucesores = ValidarEventosLogisticosSucesoresPorUltimoEvento(ultimoEventoRegistrado, eventosRegistrados, tipoEventos, numeroManifiesto);

                                    if (eventosSucesores == null || eventosSucesores.Count == 0)
                                    {
                                        eventosSucesores = dao.SeleccionarEventosSucesores(ultimoEventoRegistrado.IdTipoEvento);
                                    }
                                }
                                else
                                {
                                    eventosSucesores = dao.SeleccionarEventosSucesores(0);
                                }
                            }
                        }
                        else
                        {
                            //se consulta los eventos sucesores del ultimo evento registrado
                            eventosSucesores = ValidarEventosLogisticosSucesoresPorUltimoEvento(ultimoEventoRegistrado, eventosRegistrados, tipoEventos, numeroManifiesto);

                            if (eventosSucesores == null || eventosSucesores.Count == 0)
                            {
                                eventosSucesores = dao.SeleccionarEventosSucesores(ultimoEventoRegistrado.IdTipoEvento);
                            }
                        }
                    }
                    else
                    {
                        //No se ha registrado ningun evento al viaje
                        eventosSucesores = dao.SeleccionarEventosSucesores(0);
                    }
                }

                if (eventosSucesores != null)
                {
                    eventosSucesores = eventosSucesores.OrderBy(t => t.NombreEvento).ToList();
                }
                return(eventosSucesores);
            }

            else
            {
                DataService.AppDataService ds = new DataService.AppDataService(ParametrosSistema.TokenUsuarioActual);
                eventosSucesores = await ds.RealizarPeticionApi <List <TipoEventoLogistico> >("Evento/SeleccionarSiguienteEventoporManifiesto?numeromanifiesto=" + numeroManifiesto.ToString() + "&aplicaTerceros=" + usuarioTipoTercero, DataService.TipoPeticionApi.Get);//.ConfigureAwait(false);
            }
            return(eventosSucesores);
        }