import init from '@utils/instance'; import PR from 'piwik-react-router'; import {inQb, getUser} from 'frc-core-pro'; interface PiwikProps { piwik: any; trackName: string; } const pwInstance = init(); let hasUser = false; class Piwik { constructor({piwik, trackName}: PiwikProps) { const instance = pwInstance(); const {url, siteId, enabled} = piwik || {}; if (!instance) { let pw: any = null; if (enabled) { pw = PR({url, siteId}); // console.info('piwik has been created successfully'); pw.pushEvent = this.push; pw.trackEvent = this.trackEvent; pw.trackPageView = this.trackPageView; pw.trackName = trackName; if (pw && inQb()) { getUser((user) => { if (!hasUser) { pw.push(['setUserId', user.username]); hasUser = true; } }); } pwInstance(pw); } } return pwInstance(); } trackPageView = () => { setTimeout(() => { pwInstance().pushEvent('trackPageView'); }); }; trackEvent = (action: any, username: any) => { setTimeout(() => { if (!hasUser) { pwInstance().push(['setUserId', username]); hasUser = true; } const ac = encodeURIComponent(action); pwInstance().pushEvent('trackEvent', [encodeURIComponent(pwInstance().trackName), ac], username); }); }; push = (e: any, actions = [], username: any) => { if (inQb()) { getUser((user) => { if (!hasUser) { pwInstance().push(['setUserId', username]); hasUser = true; } if (actions) { pwInstance().push([e, ...actions, user.username]); } }); } else { if (!hasUser) { pwInstance().push(['setUserId', username]); hasUser = true; } if (actions) { pwInstance().push([e, ...actions, username]); } } }; } export default Piwik;