Example #1
0
        public virtual ActionResult Submit()
        {
            string returnUrl;

            if (!_cartItemRepository.GetAll().Any())
            {
                returnUrl = Url.Action(MVC.Home.Root());

                return(RedirectedAsync(returnUrl, Resources.Error_CartIsEmpty, true));
            }

            if (!CustomerContext.Current.IsAuthenticated)
            {
                returnUrl = Url.Action(MVC.Account.Login(Url.Action(MVC.Order.Submit())));

                return(RedirectedAsync(returnUrl, Resources.Error_LoginRequired, true));
            }

            var order = new OrderModel {
                AccessToken   = SecurityHelpers.GenerateToken(8),
                Customer      = CustomerContext.Current.Customer,
                SubmitDateUtc = DateTime.UtcNow,
                Status        = OrderStatus.Submitted,
                IpAddress     = Request.UserHostAddress
            };

            _orderRepository.AddOrUpdate(order);
            _orderRepository.SaveChanges();

            var cartItems  = _cartItemRepository.GetAll();
            var orderLines = new List <OrderLineModel>();
            var products   = _productRepository.GetAllByIds(cartItems.Select(cim => cim.Id).ToArray());

            foreach (var cartItem in _cartItemRepository.GetAll())
            {
                var product = products[cartItem.Id];

                var orderLine = new OrderLineModel {
                    Order   = order,
                    Product = product,
                    Count   = cartItem.Count
                };

                _orderLineRepository.AddOrUpdate(orderLine);
                orderLines.Add(orderLine);

                order.TotalPrice += cartItem.TotalPrice;
            }

            _orderLineRepository.SaveChanges();
            _orderRepository.SaveChanges();

            _cartItemRepository.DeleteAll();
            _cartItemRepository.SaveChanges();

            _notificationController.OrderSubmitted(CustomerContext.Current.Customer, order, orderLines).Send();

            returnUrl = Url.Action(MVC.Order.CheckOut(order.AccessToken));

            return(RedirectedAsync(returnUrl, Resources.Success_OrderSubmitted));
        }