Skip to content

armgit / spree

Public Imported from GitHub
0

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.

Added carton packing details to variants

Damian Legawiece4139e3abd33
diff --git a/spree/core/app/models/spree/stock/content_item.rb b/spree/core/app/models/spree/stock/content_item.rb
index 3fc71d93d5..62f3b7a22b 100644
--- a/spree/core/app/models/spree/stock/content_item.rb
+++ b/spree/core/app/models/spree/stock/content_item.rb
@@ -42,6 +42,7 @@ module Spree
price * quantity
end
+ # Cubic meters, following the variant.
def volume
variant_volume * quantity
end
diff --git a/spree/core/app/models/spree/stock/coordinator.rb b/spree/core/app/models/spree/stock/coordinator.rb
index f8786c70ba..7b94f7b4df 100644
--- a/spree/core/app/models/spree/stock/coordinator.rb
+++ b/spree/core/app/models/spree/stock/coordinator.rb
@@ -36,11 +36,6 @@ module Spree
packages += packer.packages
end
- # A proposal's packages belong to the cart or order being allocated.
- # Saying so is what gives them its currency, store and destination —
- # Package#owner would otherwise fall back to guessing from a unit's
- # order_id, which cart-phase units deliberately don't carry.
- packages.each { |package| package.owner = order }
packages
end
@@ -120,7 +115,7 @@ module Spree
end
def build_packer(stock_location, inventory_units)
- Packer.new(stock_location, inventory_units, splitters(stock_location))
+ Packer.new(stock_location, inventory_units, splitters(stock_location), owner: order)
end
def splitters(_stock_location)
diff --git a/spree/core/app/models/spree/stock/package.rb b/spree/core/app/models/spree/stock/package.rb
index 6781f44be3..d955816865 100644
--- a/spree/core/app/models/spree/stock/package.rb
+++ b/spree/core/app/models/spree/stock/package.rb
@@ -45,6 +45,7 @@ module Spree
def add(inventory_unit, state = :on_hand)
# Remove find_item check as already taken care by prioritizer
contents << ContentItem.new(inventory_unit, state)
+ @freight_summary = nil
end
def add_multiple(inventory_units, state = :on_hand)
@@ -58,6 +59,7 @@ module Spree
def remove_item(item)
@contents -= [item]
+ @freight_summary = nil
end
# Fix regression that removed package.order.
@@ -70,34 +72,34 @@ module Spree
contents.sum(&:amount)
end
- # Content weight plus the store's default package weight (packaging
- # tare). This is the single seam every weight consumer reads —
- # calculators, rate providers, weight rules and the weight splitter —
- # so the tare applies everywhere without any of them knowing about it.
+ # Content weight plus the tare of the store's default package (the box
+ # itself, plus filler). This is the single point every weight consumer
+ # reads — calculators, rate providers, weight rules and the weight
+ # splitter — so the tare applies everywhere without any of them knowing
+ # about it.
def weight
- contents_weight = contents.sum(&:weight)
- tare = owner&.store&.preferred_default_package_weight.to_f
-
- contents_weight + tare
+ contents.sum(&:weight) + tare
end
# The store's default package dimensions (the box this package ships
# in), used verbatim by carrier rate providers for dimensional-weight
# pricing. Item dimensions are deliberately not summed — items don't
- # stack into a box shape. Nil until the store configures all three,
- # in the unit implied by the store's unit system (in/cm).
+ # stack into a box shape. Nil until the store records all three.
#
# @return [Hash{Symbol => Float}, nil]
def dimensions
- store = owner&.store
- return if store.nil?
-
- length = store.preferred_default_package_length.to_f
- width = store.preferred_default_package_width.to_f
- height = store.preferred_default_package_height.to_f
- return if [length, width, height].any?(&:zero?)
+ default_package_type&.dimensions_in(store_dimensions_unit)
+ end
- { length: length, width: width, height: height }
+ # How this package's contents roll up into freight logistics — cartons,
+ # pallets, cubic meters, gross weight. Computed live; an order's summary
+ # comes from the frozen copy on its selected delivery rate instead.
+ #
+ # @return [Spree::FreightSummary]
+ # Memoized because quoting reads it repeatedly, and dropped whenever the
+ # contents change — a stale volume would pick the wrong freight tier.
+ def freight_summary
+ @freight_summary ||= Spree::FreightSummary.build(contents)
end
def on_hand
@@ -183,8 +185,13 @@ module Spree
to_fulfillment
end
+ # Cubic meters of packed goods — carton volume where the contents
+ # declare cartons, unit volume otherwise. Cartons stack, so unlike
+ # +dimensions+ this genuinely sums.
+ #
+ # @return [BigDecimal]
def volume
- contents.sum(&:volume)
+ freight_summary.total_volume
end
def dimension
@@ -193,6 +200,36 @@ module Spree
private
+ # The store's default box.
+ #
+ # @return [Spree::PackageType, nil]
+ def default_package_type
+ return @default_package_type if defined?(@default_package_type)
+
+ @default_package_type = owner&.store&.default_package_type
+ end
+
+ # The box's own weight, converted into the unit the contents are
+ # measured in. A merchant may record a carton in kilograms while the
+ # store quotes in pounds, and adding those numbers together would
+ # understate the tare by more than half.
+ #
+ # @return [BigDecimal]
+ def tare
+ package_type = default_package_type
+ return 0 if package_type.nil?
+
+ package_type.weight_in(owner&.store&.preferred_weight_unit || Spree::Measurement::DEFAULT_WEIGHT_UNIT)
+ end
+
+ # What a dimension means to this store, matching the fallback a
+ # variant's own dimensions take.
+ #
+ # @return [String]
+ def store_dimensions_unit
+ Spree::Variant.store_dimensions_unit(owner&.store)
+ end
+
def variant_ids
contents.map { |item| item.inventory_unit.variant_id }.compact.uniq
end
diff --git a/spree/core/app/models/spree/stock/packer.rb b/spree/core/app/models/spree/stock/packer.rb
index 4fc9c251fa..55d1d86a43 100644
--- a/spree/core/app/models/spree/stock/packer.rb
+++ b/spree/core/app/models/spree/stock/packer.rb
@@ -1,12 +1,19 @@
module Spree
module Stock
class Packer
- attr_reader :stock_location, :inventory_units, :splitters
+ attr_reader :stock_location, :inventory_units, :splitters, :owner
- def initialize(stock_location, inventory_units, splitters = [Splitter::Base])
+ # @param owner [Spree::Cart, Spree::Order, nil] the purchase being
+ # packed. Every package it builds carries this, including the ones
+ # splitters derive, because a proposed package's inventory units
+ # belong to no order yet — so anything reading the buyer through the
+ # package (the packaging tare, the channel and company eligibility
+ # rules) would otherwise see nothing.
+ def initialize(stock_location, inventory_units, splitters = [Splitter::Base], owner: nil)
@stock_location = stock_location
@inventory_units = inventory_units
@splitters = splitters
+ @owner = owner
end
def packages
@@ -18,7 +25,7 @@ module Spree
end
def default_package
- package = Package.new(stock_location)
+ package = build_package
# Group by variant_id as grouping by variant fires cached query.
inventory_units.index_by(&:variant_id).each do |variant_id, inventory_unit|
@@ -38,6 +45,16 @@ module Spree
package
end
+ # The single point every package this packer emits is born at, so the
+ # owner cannot be lost by a splitter that builds its own.
+ #
+ # @return [Spree::Stock::Package]
+ def build_package(contents = [])
+ package = Package.new(stock_location, contents)
+ package.owner = owner
+ package
+ end
+
private
def build_splitter
diff --git a/spree/core/app/models/spree/stock/splitter/base.rb b/spree/core/app/models/spree/stock/splitter/base.rb
index 7848e99ae6..bae6d30507 100644
--- a/spree/core/app/models/spree/stock/splitter/base.rb
+++ b/spree/core/app/models/spree/stock/splitter/base.rb
@@ -21,8 +21,10 @@ module Spree
next_splitter ? next_splitter.split(packages) : packages
end
+ # Through the packer, so a derived package carries the same owner as
+ # the one it was split from.
def build_package(contents = [])
- Spree::Stock::Package.new(stock_location, contents)
+ packer.build_package(contents)
end
end
end
diff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rb
index 376d5c057f..15c4f911bf 100644
--- a/spree/core/app/models/spree/variant.rb
+++ b/spree/core/app/models/spree/variant.rb
@@ -25,6 +25,10 @@ module Spree
belongs_to :product, -> { with_deleted }, touch: true, class_name: 'Spree::Product', inverse_of: :variants
belongs_to :tax_category, class_name: 'Spree::TaxCategory', optional: true
+ # The carton this variant is packed into. Geometry lives on the shared
+ # row; how many units fit and what a packed carton weighs stay here.
+ belongs_to :carton_package_type, class_name: 'Spree::PackageType', optional: true,
+ inverse_of: :variants
# Which seller sells this variant. Nil is the operator's own listing, and
# on a product whose seller owns every variant the product answers instead
# — see #resolved_seller_id. Several sellers on one product is the whole point: two
@@ -110,6 +114,7 @@ module Spree
# configuration from another store must never be reachable by id.
validate :seller_must_belong_to_store, if: -> { will_save_change_to_seller_id? }
validate :delivery_profile_must_belong_to_store, if: -> { will_save_change_to_delivery_profile_id? }
+ validate :carton_package_type_must_belong_to_store, if: -> { will_save_change_to_carton_package_type_id? }
# On an owned product the variant's own seller and profile columns carry
# no meaning — every variant is the product's seller's and ships as the
@@ -129,6 +134,9 @@ module Spree
validates :minimum_order_quantity, numericality: { only_integer: true, greater_than: 0, allow_nil: true }
validates :order_multiple, numericality: { only_integer: true, greater_than: 0, allow_nil: true }
validates :units_per_carton, numericality: { only_integer: true, greater_than: 0, allow_nil: true }
+ validates :cartons_per_pallet, numericality: { only_integer: true, greater_than: 0, allow_nil: true }
+ validates :carton_weight, numericality: { greater_than: 0, allow_nil: true }
+ validate :carton_package_type_is_a_carton
validates :purchase_unit, inclusion: { in: PURCHASE_UNITS }, allow_blank: true
# Both are data errors the merchant should hear about while editing, not
@@ -277,7 +285,8 @@ module Spree
# question.
self.whitelisted_ransackable_attributes = %w[weight depth width height sku discontinue_on cost_price cost_currency track_inventory
deleted_at product_id hs_code country_of_origin
- minimum_order_quantity order_multiple purchase_unit units_per_carton]
+ minimum_order_quantity order_multiple purchase_unit units_per_carton
+ carton_package_type_id carton_weight cartons_per_pallet]
self.whitelisted_ransackable_scopes = %i(product_name_or_sku_cont search_by_product_name_or_sku search)
def self.product_name_or_sku_cont(query)
@@ -917,8 +926,14 @@ module Spree
product&.store
end
+ # The cubic meters one unit of this variant occupies. Multiplying the
+ # raw dimension columns would answer in whatever unit the merchant typed,
+ # which is a sixteenfold error between inches and centimeters — so the
+ # name means CBM everywhere it appears (Variant, ContentItem, Package).
+ #
+ # @return [BigDecimal]
def volume
- (width || 0) * (height || 0) * (depth || 0)
+ Spree::Measurement.cubic_meters(width, height, depth, unit: dimensions_unit) || 0
end
def dimension
@@ -927,8 +942,33 @@ module Spree
# Returns the weight unit for the variant
# @return [String]
+ # Falls back to the variant's own store, like {#dimensions_unit} below —
+ # on a multi-store install the default store's unit is someone else's,
+ # and converting a kilogram catalog as pounds misweighs every quote.
def weight_unit
- attributes['weight_unit'] || Spree::Store.default.preferred_weight_unit
+ attributes['weight_unit'] || (preference_store || Spree::Store.default)&.preferred_weight_unit
+ end
+
+ # The unit this variant's width/height/depth are expressed in. Falls back
+ # to what the store's unit system implies, which is what every other
+ # dimension in the store already means — there is no separate store
+ # preference for it, so a second settable value cannot contradict the
+ # first. Mirrors {#weight_unit}, which has always resolved this way.
+ #
+ # Surfaces that show or export what the merchant actually stored — the CSV
+ # export, so a round-trip does not stamp one store's unit onto every
+ # variant — read the raw column instead.
+ #
+ # @return [String] one of {DIMENSION_UNITS}
+ def dimensions_unit
+ attributes['dimensions_unit'].presence || self.class.store_dimensions_unit(preference_store)
+ end
+
+ # @param store [Spree::Store, nil]
+ # @return [String]
+ def self.store_dimensions_unit(store)
+ store ||= Spree::Store.default
+ store&.metric_unit_system? ? 'cm' : 'in'
end
def discontinue!
@@ -990,6 +1030,25 @@ module Spree
(quantity.to_i / units_per_carton.to_f).ceil
end
+ # The cubic meters one packed carton of this variant occupies. Geometry
+ # comes from the shared carton row, so correcting a carton size fixes
+ # every product packed in it.
+ #
+ # @return [BigDecimal, nil]
+ def carton_volume
+ carton_package_type&.volume
+ end
+
+ # How many units a full pallet of this variant holds. Nil unless both
+ # halves of the chain are recorded.
+ #
+ # @return [Integer, nil]
+ def units_per_pallet
+ return if units_per_carton.to_i.zero? || cartons_per_pallet.to_i.zero?
+
+ units_per_carton * cartons_per_pallet
+ end
+
private
def order_multiple_fits_cartons
@@ -999,6 +1058,14 @@ module Spree
errors.add(:order_multiple, :incompatible_with_carton, units_per_carton: units_per_carton)
end
+ # A pallet or a shipping box is not what a product is packed into; only
+ # a carton row can stand in this slot.
+ def carton_package_type_is_a_carton
+ return if carton_package_type.blank? || carton_package_type.carton?
+
+ errors.add(:carton_package_type, :must_be_a_carton)
+ end
+
def carton_purchase_unit_has_divisor
return unless purchase_unit == 'carton'
return if units_per_carton.to_i.positive?
@@ -1133,6 +1200,18 @@ module Spree
errors.add(:delivery_profile, :invalid)
end
+ # Same guard as the delivery profile above: a carton belonging to another
+ # store must never be reachable by id.
+ def carton_package_type_must_belong_to_store
+ return if self[:carton_package_type_id].nil?
+
+ store = product&.store
+ return if store.nil?
+ return if association(:carton_package_type).reader&.store_id == store.id
+
+ errors.add(:carton_package_type, :invalid)
+ end
+
def validate_sku_uniqueness
scope = self.class.for_seller(resolved_seller_id).
where(deleted_at: nil).
diff --git a/spree/core/db/migrate/20260831100002_add_carton_details_to_spree_variants.rb b/spree/core/db/migrate/20260831100002_add_carton_details_to_spree_variants.rb
new file mode 100644
index 0000000000..341225f8d6
--- /dev/null
+++ b/spree/core/db/migrate/20260831100002_add_carton_details_to_spree_variants.rb
@@ -0,0 +1,10 @@
+class AddCartonDetailsToSpreeVariants < ActiveRecord::Migration[8.1]
+ def change
+ # The rest of the packing chain around +units_per_carton+, which
+ # docs/plans/6.0-b2b-quantity-rules.md already added. Geometry lives on
+ # the referenced carton row; only the per-product packing facts sit here.
+ add_reference :spree_variants, :carton_package_type, index: true
+ add_column :spree_variants, :carton_weight, :decimal, precision: 8, scale: 2
+ add_column :spree_variants, :cartons_per_pallet, :integer
+ end
+end
diff --git a/spree/core/spec/models/spree/stock/coordinator_spec.rb b/spree/core/spec/models/spree/stock/coordinator_spec.rb
index 6d5eb26807..43e8978bba 100644
--- a/spree/core/spec/models/spree/stock/coordinator_spec.rb
+++ b/spree/core/spec/models/spree/stock/coordinator_spec.rb
@@ -17,6 +17,25 @@ module Spree
end
end
+ # A proposed package's inventory units belong to no order yet, so the
+ # walk-to-an-order fallback answers nil and everything reading the buyer
+ # through the package — the packaging tare, the channel and company
+ # eligibility rules — silently sees nothing.
+ describe 'the package owner' do
+ it 'carries the purchase being quoted onto every package' do
+ expect(subject.build_packages.map(&:owner)).to all(eq(order))
+ end
+
+ it 'carries a cart the same way, before any order exists' do
+ cart = create(:cart, store: store)
+ create(:line_item, cart: cart, order: nil)
+
+ owners = Coordinator.new(cart.reload).build_packages.map(&:owner)
+
+ expect(owners).to all(eq(cart))
+ end
+ end
+
# Allocation asks each profile (and the order's channel) about every
# candidate location, so membership must be read from loaded rows —
# re-querying per question multiplied with items × locations.
diff --git a/spree/core/spec/models/spree/stock/package_spec.rb b/spree/core/spec/models/spree/stock/package_spec.rb
index 0308690440..586f7ca929 100644
--- a/spree/core/spec/models/spree/stock/package_spec.rb
+++ b/spree/core/spec/models/spree/stock/package_spec.rb
@@ -41,14 +41,12 @@ module Spree
# currency read the owner's store, and a cart-owned package must not
# lose them just because no order exists yet.
it 'applies the store tare to a cart-owned package' do
- @default_store.update!(preferred_default_package_weight: 2.5)
+ create(:package_type, store: @default_store, default: true, weight: 2.5, weight_unit: 'lb')
cart = create(:cart, store: @default_store)
- line_item = create(:line_item, cart: cart, order: nil, variant: variant)
+ create(:line_item, cart: cart, order: nil, variant: variant)
fulfillment = create(:shipment, cart: cart, order: nil, stock_location: create(:stock_location))
expect(fulfillment.to_package.weight).to eq(27.5)
- ensure
- @default_store.update!(preferred_default_package_weight: 0)
end
it 'falls back to the units for a package with no fulfillment' do
@@ -67,37 +65,81 @@ module Spree
# The tare applies at this single seam so every weight consumer —
# calculators, rate providers, weight rules, the weight splitter —
# inherits it without knowing the preference exists.
- it 'adds the store default package weight on top of the contents' do
- order.store.update!(preferred_default_package_weight: 2.5)
+ it 'adds the default package type weight on top of the contents' do
+ create(:package_type, store: order.store, default: true, weight: 2.5, weight_unit: 'lb')
4.times { subject.add build_inventory_unit }
expect(subject.weight).to eq(102.5)
end
+ # The summary is memoized because quoting reads it repeatedly, so a
+ # package added to after its first read would otherwise report the
+ # volume it had before — and pick the freight tier to match.
+ it 'reports the volume it holds now, not the volume it was first asked about' do
+ subject.add build_inventory_unit
+ first = subject.freight_summary.total_units
+
+ subject.add build_inventory_unit
+
+ expect(subject.freight_summary.total_units).to eq(first + 1)
+ end
+
+ it 'forgets a removed item too' do
+ item = build_inventory_unit
+ subject.add item
+ subject.add build_inventory_unit
+ subject.freight_summary
+
+ subject.remove(item)
+
+ expect(subject.freight_summary.total_units).to eq(1)
+ end
+
it 'applies the tare once per package, not per item' do
- order.store.update!(preferred_default_package_weight: 2.5)
+ create(:package_type, store: order.store, default: true, weight: 2.5, weight_unit: 'lb')
subject.add build_inventory_unit
expect(subject.weight).to eq(27.5)
end
+ # A merchant may record a carton in centimetres while the store quotes
+ # in pounds and inches. Handing the raw numbers to a carrier reads
+ # centimetres as inches — a 2.54x overstatement on every axis.
+ describe 'packages measured in another unit than the store uses' do
+ it 'converts the tare into the store weight unit' do
+ stub_store_preferences(order.store, weight_unit: 'lb')
+ create(:package_type, store: order.store, default: true, weight: 1, weight_unit: 'kg')
+
+ subject.add build_inventory_unit
+
+ # 1 kg is about 2.2 lb, not 1.
+ expect(subject.weight - 25).to be_within(0.01).of(2.2046)
+ end
+
+ it 'converts the box dimensions into the store dimension unit' do
+ stub_store_preferences(order.store, unit_system: 'imperial')
+ create(:package_type, store: order.store, default: true,
+ length: 25.4, width: 50.8, height: 76.2, dimensions_unit: 'cm')
+
+ subject.add build_inventory_unit
+
+ expect(subject.dimensions).to eq(length: 10.0, width: 20.0, height: 30.0)
+ end
+ end
+
describe '#dimensions' do
- it 'is nil until the store configures a full default package' do
+ it 'is nil until the store has a fully measured default package' do
subject.add build_inventory_unit
expect(subject.dimensions).to be_nil
- order.store.update!(preferred_default_package_length: 12, preferred_default_package_width: 9)
+ create(:package_type, store: order.store, default: true, length: 12, width: 9, height: nil, dimensions_unit: 'in')
expect(subject.dimensions).to be_nil
end
it 'returns the configured box verbatim, never derived from items' do
- order.store.update!(
- preferred_default_package_length: 12,
- preferred_default_package_width: 9,
- preferred_default_package_height: 4
- )
+ create(:package_type, store: order.store, default: true, length: 12, width: 9, height: 4, dimensions_unit: 'in')
subject.add build_inventory_unit
@@ -248,13 +290,25 @@ module Spree
end
context '#volume' do
- it 'calculates the sum of the volume of all the items' do
- contents = [ContentItem.new(build(:inventory_unit, variant: build(:variant))),
- ContentItem.new(build(:inventory_unit, variant: build(:variant))),
- ContentItem.new(build(:inventory_unit, variant: build(:variant))),
- ContentItem.new(build(:inventory_unit, variant: build(:variant)))]
+ # Cubic meters, not the product of raw dimension columns: the same
+ # numbers read as inches rather than centimeters are a sixteenfold
+ # error, which is why freight math never multiplies columns directly.
+ it 'reports the packed volume in cubic meters' do
+ variant = build(:variant, width: 10, height: 20, depth: 30, dimensions_unit: 'cm')
+ contents = [ContentItem.new(build(:inventory_unit, variant: variant, quantity: 2))]
package = Package.new(stock_location, contents)
- expect(package.volume).to eq contents.sum(&:volume)
+
+ expect(package.volume).to eq(BigDecimal('0.012'))
+ end
+
+ it 'reads the same box in inches as a larger volume' do
+ metric = build(:variant, width: 10, height: 20, depth: 30, dimensions_unit: 'cm')
+ imperial = build(:variant, width: 10, height: 20, depth: 30, dimensions_unit: 'in')
+
+ metric_package = Package.new(stock_location, [ContentItem.new(build(:inventory_unit, variant: metric))])
+ imperial_package = Package.new(stock_location, [ContentItem.new(build(:inventory_unit, variant: imperial))])
+
+ expect(imperial_package.volume).to be > metric_package.volume
end
end
diff --git a/spree/core/spec/models/spree/variant_carton_details_spec.rb b/spree/core/spec/models/spree/variant_carton_details_spec.rb
new file mode 100644
index 0000000000..69f53d352f
--- /dev/null
+++ b/spree/core/spec/models/spree/variant_carton_details_spec.rb
@@ -0,0 +1,85 @@
+require 'spec_helper'
+
+RSpec.describe 'Spree::Variant carton details', type: :model do
+ let(:store) { @default_store }
+ let(:carton) { create(:carton_package_type, store: store, length: 40, width: 30, height: 25) }
+
+ describe 'the carton reference' do
+ it 'accepts a carton-kind package type' do
+ expect(build(:variant, carton_package_type: carton)).to be_valid
+ end
+
+ # A pallet is what cartons stack on, not what a product is packed into.
+ it 'refuses a package type of any other kind' do
+ variant = build(:variant, carton_package_type: create(:pallet_package_type, store: store))
+
+ expect(variant).not_to be_valid
+ expect(variant.errors[:carton_package_type]).to be_present
+ end
+ end
+
+ describe '#carton_volume' do
+ it 'reads the geometry off the shared carton row' do
+ expect(build(:variant, carton_package_type: carton).carton_volume).to eq(BigDecimal('0.03'))
+ end
+
+ # One edit to a carton size corrects every product packed in it — the
+ # reason geometry is shared rather than copied onto each variant.
+ it 'follows the carton when the carton is resized' do
+ variant = create(:variant, carton_package_type: carton)
+ carton.update!(length: 80)
+
+ expect(variant.reload.carton_volume).to eq(BigDecimal('0.06'))
+ end
+
+ it 'is nil without a carton' do
+ expect(build(:variant).carton_volume).to be_nil
+ end
+ end
+
+ describe '#units_per_pallet' do
+ it 'multiplies out the packing chain' do
+ variant = build(:variant, units_per_carton: 24, cartons_per_pallet: 40)
+
+ expect(variant.units_per_pallet).to eq(960)
+ end
+
+ it 'is nil when either half is missing' do
+ expect(build(:variant, units_per_carton: 24).units_per_pallet).to be_nil
+ expect(build(:variant, cartons_per_pallet: 40).units_per_pallet).to be_nil
+ end
+ end
+
+ describe 'validations' do
+ it 'refuses a non-positive carton weight or pallet count' do
+ expect(build(:variant, carton_weight: 0)).not_to be_valid
+ expect(build(:variant, cartons_per_pallet: 0)).not_to be_valid
+ end
+ end
+
+ describe '#weight_unit' do
+ # The default store's unit is someone else's on a multi-store install;
+ # a kilogram catalog converted as pounds misweighs every freight quote.
+ it 'falls back to the variant own store, not the default store' do
+ other_store = create(:store)
+ stub_store_preferences(other_store, weight_unit: 'kg')
+ product = create(:product, store: other_store)
+ variant = product.default_variant
+ variant.update_columns(weight_unit: nil)
+
+ expect(variant.reload.weight_unit).to eq('kg')
+ end
+ end
+
+ describe '#dimensions_unit' do
+ it 'keeps the variant own unit when set' do
+ expect(build(:variant, dimensions_unit: 'mm').dimensions_unit).to eq('mm')
+ end
+
+ it 'follows the store unit system when unset' do
+ stub_store_preferences(store, unit_system: 'metric')
+
+ expect(create(:variant).dimensions_unit).to eq('cm')
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/variant_spec.rb b/spree/core/spec/models/spree/variant_spec.rb
index a8e1cb0e6c..0a2170b062 100644
--- a/spree/core/spec/models/spree/variant_spec.rb
+++ b/spree/core/spec/models/spree/variant_spec.rb
@@ -1214,17 +1214,27 @@ describe Spree::Variant, type: :model do
end
end
+ # Cubic meters, converted from the unit the merchant recorded — never the
+ # product of the raw columns, which reads inches as centimeters and is out
+ # by a factor of sixteen.
describe '#volume' do
let(:variant_zero_width) { create(:variant, width: 0) }
- let(:variant) { create(:variant) }
it 'is zero if any dimension parameter is zero' do
expect(variant_zero_width.volume).to eq 0
end
- it 'return the volume if the dimension parameters are different of zero' do
- volume_expected = variant.width * variant.depth * variant.height
- expect(variant.volume).to eq volume_expected
+ it 'reports cubic meters from the recorded unit' do
+ variant = create(:variant, width: 100, height: 100, depth: 100, dimensions_unit: 'cm')
+
+ expect(variant.volume).to eq(BigDecimal('1'))
+ end
+
+ it 'reads the same numbers in inches as a larger volume' do
+ metric = create(:variant, width: 10, height: 10, depth: 10, dimensions_unit: 'cm')
+ imperial = create(:variant, width: 10, height: 10, depth: 10, dimensions_unit: 'in')
+
+ expect(imperial.volume / metric.volume).to be_within(0.01).of(16.387)
end
end