class WUPushNotifications { WU = {}; WU_TOKEN_ENDPOINT = "https://admin.woowup.com/apiv3/push-notifications/generate-token"; WU_PUSH_CONFIG = "https://admin.woowup.com/apiv3/push-notifications/configuration"; WU_API_LOG_EVENT = "https://navigations-events.woowup.com/create"; PUSHER_SDK_ENDPOINT = "https://js.pusher.com/beams/1.0/push-notifications-cdn.js"; TRANSFORM_DATE = 1000*60*60*24; WU_TRACK_TYPE = 'push-notification'; MAX_DAYS = 7; EVENT_BROWSER_NOTIFICATIONS_GRANTED = "browser_notifications_granted"; EVENT_BROWSER_NOTIFICATIONS_GRANTED_DENIED = "browser_notifications_granted_denied"; EVENT_BROWSER_DONT_SHOW_POPUP = "browser_dont_show_popup"; EVENT_PUSH_NOTIFICATIONS_DONT_SUBSCRIBED = "customer_dont_subscribed"; EVENT_PUSH_NOTIFICATIONS_SUBSCRIBED = "customer_notifications_subscribed"; EVENT_SHOW_POPUP = "show_popup"; EVENT_WUP_GET_CONFIG_ERROR = "wup_get_config_data_error"; EVENT_WUP_ADD_DEVICE_ERROR = "wup_add_device_error"; EVENT_ADD_DEVICE_ERROR = "add_device_error"; EVENT_WUP_ADD_DEVICE_SUCCESS = "wup_add_device"; EVENT_WUP_GET_CONFIG_SUCCESS = "wup_load_config_data"; EVENT_CLICK_SUBSCRIBED = "click_subscribed"; EVENT_CLICK_DONT_SUBSCRIBED = "click_dont_subscribed"; EVENT_BEAMS_PERMISSION_PROMPT_REQUIRED = "beams_permission_prompt_required" EVENT_SHOW_CONFIRM_POP_UP = "wup_show_confirm_pop_up"; EVENT_CLOSE_POPUP = "wup_close_pop_up" EVENT_BEAMS_ERROR = "wup_beams_error" /** * @param publicKey * @param instanceId * @private */ configure (publicKey, instanceId) { this.WU.identifier = 'wuid'; this.WU._publicKey = publicKey; this.WU._instanceId = instanceId; this.config = {}; } /** * Returns WoowUp ID * @returns {string} */ getId () { const id = this.getUrlParameterByName(this.WU.identifier); const cacheName = '_' + this.WU.identifier; if (id) { window.localStorage.setItem(cacheName, id); return id; } return window.localStorage.getItem(cacheName); } /** * Returns value from current url parameter * @param name * @returns {string|null} */ getUrlParameterByName(name) { const queryString = window.location.search; const urlParams = new URLSearchParams(queryString); return urlParams.has(name) ? urlParams.get(name) : null; } /** * Load Pusher SDK * @param callback * @private */ _loadSDK(callback) { const script = document.createElement( "script" ) script.type = "text/javascript"; script.src = this.PUSHER_SDK_ENDPOINT; script.onload = function() { const wid = window.WUPushNotifications.getId(); if (wid) { callback(wid); } }; document.getElementsByTagName("script")[0].parentNode.appendChild( script ); } start() { if (! this.getId() || localStorage.getItem('_wu_subscribed') === "true") { return ; } if(Notification.permission === 'granted'){ this.trackEvent(this.EVENT_BROWSER_NOTIFICATIONS_GRANTED) this.startPush(); return; } if (Notification.permission === "denied") { this.trackEvent(this.EVENT_BROWSER_NOTIFICATIONS_GRANTED_DENIED) return; } const options = { 'headers': { 'Accept': 'application/json', 'Content-Type': 'application/json' } } fetch(this.WU_PUSH_CONFIG+'?appkey='+this.WU._publicKey, options) .then(response => { if (!response.ok) { throw new Error('HTTP error, status = ' + response.status); } return response.json(); }) .then(data => { data.pushnotifications_config = JSON.parse(data.pushnotifications_config); if (data.pushnotifications_config) { this.trackEvent(this.EVENT_WUP_GET_CONFIG_SUCCESS) this.config = data; this.setCustomPopUp(data); } else { this.trackEvent(this.EVENT_WUP_GET_CONFIG_ERROR, { error: "No se encontro la configuracion del popup de WoowUp." }) console.log("No se encontro la configuracion del popup de WoowUp."); } }).catch((error) => { console.log(error) this.trackEvent(this.EVENT_WUP_GET_CONFIG_ERROR,{ error: error.message }) }); } exceededMaxRetry(popUpConfig) { if ( popUpConfig.pushnotifications_config.config.max_retry == null ) { localStorage.setItem('_wu_attempts', '1'); return false; } const maxRetry = popUpConfig.pushnotifications_config.config.max_retry; const attempts = parseInt(localStorage.getItem('_wu_attempts')); return attempts > maxRetry } setCustomPopUp(popUpConfig) { if (localStorage.getItem('_wu_attempts') === null) { localStorage.setItem('_wu_attempts', '1'); } if(localStorage.getItem('_wupages_navigated') === null){ localStorage.setItem('_wupages_navigated',0); } if (localStorage.getItem('_wu_subscribed') === "false") { if (!this.canShowAgainCustomPopUp(popUpConfig) || this.exceededMaxRetry(popUpConfig)) { this.trackEvent(this.EVENT_BROWSER_DONT_SHOW_POPUP) return; } const newAttempt = parseInt(localStorage.getItem('_wu_attempts')) + 1; localStorage.setItem('_wu_attempts', ''+ newAttempt); } const pagesNavigated = parseInt(localStorage.getItem('_wupages_navigated')); const configMinPagesNavigated = popUpConfig.pushnotifications_config.config.min_pages_navigated if( pagesNavigated >= configMinPagesNavigated ){ const timeout = popUpConfig.pushnotifications_config.config.timeout; setTimeout(this.addCustomPopUp(popUpConfig.pushnotifications_html), timeout?timeout*1000:1000); } this.trackEvent(this.EVENT_SHOW_POPUP) localStorage.setItem('_wupages_navigated', pagesNavigated + 1); } addCustomPopUp(popUp){ const WUPUSHOBJ = this; const body = document.getElementsByTagName( 'BODY' )[0]; body.insertAdjacentHTML( 'beforeend', popUp ); const modal = document.getElementById("WUPUSHMODAL"); modal.style.display = "block"; const suscribe = document.getElementById("wu-suscribe"); suscribe.onclick = function() { WUPUSHOBJ.trackEvent(WUPUSHOBJ.EVENT_CLICK_SUBSCRIBED) WUPUSHOBJ.startPush(); } const dontSuscribe = document.getElementById("wu-dont-suscribe"); dontSuscribe.onclick = function() { WUPUSHOBJ.trackEvent(WUPUSHOBJ.EVENT_CLICK_DONT_SUBSCRIBED) WUPUSHOBJ.setSubscribeConfig(false); WUPUSHOBJ.closeCustomPopUp(); } } showThankyouMessage() { if (this.config.pushnotifications_config.thankyou_message == null) { return false; } const WUPUSHOBJ = this; const subscriptionMessage = document.getElementById("wu-subscription"); subscriptionMessage.style.display = "none"; const buttons = document.getElementById("wu-btn-set"); buttons.style.display = "none"; const logo = document.getElementById("wu-logo"); logo.style.display = "none"; const thankyouMessage = document.getElementById("wu-thankyou-message"); thankyouMessage.style.display = "block"; const closeButton = document.getElementById("wu-close-btn"); closeButton.style.display = "block"; const content = document.getElementById("WPNDialogContent"); if (content) { content.style.position = ''; content.style.right = ''; } const confirmMessage = document.getElementById("wu-subscription-confirm"); if (confirmMessage) { confirmMessage.style.display = "none"; } const confirmBody = document.getElementById("wu-confirm-set"); if (confirmBody) { confirmBody.style.display = "none"; } const modal = document.getElementById("WUPUSHMODAL"); modal.style.display = "block"; const body = document.getElementsByTagName('BODY')[0]; body.appendChild(document.getElementById("WUPUSHMODAL")); closeButton.onclick = function () { WUPUSHOBJ.closeCustomPopUp(); } setTimeout(function() { WUPUSHOBJ.closeCustomPopUp(); }, 4000); window.addEventListener('click', function(e){ // Clicked outside modal if (!document.getElementById('WPNDialogContent').contains(e.target)){ WUPUSHOBJ.closeCustomPopUp(); } }); } setSubscribeConfig(isSubscribed = true) { localStorage.setItem('_wu_subscribed', isSubscribed.toString()); if (!isSubscribed) { this.trackEvent(this.EVENT_PUSH_NOTIFICATIONS_DONT_SUBSCRIBED) localStorage.setItem('_wu_unsubscribed_date', Date.now().toString()); }else { this.trackEvent(this.EVENT_PUSH_NOTIFICATIONS_SUBSCRIBED) } } canShowAgainCustomPopUp(popUpConfig) { if ( localStorage.getItem('_wu_unsubscribed_date') === null ) { return false; } let days = this.MAX_DAYS; if (popUpConfig.pushnotifications_config.config.show_again != null) { days = popUpConfig.pushnotifications_config.config.show_again; } const now = Date.now(); const dontSubscribeDate = parseInt(localStorage.getItem('_wu_unsubscribed_date')); const numberOfDays = (now-dontSubscribeDate) / this.TRANSFORM_DATE; return numberOfDays >= days } showConfirmMessage() { if (!this.config.pushnotifications_config.title_confirm) { return; } const WUPUSHOBJ = this; const subscriptionMessage = document.getElementById("wu-subscription"); subscriptionMessage.style.display = "none"; const buttons = document.getElementById("wu-btn-set"); buttons.style.display = "none"; const logo = document.getElementById("wu-logo"); logo.style.display = "none"; const content = document.getElementById("WPNDialogContent"); if (content) { const screenWidth = window.screen.width; const contentPosition = Math.round((screenWidth*0.027) - 37); content.style.position = "relative"; content.style.right = contentPosition + "%"; } const confirmMessage = document.getElementById("wu-subscription-confirm"); if (confirmMessage) { confirmMessage.style.display = "block"; } const confirmBody = document.getElementById("wu-confirm-set"); if (confirmBody) { confirmBody.style.display = "flex"; } const closeButton = document.getElementById("wu-close-btn"); closeButton.style.display = "block"; const modal = document.getElementById("WUPUSHMODAL"); modal.style.display = "block"; const body = document.getElementsByTagName('BODY')[0]; body.appendChild(document.getElementById("WUPUSHMODAL")); this.trackEvent(this.EVENT_SHOW_CONFIRM_POP_UP); closeButton.onclick = function () { WUPUSHOBJ.closeCustomPopUp(); } window.addEventListener('click', function(e){ // Clicked outside modal if (!document.getElementById('WPNDialogContent').contains(e.target)){ WUPUSHOBJ.closeCustomPopUp(); } }); } closeCustomPopUp() { const modal = document.getElementById("WUPUSHMODAL"); if(!modal) return ; modal.style.display = "none"; this.trackEvent(this.EVENT_CLOSE_POPUP); } /** * Start Pusher Notifications */ startPush() { const WUPUSHOBJ = this; this._loadSDK((wid) => { const beamsClient = new PusherPushNotifications.Client({ instanceId: this.WU._instanceId, }); beamsClient .getRegistrationState() .then((state) => { const states = PusherPushNotifications.RegistrationState; switch (state) { case states.PERMISSION_PROMPT_REQUIRED: WUPUSHOBJ.trackEvent(WUPUSHOBJ.EVENT_BEAMS_PERMISSION_PROMPT_REQUIRED) WUPUSHOBJ.showConfirmMessage(); case states.PERMISSION_GRANTED_NOT_REGISTERED_WITH_BEAMS: case states.PERMISSION_GRANTED_REGISTERED_WITH_BEAMS:{ beamsClient.start() .then(function(res){ const tokenProvider = new PusherPushNotifications.TokenProvider({ url: WUPUSHOBJ.WU_TOKEN_ENDPOINT, queryParams: { appkey: WUPUSHOBJ.WU._publicKey, device_id : res._deviceId } }) beamsClient.setUserId(wid, tokenProvider).then((response) => { WUPUSHOBJ.trackEvent(WUPUSHOBJ.EVENT_WUP_ADD_DEVICE_SUCCESS, { deviceId: res._deviceId, }) WUPUSHOBJ.setSubscribeConfig(); WUPUSHOBJ.showThankyouMessage(); } ).catch((error) => { WUPUSHOBJ.trackEvent(WUPUSHOBJ.EVENT_WUP_ADD_DEVICE_ERROR, { error: error.message }) WUPUSHOBJ.closeCustomPopUp(); WUPUSHOBJ.setSubscribeConfig(false); })}) .catch( (error) => { WUPUSHOBJ.trackEvent(WUPUSHOBJ.EVENT_ADD_DEVICE_ERROR, { error: error.message }) WUPUSHOBJ.closeCustomPopUp(); WUPUSHOBJ.setSubscribeConfig(false); }) break; } case states.PERMISSION_DENIED: WUPUSHOBJ.closeCustomPopUp(); WUPUSHOBJ.setSubscribeConfig(false); alert("Tu navegador cuenta con los permisos para notificaciones bloqueados. Por favor, habilite los permisos y vuelva a intentarlo."); break; default : { WUPUSHOBJ.closeCustomPopUp(); break; } } }) .catch((error) => { console.error(error); WUPUSHOBJ.closeCustomPopUp(); WUPUSHOBJ.trackEvent(WUPUSHOBJ.EVENT_BEAMS_ERROR); }); }) } trackEvent(eventName, metadata = { deviceId: null, error: null }) { const localStorageData = { _wuid: localStorage.getItem('_wuid'), _wu_attempts: localStorage.getItem('_wu_attempts'), _wupages_navigated: localStorage.getItem('_wupages_navigated'), _wu_subscribed: localStorage.getItem('_wu_subscribed'), _wu_unsubscribed_date: localStorage.getItem('_wu_unsubscribed_date') } console.log( "Rastreando evento: ", eventName, " con detalles: ", JSON.stringify(metadata), "localStorageData", JSON.stringify(localStorageData) ) const timeTwoWeeksSeconds = 1209600; const ttlParams = Math.floor(Date.now() / 1000) + timeTwoWeeksSeconds; const API_ENDPOINT_LOG_EVENTS = this.WU_API_LOG_EVENT; const data = { event: eventName, datetime: new Date().toISOString(), public_key: this.WU._publicKey, wuid: this.getId(), ttl: ttlParams, metadata: { device_id: metadata.deviceId, error: metadata.error, localStorage: localStorageData }, type: this.WU_TRACK_TYPE }; /* Remove Logs Push */ /*fetch(API_ENDPOINT_LOG_EVENTS, { method: "POST", headers: { "Content-Type": "application/json", }, referrerPolicy: 'no-referrer', body: JSON.stringify(data) }).then(response => console.log(response)) .catch(error => console.error("Error al rastrear evento:", error));*/ } } /** * Set Push Notifications */ (function () { function _WUPushNotifications (publicKey, instanceId) { window.WUPushNotifications = new WUPushNotifications; window.WUPushNotifications.configure(publicKey, instanceId); window.WUPushNotifications.start(); } window.WU = window.WU || {}; window.WU.pushNotifications = _WUPushNotifications; })();