Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@skava/packages / core / analytics / container.js
Size: Mime:
/**
 * @todo @@perf @see https://developers.google.com/web/updates/2015/08/using-requestidlecallback#using_requestidlecallback_for_sending_analytics_data
 */
import { oneRouter } from '@skava/router';
import { isNonEmptyString } from 'exotic';
import { getTyped } from 'composition';
import { isNonEmptyArray } from 'exotic';
import { GOOGLE_TAG_MANGER_ID } from 'src/bootstrap/api/config';
import { sessionContainer } from '@skava/packages/core/auth/session';
import { localeContainer } from '@skava/packages/features/Locale';
import { requestIdleCallback } from '@skava/packages/libraries/request-idle-callback';
import { transformPDPData, transformPLPData, transformPlpProductVariant, transformPdpProductVariant, } from './transform';
const IS_BROWSER = typeof window === 'object';
/**
 * or analytics, but should be `gtm`
 */
function toGoogleTagManager() {
    return window.gta;
}
function root() {
    const ROOT_GLOBAL = IS_BROWSER ? window : global;
    return ROOT_GLOBAL;
}
function globalDataLayer() {
    const dataLayer = root().dataLayer || [];
    return dataLayer;
}
/**
 * @see https://developers.google.com/tag-manager/devguide
 */
function load() {
    root().dataLayer = globalDataLayer();
    /**
     * @deprecated @todo @@perf remove
     */
    root().gta = function (argumentsToTrack) {
        globalDataLayer().push(argumentsToTrack);
    };
}
class AnalyticsContainer {
    constructor() {
        this.queue = [];
    }
    get tracker() {
        return toGoogleTagManager();
    }
    get pageName() {
        const pathname = oneRouter.entries().pathname;
        const path = pathname.split('/');
        if (isNonEmptyString(path[1])) {
            return path[1] + ' page';
        }
        else {
            return 'Home Page';
        }
    }
    trackPageEvent() {
        const pathname = oneRouter.entries().pathname;
        const productRelatedPaths = ['/search', '/product', '/category', '/merchProductList'];
        const isProductRelatedPage = productRelatedPaths.some(productRelatedPath => pathname.includes(productRelatedPath));
        const customDimension = this.getCommonCustomDimensions();
        if (!isProductRelatedPage) {
            this.pushToDataLayer({ event: 'pageView', ...customDimension });
        }
    }
    initializeAnalytics() {
        load();
        this.tracker('js', new Date());
        this.tracker('config', GOOGLE_TAG_MANGER_ID);
        this.trackPageEvent();
        oneRouter.history.listen(() => {
            const processPageAnalyticsTracking = () => setTimeout(() => this.trackPageEvent(), 1000);
            requestIdleCallback(processPageAnalyticsTracking);
        });
    }
    getCommonCustomDimensions() {
        const { country, language } = localeContainer.item;
        return {
            SK_UserType: sessionContainer.isRegisteredUser ? 'signedIn' : 'guest',
            SK_Region: country,
            SK_Language: language,
        };
    }
    trackCustomEvent(eventDetails) {
        const { category, action, label } = eventDetails;
        const commonCustomDimensions = this.getCommonCustomDimensions();
        this.pushToDataLayer({
            event: 'customEventTracking',
            category,
            action,
            label,
            ...commonCustomDimensions,
        });
    }
    pushToDataLayer(argumentsToTrack) {
        globalDataLayer().push(argumentsToTrack);
    }
    trackPDPTagManager(item) {
        const transformedData = transformPDPData(item);
        const commonCustomDimensions = this.getCommonCustomDimensions();
        this.pushToDataLayer({
            event: 'productDetailImpression',
            ecommerce: {
                detail: {
                    products: transformedData,
                },
            },
            ...commonCustomDimensions,
        });
    }
    trackPLPTagManager(productList) {
        const isSearch = oneRouter.entries().pathname.includes('/search');
        const searchTerm = isSearch === true ? oneRouter.entries().searchTerm : '';
        const transformedData = transformPLPData(productList, searchTerm);
        const commonCustomDimensions = this.getCommonCustomDimensions();
        if (isSearch) {
            const noResult = productList && productList.length > 0 ? '' : '&searchCat=noResults';
            const queryparams = oneRouter.entries().search.includes('pageNumber')
                ? oneRouter.entries().search
                : '?SKSearchTerm=' + searchTerm + noResult;
            const pageUrl = oneRouter.pathname + queryparams;
            const pageViewDetails = {
                searchPageUrl: pageUrl,
                searchPageLocation: oneRouter.entries().href,
                searchPageTitle: 'Search Page',
                SK_SearchResultsReturned: productList.length,
            };
            this.pushToDataLayer({
                event: 'searchPageView',
                ...commonCustomDimensions,
                ...pageViewDetails,
            });
        }
        else {
            this.pushToDataLayer({
                event: 'productImpression',
                ecommerce: {
                    impressions: transformedData,
                },
                ...commonCustomDimensions,
            });
        }
    }
    getProductVariantDetails(productOptions) {
        const variants = productOptions.map(option => {
            return option.value;
        });
        return variants.join(',');
    }
    trackVirtualPageView(pageViewDetails) {
        const { pageURL, pagePath, pageTitle, ...remainingProps } = pageViewDetails;
        const commonCustomDimensions = this.getCommonCustomDimensions();
        analyticsContainer.pushToDataLayer({
            event: 'virtualPageView',
            virtualPageURL: pageURL,
            virtualPagePath: pagePath,
            virtualPageTitle: pageTitle,
            ...commonCustomDimensions,
            ...remainingProps,
        });
    }
    cartProducts(checkoutProductDetails) {
        const cartProducts = checkoutProductDetails.map((product, index) => {
            const { name, identifier, salePrice, regPrice, quantity, selectedProductOptionsList, } = product;
            return {
                name,
                id: identifier,
                price: salePrice || regPrice,
                brand: '',
                category: '',
                variant: this.getProductVariantDetails(selectedProductOptionsList),
                quantity,
                list: [],
                position: index + 1,
            };
        });
        return cartProducts;
    }
    trackPurchaseEcommerce(checkoutProductDetails, orderId, orderDetails) {
        const orderProducts = this.cartProducts(checkoutProductDetails);
        const commonCustomDimensions = this.getCommonCustomDimensions();
        const { grandTotal, grandTotalTax, estTotalShippingPrice } = orderDetails;
        this.pushToDataLayer({
            event: 'purchase',
            ecommerce: {
                purchase: {
                    actionField: {
                        id: orderId,
                        affiliation: '0.00',
                        revenue: grandTotal,
                        tax: grandTotalTax,
                        shipping: estTotalShippingPrice,
                        coupon: '',
                    },
                    products: orderProducts,
                },
            },
            ...commonCustomDimensions,
        });
    }
    trackCheckoutEcommerce(checkoutProductDetails) {
        const { index, cartProducts, pageViewDetails } = checkoutProductDetails;
        const transformedCartProducts = this.cartProducts(cartProducts);
        const commonCustomDimensions = this.getCommonCustomDimensions();
        this.pushToDataLayer({
            event: 'checkout',
            ecommerce: {
                checkout: {
                    actionField: {
                        step: index,
                    },
                    products: transformedCartProducts,
                },
            },
            ...commonCustomDimensions,
            ...pageViewDetails,
        });
    }
    /**
     * @todo @unused @typings
     */
    trackAddToListGA(productDetails) {
        const { name, key } = isNonEmptyArray(productDetails.listItems) && productDetails.listItems[0];
        const eventDetails = {
            category: oneRouter.pathname,
            action: 'addToWishList',
            label: key + '_' + name,
        };
        this.trackCustomEvent(eventDetails);
    }
    /**
     * @todo wrong type
     */
    trackRemoveFromCartGA(productDetails) {
        const { skuId, name, price, salePrice, quantity, productOptions, category, brand, } = productDetails;
        const product = {
            name,
            id: skuId,
            price: price || salePrice,
            brand: brand || 'Matee',
            category: category || '',
            variant: this.getProductVariantDetails(productOptions),
            quantity,
            dimension2: 'BOPIS',
        };
        this.pushToDataLayer({
            event: 'removeFromCart',
            RemoveFromCartCategory: oneRouter.pathname === '/checkout' ? 'Checkout Page' : 'Mini Cart',
            ecommerce: {
                remove: {
                    products: [product],
                },
            },
        });
    }
    pushAddToCartEventLayer(productDetail) {
        const { name, id } = productDetail;
        this.pushToDataLayer({
            event: 'addToCart',
            AddToCartCategory: this.pageName,
            AddToCartLabel: name + '_' + id,
            ecommerce: {
                add: {
                    products: [productDetail],
                },
            },
        });
    }
    trackAddToCartEventFromPdp(productDetail) {
        const { string, number } = getTyped(productDetail);
        const variant = transformPdpProductVariant(productDetail);
        const transformedProductDetail = {
            id: string('currentlySelectedSkuId'),
            name: string('name'),
            price: string('salePriceValue'),
            brand: string('brand'),
            category: '',
            variant,
            dimension2: 'BOPIS',
            position: 0,
            quantity: number('quantity'),
        };
        this.pushAddToCartEventLayer(transformedProductDetail);
    }
    trackAddToCartEvent(productDetail) {
        const { string, number } = getTyped(productDetail);
        const { quantity } = productDetail;
        const { productOptions, salePrice } = productDetail.currentlySelectedSku;
        const transformedProductDetail = {
            id: string('identifier'),
            name: string('name'),
            price: salePrice,
            brand: productDetail.brandName,
            category: '',
            variant: transformPlpProductVariant(productOptions),
            dimension2: 'BOPIS',
            position: 0,
            quantity: quantity === 0 ? quantity + 1 : quantity,
        };
        this.pushAddToCartEventLayer(transformedProductDetail);
    }
}
const analyticsContainer = new AnalyticsContainer();
if (typeof window === 'object') {
    console.warn('@todo @@packages merged analytics, needs to initialize the same...');
    analyticsContainer.initializeAnalytics();
}
export { AnalyticsContainer };
export { analyticsContainer };
//# sourceMappingURL=container.js.map