mySiteMap.js

655 lines | 21.954 kB Blame History Raw Download
"use strict";

require("core-js/modules/es.function.name.js");
require("core-js/modules/es.array.concat.js");
require("core-js/modules/es.object.to-string.js");
require("core-js/modules/es.regexp.to-string.js");
require("core-js/modules/es.array.includes.js");
require("core-js/modules/es.string.includes.js");
require("core-js/modules/es.array.slice.js");
require("core-js/modules/es.regexp.exec.js");
require("core-js/modules/es.string.replace.js");
require("core-js/modules/es.regexp.constructor.js");
require("core-js/modules/es.array.iterator.js");
require("core-js/modules/es.string.iterator.js");
require("core-js/modules/web.dom-collections.iterator.js");
require("core-js/modules/web.url.js");
require("core-js/modules/web.url-search-params.js");
require("core-js/modules/es.string.trim.js");
require("core-js/modules/es.string.match.js");
console.log("123");
var enviroment = "";
var pages = [];
esURLValida(window.location.href);

//DATOS DE USUARIO
var isAnonimus = false;
var email = "";
var idUser = "";
var firstName = "";
var lastName = "";
var isSuscriber = "Usuario";
var userDni = "";
var phone = "";
if (typeof vsm.loggedIn === 'function') {
  // La función existe
  console.log("3333");
  isAnonimus = vsm.loggedIn() === false || vsm.loggedIn() === null || vsm.loggedIn() === undefined ? true : false;
  email = vsm.session.email != "" ? vsm.session.email : "";
  idUser = vsm.session.id != "" ? vsm.session.id : "";
  firstName = vsm.session.name != "" ? vsm.session.name : "";
  lastName = vsm.session.lastName != "" ? vsm.session.lastName : "";
  isSuscriber = site.session.isSuscriber() && site.session != undefined ? "Suscriptor" : "Usuario";
} else {
  // La función no existe
  console.log("La función no está definida.");
}
var isMatch = false;
var url = "";
var dateTime = new Date();
dateTime = "".concat(dateTime.getDate(), "/").concat(dateTime.getMonth(), "/").concat(dateTime.getFullYear(), " - hora ").concat(dateTime.getHours(), ":").concat(dateTime.getMinutes());

//Zonas Genericas
var globalZones = [{
  name: "Header",
  selector: '#page-header'
}, {
  name: "Footer",
  selector: '#page-footer'
}];

//SELECTORES Genericos
var globalListeners = [{
  class: "#page-header-session-box .sign-in-button",
  labelName: 'Botón Ingresar',
  ItPropagation: false
}, {
  class: "#page-header-middle .b-suscription",
  labelName: 'Botón Suscribite',
  ItPropagation: false
}, {
  class: ".svg-icon.menu",
  labelName: 'Botón MENU sitio',
  ItPropagation: false
}, {
  class: ".session.with-avatar",
  labelName: 'Botón MENU mi perfil',
  ItPropagation: true
}, {
  class: ".session-options li:nth-child(2) a",
  labelName: 'Botón MI PERFIL',
  ItPropagation: true
}, {
  class: "#main-menu ul li a",
  labelName: 'TAGS',
  ItPropagation: false
}, {
  class: "#page-header .piece.markets.standard ul li",
  labelName: 'TICKERS',
  ItPropagation: false
}, {
  class: ".mitem.pwa-signed-in.session-box",
  labelName: 'Botón MENU mi perfil (MOBILE)',
  ItPropagation: true
}, {
  class: ".mitem.pwa-signed-in.session-box .session-options li:nth-child(2) a",
  labelName: 'Botón MI PERFIL (MOBILE)',
  ItPropagation: true
}, {
  class: ".pwa-footer-fixed-bar .mitem.dolar",
  labelName: 'Botón MENU Dólar (MOBILE)',
  ItPropagation: false
}];

//SELECTORES Home
var homeListeners = [{
  class: ".section article.item",
  labelName: '',
  ItPropagation: false
}, {
  class: ".sectionfull article.item",
  labelName: '',
  ItPropagation: false
}, {
  class: "article.locked",
  labelName: 'Article Member from Home',
  ItPropagation: false
}, {
  class: ".columnists .items article.item",
  labelName: 'Clumnists from Home',
  ItPropagation: false
}];

//SELECTORES PayWall
var payWallListeners = [{
  class: ".page.suscripciones a.logo",
  labelName: 'Botón - Header Logo El Cronista from Pay Wall',
  ItPropagation: false
}, {
  class: ".suscripcion .items .item .button",
  labelName: 'Quiero suscribirme',
  ItPropagation: false
}, {
  class: ".suscripcion .items .item .list_items",
  labelName: 'Botón - Mostrar detalles de  planes',
  ItPropagation: false
}, {
  class: "#page-header-session-box .sign-in-button",
  labelName: 'Botón Ingresar From Pay wall',
  ItPropagation: false
}, {
  class: ".otros-planes .otros-planes__item:first-child p a",
  labelName: 'Botón - Plan Jubilado',
  ItPropagation: false
}, {
  class: ".otros-planes .otros-planes__item:nth-child(2) p a",
  labelName: 'Botón - Plan Estudiante',
  ItPropagation: false
}, {
  class: ".page.suscripciones .whatsapp-wrapper",
  labelName: 'Botón Whatsapp from Pay Wall',
  ItPropagation: false
}, {
  class: ".footer-footer a:first-child",
  labelName: 'Botón Terminos y condiciones from Pay Wall',
  ItPropagation: false
}, {
  class: ".footer-footer a:nth-child(2)",
  labelName: 'Botón Precios vigentes from Pay Wall',
  ItPropagation: false
}];

//SELECTORES LogInWall
var logInWallListeners = [{
  class: "#appleid-signin",
  labelName: 'Botón - Iniciar sesión con Apple',
  ItPropagation: false
}, {
  class: "#facebook",
  labelName: 'Botón - Iniciar sesión con Facebook',
  ItPropagation: false
}, {
  class: "#google",
  labelName: 'Botón - Iniciar sesión con Google',
  ItPropagation: false
}, {
  class: "#vpllocallogin .localloginbtn",
  labelName: 'Botón - Iniciá sesión con tu E-mail',
  ItPropagation: false
}, {
  class: ".submit",
  labelName: 'Botón - Iniciar sesión',
  ItPropagation: false
}, {
  class: ".signup a",
  labelName: 'Botón - Registrate',
  ItPropagation: false
}, {
  class: ".forgotpassword a",
  labelName: 'Botón - Olvidé mi contraseña',
  ItPropagation: false
}, {
  class: ".terminosypolitica a:first-child",
  labelName: 'Botón - Política de privacidad',
  ItPropagation: false
}, {
  class: ".terminosypolitica a:nth-child(2)",
  labelName: 'Botón - Terminos y condiciones',
  ItPropagation: false
}, {
  class: "#vplsignup input.vsmform.submit",
  labelName: 'Botón - Registrarme',
  ItPropagation: false
}];

//SELECTORES Articulo
var articleListeners = [{
  class: "nav.breadcrumb ol li a span",
  labelName: 'Breadcrumb',
  ItPropagation: false
}, {
  class: ".speakText",
  labelName: 'Botón Escuchar',
  ItPropagation: false
}, {
  class: "#content-share",
  labelName: 'Botón Compartir'
}, {
  class: ".more-list .whatsapp a",
  labelName: 'Botón Compartir whatsapp',
  ItPropagation: true
}, {
  class: ".more-list .facebook a",
  labelName: 'Botón Compartir facebook',
  ItPropagation: true
}, {
  class: ".more-list .twitter a",
  labelName: 'Botón Compartir twitter',
  ItPropagation: true
}, {
  class: ".more-list .linkedIn a",
  labelName: 'Botón Compartir linkedIn',
  ItPropagation: true
}, {
  class: ".more-list .email a",
  labelName: 'Botón Compartir email',
  ItPropagation: true
}, {
  class: ".more-list .comments a",
  labelName: 'Botón Compartir comments',
  ItPropagation: true
}, {
  class: "#bookmark",
  labelName: 'Botón Guardar',
  ItPropagation: false
}, {
  class: ".b-member-black .button-wrapper",
  labelName: 'Botón/Caja: Invertí en periodismo de calidad',
  ItPropagation: false
}];

//SELECTORES LANDING DÓLAR
var landingDolarListeners = [{
  class: ".dolar .markets table tr",
  labelName: 'dolares',
  ItPropagation: false
}, {
  class: "nav.breadcrumb ol li a span",
  labelName: 'Breadcrumb',
  ItPropagation: false
}];

//SELECTORES MERCADOS ONLINE
var mercadosOnlineListeners = [{
  class: "nav.breadcrumb ol li a span",
  labelName: 'Breadcrumb',
  ItPropagation: false
}];

//SELECTORES Cotizaciones
var cotizacionesListeners = [{
  class: "nav.breadcrumb ol li a span",
  labelName: 'Breadcrumb',
  ItPropagation: false
}, {
  class: ".markets.button #button-follow",
  labelName: 'Seguir (cotización)',
  ItPropagation: false
}];
var confirmacionOnAirListeners = [];
var streamingExclusivoListeners = [{
  class: "#paywallButton-btn",
  labelName: 'Quiero participar',
  ItPropagation: false
}];

//SELECTORES formulario de suscripciones
var suscriptionsFormListeners = [{
  class: ".panels .panel:first-child form .button",
  labelName: 'Botón form siguiente 1',
  ItPropagation: false
}, {
  class: ".panels .panel:nth-child(2) form .button:first-child",
  labelName: 'Botón volver formulario',
  ItPropagation: false
}, {
  class: ".panels .panel:nth-child(2) form .button:nth-child(2)",
  labelName: 'Botón confirmar pago formulario',
  ItPropagation: false
}];

//Interacciones
var homeInteractions = {
  name: "Home"
};
var payWallInteractions = {
  name: PayWallIteractionName()
};
var logInWallInteractions = {
  name: "LogInWall"
};
var landingDolarInteractions = {
  name: "Landing Dólar"
};
var mercadosOnlineInteractions = {
  name: "Mercados online"
};
var confirmacionOnAirInteractions = {
  name: "Confirmacion On Air"
};
var streamingExclusivoInteractions = {
  name: "Streaming Exclusivo"
};
var suscriptionsFormInteractions = {
  name: "Suscriptions form"
};
var suscriptionsConfirmInteractions = {
  name: "Suscriptions Confirm"
};
var home = new PageType("Home", "cronista.com", homeInteractions, homeListeners, false);
var payWall = new PageType("PayWall", "cronista.com/suscripciones", payWallInteractions, payWallListeners, false);
var logInWall = new PageType("LogInWall", "cronista.com/ingresa", logInWallInteractions, logInWallListeners, false);
var landingDolar = new PageType("Landing Dólar", "cronista.com/MercadosOnline/dolar.html", landingDolarInteractions, landingDolarListeners, document.querySelector(".page.dolar"));
var mercadosOnline = new PageType("Mercados Online", "cronista.com/informacion-de-mercados", mercadosOnlineInteractions, mercadosOnlineListeners, false);
var streamingExclusivo = new PageType("Streaming Exclusivo", "cronista.com/on-air/streaming-exclusivo", streamingExclusivoInteractions, streamingExclusivoListeners, false);
var confirmacionOnAir = new PageType("ConfirmacionOnAir", "cronista.com/on-air/confirmacion-on-air", confirmacionOnAirInteractions, confirmacionOnAirListeners, false);
var suscriptionsForm = new PageType("Suscriptions form", "cronista.com/suscripciones/plan-xxx", suscriptionsFormInteractions, suscriptionsFormListeners, false);
var suscriptionsConfirm = new PageType("Suscriptions Confirm", "cronista.com/suscripciones/plan-xxx/#listo", suscriptionsConfirmInteractions, [], false);
if (validarParteDeURL(window.location.href, "MercadosOnline") && !validarParteDeURL(window.location.href, "cronista.com/MercadosOnline/dolar.html")) {
  var cotizacionesInteractions = {
    name: SalesforceInteractions.CatalogObjectInteractionName.ViewCatalogObject,
    catalogObject: {
      type: "Cotizaciones",
      id: window.cronistaDataLayer[0].articleProperty.id,
      attributes: {
        url: window.location.href,
        name: SalesforceInteractions.cashDom(".section-header-title a").text()
      },
      relatedCatalogObjects: {
        TipoDeCotizaciones: SalesforceInteractions.DisplayUtils.pageElementLoaded("html").then(function (ele) {
          return [window.cronistaDataLayer[0].articleProperty.category.toUpperCase()];
        })
      }
    }
  };
  var cotizaciones = new PageType("Cotizaciones", "cronista.com/MercadosOnline", cotizacionesInteractions, cotizacionesListeners, false);
  pages.push(cotizaciones);
}
if (document.querySelector("#pagecontent .news") || document.querySelector("#pagecontent .news-minisite") || document.querySelector("#pagecontent .news-es") || document.querySelector("#pagecontent .news-mx")) {
  var metaTag = document.querySelector('meta[property="og:image"]');
  var interaction = {
    name: SalesforceInteractions.CatalogObjectInteractionName.ViewCatalogObject,
    catalogObject: {
      type: "Article",
      id: window.cronistaDataLayer[0].articleProperty.id,
      attributes: {
        url: window.location.href,
        name: SalesforceInteractions.resolvers.fromSelector("#content-title"),
        description: SalesforceInteractions.resolvers.fromSelector(".description"),
        imageUrl: metaTag ? metaTag.getAttribute('content') : null,
        articleId: window.cronistaDataLayer[0].articleProperty.id.toString(),
        seccion: window.cronistaDataLayer[0].articleProperty.category,
        articleTitle: SalesforceInteractions.resolvers.fromSelector("#content-title"),
        publishDate: SalesforceInteractions.resolvers.fromSelector(".author-date time"),
        authorName: window.cronistaDataLayer[0].articleProperty.authorName,
        canonicalUrl: window.cronistaDataLayer[0].articleProperty.canonica,
        accessCondition: window.cronistaDataLayer[0].articleProperty.conditionsOfAccess
      },
      relatedCatalogObjects: {
        Category: SalesforceInteractions.DisplayUtils.pageElementLoaded("html").then(function (ele) {
          return [window.cronistaDataLayer[0].articleProperty.category.toUpperCase()];
        }),
        Autores: SalesforceInteractions.DisplayUtils.pageElementLoaded("html").then(function (ele) {
          return [window.cronistaDataLayer[0].articleProperty.authorName.toUpperCase()];
        }),
        CondicionDeAcceso: SalesforceInteractions.DisplayUtils.pageElementLoaded("html").then(function (ele) {
          return [window.cronistaDataLayer[0].articleProperty.conditionsOfAccess.toUpperCase()];
        })
      }
    }
  };
  var article = new PageType("Article", window.location.href, interaction, articleListeners, document.querySelector("#pagecontent .news"));
  pages.push(article);
}

//Función que devuelve el array con las info de las pageType
/*[home, payWall, article, logInWall, landingDolar, mercadosOnline, confirmacionOnAir,
streamingExclusivo, suscriptionsForm, suscriptionsConfirm]*/
function Pages() {
  pages.push(home, payWall, logInWall, landingDolar, mercadosOnline, confirmacionOnAir, streamingExclusivo, suscriptionsForm, suscriptionsConfirm);
  return pages;
}

//MATCH PAGE
function PageType(name, myUrl, interaction, myEvents, IsTemplate) {
  this.name = name;
  this.isMatch = function () {
    var url = window.location.href;
    if (url.includes('?')) {
      url = url.slice(0, window.location.href.lastIndexOf('?'));
    }
    if (url.charAt(url.length - 1) === '/') {
      url = url.slice(0, -1);
    }

    //VALIDO POR TEMPLATE O URL
    if (IsTemplate) {
      isMatch = true;
    } else {
      isMatch = url === "".concat(enviroment).concat(myUrl) ? true : false;
      if (name == "Cotizaciones" && validarParteDeURL(url, "MercadosOnline")) {
        isMatch = true;
      }
      if (name == "Suscriptions form" && validarParteDeURL(url, "cronista.com/suscripciones/plan-") && !validarParteDeURL(url, "/#listo")) {
        isMatch = true;
      }
      if (name == "Suscriptions Confirm" && validarParteDeURL(url, "#listo")) {
        isMatch = true;
      }
    }
    console.log(isMatch);
    return isMatch;
  };
  this.interaction = interaction;
  this.listeners = GenerateListeners(name, myEvents);
}
function validarParteDeURL(url, parte) {
  var parteEscapada = parte.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  var regex = new RegExp(parteEscapada);
  return regex.test(url);
}
function GlobalActions(actionEvent) {
  url = window.location.href;
  if (email) {
    actionEvent.user = actionEvent.user || {};
    actionEvent.user.attributes = actionEvent.user.attributes || {};
    actionEvent.user.identities = actionEvent.user.identities || {};
    actionEvent.user.attributes.URL || {};
    actionEvent.user.attributes.contentZones || {};
    actionEvent.user.attributes.emailAddress = email;
    actionEvent.user.attributes.isSuscription = isSuscriber;
    actionEvent.user.attributes.name = firstName;
    actionEvent.user.attributes.lastName = lastName;
    actionEvent.user.attributes.date = dateTime;
    actionEvent.user.attributes.isAnonimus = isAnonimus;
    actionEvent.user.identities.userIdCms = idUser;
  }
  return actionEvent;
}
function PayWallIteractionName() {
  var typeOfPayWall = "";
  var limit = new URL(window.location.href).searchParams.get("limit");
  if (limit != null) {
    var isLimit = limit === 'true';
    typeOfPayWall = !isLimit ? "choque exclusivo" : "choque metered";
    //let continueUrl = new URL(window.location.href).searchParams.get("continue")
    typeOfPayWall = "Pay wall - " + typeOfPayWall;
  } else {
    typeOfPayWall = "Pay wall - Choque directo";
  }
  return typeOfPayWall;
}
function ReadHomeBlocks(event) {
  var main = document.querySelector('.main-container');
  var block1 = main.childNodes[0].querySelectorAll('article.item');
  var block2 = main.childNodes[2].querySelectorAll('article.item');
  sendDataFromHomeBlocks("Click, Article from home (Bloque1)", event, block1);
  sendDataFromHomeBlocks("Click, Article from home (Bloque2)", event, block2);
}
function sendDataFromHomeBlocks(nameEvent, target, container) {
  for (var i = 0; i < container.length; i++) {
    if (target === container[i]) {
      SalesforceInteractions.sendEvent({
        interaction: {
          name: nameEvent
        },
        user: {
          identities: {
            emailAddress: email
          },
          attributes: {
            name: firstName,
            lastName: lastName
          }
        }
      });
      break;
    }
  }
}
function ReadGlobalEvents(event, listeners) {
  var dataName = listeners.labelName;
  var isSend = true;
  var nameTarget = SalesforceInteractions.cashDom(event.target).text();
  if (listeners.labelName == "TAGS") {
    switch (event.target.innerText) {
      case "EDICIÓN IMPRESA":
        dataName = "TAG: " + nameTarget;
        break;
      case "DÓLAR":
        dataName = "TAG: " + nameTarget;
        break;
      case "DÓLAR BLUE":
        dataName = "TAG: " + nameTarget;
        break;
      case "QUIÉN ES QUIÉN":
        dataName = "TAG: " + nameTarget;
        break;
      default:
        isSend = false;
        break;
    }
  }
  if (listeners.labelName == "TICKERS") {
    var tickerElement = event.currentTarget.querySelector("a span.name");
    dataName = listeners.labelName + ": " + SalesforceInteractions.cashDom(tickerElement).text();
  }
  if (listeners.labelName == 'Quiero suscribirme') {
    dataName = "Botón: " + listeners.labelName + ": " + SalesforceInteractions.cashDom(event.target.parentNode.querySelector(".title")).text();
  }
  if (listeners.labelName == 'Breadcrumb') {
    dataName = listeners.labelName + ": " + nameTarget;
  }
  if (listeners.labelName == 'Botón - Iniciar sesión') {
    var emailAnonimus = SalesforceInteractions.cashDom(".input.username .username").val();
    email = emailAnonimus;
  }
  if (listeners.labelName == 'Botón - Registrarme') {
    var _emailAnonimus = SalesforceInteractions.cashDom(".vsmemail input").val();
    var registerName = SalesforceInteractions.cashDom('input[name="vsm_name"]').val();
    var registerLastName = SalesforceInteractions.cashDom('input[name="vsm_lastname"]').val();
    firstName = registerName;
    lastName = registerLastName;
    email = _emailAnonimus;
  }
  if (listeners.labelName == 'dolares') {
    dataName = "Cotización dólar: " + SalesforceInteractions.cashDom(event.currentTarget.querySelector(".name")).text();
  }
  if (listeners.labelName == 'Botón form siguiente 1') {
    var suscriptionPhone = SalesforceInteractions.cashDom('input[name="phone"]').val();
    var suscriptionDNI = SalesforceInteractions.cashDom('input[name="document"]').val();
    var suscriptionName = SalesforceInteractions.cashDom('input[name="name"]').val();
    var suscriptionLastName = SalesforceInteractions.cashDom('input[name="lastname"]').val();
    firstName = suscriptionName;
    lastName = suscriptionLastName;
    userDni = suscriptionDNI;
    phone = suscriptionPhone;
    var dataSuscriptionForm = [suscriptionPhone, suscriptionDNI, suscriptionName, suscriptionLastName];
    for (var i = 0; i < dataSuscriptionForm.length; i++) {
      if (!dataSuscriptionForm[i].trim()) {
        isSend = false;
      }
    }
  }
  if (listeners.labelName == 'Botón confirmar pago formulario') {
    var queryString = window.location.href;
    if (!validarParteDeURL(queryString, "#listo")) {
      isSend = false;
    }
  }
  if (isSend) {
    SalesforceInteractions.sendEvent({
      interaction: {
        name: dataName
      },
      user: {
        attributes: {
          userIdCms: idUser,
          name: firstName,
          lastName: lastName,
          dni: userDni,
          phone: phone,
          isSuscriber: isSuscriber,
          emailAddress: email,
          continueUrl: url,
          isAnonimus: isAnonimus
        }
      }
    });
  }
}
function GenerateContentZones(zones) {
  var ContentZones = [];
  if (zones.length > 0) {
    for (var i = 0; i < zones.length; i++) {
      var ContentZone = {
        name: zones[i].name,
        selector: zones[i].selector
      };
      ContentZones.push(ContentZone);
    }
  }
  return ContentZones;
}
function GenerateListeners(pageType, elements) {
  var listeners = [];
  if (elements.length > 0) {
    var _loop = function _loop(i) {
      if (pageType == "Home" && (elements[i].class == elements[0].class || elements[i].class == elements[1].class)) {
        var myEventsBlock = SalesforceInteractions.listener("click", elements[i].class, function (e) {
          ReadHomeBlocks(e.currentTarget);
        });
        listeners.push(myEventsBlock);
      } else {
        var myEvents = SalesforceInteractions.listener("click", "".concat(elements[i].class), function (e) {
          if (elements[i].ItPropagation) {
            e.stopPropagation();
          }
          ReadGlobalEvents(e, elements[i]);
        });
        listeners.push(myEvents);
      }
    };
    for (var i = 0; i < elements.length; i++) {
      _loop(i);
    }
  }
  return listeners;
}
function esURLValida(url) {
  var regex = url.match(/^https:\/\/(?:dev|qa|qa2|www)\./i);
  enviroment = regex[0];
}
window.addEventListener("load", function () {
  SalesforceInteractions.init({
    cookieDomain: "cronista.com"
  }).then(function () {
    var sitemapConfig = {
      global: {
        onActionEvent: function onActionEvent(actionEvent) {
          return GlobalActions(actionEvent);
        },
        contentZones: GenerateContentZones(globalZones),
        listeners: GenerateListeners("Global", globalListeners)
      },
      pageTypeDefault: {
        name: "default",
        interaction: {
          name: "Default Page"
        }
      },
      pageTypes: Pages()
    };
    SalesforceInteractions.initSitemap(sitemapConfig);
  });
});