diff --git a/src/VirtoCommerce.XCart.Core/CartAggregate.cs b/src/VirtoCommerce.XCart.Core/CartAggregate.cs index a9d7a49..367b025 100644 --- a/src/VirtoCommerce.XCart.Core/CartAggregate.cs +++ b/src/VirtoCommerce.XCart.Core/CartAggregate.cs @@ -959,32 +959,46 @@ protected virtual bool CheckPricePolicy(TierPrice tierPrice) return tierPrice.Price.Amount > 0; } - protected virtual async Task InnerAddLineItemAsync(LineItem lineItem, CartProduct product = null, IList dynamicProperties = null) + protected virtual async Task InnerAddLineItemAsync(LineItem newLineItem, CartProduct product = null, IList dynamicProperties = null) { - var existingLineItem = LineItems.FirstOrDefault(li => li.ProductId == lineItem.ProductId); + var existingLineItem = FindExistingLineItemBeforeAdd(newLineItem.ProductId, product, dynamicProperties); + if (existingLineItem != null) { - await InnerChangeItemQuantityAsync(existingLineItem, existingLineItem.Quantity + Math.Max(1, lineItem.Quantity), product); + await InnerChangeItemQuantityAsync(existingLineItem, existingLineItem.Quantity + Math.Max(1, newLineItem.Quantity), product); - existingLineItem.FulfillmentCenterId = lineItem.FulfillmentCenterId; - existingLineItem.FulfillmentCenterName = lineItem.FulfillmentCenterName; + existingLineItem.FulfillmentCenterId = newLineItem.FulfillmentCenterId; + existingLineItem.FulfillmentCenterName = newLineItem.FulfillmentCenterName; - lineItem = existingLineItem; + newLineItem = existingLineItem; } else { - lineItem.Id = null; - Cart.Items.Add(lineItem); + newLineItem.Id = null; + Cart.Items.Add(newLineItem); } if (dynamicProperties != null) { - await UpdateCartItemDynamicProperties(lineItem, dynamicProperties); + await UpdateCartItemDynamicProperties(newLineItem, dynamicProperties); } return this; } + /// + /// Responsible for finding an existing line item before adding a new one. + /// If method returns line item, it means that the new line item should be merged with the existing one. + /// + /// new product id + /// new product object + /// new dynamuc properties that should be added/updated in cart line item + /// + protected virtual LineItem FindExistingLineItemBeforeAdd(string newProductId, CartProduct newProduct, IList newDynamicProperties) + { + return LineItems.FirstOrDefault(x => x.ProductId == newProductId); + } + protected virtual void EnsureCartExists() { if (Cart == null)