コード例 #1
0
        //UNDONE POST ONLY
        //
        // POST: /Checkout/Checkout
        //[ValidateAntiForgeryToken]
        public ActionResult Checkout()
        {
            //Get current cart items
            var currentCartItems = _shoppingCartService
                                   .GetCartWithAssociatedProducts(ShoppingCartHelpers.GetShoppingCartID(this.ControllerContext)).ToList();

            //If there are no cart items, redirect to the shoppingcart index
            if (!currentCartItems.Any())
            {
                return(RedirectToAction("Index", "ShoppingCart"));
            }

            //Construct the model that will be the container for the collected checkout information
            CheckoutViewModel checkoutModel = new CheckoutViewModel(currentCartItems, Guid.NewGuid().ToString("N"));

            //Cache the container model at a well known location unique to the user, sliding expiration of 10 minutes
            CacheHelpers.InsertCheckoutInstanceIntoCache(checkoutModel, this.ControllerContext);

            //Construct & hydrate the first step viewmodel
            var availableAddressesForUser = _userService.GetUserWithAddresses(IdentityHelpers.GetUserId(User.Identity)).Addresses.AsEnumerable();

            var model = checkoutModel.GetShippingViewModel(availableAddressesForUser);

            #region TestInformation
#if DEBUG
            model.Email       = "*****@*****.**";
            model.PhoneNumber = "1234567890";
#endif
            #endregion

            return(View("ShippingInformation", model));
        }
コード例 #2
0
        public ActionResult RemoveFromCart(Int32 cartItemID)
        {
            var importantCartUpdates = new List <String>();

            var user = _userService.Get(IdentityHelpers.GetUserId(this.User.Identity));

            var cartItems = _cartService.GetCart(user);

            if (cartItems.FirstOrDefault(ci => ci.CartItemID == cartItemID) != null)
            {
                _cartService.RemoveItemFromCart(user, cartItemID);

                _uow.Save();

                importantCartUpdates.Add("The item has been removed from your cart.");
            }
            else
            {
                return(new HttpUnauthorizedResult());
            }

            TempData.Add("ImportantCartUpdates", importantCartUpdates);

            return(RedirectToAction("Index"));
        }
コード例 #3
0
        public ActionResult AddToCart(Int32 productID, Int32 quantity = 1)
        {
            var product = _productService.Get(productID);

            if (product == null)
            {
                return(new HttpNotFoundResult("Product could not be found."));
            }

            var user = _userService.Get(IdentityHelpers.GetUserId(this.User.Identity));

            var cartItem = _cartService.GetCart(user).FirstOrDefault(ci => ci.ProductID == productID);

            if (cartItem != null)
            {
            }

            List <String> cartUpdates = _cartService.AddItemToCart(product, user, quantity);

            if (!cartUpdates.Any())
            {
                _uow.Save();
            }

            TempData.Add("ImportantCartUpdates", cartUpdates);

            return(RedirectToAction("Index"));
        }
コード例 #4
0
        //
        // GET: /Account/EditProfile
        public ActionResult EditProfile()
        {
            var user = _userService.GetUserWithProfile(IdentityHelpers.GetUserId(User.Identity));

            var model = Mapper.Map <UserProfileViewModel>(user.UserProfile);

            return(View(model));
        }
コード例 #5
0
        public ActionResult DisassociateAddress(Int32 addressId, String diff = "")
        {
            _userService.DisassociateAddress(IdentityHelpers.GetUserId(User.Identity), addressId);

            _uow.Save();

            return(RedirectToAction("EditAddresses", "Account"));
        }
コード例 #6
0
        //
        // GET: /Account/EditEmail
        public ActionResult EditEmail()
        {
            var user = _userService.Get(IdentityHelpers.GetUserId(User.Identity));

            var model = new EditEmailViewModel()
            {
                CurrentEmailAddress = user.Email
            };

            return(View(model));
        }
コード例 #7
0
        //
        // GET: /Account/DisassociateAddress/?addressId=
        public ActionResult DisassociateAddress(Int32 addressId)
        {
            var user = _userService.GetUserWithAddresses(IdentityHelpers.GetUserId(User.Identity));

            var add = user.Addresses.FirstOrDefault(a => a.AddressID == addressId);

            if (add != null)
            {
                return(View(add));
            }

            throw new HttpException(Convert.ToInt32(HttpStatusCode.NotFound), "Attempt to disassosciate non existing address.");
        }
コード例 #8
0
        public async Task <ActionResult> EditEmail(EditEmailViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = _userService.Get(IdentityHelpers.GetUserId(User.Identity));

                if (_userService.IsPasswordMatchForUser(user.UserID, model.Password))
                {
                    String originalEmail = user.Email;

                    //Check if the new email address is already assosciated with another account
                    if (_userService.GetByEmail(model.NewEmailAddress) != null)
                    {
                        _userService.SetEmailAddress(user.UserID, model.NewEmailAddress);

                        _uow.Save();

                        //Send notification email
                        String subject = "Account Email Changed";
                        String body    = "This email is to inform you that the email address associated with your account has been changed.";

                        var message = new MailMessage("*****@*****.**", originalEmail, subject, body);

                        await _emailService.SendMessageAsync(message);

                        ViewBag.SuccessMessage = "Your email address has been changed.";

                        ModelState.Clear();

                        return(View());
                    }

                    ModelState.AddPropertyError <EditEmailViewModel>(m => m.NewEmailAddress, "An account with this email already exists.");
                }
                else
                {
                    ModelState.AddPropertyError <EditEmailViewModel>(m => m.Password, "Invalid password.");

                    return(View(model));
                }
            }

            //We got this far, some.panel .panel-default failed
            return(View(model));
        }
コード例 #9
0
        //
        // GET: /Account/
        public ActionResult Index()
        {
            var user = _userService.GetUserWithOrdersAndProfile(IdentityHelpers.GetUserId(this.User.Identity));

            object importantAccountUpdates;

            TempData.TryGetValue("ImportantAccountUpdates", out importantAccountUpdates);

            var model = new AccountIndexViewModel()
            {
                ImportantAccountUpdates = importantAccountUpdates as List <String> ?? new List <String>(),
                RecentOrders            = user.Orders.OrderByDescending(o => o.OrderDate).Take(5).ToList(),
                User        = user,
                UserProfile = user.UserProfile
            };

            return(View(model));
        }
コード例 #10
0
        public ActionResult AddAddress(AddNewAddressViewModel model)
        {
            if (ModelState.IsValid)
            {
                var userID = IdentityHelpers.GetUserId(User.Identity);

                var address = Mapper.Map <Address>(model);

                address.UserID = userID;

                _userService.AddNewAddress(userID, address);

                _uow.Save();

                return(RedirectToAction("EditAddresses"));
            }

            return(View(model));
        }
コード例 #11
0
        public ActionResult EditProfile([Bind(Exclude = "UserID")] UserProfileViewModel model)
        {
            if (ModelState.IsValid)
            {
                var updatedProfile = Mapper.Map <UserProfile>(model);

                var userID = IdentityHelpers.GetUserId(this.User.Identity);

                updatedProfile.UserID = userID;

                _userService.UpdateUserProfile(userID, updatedProfile);

                _uow.Save();

                return(RedirectToAction("Index", "Account"));
            }
            else
            {
                return(View(model));
            }
        }
コード例 #12
0
        //
        // GET: /Account/OrderHistory
        public ActionResult OrderHistory(OrderHistoryViewModel model)
        {
            Int32 itemsPerPage = 5;

            var user = _userService.GetUserWithOrders(IdentityHelpers.GetUserId(User.Identity));

            var ordersQuery = user.Orders.AsQueryable();

            if (model.From != null)
            {
                ordersQuery = ordersQuery.Where(o => o.OrderDate > model.From);
            }

            if (model.To != null)
            {
                ordersQuery = ordersQuery.Where(o => o.OrderDate < model.To);
            }

            model.Orders = ordersQuery.OrderByDescending(o => o.OrderDate).ToPagedList <Order>(model.PageNumber, itemsPerPage);

            return(View(model));
        }
コード例 #13
0
        public async Task <ActionResult> EditPassword(EditPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = _userService.Get(IdentityHelpers.GetUserId(User.Identity));

                if (_userService.IsPasswordMatchForUser(user.UserID, model.CurrentPassword))
                {
                    _userService.SetPassword(user.UserID, model.NewPassword);

                    _uow.Save();

                    String subject = "Account Password Change";

                    String body = "This email is to inform you that the password associated with your account has been changed.";

                    await _userService.SendEmailAsync(user.UserID, subject, body);

                    ViewBag.SuccessMessage = "Password has been changed successfully.";

                    ModelState.Clear();

                    return(View());
                }
                else
                {
                    ModelState.AddModelError("CurrentPassword", "Password is invalid.");

                    return(View(model));
                }
            }
            else
            {
                return(View(model));
            }
        }
コード例 #14
0
        public ActionResult ShippingInformation(ShippingInformationViewModel model)
        {
            CheckoutViewModel checkoutModel;

            if (CacheHelpers.GetCheckoutInstanceFromCache(model.CheckoutInstance, this.ControllerContext, out checkoutModel) != CacheHelpers.CheckoutCacheStatus.Success)
            {
                return(RedirectToAction("Index", "ShoppingCart"));
            }

            if (ModelState.IsValid)
            {
                Address shippingAddress;

                //If the user selected an address
                if (model.SelectedShippingAddressId > 0)
                {
                    var address = _addressService.Get(model.SelectedShippingAddressId);

                    //Verify it exists
                    if (address != null)
                    {
                        //Verify it belongs to this user
                        if (address.UserID == IdentityHelpers.GetUserId(this.User.Identity))
                        {
                            shippingAddress = address;
                        }
                        else
                        {
                            throw new InvalidOperationException("Address does not belong to this user.");
                        }
                    }
                    else
                    {
                        throw new InvalidOperationException("Expected address, but not found.");
                    }
                }
                else
                {
                    shippingAddress = new Address {
                        AddressLine1 = model.AddressLine1, AddressLine2 = model.AddressLine2, City = model.City, PostalCode = model.PostalCode, State = model.State
                    }
                };

                checkoutModel.Email = model.Email;

                checkoutModel.PhoneNumber = model.PhoneNumber;

                checkoutModel.ShippingAddress = shippingAddress;

                checkoutModel.ShippingCost = _orderService.CalculateShipping(checkoutModel.CartItems);

                checkoutModel.Tax = _orderService.CalculateTax(checkoutModel.CartItems);

                var nextModel = checkoutModel.GetBillingViewModel();

                #region Test Information
#if DEBUG
                nextModel.CreditCardPayment = new CreditCardPaymentViewModel()
                {
                    //Authorize.Net Test Visa
                    CreditCardNumber = "4007000000027",
                    CVV             = "123",
                    ExpirationMonth = 1,
                    ExpirationYear  = 2018
                };

                nextModel.BillingSameAsShipping = true;
#endif
                #endregion

                ModelState.Clear();

                return(View("BillingInformation", nextModel));
            }
            else
            {
                //Resupply unbound information the model needs to redisplay
                checkoutModel.GetShippingViewModel(_userService
                                                   .GetUserWithAddresses(IdentityHelpers.GetUserId(User.Identity)).Addresses);

                return(View(model));
            }
        }
コード例 #15
0
        public ActionResult Review(ReviewViewModel model)
        {
            CheckoutViewModel checkoutModel;

            if (CacheHelpers.GetCheckoutInstanceFromCache(model.CheckoutInstance, this.ControllerContext, out checkoutModel) != CacheHelpers.CheckoutCacheStatus.Success)
            {
                return(RedirectToAction("Index", "ShoppingCart"));
            }

            //Check to see where the user was trying to go
            if (ConfirmButtonWasClicked())
            {
                //Clear the checkoutmodel from cache to prevent reprocessing
                CacheHelpers.RemoveCheckoutInstanceFromCache(this.ControllerContext);

                Order toCreate = checkoutModel.GetOrder(IdentityHelpers.GetUserId(this.User.Identity));

                Boolean orderCreated = false;
                Int32   attempts     = 3;

                Order newOrder = null;

                using (TransactionScope orderProcessingScope = new TransactionScope())
                {
                    do
                    {
                        try
                        {
                            using (TransactionScope createOrderScope = new TransactionScope())
                            {
                                _shoppingCartService.EmptyCart(ShoppingCartHelpers.GetShoppingCartID(this.ControllerContext));

                                if (!_productService.DecrementInventory(toCreate.OrderDetails))
                                {
                                    return(RedirectToAction("StockUnavailable", "Checkout"));
                                }

                                newOrder = _orderService.CreateOrder(toCreate);

                                _uow.Save();

                                orderCreated = true;

                                createOrderScope.Complete();
                            }
                        }
                        catch (DbUpdateConcurrencyException ex)
                        {
                            //Reload any entry that changed with new values before we retry
                            foreach (var item in ex.Entries)
                            {
                                item.Reload();
                            }

                            attempts--;
                        }
                    } while (!orderCreated && attempts > 0);

                    if (orderCreated)
                    {
                        using (TransactionScope scope = new TransactionScope())
                        {
                            var payment = new CreditCardPayment()
                            {
                                Amount           = newOrder.SubTotal + newOrder.Tax + newOrder.ShippingCost,
                                CreditCardNumber = checkoutModel.CreditCardPayment.CreditCardNumber,
                                CVV        = checkoutModel.CreditCardPayment.CVV,
                                Expiration = new DateTime(checkoutModel.CreditCardPayment.ExpirationYear, checkoutModel.CreditCardPayment.ExpirationMonth, DateTime.DaysInMonth(checkoutModel.CreditCardPayment.ExpirationYear, checkoutModel.CreditCardPayment.ExpirationMonth), 0, 0, 0)
                            };

                            //Authorize the payment
                            var paymentAuthResult = _creditCardService
                                                    .Authorize(payment, "Payment for order " + newOrder.OrderID, newOrder.BillingAddress);

                            //If successful authorization
                            if (paymentAuthResult.Success)
                            {
                                _transactionService.Create(paymentAuthResult.Transaction);

                                newOrder.OrderStatus = OrderStatus.Processing;

                                _orderService.Update(newOrder);

                                _uow.Save();

                                _emailService.SendMessage(EmailHelpers.GetOrderReceivedEmail(this, newOrder.Email, newOrder.OrderID));

                                scope.Complete();

                                orderProcessingScope.Complete();

                                TempData.Add("OrderID", newOrder.OrderID);

                                return(RedirectToAction("Confirmation"));
                            }
                            else
                            {
                                paymentAuthResult.Errors.ForEach(e => ModelState.AddModelError("", e));
                            }
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "We're sorry, there was a problem creating your order. " +
                                                 "Please try again and if the problem persists, please try again later.");
                    }
                }

                CacheHelpers.InsertCheckoutInstanceIntoCache(checkoutModel, this.ControllerContext);

                var reModel = checkoutModel.GetReviewViewModel();

                return(View("Review", reModel));
            }
            else if (PreviousButtonWasClicked())
            {
                var previousModel = checkoutModel.GetBillingViewModel();

                ModelState.Clear();

                return(View("BillingInformation", previousModel));
            }

            throw new HttpException(500, "Invalid destination.");
        }
コード例 #16
0
        //
        // GET: /Account/OrderDetails
        public ActionResult OrderDetails(Int32 orderId)
        {
            var order = _userService.GetCompleteOrder(IdentityHelpers.GetUserId(this.User.Identity), orderId);

            return(View(order));
        }
コード例 #17
0
        public ActionResult BillingInformation(BillingInformationViewModel model)
        {
            CheckoutViewModel checkoutModel;

            if (CacheHelpers.GetCheckoutInstanceFromCache(model.CheckoutInstance, this.ControllerContext, out checkoutModel) != CacheHelpers.CheckoutCacheStatus.Success)
            {
                return(RedirectToAction("Index", "ShoppingCart"));
            }

            if (NextButtonWasClicked())
            {
                if (ModelState.IsValid)
                {
                    Address billingAddress;

                    if (model.BillingSameAsShipping)
                    {
                        billingAddress = checkoutModel.ShippingAddress;
                    }
                    else
                    {
                        billingAddress = new Address()
                        {
                            AddressLine1 = model.AddressLine1, AddressLine2 = model.AddressLine2, City = model.City, State = model.State, PostalCode = model.PostalCode
                        }
                    };

                    checkoutModel.BillingAddress = billingAddress;

                    checkoutModel.CreditCardPayment = model.CreditCardPayment;

                    //checkoutModel.GiftCardPayments = model.GiftCardPayments;

                    var nextModel = checkoutModel.GetReviewViewModel();

                    return(View("Review", nextModel));
                }
                else
                {
                    //Resupply unbound information the model needs to redisplay
                    model = checkoutModel.GetBillingViewModel();

                    //UNDONE
                    //Clear any modelstate entries for credit card to avoid posting them back
                    //ModelState.ToList().ForEach(kvp =>
                    //    {
                    //        if (kvp.Key.Contains("CreditCard"))
                    //        {
                    //            var emptyVal = new ValueProviderResult(String.Empty, String.Empty, CultureInfo.CurrentCulture);
                    //            ModelState.SetModelValue(kvp.Key, emptyVal);
                    //        }
                    //    });

                    return(View(model));
                }
            }
            else if (PreviousButtonWasClicked())
            {
                var previousModel = checkoutModel.GetShippingViewModel(_userService
                                                                       .GetUserWithAddresses(IdentityHelpers.GetUserId(User.Identity)).Addresses);

                this.ModelState.Clear();

                return(View("ShippingInformation", previousModel));
            }

            throw new HttpException(500, "Invalid destination.");
        }
コード例 #18
0
        //
        // GET: /Account/EditAddresses
        public ActionResult EditAddresses()
        {
            var user = _userService.GetUserWithAddresses(IdentityHelpers.GetUserId(User.Identity));

            return(View(user.Addresses));
        }