From 33034e66b88968dedc5289425e1eff847ee67e12 Mon Sep 17 00:00:00 2001 From: Philipp Rothmann Date: Thu, 22 Jun 2023 22:45:21 +0200 Subject: [PATCH] fix: add null checks for articles convert_units 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 --- app/models/article.rb | 2 +- spec/models/article_spec.rb | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/app/models/article.rb b/app/models/article.rb index 53cc2708..561deaf8 100644 --- a/app/models/article.rb +++ b/app/models/article.rb @@ -211,7 +211,7 @@ class Article < ApplicationRecord 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 diff --git a/spec/models/article_spec.rb b/spec/models/article_spec.rb index 9b58abeb..3a810827 100644 --- a/spec/models/article_spec.rb +++ b/spec/models/article_spec.rb @@ -25,6 +25,18 @@ describe Article do 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')