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.

Mark extendable validations plan complete

Damian Legawiec332d937e4d7c
diff --git a/CLAUDE.md b/CLAUDE.md
index 507dae688e..7c2b829ff2 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -36,7 +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-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 on the storefront** — rejected items skip onto the cart's existing `warnings` array on 2xx, while the **order twin fails the whole batch**; 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 storefront bulk-item 2xx responses. **Shipped 2026-08-13** (all four phases).
- `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.md
index fa6c9632d8..1f9f9d95ed 100644
--- a/docs/plans/6.0-extendable-validations.md
+++ b/docs/plans/6.0-extendable-validations.md
@@ -1,6 +1,6 @@
# Extendable Validations
-**Status:** Design Finalized
+**Status:** Complete
**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
@@ -96,11 +96,17 @@ value validation is a deferred, separate topic.
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;
+ 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
@@ -245,24 +251,45 @@ after-eager-load hook so a bad registration fails boot in real apps.
## Migration Path
-1. **Phase 1 — errors contract + boot check.** `Workflow#errors`, argument-less
+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
+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,
+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,
+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 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
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index f7b62ab5a6..83e39b61b6 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -131,9 +131,11 @@ What ships instead is the work that makes the hook recommendation honest:
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.
+ once), and is **partial-success on the storefront**: a per-item rejection
+ skips the item onto the cart's existing `warnings` array on a 2xx response
+ rather than rolling back the batch. The **order-side twin fails the whole
+ batch** — a merchant's struck-out row silently not applying is worse than a
+ failed request. 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