-
Notifications
You must be signed in to change notification settings - Fork 1
/
Index.php
101 lines (80 loc) · 3.07 KB
/
Index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
namespace Taggrs\DataLayer\Controller\AddToCart;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Checkout\Model\Session;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Store\Model\StoreManagerInterface;
use Taggrs\DataLayer\Controller\AbstractDataLayerController;
use Taggrs\DataLayer\Helper\QuoteDataHelper;
use Taggrs\DataLayer\Helper\UserDataHelper;
class Index extends AbstractDataLayerController
{
private Session $checkoutSession;
private QuoteDataHelper $quoteDataHelper;
private ProductRepositoryInterface $productRepository;
public function __construct(
Context $context,
JsonFactory $resultJsonFactory,
Session $checkoutSession,
UserDataHelper $userDataHelper,
StoreManagerInterface $storeManager,
QuoteDataHelper $quoteDataHelper,
ProductRepositoryInterface $productRepository
) {
parent::__construct($context, $resultJsonFactory, $userDataHelper, $storeManager);
$this->checkoutSession = $checkoutSession;
$this->quoteDataHelper = $quoteDataHelper;
$this->productRepository = $productRepository;
}
public function getEvent(): string
{
return 'add_to_cart';
}
public function getEcommerce(): array
{
try {
$quote = $this->checkoutSession->getQuote();
} catch (NoSuchEntityException|LocalizedException $e) {
}
if (!isset($quote)) {
return [];
}
$max = 0;
$lastItem = null;
foreach ($quote->getAllVisibleItems() as $quoteItem) {
if ($quoteItem->getId() > $max) {
$max = $quoteItem->getId();
$lastItem = $quoteItem;
}
}
if ($lastItem === null) {
return [];
}
if ($lastItem->getProduct()->getTypeId() === 'configurable') {
$configProduct = $this->productRepository->getById($lastItem->getProduct()->getId());
$item['item_id'] = $configProduct->getSku();
$item['item_variant'] = $lastItem->getSku();
} else {
$item['item_id'] = $lastItem->getSku();
}
$item['item_name'] = $lastItem->getName();
$item['price'] = (float)$lastItem->getPriceInclTax();
$item['quantity'] = $lastItem->getQty();
if ($lastItem->getDiscountAmount() > 0) {
$item['discount'] = $lastItem->getDiscountAmount();
}
if ($lastItem->getQuote()->getCouponCode()) {
$item['coupon'] = $lastItem->getQuote()->getCouponCode();
}
$item = array_merge($item, $this->quoteDataHelper->getCategoryNamesByProduct($lastItem->getProduct()));
return [
'value' => (float)$this->checkoutSession->getQuote()->getGrandTotal(),
'currency' => $this->getCurrency(),
'items' => [$item],
'user_data' => $this->getUserData(),
];
}
}