PageSourceSearch

https://www.ledkia.com/core/controllers/front/Indigitall/IndigitallController.js

js ledkia.com collected 2026-10-02 03:38:03 UTC 12,336 bytes, 323 lines download raw bytes

1class IndigitallController {
2  /*
3    Lista de topics que se van a subscribir de manera forzada
4    Ejemplo: var EXTRA_TOPICS = ["contrata"];
5  */
6  static get EXTRA_TOPICS(){ return []; }
7  /*
8    Número máximo de topics según el tipo por cada usuario
9    MAX_NAV_TOPICS: topics que indican por qué URLs navega el usuario
10    MAX_DL_TOPICS: topics que indican qué variables tiene el usuario en el data layer
11  */
12  static get MAX_NAV_TOPICS(){ return 10; }
13  /* Variable de referencia que se usa para buscar el objeto relevante dentro del dataLayer */
14  static get DL_USER_CONTRACT_ATTR_NAME(){ return 'userContract'; }
15  /*
16    Prefijos para los códigos de topic en la consola de indigitall
17    NAVIGATION_PREFIX: todos los topics de navegación deben tener un código que incluya este prefijo
18    DL_PREFIX: todos los topics del dataLayer deben tener un código que incluya este prefijo
19  */
20  static get NAVIGATION_PREFIX(){ return 'nav'; }
21  /* Claves que se usarán en LocalStorage para cachear los topics a los que está suscrito el usuario */
22  static get NAVIGATION_LS_KEY(){ return 'ind.navTopics'; }
23  /* Caracter de sustitución para eliminar las barras / de los códigos de los topics */
24  static get SEPARATOR(){ return '_'; }
25
26  static getNavigationTopics(topicCodesAvailable) {
27    let navigationTopicCodes = location.pathname
28      .replace(/\.html/g, "")
29      .replace(/\./g, "")
30      .split("/")
31      .filter(function (pathFolder) {
32        return pathFolder.length > 0;
33      });
34    if (navigationTopicCodes.length == 0) {
35      return navigationTopicCodes;
36    }
37    navigationTopicCodes = navigationTopicCodes
38      .map(function (pathFolder, index) {
39        let topicCode = pathFolder;
40        for (let i = index - 1; i >= 0; i--) {
41          topicCode = navigationTopicCodes[i] + IndigitallController.SEPARATOR + topicCode;
42        }
43        return IndigitallController.NAVIGATION_PREFIX + IndigitallController.SEPARATOR + topicCode;
44      })
45      .filter(function (topicCode) {
46        return topicCodesAvailable.includes(topicCode);
47      });
48    return navigationTopicCodes;
49  }
50
51  static getTopicCodeFromHostname() {
52    return location.hostname.replace(/\./g, '');
53  }
54
55  static filterTopicsLangOff(currentNavigationTopicCodes, topicCodesLang) {
56    topicCodesLang = topicCodesLang.filter(function (topic) {
57      return (!currentNavigationTopicCodes.includes(topic.code)) ? true : false;
58    });
59    return topicCodesLang.map(function (topic) {
60      return topic.code;
61    });
62  }
63
64  static filterTopicsAlreadySubscribed(currentTopicCodes, topicsAvailable) {
65    let topicCodesNotSubscribed = topicsAvailable
66      .filter(function (topic) {
67        return !topic.subscribed;
68      })
69      .map(function (topic) {
70        return topic.code;
71      });
72
73    let topicCodesFiltered = currentTopicCodes.filter(function (topicCode) {
74      return topicCodesNotSubscribed.includes(topicCode);
75    });
76    return topicCodesFiltered;
77  }
78
79  static filterMaxTopics(topicCodes, localStorageKey, maxTopics, navigationTopicsLangOff) {
80    let topicsOn = [];
81    let topicsOff = [];
82    if(navigationTopicsLangOff.length){
83      topicsOff = navigationTopicsLangOff;
84    }
85    //let prevTopics = JSON.parse(localStorage.getItem(localStorageKey) || '[]');
86    let prevTopics = JSON.parse('[]');
87    for (let i = 0; i < topicCodes.length; i++) {
88      let topic = topicCodes[i];
89      if (topic !== '' && topic != null && !prevTopics.includes(topic)) {
90        prevTopics.push(topic);
91        if (prevTopics.length > maxTopics) {
92          topicsOff.push(prevTopics[0]);
93          prevTopics.splice(0, 1);
94        }
95        localStorage.setItem(localStorageKey, JSON.stringify(prevTopics));
96        topicsOn.push(topic);
97      }
98    }
99    return {
100      topicsOn: topicsOn,
101      topicsOff: topicsOff
102    };
103  }
104
105  static unionArrays(x, y) {
106    let obj = {};
107    for (let i = x.length - 1; i >= 0; --i) {
108      obj[x[i]] = x[i];
109    }
110    for (let i = y.length - 1; i >= 0; --i) {
111      obj[y[i]] = y[i];
112    }
113    let res = [];
114    for (let k in obj) {
115      if (obj.hasOwnProperty(k)) {
116        res.push(obj[k]);
117      }
118    }
119    return res;
120  }
121
122  static onIndigitallInitialized(permissions, device) {
123    if (permissions.push != 'granted') {
124      return;
125    }
126    if (indigitall && IndigitallController.checkIndigitallGranted()) {
127      const oldAppKey = localStorage.getItem('indigitall.repository.APP_KEY');
128      const ledkiaAppKey = IndigitallController.appKey;
129      if (oldAppKey !== ledkiaAppKey) {
130        localStorage.removeItem('indigitall.repository.NEW_USER_TIMESTAMP');
131        localStorage.removeItem('indigitall.repository.LOCATION_TIMESTAMP');
132        localStorage.removeItem('indigitall.repository.SERVICE_TIMESTAMP');
133        localStorage.removeItem('indigitall.repository.DEVICE_ID');
134        localStorage.removeItem('indigitall.repository.APP_KEY');
135      }
136      /**
137       * Remove old service worker
138       */
139      navigator.serviceWorker.getRegistrations().then((registrations) => {
140        registrations.forEach((registration) => {
141          if ([IndigitallController.baseUrl + 'core/assets/js/services/indigitall/'].includes(registration.scope)) {
142            if(registration.active && registration.active.scriptURL.indexOf('/worker.min.js') > 0){
143              //Force unregister of old service worker
144              registration.unregister();
145            }
146          } else if([IndigitallController.baseUrl + 'scripts/indigitall/'].includes(registration.scope)) {
147            //Force activate the service worker
148            registration.update();
149          }
150        });
151      });
152    }
153    indigitall.topicsList(function (topics) {
154      let topicsAvailable = topics;
155      let topicCodesAvailable = topics.map(function (topic) {
156        return topic.code;
157      });
158      let topicCodesLang = topics.filter(function (topic) {
159        return (topic.code.startsWith('nav') && topic.code.split('_').length == 2) ? topic.code : null;
160      });
161      /* Topics en base a navegación */
162      let currentNavigationTopicCodes = IndigitallController.getNavigationTopics(topicCodesAvailable);
163      let navigationTopicsLangOff = IndigitallController.filterTopicsLangOff(currentNavigationTopicCodes, topicCodesLang);
164      currentNavigationTopicCodes = IndigitallController.filterTopicsAlreadySubscribed(currentNavigationTopicCodes, topicsAvailable);
165      let navigationTopicsChanges = IndigitallController.filterMaxTopics(currentNavigationTopicCodes, IndigitallController.NAVIGATION_LS_KEY, IndigitallController.MAX_NAV_TOPICS,navigationTopicsLangOff);
166      /* Topics en base a hostname */
167      let currentHostnameTopicCode = IndigitallController.getTopicCodeFromHostname();
168      currentHostnameTopicCode = IndigitallController.filterTopicsAlreadySubscribed([currentHostnameTopicCode], topicsAvailable);
169      /* Sync con backend */
170      let topicsOn = IndigitallController.unionArrays(navigationTopicsChanges.topicsOn, currentHostnameTopicCode);
171      topicsOn = IndigitallController.unionArrays(topicsOn, IndigitallController.EXTRA_TOPICS);
172      let topicsOff = navigationTopicsChanges.topicsOff;
173      if (topicsOff.length > 0) {
174        indigitall.topicsUnsubscribe(topicsOff, function () {
175          if (topicsOn.length > 0) {
176            indigitall.topicsSubscribe(topicsOn);
177          }
178        });
179      } else if (topicsOn.length > 0) {
180        indigitall.topicsSubscribe(topicsOn);
181      }
182    });
183  }
184
185  static beforeUnloadPage(event){
186    let productsInCart = 0;
187    if(typeof HeaderController != 'undefined' && HeaderController.productsInCart){
188      productsInCart  = HeaderController.productsInCart;
189    }
190
191    if (typeof indigitall === 'function' && indigitall && IndigitallController.checkIndigitallGranted() && productsInCart > 0) {
192      IndigitallController.addIndigitallTopic('off','purchase');
193      const eventCode = 'abandoned_page';
194      const customData = {};
195      const frecuency = 7 * (24 * 3600 * 1000); // minimun time between events (in milliseconds)
196
197      const prevEventSentAt = parseInt(localStorage.getItem('indigitall.custom.' + eventCode) || '0', 10);
198      const now = (new Date()).getTime();
199
200      if (now > prevEventSentAt + frecuency) {
201
202        localStorage.setItem('indigitall.custom.' + eventCode, now);
203        if(CoreTools.getCookie('is_app')){
204          //OYS-8598: Code to use indigitall in APP
205          const customEventDataObject = {
206            eventId:'Indigitall#sendCustomEvent',
207            data: {
208              'eventname':eventCode,
209              'eventdata':JSON.stringify(customData)
210            }
211          };
212          parent.postMessage(customEventDataObject,'*');
213        }else{
214          indigitall.sendCustomEvent({
215            eventType: eventCode,
216            async: false,
217          });
218        }
219      }
220    }
221  }
222
223  static addIndigitallExternalCode(user){
224    if(user && user.indigitallId && typeof indigitall === 'function' && indigitall && IndigitallC
224ontroller.checkIndigitallGranted()) {
225
226      const currentCode = localStorage.getItem(
227        'indigitall.repository.EXTERNAL_ID'
228      );
229      if (!currentCode || currentCode != user.indigitallId) {
230        if (CoreTools.getCookie('is_app')) {
231          //OYS-8598: Code to use indigitall in APP
232          const externalCodeDataObject = {
233            eventId: 'Indigitall#setuserid',
234            data: user.indigitallId
235          };
236          parent.postMessage(externalCodeDataObject, '*');
237        } else {
238          indigitall.setExternalCode(user.indigitallId);
239        }
240      }
241    }
242  }
243
244  static addIndigitallTopic(topicId,prefix = '',topicIdNotSubscribed = ''){
245    if(typeof indigitall === 'function' && indigitall && topicId && IndigitallController.checkIndigitallGranted()) {
246      let topicIdComplete = (prefix) ? prefix.toLowerCase() + '_' + topicId.toLowerCase() : topicId.toLowerCase();
247      indigitall.topicsList((topics) => {
248        let exists  = (topicIdNotSubscribed) ? IndigitallController.checkIndigitallTopic(topics,topicIdNotSubscribed) : false;
249        if(topicIdNotSubscribed == '' || !exists){
250          topics.forEach((topic) => {
251
252            if(topic.code == topicIdComplete && !topic.subscribed){
253              IndigitallController.subscribeTopic(topicIdComplete);
254            }else if(prefix && topic.code.startsWith(prefix) && topic.code != topicIdComplete && topic.subscribed){
255              IndigitallController.unsubscribeTopic(topicIdComplete);
256            }
257          });
258        }
259      }, (e) => {
260        console.info(e);
261      });
262    }
263  }
264
265  static subscribeTopic(topicId){
266    if(CoreTools.getCookie('is_app')){
267      //OYS-8598: Code to use indigitall in APP
268      const subscribedDataObject = {
269        eventId:'Indigitall#subscribeUserToTopics',
270        data:topicId
271      };
272      parent.postMessage(subscribedDataObject,'*');
273    }else {
274      indigitall.topicsSubscribe([topicId]);
275    }
276  }
277
278  static unsubscribeTopic(topicId){
279    if(CoreTools.getCookie('is_app')){
280      //OYS-8598: Code to use indigitall in APP
281      const unsubscribedDataObject = {
282        eventId:'Indigitall#unsubscribeUserToTopics',
283        data:topicId
284      };
285      parent.postMessage(unsubscribedDataObject,'*');
286    }else {
287      indigitall.topicsUnsubscribe([topicId]);
288    }
289  }
290
291  static checkIndigitallTopic(topics,topicId,prefix = ''){
292    let topicCodesAvailable = topics.map((topic) => {
293      return (topic.subscribed) ? topic.code : false;
294    });
295    return topicCodesAvailable.includes(topicId);
296  }
297
298  static checkIndigitallGranted(){
299    const isSupported = () =>
300      'Notification' in window &&
301      'serviceWorker' in navigator &&
302      'PushManager' in window;
303    if(isSupported && window.Notification && window.Notification.permission === 'granted'){
304      return true;
305    }else{
306      return false;
307    }
308  }
309
310  static init(appKey, baseUrl)
311  {
312    IndigitallController.appKey = appKey;
313    IndigitallController.baseUrl = baseUrl;
314    indigitall.init({
315      appKey: appKey,
316      urlDeviceApi: 'https://eu2.device-api.indigitall.com/v1',
317      workerPath: '/scripts/indigitall/worker.min.js',
318      requestLocation: false,
319      onInitialized: IndigitallController.onIndigitallInitialized
320    });
321  }
322}
323window.addEventListener('beforeunload', IndigitallController.beforeUnloadPage);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.