-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFlowDataLayer.js
More file actions
345 lines (307 loc) · 11 KB
/
FlowDataLayer.js
File metadata and controls
345 lines (307 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
/* global ga, Flow, ShopifyAnalytics */
/* eslint-disable no-var, prefer-arrow-callback, prefer-template, object-shorthand */
(function flowDL() {
window.__bva__ = window.__bva__ || [];
// dependencies
// cookie handling
function setCookie(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=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
var NOT_SET = '(not set)';
function gaReady() {
return typeof ga !== 'undefined';
}
// Flow is ready of 'getExperience' function exists
function flowReady() {
return Flow && typeof Flow.getExperience === 'function';
}
// Wait until trekkie is loaded (lib will transition from an empty array to an object).
function shopifyAnalyticsReady() {
return ShopifyAnalytics && typeof ShopifyAnalytics.lib === 'object';
}
function isReady() {
return gaReady() && flowReady() && shopifyAnalyticsReady();
}
/**
* Exponential backoff. Keep trying but delay a little longer each attempt.
*/
function backoff(test, callback, delay) {
function getNewDelay() {
if (!delay) {
return 1;
}
return (delay >= Number.MAX_VALUE) ? delay : delay * 2;
}
if (test()) {
callback();
} else {
setTimeout(function () {
backoff(test, callback, getNewDelay());
}, Math.log(getNewDelay()) * 100);
}
}
function getItemFromCart(id, cart) {
var len = cart.items.length;
var item;
var i = 0;
for (i = 0; i < len; i += 1) {
if (id.toString() === cart.items[i].variant_id.toString()) {
item = cart.items[i];
}
}
return item;
}
function getOrderPricing(order) {
var pricing = {};
var prices = order.prices;
var pricesLength = order.prices.length;
var i;
for (i = 0; i < pricesLength; i += 1) {
pricing[prices[i].key] = prices[i].base.amount;
}
return pricing;
}
function flowDynamicCart(){
Flow.cart.getCart({
success: function (status, data) {
// reset dataLayer products
dataLayer.push({'products':''});
// clear any existing shopify cart items to prevent generic DL cart from being fired
if(getCookie('clearCart') === "undefined"){
document.cookie = "cart=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
setCookie('clearCart','1',1);
}
var getdata = data;
var item = getdata.items;
var eventData = [];
for (var i = item.length - 1; i >= 0; i--) {
eventData.push({
'variant' : item[i].variant_id,
'id' : item[i].product_id,
'quantity' : item[i].quantity,
'price' : item[i].local.price.base.amount,
'name' : item[i].title,
'sku' : item[i].sku
});
}
// push to dataLayer
dataLayer.push(eventData,{
'pageType' : 'Cart',
'event' : 'Cart'
});
if(__bva__.debug){
console.log("Cart"+" :"+JSON.stringify(eventData, null, " "));
}
}
});
}
function setupAddToCart() {
Flow.on('cart.addItem', function (data) {
// clear any existing shopify cart items to prevent generic DL cart from being fired
if(getCookie('clearCart') === "undefined"){
document.cookie = "cart=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
setCookie('clearCart','1',1);
}
dataLayer.push({'products':''});
var item = getItemFromCart(data.id, data.cart);
var eventData = {
'products': [{
'variant' : item.variant_id,
'id' : item.product_id,
'quantity' : data.quantity,
'price' : item.local.price.base.amount,
'name' : item.title,
'sku' : item.sku,
}],
};
// push to dataLayer
dataLayer.push(eventData,{
'pageType' : 'Add to Cart',
'event' : 'Add to Cart'
});
if(__bva__.debug){
console.log("Add to Cart"+" :"+JSON.stringify(eventData, null, " "));
}
});
}
function setupViewCart() {
// cart pageview
Flow.on('pageview.cart', function (data) {
// reset dataLayer products
dataLayer.push({'products':''});
// clear any existing shopify cart items to prevent generic DL cart from being fired
if(getCookie('clearCart') === "undefined"){
document.cookie = "cart=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
setCookie('clearCart','1',1);
}
var getdata = data;
var item = getdata.cart.items;
var eventData = [];
for (var i = item.length - 1; i >= 0; i--) {
eventData.push({
'variant' : item[i].variant_id,
'id' : item[i].product_id,
'quantity' : item[i].quantity,
'price' : item[i].local.price.base.amount,
'name' : item[i].title,
'sku' : item[i].sku
});
}
// push to dataLayer
dataLayer.push({'products': eventData },{
'pageType' : 'Cart',
'event' : 'Cart'
});
if(__bva__.debug){
console.log("Cart"+" :"+JSON.stringify(eventData, null, " "));
}
});
// using global shopify elements to detect dynamic cart data
// see more information here https://github.com/TechnicalWebAnalytics/dataLayer-shopify
flowViewcartfire = 0;
$(document).on('click', __bva__.viewCart, function (event) {
if(flowViewcartfire !== 1){
flowViewcartfire = 1;
if (__bva__.dynamicCart) {
flowCartCheck = setInterval(function () {
if ($(__bva__.cartVisableSelector).length > 0) {
clearInterval(flowCartCheck);
flowDynamicCart();
}
}, 500);
}
}
});
}
function getFlowTransactionData(order){
data = order;
getorder = data.order;
// data = order.order;
var orderPricing = getOrderPricing(getorder);
flow_items = [];
for (var i = getorder.lines.length - 1; i >= 0; i--) {
var prods = getorder.lines[i].shopify;
var description = prods.product_description.replace(/\<(meta charset\=\"utf\-8\"|span|\/span)\>/g,"");
flow_items.push({
'id' : prods.product_id,
'sku' : prods.sku,
'variantId' : prods.variant_id,
'name' : prods.title,
'price' : getorder.lines[i].price.base.amount,
'quantity' : prods.quantity,
'productType' : prods.product_type,
'description' : description,
'productURL' : prods.url,
'imageURL' : prods.image
});
}
flow_transaction = {
'transactionNumber' : getorder.number,
'transactionId' : getorder.id,
'transactionAffiliation' : window.flowSettings.flow.organization,
'transactionTotal' : getorder.total.base.amount,
'transactionTax' : orderPricing.tax || 0,
'transactionShipping' : getOrderPricing.shipping || 0,
'transactionSubtotal' : getorder.total.base.amount - ( orderPricing.tax || 0 + getOrderPricing.shipping || 0 ),
// 'promoCode' : '',
// 'discount' : '',
'products' : flow_items
}
return flow_transaction;
}
function setupCheckoutStep1() {
Flow.set('on', 'pageview.checkout_step_1', function (data) {
dataLayer.push(getFlowTransactionData(data),{
'event' :'Customer Information',
'pageType' :'Customer Information'});
dataLayer.push({'event': 'DataLayer Loaded'});
if(__bva__.debug){
console.log("Customer Information - Transaction Data"+" :"+JSON.stringify(getFlowTransactionData(data), null
, " "));
}
});
}
function setupCheckoutStep2() {
Flow.set('on', 'pageview.checkout_step_2', function (data) {
dataLayer.push(getFlowTransactionData(data),{
'event' :'Shipping Information',
'pageType' :'Shipping Information'});
dataLayer.push({'event': 'DataLayer Loaded'});
if(__bva__.debug){
console.log("Shipping - Transaction Data"+" :"+JSON.stringify(getFlowTransactionData(data), null, " "));
}
});
}
function setupCheckoutStep3() {
Flow.set('on', 'pageview.checkout_step_3', function (data) {
dataLayer.push(getFlowTransactionData(data),{
'event' :'Add Payment Info',
'pageType' :'Add Payment Info'});
dataLayer.push({'event': 'DataLayer Loaded'});
if(__bva__.debug){
console.log("Payment - Transaction Data"+" :"+JSON.stringify(getFlowTransactionData(data), null, " "));
}
});
}
function setupCheckoutThankYou() {
Flow.set('on', 'pageview.checkout_thank_you', function (data) {
getorder = data.order;
dataLayer.push({
'billingInfo': {
'fullName' : getorder.destination.contact.name.first+" "+getorder.destination.contact.name.last,
'firstName' : getorder.destination.contact.name.first,
'lastName' : getorder.destination.contact.name.last,
'address1' : getorder.destination.streets[0],
'address2' : getorder.destination.streets[1],
'street' : getorder.destination.streets[0],
'city' : getorder.destination.city,
'province' : getorder.destination.province,
'zip' : getorder.destination.postal,
'country' : getorder.destination.country,
'phone' : getorder.destination.contact.phone,
},
'checkoutEmail': getorder.destination.contact.email,
});
dataLayer.push(getFlowTransactionData(data),{
'pageType' :'Transaction',
'event' :'Transaction'
});
dataLayer.push({'event': 'DataLayer Loaded'});
if(__bva__.debug){
console.log("Transaction Data"+" :"+JSON.stringify(getFlowTransactionData(data), null, " "));
}
});
}
function setup() {
console.log('[flow_dl] Setup!');
setupAddToCart();
setupViewCart();
setupCheckoutStep1();
setupCheckoutStep2();
setupCheckoutStep3();
setupCheckoutThankYou();
}
function init() {
// Wait for GA, Shopify and Flow to be ready.
backoff(isReady, setup);
}
init();
}());