collectTotals in Magento 2

If we were to have a custom quote object which we were adding items to, we can re-calculate the totals in the cart using the following method.

$shippingAddress = $preorderQuote->getShippingAddress();
$shippingAddress->unsetData('cached_items_all');            
$quote->setTotalsCollectedFlag(false)->collectTotals();
$this->quoteRepository->save($quote);

We unset the cached item on the quote address object to force Magento to re-load the items for the address. This is necessary as Magento will sometimes not update this automatically, leading to an incorrect zero value quote and quote items.

Basket Sales Row Totals

Sales Row Totals are defined in config.xml in the nodes:

<sales>
    <quote>
        <totals>
            <shipping>
                <class>sales/quote_address_total_shipping</class>
                <after>subtotal,freeshipping,tax_subtotal</after>
                <before>grand_total</before>
            </shipping>
        </totals>
    </quote>
</sales>

The class node is instantiated by each total type, and then collect is called on each. The fetch method actually adds the total type to the address — up until this point the config.xml definition only declares the total types which should be queried for addition. Logic could exist in the fetch method to check whether the total type should be added at all. Additionally, the fetch method could add more than one type of total, as the Mage_Tax_Model_Sales_Total_Quote_Tax does.

<?php
  public function fetch(Mage_Sales_Model_Quote_Address $address)
    {
        $amount = $address->getShippingAmount();
       if ($amount != 0 || $address->getShippingDescription()) {
            $title = Mage::helper('sales')->__('Shipping & Handling');
            if ($address->getShippingDescription()) {
                $title .= ' (' . $address->getShippingDescription() . ')';
            }
            $address->addTotal(array(
                'code' => $this->getCode(),
                'title' => $title,
                'value' => $address->getShippingAmount()
            ));
        }
        return $this;
    }

These are rendered by the Mage_Checkout_Block_Cart_Totals‘ renderTotal method. A total can also have a block total renderer assigned to it instead of having to rely on the default output in the cart rows. The block is instantiated using the node names of the total config definition. The total node name is used (in the node) with _total_renderer appended to it. This is done in the Cart Totals’ _getTotalRenderer() method. In the example above, the renderer would be called *shipping_total_renderer*.

Fishpigs Total Renderer Example

Fish pigs add a cart total renderer to the cart. To achieve this, they add a shipping_total_renderer in their layout XML:

<layout>
	
	<checkout_cart_index>
		<reference name="checkout.cart.totals">
			<block type="basketshipping/total_shipping" name="shipping_total_renderer" />
		</reference>
	</checkout_cart_index>
	
</layout>

– This block will now be rendered for the shipping_total. Due to the way the fetch method works however, the row will only be added to the cart totals is not equal to zero or the address does not has a shipping description. This can be changed by overwriting the Mage_Sales_Model_Quote_Address_Total_Shipping model.

Notes on Magento’s Tax Module

Magento’s tax modules adds renderers to many of the sales/quote/total rows. This may often be overlooked when looking at the config file from Magento’s Sales module. This changes the renderers of the subtotal, shipping, discount, and grand total to renderer blocks within the tax module:

 <subtotal>
    <renderer>tax/checkout_subtotal</renderer>
    <admin_renderer>adminhtml/sales_order_create_totals_subtotal</admin_renderer>
</subtotal>
<shipping>
    <renderer>tax/checkout_shipping</renderer>
    <admin_renderer>adminhtml/sales_order_create_totals_shipping</admin_renderer>
</shipping>
<discount>
    <renderer>tax/checkout_discount</renderer>
    <admin_renderer>adminhtml/sales_order_create_totals_discount</admin_renderer>
</discount>
<grand_total>
    <renderer>tax/checkout_grandtotal</renderer>
    <admin_renderer>adminhtml/sales_order_create_totals_grandtotal</admin_renderer>
</grand_total>

Basket Row Total Areas

There are three main areas in the shipping row totals: footer, taxes, and null. Null is the default area any is output by default, other renderers require explicit output in a template, such as the taxes area. This area area is only created if tax/cart_display/grandtotal is set to Yes.

The position of taxes in Magento will render based on the tax/cart_display/grandtotal setting. If this setting is set to Yes, then the tax will not be output as part of the regular totals, and assigned to the taxes area, which by default is output as part of the grand total template (tax/checkout/grandtotal.phtml):

<?php echo $this->renderTotals('taxes', $this->getColspan()); ?>

The area is set in the fetch method of Mage_Tax_Model_Sales_Total_Quote_Tax:

$area = null;
if ($this->_config->displayCartTaxWithGrandTotal($store) && $address->getGrandTotal()) {
    $area = 'taxes';
}

if (($amount != 0) || ($this->_config->displayCartZeroTax($store))) {
    $address->addTotal(array(
        'code' => $this->getCode(),
        'title' => Mage::helper('tax')->__('Tax'),
        'full_info' => $applied ? $applied : array(),
        'value' => $amount,
        'area' => $area
    ));
}

If the tax/cart_display/grandtotal is set to “No”, then area doesn’t get assigned, and defaults to null, so the total will be output alongside all of the other totals.

Modifying the Price of a Cart Item

Magento provides a relatively easy way to modify the price of a cart item:

config.xml

<checkout_cart_product_add_after>
	<observers>
		<llapgoch_modify_add_to_cart_price>
			<model>llapgoch_pricetest/observer</model>
			<method>modifyItem</method>
			<type>model</type>
		</llapgoch_modify_add_to_cart_price>
	</observers>
</checkout_cart_product_add_after>

– The checkout_cart_product_add_after passes an instance of the product being added and the quote order item to the observer.

The Observer Method

<?php
public function modifyItem($observer){
	$item = $observer->getQuoteItem();
		
	$item = $item->getParentItem() ? $item->getParentItem() : $item; 
		
	$item->setCustomPrice(2000);
	$item->setOriginalCustomPrice(2000);
	$item->getProduct()->setIsSuperMode(true);		
}

– This will set the cart item to have a price of 2000.
– Remember to get the parent item of the cart item if we’re adding configurables to the cart.
– I’m not entirely sure what the setIsSuperMode does, it only appears in Magento’s core code once and doesn’t appear to be used anywhere else (unless I’m missing something), so it’s only here for completeness.