1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Sunnysideup\EcommerceGoogleAnalytics; |
4
|
|
|
|
5
|
|
|
use SilverStripe\Control\Director; |
6
|
|
|
use SilverStripe\Core\Config\Config; |
7
|
|
|
use SilverStripe\ORM\DataExtension; |
8
|
|
|
use Sunnysideup\Ecommerce\Pages\CheckoutPage; |
9
|
|
|
use TheIconic\Tracking\GoogleAnalytics\Analytics; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Class \Sunnysideup\EcommerceGoogleAnalytics\AnalyticsTransactionReversal |
13
|
|
|
* |
14
|
|
|
* @property \Sunnysideup\Ecommerce\Model\Order|\Sunnysideup\EcommerceGoogleAnalytics\AnalyticsTransactionReversal $owner |
15
|
|
|
*/ |
16
|
|
|
class AnalyticsTransactionReversal extends DataExtension |
17
|
|
|
{ |
18
|
|
|
private static $test_mode = false; |
19
|
|
|
|
20
|
|
|
private static $analytics_code = false; |
21
|
|
|
|
22
|
|
|
public function onBeforeArchive($order) |
23
|
|
|
{ |
24
|
|
|
//reverse the transaction if it has been cancelled |
25
|
|
|
if ($this->isAnalyticsEnabled() && $order->IsCancelled()) { |
26
|
|
|
$orderID = $order->ID; |
27
|
|
|
$memberID = $order->MemberID; |
28
|
|
|
$total = $this->negateValue($order->getSubTotal()); |
29
|
|
|
|
30
|
|
|
$analytics = new Analytics(); |
31
|
|
|
$analytics->setProtocolVersion('1') |
32
|
|
|
->setTrackingId($this->getTrackingID()) |
33
|
|
|
->setUserId(base64_encode($memberID)) |
34
|
|
|
; |
35
|
|
|
|
36
|
|
|
$analytics |
37
|
|
|
->setTransactionId($orderID) // transaction id. required |
38
|
|
|
->setRevenue($total) |
39
|
|
|
->setDebug($this->isTestMode()) |
40
|
|
|
->sendTransaction() |
41
|
|
|
; |
42
|
|
|
|
43
|
|
|
$orderItems = $order->OrderItems(); |
44
|
|
|
foreach ($orderItems as $orderItem) { |
45
|
|
|
$analytics->setTransactionId($orderID) |
46
|
|
|
->setItemName($orderItem->TableTitle()) // required |
47
|
|
|
->setItemPrice($orderItem->CalculatedTotal) |
48
|
|
|
->setItemQuantity($this->negateValue($orderItem->Quantity)) |
49
|
|
|
->setDebug($this->isTestMode()) |
50
|
|
|
->sendItem() |
51
|
|
|
; |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
public function negateValue($value) |
57
|
|
|
{ |
58
|
|
|
return $value * -1; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
public function isTestMode() |
62
|
|
|
{ |
63
|
|
|
return Config::inst()->get(AnalyticsTransactionReversal::class, 'test_mode'); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
public function isAnalyticsEnabled() |
67
|
|
|
{ |
68
|
|
|
$checkoutPage = CheckoutPage::get()->first(); |
69
|
|
|
|
70
|
|
|
return $checkoutPage->EnableGoogleAnalytics && (Director::isLive() || $this->isTestMode()); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
public function getTrackingID() |
74
|
|
|
{ |
75
|
|
|
return Config::inst()->get(AnalyticsTransactionReversal::class, 'analytics_code'); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|