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 the freight summary a forwarder quotes against

Damian Legawiecb0c7eb90360c
diff --git a/spree/core/app/models/concerns/spree/purchase/freight.rb b/spree/core/app/models/concerns/spree/purchase/freight.rb
new file mode 100644
index 0000000000..6c92cb1c26
--- /dev/null
+++ b/spree/core/app/models/concerns/spree/purchase/freight.rb
@@ -0,0 +1,52 @@
+module Spree
+ module Purchase
+ # The logistics rollup a freight forwarder quotes against — units,
+ # cartons, pallets, cubic meters and gross weight — shared by
+ # Spree::Cart and Spree::Order.
+ #
+ # Read only from what the freight provider froze onto the rates a
+ # purchase ships under, never derived from the live catalog. Until a
+ # freight rate is selected there is nothing to report, and a purchase
+ # that ships by parcel reports nothing at all: a parcel carrier does not
+ # read cubic meters. Once quoted, a carton size corrected next month must
+ # not rewrite what this container held. Same doctrine as the duty
+ # snapshot (docs/plans/6.0-duties-and-custom-fees.md).
+ module Freight
+ extend ActiveSupport::Concern
+
+ # @return [Spree::FreightSummary, nil] nil unless a selected rate
+ # carries a frozen summary
+ def freight_summary
+ return @freight_summary if defined?(@freight_summary)
+
+ summary = build_freight_summary
+ # Assigned on every path, including the empty one: every retail
+ # purchase answers "nothing", and a conditional assignment would leave
+ # that case unmemoized — querying the fulfillments again on each call,
+ # which is the opposite of what memoizing is for.
+ @freight_summary = (summary unless summary.nil? || summary.empty?)
+ end
+
+ # Dropped on reload, so a purchase whose rate selection changed in the
+ # same request reads again rather than answering from the load it had
+ # before.
+ def reload(*)
+ remove_instance_variable(:@freight_summary) if defined?(@freight_summary)
+ super
+ end
+
+ private
+
+ # Only the consignments actually shipping: a canceled fulfillment keeps
+ # its frozen summary, so counting it would report a re-allocated load
+ # twice. Two freight consignments are still one load to the forwarder,
+ # so they are merged rather than listed.
+ def build_freight_summary
+ summaries = fulfillments.valid.filter_map { |fulfillment| fulfillment.selected_delivery_rate&.freight_summary }
+ return if summaries.empty?
+
+ Spree::FreightSummary.merge(summaries)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/cart.rb b/spree/core/app/models/spree/cart.rb
index 2de72f098b..ddb9649fa0 100644
--- a/spree/core/app/models/spree/cart.rb
+++ b/spree/core/app/models/spree/cart.rb
@@ -18,6 +18,7 @@ module Spree
include Spree::SingleStoreResource
include Spree::Purchase::Channel
include Spree::Purchase::Company
+ include Spree::Purchase::Freight
include Spree::Purchase::QuantityRules
include Spree::Purchase::PurchaseOrder
include Spree::Purchase::Market
diff --git a/spree/core/app/models/spree/freight_summary.rb b/spree/core/app/models/spree/freight_summary.rb
new file mode 100644
index 0000000000..ed34220791
--- /dev/null
+++ b/spree/core/app/models/spree/freight_summary.rb
@@ -0,0 +1,183 @@
+module Spree
+ # What a cart or a package looks like to a freight forwarder: how many
+ # units, how many cartons those fill, how many pallets those stack onto,
+ # the cubic meters they occupy and what the whole thing weighs.
+ #
+ # These are the numbers a wholesale shipment is quoted and tiered on, and
+ # they are not derivable from the retail shipping data — a case of 48 bottles
+ # is one carton, not 48 parcels. A variant declares its carton
+ # (docs/plans/6.0-b2b-wholesale-shipping.md) and the rollup follows the
+ # chain Unit -> Carton -> Pallet -> CBM / weight.
+ #
+ # Lines whose variant declares no carton fall back to unit volume and
+ # weight and mark the summary {#complete?} false, so the numbers stay
+ # useful while saying plainly that some of the catalog is unmeasured.
+ #
+ # A purchase reads the copy the freight provider froze onto its selected
+ # delivery rate, and never re-derives it from the live catalog. No freight
+ # rate, no summary.
+ class FreightSummary
+ include ActiveModel::Model
+ include ActiveModel::Attributes
+
+ attribute :lines, default: -> { [] }
+
+ class << self
+ # Rolls up stock package contents.
+ #
+ # @param contents [Array<Spree::Stock::ContentItem>]
+ # @return [Spree::FreightSummary]
+ def build(contents)
+ from_pairs(Array(contents).filter_map do |item|
+ variant = item.variant
+ [variant, item.quantity] if variant
+ end)
+ end
+
+
+ # Combines the summaries several fulfillments froze into the one load
+ # the forwarder sees.
+ #
+ # Lines for the same variant are added together rather than listed
+ # twice, because carton and pallet counts were each rounded up when the
+ # line was built: three cartons in one consignment and three in another
+ # is six cartons on one pallet, not two pallets.
+ #
+ # @param summaries [Array<Spree::FreightSummary>]
+ # @return [Spree::FreightSummary]
+ def merge(summaries)
+ lines = Array(summaries).flat_map(&:lines).
+ group_by(&:variant_id).
+ map { |_variant_id, grouped| grouped.length == 1 ? grouped.first : Line.combine(grouped) }
+
+ new(lines: lines)
+ end
+
+ # Rebuilds a summary from its serialized form — the frozen copy carried
+ # in a delivery rate's metadata.
+ #
+ # @param payload [Hash, nil]
+ # @return [Spree::FreightSummary, nil]
+ def from_metadata(payload)
+ return if payload.blank?
+
+ payload = payload.with_indifferent_access
+ # Only keys this version of Line declares. A frozen snapshot outlives
+ # the code that wrote it by design, so an attribute renamed or dropped
+ # later must read as absent rather than raise on every historical
+ # order the moment it is serialized.
+ known = Spree::FreightSummary::Line.attribute_names.map(&:to_sym)
+ lines = Array(payload[:lines]).map do |line|
+ Spree::FreightSummary::Line.new(line.symbolize_keys.slice(*known))
+ end
+
+ new(lines: lines)
+ end
+
+ private
+
+ # One line per variant, whatever the packer split it into. A stock
+ # package holds a separate content item for the on-hand and backordered
+ # halves of the same variant, and each half would round its own part
+ # carton up — reporting three cartons for thirty units that fill two.
+ def from_pairs(pairs)
+ quantities = Hash.new(0)
+ variants = {}
+ pairs.each do |variant, quantity|
+ next unless variant && quantity.to_i.positive?
+
+ variants[variant.id] ||= variant
+ quantities[variant.id] += quantity.to_i
+ end
+
+ lines = quantities.map { |variant_id, quantity| Spree::FreightSummary::Line.build(variants[variant_id], quantity) }
+
+ new(lines: lines)
+ end
+ end
+
+ # @return [Integer]
+ def total_units
+ @total_units ||= sum_of(:units).to_i
+ end
+
+ # @return [Integer]
+ def total_cartons
+ @total_cartons ||= sum_of(:cartons).to_i
+ end
+
+ # Pallets are only meaningful when every carton-bearing line says how it
+ # stacks; one silent line would understate the load.
+ #
+ # @return [Integer, nil]
+ def total_pallets
+ return @total_pallets if defined?(@total_pallets)
+
+ carton_lines = lines.select(&:cartons?)
+ @total_pallets =
+ unless carton_lines.empty? || carton_lines.any? { |line| line.pallets.nil? }
+ carton_lines.sum(&:pallets)
+ end
+ end
+
+ # @return [BigDecimal] cubic meters
+ def total_volume
+ @total_volume ||= sum_of(:volume)
+ end
+
+ # @return [BigDecimal] kilograms
+ def total_weight
+ @total_weight ||= sum_of(:weight)
+ end
+
+ # True when every line was measured from its carton. False means some of
+ # the figures above came from unit dimensions instead, which under-reports
+ # the space packaging takes.
+ #
+ # @return [Boolean]
+ def complete?
+ lines.any? && lines.all?(&:complete?)
+ end
+
+ # True when there is nothing here worth reporting as freight — no lines,
+ # or lines that measured to nothing because the catalog records no
+ # dimensions. A retail cart of unmeasured goods has no freight summary
+ # rather than one full of zeros, which would read as a shipment that
+ # takes up no space.
+ #
+ # @return [Boolean]
+ def empty?
+ lines.empty? || (total_volume.zero? && total_weight.zero? && total_cartons.zero?)
+ end
+
+ # The serialized form frozen onto a delivery rate at completion.
+ #
+ # @param identify_lines [Boolean] whether each line names the variant it
+ # came from. False on a storefront that withholds commercial detail —
+ # the totals are logistics and stay, but a SKU is catalog identity.
+ # @return [Hash]
+ def as_json(identify_lines: true)
+ {
+ 'total_units' => total_units,
+ 'total_cartons' => total_cartons,
+ 'total_pallets' => total_pallets,
+ 'total_volume' => decimal_string(total_volume),
+ 'total_weight' => decimal_string(total_weight),
+ 'complete' => complete?,
+ 'lines' => lines.map { |line| line.as_json(identify_lines: identify_lines) }
+ }
+ end
+
+ private
+
+ # Plain decimal notation. BigDecimal's default renders 0.06 as "0.6e-1",
+ # which is what a client would print beside "CBM".
+ def decimal_string(value)
+ BigDecimal(value.to_s).to_s('F')
+ end
+
+ def sum_of(attribute)
+ lines.sum { |line| line.public_send(attribute) || 0 }
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/freight_summary/line.rb b/spree/core/app/models/spree/freight_summary/line.rb
new file mode 100644
index 0000000000..a781253477
--- /dev/null
+++ b/spree/core/app/models/spree/freight_summary/line.rb
@@ -0,0 +1,256 @@
+module Spree
+ class FreightSummary
+ # One variant's contribution to a freight summary.
+ #
+ # Built once from the live catalog and thereafter carried as plain data,
+ # so an order's frozen summary keeps reporting the cartons it actually
+ # shipped in even after the variant is repacked.
+ class Line
+ include ActiveModel::Model
+ include ActiveModel::Attributes
+
+ attribute :variant_id, :string
+ attribute :sku, :string
+ attribute :name, :string
+ attribute :units, :integer, default: 0
+ attribute :cartons, :integer
+ attribute :pallets, :integer
+ # The divisors behind the two counts above, carried so a summary split
+ # across consignments can be recombined without consulting the catalog
+ # it was frozen away from.
+ attribute :units_per_carton, :integer
+ attribute :cartons_per_pallet, :integer
+ # The part of the weight that scales with cartons rather than units —
+ # the declared gross where the merchant recorded one, else the empty
+ # carton's own weight. Carried for the same reason as the divisors: it
+ # is what lets two part-full cartons collapse into one without keeping
+ # both packagings' weight.
+ attribute :weight_per_carton, :decimal
+ attribute :volume, :decimal, default: 0
+ attribute :weight, :decimal, default: 0
+ # False when the variant declares no carton, so volume and weight came
+ # from unit dimensions instead.
+ attribute :complete, :boolean, default: false
+
+ # @param variant [Spree::Variant]
+ # @param quantity [Integer]
+ # @return [Spree::FreightSummary::Line]
+ def self.build(variant, quantity)
+ quantity = quantity.to_i
+ cartons = variant.cartons_for(quantity)
+ carton_volume = variant.carton_volume
+
+ if cartons && carton_volume
+ from_cartons(variant, quantity, cartons, carton_volume)
+ else
+ from_units(variant, quantity)
+ end
+ end
+
+ # The measured path: the variant declares a carton with geometry, so
+ # volume and weight are the cartons the order actually fills.
+ def self.from_cartons(variant, quantity, cartons, carton_volume)
+ new(
+ **identity(variant),
+ units: quantity,
+ cartons: cartons,
+ pallets: pallets_for(variant, cartons),
+ volume: carton_volume * cartons,
+ weight: carton_weight_for(variant, cartons, quantity),
+ weight_per_carton: weight_per_carton_for(variant),
+ complete: true
+ )
+ end
+ private_class_method :from_cartons
+
+ # The fallback: no carton on the variant, so the goods are measured
+ # loose. Real enough to quote against, and flagged as incomplete.
+ def self.from_units(variant, quantity)
+ unit_volume = Spree::Measurement.cubic_meters(
+ variant.width, variant.height, variant.depth, unit: variant.dimensions_unit
+ )
+ cartons = variant.cartons_for(quantity)
+
+ new(
+ **identity(variant),
+ units: quantity,
+ cartons: cartons,
+ # A line that counts cartons still says how they stack. Leaving it
+ # blank would drop the pallet count for the whole summary, not just
+ # for this line.
+ pallets: (pallets_for(variant, cartons) if cartons),
+ weight_per_carton: (weight_per_carton_for(variant) if cartons),
+ volume: (unit_volume || 0) * quantity,
+ # A merchant who recorded what a packed carton weighs knows more
+ # than the loose goods do, even when the carton itself is
+ # unmeasured — using the goods' weight there understates the load.
+ weight: cartons ? carton_weight_for(variant, cartons, quantity) : unit_weight(variant) * quantity,
+ complete: false
+ )
+ end
+ private_class_method :from_units
+
+ # Adds together the lines the same variant produced in several
+ # consignments.
+ #
+ # Cartons and pallets are re-derived from the combined units rather than
+ # summed, because each part was rounded up when it was built: a variant
+ # packed twelve to a carton, split three units and nine, is one carton
+ # in total and not two. The divisors ride on the line itself, so a
+ # frozen snapshot can be recombined years later without asking today's
+ # catalog — which is exactly what freezing it was meant to avoid.
+ #
+ # @param parts [Array<Spree::FreightSummary::Line>]
+ # @return [Spree::FreightSummary::Line]
+ def self.combine(parts)
+ first = parts.first
+ units = parts.sum(&:units)
+ recombined = divide(units, first.units_per_carton)
+ # `presence` is no help on an Integer — zero is present — so the
+ # "no part counted cartons" case has to be spelled out, or a line
+ # nobody packed reports zero cartons where every unmerged line
+ # reports none at all.
+ counted = parts.filter_map(&:cartons)
+ cartons = recombined || (counted.sum if counted.any?)
+ pallets = cartons && divide(cartons, first.cartons_per_pallet)
+
+ new(
+ variant_id: first.variant_id,
+ sku: first.sku,
+ name: first.name,
+ units: units,
+ units_per_carton: first.units_per_carton,
+ cartons_per_pallet: first.cartons_per_pallet,
+ cartons: cartons,
+ pallets: pallets,
+ # Volume follows the recombined carton count for the same reason
+ # the count itself does: adding two part-full cartons' volumes
+ # reports space the combined shipment does not take.
+ volume: combined_volume(parts, recombined),
+ weight: combined_weight(parts, cartons),
+ weight_per_carton: parts.filter_map(&:weight_per_carton).first,
+ complete: parts.all?(&:complete?)
+ )
+ end
+
+ # Goods weight scales with units, so summing the parts is right for it;
+ # the packaging scales with cartons, so each carton the merge collapses
+ # must give its share back — otherwise two part-full cartons folded into
+ # one keep both packagings' weight. A snapshot frozen before the
+ # component was recorded has nil here and keeps the plain sum.
+ def self.combined_weight(parts, cartons)
+ summed = parts.sum(&:weight)
+ per_carton = parts.filter_map(&:weight_per_carton).first
+ return summed if cartons.nil? || per_carton.nil?
+
+ collapsed = parts.filter_map(&:cartons).sum - cartons
+ return summed unless collapsed.positive?
+
+ summed - (per_carton * collapsed)
+ end
+ private_class_method :combined_weight
+
+ # Per-carton volume from whichever part recorded one, scaled to the
+ # combined count. Falls back to the plain sum for lines measured loose,
+ # where volume is per unit and adding is right.
+ def self.combined_volume(parts, cartons)
+ summed = parts.sum(&:volume)
+ return summed if cartons.nil?
+
+ measured = parts.detect { |part| part.complete? && part.cartons.to_i.positive? && part.volume.to_d.positive? }
+ return summed if measured.nil?
+
+ (measured.volume.to_d / measured.cartons) * cartons
+ end
+ private_class_method :combined_volume
+
+ # A part of anything still ships as a whole one.
+ def self.divide(quantity, divisor)
+ return if divisor.to_i.zero?
+
+ (quantity / divisor.to_f).ceil
+ end
+ private_class_method :divide
+
+ def self.identity(variant)
+ {
+ variant_id: variant.prefixed_id,
+ sku: variant.sku,
+ name: variant.descriptive_name,
+ units_per_carton: variant.units_per_carton,
+ cartons_per_pallet: variant.cartons_per_pallet
+ }
+ end
+ private_class_method :identity
+
+ # Nil when the variant does not say how its cartons stack — the summary
+ # then reports no pallet count at all rather than a partial one.
+ def self.pallets_for(variant, cartons)
+ divide(cartons, variant.cartons_per_pallet)
+ end
+ private_class_method :pallets_for
+
+ # A packed carton's declared gross weight where the merchant recorded
+ # one — that figure already includes the box. Otherwise the goods plus
+ # the empty carton's own weight, so the packaging is not simply lost
+ # from a shipment the summary calls fully measured.
+ def self.carton_weight_for(variant, cartons, quantity)
+ declared = Spree::Measurement.to_kilograms(variant.carton_weight, unit: variant.weight_unit)
+ return declared * cartons if declared&.positive?
+
+ (unit_weight(variant) * quantity) + (carton_tare(variant) * cartons)
+ end
+ private_class_method :carton_weight_for
+
+ # The carton-scaling component of this variant's weight: the declared
+ # gross when one is recorded (it counts per carton, goods included),
+ # else the empty carton's own weight (the goods then count per unit).
+ def self.weight_per_carton_for(variant)
+ declared = Spree::Measurement.to_kilograms(variant.carton_weight, unit: variant.weight_unit)
+ return declared if declared&.positive?
+
+ carton_tare(variant)
+ end
+ private_class_method :weight_per_carton_for
+
+ # The empty carton's own weight, in the kilograms the summary reports.
+ def self.carton_tare(variant)
+ Spree::Measurement.to_kilograms(
+ variant.carton_package_type&.weight, unit: variant.carton_package_type&.weight_unit
+ ) || 0
+ end
+ private_class_method :carton_tare
+
+ def self.unit_weight(variant)
+ Spree::Measurement.to_kilograms(variant.weight, unit: variant.weight_unit) || 0
+ end
+ private_class_method :unit_weight
+
+ # @return [Boolean]
+ def cartons?
+ cartons.to_i.positive?
+ end
+
+ # @return [Boolean]
+ def complete?
+ !!complete
+ end
+
+ def as_json(identify_lines: true)
+ identity = identify_lines ? { 'variant_id' => variant_id, 'sku' => sku, 'name' => name } : {}
+
+ identity.merge(
+ 'units' => units,
+ 'cartons' => cartons,
+ 'pallets' => pallets,
+ 'units_per_carton' => units_per_carton,
+ 'cartons_per_pallet' => cartons_per_pallet,
+ 'weight_per_carton' => weight_per_carton && BigDecimal(weight_per_carton.to_s).to_s('F'),
+ 'volume' => BigDecimal(volume.to_s).to_s('F'),
+ 'weight' => BigDecimal(weight.to_s).to_s('F'),
+ 'complete' => complete
+ )
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rb
index 42d88693f1..fb89115f58 100644
--- a/spree/core/app/models/spree/order.rb
+++ b/spree/core/app/models/spree/order.rb
@@ -27,6 +27,7 @@ module Spree
include Spree::SanitizableRichText
include Spree::Purchase::Channel
include Spree::Purchase::Company
+ include Spree::Purchase::Freight
include Spree::Purchase::QuantityRules
include Spree::Purchase::PurchaseOrder
include Spree::Purchase::Market
diff --git a/spree/core/spec/models/spree/freight_summary_spec.rb b/spree/core/spec/models/spree/freight_summary_spec.rb
new file mode 100644
index 0000000000..4c93ff4e5f
--- /dev/null
+++ b/spree/core/spec/models/spree/freight_summary_spec.rb
@@ -0,0 +1,261 @@
+require 'spec_helper'
+
+RSpec.describe Spree::FreightSummary do
+ let(:store) { @default_store }
+ let(:carton) { create(:carton_package_type, store: store, length: 40, width: 30, height: 25) }
+
+ # 40 x 30 x 25 cm = 0.03 CBM per carton.
+ let(:packed_variant) do
+ create(:variant,
+ units_per_carton: 12,
+ cartons_per_pallet: 40,
+ carton_weight: 10,
+ weight_unit: 'kg',
+ carton_package_type: carton)
+ end
+
+ def summary_for(pairs)
+ contents = pairs.map do |variant, quantity|
+ Spree::Stock::ContentItem.new(build(:inventory_unit, variant: variant, quantity: quantity))
+ end
+
+ described_class.build(contents)
+ end
+
+ describe 'a fully packed cart' do
+ subject(:summary) { summary_for([[packed_variant, 24]]) }
+
+ it 'counts units, cartons and pallets along the packing chain' do
+ expect(summary.total_units).to eq(24)
+ expect(summary.total_cartons).to eq(2)
+ expect(summary.total_pallets).to eq(1)
+ end
+
+ it 'measures volume from the carton, not the loose goods' do
+ expect(summary.total_volume).to eq(BigDecimal('0.06'))
+ end
+
+ it 'weighs the packed cartons' do
+ expect(summary.total_weight).to eq(BigDecimal('20'))
+ end
+
+ it 'reports itself complete' do
+ expect(summary).to be_complete
+ end
+ end
+
+ it 'rounds a part carton up, because a part carton still ships as one' do
+ expect(summary_for([[packed_variant, 13]]).total_cartons).to eq(2)
+ end
+
+ describe 'a variant with no carton' do
+ let(:loose_variant) do
+ create(:variant, width: 10, height: 10, depth: 10, dimensions_unit: 'cm', weight: 2, weight_unit: 'kg')
+ end
+
+ subject(:summary) { summary_for([[loose_variant, 3]]) }
+
+ it 'falls back to the goods own measurements' do
+ expect(summary.total_volume).to eq(BigDecimal('0.003'))
+ expect(summary.total_weight).to eq(BigDecimal('6'))
+ end
+
+ it 'counts no cartons' do
+ expect(summary.total_cartons).to eq(0)
+ end
+
+ # The numbers stay usable; the flag says why they are partial.
+ it 'reports itself incomplete' do
+ expect(summary).not_to be_complete
+ end
+ end
+
+ # The merchant recorded the carton's own weight; leaving it out of a
+ # summary that calls itself complete loses the packaging from the load.
+ it 'counts the empty carton weight when no gross weight is declared' do
+ tared_carton = create(:carton_package_type, store: store, length: 40, width: 30, height: 25,
+ weight: 0.4, weight_unit: 'kg')
+ variant = create(:variant, units_per_carton: 12, carton_package_type: tared_carton,
+ carton_weight: nil, weight: 1, weight_unit: 'kg')
+
+ summary = summary_for([[variant, 12]])
+
+ expect(summary.total_weight).to eq(BigDecimal('12.4'))
+ end
+
+ it 'trusts a declared gross weight, which already includes the box' do
+ tared_carton = create(:carton_package_type, store: store, length: 40, width: 30, height: 25,
+ weight: 0.4, weight_unit: 'kg')
+ variant = create(:variant, units_per_carton: 12, carton_package_type: tared_carton,
+ carton_weight: 10, weight: 1, weight_unit: 'kg')
+
+ expect(summary_for([[variant, 12]]).total_weight).to eq(BigDecimal('10'))
+ end
+
+ it 'is incomplete when any single line is unmeasured' do
+ loose = create(:variant, width: 10, height: 10, depth: 10, dimensions_unit: 'cm')
+
+ expect(summary_for([[packed_variant, 12], [loose, 1]])).not_to be_complete
+ end
+
+ describe 'pallet counting' do
+ it 'reports nothing when a carton-bearing line does not say how it stacks' do
+ unstacked = create(:variant, units_per_carton: 6, carton_package_type: carton, cartons_per_pallet: nil)
+
+ expect(summary_for([[packed_variant, 12], [unstacked, 6]]).total_pallets).to be_nil
+ end
+
+ it 'reports nothing when nothing is packed in cartons at all' do
+ loose = create(:variant, width: 10, height: 10, depth: 10)
+
+ expect(summary_for([[loose, 2]]).total_pallets).to be_nil
+ end
+ end
+
+ # A client prints these strings beside "CBM" and "kg". BigDecimal's
+ # default renders 0.06 as "0.6e-1".
+ describe 'the serialized numbers' do
+ it 'writes plain decimals, never engineering notation' do
+ json = summary_for([[packed_variant, 24]]).as_json
+
+ expect(json['total_volume']).to eq('0.06')
+ expect(json['lines'].first['volume']).to eq('0.06')
+ end
+ end
+
+ # The merchant recorded what a packed carton weighs. That is a better
+ # answer than the loose goods' weight even when nobody measured the
+ # carton's sides.
+ it 'uses a declared carton weight even when the carton is unmeasured' do
+ unmeasured_carton = create(:package_type, store: store, kind: 'carton', length: nil, width: nil, height: nil)
+ variant = create(:variant, units_per_carton: 12, carton_weight: 10, weight_unit: 'kg',
+ weight: 0.2, carton_package_type: unmeasured_carton)
+
+ summary = summary_for([[variant, 24]])
+
+ expect(summary.total_weight).to eq(BigDecimal('20'))
+ expect(summary).not_to be_complete
+ end
+
+ describe 'freezing and rebuilding' do
+ it 'round-trips through its serialized form' do
+ original = summary_for([[packed_variant, 24]])
+ rebuilt = described_class.from_metadata(original.as_json)
+
+ expect(rebuilt.total_units).to eq(original.total_units)
+ expect(rebuilt.total_cartons).to eq(original.total_cartons)
+ expect(rebuilt.total_pallets).to eq(original.total_pallets)
+ expect(rebuilt.total_volume).to eq(original.total_volume)
+ expect(rebuilt.total_weight).to eq(original.total_weight)
+ expect(rebuilt).to be_complete
+ end
+
+ it 'answers nil for an absent snapshot' do
+ expect(described_class.from_metadata(nil)).to be_nil
+ end
+
+ # A snapshot outlives the code that wrote it by design, so a key this
+ # version no longer knows must read as absent rather than raise on every
+ # historical order the moment it is serialized.
+ it 'ignores keys it no longer declares' do
+ json = summary_for([[packed_variant, 12]]).as_json
+ json['lines'].first['retired_field'] = 'whatever'
+
+ expect { described_class.from_metadata(json) }.not_to raise_error
+ end
+ end
+
+ describe '.merge' do
+ # Each part rounded its own carton count up, so adding them reports a
+ # part-empty carton twice and can invent a whole pallet.
+ it 're-derives the counts from the combined units rather than adding them' do
+ split = [summary_for([[packed_variant, 3]]), summary_for([[packed_variant, 9]])]
+
+ merged = described_class.merge(split)
+
+ expect(merged.total_units).to eq(12)
+ expect(merged.total_cartons).to eq(1)
+ expect(merged.total_pallets).to eq(1)
+ end
+
+ # Adding two part-full cartons' volumes reports space the combined
+ # shipment does not take, which would misprice a volume tier.
+ it 're-derives volume from the recombined carton count' do
+ split = [summary_for([[packed_variant, 3]]), summary_for([[packed_variant, 9]])]
+
+ merged = described_class.merge(split)
+
+ expect(merged.total_cartons).to eq(1)
+ expect(merged.total_volume).to eq(BigDecimal('0.03'))
+ end
+
+ # Goods scale with units and sum correctly; the packaging scales with
+ # cartons, and a carton the merge collapses must give its share back.
+ it 're-derives a declared gross weight from the recombined cartons' do
+ heavy = create(:variant, units_per_carton: 12, carton_package_type: carton,
+ carton_weight: 10, weight_unit: 'kg')
+ merged = described_class.merge([summary_for([[heavy, 3]]), summary_for([[heavy, 9]])])
+
+ expect(merged.total_cartons).to eq(1)
+ expect(merged.total_weight).to eq(BigDecimal('10'))
+ end
+
+ it 'counts a collapsed carton tare once, while the goods keep summing' do
+ tared_carton = create(:carton_package_type, store: store, length: 40, width: 30, height: 25,
+ weight: 0.4, weight_unit: 'kg')
+ variant = create(:variant, units_per_carton: 12, carton_package_type: tared_carton,
+ carton_weight: nil, weight: 1, weight_unit: 'kg')
+ merged = described_class.merge([summary_for([[variant, 3]]), summary_for([[variant, 9]])])
+
+ expect(merged.total_weight).to eq(BigDecimal('12.4'))
+ end
+
+ # A snapshot frozen before the component existed carries no
+ # weight_per_carton; it must keep the old plain sum, not raise or guess.
+ it 'keeps the plain sum for snapshots that predate the component' do
+ old_line = { 'units' => 3, 'cartons' => 1, 'units_per_carton' => 12,
+ 'weight' => '10.0', 'volume' => '0.03', 'complete' => true }
+ halves = [described_class.from_metadata({ 'lines' => [old_line] }),
+ described_class.from_metadata({ 'lines' => [old_line.merge('units' => 9)] })]
+
+ expect(described_class.merge(halves).total_weight).to eq(BigDecimal('20'))
+ end
+
+ it 'keeps distinct variants as separate lines' do
+ other = create(:variant, units_per_carton: 6, carton_package_type: carton)
+ merged = described_class.merge([summary_for([[packed_variant, 12]]), summary_for([[other, 6]])])
+
+ expect(merged.lines.length).to eq(2)
+ expect(merged.total_cartons).to eq(2)
+ end
+
+ it 'is incomplete when any part was' do
+ loose = create(:variant, width: 10, height: 10, depth: 10, dimensions_unit: 'cm')
+
+ merged = described_class.merge([summary_for([[packed_variant, 12]]), summary_for([[loose, 1]])])
+
+ expect(merged).not_to be_complete
+ end
+ end
+
+ describe 'having nothing to report' do
+ it 'is empty for a cart with nothing in it' do
+ expect(summary_for([])).to be_empty
+ end
+
+ # A retail catalog nobody measured would otherwise report a shipment of
+ # zero cartons taking up no space, which reads as a measured empty load
+ # rather than an unmeasured one.
+ it 'is empty when the goods carry no measurements at all' do
+ unmeasured = create(:variant, width: nil, height: nil, depth: nil, weight: 0)
+
+ expect(summary_for([[unmeasured, 3]])).to be_empty
+ end
+
+ it 'is not empty once anything is measured' do
+ measured = create(:variant, width: 10, height: 10, depth: 10, dimensions_unit: 'cm')
+
+ expect(summary_for([[measured, 1]])).not_to be_empty
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/purchase/freight_spec.rb b/spree/core/spec/models/spree/purchase/freight_spec.rb
new file mode 100644
index 0000000000..bbaa98a36a
--- /dev/null
+++ b/spree/core/spec/models/spree/purchase/freight_spec.rb
@@ -0,0 +1,132 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Purchase::Freight do
+ let(:store) { @default_store }
+ let(:carton) { create(:carton_package_type, store: store, length: 40, width: 30, height: 25) }
+ let(:variant) { create(:variant, units_per_carton: 12, cartons_per_pallet: 40, carton_package_type: carton) }
+
+ # Same rule as an order: a cart reports what a selected freight rate froze,
+ # and nothing before one is selected. The forwarder quotes against what was
+ # quoted, not against a basket the buyer is still changing.
+ describe 'a cart' do
+ let(:cart) { create(:cart, store: store) }
+ let(:snapshot) do
+ Spree::FreightSummary.new(
+ lines: [Spree::FreightSummary::Line.new(variant_id: variant.prefixed_id, units: 24,
+ cartons: 2, pallets: 1, complete: true)]
+ ).as_json
+ end
+
+ def select_freight_rate(cart, snapshot)
+ fulfillment = create(:shipment, cart: cart, order: nil)
+ create(:delivery_rate, fulfillment: fulfillment, selected: true, unpriced: true, cost: 0,
+ metadata: { 'freight_summary' => snapshot })
+ end
+
+ it 'reads what the selected freight rate froze' do
+ create(:line_item, cart: cart, order: nil, variant: variant, quantity: 24)
+ select_freight_rate(cart, snapshot)
+
+ expect(cart.reload.freight_summary.total_cartons).to eq(2)
+ end
+
+ # Items with carton data are not a freight shipment until a freight rate
+ # says so — a retail basket of measured goods reports nothing.
+ it 'has none before a freight rate is selected' do
+ create(:line_item, cart: cart, order: nil, variant: variant, quantity: 24)
+
+ expect(cart.reload.freight_summary).to be_nil
+ end
+
+ it 'has none when nothing is in it' do
+ expect(cart.freight_summary).to be_nil
+ end
+
+ # Answering "nothing" is the common case — every retail cart — so it has
+ # to be remembered too, or each serializer call queries again.
+ it 'remembers that it has none rather than re-deriving it' do
+ cart.freight_summary
+
+ expect(cart).not_to receive(:build_freight_summary)
+ expect(cart.freight_summary).to be_nil
+ end
+
+ # Remembering must not outlive the cart's state: a rate selected after
+ # the first read has to show up.
+ it 'forgets what it remembered when the cart is reloaded' do
+ expect(cart.freight_summary).to be_nil
+
+ create(:line_item, cart: cart, order: nil, variant: variant, quantity: 24)
+ select_freight_rate(cart, snapshot)
+
+ expect(cart.reload.freight_summary.total_cartons).to eq(2)
+ end
+ end
+
+ describe 'an order' do
+ let(:order) { create(:order, store: store) }
+
+ before { create(:line_item, order: order, variant: variant, quantity: 24) }
+
+ it 'reads what the freight rate froze rather than the live catalog' do
+ fulfillment = create(:shipment, order: order)
+ snapshot = Spree::FreightSummary.new(
+ lines: [Spree::FreightSummary::Line.new(units: 24, cartons: 2, pallets: 1, complete: true)]
+ ).as_json
+ create(:delivery_rate, fulfillment: fulfillment, selected: true, unpriced: true,
+ metadata: { 'freight_summary' => snapshot })
+
+ # Repacking the product must not rewrite what already shipped.
+ variant.update!(units_per_carton: 4)
+
+ expect(order.reload.freight_summary.total_cartons).to eq(2)
+ end
+
+ # Two freight shipments are still one load to the forwarder.
+ it 'sums the frozen summaries across every fulfillment' do
+ 2.times do
+ fulfillment = create(:shipment, order: order)
+ snapshot = Spree::FreightSummary.new(
+ lines: [Spree::FreightSummary::Line.new(units: 12, cartons: 1, pallets: 1,
+ volume: BigDecimal('0.03'), complete: true)]
+ ).as_json
+ create(:delivery_rate, fulfillment: fulfillment, selected: true, unpriced: true,
+ metadata: { 'freight_summary' => snapshot })
+ end
+
+ summary = order.reload.freight_summary
+
+ expect(summary.total_cartons).to eq(2)
+ expect(summary.total_volume).to eq(BigDecimal('0.06'))
+ end
+
+ # One variant split across two consignments is still one variant: each
+ # part rounded its cartons up, so adding them would invent a pallet.
+ it 're-rounds a variant split across consignments rather than adding' do
+ [3, 9].each do |units|
+ fulfillment = create(:shipment, order: order)
+ snapshot = Spree::FreightSummary.new(
+ lines: [Spree::FreightSummary::Line.new(variant_id: 'variant_abc', units: units,
+ units_per_carton: 12, cartons_per_pallet: 40,
+ cartons: 1, pallets: 1, complete: true)]
+ ).as_json
+ create(:delivery_rate, fulfillment: fulfillment, selected: true, unpriced: true,
+ metadata: { 'freight_summary' => snapshot })
+ end
+
+ summary = order.reload.freight_summary
+
+ expect(summary.total_units).to eq(12)
+ expect(summary.total_cartons).to eq(1)
+ expect(summary.total_pallets).to eq(1)
+ end
+
+ # The sale already happened. Re-deriving it would mean a carton size
+ # corrected next month silently rewrites what shipped last month.
+ it 'reports nothing rather than re-deriving when no rate froze a summary' do
+ create(:shipment, order: order)
+
+ expect(order.reload.freight_summary).to be_nil
+ end
+ end
+end