public void RemovePromoCode_IfParameterIsNull_ShouldThrowArgumentNullException( CommerceCart cart, string promoCode) { // act & assert Assert.Throws <ArgumentNullException>(() => this.cartManager.RemovePromoCode(cart, promoCode)); }
public CartServiceTests() { this.cartBuilder = Substitute.For <ICartBuilder <Connect.Cart> >(); this.cartManager = Substitute.For <ICartManager>(); this.inventoryManager = Substitute.For <IInventoryManager>(); var catalogContext = Substitute.For <ICatalogContext>(); this.catalogService = Substitute.For <ICatalogService>(); var storefrontContext = Substitute.For <IStorefrontContext>(); this.visitorContext = Substitute.For <IVisitorContext>(); this.cartService = new CartService( this.cartBuilder, this.cartManager, this.inventoryManager, catalogContext, catalogService, storefrontContext, this.visitorContext); this.fixture = new Fixture().Customize(new OmitOnRecursionCustomization()); this.cartResult = this.fixture.Create <CartResult>(); this.commerceCart = this.fixture.Create <CommerceCart>(); this.cartResult.Cart = this.commerceCart; this.cartManager.LoadCart(Arg.Any <string>(), Arg.Any <string>()).Returns(this.cartResult); }
/// <summary> /// Updates the cart currency. /// </summary> /// <param name="storefront">The storefront.</param> /// <param name="visitorContext">The visitor context.</param> /// <param name="currencyCode">The currency code.</param> /// <returns>The manager response.</returns> public virtual ManagerResponse <CartResult, bool> UpdateCartCurrency([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, [NotNull] string currencyCode) { Assert.ArgumentNotNull(storefront, "storefront"); Assert.ArgumentNotNull(visitorContext, "visitorContext"); Assert.ArgumentNotNullOrEmpty(currencyCode, "currencyCode"); var result = this.GetCurrentCart(storefront, visitorContext); if (!result.ServiceProviderResult.Success) { return(new ManagerResponse <CartResult, bool>(new CartResult { Success = false }, false)); } var cart = result.Result; var changes = new CommerceCart() { CurrencyCode = currencyCode }; var updateCartResult = this.UpdateCart(storefront, visitorContext, cart, changes); if (updateCartResult.ServiceProviderResult.Success) { var cartCache = CommerceTypeLoader.CreateInstance <CartCacheHelper>(); string customerId = visitorContext.GetCustomerId(); cartCache.InvalidateCartCache(customerId); } return(new ManagerResponse <CartResult, bool>(updateCartResult.ServiceProviderResult, updateCartResult.ServiceProviderResult.Success)); }
/// <summary> /// Gets the line shipping options. /// </summary> /// <param name="cart">The cart.</param> /// <param name="allShippingOptions">All shipping options.</param> /// <returns>The list of line shipping options.</returns> protected virtual List <LineShippingOption> GetLineShippingOptions(CommerceCart cart, List <ShippingOption> allShippingOptions) { List <LineShippingOption> lineShippingOptions = new List <LineShippingOption>(); if (cart != null && cart.Lines != null && cart.Lines.Any()) { foreach (CommerceCartLine lineItem in cart.Lines) { List <ShippingOption> shippingOptionsForLine = new List <ShippingOption>(); foreach (var shippingOption in allShippingOptions) { if (shippingOption.ShippingOptionType == ShippingOptionType.ShipToAddress || shippingOption.ShippingOptionType == ShippingOptionType.ElectronicDelivery) { bool add = shippingOption.ShippingOptionType == ShippingOptionType.ElectronicDelivery && !this.CanLineItemBeEmailed(lineItem) ? false : true; if (add) { shippingOptionsForLine.Add(shippingOption); } } } LineShippingOption lineShippingOption = new LineShippingOption(); lineShippingOption.LineId = Guid.Parse(lineItem.ExternalCartLineId).ToString(); lineShippingOption.ShippingOptions = shippingOptionsForLine.AsReadOnly(); lineShippingOptions.Add(lineShippingOption); } } return(lineShippingOptions); }
private void AddShippingOptionsToResult(CheckoutDataBaseJsonResult result, CommerceCart cart) { var response = this.ShippingManager.GetShippingPreferences(cart); var orderShippingOptions = new List <ShippingOption>(); var lineShippingOptions = new List <LineShippingOption>(); if (response.ServiceProviderResult.Success && response.Result != null) { orderShippingOptions = response.ServiceProviderResult.ShippingOptions.ToList(); lineShippingOptions = response.ServiceProviderResult.LineShippingPreferences.ToList(); } result.OrderShippingOptions = orderShippingOptions; result.LineShippingOptions = lineShippingOptions; if (result.LineShippingOptions != null && result.LineShippingOptions.Any()) { foreach (var line in result.Cart.Lines) { var lineShippingOption = result.LineShippingOptions.FirstOrDefault(l => l.LineId.Equals(line.ExternalCartLineId, StringComparison.OrdinalIgnoreCase)); if (lineShippingOption != null) { line.ShippingOptions = lineShippingOption.ShippingOptions; } } } result.SetErrors(response.ServiceProviderResult); }
public ManagerResponse <CartResult, bool> UpdateCartCurrency(string userId, string currencyCode) { Assert.ArgumentNotNullOrEmpty(currencyCode, nameof(currencyCode)); var result = GetCart(userId); if (!result.ServiceProviderResult.Success) { return(new ManagerResponse <CartResult, bool>(new CartResult { Success = false }, false)); } var cart = result.Result; var changes = new CommerceCart { CurrencyCode = currencyCode }; var updateCartResult = UpdateCart(cart, changes); if (updateCartResult.ServiceProviderResult.Success) { CartCacheHelper.InvalidateCartCache(userId); } return(new ManagerResponse <CartResult, bool>(updateCartResult.ServiceProviderResult, updateCartResult.ServiceProviderResult.Success)); }
private void AddShippingMethodsToResult(CheckoutDataBaseJsonResult result, CommerceCart cart) { var shippingRequest = new GetShippingMethodsInputModel { ShippingPreferenceType = ShippingOptionType.None.Name }; var response = this.ShippingManager.GetShippingMethods(this.CurrentStorefront, this.CurrentVisitorContext, shippingRequest); if (response.ServiceProviderResult.Success && response.Result != null) { foreach (var sm in response.Result) { var isEmailMethod = sm.GetPropertyValue("IsEmailShippingMethod") != null && (bool)sm.GetPropertyValue("IsEmailShippingMethod"); var isShipToStoreMethod = sm.GetPropertyValue("IsShipToStoreShippingMethod") != null && (bool)sm.GetPropertyValue("IsShipToStoreShippingMethod"); if (isEmailMethod) { result.EmailDeliveryMethod = sm; } if (isShipToStoreMethod) { result.ShipToStoreDeliveryMethod = sm; } } return; } result.EmailDeliveryMethod = new ShippingMethod(); result.ShipToStoreDeliveryMethod = new ShippingMethod(); result.SetErrors(response.ServiceProviderResult); }
/// <summary> /// Initializes this object based on the data contained in the provided cart. /// </summary> /// <param name="cart">The cart used to initialize this object.</param> public override void Initialize(Commerce.Entities.Carts.Cart cart, IProductResolver productResolver) { base.Initialize(cart, productResolver); CommerceCart commerceCart = cart as CommerceCart; if (commerceCart == null) { return; } if (commerceCart.OrderForms.Count > 0) { foreach (var promoCode in (commerceCart.OrderForms[0].PromoCodes ?? Enumerable.Empty <String>())) { this.PromoCodes.Add(promoCode); } } decimal totalSavings = 0; foreach (var lineitem in cart.Lines) { totalSavings += ((CommerceTotal)lineitem.Total).LineItemDiscountAmount; } this.Discount = totalSavings.ToCurrency(StorefrontManager.GetCustomerCurrency()); }
public void Initialize(CommerceCart cart, CartManager manager) { if (cart.OrderForms != null && cart.OrderForms.Any()) { //this.PromoCodes = cart.OrderForms.FirstOrDefault().PromoCodes; var cartEntity = (Cart)cart; this.TotalDiscount = (cartEntity.Lines.Sum <CartLine>((Func <CartLine, Decimal>)(lineitem => ((CommerceTotal)lineitem.Total).LineItemDiscountAmount)) + ((CommerceTotal)cartEntity.Total).OrderLevelDiscountAmount); } PromoCodes = new List <PromotionModel>(); foreach (var line in cart.Lines) { if (line.Adjustments != null && line.Adjustments.Any()) { foreach (var item in line.Adjustments) { if (item.Description.Contains('|')) { PromoCodes.Add(new PromotionModel() { CouponCode = item.Description.Split('|').First(), DisplayCartText = item.Description.Split('|').Last() }); } } } } }
public CartResult RemovePromoCode(CommerceCart cart, string promoCode) { Assert.ArgumentNotNull(cart, nameof(cart)); Assert.ArgumentNotNullOrEmpty(promoCode, nameof(promoCode)); return(this.Execute(new RemovePromoCodeRequest(cart, promoCode), this.cartServiceProvider.RemovePromoCode)); }
/// <summary> /// Gets the specified cart. /// </summary> /// <param name="cart">The cart.</param> /// <param name="rendering">The rendering.</param> /// <returns>Gets an instance of the CartRenderingModel with initialized Sitecore rendering.</returns> public static CartRenderingModel Get(CommerceCart cart, Rendering rendering) { CartRenderingModel model = new CartRenderingModel(cart); model.Initialize(rendering); return(model); }
/// <summary> /// Gets the specified cart. /// </summary> /// <param name="cart">The cart.</param> /// <param name="rendering">The rendering.</param> /// <returns>Gets an instance of the CartRenderingModel with initialized Sitecore rendering.</returns> public static CartRenderingModel Get(CommerceCart cart, Rendering rendering) { CartRenderingModel model = new CartRenderingModel(cart); model.Initialize(rendering); return model; }
/// <summary> /// Adds the basket errors to result. /// </summary> /// <param name="cart">The cart.</param> /// <param name="result">The result.</param> protected virtual void AddBasketErrorsToResult(CommerceCart cart, ServiceProviderResult result) { if (cart != null && cart.Properties["_Basket_Errors"] != null) { List <string> basketErrors = cart.Properties["_Basket_Errors"] as List <string>; basketErrors.ForEach(m => result.SystemMessages.Add(new SystemMessage { Message = m })); } }
/// <summary> /// Adds the cart to cache. /// </summary> /// <param name="cart">The cart.</param> /// <returns>The CommerceCart.</returns> public virtual CommerceCart AddCartToCache(CommerceCart cart) { if (Tracker.Current.Contact.Attachments.ContainsKey(StorefrontConstants.TrackerAttachmentKeys.CustomerCartKey)) { Tracker.Current.Contact.Attachments.Remove(StorefrontConstants.TrackerAttachmentKeys.CustomerCartKey); } Tracker.Current.Contact.Attachments.Add(StorefrontConstants.TrackerAttachmentKeys.CustomerCartKey, cart); return cart; }
public ManagerResponse <CartResult, CommerceCart> UpdateCart(CommerceCart cart, CommerceCart cartChanges) { Assert.ArgumentNotNull(cart, nameof(cart)); Assert.ArgumentNotNull(cartChanges, nameof(cartChanges)); var updateCartRequest = new UpdateCartRequest(cart, cartChanges); var result = CartServiceProvider.UpdateCart(updateCartRequest); result.WriteToSitecoreLog(); return(new ManagerResponse <CartResult, CommerceCart>(result, result.Cart as CommerceCart)); }
private AddShippingInfoResult AddShippingInfoToCart(CommerceCart cart, ShippingOptionType orderShippingPreferenceType, IEnumerable <ShippingInfo> shipments) { Assert.ArgumentNotNull(cart, nameof(cart)); Assert.ArgumentNotNull(orderShippingPreferenceType, nameof(orderShippingPreferenceType)); Assert.ArgumentNotNull(shipments, nameof(shipments)); var request = new AddShippingInfoRequest(cart, shipments.ToList(), orderShippingPreferenceType); var result = CartServiceProvider.AddShippingInfo(request); result.WriteToSitecoreLog(); return(result); }
/// <summary> /// Submits the visitor order. /// </summary> /// <param name="storefront">The storefront.</param> /// <param name="visitorContext">The visitor context.</param> /// <param name="inputModel">The input model.</param> /// <returns> /// The manager response where the new CommerceOrder is returned in the Result. /// </returns> public ManagerResponse <SubmitVisitorOrderResult, CommerceOrder> SubmitVisitorOrder([NotNull] CommerceStorefront storefront, [NotNull] IVisitorContext visitorContext, [NotNull] SubmitOrderInputModel inputModel) { Assert.ArgumentNotNull(storefront, "storefront"); Assert.ArgumentNotNull(visitorContext, "visitorContext"); Assert.ArgumentNotNull(inputModel, "inputModel"); SubmitVisitorOrderResult errorResult = new SubmitVisitorOrderResult { Success = false }; var response = this._cartManager.GetCurrentCart(storefront, visitorContext, true); if (!response.ServiceProviderResult.Success || response.Result == null) { response.ServiceProviderResult.SystemMessages.ToList().ForEach(m => errorResult.SystemMessages.Add(m)); return(new ManagerResponse <SubmitVisitorOrderResult, CommerceOrder>(errorResult, null)); } var cart = (CommerceCart)response.ServiceProviderResult.Cart; if (cart.Lines.Count == 0) { errorResult.SystemMessages.Add(new SystemMessage { Message = StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.SubmitOrderHasEmptyCart) }); return(new ManagerResponse <SubmitVisitorOrderResult, CommerceOrder>(errorResult, null)); } var cartChanges = new CommerceCart(); cartChanges.Properties["Email"] = inputModel.UserEmail; var updateCartResult = this._cartManager.UpdateCart(storefront, visitorContext, cart, cartChanges); if (!updateCartResult.ServiceProviderResult.Success) { response.ServiceProviderResult.SystemMessages.ToList().ForEach(m => errorResult.SystemMessages.Add(m)); return(new ManagerResponse <SubmitVisitorOrderResult, CommerceOrder>(errorResult, null)); } var request = new SubmitVisitorOrderRequest(cart); request.RefreshCart(true); errorResult = this._orderServiceProvider.SubmitVisitorOrder(request); if (errorResult.Success && errorResult.Order != null && errorResult.CartWithErrors == null) { var cartCache = ContextTypeLoader.CreateInstance <CartCacheHelper>(); cartCache.InvalidateCartCache(visitorContext.GetCustomerId()); } //Helpers.LogSystemMessages(errorResult.SystemMessages, errorResult); return(new ManagerResponse <SubmitVisitorOrderResult, CommerceOrder>(errorResult, errorResult.Order as CommerceOrder)); }
private CommerceCart CheckForPartyInfoOnCart(CommerceCart cart) { if (cart.Parties.Any()) { var response = this.CartManager.RemovePartiesFromCart(this.CurrentStorefront, this.CurrentVisitorContext, cart, cart.Parties.ToList()); if (response.ServiceProviderResult.Success) { cart = response.Result; } } return(cart); }
private CommerceCart CheckForShipmentInCart(CommerceCart cart) { if (cart.Shipping != null && cart.Shipping.Any()) { var response = this.CartManager.RemoveAllShippingMethods(this.CurrentStorefront, this.CurrentVisitorContext, cart); if (response.ServiceProviderResult.Success) { cart = response.Result; } } return(cart); }
public void AddCartToCache(CommerceCart cart) { var cacheProvider = GetCacheProvider(); var id = GetCustomerId(cart.CustomerId); if (cacheProvider.Contains(CommerceConstants.KnownCachePrefixes.Sitecore, CommerceConstants.KnownCacheNames.CommerceCartCache, id)) { CommerceTrace.Current.Write($"CartCacheHelper::AddCartToCache - Cart for customer id {id} is already in the cache!"); } cacheProvider.AddData(CommerceConstants.KnownCachePrefixes.Sitecore, CommerceConstants.KnownCacheNames.CommerceCartCache, id, cart); CartCookieHelper.CreateCartCookieForCustomer(id); }
/// <summary> /// Adds the cart to cache. /// </summary> /// <param name="cart">The cart.</param> public virtual void AddCartToCache(CommerceCart cart) { var cacheProvider = GetCacheProvider(); var id = this.GetCustomerId(cart.CustomerId); if (cacheProvider.Contains(Infrastructure.Constants.CommerceConstants.KnownCachePrefixes.Sitecore, Infrastructure.Constants.CommerceConstants.KnownCacheNames.CommerceCartCache, id)) { var msg = string.Format(CultureInfo.InvariantCulture, "CartCacheHelper::AddCartToCache - Cart for customer id {0} is already in the cache!", id); CommerceTrace.Current.Write(msg); } cacheProvider.AddData(Infrastructure.Constants.CommerceConstants.KnownCachePrefixes.Sitecore, Infrastructure.Constants.CommerceConstants.KnownCacheNames.CommerceCartCache, id, cart); CartCookieHelper.CreateCartCookieForCustomer(id); }
/// <summary> /// Adds the cart to cache. /// </summary> /// <param name="cart">The cart.</param> /// <returns>The CommerceCart.</returns> public virtual CommerceCart AddCartToCache(CommerceCart cart) { var cacheProvider = this.GetCacheProvider(); var id = this.GetCustomerId(cart.CustomerId); if (cacheProvider.Contains(CommerceConstants.KnownCachePrefixes.Sitecore, CommerceConstants.KnownCacheNames.CommerceCartCache, id)) { var msg = string.Format(CultureInfo.InvariantCulture, "CartCacheHelper::AddCartToCache - Cart for customer id {0} is already in the cache!", id); CommerceTrace.Current.Write(msg); } cacheProvider.AddData(CommerceConstants.KnownCachePrefixes.Sitecore, CommerceConstants.KnownCacheNames.CommerceCartCache, id, cart); return cart; }
/// <summary> /// Adds shipping info to a cart /// </summary> /// <param name="cart">The cart.</param> /// <param name="orderShippingPreferenceType">Type of the order shipping preference.</param> /// <param name="shipments">The shipments.</param> /// <returns> /// the updated cart /// </returns> protected virtual AddShippingInfoResult AddShippingInfoToCart([NotNull] CommerceCart cart, [NotNull] ShippingOptionType orderShippingPreferenceType, [NotNull] IEnumerable <ShippingInfo> shipments) { Assert.ArgumentNotNull(cart, "cart"); Assert.ArgumentNotNull(orderShippingPreferenceType, "orderShippingPreferenceType"); Assert.ArgumentNotNull(shipments, "shipments"); var request = new AddShippingInformationRequest(cart, shipments.ToList(), orderShippingPreferenceType); var result = this.CartServiceProvider.AddShippingInfo(request); if (!result.Success) { Helpers.LogSystemMessages(result.SystemMessages, result); } return(result); }
/// <summary> /// Merges the carts. /// </summary> /// <param name="storefront">The storefront.</param> /// <param name="visitorContext">The visitor context.</param> /// <param name="anonymousVisitorId">The anonymous visitor identifier.</param> /// <param name="anonymousVisitorCart">The anonymous visitor cart.</param> /// <returns> /// The manager response where the merged cart is returned in the result. /// </returns> public virtual ManagerResponse <CartResult, CommerceCart> MergeCarts([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, string anonymousVisitorId, Cart anonymousVisitorCart) { Assert.ArgumentNotNull(storefront, "storefront"); Assert.ArgumentNotNull(visitorContext, "visitorContext"); Assert.ArgumentNotNullOrEmpty(anonymousVisitorId, "anonymousVisitorId"); var userId = visitorContext.UserId; var cartResult = this.LoadCartByName(storefront.ShopName, storefront.DefaultCartName, userId, true); if (!cartResult.Success || cartResult.Cart == null) { var message = StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.CartNotFoundError); cartResult.SystemMessages.Add(new SystemMessage { Message = message }); return(new ManagerResponse <CartResult, CommerceCart>(cartResult, cartResult.Cart as CommerceCart)); } CommerceCart currentCart = (CommerceCart)cartResult.Cart; var result = new CartResult { Cart = currentCart, Success = true }; if (userId != anonymousVisitorId) { var anonymousCartHasPromocodes = (anonymousVisitorCart is CommerceCart) && ((CommerceCart)anonymousVisitorCart).OrderForms.Any(of => of.PromoCodes.Any()); if (anonymousVisitorCart != null && (anonymousVisitorCart.Lines.Any() || anonymousCartHasPromocodes)) { if ((currentCart.ShopName == anonymousVisitorCart.ShopName) || (currentCart.ExternalId != anonymousVisitorCart.ExternalId)) { var mergeCartRequest = new MergeCartRequest(anonymousVisitorCart, currentCart); result = this.CartServiceProvider.MergeCart(mergeCartRequest); } } } if (result.Success && result.Cart != null) { var cartCache = CommerceTypeLoader.CreateInstance <CartCacheHelper>(); cartCache.InvalidateCartCache(anonymousVisitorId); cartCache.AddCartToCache(result.Cart as CommerceCart); } return(new ManagerResponse <CartResult, CommerceCart>(result, result.Cart as CommerceCart)); }
private void AddShippingOptionsToResult(CheckoutDataBaseJsonResult result, CommerceCart cart) { var response = this.ShippingManager.GetShippingPreferences(cart); var orderShippingOptions = new List <ShippingOption>(); var lineShippingOptions = new List <LineShippingOption>(); if (response.ServiceProviderResult.Success && response.Result != null) { orderShippingOptions = response.ServiceProviderResult.ShippingOptions.ToList(); lineShippingOptions = response.ServiceProviderResult.LineShippingPreferences.ToList(); } result.InitializeShippingOptions(orderShippingOptions); result.InitializeLineItemShippingOptions(lineShippingOptions); result.SetErrors(response.ServiceProviderResult); }
/// <summary> /// Carts the can be emailed. /// </summary> /// <param name="cart">The cart.</param> /// <returns>True if the full cart can be emailed, otherwise false.</returns> protected virtual bool CartCanBeEmailed(CommerceCart cart) { bool canBeEmailed = true; if (cart.Lines != null && cart.Lines.Any()) { foreach (CommerceCartLine lineItem in cart.Lines) { if (!this.CanLineItemBeEmailed(lineItem)) { canBeEmailed = false; } } } return(canBeEmailed); }
private void AddBasketErrorsToResult(CommerceCart cart, ServiceProviderResult result) { if (cart?.Properties[KnownBasketWeaklyTypeProperties.BasketErrors] != null) { var basketErrors = cart.Properties[KnownBasketWeaklyTypeProperties.BasketErrors] as List <string>; if (basketErrors == null) { return; } foreach (var m in basketErrors) { result.SystemMessages.Add(new SystemMessage { Message = m }); } } }
/// <summary> /// Removes the line item from cart. /// </summary> /// <param name="storefront">The storefront.</param> /// <param name="visitorContext">The visitor context.</param> /// <param name="externalCartLineId">The external cart line identifier.</param> /// <returns> /// The manager response where the modified CommerceCart is returned in the Result. /// </returns> public virtual ManagerResponse <CartResult, CommerceCart> RemoveLineItemFromCart([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, [NotNull] string externalCartLineId) { Assert.ArgumentNotNullOrEmpty(externalCartLineId, "externalCartLineId"); var cartResult = this.LoadCartByName(storefront.ShopName, storefront.DefaultCartName, visitorContext.UserId, false); if (!cartResult.Success || cartResult.Cart == null) { var message = StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.CartNotFoundError); cartResult.SystemMessages.Add(new SystemMessage { Message = message }); return(new ManagerResponse <CartResult, CommerceCart>(cartResult, cartResult.Cart as CommerceCart)); } var cartCache = CommerceTypeLoader.CreateInstance <CartCacheHelper>(); cartCache.InvalidateCartCache(visitorContext.GetCustomerId()); CommerceCart cart = cartResult.Cart as CommerceCart; var lineToRemove = cart.Lines.SingleOrDefault(cl => cl.ExternalCartLineId == externalCartLineId); if (lineToRemove == null) { return(new ManagerResponse <CartResult, CommerceCart>(new CartResult { Success = true }, cart)); } var removeLinesRequest = new RemoveCartLinesRequest(cart, new[] { new CartLine { ExternalCartLineId = externalCartLineId, Quantity = lineToRemove.Quantity, Product = lineToRemove.Product } }); removeLinesRequest.RefreshCart(true); var removeLinesResult = this.CartServiceProvider.RemoveCartLines(removeLinesRequest); if (removeLinesResult.Success && removeLinesResult.Cart != null) { cartCache.AddCartToCache(removeLinesResult.Cart as CommerceCart); } Helpers.LogSystemMessages(removeLinesResult.SystemMessages, removeLinesResult); return(new ManagerResponse <CartResult, CommerceCart>(removeLinesResult, removeLinesResult.Cart as CommerceCart)); }
public CartServiceTests() { var storefrontContext = Substitute.For <IStorefrontContext>(); var catalogContext = Substitute.For <ICatalogContext>(); this.cartManager = Substitute.For <ICartManager>(); this.cartBuilder = Substitute.For <ICartBuilder <Connect.Cart> >(); this.fixture = this.CreateOmitOnRecursionFixture(); this.visitorContext = Substitute.For <IVisitorContext>(); this.cartService = new CartService( this.cartManager, storefrontContext, catalogContext, this.visitorContext, this.cartBuilder); this.cartResult = this.fixture.Create <CartResult>(); this.commerceCart = this.fixture.Create <CommerceCart>(); this.cartResult.Cart = this.commerceCart; this.cartManager.LoadCart(Arg.Any <string>(), Arg.Any <string>()).Returns(this.cartResult); }
private List <Party> GetPartiesForPrefix(CommerceCart cart, string prefix) { var partyList = new List <Party>(); foreach (var party in cart.Parties) { if (party is CommerceParty) { if (((CommerceParty)party).Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) { partyList.Add(party); } } else if (party is EmailParty) { if (((EmailParty)party).Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) { partyList.Add(party); } } } return(partyList); }
/// <summary> /// Gets the parties for prefix. /// </summary> /// <param name="cart">The cart.</param> /// <param name="prefix">The prefix.</param> /// <returns>The list of Party instances that match the given prefix value.</returns> protected virtual List<Party> GetPartiesForPrefix(CommerceCart cart, string prefix) { List<Party> partyList = new List<Party>(); foreach (Party party in cart.Parties) { if (party is CommerceParty) { if (((CommerceParty)party).Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) { partyList.Add(party); } } else if (party is RefSFModels.EmailParty) { if (((RefSFModels.EmailParty)party).Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) { partyList.Add(party); } } } return partyList; }
private void AddShippingOptionsToResult(CheckoutDataBaseJsonResult result, CommerceCart cart) { var response = this.ShippingManager.GetShippingPreferences(cart); var orderShippingOptions = new List<ShippingOption>(); var lineShippingOptions = new List<LineShippingOption>(); if (response.ServiceProviderResult.Success && response.Result != null) { orderShippingOptions = response.ServiceProviderResult.ShippingOptions.ToList(); lineShippingOptions = response.ServiceProviderResult.LineShippingPreferences.ToList(); } result.OrderShippingOptions = orderShippingOptions; result.LineShippingOptions = lineShippingOptions; if (result.LineShippingOptions != null && result.LineShippingOptions.Any()) { foreach (var line in result.Cart.Lines) { var lineShippingOption = result.LineShippingOptions.FirstOrDefault(l => l.LineId.Equals(line.ExternalCartLineId, StringComparison.OrdinalIgnoreCase)); if (lineShippingOption != null) { line.ShippingOptions = lineShippingOption.ShippingOptions; } } } result.SetErrors(response.ServiceProviderResult); }
/// <summary> /// Carts the can be emailed. /// </summary> /// <param name="cart">The cart.</param> /// <returns>True if the full cart can be emailed, otherwise false.</returns> protected virtual bool CartCanBeEmailed(CommerceCart cart) { bool canBeEmailed = true; if (cart.Lines != null && cart.Lines.Any()) { foreach (CommerceCartLine lineItem in cart.Lines) { if (!this.CanLineItemBeEmailed(lineItem)) { canBeEmailed = false; } } } return canBeEmailed; }
/// <summary> /// Submits the visitor order. /// </summary> /// <param name="storefront">The storefront.</param> /// <param name="visitorContext">The visitor context.</param> /// <param name="inputModel">The input model.</param> /// <returns> /// The manager response where the new CommerceOrder is returned in the Result. /// </returns> public ManagerResponse<SubmitVisitorOrderResult, CommerceOrder> SubmitVisitorOrder([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, [NotNull] SubmitOrderInputModel inputModel) { Assert.ArgumentNotNull(storefront, "storefront"); Assert.ArgumentNotNull(visitorContext, "visitorContext"); Assert.ArgumentNotNull(inputModel, "inputModel"); SubmitVisitorOrderResult errorResult = new SubmitVisitorOrderResult { Success = false }; var response = this.CartManager.GetCurrentCart(storefront, visitorContext, true); if (!response.ServiceProviderResult.Success || response.Result == null) { response.ServiceProviderResult.SystemMessages.ToList().ForEach(m => errorResult.SystemMessages.Add(m)); return new ManagerResponse<SubmitVisitorOrderResult, CommerceOrder>(errorResult, null); } var cart = (CommerceCart)response.ServiceProviderResult.Cart; if (cart.Lines.Count == 0) { errorResult.SystemMessages.Add(new SystemMessage { Message = StorefrontManager.GetSystemMessage("SubmitOrderHasEmptyCart") }); return new ManagerResponse<SubmitVisitorOrderResult, CommerceOrder>(errorResult, null); } var cartChanges = new CommerceCart(); cartChanges.Properties["Email"] = inputModel.UserEmail; var updateCartResult = this.CartManager.UpdateCart(storefront, visitorContext, cart, cartChanges); if (!updateCartResult.ServiceProviderResult.Success) { response.ServiceProviderResult.SystemMessages.ToList().ForEach(m => errorResult.SystemMessages.Add(m)); return new ManagerResponse<SubmitVisitorOrderResult, CommerceOrder>(errorResult, null); } var request = new SubmitVisitorOrderRequest(cart); request.RefreshCart(true); errorResult = this.OrderServiceProvider.SubmitVisitorOrder(request); if (errorResult.Success && errorResult.Order != null && errorResult.CartWithErrors == null) { var cartCache = CommerceTypeLoader.CreateInstance<CartCacheHelper>(); cartCache.InvalidateCartCache(visitorContext.GetCustomerId()); } Helpers.LogSystemMessages(errorResult.SystemMessages, errorResult); return new ManagerResponse<SubmitVisitorOrderResult, CommerceOrder>(errorResult, errorResult.Order as CommerceOrder); }
public Mocks() { AccountManager = Substitute.For <IAccountManager>(); AccountManager.ResolveCommerceUser() .Returns(new ManagerResponse <GetUserResult, CommerceUser>(new GetUserResult(), new CommerceUser { Email = "testMail" })); AccountManager.GetCurrentCustomerParties( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>()) .Returns(new ManagerResponse <GetPartiesResult, IEnumerable <CommerceParty> >( new GetPartiesResult(), new List <CommerceParty>())); ContactFactory = Substitute.For <IContactFactory>(); CartManager = Substitute.For <ICartManager>(); CartManager.AddLineItemsToCart( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Any <List <AddCartLineInputModel> >()) .Returns(new ManagerResponse <CartResult, bool>(new CartResult(), true)); CartManager.AddPromoCodeToCart( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Any <string>()) .Returns( new ManagerResponse <AddPromoCodeResult, CommerceCart>(new AddPromoCodeResult(), Models.CommerceCartStub)); CartManager.RemoveLineItemFromCart( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Any <string>()) .Returns( new ManagerResponse <CartResult, CommerceCart>(new CartResult(), Models.CommerceCartStub)); CartManager.GetCurrentCart( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Any <bool>()) .Returns(new ManagerResponse <CartResult, CommerceCart>(new CartResult { Cart = Models.CommerceCartStub, }, Models.CommerceCartStub)); CartManager.RemovePromoCodeFromCart( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Any <string>()) .Returns(new ManagerResponse <RemovePromoCodeResult, CommerceCart>(new RemovePromoCodeResult(), Models.CommerceCartStub)); CartManager.ChangeLineQuantity( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Any <UpdateCartLineInputModel>()) .Returns(new ManagerResponse <CartResult, CommerceCart>(new CartResult(), Models.CommerceCartStub)); CartManager.AddLineItemsToCart( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Is <List <AddCartLineInputModel> >(x => x.Single() == null)) .Returns(new ManagerResponse <CartResult, bool>(new CartResult { Success = false }, false)); CartManager.AddPromoCodeToCart( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Is <string>(x => x == string.Empty)) .Returns(new ManagerResponse <AddPromoCodeResult, CommerceCart>( new AddPromoCodeResult { Success = false }, Models.CommerceCartStub)); CartManager.RemoveLineItemFromCart( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Is <string>(x => x == null)) .Returns(new ManagerResponse <CartResult, CommerceCart>( new CartResult { Success = false }, Models.CommerceCartStub)); CartManager.RemovePromoCodeFromCart( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Is <string>(x => x == string.Empty)) .Returns(new ManagerResponse <RemovePromoCodeResult, CommerceCart>( new RemovePromoCodeResult { Success = false }, Models.CommerceCartStub)); CartManager.ChangeLineQuantity( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Is <UpdateCartLineInputModel>(x => x == null)) .Returns(new ManagerResponse <CartResult, CommerceCart>( new CartResult { Success = false }, Models.CommerceCartStub)); CartManager.RemovePartiesFromCart( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Any <CommerceCart>(), Arg.Any <List <Party> >()) .Returns(new ManagerResponse <CartResult, CommerceCart>(new AddPartiesResult(), new CommerceCart { Parties = new ReadOnlyCollection <Party>(new List <Party>()) })); CartManager.RemoveAllPaymentMethods( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Any <CommerceCart>()) .Returns(new ManagerResponse <CartResult, CommerceCart>(new AddPaymentInfoResult(), new CommerceCart { Payment = new ReadOnlyCollection <PaymentInfo>(new List <PaymentInfo>()) })); CartManager.RemoveAllShippingMethods( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Any <CommerceCart>()) .Returns(new ManagerResponse <CartResult, CommerceCart>( new AddPartiesResult(), new CommerceCart { Shipping = new ReadOnlyCollection <ShippingInfo>(new List <ShippingInfo>()) })); CartManager.SetPaymentMethods( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Is <PaymentInputModel>(x => x != null)) .Returns(new ManagerResponse <CartResult, CommerceCart>( new AddPaymentInfoResult(), Models.CommerceCartStub)); CartManager.SetPaymentMethods( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Is <PaymentInputModel>(x => x == null)) .Returns(new ManagerResponse <CartResult, CommerceCart>( new AddPaymentInfoResult { Success = false }, Models.CommerceCartStub)); CartManager.SetShippingMethods( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Is <SetShippingMethodsInputModel>(x => x != null)) .Returns(new ManagerResponse <AddShippingInfoResult, CommerceCart>( new AddShippingInfoResult(), Models.CommerceCartStub)); CartManager.SetShippingMethods( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Is <SetShippingMethodsInputModel>(x => x == null)) .Returns(new ManagerResponse <AddShippingInfoResult, CommerceCart>( new AddShippingInfoResult { Success = false }, Models.CommerceCartStub)); VisitorContext = Substitute.For <IVisitorContext>(); VisitorContext.GetCustomerId().Returns(Models.TestUserId); CommerceCart nullCart = null; CartCacheService = Substitute.For <ICartCacheService>(); CartCacheService.GetCart(Arg.Any <string>()).Returns(Models.CommerceCartStub); CartCacheService.GetCart(Arg.Is <string>(x => x.Equals(Models.UserWithEmptyCache))).Returns(nullCart); OrderManager = Substitute.For <IOrderManager>(); OrderManager.GetAvailableRegions( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Any <string>()) .Returns( new ManagerResponse <GetAvailableRegionsResult, Dictionary <string, string> >( new GetAvailableRegionsResult(), new Dictionary <string, string> { { "test", "test" } })); OrderManager.GetOrderDetails( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Any <string>()) .Returns(new ManagerResponse <GetVisitorOrderResult, CommerceOrder>(new GetVisitorOrderResult(), new CommerceOrder())); OrderManager.GetAvailableRegions( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Is <string>(x => x == null)) .Returns( new ManagerResponse <GetAvailableRegionsResult, Dictionary <string, string> >( new GetAvailableRegionsResult { Success = false }, new Dictionary <string, string>())); OrderManager.GetAvailableCountries() .Returns(new ManagerResponse <GetAvailableCountriesResult, Dictionary <string, string> >( new GetAvailableCountriesResult(), new Dictionary <string, string>())); OrderManager.SubmitVisitorOrder( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Is <SubmitOrderInputModel>(x => x != null)) .Returns(new ManagerResponse <SubmitVisitorOrderResult, CommerceOrder>( new SubmitVisitorOrderResult(), new CommerceOrder())); OrderManager.SubmitVisitorOrder( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Is <SubmitOrderInputModel>(x => x == null)) .Returns(new ManagerResponse <SubmitVisitorOrderResult, CommerceOrder>( new SubmitVisitorOrderResult { Success = false }, new CommerceOrder())); ShippingManager = Substitute.For <IShippingManager>(); ShippingManager.GetShippingPreferences( Arg.Any <CommerceCart>()) .Returns(new ManagerResponse <GetShippingOptionsResult, List <ShippingOption> >( new GetShippingOptionsResult { ShippingOptions = new ReadOnlyCollection <ShippingOption>(new List <ShippingOption>()), LineShippingPreferences = new ReadOnlyCollection <LineShippingOption>(new List <LineShippingOption>()) }, new List <ShippingOption>())); ShippingManager.GetShippingMethods( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Any <ShippingOption>()) .Returns(new ManagerResponse <GetShippingMethodsResult, IReadOnlyCollection <ShippingMethod> >( new GetShippingMethodsResult(), new HashSet <ShippingMethod>())); ShippingManager.GetShippingMethods( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Any <GetShippingMethodsInputModel>()) .Returns(new ManagerResponse <GetShippingMethodsResult, IReadOnlyCollection <ShippingMethod> >( new GetShippingMethodsResult { ShippingMethods = new ReadOnlyCollection <ShippingMethod>(Models.ShippingMethods.ToList()) }, Models.ShippingMethods)); PaymentManager = Substitute.For <IPaymentManager>(); PaymentManager.GetPaymentOptions( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>()) .Returns(new ManagerResponse <GetPaymentOptionsResult, IEnumerable <PaymentOption> >( new GetPaymentOptionsResult(), new List <PaymentOption>())); PaymentManager.GetPaymentMethods( Arg.Any <CommerceStorefront>(), Arg.Any <IVisitorContext>(), Arg.Any <PaymentOption>()) .Returns( new ManagerResponse <GetPaymentMethodsResult, IEnumerable <PaymentMethod> >( new GetPaymentMethodsResult(), new List <PaymentMethod>())); ProductResolver = Substitute.For <IProductResolver>(); ProductResolver.ResolveCatalogItem( Arg.Any <string>(), Arg.Any <string>(), Arg.Any <bool>()) .Returns(new Item(ID.NewID, new ItemData(ItemDefinition.Empty, Language.Invariant, Version.First, new FieldList()), Database.GetDatabase("master"))); }
public void AddToCart(CommerceCart cartLine) { _cartCacheHelper.AddCartToCache(cartLine); }
public CartViewModel(CommerceCart cart) { Cart = cart; }
/// <summary> /// Gets the line shipping options. /// </summary> /// <param name="cart">The cart.</param> /// <param name="allShippingOptions">All shipping options.</param> /// <returns>The list of line shipping options.</returns> protected virtual List<LineShippingOption> GetLineShippingOptions(CommerceCart cart, List<ShippingOption> allShippingOptions) { List<LineShippingOption> lineShippingOptions = new List<LineShippingOption>(); if (cart != null && cart.Lines != null && cart.Lines.Any()) { foreach (CommerceCartLine lineItem in cart.Lines) { List<ShippingOption> shippingOptionsForLine = new List<ShippingOption>(); foreach (var shippingOption in allShippingOptions) { if (shippingOption.ShippingOptionType == Sitecore.Reference.Storefront.Connect.Models.ShippingOptionType.ShipToAddress || shippingOption.ShippingOptionType == Sitecore.Reference.Storefront.Connect.Models.ShippingOptionType.ElectronicDelivery) { bool add = shippingOption.ShippingOptionType == Sitecore.Reference.Storefront.Connect.Models.ShippingOptionType.ElectronicDelivery && !this.CanLineItemBeEmailed(lineItem) ? false : true; if (add) { shippingOptionsForLine.Add(shippingOption); } } } LineShippingOption lineShippingOption = new LineShippingOption(); lineShippingOption.LineId = Guid.Parse(lineItem.ExternalCartLineId).ToString(); lineShippingOption.ShippingOptions = shippingOptionsForLine.AsReadOnly(); lineShippingOptions.Add(lineShippingOption); } } return lineShippingOptions; }
/// <summary> /// Initializes a new instance of the <see cref="CartRenderingModel"/> class. /// </summary> /// <param name="cart">The cart.</param> public CartRenderingModel(CommerceCart cart) { this.Cart = cart; }
/// <summary> /// Adds the basket errors to result. /// </summary> /// <param name="cart">The cart.</param> /// <param name="result">The result.</param> protected virtual void AddBasketErrorsToResult(CommerceCart cart, ServiceProviderResult result) { if (cart != null && cart.Properties["_Basket_Errors"] != null) { List<string> basketErrors = cart.Properties["_Basket_Errors"] as List<string>; basketErrors.ForEach(m => result.SystemMessages.Add(new SystemMessage { Message = m })); } }
private CommerceCart CheckForPartyInfoOnCart(CommerceCart cart) { if (cart.Parties.Any()) { var response = this.CartManager.RemovePartiesFromCart(this.CurrentStorefront, this.CurrentVisitorContext, cart, cart.Parties.ToList()); if (response.ServiceProviderResult.Success) { cart = response.Result; } } return cart; }
private CommerceCart CheckForShipmentInCart(CommerceCart cart) { if (cart.Shipping != null && cart.Shipping.Any()) { var response = this.CartManager.RemoveAllShippingMethods(this.CurrentStorefront, this.CurrentVisitorContext, cart); if (response.ServiceProviderResult.Success) { cart = response.Result; } } return cart; }
/// <summary> /// Sets the shipping addresses. /// </summary> /// <param name="storefront">The storefront.</param> /// <param name="visitorContext">The visitor context.</param> /// <param name="cart">The cart.</param> /// <param name="shippingAddresses">The shipping addresses.</param> /// <param name="emailPartyList">The email party list.</param> /// <returns> /// The manager response with a cart in the result. /// </returns> protected virtual AddPartiesResult SetShippingAddresses(CommerceStorefront storefront, VisitorContext visitorContext, CommerceCart cart, List<PartyInputModelItem> shippingAddresses, List<RefSFModels.EmailParty> emailPartyList) { var errorResult = new AddPartiesResult { Success = false }; var removePartiesResponse = this.RemoveAllShippingParties(storefront, visitorContext, cart); if (!removePartiesResponse.ServiceProviderResult.Success) { errorResult.SystemMessages.Add(removePartiesResponse.ServiceProviderResult.SystemMessages[0]); return errorResult; } List<Party> partyList = new List<Party>(); if (shippingAddresses != null && shippingAddresses.Any()) { partyList.AddRange(shippingAddresses.ToNewShippingParties()); } if (emailPartyList != null && emailPartyList.Any()) { partyList.AddRange(emailPartyList.Cast<Party>().ToList()); } AddPartiesRequest addPartiesRequest = new AddPartiesRequest(cart, partyList); var addPartiesResponse = this.CartServiceProvider.AddParties(addPartiesRequest); return addPartiesResponse; }