@shopgate/tracking-core
Version:
Tracking core library for the Shopgate Connect PWA.
60 lines • 11.3 kB
JavaScript
function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor;}function _callSuper(_this,derived,args){function isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{return!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));}catch(e){return false;}}derived=_getPrototypeOf(derived);return _possibleConstructorReturn(_this,isNativeReflectConstruct()?Reflect.construct(derived,args||[],_getPrototypeOf(_this).constructor):derived.apply(_this,args));}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call;}return _assertThisInitialized(self);}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return self;}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o);};return _getPrototypeOf(o);}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function");}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass);}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o;};return _setPrototypeOf(o,p);}import BasePlugin from"../Base";import SgGAUniversalTracking from"./GaUniversal";import SgGAClassicTracking from"./GaClassic";import{SGLink}from"../../helpers/helper";var TRACK_PAGE_VIEW='pageView';var TRACK_EVENT='event';var TRACK_SET='set';var TRACK_REQUIRE='require';var TRACK_CONVERSION={ADDITEM:'addItem',CURRENCY:'currencyCode',END:'trackTrans',START:'addTrans',PAGE:'page'};var ACCOUNT_CLASSIC='classic';var ACCOUNT_UNIVERSAL='universal';var shopgateOnly={merchant:false,shopgate:true};var merchantOnly={merchant:true,shopgate:false};// Command mapping tuple, [classic, universal]
var commandMapping={};commandMapping[TRACK_PAGE_VIEW]=['trackPageview','pageview'];commandMapping[TRACK_EVENT]=['trackEvent','event'];commandMapping[TRACK_SET]=[undefined,'set'];commandMapping[TRACK_CONVERSION.ADDITEM]=['addItem','ecommerce:addItem'];commandMapping[TRACK_CONVERSION.CURRENCY]=['currencyCode'];commandMapping[TRACK_CONVERSION.END]=['trackTrans','ecommerce:send'];commandMapping[TRACK_CONVERSION.START]=['addTrans','ecommerce:addTransaction'];commandMapping[TRACK_REQUIRE]=[undefined,'require'];/**
* Parent Tracking plugin for Google Analytics
*/var GaBase=/*#__PURE__*/function(_BasePlugin){/**
* Constructor
*/function GaBase(){var _this2;_classCallCheck(this,GaBase);_this2=_callSuper(this,GaBase,['GAcore',{}]);// Universal and classic merchant and shopgate accounts
_this2.accounts=[];_this2.isRegistered=false;_this2.universalPlugin=null;_this2.classicPlugin=null;return _this2;}/**
* Returns common data for a custom event
* @param {string} name Event category
* @param {Object} data Input
* @returns {{
* eventCategory: (string),
* eventAction: (string),
* eventLabel: (null|string),
* eventValue: (null|number),
* nonInteraction: (boolean)
* }}
* @private
*/_inherits(GaBase,_BasePlugin);return _createClass(GaBase,[{key:"sendCommand",value:/**
* Send command to both universal and classic sdk
*
* @param {string} command Name of the command
* @param {Object|Array|string|Function} [payload] Data for the command,
* or a function that returns data
* @param {Object} [scope] Scope (merchant or shopgate account)
* @param {string} [account] Which account to use, classic or universal
* @private
*/function sendCommand(command,payload,scope,account){if(typeof commandMapping[command]==='undefined'){return;}// Evaluate which accounts to send to.
var isClassic=typeof account==='undefined'||account===ACCOUNT_CLASSIC;var isUniversal=typeof account==='undefined'||account===ACCOUNT_UNIVERSAL;if(isUniversal&&this.universalPlugin!==null){this.universalPlugin.send(commandMapping[command][1],payload,scope);}if(isClassic&&this.classicPlugin!==null){this.classicPlugin.send(commandMapping[command][0],payload,scope);}}/**
* Helper to register for some events
* @private
*/},{key:"registerEvents",value:function registerEvents(){var _this3=this;if(this.isRegistered){return;}this.isRegistered=true;// Handle pageview event for shopgate accounts
this.register.pageview(function(data){_this3.sendCommand(TRACK_PAGE_VIEW,data.page.shopgateUrl,shopgateOnly);},shopgateOnly);// Handle pageview event for merchant account
this.register.pageview(function(data){_this3.sendCommand(TRACK_PAGE_VIEW,data.page.merchantUrl,merchantOnly);},merchantOnly);// Handle add_to_cart event as a pageview
this.register.addToCart(function(){_this3.sendCommand(TRACK_PAGE_VIEW,'add_to_cart');});// Smart app banner
this.register.smartbanner(function(data){_this3.sendCommand(TRACK_EVENT,GaBase.getEventData('Smartbanner',data));});// Scroll to top button event
this.register.scrollTop(function(data){_this3.sendCommand(TRACK_EVENT,GaBase.getEventData('ScrollTop',data),shopgateOnly);});// Qr scanner events
this.register.qrScanner(function(data){_this3.sendCommand(TRACK_EVENT,GaBase.getEventData('QRScanner',data));});// Ad scanner events
this.register.adScanner(function(data,originalData,scope){_this3.sendCommand(TRACK_EVENT,GaBase.getEventData('AdScanner',data),scope);});// Credit card scanner events
this.register.ccScanner(function(data){_this3.sendCommand(TRACK_EVENT,GaBase.getEventData('CcScanner',data));});// Filter in live suggest events
this.register.filterLiveSuggest(function(data){_this3.sendCommand(TRACK_EVENT,GaBase.getEventData('FilterLiveSuggest',data),shopgateOnly);});// Deeplink
this.register.openDeepLink(function(data){_this3.sendCommand(TRACK_EVENT,GaBase.getEventData('DeepLinkOpen',data),shopgateOnly);});// Universal link
this.register.openUniversalLink(function(data){_this3.sendCommand(TRACK_EVENT,GaBase.getEventData('UniversalLinkOpen',data),shopgateOnly);});// Deferred deep link
this.register.openDeferredDeepLink(function(data){_this3.sendCommand(TRACK_EVENT,GaBase.getEventData('DeferredDeepLinkOpen',data),shopgateOnly);});// Smart app download link
this.register.openSmartAppDownloadLink(function(data){_this3.sendCommand(TRACK_EVENT,GaBase.getEventData('SmartAppDownloadLink',data),shopgateOnly);});// Push notification
this.register.openPushNotification(function(data){_this3.sendCommand(TRACK_EVENT,GaBase.getEventData('PushNotification',data),shopgateOnly);});// Push notification
this.register.setCampaignWithUrl(function(data,raw){var shopgateUrl=new SGLink(data.url);shopgateUrl.setUtmParams(data,raw);_this3.sendCommand(TRACK_SET,['campaignName',shopgateUrl.getParam('utm_campaign')],undefined,ACCOUNT_UNIVERSAL);_this3.sendCommand(TRACK_SET,['campaignSource',shopgateUrl.getParam('utm_source')],undefined,ACCOUNT_UNIVERSAL);_this3.sendCommand(TRACK_SET,['campaignMedium',shopgateUrl.getParam('utm_medium')],undefined,ACCOUNT_UNIVERSAL);});// App review prompt
this.register.appReviewPrompt(function(data){_this3.sendCommand(TRACK_EVENT,GaBase.getEventData('AppReviewPrompt',data),shopgateOnly);});// Purchase events
this.register.purchase(function(data,rawData){_this3.sendCommand('require',['ecommerce','ecommerce.js'],null,ACCOUNT_UNIVERSAL);_this3.sendCommand(TRACK_CONVERSION.START,function(account){return{amountCompleteFloat:account.useNetPrices?data.revenueNet:data.revenueGross,amountTaxCompleteFloat:data.tax,amountShippingFloat:account.useNetPrices?data.shippingNet:data.shippingGross,city:rawData.order.shippingAddress.city,countryId:rawData.order.shippingAddress.country,currency:data.currency,orderNumber:data.id,shopName:data.affiliation,state:rawData.order.shippingAddress.stateId||''};});data.items.forEach(function(item){_this3.sendCommand(TRACK_CONVERSION.ADDITEM,function(account){return{orderNumber:rawData.order.number,productNumber:item.id,name:item.name,quantity:item.quantity,unitAmount:account.useNetPrices?item.priceNet:item.priceGross};});});_this3.sendCommand(TRACK_SET,[TRACK_CONVERSION.CURRENCY,data.currency],null,ACCOUNT_CLASSIC);_this3.sendCommand(TRACK_CONVERSION.END);});// Opt-out
this.register.removeTracker(function(){_this3.sendCommand(TRACK_EVENT,GaBase.getEventData('analyticsOptOut',{eventAction:'optOut',eventLabel:'all_accounts'}));_this3.accounts.forEach(function(account){var disableStr="ga-disable-".concat(account.id);document.cookie="".concat(disableStr,"=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/");window[disableStr]=true;});});// Revert opt-out
this.register.addTracker(function(){_this3.accounts.forEach(function(account){var disableStr="ga-disable-".concat(account.id);document.cookie="".concat(disableStr,"=false; expires=Thu, 01 Jan 1970 00:00:01 UTC; path=/");window[disableStr]=false;});_this3.sendCommand(TRACK_EVENT,GaBase.getEventData('revertOptOut',{eventAction:'optOut',eventLabel:'all_accounts'}));});}/**
* Creates an ga universals child tracker
* @param {Object} tracker Tracker configuration data
* @returns {GaUniversal} plugin instance
*/},{key:"createUniversal",value:function createUniversal(tracker){var _this$accounts;(_this$accounts=this.accounts).push.apply(_this$accounts,tracker.config.merchant.concat([tracker.config.shopgate]));this.universalPlugin=new SgGAUniversalTracking(tracker);this.registerEvents();return this.universalPlugin;}/**
* Creates a ga classic child tracker
* @param {Object} tracker Tracker configuration data
* @returns {GaClassic} plugin instance
*/},{key:"createClassic",value:function createClassic(tracker){var _this$accounts2;(_this$accounts2=this.accounts).push.apply(_this$accounts2,tracker.config.merchant);this.classicPlugin=new SgGAClassicTracking(tracker);this.registerEvents();return this.classicPlugin;}}],[{key:"getEventData",value:function getEventData(name,data){return{eventCategory:name,eventAction:data.eventAction,eventLabel:data.eventLabel,eventValue:data.eventValue,nonInteraction:data.nonInteraction};}}]);}(BasePlugin);// Export and create global instance
window.SgGATrackingInstance=new GaBase();export default window.SgGATrackingInstance;