Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Gonçalo Assunção 39 posts 68 karma points
    Jan 08, 2015 @ 22:53
    Gonçalo Assunção
    0

    How to create a Cart with Ucommerce

    Hello guys!

    I'm trying to create somekind of cart in umbraco6 using Ucommerce.

    I can't install the Razor Demo for umbraco, due to project demands. But I saw the Ucommerce Front-end and Umbraco6 demo online.

    Because it's the online versio, I can't see the "AddToBasket" helper code, that it is used in the Product Macro. And with that in mind, and minding the fact that I'm still giving my first steps as a professional web developer, I need your help, please.

    Now, in my page I have only 3 products, and each product has one "Subscribe" input type="button" that is generated through a razor macro. When the user presses the "subscribe" button the intention is to redirect him to a "payment and shipping details" page.

    Here's the code that I used to create the basket in the Products page:

               var obj_products = from items in Product.All().Where(x => x.ProductDefinition.Name ==            "Subscription").OrderBy(z => z.Sku)
                                   select items;
                Product[] arr_product = obj_products.ToArray();

                var obj_properties = from x in ProductDefinitionField.All().Where(y => y.ProductDefinition.Name == "Subscription")
                                     select x;

                ProductDefinitionField[] arr_productProperty = obj_properties.ToArray();

              
                PurchaseOrder obj_basket = TransactionLibrary.GetBasket(true).PurchaseOrder;


                PriceGroup obj_priceGroupDKK = (from price in PriceGroup.All().Where(y => y.Name == "DKK")
                                      select price).FirstOrDefault();           

                obj_basket.AddProduct(obj_priceGroupDKK, arr_product[1], 1);
                (this part was for testing the basket in this page only.)

     

    Now I need to "send" the basket to the "payment and shipping details", so that I can extract the information I need. For what I researched, I need to use a querystring, in order to redirect to the other page when the "subscribe" button is pressed.

    Thank you in advanced, and cheers from Portugal

     

  • Dennis Aaen 4500 posts 18255 karma points admin hq c-trib
    Jan 08, 2015 @ 23:17
    Dennis Aaen
    0

    Hi Gonçalo,

    I would try to provide you the content of the helpers that you can´t see. In the fuctions folder you can find a file called basket, and product.

    The basket file has this content:

    @using UCommerce.Api
    @functions{
        public static bool? AddToBasket(string addToBasketKey, string quantityKey, UCommerce.EntitiesV2.Product variant)
        {
            var request = HttpContext.Current.Request;

            if (request.Form.AllKeys.All(x => x != addToBasketKey))
            {
                return null;
            }

            if (variant == null)
            {
                return false;
            }

            var quantity = Convert.ToInt32(request.Form[quantityKey]);
            TransactionLibrary.AddToBasket(quantity, variant.Sku, variant.VariantSku);
            TransactionLibrary.ExecuteBasketPipeline();
            var returnUrl = request.RawUrl;

            if (returnUrl.Contains("item-added"))
                HttpContext.Current.Response.Redirect(returnUrl);

            if (returnUrl.Contains("?"))
                HttpContext.Current.Response.Redirect(string.Format("{0}&item-added=true", returnUrl));

            HttpContext.Current.Response.Redirect(string.Format("{0}?item-added=true", returnUrl));
            return true;
        }

        public static bool? AddVoucher(string addVoucherKey, string voucherKey)
        {
            var request = HttpContext.Current.Request;

            if (request.Form.AllKeys.All(x => x != addVoucherKey))
            {
                return null;
            }

            if (request.Form.AllKeys.All(x => x != voucherKey))
            {
                return false;
            }

            var code = request.Form[voucherKey];
            if (string.IsNullOrWhiteSpace(code))
            {
                return false;
            }

            MarketingLibrary.AddVoucher(code);
            TransactionLibrary.ExecuteBasketPipeline();
            return true;
        }

        public static bool? RemoveItem(string removeItemKey)
        {
            var request = HttpContext.Current.Request;

            if (!request.Form.AllKeys.Any(x => x.Equals(removeItemKey)))
            {
                return null;
            }

            int orderLineId;

            if (!int.TryParse(request.Form[removeItemKey], out orderLineId))
            {
                return false;
            }

            TransactionLibrary.UpdateLineItem(orderLineId, 0);
            TransactionLibrary.ExecuteBasketPipeline();
            HttpContext.Current.Response.Redirect(request.RawUrl);

            return true;
        }

        public static bool? UpdateCartLines(string updateItemKey, string quantityKey, UCommerce.EntitiesV2.PurchaseOrder basket)
        {
            var request = HttpContext.Current.Request;

            if (!request.Form.AllKeys.Any(x => x.Equals(updateItemKey)))
            {
                return null;
            }

            // NOTE: This could be made more efficient by checking whether the quantities are different
            foreach (var orderLineId in basket.OrderLines.Select(x => x.OrderLineId).ToList())
            {
                int newQuantity;
                if (int.TryParse(request.Form[quantityKey + orderLineId], out newQuantity))
                {
                    TransactionLibrary.UpdateLineItem(orderLineId, newQuantity);
                }
            }

            //// NOTE: If you are expecting a lot of changes each time, this would be better a better way to handle the updates
            // var orderLines = basket.OrderLines.ToList();
            // foreach (var orderLine in orderLines)
            // {
            //     int newQuantity;
                
            //     if (!int.TryParse(request.Form[quantityKey + orderLine], out newQuantity))
            //         continue;
                
            //     orderLine.Quantity = newQuantity;
                
            //     if (newQuantity == 0)
            //         basket.RemoveOrderLine(orderLine);
            // }

            foreach (var line in basket.OrderLines.Where(l => l.Quantity == 0))
            {
                basket.RemoveOrderLine(line);
            }

            TransactionLibrary.ExecuteBasketPipeline();
            return true;
        }

    }

    And the product file has this content

    @functions{
        public static UCommerce.EntitiesV2.Product GetVariantFromPostData(UCommerce.EntitiesV2.Product product, string variantPrefix)
        {
            var request = HttpContext.Current.Request;
            var keys = request.Form.AllKeys.Where(k => k.StartsWith(variantPrefix, StringComparison.InvariantCultureIgnoreCase));
            var properties = keys.Select(k => new { Key = k.Replace(variantPrefix, string.Empty), Value = Request.Form[k] }).ToList();

            UCommerce.EntitiesV2.Product variant = null;

            // If there are variant values we'll need to find the selected variant
            if (product.Variants.Any() && properties.Any())
            {
                variant = product.Variants.FirstOrDefault(v => v.ProductProperties
                    .Where(pp => pp.ProductDefinitionField.DisplayOnSite
                        && pp.ProductDefinitionField.IsVariantProperty
                        && !pp.ProductDefinitionField.Deleted)
                    .All(p => properties.Any(kv => kv.Key.Equals(p.ProductDefinitionField.Name, StringComparison.InvariantCultureIgnoreCase) && kv.Value.Equals(p.Value, StringComparison.InvariantCultureIgnoreCase))));
            }
            // Only use the current product where there are no variants
            else if (!product.Variants.Any())
            {
                variant = product;
            }

            return variant;
        }
    }

    Furthermore there is a folder with some helpers, in this folder there is a helper for a product. The content of this file looks like this,

    @using UCommerce
    @using UCommerce.Api
    @using UCommerce.Extensions
    @using UCommerce.EntitiesV2
    @using UCommerce.Runtime
    @using UCommerce.Search
    @using umbraco.MacroEngines
    @helper DisplayListProducts(IEnumerable<UCommerce.EntitiesV2.Product> products, UCommerce.EntitiesV2.Category category)
    {
        var facetsForQuerying = Request.QueryString.ToFacets();

        var filterProducts = category != null ? SearchLibrary.GetProductsFor(category, facetsForQuerying) : new List<UCommerce.Documents.Product>();

        if (filterProducts.Any())
        {
            foreach (var product in filterProducts.Where(x => x.DisplayOnSite))
            {
                var listProduct = products.First(x => x.Sku == product.Sku && x.VariantSku == product.VariantSku);
                @DisplayListItemProduct(listProduct, category)
            }      
        }
        else
        {
            foreach (var product in products.Where(x => x.DisplayOnSite))
            {
                @DisplayListItemProduct(product, category);
            }
        }
    }
    @helper DisplayListItemProduct(UCommerce.EntitiesV2.Product product, UCommerce.EntitiesV2.Category category)
        {
            var url = CatalogLibrary.GetNiceUrlForProduct(product, category);
            var price = CatalogLibrary.CalculatePrice(product);
        <div class="product span4">
            <div class="product-image">
                @if (!string.IsNullOrEmpty(product.ThumbnailImageMediaId))
                {
                    dynamic mediaItem = new DynamicMedia(product.ThumbnailImageMediaId);
                    <a href="@url"><img src="@mediaItem.umbracoFile" /></a>
                }
                @if (product.ProductReviews.Any())
                {
    @* View /App_Code/ReviewHelpers.cshtml for this helper *@
                    <p class="ratings">@uCommerce.Helpers.ProductReview.DisplayStars(product.Rating)</p>
                }
            </div>
            <p class="item-name"><a href="@url">@product.DisplayName()</a></p>
            <p class="item-price">@(price.YourPrice != null ? price.YourPrice.Amount.ToString() : "")</p>
            <p class="btn-group view-details"><a href="@url" class="btn">View more <span><i class="icon-shopping-cart icon-white"></i></span></a></p>
        </div>
    }

    All these files are .cshtml files. The fuctions files is located in \App_Code\uCommerce\Functions in the Razor demo store and the product helper file is located in \App_Code\uCommerce\Helpers. Hope this information can get you a step further.

    /Dennis

  • Gonçalo Assunção 39 posts 68 karma points
    Jan 09, 2015 @ 18:33
    Gonçalo Assunção
    0

    Thank you Dennis!

    I have made some improvements..

    here's the code:


        if (SiteContext.Current.OrderContext.HasBasket)
        {

            SiteContext.Current.OrderContext.ClearBasketInformation();
           

    Basket deleted!



        }

        if (request.QueryString["cartcmd"] != null && request.QueryString["cartcmd"].ToString() == "Add")
        {
            string query = request.QueryString.ToString();
            var parsed = HttpUtility.ParseQueryString(query);

            string product_Sku = parsed["productID"];

            PurchaseOrder obj_basket = TransactionLibrary.GetBasket(true).PurchaseOrder;

            TransactionLibrary.AddToBasket(1, product_Sku, null, true, true);


            if (obj_basket == null || !obj_basket.OrderLines.Any())
            {
               

    Cart is empty!


            }
            else
            {
                foreach (var y in obj_basket.OrderLines)
                {
                   

    @y.ProductName


                }
            }

            HttpContext.Current.Response.Redirect("payment and shipping details_page");
        }

     

    With this, HasBasket = true, it deletes the basket, but it appears that the code regarding the creation of a new basket, doesn't run....

    And also, the "AddToBasked" method is giving me some troubles.. If I don't coment it gives me an error loading the Macro script
                //TransactionLibrary.AddToBasket(1, product_Sku, null, true, true);
               
                TransactionLibrary.ExecuteBasketPipeline();

    What appears to be the issue here?

  • Gonçalo Assunção 39 posts 68 karma points
    Jan 09, 2015 @ 19:56
    Gonçalo Assunção
    0

    Ok, so I found the problem:

     

        if (request.QueryString["cartcmd"] != null && request.QueryString["cartcmd"].ToString() == "Add")
        {
            str_query = request.QueryString.ToString();
            var parsed = HttpUtility.ParseQueryString(str_query);

             product_Sku = parsed["productID"].ToString();

            if (SiteContext.Current.OrderContext.HasBasket)
            {
                bool_hasBasket = false;
            }
            else
            {
                bool_hasBasket = true;
            }
            PurchaseOrder obj_basket = TransactionLibrary.GetBasket(bool_hasBasket).PurchaseOrder;

            obj_basket.OrderLines.Clear();
            obj_basket.Save();

            TransactionLibrary.AddToBasket(1, product_Sku, null, true, true);

         
                if (!obj_basket.OrderLines.Any())
                {
                   

    Cart is empty!


                }

                HttpContext.Current.Response.Redirect("payment and shipping details_page");
           
        }

     

    This is my code now, and it works... Turns out, the pricing on the product that I was using for tests, didn't have the "pricing" definied in Ucommerce...


Please Sign in or register to post replies

Write your reply to:

Draft