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
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Quote\Observer\Backend;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Customer\Model\Config\Share as ShareConfig;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
/**
* Class CustomerQuote
*/
class CustomerQuoteObserver implements ObserverInterface
{
/**
* @var ShareConfig
*/
protected $config;
/**
* @var StoreManagerInterface
*/
protected $storeManager;
/**
* @var \Magento\Quote\Api\CartRepositoryInterface
*/
protected $quoteRepository;
/**
* @param StoreManagerInterface $storeManager
* @param ShareConfig $config
* @param CartRepositoryInterface $quoteRepository
*/
public function __construct(
StoreManagerInterface $storeManager,
ShareConfig $config,
CartRepositoryInterface $quoteRepository
) {
$this->storeManager = $storeManager;
$this->config = $config;
$this->quoteRepository = $quoteRepository;
}
/**
* Set new customer group to all his quotes
*
* @param Observer $observer
* @return void
*/
public function execute(Observer $observer)
{
/** @var \Magento\Customer\Api\Data\CustomerInterface $customer */
$customer = $observer->getEvent()->getCustomerDataObject();
try {
$quote = $this->quoteRepository->getForCustomer($customer->getId());
if ($customer->getGroupId() !== $quote->getCustomerGroupId()) {
/**
* It is needed to process customer's quotes for all websites
* if customer accounts are shared between all of them
*/
/** @var $websites \Magento\Store\Model\Website[] */
$websites = $this->config->isWebsiteScope()
? [$this->storeManager->getWebsite($customer->getWebsiteId())]
: $this->storeManager->getWebsites();
foreach ($websites as $website) {
$quote->setWebsite($website);
$quote->setCustomerGroupId($customer->getGroupId());
$quote->collectTotals();
$this->quoteRepository->save($quote);
}
}
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
}
}
}