Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add a deposit product to the cart based on cart total
<script>
{% assign deposit = all_products['deposit'] %}
BookingDeposit = function() {
var _this = this;
_this.cart = {{ cart | json }};
_this.depositProduct = {{ deposit | json }};
_this.depositAmount = 0;
_this.depositLine = -1;
_this.cartDepositVariantId = -1;
_this.lineQuantities = [];
this.init = function() {
_this.initData();
_this.calcDepositAmount();
if (_this.depositAmount == 0) {
if (_this.depositLine > -1) {
// remove existing deposit product
_this.removeDeposit().done(function() {
location.href = '/cart';
});
}
} else {
var depositVariant = _this.findDepositVariant();
if (_this.depositLine > -1) { // deposit variant is already in cart
if (_this.cartDepositVariantId != depositVariant.id) {
// remove existing deposit product then add new one
_this.removeDeposit().done(function() {
_this.addDepositThenReturn(depositVariant);
});
}
} else {
_this.addDepositThenReturn(depositVariant);
}
}
};
this.calcDepositAmount = function() {
for (var i = 0; i < _this.cart.items.length; i++) {
var item = _this.cart.items[i];
if (item.handle != 'deposit') {
_this.depositAmount += item.line_price;
}
}
};
this.findDepositVariant = function() {
var amount = _this.depositAmount * 100;
var index = 0,
variant = _this.depositProduct.variants[0];
while ((variant.price - amount < 0) && index < _this.depositProduct.variants.length) {
index++
variant = _this.depositProduct.variants[index];
}
return variant;
};
this.removeDeposit = function() {
return $.ajax({
type: 'POST',
url: '/cart/change.js',
data: {line: _this.depositLine, quantity: 0},
dataType: 'json'
});
}
this.addDepositThenReturn = function(variant) {
$.ajax({
type: 'POST',
url: '/cart/add.js',
data: {id:variant.id, quantity:1},
dataType: 'json'
}).done(function(cart) {
location.href = '/cart';
});
}
this.initData = function() {
{% for item in cart.items %}
{% if item.product.handle == 'deposit' %}
_this.depositLine = {{ forloop.index }};
_this.cartDepositVariantId = {{ item.variant_id }};
{% endif %}
_this.lineQuantities.push({{ item.quantity }});
{% endfor %}
}
this.init();
}
document.addEventListener("DOMContentLoaded", function(event) {
new BookingDeposit();
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.