public ReporteAsignoVo(EntregaDistribucion entrega, OrderDetail detalleOrden) { var vehiculo = entrega.Viaje.Vehiculo; var ptoEntrega = entrega.PuntoEntrega; var cliente = entrega.Cliente ?? entrega.PuntoEntrega.Cliente; Vehiculo = vehiculo.Interno + " - " + vehiculo.Patente; Viaje = entrega.Viaje.Codigo; Cliente = cliente.Codigo + " - " + cliente.Descripcion; PuntoEntrega = ptoEntrega.Codigo + " - " + ptoEntrega.Descripcion; Entrega = entrega.Descripcion; if (detalleOrden != null) { var orden = detalleOrden.Order; Orden = orden.CodigoPedido; Insumo = detalleOrden.Insumo.Descripcion; Cantidad = detalleOrden.Cantidad; Ajuste = detalleOrden.Ajuste; Total = detalleOrden.Total; Cisterna = detalleOrden.Cuaderna; FechaAlta = orden.FechaAlta.ToDisplayDateTime(); FechaPedido = orden.FechaPedido.ToDisplayDateTime(); if (orden.FechaEntrega.HasValue) { FechaEntrega = orden.FechaEntrega.Value.ToDisplayDateTime(); } } else { Orden = "-"; } }
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); }
public EntregaVo(int orden, EntregaDistribucion entregaDistribucion, TimeSpan tiempoRecorrido, double kms, DateTime?desde) { Id = entregaDistribucion.Id; IdViaje = entregaDistribucion.Viaje.Id; IdDispositivo = entregaDistribucion.Viaje.Vehiculo != null && entregaDistribucion.Viaje.Vehiculo.Dispositivo != null ? entregaDistribucion.Viaje.Vehiculo.Dispositivo.Id : 0; Vehiculo = entregaDistribucion.Viaje.Vehiculo != null ? entregaDistribucion.Viaje.Vehiculo.Interno : string.Empty; Viaje = entregaDistribucion.Viaje.Codigo; Fecha = entregaDistribucion.Viaje.Inicio.ToDisplayDateTime().ToString("dd/MM/yyyy"); Orden = entregaDistribucion.Orden; OrdenReal = orden; Entrega = entregaDistribucion.Descripcion; PuntoEntrega = entregaDistribucion.PuntoEntrega != null ? entregaDistribucion.PuntoEntrega.Nombre : string.Empty; Entregas = entregaDistribucion.Linea != null ? 0 : 1; Estado = CultureManager.GetLabel(EntregaDistribucion.Estados.GetLabelVariableName(entregaDistribucion.Estado)); TiempoRecorrido = tiempoRecorrido; var tiempoEntrega = entregaDistribucion.Entrada.HasValue && entregaDistribucion.Salida.HasValue ? entregaDistribucion.Salida.Value.Subtract(entregaDistribucion.Entrada.Value) : new TimeSpan(0); TiempoEntrega = tiempoEntrega.TotalSeconds >= 0 ? tiempoEntrega : new TimeSpan(0); Entrada = entregaDistribucion.Entrada.HasValue ? entregaDistribucion.Entrada.Value.ToDisplayDateTime().ToString("HH:mm") : string.Empty; Salida = entregaDistribucion.Salida.HasValue ? entregaDistribucion.Salida.Value.ToDisplayDateTime().ToString("HH:mm") : string.Empty; Manual = entregaDistribucion.Manual.HasValue ? entregaDistribucion.Manual.Value.ToDisplayDateTime().ToString("HH:mm") : string.Empty; Programado = entregaDistribucion.Programado.ToDisplayDateTime().ToString("HH:mm"); Desvio = entregaDistribucion.Entrada.HasValue ? entregaDistribucion.Entrada.Value.Subtract(entregaDistribucion.Programado) : new TimeSpan(0, 0, 0); Kms = kms; if (entregaDistribucion.Manual.HasValue && entregaDistribucion.Viaje.Vehiculo != null) { Hasta = entregaDistribucion.Manual.Value; if (entregaDistribucion.Orden > 0 && desde.HasValue) { Desde = desde.Value; var dao = new DAOFactory(); var reportDao = new ReportFactory(dao); var maxMonths = entregaDistribucion.Viaje.Vehiculo.Empresa != null ? entregaDistribucion.Viaje.Vehiculo.Empresa.MesesConsultaPosiciones : 3; var eventos = reportDao.MobileEventDAO.GetMobilesEvents(new List <int> { entregaDistribucion.Viaje.Vehiculo.Id }, new[] { 514 }, new List <int> { 0 }, Desde, Hasta, maxMonths); TieneFoto = eventos.Any(); } } }
protected void btGuardar_Click(object sender, EventArgs e) { try { var intercalados = Intercalados.Get(); var id = grid.SelectedIndex > -1 && grid.SelectedIndex < grid.DataKeys.Count ? Convert.ToInt32(grid.DataKeys[grid.SelectedIndex].Value) : -1; if (id <= 0) { return; } var viaje = DAOFactory.ViajeDistribucionDAO.FindById(id); Intercalado intercalado = intercalados.FirstOrDefault(i => i.Id == id); var nuevoDetalle = new EntregaDistribucion { Viaje = viaje, PuntoEntrega = DAOFactory.PuntoEntregaDAO.FindById(cbPuntoEntrega.Selected) }; nuevoDetalle.Cliente = nuevoDetalle.PuntoEntrega.Cliente; nuevoDetalle.Descripcion = nuevoDetalle.PuntoEntrega.Descripcion; nuevoDetalle.Orden = intercalado.Index; nuevoDetalle.Programado = intercalado.Hora; nuevoDetalle.TipoServicio = DAOFactory.TipoServicioCicloDAO.FindById(cbTipoServicio.Selected); viaje.InsertarEntrega(intercalado.Index, nuevoDetalle); DAOFactory.ViajeDistribucionDAO.SaveOrUpdate(viaje); ShowInfo("La entrega se ha intercalado correctamente"); if (InformarPorMail) { try { SendMail(); } catch (Exception ex) { STrace.Exception("Intercalador de Entregas", ex); ShowError("La entrega se ha intercalado correctamente, pero no se pudo enviar el mail"); } } BtnSearchClick(sender, e); } catch (Exception ex) { ShowError(ex); } }
protected void AddMarker(EntregaDistribucion item, string imageUrl) { if (item.ReferenciaGeografica == null) { return; } var id = item.Id.ToString("0"); var latitud = item.ReferenciaGeografica.Latitude; var longitud = item.ReferenciaGeografica.Longitude; var label = item.Programado.ToString("HH:mm"); var marker = MarkerFactory.CreateLabeledMarker("m" + id, imageUrl, latitud, longitud, label); marker.Size = DrawingFactory.GetSize(20, 20); marker.Offset = DrawingFactory.GetOffset(-10, -10); Monitor1.AddMarkers(LayerEntregas, marker); }
private ViajeDistribucion GetViaje(Order order, string routeCode, int idVehicle, DateTime startDateTime, int cycleType, int idVehicleType) { var viaje = DaoFactory.ViajeDistribucionDAO.FindByCodigo(order.Empresa.Id, -1, routeCode); if (viaje != null) { return(viaje); } viaje = new ViajeDistribucion { Empresa = DaoFactory.EmpresaDAO.FindById(order.Empresa.Id), Estado = ViajeDistribucion.Estados.Pendiente, Tipo = ViajeDistribucion.Tipos.Desordenado, Linea = order.Linea, Vehiculo = (idVehicle != -2) ? DaoFactory.CocheDAO.FindById(idVehicle) : null, TipoCicloLogistico = (cycleType != -2) ? DaoFactory.TipoCicloLogisticoDAO.FindById(cycleType) : null, TipoCoche = DaoFactory.TipoCocheDAO.FindById(idVehicleType), Empleado = null, Codigo = routeCode, Inicio = startDateTime, RegresoABase = true, Transportista = (order.Transportista.Id != 0) ? DaoFactory.TransportistaDAO.FindById(order.Transportista.Id) : null }; //base al inicio var entregaBase = new EntregaDistribucion { Linea = viaje.Linea, Descripcion = viaje.Linea.Descripcion, Estado = EntregaDistribucion.Estados.Pendiente, Programado = startDateTime, ProgramadoHasta = startDateTime, Orden = viaje.Detalles.Count, Viaje = viaje, KmCalculado = 0 }; viaje.Detalles.Add(entregaBase); return(viaje); }
public Detalle(EntregaDistribucion entrega) { Id = entrega.Id; Descripcion = entrega.Orden.ToString(); PopupText = string.Format("<div>Punto de Entrega: <span>{5}</span></div><div>Telefono: <span>{6}</span></div><div>Cliente: <span>{4}</span></div><div>Programado: <span>{0}</span><br/>Entrada: <span>{1}</span><br/>Salida: <span>{2}</span><br/>Manual: <span>{3}</span></div>", entrega.Programado.ToDisplayDateTime().ToString("HH:mm"), (entrega.Entrada.HasValue ? entrega.Entrada.Value.ToDisplayDateTime().ToString("HH:mm") : ""), (entrega.Salida.HasValue ? entrega.Salida.Value.ToDisplayDateTime().ToString("HH:mm") : ""), (entrega.Manual.HasValue ? entrega.Manual.Value.ToDisplayDateTime().ToString("HH:mm") : ""), entrega.Cliente != null ? entrega.Cliente.Descripcion: string.Empty, entrega.PuntoEntrega != null ? entrega.PuntoEntrega.Descripcion : entrega.Linea.Descripcion, entrega.PuntoEntrega != null ? entrega.PuntoEntrega.Telefono : string.Empty); Programado = entrega.Programado; Automatico = entrega.Entrada; Latitud = entrega.ReferenciaGeografica.Latitude; Longitud = entrega.ReferenciaGeografica.Longitude; }
public Detalle(EntregaDistribucion entrega) { Id = entrega.Id; Descripcion = entrega.Orden.ToString(); PopupText = string.Format("<div>Cód. Cliente: <span>{6}</span></div><div>Cliente: <span>{5}</span></div><div>Estado: <span>{4}</span></div><div>Programado: <span>{0}</span><br/>Entrada: <span>{1}</span><br/>Salida: <span>{2}</span><br/>Manual: <span>{3}</span></div>", entrega.Programado.ToDisplayDateTime().ToString("HH:mm"), (entrega.Entrada.HasValue ? entrega.Entrada.Value.ToDisplayDateTime().ToString("HH:mm") : ""), (entrega.Salida.HasValue ? entrega.Salida.Value.ToDisplayDateTime().ToString("HH:mm") : ""), (entrega.Manual.HasValue ? entrega.Manual.Value.ToDisplayDateTime().ToString("HH:mm") : ""), CultureManager.GetLabel(EntregaDistribucion.Estados.GetLabelVariableName(entrega.Estado)), entrega.PuntoEntrega.Descripcion, entrega.PuntoEntrega.Codigo); Programado = entrega.Programado; Automatico = entrega.Entrada; Estado = entrega.Estado; Latitud = entrega.ReferenciaGeografica.Latitude; Longitud = entrega.ReferenciaGeografica.Longitude; }
public Detalle(EntregaDistribucion entrega) { Id = entrega.Id; Descripcion = entrega.Orden.ToString(); var evento = string.Empty; if (entrega.Estado == EntregaDistribucion.Estados.NoCompletado && entrega.EventosDistri.Any()) { var msj = entrega.EventosDistri.FirstOrDefault(d => d.LogMensaje.Mensaje.TipoMensaje.DeRechazo); if (msj != null) { evento = " - " + msj.LogMensaje.Mensaje.Descripcion; } PopupText = string.Format("<div>Cód. Cliente: <span>{6}</span></div><div>Cliente: <span>{5}</span></div><div>Estado: <span><a href='../../Rechazos/Rechazo/Index' target='_blank' style='color: black'>{4}</a></span></div><div>Programado: <span>{0}</span><br/>Entrada: <span>{1}</span><br/>Salida: <span>{2}</span><br/>Manual: <span>{3}</span></div>", entrega.Programado.ToDisplayDateTime().ToString("HH:mm"), (entrega.Entrada.HasValue ? entrega.Entrada.Value.ToDisplayDateTime().ToString("HH:mm") : ""), (entrega.Salida.HasValue ? entrega.Salida.Value.ToDisplayDateTime().ToString("HH:mm") : ""), (entrega.Manual.HasValue ? entrega.Manual.Value.ToDisplayDateTime().ToString("HH:mm") : ""), CultureManager.GetLabel(EntregaDistribucion.Estados.GetLabelVariableName(entrega.Estado)) + evento, entrega.PuntoEntrega.Descripcion, entrega.PuntoEntrega.Codigo); } else { PopupText = string.Format("<div>Cód. Cliente: <span>{6}</span></div><div>Cliente: <span>{5}</span></div><div>Estado: <span>{4}</span></div><div>Programado: <span>{0}</span><br/>Entrada: <span>{1}</span><br/>Salida: <span>{2}</span><br/>Manual: <span>{3}</span></div>", entrega.Programado.ToDisplayDateTime().ToString("HH:mm"), (entrega.Entrada.HasValue ? entrega.Entrada.Value.ToDisplayDateTime().ToString("HH:mm") : ""), (entrega.Salida.HasValue ? entrega.Salida.Value.ToDisplayDateTime().ToString("HH:mm") : ""), (entrega.Manual.HasValue ? entrega.Manual.Value.ToDisplayDateTime().ToString("HH:mm") : ""), CultureManager.GetLabel(EntregaDistribucion.Estados.GetLabelVariableName(entrega.Estado)) + evento, entrega.PuntoEntrega.Descripcion, entrega.PuntoEntrega.Codigo); } Programado = entrega.Programado; Automatico = entrega.Entrada; Estado = entrega.Estado; Latitud = entrega.ReferenciaGeografica.Latitude; Longitud = entrega.ReferenciaGeografica.Longitude; }
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; } }
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); }
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 ReporteDistribucionVo(EntregaDistribucion entrega, EntregaDistribucion anterior, int orden, double km, bool verConfirmacion) { var dao = new DAOFactory(); Id = entrega.Viaje.Id; Descripcion = entrega.Descripcion; IdDispositivo = entrega.Viaje.Vehiculo != null && entrega.Viaje.Vehiculo.Dispositivo != null ? entrega.Viaje.Vehiculo.Dispositivo.Id : 0; Ruta = entrega.Viaje.Codigo; TipoVehiculo = entrega.Viaje.Vehiculo != null && entrega.Viaje.Vehiculo.TipoCoche != null ? entrega.Viaje.Vehiculo.TipoCoche.Descripcion : string.Empty; Vehiculo = entrega.Viaje.Vehiculo != null ? entrega.Viaje.Vehiculo.Interno : string.Empty; Empleado = entrega.Viaje.Empleado != null && entrega.Viaje.Empleado.Entidad != null ? entrega.Viaje.Empleado.Entidad.Descripcion : string.Empty; Fecha = entrega.Viaje.Inicio.ToDisplayDateTime().ToString("dd/MM/yyyy"); Orden = entrega.Orden; OrdenReal = orden; PuntoEntrega = entrega.PuntoEntrega != null ? entrega.PuntoEntrega.Descripcion : entrega.ReferenciaGeografica != null ? entrega.ReferenciaGeografica.Descripcion : string.Empty; Manual = entrega.Manual.HasValue ? entrega.Manual.Value.ToDisplayDateTime().ToString("HH:mm") : string.Empty; Entrada = entrega.Entrada.HasValue ? entrega.Entrada.Value.ToDisplayDateTime().ToString("HH:mm") : string.Empty; Salida = entrega.Salida.HasValue ? entrega.Salida.Value.ToDisplayDateTime().ToString("HH:mm") : string.Empty; var diferencia = entrega.Manual.HasValue && entrega.Salida.HasValue ? entrega.Salida.Value.Subtract(entrega.Manual.Value) : new TimeSpan(0); if (diferencia.Ticks != 0) { if (diferencia.TotalSeconds > 0) { Diferencia = diferencia.Hours.ToString("00") + ":" + diferencia.Minutes.ToString("00") + ":" + diferencia.Seconds.ToString("00"); } else { diferencia = new TimeSpan(-diferencia.Ticks); Diferencia = "- " + diferencia.Hours.ToString("00") + ":" + diferencia.Minutes.ToString("00") + ":" + diferencia.Seconds.ToString("00"); } } var duracion = entrega.Entrada.HasValue && entrega.Salida.HasValue ? entrega.Salida.Value.Subtract(entrega.Entrada.Value) : new TimeSpan(0); Duracion = duracion.TotalSeconds > 0 ? duracion.Hours.ToString("00") + ":" + duracion.Minutes.ToString("00") + ":" + duracion.Seconds.ToString("00") : string.Empty; Estado = CultureManager.GetLabel(EntregaDistribucion.Estados.GetLabelVariableName(entrega.Estado)); Km = km; UnreadInactive = entrega.GarminUnreadInactiveAt.HasValue ? entrega.GarminUnreadInactiveAt.Value.ToDisplayDateTime().ToString("HH:mm") : string.Empty; ReadInactive = entrega.GarminReadInactiveAt.HasValue ? entrega.GarminReadInactiveAt.Value.ToDisplayDateTime().ToString("HH:mm") : string.Empty; var reportDao = new ReportFactory(dao); if (entrega.Manual.HasValue && entrega.Viaje.Vehiculo != null) { Hasta = entrega.Manual.Value; if (anterior != null) { if (anterior.Manual.HasValue) { Desde = anterior.Manual.Value; } else if (anterior.Salida.HasValue) { Desde = anterior.Salida.Value; } else { Desde = anterior.Programado; } var maxMonths = entrega.Viaje.Vehiculo.Empresa != null ? entrega.Viaje.Vehiculo.Empresa.MesesConsultaPosiciones : 3; var eventos = reportDao.MobileEventDAO.GetMobilesEvents(new List <int> { entrega.Viaje.Vehiculo.Id }, new[] { 514 }, new List <int> { 0 }, Desde, Hasta, maxMonths); TieneFoto = eventos.Any(); } } if (verConfirmacion && entrega.Viaje.Vehiculo != null) { var mensajes = new List <string> { MessageCode.EstadoLogisticoCumplidoManual.GetMessageCode(), MessageCode.EstadoLogisticoCumplidoManualNoRealizado.GetMessageCode(), MessageCode.EstadoLogisticoCumplidoManualRealizado.GetMessageCode() }; var confirmaciones = dao.MensajeDAO.GetMensajesDeConfirmacion(new[] { entrega.Viaje.Empresa.Id }, new int[] {}).Select(m => m.Codigo); var rechazos = dao.MensajeDAO.GetMensajesDeRechazo(new[] { entrega.Viaje.Empresa.Id }, new int[] {}).Select(m => m.Codigo); mensajes.AddRange(confirmaciones); mensajes.AddRange(rechazos); Confirmacion = entrega.MensajeConfirmacion != null ? entrega.MensajeConfirmacion.Mensaje.Descripcion : string.Empty; Horario = entrega.RecepcionConfirmacion.HasValue ? entrega.RecepcionConfirmacion.Value.ToDisplayDateTime() : (DateTime?)null; var eventos = entrega.EventosDistri.Where(e => mensajes.Contains(e.LogMensaje.Mensaje.Codigo)); var evento = eventos.Any() ? eventos.OrderBy(e => e.Fecha).FirstOrDefault() : null; Distancia = evento != null?Distancias.Loxodromica(evento.LogMensaje.Latitud, evento.LogMensaje.Longitud, entrega.ReferenciaGeografica.Latitude, entrega.ReferenciaGeografica.Longitude) : (double?)null; if (entrega.PuntoEntrega != null && entrega.PuntoEntrega.ReferenciaGeografica != null && entrega.PuntoEntrega.ReferenciaGeografica.Poligono != null) { Radio = entrega.PuntoEntrega.ReferenciaGeografica.Poligono.Radio; } } }
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)); }
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)); }
protected override List <EntregaVo> GetResults() { var inicio = DateTime.UtcNow; try { var results = new List <EntregaVo>(); var viajes = DAOFactory.ViajeDistribucionDAO.GetList(new[] { ddlLocacion.Selected }, new[] { ddlPlanta.Selected }, lbTransportista.SelectedValues, new[] { -1 }, // DEPARTAMENTOS lbCentroDeCostos.SelectedValues, lbSubCentroDeCostos.SelectedValues, lbVehiculo.SelectedValues, new[] { -1 }, // EMPLEADOS new[] { -1 }, // ESTADOS new[] { cbTipoDistribucion.Selected }, SecurityExtensions.ToDataBaseDateTime(dpDesde.SelectedDate.GetValueOrDefault()), SecurityExtensions.ToDataBaseDateTime(dpHasta.SelectedDate.GetValueOrDefault())); foreach (var viajeDistribucion in viajes) { EntregaDistribucion anterior = null; var detalles = viajeDistribucion.Detalles; if (chkVerOrdenManual.Checked) { detalles = viajeDistribucion.GetEntregasPorOrdenManual(); } else if (viajeDistribucion.Tipo == ViajeDistribucion.Tipos.Desordenado) { detalles = viajeDistribucion.GetEntregasPorOrdenReal(); } var orden = 0; foreach (var entrega in detalles) { var tiempoRecorrido = new TimeSpan(0); var kms = 0.0; DateTime?desde = null; if (anterior != null && (entrega.Estado.Equals(EntregaDistribucion.Estados.Completado) || entrega.Estado.Equals(EntregaDistribucion.Estados.Visitado))) { desde = anterior.SalidaOManualExclusiva.HasValue ? anterior.SalidaOManualExclusiva.Value : (DateTime?)null; if (entrega.EntradaOManualExclusiva.HasValue && anterior.SalidaOManualExclusiva.HasValue) { tiempoRecorrido = entrega.EntradaOManualExclusiva.Value.Subtract(anterior.SalidaOManualExclusiva.Value); if (tiempoRecorrido.TotalMinutes < 0) { tiempoRecorrido = new TimeSpan(0); } } if (entrega.Viaje.Vehiculo != null && anterior.FechaMin < entrega.FechaMin && entrega.FechaMin < DateTime.MaxValue) { kms = DAOFactory.CocheDAO.GetDistance(entrega.Viaje.Vehiculo.Id, anterior.FechaMin, entrega.FechaMin); } } results.Add(new EntregaVo(orden, entrega, tiempoRecorrido, kms, desde)); orden++; if (entrega.Estado.Equals(EntregaDistribucion.Estados.Completado) || entrega.Estado.Equals(EntregaDistribucion.Estados.Visitado)) { anterior = entrega; } } } var duracion = (DateTime.UtcNow - inicio).TotalSeconds.ToString("##0.00"); STrace.Trace("Retraso de Ruta", String.Format("Duración de la consulta: {0} segundos", duracion)); return(results); } catch (Exception e) { STrace.Exception("Retraso de Ruta", e); throw; } }
protected void SaveMessage(string messageCode, string text, IEvent data, ViajeDistribucion viaje, EntregaDistribucion entrega) { var point = data.Latitud != 0 && data.Longitud != 0 ? new GPSPoint(data.Date, (float)data.Latitud, (float)data.Longitud) : null; SaveMessage(messageCode, text, point, data.Date, viaje, entrega); }
public override object Parse(int empresa, int linea, IData data) { var oEmpresa = DaoFactory.EmpresaDAO.FindById(empresa); var oCliente = DaoFactory.ClienteDAO.FindById(4186); // RESTO DE MERCADO const int vigencia = 24; var codLinea = data.AsString(Properties.DistribucionF.Centro, 4).Trim(); if (string.IsNullOrEmpty(codLinea)) { ThrowProperty("LINEA"); } var oLinea = DaoFactory.LineaDAO.FindByCodigo(empresa, codLinea); if (oLinea == null) { ThrowProperty("LINEA"); } var ruta = data.AsString(Properties.DistribucionF.Ruta, 8).Trim(); if (string.IsNullOrEmpty(ruta)) { ThrowProperty("RUTA"); } int nroViaje; if (!int.TryParse(ruta.Split(',')[1], out nroViaje)) { ThrowProperty("NUMERO_VIAJE"); } var codEntrega = data.AsString(Properties.DistribucionF.Entrega, 10).Trim(); if (string.IsNullOrEmpty(codEntrega)) { ThrowProperty("ENTREGA"); } var codCliente = data.AsString(Properties.DistribucionF.CodigoCliente, 9).Trim(); if (string.IsNullOrEmpty(codCliente)) { ThrowProperty("CODIGO_CLIENTE"); } var latitud = data.AsDouble(Properties.DistribucionF.Latitud) / 1000000.0; if (!latitud.HasValue) { ThrowProperty("LATITUD"); } var longitud = data.AsDouble(Properties.DistribucionF.Longitud) / 1000000.0; if (!longitud.HasValue) { ThrowProperty("LONGITUD"); } var fecha = data.AsString(Properties.DistribucionF.Fecha, 10).Trim(); if (string.IsNullOrEmpty(fecha)) { ThrowProperty("FECHA"); } var hora = data.AsString(Properties.DistribucionF.Hora, 8).Trim(); if (string.IsNullOrEmpty(hora)) { ThrowProperty("HORA"); } int dia, mes, anio, hr, min, seg; if (!int.TryParse(fecha.Substring(0, 2), out dia)) { ThrowProperty("DIA"); } if (!int.TryParse(fecha.Substring(3, 2), out mes)) { ThrowProperty("MES"); } if (!int.TryParse(fecha.Substring(6, 4), out anio)) { ThrowProperty("AÑO"); } if (!int.TryParse(hora.Substring(0, 2), out hr)) { ThrowProperty("HORA"); } if (hr == 0) { hr = nroViaje <= 1 ? 6 : 12; } if (!int.TryParse(hora.Substring(3, 2), out min)) { ThrowProperty("MINUTO"); } if (!int.TryParse(hora.Substring(6, 2), out seg)) { ThrowProperty("SEGUNDO"); } var gmt = new TimeSpan(-3, 0, 0); var date = new DateTime(anio, mes, dia, hr, min, seg).Subtract(gmt); var cajas = data.AsInt32(Properties.DistribucionF.Cajas); if (!cajas.HasValue) { ThrowProperty("CAJAS"); } var codigo = date.ToString("yyMMdd") + "|" + ruta; var item = GetDistribucion(empresa, linea, codigo); if (data.Operation == (int)Operation.Delete) { return(item); } if (item.Id == 0) { Coche vehiculo = null; var patente = data.AsString(Properties.DistribucionF.Patente, 10).Trim(); if (!string.IsNullOrEmpty(patente)) { vehiculo = DaoFactory.CocheDAO.GetByPatente(new[] { empresa }, new[] { oLinea.Id }, patente); } if (vehiculo == null) { var asig = DaoFactory.PreasignacionViajeVehiculoDAO.FindByCodigo(empresa, oLinea.Id, -1, ruta); if (asig != null) { vehiculo = asig.Vehiculo; } } Empleado empleado = null; var legajo = data.AsString(Properties.DistribucionF.Legajo, 10).Trim(); if (!string.IsNullOrEmpty(legajo)) { empleado = DaoFactory.EmpleadoDAO.GetByLegajo(empresa, oLinea.Id, legajo); } item.Empresa = oEmpresa; item.Linea = oLinea; item.Vehiculo = vehiculo; item.Empleado = empleado; 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); } // 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 = date, ProgramadoHasta = date, Viaje = item }; item.Detalles.Add(origen); var llegada = new EntregaDistribucion { Linea = oLinea, Descripcion = oLinea.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 += cajas.Value; DaoFactory.EntregaDistribucionDAO.SaveOrUpdate(repetido); return(item); } TipoServicioCiclo tipoServicio = null; var tipoServ = DaoFactory.TipoServicioCicloDAO.FindDefault(new[] { empresa }, new[] { linea }); if (tipoServ != null && tipoServ.Id > 0) { tipoServicio = tipoServ; } var puntoEntrega = DaoFactory.PuntoEntregaDAO.GetByCode(new[] { empresa }, new[] { linea }, new[] { -1 }, codCliente); if (puntoEntrega == null) { var descCliente = data.AsString(Properties.DistribucionF.DescripcionCliente, 128).Trim(); if (string.IsNullOrEmpty(descCliente)) { ThrowProperty("NOMBRE_CLIENTE"); } var puntoDeInteres = new ReferenciaGeografica { Codigo = codCliente, Descripcion = descCliente, Empresa = oEmpresa, Linea = oLinea, 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 = date.Date, Fin = date.AddHours(vigencia) }, Icono = oCliente.ReferenciaGeografica.TipoReferenciaGeografica.Icono }; var posicion = GetNewDireccion(latitud.Value, longitud.Value); var poligono = new Poligono { Radio = 50, Vigencia = new Vigencia { Inicio = date.Date } }; poligono.AddPoints(new[] { new PointF((float)longitud.Value, (float)latitud.Value) }); puntoDeInteres.Historia.Add(new HistoriaGeoRef { ReferenciaGeografica = puntoDeInteres, Direccion = posicion, Poligono = poligono, Vigencia = new Vigencia { Inicio = date.Date } }); DaoFactory.ReferenciaGeograficaDAO.SingleSaveOrUpdate(puntoDeInteres); STrace.Trace("QtreeReset", "DistribucionFV1 1"); puntoEntrega = new PuntoEntrega { Cliente = oCliente, Codigo = codCliente, Descripcion = descCliente, Telefono = string.Empty, Baja = false, ReferenciaGeografica = puntoDeInteres, Nomenclado = true, DireccionNomenclada = string.Empty, Nombre = descCliente }; } else { if (!puntoEntrega.ReferenciaGeografica.IgnoraLogiclink && (puntoEntrega.ReferenciaGeografica.Latitude != latitud.Value || puntoEntrega.ReferenciaGeografica.Longitude != longitud.Value)) { puntoEntrega.ReferenciaGeografica.Direccion.Vigencia.Fin = date.Date; puntoEntrega.ReferenciaGeografica.Poligono.Vigencia.Fin = date.Date; var posicion = GetNewDireccion(latitud.Value, longitud.Value); var poligono = new Poligono { Radio = 50, Vigencia = new Vigencia { Inicio = date.Date } }; poligono.AddPoints(new[] { new PointF((float)longitud.Value, (float)latitud.Value) }); puntoEntrega.ReferenciaGeografica.AddHistoria(posicion, poligono, date.Date); } puntoEntrega.ReferenciaGeografica.Vigencia.Inicio = date.Date; var end = date.AddHours(vigencia); if (puntoEntrega.ReferenciaGeografica.Vigencia.Fin < end) { puntoEntrega.ReferenciaGeografica.Vigencia.Fin = end; } DaoFactory.ReferenciaGeograficaDAO.SingleSaveOrUpdate(puntoEntrega.ReferenciaGeografica); STrace.Trace("QtreeReset", "DistribucionFV1 2"); } DaoFactory.PuntoEntregaDAO.SaveOrUpdate(puntoEntrega); var entrega = new EntregaDistribucion { Cliente = puntoEntrega.Cliente, PuntoEntrega = puntoEntrega, Descripcion = codEntrega, Estado = EntregaDistribucion.Estados.Pendiente, Orden = item.Detalles.Count - 1, Programado = date, ProgramadoHasta = date, TipoServicio = tipoServicio, Viaje = item, Bultos = cajas.Value }; item.Detalles.Add(entrega); var maxDate = item.Detalles.Max(d => d.Programado); item.Fin = maxDate; var ultimo = item.Detalles.Last(e => e.Linea != null); if (ultimo.Id > 0) { ultimo.Programado = maxDate; ultimo.ProgramadoHasta = maxDate; ultimo.Orden = item.Detalles.Count - 1; DaoFactory.EntregaDistribucionDAO.SaveOrUpdate(ultimo); } return(item); }
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(); } }
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); }
public override object Parse(int empresa, int linea, IData data) { var oEmpresa = DaoFactory.EmpresaDAO.FindById(empresa); var tipo = data[Properties.DistribucionE.Tipo].Trim(); var nroDoc = data[Properties.DistribucionE.NroDocumento].Trim(); var despacho = data[Properties.DistribucionE.FechaDespacho].Trim(); var generacion = data[Properties.DistribucionE.FechaGeneracion].Trim(); var guardia = data[Properties.DistribucionE.Guardia].Trim(); var latitud = data[Properties.DistribucionE.Latitud].Trim(); var longitud = data[Properties.DistribucionE.Longitud].Trim(); var codigoViaje = DateTime.Today.ToString("ddMMyy") + "|" + guardia; var codigoTarea = tipo + "|" + nroDoc; var empleado = DaoFactory.EmpleadoDAO.FindByLegajo(empresa, -1, guardia); if (empleado == null) { ThrowProperty("EMPLEADO"); } var vehiculo = DaoFactory.CocheDAO.FindByChofer(empleado.Id); if (vehiculo == null) { ThrowProperty("VEHICULO"); } var oLinea = vehiculo.Linea != null ? vehiculo.Linea : empleado.Linea; if (oLinea == null) { ThrowProperty("LINEA"); } var oCliente = DaoFactory.ClienteDAO.GetList(new[] { empresa }, new[] { -1 }).FirstOrDefault(); if (oCliente == null) { ThrowProperty("CLIENTE"); } const int vigencia = 24; var item = GetDistribucion(empresa, oLinea.Id, codigoViaje); if (data.Operation == (int)Operation.Delete) { return(item); } var anioDespacho = Convert.ToInt32(despacho.Substring(0, 4)); var mesDespacho = Convert.ToInt32(despacho.Substring(5, 2)); var diaDespacho = Convert.ToInt32(despacho.Substring(8, 2)); var horaDespacho = Convert.ToInt32(despacho.Substring(11, 2)); var minDespacho = Convert.ToInt32(despacho.Substring(14, 2)); var gmt = new TimeSpan(-3, 0, 0); var fechaDespacho = new DateTime(anioDespacho, mesDespacho, diaDespacho, horaDespacho, minDespacho, 0).Subtract(gmt); var anioGeneracion = Convert.ToInt32(generacion.Substring(0, 4)); var mesGeneracion = Convert.ToInt32(generacion.Substring(5, 2)); var diaGeneracion = Convert.ToInt32(generacion.Substring(8, 2)); var horaGeneracion = Convert.ToInt32(generacion.Substring(11, 2)); var minGeneracion = Convert.ToInt32(generacion.Substring(14, 2)); var fechaGeneracion = new DateTime(anioGeneracion, mesGeneracion, diaGeneracion, horaGeneracion, minGeneracion, 0).Subtract(gmt); if (item.Id == 0) { item.Empresa = oEmpresa; item.Linea = oLinea; item.Vehiculo = vehiculo; item.Inicio = fechaDespacho; item.Fin = fechaDespacho; item.Tipo = ViajeDistribucion.Tipos.Desordenado; item.RegresoABase = false; item.Estado = ViajeDistribucion.Estados.Pendiente; item.Alta = DateTime.UtcNow; item.ProgramacionDinamica = false; item.NumeroViaje = 1; item.Empleado = empleado; item.CentroDeCostos = vehiculo.CentroDeCostos; item.SubCentroDeCostos = vehiculo.SubCentroDeCostos; } // 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 = fechaDespacho, ProgramadoHasta = fechaDespacho, Viaje = item }; item.Detalles.Add(origen); } TipoServicioCiclo tipoServicio = null; var tipoServ = DaoFactory.TipoServicioCicloDAO.FindDefault(new[] { empresa }, new[] { oLinea.Id }); if (tipoServ != null && tipoServ.Id > 0) { tipoServicio = tipoServ; } var lat = Convert.ToDouble(latitud, CultureInfo.InvariantCulture); var lon = Convert.ToDouble(longitud, CultureInfo.InvariantCulture); var puntoEntrega = DaoFactory.PuntoEntregaDAO.GetByCode(new[] { empresa }, new[] { oLinea.Id }, new[] { oCliente.Id }, codigoTarea); 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 = codigoTarea, Descripcion = codigoTarea, 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 = fechaDespacho.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", "DistribucionEV1 1"); puntoEntrega = new PuntoEntrega { Cliente = oCliente, Codigo = codigoTarea, Descripcion = codigoTarea, Telefono = string.Empty, Baja = false, ReferenciaGeografica = puntoDeInteres, Nomenclado = true, DireccionNomenclada = string.Empty, Nombre = codigoTarea }; } 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 = fechaDespacho.AddHours(vigencia); if (puntoEntrega.ReferenciaGeografica.Vigencia.Fin < end) { puntoEntrega.ReferenciaGeografica.Vigencia.Fin = end; } DaoFactory.ReferenciaGeograficaDAO.SingleSaveOrUpdate(puntoEntrega.ReferenciaGeografica); STrace.Trace("QtreeReset", "DistribucionEV1 2"); } DaoFactory.PuntoEntregaDAO.SaveOrUpdate(puntoEntrega); var entrega = new EntregaDistribucion { Cliente = oCliente, PuntoEntrega = puntoEntrega, Descripcion = codigoTarea, Estado = EntregaDistribucion.Estados.Pendiente, Orden = item.Detalles.Count, Programado = fechaDespacho, ProgramadoHasta = fechaDespacho, TipoServicio = tipoServicio, Viaje = item }; item.Detalles.Add(entrega); var lastDetail = item.Detalles.LastOrDefault(); item.Fin = lastDetail == null ? item.Inicio : lastDetail.Programado; return(item); }
protected void SaveMessage(string messageCode, string text, GPSPoint position, DateTime fecha, ViajeDistribucion viaje, EntregaDistribucion entrega) { if (MessageSaver == null) { return; } MessageSaver.Save(null, messageCode, Vehiculo.Dispositivo, Vehiculo, Empleado, fecha, position, text, viaje, entrega); }
public static ViajeDistribucion InsertarEntrega(this ViajeDistribucion distribucion, int index, EntregaDistribucion entrega) { if (index < 0) { index = 0; } if (index < distribucion.Detalles.Count) { distribucion.Detalles.Insert(index, entrega); } else { distribucion.Detalles.Add(entrega); } entrega.Viaje = distribucion; return(distribucion.Renumerar()); }
public override object Parse(int empresa, int linea, IData data) { var oEmpresa = DaoFactory.EmpresaDAO.FindById(empresa); var oLinea = DaoFactory.LineaDAO.FindById(linea); if (oLinea == null) { ThrowProperty("LINEA"); } const int vigencia = 24; var codRuta = data[Properties.DistribucionB.CodigoRuta].Trim(); if (string.IsNullOrEmpty(codRuta)) { ThrowProperty("RUTA"); } var codEntrega = data[Properties.DistribucionB.CodigoEntrega].Trim(); if (string.IsNullOrEmpty(codEntrega)) { ThrowProperty("ENTREGA"); } var codPuntoEntrega = data[Properties.DistribucionB.CodigoPuntoEntrega].Trim(); if (string.IsNullOrEmpty(codPuntoEntrega)) { ThrowProperty("PUNTO_ENTREGA"); } var estado = data[Properties.DistribucionB.Estado].Trim(); var fecha = data[Properties.DistribucionB.Fecha].Trim(); if (string.IsNullOrEmpty(fecha)) { ThrowProperty("FECHA"); } if (fecha.Length != 8) { ThrowProperty("FECHA"); } var hora = data[Properties.DistribucionB.HoraProgramada].Trim(); if (string.IsNullOrEmpty(hora)) { ThrowProperty("HORA"); } if (hora.Length != 8) { ThrowProperty("HORA"); } int dia, mes, anio, hr, min, seg; if (!int.TryParse(fecha.Substring(0, 4), out anio)) { ThrowProperty("AÑO"); } if (!int.TryParse(fecha.Substring(4, 2), out mes)) { ThrowProperty("MES"); } if (!int.TryParse(fecha.Substring(6, 2), out dia)) { ThrowProperty("DIA"); } if (!int.TryParse(hora.Substring(0, 2), out hr)) { ThrowProperty("HORA"); } if (!int.TryParse(hora.Substring(3, 2), out min)) { ThrowProperty("MINUTO"); } if (!int.TryParse(hora.Substring(6, 2), out seg)) { ThrowProperty("SEGUNDO"); } var gmt = new TimeSpan(-3, 0, 0); var date = new DateTime(anio, mes, dia, hr, min, seg).Subtract(gmt); var item = GetDistribucion(empresa, linea, codRuta); if (data.Operation == (int)Operation.Delete) { return(item); } if (!string.IsNullOrEmpty(estado)) { if (item.Id != 0) { var ptoEntrega = item.Detalles.FirstOrDefault(d => d.PuntoEntrega != null && d.Descripcion == codEntrega); if (ptoEntrega == null) { return(item); } item.Detalles.Remove(ptoEntrega); DaoFactory.EntregaDistribucionDAO.Delete(ptoEntrega); } return(item); } if (item.Id == 0) { Coche vehiculo = null; var interno = data[Properties.DistribucionB.Interno].Trim(); if (!string.IsNullOrEmpty(interno)) { vehiculo = DaoFactory.CocheDAO.GetByInternoEndsWith(new[] { empresa }, new[] { linea }, interno); if (vehiculo == null) { STrace.Error("Logiclink", string.Format("Interno {0} no encontrado para el viaje: {1}", interno, codRuta)); } } else { STrace.Error("Logiclink", "Interno vacío para el viaje: " + codRuta); } item.Empresa = oEmpresa; item.Linea = oLinea; 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 = 1; } // 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 = date, ProgramadoHasta = date, Viaje = item }; item.Detalles.Add(origen); var llegada = new EntregaDistribucion { Linea = oLinea, Descripcion = oLinea.Descripcion, Estado = EntregaDistribucion.Estados.Pendiente, Orden = item.Detalles.Count, Programado = date, ProgramadoHasta = date, Viaje = item }; item.Detalles.Add(llegada); } TipoServicioCiclo tipoServicio = null; var tipoServ = DaoFactory.TipoServicioCicloDAO.FindDefault(new[] { empresa }, new[] { linea }); if (tipoServ != null && tipoServ.Id > 0) { tipoServicio = tipoServ; } var puntoEntrega = DaoFactory.PuntoEntregaDAO.GetByCode(new[] { empresa }, new[] { linea }, new[] { -1 }, codPuntoEntrega); if (puntoEntrega == null) { ThrowProperty("PUNTO_ENTREGA_INEXISTENTE"); } else { var end = date.AddHours(vigencia); puntoEntrega.ReferenciaGeografica.Vigencia.Inicio = date.Date.ToDataBaseDateTime(); if (puntoEntrega.ReferenciaGeografica.Vigencia.Fin < end) { puntoEntrega.ReferenciaGeografica.Vigencia.Fin = end; } DaoFactory.ReferenciaGeograficaDAO.SingleSaveOrUpdate(puntoEntrega.ReferenciaGeografica); STrace.Trace("QtreeReset", "DistribucionBV1"); DaoFactory.PuntoEntregaDAO.SaveOrUpdate(puntoEntrega); } var entrega = new EntregaDistribucion { Cliente = puntoEntrega.Cliente, PuntoEntrega = puntoEntrega, Descripcion = codEntrega, Estado = EntregaDistribucion.Estados.Pendiente, Orden = item.Detalles.Count - 1, Programado = date, ProgramadoHasta = date, TipoServicio = tipoServicio, Viaje = item }; item.Detalles.Add(entrega); var maxDate = item.Detalles.Max(d => d.Programado); item.Fin = maxDate; var ultimo = item.Detalles.Last(e => e.Linea != null); if (ultimo.Id > 0) { ultimo.Programado = maxDate; ultimo.ProgramadoHasta = maxDate; ultimo.Orden = item.Detalles.Count - 1; DaoFactory.EntregaDistribucionDAO.SaveOrUpdate(ultimo); } return(item); }
private void ProcessDistribucionPorGps(ViajeDistribucion distribucion) { var entregas = distribucion.Detalles; var mensajes = new List <string> { MessageCode.EstadoLogisticoCumplidoManual.GetMessageCode(), MessageCode.EstadoLogisticoCumplidoManualNoRealizado.GetMessageCode(), MessageCode.EstadoLogisticoCumplidoManualRealizado.GetMessageCode() }; var confirmaciones = DaoFactory.MensajeDAO.GetMensajesDeConfirmacion(new[] { distribucion.Empresa.Id }, new int[] { }).Select(m => m.Codigo); var rechazos = DaoFactory.MensajeDAO.GetMensajesDeRechazo(new[] { distribucion.Empresa.Id }, new int[] { }).Select(m => m.Codigo); mensajes.AddRange(confirmaciones); mensajes.AddRange(rechazos); EntregaDistribucion anterior = null; if (distribucion.Tipo == ViajeDistribucion.Tipos.Desordenado) { entregas = distribucion.GetEntregasPorOrdenReal(); } var orden = 0; foreach (var entrega in entregas) { var te = new TimeElapsed(); var tiempoRecorrido = new TimeSpan(0); var kms = 0.0; if (anterior != null && (entrega.Estado.Equals(EntregaDistribucion.Estados.Completado) || entrega.Estado.Equals(EntregaDistribucion.Estados.Visitado))) { if (entrega.EntradaOManualExclusiva.HasValue && anterior.SalidaOManualExclusiva.HasValue) { tiempoRecorrido = entrega.EntradaOManualExclusiva.Value.Subtract(anterior.SalidaOManualExclusiva.Value); if (tiempoRecorrido.TotalMinutes < 0) { tiempoRecorrido = new TimeSpan(0); } } if (entrega.Viaje.Vehiculo != null && anterior.FechaMin < entrega.FechaMin && entrega.FechaMin < DateTime.MaxValue) { var dm = DaoFactory.DatamartDAO.GetMobilesKilometers(anterior.FechaMin, entrega.FechaMin, new List <int> { entrega.Viaje.Vehiculo.Id }).FirstOrDefault(); kms = dm != null ? dm.Kilometers : 0.0; //kms = DaoFactory.CocheDAO.GetDistance(entrega.Viaje.Vehiculo.Id, anterior.FechaMin, entrega.FechaMin); } } var tiempoEntrega = entrega.Salida.HasValue && entrega.Entrada.HasValue ? entrega.Salida.Value.Subtract(entrega.Entrada.Value) : new TimeSpan(); var desvio = entrega.Entrada.HasValue ? entrega.Entrada.Value.Subtract(entrega.Programado) : new TimeSpan(); var eventos = entrega.EventosDistri.Where(e => mensajes.Contains(e.LogMensaje.Mensaje.Codigo)); var evento = eventos.Any() ? eventos.OrderBy(e => e.Fecha).FirstOrDefault() : null; var distancia = evento != null?Distancias.Loxodromica(evento.LogMensaje.Latitud, evento.LogMensaje.Longitud, entrega.ReferenciaGeografica.Latitude, entrega.ReferenciaGeografica.Longitude) : (double?)null; var registro = new DatamartDistribucion { Empresa = entrega.Viaje.Empresa, Linea = entrega.Linea, Vehiculo = entrega.Viaje.Vehiculo, CentroDeCostos = entrega.Viaje.CentroDeCostos, Viaje = entrega.Viaje, Detalle = entrega, Fecha = entrega.Viaje.Inicio, Ruta = entrega.Viaje.Codigo.Trim(), Entrega = entrega.Descripcion.Trim().Length > 50 ? entrega.Descripcion.Trim().Substring(0, 50) : entrega.Descripcion.Trim(), IdEstado = entrega.Estado, Estado = CultureManager.GetLabel(EntregaDistribucion.Estados.GetLabelVariableName(entrega.Estado)), Km = kms, Recorrido = tiempoRecorrido.TotalMinutes, TiempoEntrega = tiempoEntrega.TotalSeconds > 0 ? tiempoEntrega.TotalMinutes : 0.0, Entrada = entrega.Entrada, Salida = entrega.Salida, Manual = entrega.Manual, Programado = entrega.Programado, Desvio = desvio.TotalMinutes, Orden = orden, Importe = 0.0f, PuntoEntrega = entrega.PuntoEntrega, Confirmacion = entrega.MensajeConfirmacion != null ? entrega.MensajeConfirmacion.Mensaje.Descripcion : string.Empty, Cliente = entrega.PuntoEntrega != null && entrega.PuntoEntrega.Cliente != null ? entrega.PuntoEntrega.Cliente.Descripcion : string.Empty, Distancia = distancia }; DaoFactory.DatamartDistribucionDAO.Save(registro); orden++; if (entrega.Estado.Equals(EntregaDistribucion.Estados.Completado) || entrega.Estado.Equals(EntregaDistribucion.Estados.Visitado)) { anterior = entrega; } } }
protected void SaveMessage(string messageCode, DateTime fecha, ViajeDistribucion viaje, EntregaDistribucion entrega) { SaveMessage(messageCode, string.Empty, null, fecha, viaje, entrega); }
public override object Parse(int empresa, int linea, IData data) { var item = GetDistribucion(empresa, linea, data); if (data.Operation == (int)Operation.Delete) { return(item); } var modificaCabecera = data.AsBool(Properties.Distribucion.ModificaCabecera) ?? true; var gmt = data.AsInt32(Properties.Distribucion.Gmt) ?? 0; if (item.Id == 0 || modificaCabecera) { if (item.Id == 0) { item.Empresa = DaoFactory.EmpresaDAO.FindById(empresa); item.Linea = linea > 0 ? DaoFactory.LineaDAO.FindById(linea) : null; item.Alta = DateTime.UtcNow; } var codigoLinea = data.AsString(Properties.Distribucion.Linea, 8); if (codigoLinea != null) { item.Linea = GetLinea(empresa, codigoLinea) ?? item.Linea; linea = item.Linea != null ? item.Linea.Id : -1; } var interno = data.AsString(Properties.Distribucion.Vehiculo, 32); if (interno != null) { var vehiculo = DaoFactory.CocheDAO.FindByInterno(new[] { empresa }, new[] { linea }, interno); if (vehiculo != null) { item.Vehiculo = vehiculo; } } var legajo = data.AsString(Properties.Distribucion.Empleado, 10); if (legajo != null) { var empleado = DaoFactory.EmpleadoDAO.FindByLegajo(empresa, linea, legajo); if (empleado != null) { item.Empleado = empleado; } } var fecha = data.AsDateTime(Properties.Distribucion.Fecha, gmt); if (!fecha.HasValue) { ThrowProperty("Fecha"); } item.Inicio = fecha.Value; var tipo = data.AsString(Properties.Distribucion.TipoCiclo, 1) ?? "N"; switch (tipo) { case "R": item.Tipo = ViajeDistribucion.Tipos.RecorridoFijo; break; case "D": item.Tipo = ViajeDistribucion.Tipos.Desordenado; break; default: item.Tipo = ViajeDistribucion.Tipos.Ordenado; break; } var regresaABase = data.AsBool(Properties.Distribucion.RegresaABase); if (regresaABase.HasValue) { item.RegresoABase = regresaABase.Value; } } // Entregas if (item.Detalles.Count == 0) { //Si no existe, agrego la slida de base var salidaBase = new EntregaDistribucion { Descripcion = item.Linea.Descripcion, Linea = item.Linea, Viaje = item, Programado = item.Inicio, ProgramadoHasta = item.Inicio }; item.Detalles.Add(salidaBase); } else if (item.Detalles.Count > 1) { //Si existe, elimino la llegada a base (despues la vuelvo a agregar si hace falta). var last = item.Detalles.Last(); if (last.Linea != null) { item.Detalles.RemoveAt(item.Detalles.Count - 1); } } var codigoCliente = data.AsString(Properties.Distribucion.Cliente, 32); var codigoPuntoEntrega = data.AsString(Properties.Distribucion.PuntoEntrega, 32); var codigoTipoServicio = data.AsString(Properties.Distribucion.TipoServicio, 64); var programado = data.AsDateTime(Properties.Distribucion.Programado, gmt); if (programado.HasValue && item.Inicio.Subtract(programado.Value).TotalHours > 24) { programado = item.Inicio.Date.AddHours(programado.Value.Hour).AddMinutes(programado.Value.Minute); } var orden = data.AsInt32(Properties.Distribucion.Orden); if (string.IsNullOrEmpty(codigoCliente)) { ThrowProperty("Cliente"); } if (string.IsNullOrEmpty(codigoPuntoEntrega)) { ThrowProperty("PuntoEntrega"); } var cliente = DaoFactory.ClienteDAO.FindByCode(new[] { empresa }, new[] { linea }, codigoCliente); if (cliente == null) { ThrowProperty("Cliente"); } var puntoEntrega = DaoFactory.PuntoEntregaDAO.FindByCode(new[] { empresa }, new[] { linea }, new[] { cliente.Id }, codigoPuntoEntrega); if (puntoEntrega == null) { ThrowProperty("PuntoEntrega"); } var tipoServicio = string.IsNullOrEmpty(codigoTipoServicio) ? null : DaoFactory.TipoServicioCicloDAO.FindByCode(new[] { empresa }, new[] { linea }, codigoTipoServicio); var entrega = new EntregaDistribucion { Viaje = item, Cliente = cliente, PuntoEntrega = puntoEntrega, TipoServicio = tipoServicio, Orden = item.Detalles.Count, Descripcion = puntoEntrega.Descripcion }; item.Detalles.Add(entrega); if (programado.HasValue) { entrega.Programado = programado.Value; entrega.ProgramadoHasta = programado.Value; } else { CalcularHorarioPorDistancia(item); } if (item.RegresoABase) { // Si regresa a base, agrego la llegada var regresoBase = new EntregaDistribucion { Descripcion = item.Linea.Descripcion, Linea = item.Linea, Viaje = item, Programado = item.Inicio, ProgramadoHasta = item.Inicio, Orden = item.Detalles.Count }; item.Detalles.Add(regresoBase); CalcularHorarioPorDistancia(item); } var lastDetail = item.Detalles.LastOrDefault(); item.Fin = lastDetail == null ? item.Inicio : lastDetail.Programado; return(item); }
public LogMensajeBase Save(IMessage evento, string codigo, Dispositivo dispositivo, Coche coche, Empleado chofer, DateTime fecha, GPSPoint inicio, string texto, ViajeDistribucion viaje, EntregaDistribucion entrega) { return(Save(evento, codigo, dispositivo, coche, chofer, fecha, inicio, null, texto, null, null, null, null, viaje, entrega)); }
protected override List <ReporteDistribucionVo> GetResults() { var inicio = DateTime.UtcNow; try { var results = new List <ReporteDistribucionVo>(); if (ddlRuta.Selected > 0) { var dms = DAOFactory.DatamartDistribucionDAO.GetRecords(ddlRuta.Selected); foreach (var dm in dms) { results.Add(new ReporteDistribucionVo(dm, chkVerConfirmacion.Checked)); } return(results); } if (QueryExtensions.IncludesAll(ddlVehiculo.SelectedValues)) { ddlVehiculo.ToogleItems(); } if (ddlEstados.SelectedStringValues.Count == 0) { ddlEstados.ToogleItems(); } var desde = dpDesde.SelectedDate.Value.ToDataBaseDateTime(); var hasta = dpHasta.SelectedDate.Value.ToDataBaseDateTime(); var sql = DAOFactory.DatamartDistribucionDAO.GetReporteDistribucion(ddlLocacion.Selected, ddlPlanta.Selected, ddlVehiculo.SelectedValues, ddlPuntoEntrega.Selected, ddlEstados.SelectedStringValues.Count > 0 ? ddlEstados.SelectedValues : new List <int> { -1 }, desde, hasta); sql.SetResultTransformer(Transformers.AliasToBean(typeof(ReporteDistribucionVo))); var report = sql.List <ReporteDistribucionVo>(); results = report.Select(r => new ReporteDistribucionVo(r)).ToList(); if (hasta > DateTime.Today.ToDataBaseDateTime()) { var viajesDeHoy = DAOFactory.ViajeDistribucionDAO.GetList(ddlLocacion.SelectedValues, ddlPlanta.SelectedValues, ddlTransportista.SelectedValues, new[] { -1 }, // DEPARTAMENTOS new[] { -1 }, // CENTROS DE COSTO new[] { -1 }, // SUB CENTROS DE COSTO ddlVehiculo.SelectedValues, new[] { -1 }, // EMPLEADOS new[] { -1 }, // ESTADOS DateTime.Today.ToDataBaseDateTime(), hasta) .Where(e => e.Id == ddlRuta.Selected || ddlRuta.Selected == 0); foreach (var viaje in viajesDeHoy) { EntregaDistribucion anterior = null; var estados = ddlEstados.SelectedValues; var detalles = viaje.Detalles; if (chkVerOrdenManual.Checked) { detalles = viaje.GetEntregasPorOrdenManual(); } else if (viaje.Tipo == ViajeDistribucion.Tipos.Desordenado) { detalles = viaje.GetEntregasPorOrdenReal(); } detalles = detalles.Where(e => ddlPuntoEntrega.Selected == 0 || (e.PuntoEntrega != null && e.PuntoEntrega.Id == ddlPuntoEntrega.Selected)) .Where(e => estados.Contains(e.Estado)) .ToList(); var orden = 0; foreach (var entrega in detalles) { var kms = 0.0; if (anterior != null && !entrega.Estado.Equals(EntregaDistribucion.Estados.Cancelado) && !entrega.Estado.Equals(EntregaDistribucion.Estados.NoCompletado) && !entrega.Estado.Equals(EntregaDistribucion.Estados.SinVisitar) && entrega.Viaje.Vehiculo != null && anterior.FechaMin < entrega.FechaMin && entrega.FechaMin < DateTime.MaxValue) { kms = DAOFactory.CocheDAO.GetDistance(entrega.Viaje.Vehiculo.Id, anterior.FechaMin, entrega.FechaMin); } results.Add(new ReporteDistribucionVo(entrega, anterior, orden, kms, chkVerConfirmacion.Checked)); orden++; if (!entrega.Estado.Equals(EntregaDistribucion.Estados.Cancelado) && !entrega.Estado.Equals(EntregaDistribucion.Estados.NoCompletado) && !entrega.Estado.Equals(EntregaDistribucion.Estados.SinVisitar)) { anterior = entrega; } } } } var duracion = (DateTime.UtcNow - inicio).TotalSeconds.ToString("##0.00"); STrace.Trace("Estado de Entregas", String.Format("Duración de la consulta: {0} segundos", duracion)); return(results); } catch (Exception e) { STrace.Exception("Estado de Entregas", e); throw; } }
public LogMensajeBase Save(IMessage evento, string codigo, Dispositivo dispositivo, Coche coche, Empleado chofer, DateTime fecha, GPSPoint inicio, GPSPoint fin, string texto, int?velPermitida, int?velAlcanzada, int?idReferenciaGeografica, Zona zonaManejo, ViajeDistribucion viaje, EntregaDistribucion entrega) { try { var device = dispositivo ?? DaoFactory.DispositivoDAO.GetGenericDevice(coche.Empresa); var driver = chofer ?? (coche != null && !coche.IdentificaChoferes ? coche.Chofer : null); if (string.IsNullOrEmpty(codigo.Trim())) { return(null); } var mensaje = DaoFactory.MensajeDAO.GetByCodigo(codigo, coche != null ? coche.Empresa : null, coche != null ? coche.Linea : null); if (mensaje == null) { return(DiscardDueToInvalidMessage(codigo, coche, inicio, device, fin, driver, fecha)); } var ticket = DaoFactory.TicketDAO.FindEnCurso(dispositivo); var detalleTicket = ticket == null ? null : ticket.GetDetalleProximo(); driver = driver ?? (ticket != null ? ticket.Empleado : null); if (mensaje.Acceso >= Usuario.NivelAcceso.SysAdmin) { return(null); //var log = new LogMensajeAdmin //{ // Chofer = driver, // Coche = coche, // Dispositivo = device, // Estado = 0, // Fecha = fecha, // FechaAlta = DateTime.UtcNow, // Expiracion = DateTime.UtcNow.AddDays(1), // Horario = ticket, // DetalleHorario = detalleTicket, // Usuario = null, // Latitud = inicio != null ? inicio.Lat : 0, // Longitud = inicio != null ? inicio.Lon : 0, // FechaFin = fin != null ? fin.Date : (DateTime?)null, // LatitudFin = fin != null ? new Double?(fin.Lat) : null, // LongitudFin = fin != null ? new Double?(fin.Lon) : null, // VelocidadAlcanzada = velAlcanzada, // VelocidadPermitida = velPermitida, // IdPuntoDeInteres = idReferenciaGeografica, // Mensaje = DaoFactory.MensajeDAO.FindById(mensaje.Id), // Texto = String.Concat(mensaje.Texto, ' ', texto), // TieneFoto = codigo == ((int)MessageIdentifier.Picture).ToString(CultureInfo.InvariantCulture) //}; //ProcessActions(log); //return log; } else { var log = new LogMensaje { Chofer = driver, Coche = coche, Dispositivo = device, Estado = 0, Fecha = fecha, FechaAlta = DateTime.UtcNow, Expiracion = DateTime.UtcNow.AddDays(1), Horario = ticket, DetalleHorario = detalleTicket, Usuario = null, Latitud = inicio != null ? inicio.Lat : 0, Longitud = inicio != null ? inicio.Lon : 0, FechaFin = fin != null ? fin.Date : (DateTime?)null, LatitudFin = fin != null ? new Double?(fin.Lat) : null, LongitudFin = fin != null ? new Double?(fin.Lon) : null, VelocidadAlcanzada = velAlcanzada, VelocidadPermitida = velPermitida, IdPuntoDeInteres = idReferenciaGeografica, Mensaje = DaoFactory.MensajeDAO.FindById(mensaje.Id), Texto = String.Concat(mensaje.Texto, ' ', texto), TieneFoto = codigo == ((int)MessageIdentifier.Picture).ToString(CultureInfo.InvariantCulture), Viaje = viaje, Entrega = entrega }; ProcessActions(log); if (MessageIdentifierX.IsEngineOnOffEvent(log.Mensaje)) { DaoFactory.LastVehicleEventDAO.Save(log, Coche.Totalizador.EstadoMotor); } else if (MessageIdentifierX.IsGarminOnOffEvent(log.Mensaje)) { DaoFactory.LastVehicleEventDAO.Save(log, Coche.Totalizador.EstadoGarmin); } else if (MessageIdentifierX.IsPrivacyOnOffEvent(log.Mensaje)) { DaoFactory.LastVehicleEventDAO.Save(log, Coche.Totalizador.EstadoGps); } return(log); } } catch (Exception ex) { STrace.Exception(GetType().FullName, ex); return(null); } }