Skip to content

Commit

Permalink
Conversion fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
lentschi committed May 13, 2022
1 parent b7f32d7 commit 1708d23
Show file tree
Hide file tree
Showing 10 changed files with 60 additions and 26 deletions.
1 change: 1 addition & 0 deletions app/assets/javascripts/article-form.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ class ArticleForm {
this.filterAvailableRatioUnits();
this.setMinimumOrderUnitDisplay();
this.updateAvailableBillingAndGroupOrderUnits();
this.updateUnitMultiplierLabels();
}

setMinimumOrderUnitDisplay() {
Expand Down
14 changes: 10 additions & 4 deletions app/assets/javascripts/group-order-form.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,9 @@ class GroupOrderForm {

const missing$ = row$.find('.missing-units');

const quantity = parseFloat(quantity$.val());
const quantity = parseFloat(quantity$.val().trim().replace(',', '.'));
const granularity = parseFloat(quantity$.attr('step'));
const tolerance = parseFloat(tolerance$.val());
const tolerance = tolerance$.length === 1 ? parseFloat(tolerance$.val().trim().replace(',', '.')) : 0;
const packSize = quantity$.data('ratio-group-order-unit-supplier-unit');
const othersQuantity = quantity$.data('others-quantity');
const othersTolerance = quantity$.data('others-tolerance');
Expand Down Expand Up @@ -153,7 +153,7 @@ class GroupOrderForm {
const missing = this.calcMissingItems(packSize, totalQuantity, totalTolerance)

used$.text(isNaN(used) ? '?' : used);
unused$.text(isNaN(unused) ? '?' : unused);
unused$.text(isNaN(unused) ? '?' : round(unused, 2));

usedTolerance$.text(isNaN(usedTolerance) ? '?' : usedTolerance);
unusedTolerance$.text(isNaN(unusedTolerance) ? '?' : unusedTolerance);
Expand All @@ -167,7 +167,7 @@ class GroupOrderForm {
totalPrice$.text(I18n.l('currency', totalPrice));
totalPrice$.data('price', totalPrice);

missing$.text(missing);
missing$.text(round(missing, 2));
if (packSize > 1) {
this.setRowStyle(row$, missing, granularity);
}
Expand Down Expand Up @@ -201,3 +201,9 @@ class GroupOrderForm {
return (remainder > 0 && (remainder + tolerance >= packSize));
}
}


function round(num, precision) {
const factor = precision * Math.pow(10, precision);
return Math.round((num + Number.EPSILON) * factor) / factor;
}
38 changes: 32 additions & 6 deletions app/assets/javascripts/unit-conversion-field.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,27 @@
class UnitConversionField {
constructor(field$, units, popoverTemplate$) {
constructor(field$, units, popoverTemplate$, useTargetUnitForStep = true) {
this.field$ = field$;
// TODO: not very clean and not jquery-esque:
this.field$[0].unitConversionField = this;
this.popoverTemplate = popoverTemplate$[0].content.querySelector('.popover_contents');
this.units = units;
this.useTargetUnitForStep = useTargetUnitForStep;

this.loadArticleUnitRatios();

// if every ratio is the same, don't even bother showing the popover:
if (this.ratios.every(ratio => ratio.quantity === 1)) {
return;
}

this.initializeFocusListener();
}

loadArticleUnitRatios() {
this.ratios = [];
for (let i = 0; this.field$.data(`ratio-quantity-${i}`) !== undefined; i++) {
this.ratios.push({
quantity: this.field$.data(`ratio-quantity-${i}`),
quantity: parseFloat(this.field$.data(`ratio-quantity-${i}`)),
unit: this.field$.data(`ratio-unit-${i}`),
});
}
Expand Down Expand Up @@ -154,19 +161,38 @@ class UnitConversionField {
}

applyConversion() {
this.field$.val(this.getConversionResult());
this.field$
.val(this.getConversionResult())
.trigger('change');
}

getQuantityInputValue() {
const val = parseFloat(this.quantityInput$.val().trim().replace(',', '.'));
if (isNaN(val)) {
return 0;
}

return val;
}

getTargetUnit() {
return this.defaultUnit === undefined ? this.supplierOrderUnit : this.defaultUnit;
}

getConversionResult() {
const result = this.getUnitRatio(this.quantityInput$.val(), this.unitSelect$.val(), this.defaultUnit === undefined ? this.supplierOrderUnit : this.defaultUnit);
const result = this.getUnitRatio(this.getQuantityInputValue(), convertEmptyStringToUndefined(this.unitSelect$.val()), this.getTargetUnit());
return Math.round(result * 10000) / 10000;
}

onUnitSelectChanged() {
const newValue = this.getUnitRatio(this.quantityInput$.val(), this.previousUnitSelectValue, convertEmptyStringToUndefined(this.unitSelect$.val()));
const newValue = this.getUnitRatio(this.getQuantityInputValue(), this.previousUnitSelectValue, convertEmptyStringToUndefined(this.unitSelect$.val()));
this.quantityInput$.val(newValue);

this.previousUnitSelectValue = convertEmptyStringToUndefined(this.unitSelect$.val());
const selectedUnit = convertEmptyStringToUndefined(this.unitSelect$.val());
this.previousUnitSelectValue = selectedUnit;

const step = this.useTargetUnitForStep ? this.getUnitRatio(1, this.getTargetUnit(), selectedUnit) : 0.001;
this.quantityInput$.attr('step', step);
}
}

Expand Down
5 changes: 3 additions & 2 deletions app/helpers/orders_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,10 @@ def units_history_line(order_article, options = {})
# Sensible in tables with multiple columns.
# @return [String] Text showing unit and unit quantity when applicable.
def pkg_helper(article, options = {})
return '' if !article || article.unit_quantity == 1
first_ratio = article&.article_unit_ratios&.first
return '' if first_ratio.nil? || first_ratio.quantity == 1

uq_text = #{article.unit_quantity}"
uq_text = #{first_ratio.quantity} #{ArticleUnits.as_options.invert[first_ratio.unit]}"
uq_text = content_tag(:span, uq_text, class: 'hidden-phone') if options[:soft_uq]
if options[:plain]
uq_text
Expand Down
6 changes: 3 additions & 3 deletions app/models/concerns/price_calculation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ module PriceCalculation
extend ActiveSupport::Concern

def unit_quantity
first_ration = article_unit_ratios.first
if first_ration.nil?
first_ratio = article_unit_ratios.first
if first_ratio.nil?
1
else
first_ration.quantity
first_ratio.quantity
end
end

Expand Down
2 changes: 1 addition & 1 deletion app/models/order.rb
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ def sum(type = :gross)
total = 0
if type == :net || type == :gross || type == :fc
for oa in order_articles.ordered.includes(:article, :article_price)
quantity = oa.units * oa.price.unit_quantity
quantity = oa.units * oa.price.convert_quantity(1, oa.price.supplier_order_unit, oa.price.group_order_unit)
case type
when :net
total += quantity * oa.price.price
Expand Down
13 changes: 7 additions & 6 deletions app/models/order_article.rb
Original file line number Diff line number Diff line change
Expand Up @@ -81,29 +81,30 @@ def update_results!
# 4 | 5 | 4 | 2
#
def calculate_units_to_order(quantity, tolerance = 0)
unit_size = price.unit_quantity
unit_size = price.convert_quantity(1, price.supplier_order_unit, price.group_order_unit)
units = quantity / unit_size
remainder = quantity % unit_size
units += ((remainder > 0) && (remainder + tolerance >= unit_size) ? 1 : 0)
end

# Calculate price for ordered quantity.
def total_price
units * price.unit_quantity * price.price
units * price.convert_quantity(1, price.supplier_order_unit, price.group_order_unit) * price.price
end

# Calculate gross price for ordered qunatity.
def total_gross_price
units * price.unit_quantity * price.gross_price
units * price.convert_quantity(1, price.supplier_order_unit, price.group_order_unit) * price.gross_price
end

def ordered_quantities_different_from_group_orders?(ordered_mark = "!", billed_mark = "?", received_mark = "?")
converted_quantity = price.convert_quantity(1, price.supplier_order_unit, price.group_order_unit)
if not units_received.nil?
((units_received * price.unit_quantity) == group_orders_sum[:quantity]) ? false : received_mark
((units_received * converted_quantity) == group_orders_sum[:quantity]) ? false : received_mark
elsif not units_billed.nil?
((units_billed * price.unit_quantity) == group_orders_sum[:quantity]) ? false : billed_mark
((units_billed * converted_quantity) == group_orders_sum[:quantity]) ? false : billed_mark
elsif not units_to_order.nil?
((units_to_order * price.unit_quantity) == group_orders_sum[:quantity]) ? false : ordered_mark
((units_to_order * converted_quantity) == group_orders_sum[:quantity]) ? false : ordered_mark
else
nil # can happen in integration tests
end
Expand Down
2 changes: 1 addition & 1 deletion app/views/group_orders/_form.html.haml
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@
%i.icon-plus

%td.tolerance.group-order-input{style: ('display:none' if @order.stockit?)}
- if (@ordering_data[:order_articles][order_article.id][:unit] > 1)
- if (@ordering_data[:order_articles][order_article.id][:ratio_group_order_unit_supplier_unit] != 1)
%span.used= @ordering_data[:order_articles][order_article.id][:used_tolerance]
+
%span.unused= @ordering_data[:order_articles][order_article.id][:tolerance] - @ordering_data[:order_articles][order_article.id][:used_tolerance]
Expand Down
3 changes: 1 addition & 2 deletions app/views/orders/_edit_amount.html.haml
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
-# NOTE: if you modify tiny details here you must also change them in `receive_on_order_article_update.js.erb`
- content_for :javascript do
:javascript
const units = #{raw(ArticleUnits.units.to_json)};
$('.units_received').each((_, field) => new UnitConversionField($(field), units, $('#unit_conversion_popover_content_template')));
$('.units_received').each((_, field) => new UnitConversionField($(field), #{raw(ArticleUnits.units.to_json)}, $('#unit_conversion_popover_content_template'), false));
= render 'shared/js_templates/unit_conversion_popover_template'
= fields_for 'order_articles', order_article, index: order_article.id do |form|
- cssclass = "order-article #{cycle('even', 'odd', name: 'articles')}"
Expand Down
2 changes: 1 addition & 1 deletion app/views/shared/articles_by/_article_single.html.haml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
%h4.name.pull-left
= order_article.article.name
%small
= "(#{order_article.article.unit}, #{number_to_currency order_article.price.fc_price}"
= "(#{format_group_order_unit(order_article.article)}, #{number_to_currency order_article.price.fc_price}"
- pkg_info = pkg_helper(order_article.price)
= ", #{pkg_info}".html_safe unless pkg_info.blank?
)
Expand Down

0 comments on commit 1708d23

Please sign in to comment.