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.

17.6 KB
Raw Blame

B2B Quantity Rules (MOQ, Order Multiples, Purchase Unit)

Status: In progress — design finalized 2026-08-30 (one-question-per-entity doctrine, decisions.md 2026-08-30); implementation started 2026-08-31 (backend + dashboard; storefront deferred) Target: Spree 6.0 Depends on: B2B Wholesale Shipping (6.0-b2b-wholesale-shipping.md — packing chain on variants), B2B Companies & Catalogs (6.0-b2b-companies-and-catalogs.md), Extendable Validations (6.0-extendable-validations.md), Service Workflows (6.0-service-workflows.md) Author: Damian + Claude Last updated: 2026-08-31

Summary

Wholesale products can't be purchased in arbitrary quantities. Two distinct rules govern how many units a buyer may order: a minimum order quantity (MOQ — the least a buyer may purchase) and an order multiple (the increment orders must land on, because the product is packed in multiples). MOQ 48 with multiple 24 means 48 / 72 / 96 / 120 are valid and 50 or 100 are not. On top of that, wholesale buyers think in cartons, not units — a merchant sells the SKU internally by unit but commercially by carton, so the storefront should offer "2 CTNS — 48 units / 3 CTNS — 72 units" rather than a 1-2-3 stepper. Finally, merchants often require a minimum for the whole B2B order (an amount, e.g. $500) independent of any single SKU.

This plan adds those rules as a purchasing layer over unchanged inventory: stock stays in units, Stock::Quantifier and availability are untouched, and the rules are enforced where quantities enter the cart — the Carts::AddItem / Carts::UpsertItems workflows that already own item validation. It builds directly on the packing chain: this plan adds units_per_carton (see the decision below) and the wholesale-shipping plan adds the rest around it, completing SKU → MOQ → Order Multiple → Carton → Pallet.

Key Decisions (do not deviate without discussion)

  • Commercial terms live on the Catalog (2026-08-30, one-question-per- entity doctrine — decisions.md): the Catalog is the buyer's commercial agreement (assortment + attached price list + terms), so both the contextual quantity tiers (retail 1/1, small business 24/12, wholesale 48/24, distributor 480/240 on the same SKU) and the cart-level order minimum are catalog data, resolved through the existing Catalog.for_context chain (nearest company node → customer groups → the channel's default catalog). The channel-level minimum falls out for free: the wholesale channel's default catalog carries the $500 minimum — no channel mechanism needed. Variant columns stay the base rule for buyers who resolve no catalog terms.
  • Catalog terms are typed tables per grain, never one generic catalog_rules table or an STI rule family (2026-08-30, review): quantity rules are (catalog, variant?) → integers on the add-to-cart hot path (indexed typed lookups, catalog-scale cardinality); minimums are (catalog, currency) → money checked at completion with DB-enforced per-currency uniqueness. One munged table is the polymorphic Adjustment mistake the typed-adjustments split un-made; an STI rule family is the wrong category — rules are matching predicates stored as low-cardinality preference blobs (unindexable for the hot path, no DB uniqueness), and giving catalogs a rules engine would reopen the two-mechanisms ambiguity the one-question-per-entity doctrine closed. A future term kind gets its own typed table under the same catalog Terms surface.
  • The catalog-wide default is a pair of columns on the catalog itself (2026-08-30, follow-up review — supersedes the same-day NULL-variant-row sketch): spree_catalogs gains minimum_order_quantity + order_multiple, and spree_catalog_quantity_rules is strictly the per-variant override (variant_id null: false, one plain unique index — no partial indexes, no MySQL fallback). Three-level symmetry, same column pair at each level: variant base → catalog default → catalog × variant override; the catalog default costs no extra query (resolved catalogs are request-memoized), and the dashboard edits it as ordinary catalog form fields.
  • Terms resolve per-field, nearest-agreement-wins (2026-08-30): the first catalog in resolution order that defines a field (a quantity row for the variant, a minimum for the currency) wins that field; catalogs that are silent on a field pass through. All-or-nothing resolution was rejected — a distributor catalog with no stated minimum must not silently waive the channel default's $500.
  • No ChannelRule family — superseded same day (2026-08-30): an earlier draft of this plan introduced an STI rule family on Channel for minimums and access gating. Dropped: with terms on the catalog, nothing purchase-shaped is left for it, and access gating (storefront_access, guest_checkout) stays as the existing Channel preferences — gating must bind before the buyer has an identity, and catalogs resolve from identity, so gating can never be catalog data. Order minimums are born per currency (one row per currency on the catalog, per the recorded no-FX constraint — never one amount plus a currency column).
  • Inventory is never restated. Quantities are stored, reserved, moved and counted in units everywhere; cartons and pallets are a purchasing and display vocabulary. No code below the cart layer may read these rules.
  • Enforcement lives in the item workflows. Carts::AddItem and Carts::UpsertItems gain a quantity-rules validation as a named step (core behavior, not a hook — hooks remain the host-app extension surface). Storefront violations render the standard validation error naming the nearest valid quantities; the admin order twin is unrestricted (staff can always key in what the customer actually negotiated).
  • The storefront rounds up, the server refuses. The quantity selector starts at the MOQ and steps by the multiple (or by cartons when the purchase unit is carton); the API never silently rounds a submitted quantity — an invalid quantity is a 422 with the valid neighbors in the message. Silent rounding on a wholesale order is a five-figure surprise.
  • Purchase unit is display vocabulary. purchase_unit ∈ unit | carton on the variant changes what the storefront and line-item serializers present ("2 CTNS — 48 units"); the stored line-item quantity remains units. Requires units_per_carton; validated together.
  • Cart-level minimum is enforced at completion, not add-to-cart — a buyer must be able to build the order below the threshold and see how far they are from it ("$180 to reach the $500 minimum"), so the check is a Carts::Complete validation plus a computed shortfall the cart serializer exposes.
  • units_per_carton lands with this plan, not with wholesale shipping (2026-08-31, implementation review): purchase_unit: 'carton' is meaningless without the divisor, and the wholesale-shipping plan is design only. This plan adds units_per_carton to spree_variants; the wholesale plan still owns the rest of the packing chain (carton_package_type_id, carton_weight, cartons_per_pallet) and must not re-add this column.
  • Completion refuses an out-of-rule line, it does not warn (2026-08-31): rules can change between add-to-cart and checkout, so Carts::Complete re-checks every line through Checkout::Requirements with completion: true — the same place out-of-stock and discontinued lines are refused — naming the nearest valid quantities. Staff-initiated carts skip both this and the order minimum, matching the po_number precedent (created_by_id present).
  • The order minimum is advisory before completion, blocking at it (2026-08-31): the shortfall rides Checkout::Requirements as an advisory requirement so the buyer sees "$180 to reach the $500 minimum" while they can still act on it, and becomes refusal only when completion is attempted.
  • Per-product terms live on the assortment row, not a parallel list (2026-08-31, design review): the first build put a per-variant override table in the catalog page's right column, which duplicated the products card sitting beside it and squeezed a two-input-per-row table into a sidebar. Terms are now inline cells on the assortment row — MOQ and multiple, blank meaning "uses the catalog default", which shows as the placeholder. Stating a term for a product that is not in the assortment adds it, and removing a product removes its terms: a rule has nothing to apply to without its product, and one left behind would come back into force unannounced if that product were ever re-added.
  • A product row writes every variant's rule (2026-08-31): the rows are per variant in the database but a merchant thinks "minimum 48 of this product", so a row's cells write the same pair to all of the product's variants. A product whose variants disagree reads mixed rather than claiming one of them; typing over it sets them all. Per-variant divergence stays reachable through the API and is not a dashboard surface.
  • Every catalog term stages behind the page's Save (2026-08-31): order minimums and per-product terms were writing on click inside a dirty-tracked form, so a merchant who edited terms and then hit Discard kept changes they thought they had thrown away. All of it now rides the form the way the assortment already did.
  • The storefront ships separately (2026-08-31): the Next.js selector, carton display and shortfall banner are a follow-up on the storefront repo. The Store API exposes everything they need (resolved rules on the variant, minimum + shortfall on the cart), so the two land independently.

Design Details

Variant rules

# spree_variants gains:
#   minimum_order_quantity  integer   # nil = 1
#   order_multiple          integer   # nil = 1
#   purchase_unit           string    # 'unit' (nil) | 'carton'

class Spree::Variant
  def valid_order_quantity?(quantity)
    quantity >= (minimum_order_quantity || 1) &&
      (quantity % (order_multiple || 1)).zero?
  end

  def nearest_valid_quantities(quantity)
    # the two neighbors used in the validation message and the stepper
  end
end

Validations on the variant: order_multiple must divide evenly into a declared units_per_carton when both are present (a multiple of 24 with 20-unit cartons is a data error the merchant should hear about at edit time, not discover in a customer complaint); purchase_unit: 'carton' requires units_per_carton.

The base columns bind every cart; the dual-audience SKU (retail 1/1, wholesale 48/24) is solved by catalog quantity rules (below).

Workflow enforcement

  • Carts::AddItem / Carts::UpsertItems: a validate_quantity_rules step checks the resulting line quantity (an add of 24 onto an existing 24 is 48 — valid), so increments compose. Rejections carry ActiveModel::Errors per the extendable-validations contract; on the storefront bulk path they ride the existing partial-success warnings channel.
  • Carts::Complete: validates every line once more (rules may have changed since the item was added) plus the cart-level minimum. Staff-created and admin-completed orders skip both (same created_by pattern as return eligibility).

Storefront quantity UX

  • The store variant serializer exposes the rules (minimum_order_quantity, order_multiple, purchase_unit, units_per_carton, cartons_per_pallet) so any storefront can build the right selector without extra calls.
  • Reference storefront: +/- stepper stepping by the multiple, starting at the MOQ; when purchase_unit is carton, the selector counts cartons and shows the unit equivalent ("3 CTNS — 72 units"); line items display both.
  • Cart page shows the shortfall banner when a cart-level minimum applies and is not yet met.

Catalog commercial terms

# spree_catalogs gains the catalog-wide default (2026-08-30 follow-up):
#   minimum_order_quantity  integer   # nil = no catalog-wide rule
#   order_multiple          integer
#
# spree_catalog_quantity_rules — strictly the per-variant overrides:
#   catalog_id  bigint  null: false
#   variant_id  bigint  null: false
#   minimum_order_quantity  integer
#   order_multiple          integer
# unique index on (catalog_id, variant_id)

# spree_catalog_order_minimums — the cart-level minimum:
#   catalog_id  bigint  null: false
#   currency    string  null: false
#   amount      decimal(10,2), null: false
# unique index on (catalog_id, currency)
  • Resolution — per-field, nearest-agreement-wins. For a variant's quantity rules: walk the cart's resolved catalogs in Catalog.for_context order; within each catalog the variant override row beats the catalog's own default columns; the first catalog defining the field wins; nothing anywhere → the variant base columns. Same pair of column names at all three levels. For the order minimum: the first resolved catalog with a row for the cart's currency; none → no minimum. A retail buyer resolves no catalogs and gets base behavior untouched.
  • The resolution readers live beside the existing catalog machinery (Catalog.for_context is already request-memoized via Spree::Current), exposed as Cart#quantity_rules_for(variant) and Cart#order_minimum / #below_order_minimum? / #order_minimum_shortfall — computed, never stored.
  • Carts::Complete validates the minimum for customer-initiated checkouts; staff-created orders skip it. Store cart serializer exposes the minimum, whether it is met, and the shortfall; the store variant serializer exposes the buyer's resolved quantity rules (base or catalog override) so storefronts render the right stepper without knowing the mechanism.
  • A terms-only catalog is legitimate: empty assortment (which the resolver already treats as "no visibility narrowing"), no price list, just terms rows — that is how a channel's default catalog carries a minimum without touching what anyone sees or pays.
  • Dashboard: the catalog page gains a Commercial terms card (per-currency minimums + a paginated per-product quantity-override table); channel gating settings are untouched.

Migration Path

  1. Schema — the three columns on spree_variants + spree_catalog_quantity_rules + spree_catalog_order_minimums.
  2. Variant model + validations, serializer exposure (store + admin), the three-write-paths permit for the new variant attributes (duties-plan constraint).
  3. Catalog terms — the two term models, per-field resolution readers on the cart, admin CRUD nested under /admin/catalogs/:id.
  4. Workflow steps — item workflows + completion checks (resolved quantity rules + order minimum).
  5. Dashboard — a "B2B ordering" section beside the Carton section on the variant sheet + bulk spreadsheet; catalog Commercial terms card.
  6. Storefront — selector, carton display, shortfall banner.

Nothing to migrate: all columns start empty and empty means today's behavior (MOQ 1, multiple 1, unit display).

Constraints on Current Work

  • Never read quantity rules below the cart layer — no stock, allocation, or fulfillment code may branch on MOQ/multiple/purchase-unit.
  • Never silently round a submitted quantity — refuse with the valid neighbors.
  • New item mutations keep routing through AddItem/UpsertItems (existing extendable-validations constraint) — that is what makes the enforcement complete.
  • Carton/pallet packing data is owned by 6.0-b2b-wholesale-shipping.md; this plan reads it, never redefines it — except units_per_carton, which this plan adds (2026-08-31). The wholesale plan must not re-add that column.
  • A new variant attribute must be permitted in three places or a write path silently drops it: the inline variants: [...] list on Admin::ProductsController, the nested Admin::Products::VariantsController, and Seller::ProductsController (duties-plan constraint).
  • Commercial terms are catalog data. No purchase-term settings on Spree::Channel (a surface's terms are its default catalog's) and no new term columns on variants beyond the base rules — a new kind of term starts as catalog rows resolved per-field through Catalog.for_context.
  • Access gating stays on Channel (storefront_access, guest_checkout) — never move it to catalogs; gating binds before identity exists.

Open Questions

  1. Storefront quantity UX (deferred 2026-08-31, not blocked) — the selector, carton display and shortfall banner are a follow-up on the spree/storefront repo. The Store API already exposes what they need.
  2. Carton-denominated minimums ("minimum 10 cartons per order") — deferred; the amount minimum covers the common case, and a carton-count minimum needs the freight summary at completion time anyway. (The catalog/price-list ownership question this plan previously carried was resolved 2026-08-30 by the one-question-per-entity doctrine — decisions.md.)

References

  • Merchant feedback, 2026-08 (MOQ + order multiple; carton as the commercial purchase unit; pallet quantities; per-catalog rule tiers; minimum B2B order value).
  • docs/plans/6.0-b2b-wholesale-shipping.md — the rest of the packing chain (carton_package_type_id, carton_weight, cartons_per_pallet, PackageType) around the units_per_carton this plan adds.
  • docs/plans/6.0-extendable-validations.md — UpsertItems contract, partial-success warnings, ActiveModel::Errors rejections.
  • docs/plans/6.0-b2b-companies-and-catalogs.md — catalogs, Products::ForContext, company on cart.