Advertisement
Dzhubal

Untitled

Oct 21st, 2019
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function cqGetDate() {
  2.     var today = new Date(),
  3.         isoDate = today.toISOString();
  4.     return isoDate.split('.')[0];
  5. };
  6.  
  7. function cqGetTimelapse() {
  8.     var seconds = Math.floor((Date.now()-parseInt(localStorage['orderStartedTime']))/1000),
  9.         timeLapse = new Date(null);
  10.     timeLapse.setSeconds(seconds);
  11.     var lapseResult = timeLapse.toISOString().substr(11, 8);
  12.     return lapseResult;
  13. };
  14.  
  15. function getClosest(el, s) {
  16.     var r = undefined;
  17.     while (el) {
  18.         if (el.matches(s)) {
  19.             r = el;
  20.             break;
  21.         } else if (el.tagName.toLowerCase()=='body') {
  22.             break;
  23.         };
  24.         el = el.parentElement;
  25.     };
  26.     return r;
  27. };
  28.  
  29. var isProdPage = document.querySelectorAll('.ty-product-block.ty-product-detail').length>0;
  30. if (isProdPage) {
  31.     var name, img, amount, url = location.href;
  32.     var checkProps = setInterval(function() {
  33.         if ((document.querySelectorAll('.ty-product-block-title bdi').length>0)&&
  34.             (document.querySelectorAll('.ty-product-block .ty-price bdi .ty-price-num:nth-of-type(1)').length>0)&&
  35.             (document.querySelectorAll('.ty-product-block img.ty-pict').length>0)) {
  36.             clearInterval(checkProps);
  37.             name = document.querySelector('.ty-product-block-title bdi').textContent.trim();
  38.             img = document.querySelector('.ty-product-block img.ty-pict').getAttribute('src');
  39.             amount = parseInt(document.querySelector('.ty-product-block .ty-price bdi .ty-price-num:nth-of-type(1)').textContent.split(',')[0].split('.')[0].replace(/\D/g, ''));
  40.             carrotquest.track('$product_viewed', {
  41.                 '$name': name,
  42.                 '$img': img,
  43.                 '$amount': amount,
  44.                 '$url': url
  45.             });
  46.             carrotquest.identify([{op: 'union', key: '$viewed_products', value: name}]);
  47.         };
  48.     }, 500);
  49.     document.addEventListener('click', function(e) {
  50.         if (e.target.matches('.ty-product-block button[type="submit"]')) {
  51.             amount = parseInt(document.querySelector('.ty-product-block .ty-price bdi .ty-price-num:nth-of-type(1)').textContent.split(',')[0].split('.')[0].replace(/\D/g, ''));
  52.             var qty = parseInt(document.querySelector('.ty-product-block .ty-value-changer__input.cm-amount, .ty-product-block .ty-qty select[name*="[amount]"]').value),
  53.                 ttl = amount * qty,
  54.                 opt = document.querySelectorAll('.ty-product-options__box input:checked').length!=0?
  55.                         document.querySelector('.ty-product-options__box input:checked').parentElement.textContent.trim():' ';
  56.             carrotquest.track('$cart_added', {
  57.                 '$name': name,
  58.                 '$img': img,
  59.                 '$amount': amount,
  60.                 '$url': url,
  61.                 'Вариация': opt
  62.             });
  63.             carrotquest.identify([
  64.                 {op: 'union', key: '$cart_items', value: name},
  65.                 {op: 'add', key: '$cart_amount', value: ttl}
  66.             ]);
  67.         };
  68.     });
  69. } else if (document.querySelectorAll('.ty-breadcrumbs').length>0 && document.querySelectorAll('.ty-product-list').length!=0) {
  70.     var crumbs = Array.from(document.querySelectorAll('.ty-breadcrumbs__a, .ty-breadcrumbs__current bdi')).map(function(el) {
  71.         return el.textContent.trim()
  72.     });
  73.     switch (crumbs.length) {
  74.         case 4:
  75.             carrotquest.track('Посмотрел подкатегорию', {
  76.                 'Название подкатегории': crumbs[3]
  77.             });
  78.             carrotquest.identify([
  79.                 {op: 'union', key: 'Просмотренные подкатегории', value: crumbs[3]},
  80.                 {op: 'union', key: 'Просмотренные категории', value: crumbs[2]},
  81.                 {op: 'union', key: 'Просмотренные разделы', value: crumbs[1]}
  82.             ]);
  83.             break;
  84.         case 3:
  85.             carrotquest.track('Посмотрел категорию', {
  86.                 'Название категории': crumbs[2]
  87.             });
  88.             carrotquest.identify([
  89.                 {op: 'union', key: 'Просмотренные категории', value: crumbs[2]},
  90.                 {op: 'union', key: 'Просмотренные разделы', value: crumbs[1]}
  91.             ]);
  92.             break;
  93.         case 2:
  94.             carrotquest.track('Посмотрел раздел', {
  95.                 'Название раздела': crumbs[1]
  96.             });
  97.             carrotquest.identify([{op: 'union', key: 'Просмотренные разделы', value: crumbs[1]}]);
  98.             break;
  99.         default: break;
  100.     };
  101.     document.addEventListener('click', function(e) {
  102.         if (e.target.matches('.ty-product-list form[name*="product_form_"] button.ty-btn__add-to-cart')) {
  103.             var item = getClosest(e.target, 'form[name*="product_form_"]'),
  104.                 name = item.querySelector('.product-title').textContent.trim(),
  105.                 url = item.querySelector('.product-title').getAttribute('href'),
  106.                 img = item.querySelector('img.ty-pict').getAttribute('src'),
  107.                 price = parseInt(item.querySelector('bdi > .ty-price-num').textContent.split('.')[0].replace(/\D/g, '')),
  108.                 qty = parseInt(item.querySelector('.ty-qty [name*="[amount]"]').value),
  109.                 ttl = price * qty;
  110.             carrotquest.track('$cart_added', {
  111.                 '$name': name,
  112.                 '$img': img,
  113.                 '$amount': price,
  114.                 '$url': url,
  115.                 'Вариация': ' '
  116.             });
  117.             carrotquest.identify([
  118.                 {op: 'union', key: '$cart_items', value: name},
  119.                 {op: 'add', key: '$cart_amount', value: ttl}
  120.             ]);
  121.         };
  122.     });
  123. };
  124.  
  125. document.addEventListener('click', function(e) {
  126.     if (e.target.matches('button[name="dispatch[auth.login]"]')) {
  127.         carrotquest.track('Клик "Войти"');
  128.     } else if (e.target.matches('form[name="coupon_code_form"] button[type="submit"]')) {
  129.         var promo = getClosest(e.target, 'form').querySelector('input#coupon_field').value;
  130.         carrotquest.track('Ввел промокод', {
  131.             'Промокод': promo
  132.         });
  133.     };;
  134. });
  135.  
  136. if (location.pathname=='/cart/') {
  137.     function get_items() {
  138.         var items = document.querySelectorAll('.ty-cart-content__product-elem a.ty-cart-content__product-title').length,
  139.             cartAmount = items==0?0:parseInt(document.querySelector('#sec_cart_total').textContent.split('.')[0].replace(/\D/g, ''));
  140.         carrotquest.identify([
  141.             {
  142.                 op: items == 0 ? 'delete' : 'update_or_create',
  143.                 key: '$cart_items',
  144.                 value: items == 0 ? 0 : Array.from(document.querySelectorAll('.ty-cart-content__product-elem a.ty-cart-content__product-title')).map(function(elem) {
  145.                     return elem.textContent.trim();
  146.                 })
  147.             },
  148.             { op: items == 0 ? 'delete' : 'update_or_create', key: '$cart_amount', value: cartAmount }
  149.         ])
  150.         localStorage['lastAmount'] = cartAmount;
  151.     };
  152.     setTimeout(get_items, 1000);
  153.     carrotquest.track('$cart_viewed');
  154.     document.addEventListener('click', function(e) {
  155.         if (e.target.matches('a.ty-cart-content__product-delete, a.ty-cart-content__product-delete *')) {
  156.             carrotquest.track('Удалил товар из корзины', {
  157.                 '$name': getClosest(e.target, '.ty-cart-content__product-elem').querySelector('a.ty-cart-content__product-title').textContent.trim()
  158.             });
  159.             setTimeout(get_items, 1000);
  160.         } else if (e.target.matches('a[href="https://surmarket.ru/checkout/"]')) {
  161.             localStorage['lastAmount'] = parseInt(document.querySelector('#sec_cart_total').textContent.split('.')[0].replace(/\D/g, ''));
  162.         };
  163.     });
  164. };
  165.  
  166. if (location.pathname=='/checkout/') {
  167.     carrotquest.track('$order_started');
  168.     localStorage['orderStarted'] = true;
  169.     localStorage['orderStartedTime'] = Date.now();
  170.     setTimeout(function() {
  171.         localStorage['lastAmount'] = document.querySelector('.ty-checkout-summary__item[data-ct-checkout-summary="items"]>span>bdi>span').textContent.split('.')[0].replace(/\D/g, '');
  172.         carrotquest.identify([{op: 'update_or_create', key: '$cart_amount', value: localStorage['lastAmount']}]);
  173.     }, 2000);
  174.     document.addEventListener('mousedown', function(e) {
  175.         if (e.target.matches('a.ty-order-products__item-delete, a.ty-order-products__item-delete *')) {
  176.             var dName = getClosest(e.target, '.ty-order-products__item').querySelector('bdi').textContent.trim();
  177.             carrotquest.track('Удалил товар из корзины', {
  178.                 '$name': dName
  179.             });
  180.             carrotquest.identify([{op: 'exclude', key: '$cart_items', value: dName}]);
  181.         } else if (e.target.matches('button#litecheckout_place_order, button#litecheckout_place_order *')) {
  182.             var name = document.querySelector('input#litecheckout_fullname').value,
  183.                 phone = document.querySelector('input#litecheckout_phone').value,
  184.                 email = document.querySelector('input#litecheckout_email').value;
  185.             if (name!='') {
  186.                 carrotquest.identify([{op: 'update_or_create', key: '$name', value: name}]);
  187.             };
  188.             if (phone!='') {
  189.                 carrotquest.identify([{op: 'update_or_create', key: '$phone', value: phone}]);
  190.             };
  191.             if (email!='') {
  192.                 carrotquest.identify([{op: 'update_or_create', key: '$email', value: email}]);
  193.             };
  194.         };
  195.     });
  196. };
  197.  
  198. if (location.search.indexOf('?dispatch=checkout.complete&order_id=')>-1 && localStorage['orderStarted']=='true') {
  199.     var orderId = location.search.replace(/\D/g, '');
  200.     carrotquest.track('$order_completed', {
  201.         '$order_amount': localStorage['lastAmount'],
  202.         '$order_id_human': orderId
  203.     });
  204.     carrotquest.identify([
  205.         { op: "delete", key: "$cart_items", value: 0 },
  206.         { op: "delete", key: "$viewed_products", value: 0 },
  207.         { op: "delete", key: "$cart_amount", value: 0 },
  208.         { op: "add", key: "$revenue", value: parseInt(localStorage['lastAmount']) },
  209.         { op: "add", key: "$orders_count", value: 1 },
  210.         { op: "update_or_create", key: "$last_payment", value: localStorage['lastAmount'] },
  211.         { op: "update_or_create", key: "Номер последнего заказа", value: orderId },
  212.         { op: "update_or_create", key: "Дата последнего заказа", value: cqGetDate() },
  213.         { op: 'update_or_create', key: 'Продолжительность оформления заказа', value: cqGetTimelapse() }
  214.     ]);
  215.     localStorage['orderStarted'] = false;
  216.     localStorage.removeItem('lastAmount');
  217.     localStorage.removeItem('orderStartedTime');
  218. };
  219.  
  220. switch (location.pathname) {
  221.     case '/profiles-add/':
  222.         carrotquest.track('Переход "Регистрация"');
  223.         break;
  224.     case '/profiles-update/':
  225.         carrotquest.track('Переход "Учетная запись"');
  226.         break;
  227.     case '/orders/':
  228.         carrotquest.track('Переход "Мои заказы"');
  229.         break;
  230.     case '/reward-points/':
  231.         carrotquest.track('Переход "Мои бонусные баллы"');
  232.         break;
  233.     case '/wishlist/':
  234.         carrotquest.track('Переход "Список желаний"');
  235.         break;
  236.     case '/compare/':
  237.         carrotquest.track('Переход "Список сравнения"');
  238.         break;
  239.     case '/dostavka/':
  240.         carrotquest.track('Переход "Доставка и оплата"');
  241.         break;
  242.     case '/faq/about-shipping/':
  243.         carrotquest.track('Переход "Пример расчета стоимости доставки"');
  244.         break;
  245.     case '/reclamation/':
  246.         carrotquest.track('Переход "Обмен или возврат"');
  247.         break;
  248.     case '/contact/':
  249.         carrotquest.track('Переход "Контакты и реквизиты"');
  250.         break;
  251.     case '/faq/cdek':
  252.         carrotquest.track('Переход "Склады СДЭК"');
  253.         break;
  254.     case '/feedback/':
  255.         carrotquest.track('Переход "Обратная связь"');
  256.         break;
  257.     case '/contact':
  258.         carrotquest.track('Переход "Наши реквизиты"');
  259.         break;
  260.     case '/cooperation/':
  261.         carrotquest.track('Переход "Работа с юридическими лицами"');
  262.         break;
  263.     case '/opt/':
  264.         carrotquest.track('Переход "Оптовые предложения (от 10000 руб.)"');
  265.         break;
  266.     case '/about/':
  267.         carrotquest.track('Переход "О нас"');
  268.         break;
  269.     case '/sales-office/':
  270.         carrotquest.track('Переход "Офис продаж"');
  271.         break;
  272.     case '/reward':
  273.         carrotquest.track('Переход "Бонусная программа"');
  274.         break;
  275.     case '/feedback-ru/':
  276.         carrotquest.track('Переход "Отзывы покупателей"');
  277.         break;
  278.     case '/info/':
  279.         carrotquest.track('Переход "Информация для покупателей"');
  280.         break;
  281.     case '/sitemap/':
  282.         carrotquest.track('Переход "Карта сайта"');
  283.         break;
  284.     default: break;
  285. };
  286.  
  287. document.addEventListener('submit', function(e) {
  288.     if (e.target.matches('form[name="search_form"]')) {
  289.         carrotquest.track('Поиск', {
  290.             'Значение поиска': e.target.querySelector('input#ecl_live_search').value
  291.         });
  292.     };
  293. });
  294.  
  295. function dataCollection() {
  296.     if (typeof $ !='undefined') {
  297.         clearInterval(checkJQuery);
  298.         $(document).on('change', 'input[name="user_data[phone]"]', function() {
  299.             carrotquest.identify([{op: 'update_or_create', key: '$phone', value: $(this).val()}]);
  300.         });
  301.         $(document).on('change', 'input[name="user_data[email]"], input[name="user_login"]', function() {
  302.             carrotquest.identify([{op: 'update_or_create', key: '$email', value: $(this).val()}]);
  303.         });
  304.         $(document).on('change', 'input[name="user_data[fullname]"]', function() {
  305.             carrotquest.identify([{op: 'update_or_create', key: '$name', value: $(this).val()}]);
  306.         });
  307.     };
  308. };
  309. var checkJQuery = setInterval(dataCollection, 500);
  310. setTimeout(function() {
  311.     clearInterval(checkJQuery);
  312. }, 5000);
  313.  
  314. (function() {
  315.     init()
  316.     function init() {
  317.         setTimeout(addMouseout, 5000);
  318.     }
  319.     function addMouseout() {
  320.         document.addEventListener('mouseout', mouseout);
  321.     }
  322.     function mouseout(e) {
  323.         if (Math.round(e.x) >= 0 && Math.round(e.y) <= 0) {
  324.             carrotquest.track('Попытка ухода с сайта');
  325.             deleteEvent();
  326.             setTimeout(addMouseout, 10000);
  327.         }
  328.     }
  329.     function deleteEvent() {
  330.         document.removeEventListener('mouseout', mouseout);
  331.     }
  332. }());
  333.  
  334. function TrackUtm(){
  335.     var utm_source = window.location.href.match(/utm_source=([^&]+)/);
  336.     var utm_medium = window.location.href.match(/utm_medium=([^&]+)/);
  337.     var utm_campaign = window.location.href.match(/utm_campaign=([^&]+)/);
  338.     var utm_term = window.location.href.match(/utm_term=([^&]+)/);
  339.     var utm_content = window.location.href.match(/utm_content=([^&]+)/);
  340.     if (utm_content != undefined) {
  341.         carrotquest.identify([
  342.             {op: 'update_or_create', key: 'Последняя метка UTM Content', value: utm_content[1]},
  343.             {op: 'union', key: 'Все метки UTM Content', value: utm_content[1]}
  344.         ]);
  345.     }
  346.     if (utm_source != undefined) {
  347.         carrotquest.identify([
  348.             {op: 'update_or_create', key: 'Последняя метка UTM Source', value: utm_source[1]},
  349.             {op: 'union', key: 'Все метки UTM Source', value: utm_source[1]}
  350.         ]);
  351.     }
  352.     if (utm_medium != undefined) {
  353.         carrotquest.identify([
  354.             {op: 'update_or_create', key: 'Последняя метка UTM Medium', value: utm_medium[1]},
  355.             {op: 'union', key: 'Все метки UTM Medium', value: utm_medium[1]}
  356.         ]);
  357.     }
  358.     if (utm_campaign != undefined) {
  359.         carrotquest.identify([
  360.             {op: 'update_or_create', key: 'Последняя метка UTM Campaign', value: utm_campaign[1]},
  361.             {op: 'union', key: 'Все метки UTM Campaign', value: utm_campaign[1]}
  362.         ]);
  363.     }
  364.     if (utm_term != undefined) {
  365.         carrotquest.identify([
  366.             {op: 'update_or_create', key: 'Последняя метка UTM Term', value: utm_term[1]},
  367.             {op: 'union', key: 'Все метки UTM Term', value: utm_term[1]}
  368.         ]);
  369.     }
  370. };
  371. TrackUtm();
  372.  
  373. carrotquest.addCallback('conversation_opened', function(data) {
  374.     if (data.message == '198331') {
  375.         ga('send', 'event', 'CarrotQuest', 'PopupSeen-Rus');
  376.         yaCounter24705737.reachGoal('PopupSeen-Rus');
  377.     } else if (data.message == '221627768880762521') {
  378.         ga('send', 'event', 'CarrotQuest', 'PopupSeen-SPb');
  379.         yaCounter24705737.reachGoal('PopupSeen-SPb');
  380.     };
  381. });
  382. carrotquest.addCallback('user_replied', function(data) {
  383.     if (data.message == '198331') {
  384.         ga('send', 'event', 'CarrotQuest', 'LeftEmailInPopup-Rus');
  385.         yaCounter24705737.reachGoal('LeftEmailInPopup-Rus');
  386.     } else if (data.message == '221627768880762521') {
  387.         ga('send', 'event', 'CarrotQuest', 'LeftEmailInPopup-SPb');
  388.         yaCounter24705737.reachGoal('LeftEmailInPopup-SPb');
  389.     };
  390. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement