Zend certified PHP/Magento developer

Custom Totals Collector Not Calculating Correctly On Checkout

I have created a customer totals collector with files defined as below:

etc/sales.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Sales:etc/sales.xsd">
    <section name="quote">
        <group name="totals">
            <item name="tax_subtotal" instance="VendorModuleModelSalesTotalQuoteTax" sort_order="449"/>
        </group>
    </section>
</config>

VendorModuleModelSalesTotalQuoteTax

<?php

namespace VendorModuleModelSalesTotalQuote;

use MagentoCustomerApiDataAddressInterfaceFactory as CustomerAddressFactory;
use MagentoCustomerApiDataRegionInterfaceFactory as CustomerAddressRegionFactory;
use MagentoTaxHelperData as TaxHelper;
use MagentoTaxApiDataQuoteDetailsInterfaceFactory;
use MagentoTaxApiDataQuoteDetailsItemInterfaceFactory;
use MagentoTaxModelSalesTotalQuoteTax as MagentoTax;
use MagentoTaxModelConfig;
use MagentoTaxApiTaxCalculationInterface;
use MagentoTaxApiDataTaxClassKeyInterfaceFactory;
use MagentoFrameworkSerializeSerializerJson;

class Tax extends MagentoTax
{
    public function collect(
        MagentoQuoteModelQuote $quote,
        MagentoQuoteApiDataShippingAssignmentInterface $shippingAssignment,
        MagentoQuoteModelQuoteAddressTotal $total
    ) {
        $address = $shippingAssignment->getShipping()->getAddress();
        $items = $this->_getAddressItems($address);

        if (!count($items)) {
            return $this;
        }

        $subtotal += $quoteItem->getBaseRowTotalInclTax();
        $tax += $quoteItem->getBaseTaxAmount();  
        
        $total->setTotalAmount('subtotal', $subtotal);
        $total->setBaseTotalAmount('subtotal', $subtotal);
        $total->setSubtotalInclTax($subtotal);
        $total->setBaseSubtotalInclTax($subtotal);
        $total->setTotalAmount('tax', $tax);
        $total->setBaseTotalAmount('tax', $tax);
        $total->setGrandTotal($subtotal);

        return $this;
    }
}

Lets say for example I have a single product in the cart which costs £15.99(Inc Tax)
Shipping cost is £2.95 and tax is £2.67

In the checkout (with Full Tax summary enabled in admin) I get the following total, which is clearly wrong 😀

enter image description here

So by the looks of the grand total, it’s being calculated using priceExclTax + priceInclTax + shipping + tax amount

I have no clue how to get this working correctly and have tried different sort order values in sales.xml, the only other result I get is, the shipping is not calculated so the grand total is the same as the sub total – which again is wrong 🙂