[NEED HELP] Replacing a product in the shopping cart

Djekh
New Member
1 0 0

Hello,

I need your help, I would like to create a script that would detect if there are more than 2 products in my cart and replace them with another product.

Basically, if the customer has 2 items in his cart then the script removes 1 item and adds the same item with a reduction of -50%.

To do this I duplicate my products and set the price at -50% than the original.

For easy reference I have named my products:

- ROLEX

- ROLEX (-50%)

If the customer has 2 ROLEX in his basket then the script removes one of them and adds the rolex at -50% in his basket.

Here is the basis of my script but I can't go any further:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js" integrity="sha512-3j3VU6WC5rPQB4Ld1jnLV7Kd5xr+cq9avvhwqzbH/taCRNURoeEpoPBK9pDyeukwSxwRPJ8fDgvYXd6SkaZ2TA==" crossorigin="anonymous"></script>

<script>
jQuery(document).ready(function() {
 jQuery.getJSON('/cart.js', function(cart) {  
   if(Cookies.get('updated') != btoa(JSON.stringify(cart))) {   
          var reduced_paire = Math.floor(cart.item_count / 2); 
          var items_count = Object.keys(cart.items).length;
          const variants = [];

          {% for product in collections.all.products %}
              {% for variants in product.variants %}
                  variants.push(['{{ product.title }}', '{{ variants.title }}', '{{ variants.id }}']);    
              {% endfor %}
          {% endfor %}

          var loop_count = 0;
                                 
          if(reduced_paire > items_count) {
            jQuery.each(cart.items, function(index) {                                 
              if(reduced_paire < cart.items[index].quantity) {
                if(loop_count != reduced_paire) {
                  var id = cart.items[index].id;
                  var quantity = cart.items[index].quantity;
                  const found = variants.filter(v => v[0] == ""+ cart.items[index].title +" (-50%)" && v[1] == ""+ cart.items[index].variant_title +"");
                  console.log(found);
                  jQuery.post('/cart/add.js', {
                       id: found.id,
                       quantity: quantity - reduced_paire
                  });
                  jQuery.post('/cart/change.js', {
                      'id': id,
                      'quantity': quantity - reduced_paire
                  });
                  var loop_count = loop_count + reduced_paire;
                }
               } else {
                 console.log("error : 2");
               }
            });
          } else {
            console.log("error : 1");
          }
  
  		  Cookies.set('updated', btoa(JSON.stringify(cart)));
   		}
	});
});
</script>

 

Thank you in advance for your help

0 Likes