public async Task RecalculateAsync_HasPromoRewards_CalculateTotalsCalled() { // Arrange var cartAggregate = GetValidCartAggregate(); cartAggregate.Cart.Items = new List <LineItem> { _fixture.Create <LineItem>() }; var context = new PromotionEvaluationContext(); var promoResult = new PromotionResult(); var promoReward = new StubPromotionReward { Id = _fixture.Create <string>(), IsValid = true }; promoResult.Rewards.Add(promoReward); _mapperMock.Setup(x => x.Map <PromotionEvaluationContext>(It.Is <CartAggregate>(x => x == cartAggregate))) .Returns(context); _marketingPromoEvaluatorMock .Setup(x => x.EvaluatePromotionAsync(It.Is <PromotionEvaluationContext>(x => x == context))) .ReturnsAsync(promoResult); // Act var result = await cartAggregate.RecalculateAsync(); // Assert _shoppingCartTotalsCalculatorMock.Verify(x => x.CalculateTotals(It.Is <ShoppingCart>(x => x == cartAggregate.Cart)), Times.Once); }
/// <summary> /// Default bind data method. /// </summary> private void BindData() { var isEmpty = CartHelper.IsEmpty; // Make sure to check that prices has not changed if (!isEmpty) { // restore coupon code to context string couponCode = Session[Constants.LastCouponCode] as string; if (!String.IsNullOrEmpty(couponCode)) { MarketingContext.Current.AddCouponToMarketingContext(couponCode); } CartHelper.Cart.ProviderId = "FrontEnd"; CartHelper.RunWorkflow(Constants.CartValidateWorkflowName); // If cart is empty, remove it from the database isEmpty = CartHelper.IsEmpty; if (isEmpty) { CartHelper.Delete(); } CartHelper.Cart.AcceptChanges(); } if (!isEmpty) { lvCartItems.DataSource = CartHelper.LineItems; _promotionResult = CartHelper.GetPromotions(); } lvCartItems.DataBind(); }
public int CalculateTotalOrderValue() { //calculatePromovalue; int promoValue = 0; var items = new List <char>(_itemsList); PromotionResult ruleResult = this._ruleset.ExecuteRules(items.ToArray()); while (ruleResult != null) { if (ruleResult.ItemsUsed != null) { foreach (var item in ruleResult.ItemsUsed) { items.Remove(item); } promoValue += ruleResult.Value; } ruleResult = this._ruleset.ExecuteRules(items.ToArray()); } //calculate order total value int totalOrderValue = promoValue + CalculateNonPromoValue(items.ToArray()); return(totalOrderValue); }
public async Task <ApiPromotionResultResponse> GetPromotionResult([FromUri] int promotionTypeId, int?promotionCategoryId = null) { var apiResp = new ApiPromotionResultResponse { ResponseType = -1, ResponseMessage = "Failed" }; var retVal = await _promotion.GetPromotionTypeResult(promotionTypeId, promotionCategoryId); if (retVal.Count > 0) { apiResp.ResponseObject = new List <PromotionResult>(); int count = 1; foreach (var _promo in retVal) { var promotion = new PromotionResult(); promotion.Bind(_promo); promotion.PromoNumber = count; apiResp.ResponseObject.Add(promotion); count++; } apiResp.ResponseObject.OrderByDescending(x => x.NumberOfVotes); apiResp.ResponseType = 1; apiResp.ResponseMessage = "Success"; } return(apiResp); }
public async Task <PromotionResult> EvaluatePromotionAsync(IEvaluationContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var promoContext = context as PromotionEvaluationContext; if (promoContext == null) { throw new ArgumentException($"{nameof(context)} type {context.GetType()} must be derived from PromotionEvaluationContext"); } var promotions = await _promotionSearchService.SearchPromotionsAsync(new PromotionSearchCriteria { OnlyActive = true, StoreIds = new[] { promoContext.StoreId }, Take = int.MaxValue }); var result = new PromotionResult(); Func <PromotionEvaluationContext, IEnumerable <PromotionReward> > evalFunc = (evalContext) => promotions.Results.SelectMany(x => x.EvaluatePromotion(evalContext)) .OrderByDescending(x => x.Promotion.IsExclusive) .ThenByDescending(x => x.Promotion.Priority) .Where(x => x.IsValid) .ToList(); EvalAndCombineRewardsRecursively(promoContext, evalFunc, result.Rewards, new List <PromotionReward>()); return(result); }
public async Task EvaluatePromotionsAsync_HasCart_PromotionEvaluated() { // Arrange var cartAggregate = GetValidCartAggregate(); cartAggregate.Cart.Items = new List <LineItem> { _fixture.Create <LineItem>() }; var context = new PromotionEvaluationContext(); var promoResult = new PromotionResult(); var promoReward = new StubPromotionReward { Id = _fixture.Create <string>(), IsValid = true }; promoResult.Rewards.Add(promoReward); _mapperMock.Setup(x => x.Map <PromotionEvaluationContext>(It.Is <CartAggregate>(x => x == cartAggregate))) .Returns(context); _marketingPromoEvaluatorMock .Setup(x => x.EvaluatePromotionAsync(It.Is <PromotionEvaluationContext>(x => x == context))) .ReturnsAsync(promoResult); // Act var result = await cartAggregate.EvaluatePromotionsAsync(); // Assert result.Rewards.Should().ContainSingle(x => x.Id == promoReward.Id); }
/// <inheritdoc/> public override bool Equals(object obj) { if (obj is PromotionResult) { PromotionResult other = obj as PromotionResult; return(this.Size == other.Size && this.Promotion == other.Promotion); } return(false); }
/// <summary> /// Default bind data method. /// </summary> public void BindData() { if (!_cartHelper.IsEmpty) { _promotionResult = _cartHelper.GetPromotions(); } lvCartItems.DataSource = ShipmentLineItems; lvCartItems.DataBind(); }
/// <summary> /// Gets the discount price. /// </summary> /// <param name="entry">The entry.</param> /// <returns></returns> //public static Price GetDiscountPrice(Entry entry) //{ // return GetDiscountPrice(entry, string.Empty, string.Empty); //} /// <summary> /// Gets the discount price. /// </summary> /// <param name="entry">The entry.</param> /// <param name="catalogName">Name of the catalog.</param> /// <returns></returns> //public static Price GetDiscountPrice(Entry entry, string catalogName) //{ // return GetDiscountPrice(entry, catalogName, string.Empty); //} /// <summary> /// Gets the discounted price of the catalog entry. /// </summary> /// <param name="entry">The catalog entry.</param> /// <param name="catalogName">Name of the catalog to filter the discounts for. If null, all catalogs containing the entry will be used.</param> /// <param name="catalogNodeCode">The catalog node code to filter the discounts for. If null, all catalog nodes containing the entry will be used.</param> /// <param name="market">The market to fetch tiered base pricing for.</param> /// <returns>The discounted price of the catalog entry.</returns> /// <remarks>Uses market.DefaultCurrency for the currency.</remarks> //public static Price GetDiscountPrice(Entry entry, string catalogName, string catalogNodeCode, IMarket market) //{ // return GetDiscountPrice(entry, catalogName, catalogNodeCode, market, market.DefaultCurrency); //} /// <summary> /// Gets the discounted price of the catalog entry. /// </summary> /// <param name="entry">The catalog entry.</param> /// <param name="catalogName">Name of the catalog to filter the discounts for. If null, all catalogs containing the entry will be used.</param> /// <param name="catalogNodeCode">The catalog node code to filter the discounts for. If null, all catalog nodes containing the entry will be used.</param> /// <param name="market">The market to fetch tiered base pricing for.</param> /// <param name="currency">The currency to fetch prices in.</param> /// <returns>The discounted price of the catalog entry.</returns> //public static Price GetDiscountPrice(Entry entry, string catalogName, string catalogNodeCode, IMarket market, Currency currency) //{ // if (entry == null) // throw new NullReferenceException("entry can't be null"); // decimal minQuantity = 1; // // get min quantity attribute // if (entry.ItemAttributes != null) // minQuantity = entry.ItemAttributes.MinQuantity; // // we can't pass qauntity of 0, so make it default to 1 // if (minQuantity <= 0) // minQuantity = 1; // // Get sale price for the current user // Price price = StoreHelper.GetSalePrice(entry, minQuantity, market, currency); // if (price == null) // { // return null; // } // string catalogNodes = String.Empty; // string catalogs = String.Empty; // // Now cycle through all the catalog nodes where this entry is present filtering by specified catalog and node code // // The nodes are only populated when Full or Nodes response group is specified. // if (entry.Nodes != null && entry.Nodes.CatalogNode != null && entry.Nodes.CatalogNode.Length > 0) // { // foreach (CatalogNode node in entry.Nodes.CatalogNode) // { // string entryCatalogName = CatalogContext.Current.GetCatalogDto(node.CatalogId).Catalog[0].Name; // // Skip filtered catalogs // if (!String.IsNullOrEmpty(catalogName) && !entryCatalogName.Equals(catalogName)) // continue; // // Skip filtered catalogs nodes // if (!String.IsNullOrEmpty(catalogNodeCode) && !node.ID.Equals(catalogNodeCode, StringComparison.OrdinalIgnoreCase)) // continue; // if (String.IsNullOrEmpty(catalogs)) // catalogs = entryCatalogName; // else // catalogs += ";" + entryCatalogName; // if (String.IsNullOrEmpty(catalogNodes)) // catalogNodes = node.ID; // else // catalogNodes += ";" + node.ID; // } // } // if (String.IsNullOrEmpty(catalogs)) // catalogs = catalogName; // if (String.IsNullOrEmpty(catalogNodes)) // catalogNodes = catalogNodeCode; // // Get current context // Dictionary<string, object> context = MarketingContext.Current.MarketingProfileContext; // // Create filter // PromotionFilter filter = new PromotionFilter(); // filter.IgnoreConditions = false; // filter.IgnorePolicy = false; // filter.IgnoreSegments = false; // filter.IncludeCoupons = false; // // Create new entry // // TPB: catalogNodes is determined by the front end. GetParentNodes(entry) // PromotionEntry result = new PromotionEntry(catalogs, catalogNodes, entry.ID, price.Money.Amount); // var promotionEntryPopulateService = (IPromotionEntryPopulate)MarketingContext.Current.PromotionEntryPopulateFunctionClassInfo.CreateInstance(); // promotionEntryPopulateService.Populate(result, entry, market.MarketId, currency); // PromotionEntriesSet sourceSet = new PromotionEntriesSet(); // sourceSet.Entries.Add(result); // return GetDiscountPrice(filter, price, sourceSet, sourceSet); //} /// <summary> /// Gets the discount price by evaluating the discount rules and taking into account segments customer belongs to. /// </summary> /// <param name="entry">The entry.</param> /// <param name="catalogName">Name of the catalog to filter the discounts for. If null, all catalogs entry belongs to will be applied.</param> /// <param name="catalogNodeCode">The catalog node code to filter the discounts for. If null, all catalog nodes entry belongs to will be applied.</param> /// <returns></returns> //public static Price GetDiscountPrice(Entry entry, string catalogName, string catalogNodeCode) //{ // ICurrentMarket currentMarketService = ServiceLocator.Current.GetInstance<ICurrentMarket>(); // return GetDiscountPrice(entry, catalogName, catalogNodeCode, currentMarketService.GetCurrentMarket()); //} /// <summary> /// Gets the discount price. /// </summary> /// <param name="filter">The filter.</param> /// <param name="salePrice">The sale price.</param> /// <param name="sourceSet">The source set.</param> /// <param name="targetSet">The target set.</param> /// <returns></returns> //private static Price GetDiscountPrice(PromotionFilter filter, Price salePrice, PromotionEntriesSet sourceSet, PromotionEntriesSet targetSet) //{ // // Create new promotion helper, which will initialize PromotionContext object for us and setup context dictionary // CustomPromotionHelper helper = new CustomPromotionHelper(); // // Only target entries // helper.PromotionContext.TargetGroup = PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Entry).Key; // // Configure promotion context // helper.PromotionContext.SourceEntriesSet = sourceSet; // helper.PromotionContext.TargetEntriesSet = targetSet; // // Execute the promotions and filter out basic collection of promotions, we need to execute with cache disabled, so we get latest info from the database // helper.Eval(filter); // // Check the count, and get new price // if (helper.PromotionContext.PromotionResult.PromotionRecords.Count > 0) // don't get anything here // return ObjectHelper.CreatePrice(new Money(salePrice.Money.Amount - GetDiscountPrice(helper.PromotionContext.PromotionResult), salePrice.Money.Currency)); // else // return salePrice; //} /// <summary> /// Gets the discount price. /// </summary> /// <param name="result">The result.</param> /// <returns></returns> private static decimal GetDiscountPrice(PromotionResult result) { decimal discountAmount = 0; foreach (PromotionItemRecord record in result.PromotionRecords) { discountAmount += GetDiscountAmount(record, record.PromotionReward); } return(discountAmount); }
//public Decimal GetPercentOrAmountProductDiscount(PromotionResult promotionResult, CustomerOrderPromotion customerOrderPromotion) //{ // if (!promotionResult.Amount.HasValue) // throw new ArgumentNullException("Amount"); // if (promotionResult.Amount.Value == Decimal.Zero) // throw new ArgumentOutOfRangeException("Amount"); // return customerOrderPromotion.CustomerOrder.OrderLines.Where<OrderLine>((Func<OrderLine, bool>)(o => // { // PromotionResult promotionResult1 = o.PromotionResult; // Guid? nullable = promotionResult1 != null ? new Guid?(promotionResult1.Id) : new Guid?(); // Guid id = promotionResult.Id; // if ((nullable.HasValue ? (nullable.HasValue ? (nullable.GetValueOrDefault() == id ? 1 : 0) : 1) : 0) != 0) // return !o.Product.IsQuoteRequired; // return false; // })).Sum<OrderLine>((Func<OrderLine, Decimal>)(orderLine => // { // Decimal actualPrice = this.GetPricingServiceResult(orderLine).ActualPrice; // Decimal retailPrice = orderLine.RegularPrice; // Decimal? amount = promotionResult.Amount; // Decimal lowestPrice; // bool? isPercent = promotionResult.IsPercent; // if ((isPercent.HasValue ? (isPercent.GetValueOrDefault() ? 1 : 0) : 0) == 0) // { // lowestPrice = GetLowestPriceBaseAmountBasedPromotion(actualPrice, retailPrice, amount); // if (lowestPrice == actualPrice) // { // return 0; // } // return NumberHelper.RoundCurrency(orderLine.QtyOrdered * promotionResult.Amount.Value); // } // else // { // Decimal percent = amount.Value / new Decimal(100); // lowestPrice = GetLowestPriceBasePercentBasedPromotion(actualPrice, retailPrice, amount); // if (lowestPrice == actualPrice) // { // return 0; // } // return NumberHelper.RoundCurrency(orderLine.QtyOrdered * NumberHelper.GetDiscount(retailPrice, percent)); // } // })); //} public virtual Decimal GetPercentOrAmountProductDiscount(PromotionResult promotionResult, CustomerOrderPromotion customerOrderPromotion) { if (!promotionResult.Amount.HasValue) { throw new ArgumentNullException("Amount"); } if (promotionResult.Amount.Value == Decimal.Zero) { throw new ArgumentOutOfRangeException("Amount"); } if (customerOrderPromotion?.OrderLine != null) // check if customerOrderPromotion object is not null with ? operator { Guid?id1 = customerOrderPromotion.OrderLine.PromotionResult?.Id; Guid id2 = promotionResult.Id; if ((id1.HasValue ? (id1.HasValue ? (id1.GetValueOrDefault() != id2 ? 1 : 0) : 0) : 1) == 0 && !customerOrderPromotion.OrderLine.Product.IsQuoteRequired) { ProductPriceDto productPriceDto = this.GetPricingServiceResult((IEnumerable <OrderLine>) new List <OrderLine>() { customerOrderPromotion.OrderLine }).FirstOrDefault <KeyValuePair <Guid, ProductPriceDto> >((Func <KeyValuePair <Guid, ProductPriceDto>, bool>)(o => o.Key == customerOrderPromotion.OrderLine.Id)).Value; //Decimal amount = productPriceDto != null ? productPriceDto.UnitListPrice : Decimal.Zero; // New Decimal actualPrice = productPriceDto.UnitRegularPrice; /*this.GetPricingServiceResult(orderLine).ActualPrice; */ //unitregularprice Decimal retailPrice = productPriceDto.UnitListPrice; Decimal?promoAmount = promotionResult.Amount; Decimal lowestPrice; bool? isPercent = promotionResult.IsPercent; if ((isPercent.HasValue ? (isPercent.GetValueOrDefault() ? 1 : 0) : 0) == 0) { lowestPrice = GetLowestPriceBaseAmountBasedPromotion(actualPrice, retailPrice, promoAmount); if (lowestPrice == actualPrice) { return(0); } return(NumberHelper.RoundCurrency(customerOrderPromotion.OrderLine.QtyOrdered * promotionResult.Amount.Value)); } else { Decimal percent = promoAmount.Value / new Decimal(100); lowestPrice = GetLowestPriceBasePercentBasedPromotion(actualPrice, retailPrice, promoAmount); if (lowestPrice == actualPrice) { return(0); } return(NumberHelper.RoundCurrency(customerOrderPromotion.OrderLine.QtyOrdered * NumberHelper.GetDiscount(retailPrice, promotionResult.Amount.Value / new Decimal(100)))); } } } return(Decimal.Zero); }
public void TestMethod_ScenarioD() { //Arrange IPromotion promotion = null; promotion = new Promotion1(); PromotionResult promotionResult = new PromotionResult(promotion); promotionResult.Items.Add(new ItemA() { NoOfItems = 3, Cost = 50 }); promotionResult.Items.Add(new ItemB() { NoOfItems = 5, Cost = 30 }); promotionResult.Items.Add(new ItemC() { NoOfItems = 1, Cost = 20 }); promotionResult.Items.Add(new ItemD() { NoOfItems = 1, Cost = 15 }); //Act var result = promotionResult.Calculate(); //Assert Assert.AreEqual <double>(result, 280); }
public virtual async Task <PromotionResult> EvaluatePromotionsAsync() { EnsureCartExists(); var promotionResult = new PromotionResult(); if (!Cart.Items.IsNullOrEmpty() && !Cart.Items.Any(i => i.IsReadOnly)) { var evalContext = _mapper.Map <PromotionEvaluationContext>(this); promotionResult = await EvaluatePromotionsAsync(evalContext); } return(promotionResult); }
public PromotionResult ProcessEvent(IMarketingEvent markertingEvent) { var retVal = new PromotionResult(); var promotions = _promotionService.GetActivePromotions(); foreach (var promotion in promotions) { var rewards = promotion.ProcessEvent(markertingEvent).Where(x => x != null); foreach (var promotionReward in rewards) { retVal.Rewards.Add(promotionReward); } } return(retVal); }
public override void ClearPromotionResult(CustomerOrder customerOrder) { //4.2 Code //customerOrder.OrderLines.Where<OrderLine>((Func<OrderLine, bool>)(o => //{ // PromotionResult promotionResult = o.PromotionResult; // Guid? nullable = promotionResult != null ? new Guid?(promotionResult.Id) : new Guid?(); // Guid id = this.PromotionResult.Id; // if (!nullable.HasValue) // return false; // if (!nullable.HasValue) // return true; // return nullable.GetValueOrDefault() == id; //})).ToList<OrderLine>().ForEach((Action<OrderLine>)(orderLine => //{ // // BUSA-683 : Volume Discount Promotion - Issue when user cart qualifies add free product promotion &volume discount group. // this.UnitOfWork.Save(); // var id = this.UnitOfWork.GetRepository<OrderLine>().GetTable().Where(x => x.Id == orderLine.Id).Count(); // if (id > 0) // { // this.CustomerOrderUtilities.RemoveOrderLine(customerOrder, orderLine); // } //})); foreach (OrderLine orderLine in customerOrder.OrderLines.Where <OrderLine>((Func <OrderLine, bool>)(o => { PromotionResult promotionResult = o.PromotionResult; Guid?nullable = promotionResult != null ? new Guid?(promotionResult.Id) : new Guid?(); Guid id = this.PromotionResult.Id; if (!nullable.HasValue) { return(false); } if (!nullable.HasValue) { return(true); } return(nullable.GetValueOrDefault() == id); })).ToList <OrderLine>()) { PipelineHelper.VerifyResults((PipeResultBase)this.CartPipeline.RemoveCartLine(new Insite.Cart.Services.Pipelines.Parameters.RemoveCartLineParameter() { Cart = customerOrder, CartLine = orderLine })); } }
protected override async Task <PromotionResult> EvaluatePromotionWithoutCache(PromotionEvaluationContext promoContext) { var promotionSearchCriteria = AbstractTypeFactory <PromotionSearchCriteria> .TryCreateInstance(); promotionSearchCriteria.PopulateFromEvalContext(promoContext); promotionSearchCriteria.OnlyActive = true; promotionSearchCriteria.Take = int.MaxValue; promotionSearchCriteria.StoreIds = string.IsNullOrEmpty(promoContext.StoreId) ? null : new[] { promoContext.StoreId }; var promotions = await _promotionSearchService.SearchPromotionsAsync(promotionSearchCriteria); var result = new PromotionResult(); await EvalAndCombineRewardsRecursivelyAsync(promoContext, promotions.Results, result.Rewards, new List <PromotionReward>()); return(result); }
public async Task <ActionResult> Edit([Bind(Include = "WidgetId,Description,MainBusCode,TestPassDateTime,WidgetStatus,CurrentWorkerId")] Widget widget, string command) { if (ModelState.IsValid) { PromotionResult promotionResult = new PromotionResult(); if (command == "Save") { promotionResult.Success = true; promotionResult.Message = String.Format("Changes to widget {0} have been successfully saved.", widget.WidgetId); } else if (command == "Claim") { promotionResult = widget.ClaimWorkListItem(User.Identity.GetUserId()); } else if (command == "Relinquish") { promotionResult = widget.RelinquishWorkListItem(); } else { promotionResult = widget.PromoteWorkListItem(command); } if (!promotionResult.Success) { TempData["MessageToClient"] = promotionResult.Message; } _applicationDbContext.Entry(widget).State = EntityState.Modified; await _applicationDbContext.SaveChangesAsync(); if (command == "Claim" && promotionResult.Success) { return(RedirectToAction("Edit", widget.WidgetId)); } return(RedirectToAction("Index", "WorkList")); } return(View(widget)); }
public async Task <ActionResult> Edit([Bind(Include = "WidgetId,Description,MainBusCode,TestPassDateTime,WidgetStatus,CurrentWorkerId")] Widget widget, string command) { if (ModelState.IsValid) { PromotionResult promotionResult = new PromotionResult(); if (command == "Save") { promotionResult.Success = true; promotionResult.Message = String.Format("Changes to widget {0} have been successfully saved.", widget.WidgetId); Log4NetHelper.Log(promotionResult.Message, LogLevel.INFO, widget.EntityFormalNamePlural, widget.WidgetId, User.Identity.Name, null); } else if (command == "Claim") { promotionResult = widget.ClaimWorkListItem(User.Identity.GetUserId()); } else if (command == "Relinquish") { promotionResult = widget.RelinquishWorkListItem(); } else { promotionResult = widget.PromoteWorkListItem(command); } if (promotionResult.Success) { TempData["MessageToClient"] = promotionResult.Message; } db.Entry(widget).State = EntityState.Modified; await db.SaveChangesAsync(); if (command == "Claim" && promotionResult.Success) { return(RedirectToAction("Edit", widget.WidgetId)); } return(RedirectToAction("Index", "WorkList")); } //ViewBag.CurrentWorkerId = new SelectList(db.ApplicationUsers, "Id", "FirstName", widget.CurrentWorkerId); return(View(widget)); }
public async Task <ActionResult> Edit([Bind(Include = "WorkOrderId,CustomerId,OrderDateTime,TargetDateTime,DropDeadDateTime,Description,WorkOrderStatus,CertificationRequirements,CurrentWorkerId,ReworkNotes")] WorkOrder workOrder, string command) { if (ModelState.IsValid) { // Populate Parts and Labors. workOrder.Parts = _applicationDbContext.Parts.Where(p => p.WorkOrderId == workOrder.WorkOrderId).ToList(); workOrder.Labors = _applicationDbContext.Labors.Where(l => l.WorkOrderId == workOrder.WorkOrderId).ToList(); var promotionResult = new PromotionResult(); if (command == "Save") { promotionResult.Success = true; } else if (command == "Claim") { promotionResult = workOrder.ClaimWorkListItem(User.Identity.GetUserId()); } else { promotionResult = workOrder.PromoteWorkListItem(command); } if (!promotionResult.Success) { TempData["MessageToClient"] = promotionResult.Message; } _applicationDbContext.Entry(workOrder).State = EntityState.Modified; await _applicationDbContext.SaveChangesAsync(); return(RedirectToAction("Index")); } return(View(workOrder)); }
public async Task <ActionResult> Edit([Bind(Include = "WorkOrderId,CustomerId,OrderDateTime,TargetDateTime,DropDeadDateTime,Description,WorkOrderStatus,CertificationRequirements,CurrentWorkerId")] WorkOrder workOrder, string command) { if (ModelState.IsValid) { // Populate Parts and Labors workOrder.Parts = context.Parts.Where(p => p.WorkOrderId == workOrder.WorkOrderId).ToList(); workOrder.Labors = context.Labors.Where(l => l.WorkOrderId == workOrder.WorkOrderId).ToList(); PromotionResult promotionResult = new PromotionResult(); if (command == "Save") { promotionResult.Success = true; } else if (command == "Claim") { promotionResult = workOrder.ClaimWorkOrder(User.Identity.GetUserId()); } else { promotionResult = workOrder.PromoteWorkOrder(command); } if (!promotionResult.Success) { TempData["MessageToClient"] = promotionResult.Message; } context.Entry(workOrder).State = EntityState.Modified; await context.SaveChangesAsync(); return(RedirectToAction("Index")); } //ViewBag.CurrentWorkerId = new SelectList(context.ApplicationUsers, "Id", "FirstName", workOrder.CurrentWorkerId); //ViewBag.CustomerId = new SelectList(context.Customers, "CustomerId", "AccountNumber", workOrder.CustomerId); return(View(workOrder)); }
public PromotionResult Evaluate(char[] itemsList) { PromotionResult result = null; List <char> matchingItems = new List <char>(); int price = 0; List <char> items = new List <char>(itemsList); while (DoesSatifyCondition(items.ToArray())) { foreach (var itemPricePair in _itemCountPairList) { char itemName = itemPricePair.Item1; int setSize = itemPricePair.Item2; int iter = 0; while (iter++ < setSize) { matchingItems.Add(itemName); items.Remove(itemName); } } price += this._price; } if (matchingItems.Count > 0) { if (result == null) { result = new PromotionResult(); } result.ItemsUsed = matchingItems.ToArray(); result.Value = price; } return(result); }
public async Task ValidateCouponAsync_ValidCoupon_CouponValidated() { // Arrange var cartAggregate = GetValidCartAggregate(); cartAggregate.Cart.Items = new List <LineItem> { _fixture.Create <LineItem>() }; var coupon = _fixture.Create <string>(); var context = new PromotionEvaluationContext { Coupon = coupon, }; var stub = new PromotionResult(); stub.Rewards.Add(new StubPromotionReward { Coupon = coupon, IsValid = true }); _mapperMock.Setup(x => x.Map <PromotionEvaluationContext>(It.Is <CartAggregate>(x => x == cartAggregate))) .Returns(context); _marketingPromoEvaluatorMock .Setup(x => x.EvaluatePromotionAsync(It.Is <PromotionEvaluationContext>(x => x.Coupon == coupon))) .ReturnsAsync(stub); // Act var result = await cartAggregate.ValidateCouponAsync(coupon); // Assert result.Should().BeTrue(); }
public PromotionResult ExecuteRules(char[] itemList) { PromotionResult minResult = null; foreach (var rule in _rulesList) { var ruleResult = rule.Evaluate(itemList); if (ruleResult != null) { if (minResult == null) { minResult = ruleResult; } else if (minResult.Value > ruleResult.Value) { minResult = ruleResult; } } } return(minResult); }
protected override void AddOrUpdateCustomerOrderPromotion(CustomerOrder customerOrder, CustomerOrderPromotion appliedPromotion, OrderLine orderLine, PromotionResult promotionResult) { ICollection <CustomerOrderPromotion> customerOrderPromotions = customerOrder.CustomerOrderPromotions; foreach (CustomerOrderPromotion customerOrderPromotion in customerOrderPromotions.Where <CustomerOrderPromotion>((Func <CustomerOrderPromotion, bool>)(p => { Guid?orderLineId = p.OrderLineId; Guid id = orderLine.Id; if (!orderLineId.HasValue) { return(false); } if (!orderLineId.HasValue) { return(true); } return(orderLineId.GetValueOrDefault() == id); }))) { customerOrderPromotion.Amount = new Decimal?(new Decimal()); } if (appliedPromotion != null && appliedPromotion.Promotion != null && !appliedPromotion.OrderLineId.HasValue) { appliedPromotion.OrderLineId = new Guid?(orderLine.Id); appliedPromotion.OrderLine = orderLine; appliedPromotion.Amount = new Decimal?(this.PromotionProvider.GetAppliedAmount(appliedPromotion, string.Empty)); } else { CustomerOrderPromotion customerOrderPromotion = new CustomerOrderPromotion() { CustomerOrderId = customerOrder.Id, CustomerOrder = customerOrder, PromotionId = promotionResult.PromotionId, Promotion = this.UnitOfWork.GetRepository <Promotion>().Get(promotionResult.PromotionId), OrderLineId = new Guid?(orderLine.Id), OrderLine = orderLine }; customerOrderPromotion.Amount = new Decimal?(this.PromotionProvider.GetAppliedAmount(customerOrderPromotion, string.Empty)); customerOrder.CustomerOrderPromotions.Add(customerOrderPromotion); } }
public PromotionResult EvaluatePromotion(IEvaluationContext context) { var now = DateTime.UtcNow; var promotions = _promotionService.GetActivePromotions(); var promoContext = (PromotionEvaluationContext)context; var retVal = new PromotionResult(); var rewards = promotions.SelectMany(x => x.EvaluatePromotion(context)).ToArray(); //best shipment promotion var curShipmentAmount = promoContext.ShipmentMethodCode != null ? promoContext.ShipmentMethodPrice : 0m; var allShipmentRewards = rewards.OfType<ShipmentReward>().ToArray(); EvaluteBestAmountRewards(curShipmentAmount, allShipmentRewards).ToList().ForEach(x => retVal.Rewards.Add(x)); //best catalog item promotion var allItemsRewards = rewards.OfType<CatalogItemAmountReward>().ToArray(); var groupRewards = allItemsRewards.GroupBy(x => x.ProductId).Where(x=>x.Key != null); foreach (var groupReward in groupRewards) { var item = promoContext.PromoEntries.FirstOrDefault(x => x.ProductId == groupReward.Key); if (item != null) { EvaluteBestAmountRewards(item.Price, groupReward.ToArray()).ToList().ForEach(x => retVal.Rewards.Add(x)); } } //best order promotion var cartSubtotalRewards = rewards.OfType<CartSubtotalReward>().Where(x => x.IsValid).OrderByDescending(x => x.Amount); var cartSubtotalReward = cartSubtotalRewards.FirstOrDefault(x => !string.IsNullOrEmpty(x.Coupon)) ?? cartSubtotalRewards.FirstOrDefault(); if (cartSubtotalReward != null) { retVal.Rewards.Add(cartSubtotalReward); //Exlusive offer if (cartSubtotalReward.IsExclusive) { var itemRewards = retVal.Rewards.OfType<CatalogItemAmountReward>().ToList(); for (var i = itemRewards.Count - 1; i >= 0; i--) { retVal.Rewards.Remove(itemRewards[i]); } } } var potentialCartSubtotalRewards = rewards.OfType<CartSubtotalReward>().Where(x => !x.IsValid).OrderByDescending(x => x.Amount); var potentialCartSubtotalReward = potentialCartSubtotalRewards.FirstOrDefault(x => !string.IsNullOrEmpty(x.Coupon)) ?? cartSubtotalRewards.FirstOrDefault(); if (potentialCartSubtotalReward != null && cartSubtotalReward != null) { if (potentialCartSubtotalReward.Amount > cartSubtotalReward.Amount) { retVal.Rewards.Add(potentialCartSubtotalReward); } } else if (potentialCartSubtotalReward != null) { retVal.Rewards.Add(potentialCartSubtotalReward); } //Gifts rewards.OfType<GiftReward>().ToList().ForEach(x => retVal.Rewards.Add(x)); //Special offer rewards.OfType<SpecialOfferReward>().ToList().ForEach(x => retVal.Rewards.Add(x)); return retVal; }
public PromotionResult EvaluatePromotion(IEvaluationContext context) { var now = DateTime.UtcNow; var promotions = _promotionService.GetActivePromotions(); var promoContext = (PromotionEvaluationContext)context; var retVal = new PromotionResult(); var rewards = promotions.SelectMany(x => x.EvaluatePromotion(context)).ToArray(); //best shipment promotion var curShipmentAmount = promoContext.ShipmentMethodCode != null ? promoContext.ShipmentMethodPrice : 0m; var allShipmentRewards = rewards.OfType <ShipmentReward>().ToArray(); EvaluteBestAmountRewards(curShipmentAmount, allShipmentRewards).ToList().ForEach(x => retVal.Rewards.Add(x)); //best catalog item promotion var allItemsRewards = rewards.OfType <CatalogItemAmountReward>().ToArray(); var groupRewards = allItemsRewards.GroupBy(x => x.ProductId).Where(x => x.Key != null); foreach (var groupReward in groupRewards) { var item = promoContext.PromoEntries.First(x => x.ProductId == groupReward.Key); EvaluteBestAmountRewards(item.Price, groupReward.ToArray()).ToList().ForEach(x => retVal.Rewards.Add(x)); } //best order promotion var cartSubtotalRewards = rewards.OfType <CartSubtotalReward>().Where(x => x.IsValid).OrderByDescending(x => x.Amount); var cartSubtotalReward = cartSubtotalRewards.FirstOrDefault(x => !string.IsNullOrEmpty(x.Coupon)) ?? cartSubtotalRewards.FirstOrDefault(); if (cartSubtotalReward != null) { retVal.Rewards.Add(cartSubtotalReward); //Exlusive offer if (cartSubtotalReward.IsExclusive) { var itemRewards = retVal.Rewards.OfType <CatalogItemAmountReward>().ToList(); for (var i = itemRewards.Count - 1; i >= 0; i--) { retVal.Rewards.Remove(itemRewards[i]); } } } var potentialCartSubtotalRewards = rewards.OfType <CartSubtotalReward>().Where(x => !x.IsValid).OrderByDescending(x => x.Amount); var potentialCartSubtotalReward = potentialCartSubtotalRewards.FirstOrDefault(x => !string.IsNullOrEmpty(x.Coupon)) ?? cartSubtotalRewards.FirstOrDefault(); if (potentialCartSubtotalReward != null && cartSubtotalReward != null) { if (potentialCartSubtotalReward.Amount > cartSubtotalReward.Amount) { retVal.Rewards.Add(potentialCartSubtotalReward); } } else if (potentialCartSubtotalReward != null) { retVal.Rewards.Add(potentialCartSubtotalReward); } //Gifts rewards.OfType <GiftReward>().ToList().ForEach(x => retVal.Rewards.Add(x)); //Special offer rewards.OfType <SpecialOfferReward>().ToList().ForEach(x => retVal.Rewards.Add(x)); return(retVal); }
public async Task <PromotionResult> EvaluatePromotionAsync(IEvaluationContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var promoContext = context as PromotionEvaluationContext; if (promoContext == null) { throw new ArgumentException($"{nameof(context)} type {context.GetType()} must be derived from PromotionEvaluationContext"); } var promotions = await _promotionSearchService.SearchPromotionsAsync(new PromotionSearchCriteria { OnlyActive = true, StoreIds = new[] { promoContext.StoreId }, Take = int.MaxValue }); var result = new PromotionResult(); var rewards = promotions.Results.SelectMany(x => x.EvaluatePromotion(context)).Where(x => x.IsValid).ToArray(); var firstOrderExlusiveReward = rewards.FirstOrDefault(x => x.Promotion.IsExclusive); if (firstOrderExlusiveReward != null) { //Add only rewards from exclusive promotion result.Rewards.AddRange(rewards.Where(x => x.Promotion == firstOrderExlusiveReward.Promotion)); } else { //best shipment promotion var curShipmentAmount = promoContext.ShipmentMethodCode != null ? promoContext.ShipmentMethodPrice : 0m; var allShipmentRewards = rewards.OfType <ShipmentReward>().ToArray(); var groupedByShippingMethodRewards = allShipmentRewards.GroupBy(x => x.ShippingMethod); foreach (var shipmentRewards in groupedByShippingMethodRewards) { var bestShipmentReward = GetBestAmountReward(curShipmentAmount, shipmentRewards); if (bestShipmentReward != null) { result.Rewards.Add(bestShipmentReward); } } //best catalog item promotion var allItemsRewards = rewards.OfType <CatalogItemAmountReward>().ToArray(); var groupRewards = allItemsRewards.GroupBy(x => x.ProductId).Where(x => x.Key != null); foreach (var groupReward in groupRewards) { var item = promoContext.PromoEntries.FirstOrDefault(x => x.ProductId == groupReward.Key); if (item != null) { var bestItemReward = GetBestAmountReward(item.Price, groupReward); if (bestItemReward != null) { result.Rewards.Add(bestItemReward); } } } //best order promotion var cartSubtotalRewards = rewards.OfType <CartSubtotalReward>().Where(x => x.IsValid).OrderByDescending(x => x.GetRewardAmount(promoContext.CartTotal, 1)); var cartSubtotalReward = cartSubtotalRewards.FirstOrDefault(x => !string.IsNullOrEmpty(x.Coupon)) ?? cartSubtotalRewards.FirstOrDefault(); if (cartSubtotalReward != null) { result.Rewards.Add(cartSubtotalReward); } //Gifts rewards.OfType <GiftReward>().ToList().ForEach(x => result.Rewards.Add(x)); //Special offer rewards.OfType <SpecialOfferReward>().ToList().ForEach(x => result.Rewards.Add(x)); } return(result); }
protected override async Task <PromotionResult> EvaluatePromotionWithoutCache(PromotionEvaluationContext promoContext) { var promotionSearchCriteria = AbstractTypeFactory <PromotionSearchCriteria> .TryCreateInstance(); promotionSearchCriteria.PopulateFromEvalContext(promoContext); promotionSearchCriteria.OnlyActive = true; promotionSearchCriteria.Take = int.MaxValue; promotionSearchCriteria.StoreIds = string.IsNullOrEmpty(promoContext.StoreId) ? null : new[] { promoContext.StoreId }; var promotions = await _promotionSearchService.SearchPromotionsAsync(promotionSearchCriteria); var result = new PromotionResult(); var evalPromtionTasks = promotions.Results.Select(x => x.EvaluatePromotionAsync(promoContext)).ToArray(); await Task.WhenAll(evalPromtionTasks); var rewards = evalPromtionTasks.SelectMany(x => x.Result).Where(x => x.IsValid).ToArray(); var firstOrderExclusiveReward = rewards.FirstOrDefault(x => x.Promotion.IsExclusive); if (firstOrderExclusiveReward != null) { //Add only rewards from exclusive promotion result.Rewards.AddRange(rewards.Where(x => x.Promotion == firstOrderExclusiveReward.Promotion)); } else { //best shipment promotion var curShipmentAmount = promoContext.ShipmentMethodCode != null ? promoContext.ShipmentMethodPrice : 0m; var allShipmentRewards = rewards.OfType <ShipmentReward>().ToArray(); var groupedByShippingMethodRewards = allShipmentRewards.GroupBy(x => x.ShippingMethod); foreach (var shipmentRewards in groupedByShippingMethodRewards) { var bestShipmentReward = GetBestAmountReward(curShipmentAmount, shipmentRewards); if (bestShipmentReward != null) { result.Rewards.Add(bestShipmentReward); } } //best payment promotion var currentPaymentAmount = promoContext.PaymentMethodCode != null ? promoContext.PaymentMethodPrice : 0m; var allPaymentRewards = rewards.OfType <PaymentReward>().ToArray(); var groupedByPaymentMethodRewards = allPaymentRewards.GroupBy(x => x.PaymentMethod); foreach (var paymentRewards in groupedByPaymentMethodRewards) { var bestPaymentReward = GetBestAmountReward(currentPaymentAmount, paymentRewards); if (bestPaymentReward != null) { result.Rewards.Add(bestPaymentReward); } } //best catalog item promotion var allItemsRewards = rewards.OfType <CatalogItemAmountReward>().ToArray(); var groupRewards = allItemsRewards.GroupBy(x => x.ProductId).Where(x => x.Key != null); foreach (var groupReward in groupRewards) { var item = promoContext.PromoEntries.FirstOrDefault(x => x.ProductId == groupReward.Key); if (item != null) { var bestItemReward = GetBestAmountReward(item.Price, item.Quantity, groupReward); if (bestItemReward != null) { result.Rewards.Add(bestItemReward); } } } //best order promotion var cartSubtotalRewards = rewards.OfType <CartSubtotalReward>().Where(x => x.IsValid).OrderByDescending(x => x.GetRewardAmount(promoContext.CartTotal, 1)); var cartSubtotalReward = cartSubtotalRewards.FirstOrDefault(x => !string.IsNullOrEmpty(x.Coupon)) ?? cartSubtotalRewards.FirstOrDefault(); if (cartSubtotalReward != null) { result.Rewards.Add(cartSubtotalReward); } //Gifts rewards.OfType <GiftReward>().ToList().ForEach(x => result.Rewards.Add(x)); //Special offer rewards.OfType <SpecialOfferReward>().ToList().ForEach(x => result.Rewards.Add(x)); } return(result); }
public async Task <ActionResult> Edit([Bind(Include = "WorkOrderId,CustomerId,OrderDateTime,TargetDateTime,DropDeadDateTime,Description,WorkOrderStatus,CertificationRequirements,CurrentWorkerId,ReworkNotes,RowVersion")] WorkOrder workOrder, string command) { if (ModelState.IsValid) { //Populate Parts and Labors workOrder.Parts = _applicationDbContext.Parts.Where(p => p.WorkOrderId == workOrder.WorkOrderId).ToList(); workOrder.Labors = _applicationDbContext.Labors.Where(p => p.WorkOrderId == workOrder.WorkOrderId).ToList(); PromotionResult promotionResult = new PromotionResult(); if (command == "Save") { promotionResult.Success = true; } else if (command == "Claim") { promotionResult = workOrder.ClaimWorkListItem(User.Identity.GetUserId()); } else if (command == "Relinquish") { promotionResult = workOrder.RelinquishWorkListItem(); } else { promotionResult = workOrder.PromoteWorkListItem(command); } if (!promotionResult.Success) { TempData["MessageToClient"] = promotionResult.Message; } //try //{ // var zero = 0; // var test = 1 / zero; //} //catch (Exception ex) //{ // Log4NetHelper.Log(null, LogLevel.ERROR, "WorkOrders", workOrder.WorkOrderId, User.Identity.Name, ex); //} _applicationDbContext.Entry(workOrder).State = EntityState.Modified; try { await _applicationDbContext.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (command == "Claim") { TempData["MessageToClient"] = String.Format("Someone else has claimed work order {0} since you retrieved it.", workOrder.WorkOrderId); } else { TempData["MessageToClient"] = String.Format("Someone else has modified work order {0} since you retrieved it.", workOrder.WorkOrderId); } return(RedirectToAction("Index", "WorkList")); } //Audit Trail Log4NetHelper.Log(promotionResult.Message, LogLevel.INFO, workOrder.EntityFormalNamePlural, workOrder.Id, User.Identity.Name, null); if (command == "Claim" && promotionResult.Success) { return(RedirectToAction("Edit", workOrder.WorkOrderId)); } return(RedirectToAction("Index", "WorkList")); } return(View(workOrder)); }
public void PromotionResultChanged(PromotionResult entity, UpdateOperations operation) { CheckIsAdminOrSystem(); }
public PromotionResult ProcessEvent(IMarketingEvent markertingEvent) { var retVal = new PromotionResult(); var promotions = _promotionService.GetActivePromotions(); foreach (var promotion in promotions) { var rewards = promotion.ProcessEvent(markertingEvent).Where(x => x != null); foreach (var promotionReward in rewards) { retVal.Rewards.Add(promotionReward); } } return retVal; }
public async Task <ActionResult> Edit([Bind(Include = "WorkOrderId,CustomerId,OrderDateTime,TargetDateTime,DropDeadDateTime,Description,WorkOrderStatus,CertificationRequirements,CurrentWorkerId,ReworkNotes,RowVersion")] WorkOrder workOrder, string command) { if (ModelState.IsValid) { workOrder.Parts = db.Parts.Where(p => p.WorkOrderId == workOrder.WorkOrderId).ToList(); workOrder.Labors = db.Labors.Where(l => l.WorkOrderId == workOrder.WorkOrderId).ToList(); PromotionResult pr = new PromotionResult(); if (command == "Save") { pr.Success = true; pr.Message = String.Format("Changes to work order {0} have been successfully saved.", workOrder.Id); Log4NetHelper.Log(pr.Message, LogLevel.INFO, workOrder.EntityFormalNamePlural, workOrder.Id, User.Identity.Name, null); } else if (command == "Claim") { pr = workOrder.ClaimWorkListItem(User.Identity.GetUserId()); } else if (command == "Relinquish") { pr = workOrder.RelinquishWorkListItem(); } else { pr = workOrder.PromoteWorkListItem(command); } if (!pr.Success) { TempData["MessageToClient"] = pr.Message; } //try //{ // var zero = 0; // var test = 1 / zero; //} //catch (Exception ex) //{ // Log4NetHelper.Log(null, LogLevel.ERROR, "WorkOrders", workOrder.WorkOrderId, User.Identity.Name, ex); //} //Now is handle by the ClaimWorkOrder method //workOrder.CurrentWorkerId = User.Identity.GetUserId(); db.Entry(workOrder).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException ex) { if (command == "Claim") { TempData["MessageToClient"] = String.Format("Someone else has claimed work order {0} since you retrieve it.", workOrder.WorkOrderId); } else { TempData["MessageToClient"] = String.Format("Someone else has modified work order {0} since you retrieve it.", workOrder.WorkOrderId); } return(RedirectToAction("Index", "WorkList")); } Log4NetHelper.Log(pr.Message, LogLevel.INFO, workOrder.EntityFormalNamePlural, workOrder.Id, User.Identity.Name, null); if (command == "Claim" && pr.Success) { return(RedirectToAction("Edit", workOrder.WorkOrderId)); } return(RedirectToAction("Index", "WorkList")); } //ViewBag.CurrentWorkerId = new SelectList(db.ApplicationUsers, "Id", "FirstName", workOrder.CurrentWorkerId); //ViewBag.CustomerId = new SelectList(db.Customers, "CustomerId", "AccountNumber", workOrder.CustomerId); return(View(workOrder)); }
protected virtual void ApplyDiscountToOrderLines(PromotionResult promotionResult, OrderLine orderLine, CustomerOrder customerOrder) { CustomerOrderPromotion appliedPromotion = customerOrder.CustomerOrderPromotions.FirstOrDefault <CustomerOrderPromotion>((Func <CustomerOrderPromotion, bool>)(p => p.PromotionId == promotionResult.PromotionId)); List <OrderLine> list = new List <OrderLine>(); list.Add(orderLine); if (SiteContext.Current != null && SiteContext.Current.ShipTo != null) { if (string.IsNullOrEmpty(orderLine.CostCode)) { //orderLine.PromotionResult = promotionResult; ProductPromotionHelper_Brasseler helper = new ProductPromotionHelper_Brasseler(this.pricingPipeline, this.promotionAmountProvider); IDictionary <Guid, ProductPriceDto> pricingServiceResult = helper.GetPricingServiceResult((IEnumerable <OrderLine>)list); ProductPriceDto productPriceDto = pricingServiceResult.First(o => o.Key == orderLine.Id).Value; Decimal UnitNetPrice = orderLine.UnitNetPrice; // Check current flow of Customer. HelperUtility helperUtility = new HelperUtility(); var currentCustomer = helperUtility.GetCurrentCustomerFlow(customerOrder); if (currentCustomer.CustomProperties.Where(x => x.Name.EqualsIgnoreCase("SubscriptionDiscount")).Count() > 0) { var amount = currentCustomer.CustomProperties.FirstOrDefault(x => x.Name.EqualsIgnoreCase("SubscriptionDiscount")).Value; if (string.IsNullOrEmpty(amount)) { return; } Decimal?subscriptionDiscount = Decimal.Parse(amount, CultureInfo.InvariantCulture); //return if subscription discount is zero if (subscriptionDiscount < 1) { return; } Decimal percent = subscriptionDiscount.Value / new Decimal(100); //BUSA-463 Subscription: Hold previous ActualPrice to calculate discount for this promotion orderLine.CostCode = orderLine.UnitNetPrice.ToString(CultureInfo.InvariantCulture); var num1 = NumberHelper.ApplyDiscount(UnitNetPrice, percent); //if (orderLine.PromotionResult != null) //{ // if (!(orderLine.UnitNetPrice < num1)) // { // CustomerOrderPromotion deleted = customerOrder.CustomerOrderPromotions.FirstOrDefault<CustomerOrderPromotion>((Func<CustomerOrderPromotion, bool>)(p => // { // Guid? orderLineId = p.OrderLineId; // Guid id = orderLine.Id; // if (!orderLineId.HasValue) // return false; // if (!orderLineId.HasValue) // return true; // return orderLineId.GetValueOrDefault() == id; // })); // if (deleted != null) // { // customerOrder.CustomerOrderPromotions.Remove(deleted); // this.UnitOfWork.GetRepository<CustomerOrderPromotion>().Delete(deleted); // } // } // else // return; //} //orderLine.PromotionResult = promotionResult; orderLine.UnitListPrice = productPriceDto.UnitListPrice; orderLine.UnitRegularPrice = productPriceDto.UnitRegularPrice; orderLine.UnitNetPrice = num1; orderLine.UnitNetPrice = orderLine.UnitNetPrice < Decimal.Zero ? Decimal.Zero : orderLine.UnitNetPrice; orderLine.TotalRegularPrice = NumberHelper.RoundCurrency(orderLine.UnitListPrice * orderLine.QtyOrdered); orderLine.TotalNetPrice = NumberHelper.RoundCurrency(orderLine.UnitNetPrice * orderLine.QtyOrdered); this.AddOrUpdateCustomerOrderPromotion(customerOrder, appliedPromotion, orderLine, promotionResult); } } } }