Fix invoice total calculation

#623
This commit is contained in:
Artur Beljajev 2018-03-13 14:32:38 +02:00
parent ef6f482528
commit 9a4380fd96
2 changed files with 10 additions and 6 deletions

View file

@ -34,7 +34,7 @@ class Invoice < ActiveRecord::Base
before_create :set_invoice_number before_create :set_invoice_number
before_create :apply_default_vat_rate, unless: :vat_rate? 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 attribute :vat_rate, ::Type::VATRate.new
attr_readonly :vat_rate attr_readonly :vat_rate
@ -150,14 +150,18 @@ class Invoice < ActiveRecord::Base
end end
def subtotal def subtotal
(items.map(&:item_sum_without_vat).sum).round(2) invoice_items.collect { |line_item| line_item.item_sum_without_vat }.reduce(:+)
end end
def vat def vat_amount
return 0 unless vat_rate return 0 unless vat_rate
subtotal * vat_rate / 100 subtotal * vat_rate / 100
end end
def total
calculate_total unless total?
end
private private
def apply_default_vat_rate def apply_default_vat_rate
@ -165,6 +169,6 @@ class Invoice < ActiveRecord::Base
end end
def calculate_total def calculate_total
# (sum_without_vat + vat).round(2) self.total = subtotal + vat_amount
end end
end end

View file

@ -59,12 +59,12 @@ class InvoiceTest < ActiveSupport::TestCase
end end
def test_calculates_vat_amount def test_calculates_vat_amount
assert_equal BigDecimal('1.5'), @invoice.vat assert_equal BigDecimal('1.5'), @invoice.vat_amount
end end
def test_vat_amount_is_zero_when_vat_rate_is_blank def test_vat_amount_is_zero_when_vat_rate_is_blank
@invoice.vat_rate = nil @invoice.vat_rate = nil
assert_equal 0, @invoice.vat assert_equal 0, @invoice.vat_amount
end end
def test_calculates_subtotal def test_calculates_subtotal