From 77666704b3e96f487de3b684234fdebadf7e8cf9 Mon Sep 17 00:00:00 2001
From: Axel Rutz <axel.rutz@clever-systems.net>
Date: Thu, 29 May 2014 12:14:01 +0200
Subject: [PATCH] Issue #2276233 by axel.rutz: Fixed Reverse calculation
 messes up price components on discount.

---
 commerce_vat.module |   18 ++++++++++++++----
 1 file changed, 14 insertions(+), 4 deletions(-)

diff --git a/commerce_vat.module b/commerce_vat.module
index 85191df..07d6845 100644
--- a/commerce_vat.module
+++ b/commerce_vat.module
@@ -330,10 +330,20 @@ function commerce_vat_rate_apply($vat_rate, $line_item) {
      $direction = variable_get('commerce_vat_direction', 'forward');
 
      if ($direction == 'reverse') {
-      $data = $wrapper->commerce_unit_price->data->value();
-      $data['components'][0]['price']['amount'] = $data['components'][0]['price']['amount'] - $vat_price['amount'];
-      $wrapper->commerce_unit_price->data = $data;
-      $included = TRUE;
+       $data = $wrapper->commerce_unit_price->data->value();
+       $amount = $wrapper->commerce_unit_price->amount->value();
+       // Reduce components proportionally.
+       $amount_to_reduce_total = $vat_price['amount'];
+       $amount_to_reduce_left = $vat_price['amount'];
+       foreach ($data['components'] as &$component) {
+         $amount_to_reduce_current = commerce_vat_rate_round_amount($component['price']['amount'] / $amount * $amount_to_reduce_total);
+         $component['price']['amount'] -= $amount_to_reduce_current;
+         $amount_to_reduce_left -= $amount_to_reduce_current;
+       }
+       // Remaining rounding difference deliberately reduces first component.
+       $data['components'][0]['price']['amount'] = $data['components'][0]['price']['amount'] - $amount_to_reduce_left;
+       $wrapper->commerce_unit_price->data = $data;
+       $included = TRUE;
      }
      else {
        // Include the vat amount in the displayed unit price.
-- 
1.7.9.5

