public override void ApplyPromotionResult(CustomerOrder customerOrder)
        {
            CustomerOrderPromotion customerOrderPromotion = customerOrder.CustomerOrderPromotions.FirstOrDefault <CustomerOrderPromotion>((Func <CustomerOrderPromotion, bool>)(p => p.PromotionId == this.PromotionResult.PromotionId));

            if (customerOrderPromotion == null)
            {
                return;
            }
            customerOrderPromotion.Amount = new Decimal?(this.PromotionProvider.GetAppliedAmount(customerOrderPromotion, string.Empty));
        }
        /// <summary>The apply promotion result.</summary>
        /// <param name="customerOrder">The customer order.</param>
        public override void ApplyPromotionResult(CustomerOrder customerOrder)
        {
            if (!this.PromotionResult.Amount.HasValue)
            {
                throw new ArgumentNullException("Amount");
            }
            if (this.PromotionResult.Amount.Value < Decimal.Zero)
            {
                throw new ArgumentOutOfRangeException("Amount");
            }
            if (this.PromotionResult.Product == null)
            {
                throw new ArgumentNullException("Product");
            }
            CustomerOrderPromotion appliedPromotion = customerOrder.CustomerOrderPromotions.FirstOrDefault <CustomerOrderPromotion>((Func <CustomerOrderPromotion, bool>)(p => p.PromotionId == this.PromotionResult.PromotionId));

            foreach (OrderLine orderLine1 in customerOrder.OrderLines.Where <OrderLine>((Func <OrderLine, bool>)(ol =>
            {
                if (!ol.IsPromotionItem)
                {
                    return(ol.Product.Id == this.PromotionResult.Product.Id);
                }
                return(false);
            })))
            {
                OrderLine orderLine = orderLine1;
                if (!(this.PromotionResult.Amount.Value > orderLine.QtyOrdered))
                {
                    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);
                    }
                    orderLine.PromotionResult = this.PromotionResult;
                    orderLine.QtyOrdered      = this.PromotionResult.Amount.Value;
                    this.AddOrUpdateCustomerOrderPromotion(customerOrder, appliedPromotion, orderLine, this.PromotionResult);
                }
            }
        }
예제 #3
0
        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);
            }
        }
 /// <summary>The product discount.</summary>
 /// <param name="customerOrderPromotion">The customer order promotion.</param>
 /// <returns>The <see cref="T:System.Decimal" />.</returns>
 public override Decimal ProductDiscount(CustomerOrderPromotion customerOrderPromotion)
 {
     if (customerOrderPromotion.OrderLine != null)
     {
         Guid?id1 = customerOrderPromotion.OrderLine.PromotionResult?.Id;
         Guid id2 = this.PromotionResult.Id;
         if ((id1.HasValue ? (id1.HasValue ? (id1.GetValueOrDefault() == id2 ? 1 : 0) : 1) : 0) != 0 && !customerOrderPromotion.OrderLine.Product.IsQuoteRequired)
         {
             Decimal?unitRegularPrice = 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?.UnitRegularPrice;
             Decimal qtyOrdered = customerOrderPromotion.OrderLine.QtyOrdered;
             Decimal?nullable   = unitRegularPrice;
             Decimal?amount     = this.PromotionResult.Amount;
             Decimal num        = Decimal.Zero;
             return(NumberHelper.RoundCurrency(qtyOrdered * num));
         }
     }
     return(Decimal.Zero);
 }
        //public override Decimal ProductDiscount(CustomerOrder customerOrder)
        //{
        //    return Decimal.Zero;
        //}

        public override void ApplyPromotionResult(CustomerOrder customerOrder)
        {
            //BUSA- 463 Subscrition- Not include promotional product in subscrition order
            if (!customerOrder.Status.EqualsIgnoreCase("Saved") && !customerOrder.Status.EqualsIgnoreCase("SubscriptionOrder") && !customerOrder.Status.EqualsIgnoreCase("Return Requested"))
            {
                if (!this.PromotionResult.Amount.HasValue)
                {
                    throw new ArgumentNullException("Amount");
                }
                if (this.PromotionResult.Amount.Value <= Decimal.Zero)
                {
                    throw new ArgumentOutOfRangeException("Amount");
                }
                if (this.PromotionResult.Product == null)
                {
                    throw new ArgumentNullException("Product");
                }
                if (this.PromotionResult.Product.TrackInventory && (!this.InventorySettings.AllowBackOrder || this.PromotionResult.Product.IsDiscontinued))
                {
                    ProductInventory inventory = this.InventoryPipeline.Value.GetQtyOnHand(new GetQtyOnHandParameter(true)
                    {
                        GetInventoryParameter = new GetInventoryParameter()
                        {
                            ProductIds = new List <Guid>()
                            {
                                this.PromotionResult.Product.Id
                            },
                            Products = new List <Product>()
                            {
                                this.PromotionResult.Product
                            }
                        }
                    }).Inventories[this.PromotionResult.Product.Id];
                    if ((inventory != null ? inventory.QtyOnHand : Decimal.Zero) < this.PromotionResult.Amount.Value)
                    {
                        return;
                    }
                }
                IProductUtilities productUtilities = this.ProductUtilities;
                List <Product>    products         = new List <Product>();
                products.Add(this.PromotionResult.Product);
                Customer billTo = SiteContext.Current.BillTo;
                Customer shipTo = SiteContext.Current.ShipTo;
                if (productUtilities.GetRestrictedProductIds(products, billTo, shipTo).Any <Guid>())
                {
                    return;
                }
                OrderLine orderLine1 = new OrderLine();
                orderLine1.UnitOfMeasure = this.PromotionResult.Product.UnitOfMeasure;
                orderLine1.Id            = Guid.NewGuid();
                // BUSA-1319: Limit Qty Per Product
                var maxProductQty = this.PromotionResult.Product.CustomProperties.Where(x => x.Name == "maxProductQty").Select(s => s.Value).FirstOrDefault() ?? "0";

                if (!string.IsNullOrEmpty(maxProductQty) && Convert.ToInt32(maxProductQty) != 0 && this.PromotionResult.Amount.Value > Convert.ToDecimal(maxProductQty))
                {
                    orderLine1.QtyOrdered = Convert.ToDecimal(maxProductQty);
                }
                else
                {
                    orderLine1.QtyOrdered = this.PromotionResult.Amount.Value;
                } // BUSA-1319: END
                OrderLine orderLine2 = orderLine1;
                this.OrderLineUtilities.SetProduct(orderLine2, this.PromotionResult.Product);
                PipelineHelper.VerifyResults((PipeResultBase)this.CartPipeline.AddCartLine(new Insite.Cart.Services.Pipelines.Parameters.AddCartLineParameter()
                {
                    Cart     = customerOrder,
                    CartLine = orderLine2
                }));
                CustomerOrderPromotion customerOrderPromotion = customerOrder.CustomerOrderPromotions.FirstOrDefault <CustomerOrderPromotion>((Func <CustomerOrderPromotion, bool>)(p => p.PromotionId == this.PromotionResult.PromotionId));
                if (customerOrderPromotion != null)
                {
                    customerOrderPromotion.OrderLineId = new Guid?(orderLine2.Id);
                    customerOrderPromotion.Amount      = new Decimal?(new Decimal());
                }
                orderLine2.PromotionResult  = this.PromotionResult;
                orderLine2.IsPromotionItem  = true;
                orderLine2.UnitNetPrice     = Decimal.Zero;
                orderLine2.UnitRegularPrice = this.PromotionResult.Product.BasicListPrice;

                // BUSA-683 : Volume Discount Promotion -Issue when user cart qualifies add free product promotion & volume discount group.
                var orderLineCount = customerOrder.OrderLines.Where(x => x.Id == new Guid()).Count();

                //start BUSA-683 Volume Discount Promotion -Issue when user's cart qualifies add free product promotion & volume discount group
                if (this.PromotionResult.Promotion.RuleManager.RuleClauses.Where(x => x.CriteriaType == "OverideVolumeDiscount").Count() > 0)
                {
                    var vdgOverride = this.PromotionResult.Promotion.RuleManager.RuleClauses.Where(x => x.CriteriaType == "OverideVolumeDiscount").FirstOrDefault().CriteriaValue;
                    //check if override VDG
                    if (vdgOverride == "Yes")
                    {
                        var ruleProductId = this.PromotionResult.Promotion.RuleManager.RuleClauses.Where(x => x.CriteriaType == "OrderedProduct").Count() > 0 ? this.PromotionResult.Promotion.RuleManager.RuleClauses.Where(x => x.CriteriaType == "OrderedProduct").FirstOrDefault().SimpleValue : string.Empty;

                        var ruleOrderLine = customerOrder.OrderLines.Where(x => x.ProductId.ToString() == ruleProductId.ToString()).FirstOrDefault();
                        if (ruleOrderLine != null && !string.IsNullOrEmpty(ruleOrderLine.ConfigurationViewModel))
                        {
                            ruleOrderLine.UnitNetPrice = ruleOrderLine.UnitListPrice;
                            ruleOrderLine.SmartPart    = string.Empty;

                            ruleOrderLine.ConfigurationViewModel = "false";
                            var grpDescription = ruleOrderLine.GetProperty("GrpDescription", "");

                            if (!string.IsNullOrEmpty(grpDescription))
                            {
                                ruleOrderLine.SetProperty("GrpDescription", " ");
                            }

                            CartHelper_Brasseler helper = new CartHelper_Brasseler(this.pricingPipeline);
                            helper.UpdateVolumeGrpPricing(customerOrder, ruleOrderLine.Product.PriceBasis, UnitOfWork);
                            if (orderLineCount == 0)
                            {
                                PipelineHelper.VerifyResults((PipeResultBase)this.CartPipeline.AddCartLine(new Insite.Cart.Services.Pipelines.Parameters.AddCartLineParameter()
                                {
                                    Cart     = customerOrder,
                                    CartLine = orderLine1
                                }));
                                orderLine1.PromotionResult = this.PromotionResult;

                                orderLine1.IsPromotionItem  = true;
                                orderLine1.UnitNetPrice     = Decimal.Zero;
                                orderLine1.UnitRegularPrice = this.PromotionResult.Product.BasicListPrice;
                            }
                        }
                        else
                        {
                            if (orderLineCount == 0)
                            {
                                PipelineHelper.VerifyResults((PipeResultBase)this.CartPipeline.AddCartLine(new Insite.Cart.Services.Pipelines.Parameters.AddCartLineParameter()
                                {
                                    Cart     = customerOrder,
                                    CartLine = orderLine1
                                }));
                                orderLine1.PromotionResult = this.PromotionResult;

                                orderLine1.IsPromotionItem  = true;
                                orderLine1.UnitNetPrice     = Decimal.Zero;
                                orderLine1.UnitRegularPrice = this.PromotionResult.Product.BasicListPrice;
                            }
                        }
                    }
                    else
                    {
                        //Do nothing
                    }
                }
                //end BUSA-683 Volume Discount Promotion -Issue when user's cart qualifies add free product promotion & volume discount group
                else
                {
                    PipelineHelper.VerifyResults((PipeResultBase)this.CartPipeline.AddCartLine(new Insite.Cart.Services.Pipelines.Parameters.AddCartLineParameter()
                    {
                        Cart     = customerOrder,
                        CartLine = orderLine1
                    }));
                    orderLine1.PromotionResult = this.PromotionResult;

                    orderLine1.IsPromotionItem  = true;
                    orderLine1.UnitNetPrice     = Decimal.Zero;
                    orderLine1.UnitRegularPrice = this.PromotionResult.Product.BasicListPrice;
                }
            }
        }
예제 #6
0
        decimal orderPromoRank = 0;// BUSA-530 : Promotion is unavailable error message is displayed when user applying second coupon code

        protected override IList <Promotion> GetQualifyingPromotions(CustomerOrder customerOrder)
        {
            List <Promotion>     promotionList             = new List <Promotion>();
            IEnumerable <string> orderPromotionCodes       = customerOrder.OrderPromotionCodes.Select <OrderPromotionCode, string>((Func <OrderPromotionCode, string>)(o => o.Code));
            List <object>        rulesEngineContextObjects = new List <object>()
            {
                (object)customerOrder,
                (object)customerOrder.Customer
            };
            UserProfileDto userProfile = SiteContext.Current.UserProfileDto;

            if (userProfile != null)
            {
                rulesEngineContextObjects.Add((object)userProfile);
            }
            //IList<Promotion> promotions = this.Promotions;
            IRepository <CustomerOrderPromotion> promotions = this.UnitOfWork.GetRepository <CustomerOrderPromotion>();
            IOrderedEnumerable <Promotion>       source     = this.Promotions.OrderBy <Promotion, bool>(new Func <Promotion, bool>(this.CheckIfPromotionHasOrderPromotionRule));

            foreach (Promotion prd in source.Where <Promotion>((Func <Promotion, bool>)(promotion =>
            {
                if (promotion.PromoCode.IsBlank() || this.ListContainsPromotionCode(orderPromotionCodes, promotion.PromoCode))
                {
                    return(this.RulesEngine.Execute((IBusinessObject)promotion, rulesEngineContextObjects));
                }
                return(false);
            })))
            {
                if (prd.PromotionResults.Where(p => p.PromotionResultType == "PercentOffOrder" || p.PromotionResultType == "AmountOffOrder").Count() > 0)
                {
                    // BUSA-530 : Promotion is unavailable error message is displayed when user applying second coupon code Starts
                    if (string.IsNullOrEmpty(prd.PromoCode))
                    {
                        if (prd.Rank > orderPromoRank)
                        {
                            orderPromoRank = prd.Rank;
                        }
                    }
                    // BUSA-530 : Promotion is unavailable error message is displayed when user applying second coupon code Ends
                }
            }

            // BUSA-530 : Promotion is unavailable error message is displayed when user applying second coupon code Starts
            foreach (Promotion promotion in source.Where <Promotion>((Func <Promotion, bool>)(promotion =>
            {
                if (promotion.PromoCode.IsBlank() || this.ListContainsPromotionCode(orderPromotionCodes, promotion.PromoCode))
                {
                    return(this.RulesEngine.Execute((IBusinessObject)promotion, rulesEngineContextObjects));
                }
                return(false);
            })))
            {
                if ((promotion.PromotionResults.Where(p => p.PromotionResultType == "PercentOffOrder" || p.PromotionResultType == "AmountOffOrder").Count() > 0))
                {
                    if (orderPromoRank <= promotion.Rank && string.IsNullOrEmpty(promotion.PromoCode))
                    {
                        CustomerOrderPromotion inserted = new CustomerOrderPromotion()
                        {
                            CustomerOrderId = customerOrder.Id,
                            CustomerOrder   = customerOrder,
                            PromotionId     = promotion.Id,
                            Promotion       = this.UnitOfWork.GetRepository <Promotion>().Get(promotion.Id)
                        };
                        promotionList.Add(promotion);
                        customerOrder.CustomerOrderPromotions.Add(inserted);
                        promotions.Insert(inserted);
                    }
                    else
                    {
                        if (customerOrder.OrderPromotionCodes != null)
                        {
                            foreach (var pro in customerOrder.CustomerOrderPromotions)
                            {
                                if (pro.Promotion.PromotionResults.Where(p => p.PromotionResultType == "PercentOffOrder" || p.PromotionResultType == "AmountOffOrder").Count() > 0)
                                {
                                    if (string.IsNullOrEmpty(pro.Promotion.PromoCode))
                                    {
                                        promotionList.Remove(pro.Promotion);
                                        customerOrder.CustomerOrderPromotions.Remove(pro);
                                        promotions.Delete(pro);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(promotion.PromoCode) && orderPromoRank <= promotion.Rank)
                    {
                        if (promotion.PromotionResults.Where(p => p.PromotionResultType == "PercentOffOrder" || p.PromotionResultType == "AmountOffOrder").Count() > 0)
                        {
                            if (!string.IsNullOrEmpty(promotion.PromoCode))
                            {
                                CustomerOrderPromotion inserted = new CustomerOrderPromotion()
                                {
                                    CustomerOrderId = customerOrder.Id,
                                    CustomerOrder   = customerOrder,
                                    PromotionId     = promotion.Id,
                                    Promotion       = this.UnitOfWork.GetRepository <Promotion>().Get(promotion.Id)
                                };
                                promotionList.Add(promotion);
                                customerOrder.CustomerOrderPromotions.Add(inserted);
                                promotions.Insert(inserted);
                            }
                        }
                    }
                }
                //BUSA-574 : Promotion with highest rank overrides previously applied promotion on category level Starts
                else if (promotion.RuleManager.RuleClauses.Where(x => x.CriteriaType == "OrderedProductCategory").Count() > 0)
                {
                    CustomerOrderPromotion inserted = new CustomerOrderPromotion()
                    {
                        CustomerOrderId = customerOrder.Id,
                        CustomerOrder   = customerOrder,
                        PromotionId     = promotion.Id,
                        Promotion       = this.UnitOfWork.GetRepository <Promotion>().Get(promotion.Id)
                    };
                    promotionList.Add(promotion);
                    customerOrder.CustomerOrderPromotions.Add(inserted);
                    promotions.Insert(inserted);
                }
                //BUSA-574 : Promotion with highest rank overrides previously applied promotion on category level Ends
                else
                {
                    //BUSA-569 : Bundle Promotion with highest rank overrides previous applied promotions Starts.
                    //BUSA-620 : Error with API call popup is displayed on PLP page Starts
                    Guid?productId = Guid.Empty;
                    if (promotion.PromotionResults.Count() > 0)
                    {
                        productId = promotion.PromotionResults.FirstOrDefault().ProductId;
                    }
                    //BUSA-620 : Error with API call popup is displayed on PLP page Ends
                    decimal productHighRank = 0;
                    foreach (Promotion prd in source.Where <Promotion>((Func <Promotion, bool>)(promotion1 =>
                    {
                        if (promotion1.PromoCode.IsBlank() || this.ListContainsPromotionCode(orderPromotionCodes, promotion1.PromoCode))
                        {
                            return(this.RulesEngine.Execute((IBusinessObject)promotion1, rulesEngineContextObjects));
                        }
                        return(false);
                    })))
                    {
                        if (!(prd.PromotionResults.Where(p => p.PromotionResultType == "PercentOffOrder" || p.PromotionResultType == "AmountOffOrder").Count() > 0))
                        {
                            if (string.IsNullOrEmpty(prd.PromoCode))
                            {
                                var a = prd.PromotionResults.Where(p => p.ProductId == productId).FirstOrDefault();
                                if (a != null && a.ProductId == productId)
                                {
                                    if (prd.Rank > productHighRank)
                                    {
                                        productHighRank = prd.Rank;
                                    }
                                }
                            }
                        }
                    }
                    if (productHighRank <= promotion.Rank && string.IsNullOrEmpty(promotion.PromoCode))
                    {
                        CustomerOrderPromotion inserted = new CustomerOrderPromotion()
                        {
                            CustomerOrderId = customerOrder.Id,
                            CustomerOrder   = customerOrder,
                            PromotionId     = promotion.Id,
                            Promotion       = this.UnitOfWork.GetRepository <Promotion>().Get(promotion.Id)
                        };
                        promotionList.Add(promotion);
                        customerOrder.CustomerOrderPromotions.Add(inserted);
                        promotions.Insert(inserted);
                    }

                    if (!string.IsNullOrEmpty(promotion.PromoCode) && productHighRank <= promotion.Rank)
                    {
                        if (!string.IsNullOrEmpty(promotion.PromoCode))
                        {
                            CustomerOrderPromotion inserted = new CustomerOrderPromotion()
                            {
                                CustomerOrderId = customerOrder.Id,
                                CustomerOrder   = customerOrder,
                                PromotionId     = promotion.Id,
                                Promotion       = this.UnitOfWork.GetRepository <Promotion>().Get(promotion.Id)
                            };
                            promotionList.Add(promotion);
                            customerOrder.CustomerOrderPromotions.Add(inserted);
                            promotions.Insert(inserted);
                        }
                    }

                    //BUSA-569 : Bundle Promotion with highest rank overrides previous applied promotions Ends.
                }

                // BUSA-463 : Subscription Starts
                if (promotion.PromotionResults.Where(p => p.PromotionResultType == "DiscountSubscriptionProduct").Count() > 0)
                {
                    var subscriptionPromotionCount = promotionList.Where(x => x.PromotionResults.Where(p => p.PromotionResultType == "DiscountSubscriptionProduct").Count() > 0).Count();
                    if (subscriptionPromotionCount == 0)
                    {
                        {
                            CustomerOrderPromotion inserted = new CustomerOrderPromotion()
                            {
                                CustomerOrderId = customerOrder.Id,
                                CustomerOrder   = customerOrder,
                                PromotionId     = promotion.Id,
                                Promotion       = this.UnitOfWork.GetRepository <Promotion>().Get(promotion.Id)
                            };
                            promotionList.Add(promotion);
                            customerOrder.CustomerOrderPromotions.Add(inserted);
                            promotions.Insert(inserted);
                        }
                    }
                }
                // BUSA-463 : Subscription Ends

                if (!this.CheckoutSettings.AllowMultiplePromotions)
                {
                    return((IList <Promotion>)promotionList);
                }
            }
            // BUSA-530 : Promotion is unavailable error message is displayed when user applying second coupon code Ends

            // BUSA-462 : Subscription. Display only SmartSupply Promotions on SmartSupply Detail page.
            if (customerOrder.Status.EqualsIgnoreCase("SubscriptionOrder") && promotionList.Count() > 0)
            {
                List <Promotion> lstPromo = new List <Promotion>();

                promotionList.ForEach(x =>
                {
                    if (x.PromotionResults.Where(r => r.PromotionResultType == "DiscountSubscriptionProduct").Count() > 0 || x.PromotionResults.Where(r => r.PromotionResultType == "DiscountSubscriptionShipping").Count() > 0)
                    {
                        lstPromo.Add(x);
                    }
                });

                var lstPromotionNotApplicable = promotionList.Except(lstPromo).ToList();

                foreach (var p in lstPromotionNotApplicable)
                {
                    promotionList.Remove(p);
                    var cop = customerOrder.CustomerOrderPromotions.Where(x => x.PromotionId == p.Id)?.FirstOrDefault();
                    customerOrder.CustomerOrderPromotions.Remove(cop);
                    promotions.Delete(cop);
                }
            }

            return((IList <Promotion>)promotionList);
        }
        protected CustomerOrder CreateNewCart(IUnitOfWork unitOfWork, CustomerOrder customerOrder, AddRmaParameter parameter, AddRmaResult result)
        {
            CustomSettings customSettings = new CustomSettings();
            CustomerOrder  cart           = new CustomerOrder()
            {
                Id                       = Guid.NewGuid(),
                OrderNumber              = customSettings.RMA_OrderNumberPrefix + customerOrder.OrderNumber.Substring(1),
                OrderDate                = DateTimeProvider.Current.Now,
                Customer                 = customerOrder.Customer,
                ShipTo                   = customerOrder.ShipTo,
                DropShipCustomer         = customerOrder.DropShipCustomer,
                WebsiteId                = customerOrder.WebsiteId,
                Website                  = customerOrder.Website,
                Affiliate                = customerOrder.Affiliate,
                ShipVia                  = customerOrder.ShipVia,
                InitiatedByUserProfile   = customerOrder.InitiatedByUserProfile,
                InitiatedByUserProfileId = customerOrder.InitiatedByUserProfileId,
                CurrencyId               = customerOrder.CurrencyId,
                PlacedByUserName         = customerOrder.PlacedByUserName,
                PlacedByUserProfile      = customerOrder.PlacedByUserProfile,
                Status                   = "Return Requested",
                CustomerPO               = customerOrder.CustomerPO,
                Notes                    = customerOrder.Notes,
                Type                     = "Return Requested",
                Salesperson              = customerOrder.Salesperson,
                SalespersonId            = customerOrder.SalespersonId,
                PlacedByUserProfileId    = customerOrder.PlacedByUserProfileId,
                ShippingCharges          = customerOrder.ShippingCharges
            };

            cart.OrderPromotionCodes           = customerOrder.OrderPromotionCodes.ToList();
            cart.TermsCode                     = customerOrder.TermsCode;
            cart.ShippingCalculationNeededAsOf = DateTimeOffset.Now;

            this.CartPipeline.SetBillTo(new SetBillToParameter()
            {
                Cart   = cart,
                BillTo = cart.Customer
            });

            this.CartPipeline.SetShipTo(new SetShipToParameter()
            {
                Cart   = cart,
                ShipTo = cart.ShipTo
            });

            // Add the Returned Sequence in the Order Number
            var returnedSeq = unitOfWork.GetRepository <CustomerOrder>().GetTable().Where(x => x.OrderNumber.StartsWith(cart.OrderNumber)).Count();

            if (returnedSeq != 0)
            {
                returnedSeq += 1;
            }
            else
            {
                returnedSeq = 1;
            }
            cart.OrderNumber = cart.OrderNumber + "/" + returnedSeq;
            result.Properties.Add("ReturnNumber", cart.OrderNumber);

            // Getting the Invoice Number
            var invoiceNumber = string.Empty;

            if (!string.IsNullOrEmpty(result.OrderHistory.ErpOrderNumber))
            {
                var erpNumber    = result.OrderHistory.ErpOrderNumber.Split('-')[0];
                var invoiceQuery = (from ih in unitOfWork.GetRepository <InvoiceHistory>().GetTable()
                                    join ihl in unitOfWork.GetRepository <InvoiceHistoryLine>().GetTable()
                                    on ih.Id equals ihl.InvoiceHistoryId
                                    where ihl.ErpOrderNumber == erpNumber
                                    select ih.InvoiceNumber);
                if (!string.IsNullOrEmpty(invoiceQuery.FirstOrDefault()))
                {
                    invoiceNumber = invoiceQuery.FirstOrDefault().Split('-')[0].ToString();
                    result.Properties.Add("InvoiceNumber", invoiceNumber);
                }
            }

            foreach (var customProperty in customerOrder.CustomProperties)
            {
                cart.SetProperty(customProperty.Name, customProperty.Value);
            }

            List <int> qtyReturn = new List <int>();

            List <int> line          = new List <int>();
            var        chkReturnType = 0; // To check partial return or full return based on quantity return

            foreach (var ol in customerOrder.OrderLines.ToList())
            {
                RmaLineDto rmaLineDto = parameter.RmaLines.FirstOrDefault((RmaLineDto r) => r.Line.Equals(ol.Line)) ?? new RmaLineDto();
                if (rmaLineDto.RmaQtyRequested != 0)
                {
                    if (ol.IsPromotionItem.Equals(true))
                    {
                        line.Add(ol.Line);
                    }

                    Insite.Cart.Services.Pipelines.Parameters.AddCartLineParameter addCartLineParameter = new Insite.Cart.Services.Pipelines.Parameters.AddCartLineParameter();
                    addCartLineParameter.Cart             = cart;
                    addCartLineParameter.Product          = ol.Product;
                    addCartLineParameter.QtyOrdered       = rmaLineDto.RmaQtyRequested;
                    addCartLineParameter.UnitOfMeasure    = ol.UnitOfMeasure;
                    addCartLineParameter.CostCode         = ol.CostCode;
                    addCartLineParameter.Notes            = ol.Notes;
                    addCartLineParameter.CustomProperties = ol.CustomProperties.ToList();
                    qtyReturn.Add(rmaLineDto.RmaQtyRequested);

                    Insite.Cart.Services.Pipelines.Results.AddCartLineResult addCartLineResult = CartPipeline.AddCartLine(addCartLineParameter);
                    addCartLineResult.CartLine.SmartPart         = ol.SmartPart;
                    addCartLineResult.CartLine.UnitCost          = ol.UnitCost;
                    addCartLineResult.CartLine.UnitListPrice     = ol.UnitListPrice;
                    addCartLineResult.CartLine.UnitNetPrice      = ol.UnitNetPrice;
                    addCartLineResult.CartLine.UnitRegularPrice  = ol.UnitRegularPrice;
                    addCartLineResult.CartLine.TotalNetPrice     = ol.TotalNetPrice;
                    addCartLineResult.CartLine.TotalRegularPrice = ol.TotalRegularPrice;

                    if (ol.QtyOrdered > rmaLineDto.RmaQtyRequested)
                    {
                        chkReturnType += 1;
                    }
                }
            }

            if (chkReturnType != 0)
            {
                cart.Notes = invoiceNumber + "/" + 1; // 1 indicates the partial return
            }
            else if (customerOrder.OrderLines.Where(x => x.UnitNetPrice > 0).Count() > cart.OrderLines.Count())
            {
                cart.Notes = invoiceNumber + "/" + 1; // 1 indicates the partial return
            }
            else
            {
                cart.Notes = invoiceNumber + "/" + 0; // 0 indicates the full return
            }

            List <OrderLine> orderLineList = cart.OrderLines.ToList();

            for (int i = 0; i < orderLineList.Count; i++)
            {
                OrderLine orderLine = orderLineList[i];
                if (line.Contains(orderLine.Line))
                {
                    orderLine.IsPromotionItem = true;
                }
            }

            var totalQty = result.OrderHistory.OrderHistoryLines.Where(x => x.ProductErpNumber != "WEBDISCOUNT" && !line.Contains(Convert.ToInt32(x.LineNumber)) && (x.UnitNetPrice > 0 || x.QtyShipped < x.QtyOrdered)).Select(qty => qty.QtyOrdered).Sum();

            foreach (var promotion in customerOrder.CustomerOrderPromotions.ToList())
            {
                CustomerOrderPromotion orderPromotion = new CustomerOrderPromotion();
                orderPromotion.Id = new Guid();
                orderPromotion.CustomerOrderId  = cart.Id;
                orderPromotion.PromotionId      = promotion.PromotionId;
                orderPromotion.OrderLineId      = promotion.OrderLineId;
                orderPromotion.CustomProperties = promotion.CustomProperties;
                cart.CustomerOrderPromotions.Add(orderPromotion);

                if (promotion.OrderLineId == null && cart.Notes.Split('/')[1] == "1" && !promotion.Promotion.Name.ToLower().Contains("shipping") && totalQty != 0 && qtyReturn.Count > 0)
                {
                    orderPromotion.Amount = ((decimal)promotion.Amount / totalQty) * qtyReturn.Sum();
                }
                else
                {
                    orderPromotion.Amount = promotion.Amount;
                }
            }

            unitOfWork.GetRepository <CustomerOrder>().Insert(cart);
            unitOfWork.Save();

            return(cart);
        }
예제 #8
0
        public CustomerOrder CreateNewCart(IUnitOfWork unitOfWork, OrderHistory customerOrder, AddRmaParameter parameter, AddRmaResult result)
        {
            var orderNumber = string.Empty;

            if (string.IsNullOrEmpty(customerOrder.WebOrderNumber) && !string.IsNullOrEmpty(customerOrder.ErpOrderNumber))
            {
                orderNumber = customerOrder.ErpOrderNumber.Split('-')[0];
            }
            else
            {
                orderNumber = customerOrder.WebOrderNumber.Substring(0, 1) == "W" ? customerOrder.WebOrderNumber.Substring(1) : customerOrder.WebOrderNumber.Split('-')[0];
            }

            Customer customer = new Customer();

            if (string.IsNullOrEmpty(customerOrder.CustomerSequence) || customerOrder.CustomerSequence.Equals(customerOrder.CustomerNumber))
            {
                customer = unitOfWork.GetRepository <Customer>().GetTable().Where(x => x.CustomerNumber == customerOrder.CustomerNumber).FirstOrDefault();
            }
            else
            {
                customer = unitOfWork.GetRepository <Customer>().GetTable().Where(x => x.CustomerNumber == customerOrder.CustomerNumber && x.CustomerSequence == customerOrder.CustomerSequence).FirstOrDefault();
            }

            SiteContextDto siteContextDto = new SiteContextDto(SiteContext.Current);
            var            websiteId      = siteContextDto.Website.Id;
            var            website        = siteContextDto.Website;

            Salesperson salesperson = new Salesperson();

            salesperson = unitOfWork.GetRepository <Salesperson>().GetTable().Where(x => x.Name.Equals(customerOrder.Salesperson)).FirstOrDefault();

            ShipVia shipVia = unitOfWork.GetRepository <ShipVia>().GetTable().Where(x => x.ShipCode.ToLower().Equals(customerOrder.ShipCode.ToLower())).FirstOrDefault();

            CustomerOrder cart = new CustomerOrder()
            {
                Id              = new Guid(),
                OrderNumber     = customSettings.RMA_OrderNumberPrefix + orderNumber,
                OrderDate       = DateTimeProvider.Current.Now,
                Customer        = customer,
                WebsiteId       = websiteId,
                Website         = website,
                Status          = "Return Requested",
                CustomerPO      = customerOrder.CustomerPO,
                Notes           = customerOrder.Notes,
                Type            = "Return Requested",
                Salesperson     = salesperson,
                SalespersonId   = salesperson.Id,
                ShippingCharges = customerOrder.ShippingCharges,
                ShipCode        = customerOrder.ShipCode,
                ShipVia         = shipVia
            };

            foreach (var promotion in customerOrder.OrderHistoryPromotions.ToList())
            {
                CustomerOrderPromotion orderPromotion = new CustomerOrderPromotion()
                {
                    Id = new Guid(),
                    CustomerOrderId  = cart.Id,
                    PromotionId      = promotion.PromotionId,
                    OrderLineId      = promotion.OrderHistoryLineId,
                    Amount           = promotion.Amount,
                    CustomProperties = promotion.CustomProperties
                };
                cart.CustomerOrderPromotions.Add(orderPromotion);
            }

            this.CartPipeline.SetBillTo(new SetBillToParameter()
            {
                Cart   = cart,
                BillTo = cart.Customer
            });

            this.CartPipeline.SetShipTo(new SetShipToParameter()
            {
                Cart   = cart,
                ShipTo = cart.ShipTo
            });

            // Add the Returned Sequence in the Order Number
            var returnedSeq = unitOfWork.GetRepository <CustomerOrder>().GetTable().Where(x => x.OrderNumber.StartsWith(cart.OrderNumber)).Count();

            if (returnedSeq != 0)
            {
                returnedSeq += 1;
            }
            else
            {
                returnedSeq = 1;
            }
            cart.OrderNumber = cart.OrderNumber + "/" + returnedSeq;

            // Getting the Invoice Number
            var invoiceNumber = string.Empty;

            if (!string.IsNullOrEmpty(result.OrderHistory.ErpOrderNumber))
            {
                var erpNumber    = result.OrderHistory.ErpOrderNumber.Split('-')[0];
                var invoiceQuery = (from ih in unitOfWork.GetRepository <InvoiceHistory>().GetTable()
                                    join ihl in unitOfWork.GetRepository <InvoiceHistoryLine>().GetTable()
                                    on ih.Id equals ihl.InvoiceHistoryId
                                    where ihl.ErpOrderNumber == erpNumber
                                    select ih.InvoiceNumber);
                if (!string.IsNullOrEmpty(invoiceQuery.FirstOrDefault()))
                {
                    invoiceNumber = invoiceQuery.FirstOrDefault().Split('-')[0].ToString();
                }
            }

            foreach (var customProperty in customerOrder.CustomProperties)
            {
                cart.SetProperty(customProperty.Name, customProperty.Value);
            }

            var chkReturnType = 0; // To check partial return or full return based on quantity return

            foreach (var ol in customerOrder.OrderHistoryLines.ToList())
            {
                RmaLineDto rmaLineDto = parameter.RmaLines.FirstOrDefault((RmaLineDto r) => r.Line.Equals(ol.LineNumber)) ?? new RmaLineDto();
                if (rmaLineDto.RmaQtyRequested != 0)
                {
                    AddCartLineParameter addCartLineParameter = new AddCartLineParameter();
                    addCartLineParameter.Cart             = cart;
                    addCartLineParameter.Product          = unitOfWork.GetRepository <Product>().GetTable().Where(x => x.Name.Equals(ol.ProductErpNumber)).FirstOrDefault();
                    addCartLineParameter.QtyOrdered       = rmaLineDto.RmaQtyRequested;
                    addCartLineParameter.UnitOfMeasure    = ol.UnitOfMeasure;
                    addCartLineParameter.Notes            = ol.Notes;
                    addCartLineParameter.CustomProperties = ol.CustomProperties.ToList();

                    Insite.Cart.Services.Pipelines.Results.AddCartLineResult addCartLineResult = CartPipeline.AddCartLine(addCartLineParameter);
                    addCartLineResult.CartLine.UnitCost          = ol.UnitCost;
                    addCartLineResult.CartLine.UnitListPrice     = addCartLineParameter.Product.BasicListPrice;
                    addCartLineResult.CartLine.UnitNetPrice      = ol.UnitNetPrice;
                    addCartLineResult.CartLine.UnitRegularPrice  = ol.UnitRegularPrice;
                    addCartLineResult.CartLine.TotalNetPrice     = ol.TotalNetPrice;
                    addCartLineResult.CartLine.TotalRegularPrice = ol.TotalRegularPrice;

                    if (ol.QtyOrdered > rmaLineDto.RmaQtyRequested)
                    {
                        chkReturnType += 1;
                    }
                }
            }

            if (chkReturnType != 0 || customerOrder.OrderHistoryLines.Count() > cart.OrderLines.Count())
            {
                cart.Notes = invoiceNumber + "/" + 1; // 1 indicates the partial return
            }
            else
            {
                cart.Notes = invoiceNumber + "/" + 0; // 0 indicates the full return
            }

            unitOfWork.GetRepository <CustomerOrder>().Insert(cart);
            unitOfWork.Save();

            return(cart);
        }
예제 #9
0
        public override Decimal ProductDiscount(CustomerOrderPromotion customerOrderPromotion)
        {
            ProductPromotionHelper_Brasseler helper = new ProductPromotionHelper_Brasseler(this.PricingPipeline, this.promotionAmountProvider);

            return(helper.GetPercentOrAmountProductDiscount(this.PromotionResult, customerOrderPromotion));
        }
예제 #10
0
        public override Decimal ProductDiscount(CustomerOrderPromotion customerOrderPromotion)
        {
            //return customerOrderPromotion.CustomerOrder.OrderLines.Where<OrderLine>((Func<OrderLine, bool>)(o =>
            //{
            //    if (o.CustomProperties.Where(x => x.Name.EqualsIgnoreCase("IsSubscriptionOpted")).Count() > 0)
            //    {
            //        var IsSubscriptionOpted = o.CustomProperties.FirstOrDefault(x => x.Name.EqualsIgnoreCase("IsSubscriptionOpted")).Value;

            //        if (!string.IsNullOrEmpty(o.CostCode))
            //        {
            //            return true;
            //        }
            //    }
            //    return false;
            //})).Sum(orderLine =>
            //{
            //    //BUSA-463 Subscription: Get previous ActualPrice to calculate discount for this promotion
            //    if (!string.IsNullOrEmpty(orderLine.CostCode))
            //    {
            //        Decimal actualPrice = decimal.Parse(orderLine.CostCode, CultureInfo.InvariantCulture);

            //        Decimal qtyOrdered = orderLine.QtyOrdered;
            //        HelperUtility helperUtility = new HelperUtility();
            //        var currentCustomer = helperUtility.GetCurrentCustomerFlow(customerOrderPromotion.CustomerOrder);
            //        string amount = string.Empty;
            //        if (currentCustomer == null)
            //        {
            //            currentCustomer = customerOrderPromotion.CustomerOrder.Customer;
            //        }
            //        if (currentCustomer.CustomProperties.Where(x => x.Name.EqualsIgnoreCase("SubscriptionDiscount")).Count() > 0)
            //        {
            //            amount = currentCustomer.CustomProperties.FirstOrDefault(x => x.Name.EqualsIgnoreCase("SubscriptionDiscount")).Value;
            //        }

            //        if (string.IsNullOrEmpty(amount))
            //        {
            //            return 0;
            //        }
            //        Decimal? subscriptionDiscount = Decimal.Parse(amount, CultureInfo.InvariantCulture);

            //        Decimal percent = subscriptionDiscount.Value / new Decimal(100);

            //        Decimal Act = NumberHelper.ApplyDiscount(actualPrice, percent);

            //        Decimal num = actualPrice - Act;

            //        return NumberHelper.RoundCurrency(qtyOrdered * num);
            //    }
            //    else
            //        return 0;
            //});


            if (customerOrderPromotion.OrderLine != null)
            {
                if (customerOrderPromotion.OrderLine.CustomProperties.Where(x => x.Name.EqualsIgnoreCase("IsSubscriptionOpted")).Count() > 0)
                {
                    var IsSubscriptionOpted = customerOrderPromotion.OrderLine.CustomProperties.FirstOrDefault(x => x.Name.EqualsIgnoreCase("IsSubscriptionOpted")).Value;

                    if (!string.IsNullOrEmpty(customerOrderPromotion.OrderLine.CostCode))
                    {
                        Decimal actualPrice = decimal.Parse(customerOrderPromotion.OrderLine.CostCode, CultureInfo.InvariantCulture);

                        Decimal       qtyOrdered      = customerOrderPromotion.OrderLine.QtyOrdered;
                        HelperUtility helperUtility   = new HelperUtility();
                        var           currentCustomer = helperUtility.GetCurrentCustomerFlow(customerOrderPromotion.CustomerOrder);
                        string        amount          = string.Empty;
                        if (currentCustomer == null)
                        {
                            currentCustomer = customerOrderPromotion.CustomerOrder.Customer;
                        }
                        if (currentCustomer.CustomProperties.Where(x => x.Name.EqualsIgnoreCase("SubscriptionDiscount")).Count() > 0)
                        {
                            amount = currentCustomer.CustomProperties.FirstOrDefault(x => x.Name.EqualsIgnoreCase("SubscriptionDiscount")).Value;
                        }

                        if (string.IsNullOrEmpty(amount))
                        {
                            return(0);
                        }
                        Decimal?subscriptionDiscount = Decimal.Parse(amount, CultureInfo.InvariantCulture);

                        Decimal percent = subscriptionDiscount.Value / new Decimal(100);

                        Decimal Act = NumberHelper.ApplyDiscount(actualPrice, percent);

                        Decimal num = actualPrice - Act;

                        return(NumberHelper.RoundCurrency(qtyOrdered * num));
                    }
                }
            }
            return(0);
            //*********************************************************
            //ProductPromotionHelper_Brasseler helper = new ProductPromotionHelper_Brasseler(this.PricingPipeline, this.PromotionProvider);
            //return helper.GetPercentOrAmountProductDiscount(this.PromotionResult, customerOrderPromotion);
        }
예제 #11
0
        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);
                    }
                }
            }
        }
        //public void ApplyDiscountToOrderLines(PromotionResult promotionResult, IEnumerable<OrderLine> orderLines)
        //{
        //    if (!promotionResult.Amount.HasValue)
        //        throw new ArgumentNullException("Amount");
        //    if (promotionResult.Amount.Value == Decimal.Zero)
        //        throw new ArgumentOutOfRangeException("Amount");
        //    foreach (OrderLine orderLine1 in orderLines)
        //    {
        //        orderLine1.PromotionResult = promotionResult;
        //        PricingServiceResult pricingServiceResult = this.GetPricingServiceResult(orderLine1);
        //        OrderLine orderLine2 = orderLine1;
        //        bool? isPercent = promotionResult.IsPercent;
        //        Decimal lowestPrice;
        //        Decimal actualPrice = pricingServiceResult.ActualPrice;
        //        Decimal retailPrice = orderLine1.RegularPrice;
        //        Decimal? amount = promotionResult.Amount;

        //        if ((isPercent.HasValue ? (isPercent.GetValueOrDefault() ? 1 : 0) : 0) == 0)
        //        {
        //            lowestPrice = GetLowestPriceBaseAmountBasedPromotion(actualPrice, retailPrice, amount);
        //        }
        //        else
        //        {
        //            lowestPrice = GetLowestPriceBasePercentBasedPromotion(actualPrice, retailPrice, amount);
        //        }
        //        orderLine2.ActualPrice = lowestPrice;
        //        orderLine1.RegularPrice = pricingServiceResult.RegularPrice;
        //        orderLine1.ActualPrice = orderLine1.ActualPrice < Decimal.Zero ? Decimal.Zero : orderLine1.ActualPrice;
        //    }
        //}
        public virtual void ApplyDiscountToOrderLines(PromotionResult promotionResult, IEnumerable <OrderLine> orderLines, CustomerOrder customerOrder)
        {
            if (!promotionResult.Amount.HasValue)
            {
                throw new ArgumentNullException("Amount");
            }
            Decimal?amount = promotionResult.Amount;

            if (amount.Value == Decimal.Zero)
            {
                throw new ArgumentOutOfRangeException("Amount");
            }
            IList <OrderLine> source = orderLines as IList <OrderLine> ?? (IList <OrderLine>)orderLines.ToList <OrderLine>();

            if (!source.Any <OrderLine>())
            {
                return;
            }
            IDictionary <Guid, ProductPriceDto> pricingServiceResult = this.GetPricingServiceResult((IEnumerable <OrderLine>)source);
            CustomerOrderPromotion appliedPromotion = customerOrder.CustomerOrderPromotions.FirstOrDefault <CustomerOrderPromotion>((Func <CustomerOrderPromotion, bool>)(p => p.PromotionId == promotionResult.PromotionId));

            foreach (OrderLine orderLine1 in (IEnumerable <OrderLine>)source)
            {
                OrderLine       orderLine       = orderLine1;
                ProductPriceDto productPriceDto = pricingServiceResult.First <KeyValuePair <Guid, ProductPriceDto> >((Func <KeyValuePair <Guid, ProductPriceDto>, bool>)(o => o.Key == orderLine.Id)).Value;
                bool?           isPercent       = promotionResult.IsPercent;
                Decimal         lowestPrice;
                Decimal         actualPrice = productPriceDto.UnitRegularPrice;/*pricingServiceResult.ActualPrice*/
                Decimal         retailPrice = orderLine1.UnitListPrice;
                Decimal?        promoAmount = promotionResult.Amount;

                if ((isPercent.HasValue ? (isPercent.GetValueOrDefault() ? 1 : 0) : 0) == 0)
                {
                    lowestPrice = GetLowestPriceBaseAmountBasedPromotion(actualPrice, retailPrice, amount);
                }
                else
                {
                    lowestPrice = GetLowestPriceBasePercentBasedPromotion(actualPrice, retailPrice, amount);
                }
                Decimal num3 = lowestPrice;
                if (orderLine.PromotionResult != null)
                {
                    if (!(orderLine.UnitNetPrice < num3))
                    {
                        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
                    {   // BUSA-1242: category level promotion is inserted into CustomerOrderPromotion table with null values
                        if (appliedPromotion != null)
                        {
                            if (appliedPromotion.Amount == null && appliedPromotion.OrderLineId == null)
                            {
                                customerOrder.CustomerOrderPromotions.Remove(appliedPromotion);
                                this.UnitOfWork.GetRepository <CustomerOrderPromotion>().Delete(appliedPromotion);
                            }
                        }
                        continue;
                    }
                }
                orderLine.PromotionResult   = promotionResult;
                orderLine.UnitListPrice     = productPriceDto.UnitListPrice;
                orderLine.UnitRegularPrice  = productPriceDto.UnitRegularPrice;
                orderLine.UnitNetPrice      = num3;
                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);
            }
        }
        public virtual 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));

                //BUSA_1242: Prod Category Level Promotion is inserted in customerorderpromotion table with 0 amount
                if (appliedPromotion.Amount <= 0)
                {
                    if (appliedPromotion.Promotion.PromotionResults.Count == 1 && appliedPromotion.Promotion.PromotionResults.Where(x => x.PromotionResultType == "DiscountProductsInCategory").Any())
                    {
                        orderLine.PromotionResult = (PromotionResult)null;
                        customerOrder.CustomerOrderPromotions.Remove(appliedPromotion);
                        this.UnitOfWork.GetRepository <CustomerOrderPromotion>().Delete(appliedPromotion);
                    }
                }
            }
            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));

                //BUSA_1242: Prod Category Level Promotion is inserted in customerorderpromotion table with 0 amount
                if (customerOrderPromotion.Amount <= 0 && customerOrderPromotion.Promotion.PromotionResults.Where(x => x.PromotionResultType == "DiscountProductsInCategory").Any())
                {
                    orderLine.PromotionResult = (PromotionResult)null;
                }
                else
                {
                    customerOrder.CustomerOrderPromotions.Add(customerOrderPromotion);
                }
            }
        }
        //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);
        }