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.

26.8 KB
Raw Blame

B2B Wholesale Shipping (Cartons, Pallets, Containers)

Status: Implemented — design finalized 2026-08-30; phases 1–6 implemented 2026-08-31 (measurement helper, package types, carton chain, freight summary, volume/company rules, freight provider + unpriced rates, with the admin and store API surfaces); phases 8–9 implemented 2026-09-05 (dashboard, storefront). Phase 7 (deposits) is out of scope — see the decision below. Target: Spree 6.0 Depends on: Delivery Profiles (6.0-delivery-profiles.md), Delivery Method Rules (6.0-delivery-method-rules.md), Delivery Rate Provider (6.0-delivery-rate-provider.md), B2B Companies & Catalogs (6.0-b2b-companies-and-catalogs.md), Duties & Custom Fees (6.0-duties-and-custom-fees.md), Service Workflows (6.0-service-workflows.md) Author: Damian + Claude Last updated: 2026-09-07 (deposits are out of scope — how a buyer pays is its own subject with its own plan)

Summary

Wholesale orders don't ship like retail orders. A B2B purchase leaves the warehouse as cartons, a pallet, or a container — chosen by the total volume of the order — and for international freight the shipping price is usually quoted by a forwarder after the merchant reviews the order, not calculated at checkout. What the platform must do is different from parcel shipping: know how products pack into cartons, roll a cart up into logistics numbers (carton count, cubic meters, gross weight), classify the shipment into the right merchant-configured tier, and let checkout complete without a shipping price.

This plan adds that layer without touching retail shipping, so one catalog can serve both retail and wholesale buyers: a store-scoped Spree::PackageType model (boxes, cartons, pallets, containers — absorbing the four default_package_* store preferences), per-variant carton details (a reference to a carton-kind PackageType plus units_per_carton and packed gross weight), a freight summary rollup computed on the existing (currently unused) Stock::Package#volume chain, a DeliveryMethodRules::VolumeRule so shipment tiers are configuration on delivery methods rather than code, and unpriced delivery rates — a first-class "freight quoted after review" rate carrying the logistics summary instead of a price.

What this plan deliberately does not cover: how a wholesale buyer pays. Deposits, net terms and credit limits are one subject and belong in one plan of their own — see the decision below.

Key Decisions (do not deviate without discussion)

  • Spree::PackageType is the packaging vocabulary (2026-08-30): store-scoped rows, kind ∈ box | envelope | carton | pallet | container, geometry (length/width/height + dimensions_unit), max_weight. It replaces the four default_package_* store preferences — the store's default shipping box becomes the store's default PackageType row (one default per store), read through the existing single access point (Stock::Package#weight/#dimensions). The preferences are deleted outright, with no deprecation bridge (2026-08-31, interactive review — a recorded exception to the always-bridge convention): they were added in this same unreleased 6.0 cycle, so there is no released API to keep working, and a bridge writing through to a row would leave two spellings of the store's box for one release with nothing gained. The name is deliberately NOT Spree::Package: Spree::Stock::Package is the in-memory packing unit at the heart of the estimator, and a persisted sibling with the same name would be permanently confusing.

  • Carton details live on a PackageType reference, not loose columns (2026-08-30, interactive review): spree_variants gains carton_package_type_id + units_per_carton + carton_weight. Geometry belongs to the shared carton row (merchants reuse standard carton sizes; one edit fixes every product packed in that carton); packing facts that vary per product — how many units fit, what a packed carton weighs — stay on the variant. Accepted cost: the product editors need a carton picker with inline create, and CSV/spreadsheet paths resolve cartons by name.

  • Tier classification is a rule, not a calculator or a provider branch. DeliveryMethodRules::VolumeRule (min/max volume in CBM) drops in beside WeightRule/ItemTotalRule; each shipment type (carton / pallet / 20ft / 40ft) is an ordinary DeliveryMethod whose volume rule defines its range. Eligibility hooks only in the Estimator filter chain, per 6.0-delivery-method-rules.md.

  • No new delivery profile kind. The same product ships parcel to a consumer and carton to a wholesale buyer, and a product has exactly one profile — so freight methods live on the regular shipping profile, gated by buyer context (ChannelRule, and the new CompanyRule), not by product.

  • Unpriced rates are first-class (2026-08-30, interactive review): Estimate and DeliveryRate gain an unpriced boolean; the estimator skips markup for them and serializers/UIs render "quoted after review" copy instead of a price. A zero-cost rate rendering as "Free" is a merchant-facing lie, and 6.0 is the window to model this properly instead of blessing the placeholder-rate workaround.

  • Deposits are out of scope (2026-09-07, interactive review — superseding the 2026-08-30 "deposits are collected" decision). This plan is about how wholesale goods ship: how they pack, how a cart rolls up into the numbers a forwarder quotes against, which tier a shipment falls into, and how a rate says its price is still to come. How the buyer pays is a different subject.

    Deposits (part payment now) and net terms (pay later) are two halves of one arrangement — merchants commonly combine them, "40% deposit, balance Net 30" — so answering half of it inside a shipping plan produces a vocabulary with no way to set it and no home for the other half. In particular a delivery method must not carry a deposit_percentage: the arrangement is negotiated with a buyer, not attached to how the goods travel. Partial payments themselves are untouched — they predate this work and remain generally available.

    What this plan does leave is the extension point, so the plan that owns the subject has somewhere to attach. Purchase#amount_due_at_checkout answers the whole total through {Spree::Purchases::AmountDueAtCheckout}, replaceable through Spree::Dependencies; four decisions read it rather than total — checkout requirements, both completion guards, and dispatch. Those are the places that ask "has enough money arrived?", and they are what an arrangement collecting part of the total up front would otherwise have to patch one by one. Everything else — what a new payment or gateway session defaults to, and the capture loop — still reads total, because those are amounts rather than decisions and a caller passes an explicit figure.

    Deposits, net terms and credit limits belong together in a payment-terms plan of their own, which does not yet exist. Two OSS plans already defer to it (6.0-payment-method-rules.md, 6.0-6.1-b2b-payment-terms.md) and the Enterprise tier table records the boundary.

    DeliveryRateProvider::Freight keeps only the unpriced rate, which was always its real subject; the deposit readers were a second idea living in the same class.

  • An unset variant dimensions_unit follows the store's unit system (2026-08-31, interactive review): imperial reads as inches, metric as centimeters. No new store preference — unit_system already decides what the store's box dimensions mean, and a second settable value could contradict it. This mirrors weight_unit's fallback in shape, not in mechanism, because there is no default_dimensions_unit to mirror.

  • Volume math is unit-aware from day one. CBM derived from inch dimensions differs from centimeter math by a factor of ~16 — the raw-number shortcut WeightRule was allowed (6.0-delivery-method-rules.md, resolved question 1) is not available here. A small conversion helper normalizes dimensions to centimeters before multiplying.

  • The freight summary on a completed order is frozen, never re-derived. The summary the provider computes at estimate time is persisted in the selected DeliveryRate#metadata (jsonb, already exists); order-facing reads come from there, on carts and orders alike — a purchase with no selected freight rate reports no summary. Same doctrine as the duty snapshot in 6.0-duties-and-custom-fees.md — never re-derive logistics from the live catalog on an existing order.

  • The quoted freight charge is a Fee. After the merchant gets the forwarder's quote, the amount goes onto the order through the existing /admin/orders/:id/fees endpoint (kind freight) — no retroactive editing of the delivery rate, no new money path.

  • Lot numbers are not this plan. Recording which lot/pallet a unit came from is an inventory concern and lives in 6.0-inventory-operations.md (lot-level inventory added there 2026-08-30).

Design Details

Spree::PackageType

class Spree::PackageType < Spree.base_class
  include Spree::SingleStoreResource
  include Spree::Metadata

  KINDS = %w[box envelope carton pallet container].freeze

  belongs_to :store, class_name: 'Spree::Store'
  has_many :variants, class_name: 'Spree::Variant',
           foreign_key: :carton_package_type_id, dependent: :restrict_with_error

  validates :name, presence: true, uniqueness: { scope: spree_base_uniqueness_scope }
  validates :kind, inclusion: { in: KINDS }
  # length/width/height decimal(8,2), dimensions_unit, max_weight decimal(10,2),
  # weight_unit, default boolean

  def volume
    Spree::Measurement.cubic_meters(length, width, height, unit: dimensions_unit)
  end
end
  • One default per store (the shipping box), demoted Channel-style (conditional UPDATE, partial index) — the same pattern as CompanyAddress defaults. Stock::Package#weight (tare) and #dimensions read the default row instead of the four store preferences, so the EasyPost parcel path is unchanged in shape. The preferences themselves are removed outright — see the decision above; the upgrade task below is what carries their values over.
  • An upgrade task (spree:upgrade:package_types) creates the default row per store from the preference values before they are dropped, skipping stores still on the seeded zeros. It runs before the migration that removes the preference keys, and is what makes deleting them safe without a bridge.
  • carton rows are what variants reference (below). pallet/container rows are merchant vocabulary and reference data (and the natural anchor for future label/BOL work); nothing in the tier math depends on them — tiers are volume ranges on rules, so a merchant can configure tiers without ever defining a pallet row.

Cross-reference (2026-09-03, 6.0-shipping-labels-and-deliveries.md). A freight consignment's tracking — the forwarder's PRO or container number — is a Spree::Delivery row on the fulfillment, hand-entered with a free-text carrier and a pasted tracking_url, and delivered is staff-confirmed through the fulfillment's mark_delivered (no webhook ever arrives for a container). The model was named Delivery rather than Parcel precisely because this plan uses "parcel" as the antonym of freight. Freight paperwork — bill of lading, pallet placards, packing list — is never a Spree::ShippingLabel (that table holds carrier labels with a cost and a refund lifecycle); it goes to Spree::OrderDocument or the client-side prints in 6.1-b2b-order-documents.md. The "future label/BOL work" anchor above is recorded there as a deferred nullable package_type_id on spree_deliveries.

  • Admin API: /api/v3/admin/package_types CRUD under the settings scope; dashboard page under Settings → Shipping.

Cross-reference (2026-09-08, 6.0-seller-package-types.md). On a marketplace a package type has an optional seller owner: the marketplace's rows (nil seller_id) are a vocabulary every seller reads and may pack into, a seller's rows are theirs alone, and a package from a seller's warehouse is quoted with that seller's default box before falling back to the store's. Two consequences for this section: "one default per store" became one per owner, and the admin endpoint moved from the settings permission resource to a seller-grantable package_types resource. Stock::Package#default_package_type is the one place that resolves whose box a package gets.

Variant carton details

# spree_variants gains:
#   carton_package_type_id  bigint          # a PackageType with kind 'carton'
#   units_per_carton        integer
#   carton_weight           decimal(8,2)    # gross weight of one PACKED carton
#   cartons_per_pallet      integer         # optional third packing level

class Spree::Variant
  belongs_to :carton_package_type, class_name: 'Spree::PackageType', optional: true

  def carton_volume
    carton_package_type&.volume
  end

  def cartons_for(quantity)
    return nil if units_per_carton.blank? || units_per_carton.zero?

    (quantity / units_per_carton.to_f).ceil
  end

  def units_per_pallet
    return nil if units_per_carton.blank? || cartons_per_pallet.blank?

    units_per_carton * cartons_per_pallet
  end
end

Geometry comes from the shared carton row; units_per_carton, carton_weight and cartons_per_pallet are the per-product packing facts. Together they form the packing chain Unit → Carton → Pallet → CBM / Weight: the freight summary reports pallet counts wherever cartons_per_pallet is present, and the same data feeds the quantity-rules plan (6.0-b2b-quantity-rules.md) — a buyer ordering 5 pallets is ordering 200 cartons is ordering 4,800 units, and Spree knows all three numbers from one place. Pallet geometry stays on pallet-kind PackageType rows; the variant only records how it stacks. A validation refuses a reference to a non-carton kind, and cross-store references must be impossible by construction (the association is resolved through current_store in every controller, per the scope-fetching rule).

Editing: the variant sheet and the bulk spreadsheet both get a Carton section — a carton picker (with inline "new carton size" create, since merchants discover carton sizes while cataloguing) plus the two numeric fields. CSV import/export and the spreadsheet resolve the carton by PackageType#name within the store. The three new variant attributes must be permitted in all three variant write paths (6.0-duties-and-custom-fees.md constraint: the nested variants controller, the inline variants: [...] list on the products controller, and the permitted-attribute declaration).

Spree::Measurement is a tiny stateless conversion module (in/ft/mm/ cm → cm for dimensions, g/kg/lb/oz → kg for weight) — the one genuinely new primitive this plan needs. Two module functions with unit tables, not a value-object zoo.

Freight summary

# Value object (ActiveModel::Model + Attributes, per conventions — no Struct)
Spree::FreightSummary.build(contents, store:)
# => total_units, total_cartons, total_pallets (nil unless every carton-bearing
#    line declares cartons_per_pallet), total_volume (CBM), total_weight (kg),
#    complete? (false when any line lacks carton data), lines[]

Per line: cartons = variant.cartons_for(quantity), volume = cartons × carton_volume, weight = cartons × carton_weight. Lines without carton data fall back to unit volume/weight × quantity and mark the summary incomplete — the numbers stay useful, and the flag tells the merchant why they're partial.

Stock::Package#volume is redefined through the same unit-aware math (its current raw contents.sum(&:volume) has no consumers, so this is safe); the deliberate "item dimensions are not summed" stance of Package#dimensions stays untouched — freight aggregates carton volume, which does stack.

VolumeRule and CompanyRule

class Spree::DeliveryMethodRules::VolumeRule < Spree::DeliveryMethodRule
  preference :minimum_volume, :decimal, default: nil, nullable: true  # CBM
  preference :maximum_volume, :decimal, default: nil, nullable: true

  def eligible?(package)
    volume = package.freight_summary.total_volume
    return false if preferred_minimum_volume.present? && volume < preferred_minimum_volume
    return false if preferred_maximum_volume.present? && volume > preferred_maximum_volume
    true
  end
end

Same shape and fail-open convention as WeightRule, but the compared value is always CBM (unit-aware), never a raw column sum. Registered in the engine + i18n + dashboard Conditions card like the existing rules.

DeliveryMethodRules::CompanyRule gates by buyer context: preference :company_orders_only, :boolean, default: true. On, a freight method is hidden from retail carts; off, a parcel method is hidden from B2B carts where a merchant wants a hard split. It reads package.owner.b2b? (company resolution already lives on the cart).

A boolean, not a required | absent string (2026-09-05, interactive review): the rule has exactly two sides, and a string spelling them made the dashboard render a free-text box for what is a switch — a preference type carries its own UI, so the type has to be the honest one. The third state the string allowed (unset = unconstrained) is not lost but relocated: having no company rule is what leaves a method open to both, which is where that meaning belonged. Per-company narrowing stays Enterprise territory — OSS gates on presence only, consistent with the no-company-roles stance.

The wholesale tier table is then pure configuration: four delivery methods ("Carton shipping", "Pallet", "20ft container", "40ft container"), each with a VolumeRule range + CompanyRule(required), on the freight rate provider.

Unpriced rates and the freight rate provider

  • Spree::DeliveryRateProvider::Freight ships in core beside Internal. estimates(package) returns one Estimate with unpriced: true, cost: 0, the method's name, and metadata = the freight summary.
  • Estimate gains unpriced (boolean attribute); spree_delivery_rates gains an unpriced boolean column (default false). The estimator skips markup for unpriced estimates and keeps its cheapest-first sort (cost is 0, so unpriced rates naturally sort first among freight-only sets; mixed priced/unpriced offerings are a merchant configuration choice).
  • Store + admin rate serializers expose unpriced; the storefront and dashboard render "Quoted after review" (i18n) instead of a price. Order totals charge zero shipping at placement.
  • Completion snapshot: the winning rate row already persists metadata, so the frozen summary rides for free.

Where the money happens, end to end

  1. Buyer completes checkout on an unpriced freight rate. The goods are paid for; the freight is not, because nobody has quoted it yet.
  2. Merchant reviews the order — the dashboard order page shows a Logistics card (shipment type, units, cartons, CBM, gross weight) read from the rate metadata.
  3. Merchant gets the forwarder's quote and adds it as a Fee (kind freight) via /admin/orders/:id/fees; totals recompute through the existing typed-adjustments path, and the order owes the difference.
  4. Merchant collects that balance through the payment surfaces that already exist; Orders::UpdateStatuses rolls the order to paid.

How a buyer might instead pay a deposit up front, or take the goods on net terms, is the payment-terms plan's subject, not this one's.

API surface

  • Admin: package_types CRUD; variant carton attributes on the existing product/variant writes; delivery method rules types discovery picks up the two new rules automatically; order serializer exposes outstanding_balance (if not already) + the partial payment status.
  • Store: cart and order serializers gain a freight_summary object (nullable — null when no line carries carton data); summaries are computed read from the selected freight rate's metadata on carts and orders alike, so a parcel shipment carries none. The delivery rate serializer gains unpriced.

Migration Path

  1. Unit groundwork — Spree::Measurement; Variant#dimensions_unit store fallback (mirror of the existing weight_unit fallback).
  2. Schema — spree_package_types; carton_package_type_id + carton_weight + cartons_per_pallet on spree_variants (around the units_per_carton 6.0-b2b-quantity-rules.md already added); unpriced on spree_delivery_rates.
  3. PackageType — model, upgrade task (spree:upgrade:package_types) creating default rows from the store preferences, Stock::Package reading through the default row, then the preferences removed outright (no bridge).
  4. Rollups — FreightSummary, unit-aware Stock::Package#volume.
  5. Rules — VolumeRule + CompanyRule (+ engine registration, i18n, dashboard Conditions card).
  6. Freight provider + unpriced rates — provider, estimator handling, serializers.
  7. Deposits — amount_due_at_checkout, the Carts::Complete payment-sufficiency change, partially_paid in the status rollup, admin balance surfaces. Cut 2026-09-07 and moved to a payment-terms plan of its own; nothing from this phase ships here.
  8. Dashboard — package types settings page, variant carton section (sheet + spreadsheet + CSV), order Logistics card, "quoted after review" rendering. The Settings → Store card that edited the four default_package_* preferences was removed with them in phase 3, so between phase 3 and this phase the store's shipping box is API-only. That gap is the cost of dropping the preferences without a bridge; the settings page below is what closes it, and it should not ship far behind.
  9. Storefront — freight summary on cart/checkout, unpriced rate copy.

No data migration beyond the package-type backfill: carton fields start empty, and nothing changes for stores that never fill them.

Constraints on Current Work

  • How the buyer pays is not this plan's subject. Deposits, net terms and credit limits belong together in a payment-terms plan of their own (2026-09-07). A delivery method must not grow a deposit_percentage, and freight must not become a second place payment arrangements are configured — that coupling was built here once and removed for exactly this reason.
  • Never compute volume by multiplying raw dimension columns. All volume/CBM math goes through the unit-aware helper; the raw-number shortcut recorded for WeightRule does not extend to volume.
  • No new readers of the default_package_* store preferences. Package dimensions are read through Stock::Package#weight/#dimensions (today) and the default PackageType row (after phase 3).
  • Don't build "freight quoted later" as a zero-cost priced rate. The unpriced flag is the mechanism; a $0 rate renders as free shipping.
  • units_per_carton is already on spree_variants — added by 6.0-b2b-quantity-rules.md (2026-08-31), which needs the divisor for its carton purchase unit. This plan adds the rest of the chain (carton_package_type_id, carton_weight, cartons_per_pallet) around it and must not re-declare it.
  • Don't add carton dimension columns to spree_variants. Carton geometry lives on the referenced PackageType; only packing facts (units_per_carton, carton_weight) sit on the variant.
  • Post-placement freight charges are Fees, never delivery-rate edits or ad-hoc money columns.
  • A new variant attribute must be permitted in all three write paths or it silently drops on the dashboard's product Save (duties-plan lesson).
  • Tier/eligibility logic hooks only in the Estimator filter chain via rules (existing 6.0-delivery-method-rules.md constraint).

Known Gaps (found in review, deliberately not fixed here)

  • EasyPost's parcel weight now converts from the store's weight_unit, not its unit_system. The old reading multiplied a metric store's weight as if it were grams; the new one asks the preference that actually says what weights mean. It is the correct reading and it makes the tare (converted the same way) add up, but a live store on unit_system: metric that never set weight_unit moves from grams to the lb default — a large rescale of its quotes. Needs a release note, not a code change: such a store was already mixing units, since its variant weights were read in the default unit everywhere else.

  • freight_summary is an unstructured object in the OpenAPI specs. It serializes with a known shape, so a $ref'd FreightSummary schema would let clients validate it. Not done here: the specs are generated from the rswag integration specs, the property type comes from Typelizer, and all sixty-odd unstructured attributes across the v3 serializers (metadata included) work the same way. Giving this one a shared schema means changing how the generator derives types across all three API branches — shared documentation infrastructure, not this feature.

  • Content weights are still summed across units. Package#weight now converts the packaging tare into the store's weight unit, but Stock::ContentItem#weight sums variant.weight * quantity raw, and Variant#weight_unit falls back per variant — so a variant stored in grams and one in pounds are added together unconverted. This predates the plan and affects WeightRule, the weight splitter's threshold and the EasyPost parcel weight; Spree::Measurement is now in place to fix it, but the change touches every weight consumer and belongs in its own pass.

Open Questions

None. Both were resolved on 2026-09-05 — see Key Decisions.

References

  • Merchant feedback, 2026-08 (wholesale carton/pallet/container shipping with freight quoted after review; logistics summary as the checkout output).
  • docs/plans/6.0-delivery-method-rules.md — rules pattern + Estimator-only eligibility constraint.
  • docs/plans/6.0-delivery-rate-provider.md — provider contract the freight provider implements.
  • docs/plans/6.0-duties-and-custom-fees.md — Fee substrate + snapshot doctrine + the three-places variant attribute constraint.
  • docs/plans/6.0-b2b-companies-and-catalogs.md — company on cart, #b2b? / resolved_company.
  • docs/plans/6.0-service-workflows.md — the Carts::Complete pipeline.
  • docs/plans/6.0-b2b-quantity-rules.md — MOQ / order multiples / purchase unit built on the same packing chain.
  • docs/plans/6.0-inventory-operations.md — lot-level inventory (out of scope here).
  • Existing volume chain: spree/core/app/models/spree/variant.rb (#volume), .../stock/content_item.rb, .../stock/package.rb.
  • Store default package preferences: spree/core/app/models/spree/store.rb.