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.

19.6 KB
Raw Blame

Extendable Validations

Status: Implemented Target: Spree 6.0 Depends on: 6.0-service-workflows.md (hook contracts), 6.0-cart-order-split.md (Cart/Order twins) Author: Damian Legawiec + Claude Last updated: 2026-08-13

Summary

Adding — and sometimes relaxing — validations is one of the most common ways developers extend Spree. Today that story is fragmented: workflow validate hooks cover most flows but the bulk item paths bypass them entirely, product writes have no veto point at all, a hook rejection produces a flat message with a wrong hardcoded error code, and model-level customization is spread across four unrelated mechanisms (an undocumented validator registry on Address, a password-validator swap, bespoke store preferences, and decorators). This plan makes workflow validate hooks the single recommended way to extend validation of Spree flows, closes the gaps that undermine that recommendation, and deliberately does not build a generic model-validation registry. Model-shape rules stay on models: store preferences and the (newly documented) Address validator registry for core knobs, additive decorators as the last resort, and custom fields for new merchant-managed attributes (an extension's own data goes in its own columns, per 6.0-6.1-custom-fields-roadmap.md) — whose own value validation is a deferred, separate topic.

Key Decisions (do not deviate without discussion)

  • No generic add/remove validation registry across models. For adding a validation, a prepended decorator (base.validates ...) is already short, fully expressive, and Rails-native — a registry would be a second syntax for the same thing. For removing one, a registry only works if every core validation is repackaged as a named unit, which is heavy machinery for a rare case with no competitor precedent (Shopify, Medusa, Saleor, Vendure ship nothing comparable). Relaxing a core rule is served by named store preferences (disable_sku_validation pattern) added on demand, or by overriding the gating predicate (require_phone? pattern) in a decorator.
  • Workflow validate hooks are the recommended extension surface for flow-level rules — purchase limits, B2B eligibility, region policy, anything that vetoes an action rather than shapes a record. Decorators remain documented as the supported way to add model-shape rules, with an explicit "last resort" framing.
  • Carts::UpsertItems graduates to the workflow tier and becomes the single gate for every item mutation that is not a plain add-increment: create-with-items, bulk item updates, quantity sets. It fires validate once per item with the same readers Carts::AddItem exposes (cart, variant, quantity), so one handler class registers on both carts.add_item.validate and carts.upsert_items.validate with an identical body. Item application steps are shared with AddItem via collaborators so tax-estimate, stock reservation, and recalculation behavior cannot drift again (today UpsertItems silently skips the tax estimate and reservations and runs a totals-only recalculation). The batch recalculates once at the end — that is the entire performance win; a literal upsert_all is rejected because it bypasses ActiveRecord validations, normalizations, and line-item price capture on the money path.
  • Products::Create, Products::Update, and Products::Destroy become workflows with validate + lifecycle hooks. They are deliberately thin — assigning nested data (variants, media, prices, custom fields, categories) stays on the model's own setters and after_create/after_save callbacks, where every caller gets it whether or not a workflow is involved. The workflow exists for the veto point, and its placement is the payoff: those setters stash their input and replay it once the product exists, so validate runs before the insert and a rejection leaves no half-built product behind. Every server-side write path routes through them: Admin API v3, the CSV importer, seeds and sample data. Hooks always fire — no bulk bypass flag; an installation with no handlers pays nothing. Variants ride the product graph (99% of variant writes are nested under the product); there is no standalone variant workflow. Destroy as a workflow exists precisely so cleanup and side-effect work can attach to it.
  • Address gets no workflow. Address writes are plain CRUD from many paths, and the demand is field-shaped and regional — already served by store preferences, the gating predicates, and Spree.validators.addresses. Flow-level address policy (verification, PO-box bans) belongs on carts.complete.validate and the checkout requirements registry, which already exist. The work here is polish: document the registry, give it a removal API, add the missing require_company store preference.
  • Cart creation itself gets no workflow. Creating an empty cart is not something merchants need to veto; the meaningful gates are item mutation and completion, both covered. This keeps faith with the "no workflows for plain CRUD" decision (decisions.md 2026-08-02).
  • Rejections carry ActiveModel::Errors, not a flat string (2026-08-13). Every workflow instance exposes an errors object; validate handlers add to it (workflow.errors.add(:quantity, :purchase_limit_exceeded, message: ...)) and reject! renders through the same render_validation_error path model 422s use — per-field details with symbolic codes, one error vocabulary for clients regardless of whether a model or an extension rejected the write. Chosen over reject-keyword-arguments because it reuses the existing error pipeline instead of inventing a parallel rejection object. Accepted trade-off: the handler contract changes; reject!(message) stays as a bridge that maps the string onto errors.add(:base, ...), so existing handlers keep working but render as base errors until migrated. Controllers stop hardcoding wrong codes (today a purchase-limit rejection on add-item renders as insufficient_stock).
  • Item mutations unify under UpsertItems (2026-08-13). PATCH quantity and DELETE item both route through the workflow (quantity 0 = remove), so every non-increment mutation shares one hook pair and rules like minimum-order quantity or "can't remove a bundled gift item" get a veto. Carts::SetQuantity and Carts::RemoveLineItem become deprecated shells; their Dependencies keys (cart_set_item_quantity_service, cart_remove_line_item_service) stay readable with warnings until 6.1, per the standing deprecation-bridge convention.
  • Batch upserts are partial-success with warnings (2026-08-13). A per-item rejection skips that item and records a warning; valid items persist and the response is 2xx with the dropped items on the cart's existing warnings array (code, message, variant_id, item_index) — the channel the out-of-stock sweep already publishes to, so clients read one vocabulary rather than a second top-level key. Chosen for storefront "restore my old cart" flows, where one discontinued variant must not block re-adding everything else. This is the storefront contract only: the order-side twin fails the whole batch (partial_success? is false), because a merchant's struck-out or repriced row silently not applying is worse than a failed request. Accepted trade-offs: storefront writes on a 2xx response are partial — clients must check warnings; and there is deliberately no whole-batch veto in 6.0 — inside upsert_items.validate a rejection is always per-item (a handler that wants to block everything rejects every item; a batch-level veto ships later only if demanded). Single-item flows (AddItem, complete, products.*) are unaffected: a rejection there is still a hard 422.
  • Custom-field value validation is deferred (bigger topic, own plan). The direction to carry forward: Shopify-style per-definition validations (length, range, regex, allowed values) enforced in the CustomField model where all three write paths converge, gating new writes only. The standing "required stays advisory — never a model validation" constraint (decisions.md 2026-08-06) is untouched. Amended 2026-10-06: designed in 6.0-6.1-custom-fields-roadmap.md (Part 5) for 6.1: rules in a validations JSON column (required, min/max, choices for the choice type), no regex, and required enforced only where a shopper writes the field (amended 2026-11-02): at checkout as a checkout requirement in Checkout::DefaultRequirements, not a carts.complete.validate hook, so the cart's requirements and the completion gate agree; and at customer registration and account update as a 422 from the customer write flow, before the account is created.

Design Details

Hook surface after this plan

Key Hooks Status
carts.add_item validate, after_item_added shipped
carts.upsert_items validate (per item), after_items_upserted new
products.create validate, after_create new
products.update validate, after_update new
products.destroy validate, after_destroy new

The Orders::UpsertItems twin subclasses Carts::UpsertItems exactly like the existing Orders::AddItem twin, so orders.upsert_items.* keys exist for free under the inheritance rule in Spree::Workflow.inherited (draft-order edits fire the order keys).

Carts::UpsertItems workflow

Shape (final structure to be settled in implementation):

class Spree::Carts::UpsertItems < Spree::Workflow
  hooks :validate, :after_items_upserted

  attr_reader :item   # current item during per-item hook dispatch
  # item responds to: variant, quantity, metadata, line_item (nil until applied)

  def perform(cart:, items:)
    super
    step :resolve_items          # one query for all variants
    ApplicationRecord.transaction do
      step :apply_items          # per item: run_hooks :validate, then apply
                                 # (find/build line item, save, price capture,
                                 # tax estimate for new items)
      step :handle_stock_reservations if cart.in_checkout?
      step :recalculate, with: -> { Spree.cart_recalculate_workflow }
      run_hooks :after_items_upserted
    end
    success(cart.reload)
  end
end

During per-item validate dispatch, the workflow exposes the current item's variant and quantity under the same reader names AddItem uses, plus the full items array for cross-item rules ("max 20 units per order"). A handler written for carts.add_item.validate therefore works unchanged when also registered on carts.upsert_items.validate.

Semantics: upsert sets quantity (unlike AddItem, which increments), and quantity 0 removes the line item. Validation is per item, not a batch pre-pass: each item is validated immediately before it is applied, so an item's handler runs after earlier items in the same batch have already been written inside the transaction. A handler must therefore judge the item it is given rather than assume nothing has happened yet.

Per-item rejection semantics differ from every other workflow: the batch loop catches a reject! raised during an item's validate dispatch, skips that item, and records a warning (item_index, code, message — derived from the item's errors object). A line that fails to save (stock availability, say) is treated the same way rather than aborting the batch. The remaining items proceed and the cart recalculates over what actually applied. Warnings are written to the cart's own warnings attribute, so clients read them at cart.warnings in the ordinary cart payload — not as a separate top-level key.

Call sites routed through it: Carts::Create / Carts::Update (items: payloads), the Store API bulk item endpoints, PATCH quantity, and DELETE item.

Products::* workflows

Products::Create and Products::Update wrap the existing save path: assign attributes (nested variants included), run_hooks :validate with the dirty record readable by handlers (workflow.product, inspecting product.changes), then save inside a transaction and fire the lifecycle hook. Products::Destroy wraps the paranoia soft-delete the same way so host cleanup attaches to after_destroy.

Wiring:

  • Admin API v3 products controller create/update/destroy call the workflows through Spree.product_create_workflow / product_update_workflow / product_destroy_workflow dependency keys.
  • The CSV importer's product row processing calls the same workflows. Handlers therefore fire per imported row; this is deliberate (one gate) and the docs must state that validate handlers need to be fast and free of per-call external I/O.
  • Seeds and sample data go through the workflows too, so a host validate handler that would reject sample data surfaces loudly rather than diverging.

Model validations on Product/Variant stay exactly where they are — the workflow hook is for host policy, not a replacement for data-integrity rules.

Rejection error contract

Spree::Workflow gains an errors reader (an ActiveModel::Errors bound to the workflow instance). Handlers add symbolic, optionally field-scoped errors and reject:

class MyStore::CheckPurchaseLimit
  def call(workflow)
    return if workflow.quantity <= 10

    workflow.errors.add(:quantity, :purchase_limit_exceeded,
                        message: 'You can order at most 10 of this item.')
    workflow.reject!
  end
end

reject! with no arguments fails the flow carrying workflow.errors; reject!(message) remains as a bridge mapping the string to :base. render_service_error already branches on ActiveModel::Errors and renders per-field details through render_validation_error, so extension rejections become indistinguishable in shape from model validation 422s — controllers stop choosing error codes for rejections they didn't make. In UpsertItems, each item's errors convert to warning entries instead of a 422 (see above).

Additionally: Spree.hooks.validate! (the boot check that fails on typo'd hook keys) is currently exercised only in specs — wire it into the engine's after-eager-load hook so a bad registration fails boot in real apps.

Address polish

  • Document Spree.validators.addresses (registry exists, has no docs) and add a removal API symmetrical with Spree.hooks.unregister.
  • Add the require_company store preference behind the existing require_company? predicate (today it hard-returns false with no knob).
  • Write the missing "customizing validations" docs section: additive decorators supported; relaxing a core rule = use the preference where one exists or override the gating predicate; clear_validators! explicitly discouraged.
  • Replace docs/developer/customization/checkout.mdx, which still documents the deleted state-machine checkout DSL and is linked from the v6 nav.

Migration Path

All four phases shipped 2026-08-13.

  1. Phase 1 — errors contract + boot check. ✅ Workflow#errors, argument-less reject!, the reject!(message) → :base bridge, stop hardcoding wrong codes at hook-bearing call sites, wire Spree.hooks.validate! into boot.
  2. Phase 2 — Carts::UpsertItems graduation. ✅ Workflow + shared item application with AddItem, per-item validate with skip-and-warn semantics, quantity-0 removal; route create-with-items, bulk items, PATCH quantity and DELETE item through it; warnings array in the Store API cart responses + SDK types; SetQuantity/RemoveLineItem become deprecated shells; Orders::UpsertItems twin rides along. Carts::Complete battery must pass unmodified.
  3. Phase 3 — Products::* workflows. ✅ Create/Update/Destroy workflows, Admin API wiring, CSV importer + seeds routing, dependency keys.
  4. Phase 4 — Address polish + docs. ✅ Registry docs + removal API, require_company preference, validations customization guide, checkout doc replacement.

No schema changes anywhere in this plan.

Notes from implementation

  • The product workflows are thin by design, not by omission. An earlier draft of this plan justified them as "creation is already orchestration"; that was wrong — Spree::Product already implements variants=, media=, prices=, custom_fields= and friends as deferring setters replayed in callbacks, and that is where they belong. The workflow's contribution is the hook, sited before the insert.

  • The order-side twin fails the whole batch rather than warning (partial_success? returns false): a merchant's struck-out or repriced row silently not applying is worse than a failed request. Storefront carts keep partial-success. Decided 2026-08-13 during Phase 2.

  • Skipped items ride the cart's existing warnings array rather than a new top-level key — the out-of-stock sweep already publishes there in the same shape, so clients read one vocabulary.

  • Removals resolve their variant through the cart's own line items, not store.variants: a product since deleted or unpublished has left that scope, and refusing to remove it would strand the customer with a line they cannot delete.

  • Workflow authoring trap found and documented: inside #perform a parameter name is a local variable and shadows the generated reader, so a step assigning @product is invisible to success(product). Name derived state differently from the parameter that seeded it (Products::Create takes record: and exposes product).

Constraints on Current Work

  • New code that mutates cart line items must route through Carts::AddItem or Carts::UpsertItems — never write line items directly from a service or controller, and never call the Tier-1 UpsertItems service in new code once the workflow lands.
  • New product write paths (any importer, sync job, or API surface) call the Products::* workflows, not product.save directly.
  • Don't hardcode HTTP error codes at render_service_error call sites for hook-bearing workflows; let the rejection's errors object carry its codes once Phase 1 lands.
  • Clients (SDKs, dashboard, storefront examples) must treat the bulk-item endpoints as partial-success: check the warnings array on 2xx responses, never assume every requested item was written.
  • New validate handlers should add symbolic errors to workflow.errors and call argument-less reject!; reject!(message) is legacy style for new code.
  • No new bespoke validation toggles as globals — the disable_sku_validation pattern continues on Spree::Store preferences (6.0-store-scoped-configuration.md).
  • Custom-field value validation work must not start from controllers — when it happens, it lands in the CustomField model per this plan's deferred note.

Open Questions

None remaining — all three design questions (rejection error contract, item mutation unification, batch failure semantics) were resolved 2026-08-13 and moved to Key Decisions. Two topics are deliberately out of scope rather than open: custom-field value validation (own future plan; direction noted in Key Decisions) and a batch-level veto for upsert_items.validate (ships only if demanded).

References

  • docs/plans/6.0-service-workflows.md — hook families, tier doctrine
  • docs/plans/decisions.md 2026-08-02 (hook boundary, no workflows for plain CRUD), 2026-08-06 (custom-field required stays advisory)
  • spree/core/lib/spree/workflow.rb, spree/core/lib/spree/hooks.rb
  • spree/core/app/services/spree/carts/upsert_items.rb (Tier-1 predecessor)
  • docs/developer/customization/workflows.mdx, decorators.mdx