Exemplo n.º 1
0
        public async Task <IActionResult> Index(DeliveryAddressViewModel deliveryAddres)
        {
            deliveryAddres.MinimumCharge  = _config.GetValue <int>("LowestDeliveryCost");
            deliveryAddres.CostByBlock    = _config.GetValue <int>("DeliveryCostByBlock");
            deliveryAddres.DeliveryRadius = _config.GetValue <int>("DeliveryRadius");

            if (!ModelState.IsValid)
            {
                try
                {
                    var potentialPlace = await _deliveryRepository.GuessPlaceIdAsync(deliveryAddres.AddressLine1);

                    var placeConfirmed = await _deliveryRepository.GetPlaceAsync(potentialPlace);

                    deliveryAddres.AddressLine1 = placeConfirmed.StreetName + " " + placeConfirmed.StreetNumber + ", " + placeConfirmed.PostalCode;
                    deliveryAddres.ZipCode      = placeConfirmed.PostalCode;
                    deliveryAddres.StreetName   = placeConfirmed.StreetName;
                    deliveryAddres.StreetNumber = placeConfirmed.StreetNumber;
                }
                catch
                {
                    return(View(deliveryAddres));
                }
            }

            var distance = await _deliveryRepository.GetDistanceAsync(deliveryAddres.AddressLine1);

            if (distance > deliveryAddres.DeliveryRadius)
            {
                if (distance > 0)
                {
                    ModelState.AddModelError("DistanceNotCovered", $"La distancia debe ser menor a {deliveryAddres.DeliveryRadius/1000}kms. Tu ubicación está a {(distance / 1000.0).ToString("#.##")} kms.");
                }
                else
                {
                    ModelState.AddModelError("DistanceError", "No pudimos calcular la distancia.");
                }

                return(View(deliveryAddres));
            }

            var delivery = _mapper.Map <DeliveryAddressViewModel, DeliveryAddress>(deliveryAddres);

            delivery.ShoppingCartId = _cartRepository.GetSessionCartId();
            delivery.DeliveryCost   = _deliveryRepository.GetDeliveryEstimate(distance);
            delivery.Distance       = distance;


            var user = await _userManager.GetUser(_signInManager);

            if (user != null)
            {
                delivery.User = user;
            }

            try
            {
                _deliveryRepository.AddOrUpdateDelivery(delivery);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(ex.InnerException.Message, ex.Message);
                return(View(deliveryAddres));
            }

            return(RedirectToAction("Index", "ShoppingCart", null));
        }