diff --git a/app/models/invoice.rb b/app/models/invoice.rb index 19e25d5c9..a5c3f3f85 100644 --- a/app/models/invoice.rb +++ b/app/models/invoice.rb @@ -34,7 +34,7 @@ class Invoice < ActiveRecord::Base before_create :set_invoice_number before_create :apply_default_vat_rate, unless: :vat_rate? - before_create :save_total + before_create :calculate_total, unless: :total? attribute :vat_rate, ::Type::VATRate.new attr_readonly :vat_rate @@ -150,14 +150,18 @@ class Invoice < ActiveRecord::Base end def subtotal - (items.map(&:item_sum_without_vat).sum).round(2) + invoice_items.collect { |line_item| line_item.item_sum_without_vat }.reduce(:+) end - def vat + def vat_amount return 0 unless vat_rate subtotal * vat_rate / 100 end + def total + calculate_total unless total? + end + private def apply_default_vat_rate @@ -165,6 +169,6 @@ class Invoice < ActiveRecord::Base end def calculate_total - # (sum_without_vat + vat).round(2) + self.total = subtotal + vat_amount end end diff --git a/test/models/invoice_test.rb b/test/models/invoice_test.rb index fb7e66821..9222f83b8 100644 --- a/test/models/invoice_test.rb +++ b/test/models/invoice_test.rb @@ -59,12 +59,12 @@ class InvoiceTest < ActiveSupport::TestCase end def test_calculates_vat_amount - assert_equal BigDecimal('1.5'), @invoice.vat + assert_equal BigDecimal('1.5'), @invoice.vat_amount end def test_vat_amount_is_zero_when_vat_rate_is_blank @invoice.vat_rate = nil - assert_equal 0, @invoice.vat + assert_equal 0, @invoice.vat_amount end def test_calculates_subtotal