Пример #1
0
    /// <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);
        }

        var validationErrors = ShoppingCartInfoProvider.ValidateShoppingCart(ShoppingCart);

        // Try to show message through Message Panel web part
        if (validationErrors.Any() || orderChanged)
        {
            CMSEventArgs <string> args = new CMSEventArgs <string>();
            args.Parameter = validationErrors
                             .Select(e => HTMLHelper.HTMLEncode(e.GetMessage()))
                             .Join("<br />");

            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) && validationErrors.Any())
            {
                lblError.Visible = true;
                lblError.Text    = validationErrors
                                   .Select(e => HTMLHelper.HTMLEncode(e.GetMessage()))
                                   .Join("<br />");
            }
        }
        return(!validationErrors.Any());
    }
        public ActionResult PreviewAndPay(PreviewAndPayViewModel model)
        {
            // Gets the current shopping cart
            ShoppingCartInfo cart = shoppingService.GetCurrentShoppingCart();

            // Validates the shopping cart
            var validationErrors = ShoppingCartInfoProvider.ValidateShoppingCart(cart);

            // Gets the selected payment method, assigns it to the shopping cart, and evaluates the cart
            shoppingService.SetPaymentOption(model.PaymentMethod.PaymentMethodID);

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

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

            // Creates an order from the current shopping cart
            // If the order was created successfully, empties the cart
            OrderInfo order = shoppingService.CreateOrder();

            // Redirects to the payment gateway
            return(RedirectToAction("Index", "Payment", new { orderID = order.OrderID }));
        }
Пример #3
0
        public ActionResult ShoppingCartCheckout()
        {
            var cart             = mShoppingService.GetCurrentShoppingCart();
            var validationErrors = ShoppingCartInfoProvider.ValidateShoppingCart(cart);

            cart.Evaluate();

            if (!validationErrors.Any())
            {
                var customer = GetCustomerOrCreateFromAuthenticatedUser();
                if (customer != null)
                {
                    mShoppingService.SetCustomer(customer);
                }

                mShoppingService.SaveCart();
                return(RedirectToAction("DeliveryDetails"));
            }

            // Fill model state with errors from the check result
            ProcessCheckResult(validationErrors);

            var viewModel = mCheckoutService.PrepareCartViewModel();

            return(View("ShoppingCart", viewModel));
        }
        public ActionResult ShoppingCartCheckout()
        {
            // Gets the current user's shopping cart
            ShoppingCartInfo cart = shoppingService.GetCurrentShoppingCart();

            // Validates the shopping cart
            var cartValidator = ShoppingCartInfoProvider.ValidateShoppingCart(cart);

            // If the validation is successful, redirects to the next step of the checkout process
            if (!cartValidator.Any())
            {
                // Saves the validated shopping cart before redirecting the checkout step
                // This prevents loss of data between requests.
                shoppingService.SaveCart();

                return(RedirectToAction("DeliveryDetails"));
            }

            // If the validation fails, redirects back to the shopping cart
            return(RedirectToAction("ShoppingCart"));
        }
    /// <summary>
    /// Validates shopping cart content.
    /// </summary>
    public override bool IsValid()
    {
        // Force loading current values
        ShoppingCart.Evaluate();

        // Validate inventory
        var cartValidationErrors        = ShoppingCartInfoProvider.ValidateShoppingCart(ShoppingCart);
        var shippingAndPaymentValidator = new ShippingAndPaymentValidator(ShoppingCart);

        shippingAndPaymentValidator.Validate();

        if (cartValidationErrors.Any() || !shippingAndPaymentValidator.IsValid)
        {
            lblError.Text = cartValidationErrors
                            .Union(shippingAndPaymentValidator.Errors)
                            .Select(e => HTMLHelper.HTMLEncode(e.GetMessage()))
                            .Join("<br />");

            return(false);
        }

        return(true);
    }
    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 AddProduct(productIDs, quantities, options, price) { \n" +
                                                   "setProduct(productIDs); \n" +
                                                   "setQuantity(quantities); \n" +
                                                   "setOptions(options); \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;

            ScriptHelper.RegisterStartupScript(this, typeof(string), "ShoppingCartContent_DisableCouponCodes", "$cmsj(\".cart-coupon-code .button > input\").prop(\"disabled\", true)", true);
        }

        // Show/Hide dropdownlist with currencies
        pnlCurrency.Visible &=
            (ShoppingCartControl.CheckoutProcessType != CheckoutProcessEnum.CMSDeskOrderItems) &&
            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)
        {
            var validationErrors = ShoppingCartInfoProvider.ValidateShoppingCart(ShoppingCart);

            if (validationErrors.Any())
            {
                lblError.Text = validationErrors
                                .Select(error => HTMLHelper.HTMLEncode(error.GetMessage()))
                                .Join("<br />");
            }
        }

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

        rptrCouponCodes.DataSource = new CouponCodesViewModel(ShoppingCart.CouponCodes);
        rptrCouponCodes.DataBind();

        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();

        var shoppingService = Service.Resolve <IShoppingService>();

        var addedItem = shoppingService.AddItemToCart(cartItemParams);

        if (addedItem == null)
        {
            return;
        }

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

        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;

            // Validate inventory
            string validateInventoryMessage = String.Empty;

            var validationErrors = ShoppingCartInfoProvider.ValidateShoppingCart(ShoppingCart);
            if (validationErrors.Any())
            {
                validateInventoryMessage = validationErrors
                                           .Select(e => HTMLHelper.HTMLEncode(e.GetMessage()))
                                           .Join("<br />");
            }

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

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

            // 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);
        }
    }