Skip to content

Commit bc84529

Browse files
committed
Add data persistence system, make it flush events created during ajax
1 parent bb4a650 commit bc84529

6 files changed

Lines changed: 162 additions & 84 deletions

classes/Handler/GanalyticsDataHandler.php

Lines changed: 24 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -41,48 +41,12 @@ public function __construct($cartId, $shopId)
4141
$this->shopId = (int) $shopId;
4242
}
4343

44-
/**
45-
* manageData
46-
*
47-
* @param string|array $data
48-
* @param string $action
49-
*
50-
* @return mixed
51-
*/
52-
public function manageData($data, $action)
53-
{
54-
if ('R' === $action) {
55-
return $this->readData();
56-
}
57-
58-
if ('W' === $action) {
59-
return $this->ganalyticsDataRepository->addNewRow(
60-
(int) $this->cartId,
61-
(int) $this->shopId,
62-
json_encode($data)
63-
);
64-
}
65-
66-
if ('A' === $action) {
67-
return $this->appendData($data);
68-
}
69-
70-
if ('D' === $action) {
71-
return $this->ganalyticsDataRepository->deleteRow(
72-
$this->cartId,
73-
$this->shopId
74-
);
75-
}
76-
77-
return false;
78-
}
79-
8044
/**
8145
* readData
8246
*
8347
* @return array
8448
*/
85-
private function readData()
49+
public function readData()
8650
{
8751
$dataReturned = $this->ganalyticsDataRepository->findDataByCartIdAndShopId(
8852
$this->cartId,
@@ -97,23 +61,38 @@ private function readData()
9761
}
9862

9963
/**
100-
* appendData
101-
*
102-
* @param string $data
64+
* Deletes all persisted data, probably because it was flushed.
10365
*
10466
* @return bool
10567
*/
106-
private function appendData($data)
68+
public function deleteData()
10769
{
108-
$dataReturned = $this->ganalyticsDataRepository->findDataByCartIdAndShopId(
70+
return $this->ganalyticsDataRepository->deleteRow(
10971
$this->cartId,
11072
$this->shopId
11173
);
74+
}
11275

113-
if (false === $dataReturned) {
114-
$newData = [$data];
76+
/**
77+
* Stores event into data repository so we can output it
78+
* on first available chance.
79+
*
80+
* @param string $dataToPersist
81+
*
82+
* @return bool
83+
*/
84+
public function persistData($dataToPersist)
85+
{
86+
// Try to get current data
87+
$currentData = $this->readData();
88+
89+
// If no data has been persisted yet, we create a new array, otherwise
90+
// we add it to the previous events stored.
91+
if (!empty($currentData)) {
92+
$newData = $currentData;
93+
$newData[] = $dataToPersist;
11594
} else {
116-
$newData[] = $this->jsonDecodeValidJson($dataReturned);
95+
$newData = [$dataToPersist];
11796
}
11897

11998
return $this->ganalyticsDataRepository->addNewRow(

classes/Hook/HookActionCarrierProcess.php

Lines changed: 15 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,22 @@ public function run()
5151
$this->context->shop->id
5252
);
5353

54-
$carrierName = $carrierRepository->findByCarrierId((int) $this->params['cart']->id_carrier);
55-
$js = $this->getGoogleAnalytics4($carrierName);
54+
// Load carrier name
55+
$carrierName = (string) $carrierRepository->findByCarrierId((int) $this->params['cart']->id_carrier);
56+
57+
// Prepare and render the event
58+
$eventData = [
59+
'currency' => $this->context->currency->iso_code,
60+
'value' => (float) $this->context->cart->getSummaryDetails()['total_price'],
61+
'shipping_tier' => $carrierName,
62+
];
63+
$js = $this->module->getTools()->renderEvent(
64+
'add_shipping_info',
65+
$eventData
66+
);
5667

57-
$ganalyticsDataHandler->manageData($js, 'A');
68+
// Store it into our repository so we can flush it on next page load
69+
$ganalyticsDataHandler->persistData($js);
5870
}
5971
}
6072

@@ -65,21 +77,4 @@ public function setParams($params)
6577
{
6678
$this->params = $params;
6779
}
68-
69-
/**
70-
* @param string $carrierName
71-
*/
72-
protected function getGoogleAnalytics4($carrierName)
73-
{
74-
$eventData = [
75-
'currency' => $this->context->currency->iso_code,
76-
'value' => (float) $this->context->cart->getSummaryDetails()['total_price'],
77-
'shipping_tier' => $carrierName,
78-
];
79-
80-
return $this->module->getTools()->renderEvent(
81-
'add_shipping_info',
82-
$eventData
83-
);
84-
}
8580
}

classes/Hook/HookActionCartSave.php

Lines changed: 71 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,75 @@ public function __construct(Ps_Googleanalytics $module, Context $context)
5151
*/
5252
public function run()
5353
{
54+
// Check if this request is coming to cart controller, we have some product ID and some action to do
55+
if ($this->context->controller->php_self != 'cart' ||
56+
!Tools::isSubmit('id_product') ||
57+
!Tools::isSubmit('action')
58+
) {
59+
return;
60+
}
61+
62+
// Resolve action and required parameters
63+
$id_product = null;
64+
$id_product_attribute = null;
65+
$event = null;
66+
$event_quantity = null;
67+
68+
/*
69+
* Add to cart from product page
70+
* POST - [id_product] => 1, [qty] => 1, [add] => 1
71+
*/
72+
if (Tools::isSubmit('add')) {
73+
$id_product = (int) Tools::getValue('id_product');
74+
$id_product_attribute = 0; // This information is not passed, we would need to somehow get it from the attributes
75+
$event = 'add_to_cart';
76+
$event_quantity = (int) Tools::getValue('qty');
77+
78+
/*
79+
* Up from cart page
80+
* GET - [id_product] => 1, [id_product_attribute] => 1
81+
* POST - [qty] => 2, [op] => up
82+
*/
83+
} else if (Tools::isSubmit('op') && Tools::getValue('op') == 'up') {
84+
$id_product = (int) Tools::getValue('id_product');
85+
$id_product_attribute = (int) Tools::getValue('id_product_attribute');
86+
$event = 'add_to_cart';
87+
$event_quantity = (int) Tools::getValue('qty');
88+
89+
/*
90+
* Down from cart page
91+
* GET - [id_product] => 1, [id_product_attribute] => 1
92+
* POST - [qty] => 2, [op] => down
93+
*/
94+
} else if (Tools::isSubmit('op') && Tools::getValue('op') == 'down') {
95+
$id_product = (int) Tools::getValue('id_product');
96+
$id_product_attribute = (int) Tools::getValue('id_product_attribute');
97+
$event = 'remove_from_cart';
98+
$event_quantity = (int) Tools::getValue('qty');
99+
100+
/*
101+
* Delete from cart page
102+
* GET - [id_product] => 1, [id_product_attribute] => 1, [delete] => 1
103+
*/
104+
} else if (Tools::isSubmit('delete')) {
105+
$id_product = (int) Tools::getValue('id_product');
106+
$id_product_attribute = (int) Tools::getValue('id_product_attribute');
107+
$event = 'remove_from_cart';
108+
$event_quantity = 1; // We have no easy way to distinguish this
109+
}
110+
111+
// Get our tag handler
112+
$ganalyticsDataHandler = new GanalyticsDataHandler(
113+
$this->context->cart->id,
114+
$this->context->shop->id
115+
);
116+
117+
$ganalyticsDataHandler->persistData("Event " . $event . ", id_product " . $id_product . ", id_product_attribute " . $id_product_attribute . ", event_quantity " . $event_quantity . "");
118+
return;
119+
120+
// Render the event
121+
// $this->gaScripts .= $this->module->getTools()->renderEvent('sign_up', []);
122+
54123
if (!isset($this->context->cart)) {
55124
return;
56125
}
@@ -113,7 +182,7 @@ public function run()
113182
$productId = Tools::getValue('id_product');
114183
}
115184

116-
$gaCart = $ganalyticsDataHandler->manageData('', 'R');
185+
$gaCart = $ganalyticsDataHandler->readData();
117186

118187
if ($cart['removeAction'] == 'delete') {
119188
$gaProducts['quantity'] = -1;
@@ -130,7 +199,7 @@ public function run()
130199
}
131200

132201
$gaCart[$productId] = $gaProducts;
133-
$ganalyticsDataHandler->manageData($gaCart, 'W');
202+
$ganalyticsDataHandler->persistData($gaCart);
134203
}
135204
}
136205
}

classes/Hook/HookDisplayBackOfficeHeader.php

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -154,22 +154,23 @@ public function processOrder($idOrder)
154154
// Empty script for the current order
155155
$gaScripts = '';
156156

157+
// Prepare order products, if the cart still exists
158+
$orderProducts = [];
159+
$cart = new Cart($order->id_cart);
160+
if (Validate::isLoadedObject($cart)) {
161+
$orderProducts = $productWrapper->prepareItemListFromProductList($cart->getProducts(), true);
162+
}
163+
157164
// Add payment event
158165
$gaScripts .= $this->module->getTools()->renderEvent(
159166
'add_payment_info',
160167
[
161168
'currency' => $orderData['currency'],
162169
'payment_type' => $orderData['payment_type'],
170+
'items' => $orderProducts
163171
]
164172
);
165173

166-
// Prepare order products, if the cart still exists
167-
$orderProducts = [];
168-
$cart = new Cart($order->id_cart);
169-
if (Validate::isLoadedObject($cart)) {
170-
$orderProducts = $productWrapper->prepareItemListFromProductList($cart->getProducts(), true);
171-
}
172-
173174
// Render transaction code
174175
$gaScripts .= $this->module->getTools()->renderPurchaseEvent(
175176
$orderProducts,

classes/Hook/HookDisplayBeforeBodyClosingTag.php

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,12 +50,20 @@ public function __construct(Ps_Googleanalytics $module, Context $context)
5050
*/
5151
public function run()
5252
{
53+
$ganalyticsDataHandler = new GanalyticsDataHandler(
54+
$this->context->cart->id,
55+
$this->context->shop->id
56+
);
57+
5358
// Prepare our tag handler
5459
$gaTagHandler = new GanalyticsJsHandler($this->module, $this->context);
5560

5661
// Log information about product listing
5762
$this->saveInformationAboutListing();
5863

64+
// Flush events stored in data storage from previous pages
65+
$this->outputStoredEvents();
66+
5967
// Add events
6068
$this->renderProductListing();
6169
$this->renderSearch();
@@ -77,7 +85,7 @@ public function run()
7785
$this->context->shop->id
7886
);
7987

80-
$gacarts = $ganalyticsDataHandler->manageData('', 'R');
88+
$gacarts = $ganalyticsDataHandler->readData();
8189
$controller_name = Tools::getValue('controller');
8290

8391
if (count($gacarts) > 0 && $controller_name != 'product') {
@@ -140,8 +148,6 @@ public function run()
140148
$this->gaScripts .= $gacart;
141149
}
142150
}
143-
144-
$ganalyticsDataHandler->manageData('', 'D');
145151
}
146152

147153
return $gaTagHandler->generate($this->gaScripts);
@@ -322,4 +328,31 @@ private function saveInformationAboutListing()
322328
'item_list_name' => $listing['label'],
323329
]);
324330
}
331+
332+
/**
333+
* Outputs all events we stored into data repository during previous AJAX requests
334+
* on previous page.
335+
*/
336+
private function outputStoredEvents()
337+
{
338+
// Prepare handler responsible for storing our data
339+
$ganalyticsDataHandler = new GanalyticsDataHandler(
340+
$this->context->cart->id,
341+
$this->context->shop->id
342+
);
343+
344+
// Get all stored events
345+
$storedEvents = $ganalyticsDataHandler->readData();
346+
if (empty($storedEvents)) {
347+
return;
348+
}
349+
350+
foreach ($storedEvents as $event) {
351+
$this->gaScripts .= $event;
352+
dump($event);
353+
}
354+
355+
// Delete the repository because everything has been flushed
356+
$ganalyticsDataHandler->deleteData();
357+
}
325358
}

classes/Hook/HookDisplayOrderConfirmation.php

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -75,22 +75,23 @@ public function run()
7575
// Prepare transaction data
7676
$orderData = $orderWrapper->wrapOrder($order);
7777

78+
// Prepare order products, if the cart still exists
79+
$orderProducts = [];
80+
$cart = new Cart($order->id_cart);
81+
if (Validate::isLoadedObject($cart)) {
82+
$orderProducts = $productWrapper->prepareItemListFromProductList($cart->getProducts(), true);
83+
}
84+
7885
// Add payment event
7986
$gaScripts .= $this->module->getTools()->renderEvent(
8087
'add_payment_info',
8188
[
8289
'currency' => $orderData['currency'],
8390
'payment_type' => $orderData['payment_type'],
91+
'items' => $orderProducts
8492
]
8593
);
8694

87-
// Prepare order products, if the cart still exists
88-
$orderProducts = [];
89-
$cart = new Cart($order->id_cart);
90-
if (Validate::isLoadedObject($cart)) {
91-
$orderProducts = $productWrapper->prepareItemListFromProductList($cart->getProducts(), true);
92-
}
93-
9495
// Render transaction code
9596
$gaScripts .= $this->module->getTools()->renderPurchaseEvent(
9697
$orderProducts,

0 commit comments

Comments
 (0)