Can we restrict customer for add to cart once his quote total crosses specific count?
For example i need to restrict customer add to cart action, once the subtotal in quote crosses 500. I have created customer custom attribute called order_limit, can we check this condition and restrict customer to do add to cart action?
I used below event in my events.xml
<event name="controller_action_predispatch_checkout_cart_add">
<observer name="checkout_cart_add" instance="[Vendor]\[Module]\Observer\RestrictCart" />
</event>
This is my observer code
class RestrictCart implements ObserverInterface{
protected $_objectManager = null;
protected $_messageManager;
protected $_customerSession;
protected $quoteFactory;
protected $_checkoutSession;
protected $_customer;
public function __construct(
\Magento\Framework\Message\ManagerInterface $messageManager,
\Magento\Framework\ObjectManagerInterface $objectManager,
\Magento\Customer\Model\Session $customerSession,
\Magento\Quote\Model\QuoteFactory $quoteFactory,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Customer\Model\CustomerFactory $customer
){
$this->_messageManager = $messageManager;
$this->_objectManager = $objectManager;
$this->_customerSession = $customerSession;
$this->quoteFactory = $quoteFactory;
$this->_checkoutSession = $checkoutSession;
$this->_customer = $customer;
}
public function execute(\Magento\Framework\Event\Observer $observer){
try{
if($observer->getRequest()->getParam('product', false)) {
$productId = $observer->getRequest()->getParam('product', false);
$requestedQty = $observer->getRequest()->getParam('qty', false);
$product = $this->_objectManager->create('Magento\Catalog\Model\Product')->load($observer->getRequest()->getParam('product', false));
$StockState = $this->_objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
$resource = $this->_objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
if($this->_customerSession->isLoggedIn()){
$customerId = $this->_customerSession->getCustomer()->getId();
$cusomerData = $this->getCurrentCustomer($customerId);
$order_limit = $cusomerData->getOrderLimit();
$quote = $this->_checkoutSession->getQuote();
$subTotal = $quote->getSubtotal();
if($subTotal > $order_limit){
$this->_messageManager->addError(__('Order limit Crossed!!!'));
return $this;
}
}
return $this;
}catch (\Exception $e) {
print_r($e->getMessage());
}
}
public function getQuoteCollection($customerId)
{
$quote = $this->quoteFactory->create()->getCollection()->addFieldToFilter('customer_id',$customerId);
return $quote;
}
public function getCurrentCustomer($id){
$customerObj = $this->_customer->create();
$customer = $customerObj->load($id);
return $customer;
}
}
This code is working fine only when we add product from detail page, how same thing can be used on updating cart?
controller_action_predispatch_checkout_cart_add
? I donot think is good because this event does not called every time