The Magento totals sort order hell

Yesterday I had an interesting problem in a Magento community installation of one of my clients:

After the deinstallation of the Unirgy_GiftCert extension the total values subtotal, tax and grand_total were totally messed up. That means sums without tax were shown as grand_total and subtotal whereas it was configured totally different.
After some debugging action I found out that incorrect dependencies for the total models were the cause for this issue (the sort order did change because of the uninstallation of the gift certificate extension):
Instead of calculating/collecting the tax sum before the grand total the tax totals model was moved to the end of the list which resulted in the grand total being calculated without tax.

Magento allows to configure the sort order for all totals completely flexible by either defining <before> and <after> XML tags for each quote total or by configuring sort order numbers in System > Configuration > Sales.
Unfortunately with more and more 3rd party extensions installed which add additional totals (e.g. extra payment fees, etc.) the sort order may get corrupt because one module may define tax total model before grand_total total model while another extension requires its custom points total model before tax but after grand_total. You see this might get any complex 🙂

The easiest way out of this dependency hell is to debug Mage_Sales_Model_Config_Ordered::_compareSortOrder() and see what is the result of the total model comparison.

Vinai did also write an excellent Stackoverflow answer regarding this topic and and also mentioned a way to visualize the dependencies.