/// <summary>
        /// Adds product to the visitor's cart.
        /// </summary>
        /// <param name="productId">
        /// The product id.
        /// </param>
        /// <param name="quantity">
        /// The quantity.
        /// </param>
        /// <returns>
        /// The <see cref="Cart"/>.
        /// </returns>
        public Cart AddToCart(string productId, uint quantity)
        {
            Assert.ArgumentNotNull(productId, "productId");

            var cart = this.GetCart();

            if (string.IsNullOrWhiteSpace(cart.ShopName))
            {
                cart.ShopName = this.ShopName;
            }

            CartResult cartResult;
            var        cartLineToChange = cart.Lines.FirstOrDefault(cl => cl.Product != null && cl.Product.ProductId == productId);

            if (cartLineToChange != null)
            {
                cartLineToChange.Quantity += quantity;
                var updateRequest = new UpdateCartLinesRequest(cart, new[] { cartLineToChange });
                cartResult = this._cartServiceProvider.UpdateCartLines(updateRequest);
            }
            else
            {
                var cartLine = new CartLine {
                    Product = new CartProduct {
                        ProductId = productId
                    }, Quantity = quantity
                };
                this.UpdateStockInformation(cartLine);
                var request = new AddCartLinesRequest(cart, new[] { cartLine });
                cartResult = this._cartServiceProvider.AddCartLines(request);
            }

            return(this.UpdatePrices(cartResult.Cart));
        }
Exemple #2
0
        public ActionResult AddToBasket(AddToBasketButtonAddToBasketViewModel viewModel)
        {
            var cartServiceProvider = new CartServiceProvider();

            var    contactFactory = new ContactFactory();
            string userId         = contactFactory.GetContact();

            var createCartRequest = new CreateOrResumeCartRequest(Context.GetSiteName(), userId);

            var cart = cartServiceProvider.CreateOrResumeCart(createCartRequest).Cart;

            var cartProduct = new CartProduct
            {
                ProductId = viewModel.ProductSku,
                Price     = new Price(Convert.ToDecimal(viewModel.Price), cart.CurrencyCode)
            };

            cartProduct.Properties.Add("VariantSku", viewModel.VariantSku);

            var cartLines = new ReadOnlyCollection <CartLine>(
                new Collection <CartLine> {
                new CartLine
                {
                    Product  = cartProduct,
                    Quantity = (uint)viewModel.Quantity
                }
            }
                );

            var request = new AddCartLinesRequest(cart, cartLines);

            cartServiceProvider.AddCartLines(request);

            return(Json(_miniBasketService.Refresh(), JsonRequestBehavior.AllowGet));
        }
Exemple #3
0
        public ManagerResponse <CartResult, bool> AddLineItemsToCart(string userId, IEnumerable <AddCartLineInputModel> inputModelList)
        {
            Assert.ArgumentNotNull(inputModelList, nameof(inputModelList));

            var cartResult = LoadCartByName(CommerceConstants.CartSettings.DefaultCartName, userId, false);

            if (!cartResult.Success || cartResult.Cart == null)
            {
                var message = DictionaryPhraseRepository.Current.Get("/System Messages/Cart/Cart Not Found Error", "Could not retrieve the cart for the current user");
                cartResult.SystemMessages.Add(new SystemMessage {
                    Message = message
                });
                return(new ManagerResponse <CartResult, bool>(cartResult, cartResult.Success));
            }

            var lines = new List <CartLine>();

            foreach (var inputModel in inputModelList)
            {
                Assert.ArgumentNotNullOrEmpty(inputModel.ProductId, nameof(inputModel.ProductId));
                Assert.ArgumentNotNullOrEmpty(inputModel.CatalogName, nameof(inputModel.CatalogName));
                Assert.ArgumentNotNull(inputModel.Quantity, nameof(inputModel.Quantity));

                if (inputModel.Quantity == null)
                {
                    continue;
                }
                var quantity = (uint)inputModel.Quantity;

                var cartLine = new CommerceCartLine(inputModel.CatalogName, inputModel.ProductId, inputModel.VariantId == "-1" ? null : inputModel.VariantId, quantity)
                {
                    Properties =
                    {
                        ["ProductUrl"] = inputModel.ProductUrl,
                        ["ImageUrl"]   = inputModel.ImageUrl
                    }
                };
                //UpdateStockInformation(cartLine, inputModel.CatalogName);

                lines.Add(cartLine);
            }

            CartCacheHelper.InvalidateCartCache(userId);

            var cart            = cartResult.Cart as CommerceCart;
            var addLinesRequest = new AddCartLinesRequest(cart, lines);

            RefreshCart(addLinesRequest, true);
            var addLinesResult = CartServiceProvider.AddCartLines(addLinesRequest);

            if (addLinesResult.Success && addLinesResult.Cart != null)
            {
                CartCacheHelper.AddCartToCache(addLinesResult.Cart as CommerceCart);
            }

            AddBasketErrorsToResult(addLinesResult.Cart as CommerceCart, addLinesResult);

            addLinesResult.WriteToSitecoreLog();
            return(new ManagerResponse <CartResult, bool>(addLinesResult, addLinesResult.Success));
        }
        public ManagerResponse <CartResult, Cart> AddLineItemsToCart(Cart cart, IEnumerable <CartLineArgument> cartLines, string giftCardProductId, string giftCardPageLink)
        {
            Assert.ArgumentNotNull(cart, nameof(cart));
            Assert.ArgumentNotNull(cartLines, nameof(cartLines));

            var cartLineList = new List <CartLine>();

            foreach (CartLineArgument cartLine in cartLines)
            {
                Assert.ArgumentNotNullOrEmpty(cartLine.ProductId, "inputModel.ProductId");
                Assert.ArgumentNotNullOrEmpty(cartLine.CatalogName, "inputModel.CatalogName");
                Assert.ArgumentNotNull(cartLine.Quantity, "inputModel.Quantity");
                decimal quantity = cartLine.Quantity;

                var commerceCartLine = new CommerceCartLine(cartLine.CatalogName, cartLine.ProductId, cartLine.VariantId == "-1" ? null : cartLine.VariantId, quantity);
                cartLineList.Add(commerceCartLine);
            }

            var request    = new AddCartLinesRequest(cart, cartLineList);
            var cartResult = this.cartServiceProvider.AddCartLines(request);

            if (!cartResult.Success)
            {
                cartResult.SystemMessages.LogSystemMessages(cartResult);
            }

            return(new ManagerResponse <CartResult, Cart>(cartResult, cartResult.Cart));
        }
        public PipelineExecutionResult Execute(IPipelineArgs <AddToBasketRequest, AddToBasketResponse> subject)
        {
            if (subject.Request.Properties.ContainsKey("FromUCommerce"))
            {
                if (!(bool)subject.Request.Properties["FromUCommerce"])
                {
                    return(PipelineExecutionResult.Success);
                }
            }

            //var cart = MappingLibrary.MapPurchaseOrderToCart(subject.Request.PurchaseOrder);

            var    contactFactory = new ContactFactory();
            string userId         = contactFactory.GetContact();

            var cartServiceProvider = new CartServiceProvider();
            var createCartRequest   = new CreateOrResumeCartRequest(Context.GetSiteName(), userId);

            //should it do anything???
            var cart = cartServiceProvider.CreateOrResumeCart(createCartRequest).Cart;

            var cartLine = MappingLibrary.MapOrderLineToCartLine(subject.Response.OrderLine);

            var request = new AddCartLinesRequest(cart, new Collection <CartLine> {
                cartLine
            });

            request.Properties["FromUCommerce"] = true;

            var serviceProvider = new CartServiceProvider();

            serviceProvider.AddCartLines(request);

            return(PipelineExecutionResult.Success);
        }
        protected CartLinesRequest CreateCartLinesRequest(CommerceEventInstance eventInstance)
        {
            var cart  = MapEventToCartEntity(eventInstance);
            var lines = cart.Lines; // Only the modified lines are passed in the event, so modified equal total cart lines
            CartLinesRequest request;

            if (eventInstance.CommerceEventId == LinesAddedEventId) //TODO: When there will be more events implemented, create an enum thats more maintainable.
            {
                request = new AddCartLinesRequest(cart, lines);
            }
            else if (eventInstance.CommerceEventId == LinesRemovedEventId)
            {
                request = new RemoveCartLinesRequest(cart, lines);
            }
            else
            {
                throw new NotImplementedException($"Tracking for CommerceEvent with id {eventInstance.CommerceEventId} not implemented");
            }

            request.Shop = new Sitecore.Commerce.Entities.Shop {
                Name = eventInstance.ShopName
            };

            return(request);
        }
Exemple #7
0
        public ActionResult Add(string itemId)
        {
            var productItem = Database.GetDatabase("master").GetItem(new ID(itemId));

            var request = new AddCartLinesRequest(Cart, new[] {
                new CommerceCartLine
                {
                    Product = new CommerceCartProduct
                    {
                        ProductCatalog   = "Habitat_Master",
                        ProductId        = productItem.Name,
                        ProductVariantId = productItem.Children.FirstOrDefault()?.Name
                    },
                    Quantity = 1
                }
            });

            var result = csp.AddCartLines(request);

            if (!result.Success)
            {
                throw new InvalidOperationException(string.Join(",", result.SystemMessages.Select(x => x.Message)));
            }

            return(Redirect(LinkManager.GetItemUrl(Sitecore.Context.Item)));
        }
        /// <summary>
        /// Adds the line item to cart.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="visitorContext">The visitor context.</param>
        /// <param name="inputModelList">The input model.</param>
        /// <returns>
        /// The manager response where the result is retuned indicating the success or failure of the operation.
        /// </returns>
        public virtual ManagerResponse <CartResult, bool> AddLineItemsToCart([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, IEnumerable <AddCartLineInputModel> inputModelList)
        {
            Assert.ArgumentNotNull(inputModelList, "inputModelList");

            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, bool>(cartResult, cartResult.Success));
            }

            var lines = new List <CartLine>();

            foreach (var inputModel in inputModelList)
            {
                Assert.ArgumentNotNullOrEmpty(inputModel.ProductId, "inputModel.ProductId");
                Assert.ArgumentNotNullOrEmpty(inputModel.CatalogName, "inputModel.CatalogName");
                Assert.ArgumentNotNull(inputModel.Quantity, "inputModel.Quantity");

                var quantity = (uint)inputModel.Quantity;

                //// Special handling for a Gift Card
                if (inputModel.ProductId.Equals(storefront.GiftCardProductId, StringComparison.OrdinalIgnoreCase))
                {
                    inputModel.VariantId = inputModel.GiftCardAmount.Value.ToString("000", CultureInfo.InvariantCulture);
                }

                var cartLine = new CommerceCartLine(inputModel.CatalogName, inputModel.ProductId, inputModel.VariantId == "-1" ? null : inputModel.VariantId, quantity);
                cartLine.Properties["ProductUrl"] = inputModel.ProductUrl;
                cartLine.Properties["ImageUrl"]   = inputModel.ImageUrl;
                //// UpdateStockInformation(storefront, visitorContext, cartLine, inputModel.CatalogName);

                lines.Add(cartLine);
            }

            var cartCache = CommerceTypeLoader.CreateInstance <CartCacheHelper>();

            cartCache.InvalidateCartCache(visitorContext.GetCustomerId());

            var cart            = cartResult.Cart as CommerceCart;
            var addLinesRequest = new AddCartLinesRequest(cart, lines);

            addLinesRequest.RefreshCart(true);
            var addLinesResult = this.CartServiceProvider.AddCartLines(addLinesRequest);

            if (addLinesResult.Success && addLinesResult.Cart != null)
            {
                cartCache.AddCartToCache(addLinesResult.Cart as CommerceCart);
            }

            this.AddBasketErrorsToResult(addLinesResult.Cart as CommerceCart, addLinesResult);

            Helpers.LogSystemMessages(addLinesResult.SystemMessages, addLinesResult);
            return(new ManagerResponse <CartResult, bool>(addLinesResult, addLinesResult.Success));
        }
Exemple #9
0
        public ActionResult AddProduct()
        {
            var loadCartRequest = new LoadCartRequest("CommerceEngineDefaultStorefront", "Default", "1234");
            var loadCartResult  = _cartServiceProvider.LoadCart(loadCartRequest);
            var cart            = loadCartResult.Cart;

            // Add a cart line: note that adding a line for the same product twice will update the quantity, not add a line: this is configured in commerce engine (look for RollupCartLinesPolicy)
            var lines    = new List <CartLine>();
            var cartLine = new CommerceCartLine("Neu", "47838_aus_allen_sternen_liebe_cd", "", 1.0M);

            lines.Add(cartLine);

            var addLinesRequest = new AddCartLinesRequest(cart, lines);
            var addLinesResult  = _cartServiceProvider.AddCartLines(addLinesRequest);

            return(View("Cart", addLinesResult));
        }
Exemple #10
0
        public ActionResult GetCartLineFulfillmentMethods()
        {
            // Load a cart
            var loadCartRequest = new LoadCartRequest("CommerceEngineDefaultStorefront", "Default", "1234");
            var loadCartResult  = _cartServiceProvider.LoadCart(loadCartRequest);
            var cart            = loadCartResult.Cart as CommerceCart;

            // Add a line to the cart
            var lines    = new List <CartLine>();
            var cartLine = new CommerceCartLine("NEU", "test", "", 1.0M);

            lines.Add(cartLine);

            var addLinesRequest = new AddCartLinesRequest(cart, lines);
            var addLinesResult  = _cartServiceProvider.AddCartLines(addLinesRequest);

            cart = addLinesResult.Cart as CommerceCart;

            var shippingService = new ShippingServiceProvider();

            var shippingOption = new ShippingOption
            {
                ShippingOptionType =
                    ShippingOptionType
                    .DeliverItemsIndividually,     // This will trigger calling GetCartLinesFulfillmentMethods instead of GetCartFulfillmentMethods
            };

            var shippingParty = new CommerceParty
            {
                Address1    = "Main Street", City = "Montreal", ZipPostalCode = "NW7 7SJ", Country = "Canada",
                CountryCode = "CA"
            };

            var request = new GetShippingMethodsRequest(shippingOption, shippingParty, cart)
            {
                Lines = cart.Lines.Cast <CommerceCartLine>().ToList()
            };
            var result = shippingService.GetShippingMethods(request);

            return(View(result));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AddLinesToCartTest"/> class.
        /// </summary>
        public AddLinesToCartTest()
        {
            this.visitorId = Guid.NewGuid();

            this.cart = new Cart
            {
                ExternalId = this.visitorId.ToString(),
                Lines      = new ReadOnlyCollection <CartLine>(new List <CartLine> {
                    new CartLine()
                })
            };

            this.lineToAdd = new CartLine
            {
                Product = new CartProduct
                {
                    ProductId = "100500",
                    Price     = new Price {
                        Amount = 100
                    }
                },
                Quantity = 12
            };

            this.request = new AddCartLinesRequest(this.cart, new[] { this.lineToAdd });
            this.result  = new CartResult();
            this.args    = new ServicePipelineArgs(this.request, this.result);

            this.client = Substitute.For <ICartsServiceChannel>();

            var clientFactory = Substitute.For <ServiceClientFactory>();

            clientFactory.CreateClient <ICartsServiceChannel>(Arg.Any <string>(), Arg.Any <string>()).Returns(this.client);

            this.processor = new AddLinesToCart {
                ClientFactory = clientFactory
            };
        }
Exemple #12
0
        public override void Process(ServicePipelineArgs args)
        {
            UpdateCartLinesRequest request;
            CartResult             result;

            CheckParametersAndSetupRequestAndResult(args, out request, out result);

            using (new DisposableThreadLifestyleScope())
            {
                if (IsFromUcommerce(request) || !args.Result.Success)
                {
                    return;
                }

                var basket = _basketService.GetBasketByCartExternalId(request.Cart.ExternalId);

                var existingOrderLines = basket.PurchaseOrder.OrderLines;

                var query = (from updatedOrderLine in request.Lines
                             join originalOrderLine in existingOrderLines
                             on updatedOrderLine.ExternalCartLineId equals originalOrderLine.OrderLineId.ToString() into matchedOrderLines
                             from matchedOrderLine in matchedOrderLines.DefaultIfEmpty()
                             where matchedOrderLine == null
                             select new { NewCartLine = updatedOrderLine }).ToList();

                if (!query.Any())
                {
                    return;
                }

                var newCartLines = query.Select(x => x.NewCartLine).ToList();

                var cartServiceProvider = new CartServiceProvider();
                var addCartLinesRequest = new AddCartLinesRequest(request.Cart, newCartLines);
                cartServiceProvider.AddCartLines(addCartLinesRequest);
            }
        }
        /// <summary>
        /// Adds the line item to cart.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="visitorContext">The visitor context.</param>
        /// <param name="inputModelList">The input model.</param>
        /// <returns>
        /// The manager response where the result is retuned indicating the success or failure of the operation.
        /// </returns>
        public virtual ManagerResponse<CartResult, bool> AddLineItemsToCart([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, IEnumerable<AddCartLineInputModel> inputModelList)
        {
            Assert.ArgumentNotNull(inputModelList, "inputModelList");

            var cartResult = this.LoadCartByName(storefront.ShopName, storefront.DefaultCartName, visitorContext.UserId, false);
            if (!cartResult.Success || cartResult.Cart == null)
            {
                var message = StorefrontManager.GetSystemMessage("CartNotFoundError");
                cartResult.SystemMessages.Add(new SystemMessage { Message = message });
                return new ManagerResponse<CartResult, bool>(cartResult, cartResult.Success);
            }

            var lines = new List<CartLine>();
            foreach (var inputModel in inputModelList)
            {
                Assert.ArgumentNotNullOrEmpty(inputModel.ProductId, "inputModel.ProductId");
                Assert.ArgumentNotNullOrEmpty(inputModel.CatalogName, "inputModel.CatalogName");
                Assert.ArgumentNotNull(inputModel.Quantity, "inputModel.Quantity");

                var quantity = (uint)inputModel.Quantity;

                //// Special handling for a Gift Card
                if (inputModel.ProductId.Equals(storefront.GiftCardProductId, StringComparison.OrdinalIgnoreCase))
                {
                    inputModel.VariantId = inputModel.GiftCardAmount.Value.ToString("000", CultureInfo.InvariantCulture);
                }

                var cartLine = new CommerceCartLine(inputModel.CatalogName, inputModel.ProductId, inputModel.VariantId == "-1" ? null : inputModel.VariantId, quantity);
                cartLine.Properties["ProductUrl"] = inputModel.ProductUrl;
                cartLine.Properties["ImageUrl"] = inputModel.ImageUrl;
                //// UpdateStockInformation(storefront, visitorContext, cartLine, inputModel.CatalogName);

                lines.Add(cartLine);
            }

            var cartCache = CommerceTypeLoader.CreateInstance<CartCacheHelper>();
            cartCache.InvalidateCartCache(visitorContext.GetCustomerId());

            var cart = cartResult.Cart as CommerceCart;
            var addLinesRequest = new AddCartLinesRequest(cart, lines);
            addLinesRequest.RefreshCart(true);
            var addLinesResult = this.CartServiceProvider.AddCartLines(addLinesRequest);
            if (addLinesResult.Success && addLinesResult.Cart != null)
            {
                cartCache.AddCartToCache(addLinesResult.Cart as CommerceCart);
            }

            this.AddBasketErrorsToResult(addLinesResult.Cart as CommerceCart, addLinesResult);

            Helpers.LogSystemMessages(addLinesResult.SystemMessages, addLinesResult);
            return new ManagerResponse<CartResult, bool>(addLinesResult, addLinesResult.Success);
        }
Exemple #14
0
        public ActionResult BasketToOrder()
        {
            var shopName =
                "CommerceEngineDefaultStorefront"; // Better use a configured store, not CommerceEngineDefaultStorefront as it's not really configured
            var cartName = "Default";
            var userId   = "Entity-Customer-34d758ae2d2d472d89014954d0cc4440";
            var domain   = Context.User.Domain;

            // Get a cart
            var loadCartRequest = new LoadCartByNameRequest(shopName, cartName, userId);
            var cartResult      = _cartServiceProvider.LoadCart(loadCartRequest);

            Assert.IsTrue(cartResult.Success, String.Join("|", cartResult.SystemMessages.Select(e => e.Message)));

            var cart = cartResult.Cart;

            var quantity = 0.0M; // Get initial quantity

            if (cart.Lines.Count > 0)
            {
                quantity = cart.Lines[0].Quantity;
            }

            // Add a cart line: note that adding a line for the same product twice will update the quantity, not add a line: this is configured in commerce engine (look for RollupCartLinesPolicy)
            var lines    = new List <CartLine>();
            var cartLine = new CommerceCartLine("Neu", "47838_aus_allen_sternen_liebe_cd", "", 1.0M);

            lines.Add(cartLine);

            var addLinesRequest = new AddCartLinesRequest(cart, lines);
            var addLinesResult  = _cartServiceProvider.AddCartLines(addLinesRequest);

            Assert.IsTrue(addLinesResult.Success,
                          String.Join("|", addLinesResult.SystemMessages.Select(e => e.Message)));

            var updatedCart = addLinesResult.Cart;

            Assert.IsTrue(updatedCart.Lines.Count > 0, "Updated cart should have at least one line");
            Assert.IsTrue(quantity + 1 == updatedCart.Lines[0].Quantity, "new quantity should be one more than before");

            var reloadCartRequest  = new LoadCartByNameRequest(shopName, cartName, userId);
            var reloadedCartResult = _cartServiceProvider.LoadCart(reloadCartRequest);

            Assert.IsTrue(reloadedCartResult.Success,
                          String.Join("|", reloadedCartResult.SystemMessages.Select(e => e.Message)));

            var reloadedCart = reloadedCartResult.Cart;

            Assert.IsTrue(reloadedCart.Lines.Count > 0, "Reloaded cart should have at least one line");
            Assert.IsTrue(quantity + 1 == reloadedCart.Lines[0].Quantity,
                          "reloaded cart quantity should be one more than before");

            // Switching cart :-)
            cart = reloadedCart;

            // Add a shipping address
            CommerceParty shippingAddress = new CommerceParty();

            shippingAddress.ExternalId    = "Shipping";
            shippingAddress.PartyId       = shippingAddress.ExternalId;
            shippingAddress.Name          = "Shipping";
            shippingAddress.Address1      = "Barbara Strozzilaan 201";
            shippingAddress.Company       = "Sitecore";
            shippingAddress.Country       = "Canada";
            shippingAddress.State         = "ON"; // State is checked by commerce engine: you can configure it in Commerce
            shippingAddress.CountryCode   = "CA"; // Country is checked by commerce engine
            shippingAddress.LastName      = "Werkman";
            shippingAddress.FirstName     = "Erwin";
            shippingAddress.City          = "Amsterdam";
            shippingAddress.ZipPostalCode = "1030AC";

            var cartParties = cart.Parties.ToList();

            cartParties.Add(shippingAddress);
            cart.Parties = cartParties;

            ShippingOptionType shippingOptionType = ShippingOptionType.ShipToAddress;

            ICollection <CommerceShippingInfo> shippingInfoList = new List <CommerceShippingInfo>();

            var commerceShippingInfo = new CommerceShippingInfo();

            commerceShippingInfo.ShippingOptionType = ShippingOptionType.ShipToAddress;
            commerceShippingInfo.PartyID            = shippingAddress.ExternalId;
            commerceShippingInfo.ShippingMethodID   = "B146622D-DC86-48A3-B72A-05EE8FFD187A"; // Ship Items > Ground
            commerceShippingInfo.ShippingMethodName =
                "Ground";                                                                     // Method id and name have to match what is configured in Sitecore Commerce Control Panel

            shippingInfoList.Add(commerceShippingInfo);

            var csShippingInfoList = new List <ShippingInfo>();

            foreach (var shippingInfo in shippingInfoList)
            {
                csShippingInfoList.Add(shippingInfo);
            }

            // Add a shipping address and shipping method
            var addShippingInfoRequest =
                new Sitecore.Commerce.Engine.Connect.Services.Carts.AddShippingInfoRequest(cart, csShippingInfoList,
                                                                                           shippingOptionType);
            var result = _cartServiceProvider.AddShippingInfo(addShippingInfoRequest);

            Assert.IsTrue(result.Success, String.Join("|", result.SystemMessages.Select(e => e.Message)));

            // Reload the cart so we have the latest information on how much we need to pay
            reloadedCartResult = _cartServiceProvider.LoadCart(reloadCartRequest);

            Assert.IsTrue(reloadedCartResult.Success,
                          String.Join("|", reloadedCartResult.SystemMessages.Select(e => e.Message)));

            cart = reloadedCartResult.Cart;

            // Add billing address
            CommerceParty billingAddress = new CommerceParty();

            billingAddress.ExternalId =
                "Billing"; // This should correspond to the PartyId you are setting for the payment info
            billingAddress.PartyId       = billingAddress.ExternalId;
            billingAddress.Name          = "Billing";
            billingAddress.Address1      = "Dorpsstraat 50";
            billingAddress.Company       = "Sitecore";
            billingAddress.Country       = "Canada";
            billingAddress.State         = "ON"; // State is checked: you can configure it in Commerce
            billingAddress.CountryCode   = "CA";
            billingAddress.LastName      = "Werkman";
            billingAddress.FirstName     = "Erwin";
            billingAddress.City          = "Amsterdam";
            billingAddress.ZipPostalCode = "1234AK";

            cart.Parties.Add(billingAddress);

            // Add a payment address and payment method
            var payments = new List <PaymentInfo>();

            /*
             * For federated payment info to work, you need to set up the Braintree integration
             * var federatedPaymentInfo = new FederatedPaymentInfo();
             *
             * federatedPaymentInfo.PartyID = billingAddress.ExternalId;
             * federatedPaymentInfo.PaymentMethodID = "0CFFAB11-2674-4A18-AB04-228B1F8A1DEC";    // Federated Payment
             * federatedPaymentInfo.Amount = cart.Total.Amount;   // Total payment (of all payment methods for a cart) should always be the same as the total amount of the order
             * federatedPaymentInfo.CardToken = "payment-nonce";  // This should be valid b
             *
             * payments.Add(federatedPaymentInfo);
             */

            var giftCardPaymentInfo = new GiftCardPaymentInfo();

            giftCardPaymentInfo.PaymentMethodID = "B5E5464E-C851-4C3C-8086-A4A874DD2DB0"; // GiftCard
            giftCardPaymentInfo.Amount          = cart.Total.Amount;
            giftCardPaymentInfo.ExternalId      = "GC1000000";                            // This is the number of the giftcard
            giftCardPaymentInfo.PartyID         = billingAddress.ExternalId;

            payments.Add(giftCardPaymentInfo);

            var addPaymentInfoRequest = new AddPaymentInfoRequest(cart, payments);
            var addPaymentInfoResult  = _cartServiceProvider.AddPaymentInfo(addPaymentInfoRequest);

            Assert.IsTrue(addPaymentInfoResult.Success,
                          String.Join("|", addPaymentInfoResult.SystemMessages.Select(e => e.Message)));

            var freshCartRequest = new LoadCartByNameRequest(shopName, cartName, userId);
            var freshCartResult  = _cartServiceProvider.LoadCart(reloadCartRequest);

            Assert.IsTrue(freshCartResult.Success,
                          String.Join("|", freshCartResult.SystemMessages.Select(e => e.Message)));

            cart.Email = "*****@*****.**"; // This is necessary otherwise the cart will not become an order

            // Save the cart as an order
            var submitVisitorOrderRequest = new SubmitVisitorOrderRequest(cart);
            var submitVisitorOrderResult  = _orderServiceProvider.SubmitVisitorOrder(submitVisitorOrderRequest);

            Assert.IsTrue(submitVisitorOrderResult.Success,
                          String.Join("|", submitVisitorOrderResult.SystemMessages.Select(e => e.Message)));

            return(View("Cart", freshCartResult));
        }
Exemple #15
0
        public ActionResult Index()
        {
            var loadCartRequest = new LoadCartRequest("CommerceEngineDefaultStorefront", "Default", "1234");
            var loadCartResult  = _cartServiceProvider.LoadCart(loadCartRequest);

            var cart = loadCartResult.Cart as CommerceCart;

            var lines    = new List <CartLine>();
            var cartLine = new CommerceCartLine("Habitat_Master", "6042567", "56042567", 1.0M);

            lines.Add(cartLine);

            var addLinesRequest = new AddCartLinesRequest(cart, lines);
            var addLinesResult  = _cartServiceProvider.AddCartLines(addLinesRequest);

            // Add a shipping address
            CommerceParty shippingAddress = new CommerceParty();

            shippingAddress.ExternalId    = "Shipping";
            shippingAddress.PartyId       = shippingAddress.ExternalId;
            shippingAddress.Name          = "Shipping";
            shippingAddress.Address1      = "Barbara Strozzilaan 201";
            shippingAddress.Company       = "Sitecore";
            shippingAddress.Country       = "Canada";
            shippingAddress.State         = "ON"; // State is checked by commerce engine: you can configure it in Commerce
            shippingAddress.CountryCode   = "CA"; // Country is checked by commerce engine
            shippingAddress.LastName      = "Werkman";
            shippingAddress.FirstName     = "Erwin";
            shippingAddress.City          = "Amsterdam";
            shippingAddress.ZipPostalCode = "1030AC";

            var cartParties = cart.Parties.ToList();

            cartParties.Add(shippingAddress);
            cart.Parties = cartParties;

            ShippingOptionType shippingOptionType = ShippingOptionType.ShipToAddress;

            ICollection <CommerceShippingInfo> shippingInfoList = new List <CommerceShippingInfo>();

            var commerceShippingInfo = new CommerceShippingInfo();

            commerceShippingInfo.ShippingOptionType = ShippingOptionType.ShipToAddress;
            commerceShippingInfo.PartyID            = shippingAddress.ExternalId;
            commerceShippingInfo.ShippingMethodID   = "B146622D-DC86-48A3-B72A-05EE8FFD187A"; // Ship Items > Ground
            commerceShippingInfo.ShippingMethodName =
                "Ground";                                                                     // Method id and name have to match what is configured in Sitecore Commerce Control Panel

            shippingInfoList.Add(commerceShippingInfo);

            var csShippingInfoList = new List <ShippingInfo>();

            foreach (var shippingInfo in shippingInfoList)
            {
                csShippingInfoList.Add(shippingInfo);
            }

            // Add a shipping address and shipping method
            var addShippingInfoRequest =
                new Sitecore.Commerce.Engine.Connect.Services.Carts.AddShippingInfoRequest(cart, csShippingInfoList,
                                                                                           shippingOptionType);
            var result = _cartServiceProvider.AddShippingInfo(addShippingInfoRequest);

            cart = result.Cart as CommerceCart;

            // Add billing address
            CommerceParty billingAddress = new CommerceParty();

            billingAddress.ExternalId =
                "Billing"; // This should correspond to the PartyId you are setting for the payment info
            billingAddress.PartyId       = billingAddress.ExternalId;
            billingAddress.Name          = "Billing";
            billingAddress.Address1      = "Dorpsstraat 50";
            billingAddress.Company       = "Sitecore";
            billingAddress.Country       = "Canada";
            billingAddress.State         = "ON"; // State is checked: you can configure it in Commerce
            billingAddress.CountryCode   = "CA";
            billingAddress.LastName      = "Werkman";
            billingAddress.FirstName     = "Erwin";
            billingAddress.City          = "Amsterdam";
            billingAddress.ZipPostalCode = "1234AK";

            cart.Parties.Add(billingAddress);

            // Add a payment address and payment method
            var payments = new List <PaymentInfo>();

            var simplePaymentInfo = new SimplePaymentInfo();

            simplePaymentInfo.PaymentMethodID = "9B110CC3-C7C8-4492-8FCF-0CDE5D3E0EB0";
            simplePaymentInfo.Amount          = cart.Total.Amount;

            payments.Add(simplePaymentInfo);

            /*
             * var giftCardPaymentInfo = new GiftCardPaymentInfo();
             * giftCardPaymentInfo.PaymentMethodID = "B5E5464E-C851-4C3C-8086-A4A874DD2DB0"; // GiftCard
             * giftCardPaymentInfo.Amount = cart.Total.Amount;
             * giftCardPaymentInfo.ExternalId = "GC1000000"; // This is the number of the giftcard
             * giftCardPaymentInfo.PartyID = billingAddress.ExternalId;    // For a gift card this is not really necessary and not recorded
             *
             * payments.Add(giftCardPaymentInfo);
             */

            var addPaymentInfoRequest = new AddPaymentInfoRequest(cart, payments);
            var addPaymentInfoResult  = _cartServiceProvider.AddPaymentInfo(addPaymentInfoRequest);


            return(View("Cart", addPaymentInfoResult));
        }