Skip to content

Commit

Permalink
fix: add null checks for articles convert_units
Browse files Browse the repository at this point in the history
Prevents division by zero exception because of a unit beeing 0.
A Unit becomes also zero e.g. when a comma symbol is used Unit.new("0,9kg") == 0

fixes #1014
  • Loading branch information
yksflip committed Jun 22, 2023
1 parent 45e2668 commit 33034e6
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
2 changes: 1 addition & 1 deletion app/models/article.rb
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ def convert_units(new_article = shared_article)
rescue StandardError
nil
end
if fc_unit && supplier_unit && fc_unit =~ supplier_unit
if fc_unit != 0 && supplier_unit != 0 && fc_unit && supplier_unit && fc_unit =~ supplier_unit
conversion_factor = (supplier_unit / fc_unit).to_base.to_r
new_price = new_article.price / conversion_factor
new_unit_quantity = new_article.unit_quantity * conversion_factor
Expand Down
12 changes: 12 additions & 0 deletions spec/models/article_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,18 @@
expect(article.convert_units(article1)).to be false
end

it 'returns false if unit = 0' do
article1 = build(:article, supplier: supplier, unit: '1kg', price: 2, unit_quantity: 1)
article2 = build(:article, supplier: supplier, unit: '0kg', price: 2, unit_quantity: 1)
expect(article1.convert_units(article2)).to be false
end

it 'returns false if unit becomes zero because of , symbol in unit format' do
article1 = build(:article, supplier: supplier, unit: '0,8kg', price: 2, unit_quantity: 1)
article2 = build(:article, supplier: supplier, unit: '0,9kg', price: 2, unit_quantity: 1)
expect(article1.convert_units(article2)).to be false
end

it 'converts from ST to KI (german foodcoops legacy)' do
article1 = build(:article, supplier: supplier, unit: 'ST')
article2 = build(:article, supplier: supplier, name: 'banana 10-12 St', price: 12.34, unit: 'KI')
Expand Down

0 comments on commit 33034e6

Please sign in to comment.