Exemplo n.º 1
0
        public async Task <ActionResult> PlaceOrder(Cart cart, OrderDTO order, string paymentMethod)
        {
            if (cart.LineCollection.Count == 0)
            {
                TempData["EmptyMessage"] = "true";
                return(RedirectToAction("index", "cart"));
            }

            // Add paymentMethod
            var addMethodResult = _orderRepo.AddPaymentMethod(order, paymentMethod);

            // Add orderStatus
            var addOrderStatusResult = _orderRepo.UpdateStatus(order, OrderStatusNames.Pending);

            // Check model valid
            if (!ModelState.IsValid || addMethodResult == null || addOrderStatusResult == null)
            {
                var model = new CheckoutViewModel()
                {
                    Order        = order,
                    OrderDetails = GetOrderDetails(cart)
                };
                return(View("index", model));
            }

            // Add userId if authenticated
            if (User.Identity.IsAuthenticated)
            {
                order.UserId = User.Identity.GetUserId();
            }

            // Get order details and calulate summary
            var orderDetails = GetOrderDetails(cart, false);

            order.SubTotal = cart.Summary;



            // Save order to repository
            var result = _orderRepo.Save(order, orderDetails);

            if (result == null)
            {
                TempData["OrderSuccess"] = "false";
                return(RedirectToAction("index", "cart"));
            }

            // Send mail
            var callbackUrl = Url.Action("index", "tracking", new { id = result.Id }, protocol: Request.Url.Scheme);
            var body        = MailHelper.CreateSuccessPlacingOrderEmailBody(ControllerContext, callbackUrl, result.Id);
            var message     = new IdentityMessage
            {
                Subject     = $"Order {result.Id}",
                Destination = result.Email,
                Body        = body
            };
            var emailService = new EmailService();
            await emailService.SendAsync(message);

            TempData["OrderSuccess"] = "true";
            cart.LineCollection.Clear();

            return(RedirectToAction("index", "tracking", new { id = result.Id }));
        }