public IHttpActionResult calculateProductUnitPrice([FromBody] ProductDetailCalculatorParameter parameter)
        {
            try
            {
                using (var db = new DB_context())
                {
                    var temp = db.Products.AsQueryable();
                    Dictionary <string, object> result = new Dictionary <string, object>();
                    var listProduct = db.Products.OrderByDescending(data => data.ProductID).ToList();

                    ProductCalculator calculator = new ProductCalculator(';');
                    foreach (var item in listProduct)
                    {
                        calculator.calculateProductUnitPrice(item, parameter);
                    }

                    db.SaveChanges();
                    return(Ok("Data Saved Successfully"));
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        protected void Page_PreRender(object sender, EventArgs e)
        {
            foreach (RepeaterItem ri in SelectedProductRepeater.Items)
            {
                HiddenField pid       = (HiddenField)ri.FindControl("PID");
                int         productId = AlwaysConvert.ToInt(pid.Value);
                Product     p         = ProductDataSource.Load(productId);
                if (p != null && p.ProductOptions.Count > 0)
                {
                    Dictionary <int, int> selectedOptions = GetSelectedOptions(ri.ItemIndex);
                    bool              allOptionsSelected  = (selectedOptions.Count == p.ProductOptions.Count);
                    string            optionList          = ProductVariantDataSource.GetOptionList(p.Id, selectedOptions, true);
                    ProductCalculator pcalc        = ProductCalculator.LoadForProduct(p.Id, 1, optionList, string.Empty);
                    Literal           productPrice = (Literal)ri.FindControl("ProductPrice");
                    productPrice.Text = pcalc.Price.LSCurrencyFormat("lc");
                    if (allOptionsSelected)
                    {
                        ProductVariant pv = ProductVariantDataSource.LoadForOptionList(p.Id, optionList);
                        if (pv != null && !pv.Available)
                        {
                            HtmlTableRow trInvalidVariant = (HtmlTableRow)ri.FindControl("trInvalidVariant");
                            if (trInvalidVariant != null)
                            {
                                trInvalidVariant.Visible = true;
                            }
                        }
                    }
                }
            }

            // SAVE THE CUSTOM VIEWSTATE
            SaveCustomViewState();
        }
示例#3
0
        protected decimal GetPrice(object dataItem)
        {
            WishlistItem item = (WishlistItem)dataItem;
            //DETERMINE THE BASE PRICE OF THE ITEM
            decimal price;

            if (item.Product.UseVariablePrice)
            {
                price = AlwaysConvert.ToDecimal(item.Price);
                if (price < item.Product.MinimumPrice)
                {
                    price = AlwaysConvert.ToDecimal(item.Product.MinimumPrice);
                }
                if (price > item.Product.MaximumPrice)
                {
                    price = AlwaysConvert.ToDecimal(item.Product.MaximumPrice);
                }
                item.Price = price;
            }
            else
            {
                // ADD PRICE OF KIT PRODUCTS AS WELL
                ProductCalculator c = ProductCalculator.LoadForProduct(item.Product.Id, 1, item.OptionList, item.KitList);
                price = c.Price;
            }
            return(price);
        }
示例#4
0
        public void SetUp()
        {
            checkoutTill = new ProductCalculator();
            var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ProductDB.json"); //using ProductDb to replicate the Database
            var reader   = new StreamReader(filePath);
            var jsonStr  = reader.ReadToEnd();

            checkoutTill.SetProductPrice(jsonStr);
        }
示例#5
0
        public void TotalsOnlyWithSpecialOffersDecoupled()
        {
            List <Item> products = new List <Item>()
            {
                new Item()
                {
                    SKU = "A99", UnitPrice = 0.50m
                },
                new Item()
                {
                    SKU = "A99", UnitPrice = 0.50m
                },
                new Item()
                {
                    SKU = "A99", UnitPrice = 0.50m
                },
                new Item()
                {
                    SKU = "A99", UnitPrice = 0.50m
                },
                new Item()
                {
                    SKU = "B15", UnitPrice = 0.30m
                },
                new Item()
                {
                    SKU = "B15", UnitPrice = 0.30m
                },
                new Item()
                {
                    SKU = "B15", UnitPrice = 0.30m
                },
                new Item()
                {
                    SKU = "C40", UnitPrice = 0.60m
                }
            };

            List <PricingRule> discountRules = new List <PricingRule>
            {
                new PricingRule {
                    SKU = "A99", Quantity = 3, DiscountPrice = 1.3m
                },
                new PricingRule {
                    SKU = "B15", Quantity = 2, DiscountPrice = 0.45m
                }
            };

            var totaller = new ProductCalculator(products, discountRules);

            Assert.IsTrue(totaller.Total() == 3.15m);
        }
示例#6
0
        private IEnumerable <IFoodstuff> GetSaladIngredients(double weight, DishesIndex dish)
        {
            Console.Write($"{dish} будет готов через секунду: ");

            for (int i = 1; i < 2; i++)
            {
                Thread.Sleep(1000);

                Console.Write($"{i} ");
            }

            Console.Write($"\n");


            var saladWeight =
                ProductCalculator.CalculateWeightOfProductInDish(
                    weight, SaladData.GRAMS_OF_SALAD_PER_100_GRAMS_OF_SALAD);

            var parmesanWeight =
                ProductCalculator.CalculateWeightOfProductInDish(
                    weight, SaladData.GRAMS_OF_PARMESAN_PER_100_GRAMS_OF_SALAD);

            var breadWeight =
                ProductCalculator.CalculateWeightOfProductInDish(
                    weight, SaladData.GRAMS_OF_BREAD_PER_100_GRAMS_OF_SALAD);

            var garlicWeight =
                ProductCalculator.CalculateWeightOfProductInDish(
                    weight, SaladData.GRAMS_OF_GARLIC_PER_100_GRAMS_OF_SALAD);

            var oliveOilWeight =
                ProductCalculator.CalculateWeightOfProductInDish(
                    weight, SaladData.GRAMS_OF_OLIVE_OIL_PER_100_GRAMS_OF_SALAD);

            var saltWeight =
                ProductCalculator.CalculateWeightOfProductInDish(
                    weight, SaladData.GRAMS_OF_SALT_PER_100_GRAMS_OF_SALAD);

            var blackPepperWeight =
                ProductCalculator.CalculateWeightOfProductInDish(
                    weight, SaladData.GRAMS_OF_BLACK_PEPPER_PER_100_GRAMS_OF_SALAD);

            return(new List <IFoodstuff> {
                Store.GetLactucaSativa(saladWeight),
                Store.GetParmesan(parmesanWeight),
                Store.GetCiabattaBread(breadWeight),
                Store.GetGarlic(garlicWeight),
                Store.GetOliveOil(oliveOilWeight),
                Store.GetSeaSalt(saltWeight),
                Store.GetBlackPepper(blackPepperWeight)
            });
        }
示例#7
0
        protected string GetPrice(object dataItem)
        {
            //DETERMINE THE BASE PRICE OF THE ITEM
            WishlistItem item = (WishlistItem)dataItem;
            decimal      price;

            if (item.Product.IsSubscription && item.Product.SubscriptionPlan.IsOptional)
            {
                ProductCalculator c = ProductCalculator.LoadForProduct(item.Product.Id, 1, item.OptionList, item.KitList, AbleContext.Current.UserId, false, !item.IsSubscription);
                price = c.Price;
            }
            else
            {
                if (item.Product.UseVariablePrice)
                {
                    price = AlwaysConvert.ToDecimal(item.Price);
                    if (price < item.Product.MinimumPrice)
                    {
                        price = AlwaysConvert.ToDecimal(item.Product.MinimumPrice);
                    }
                    if (price > item.Product.MaximumPrice)
                    {
                        price = AlwaysConvert.ToDecimal(item.Product.MaximumPrice);
                    }
                    item.Price = price;
                }
                else
                {
                    // ADD PRICE OF KIT PRODUCTS AS WELL
                    ProductCalculator c = ProductCalculator.LoadForProduct(item.Product.Id, 1, item.OptionList, item.KitList);
                    price = c.Price;
                }
            }

            if (item.Product.VolumeDiscounts.Count > 0)
            {
                foreach (var rec in item.Product.VolumeDiscounts[0].Levels)
                {
                    if (item.Desired >= rec.MinValue && item.Desired <= rec.MaxValue)
                    {
                        return((rec.DiscountAmount).LSCurrencyFormat("ulc") + " ea.");
                    }
                }
            }

            decimal shopPrice = TaxHelper.GetShopPrice(price, item.Product.TaxCode != null ? item.Product.TaxCode.Id : 0);

            return(shopPrice > 0 ? shopPrice.LSCurrencyFormat("ulc") + " ea." : "");
        }
示例#8
0
        /// <summary>
        /// Recalculates the item price for the user the wishlist is associated to
        /// </summary>
        public void Recalculate()
        {
            if (this.Product.UseVariablePrice)
            {
                return;
            }
            //CALCULATE THE PRICE OF THE PRODUCT
            ProductCalculator pcalc = ProductCalculator.LoadForProduct(this.ProductId, this.Desired, this.OptionList, this.KitList, this.Wishlist.UserId);

            if (this.Price != pcalc.Price)
            {
                this.Price = pcalc.Price;
                this.Save();
            }
        }
示例#9
0
        private IEnumerable <IFoodstuff> GetSauceIngredients(double weight, DishesIndex dish)
        {
            Console.Write($"{dish} будет готов через секунду: ");

            for (int i = 1; i < 2; i++)
            {
                Thread.Sleep(1000);

                Console.Write($"{i} ");
            }

            Console.Write($"\n");


            var eggYolkWeight =
                ProductCalculator.CalculateWeightOfProductInDish(
                    weight, SauceData.GRAMS_OF_EGG_YOLK_PER_100_GRAMS_OF_SAUCE);

            var powderWeight =
                ProductCalculator.CalculateWeightOfProductInDish(
                    weight, SauceData.GRAMS_OF_MUSTARD_POWDER_PER_100_GRAMS_OF_SAUCE);

            var kefirWeight =
                ProductCalculator.CalculateWeightOfProductInDish(
                    weight, SauceData.GRAMS_OF_KEFIR_PER_100_GRAMS_OF_SAUCE);

            var oliveOilWeight =
                ProductCalculator.CalculateWeightOfProductInDish(
                    weight, SauceData.GRAMS_OF_OLIVE_OIL_PER_100_GRAMS_OF_SAUCE);

            var saltWeight =
                ProductCalculator.CalculateWeightOfProductInDish(
                    weight, SauceData.GRAMS_OF_SALT_PER_100_GRAMS_OF_SAUCE);

            var oreganoWeight =
                ProductCalculator.CalculateWeightOfProductInDish(
                    weight, SauceData.GRAMS_OF_OREGANO_PER_100_GRAMS_OF_SAUCE);

            return(new List <IFoodstuff> {
                Store.GetEggYolk(eggYolkWeight),
                Store.GetMustardPowder(powderWeight),
                Store.GetKefir(kefirWeight),
                Store.GetOliveOil(oliveOilWeight),
                Store.GetSeaSalt(saltWeight),
                Store.GetOregano(oreganoWeight)
            });
        }
示例#10
0
            protected string GetVariantPrice(string optionList)
            {
                ProductCalculator pcalc = null;

                if (!string.IsNullOrEmpty(optionList) && _showMSRP)
                {
                    pcalc = ProductCalculator.LoadForProduct(_ProductId, 1, optionList, string.Empty);
                    return(pcalc.MSRP.LSCurrencyFormat("ulc"));
                }
                else if (!string.IsNullOrEmpty(optionList))
                {
                    Product p = ProductDataSource.Load(_ProductId);
                    pcalc = ProductCalculator.LoadForProduct(_ProductId, 1, optionList, string.Empty);
                    return(TaxHelper.GetShopPrice(pcalc.Price, p.TaxCode != null ? p.TaxCode.Id : 0).LSCurrencyFormat("ulc"));
                }
                return("");
            }
示例#11
0
        public IFoodstuff MakeDishBy(IChef chef, DishesIndex dish, double weight)
        {
            try
            {
                var sauceWeight =
                    ProductCalculator.CalculateWeightOfProductInDish(
                        weight, SaladData.GRAMS_OF_CAESAR_SAUCE_PER_100_GRAMS_OF_SALAD);

                var saladDressing = chef.MakeDish(DishesIndex.CaesarSauce, sauceWeight);

                return(chef.MakeDish(dish, weight, saladDressing));
            }
            catch
            {
                throw;
            }
        }
        protected void Price_PreRender(object sender, EventArgs e)
        {
            int     productId = AlwaysConvert.ToInt(HiddenProductId.Value);
            Product product   = ProductDataSource.Load(productId);

            if (product != null)
            {
                //GET THE SELECTED KIT OPTIONS
                GetSelectedKitOptions(product);
            }
            //SET THE CURRENT CALCULATED PRICE
            string            optionList = ProductVariantDataSource.GetOptionList(productId, _SelectedOptions, true);
            ProductCalculator pcalc      = ProductCalculator.LoadForProduct(productId, 1, optionList, AlwaysConvert.ToList(",", _SelectedKitProducts));

            Price.Text = string.Format("{0:F2}", pcalc.Price);

            if (product.UseVariablePrice)
            {
                string varPriceText = string.Empty;
                if (product.MinimumPrice > 0)
                {
                    if (product.MaximumPrice > 0)
                    {
                        varPriceText = string.Format("(between {0} and {1})", product.MinimumPrice.LSCurrencyFormat("lcf"), product.MaximumPrice.LSCurrencyFormat("lcf"));
                    }
                    else
                    {
                        varPriceText = string.Format("(at least {0})", product.MinimumPrice.LSCurrencyFormat("lcf"));
                    }
                }
                else if (product.MaximumPrice > 0)
                {
                    varPriceText = string.Format("({0} maximum)", product.MaximumPrice.LSCurrencyFormat("lcf"));
                }
                phVariablePrice.Controls.Add(new LiteralControl(varPriceText));
            }

            // CHANGING PRODUCT PRICE OPTION SHOULD NOT AVAILABLE FOR KIT PRODUCTS
            Price.Enabled = (product.KitStatus != KitStatus.Master);

            InventoryAlertUpdate();
        }
示例#13
0
文件: Program.cs 项目: laaragm/CSharp
        static void Main(string[] args)
        {
            List <Product> products = new List <Product>();

            Console.Write("Number of products: ");
            int numberOfProducts = int.Parse(Console.ReadLine());

            for (int i = 0; i < numberOfProducts; i++)
            {
                string[] p     = Console.ReadLine().Split(',');
                double   price = double.Parse(p[1], CultureInfo.InvariantCulture);
                products.Add(new Product(p[0], price));
            }

            ProductCalculator calculationService = new ProductCalculator();

            Product product = calculationService.Max(products);

            Console.WriteLine();
            Console.Write("The most expensive item is: ");
            Console.WriteLine(product);
        }
示例#14
0
        protected virtual Dictionary <string, double> CalculateNutritionInformation(Dictionary <IFoodstuff, double> _proportions)
        {
            var query = _proportions
                        .Select(proportion =>
            {
                var caloric = ProductCalculator.CalculateWeightOfProductInDish(
                    proportion.Value, proportion.Key.CaloricPer100Grams);
                var fats = ProductCalculator.CalculateWeightOfProductInDish(
                    proportion.Value, proportion.Key.FatsPer100Grams);
                var proteins = ProductCalculator.CalculateWeightOfProductInDish(
                    proportion.Value, proportion.Key.ProteinsPer100Grams);
                var carbohydrates = ProductCalculator.CalculateWeightOfProductInDish(
                    proportion.Value, proportion.Key.CarbohydratesPer100Grams);

                var r = new { caloric, fats, proteins, carbohydrates };

                return(r);
            })
                        .Aggregate((f, n) =>
            {
                return
                (new
                {
                    caloric = f.caloric + n.caloric,
                    fats = f.fats + n.fats,
                    proteins = f.proteins + n.proteins,
                    carbohydrates = f.carbohydrates + n.carbohydrates
                });
            })
            ;

            return(new Dictionary <string, double>
            {
                { "caloric", query.caloric },
                { "fats", query.fats },
                { "proteins", query.proteins },
                { "carbohydrates", query.carbohydrates }
            });
        }
示例#15
0
        protected string GetPrice(object dataItem)
        {
            //DETERMINE THE BASE PRICE OF THE ITEM
            WishlistItem item = (WishlistItem)dataItem;
            decimal      price;

            if (item.Product.IsSubscription && item.Product.SubscriptionPlan.IsOptional)
            {
                ProductCalculator c = ProductCalculator.LoadForProduct(item.Product.Id, 1, item.OptionList, item.KitList, AbleContext.Current.UserId, false, !item.IsSubscription);
                price = c.Price;
            }
            else
            {
                if (item.Product.UseVariablePrice)
                {
                    price = AlwaysConvert.ToDecimal(item.Price);
                    if (price < item.Product.MinimumPrice)
                    {
                        price = AlwaysConvert.ToDecimal(item.Product.MinimumPrice);
                    }
                    if (price > item.Product.MaximumPrice)
                    {
                        price = AlwaysConvert.ToDecimal(item.Product.MaximumPrice);
                    }
                    item.Price = price;
                }
                else
                {
                    // ADD PRICE OF KIT PRODUCTS AS WELL
                    ProductCalculator c = ProductCalculator.LoadForProduct(item.Product.Id, 1, item.OptionList, item.KitList);
                    price = c.Price;
                }
            }

            decimal shopPrice = TaxHelper.GetShopPrice(price, item.Product.TaxCode != null ? item.Product.TaxCode.Id : 0);

            return(shopPrice.LSCurrencyFormat("ulc"));
        }
示例#16
0
        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (_Product != null)
            {
                if (!_Product.UseVariablePrice || _Product.IsSubscription)
                {
                    if (_showQuoteOnZeroPrice && !(_Product.VolumeDiscounts.Any() && _Product.VolumeDiscounts[0].Levels.Any()))
                    {
                        if (_Product.Price == 0)
                        {
                            Price.Text = "Request a quote";
                            return;
                        }
                    }

                    if (_hideZeroPrice)
                    {
                        if (_Product.Price == 0 && _Product.ProductOptions.Count > 0)
                        {
                            this.Visible = false;
                            return;
                        }
                    }
                    // UPDATE THE INCLUDED KITPRODUCTS (Included-Hidden and Included-Shown)
                    if (_SelectedKitProducts.Count == 0 && this.EnableDefaultKitProducts)
                    {
                        UpdateIncludedKitOptions();
                    }
                    ProductCalculator pcalc = ProductCalculator.LoadForProduct(_Product.Id, 1, _OptionList, AlwaysConvert.ToList(",", _SelectedKitProducts), AbleContext.Current.UserId, true, this.CalculateOneTimePrice);

                    //IF REQUIRED MAKE ADJUSTMENTS TO DISPLAYED PRICE TO INCLUDE VAT
                    decimal basePriceWithVAT = TaxHelper.GetShopPrice(_Product.Price, (_Product.TaxCode != null) ? _Product.TaxCode.Id : 0);
                    decimal priceWithVAT     = pcalc.PriceWithTax;
                    decimal msrpWithVAT      = TaxHelper.GetShopPrice(_Product.MSRP, (_Product.TaxCode != null) ? _Product.TaxCode.Id : 0);
                    if (!_Product.HidePrice)
                    {
                        //PRICE IS VISIBLE, NO POPUP
                        phPricePopup.Visible = false;
                        //SHOW RETAIL PRICE IF INDICATED
                        if (_ShowRetailPrice && msrpWithVAT > 0 && !_Product.UseVariablePrice)
                        {
                            RetailPrice1.Text = string.Format(_RetailPriceFormat, msrpWithVAT.LSCurrencyFormat("ulc"));
                        }
                        else
                        {
                            RetailPrice1.Text = string.Empty;
                        }
                        //SHOW THE PRICE
                        if (pcalc.AppliedSpecial != null)
                        {
                            // SHOW THE BASE PRICE AND SPECIAL PRICE
                            RetailPrice1.Text = string.Format(_BasePriceFormat, basePriceWithVAT.LSCurrencyFormat("ulc"));
                            if (pcalc.AppliedSpecial.EndDate != DateTime.MinValue)
                            {
                                Price.Text = string.Format(_SpecialPriceFormat, priceWithVAT.LSCurrencyFormat("ulc"), pcalc.AppliedSpecial.EndDate);
                            }
                            else
                            {
                                Price.Text = string.Format(_SpecialPriceFormat2, priceWithVAT.LSCurrencyFormat("ulc"), null);
                            }
                        }
                        else
                        {
                            Price.Text = string.Format(_PriceFormat, priceWithVAT.LSCurrencyFormat("ulc"));
                        }
                    }
                    else
                    {
                        // HIDDEN PRICE, USE POPUP
                        Price.Visible    = false;
                        ProductName.Text = _Product.Name;
                        // THESE VARIABLES WILL TRACK SAVINGS OFF LISTED OR REGULAR PRICE
                        decimal amountSaved  = 0;
                        decimal percentSaved = 0;
                        // DETERMINE IF A SALE OR SPECIAL PRICE IS APPLIED
                        bool salePriceEffective = (pcalc.AppliedSpecial != null);
                        // DETERMINE IF MSRP IS AVAILABLE FOR DISPLAY
                        if (_ShowRetailPrice && msrpWithVAT > 0 && !salePriceEffective)
                        {
                            trRetailPrice.Visible       = true;
                            HiddenRetailPriceLabel.Text = PopupRetailPriceLabel;
                            HiddenRetailPrice.Text      = string.Format(PopupRetailPriceFormat, msrpWithVAT.LSCurrencyFormat("ulc"));
                            // CALCULATE AMOUNT SAVED OVER MSRP
                            amountSaved  = (msrpWithVAT - priceWithVAT);
                            percentSaved = ((decimal)(amountSaved / msrpWithVAT)) * 100;
                        }
                        else
                        {
                            trRetailPrice.Visible = false;
                        }
                        // CHECK IF A SALE PRICE IS APPLIED
                        if (salePriceEffective)
                        {
                            // SPECIAL APPLIED, SHOW THE PRODUCT BASE PRICE AND THE SPECIAL PRICE
                            trSpecialPrice.Visible = true;
                            HiddenPriceLabel.Text  = PopupBasePriceLabel;
                            HiddenPrice.Text       = string.Format(PopupBasePriceFormat, basePriceWithVAT.LSCurrencyFormat("ulc"));
                            SpecialPriceLabel.Text = PopupSpecialPriceLabel;
                            if (pcalc.AppliedSpecial.EndDate != DateTime.MinValue)
                            {
                                SpecialPrice.Text = string.Format(PopupSpecialPriceFormat, priceWithVAT.LSCurrencyFormat("ulc"), pcalc.AppliedSpecial.EndDate);
                            }
                            else
                            {
                                SpecialPrice.Text = string.Format(PopupSpecialPriceFormat2, priceWithVAT.LSCurrencyFormat("ulc"), null);
                            }
                            // CALCULATE AMOUNT SAVED WITH SALE PRICE
                            amountSaved  = (basePriceWithVAT - priceWithVAT);
                            percentSaved = ((decimal)(amountSaved / basePriceWithVAT)) * 100;
                        }
                        else
                        {
                            // NO SPECIAL, SO JUST SHOW THE CALCULATED PRICE
                            HiddenPriceLabel.Text = PopupPriceLabel;
                            HiddenPrice.Text      = string.Format(PopupPriceFormat, priceWithVAT.LSCurrencyFormat("ulc"));
                        }
                        // SEE IF WE HAVE AN AMOUNT SAVED VALUE
                        if (amountSaved > 0)
                        {
                            trAmountSaved.Visible = true;
                            AmountSavedLabel.Text = PopupAmountSavedLabel;
                            AmountSaved.Text      = string.Format(PopupAmountSavedFormat, amountSaved.LSCurrencyFormat("ulc"), percentSaved);
                        }
                        else
                        {
                            trAmountSaved.Visible = false;
                        }
                    }
                }
                else
                {
                    //DO NOT DISPLAY THIS CONTROL IF THE PRODUCT HAS VARIABLE PRICE
                    this.Controls.Clear();
                }
            }
            else
            {
                //DO NOT DISPLAY THIS CONTROL IF THE PRODUCT IS UNAVAILABLE
                this.Controls.Clear();
            }
            SaveCustomViewState();
        }
示例#17
0
        /// <summary>
        /// Creates a basket item for a product
        /// </summary>
        /// <param name="productId">Id of the product for which to create the basket item</param>
        /// <param name="quantity">The quantity of basket item</param>
        /// <param name="optionList">List of option ids for the variant</param>
        /// <param name="kitList">List of product Ids of the kit items</param>
        /// <param name="userId">The user Id</param>
        /// <returns>The BasketItem created</returns>
        public static BasketItem CreateForProduct(int productId, short quantity, string optionList, string kitList, int userId)
        {
            // vALIDATE PARAMETERS
            Product product = ProductDataSource.Load(productId);

            if (product == null)
            {
                throw new ArgumentException("invalid product specified", "product");
            }
            if (quantity < 1)
            {
                throw new ArgumentException("quantity must be greater than 0", "quantity");
            }
            if (!string.IsNullOrEmpty(optionList))
            {
                ProductVariant v = ProductVariantDataSource.LoadForOptionList(productId, optionList);
                if (v == null)
                {
                    throw new ArgumentException("specified product options are invalid", "optionList");
                }
            }
            if (product.KitStatus == KitStatus.Master)
            {
                Kit kit = product.Kit;
                if (!kit.ValidateChoices(kitList))
                {
                    throw new ArgumentException("specified kit configuration is invalid", "kitProductIds");
                }
            }

            //GET THE QUANTITY
            short tempQuantity   = quantity;
            short basketQuantity = GetExistingBasketCount(product);

            if ((product.MinQuantity > 0) && ((tempQuantity + basketQuantity) < product.MinQuantity))
            {
                tempQuantity = (short)(product.MinQuantity - basketQuantity);
            }


            if ((product.MaxQuantity > 0) && ((tempQuantity + basketQuantity) > product.MaxQuantity))
            {
                tempQuantity = (short)(product.MaxQuantity - basketQuantity);
            }


            if (tempQuantity < 1)
            {
                return(null);
            }
            quantity = tempQuantity;

            BasketItem item = new BasketItem();
            //CALCULATE THE PRICE OF THE PRODUCT
            ProductCalculator pcalc = ProductCalculator.LoadForProduct(productId, quantity, optionList, kitList, userId);

            item.Sku    = pcalc.Sku;
            item.Price  = pcalc.Price;
            item.Weight = pcalc.Weight;
            //SET VALUES COMMON TO ALL BASKET ITEMS
            item.TaxCodeId     = product.TaxCodeId;
            item.Name          = product.Name;
            item.Quantity      = quantity;
            item.OrderItemType = CommerceBuilder.Orders.OrderItemType.Product;
            item.Shippable     = product.Shippable;
            item.ProductId     = productId;
            item.OptionList    = optionList;
            item.KitList       = kitList;

            // COPY MERCHANT INPUT FIELDS, PRODUCT TEMPLATE FIELDS
            foreach (ProductTemplateField tf in product.TemplateFields)
            {
                if (!string.IsNullOrEmpty(tf.InputValue))
                {
                    InputField field = tf.InputField;
                    if (field.IsMerchantField && field.PersistWithOrder)
                    {
                        BasketItemInput itemInput = new BasketItemInput();
                        itemInput.BasketItemId = item.BasketItemId;
                        itemInput.InputFieldId = tf.InputFieldId;
                        itemInput.InputValue   = tf.InputValue;
                        item.Inputs.Add(itemInput);
                    }
                }
            }


            return(item);
        }
        public void Page_Init(object sender, EventArgs e)
        {
            if (_Order == null)
            {
                OrderId = AbleCommerce.Code.PageHelper.GetOrderId();
            }
            if (_OrderShipment == null)
            {
                OrderShipmentId = AlwaysConvert.ToInt(Request.QueryString["OrderShipmentId"]);
            }
            if (_Order == null)
            {
                Response.Redirect("~/Admin/Orders/Default.aspx");
            }
            _ProductId = AlwaysConvert.ToInt(Request.QueryString["ProductId"]);
            _Product   = ProductDataSource.Load(_ProductId);


            if (_Product == null)
            {
                if (_OrderShipment == null)
                {
                    Response.Redirect("~/Admin/Orders/Edit/FindProduct.aspx?OrderNumber=" + _Order.OrderNumber.ToString());
                }
                else
                {
                    Response.Redirect("~/Admin/Orders/Shipments/FindProduct.aspx?OrderShipmentId=" + _OrderShipmentId.ToString());
                }
            }

            if (_OrderShipment == null)
            {
                BackButton.NavigateUrl = "~/Admin/Orders/Edit/EditOrderItems.aspx?OrderNumber=" + _Order.OrderNumber.ToString();
            }
            else
            {
                BackButton.NavigateUrl = "~/Admin/Orders/Shipments/EditShipment.aspx?OrderShipmentId=" + _OrderShipmentId.ToString();
            }

            // update instruction text
            GiftCertMessage.Visible     = _Product.IsGiftCertificate;
            DigitalGoodsMessage.Visible = _Product.IsDigitalGood;
            SubscriptionMessage.Visible = _Product.IsSubscription;

            //SET NAME AND PRICE
            Name.Text             = _Product.Name;
            HiddenProductId.Value = _Product.Id.ToString();
            //BUILD PRODUCT ATTRIBUTES
            _SelectedOptions = AbleCommerce.Code.ProductHelper.BuildProductOptions(_Product, phOptions, true);
            //BUILD PRODUCT CHOICES
            AbleCommerce.Code.ProductHelper.BuildProductChoices(_Product, phOptions);
            //BUILD KIT OPTIONS
            _SelectedKitProducts = AbleCommerce.Code.ProductHelper.BuildKitOptions(_Product, phOptions);
            //SET PRICE
            string            optionList = ProductVariantDataSource.GetOptionList(_Product.Id, _SelectedOptions, true);
            ProductCalculator pcalc      = ProductCalculator.LoadForProduct(_Product.Id, 1, optionList, AlwaysConvert.ToList(",", _SelectedKitProducts), _Order.UserId);

            Price.Text = string.Format("{0:F2}", pcalc.Price);
            // IF ALL OPTIONS HAVE A VALUE SELECTED, SHOW THE BASKET CONTROLS
            SaveButton.Visible = (_SelectedOptions.Count >= _Product.ProductOptions.Count);
            //BackButton.NavigateUrl += "?OrderNumber=" + _Order.OrderNumber.ToString();


            //CHECK IF SHIPMENTS NEED TO BE DISPLAYED
            trShipment.Visible = (_OrderShipment == null && _Product.Shippable != Shippable.No);
            if (trShipment.Visible)
            {
                //BIND SHIPMENT LIST
                foreach (OrderShipment shipment in _Order.Shipments)
                {
                    string address = string.Format("{0} {1} {2} {3}", shipment.ShipToFirstName, shipment.ShipToLastName, shipment.ShipToAddress1, shipment.ShipToCity);
                    if (address.Length > 50)
                    {
                        address = address.Substring(0, 47) + "...";
                    }
                    string name = "Shipment #" + shipment.ShipmentNumber + " to " + address;
                    ShipmentsList.Items.Add(new ListItem(name, shipment.Id.ToString()));
                }

                if (_Order.Shipments != null && _Order.Shipments.Count == 1)
                {
                    // IF THERE IS JUST ONLY ONE SHIPMENT THEN SELECT IT
                    ShipmentsList.SelectedIndex = 2;
                }
            }

            // if a new shipment option is selected then initialize the related fields
            DisplayOrderShipmentFields(ShipmentsList.SelectedValue == "-1"); ShipFrom.DataSource = AbleContext.Current.Store.Warehouses;
            ShipFrom.DataBind();
            if (AddressList.Items.Count <= 1)
            {
                BindShippingAddresses(this.AddressList);
            }
        }
 protected void FinishButton_Click(object sender, EventArgs e)
 {
     foreach (RepeaterItem ri in SelectedProductRepeater.Items)
     {
         HiddenField pid       = (HiddenField)ri.FindControl("PID");
         int         productId = AlwaysConvert.ToInt(pid.Value);
         Product     product   = ProductDataSource.Load(productId);
         if (product == null)
         {
             return;
         }
         if (!AllProductOptionsSelected(product, ri))
         {
             return;
         }
         TextBox KitQuantity = (TextBox)ri.FindControl("KitQuantity");
         short   quantity    = AlwaysConvert.ToInt16(KitQuantity.Text);
         if (quantity > 0)
         {
             ProductVariant productVariant = null;
             string         optionList     = string.Empty;
             if (product.ProductOptions.Count > 0)
             {
                 Dictionary <int, int> selectedOptions = GetSelectedOptions(ri.ItemIndex);
                 productVariant = ProductVariantDataSource.LoadForOptionList(productId, selectedOptions);
                 optionList     = ProductVariantDataSource.GetOptionList(productId, selectedOptions, true);
             }
             TextBox      NameFormat = (TextBox)ri.FindControl("NameFormat");
             DropDownList PriceMode  = (DropDownList)ri.FindControl("PriceMode");
             TextBox      Price      = (TextBox)ri.FindControl("Price");
             DropDownList WeightMode = (DropDownList)ri.FindControl("WeightMode");
             TextBox      Weight     = (TextBox)ri.FindControl("Weight");
             CheckBox     IsSelected = (CheckBox)ri.FindControl("IsSelected");
             KitProduct   kitProduct = new KitProduct();
             kitProduct.ProductId    = productId;
             kitProduct.KitComponent = _KitComponent;
             if (productVariant != null)
             {
                 kitProduct.OptionList = productVariant.OptionList;
             }
             kitProduct.Name     = NameFormat.Text;
             kitProduct.Quantity = quantity;
             ProductCalculator pcalc = ProductCalculator.LoadForProduct(productId, 1, optionList, string.Empty);
             kitProduct.PriceModeId = AlwaysConvert.ToByte(PriceMode.SelectedIndex);
             if (kitProduct.PriceMode == InheritanceMode.Inherit)
             {
                 kitProduct.Price = pcalc.Price;
             }
             else
             {
                 kitProduct.Price = AlwaysConvert.ToDecimal(Price.Text);
             }
             kitProduct.WeightModeId = AlwaysConvert.ToByte(WeightMode.SelectedIndex);
             if (kitProduct.WeightMode == InheritanceMode.Inherit)
             {
                 kitProduct.Weight = pcalc.Weight;
             }
             else
             {
                 kitProduct.Weight = AlwaysConvert.ToDecimal(Weight.Text);
             }
             kitProduct.IsSelected = IsSelected.Checked;
             kitProduct.Save();
         }
     }
     Response.Redirect(string.Format("EditKit.aspx?CategoryId={0}&ProductId={1}", _CategoryId, _ProductId));
 }
示例#20
0
        public void Calculate_ArgsGiven_CorretResult()
        {
            ProductCalculator sut = new ProductCalculator();

            Assert.AreEqual(12, sut.Calculate(3, 4));
        }
        /// <summary>
        /// Gets the order items that would result from the addition of the given product to an order.
        /// </summary>
        /// <param name="productId">The id of the product to add.</param>
        /// <param name="quantity">The quantity of the product to add.</param>
        /// <param name="optionList">List of option choice ids if this is a variant</param>
        /// <param name="kitList">List of kit products if it is a Kit</param>
        /// <returns>The order items that would result from the addition of the given product to an order</returns>
        public static List <OrderItem> CreateForProduct(int productId, short quantity, string optionList, string kitList)
        {
            List <OrderItem> orderItems = new List <OrderItem>();
            Product          product    = ProductDataSource.Load(productId);

            if (product != null)
            {
                //CREATE THE BASE ORDER ITEM
                OrderItem baseItem = new OrderItem();
                baseItem.Name          = product.Name;
                baseItem.OrderItemType = OrderItemType.Product;
                baseItem.ProductId     = productId;
                baseItem.TaxCodeId     = product.TaxCodeId;
                baseItem.Quantity      = quantity;
                baseItem.ShippableId   = product.ShippableId;
                //CALCULATE THE PRICE OF THE PRODUCT
                ProductCalculator pcalc = ProductCalculator.LoadForProduct(productId, quantity, optionList, kitList);
                baseItem.Sku    = pcalc.Sku;
                baseItem.Price  = pcalc.Price;
                baseItem.Weight = pcalc.Weight;
                //CHECK PRODUCT VARIANT
                ProductVariant variant = ProductVariantDataSource.LoadForOptionList(productId, optionList);
                if (variant != null)
                {
                    baseItem.OptionList  = optionList;
                    baseItem.VariantName = variant.VariantName;
                }
                //CHECK FOR DIGITAL GOODS
                foreach (ProductDigitalGood dg in product.DigitalGoods)
                {
                    if (dg.DigitalGood != null && (String.IsNullOrEmpty(baseItem.OptionList) || baseItem.OptionList == dg.OptionList))
                    {
                        OrderItemDigitalGood oidg = new OrderItemDigitalGood();
                        oidg.OrderItemId   = baseItem.OrderItemId;
                        oidg.DigitalGoodId = dg.DigitalGoodId;
                        oidg.Name          = dg.DigitalGood.Name;
                        baseItem.DigitalGoods.Add(oidg);
                    }
                }
                orderItems.Add(baseItem);

                //CHECK FOR KIT ITEMS
                int[] kitProductIds = AlwaysConvert.ToIntArray(kitList);
                if (kitProductIds != null && kitProductIds.Length > 0)
                {
                    LSDecimal baseItemPrice  = baseItem.Price;
                    LSDecimal baseItemWeight = baseItem.Weight;
                    foreach (int kitProductId in kitProductIds)
                    {
                        KitProduct kitProduct = KitProductDataSource.Load(kitProductId);
                        if (kitProduct != null)
                        {
                            OrderItem kitItem = new OrderItem();
                            kitItem.Name          = kitProduct.DisplayName;
                            kitItem.OrderItemType = OrderItemType.Product;
                            kitItem.ParentItemId  = baseItem.OrderItemId;
                            kitItem.ProductId     = kitProduct.ProductId;
                            kitItem.OptionList    = kitProduct.OptionList;
                            kitItem.Quantity      = (short)(kitProduct.Quantity * baseItem.Quantity);
                            kitItem.Sku           = kitProduct.Product.Sku;
                            kitItem.TaxCodeId     = kitProduct.Product.TaxCodeId;
                            kitItem.Price         = kitProduct.CalculatedPrice / kitProduct.Quantity;
                            kitItem.Weight        = kitProduct.CalculatedWeight / kitProduct.Quantity;
                            //CHECK FOR DIGITAL GOODS
                            foreach (DigitalGood dg in kitItem.Product.DigitalGoods)
                            {
                                OrderItemDigitalGood oidg = new OrderItemDigitalGood();
                                oidg.OrderItemId   = kitItem.OrderItemId;
                                oidg.DigitalGoodId = dg.DigitalGoodId;
                                kitItem.DigitalGoods.Add(oidg);
                            }
                            baseItemPrice  -= kitProduct.CalculatedPrice;
                            baseItemWeight -= kitProduct.CalculatedWeight;
                            orderItems.Add(kitItem);
                        }
                    }
                    baseItem.Price  = baseItemPrice;
                    baseItem.Weight = baseItemWeight;
                }
            }
            return(orderItems);
        }
示例#22
0
 protected void Page_PreRender(object sender, EventArgs e)
 {
     if (_Product != null)
     {
         if (!_Product.UseVariablePrice)
         {
             // UPDATE THE INCLUDED KITPRODUCTS (Included-Hidden and Included-Shown)
             string kitList = string.Empty;
             if (_SelectedKitProducts == null || _SelectedKitProducts.Count == 0)
             {
                 UpdateIncludedKitOptions();
                 kitList = AlwaysConvert.ToList(",", _SelectedKitProducts.ToArray());
             }
             ProductCalculator pcalc = ProductCalculator.LoadForProduct(_Product.Id, 1, _OptionList, kitList, 0);
             //IF REQUIRED MAKE ADJUSTMENTS TO DISPLAYED PRICE TO INCLUDE VAT
             decimal basePriceWithVAT = TaxHelper.GetShopPrice(_Product.Price, (_Product.TaxCode != null ? _Product.TaxCode.Id : 0));
             decimal priceWithVAT     = TaxHelper.GetShopPrice(pcalc.Price, (_Product.TaxCode != null ? _Product.TaxCode.Id : 0));
             decimal msrpWithVAT      = TaxHelper.GetShopPrice(_Product.MSRP, (_Product.TaxCode != null ? _Product.TaxCode.Id : 0));
             if (!_Product.HidePrice)
             {
                 //PRICE IS VISIBLE, NO POPUP
                 phPricePopup.Visible = false;
                 //SHOW RETAIL PRICE IF INDICATED
                 if (_ShowRetailPrice && msrpWithVAT > 0 && !_Product.UseVariablePrice)
                 {
                     RetailPrice1.Text = string.Format(_RetailPriceFormat, msrpWithVAT.LSCurrencyFormat("lc"));
                 }
                 else
                 {
                     RetailPrice1.Text = string.Empty;
                 }
                 //SHOW THE PRICE
                 if (pcalc.AppliedSpecial != null && pcalc.AppliedSpecial.EndDate != DateTime.MinValue)
                 {
                     // SHOW THE BASE PRICE AND SPECIAL PRICE
                     RetailPrice1.Text = string.Format(_BasePriceFormat, basePriceWithVAT.LSCurrencyFormat("lc"));
                     Price.Text        = string.Format(_SpecialPriceFormat, priceWithVAT.LSCurrencyFormat("lc"), pcalc.AppliedSpecial.EndDate);
                 }
                 else
                 {
                     Price.Text = string.Format(_PriceFormat, priceWithVAT.LSCurrencyFormat("lc"));
                 }
             }
             else
             {
                 // HIDDEN PRICE, USE POPUP
                 Price.Visible    = false;
                 ProductName.Text = _Product.Name;
                 // THESE VARIABLES WILL TRACK SAVINGS OFF LISTED OR REGULAR PRICE
                 decimal amountSaved  = 0;
                 decimal percentSaved = 0;
                 // DETERMINE IF A SALE OR SPECIAL PRICE IS APPLIED
                 bool salePriceEffective = (pcalc.AppliedSpecial != null && pcalc.AppliedSpecial.EndDate != DateTime.MinValue);
                 // DETERMINE IF MSRP IS AVAILABLE FOR DISPLAY
                 if (_ShowRetailPrice && msrpWithVAT > 0 && !salePriceEffective)
                 {
                     trRetailPrice.Visible       = true;
                     HiddenRetailPriceLabel.Text = PopupRetailPriceLabel;
                     HiddenRetailPrice.Text      = string.Format(PopupRetailPriceFormat, msrpWithVAT.LSCurrencyFormat("lc"));
                     // CALCULATE AMOUNT SAVED OVER MSRP
                     amountSaved  = (msrpWithVAT - priceWithVAT);
                     percentSaved = ((decimal)(amountSaved / msrpWithVAT)) * 100;
                 }
                 else
                 {
                     trRetailPrice.Visible = false;
                 }
                 // CHECK IF A SALE PRICE IS APPLIED
                 if (salePriceEffective)
                 {
                     // SPECIAL APPLIED, SHOW THE PRODUCT BASE PRICE AND THE SPECIAL PRICE
                     trSpecialPrice.Visible = true;
                     HiddenPriceLabel.Text  = PopupBasePriceLabel;
                     HiddenPrice.Text       = string.Format(PopupBasePriceFormat, basePriceWithVAT.LSCurrencyFormat("lc"));
                     SpecialPriceLabel.Text = PopupSpecialPriceLabel;
                     SpecialPrice.Text      = string.Format(PopupSpecialPriceFormat, priceWithVAT.LSCurrencyFormat("lc"), pcalc.AppliedSpecial.EndDate);
                     // CALCULATE AMOUNT SAVED WITH SALE PRICE
                     amountSaved  = (basePriceWithVAT - priceWithVAT);
                     percentSaved = ((decimal)(amountSaved / basePriceWithVAT)) * 100;
                 }
                 else
                 {
                     // NO SPECIAL, SO JUST SHOW THE CALCULATED PRICE
                     HiddenPriceLabel.Text = PopupPriceLabel;
                     HiddenPrice.Text      = string.Format(PopupPriceFormat, priceWithVAT.LSCurrencyFormat("lc"));
                 }
                 // SEE IF WE HAVE AN AMOUNT SAVED VALUE
                 if (amountSaved > 0)
                 {
                     trAmountSaved.Visible = true;
                     AmountSavedLabel.Text = PopupAmountSavedLabel;
                     AmountSaved.Text      = string.Format(PopupAmountSavedFormat, amountSaved.LSCurrencyFormat("lc"), percentSaved);
                 }
                 else
                 {
                     trAmountSaved.Visible = false;
                 }
                 //DO NOT GIVE ADD BUTTON FOR KITTED PRODUCTS
                 //AddToCartButton.Visible = (_Product.KitStatus != KitStatus.Master);
             }
         }
         else
         {
             //DO NOT DISPLAY THIS CONTROL IF THE PRODUCT HAS VARIABLE PRICE
             this.Controls.Clear();
             Label lbl = new Label();
             lbl.Text = "Variable";
             this.Controls.Add(lbl);
         }
     }
     else
     {
         //DO NOT DISPLAY THIS CONTROL IF THE PRODUCT IS UNAVAILABLE
         this.Controls.Clear();
     }
     SaveCustomViewState();
 }
示例#23
0
        private static IList <Variant> GetAvailableVariants(Product product)
        {
            IList <Variant> variants = new List <Variant>();
            List <Option>   relatedOptions = new List <Option>();
            int             lastIndex = -1, colorOptionIndex = -1, sizeOptionIndex = -1, materialOptionIndex = -1, patternOptionIndex = -1;
            Option          colorOption = null, sizeOption = null, materialOption = null, patternOption = null;
            string          optionListPattern = string.Empty;

            if (product.ProductOptions.Count > 0)
            {
                // check variants and options
                IList <ProductOption> options = product.ProductOptions;
                foreach (ProductOption pOption in options)
                {
                    if (!string.IsNullOrEmpty(optionListPattern))
                    {
                        optionListPattern += ",";
                    }
                    string optionName = pOption.Option.Name.ToLowerInvariant();

                    if (optionName == "color")
                    {
                        colorOption = pOption.Option; colorOptionIndex = ++lastIndex; relatedOptions.Add(colorOption); optionListPattern += "{C}";
                    }
                    else if (optionName == "size")
                    {
                        sizeOption = pOption.Option; sizeOptionIndex = ++lastIndex; relatedOptions.Add(sizeOption); optionListPattern += "{S}";
                    }
                    else if (optionName == "material")
                    {
                        materialOption = pOption.Option; materialOptionIndex = ++lastIndex; relatedOptions.Add(materialOption); optionListPattern += "{M}";
                    }
                    else if (optionName == "pattern")
                    {
                        patternOption = pOption.Option; patternOptionIndex = ++lastIndex; relatedOptions.Add(patternOption); optionListPattern += "{P}";
                    }
                    else
                    {
                        optionListPattern += "0";  // fill the options list pattern with zero
                    }
                }
            }

            if (relatedOptions.Count > 0)
            {
                Store  store    = AbleContext.Current.Store;
                string storeUrl = store.StoreUrl;
                if (!storeUrl.EndsWith("/"))
                {
                    storeUrl += "/";
                }

                // calculate all valid combinations using the option choices
                List <int[]>          choiceCombinations = GetAllChoicesCombinations(relatedOptions);
                ProductVariantManager variantManager     = new ProductVariantManager(product.Id);
                IList <string>        imageUrlList       = new List <string>(); // require to keep track of unique images for variants

                foreach (int[] choicesCombination in choiceCombinations)
                {
                    // collect the choice id values
                    int colorChoiceId = 0, sizeChoiceId = 0, materialChoiceId = 0, patternChoiceId = 0;
                    if (colorOptionIndex >= 0)
                    {
                        colorChoiceId = choicesCombination[colorOptionIndex];
                    }
                    if (sizeOptionIndex >= 0)
                    {
                        sizeChoiceId = choicesCombination[sizeOptionIndex];
                    }
                    if (materialOptionIndex >= 0)
                    {
                        materialChoiceId = choicesCombination[materialOptionIndex];
                    }
                    if (patternOptionIndex >= 0)
                    {
                        patternChoiceId = choicesCombination[patternOptionIndex];
                    }

                    // build option list, fill the color, size, material, and pattern choice id values while for rest of options fill in zero value
                    string optionList = optionListPattern;
                    optionList = optionList.Replace("{C}", colorChoiceId.ToString());
                    optionList = optionList.Replace("{S}", sizeChoiceId.ToString());
                    optionList = optionList.Replace("{M}", materialChoiceId.ToString());
                    optionList = optionList.Replace("{P}", patternChoiceId.ToString());

                    ProductVariant productVariant = variantManager.GetVariantFromOptions(optionList);
                    if (productVariant != null)
                    {
                        // check availability
                        if (!productVariant.Available)
                        {
                            continue;
                        }

                        Variant variant = new Variant();
                        variant.Product = product;

                        string variantNamePart    = string.Empty;
                        string variantoptionsList = string.Empty;

                        if (colorChoiceId > 0)
                        {
                            variant.Color       = EntityLoader.Load <OptionChoice>(colorChoiceId).Name;
                            variantNamePart    += string.IsNullOrEmpty(variantNamePart) ? variant.Color : "," + variant.Color;
                            variantoptionsList += string.IsNullOrEmpty(variantoptionsList) ? colorChoiceId.ToString() : "," + colorChoiceId.ToString();
                        }
                        if (sizeChoiceId > 0)
                        {
                            variant.Size        = EntityLoader.Load <OptionChoice>(sizeChoiceId).Name;
                            variantNamePart    += string.IsNullOrEmpty(variantNamePart) ? variant.Size : "," + variant.Size;
                            variantoptionsList += string.IsNullOrEmpty(variantoptionsList) ? sizeChoiceId.ToString() : "," + sizeChoiceId.ToString();
                        }
                        if (materialChoiceId > 0)
                        {
                            variant.Material    = EntityLoader.Load <OptionChoice>(materialChoiceId).Name;
                            variantNamePart    += string.IsNullOrEmpty(variantNamePart) ? variant.Material : "," + variant.Material;
                            variantoptionsList += string.IsNullOrEmpty(variantoptionsList) ? materialChoiceId.ToString() : "," + materialChoiceId.ToString();
                        }
                        if (patternChoiceId > 0)
                        {
                            variant.Pattern     = EntityLoader.Load <OptionChoice>(patternChoiceId).Name;
                            variantNamePart    += string.IsNullOrEmpty(variantNamePart) ? variant.Pattern : "," + variant.Pattern;
                            variantoptionsList += string.IsNullOrEmpty(variantoptionsList) ? patternChoiceId.ToString() : "," + patternChoiceId.ToString();
                        }

                        variant.Name = string.Format("{0} - {1}", product.Name, variantNamePart);
                        variant.Link = ResolveUrl(product.NavigateUrl, storeUrl) + string.Format("?Options={0}", variantoptionsList);

                        // WE CAN ONLY USE ALPHANUMERIC CHARACTERS FOR ID, CREATE ID VALUE USING THE APAREL OPTIONS
                        // [Product_Id]C[COLOR_CHOICE_ID]S[SIZE_CHOICE_ID]M[MATERIAL_CHOICE_ID]P[PATTERN_CHOICE_ID]
                        variant.Id = string.Format("{0}C{1}S{2}M{3}P{4}",
                                                   product.Id,
                                                   (colorOptionIndex > -1 ? colorChoiceId.ToString() : string.Empty),
                                                   (sizeOptionIndex > -1 ? sizeChoiceId.ToString() : string.Empty),
                                                   (materialOptionIndex > -1 ? materialChoiceId.ToString() : string.Empty),
                                                   (patternOptionIndex > -1 ? patternChoiceId.ToString() : string.Empty));

                        // VERIFY UNIQUE IMAGE LINK CONSIDERING FOLLOWING GOOGLE FEED REQUIREMENTS
                        // For products that fall under “Apparel & Accessories” and all corresponding sub-categories in feeds targeting the US, UK, DE, FR, and JP:
                        // If you are submitting product variants that differ in ‘‘color’, or ‘pattern’, or ‘material’,
                        // we require you to submit specific images corresponding to each of these variants.
                        // If you do not have the correct image for the variation of the product, you may not submit that variant.
                        // We recommend specific images for ‘size’ variants too. However, if these are not available you may submit the same image URL for items that differ in ‘size’.
                        string imageUrl = string.Empty;
                        if (!string.IsNullOrEmpty(productVariant.ImageUrl))
                        {
                            imageUrl = productVariant.ImageUrl.ToLowerInvariant();
                        }
                        if (string.IsNullOrEmpty(imageUrl) && !string.IsNullOrEmpty(product.ImageUrl))
                        {
                            imageUrl = product.ImageUrl.ToLowerInvariant();                                                                            // use product image if no image
                        }
                        if (string.IsNullOrEmpty(imageUrl))
                        {
                            continue;                                 // skip if no image
                        }
                        if (!IsAbsoluteURL(imageUrl))
                        {
                            imageUrl = ResolveUrl(imageUrl, storeUrl);
                        }

                        // verify unique image for each combination of ‘color’, ‘pattern’, and ‘material’
                        if (imageUrlList.Contains(imageUrl))
                        {
                            bool isUniqueImage = true;
                            // MAKE SURE OTHER VARIANTS ONLY DIFFER BY SIZE, OTHERWISE SKIP THIS
                            foreach (Variant otherVariant in variants)
                            {
                                if (imageUrl == otherVariant.ImageUrl)
                                {
                                    if (!(variant.Color == otherVariant.Color &&
                                          variant.Pattern == otherVariant.Pattern &&
                                          variant.Material == otherVariant.Material &&
                                          variant.Size != otherVariant.Size))
                                    {
                                        isUniqueImage = false;
                                        break;
                                    }
                                }
                            }
                            // SKIP THIS VARIANT, AS WE DO NOT HAVE A UNIQUE IMAGE FOR THIS VARIANT AS THIS IMAGE ALREADY USED FOR ANOTHER VARIANT, WHICH DIFFERS FOR MORE THEN SIZE
                            if (!isUniqueImage)
                            {
                                continue;
                            }
                        }

                        // else add to variant image dictionary to keep track of rest of variants
                        imageUrlList.Add(imageUrl);
                        variant.ImageUrl = imageUrl;

                        // use product id as item group id, this must be same for all variants of same product, but must be unique for variants of each product
                        variant.ItemGroupId = product.Id.ToString();

                        ProductCalculator productCalculator = ProductCalculator.LoadForProduct(product.Id, 1, productVariant.OptionList, string.Empty, 0);
                        variant.Weight = productCalculator.Weight;
                        variant.Price  = productCalculator.Price;
                        variant.Sku    = productCalculator.Sku;

                        string gtin = productVariant.GTIN;
                        if (string.IsNullOrEmpty(gtin))
                        {
                            // for compatibility with AC7 data check if SKU is a UPC
                            gtin = IsUpcCode(productVariant.Sku) ? productVariant.Sku : string.Empty;
                        }
                        variant.GTIN        = gtin;
                        variant.ModelNumber = productVariant.ModelNumber;
                        variant.InStock     = productVariant.InStock;
                        variants.Add(variant);
                    }
                }
            }

            return(variants);
        }
        /// <summary>
        /// Recalculates all items in the basket, for example price and kit member products
        /// </summary>
        internal void Recalculate()
        {
            // BUILD A LIST OF ANY CHILD (GENERATED) PRODUCTS
            List <int>        childItemIds  = new List <int>();
            List <BasketItem> childProducts = new List <BasketItem>();

            foreach (BasketItem item in this)
            {
                if (item.OrderItemType == OrderItemType.Product && item.IsChildItem)
                {
                    childItemIds.Add(item.BasketItemId);
                    childProducts.Add(item);
                }
            }

            // MOVE THROUGH THE COLLECTION AND REMOVE ANY ITEMS ASSOCIATED WITH A CHILD ITEM
            for (int i = this.Count - 1; i >= 0; i--)
            {
                BasketItem item      = this[i];
                List <int> childPath = item.GetPath();
                if (IsChildItemInPath(childItemIds, childPath))
                {
                    if (item.OrderItemType == OrderItemType.Product)
                    {
                        this.RemoveAt(i);
                    }
                    else
                    {
                        this.DeleteAt(i);
                    }
                }
            }

            // LOOP EACH REMAINING ITEM AND RECALCULATE
            int currentCount = this.Count;

            for (int i = 0; i < currentCount; i++)
            {
                BasketItem basketItem = this[i];
                Basket     basket     = basketItem.Basket;
                int        userId     = (basket == null ? Token.Instance.UserId : basket.UserId);

                // WE ONLY NEED TO CHECK PRODUCTS, NON-PRODUCT ITEMS HAVE NO RECALCULATION TASKS
                if (basketItem.OrderItemType == OrderItemType.Product)
                {
                    // IF WE HAVE A KIT, WE MUST REFRESH ANY CONFIGURED KIT OPTIONS
                    bool isKit = (basketItem.Product.KitStatus == KitStatus.Master);
                    if (isKit)
                    {
                        basketItem.KitList = basketItem.Product.Kit.RefreshKitProducts(basketItem.KitList);
                    }

                    // RECALCULATE THE STARTING SKU/PRICE/WEIGHT FOR THIS ITEM
                    ProductCalculator pcalc = ProductCalculator.LoadForProduct(basketItem.ProductId, basketItem.Quantity, basketItem.OptionList, basketItem.KitList, userId);
                    basketItem.Sku    = pcalc.Sku;
                    basketItem.Weight = pcalc.Weight;
                    if (isKit || !basketItem.Product.UseVariablePrice)
                    {
                        // KITS AND NONVARIABLE PRICED PRODUCTS MUST HAVE PRICE RECALCULATED
                        basketItem.Price = pcalc.Price;
                    }
                    basketItem.Save();

                    // REGENERATE THE KIT ITEMS FOR THIS ITEM
                    if (basket != null && isKit)
                    {
                        // OBTAIN THE KIT PRODUCTS THAT ARE SELECTED RATHER THAN INCLUDED
                        int[] kitProductIds = AlwaysConvert.ToIntArray(basketItem.KitList);
                        if (kitProductIds != null && kitProductIds.Length > 0)
                        {
                            //keep track of the price/weight of the master line item
                            //decrement these values for each line item registered
                            LSDecimal masterPrice  = basketItem.Price;
                            LSDecimal masterWeight = basketItem.Weight;
                            foreach (int kitProductId in kitProductIds)
                            {
                                KitProduct kitProduct = KitProductDataSource.Load(kitProductId);
                                if (kitProduct != null && kitProduct.KitComponent.InputType != KitInputType.IncludedHidden)
                                {
                                    // WE WANT TO GENERATE BASKET RECORDS FOR ALL ITEMS *EXCEPT* INCLUDED HIDDEN ITEMS
                                    // INCLUDED HIDDEN ITEMS ARE TREATED AS PART OF THE MAIN PRODUCT AND ARE NOT GENERATED
                                    // UNTIL THE ORDER IS FINALIZED
                                    Product    product    = kitProduct.Product;
                                    BasketItem searchItem = new BasketItem();
                                    searchItem.BasketId         = basket.BasketId;
                                    searchItem.OrderItemType    = OrderItemType.Product;
                                    searchItem.ParentItemId     = basketItem.BasketItemId;
                                    searchItem.ProductId        = product.ProductId;
                                    searchItem.OptionList       = kitProduct.OptionList;
                                    searchItem.BasketShipmentId = basketItem.BasketShipmentId;

                                    // LOOK FOR ITEM
                                    BasketItem childItem = FindChildProduct(childProducts, searchItem);

                                    // UPDATE CALCULATED PROPERTIES
                                    childItem.Name      = kitProduct.DisplayName;
                                    childItem.Quantity  = (short)(kitProduct.Quantity * basketItem.Quantity);
                                    childItem.TaxCodeId = product.TaxCodeId;
                                    childItem.Shippable = product.Shippable;
                                    childItem.Price     = kitProduct.CalculatedPrice / kitProduct.Quantity;;
                                    childItem.Weight    = kitProduct.CalculatedWeight / kitProduct.Quantity;
                                    // CALCULATE SKU
                                    ProductCalculator childCalc = ProductCalculator.LoadForProduct(childItem.ProductId, childItem.Quantity, childItem.OptionList, childItem.KitList, basket.UserId);
                                    childItem.Sku = childCalc.Sku;

                                    basket.Items.Add(childItem);
                                    childItem.Save();
                                    masterPrice  -= kitProduct.CalculatedPrice;
                                    masterWeight -= kitProduct.CalculatedWeight;
                                }
                            }

                            // UPDATE MASTER PRICE, FACTORING IN CHILD ITEMS
                            basketItem.Price  = masterPrice;
                            basketItem.Weight = masterWeight;
                            basketItem.Save();
                        }
                    }
                }
            }

            // DELETE ANY CHILD PRODUCTS THAT WERE NOT PRESERVED
            foreach (BasketItem bi in childProducts)
            {
                bi.Delete();
            }
        }
        protected void AddProductPrice_PreRender(object sender, EventArgs e)
        {
            int     productId = AlwaysConvert.ToInt(AddProductId.Value);
            Product product   = ProductDataSource.Load(productId);

            if (product != null)
            {
                //GET THE SELECTED KIT OPTIONS
                GetSelectedKitOptions(product);
                //SET THE CURRENT CALCULATED PRICE
                string            optionList            = ProductVariantDataSource.GetOptionList(productId, _SelectedOptions, true);
                bool              calculateOneTimePrice = AlwaysConvert.ToBool(OptionalSubscription.SelectedValue, false);
                ProductCalculator pcalc = ProductCalculator.LoadForProduct(productId, 1, optionList, AlwaysConvert.ToList(",", _SelectedKitProducts), _UserId, false, calculateOneTimePrice);
                AddProductPrice.Text = string.Format("{0:F2}", pcalc.Price);

                if (product.IsSubscription)
                {
                    if (product.SubscriptionPlan.IsRecurring)
                    {
                        if (!calculateOneTimePrice)
                        {
                            short frequency = product.SubscriptionPlan.PaymentFrequencyType == PaymentFrequencyType.Optional ? AlwaysConvert.ToInt16(AutoDeliveryInterval.SelectedValue) : product.SubscriptionPlan.PaymentFrequency;
                            SubscriptionMessage.Text    = ProductHelper.GetRecurringPaymentMessage(product.Price, 0, product.SubscriptionPlan, frequency);
                            SubscriptionMessage.Visible = true;
                        }
                        else
                        {
                            SubscriptionMessage.Visible = false;
                        }
                    }
                    else
                    {
                        trSubscriptionRow.Visible = product.SubscriptionPlan.IsOptional;
                    }
                }
                else
                {
                    trSubscriptionRow.Visible = false;
                }

                if (product.UseVariablePrice && !product.IsSubscription && !product.IsKit)
                {
                    AddProductVariablePrice.Text    = string.Format("{0:F2}", pcalc.Price);
                    AddProductVariablePrice.Visible = true;
                    string varPriceText = string.Empty;
                    if (product.MinimumPrice > 0)
                    {
                        if (product.MaximumPrice > 0)
                        {
                            varPriceText = string.Format("(between {0} and {1})", product.MinimumPrice.LSCurrencyFormat("lcf"), product.MaximumPrice.LSCurrencyFormat("lcf"));
                        }
                        else
                        {
                            varPriceText = string.Format("(at least {0})", product.MinimumPrice.LSCurrencyFormat("lcf"));
                        }
                    }
                    else if (product.MaximumPrice > 0)
                    {
                        varPriceText = string.Format("({0} maximum)", product.MaximumPrice.LSCurrencyFormat("lcf"));
                    }
                    phVariablePrice.Controls.Add(new LiteralControl(varPriceText));
                }
                AddProductPrice.Visible = !AddProductVariablePrice.Visible;
                if ((AddProductPrice.Visible && _Basket.UserId == AbleContext.Current.UserId) || (product.IsKit))
                {
                    AddProductPrice.Enabled = false;
                }
            }
        }
示例#26
0
        /// <summary>
        /// Gets feed data for a batch of products
        /// </summary>
        /// <param name="products">the batch of products</param>
        /// <param name="defaultBrand">Default brand to use if none is set for a product</param>
        /// <param name="defaultCategory">Default category to use if none is set for a product</param>
        /// <returns>Feed data for the batch of products</returns>
        private static string GetFeedData(IList <Product> products, string defaultBrand, string defaultCategory)
        {
            Store  store    = AbleContext.Current.Store;
            string storeUrl = store.StoreUrl;

            if (!storeUrl.EndsWith("/"))
            {
                storeUrl += "/";
            }
            string googleWeightUnit = GetGoogleWeightUnit(store.WeightUnit);

            using (StringWriter feedWriter = new StringWriter())
            {
                foreach (Product product in products)
                {
                    IList <Variant> variants = new List <Variant>();

                    // prepare variables that need logic applied
                    string desc           = StringHelper.CleanupSpecialChars(product.Summary);
                    string condition      = string.IsNullOrEmpty(product.Condition) ? "new" : product.Condition;
                    string brand          = product.Manufacturer != null ? product.Manufacturer.Name : defaultBrand;
                    string modelNumber    = string.IsNullOrEmpty(product.ModelNumber) ? product.Sku : product.ModelNumber;
                    string productType    = GetProductType(product);
                    string googleCategory = string.IsNullOrEmpty(product.GoogleCategory) ? defaultCategory : product.GoogleCategory;

                    // check if we need to export product variants, for this we first need to check product google category.
                    // Variant-level information is required only for products in the “'Apparel & Accessories' category,
                    // and all related subcategories. Apparel variants are only required for feeds targeting the US, UK, DE, FR, and JP.
                    // For feeds targeting other countries, the attributes are recommended and may be required in the future.
                    bool isApparelProduct = googleCategory.Trim().StartsWith("apparel & accessories", StringComparison.InvariantCultureIgnoreCase);
                    if (isApparelProduct && product.PublishFeedAsVariants)
                    {
                        variants = GetAvailableVariants(product);
                    }

                    // if there are variants to export
                    if (variants.Count > 0)
                    {
                        foreach (Variant variant in variants)
                        {
                            // generate the feed line
                            // basic product information (id, title, description, google_product_category, product_type, link, image_link, condition)
                            string        availability       = GetAvailability(product, variant);
                            string        variantModelNumber = string.IsNullOrEmpty(variant.ModelNumber) ? variant.Sku : variant.ModelNumber;
                            StringBuilder feedLine           = new StringBuilder();
                            feedLine.Append(variant.Id + "\t");
                            feedLine.Append(StringHelper.CleanupSpecialChars(variant.Name) + "\t");
                            feedLine.Append(desc + "\t");
                            feedLine.Append(googleCategory + "\t");
                            feedLine.Append(productType + "\t");
                            feedLine.Append(variant.Link + "\t");
                            feedLine.Append(variant.ImageUrl + "\t");
                            feedLine.Append(condition + "\t");

                            // availability and price (availability, price)
                            feedLine.Append(availability + "\t");
                            feedLine.Append(string.Format("{0:F2}", variant.Price) + "\t");

                            // unique product identifiers (brand, gtin, mpn)
                            feedLine.Append(brand + "\t");
                            feedLine.Append(variant.GTIN + "\t");
                            feedLine.Append(variantModelNumber + "\t");

                            // apparel products (gender, age_group)
                            feedLine.Append(product.Gender + "\t");
                            feedLine.Append(product.AgeGroup + "\t");

                            // variants (item_group_id, color, size, material, pattern)
                            feedLine.Append(variant.ItemGroupId + "\t");
                            feedLine.Append(variant.Color + "\t");
                            feedLine.Append(variant.Size + "\t");
                            feedLine.Append(variant.Material + "\t");
                            feedLine.Append(variant.Pattern + "\t");

                            // Adwords
                            feedLine.Append(product.AdwordsGrouping + "\t");
                            feedLine.Append(product.AdwordsLabels + "\t");
                            feedLine.Append(product.ExcludedDestination.ToString() + "\t");
                            feedLine.Append(product.AdwordsRedirect + "\t");

                            // tax and shipping (shipping_weight)
                            feedLine.Append(string.Format("{0:F2} {1}", variant.Weight, googleWeightUnit));
                            feedWriter.WriteLine(feedLine.ToString());
                        }
                    }
                    else
                    {
                        // prepare variables that need logic applied
                        string availability = GetAvailability(product);
                        string name         = StringHelper.CleanupSpecialChars(product.Name);
                        string url          = ResolveUrl(product.NavigateUrl, storeUrl);
                        string imgurl       = product.ImageUrl;
                        if (!string.IsNullOrEmpty(imgurl) && !IsAbsoluteURL(imgurl))
                        {
                            imgurl = ResolveUrl(imgurl, storeUrl);
                        }
                        string gtin = product.GTIN;
                        if (string.IsNullOrEmpty(gtin))
                        {
                            // for compatibility with AC7 data check if SKU is a UPC
                            gtin = IsUpcCode(product.Sku) ? product.Sku : string.Empty;
                        }

                        // generate the feed line
                        // basic product information (id, title, description, google_product_category, product_type, link, image_link, condition)
                        StringBuilder feedLine = new StringBuilder();
                        feedLine.Append(product.Id + "\t");
                        feedLine.Append(name + "\t");
                        feedLine.Append(desc + "\t");
                        feedLine.Append(googleCategory + "\t");
                        feedLine.Append(productType + "\t");
                        feedLine.Append(url + "\t");
                        feedLine.Append(imgurl + "\t");
                        feedLine.Append(condition + "\t");

                        // availability and price (availability, price)
                        decimal           price       = product.Price;
                        ProductCalculator pcalculator = ProductCalculator.LoadForProduct(product.Id, 1, string.Empty, string.Empty, 0, false);
                        if (pcalculator != null)
                        {
                            price = pcalculator.Price;
                        }
                        feedLine.Append(availability + "\t");
                        feedLine.Append(string.Format("{0:F2}", price) + "\t");

                        // unique product identifiers (brand, gtin, mpn)
                        feedLine.Append(brand + "\t");
                        feedLine.Append(gtin + "\t");
                        feedLine.Append(modelNumber + "\t");

                        // apparel products (gender, age_group)
                        feedLine.Append(product.Gender + "\t");
                        feedLine.Append(product.AgeGroup + "\t");

                        // variants (item_group_id, color, size, material, pattern)
                        feedLine.Append(string.Empty + "\t");
                        feedLine.Append(product.Color + "\t");
                        feedLine.Append(product.Size + "\t");
                        feedLine.Append(string.Empty + "\t");
                        feedLine.Append(string.Empty + "\t");

                        // Adwords
                        feedLine.Append(product.AdwordsGrouping + "\t");
                        feedLine.Append(product.AdwordsLabels + "\t");
                        feedLine.Append(product.ExcludedDestination.ToString() + "\t");
                        feedLine.Append(product.AdwordsRedirect + "\t");

                        // tax and shipping (shipping_weight)
                        feedLine.Append(string.Format("{0:F2} {1}", product.Weight, googleWeightUnit));
                        feedWriter.WriteLine(feedLine.ToString());
                    }
                }

                string returnData = feedWriter.ToString();
                feedWriter.Close();
                return(returnData);
            }
        }