public void addDirections(GoogleDirections directions)
    {
        // loop over steps
        Steps[] steps = directions.routes[0].legs[0].steps;

        for (int stepsIndex = 0; steps.Length > stepsIndex; stepsIndex++)
        {
            print(steps[stepsIndex].end_location.lat);
            createSphere(
                steps[stepsIndex].end_location.lat,
                steps[stepsIndex].end_location.lng,
                sphereCollider.radius,
                this.transform
                );
        }

        // add start
        createSphere(
            directions.routes[0].legs[0].start_location.lat,
            directions.routes[0].legs[0].start_location.lng,
            sphereCollider.radius,
            this.transform
            );

        // add end
        createSphere(
            directions.routes[0].legs[0].end_location.lat,
            directions.routes[0].legs[0].end_location.lng,
            sphereCollider.radius,
            this.transform
            );
    }
Exemplo n.º 2
0
        public virtual ViajeDistribucion UpdateRoute(SosTicket ticket)
        {
            var viaje = ticket.Distribucion ?? DaoFactory.ViajeDistribucionDAO.FindByCodigo(ticket.NumeroServicio);

            //si el servicio fue asignado cancelado, preasignado cancelado o ambos cancelados
            if (ticket.EstadoServicio == SosTicket.EstadosServicio.AsignacionCancelada ||
                ticket.EstadoServicio == SosTicket.EstadosServicio.PreAsignacionCancelada ||
                ticket.EstadoServicio == SosTicket.EstadosServicio.AsignacionYPreAsignacionCancelada)
            {
                viaje.Estado = ViajeDistribucion.Estados.Anulado;
            }

            viaje.Inicio   = ticket.HoraServicio;
            viaje.Vehiculo = DaoFactory.CocheDAO.FindByInterno(new[] { viaje.Empresa.Id }, new[] { -1 }, ticket.Movil.ToString());

            var origen  = viaje.Detalles.FirstOrDefault(e => e.Descripcion.Contains("O"));
            var destino = viaje.Detalles.FirstOrDefault(e => e.Descripcion.Contains("D"));

            origen.Programado      = ticket.HoraServicio;
            origen.ProgramadoHasta = ticket.HoraServicio.AddHours(1);

            var o          = new LatLon(origen.ReferenciaGeografica.Latitude, origen.ReferenciaGeografica.Longitude);
            var d          = new LatLon(destino.ReferenciaGeografica.Latitude, destino.ReferenciaGeografica.Longitude);
            var directions = GoogleDirections.GetDirections(o, d, GoogleDirections.Modes.Driving, string.Empty, null);

            if (directions != null)
            {
                var duracion = directions.Duration;
                destino.Programado      = destino.Programado.Add(duracion);
                destino.ProgramadoHasta = destino.ProgramadoHasta.Add(duracion);
            }

            return(viaje);
        }
Exemplo n.º 3
0
        public void DrawViajeProgramado(int idViajeProgramado)
        {
            Monitor.ClearLayer(LayerViajeProgramado);
            if (idViajeProgramado > 0)
            {
                var viaje = DAOFactory.ViajeProgramadoDAO.FindById(idViajeProgramado);
                if (viaje != null)
                {
                    var count = viaje.Detalles.Count;
                    if (count > 1)
                    {
                        var primero   = viaje.Detalles[0].PuntoEntrega;
                        var ultimo    = viaje.Detalles[count - 1].PuntoEntrega;
                        var origen    = new LatLon(primero.ReferenciaGeografica.Latitude, primero.ReferenciaGeografica.Longitude);
                        var destino   = new LatLon(ultimo.ReferenciaGeografica.Latitude, ultimo.ReferenciaGeografica.Longitude);
                        var waypoints = new List <LatLon>();
                        for (int i = 1; i < count - 1; i++)
                        {
                            var punto    = viaje.Detalles[i].PuntoEntrega;
                            var waypoint = new LatLon(punto.ReferenciaGeografica.Latitude, punto.ReferenciaGeografica.Longitude);
                            waypoints.Add(waypoint);
                        }

                        var directions = GoogleDirections.GetDirections(origen, destino, GoogleDirections.Modes.Driving, string.Empty, waypoints.ToArray());
                        var posiciones = directions.Legs.SelectMany(l => l.Steps.SelectMany(s => s.Points));
                        var line       = new Line("D:" + Color.Red.ToArgb(), StyleFactory.GetLineFromColor(Color.Red, 4, 0.5));
                        line.AddPoints(posiciones.Select(p => new Point("", p.Longitud, p.Latitud)));
                        Monitor.AddGeometries(LayerViajeProgramado, line);
                        Monitor.SetCenter(destino.Latitud, destino.Longitud);
                    }
                }
            }
        }
Exemplo n.º 4
0
 protected override void OnCreate(Bundle savedInstanceState)
 {
     base.OnCreate(savedInstanceState);
     SetContentView(Resource.Layout.Inicio);
     drawer = new Drawer(this);
     core   = new GoogleDirections();
     // Mapa
     _mapFragment = FragmentManager.FindFragmentById <MapFragment>(Resource.Id.mapa_nuevomandado);
     _mapFragment.GetMapAsync(this);
     SetResources();
 }
Exemplo n.º 5
0
        public void Programming(Order order, string routeCode, int idVehicle, DateTime startDateTime, int cycleType, int idVehicleType)
        {
            var viaje = GetViaje(order, routeCode, idVehicle, startDateTime, cycleType, idVehicleType);

            var entrega = new EntregaDistribucion
            {
                Viaje        = viaje,
                Estado       = EntregaDistribucion.Estados.Pendiente,
                Orden        = viaje.Detalles.Count,
                Descripcion  = order.CodigoPedido,
                PuntoEntrega = DaoFactory.PuntoEntregaDAO.FindById(order.PuntoEntrega.Id)
            };

            var ultimo     = viaje.Detalles.Count == 1 ? viaje.Detalles.Last().ReferenciaGeografica : viaje.Detalles[viaje.Detalles.Count - 2].ReferenciaGeografica;
            var origen     = new LatLon(ultimo.Latitude, ultimo.Longitude);
            var destino    = new LatLon(entrega.ReferenciaGeografica.Latitude, entrega.ReferenciaGeografica.Longitude);
            var directions = GoogleDirections.GetDirections(origen, destino, GoogleDirections.Modes.Driving, string.Empty, null);

            if (directions != null)
            {
                var distancia = directions.Distance / 1000.0;
                var duracion  = directions.Duration;
                var fecha     = viaje.Detalles.Last().Programado.Add(duracion);

                entrega.Programado      = fecha;
                entrega.ProgramadoHasta = fecha;
                entrega.KmCalculado     = distancia;
            }

            viaje.Detalles.Add(entrega);
            viaje.AgregarBaseFinal();

            viaje.Fin = viaje.Detalles.Last().ProgramadoHasta;

            DaoFactory.ViajeDistribucionDAO.SaveOrUpdate(viaje);

            foreach (var punto in viaje.Detalles.Where(d => d.PuntoEntrega != null).Select(d => d.PuntoEntrega))
            {
                punto.ReferenciaGeografica.Vigencia.Fin = viaje.Fin.AddMinutes(viaje.Empresa.EndMarginMinutes);
                DaoFactory.PuntoEntregaDAO.SaveOrUpdate(punto);
            }

            var dict           = new Dictionary <int, List <int> >();
            var todaslaslineas = DaoFactory.LineaDAO.GetList(new[] { viaje.Empresa.Id }).Select(l => l.Id).ToList();

            todaslaslineas.Add(-1);
            dict.Add(viaje.Empresa.Id, todaslaslineas);
            DaoFactory.ReferenciaGeograficaDAO.UpdateGeocercas(dict);

            // Si todos los OrdetDetails están ruteados entonces setea la orden en programado
            order.Programado = order.OrderDetails.All(od => od.Estado != OrderDetail.Estados.Pendiente);

            DaoFactory.OrderDAO.SaveOrUpdate(order);
        }
Exemplo n.º 6
0
        private void ShowRecorrido(bool recalcularValores)
        {
            monitor.ClearLayer(LayerRecorrido);
            var count = lstAsignadas.Items.Count;

            if (count > 1)
            {
                var primero   = DAOFactory.PuntoEntregaDAO.FindById(Convert.ToInt32(lstAsignadas.Items[0].Value));
                var ultimo    = DAOFactory.PuntoEntregaDAO.FindById(Convert.ToInt32(lstAsignadas.Items[count - 1].Value));
                var origen    = new LatLon(primero.ReferenciaGeografica.Latitude, primero.ReferenciaGeografica.Longitude);
                var destino   = new LatLon(ultimo.ReferenciaGeografica.Latitude, ultimo.ReferenciaGeografica.Longitude);
                var waypoints = new List <LatLon>();
                for (int i = 1; i < count - 1; i++)
                {
                    var punto    = DAOFactory.PuntoEntregaDAO.FindById(Convert.ToInt32(lstAsignadas.Items[i].Value));
                    var waypoint = new LatLon(punto.ReferenciaGeografica.Latitude, punto.ReferenciaGeografica.Longitude);
                    waypoints.Add(waypoint);
                }

                var directions = GoogleDirections.GetDirections(origen, destino, GoogleDirections.Modes.Driving, string.Empty, waypoints.ToArray());
                var posiciones = directions.Legs.SelectMany(l => l.Steps.SelectMany(s => s.Points));
                var line       = new Line("D:" + Color.Red.ToArgb(), StyleFactory.GetLineFromColor(Color.Red, 4, 0.5));
                line.AddPoints(posiciones.Select(p => new Point("", p.Longitud, p.Latitud)));

                Points.Set(posiciones.Select(p => new PointF((float)p.Longitud, (float)p.Latitud)).ToList());

                monitor.AddGeometries(LayerRecorrido, line);

                if (recalcularValores)
                {
                    var ts = directions.Duration;
                    txtHoras.Text = ((int)Math.Truncate(ts.TotalHours)).ToString("00") + ":" + ((int)(ts.Minutes)).ToString("00") + ":" + ((int)(ts.Seconds)).ToString("00");
                    txtKm.Text    = (directions.Distance / 1000.00).ToString("#0.00");
                }
            }
            else
            {
                if (recalcularValores)
                {
                    txtHoras.Text = "00:00:00";
                    txtKm.Text    = "0.00";
                }
            }
        }
Exemplo n.º 7
0
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        GoogleMarkers GoogleMarker = new GoogleMarkers();

        GoogleMarker.DataLatitudeField = "45.17654";
        GoogleMarker.DataLongitudeField = "14.4967";
        GoogleMarker.TargetControlID = "GoogleMap1";

        GoogleDirections gDirections = new GoogleDirections();
        LatLng gLatLngDestination = new LatLng();
        gLatLngDestination.Latitude = 45.17654;
        gLatLngDestination.Longitude = 14.4967;

        LatLng gLatLngOrigin = new LatLng();
        gLatLngOrigin.Latitude = 46.17654;
        gLatLngOrigin.Longitude = 14.4967;
    }
Exemplo n.º 8
0
        private Intercalado CalcularDirectionsOriginal(Intercalado intercalado)
        {
            var viaje      = Viajes.FirstOrDefault(v => v.Id == intercalado.Id);
            var first      = viaje.Detalles.First().ReferenciaGeografica;
            var last       = viaje.Detalles.Last().ReferenciaGeografica;
            var origen     = new LatLon(first.Latitude, first.Longitude);
            var destino    = new LatLon(last.Latitude, last.Longitude);
            var waypoints  = viaje.Detalles.Skip(1).Take(viaje.Detalles.Count - 2).Select(w => new LatLon(w.ReferenciaGeografica.Latitude, w.ReferenciaGeografica.Longitude)).ToList();
            var directions = GoogleDirections.GetDirections(origen, destino, GoogleDirections.Modes.Driving,
                                                            string.Empty, waypoints.ToArray());

            intercalado.ViajeAnterior = directions;
            if (directions != null)
            {
                intercalado.CostoKmOld = directions.Distance;
            }
            var duracionAnterior = viaje.Detalles.Last().Programado.Subtract(viaje.Detalles.First().Programado);

            intercalado.CostoMinOld = duracionAnterior.TotalMinutes;

            return(intercalado);
        }
Exemplo n.º 9
0
        public virtual void AgregarBaseFinal()
        {
            for (var i = 1; i < Detalles.Count; i++)
            {
                if (Detalles[i].Descripcion.Equals(Detalles[0].Descripcion))
                {
                    Detalles.RemoveAt(i);
                }
            }

            var baseFinal = new EntregaDistribucion()
            {
                Linea       = Detalles[0].Linea,
                Descripcion = Detalles[0].Descripcion,
                Estado      = EntregaDistribucion.Estados.Pendiente,
                Orden       = Detalles.Count,
                Viaje       = Detalles[0].Viaje
            };

            var ultimo     = Detalles.Last().ReferenciaGeografica;
            var origen     = new LatLon(ultimo.Latitude, ultimo.Longitude);
            var destino    = new LatLon(baseFinal.ReferenciaGeografica.Latitude, baseFinal.ReferenciaGeografica.Longitude);
            var directions = GoogleDirections.GetDirections(origen, destino, GoogleDirections.Modes.Driving, string.Empty, null);

            if (directions != null)
            {
                var distancia = directions.Distance / 1000.0;
                var duracion  = directions.Duration;
                var fecha     = Detalles.Last().Programado.Add(duracion);

                baseFinal.Programado      = fecha;
                baseFinal.ProgramadoHasta = fecha;
                baseFinal.KmCalculado     = distancia;
            }

            Detalles.Add(baseFinal);
        }
    IEnumerator GetText()
    {
        UnityWebRequest www = UnityWebRequest.Get(
            api +
            "?key=" + apiKey.text +
            "&origin=" + origin +
            "&destination=" + destination
            );

        yield return(www.SendWebRequest());

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            // parse the data
            GoogleDirections directions = JsonUtility.FromJson <GoogleDirections>(www.downloadHandler.text);

            // call listeners
            OnDirectionsLoaded.Invoke(directions);
        }
    }
Exemplo n.º 11
0
        public static void SetRoutes(Xamarin.Forms.GoogleMaps.Map map, GoogleDirections googleDirections)
        {
            if (googleDirections.routes.Count > 0)
            {
                string encodedPoints = googleDirections.routes[0].overview_polyline.points;

                var lstDecodedPoints = GetPolylinePoints(encodedPoints);
                var latLngPoints     = new Position[lstDecodedPoints.Count];
                int index            = 0;

                var polylineoption = new Xamarin.Forms.GoogleMaps.Polyline();
                polylineoption.StrokeColor = Xamarin.Forms.Color.Red;

                foreach (Location loc in lstDecodedPoints)
                {
                    latLngPoints[index++] = new Position(loc.Latitude, loc.Longitude);
                    polylineoption.Positions.Add(new Position(loc.Latitude, loc.Longitude));
                }

                map.Polylines.Add(polylineoption);

                UpdateCamera(map, latLngPoints[0]);
            }
        }
Exemplo n.º 12
0
        public XmlDocument ObtenerEstadoEntrega(String Distrito, String Base, String Entrega, String Cliente)
        {
            var address = HttpContext.Current.Request.UserHostAddress;

            try
            {
                using (StreamWriter sw = File.AppendText(Directory.GetCurrentDirectory() + @"\LOGIP.txt"))
                {
                    sw.WriteLine(address.ToString() + "\t" + DateTime.Now.ToString("ddMMyyyyHHmmssfff"));
                }
            }
            catch (Exception)
            {
            }

            if (!String.IsNullOrEmpty(Distrito) &&
                !String.IsNullOrEmpty(Base) &&
                (!String.IsNullOrEmpty(Entrega) ||
                 !String.IsNullOrEmpty(Cliente)))
            {
                var EstadoActual            = "";
                var TiempoLlegada           = "";
                var DistanciakmtsLlegada    = "";
                var linkGoogleMaps          = "https://www.google.com.ar/maps/dir/-34.598198,-58.3841437/-34.5972089,-58.3780497";
                ViajeDistribucionDAO dao    = new ViajeDistribucionDAO();
                LogPosicionDAO       daopos = new LogPosicionDAO();
                var sinbase = dao.FindAll().Where(x => x.Inicio.Day.Equals(DateTime.Now.Day) &&
                                                  x.Inicio.Month.Equals(DateTime.Now.Month) &&
                                                  x.Inicio.Year.Equals(DateTime.Now.Year) && x.Empresa.RazonSocial.ToString().Trim().ToUpper().Contains(Distrito.Trim().ToUpper()));
                if (!String.IsNullOrEmpty(Base))
                {
                    sinbase = sinbase.Where(x => x.Linea == null ||
                                            x.Linea != null &&
                                            x.Linea.Descripcion.ToString().Trim().ToUpper().Contains(Base.Trim().ToUpper()));
                }
                bool closeLoop = false;
                foreach (var item in sinbase)
                {
                    foreach (EntregaDistribucion detalle in item.Detalles.Where(x => x.PuntoEntrega != null))
                    {
                        //codigo = entrega
                        //descripcion cliente
                        if (detalle.PuntoEntrega.Codigo.Trim().ToUpper().Equals(Entrega.Trim().ToUpper()) ||
                            detalle.PuntoEntrega.Descripcion.Trim().ToUpper().Equals(Cliente.Trim().ToUpper()))
                        {
                            switch (detalle.Estado)
                            {
                            case EntregaDistribucion.Estados.EnSitio:
                            {
                                EstadoActual = "EnSitio";
                                break;
                            }

                            case EntregaDistribucion.Estados.Completado:
                            {
                                EstadoActual = "Completado";
                                break;
                            }

                            case EntregaDistribucion.Estados.Cancelado:
                            {
                                EstadoActual = "Cancelado";
                                break;
                            }

                            case EntregaDistribucion.Estados.EnZona:
                            {
                                EstadoActual = "EnZona";
                                break;
                            }

                            case EntregaDistribucion.Estados.NoCompletado:
                            {
                                EstadoActual = "NoCompletado";
                                break;
                            }

                            case EntregaDistribucion.Estados.Pendiente:
                            {
                                EstadoActual = "Pendiente";
                                break;
                            }

                            case EntregaDistribucion.Estados.Restaurado:
                            {
                                EstadoActual = "Restaurado";
                                break;
                            }

                            case EntregaDistribucion.Estados.SinVisitar:
                            {
                                EstadoActual = "SinVisitar";
                                break;
                            }

                            case EntregaDistribucion.Estados.Visitado:
                            {
                                EstadoActual = "Visitado";
                                break;
                            }

                            default:
                                break;
                            }

                            LogUltimaPosicionVo ult = daopos.GetLastVehiclePosition(item.Vehiculo);
                            if (ult == null)
                            {
                                ult = daopos.GetLastOnlineVehiclePosition(item.Vehiculo);
                            }
                            LatLon origen  = new LatLon(ult.Latitud, ult.Longitud);
                            LatLon destino = new LatLon(detalle.PuntoEntrega.ReferenciaGeografica.Latitude, detalle.PuntoEntrega.ReferenciaGeografica.Longitude);

                            linkGoogleMaps = "https://www.google.com.ar/maps/dir/" + origen.Latitud.ToString().Replace(',', '.') + "," + origen.Longitud.ToString().Replace(',', '.') + "/" + destino.Latitud.ToString().Replace(',', '.') + "," + destino.Longitud.ToString().Replace(',', '.');

                            var waypoints = new List <LatLon>();
                            waypoints.Add(origen);
                            waypoints.Add(destino);
                            var directions = GoogleDirections.GetDirections(origen, destino, GoogleDirections.Modes.Driving, string.Empty, waypoints.ToArray());
                            int reintentos = 0;
                            while (directions == null && reintentos < 4)
                            {
                                reintentos++;
                                Thread.Sleep(2000);
                                directions = GoogleDirections.GetDirections(origen, destino, GoogleDirections.Modes.Driving, string.Empty, waypoints.ToArray());
                            }
                            if (directions != null)
                            {
                                TiempoLlegada        = new DateTime(directions.Duration.Ticks).ToString("HH:mm:ss");
                                DistanciakmtsLlegada = (directions.Distance / 1000).ToString();
                            }
                            closeLoop = true;
                            break;
                        }
                    }
                    if (closeLoop)
                    {
                        break;
                    }
                }
                XmlDocument    doc            = new XmlDocument();
                XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
                XmlElement     root           = doc.DocumentElement;
                doc.InsertBefore(xmlDeclaration, root);

                //(2) string.Empty makes cleaner code
                XmlElement element1 = doc.CreateElement(string.Empty, "body", string.Empty);
                doc.AppendChild(element1);

                XmlElement element2 = doc.CreateElement(string.Empty, "EstadoActual", string.Empty);
                XmlText    text1    = doc.CreateTextNode(EstadoActual);
                element2.AppendChild(text1);
                element1.AppendChild(element2);

                XmlElement element3 = doc.CreateElement(string.Empty, "TiempoLlegadaHHMMSS", string.Empty);
                XmlText    text2    = doc.CreateTextNode(TiempoLlegada);
                element3.AppendChild(text2);
                element1.AppendChild(element3);

                XmlElement element4 = doc.CreateElement(string.Empty, "DistanciakmtsLlegada", string.Empty);
                XmlText    text3    = doc.CreateTextNode(DistanciakmtsLlegada);
                element4.AppendChild(text3);
                element1.AppendChild(element4);

                XmlElement element5 = doc.CreateElement(string.Empty, "linkGoogleMaps", string.Empty);
                XmlText    text4    = doc.CreateTextNode(linkGoogleMaps);
                element5.AppendChild(text4);
                element1.AppendChild(element5);

                return(doc);
            }
            else
            {
                return(new XmlDocument());
            }
        }
Exemplo n.º 13
0
        public ViajeDistribucion Parse(out int rutas, out int entregas)
        {
            const int vigencia = 12;

            var te   = new TimeElapsed();
            var rows = ParseFile(Llfile.FilePath).Rows;

            STrace.Trace(Component, string.Format("Archivo parseado en {0} segundos", te.getTimeElapsed().TotalSeconds));

            var listPuntos      = new List <PuntoEntrega>();
            var listReferencias = new List <ReferenciaGeografica>();

            rutas    = 0;
            entregas = 0;

            var sLinea   = rows[Properties.DistribucionSos.Base][0].ToString().Replace("\t", string.Empty).Split(':')[1];
            var sFecha   = rows[Properties.DistribucionSos.Fecha][0].ToString().Replace("\t", string.Empty).Split(':');
            var sHora    = rows[Properties.DistribucionSos.HoraProgramada][0].ToString().Replace("\t", string.Empty).Split(':');
            var sEntrega = rows[Properties.DistribucionSos.Entrega][0].ToString().Replace("\t", string.Empty).Split(':')[1];
            var sPatente = rows[Properties.DistribucionSos.Patente][0].ToString().Replace("\t", string.Empty).Split(':')[1];
            var sLatO    = rows[Properties.DistribucionSos.LatitudOrigen][0].ToString().Replace("\t", string.Empty).Split(':')[1];
            var sLonO    = rows[Properties.DistribucionSos.LongitudOrigen][0].ToString().Replace("\t", string.Empty).Split(':')[1];
            var sLatD    = rows[Properties.DistribucionSos.LatitudDestino][0].ToString().Replace("\t", string.Empty).Split(':')[1];
            var sLonD    = rows[Properties.DistribucionSos.LongitudDestino][0].ToString().Replace("\t", string.Empty).Split(':')[1];

            if (string.IsNullOrEmpty(sEntrega))
            {
                ThrowProperty("CODIGO ENTREGA", Llfile.Strategy);
            }
            if (string.IsNullOrEmpty(sPatente))
            {
                ThrowProperty("PATENTE", Llfile.Strategy);
            }

            var linea = DaoFactory.LineaDAO.FindByCodigo(Empresa.Id, sLinea);

            if (linea == null)
            {
                ThrowProperty("BASE", Llfile.Strategy);
            }

            var viaje = DaoFactory.ViajeDistribucionDAO.FindByCodigo(Empresa.Id, linea.Id, sEntrega);

            if (viaje != null)
            {
                return(viaje);
            }

            var dia   = Convert.ToInt32(sFecha[1].Substring(0, 2));
            var mes   = Convert.ToInt32(sFecha[1].Substring(3, 2));
            var anio  = Convert.ToInt32(sFecha[1].Substring(6, 4));
            var hora  = Convert.ToInt32(sHora[1]);
            var min   = Convert.ToInt32(sHora[2]);
            var seg   = Convert.ToInt32(sHora[3]);
            var gmt   = new TimeSpan(-3, 0, 0);
            var fecha = new DateTime(anio, mes, dia, hora, min, seg).Subtract(gmt);

            var vehiculo = DaoFactory.CocheDAO.FindByPatente(Empresa.Id, sPatente);

            if (vehiculo == null)
            {
                ThrowProperty("VEHICULO", Llfile.Strategy);
            }

            viaje = new ViajeDistribucion
            {
                Inicio       = fecha,
                Codigo       = sEntrega,
                Empresa      = Empresa,
                Linea        = linea,
                Vehiculo     = vehiculo,
                Tipo         = ViajeDistribucion.Tipos.Desordenado,
                Alta         = DateTime.UtcNow,
                RegresoABase = false,
                Estado       = ViajeDistribucion.Estados.Pendiente
            };

            rutas++;

            var origen = new EntregaDistribucion
            {
                Linea           = linea,
                Descripcion     = linea.Descripcion,
                Estado          = EntregaDistribucion.Estados.Pendiente,
                Orden           = 0,
                Programado      = fecha,
                ProgramadoHasta = fecha,
                Viaje           = viaje
            };

            viaje.Detalles.Add(origen);

            var nombreOrigen  = sEntrega + " - O";
            var nombreDestino = sEntrega + " - D";

            TipoServicioCiclo tipoServicio = null;
            var tipoServ = DaoFactory.TipoServicioCicloDAO.FindDefault(new[] { Empresa.Id }, new[] { linea.Id });

            if (tipoServ != null && tipoServ.Id > 0)
            {
                tipoServicio = tipoServ;
            }

            sLatO = sLatO.Replace(',', '.');
            sLonO = sLonO.Replace(',', '.');
            var latO = Convert.ToDouble(sLatO, CultureInfo.InvariantCulture);
            var lonO = Convert.ToDouble(sLonO, CultureInfo.InvariantCulture);

            ValidateGpsPoint(nombreOrigen, nombreOrigen, (float)latO, (float)lonO);

            sLatD = sLatD.Replace(',', '.');
            sLonD = sLonD.Replace(',', '.');
            var latD = Convert.ToDouble(sLatD, CultureInfo.InvariantCulture);
            var lonD = Convert.ToDouble(sLonD, CultureInfo.InvariantCulture);

            ValidateGpsPoint(nombreOrigen, nombreOrigen, (float)latD, (float)lonD);

            #region Origen

            var puntoEntregaO = DaoFactory.PuntoEntregaDAO.FindByCode(new[] { Empresa.Id },
                                                                      new[] { linea.Id },
                                                                      new[] { Cliente.Id },
                                                                      nombreOrigen);

            if (puntoEntregaO == null)
            {
                var empresaGeoRef = Empresa;
                var lineaGeoRef   = linea;

                var puntoDeInteres = new ReferenciaGeografica
                {
                    Codigo                   = nombreOrigen,
                    Descripcion              = nombreOrigen,
                    Empresa                  = empresaGeoRef,
                    Linea                    = lineaGeoRef,
                    EsFin                    = Cliente.ReferenciaGeografica.TipoReferenciaGeografica.EsFin,
                    EsInicio                 = Cliente.ReferenciaGeografica.TipoReferenciaGeografica.EsInicio,
                    EsIntermedio             = Cliente.ReferenciaGeografica.TipoReferenciaGeografica.EsIntermedio,
                    InhibeAlarma             = Cliente.ReferenciaGeografica.TipoReferenciaGeografica.InhibeAlarma,
                    TipoReferenciaGeografica = Cliente.ReferenciaGeografica.TipoReferenciaGeografica,
                    Vigencia                 = new Vigencia {
                        Inicio = DateTime.UtcNow, Fin = fecha.AddHours(vigencia)
                    },
                    Icono = Cliente.ReferenciaGeografica.TipoReferenciaGeografica.Icono
                };

                var posicion = GetNewDireccion(latO, lonO);

                var poligono = new Poligono {
                    Radio = 50, Vigencia = new Vigencia {
                        Inicio = DateTime.UtcNow
                    }
                };
                poligono.AddPoints(new[] { new PointF((float)lonO, (float)latO) });

                puntoDeInteres.Historia.Add(new HistoriaGeoRef
                {
                    ReferenciaGeografica = puntoDeInteres,
                    Direccion            = posicion,
                    Poligono             = poligono,
                    Vigencia             = new Vigencia {
                        Inicio = DateTime.UtcNow
                    }
                });

                listReferencias.Add(puntoDeInteres);

                puntoEntregaO = new PuntoEntrega
                {
                    Cliente              = Cliente,
                    Codigo               = nombreOrigen,
                    Descripcion          = nombreOrigen,
                    Telefono             = string.Empty,
                    Baja                 = false,
                    ReferenciaGeografica = puntoDeInteres,
                    Nomenclado           = true,
                    DireccionNomenclada  = string.Empty,
                    Nombre               = nombreOrigen
                };
            }
            else
            {
                if (!puntoEntregaO.ReferenciaGeografica.IgnoraLogiclink && (puntoEntregaO.ReferenciaGeografica.Latitude != latO || puntoEntregaO.ReferenciaGeografica.Longitude != lonO))
                {
                    puntoEntregaO.ReferenciaGeografica.Direccion.Vigencia.Fin = DateTime.UtcNow;
                    puntoEntregaO.ReferenciaGeografica.Poligono.Vigencia.Fin  = DateTime.UtcNow;

                    var posicion = GetNewDireccion(latO, lonO);
                    var poligono = new Poligono {
                        Radio = 50, Vigencia = new Vigencia {
                            Inicio = DateTime.UtcNow
                        }
                    };
                    poligono.AddPoints(new[] { new PointF((float)lonO, (float)latO) });

                    puntoEntregaO.ReferenciaGeografica.AddHistoria(posicion, poligono, DateTime.UtcNow);
                }

                var end = fecha.AddHours(vigencia);
                if (puntoEntregaO.ReferenciaGeografica.Vigencia.Fin < end)
                {
                    puntoEntregaO.ReferenciaGeografica.Vigencia.Fin = end;
                }

                listReferencias.Add(puntoEntregaO.ReferenciaGeografica);
            }

            listPuntos.Add(puntoEntregaO);

            var entregaO = new EntregaDistribucion
            {
                Cliente         = Cliente,
                PuntoEntrega    = puntoEntregaO,
                Descripcion     = nombreOrigen,
                Estado          = EntregaDistribucion.Estados.Pendiente,
                Orden           = viaje.Detalles.Count,
                Programado      = fecha,
                ProgramadoHasta = fecha,
                TipoServicio    = tipoServicio,
                Viaje           = viaje
            };

            viaje.Detalles.Add(entregaO);
            entregas++;

            #endregion

            #region Destino

            var puntoEntregaD = DaoFactory.PuntoEntregaDAO.FindByCode(new[] { Empresa.Id },
                                                                      new[] { linea.Id },
                                                                      new[] { Cliente.Id },
                                                                      nombreDestino);

            if (puntoEntregaD == null)
            {
                var empresaGeoRef = Empresa;
                var lineaGeoRef   = linea;

                var puntoDeInteres = new ReferenciaGeografica
                {
                    Codigo                   = nombreDestino,
                    Descripcion              = nombreDestino,
                    Empresa                  = empresaGeoRef,
                    Linea                    = lineaGeoRef,
                    EsFin                    = Cliente.ReferenciaGeografica.TipoReferenciaGeografica.EsFin,
                    EsInicio                 = Cliente.ReferenciaGeografica.TipoReferenciaGeografica.EsInicio,
                    EsIntermedio             = Cliente.ReferenciaGeografica.TipoReferenciaGeografica.EsIntermedio,
                    InhibeAlarma             = Cliente.ReferenciaGeografica.TipoReferenciaGeografica.InhibeAlarma,
                    TipoReferenciaGeografica = Cliente.ReferenciaGeografica.TipoReferenciaGeografica,
                    Vigencia                 = new Vigencia {
                        Inicio = DateTime.UtcNow, Fin = fecha.AddHours(vigencia)
                    },
                    Icono = Cliente.ReferenciaGeografica.TipoReferenciaGeografica.Icono
                };

                var posicion = GetNewDireccion(latD, lonD);

                var poligono = new Poligono {
                    Radio = 50, Vigencia = new Vigencia {
                        Inicio = DateTime.UtcNow
                    }
                };
                poligono.AddPoints(new[] { new PointF((float)lonD, (float)latD) });

                puntoDeInteres.Historia.Add(new HistoriaGeoRef
                {
                    ReferenciaGeografica = puntoDeInteres,
                    Direccion            = posicion,
                    Poligono             = poligono,
                    Vigencia             = new Vigencia {
                        Inicio = DateTime.UtcNow
                    }
                });

                listReferencias.Add(puntoDeInteres);

                puntoEntregaD = new PuntoEntrega
                {
                    Cliente              = Cliente,
                    Codigo               = nombreDestino,
                    Descripcion          = nombreDestino,
                    Telefono             = string.Empty,
                    Baja                 = false,
                    ReferenciaGeografica = puntoDeInteres,
                    Nomenclado           = true,
                    DireccionNomenclada  = string.Empty,
                    Nombre               = nombreDestino
                };
            }
            else
            {
                if (!puntoEntregaD.ReferenciaGeografica.IgnoraLogiclink && (puntoEntregaD.ReferenciaGeografica.Latitude != latD || puntoEntregaD.ReferenciaGeografica.Longitude != lonD))
                {
                    puntoEntregaD.ReferenciaGeografica.Direccion.Vigencia.Fin = DateTime.UtcNow;
                    puntoEntregaD.ReferenciaGeografica.Poligono.Vigencia.Fin  = DateTime.UtcNow;

                    var posicion = GetNewDireccion(latD, lonD);
                    var poligono = new Poligono {
                        Radio = 50, Vigencia = new Vigencia {
                            Inicio = DateTime.UtcNow
                        }
                    };
                    poligono.AddPoints(new[] { new PointF((float)lonD, (float)latD) });

                    puntoEntregaD.ReferenciaGeografica.AddHistoria(posicion, poligono, DateTime.UtcNow);
                }

                var end = fecha.AddHours(vigencia);
                if (puntoEntregaD.ReferenciaGeografica.Vigencia.Fin < end)
                {
                    puntoEntregaD.ReferenciaGeografica.Vigencia.Fin = end;
                }

                listReferencias.Add(puntoEntregaD.ReferenciaGeografica);
            }

            listPuntos.Add(puntoEntregaD);

            var anterior   = puntoEntregaO.ReferenciaGeografica;
            var siguiente  = puntoEntregaD.ReferenciaGeografica;
            var o          = new LatLon(anterior.Latitude, anterior.Longitude);
            var d          = new LatLon(siguiente.Latitude, siguiente.Longitude);
            var directions = GoogleDirections.GetDirections(o, d, GoogleDirections.Modes.Driving, string.Empty, null);

            if (directions != null)
            {
                var duracion = directions.Duration;
                fecha = entregaO.Programado.Add(duracion);
            }

            var entregaD = new EntregaDistribucion
            {
                Cliente         = Cliente,
                PuntoEntrega    = puntoEntregaD,
                Descripcion     = nombreDestino,
                Estado          = EntregaDistribucion.Estados.Pendiente,
                Orden           = viaje.Detalles.Count,
                Programado      = fecha,
                ProgramadoHasta = fecha,
                TipoServicio    = tipoServicio,
                Viaje           = viaje
            };

            viaje.Detalles.Add(entregaD);
            entregas++;

            viaje.Fin = fecha;

            #endregion

            STrace.Trace(Component, "Guardando referencias geográficas: " + listReferencias.Count);
            te.Restart();
            foreach (var referenciaGeografica in listReferencias)
            {
                DaoFactory.ReferenciaGeograficaDAO.Guardar(referenciaGeografica);
            }
            STrace.Trace(Component, string.Format("Referencias guardadas en {0} segundos", te.getTimeElapsed().TotalSeconds));

            STrace.Trace(Component, "Guardando puntos de entrega: " + listPuntos.Count);
            te.Restart();
            foreach (var puntoEntrega in listPuntos)
            {
                DaoFactory.PuntoEntregaDAO.SaveOrUpdate(puntoEntrega);
            }
            STrace.Trace(Component, string.Format("Puntos guardados en {0} segundos", te.getTimeElapsed().TotalSeconds));

            STrace.Trace(Component, "Guardando Viaje");
            te.Restart();
            DaoFactory.ViajeDistribucionDAO.SaveOrUpdate(viaje);
            STrace.Trace(Component, string.Format("Viaje guardado en {0} segundos", te.getTimeElapsed().TotalSeconds));

            return(viaje);
        }
Exemplo n.º 14
0
        public override object Parse(int empresa, int linea, IData data)
        {
            var oEmpresa = DaoFactory.EmpresaDAO.FindById(empresa);

            var patente  = data.AsString(Properties.Distribution.Coche, 32).Trim();
            var vehiculo = patente != string.Empty ? DaoFactory.CocheDAO.FindByPatente(empresa, patente) : null;

            var oLinea = vehiculo != null && vehiculo.Linea != null ? vehiculo.Linea : DaoFactory.LineaDAO.FindById(linea);

            if (oLinea == null)
            {
                ThrowProperty("LINEA");
            }
            var oCliente = DaoFactory.ClienteDAO.GetList(new[] { empresa }, new[] { -1 }).FirstOrDefault();

            if (oCliente == null)
            {
                ThrowProperty("CLIENTE");
            }
            const int vigencia = 12;

            var sFecha = data.AsString(Properties.Distribution.Fecha, 6).Trim();
            var codigo = sFecha + data.AsString(Properties.Distribution.Codigo, 8).Trim();
            var item   = GetDistribucion(empresa, oLinea.Id, codigo);

            if (data.Operation == (int)Operation.Delete)
            {
                return(item);
            }

            var sHora = data.AsString(Properties.Distribution.Horario, 4).Trim();

            if (sHora.Length == 3)
            {
                sHora = "0" + sHora;
            }
            else if (sHora.Length != 4)
            {
                ThrowProperty("HORARIO");
            }

            var latitud  = data.AsString(Properties.Distribution.Latitud, 10).Trim();
            var longitud = data.AsString(Properties.Distribution.Longitud, 10).Trim();
            var esBase   = latitud.Trim().Equals(string.Empty) && longitud.Trim().Equals(string.Empty);
            //var orden = data.AsString(Properties.Distribution.Orden, 2).Trim();
            // HACE FALTA AGREGAR EL CAMPO AL MAPEO

            var dia   = Convert.ToInt32(sFecha.Substring(0, 2));
            var mes   = Convert.ToInt32(sFecha.Substring(2, 2));
            var anio  = Convert.ToInt32(sFecha.Substring(4, 2)) + 2000;
            var hora  = Convert.ToInt32(sHora.Substring(0, 2));
            var min   = Convert.ToInt32(sHora.Substring(2, 2));
            var gmt   = new TimeSpan(-3, 0, 0);
            var fecha = new DateTime(anio, mes, dia, hora, min, 0).Subtract(gmt);

            if (item.Id == 0)
            {
                item.Empresa              = oEmpresa;
                item.Linea                = oLinea;
                item.Vehiculo             = vehiculo;
                item.Inicio               = fecha;
                item.Fin                  = fecha;
                item.Tipo                 = ViajeDistribucion.Tipos.Desordenado;
                item.RegresoABase         = true;
                item.Estado               = ViajeDistribucion.Estados.Pendiente;
                item.Alta                 = DateTime.UtcNow;
                item.ProgramacionDinamica = codigo.Contains("TR");

                var nroViaje = data.AsString(Properties.Distribution.NroViaje, 1).Trim();
                item.NumeroViaje = Convert.ToInt32(nroViaje);

                if (patente != string.Empty)
                {
                    if (vehiculo != null)
                    {
                        item.Empleado          = !vehiculo.IdentificaChoferes ? vehiculo.Chofer : null;
                        item.CentroDeCostos    = vehiculo.CentroDeCostos;
                        item.SubCentroDeCostos = vehiculo.SubCentroDeCostos;
                    }
                    else
                    {
                        STrace.Error("Logiclink", string.Format("Patente {0} no encontrada para el viaje: {1}", patente, codigo));
                    }
                }
                else
                {
                    STrace.Error("Logiclink", "Patente vacía para el viaje: " + codigo);
                }
            }
            else
            {
                if (fecha < item.Inicio)
                {
                    item.Inicio = fecha;
                }
            }

            var km       = data.AsString(Properties.Distribution.Km, 32).Trim();
            var distance = Convert.ToDouble(km, CultureInfo.InvariantCulture);

            if (esBase)
            {
                if (codigo.Contains("TR"))
                {
                    var ultimo     = item.Detalles.Last().ReferenciaGeografica;
                    var origen     = new LatLon(ultimo.Latitude, ultimo.Longitude);
                    var destino    = new LatLon(oLinea.ReferenciaGeografica.Latitude, oLinea.ReferenciaGeografica.Longitude);
                    var directions = GoogleDirections.GetDirections(origen, destino, GoogleDirections.Modes.Driving, string.Empty, null);

                    if (directions != null)
                    {
                        distance = directions.Distance / 1000.0;
                        var duracion = directions.Duration;
                        fecha = item.Detalles.Last().Programado.Add(duracion);
                    }
                }

                var llegada = new EntregaDistribucion
                {
                    Linea           = oLinea,
                    Descripcion     = oLinea.Descripcion,
                    Estado          = EntregaDistribucion.Estados.Pendiente,
                    Orden           = item.Detalles.Count,
                    Programado      = fecha,
                    ProgramadoHasta = fecha,
                    Viaje           = item,
                    KmCalculado     = distance
                };
                item.Detalles.Add(llegada);

                return(item);
            }

            // Entregas
            if (item.Detalles.Count == 0)
            {
                //Si no existe, agrego la salida de base
                var origen = new EntregaDistribucion
                {
                    Linea           = oLinea,
                    Descripcion     = oLinea.Descripcion,
                    Estado          = EntregaDistribucion.Estados.Pendiente,
                    Orden           = 0,
                    Programado      = fecha,
                    ProgramadoHasta = fecha,
                    Viaje           = item
                };
                item.Detalles.Add(origen);
            }

            var codigoPuntoEntrega = data.AsString(Properties.Distribution.PuntoEntrega, 16).Trim();
            var nombre             = data.AsString(Properties.Distribution.Nombre, 32).Trim();

            if (string.IsNullOrEmpty(codigoPuntoEntrega))
            {
                ThrowProperty("PuntoEntrega");
            }

            if (item.Detalles.Any(d => d.PuntoEntrega != null && d.PuntoEntrega.Codigo == codigoPuntoEntrega))
            {
                return(item);
            }

            TipoServicioCiclo tipoServicio = null;
            var tipoServ = DaoFactory.TipoServicioCicloDAO.FindDefault(new[] { empresa }, new[] { oLinea.Id });

            if (tipoServ != null && tipoServ.Id > 0)
            {
                tipoServicio = tipoServ;
            }

            latitud  = latitud.Replace(',', '.');
            longitud = longitud.Replace(',', '.');
            var lat = Convert.ToDouble(latitud, CultureInfo.InvariantCulture);
            var lon = Convert.ToDouble(longitud, CultureInfo.InvariantCulture);

            ValidateGpsPoint(codigo, codigoPuntoEntrega, (float)lat, (float)lon);

            var puntoEntrega = DaoFactory.PuntoEntregaDAO.GetByCode(new[] { empresa }, new[] { oLinea.Id }, new[] { oCliente.Id }, codigoPuntoEntrega);

            if (puntoEntrega == null)
            {
                var empresaGeoRef = item.Vehiculo != null && item.Vehiculo.Empresa == null ? null : oCliente.Empresa == null ? null : oEmpresa;
                var lineaGeoRef   = item.Vehiculo != null && item.Vehiculo.Linea == null ? null : oCliente.Linea == null ? null : oLinea;

                var puntoDeInteres = new ReferenciaGeografica
                {
                    Codigo                   = codigoPuntoEntrega,
                    Descripcion              = nombre,
                    Empresa                  = empresaGeoRef,
                    Linea                    = lineaGeoRef,
                    EsFin                    = oCliente.ReferenciaGeografica.TipoReferenciaGeografica.EsFin,
                    EsInicio                 = oCliente.ReferenciaGeografica.TipoReferenciaGeografica.EsInicio,
                    EsIntermedio             = oCliente.ReferenciaGeografica.TipoReferenciaGeografica.EsIntermedio,
                    InhibeAlarma             = oCliente.ReferenciaGeografica.TipoReferenciaGeografica.InhibeAlarma,
                    TipoReferenciaGeografica = oCliente.ReferenciaGeografica.TipoReferenciaGeografica,
                    Vigencia                 = new Vigencia {
                        Inicio = DateTime.UtcNow, Fin = fecha.AddHours(vigencia)
                    },
                    Icono = oCliente.ReferenciaGeografica.TipoReferenciaGeografica.Icono
                };

                var posicion = GetNewDireccion(lat, lon);

                var poligono = new Poligono {
                    Radio = 50, Vigencia = new Vigencia {
                        Inicio = DateTime.UtcNow
                    }
                };
                poligono.AddPoints(new[] { new PointF((float)lon, (float)lat) });

                puntoDeInteres.Historia.Add(new HistoriaGeoRef
                {
                    ReferenciaGeografica = puntoDeInteres,
                    Direccion            = posicion,
                    Poligono             = poligono,
                    Vigencia             = new Vigencia {
                        Inicio = DateTime.UtcNow
                    }
                });

                DaoFactory.ReferenciaGeograficaDAO.SingleSaveOrUpdate(puntoDeInteres);
                STrace.Trace("QtreeReset", "DistribucionV1 1");

                puntoEntrega = new PuntoEntrega
                {
                    Cliente              = oCliente,
                    Codigo               = codigoPuntoEntrega,
                    Descripcion          = nombre,
                    Telefono             = string.Empty,
                    Baja                 = false,
                    ReferenciaGeografica = puntoDeInteres,
                    Nomenclado           = true,
                    DireccionNomenclada  = string.Empty,
                    Nombre               = nombre
                };
            }
            else
            {
                if (!puntoEntrega.ReferenciaGeografica.IgnoraLogiclink && (puntoEntrega.ReferenciaGeografica.Latitude != lat || puntoEntrega.ReferenciaGeografica.Longitude != lon))
                {
                    puntoEntrega.ReferenciaGeografica.Direccion.Vigencia.Fin = DateTime.UtcNow;
                    puntoEntrega.ReferenciaGeografica.Poligono.Vigencia.Fin  = DateTime.UtcNow;

                    var posicion = GetNewDireccion(lat, lon);
                    var poligono = new Poligono {
                        Radio = 50, Vigencia = new Vigencia {
                            Inicio = DateTime.UtcNow
                        }
                    };
                    poligono.AddPoints(new[] { new PointF((float)lon, (float)lat) });

                    puntoEntrega.ReferenciaGeografica.AddHistoria(posicion, poligono, DateTime.UtcNow);
                }

                var end = fecha.AddHours(vigencia);
                if (puntoEntrega.ReferenciaGeografica.Vigencia.Fin < end)
                {
                    puntoEntrega.ReferenciaGeografica.Vigencia.Fin = end;
                }

                DaoFactory.ReferenciaGeograficaDAO.SingleSaveOrUpdate(puntoEntrega.ReferenciaGeografica);
                STrace.Trace("QtreeReset", "DistribucionV1 2");
            }

            DaoFactory.PuntoEntregaDAO.SaveOrUpdate(puntoEntrega);

            if (codigo.Contains("TR"))
            {
                var ultimo     = item.Detalles.Last().ReferenciaGeografica;
                var origen     = new LatLon(ultimo.Latitude, ultimo.Longitude);
                var destino    = new LatLon(puntoEntrega.ReferenciaGeografica.Latitude, puntoEntrega.ReferenciaGeografica.Longitude);
                var directions = GoogleDirections.GetDirections(origen, destino, GoogleDirections.Modes.Driving, string.Empty, null);

                if (directions != null)
                {
                    distance = directions.Distance / 1000.0;
                    var duracion = directions.Duration;
                    fecha = item.Detalles.Last().Programado.Add(duracion);
                }
            }

            if (item.Detalles.Last().TipoServicio != null)
            {
                fecha = fecha.AddMinutes(item.Detalles.Last().TipoServicio.Demora);
            }

            var entrega = new EntregaDistribucion
            {
                Cliente      = oCliente,
                PuntoEntrega = puntoEntrega,
                Descripcion  = codigoPuntoEntrega,
                Estado       = EntregaDistribucion.Estados.Pendiente,
                Orden        = item.Detalles.Count,
                //Orden = Convert.ToInt32(orden, CultureInfo.InvariantCulture),
                Programado      = fecha,
                ProgramadoHasta = fecha,
                TipoServicio    = tipoServicio,
                Viaje           = item,
                KmCalculado     = distance
            };

            item.Detalles.Add(entrega);

            var lastDetail = item.Detalles.LastOrDefault();

            item.Fin = lastDetail == null ? item.Inicio : lastDetail.Programado;
            return(item);
        }
Exemplo n.º 15
0
        public void Parse(out int rutas, out int entregas)
        {
            const char separator = '|';
            const int  vigencia  = 12;

            var te   = new TimeElapsed();
            var rows = ParseFile(Llfile.FilePath, separator).Rows;

            STrace.Trace(Component, string.Format("Archivo parseado en {0} segundos", te.getTimeElapsed().TotalSeconds));
            te.Restart();
            PreBufferRows(rows);
            STrace.Trace(Component, string.Format("PreBufferRows en {0} segundos", te.getTimeElapsed().TotalSeconds));

            var listViajes      = new List <ViajeDistribucion>(rows.Count);
            var listPuntos      = new List <PuntoEntrega>();
            var listReferencias = new List <ReferenciaGeografica>();

            rutas    = 0;
            entregas = 0;

            STrace.Trace(Component, "Cantidad de filas: " + rows.Count);
            var filas = 0;

            foreach (var row in rows)
            {
                filas++;
                STrace.Trace(Component, string.Format("Procesando fila: {0}/{1}", filas, rows.Count));

                var patente  = row.Cells[Properties.DistribucionQuilmes.Patente].ToString().Trim();
                var vehiculo = _cochesBuffer.SingleOrDefault(v => v.Patente == patente);

                var oLinea = vehiculo != null && vehiculo.Linea != null ? vehiculo.Linea : Linea;
                if (oLinea == null)
                {
                    ThrowProperty("LINEA", Llfile.Strategy);
                }

                var sFecha = row.Cells[Properties.DistribucionQuilmes.Fecha].ToString().Trim();
                var codigo = sFecha + row.Cells[Properties.DistribucionQuilmes.Ruta].ToString().Trim();

                var sHora = row.Cells[Properties.DistribucionQuilmes.Hora].ToString().Trim();
                if (sHora.Length == 3)
                {
                    sHora = "0" + sHora;
                }
                else if (sHora.Length != 4)
                {
                    ThrowProperty("HORARIO", Llfile.Strategy);
                }

                var latitud  = row.Cells[Properties.DistribucionQuilmes.Latitud].ToString().Trim();
                var longitud = row.Cells[Properties.DistribucionQuilmes.Longitud].ToString().Trim();
                var esBase   = latitud.Trim().Equals(string.Empty) && longitud.Trim().Equals(string.Empty);

                var dia   = Convert.ToInt32(sFecha.Substring(0, 2));
                var mes   = Convert.ToInt32(sFecha.Substring(2, 2));
                var anio  = Convert.ToInt32(sFecha.Substring(4, 2)) + 2000;
                var hora  = Convert.ToInt32(sHora.Substring(0, 2));
                var min   = Convert.ToInt32(sHora.Substring(2, 2));
                var gmt   = new TimeSpan(-3, 0, 0);
                var fecha = new DateTime(anio, mes, dia, hora, min, 0).Subtract(gmt);

                if (listViajes.Count == 0 || codigo != listViajes.Last().Codigo)
                {
                    var byCode = _viajesBuffer.SingleOrDefault(v => v.Codigo == codigo);
                    if (byCode != null)
                    {
                        continue;
                    }
                }

                ViajeDistribucion item;

                if (listViajes.Count > 0 && listViajes.Any(v => v.Codigo == codigo))
                {
                    item = listViajes.SingleOrDefault(v => v.Codigo == codigo);
                    if (fecha < item.Inicio)
                    {
                        item.Inicio = fecha;
                    }
                }
                else
                {
                    item = new ViajeDistribucion {
                        Codigo = codigo
                    };
                    rutas++;

                    item.Empresa              = Empresa;
                    item.Linea                = oLinea;
                    item.Vehiculo             = vehiculo;
                    item.Inicio               = fecha;
                    item.Fin                  = fecha;
                    item.Tipo                 = ViajeDistribucion.Tipos.Desordenado;
                    item.RegresoABase         = true;
                    item.Estado               = ViajeDistribucion.Estados.Pendiente;
                    item.Alta                 = DateTime.UtcNow;
                    item.ProgramacionDinamica = codigo.Contains("TR");

                    var nroViaje = row.Cells[Properties.DistribucionQuilmes.Viaje].ToString().Trim();
                    item.NumeroViaje = Convert.ToInt32(nroViaje);

                    if (vehiculo != null)
                    {
                        item.Empleado          = !vehiculo.IdentificaChoferes ? vehiculo.Chofer : null;
                        item.CentroDeCostos    = vehiculo.CentroDeCostos;
                        item.SubCentroDeCostos = vehiculo.SubCentroDeCostos;
                    }
                    else
                    {
                        STrace.Error(Component, string.Format("Patente {0} no encontrada para el viaje: {1}", patente, codigo));
                    }

                    listViajes.Add(item);
                }

                var kms      = row.Cells[Properties.DistribucionQuilmes.Kms].ToString().Trim();
                var distance = Convert.ToDouble(kms, CultureInfo.InvariantCulture);

                if (esBase)
                {
                    if (codigo.Contains("TR"))
                    {
                        var ultimo  = item.Detalles.Last().ReferenciaGeografica;
                        var origen  = new LatLon(ultimo.Latitude, ultimo.Longitude);
                        var destino = new LatLon(oLinea.ReferenciaGeografica.Latitude,
                                                 oLinea.ReferenciaGeografica.Longitude);
                        var directions = GoogleDirections.GetDirections(origen, destino, GoogleDirections.Modes.Driving,
                                                                        string.Empty, null);

                        if (directions != null)
                        {
                            distance = directions.Distance / 1000.0;
                            var duracion = directions.Duration;
                            fecha = item.Detalles.Last().Programado.Add(duracion);
                        }
                    }

                    var llegada = new EntregaDistribucion
                    {
                        Linea           = oLinea,
                        Descripcion     = oLinea.Descripcion,
                        Estado          = EntregaDistribucion.Estados.Pendiente,
                        Orden           = item.Detalles.Count,
                        Programado      = fecha,
                        ProgramadoHasta = fecha,
                        Viaje           = item,
                        KmCalculado     = distance
                    };

                    item.Detalles.Add(llegada);
                    continue;
                }

                // Entregas
                if (item.Detalles.Count == 0)
                {
                    //Si no existe, agrego la salida de base
                    var origen = new EntregaDistribucion
                    {
                        Linea           = oLinea,
                        Descripcion     = oLinea.Descripcion,
                        Estado          = EntregaDistribucion.Estados.Pendiente,
                        Orden           = 0,
                        Programado      = fecha,
                        ProgramadoHasta = fecha,
                        Viaje           = item
                    };
                    item.Detalles.Add(origen);
                }

                var codigoPuntoEntrega = row.Cells[Properties.DistribucionQuilmes.CodigoCliente].ToString().Trim();
                var nombre             = row.Cells[Properties.DistribucionQuilmes.DescripcionCliente].ToString().Trim();
                if (string.IsNullOrEmpty(codigoPuntoEntrega))
                {
                    ThrowProperty("PUNTO ENTREGA", Llfile.Strategy);
                }

                if (item.Detalles.Any(d => d.PuntoEntrega != null && d.PuntoEntrega.Codigo == codigoPuntoEntrega))
                {
                    continue;
                }

                TipoServicioCiclo tipoServicio = null;
                var tipoServ = _tiposServicioBuffer.SingleOrDefault(ts => ts.Linea == null || ts.Linea.Id == oLinea.Id);
                if (tipoServ != null && tipoServ.Id > 0)
                {
                    tipoServicio = tipoServ;
                }

                latitud  = latitud.Replace(',', '.');
                longitud = longitud.Replace(',', '.');
                var lat = Convert.ToDouble(latitud, CultureInfo.InvariantCulture);
                var lon = Convert.ToDouble(longitud, CultureInfo.InvariantCulture);
                ValidateGpsPoint(codigo, codigoPuntoEntrega, (float)lat, (float)lon);

                var puntoEntrega = _puntosBuffer.SingleOrDefault(p => p.Codigo == codigoPuntoEntrega);

                if (puntoEntrega == null)
                {
                    var empresaGeoRef = item.Vehiculo != null && item.Vehiculo.Empresa == null ? null : Cliente.Empresa == null ? null : Empresa;
                    var lineaGeoRef   = item.Vehiculo != null && item.Vehiculo.Linea == null ? null : Cliente.Linea == null ? null : oLinea;

                    var puntoDeInteres = new ReferenciaGeografica
                    {
                        Codigo                   = codigoPuntoEntrega,
                        Descripcion              = nombre,
                        Empresa                  = empresaGeoRef,
                        Linea                    = lineaGeoRef,
                        EsFin                    = Cliente.ReferenciaGeografica.TipoReferenciaGeografica.EsFin,
                        EsInicio                 = Cliente.ReferenciaGeografica.TipoReferenciaGeografica.EsInicio,
                        EsIntermedio             = Cliente.ReferenciaGeografica.TipoReferenciaGeografica.EsIntermedio,
                        InhibeAlarma             = Cliente.ReferenciaGeografica.TipoReferenciaGeografica.InhibeAlarma,
                        TipoReferenciaGeografica = Cliente.ReferenciaGeografica.TipoReferenciaGeografica,
                        Vigencia                 = new Vigencia {
                            Inicio = DateTime.UtcNow, Fin = fecha.AddHours(vigencia)
                        },
                        Icono = Cliente.ReferenciaGeografica.TipoReferenciaGeografica.Icono
                    };

                    var posicion = GetNewDireccion(lat, lon);

                    var poligono = new Poligono {
                        Radio = 50, Vigencia = new Vigencia {
                            Inicio = DateTime.UtcNow
                        }
                    };
                    poligono.AddPoints(new[] { new PointF((float)lon, (float)lat) });

                    puntoDeInteres.Historia.Add(new HistoriaGeoRef
                    {
                        ReferenciaGeografica = puntoDeInteres,
                        Direccion            = posicion,
                        Poligono             = poligono,
                        Vigencia             = new Vigencia {
                            Inicio = DateTime.UtcNow
                        }
                    });

                    listReferencias.Add(puntoDeInteres);

                    puntoEntrega = new PuntoEntrega
                    {
                        Cliente              = Cliente,
                        Codigo               = codigoPuntoEntrega,
                        Descripcion          = nombre,
                        Telefono             = string.Empty,
                        Baja                 = false,
                        ReferenciaGeografica = puntoDeInteres,
                        Nomenclado           = true,
                        DireccionNomenclada  = string.Empty,
                        Nombre               = nombre
                    };
                }
                else
                {
                    if (!puntoEntrega.ReferenciaGeografica.IgnoraLogiclink && (puntoEntrega.ReferenciaGeografica.Latitude != lat || puntoEntrega.ReferenciaGeografica.Longitude != lon))
                    {
                        puntoEntrega.ReferenciaGeografica.Direccion.Vigencia.Fin = DateTime.UtcNow;
                        puntoEntrega.ReferenciaGeografica.Poligono.Vigencia.Fin  = DateTime.UtcNow;

                        var posicion = GetNewDireccion(lat, lon);
                        var poligono = new Poligono {
                            Radio = 50, Vigencia = new Vigencia {
                                Inicio = DateTime.UtcNow
                            }
                        };
                        poligono.AddPoints(new[] { new PointF((float)lon, (float)lat) });

                        puntoEntrega.ReferenciaGeografica.AddHistoria(posicion, poligono, DateTime.UtcNow);
                    }

                    var end = fecha.AddHours(vigencia);
                    if (puntoEntrega.ReferenciaGeografica.Vigencia.Fin < end)
                    {
                        puntoEntrega.ReferenciaGeografica.Vigencia.Fin = end;
                    }

                    listReferencias.Add(puntoEntrega.ReferenciaGeografica);
                }

                listPuntos.Add(puntoEntrega);

                if (codigo.Contains("TR"))
                {
                    var ultimo     = item.Detalles.Last().ReferenciaGeografica;
                    var origen     = new LatLon(ultimo.Latitude, ultimo.Longitude);
                    var destino    = new LatLon(puntoEntrega.ReferenciaGeografica.Latitude, puntoEntrega.ReferenciaGeografica.Longitude);
                    var directions = GoogleDirections.GetDirections(origen, destino, GoogleDirections.Modes.Driving, string.Empty, null);

                    if (directions != null)
                    {
                        distance = directions.Distance / 1000.0;
                        var duracion = directions.Duration;
                        fecha = item.Detalles.Last().Programado.Add(duracion);
                    }
                }

                if (item.Detalles.Last().TipoServicio != null)
                {
                    fecha = fecha.AddMinutes(item.Detalles.Last().TipoServicio.Demora);
                }

                var entrega = new EntregaDistribucion
                {
                    Cliente      = Cliente,
                    PuntoEntrega = puntoEntrega,
                    Descripcion  = codigoPuntoEntrega,
                    Estado       = EntregaDistribucion.Estados.Pendiente,
                    Orden        = item.Detalles.Count,
                    //Orden = Convert.ToInt32(orden, CultureInfo.InvariantCulture),
                    Programado      = fecha,
                    ProgramadoHasta = fecha,
                    TipoServicio    = tipoServicio,
                    Viaje           = item,
                    KmCalculado     = distance
                };

                item.Detalles.Add(entrega);
                entregas++;

                var lastDetail = item.Detalles.LastOrDefault();
                item.Fin = lastDetail == null ? item.Inicio : lastDetail.Programado;
            }

            STrace.Trace(Component, "Guardando referencias geográficas: " + listReferencias.Count);
            te.Restart();
            foreach (var referenciaGeografica in listReferencias)
            {
                DaoFactory.ReferenciaGeograficaDAO.Guardar(referenciaGeografica);
            }
            STrace.Trace(Component, string.Format("Referencias guardadas en {0} segundos", te.getTimeElapsed().TotalSeconds));

            STrace.Trace(Component, "Guardando puntos de entrega: " + listPuntos.Count);
            te.Restart();
            foreach (var puntoEntrega in listPuntos)
            {
                DaoFactory.PuntoEntregaDAO.SaveOrUpdate(puntoEntrega);
            }
            STrace.Trace(Component, string.Format("Puntos guardados en {0} segundos", te.getTimeElapsed().TotalSeconds));

            STrace.Trace(Component, "Guardando Viajes: " + listViajes.Count);
            te.Restart();
            foreach (var viajeDistribucion in listViajes)
            {
                DaoFactory.ViajeDistribucionDAO.SaveOrUpdate(viajeDistribucion);
            }
            STrace.Trace(Component, string.Format("Viajes guardados en {0} segundos", te.getTimeElapsed().TotalSeconds));

            DaoFactory.ReferenciaGeograficaDAO.DeleteCacheList(-1, -1);
            DaoFactory.ReferenciaGeograficaDAO.DeleteCacheList(Empresa.Id, -1);

            var lineas = DaoFactory.LineaDAO.FindList(new[] { Empresa.Id });

            foreach (var lin in lineas)
            {
                DaoFactory.ReferenciaGeograficaDAO.DeleteCacheList(Empresa.Id, lin.Id);
            }
        }
        public List<GoogleMap> getServicePointsAlongRoute(GoogleDirections.TDirections directionsObj)
        {
            bool flag = false;
            int size = directionsObj.routes[0].legs[0].steps.Length;
            GoogleDirections.Step[] tLegs=directionsObj.routes[0].legs[0].steps;
            GoogleDirections.Step pointer = null;
            int incrementSize = size / 5;
            incrementSize = incrementSize-1;
            List<GoogleMap> pointerList = new List<GoogleMap>();
            GoogleMap gMap = null;
            for(int i=0;i<tLegs.Length;i++)
            {
                if(i==tLegs.Length-1)
                {
                    flag = true;
                }
                pointer = tLegs[i];
                gMap = new GoogleMap();
                gMap.latitude=pointer.start_location.lat+"";
                gMap.longitude=pointer.start_location.lng+"";

                gMap.elatitude = pointer.end_location.lat + "";
                gMap.elongitude = pointer.end_location.lng + "";

                pointerList.Add(gMap);
            }
            if(!flag)
            {
                gMap = new GoogleMap();
                gMap.latitude = tLegs[tLegs.Length-1].end_location.lat + "";
                gMap.longitude = tLegs[tLegs.Length - 1].end_location.lng + "";

                pointerList.Add(gMap);
            }
            return pointerList;
        }
Exemplo n.º 17
0
        private ViajeDistribucion BuildRoute(SosTicket service)
        {
            var       empresa  = DaoFactory.EmpresaDAO.FindByCodigo(CodigoEmpresa);
            var       linea    = DaoFactory.LineaDAO.FindByCodigo(empresa.Id, CodigoLinea);
            var       cliente  = DaoFactory.ClienteDAO.FindByCode(new[] { empresa.Id }, new[] { -1 }, CodigoCliente);
            const int vigencia = 12;
            var       fecha    = service.HoraServicio;

            var viaje = new ViajeDistribucion();

            if (service.Distribucion == null)
            {
                //viaje
                viaje.Codigo       = service.NumeroServicio;
                viaje.Empresa      = empresa;
                viaje.Linea        = linea;
                viaje.Estado       = ViajeDistribucion.Estados.Pendiente;
                viaje.Tipo         = ViajeDistribucion.Tipos.Desordenado;
                viaje.Inicio       = fecha;
                viaje.RegresoABase = false;
                viaje.Fin          = fecha.AddHours(1);
                viaje.Vehiculo     = DaoFactory.CocheDAO.FindByInterno(new[] { empresa.Id }, new[] { -1 }, service.Movil.ToString());

                //base al inicio
                var entregaBase = new EntregaDistribucion();
                entregaBase.Linea           = linea;
                entregaBase.Descripcion     = linea.Descripcion;
                entregaBase.Estado          = EntregaDistribucion.Estados.Pendiente;
                entregaBase.Programado      = fecha;
                entregaBase.ProgramadoHasta = fecha.AddHours(1);
                entregaBase.Orden           = viaje.Detalles.Count;
                entregaBase.Viaje           = viaje;
                entregaBase.KmCalculado     = 0;
                viaje.Detalles.Add(entregaBase);

                var nombreOrigen  = service.NumeroServicio + " - A";
                var nombreDestino = service.NumeroServicio + " - B";

                TipoServicioCiclo tipoServicio = null;
                var tipoServ = DaoFactory.TipoServicioCicloDAO.FindDefault(new[] { empresa.Id }, new[] { -1 });
                if (tipoServ != null && tipoServ.Id > 0)
                {
                    tipoServicio = tipoServ;
                }

                #region Origen

                var puntoEntregaO = DaoFactory.PuntoEntregaDAO.FindByCode(new[] { empresa.Id },
                                                                          new[] { -1 },
                                                                          new[] { cliente.Id },
                                                                          nombreOrigen);

                if (puntoEntregaO == null)
                {
                    var empresaGeoRef = empresa;
                    var lineaGeoRef   = linea;

                    var puntoDeInteres = new ReferenciaGeografica
                    {
                        Codigo                   = nombreOrigen,
                        Descripcion              = nombreOrigen,
                        Empresa                  = empresaGeoRef,
                        Linea                    = lineaGeoRef,
                        EsFin                    = cliente.ReferenciaGeografica.TipoReferenciaGeografica.EsFin,
                        EsInicio                 = cliente.ReferenciaGeografica.TipoReferenciaGeografica.EsInicio,
                        EsIntermedio             = cliente.ReferenciaGeografica.TipoReferenciaGeografica.EsIntermedio,
                        InhibeAlarma             = cliente.ReferenciaGeografica.TipoReferenciaGeografica.InhibeAlarma,
                        TipoReferenciaGeografica = cliente.ReferenciaGeografica.TipoReferenciaGeografica,
                        Vigencia                 = new Vigencia {
                            Inicio = DateTime.UtcNow, Fin = fecha.AddHours(vigencia)
                        },
                        Icono = cliente.ReferenciaGeografica.TipoReferenciaGeografica.Icono
                    };

                    var posicion = GetNewDireccion(service.Origen.Latitud, service.Origen.Longitud);
                    var poligono = new Poligono {
                        Radio = 50, Vigencia = new Vigencia {
                            Inicio = DateTime.UtcNow
                        }
                    };
                    poligono.AddPoints(new[] { new PointF((float)service.Origen.Longitud, (float)service.Origen.Latitud) });

                    puntoDeInteres.Historia.Add(new HistoriaGeoRef
                    {
                        ReferenciaGeografica = puntoDeInteres,
                        Direccion            = posicion,
                        Poligono             = poligono,
                        Vigencia             = new Vigencia {
                            Inicio = DateTime.UtcNow
                        }
                    });

                    DaoFactory.ReferenciaGeograficaDAO.SaveOrUpdate(puntoDeInteres);

                    puntoEntregaO = new PuntoEntrega
                    {
                        Cliente              = cliente,
                        Codigo               = nombreOrigen,
                        Descripcion          = nombreOrigen,
                        Telefono             = string.Empty,
                        Baja                 = false,
                        ReferenciaGeografica = puntoDeInteres,
                        Nomenclado           = true,
                        DireccionNomenclada  = service.Origen.Direccion + ", " + service.Origen.Localidad,
                        Nombre               = nombreOrigen
                    };
                }
                else
                {
                    if (!puntoEntregaO.ReferenciaGeografica.IgnoraLogiclink && (puntoEntregaO.ReferenciaGeografica.Latitude != service.Origen.Latitud || puntoEntregaO.ReferenciaGeografica.Longitude != service.Origen.Longitud))
                    {
                        puntoEntregaO.ReferenciaGeografica.Direccion.Vigencia.Fin = DateTime.UtcNow;
                        puntoEntregaO.ReferenciaGeografica.Poligono.Vigencia.Fin  = DateTime.UtcNow;

                        var posicion = GetNewDireccion(service.Origen.Latitud, service.Origen.Longitud);
                        var poligono = new Poligono {
                            Radio = 50, Vigencia = new Vigencia {
                                Inicio = DateTime.UtcNow
                            }
                        };
                        poligono.AddPoints(new[] { new PointF((float)service.Origen.Longitud, (float)service.Origen.Latitud) });

                        puntoEntregaO.ReferenciaGeografica.AddHistoria(posicion, poligono, DateTime.UtcNow);
                    }

                    var end = fecha.AddHours(vigencia);
                    if (puntoEntregaO.ReferenciaGeografica.Vigencia.Fin < end)
                    {
                        puntoEntregaO.ReferenciaGeografica.Vigencia.Fin = end;
                    }

                    DaoFactory.ReferenciaGeograficaDAO.SaveOrUpdate(puntoEntregaO.ReferenciaGeografica);
                }

                DaoFactory.PuntoEntregaDAO.SaveOrUpdate(puntoEntregaO);

                var entregaO = new EntregaDistribucion
                {
                    Cliente         = cliente,
                    PuntoEntrega    = puntoEntregaO,
                    Descripcion     = nombreOrigen,
                    Estado          = EntregaDistribucion.Estados.Pendiente,
                    Orden           = viaje.Detalles.Count,
                    Programado      = fecha,
                    ProgramadoHasta = fecha,
                    TipoServicio    = tipoServicio,
                    Viaje           = viaje
                };

                viaje.Detalles.Add(entregaO);

                #endregion

                #region Destino

                var puntoEntregaD = DaoFactory.PuntoEntregaDAO.FindByCode(new[] { empresa.Id },
                                                                          new[] { -1 },
                                                                          new[] { cliente.Id },
                                                                          nombreDestino);

                if (puntoEntregaD == null)
                {
                    var empresaGeoRef = empresa;
                    var lineaGeoRef   = linea;

                    var puntoDeInteres = new ReferenciaGeografica
                    {
                        Codigo                   = nombreDestino,
                        Descripcion              = nombreDestino,
                        Empresa                  = empresaGeoRef,
                        Linea                    = lineaGeoRef,
                        EsFin                    = cliente.ReferenciaGeografica.TipoReferenciaGeografica.EsFin,
                        EsInicio                 = cliente.ReferenciaGeografica.TipoReferenciaGeografica.EsInicio,
                        EsIntermedio             = cliente.ReferenciaGeografica.TipoReferenciaGeografica.EsIntermedio,
                        InhibeAlarma             = cliente.ReferenciaGeografica.TipoReferenciaGeografica.InhibeAlarma,
                        TipoReferenciaGeografica = cliente.ReferenciaGeografica.TipoReferenciaGeografica,
                        Vigencia                 = new Vigencia {
                            Inicio = DateTime.UtcNow, Fin = fecha.AddHours(vigencia)
                        },
                        Icono = cliente.ReferenciaGeografica.TipoReferenciaGeografica.Icono
                    };

                    var posicion = GetNewDireccion(service.Destino.Latitud, service.Destino.Longitud);

                    var poligono = new Poligono {
                        Radio = 50, Vigencia = new Vigencia {
                            Inicio = DateTime.UtcNow
                        }
                    };
                    poligono.AddPoints(new[] { new PointF((float)service.Destino.Longitud, (float)service.Destino.Latitud) });

                    puntoDeInteres.Historia.Add(new HistoriaGeoRef
                    {
                        ReferenciaGeografica = puntoDeInteres,
                        Direccion            = posicion,
                        Poligono             = poligono,
                        Vigencia             = new Vigencia {
                            Inicio = DateTime.UtcNow
                        }
                    });

                    DaoFactory.ReferenciaGeograficaDAO.SaveOrUpdate(puntoDeInteres);

                    puntoEntregaD = new PuntoEntrega
                    {
                        Cliente              = cliente,
                        Codigo               = nombreDestino,
                        Descripcion          = nombreDestino,
                        Telefono             = string.Empty,
                        Baja                 = false,
                        ReferenciaGeografica = puntoDeInteres,
                        Nomenclado           = true,
                        DireccionNomenclada  = service.Destino.Direccion + ", " + service.Destino.Localidad,
                        Nombre               = nombreDestino
                    };
                }
                else
                {
                    if (!puntoEntregaD.ReferenciaGeografica.IgnoraLogiclink && (puntoEntregaD.ReferenciaGeografica.Latitude != service.Destino.Latitud || puntoEntregaD.ReferenciaGeografica.Longitude != service.Destino.Longitud))
                    {
                        puntoEntregaD.ReferenciaGeografica.Direccion.Vigencia.Fin = DateTime.UtcNow;
                        puntoEntregaD.ReferenciaGeografica.Poligono.Vigencia.Fin  = DateTime.UtcNow;

                        var posicion = GetNewDireccion(service.Destino.Latitud, service.Destino.Longitud);
                        var poligono = new Poligono {
                            Radio = 50, Vigencia = new Vigencia {
                                Inicio = DateTime.UtcNow
                            }
                        };
                        poligono.AddPoints(new[] { new PointF((float)service.Destino.Longitud, (float)service.Destino.Latitud) });

                        puntoEntregaD.ReferenciaGeografica.AddHistoria(posicion, poligono, DateTime.UtcNow);
                    }

                    var end = fecha.AddHours(vigencia);
                    if (puntoEntregaD.ReferenciaGeografica.Vigencia.Fin < end)
                    {
                        puntoEntregaD.ReferenciaGeografica.Vigencia.Fin = end;
                    }

                    DaoFactory.ReferenciaGeograficaDAO.SaveOrUpdate(puntoEntregaD.ReferenciaGeografica);
                }

                DaoFactory.PuntoEntregaDAO.SaveOrUpdate(puntoEntregaD);

                var anterior   = puntoEntregaO.ReferenciaGeografica;
                var siguiente  = puntoEntregaD.ReferenciaGeografica;
                var o          = new LatLon(anterior.Latitude, anterior.Longitude);
                var d          = new LatLon(siguiente.Latitude, siguiente.Longitude);
                var directions = GoogleDirections.GetDirections(o, d, GoogleDirections.Modes.Driving, string.Empty, null);

                if (directions != null)
                {
                    var duracion = directions.Duration;
                    fecha = entregaO.Programado.Add(duracion);
                }

                var entregaD = new EntregaDistribucion
                {
                    Cliente         = cliente,
                    PuntoEntrega    = puntoEntregaD,
                    Descripcion     = nombreDestino,
                    Estado          = EntregaDistribucion.Estados.Pendiente,
                    Orden           = viaje.Detalles.Count,
                    Programado      = fecha,
                    ProgramadoHasta = fecha,
                    TipoServicio    = tipoServicio,
                    Viaje           = viaje
                };

                viaje.Detalles.Add(entregaD);
                viaje.Fin = fecha;

                #endregion
            }
            return(viaje);
        }
Exemplo n.º 18
0
        private Intercalado CalcularDirectionsIntercalado(Intercalado intercalado, PuntoEntrega nuevoPunto)
        {
            var viaje = Viajes.FirstOrDefault(v => v.Id == intercalado.Id);

            var first  = viaje.Detalles.First().ReferenciaGeografica;
            var origen = new LatLon(first.Latitude, first.Longitude);

            var last    = viaje.Detalles.Last().ReferenciaGeografica;
            var destino = new LatLon(last.Latitude, last.Longitude);

            var waypoints = viaje.Detalles.Skip(1).Take(viaje.Detalles.Count - 2).Select(w => new LatLon(w.ReferenciaGeografica.Latitude, w.ReferenciaGeografica.Longitude)).ToList();

            var nuevaLatLon = new LatLon(nuevoPunto.ReferenciaGeografica.Latitude,
                                         nuevoPunto.ReferenciaGeografica.Longitude);

            if (intercalado.Index == 0)
            {
                waypoints.Insert(0, origen);
                origen = nuevaLatLon;
            }
            else if (intercalado.Index >= viaje.Detalles.Count)
            {
                waypoints.Add(destino);
                destino = nuevaLatLon;
            }
            else if (intercalado.Index == viaje.Detalles.Count - 1)
            {
                waypoints.Add(nuevaLatLon);
            }
            else
            {
                waypoints.Insert(intercalado.Index, nuevaLatLon);
            }

            var directions = GoogleDirections.GetDirections(origen, destino, GoogleDirections.Modes.Driving,
                                                            string.Empty, waypoints.ToArray());

            intercalado.ViajeIntercalado = directions;
            if (directions != null)
            {
                intercalado.CostoKm = directions.Distance;
            }

            var nuevoDetalle = new EntregaDistribucion
            {
                PuntoEntrega = nuevoPunto,
                Cliente      = nuevoPunto.Cliente,
                Descripcion  = nuevoPunto.Descripcion
            };

            viaje.InsertarEntrega(intercalado.Index, nuevoDetalle);
            if (intercalado.Index > 0)
            {
                viaje.CalcularHorario(intercalado.Index, intercalado.ViajeIntercalado);
            }
            if (intercalado.Index < viaje.Detalles.Count)
            {
                viaje.CalcularHorario(intercalado.Index, intercalado.ViajeIntercalado);
            }

            var duracionNueva = viaje.Detalles.Last().Programado.Subtract(viaje.Detalles.First().Programado);

            intercalado.CostoMin = duracionNueva.TotalMinutes;

            intercalado.Hora = nuevoDetalle.Programado;

            viaje.RemoverEntrega(intercalado.Index);

            return(intercalado);
        }
Exemplo n.º 19
0
        protected override void OnExecute(Timer timer)
        {
            STrace.Trace(ComponentName, "Inicio de la tarea");

            var inicio = DateTime.UtcNow;

            var empresas = DaoFactory.EmpresaDAO.GetList().Where(e => e.GeneraRutaInversa);

            STrace.Trace(GetType().FullName, string.Format("Procesando empresas. Cantidad: {0}", empresas.Count()));

            try
            {
                foreach (var empresa in empresas)
                {
                    var vehiculos = DaoFactory.CocheDAO.FindList(new[] { empresa.Id }, new[] { -1 })
                                    .Where(c => c.Dispositivo != null);
                    var clientes = DaoFactory.ClienteDAO.GetList(new[] { empresa.Id }, new[] { -1 }).Select(c => c.Id).ToList();

                    var vehiculosPendientes = vehiculos.Count();
                    STrace.Trace(GetType().FullName, string.Format("Vehículos a procesar: {0}", vehiculosPendientes));

                    var eventosEntradas = DaoFactory.LogMensajeDAO.GetByVehiclesAndCode(vehiculos.Select(v => v.Id).ToArray(), MessageCode.InsideGeoRefference.GetMessageCode(), Desde, Hasta, 1);
                    var eventosSalidas  = DaoFactory.LogMensajeDAO.GetByVehiclesAndCode(vehiculos.Select(v => v.Id).ToArray(), MessageCode.OutsideGeoRefference.GetMessageCode(), Desde.AddDays(-7), Hasta, 1);

                    foreach (var vehiculo in vehiculos)
                    {
                        STrace.Trace(GetType().FullName, string.Format("Procesando vehículo: {0}", vehiculo.Id));

                        var entradas = eventosEntradas.Where(ev => ev.Coche.Id == vehiculo.Id &&
                                                             ev.Fecha > Desde &&
                                                             ev.Fecha < Hasta &&
                                                             ev.IdPuntoDeInteres.HasValue);

                        STrace.Trace(GetType().FullName, string.Format("Entradas a procesar: {0}", entradas.Count()));

                        var i = 1;
                        foreach (var entrada in entradas)
                        {
                            STrace.Trace(GetType().FullName, string.Format("Procesando entrada: {0}/{1}", i, entradas.Count()));

                            var ptoFin = DaoFactory.PuntoEntregaDAO.FindByClientesAndGeoreferencia(clientes, entrada.IdPuntoDeInteres.Value);
                            if (ptoFin == null)
                            {
                                continue;
                            }

                            var salidas = eventosSalidas.Where(ev => ev.Coche.Id == vehiculo.Id &&
                                                               ev.Fecha > entrada.Fecha.AddDays(-7) &&
                                                               ev.Fecha < entrada.Fecha.AddSeconds(-1) &&
                                                               ev.IdPuntoDeInteres.HasValue)
                                          .OrderByDescending(s => s.Fecha);

                            foreach (var salida in salidas)
                            {
                                var ptoInicio = DaoFactory.PuntoEntregaDAO.FindByClientesAndGeoreferencia(clientes, salida.IdPuntoDeInteres.Value);
                                if (ptoInicio != null)
                                {
                                    if (ptoInicio == ptoFin)
                                    {
                                        break;
                                    }

                                    var codigo = salida.Fecha.AddHours(-3).ToString("yyyyMMdd") + "|" + vehiculo.Interno + "|" + ptoInicio.Codigo + "-" + ptoFin.Codigo;
                                    var viaje  = new ViajeDistribucion
                                    {
                                        Alta         = DateTime.UtcNow,
                                        Codigo       = codigo.Length <= 32 ? codigo : codigo.Substring(0, 32),
                                        Empresa      = empresa,
                                        Estado       = ViajeDistribucion.Estados.Cerrado,
                                        Fin          = entrada.Fecha,
                                        Inicio       = salida.Fecha,
                                        InicioReal   = salida.Fecha,
                                        Linea        = vehiculo.Linea,
                                        NumeroViaje  = 1,
                                        RegresoABase = false,
                                        Tipo         = ViajeDistribucion.Tipos.Desordenado,
                                        Vehiculo     = vehiculo
                                    };

                                    var entrega1 = new EntregaDistribucion
                                    {
                                        Cliente         = ptoInicio.Cliente,
                                        PuntoEntrega    = ptoInicio,
                                        Descripcion     = ptoInicio.Descripcion,
                                        Estado          = EntregaDistribucion.Estados.Visitado,
                                        Orden           = 1,
                                        Programado      = salida.Fecha,
                                        ProgramadoHasta = salida.Fecha,
                                        Viaje           = viaje,
                                        Salida          = salida.Fecha
                                    };

                                    viaje.Detalles.Add(entrega1);

                                    var fechaFin   = entrada.Fecha;
                                    var kms        = 0.0;
                                    var origen     = new LatLon(ptoInicio.ReferenciaGeografica.Latitude, ptoInicio.ReferenciaGeografica.Longitude);
                                    var destino    = new LatLon(ptoFin.ReferenciaGeografica.Latitude, ptoFin.ReferenciaGeografica.Longitude);
                                    var directions = GoogleDirections.GetDirections(origen, destino, GoogleDirections.Modes.Driving, string.Empty, null);

                                    if (directions != null)
                                    {
                                        var duracion = directions.Duration;
                                        kms      = directions.Distance / 1000.0;
                                        fechaFin = salida.Fecha.Add(duracion);
                                    }

                                    var entrega2 = new EntregaDistribucion
                                    {
                                        Cliente         = ptoFin.Cliente,
                                        PuntoEntrega    = ptoFin,
                                        Descripcion     = ptoFin.Descripcion,
                                        Estado          = EntregaDistribucion.Estados.Visitado,
                                        Orden           = 2,
                                        Programado      = fechaFin,
                                        ProgramadoHasta = fechaFin,
                                        Viaje           = viaje,
                                        Entrada         = entrada.Fecha,
                                        KmCalculado     = kms
                                    };

                                    viaje.Detalles.Add(entrega2);

                                    DaoFactory.ViajeDistribucionDAO.SaveOrUpdate(viaje);
                                    break;
                                }
                            }
                            i++;
                        }

                        STrace.Trace(GetType().FullName, string.Format("Vehículos a procesar: {0}", --vehiculosPendientes));
                    }
                }

                STrace.Trace(GetType().FullName, "Tarea finalizada.");

                var fin      = DateTime.UtcNow;
                var duration = fin.Subtract(inicio).TotalMinutes;

                DaoFactory.DataMartsLogDAO.SaveNewLog(inicio, fin, duration, DataMartsLog.Moludos.GeneracionInversa, "Generación inversa finalizada exitosamente");
            }
            catch (Exception ex)
            {
                AddError(ex);
            }
            finally
            {
                ClearData();
            }
        }