Skip to content

Commit

Permalink
Update price logic & GA4
Browse files Browse the repository at this point in the history
  • Loading branch information
srenon committed Mar 2, 2021
1 parent 9f424a8 commit 289bfd2
Show file tree
Hide file tree
Showing 10 changed files with 189 additions and 115 deletions.
25 changes: 1 addition & 24 deletions Block/Data/Product.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,9 @@
namespace MagePal\GoogleTagManager\Block\Data;

use Exception;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Block\Product\AbstractProduct;
use Magento\Catalog\Block\Product\Context;
use Magento\Catalog\Helper\Data;
use Magento\Catalog\Pricing\Price\FinalPrice;
use MagePal\GoogleTagManager\Block\DataLayer;
use MagePal\GoogleTagManager\DataLayer\ProductData\ProductProvider;
use MagePal\GoogleTagManager\Helper\Product as ProductHelper;
Expand Down Expand Up @@ -70,7 +68,7 @@ protected function _prepareLayout()
'parent_sku' => $product->getData('sku'),
'product_type' => $product->getTypeId(),
'name' => $product->getName(),
'price' => $this->getPrice(),
'price' => $this->productHelper->getProductPrice($product),
'attribute_set_id' => $product->getAttributeSetId(),
'path' => implode(" > ", $this->getBreadCrumbPath()),
'category' => $this->getProductCategoryName(),
Expand All @@ -91,27 +89,6 @@ protected function _prepareLayout()
return $this;
}

/**
* @return mixed
*/
public function getPrice()
{
/** @var $tm DataLayer */
$tm = $this->getParentBlock();
$price = 0;

/** @var $product ProductInterface */
if ($this->getProduct()) {
$price = $this->getProduct()
->getPriceInfo()
->getPrice(FinalPrice::PRICE_CODE)
->getAmount()
->getBaseAmount() ?: 0;
}

return $tm->formatPrice($price);
}

/**
* Get category name from breadcrumb
*
Expand Down
19 changes: 18 additions & 1 deletion Block/DataLayerAbstract.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,18 @@
use MagePal\GoogleTagManager\Helper\Data as GtmHelper;

/**
* @method setBlockName($name)
* @method getBlockName()
* @method setList($name)
* @method getList()
* @method setListType()
* @method setListType($type)
* @method getListType()
* @method setItemListName($name)
* @method getItemListName()
* @method setUseWidgetTitle($title)
* @method getUseWidgetTitle()
* @method getShowCategory()
* @method getCatalogWidgetBlockList()
*/
class DataLayerAbstract extends Template
{
Expand Down Expand Up @@ -88,6 +97,14 @@ public function getDataLayer()
['dataLayer' => $this]
);

return $this->processDataLayer();
}

/**
* @return array
*/
public function processDataLayer()
{
$result = [];

if (!empty($this->getVariables())) {
Expand Down
23 changes: 23 additions & 0 deletions DataLayer/ProductData/ProductImpressionAbstract.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ abstract class ProductImpressionAbstract
/** @var string */
private $listType = '';

/**
* @var string
*/
private $itemListName = '';

/**
* @return array
*/
Expand Down Expand Up @@ -94,4 +99,22 @@ public function setListType(string $listType)
$this->listType = $listType;
return $this;
}

/**
* @return string
*/
public function getItemListName()
{
return $this->itemListName;
}

/**
* @param string $itemListName
* @return ProductImpressionAbstract
*/
public function setItemListName(string $itemListName)
{
$this->itemListName = $itemListName;
return $this;
}
}
83 changes: 83 additions & 0 deletions Helper/Data.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@

namespace MagePal\GoogleTagManager\Helper;

use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Pricing\Price\FinalPrice;
use Magento\Catalog\Model\Product\Type;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Store\Model\ScopeInterface;

Expand Down Expand Up @@ -202,4 +205,84 @@ public function setDataLayerName($name)
$this->_dataLayerName = $name;
return $this;
}

/**
* @param null $store_id
* @return bool
*/
public function isCategoryLayerEnabled($store_id = null)
{
return $this->scopeConfig->isSetFlag(
'googletagmanager/general/category_layer',
ScopeInterface::SCOPE_STORE,
$store_id
);
}

/**
* @param ProductInterface $product
* @param array $viewItem
*/
public function addCategoryElements($product, &$viewItem)
{
if (!$this->isCategoryLayerEnabled() || !$product) {
return;
}

$categoryList = [];
$index = 1;
$categoryCollection = $product->getCategoryCollection();
$categories = $categoryCollection->addAttributeToSelect('name');

if (array_key_exists('item_category', $viewItem)) {
$index = 2;
$categoryList[] = $viewItem['item_category'];
}

foreach ($categories as $category) {
if (!in_array($category->getName(), $categoryList)) {
$categoryList[] = $category->getName();

if ($index == 1) {
$viewItem['item_category'] = $category->getName();
$index++;
} else {
$viewItem['item_category_' . $index] = $category->getName();
$index++;
}

if ($index >= 5) {
break;
}
}
}
}

/**
* @param $product
* @return float
*/
public function getProductPrice($product)
{
$price = 0;

/** @var $product ProductInterface */
if ($product) {
$price = $product
->getPriceInfo()
->getPrice(FinalPrice::PRICE_CODE)
->getAmount()
->getBaseAmount() ?: 0;
}

if (!$price) {
if ($product->getTypeId() == Type::TYPE_SIMPLE) {
$price = $product->getPrice();
} else {
$price = $product->getFinalPrice();
}
}

return $this->formatPrice($price);
}
}
13 changes: 0 additions & 13 deletions Helper/DataLayerItem.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,19 +55,6 @@ public function getItemVariantFormat($store_id = null)
}
}

/**
* @param null $store_id
* @return bool
*/
public function isCategoryLayerEnabled($store_id = null)
{
return $this->scopeConfig->isSetFlag(
'googletagmanager/general/category_layer',
ScopeInterface::SCOPE_STORE,
$store_id
);
}

/**
* @param OrderItem $item | QuoteItem $item
* @return array
Expand Down
5 changes: 2 additions & 3 deletions Helper/Product.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,11 @@

namespace MagePal\GoogleTagManager\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Framework\UrlInterface;

class Product extends AbstractHelper
class Product extends Data
{

public function getImageUrl($product)
{
/** @var $product ProductInterface */
Expand Down
13 changes: 11 additions & 2 deletions Model/DataLayerEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,18 @@ class DataLayerEvent
const CART_PAGE_EVENT = 'cartPage';
const PURCHASE_EVENT = 'purchase';
const ORDER_SUCCESS_PAGE_EVENT = 'orderSuccessPage';
/** @deprecated - GTM_ORDER_COMPLETE_EVENT replace with PURCHASE_EVENT */
const GTM_ORDER_COMPLETE_EVENT = 'gtm.orderComplete';
const ALL_PAGE_EVENT = 'allPage';
const SEARCH_PAGE_EVENT = 'searchPage';
const HOME_PAGE_EVENT = 'homePage';

/** @deprecated - GTM_ORDER_COMPLETE_EVENT replace with PURCHASE_EVENT */
const GTM_ORDER_COMPLETE_EVENT = 'gtm.orderComplete';

/** Google Analytics 4 */
const GA4_REFUND_EVENT = 'refund';
const GA4_ADD_TO_CART_EVENT = 'add_to_cart';
const GA4_REMOVE_FROM_CART_EVENT = 'remove_from_cart';
const GA4_VIEW_ITEM_LIST = 'view_item_list';
const GA4_VIEW_ITEM = 'view_item';
const GA4_VIEW_CART = 'view_cart';
}
65 changes: 38 additions & 27 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
[![Total Downloads](https://poser.okvpn.org/magepal/magento2-googletagmanager/downloads)](https://packagist.org/packages/magepal/magento2-googletagmanager)
[![Latest Stable Version](https://poser.okvpn.org/magepal/magento2-googletagmanager/v/stable)](https://packagist.org/packages/magepal/magento2-googletagmanager)

#### Whether you are a small Magento retailer or an Enterprise customer, our suite of Google Tag Manager extensions will help you integrate the most challenging GTM projects within days, instead of spending weeks or months creating custom solutions.
#### Whether you are a small Magento retailer or an Enterprise customer, our suite of Google Tag Manager extensions will help you integrate the most challenging GTM projects within days, instead of spending weeks or months creating custom solutions.
For Magento 2.0.x, 2.1.x, 2.2.x, 2.3.x and 2.4.x

<a href="https://www.magepal.com/magento2/extensions/digital-marketing.html"><img alt="Magento Enhanced Ecommerce for Google Tag Manager" src="https://user-images.githubusercontent.com/1415141/88172990-d89cd300-cbef-11ea-8a51-cc39f55b0218.png" /></a>
Expand All @@ -19,12 +19,12 @@ Magento code providing the data is available to Google Tag Manager.

Google Tag Manager makes running your digital marketing campaigns much easier when calibrating with multiple department and Ad agencies by making available the right set of tools so that everyone can get their job done quickly without relying on developers.

Without having the all data you need at your finger tips your integration will become a difficult, time-consuming and messy since each developer will only focus on the current task at hand instead of focusing on writing reusable components for future integration.
Without having the all data you need at your fingertips your integration will become a difficult, time-consuming and messy since each developer will only focus on the current task at hand instead of focusing on writing reusable components for future integration.

Our extension provides a vast array of over 60 preconfigure data layer elements to make integrating your Magento store with any other third-party service a breeze using Google Tag Manager.
Extracting, customizing and adding your own custom data from your Magento store to Google Tag Manager is as easy as 10 lines of code using our easy to customize APIs.

>:warning: Google Tag Manager 2.5.0 has some breaking changes to Enhanced Ecommerce. Please download the latest version of Enhanced Ecommerce 1.5.0 or greater from www.magepal.com account.
>:warning: Google Tag Manager 2.6.0 has some breaking changes to Enhanced Ecommerce. Please download the latest version of Enhanced Ecommerce 1.6.0 or greater from www.magepal.com account.

### Why use our Google Tag Manager extension?
Expand All @@ -34,9 +34,13 @@ full advantage of GTM when integrating third-parties tracking codes that require
such as product name, price, items added to cart, order items, total, shipping amount or any other data. Our extension
provides hundreds of data elements and events to accomplish any integration and provides the building block to make
your next integration a success. With a few lines of code, you can quickly extend our extension to accomplish your
most challenging integration. Google Tag Manager is only as powerful as the data layer powering it. 
most challenging integration. Google Tag Manager is only as powerful as the data layer powering it.
Learn more about [customizing Google Tag Manger](https://www.magepal.com/help/docs/google-tag-manager-for-magento/#api).

### Google Analytics 4
Upgrade to the next generation of tracking from Google. [Google Analytics 4](https://www.magepal.com/google-analytics-4-for-google-tag-manager.html?utm_source=ga4%20for%20Google%20Tag%20Manager&utm_medium=github) comes with a bunch of key features that make it very different and more powerful than Enhanced Ecommerce.
Gain access to GA4 new approach to privacy-first tracking, channel measurement, and AI based predictive data with MagePal Google Analytics 4 Extension.

### Google Analytics Enhanced E-commerce
Want to track more? Upgrade to our new [Enhanced E-commerce for Google Tag Manager](https://www.magepal.com/enhanced-ecommerce-for-google-tag-manager.html?utm_source=Enhanced%20Ecommerce%20for%20Google%20Tag%20Manager&utm_medium=github) to take full advantage of Google Analytics most powerful e-commerce features.
Gain valuable insight and increase your conversion rate by leveraging Google Enhanced Ecommerce to better understand your user actions and behaviors.
Expand All @@ -58,28 +62,30 @@ Please Note: Merchants should consult with their own legal counsel to ensure tha

### Get more from Google Tag Manager with our add-on Extensions

| Features | GTM | EE | DL |
|-----------------------------|:---:|:--:|:--:|
| Global Page Tracking | X | X | |
| Order Conversion Tracking | X | X | |
| Page Type Event | | X | |
| Product Clicks | | X | |
| Product Detail Impressions | | X | |
| Add to Cart | | X | |
| Remove from Cart | | X | |
| Checkout Steps | | X | |
| Order Refunds | | X | |
| Admin Order Tracking | | X | |
| Access DataLayer using JS | | | X |
| Bing UET Tracking | | | X |
| Full Facebook Tracking | | | X |
| Custom Image Pixel Tracking | | | X |
| Custom iFrame Tracking | | | X |
| Third-Party Integration | | | X |
| Extend individual page type | | | X |
| Features | GTM | EE | GA4 | DL |
|-----------------------------|:---:|:---:|:---:|:---:|
| Global Page Tracking | X | X | X | |
| Order Conversion Tracking | X | X | X | |
| Page Type Event | | X | X | |
| Product Clicks | | X | X | |
| Product Detail Impressions | | X | X | |
| Add to Cart | | X | X | |
| Remove from Cart | | X | X | |
| Checkout Steps | | X | X | |
| Order Refunds | | X | X | |
| Admin Order Tracking | | X | X | |
| Access DataLayer using JS | | | | X |
| Bing UET Tracking | | | | X |
| Full Facebook Tracking | | | | X |
| Custom Image Pixel Tracking | | | | X |
| Custom iFrame Tracking | | | | X |
| Third-Party Integration | | | | X |
| Extend individual page type | | | | X |

GTM - [Google Tag Manager for Magento 2 Extension](https://www.magepal.com/magento2/extensions/google-tag-manager.html)

GA4 - [Google Analytics 4 for Google Tag Manager Extension](https://www.magepal.com/magento2/extensions/google-analytics-4-for-google-tag-manager.html)

EE - [Enhanced E-commerce for Google Tag Manager Extension](https://www.magepal.com/magento2/extensions/enhanced-ecommerce-for-google-tag-manager.html)

DL - [DataLayer for Google Tag Manager Extension](https://www.magepal.com/magento2/extensions/datalayer-for-google-tag-manager.html)
Expand Down Expand Up @@ -152,22 +158,26 @@ Our Magento extension provide a vast array of over 60 preconfigure data layer el
* Events
* productImpression*, categoryPage**, allPage**, catalogCategoryViewPage**, mpCustomerSession
* productClick*, addToCart*, productListSwatchClicked**, productListSwatchSelected**
* view_item_list***, select_item***, add_to_cart***

##### Product Detail Page Events
* Events
* productDetail*, productImpression*, productPage**, allPage**, catalogProductViewPage**, mpCustomerSession
* productClick*, addToCart*, removeFromCart*, productDetailSwatchClicked**, productDetailSwatchSelected**, addToCartItemOutOfStock*, addToCartItemOptionRequired*
* productClick*, addToCart*, removeFromCart*, productDetailSwatchClicked**, productDetailSwatchSelected**, addToCartItemOutOfStock*, addToCartItemOptionRequired*, addToCartItemInvalidQtyIncrements*
* view_item***, select_item***, add_to_cart***, view_item_list***

##### Shopping Cart Page Events
* Events
* cartPage**, allPage**, checkoutCartIndexPage**, productImpression*, mpCustomerSession
* productClick*, addToCart*, removeFromCart*

* select_item***, add_to_cart***, remove_from_cart***, view_item_list***

##### Checkout Page Events
* Events
* checkoutPage**, allPage**, checkoutIndexIndexPage**, checkout*, checkoutOption*, mpCustomerSession
* checkoutEmailValidation*, shippingMethodAdded*, checkoutShippingStepCompleted*, checkoutShippingStepFailed*, paymentMethodAdded*, checkoutPaymentStepFailed*, checkoutPaymentStepCompleted*

* begin_checkout***, add_shipping_info***, add_payment_info***

##### Order Confirmation Page Events
* Events
* purchase*, orderSuccessPage**, allPage**, checkoutOnepageSuccessPage**
Expand Down Expand Up @@ -345,7 +355,8 @@ Our Magento extension provide a vast array of over 60 preconfigure data layer el
`*` - Data layer provide by our [Enhanced Ecommerce Extension](https://www.magepal.com/enhanced-ecommerce-for-google-tag-manager.html)

`**` - Data layer provide by our [Data Layer Extension](https://www.magepal.com/magento2/extensions/datalayer-for-google-tag-manager.html)


`***` - Data layer provide by our [Google Analytics 4 Extension](https://www.magepal.com/google-analytics-4-for-google-tag-manager.html)

Contribution
---
Expand Down
Loading

0 comments on commit 289bfd2

Please sign in to comment.