Skip to content

Commit

Permalink
Merge pull request PrestaShop#153 from Hlavtox/workload-1
Browse files Browse the repository at this point in the history
Implement remaining tracking events for GA4
  • Loading branch information
Hlavtox authored Dec 1, 2023
2 parents c80b709 + 9af1d3f commit 20cdcca
Show file tree
Hide file tree
Showing 20 changed files with 805 additions and 612 deletions.
3 changes: 2 additions & 1 deletion classes/Database/Install.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,8 @@ public function registerHooks()
$this->module->registerHook('actionProductCancel') &&
$this->module->registerHook('actionValidateOrder') &&
$this->module->registerHook('actionOrderStatusPostUpdate') &&
$this->module->registerHook('actionCartSave') &&
$this->module->registerHook('actionCartUpdateQuantityBefore') &&
$this->module->registerHook('actionObjectProductInCartDeleteBefore') &&
$this->module->registerHook('displayBackOfficeHeader') &&
$this->module->registerHook('actionCarrierProcess');
}
Expand Down
122 changes: 4 additions & 118 deletions classes/GoogleAnalyticsTools.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,23 +24,6 @@

class GoogleAnalyticsTools
{
/**
* filter
*
* @param string $gaScripts
* @param int $filterable
*
* @return string
*/
public function filter($gaScripts, $filterable)
{
if (1 == $filterable) {
return implode(';', array_unique(explode(';', $gaScripts)));
}

return $gaScripts;
}

/**
* Renders purchase event for order
*
Expand All @@ -57,127 +40,30 @@ public function renderPurchaseEvent($orderProducts, $orderData, $callbackUrl)
}

$callbackData = [
'orderid' => $orderData['id'],
'orderid' => $orderData['transaction_id'],
'customer' => $orderData['customer'],
];

$eventData = [
'transaction_id' => (int) $orderData['id'],
'transaction_id' => (int) $orderData['transaction_id'],
'affiliation' => $orderData['affiliation'],
'value' => (float) $orderData['revenue'],
'value' => (float) $orderData['value'],
'tax' => (float) $orderData['tax'],
'shipping' => (float) $orderData['shipping'],
'currency' => $orderData['currency'],
'items' => [],
'items' => $orderProducts,
'event_callback' => "function() {
$.get('" . $callbackUrl . "', " . json_encode($callbackData, JSON_UNESCAPED_UNICODE) . ');
}',
];

foreach ($orderProducts as $product) {
$eventData['items'][] = [
'item_id' => (int) $product['id'],
'item_name' => $product['name'],
'quantity' => (int) $product['quantity'],
'price' => (float) $product['price'],
];
}

return $this->renderEvent(
'purchase',
$eventData,
['event_callback']
);
}

/**
* addProductClick
*
* @param array $products
* @param string $currencyIsoCode
*
* @return string|void
*/
public function addProductClick($products, $currencyIsoCode)
{
if (!is_array($products)) {
return;
}

$js = '';
foreach ($products as $key => $product) {
$eventData = [
'items' => [
'item_id' => (int) $product['id'],
'item_name' => $product['name'],
'quantity' => (int) $product['quantity'],
'price' => (float) $product['price'],
'currency' => $currencyIsoCode,
'index' => (int) $product['position'],
'item_brand' => $product['brand'],
'item_category' => $product['category'],
'item_list_id' => $product['list'],
'item_variant' => $product['variant'],
],
];

// Add send_to parameter to avoid sending extra events
// to other gtag configs (Ads for example).
$eventData = array_merge(
['send_to' => Configuration::get('GA_ACCOUNT_ID')],
$eventData
);

$productId = explode('-', $product['id']);
$js .= '$(\'article[data-id-product="' . $productId[0] . '"] a.quick-view\').on(
"click",
function() {
gtag("event", "select_item", ' . json_encode($eventData, JSON_UNESCAPED_UNICODE) . ')
});';
}

return $js;
}

/**
* addProductClickByHttpReferal
*
* @param array $products
*
* @return string|void
*/
public function addProductClickByHttpReferal($products, $currencyIsoCode)
{
if (!is_array($products)) {
return;
}

$js = '';
foreach ($products as $key => $product) {
$eventData = [
'items' => [
'item_id' => (int) $product['id'],
'item_name' => $product['name'],
'quantity' => (int) $product['quantity'],
'price' => (float) $product['price'],
'currency' => $currencyIsoCode,
'index' => (int) $product['position'],
'item_brand' => $product['brand'],
'item_category' => $product['category'],
'item_list_id' => $product['list'],
'item_variant' => $product['variant'],
],
];

$js .= $this->renderEvent(
'select_item',
$eventData
);
}

return $js;
}

/**
* Encodes array of data into JSON, optionally ignoring some of the values
*
Expand Down
69 changes: 24 additions & 45 deletions classes/Handler/GanalyticsDataHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,48 +41,12 @@ public function __construct($cartId, $shopId)
$this->shopId = (int) $shopId;
}

/**
* manageData
*
* @param string|array $data
* @param string $action
*
* @return mixed
*/
public function manageData($data, $action)
{
if ('R' === $action) {
return $this->readData();
}

if ('W' === $action) {
return $this->ganalyticsDataRepository->addNewRow(
(int) $this->cartId,
(int) $this->shopId,
json_encode($data)
);
}

if ('A' === $action) {
return $this->appendData($data);
}

if ('D' === $action) {
return $this->ganalyticsDataRepository->deleteRow(
$this->cartId,
$this->shopId
);
}

return false;
}

/**
* readData
*
* @return array
*/
private function readData()
public function readData()
{
$dataReturned = $this->ganalyticsDataRepository->findDataByCartIdAndShopId(
$this->cartId,
Expand All @@ -97,23 +61,38 @@ private function readData()
}

/**
* appendData
*
* @param string $data
* Deletes all persisted data, probably because it was flushed.
*
* @return bool
*/
private function appendData($data)
public function deleteData()
{
$dataReturned = $this->ganalyticsDataRepository->findDataByCartIdAndShopId(
return $this->ganalyticsDataRepository->deleteRow(
$this->cartId,
$this->shopId
);
}

if (false === $dataReturned) {
$newData = [$data];
/**
* Stores event into data repository so we can output it
* on first available chance.
*
* @param string $dataToPersist
*
* @return bool
*/
public function persistData($dataToPersist)
{
// Try to get current data
$currentData = $this->readData();

// If no data has been persisted yet, we create a new array, otherwise
// we add it to the previous events stored.
if (!empty($currentData)) {
$newData = $currentData;
$newData[] = $dataToPersist;
} else {
$newData[] = $this->jsonDecodeValidJson($dataReturned);
$newData = [$dataToPersist];
}

return $this->ganalyticsDataRepository->addNewRow(
Expand Down
45 changes: 20 additions & 25 deletions classes/Hook/HookActionCarrierProcess.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
namespace PrestaShop\Module\Ps_Googleanalytics\Hooks;

use Context;
use PrestaShop\Module\Ps_Googleanalytics\Handler\GanalyticsDataHandler;
use PrestaShop\Module\Ps_Googleanalytics\Repository\CarrierRepository;
use Ps_Googleanalytics;

Expand All @@ -46,15 +45,28 @@ public function run()
{
if (isset($this->params['cart']->id_carrier)) {
$carrierRepository = new CarrierRepository();
$ganalyticsDataHandler = new GanalyticsDataHandler(
$this->context->cart->id,
$this->context->shop->id
);

$carrierName = $carrierRepository->findByCarrierId((int) $this->params['cart']->id_carrier);
$js = $this->getGoogleAnalytics4($carrierName);
// Load carrier name
$carrierName = (string) $carrierRepository->findByCarrierId((int) $this->params['cart']->id_carrier);

// Check if we actually have some name
if (empty($carrierName)) {
return;
}

$ganalyticsDataHandler->manageData($js, 'A');
// Prepare and render the event
$eventData = [
'currency' => $this->context->currency->iso_code,
'value' => (float) $this->context->cart->getSummaryDetails()['total_price'],
'shipping_tier' => $carrierName,
];
$jsCode = $this->module->getTools()->renderEvent(
'add_shipping_info',
$eventData
);

// Store it into our repository so we can flush it on next page load
$this->module->getDataHandler()->persistData($jsCode);
}
}

Expand All @@ -65,21 +77,4 @@ public function setParams($params)
{
$this->params = $params;
}

/**
* @param string $carrierName
*/
protected function getGoogleAnalytics4($carrierName)
{
$eventData = [
'currency' => $this->context->currency->iso_code,
'value' => (float) $this->context->cart->getSummaryDetails()['total_price'],
'shipping_tier' => $carrierName,
];

return $this->module->getTools()->renderEvent(
'add_shipping_info',
$eventData
);
}
}
Loading

0 comments on commit 20cdcca

Please sign in to comment.