public ActionResult PreviewAndPay(PreviewAndPayViewModel model)
        {
            // Gets the current user's shopping cart
            ShoppingCart cart = shoppingService.GetCurrentShoppingCart();

            // Validates the shopping cart
            ShoppingCartCheckResult checkResult = cart.ValidateContent();

            // Gets the selected payment method and assigns it to the shopping cart
            cart.PaymentMethod = paymentRepository.GetById(model.PaymentMethod.PaymentMethodID);

            // Evaluates the shopping cart
            cart.Evaluate();

            // If the validation was not successful, displays the preview step again
            if (checkResult.CheckFailed || !IsPaymentMethodValid(model.PaymentMethod.PaymentMethodID))
            {
                // Prepares a model from the preview step
                PreviewAndPayViewModel viewModel = PreparePreviewViewModel();

                // Displays the preview step again
                return(View("PreviewAndPay", viewModel));
            }

            // Creates an order from the shopping cart
            Order order = shoppingService.CreateOrder(cart);

            // Deletes the shopping cart from the database
            shoppingService.DeleteShoppingCart(cart);

            // Redirects to the payment gateway
            return(RedirectToAction("Index", "Payment", new { orderID = order.OrderID }));
        }
    /// <summary>
    /// Performs an inventory check for all items in the shopping cart and show message if required.
    /// </summary>
    /// <returns>True if all items are available in sufficient quantities, otherwise false</returns>
    private bool CheckShoppingCart()
    {
        // Remove error message before reevaluation
        lblError.Text = string.Empty;

        if (ShoppingCart.IsEmpty)
        {
            lblError.Visible = true;
            lblError.Text    = ResHelper.GetString("com.checkout.cartisempty");
            return(false);
        }

        ShoppingCartCheckResult checkResult = ShoppingCartInfoProvider.CheckShoppingCart(ShoppingCart);

        // Try to show message through Message Panel web part
        if (checkResult.CheckFailed || orderChanged)
        {
            CMSEventArgs <string> args = new CMSEventArgs <string>();
            args.Parameter = checkResult.GetHTMLFormattedMessage();
            ComponentEvents.RequestEvents.RaiseEvent(this, args, MESSAGE_RAISED);

            // If Message Panel web part is not present (Parameter is cleared by web part after successful handling), show error message in error label
            if (!string.IsNullOrEmpty(args.Parameter) && checkResult.CheckFailed)
            {
                lblError.Visible = true;
                lblError.Text    = checkResult.GetHTMLFormattedMessage();
            }
        }
        return(!checkResult.CheckFailed);
    }
    /// <summary>
    /// Validates shopping cart content.
    /// </summary>
    public override bool IsValid()
    {
        // Force loading current values
        ShoppingCartInfoProvider.EvaluateShoppingCart(ShoppingCart);

        // Check inventory
        ShoppingCartCheckResult checkResult = ShoppingCartInfoProvider.CheckShoppingCart(ShoppingCart);

        if (checkResult.CheckFailed)
        {
            lblError.Text = checkResult.GetHTMLFormattedMessage();

            return(false);
        }

        // Check if cart contains at least one product
        if (ShoppingCart.IsEmpty)
        {
            lblError.Text = GetString("com.checkout.cartisempty");

            return(false);
        }

        return(true);
    }
    /// <summary>
    /// Validates shopping cart content.
    /// </summary>
    public override bool IsValid()
    {
        // Force loading current values
        ShoppingCartInfoProvider.EvaluateShoppingCart(ShoppingCart);

        // Check inventory
        ShoppingCartCheckResult checkResult = ShoppingCartInfoProvider.CheckShoppingCart(ShoppingCart);

        if (checkResult.CheckFailed)
        {
            lblError.Text = checkResult.GetHTMLFormattedMessage();

            return(false);
        }

        return(true);
    }
示例#5
0
        public ActionResult ShoppingCartCheckout()
        {
            // Gets the current user's shopping cart
            ShoppingCart cart = shoppingService.GetCurrentShoppingCart();

            // Validates the shopping cart
            ShoppingCartCheckResult checkResult = cart.ValidateContent();

            // If the validation is successful, redirects to the next step of the checkout process
            if (!checkResult.CheckFailed)
            {
                return(RedirectToAction("DeliveryDetails"));
            }

            // If the validation fails, redirects back to shopping cart
            return(RedirectToAction("ShoppingCart"));
        }
        private void ProcessCheckResult(ShoppingCartCheckResult checkResult)
        {
            // Process the check result for each item
            foreach (var itemResult in checkResult.ItemResults)
            {
                // Get the item errors separated by a space and add them into the model state
                var error = itemResult.GetMessage(" ");

                // Use the item ID as an error unique identifier
                var key = itemResult.CartItem.CartItemID.ToString();
                ModelState.AddModelError(key, error);
            }

            if (checkResult.ShippingOptionNotAvailable)
            {
                ModelState.AddModelError("shipping", ResHelper.GetString("DancingGoatMvc.Shipping.NotApplicable"));
            }
        }
    /// <summary>
    /// Performs an inventory check for all items in the shopping cart and show message if required.
    /// </summary>
    /// <returns>True if all items are available in sufficient quantities, otherwise false</returns>
    private bool CheckShoppingCart()
    {
        // Remove error message before reevaluation
        lblError.Text = string.Empty;

        if (ShoppingCart.IsEmpty)
        {
            lblError.Visible = true;
            lblError.Text    = ResHelper.GetString("com.checkout.cartisempty");
            return(false);
        }

        ShoppingCartCheckResult checkResult = ShoppingCartInfoProvider.CheckShoppingCart(ShoppingCart);

        if (checkResult.CheckFailed)
        {
            lblError.Text = checkResult.GetHTMLFormattedMessage();
        }

        // Display error message if required
        lblError.Visible = !string.IsNullOrEmpty(lblError.Text.Trim());
        return(!checkResult.CheckFailed);
    }
    private bool ValidateShoppingCart(ShoppingCartInfo shoppingCart)
    {
        bool valid = true;

        // Check currency
        if (shoppingCart.Currency == null)
        {
            valid = false;
            LogError("Missing currency", EVENT_CODE_VALIDATION);
        }
        // Check shopping cart items.
        // The following conditions must be met to pass the check:
        // 1)All shopping cart items are enabled 2)Max units in one order are not exceeded
        // 3)There is enough units in the inventory 4) Customer is registered, if there is a membership type product in the cart
        // 5)Product validity is valid, if there is a membership or e-product type product in the cart
        ShoppingCartCheckResult result = ShoppingCartInfoProvider.CheckShoppingCart(shoppingCart);

        if (result.CheckFailed || shoppingCart.IsEmpty)
        {
            valid = false;
            LogError("Invalid items", EVENT_CODE_VALIDATION);
        }
        // Check customer
        if (shoppingCart.Customer == null)
        {
            valid = false;
            LogError("Missing customer", EVENT_CODE_VALIDATION);
        }
        // Check BillingAddress
        if (shoppingCart.ShoppingCartBillingAddress == null)
        {
            valid = false;
            LogError("Missing billing address", EVENT_CODE_VALIDATION);
        }
        // Check PaymentOption
        if (shoppingCart.PaymentOption == null)
        {
            valid = false;
            LogError("Missing payment", EVENT_CODE_VALIDATION);
        }

        // Check whether payment option is valid for user.
        string message;

        if (!CheckPaymentOptionIsValidForUser(shoppingCart, out message))
        {
            LogError(message, EVENT_CODE_VALIDATION);
            valid = false;
        }

        // Check payment is valid for cart shipping
        if (!CheckPaymentIsAllowedForShipping(shoppingCart, shoppingCart.ShoppingCartPaymentOptionID))
        {
            LogError("Invalid payment option for selected shipping", EVENT_CODE_VALIDATION);
            valid = false;
        }

        // If there is at least one product that needs shipping
        if (ShippingOptionInfoProvider.IsShippingNeeded(shoppingCart))
        {
            // Check shipping option
            if (shoppingCart.ShippingOption == null)
            {
                valid = false;
                LogError("Missing shipping option", EVENT_CODE_VALIDATION);
            }
        }

        return(valid);
    }
    /// <summary>
    /// Process this step.
    /// </summary>
    public override bool ProcessStep()
    {
        // Do not process step if order is paid
        if (OrderIsPaid)
        {
            return(false);
        }

        // Shopping cart units are already saved in database (on "Update" or on "btnAddProduct_Click" actions)
        bool isOK = false;

        if (ShoppingCart != null)
        {
            // Reload data
            ReloadData();

            // Check available items before "Check out"
            ShoppingCartCheckResult checkResult = ShoppingCartInfoProvider.CheckShoppingCart(ShoppingCart);

            if (checkResult.CheckFailed)
            {
                lblError.Text = checkResult.GetHTMLFormattedMessage();
            }
            else if (ShoppingCartControl.CheckoutProcessType == CheckoutProcessEnum.CMSDeskOrderItems)
            {
                // Indicates whether order saving process is successful
                isOK = true;

                try
                {
                    ShoppingCartInfoProvider.SetOrder(ShoppingCart);
                }
                catch (Exception ex)
                {
                    // Log exception
                    EventLogProvider.LogException("Shopping cart", "SAVEORDER", ex, ShoppingCart.ShoppingCartSiteID);
                    isOK = false;
                }

                if (isOK)
                {
                    lblInfo.Text = GetString("general.changessaved");

                    // Send order notification when editing existing order
                    if (ShoppingCartControl.CheckoutProcessType == CheckoutProcessEnum.CMSDeskOrderItems)
                    {
                        if (chkSendEmail.Checked)
                        {
                            OrderInfoProvider.SendOrderNotificationToAdministrator(ShoppingCart);
                            OrderInfoProvider.SendOrderNotificationToCustomer(ShoppingCart);
                        }
                    }
                    // Send order notification emails when on the live site
                    else if (ECommerceSettings.SendOrderNotification(SiteContext.CurrentSite.SiteName))
                    {
                        OrderInfoProvider.SendOrderNotificationToAdministrator(ShoppingCart);
                        OrderInfoProvider.SendOrderNotificationToCustomer(ShoppingCart);
                    }
                }
                else
                {
                    lblError.Text = GetString("ecommerce.orderpreview.errorordersave");
                }
            }
            // Go to the next step
            else
            {
                // Save other options
                if (!ShoppingCartControl.IsInternalOrder)
                {
                    ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
                }

                isOK = true;
            }
        }

        return(isOK);
    }
    protected override void OnPreRender(EventArgs e)
    {
        // Register add product script
        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "AddProductScript",
                                               ScriptHelper.GetScript(
                                                   "function setProduct(val) { document.getElementById('" + hidProductID.ClientID + "').value = val; } \n" +
                                                   "function setQuantity(val) { document.getElementById('" + hidQuantity.ClientID + "').value = val; } \n" +
                                                   "function setOptions(val) { document.getElementById('" + hidOptions.ClientID + "').value = val; } \n" +
                                                   "function setPrice(val) { document.getElementById('" + hdnPrice.ClientID + "').value = val; } \n" +
                                                   "function setIsPrivate(val) { document.getElementById('" + hdnIsPrivate.ClientID + "').value = val; } \n" +
                                                   "function AddProduct(productIDs, quantities, options, price, isPrivate) { \n" +
                                                   "setProduct(productIDs); \n" +
                                                   "setQuantity(quantities); \n" +
                                                   "setOptions(options); \n" +
                                                   "setPrice(price); \n" +
                                                   "setIsPrivate(isPrivate); \n" +
                                                   Page.ClientScript.GetPostBackEventReference(btnAddProduct, null) +
                                                   ";} \n" +
                                                   "function RefreshCart() {" +
                                                   Page.ClientScript.GetPostBackEventReference(btnAddProduct, null) +
                                                   ";} \n"
                                                   ));

        // Register dialog script
        ScriptHelper.RegisterDialogScript(Page);

        // Hide columns with identifiers
        gridData.Columns[0].Visible = false;
        gridData.Columns[1].Visible = false;
        gridData.Columns[2].Visible = false;
        gridData.Columns[3].Visible = false;

        // Hide actions column
        gridData.Columns[5].Visible = (ShoppingCartControl.CheckoutProcessType == CheckoutProcessEnum.CMSDeskOrderItems) ||
                                      (ShoppingCartControl.CheckoutProcessType == CheckoutProcessEnum.CMSDeskOrder);

        // Disable specific controls
        if (!Enabled)
        {
            lnkNewItem.Enabled       = false;
            lnkNewItem.OnClientClick = "";
            selectCurrency.Enabled   = false;
            btnEmpty.Enabled         = false;
            btnUpdate.Enabled        = false;
            txtCoupon.Enabled        = false;
            chkSendEmail.Enabled     = false;
        }

        // Show/Hide dropdownlist with currencies
        pnlCurrency.Visible &= (selectCurrency.HasData && selectCurrency.DropDownSingleSelect.Items.Count > 1);

        // Check session parameters for inventory check
        if (ValidationHelper.GetBoolean(SessionHelper.GetValue("checkinventory"), false))
        {
            checkInventory = true;
            SessionHelper.Remove("checkinventory");
        }

        // Check inventory
        if (checkInventory)
        {
            ShoppingCartCheckResult checkResult = ShoppingCartInfoProvider.CheckShoppingCart(ShoppingCart);

            if (checkResult.CheckFailed)
            {
                lblError.Text = checkResult.GetHTMLFormattedMessage();
            }
        }

        // Display messages if required
        lblError.Visible = !string.IsNullOrEmpty(lblError.Text.Trim());
        lblInfo.Visible  = !string.IsNullOrEmpty(lblInfo.Text.Trim());

        base.OnPreRender(e);
    }
    /// <summary>
    /// Adds product to the shopping cart.
    /// </summary>
    private void AddProductToShoppingCart()
    {
        SKUID = hdnSKUID.Value.ToInteger(0);

        // Validate input data
        if (!IsValid() || (SKU == null))
        {
            // Do not process
            return;
        }

        // Try to redirect before any currently selected variant checks (selector in listings issue)
        if (RedirectToDetailsEnabled)
        {
            if (!ShowProductOptions)
            {
                // Does product have some enabled product option categories?
                bool hasOptions = !DataHelper.DataSourceIsEmpty(OptionCategoryInfoProvider.GetProductOptionCategories(SKUID, true));

                if (hasOptions)
                {
                    // Redirect to product details
                    URLHelper.Redirect("~/CMSPages/Ecommerce/GetProduct.aspx?productid=" + SKUID);
                }
            }
        }

        if (SKU.HasVariants)
        {
            // Check if configured variant is available
            if ((SelectedVariant == null) || !SelectedVariant.Variant.SKUEnabled)
            {
                ScriptHelper.RegisterStartupScript(Page, typeof(string), "ShoppingCartAddItemErrorAlert", ScriptHelper.GetAlertScript(GetString("com.cartcontent.nonexistingvariantselected")));
                return;
            }
        }

        // Get cart item parameters
        var cartItemParams = GetShoppingCartItemParameters();

        string error = null;

        // Check if it is possible to add this item to shopping cart
        if (!Service.Resolve <ICartItemChecker>().CheckNewItem(cartItemParams, ShoppingCart))
        {
            error = String.Format(GetString("ecommerce.cartcontent.productdisabled"), SKU.SKUName);
        }

        if (!string.IsNullOrEmpty(error))
        {
            // Show error message and cancel adding the product to shopping cart
            ScriptHelper.RegisterStartupScript(Page, typeof(string), "ShoppingCartAddItemErrorAlert", ScriptHelper.GetAlertScript(error));
            return;
        }

        // Fire on add to shopping cart event
        var eventArgs = new CancelEventArgs();

        OnAddToShoppingCart?.Invoke(this, eventArgs);

        // If adding to shopping cart was canceled
        if (eventArgs.Cancel)
        {
            return;
        }

        // Get cart item parameters in case something changed
        cartItemParams = GetShoppingCartItemParameters();

        if (ShoppingCart != null)
        {
            // Shopping cart is not saved yet
            if (ShoppingCart.ShoppingCartID == 0)
            {
                ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
            }

            // Add item to shopping cart
            var addedItem = ShoppingCartInfoProvider.SetShoppingCartItem(ShoppingCart, cartItemParams);

            if (addedItem != null)
            {
                addedItem.CartItemAutoAddedUnits = 0;

                // Update shopping cart item in database
                ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(addedItem);

                // Update product options and bundle items in database
                addedItem.ProductOptions.ForEach(ShoppingCartItemInfoProvider.SetShoppingCartItemInfo);
                addedItem.BundleItems.ForEach(ShoppingCartItemInfoProvider.SetShoppingCartItemInfo);

                if (TrackAddToShoppingCartConversion)
                {
                    // Track 'Add to shopping cart' conversion
                    ECommerceHelper.TrackAddToShoppingCartConversion(addedItem);
                }

                // Recalculate shopping cart
                ShoppingCart.Evaluate();

                // Log activity before possible redirect to shopping cart
                LogProductAddedToSCActivity(addedItem);

                // If user has to be redirected to shopping cart
                if (RedirectToShoppingCart)
                {
                    // Set shopping cart referrer
                    SessionHelper.SetValue("ShoppingCartUrlReferrer", RequestContext.CurrentURL);

                    // Ensure shopping cart update
                    SessionHelper.SetValue("checkinventory", true);

                    // Redirect to shopping cart
                    URLHelper.Redirect(UrlResolver.ResolveUrl(ShoppingCartUrl));
                }
                else
                {
                    // Localize SKU name
                    string skuName = (addedItem.SKU != null) ? ResHelper.LocalizeString(addedItem.SKU.SKUName) : String.Empty;

                    // Check inventory
                    ShoppingCartCheckResult checkResult = ShoppingCartInfoProvider.CheckShoppingCart(ShoppingCart);
                    string checkInventoryMessage        = checkResult.GetFormattedMessage();

                    // Get product added message
                    string message = String.Format(GetString("com.productadded"), skuName);

                    // Add inventory check message
                    if (!String.IsNullOrEmpty(checkInventoryMessage))
                    {
                        message += "\n\n" + checkInventoryMessage;
                    }

                    // Count and show total price with options
                    CalculateTotalPrice();

                    // Register the call of JS handler informing about added product
                    ScriptHelper.RegisterStartupScript(Page, typeof(string), "ShoppingCartItemAddedHandler", "if (typeof ShoppingCartItemAddedHandler == 'function') { ShoppingCartItemAddedHandler(" + ScriptHelper.GetString(message) + "); }", true);
                }
            }
        }
    }
    /// <summary>
    /// Adds product to the shopping cart.
    /// </summary>
    private void AddProductToShoppingCart()
    {
        // Validate input data
        if (!IsValid() || (SKU == null))
        {
            // Do not proces
            return;
        }

        if (RedirectToDetailsEnabled)
        {
            if (!ShowProductOptions && !ShowDonationProperties)
            {
                // Does product have some enabled product option categories?
                bool hasOptions = !DataHelper.DataSourceIsEmpty(OptionCategoryInfoProvider.GetSKUOptionCategories(SKUID, true));

                // Is product a customizable donation?
                bool isCustomizableDonation = ((SKU != null) &&
                                               (SKU.SKUProductType == SKUProductTypeEnum.Donation) &&
                                               (!((SKU.SKUPrice == SKU.SKUMinPrice) && (SKU.SKUPrice == SKU.SKUMaxPrice)) || SKU.SKUPrivateDonation));

                if (hasOptions || isCustomizableDonation)
                {
                    // Redirect to product details
                    URLHelper.Redirect("~/CMSPages/GetProduct.aspx?productid=" + SKUID);
                }
            }
        }

        // Get cart item parameters
        ShoppingCartItemParameters cartItemParams = GetShoppingCartItemParameters();

        string error = null;

        // Check if customer is enabled
        if ((ShoppingCart.Customer != null) && (!ShoppingCart.Customer.CustomerEnabled))
        {
            error = GetString("ecommerce.cartcontent.customerdisabled");
        }

        // Check if it is possible to add this item to shopping cart
        if ((error == null) && !ShoppingCartInfoProvider.CheckNewShoppingCartItems(ShoppingCart, cartItemParams))
        {
            error = String.Format(GetString("ecommerce.cartcontent.productdisabled"), SKU.SKUName);
        }

        if (!string.IsNullOrEmpty(error))
        {
            // Show error message and cancel adding the product to shopping cart
            ScriptHelper.RegisterStartupScript(Page, typeof(string), "ShoppingCartAddItemErrorAlert", ScriptHelper.GetAlertScript(error));
            return;
        }

        // If donation properties are used and donation properties form is not valid
        if (donationProperties.Visible && !String.IsNullOrEmpty(donationProperties.Validate()))
        {
            return;
        }

        // Fire on add to shopping cart event
        CancelEventArgs eventArgs = new CancelEventArgs();

        if (OnAddToShoppingCart != null)
        {
            OnAddToShoppingCart(this, eventArgs);
        }

        // If adding to shopping cart was cancelled
        if (eventArgs.Cancel)
        {
            return;
        }

        // Get cart item parameters in case something changed
        cartItemParams = GetShoppingCartItemParameters();

        // Log activity
        LogProductAddedToSCActivity(SKUID, SKU.SKUName, Quantity);

        if (ShoppingCart != null)
        {
            bool updateCart = false;

            // Assign current shopping cart to current user
            CurrentUserInfo ui = CMSContext.CurrentUser;
            if (!ui.IsPublic())
            {
                ShoppingCart.User = ui;
                updateCart        = true;
            }

            // Shopping cart is not saved yet
            if (ShoppingCart.ShoppingCartID == 0)
            {
                updateCart = true;
            }

            // Update shopping cart when required
            if (updateCart)
            {
                ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
            }

            // Add item to shopping cart
            ShoppingCartItemInfo addedItem = ShoppingCart.SetShoppingCartItem(cartItemParams);

            if (addedItem != null)
            {
                // Update shopping cart item in database
                ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(addedItem);

                // Update product options in database
                foreach (ShoppingCartItemInfo option in addedItem.ProductOptions)
                {
                    ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(option);
                }

                // Update bundle items in database
                foreach (ShoppingCartItemInfo bundleItem in addedItem.BundleItems)
                {
                    ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(bundleItem);
                }

                // Track 'Add to shopping cart' conversion
                ECommerceHelper.TrackAddToShoppingCartConversion(addedItem);

                // If user has to be redirected to shopping cart
                if (RedirectToShoppingCart)
                {
                    // Set shopping cart referrer
                    SessionHelper.SetValue("ShoppingCartUrlReferrer", URLHelper.CurrentURL);

                    // Ensure shopping cart update
                    SessionHelper.SetValue("checkinventory", true);

                    // Redirect to shopping cart
                    URLHelper.Redirect(ShoppingCartUrl);
                }
                else
                {
                    // Localize SKU name
                    string skuName = (addedItem.SKU != null) ? ResHelper.LocalizeString(addedItem.SKU.SKUName) : "";

                    // Check inventory
                    ShoppingCartCheckResult checkResult = ShoppingCartInfoProvider.CheckShoppingCart(ShoppingCart);
                    string checkInventoryMessage        = checkResult.GetFormattedMessage();

                    // Get prodcut added message
                    string message = String.Format(GetString("com.productadded"), skuName);

                    // Add inventory check message
                    if (!String.IsNullOrEmpty(checkInventoryMessage))
                    {
                        message += "\n\n" + checkInventoryMessage;
                    }

                    // Count and show total price with options
                    CalculateTotalPrice();

                    // Register the call of JS handler informing about added product
                    ScriptHelper.RegisterStartupScript(Page, typeof(string), "ShoppingCartItemAddedHandler", "if (typeof ShoppingCartItemAddedHandler == 'function') { ShoppingCartItemAddedHandler(" + ScriptHelper.GetString(message) + "); }", true);
                }
            }
        }
    }