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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Add extendable validations plan
Damian Legawiec8df8634a4096
diff --git a/CLAUDE.md b/CLAUDE.mdindex 7acd340a8e..507dae688e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -36,6 +36,7 @@ Active plans (6.0 target, work pending):- `6.0-replace-taxons-with-categories.md` — Split Taxon into Category (hierarchy) + Collection (flat/rule-based). **Shipped to 6-0-dev (PR #14302):** the Category surface (5.5–5.6) plus the 6.0 core — `spree_taxons`→`spree_categories` table rename + inheritance flip (`Spree::Category < Spree.base_class`, `Spree::Taxon` alias kept), the full `Collection` stack (model + rules + DB/Meilisearch manual sort + API), the taxon→category/collection data migration, and de-ruling Category. Pending (all 6.1): channel-aware `CollectionRules::AvailableOn` (ships interim now, rides with channels) + dropping `spree_taxon_rules`/`Taxonomy`. No brand feature in 6.0 — brands are modeled as a Category/Collection; `brand_taxon`/`brand_name` removed with `Taxonomy`.- `6.0-delivery-method-rules.md` — `Spree::DeliveryMethodRule` STI on DeliveryMethod (design finalized 2026-07-29): ItemTotal/Weight rules first (Channel/Market/CustomerGroup later in lockstep with payment-method-rules), enforced solely in `Stock::Estimator`'s method filter so calculator- AND provider-priced methods obey eligibility; replaces the FlatRate-only bound preferences (one-release bridge + data task). **Phase 1 shipped** (rules + Estimator seam + admin nested CRUD/types discovery + dashboard Conditions card). **2026-08-06:** `ExcludedProductsRule` (products via `spree_delivery_method_rule_products` join, Saleor-style method-side exclusion) replaces the dropped `spree_products.excluded_delivery_method_ids` JSON column; rule-reference storage picks by cardinality — small reference sets stay `normalize_id_preference` arrays, catalog-scale (products) gets a join table.- `6.0-service-workflows.md` — Two-tier services doctrine (2026-07-30). **Tier 1 `app/services/`:** plain `ServiceModule` classes, hand-written `def call(cart:, ...)`, Ruby kwargs as the contract — the permanent default; no DSL, no new `run`-pipelines, no hand-rolled sagas. **Tier 2 `app/workflows/`:** `Spree::Workflow` — named steps inside a plain `def perform(order:, ...)` (the ActiveJob::Continuable shape; bare `super` turns parameters into readers). Vocabulary: `step`/`external_step` (+ `with:`, `on_flow_failure:`), `run_hooks` + class-level `hooks`, `failure`/`halt!`; plain `ApplicationRecord.transaction`/`with_lock`/`rescue`/`publish_event`; every step instrumented as `step.spree_workflow`. Money lives in `Carts::RecalculateTotals` (single totals seam; the completed-order branch is the post-placement resum — rows re-summed, never regenerated), statuses in `Orders::UpdateStatuses` (refreshes each fulfillment's state, then rolls up); Order/CartUpdater are 6.1-removed warning shells. Shared Cart/Order surface lives in `Spree::Purchase::*` concerns; completion side effects (newsletter, account creation, risk) run in the sync `OrderPlacedSubscriber` on order.placed. Reserved for flows needing hooks, compensation/external I/O, or replay — currently `Carts::Complete`, `Carts::AddItem`, `Carts::Recalculate`, `Carts::RecalculateTotals` (+ order twins) and `Orders::Cancel` (absorbed `Order#after_cancel`; gateway settlement is an external_step). A service graduates to the workflow tier when it earns a hook, never speculatively — but hooks on flows already in the tier ship deliberately on the 6.0 boundary (2026-08-02), since hook keys are public API and moving one later is breaking. **New models get no state machine** — plain `status` string + inclusion validation, transitions through workflows; gateway I/O never in a save callback. Three hook families, contracts settled 2026-08-02: **lifecycle** (past tense, read-only), **validate** (handler calls `workflow.reject!(message)` to veto), **context** (`set_*_context`/`get_provider_data` — handler returns a hash, `run_hooks` deep-merges all handlers and returns it; last writer wins on collision). Phase 3 **shipped (2026-08-02)**: `run_hooks` returns the merged hash and `Workflow#reject!` is public API; `validate`/context/lifecycle hooks live on AddItem, Complete, Recalculate, RecalculateTotals, Cancel and Resume; `Fulfillments::Create`, `Payments::Capture`/`Refund`, `Payments::HandleWebhook` and `Carts::Merge` moved to `app/workflows/` (seams `fulfillment_create_workflow`, `payment_capture_workflow`, `payment_refund_workflow`, `payments_handle_webhook_workflow`, `cart_merge_workflow`; legacy names readable one release). **Customer registration (2026-08-05):** `Customers::Create` (seam `customer_create_workflow`, hooks `customers.create.validate`/`after_create`) is the single storefront customer-creation flow — self-registration + checkout account box (optional `order:` adopts addresses and links the order); absorbs `Orders::CreateUserAccount` (deprecated shell); admin create stays plain CRUD; token issuance stays in controllers; core sends NO welcome email — signup email is host-app code on `user.created` or the `after_create` hook. Payment workflows own the transaction boundary and guards — money movement stays in the model, called from an `external_step`. No workflows for plain CRUD. Workflow Dependencies seams use `*_workflow` keys; legacy `*_service` names stay settable/readable with warnings until 6.1 but writes are stashed, never applied (old service classes aren't workflow-contract compatible). `Carts::Complete` battery must pass unmodified. **Durability = plain Rails:** long-running background work uses `ActiveJob::Continuable` directly (reference: `Spree::Imports::ProcessJob` — CSV spine with a row-number cursor; `CreateRowsJob`/`ProcessRowsJob` deprecated shells); workflows are synchronous request-cycle flows and are NOT jobs — Workflow-level durable execution ships only if the payout run proves the need.+- `6.0-extendable-validations.md` — Workflow `validate` hooks are THE validation extension surface; **no generic model-validation registry** (design finalized 2026-08-13 — decorators stay the documented additive path, relaxing core rules = store preferences/predicate overrides). Ships: `Carts::UpsertItems` graduated to a workflow absorbing every non-increment item mutation (bulk payloads, PATCH quantity, DELETE = quantity 0; per-item `validate` with `AddItem`-compatible readers, shared item-application steps, ONE recalculate per batch; **partial-success** — rejected items skip into a `warnings` array on 2xx, no whole-batch veto; `SetQuantity`/`RemoveLineItem` → deprecated shells), `Products::Create`/`Update`/`Destroy` workflows (all write paths route through: Admin API v3, CSV importer, seeds; no standalone variant workflow), **rejections carry `ActiveModel::Errors`** (`Workflow#errors` + argument-less `reject!` rendering via `render_validation_error`; `reject!(message)` bridges to `:base`), `Spree.hooks.validate!` wired into boot, Address polish (document `Spree.validators.addresses` + removal API, `require_company` store preference). Address and cart creation get NO workflow (plain CRUD); custom-field value validation deferred to its own plan (Shopify-style per-definition rules, new-writes-only; `required` stays advisory). **Constraints now:** new item mutations route through `AddItem`/`UpsertItems`, new product write paths call the `Products::*` workflows, no hardcoded error codes at hook-bearing `render_service_error` call sites, clients must check `warnings` on bulk-item 2xx responses.- `6.0-store-scoped-configuration.md` — Move eight commerce-behavior globals (`auto_capture` + `auto_capture_on_dispatch` → one `capture_method` string; `allow_checkout_on_gateway_error` dropped, not moved — nothing reads it; `track_inventory_levels`, `stock_reservations_enabled`, `track_price_history`, `show_products_without_price`, `address_requires_phone`, `disable_sku_validation`) from `Spree::Config` to `Spree::Store` preferences. Store preference is **authoritative — no runtime fallback** (a fallback chain is what made `default_stock_reservation_ttl_minutes` silently unreachable); upgrade carries values over via `spree:store_settings:backfill_from_config`; globals are deprecated shells until 6.1. Storeless readers (`Address`, the product availability scope) use `Spree::Current.store` with a default fallback. Seven dead settings (`products_per_page`, `storefront_*_path`, …) get shells then deletion. **Capture timing is one vocabulary (2026-08-13):** `Spree::CaptureMethod` = `checkout | on_dispatch | manual` — a Store preference, overridable by a nullable `capture_method` **column** on PaymentMethod (null = inherit; a column, not a preference, since the payment-method preferences blob is per-provider gateway credentials); read `resolved_capture_method`, write `capture_method`; dispatch capture is decided per payment so a `manual` method is never charged by a dispatch; `spree:migrate_capture_methods` carries `auto_capture` over. **Constraints now:** no new `Spree::Config` reads of the movers; no new code against `auto_capture`/`auto_capture_on_dispatch` (deprecated on both models); new behavior flags are born on Store, never global; jobs that validate addresses or query the catalog must set `Spree::Current.store`.- `6.0-store-scoped-custom-field-definitions.md` — Add `store_id` + persisted `filter_key` to `Spree::MetafieldDefinition` (today global and computed), making uniqueness `(store_id, resource_type, filter_key)` with a DB index. Deferred from the 5.6 custom-field search/sort/filter work (schema change, not patch-safe). **Until then:** `filter_key` is a computed method — no Ransack predicates or `where`/`order` against it; definitions are global; uniqueness rests on a `CONCAT` validation with no index behind it.diff --git a/docs/plans/6.0-extendable-validations.md b/docs/plans/6.0-extendable-validations.mdnew file mode 100644index 0000000000..fa6c9632d8--- /dev/null+++ b/docs/plans/6.0-extendable-validations.md@@ -0,0 +1,305 @@+# Extendable Validations++**Status:** Design Finalized+**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 attributes — 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. Product writes are real+ orchestration (nested variants, delivery-profile stamping, the two-step+ custom-fields write, publications), not the plain CRUD the services doctrine+ rejects wrapping. 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 a `warnings` array (`item_index`, `code`, `message`)+ alongside the cart. Chosen for storefront "restore my old cart" flows, where+ one discontinued variant must not block re-adding everything else.+ **Accepted trade-offs:** writes on a 2xx response are partial — clients must+ check `warnings`, and the SDKs and cart serializers grow a warnings contract;+ 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.++## 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):++```ruby+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, currency check+ each_item { run_hooks :validate } # cart/variant/quantity readers per item+ ApplicationRecord.transaction do+ step :apply_items # shared collaborators with AddItem:+ # 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. 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);+the remaining items proceed and the cart recalculates over what actually+applied. The workflow returns the cart plus the collected warnings, and the+Store API renders them as a top-level `warnings` array beside the cart+payload (SDK types updated to match).++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:++```ruby+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++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.++## 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`diff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex d00a526af0..f7b62ab5a6 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -112,6 +112,47 @@ Consequences: Admin API code must never assume `current_store` is the defaultstore, and store-touching cache keys must carry the store id by construction.Plan: `6.0-store-context-and-first-run-setup.md`.+## 2026-08-13: Validate hooks are the validation extension surface; no generic model-validation registry++New plan `6.0-extendable-validations.md`. The question was whether developers+customizing validations — the single most common core-model modification —+deserve a generic add/remove validation mechanism, or whether workflow+`validate` hooks plus the existing model-level knobs already are the answer.+Decision: the latter. Adding a rule via prepended decorator is already short+and Rails-native; removing one via registry would require repackaging every+core validation as a named unit, and no competitor ships anything comparable.+Relaxing a core rule stays on named store preferences+(`disable_sku_validation` pattern) or predicate overrides.++What ships instead is the work that makes the hook recommendation honest:++- **`Carts::UpsertItems` graduates to the workflow tier** and absorbs every+ non-increment item mutation (bulk payloads, PATCH quantity, DELETE item —+ quantity `0` removes). It fires `validate` per item with `AddItem`-compatible+ readers, shares the item-application steps with `AddItem` (whose per-item+ full recalculate is what made N-item adds slow — the batch recalculates+ once), and is **partial-success**: a per-item rejection skips the item into+ a `warnings` array (`item_index`, `code`, `message`) on a 2xx response+ rather than rolling back the batch. No whole-batch veto in 6.0.+ `SetQuantity`/`RemoveLineItem` become deprecated shells.+- **`Products::Create`/`Update`/`Destroy` become workflows** (real+ orchestration, not the plain CRUD the doctrine rejects) with all write paths+ routed through them — Admin API v3, CSV importer, seeds — so hooks always+ fire. Variants ride the product graph; no standalone variant workflow.+- **Rejections carry `ActiveModel::Errors`.** `Workflow#errors` ++ argument-less `reject!` render through `render_validation_error`, so+ extension rejections share the model-422 shape (field-scoped symbolic+ codes) instead of a flat message under a controller-hardcoded wrong code.+ `reject!(message)` bridges to `:base`.+- **Address and cart creation get no workflow** — plain CRUD, demand already+ served (store preferences, gating predicates, `Spree.validators.addresses`+ which finally gets docs + a removal API + a `require_company` preference;+ flow-level address policy belongs on `carts.complete.validate`).+- **Custom-field value validation deferred** to its own plan: Shopify-style+ per-definition length/range/regex/allowed-values, enforced in the+ `CustomField` model, gating new writes only. The 2026-08-06 "required stays+ advisory" constraint is untouched.+## 2026-08-12: The label leads, fulfilled follows (amends the Phase 7 fulfill flow)A warehouse prints the label, sticks it on the box, hands the box over — and