Updating cart removing items at random

in Help edited January 2013
HI guys,

I'm fairly intermediate with javascript and json, but am keen to get this advanced cart of mine running. I'm in the early stages but have come across a weird problem which I'll provide some backstory to first.

I'm building a cart system for my company which has very loose pricing options. Every customer has difference prices for all our products, and these prices will adjust based on quantity. I'm going to build a database that pulls all the pricing information out and adjusts on the site depending on who's logged in. This is down the road. Right now, I'm just working on the script that will adjust the price of items in the cart. If you visit my store you can add 3 items at 3 volume sizes. These are currently set at $20. I've created a link, that when clicked removes all the items from the cart and re-adds them at a new price of $19. This works great, the first time. If I click it again it should just run the script again and re-add them still at $19. The console seems to say this is happening, but when I open the cart sometimes 1, 2 or 3 items have simply vanished.

Is there anything totally obvious that I've missed/messed up here?
My next step is going to run this script when the add to cart button is pressed, but I wanted to get this bug out of the way first. Ideally what will happen is the item is added to the cart, it will check and see how many items are in the cart, if a price break has been reached it will remove them and re-add them according to the new price point.

Am I using the best javascript file for this? Should I be using raw? Thanks for any help.

view the store at http://www.integra-adhesives.com/shop/
myfoxy.js is the script I'm working on.

Tagged:
Comments
  • fc_adamfc_adam FoxyCart Team
    @terenceRoberts,

    So if I'm understanding you correctly, you're basically setting up pricing tiers, that adjusts depending on the quantity ordered?

    If that is the case, I'd suggest setting up product discounts for the products that have those volume discounts. Let's say for example, that you have a product that is priced at $20, for 3-9 products it becomes $19 and 10+ it becomes $18 per product. You would set that up with a discount that looked like this:

    In a link:
    discount_quantity_amount=Volume Discount{3-1|10-2}
    

    In a form:
    <input type="hidden" name="discount_quantity_amount" value="Volume Discount{3-1|10-2}" />
    

    You could do it with javascript if you wanted - but this will be a much more robust way to do it, and will allow people to change the quantity on the cart without you having to duplicate your javascript there as well.
  • @fc_adam,

    Jeez. I was making things far more complicated then needed. I didn't realise that I could break up the quantity discount like that. So if there were discounts based on the options as well would I control that just with an if statement in php? I know I could do this in PHP, just want to make sure nothing else is built in that I'm missing.

    Say
    Product 1 - Option 1 = $20 @ 1, $19 @ 3, $18 @ 10
    Product 1 - Option 2 = $18 @ 1, $15 @ 3, $12 @ 10
    Product 1 - Option 3 = $16 @ 1, $12 @ 3, $10 @ 10

    thanks for your quick response, and much more elegant solution.

  • fc_adamfc_adam FoxyCart Team
    @terenceRoberts,

    Ah - so that will make it a little bit different. I'm assuming the options are a dropdown for the individual product, rather than three separate products.

    In that case, you'll need to get a little fancy. Two options I can think of.

    Firstly, you can use javascript to switch out the discount string depending on the option selected. So if option 2 is selected, you'd change it to {3-3|10-6}.

    The second option depends how you've got your products set up. If those volume discounts were standard across your products, you could set up three categories to represent those three volume discounts and apply the discount at the category level. Then, on your option listing, you could use product modifiers to change the category code to put the product into the required category. That way, depending on the option chosen, the category will be different which will apply the different category level. So your select dropdown could look like this:
    <input type="hidden" name="price" value="20" />
    <input type="hidden" name="category" value="cat1" />
    <select name="option">
      <option value="Option 1">Option 1</option>
      <option value="Option 2{p-2|y:cat2}>Option 2</option>
      <option value="Option 3{p-4|y:cat3}>Option 3</option>
    </select>
    
  • @fc_adam

    Perfect, thanks again. I see the advantages of both routes. We have say 15 different products with their own qty price break points, and for some products there are two options which will affect price breaks differently based on the volume and whether the colour is stock or custom. It might end up easier doing it in javascript/php and using a switch or if statements, especially since all the pricing information is unique I'll be pulling that out of the database with php anyway. I'll play around and see which will be easier to maintain in the long run.

    cheers
  • @fc_adam,

    Hi, I'm back.
    Is there any way to create the category level discounts dynamically?
    If you visit the shop link I submitted earlier there are 3 colours and 3 volumes set up right now. The discounts apply fine, except if I wanted to have a 100ml Alabaster, 100ml Bisque, and 100ml Bone. I guess the discount is only being applied to the specific product it's assigned.

    I can't use the category level discounts in the foxycart admin because customer 1 and customer 2 will have different discount amounts (ie. customer 1 order 4 100ml's (of any stock colour) and gets a $3.50 discount whereas customer 2 orders 4 100ml's (of any stock colour) and get's a $4.25 discount.)

    If I could dynamically adjust the category discount that would be great, but I haven't seen any documentation on this. Is there another route? I was thinking maybe creating coupons with dynamic discounts might work, but wanted to check if there was another solution first.

    Cheers.

  • fc_adamfc_adam FoxyCart Team
    @terenceRoberts,

    So it's not possible to create a dynamic category level discount - but you could instead work on a dynamic product level discount as part of your add to cart form. Using javascript you'd dynamically change the discount string to match what the customer selects.
  • @fc_adam,

    Right now I'm using Javascript to change the discount code like so:
    switch(value) {
    	    case '100ml':
    	        $('.label_right').text('Price : $19.50/ea');
    		$('#price').val('19.50');
    		$('#vol_disc').val('Volume Discount{4-5|20-7.50|y:100ml_xi}');
    		$('#stock_cust').val('stock');
    		$('#cat').val('100ml_xi');
    		break;
    						
    		case '250ml':
    		$('.label_right').text('Price : $35.00/ea');
    		$('#price').val('35.00');
    		$('#vol_disc').val('Volume Discount{4-13.50|y:250ml_xi}');
    		$('#stock_cust').val('stock');
    		$('#cat').val('250ml_xi');
    		break;
    						
    		case '500ml':
    		$('.label_right').text('Price : $37.00/ea');
    		$('#price').val('37.00');
    		$('#vol_disc').val('Volume Discount{12-3|y:500ml_xi}');
    		$('#stock_cust').val('stock');
    		$('#cat').val('500ml_xi');
    		break;
    	}
    

    And it works fine for individual products, it's more when things are in the cart that I'm having issues. If I have 2 100ml Alabaster, 1 100ml Bisque and 1 100ml Bone it's treating them separately. They are essentially the same 'product' and should be treated as such as far as the discount goes, the colour is just an option.

    This is what I was doing before, and it was working except that when it added them back to the cart sometimes they would all get added back, sometimes it would be missing 1, or 2, or all.
    function jsonp_seesion() {
    	var ids = [];
    	var obj = {};
    	var remove_url;
    	var add_url;
    	var current_price;				
    	$.ajax({
    		dataType: 'jsonp',
    		url: 'https://integra.foxycart.com/cart?output=json',
    		success: function(jsonp){
    			// get length of all products in cart
    			for(var p = 0; p < jsonp.products.length; p++) {
    				current_price = jsonp.products[p].base_price;
    				current_price -= 1;
    				
    				//put all the object data into an object
    				obj = {
    					"type":jsonp.products[p].name,
    					"color":jsonp.products[p].options.colour,
    					"group":jsonp.products[p].options.pricegroup,
    					"id":jsonp.products[p].id,
    					"size":jsonp.products[p].options.size,
    					"qty":jsonp.products[p].quantity
    				};
    				// push the object into array
    				ids.push(obj);
    				
                                    //call replace_products function with product id parameter
    				replace_products(ids[p].id);
    			}					
    			
    			function replace_products(product_id) {
    				remove_url="https://integra.foxycart.com/cart?output=json&cart=update&id="+product_id+"&quantity=0"+fcc.session_get();
    		 
    				// Do the remove request, with parameter quantity=0
    				$.ajax({
    					dataType: 'jsonp',
    					//type: "POST",
    					url: remove_url
    					//async: false,
    				});
    				add_items();
    			}
    							
    			function add_items() {
    				add_url=get_add_url();
    				console.log("add_url : "+add_url);
    				$.ajax({
    					dataType: 'jsonp',
    					url: add_url
    				});
    								
    			}
    							
    			function get_add_url() {
    			add_url="https://integra.foxycart.com/cart?name="+ids[p].type+"&colour="+ids[p].color+"&pricegroup="+ids[p].group+"&size="+ids[p].size+"&quantity="+ids[p].qty+"&price=19"+fcc.session_get();
    				return add_url;
    			}
    		}
    	})
    }
    

    Do you think I need to be going back to doing something more like that?
  • fc_adamfc_adam FoxyCart Team
    @terenceRoberts,

    If I'm understanding you correctly, you're saying that if you change one of the options in the add to cart, it's adding it as a different colour - is that right? If that's correct, that is expected behaviour. Products with different options will be broken out on their own. So if I add a red shirt and a blue shirt, that will be two different products in the cart.

    Just a heads up, you can't use product modifiers in a discount, so the following wont work like you're expecting it to:
    $('#vol_disc').val('Volume Discount{4-5|20-7.50|y:100ml_xi}');
    

    That last tier with 'y:100ml_xi' isn't valid for a discount string.
  • edited January 2013
    @fc_adam,

    Okay. I think based on what you've told me I need to go back to my first approach using Javascript to remove/re-add items. I think I probably need to read up on the preprocess/process/postprocess functions to get what I want. I don't want to eat much more of your time, but let me list off what I'm needing to build, and you just let me know if this is doable, and maybe some pointers at what I need to read up on!

    1. There are 11 base products
    2. Of these products, the main selling product is offered in 3 volumes and 300 colours.
    3. The 3 volume sizes have unique base price points for 1 unit ordered, and have price break points at various levels purchased.
    4. In addition to the volume price points, there are also stock colours and custom colours available, custom colours will have different prices and price breaks than stock.
    5. The pricing and price breaks are unique to each customer. While there are base prices that many customers receive across the board, there are many customers who will receive a lower base price and different prices at quantity purchased.

    So in your last post, you were understanding me correctly. Customers need to be able to mix and match product options, that is, 1 main product and 4 different options will still trigger the discount even if they're seen as separate products by the cart system.

    What I was doing before with the javascript was when items were added to the cart, I was thinking I could check every item in the cart and then arrange each by product type in arrays/objects. Then if the quantity of items was hit remove all those items and re-add them at the new price. This seemed to work except that items were randomly disappearing. Probably my own scripting shortcomings which I can figure out. But I also need to run this script if they modify the quantity within the cart screen. And I'm thinking this is where the pre-process/process/post-process functions will come into play. The question I have with them is do I just make my own .js file and create a function with those names and they will automatically get called?

    Thanks again for all your time!
  • fc_adamfc_adam FoxyCart Team
    @terenceRoberts,

    So that's a pretty intense setup!

    So to apply a discount across multiple different products - the category discount will be your best bet - but the issue there is that you can't dynamically change what that discount is - which you will need to do from what I understand. Unless the different pricing some customers receive is standard - such as you have maybe two or three different discount tiers that customers could receive? If that's the case, you could have a different category for each of those different price tiers - and depending on the customer, you could change the category setting in the add to cart. Could that work?

    You could go back to adding/removing products to get the end result as well, and you're right that you'll need to do this on your website and on the cart. On your website you'd make use of the preprocess/process events to work out what needs to be added and removed. On your cart though, you would just do it on page load - you wouldn't use those process functions - as if someone updates the cart, that triggers a page refresh.

    If those price breaks are somewhat standard for the different customers - I'd go the category route if it were me - purely because adding and removing products can get a little involved when you start doing it with each add to cart action.
  • @fc_adam,

    Intense setup indeed. I've gone through a number of eCommerce setups trying to find something that can accommodate this tall order.

    You've got a good point with the price groups. I will look and see if we could break all customers down to price group categories like 8-10. That would still then mean many subcategories , but could be an easier solution in the long run. If there are 20-30+ with the infinite possibility of expansion I will have to go the javascript route.

    I will inquire about this with management, but I'm likely going to have to end up the fully custom route. As an entry level developer it's both daunting and exciting! I'll let you know how I make out.
  • edited March 2013
    @fc_adam,

    I figured I might as well continue in this thread so I'm back to having an issue similar to when I started out. My cart is almost finished. All the if statements pulling out various prices here any there.

    I've got one last issue. There are two more pricing variables where if a customer hits a specific quantity of a certain cartridge size they get a price break, but only if this minimum is met and is in specified increments.

    I have a loop that goes through all products in the cart and puts those that meet this criteria into an object and into an array.

    Now what I'm trying to do, is if the customer adjusts the quantity in the ^^cart^^ page to run this script. So I'm editing my /cart/, but can't figure out how to get the products in.
    function replace_products(product_id) {
    // Do the remove request, with parameter quantity=0        
        remove_url='https://integra.foxycart.com/cart?&output=json&cart=update&id=' + product_id + '&quantity=0';
            
            
            $.ajax({
              dataType: 'jsonp',
              type: "POST",
              url: remove_url,
              //async: false,
              success: function() {console.log('successfully removed!');fc_UpdateCart();}
            });
            
            add_items();
          }
          
      function add_items() {
        add_url="https://integra.foxycart.com/cart?&output=json&cart=update&name=test&colour=red&price=12&&size=100ml&quantity=14";
        //add_url='https://integra.foxycart.com/cart?&output=json&cart=update&name='+ids[i].name+'&colour='+ids[i].colour+'&size='+ids[i].size+'&quantity='+ids[i].qty+'&price='+ids[i].base_price;
        
        $.ajax({
          dataType: 'jsonp',
          type: "POST",
          url: add_url,
          success: function() {console.log('successfully added!');fc_UpdateCart();}
        });
      }
    
    

    So the items are being removed. And the data for what needs to be sent to update the cart gets sent, but the items won't appear in the cart.

    I'm wondering if it's because of the callback function (which I don't have) but when I try to call fcc.session_get() it says fcc not defined.

    am I missing something obvious?

    cheers


    ** Nevermind, I think I sorted it. I had i changed cart=update to cart=add and it seems to work!

    I also combined it all into one call because I think that sometimes it was executing the add before the remove was complete.
    $.ajax({
              dataType: 'jsonp',
              type: "POST",
              url: remove_url,
              success: function() {console.log('successfully removed!');
                  $.ajax({
                    dataType: 'jsonp',
                    type: "POST",
                    url: add_url,               
                    success: function() {console.log('successfully added!');fc_UpdateCart();}
                  });
                }
            });
    
  • fc_adamfc_adam FoxyCart Team
    @terenceRoberts,

    Glad you were able to get that working.

    In terms of the fcc not defined error - currently there is a bit of a disconnect between your website and the cart/checkout templates. The new fcc object doesn't exist on the cart/checkout - but the cart json object is available as fc_json.
Sign In or Register to comment.