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.

Made every application setting configurable from the environment

Damian Legawiec4ca56e88459b
diff --git a/docs/developer/core-concepts/carts.mdx b/docs/developer/core-concepts/carts.mdx
index 5bdc920703..667e51483e 100644
--- a/docs/developer/core-concepts/carts.mdx
+++ b/docs/developer/core-concepts/carts.mdx
@@ -137,10 +137,86 @@ A cart tells you what it still needs before it can be completed:
}
```
-An empty `requirements` array means the cart is ready.
+Every entry has the same four fields. Branch on `code` — `message` is translated prose
+meant for a person, and `step` is only a grouping hint.
This is what lets you design your own checkout. Spree tells you what's missing; you decide how and when to ask for it — one long page, a few steps, or whatever suits your storefront.
+Seven checks run on every cart read:
+
+| `code` | `step` | Raised when |
+|---|---|---|
+| `line_items_required` | `cart` | The cart is empty |
+| `email_required` | `address` | No email address |
+| `ship_address_required` | `address` | Something needs shipping and there is no address |
+| `delivery_method_required` | `delivery` | A delivery method hasn't been chosen |
+| `payment_required` | `payment` | The total isn't covered by payments |
+| `po_number_required` | `address` | A company requires a purchase-order number |
+| `order_minimum_not_met` | `cart` | Below the order minimum, with the shortfall in the message |
+
+<Warning>
+ **An empty `requirements` array does not guarantee completion will succeed.** What a
+ cart reports is the *advisory* set. Completing one additionally checks stock
+ (`out_of_stock`, `discontinued`), negotiated quantity rules
+ (`quantity_rule_violated`) and the guest-checkout policy
+ (`guest_checkout_not_allowed`) — each of which has to load line items, so they are
+ held back to keep reading a cart cheap. Treat a failed completion as a normal path,
+ not an exception.
+</Warning>
+
+### Checkout steps
+
+A cart also reports a step list, so you can render a progress indicator:
+
+<CodeGroup>
+
+```typescript Store SDK
+const cart = await client.carts.get(cartId)
+
+cart.current_step // "delivery"
+cart.completed_steps // ["address"]
+```
+
+```json Response
+{
+ "current_step": "delivery",
+ "completed_steps": ["address"]
+}
+```
+
+</CodeGroup>
+
+Spree has no checkout state machine. The list is computed from the cart's own data,
+and nothing on the server refuses a write because of where the customer appears to be
+— you can set an address, choose delivery and attach a payment in any order.
+`current_step` is simply the step of the first unmet requirement.
+
+Five steps are built in, and three only appear when they apply:
+
+| Step | Present when |
+|---|---|
+| `address` | Always |
+| `delivery` | The cart has items and isn't entirely digital |
+| `payment` | The total is above zero |
+| `confirm` | A payment method asks for one, or the store always wants one |
+| `complete` | Always |
+
+So a free digital order reports `address` then `complete`. A storefront that hardcodes
+five steps will show two that never apply.
+
+<Note>
+ Requirements use one grouping name that is not a step: **`cart`**. Missing line
+ items, the order minimum and stock problems are filed under it, and there is no
+ `cart` entry in the step list — `current_step` reports those as `address`. If you
+ group requirements by `step` to place them on screens, give `cart` a home.
+</Note>
+
+Checkout introspection lives on the cart, not the order. An order has already been
+placed, so `current_step` and `requirements` do not appear on it.
+
+To add your own step or requirement, see
+[Customizing checkout](/developer/customization/checkout).
+
## Checkout
<Steps>
diff --git a/docs/developer/customization/checkout.mdx b/docs/developer/customization/checkout.mdx
new file mode 100644
index 0000000000..825b3d1cf6
--- /dev/null
+++ b/docs/developer/customization/checkout.mdx
@@ -0,0 +1,133 @@
+---
+title: Customizing Checkout
+description: Add your own checkout step or requirement, and reorder or remove the built-in ones.
+---
+
+Spree does not run your checkout — your storefront does. What Spree owns is the list
+of things a cart still needs, which it reports on cart reads and enforces when you
+complete one. Adding to that list is how you make checkout require something of your
+own.
+
+<Note>
+ For what a cart reports and how to read it, see
+ [Carts](/developer/core-concepts/carts#checkout-requirements). This page is about
+ adding to it.
+</Note>
+
+## Requirements are the gate, steps are a label
+
+Two things are easy to confuse:
+
+- A **requirement** is enforced. It appears on cart reads while unmet, and completing
+ a cart recomputes the list and refuses if anything is outstanding.
+- A **step** is descriptive. It exists so a storefront can render a progress
+ indicator. Nothing on the server checks which step a customer is on.
+
+So a requirement is what you reach for when something must be true before an order
+exists. A step is only worth adding when your checkout genuinely has a stage the
+built-in five don't describe.
+
+## Adding a requirement
+
+When the flow is unchanged and you only need one more condition:
+
+```ruby server/config/initializers/spree.rb
+Rails.application.config.to_prepare do
+ Spree::Checkout::Registry.add_requirement(
+ step: :address,
+ field: :vat_number,
+ message: 'VAT number is required for business orders',
+ satisfied: ->(cart) { cart.custom_fields['vat_number'].present? }
+ )
+end
+```
+
+While `satisfied:` returns false the cart reports the requirement and refuses to
+complete. Its `code` is derived as `<field>_required` — `vat_number_required` here.
+
+Pass `applicable:` to scope it. It is checked before `satisfied:`, so a requirement
+that doesn't apply never appears at all:
+
+```ruby
+applicable: ->(cart) { cart.customer&.company.present? }
+```
+
+<Warning>
+ **Register inside `to_prepare`, not at the top level of an initializer.** The
+ registry is reloadable code holding class-level state, so anything registered once
+ at boot is discarded the first time your app reloads in development, and your
+ requirement quietly stops applying. `to_prepare` runs again after every reload.
+</Warning>
+
+`message` is stored verbatim — wrap it in `Spree.t` yourself if it needs translating.
+
+## Adding a step
+
+A step bundles its own requirements and says when it is satisfied:
+
+```ruby server/config/initializers/spree.rb
+Rails.application.config.to_prepare do
+ Spree::Checkout::Registry.register_step(
+ name: :loyalty,
+ before: :payment,
+ satisfied: ->(cart) { cart.custom_fields['loyalty_number'].present? },
+ requirements: ->(cart) {
+ [{ step: 'loyalty', field: 'loyalty_number',
+ message: 'Loyalty number is required' }]
+ }
+ )
+end
+```
+
+The step now appears in the cart's `checkout_steps`, its requirements show up while
+unsatisfied, and completion refuses the cart until they are met.
+
+Each lambda receives the cart. Placement is controlled by two keywords:
+
+| Keyword | Effect |
+|---|---|
+| `before:` / `after:` | Place the step next to an existing one. `before:` wins if both are given |
+| `applicable:` | Whether the step exists for this cart at all — checked before `satisfied:` |
+
+An unanchored step lands immediately before `complete`. An anchor naming a step this
+particular cart doesn't have — `before: :payment` on a free cart — falls back to the
+same place.
+
+Unlike an added requirement, a step's `requirements:` lambda may set its own `code:`.
+
+## Reordering or removing built-in steps
+
+```ruby server/config/initializers/spree.rb
+Rails.application.config.to_prepare do
+ # Drop a step from the reported list
+ Spree::Checkout::Registry.base_steps.delete('confirm')
+
+ # Or change when one applies
+ Spree::Checkout::Registry.base_steps['payment'] = ->(cart) { cart.total > 0 }
+
+ # Or reorder wholesale — known names keep their own applicability
+ Spree::Checkout::Registry.base_step_names = %w[address payment delivery complete]
+end
+```
+
+<Warning>
+ Removing a step removes it from the reported list. It does **not** remove the
+ requirements filed under it — dropping `payment` does not let an unpaid cart
+ complete. Requirements and steps are separate on purpose.
+</Warning>
+
+## Prefer a requirement to a workflow hook
+
+A [workflow hook](/developer/customization/workflows) on `carts.complete.validate`
+can also reject a cart, and there are cases for it — anything needing a network call, or a
+decision that only makes sense at the moment of completion.
+
+For anything a customer has to fix, a requirement is better: it is reported on every
+cart read, so the storefront can show it while they can still act, rather than failing
+at the last step with an error they have to interpret.
+
+## Related
+
+- [Carts](/developer/core-concepts/carts) — reading requirements and completing a cart
+- [Custom fields](/developer/core-concepts/metafields) — storing your own data on a cart
+- [Services & Workflows](/developer/customization/workflows) — hooks that run during completion
diff --git a/docs/developer/customization/configuration.mdx b/docs/developer/customization/configuration.mdx
index cf60fbd797..1c3a2d9422 100644
--- a/docs/developer/customization/configuration.mdx
+++ b/docs/developer/customization/configuration.mdx
@@ -1,230 +1,128 @@
---
title: Configuration
-description: Every global Spree setting that is actually read by Spree — grouped by area, with defaults and what each one changes.
+description: Every Spree setting, the environment variable that sets it, and what it changes.
---
-Global settings live in `config/initializers/spree.rb` and apply to the whole application. Anything that varies per store — currency, markets, delivery zones, languages — is data you change in the dashboard instead.
+All business configuration can be performaed fromm the Admin Dashboard.What is left is a small set of settings describing the *installation*: limits,
+expiries, and where things are hosted. **Every one of them is set with an environment
+variable**, so changing one is a config change rather than a code change.
-```ruby config/initializers/spree.rb
-Spree.config do |config|
- config.minimum_password_length = 10
- config.allow_empty_price_amount = true
-end
+```bash
+SPREE_MINIMUM_PASSWORD_LENGTH=10
+SPREE_JWT_EXPIRATION=1800
```
+Values are converted to the setting's type, so `SPREE_WEBHOOKS_ENABLED=false` really
+is false. A value that cannot be converted — `SPREE_JWT_EXPIRATION=abc` — fails at
+boot rather than silently reverting to the default.
+
<Note>
-Restart your Rails server after editing the initializer.
+ Booleans accept `true`/`false`, `1`/`0`, `yes`/`no` and `on`/`off`, in any case.
</Note>
-## Deployment settings read the environment
-
-Settings that describe the deployment rather than commerce behavior can be set with an environment variable — no Ruby, no code change, no restart-after-edit dance. An explicitly configured value always wins over the environment.
+## Hosting
-| Setting | Environment variable | What it configures |
+| Variable | Default | What it does |
|---|---|---|
-| `dashboard_url` | `SPREE_DASHBOARD_URL` | Origin where the admin dashboard is hosted (e.g. `https://admin.my-shop.com`). Used for every link that sends someone into the dashboard: invitation emails, SSO redirects, and the first-run setup link printed by `db:seed`. |
-| `seller_panel_url` | `SPREE_SELLER_PANEL_URL` | Origin where the marketplace seller panel is hosted, when you serve it somewhere other than this app's own `/sellers` mount. Used for links sent to sellers, today the invitation email. Leave it unset to use `/sellers`; with no panel deployed at all, those links open the dashboard. |
-
-This page lists only settings Spree actually reads. Settings that exist for backwards compatibility are listed under [Deprecated settings](#deprecated-settings) rather than mixed in with the rest.
-
-## Settings that belong to a store
-
-Settings that shape how a shop sells — when customers are charged, whether stock is counted, which products appear without a price — are properties of a store, not of the installation, so they live on `Spree::Store` and are edited in the dashboard under **Settings → Store**:
-
-`capture_method`, `track_inventory_levels`, `stock_reservations_enabled`, `stock_reservation_ttl_minutes`, `track_price_history`, `show_products_without_price`, `disable_sku_validation`, `address_requires_phone`, `company_field_enabled`, `tax_using_ship_address`, plus `guest_checkout` and `storefront_access` — those last two are owned by the channel, and the store's value is what a channel falls back to.
-
-The global versions of these settings still exist but are no longer read, so setting one in the initializer changes nothing. If you're upgrading from an installation that used them, run `bin/rake spree:store_settings:backfill_from_config` to copy your values onto every store.
-
-```ruby
-store = Spree::Current.store
-store.preferred_capture_method # => "checkout"
-store.update!(preferred_track_inventory_levels: false)
-```
-
-### When customers are charged
-
-`capture_method` says when a customer is charged rather than only authorized. It applies to every payment method, not just card gateways. It takes one of three values:
-
-| Value | What happens |
-|---|---|
-| `checkout` | The money is taken as soon as the order is placed. This is the default. |
-| `on_dispatch` | The amount is authorized at checkout and captured when the goods are dispatched. |
-| `manual` | The amount is authorized at checkout and staff capture it when they choose. |
-
-A payment method can override the store for its own payments by setting the same three values; leaving it blank inherits the store's choice. Ask a payment method what applies with `resolved_capture_method`, or use the `capture_at_checkout?`, `capture_on_dispatch?` and `capture_manually?` questions.
-
-```ruby
-payment_method.update!(capture_method: 'on_dispatch')
-payment_method.resolved_capture_method # => "on_dispatch"
-
-payment_method.update!(capture_method: nil) # back to inheriting
-payment_method.resolved_capture_method # => "checkout"
-```
-
-If you're upgrading from an installation that used the older `auto_capture` and `auto_capture_on_dispatch` booleans, two tasks carry it over: `spree:store_settings:backfill_from_config` maps the old globals onto each store's `capture_method`, and `spree:migrate_capture_methods` converts the per-payment-method `auto_capture` column. A method left without a value inherits its store.
+| `SPREE_DASHBOARD_URL` | — | Origin where the dashboard is hosted. Used for every link that sends someone into it — invitation emails, SSO redirects, and the first-run setup link printed by `db:seed`. |
+| `SPREE_SELLER_PANEL_URL` | — | Origin where the marketplace seller panel is hosted, when it isn't this app's own `/sellers` mount. Unset uses `/sellers`; with no panel deployed, seller links open the dashboard. |
+| `SPREE_STORE_SCOPE_GUARD` | `log` | Tripwire for queries that miss a store scope, in development and test only. `log` warns, `raise` fails, `off` disables. Never active in production. |
-## Checkout and payments
+## Carts
-| Setting | Default | What it does |
+| Variable | Default | What it does |
|---|---|---|
-| `always_include_confirm_step` | `false` | Always shows a confirmation step, even when the payment method doesn't need one. |
-| `credit_to_new_allocation` | `false` | Records refunded store credit as a new entry each time instead of topping the original credit back up. |
+| `SPREE_GUEST_CART_EXPIRY_DAYS` | `30` | How long an abandoned guest cart is kept before deletion. |
+| `SPREE_CUSTOMER_CART_EXPIRY_DAYS` | `90` | How long a signed-in customer's abandoned cart is kept. |
+| `SPREE_EMPTY_CART_EXPIRY_HOURS` | `48` | How long a cart with no items is kept. |
-## Carts and stock reservations
+## Products and pricing
-| Setting | Default | What it does |
+| Variable | Default | What it does |
|---|---|---|
-| `guest_cart_expiry_days` | `30` | How long an abandoned guest cart is kept before deletion. |
-| `customer_cart_expiry_days` | `90` | How long a signed-in customer's abandoned cart is kept. |
-| `empty_cart_expiry_hours` | `48` | How long a cart with no items is kept. |
+| `SPREE_ALLOW_EMPTY_PRICE_AMOUNT` | `false` | Allows a price to be left blank instead of requiring an amount. Prices in a price list already allow blank. |
+| `SPREE_ALWAYS_USE_TRANSLATIONS` | `false` | Always read product, category and collection names from the translation tables, even in the store's own default language. |
-## Products and pricing
+## Payments
-| Setting | Default | What it does |
+| Variable | Default | What it does |
|---|---|---|
-| `allow_empty_price_amount` | `false` | Allows a price to be left blank instead of requiring an amount. Prices in a price list already allow blank. |
-| `price_history_retention_days` | `30` | How many days of price history the `spree:price_history:prune` task keeps. |
-| `always_use_translations` | `false` | Always read product, category and collection names from the translation tables, even in the store's own default language. |
+| `SPREE_CREDIT_TO_NEW_ALLOCATION` | `false` | Records refunded store credit as a new entry each time instead of topping the original credit back up. |
## Addresses
-| Setting | Default | What it does |
+| Variable | Default | What it does |
|---|---|---|
-| `geocode_addresses` | `true` | Looks up latitude and longitude for saved addresses. |
+| `SPREE_GEOCODE_ADDRESSES` | `true` | Looks up latitude and longitude for saved addresses. |
-## Media
+## Uploads
-| Setting | Default | What it does |
+| Variable | Default | What it does |
|---|---|---|
-| `max_image_download_size` | `20971520` | Largest file size, in bytes, accepted when downloading an image from an external URL. |
-| `images_save_from_url_job_attempts` | `5` | How many times to retry fetching an external image before giving up. |
+| `SPREE_MAX_IMAGE_DOWNLOAD_SIZE` | `20971520` | Largest file accepted when downloading an image from an external URL, in bytes (20 MB). |
+| `SPREE_IMAGES_SAVE_FROM_URL_JOB_ATTEMPTS` | `5` | How many times to retry fetching an external image before giving up. |
+| `SPREE_MAX_VIDEO_UPLOAD_SIZE` | `524288000` | Largest product video accepted, in bytes (500 MB). |
+| `SPREE_MAX_SELLER_DOCUMENT_UPLOAD_SIZE` | `20971520` | Largest document a seller may upload for a requirement, in bytes (20 MB). Small on purpose — these are certificates and registrations. |
## Promotions and gift cards
-| Setting | Default | What it does |
+| Variable | Default | What it does |
|---|---|---|
-| `coupon_codes_web_limit` | `500` | How many coupon codes are created immediately when saving a promotion. Larger batches move to a background job so saving stays fast. |
-| `coupon_codes_total_limit` | `5000` | Maximum coupon codes a single promotion may generate. |
-| `gift_card_batch_web_limit` | `500` | How many gift card codes a batch creates immediately before switching to a background job. |
-| `gift_card_batch_limit` | `50000` | Maximum gift card codes in a single batch. |
+| `SPREE_COUPON_CODES_WEB_LIMIT` | `500` | How many coupon codes are created immediately when saving a promotion. Larger batches move to a background job so saving stays fast. |
+| `SPREE_COUPON_CODES_TOTAL_LIMIT` | `5000` | Maximum coupon codes a single promotion may generate. |
+| `SPREE_GIFT_CARD_BATCH_WEB_LIMIT` | `500` | How many gift card codes a batch creates immediately before switching to a background job. |
+| `SPREE_GIFT_CARD_BATCH_LIMIT` | `50000` | Maximum gift card codes in a single batch. |
## Accounts and passwords
-| Setting | Default | What it does |
+| Variable | Default | What it does |
|---|---|---|
-| `minimum_password_length` | `8` | Shortest password a customer or staff member may set. |
-| `maximum_password_length` | `72` | Longest password allowed. |
-| `max_failed_login_attempts` | `5` | Failed sign-ins before an account is temporarily locked. |
-| `lockout_duration` | `1800` | How long an account stays locked, in seconds. |
-| `customer_password_reset_expires_in` | `15` | How long a customer's password reset link stays valid, in minutes. |
-| `admin_password_reset_expires_in` | `15` | How long a staff password reset link stays valid, in minutes. |
-
-## URLs
-
-| Setting | Default | What it does |
-|---|---|---|
-| `dashboard_url` | `nil` | Where the React dashboard lives, so single sign-on can send staff back to it after they authenticate. |
-| `admin_url` | `nil` | Base address used to build staff invitation links in email. Invitation links are relative when this is unset. |
+| `SPREE_MINIMUM_PASSWORD_LENGTH` | `8` | Shortest password a customer or staff member may set. |
+| `SPREE_MAXIMUM_PASSWORD_LENGTH` | `ActiveModel::SecurePassword::MAXPASSWORDLENGTHALLOWED` | Longest password allowed. |
+| `SPREE_MAX_FAILED_LOGIN_ATTEMPTS` | `5` | Failed sign-ins before an account is temporarily locked. |
+| `SPREE_LOCKOUT_DURATION` | `1800` | How long an account stays locked, in seconds. |
+| `SPREE_CUSTOMER_PASSWORD_RESET_EXPIRES_IN` | `15` | How long a customer's password reset link stays valid, in minutes. |
+| `SPREE_ADMIN_PASSWORD_RESET_EXPIRES_IN` | `15` | How long a staff password reset link stays valid, in minutes. |
## Imports and events
-| Setting | Default | What it does |
+| Variable | Default | What it does |
|---|---|---|
-| `large_import_threshold` | `500` | Row count above which a CSV import switches to bulk processing — faster, with less live progress detail. |
-| `events_log_enabled` | `true` | Writes every Spree event to the Rails log. |
-| `disable_migration_check` | `false` | Silences the boot warning about pending engine migrations. |
-
-## API settings
+| `SPREE_LARGE_IMPORT_THRESHOLD` | `500` | Row count above which a CSV import switches to bulk processing — faster, with less live progress detail. |
+| `SPREE_EVENTS_LOG_ENABLED` | `true` | Writes every Spree event to the Rails log. |
+| `SPREE_DISABLE_MIGRATION_CHECK` | `false` | Silences the boot warning about pending engine migrations. |
-API settings live on their own configuration object:
+## API authentication
-```ruby config/initializers/spree.rb
-Spree::Api::Config.jwt_expiration = 1800
-```
-
-### Authentication
-
-| Setting | Default | What it does |
+| Variable | Default | What it does |
|---|---|---|
-| `jwt_expiration` | `3600` | How long a customer or store access token stays valid, in seconds. |
-| `admin_jwt_expiration` | `300` | How long a staff access token stays valid. Deliberately short — admin tokens carry far more privilege. |
-| `refresh_token_expiry` | `2592000` | How long a refresh token stays valid, in seconds (30 days). |
-| `jwt_secret_key` | `nil` | Signing key for tokens. Falls back to the Rails secret key base. |
+| `SPREE_JWT_EXPIRATION` | `3600` | How long a customer or store access token stays valid, in seconds. |
+| `SPREE_ADMIN_JWT_EXPIRATION` | `300` | How long a staff access token stays valid. Deliberately short — staff tokens carry far more privilege. |
+| `SPREE_REFRESH_TOKEN_EXPIRY` | `2592000` | How long a refresh token stays valid, in seconds (30 days). |
+| `SPREE_JWT_SECRET_KEY` | — | Signing key for tokens. Falls back to `Rails.application.credentials.jwt_secret_key`, then the Rails secret key base. |
-### Rate limits
+## API rate limits
-| Setting | Default | What it does |
+| Variable | Default | What it does |
|---|---|---|
-| `rate_limit_window` | `60` | Length of the rate-limit window, in seconds. |
-| `rate_limit_per_key` | `300` | Requests allowed per window for each publishable API key + client IP pair (per visitor), and for keyless traffic per IP. Applies across the whole API, not per endpoint. |
-| `rate_limit_per_secret_key` | `600` | Requests allowed per secret API key per window, across the whole API. |
-| `rate_limit_login` | `5` | Sign-in attempts allowed per IP per window. |
-| `rate_limit_register` | `3` | Registration attempts per IP. |
-| `rate_limit_refresh` | `10` | Token refresh attempts per IP. |
-| `rate_limit_password_reset` | `3` | Password reset requests per IP. |
-| `max_request_body_size` | `102400` | Largest accepted request body, in bytes (100 KB). |
-
-### Webhooks
-
-| Setting | Default | What it does |
+| `SPREE_RATE_LIMIT_WINDOW` | `60` | Length of the rate-limit window, in seconds. |
+| `SPREE_RATE_LIMIT_PER_KEY` | `300` | Requests per window for each publishable key + client IP pair, and for keyless traffic per IP. Across the whole API, not per endpoint. |
+| `SPREE_RATE_LIMIT_PER_SECRET_KEY` | `600` | Requests per secret API key per window, across the whole API. |
+| `SPREE_RATE_LIMIT_LOGIN` | `5` | Sign-in attempts allowed per IP per window. |
+| `SPREE_RATE_LIMIT_REGISTER` | `3` | Registration attempts per IP. |
+| `SPREE_RATE_LIMIT_REFRESH` | `10` | Token refresh attempts per IP. |
+| `SPREE_RATE_LIMIT_PASSWORD_RESET` | `3` | Password reset requests per IP. |
+| `SPREE_MAX_REQUEST_BODY_SIZE` | `102400` | Largest accepted request body, in bytes (100 KB). |
+
+## Webhooks
+
+| Variable | Default | What it does |
|---|---|---|
-| `webhooks_enabled` | `true` | Whether webhooks fire at all. |
-| `webhooks_verify_ssl` | `true` | Verifies SSL certificates on webhook endpoints. Off in development. |
-
-## Reading a setting
-
-```ruby
-Spree::Config.minimum_password_length # => 8
-Spree::Api::Config.jwt_expiration # => 3600
-```
-
-Assigning at runtime affects only the current process and is lost on restart. Set values in the initializer to make them stick.
-
-## Deprecated settings
-
-These still exist so upgrades don't break, but Spree either ignores them or reads them only from subsystems it has replaced. Don't use them in new code.
-
-| Setting | Use instead |
-|---|---|
-| `return_eligibility_number_of_days` | The `return_window_days` preference on [Market](/developer/core-concepts/markets), or a `returns.create.validate` [hook](/developer/customization/workflows) |
-| `restock_inventory` | Restocking is decided per return line item by its resellable flag — see [Returns](/developer/core-concepts/returns-exchanges-claims#processing-a-return) |
-| `expedited_exchanges` | [Exchanges](/developer/core-concepts/returns-exchanges-claims) |
-| `expedited_exchanges_days_window` | [Exchanges](/developer/core-concepts/returns-exchanges-claims) |
-| `enable_legacy_default_price` | Compatibility switch for the old default-price behavior; leave off |
-| `use_user_locale` | Locale comes from the `x-spree-locale` header or the `locale` parameter |
-| `company` | The `company_field_enabled` setting on the store |
-| `address_requires_phone` | The `address_requires_phone` setting on the store |
-| `default_stock_reservation_ttl_minutes` | The `stock_reservation_ttl_minutes` setting on the store |
-| `auto_capture` | The `capture_method` setting on the store |
-| `auto_capture_on_dispatch` | The `capture_method` setting on the store |
-| `stock_reservations_enabled` | The `stock_reservations_enabled` setting on the store |
-| `track_inventory_levels` | The `track_inventory_levels` setting on the store |
-| `show_products_without_price` | The `show_products_without_price` setting on the store |
-| `disable_sku_validation` | The `disable_sku_validation` setting on the store |
-| `track_price_history` | The `track_price_history` setting on the store |
-| `tax_using_ship_address` | The `tax_using_ship_address` setting on the store |
-| `disable_store_presence_validation` | Every store-owned record now requires a store |
-
-<Warning>
-These settings have no effect at all, and are scheduled for removal: `allow_checkout_on_gateway_error` (completion checks whether payments cover the total, so a failed gateway call never completes an order), `products_per_page`, `alternative_shipping_phone`, `show_variant_full_price`, `reserve_stock_on`, `storefront_products_path`, `storefront_taxons_path`, `storefront_pages_path`. Setting them changes nothing.
-</Warning>
-
-## Settings that have been removed
-
-These settings are gone. Assigning one in your initializer now raises `NoMethodError`, so delete the line.
-
-| Setting | What to do instead |
-|---|---|
-| `send_core_emails` | The `send_consumer_transactional_emails` setting on the store, which turns a shop's customer emails on and off. |
-| `currency` | Currency belongs to the store and the market. |
-| `address_requires_state` | State requirements come from the address country. |
-| `checkout_zone` | Use [delivery zones](/developer/core-concepts/fulfillments#delivery-methods-and-zones). |
-| `allow_guest_checkout` | Use the `guest_checkout` setting on the store or channel. |
-| `binary_inventory_cache` | A stock change always touches its variant. |
-| `logo`, `mailer_logo` | The store's own `logo` and `mailer_logo` images, uploaded in the dashboard. Only the global settings are gone; the images themselves are unchanged. |
-| `layout`, `always_put_site_name_in_title`, `title_site_name_separator`, `max_level_in_taxons_menu`, `show_raw_product_description`, `shipping_instructions`, `show_only_complete_orders_by_default` | These configured the removed Rails storefront and admin. A storefront owns its own presentation. |
+| `SPREE_WEBHOOKS_ENABLED` | `true` | Whether webhooks fire at all. |
+| `SPREE_WEBHOOKS_VERIFY_SSL` | `true` | Verifies SSL certificates on webhook endpoints. Off in development. |
## Related
+- [Stores](/developer/core-concepts/stores) — the settings a shop owns
- [Model preferences](/developer/customization/model-preferences) — per-record settings
- [Services & Workflows](/developer/customization/workflows) — changing behavior rather than settings
diff --git a/docs/developer/customization/decorators.mdx b/docs/developer/customization/decorators.mdx
index 5ca873ac73..a236b35a1b 100644
--- a/docs/developer/customization/decorators.mdx
+++ b/docs/developer/customization/decorators.mdx
@@ -9,10 +9,9 @@ description: Use Spree decorators to add or modify behavior on core models, cont
- **[Events & Subscribers](/developer/core-concepts/events)** - For reacting to model changes (after save, create, update, delete)
- **[Webhooks](/developer/core-concepts/webhooks)** - For notifying external services when events occur
- **[Dependencies](/developer/customization/dependencies)** - For swapping out services, serializers, and abilities
- - **[Admin Navigation](/developer/dashboard/customization/navigation)** - For adding menu items without controller decorators
- - **[Admin Partials](/developer/dashboard/customization/quickstart)** - For extending admin UI without view decorators
- - **[Admin Tables](/developer/dashboard/customization/tables)** - For customizing admin list views
- - **[Ransack Configuration](/developer/core-concepts/search-filtering#extending-ransackable-configuration)** - For adding searchable/sortable fields without model decorators
+ - **[Dashboard Navigation](/developer/dashboard/customization/navigation)** - For adding menu items
+ - **[Dashboard Slots](/developer/dashboard/customization/slots)** - For adding your own UI to an existing dashboard screen
+ - **[Dashboard Tables](/developer/dashboard/customization/tables)** - For customizing list views
</Warning>
## When to Use Decorators vs Modern Alternatives
@@ -25,12 +24,14 @@ Before reaching for a decorator, check if your use case is better served by a mo
| Notify external service on changes | Model decorator with callbacks | [Webhooks](/developer/core-concepts/webhooks) |
| Custom add-to-cart logic | Service decorator | [Dependencies injection](/developer/customization/dependencies) |
| Custom API responses | Serializer decorator | [Dependencies injection](/developer/customization/dependencies) |
-| Add admin menu item | Controller decorator | [Admin Navigation API](/developer/dashboard/customization/navigation) |
-| Add section to admin form | View decorator/override | [Admin Partials injection](/developer/dashboard/customization/quickstart) |
-| Add searchable/filterable field | Model decorator with `ransackable_attributes` | [Ransack configuration](/developer/core-concepts/search-filtering#extending-ransackable-configuration) |
+| Add a dashboard menu item | Controller decorator | [Navigation registry](/developer/dashboard/customization/navigation) |
+| Add a section to a dashboard form | View decorator/override | [Slots](/developer/dashboard/customization/slots) |
+| Narrow what an endpoint returns | Overriding an action | Controller decorator overriding `scope` |
+| Accept a new attribute on write | Controller decorator | `Model.additional_permitted_attributes +=` |
| Add association to core model | - | Decorator (still appropriate) |
| Add validation to core model | - | Decorator (still appropriate) |
| Add new method to core model | - | Decorator (still appropriate) |
+| Make a new column [filterable](/developer/core-concepts/search-filtering) | - | Decorator (still appropriate) |
<Info>
Decorators are still appropriate for **structural changes** like adding associations, validations, scopes, and new methods to models. Use modern alternatives for **behavioral changes** like callbacks, hooks, and side effects.
@@ -38,9 +39,17 @@ Before reaching for a decorator, check if your use case is better served by a mo
## Overview
-All of Spree's models, controllers, helpers, etc can easily be extended or overridden to meet your exact requirements using standard Ruby idioms.
+Spree's models, API controllers and helpers can be extended or overridden to meet your requirements using standard Ruby idioms.
-Standard practice for including such changes in your application or extension is to create a file within the relevant **app/models/spree** or **app/controllers/spree** directory with the original class name with **_decorator** appended.
+The convention is a file under `server/app/models/spree` or `server/app/controllers/spree`, named after the original class with `_decorator` appended. The generators below place it for you.
+
+<Note>
+ There is nothing else to decorate. The dashboard is a React application that
+ talks to the Admin API, and the storefront is your own — so the only
+ controllers Spree ships are the API ones, and the only views are the emails.
+ Customize the dashboard through
+ [its own extension points](/developer/dashboard/customization/quickstart).
+</Note>
## Why Use Decorators?
@@ -93,7 +102,7 @@ Spree provides generators to create decorator files with the correct structure:
<CodeGroup>
```bash Spree CLI (Docker)
-spree generate spree:model_decorator Spree::Product
+spree generate model_decorator Spree::Product
```
```bash Without Spree CLI
@@ -102,7 +111,7 @@ bin/rails g spree:model_decorator Spree::Product
</CodeGroup>
-This creates `app/models/spree/product_decorator.rb`:
+This creates `server/app/models/spree/product_decorator.rb`:
```ruby
module Spree
@@ -121,19 +130,19 @@ end
<CodeGroup>
```bash Spree CLI (Docker)
-spree generate spree:controller_decorator Spree::Admin::ProductsController
+spree generate controller_decorator Spree::Api::V3::Admin::ProductsController
```
```bash Without Spree CLI
-bin/rails g spree:controller_decorator Spree::Admin::ProductsController
+bin/rails g spree:controller_decorator Spree::Api::V3::Admin::ProductsController
```
</CodeGroup>
-This creates `app/controllers/spree/admin/products_controller_decorator.rb`:
+This creates `server/app/controllers/spree/api/v3/admin/products_controller_decorator.rb`:
```ruby
-module Spree::Admin
+module Spree::Api::V3::Admin
module ProductsControllerDecorator
def self.prepended(base)
# base.before_action :my_filter
@@ -143,7 +152,7 @@ module Spree::Admin
end
end
-Spree::Admin::ProductsController.prepend Spree::Admin::ProductsControllerDecorator
+Spree::Api::V3::Admin::ProductsController.prepend Spree::Api::V3::Admin::ProductsControllerDecorator
```
The generator accepts any namespace depth. `Spree::ProductsController` produces a top-level `module Spree` wrapper; `Spree::Api::V3::Store::ProductsController` produces a `module Spree::Api::V3::Store` wrapper. The final `.prepend` line is always fully qualified.
@@ -154,7 +163,7 @@ The generator accepts any namespace depth. `Spree::ProductsController` produces
The most common use case is changing the behavior of existing methods. When overriding a method, you can call `super` to invoke the original implementation:
-```ruby app/models/spree/product_decorator.rb
+```ruby server/app/models/spree/product_decorator.rb
module Spree
module ProductDecorator
def available?
@@ -178,7 +187,7 @@ end
Add new instance methods directly in the decorator module:
-```ruby app/models/spree/product_decorator.rb
+```ruby server/app/models/spree/product_decorator.rb
module Spree
module ProductDecorator
def featured?
@@ -199,7 +208,7 @@ end
Use the `self.prepended(base)` callback to add associations:
-```ruby app/models/spree/product_decorator.rb
+```ruby server/app/models/spree/product_decorator.rb
module Spree
module ProductDecorator
def self.prepended(base)
@@ -214,7 +223,7 @@ end
### Adding Validations
-```ruby app/models/spree/product_decorator.rb
+```ruby server/app/models/spree/product_decorator.rb
module Spree
module ProductDecorator
def self.prepended(base)
@@ -229,7 +238,7 @@ end
### Adding Scopes
-```ruby app/models/spree/product_decorator.rb
+```ruby server/app/models/spree/product_decorator.rb
module Spree
module ProductDecorator
def self.prepended(base)
@@ -247,7 +256,7 @@ end
Use `extend` within the `prepended` callback to add class methods:
-```ruby app/models/spree/product_decorator.rb
+```ruby server/app/models/spree/product_decorator.rb
module Spree
module ProductDecorator
def self.prepended(base)
@@ -273,137 +282,107 @@ Spree::Product.search_by_name('shirt')
## Decorating Controllers
+The only controllers Spree ships are the API ones, under
+`Spree::Api::V3::Store` and `Spree::Api::V3::Admin`. There is no server-rendered
+storefront or admin to decorate — the dashboard is a React app that talks to the
+Admin API, and the storefront is yours.
+
<Warning>
- **Consider creating a new controller instead of decorating.** Creating your own controller that inherits from Spree's base controllers is more maintainable and less likely to break during upgrades. Use controller decorators only when you must modify existing Spree actions.
+ **Reach for a decorator last.** A `ResourceController` subclass exposes named
+ hooks — `scope`, `permitted_params`, `serializer_class`, `collection_includes`
+ — and overriding one of those in a decorator is safe. Overriding an *action*
+ couples your code to Spree's internals and is what breaks on upgrade.
</Warning>
-### Recommended: Create a New Controller
+### Narrowing what an endpoint returns
-Instead of decorating `Spree::ProductsController` to add a new action, create your own controller:
-
-```ruby app/controllers/spree/product_quick_views_controller.rb
-module Spree
- class ProductQuickViewsController < StoreController
- def show
- @product = current_store.products.friendly.find(params[:product_id])
- render partial: 'spree/products/quick_view', locals: { product: @product }
- end
- end
-end
-```
+The most common reason to decorate: restrict a listing beyond what the store
+scope already does.
-```ruby config/routes.rb
-Spree::Core::Engine.add_routes do
- get 'products/:product_id/quick_view', to: 'product_quick_views#show', as: :product_quick_view
-end
+```bash
+spree generate controller_decorator Spree::Api::V3::Admin::ProductsController
```
-This approach:
-- Won't break when Spree updates `ProductsController`
-- Is easier to test in isolation
-- Makes your customizations clearly visible in your codebase
-
-### Adding a New Action via Decorator
-
-If you must add an action to an existing controller:
-
-```ruby app/controllers/spree/products_controller_decorator.rb
-module Spree
+```ruby server/app/controllers/spree/api/v3/admin/products_controller_decorator.rb
+module Spree::Api::V3::Admin
module ProductsControllerDecorator
- def self.prepended(base)
- base.before_action :load_product, only: [:quick_view]
- end
+ protected
- def quick_view
- respond_to do |format|
- format.html { render partial: 'quick_view', locals: { product: @product } }
- format.json { render json: @product }
- end
- end
+ # `super` is already scoped to the current store. Chain onto it — never
+ # replace it, or the endpoint stops being scoped and starts returning
+ # another store's records.
+ def scope
+ return super if current_user.spree_admin?
- private
-
- def load_product
- @product = current_store.products.friendly.find(params[:id])
+ super.where(discontinue_on: nil)
end
end
-
- ProductsController.prepend(ProductsControllerDecorator)
end
-```
-Don't forget to add the route:
-
-```ruby config/routes.rb
-Spree::Core::Engine.add_routes do
- get 'products/:id/quick_view', to: 'products#quick_view', as: :product_quick_view
-end
+Spree::Api::V3::Admin::ProductsController.prepend(
+ Spree::Api::V3::Admin::ProductsControllerDecorator
+)
```
-### Modifying Existing Actions
+`current_user` is the signed-in staff member, and `spree_admin?` asks whether
+they hold the admin role for the current store.
<Warning>
- **High risk of breaking during upgrades.** When you override an existing Spree action, your code depends on Spree's internal implementation details. If Spree changes the action's behavior, instance variables, or method signatures in a future version, your decorator may silently break or cause unexpected bugs. Use [Events](/developer/core-concepts/events) for post-action side effects instead.
+ `current_user` is only set when the request carries a staff token. A request
+ authenticated with a [secret API key](/api-reference/admin-api/authentication)
+ has no user, so `current_user` is `nil` — guard for it, or a server-to-server
+ integration hits `NoMethodError` on every call.
</Warning>
-```ruby app/controllers/spree/admin/products_controller_decorator.rb
-module Spree
- module Admin
- module ProductsControllerDecorator
- def create
- # Add custom logic before
- log_product_creation_attempt
-
- # Call original method
- super
+### Accepting an extra attribute
- # Add custom logic after
- notify_team_of_new_product if @product.persisted?
- end
+If your decorator added a column to a core model, the controller has to permit
+it — but you rarely need a decorator for that. Extensions append to the model's
+own list from an initializer:
- private
+```ruby server/config/initializers/spree.rb
+Spree::Product.additional_permitted_attributes += [:brand_id]
+```
- def log_product_creation_attempt
- Rails.logger.info "Product creation attempted by #{current_spree_user.email}"
- end
+Always `+=`, never `=`, or you drop what another extension added.
- def notify_team_of_new_product
- ProductNotificationJob.perform_later(@product)
- end
- end
+### A new endpoint is a new controller
- ProductsController.prepend(ProductsControllerDecorator)
- end
-end
-```
+To add an action, write your own controller rather than decorating one of
+Spree's. It inherits the same pagination, filtering and authorization:
-<Info>
- **Better alternative:** For post-action side effects like notifications, use [Events subscribers](/developer/core-concepts/events) instead. Subscribe to `product.created` to be notified when products are created, without coupling to controller internals.
-</Info>
+```ruby server/app/controllers/spree/api/v3/admin/product_audits_controller.rb
+module Spree::Api::V3::Admin
+ class ProductAuditsController < ResourceController
+ # Names the API-key scope this endpoint needs: `read_products` for
+ # index/show, `write_products` for everything else. Every Admin API
+ # controller must declare one.
+ scoped_resource :products
-### Adding Before Actions
+ protected
-```ruby app/controllers/spree/checkout_controller_decorator.rb
-module Spree
- module CheckoutControllerDecorator
- def self.prepended(base)
- base.before_action :check_minimum_order, only: [:update]
+ def model_class
+ Spree::ProductAudit
end
- private
-
- def check_minimum_order
- if @order.total < 25.0 && params[:state] == 'payment'
- flash[:error] = 'Minimum order amount is $25'
- redirect_to checkout_state_path(@order.state)
- end
+ def serializer_class
+ MyApp::ProductAuditSerializer
end
end
-
- CheckoutController.prepend(CheckoutControllerDecorator)
end
```
+Add the route to your application's `config/routes.rb`, inside the engine's
+route hook. See [extending the API](/developer/customization/api).
+
+<Info>
+ **For side effects, use events rather than a decorator.** Subscribing to
+ `product.created` runs your code for every caller — the dashboard, a secret
+ API key, an import, the console. A controller override only fires for
+ requests that happen to pass through that controller. See
+ [Events](/developer/core-concepts/events).
+</Info>
+
## Best Practices
<CardGroup cols={2}>
@@ -429,7 +408,7 @@ end
If you have many customizations for a single class, consider splitting them into focused decorators:
```
-app/models/spree/
+server/app/models/spree/
├── product_decorator.rb # Main decorator (loads others)
├── product/
│ ├── brand_decorator.rb # Brand association
@@ -437,13 +416,22 @@ app/models/spree/
│ └── seo_decorator.rb # SEO-related methods
```
-```ruby app/models/spree/product_decorator.rb
-# Load focused decorators
-require_dependency 'spree/product/brand_decorator'
-require_dependency 'spree/product/inventory_decorator'
-require_dependency 'spree/product/seo_decorator'
+```ruby server/app/models/spree/product_decorator.rb
+module Spree
+ module ProductDecorator
+ include Product::BrandDecorator
+ include Product::InventoryDecorator
+ include Product::SeoDecorator
+ end
+
+ Product.prepend(ProductDecorator)
+end
```
+Each focused module is a plain module — only the top-level decorator calls
+`prepend`. Autoloading resolves them from their paths, so nothing needs
+requiring by hand.
+
## Common Pitfalls
### Forgetting to Call Super
@@ -499,7 +487,7 @@ If you have existing decorators that use callbacks for side effects, consider mi
**Before (Decorator with callback):**
-```ruby app/models/spree/product_decorator.rb
+```ruby server/app/models/spree/product_decorator.rb
module Spree
module ProductDecorator
def self.prepended(base)
@@ -519,7 +507,7 @@ end
**After (Events subscriber):**
-```ruby app/subscribers/product_sync_subscriber.rb
+```ruby server/app/subscribers/product_sync_subscriber.rb
class ProductSyncSubscriber < Spree::Subscriber
subscribes_to 'product.updated'
@@ -527,14 +515,16 @@ class ProductSyncSubscriber < Spree::Subscriber
product = Spree::Product.find_by_prefix_id(event.payload['id'])
return unless product
- # The payload includes changes, check if name changed
- if event.payload['previous_changes']&.key?('name')
- ExternalSyncJob.perform_later(product)
- end
+ ExternalSyncJob.perform_later(product)
end
end
```
+The payload is the record as the API serializes it, so it carries the new
+values rather than a list of what changed. When a subscriber only cares about
+one attribute, compare against what you last synced rather than looking for a
+changeset in the event.
+
### Benefits of Migration
<CardGroup cols={2}>
@@ -560,7 +550,7 @@ end
- [Events](/developer/core-concepts/events) - Learn about Spree's event system
- [Webhooks](/developer/core-concepts/webhooks) - HTTP callbacks for external integrations
- [Dependencies](/developer/customization/dependencies) - Swap core services with your own
-- [Admin Navigation](/developer/dashboard/customization/navigation) - Extend admin menu without decorators
-- [Admin Partials](/developer/dashboard/customization/quickstart) - Extend admin UI without view decorators
+- [Extending the API](/developer/customization/api) - Add your own endpoints
+- [Dashboard customization](/developer/dashboard/customization/quickstart) - Extend the dashboard from its own React app
- [Extending Core Models Tutorial](/developer/tutorial/model-and-api) - Step-by-step guide to connecting custom models with Spree core
- [Customization Overview](/developer/customization/quickstart) - General customization patterns
diff --git a/docs/developer/customization/validations.mdx b/docs/developer/customization/validations.mdx
index 02ba29185c..5383e6ed89 100644
--- a/docs/developer/customization/validations.mdx
+++ b/docs/developer/customization/validations.mdx
@@ -81,7 +81,8 @@ cause. Use one of these instead.
### Store preferences
-Some rules are already switchable, per store, from the dashboard or a console:
+Some rules are switchable per store, with no code at all. Change them in the
+dashboard under **Settings → Store**, or through the Admin API:
| Preference | Effect |
|---|---|
@@ -90,30 +91,38 @@ Some rules are already switchable, per store, from the dashboard or a console:
| `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)
+<CodeGroup>
+
+```typescript Admin SDK
+await adminClient.store.update({
+ preferred_address_requires_phone: false,
+})
```
-### Overriding the gating predicate
+```bash cURL
+curl -X PATCH 'https://api.mystore.com/api/v3/admin/store' \
+ -H 'X-Spree-API-Key: sk_xxx' \
+ -H 'Content-Type: application/json' \
+ -d '{ "preferred_address_requires_phone": false }'
+```
-Most conditional validations in `Spree::Address` are gated on a predicate you
-can override, which is far safer than removing the validation:
+</CodeGroup>
-```ruby
-module MyStore
- module AddressDecorator
- # Business addresses only in this store.
- def require_company?
- !quick_checkout
- end
- end
-end
+<Note>
+ All four are editable in the dashboard except `address_requires_company`, which
+ is API-only for now.
+</Note>
-Spree::Address.prepend(MyStore::AddressDecorator)
-```
+### Changing when a rule applies
+
+Most conditional rules on an address are gated on a predicate — `require_name?`,
+`require_street?`, `require_postal_code?`, `require_phone?` and
+`require_company?`. Overriding one changes *when* the rule applies without
+removing it, which is safer than dropping the validation outright.
-`require_name?`, `require_street?`, `require_postal_code?`, `require_phone?` and
-`require_company?` all work this way.
+This is the one case here that needs Ruby. See
+[decorators](/developer/customization/decorators) for how to override a model
+method.
### The address validator registry
@@ -121,7 +130,7 @@ 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
+# server/config/initializers/spree.rb — or config.to_prepare for your own classes
Spree.validators.addresses.register(MyStore::PostBoxValidator)
# Drop a rule Spree ships
diff --git a/docs/docs.json b/docs/docs.json
index 911758cc7e..1dc21c627b 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -376,10 +376,6 @@
"source": "/developer/customization/authentication",
"destination": "/v5/developer/customization/authentication"
},
- {
- "source": "/developer/customization/checkout",
- "destination": "/v5/developer/customization/checkout"
- },
{
"source": "/developer/customization/routes",
"destination": "/v5/developer/customization/routes"
@@ -891,6 +887,7 @@
"developer/customization/metadata",
"developer/customization/permissions",
"developer/customization/api",
+ "developer/customization/checkout",
"developer/customization/decorators"
],
"icon": "code"
diff --git a/spree/api/lib/spree/api/configuration.rb b/spree/api/lib/spree/api/configuration.rb
index 1df1362e7a..fb8e668583 100644
--- a/spree/api/lib/spree/api/configuration.rb
+++ b/spree/api/lib/spree/api/configuration.rb
@@ -3,25 +3,30 @@ require 'spree/core/preferences/runtime_configuration'
module Spree
module Api
class Configuration < Spree::Preferences::RuntimeConfiguration
- preference :jwt_expiration, :integer, default: 3600 # 1 hour in seconds (customer/store JWT default)
- preference :admin_jwt_expiration, :integer, default: 300 # 5 minutes — admin tokens have higher blast radius
- preference :jwt_secret_key, :string, default: nil
- preference :refresh_token_expiry, :integer, default: 2_592_000 # 30 days in seconds
+ preference :jwt_expiration, :integer, default: 3600, env: 'SPREE_JWT_EXPIRATION' # 1 hour in seconds (customer/store JWT default)
+ preference :admin_jwt_expiration, :integer, default: 300, env: 'SPREE_ADMIN_JWT_EXPIRATION' # 5 minutes — admin tokens have higher blast radius
+ # SPREE_JWT_SECRET_KEY resolves inside the preference, so it sits ahead of
+ # the Rails credentials fallback in Spree::Api::V3::JwtAuthentication —
+ # an operator who sets it means it. The older, unprefixed JWT_SECRET_KEY
+ # keeps its place behind credentials so existing deployments are
+ # unaffected.
+ preference :jwt_secret_key, :string, default: nil, env: 'SPREE_JWT_SECRET_KEY'
+ preference :refresh_token_expiry, :integer, default: 2_592_000, env: 'SPREE_REFRESH_TOKEN_EXPIRY' # 30 days in seconds
# Rate limiting
- preference :rate_limit_per_key, :integer, default: 300 # per publishable API key + client IP (per visitor)
- preference :rate_limit_per_secret_key, :integer, default: 600 # per secret API key, across the whole API
- preference :rate_limit_window, :integer, default: 60 # window in seconds
- preference :rate_limit_login, :integer, default: 5 # per IP
- preference :rate_limit_register, :integer, default: 3 # per IP
- preference :rate_limit_refresh, :integer, default: 10 # per IP
- preference :rate_limit_password_reset, :integer, default: 3 # per IP
+ preference :rate_limit_per_key, :integer, default: 300, env: 'SPREE_RATE_LIMIT_PER_KEY' # per publishable API key + client IP (per visitor)
+ preference :rate_limit_per_secret_key, :integer, default: 600, env: 'SPREE_RATE_LIMIT_PER_SECRET_KEY' # per secret API key, across the whole API
+ preference :rate_limit_window, :integer, default: 60, env: 'SPREE_RATE_LIMIT_WINDOW' # window in seconds
+ preference :rate_limit_login, :integer, default: 5, env: 'SPREE_RATE_LIMIT_LOGIN' # per IP
+ preference :rate_limit_register, :integer, default: 3, env: 'SPREE_RATE_LIMIT_REGISTER' # per IP
+ preference :rate_limit_refresh, :integer, default: 10, env: 'SPREE_RATE_LIMIT_REFRESH' # per IP
+ preference :rate_limit_password_reset, :integer, default: 3, env: 'SPREE_RATE_LIMIT_PASSWORD_RESET' # per IP
# Request body size limit in bytes
- preference :max_request_body_size, :integer, default: 102_400 # 100KB
+ preference :max_request_body_size, :integer, default: 102_400, env: 'SPREE_MAX_REQUEST_BODY_SIZE' # 100KB
- preference :webhooks_enabled, :boolean, default: true
- preference :webhooks_verify_ssl, :boolean, default: !Rails.env.development?
+ preference :webhooks_enabled, :boolean, default: true, env: 'SPREE_WEBHOOKS_ENABLED'
+ preference :webhooks_verify_ssl, :boolean, default: !Rails.env.development?, env: 'SPREE_WEBHOOKS_VERIFY_SSL'
end
end
end
diff --git a/spree/api/lib/spree/api/engine.rb b/spree/api/lib/spree/api/engine.rb
index ef5d6c6b3b..ed018c4ee1 100644
--- a/spree/api/lib/spree/api/engine.rb
+++ b/spree/api/lib/spree/api/engine.rb
@@ -24,6 +24,12 @@ module Spree
Spree.subscribers << Spree::WebhookEventSubscriber
end
+ # Runs after initializers so an explicitly assigned preference — which
+ # wins over the environment — is never rejected for a stale env var.
+ config.after_initialize do
+ Spree::Api::Configuration.validate_env!(Spree::Api::Config)
+ end
+
# Warn in production if no dedicated JWT secret key is configured
config.after_initialize do
next unless Rails.env.production?
diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rb
index 6831489288..29c0a2873f 100644
--- a/spree/core/lib/spree/core/engine.rb
+++ b/spree/core/lib/spree/core/engine.rb
@@ -89,6 +89,12 @@ module Spree
Spree::Deprecation = ActiveSupport::Deprecation.new('6.0', 'Spree')
end
+ # Runs after initializers so an explicitly assigned preference — which
+ # wins over the environment — is never rejected for a stale env var.
+ config.after_initialize do
+ Spree::Core::Configuration.validate_env!(Spree::Config)
+ end
+
# I18n's config lives in fiber/thread-local storage that survives across
# requests on reused server threads, so a request that never assigns its
# own locale would render in whatever locale the previous request on the
diff --git a/spree/core/lib/spree/core/preferences/runtime_configuration.rb b/spree/core/lib/spree/core/preferences/runtime_configuration.rb
index 219236998d..62cecb172b 100644
--- a/spree/core/lib/spree/core/preferences/runtime_configuration.rb
+++ b/spree/core/lib/spree/core/preferences/runtime_configuration.rb
@@ -1,6 +1,21 @@
module Spree
module Preferences
+ # Raised when an environment variable backing a preference holds a value
+ # that does not parse as the declared type.
+ class InvalidEnvironmentValue < StandardError
+ def initialize(variable, value, type, expected = nil)
+ article = type == :integer ? 'an' : 'a'
+ expected ||= "#{article} #{type}"
+ super("#{variable}=#{value.inspect} is not valid for #{article} #{type} setting. Expected #{expected}.")
+ end
+ end
+
class RuntimeConfiguration
+ # Deliberately not ActiveModel::Type::Boolean: it casts "no", "Off" and
+ # every unrecognised string — a typo included — to true.
+ BOOLEAN_TRUE = %w[true 1 yes on].freeze
+ BOOLEAN_FALSE = %w[false 0 no off].freeze
+
def initialize
load_defaults
end
@@ -71,10 +86,12 @@ module Spree
# set in an initializer or at runtime always wins over the
# environment; the env var only fills an unset preference.
#
+ # @param type [Symbol] declared type, used to coerce the env var
# @param env [String, nil] environment variable backing this setting
- def preference(name, _type, default: nil, deprecated: false, env: nil)
+ def preference(name, type, default: nil, deprecated: false, env: nil)
defaults[name] = default
deprecations[name] = deprecated
+ types[name] = type
env_vars[name] = env if env
attr_writer name
@@ -88,7 +105,12 @@ module Spree
value = instance_variable_get(ivar)
return value unless value.nil?
- ENV[env].presence || default
+ raw = ENV[env]
+ return default if raw.nil? || raw.empty?
+
+ # Memoized into the ivar so coercion runs once per process, not
+ # once per read — these sit on the request path.
+ instance_variable_set(ivar, self.class.coerce_env(env, raw, type))
end
else
attr_reader name
@@ -103,10 +125,62 @@ module Spree
@deprecations ||= {}
end
+ # @return [Hash{Symbol => Symbol}] declared type per preference
+ def types
+ @types ||= {}
+ end
+
# @return [Hash{Symbol => String}] preferences backed by an env var
def env_vars
@env_vars ||= {}
end
+
+ # Reads every env-backed preference so a malformed value fails at boot
+ # rather than on the first request that happens to read it. Reading
+ # also memoizes the coerced value, so this doubles as a warm-up.
+ #
+ # @param instance [RuntimeConfiguration] configuration to validate
+ # @raise [Spree::Preferences::InvalidEnvironmentValue]
+ # @return [void]
+ def validate_env!(instance)
+ env_vars.each_key { |name| instance.public_send(name) }
+ nil
+ end
+
+ # Env vars arrive as strings, so an uncoerced `SPREE_X=false` would be
+ # the truthy String "false". Coercion is strict: a value that does not
+ # parse raises rather than falling back to the default, since a typo'd
+ # setting silently reverting is worse than a failed boot.
+ #
+ # @param variable [String] name of the environment variable
+ # @param value [String] raw value read from the environment
+ # @param type [Symbol] declared preference type
+ # @return [Object] the coerced value
+ def coerce_env(variable, value, type)
+ case type
+ when :boolean then coerce_env_boolean(variable, value)
+ when :integer then coerce_env_number(variable, value, type) { Integer(value, 10) }
+ when :decimal then coerce_env_number(variable, value, type) { BigDecimal(value) }
+ when :array then value.split(',').map(&:strip).reject(&:empty?)
+ else value
+ end
+ end
+
+ private
+
+ def coerce_env_boolean(variable, value)
+ normalized = value.strip.downcase
+ return true if BOOLEAN_TRUE.include?(normalized)
+ return false if BOOLEAN_FALSE.include?(normalized)
+
+ raise InvalidEnvironmentValue.new(variable, value, :boolean, "#{BOOLEAN_TRUE.join(', ')}, #{BOOLEAN_FALSE.join(', ')}")
+ end
+
+ def coerce_env_number(variable, value, type)
+ yield
+ rescue ArgumentError, TypeError
+ raise InvalidEnvironmentValue.new(variable, value, type)
+ end
end
end
end
diff --git a/spree/core/spec/lib/spree/core/preferences/runtime_configuration_spec.rb b/spree/core/spec/lib/spree/core/preferences/runtime_configuration_spec.rb
index 4196e95b39..8bc319e410 100644
--- a/spree/core/spec/lib/spree/core/preferences/runtime_configuration_spec.rb
+++ b/spree/core/spec/lib/spree/core/preferences/runtime_configuration_spec.rb
@@ -7,6 +7,10 @@ RSpec.describe Spree::Preferences::RuntimeConfiguration do
Class.new(described_class) do
preference :plain_setting, :string, default: 'coded'
preference :env_setting, :string, default: 'coded', env: 'SPREE_SPEC_ENV_SETTING'
+ preference :boolean_setting, :boolean, default: true, env: 'SPREE_SPEC_BOOLEAN'
+ preference :integer_setting, :integer, default: 3600, env: 'SPREE_SPEC_INTEGER'
+ preference :decimal_setting, :decimal, default: 0, env: 'SPREE_SPEC_DECIMAL'
+ preference :array_setting, :array, default: [], env: 'SPREE_SPEC_ARRAY'
end
end
@@ -43,4 +47,105 @@ RSpec.describe Spree::Preferences::RuntimeConfiguration do
expect(configuration[:env_setting]).to eq('coded')
end
end
+
+ # Env vars arrive as strings, so without coercion SPREE_X=false would be the
+ # truthy String "false" and SPREE_X=30 the String "30".
+ describe 'type coercion' do
+ def with_env(name, value)
+ stub_const('ENV', ENV.to_h.merge(name => value))
+ configuration_class.new
+ end
+
+ context 'with a boolean setting' do
+ %w[true 1 yes on TRUE Yes ON].each do |spelling|
+ it "reads #{spelling.inspect} as true" do
+ expect(with_env('SPREE_SPEC_BOOLEAN', spelling)[:boolean_setting]).to be(true)
+ end
+ end
+
+ %w[false 0 no off FALSE No Off].each do |spelling|
+ it "reads #{spelling.inspect} as false" do
+ expect(with_env('SPREE_SPEC_BOOLEAN', spelling)[:boolean_setting]).to be(false)
+ end
+ end
+
+ it 'raises on a value that is neither' do
+ expect { with_env('SPREE_SPEC_BOOLEAN', 'nope')[:boolean_setting] }.to raise_error(
+ Spree::Preferences::InvalidEnvironmentValue, /SPREE_SPEC_BOOLEAN="nope"/
+ )
+ end
+ end
+
+ context 'with an integer setting' do
+ it 'reads a number as an Integer' do
+ expect(with_env('SPREE_SPEC_INTEGER', '30')[:integer_setting]).to eq(30)
+ end
+
+ # `.to_i` would silently turn this typo into 0 and then into the default.
+ it 'raises on a value that is not a number' do
+ expect { with_env('SPREE_SPEC_INTEGER', '3O0')[:integer_setting] }.to raise_error(
+ Spree::Preferences::InvalidEnvironmentValue, /SPREE_SPEC_INTEGER="3O0"/
+ )
+ end
+
+ it 'raises rather than truncating a decimal' do
+ expect { with_env('SPREE_SPEC_INTEGER', '1.5')[:integer_setting] }.to raise_error(
+ Spree::Preferences::InvalidEnvironmentValue
+ )
+ end
+ end
+
+ context 'with a decimal setting' do
+ it 'reads a number as a BigDecimal' do
+ expect(with_env('SPREE_SPEC_DECIMAL', '1.5')[:decimal_setting]).to eq(BigDecimal('1.5'))
+ end
+
+ it 'raises on a value that is not a number' do
+ expect { with_env('SPREE_SPEC_DECIMAL', 'abc')[:decimal_setting] }.to raise_error(
+ Spree::Preferences::InvalidEnvironmentValue, /SPREE_SPEC_DECIMAL="abc"/
+ )
+ end
+ end
+
+ context 'with an array setting' do
+ it 'splits on commas and strips whitespace' do
+ expect(with_env('SPREE_SPEC_ARRAY', 'a, b ,c')[:array_setting]).to eq(%w[a b c])
+ end
+ end
+
+ it 'leaves a string setting as it is' do
+ expect(with_env('SPREE_SPEC_ENV_SETTING', 'false')[:env_setting]).to eq('false')
+ end
+
+ it 'falls back to the typed default when the variable is unset' do
+ configuration = with_env('SPREE_SPEC_ENV_SETTING', 'ignored')
+
+ expect(configuration[:integer_setting]).to eq(3600)
+ expect(configuration[:boolean_setting]).to be(true)
+ end
+
+ it 'prefers an explicitly assigned value over the environment' do
+ configuration = with_env('SPREE_SPEC_INTEGER', '30')
+ configuration.integer_setting = 99
+
+ expect(configuration[:integer_setting]).to eq(99)
+ end
+
+ describe '.validate_env!' do
+ it 'raises at boot for a malformed value' do
+ configuration = with_env('SPREE_SPEC_INTEGER', 'abc')
+
+ expect { configuration_class.validate_env!(configuration) }.to raise_error(
+ Spree::Preferences::InvalidEnvironmentValue
+ )
+ end
+
+ it 'passes over a malformed value that an explicit assignment overrides' do
+ configuration = with_env('SPREE_SPEC_INTEGER', 'abc')
+ configuration.integer_setting = 99
+
+ expect { configuration_class.validate_env!(configuration) }.not_to raise_error
+ end
+ end
+ end
end
diff --git a/spree/lib/generators/spree/install/templates/config/initializers/spree.rb b/spree/lib/generators/spree/install/templates/config/initializers/spree.rb
index 3afbbee41c..18089118a8 100644
--- a/spree/lib/generators/spree/install/templates/config/initializers/spree.rb
+++ b/spree/lib/generators/spree/install/templates/config/initializers/spree.rb
@@ -1,29 +1,18 @@
-# Configure Spree Preferences
+# Spree settings are configured with environment variables — see
+# https://docs.spreecommerce.org/developer/customization/configuration
+# for every setting and the variable that sets it.
#
-# Note: Initializing preferences available within the Admin will overwrite any changes that were made through the user interface when you restart.
-# If you would like users to be able to update a setting with the Admin it should NOT be set here.
+# SPREE_MINIMUM_PASSWORD_LENGTH=10
#
-# Note: If a preference is set here it will be stored within the cache & database upon initialization.
-# Just removing an entry from this initializer will not make the preference value go away.
-# Instead you must either set a new value or remove entry, clear cache, and remove database entry.
+# Anything that shapes how a shop sells — currency, taxes, when customers are
+# charged — belongs to the store and is edited in the dashboard, not here.
#
-# In order to initialize a setting do:
-# config.setting_name = 'new value'
+# Use a Spree.config block only for a value that has to be computed in Ruby;
+# it is applied at boot and wins over the environment.
#
-# More on configuring Spree preferences can be found at:
-# https://docs.spreecommerce.org/developer/customization
-Spree.config do |config|
- # Example:
- # Uncomment to stop tracking inventory levels in the application
- # config.track_inventory_levels = false
-end
-
-# Background job queue names
-# Spree.queues.default = :default
-# Spree.queues.events = :default # Event subscribers (Spree::Events::SubscriberJob)
-# Spree.queues.variants = :default
-# Spree.queues.stock_location_stock_levels = :default
-# Spree.queues.coupon_codes = :default
+# Spree.config do |config|
+# config.minimum_password_length = 10
+# end
# Use a CDN host for images, eg. Cloudfront
# This is used in the frontend to generate absolute URLs to images
@@ -37,17 +26,12 @@ end
# Use a different service for storage (S3, google, etc)
# unless Rails.env.test?
-# Spree.private_storage_service_name = :amazon_public # public assets, such as product images
-# Spree.public_storage_service_name = :amazon_private # private assets, such as invoices, etc
+# Spree.public_storage_service_name = :amazon_public # public assets, such as product images
+# Spree.private_storage_service_name = :amazon_private # private assets, such as invoices, etc
# end
-# Configure Spree Dependencies
-#
-# Note: If a dependency is set here it will NOT be stored within the cache & database upon initialization.
-# Just removing an entry from this initializer will make the dependency value go away.
-#
-# More on how to use Spree dependencies can be found at:
-# https://docs.spreecommerce.org/customization/dependencies
+# Swap a Spree service for your own — see
+# https://docs.spreecommerce.org/developer/customization/dependencies
Spree.dependencies do |dependencies|
# Example:
# Uncomment to change the default Service handling adding Items to Cart
@@ -90,30 +74,32 @@ Rails.application.config.after_initialize do
# Extensions can register additional permission resources:
# Spree.permissions.register_scope(:reviews, group: :catalog, resources: -> { [MyApp::Review] })
#
- # To customize authorization beyond the catalog, replace the ability class:
- # Spree::Dependencies.ability_class = 'MyApp::Ability'
- #
# More: https://spreecommerce.org/docs/developer/customization/permissions
end
# Background job queue configuration
+# Spree.queues.addresses = :default
+# Spree.queues.api_keys = :default
+# Spree.queues.categories = :default
+# Spree.queues.collections = :default
+# Spree.queues.coupon_codes = :default
+# Spree.queues.data_requests = :default
# Spree.queues.default = :default
# Spree.queues.events = :default
# Spree.queues.exports = :default
+# Spree.queues.gift_cards = :default
# Spree.queues.images = :default
# Spree.queues.imports = :default
+# Spree.queues.payment_webhooks = :default
+# Spree.queues.payouts = :default
# Spree.queues.products = :default
-# Spree.queues.variants = :default
-# Spree.queues.taxons = :default
+# Spree.queues.search = :default
# Spree.queues.stock_location_stock_levels = :default
-# Spree.queues.coupon_codes = :default
+# Spree.queues.stock_reservations = :default
+# Spree.queues.tax_identifiers = :default
# Spree.queues.themes = :default
-# Spree.queues.addresses = :default
-# Spree.queues.gift_cards = :default
+# Spree.queues.variants = :default
# Spree.queues.webhooks = :default
-# Spree.queues.payment_webhooks = :default
-# Spree.queues.api_keys = :default
-# Spree.queues.search = :default
# Search provider — requires the spree_meilisearch gem
# Spree.search_provider = 'SpreeMeilisearch::SearchProvider'