In some cases it could come in handy if we could do calculations with rules on a price field instead of a line-item.
I made a custom rule for that purpose, maybe it comes in handy for anyone.
/**
* Implementation of hook_rules_action_info().
*/
function MYMODULE_rules_action_info() {
return array(
'MYMODULE_calculate_vat' => array(
'label' => t('Calculate VAT on a price field'),
'parameter' => array(
'commerce_price' => array(
'type' => 'commerce_price',
'label' => t('Price field without VAT'),
),
'vat_rate_name' => array(
'type' => 'text',
'label' => t('vat rate'),
'options list' => 'commerce_vat_rate_titles',
),
),
'provides' => array(
'applied_vat' => array(
'type' => 'commerce_price',
'label' => t('Price inclusive VAT'),
),
),
'group' => t('Commerce VAT'),
'callbacks' => array(
'execute' => 'MYMODULE_commerce_vat_rate_rules_calculate_apply',
),
),
);
}
/**
* Applies a vat rate to the base price of a price field.
*
* @param $vat_rate
* The vat rate to apply to the line item.
* @param $commerce_price
* The field whose base price will be modified to include the vat.
*
* @return
* A price array representing the vat applied to the line item or FALSE if
* none was applied.
*/
function MYMODULE_commerce_vat_rate_rules_calculate_apply($commerce_price, $vat_rate) {
if ($vat_rate = commerce_vat_rate_load($vat_rate)) {
foreach ($vat_rate['rates'] as $rate) {
if (strtotime($rate['start']) < time()) {
$rate_info = $rate;
break;
}
}
// If a valid rate is specified...
if (isset($rate_info['rate']) && is_numeric($rate_info['rate'])) {
// Don't apply vat if the unit price has a NULL amount.
if (is_null($commerce_price['amount'])) {
return;
}
//Todo: load the data for the field to pay respect to the rounded options
// If the price has been rounded up take the half off before calculating VAT
if (isset($data['rounded_up']) && $data['rounded_up']) {
$commerce_price['amount'] = $commerce_price['amount'] - 0.5;
}
$commerce_price['amount'] = $commerce_price['amount'] * $rate_info['rate'];
$commerce_price['amount'] = commerce_vat_rate_round_amount($commerce_price['amount']);
return array('applied_vat' => $commerce_price);
}
return FALSE;
}
return FALSE;
}
Comments
Comment #1
Dolcey commentedCurrently I have a problem with VAT, all my products have reduced VAT, VAT and shipping is standard, and failed to apply, use the Commerce European Union VAT module complementing.
I can implement this rule somehow I need?