var queryParams; var utm_campaign="", utm_content="", utm_medium="", utm_Source =null, utm_term="", google_cid=""; var utm_Form; var $metaBusiness = $("meta[name='rp-business']"); var businessValue = (($metaBusiness.length) && ($metaBusiness.attr("content") !== "")) ? $metaBusiness.attr("content") : 'undefined'; var RepsolSolmatch = { AnalyticsSolmatch: { init: function(){ if(sessionStorage.UTM!=undefined){ utm_Form=JSON.parse(sessionStorage.UTM); if(utm_Form.utm_source){ Repsol.utils.setParamUtm(); } else{ Repsol.utils.searchParamUtm(); } } else{ Repsol.utils.searchParamUtm(); } if(document.cookie.indexOf("_ga=")>-1){ gaCookie = document.cookie.split("_ga=")[1].split(";")[0].split("."); google_cid = gaCookie[2] + "." + gaCookie[3]; } RepsolSolmatch.AnalyticsSolmatch.events(); }, events: function () { $(document).on("click", ".block-search-community .blockButton .btn-list a", function (e) { e.stopPropagation(); RepsolSolmatch.AnalyticsSolmatch.clickFunnelMatcher($(this)); params = { field_name_1: undefined, field_name_2: undefined, selected_option_1: 'matcher', selected_option_2: undefined, establishment_category: undefined, establishment_raiting: undefined, establishment_state: undefined }; Repsol.AnalyticsRomProd.funnelRomProd($(this), params); }); $(document).on("click", ".map-component .buttonSearch", function (e) { e.stopPropagation(); RepsolSolmatch.AnalyticsSolmatch.clickFunnelMatcherBis($(this)); params = { field_name_1: undefined, field_name_2: undefined, selected_option_1: 'matcher', selected_option_2: undefined, establishment_category: undefined, establishment_raiting: undefined, establishment_state: undefined }; Repsol.AnalyticsRomProd.funnelRomProd($(this), params); }); $(document).on("click", ".card-ecommerce .card-link .rp-link-click", function (e) { e.stopPropagation(); if(businessValue === 'solmatch'){ if($(this).parent().hasClass("buttonModalMatcher")){ RepsolSolmatch.AnalyticsSolmatch.clickButtonActiveCommu($(this)); } else { RepsolSolmatch.AnalyticsSolmatch.clickButtonNoModalCommu($(this)); } } }); $(document).on("click", ".hero-card .call-me-form .button-repsol > a", function (e) { e.stopPropagation(); if (businessValue === 'solmatch') { RepsolSolmatch.AnalyticsSolmatch.clickButtonHeroActiveCommu($(this)); } }); $(document).on("click", ".illustration-lottie__controller__item-container", function (e) { const $this = $(this); var params= { component_description: $this.parent().attr("data-attr-mod"), component_name: $this.parents("[data-component]").attr("data-component"), }; RepsolSolmatch.AnalyticsSolmatch.clickButtonInfogra($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), params); }); $(document).on("click", ".numberPhoneHeader a", function (e){ Repsol.Analytics.clickBtn($(this)); Repsol.AnalyticsRomProd.linkClickRomProd($(this), {}); }); $(document).on("click", ".mosaic .buttonModalMatcher .rp-link-click", function (e) { if (businessValue === 'solmatch') { RepsolSolmatch.AnalyticsSolmatch.clickButtonModalMatcher($(this)); } }); }, clickFunnelMatcherBis: function (obj) { var jsonInfo = { event: 'solmatch_matcher_funnel', funnel_action: 'address search', funnel_step: "01", funnel_type: 'matcher', event_detail: "long", solmatch_solar_community_name: undefined, solmatch_solar_community_address: undefined, solmatch_solar_community_state: undefined, solmatch_solar_community_type: undefined, solmatch_solar_community: undefined } jsonInfo["solmatch_address"] = ($.cookie("direccion")) ? $.cookie("direccion") : undefined; RepsolSolmatch.AnalyticsSolmatch.setInfoClick(jsonInfo); const latitude = DOMPurify.sanitize($("#latResult").val()), longitude = DOMPurify.sanitize($("#lngResult").val()); let url = ''; if (searchActive == true) { url = $(".communityDetailPath").val() + "?lat=" + latitude + "&lng=" + longitude; } else if (searchActive == false) { url = $(".communityDetailPathKo").val() + "?lat=" + latitude + "&lng=" + longitude; } else{ url = $(".nearbyCommunities").val() + "?lat=" + latitude + "&lng=" + longitude; } Repsol.utils.redirectToUrl(url); }, clickFunnelMatcherBisNoRedirect: function (obj) { var jsonInfo = { event: 'solmatch_matcher_funnel', funnel_action: 'address search', funnel_step: "01", funnel_type: 'matcher', event_detail: "long", solmatch_solar_community_name: undefined, solmatch_solar_community_address: undefined, solmatch_solar_community_state: undefined, solmatch_solar_community_type: undefined, solmatch_solar_community: undefined } jsonInfo["solmatch_address"] = ($.cookie("direccion")) ? $.cookie("direccion") : undefined; RepsolSolmatch.AnalyticsSolmatch.setInfoClick(jsonInfo); }, clickFunnelMatcher: function (obj) { var jsonInfo = { event: 'solmatch_matcher_funnel', funnel_action: 'address search', funnel_step: "01", funnel_type: 'matcher', event_detail: "long", solmatch_solar_community_name: undefined, solmatch_solar_community_address: undefined, solmatch_solar_community_state: undefined, solmatch_solar_community_type: undefined, solmatch_solar_community: undefined } jsonInfo["solmatch_address"] = ($.cookie("direccion")) ? $.cookie("direccion") : undefined; RepsolSolmatch.AnalyticsSolmatch.setInfoClick(jsonInfo); const latitude = DOMPurify.sanitize($("#latResult").val()), longitude = DOMPurify.sanitize($("#lngResult").val()); let url = ''; if (searchActiveMap == true) { url = $(".communityDetailPath").val() + "?lat=" + latitude + "&lng=" + longitude; } else if (searchActiveMap == false) { url = $(".communityDetailPathKo").val() + "?lat=" + latitude + "&lng=" + longitude; } else{ url = $(".nearbyCommunities").val() + "?lat=" + latitude + "&lng=" + longitude; } Repsol.utils.redirectToUrl(url); }, clickFunnelMatcherNoRedirect: function (obj) { var jsonInfo = { event: 'solmatch_matcher_funnel', funnel_action: 'address search', funnel_step: "01", funnel_type: 'matcher', event_detail: "long", solmatch_solar_community_name: undefined, solmatch_solar_community_address: undefined, solmatch_solar_community_state: undefined, solmatch_solar_community_type: undefined, solmatch_solar_community: undefined } jsonInfo["solmatch_address"] = ($.cookie("direccion")) ? $.cookie("direccion") : undefined; RepsolSolmatch.AnalyticsSolmatch.setInfoClick(jsonInfo); }, clickFunnelMatcherModal: function (obj) { direccionLista = Repsol.utils.getData("matcher_way") ? Repsol.utils.getData("matcher_way") : undefined; var matcher_way = direccionLista; getCookieList("direccion"); var titleRight = $(".community-card .community-list-component .block-info-text .rp-title-1").text(); var adressRight = $(".community-card .community-list-component .block-info-text .rp-body-1").text(); var status = $(".community-card .community-list-component .block-tooltip .estado").text(); var jsonInfo = { event: 'solmatch_matcher_funnel', funnel_action: 'matcher form open', funnel_step: "02_02", funnel_type: "matcher", event_detail: matcher_way, solmatch_solar_community_name: titleRight, solmatch_solar_community_address: adressRight, solmatch_solar_community_state: status, solmatch_solar_community_type: undefined , solmatch_solar_community: undefined + " | " + titleRight + " | " + status } if ($.cookie("direccion") != undefined) { jsonInfo["solmatch_address"] = $.cookie("direccion"); } else { jsonInfo["solmatch_address"] = undefined } RepsolSolmatch.AnalyticsSolmatch.setInfoClick(jsonInfo); }, clickFunnelMatcherSendForm: function (obj) { direccionLista = Repsol.utils.getData("matcher_way") ? Repsol.utils.getData("matcher_way") : undefined; var matcher_way = direccionLista; getCookieList("direccion"); var titleRight = $(".community-card .community-list-component .block-info-text .rp-title-1").text(); var adressRight = $(".community-card .community-list-component .block-info-text .rp-body-1").text(); var status = $(".community-card .community-list-component .block-tooltip .estado").text(); var jsonInfo = { event: 'solmatch_matcher_funnel', funnel_action: 'matcher form', funnel_step: "03", funnel_type: "matcher", event_detail: matcher_way, solmatch_solar_community_name: titleRight, solmatch_solar_community_address: adressRight, solmatch_solar_community_state: status, solmatch_solar_community_type: undefined , solmatch_solar_community: undefined + " | " + titleRight + " | " + status } if ($.cookie("direccion") != undefined) { jsonInfo["solmatch_address"] = $.cookie("direccion"); } else { jsonInfo["solmatch_address"] = undefined } document.cookie = "formSend" + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; eraseCookie("formSend", "modalMatcher"); document.cookie = "commutySolar" + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; eraseCookie("commutySolar", titleRight); document.cookie = "commutySolarAdress" + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; eraseCookie("commutySolarAdress", adressRight); document.cookie = "commutySolarState" + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; eraseCookie("commutySolarState", status); RepsolSolmatch.AnalyticsSolmatch.setInfoClick(jsonInfo); }, clickFunnelModalLista: function (obj) { direccionLista = Repsol.utils.getData("matcher_way") ? Repsol.utils.getData("matcher_way") : undefined; var matcher_way = direccionLista; var jsonInfo = { 'event': 'solmatch_open_funnel', 'event_type': 'matcher profile', 'link_text':obj.find(".text").text(), 'link_url': obj.attr("href"), 'component_name': "content block", 'event_detail': matcher_way } var jsonInfo = { event: 'solmatch_matcher_funnel', funnel_action: 'waiting list form open', funnel_step: "02_02", funnel_type: 'waiting list', event_detail: matcher_way, } if($(".adressInput").length>0){ jsonInfo["solmatch_address"] = undefined; } else{ if ($.cookie("direccion") != undefined) { jsonInfo["solmatch_address"] = $.cookie("direccion"); } else { jsonInfo["solmatch_address"] = undefined } } RepsolSolmatch.AnalyticsSolmatch.setInfoClick(jsonInfo); }, clickFunnelModalSendLista: function (obj) { var jsonInfo = { event: 'solmatch_matcher_funnel', funnel_action: 'waiting list form', funnel_step: "03", funnel_type: 'waiting list', event_detail:"short", } jsonInfo["solmatch_address"] = ($.cookie("direccion")) ? $.cookie("direccion") : undefined; document.cookie = "formSend" + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; eraseCookie("formSend", "listaEspera"); RepsolSolmatch.AnalyticsSolmatch.setInfoClick(jsonInfo); }, clickFunnelModalRooferPass1: function (obj) { paso1Roofer = obj.find("input").val(); }, clickFunnelModalRooferPass2: function (obj) { paso2Roofer = obj.find("input").val(); }, clickFunnelModalRooferPass3: function (obj) { paso3Roofer = obj.find("input").val(); }, clickFunnelModalRooferPass4: function (obj) { paso4Roofer = obj.find("input").val(); }, clickFunnelModalRooferPass5: function (obj) { paso5Roofer = $(".selectPass5 .typeVie .boxSelect .rp-body-1").text(); paso5Roofer += " " + $(".selectPass5 #direccionCalle").val(); paso5Roofer += ", " + $(".selectPass5 #direccionCP").val(); paso5Roofer += ", " + $(".selectPass5 #DireccionMunicipio__c").val(); paso5Roofer += ", " + $(".selectPass5 .typePro .boxSelect .rp-body-1").text(); var jsonInfo = { event: 'solmatch_roofer_funnel', funnel_action: "roofer form", funnel_step: "03", funnel_type: 'roofer', event_category: "q1 " + paso1Roofer+ " - q2 " + paso2Roofer+" - q3 " + paso3Roofer, solmatch_solar_community_name: undefined, solmatch_solar_community_address: paso5Roofer, solmatch_solar_community_state: "sent roofer", solmatch_solar_community_type: paso4Roofer, solmatch_solar_community: paso4Roofer + " | " + undefined + " | " + "sent roofer" } if(paso4Roofer=="Colegio"){ jsonInfo["solmatch_solar_community_name"]= $("#schoolName").val(); jsonInfo["solmatch_solar_community"]= paso4Roofer + " | " + $("#schoolName").val() + " | " + "sent roofer" document.cookie = "nameSchool" + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; eraseCookie("nameSchool", $("#schoolName").val()); } RepsolSolmatch.AnalyticsSolmatch.setInfoClick(jsonInfo); }, clickFunnelModalRooferPass6: function (obj) { qualificationJson= "q1 " + paso1Roofer+ " - q2 " + paso2Roofer+" - q3 " + paso3Roofer, document.cookie = "formSend" + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; eraseCookie("formSend", "modalRoofer"); document.cookie = "qualification" + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; $.cookie("qualification", qualificationJson); document.cookie = "commutySolarAdress" + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; eraseCookie("commutySolarAdress", paso5Roofer); document.cookie = "communityType" + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; eraseCookie("communityType", paso4Roofer); }, clickButtonModalMatcher: function(obj){ var jsonInfo = { 'event': 'solmatch_open_funnel', 'event_type': 'matcher profile', 'link_text':obj.find(".text").text(), 'link_url': obj.attr("href"), 'event_detail': Repsol.Analytics.getFunnelEventDetail(obj), 'component_name': obj.parents("[data-component]").attr("data-component") } RepsolSolmatch.AnalyticsSolmatch.setInfoClick(jsonInfo); }, clickButtonActiveCommu: function(obj){ var jsonInfo = { 'event': 'solmatch_open_funnel', 'event_type': 'matcher profile', 'link_text':obj.find(".text").text(), 'link_url': obj.attr("href"), 'component_name': "card services" } RepsolSolmatch.AnalyticsSolmatch.setInfoClick(jsonInfo); }, clickButtonNoModalCommu: function(obj){ var jsonInfo = { 'event': 'solmatch_open_funnel', 'event_type': 'roofer profile', 'link_text':obj.find(".text").text(), 'link_url': obj.attr("href"), 'component_name': "card services" } RepsolSolmatch.AnalyticsSolmatch.setInfoClick(jsonInfo); }, clickButtonHeroActiveCommu: function(obj){ var jsonInfo = { 'event': 'solmatch_open_funnel', 'event_type': 'roofer profile', 'link_text':obj.find(".text").text(), 'link_url': obj.attr("href"), 'component_name': "Hero Card" } RepsolSolmatch.AnalyticsSolmatch.setInfoClick(jsonInfo); }, clickButtonInfogra: function(obj){ var jsonInfo = { 'event': 'interaction', 'component_description': obj.parent().attr("data-attr-mod"), 'component_name': obj.parents("[data-component]").attr("data-component") } RepsolSolmatch.AnalyticsSolmatch.setInfoClick(jsonInfo); }, setInfoClick: function (jsonInfo) { window.dataLayer.push(jsonInfo); Repsol.Analytics.sendAdobeDataLayer(jsonInfo); } } } var paso1Roofer, paso2Roofer, paso3Roofer, paso4Roofer,qualificationJson; function createCookie(nameCookie, value, days) { document.cookie = value + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expires = "; expires=" + date.toGMTString(); } else var expires = ""; document.cookie = nameCookie + "=" + value + expires + "; path=/"; } var direccionLista = ""; function getCookieList(name) { const value = document.cookie; const parts = value.split(name + '='); if (parts.length === 2) { direccionLista = parts.pop().split(';').shift(); } } $(document).ready(function () { RepsolSolmatch.AnalyticsSolmatch.init(); }); function eraseCookie(nameCookie, valor) { createCookie(nameCookie, valor, 1); } Repsol.Analytics.Store = { event: { viewItemList : "view_item_list", viewItem : "view_item", viewCart : "view_cart", selectItem : "select_item", addToCart : "add_to_cart", removeFromCart : "remove_from_cart", removeAllFromCart : "remove_all_from_cart", beginCheckout: "begin_checkout", addShippingInfo: "add_shipping_info", addPaymentInfo: "add_payment_info", purchase: "purchase" }, init: () => { Repsol.Analytics.Store.events(); }, events: () => { $(document).on("click", ".product-list__filters-category-item .product-list__filters-category-link", function () { Repsol.Analytics.Store.clickBtn($(this)); let obj=$(this); if(obj.hasClass('product-list__filters-category-link') || obj.hasClass('product-list__filters-category-sub-list-link') || obj.hasClass('product-list__filters-category-sub-list-2-link') || obj.hasClass('product-list__category-link') || obj.hasClass('product-list__category-sub-list-link')){ var params = { component_name: 'menú lateral' }; Repsol.AnalyticsRomProd.menuClickRomProd2024(obj, params); } else{ Repsol.AnalyticsRomProd.linkClickRomProd($(this), {}); } }); $(document).on("click", ".product-list__manual-card", function () { Repsol.Analytics.Store.clickBtnManualCard($(this)); let params ={ link_text: Repsol.AnalyticsRomProd.Getters.getTextLink($(this).find('.rp-small-button')) } Repsol.AnalyticsRomProd.linkClickRomProd($(this), params); }); $(document).on("click", ".product-list__filters-category-sub-list .product-list__filters-category-sub-list-link", function () { Repsol.Analytics.Store.clickBtn($(this)); let obj = $(this); if(obj.hasClass('product-list__filters-category-link') || obj.hasClass('product-list__filters-category-sub-list-link') || obj.hasClass('product-list__filters-category-sub-list-2-link') || obj.hasClass('product-list__category-link') || obj.hasClass('product-list__category-sub-list-link')){ var params = { component_name: 'menú lateral' }; Repsol.AnalyticsRomProd.menuClickRomProd2024(obj, params); } else{ Repsol.AnalyticsRomProd.linkClickRomProd($(this), {}); } }); $(document).on("click", ".product-list__filters-category-sub-list-2 .product-list__filters-category-sub-list-2-link", function () { Repsol.Analytics.Store.clickBtn($(this)); let obj=$(this); if(obj.hasClass('product-list__filters-category-link') || obj.hasClass('product-list__filters-category-sub-list-link') || obj.hasClass('product-list__filters-category-sub-list-2-link') || obj.hasClass('product-list__category-link') || obj.hasClass('product-list__category-sub-list-link')){ var params = { component_name: 'menú lateral' }; Repsol.AnalyticsRomProd.menuClickRomProd2024(obj, params); } else{ Repsol.AnalyticsRomProd.linkClickRomProd($(this), {}); } }); $(document).on("click", ".product-list__category-list .product-list__category-item-list .product-list__category-link", function () { Repsol.Analytics.Store.clickBtn($(this)); let obj=$(this); if(obj.hasClass('product-list__filters-category-link') || obj.hasClass('product-list__filters-category-sub-list-link') || obj.hasClass('product-list__filters-category-sub-list-2-link') || obj.hasClass('product-list__category-link') || obj.hasClass('product-list__category-sub-list-link')){ var params = { component_name: 'menú lateral' }; Repsol.AnalyticsRomProd.menuClickRomProd2024(obj, params); } else{ Repsol.AnalyticsRomProd.linkClickRomProd($(this), {}); } }); $(document).on("click", ".product-list__category-sub-list .product-list__category-sub-item .product-list__category-sub-list-link", function () { Repsol.Analytics.Store.clickBtn($(this)); let obj=$(this); if(obj.hasClass('product-list__filters-category-link') || obj.hasClass('product-list__filters-category-sub-list-link') || obj.hasClass('product-list__filters-category-sub-list-2-link') || obj.hasClass('product-list__category-link') || obj.hasClass('product-list__category-sub-list-link')){ var params = { component_name: 'menú lateral' }; Repsol.AnalyticsRomProd.menuClickRomProd2024(obj, params); } else{ Repsol.AnalyticsRomProd.linkClickRomProd($(this), {}); } }); $(document).on("click", ".product-list .product-list__filter .dropdown-menu-list .dropdown-item", function () { Repsol.Analytics.Store.clickFilter($(this)); var params ={ element_type: 'filter list', }; Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), params); }); $(document).on("click", ".product-list__filters-delete, .product-list__filters-delete--mobile", function () { Repsol.Analytics.Store.clickCleanFilter($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), {}); }); $(document).on("click", ".product-list__dropdown-item.dropdown-item", function () { Repsol.Analytics.Store.clickProductListSortOrder($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), {}); }); $(document).on("click", ".product-list__sort-button", function () { Repsol.Analytics.Store.clickFilterOrder($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), {}); }); $(document).on("click", ".pagination-container .page-item.page-item--prev, .pagination-container .page-item.page-item--next", function (e) { const $this = $(this); var params = { element_type: $this.hasClass("page-item--prev") ? 'prev' : 'next', link_text: $this.attr("data-text"), }; Repsol.Analytics.Store.clickPaginationArrow($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), params); }); $(document).on("click", ".pagination-container .page-item:not(.page-item--prev, .page-item--next)", function (e) { if (!$(this).hasClass("next")) { var params = { element_type: 'page number', }; Repsol.Analytics.Store.clickPaginationNumber($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), params); } }); $(document).on("click", ".accordion-product-detail .cmp-accordion__item", function () { Repsol.Analytics.Store.clickDetailInfo($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), {}); }); $(document).on("click", ".accordion-product-detail__links .rp-link", function () { /* file-download-deprecation Repsol.Analytics.Store.clickDownloadInfo($(this)); */ Repsol.AnalyticsRomProd.fileDownloadRomProd($(this)); }) $(document).on("click", ".product-detail-component .slick-arrow, .related-products-component .slick-arrow, .store-access-component .slick-arrow", function () { Repsol.Analytics.Store.clickArrow($(this)); }) $(document).on("click", ".product-detail-component .slick-arrow, .recommended-products-component .slick-arrow, .store-access-component .slick-arrow", function () { Repsol.Analytics.Store.clickArrow($(this)); }) $(document).on("click", ".product-add-unit .plus,.product-add-unit .minus, .cart-component .product-qty-actions .plus, .cart-component .product-qty-actions .minus", function () { Repsol.Analytics.Store.clickModifyCart($(this)); }) $(document).on("click", ".product-detail-component .js-waiting-list", function () { const $this = $(this); var params = { element_type: 'button', event_detail: $this.closest('.product-detail-component').find('.product-detail__title').length > 0 ? $this.closest('.product-detail-card').find('.product-detail__title')[0].innerText.trim() : undefined, }; Repsol.Analytics.Store.clickSoldOutWaitingListBtn($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), params); }); $(document).on("click", "#soldOutWaitingListModal [data-dismiss='modal']", function () { const $this = $(this); var params = { element_type: $this.attr('data-elemet-type') ? $this.attr('data-elemet-type') : 'closing blade', link_text: $.trim(Repsol.AnalyticsRomProd.Getters.getFreeSpaceText($this.text())) ? $.trim(Repsol.AnalyticsRomProd.Getters.getFreeSpaceText($this.text())) : 'x', } Repsol.Analytics.Store.clickClose($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), params); }); $(document).on("change", "#soldOutWaitingListModal .legal-container input.cmp-form-options__field--checkbox[name='accept-policy']", function () { Repsol.Analytics.Store.clickCheckbox($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), {}); }); //Repsol Klin $(document).on("click", ".product-detail-component .js-waylet-button", function () { const $this = $(this); const params = { element_type: 'button', element_description: 'open modal klin', content_name: Repsol.AnalyticsRomProd.EcommerceCart.getContentName($this) || $this.closest('.product-detail-component').find('.product-detail__title').length > 0 ? $this.closest('.product-detail-card').find('.product-detail__title')[0].innerText.trim() : undefined, event_detail: $this.closest('.product-detail-component').find('.product-detail__title').length > 0 ? $this.closest('.product-detail-card').find('.product-detail__title')[0].innerText.trim() : undefined, }; Repsol.Analytics.Store.clickInteractionKlin($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), params); }) $(document).on("click", ".product-detail-component .modal-klin__wayletbtn-already .rp-btn", function () { const params = { link_type: 'internal', content_name: 'Para completar tu suscripcion, necesitar tener la app Waylet.', component_name: 'popup', }; Repsol.Analytics.Store.linkClikKlin($(this),params); Repsol.AnalyticsRomProd.linkClickRomProd($(this),params); }) $(document).on("click", ".product-detail-component .klin-button-dw", function () { const $this = $(this); const params = { link_type: 'internal', content_name: 'Para completar tu suscripcion, necesitar tener la app Waylet.', component_name: 'popup', link_text: $this.hasClass('button-google') ? 'google play' : 'app store', }; Repsol.Analytics.Store.linkClikKlin($(this),params); Repsol.AnalyticsRomProd.linkClickRomProd($(this),params); }) //Click installation price modal of electric chargers in product detail $(document).on("click", ".charger-card-distributive-component .charger-card-distributive__top-text button", function () { Repsol.Analytics.Store.clickInteraction($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), {}); }); //Open price modal of electric chargers in product detail $("#chargerCardsDitributiveModal").on('shown.bs.modal', function (e) { Repsol.Analytics.Store.viewPopUpV2($(this)); var params ={ component_name : Repsol.Analytics.getComponentParentLink($(this).closest('[data-component]')) != null ? Repsol.Analytics.getComponentParentLink($(this).closest('[data-component]')) : Repsol.Analytics.getComponentParentLink($(this)), content_name : Repsol.Analytics.Store.getContentName($(this)) }; Repsol.AnalyticsRomProd.viewElementRomProd($(this), params); }) $(document).on("click", "#chargerCardsDitributiveModal .js-close-modal, #chargerCardsDitributiveModal .modal-header .close", function () { const $this = $(this); var params = { component_name: Repsol.AnalyticsRomProd.Getters.getComponentParentLink($this.closest('[data-component]')) != null ? Repsol.AnalyticsRomProd.Getters.getComponentParentLink($this.closest('[data-component]')) : Repsol.AnalyticsRomProd.Getters.getComponentParentLink($this), component_position: 'popup', link_text: $this.attr("data-text") ? $.trim(Repsol.AnalyticsRomProd.Getters.getFreeSpaceText($this.attr("data-text"))) : $.trim(Repsol.AnalyticsRomProd.Getters.getFreeSpaceText($this.text())), }; Repsol.Analytics.Store.closePopUp2($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), params); }); //Click icon cart overlay $(document).on("click", ".header-ecom-top .header-store .minicart .icon-rp", function () { Repsol.Analytics.Store.clickStoreMiniCartIcon($(this)); var params= { link_url: document.querySelector('.store-minicart-component').getAttribute('data-cart-page') || undefined, link_text: 'Carrito', menu_name: 'header', link_domain: window.location.hostname }; Repsol.AnalyticsRomProd.menuClickRomProd2024($(this), params); }); $(document).on("mouseenter", ".header-ecom-top .header-store .minicart .icon-rp", function () { Repsol.Analytics.Store.hoverStoreMiniCart($(this)); var params= { link_url: document.querySelector('.store-minicart-component').getAttribute('data-cart-page') || undefined, link_text: 'Carrito', menu_name: 'header' , link_domain: window.location.hostname }; Repsol.AnalyticsRomProd.menuViewRomProd2024($(this), params); }); $(document).on("click", ".store-minicart-component .minicart-footer .rp-link-click", function () { if($(this).closest(".js-show-login").length == 0){ Repsol.Analytics.Store.clickBtnStoreCart($(this)); Repsol.AnalyticsRomProd.linkClickRomProd($(this), {}); } }); $(document).on("click", ".minicart-empty .minicart-footer-buttons .js-show-login", function () { let btn = $(this).find(".rp-btn"); Repsol.Analytics.Store.clickShortBtnStoreCart(btn); Repsol.AnalyticsRomProd.clickInteractionRomProd(btn, {}); }); $(document).on("click", "#registerAuxMsgModal .modal-header .js-close-modal, #storeServiceActivationAuxMsgModal .modal-header .js-close-modal", function () { const $this = $(this); var params = { element_type: $this.attr('data-elemet-type') ? $this.attr('data-elemet-type') : 'closing blade', link_text: $.trim(Repsol.AnalyticsRomProd.Getters.getFreeSpaceText($this.text())) ? $.trim(Repsol.AnalyticsRomProd.Getters.getFreeSpaceText($this.text())) : 'x', } Repsol.Analytics.Store.clickClose($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), params); }); $(document).on("click", "#registerAuxMsgModal .rp-link-click:not([href^='tel']):not([href^='mailto']), #storeServiceActivationAuxMsgModal .rp-link-click:not([href^='tel']):not([href^='mailto'])", function () { Repsol.Analytics.Store.clickBtn($(this)); let obj=$(this); if(obj.hasClass('product-list__filters-category-link') || obj.hasClass('product-list__filters-category-sub-list-link') || obj.hasClass('product-list__filters-category-sub-list-2-link') || obj.hasClass('product-list__category-link') || obj.hasClass('product-list__category-sub-list-link')){ var params = { component_name: 'menú lateral' }; Repsol.AnalyticsRomProd.menuClickRomProd2024(obj, params); } else{ Repsol.AnalyticsRomProd.linkClickRomProd($(this), {}); } }); $(document).on("show.bs.modal", "#registerLoginModal", function (e) { let $target = $(e.target); if($target.hasClass('register-login-modal-component')) { let text = $(this).find('.cmp-tabs__tab--active').text(); var tabType = undefined if (text.indexOf("cuenta") != -1) { tabType = "register" //Repsol.Analytics.Store.clickOpenRegister(tabType); } } }) $(document).on("click", "#registerLoginModal .cmp-tabs__tablist .cmp-tabs__tab", function (ev) { let $delegateTarget = ev.delegateTarget && ev.delegateTarget.activeElement ? $(ev.delegateTarget.activeElement) : $(this); if($delegateTarget.get(0) == $(this).get(0)){ var text = $(this).html(); var tabType = undefined if (text.indexOf("cuenta") != -1) { tabType = "register"; //Repsol.Analytics.Store.clickOpenRegister(tabType); } else { tabType = "login" } Repsol.Analytics.Store.clickLoginRegisterTab($(this), tabType); } }) $(document).on("click", ".js-send-register-form, .login-form .button-input .rp-btn", function () { Repsol.Analytics.Store.clickBtn($(this)); let obj=$(this); if(obj.hasClass('product-list__filters-category-link') || obj.hasClass('product-list__filters-category-sub-list-link') || obj.hasClass('product-list__filters-category-sub-list-2-link') || obj.hasClass('product-list__category-link') || obj.hasClass('product-list__category-sub-list-link')){ var params = { component_name: 'menú lateral' }; Repsol.AnalyticsRomProd.menuClickRomProd2024(obj, params); } else{ Repsol.AnalyticsRomProd.linkClickRomProd($(this), {}); } }); $(document).on("show.bs.modal", "#cifRegisterModal", function (e) { const $this = $(this); var params = { content_name: Repsol.AnalyticsRomProd.EcommerceCart.getContentName($this), }; Repsol.Analytics.Store.viewPopUp($(this)); Repsol.AnalyticsRomProd.viewElementRomProd($(this), params); }) $(document).on("click", "#cifRegisterModal .js-close-modal", function (e) { const $this = $(this); var params = { component_name: Repsol.AnalyticsRomProd.Getters.getComponentLink($this), element_type: 'close', element_description: 'popup', link_text: $this.attr("data-text") ? $.trim(Repsol.AnalyticsRomProd.Getters.getFreeSpaceText($this.attr("data-text"))) : $.trim(Repsol.AnalyticsRomProd.Getters.getFreeSpaceText($this.text())), content_name: Repsol.AnalyticsRomProd.EcommerceCart.getContentName($this), }; Repsol.Analytics.Store.closePopUp($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), params); }); $(document).on("click", ".js-send-store-service-activation-btn", function () { Repsol.Analytics.Store.clickBtn($(this)); let obj=$(this); if(obj.hasClass('product-list__filters-category-link') || obj.hasClass('product-list__filters-category-sub-list-link') || obj.hasClass('product-list__filters-category-sub-list-2-link') || obj.hasClass('product-list__category-link') || obj.hasClass('product-list__category-sub-list-link')){ var params = { component_name: 'menú lateral' }; Repsol.AnalyticsRomProd.menuClickRomProd2024(obj, params); } else{ Repsol.AnalyticsRomProd.linkClickRomProd($(this), {}); } }); let $productListComponent = $(document).find(".product-list-component"); $productListComponent.on("click", ".product-list__item", (event) => { let $this = $(event.currentTarget); Repsol.Analytics.Store.setProductsStorage($this); Repsol.Analytics.Store.getProductsDataLayer(Repsol.Analytics.Store.event.selectItem, $this); }); let $relatedProductComponent = $(document).find(".related-products-component"); $relatedProductComponent.on("click", ".related-products-carousel__item", (event) => { let $this = $(event.currentTarget); Repsol.Analytics.Store.setProductsStorage($this); Repsol.Analytics.Store.getProductsDataLayer(Repsol.Analytics.Store.event.selectItem, $this); }); let $recommendedProductComponent = $(document).find(".recommended-products-component"); $recommendedProductComponent.on("click", ".recommended-products-carousel__item", (event) => { let $this = $(event.currentTarget); Repsol.Analytics.Store.setProductsStorage($this); Repsol.Analytics.Store.getProductsDataLayer(Repsol.Analytics.Store.event.selectItem, $this); }); let $checkoutComponent = $(document).find(".checkout-component"); $('.checkout-component:not(.multistep)').on("change", ".cmp-form-options__field[data-name='shipping-method']", (event) => { let $this = $(event.currentTarget); Repsol.Analytics.Store.getCheckoutDataLayer(Repsol.Analytics.Store.event.addShippingInfo, $this); }); $('.checkout-component:not(.multistep)').on("change", ".cmp-form-options__field[data-name='payment-method']", (event) => { let $this = $(event.currentTarget); Repsol.Analytics.Store.getCheckoutDataLayer(Repsol.Analytics.Store.event.addPaymentInfo, $this); }); $checkoutComponent.on("click", ".js-order-btn", function () { Repsol.Analytics.Store.clickBtn($(this)); let obj=$(this); if(obj.hasClass('product-list__filters-category-link') || obj.hasClass('product-list__filters-category-sub-list-link') || obj.hasClass('product-list__filters-category-sub-list-2-link') || obj.hasClass('product-list__category-link') || obj.hasClass('product-list__category-sub-list-link')){ var params = { component_name: 'menú lateral' }; Repsol.AnalyticsRomProd.menuClickRomProd2024(obj, params); } else{ Repsol.AnalyticsRomProd.linkClickRomProd($(this), {}); } }); $checkoutComponent.on("click", ".js-apply-coupon", function () { Repsol.Analytics.Store.clickShortBtn($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), {}); }); let $storeCardsDistributiveComponent = $(document).find(".distributive-store-cards-component"); $storeCardsDistributiveComponent.on("click", ".product-grid__item, .carousel__item ", (event) => { let $this = $(event.currentTarget); Repsol.Analytics.Store.setProductsStorage($this); Repsol.Analytics.Store.getProductsDataLayer(Repsol.Analytics.Store.event.selectItem, $this); }); $(document).on("change", ".store-service-activation-form .privacy-policy-content input.cmp-form-options__field--checkbox", function () { Repsol.Analytics.Store.clickCheckbox($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), {}); }); $(document).on("click", ".store-service-activation-form .activation-dropdown-toggle", function () { Repsol.Analytics.Store.clickDropDown($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), {}); }); $(document).on("click", ".cmp-form-options__field-label--cf, .rp-arrow", function () { const $this = $(this); let elementType; let textDefault; if ($this.closest('.coupon-fieldset').find('.icon-rp-Arrow_up').length > 0 || $this.closest('.total-mobile').find('.icon-rp-Arrow_down').length > 0) { elementType = 'drop-down close' textDefault = 'Close' } else if($this.closest('.coupon-fieldset').find('.icon-rp-Arrow_down').length > 0 || $this.closest('.total-mobile').find('.icon-rp-Arrow_up').length > 0) { elementType = 'drop-down open' textDefault = 'Open' } var params = { element_type: elementType, link_text: $this.text() !== "" ? $.trim(Repsol.AnalyticsRomProd.Getters.getFreeSpaceText($this.text())) : $this.parent().find('label').text() || textDefault, }; const $element = $('.cmp-form-options__field-label--cf, .rp-arrow'); const $container = $element.closest('article.card-ecommerce.card-es-info.link-fragment[data-component="links-fragment"]'); if ($container.length == 0) { Repsol.Analytics.Store.clickDropDownStoreCart($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), params); } }); $(document).on("click", "article.card-ecommerce.card-es-info.link-fragment .list-link a span, article.card-ecommerce.card-es-info.link-fragment .link a.rp-link-click", function () { const $clickedLink = $(this).closest("a"); const aHref = $clickedLink.attr("href"); const $article = $clickedLink.closest("article.card-ecommerce.card-es-info.link-fragment"); const $paragraph = $article.find(".rp-title-1 .rp-title p").text().trim(); const spanText = $(this).is(".list-link a span") ? $clickedLink.find("span").first().text().trim() : "Ver todo"; var paramsLinkFrag = { event: 'link_click', component_catalogue: Repsol.AnalyticsRomProd.Getters.getComponentCatalog($(this)) || undefined, component_description: Repsol.AnalyticsRomProd.Getters.getComponentDesc($(this)) || undefined, component_name: $paragraph || Repsol.AnalyticsRomProd.Getters.getContentName($(this)) || undefined, component_position: Repsol.AnalyticsRomProd.Getters.getComponentPosition($(this)) || undefined, content_name: Repsol.AnalyticsRomProd.Getters.getContentName($(this)) || undefined, link_domain: Repsol.AnalyticsRomProd.Getters.getDomineLink($(this)) || undefined, link_is_cta: $(this).attr("data-cta") || 'false', link_text: spanText || Repsol.AnalyticsRomProd.Getters.getTextLink($(this)) || undefined, link_type: Repsol.AnalyticsRomProd.Getters.getTypeLink($clickedLink) || Repsol.AnalyticsRomProd.Getters.getTypeLink($(this)) || undefined, link_url: aHref || $(this).attr("href") || undefined, event_detail: Repsol.AnalyticsRomProd.Getters.getEventDetail($(this)) || undefined }; Repsol.Analytics.Store.linkClickCopyRom($(this), paramsLinkFrag); Repsol.AnalyticsRomProd.linkClickRomProd($(this), paramsLinkFrag); }); $(document).on("click", ".js-apply-coupon", function () { Repsol.Analytics.Store.clickShortBtnStoreCart($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), {}); }); $(document).on("click", ".cart-go-back, .cart-order-btn", function (event) { Repsol.Analytics.Store.clickBtnStoreCart($(this)); const $this = $(this); var params = { link_url: $this.attr("href") ? $this.attr("href") : $this.find('a').attr("href") || undefined, }; Repsol.AnalyticsRomProd.linkClickRomProd($(this), params); }); $(document).on("click", ".store-service-activation-form .activation-policy-info a, .store-service-activation-form .privacy-policy-content .rp-input-repsol a", function () { Repsol.Analytics.Store.clickBtn($(this)); let obj=$(this); if(obj.hasClass('product-list__filters-category-link') || obj.hasClass('product-list__filters-category-sub-list-link') || obj.hasClass('product-list__filters-category-sub-list-2-link') || obj.hasClass('product-list__category-link') || obj.hasClass('product-list__category-sub-list-link')){ var params = { component_name: 'menú lateral' }; Repsol.AnalyticsRomProd.menuClickRomProd2024(obj, params); } else{ Repsol.AnalyticsRomProd.linkClickRomProd($(this), {}); } }); $('.checkout-component:not(.multistep)').on("change", ".legal-container input.cmp-form-options__field--checkbox[name='accept-policy']", function () { const $this = $(this); var params = { element_type: 'checkbox', link_text: Repsol.AnalyticsRomProd.Getters.getCheckboxText($this), }; Repsol.Analytics.Store.clickCheckbox($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), params); }); $('.checkout-component.multistep').on("change", ".legal-container input.cmp-form-options__field--checkbox[name='accept-policy']", function () { const $this = $(this); var params = { element_type: 'checkbox', link_text: Repsol.AnalyticsRomProd.Getters.getCheckboxText($this), }; Repsol.Analytics.Store.clickCheckoutCheckboxPolicy($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), params); }); $(document).on("click", ".checkout .legal-container .lopd-tooltip .lopd-xf .js-modal-policies", function () { Repsol.Analytics.Store.clickCheckoutOrderBtn($(this)); const params = { link_text: $(this).parents(':eq(2)').find('.js-modal-policies').text(), component_name: $(this).parents("[data-component]").length > 0 ? $(this).parents("[data-component]").attr("data-component") : Repsol.AnalyticsRomProd.Getters.getComponentLink($(this)) } Repsol.AnalyticsRomProd.linkClickRomProd($(this), params); }); $(document).on("click", ".checkout .checkout-edit-btn", function () { Repsol.Analytics.Store.clickShortBtn($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), {}); }); $(document).on("click", ".checkout .js-next-step", function () { Repsol.Analytics.Store.clickBtn($(this)); Repsol.AnalyticsRomProd.linkClickRomProd($(this), {}); }); $(document).on("click", ".checkout input.cmp-form-options__field--radio[name='payment-method']", function () { const $this = $(this); var params = { element_type: 'button', link_text: $this.parents(':eq(2)').find('.cmp-form-options__field-description .rp-body-1').text(), }; Repsol.Analytics.Store.clickCheckoutPaymentMethod($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), params); }); $(document).on("click", ".store-access-component .store-access-list-item a", function () { Repsol.Analytics.Store.clickBtn($(this)); let obj=$(this); if(obj.hasClass('product-list__filters-category-link') || obj.hasClass('product-list__filters-category-sub-list-link') || obj.hasClass('product-list__filters-category-sub-list-2-link') || obj.hasClass('product-list__category-link') || obj.hasClass('product-list__category-sub-list-link')){ var params = { component_name: 'menú lateral' }; Repsol.AnalyticsRomProd.menuClickRomProd2024(obj, params); } else{ Repsol.AnalyticsRomProd.linkClickRomProd($(this), {}); } }); $(document).on("click", ".checkout-component .product-item__delete", function () { let item = $(this).closest('.product-item') Repsol.Analytics.Store.clickModifyCart($(this)); Repsol.Analytics.Store.getProductsDataLayer(Repsol.Analytics.Store.event.removeFromCart, item); }) $(document).on("click", ".store-catalog-page .breadcrumb .cmp-breadcrumb__item a", function () { Repsol.Analytics.Store.clickBtn($(this)); let obj=$(this); if(obj.hasClass('product-list__filters-category-link') || obj.hasClass('product-list__filters-category-sub-list-link') || obj.hasClass('product-list__filters-category-sub-list-2-link') || obj.hasClass('product-list__category-link') || obj.hasClass('product-list__category-sub-list-link')){ var params = { component_name: 'menú lateral' }; Repsol.AnalyticsRomProd.menuClickRomProd2024(obj, params); } else{ Repsol.AnalyticsRomProd.linkClickRomProd($(this), {}); } }) $(document).on("click", ".cart-component .product-delete-btn", function () { let item = $(this).closest('.cart-product') Repsol.Analytics.Store.clickModifyCart($(this)); Repsol.Analytics.Store.getProductsDataLayer(Repsol.Analytics.Store.event.removeAllFromCart, item); }) let $crosssellProductComponent = $(document).find(".cross-sell-products-component"); $crosssellProductComponent.on("click", ".product-card__detail", (event) => { let $this = $(event.currentTarget); let $product = $this.closest('.cross_sell-product__card'); let $componentName = $this.closest('.cross-sell-products-component').data('component'); sessionStorage.setItem('cross-sell-component-name', $componentName); Repsol.Analytics.Store.setProductsStorage($product); Repsol.Analytics.Store.getProductsDataLayer(Repsol.Analytics.Store.event.selectItem, $product); }) $(document).on("change", ".product-review-form-component .cmp-form-options__field--checkbox", function () { Repsol.Analytics.Store.clickCheckbox($(this)); Repsol.AnalyticsRomProd.clickInteractionRomProd($(this), {}); }); $(document).on("click", ".product-review-form-component .js-send-product-review-form", function () { Repsol.Analytics.Store.clickBtn($(this)); Repsol.AnalyticsRomProd.linkClickRomProd($(this), {}); }); let storeCardsDistributiveComponent = document.querySelectorAll(".distributive-store-cards-component"); storeCardsDistributiveComponent.forEach((distributive) => { const idTab = distributive.closest('.cmp-tabs__tabpanel')?.getAttribute('id'); const tabDistributive = document.getElementById(`${idTab}-tab`); if(tabDistributive){ tabDistributive.addEventListener("click", () =>{ RepsolDistributiveStoreCards.sendEcommerceDL($(distributive)); }) } }) let $comparativeProductsComponent = $(document).find(".comparative-products-component"); $comparativeProductsComponent.on("click", ".comparative-products-card__detail-link", (event) => { let $this = $(event.currentTarget); const $item = $this.closest(".comparative-products-card"); Repsol.Analytics.Store.setProductsStorage($item); Repsol.Analytics.Store.getProductsDataLayer(Repsol.Analytics.Store.event.selectItem, $item); }); $comparativeProductsComponent.on("click", ".comparative-products-carousel-nav .slick-arrow", (event) => { let $this = $(event.currentTarget); const params = { element_type: 'Button', link_text: $this.attr("data-text"), content_name: $this.closest(".comparative-products-component").find(".comparative-products__title .rp-title")?.text()?.trim() }; Repsol.Analytics.ES.clickInteractionV4($this, params); Repsol.AnalyticsRomProd.clickInteractionRomProd($this, params); }) }, ecommerceDataLayer: (eventType, component, items, ecommerceData) => { Repsol.Analytics.Store.resetEcommerceData(); let userIsLogged = Repsol.Analytics.Store.userIsLogged(); let componentName = undefined; for(let i = 0; i < items.length; i++){ let item = items[i]; let keys = Object.keys(item); for(let j = 0; j < keys.length; j++){ let key = keys[j]; if(item[key] === null || item[key] === "" || item[key] === "undefined"){ item[key] = undefined; } if((eventType == Repsol.Analytics.Store.event.addToCart || eventType == Repsol.Analytics.Store.event.removeFromCart) && key == 'quantity'){ item[key] = 1 } } } function getComponentFromSessionStorage() { return new Promise((resolve, reject) => { if(sessionStorage.getItem('cross-sell-component-name')) { componentName = sessionStorage.getItem('cross-sell-component-name'); resolve(componentName); } else { if(component.attr("data-component")){ componentName = component.attr("data-component"); resolve(componentName); } else if(component.closest("[data-component]").length > 0){ componentName = component.closest("[data-component]").attr("data-component"); resolve(componentName); } else { reject(); } } }) } if(component.attr("data-component")){ componentName = component.attr("data-component"); }else if(component.closest("[data-component]").length > 0){ componentName = component.closest("[data-component]").attr("data-component"); } if(eventType == Repsol.Analytics.Store.event.viewItem) { getComponentFromSessionStorage() .then(result => { componentName = result; sessionStorage.removeItem('cross-sell-component-name'); }) .catch(() => { }) } if(eventType == Repsol.Analytics.Store.event.removeAllFromCart){ eventType = Repsol.Analytics.Store.event.removeFromCart } let userId = undefined; if( userIsLogged == "true" && userIsLogged != null ){ var data = Repsol.Analytics.getAccountInfoDL(); if(data && data.user && data.user != ''){ userId = data.user; } } let jsonInfo = { "event": eventType, //"user_is_logged": userIsLogged, "user_id": userId, "component_name": componentName, "ecommerce": { "items": items }, "business": Repsol.Analytics.ES.getBusinessMeta() }; let ecommerceDataKeys = Object.keys(ecommerceData); for(let i = 0; i < ecommerceDataKeys.length; i++){ let key = ecommerceDataKeys[i]; if(ecommerceData[key] == null || ecommerceData[key] == "" || ecommerceData[key] == "undefined"){ ecommerceData[key] = undefined; } if(eventType == Repsol.Analytics.Store.event.beginCheckout || eventType == Repsol.Analytics.Store.event.addShippingInfo || eventType == Repsol.Analytics.Store.event.addPaymentInfo || eventType == Repsol.Analytics.Store.event.purchase) { jsonInfo.ecommerce[key] = ecommerceData[key] } else { jsonInfo[key] = ecommerceData[key] } } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, getProductsDataLayer: (eventType, component) =>{ let items = Repsol.Analytics.Store.getProductData(component); Repsol.Analytics.Store.ecommerceDataLayer(eventType, component, items, {}); }, getCheckoutDataLayer: (eventType, component) => { if(eventType == Repsol.Analytics.Store.event.purchase){ let data = JSON.parse(sessionStorage.getItem("user")); var coupon = data && data.coupon ? data.coupon : undefined, transaction_id = data && data.order ? data.order : undefined, currency = data && data.currency ? data.currency : undefined, value = data && data.totalValue ? parseFloat(data.totalValue) : undefined, affilation = data && data.affilation ? data.affilation : undefined, shippingTier = data && data.shippingMethod ? data.shippingMethod : undefined, paymentType = data && data.paymentMethod ? data.paymentMethod : undefined, business = Repsol.Analytics.ES.getBusinessMeta(); shippingCosts = data && data.shippingCosts ? data.shippingCosts : undefined; var items = data.products ? data.products : []; }else{ let $orderInfo = $(".checkout-component").find('.checkout-order-box.main'); var items = Repsol.Analytics.Store.getProductData($orderInfo); var coupon = $orderInfo.find("[data-coupon]") ? $orderInfo.find("[data-coupon]").attr("data-coupon") : undefined, currency = $orderInfo.find("[data-currency]") ? $orderInfo.find("[data-currency]").attr("data-currency") : undefined, value = $orderInfo.find("[data-total-value]") ? parseFloat($orderInfo.find("[data-total-value]").attr("data-total-value")) : undefined; var $description = component.closest('.cmp-form-options').find('.cmp-form-options__field-description > span'); business = Repsol.Analytics.ES.getBusinessMeta(); } let ecommerceData = { "currency": currency, "value": value, } switch (eventType){ case Repsol.Analytics.Store.event.addShippingInfo: ecommerceData["shipping_tier"] = component.hasClass('shipping-free-shipping') ? component.attr('data-carrier-title') : ($description ? $description.text().trim() : undefined); break case Repsol.Analytics.Store.event.addPaymentInfo: ecommerceData["payment_type"] = $description ? $description.text().trim() : undefined break case Repsol.Analytics.Store.event.purchase: ecommerceData["shipping_tier"] = shippingTier ecommerceData["shipping"] = shippingCosts ecommerceData["payment_type"] = paymentType ecommerceData["transaction_id"] = transaction_id break } Repsol.Analytics.Store.ecommerceDataLayer(eventType, component, items, ecommerceData); }, getCartStoreDataLayer: (eventType, component) => { let coupon = $(document).find(".cart-component").attr('data-coupon'); let currency = $(document).find(".cart-component").attr('data-currency'); let value = $(document).find(".cart-component").attr('data-value'); let items = Repsol.Analytics.Store.getProductData(component); let ecommerceData = { "coupon" : coupon, "currency" : currency, "value" : value } Repsol.Analytics.Store.ecommerceDataLayer(eventType, component, items, ecommerceData); }, resetEcommerceData: () => { let jsonInfo = { ecommerce: null } Repsol.Analytics.Store.sendDataLayer(jsonInfo); }, userIsLogged: () => { let isLogged = Repsol.utils.getCookie("isLogged"); if( isLogged === "true" ){ return true; }else{ return false; } }, getProductData: function(component){ const eventType = component.attr("data-event"); let products = component.find(".js-analytics-store"); let productsArray = []; products.each(function(){ let $this = $(this); let $product = $this.find(".js-analytics-store-product"); let $componentParent = $this.closest("[data-component]"); let componentName = ''; let itemId = $product.attr("data-id"), itemName = $product.attr("data-name"), itemCategory = $product.attr("data-category"), itemBrand = $product.attr("data-brand"), price = $product.attr("data-price"), itemVariant = $product.attr("data-variant"), indexList = $this.parent("[data-list-index]").length > 0 ? $this.parent("[data-list-index]").attr("data-list-index") : "", quantity = $product.attr("data-quantity"), affiliate = Repsol.Analytics.ES.getBusinessMeta(), itemImage = $product.attr("data-image"), itemDescription = $product.attr("data-description"), itemDiscount = $product.attr("data-discount"), itemSku = $product.attr("data-sku"), itemListName = $product.attr("data-list-name"), itemSalableQuantity = $product.attr("data-salable-quantity"), itemCurrency = $product.attr("data-currency") itemCoupon = $product.attr("data-coupon"); if(sessionStorage.getItem('cross-sell-component-name')) { componentName = sessionStorage.getItem('cross-sell-component-name'); } else { componentName = $componentParent.length > 0 ? $componentParent.attr("data-component") : ""; } if( !isNaN(parseInt(indexList)) ){ indexList = parseInt(indexList) + 1; } if( !isNaN(parseInt(quantity)) ){ quantity = parseInt(quantity); }else{ quantity = ''; } let item = { "item_id" : itemId, "item_name" : itemName, "item_brand": itemBrand, "price" : parseFloat(price), "item_variant": itemVariant, "item_list_name": itemListName?.trim(), "index" : indexList, "quantity" : quantity, "affiliation": affiliate, "discount": itemDiscount ? parseFloat(itemDiscount) : 0, "product_sku": itemSku } const categories = itemCategory ? itemCategory.split(',') : []; const defaultCategory = '2_Default Category'; const filteredCategories = categories.filter(category => category != defaultCategory); const totalCategories = categories.length != filteredCategories.length ? categories.length : filteredCategories.length; if(filteredCategories.length > 0){ for(let i = 0; i < totalCategories; i++){ const category = filteredCategories[i] ?? ''; if(i == 0){ item["item_category"] = category }else{ item[`item_category${i + 1}`] = category } } }else{ item["item_category"] = ''; item["item_category2"] = ''; } switch(eventType){ case Repsol.Analytics.Store.event.addToCart: item["image_path"] = itemImage ? itemImage : undefined; item["product_description"] = itemDescription ? itemDescription : undefined; break; case Repsol.Analytics.Store.event.viewItem: case Repsol.Analytics.Store.event.viewCart: item["product_status"] = Repsol.Analytics.Store.getProductStatus(itemSalableQuantity); break; case Repsol.Analytics.Store.event.beginCheckout: case Repsol.Analytics.Store.event.addShippingInfo: case Repsol.Analytics.Store.event.addPaymentInfo: case Repsol.Analytics.Store.event.purchase: item["currency"] = itemCurrency ? itemCurrency : ''; item["coupon"] = itemCoupon ? itemCoupon : ''; break; } productsArray.push(item); }); return productsArray; }, getCategory: function () { let breadCrumbList = $(".breadcrumb .cmp-breadcrumb__list").find("li"); let categoryList = []; for (let i = 0; i < breadCrumbList.length; i++) { if ($(breadCrumbList[i]).text() !== "...") { categoryList.push($(breadCrumbList[i]).text().trim()); } } return categoryList; }, clickFilter: function (obj) { var jsonInfo = { event: 'interaction', element_type: 'filter list', link_text: $.trim(Repsol.Analytics.getFreeSpaceText(obj.text())), filter_detail_category: obj.find("input").attr("data-parent"), component_position: undefined, component_name: Repsol.Analytics.getComponentLink(obj) } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, clickCleanFilter: function (obj) { var jsonInfo = { event: 'interaction', element_type: 'filter erase', link_text: $.trim(Repsol.Analytics.getFreeSpaceText(obj.text())), component_position: undefined, component_name: Repsol.Analytics.getComponentLink(obj) } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, clickFilterDropdown: function (obj) { var jsonInfo = { event: 'interaction', element_type: 'filter dropdown', link_text: $.trim(Repsol.Analytics.getFreeSpaceText(obj.text())), component_position: undefined, component_name: Repsol.Analytics.getComponentLink(obj) } Repsol.Analytics.setInfoClick(jsonInfo); }, clickFilterOrder: function (obj) { var jsonInfo = { event: 'interaction', element_type: 'filter order', link_text: obj.attr("data-sort-order") == "asc" ? "up" : "down", component_position: undefined, component_name: Repsol.Analytics.getComponentLink(obj) } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, clickPaginationNumber: function (obj) { var jsonInfo = { event: 'interaction', element_type: 'page number', link_text: $.trim(Repsol.Analytics.getFreeSpaceText(obj.text())), component_name: Repsol.Analytics.getComponentLink(obj) } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, clickPaginationArrow: function (obj) { var jsonInfo = { event: 'interaction', element_type: 'prev', link_text: obj.attr("data-text"), component_name: Repsol.Analytics.getComponentLink(obj) } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, clickDetailInfo: function (obj) { $this = obj.find('.cmp-accordion__title h3') var jsonInfo = { event: 'interaction', element_type: 'drop-down', link_text: $.trim(Repsol.Analytics.getFreeSpaceText(obj.find('.cmp-accordion__title').text())), component_position: undefined, component_name: Repsol.Analytics.getComponentLink(obj) } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, clickDownloadInfo: function (obj) { $this = obj.find('span') var jsonInfo = { event: 'file_download', file_name: Repsol.Analytics.Store.getFileName(obj.attr("href")), link_domain: Repsol.Analytics.getDomineLink(obj), link_text: $.trim(Repsol.Analytics.getFreeSpaceText($this.text())), link_url: obj.attr("href") || '', component_position: undefined, component_name: Repsol.Analytics.getComponentLink(obj) } Repsol.Analytics.Store.sendDataLayer(jsonInfo); }, clickModifyCart: function (obj) { var link_text = undefined; if(obj.find("[class*='icon-rp']").length > 0 && obj.find("[class*='icon-rp']").attr('data-text')){ link_text = obj.find("[class*='icon-rp']").attr('data-text'); }else if (obj.find(".icon-rp-Plus").length > 0) { link_text = "+"; } else if (obj.find(".icon-rp-Minus").length > 0) { link_text = "-"; } else if (obj.find(".icon-rp-Delete").length > 0) { link_text = "Eliminar"; } var jsonInfo = { event: 'interaction', element_type: 'button', link_text: link_text, component_name: Repsol.Analytics.getComponentParentLink(obj) != null ? Repsol.Analytics.getComponentParentLink(obj) : undefined } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, clickClose: function (obj) { var jsonInfo = { event: 'interaction', element_type: obj.attr('data-elemet-type') ? obj.attr('data-elemet-type') : 'closing blade', link_text: $.trim(Repsol.Analytics.getFreeSpaceText(obj.text())) ? $.trim(Repsol.Analytics.getFreeSpaceText(obj.text())) : 'x', component_position: undefined, component_name: Repsol.Analytics.getComponentParentLink(obj) != null ? Repsol.Analytics.getComponentParentLink(obj) : undefined } Repsol.Analytics.setInfoClick(jsonInfo); }, clickOpenCart: function (obj) { var jsonInfo = { event: 'interaction', element_type: 'floating cart', link_text: 'cart icon', component_position: undefined, component_name: Repsol.Analytics.getComponentLink(obj) } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, openModalLogin: function (obj) { var jsonInfo = { event: 'account_login', funnel_type: 'login', funnel_action: 'login_form', funnel_step: '01', method: 'password', component_position: undefined, component_name: 'card de login', account_action: 'funnel', service: 'tienda' }; Repsol.Analytics.setInfoClick(jsonInfo); }, clickOpenRegister: function (tab) { var jsonInfo = { event: tab == "register" ? 'account_register' : 'account_login', funnel_type: tab == "register" ? 'register_long' : 'login', funnel_action: tab == "register" ? 'create_account_form' : 'login_form', funnel_step: '01', method: 'password', component_position: undefined, component_name: 'card de login', account_action: 'funnel', service: 'tienda' } if(tab == 'register'){ jsonInfo.loyalty_cesion = $('.register-form').find("input[name='policy-cesion-consent']").length > 0 ? ($('.register-form').find("input[name='policy-cesion-consent']").is(':checked') ? 'true' : 'false') : undefined jsonInfo.loyalty_cesion_terceros = $('.register-form').find("input[name='policy-cesion-third-consent']").length > 0 ? ($('.register-form').find("input[name='policy-cesion-third-consent']").is(':checked') ? 'true' : 'false') : undefined } Repsol.Analytics.setInfoClick(jsonInfo); }, clickProductListSortOrder: function(obj) { let linkText = obj.text() let jsonInfo = { event: 'interaction', element_type: 'filter dropdown', link_text: linkText, component_position: undefined, component_name: Repsol.Analytics.getComponentLink(obj) } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, clickLoginRegisterTab: function (obj, tab){ var jsonInfo= { event: 'interaction', link_text: obj.attr("data-text") ? Repsol.Analytics.getFreeSpaceText(obj.attr("data-text")) : Repsol.Analytics.getFreeSpaceText(obj.text()), component_name: 'card de login', element_type: Repsol.Analytics.getTypeInteraction(obj) } Repsol.Analytics.setInfoClick(jsonInfo); }, clickCartClose: function(obj) { let jsonInfo = { event: 'interaction', element_type: 'closing blade', link_text: 'x', component_position: undefined, component_name: Repsol.Analytics.getComponentParentLink(obj) != null ? Repsol.Analytics.getComponentParentLink(obj) : undefined } Repsol.Analytics.Store.setInfoClick(jsonInfo) }, clickBtn: (obj) =>{ var hasFieldset; var fieldName; var isChecked; var jsonInfo= { event: 'link_click', link_domain: Repsol.Analytics.getDomineLink(obj), link_text: Repsol.Analytics.getTextLink(obj), link_url: obj.attr("href") || undefined, outbound: Repsol.Analytics.getOutboundLink(obj), link_type: Repsol.Analytics.getTypeLink(obj), component_name: obj.parents("[data-component]").length > 0 ? obj.parents("[data-component]").attr("data-component") : Repsol.Analytics.getComponentLink(obj), component_position: undefined, link_is_cta: obj.attr("data-cta") || 'false' } if ( obj.closest('.register').length > 0 || obj.closest('.checkout').length > 0 ) { hasFieldset = obj.closest('.register, .checkout').find('.cmp-form-options'); var checkboxes = hasFieldset.find('input[type="checkbox"]'); size = 1; checkboxes.each(function() { fieldName = $(this).closest('.cmp-form-options__field-description').text().replace(/[\n\t]/g, '').trim() || $(this).closest('fieldset').find('.cmp-form-options__field-description').text().replace(/[\n\t]/g, '').trim(); jsonInfo['field_name_' + (size)] = fieldName, isChecked = $(this).prop('checked') ? 'true' : 'false'; jsonInfo['selected_option_' + (size)] = isChecked; size ++; }); for (var i = size; i <= 4; i++) { jsonInfo['field_name_' + (i)] = undefined; jsonInfo['selected_option_' + (i)] = undefined; } } else { var jsonInfo= { event: 'link_click', link_domain: Repsol.Analytics.getDomineLink(obj), link_text: Repsol.Analytics.getTextLink(obj), link_url: obj.attr("href") || undefined, outbound: Repsol.Analytics.getOutboundLink(obj), link_type: Repsol.Analytics.getTypeLink(obj), component_name: obj.parents("[data-component]").length > 0 ? obj.parents("[data-component]").attr("data-component") : Repsol.Analytics.getComponentLink(obj), component_position: undefined, link_is_cta: obj.attr("data-cta") || 'false' } } if(obj.hasClass('product-list__filters-category-link') || obj.hasClass('product-list__filters-category-sub-list-link') || obj.hasClass('product-list__filters-category-sub-list-2-link') || obj.hasClass('product-list__category-link') || obj.hasClass('product-list__category-sub-list-link')){ jsonInfo.event = 'menu_click'; jsonInfo.component_name = 'menú lateral'; jsonInfo.page_language = Repsol.Analytics.getLanguage(); jsonInfo.menu_main_name = Repsol.Analytics.Store.setMainName(); jsonInfo.services_available = undefined; jsonInfo.services_available_quantity = undefined; jsonInfo.page_real_url = window.location.href; Repsol.Analytics.Store.setInfoServices(jsonInfo); delete jsonInfo.link_is_cta; } if(obj.hasClass('product-list__filters-category-link') || obj.hasClass('product-list__category-link')){ jsonInfo.menú_name = 'secondary'; jsonInfo.menu_secondary_name = obj.text(); jsonInfo.menu_tertiary_name = undefined; } if(obj.hasClass('product-list__filters-category-sub-list-link') || obj.hasClass('product-list__filters-category-sub-list-2-link') || obj.hasClass('product-list__category-sub-list-link')){ let menuSecondaryName = ''; if(obj.closest(".product-list__filters-category-item").length > 0){ menuSecondaryName = obj.closest(".product-list__filters-category-item").find(".product-list__filters-category-link:first").text().length ? obj.closest(".product-list__filters-category-item").find(".product-list__filters-category-link:first").text() : undefined; }else{ menuSecondaryName = obj.closest(".product-list__category-item").find(".product-list__category-link:first").text().length ? obj.closest(".product-list__category-item").find(".product-list__category-link:first").text() : undefined } jsonInfo.menú_name = 'tertiary'; jsonInfo.menu_secondary_name = menuSecondaryName; jsonInfo.menu_tertiary_name = obj.text(); } if(obj.hasClass('product-list__filters-category-link') || obj.hasClass('product-list__filters-category-sub-list-link') || obj.hasClass('product-list__filters-category-sub-list-2-link') || obj.hasClass('product-list__category-link') || obj.hasClass('product-list__category-sub-list-link')){ delete jsonInfo.component_position; Repsol.Analytics.Store.sendDataLayer(jsonInfo); } else{ Repsol.Analytics.Store.setInfoClick(jsonInfo); } }, clickBtnManualCard: (obj) =>{ var jsonInfo= { event: 'link_click', link_domain: Repsol.Analytics.getDomineLink(obj), link_text: Repsol.Analytics.getTextLink(obj.find('.rp-small-button')), link_url: obj.attr("href") || undefined, outbound: Repsol.Analytics.getOutboundLink(obj), link_type: Repsol.Analytics.getTypeLink(obj), component_name: obj.parents("[data-component]").length > 0 ? obj.parents("[data-component]").attr("data-component") : Repsol.Analytics.getComponentLink(obj), link_is_cta: obj.attr("data-cta") || 'false' } Repsol.Analytics.Store.sendDataLayer(jsonInfo); }, clickBtnStoreCart: (obj) =>{ var jsonInfo= { event: 'link_click', link_domain: Repsol.Analytics.getDomineLink(obj), link_text: Repsol.Analytics.getTextLink(obj), link_url: obj.attr("href") ? obj.attr("href") : obj.find('a').attr("href") || undefined, link_type: Repsol.Analytics.getTypeLink(obj), component_name: obj.parents("[data-component]").length > 0 ? obj.parents("[data-component]").attr("data-component") : Repsol.Analytics.getComponentLink(obj), } Repsol.Analytics.Store.sendDataLayer(jsonInfo); }, clickShortBtn: (obj) =>{ var jsonInfo= { event: 'interaction', link_text: obj.attr("data-text") ? Repsol.Analytics.getFreeSpaceText(obj.attr("data-text")) : Repsol.Analytics.getFreeSpaceText(obj.text()), component_name: obj.parents("[data-component]").length > 0 ? obj.parents("[data-component]").attr("data-component") : Repsol.Analytics.getComponentLink(obj), element_type: Repsol.Analytics.getTypeInteraction(obj), business: Repsol.Analytics.ES.getBusinessMeta() } Repsol.Analytics.Store.sendDataLayer(jsonInfo); }, clickStoreMiniCartIcon: (obj) =>{ var jsonInfo= { event: 'menu_click', link_domain: Repsol.Analytics.getDomineLink(obj), link_url: document.querySelector('.store-minicart-component').getAttribute('data-cart-page') || undefined, link_text: 'Carrito', link_type: Repsol.Analytics.getTypeLink(obj), component_name: obj.parents("[data-component]").length > 0 ? obj.parents("[data-component]").attr("data-component") : Repsol.Analytics.getComponentLink(obj), menu_name: 'header', menu_main_name: undefined, menu_secondary_name: undefined, menu_tertiary_name: undefined } Repsol.Analytics.Store.sendDataLayer(jsonInfo); }, hoverStoreMiniCart: (obj) =>{ var jsonInfo= { event: 'menu_view', link_domain: Repsol.Analytics.getDomineLink(obj), link_url: document.querySelector('.store-minicart-component').getAttribute('data-cart-page') || undefined, link_text: "Carrito", link_type: Repsol.Analytics.getTypeLink(obj), component_name: obj.parents("[data-component]").length > 0 ? obj.parents("[data-component]").attr("data-component") : Repsol.Analytics.getComponentLink(obj), menu_name: 'header', menu_main_name: undefined, menu_secondary_name: undefined, menu_tertiary_name: undefined } Repsol.Analytics.Store.sendDataLayer(jsonInfo); }, clickShortBtnStoreCart: (obj) =>{ var jsonInfo= { event: 'interaction', link_text: obj.attr("data-text") ? Repsol.Analytics.getFreeSpaceText(obj.attr("data-text")) : Repsol.Analytics.getFreeSpaceText(obj.text()), component_name: obj.parents("[data-component]").length > 0 ? obj.parents("[data-component]").attr("data-component") : Repsol.Analytics.getComponentLink(obj), element_type: Repsol.Analytics.getTypeInteraction(obj), } Repsol.Analytics.Store.sendDataLayer(jsonInfo); }, clickCheckoutOrderBtn: (obj) =>{ const jsonInfo = { event: 'link_click', link_domain: Repsol.Analytics.getDomineLink(obj), link_text: obj.parents(':eq(2)').find('.js-modal-policies').text(), link_url: obj.attr("href") || undefined, outbound: Repsol.Analytics.getOutboundLink(obj), link_type: Repsol.Analytics.getTypeLink(obj), component_name: obj.parents("[data-component]").length > 0 ? obj.parents("[data-component]").attr("data-component") : Repsol.Analytics.getComponentLink(obj), component_position: undefined, link_is_cta: obj.attr("data-cta") || 'false' } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, clickCheckoutBtn: (obj) =>{ var jsonInfo= { event: 'link_click', link_domain: Repsol.Analytics.getDomineLink(obj), link_text: Repsol.Analytics.getTextLink(obj), link_url: obj.attr("href") || undefined, component_name: obj.parents("[data-component]").length > 0 ? obj.parents("[data-component]").attr("data-component") : Repsol.Analytics.getComponentLink(obj) } Repsol.Analytics.Store.sendDataLayer(jsonInfo); }, clickCheckoutPaymentMethod: (obj) => { jsonInfo= { event: 'interaction', link_text: obj.parents(':eq(2)').find('.cmp-form-options__field-description .rp-body-1').text(), component_name: obj.parents("[data-component]").length > 0 ? obj.parents("[data-component]").attr("data-component") : Repsol.Analytics.getComponentLink(obj), element_type: 'button', business: Repsol.Analytics.ES.getBusinessMeta() } Repsol.Analytics.Store.sendDataLayer(jsonInfo); }, clickArrow: (obj) =>{ var jsonInfo= { event: 'interaction', link_text: obj.attr("data-text") ? obj.attr("data-text") : obj.text(), component_name: Repsol.Analytics.getComponentLink(obj), element_type: Repsol.Analytics.getTypeInteraction(obj) } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, storeServiceActivation: (obj) => { var jsonInfo= { event: 'account_register', funnel_type: 'register_short', funnel_action: 'create_account_form', funnel_step: '01', method : undefined, component_position: undefined, component_name: 'card de login', account_action: 'funnel', service: 'tienda', loyalty_cesion: obj.find("input[name='policy-cesion-consent']").length > 0 ? (obj.find("input[name='policy-cesion-consent']").is(':checked') ? 'true' : 'false' ) : undefined, loyalty_cesion_terceros: obj.find("input[name='policy-cesion-third-consent']").length > 0 ? (obj.find("input[name='policy-cesion-third-consent']").is(':checked') ? 'true' : 'false' ) : undefined } Repsol.Analytics.Store.setInfoClick(jsonInfo) }, clickCheckbox: function (obj) { var jsonInfo = { event: 'interaction', element_type: 'checkbox', link_text: Repsol.Analytics.getCheckboxText(obj), component_position: undefined, component_name: Repsol.Analytics.getComponentLink(obj) } Repsol.Analytics.Store.sendDataLayer(jsonInfo); }, clickCheckoutCheckboxPolicy: function (obj) { var jsonInfo = { event: 'interaction', element_type: 'button', link_text: Repsol.Analytics.getCheckboxText(obj), component_position: undefined, component_name: Repsol.Analytics.getComponentLink(obj) } Repsol.Analytics.Store.sendDataLayer(jsonInfo); }, clickDropDown: function(obj){ var jsonInfo = { event: 'interaction', element_type: 'drop-down', link_text: $.trim(Repsol.Analytics.getFreeSpaceText(obj.text())), component_position: undefined, component_name: Repsol.Analytics.getComponentLink(obj) } Repsol.Analytics.Store.sendDataLayer(jsonInfo); }, clickProductListFilter: function (obj, linkText) { let filter = $(obj).closest('.product-list__filter'); var jsonInfo = { event: 'interaction', element_type: 'filter list', link_text: linkText, filter_detail_category: $(filter).attr("data-parent"), component_name: Repsol.Analytics.getComponentLink($(obj)) } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, clickProductListClearFilters: function (obj) { let filter = $(obj).closest('.product-list__filter'); var jsonInfo = { event: 'interaction', element_type: 'filter erase', link_text: $(obj).text(), component_name: Repsol.Analytics.getComponentLink($(obj)) } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, clickProductListDropdownFilter: function (obj) { var jsonInfo = { event: 'interaction', element_type: 'filter dropdown', link_text: $(obj).find('.dropdown-toggle__text').text(), component_name: Repsol.Analytics.getComponentLink($(obj)) } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, clickProductListDropdownOrder: function (obj, linkText) { var jsonInfo = { event: 'interaction', element_type: 'filter order', link_text: linkText, component_name: Repsol.Analytics.getComponentLink($(obj)) } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, clickProductListMoreFilters: function (obj) { var jsonInfo = { event: 'interaction', element_type: 'button', link_text: $(obj).find('.text').text(), component_name: Repsol.Analytics.getComponentLink($(obj)) } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, clickProductListVehicleSearchOpenModalBtn: function (obj) { const jsonInfo = { event: 'interaction', component_name: Repsol.Analytics.getComponentLink($(obj)), component_description: undefined, element_type: 'button', element_description: 'open popup buscador vehículo', link_text: $(obj).find('.text').text(), content_name: 'Introduce tu matrícula o modelo para ver productos compatibles', user_is_subscribed: undefined, user_is_logged: Repsol.Analytics.Store.userIsLogged(), page_real_url: window.location.href, } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, clickProductListVehicleSearchPanelSelect: function (obj) { const jsonInfo = { event: 'interaction', component_name: Repsol.Analytics.getComponentLink($(obj)), component_description: undefined, element_type: 'button', element_description: 'select', link_text: $(obj).parent().parent().find('.rp-title-2').text(), content_name: undefined, user_is_subscribed: undefined, user_is_logged: Repsol.Analytics.Store.userIsLogged(), page_real_url: window.location.href, } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, clickProductListSearchVehicleBtn: function (obj) { const form = obj.closest('#lubricant-search-model'); const inputs = [...$(form).find('[data-analytic-field-name]')]; const jsonInfo = { event: 'filter', filter_section: 'buscador modelo', field_name_1: inputs[0].getAttribute('data-analytic-field-name'), field_name_2: inputs[1].getAttribute('data-analytic-field-name'), field_name_3: inputs[2].getAttribute('data-analytic-field-name'), field_name_4: inputs[3].getAttribute('data-analytic-field-name'), selected_option_1: inputs[0].querySelector('.text').textContent.replace(/\n/g, '').trim(), selected_option_2: inputs[1].querySelector('.text').textContent.replace(/\n/g, '').trim(), selected_option_3: inputs[2].querySelector('.text').textContent.replace(/\n/g, '').trim(), selected_option_4: inputs[3].querySelector('.text').textContent.replace(/\n/g, '').trim(), filter_interaction: $(obj).find('.btn-text').text().replace(/\n/g, '').trim(), filter_search_termm: undefined, component_name: Repsol.Analytics.getComponentLink($(obj)), component_description: undefined, user_is_subscribed: undefined, user_is_logged: Repsol.Analytics.Store.userIsLogged(), page_real_url: window.location.href, } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, errorProductListSearchInput: function(obj) { const analyticField = obj.getAttribute('data-analytic-field-name').toLowerCase(); const errorMessage = obj.querySelector('.error-msg-required').textContent; const errorDescription = `buscador modelo|${analyticField}|${errorMessage}`; let jsonInfo = { event: 'r_error', error_type: 'filter_error', error_description: errorDescription, user_is_subscribed: undefined, user_is_logged: Repsol.Analytics.Store.userIsLogged(), page_real_url: window.location.href } jsonInfo = {...jsonInfo,...Repsol.Analytics.Store.fillAnalyticWithUserInfo(jsonInfo)}; Repsol.Analytics.Store.setInfoClick(jsonInfo); }, clickProductListSearchEditBtn: function (obj) { const jsonInfo = { event: 'interaction', component_name: Repsol.Analytics.getComponentLink($(obj)), component_description: undefined, element_type: 'button', element_description: 'edit', link_text: 'Editar', content_name: $(obj).parents().eq(3).find('.recommendation-heading').text().replace(':', ''), user_is_subscribed: undefined, user_is_logged: Repsol.Analytics.Store.userIsLogged(), page_real_url: window.location.href, } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, clickProductListSearchRestoreBtn: function (obj) { const jsonInfo = { event: 'interaction', component_name: Repsol.Analytics.getComponentLink($(obj)), component_description: undefined, element_type: 'button', element_description: 'delete', link_text: 'Eliminar', content_name: $(obj).parents().eq(3).find('.recommendation-heading').text().replace(':', ''), user_is_subscribed: undefined, user_is_logged: Repsol.Analytics.Store.userIsLogged(), page_real_url: window.location.href, } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, clickProductListSearchByPlateBtn: function (obj) { const form = obj.closest('#lubricant-search-plate'); const inputs = [...$(form).find('[data-analytic-field-name]')]; const jsonInfo = { event: 'interaction', component_name: Repsol.Analytics.getComponentLink($(obj)), component_description: 'cargar coincidencias', element_type: 'button', element_description: 'view_results', link_text: $(obj).find('.btn-text').text().replace(/\n/g, '').trim(), content_name: undefined, user_is_subscribed: undefined, user_is_logged: Repsol.Analytics.Store.userIsLogged(), page_real_url: window.location.href, } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, //Analytic errorProductListSearchByPlateBtn: function (obj) { const parentElementError = obj.closest('.accordion-panel__content'); const errorMessage = parentElementError.querySelector('.results-without-match').textContent.trim(); const errorDescription = `buscador matrícula|vehículo|${errorMessage}`; let jsonInfo = { event: 'r_error', error_type: 'filter_error', error_description: errorDescription, user_is_subscribed: undefined, // TODO: retomar cuando este listo la newsletter user_is_logged: Repsol.Analytics.Store.userIsLogged(), page_real_url: window.location.href } jsonInfo = {...jsonInfo,...Repsol.Analytics.Store.fillAnalyticWithUserInfo(jsonInfo)}; Repsol.Analytics.Store.setInfoClick(jsonInfo); }, // Analytic 4.1.19 clickProductListSearchByPlateItem: function (obj) { const modal = obj.closest('#lurbicantSearchModal'); const panel = $(modal).find('[data-accordion-panel="plate-info"]'); const form = $(panel).find('#lubricant-search-plate'); const inputs = [...$(form).find('.rp-input-repsol')]; const jsonInfo = { event: 'filter', filter_section: 'buscador matrícula', field_name_1: $(panel).find('.rp-input-repsol .label').text().trim(), field_name_2: undefined, field_name_3: undefined, field_name_4: undefined, selected_option_1: obj.textContent.replace(/\n/g, '').trim(), selected_option_2: undefined, selected_option_3: undefined, selected_option_4: undefined, filter_interaction: 'Ver resultados', filter_search_termm: undefined, component_name: Repsol.Analytics.getComponentLink($(obj)), component_description: undefined, user_is_subscribed: undefined, user_is_logged: Repsol.Analytics.Store.userIsLogged(), page_real_url: window.location.href, } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, errorProductListSearchInputFormat: function () { const jsonInfo = { event: 'r_error', error_type: 'filter_error', error_description: 'buscador matrícula|matrícula', user_is_subscribed: undefined, user_is_logged: Repsol.Analytics.Store.userIsLogged(), page_real_url: window.location.href, } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, fillAnalyticWithUserInfo: function (jsonInfo){ const clientID = Repsol.Analytics.getIdUser() ? Repsol.Analytics.getIdUser() : undefined; const userIsLogged = Repsol.Analytics.Store.userIsLogged(); let userId = undefined; if( userIsLogged && userIsLogged != null ){ var data = Repsol.Analytics.getAccountInfoDL(); if(data && data.user && data.user != ''){ userId = data.user; } } var jsonInfo = { user_id: userId, client_id: clientID, } return jsonInfo; }, // Analytic 4.1.22 errorProductListSearchInputEmpty: function () { let jsonInfo = { event: 'r_error', error_type: 'filter_error', error_description: 'buscador matrícula|vehículo|El formato no es correcto', user_is_subscribed: undefined, // TODO: retomar cuando este listo la newsletter user_is_logged: Repsol.Analytics.Store.userIsLogged(), page_real_url: window.location.href } jsonInfo = {...jsonInfo,...Repsol.Analytics.Store.fillAnalyticWithUserInfo(jsonInfo)}; Repsol.Analytics.Store.setInfoClick(jsonInfo); }, clickDropDownStoreCart: function(obj){ let elementType; let textDefault; if (obj.closest('.coupon-fieldset').find('.icon-rp-Arrow_up').length > 0 || obj.closest('.total-mobile').find('.icon-rp-Arrow_down').length > 0) { elementType = 'drop-down close' textDefault = 'Close' } else if(obj.closest('.coupon-fieldset').find('.icon-rp-Arrow_down').length > 0 || obj.closest('.total-mobile').find('.icon-rp-Arrow_up').length > 0) { elementType = 'drop-down open' textDefault = 'Open' } var jsonInfo = { event: 'interaction', element_type: elementType, link_text: obj.text() !== "" ? $.trim(Repsol.Analytics.getFreeSpaceText(obj.text())) : obj.parent().find('label').text() || textDefault, component_name: Repsol.Analytics.getComponentLink(obj) } Repsol.Analytics.Store.sendDataLayer(jsonInfo); }, clickSoldOutWaitingListBtn: function (obj) { var jsonInfo = { event: 'interaction', element_type: 'button', link_text: $.trim(Repsol.Analytics.getFreeSpaceText(obj.text())), event_detail: obj.closest('.product-detail-component').find('.product-detail__title').length > 0 ? obj.closest('.product-detail-card').find('.product-detail__title')[0].innerText.trim() : undefined, business: Repsol.Analytics.ES.getBusinessMeta(), component_position: undefined, component_name: Repsol.Analytics.getComponentLink(obj) } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, setInfoClick: function(jsonInfo){ var isLogged = Repsol.Analytics.getCookie("isLogged"); if( isLogged == "true" && isLogged != null ){ var data = Repsol.Analytics.getAccountInfoDL(); if(data && data.user && data.user != ''){ jsonInfo.user_id = data.user; } } Repsol.Analytics.Store.sendDataLayer(jsonInfo); }, replaceProductData: (data) =>{ let keys = Object.keys(data); for(let i = 0; i < keys.length; i++){ let key = keys[i] if(data[key] && typeof data[key] === 'string'){ if(data[key].indexOf('%') != -1){ let replacedData = data[key].replace(/%/g, '%25') data[key] = replacedData } } } return data }, sendDataLayer: (jsonInfo) => { window.dataLayer.push(jsonInfo); Repsol.Analytics.sendAdobeDataLayer(jsonInfo); }, error: (obj, error) => { var jsonInfo= { event: 'error', error_type: obj.attr('data-error-type') ? obj.attr('data-error-type') : obj.closest('[data-error-type]').length > 0 ? obj.closest('[data-error-type]').attr("data-error-type").toLowerCase() : undefined, error_description: error ? error : Repsol.Analytics.ES.getFormErrorFields($('.checkout-component')), error_digitalcategory: obj.attr('data-error-digitalcategory') ? obj.attr('data-error-digitalcategory') : obj.closest('[data-error-digitalcategory]').length > 0 ? obj.closest('[data-error-digitalcategory]').attr("data-error-digitalcategory").toLowerCase() : undefined, funnel_type: obj.attr('data-funnel-type') ? obj.attr('data-funnel-type') : obj.closest('[data-funnel-type]').length > 0 ? obj.closest('[data-funnel-type]').attr("data-funnel-type") : undefined, funnel_action: obj.attr('data-funnel-action') ? obj.attr('data-funnel-action') : obj.closest('[data-funnel-action]').length > 0 ? obj.closest('[data-funnel-action]').attr("data-funnel-action") : undefined, funnel_step: obj.attr('data-funnel-step') ? obj.attr('data-funnel-step') : obj.closest('[data-funnel-step]').length > 0 ? obj.closest('[data-funnel-step]').attr("data-funnel-step") : undefined, component_name: obj.parents("[data-component]").length > 0 ? obj.parents("[data-component]").attr("data-component") : Repsol.Analytics.getComponentLink(obj) } Repsol.Analytics.Store.sendDataLayer(jsonInfo); }, errorStock: (errorMessage) => { var jsonInfo= { event: 'r_error', error_type: 'out of stock', error_description: errorMessage, user_is_subscribed: undefined, // TODO: retomar cuando este listo la newsletter user_is_logged: Repsol.Analytics.Store.userIsLogged(), page_real_url: window.location.href } jsonInfo = {...jsonInfo,...Repsol.Analytics.Store.fillAnalyticWithUserInfo(jsonInfo)}; Repsol.Analytics.Store.sendDataLayer(jsonInfo); }, errorRpAlert: (errorMsg) =>{ var jsonInfo= { event: 'r_error', error_type: errorMsg, error_description: errorMsg, page_real_url: window.location.href, user_is_subscribed: undefined, // TODO: retomar cuando este listo la newsletter user_is_logged: Repsol.Analytics.Store.userIsLogged() } jsonInfo = {...jsonInfo,...Repsol.Analytics.Store.fillAnalyticWithUserInfo(jsonInfo)}; Repsol.Analytics.Store.sendDataLayer(jsonInfo); }, errorCheckout: ({component, error, element}) => { let jsonInfo= { event: 'error', error_type: component.attr('data-error-type') ? component.attr('data-error-type') : component.closest('[data-error-type]').length > 0 ? component.closest('[data-error-type]').attr("data-error-type").toLowerCase() : undefined, error_description: error ? error : Repsol.Analytics.ES.getFormErrorFields($(element)), error_digitalcategory: component.attr('data-error-digitalcategory') ? component.attr('data-error-digitalcategory') : component.closest('[data-error-digitalcategory]').length > 0 ? component.closest('[data-error-digitalcategory]').attr("data-error-digitalcategory").toLowerCase() : undefined, funnel_type: component.attr('data-funnel-type') ? component.attr('data-funnel-type') : component.closest('[data-funnel-type]').length > 0 ? component.closest('[data-funnel-type]').attr("data-funnel-type") : undefined, funnel_action: component.attr('data-funnel-action') ? component.attr('data-funnel-action') : component.closest('[data-funnel-action]').length > 0 ? component.closest('[data-funnel-action]').attr("data-funnel-action") : undefined, funnel_step: element.closest('.checkout-tabpanel').attr("data-step") ?? undefined, component_name: component.parents("[data-component]").length > 0 ? component.parents("[data-component]").attr("data-component") : Repsol.Analytics.getComponentLink(component) } Repsol.Analytics.Store.sendDataLayer(jsonInfo); }, commonError: ({component, error, errorType}) => { if (!errorType) { errorType = Repsol.Analytics.ES.getFormErrorTypeTitle(component); } let jsonInfo= { event: 'r_error', error_type: errorType, error_description: error ? error : Repsol.Analytics.ES.getFormErrorFieldsES(component), user_is_subscribed: undefined, // TODO: retomar cuando este listo la newsletter user_is_logged: Repsol.Analytics.Store.userIsLogged(), page_real_url: window.self !== window.top ? urlRealIframeRT() : window.location.href } jsonInfo = {...jsonInfo,...Repsol.Analytics.Store.fillAnalyticWithUserInfo(jsonInfo)}; Repsol.Analytics.Store.sendDataLayer(jsonInfo); }, errorReview: function (obj, response) { var jsonInfo = { event: 'r_error', error_type: Repsol.Analytics.ES.getFormErrorTypeTitle(obj), error_description: (response && response.errorMessage)? response.errorMessage : Repsol.Analytics.ES.getFormErrorFieldsES(obj), user_is_subscribed: undefined, // TODO: retomar cuando este listo la newsletter user_is_logged: Repsol.Analytics.Store.userIsLogged(), page_real_url: window.self !== window.top ? urlRealIframeRT() : window.location.href } jsonInfo = {...jsonInfo,...Repsol.Analytics.Store.fillAnalyticWithUserInfo(jsonInfo)}; Repsol.Analytics.Store.sendDataLayer(jsonInfo); }, getFileName: (url) =>{ let fileName = undefined; if(url){ let urlSplit = url.split('/'); file = urlSplit[urlSplit.length - 1]; let fileSplit = file.split('.') fileName = fileSplit[0]; } return fileName; }, fixDescriptionComponent: function () { $(".text-title-component").find(".rp-limit-10").each(function (){ $(this).removeClass("rp-limit-10"); }) }, setMainName: function(){ if($(".product-list__filters-category-header").length > 0){ return $(".product-list__filters-category-header .product-list__filters-category-title").text().length ? $(".product-list__filters-category-header .product-list__filters-category-title").text() : undefined; }else{ return $(".product-list__category-header .product-list__category-title").text().length ? $(".product-list__category-header .product-list__category-title").text() : undefined; } }, setInfoServices: function(jsonInfo){ var isLogged = Repsol.Analytics.getCookie("isLogged"); var isEcommerce = $(".rp-ecommerce-page").length ? true : false; if( isEcommerce && (isLogged == "true" && isLogged != null) ){ var data = Repsol.Analytics.getAccountInfoDL(); if(data && data !=""){ jsonInfo.services_available = data.service ? data.service : "undefined"; jsonInfo.services_available_quantity = data.serviceQty ? data.serviceQty : "undefined"; } } }, viewKlimPopUp: (obj, params) => { var jsonInfo = { event: "view_element", component_description: params.component_description || Repsol.AnalyticsRomProd.Getters.getComponentDesc(obj), component_name: params.component_name || Repsol.AnalyticsRomProd.Getters.getComponentLink(obj), content_name: params.content_name || Repsol.AnalyticsRomProd.Getters.getContentName(obj), event_detail: params.event_detail || Repsol.AnalyticsRomProd.Getters.getEventDetail(obj), } Repsol.AnalyticsRomProd.Getters.setInfoClick(jsonInfo); }, viewPopUp: (obj) => { let jsonInfo= { event: 'view_popup', component_name: Repsol.Analytics.getComponentLink(obj), component_description: undefined, content_name: Repsol.Analytics.Store.getContentName(obj), user_is_logged: Repsol.Analytics.Store.userIsLogged() } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, viewPopUpV2: (obj) => { let jsonInfo= { event: 'view_popup', component_name: Repsol.Analytics.getComponentParentLink(obj.closest('[data-component]')) != null ? Repsol.Analytics.getComponentParentLink(obj.closest('[data-component]')) : Repsol.Analytics.getComponentParentLink(obj), content_name: Repsol.Analytics.Store.getContentName(obj) } Repsol.Analytics.Store.sendDataLayer(jsonInfo); }, closePopUp: (obj) => { var jsonInfo = { event: 'interaction', component_name: Repsol.Analytics.getComponentLink(obj), component_description: undefined, element_type: 'close', element_description: 'popup', link_text: obj.attr("data-text") ? $.trim(Repsol.Analytics.getFreeSpaceText(obj.attr("data-text"))) : $.trim(Repsol.Analytics.getFreeSpaceText(obj.text())), content_name: Repsol.Analytics.Store.getContentName(obj), user_is_logged: Repsol.Analytics.Store.userIsLogged() } Repsol.Analytics.Store.setInfoClick(jsonInfo); }, closePopUp2: (obj) => { var jsonInfo = { event: 'interaction', component_name: Repsol.Analytics.getComponentParentLink(obj.closest('[data-component]')) != null ? Repsol.Analytics.getComponentParentLink(obj.closest('[data-component]')) : Repsol.Analytics.getComponentParentLink(obj), component_position: 'popup', element_type: Repsol.Analytics.getTypeInteraction(obj), link_text: obj.attr("data-text") ? $.trim(Repsol.Analytics.getFreeSpaceText(obj.attr("data-text"))) : $.trim(Repsol.Analytics.getFreeSpaceText(obj.text())) } Repsol.Analytics.Store.sendDataLayer(jsonInfo) }, getContentName : (obj) =>{ let contentName = ""; let modal = obj.hasClass("modal") ? obj : (obj.closest(".modal").length > 0 ? obj.closest(".modal") : "") if(modal){ contentName = modal.find(".modal-header").text().trim() } return contentName ? contentName : undefined; }, getProductStatus : (salableQuantity) => { return salableQuantity > 0 ? 'stock' : 'out of stock'; }, clickInteraction: (obj) =>{ var jsonInfo= { event: 'interaction', link_text: obj.attr("data-text") ? Repsol.Analytics.getFreeSpaceText(obj.attr("data-text")) : Repsol.Analytics.getFreeSpaceText(obj.text()), component_name: Repsol.Analytics.getComponentParentLink(obj.closest('[data-component]')) != null ? Repsol.Analytics.getComponentParentLink(obj.closest('[data-component]')) : Repsol.Analytics.getComponentParentLink(obj), element_type: Repsol.Analytics.getTypeInteraction(obj), component_position: undefined } Repsol.Analytics.Store.sendDataLayer(jsonInfo); }, clickInteractionKlin: (obj) =>{ let $component = obj.closest('[data-component]'); var jsonInfo= { event: 'interaction', component_name: Repsol.Analytics.getComponentParentLink(obj.closest('[data-component]')) != null ? Repsol.Analytics.getComponentParentLink(obj.closest('[data-component]')) : Repsol.Analytics.getComponentParentLink(obj), component_description: undefined, element_type: 'button', element_description: 'open modal klin', link_text: obj.attr("data-text") ? Repsol.Analytics.getFreeSpaceText(obj.attr("data-text")) : Repsol.Analytics.getFreeSpaceText(obj.text()), content_name: Repsol.Analytics.Store.getContentName(obj) || obj.closest('.product-detail-component').find('.product-detail__title').length > 0 ? obj.closest('.product-detail-card').find('.product-detail__title')[0].innerText.trim() : undefined, user_type: sessionStorage.getItem("user") ? JSON.parse(sessionStorage.getItem("user")).user_type : undefined, gdpr_4__c: Repsol.Analytics.ES.GDPR.getGDPR4($component), event_detail: obj.closest('.product-detail-component').find('.product-detail__title').length > 0 ? obj.closest('.product-detail-card').find('.product-detail__title')[0].innerText.trim() : undefined, component_position: undefined } Repsol.Analytics.Store.sendDataLayer(jsonInfo); }, linkClickCopyRom: function(obj, params){ var jsonInfo = { event: 'link_click', component_catalogue: params.component_catalogue || Repsol.AnalyticsRomProd.Getters.getComponentCatalog(obj), component_description: params.component_description || Repsol.AnalyticsRomProd.Getters.getComponentDesc(obj) || undefined, component_name: params.component_name || Repsol.AnalyticsRomProd.Getters.getComponentLink(obj), component_position: params.component_position || Repsol.AnalyticsRomProd.Getters.getComponentPosition(obj), content_name: params.content_name || Repsol.AnalyticsRomProd.Getters.getContentName(obj), link_domain: params.link_domain || Repsol.AnalyticsRomProd.Getters.getDomineLink(obj), link_is_cta: params.link_is_cta || obj.attr("data-cta") || 'False', link_text: params.link_text || Repsol.AnalyticsRomProd.Getters.getTextLink(obj), link_type: params.link_type || Repsol.AnalyticsRomProd.Getters.getTypeLink(obj), link_url: params.link_url || obj.attr("href") || undefined, event_detail: params.event_detail || Repsol.AnalyticsRomProd.Getters.getEventDetail(obj), } if(Repsol.AnalyticsRomProd.Site.isCommerceSite){ jsonInfo['establishment_adress'] = params.establishment_adress || Repsol.AnalyticsRomProd.Getters.getEstablishmentAdress(); } Repsol.AnalyticsRomProd.Getters.setInfoClick(jsonInfo); }, linkClikKlin: function(obj, params){ var jsonInfo = { event: 'link_click', link_domain: params.link_domain || Repsol.AnalyticsRomProd.Getters.getDomineLink(obj), link_url: params.link_url || obj.attr("href") || undefined, link_text: params.link_text || Repsol.AnalyticsRomProd.Getters.getTextLink(obj), link_type: params.link_type || Repsol.AnalyticsRomProd.Getters.getTypeLink(obj), content_name: params.content_name || Repsol.AnalyticsRomProd.Getters.getContentName(obj), component_name: params.component_name || Repsol.AnalyticsRomProd.Getters.getComponentLink(obj), component_description: params.component_description || Repsol.AnalyticsRomProd.Getters.getComponentDesc(obj), component_position: params.component_position || Repsol.AnalyticsRomProd.Getters.getComponentPosition(obj), event_detail: params.event_detail || Repsol.AnalyticsRomProd.Getters.getEventDetail(obj), link_is_cta: params.link_is_cta || obj.attr("data-cta") || 'False', user_type: sessionStorage.getItem("user") ? JSON.parse(sessionStorage.getItem("user")).user_type : undefined, } Repsol.AnalyticsRomProd.Getters.setInfoClick(jsonInfo); }, setProductsStorage: (element) => { const items = Repsol.Analytics.Store.getProductData(element); const product = items ? items[0] : ''; let productsStorage = Repsol.utils.getData('productsAnalytics') ?? []; const savedProductIndex = productsStorage.findIndex((item) => { return product.product_sku == item.product_sku; }) if(savedProductIndex != -1){ productsStorage.splice(savedProductIndex, 1) } productsStorage.push(product) Repsol.utils.setData('productsAnalytics', productsStorage); }, getProductDataStorage: (data, sku) =>{ let valueData = ''; const productsStorage = Repsol.utils.getData('productsAnalytics'); const savedProduct = productsStorage?.find((product) =>{ return product.product_sku == sku; }); if(savedProduct){ valueData = savedProduct[data] ? savedProduct[data] : ''; } return valueData; }, getProductCategories: (categoriesList) => { let categories = ''; for(let i = 0; i < categoriesList.length; i++){ const category = categoriesList[i]; const categoryInfo = `${category.id}_${category.name}`; categories += categoryInfo; if(i < categoriesList.length - 1){ categories += ',' } } return categories; }, removeProductStorage: (sku) =>{ let productsStorage = Repsol.utils.getData('productsAnalytics') ?? []; const productIndex = productsStorage?.findIndex((product) =>{ return product.product_sku == sku; }); if(productIndex != -1){ productsStorage.splice(productIndex, 1); } Repsol.utils.setData('productsAnalytics', productsStorage); }, removeAllProductsStorage: () =>{ Repsol.utils.setData('productsAnalytics', []); } } $(document).ready(function () { Repsol.Analytics.Store.init(); }); var RepsolEcommerce = RepsolEcommerce || {}; RepsolEcommerce.utils = { replaceCharacters: function(text){ var from = 'ÁÃÀÄÂÉËÈÊÍÏÌÎÓÖÒÔØÚÜÙÛÑÇáãàäâéëèêíïìîóöòôøúüùûñç', to = 'AAAAAEEEEIIIIOOOOOUUUUNcaaaaaeeeeiiiiooooouuuunc'; for(var i = 0; i< text.length; i++){ if(from.indexOf(text.charAt(i)) != -1){ var newChart = to.charAt(from.indexOf(text.charAt(i))); text = text.replace(text.charAt(i), newChart); } } return text; }, zeroFill: function(number, width) { if(!isNaN(number)){ var numberOutput = Math.abs(number); var length = numberOutput.toString().length; var zero = "0"; if (width <= length) { if (number < 0) { return ("-" + numberOutput.toString()); } else { return numberOutput.toString(); } } else { if (number < 0) { return ("-" + (zero.repeat(width - length)) + numberOutput.toString()); } else { return ((zero.repeat(width - length)) + numberOutput.toString()); } } }else{ return number; } }, currentURL: function(){ var pathArray = window.location.pathname.split('/'); if(pathArray[pathArray.length-1] == ""){ pathArray.pop(); } if(pathArray[pathArray.length-1].indexOf(".") != -1){ return pathArray[pathArray.length-1].toLowerCase().substring(0, pathArray[pathArray.length-1].indexOf(".")); } else { return pathArray[pathArray.length-1].toLowerCase(); } }, checkEnvMagentoDomain: function() { let hostname = window.location.hostname let enviroment = '' if(hostname === 'dev-es.repsol.com') { enviroment = 'tienda.dev-es.repsol.com' } else if(hostname === 'stage-es.repsol.com') { enviroment = 'tienda.stage-es.repsol.com' } else if(hostname === 'qa-es.repsol.com') { enviroment = 'tienda.qa-es.repsol.com' }else { enviroment = 'tienda.repsol.es' } return enviroment }, findInArray: (array, search) => { let match = false; for(let i= 0; i < array.length; i++){ let item = array[i]; if(item == search){ match = true; break; } } return match; }, removeSpecialCharacters: (text) =>{ let specialCharacters = ["\\", "^", "$", "*", "¿", "?", ".", "+", "(", ")", "[", "]", "|", "{", "}", ",", "¡", "!", "~", "`", "@", "#", "%", "&", "=", "'", "\"", ":", ";", "<", ">", "/"]; for (let i = 0; i < specialCharacters.length; i++) { let chart = specialCharacters[i]; text = text.replaceAll(chart, ''); } return text; }, roundDecimalNumber: (number) => { let numberSplit = number.toString().split('.') let decimal = numberSplit[1] let firstDecimal = decimal?.charAt(0) let secondDecimal = decimal?.charAt(1) if(firstDecimal == 9 && secondDecimal == 9) { return Math.trunc(number * 100) / 100; } else { var m = Number((Math.abs(number) * 100).toPrecision(15)); return (Math.round(m) / 100 * Math.sign(number)).toFixed(2); } }, setPreviousUrlStore: () => { const domain = window.location.href; if(!domain.includes('/tienda')) { const previousUrl = window.location.href; if(previousUrl && !previousUrl.includes('/tienda')) { sessionStorage.setItem("paginaDeProcedenciaTienda", previousUrl); } } }, getPreviousUrlStore: () => { const paginaDeProcedencia = sessionStorage.getItem("paginaDeProcedenciaTienda"); if (paginaDeProcedencia && paginaDeProcedencia !== null && paginaDeProcedencia.trim() !== "" ) { return paginaDeProcedencia; } else { return "undefined"; } }, removeHTMLTags: (string) =>{ return string.replace(/<[^>]*>?/gm, '') }, formatThousandsNumber: (number) => { let formattedNumber = new Intl.NumberFormat("es-CL").format(number); if(formattedNumber.indexOf(',') != -1){ const decimals = formattedNumber.substr(formattedNumber.indexOf(',') + 1) if(decimals.length == 1){ formattedNumber += '0'; } }else{ formattedNumber += ',00'; } return formattedNumber; }, getCurrency: (currency) =>{ return currency == 'EUR' ? '€' : currency; }, toCamelCase: (string) => { let stringToCamelCase = ''; const stringSplit = string.split(' '); for(let i = 0; i < stringSplit.length; i++){ let str = stringSplit[i]; stringToCamelCase += str.replace(/(?:^\w|[A-ZÑ]|\b\w)/g, function(word, index) { return index === 0 ? word.toUpperCase() : word.toLowerCase(); }).replace(/\s+/g, ''); if(i < stringSplit.length -1 ){ stringToCamelCase += ' ' } } return stringToCamelCase; }, formatPrice: (element) => { const priceElems = element.querySelectorAll('.js-formatted-price'); priceElems.forEach((elem) => { let price = elem.innerText; elem.innerText = price.replace('.', ','); }); }, encryptIBAN: function (iban) { return `${iban.substr(0, 4)}**** **** **** **** **${iban.substr(iban.length - 2)}`; }, getUTMData: () =>{ let utmData; const utmStorageData = Repsol.utils.getData("rpVar_UTM"); if(utmStorageData){ utmData = { utmCampaign: utmStorageData.utm_campaign ?? "", utmContent: utmStorageData.utm_content ?? "", utmMedium: utmStorageData.utm_medium ?? "", utmSource: utmStorageData.utm_source ?? "", utmTerm: utmStorageData.utm_term ?? "" } } return utmData; }, getOffset: (element) =>{ if (!element.getClientRects().length) { return { top: 0, left: 0 }; } let rect = element.getBoundingClientRect(); let win = element.ownerDocument.defaultView; return ( { top: rect.top + win.pageYOffset, left: rect.left + win.pageXOffset } ); } } RepsolCards = { init: function () { RepsolCards.events(); }, events: function () { $(document).on("click", ".card-funnel a:not('.rp-no-link-product')", function (ev) { ev.preventDefault(); Repsol.utils.funnel.clearSession(); var link = $(this).attr("href"); const target = $(this).attr("target") ?? '_self'; var $card = $(this).closest(".card-funnel").find(".productDetail"); if ($card.length > 0) { let quoteProduct = { "id": $card.attr("data-product-id"), "name": $card.attr("data-product-name"), "rate": $card.attr("data-product-rate"), "family": $card.attr("data-product-family"), "commodity": $card.attr("data-product-commodity"), "isFlatRate": $card.children(".productIsFlatType").text() } Repsol.utils.createStorage("quoteProduct", quoteProduct, false); var family_name = $card.attr("data-product-family"); Repsol.utils.createStorage("family_name", family_name, false); } setTimeout(function () { if(target == '_blank'){ window.open(link, target); }else{ window.location = link; } }, 1000); }); }, svas: { exclusive : function(obj){ var $sva = obj; var $parent = $sva.closest(".add-services-list"); if($sva.hasClass("cmp-form-options--radio") && $parent.length > 0 ){ $parent.find(".cmp-form-options--radio").each(function(){ if($sva.val() != $(this).val()){ if($(this).is(':checked')){ $(this).prop("checked", false); } } }); } }, isExclusive: (services, service) => { let totalElectricitySVA = 0, totalGasSVA = 0, isClimaSVA = false, exclusiveSVA = false, climaSVAId = 'svaclima'; for(var i = 0; i < services.length; i++){ if(services[i].typeProduct == "electricity"){ totalElectricitySVA++; }else{ totalGasSVA++; } if(services[i].id == climaSVAId){ isClimaSVA = true; } } if(service.typeProduct == 'electricity' && totalElectricitySVA > 1 && isClimaSVA){ exclusiveSVA = true; } return exclusiveSVA; } } } var RepsolLoginStore = { cookieNames: { isLoginStore: "loginTiendaOnline", phpSession: "PHPSESSID" }, services:{ waylet: 'CM' }, init: function () { RepsolLoginStore.events(); }, events: function () { $(document).on("click", ".js-close-login-store", function () { RepsolLoginStore.close(); }); RepsolLoginStore.showLoginRegisterModal() }, open: function () { Repsol.utils.setCookie(RepsolLoginStore.cookieNames.isLoginStore, "true"); }, close: function () { Repsol.utils.deleteCookie(RepsolLoginStore.cookieNames.isLoginStore); }, isActive: function () { var cookie = Repsol.utils.getCookie(RepsolLoginStore.cookieNames.isLoginStore); if (cookie && cookie == "true") { return true; } else { return false; } }, checkUserLogged: function() { const isLogged = Repsol.utils.getCookie('isLogged'); const logged = isLogged !== 'true' ? false : true; return logged; }, getAccountUserData: () => { let p = new Promise(function (resolve, reject) { if (window.gigya) { gigya.accounts.getAccountInfo({ include: "profile,data,preferences", callback: function (response) { if (response.errorCode === 0) { resolve(response); } else { reject(response); } } }); } else { reject(); } }); return p; }, loginRegisterStoreActivation: function () { let url = "/bin/repsol-ecommerce/store/register" let guestCart = null; if (typeof miniCart !== 'undefined' && miniCart.idCart && miniCart.idCart != "") { guestCart = miniCart.idCart; } let p = new Promise(function (resolve, reject) { RepsolLoginStore.getAccountUserData() .then(resp => { const registerExpress = (response) => { let userData = response['data'] != undefined ? response['data'] : '' let userDocID = userData['DocID'] != undefined ? userData['DocID'] : '' let userDocType = userDocID['TipoLoyalty'] != undefined ? userDocID['TipoLoyalty'] : '' let userDocTypeNumber = userDocID['Loyalty'] != undefined ? userDocID['Loyalty'] : '' let email = response['profile']['email'] ? response['profile']['email'] : '' let name = response['profile']['firstName'] ? response['profile']['firstName'] : ' ' let lastName = response['profile']['lastName'] ? response['profile']['lastName'] : ' ' let uid = response['UID'] ? response['UID'] : '' let isStoreServiceActive = response['data'] && response['data']['Service'] && response['data']['Service']['TiendaOnline'] ? response['data']['Service']['TiendaOnline'] : false let $header = $('.header-ecom') let $headerStore = $('.header-ecom').data('header-type') let $headerStayPage = $('.header-ecom').data('stay-current-page') let $headerCurrentPage = $('.header-ecom').data('current-page') var isNew360 = $("#new360").attr("data-new-consents"); if(userDocType && userDocTypeNumber && isStoreServiceActive != true) { let documentTypes = { "NIF": "0", "NIE": "1", "PASAPORTE": "2", "CIF": "3", } let data = { "operation": "update", "email": email, "uid": uid, "lastName": lastName, "name": name, "cartId": guestCart, "documentType": documentTypes ? documentTypes[userDocType] : '0', "document": userDocTypeNumber, "alreadyInLoyalty": "true", "isNew360": isNew360 }; let xhr = new XMLHttpRequest(); xhr.addEventListener("readystatechange", function () { if (this.readyState === 4) { if (this.status == 200) { let response = JSON.parse(this.responseText); if (response.errorCode == 0) { resolve(response); } else { reject(response); } } else { reject(); } } }); xhr.open("POST", url); xhr.setRequestHeader("Content-Type", "application/json"); xhr.send(JSON.stringify(data)); } else { reject() } } registerExpress(resp) }).catch(err => { reject(); }); }); return p; }, magentoLogin: function () { let url = "/bin/repsol-ecommerce/store/register"; let guestCart = null; guestCart = localStorage?.cartId ? JSON.parse(localStorage.getItem('cartId'))?.id : undefined let p = new Promise(function (resolve, reject) { RepsolLoginStore.getAccountUserData() .then(resp => { if (resp['profile'] && resp['UID']) { let email = resp['profile']['email'] ? resp['profile']['email'] : '', name = resp['profile']['firstName'] ? resp['profile']['firstName'] : ' ', lastName = resp['profile']['lastName'] ? resp['profile']['lastName'] : ' ', uid = resp['UID'], operation = "login"; let data = { "operation": operation, "email": email, "uid": uid, "lastName": lastName, "name": name, "cartId": guestCart }; let xhr = new XMLHttpRequest(); xhr.addEventListener("readystatechange", function () { if (this.readyState === 4) { if (this.status == 200) { let response = JSON.parse(this.responseText); if (response.errorCode == 0) { let magentoSession = DOMPurify.sanitize(response.magentoSession); if (magentoSession && Repsol.utils.validations.phpsessid(magentoSession)) { let cookieDomain = RepsolLoginStore.getCookieDomain(); document.cookie = RepsolLoginStore.cookieNames.phpSession + "=" + response.magentoSession + "; domain=" + cookieDomain + ";path=/;"; } RepsolLoginStore.updateMergedCart(response); resolve(response); } else { reject(response); } } else { reject(); } } }); xhr.open("POST", url); xhr.setRequestHeader("Content-Type", "application/json"); xhr.send(JSON.stringify(data)); } else { reject(); } }) .catch(err => { reject(); }); }); return p; }, setCartIdToLocalStorage: function(cart) { const cartId = cart?.id let date = new Date() date.setDate(date.getDate() + 1); localStorage.setItem("cartId", `{"id": "${cartId}", "expDate":${date.getTime()}}`) }, setMergedCarts: async function(data) { const customerToken = data?.customerToken const sourceCartId = localStorage?.cartId ? JSON.parse(localStorage.getItem('cartId'))?.id : undefined if (customerToken) { localStorage.setItem("ct", JSON.stringify(data.customerToken)); const destCartId = data?.mergedCartId; const mergeCartResponse = await RepsolStore.mergeCarts(sourceCartId, destCartId); const cart = mergeCartResponse?.data?.mergeCarts; let date = new Date() date.setDate(date.getDate() + 1); localStorage.setItem("cartId", `{"id": "${cartId}", "expDate":${date.getTime()}}`) localStorage.setItem('cart', JSON.stringify(cart)); if ($(document).find(".store-minicart-component").length > 0) { miniCart.loadProducts(); } } }, updateMergedCart: function (data) { if (data.mergedCartId && data.mergedCartId != "") { var mergedCartId = data.mergedCartId; let date = new Date(); date.setDate(date.getDate() + 365); localStorage.setItem("cartId", `{"id": "${mergedCartId}", "expDate":${date.getTime()}}`) } if (data.mergeCarts && data.mergeCarts != "") { localStorage.setItem("cart", JSON.stringify(data.mergeCarts)); } if (data.customerToken && data.customerToken != "") { localStorage.setItem("ct", JSON.stringify(data.customerToken)); } if ($(document).find(".store-minicart-component").length > 0) { miniCart.idCart = mergedCartId; miniCart.loadProducts(); } }, isLoggedOnMagento: async () => { const ENVIRONMENT = RepsolEcommerce.utils.checkEnvMagentoDomain() const URL = `https://${ENVIRONMENT}/authentication/login/islogged` try { const response = await fetch(URL, { credentials: 'include' }) if (!response.ok) { console.log(response.status, response.statusText) throw new Error(`Error al obtener los datos: ${response.status} ${response.statusText}`) return {} } const data = await response.json() return data?.isLogged } catch (error) { if (error instanceof TypeError) { console.error('Error de red:', error.message) } else if (error instanceof SyntaxError) { console.error('Error en la respuesta del servidor:', error.message) } else if (error instanceof Error) { console.error('Ha habido un error:', error.message) } else { console.error('Error desconocido:', error) } return {} } }, isLoggedMagento: () => { let enviroment = RepsolEcommerce.utils.checkEnvMagentoDomain() let url = `https://${enviroment}/authentication/login/islogged`; let p = new Promise(function (resolve, reject) { $.ajax({ url: url, xhrFields: { withCredentials: true }, success: function (data) { if(data.isLogged && data.isLogged === true){ resolve({ "complete": true, "isLogged": true }); }else{ reject({ "complete": true, "isLogged": false }); } }, error: function (error) { reject({ "complete": false, "isLogged": false }); } }) }); return p; }, magentoLogout: () => { let cookieDomain = RepsolLoginStore.getCookieDomain(); document.cookie = `${RepsolLoginStore.cookieNames.phpSession}=; domain=${cookieDomain}; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;`; window.localStorage.removeItem("ct"); window.localStorage.removeItem("cart"); window.localStorage.removeItem("cartId"); window.localStorage.removeItem("activeCart"); window.localStorage.removeItem("giftCardPlace"); }, updateLoginMagento: () => { let p = new Promise(function (resolve, reject) { RepsolLoginStore.isLoggedMagento().then(resp => { resolve(); }) .catch(err => { var isLogged = Repsol.utils.getCookie("isLogged"); if (isLogged === "true") { RepsolLoginStore.magentoLogin().then(resp => { resolve(); }).catch(err => { reject(); }); } else { resolve(); } }) }) return p; }, getCookieDomain: () =>{ let hostname = window.location.hostname; if(hostname.indexOf('repsol.es') != -1){ return '.repsol.es'; }else{ return '.repsol.com'; } }, isLoggedServices: () =>{ let p = new Promise(function (resolve, reject) { RepsolLoginStore.getAccountUserData() .then(resp => { let servicesList = {}; if (resp['data'] && resp['data']['Service']) { let services = resp['data']['Service'], waylet = RepsolLoginStore.services.waylet; if(services[waylet] && services[waylet] === true){ servicesList[waylet] = true; } } let data = { "isLogged": true, "uid": resp['UID'], "services": servicesList }; resolve(data); }).catch(err => { let data = { "isLogged": false, "services": {} }; reject(data) }); }); return p; }, showLoginRegisterModal: () => { const buttons = $('.show-modal-login'); const loginTab = $('.register-login-forms-container').find('.cmp-tabs__tab')[0]; const loginTabPanel = $('.register-login-forms-container').find('.cmp-tabs__tabpanel')[0]; const registerTab = $('.register-login-forms-container').find('.cmp-tabs__tab')[1]; const registerTabPanel = $('.register-login-forms-container').find('.cmp-tabs__tabpanel')[1]; buttons.each((index, button) => { $(button).on('click', (event) => { event.preventDefault(); const tab = button.getAttribute('data-login-tab'); if(tab == 'register'){ $(loginTab).removeClass('cmp-tabs__tab--active'); $(loginTabPanel).removeClass('cmp-tabs__tabpanel--active'); $(registerTab).addClass('cmp-tabs__tab--active'); $(registerTabPanel).addClass('cmp-tabs__tabpanel--active'); }else{ $(loginTab).addClass('cmp-tabs__tab--active'); $(loginTabPanel).addClass('cmp-tabs__tabpanel--active'); $(registerTab).removeClass('cmp-tabs__tab--active'); $(registerTabPanel).removeClass('cmp-tabs__tabpanel--active'); } RepsolRegisterLoginModal.showModal(); }) }) }, registerStoreFast : () => { let p = new Promise(function (resolve, reject) { RepsolLoginStore.magentoLogin() .then(resp => { if (resp['errorCode'] == 0) { RepsolLoginStore.loginRegisterStoreActivation().then(resp => { if(resp["errorCode"] == 0){ resolve(); }else{ reject(); } }).catch(err => { reject(); }); } else { reject(); } }).catch(err => { reject(); }); }); return p; } }; var RepsolHeader = { breackpoint: 1024, init: function () { RepsolHeader.events(); RepsolHeader.specifiLisener(); $(window).on("resize", RepsolHeader.events); }, events: function () { let navBar = $(".header-xf").find(".store-message-component").height(); if (!$(".header-xf").find(".store-message-component").hasClass("show")) navBar = 0; let linkBar = $(".header-es").find(".linksbar-ecommerce-component").height(); let breadcrumb = $(".header-xf").find(".breadcrumb").height(); let saveHeight = 0; if ($(window).width() >= RepsolHeader.breackpoint ){ if (navBar !== undefined ) { saveHeight += navBar; } if (breadcrumb !== undefined ) { if ($(".header-es").find(".store-message-component").length < 0) { // $(document).find(".breadcrumb").css("margin-top", navBar + 'px'); saveHeight = 0; } } } else { if(navBar !== undefined ){ saveHeight += navBar; if (breadcrumb !== undefined ) { if ($(".header-es").find(".store-message-component").length < 0) { // $(document).find(".breadcrumb").css("margin-top", navBar + 'px'); saveHeight = 0; } } } if (linkBar !== undefined ){ saveHeight += linkBar; if (breadcrumb !== undefined ) { saveHeighttwo = navBar + linkBar; $(document).find(".breadcrumb").css("margin-top", saveHeighttwo + 'px'); saveHeight = 0; } } } // if ($(".header-es").find(".store-message-component").length < 0) { // $(document).find("main").css("margin-top", saveHeight + 'px'); // } }, specifiLisener: function () { var elemento = $('.store-message-component'); if (elemento.length > 0){ var observer = new MutationObserver(function(mutationsList) { mutationsList.forEach(function(mutation) { if (mutation.type === 'attributes' && mutation.attributeName === 'class') { if (!elemento.hasClass('show')) { RepsolHeader.events(); } } }); }); var observerOptions = { attributes: true, attributeFilter: ['class'], }; observer.observe(elemento[0], observerOptions); } } } var RepsolLanding = { lista: {}, checkUrl: false, checkComponent: false, locationPath: window.location.href, init: function(){ RepsolLanding.lista = RepsolLanding.loadJson(); RepsolLanding.checkUrls(); RepsolLanding.checkComponents(); RepsolLanding.events(); }, events: function(){ if(RepsolLanding.checkUrl && RepsolLanding.checkComponent){ let components = RepsolLanding.lista.components; for (var i = 0, l = components.length; i < l; ++i) { if($(document).find("." + components[i]).length > 0){ $("." + components[i]).on("click", ".rp-link-click, .rp-btn", function () { let hasProduct = $(this).closest(".card-ecommerce").find(".productDetail"); if(hasProduct.length != 0 && hasProduct != ""){ let path = $(this).closest(".card-ecommerce").find("a"); for (let j=0; j < path.length; j++){ if (path[j].getAttribute("href").includes("tarifas")){ Repsol.utils.setData("landingEyG", path[j].getAttribute("href")); break; } else{ Repsol.utils.setData("landingEyG", path[j].getAttribute("href")); } } }else{ if(!RepsolLanding.locationPath.includes('cotizador')){ Repsol.utils.setData("landingEyG", RepsolLanding.locationPath); } } }); } } } else if (!RepsolLanding.locationPath.includes('cotizador')){ Repsol.utils.removeData("landingEyG"); } }, loadJson: function(){ var content = {}; $.ajax({ url: "/content/dam/repsol-ecommerce/inc/landing-funnel-info.json", async: false, dataType: 'json', success: function (data) { content.rutas = data.url; content.components = data.component; }, error: function (error){ console.log(error); } }) return content; }, checkUrls: function(){ let locationPath = window.location.href, url = RepsolLanding.lista.rutas; for (var i = 0; i < url.length; ++i) { let tempUrl = url[i]; if(locationPath.includes(tempUrl)){ RepsolLanding.checkUrl = true break; } else { RepsolLanding.checkUrl = false } } }, checkComponents: function(){ let components = RepsolLanding.lista.components; for (var i = 0, l = components.length; i < l; ++i) { if($(document).find("." + components[i]).length > 0){ RepsolLanding.checkComponent = true break; } else{ RepsolLanding.checkComponent = false } } } } var RepsolConecta = { getTiers: function(data) { let url = '/bin/repsol-ecommerce/store/waylet'; data.operation = "tiers"; return new Promise(function (resolve, reject) { let xhr = new XMLHttpRequest(); xhr.addEventListener("readystatechange", function () { if (this.readyState === 4) { if (this.status == 200) { let response = JSON.parse(this.responseText); if(response?.errors?.length == 0){ let data = response.data ? response.data : {}; resolve(data) }else{ reject() } } else { reject(); } } }); xhr.open("POST", url); xhr.setRequestHeader("Content-Type", "application/json"); xhr.send(JSON.stringify(data)); }) }, getUserWaylet : () =>{ let p = new Promise(function (resolve, reject) { RepsolLoginStore.isLoggedServices().then(resp => { let response = resp; let services = response.services; let waylet = RepsolLoginStore.services.waylet; if(response.isLogged && services[waylet] && response.uid){ let data = { "gigyaId": response.uid } RepsolConecta.getTiers(data).then(resp => { let tiersList = resp.tierList ? resp.tierList : []; let collectiveList = resp.collectiveList ? resp.collectiveList : []; const tierActive = tiersList.find(tier => tier.isActive === true); let collectivesActive = collectiveList.filter(collective => collective.isActive === true); const tierNames = { "AGPR1": "tier1", "AGPR2": "tier2", "AGPR3": "tier3", "AGPR4": "tier4" } const currentTierId = tierActive?.idPaquete; let nextTierId = null; let nextTierPercentage = null; let percentage = tierActive.tiendaOnlinePercentage ? tierActive.tiendaOnlinePercentage : tierActive.loyaliaPercentage ? tierActive.loyaliaPercentage : null; if (currentTierId) { const higherTier = tiersList.find((tier) => { let tierPercentage = tier.tiendaOnlinePercentage ? tier.tiendaOnlinePercentage : tier.loyaliaPercentage ? tier.loyaliaPercentage : null; return tierPercentage > percentage }); if (higherTier) { nextTierId = higherTier?.idPaquete; nextTierPercentage = higherTier?.tiendaOnlinePercentage ? higherTier?.tiendaOnlinePercentage : higherTier?.loyaliaPercentage ? higherTier?.loyaliaPercentage : null; } } if(percentage){ let percentageCollective = 0; collectivesActive.forEach((collective) => { if(collective.tiendaOnlinePercentage){ percentageCollective += collective.tiendaOnlinePercentage } }) let userInfo = { 'isLogged' : true, 'waylet': true, 'percentage': percentage + percentageCollective, 'currentTierId': tierNames[currentTierId], 'nextTierId': tierNames[nextTierId] || 'notier', 'nextTierPercentage': nextTierPercentage + percentageCollective || 0, } resolve(userInfo) }else{ let userInfo = { 'isLogged' : true, 'waylet': false } resolve(userInfo) } }).catch(err => { let userInfo = { 'isLogged' : true, 'waylet': false } resolve(userInfo) }); }else{ let userInfo = { 'isLogged' : true, 'waylet': false } resolve(userInfo) } }).catch(err => { let userInfo = { 'isLogged' : false, 'waylet': false } resolve(userInfo) }); }); return p; }, showWayletMessage: (obj, data = {}) => { let constantsList = obj.data("constants"); if(constantsList){ if(constantsList.waylet_image_url){ obj.find('.js-repsol-conecta-waylet-img').attr('src', constantsList.waylet_image_url) } if(constantsList.waylet_mobile_image_url){ obj.find('.js-repsol-conecta-waylet-img-mobile').attr('src', constantsList.waylet_mobile_image_url) } } let waylet = RepsolLoginStore.services.waylet; RepsolConecta.getUserWaylet().then((resp)=>{ let isLogged = resp.isLogged ? resp.isLogged : false let waylet = resp.waylet ? resp.waylet : false let percentage = resp.percentage ? resp.percentage : '' if(isLogged){ let username = Repsol.utils.getCookie("username"); if(username && username != "''" && username != "null" && Object.keys(data).length){ username = username.replace(',','').trim() data.username = username; } if(waylet && percentage){ data.percentage = percentage; data.status = 2; RepsolConecta.setWayletMessage(obj, data); }else{ data.status = 1; if(data.percentageLoggedNotWaylet){ data.percentage = data.percentageLoggedNotWaylet; } if(data.percentageLoggedNotWaylet2){ data.percentage2 = data.percentageLoggedNotWaylet2; } delete data.percentageNotLogged; delete data.percentageLoggedNotWaylet; delete data.percentageLoggedNotWaylet2; RepsolConecta.setWayletMessage(obj, data); } }else{ data.status = 0; if(data.percentageNotLogged){ data.percentage = data.percentageNotLogged; delete data.percentageNotLogged; delete data.percentageLoggedNotWaylet; delete data.percentageLoggedNotWaylet2; } RepsolConecta.setWayletMessage(obj, data); } }).catch(err => { data.status = 0; if(data.percentageNotLogged){ data.percentage = data.percentageNotLogged; delete data.percentageNotLogged; delete data.percentageLoggedNotWaylet; delete data.percentageLoggedNotWaylet2; } RepsolConecta.setWayletMessage(obj, data); }).finally(() => { obj.find('.js-repsol-conecta-waylet').removeClass('d-none'); }) }, setWayletMessage: (obj, data) => { let status = data.status ? data.status : 0; let total = data.total ? data.total : 0; let currency = data.currency ? data.currency : ''; let percentageWaylet = data.percentage ? data.percentage : 0; let percentage2Waylet = data.percentage2 ? data.percentage2 : 0; let username = data.username ? data.username + ', ' : ''; let text = ''; let maxBalanceWaylet = obj.data("constants").max_balance_waylet let msgElem = obj.find('.js-repsol-conecta-waylet-message'); const showUsername = !msgElem.attr("data-username") || (msgElem.attr("data-username") && msgElem.attr("data-username") == "true") ? true : false; switch(status){ case 0: text = obj.attr('data-text-not-logged') ? obj.attr('data-text-not-logged') : ''; break; case 1: text = obj.attr('data-text-logged-not-waylet') ? obj.attr('data-text-logged-not-waylet') : ''; break; case 2: text = obj.attr('data-text-logged-waylet') ? obj.attr('data-text-logged-waylet') : ''; break; } let balanceWaylet = RepsolConecta.getBalanceWaylet(Number(total), parseFloat(percentageWaylet)) let balanceWaylet2 = RepsolConecta.getBalanceWaylet(Number(total), parseFloat(percentage2Waylet)) if(maxBalanceWaylet && maxBalanceWaylet < Number(balanceWaylet) && maxBalanceWaylet < Number(balanceWaylet2)){ maxBalanceWaylet = maxBalanceWaylet.toString().replace('.', ',') text = obj.attr('data-text-logged-not-waylet-max-balance') ? obj.attr('data-text-logged-not-waylet-max-balance') : ''; text = text.replace('X€', `${maxBalanceWaylet} ${currency}`) } else if (maxBalanceWaylet && maxBalanceWaylet < Number(balanceWaylet)){ maxBalanceWaylet = maxBalanceWaylet.toString().replace('.', ',') text = text.replace('X€', `${maxBalanceWaylet} ${currency}`) } else if(maxBalanceWaylet && maxBalanceWaylet < Number(balanceWaylet2)) { maxBalanceWaylet = maxBalanceWaylet.toString().replace('.', ',') balanceWaylet2 = balanceWaylet2.toString().replace('.', ',') text = text.replace('X€', `${balanceWaylet} ${currency}`) text = text.replace('Y€', `${maxBalanceWaylet} ${currency}`) } else { balanceWaylet = balanceWaylet.toString().replace('.', ',') balanceWaylet2 = balanceWaylet2.toString().replace('.', ',') text = text.replace('X€', `${balanceWaylet} ${currency}`) text = text.replace('Y€', `${balanceWaylet2} ${currency}`) } if(username && showUsername){ text = username + text; } text = text.replace('{0}', percentageWaylet); if(typeof textile !== "undefined"){ text = textile(text) } msgElem.html(text); }, getBalanceWaylet: function(total, percentage) { let balance = total * percentage/100; return RepsolEcommerce.utils.roundDecimalNumber(balance) } } var RepsolGraphql = { generateQueryParamRequest: function(){ if(!!Repsol.utils.getCookie("PHPSESSID")) { return "?GQSEID=" + Repsol.utils.getCookie("PHPSESSID"); } return ""; } } const RepsolStore = { API_URL: '/api/graphql', fetchData: async function(query) { const CUSTOMER_TOKEN = localStorage?.ct ? JSON.parse(localStorage.getItem('ct')) : null const headers = { 'Content-Type': 'application/json', 'Accept': 'application/json', } if(CUSTOMER_TOKEN) { headers.Authorization = `Bearer ${CUSTOMER_TOKEN}` } const options = { method: 'POST', timeout: 5000, headers: headers, body: JSON.stringify({ query: query, }) } try { const response = await fetch(RepsolStore.API_URL + RepsolGraphql.generateQueryParamRequest(), options) if (!response.ok) { throw new Error(`Error al obtener los datos: ${response.status} ${response.statusText}`) } const data = await response.json() return data } catch (error) { throw error } }, createEmptyCart: async function () { const query = ` mutation { createEmptyCart } ` const data = await RepsolStore.fetchData(query) return data }, customerCart: async function () { const query = ` { customerCart { id email estimate { product { name sku virtual_product } estimate } items { id uid quantity name parent_url_key product { url_key name h1_label sku parent_sku stock_status salable_quantity category_ids{ id name } manufacturer_label thumbnail { url } price_range { minimum_price { regular_price { value currency } discount { amount_off percent_off } final_price { value currency } } } reservation_price ... on SimpleProduct { capacidad_label talla_label } } prices { grand_total { value currency } subtotal_including_tax { currency value } subtotal_with_discount_excluding_tax { currency value } discounts { label amount { currency value } } grand_total_excluding_tax { currency value } vat_breakdown { tax_percentage tax_base { value currency } tax { value currency } total_including_tax { value currency } } applied_taxes { label amount { value currency } } } errors { code message } } applied_coupons { code } applied_gift_cards { applied_balance { value currency } code current_balance { value currency } multiple_uses } available_payment_methods { code title cards_logos { url } paycomet_params { card_holder_name date_month date_year pa_number cvc2 jet_id payment_error_message jetIframe_script cards_logos { url } } instantcredit_params { active ic_script ic_configuration ic_simulator cards_logos { url } } waylet_params { cards_logos { url } } } billing_address { city firstname lastname postcode street telephone country { code label } region { code label } } shipping_addresses { firstname lastname street city telephone region { code label } country { code label } available_shipping_methods { available carrier_code carrier_title error_message method_code amount { currency value } price_excl_tax { value currency } price_incl_tax { value currency } } selected_shipping_method { carrier_code carrier_title method_code amount { value currency } } } prices { grand_total { value currency } subtotal_including_tax { currency value } subtotal_with_discount_excluding_tax { currency value } discounts { label amount { currency value } } grand_total_excluding_tax { currency value } vat_breakdown { tax_percentage tax_base { value currency } tax { value currency } total_including_tax { value currency } } applied_taxes { label amount { value currency } } } } } ` const data = await RepsolStore.fetchData(query) return data }, getCart: async function () { const CART_ID = localStorage?.cartId ? JSON.parse(localStorage.getItem('cartId'))?.id : undefined const query = ` { cart(cart_id: "${CART_ID}") { id email estimate { product { name sku virtual_product } estimate } items { id uid name parent_url_key product { url_key name h1_label sku parent_sku stock_status salable_quantity is_canary_product category_ids{ id name } manufacturer_label thumbnail { url } price_range { minimum_price { regular_price { value currency } discount { amount_off percent_off } final_price { value currency } } } reservation_price ... on SimpleProduct { capacidad_label talla_label } ... on BundleProduct { items { title options { uid quantity price price_type label product { uid name sku salable_quantity __typename } } } } short_description { html } } quantity ... on BundleCartItem { bundle_options { uid label type values { uid id label price quantity } } } prices { row_total_including_tax { value currency } } errors { code message } } applied_coupons { code } applied_gift_cards { applied_balance { value currency } code current_balance { value currency } multiple_uses } available_payment_methods { code title cards_logos { url } paycomet_params { card_holder_name date_month date_year pa_number cvc2 jet_id payment_error_message jetIframe_script cards_logos { url } } instantcredit_params { active ic_script ic_configuration ic_simulator cards_logos { url } } waylet_params { cards_logos { url } } } shipping_addresses { firstname lastname street city region { code label } country { code label } telephone available_shipping_methods { amount { currency value } available carrier_code carrier_title error_message method_code price_excl_tax { value currency } price_incl_tax { value currency } } selected_shipping_method { amount { value currency } carrier_code carrier_title method_code } } prices { grand_total { value currency } subtotal_including_tax { currency value } subtotal_with_discount_excluding_tax { currency value } discounts { label amount { currency value } } grand_total_excluding_tax { currency value } vat_breakdown { tax_percentage tax_base { value currency } tax { value currency } total_including_tax { value currency } } applied_taxes { label amount { value currency } } } } } ` const data = await RepsolStore.fetchData(query) return data }, getCartOverlay: async function () { const CART_ID = localStorage?.cartId ? JSON.parse(localStorage.getItem('cartId'))?.id : undefined const query = ` { cart(cart_id: "${CART_ID}") { id items { id uid name product { url_key name h1_label sku parent_sku stock_status salable_quantity is_canary_product category_ids{ id name } manufacturer_label thumbnail { url } price_range { minimum_price { regular_price { value currency } discount { amount_off percent_off } final_price { value currency } } } reservation_price ... on SimpleProduct { capacidad_label talla_label } ... on BundleProduct { items { title options { uid quantity price label product { uid name sku salable_quantity __typename } } } } short_description { html } } quantity ... on BundleCartItem { bundle_options { uid label type values { uid id label price quantity } } } prices { row_total_including_tax { value currency } } errors { code message } } applied_coupons { code } applied_gift_cards { applied_balance { value currency } code current_balance { value currency } multiple_uses } prices { grand_total { value currency } subtotal_including_tax { currency value } discounts { label amount { currency value } } } } } ` const data = await RepsolStore.fetchData(query) return data }, mergeCarts: async function (sourceCartId, destCartId) { const CART_ID = localStorage?.cartId ? JSON.parse(localStorage.getItem('cartId'))?.id : undefined const query = ` mutation { mergeCarts( source_cart_id: "${sourceCartId}" destination_cart_id: "${destCartId}" ) { id estimate { product { name sku virtual_product } estimate } items { id uid quantity name parent_url_key product { name h1_label sku parent_sku stock_status salable_quantity is_canary_product category_ids{ id name } manufacturer_label url_key thumbnail { url } price_range { minimum_price { final_price { value currency } } } reservation_price ... on SimpleProduct { capacidad_label talla_label } } prices { grand_total { value currency } subtotal_including_tax { currency value } subtotal_with_discount_excluding_tax { currency value } discounts { label amount { currency value } } grand_total_excluding_tax { currency value } vat_breakdown { tax_percentage tax_base { value currency } tax { value currency } total_including_tax { value currency } } applied_taxes { label amount { value currency } } } errors { code message } } } } ` const data = await RepsolStore.fetchData(query) return data }, addProductsToCart: async function (qty, id, items) { const CART_ID = localStorage?.cartId ? JSON.parse(localStorage.getItem('cartId'))?.id : undefined let cartItemsString = ""; items.forEach((item) => { cartItemsString += `"${item}"`; }); let isBundleProduct = cartItemsString != ""; let query = ` mutation { addProductsToCart( cartId: "${CART_ID}", cartItems: [ { quantity: ${qty} sku: "${id}"` if(isBundleProduct){ query+=` selected_options: [ ${cartItemsString} ]` } query+=` } ] ) { cart { id items { id uid name product { name h1_label sku parent_sku stock_status salable_quantity category_ids{ id name } manufacturer_label url_key thumbnail { url } price_range { minimum_price { regular_price { value currency } final_price { value currency } discount { amount_off percent_off } } } reservation_price short_description { html } ... on SimpleProduct { capacidad_label talla_label } ... on BundleProduct { items { uid type title options { uid quantity price label product { uid name sku salable_quantity __typename } } } } } quantity ... on BundleCartItem { bundle_options { uid label type values { uid id label price quantity } } } prices { row_total_including_tax { value currency } } errors { code message } } applied_coupons { code } applied_gift_cards { applied_balance { value currency } code current_balance { value currency } multiple_uses } available_payment_methods { code title cards_logos { url } paycomet_params { card_holder_name date_month date_year pa_number cvc2 jet_id payment_error_message jetIframe_script cards_logos { url } } instantcredit_params { active ic_script ic_configuration ic_simulator cards_logos { url } } waylet_params { cards_logos { url } } } billing_address { city country { code label } firstname lastname postcode region { code label } street telephone } shipping_addresses { firstname lastname street city region { code label } country { code label } telephone available_shipping_methods { amount { currency value } available carrier_code carrier_title error_message method_code price_excl_tax { value currency } price_incl_tax { value currency } } selected_shipping_method { amount { value currency } carrier_code carrier_title method_code } } prices { grand_total { value currency } subtotal_including_tax { currency value } subtotal_with_discount_excluding_tax { currency value } discounts { label amount { currency value } } grand_total_excluding_tax { currency value } vat_breakdown { tax_percentage tax_base { value currency } tax { value currency } total_including_tax { value currency } } applied_taxes { label amount { value currency } } } } user_errors { code message } } } ` const data = await RepsolStore.fetchData(query) return data }, addMultipleProductsToCart: async function (items) { const CART_ID = localStorage?.cartId ? JSON.parse(localStorage.getItem('cartId'))?.id : undefined let cartItemsString = ""; items.forEach((item, index) => { cartItemsString += ` { sku: "${item.sku}", quantity: ${item.quantity} } `; if (index < items.length - 1) { cartItemsString += ","; } }); const query = ` mutation { addProductsToCart( cartId: "${CART_ID}", cartItems: [${cartItemsString}] ) { cart { id email total_quantity estimate { product { name sku virtual_product } estimate } items { id uid name product { name sku url_key stock_status salable_quantity thumbnail { url } price_range { minimum_price { regular_price { value currency } final_price { value currency } } } reservation_price ... on SimpleProduct { capacidad_label talla_label } } quantity prices { row_total_including_tax { value currency } } errors { code message } } prices { grand_total { value currency } subtotal_including_tax { currency value } subtotal_with_discount_excluding_tax { currency value } discounts { label amount { currency value } } grand_total_excluding_tax { currency value } vat_breakdown { tax_percentage tax_base { value currency } tax { value currency } total_including_tax { value currency } } applied_taxes { label amount { value currency } } } } user_errors { code message } } } ` const data = await RepsolStore.fetchData(query) return data }, updateCartItems: async function (qty, id) { const CART_ID = localStorage?.cartId ? JSON.parse(localStorage.getItem('cartId'))?.id : undefined const query = ` mutation { updateCartItems( input: { cart_id: "${CART_ID}", cart_items: [ { cart_item_uid: "${id}" quantity: ${qty} } ] } ) { cart { id email estimate { product { name sku virtual_product } estimate } items { id uid name parent_url_key product { url_key name h1_label sku parent_sku stock_status salable_quantity category_ids{ id name } manufacturer_label thumbnail { url } price_range { minimum_price { regular_price { value currency } discount { amount_off percent_off } final_price { value currency } } } short_description { html } reservation_price ... on SimpleProduct { capacidad_label talla_label } ... on BundleProduct { items { uid type title options { uid quantity price price_type label product { uid name sku salable_quantity __typename } } } } } quantity ... on BundleCartItem { bundle_options { uid label type values { uid id label price quantity } } } prices { row_total_including_tax { value currency } } errors { code message } } applied_coupons { code } applied_gift_cards { applied_balance { value currency } code current_balance { value currency } multiple_uses } available_payment_methods { code title cards_logos { url } paycomet_params { card_holder_name date_month date_year pa_number cvc2 jet_id payment_error_message jetIframe_script cards_logos { url } } instantcredit_params { active ic_script ic_configuration ic_simulator cards_logos { url } } waylet_params { cards_logos { url } } } billing_address { city country { code label } firstname lastname postcode region { code label } street telephone } shipping_addresses { firstname lastname street city region { code label } country { code label } telephone available_shipping_methods { amount { currency value } available carrier_code carrier_title error_message method_code price_excl_tax { value currency } price_incl_tax { value currency } } selected_shipping_method { amount { value currency } carrier_code carrier_title method_code } } prices { grand_total { value currency } subtotal_including_tax { currency value } subtotal_with_discount_excluding_tax { currency value } discounts { label amount { currency value } } grand_total_excluding_tax { currency value } vat_breakdown { tax_percentage tax_base { value currency } tax { value currency } total_including_tax { value currency } } applied_taxes { label amount { value currency } } } } } } ` const data = await RepsolStore.fetchData(query) return data }, updateMultipleCartItems: async function (items) { const CART_ID = localStorage?.cartId ? JSON.parse(localStorage.getItem('cartId'))?.id : undefine let cartItemsString = ""; items.forEach((item, index) => { cartItemsString += ` { cart_item_uid: "${item.cart_item_uid}", quantity: ${item.quantity} } `; if (index < items.length - 1) { cartItemsString += ","; } }); const query = ` mutation { updateCartItems( input: { cart_id: "${CART_ID}", cart_items: [${cartItemsString}] } ) { cart { id email total_quantity estimate { product { name sku virtual_product } estimate } items { id uid quantity name parent_url_key product { name h1_label sku parent_sku stock_status only_x_left_in_stock salable_quantity category_ids{ id name } manufacturer_label image { label url } thumbnail { label url } price_range { minimum_price { final_price { value currency } discount { amount_off percent_off } } } reservation_price ... on SimpleProduct{ capacidad_label talla_label } } errors { code message } } prices { grand_total { value currency } subtotal_including_tax { currency value } subtotal_with_discount_excluding_tax { currency value } discounts { label amount { currency value } } grand_total_excluding_tax { currency value } vat_breakdown { tax_percentage tax_base { value currency } tax { value currency } total_including_tax { value currency } } applied_taxes { label amount { value currency } } } } } } ` const data = await RepsolStore.fetchData(query) return data }, removeItemFromCart: async function (id) { const CART_ID = localStorage?.cartId ? JSON.parse(localStorage.getItem('cartId'))?.id : undefined const query = ` mutation { removeItemFromCart( input: { cart_id: "${CART_ID}", cart_item_id: ${id} } ) { cart { id email estimate { product { name sku virtual_product } estimate } items { id uid name parent_url_key product { url_key name h1_label sku parent_sku stock_status salable_quantity category_ids{ id name } manufacturer_label thumbnail { url } price_range { minimum_price { regular_price { value currency } discount { amount_off percent_off } final_price { value currency } } } reservation_price ... on SimpleProduct { capacidad_label talla_label } ... on BundleProduct { items { uid type title options { uid quantity price price_type label product { uid name sku salable_quantity __typename } } } } } quantity ... on BundleCartItem { bundle_options { uid label type values { uid id label price quantity } } } prices { row_total_including_tax { value currency } } errors { code message } } applied_coupons { code } applied_gift_cards { applied_balance { value currency } code current_balance { value currency } multiple_uses } available_payment_methods { code title cards_logos { url } paycomet_params { card_holder_name date_month date_year pa_number cvc2 jet_id payment_error_message jetIframe_script cards_logos { url } } instantcredit_params { active ic_script ic_configuration ic_simulator cards_logos { url } } waylet_params { cards_logos { url } } } billing_address { city country { code label } firstname lastname postcode region { code label } street telephone } shipping_addresses { firstname lastname street city region { code label } country { code label } telephone available_shipping_methods { amount { currency value } available carrier_code carrier_title error_message method_code price_excl_tax { value currency } price_incl_tax { value currency } } selected_shipping_method { amount { value currency } carrier_code carrier_title method_code } } prices { grand_total { value currency } subtotal_including_tax { currency value } subtotal_with_discount_excluding_tax { currency value } discounts { label amount { currency value } } grand_total_excluding_tax { currency value } vat_breakdown { tax_percentage tax_base { value currency } tax { value currency } total_including_tax { value currency } } applied_taxes { label amount { value currency } } } } } } ` const data = await RepsolStore.fetchData(query) return data }, setShippingMethod: async function(method) { const CART_ID = localStorage?.cartId ? JSON.parse(localStorage.getItem('cartId'))?.id : undefined const { carrier_code = '', method_code = '' } = method ?? {} const query = ` mutation { setShippingMethodsOnCart( input: { cart_id: "${CART_ID}" shipping_methods: [ { carrier_code: "${carrier_code}", method_code: "${method_code}" } ] } ) { cart { id email estimate { product { name sku virtual_product } estimate } items { id uid quantity name product { url_key name h1_label sku parent_sku stock_status salable_quantity category_ids{ id name } manufacturer_label thumbnail { url } price_range { minimum_price { regular_price { value currency } discount { amount_off percent_off } final_price { value currency } } } reservation_price ... on SimpleProduct { capacidad_label talla_label } ... on BundleProduct { items { uid type title options { uid quantity price price_type label product { uid name sku salable_quantity __typename } } } } } ... on BundleCartItem { bundle_options { uid label type values { uid id label price quantity } } } prices { row_total_including_tax { value currency } } errors { code message } } applied_coupons { code } applied_gift_cards { applied_balance { value currency } code current_balance { value currency } multiple_uses } available_payment_methods { code title cards_logos { url } paycomet_params { card_holder_name date_month date_year pa_number cvc2 jet_id payment_error_message jetIframe_script cards_logos { url } } instantcredit_params { active ic_script ic_configuration ic_simulator cards_logos { url } } waylet_params { cards_logos { url } } } billing_address { city firstname lastname postcode street telephone country { code label } region { code label } } shipping_addresses { firstname lastname street city telephone region { code label } country { code label } available_shipping_methods { available carrier_code carrier_title error_message method_code amount { currency value } price_excl_tax { value currency } price_incl_tax { value currency } } selected_shipping_method { carrier_code carrier_title method_code amount { value currency } } } prices { grand_total { value currency } subtotal_including_tax { currency value } subtotal_with_discount_excluding_tax { currency value } discounts { label amount { currency value } } grand_total_excluding_tax { currency value } vat_breakdown { tax_percentage tax_base { value currency } tax { value currency } total_including_tax { value currency } } applied_taxes { label amount { value currency } } } } } } ` const data = await RepsolStore.fetchData(query) return data }, setPaymentMethod: async function(code) { const CART_ID = localStorage?.cartId ? JSON.parse(localStorage.getItem('cartId'))?.id : undefined const query = ` mutation { setPaymentMethodOnCart( input: { cart_id: "${CART_ID}" payment_method: { code: "${code}" } } ) { cart { id email estimate { product { name sku virtual_product } estimate } items { id uid quantity name product { url_key name h1_label sku parent_sku stock_status salable_quantity category_ids{ id name } manufacturer_label thumbnail { url } price_range { minimum_price { regular_price { value currency } discount { amount_off percent_off } final_price { value currency } } } reservation_price ... on SimpleProduct { capacidad_label talla_label } ... on BundleProduct { items { uid type title options { uid quantity price price_type label product { uid name sku salable_quantity __typename } } } } } ... on BundleCartItem { bundle_options { uid label type values { uid id label price quantity } } } prices { row_total_including_tax { value currency } } errors { code message } } applied_coupons { code } applied_gift_cards { applied_balance { value currency } code current_balance { value currency } multiple_uses } available_payment_methods { code title cards_logos { url } paycomet_params { card_holder_name date_month date_year pa_number cvc2 jet_id payment_error_message jetIframe_script cards_logos { url } } instantcredit_params { active ic_script ic_configuration ic_simulator cards_logos { url } } waylet_params { cards_logos { url } } } billing_address { city firstname lastname postcode street telephone country { code label } region { code label } } shipping_addresses { firstname lastname street city telephone region { code label } country { code label } available_shipping_methods { available carrier_code carrier_title error_message method_code amount { currency value } price_excl_tax { value currency } price_incl_tax { value currency } } selected_shipping_method { carrier_code carrier_title method_code amount { value currency } } } prices { grand_total { value currency } subtotal_including_tax { currency value } subtotal_with_discount_excluding_tax { currency value } discounts { label amount { currency value } } grand_total_excluding_tax { currency value } vat_breakdown { tax_percentage tax_base { value currency } tax { value currency } total_including_tax { value currency } } applied_taxes { label amount { value currency } } } } } } ` const data = await RepsolStore.fetchData(query) return data }, setShippingAddressWithId: async function(id) { const CART_ID = localStorage?.cartId ? JSON.parse(localStorage.getItem('cartId'))?.id : undefined const query = ` mutation { setShippingAddressesOnCart( input: { cart_id: "${CART_ID}" shipping_addresses: { customer_address_id: ${id} } } ) { cart { id email estimate { product { name sku virtual_product } estimate } items { id uid quantity name product { url_key name h1_label sku parent_sku stock_status salable_quantity category_ids{ id name } manufacturer_label thumbnail { url } price_range { minimum_price { regular_price { value currency } discount { amount_off percent_off } final_price { value currency } } } reservation_price ... on SimpleProduct { capacidad_label talla_label } ... on BundleProduct { items { uid type title options { uid quantity price price_type label product { uid name sku salable_quantity __typename } } } } } ... on BundleCartItem { bundle_options { uid label type values { uid id label price quantity } } } prices { row_total_including_tax { value currency } } errors { code message } } applied_coupons { code } applied_gift_cards { applied_balance { value currency } code current_balance { value currency } multiple_uses } available_payment_methods { code title cards_logos { url } paycomet_params { card_holder_name date_month date_year pa_number cvc2 jet_id payment_error_message jetIframe_script cards_logos { url } } instantcredit_params { active ic_script ic_configuration ic_simulator cards_logos { url } } waylet_params { cards_logos { url } } } billing_address { city firstname lastname postcode street telephone country { code label } region { code label } } shipping_addresses { firstname lastname street city telephone region { code label } country { code label } available_shipping_methods { available carrier_code carrier_title error_message method_code amount { currency value } price_excl_tax { value currency } price_incl_tax { value currency } } selected_shipping_method { carrier_code carrier_title method_code amount { value currency } } } prices { grand_total { value currency } subtotal_including_tax { currency value } subtotal_with_discount_excluding_tax { currency value } discounts { label amount { currency value } } grand_total_excluding_tax { currency value } vat_breakdown { tax_percentage tax_base { value currency } tax { value currency } total_including_tax { value currency } } applied_taxes { label amount { value currency } } } } } } ` const data = await RepsolStore.fetchData(query) return data }, // Get Customer getCustomer: async function() { const query = ` query { customer { firstname lastname suffix email addresses { id firstname lastname street city region { region_code region } postcode country_code country { country_code country_name } telephone region_id default_shipping default_billing } } } ` const data = await RepsolStore.fetchData(query) return data }, getPaymentMethods: async function() { const CART_ID = localStorage?.cartId ? JSON.parse(localStorage.getItem('cartId'))?.id : undefined const query = ` query { cart( cart_id: "${CART_ID}") { available_payment_methods { code title cards_logos { url } paycomet_params { card_holder_name date_month date_year pa_number cvc2 jet_id payment_error_message jetIframe_script cards_logos { url } } instantcredit_params { active ic_script ic_configuration ic_simulator cards_logos { url } } waylet_params { cards_logos { url } } } } } ` const data = await RepsolStore.fetchData(query) return data }, addNewShippingAddress: async function(address) { const CART_ID = localStorage?.cartId ? JSON.parse(localStorage.getItem('cartId'))?.id : undefined const { firstname = '', lastname = '', company = '', address1 = '', address2 = '', street = '', city = '', region = '', region_id = '', postcode = '', country_code = '', telephone = '', document = '', default_shipping = '', default_billing = '' } = address ?? {} const query = ` mutation { createCustomerAddress( input: { country_code: ${country_code} street: ["${address1}", "${address2}"] telephone: "${telephone}" postcode: "${postcode}" city: "${city}" firstname: "${firstname}" lastname: "${lastname}" vat_id: "${document}" default_shipping: ${default_shipping} default_billing: ${default_billing} region: { region_id: ${region_id} } } ) { id country_code street telephone postcode city vat_id default_shipping default_billing region { region region_code } } } ` const data = await RepsolStore.fetchData(query) return data }, removeAddressWithId: async function(id) { const CART_ID = localStorage?.cartId ? JSON.parse(localStorage.getItem('cartId'))?.id : undefined const query = ` mutation { deleteCustomerAddress(id: ${id}) } ` const data = await RepsolStore.fetchData(query) return data }, setBillingAddress: async function(address) { const CART_ID = localStorage?.cartId ? JSON.parse(localStorage.getItem('cartId'))?.id : undefined const { firstname = '', lastname = '', company = '', address1 = '', address2 = '', street = '', city = '', region = '', region_id = '', postcode = '', country_code = '', telephone = '', document = '', save = '' } = address ?? {} const query = ` mutation { setBillingAddressOnCart( input: { cart_id: "${CART_ID}" billing_address: { address: { firstname: "${firstname}" lastname: "${lastname}" company: "${company}" street: ["${address1}", "${address2}"] city: "${city}" region: "" region_id: "${region_id}" postcode: "${postcode}" country_code: "${country_code}" telephone: "${telephone}" save_in_address_book: ${save} } } } ) { cart { billing_address { firstname lastname company street city postcode telephone region { code label } country { code label } } } } } ` const data = await RepsolStore.fetchData(query) return data }, setBillingAddressSameShipping: async function() { const CART_ID = localStorage?.cartId ? JSON.parse(localStorage.getItem('cartId'))?.id : undefined const query = ` mutation { setBillingAddressOnCart( input: { cart_id: "${CART_ID}", billing_address: { same_as_shipping: true } } ) { cart { id email estimate { product { name sku virtual_product } estimate } items { id uid quantity name product { url_key name h1_label sku parent_sku stock_status salable_quantity category_ids{ id name } manufacturer_label thumbnail { url } price_range { minimum_price { regular_price { value currency } discount { amount_off percent_off } final_price { value currency } } } reservation_price ... on SimpleProduct { capacidad_label talla_label } } prices { row_total_including_tax { value currency } } errors { code message } } applied_coupons { code } applied_gift_cards { applied_balance { value currency } code current_balance { value currency } multiple_uses } available_payment_methods { code title cards_logos { url } paycomet_params { card_holder_name date_month date_year pa_number cvc2 jet_id payment_error_message jetIframe_script cards_logos { url } } instantcredit_params { active ic_script ic_configuration ic_simulator cards_logos { url } } waylet_params { cards_logos { url } } } billing_address { city firstname lastname postcode street telephone country { code label } region { code label } } shipping_addresses { firstname lastname street city telephone region { code label } country { code label } available_shipping_methods { available carrier_code carrier_title error_message method_code amount { currency value } price_excl_tax { value currency } price_incl_tax { value currency } } selected_shipping_method { carrier_code carrier_title method_code amount { value currency } } } prices { grand_total { value currency } subtotal_including_tax { currency value } subtotal_with_discount_excluding_tax { currency value } discounts { label amount { currency value } } grand_total_excluding_tax { currency value } vat_breakdown { tax_percentage tax_base { value currency } tax { value currency } total_including_tax { value currency } } applied_taxes { label amount { value currency } } } } } } ` const data = await RepsolStore.fetchData(query) return data }, paycometPlaceOrder: async function(method) { const CART_ID = localStorage?.cartId ? JSON.parse(localStorage.getItem('cartId'))?.id : undefined let code = method['code'] let paytpvToken = method['paytpvToken'] !== undefined ? method['paytpvToken'] : '' let comment = $('textarea[name="comments"]').val() let attrToMagento = StoreCheckout.salesAttributesMagento(); const query = ` mutation { placeOrder( input: { cart_id: "${CART_ID}" comment: "${comment}" utm_campaign: "${attrToMagento.utm_campaign}" utm_content: "${attrToMagento.utm_content}" utm_medium: "${attrToMagento.utm_medium}" utm_source: "${attrToMagento.utm_source}" utm_term: "${attrToMagento.utm_term}" optanon_consent: "${attrToMagento.optanon_consent}" origin_source: "${attrToMagento.origin_source}" url_procedencia__c: "${attrToMagento.url_procedencia__c}" landing_page__c: "${attrToMagento.landing_page__c}" payment_method: { code: "${code}" additional_data: { save_card: 0 paycomet_card: "" paycomet_jet_token: "${paytpvToken}" } } } ) { order { order_number order_id } payment_form { url error } } } ` const data = await RepsolStore.fetchData(query) return data }, addCoupon: async function(code) { const CART_ID = localStorage?.cartId ? JSON.parse(localStorage.getItem('cartId'))?.id : undefined const query = ` mutation { applyCouponToCart( input: { cart_id: "${CART_ID}", coupon_code: "${code}" } ) { cart { id email estimate { product { name sku virtual_product } estimate } items { id uid quantity name parent_url_key product { url_key name h1_label sku parent_sku stock_status salable_quantity category_ids{ id name } manufacturer_label thumbnail { url } price_range { minimum_price { regular_price { value currency } discount { amount_off percent_off } final_price { value currency } } } reservation_price ... on SimpleProduct { capacidad_label talla_label } ... on BundleProduct { items { uid type title options { uid quantity price price_type label product { uid name sku salable_quantity __typename } } } } } ... on BundleCartItem { bundle_options { uid label type values { uid id label price quantity } } } prices { row_total_including_tax { value currency } } errors { code message } } applied_coupons { code } applied_gift_cards { applied_balance { value currency } code current_balance { value currency } multiple_uses } available_payment_methods { code title cards_logos { url } paycomet_params { card_holder_name date_month date_year pa_number cvc2 jet_id payment_error_message jetIframe_script cards_logos { url } } instantcredit_params { active ic_script ic_configuration ic_simulator cards_logos { url } } waylet_params { cards_logos { url } } } billing_address { city firstname lastname postcode street telephone country { code label } region { code label } } shipping_addresses { firstname lastname street city telephone region { code label } country { code label } available_shipping_methods { available carrier_code carrier_title error_message method_code amount { currency value } price_excl_tax { value currency } price_incl_tax { value currency } } selected_shipping_method { carrier_code carrier_title method_code amount { value currency } } } prices { grand_total { value currency } subtotal_including_tax { currency value } subtotal_with_discount_excluding_tax { currency value } discounts { label amount { currency value } } grand_total_excluding_tax{ currency value } vat_breakdown { tax_percentage tax_base { value currency } tax { value currency } total_including_tax { value currency } } applied_taxes { label amount { value currency } } } } } } ` const data = await RepsolStore.fetchData(query) return data }, removeCoupons: async function() { const CART_ID = localStorage?.cartId ? JSON.parse(localStorage.getItem('cartId'))?.id : undefined const query = ` mutation { removeCouponFromCart( input: { cart_id: "${CART_ID}" } ) { cart { id email estimate { product { name sku virtual_product } estimate } items { id uid quantity name parent_url_key product { url_key name h1_label sku parent_sku stock_status salable_quantity category_ids{ id name } manufacturer_label thumbnail { url } price_range { minimum_price { regular_price { value currency } discount { amount_off percent_off } final_price { value currency } } } reservation_price ... on SimpleProduct { capacidad_label talla_label } ... on BundleProduct { items { uid type title options { uid quantity price price_type label product { uid name sku salable_quantity __typename } } } } } ... on BundleCartItem { bundle_options { uid label type values { uid id label price quantity } } } prices { row_total_including_tax { value currency } } errors { code message } } applied_coupons { code } applied_gift_cards { applied_balance { value currency } code current_balance { value currency } multiple_uses } available_payment_methods { code title cards_logos { url } paycomet_params { card_holder_name date_month date_year pa_number cvc2 jet_id payment_error_message jetIframe_script cards_logos { url } } instantcredit_params { active ic_script ic_configuration ic_simulator cards_logos { url } } waylet_params { cards_logos { url } } } billing_address { city firstname lastname postcode street telephone country { code label } region { code label } } shipping_addresses { firstname lastname street city telephone region { code label } country { code label } available_shipping_methods { available carrier_code carrier_title error_message method_code amount { currency value } price_excl_tax { value currency } price_incl_tax { value currency } } selected_shipping_method { carrier_code carrier_title method_code amount { value currency } } } prices { grand_total { value currency } subtotal_including_tax { currency value } subtotal_with_discount_excluding_tax { currency value } discounts { label amount { currency value } } grand_total_excluding_tax{ currency value } vat_breakdown { tax_percentage tax_base { value currency } tax { value currency } total_including_tax { value currency } } applied_taxes { label amount { value currency } } } } } } ` const data = await RepsolStore.fetchData(query) return data }, addGiftCard: async function(code) { const CART_ID = localStorage?.cartId ? JSON.parse(localStorage.getItem('cartId'))?.id : undefined const query = ` mutation { applyGiftCardToCart( input: { cart_id: "${CART_ID}", gift_card_code: "${code}" } ) { cart { id email estimate { product { name sku virtual_product } estimate } items { id uid quantity name parent_url_key product { url_key name h1_label sku parent_sku stock_status salable_quantity category_ids{ id name } manufacturer_label thumbnail { url } price_range { minimum_price { regular_price { value currency } discount { amount_off percent_off } final_price { value currency } } } reservation_price ... on SimpleProduct { capacidad_label talla_label } } prices { row_total_including_tax { value currency } } errors { code message } } applied_coupons { code } applied_gift_cards { applied_balance { value currency } code current_balance { value currency } multiple_uses } available_payment_methods { code title cards_logos { url } paycomet_params { card_holder_name date_month date_year pa_number cvc2 jet_id payment_error_message jetIframe_script cards_logos { url } } instantcredit_params { active ic_script ic_configuration ic_simulator cards_logos { url } } waylet_params { cards_logos { url } } } billing_address { city firstname lastname postcode street telephone country { code label } region { code label } } shipping_addresses { firstname lastname street city telephone region { code label } country { code label } available_shipping_methods { available carrier_code carrier_title error_message method_code amount { currency value } price_excl_tax { value currency } price_incl_tax { value currency } } selected_shipping_method { carrier_code carrier_title method_code amount { value currency } } } prices { grand_total { value currency } subtotal_including_tax { currency value } subtotal_with_discount_excluding_tax { currency value } discounts { label amount { currency value } } grand_total_excluding_tax{ currency value } vat_breakdown { tax_percentage tax_base { value currency } tax { value currency } total_including_tax { value currency } } applied_taxes { label amount { value currency } } } } } } ` const data = await RepsolStore.fetchData(query) return data }, removeGiftCard: async function(code) { const CART_ID = localStorage?.cartId ? JSON.parse(localStorage.getItem('cartId'))?.id : undefined const query = ` mutation { removeGiftCardFromCart( input: { cart_id: "${CART_ID}", gift_card_code: "${code}" } ) { cart { id email estimate { product { name sku virtual_product } estimate } items { id uid quantity name parent_url_key product { url_key name h1_label sku parent_sku stock_status salable_quantity category_ids{ id name } manufacturer_label thumbnail { url } price_range { minimum_price { regular_price { value currency } discount { amount_off percent_off } final_price { value currency } } } reservation_price ... on SimpleProduct { capacidad_label talla_label } } prices { row_total_including_tax { value currency } } errors { code message } } applied_coupons { code } applied_gift_cards { code } available_payment_methods { code title cards_logos { url } paycomet_params { card_holder_name date_month date_year pa_number cvc2 jet_id payment_error_message jetIframe_script cards_logos { url } } instantcredit_params { active ic_script ic_configuration ic_simulator cards_logos { url } } waylet_params { cards_logos { url } } } billing_address { city firstname lastname postcode street telephone country { code label } region { code label } } shipping_addresses { firstname lastname street city telephone region { code label } country { code label } available_shipping_methods { available carrier_code carrier_title error_message method_code amount { currency value } price_excl_tax { value currency } price_incl_tax { value currency } } selected_shipping_method { carrier_code carrier_title method_code amount { value currency } } } prices { grand_total { value currency } subtotal_including_tax { currency value } subtotal_with_discount_excluding_tax { currency value } discounts { label amount { currency value } } grand_total_excluding_tax{ currency value } vat_breakdown { tax_percentage tax_base { value currency } tax { value currency } total_including_tax { value currency } } applied_taxes { label amount { value currency } } } } } } ` const data = await RepsolStore.fetchData(query) return data }, getRegions: async function() { const CART_ID = localStorage?.cartId ? JSON.parse(localStorage.getItem('cartId'))?.id : undefined const query = ` query { countries { id full_name_locale available_regions { id code name } } } ` const data = await RepsolStore.fetchData(query) return data }, handleErrors: async function(errors) { const error = RepsolStoreErrors.checkHandledErrorType(errors) if(error === 'CART_OUTDATED') { await RepsolStore.handleOutdatedCart(); } if(error === 'CART_INACTIVE') { await RepsolStore.createNewCart(); } if(error === 'CUSTOMER_TOKEN_OUTDATED') { await RepsolStore.loginUserOnMagento(); } if(error === 'PLACE_ORDER_ERROR') { StoreCheckout.showPlacerOrderError(errors); } if(error === 'UNHANDLED_ERROR') { RepsolStore.showUnhandledErrorMessage(); } }, createNewCart: async function() { const response = await RepsolStore.createEmptyCart(); const cartId = response?.data?.createEmptyCart; RepsolStore.saveCartIdToLocalStorage(cartId); const cartResponse = await RepsolStore.getCart(); const cart = cartResponse?.data?.cart; RepsolStore.saveCartToLocalStorage(cart); }, restoreUserCart: async function() { try { const isLoggedOnMagento = await RepsolLoginStore.isLoggedOnMagento(); if (!isLoggedOnMagento) { await miniCart.loginUserOnMagento(); } const customerCartResponse = await RepsolStore.customerCart() const cart = customerCartResponse?.data?.customerCart const cartId = customerCartResponse?.data?.customerCart?.id RepsolStore.saveCartIdToLocalStorage(cartId) RepsolStore.saveCartToLocalStorage(cart) return cart } catch(error) { miniCart.showUnhandledErrorMessage(); } }, restoreGuestCart: async function() { try { const emptyCartResponse = await RepsolStore.createEmptyCart(); const cartId = emptyCartResponse?.data?.createEmptyCart; RepsolStore.saveCartIdToLocalStorage(cartId); const cartStorage = localStorage?.cart ? JSON.parse(localStorage.getItem('cart')) : undefined; const products = cartStorage?.cart?.items || cartStorage?.items; const items = []; if(cartStorage && products) { products.forEach((item) => { itemObj = { sku: item.product.sku, quantity: item.quantity } items.push(itemObj); }) const addProductsResponse = await RepsolStore.addMultipleProductsToCart(items); const cart = addProductsResponse?.data?.addProductsToCart?.cart; RepsolStore.saveCartToLocalStorage(cart); } } catch(error) { RepsolStore.showUnhandledErrorMessage(); } }, handleOutdatedCart: async function() { const isLogged = Repsol.utils.getCookie('isLogged'); if(isLogged === 'true') { await RepsolStore.restoreUserCart(); } else { await RepsolStore.restoreGuestCart(); } }, loginUserOnMagento: async function() { const magentoLoginResponse = await RepsolLoginStore.magentoLogin(); const errorCode = magentoLoginResponse?.errorCode; if (errorCode === 0) { const customerToken = magentoLoginResponse?.customerToken; localStorage.setItem("ct", JSON.stringify(customerToken)); } return magentoLoginResponse; }, saveCartToLocalStorage: function(cart) { localStorage.setItem('cart', JSON.stringify(cart)); }, saveCartIdToLocalStorage: function(cartId) { let date = new Date() date.setDate(date.getDate() + 1); localStorage.setItem("cartId", `{"id": "${cartId}", "expDate":${date.getTime()}}`) }, showUnhandledErrorMessage: function() { const errorMsg = 'Algo salió mal. No hemos podido realizar la acción. Por favor, inténtalo de nuevo más tarde.'; RpAlert.msgError(`${errorMsg}.`); Repsol.Analytics.Store.errorRpAlert(errorMsg); var myObj = $(".store-minicart-component"); var params = { error_type: errorMsg, error_description: errorMsg, }; Repsol.AnalyticsRomProd.errorRomProd(myObj, params); }, showTopErrorMessage: function(errorMsg) { RpAlert.msgError(`${errorMsg}.`); RepsolRegister.analytics.Store.errorRpAlert(errorMsg); var params = { error_type: errorMsg, error_description: errorMsg, }; Repsol.AnalyticsRomProd.errorRomProd(errorMsg, params); }, generateDAMImageURL: function(item) { const capacidadFromParent = ["125ml", "1l"]; const tallaFromParent = []; const weightFromParent = ["1"] let capacity = ''; let size = ''; const product = item?.product ? item.product : item; const sizes = { capacidad: product?.capacidad_label ? product?.capacidad_label.replace(' ', '').toLowerCase() : undefined, talla: product?.talla_label ? product?.talla_label.replace(' ', '').toLowerCase() : undefined, } const productURLKey = product?.url_key; if(productURLKey) { const url_key = productURLKey.toLowerCase(); const URLKeyArray = url_key.split('-'); let damImageURL; let lastArrayItem = URLKeyArray[URLKeyArray.length - 1]; let fixedURLKey = url_key; capacity = sizes?.capacidad ? sizes?.capacidad.length : undefined if(capacity != undefined && capacity > 0) { if(lastArrayItem == sizes?.capacidad) { capacidadFromParent.map(str => { if(lastArrayItem == str) { const lastItem = URLKeyArray.splice(-1, 1); fixedURLKey = URLKeyArray.join('-'); } }); } } size = sizes?.talla ? sizes?.talla.length : undefined if(size != undefined && size > 0) { if(lastArrayItem == sizes?.talla) { const lastItem = URLKeyArray.splice(-1, 1); fixedURLKey = URLKeyArray.join('-'); } } weightFromParent.map(str => { if(lastArrayItem == str) { const lastItem = URLKeyArray.splice(-1, 1); fixedURLKey = URLKeyArray.join('-'); } }); if(fixedURLKey) { damImageURL = `/content/dam/repsol-ecommerce/tienda/productos/${fixedURLKey.charAt(0)}/${fixedURLKey}/${fixedURLKey}-001.jpg`; return damImageURL; } } else { return undefined; } }, getStock : async (urlKey) => { let url = `/bin/repsol-ecommerce/store/stock.json?url_key=${urlKey}` const headers = { 'Content-Type': 'application/json', 'Accept': 'application/json', } const options = { method: 'GET', headers: headers } try { const response = await fetch(url, options) if (!response.ok) { throw new Error(`Error al obtener los datos: ${response.status} ${response.statusText}`) } const data = await response.json() return data } catch (error) { if (error instanceof TypeError) { console.error('Error de red:', error.message) } else if (error instanceof SyntaxError) { console.error('Error en la respuesta del servidor:', error.message) } else if (error instanceof Error) { console.error('Ha habido un error:', error.message) } else { console.error('Error desconocido:', error) } return {} } }, getVariant: (item) =>{ let variant = ''; if (item.product.capacidad_label && item.product.capacidad_label.length > 0) { variant = item.product.capacidad_label; }else if (item.product.talla_label && item.product.talla_label.length > 0) { variant = item.product.talla_label; } return variant; }, getProductDetailPage: (productDetailPage, urlKey) => { if (productDetailPage) { if (productDetailPage.indexOf(".html") != -1) { let productDetailPageSplit = productDetailPage.split(".html") productDetailPage = productDetailPageSplit[0] + "." + urlKey + ".html" + (productDetailPageSplit[1] ? productDetailPageSplit[1] : '') } else { productDetailPage += urlKey } } return productDetailPage; }, calculateProductDiscount: (regularPrice, finalPrice) =>{ function roundByDecimal(number) { const decimal = number - Math.floor(number); if(decimal >= 0.5){ return Math.ceil(number); } else { return Math.floor(number); } } let discount = 0; if(Number(regularPrice) > Number(finalPrice)) { const discountDecimal = Number(100 - ((finalPrice * 100) / regularPrice)); discount = roundByDecimal(discountDecimal); } return discount; } } const RepsolStoreErrors = { userErrors: Object.freeze({ '1035': 'PRODUCT_OUT_OF_STOCK', '1038': 'PRODUCT_WITH_STOCK_ERROR', '1040': 'SHIPPING_ADDRESS_MULTIPLE_SELECTED', '1041': 'ADDRESS_NOT_VALID', '1042': 'GUEST_CHECKOUT_NOT_AVAILABLE', '1047': 'REGION_ID_NOT_DEFINE', '1120': 'PRODUCT_NOT_AVAILABLE', '1123': 'SHIPPING_ADDRESS_NOT_AVAILABLE', '1124': 'SHIPPING_ADDRESS_NOT_SELECTED', '1139': 'PAYMENT_METHOD_NOT_AVAILABLE', '1150': 'PLACE_ORDER_SHIPPING_ERROR', }), handledErrors: Object.freeze({ '3000': 'CART_ERROR', '3001': 'PRODUCT_SKU_ERROR', '3004': 'CART_OUTDATED', '3005': 'TOKEN_OUTDATED', '3006': 'PLACE_ORDER_ERROR', '3009': 'PAYMENT_METHOD_RETRIEVE_ERROR', '3012': 'ONLY_LOGGED_USER_ACTION_ALLOWED', '3013': 'ADDRESS_ALREADY_EXISTS', '3060': 'UPDATED_PRODUCT_STOCK_ERROR', '3023': 'ADDRESS_ALREADY_EXIST', '3025': 'INACTIVE_CART', '3035': 'SHIPPING_ADDRESS_NOT_SELECTED', '3055': 'ACCOUNT_DISABLED', '3056': 'ACCOUNT_DISABLED_TEMPORATILY', '3057': 'ACCOUNT_DISABLED_TEMPORATILY', '3062': 'COUPON_NOT_VALID', '3065': 'CART_INACTIVE', '3066': 'GIFT_CARD_NOT_VALID', '3067': 'COUPON_NOT_VALID', '3068': 'COUPON_NOT_ACTIVE', '3069': 'COUPON_HAS_BEEN_USED', '3070': 'COUPON_HAS_BEEN_USED_MANY_TIMES', '3071': 'COUPON_HAS_BEEN_USED_BY_CUSTOMER', '3072': 'COUPON_NOT_VALID_FOR_ITEMS', '3073': 'COUPON_NOT_VALID_FOR_ITEMS', '3074': 'GIFT_CARD_NOT_FOUND', '3075': 'GIFT_CARD_NOT_ENABLED', '3076': 'GIFT_CARD_IS_EXPIRED', '3077': 'GIFT_CARD_HAS_BEEN_USED', '3078': 'GIFT_CARD_IS_EXPIRED', '3080': 'GIFT_CARD_INSUFFICIENT_MINIMUM_AMOUNT' }), errorToken: Object.freeze({ '3005': 'CUSTOMER_TOKEN_OUTDATED', '3012': 'CUSTOMER_TOKEN_OUTDATED', '3055': 'CUSTOMER_TOKEN_OUTDATED', '3056': 'CUSTOMER_TOKEN_OUTDATED', '3057': 'CUSTOMER_TOKEN_OUTDATED', }), checkHandledErrorType: function(errors) { const error = errors?.[0] const errorCode = error?.code_number if (RepsolStoreErrors.handledErrors.hasOwnProperty(errorCode)) { if (RepsolStoreErrors.errorToken.hasOwnProperty(errorCode)) { return RepsolStoreErrors.errorToken[errorCode]; } else { return RepsolStoreErrors.handledErrors[errorCode]; } } else { return 'UNHANDLED_ERROR'; } }, checkUserErrorTypes: function(errors) { const userErrorsArray = []; errors.forEach((error) => { if (RepsolStoreErrors.userErrors.hasOwnProperty(error.code_number)) { userErrorsArray.push(RepsolStoreErrors.userErrors[error.code_number]); } }); return userErrorsArray; }, getCouponErrorMsg: (component, errors) => { const errorCode = errors?.[0]?.code_number; const error = RepsolStoreErrors.checkHandledErrorType(errors); const couponNotValidErrorMsg = component.getAttribute('data-coupon-not-valid-error'); const couponNotActiveErrorMsg = component.getAttribute('data-coupon-not-active-error'); const couponHasBeenUsedErrorMsg = component.getAttribute('data-coupon-has-been-used-error'); const couponHasBeenUsedManyTimesErrorMsg = component.getAttribute('data-coupon-has-been-used-many-times-error'); const couponHasBeenUsedByCustomerErrorMsg = component.getAttribute('data-coupon-has-been-used-by-customer-error'); const couponNotValidForItemsErrorMsg = component.getAttribute('data-coupon-not-valid-for-items-error'); const couponNotFoundErrorMsg = component.getAttribute('data-coupon-not-found-error'); const couponNotEnabledErrorMsg = component.getAttribute('data-coupon-not-enabled-error'); const couponIsExpiredErrorMsg = component.getAttribute('data-coupon-is-expired-error'); const couponInsufficientMinimunAmountErrorMsg = component.getAttribute('data-coupon-insufficient-minimun-amount-error'); let couponErrorMsg = ''; switch(error){ case 'GIFT_CARD_NOT_VALID': case 'COUPON_NOT_VALID': couponErrorMsg = couponNotValidErrorMsg; break; case 'COUPON_NOT_ACTIVE': couponErrorMsg = couponNotActiveErrorMsg; break; case 'COUPON_HAS_BEEN_USED': case 'GIFT_CARD_HAS_BEEN_USED': couponErrorMsg = couponHasBeenUsedErrorMsg; break; case 'COUPON_HAS_BEEN_USED_MANY_TIMES': couponErrorMsg = couponHasBeenUsedManyTimesErrorMsg; break; case 'COUPON_HAS_BEEN_USED_BY_CUSTOMER': couponErrorMsg = couponHasBeenUsedByCustomerErrorMsg; break; case 'COUPON_NOT_VALID_FOR_ITEMS': couponErrorMsg = couponNotValidForItemsErrorMsg; if(errorCode == '3073'){ const errorMsg = errors?.[0]?.message; const errorMsgSplit = errorMsg.split(':'); couponErrorMsg += `: ${errorMsgSplit?.[1]?.trim()}`; }else{ couponErrorMsg += '.'; } break; case 'GIFT_CARD_NOT_FOUND': couponErrorMsg = couponNotFoundErrorMsg; break; case 'GIFT_CARD_NOT_ENABLED': couponErrorMsg = couponNotEnabledErrorMsg; break; case 'GIFT_CARD_IS_EXPIRED': couponErrorMsg = couponIsExpiredErrorMsg; break; case 'GIFT_CARD_INSUFFICIENT_MINIMUM_AMOUNT': couponErrorMsg = couponInsufficientMinimunAmountErrorMsg; break; } return couponErrorMsg; } } Repsol.analyticSetDataPosition = { init: function() { const ecommercePage = document.querySelector('.rp-ecommerce-page'); const components = ecommercePage.querySelectorAll('[data-component]'); this.setDataPositionWithoutParent(components); this.setDataPositionWithParent(components); this.setDataPositionToAnalyticElement(components); }, setDataPositionWithoutParent: function(components) { const noParent = Array.from(components).filter(component => $(component).parents('[data-component]').length == 0); console.log('Parents:', noParent); noParent.forEach((component, index) => { const position = index + 1; const componentName = component.getAttribute('data-component'); component.dataset.position = position; component.dataset.componentParent = `${componentName}[${position}]`; }); }, setDataPositionWithParent: function(components) { components.forEach(component => { const children = [...component.querySelectorAll('[data-component]')]; const componentParentName = component.getAttribute('data-component'); const componentParentPosition = component.getAttribute('data-position'); if(children.length > 0) { children.forEach((child, index) => { const position = index + 1; const componentName = child.getAttribute('data-component'); const componentParent = `${componentParentName}[${componentParentPosition}] ${componentName}[${position}]`; child.dataset.position = position; child.dataset.componentParent = componentParent; }); } }); }, setDataPositionToAnalyticElement: function(components) { components.forEach(component => { const links = [...component.querySelectorAll('.rp-link-click')]; const componentParentName = component.getAttribute('data-component-parent'); if(links.length > 0) { links.forEach((link, index) => { const position = index + 1; const componentClass = link.getAttribute('class'); const componentParent = `${componentParentName} ${componentClass}[${position}]`; link.dataset.position = position; link.dataset.componentParent = componentParent; }); } }); } } Repsol.DropdownSelect = { event : document.createEvent('Event'), init:function(){ Repsol.DropdownSelect.event.initEvent('rp-select-change', true, true); Repsol.DropdownSelect.events(); }, events:function(){ $(document).on('click','.rp-dropdown.select-mode:not(.rp-disabled) .dropdown-item', function(){ Repsol.DropdownSelect.setValue($(this)); document.dispatchEvent(Repsol.select.event); let dropdownToggle = $(this).closest(".rp-dropdown").find(".dropdown-toggle-custom").length > 0 ? $(this).closest(".rp-dropdown").find(".dropdown-toggle-custom") : $(this).closest(".rp-dropdown").find(".dropdown-toggle"); dropdownToggle.trigger('rp-change'); }); $(document).on("blur", ".dropdown.select-mode:not(.dropdown-product-list-search):not(.not-blur-validation) .dropdown-toggle", function () { Repsol.forms.validate.SelectedDropdown($(this)); }); $(document).on("rp-change", ".dropdown.select-mode .dropdown-toggle", function () { Repsol.forms.validate.SelectedDropdown($(this)); }); }, setValue: function(obj){ const valueText = obj.text(); const value = obj.attr("data-value"); const objDrop = obj.parents(".rp-dropdown").find(".dropdown-toggle-custom").length > 0 ? obj.parents(".rp-dropdown").find(".dropdown-toggle-custom") : obj.parents(".rp-dropdown").find(".dropdown-toggle"); objDrop.attr("data-value", value); objDrop.find('.text').text(valueText); obj.parents(".rp-dropdown").trigger("change"); }, validateDropdown: function(obj) { } } Repsol.analyticSetDataPosition = { init: function() { const ecommercePage = document.querySelector('.rp-ecommerce-page'); const components = ecommercePage.querySelectorAll('[data-component]'); this.setDataPositionWithoutParent(components); this.setDataPositionWithParent(components); this.setDataPositionToAnalyticElement(components); }, setDataPositionWithoutParent: function(components) { const noParent = Array.from(components).filter(component => $(component).parents('[data-component]').length == 0); console.log('Parents:', noParent); noParent.forEach((component, index) => { const position = index + 1; const componentName = component.getAttribute('data-component'); component.dataset.position = position; component.dataset.componentParent = `${componentName}[${position}]`; }); }, setDataPositionWithParent: function(components) { components.forEach(component => { const children = [...component.querySelectorAll('[data-component]')]; const componentParentName = component.getAttribute('data-component'); const componentParentPosition = component.getAttribute('data-position'); if(children.length > 0) { children.forEach((child, index) => { const position = index + 1; const componentName = child.getAttribute('data-component'); const componentParent = `${componentParentName}[${componentParentPosition}] ${componentName}[${position}]`; child.dataset.position = position; child.dataset.componentParent = componentParent; }); } }); }, setDataPositionToAnalyticElement: function(components) { components.forEach(component => { const links = [...component.querySelectorAll('.rp-link-click')]; const componentParentName = component.getAttribute('data-component-parent'); if(links.length > 0) { links.forEach((link, index) => { const position = index + 1; const componentClass = link.getAttribute('class'); const componentParent = `${componentParentName} ${componentClass}[${position}]`; link.dataset.position = position; link.dataset.componentParent = componentParent; }); } }); } } Repsol.DropdownCommonBehavior = { lastItemWithMouse: '', mouseMoveOccurred : false, currentIndex : undefined, init:function(){ this.selectByLetter(); this.selectWithArrows(); this.dropdownAction(); this.addedAttributeHtml(); }, addedAttributeHtml: function () { var dropdownFound = $('.rp-ecommerce-page form .dropdown-toggle'); if (dropdownFound) { dropdownFound.attr('tabindex', '0'); } }, selectByLetter: function (){ var containerList; var words; var pressedLastLetter; $(document).on('keyup', '.dropdown', function(event) { Repsol.DropdownCommonBehavior.mouseMoveOccurred = false; containerList = $(document).find('.dropdown-menu.show'); words = containerList.find('.dropdown-item'); var pressedLetter = String.fromCharCode(event.which).toLowerCase(); if (/^[aA-zZ]$/.test(pressedLetter)) { if(pressedLetter !== pressedLastLetter) { pressedLastLetter = pressedLetter; Repsol.DropdownCommonBehavior.searchLetter(words,pressedLetter,containerList); } else { var nextIndex = ( Repsol.DropdownCommonBehavior.currentIndex + 1); Repsol.DropdownCommonBehavior.currentIndex = nextIndex; itemFound = $(words[nextIndex]); pressedLastLetter = itemFound.text().trim().toLowerCase().charAt(0); if(itemFound){ if(pressedLastLetter == pressedLetter){ Repsol.DropdownCommonBehavior.activeItem(words,itemFound,containerList); } else Repsol.DropdownCommonBehavior.searchLetter(words,pressedLetter,containerList); } } } }); }, searchLetter: function(words,pressedLetter,containerList){ var itemFound = words.filter(function() { return $(this).text().trim().toLowerCase().startsWith(pressedLetter); }).first(); Repsol.DropdownCommonBehavior.currentIndex = words.index(itemFound); if (itemFound.length > 0) { Repsol.DropdownCommonBehavior.activeItem(words,itemFound,containerList); } }, activeItem: function (words,itemFound,containerList){ words.removeClass('active-dropdown-item'); $(itemFound).addClass('active-dropdown-item'); containerList.scrollTop(0); containerList.scrollTop(itemFound.position().top); }, selectWithArrows: function () { $(document).on('keyup', '.dropdown', function(event) { containerList = $(document).find('.dropdown-menu.show'); if (event.key === 'ArrowUp' || event.key === 'ArrowDown' ) { Repsol.DropdownCommonBehavior.mouseMoveOccurred = false; event.preventDefault(); var items = $('.dropdown-menu.show .dropdown-item'); var activeItem = $('.dropdown-menu.show .dropdown-item.active-dropdown-item'); if (Repsol.DropdownCommonBehavior.lastItemWithMouse != undefined) { activeItem = Repsol.DropdownCommonBehavior.lastItemWithMouse; } Repsol.DropdownCommonBehavior.lastItemWithMouse = undefined; var currentIndex = items.index(activeItem); var nextIndex; if (event.key === 'ArrowUp') { nextIndex = Math.max(0, currentIndex - 1); console.log("item actual: " + currentIndex); console.log("next item: " + nextIndex); } else if (event.key === 'ArrowDown') { nextIndex = Math.min(items.length - 1, currentIndex + 1); console.log(currentIndex); console.log(nextIndex); } activeItem.removeClass('active-dropdown-item'); items.eq(nextIndex).addClass('active-dropdown-item').focus(); containerList.scrollTop(0); containerList.scrollTop(items.eq(nextIndex).position().top); } if (event.key === 'Enter') { $('.dropdown-item.active-dropdown-item').click(); } }); }, dropdownAction:function() { var items; $("body").on('mousemove', function() { Repsol.DropdownCommonBehavior.mouseMoveOccurred = true; }); $('.dropdown-menu').on('mouseover', '.dropdown-item', function() { items= $(".dropdown-item"); if(Repsol.DropdownCommonBehavior.mouseMoveOccurred==true){ Repsol.DropdownCommonBehavior.lastItemWithMouse = $(".dropdown-menu").find(":hover"); Repsol.DropdownCommonBehavior.mouseMoveOccurred = false; items.each(function(){ if($(this).hasClass('active-dropdown-item')) { $(this).removeClass('active-dropdown-item'); } }); $(this).addClass('active-dropdown-item'); } // $(this).css('background-color', 'white') }); } } $(document).ready(function () { Repsol.DropdownCommonBehavior.init(); RepsolHeader.init(); RepsolCards.init(); RepsolLoginStore.init(); RepsolLanding.init(); RepsolEcommerce.utils.setPreviousUrlStore(); Repsol.utils.setOriginSource(); Repsol.analyticSetDataPosition.init(); Repsol.DropdownSelect.init(); }); RepsolEcommerce.forms = { init: function () { RepsolEcommerce.forms.events(); }, events: () =>{ document.querySelectorAll("textarea").forEach((element)=>{ element.addEventListener("input", () => { RepsolEcommerce.forms.countCharacters(element); }); }); let fields = ["[name='review-name']", "[name='review-title']", "[name='review-opinion']"]; fields.forEach((field) => { document.querySelector(field)?.addEventListener("blur", (e) =>{ let target = e.target; RepsolEcommerce.forms.hideErrors(target); }) }) let ratingInputs = document.querySelectorAll("input[name='rating']") ratingInputs.forEach((field) => { field.addEventListener("click", (e) =>{ let target = e.target; RepsolEcommerce.forms.hideErrors(target); }) }) }, countCharacters: (obj) =>{ let charCounter = obj.value.length; let rpInput = obj.closest(".rp-input-repsol") let counter = rpInput?.querySelector(".js-char-counter"); if(counter){ counter.textContent = charCounter; } }, hideErrors:(obj) =>{ const $parent = obj.closest(".cmp-form"); $parent.classList.remove('error'); let errors = $parent.querySelectorAll(".error-msg") errors.forEach((error) => { error.classList.add("d-none") }) }, setEmailSessionStore: (email) => { if (email) { sessionStorage.setItem('usr_email', email); } }, setPhoneSessionStore: (phone) => { if (phone) { const formattedPhone = `+34${phone}`; sessionStorage.setItem('usr_num', formattedPhone); } }, setEmailPhoneSessionStore: (email, phone) => { RepsolEcommerce.forms.setEmailSessionStore(email); RepsolEcommerce.forms.setPhoneSessionStore(phone); }, validateLengthPhone: function(input, maxLength) { if (input.value.length > maxLength) { input.value = input.value.slice(0, maxLength); } } } $(document).ready(function () { RepsolEcommerce.forms.init(); }) RepsolModal = { init: function () { RepsolModal.events(); }, events: function () { const closeModalElems = document.querySelectorAll('.js-close-modal'); closeModalElems.forEach((elem) => { elem.addEventListener('click', (ev) => { ev.preventDefault(); RepsolModal.closeModal(elem); }); }); const openModalElems = document.querySelectorAll('.js-open-modal'); openModalElems.forEach((elem) => { elem.addEventListener('click', (ev) => { if(!window.matchMedia("(min-width: 1024px)").matches && elem.classList.contains('open-modal-desktop')){ return; }else{ ev.preventDefault(); RepsolModal.openModal(elem); } }); }); }, openModal: (elem) => { const idModal = elem.getAttribute('data-target'); const modal = document.getElementById(idModal); if(modal){ $(modal).modal('show'); } }, closeModal: (elem) => { let modal = elem.closest(".modal"); if (modal) { $(modal).modal("hide"); } } } document.addEventListener("DOMContentLoaded", () => { RepsolModal.init(); }); window.addEventListener("resize", () => { if(!window.matchMedia("(min-width: 1024px)").matches){ const modals = document.querySelectorAll('.modal'); modals.forEach((modal) => { const idModal = modal.getAttribute('id'); const targetModal = document.querySelector(`[data-target=${idModal}]`); if(targetModal && targetModal.classList.contains('open-modal-desktop')){ $(modal).modal("hide"); } }) } });