コード例 #1
0
ファイル: ShoppingCart.cs プロジェクト: pha4/kentico
        /// <summary>
        /// Adds an item to the shopping cart and saves the newly created cart into the database. Also saves the shopping cart if it wasn't saved yet.
        /// </summary>
        /// <param name="skuId">ID of the added product's SKU object.</param>
        /// <param name="quantity">Number of added product units.</param>
        public void AddItem(int skuId, int quantity = 1)
        {
            var parameters = new ShoppingCartItemParameters
            {
                SKUID    = skuId,
                Quantity = quantity
            };

            var cartItem = ShoppingCartInfoProvider.SetShoppingCartItem(OriginalCart, parameters);

            if (cartItem == null)
            {
                return;
            }

            if (OriginalCart.ShoppingCartID == 0)
            {
                Save(false);
            }

            ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(cartItem);

            mActivityLogger?.LogProductAddedToShoppingCartActivity(cartItem.SKU, quantity);

            mItems = null;
        }
    /// <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;
        }

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

        if (ShoppingCart != null)
        {
            // Add item to shopping cart
            ShoppingCartInfoProvider.SetShoppingCartItem(ShoppingCart, cartItemParams);
        }

        // Close dialog window and refresh content
        ScriptHelper.RegisterStartupScript(Page, typeof(Page), "addScript", ScriptHelper.GetScript("RefreshCart();"));
    }
コード例 #3
0
    private void cartItemSelector_OnAddToShoppingCart(object sender, CancelEventArgs e)
    {
        // Get items parameters
        var cartItemParams = cartItemSelector.GetShoppingCartItemParameters();

        if (ShoppingCartObj != null)
        {
            // Add item to shopping cart
            ShoppingCartInfoProvider.SetShoppingCartItem(ShoppingCartObj, cartItemParams);
        }

        // Close dialog window and refresh content
        ScriptHelper.RegisterStartupScript(Page, typeof(Page), "addScript", ScriptHelper.GetScript("RefreshCart();"));

        // Cancel further processing by shopping cart item selector control
        e.Cancel = true;
    }
コード例 #4
0
    /// <summary>
    /// Sets product in the shopping cart.
    /// </summary>
    /// <param name="itemParams">Shopping cart item parameters</param>
    protected void AddProducts(ShoppingCartItemParameters itemParams)
    {
        IShoppingService shoppingService = Service.Resolve <IShoppingService>();

        var ui = MembershipContext.AuthenticatedUser;

        if (!ui.IsPublic())
        {
            ShoppingCart.User = ui;
            ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
        }
        if (!ShoppingCartControl.IsInternalOrder)
        {
            var addedItem = shoppingService.AddItemToCart(itemParams);

            // Track add to shopping cart conversion
            ECommerceHelper.TrackAddToShoppingCartConversion(addedItem);
        }
        else if (Service.Resolve <ICartItemChecker>().CheckNewItem(itemParams, ShoppingCart))
        {
            ShoppingCartInfoProvider.SetShoppingCartItem(ShoppingCart, itemParams);
        }

        // Avoid adding the same product after page refresh
        if (lblError.Text == "")
        {
            string url = RequestContext.CurrentURL;

            if (!string.IsNullOrEmpty(URLHelper.GetUrlParameter(url, "productid")) ||
                !string.IsNullOrEmpty(URLHelper.GetUrlParameter(url, "quantity")) ||
                !string.IsNullOrEmpty(URLHelper.GetUrlParameter(url, "options")))
            {
                // Remove parameters from URL
                url = URLHelper.RemoveParameterFromUrl(url, "productid");
                url = URLHelper.RemoveParameterFromUrl(url, "quantity");
                url = URLHelper.RemoveParameterFromUrl(url, "options");
                URLHelper.Redirect(url);
            }
        }
    }
コード例 #5
0
    private void btnAddProduct_Click(object sender, EventArgs e)
    {
        // Do not add item if order is paid
        if (OrderIsPaid)
        {
            return;
        }

        // Get strings with productIDs and quantities separated by ';'
        string productIDs = ValidationHelper.GetString(hidProductID.Value, "");
        string quantities = ValidationHelper.GetString(hidQuantity.Value, "");
        string options    = ValidationHelper.GetString(hidOptions.Value, "");

        // Add new products to shopping cart
        if ((productIDs != "") && (quantities != ""))
        {
            int[] arrID      = ValidationHelper.GetIntegers(productIDs.TrimEnd(';').Split(';'), 0);
            int[] arrQuant   = ValidationHelper.GetIntegers(quantities.TrimEnd(';').Split(';'), 0);
            int[] intOptions = ValidationHelper.GetIntegers(options.Split(','), 0);

            // Check site binding
            if (!CheckSiteBinding(arrID) || !CheckSiteBinding(intOptions))
            {
                return;
            }

            lblError.Text = "";

            for (int i = 0; i < arrID.Length; i++)
            {
                int skuId = arrID[i];

                SKUInfo skuInfo = SKUInfoProvider.GetSKUInfo(skuId);
                if ((skuInfo != null) && !skuInfo.IsProductOption)
                {
                    int quantity = arrQuant[i];

                    ShoppingCartItemParameters cartItemParams = new ShoppingCartItemParameters(skuId, quantity, intOptions);

                    // Add product to the shopping cart
                    ShoppingCartInfoProvider.SetShoppingCartItem(ShoppingCart, cartItemParams);

                    // Log activity
                    if (!ShoppingCartControl.IsInternalOrder)
                    {
                        ShoppingCartControl.TrackActivityProductAddedToShoppingCart(skuInfo, quantity);
                    }

                    // Show empty button
                    btnEmpty.Visible = true;
                }
            }
        }

        // Invalidate values
        hidProductID.Value = "";
        hidOptions.Value   = "";
        hidQuantity.Value  = "";

        ShoppingCart.Evaluate();

        // Update values in table
        btnUpdate_Click(btnAddProduct, e);

        if (ShoppingCart.ContentTable.Any())
        {
            // Inventory should be checked
            checkInventory = true;
        }
        else
        {
            // Hide cart content when empty
            HideCartContent();
        }
    }
コード例 #6
0
        private void GenerateEcommerceData(int siteID)
        {
            var siteName     = SiteInfoProvider.GetSiteName(siteID);
            var currencyInfo = CurrencyInfoProvider.GetCurrencies(siteID)
                               .Where("CurrencyIsMain", QueryOperator.Equals, 1).TopN(1).FirstOrDefault();
            var list1 = PaymentOptionInfoProvider.GetPaymentOptions(siteID).ToList();
            var list2 = ShippingOptionInfoProvider.GetShippingOptions(siteID).ToList();

            var orderStatusList = OrderStatusInfoProvider.GetOrderStatuses(siteID).ToDictionary(status => status.StatusName);

            var manufacturerExceptionList = new List <int>
            {
                ManufacturerInfoProvider.GetManufacturerInfo("Aerobie", siteName).ManufacturerID,
                //ManufacturerInfoProvider.GetManufacturerInfo("Chemex", siteName).ManufacturerID,
                //ManufacturerInfoProvider.GetManufacturerInfo("Espro", siteName).ManufacturerID
            };
            var list3 = SKUInfoProvider.GetSKUs(siteID).ToList().Where(sku =>
            {
                if (sku.IsProduct)
                {
                    return(!manufacturerExceptionList.Contains(sku.SKUManufacturerID));
                }
                return(false);
            }).ToList();
            int         num1;
            IList <int> intList;

            if (CustomerInfoProvider.GetCustomers().WhereEquals("CustomerSiteID", siteID).Count < 50)
            {
                num1    = customerNames.Length;
                intList = new List <int>();
                for (var index = 0; index < num1; ++index)
                {
                    intList.Add(GenerateCustomer(customerNames[index], siteID).CustomerID);
                }
            }
            else
            {
                intList = DataHelper.GetIntegerValues(CustomerInfoProvider.GetCustomers().Column("CustomerID")
                                                      .WhereEquals("CustomerSiteID", siteID).WhereNotEquals("CustomerEmail", "alex").Tables[0],
                                                      "CustomerID");
                num1 = intList.Count;
            }

            var num2 = 0;
            var num3 = 0;

            for (var index1 = 0; index1 <= 30; ++index1)
            {
                ++num2;
                var num4 = 0;
                if (index1 > 5)
                {
                    num4 = rand.Next(-1, 2);
                }
                for (var index2 = 0; index2 < num2 / 2 + num4; ++index2)
                {
                    var orderStatusInfo = index1 >= 25
                        ? index1 >= 29 ? orderStatusList["New"] : orderStatusList["InProgress"]
                        : orderStatusList["Completed"];
                    var orderInfo = new OrderInfo
                    {
                        OrderCustomerID = intList[num3 % num1],
                        OrderCurrencyID = currencyInfo.CurrencyID,
                        OrderSiteID     = siteID,
                        OrderStatusID   = orderStatusInfo.StatusID,
                        OrderIsPaid     = "Completed".Equals(orderStatusInfo.StatusName, StringComparison.Ordinal) ||
                                          (uint)rand.Next(0, 2) > 0U,
                        OrderShippingOptionID         = list2[rand.Next(list2.Count)].ShippingOptionID,
                        OrderPaymentOptionID          = list1[rand.Next(list1.Count)].PaymentOptionID,
                        OrderGrandTotal               = decimal.Zero,
                        OrderGrandTotalInMainCurrency = decimal.Zero,
                        OrderTotalPrice               = decimal.Zero,
                        OrderTotalPriceInMainCurrency = decimal.Zero,
                        OrderTotalShipping            = new decimal(10),
                        OrderTotalTax = new decimal(10)
                    };
                    OrderInfoProvider.SetOrderInfo(orderInfo);
                    var orderItems = GenerateOrderItems(orderInfo, list3);
                    GenerateOrderAddress(orderInfo.OrderID, GetRandomCountryId(), AddressType.Billing);
                    GenerateOrderAddress(orderInfo.OrderID, GetRandomCountryId(), AddressType.Shipping);
                    orderInfo.OrderDate       = DateTime.Now.AddDays(index1 - 30);
                    orderInfo.OrderTotalPrice = orderItems;
                    orderInfo.OrderTotalPriceInMainCurrency = orderItems;
                    orderInfo.OrderGrandTotal = orderItems;
                    orderInfo.OrderGrandTotalInMainCurrency = orderItems;
                    var cartInfoFromOrder = ShoppingCartInfoProvider.GetShoppingCartInfoFromOrder(orderInfo.OrderID);
                    orderInfo.OrderInvoiceNumber = OrderInfoProvider.GenerateInvoiceNumber(cartInfoFromOrder);
                    orderInfo.OrderInvoice       = ShoppingCartInfoProvider.GetOrderInvoice(cartInfoFromOrder);
                    OrderInfoProvider.SetOrderInfo(orderInfo);
                    ++num3;
                }
            }

            if (UserInfoProvider.GetUserInfo("alex") != null)
            {
                return;
            }
            var customerInfo = new CustomerInfo
            {
                CustomerEmail             = "*****@*****.**",
                CustomerFirstName         = "Alexander",
                CustomerLastName          = "Adams",
                CustomerSiteID            = siteID,
                CustomerCompany           = "Alex & Co. Ltd",
                CustomerTaxRegistrationID = "12S379BDF798",
                CustomerOrganizationID    = "WRQ7987VRG79"
            };

            CustomerInfoProvider.SetCustomerInfo(customerInfo);
            var userInfo = CustomerInfoProvider.RegisterCustomer(customerInfo, "", "alex");
            var roleInfo = RoleInfoProvider.GetRoleInfo("SilverPartner", siteID);

            if (roleInfo != null)
            {
                UserInfoProvider.AddUserToRole(userInfo.UserID, roleInfo.RoleID);
            }
            for (var index = 0; index < 5; ++index)
            {
                var cart = new ShoppingCartInfo();
                cart.ShoppingCartCulture         = CultureHelper.GetDefaultCultureCode(siteName);
                cart.ShoppingCartCurrencyID      = currencyInfo.CurrencyID;
                cart.ShoppingCartSiteID          = siteID;
                cart.ShoppingCartCustomerID      = customerInfo.CustomerID;
                cart.ShoppingCartBillingAddress  = GenerateAddress(GetRandomCountryId(), customerInfo.CustomerID);
                cart.ShoppingCartShippingAddress = GenerateAddress(GetRandomCountryId(), customerInfo.CustomerID);
                cart.User = userInfo;
                ShoppingCartInfoProvider.SetShoppingCartInfo(cart);
                ShoppingCartInfoProvider.SetShoppingCartItem(cart,
                                                             new ShoppingCartItemParameters(list3.ElementAt(rand.Next(list3.Count)).SKUID, rand.Next(5)));
                cart.Evaluate();
                ShoppingCartInfoProvider.SetOrder(cart);
            }
        }
コード例 #7
0
    /// <summary>
    /// Sets product in the shopping cart.
    /// </summary>
    /// <param name="itemParams">Shopping cart item parameters</param>
    protected void AddProducts(ShoppingCartItemParameters itemParams)
    {
        // Get main product info
        int productId = itemParams.SKUID;
        int quantity  = itemParams.Quantity;

        if ((productId > 0) && (quantity > 0))
        {
            // Check product/options combination
            if (Service.Resolve <ICartItemChecker>().CheckNewItem(itemParams, ShoppingCart))
            {
                // Get requested SKU info object from database
                SKUInfo skuObj = SKUInfoProvider.GetSKUInfo(productId);
                if (skuObj != null)
                {
                    // On the live site
                    if (!ShoppingCartControl.IsInternalOrder)
                    {
                        bool updateCart = false;

                        // Assign current shopping cart to current user
                        var ui = MembershipContext.AuthenticatedUser;
                        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);
                        }

                        // Set item in the shopping cart
                        var product = ShoppingCartInfoProvider.SetShoppingCartItem(ShoppingCart, itemParams);

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

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

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

                        // Track add to shopping cart conversion
                        ECommerceHelper.TrackAddToShoppingCartConversion(product);
                    }
                    // In CMSDesk
                    else
                    {
                        // Set item in the shopping cart
                        ShoppingCartInfoProvider.SetShoppingCartItem(ShoppingCart, itemParams);
                    }
                }
            }

            // Avoid adding the same product after page refresh
            if (lblError.Text == "")
            {
                string url = RequestContext.CurrentURL;

                if (!string.IsNullOrEmpty(URLHelper.GetUrlParameter(url, "productid")) ||
                    !string.IsNullOrEmpty(URLHelper.GetUrlParameter(url, "quantity")) ||
                    !string.IsNullOrEmpty(URLHelper.GetUrlParameter(url, "options")))
                {
                    // Remove parameters from URL
                    url = URLHelper.RemoveParameterFromUrl(url, "productid");
                    url = URLHelper.RemoveParameterFromUrl(url, "quantity");
                    url = URLHelper.RemoveParameterFromUrl(url, "options");
                    URLHelper.Redirect(url);
                }
            }
        }
    }
コード例 #8
0
    /// <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);
                }
            }
        }
    }