#StackBounty: #magento2 #checkout #tax #plugin Custom Tax Calculation infinite loop issue in Magento2

Bounty: 100

I am calculating custom Tax for the cart item, Used the following code.

Vendor/Module/etc/di.xml

<type name="MagentoQuoteModelQuoteAddressTotal">
    <plugin name="mbs_customtax_cart_item" type="VendorModulePluginCustomTaxTotal" />
</type>

Vendor/Module/Plugin/CustomTaxTotal.php

<?php

namespace VendorModulePlugin;

class CustomTaxTotal
{

private $logger;   
private $_productloader;  
private $_cart;
private $customTax = null;   
private $cartItemLoader;

public function __construct(
    PsrLogLoggerInterface $logger,
    VendorModuleModelProductCartItemLoader $cartItemLoader
) {
    $this->logger = $logger;
    $this->cartItemLoader = $cartItemLoader;
}

private function calculateCustomTaxForQuote()
{
    if (is_null($this->customTax)) {
        $this->logger->info('--total--');
        $this->customTax = $this->cartItemLoader->getCartItemWithTaxRates();
    }

    return $this->customTax;
}

public function beforeAddTotalAmount(
    MagentoQuoteModelQuoteAddressTotal $subject,
    $code,
    $amount
) {
    if ($code =='tax') {
        $amount += $this->calculateCustomTaxForQuote();
    }

    return [$code, $amount];
}

public function beforeAddBaseTotalAmount(
    MagentoQuoteModelQuoteAddressTotal $subject,
    $code,
    $amount
) {
    if ($code =='tax') {
        $amount += $this->calculateCustomTaxForQuote();
    }

    return [$code, $amount];
  }
 }

VendorModuleModelProductCartItemLoader.php

<?php
namespace VendorModuleModel;

class ProductCartItemLoader
{
 private $productFactory;

private $cart;

private $customerSession;

private $taxCalculation;

private $scopeConfig;

private $collectionFactory;

private $dataObjectFactory;

public function __construct(
    MagentoCatalogModelProductFactory $productFactory,
    MagentoCheckoutModelCart $cart,
    MagentoCustomerModelSession $customerSession,
    MagentoTaxModelCalculation $taxCalculation,
    MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig,
    MagentoFrameworkDataCollectionFactory $collectionFactory,
    MagentoFrameworkDataObjectFactory $dataObjectFactory
) {
    $this->productFactory = $productFactory;
    $this->cart = $cart;
    $this->customerSession = $customerSession;
    $this->taxCalculation = $taxCalculation;
    $this->scopeConfig = $scopeConfig;
    $this->collectionFactory = $collectionFactory;
    $this->dataObjectFactory = $dataObjectFactory;
}

public function getCartItemWithTaxRates()
{
    $itemsCollection = $this->cart->getQuote()->getItemsCollection();
    $productCollection = $this->getProductWithExternalData($itemsCollection);

    $taxAmount = 0;
    foreach ($itemsCollection as $item) {
        $product = $productCollection->getItemByColumnValue('entity_id', $item->getProductId());

        if ($product and $product->getData('pod_image_id')!='') {
            $taxRate = $this->getRate($product);

            if ($taxRate > 0) {
                $taxAmount += ($product->getData('pod_price') * $taxRate)/100;
            }
        }
    }

    return $taxAmount;
}

private function getRate($product)
{
    $productTaxClassId = $product->getTaxClassId();
    $shippingAddress = $this->customerSession->getCustomer()->getDefaultShippingAddress();
    $countryCode =  (isset($shippingAddress['country_id']) && !empty($shippingAddress['country_id'])) ? $shippingAddress['country_id'] : 'GB';
    $rate = $this->taxCalculation->getRate(
        new MagentoFrameworkDataObject(
            [
                'country_id' => $countryCode,
                'customer_class_id' => $this->scopeConfig->getValue('tax/classes/default_customer_tax_class'),
                'product_class_id' => $productTaxClassId
            ]
        )
    );

    return $rate;
}


private function getProductWithExternalData($itemsCollection):MagentoFrameworkDataCollection
{
    $parsedCollection = $this->collectionFactory->create();

    if ($this->cart->getQuote()->getId()) {
        $productIds = [];
        foreach ($itemsCollection as $item) {
            $productIds[] = $item->getProductId();
        }

        $productCollection = $this->productFactory->create()->getCollection()
            ->addFieldToSelect('tax_class_id')
            ->addIdFilter($productIds);

        $productCollection->getSelect()->joinLeft(
            ['pod' => $productCollection->getSelect()->getConnection()->getTableName('pod_temp_cart')],
            'e.entity_id=pod.product_id and pod.quote_id=' . $this->cart->getQuote()->getId(),
            ['pod.image_id as pod_image_id', 'pod.price as pod_price']
        );

        $result = $productCollection->getSelect()->getConnection()->fetchAll($productCollection->getSelect());

        if (!empty($result)) {
            foreach ($result as $item) {
                $data = $this->dataObjectFactory->create();
                $data->setData($item);
                $parsedCollection->addItem($data);
            }
        }
    }

    return $parsedCollection;
   }
}

From the Above code I am getting the Correct Tax amount but once i click Place order getting the below error due to this unable to place the order.

Infinite loop detected,in exception file.

Please someone update me the working solution for this. Thanks


Get this bounty!!!

#StackBounty: #magento2 #event-observer #product-attribute #tax Apply Tax to the cart total based on product attribute value magento 2.3

Bounty: 50

I am applying custom tax for the cart item based on the product attribute value.

used below event for that.

Vendor/Module/etc/events.xml

<event name="sales_quote_address_collect_totals_after">
    <observer name="changeTax" instance="VendorModuleObserverChangeTax"/>
</event>

Then VendorModuleObserverChangeTax.php

<?php
namespace VendorModuleObserver;

use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkEventObserver;
class ChangeTax implements ObserverInterface
{
 private $logger;
 protected $_productloader;
 protected $_cart;
 public function __construct(
     PsrLogLoggerInterface $logger,
     MagentoCatalogModelProductFactory $_productloader,
     MagentoCheckoutModelCart $cart
  ) {
     $this->logger = $logger;
     $this->_productloader = $_productloader;       
     $this->_cart = $cart;      
   }
 public function execute(Observer $observer)
  {
    /** @var MagentoQuoteModelQuoteAddressTotal */
     $this->logger->info('--total--');
     $total = $observer->getData('total');
     // retrieve quote items collection     
     $itemsCollection = $this->_cart->getQuote()->getItemsCollection();
     $isDeliverable = [];
     foreach($itemsCollection as $items){
        $productId = $items->getProductId();
        $this->logger->info('--itemIds--'.$productId);
        $product = $this->_productloader->create()->load($productId);
        $deliveryProduct = $product->getIsDelivery();
        if($deliveryProduct){
            $isDeliverable[] = $productId;
         }          
       }
      if(count($isDeliverable) > 0){
        $this->logger->info('--inside--');
        $total->addBaseTotalAmount('tax', 6);
        $total->setGrandTotal((float)$total->getGrandTotal() + 6);
        $total->setBaseGrandTotal((float)$total->getBaseGrandTotal() + 6);
      }
      return $this;
   }
}

The event is firing but the Tax is not getting applied, can anyone help me on this issue please? Thank you for the support!!


Get this bounty!!!

#StackBounty: #magento2 #orders #tax How to get tax settings from order object?

Bounty: 50

In Magento 2 how we can check from order object that what is the settings for the tax either its including or excluding.
We can get the tax info generally by this function

$this->scopeConfig->getValue('tax/calculation/price_includes_tax',
                $storeScope);

but this function return the current setting for the tax, is there any method to check the setting from the order object ? So we can get the tax settings while the order created.

What if we save the settings while order creation ?


Get this bounty!!!

#StackBounty: #magento2 #tax #tax-calculation Tax price issue on the product and listing page in Magento 2

Bounty: 50

I am facing an issue with the price display on the listing page and product page.

There are three cases:

Case 1: Display Product Prices In Catalog -> Including Tax

The price display on the front-end is 34,56 €
enter image description here

Case 2: Display Product Prices In Catalog -> Excluding Tax

The price display on the front-end is 29,04 €
enter image description here

Case 3: Display Product Prices In Catalog -> Including and Excluding
Tax

The price display on the front-end is 33,99 € 28,56 €
enter image description here

I want to display 33.99€ with the including tax. I don’t know why there is displaying 34.56 instead of 33.99.
The same configuration working for Magento 1 website. In the Magento 1 site, there is showing 33.99 € on the front-end.Can you guys help me? Your help would be appreciated.

Please see my configuration in below screenshots,

enter image description here
enter image description here


Get this bounty!!!

#StackBounty: #magento2 #price #addtocart #tax How to set custom tax price during add to cart in Magento 2

Bounty: 50

I am adding product to cart using ajax call.

Here is my controller code.

use MagentoFrameworkControllerResultFactory;
use MagentoFrameworkAppActionAction;
use MagentoFrameworkAppActionContext;
class AddItems extends MagentoFrameworkAppActionAction
{

 protected $formKey;   
 protected $cart;
 protected $product;
 protected $_resource;
 protected $checkoutSession;
 protected $_taxCalculationService;
 protected $quoteRepository;

public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoFrameworkDataFormFormKey $formKey,
MagentoCheckoutModelCart $cart,
MagentoCatalogModelProductFactory $product,
MagentoFrameworkAppResourceConnection $resource,
MagentoCheckoutModelSession $checkoutSession,
MagentoTaxApiTaxCalculationInterface $taxCalculationService,
MagentoQuoteApiCartRepositoryInterface $quoteRepository,
  array $data = []
) {
   $this->formKey = $formKey;
   $this->cart = $cart;
   $this->product = $product;     
   $this->_resource = $resource;
   $this->checkoutSession = $checkoutSession;  
   $this->_taxCalculationService = $taxCalculationService; 
   $this->quoteRepository = $quoteRepository;
    parent::__construct($context);
 }

 public function execute()
{ 

 try{
   $productId = 10;
    $params = array(
        'form_key' => $this->formKey->getFormKey(),
        'product_id' => $productId, //product Id
        'qty'   =>1 //quantity of product                
    );
    $_product = $this->product->create()->load($productId);       
     $item = $this->cart->getQuote()->getItemByProduct($_product );
    if($item){          
        $quote = $this->cart->getQuote();                   
        $quote->updateItem($item->getId(), array( 'qty' => 1));
        $quote->save();
    }else{                  
        $this->cart->addProduct($_product , $params);
    }
  $customPrice = 1000;
  $grossAmt = 550;

  $productTaxClassId = $child_product->getTaxClassId();
  $customerId = $this->getCustomerId();
  $storeId = $this->_storeManager->getStore()->getId();
  $productRates = $this->_taxCalculationService->getCalculatedRate($productTaxClassId, $customerId, $storeId);

  $taxAmount = ((1 * $grossAmt * $productRates) / 100);

  $quote = $this->cart->getQuote();
  $quoteId = $quote->getId();   
  $productItem = $this->getProductQuote($_product );                
  $productItem->setCustomPrice($customPrice);
  $productItem->setOriginalCustomPrice($customPrice);
  $productItem->getProduct()->setIsSuperMode(true);   
  $this->cart->save(); 
   $productItem->setTaxAmount($taxAmount)->setBaseTaxAmount($taxAmount)->save(); 
    $quote = $this->checkoutSession->getQuote();
    $quote->collectTotals();
    //$quote->save(); 
    $this->quoteRepository->save($quote);
   }
 }

public function getProductQuote($product) {
    $quote = $this->checkoutSession->getQuote();        
    $cartItems = $quote->getItemByProduct($product);        
    return $cartItems;
}
}     

Using above code, i am able to add product to cart with custom price.

I need to add custom tax price also upon adding the product to cart. Right now tax is not getting applied.

How can i set custom tax price for the product added to cart.

Can anyone help me please, custom tax price i have got in variable, $taxAmount

This code save the data to “tax_amount” and “base_tax_amount” fields in quote_item table but when navigated to cart page, tax is showing as 0 and in table values are restored to 0.

$productItem->setTaxAmount($taxAmount)->setBaseTaxAmount($taxAmount)->save(); 
             $quote = $this->checkoutSession->getQuote();
             $quote->collectTotals();
             $this->quoteRepository->save($quote);
            // $quote->save();

Please share the ideas where i am doing wrong here. Thanks in advance


Get this bounty!!!

#StackBounty: #tax #magento-1.9.4.0 #php-7.2.14 Suddenly double tax applied CE 1.9

Bounty: 50

The last month our shop www.sinful.eu (which has 5 multiple shops), has been experiencing double tax issues. We have over the last month had this issue 3 times. The problem is solved doing the following:

  1. OP Cache flush

  2. Magento cache flush

  3. Server reboot

The double tax applies as customers add products to the basket. Nothing seems to trig this issue, as it has appeared even on days we haven’t been at work.

Our Tax calculation is setup like this:

  • Tax Calculation Method Based On: Total
  • Tax Calculation Based On: Shipping address

  • Catalog prices: including tax

  • Shipping prices: Including tax

  • Klarna invoice fee prices: Including tax

  • Apply customer tax: Before discount

  • Apply discount on prices: Including tax

  • Apply tax on: Customer price if available

  • Enable cross border trade: No

  • Default Country: Denmark

  • Default post code: *

Our Tax classes are setup correct aswell.


Get this bounty!!!

#StackBounty: #magento-1.9 #tax #taxes #tax-calculation Suddenly double tax applied CE 1.9

Bounty: 50

The last month our shop www.sinful.eu (which has 5 multiple shops), has been experiencing double tax issues. We have over the last month had this issue 3 times. The problem is solved doing the following:

  1. OP Cache flush

  2. Magento cache flush

  3. Server reboot

The double tax applies as customers add products to the basket. Nothing seems to trig this issue, as it has appeared even on days we haven’t been at work.

Our Tax calculation is setup like this:

  • Tax Calculation Method Based On: Total
  • Tax Calculation Based On: Shipping address

  • Catalog prices: including tax

  • Shipping prices: Including tax

  • Klarna invoice fee prices: Including tax

  • Apply customer tax: Before discount

  • Apply discount on prices: Including tax

  • Apply tax on: Customer price if available

  • Enable cross border trade: No

  • Default Country: Denmark

  • Default post code: *

Our Tax classes is setup correct aswell.

Bonus info: We’re running Magento 1.9.4.0 on PHP 7.2.14

Anyone got any suggestions of what we could do to get rid of this problem?

A thousand thanks in advance for the help, this is really a frustrating issue.


Get this bounty!!!