private void SendOrderEmails(CheckoutResult checkoutResult, Order submittedOrder, Dictionary <string, string> orderTokens)
        {
            try
            {
                EmailController emailController = new EmailController();

                string adminEmailResponse = emailController.SendEmailTemplate(EmailTemplateNames.OrderReceivedAdmin, orderTokens, storeContext.CurrentStore.GetSetting(StoreSettingNames.OrderCompletedEmailRecipient), storeContext.CurrentStore);
                if (WA.Parser.ToBool(storeContext.CurrentStore.GetSetting(StoreSettingNames.SendOrderReceivedEmail)).GetValueOrDefault(true))
                {
                    string emailResponse = emailController.SendEmailTemplate(EmailTemplateNames.OrderReceived, orderTokens, submittedOrder.CustomerEmail, storeContext.CurrentStore);

                    if (!string.IsNullOrEmpty(emailResponse))
                    {
                        checkoutResult.Warnings.Add(string.Format(@"Something went wrong when we tried to email your order receipt. {0}", emailResponse));
                    }
                }
            }
            catch (Exception ex)
            {
                checkoutResult.Warnings.Add(string.Format(@"Something went wrong when we tried to email your order receipt. {0}", ex.Message));
            }
        }
        internal CheckoutResult DoPostCheckoutProcessing(Order submittedOrder, bool sendEmails)
        {
            CheckoutResult checkoutResult = new CheckoutResult();

            checkoutResult.SubmittedOrder = submittedOrder;

            if (submittedOrder != null)
            {
                bool paymentStatusOk = (submittedOrder.PaymentStatus == PaymentStatusName.Completed) || (submittedOrder.PaymentStatus == PaymentStatusName.Pending);
                bool orderStatusOk   = (submittedOrder.OrderStatus == OrderStatusName.Completed) || (submittedOrder.OrderStatus == OrderStatusName.Processing);

                if (paymentStatusOk && orderStatusOk)
                {
                    //---- Order SUCCESS
                    DoPostCheckoutSuccess(checkoutResult, submittedOrder, sendEmails);
                }
                else if (!paymentStatusOk)
                {
                    checkoutResult.Errors.Add(string.Format(@"Payment Failed. Your order status is: {0}", submittedOrder.OrderStatus));
                    PaymentTransaction paymentTransaction = submittedOrder.GetMostRecentPaymentTransaction();
                    if (paymentTransaction != null && !string.IsNullOrEmpty(paymentTransaction.GatewayError))
                    {
                        checkoutResult.Errors.Add(string.Format(@" Payment Error: {0}.", paymentTransaction.GatewayError));
                    }
                }
                else if (!orderStatusOk)
                {
                    checkoutResult.Errors.Add(string.Format(@"Unable to complete your order. Your order status is: {0}", submittedOrder.OrderStatus));
                }
            }
            else
            {
                checkoutResult.Errors.Add("Submitted Order was NULL");
            }

            return(checkoutResult);
        }
        private void PostOrderTokensToUrl(CheckoutResult checkoutResult, Dictionary <string, string> orderTokens, string urlToPostOrder)
        {
            if (!string.IsNullOrEmpty(urlToPostOrder))
            {
                try
                {
                    orderTokens["store.guid"] = storeContext.CurrentStore.StoreGuid.Value.ToString();

                    HttpWebResponse postResponse   = HttpHelper.HttpPost(urlToPostOrder, orderTokens);
                    string          responseString = HttpHelper.WebResponseToString(postResponse);

                    if (postResponse.StatusCode != HttpStatusCode.OK || (!string.IsNullOrEmpty(responseString) && !responseString.StartsWith("OK")))
                    {
                        checkoutResult.Warnings.Add(string.Format(@"Something went wrong when we tried to POST your order. Error: {0} {1}", responseString, postResponse.StatusDescription));
                    }
                }
                catch (WebException webEx)
                {
                    string response = "";
                    if (webEx.Response != null)
                    {
                        StreamReader reader = new StreamReader(webEx.Response.GetResponseStream());
                        response = reader.ReadToEnd();
                    }

                    checkoutResult.Warnings.Add(string.Format(@"Something went wrong when we tried to POST your order. Exception: {0}. Response: {1}", webEx.Message, response));
                }
                catch (Exception postEx)
                {
                    // NOTE - should a failure here be propagated up to the user?
                    //checkoutResult.Errors.Add(string.Format(@"Something went wrong when we tried to POST your order to ""{0}"". Error: {1}", urlToPostOrder, postEx.Message));

                    Exceptions.LogException(postEx);
                }
            }
        }
        private void DoPostCheckoutSuccess(CheckoutResult checkoutResult, Order submittedOrder, bool sendEmails)
        {
            //--- Update Inventory
            foreach (var orderItem in submittedOrder.OrderItemCollectionByOrderId)
            {
                var product = orderItem.UpToProductByProductId;
                if (product.InventoryIsEnabled.GetValueOrDefault(false))
                {
                    product.InventoryQtyInStock = product.InventoryQtyInStock - orderItem.Quantity;
                    product.Save();
                }
            }

            //List<Product> productsOrdered = submittedOrder.GetOrderItemProducts();
            //foreach(Product p in productsOrdered)
            //{
            //    if(p.InventoryIsEnabled.GetValueOrDefault(false))
            //    {
            //        Product temp = new Product();
            //        if (temp.LoadByPrimaryKey(p.Id.Value))
            //        {
            //            temp.InventoryQtyInStock--;
            //            temp.Save();
            //        }
            //    }
            //}

            //--- Clear the Checkout SESSION
            HttpContext.Current.Session.Remove(storeContext.SessionKeys.CheckoutOrderInfo);

            //--- Delete the Cart
            CartController cartController = new CartController(storeContext);

            //cartController.DeleteCart();
            cartController.DeleteCartForOrder(submittedOrder);

            try
            {
                //--- Add DNN Roles to user if order is PAID
                if (submittedOrder.PaymentStatus == PaymentStatusName.Completed)
                {
                    AddUserToDnnRoles(submittedOrder);
                }

                TokenHelper tokenHelper = new TokenHelper(storeContext);
                Dictionary <string, string> orderTokens = tokenHelper.GetOrderTokens(submittedOrder, false);

                string urlToPostOrder = storeContext.CurrentStore.GetSetting(StoreSettingNames.UrlToPostCompletedOrder);
                PostOrderTokensToUrl(checkoutResult, orderTokens, urlToPostOrder);

                if (sendEmails)
                {
                    Dictionary <string, string> orderEmailTokens = tokenHelper.GetOrderTokens(submittedOrder, true);
                    SendOrderEmails(checkoutResult, submittedOrder, orderEmailTokens);
                }
            }
            catch (Exception ex)
            {
                checkoutResult.Warnings.Add(ex.Message);

                Exceptions.LogException(ex);
            }
        }