WDDiscountApp.CartPage.Show_CalculateTier = function () {
var TierProducts = [];
var UpdateCartItem = function (item, updatedItemPrice, updatedLinePrice, isNotInRange, isUpdate, index) {
if (isUpdate) {
var originalItemPrice = globalFields.ConvertToFixedDecimalNumber(item.original_price / 100), originalLinePrice = globalFields.ConvertToFixedDecimalNumber(item.original_line_price / 100);
var condition1 = updatedItemPrice == originalItemPrice;
updatedItemPrice = globalFields.ConvertToFixedDecimalString(updatedItemPrice), updatedLinePrice = globalFields.ConvertToFixedDecimalString(updatedLinePrice);
if (isNotInRange || condition1) {
jQuery('#ecom-cart .ecom-cart__product-prices').eq(index).html('
' + globalFields.formatMoney(updatedItemPrice, globalFields.amount) + '
');
jQuery('.drawer__contents .drawer__cart-items-wrapper td[headers="CartDrawer-ColumnProduct"]').eq(index).find('.cart-item__discounted-prices,.product-option:first').html('' + globalFields.formatMoney(updatedItemPrice, globalFields.amount) + '
');
jQuery('.drawer__cart-items-wrapper .cart-item__totals.right .cart-item__price-wrapper').eq(index).html('' + globalFields.formatMoney(updatedLinePrice, globalFields.amount) + '
');
jQuery('#ecom-cart .ecom-cart__product-item__totals .ecom-cart__product-item__price-wrapper').eq(index).html('' + globalFields.formatMoney(updatedLinePrice, globalFields.amount) + '
');
$('.ecom-cart__product-discounts').hide()
}
else {
originalItemPrice = globalFields.ConvertToFixedDecimalString(originalItemPrice), originalLinePrice = globalFields.ConvertToFixedDecimalString(originalLinePrice);
jQuery('#ecom-cart .ecom-cart__product-prices').eq(index).html('' + globalFields.formatMoney(originalItemPrice, globalFields.amount) + '
' + globalFields.formatMoney(updatedItemPrice, globalFields.amount) + '
');
jQuery('.drawer__contents .drawer__cart-items-wrapper td[headers="CartDrawer-ColumnProduct"]').eq(index).find('.cart-item__discounted-prices , .product-option:first').html('' + globalFields.formatMoney(originalItemPrice, globalFields.amount) + '
' + globalFields.formatMoney(updatedItemPrice, globalFields.amount) + '
');
jQuery('.drawer__cart-items-wrapper .cart-item__totals.right .cart-item__price-wrapper').eq(index).html('' + globalFields.formatMoney(originalLinePrice, globalFields.amount) + '
' + globalFields.formatMoney(updatedLinePrice, globalFields.amount) + '
');
jQuery('#ecom-cart .ecom-cart__product-item__totals .ecom-cart__product-item__price-wrapper').eq(index).html('' + globalFields.formatMoney(originalLinePrice, globalFields.amount) + '
' + globalFields.formatMoney(updatedLinePrice, globalFields.amount) + '
');
// $('.ecom-cart__product-discounts').hide()
}
}
jQuery('.discounts.list-unstyled').remove();
}
var UpdateCartSubtotal = function (isUpdate, updatedTotalPrice, originalTotalPrice) {
if (isUpdate) {
updatedTotalPrice = globalFields.ConvertToFixedDecimalString(updatedTotalPrice), originalTotalPrice = globalFields.ConvertToFixedDecimalString(originalTotalPrice);
if (originalTotalPrice != updatedTotalPrice) {
jQuery('#ecom-cart .ecom-cart__informations-items_subtotal_price .totals__subtotal-value').html('' + globalFields.formatMoney(originalTotalPrice, globalFields.amount) + ' ' + globalFields.formatMoney(updatedTotalPrice, globalFields.amount) + '');
jQuery('.cart-drawer__footer .totals .totals__total-value').html('' + globalFields.formatMoney(originalTotalPrice, globalFields.amount) + ' ' + globalFields.formatMoney(updatedTotalPrice, globalFields.amount) + '');
}
else {
jQuery('#ecom-cart .ecom-cart__informations-items_subtotal_price .totals__subtotal-value').html('' + globalFields.formatMoney(updatedTotalPrice, globalFields.amount) + '');
jQuery('.cart-drawer__footer .totals .totals__total-value').html('' + globalFields.formatMoney(updatedTotalPrice, globalFields.amount) + '');
}
}
}
var UpdateSavingMessage = function (isUpdate) {
if (priceDiff > 0 && isUpdate && globalFields.isCartPage) {
var saveMessage = globalFields.settings.cart_saving_message.replace('{{discount_amount}}', '' + globalFields.formatMoney(priceDiff.toFixed(2), globalFields.amount) + '');
var saveHtml = '' + saveMessage + '';
if (jQuery(window).width() < 700) {
jQuery('#saved-banner-div').length == 0 ? jQuery('#ecom-cart .ecom-cart__informations-items_subtotal_price').after('' + saveHtml + '
') : jQuery('#saved-banner-div').html(saveHtml);
}
else{
jQuery('#saved-banner-div').length == 0 ? jQuery('#ecom-cart .ecom-cart__informations-items_subtotal_price').after('' + saveHtml + '
') : jQuery('#saved-banner-div').html(saveHtml);
}
}
else if (globalFields.isCartPage) {
jQuery('#saved-banner-div').remove();
}
}
var CheckoutClickCart = function () {
console.log("checkout...")
jQuery('#ecom-cart button[name="checkout"]').click(function () {
// jQuery('[name="updates[]"]').each(function () {
// var qtyValue = this.value; var idAtrbtValue = jQuery(this).attr('id'); idAtrbtValue = idAtrbtValue.split('_'); idAtrbtValue = idAtrbtValue[1];
// idAtrbtValue = idAtrbtValue.split(':'); idAtrbtValue = idAtrbtValue[0];
// for (i = 0; i < globalFieldsCartPage_WD.cartObj.items.length; i++) {
// if (globalFieldsCartPage_WD.cartObj.items[i].variant_id == Number(idAtrbtValue)) { globalFieldsCartPage_WD.cartObj.items[i].quantity = Number(qtyValue); }
// }
// });
// TieredPricingCart(globalFieldsCartPage_WD.cartObj, false);
GetCode(false);
});
}
var CheckoutClickAjax = function () {
jQuery('.drawer__footer button[name="checkout"]').click(function (e) {
e.preventDefault();
GetCode(true);
});
}
var GetCode = function (isUpper) {
if (priceDiff > 0) {
jQuery.ajax({
type: "POST", async: false, url: "https://wholesale.apptiv.in/tier/ACPGenerateDiscountCode",
data: { priceDifference: priceDiff, subTotal: minimumDiscountSubtotal, variantIds: variantIdsToSend.toString() },
success: function (result) {
var data_ = JSON.stringify(result); var parsed_data = JSON.parse(data_); var PRID = parsed_data.PRID;
var DCID = parsed_data.DCID; var DiscountCode = parsed_data.DiscountCode;
SetCookie("discountCodes", PRID + "-" + DCID + "-" + DiscountCode, 30);
if (!isUpper) {
DiscountCodeCookie(DiscountCode);
jQuery('form[action="/cart"]').append('');
window.location.href = '/checkout?discount=' + DiscountCode;
} else {
DiscountCodeCookie(DiscountCode);
//jQuery('form.cart-form').append('');
window.location.href = '/checkout?discount=' + DiscountCode;
}
},
error: function (e) { console.log(e.statusText); window.location.href = '/checkout'; }
});
}
else if (isUpper) {
window.location.href = '/checkout';
}
else{
window.location.href = '/checkout';
}
}
//DRAFT ORDER API
let marketregion = globalFields.CuurencyCode();
// var GetCode = function (isUpper) {
// if (priceDiff > 0) {
// jQuery.ajax({
// //type: "POST", async: false, url: "https://wholesale.apptiv.in/api/ACPGeneratedraftorderforAllstore",
// type: "POST", async: false, url: "https://wholesale.apptiv.in/tier/ACPGenerateDiscountCode",
// data: {TierProductsarray:JSON.stringify(TierProducts),DiscountText:"",priceDifference: priceDiff, subTotal: minimumDiscountSubtotal, variantIds: variantIdsToSend.toString(),cartItemsObj:JSON.stringify(globalFieldsCartPage_WD.cartObj),MarketRegionCode:marketregion },
// success: function(result) {
// setTimeout(function() {
// window.location.href = result;
// },300);
// },
// error: function (e) { console.log(e.statusText); window.location.href = '/checkout'; }
// });
// }
//else if (isUpper) {
// window.location.href = '/checkout';
// }
//else{
// window.location.href = '/checkout';
// }
//}
var ReInvokeAjaxCartButton = function () {
jQuery('.mb_cart.mb_item button.btn, .top-header .dropdown-cart button.btn').off("click"); CheckoutClickAjax();
}
var variantIdsToSend = [], minimumDiscountSubtotal = 0, priceDiff = 0;
var hide_buttons = null;
var HideAdditionalPayments = function() {
hide_buttons = setInterval(function() {
console.log('buttons and tiered');
if(jQuery('.additional_checkout_buttons, .dynamic-checkout__content').length>0){
jQuery('.additional_checkout_buttons, .dynamic-checkout__content').hide();
clearInterval(hide_buttons);
}
}, 500);
}
var TieredPricingCart =async function (cartObject, isUpdate) {
TierProducts = [];
variantIdsToSend = []; minimumDiscountSubtotal = 0; priceDiff = 0; var updatedTotalPrice = 0;
for (k = 0; k < cartObject.items.length; k++) {
var item = cartObject.items[k], isInRange = true; itemTiers = GetTiersFromTiersArray(item.variant_id);
if (itemTiers != undefined && itemTiers.status && globalFields.StartEndDateValid(itemTiers.start_date, itemTiers.end_date)) {
let DiscountAppliedOn = itemTiers.DiscountAppliedON != null && itemTiers.DiscountAppliedON != '' && itemTiers.DiscountAppliedON != undefined ? true : false;
let Location_Tag_s = itemTiers.Location_Tag_ != null && itemTiers.Location_Tag_ != '' && itemTiers.Location_Tag_ != undefined ? true : false;
if(DiscountAppliedOn){
if(Location_Tag_s){
let DiscountAppliedOnTag =itemTiers.DiscountAppliedON == 'Both_Store' || itemTiers.DiscountAppliedON == 'Online_Store' ? true : false;
let LocationObject = Object.keys(itemTiers.Location_Tag_);
if(LocationObject[0] == 'StoreLocation'){
let StoreLocationcheck = itemTiers.Location_Tag_[LocationObject[0]].includes(globalFields.Storecountry) || itemTiers.Location_Tag_[LocationObject[0]].includes(globalFields.Storecity) ? true : false;
if(StoreLocationcheck && DiscountAppliedOnTag){
var rslt =await CalculateTier(item, itemTiers, updatedTotalPrice, isUpdate, true, k);
updatedTotalPrice = rslt[0]; isInRange = rslt[1];
if (rslt[1]) {
updatedTotalPrice += globalFields.ConvertToFixedDecimalNumber(item.original_line_price / 100);
}
}else{
updatedTotalPrice += globalFields.ConvertToFixedDecimalNumber(item.original_line_price / 100);
}
}else{
let TierLocation = itemTiers.Location_Tag_[LocationObject[0]];
let CusotmerCountryLocation = globalFields.Customercountry;
let CusotmerCityLocation = globalFields.Customercity;
let CustomerLocationcheck_1 = (arr, arr1) =>{return arr.some(item => arr1.includes(item))};
let CustomerLocationcheck_2 = (arr2, arr3) =>{return arr2.some(item => arr3.includes(item))};
let CityValue = CustomerLocationcheck_1(TierLocation,CusotmerCountryLocation);
let CountryValue = CustomerLocationcheck_2(TierLocation,CusotmerCityLocation);
if(DiscountAppliedOnTag && (CityValue || CountryValue)){
var rslt =await CalculateTier(item, itemTiers, updatedTotalPrice, isUpdate, true, k);
updatedTotalPrice = rslt[0]; isInRange = rslt[1];
if (rslt[1]) {
updatedTotalPrice += globalFields.ConvertToFixedDecimalNumber(item.original_line_price / 100);
}
}else{
updatedTotalPrice += globalFields.ConvertToFixedDecimalNumber(item.original_line_price / 100);
}
}
}else{
if(itemTiers.DiscountAppliedON == 'Both_Store' || itemTiers.DiscountAppliedON == 'Online_Store' ){
var rslt =await CalculateTier(item, itemTiers, updatedTotalPrice, isUpdate, true, k);
updatedTotalPrice = rslt[0]; isInRange = rslt[1];
if (rslt[1]) {
updatedTotalPrice += globalFields.ConvertToFixedDecimalNumber(item.original_line_price / 100);
}
}else{
updatedTotalPrice += globalFields.ConvertToFixedDecimalNumber(item.original_line_price / 100);
}
}
}else{
var rslt =await CalculateTier(item, itemTiers, updatedTotalPrice, isUpdate, true, k);
updatedTotalPrice = rslt[0]; isInRange = rslt[1];
if (rslt[1]) {
updatedTotalPrice += globalFields.ConvertToFixedDecimalNumber(item.original_line_price / 100);
}
}
}
else {
updatedTotalPrice += globalFields.ConvertToFixedDecimalNumber(item.original_line_price / 100);
}
if (!isInRange) {
minimumDiscountSubtotal += globalFields.ConvertToFixedDecimalNumber(item.original_line_price / 100); variantIdsToSend.push(item.variant_id);
}
}
UpdateCartSubtotal(isUpdate, globalFields.ConvertToFixedDecimalNumber(updatedTotalPrice), globalFields.ConvertToFixedDecimalNumber(cartObject.original_total_price / 100));
priceDiff = globalFields.ConvertToFixedDecimalNumber((globalFields.ConvertToFixedDecimalNumber(cartObject.original_total_price / 100) - globalFields.ConvertToFixedDecimalNumber(updatedTotalPrice)));
UpdateSavingMessage(isUpdate);
if(priceDiff){
HideAdditionalPayments();
}
setTimeout(function(){
clearInterval(hide_buttons);
}, 5000);
}
setTimeout(function(){
clearInterval(hide_buttons);
}, 10000);
var GetTiersFromTiersArray = function (variantId) {
var tierObj = jQuery.grep(globalFieldsCartPage_WD.cartTiersArray, function (n) { return (n.variant_id === variantId); });
if (tierObj[0].tiers == "[]") {
return undefined;
}
else {
return globalFields.GetTierObject(tierObj[0].tiers[0], variantId);
}
}
// var CalculateTier = function (item, itemTiers, updatedTotalPrice, isUpdate, isNotInRange, index) {
// for (i = 0; i < itemTiers.tier_min.length; i++) {
// var allVariantItemQty = 0;
// var tierPrice = parseFloat(itemTiers.tier_values[i]);
// var minTier = parseInt(itemTiers.tier_min[i]), maxTier = itemTiers.tier_max[i] != 'max' ? parseInt(itemTiers.tier_max[i]) : itemTiers.tier_max[i];
// var updatedItemPrice = 0, updatedLinePrice = 0, condition1 = false, condition2 = false;
// if (itemTiers.entity_type === 'products' || itemTiers.entity_type === 'collections') {
// var tempItemArray = [];
// if (itemTiers.entity_type === 'collections') {
// var tempTierArray = jQuery.grep(globalFieldsCartPage_WD.cartTiersArray, function (n) { return (n.tiers != '[]' && n.tiers[0].entity_type == 'collections' && n.tiers[0].entity_id == itemTiers.entity_id); });
// for (var m = 0; m < tempTierArray.length; m++) {
// var temp = jQuery.grep(globalFieldsCartPage_WD.cartObj.items, function (n) { return (n.variant_id == tempTierArray[m].variant_id); });
// if (temp.length != 0) {
// tempItemArray.push(temp[0]);
// }
// }
// }
// else {
// tempItemArray = jQuery.grep(globalFieldsCartPage_WD.cartObj.items, function (n) { return (n.product_id == item.product_id ); });
// }
// for (j = 0; j < tempItemArray.length; j++) { allVariantItemQty += tempItemArray[j].quantity; }
// condition1 = allVariantItemQty >= minTier;
// condition2 = maxTier == "max" || allVariantItemQty <= maxTier;
// }
// else {
// condition1 = item.quantity >= minTier;
// condition2 = maxTier == "max" || item.quantity <= maxTier;
// }
// if (condition1 && condition2) {
// isNotInRange = false;
// if (itemTiers.discount_type == 'percentage') {
// var originalPriceCut = parseFloat(globalFields.ConvertToFixedDecimalNumber((parseFloat(tierPrice) / 100) * globalFields.ConvertToFixedDecimalNumber(item.original_price / 100)));
// updatedItemPrice = globalFields.ConvertToFixedDecimalNumber(globalFields.ConvertToFixedDecimalNumber(item.original_price / 100) - originalPriceCut);
// }
// else if (itemTiers.discount_type == 'fixed') {
// updatedItemPrice = globalFields.ConvertToFixedDecimalNumber(globalFields.ConvertToFixedDecimalNumber(item.original_price / 100) - parseFloat(tierPrice));
// }
// else if (itemTiers.discount_type == 'fixed_price') {
// updatedItemPrice = globalFields.ConvertToFixedDecimalNumber(parseFloat(tierPrice));
// }
// if (updatedItemPrice < 0) { updatedItemPrice = 0; }
// updatedLinePrice = globalFields.ConvertToFixedDecimalNumber(updatedItemPrice * item.quantity);
// updatedTotalPrice += globalFields.ConvertToFixedDecimalNumber(updatedLinePrice);
// UpdateCartItem(item, updatedItemPrice, updatedLinePrice, isNotInRange, isUpdate, index);
// }
// }
// if (isNotInRange) {
// UpdateCartItem(item, globalFields.ConvertToFixedDecimalNumber(item.original_price / 100), globalFields.ConvertToFixedDecimalNumber(item.original_line_price / 100), isNotInRange, isUpdate, index);
// }
// return [updatedTotalPrice, isNotInRange];
// }
var CalculateTier =async function (item, itemTiers, updatedTotalPrice, isUpdate, isNotInRange, index) {
let isFound = TierProducts.some(element => {if (element.VarientID === item.variant_id) { return true;}return false;});
//get cost price
async function getCostPrice1(variantId){
console.log("cost price");
let accessToken = "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";
const myHeaders = new Headers();
myHeaders.append("X-Shopify-Access-Token", accessToken );
const requestOptions = {
method: "GET",
headers: myHeaders,
redirect: "follow"
};
try {
let resData = await fetch(`https://6edc19.myshopify.com/admin/api/2024-01/variants/${variantId}.json`, requestOptions);
let data = await resData.json();
console.log("data", data);
let inventryId = data.variant.inventory_item_id;
//for cost price
let responseData = await fetch(`https://6edc19.myshopify.com/admin/api/2024-01/inventory_items/${inventryId}.json`, requestOptions);
let costData = await responseData.json();
let costPrice = costData.inventory_item.cost;
console.log(">>>", costPrice);
return costPrice;
} catch (er){
console.log("err>>>>", er)
}
}
//end
//function for get cost price by backend
async function getCostPrice(variantId){
let accessToken = "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"
const myHeaders = new Headers();
myHeaders.append("X-Shopify-Access-Token", accessToken );
const requestOptions = {
method: "GET",
headers: myHeaders,
redirect: "follow"
};
try {
let resData = await fetch(`https://wholesale.apptiv.in/storeFront/getVariantCost?Shop=${Shopify.shop}&variantId=${variantId}`, requestOptions);
let costPrice = await resData.json();
return costPrice.data;
} catch (er){
console.log("err>>>>", er)
}
}
//end function
for (i = 0; i < itemTiers.tier_min.length; i++) {
var allVariantItemQty = 0;
var tempTierProductsobj = {};
var tierPrice = parseFloat(itemTiers.tier_values[i]);
var minTier = parseInt(itemTiers.tier_min[i]), maxTier = itemTiers.tier_max[i] != 'max' ? parseInt(itemTiers.tier_max[i]) : itemTiers.tier_max[i];
var updatedItemPrice = 0, updatedLinePrice = 0, condition1 = false, condition2 = false;
if (itemTiers.entity_type === 'products' || itemTiers.entity_type === 'collections') {
var tempItemArray = [];
if (itemTiers.entity_type === 'collections') {
var tempTierArray = jQuery.grep(globalFieldsCartPage_WD.cartTiersArray, function (n) { return (n.tiers != '[]' && n.tiers[0].entity_type == 'collections' && n.tiers[0].entity_id == itemTiers.entity_id); });
for (var m = 0; m < tempTierArray.length; m++) {
var temp = jQuery.grep(globalFieldsCartPage_WD.cartObj.items, function (n) { return (n.variant_id == tempTierArray[m].variant_id); });
if (temp.length != 0) {
tempItemArray.push(temp[0]);
}
}
}
else {
tempItemArray = jQuery.grep(globalFieldsCartPage_WD.cartObj.items, function (n) { return (n.product_id == item.product_id ); });
}
for (j = 0; j < tempItemArray.length; j++) { allVariantItemQty += tempItemArray[j].quantity; }
condition1 = allVariantItemQty >= minTier;
condition2 = maxTier == "max" || allVariantItemQty <= maxTier;
}
else {
condition1 = item.quantity >= minTier;
condition2 = maxTier == "max" || item.quantity <= maxTier;
}
if (condition1 && condition2) {
isNotInRange = false;
if (itemTiers.discount_type == 'percentage') {
var originalPriceCut = parseFloat(globalFields.ConvertToFixedDecimalNumber((parseFloat(tierPrice) / 100) * globalFields.ConvertToFixedDecimalNumber(item.original_price / 100)));
updatedItemPrice = globalFields.ConvertToFixedDecimalNumber(globalFields.ConvertToFixedDecimalNumber(item.original_price / 100) - originalPriceCut);
if(!isFound){
tempTierProductsobj['Discountvalue'] = tierPrice;
tempTierProductsobj['DiscountType'] = itemTiers.discount_type;
tempTierProductsobj['VarientID'] = item.variant_id;
tempTierProductsobj['titleDiscount'] ="Wholesale_Discount";
}
}
else if (itemTiers.discount_type == 'fixed') {
updatedItemPrice = globalFields.ConvertToFixedDecimalNumber(globalFields.ConvertToFixedDecimalNumber(item.original_price / 100) - parseFloat(tierPrice));
if(!isFound){
tempTierProductsobj['Discountvalue'] = tierPrice;
tempTierProductsobj['DiscountType'] = itemTiers.discount_type;
tempTierProductsobj['VarientID'] = item.variant_id;
tempTierProductsobj['titleDiscount'] ="Wholesale_Discount";
}
}
else if (itemTiers.discount_type == 'costMargin') {
// updatedItemPrice = globalFields.ConvertToFixedDecimalNumber(parseFloat(tierPrice));
costPrice = await getCostPrice(item.id);
costPrice = Number(costPrice);
if ( costPrice != 0 && costPrice != null ) {
let marginCalculation = costPrice * tierPrice;
marginCalculation = marginCalculation / 100;
marginCalculation = marginCalculation + Number(costPrice);
console.log(">>", marginCalculation)
updatedItemPrice = globalFields.ConvertToFixedDecimalNumber(parseFloat(marginCalculation));
}else{
isNotInRange = true;
//updatedItemPrice = globalFields.ConvertToFixedDecimalNumber(parseFloat(item.original_price/100));
}
}
else if (itemTiers.discount_type == 'fixed_price') {
if ( itemTiers.costMargin ){
let costPrice = await getCostPrice( item.id );
let marginCalculation = costPrice * tierPrice;
marginCalculation = marginCalculation / 100;
marginCalculation = marginCalculation + Number(costPrice);
updatedItemPrice = globalFields.ConvertToFixedDecimalNumber(parseFloat(marginCalculation));
// discountedPrice = marginCalculation.toFixed(2);
// tieredOff = globalFields.formatMoney(marginCalculation.toFixed(2), globalFields.amount);
}else{
updatedItemPrice = globalFields.ConvertToFixedDecimalNumber(parseFloat(tierPrice));
}
}
if (updatedItemPrice < 0) { updatedItemPrice = 0; }
updatedLinePrice = globalFields.ConvertToFixedDecimalNumber(updatedItemPrice * item.quantity);
updatedTotalPrice += globalFields.ConvertToFixedDecimalNumber(updatedLinePrice);
UpdateCartItem(item, updatedItemPrice, updatedLinePrice, isNotInRange, isUpdate, index);
if(!isFound){
TierProducts.push(tempTierProductsobj);
}
}
}
if (isNotInRange) {
UpdateCartItem(item, globalFields.ConvertToFixedDecimalNumber(item.original_price / 100), globalFields.ConvertToFixedDecimalNumber(item.original_line_price / 100), isNotInRange, isUpdate, index);
}
return [updatedTotalPrice, isNotInRange];
}
var DiscountCodeCookie = function (discount_code) {
jQuery.ajax({
type: "HEAD", url: "/discount/" + discount_code,
success: function (_result) { },
error: function (e) { console.log(e.statusText); }
})
}
var FetchCartTiers = function () {
jQuery.ajax({
async: false,
url: "/cart/?view=wd_cart_tiers",
success: function (result) {
globalFieldsCartPage_WD.cartTiersArray = JSON.parse(result);
TieredPricingCart(globalFieldsCartPage_WD.cartObj, true);
CheckoutClickCart(); CheckoutClickAjax();
},
error: function (e) { console.log(e.statusText); }
});
}
/*
var open = window.XMLHttpRequest.prototype.open, send = window.XMLHttpRequest.prototype.send, onReadyStateChange;
function openReplacement(method, url, async, user, password) { return open.apply(this, arguments); }
function sendReplacement(data) {
this.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
ProcessCartResponse(this._url, this.responseText);
}
};
return send.apply(this, arguments);
}
window.XMLHttpRequest.prototype.open = openReplacement; window.XMLHttpRequest.prototype.send = sendReplacement;
*/
jQuery(document).ajaxComplete(function (event, xhr, settings) {
ProcessCartResponse(settings.url, xhr.responseText);
});
var ProcessCartResponse = function (splittedUrl, responseText) {
if (splittedUrl != 'undefined' && splittedUrl != "" && splittedUrl != null) {
splittedUrl = splittedUrl.split("?");
if (splittedUrl[0] == "/cart.js" || splittedUrl[0] == "/cart/change.js") {
globalFieldsCartPage_WD.cartObj = JSON.parse(responseText);
setTimeout(function () {
FetchCartTiers();
}, 800);
}
}
}
try{
var nativeFetch = window.fetch;
window.fetch = function(...args) {
if(args[0].includes("/cart/change") || args[0].includes("/cart/add")){
setTimeout(function () {
fetch('/cart.js')
.then(r => r.json().then(data => ({status: r.status, body: data})))
.then(obj => ProcessCartResponse("/cart.js", JSON.stringify(obj.body)));
}, 500);
}
return nativeFetch.apply(window, args);
}
}
catch(e){}
async function handleDiscount() {
try {
const response = await fetch("/discount/CLEAR");
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const contentType = response.headers.get("Content-Type");
if (contentType && contentType.includes("application/json")) {
const data = await response.json();
console.log("Discount data:", data);
// Continue processing or updating the UI as needed
} else {
$(".ecom-cart__product-discounts").remove();
$(".discounts list-unstyled").remove();
// Handle non-JSON content, such as HTML or other types
// console.error("Unexpected content type:", contentType);
// Handle specific error scenarios or display a user-friendly message
}
} catch (error) {
// Handle errors
// console.error("Error fetching discount:", error.message);
// Handle specific error scenarios or display a user-friendly message
}
}
var perfEntries = performance.getEntriesByType("navigation");
if (perfEntries[0].type === "back_forward") {
location.reload();
}
var SetCookie = function (cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); var expires = "expires=" + d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; }
setTimeout(function () {
TieredPricingCart(globalFieldsCartPage_WD.cartObj, true); CheckoutClickCart(); CheckoutClickAjax();handleDiscount();
}, 1500);
}
var globalFieldsCartPage_WD = new WDDiscountApp.CartPage.Global(); var cartObject = new WDDiscountApp.CartPage.Show_CalculateTier();