UNPKG

@virto-commerce/front-modules-google-ecommerce-analytics

Version:

This module is designed for use with the VirtoCommerce frontend app. It provides a simple interface to initialize and use Google Analytics, allowing you to track user interactions and events on your website.

216 lines (215 loc) 12.7 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.useGoogleAnalyticsModule = useGoogleAnalyticsModule; var lodash_1 = require("lodash"); var DEBUG_PREFIX = "[GA]"; var GOOGLE_ANALYTICS_SETTINGS_MAPPING = { "GoogleAnalytics4.MeasurementId": "trackId", }; var currencyCode; var canUseDOM = false; var logger = { debug: function () { }, error: function () { }, info: function () { }, warn: function () { }, }; function initModule(_a) { var _b; var getModuleSettings = _a.getModuleSettings, isDevelopment = _a.isDevelopment, loggerInstance = _a.logger, useScriptTag = _a.useScriptTag, currentCurrency = _a.currentCurrency, initialCurrencyCode = _a.currencyCode; var settings = getModuleSettings(GOOGLE_ANALYTICS_SETTINGS_MAPPING); var trackId = settings.trackId; canUseDOM = !!(typeof window !== "undefined" && ((_b = window.document) === null || _b === void 0 ? void 0 : _b.createElement)); if (!canUseDOM || !trackId) { return; } logger = loggerInstance; if (!isDevelopment) { useScriptTag("https://www.googletagmanager.com/gtag/js?id=".concat(trackId)); } else { logger === null || logger === void 0 ? void 0 : logger.debug(DEBUG_PREFIX, "initialized without sync with google"); } currencyCode = initialCurrencyCode; window.dataLayer = window.dataLayer || []; window.gtag = function gtag() { // is not working with rest // eslint-disable-next-line prefer-rest-params window.dataLayer.push(arguments); }; window.gtag("js", new Date()); window.gtag("config", String(trackId), { debug_mode: true }); window.gtag("set", { currency: currentCurrency.value.code }); } function getCategories(breadcrumbs) { if (breadcrumbs === void 0) { breadcrumbs = []; } var categories = {}; breadcrumbs .filter(function (breadcrumb) { return breadcrumb.typeName !== "CatalogProduct"; }) .slice(0, 5) // first five, according to the documentation .forEach(function (breadcrumb, i) { var number = i + 1; categories["item_category".concat(number > 1 ? number : "")] = breadcrumb.title; }); return categories; } function productToGtagItem(item, index) { var _a, _b, _c, _d, _e, _f; var categories = "breadcrumbs" in item ? getCategories(item.breadcrumbs) : {}; return __assign({ index: index, item_id: item.code, item_name: item.name, affiliation: (_a = item.vendor) === null || _a === void 0 ? void 0 : _a.name, price: (_c = (_b = item.price) === null || _b === void 0 ? void 0 : _b.list) === null || _c === void 0 ? void 0 : _c.amount, discount: (_e = (_d = item.price) === null || _d === void 0 ? void 0 : _d.discountAmount) === null || _e === void 0 ? void 0 : _e.amount, quantity: (_f = item.availabilityData) === null || _f === void 0 ? void 0 : _f.availableQuantity }, categories); } function lineItemToGtagItem(item, index) { var _a, _b, _c, _d, _e, _f, _g, _h, _j; var categories = getCategories((_a = item.product) === null || _a === void 0 ? void 0 : _a.breadcrumbs); return __assign({ index: index, item_id: item.sku, item_name: item.name, affiliation: ((_b = item.vendor) === null || _b === void 0 ? void 0 : _b.name) || "?", currency: item.placedPrice.currency.code, discount: ((_c = item.discountAmount) === null || _c === void 0 ? void 0 : _c.amount) || ((_d = item.discountTotal) === null || _d === void 0 ? void 0 : _d.amount), price: "price" in item ? item.price.amount : item.listPrice.amount, quantity: item.quantity, promotion_id: (_f = (_e = item.discounts) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.promotionId, promotion_name: (_h = (_g = item.discounts) === null || _g === void 0 ? void 0 : _g[0]) === null || _h === void 0 ? void 0 : _h.promotionName, promotions: (_j = item.discounts) === null || _j === void 0 ? void 0 : _j.map(function (promotion) { return promotion.promotionName; }).join(", ").trim() }, categories); } /** @deprecated use direct mapping */ function getCartEventParams(cart) { return { currency: currencyCode, value: cart.total.amount, items: cart.items.map(lineItemToGtagItem), items_count: cart.items.length, }; } function sendEvent(eventName, eventParams) { if (canUseDOM && window.gtag) { window.gtag("event", eventName, eventParams); } else { logger === null || logger === void 0 ? void 0 : logger.debug(DEBUG_PREFIX, eventName, eventParams); } } function viewItemList(items, params) { if (items === void 0) { items = []; } sendEvent("view_item_list", __assign(__assign({}, params), { items_skus: items .map(function (el) { return el.code; }) .join(", ") .trim(), items_count: items.length })); } function selectItem(item, params) { var gtagItem = "productId" in item ? lineItemToGtagItem(item) : productToGtagItem(item); sendEvent("select_item", __assign(__assign({}, params), { items: [gtagItem] })); } function viewItem(item, params) { var _a, _b; sendEvent("view_item", __assign(__assign({}, params), { currency: currencyCode, value: (_b = (_a = item.price) === null || _a === void 0 ? void 0 : _a.actual) === null || _b === void 0 ? void 0 : _b.amount, items: [productToGtagItem(item)] })); } function addItemToWishList(item, params) { var _a, _b; sendEvent("add_to_wishlist", __assign(__assign({}, params), { currency: currencyCode, value: (_b = (_a = item.price) === null || _a === void 0 ? void 0 : _a.actual) === null || _b === void 0 ? void 0 : _b.amount, items: [productToGtagItem(item)] })); } function addItemToCart(item, quantity, params) { var _a, _b; if (quantity === void 0) { quantity = 1; } var inputItem = productToGtagItem(item); inputItem.quantity = quantity; sendEvent("add_to_cart", __assign(__assign({}, params), { currency: currencyCode, value: ((_b = (_a = item.price) === null || _a === void 0 ? void 0 : _a.actual) === null || _b === void 0 ? void 0 : _b.amount) * quantity, items: [inputItem] })); } function addItemsToCart(items, params) { var subtotal = (0, lodash_1.sumBy)(items, function (item) { var _a, _b; return (_b = (_a = item === null || item === void 0 ? void 0 : item.price) === null || _a === void 0 ? void 0 : _a.actual) === null || _b === void 0 ? void 0 : _b.amount; }); var inputItems = items.filter(function (item) { return item; }).map(function (item) { return productToGtagItem(item); }); sendEvent("add_to_cart", __assign(__assign({}, params), { currency: currencyCode, value: subtotal, items: inputItems, items_count: inputItems.length })); } function removeItemsFromCart(items, params) { var subtotal = (0, lodash_1.sumBy)(items, function (item) { var _a; return (_a = item.extendedPrice) === null || _a === void 0 ? void 0 : _a.amount; }); var inputItems = items.map(function (item) { return lineItemToGtagItem(item); }); sendEvent("remove_from_cart", __assign(__assign({}, params), { currency: currencyCode, value: subtotal, items: inputItems, items_count: inputItems.length })); } function viewCart(cart, params) { var cartEventParams = getCartEventParams(cart); sendEvent("view_cart", __assign(__assign({}, params), cartEventParams)); } function clearCart(cart, params) { var cartEventParams = getCartEventParams(cart); sendEvent("clear_cart", __assign(__assign({}, params), cartEventParams)); } function beginCheckout(cart, params) { var _a, _b; try { sendEvent("begin_checkout", __assign(__assign({}, params), { currency: cart.currency.code, value: cart.total.amount, items: cart.items.map(lineItemToGtagItem), items_count: cart.items.length, coupon: (_b = (_a = cart.coupons) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.code })); } catch (e) { logger === null || logger === void 0 ? void 0 : logger.error(DEBUG_PREFIX, beginCheckout.name, e); } } function addShippingInfo(cart, params, shipmentMethodOption) { var _a, _b; try { sendEvent("add_shipping_info", __assign(__assign({}, params), { shipping_tier: shipmentMethodOption, currency: cart === null || cart === void 0 ? void 0 : cart.shippingPrice.currency.code, value: cart === null || cart === void 0 ? void 0 : cart.shippingPrice.amount, coupon: (_b = (_a = cart === null || cart === void 0 ? void 0 : cart.coupons) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.code, items: cart === null || cart === void 0 ? void 0 : cart.items.map(lineItemToGtagItem), items_count: cart === null || cart === void 0 ? void 0 : cart.items.length })); } catch (e) { logger === null || logger === void 0 ? void 0 : logger.error(DEBUG_PREFIX, addShippingInfo.name, e); } } function addPaymentInfo(cart, params, paymentGatewayCode) { var _a, _b, _c, _d; try { sendEvent("add_payment_info", __assign(__assign({}, params), { payment_type: paymentGatewayCode, currency: (_a = cart === null || cart === void 0 ? void 0 : cart.currency) === null || _a === void 0 ? void 0 : _a.code, value: (_b = cart === null || cart === void 0 ? void 0 : cart.total) === null || _b === void 0 ? void 0 : _b.amount, coupon: (_d = (_c = cart === null || cart === void 0 ? void 0 : cart.coupons) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.code, items: cart === null || cart === void 0 ? void 0 : cart.items.map(lineItemToGtagItem), items_count: cart === null || cart === void 0 ? void 0 : cart.items.length })); } catch (e) { logger === null || logger === void 0 ? void 0 : logger.error(DEBUG_PREFIX, addPaymentInfo.name, e); } } function purchase(order, transactionId, params) { var _a, _b, _c, _d, _e; try { sendEvent("purchase", __assign(__assign({}, params), { currency: (_a = order.currency) === null || _a === void 0 ? void 0 : _a.code, transaction_id: transactionId, value: order.total.amount, coupon: (_b = order.coupons) === null || _b === void 0 ? void 0 : _b[0], shipping: (_c = order.shippingTotal) === null || _c === void 0 ? void 0 : _c.amount, tax: (_d = order.taxTotal) === null || _d === void 0 ? void 0 : _d.amount, items: order.items.map(lineItemToGtagItem), items_count: (_e = order === null || order === void 0 ? void 0 : order.items) === null || _e === void 0 ? void 0 : _e.length })); } catch (e) { logger === null || logger === void 0 ? void 0 : logger.error(DEBUG_PREFIX, purchase.name, e); } } function placeOrder(order, params) { var _a, _b, _c, _d; try { sendEvent("place_order", __assign(__assign({}, params), { currency: (_a = order.currency) === null || _a === void 0 ? void 0 : _a.code, value: (_b = order.total) === null || _b === void 0 ? void 0 : _b.amount, coupon: (_c = order.coupons) === null || _c === void 0 ? void 0 : _c[0], shipping: order.shippingTotal.amount, tax: order.taxTotal.amount, items_count: (_d = order.items) === null || _d === void 0 ? void 0 : _d.length })); } catch (e) { logger === null || logger === void 0 ? void 0 : logger.error(DEBUG_PREFIX, placeOrder.name, e); } } function search(searchTerm, visibleItems, itemsCount) { if (visibleItems === void 0) { visibleItems = []; } if (itemsCount === void 0) { itemsCount = 0; } sendEvent("search", { search_term: searchTerm, items_count: itemsCount, visible_items: visibleItems .map(function (el) { return el.code; }) .join(", ") .trim(), }); } function useGoogleAnalyticsModule() { return { sendEvent: sendEvent, viewItemList: viewItemList, selectItem: selectItem, viewItem: viewItem, addItemToWishList: addItemToWishList, addItemToCart: addItemToCart, addItemsToCart: addItemsToCart, removeItemsFromCart: removeItemsFromCart, viewCart: viewCart, clearCart: clearCart, beginCheckout: beginCheckout, addShippingInfo: addShippingInfo, addPaymentInfo: addPaymentInfo, purchase: purchase, placeOrder: placeOrder, search: search, initModule: initModule, }; }