Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Added unit conversion for lengths and weights
Damian Legawiec9ac4306bd493
diff --git a/spree/core/lib/spree/measurement.rb b/spree/core/lib/spree/measurement.rbnew file mode 100644index 0000000000..367efc4a70--- /dev/null+++ b/spree/core/lib/spree/measurement.rb@@ -0,0 +1,113 @@+module Spree+ # Unit conversion for the physical measurements Spree stores: dimensions in+ # millimeters, centimeters, inches or feet, and weights in grams, kilograms,+ # pounds or ounces.+ #+ # Spree keeps measurements in whatever unit the merchant typed, next to the+ # unit itself, so any calculation combining two records has to normalize+ # first. Volume is where this stops being cosmetic — a carton measured in+ # inches has roughly sixteen times the cubic value of the same numbers read+ # as centimeters, so cubic meters derived from raw dimension columns are+ # wrong for most of the world.+ #+ # Stateless module functions over two unit tables, deliberately not a value+ # object: callers already hold a number and a unit string.+ module Measurement+ # Centimeters per unit of length.+ LENGTH_IN_CENTIMETERS = {+ 'mm' => BigDecimal('0.1'),+ 'cm' => BigDecimal('1'),+ 'in' => BigDecimal('2.54'),+ 'ft' => BigDecimal('30.48')+ }.freeze++ # Kilograms per unit of weight.+ WEIGHT_IN_KILOGRAMS = {+ 'g' => BigDecimal('0.001'),+ 'kg' => BigDecimal('1'),+ 'lb' => BigDecimal('0.45359237'),+ 'oz' => BigDecimal('0.028349523125')+ }.freeze++ CENTIMETERS_PER_METER = BigDecimal('100')++ DEFAULT_LENGTH_UNIT = 'cm'.freeze+ DEFAULT_WEIGHT_UNIT = 'kg'.freeze++ class << self+ # Converts a length to centimeters.+ #+ # @param value [Numeric, String, nil]+ # @param unit [String, nil] one of {LENGTH_IN_CENTIMETERS}'s keys; an+ # unknown or blank unit is read as centimeters+ # @return [BigDecimal, nil] nil when the value is missing+ def to_centimeters(value, unit: DEFAULT_LENGTH_UNIT)+ convert(value, LENGTH_IN_CENTIMETERS, unit, DEFAULT_LENGTH_UNIT)+ end++ # Converts a weight to kilograms.+ #+ # @param value [Numeric, String, nil]+ # @param unit [String, nil] one of {WEIGHT_IN_KILOGRAMS}'s keys; an+ # unknown or blank unit is read as kilograms+ # @return [BigDecimal, nil] nil when the value is missing+ def to_kilograms(value, unit: DEFAULT_WEIGHT_UNIT)+ convert(value, WEIGHT_IN_KILOGRAMS, unit, DEFAULT_WEIGHT_UNIT)+ end++ # Converts a length between any two supported units.+ #+ # @param value [Numeric, String, nil]+ # @param from [String, nil]+ # @param to [String, nil]+ # @return [BigDecimal, nil] nil when the value is missing+ def convert_length(value, from:, to:)+ rescale(to_centimeters(value, unit: from), LENGTH_IN_CENTIMETERS, to, DEFAULT_LENGTH_UNIT)+ end++ # Converts a weight between any two supported units.+ #+ # @param value [Numeric, String, nil]+ # @param from [String, nil]+ # @param to [String, nil]+ # @return [BigDecimal, nil] nil when the value is missing+ def convert_weight(value, from:, to:)+ rescale(to_kilograms(value, unit: from), WEIGHT_IN_KILOGRAMS, to, DEFAULT_WEIGHT_UNIT)+ end++ # The cubic meters a box of these dimensions occupies — the CBM figure+ # freight is quoted and tiered on.+ #+ # @param length [Numeric, nil]+ # @param width [Numeric, nil]+ # @param height [Numeric, nil]+ # @param unit [String, nil] the unit all three are expressed in+ # @return [BigDecimal, nil] nil unless all three dimensions are present+ # and positive — a box with a missing or zero side has no volume worth+ # reporting, and returning zero would read as "measured, and empty"+ def cubic_meters(length, width, height, unit: DEFAULT_LENGTH_UNIT)+ sides = [length, width, height].map { |side| to_centimeters(side, unit: unit) }+ return if sides.any? { |side| side.nil? || side <= 0 }++ sides.inject(:*) / (CENTIMETERS_PER_METER**3)+ end++ private++ # Turns a normalized figure (centimeters, kilograms) back into the+ # target unit.+ def rescale(normalized, table, unit, default_unit)+ return if normalized.nil?++ normalized / (table[unit.to_s.downcase.presence || default_unit] || table[default_unit])+ end++ def convert(value, table, unit, default_unit)+ return if value.nil? || (value.is_a?(String) && value.blank?)++ factor = table[unit.to_s.downcase.presence || default_unit] || table[default_unit]+ value.to_d * factor+ end+ end+ end+enddiff --git a/spree/core/spec/lib/spree/measurement_spec.rb b/spree/core/spec/lib/spree/measurement_spec.rbnew file mode 100644index 0000000000..5fbbb521cb--- /dev/null+++ b/spree/core/spec/lib/spree/measurement_spec.rb@@ -0,0 +1,98 @@+require 'spec_helper'++RSpec.describe Spree::Measurement do+ describe '.to_centimeters' do+ it 'converts every supported length unit' do+ expect(described_class.to_centimeters(1, unit: 'cm')).to eq(BigDecimal('1'))+ expect(described_class.to_centimeters(10, unit: 'mm')).to eq(BigDecimal('1'))+ expect(described_class.to_centimeters(1, unit: 'in')).to eq(BigDecimal('2.54'))+ expect(described_class.to_centimeters(1, unit: 'ft')).to eq(BigDecimal('30.48'))+ end++ it 'reads a blank or unrecognized unit as centimeters' do+ expect(described_class.to_centimeters(5, unit: nil)).to eq(BigDecimal('5'))+ expect(described_class.to_centimeters(5, unit: 'furlongs')).to eq(BigDecimal('5'))+ end++ it 'is case insensitive' do+ expect(described_class.to_centimeters(1, unit: 'IN')).to eq(BigDecimal('2.54'))+ end++ it 'answers nil for a missing value rather than zero' do+ expect(described_class.to_centimeters(nil, unit: 'cm')).to be_nil+ expect(described_class.to_centimeters('', unit: 'cm')).to be_nil+ end+ end++ describe '.to_kilograms' do+ it 'converts every supported weight unit' do+ expect(described_class.to_kilograms(1, unit: 'kg')).to eq(BigDecimal('1'))+ expect(described_class.to_kilograms(1000, unit: 'g')).to eq(BigDecimal('1'))+ expect(described_class.to_kilograms(1, unit: 'lb')).to eq(BigDecimal('0.45359237'))+ expect(described_class.to_kilograms(16, unit: 'oz')).to eq(BigDecimal('0.45359237'))+ end++ it 'answers nil for a missing value' do+ expect(described_class.to_kilograms(nil)).to be_nil+ end+ end++ describe '.convert_length' do+ it 'converts between any two supported units' do+ expect(described_class.convert_length(2.54, from: 'cm', to: 'in')).to eq(BigDecimal('1'))+ expect(described_class.convert_length(1, from: 'ft', to: 'in')).to eq(BigDecimal('12'))+ expect(described_class.convert_length(1, from: 'cm', to: 'mm')).to eq(BigDecimal('10'))+ end++ it 'is the identity when the units match' do+ expect(described_class.convert_length(7, from: 'in', to: 'in')).to eq(BigDecimal('7'))+ end++ it 'answers nil for a missing value' do+ expect(described_class.convert_length(nil, from: 'cm', to: 'in')).to be_nil+ end+ end++ describe '.convert_weight' do+ it 'converts between any two supported units' do+ expect(described_class.convert_weight(1, from: 'kg', to: 'g')).to eq(BigDecimal('1000'))+ expect(described_class.convert_weight(1, from: 'lb', to: 'oz')).to eq(BigDecimal('16'))+ end++ it 'is the identity when the units match' do+ expect(described_class.convert_weight(3, from: 'lb', to: 'lb')).to eq(BigDecimal('3'))+ end+ end++ describe '.cubic_meters' do+ it 'converts a metric box' do+ expect(described_class.cubic_meters(100, 100, 100, unit: 'cm')).to eq(BigDecimal('1'))+ end++ # The whole reason the helper exists: the same three numbers mean very+ # different volumes depending on the unit, so freight math can never+ # multiply raw dimension columns.+ it 'reads the same numbers in inches as roughly sixteen times the volume' do+ metric = described_class.cubic_meters(10, 10, 10, unit: 'cm')+ imperial = described_class.cubic_meters(10, 10, 10, unit: 'in')++ expect(imperial / metric).to be_within(0.01).of(16.387)+ end++ it 'answers nil when a dimension is missing or zero' do+ expect(described_class.cubic_meters(10, 10, nil, unit: 'cm')).to be_nil+ expect(described_class.cubic_meters(10, 0, 10, unit: 'cm')).to be_nil+ expect(described_class.cubic_meters(nil, nil, nil, unit: 'cm')).to be_nil+ end+ end++ # Two lists of the same vocabulary can drift, and a unit a merchant may+ # store but this cannot convert is silently read as the default — a pound+ # counted as a kilogram, an inch as a centimeter.+ describe 'the units it covers' do+ it 'converts every unit a variant may be measured in' do+ expect(described_class::LENGTH_IN_CENTIMETERS.keys).to match_array(Spree::Variant::DIMENSION_UNITS)+ expect(described_class::WEIGHT_IN_KILOGRAMS.keys).to match_array(Spree::Variant::WEIGHT_UNITS)+ end+ end+end