public void ApplyTotalDiscountRule_ValidDiscount(int numDevices, decimal amount, decimal expectedDiscount) { decimal discount = DiscountHelper.ApplyTotalDiscountRule(numDevices, amount); Assert.Equal(expectedDiscount, discount); }
public PriceCalculatorTest() { var discountConfig = GetTestDiscountConfig(); var rules = DiscountHelper.GetDiscountRuleFromConfig(discountConfig); _calculator = new PriceCalculator(rules); }
public void OldPriceNullTest() { decimal? oldPrice = null; const decimal price = 2000.00m; const int actual = 0; var discount = DiscountHelper.CalculateDiscount(price, oldPrice); Assert.AreEqual(discount, actual); }
public void DiscountsFractionalTest1() { decimal? oldPrice = 1856.00m; const decimal price = 1324.00m; const int actual = 28; var discount = DiscountHelper.CalculateDiscount(price, oldPrice); Assert.AreEqual(discount, actual); }
public void DiscountsIntegerTest() { decimal? oldPrice = 1000.00m; const decimal price = 800.00m; const int actual = 20; var discount = DiscountHelper.CalculateDiscount(price, oldPrice); Assert.AreEqual(discount, actual); }
public void DiscountsFractionalTest2() { decimal? oldPrice = 1248.34m; const decimal price = 793.65m; const int actual = 36; var discount = DiscountHelper.CalculateDiscount(price, oldPrice); Assert.AreEqual(discount, actual); }
public ActionResult AddFoodToCart(String FoodID, String Size) { List <OrderDetail> mycart = (List <OrderDetail>)Session[CART_STRING]; if (mycart == null) { mycart = new List <OrderDetail>(); } OrderDetail item = new OrderDetail { FoodID = FoodID, Size = Size }; if (mycart.Exists(o => o.FoodID == FoodID && o.Size == Size)) { //plus quantity with 1 int index = mycart.FindIndex(o => o.FoodID == item.FoodID && o.Size == item.Size); int oldquantity = mycart[index].Quantity; mycart[index].Quantity = oldquantity + 1; if (DiscountHelper.IsDiscountToday() && oldquantity % 2 == 1) { //discount if (Size == "S") { mycart[index].Discount += mycart[index].Dish.Price * 2 * 0.15; } else if (Size == "M") { mycart[index].Discount += mycart[index].Dish.Price * 2 * 0.25; } else if (Size == "L") { mycart[index].Discount += mycart[index].Dish.Price * 2 * 0.35; } } } else { using (PizzaExpressModel context = new PizzaExpressModel()) { //create new order detail by load some info //Debug.WriteLine("vao den doan lay tu DB"); var dish = context.Dishes.Include(d => d.Food).Single(d => d.FoodID == FoodID && d.Size == Size); //dish.Food = food; item.Dish = dish; item.Size = Size; item.Quantity = 1; mycart.Add(item); } } Session[CART_STRING] = mycart; return(Content("add to cart successfully, size of cart now is " + mycart.Count)); }
/// <summary> /// Computes a human-readable summary of discounts for each dependent /// </summary> /// <returns>Returns a human-readable summary of discounts for each dependent</returns> public List <string> BenefitsDiscountSummary() { var summaries = new List <string>(); foreach (var person in ProccessedDependents) { summaries.AddRange(DiscountHelper.BenefitsDiscountSummary(person)); } return(summaries); }
public void ApplyIndividualDiscountRule_NoDiscount(int year) { var deviceMock = new DeviceModel { Year = year }; decimal discount = DiscountHelper.ApplyIndividualDiscountRule(deviceMock); Assert.Equal(0.0m, discount); }
public void InitHelpers() { cartHelper = new CartHelper(driver); comparingHelper = new ComparingHelper(driver); discountHelper = new DiscountHelper(driver); filterHelper = new FilterHelper(driver); productCatalogHelper = new ProductCatalogHelper(driver); productListHelper = new ProductListHelper(driver); searchHelper = new SearchHelper(driver); sortingHelper = new SortingHelper(driver); }
public void GetValidConfigTest() { var _config = GetTestDiscountConfig(); var rules = DiscountHelper.GetDiscountRuleFromConfig(_config); Assert.IsType <List <IDiscountRule> >(rules); Assert.Equal(4, rules.Count); var firstRule = rules.First(); Assert.IsType <Discount10>(firstRule); Assert.Equal("Discount 10%", firstRule.AssignedName); }
public void ApplyIndividualDiscountRule_ValidDiscount(int year, decimal price, decimal expectedDiscount) { var deviceMock = new DeviceModel { Year = year, Price = price }; decimal discount = DiscountHelper.ApplyIndividualDiscountRule(deviceMock); Assert.Equal(expectedDiscount, discount); }
public ShoppingCart Sell <T>(T requestedItem, int quantity) where T : BaseItem { var discount = DiscountHelper.GetDiscount(quantity); return(new ShoppingCart { Item = requestedItem, PurchaseQuantity = quantity, PurchaseDiscount = discount, PurchaseAmount = requestedItem.Price * DiscountHelper.ApplyDiscount(discount) * quantity }); }
public void PercentageDiscount_CalculateAppliedDiscount_With50PercentDiscount() { // Arrange var percentageDiscount = new PercentageDiscount(DiscountHelper.CreateDiscountedProducts(), 0.50m); // Act var result = percentageDiscount.DiscountsApplicable(ProductQuantityHelper.CreateProducts()).ToArray(); // Assert Assert.AreEqual(result.Any(), true); Assert.AreEqual(result[0].Type, DiscountType.Percentage); Assert.AreEqual(result[0].Amount, 0.16m); Assert.AreEqual(result[0].Text, "Apples 50% OFF: - 16p"); }
public void Can_Sum_Product_Corretly() { //Arrange // Repository DiscountHelper repo = new DiscountHelper(); decimal ExpectedValue = products.Sum(m => m.price) + 0.9M; //Act //callin class LinqValueCalculator target = new LinqValueCalculator(repo); decimal ActualValue = target.ProductValue(products); //Assert Assert.AreEqual(ExpectedValue, ActualValue); }
// todo: centralize and test /// <summary> /// The discount value in cents, based on catalog information /// </summary> /// <param name="productId">The product unique identifier.</param> /// <returns></returns> public int GetDiscountAmountInCents(int productId = 0, OrderInfo order = null) { var product = DomainHelper.GetProductById(productId); var productPrice = 0; if (product != null) { if (product.Ranges != null && product.Ranges.Any()) { var range = product.Ranges.FirstOrDefault(x => x.From <= 1 && x.PriceInCents != 0); if (range != null) { productPrice = range.PriceInCents; } } else { //productPrice = product.Price.BeforeDiscount.ValueInCents; this doesn't work, because IsDiscounted will call this function, creating a loop } } if (order == null) { order = OrderHelper.GetOrder(); } var orderCount = 0; if (order != null) { orderCount = order.OrderLines.Select(l => l.ProductInfo).Where(p => p.OriginalId == productId).Sum(p => p.Quantity); } var discountValue = RangedDiscountValue(orderCount); if (DiscountType == DiscountType.NewPrice) { return(discountValue - productPrice); } if (DiscountType == DiscountType.Amount) { return(Math.Max(discountValue, productPrice)); } if (DiscountType == DiscountType.Percentage) { return(DiscountHelper.PercentageCalculation(discountValue, productPrice)); } return(0); }
public void ShoppingBasket_CheckCalculateTotalPrice_WithPercentageDiscount() { // Arrange var percentageDiscount = new Mock <IDiscount>(); percentageDiscount.Setup(mock => mock.DiscountsApplicable(It.IsAny <IEnumerable <ProductQuantity> >())) .Returns(DiscountHelper.CreatePercentageAppliedDiscount()); var shoppingBasket = new ShoppingBasket(new List <IDiscount> { percentageDiscount.Object }); shoppingBasket.AddProducts(ProductQuantityHelper.CreateProducts()); // Act var discountsTotal = shoppingBasket.GetBasketDiscounts().Sum(item => item.Amount); var result = shoppingBasket.SubTotal - discountsTotal; // Assert Assert.AreEqual(result, 3.20m); }
static void Main(string[] args) { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); IConfiguration config = builder.Build(); var discountConfig = new Discount(); config.GetSection("Discount").Bind(discountConfig); var discountRules = DiscountHelper.GetDiscountRuleFromConfig(discountConfig); var calculator = new PriceCalculator(discountRules); //due to important part is Price calculator model, so skip input args and validation here //assume all data is correct and invalid data will be reject before this Console.WriteLine("-- Start Calculate input"); Console.WriteLine("Test with 1 person, code DIS10, price 500"); var bestRule = calculator.GetBestRule(1, "DIS10", 500); if (!string.IsNullOrEmpty(bestRule.Name)) { Console.WriteLine("-Match with promotion : " + bestRule.Name.ToString()); Console.WriteLine("-Amount : " + bestRule.Price.ToString()); } Console.WriteLine("Test with 1 person, code STARCARD, price 2000"); bestRule = calculator.GetBestRule(1, "STARCARD", 2000); if (!string.IsNullOrEmpty(bestRule.Name)) { Console.WriteLine("-Match with promotion : " + bestRule.Name.ToString()); Console.WriteLine("-Amount : " + bestRule.Price.ToString()); } Console.WriteLine("Test with 2 person, code DIS10, price 1500"); bestRule = calculator.GetBestRule(2, "DIS10", 1500); if (!string.IsNullOrEmpty(bestRule.Name)) { Console.WriteLine("-Match with promotion : " + bestRule.Name.ToString()); Console.WriteLine("-Amount : " + bestRule.Price.ToString()); } Console.WriteLine("-- End Calculation"); }
/// <summary> /// Gets the adjusted price. /// </summary> /// <param name="discount">The discount.</param> /// <param name="priceBeforeDiscount">The price before discount.</param> /// <returns></returns> public static int GetAdjustedPrice(this IProductDiscount discount, int priceBeforeDiscount, int orderTotalItemCount = 0) { if (discount == null || discount.Type == DiscountType.FreeShipping) { return(priceBeforeDiscount); } var discountValue = discount.DiscountValue; // discount.RangedDiscountValue(orderTotalItemCount); if (discount.Type == DiscountType.Percentage) { return(priceBeforeDiscount - DiscountHelper.PercentageCalculation(priceBeforeDiscount, discountValue)); } if (discount.Type == DiscountType.Amount) { return(priceBeforeDiscount - discountValue); } if (discount.Type == DiscountType.NewPrice) { return(discountValue); } return(priceBeforeDiscount); }
public ActionResult DiscountRequestPost(string coupon) { DiscountCode discount = db.DiscountCodes.FirstOrDefault(current => current.Code == coupon); string result = CheckCouponValidation(discount); if (result != "true") { return(Json(result, JsonRequestBehavior.AllowGet)); } List <ProductInCart> productInCarts = GetProductInBasketByCoockie(); decimal subTotal = GetSubtotal(productInCarts); decimal total = subTotal; DiscountHelper helper = new DiscountHelper(); decimal discountAmount = helper.CalculateDiscountAmount(discount, total); SetDiscountCookie(discountAmount.ToString(), coupon); return(Json("true", JsonRequestBehavior.AllowGet)); }
protected void gvCart_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName != "Page") { List <OrderDetail> mycart = (List <OrderDetail>)Session[CART_STRING]; int rowindex = ((GridViewRow)((Button)e.CommandSource).NamingContainer).RowIndex; String FoodID = gvCart.Rows[rowindex].Cells[0].Text; String Size = gvCart.Rows[rowindex].Cells[2].Text; int oldquantity = Convert.ToInt32(gvCart.Rows[rowindex].Cells[3].Text); int odindex = mycart.FindIndex(o => o.FoodID == FoodID && o.Size == Size); if (e.CommandName == "PlusQuantity" && oldquantity < 10) { mycart[odindex].Quantity = oldquantity + 1; if (DiscountHelper.IsDiscountToday() && oldquantity % 2 == 1) { //discount if (Size == "S") { mycart[odindex].Discount += mycart[odindex].Dish.Price * 2 * 0.15; } else if (Size == "M") { mycart[odindex].Discount += mycart[odindex].Dish.Price * 2 * 0.25; } else if (Size == "L") { mycart[odindex].Discount += mycart[odindex].Dish.Price * 2 * 0.35; } } } else if (e.CommandName == "MinusQuantity" && oldquantity > 1) { mycart[odindex].Quantity = oldquantity - 1; if (DiscountHelper.IsDiscountToday() && oldquantity % 2 == 0) { //reduce discount if (Size == "S") { mycart[odindex].Discount -= mycart[odindex].Dish.Price * 2 * 0.15; } else if (Size == "M") { mycart[odindex].Discount -= mycart[odindex].Dish.Price * 2 * 0.25; } else if (Size == "L") { mycart[odindex].Discount -= mycart[odindex].Dish.Price * 2 * 0.35; } } } else if (e.CommandName == "RemoveItem") { mycart.RemoveAt(odindex); } loadDataToGridView(); } }
public Dependent() { DiscountHelper = new DiscountHelper(); }
/// <summary> /// What are my benefit costs when adjusted for my discounts? /// </summary> public decimal AdjustedAnnualBenefits() { return(DiscountHelper.ComputeAdjustedBenefits(this)); }
public override decimal CalculateDeduction(string name) { return(DiscountHelper.CanApplyNameDiscount(name) ? DiscountHelper.ApplyDiscount(500.00M) : 500.00M); }
public DiscountHelperTests() { _discountHelper = new DiscountHelper(); }
public void ApplyCostDiscountTotalRule_NoDiscount(int numDevices, decimal amount) { decimal discount = DiscountHelper.ApplyCostDiscountTotalRule(numDevices, amount); Assert.Equal(0.0m, discount); }
/// <summary> /// Determine how much of a discount this person gets based on eligibility criteria /// </summary> /// <returns>The percentage discount availabile</returns> public int BenefitsDiscountPercentage() { return(DiscountHelper.ComputeDiscountPercentage(this)); }
/// <summary> /// Parameterless constructor for Model Binding /// </summary> public Employee() { DiscountHelper = new DiscountHelper(); }
/// <summary> /// Includes dependents /// </summary> public decimal AdjustedAnnualBenefits() { var total = DiscountHelper.ComputeAdjustedBenefits(this); return(total + ProccessedDependents.Sum(d => d.AdjustedAnnualBenefits())); }
public int DiscountAmountForOrder(IOrderDiscount discount, OrderInfo orderInfo, bool applyDiscountEffects = false) //, IAuthenticationProvider authenticationProvider = null) { if (!string.IsNullOrEmpty(discount.CouponCode) && !orderInfo.CouponCodes.Contains(discount.CouponCode)) { return(0); } if (orderInfo.Status == OrderStatus.Incomplete) { var coupons = _couponCodeService.GetAllForDiscount(discount.Id); if (coupons.Any()) // { var availableCoupons = coupons.Where(c => c.NumberAvailable > 0).Select(c => c.CouponCode); if (!availableCoupons.Intersect(orderInfo.CouponCodes).Any()) { return(0); } } } var authenticationProvider = IO.Container.Resolve <IAuthenticationProvider>(); if (discount.MemberGroups.Any() && !discount.MemberGroups.Intersect(authenticationProvider.RolesForCurrentUser).Any()) { return(0); } if (discount.OncePerCustomer && !string.IsNullOrEmpty(authenticationProvider.CurrentLoginName)) { var ordersforCurrentMember = OrderHelper.GetOrdersForCustomer(authenticationProvider.CurrentLoginName).Where(x => x.Status != OrderStatus.Incomplete && x.Status != OrderStatus.Cancelled && x.Status != OrderStatus.Returned); if (ordersforCurrentMember.Any(x => x.Discounts.Any(d => d.OriginalId == discount.Id))) { return(0); } } var applicableOrderLines = !discount.AffectedOrderlines.Any() ? orderInfo.OrderLines : _orderService.GetApplicableOrderLines(orderInfo, discount.AffectedOrderlines); if (discount.AffectedProductTags != null && discount.AffectedProductTags.Any()) { applicableOrderLines = applicableOrderLines.Where(line => line.ProductInfo.Tags.Intersect(discount.AffectedProductTags).Any()).ToList(); } var isSellableUnitDiscount = discount.AffectedOrderlines.Any() || (discount.AffectedProductTags != null && discount.AffectedProductTags.Any()); var orderSellableUnits = new List <SellableUnit>(); foreach (var line in applicableOrderLines) { //for (var i = 0; i < line.ProductInfo.ItemCount; i++) orderSellableUnits.AddRange(line.SellableUnits); // maak een lijst met de prijzen van alle (losse) items van de order } var numberOfItemsLeftOutOfSets = discount.NumberOfItemsCondition == 0 ? 0 : applicableOrderLines.Sum(line => line.ProductInfo.ItemCount.GetValueOrDefault(1)) % discount.NumberOfItemsCondition; var applicableSellableUnits = orderSellableUnits.OrderBy(item => item.PriceInCents).Take(orderSellableUnits.Count - numberOfItemsLeftOutOfSets).ToList(); var rangedDiscountValue = RangedDiscountValueForOrder(discount, orderInfo); // todo: not localized var discountAmount = rangedDiscountValue; var maximumDiscountableAmount = 0L; var timesApplicable = 1; if (discount.Condition == DiscountOrderCondition.None) { maximumDiscountableAmount = applicableOrderLines.Sum(orderline => orderline.AmountInCents - (orderline.GetOriginalAmount(false, true) - orderline.GetOriginalAmount(true, true))); timesApplicable = applicableOrderLines.Sum(orderLine => orderLine.ProductInfo.ItemCount.GetValueOrDefault(1)); } else if (discount.Condition == DiscountOrderCondition.OnTheXthItem && discount.NumberOfItemsCondition > 0) { isSellableUnitDiscount = true; // todo: test discountAmount = discountAmount * applicableSellableUnits.Count() / discount.NumberOfItemsCondition; applicableSellableUnits = applicableSellableUnits.Take(orderSellableUnits.Count / discount.NumberOfItemsCondition).ToList(); maximumDiscountableAmount = applicableSellableUnits.Sum(su => su.PriceInCents); // bereken de korting over de x goedkoopste items, waarbij x het aantal sets in de order is } else if (discount.Condition == DiscountOrderCondition.PerSetOfXItems && discount.NumberOfItemsCondition > 0) { isSellableUnitDiscount = true; timesApplicable = applicableSellableUnits.Count() / discount.NumberOfItemsCondition; if (discount.DiscountType == DiscountType.Amount) { applicableSellableUnits = applicableSellableUnits.Take(orderSellableUnits.Count / discount.NumberOfItemsCondition).ToList(); } discountAmount = discountAmount * applicableSellableUnits.Count() / discount.NumberOfItemsCondition; maximumDiscountableAmount = applicableSellableUnits.Sum(su => su.PriceInCents); } if (discount.IncludeShippingInOrderDiscountableAmount) { maximumDiscountableAmount += orderInfo.ShippingProviderAmountInCents; } if (discount.DiscountType == DiscountType.Amount) { // currently not on SellableUnits, because that would break existing functionality if (applyDiscountEffects) { var amountDiscountEffect = new AmountDiscountEffect { Amount = rangedDiscountValue }; if (isSellableUnitDiscount) { foreach (var su in applicableSellableUnits) { su.SellableUnitDiscountEffects.AddEffect(amountDiscountEffect); } } else { orderInfo.OrderDiscountEffects.AddEffect(amountDiscountEffect); } } return((int)Math.Min(discountAmount, maximumDiscountableAmount)); } if (discount.DiscountType == DiscountType.Percentage) { // wanneer SellableUnit/OrderLine/Order if (applyDiscountEffects) { var percentageDiscountEffect = new PercentageDiscountEffect { Percentage = rangedDiscountValue / 10000m }; if (isSellableUnitDiscount) { foreach (var su in applicableSellableUnits) { su.SellableUnitDiscountEffects.AddEffect(percentageDiscountEffect); } } else { orderInfo.OrderDiscountEffects.AddEffect(percentageDiscountEffect); } } return(DiscountHelper.PercentageCalculation(rangedDiscountValue, maximumDiscountableAmount)); } if (discount.DiscountType == DiscountType.NewPrice) { if (applyDiscountEffects) { var newPriceDiscountEffect = new NewPriceDiscountEffect { NewPrice = rangedDiscountValue }; foreach (var applicableSellableUnit in applicableSellableUnits) { applicableSellableUnit.SellableUnitDiscountEffects.AddEffect(newPriceDiscountEffect); } } if (discount.Condition == DiscountOrderCondition.OnTheXthItem && discount.NumberOfItemsCondition > 0) { return(applicableSellableUnits.Take(orderSellableUnits.Count / discount.NumberOfItemsCondition).Select(su => Math.Max(0, su.PriceInCents - discountAmount)).Sum()); } return((int)Math.Max(0, maximumDiscountableAmount - rangedDiscountValue * timesApplicable)); } return(0); }