Unravelling Magento’s collectTotals: The Core Process
Unravelling Magento’s collectTotals: The Core Process

Unravelling Magento’s collectTotals: The Core Process

Published May 1, 2013 in Development
Unravelling Magento’s collectTotals: Introduction
April 24, 2013
Unravelling Magento’s collectTotals: Orders and Caveats
May 8, 2013

Previous entries

In this series, we’re looking at Magento’s process for calculating and displaying totals for a cart. In our introduction, we briefly covered what a “total” or “total collector” is and saw how one is defined in config.xml. Now it’s time to take a closer look at the models and data structure involved. The job of a total collector model can be divided into two processes: Calculation and display.

You’re highly encouraged to open up the Magento codebase and follow along with the referenced code.

The collectTotals process

As mentioned in the previous article, the calculation of cart totals is kicked off with a call to Mage_Sales_Model_Quote::collectTotals. Before taking a look at the code, there are a few things to take note of about the underlying data structure for totals:

  • While it’s not required, many totals have database fields dedicated to them – usually “totalname_amount” and “base_totalname_amount” for the store and base currencies. (Ex., “gift_cards_amount” and “base_gift_cards_amount”)
  • Since totals calculations are done on each individual quote address, these fields are typically in sales_flat_quote_address, and there are methods for automatically adding to these amounts and incorporating them into the quote address’s total.
  • It’s not uncommon for fields of the same name to exist in sales_flat_quote_address_item and be managed directly by the total collector.
  • There are no restrictions on what values a particular total collector can modify. Example: The “subtotal” collector modifies several values, including “price” and “row_total” on quote items.
  • sales_flat_quote does contain “subtotal” and “grand_total,” which are special in that collectTotals automatically takes care of populating them after all total collectors have run.

With that out of the way, it’s time to examine the general flow of execution for collectTotals. collectTotals is run at various points, almost always immediately before the quote is saved. Examples would include during a visit to the cart page, upon the submission of each step during the checkout, and immediately before final order placement. Here’s a truncated version of collectTotals, with the main areas of code we’re concerned with:

The parts I’ve truncated deal with dispatching events, zeroing out values before the process begins, validation, and setting item quantities on the quote. Here’s an explanation of the main collection process:

  • Mage_Sales_Model_Quote::collectTotals loops through each quote address and calls Mage_Sales_Model_Quote_Address::collectTotals.
  • In collectTotals for an address, getTotalCollector()->getCollectors is used to get a sorted array of the defined total models and loop through them.
  • The “collect” method is run on each total model (all of which extend Mage_Sales_Model_Quote_Address_Total_Abstract). This method accepts the address as a parameter and does the heavy lifting of totals calculation.
    • The logic almost always involves looping through the address’s quote items via _getAddressItems. The handy methods _addAmount and _addBaseAmount can be used to add to the value of a field on the address matching the name of the total collector (like “discount_amount”), which will also add to the grand total for the address.
    • Any modification to the values on the quoted address itself is done here as well.
  • In Mage_Sales_Model_Quote::collectTotals, subtotal and grand_total are accumulated from the totals on each address.
  • With few exceptions, the quote (and by extension its addresses and items) is immediately saved after collectTotals is run.

To re-emphasize, no price information exists on the quote at all until this process has run the first time. When a product is added to the cart, it is added without price info, and the appropriate price is looked up and applied in one of the total collectors.

It may seem strange that totals are collected for both shipping and billing addresses on a quote and then summed. First of all, it’s appropriate for calculations to be done in the context of a specific address, because address information may affect things like tax and shipping. But if the two addresses’ totals are added together, how can the result be correct? The key is in _getAddressItems on the total model, which will return items only for the relevant address. (Typically the shipping address, or the billing address on a virtual quote.) Thus you end up with $0 totals on the address for which no items are returned. And for multi-shipping, quote items are explicitly associated with one address or another, which makes the general collectTotals process work out nicely.

Displaying totals

The process for calculating totals on a quote may still seem a bit opaque, but if you spend some time examining the various total models defined in the core, the general functionality should begin to click. There’s one other key component to a total model, however: Displaying totals in the cart or checkout (or wherever). It’s not required for a total to be displayed, but totals like “subtotal,” “discount,” “tax” and “grand_total” should be itemized on the page.

You’ve seen that collectTotals on the quote model and “collect” on a total model are the key methods involved with calculating and saving info. For displaying, getTotals on the quote model and “fetch” on the total model comprise the main event. Here’s the basic process:

  • Mage_Checkout_Block_Cart_Totals is the block included in the layout. The corresponding template outputs the results of renderTotals on this block.
  • Mage_Checkout_Block_Cart_Totals::renderTotals loops through the results of the block’s own getTotals method, which in turn calls Mage_Sales_Model_Quote::getTotals.
  • As comes as no surprise at this point, a getTotals method is called on each quote address. And parallel with the process we saw with collection, getTotalCollector()->getRetrievers is used to get the sorted total models. (This is distinct from getCollectors. In this case, admin configuration can actually be used to dictate the order in which totals are displayed.)
  • The “fetch” method is called on each total model, once again with the address passed as a parameter.
    • Ultimately, this method calls addTotal on the quote address, passing an array with the total’s code, a display title, and the value to display.
    • What is ultimately stored on the quote address is an instance of Mage_Sales_Model_Quote_Address_Total, which is a Varien_Object with an added “merge” method to facilitate summing the values of two such objects.
  • As Mage_Sales_Model_Quote::getTotals loops through each address, it uses the “merge” method mentioned above to reconcile each address’s data for a particular total into one final set of information to display.
  • Finally, Mage_Checkout_Block_Cart_Totals::renderTotals calls renderTotal for each total, which instantiates the appropriate block (more on this in a moment) and returns the results of toHtml.

Exactly which block class is used to render a specific total is determined as follows:

  • A block can be defined directly in layout XML for any total. It should simply have the name “{totalcode}_total_renderer,” and this block will be used to render the corresponding total.
  • If no renderer is defined in layout, the next place checked is the global config XML. We’ve already seen where totals are defined (in the node path “global/sales/quote/totals”). The node for a specific total can define <renderer> in addition to <class>, <before> and <after>. The expected value is a block code. An example can be found in config.xml for Mage_Checkout, where the renderer “checkout/total_nominal” is specified for the “nominal” total.
  • If neither of the above defined a renderer, the default Mage_Checkout_Block_Total_Default is used.

And there you have it! The collection and display processes are as simple as that. All right, so “simple” may not be the word to describe them. But with the outlines above, you should be well equipped to examine the code of the various models that are involved and get a feel for the flow of execution.

A quick example

All of the native total collectors have their own quirks, complexities, and “exceptions” to the rules, so finding a straight-forward example is a challenge. To simplify as much as possible, I’ll present the following pseudo example of how the two key methods on a total work. Most totals follow the same basic process in some fashion.

In the next part, we’ll discuss some final points that are worth consideration before Magento totals can be considered well and truly conquered.

Next entries

5 Comments

  1. Trey Trimble says:

    How does $address->getMytotalAmount(); get the value set by $item->setMytotalAmount($amt);

    Wouldn’t you need to get the value from the item or set the value on the adress object, such as $address->getMyTotalAmount();

    • Vinai Kopp says:

      Hi,

      first, thank you for this excellent series! It is well written and covers a complex subject nicely, breaking it into manageable bites.
      One small note though (can’t help but being a smartass – sorry). It is not required to set the total code within the total model in the __construct() method of the example. The total code is set on the model after instantiation by Mage_Sales_Model_Quote_Address_Total_Collector::_initModelInstance().
      Setting the code in the constructor won’t do any harm, it will simply be overwritten again. This might be confusing though if there is a discrepancy between the code specified in the XML and the one specified in the constructor.

      Thanks again for the contributions!

    • Chris Nanninga says:

      If memory serves, $this->_addAmount in the “fetch” method takes care of setting the total on the address.

  2. Jason North says:

    Great set of articles!
    I have a problem, if you wouldn’t mind helping.

    I have a shopping cart rule set up for a certain product to get discounted 100%. In the Discount subtotal, it DOUBLES the discount, but in the Grand Total, it calculates the discount correctly.

    Any idea why? I can’t seem to find why the discount might be doubling on the front-end. So weird.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Most Recent PostsView all
December 13, 2019

The Instagram Effect: How the Rise of Visual UGC is Transforming eCommerce

As anyone who’s ever gone on a first date will tell you, first impressions matter. A brand’s website is no exception to this universal truth. Visitors […]
December 12, 2019

Reducing CPC and Increasing Clicks with Google Smart Shopping

November 22, 2019

Partner Round-Up: Holiday Prep for eCommerce

When it comes to preparing your eCommerce site for the holiday season, there’s no shortage of advice available. Black Friday, Cyber Monday, Christmas sales, and the […]