UK Tax / VAT Setup Script

Posted . Visible to the public.

This script sets up everything for UK VAT from a default 1.9.1.0 install.

<?php
/* @var $installer Mage_Core_Model_Resource_Setup */
$installer = $this;
$installer->startSetup();

/**
 * Define VAT band names
 */
define('VAT_STANDARD', 'VAT Standard');
define('VAT_REDUCED', 'VAT Reduced');
define('VAT_ZERO', 'VAT Zero');

/**
 * Remove current rules, rates and product classes
 */
$taxCalculation = Mage::getModel('tax/calculation');
foreach (Mage::getModel('tax/calculation_rule')->getCollection() as $rule) {
    $taxCalculation->deleteByRuleId($rule->getId());
    $rule->delete();
}
foreach (Mage::getModel('tax/class')->getCollection() as $class) {
    if ($class->getClassType() == Mage_Tax_Model_Class::TAX_CLASS_TYPE_PRODUCT) {
        $class->delete();
    }
}
foreach (Mage::getModel('tax/calculation_rate')->getcollection() as $rate) {
    $rate->delete();
}

/**
 * Add new product classes, rates and rules
 */
$taxRates = [
    VAT_STANDARD => 20,
    VAT_REDUCED  => 5,
    VAT_ZERO     => 0,
];
foreach ($taxRates as $name => $rate) {
    $id = Mage::getModel('tax/class')
        ->setClassType(Mage_Tax_Model_Class::TAX_CLASS_TYPE_PRODUCT)
        ->setClassName($name)
        ->save()
        ->getId();
    $productClassIds[$name] = $id;
}
foreach ($taxRates as $name => $rate) {
    $id = Mage::getModel('tax/calculation_rate')
        ->setCode($name)
        ->setTaxCountryId('GB')
        ->setTaxRegionId(0)
        ->setTaxPostcode('*')
        ->setRate($rate)
        ->save()
        ->getId();
    $rateIds[$name] = $id;
}
$customerClassId = Mage::getModel('tax/class')->load('Retail Customer', 'class_name')->getId();
foreach ($taxRates as $name => $rate) {
    Mage::getModel('tax/calculation_rule')
        ->setCode($name)
        ->setTaxCustomerClass(array($customerClassId))
        ->setTaxProductClass(array($productClassIds[$name]))
        ->setTaxRate(array($rateIds[$name]))
        ->save();
}

/**
 * Set tax config
 */
$tuples = [
    ['tax/classes/shipping_tax_class', $productClassIds[VAT_STANDARD]],
    ['tax/calculation/price_includes_tax', 1],
    ['tax/calculation/shipping_includes_tax', 1],
    ['tax/calculation/discount_tax', 1],
    ['tax/defaults/country', 'GB'],
    ['tax/defaults/region', '0'],
    ['tax/defaults/postcode', '*'],
    ['tax/display/type', 2],
    ['tax/display/shipping', 2],
    ['tax/cart_display/price', 2],
    ['tax/cart_display/subtotal', 2],
    ['tax/cart_display/shipping', 2],
    ['tax/cart_display/grandtotal', 1],
    ['tax/sales_display/price', 2],
    ['tax/sales_display/subtotal', 2],
    ['tax/sales_display/shipping', 2],
    ['tax/sales_display/grandtotal', 1],
];
foreach ($tuples as list($path, $val)) {
    $installer->setConfigData($path, $val);
}

$installer->endSetup();
Mike Whitby
Last edit
Mike Whitby
Posted by Mike Whitby to Magento (2015-06-25 14:13)