Esempio n. 1
0
        public async Task <ActionResult> AddToEvent(int eventId, int orderId)
        {
            var newOrderEvent = new EventOrderModel
            {
                EventId      = eventId,
                OrderId      = orderId,
                Participated = false
            };

            Db.EventOrderModels.Add(newOrderEvent);

            var email      = ConfigurationManager.AppSettings["ManotonAdmin"].ToString();
            var ambassador = await Db.AmbassadorModels.FirstOrDefaultAsync(p => p.Email == email);

            var order = await Db.OrderModels.FirstOrDefaultAsync(p => p.Id == orderId);

            AmbassadorModel oldAmbassador = order.OrderAmbassador;

            order.OrderAmbassador = ambassador;

            order.Status            = OrderStatus.PreAssigned;
            order.StatusLastUpdated = DateTime.UtcNow;
            if (User != null)
            {
                order.LogMessage(User, $"Change ambassador from {(oldAmbassador != null ? oldAmbassador.Email : "no-data")} to {ambassador.Email}");
            }

            await Db.SaveChangesAsync();

            return(RedirectToAction("AssignEvent", new { orderId }));
        }
        public async Task SendAmbassadorChangedNotification(OrderModel order, AmbassadorModel oldAmbassador, AmbassadorModel newAmbassador)
        {
            var mailMessage = new MailMessage
            {
                From    = _fromEmail,
                Subject = $"[Atomic Limbs] Nuevo pedido (#{order.Id})",
                To      = newAmbassador.Email,
                Body    = CompiledTemplateEngine.Render("Mails.OrderNewAmbassador", order),
            };
            await AzureQueue.EnqueueAsync(mailMessage);

            if (oldAmbassador != null && oldAmbassador != newAmbassador) //tenia otro embajador
            {
                order.OrderAmbassador = oldAmbassador;

                mailMessage = new MailMessage
                {
                    From    = _fromEmail,
                    Subject = $"[Atomic Limbs] Cambio de embajador (pedido #{order.Id})",
                    To      = oldAmbassador.Email,
                    Body    = CompiledTemplateEngine.Render("Mails.OrderNewAmbassadorToOldAmbassador", order),
                };
                await AzureQueue.EnqueueAsync(mailMessage);

                order.OrderAmbassador = newAmbassador;
            }
        }
        public void Remove(AmbassadorModel entity)
        {
            var obj = _context.AmbassadorModels.Find(entity.Id);

            _context.AmbassadorModels.Remove(obj);
            _context.SaveChanges();
        }
Esempio n. 4
0
        public async Task <ActionResult> AssignAmbassadorAuto(int id)
        {
            OrderModel order = await Db.OrderModels.Include(p => p.OrderRequestor).FirstOrDefaultAsync(p => p.Id == id);

            if (order == null)
            {
                return(HttpNotFound());
            }

            AmbassadorModel closestAmbassador = await _os.GetAmbassadorAutoAssignAsync(order);

            if (closestAmbassador == null)
            {
                TempData["msg"] = "No se han encontrado embajadores cercanos para asignar automáticamente";
                return(RedirectToAction("Details", "Orders", new { order.Id, area = "" }));
            }

            var result = await _os.AssignmentAmbassadorAsync(closestAmbassador.Id, id, User, _ns);

            if (!result)
            {
                return(HttpNotFound());
            }

            return(RedirectToAction("Index"));
        }
Esempio n. 5
0
        public async Task <ActionResult> EditStatus(int orderId, OrderStatus newStatus, string returnUrl)
        {
            if (newStatus == OrderStatus.PreAssigned)
            {
                return(new HttpUnauthorizedResult("use admin panel to assign ambassador"));
            }

            var order = await Db.OrderModels.Include(x => x.OrderAmbassador).Include(x => x.OrderRequestor).FirstOrDefaultAsync(x => x.Id == orderId);

            if (order == null)
            {
                return(HttpNotFound());
            }

            if (!CanEditOrder(order))
            {
                return(HttpNotFound());
            }

            var oldStatus = order.Status;

            if (newStatus == OrderStatus.NotAssigned)
            {
                order.OrderAmbassador = null;
            }

            if (newStatus == OrderStatus.Rejected)
            {
                Db.OrderRefusedModels.Add(new OrderRefusedModels
                {
                    OrderId      = order.Id,
                    AmbassadorId = order.OrderAmbassador.Id,
                    Date         = DateTime.Now
                });
            }

            order.Status            = newStatus;
            order.StatusLastUpdated = DateTime.UtcNow;
            order.LogMessage(User, $"Change status from {oldStatus} to {newStatus}");

            Db.OrderModels.AddOrUpdate(order);
            await Db.SaveChangesAsync();

            await _ns.SendStatusChangeNotification(order, oldStatus, newStatus);

            //Luego de actualizar el estado a rejected (SaveChanges)
            if (newStatus == OrderStatus.Rejected)
            {
                AmbassadorModel ambassador = await _os.GetAmbassadorAutoAssignAsync(order);

                if (ambassador != null)
                {
                    await _os.AssignmentAmbassadorAsync(ambassador.Id, order.Id, User, _ns);
                }
            }

            return(RedirectToLocal(returnUrl));
        }
        private void ValidateData(AmbassadorModel ambassadorModel, bool?termsAndConditions)
        {
            ModelState[nameof(ambassadorModel.Id)]?.Errors.Clear();
            ModelState[nameof(ambassadorModel.UserId)]?.Errors.Clear();
            ModelState[nameof(ambassadorModel.Email)]?.Errors.Clear();

            if (ambassadorModel.Birth > DateTime.UtcNow.AddYears(-AmbassadorModel.MinYear))
            {
                ModelState.AddModelError(nameof(ambassadorModel.Birth), $@"Debes ser mayor de {AmbassadorModel.MinYear} años.");
            }

            if (termsAndConditions.HasValue && !termsAndConditions.Value)
            {
                ModelState.AddModelError(nameof(termsAndConditions), @"Debe aceptar terminos y condiciones.");
            }
        }
        public async Task <ActionResult> Create(AmbassadorModel ambassadorModel, bool?termsAndConditions)
        {
            if (!User.IsInRole(AppRoles.Administrator))
            {
                ambassadorModel.Email  = User.Identity.GetUserName();
                ambassadorModel.UserId = User.Identity.GetUserId();
            }

            ValidateData(ambassadorModel, termsAndConditions);
            ViewBag.TermsAndConditions = termsAndConditions;
            if (!ModelState.IsValid)
            {
                return(View("Create", ambassadorModel));
            }

            var pointAddress = ambassadorModel.Country + ", " + ambassadorModel.City + ", " + ambassadorModel.Address;

            ambassadorModel.Location = Geolocalization.GetPoint(pointAddress);

            if (ambassadorModel.Id == 0 && (User.IsInRole(AppRoles.Unassigned) || User.IsInRole(AppRoles.Administrator)))
            {
                //CREATE
                var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(Db));
                await userManager.RemoveFromRoleAsync(ambassadorModel.UserId, AppRoles.Unassigned);

                await userManager.AddToRoleAsync(ambassadorModel.UserId, AppRoles.Ambassador);

                Db.AmbassadorModels.Add(ambassadorModel);
                await Db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            if (!ambassadorModel.CanViewOrEdit(User))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.Conflict));
            }

            //EDIT
            Db.Entry(ambassadorModel).State = EntityState.Modified;
            await Db.SaveChangesAsync();

            return(RedirectToAction("Index", "Manage"));
        }
Esempio n. 8
0
        public async Task <ActionResult> RemoveFromEvent(int eventOrderId, int orderId)
        {
            var eventOrder = Db.EventOrderModels.FirstOrDefault(p => p.Id == eventOrderId);

            Db.EventOrderModels.Remove(eventOrder);

            var order = await Db.OrderModels.FirstOrDefaultAsync(p => p.Id == orderId);

            AmbassadorModel oldAmbassador = order.OrderAmbassador;

            order.OrderAmbassador = null;

            order.Status            = OrderStatus.NotAssigned;
            order.StatusLastUpdated = DateTime.UtcNow;
            if (User != null)
            {
                order.LogMessage(User, $"Remove ambassador {oldAmbassador.Email} to no-data");
            }

            await Db.SaveChangesAsync();

            return(RedirectToAction("AssignEvent", new { orderId }));
        }
Esempio n. 9
0
        public async Task <bool> AssignmentAmbassadorAsync(int id, int idOrder, IPrincipal user, IOrderNotificationService _ns)
        {
            OrderModel order = await _db.OrderModels.Include(x => x.OrderAmbassador).Include(x => x.RenderPieces).Include(x => x.OrderRequestor).FirstOrDefaultAsync(x => x.Id == idOrder);

            if (order == null)
            {
                return(false);
            }

            AmbassadorModel newAmbassador = await _db.AmbassadorModels.FindAsync(id);

            if (newAmbassador == null)
            {
                return(false);
            }

            AmbassadorModel oldAmbassador  = order.OrderAmbassador;
            OrderStatus     orderOldStatus = order.Status;

            order.OrderAmbassador   = newAmbassador;
            order.Status            = OrderStatus.PreAssigned;
            order.StatusLastUpdated = DateTime.UtcNow;
            order.RenderPieces.ForEach(p => p.Printed = false);
            if (user != null)
            {
                order.LogMessage(user, $"Change ambassador from {(oldAmbassador != null ? oldAmbassador.Email : "no-data")} to {newAmbassador.Email}");
            }

            await _db.SaveChangesAsync();

            await _ns.SendStatusChangeNotification(order, orderOldStatus, OrderStatus.PreAssigned);

            await _ns.SendAmbassadorChangedNotification(order, oldAmbassador, newAmbassador);

            return(true);
        }
 public void Add(AmbassadorModel entity)
 {
     _context.AmbassadorModels.Add(entity);
     _context.SaveChanges();
 }
Esempio n. 11
0
        public async Task <AmbassadorModel> GetAmbassadorAutoAssignAsync(OrderModel order)
        {
            AmbassadorModel closestAmbassador = null;

            DbGeography location = order.OrderRequestor.Location;

            closestAmbassador = await _db.AmbassadorModels.Include(p => p.User).Include(p => p.RefusedOrders)
                                .OrderBy(p => p.Location.Distance(location))
                                .FirstOrDefaultAsync(p => (p.Location.Distance(location) / 1000) <= 50d &&
                                                     p.User.EmailConfirmed &&
                                                     !p.RefusedOrders.Any(x => x.OrderId == order.Id) &&
                                                     !p.OrderModel.Any(o =>
                                                                       o.Status == OrderStatus.PreAssigned ||
                                                                       o.Status == OrderStatus.Pending ||
                                                                       o.Status == OrderStatus.Ready ||
                                                                       o.Status == OrderStatus.ArrangeDelivery));

            if (closestAmbassador == null)
            {
                HttpResponseMessage response = await CallAndreaniApiAsync();

                if (!response.IsSuccessStatusCode)
                {
                    return(closestAmbassador);
                }

                string content = await response.Content.ReadAsStringAsync();

                XDocument createXml = XDocument.Parse(content);

                IEnumerable <UbicacionAndreani> ubicaciones = createXml.Descendants("item").Select(p => new UbicacionAndreani
                {
                    Descripcion   = p.Element("Descripcion").Value,
                    Direccion     = p.Element("Direccion").Value,
                    HoradeTrabajo = p.Element("HoradeTrabajo").Value,
                    Latitud       = p.Element("Latitud").Value,
                    Longitud      = p.Element("Longitud").Value,
                    Mail          = p.Element("Mail").Value,
                    Numero        = p.Element("Numero").Value,
                    Responsable   = p.Element("Responsable").Value,
                    Resumen       = p.Element("Resumen").Value,
                    Sucursal      = p.Element("Sucursal").Value,
                    Telefono1     = p.Element("Telefono1").Value,
                    Telefono2     = p.Element("Telefono2").Value,
                    Telefono3     = p.Element("Telefono3").Value,
                    TipoSucursal  = p.Element("TipoSucursal").Value,
                    TipoTelefono1 = p.Element("TipoTelefono1").Value,
                    TipoTelefono2 = p.Element("TipoTelefono2").Value,
                    TipoTelefono3 = p.Element("TipoTelefono3").Value,
                    Location      = SiteHelper.GeneratePoint($"{p.Element("Latitud").Value},{p.Element("Longitud").Value}".Split(','))
                });

                var listAmbassadors = await _db.AmbassadorModels
                                      .Include(p => p.User)
                                      .Include(p => p.RefusedOrders)
                                      .Where(p => p.User.EmailConfirmed &&
                                             !p.RefusedOrders.Any(x => x.OrderId == order.Id) &&
                                             !p.OrderModel.Any(o => o.Status == OrderStatus.PreAssigned ||
                                                               o.Status == OrderStatus.Pending ||
                                                               o.Status == OrderStatus.Ready ||
                                                               o.Status == OrderStatus.ArrangeDelivery))
                                      .OrderBy(p => p.Location.Distance(p.Location))
                                      .ToListAsync();

                closestAmbassador = listAmbassadors.FirstOrDefault(p =>
                                                                   ubicaciones.Any(x => (x.Location.Distance(p.Location) / 1000) <= 20d));
            }

            return(closestAmbassador);
        }