Пример #1
0
 public ShoppingCart Get(Customer customer, CartTypeEnum cartType, int storeId)
 {
     return(CachedObjectProvider.Get(new ShoppingCartCacheContext(
                                         customer: customer,
                                         cartType: cartType,
                                         storeId: storeId)));
 }
Пример #2
0
 public AvaTaxRate Get(Customer customer, CartTypeEnum cartType, int storeId)
 {
     return(CachedObjectProvider.Get(new AvaTaxRateCacheContext(
                                         customer: customer,
                                         cartType: cartType,
                                         storeId: storeId)));
 }
Пример #3
0
        public ActionResult MinicartLink(CartTypeEnum cartType)
        {
            var customer = HttpContext.GetCustomer();
            var cart     = CachedShoppingCartProvider.Get(customer, cartType, AppLogic.StoreID());

            return(PartialView(
                       cartType == CartTypeEnum.ShoppingCart
                                        ? ViewNames.MiniCartLinkPartial
                                        : ViewNames.MiniWishLinkPartial,
                       GetShoppingCartViewModel(cart, customer)));
        }
Пример #4
0
 public AvaTaxRate(
     Customer customer,
     int storeId,
     CartTypeEnum cartType,
     decimal shippingTaxRate)
 {
     Customer        = customer;
     StoreId         = storeId;
     CartType        = cartType;
     ShippingTaxRate = shippingTaxRate;
 }
Пример #5
0
    private void GoNextPage(HttpContext context, bool itemIsARegistryItem = false, CartTypeEnum cartType = CartTypeEnum.ShoppingCart, Customer ThisCustomer = null)
    {
        string ReturnURL = CommonLogic.QueryStringCanBeDangerousContent("ReturnURL");

        if (ReturnURL.IndexOf("<script>", StringComparison.InvariantCultureIgnoreCase) != -1)
        {
            throw new ArgumentException("SECURITY EXCEPTION");
        }

        CartTypeEnum CartType = CartTypeEnum.ShoppingCart;

        if (CommonLogic.FormNativeInt("IsWishList") == 1 || CommonLogic.QueryStringUSInt("IsWishList") == 1)
        {
            CartType = CartTypeEnum.WishCart;
        }

        bool isAddRegistryItem = (cartType == CartTypeEnum.ShoppingCart && itemIsARegistryItem);

        if ((isAddRegistryItem) ||
            ("STAY".Equals(AppLogic.AppConfig("AddToCartAction"), StringComparison.InvariantCultureIgnoreCase) && ReturnURL.Length != 0))
        {
            string addedParam = string.Empty;
            if (isAddRegistryItem)
            {
                addedParam = "&" + DomainConstants.NOTIFICATION_QRY_STRING_PARAM + "=" + AppLogic.GetString("editgiftregistry.aspx.48", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            }
            context.Response.Redirect(ReturnURL + addedParam);
        }
        else
        {
            if (ReturnURL.Length == 0)
            {
                ReturnURL = string.Empty;
                if (context.Request.UrlReferrer != null)
                {
                    ReturnURL = context.Request.UrlReferrer.AbsoluteUri; // could be null
                }
                if (ReturnURL == null)
                {
                    ReturnURL = string.Empty;
                }
            }
            if (CartType == CartTypeEnum.WishCart)
            {
                context.Response.Redirect("wishlist.aspx?ReturnUrl=" + Security.UrlEncode(ReturnURL));
            }
            if (CartType == CartTypeEnum.GiftRegistryCart)
            {
                context.Response.Redirect("giftregistry.aspx?ReturnUrl=" + Security.UrlEncode(ReturnURL));
            }
            context.Response.Redirect("ShoppingCart.aspx?add=true&ReturnUrl=" + Security.UrlEncode(ReturnURL));
        }
    }
        public ActionResult MinicartLink(CartTypeEnum cartType)
        {
            var customer  = HttpContext.GetCustomer();
            var itemCount = CachedShoppingCartProvider
                            .Get(customer, cartType, AppLogic.StoreID())
                            .CartItems
                            .Sum(item => item.Quantity);

            return(PartialView(
                       cartType == CartTypeEnum.ShoppingCart
                                        ? ViewNames.MiniCartLinkPartial
                                        : ViewNames.MiniWishLinkPartial,
                       new MinicartLinkViewModel {
                ItemCount = itemCount
            }));
        }
Пример #7
0
        public ActionResult DeleteMiniCartItem(int id, CartTypeEnum cartType)
        {
            var customer = HttpContext.GetCustomer();

            // Make request, check status
            var response = CartActionProvider.RemoveItemFromCart(customer, cartType, id);

            switch (response.Status)
            {
            case CartActionStatus.Forbidden:
            case CartActionStatus.RequiresLogin:
            case CartActionStatus.SessionTimeout:
                foreach (var message in response.Messages)
                {
                    NoticeProvider.PushNotice(message.ConvertToNotice());
                }
                return(Json(
                           data: new AjaxAddToCartData(
                               status: response.Status.ToString(),
                               messages: null,
                               minicartData: GetMinicartData(customer, response.UpdatedCart, null)),
                           behavior: JsonRequestBehavior.AllowGet));

            default:
                break;
            }

            // Handle non-ajax calls
            if (!Request.IsAjaxRequest())
            {
                foreach (var message in response.Messages)
                {
                    NoticeProvider.PushNotice(message.ConvertToNotice());
                }
                return(RedirectToAction(ActionNames.Index, ControllerNames.Checkout));
            }

            // The view should reflect the real cart not the posted values in the modelstate.
            ModelState.Clear();
            return(Json(
                       GetMinicartData(
                           customer: customer,
                           cart: response.UpdatedCart,
                           messages: response.Messages.Select(
                               n => n.ConvertToAjaxNotice())),
                       JsonRequestBehavior.AllowGet));
        }
Пример #8
0
 public KitAddToCartViewModel(
     string regularBasePrice,
     string basePrice,
     string customizedPrice,
     string customerLevelPrice,
     bool isUnorderable,
     bool isCallToOrder,
     bool showRegularBasePrice,
     bool showBasePrice,
     bool showCustomerLevelPrice,
     bool showWishlistButton,
     bool showBuyButton,
     bool showQuantity,
     bool hidePriceUntilCart,
     SelectList restrictedQuantities,
     PayPalAd payPalAd,
     bool showSchemaOrgPrice,
     string schemaBasePrice,
     string isoThreeLetterCurrency,
     string schemaProductUrl,
     string schemaOfferUrl,
     CartTypeEnum cartType)
 {
     RegularBasePrice       = regularBasePrice;
     BasePrice              = basePrice;
     CustomizedPrice        = customizedPrice;
     CustomerLevelPrice     = customerLevelPrice;
     IsUnorderable          = isUnorderable;
     IsCallToOrder          = isCallToOrder;
     ShowRegularBasePrice   = showRegularBasePrice;
     ShowBasePrice          = showBasePrice;
     ShowCustomerLevelPrice = showCustomerLevelPrice;
     ShowWishlistButton     = showWishlistButton;
     ShowBuyButton          = showBuyButton;
     ShowQuantity           = showQuantity;
     RestrictedQuantities   = restrictedQuantities;
     PayPalAd               = payPalAd;
     HidePriceUntilCart     = hidePriceUntilCart;
     ShowSchemaOrgPrice     = showSchemaOrgPrice;
     SchemaBasePrice        = schemaBasePrice;
     IsoThreeLetterCurrency = isoThreeLetterCurrency;
     SchemaProductUrl       = schemaProductUrl;
     SchemaOfferUrl         = schemaOfferUrl;
     CartType               = cartType;
 }
Пример #9
0
 public AddToCartViewModel(
     bool showQuantity,
     SelectList restrictedQuantities,
     bool customerEntersPrice,
     string customerEntersPricePrompt,
     SelectList colorOptions,
     string colorOptionPrompt,
     SelectList sizeOptions,
     string sizeOptionPrompt,
     string textOptionPrompt,
     bool showTextOption,
     bool requiresTextOption,
     int textOptionMaxLength,
     bool isCallToOrder,
     bool showBuyButton,
     bool showWishlistButton,
     PayPalAd payPalAd,
     bool showBuySafeKicker,
     string buySafeKickerType,
     bool colorSelectorChangesImage,
     bool isSimpleProduct,
     CartTypeEnum cartType)
 {
     ShowQuantity              = showQuantity;
     RestrictedQuantities      = restrictedQuantities;
     CustomerEntersPrice       = customerEntersPrice;
     CustomerEntersPricePrompt = customerEntersPricePrompt;
     ColorOptions              = colorOptions;
     ColorOptionPrompt         = colorOptionPrompt;
     SizeOptions               = sizeOptions;
     SizeOptionPrompt          = sizeOptionPrompt;
     TextOptionPrompt          = textOptionPrompt;
     ShowTextOption            = showTextOption;
     RequiresTextOption        = requiresTextOption;
     TextOptionMaxLength       = textOptionMaxLength;
     IsCallToOrder             = isCallToOrder;
     ShowBuyButton             = showBuyButton;
     ShowWishlistButton        = showWishlistButton;
     PayPalAd                  = payPalAd;
     ShowBuySafeKicker         = showBuySafeKicker;
     BuySafeKickerType         = buySafeKickerType;
     ColorSelectorChangesImage = colorSelectorChangesImage;
     IsSimpleProduct           = isSimpleProduct;
     CartType                  = cartType;
 }
Пример #10
0
        public static KitComposition FromCart(Customer thisCustomer, CartTypeEnum cartType, int cartId)
        {
            KitComposition composition = new KitComposition(cartId);

            using (SqlConnection dbconn = new SqlConnection(DB.GetDBConn()))
            {
                dbconn.Open();
                string query = string.Format(
                    @"SELECT 
                                    kc.ShoppingCartRecID, 
                                    kc.ProductID, 
                                    kc.VariantID, 
                                    kc.KitGroupID, 
                                    kc.KitItemID,
                                    ki.Name,
                                    kc.TextOption,
                                    kc.Quantity
                                    FROM KitCart kc WITH (NOLOCK)
                                    INNER JOIN ShoppingCart sc WITH (NOLOCK) ON kc.ShoppingCartRecID = sc.ShoppingCartRecID 
                                    INNER JOIN KitItem ki ON ki.KitItemID = kc.KitItemID
                                    WHERE kc.CustomerID = {0} AND sc.CartType = {1}  AND sc.ShoppingCartRecID = {2}",
                    thisCustomer.CustomerID, (int)cartType, cartId);
                using (IDataReader reader = DB.GetRS(query, dbconn))
                {
                    while (reader.Read())
                    {
                        KitCartItem kit = new KitCartItem();
                        kit.CustomerID = thisCustomer.CustomerID;
                        kit.ProductID  = DB.RSFieldInt(reader, "ProductID");
                        kit.VariantID  = DB.RSFieldInt(reader, "VariantID");
                        kit.KitGroupID = DB.RSFieldInt(reader, "KitGroupID");
                        kit.KitItemID  = DB.RSFieldInt(reader, "KitItemID");
                        kit.Name       = DB.RSFieldByLocale(reader, "Name", thisCustomer.LocaleSetting);
                        kit.TextOption = DB.RSField(reader, "TextOption");
                        kit.Quantity   = DB.RSFieldInt(reader, "Quantity");

                        composition.Compositions.Add(kit);
                    }
                }
            }

            return(composition);
        }
Пример #11
0
        public ActionResult Index(CartTypeEnum cartType)
        {
            // Do not show this minicart if it is disabled
            var enabled = cartType == CartTypeEnum.WishCart
                                ? AppLogic.AppConfigBool("ShowWishButtons")
                                : AppLogic.AppConfigBool("Minicart.Enabled") &&
                          AppLogic.GetCurrentPageType() != PageTypes.Checkout;

            if (!enabled)
            {
                return(Content(string.Empty));
            }

            var customer = HttpContext.GetCustomer();
            var cart     = CachedShoppingCartProvider.Get(customer, cartType, AppLogic.StoreID());

            return(PartialView(
                       cartType == CartTypeEnum.ShoppingCart
                                        ? ViewNames.MiniCartPartial
                                        : ViewNames.MiniWishPartial,
                       GetShoppingCartViewModel(cart, customer)));
        }
Пример #12
0
        protected void AddToCart(CartTypeEnum cartType)
        {
            try
            {
                if (KitData.HasFileUploadGroup)
                {
                    KitData.MoveAllTempImagesToOrdered();
                }

                KitComposition composition = ComposeAddToCart();

                if (KitData.HasRequiredGroups)
                {
                    List <String> RequiredGroupNames = new List <String>();

                    foreach (KitGroupData requiredGroup in KitData.Groups)
                    {
                        if (requiredGroup.IsRequired)
                        {
                            int hasBeenSelected = composition.Compositions.Where(kci => kci.KitGroupID.Equals(requiredGroup.Id)).Count();
                            if (hasBeenSelected == 0)
                            {
                                RequiredGroupNames.Add(requiredGroup.Name);
                            }
                        }
                    }

                    if (RequiredGroupNames.Count > 0)
                    {
                        StringBuilder sb = new StringBuilder(1000);
                        sb.Append(AppLogic.GetString("product.kit2product.xml.config.16", ThisCustomer.LocaleSetting));
                        sb.Append("<ul  data-role=\"listview\">");
                        foreach (String requiredGroup in RequiredGroupNames)
                        {
                            sb.Append("<li>" + requiredGroup + "</li>");
                        }
                        sb.Append("</ul>");
                        ShowError(sb.ToString());
                        return;
                    }
                }

                String       tmp  = DB.GetNewGUID();
                ShoppingCart cart = new ShoppingCart(1, ThisCustomer, cartType, 0, false);

                int qty = GetQuantity();

                if (KitData.HasCartMapping)
                {
                    AppLogic.ClearKitItems(ThisCustomer, KitData.Id, KitData.VariantId, KitData.ShoppingCartRecordId);
                    CartItem lineItem = cart.CartItems.FirstOrDefault(item => item.ShoppingCartRecordID == KitData.ShoppingCartRecordId);
                    cart.SetItemQuantity(lineItem.ShoppingCartRecordID, qty);
                    cart.ProcessKitComposition(composition, KitData.Id, KitData.VariantId, KitData.ShoppingCartRecordId);
                }
                else
                {
                    //GFS - If customer a session has been cleared and no cookies are available, we must create a customer record to associate the new cart ID to.
                    //If this is not done, adding a kit product within the said environment will render an empty shopping cart.
                    ThisCustomer.RequireCustomerRecord();
                    int shipId   = ThisCustomer.PrimaryShippingAddressID;
                    int NewRecID = cart.AddItem(ThisCustomer,
                                                ThisCustomer.PrimaryShippingAddressID,
                                                KitData.Id, KitData.VariantId, qty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, cartType, false, false, 0, System.Decimal.Zero, composition);
                }
            }
            catch { }


            bool stayOnThisPage = AppLogic.AppConfig("AddToCartAction").Equals("STAY", StringComparison.InvariantCultureIgnoreCase);

            if (stayOnThisPage)
            {
                // some tokens like the shoppingcart qty may already be rendered
                // we therefore need to re-display the page to display the correct qty
                Response.Redirect(this.Request.Url.ToString());
            }
            else
            {
                string returnUrl = CommonLogic.GetThisPageName(false) + "?" + CommonLogic.ServerVariables("QUERY_STRING");

                switch (cartType)
                {
                case CartTypeEnum.ShoppingCart:
                    Response.Redirect(ResolveClientUrl("~/ShoppingCart.aspx?add=true&ReturnUrl=" + Security.UrlEncode(returnUrl)));
                    break;

                case CartTypeEnum.GiftRegistryCart:
                    Response.Redirect(ResolveClientUrl("~/giftregistry.aspx?ReturnUrl=" + Security.UrlEncode(returnUrl)));
                    break;

                case CartTypeEnum.WishCart:
                    Response.Redirect(ResolveClientUrl("~/wishlist.aspx?ReturnUrl=" + Security.UrlEncode(returnUrl)));
                    break;
                }
            }
        }
        public ActionResult UpdateMinicart([Bind(Include = "CartItems")] MinicartViewModel cartViewModel, CartTypeEnum cartType, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction(ActionNames.Index, ControllerNames.Minicart));
            }

            var customer = HttpContext.GetCustomer();

            if (!customer.HasCustomerRecord)
            {
                // Customer session has been lost somewhere - give them a generic error and redirect
                // This can happen if their session times out, or if they are using their browser's 'Back' button to get to an outdated minicart state
                NoticeProvider.PushNotice(AppLogic.GetString("minicart.updateerror"), NoticeType.Failure);
                return(Redirect(Url.MakeSafeReturnUrl(returnUrl)));
            }

            // Make request, check status
            var response = UpdateCartFromViewModel(cartViewModel, customer, cartType);

            switch (response.Status)
            {
            case CartActionStatus.Forbidden:
            case CartActionStatus.RequiresLogin:
            case CartActionStatus.SessionTimeout:
                foreach (var message in response.Messages)
                {
                    NoticeProvider.PushNotice(message.ConvertToNotice());
                }
                return(Json(
                           data: new AjaxAddToCartData(
                               status: response.Status.ToString(),
                               messages: null,
                               minicartData: GetMinicartData(customer, response.UpdatedCart, null)),
                           behavior: JsonRequestBehavior.AllowGet));

            default:
                break;
            }

            // Handle non-ajax calls
            if (!Request.IsAjaxRequest())
            {
                foreach (var message in response.Messages)
                {
                    NoticeProvider.PushNotice(message.ConvertToNotice());
                }

                return(RedirectToAction(ActionNames.Index, ControllerNames.Checkout,
                                        new { returnUrl = Url.MakeSafeReturnUrl(returnUrl, Url.GetDefaultContinueShoppingUrl()) }));
            }

            // The view should reflect the real cart not the posted values in the modelstate.
            ModelState.Clear();
            return(Json(
                       GetMinicartData(
                           customer: customer,
                           cart: response.UpdatedCart,
                           messages: response.Messages.Select(
                               n => n.ConvertToAjaxNotice())),
                       JsonRequestBehavior.AllowGet));
        }
Пример #14
0
        public static AddToCartContext ConvertToAddToCartContext(this KitAddToCartPostModel kitAddToCartPostModel, Customer customer, CartTypeEnum cartType)
        {
            // Start with default kit data with no customer selections
            var kitData = KitProductData.Find(
                productId: kitAddToCartPostModel.ProductId,
                cartRecId: kitAddToCartPostModel.CartRecordId ?? 0,
                thisCustomer: customer);

            // Move uploaded files to their permanent location.
            kitData.TempFileStub = kitAddToCartPostModel.TemporaryImageNameStub;
            if (kitData.HasFileUploadGroup)
            {
                kitData.MoveAllTempImagesToOrdered();                 // This also updates the text option field for file uploads.
            }
            return(new AddToCartContext()
            {
                Customer = customer,
                CartType = cartType,

                ShoppingCartRecId = kitAddToCartPostModel.CartRecordId,
                Quantity = kitAddToCartPostModel.Quantity,

                ProductId = kitAddToCartPostModel.ProductId,
                VariantId = kitAddToCartPostModel.VariantId,
                UpsellProducts = kitAddToCartPostModel.UpsellProducts,
                IsWishlist = kitAddToCartPostModel.IsWishlist,

                CustomerEnteredPrice = 0,
                Color = string.Empty,
                Size = string.Empty,
                TextOption = string.Empty,

                TemporaryImageNameStub = kitAddToCartPostModel.TemporaryImageNameStub,
                KitData = kitData,
                Composition =
                    BuildCompositionFromModel(
                        model: kitAddToCartPostModel,
                        kitData: kitData,
                        customerId: customer.CustomerID)
            });
        }
Пример #15
0
        public static AddToCartContext ConvertToAddToCartContext(this KitAddToCartPostModel kitAddToCartPostModel, Customer customer, CartTypeEnum cartType)
        {
            // Start with default kit data with no customer selections
            var kitData = KitProductData.Find(
                productId: kitAddToCartPostModel.ProductId,
                cartRecId: kitAddToCartPostModel.CartRecordId ?? 0,
                thisCustomer: customer);

            // Add the temp file stup to the kit data for use later.
            kitData.TempFileStub = kitAddToCartPostModel.TemporaryImageNameStub;

            return(new AddToCartContext()
            {
                Customer = customer,
                CartType = cartType,

                ShoppingCartRecId = kitAddToCartPostModel.CartRecordId,
                Quantity = kitAddToCartPostModel.Quantity,

                ProductId = kitAddToCartPostModel.ProductId,
                VariantId = kitAddToCartPostModel.VariantId,
                UpsellProducts = kitAddToCartPostModel.UpsellProducts,
                IsWishlist = kitAddToCartPostModel.IsWishlist,

                CustomerEnteredPrice = 0,
                Color = string.Empty,
                Size = string.Empty,
                TextOption = string.Empty,

                TemporaryImageNameStub = kitAddToCartPostModel.TemporaryImageNameStub,
                KitData = kitData,
                Composition =
                    BuildCompositionFromModel(
                        model: kitAddToCartPostModel,
                        kitData: kitData,
                        customerId: customer.CustomerID)
            });
        }
Пример #16
0
        public void ProcessCart(bool DoingFullCheckout, bool ForceOnePageCheckout, bool InternationalCheckout)
        {
            Response.CacheControl = "private";
            Response.Expires      = 0;
            Response.AddHeader("pragma", "no-cache");

            ThisCustomer.RequireCustomerRecord();
            CartTypeEnum cte = CartTypeEnum.ShoppingCart;

            if (CommonLogic.QueryStringCanBeDangerousContent("CartType").Length != 0)
            {
                cte = (CartTypeEnum)CommonLogic.QueryStringUSInt("CartType");
            }

            cart = new ShoppingCart(1, ThisCustomer, cte, 0, false);

            if (cart.InventoryTrimmed || this.InventoryTrimmed)
            {
                HandleInventoryTrimmed();
                return; //Bail and warn the customer that their cart changed before putting them into checkout
            }

            if (cart.IsEmpty())
            {
                cart.ClearCoupon();
                // can't have this at this point:
                switch (cte)
                {
                case CartTypeEnum.ShoppingCart:
                    Response.Redirect("shoppingcart.aspx");
                    break;

                case CartTypeEnum.WishCart:
                    Response.Redirect("wishlist.aspx");
                    break;

                case CartTypeEnum.GiftRegistryCart:
                    Response.Redirect("giftregistry.aspx");
                    break;

                default:
                    Response.Redirect("shoppingcart.aspx");
                    break;
                }
            }

            // update cart quantities:
            UpdateCartQuantity();

            // save coupon code, no need to reload cart object
            // will update customer record also:
            if (cte == CartTypeEnum.ShoppingCart)
            {
                cart.SetCoupon(CouponCode.Text, true);

                // kind of backwards, but if DisallowOrderNotes is false, then
                // allow order notes
                if (!AppLogic.AppConfigBool("DisallowOrderNotes"))
                {
                    if (OrderNotes.Text.Trim().Length > 0)
                    {
                        SqlParameter sp = new SqlParameter("@OrderNotes", SqlDbType.NText);
                        sp.Value = OrderNotes.Text.Trim();
                        SqlParameter[] spa = { sp };
                        ThisCustomer.UpdateCustomer(spa);
                    }
                }

                // rebind the cart summary control to handle coupon
                ctrlCartSummary.DataSource = cart;

                // check for upsell products
                if (CommonLogic.FormCanBeDangerousContent("Upsell").Length != 0)
                {
                    foreach (String s in CommonLogic.FormCanBeDangerousContent("Upsell").Split(','))
                    {
                        int ProductID = Localization.ParseUSInt(s);
                        if (ProductID != 0)
                        {
                            int VariantID = AppLogic.GetProductsDefaultVariantID(ProductID);
                            if (VariantID != 0)
                            {
                                int            NewRecID = cart.AddItem(ThisCustomer, ThisCustomer.PrimaryShippingAddressID, ProductID, VariantID, 1, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, CartTypeEnum.ShoppingCart, true, false, 0, System.Decimal.Zero);
                                Decimal        PR       = AppLogic.GetUpsellProductPrice(0, ProductID, ThisCustomer.CustomerLevelID);
                                SqlParameter[] spa      = { DB.CreateSQLParameter("@Price", SqlDbType.Decimal, 10, PR, ParameterDirection.Input), DB.CreateSQLParameter("@CartRecID", SqlDbType.Int, 4, NewRecID, ParameterDirection.Input) };
                                DB.ExecuteSQL("update shoppingcart set IsUpsell=1, ProductPrice=@Price where ShoppingCartRecID=@CartRecID", spa);
                            }
                        }
                    }
                }

                if (cart.CheckInventory(ThisCustomer.CustomerID))
                {
                    ErrorMsgLabel.Text += Server.HtmlEncode(AppLogic.GetString("shoppingcart_process.aspx.1", SkinID, ThisCustomer.LocaleSetting));
                    // inventory got adjusted, send them back to the cart page to confirm the new values!
                }
            }

            if (cte == CartTypeEnum.WishCart)
            {
                Response.Redirect("wishlist.aspx");
            }
            if (cte == CartTypeEnum.GiftRegistryCart)
            {
                Response.Redirect("giftregistry.aspx");
            }

            cart.ClearShippingOptions();
            if (DoingFullCheckout)
            {
                bool validated =
                    cart.MeetsMinimumOrderAmount(AppLogic.AppConfigUSDecimal("CartMinOrderAmount")) &&
                    cart.MeetsMinimumOrderQuantity(AppLogic.AppConfigUSInt("MinCartItemsBeforeCheckout")) &&
                    !cart.ExceedsMaximumOrderQuantity(AppLogic.AppConfigUSInt("MaxCartItemsBeforeCheckout")) &&
                    (!cart.HasCoupon() || cart.CouponIsValid);

                if (validated)
                {
                    AppLogic.eventHandler("BeginCheckout").CallEvent("&BeginCheckout=true");

                    if (InternationalCheckout)
                    {
                        Response.Redirect("internationalcheckout.aspx");
                    }

                    if ((ThisCustomer.IsRegistered || ThisCustomer.EMail.Length != 0) && (ThisCustomer.Password.Length == 0 || ThisCustomer.PrimaryBillingAddressID == 0 || ThisCustomer.PrimaryShippingAddressID == 0 || !ThisCustomer.HasAtLeastOneAddress()))
                    {
                        Response.Redirect("createaccount.aspx?checkout=true");
                    }

                    if (!ThisCustomer.IsRegistered || ThisCustomer.PrimaryBillingAddressID == 0 || ThisCustomer.PrimaryShippingAddressID == 0 || !ThisCustomer.HasAtLeastOneAddress())
                    {
                        Response.Redirect("createaccount.aspx?checkout=true");
                    }
                    else
                    {
                        if (AppLogic.AppConfigBool("SkipShippingOnCheckout") || cart.IsAllSystemComponents() || cart.IsAllDownloadComponents())
                        {
                            if (cart.ContainsGiftCard())
                            {
                                Response.Redirect("checkoutgiftcard.aspx");
                            }
                            else
                            {
                                Response.Redirect("checkoutpayment.aspx");
                            }
                        }

                        if ((cart.HasMultipleShippingAddresses() || cart.HasGiftRegistryComponents()) && cart.TotalQuantity() <= AppLogic.MultiShipMaxNumItemsAllowed() && cart.CartAllowsShippingMethodSelection)
                        {
                            Response.Redirect("checkoutshippingmult.aspx");
                        }
                        else
                        {
                            Response.Redirect("checkoutshipping.aspx");
                        }
                    }
                }
                InitializePageContent();
            }

            //Make sure promotions is updated when the cart changes
            BindPromotions();
        }
Пример #17
0
        public static AddToCartContext ConvertToAddToCartContext(this AddToCartPostModel addToCartPostModel, Customer customer, CartTypeEnum cartType)
        {
            return(new AddToCartContext()
            {
                Customer = customer,
                CartType = cartType,

                ShoppingCartRecId = addToCartPostModel.CartRecordId,
                Quantity = addToCartPostModel.Quantity,

                ProductId = addToCartPostModel.ProductId,
                VariantId = addToCartPostModel.VariantId,
                UpsellProducts = addToCartPostModel.UpsellProducts,
                IsWishlist = addToCartPostModel.IsWishlist,

                CustomerEnteredPrice = addToCartPostModel.CustomerEnteredPrice,
                Color = addToCartPostModel.Color,
                Size = addToCartPostModel.Size,
                TextOption = addToCartPostModel.TextOption,

                TemporaryImageNameStub = string.Empty,
                KitData = null,
                Composition = null
            });
        }
Пример #18
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            Response.CacheControl = "private";
            Response.Expires      = 0;
            Response.AddHeader("pragma", "no-cache");

            CartTypeEnum CartType = CartTypeEnum.ShoppingCart;

            Customer ThisCustomer = Customer.Current;

            ThisCustomer.RequireCustomerRecord();
            int CustomerID = ThisCustomer.CustomerID;

            ShoppingCart cart = new ShoppingCart(1, ThisCustomer, CartType, 0, false);

            for (int i = 0; i < Request.Form.Count; i++)
            {
                String FieldName = Request.Form.Keys[i];
                String FieldVal  = Request.Form[Request.Form.Keys[i]];
                if (FieldName.ToUpperInvariant().IndexOf("_VLDT") == -1 && (FieldName.ToLowerInvariant().StartsWith("price_") || FieldName.ToLowerInvariant().StartsWith("qty_")) && FieldVal.Trim().Length != 0)
                {
                    try // ignore errors, just add what items we can:
                    {
                        decimal CustomerEnteredPrice = Decimal.Zero;
                        int     Qty = 0;
                        if (FieldName.ToLowerInvariant().StartsWith("price_"))
                        {
                            CustomerEnteredPrice = Currency.ConvertToBaseCurrency(Localization.ParseLocaleDecimal(FieldVal, ThisCustomer.LocaleSetting), ThisCustomer.CurrencySetting);
                        }
                        else
                        {
                            Qty = Localization.ParseNativeInt(FieldVal);
                        }
                        String[] flds      = FieldName.Split('_');
                        int      ProductID = Localization.ParseUSInt(flds[1]);
                        int      VariantID = Localization.ParseUSInt(flds[2]);
                        int      ColorIdx  = Localization.ParseUSInt(flds[3]);
                        int      SizeIdx   = Localization.ParseUSInt(flds[4]);
                        if (Qty == 0)
                        {
                            Qty = 1;
                        }
                        String ChosenColor            = String.Empty;
                        String ChosenSize             = String.Empty;
                        String ChosenColorSKUModifier = String.Empty;
                        String ChosenSizeSKUModifier  = String.Empty;
                        if (ColorIdx > -1 || SizeIdx > -1)
                        {
                            using (SqlConnection dbconn = new SqlConnection(DB.GetDBConn()))
                            {
                                dbconn.Open();
                                using (IDataReader rs = DB.GetRS("select * from productvariant where VariantID=" + VariantID.ToString(), dbconn))
                                {
                                    rs.Read();
                                    ChosenColor = DB.RSFieldByLocale(rs, "Colors", Localization.GetDefaultLocale()).Split(',')[ColorIdx].Trim();
                                    if (DB.RSField(rs, "ColorSKUModifiers").Length != 0)
                                    {
                                        ChosenColorSKUModifier = DB.RSField(rs, "ColorSKUModifiers").Split(',')[ColorIdx].Trim();
                                    }
                                    ChosenSize = DB.RSFieldByLocale(rs, "Sizes", Localization.GetDefaultLocale()).Split(',')[SizeIdx].Trim();
                                    if (DB.RSField(rs, "SizeSKUModifiers").Length != 0)
                                    {
                                        ChosenSizeSKUModifier = DB.RSField(rs, "SizeSKUModifiers").Split(',')[SizeIdx].Trim();
                                    }
                                }
                            }
                        }

                        String TextOption = String.Empty;
                        cart.AddItem(ThisCustomer, 0, ProductID, VariantID, Qty, ChosenColor, ChosenColorSKUModifier, ChosenSize, ChosenSizeSKUModifier, TextOption, CartType, false, false, 0, CustomerEnteredPrice);
                    }
                    catch { }
                }
            }
            cart = null;


            String ReturnURL = CommonLogic.QueryStringCanBeDangerousContent("ReturnURL");

            if (AppLogic.AppConfig("AddToCartAction").Equals("STAY", StringComparison.InvariantCultureIgnoreCase) && ReturnURL.Length != 0)
            {
                Response.Redirect(ReturnURL);
            }
            else
            {
                String url = CommonLogic.IIF(CartType == CartTypeEnum.WishCart, "wishlist.aspx", "ShoppingCart.aspx?add=true");
                Response.Redirect(url);
            }
        }
Пример #19
0
 public ShoppingCartCacheContext(Customer customer, CartTypeEnum cartType, int storeId)
 {
     Customer = customer;
     CartType = cartType;
     StoreId  = storeId;
 }
Пример #20
0
        /// <summary>
        /// Handles the table order add to cart which was handled before by the tableorder_process.aspx .
        /// </summary>
        private void HandleTableOrderAddToCart()
        {
            CartTypeEnum CartType = CartTypeEnum.ShoppingCart;

            m_SkinBase.ThisCustomer.RequireCustomerRecord();
            int CustomerID = m_SkinBase.ThisCustomer.CustomerID;

            ShoppingCart cart = new ShoppingCart(1, m_SkinBase.ThisCustomer, CartType, 0, false);

            for (int i = 0; i < HttpContext.Current.Request.Form.Count; i++)
            {
                String FieldName = HttpContext.Current.Request.Form.Keys[i];
                String FieldVal  = HttpContext.Current.Request.Form[HttpContext.Current.Request.Form.Keys[i]];
                if (FieldName.ToUpperInvariant().IndexOf("_VLDT") == -1 && (FieldName.ToLowerInvariant().StartsWith("price_") || FieldName.ToLowerInvariant().StartsWith("qty_")) && FieldVal.Trim().Length != 0)
                {
                    try // ignore errors, just add what items we can:
                    {
                        decimal CustomerEnteredPrice = Decimal.Zero;
                        int     Qty = 0;
                        if (FieldName.ToLowerInvariant().StartsWith("price_"))
                        {
                            CustomerEnteredPrice = Currency.ConvertToBaseCurrency(Localization.ParseLocaleDecimal(FieldVal, m_SkinBase.ThisCustomer.LocaleSetting), m_SkinBase.ThisCustomer.CurrencySetting);
                        }
                        else
                        {
                            Qty = Localization.ParseNativeInt(FieldVal);
                        }
                        String[] flds      = FieldName.Split('_');
                        int      ProductID = Localization.ParseUSInt(flds[1]);
                        int      VariantID = Localization.ParseUSInt(flds[2]);
                        int      ColorIdx  = Localization.ParseUSInt(flds[3]);
                        int      SizeIdx   = Localization.ParseUSInt(flds[4]);
                        if (Qty == 0)
                        {
                            Qty = 1;
                        }

                        String ChosenColor            = String.Empty;
                        String ChosenSize             = String.Empty;
                        String ChosenColorSKUModifier = String.Empty;
                        String ChosenSizeSKUModifier  = String.Empty;

                        if (ColorIdx > -1 || SizeIdx > -1)
                        {
                            using (SqlConnection dbconn = new SqlConnection(DB.GetDBConn()))
                            {
                                dbconn.Open();
                                using (IDataReader rs = DB.GetRS("select * from productvariant where VariantID=" + VariantID.ToString(), dbconn))
                                {
                                    rs.Read();
                                    ChosenColor = DB.RSFieldByLocale(rs, "Colors", Localization.GetDefaultLocale()).Split(',')[ColorIdx].Trim();
                                    if (DB.RSField(rs, "ColorSKUModifiers").Length != 0)
                                    {
                                        ChosenColorSKUModifier = DB.RSField(rs, "ColorSKUModifiers").Split(',')[ColorIdx].Trim();
                                    }

                                    ChosenSize = DB.RSFieldByLocale(rs, "Sizes", Localization.GetDefaultLocale()).Split(',')[SizeIdx].Trim();
                                    if (DB.RSField(rs, "SizeSKUModifiers").Length != 0)
                                    {
                                        ChosenSizeSKUModifier = DB.RSField(rs, "SizeSKUModifiers").Split(',')[SizeIdx].Trim();
                                    }
                                }
                            }
                        }

                        String TextOption = String.Empty;
                        cart.AddItem(m_SkinBase.ThisCustomer, m_SkinBase.ThisCustomer.PrimaryShippingAddressID, ProductID, VariantID, Qty, ChosenColor, ChosenColorSKUModifier, ChosenSize, ChosenSizeSKUModifier, TextOption, CartType, false, false, 0, CustomerEnteredPrice);
                    }
                    catch { }
                }
            }
            cart = null;


            String ReturnURL = m_SkinBase.Page.Request.Url.ToString();

            if (AppLogic.AppConfig("AddToCartAction").Equals("STAY", StringComparison.InvariantCultureIgnoreCase) && ReturnURL.Length != 0)
            {
                HttpContext.Current.Response.Redirect(ReturnURL);
            }
            else
            {
                String previousEntityPage = SE.MakeObjectLink("Category", m_EntityInstanceID, String.Empty);
                String url = CommonLogic.IIF(CartType.Equals(CartTypeEnum.WishCart), "wishlist.aspx", "ShoppingCart.aspx?add=true&returnurl=" + previousEntityPage);
                HttpContext.Current.Response.Redirect(url);
            }
        }
Пример #21
0
        CartActionResponse UpdateCartFromViewModel(MinicartViewModel cartViewModel, Customer customer, CartTypeEnum cartType)
        {
            if (cartViewModel.CartItems == null)
            {
                return(null);
            }

            var messages = new List <CartActionMessage>();
            CartActionResponse response = null;

            foreach (var cartItem in cartViewModel.CartItems)
            {
                // Is this a Recurring Interval (Variant) change only?
                if (cartItem.RecurringVariantId != 0 &&
                    cartItem.VariantId != cartItem.RecurringVariantId &&
                    AppLogic.AppConfigBool("AllowRecurringFrequencyChangeInCart"))                        // Update Recurring Interval (Variant)
                {
                    response = CartActionProvider.ReplaceRecurringIntervalVariantInCart(
                        customer: customer,
                        cartType: cartType,
                        shoppingCartRecId: cartItem.Id,
                        oldVariantId: cartItem.VariantId,
                        newVariantId: cartItem.RecurringVariantId);
                }
                else                 // Perform regular Qty Update
                {
                    response = CartActionProvider.UpdateItemQuantityInCart(new UpdateQuantityContext()
                    {
                        Customer          = customer,
                        CartType          = cartType,
                        ShoppingCartRecId = cartItem.Id,
                        Quantity          = cartItem.Quantity
                    });
                }

                if (response.Status != CartActionStatus.Success)
                {
                    return(response);
                }

                messages.AddRange(response.Messages.ToList());
            }

            return(new CartActionResponse(
                       updatedCart: response.UpdatedCart
                       ?? CachedShoppingCartProvider.Get(customer, cartType, AppLogic.StoreID()),
                       status: CartActionStatus.Success,
                       messages: messages));
        }
Пример #22
0
 public AvaTaxRateCacheContext(Customer customer, CartTypeEnum cartType, int storeId)
 {
     Customer = customer;
     CartType = cartType;
     StoreId  = storeId;
 }
Пример #23
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            Response.CacheControl = "private";
            Response.Expires      = 0;
            Response.AddHeader("pragma", "no-cache");

            ThisCustomer.RequireCustomerRecord();

            String ReturnURL = CommonLogic.QueryStringCanBeDangerousContent("ReturnURL");

            AppLogic.CheckForScriptTag(ReturnURL);

            CartTypeEnum CartType = CartTypeEnum.ShoppingCart;

            if (CommonLogic.FormNativeInt("IsWishList") == 1 || CommonLogic.QueryStringUSInt("IsWishList") == 1)
            {
                CartType = CartTypeEnum.WishCart;
            }
            if (CommonLogic.FormNativeInt("IsGiftRegistry") == 1 || CommonLogic.QueryStringUSInt("IsGiftRegistry") == 1)
            {
                CartType = CartTypeEnum.GiftRegistryCart;
            }
            if (AppLogic.HideForWholesaleSite(ThisCustomer.CustomerLevelID))
            {
                Response.Redirect("Default.aspx");
            }

            if (!ThisCustomer.IsRegistered && AppLogic.AppConfigBool("DisallowAnonCustomerToCreateWishlist") && AppLogic.ProductIsMLExpress() == false)
            {
                string ErrMsg = string.Empty;

                ErrorMessage er;

                if (CommonLogic.FormNativeInt("IsWishList") == 1 || CommonLogic.QueryStringUSInt("IsWishList") == 1)
                {
                    ErrMsg = AppLogic.GetString("signin.aspx.27", 1, ThisCustomer.LocaleSetting);
                    er     = new ErrorMessage(ErrMsg);
                    Response.Redirect("signin.aspx?ErrorMsg=" + er.MessageId + "&ReturnUrl=" + Security.UrlEncode(ReturnURL));
                }

                if (CommonLogic.FormNativeInt("IsGiftRegistry") == 1 || CommonLogic.QueryStringUSInt("IsGiftRegistry") == 1)
                {
                    ErrMsg = AppLogic.GetString("signin.aspx.28", 1, ThisCustomer.LocaleSetting);
                    er     = new ErrorMessage(ErrMsg);
                    Response.Redirect("signin.aspx?ErrorMsg=" + er.MessageId + "&ReturnUrl=" + Security.UrlEncode(ReturnURL));
                }
            }

            // if editing, nuke what was there, it will be replaced from what was submitted now from the product page.
            // NOTE. if a kit or pack was "edited", you don't have to do this, and ShoppingCartRecID is not material (and should not be in the form post)
            // kits and packs are "moved" from active cart to temp cart records, so they won't have a cart record id to begin with. They are built in the KitCart and CustomCart tables instead
            int ShoppingCartRecID = CommonLogic.FormUSInt("CartRecID"); // only used for (non kit or pack) product/order edits from prior cart record

            if (ShoppingCartRecID == 0)
            {
                ShoppingCartRecID = CommonLogic.QueryStringUSInt("CartRecID");
            }
            if (ShoppingCartRecID != 0)
            {
                DB.ExecuteSQL("delete from ShoppingCart where ShoppingCartRecID=" + ShoppingCartRecID.ToString() + " and CustomerID=" + ThisCustomer.CustomerID.ToString() + " and CartType=" + ((int)CartType).ToString() + " and StoreID = " + AppLogic.StoreID());
            }

            int ShippingAddressID = CommonLogic.QueryStringUSInt("ShippingAddressID"); // only used for multi-ship

            if (ShippingAddressID == 0)
            {
                ShippingAddressID = CommonLogic.FormNativeInt("ShippingAddressID");
            }
            if ((ShippingAddressID == 0 || !ThisCustomer.OwnsThisAddress(ShippingAddressID)) && ThisCustomer.PrimaryShippingAddressID != 0)
            {
                ShippingAddressID = ThisCustomer.PrimaryShippingAddressID;
            }

            int ProductID = CommonLogic.QueryStringUSInt("ProductID");

            if (ProductID == 0)
            {
                ProductID = CommonLogic.FormUSInt("ProductID");
            }

            int VariantID = CommonLogic.QueryStringUSInt("VariantID");

            if (VariantID == 0)
            {
                VariantID = CommonLogic.FormUSInt("VariantID");
            }
            if (ProductID == 0)
            {
                ProductID = AppLogic.GetVariantProductID(VariantID);
            }

            // if no VariantID is located, get the default variantID for the product
            if (VariantID == 0)
            {
                VariantID = AppLogic.GetDefaultProductVariant(ProductID);
            }

            int Quantity = CommonLogic.QueryStringUSInt("Quantity");

            if (Quantity == 0)
            {
                Quantity = CommonLogic.FormNativeInt("Quantity");
            }
            if (Quantity == 0)
            {
                Quantity = 1;
            }

            VariantStyleEnum VariantStyle = (VariantStyleEnum)CommonLogic.QueryStringUSInt("VariantStyle");

            if (CommonLogic.QueryStringCanBeDangerousContent("VariantStyle").Length == 0)
            {
                VariantStyle = (VariantStyleEnum)CommonLogic.FormNativeInt("VariantStyle");
            }

            decimal CustomerEnteredPrice = CommonLogic.FormNativeDecimal("Price");

            if (CustomerEnteredPrice == System.Decimal.Zero)
            {
                CustomerEnteredPrice = CommonLogic.QueryStringNativeDecimal("Price");
            }
            if (!AppLogic.VariantAllowsCustomerPricing(VariantID))
            {
                CustomerEnteredPrice = System.Decimal.Zero;
            }
            if (CustomerEnteredPrice < System.Decimal.Zero)
            {
                CustomerEnteredPrice = -CustomerEnteredPrice;
            }
            int CustomerID = ThisCustomer.CustomerID;

            if (Currency.GetDefaultCurrency() != ThisCustomer.CurrencySetting && CustomerEnteredPrice != 0)
            {
                CustomerEnteredPrice = Currency.Convert(CustomerEnteredPrice, ThisCustomer.CurrencySetting, Localization.StoreCurrency());
            }


            // QueryString params override Form Params!

            String ChosenColor            = String.Empty;
            String ChosenColorSKUModifier = String.Empty;
            String ChosenSize             = String.Empty;
            String ChosenSizeSKUModifier  = String.Empty;
            String TextOption             = CommonLogic.FormCanBeDangerousContent("TextOption");

            if (CommonLogic.QueryStringCanBeDangerousContent("TextOption").Length != 0)
            {
                TextOption = Security.HtmlEncode(CommonLogic.QueryStringCanBeDangerousContent("TextOption"));
            }


            // the color & sizes coming in here are MUST be in the Master WebConfig Locale ALWAYS!
            if (CommonLogic.QueryStringCanBeDangerousContent("Color").Length != 0)
            {
                String[] ColorSel = CommonLogic.QueryStringCanBeDangerousContent("Color").Split(',');
                try
                {
                    ChosenColor = Security.HtmlEncode(ColorSel[0]);
                }
                catch { }
                try
                {
                    ChosenColorSKUModifier = Security.HtmlEncode(ColorSel[1]);
                }
                catch { }
            }

            if (ChosenColor.Length == 0 && CommonLogic.FormCanBeDangerousContent("Color").Length != 0)
            {
                String[] ColorSel = CommonLogic.FormCanBeDangerousContent("Color").Split(',');
                try
                {
                    ChosenColor = Security.HtmlEncode(ColorSel[0]).Trim();
                }
                catch { }
                try
                {
                    ChosenColorSKUModifier = Security.HtmlEncode(ColorSel[1]);
                }
                catch { }
            }

            if (CommonLogic.QueryStringCanBeDangerousContent("Size").Length != 0)
            {
                String[] SizeSel = CommonLogic.QueryStringCanBeDangerousContent("Size").Split(',');
                try
                {
                    ChosenSize = Security.HtmlEncode(SizeSel[0]).Trim();
                }
                catch { }
                try
                {
                    ChosenSizeSKUModifier = Security.HtmlEncode(SizeSel[1]);
                }
                catch { }
            }

            if (ChosenSize.Length == 0 && CommonLogic.FormCanBeDangerousContent("Size").Length != 0)
            {
                String[] SizeSel = CommonLogic.FormCanBeDangerousContent("Size").Split(',');
                try
                {
                    ChosenSize = Security.HtmlEncode(SizeSel[0]).Trim();
                }
                catch { }
                try
                {
                    ChosenSizeSKUModifier = Security.HtmlEncode(SizeSel[1]);
                }
                catch { }
            }


            if (VariantStyle == VariantStyleEnum.ERPWithRollupAttributes)
            {
                String match  = "<GroupAttributes></GroupAttributes>";
                String match2 = "<GroupAttributes></GroupAttributes>";
                if (ChosenSize.Trim().Length != 0 && ChosenColor.Trim().Length != 0)
                {
                    match  = "<GroupAttributes><GroupAttributeName=\"Attr1\"Value=\"" + ChosenSize + "\"/><GroupAttributeName=\"Attr2\"Value=\"" + ChosenColor + "\"/></GroupAttributes>";
                    match2 = "<GroupAttributes><GroupAttributeName=\"Attr1\"Value=\"" + ChosenColor + "\"/><GroupAttributeName=\"Attr2\"Value=\"" + ChosenSize + "\"/></GroupAttributes>";
                }
                else if (ChosenSize.Trim().Length != 0 && ChosenColor.Trim().Length == 0)
                {
                    match = "<GroupAttributes><GroupAttributeName=\"Attr1\"Value=\"" + ChosenSize + "\"/></GroupAttributes>";
                }
                else if (ChosenSize.Trim().Length == 0 && ChosenColor.Trim().Length != 0)
                {
                    match = "<GroupAttributes><GroupAttributeName=\"Attr1\"Value=\"" + ChosenColor + "\"/></GroupAttributes>";
                }

                // reset variant id to the proper attribute match!
                using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
                {
                    con.Open();
                    using (IDataReader rsERP = DB.GetRS("select VariantID,ExtensionData2 from ProductVariant with (NOLOCK) where VariantID=" + VariantID.ToString(), con))
                    {
                        while (rsERP.Read())
                        {
                            String thisVariantMatch = DB.RSField(rsERP, "ExtensionData2").Replace(" ", "").Trim();
                            match = Regex.Replace(match, "\\s+", "", RegexOptions.Compiled);

                            match2 = Regex.Replace(match2, "\\s+", "", RegexOptions.Compiled);

                            thisVariantMatch = Regex.Replace(thisVariantMatch, "\\s+", "", RegexOptions.Compiled);
                            if (match.Equals(thisVariantMatch, StringComparison.InvariantCultureIgnoreCase) ||
                                match2.Equals(thisVariantMatch, StringComparison.InvariantCultureIgnoreCase))
                            {
                                VariantID = DB.RSFieldInt(rsERP, "VariantID");
                                break;
                            }
                        }
                    }
                }
            }

            ShoppingCart cart = new ShoppingCart(1, ThisCustomer, CartType, 0, false);

            if (Quantity > 0)
            {
                if (AppLogic.IsAKit(ProductID))
                {
                    // -- new kit format -- //
                    bool productIsUsingKit2XmlPackage = !CommonLogic.IsStringNullOrEmpty(CommonLogic.FormCanBeDangerousContent("KitItems"));
                    if (productIsUsingKit2XmlPackage)
                    {
                        if (CommonLogic.FormBool("IsEditKit") && CommonLogic.FormUSInt("CartRecID") > 0)
                        {
                            int cartId = CommonLogic.FormUSInt("CartRecID");
                            AppLogic.ClearKitItems(ThisCustomer, ProductID, VariantID, cartId);
                        }

                        KitComposition preferredComposition = KitComposition.FromForm(ThisCustomer, ProductID, VariantID);

                        String tmp      = DB.GetNewGUID();
                        int    NewRecID = cart.AddItem(ThisCustomer, ShippingAddressID, ProductID, VariantID, Quantity, string.Empty, ChosenColorSKUModifier, ChosenSize, ChosenSizeSKUModifier, TextOption, CartType, false, false, 0, System.Decimal.Zero, preferredComposition);
                    }
                    else
                    {
                        String tmp      = DB.GetNewGUID();
                        int    NewRecID = cart.AddItem(ThisCustomer, ShippingAddressID, ProductID, VariantID, Quantity, ChosenColor, ChosenColorSKUModifier, ChosenSize, ChosenSizeSKUModifier, TextOption, CartType, false, false, 0, System.Decimal.Zero);
                    }
                }
                else
                {
                    cart.AddItem(ThisCustomer, ShippingAddressID, ProductID, VariantID, Quantity, ChosenColor, ChosenColorSKUModifier, ChosenSize, ChosenSizeSKUModifier, TextOption, CartType, false, false, 0, CustomerEnteredPrice);
                }
            }

            // handle upsell products:
            String UpsellProducts = CommonLogic.FormCanBeDangerousContent("UpsellProducts").Trim();

            if (UpsellProducts.Length != 0 && CartType == CartTypeEnum.ShoppingCart)
            {
                foreach (String s in UpsellProducts.Split(','))
                {
                    String PID = s.Trim();
                    if (PID.Length != 0)
                    {
                        int UpsellProductID = 0;
                        try
                        {
                            UpsellProductID = Localization.ParseUSInt(PID);
                            if (UpsellProductID != 0)
                            {
                                int UpsellVariantID = AppLogic.GetProductsFirstVariantID(UpsellProductID);
                                if (UpsellVariantID != 0)
                                {
                                    // this variant COULD have one size or color, so set it up like that:
                                    String Sizes             = String.Empty;
                                    String SizeSKUModifiers  = String.Empty;
                                    String Colors            = String.Empty;
                                    String ColorSKUModifiers = String.Empty;

                                    using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
                                    {
                                        con.Open();
                                        using (IDataReader rs = DB.GetRS("select Sizes,SizeSKUModifiers,Colors,ColorSKUModifiers from ProductVariant  with (NOLOCK)  where VariantID=" + UpsellVariantID.ToString(), con))
                                        {
                                            if (rs.Read())
                                            {
                                                Sizes             = DB.RSFieldByLocale(rs, "Sizes", Localization.GetDefaultLocale());
                                                SizeSKUModifiers  = DB.RSFieldByLocale(rs, "SizeSKUModifiers", Localization.GetDefaultLocale());
                                                Colors            = DB.RSFieldByLocale(rs, "Colors", Localization.GetDefaultLocale());
                                                ColorSKUModifiers = DB.RSFieldByLocale(rs, "ColorSKUModifiers", Localization.GetDefaultLocale());
                                            }
                                        }
                                    }

                                    // safety check:
                                    if (Sizes.IndexOf(',') != -1)
                                    {
                                        Sizes            = String.Empty;
                                        SizeSKUModifiers = String.Empty;
                                    }
                                    // safety check:
                                    if (Colors.IndexOf(',') != -1)
                                    {
                                        Colors            = String.Empty;
                                        ColorSKUModifiers = String.Empty;
                                    }
                                    cart.AddItem(ThisCustomer, ShippingAddressID, UpsellProductID, UpsellVariantID, 1, Colors, ColorSKUModifiers, Sizes, SizeSKUModifiers, String.Empty, CartType, false, false, 0, System.Decimal.Zero);
                                    Decimal PR = AppLogic.GetUpsellProductPrice(ProductID, UpsellProductID, ThisCustomer.CustomerLevelID);
                                    DB.ExecuteSQL("update shoppingcart set IsUpsell=1, ProductPrice=" + Localization.CurrencyStringForDBWithoutExchangeRate(PR) + " where CartType=" + ((int)CartType).ToString() + " and CustomerID=" + ThisCustomer.CustomerID.ToString() + " and ProductID=" + UpsellProductID.ToString() + " and VariantID=" + UpsellVariantID.ToString() + " and convert(nvarchar(1000),ChosenColor)='' and convert(nvarchar(1000),ChosenSize)='' and convert(nvarchar(1000),TextOption)=''");
                                }
                            }
                        }
                        catch { }
                    }
                }
            }

            cart = null;

            AppLogic.eventHandler("AddToCart").CallEvent("&AddToCart=true&VariantID=" + VariantID.ToString() + "&ProductID=" + ProductID.ToString() + "&ChosenColor=" + ChosenColor + "&ChosenSize=" + ChosenSize);

            if (AppLogic.AppConfig("AddToCartAction").Equals("STAY", StringComparison.InvariantCultureIgnoreCase) &&
                ReturnURL.Length != 0)
            {
                Response.Redirect(ReturnURL);
            }
            else
            {
                if (ReturnURL.Length == 0)
                {
                    ReturnURL = String.Empty;
                    if (Request.UrlReferrer != null)
                    {
                        ReturnURL = Request.UrlReferrer.AbsoluteUri; // could be null
                    }
                    if (ReturnURL == null)
                    {
                        ReturnURL = String.Empty;
                    }
                }
                if (CartType == CartTypeEnum.WishCart)
                {
                    Response.Redirect("wishlist.aspx?ReturnUrl=" + Security.UrlEncode(ReturnURL));
                }
                if (CartType == CartTypeEnum.GiftRegistryCart)
                {
                    Response.Redirect("giftregistry.aspx?ReturnUrl=" + Security.UrlEncode(ReturnURL));
                }
                Response.Redirect("ShoppingCart.aspx?add=true&ReturnUrl=" + Security.UrlEncode(ReturnURL));
            }
        }
Пример #24
0
        public void ProcessCart(bool DoingFullCheckout)
        {
            Response.CacheControl = "private";
            Response.Expires      = 0;
            Response.AddHeader("pragma", "no-cache");

            ThisCustomer.RequireCustomerRecord();
            CartTypeEnum cte = CartTypeEnum.ShoppingCart;

            if (CommonLogic.QueryStringCanBeDangerousContent("CartType").Length != 0)
            {
                cte = (CartTypeEnum)CommonLogic.QueryStringUSInt("CartType");
            }
            cart = new InterpriseShoppingCart(null, 1, ThisCustomer, cte, string.Empty, false, true);

            if (!Page.IsPostBack)
            {
                string couponCode = string.Empty;
                if (cart.HasCoupon(ref couponCode))
                {
                    CouponCode.Text = couponCode;
                }
            }
            else
            {
                if (string.IsNullOrEmpty(CouponCode.Text))
                {
                    cart.ClearCoupon();
                }
            }

            // check if credit on hold
            if (ThisCustomer.IsCreditOnHold)
            {
                Response.Redirect("shoppingcart.aspx");
            }

            if (cart.IsEmpty())
            {
                // can't have this at this point:
                switch (cte)
                {
                case CartTypeEnum.ShoppingCart:
                    Response.Redirect("shoppingcart.aspx");
                    break;

                case CartTypeEnum.WishCart:
                    Response.Redirect("wishlist.aspx");
                    break;

                case CartTypeEnum.GiftRegistryCart:
                    Response.Redirect("giftregistry.aspx");
                    break;

                default:
                    Response.Redirect("shoppingcart.aspx");
                    break;
                }
            }

            //Make it a method
            UpdateCartItems();

            // save coupon code, no need to reload cart object
            // will update customer record also:
            if (cte == CartTypeEnum.ShoppingCart)
            {
                if (!string.IsNullOrEmpty(CouponCode.Text))
                {
                    string errorMessage = string.Empty;
                    if (cart.IsCouponValid(ThisCustomer, CouponCode.Text, ref errorMessage))
                    {
                        cart.ApplyCoupon(CouponCode.Text);
                    }
                    else
                    {
                        // NULL out the coupon for this cusotmer...
                        InterpriseHelper.ClearCustomerCoupon(ThisCustomer.CustomerCode, ThisCustomer.IsRegistered);

                        ErrorMsgLabel.Text = errorMessage;
                        CouponCode.Text    = string.Empty;
                        return;
                    }
                }

                // check for upsell products
                if (CommonLogic.FormCanBeDangerousContent("Upsell").Length != 0)
                {
                    foreach (string s in CommonLogic.FormCanBeDangerousContent("Upsell").Split(','))
                    {
                        int ProductID = Localization.ParseUSInt(s);
                        if (ProductID == 0)
                        {
                            continue;
                        }

                        string itemCode = InterpriseHelper.GetInventoryItemCode(ProductID);
                        string shippingAddressID;

                        shippingAddressID = CommonLogic.IIF(ThisCustomer.IsNotRegistered, string.Empty, ThisCustomer.PrimaryShippingAddressID);

                        var umInfo = InterpriseHelper.GetItemDefaultUnitMeasure(itemCode);
                        cart.AddItem(ThisCustomer, shippingAddressID, itemCode, ProductID, 1, umInfo.Code, CartTypeEnum.ShoppingCart);
                    }
                }

                bool hasCheckedOptions = false;

                if (pnlOrderOptions.Visible)
                {
                    // Process the Order Options
                    foreach (RepeaterItem ri in OrderOptionsList.Items)
                    {
                        hasCheckedOptions = true;
                        DataCheckBox cbk = (DataCheckBox)ri.FindControl("OrderOptions");
                        if (cbk.Checked)
                        {
                            string      itemCode  = (string)cbk.Data;
                            HiddenField hfCounter = ri.FindControl("hfItemCounter") as HiddenField;
                            TextBox     txtNotes  = ri.FindControl("txtOrderOptionNotes") as TextBox;

                            string strNotes = HttpUtility.HtmlEncode(txtNotes.Text);
                            string notes    = CommonLogic.IIF((strNotes != null), CommonLogic.CleanLevelOne(strNotes), string.Empty);

                            //check the length of order option notes
                            //should not exceed 1000 characters including spaces
                            int maxLen = 1000;
                            if (notes.Length > maxLen)
                            {
                                notes = notes.Substring(0, maxLen);
                            }

                            string unitMeasureCode = string.Empty;

                            // check if the item has only 1 unit measure
                            // hence it's rendered as a label
                            // else it would be rendered as a drop down list
                            Label lblUnitMeasureCode = ri.FindControl("lblUnitMeasureCode") as Label;
                            if (null != lblUnitMeasureCode && lblUnitMeasureCode.Visible)
                            {
                                unitMeasureCode = lblUnitMeasureCode.Text;
                            }
                            else
                            {
                                // it's rendered as combobox because the item has multiple unit measures configured
                                DropDownList cboUnitMeasureCode = ri.FindControl("cboUnitMeasureCode") as DropDownList;
                                if (null != cboUnitMeasureCode && cboUnitMeasureCode.Visible)
                                {
                                    unitMeasureCode = cboUnitMeasureCode.SelectedValue;
                                }
                            }

                            if (CommonLogic.IsStringNullOrEmpty(unitMeasureCode))
                            {
                                throw new ArgumentException("Unit Measure not specified!!!");
                            }

                            //check if this Order Option has Restricted Quantity and Minimum Order Qty set.
                            decimal itemQuantity = 1;

                            using (var con = DB.NewSqlConnection())
                            {
                                con.Open();
                                using (var reader = DB.GetRSFormat(con, "SELECT iw.RestrictedQuantity, iw.MinOrderQuantity FROM InventoryItem i with (NOLOCK) INNER JOIN InventoryItemWebOption iw with (NOLOCK) ON i.ItemCode = iw.ItemCode AND iw.WebsiteCode = {0} WHERE i.ItemCode = {1}", DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode), DB.SQuote(itemCode)))
                                {
                                    if (reader.Read())
                                    {
                                        string  restrictedQuantitiesValue = DB.RSField(reader, "RestrictedQuantity");
                                        decimal minimumOrderQuantity      = Convert.ToDecimal(DB.RSFieldDecimal(reader, "MinOrderQuantity"));
                                        if (!CommonLogic.IsStringNullOrEmpty(restrictedQuantitiesValue))
                                        {
                                            string[] quantityValues = restrictedQuantitiesValue.Split(',');
                                            if (quantityValues.Length > 0)
                                            {
                                                int  ctr  = 0;
                                                bool loop = true;
                                                while (loop)
                                                {
                                                    int    quantity      = 0;
                                                    string quantityValue = quantityValues[ctr];
                                                    if (int.TryParse(quantityValue, out quantity))
                                                    {
                                                        if (quantity >= minimumOrderQuantity)
                                                        {
                                                            itemQuantity = quantity;
                                                            loop         = false;
                                                        }
                                                    }
                                                    ctr++;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            if (minimumOrderQuantity > 0)
                                            {
                                                itemQuantity = minimumOrderQuantity;
                                            }
                                        }
                                    }
                                }
                            }
                            // Add the selected Order Option....
                            Guid cartItemId = Guid.Empty;
                            cart.AddItem(ThisCustomer, ThisCustomer.PrimaryShippingAddressID, itemCode, int.Parse(hfCounter.Value), itemQuantity, unitMeasureCode, CartTypeEnum.ShoppingCart);
                        }
                    }
                }

                if (hasCheckedOptions)
                {
                    //refresh the option items
                    RenderOrderOptions();
                }

                if (OrderNotes.Visible)
                {
                    string sOrderNotes = CommonLogic.CleanLevelOne(OrderNotes.Text);
                    //check the length of order notes
                    //should not exceed 255 characters including spaces
                    if (sOrderNotes.Length > DomainConstants.ORDER_NOTE_MAX_LENGTH)
                    {
                        sOrderNotes = sOrderNotes.Substring(0, DomainConstants.ORDER_NOTE_MAX_LENGTH);
                    }

                    DB.ExecuteSQL(
                        String.Format("UPDATE Customer SET Notes = {0} WHERE CustomerCode = {1}",
                                      sOrderNotes.ToDbQuote(),
                                      ThisCustomer.CustomerCode.ToDbQuote())
                        );
                }
            }
            bool validated = true;

            if (cart.InventoryTrimmed)
            {
                // inventory got adjusted, send them back to the cart page to confirm the new values!
                ErrorMsgLabel.Text += Server.UrlDecode(AppLogic.GetString("shoppingcart.cs.43", SkinID, ThisCustomer.LocaleSetting));
                validated           = false;
            }
            cart = new InterpriseShoppingCart(base.EntityHelpers, SkinID, ThisCustomer, CartTypeEnum.ShoppingCart, string.Empty, false, true);

            if (AppLogic.AppConfigBool("ShowShipDateInCart") && AppLogic.AppConfigBool("ShowStockHints"))
            {
                cart.BuildSalesOrderDetails();
            }

            if (cte == CartTypeEnum.WishCart)
            {
                Response.Redirect("wishlist.aspx");
            }
            if (cte == CartTypeEnum.GiftRegistryCart)
            {
                Response.Redirect("giftregistry.aspx");
            }

            if (DoingFullCheckout)
            {
                if (!cart.MeetsMinimumOrderAmount(AppLogic.AppConfigUSDecimal("CartMinOrderAmount")))
                {
                    validated = false;
                }

                if (!cart.MeetsMinimumOrderQuantity(AppLogic.AppConfigUSInt("MinCartItemsBeforeCheckout")))
                {
                    validated = false;
                }

                string couponCode         = string.Empty;
                string couponErrorMessage = string.Empty;
                if (cart.HasCoupon(ref couponCode) && !cart.IsCouponValid(ThisCustomer, couponCode, ref couponErrorMessage))
                {
                    validated = false;
                }

                //One page checkout is not implemented in mobile.

                //if (AppLogic.AppConfigBool("Checkout.UseOnePageCheckout") && !cart.HasMultipleShippingAddresses())
                //{
                //    Response.Redirect("checkout1.aspx");
                //}

                if (validated)
                {
                    if (ThisCustomer.IsRegistered && (ThisCustomer.PrimaryBillingAddressID == string.Empty)) // || !ThisCustomer.HasAtLeastOneAddress()
                    {
                        Response.Redirect("selectaddress.aspx?add=true&setPrimary=true&checkout=true&addressType=Billing");
                    }

                    if (ThisCustomer.IsRegistered && (ThisCustomer.PrimaryShippingAddressID == string.Empty)) //  || !ThisCustomer.HasAtLeastOneAddress()
                    {
                        Response.Redirect("selectaddress.aspx?add=true&setPrimary=true&checkout=False&addressType=Shipping");
                    }

                    if (ThisCustomer.IsNotRegistered || ThisCustomer.PrimaryBillingAddressID == string.Empty || ThisCustomer.PrimaryShippingAddressID == string.Empty || !ThisCustomer.HasAtLeastOneAddress())
                    {
                        Response.Redirect("checkoutanon.aspx?checkout=true");
                    }
                    else
                    {
                        if (AppLogic.AppConfigBool("SkipShippingOnCheckout") ||
                            !cart.HasShippableComponents())
                        {
                            cart.MakeShippingNotRequired();
                            Response.Redirect("checkoutpayment.aspx");
                        }

                        if ((cart.HasMultipleShippingAddresses() && cart.NumItems() <= AppLogic.MultiShipMaxNumItemsAllowed() && cart.CartAllowsShippingMethodSelection))
                        {
                            Response.Redirect("checkoutshippingmult.aspx");
                        }
                        else
                        {
                            Response.Redirect("checkoutshipping.aspx");
                        }
                    }
                }
                InitializePageContent();
            }
        }