Beispiel #1
0
 public bool Add(ShoppingCartItem model)
 {
     StringBuilder builder = new StringBuilder();
     builder.Append("insert into Shop_ShoppingCarts(");
     builder.Append("ItemId,UserId,Target,Quantity,ItemType,Name,ThumbnailsUrl,Description,CostPrice,SellPrice,AdjustedPrice,Attributes,Weight,Deduct,Points,ProductLineId,SupplierId,SupplierName)");
     builder.Append(" values (");
     builder.Append("@ItemId,@UserId,@Target,@Quantity,@ItemType,@Name,@ThumbnailsUrl,@Description,@CostPrice,@SellPrice,@AdjustedPrice,@Attributes,@Weight,@Deduct,@Points,@ProductLineId,@SupplierId,@SupplierName)");
     SqlParameter[] cmdParms = new SqlParameter[] { 
         new SqlParameter("@ItemId", SqlDbType.Int, 4), new SqlParameter("@UserId", SqlDbType.Int, 4), new SqlParameter("@SKU", SqlDbType.NVarChar, 50), new SqlParameter("@Quantity", SqlDbType.Int, 4), new SqlParameter("@ItemType", SqlDbType.Int, 4), new SqlParameter("@Name", SqlDbType.NVarChar, 200), new SqlParameter("@ThumbnailsUrl", SqlDbType.NVarChar, 300), new SqlParameter("@Description", SqlDbType.NVarChar, 500), new SqlParameter("@CostPrice", SqlDbType.Money, 8), new SqlParameter("@SellPrice", SqlDbType.Money, 8), new SqlParameter("@AdjustedPrice", SqlDbType.Money, 8), new SqlParameter("@Attributes", SqlDbType.Text), new SqlParameter("@Weight", SqlDbType.Int, 4), new SqlParameter("@Deduct", SqlDbType.Money, 8), new SqlParameter("@Points", SqlDbType.Int, 4), new SqlParameter("@ProductLineId", SqlDbType.Int, 4), 
         new SqlParameter("@SupplierId", SqlDbType.Int, 4), new SqlParameter("@SupplierName", SqlDbType.NVarChar, 100)
      };
     cmdParms[0].Value = model.ItemId;
     cmdParms[1].Value = model.UserId;
     cmdParms[2].Value = model.SKU;
     cmdParms[3].Value = model.Quantity;
     cmdParms[4].Value = model.ItemType;
     cmdParms[5].Value = model.Name;
     cmdParms[6].Value = model.ThumbnailsUrl;
     cmdParms[7].Value = model.Description;
     cmdParms[8].Value = model.CostPrice;
     cmdParms[9].Value = model.SellPrice;
     cmdParms[10].Value = model.AdjustedPrice;
     cmdParms[11].Value = model.Attributes;
     cmdParms[12].Value = model.Weight;
     cmdParms[13].Value = model.Deduct;
     cmdParms[14].Value = model.Points;
     cmdParms[15].Value = model.ProductLineId;
     cmdParms[0x10].Value = model.SupplierId;
     cmdParms[0x11].Value = model.SupplierName;
     return (DbHelperSQL.ExecuteSql(builder.ToString(), cmdParms) > 0);
 }
Beispiel #2
0
        public void AddProductToCart(Guid customerId, Guid productId, int quantity)
        {
            var user = _userRepository.Get(customerId);

            var shoppingCart = _shoppingCartRepository.Single(s => s.User.Id == user.Id);
            if (shoppingCart == null)
                throw new DomainException("User {0} don't exist shoppingcart.", customerId);

            var product = _productRepository.Get(productId);
            var shoppingCartItem = _shoppingCartItemRepository.FindItem(shoppingCart, product);
            if (shoppingCartItem == null)
            {
                shoppingCartItem = new ShoppingCartItem()
                {
                    Product = product,
                    ShoppingCart = shoppingCart,
                    Quantity = quantity
                };

                _shoppingCartItemRepository.Insert(shoppingCartItem);
            }
            else
            {
                shoppingCartItem.UpdateQuantity(shoppingCartItem.Quantity + quantity);
                _shoppingCartItemRepository.Update(shoppingCartItem);
            }
        }
Beispiel #3
0
 public CartItemAdded(ShoppingCart cart, ShoppingCartItem item)
 {
     CartId = cart.Id;
     ItemId = item.Id;
     ProductId = item.ProductPrice.ProductId;
     ProductPriceId = item.ProductPrice.Id;
     Quantity = item.Quantity;
 }
 public CartItemQuantityChanged(ShoppingCart cart, ShoppingCartItem item, int oldQuantity)
 {
     CartId = cart.Id;
     ItemId = item.Id;
     ProductId = item.ProductPrice.ProductId;
     ProductPriceId = item.ProductPrice.Id;
     OldQuantity = oldQuantity;
     NewQuantity = item.Quantity;
 }
        public void AddItem(ShoppingCart cart, ShoppingCartItem item)
        {
            Require.NotNull(cart, "cart");
            Require.NotNull(item, "item");

            cart.Items.Add(item);
            _repository.Database.SaveChanges();

            Event.Raise(new CartItemAdded(cart, item));
        }
 public ActionResult AddCart(string sku, int count = 1, string viewName = "AddCart")
 {
     if (string.IsNullOrWhiteSpace(sku))
     {
         return base.RedirectToAction("Index", "Home");
     }
     int userId = (base.currentUser == null) ? -1 : base.currentUser.UserID;
     ShoppingCartHelper helper = new ShoppingCartHelper(userId);
     ShoppingCartItem cartItem = new ShoppingCartItem();
     ProductModel model = new ProductModel();
     Maticsoft.Model.Shop.Products.SKUInfo modelBySKU = this.skuBll.GetModelBySKU(sku);
     if (modelBySKU == null)
     {
         return base.Content("NOSKU");
     }
     List<Maticsoft.Model.Shop.Products.SKUInfo> list2 = new List<Maticsoft.Model.Shop.Products.SKUInfo> {
         modelBySKU
     };
     model.ProductSkus = list2;
     model.ProductInfo = this.productBll.GetModelByCache(modelBySKU.ProductId);
     if ((model.ProductInfo != null) && (model.ProductSkus != null))
     {
         cartItem.Name = model.ProductInfo.ProductName;
         cartItem.Quantity = count;
         cartItem.SKU = model.ProductSkus[0].SKU;
         cartItem.ProductId = model.ProductInfo.ProductId;
         cartItem.UserId = userId;
         List<Maticsoft.Model.Shop.Products.SKUItem> sKUItemsBySkuId = this.skuBll.GetSKUItemsBySkuId(modelBySKU.SkuId);
         if ((sKUItemsBySkuId != null) && (sKUItemsBySkuId.Count > 0))
         {
             cartItem.SkuValues = new string[sKUItemsBySkuId.Count];
             int index = 0;
             sKUItemsBySkuId.ForEach(delegate (Maticsoft.Model.Shop.Products.SKUItem xx) {
                 cartItem.SkuValues[index++] = xx.ValueStr;
                 if (!string.IsNullOrWhiteSpace(xx.ImageUrl))
                 {
                     cartItem.SkuImageUrl = xx.ImageUrl;
                 }
             });
         }
         cartItem.ThumbnailsUrl = model.ProductInfo.ThumbnailUrl1;
         cartItem.CostPrice = model.ProductSkus[0].CostPrice.HasValue ? model.ProductSkus[0].CostPrice.Value : 0M;
         cartItem.MarketPrice = model.ProductInfo.MarketPrice.HasValue ? model.ProductInfo.MarketPrice.Value : 0M;
         cartItem.SellPrice = cartItem.AdjustedPrice = model.ProductSkus[0].SalePrice;
         cartItem.Weight = model.ProductSkus[0].Weight.HasValue ? model.ProductSkus[0].Weight.Value : 0;
         helper.AddItem(cartItem);
         ShoppingCartInfo shoppingCart = helper.GetShoppingCart();
         ((dynamic) base.ViewBag).TotalPrice = shoppingCart.TotalSellPrice;
         ((dynamic) base.ViewBag).ItemCount = shoppingCart.Quantity;
     }
     ((dynamic) base.ViewBag).Title = "添加购物车";
     return base.RedirectToAction("CartInfo");
 }
Beispiel #7
0
 public bool FindProduct(ShoppingCartItem cart)
 {
     int index = MyCartList.IndexOf(cart);
     if (index <0 )
         return false;
     else
     {
         MyCartList[index].Quantity += cart.Quantity;
         MyCartList[index].Total = (MyCartList[index].Quantity * MyCartList[index].UnitPrice);
         return true;
     }
 }
    protected void ProductFormView_ItemCommand(object sender, FormViewCommandEventArgs e)
    {
        ShoppingCartItem cart = new ShoppingCartItem();
        if (Session["UserName"] != null)
        {
            if (e.CommandName == "AddToCartcmd")
                AddToCart(cart);

            if (e.CommandName == "WishListcmd")
                AddToWishList();
        }
    }
        // PUT api/awbuildversion/5
        public void Put(ShoppingCartItem value)
        {
            var GetActionType = Request.Headers.Where(x => x.Key.Equals("ActionType")).FirstOrDefault();

            if (GetActionType.Key != null)
            {
                if (GetActionType.Value.ToList()[0].Equals("DELETE"))
                    adventureWorks_BC.ShoppingCartItemDelete(value);
                if (GetActionType.Value.ToList()[0].Equals("UPDATE"))
                    adventureWorks_BC.ShoppingCartItemUpdate(value);
            }
        }
Beispiel #10
0
    /// <summary>
    /// e-event retains its value, hence we are able to get quantity text box value
    /// </summary>
    /// <param name="source"></param>
    /// <param name="e"></param>
    protected void ProductDataList_ItemCommand(object source, DataListCommandEventArgs e)
    {
        ShoppingCartItem cart = new ShoppingCartItem();
        if (Session["UserName"] != null)
        {
            if (e.CommandName == "AddToCartcmd")
            {
                AddToCart(e, cart);
            }

            if (e.CommandName == "WishListcmd")
                InsertWishList(e);
        }
    }
Beispiel #11
0
    /// <summary>
    /// items to be added to database
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void AddToCartLinkButton_Click(object sender, EventArgs e)
    {
        //RetreiveWishList();
        ShoppingCartItem cart = new ShoppingCartItem();
        GridViewRow row = ((Control)sender).NamingContainer as GridViewRow;
        GridView grid = row.NamingContainer as GridView;
        //LOADCATEGORIES
        cart.ProductId = grid.DataKeys[row.RowIndex].Value.ToString();
        cart.ProductName = (row.FindControl("ProductLabel") as Label).Text;
        cart.UnitPrice = decimal.Parse((row.FindControl("UnitPriceLabel") as Label).Text);
        cart.Quantity = 1;
        cart.Total = cart.UnitPrice * cart.Quantity;

        ShoppingCartItem temp = new ShoppingCartItem { ProductId = cart.ProductId, Quantity = cart.Quantity };
        if (!myCart.FindProduct(temp))
            myCart.AddCart(cart);

        Server.Transfer("~/Modules/aspx/MyCart.aspx");
    }
        public void ShoppingCartItem_Serialize_PropertyNamesAsExpected()
        {
            // Arrange
            var shoppingCartItem = new ShoppingCartItem(null, 0, 0, "EUR");

            // Act
            var serializedObject = JsonConvert.SerializeObject(shoppingCartItem);

            // Assert
            Assert.AreEqual(@"{
				""name"": null,
				""description"": null,
				""unit_price"": 0.0,
                ""currency"": ""EUR"",
				""quantity"": 0,
				""merchant_item_id"": null,
				""tax_table_selector"": null,
				""weight"": null
			}".RemoveWhiteSpace(), serializedObject.RemoveWhiteSpace());
        }
        public ShoppingCartItem AddItem(ShoppingCart cart, Product product, ProductPrice productPrice, int quantity)
        {
            Require.NotNull(cart, "cart");
            Require.NotNull(product, "product");
            Require.NotNull(productPrice, "productPrice");
            Require.That(quantity > 0, "quantity", "Quantity should be greater than zero.");

            var item = cart.Items.FirstOrDefault(i => i.ProductPrice.Id == productPrice.Id);
            if (item == null)
            {
                item = new ShoppingCartItem(productPrice, quantity, cart);
                AddItem(cart, item);
            }
            else
            {
                ChangeItemQuantity(cart, item, item.Quantity + quantity);
            }

            return item;
        }
    private void AddToCart(ShoppingCartItem cart)
    {
        cart.ProductId = ProductFormView.DataKey[0].ToString();
        cart.ProductName = (ProductFormView.Row.FindControl("ProductLabel") as Label).Text;
        cart.UnitPrice = decimal.Parse((ProductFormView.Row.FindControl("UnitPriceLabel") as Label).Text);
        TextBox quantityTextBox = ProductFormView.Row.FindControl("QuantityTextBox") as TextBox;
        if (quantityTextBox.Text.Equals(string.Empty))
            cart.Quantity = 1;
        else
            cart.Quantity = int.Parse(quantityTextBox.Text);
        cart.Total = cart.UnitPrice * cart.Quantity;

        ShoppingCartItem temp = new ShoppingCartItem { ProductId = cart.ProductId, Quantity = cart.Quantity };
        if (!myCart.FindProduct(temp))
            myCart.AddCart(cart);

        Session["MyCart"] = myCart;

        Server.Transfer("~/Modules/aspx/MyCart.aspx");
    }
        public void Add(int id)
        {
            ShoppingCartItem cartItem = (from item in Items
                                         where item.Id == id
                                         select item).FirstOrDefault();

            if (cartItem == null)
            {
                Movie movie = repository.Get(id);
                cartItem = new ShoppingCartItem
                {
                    Id = movie.Id,
                    Title = movie.Title,
                    UnitPrice = movie.Price,
                    Quantity = 1
                };
                Items.Add(cartItem);
            }
            else
                cartItem.Quantity++;
        }
Beispiel #16
0
        public void TestPrice()
        {
            var item = new ShoppingCartItem(price: 10m);

            Assert.Equal(10m, item.Price);
        }
Beispiel #17
0
        public void TestItemId()
        {
            var item = new ShoppingCartItem(itemId: "id5");

            Assert.Equal("id5", item.ItemId);
        }
Beispiel #18
0
        /// <summary>
        /// Get dimensions of associated products (for quantity 1)
        /// </summary>
        /// <param name="shoppingCartItem">Shopping cart item</param>
        /// <param name="ignoreFreeShippedItems">Whether to ignore the weight of the products marked as "Free shipping"</param>
        /// <returns>Width. Length. Height</returns>
        protected virtual async Task <(decimal width, decimal length, decimal height)> GetAssociatedProductDimensionsAsync(ShoppingCartItem shoppingCartItem,
                                                                                                                           bool ignoreFreeShippedItems = false)
        {
            if (shoppingCartItem == null)
            {
                throw new ArgumentNullException(nameof(shoppingCartItem));
            }

            decimal length;
            decimal height;
            decimal width;

            width = length = height = decimal.Zero;

            //don't consider associated products dimensions
            if (!_shippingSettings.ConsiderAssociatedProductsDimensions)
            {
                return(width, length, height);
            }

            //attributes
            if (string.IsNullOrEmpty(shoppingCartItem.AttributesXml))
            {
                return(width, length, height);
            }

            //bundled products (associated attributes)
            var attributeValues = (await _productAttributeParser.ParseProductAttributeValuesAsync(shoppingCartItem.AttributesXml))
                                  .Where(x => x.AttributeValueType == AttributeValueType.AssociatedToProduct).ToList();

            foreach (var attributeValue in attributeValues)
            {
                var associatedProduct = await _productService.GetProductByIdAsync(attributeValue.AssociatedProductId);

                if (associatedProduct == null || !associatedProduct.IsShipEnabled || (associatedProduct.IsFreeShipping && ignoreFreeShippedItems))
                {
                    continue;
                }

                width  += associatedProduct.Width * attributeValue.Quantity;
                length += associatedProduct.Length * attributeValue.Quantity;
                height += associatedProduct.Height * attributeValue.Quantity;
            }

            return(width, length, height);
        }
Beispiel #19
0
 public void InitProduct()
 {
     _product          = new Product(ProductType.Perfume, "Imported bottle of parfume");
     _shoppingCartItem = new ShoppingCartItem(_calculator, _product, true, 47.50m);
 }
        /// <summary>
        /// Handle shopping cart changed event
        /// </summary>
        /// <param name="cartItem">Shopping cart item</param>
        public void HandleShoppingCartChangedEvent(ShoppingCartItem cartItem)
        {
            //whether marketing automation is enabled
            if (!_sendInBlueSettings.UseMarketingAutomation)
            {
                return;
            }

            try
            {
                //create API client
                var client = CreateMarketingAutomationClient();

                //first, try to identify current customer
                client.Identify(new Identify(cartItem.Customer.Email));

                //get shopping cart GUID
                var shoppingCartGuid = _genericAttributeService.GetAttribute <Guid?>(cartItem.Customer, SendinBlueDefaults.ShoppingCartGuidAttribute);

                //create track event object
                var trackEvent = new TrackEvent(cartItem.Customer.Email, string.Empty);

                //get current customer's shopping cart
                var cart = cartItem.Customer.ShoppingCartItems
                           .Where(item => item.ShoppingCartType == ShoppingCartType.ShoppingCart)
                           .LimitPerStore(_storeContext.CurrentStore.Id).ToList();

                if (cart.Any())
                {
                    //get URL helper
                    var urlHelper = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext);

                    //get shopping cart amounts
                    _orderTotalCalculationService.GetShoppingCartSubTotal(cart, _workContext.TaxDisplayType == TaxDisplayType.IncludingTax,
                                                                          out var cartDiscount, out _, out var cartSubtotal, out _);
                    var cartTax      = _orderTotalCalculationService.GetTaxTotal(cart, false);
                    var cartShipping = _orderTotalCalculationService.GetShoppingCartShippingTotal(cart);
                    var cartTotal    = _orderTotalCalculationService.GetShoppingCartTotal(cart, false, false);

                    //get products data by shopping cart items
                    var itemsData = cart.Where(item => item.Product != null).Select(item =>
                    {
                        //try to get product attribute combination
                        var combination = _productAttributeParser.FindProductAttributeCombination(item.Product, item.AttributesXml);

                        //get default product picture
                        var picture = _pictureService.GetProductPicture(item.Product, item.AttributesXml);

                        //get product SEO slug name
                        var seName = _urlRecordService.GetSeName(item.Product);

                        //create product data
                        return(new
                        {
                            id = item.Product.Id,
                            name = item.Product.Name,
                            variant_id = combination?.Id ?? item.Product.Id,
                            variant_name = combination?.Sku ?? item.Product.Name,
                            sku = combination?.Sku ?? item.Product.Sku,
                            category = item.Product.ProductCategories.Aggregate(",", (all, category) => {
                                var res = category.Category.Name;
                                res = all == "," ? res : all + ", " + res;
                                return res;
                            }),
                            url = urlHelper.RouteUrl("Product", new { SeName = seName }, _webHelper.CurrentRequestProtocol),
                            image = _pictureService.GetPictureUrl(picture),
                            quantity = item.Quantity,
                            price = _priceCalculationService.GetSubTotal(item)
                        });
                    }).ToArray();

                    //prepare cart data
                    var cartData = new
                    {
                        affiliation      = _storeContext.CurrentStore.Name,
                        subtotal         = cartSubtotal,
                        shipping         = cartShipping ?? decimal.Zero,
                        total_before_tax = cartSubtotal + cartShipping ?? decimal.Zero,
                        tax      = cartTax,
                        discount = cartDiscount,
                        revenue  = cartTotal ?? decimal.Zero,
                        url      = urlHelper.RouteUrl("ShoppingCart", null, _webHelper.CurrentRequestProtocol),
                        currency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)?.CurrencyCode,
                        //gift_wrapping = string.Empty, //currently we can't get this value
                        items = itemsData
                    };

                    //if there is a single item in the cart, so the cart is just created
                    if (cart.Count == 1)
                    {
                        shoppingCartGuid = Guid.NewGuid();
                    }
                    else
                    {
                        //otherwise cart is updated
                        shoppingCartGuid = shoppingCartGuid ?? Guid.NewGuid();
                    }
                    trackEvent.EventName = SendinBlueDefaults.CartUpdatedEventName;
                    trackEvent.EventData = new { id = $"cart:{shoppingCartGuid}", data = cartData };
                }
                else
                {
                    //there are no items in the cart, so the cart is deleted
                    shoppingCartGuid     = shoppingCartGuid ?? Guid.NewGuid();
                    trackEvent.EventName = SendinBlueDefaults.CartDeletedEventName;
                    trackEvent.EventData = new { id = $"cart:{shoppingCartGuid}" };
                }

                //track event
                client.TrackEvent(trackEvent);

                //update GUID for the current customer's shopping cart
                _genericAttributeService.SaveAttribute(cartItem.Customer, SendinBlueDefaults.ShoppingCartGuidAttribute, shoppingCartGuid);
            }
            catch (Exception exception)
            {
                //log full error
                _logger.Error($"SendinBlue Marketing Automation error: {exception.Message}.", exception, cartItem.Customer);
            }
        }
Beispiel #21
0
        public virtual async Task <IActionResult> AddBid(string productId, int shoppingCartTypeId, IFormCollection form,
                                                         [FromServices] IAuctionService auctionService)
        {
            var customer = _workContext.CurrentCustomer;

            if (!await _groupService.IsRegistered(customer))
            {
                return(Json(new
                {
                    success = false,
                    message = _translationService.GetResource("ShoppingCart.Mustberegisteredtobid")
                }));
            }
            decimal bid = 0;

            foreach (string formKey in form.Keys)
            {
                if (formKey.Equals(string.Format("auction_{0}.HighestBidValue", productId), StringComparison.OrdinalIgnoreCase))
                {
                    decimal.TryParse(form[formKey], out bid);
                    if (bid == 0)
                    {
                        decimal.TryParse(form[formKey], NumberStyles.AllowDecimalPoint, CultureInfo.GetCultureInfo("en-US").NumberFormat, out bid);
                    }

                    bid = Math.Round(bid, 2);
                    break;
                }
            }
            if (bid <= 0)
            {
                return(Json(new
                {
                    success = false,
                    message = _translationService.GetResource("ShoppingCart.BidMustBeHigher")
                }));
            }

            Product product = await _productService.GetProductById(productId);

            if (product == null)
            {
                throw new ArgumentNullException(nameof(product));
            }

            if (product.HighestBidder == customer.Id)
            {
                return(Json(new
                {
                    success = false,
                    message = _translationService.GetResource("ShoppingCart.AlreadyHighestBidder")
                }));
            }

            var warehouseId = _shoppingCartSettings.AllowToSelectWarehouse ? form["WarehouseId"].ToString() : _workContext.CurrentStore.DefaultWarehouseId;

            var shoppingCartItem = new ShoppingCartItem
            {
                Attributes         = new List <CustomAttribute>(),
                CreatedOnUtc       = DateTime.UtcNow,
                ProductId          = product.Id,
                WarehouseId        = warehouseId,
                ShoppingCartTypeId = ShoppingCartType.Auctions,
                StoreId            = _workContext.CurrentStore.Id,
                EnteredPrice       = bid,
                Quantity           = 1
            };

            var warnings = (await _shoppingCartValidator.GetStandardWarnings(customer, product, shoppingCartItem)).ToList();

            warnings.AddRange(_shoppingCartValidator.GetAuctionProductWarning(bid, product, customer));

            if (warnings.Any())
            {
                string toReturn = "";
                foreach (var warning in warnings)
                {
                    toReturn += warning + "</br>";
                }

                return(Json(new
                {
                    success = false,
                    message = toReturn
                }));
            }

            //insert new bid
            await auctionService.NewBid(customer, product, _workContext.CurrentStore, _workContext.WorkingLanguage, warehouseId, bid);

            //activity log
            await _customerActivityService.InsertActivity("PublicStore.AddNewBid", product.Id, _translationService.GetResource("ActivityLog.PublicStore.AddToBid"), product.Name);

            var addtoCartModel = await _mediator.Send(new GetAddToCart()
            {
                Product        = product,
                Customer       = customer,
                Quantity       = 1,
                CartType       = ShoppingCartType.Auctions,
                Currency       = _workContext.WorkingCurrency,
                Store          = _workContext.CurrentStore,
                Language       = _workContext.WorkingLanguage,
                TaxDisplayType = _workContext.TaxDisplayType,
            });

            return(Json(new
            {
                success = true,
                message = _translationService.GetResource("ShoppingCart.Yourbidhasbeenplaced"),
                html = await this.RenderPartialViewToString("_PopupAddToCart", addtoCartModel, true),
                model = addtoCartModel
            }));
        }
 public void TestItemId()
 {
     var item = new ShoppingCartItem(itemId: "id5");
     Assert.AreEqual("id5", item.ItemId);
 }
 public void TestCategory()
 {
     var item = new ShoppingCartItem(category: "cat1");
     Assert.AreEqual("cat1", item.Category);
 }
 public override decimal GetSubTotal(ShoppingCartItem shoppingCartItem, bool includeDiscounts = true)
 {
     decimal discountAmount;
     global::Nop.Core.Domain.Discounts.Discount appliedDiscount;
     return GetSubTotal(shoppingCartItem, includeDiscounts, out discountAmount, out appliedDiscount);
 }
Beispiel #25
0
 public bool Update(ShoppingCartItem model)
 {
     StringBuilder builder = new StringBuilder();
     builder.Append("update Shop_ShoppingCarts set ");
     builder.Append("Target=@Target,");
     builder.Append("Quantity=@Quantity,");
     builder.Append("ItemType=@ItemType,");
     builder.Append("Name=@Name,");
     builder.Append("ThumbnailsUrl=@ThumbnailsUrl,");
     builder.Append("Description=@Description,");
     builder.Append("CostPrice=@CostPrice,");
     builder.Append("SellPrice=@SellPrice,");
     builder.Append("AdjustedPrice=@AdjustedPrice,");
     builder.Append("Attributes=@Attributes,");
     builder.Append("Weight=@Weight,");
     builder.Append("Deduct=@Deduct,");
     builder.Append("Points=@Points,");
     builder.Append("ProductLineId=@ProductLineId,");
     builder.Append("SupplierId=@SupplierId,");
     builder.Append("SupplierName=@SupplierName");
     builder.Append(" where ItemId=@ItemId and UserId=@UserId ");
     SqlParameter[] cmdParms = new SqlParameter[] { 
         new SqlParameter("@SKU", SqlDbType.NVarChar, 50), new SqlParameter("@Quantity", SqlDbType.Int, 4), new SqlParameter("@ItemType", SqlDbType.Int, 4), new SqlParameter("@Name", SqlDbType.NVarChar, 200), new SqlParameter("@ThumbnailsUrl", SqlDbType.NVarChar, 300), new SqlParameter("@Description", SqlDbType.NVarChar, 500), new SqlParameter("@CostPrice", SqlDbType.Money, 8), new SqlParameter("@SellPrice", SqlDbType.Money, 8), new SqlParameter("@AdjustedPrice", SqlDbType.Money, 8), new SqlParameter("@Attributes", SqlDbType.Text), new SqlParameter("@Weight", SqlDbType.Int, 4), new SqlParameter("@Deduct", SqlDbType.Money, 8), new SqlParameter("@Points", SqlDbType.Int, 4), new SqlParameter("@ProductLineId", SqlDbType.Int, 4), new SqlParameter("@SupplierId", SqlDbType.Int, 4), new SqlParameter("@SupplierName", SqlDbType.NVarChar, 100), 
         new SqlParameter("@ItemId", SqlDbType.Int, 4), new SqlParameter("@UserId", SqlDbType.Int, 4)
      };
     cmdParms[0].Value = model.SKU;
     cmdParms[1].Value = model.Quantity;
     cmdParms[2].Value = model.ItemType;
     cmdParms[3].Value = model.Name;
     cmdParms[4].Value = model.ThumbnailsUrl;
     cmdParms[5].Value = model.Description;
     cmdParms[6].Value = model.CostPrice;
     cmdParms[7].Value = model.SellPrice;
     cmdParms[8].Value = model.AdjustedPrice;
     cmdParms[9].Value = model.Attributes;
     cmdParms[10].Value = model.Weight;
     cmdParms[11].Value = model.Deduct;
     cmdParms[12].Value = model.Points;
     cmdParms[13].Value = model.ProductLineId;
     cmdParms[14].Value = model.SupplierId;
     cmdParms[15].Value = model.SupplierName;
     cmdParms[0x10].Value = model.ItemId;
     cmdParms[0x11].Value = model.UserId;
     return (DbHelperSQL.ExecuteSql(builder.ToString(), cmdParms) > 0);
 }
Beispiel #26
0
 public static OrderItem CreateFromCartItem(ShoppingCartItem cartItem, decimal finalUnitPrice)
 {
     return new OrderItem
     {
         ProductPriceId = cartItem.ProductPrice.Id,
         ProductPrice = cartItem.ProductPrice,
         ProductName = cartItem.ProductPrice.Name,
         SKU = cartItem.ProductPrice.Sku,
         UnitPrice = finalUnitPrice,
         Quantity = cartItem.Quantity
     };
 }
 /// <summary>
 /// Create a new ShoppingCartItem object.
 /// </summary>
 /// <param name="shoppingCartItemID">Initial value of ShoppingCartItemID.</param>
 /// <param name="shoppingCartID">Initial value of ShoppingCartID.</param>
 /// <param name="quantity">Initial value of Quantity.</param>
 /// <param name="dateCreated">Initial value of DateCreated.</param>
 /// <param name="modifiedDate">Initial value of ModifiedDate.</param>
 public static ShoppingCartItem CreateShoppingCartItem(int shoppingCartItemID, string shoppingCartID, int quantity, global::System.DateTime dateCreated, global::System.DateTime modifiedDate)
 {
     ShoppingCartItem shoppingCartItem = new ShoppingCartItem();
     shoppingCartItem.ShoppingCartItemID = shoppingCartItemID;
     shoppingCartItem.ShoppingCartID = shoppingCartID;
     shoppingCartItem.Quantity = quantity;
     shoppingCartItem.DateCreated = dateCreated;
     shoppingCartItem.ModifiedDate = modifiedDate;
     return shoppingCartItem;
 }
 public void TestPrice()
 {
     var item = new ShoppingCartItem(price: (decimal) 10);
     Assert.AreEqual((decimal) 10, item.Price);
 }
Beispiel #29
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="id"></param>
 /// <param name="cartItem"></param>
 /// <returns></returns>
 public bool UpdateItem(int id, ShoppingCartItem cartItem)
 {
     return(PutRequest <bool>(_baseUrl + string.Format(ApiRoutes.Cart.UpdateItem, id), _token, GetHttpContent(cartItem)));
 }
 public void TestQuantity()
 {
     var item = new ShoppingCartItem(quantity: 100);
     Assert.AreEqual(100, item.Quantity);
 }
Beispiel #31
0
        public string GetAttributeDescription(ShoppingCartItem shoppingCartItem)
        {
            string result = ProductAttributeHelper.FormatAttributes(shoppingCartItem.ProductVariant, shoppingCartItem.AttributesXML);

            return(result);
        }
Beispiel #32
0
 private ShoppingCartInfo GetShoppingCart(HttpContext context, User userBuyer, out ShoppingCartHelper shoppingCartHelper)
 {
     ShoppingCartInfo cartInfo = null;
     string str = context.Request.Form["SkuInfos"];
     if (string.IsNullOrWhiteSpace(str))
     {
         shoppingCartHelper = new ShoppingCartHelper(userBuyer.UserID);
         cartInfo = shoppingCartHelper.GetShoppingCart();
     }
     else
     {
         JsonArray array;
         shoppingCartHelper = null;
         try
         {
             array = JsonConvert.Import<JsonArray>(str);
         }
         catch (Exception)
         {
             throw;
         }
         if ((array == null) || (array.Length < 1))
         {
             return null;
         }
         JsonObject obj2 = array.GetObject(0);
         string sku = obj2["SKU"].ToString();
         int num = Globals.SafeInt(obj2["Count"].ToString(), 1);
         int id = Globals.SafeInt(obj2["ProSales"].ToString(), -1);
         Maticsoft.Model.Shop.Products.SKUInfo modelBySKU = this._skuInfoManage.GetModelBySKU(sku);
         if (modelBySKU == null)
         {
             return null;
         }
         Maticsoft.Model.Shop.Products.ProductInfo model = this._productInfoManage.GetModel(modelBySKU.ProductId);
         if (model == null)
         {
             return null;
         }
         ShoppingCartItem itemInfo = new ShoppingCartItem {
             MarketPrice = model.MarketPrice.HasValue ? model.MarketPrice.Value : 0M,
             Name = model.ProductName,
             Quantity = num,
             SellPrice = modelBySKU.SalePrice,
             AdjustedPrice = modelBySKU.SalePrice,
             SKU = modelBySKU.SKU,
             ProductId = modelBySKU.ProductId,
             UserId = userBuyer.UserID
         };
         if (id > 0)
         {
             Maticsoft.Model.Shop.Products.ProductInfo proSaleModel = this._productInfoManage.GetProSaleModel(id);
             if (proSaleModel == null)
             {
                 return null;
             }
             if (DateTime.Now > proSaleModel.ProSalesEndDate)
             {
                 throw new ArgumentNullException("活动已过期");
             }
             itemInfo.AdjustedPrice = proSaleModel.ProSalesPrice;
         }
         List<Maticsoft.Model.Shop.Products.SKUItem> sKUItemsBySkuId = this._skuInfoManage.GetSKUItemsBySkuId(modelBySKU.SkuId);
         if ((sKUItemsBySkuId != null) && (sKUItemsBySkuId.Count > 0))
         {
             itemInfo.SkuValues = new string[sKUItemsBySkuId.Count];
             int index = 0;
             sKUItemsBySkuId.ForEach(delegate (Maticsoft.Model.Shop.Products.SKUItem xx) {
                 itemInfo.SkuValues[index++] = xx.ValueStr;
                 if (!string.IsNullOrWhiteSpace(xx.ImageUrl))
                 {
                     itemInfo.SkuImageUrl = xx.ImageUrl;
                 }
             });
         }
         itemInfo.ThumbnailsUrl = model.ThumbnailUrl1;
         itemInfo.CostPrice = modelBySKU.CostPrice.HasValue ? modelBySKU.CostPrice.Value : 0M;
         itemInfo.Weight = modelBySKU.Weight.HasValue ? modelBySKU.Weight.Value : 0;
         Maticsoft.Model.Shop.Supplier.SupplierInfo modelByCache = new Maticsoft.BLL.Shop.Supplier.SupplierInfo().GetModelByCache(model.SupplierId);
         if (modelByCache != null)
         {
             itemInfo.SupplierId = new int?(modelByCache.SupplierId);
             itemInfo.SupplierName = modelByCache.Name;
         }
         cartInfo = new ShoppingCartInfo();
         cartInfo.Items.Add(itemInfo);
     }
     try
     {
         cartInfo = new SalesRuleProduct().GetWholeSale(cartInfo);
     }
     catch (Exception)
     {
         return null;
     }
     return cartInfo;
 }
        /// <summary>
        /// Gets discount amount
        /// </summary>
        /// <param name="shoppingCartItem">The shopping cart item</param>
        /// <returns>Discount amount</returns>
        public virtual decimal GetDiscountAmount(ShoppingCartItem shoppingCartItem)
        {
            Discount appliedDiscount;

            return(GetDiscountAmount(shoppingCartItem, out appliedDiscount));
        }
    public void TestAlternateTaxTables() {
      CheckoutShoppingCartRequest request = new CheckoutShoppingCartRequest(MERCHANT_ID, MERCHANT_KEY, EnvironmentType.Sandbox, "USD", 120);

      //Ensure the factory works as expected
      AlternateTaxTable ohio1 = new AlternateTaxTable("ohio");
      request.AlternateTaxTables.Add(ohio1);
      AlternateTaxTable ohio2 = request.AlternateTaxTables["ohio"];
      AlternateTaxTable ohio3 = new AlternateTaxTable("ohio", true);

      //Ensure that two Tax tables with the same name are not the same reference
      Assert.AreSame(ohio1, ohio2);
      Assert.IsFalse(object.ReferenceEquals(ohio1, ohio3));
      //Assert.AreEqual(ohio1, ohio3);

      //Now add some rules to the item
      ohio1.AddStateTaxRule("OH", .02);

      //Make sure we can add an item to the cart.
      ShoppingCartItem item = request.AddItem("Item 1", "Cool Candy 1", 2.00M, 1, ohio1);

      try {
        request.AddItem("Item 2", "Cool Candy 2", 2.00M, 1, ohio3);
        Assert.Fail("An exception should have been thrown when we tried to add an item that has a new Tax Reference");
      }
      catch (Exception) {

      }

      //Now this should work fine.
      request.AddItem("Item 3", "Cool Candy 3", string.Empty, 2.00M, 1, ohio2);

      //you could create this as an IShoppingCartItem or ShoppingCartItem
      IShoppingCartItem newItem = new ShoppingCartItem("Item 2", "Cool Candy 2", string.Empty, 2.00M, 2, AlternateTaxTable.Empty, "This is a test of a string of private data");
      //now decide to change your mind on the quantity and price
      newItem.Price = 20;
      newItem.Quantity = 4;

      request.AddItem(newItem);

      //Console.WriteLine("private data:" + newItem.MerchantPrivateItemData);

      Assert.AreEqual("This is a test of a string of private data", newItem.MerchantPrivateItemData);

      //now change the private data string and compare again.
      newItem.MerchantPrivateItemData = "This is a new String";
      Assert.AreEqual("This is a new String", newItem.MerchantPrivateItemData);

      //now change the private data string and compare again.
      newItem.MerchantPrivateItemData = string.Empty;
      Assert.AreEqual(string.Empty, newItem.MerchantPrivateItemData);

      Assert.AreEqual(1, ohio1.RuleCount);

      DigitalItem emailDigitalItem = new DigitalItem();
      request.AddItem("Email Digital Item", "Cool DigitalItem", 2.00m, 1, emailDigitalItem);

      DigitalItem urlDigitalItem = new DigitalItem(new Uri("http://www.google.com/download.aspx?myitem=1"), "Url Description for item");
      request.AddItem("Url Digital Item", "Cool Url DigitalItem", 2.00m, 1, urlDigitalItem);

      DigitalItem keyDigitalItem = new DigitalItem("24-235-sdf-123541-53", "Key Description for item");
      request.AddItem("Url Digital Item", "Cool Url DigitalItem", 2.00m, 1, keyDigitalItem);

      DigitalItem keyUrlItem = new DigitalItem("24-235-sdf-123541-53", "http://www.google.com/download.aspx?myitem=1", "Url/Key Description for item");
      request.AddItem("Url Digital Item", "Cool Url DigitalItem", 2.00m, 1, keyUrlItem);

      //lets make sure we can add 2 different flat rate shipping amounts

      request.AddFlatRateShippingMethod("UPS Ground", 5);
      request.AddFlatRateShippingMethod("UPS 2 Day Air", 25);
      request.AddFlatRateShippingMethod("Test", 12, new ShippingRestrictions());

      //You can't mix shipping methods
      try {
        request.AddMerchantCalculatedShippingMethod("Test", 12.95m);
        Assert.Fail("AddCarrierCalculatedShippingOption should not allow duplicates.");
      }
      catch {
      }

      //lets try adding a Carrier Calculated Shipping Type

      //this should fail because the city is empty
      try {
        request.AddShippingPackage("failedpackage", string.Empty, "OH", "44114", DeliveryAddressCategory.COMMERCIAL, 2, 3, 4);
        Assert.Fail("AddCarrierCalculatedShippingOption should not allow duplicates.");
      }
      catch {
      }

      //The first thing that needs to be done for carrier calculated shipping is we must set the FOB address.
      request.AddShippingPackage("main", "Cleveland", "OH", "44114", DeliveryAddressCategory.COMMERCIAL, 2, 3, 4);

      //this should fail because two packages exist
      try {
        request.AddShippingPackage("failedpackage", "Cleveland", "OH", "44114", DeliveryAddressCategory.COMMERCIAL, 2, 3, 4);
        Assert.Fail("AddCarrierCalculatedShippingOption should not allow duplicates.");
      }
      catch {
      }

      try {
        request.AddShippingPackage("main", "Cleveland", "OH", "44114");
        Assert.Fail("AddCarrierCalculatedShippingOption should not allow duplicates.");
      }
      catch {
      }

      //The next thing we will do is add a Fedex Home Package.
      //We will set the default to 3.99, the Pickup to Regular Pickup, the additional fixed charge to 1.29 and the discount to 2.5%
      CarrierCalculatedShippingOption option
        = request.AddCarrierCalculatedShippingOption(ShippingType.Fedex_Home_Delivery, 3.99m, CarrierPickup.REGULAR_PICKUP, 1.29m, -2.5);
      option.AdditionalVariableChargePercent = 0; //make sure we can set it back to 0;
      option.AdditionalFixedCharge = 0;

      Assert.AreEqual(option.StatedShippingType, ShippingType.Fedex_Home_Delivery);
      Assert.AreEqual(option.Price, 3.99m);

      Assert.AreEqual(option.AdditionalVariableChargePercent, 0);
      Assert.AreEqual(option.AdditionalFixedCharge, 0);

      try {
        option.AdditionalFixedCharge = -1;
        Assert.Fail("Additional charge must be >= 0");
      }
      catch {
      }

      option.AdditionalVariableChargePercent = 2; //make sure we can set it back to 0;
      option.AdditionalFixedCharge = 3;

      Assert.AreEqual(option.AdditionalVariableChargePercent, 2);
      Assert.AreEqual(option.AdditionalFixedCharge, 3);

      //this should fail
      try {
        request.AddCarrierCalculatedShippingOption(ShippingType.Fedex_Home_Delivery, 3.99m, CarrierPickup.REGULAR_PICKUP, 1.29m, -2.5);
        Assert.Fail("AddCarrierCalculatedShippingOption should not allow duplicates.");
      }
      catch {

      }

      //verify the rounding works
      CarrierCalculatedShippingOption ccso = request.AddCarrierCalculatedShippingOption(ShippingType.Fedex_Ground, 1.993m);
      Assert.AreEqual(1.99m, ccso.Price);
      ccso.Price = 1.975m;
      Assert.AreEqual(1.98m, ccso.Price);
      request.AddCarrierCalculatedShippingOption(ShippingType.Fedex_Second_Day, 9.99m, CarrierPickup.REGULAR_PICKUP, 2.34m, -24.5);

      //Ensure we are able to create the cart xml

      byte[] cart = request.GetXml();

      //Console.WriteLine(EncodeHelper.Utf8BytesToString(cart));

      //test to see if the item can desialize
      Assert.IsNotNull(GCheckout.Util.EncodeHelper.Deserialize(cart));
    }
        /// <summary>
        /// Gets the shopping cart item sub total
        /// </summary>
        /// <param name="shoppingCartItem">The shopping cart item</param>
        /// <param name="includeDiscounts">A value indicating whether include discounts or not for price computation</param>
        /// <param name="discountAmount">Applied discount amount</param>
        /// <param name="appliedDiscount">Applied discount</param>
        /// <returns>Shopping cart item sub total</returns>
        public virtual async Task <(decimal subTotal, decimal discountAmount, List <AppliedDiscount> appliedDiscounts)> GetSubTotal(ShoppingCartItem shoppingCartItem,
                                                                                                                                    bool includeDiscounts = true)
        {
            if (shoppingCartItem == null)
            {
                throw new ArgumentNullException("shoppingCartItem");
            }

            decimal subTotal;
            //unit price
            var getunitPrice = await GetUnitPrice(shoppingCartItem, includeDiscounts);

            var     unitPrice      = getunitPrice.unitprice;
            decimal discountAmount = getunitPrice.discountAmount;
            List <AppliedDiscount> appliedDiscounts = getunitPrice.appliedDiscounts;

            //discount
            if (appliedDiscounts.Any())
            {
                //we can properly use "MaximumDiscountedQuantity" property only for one discount (not cumulative ones)
                Discount oneAndOnlyDiscount = null;
                if (appliedDiscounts.Count == 1)
                {
                    oneAndOnlyDiscount = await _discountService.GetDiscountById(appliedDiscounts.FirstOrDefault().DiscountId);
                }

                if (oneAndOnlyDiscount != null &&
                    oneAndOnlyDiscount.MaximumDiscountedQuantity.HasValue &&
                    shoppingCartItem.Quantity > oneAndOnlyDiscount.MaximumDiscountedQuantity.Value)
                {
                    //we cannot apply discount for all shopping cart items
                    var discountedQuantity = oneAndOnlyDiscount.MaximumDiscountedQuantity.Value;
                    var discountedSubTotal = unitPrice * discountedQuantity;
                    discountAmount = discountAmount * discountedQuantity;

                    var notDiscountedQuantity  = shoppingCartItem.Quantity - discountedQuantity;
                    var notDiscountedUnitPrice = await GetUnitPrice(shoppingCartItem, false);

                    var notDiscountedSubTotal = notDiscountedUnitPrice.unitprice * notDiscountedQuantity;

                    subTotal = discountedSubTotal + notDiscountedSubTotal;
                }
                else
                {
                    //discount is applied to all items (quantity)
                    //calculate discount amount for all items
                    discountAmount = discountAmount * shoppingCartItem.Quantity;

                    subTotal = unitPrice * shoppingCartItem.Quantity;
                }
            }
            else
            {
                subTotal = unitPrice * shoppingCartItem.Quantity;
            }
            return(subTotal, discountAmount, appliedDiscounts);
        }
        public override decimal GetSubTotal(ShoppingCartItem shoppingCartItem, bool includeDiscounts, out decimal discountAmount, out global::Nop.Core.Domain.Discounts.Discount appliedDiscount)
        {
            discountAmount = 0M;
            appliedDiscount = null;
            decimal lineSubTotal = _priceCalculationService.GetUnitPrice(shoppingCartItem, false) * shoppingCartItem.Quantity;

            if (!_promoSettings.Enabled)
                return base.GetSubTotal(shoppingCartItem, includeDiscounts, out discountAmount, out appliedDiscount);

            BasketResponse basketResponse = _promoUtilities.GetBasketResponse();
            if(!basketResponse.IsValid())
                return lineSubTotal;

            discountAmount = basketResponse.GetLineDiscountAmount(shoppingCartItem);
            if (discountAmount != decimal.Zero)
            {
                if (discountAmount <= lineSubTotal)
                {
                    appliedDiscount = new global::Nop.Core.Domain.Discounts.Discount()
                    {
                        Name = string.Join(", ", basketResponse.LineDiscountNames(shoppingCartItem)
                                                               .Select(n => _localizationService.GetValidatedResource(n))),
                        DiscountAmount = discountAmount
                    };

                    lineSubTotal -= discountAmount;
                }
                else
                {
                    string shortMessage = "PriceCalculationService - GetSubTotal";
                    string fullMessage = string.Format("id: {0}, productId: {1}, attributesXml: {2}, basketResponseXml: {3}", shoppingCartItem.Id, shoppingCartItem.ProductId, shoppingCartItem.AttributesXml, basketResponse.ToXml());
                    _logger.InsertLog(global::Nop.Core.Domain.Logging.LogLevel.Error, shortMessage, fullMessage, _workContext.CurrentCustomer);
                }
            }

            return lineSubTotal;
        }
Beispiel #37
0
        public static async Task <bool> ProductAvailability(ShoppingCartItem cartItem, IUnitOfWork uow)
        {
            var inventory = await uow.ProductInventory.Get(g => g.ProductID == cartItem.ProductID);

            return(inventory.Quantity > cartItem.Quantity ? true : false);
        }
        public void ChangeItemQuantity(ShoppingCart cart, ShoppingCartItem item, int newQuantity)
        {
            Require.NotNull(cart, "cart");
            Require.NotNull(item, "item");
            Require.That(newQuantity > 0, "newQuantity", "Quantity should be greater than zero.");

            if (item.Quantity != newQuantity)
            {
                var oldQuantity = item.Quantity;
                item.Quantity = newQuantity;

                _repository.Database.SaveChanges();

                Event.Raise(new CartItemQuantityChanged(cart, item, oldQuantity));
            }
        }
Beispiel #39
0
        /// <summary>
        /// Get dimensions of associated products (for quantity 1)
        /// </summary>
        /// <param name="shoppingCartItem">Shopping cart item</param>
        /// <param name="width">Width</param>
        /// <param name="length">Length</param>
        /// <param name="height">Height</param>
        public virtual async Task <(decimal width, decimal length, decimal height)> GetAssociatedProductDimensions(ShoppingCartItem shoppingCartItem)
        {
            if (shoppingCartItem == null)
            {
                throw new ArgumentNullException("shoppingCartItem");
            }

            var width  = decimal.Zero;
            var length = decimal.Zero;
            var height = decimal.Zero;

            //attributes
            if (String.IsNullOrEmpty(shoppingCartItem.AttributesXml))
            {
                return(0, 0, 0);
            }

            var product = await _productService.GetProductById(shoppingCartItem.ProductId);

            //bundled products (associated attributes)
            var attributeValues = _productAttributeParser.ParseProductAttributeValues(product, shoppingCartItem.AttributesXml)
                                  .Where(x => x.AttributeValueType == AttributeValueType.AssociatedToProduct)
                                  .ToList();

            foreach (var attributeValue in attributeValues)
            {
                var associatedProduct = await _productService.GetProductById(attributeValue.AssociatedProductId);

                if (associatedProduct != null && associatedProduct.IsShipEnabled)
                {
                    width  += associatedProduct.Width * attributeValue.Quantity;
                    length += associatedProduct.Length * attributeValue.Quantity;
                    height += associatedProduct.Height * attributeValue.Quantity;
                }
            }
            return(width, length, height);
        }
 public void AddItem(ShoppingCartItem itemInfo)
 {
     this._cartProvider.AddItem(itemInfo);
 }
Beispiel #41
0
        public void TestQuantity()
        {
            var item = new ShoppingCartItem(quantity: 100);

            Assert.Equal(100, item.Quantity);
        }
Beispiel #42
0
        public IActionResult CreateShoppingCartItem([ModelBinder(typeof(JsonModelBinder <ShoppingCartItemDto>))] Delta <ShoppingCartItemDto> shoppingCartItemDelta)
        {
            // Here we display the errors if the validation has failed at some point.
            if (!ModelState.IsValid)
            {
                return(Error());
            }

            ShoppingCartItem newShoppingCartItem = _factory.Initialize();

            shoppingCartItemDelta.Merge(newShoppingCartItem);

            // We know that the product id and customer id will be provided because they are required by the validator.
            // TODO: validate
            Product product = _productService.GetProductById(newShoppingCartItem.ProductId);

            if (product == null)
            {
                return(Error(HttpStatusCode.NotFound, "product", "not found"));
            }

            Customer customer = _customerService.GetCustomerById(newShoppingCartItem.CustomerId);

            if (customer == null)
            {
                return(Error(HttpStatusCode.NotFound, "customer", "not found"));
            }

            ShoppingCartType shoppingCartType = (ShoppingCartType)Enum.Parse(typeof(ShoppingCartType), shoppingCartItemDelta.Dto.ShoppingCartType);

            if (!product.IsRental)
            {
                newShoppingCartItem.RentalStartDateUtc = null;
                newShoppingCartItem.RentalEndDateUtc   = null;
            }

            string attributesXml = _productAttributeConverter.ConvertToXml(shoppingCartItemDelta.Dto.Attributes, product.Id);

            int currentStoreId = _storeContext.CurrentStore.Id;

            IList <string> warnings = _shoppingCartService.AddToCart(customer, product, shoppingCartType, currentStoreId, attributesXml, 0M,
                                                                     newShoppingCartItem.RentalStartDateUtc, newShoppingCartItem.RentalEndDateUtc,
                                                                     shoppingCartItemDelta.Dto.Quantity ?? 1);

            if (warnings.Count > 0)
            {
                foreach (var warning in warnings)
                {
                    ModelState.AddModelError("shopping cart item", warning);
                }

                return(Error(HttpStatusCode.BadRequest));
            }
            else
            {
                // the newly added shopping cart item should be the last one
                newShoppingCartItem = customer.ShoppingCartItems.LastOrDefault();
            }

            // Preparing the result dto of the new product category mapping
            ShoppingCartItemDto newShoppingCartItemDto = _dtoHelper.PrepareShoppingCartItemDTO(newShoppingCartItem);

            var shoppingCartsRootObject = new ShoppingCartItemsRootObject();

            shoppingCartsRootObject.ShoppingCartItems.Add(newShoppingCartItemDto);

            var json = _jsonFieldsSerializer.Serialize(shoppingCartsRootObject, string.Empty);

            return(new RawJsonActionResult(json));
        }
Beispiel #43
0
        public void TestCategory()
        {
            var item = new ShoppingCartItem(category: "cat1");

            Assert.Equal("cat1", item.Category);
        }
Beispiel #44
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="sci">Shopping cart item</param>
 /// <param name="product">Product</param>
 /// <param name="qty">Override "Quantity" property of shopping cart item</param>
 public PackageItem(ShoppingCartItem sci, Product product, int?qty = null)
 {
     ShoppingCartItem   = sci;
     Product            = product;
     OverriddenQuantity = qty;
 }
Beispiel #45
0
 public static void MappingshoppingcartDto(this  ShoppingCartItemdto shoppingcartdto, ShoppingCartItem shoppingcart)
 {
     shoppingcartdto.ShoppingCartItemId = shoppingcart.ShoppingCartItemId;
     shoppingcartdto.Amount             = shoppingcart.Amount;
     shoppingcartdto.ShoppingCartId     = shoppingcart.ShoppingCartId;
 }
Beispiel #46
0
 private ShoppingCartInfo GetCartInfo4SKU(Maticsoft.Model.Shop.Products.ProductInfo productInfo, Maticsoft.Model.Shop.Products.SKUInfo skuInfo, int quantity, Maticsoft.Model.Shop.Products.ProductInfo proSaleInfo)
 {
     ShoppingCartInfo info = new ShoppingCartInfo();
     ShoppingCartItem cartItem = new ShoppingCartItem {
         MarketPrice = productInfo.MarketPrice.HasValue ? productInfo.MarketPrice.Value : 0M,
         Name = productInfo.ProductName,
         Quantity = (quantity < 1) ? 1 : quantity,
         SellPrice = skuInfo.SalePrice,
         AdjustedPrice = skuInfo.SalePrice,
         SKU = skuInfo.SKU,
         ProductId = skuInfo.ProductId,
         UserId = base.currentUser.UserID
     };
     if (proSaleInfo != null)
     {
         cartItem.AdjustedPrice = proSaleInfo.ProSalesPrice;
     }
     if (productInfo.SupplierId > 0)
     {
         Maticsoft.Model.Shop.Supplier.SupplierInfo modelByCache = new Maticsoft.BLL.Shop.Supplier.SupplierInfo().GetModelByCache(productInfo.SupplierId);
         if (modelByCache != null)
         {
             cartItem.SupplierId = new int?(modelByCache.SupplierId);
             cartItem.SupplierName = modelByCache.Name;
         }
     }
     List<Maticsoft.Model.Shop.Products.SKUItem> sKUItemsBySkuId = new Maticsoft.BLL.Shop.Products.SKUInfo().GetSKUItemsBySkuId(skuInfo.SkuId);
     if ((sKUItemsBySkuId != null) && (sKUItemsBySkuId.Count > 0))
     {
         cartItem.SkuValues = new string[sKUItemsBySkuId.Count];
         int index = 0;
         sKUItemsBySkuId.ForEach(delegate (Maticsoft.Model.Shop.Products.SKUItem xx) {
             cartItem.SkuValues[index++] = xx.ValueStr;
             if (!string.IsNullOrWhiteSpace(xx.ImageUrl))
             {
                 cartItem.SkuImageUrl = xx.ImageUrl;
             }
         });
     }
     cartItem.ThumbnailsUrl = productInfo.ThumbnailUrl1;
     cartItem.CostPrice = skuInfo.CostPrice.HasValue ? skuInfo.CostPrice.Value : 0M;
     cartItem.Weight = skuInfo.Weight.HasValue ? skuInfo.Weight.Value : 0;
     info.Items.Add(cartItem);
     return info;
 }
Beispiel #47
0
        public virtual async Task <IActionResult> AddProductDetails(string productId, int shoppingCartTypeId, IFormCollection form)
        {
            var product = await _productService.GetProductById(productId);

            if (product == null)
            {
                return(Json(new
                {
                    redirect = Url.RouteUrl("HomePage"),
                }));
            }

            //you can't add group products
            if (product.ProductTypeId == ProductType.GroupedProduct)
            {
                return(Json(new
                {
                    success = false,
                    message = "Grouped products couldn't be added to the cart"
                }));
            }

            //you can't add reservation product to wishlist
            if (product.ProductTypeId == ProductType.Reservation && (ShoppingCartType)shoppingCartTypeId == ShoppingCartType.Wishlist)
            {
                return(Json(new
                {
                    success = false,
                    message = "Reservation products couldn't be added to the wishlist"
                }));
            }

            //you can't add auction product to wishlist
            if (product.ProductTypeId == ProductType.Auction && (ShoppingCartType)shoppingCartTypeId == ShoppingCartType.Wishlist)
            {
                return(Json(new
                {
                    success = false,
                    message = "Auction products couldn't be added to the wishlist"
                }));
            }
            //check available date
            if (product.AvailableEndDateTimeUtc.HasValue && product.AvailableEndDateTimeUtc.Value < DateTime.UtcNow)
            {
                return(Json(new
                {
                    success = false,
                    message = _translationService.GetResource("ShoppingCart.NotAvailable")
                }));
            }


            #region Update existing shopping cart item?
            string updatecartitemid = "";
            foreach (string formKey in form.Keys)
            {
                if (formKey.Equals(string.Format("addtocart_{0}.UpdatedShoppingCartItemId", productId), StringComparison.OrdinalIgnoreCase))
                {
                    updatecartitemid = form[formKey];
                    break;
                }
            }

            ShoppingCartItem updatecartitem = null;
            if (_shoppingCartSettings.AllowCartItemEditing && !string.IsNullOrEmpty(updatecartitemid))
            {
                var cart = _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, (ShoppingCartType)shoppingCartTypeId);
                updatecartitem = cart.FirstOrDefault(x => x.Id == updatecartitemid);

                //is it this product?
                if (updatecartitem != null && product.Id != updatecartitem.ProductId)
                {
                    return(Json(new
                    {
                        success = false,
                        message = "This product does not match a passed shopping cart item identifier"
                    }));
                }
            }
            #endregion

            #region Customer entered price
            decimal?customerEnteredPriceConverted = null;
            if (product.EnteredPrice)
            {
                foreach (string formKey in form.Keys)
                {
                    if (formKey.Equals(string.Format("addtocart_{0}.CustomerEnteredPrice", productId), StringComparison.OrdinalIgnoreCase))
                    {
                        if (decimal.TryParse(form[formKey], out decimal customerEnteredPrice))
                        {
                            customerEnteredPriceConverted = await _currencyService.ConvertToPrimaryStoreCurrency(customerEnteredPrice, _workContext.WorkingCurrency);
                        }
                        break;
                    }
                }
            }
            #endregion

            #region Quantity

            int quantity = 1;
            foreach (string formKey in form.Keys)
            {
                if (formKey.Equals(string.Format("addtocart_{0}.EnteredQuantity", productId), StringComparison.OrdinalIgnoreCase))
                {
                    int.TryParse(form[formKey], out quantity);
                    break;
                }
            }

            #endregion

            //product and gift voucher attributes
            var attributes = await _mediator.Send(new GetParseProductAttributes()
            {
                Product = product, Form = form
            });

            //rental attributes
            DateTime?rentalStartDate = null;
            DateTime?rentalEndDate   = null;
            if (product.ProductTypeId == ProductType.Reservation)
            {
                product.ParseReservationDates(form, out rentalStartDate, out rentalEndDate);
            }

            //product reservation
            string reservationId = "";
            string parameter     = "";
            string duration      = "";
            if (product.ProductTypeId == ProductType.Reservation)
            {
                foreach (string formKey in form.Keys)
                {
                    if (formKey.Contains("Reservation"))
                    {
                        reservationId = form["Reservation"].ToString();
                        break;
                    }
                }

                if (product.IntervalUnitId == IntervalUnit.Hour || product.IntervalUnitId == IntervalUnit.Minute)
                {
                    if (string.IsNullOrEmpty(reservationId))
                    {
                        return(Json(new
                        {
                            success = false,
                            message = _translationService.GetResource("Product.Addtocart.Reservation.Required")
                        }));
                    }
                    var productReservationService = HttpContext.RequestServices.GetRequiredService <IProductReservationService>();
                    var reservation = await productReservationService.GetProductReservation(reservationId);

                    if (reservation == null)
                    {
                        return(Json(new
                        {
                            success = false,
                            message = "No reservation found"
                        }));
                    }
                    duration        = reservation.Duration;
                    rentalStartDate = reservation.Date;
                    parameter       = reservation.Parameter;
                }
                else if (product.IntervalUnitId == IntervalUnit.Day)
                {
                    string datefrom = "";
                    string dateto   = "";
                    foreach (var item in form)
                    {
                        if (item.Key == "reservationDatepickerFrom")
                        {
                            datefrom = item.Value;
                        }

                        if (item.Key == "reservationDatepickerTo")
                        {
                            dateto = item.Value;
                        }
                    }

                    string datePickerFormat = "MM/dd/yyyy";
                    if (!string.IsNullOrEmpty(datefrom))
                    {
                        rentalStartDate = DateTime.ParseExact(datefrom, datePickerFormat, CultureInfo.InvariantCulture);
                    }

                    if (!string.IsNullOrEmpty(dateto))
                    {
                        rentalEndDate = DateTime.ParseExact(dateto, datePickerFormat, CultureInfo.InvariantCulture);
                    }
                }
            }

            var cartType = updatecartitem == null ? (ShoppingCartType)shoppingCartTypeId :
                           //if the item to update is found, then we ignore the specified "shoppingCartTypeId" parameter
                           updatecartitem.ShoppingCartTypeId;

            //save item
            var addToCartWarnings = new List <string>();


            string warehouseId = _shoppingCartSettings.AllowToSelectWarehouse ?
                                 form["WarehouseId"].ToString() :
                                 product.UseMultipleWarehouses ? _workContext.CurrentStore.DefaultWarehouseId :
                                 (string.IsNullOrEmpty(_workContext.CurrentStore.DefaultWarehouseId) ? product.WarehouseId : _workContext.CurrentStore.DefaultWarehouseId);

            if (updatecartitem == null)
            {
                //add to the cart
                addToCartWarnings.AddRange(await _shoppingCartService.AddToCart(_workContext.CurrentCustomer,
                                                                                productId, cartType, _workContext.CurrentStore.Id, warehouseId,
                                                                                attributes, customerEnteredPriceConverted,
                                                                                rentalStartDate, rentalEndDate, quantity, true, reservationId, parameter, duration, getRequiredProductWarnings: false));
            }
            else
            {
                var cart = _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, (ShoppingCartType)shoppingCartTypeId);
                var otherCartItemWithSameParameters = await _shoppingCartService.FindShoppingCartItem(
                    cart, updatecartitem.ShoppingCartTypeId, productId, warehouseId, attributes, customerEnteredPriceConverted,
                    rentalStartDate, rentalEndDate);

                if (otherCartItemWithSameParameters != null &&
                    otherCartItemWithSameParameters.Id == updatecartitem.Id)
                {
                    //ensure it's other shopping cart cart item
                    otherCartItemWithSameParameters = null;
                }
                //update existing item
                addToCartWarnings.AddRange(await _shoppingCartService.UpdateShoppingCartItem(_workContext.CurrentCustomer,
                                                                                             updatecartitem.Id, warehouseId, attributes, customerEnteredPriceConverted,
                                                                                             rentalStartDate, rentalEndDate, quantity, true));
                if (otherCartItemWithSameParameters != null && !addToCartWarnings.Any())
                {
                    //delete the same shopping cart item (the other one)
                    await _shoppingCartService.DeleteShoppingCartItem(_workContext.CurrentCustomer, otherCartItemWithSameParameters);
                }
            }

            #region Return result

            if (addToCartWarnings.Any())
            {
                //cannot be added to the cart/wishlist
                //display warnings
                return(Json(new
                {
                    success = false,
                    message = addToCartWarnings.ToArray()
                }));
            }

            var addtoCartModel = await _mediator.Send(new GetAddToCart()
            {
                Product              = product,
                Customer             = _workContext.CurrentCustomer,
                Quantity             = quantity,
                CartType             = cartType,
                CustomerEnteredPrice = customerEnteredPriceConverted,
                Attributes           = attributes,
                Currency             = _workContext.WorkingCurrency,
                Store          = _workContext.CurrentStore,
                Language       = _workContext.WorkingLanguage,
                TaxDisplayType = _workContext.TaxDisplayType,
                Duration       = duration,
                Parameter      = parameter,
                ReservationId  = reservationId,
                StartDate      = rentalStartDate,
                EndDate        = rentalEndDate
            });

            //added to the cart/wishlist
            switch (cartType)
            {
            case ShoppingCartType.Wishlist:
            {
                //activity log
                await _customerActivityService.InsertActivity("PublicStore.AddToWishlist", product.Id, _translationService.GetResource("ActivityLog.PublicStore.AddToWishlist"), product.Name);

                if (_shoppingCartSettings.DisplayWishlistAfterAddingProduct)
                {
                    //redirect to the wishlist page
                    return(Json(new
                        {
                            redirect = Url.RouteUrl("Wishlist"),
                        }));
                }

                //display notification message and update appropriate blocks
                var qty = _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, ShoppingCartType.Wishlist).Sum(x => x.Quantity);
                var updatetopwishlistsectionhtml = string.Format(_translationService.GetResource("Wishlist.HeaderQuantity"), qty);

                return(Json(new
                    {
                        success = true,
                        message = string.Format(_translationService.GetResource("Products.ProductHasBeenAddedToTheWishlist.Link"), Url.RouteUrl("Wishlist")),
                        updatetopwishlistsectionhtml = updatetopwishlistsectionhtml,
                        wishlistqty = qty,
                        html = await this.RenderPartialViewToString("_PopupAddToCart", addtoCartModel, true),
                        model = addtoCartModel
                    }));
            }

            case ShoppingCartType.ShoppingCart:
            default:
            {
                //activity log
                await _customerActivityService.InsertActivity("PublicStore.AddToShoppingCart", product.Id, _translationService.GetResource("ActivityLog.PublicStore.AddToShoppingCart"), product.Name);

                if (_shoppingCartSettings.DisplayCartAfterAddingProduct)
                {
                    //redirect to the shopping cart page
                    return(Json(new
                        {
                            redirect = Url.RouteUrl("ShoppingCart"),
                        }));
                }

                //display notification message and update appropriate blocks
                var shoppingCartTypes = new List <ShoppingCartType>();
                shoppingCartTypes.Add(ShoppingCartType.ShoppingCart);
                shoppingCartTypes.Add(ShoppingCartType.Auctions);
                if (_shoppingCartSettings.AllowOnHoldCart)
                {
                    shoppingCartTypes.Add(ShoppingCartType.OnHoldCart);
                }

                var updatetopcartsectionhtml = string.Format(_translationService.GetResource("ShoppingCart.HeaderQuantity"),
                                                             _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, shoppingCartTypes.ToArray())
                                                             .Sum(x => x.Quantity));

                var miniShoppingCartmodel = _shoppingCartSettings.MiniShoppingCartEnabled ? await _mediator.Send(new GetMiniShoppingCart()
                    {
                        Customer       = _workContext.CurrentCustomer,
                        Currency       = _workContext.WorkingCurrency,
                        Language       = _workContext.WorkingLanguage,
                        TaxDisplayType = _workContext.TaxDisplayType,
                        Store          = _workContext.CurrentStore
                    }) : null;

                return(Json(new
                    {
                        success = true,
                        message = string.Format(_translationService.GetResource("Products.ProductHasBeenAddedToTheCart.Link"), Url.RouteUrl("ShoppingCart")),
                        html = await this.RenderPartialViewToString("_PopupAddToCart", addtoCartModel, true),
                        updatetopcartsectionhtml = updatetopcartsectionhtml,
                        sidebarshoppingcartmodel = miniShoppingCartmodel,
                        refreshreservation = product.ProductTypeId == ProductType.Reservation && product.IntervalUnitId != IntervalUnit.Day,
                        model = addtoCartModel
                    }));
            }
            }


            #endregion
        }
Beispiel #48
0
        /// <summary>
        /// Add a product variant to shopping cart
        /// </summary>
        /// <param name="customer">Customer</param>
        /// <param name="productVariant">Product variant</param>
        /// <param name="shoppingCartType">Shopping cart type</param>
        /// <param name="selectedAttributes">Selected attributes</param>
        /// <param name="customerEnteredPrice">The price enter by a customer</param>
        /// <param name="quantity">Quantity</param>
        /// <param name="automaticallyAddRequiredProductVariantsIfEnabled">Automatically add required product variants if enabled</param>
        /// <returns>Warnings</returns>
        public virtual IList <string> AddToCart(Customer customer, ProductVariant productVariant,
                                                ShoppingCartType shoppingCartType, string selectedAttributes,
                                                decimal customerEnteredPrice, int quantity, bool automaticallyAddRequiredProductVariantsIfEnabled)
        {
            if (customer == null)
            {
                throw new ArgumentNullException("customer");
            }

            if (productVariant == null)
            {
                throw new ArgumentNullException("productVariant");
            }

            var warnings = new List <string>();

            if (shoppingCartType == ShoppingCartType.ShoppingCart && !_permissionService.Authorize(StandardPermissionProvider.EnableShoppingCart, customer))
            {
                warnings.Add("Shopping cart is disabled");
                return(warnings);
            }
            if (shoppingCartType == ShoppingCartType.Wishlist && !_permissionService.Authorize(StandardPermissionProvider.EnableWishlist, customer))
            {
                warnings.Add("Wishlist is disabled");
                return(warnings);
            }

            if (quantity <= 0)
            {
                warnings.Add(_localizationService.GetResource("ShoppingCart.QuantityShouldPositive"));
                return(warnings);
            }

            //reset checkout info
            _customerService.ResetCheckoutData(customer);

            var cart = customer.ShoppingCartItems.Where(sci => sci.ShoppingCartType == shoppingCartType).ToList();

            var shoppingCartItem = FindShoppingCartItemInTheCart(cart,
                                                                 shoppingCartType, productVariant, selectedAttributes, customerEnteredPrice);

            if (shoppingCartItem != null)
            {
                //update existing shopping cart item
                int newQuantity = shoppingCartItem.Quantity + quantity;
                warnings.AddRange(GetShoppingCartItemWarnings(customer, shoppingCartType, productVariant,
                                                              selectedAttributes, customerEnteredPrice, newQuantity, automaticallyAddRequiredProductVariantsIfEnabled));

                if (warnings.Count == 0)
                {
                    shoppingCartItem.AttributesXml = selectedAttributes;
                    shoppingCartItem.Quantity      = newQuantity;
                    shoppingCartItem.UpdatedOnUtc  = DateTime.UtcNow;
                    _customerService.UpdateCustomer(customer);

                    //event notification
                    _eventPublisher.EntityUpdated(shoppingCartItem);
                }
            }
            else
            {
                //new shopping cart item
                warnings.AddRange(GetShoppingCartItemWarnings(customer, shoppingCartType, productVariant,
                                                              selectedAttributes, customerEnteredPrice, quantity, automaticallyAddRequiredProductVariantsIfEnabled));
                if (warnings.Count == 0)
                {
                    //maximum items validation
                    switch (shoppingCartType)
                    {
                    case ShoppingCartType.ShoppingCart:
                    {
                        if (cart.Count >= _shoppingCartSettings.MaximumShoppingCartItems)
                        {
                            return(warnings);
                        }
                    }
                    break;

                    case ShoppingCartType.Wishlist:
                    {
                        if (cart.Count >= _shoppingCartSettings.MaximumWishlistItems)
                        {
                            return(warnings);
                        }
                    }
                    break;

                    default:
                        break;
                    }

                    DateTime now = DateTime.UtcNow;
                    shoppingCartItem = new ShoppingCartItem()
                    {
                        ShoppingCartType     = shoppingCartType,
                        ProductVariant       = productVariant,
                        AttributesXml        = selectedAttributes,
                        CustomerEnteredPrice = customerEnteredPrice,
                        Quantity             = quantity,
                        CreatedOnUtc         = now,
                        UpdatedOnUtc         = now
                    };
                    customer.ShoppingCartItems.Add(shoppingCartItem);
                    _customerService.UpdateCustomer(customer);

                    //event notification
                    _eventPublisher.EntityInserted(shoppingCartItem);
                }
            }

            return(warnings);
        }
        public virtual ActionResult ProductDetails(int productId, int updatecartitemid = 0)
        {
            var product = _productService.GetProductById(productId);

            if (product == null || product.Deleted)
            {
                return(InvokeHttp404());
            }

            var notAvailable =
                //published?
                (!product.Published && !_catalogSettings.AllowViewUnpublishedProductPage) ||
                //ACL (access control list)
                !_aclService.Authorize(product) ||
                //Store mapping
                !_storeMappingService.Authorize(product) ||
                //availability dates
                !product.IsAvailable();

            //Check whether the current user has a "Manage products" permission (usually a store owner)
            //We should allows him (her) to use "Preview" functionality
            if (notAvailable && !_permissionService.Authorize(StandardPermissionProvider.ManageProducts))
            {
                return(InvokeHttp404());
            }

            //visible individually?
            if (!product.VisibleIndividually)
            {
                //is this one an associated products?
                var parentGroupedProduct = _productService.GetProductById(product.ParentGroupedProductId);
                if (parentGroupedProduct == null)
                {
                    return(RedirectToRoute("HomePage"));
                }

                return(RedirectToRoute("Product", new { SeName = parentGroupedProduct.GetSeName() }));
            }

            //update existing shopping cart or wishlist  item?
            ShoppingCartItem updatecartitem = null;

            if (_shoppingCartSettings.AllowCartItemEditing && updatecartitemid > 0)
            {
                var cart = _workContext.CurrentCustomer.ShoppingCartItems
                           .LimitPerStore(_storeContext.CurrentStore.Id)
                           .ToList();
                updatecartitem = cart.FirstOrDefault(x => x.Id == updatecartitemid);
                //not found?
                if (updatecartitem == null)
                {
                    return(RedirectToRoute("Product", new { SeName = product.GetSeName() }));
                }
                //is it this product?
                if (product.Id != updatecartitem.ProductId)
                {
                    return(RedirectToRoute("Product", new { SeName = product.GetSeName() }));
                }
            }

            //save as recently viewed
            _recentlyViewedProductsService.AddProductToRecentlyViewedList(product.Id);

            //display "edit" (manage) link
            if (_permissionService.Authorize(StandardPermissionProvider.AccessAdminPanel) &&
                _permissionService.Authorize(StandardPermissionProvider.ManageProducts))
            {
                //a vendor should have access only to his products
                if (_workContext.CurrentVendor == null || _workContext.CurrentVendor.Id == product.VendorId)
                {
                    DisplayEditLink(Url.Action("Edit", "Product", new { id = product.Id, area = "Admin" }));
                }
            }

            //activity log
            _customerActivityService.InsertActivity("PublicStore.ViewProduct", _localizationService.GetResource("ActivityLog.PublicStore.ViewProduct"), product.Name);

            //model
            var model = _productModelFactory.PrepareProductDetailsModel(product, updatecartitem, false);
            //template
            var productTemplateViewPath = _productModelFactory.PrepareProductTemplateViewPath(product);

            return(View(productTemplateViewPath, model));
        }
        /// <summary>
        /// Handle shopping cart changed event
        /// </summary>
        /// <param name="cartItem">Shopping cart item</param>
        /// <returns>A task that represents the asynchronous operation</returns>
        public async Task HandleShoppingCartChangedEventAsync(ShoppingCartItem cartItem)
        {
            //whether marketing automation is enabled
            if (!_sendinblueSettings.UseMarketingAutomation)
            {
                return;
            }

            var customer = await _customerService.GetCustomerByIdAsync(cartItem.CustomerId);

            try
            {
                //create API client
                var client = CreateMarketingAutomationClient();

                //first, try to identify current customer
                await client.IdentifyAsync(new Identify(customer.Email));

                //get shopping cart GUID
                var shoppingCartGuid = await _genericAttributeService
                                       .GetAttributeAsync <Guid?>(customer, SendinblueDefaults.ShoppingCartGuidAttribute);

                //create track event object
                var trackEvent = new TrackEvent(customer.Email, string.Empty);

                //get current customer's shopping cart
                var store = await _storeContext.GetCurrentStoreAsync();

                var cart = await _shoppingCartService
                           .GetShoppingCartAsync(customer, ShoppingCartType.ShoppingCart, store.Id);

                if (cart.Any())
                {
                    //get URL helper
                    var urlHelper = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext);

                    //get shopping cart amounts
                    var(_, cartDiscount, _, cartSubtotal, _) = await _orderTotalCalculationService.GetShoppingCartSubTotalAsync(cart,
                                                                                                                                await _workContext.GetTaxDisplayTypeAsync() == TaxDisplayType.IncludingTax);

                    var cartTax = await _orderTotalCalculationService.GetTaxTotalAsync(cart, false);

                    var cartShipping = await _orderTotalCalculationService.GetShoppingCartShippingTotalAsync(cart);

                    var(cartTotal, _, _, _, _, _) = await _orderTotalCalculationService.GetShoppingCartTotalAsync(cart, false, false);

                    //get products data by shopping cart items
                    var itemsData = await cart.Where(item => item.ProductId != 0).SelectAwait(async item =>
                    {
                        var product = await _productService.GetProductByIdAsync(item.ProductId);

                        //try to get product attribute combination
                        var combination = await _productAttributeParser.FindProductAttributeCombinationAsync(product, item.AttributesXml);

                        //get default product picture
                        var picture = await _pictureService.GetProductPictureAsync(product, item.AttributesXml);

                        //get product SEO slug name
                        var seName = await _urlRecordService.GetSeNameAsync(product);

                        //create product data
                        return(new
                        {
                            id = product.Id,
                            name = product.Name,
                            variant_id = combination?.Id ?? product.Id,
                            variant_name = combination?.Sku ?? product.Name,
                            sku = combination?.Sku ?? product.Sku,
                            category = await(await _categoryService.GetProductCategoriesByProductIdAsync(item.ProductId)).AggregateAwaitAsync(",", async(all, pc) =>
                            {
                                var res = (await _categoryService.GetCategoryByIdAsync(pc.CategoryId)).Name;
                                res = all == "," ? res : all + ", " + res;
                                return res;
                            }),
                            url = urlHelper.RouteUrl("Product", new { SeName = seName }, _webHelper.GetCurrentRequestProtocol()),
                            image = (await _pictureService.GetPictureUrlAsync(picture)).Url,
                            quantity = item.Quantity,
                            price = (await _shoppingCartService.GetSubTotalAsync(item, true)).subTotal
                        });
                    }).ToArrayAsync();

                    //prepare cart data
                    var cartData = new
                    {
                        affiliation      = store.Name,
                        subtotal         = cartSubtotal,
                        shipping         = cartShipping ?? decimal.Zero,
                        total_before_tax = cartSubtotal + cartShipping ?? decimal.Zero,
                        tax      = cartTax,
                        discount = cartDiscount,
                        revenue  = cartTotal ?? decimal.Zero,
                        url      = urlHelper.RouteUrl("ShoppingCart", null, _webHelper.GetCurrentRequestProtocol()),
                        currency = (await _currencyService.GetCurrencyByIdAsync(_currencySettings.PrimaryStoreCurrencyId))?.CurrencyCode,
                        //gift_wrapping = string.Empty, //currently we can't get this value
                        items = itemsData
                    };

                    //if there is a single item in the cart, so the cart is just created
                    if (cart.Count == 1)
                    {
                        shoppingCartGuid = Guid.NewGuid();
                    }
                    else
                    {
                        //otherwise cart is updated
                        shoppingCartGuid ??= Guid.NewGuid();
                    }
                    trackEvent.EventName = SendinblueDefaults.CartUpdatedEventName;
                    trackEvent.EventData = new { id = $"cart:{shoppingCartGuid}", data = cartData };
                }
                else
                {
                    //there are no items in the cart, so the cart is deleted
                    shoppingCartGuid ??= Guid.NewGuid();
                    trackEvent.EventName = SendinblueDefaults.CartDeletedEventName;
                    trackEvent.EventData = new { id = $"cart:{shoppingCartGuid}" };
                }

                //track event
                await client.TrackEventAsync(trackEvent);

                //update GUID for the current customer's shopping cart
                await _genericAttributeService.SaveAttributeAsync(customer, SendinblueDefaults.ShoppingCartGuidAttribute, shoppingCartGuid);
            }
            catch (Exception exception)
            {
                //log full error
                await _logger.ErrorAsync($"Sendinblue Marketing Automation error: {exception.Message}.", exception, customer);
            }
        }
Beispiel #51
0
        public virtual async Task <IActionResult> ProductDetails(string productId, string updatecartitemid = "")
        {
            var product = await _productService.GetProductById(productId);

            if (product == null)
            {
                return(InvokeHttp404());
            }

            var customer = _workContext.CurrentCustomer;

            //published?
            if (!_catalogSettings.AllowViewUnpublishedProductPage)
            {
                //Check whether the current user has a "Manage catalog" permission
                //It allows him to preview a product before publishing
                if (!product.Published && !await _permissionService.Authorize(StandardPermissionProvider.ManageProducts, customer))
                {
                    return(InvokeHttp404());
                }
            }

            //ACL (access control list)
            if (!_aclService.Authorize(product, customer))
            {
                return(InvokeHttp404());
            }

            //Store mapping
            if (!_storeMappingService.Authorize(product))
            {
                return(InvokeHttp404());
            }

            //availability dates
            if (!product.IsAvailable() && !(product.ProductType == ProductType.Auction))
            {
                return(InvokeHttp404());
            }

            //visible individually?
            if (!product.VisibleIndividually)
            {
                //is this one an associated products?
                var parentGroupedProduct = await _productService.GetProductById(product.ParentGroupedProductId);

                if (parentGroupedProduct == null)
                {
                    return(RedirectToRoute("HomePage"));
                }

                return(RedirectToRoute("Product", new { SeName = parentGroupedProduct.GetSeName(_workContext.WorkingLanguage.Id) }));
            }
            //update existing shopping cart item?
            ShoppingCartItem updatecartitem = null;

            if (_shoppingCartSettings.AllowCartItemEditing && !String.IsNullOrEmpty(updatecartitemid))
            {
                var cart = _shoppingCartService.GetShoppingCart(_storeContext.CurrentStore.Id);

                updatecartitem = cart.FirstOrDefault(x => x.Id == updatecartitemid);
                //not found?
                if (updatecartitem == null)
                {
                    return(RedirectToRoute("Product", new { SeName = product.GetSeName(_workContext.WorkingLanguage.Id) }));
                }
                //is it this product?
                if (product.Id != updatecartitem.ProductId)
                {
                    return(RedirectToRoute("Product", new { SeName = product.GetSeName(_workContext.WorkingLanguage.Id) }));
                }
            }

            //prepare the model
            var model = await _mediator.Send(new GetProductDetailsPage()
            {
                Store               = _storeContext.CurrentStore,
                Product             = product,
                IsAssociatedProduct = false,
                UpdateCartItem      = updatecartitem
            });

            //product template
            var productTemplateViewPath = await _mediator.Send(new GetProductTemplateViewPath()
            {
                ProductTemplateId = product.ProductTemplateId
            });

            //save as recently viewed
            await _recentlyViewedProductsService.AddProductToRecentlyViewedList(customer.Id, product.Id);

            //display "edit" (manage) link
            if (await _permissionService.Authorize(StandardPermissionProvider.AccessAdminPanel, customer) &&
                await _permissionService.Authorize(StandardPermissionProvider.ManageProducts, customer))
            {
                //a vendor should have access only to his products
                if (_workContext.CurrentVendor == null || _workContext.CurrentVendor.Id == product.VendorId)
                {
                    DisplayEditLink(Url.Action("Edit", "Product", new { id = product.Id, area = "Admin" }));
                }
            }

            //activity log
            await _customerActivityService.InsertActivity("PublicStore.ViewProduct", product.Id, _localizationService.GetResource("ActivityLog.PublicStore.ViewProduct"), product.Name);

            await _customerActionEventService.Viewed(customer, this.HttpContext.Request.Path.ToString(), this.Request.Headers[HeaderNames.Referer].ToString() != null?Request.Headers[HeaderNames.Referer].ToString() : "");

            await _productService.UpdateMostView(productId);

            return(View(productTemplateViewPath, model));
        }
Beispiel #52
0
        /// <summary>
        /// Get dimensions values of the single shopping cart item
        /// </summary>
        /// <param name="item">Shopping cart item</param>
        /// <returns>Dimensions values</returns>
        private (decimal width, decimal length, decimal height) GetDimensionsForSingleItem(ShoppingCartItem item)
        {
            var items = new[] { new GetShippingOptionRequest.PackageItem(item, 1) };

            return(GetDimensions(items));
        }
 /// <summary>
 /// Gets the shopping cart item sub total
 /// </summary>
 /// <param name="shoppingCartItem">The shopping cart item</param>
 /// <param name="includeDiscounts">A value indicating whether include discounts or not for price computation</param>
 /// <returns>Shopping cart item sub total</returns>
 public virtual decimal GetSubTotal(ShoppingCartItem shoppingCartItem, bool includeDiscounts)
 {
     return(GetUnitPrice(shoppingCartItem, includeDiscounts) * shoppingCartItem.Quantity);
 }
        /// <summary>
        /// Gets the shopping cart unit price (one item)
        /// </summary>
        /// <param name="shoppingCartItem">The shopping cart item</param>
        /// <param name="includeDiscounts">A value indicating whether include discounts or not for price computation</param>
        /// <param name="discountAmount">Applied discount amount</param>
        /// <param name="appliedDiscount">Applied discount</param>
        /// <returns>Shopping cart unit price (one item)</returns>
        public virtual async Task <(decimal unitprice, decimal discountAmount, List <AppliedDiscount> appliedDiscounts)> GetUnitPrice(ShoppingCartItem shoppingCartItem,
                                                                                                                                      bool includeDiscounts = true)
        {
            if (shoppingCartItem == null)
            {
                throw new ArgumentNullException("shoppingCartItem");
            }
            var product = await _productService.GetProductById(shoppingCartItem.ProductId);

            return(await GetUnitPrice(product,
                                      _workContext.CurrentCustomer,
                                      shoppingCartItem.ShoppingCartType,
                                      shoppingCartItem.Quantity,
                                      shoppingCartItem.AttributesXml,
                                      shoppingCartItem.CustomerEnteredPrice,
                                      shoppingCartItem.RentalStartDateUtc,
                                      shoppingCartItem.RentalEndDateUtc,
                                      includeDiscounts));
        }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="sci">Shopping cart item</param>
 /// <param name="qty">Override "Quantity" property of shopping cart item</param>
 public PackageItem(ShoppingCartItem sci, int?qty = null)
 {
     this.ShoppingCartItem   = sci;
     this.OverriddenQuantity = qty;
 }
Beispiel #56
0
 public ShoppingCartItem DataRowToModel(DataRow row)
 {
     ShoppingCartItem item = new ShoppingCartItem();
     if (row != null)
     {
         if ((row["ItemId"] != null) && (row["ItemId"].ToString() != ""))
         {
             item.ItemId = int.Parse(row["ItemId"].ToString());
         }
         if ((row["UserId"] != null) && (row["UserId"].ToString() != ""))
         {
             item.UserId = int.Parse(row["UserId"].ToString());
         }
         if (row["SKU"] != null)
         {
             item.SKU = row["SKU"].ToString();
         }
         if ((row["Quantity"] != null) && (row["Quantity"].ToString() != ""))
         {
             item.Quantity = int.Parse(row["Quantity"].ToString());
         }
         if ((row["ItemType"] != null) && (row["ItemType"].ToString() != ""))
         {
             item.ItemType = (CartItemType) int.Parse(row["ItemType"].ToString());
         }
         if (row["Name"] != null)
         {
             item.Name = row["Name"].ToString();
         }
         if (row["ThumbnailsUrl"] != null)
         {
             item.ThumbnailsUrl = row["ThumbnailsUrl"].ToString();
         }
         if (row["Description"] != null)
         {
             item.Description = row["Description"].ToString();
         }
         if ((row["CostPrice"] != null) && (row["CostPrice"].ToString() != ""))
         {
             item.CostPrice = decimal.Parse(row["CostPrice"].ToString());
         }
         if ((row["SellPrice"] != null) && (row["SellPrice"].ToString() != ""))
         {
             item.SellPrice = decimal.Parse(row["SellPrice"].ToString());
         }
         if ((row["AdjustedPrice"] != null) && (row["AdjustedPrice"].ToString() != ""))
         {
             item.AdjustedPrice = decimal.Parse(row["AdjustedPrice"].ToString());
         }
         if (row["Attributes"] != null)
         {
             item.Attributes = row["Attributes"].ToString();
         }
         if ((row["Weight"] != null) && (row["Weight"].ToString() != ""))
         {
             item.Weight = int.Parse(row["Weight"].ToString());
         }
         if ((row["Deduct"] != null) && (row["Deduct"].ToString() != ""))
         {
             item.Deduct = new decimal?(decimal.Parse(row["Deduct"].ToString()));
         }
         if ((row["Points"] != null) && (row["Points"].ToString() != ""))
         {
             item.Points = int.Parse(row["Points"].ToString());
         }
         if ((row["ProductLineId"] != null) && (row["ProductLineId"].ToString() != ""))
         {
             item.ProductLineId = new int?(int.Parse(row["ProductLineId"].ToString()));
         }
         if ((row["SupplierId"] != null) && (row["SupplierId"].ToString() != ""))
         {
             item.SupplierId = new int?(int.Parse(row["SupplierId"].ToString()));
         }
         if (row["SupplierName"] != null)
         {
             item.SupplierName = row["SupplierName"].ToString();
         }
     }
     return item;
 }
Beispiel #57
0
        public IActionResult UpdateShoppingCartItem([ModelBinder(typeof(JsonModelBinder <ShoppingCartItemDto>))] Delta <ShoppingCartItemDto> shoppingCartItemDelta)
        {
            // Here we display the errors if the validation has failed at some point.
            if (!ModelState.IsValid)
            {
                return(Error());
            }

            // We kno that the id will be valid integer because the validation for this happens in the validator which is executed by the model binder.
            ShoppingCartItem shoppingCartItemForUpdate =
                _shoppingCartItemApiService.GetShoppingCartItem(int.Parse(shoppingCartItemDelta.Dto.Id));

            if (shoppingCartItemForUpdate == null)
            {
                return(Error(HttpStatusCode.NotFound, "shopping_cart_item", "not found"));
            }

            shoppingCartItemDelta.Merge(shoppingCartItemForUpdate);

            if (!shoppingCartItemForUpdate.Product.IsRental)
            {
                shoppingCartItemForUpdate.RentalStartDateUtc = null;
                shoppingCartItemForUpdate.RentalEndDateUtc   = null;
            }

            if (shoppingCartItemDelta.Dto.Attributes != null)
            {
                shoppingCartItemForUpdate.AttributesXml = _productAttributeConverter.ConvertToXml(shoppingCartItemDelta.Dto.Attributes, shoppingCartItemForUpdate.Product.Id);
            }

            // The update time is set in the service.
            var warnings = _shoppingCartService.UpdateShoppingCartItem(shoppingCartItemForUpdate.Customer, shoppingCartItemForUpdate.Id,
                                                                       shoppingCartItemForUpdate.AttributesXml, shoppingCartItemForUpdate.CustomerEnteredPrice,
                                                                       shoppingCartItemForUpdate.RentalStartDateUtc, shoppingCartItemForUpdate.RentalEndDateUtc,
                                                                       shoppingCartItemForUpdate.Quantity);

            if (warnings.Count > 0)
            {
                foreach (var warning in warnings)
                {
                    ModelState.AddModelError("shopping cart item", warning);
                }

                return(Error(HttpStatusCode.BadRequest));
            }
            else
            {
                shoppingCartItemForUpdate = _shoppingCartItemApiService.GetShoppingCartItem(shoppingCartItemForUpdate.Id);
            }

            // Preparing the result dto of the new product category mapping
            ShoppingCartItemDto newShoppingCartItemDto = _dtoHelper.PrepareShoppingCartItemDTO(shoppingCartItemForUpdate);

            var shoppingCartsRootObject = new ShoppingCartItemsRootObject();

            shoppingCartsRootObject.ShoppingCartItems.Add(newShoppingCartItemDto);

            var json = _jsonFieldsSerializer.Serialize(shoppingCartsRootObject, string.Empty);

            return(new RawJsonActionResult(json));
        }
        /// <returns>A task that represents the asynchronous operation</returns>
        public virtual async Task <IActionResult> EstimateShipping([FromQuery] ProductDetailsModel.ProductEstimateShippingModel model, IFormCollection form)
        {
            if (model == null)
            {
                model = new ProductDetailsModel.ProductEstimateShippingModel();
            }

            var errors = new List <string>();

            if (!_shippingSettings.EstimateShippingCityNameEnabled && string.IsNullOrEmpty(model.ZipPostalCode))
            {
                errors.Add(await _localizationService.GetResourceAsync("Shipping.EstimateShipping.ZipPostalCode.Required"));
            }

            if (_shippingSettings.EstimateShippingCityNameEnabled && string.IsNullOrEmpty(model.City))
            {
                errors.Add(await _localizationService.GetResourceAsync("Shipping.EstimateShipping.City.Required"));
            }

            if (model.CountryId == null || model.CountryId == 0)
            {
                errors.Add(await _localizationService.GetResourceAsync("Shipping.EstimateShipping.Country.Required"));
            }

            if (errors.Count > 0)
            {
                return(Json(new
                {
                    Success = false,
                    Errors = errors
                }));
            }

            var product = await _productService.GetProductByIdAsync(model.ProductId);

            if (product == null || product.Deleted)
            {
                errors.Add(await _localizationService.GetResourceAsync("Shipping.EstimateShippingPopUp.Product.IsNotFound"));
                return(Json(new
                {
                    Success = false,
                    Errors = errors
                }));
            }

            var wrappedProduct = new ShoppingCartItem()
            {
                StoreId            = (await _storeContext.GetCurrentStoreAsync()).Id,
                ShoppingCartTypeId = (int)ShoppingCartType.ShoppingCart,
                CustomerId         = (await _workContext.GetCurrentCustomerAsync()).Id,
                ProductId          = product.Id,
                CreatedOnUtc       = DateTime.UtcNow
            };

            var addToCartWarnings = new List <string>();

            //customer entered price
            wrappedProduct.CustomerEnteredPrice = await _productAttributeParser.ParseCustomerEnteredPriceAsync(product, form);

            //entered quantity
            wrappedProduct.Quantity = _productAttributeParser.ParseEnteredQuantity(product, form);

            //product and gift card attributes
            wrappedProduct.AttributesXml = await _productAttributeParser.ParseProductAttributesAsync(product, form, addToCartWarnings);

            //rental attributes
            _productAttributeParser.ParseRentalDates(product, form, out var rentalStartDate, out var rentalEndDate);
            wrappedProduct.RentalStartDateUtc = rentalStartDate;
            wrappedProduct.RentalEndDateUtc   = rentalEndDate;

            var result = await _shoppingCartModelFactory.PrepareEstimateShippingResultModelAsync(new[] { wrappedProduct }, model, false);

            return(Json(result));
        }
Beispiel #59
0
        public virtual IActionResult AddProductToCart_Details(string productId, int shoppingCartTypeId, IFormCollection form)
        {
            var product = _productService.GetProductById(productId);

            if (product == null)
            {
                return(Json(new
                {
                    redirect = Url.RouteUrl("HomePage"),
                }));
            }

            //you can't add group products
            if (product.ProductType == ProductType.GroupedProduct)
            {
                return(Json(new
                {
                    success = false,
                    message = "Grouped products couldn't be added to the cart"
                }));
            }

            //you can't add reservation product to wishlist
            if (product.ProductType == ProductType.Reservation && (ShoppingCartType)shoppingCartTypeId == ShoppingCartType.Wishlist)
            {
                return(Json(new
                {
                    success = false,
                    message = "Reservation products couldn't be added to the wishlist"
                }));
            }

            //you can't add auction product to wishlist
            if (product.ProductType == ProductType.Auction && (ShoppingCartType)shoppingCartTypeId == ShoppingCartType.Wishlist)
            {
                return(Json(new
                {
                    success = false,
                    message = "Auction products couldn't be added to the wishlist"
                }));
            }

            #region Update existing shopping cart item?
            string updatecartitemid = "";
            foreach (string formKey in form.Keys)
            {
                if (formKey.Equals(string.Format("addtocart_{0}.UpdatedShoppingCartItemId", productId), StringComparison.OrdinalIgnoreCase))
                {
                    updatecartitemid = form[formKey];
                    break;
                }
            }
            ShoppingCartItem updatecartitem = null;
            if (_shoppingCartSettings.AllowCartItemEditing && !String.IsNullOrEmpty(updatecartitemid))
            {
                var cart = _workContext.CurrentCustomer.ShoppingCartItems
                           .Where(x => x.ShoppingCartTypeId == shoppingCartTypeId)
                           .LimitPerStore(_storeContext.CurrentStore.Id)
                           .ToList();
                updatecartitem = cart.FirstOrDefault(x => x.Id == updatecartitemid);

                //is it this product?
                if (updatecartitem != null && product.Id != updatecartitem.ProductId)
                {
                    return(Json(new
                    {
                        success = false,
                        message = "This product does not match a passed shopping cart item identifier"
                    }));
                }
            }
            #endregion

            #region Customer entered price
            decimal customerEnteredPriceConverted = decimal.Zero;
            if (product.CustomerEntersPrice)
            {
                foreach (string formKey in form.Keys)
                {
                    if (formKey.Equals(string.Format("addtocart_{0}.CustomerEnteredPrice", productId), StringComparison.OrdinalIgnoreCase))
                    {
                        if (decimal.TryParse(form[formKey], out decimal customerEnteredPrice))
                        {
                            customerEnteredPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(customerEnteredPrice, _workContext.WorkingCurrency);
                        }
                        break;
                    }
                }
            }
            #endregion

            #region Quantity

            int quantity = 1;
            foreach (string formKey in form.Keys)
            {
                if (formKey.Equals(string.Format("addtocart_{0}.EnteredQuantity", productId), StringComparison.OrdinalIgnoreCase))
                {
                    int.TryParse(form[formKey], out quantity);
                    break;
                }
            }

            #endregion

            //product and gift card attributes
            string attributes = _shoppingCartViewModelService.ParseProductAttributes(product, form);

            //rental attributes
            DateTime?rentalStartDate = null;
            DateTime?rentalEndDate   = null;
            if (product.ProductType == ProductType.Reservation)
            {
                _shoppingCartViewModelService.ParseReservationDates(product, form, out rentalStartDate, out rentalEndDate);
            }

            //product reservation
            string reservationId = "";
            string parameter     = "";
            string duration      = "";
            if (product.ProductType == ProductType.Reservation)
            {
                foreach (string formKey in form.Keys)
                {
                    if (formKey.Contains("Reservation"))
                    {
                        reservationId = form["Reservation"].ToString();
                        break;
                    }
                }

                if (product.IntervalUnitType == IntervalUnit.Hour || product.IntervalUnitType == IntervalUnit.Minute)
                {
                    if (string.IsNullOrEmpty(reservationId))
                    {
                        return(Json(new
                        {
                            success = false,
                            message = _localizationService.GetResource("Product.Addtocart.Reservation.Required")
                        }));
                    }
                    var reservation = _productReservationService.GetProductReservation(reservationId);
                    if (reservation == null)
                    {
                        return(Json(new
                        {
                            success = false,
                            message = "No reservation found"
                        }));
                    }
                    duration        = reservation.Duration;
                    rentalStartDate = reservation.Date;
                    parameter       = reservation.Parameter;
                }
                else if (product.IntervalUnitType == IntervalUnit.Day)
                {
                    string datefrom = "";
                    string dateto   = "";
                    foreach (var item in form)
                    {
                        if (item.Key == "reservationDatepickerFrom")
                        {
                            datefrom = item.Value;
                        }

                        if (item.Key == "reservationDatepickerTo")
                        {
                            dateto = item.Value;
                        }
                    }

                    string datePickerFormat = "MM/dd/yyyy";
                    if (!string.IsNullOrEmpty(datefrom))
                    {
                        rentalStartDate = DateTime.ParseExact(datefrom, datePickerFormat, CultureInfo.InvariantCulture);
                    }

                    if (!string.IsNullOrEmpty(dateto))
                    {
                        rentalEndDate = DateTime.ParseExact(dateto, datePickerFormat, CultureInfo.InvariantCulture);
                    }
                }
            }

            var cartType = updatecartitem == null ? (ShoppingCartType)shoppingCartTypeId :
                           //if the item to update is found, then we ignore the specified "shoppingCartTypeId" parameter
                           updatecartitem.ShoppingCartType;

            //save item
            var addToCartWarnings = new List <string>();

            if (product.AvailableEndDateTimeUtc.HasValue && product.AvailableEndDateTimeUtc.Value < DateTime.UtcNow)
            {
                return(Json(new
                {
                    success = false,
                    message = _localizationService.GetResource("ShoppingCart.NotAvailable")
                }));
            }

            if (updatecartitem == null)
            {
                //add to the cart
                addToCartWarnings.AddRange(_shoppingCartService.AddToCart(_workContext.CurrentCustomer,
                                                                          productId, cartType, _storeContext.CurrentStore.Id,
                                                                          attributes, customerEnteredPriceConverted,
                                                                          rentalStartDate, rentalEndDate, quantity, true, reservationId, parameter, duration));
            }
            else
            {
                var cart = _workContext.CurrentCustomer.ShoppingCartItems
                           .Where(x => x.ShoppingCartType == updatecartitem.ShoppingCartType)
                           .LimitPerStore(_storeContext.CurrentStore.Id)
                           .ToList();
                var otherCartItemWithSameParameters = _shoppingCartService.FindShoppingCartItemInTheCart(
                    cart, updatecartitem.ShoppingCartType, productId, attributes, customerEnteredPriceConverted,
                    rentalStartDate, rentalEndDate);
                if (otherCartItemWithSameParameters != null &&
                    otherCartItemWithSameParameters.Id == updatecartitem.Id)
                {
                    //ensure it's other shopping cart cart item
                    otherCartItemWithSameParameters = null;
                }
                //update existing item
                addToCartWarnings.AddRange(_shoppingCartService.UpdateShoppingCartItem(_workContext.CurrentCustomer,
                                                                                       updatecartitem.Id, attributes, customerEnteredPriceConverted,
                                                                                       rentalStartDate, rentalEndDate, quantity, true));
                if (otherCartItemWithSameParameters != null && !addToCartWarnings.Any())
                {
                    //delete the same shopping cart item (the other one)
                    _shoppingCartService.DeleteShoppingCartItem(_workContext.CurrentCustomer, otherCartItemWithSameParameters);
                }
            }

            #region Return result

            if (addToCartWarnings.Any())
            {
                //cannot be added to the cart/wishlist
                //let's display warnings
                return(Json(new
                {
                    success = false,
                    message = addToCartWarnings.ToArray()
                }));
            }

            var addtoCartModel = _shoppingCartViewModelService.PrepareAddToCartModel(product, _workContext.CurrentCustomer, quantity, customerEnteredPriceConverted, attributes, cartType, rentalStartDate, rentalEndDate, reservationId, parameter, duration);

            //added to the cart/wishlist
            switch (cartType)
            {
            case ShoppingCartType.Wishlist:
            {
                //activity log
                _customerActivityService.InsertActivity("PublicStore.AddToWishlist", product.Id, _localizationService.GetResource("ActivityLog.PublicStore.AddToWishlist"), product.Name);

                if (_shoppingCartSettings.DisplayWishlistAfterAddingProduct)
                {
                    //redirect to the wishlist page
                    return(Json(new
                        {
                            redirect = Url.RouteUrl("Wishlist"),
                        }));
                }

                //display notification message and update appropriate blocks
                var updatetopwishlistsectionhtml = string.Format(_localizationService.GetResource("Wishlist.HeaderQuantity"),
                                                                 _workContext.CurrentCustomer.ShoppingCartItems
                                                                 .Where(sci => sci.ShoppingCartType == ShoppingCartType.Wishlist)
                                                                 .LimitPerStore(_storeContext.CurrentStore.Id)
                                                                 .Sum(x => x.Quantity));

                return(Json(new
                    {
                        success = true,
                        message = string.Format(_localizationService.GetResource("Products.ProductHasBeenAddedToTheWishlist.Link"), Url.RouteUrl("Wishlist")),
                        updatetopwishlistsectionhtml = updatetopwishlistsectionhtml,
                        html = this.RenderPartialViewToString("_AddToCart", addtoCartModel),
                    }));
            }

            case ShoppingCartType.ShoppingCart:
            default:
            {
                //activity log
                _customerActivityService.InsertActivity("PublicStore.AddToShoppingCart", product.Id, _localizationService.GetResource("ActivityLog.PublicStore.AddToShoppingCart"), product.Name);

                if (_shoppingCartSettings.DisplayCartAfterAddingProduct)
                {
                    //redirect to the shopping cart page
                    return(Json(new
                        {
                            redirect = Url.RouteUrl("ShoppingCart"),
                        }));
                }

                //display notification message and update appropriate blocks
                var updatetopcartsectionhtml = string.Format(_localizationService.GetResource("ShoppingCart.HeaderQuantity"),
                                                             _workContext.CurrentCustomer.ShoppingCartItems
                                                             .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
                                                             .LimitPerStore(_storeContext.CurrentStore.Id)
                                                             .Sum(x => x.Quantity));

                var updateflyoutcartsectionhtml = _shoppingCartSettings.MiniShoppingCartEnabled
                            ? this.RenderViewComponentToString("FlyoutShoppingCart")
                            : "";

                return(Json(new
                    {
                        success = true,
                        message = string.Format(_localizationService.GetResource("Products.ProductHasBeenAddedToTheCart.Link"), Url.RouteUrl("ShoppingCart")),
                        html = this.RenderPartialViewToString("_AddToCart", addtoCartModel),
                        updatetopcartsectionhtml = updatetopcartsectionhtml,
                        updateflyoutcartsectionhtml = updateflyoutcartsectionhtml,
                        refreshreservation = product.ProductType == ProductType.Reservation && product.IntervalUnitType != IntervalUnit.Day
                    }));
            }
            }


            #endregion
        }
Beispiel #60
0
        public Models.OperationReturnModel <ShoppingCartItem> UpdateItem(Guid cartId, ShoppingCartItem updatedItem)
        {
            Models.OperationReturnModel <ShoppingCartItem> retVal = new Models.OperationReturnModel <ShoppingCartItem>();
            try
            {
                _shoppingCartLogic.UpdateItem(this.AuthenticatedUser, this.SelectedUserContext, cartId, updatedItem);
                retVal.SuccessResponse = updatedItem;
                retVal.IsSuccess       = true;
            }
            catch (Exception ex)
            {
                _log.WriteErrorLog(string.Format("AddItem({0})", JsonConvert.SerializeObject(updatedItem)), ex);
                ExceptionEmail.Send(ex, string.Format("AddItem({0})", JsonConvert.SerializeObject(updatedItem)));
                retVal.ErrorMessage = ex.Message;
                retVal.IsSuccess    = false;
            }

            return(retVal);
        }