コード例 #1
0
        private void CalcularHorarioPorDistancia(ViajeDistribucion distribucion)
        {
            var index = distribucion.Detalles.Count - 1;

            if (index < 0)
            {
                return;
            }
            if (index == 0)
            {
                distribucion.Detalles[index].Programado      = distribucion.Inicio;
                distribucion.Detalles[index].ProgramadoHasta = distribucion.Inicio;
                return;
            }

            var velocidadPromedio = GetVelocidad(distribucion);

            var prev = distribucion.Detalles[index - 1];
            var item = distribucion.Detalles[index];

            var prevDate = prev.Programado;

            var prevPunto = prev.PuntoEntrega != null
                                ? prev.PuntoEntrega.ReferenciaGeografica
                                : prev.Linea.ReferenciaGeografica;
            var punto = item.PuntoEntrega != null
                            ? item.PuntoEntrega.ReferenciaGeografica
                            : item.Linea.ReferenciaGeografica;

            var demora = prev.TipoServicio != null ? prev.TipoServicio.Demora : 0;

            var distancia = GeocoderHelper.CalcularDistacia(prevPunto.Latitude,
                                                            prevPunto.Longitude,
                                                            punto.Latitude,
                                                            punto.Longitude);
            var tiempoViaje = TimeSpan.FromHours(distancia / velocidadPromedio);

            var hora = prevDate.AddMinutes(demora).Add(tiempoViaje);

            distribucion.Detalles[index].Programado      = hora;
            distribucion.Detalles[index].ProgramadoHasta = hora;
            distribucion.Fin = hora;
        }
コード例 #2
0
        private void CalcularKm(ViajeDistribucion viaje)
        {
            EntregaDistribucion anterior = null;
            var detalles = viaje.GetEntregasOrdenadas();

            foreach (var entrega in detalles)
            {
                if (entrega.PuntoEntrega != null && entrega.Estado != EntregaDistribucion.Estados.Completado &&
                    entrega.Estado != EntregaDistribucion.Estados.NoCompletado)
                {
                    continue;
                }

                if (anterior != null)
                {
                    var changed = false;
                    if (!entrega.KmGps.HasValue || entrega.KmGps.Value == 0)
                    {
                        entrega.KmGps = DAOFactory.CocheDAO.GetDistance(viaje.Vehiculo.Id, anterior.ManualOSalida, entrega.ManualOSalida);
                        changed       = true;
                    }
                    if (!entrega.KmCalculado.HasValue || entrega.KmCalculado.Value == 0)
                    {
                        entrega.KmCalculado = GeocoderHelper.CalcularDistacia(anterior.ReferenciaGeografica.Latitude,
                                                                              anterior.ReferenciaGeografica.Longitude,
                                                                              entrega.ReferenciaGeografica.Latitude,
                                                                              entrega.ReferenciaGeografica.Longitude);
                        changed = true;
                    }
                    if (changed)
                    {
                        DAOFactory.EntregaDistribucionDAO.SaveOrUpdate(entrega);
                    }
                }
                anterior = entrega;
            }
        }
コード例 #3
0
        public void Parse(out int rutas, out int entregas)
        {
            const int vigencia = 24;

            var te   = new TimeElapsed();
            var rows = ParseFile(Llfile.FilePath, Properties.DistribucionReginaldLee.Anchos).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 ruta = row.Cells[Properties.DistribucionReginaldLee.CodigoRuta].ToString().Trim();
                if (ruta == string.Empty)
                {
                    ThrowProperty("CODIGO_RUTA", Llfile.Strategy);
                }

                var nroViaje = 1;
                if (ruta.Contains(","))
                {
                    var rutaSplitted = ruta.Split(',');
                    int.TryParse(rutaSplitted[1], out nroViaje);
                }

                var codEntrega = row.Cells[Properties.DistribucionReginaldLee.CodigoPedido].ToString().Trim();
                if (codEntrega == string.Empty)
                {
                    ThrowProperty("CODIGO_ENTREGA", Llfile.Strategy);
                }

                var codCliente = row.Cells[Properties.DistribucionReginaldLee.CodigoCliente].ToString().Trim();
                if (codCliente == string.Empty)
                {
                    ThrowProperty("CODIGO_CLIENTE", Llfile.Strategy);
                }

                var    rowWithCoords = true;
                double latitud;
                double longitud;

                if (!double.TryParse(row.Cells[Properties.DistribucionReginaldLee.Latitud].ToString().Trim(), out latitud))
                {
                    rowWithCoords = false;
                }
                if (!double.TryParse(row.Cells[Properties.DistribucionReginaldLee.Longitud].ToString().Trim(), out longitud))
                {
                    rowWithCoords = false;
                }

                var orientacionSouthNorth = row.Cells[Properties.DistribucionReginaldLee.OrientacionNorthSouth].ToString().Trim();
                var orientacionEastWest   = row.Cells[Properties.DistribucionReginaldLee.OrientacionEastWest].ToString().Trim();

                if (orientacionSouthNorth.Equals("S"))
                {
                    latitud = latitud * (-1);
                }
                if (orientacionEastWest.Equals("W"))
                {
                    longitud = longitud * (-1);
                }

                var fecha = row.Cells[Properties.DistribucionReginaldLee.Fecha].ToString().Trim();
                if (fecha == string.Empty)
                {
                    ThrowProperty("FECHA", Llfile.Strategy);
                }

                int dia, mes, anio, hr, min;
                int.TryParse(fecha.Substring(0, 4), out anio);
                int.TryParse(fecha.Substring(5, 2), out mes);
                int.TryParse(fecha.Substring(8, 2), out dia);
                int.TryParse(fecha.Substring(11, 2), out hr);
                int.TryParse(fecha.Substring(14, 2), out min);

                var gmt  = new TimeSpan(-3, 0, 0);
                var date = new DateTime(anio, mes, dia, hr, min, 0).Subtract(gmt);

                int packs;
                if (!int.TryParse(row.Cells[Properties.DistribucionReginaldLee.Packs].ToString().Trim(), out packs))
                {
                    try
                    {
                        ThrowProperty("PACKS", Llfile.Strategy);
                    }
                    catch (Exception ex2)
                    {
                        STrace.Exception(Component, ex2, String.Format("Error en Fila #{0}: {1}", filas, ex2.Message));
                        continue;
                    }
                }

                var codigo = date.ToString("yyMMdd") + "|" + ruta;

                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);
                }
                else
                {
                    item = new ViajeDistribucion {
                        Codigo = codigo
                    };
                    rutas++;

                    Coche vehiculo = null;
                    var   interno  = row.Cells[Properties.DistribucionReginaldLee.Interno].ToString().Trim();
                    if (interno.Length == 3)
                    {
                        interno = "0" + interno;
                    }
                    if (!string.IsNullOrEmpty(interno))
                    {
                        vehiculo = _cochesBuffer.SingleOrDefault(c => c.Interno == interno);
                    }

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

                    item.Empresa      = Empresa;
                    item.Linea        = vehiculo.Linea;
                    item.Vehiculo     = vehiculo;
                    item.Inicio       = date;
                    item.Fin          = date;
                    item.Tipo         = ViajeDistribucion.Tipos.Desordenado;
                    item.RegresoABase = true;
                    item.Estado       = ViajeDistribucion.Estados.Pendiente;
                    item.Alta         = DateTime.UtcNow;
                    item.NumeroViaje  = Convert.ToInt32(nroViaje);

                    listViajes.Add(item);
                }

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

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

                if (item.Detalles.Any(d => d.PuntoEntrega != null && d.PuntoEntrega.Codigo == codCliente))
                {
                    var repetido = item.Detalles.FirstOrDefault(d => d.PuntoEntrega != null && d.PuntoEntrega.Codigo == codCliente);
                    repetido.Bultos += packs;
                    continue;
                }

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

                var puntoEntrega = _puntosBuffer.SingleOrDefault(p => p.Codigo == codCliente);
                if (puntoEntrega == null)
                {
                    var descCliente = row.Cells[Properties.DistribucionReginaldLee.DescripcionCliente].ToString().Trim();

                    var puntoDeInteres = new ReferenciaGeografica
                    {
                        Codigo                   = codCliente,
                        Descripcion              = descCliente,
                        Empresa                  = Empresa,
                        Linea                    = item.Linea,
                        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 = date.Date, Fin = date.AddHours(vigencia)
                        },
                        Icono = Cliente.ReferenciaGeografica.TipoReferenciaGeografica.Icono
                    };

                    if (!rowWithCoords)
                    {
                        try
                        {
                            ThrowProperty("LATITUD_LONGITUD", Llfile.Strategy);
                        }
                        catch (Exception ex)
                        {
                            STrace.Exception(Component, ex, String.Format("Error en Fila #{0}: {1}", filas, ex.Message));
                            continue;
                        }
                    }

                    var posicion = GetNewDireccion(latitud, longitud);

                    var poligono = new Poligono {
                        Radio = 50, Vigencia = new Vigencia {
                            Inicio = date.Date
                        }
                    };
                    poligono.AddPoints(new[] { new PointF((float)longitud, (float)latitud) });

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

                    listReferencias.Add(puntoDeInteres);

                    puntoEntrega = new PuntoEntrega
                    {
                        Cliente              = Cliente,
                        Codigo               = codCliente,
                        Descripcion          = descCliente,
                        Telefono             = string.Empty,
                        Baja                 = false,
                        ReferenciaGeografica = puntoDeInteres,
                        Nomenclado           = true,
                        DireccionNomenclada  = string.Empty,
                        Nombre               = descCliente
                    };
                }
                else
                {
                    if (!rowWithCoords)
                    {
                        try
                        {
                            ThrowProperty("LATITUD_LONGITUD", Llfile.Strategy);
                        }
                        catch (Exception ex)
                        {
                            STrace.Exception(Component, ex, String.Format("Error en Fila #{0}: {1}", filas, ex.Message));
                            continue;
                        }
                    }

                    if (!puntoEntrega.ReferenciaGeografica.IgnoraLogiclink && (puntoEntrega.ReferenciaGeografica.Latitude != latitud || puntoEntrega.ReferenciaGeografica.Longitude != longitud))
                    {
                        puntoEntrega.ReferenciaGeografica.Direccion.Vigencia.Fin = date.Date;
                        puntoEntrega.ReferenciaGeografica.Poligono.Vigencia.Fin  = date.Date;

                        var posicion = GetNewDireccion(latitud, longitud);
                        var poligono = new Poligono {
                            Radio = 50, Vigencia = new Vigencia {
                                Inicio = date.Date
                            }
                        };
                        poligono.AddPoints(new[] { new PointF((float)longitud, (float)latitud) });

                        puntoEntrega.ReferenciaGeografica.AddHistoria(posicion, poligono, date.Date);
                    }

                    if (puntoEntrega.ReferenciaGeografica.Vigencia.Inicio > date.Date)
                    {
                        puntoEntrega.ReferenciaGeografica.Vigencia.Inicio = date.Date;
                    }

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

                    puntoEntrega.ReferenciaGeografica.Linea = item.Linea;
                    listReferencias.Add(puntoEntrega.ReferenciaGeografica);
                }

                listPuntos.Add(puntoEntrega);

                var kms      = 0.0;
                var orden    = item.Detalles.Count - 1;
                var anterior = item.Detalles.FirstOrDefault(d => d.Orden == orden - 1);
                if (anterior != null)
                {
                    kms = GeocoderHelper.CalcularDistacia(anterior.ReferenciaGeografica.Latitude, anterior.ReferenciaGeografica.Longitude, puntoEntrega.ReferenciaGeografica.Latitude, puntoEntrega.ReferenciaGeografica.Longitude);
                }
                var entrega = new EntregaDistribucion
                {
                    Cliente         = puntoEntrega.Cliente,
                    PuntoEntrega    = puntoEntrega,
                    Descripcion     = codEntrega,
                    Estado          = EntregaDistribucion.Estados.Pendiente,
                    Orden           = orden,
                    Programado      = date,
                    ProgramadoHasta = date,
                    TipoServicio    = tipoServicio,
                    Viaje           = item,
                    Bultos          = packs
                };

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

                var maxDate = item.Detalles.Max(d => d.Programado);
                item.Fin = maxDate;

                var ultimo = item.Detalles.Last(e => e.Linea != null);
                ultimo.Programado      = maxDate;
                ultimo.ProgramadoHasta = maxDate;
                ultimo.Orden           = item.Detalles.Count - 1;
            }

            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));
        }
コード例 #4
0
        public void ParseRutas(out int rutas, out int entregas, out string observaciones)
        {
            const int vigencia = 12;

            var te   = new TimeElapsed();
            var rows = ParseExcelFile(Llfile.FilePath, true);

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

            var listViajes        = new List <ViajeDistribucion>();
            var listReferencias   = new List <ReferenciaGeografica>();
            var listPuntosEntrega = new List <PuntoEntrega>();

            rutas         = 0;
            entregas      = 0;
            observaciones = string.Empty;

            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 codigoLinea = "4"; // POR DEFAULT ES MUNRO
                var linea       = _lineasBuffer.SingleOrDefault(l => l.DescripcionCorta == codigoLinea);
                if (linea == null)
                {
                    observaciones = "Valor inválido para el campo LINEA";
                    continue;
                }

                var sFecha        = row[Properties.DistribucionCCU.Fecha].ToString().Trim();
                var planilla      = row[Properties.DistribucionCCU.Planilla].ToString().Trim();
                var codCliente    = row[Properties.DistribucionCCU.CodigoCliente].ToString().Trim();
                var factura       = row[Properties.DistribucionCCU.Factura].ToString().Trim();
                var sHectolitros  = row[Properties.DistribucionCCU.Hectolitros].ToString().Trim().Replace('.', ',');
                var sImporteTotal = row[Properties.DistribucionCCU.ImporteTotal].ToString().Trim().Replace('.', ',');
                var hectolitros   = Convert.ToDouble(sHectolitros);
                var importeTotal  = Convert.ToDouble(sImporteTotal);

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

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

                ViajeDistribucion viaje;

                if (listViajes.Count > 0 && listViajes.Any(v => v.Codigo == planilla))
                {
                    viaje = listViajes.SingleOrDefault(v => v.Codigo == planilla);
                }
                else
                {
                    viaje = new ViajeDistribucion
                    {
                        Empresa      = this.Empresa,
                        Linea        = linea,
                        Codigo       = planilla,
                        Inicio       = fecha,
                        Fin          = fecha,
                        Tipo         = ViajeDistribucion.Tipos.Desordenado,
                        RegresoABase = true,
                        Estado       = ViajeDistribucion.Estados.Pendiente,
                        Alta         = DateTime.UtcNow,
                        NumeroViaje  = 1
                    };

                    listViajes.Add(viaje);
                    rutas++;
                }

                if (viaje.Detalles.Count == 0)
                {
                    //el primer elemento es la base
                    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 llegada = new EntregaDistribucion
                    {
                        Linea           = linea,
                        Descripcion     = linea.Descripcion,
                        Estado          = EntregaDistribucion.Estados.Pendiente,
                        Orden           = viaje.Detalles.Count,
                        Programado      = fecha,
                        ProgramadoHasta = fecha,
                        Viaje           = viaje
                    };
                    viaje.Detalles.Add(llegada);
                }

                if (viaje.Detalles.Where(d => d.PuntoEntrega != null).Any(d => d.PuntoEntrega.Codigo == codCliente))
                {
                    var detalle = viaje.Detalles.Where(d => d.PuntoEntrega != null).SingleOrDefault(d => d.PuntoEntrega.Codigo == codCliente);
                    detalle.Volumen += hectolitros;
                    detalle.Valor    = importeTotal;
                    continue;
                }

                var puntoEntrega = _clientesBuffer.SingleOrDefault(p => p.Codigo == codCliente);

                if (puntoEntrega == null)
                {
                    observaciones = "Valor inválido para el campo PUNTO ENTREGA";
                    continue;
                }
                else
                {
                    var end = fecha.AddHours(vigencia);
                    if (puntoEntrega.ReferenciaGeografica.Vigencia.Fin < end)
                    {
                        puntoEntrega.ReferenciaGeografica.Vigencia.Fin = end;
                    }

                    listReferencias.Add(puntoEntrega.ReferenciaGeografica);
                    listPuntosEntrega.Add(puntoEntrega);
                }

                var entrega = new EntregaDistribucion
                {
                    Cliente         = puntoEntrega.Cliente,
                    PuntoEntrega    = puntoEntrega,
                    Descripcion     = factura,
                    Estado          = EntregaDistribucion.Estados.Pendiente,
                    Orden           = viaje.Detalles.Count - 1,
                    Programado      = fecha,
                    ProgramadoHasta = fecha.AddMinutes(Empresa.MarginMinutes),
                    Viaje           = viaje,
                    Volumen         = hectolitros,
                    Valor           = importeTotal
                };

                viaje.Detalles.Add(entrega);
                entregas++;
            }

            var nroViaje = 0;

            foreach (var viajeDistribucion in listViajes)
            {
                nroViaje++;
                if (viajeDistribucion.Detalles.Count > 0)
                {
                    var dirBase           = viajeDistribucion.Detalles.First().ReferenciaGeografica;
                    var velocidadPromedio = 20;

                    var hora       = viajeDistribucion.Inicio;
                    var nroEntrega = 0;
                    foreach (var detalle in viajeDistribucion.Detalles)
                    {
                        nroEntrega++;
                        STrace.Trace(Component, string.Format("Calculando horarios, viaje {0}/{1}, entrega {2}/{3}", nroViaje, listViajes.Count, nroEntrega, viajeDistribucion.Detalles.Count()));
                        var distancia = GeocoderHelper.CalcularDistacia(dirBase.Latitude, dirBase.Longitude, detalle.ReferenciaGeografica.Latitude, detalle.ReferenciaGeografica.Longitude);
                        var horas     = distancia / velocidadPromedio;
                        var demora    = detalle.TipoServicio != null ? detalle.TipoServicio.Demora : 0;
                        detalle.Programado      = hora.AddHours(horas).AddMinutes(demora);
                        detalle.ProgramadoHasta = detalle.Programado.AddMinutes(Empresa.MarginMinutes);
                        detalle.KmCalculado     = distancia;
                        dirBase = detalle.ReferenciaGeografica;
                        hora    = detalle.Programado;
                    }
                }

                var maxDate = viajeDistribucion.Detalles.Max(d => d.Programado);
                viajeDistribucion.Fin = maxDate;

                var ultimo = viajeDistribucion.Detalles.Last(e => e.Linea != null);
                ultimo.Programado      = maxDate;
                ultimo.ProgramadoHasta = maxDate.AddMinutes(Empresa.MarginMinutes);
                ultimo.Orden           = viajeDistribucion.Detalles.Count - 1;
            }

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

            STrace.Trace(Component, "Guardando puntos de entrega: " + listPuntosEntrega.Count);
            te.Restart();
            foreach (var puntoEntrega in listPuntosEntrega)
            {
                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));
        }
コード例 #5
0
ファイル: AltaTicket.aspx.cs プロジェクト: jesumarquez/lt
        private void RecalcularHoras(int index)
        {
            var delta = GetDeltas();

            DeltaTime.Set(delta);

            var d            = StartDate.Get();
            var saleDePlanta = DateTime.MinValue;
            var saleDeObra   = DateTime.MinValue;

            var coche             = cbMovil.Selected > 0 ? DAOFactory.CocheDAO.FindById(cbMovil.Selected) : null;
            var velocidadPromedio = coche != null ? (coche.VelocidadPromedio > 0 ? coche.VelocidadPromedio
                : (coche.TipoCoche.VelocidadPromedio > 0 ? coche.TipoCoche.VelocidadPromedio : 20))
                                        : 20;

            var direccionLinea = GetDireccionLinea();
            var direccionMapa  = GetDireccionPuntoDeEntrega();

            foreach (C1GridViewRow item in gridEstados.Rows)
            {
                var estadoId = (int)gridEstados.DataKeys[item.RowIndex].Value;
                var estado   = DAOFactory.EstadoDAO.FindById(estadoId);

                if (estado.EsPuntoDeControl == 5)
                {
                    saleDePlanta = d;                               //Sale de Planta
                }
                if (estado.EsPuntoDeControl == 7)
                {
                    saleDeObra = d;                               //Sale de Obra
                }
                //if (item.RowIndex == 0) continue;
                if (item.RowIndex <= index)
                {
                    var txt = item.FindControl("txtHoraEstado") as TextBox;
                    if (txt != null)
                    {
                        d = GetHours(txt.Text, d);
                    }
                    continue;
                }

                if (estado.EsPuntoDeControl == 6 && saleDePlanta != DateTime.MinValue)
                {
                    //Llega a Obra
                    var distancia = direccionLinea != null && direccionMapa != null?
                                    GeocoderHelper.CalcularDistacia(direccionLinea.Latitude, direccionLinea.Longitude, direccionMapa.Latitude, direccionMapa.Longitude)
                                        : 0;

                    var horas = distancia / velocidadPromedio;

                    d = d.Add(horas > 0 ? TimeSpan.FromHours(horas) : delta[item.RowIndex]);

                    var txt = item.FindControl("txtHoraEstado") as TextBox;
                    var lbl = item.FindControl("lblDiaProgramado") as Label;
                    if (txt != null)
                    {
                        txt.Text = d.ToString("HH:mm");
                    }
                    if (lbl != null)
                    {
                        lbl.Text = d.ToString("dd-MM-yyyy");
                    }
                }
                else if (estado.EsPuntoDeControl == 8 && saleDeObra != DateTime.MinValue)
                {
                    ////Llega a Planta

                    var distancia = direccionLinea != null && direccionMapa != null?
                                    GeocoderHelper.CalcularDistacia(direccionMapa.Latitude, direccionMapa.Longitude, direccionLinea.Latitude, direccionLinea.Longitude)
                                        : 0;

                    var horas = distancia / velocidadPromedio;

                    d = d.Add(horas > 0 ? TimeSpan.FromHours(horas) : delta[item.RowIndex]);

                    var txt = item.FindControl("txtHoraEstado") as TextBox;
                    var lbl = item.FindControl("lblDiaProgramado") as Label;
                    if (txt != null)
                    {
                        txt.Text = d.ToString("HH:mm");
                    }
                    if (lbl != null)
                    {
                        lbl.Text = d.ToString("dd-MM-yyyy");
                    }
                }
                else
                {
                    //Normal
                    d = d.Add(delta[item.RowIndex]);

                    var txt = item.FindControl("txtHoraEstado") as TextBox;
                    var lbl = item.FindControl("lblDiaProgramado") as Label;
                    if (txt != null)
                    {
                        txt.Text = d.ToString("HH:mm");
                    }
                    if (lbl != null)
                    {
                        lbl.Text = d.ToString("dd-MM-yyyy");
                    }
                }
            }

            updGridEstados.Update();
        }
コード例 #6
0
        public void Parse(out int rutas, out int entregas, out string observaciones)
        {
            const int vigencia = 12;

            var te   = new TimeElapsed();
            var rows = ParseExcelFile(Llfile.FilePath, true);

            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;
            observaciones = string.Empty;

            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 stringFecha = row[Properties.DistribucionMusimundo.Fecha].ToString().Trim();

                var fecha = new DateTime(Convert.ToInt32(stringFecha.Substring(0, 4)),
                                         Convert.ToInt32(stringFecha.Substring(4, 2)),
                                         Convert.ToInt32(stringFecha.Substring(6, 2)),
                                         Convert.ToInt32(stringFecha.Substring(8, 2)),
                                         0,
                                         0).AddHours(-3);


                var patente      = row[Properties.DistribucionMusimundo.Patente].ToString().Trim();
                var codigoPedido = row[Properties.DistribucionMusimundo.Factura].ToString().Trim();
                var numeroViaje  = Convert.ToInt32(row[Properties.DistribucionMusimundo.TM].ToString().Trim());
                //var secuencia = Convert.ToInt32(row[GetColumnByValue(Fields.Secuencia.Value)]);
                var codigoViaje = string.Format("{0}|{1}|{2}", stringFecha.Substring(0, 8), patente, numeroViaje);
                var strLat      = row[Properties.DistribucionMusimundo.Coord1].ToString().Trim().Replace('.', ',');
                var strLon      = row[Properties.DistribucionMusimundo.Coord2].ToString().Trim().Replace('.', ',');
                var latitud     = Convert.ToDouble(strLat);
                var longitud    = Convert.ToDouble(strLon);
                var importe     = row[Properties.DistribucionMusimundo.Importe].ToString().Trim() != "" ? Convert.ToDouble(row[Properties.DistribucionMusimundo.Importe].ToString().Trim()) : 0.0;
                var nombre      = row[Properties.DistribucionMusimundo.Direccion].ToString().Trim();

                var vehiculo = _cochesBuffer.SingleOrDefault(v => v.Patente.Contains(patente));
                var chofer   = vehiculo != null && !vehiculo.IdentificaChoferes ? vehiculo.Chofer : null;
                var oLinea   = vehiculo != null && vehiculo.Linea != null ? vehiculo.Linea : Linea;
                if (oLinea == null)
                {
                    observaciones = "Valor inválido para el campo LINEA";
                    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;
                }

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

                ViajeDistribucion viaje;

                if (listViajes.Count > 0 && codigoViaje == listViajes.Last().Codigo)
                {
                    viaje = listViajes.Last();
                }
                else
                {
                    #region viaje = new ViajeDistribucion()

                    viaje = new ViajeDistribucion
                    {
                        Empresa      = vehiculo.Empresa,
                        Linea        = oLinea,
                        Vehiculo     = vehiculo,
                        Empleado     = chofer,
                        Codigo       = codigoViaje,
                        Estado       = ViajeDistribucion.Estados.Pendiente,
                        Inicio       = fecha,
                        Fin          = fecha,
                        NumeroViaje  = Convert.ToInt32(numeroViaje),
                        Tipo         = ViajeDistribucion.Tipos.Desordenado,
                        Alta         = DateTime.UtcNow,
                        RegresoABase = true
                    };

                    #endregion

                    listViajes.Add(viaje);
                    rutas++;
                }

                viaje.Fin = fecha;

                if (viaje.Detalles.Count == 0)
                {
                    //el primer elemento es la base
                    var origen = new EntregaDistribucion
                    {
                        Linea           = oLinea,
                        Descripcion     = oLinea.Descripcion,
                        Estado          = EntregaDistribucion.Estados.Pendiente,
                        Orden           = 0,
                        Programado      = fecha,
                        ProgramadoHasta = fecha,
                        Viaje           = viaje
                    };
                    viaje.Detalles.Add(origen);

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

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

                if (puntoEntrega == null)
                {
                    #region var puntoDeInteres = new ReferenciaGeografica()

                    var empresaGeoRef = viaje.Vehiculo != null && viaje.Vehiculo.Empresa == null ? null : Cliente.Empresa == null ? null : Empresa;
                    var lineaGeoRef   = viaje.Vehiculo != null && viaje.Vehiculo.Linea != null
                                            ? viaje.Vehiculo.Linea
                                            : Cliente.Linea ?? oLinea;

                    var puntoDeInteres = new ReferenciaGeografica
                    {
                        Codigo                   = codigoPedido,
                        Descripcion              = codigoPedido,
                        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
                    };

                    #endregion

                    #region var posicion = new Direccion()

                    var posicion = GetNewDireccion(latitud, longitud);

                    #endregion

                    #region var poligono = new Poligono()

                    var poligono = new Poligono {
                        Radio = 100, Vigencia = new Vigencia {
                            Inicio = DateTime.UtcNow
                        }
                    };
                    poligono.AddPoints(new[] { new PointF((float)longitud, (float)latitud) });

                    #endregion

                    puntoDeInteres.AddHistoria(posicion, poligono, DateTime.UtcNow);

                    listReferencias.Add(puntoDeInteres);

                    #region puntoEntrega = new PuntoEntrega()

                    puntoEntrega = new PuntoEntrega
                    {
                        Cliente              = Cliente,
                        Codigo               = codigoPedido,
                        Descripcion          = codigoPedido,
                        Telefono             = string.Empty,
                        Baja                 = false,
                        ReferenciaGeografica = puntoDeInteres,
                        Nomenclado           = true,
                        DireccionNomenclada  = string.Empty,
                        Importe              = importe,
                        Nombre               = nombre
                    };

                    #endregion

                    listPuntos.Add(puntoEntrega);
                }
                else
                {
                    if (!puntoEntrega.ReferenciaGeografica.IgnoraLogiclink && (puntoEntrega.ReferenciaGeografica.Latitude != latitud || puntoEntrega.ReferenciaGeografica.Longitude != longitud))
                    {
                        puntoEntrega.ReferenciaGeografica.Direccion.Vigencia.Fin = DateTime.UtcNow;
                        puntoEntrega.ReferenciaGeografica.Poligono.Vigencia.Fin  = DateTime.UtcNow;

                        #region var posicion = new Direccion()

                        var posicion = GetNewDireccion(latitud, longitud);

                        #endregion

                        #region var poligono = new Poligono()

                        var poligono = new Poligono {
                            Radio = 100, Vigencia = new Vigencia {
                                Inicio = DateTime.UtcNow
                            }
                        };
                        poligono.AddPoints(new[] { new PointF((float)longitud, (float)latitud) });

                        #endregion

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

                    #region puntoEntrega.ReferenciaGeografica.Vigencia.Fin = end

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

                    #endregion


                    puntoEntrega.ReferenciaGeografica.Linea = oLinea;
                    listReferencias.Add(puntoEntrega.ReferenciaGeografica);

                    puntoEntrega.Nombre  = nombre;
                    puntoEntrega.Importe = importe;

                    listPuntos.Add(puntoEntrega);
                }

                #region var entrega = new EntregaDistribucion()

                var entrega = new EntregaDistribucion
                {
                    Cliente      = Cliente,
                    PuntoEntrega = puntoEntrega,
                    Descripcion  = nombre.Length > 128 ? nombre.Substring(0, 128) : nombre,
                    Estado       = EntregaDistribucion.Estados.Pendiente,
                    //Orden = secuencia,
                    Orden           = viaje.Detalles.Count - 1,
                    Programado      = fecha,
                    ProgramadoHasta = fecha.AddMinutes(Empresa.MarginMinutes),
                    TipoServicio    = tipoServicio,
                    Viaje           = viaje
                };

                #endregion

                viaje.Detalles.Add(entrega);
                entregas++;
            }

            foreach (var viajeDistribucion in listViajes)
            {
                if (viajeDistribucion.Detalles.Count > 0)
                {
                    var dirBase = viajeDistribucion.Detalles.First().ReferenciaGeografica;

                    var coche             = viajeDistribucion.Vehiculo;
                    var velocidadPromedio = coche != null && coche.VelocidadPromedio > 0
                        ? coche.VelocidadPromedio
                        : coche != null && coche.TipoCoche.VelocidadPromedio > 0 ? coche.TipoCoche.VelocidadPromedio : 20;

                    var hora = viajeDistribucion.Inicio;
                    foreach (var detalle in viajeDistribucion.Detalles)
                    {
                        var distancia = GeocoderHelper.CalcularDistacia(dirBase.Latitude, dirBase.Longitude, detalle.ReferenciaGeografica.Latitude, detalle.ReferenciaGeografica.Longitude);
                        var horas     = distancia / velocidadPromedio;
                        var demora    = detalle.TipoServicio != null ? detalle.TipoServicio.Demora : 0;
                        detalle.Programado      = hora.AddHours(horas).AddMinutes(demora);
                        detalle.ProgramadoHasta = detalle.Programado.AddMinutes(Empresa.MarginMinutes);
                        detalle.KmCalculado     = distancia;
                        dirBase = detalle.ReferenciaGeografica;
                        hora    = detalle.Programado;
                    }
                }

                var maxDate = viajeDistribucion.Detalles.Max(d => d.Programado);
                viajeDistribucion.Fin = maxDate;

                var ultimo = viajeDistribucion.Detalles.Last(e => e.Linea != null);
                ultimo.Programado      = maxDate;
                ultimo.ProgramadoHasta = maxDate.AddMinutes(Empresa.MarginMinutes);
                ultimo.Orden           = viajeDistribucion.Detalles.Count - 1;
            }

            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));
        }