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.

Make address validation rules adjustable without decorators

Damian Legawieca4d7a79e5bc2
diff --git a/docs/developer/customization/validations.mdx b/docs/developer/customization/validations.mdx
new file mode 100644
index 0000000000..eaea86cee7
--- /dev/null
+++ b/docs/developer/customization/validations.mdx
@@ -0,0 +1,173 @@
+---
+title: Validations
+section: customization
+---
+
+## Overview
+
+Adding a rule — and occasionally relaxing one Spree ships — is one of the most
+common reasons to reach into core models. There are three ways to do it, and
+picking the right one is mostly a question of *what kind of rule* you have.
+
+| Your rule is about… | Use |
+|---|---|
+| Whether an **operation** may happen — a purchase limit, B2B eligibility, a region policy | A workflow [`validate` hook](/developer/customization/workflows) |
+| The **shape of a record** — a field you added must be present, a format must match | A [decorator](/developer/customization/decorators) adding a validation |
+| A **new attribute** you need on an existing model | [Custom fields](/developer/core-concepts/metafields) |
+
+Spree deliberately has no registry for adding or removing arbitrary model
+validations. Adding one with a decorator is already a single line of ordinary
+Rails, and removing a core rule is served by the knobs below.
+
+## Vetoing an operation
+
+This is the one to reach for first. A `validate` hook runs inside the flow,
+before anything is written, and can stop it:
+
+```ruby
+# config/initializers/spree.rb
+Spree.hooks.register('carts.add_item.validate', 'MyStore::CheckPurchaseLimit')
+Spree.hooks.register('carts.upsert_items.validate', 'MyStore::CheckPurchaseLimit')
+
+module MyStore
+ class 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
+end
+```
+
+Why this beats a model validation for operational rules: it runs only for the
+operation you targeted, so a data migration or an admin correction isn't fought
+by a customer-facing rule; it sees the whole flow, not one record; and it can
+tell staff from customers (`workflow.created_by`) to allow a supervisor
+override.
+
+Both cart keys appear above because adding to a cart and setting a quantity are
+different flows. See [Services & Workflows](/developer/customization/workflows)
+for the full hook list.
+
+## Adding a rule to a model
+
+For rules about the shape of a record, a decorator is the supported route:
+
+```ruby
+# app/models/spree/product_decorator.rb
+module MyStore
+ module ProductDecorator
+ def self.prepended(base)
+ base.validates :external_id, presence: true, uniqueness: true
+ end
+ end
+end
+
+Spree::Product.prepend(MyStore::ProductDecorator)
+```
+
+Decorators couple you to Spree internals, so prefer a hook when the rule is
+really about an operation. See
+[Decorators](/developer/customization/decorators).
+
+## Relaxing a rule Spree ships
+
+Never call `clear_validators!` — it wipes every validation on the model,
+including ones added by other extensions, and the breakage appears far from the
+cause. Use one of these instead.
+
+### Store preferences
+
+Some rules are already switchable, per store, from the dashboard or a console:
+
+| Preference | Effect |
+|---|---|
+| `address_requires_phone` | Requires a phone number on addresses |
+| `company_field_enabled` | Shows the company field on address forms |
+| `address_requires_company` | Requires it — only meaningful with the field shown |
+| `disable_sku_validation` | Turns off SKU uniqueness |
+
+```ruby
+store.update!(preferred_address_requires_company: true)
+```
+
+### Overriding the gating predicate
+
+Most conditional validations in `Spree::Address` are gated on a predicate you
+can override, which is far safer than removing the validation:
+
+```ruby
+module MyStore
+ module AddressDecorator
+ # Business addresses only in this store.
+ def require_company?
+ !quick_checkout
+ end
+ end
+end
+
+Spree::Address.prepend(MyStore::AddressDecorator)
+```
+
+`require_name?`, `require_street?`, `require_zipcode?`, `require_phone?` and
+`require_company?` all work this way.
+
+### The address validator registry
+
+Address rules are regional and business-specific, so addresses carry a registry
+of extra validator classes you can add to and remove from:
+
+```ruby
+# config/initializers/spree.rb — or config.to_prepare for your own classes
+Spree.validators.addresses.register(MyStore::PostBoxValidator)
+
+# Drop a rule Spree ships
+Spree.validators.addresses.unregister(Spree::Addresses::PhoneValidator)
+```
+
+A validator is an ordinary `ActiveModel::Validator`:
+
+```ruby
+module MyStore
+ class PostBoxValidator < ActiveModel::Validator
+ def validate(record)
+ return unless record.address1.to_s.match?(/\A\s*P\.?O\.? Box/i)
+
+ record.errors.add(:address1, :po_box_not_deliverable)
+ end
+ end
+end
+```
+
+Register your own classes from `config.to_prepare` rather than an initializer —
+the registry holds classes, and a reloadable constant registered once at boot
+goes stale on the next reload.
+
+## Checkout requirements
+
+Rules about what a cart needs *before it can be completed* — a phone number
+before delivery, a purchase order number for B2B — belong in the checkout
+requirements registry rather than a model validation, because they also drive
+what the storefront shows as outstanding:
+
+```ruby
+Spree::Checkout::Registry.add_requirement(
+ step: 'address',
+ field: 'phone',
+ message: 'Phone number is required for delivery',
+ satisfied: ->(cart) { cart.ship_address&.phone.present? }
+)
+```
+
+See the [Spree 6 quickstart](/v6/developer/customization/quickstart) for the full registry API.
+
+## Custom field values
+
+Custom fields currently validate their type only — a `Number` field rejects
+non-numbers, a `Json` field rejects malformed JSON. There is no per-definition
+length, range or format rule yet. A product type marking a custom field as
+*required* is an advisory marker shown in the dashboard; the server does not
+enforce it.
diff --git a/docs/developer/customization/workflows.mdx b/docs/developer/customization/workflows.mdx
index cfd686c052..62445481b9 100644
--- a/docs/developer/customization/workflows.mdx
+++ b/docs/developer/customization/workflows.mdx
@@ -37,7 +37,7 @@ result = Spree.cart_add_item_workflow.call(cart: cart, variant: variant, quantit
if result.success?
line_item = result.value
else
- puts result.error.value
+ puts result.error.to_s
end
```
@@ -76,12 +76,31 @@ module MyStore
# every #perform keyword is a reader: cart, variant, quantity, ...
return if workflow.quantity <= 10
- workflow.reject!('You can order at most 10 of this item.')
+ workflow.errors.add(:quantity, :purchase_limit_exceeded,
+ message: 'You can order at most 10 of this item.')
+ workflow.reject!
end
end
end
```
+`workflow.errors` is an `ActiveModel::Errors`, the same object a model uses. A
+rejection therefore reaches the API in the shape clients already handle for
+validation failures — the field name, a symbolic code, and the message:
+
+```json
+{
+ "error": {
+ "code": "validation_error",
+ "message": "Quantity You can order at most 10 of this item.",
+ "details": { "quantity": ["You can order at most 10 of this item."] }
+ }
+}
+```
+
+Add to `:base` for a rejection that isn't about one field. `reject!('message')`
+with an argument is shorthand for exactly that.
+
<Note>
Hook keys are validated at boot. Registering against a hook that doesn't exist
raises `Spree::Hooks::UnknownHookError` with the list of valid hooks for that
@@ -233,6 +252,8 @@ is reported through `Rails.error` so it's visible rather than mysterious.
|---|---|---|---|
| `carts.add_item` | `validate` | validate | Before the line item is built |
| `carts.add_item` | `after_item_added` | lifecycle | After the item is saved and totals recalculated (in transaction) |
+| `carts.upsert_items` | `validate` | validate | Once per item, before anything is written — quantity edits, removals and bulk payloads |
+| `carts.upsert_items` | `after_items_upserted` | lifecycle | After the batch is applied and the cart recalculated once (in transaction) |
| `carts.complete` | `validate` | validate | After checkout requirements pass, before the order is created |
| `carts.complete` | `before_finalize` | lifecycle | After payment, before the order is placed |
| `carts.complete` | `after_finalize` | lifecycle | After the order is placed |
@@ -257,13 +278,35 @@ is reported through `Rails.error` so it's visible rather than mysterious.
| `payments.handle_webhook` | `after_handle` | lifecycle | After the gateway callback is processed |
| `customers.create` | `validate` | validate | After the customer is built, before it is saved — the registration-policy veto (bot screening, B2B approval) |
| `customers.create` | `after_create` | lifecycle | After the customer is created and the newsletter subscriber linked |
+| `products.create` | `validate` | validate | After the product is built, before it is saved — fires for the Admin API, CSV imports and seeds alike |
+| `products.create` | `after_create` | lifecycle | After the product is saved (in transaction) |
+| `products.update` | `validate` | validate | With the pending attributes assigned, so `product.changes` describes the edit |
+| `products.update` | `after_update` | lifecycle | After the product is saved (in transaction) |
+| `products.destroy` | `validate` | validate | Before the product is soft-deleted — refuse a deletion your store shouldn't allow |
+| `products.destroy` | `after_destroy` | lifecycle | After the soft-delete, for host cleanup (in transaction) |
`before_cancel` and `before_resume` accept `reject!` like a `validate` hook.
Draft-order editing in the admin uses **twin workflows** with their own keys —
-`orders.add_item`, `orders.recalculate`, `orders.recalculate_totals` — carrying
-the same hooks as their cart counterparts. Register against the cart key for
-storefront carts, the order key for admin edits, or both.
+`orders.add_item`, `orders.upsert_items`, `orders.recalculate`,
+`orders.recalculate_totals` — carrying the same hooks as their cart
+counterparts. Register against the cart key for storefront carts, the order key
+for admin edits, or both.
+
+<Note>
+`carts.add_item` **adds** to a quantity; `carts.upsert_items` **sets** it, and
+is what a quantity edit, a removal (quantity `0`) and a bulk item payload all
+run through. A rule about what may be in a cart therefore belongs on both keys —
+the readers are the same (`cart`, `variant`, `quantity`), so one handler class
+registers against each.
+
+`upsert_items` is also the one flow where a rejection is **not** fatal on the
+storefront: the vetoed item is skipped, the rest of the batch applies, and what
+was dropped comes back in the cart's `warnings`. A customer restoring a saved
+cart keeps whatever is still purchasable. Admin order edits behave the opposite
+way — the whole edit fails — because a silently dropped row is worse than a
+failed request when a merchant is editing.
+</Note>
Inspect what's available at runtime:
@@ -346,7 +389,7 @@ The whole vocabulary:
| `on_flow_failure: :name` | Names the undo for a step, run in reverse if a later step fails |
| `run_hooks :name` | Dispatches a declared hook; returns the merged hash from context handlers |
| `failure(value, error)` | Aborts the flow — rolls back an open transaction and returns a failure result |
-| `reject!(message)` | The same, named for hook handlers vetoing a flow |
+| `reject!` | The same, named for hook handlers vetoing a flow — carries `workflow.errors` |
| `halt!(value)` | Successful early exit (not valid inside a transaction the workflow opened) |
| `hooks :a, :b` | Declares the extension points this workflow dispatches |
diff --git a/docs/docs.json b/docs/docs.json
index ca39e6b770..e0abceb82f 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -333,6 +333,7 @@
"developer/customization/checkout",
"developer/customization/permissions",
"developer/customization/workflows",
+ "developer/customization/validations",
"developer/customization/dependencies",
"developer/customization/decorators",
"developer/customization/model-preferences",
@@ -1094,6 +1095,7 @@
"v6/developer/customization/configuration",
"v6/developer/customization/permissions",
"developer/customization/workflows",
+ "developer/customization/validations",
"developer/customization/api",
"developer/customization/model-preferences",
"developer/customization/metadata",
diff --git a/spree/core/app/models/spree/address.rb b/spree/core/app/models/spree/address.rb
index a91a99f7c7..4edac63a8e 100644
--- a/spree/core/app/models/spree/address.rb
+++ b/spree/core/app/models/spree/address.rb
@@ -64,6 +64,7 @@ module Spree
validates :city, :country
validates :zipcode, if: :require_zipcode?
validates :phone, if: :require_phone?
+ validates :company, if: :require_company?
end
validate :state_validate, :postal_code_validate
@@ -209,7 +210,9 @@ module Spree
end
def require_company?
- false
+ # Only meaningful when the field is on the form at all — requiring a
+ # value the customer is never shown would make checkout unfinishable.
+ !quick_checkout && show_company_address_field? && store_preference(:address_requires_company, false)
end
def require_street?
diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rb
index d2c2a5b4d7..af5d17f2c6 100644
--- a/spree/core/app/models/spree/store.rb
+++ b/spree/core/app/models/spree/store.rb
@@ -81,6 +81,9 @@ module Spree
preference :track_price_history, :boolean, default: true
# Address preferences
preference :company_field_enabled, :boolean, default: false
+ # Showing the company field and requiring it are separate decisions: a
+ # B2B store collects it from everyone, a mixed store only offers it.
+ preference :address_requires_company, :boolean, default: false
preference :address_requires_phone, :boolean, default: false
# digital assets preferences
preference :limit_digital_download_count, :boolean, default: true
diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rb
index e179591e85..36b51c6e09 100644
--- a/spree/core/lib/spree/core.rb
+++ b/spree/core/lib/spree/core.rb
@@ -633,6 +633,7 @@ require 'spree/core/number_generator'
require 'spree/number_generators/registry'
require 'spree/migrations'
require 'spree/translation_migrations'
+require 'spree/validators'
require 'spree/core/engine'
require 'spree/i18n'
diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rb
index 071d4d12cb..275b482b9d 100644
--- a/spree/core/lib/spree/core/engine.rb
+++ b/spree/core/lib/spree/core/engine.rb
@@ -48,7 +48,9 @@ module Spree
PromoEnvironment = Struct.new(:rules, :actions)
PricingEnvironment = Struct.new(:rules)
OrderRoutingEnvironment = Struct.new(:strategies, :rules)
- SpreeValidators = Struct.new(:addresses)
+ # Spree::Validators, not a Struct: the sets carry register/unregister so
+ # a host can drop a core rule (see Spree.validators.addresses).
+ SpreeValidators = Spree::Validators
CustomFieldsEnvironment = Struct.new(:types, :enabled_resources)
isolate_namespace Spree
engine_name 'spree'
diff --git a/spree/core/lib/spree/validators.rb b/spree/core/lib/spree/validators.rb
new file mode 100644
index 0000000000..b75562d8b8
--- /dev/null
+++ b/spree/core/lib/spree/validators.rb
@@ -0,0 +1,74 @@
+module Spree
+ # Registry of extra validator classes run against a model on top of its own
+ # validations. Addresses are the one model that ships with it, because
+ # address rules are regional and business-specific — phone formats, VAT
+ # numbers, address verification — and a host needs to add and remove them
+ # without reopening the model.
+ #
+ # Spree.validators.addresses.register(MyStore::PostBoxValidator)
+ # Spree.validators.addresses.unregister(Spree::Addresses::PhoneValidator)
+ #
+ # Register from `config.to_prepare` (not an initializer) when the validator
+ # is your own class: the set holds classes, so a reloadable constant
+ # registered once at boot would go stale on the next reload.
+ #
+ # For rules that veto a whole flow rather than shape a record, use a
+ # workflow :validate hook instead (see Spree::Hooks).
+ class Validators
+ # One named set of validator classes. Subclasses Array so the historical
+ # `Spree.validators.addresses` — which was a plain array of classes, and
+ # which hosts may already read, map or push onto — keeps behaving exactly
+ # as it did; register/unregister are the documented API on top.
+ class Set < Array
+ def initialize(entries = [])
+ super()
+ replace(entries)
+ end
+
+ # @param validator [Class, String] class responding to the
+ # ActiveModel::Validator contract
+ # @return [Class] the registered validator
+ def register(validator)
+ resolved = resolve(validator)
+ push(resolved) unless include?(resolved)
+ resolved
+ end
+
+ # @param validator [Class, String]
+ # @return [Class, nil] the removed validator, nil when not registered
+ def unregister(validator)
+ delete(resolve(validator))
+ end
+
+ def replace(entries)
+ super(Array(entries).map { |entry| resolve(entry) })
+ end
+
+ private
+
+ def resolve(validator)
+ validator.is_a?(String) || validator.is_a?(Symbol) ? validator.to_s.constantize : validator
+ end
+ end
+
+ def initialize
+ @sets = Hash.new { |sets, name| sets[name] = Set.new }
+ end
+
+ def [](name)
+ @sets[name.to_sym]
+ end
+
+ def []=(name, entries)
+ @sets[name.to_sym] = Set.new(entries)
+ end
+
+ def addresses
+ self[:addresses]
+ end
+
+ def addresses=(entries)
+ self[:addresses] = entries
+ end
+ end
+end
diff --git a/spree/core/spec/lib/spree/validators_spec.rb b/spree/core/spec/lib/spree/validators_spec.rb
new file mode 100644
index 0000000000..1903fa4ebc
--- /dev/null
+++ b/spree/core/spec/lib/spree/validators_spec.rb
@@ -0,0 +1,63 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Validators do
+ let(:registry) { described_class.new }
+
+ # Extensions have always read this as a plain array of classes.
+ it 'behaves like an array of validator classes' do
+ registry.addresses = [Spree::Addresses::PhoneValidator]
+
+ expect(registry.addresses).to be_an(Array)
+ expect(registry.addresses).to eq([Spree::Addresses::PhoneValidator])
+ end
+
+ it 'registers a validator by class or name' do
+ registry.addresses.register('Spree::Addresses::PhoneValidator')
+
+ expect(registry.addresses).to eq([Spree::Addresses::PhoneValidator])
+ end
+
+ it 'ignores a validator already registered' do
+ 2.times { registry.addresses.register(Spree::Addresses::PhoneValidator) }
+
+ expect(registry.addresses.size).to eq(1)
+ end
+
+ # The point of the registry: dropping a rule core ships.
+ it 'unregisters a validator' do
+ registry.addresses.register(Spree::Addresses::PhoneValidator)
+
+ expect(registry.addresses.unregister(Spree::Addresses::PhoneValidator)).to eq(Spree::Addresses::PhoneValidator)
+ expect(registry.addresses).to be_empty
+ end
+
+ it 'returns nil when unregistering something never registered' do
+ expect(registry.addresses.unregister(Spree::Addresses::PhoneValidator)).to be_nil
+ end
+end
+
+RSpec.describe 'Spree.validators.addresses' do
+ around do |example|
+ original = Spree.validators.addresses.dup
+ example.run
+ Spree.validators.addresses.replace(original)
+ end
+
+ it 'ships the phone validator by default' do
+ expect(Spree.validators.addresses).to include(Spree::Addresses::PhoneValidator)
+ end
+
+ it 'runs a registered validator against addresses' do
+ stub_const('SpecPostBoxValidator', Class.new(ActiveModel::Validator) do
+ def validate(record)
+ record.errors.add(:address1, 'cannot be a PO box') if record.address1.to_s.match?(/\APO Box/i)
+ end
+ end)
+ Spree.validators.addresses.register(SpecPostBoxValidator)
+
+ address = build(:address, address1: 'PO Box 123')
+
+ expect(address).not_to be_valid
+ expect(address.errors['address1']).to include('cannot be a PO box')
+ end
+end
diff --git a/spree/core/spec/models/spree/address_spec.rb b/spree/core/spec/models/spree/address_spec.rb
index 401ee12990..6c14c1e27b 100644
--- a/spree/core/spec/models/spree/address_spec.rb
+++ b/spree/core/spec/models/spree/address_spec.rb
@@ -210,6 +210,25 @@ describe Spree::Address, type: :model do
end
end
+ context 'when company is required' do
+ it 'validates presence of the company' do
+ stub_store_preferences(company_field_enabled: true, address_requires_company: true)
+
+ address.company = ''
+ address.valid?
+ expect(address.errors['company']).to eq(["can't be blank"])
+ end
+
+ # Requiring a field the customer is never shown would make checkout
+ # unfinishable, so the requirement follows the field being on the form.
+ it 'stays optional while the company field is hidden' do
+ stub_store_preferences(company_field_enabled: false, address_requires_company: true)
+
+ address.company = ''
+ expect(address).to be_valid
+ end
+ end
+
it 'requires zipcode' do
address.zipcode = ''
address.valid?
@@ -527,7 +546,9 @@ describe Spree::Address, type: :model do
before { order.update_attribute(:bill_address, address2) }
it 'has required attributes' do
- expect(Spree::Address.required_fields).to eq([:firstname, :lastname, :address1, :city, :country, :zipcode, :phone])
+ # Every conditionally-required field, whatever the store's settings —
+ # phone and company both default to off.
+ expect(Spree::Address.required_fields).to eq([:firstname, :lastname, :address1, :city, :country, :zipcode, :phone, :company])
end
it 'is editable' do