Shoora
10/3/2018 - 5:00 AM

ecommerce js

ecommerce js

//@gtag
//https://developers.google.com/analytics/devguides/collection/gtagjs/enhanced-ecommerce?hl=ru
//https://developers.google.com/analytics/devguides/collection/gtagjs/events#send-events

var gasiteName = 'site';

function qs(key) {
    key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
    var match = location.search.match(new RegExp("[?&]"+key+"=([^&]+)(&|$)"));
    return match && decodeURIComponent(match[1].replace(/\+/g, " "));
}



BX.ready(function () {

console.log('x.ga.ecommerce.js ready');





if($('#bx-soa-order-form').length>0)
{
	console.log('x.ga.ecommerce.js Found order form');

	$('#bx-soa-orderSave .btn').click(function(){


		var orderTotal = parseFloat(BX.Sale.OrderAjaxComponent.result.TOTAL.ORDER_PRICE);

		console.log('orderTotal', orderTotal);

		var items = BX.Sale.OrderAjaxComponent.result.GRID.ROWS;
		var orderItems = [];

		$.each(items, function(index, item) {

			var props = $.map(item.data.PROPS, function(p) { return p["VALUE"]; });

			var data = {
				'id': item.data.PRODUCT_ID,
				'name': (item.data.NAME + " "+ props.join(", ")).trim(),
				'price': parseFloat(item.data.PRICE),
				'quantity': parseInt(item.data.QUANTITY)
			};
			// no data for: sku,category

			console.log('order.item.' + index, data);
			orderItems.push(data);
		});

		sessionStorage.setItem('order', JSON.stringify({
			total: orderTotal, 
			items: orderItems
		}));

		console.log('storedOrderJSON', sessionStorage.getItem('order'));

	});

};



if(window.location.pathname == '/personal/cart/'){
	window.onload = function() {
		console.log('cart_open');
		yaCounter47617351.reachGoal('cart_open');
	};
}


if(window.location.pathname == '/personal/order/make/' && qs('ORDER_ID') != null)
{

	var order_id = qs('ORDER_ID');

    var clientOrder = JSON.parse(sessionStorage.getItem('order'));

	console.log('store.order.created', 'order' + order_id, clientOrder);

	gtag('event', 'purchase', {
		'transaction_id': order_id,
		'affiliation': gasiteName,
		'value': clientOrder.total,
		'shipping': 0, // no data
		'tax': 0, // no data,
		'items': clientOrder.items
	});
}



/*

$('.prod_buttons .button.buy, .list_product_row .button_buy, #quick_order').click(function() {

	if($(this).parents('.right_desk_product').length > 0){
		var button = $(this),
			form = button.parents('form'),
			page = 'internal_page',
			productId = parseInt(form.find('#product_id').val()),
			productPrice = parseFloat(form.find('.prod_price > span').text().replace(/[^0-9]/g,'')),
			quantity = parseInt(form.find('#quantity').val());
	}else{
		var button = $(this),
			block_product = button.parents('.block_product'),
			form = block_product.find('form'),
			page = 'Category',
			productId = parseInt(form.find('#product_id').val()),
			productPrice = parseFloat(block_product.find('.jshop_price > span').text().replace(/[^0-9]/g,'')),
			quantity = 1;
	}

    if (productId && productPrice) {

		if(quantity>1){
			productPrice = productPrice * quantity;
		}


		if(button.attr('id') == 'quick_order'){
			console.log('fastorder', quantity, productPrice, page, productId);
			ga('send', 'event', 'FastOrder', productPrice, page, productId);
			yaCounter45334986.reachGoal('fastorder', { order_price: productPrice, currency: "RUB", product_id: productId });
		}else{
			console.log('addtocart', quantity, productPrice, page, productId);
			ga('send', 'event', 'AddCart', productPrice, page, productId);
			yaCounter45334986.reachGoal('addtocart', { order_price: productPrice, currency: "RUB", product_id: productId });
		}

    }

});
*/



/*
$('#quick_order').click(function(){
	yaCounter45334986.reachGoal('fastorder', { order_price: productPrice, currency: "RUB", product_id: productId });
});

$('.cat-item-buy[onclick*=addToCart], .l-add-cart[onclick*=addToCart]').click(function() {
    var button = $(this),
        action = button.attr('onclick'),
        page = button.hasClass('cat-item-buy') ? 'Category' : 'internal_page',
        productId = parseInt(action.split('addToCart(')[1]),
        productPrice = parseFloat(
            button.hasClass('cat-item-buy') ? button.parent().find('.cat-price-price.onstock').text() : button.parent().find('.product-price[itemprop=price]').attr('content')
        );
    if (productId && productPrice) {
        ga('send', 'event', 'AddCart', productPrice.toString(), page, productId);
    }
    console.log('gaAddToCart', page, productId, productPrice);
});
function getProductIdFromPage() {
    var btn = $('.product-aside').find('.l-add-cart[onclick*=addToCart]');
    return btn.length ? parseInt(btn.attr('onclick').split('addToCart(')[1]) : 0;
}
*/


/*
$(document).on('click', '#submitForm_7', function(){
    ga('send', 'event', 'oneclick', 'Отправить');
	console.log('oneclick');
});
$(document).on('click', '#submitForm_8', function() {
    ga('send', 'event', 'callback', 'Отправить');
	console.log('callback');
});*/

});
var gasiteName = 'sitename';

function qs(key) {
    key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
    var match = location.search.match(new RegExp("[?&]"+key+"=([^&]+)(&|$)"));
    return match && decodeURIComponent(match[1].replace(/\+/g, " "));
}



BX.ready(function () {

console.log('x.ga.ecommerce.js ready');





if($('#bx-soa-order-form').length>0)
{
	console.log('x.ga.ecommerce.js Found order form');

	$('#bx-soa-orderSave .btn').click(function(){


		var orderTotal = parseFloat(BX.Sale.OrderAjaxComponent.result.TOTAL.ORDER_PRICE);

		console.log('orderTotal', orderTotal);

		var items = BX.Sale.OrderAjaxComponent.result.GRID.ROWS;
		var orderItems = [];

		$.each(items, function(index, item) {

			var props = $.map(item.data.PROPS, function(p) { return p["VALUE"]; });

			var data = {
				'sku': item.data.PRODUCT_ID,
				'name': (item.data.NAME + " "+ props.join(", ")).trim(),
				'price': parseFloat(item.data.PRICE),
				'quantity': parseInt(item.data.QUANTITY)
			};
			// no data for: sku,category

			console.log('order.item.' + index, data);
			orderItems.push(data);
		});

		sessionStorage.setItem('order', JSON.stringify({
			total: orderTotal, 
			items: orderItems
		}));

		console.log('storedOrderJSON', sessionStorage.getItem('order'));

	});

};



if(window.location.pathname == '/personal/cart/'){
	window.onload = function() {
		console.log('cart_open');
		yaCounter45334986.reachGoal('cart_open');
	};
}


if(window.location.pathname == '/personal/order/make/' && qs('ORDER_ID') != null)
{

	var order_id = qs('ORDER_ID');

    var clientOrder = JSON.parse(sessionStorage.getItem('order'));

	console.log('store.order.created', 'order' + order_id, clientOrder);


	ga('require', 'ecommerce');

	var orderData = {
		'id': order_id,
		'affiliation': gasiteName,
		'revenue': clientOrder.total,
		'shipping': '', // no data
		'tax': '' // no data
	};

	console.log('order.data', orderData);

	ga('ecommerce:addTransaction', orderData);

	clientOrder.items.forEach(function(item, index){
		item.id = order_id;
		console.log('ga add item', item);
		ga('ecommerce:addItem', item);
	});

	ga('ecommerce:send');

}





$('.prod_buttons .button.buy, .list_product_row .button_buy, #quick_order').click(function() {

	if($(this).parents('.right_desk_product').length > 0){
		var button = $(this),
			form = button.parents('form'),
			page = 'internal_page',
			productId = parseInt(form.find('#product_id').val()),
			productPrice = parseFloat(form.find('.prod_price > span').text().replace(/[^0-9]/g,'')),
			quantity = parseInt(form.find('#quantity').val());
	}else{
		var button = $(this),
			block_product = button.parents('.block_product'),
			form = block_product.find('form'),
			page = 'Category',
			productId = parseInt(form.find('#product_id').val()),
			productPrice = parseFloat(block_product.find('.jshop_price > span').text().replace(/[^0-9]/g,'')),
			quantity = 1;
	}

    if (productId && productPrice) {

		if(quantity>1){
			productPrice = productPrice * quantity;
		}


		if(button.attr('id') == 'quick_order'){
			console.log('fastorder', quantity, productPrice, page, productId);
			ga('send', 'event', 'FastOrder', productPrice, page, productId);
			yaCounter45334986.reachGoal('fastorder', { order_price: productPrice, currency: "RUB", product_id: productId });
		}else{
			console.log('addtocart', quantity, productPrice, page, productId);
			ga('send', 'event', 'AddCart', productPrice, page, productId);
			yaCounter45334986.reachGoal('addtocart', { order_price: productPrice, currency: "RUB", product_id: productId });
		}

    }

});

/*
$('#quick_order').click(function(){
	yaCounter45334986.reachGoal('fastorder', { order_price: productPrice, currency: "RUB", product_id: productId });
});

$('.cat-item-buy[onclick*=addToCart], .l-add-cart[onclick*=addToCart]').click(function() {
    var button = $(this),
        action = button.attr('onclick'),
        page = button.hasClass('cat-item-buy') ? 'Category' : 'internal_page',
        productId = parseInt(action.split('addToCart(')[1]),
        productPrice = parseFloat(
            button.hasClass('cat-item-buy') ? button.parent().find('.cat-price-price.onstock').text() : button.parent().find('.product-price[itemprop=price]').attr('content')
        );
    if (productId && productPrice) {
        ga('send', 'event', 'AddCart', productPrice.toString(), page, productId);
    }
    console.log('gaAddToCart', page, productId, productPrice);
});
function getProductIdFromPage() {
    var btn = $('.product-aside').find('.l-add-cart[onclick*=addToCart]');
    return btn.length ? parseInt(btn.attr('onclick').split('addToCart(')[1]) : 0;
}
*/

$(document).on('click', '#submitForm_7', function(){
    ga('send', 'event', 'oneclick', 'Отправить');
	console.log('oneclick');
});
$(document).on('click', '#submitForm_8', function() {
    ga('send', 'event', 'callback', 'Отправить');
	console.log('callback');
});

});
var gasiteName = 'yoursite';

function qs(key) {
    key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
    var match = location.search.match(new RegExp("[?&]"+key+"=([^&]+)(&|$)"));
    return match && decodeURIComponent(match[1].replace(/\+/g, " "));
}



BX.ready(function () {

console.log('x.ga.ecommerce.js ready');



if($('#bx-soa-order-form').length>0)
{

	$('#bx-soa-orderSave a').click(function(){


		var orderTotalPriceEl = $('.bx-soa-cart-total-line.bx-soa-cart-total-line-total .bx-soa-cart-d'),
			orderItemEl = $('#bxr-basket-body .basket-body-table tr:gt(0)'),
			orderTotal = parseFloat(orderTotalPriceEl.text());


		console.log('orderTotal', orderTotal);

		var itemsIDs = JSON.parse($('#bxr-basket-data').text()).ITEMS;
		var orderItems = [];


		orderItemEl.each(function(index) {
			var item = $(this),
				titleEl = item.find('.basket-name a'),
				priceEl = item.find('.basket-price'),
				qtyEl   = item.find('input[name=quantity]');

			var data = {
				'sku': parseInt(itemsIDs[index]),
				'name': titleEl.text().trim(),
				'price': parseFloat(priceEl.text()),
				'quantity': parseInt(qtyEl.val())
			};
			// no data for: sku,category

			console.log('order.item.' + item.index(), data);
			orderItems.push(data);
		});

		sessionStorage.setItem('order', JSON.stringify({
			total: orderTotal, 
			items: orderItems
		}));

		console.log('storedOrderJSON', sessionStorage.getItem('order'));

	});

};


if(window.location.pathname == '/personal/order/make/')
{

	var order_id = qs('ORDER_ID'), clientOrder = JSON.parse(sessionStorage.getItem('order'));

	console.log('store.order.created', 'order' + order_id, clientOrder);


	ga('require', 'ecommerce');

	var orderData = {
		'id': order_id,
		'affiliation': gasiteName,
		'revenue': clientOrder.total,
		'shipping': '', // no data
		'tax': '' // no data
	};

	console.log('order.data', orderData);

	ga('ecommerce:addTransaction', orderData);

	clientOrder.items.forEach(function(item, index){
		item.id = order_id;
		console.log('ga add item', item);
		ga('ecommerce:addItem', item);
	});

	ga('ecommerce:send');

}



/*
$('.cat-item-buy[onclick*=addToCart], .l-add-cart[onclick*=addToCart]').click(function() {
    var button = $(this),
        action = button.attr('onclick'),
        page = button.hasClass('cat-item-buy') ? 'Category' : 'internal_page',
        productId = parseInt(action.split('addToCart(')[1]),
        productPrice = parseFloat(
            button.hasClass('cat-item-buy') ? button.parent().find('.cat-price-price.onstock').text() : button.parent().find('.product-price[itemprop=price]').attr('content')
        );

    if (productId && productPrice) {
        ga('send', 'event', 'AddCart', productPrice.toString(), page, productId);
    }

    console.log('gaAddToCart', page, productId, productPrice);
});



function getProductIdFromPage() {
    var btn = $('.product-aside').find('.l-add-cart[onclick*=addToCart]');
    return btn.length ? parseInt(btn.attr('onclick').split('addToCart(')[1]) : 0;
}
*/

$(document).on('click', '#submitForm_7', function(){
    ga('send', 'event', 'oneclick', 'Отправить');
	console.log('oneclick');
});
$(document).on('click', '#submitForm_8', function() {
    ga('send', 'event', 'callback', 'Отправить');
	console.log('callback');
});

});
var gasiteName = 'yoursite';

$(document).on('store.order.created', function(event, data) {
    if (typeof data.resp['order_id'] == 'undefined') {
        console.log('store.order.created', 'not found order_id');
        return;
    }

    var order_id = data.resp['order_id'];
    console.log('store.order.created', 'order_id = ' + order_id);

    var orderTotalPriceEl = data.cartcontent.find('.tab-row-total .product-price-total'),
        orderItemEl = data.cartcontent.find('.tab-row-item');


    ga('require', 'ecommerce');

    var orderData = {
        'id': order_id,
        'affiliation': gasiteName,
        'revenue': parseFloat(orderTotalPriceEl.text()),
        'shipping': '', // no data
        'tax': '' // no data
    };

    console.log('order.data', orderData);
    ga('ecommerce:addTransaction', orderData);

    orderItemEl.each(function() {
        var item = $(this),
            titleEl = item.find('.cart-title a:eq(0)'),
            priceEl = item.find('.cart-price'),
            qtyEl = item.find('.cart-sel input');

        var data = {
            'id': order_id,
            'sku': parseInt(qtyEl.attr('data-id')),
            'name': titleEl.text().trim(),
            'price': parseFloat(priceEl.attr('data-price')),
            'quantity': parseInt(qtyEl.val())
        };
        // no data for: sku,category

        console.log('order.item.' + item.index(), data);
        ga('ecommerce:addItem', data);
    });

    ga('ecommerce:send', {
        'hitCallback': data.callback()
    });

});


$('.cat-item-buy[onclick*=addToCart], .l-add-cart[onclick*=addToCart]').click(function() {
    var button = $(this),
        action = button.attr('onclick'),
        page = button.hasClass('cat-item-buy') ? 'Category' : 'internal_page',
        productId = parseInt(action.split('addToCart(')[1]),
        productPrice = parseFloat(
            button.hasClass('cat-item-buy') ? button.parent().find('.cat-price-price.onstock').text() : button.parent().find('.product-price[itemprop=price]').attr('content')
        );

    if (productId && productPrice) {
        ga('send', 'event', 'AddCart', productPrice.toString(), page, productId);
    }

    console.log('gaAddToCart', page, productId, productPrice);
});


$('.quick-buy-button').click(function() {
    ga('send', 'event', 'AddCart', 'OneClick', 'internal_page', getProductIdFromPage());
});

$('.buyInCredit').click(function() {
    ga('send', 'event', 'AddCart', 'Installment_Pay', 'internal_page', getProductIdFromPage());
});

$('.l-add-cart.china-stock').click(function() {
    ga('send', 'event', 'AddCart', 'CH_Price', 'internal_page', getProductIdFromPage());
});



function getProductIdFromPage() {
    var btn = $('.product-aside').find('.l-add-cart[onclick*=addToCart]');
    return btn.length ? parseInt(btn.attr('onclick').split('addToCart(')[1]) : 0;
}